@libraz/formulon 0.13.0 โ†’ 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,18 +5,28 @@
5
5
  [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/libraz/formulon/blob/main/LICENSE)
6
6
  [![Docs](https://img.shields.io/badge/docs-formulon.libraz.net-2563eb)](https://formulon.libraz.net)
7
7
 
8
- Excel 365 calculation engine, compiled to WebAssembly. Evaluates formulas,
9
- loads and saves `.xlsx` workbooks, and defaults to the `win-365-ja_JP`
10
- behavior profile. Hosts can select the separately supported
11
- `mac-365-ja_JP` profile when required.
8
+ **Recalculate Excel workbooks and formulas in the browser and Node, with results checked against real Excel 365.**
9
+ The engine is a C++17 core compiled to WebAssembly, so it needs no Excel install, no Windows and no server: a workbook a user opens in the page is calculated on their machine and never uploaded.
12
10
 
13
- ## Install
11
+ Known differences from Excel are listed case by case in [`tests/divergence.yaml`](https://github.com/libraz/formulon/blob/main/tests/divergence.yaml), each with a reason and the Excel build it was last verified on.
14
12
 
15
- ```sh
16
- npm install @libraz/formulon
13
+ ๐Ÿ“– **[Documentation](https://formulon.libraz.net)**  ยท  **[WASM guide](https://formulon.libraz.net/runtimes/wasm)**  ยท  **[API](https://formulon.libraz.net/api/wasm)**  ยท  **[Demos](https://formulon.libraz.net/demos)**
14
+
15
+ ## What's inside
16
+
17
+ - **Formula engine** โ€” 526 Excel function names, 511 implemented locally; dynamic arrays, `LET` / `LAMBDA`, and `REGEX*`. [Coverage](https://formulon.libraz.net/compatibility/formula-coverage)
18
+ - **Workbook I/O** โ€” read, recalculate and write `.xlsx` and `.xlsb`, including styles, conditional formatting, tables, pivot tables and print layout. [File formats](https://formulon.libraz.net/compatibility/file-format-support)
19
+ - **Locale profiles** โ€” 28 Excel behavior profiles across fourteen locales on Mac and Windows hosts. [Locale profiles](https://formulon.libraz.net/compatibility/locale-profiles)
20
+ - **Excel oracle** โ€” formula results are compared bit for bit against goldens captured from Mac Excel 365 in fourteen locales. [Oracle testing](https://formulon.libraz.net/compatibility/oracle-testing)
21
+ - **Two builds** โ€” a single-threaded default that loads anywhere, and `@libraz/formulon/threads` for parallel recalculation. [Choosing a build](#choosing-a-build)
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ npm install @libraz/formulon # browsers and Node 22+
17
27
  ```
18
28
 
19
- Requires Node.js 22 or newer (the package is shipped as ES modules).
29
+ The package is ES modules only and ships its TypeScript declarations.
20
30
 
21
31
  ## Quick start
22
32
 
@@ -24,192 +34,73 @@ Requires Node.js 22 or newer (the package is shipped as ES modules).
24
34
  import createFormulon from '@libraz/formulon';
25
35
 
26
36
  const Module = await createFormulon();
27
-
28
- const r = Module.evalFormula('=SUM(1,2,3)');
29
- console.log(r.value.number); // 6
37
+ console.log(Module.evalFormula('=SUM(1,2,3)').value.number); // 6
30
38
  ```
31
39
 
32
- `evalFormula` returns an envelope of the form `{ status, value }`. Excel
33
- errors (e.g. `#DIV/0!`) are surfaced as a `value.kind === 4` (Error)
34
- result rather than a failed status; only host-side problems
35
- (out-of-memory, parser crashes) populate `status.ok === false`.
40
+ Excel errors such as `#DIV/0!` come back as values (`value.kind === 4`); `status.ok === false` is reserved for host-side failures. See [Errors](https://formulon.libraz.net/compatibility/errors).
36
41
 
37
- ## Workbook example
42
+ ## Recalculate a workbook
38
43
 
39
44
  ```js
40
45
  import createFormulon from '@libraz/formulon';
41
46
  import { readFile, writeFile } from 'node:fs/promises';
42
47
 
43
48
  const Module = await createFormulon();
44
-
45
- // Load an existing workbook from disk.
46
- const bytes = await readFile('input.xlsx');
47
- const wb = Module.Workbook.loadBytes(bytes);
49
+ const wb = Module.Workbook.loadBytes(await readFile('input.xlsx'));
48
50
  try {
49
- if (!wb.isValid()) {
50
- throw new Error(`load failed: ${Module.lastErrorMessage()}`);
51
- }
51
+ if (!wb.isValid()) throw new Error(Module.lastErrorMessage());
52
52
 
53
- // Mutate, recalc, save.
54
- wb.setNumber(0, 0, 0, 42); // Sheet1!A1 = 42
55
- wb.setFormula(0, 1, 0, '=A1*2'); // Sheet1!A2 = =A1*2
53
+ wb.setNumber(0, 0, 0, 42); // Sheet1!A1
54
+ wb.setFormula(0, 1, 0, '=A1*2'); // Sheet1!A2
56
55
  wb.recalc();
57
-
58
- const a2 = wb.getValue(0, 1, 0);
59
- console.log(a2.value.number); // 84
56
+ console.log(wb.getValue(0, 1, 0).value.number); // 84
60
57
 
61
58
  const saved = wb.save();
62
- if (saved.status.ok) {
63
- await writeFile('output.xlsx', saved.bytes);
64
- }
59
+ if (saved.status.ok) await writeFile('output.xlsx', saved.bytes);
65
60
  } finally {
66
- // Always release the native handle.
67
- wb.delete();
61
+ wb.delete(); // workbooks wrap a native handle
68
62
  }
69
63
  ```
70
64
 
71
- ## Choosing a build
72
-
73
- The package ships two builds of the same API:
74
-
75
- | Import | Threads | Hosting requirement |
76
- | --- | --- | --- |
77
- | `@libraz/formulon` | none | none; loads in any page, worker, Electron `file://` page, or Node |
78
- | `@libraz/formulon/threads` | up to 8 Web Workers for `recalcParallel` | a browser page must be cross-origin isolated |
65
+ ## Switching locale profiles
79
66
 
80
- The default build uses ordinary (non-shared) memory and starts no workers.
81
- `recalcParallel` is still callable there and runs the pass serially,
82
- reporting `workerThreadsStarted: 0`.
83
-
84
- The threads build allocates its memory as a `SharedArrayBuffer` and
85
- pre-spawns its worker pool when the factory is called, so in a browser it
86
- only loads when the page is served with `Cross-Origin-Opener-Policy:
87
- same-origin` and `Cross-Origin-Embedder-Policy: require-corp`. Node needs
88
- no extra setup.
67
+ New workbooks use `win-365-en_US`. Formulas are always written with English function names and the stored separators; the profile decides how text is parsed and how results are rendered. Switch it per workbook and recalculate:
89
68
 
90
69
  ```js
91
- import createFormulon from '@libraz/formulon/threads';
70
+ const wb = Module.Workbook.createDefault();
71
+ try {
72
+ wb.setFormula(0, 0, 0, '=LENB("ๆ—ฅๆœฌ")'); // A1
73
+ wb.setFormula(0, 1, 0, '=VALUE("1,5")'); // A2
74
+ wb.setFormula(0, 2, 0, '=ISEVEN(2)'); // A3
75
+
76
+ for (const id of ['mac-365-en_US', 'mac-365-ja_JP', 'mac-365-de_DE']) {
77
+ wb.setExcelProfileId(id);
78
+ wb.recalc(); // a profile change marks formulas dirty
79
+ console.log(id, [0, 1, 2].map((row) => wb.getDisplayText(0, row, 0).text));
80
+ }
81
+ } finally {
82
+ wb.delete();
83
+ }
84
+ // mac-365-en_US [ '2', '#VALUE!', 'TRUE' ]
85
+ // mac-365-ja_JP [ '4', '#VALUE!', 'TRUE' ]
86
+ // mac-365-de_DE [ '2', '1,5', 'WAHR' ]
92
87
  ```
93
88
 
94
- ## Bundler integration (Vite, webpack, esbuild)
95
-
96
- Each build is an ES module factory plus a companion `.wasm`
97
- (`formulon.wasm`, or `formulon_threads.wasm` for the threads build).
98
- Consumer-side concerns worth knowing about:
89
+ The ids are `{mac,win}-365-{ja_JP,en_US,de_DE,fr_FR,zh_CN,ko_KR,th_TH,es_ES,es_MX,pt_BR,ru_RU,zh_TW,it_IT,nl_NL}`. Every `mac-*` profile and `win-365-ja_JP` is measured against Excel; the other `win-*` profiles are estimated from the Mac measurements. On a `mac-*` profile, text comparison, sorting, lookups and grouping follow that locale's measured Mac Excel collation; `win-*` profiles compare text case-insensitively by bytes, because Windows ordering is not measured. The profile is not saved into the file, so store the id your application targets and apply it again after loading.
99
90
 
100
- **1. The threads build needs ES module workers.** Its pthread workers are
101
- spawned by Emscripten with
102
- `new Worker(new URL("formulon_threads_core.js", import.meta.url), {type: "module"})`.
103
- Bundlers default to classic (IIFE) workers and must be told otherwise:
104
-
105
- ```ts
106
- // vite.config.ts
107
- export default defineConfig({
108
- worker: { format: 'es' },
109
- });
110
- ```
91
+ ## Choosing a build
111
92
 
112
- webpack 5 picks up the `{type: "module"}` automatically when
113
- `output.module: true`. esbuild requires `--format=esm` for the worker
114
- chunk.
115
-
116
- **2. Node bridging code is compiled in.** The factory contains a Node
117
- branch (lazy-loaded `node:module`, plus `node:worker_threads` in the
118
- threads build) that browser bundlers will warn about as
119
- "externalised". The warnings are harmless โ€” the branch is dead code at
120
- runtime in browsers โ€” but if you want to silence them, mark the imports
121
- external:
122
-
123
- ```ts
124
- // vite.config.ts
125
- export default defineConfig({
126
- optimizeDeps: { exclude: ['@libraz/formulon'] },
127
- build: {
128
- rollupOptions: {
129
- external: [/^node:/],
130
- },
131
- },
132
- });
133
- ```
93
+ | Import | Threads | Hosting requirement |
94
+ | --- | --- | --- |
95
+ | `@libraz/formulon` | none; `recalcParallel` runs serially | none; loads in any page, worker, Electron `file://` page, or Node |
96
+ | `@libraz/formulon/threads` | up to 8 workers for `recalcParallel` | a browser page must be cross-origin isolated (COOP / COEP); bundlers need ES module workers |
134
97
 
135
- If your bundler errors on the `await import("node:...")` form rather
136
- than just warning, raise the build target to `es2022` so the
137
- async-function-scoped `await` lexes cleanly:
98
+ Bundler settings for Vite, webpack and esbuild are in [Bundler requirements](https://formulon.libraz.net/runtimes/wasm#bundler-requirements).
138
99
 
139
- ```ts
140
- // vite.config.ts
141
- export default defineConfig({
142
- build: { target: 'es2022' },
143
- });
144
- ```
100
+ ## Non-goals
145
101
 
146
- ### Parallel recalculation
147
-
148
- `Workbook.recalc()` remains the serial, caller-thread recalculation API.
149
- `Workbook.recalcParallel(threadCount)` starts workers only in the
150
- `@libraz/formulon/threads` build; it is synchronous and returns a
151
- `{ status, stats }` result after all workers have joined. A thread count of
152
- `0` selects automatic detection capped at 8, `1` keeps all evaluation on the
153
- caller thread and starts no workers, and `2..8` sets the maximum worker count.
154
- Values above 8 return a failed status with `kInvalidArgument`.
155
-
156
- The five 64-bit scheduler counters in `stats` are surfaced as JavaScript
157
- `number` values (not `bigint`) and are exact through `Number.MAX_SAFE_INTEGER`
158
- (`2^53 - 1`). `workerThreadsStarted` and `workerThreadsUsed` report actual
159
- worker telemetry; the scheduler may use fewer workers than requested.
160
-
161
- ## API reference
162
-
163
- The full TypeScript surface is shipped as `dist/formulon.d.ts` and is the
164
- authoritative reference. Highlights:
165
-
166
- - `createFormulon(opts?)` -- the default export. Returns a Promise
167
- resolving to a `FormulonModule`.
168
- - `Module.evalFormula(formula)` -- one-shot evaluation against a fresh
169
- workbook.
170
- - `Module.Workbook.createDefault() / createEmpty() / loadBytes(bytes)` --
171
- factory methods for building or loading a workbook.
172
- - `Workbook.setNumber / setBool / setText / setBlank / setFormula` --
173
- cell mutators.
174
- - `Workbook.recalc()` -- triggers a serial, full dependency-ordered
175
- recalculation.
176
- - `Workbook.recalcParallel(threadCount)` -- synchronously recalculates with
177
- the parallel SCC scheduler and returns status plus telemetry (serial
178
- outside the threads build).
179
- - `Workbook.getValue(sheet, row, col)` -- reads a cached cell value.
180
- - `Workbook.save()` -- serialises back to an in-memory `.xlsx` byte buffer.
181
-
182
- Workbook handles wrap a native pointer; always call `wb.delete()` (in a
183
- `finally` block) when done.
184
-
185
- Two C ABI capabilities are bound in the Python package but not exposed
186
- here: `fm_workbook_set_iterative_enabled` (toggling iterative calculation
187
- without re-supplying the existing iteration cap and residual threshold --
188
- `setIterative(enabled, maxIterations, maxChange)` here always takes all
189
- three) and `fm_styles_add_batch` (bulk style registration). This is a
190
- genuine gap, not an intentional exclusion.
191
-
192
- ## Memory when loading a workbook
193
-
194
- Both surfaces inflate each worksheet part into memory whole before
195
- parsing it (the zip reader caps this at 100 MiB per entry, 256 MiB per
196
- load); `loadBytes` here then always builds a DOM tree from that buffer.
197
- The native CLI switches to a streaming parser for worksheets past 256
198
- KiB instead, which skips building the DOM tree -- that implementation
199
- costs binary size the WASM budget does not have -- but still holds the
200
- same inflated XML buffer first. Sheets are read one at a time, so the
201
- peak is per worksheet, and the practical ceiling here is the 32-bit WASM
202
- address space. Results are identical either way.
203
-
204
- ## Project
205
-
206
- Documentation โ€” guides, compatibility notes, and the per-runtime API
207
- reference โ€” is at <https://formulon.libraz.net>. Source, design notes,
208
- and the oracle test suite live at <https://github.com/libraz/formulon>.
209
- [formulon-cell](https://github.com/libraz/formulon-cell) is a browser
210
- spreadsheet UI built on this package; it doubles as an integration test
211
- and a worked example of embedding the engine.
102
+ VBA execution, legacy `.xls`, chart rendering, Power Query / DAX, pivot cache refresh from source data, live external connections, and a spreadsheet UI are permanently out of scope. See [Non-goals](https://formulon.libraz.net/compatibility/non-goals).
212
103
 
213
104
  ## License
214
105
 
215
- Apache License 2.0. See [LICENSE](./LICENSE) and [NOTICE](./NOTICE).
106
+ [Apache License 2.0](./LICENSE). See also [NOTICE](./NOTICE).
package/dist/common.js CHANGED
@@ -195,8 +195,8 @@ export const LogLevel = Object.freeze({ Debug: 0, Info: 1, Warn: 2, Error: 3, Of
195
195
  * `undefined`/`null` to leave `base` unchanged (signature/description
196
196
  * stay `undefined`).
197
197
  * @param {string} locale A BCP-47 display locale tag (e.g. `"fr-FR"`),
198
- * matching the keys in `aliases` / `localized`. Independent of the numeric
199
- * locale code passed to `functionMetadata()`.
198
+ * matching the keys in `aliases` / `localized`. Independent of the profile id
199
+ * passed to the engine locale calls.
200
200
  * @returns {object} The merged metadata (a new object), or `base` verbatim
201
201
  * when `entry` is absent.
202
202
  */
@@ -520,7 +520,44 @@ export enum CalcMode {
520
520
  AutoNoTable = 2,
521
521
  }
522
522
 
523
- export type ExcelProfileId = 'mac-365-ja_JP' | 'win-365-ja_JP';
523
+ /**
524
+ * Full formula-behaviour profile id: `mac` or `win` combined with one of
525
+ * `ja_JP`, `en_US`, `de_DE`, `fr_FR`, `zh_CN`, `ko_KR`, `th_TH`, `es_ES`,
526
+ * `es_MX`, `pt_BR`, `ru_RU`, `zh_TW`, `it_IT`, `nl_NL`
527
+ * (for example `win-365-en_US`). New workbooks default to `win-365-en_US`.
528
+ * The `mac-*` ids and `win-365-ja_JP` follow Excel measurements; every other
529
+ * `win-*` id is estimated from the Mac measurements plus the Windows host
530
+ * rules.
531
+ */
532
+ export type ExcelProfileId =
533
+ | 'mac-365-ja_JP'
534
+ | 'win-365-ja_JP'
535
+ | 'mac-365-en_US'
536
+ | 'win-365-en_US'
537
+ | 'mac-365-de_DE'
538
+ | 'win-365-de_DE'
539
+ | 'mac-365-fr_FR'
540
+ | 'win-365-fr_FR'
541
+ | 'mac-365-zh_CN'
542
+ | 'win-365-zh_CN'
543
+ | 'mac-365-ko_KR'
544
+ | 'win-365-ko_KR'
545
+ | 'mac-365-th_TH'
546
+ | 'win-365-th_TH'
547
+ | 'mac-365-es_ES'
548
+ | 'win-365-es_ES'
549
+ | 'mac-365-es_MX'
550
+ | 'win-365-es_MX'
551
+ | 'mac-365-pt_BR'
552
+ | 'win-365-pt_BR'
553
+ | 'mac-365-ru_RU'
554
+ | 'win-365-ru_RU'
555
+ | 'mac-365-zh_TW'
556
+ | 'win-365-zh_TW'
557
+ | 'mac-365-it_IT'
558
+ | 'win-365-it_IT'
559
+ | 'mac-365-nl_NL'
560
+ | 'win-365-nl_NL';
524
561
 
525
562
  /**
526
563
  * A wall-clock reading in local civil fields, as read back from
@@ -724,9 +761,14 @@ export interface SheetFormatDefaults {
724
761
  hasDefaultRowHeight: boolean;
725
762
  }
726
763
 
727
- /** Return type of `Workbook.getSheetFormatDefaults(sheet)`. */
764
+ /** Return type of `Workbook.getSheetFormatDefaults(sheet)`. The effective
765
+ * values are read-only and ignored by `setSheetFormatDefaults`. */
728
766
  export interface SheetFormatDefaultsResult extends SheetFormatDefaults {
729
767
  status: Status;
768
+ /** Character units the sheet lays columns out with: `defaultColWidth` when set, else 8.43. */
769
+ effectiveDefaultColWidth: number;
770
+ /** Points the sheet lays rows out with: `defaultRowHeight` when set, else 102/7 (about 14.57). */
771
+ effectiveDefaultRowHeight: number;
730
772
  }
731
773
 
732
774
  /** Return type of `Workbook.getFormula` / `getFormulaR1C1`. `formula` is `null` when the cell holds no formula. */
@@ -1023,7 +1065,51 @@ export interface CellNode {
1023
1065
  readonly col: number;
1024
1066
  }
1025
1067
 
1026
- /** Result envelope for `functionMetadata(name, locale)`.
1068
+ /** One error value's spelling under a profile: the canonical (en-invariant)
1069
+ * text and the profile's Excel spelling. `measured` is `false` when the
1070
+ * localized spelling is assumed rather than captured from Excel. */
1071
+ export interface LocaleErrorName {
1072
+ readonly canonical: string;
1073
+ readonly localized: string;
1074
+ readonly measured: boolean;
1075
+ }
1076
+
1077
+ /** Order in which a locale writes day, month and year. */
1078
+ export type LocaleDateOrder = 'mdy' | 'ymd' | 'dmy';
1079
+
1080
+ /** Scalar locale facts of one {@link ExcelProfileId}. `measured` is `true`
1081
+ * for the profiles captured from Excel (every `mac-*` id and
1082
+ * `win-365-ja_JP`) and `false` for the estimated `win-*` ids. Every
1083
+ * scalar field is captured in each Mac locale, so `measured` covers them
1084
+ * all; only `errorNames` carries per-entry flags.
1085
+ * `errorNames` is indexed by error-code ordinal. */
1086
+ export interface LocaleFacts {
1087
+ readonly decimalSeparator: string;
1088
+ readonly groupSeparator: string;
1089
+ readonly listSeparator: string;
1090
+ readonly arrayColumnSeparator: string;
1091
+ readonly arrayRowSeparator: string;
1092
+ readonly trueName: string;
1093
+ readonly falseName: string;
1094
+ readonly dateOrder: LocaleDateOrder;
1095
+ readonly currencySymbol: string;
1096
+ /** `true` when the currency symbol follows the number. */
1097
+ readonly currencySuffix: boolean;
1098
+ /** `true` when one space separates the symbol and the number. */
1099
+ readonly currencySpace: boolean;
1100
+ readonly currencyDefaultDecimals: number;
1101
+ readonly measured: boolean;
1102
+ readonly errorNames: readonly LocaleErrorName[];
1103
+ }
1104
+
1105
+ /** Return type of `Workbook.localeFacts(profileId)`. `facts` is `null` on
1106
+ * failure (an unknown profile id). */
1107
+ export interface LocaleFactsResult {
1108
+ status: Status;
1109
+ facts: LocaleFacts | null;
1110
+ }
1111
+
1112
+ /** Result envelope for `functionMetadata(name)`.
1027
1113
  *
1028
1114
  * `ok` is `false` when no function matches `name`; the remaining
1029
1115
  * fields are absent. When `ok` is `true`, `name` / `minArity` /
@@ -1090,8 +1176,8 @@ export interface MergedFunctionMetadataResult extends FunctionMetadataResult {
1090
1176
  *
1091
1177
  * When `entry` is `undefined`, `base` is returned verbatim (signature /
1092
1178
  * description stay `undefined`). `locale` is a BCP-47 display tag matching
1093
- * the keys in `aliases` / `localized`, independent of the numeric locale
1094
- * passed to `functionMetadata()`. See `docs/function-metadata-schema.md`.
1179
+ * the keys in `aliases` / `localized`, independent of the profile id
1180
+ * passed to the engine locale calls. See `docs/function-metadata-schema.md`.
1095
1181
  *
1096
1182
  * A pure host-side helper: it touches no WASM state and is exported from
1097
1183
  * this package's hand-written entry point rather than the generated module
@@ -1762,7 +1848,7 @@ export enum AnchorEditAs {
1762
1848
  }
1763
1849
 
1764
1850
  /** How a colour was resolved. Mirrors `fm_color_resolution_t`. `Exact` is a literal or workbook-supplied
1765
- * colour; `DefaultTheme` / `ThemeUnparseable` mean the default (Office 2013-2022) theme was used because
1851
+ * colour; `DefaultTheme` / `ThemeUnparseable` mean the current Excel Office (Aptos) theme was used because
1766
1852
  * the theme part is absent / unparseable; `IndexOutOfRange` is black; `AutoContext` is an automatic colour
1767
1853
  * (black for font and border, white for fills). */
1768
1854
  export enum ColorResolution {
@@ -2124,12 +2210,41 @@ export interface ImageInsertOptions {
2124
2210
  heightEmu?: number;
2125
2211
  }
2126
2212
 
2127
- /** Result of `Workbook.insertImage`; `objectId` is zero on failure. */
2213
+ /** Result of `Workbook.insertImage` and `Workbook.restoreImage`; `objectId` is zero on failure. */
2128
2214
  export interface InsertImageResult {
2129
2215
  status: Status;
2130
2216
  objectId: number;
2131
2217
  }
2132
2218
 
2219
+ /** New placement of an existing picture, in the quantities `listDrawingObjects`
2220
+ * reports: `row` / `col` / `rowOffEmu` / `colOffEmu` are the top-left marker of the
2221
+ * anchor box (`fromRow` ...), `widthEmu` / `heightEmu` the picture's own unrotated
2222
+ * size (`cx` / `cy`); a zero size keeps the current one. `anchorKind` is `OneCell`
2223
+ * (default) or `TwoCell`; `editAs` applies to a two-cell anchor only. */
2224
+ export interface ImagePlacement {
2225
+ anchorKind?: AnchorKind;
2226
+ editAs?: AnchorEditAs;
2227
+ row?: number;
2228
+ col?: number;
2229
+ rowOffEmu?: number;
2230
+ colOffEmu?: number;
2231
+ widthEmu?: number;
2232
+ heightEmu?: number;
2233
+ }
2234
+
2235
+ /** Result of `Workbook.snapshotImage`. `bytes` is an opaque, versioned capture to hand
2236
+ * to `restoreImage`; it is empty on failure. */
2237
+ export interface ImageSnapshotResult {
2238
+ status: Status;
2239
+ bytes: Uint8Array;
2240
+ }
2241
+
2242
+ /** Options of `Workbook.restoreImage`. With `newId` the capture is added on top as a
2243
+ * copy with a fresh id; otherwise a picture with the same id is replaced. */
2244
+ export interface RestoreImageOptions {
2245
+ newId?: boolean;
2246
+ }
2247
+
2133
2248
  /** Result of the five raw print-settings getters. The empty `xml` string
2134
2249
  * means the sheet declares no such element. */
2135
2250
  export interface SheetPrintXmlResult {
@@ -2339,13 +2454,19 @@ export interface Workbook {
2339
2454
  * cell's text. */
2340
2455
  setCellPhoneticProperties(sheet: number, row: number, col: number, properties: PhoneticProperties): Status;
2341
2456
  setBlank(sheet: number, row: number, col: number): Status;
2457
+ /** Stores a formula. Returns `kParserUnexpectedToken` and changes nothing when the text
2458
+ * does not parse: a syntax error, or a built-in called through a sheet / workbook qualifier. */
2342
2459
  setFormula(sheet: number, row: number, col: number, formula: string): Status;
2343
2460
 
2344
2461
  getValue(sheet: number, row: number, col: number): CellResult;
2345
2462
 
2346
- /** The stored A1 formula (leading `=` included), or `formula: null` for a cell that holds none. */
2463
+ /** The stored A1 formula (leading `=` included), or `formula: null` for a cell that holds none.
2464
+ * The text is returned as entered; a formula loaded from a file shows book names, not `[N]` indexes. */
2347
2465
  getFormula(sheet: number, row: number, col: number): FormulaResult;
2348
- /** The formula in R1C1 notation relative to the cell, without a leading `=`; `formula: null` when the cell holds none. */
2466
+ /** The formula in R1C1 notation relative to the cell, without a leading `=`; `formula: null` when the cell holds none.
2467
+ * A formula loaded from a file that does not parse is kept verbatim, evaluates to `#NAME?`, and fails here with
2468
+ * `kParserUnexpectedToken`; `setFormula` never produces that state.
2469
+ * Sheet and external qualifiers are quoted as a whole only when the path, book or sheet name needs it. */
2349
2470
  getFormulaR1C1(sheet: number, row: number, col: number): FormulaResult;
2350
2471
  /** One page of the populated cells (formula or non-blank value, spill phantoms included) inside
2351
2472
  * `range`, row-major. `cursor` is the `nextCursor` of the previous page (omit for the first);
@@ -2483,8 +2604,8 @@ export interface Workbook {
2483
2604
  setPinnedNow(year: number, month: number, day: number, hour: number, minute: number, second: number): Status;
2484
2605
  clearPinnedNow(): Status;
2485
2606
 
2486
- /**
2487
- * Full formula-behaviour profile id. Defaults to `win-365-ja_JP`.
2607
+ /** Full formula-behaviour profile id. Defaults to `win-365-en_US`.
2608
+ * Pick another locale or host with any {@link ExcelProfileId}.
2488
2609
  */
2489
2610
  excelProfileId(): StringResult<ExcelProfileId>;
2490
2611
  setExcelProfileId(profileId: ExcelProfileId): Status;
@@ -2495,13 +2616,15 @@ export interface Workbook {
2495
2616
  * hyperlinks, tables, print areas, manual breaks and the auto-filter
2496
2617
  * range. The ranges and formulas inside the worksheet `<extLst>` (the
2497
2618
  * `x14` conditional-formatting block, sparkline groups, `x14`
2498
- * validations) move with them, as Excel moves them.
2619
+ * validations) move with them, as Excel moves them, and so do the cells
2620
+ * named by the other worksheet content kept verbatim for a lossless save:
2621
+ * protected ranges, scenarios, a sheet sort state, cell watches,
2622
+ * ignored-error ranges and web-publish ranges.
2499
2623
  *
2500
- * They do not move an unmodelled `<worksheet>` child kept byte-verbatim
2501
- * so a save does not drop it (a `<sortState>`, for one): a `ref` inside
2502
- * it keeps its pre-edit rectangle, and nothing reports it. An insert also
2503
- * does not copy the formatting of the row or column before it onto the
2504
- * new one, which Excel does โ€” a sparkline included.
2624
+ * They do not move the anchor of an embedded OLE object or form control,
2625
+ * also kept verbatim: it keeps its pre-edit cell, and nothing reports it.
2626
+ * An insert also does not copy the formatting of the row or column before
2627
+ * it onto the new one, which Excel does โ€” a sparkline included.
2505
2628
  */
2506
2629
 
2507
2630
  /** Inserts `count` rows at `row` on `sheet` and rewrites cross-workbook
@@ -2521,10 +2644,12 @@ export interface Workbook {
2521
2644
  definedNameCount(): NumberResult;
2522
2645
  definedNameAt(idx: number): DefinedNameEntry;
2523
2646
  /** Adds, replaces, or (when `formula` is empty) removes a workbook-
2524
- * scoped defined name. */
2647
+ * scoped defined name. A non-empty `formula` that does not parse is
2648
+ * rejected with `kParserUnexpectedToken`. */
2525
2649
  setDefinedName(name: string, formula: string): Status;
2526
2650
  /** Adds, replaces, or removes a defined name in workbook scope (-1)
2527
- * or a sheet-local scope (0-based sheet index). */
2651
+ * or a sheet-local scope (0-based sheet index). A non-empty `formula`
2652
+ * that does not parse is rejected with `kParserUnexpectedToken`. */
2528
2653
  setDefinedNameScoped(name: string, formula: string, localSheetId: number): Status;
2529
2654
 
2530
2655
  tableCount(): NumberResult;
@@ -2599,6 +2724,14 @@ export interface Workbook {
2599
2724
  insertImage(sheet: number, bytes: Uint8Array, opts?: ImageInsertOptions): InsertImageResult;
2600
2725
  /** Removes the picture `objectId` and its media once nothing else references it. */
2601
2726
  removeImage(sheet: number, objectId: number): Status;
2727
+ /** Moves and resizes the picture `objectId`, keeping its id, crop, rotation and every other element. */
2728
+ setImageAnchor(sheet: number, objectId: number, placement: ImagePlacement): Status;
2729
+ /** Makes the picture `objectId` item `index` of `listDrawingObjects`, whose order is the stacking order (0 is the back). */
2730
+ setImageZOrder(sheet: number, objectId: number, index: number): Status;
2731
+ /** Captures the picture `objectId` with its list position, element and media as opaque bytes for `restoreImage`. */
2732
+ snapshotImage(sheet: number, objectId: number): ImageSnapshotResult;
2733
+ /** Puts a `snapshotImage` capture back and returns the picture's id: in place of a picture with the same id at its recorded position, or as a copy on top with `newId`. */
2734
+ restoreImage(sheet: number, bytes: Uint8Array, opts?: RestoreImageOptions): InsertImageResult;
2602
2735
 
2603
2736
  passthroughCount(): NumberResult;
2604
2737
  passthroughAt(idx: number): PassthroughEntry;
@@ -2938,6 +3071,8 @@ export interface Workbook {
2938
3071
  setRowOutline(sheet: number, row: number, level: number): Status;
2939
3072
  /** Removes the height override at `row`, returning it to the sheet default. */
2940
3073
  clearRowHeight(sheet: number, row: number): Status;
3074
+ /** Removes the width override on columns `first..last`, returning them to the sheet default width. Hidden state, outline level and column style are kept. */
3075
+ clearColumnWidth(sheet: number, first: number, last: number): Status;
2941
3076
 
2942
3077
  /** Reads the sheet's default column / row metrics. */
2943
3078
  getSheetFormatDefaults(sheet: number): SheetFormatDefaultsResult;
@@ -3064,6 +3199,8 @@ export interface Workbook {
3064
3199
  setThemeColors(colors: number[]): Status;
3065
3200
  /** Rewrites the theme's major and minor typefaces. */
3066
3201
  setThemeFonts(fonts: ThemeFonts): Status;
3202
+ /** Removes the theme part so the workbook reports the default theme (`source` is `Default`). Excel adds a theme part again when it saves the file. */
3203
+ resetTheme(): Status;
3067
3204
  /** Resolves a colour specification to ARGB against the theme and the
3068
3205
  * indexed palette; `context` decides what an automatic colour means. */
3069
3206
  resolveColor(spec: ColorSpec, context: ColorContext): ResolvedColorResult;
@@ -3075,7 +3212,9 @@ export interface Workbook {
3075
3212
  /** Returns every external-link record carried by the workbook in
3076
3213
  * `<externalReferences>` document order. Empty for fresh workbooks
3077
3214
  * and any package whose source archive had no `<externalReferences>`
3078
- * block. */
3215
+ * block. A formula, name, conditional-format rule or data validation that names an unregistered
3216
+ * book (bracket or path spelling) appends a record without renumbering; a book already present,
3217
+ * in any letter case, adds none. */
3079
3218
  getExternalLinks(): ListResult<ExternalLinkRecord>;
3080
3219
 
3081
3220
  /** Adds a merge range to `sheet`. */
@@ -3139,7 +3278,8 @@ export interface Workbook {
3139
3278
  * cell-range list; the rule itself surfaces its raw OOXML payload
3140
3279
  * (the engine does not yet evaluate validation rules). */
3141
3280
  getValidations(sheet: number): ListResult<DataValidationEntry>;
3142
- /** Appends a data-validation rule to `sheet`. */
3281
+ /** Appends a data-validation rule to `sheet`. A non-empty `formula1` / `formula2`
3282
+ * that does not parse is rejected with `kParserUnexpectedToken`. */
3143
3283
  addValidation(sheet: number, validation: DataValidationInput): Status;
3144
3284
  /** Removes the validation rule at `index`. Returns `kInvalidArgument`
3145
3285
  * if `index` is out of range. */
@@ -3156,7 +3296,9 @@ export interface Workbook {
3156
3296
  * `index` is the new rule's position in the sheet's flattened CF rule
3157
3297
  * sequence (the same indexing `getConditionalFormats` and
3158
3298
  * `removeConditionalFormatAt` use); it stays valid until a subsequent
3159
- * add/remove/clear mutation on the same sheet renumbers the sequence. */
3299
+ * add/remove/clear mutation on the same sheet renumbers the sequence.
3300
+ * A non-empty `formula1` / `formula2` that does not parse is rejected
3301
+ * with `kParserUnexpectedToken`. */
3160
3302
  addConditionalFormat(sheet: number, rule: ConditionalFormatInput): AddStyleResult;
3161
3303
  /** Removes the CF rule at `index` (flattened order). When the
3162
3304
  * containing block becomes empty it is removed too. */
@@ -3175,28 +3317,40 @@ export interface Workbook {
3175
3317
  dependents(sheet: number, row: number, col: number, depth: number): ListResult<CellNode>;
3176
3318
 
3177
3319
  /** Returns metadata for the function `name` (case-insensitive). When
3178
- * the function is unknown, returns `{ok: false}`. `locale` selects
3179
- * the catalog locale (`0` = `en-US`, `1` = `ja-JP`) and is validated,
3180
- * but does not change the result: the description / signature fields
3181
- * are always `undefined` (see {@link FunctionMetadataResult}). */
3182
- functionMetadata(name: string, locale: number): FunctionMetadataResult;
3320
+ * the function is unknown, returns `{ok: false}`. The result is
3321
+ * locale-invariant: the description / signature fields are always
3322
+ * `undefined` (see {@link FunctionMetadataResult}). */
3323
+ functionMetadata(name: string): FunctionMetadataResult;
3183
3324
  /** Returns every registered function's canonical name in ascending
3184
3325
  * sort order. */
3185
3326
  functionNames(): ListResult<string>;
3186
3327
 
3187
3328
  /** Returns the localized display name for the canonical function
3188
- * `canonicalName` in `locale`. No alias table exists in any locale,
3189
- * so this always returns the canonical name unchanged; localized
3190
- * display names belong to the host's provider document. `value` is
3191
- * the empty string, with `status.ok === false`, when the canonical
3192
- * name does not match a registered function. */
3193
- localizeFunctionName(canonicalName: string, locale: number): StringResult;
3329
+ * `canonicalName` under `profileId`. `de_DE` and `fr_FR` profiles return
3330
+ * Excel's function names for that locale; `ja_JP` renames only `DOLLAR`,
3331
+ * `USDOLLAR` and `DBCS`; the other locales return the canonical name
3332
+ * unchanged. `value` is the empty string, with `status.ok === false`,
3333
+ * when `profileId` is unknown or the name does not match a registered
3334
+ * function. */
3335
+ localizeFunctionName(canonicalName: string, profileId: ExcelProfileId): StringResult;
3194
3336
  /** Inverse of `localizeFunctionName`: returns the canonical English
3195
- * name for the localized function `localizedName`. With no alias
3196
- * table this is a case-insensitive canonical-name match, in every
3197
- * locale. `value` is the empty string, with `status.ok === false`,
3198
- * when no function matches. */
3199
- canonicalizeFunctionName(localizedName: string, locale: number): StringResult;
3337
+ * name for the localized function `localizedName` under `profileId`.
3338
+ * `value` is the empty string, with `status.ok === false`, when
3339
+ * `profileId` is unknown or no function matches. */
3340
+ canonicalizeFunctionName(localizedName: string, profileId: ExcelProfileId): StringResult;
3341
+ /** Rewrites stored (en-invariant) formula text into `profileId`'s Excel
3342
+ * spelling: function names, list / array separators, decimal points,
3343
+ * booleans and error names. Strings, quoted sheet names, external
3344
+ * qualifiers and structured-reference brackets are kept verbatim. A pure
3345
+ * text rewrite; the grammar is not validated. `status.ok` is `false`
3346
+ * for an unknown `profileId`. */
3347
+ localizeFormula(formula: string, profileId: ExcelProfileId): StringResult;
3348
+ /** Inverse of `localizeFormula`: rewrites `profileId`-spelled formula text
3349
+ * into the en-invariant form. */
3350
+ canonicalizeFormula(formula: string, profileId: ExcelProfileId): StringResult;
3351
+ /** Returns the locale facts (separators, boolean names, date order,
3352
+ * currency, error names) of `profileId`. */
3353
+ localeFacts(profileId: ExcelProfileId): LocaleFactsResult;
3200
3354
 
3201
3355
  /** Returns dynamic-array spill info for `(sheet, row, col)`.
3202
3356
  * When the cell is part of a spill region (anchor or phantom),
Binary file