/** * Code Mode cell functions (Extension Spec §5) — compile a workbook-carried * TypeScript/JS function into a registrable {@link FunctionDef}, under the * anti-macro rules (§5.3): * * - **Capability-free by default.** The function body runs with ambient I/O * globals shadowed to `undefined` (`fetch`, `require`, `process`, `globalThis`, * `Function`, `eval`, timers, …), so a function that tries to reach the network * or escape the scope fails with an error value rather than doing it. Only its * arguments reach the body. (A production deployment hardens this further with a * real isolate — QuickJS / a worker; this is the in-process approximation.) * - **Purity profile.** `Date` and `Math.random` are removed unless the descriptor * declares `volatile`, in which case the function is volatile everywhere. * - **Read-only arguments, no workbook mutation.** The body gets argument values, * nothing else — it cannot call `setInput` or reach the workbook. * * The version hash (source + signature) identifies the function; editing it * produces a new version so every call site invalidates (via * `workbook.upsertFunction`). */ import { isBlocking } from '@tanstack/spreadsheet-core' import type { ArgDescriptor, BlockingValue, CellValue, CellValueType, FunctionDef, RangeArg, } from '@tanstack/spreadsheet-core' export interface CodeFunctionSpec { /** Registered name — namespaced (e.g. `FN.TRUE_RUNWAY`). */ name: string args: Array<{ name: string; type?: CellValueType; acceptsRange?: boolean }> returns?: CellValueType description?: string /** JS function body. Parameters are the arg names; it must `return` a value. */ source: string /** Opt into ambient nondeterminism (`Date`, `Math.random`) — RAND semantics. */ volatile?: boolean } export interface CompiledCodeFunction { def: FunctionDef version: string spec: CodeFunctionSpec } /** * Ambient globals denied to a capability-free function body — shadowed to * `undefined` as parameters. (`eval` and `import` are reserved words and can't be * parameter names; `"use strict"` already neuters `eval` scope access. Full * isolation needs a real isolate — QuickJS / a worker — this is the in-process * approximation.) */ const DENY = [ 'fetch', 'XMLHttpRequest', 'WebSocket', 'require', 'module', 'process', 'global', 'globalThis', 'window', 'self', 'document', 'localStorage', 'Function', 'setTimeout', 'setInterval', 'queueMicrotask', ] /** * A stable 64-bit hex hash (two independent FNV-1a streams) — collision- * resistant enough to be load-bearing for cache invalidation, where the old * 32-bit hash risked a silent collision between two function versions. */ export function hashSource(input: string): string { let h1 = 0x811c9dc5 let h2 = 0xc9dc5118 for (let i = 0; i < input.length; i++) { const c = input.charCodeAt(i) h1 = Math.imul(h1 ^ c, 0x01000193) h2 = Math.imul(h2 ^ c, 0x01000197) } const hex = (n: number) => (n >>> 0).toString(16).padStart(8, '0') return hex(h1) + hex(h2) } /** `Math` without `random` — used for non-volatile functions. */ function sanitizedMath(): typeof Math { const m = {} as Record for (const k of Object.getOwnPropertyNames(Math)) m[k] = (Math as never)[k] m.random = () => { throw new Error('Math.random is unavailable in a non-volatile function') } return Object.freeze(m) as unknown as typeof Math } const SAFE_MATH = sanitizedMath() /** * Host-injected execution port for Code Mode — the codebase's port pattern * (Clock, AsyncPort, SheetProvider). A host plugs in a real isolate (QuickJS, a * worker) by implementing {@link CodeExecutor}; the compiler stays agnostic of * how the body is run. */ export interface CodeExecutor { /** * Compile a capability-free function body (which `return`s a value) into a * callable that takes the argument values positionally and returns the result * (or throws). Enforcing purity/capability-freedom is the executor's job. */ compile: (opts: { source: string params: Array volatile: boolean }) => (args: Array) => unknown } /** * **Not a sandbox.** The default, dev/test executor: it runs the body in-process * via `new Function` with I/O globals shadowed to `undefined` and `Date`/ * `Math.random` removed unless volatile. Shadowing is a speed bump, not a * security boundary — a production host MUST inject a real isolate * ({@link CodeExecutor}) instead of trusting this. */ export const unsafeInProcessExecutor: CodeExecutor = { compile({ source, params, volatile }) { const raw = new Function( ...DENY, 'Date', 'Math', ...params, `"use strict";\n${source}`, ) as (...a: Array) => unknown const denied = DENY.map(() => undefined) return (args) => raw( ...denied, volatile ? Date : undefined, volatile ? Math : SAFE_MATH, ...args, ) }, } function toCell(v: unknown): CellValue { if (v === null || v === undefined) return null if (typeof v === 'boolean' || typeof v === 'string') return v if (typeof v === 'number') { return Number.isFinite(v) ? v : { kind: 'error', code: '#NUM!' } } return { kind: 'error', code: '#VALUE!' } // objects/arrays aren't scalars } /** * Materialize a range argument to a dense 2D grid of values, propagating a * blocking (error/pending) cell. Bounded to 65 536 cells — a range argument is * a bounded block, not a whole column. */ function materializeGrid( rng: RangeArg, ): Array> | BlockingValue { if (rng.rows * rng.cols > 65_536) return { kind: 'error', code: '#VALUE!' } const grid: Array> = [] for (let r = 0; r < rng.rows; r++) { const row: Array = [] for (let c = 0; c < rng.cols; c++) { const v = rng.at(r, c) if (isBlocking(v)) return v row.push(v) } grid.push(row) } return grid } export function compileCodeFunction( spec: CodeFunctionSpec, executor: CodeExecutor = unsafeInProcessExecutor, ): CompiledCodeFunction { const argNames = spec.args.map((a) => a.name) const version = hashSource( `${spec.name}|${argNames.join(',')}|${spec.volatile ? 'v' : ''}|${spec.source}`, ) // Compile once through the executor port (default: the in-process fallback). const run = executor.compile({ source: spec.source, params: argNames, volatile: !!spec.volatile, }) const args: Array = spec.args.map((a) => ({ name: a.name, type: a.type, acceptsRange: a.acceptsRange, })) const def: FunctionDef = { name: spec.name, kind: 'sync', minArgs: spec.args.length, maxArgs: spec.args.length, volatile: spec.volatile, version, description: spec.description, args, returns: spec.returns, evaluate(ctx) { const values: Array = [] for (let i = 0; i < spec.args.length; i++) { // A range argument (declared `acceptsRange`) is passed through as a dense // 2D array of values — non-builtins receive ranges like builtins do. if (spec.args[i]!.acceptsRange) { const rng = ctx.args.range(i) if (rng) { const grid = materializeGrid(rng) if (grid && !Array.isArray(grid)) return grid // blocking values.push(grid) continue } } const v = ctx.args.scalar(i) if (isBlocking(v)) return v // propagate errors / pending values.push(v) } try { return toCell(run(values)) } catch (e) { // Keep the thrown message reachable (Principle 3) instead of a bare code. const detail = e instanceof Error ? e.message : String(e) return { kind: 'error', code: '#VALUE!', detail } } }, } return { def, version, spec } }