@evotecit/officeimo 0.1.2 → 0.1.3

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.
Files changed (37) hide show
  1. package/README.md +43 -49
  2. package/bundles/officeimo-canopyx.js +966 -122
  3. package/bundles/officeimo-canopyx.mjs +929 -92
  4. package/bundles/officeimo-csv.js +18 -15
  5. package/bundles/officeimo-csv.mjs +16 -13
  6. package/bundles/officeimo-datatables.js +168 -82
  7. package/bundles/officeimo-datatables.mjs +140 -54
  8. package/bundles/officeimo-pdf.js +148 -65
  9. package/bundles/officeimo-pdf.mjs +124 -41
  10. package/bundles/officeimo.js +168 -82
  11. package/bundles/officeimo.mjs +140 -54
  12. package/dist/csv/index.js +16 -13
  13. package/dist/integrations/canopyx/diagnostics.d.ts +3 -0
  14. package/dist/integrations/canopyx/diagnostics.js +17 -0
  15. package/dist/integrations/canopyx/grouping.d.ts +6 -0
  16. package/dist/integrations/canopyx/grouping.js +188 -0
  17. package/dist/integrations/canopyx/index.d.ts +2 -2
  18. package/dist/integrations/canopyx/index.js +72 -15
  19. package/dist/integrations/canopyx/metadata.d.ts +4 -0
  20. package/dist/integrations/canopyx/metadata.js +51 -0
  21. package/dist/integrations/canopyx/presentation.d.ts +8 -0
  22. package/dist/integrations/canopyx/presentation.js +40 -0
  23. package/dist/integrations/canopyx/rule-predicates.d.ts +3 -0
  24. package/dist/integrations/canopyx/rule-predicates.js +110 -0
  25. package/dist/integrations/canopyx/rules.d.ts +6 -0
  26. package/dist/integrations/canopyx/rules.js +176 -0
  27. package/dist/integrations/canopyx/source.js +24 -22
  28. package/dist/integrations/canopyx/types.d.ts +89 -8
  29. package/dist/integrations/canopyx/workbook.d.ts +6 -0
  30. package/dist/integrations/canopyx/workbook.js +52 -0
  31. package/dist/pdf/font-resources.js +33 -14
  32. package/dist/pdf/pages.js +60 -14
  33. package/dist/pdf/table-band-flow.js +7 -2
  34. package/dist/pdf/table-band-plan.js +9 -1
  35. package/dist/pdf/table-layout.js +6 -2
  36. package/dist/pdf/table-structure.js +9 -8
  37. package/package.json +1 -1
@@ -0,0 +1,176 @@
1
+ import { captureFields } from "../../internal/capture.js";
2
+ import { canopyPredicate } from "./rule-predicates.js";
3
+ // Stable document palette. Browser CSS variables and resolved cell.format are never interpreted.
4
+ const palette = {
5
+ info: { color: "4472C4", background: "DDEBF7", foreground: "1F4E78" },
6
+ success: { color: "70AD47", background: "E2F0D9", foreground: "375623" },
7
+ warning: { color: "FFC000", background: "FFF2CC", foreground: "9C6500" },
8
+ danger: { color: "C00000", background: "FFC7CE", foreground: "9C0006" }
9
+ };
10
+ class UnsupportedRule extends Error {
11
+ }
12
+ const unsupported = (message) => { throw new UnsupportedRule(message); };
13
+ /** Compile declarations in source order, then emit native target/aspect priorities.
14
+ * Data-column selectors let grouped writers exclude generated headings, subtotals and grand totals. */
15
+ export function canopyRules(request, format, grouped, tones, report, options = {}, cellTypes) {
16
+ if (request.formatRules === undefined || format === "csv")
17
+ return [];
18
+ if (!Array.isArray(request.formatRules) || request.formatRules.length > 1000)
19
+ throw new TypeError("Canopy formatRules must be a bounded array of at most 1,000 declarations.");
20
+ const visuals = [], cells = [], rows = [], ids = new Set(), columns = request.columns;
21
+ const inputs = request.formatRules;
22
+ const declarations = inputs.map(input => {
23
+ if (!input || typeof input !== "object")
24
+ throw new TypeError("Canopy rule declarations must be objects.");
25
+ const rule = captureFields(input, ["id", "enabled", "stopIfTrue", "column", "when", "target", "style"]);
26
+ if (typeof rule.id !== "string" || !rule.id || ids.has(rule.id))
27
+ throw new TypeError("Canopy rule IDs must be unique nonempty strings.");
28
+ ids.add(rule.id);
29
+ if (rule.enabled !== undefined && typeof rule.enabled !== "boolean" || rule.stopIfTrue !== undefined && typeof rule.stopIfTrue !== "boolean")
30
+ throw new TypeError("Canopy rule flags must be boolean.");
31
+ const style = rule.style && typeof rule.style === "object" ? captureFields(rule.style, ["tone", "bar", "scale"]) : rule.style;
32
+ return { ...rule, style };
33
+ });
34
+ if (format === "pdf") {
35
+ for (const rule of declarations)
36
+ if (rule.enabled !== false)
37
+ report({ code: "PDF_NATIVE_RULE_NOT_RENDERED:" + rule.id });
38
+ return [];
39
+ }
40
+ const hasStops = declarations.some(rule => rule.enabled !== false && rule.stopIfTrue);
41
+ if (hasStops && declarations.some(rule => rule.enabled !== false && (rule.style?.bar !== undefined || rule.style?.scale !== undefined))) {
42
+ report({ code: "UNSUPPORTED_GLOBAL_STOP_WITH_NATIVE_VISUALS" });
43
+ return [];
44
+ }
45
+ const barColumns = new Set(declarations.filter(rule => rule.enabled !== false && rule.style?.bar !== undefined).map(rule => rule.column));
46
+ const barTone = declarations.find(rule => rule.enabled !== false && rule.target !== "row" && rule.style?.tone !== undefined && rule.column !== undefined && barColumns.has(rule.column));
47
+ if (barTone) {
48
+ // Canopy suppresses a cell tone's fill only where its bar resolves. A single native tone patch cannot express both cases.
49
+ report({ code: "UNSUPPORTED_CELL_TONE_WITH_DATA_BAR", columnId: barTone.column });
50
+ return [];
51
+ }
52
+ const priorStops = [];
53
+ const priorRows = [], priorCells = new Map();
54
+ const requiredCells = new Map();
55
+ const column = (id) => {
56
+ const index = columns.findIndex(column => column.id === id);
57
+ if (index < 0)
58
+ return unsupported("RULE_COLUMN_NOT_EXPORTED:" + id);
59
+ return index;
60
+ };
61
+ const numeric = (id) => {
62
+ if (columns[column(id)].kind !== "number")
63
+ unsupported("RULE_COLUMN_NOT_NUMERIC:" + id);
64
+ };
65
+ const color = (name) => {
66
+ const mapping = tones.get(name), value = mapping?.background ?? mapping?.color ?? palette[name]?.color;
67
+ if (value === undefined)
68
+ return unsupported("UNMAPPED_RULE_TONE:" + name);
69
+ return value;
70
+ };
71
+ const style = (name) => {
72
+ const defaults = palette[name];
73
+ const mapping = tones.get(name) ?? (defaults ? { background: defaults.background, color: defaults.foreground } : undefined);
74
+ if (!mapping)
75
+ return unsupported("UNMAPPED_RULE_TONE:" + name);
76
+ if ("alignment" in mapping || "wrapText" in mapping)
77
+ return unsupported("UNSUPPORTED_RULE_TONE_STYLE:" + name);
78
+ return {
79
+ ...("background" in mapping && mapping.background !== undefined ? { fill: { color: mapping.background } } : {}),
80
+ font: { ...(mapping.color === undefined ? {} : { color: mapping.color }),
81
+ ...("bold" in mapping && mapping.bold !== undefined ? { bold: mapping.bold } : {}),
82
+ ...("italic" in mapping && mapping.italic !== undefined ? { italic: mapping.italic } : {}) },
83
+ ...("numberFormat" in mapping && mapping.numberFormat !== undefined ? { numberFormat: mapping.numberFormat } : {})
84
+ };
85
+ };
86
+ for (const rule of declarations) {
87
+ if (rule.enabled === false)
88
+ continue;
89
+ try {
90
+ if (request.values !== "raw")
91
+ unsupported("NATIVE_RULE_REQUIRES_RAW_VALUES");
92
+ if (rule.target === "columns" || "columns" in rule && rule.columns !== undefined)
93
+ unsupported("UNSUPPORTED_RULE_COLUMNS_TARGET");
94
+ if (!rule.style || typeof rule.style !== "object" || Array.isArray(rule.style))
95
+ throw new TypeError("Canopy rule style must be an object.");
96
+ const styleInput = captureFields(rule.style, ["tone", "bar", "scale"]);
97
+ if (Object.keys(styleInput).some(key => !["tone", "bar", "scale"].includes(key)))
98
+ unsupported("UNSUPPORTED_RULE_STYLE");
99
+ const supplied = [styleInput.bar, styleInput.scale, styleInput.tone].filter(value => value !== undefined);
100
+ if (supplied.length !== 1)
101
+ unsupported("UNSUPPORTED_RULE_STYLE_COMBINATION");
102
+ if (styleInput.bar !== undefined) {
103
+ if (rule.column === undefined || rule.when !== undefined || rule.target === "row")
104
+ unsupported("UNSUPPORTED_BAR_TARGET");
105
+ numeric(rule.column);
106
+ if (rule.stopIfTrue)
107
+ unsupported("UNSUPPORTED_BAR_STOP");
108
+ const { minimum, maximum, tone = "info", showValue } = captureFields(styleInput.bar, ["minimum", "maximum", "tone", "showValue"]);
109
+ if (minimum === undefined || maximum === undefined)
110
+ return unsupported("UNBOUNDED_CANOPY_BAR");
111
+ if (!Number.isFinite(minimum) || !Number.isFinite(maximum) || maximum <= minimum)
112
+ throw new TypeError("Canopy bar bounds must be finite and increasing.");
113
+ visuals.push({ type: "dataBar", range: { column: rule.column }, color: color(tone),
114
+ minimum: { type: "number", value: minimum }, maximum: { type: "number", value: maximum }, ...(showValue === undefined ? {} : { showValue }) });
115
+ requiredCells.set(column(rule.column), "number");
116
+ }
117
+ else if (styleInput.scale !== undefined) {
118
+ if (rule.stopIfTrue)
119
+ unsupported("UNSUPPORTED_SCALE_STOP");
120
+ if (rule.column === undefined || rule.when !== undefined || rule.target === "row")
121
+ unsupported("UNSUPPORTED_SCALE_TARGET");
122
+ numeric(rule.column);
123
+ const { stops } = captureFields(styleInput.scale, ["stops"]);
124
+ if (!Array.isArray(stops) || stops.length < 2 || stops.length > 3)
125
+ unsupported("UNSUPPORTED_SCALE_STOPS");
126
+ const mapped = stops.map((input) => {
127
+ const stop = captureFields(input, ["type", "value", "tone"]);
128
+ if (!["min", "max", "number", "percent", "percentile"].includes(stop.type))
129
+ unsupported("UNSUPPORTED_SCALE_THRESHOLD:" + stop.type);
130
+ const threshold = stop.type === "min" || stop.type === "max" ? { type: stop.type }
131
+ : { type: stop.type, value: stop.value };
132
+ return { threshold, color: color(stop.tone) };
133
+ });
134
+ visuals.push({ type: "colorScale", range: { column: rule.column },
135
+ stops: mapped });
136
+ requiredCells.set(column(rule.column), "number");
137
+ }
138
+ else {
139
+ if (rule.when === undefined || styleInput.tone === undefined || rule.target !== "row" && rule.column === undefined)
140
+ unsupported("UNSUPPORTED_HIGHLIGHT_TARGET");
141
+ if (rule.target !== undefined && rule.target !== "row" && rule.target !== "cell")
142
+ unsupported("UNSUPPORTED_RULE_TARGET");
143
+ const range = rule.target === "row" ? { column: columns[0].id, through: columns.at(-1).id } : { column: rule.column };
144
+ if (rule.column !== undefined)
145
+ column(rule.column);
146
+ const ruleCells = new Map();
147
+ const ownPredicate = canopyPredicate(request, grouped, options, rule.when, unsupported, ruleCells);
148
+ const reachable = priorStops.length ? "AND(" + ownPredicate + ",NOT(OR(" + priorStops.join(",") + ")))" : ownPredicate;
149
+ const previous = rule.target === "row" ? priorRows : priorCells.get(rule.column) ?? [];
150
+ const formula = previous.length ? "AND(" + reachable + ",NOT(OR(" + previous.join(",") + ")))" : reachable;
151
+ if (formula.length > 8192)
152
+ unsupported("RULE_FORMULA_LIMIT");
153
+ (rule.target === "row" ? rows : cells).push({ type: "expression", range, formula, style: style(styleInput.tone) });
154
+ previous.push(ownPredicate);
155
+ if (rule.target !== "row")
156
+ priorCells.set(rule.column, previous);
157
+ for (const [column, type] of ruleCells)
158
+ requiredCells.set(column, type);
159
+ // A matched declaration still stops the row when an earlier tone on that target already won.
160
+ if (rule.stopIfTrue)
161
+ priorStops.push(ownPredicate);
162
+ }
163
+ }
164
+ catch (error) {
165
+ if (!(error instanceof UnsupportedRule))
166
+ throw error;
167
+ report({ code: error.message + ":" + rule.id, ...(rule.column === undefined ? {} : { columnId: rule.column }) });
168
+ if (hasStops)
169
+ return []; // A partial sequence cannot claim to preserve its row-global stopping behavior.
170
+ }
171
+ }
172
+ for (const [column, type] of requiredCells)
173
+ cellTypes?.set(column, type);
174
+ // Canopy paints cell visuals/tones over the row tint. Build masks before changing native priority order.
175
+ return Object.freeze([...visuals, ...cells, ...rows]);
176
+ }
@@ -3,37 +3,31 @@ import { datetime } from "./dates.js";
3
3
  import { captureFields } from "../../internal/capture.js";
4
4
  import { copyColumns } from "../../internal/rows.js";
5
5
  import { copyCellPresentation } from "../../core/presentation.js";
6
+ import { canopyDiagnostics } from "./diagnostics.js";
7
+ import { canopyNumberFormat, canopyXlsxWidth } from "./presentation.js";
6
8
  const columnFields = ["width", "format", "wrapText", "alignment", "rowHeader", "groups"];
7
9
  /** Map an immutable CanopyX record capture to a writer without querying the grid or retaining its body. */
8
10
  export function createCanopyExport(capture, format, options = {}) {
11
+ return prepareCanopyExport(capture, format, options).source;
12
+ }
13
+ /** @internal Capture the input once before full-writer metadata mapping and asynchronous enumeration. */
14
+ export function prepareCanopyExport(capture, format, options = {}) {
9
15
  options = captureFields(options, ["tones", "columnOptions", "unsupportedPresentation", "datetime", "xlsx", "signal", "onDiagnostic"]);
10
16
  if (format !== "xlsx" && format !== "csv" && format !== "pdf")
11
17
  throw new TypeError("Canopy export format must be xlsx, csv or pdf.");
12
18
  if (!capture || typeof capture.rows !== "function" || !capture.request)
13
19
  throw new TypeError("A portable CanopyX capture with request and rows() is required.");
14
- const { request } = capture, signal = options.signal, values = request.values;
20
+ const request = captureFields(capture.request, ["columns", "recordCount", "values", "presentation", "timeZone", "revision", "scope", "total", "matched", "selection", "query", "generatedAt", "grouping", "formatRules"]);
21
+ const signal = options.signal, values = request.values;
15
22
  if (!Array.isArray(request.columns) || !request.columns.length || (request.recordCount !== null && (!Number.isSafeInteger(request.recordCount) || request.recordCount < 0)) ||
16
23
  (values !== "raw" && values !== "display") || (request.timeZone !== "utc" && request.timeZone !== "local") || typeof request.revision !== "string")
17
24
  throw new TypeError("Invalid portable CanopyX capture metadata.");
18
- const policy = options.unsupportedPresentation ?? (format === "csv" ? "text" : "reject"), dateMode = options.datetime ?? "preserve", notify = options.onDiagnostic;
25
+ const dateMode = options.datetime ?? "preserve", report = canopyDiagnostics(format, options);
19
26
  const clock = options.xlsx?.dateMode ?? request.timeZone;
20
27
  if (clock !== "utc" && clock !== "local")
21
28
  throw new TypeError("XLSX dateMode must be utc or local.");
22
- if (policy !== "reject" && policy !== "text")
23
- throw new TypeError("unsupportedPresentation must be reject or text.");
24
29
  if (dateMode !== "preserve" && dateMode !== "typed" && dateMode !== "text")
25
30
  throw new TypeError("datetime must be preserve, typed or text.");
26
- if (notify !== undefined && typeof notify !== "function")
27
- throw new TypeError("onDiagnostic must be a synchronous function.");
28
- const report = (diagnostic) => {
29
- if (policy === "reject")
30
- throw new TypeError("Unsupported Canopy presentation: " + diagnostic.code + (diagnostic.columnId ? " (" + diagnostic.columnId + ")" : ""));
31
- const result = notify?.(Object.freeze(diagnostic));
32
- if (result && typeof result.then === "function") {
33
- void Promise.resolve(result).catch(() => { });
34
- throw new TypeError("onDiagnostic must be synchronous.");
35
- }
36
- };
37
31
  const diagnostics = (items, rowId, columnId) => {
38
32
  if (items === undefined)
39
33
  return;
@@ -42,9 +36,7 @@ export function createCanopyExport(capture, format, options = {}) {
42
36
  for (const code of items)
43
37
  report({ code, ...(rowId === undefined ? {} : { rowId }), ...(columnId === undefined ? {} : { columnId }) });
44
38
  };
45
- if (request.presentation === "text")
46
- report({ code: "TEXT_ONLY_CAPTURE" });
47
- else if (request.presentation !== "semantic")
39
+ if (request.presentation !== "text" && request.presentation !== "semantic")
48
40
  throw new TypeError("Canopy captures must declare text or semantic presentation.");
49
41
  const tones = new Map(Object.entries(options.tones ?? {}).map(([name, style]) => {
50
42
  if (!style || typeof style !== "object" || Array.isArray(style))
@@ -57,12 +49,16 @@ export function createCanopyExport(capture, format, options = {}) {
57
49
  if (typeof name !== "string")
58
50
  throw new TypeError("Canopy tones must be strings.");
59
51
  const style = tones.get(name);
60
- if (!style)
52
+ if (!style && name !== "neutral")
61
53
  report({ code: "UNMAPPED_TONE:" + name, rowId, ...(columnId === undefined ? {} : { columnId }) });
62
54
  return style;
63
55
  };
64
56
  const ids = new Set();
65
- const specs = request.columns.map(column => {
57
+ const specs = request.columns.map(input => {
58
+ const fields = captureFields(input, ["id", "title", "kind", "width", "pinned", "format", "wrap", "alignment", "diagnostics"]);
59
+ const column = Object.freeze({ ...fields,
60
+ ...(fields.width === undefined ? {} : { width: Object.freeze(captureFields(fields.width, ["unit", "preferred", "minimum", "maximum"])) }),
61
+ ...(fields.format === undefined ? {} : { format: Object.freeze(captureFields(fields.format, ["minimumFractionDigits", "maximumFractionDigits", "prefix", "suffix"])) }) });
66
62
  if (!column || typeof column.id !== "string" || !column.id || ids.has(column.id) || typeof column.title !== "string" ||
67
63
  !["text", "number", "datetime"].includes(column.kind) ||
68
64
  (column.wrap !== undefined && typeof column.wrap !== "boolean") || (column.alignment !== undefined && !["left", "right"].includes(column.alignment)) ||
@@ -78,14 +74,19 @@ export function createCanopyExport(capture, format, options = {}) {
78
74
  if (!columnFields.includes(key))
79
75
  throw new TypeError("Unsupported Canopy column option: " + key);
80
76
  const override = captureFields(selected, columnFields);
77
+ const numericFormat = format === "xlsx" && values === "raw" && column.kind === "number" && column.format !== undefined && override.format === undefined
78
+ ? canopyNumberFormat(column.format, report, column.id) : undefined;
81
79
  const [captured] = copyColumns([{ ...override, key: column.id, header: column.title,
80
+ ...(format === "xlsx" && override.width === undefined && column.width !== undefined ? { width: canopyXlsxWidth(column.width.preferred) } : {}),
81
+ ...(override.format === undefined && numericFormat !== undefined ? { format: numericFormat } : {}),
82
+ ...(format === "xlsx" && values === "raw" && column.kind === "datetime" && override.format === undefined ? { format: "yyyy-mm-dd hh:mm:ss.000" } : {}),
82
83
  ...(values === "raw" && column.kind === "number" ? { type: "number" } : {}),
83
84
  ...(override.wrapText === undefined && column.wrap === undefined ? {} : { wrapText: override.wrapText ?? column.wrap }),
84
85
  ...(override.alignment === undefined && column.alignment === undefined ? {} : { alignment: override.alignment ?? column.alignment }) }]);
85
- return Object.freeze({ id: column.id, kind: column.kind, column: Object.freeze(captured) });
86
+ return Object.freeze({ id: column.id, kind: column.kind, input: column, column: Object.freeze(captured) });
86
87
  });
87
88
  const rowCount = request.recordCount;
88
- return Object.freeze({ columns: Object.freeze(specs.map(spec => spec.column)), rowCount, async *rows() {
89
+ const source = Object.freeze({ columns: Object.freeze(specs.map(spec => spec.column)), rowCount, async *rows() {
89
90
  checkAbort(signal);
90
91
  let count = 0;
91
92
  for await (const row of inputRows(capture.rows(signal ? { signal } : {}), signal)) {
@@ -119,4 +120,5 @@ export function createCanopyExport(capture, format, options = {}) {
119
120
  if (rowCount !== null && count !== rowCount)
120
121
  throw new TypeError("Canopy capture did not produce its declared recordCount.");
121
122
  } });
123
+ return Object.freeze({ source, request: Object.freeze({ ...request, columns: Object.freeze(specs.map(spec => spec.input)) }), report, tones });
122
124
  }
@@ -2,7 +2,7 @@ import type { CellPresentation, ColumnSettings, ExportLimits, ExportProgress, Ex
2
2
  import type { ExportLink } from "../../core/links.js";
3
3
  import type { CsvOptions } from "../../csv/index.js";
4
4
  import type { XlsxOptions } from "../../xlsx/index.js";
5
- import type { PdfOptions } from "../../pdf/index.js";
5
+ import type { PdfOptions, GroupedPdfOptions } from "../../pdf/index.js";
6
6
  /** Structural portable capture. CanopyX owns queries, selection, presenters and revision validation. */
7
7
  export interface CanopyExportCell {
8
8
  readonly value: string | number | boolean | null;
@@ -11,6 +11,13 @@ export interface CanopyExportCell {
11
11
  readonly link?: ExportLink;
12
12
  readonly diagnostics?: readonly string[];
13
13
  }
14
+ /** CanopyX's declarative numeric intent; this is never parsed as native Excel syntax. */
15
+ export interface CanopyNumberFormat {
16
+ readonly minimumFractionDigits?: number;
17
+ readonly maximumFractionDigits?: number;
18
+ readonly prefix?: string;
19
+ readonly suffix?: string;
20
+ }
14
21
  export interface CanopyExportColumn {
15
22
  readonly id: string;
16
23
  readonly title: string;
@@ -21,6 +28,8 @@ export interface CanopyExportColumn {
21
28
  readonly minimum: number;
22
29
  readonly maximum?: number;
23
30
  };
31
+ readonly pinned?: "left" | "right" | null;
32
+ readonly format?: CanopyNumberFormat;
24
33
  readonly wrap?: boolean;
25
34
  readonly alignment?: "left" | "right";
26
35
  readonly diagnostics?: readonly string[];
@@ -31,6 +40,66 @@ export interface CanopyExportRow {
31
40
  readonly tone?: string;
32
41
  readonly diagnostics?: readonly string[];
33
42
  }
43
+ /** Captured half-open detail ranges, never ranges from a different export scope. */
44
+ export interface CanopyExportGroup {
45
+ readonly key: string;
46
+ readonly value: string | number | boolean | null;
47
+ readonly text?: string;
48
+ readonly offset: number;
49
+ readonly count: number;
50
+ readonly aggregates: Readonly<Record<string, number | null>>;
51
+ readonly groups?: readonly CanopyExportGroup[];
52
+ }
53
+ export interface CanopyExportGrouping {
54
+ readonly levels: readonly {
55
+ readonly column: string;
56
+ readonly direction: "asc" | "desc";
57
+ readonly title?: string;
58
+ }[];
59
+ readonly aggregates: readonly {
60
+ readonly id: string;
61
+ readonly column: string;
62
+ readonly operation: string;
63
+ readonly label?: string;
64
+ }[];
65
+ readonly totals: Readonly<Record<string, number | null>>;
66
+ readonly groups: readonly CanopyExportGroup[];
67
+ }
68
+ export interface CanopyRuleFilter {
69
+ readonly column: string;
70
+ /** Native numeric/typed-UTC-date comparisons and null tests are bounded; unrepresentable type/culture profiles need explicit text fallback. */
71
+ readonly operator: string;
72
+ readonly values?: readonly (string | number | boolean)[];
73
+ }
74
+ export interface CanopyRulePredicate {
75
+ readonly operator: string;
76
+ readonly filters?: readonly CanopyRuleFilter[];
77
+ readonly groups?: readonly CanopyRulePredicate[];
78
+ }
79
+ export interface CanopyFormatRule {
80
+ readonly id: string;
81
+ readonly enabled?: boolean;
82
+ readonly stopIfTrue?: boolean;
83
+ readonly column?: string;
84
+ readonly when?: CanopyRulePredicate;
85
+ readonly target?: "row" | "cell" | "columns";
86
+ readonly style: {
87
+ readonly tone?: string;
88
+ readonly bar?: {
89
+ readonly minimum?: number;
90
+ readonly maximum?: number;
91
+ readonly tone?: string;
92
+ readonly showValue?: boolean;
93
+ };
94
+ readonly scale?: {
95
+ readonly stops: readonly {
96
+ readonly type: string;
97
+ readonly value?: number;
98
+ readonly tone: string;
99
+ }[];
100
+ };
101
+ };
102
+ }
34
103
  export interface CanopyCapture {
35
104
  readonly request: {
36
105
  readonly columns: readonly CanopyExportColumn[];
@@ -39,6 +108,15 @@ export interface CanopyCapture {
39
108
  readonly presentation: "text" | "semantic";
40
109
  readonly timeZone: "utc" | "local";
41
110
  readonly revision: string;
111
+ readonly scope?: "filtered" | "selected" | "all";
112
+ readonly total?: number | null;
113
+ readonly matched?: number | null;
114
+ readonly selection?: readonly string[];
115
+ /** The actual accepted export query. OfficeIMO never evaluates or substitutes a live-view query. */
116
+ readonly query?: object;
117
+ readonly generatedAt?: string;
118
+ readonly grouping?: CanopyExportGrouping;
119
+ readonly formatRules?: readonly CanopyFormatRule[];
42
120
  };
43
121
  /** Fresh serial enumeration. The signal must reach the source's in-flight page requests. */
44
122
  rows(options?: {
@@ -52,21 +130,18 @@ export interface CanopyDiagnostic {
52
130
  readonly columnId?: string;
53
131
  }
54
132
  export interface CanopySourceOptions {
55
- /** Map semantic tones explicitly; CSS and DOM rules are never inferred. Cell tone overrides row tone. */
133
+ /** Map semantic tones explicitly; canonical neutral defaults to no override. Cell tone overrides row tone. */
56
134
  readonly tones?: Readonly<Record<string, CellPresentation>>;
57
- /** Selected-column overrides. Unselected IDs are ignored; widths use Excel zero-character units, not CSS pixels. */
135
+ /** Selected-column overrides. Unselected IDs are ignored. Native format overrides remain literal Excel syntax. */
58
136
  readonly columnOptions?: Readonly<Record<string, Omit<Partial<ColumnSettings>, "header" | "type">>>;
59
- /** XLSX/PDF reject unsupported presentation by default. CSV defaults to text because it has no visual styling. */
137
+ /** Genuine unsupported effects reject by default in XLSX/PDF; text accepts them with diagnostics. */
60
138
  readonly unsupportedPresentation?: "reject" | "text";
61
- /** XLSX: preserve uses typed Dates where exact and literal ISO text for greater precision. */
62
139
  readonly datetime?: "preserve" | "typed" | "text";
63
- /** The same clock used by the XLSX writer; defaults to the native capture's timeZone. */
64
140
  readonly xlsx?: Pick<XlsxOptions, "dateMode">;
65
141
  readonly signal?: AbortSignal;
66
- /** Synchronous notification; throwing aborts enumeration. No unbounded diagnostic list is retained. */
67
142
  readonly onDiagnostic?: (diagnostic: CanopyDiagnostic) => void;
68
143
  }
69
- /** Each call to rows opens an independent native capture enumeration. No whole-table matrix is retained. */
144
+ /** Flat, reusable typed rows. Full writers additionally map captured groups and native rules. */
70
145
  export interface CanopyExport {
71
146
  readonly columns: readonly (ColumnSettings & {
72
147
  readonly key: string;
@@ -80,4 +155,10 @@ export interface CanopyWriteOptions extends CanopySourceOptions {
80
155
  readonly xlsx?: Omit<XlsxOptions, "columns" | "signal" | "onProgress">;
81
156
  readonly csv?: Omit<CsvOptions, "columns" | "signal" | "onProgress" | "valueMode">;
82
157
  readonly pdf?: Omit<PdfOptions, "columns" | "signal" | "onProgress">;
158
+ /** Existing grouped-writer callbacks. Omitted labels use the documented English defaults. */
159
+ readonly grouped?: Partial<Pick<GroupedPdfOptions, "subtotalLabel" | "grandTotalLabel" | "includeGrandTotal" | "continuationLabel" | "groupHeadingLevel">> & {
160
+ readonly labelColumn?: Pick<ColumnSettings, "header">;
161
+ };
162
+ /** Add a metadata worksheet containing only captured export metadata and its accepted query. */
163
+ readonly about?: boolean;
83
164
  }
@@ -0,0 +1,6 @@
1
+ import type { XlsxOptions } from "../../xlsx/index.js";
2
+ import type { GroupedReportSource } from "../../core/grouped-report.js";
3
+ import type { ExportResult, OutputDestination } from "../../core/index.js";
4
+ import type { CanopyExport, CanopyWriteOptions } from "./types.js";
5
+ /** Compose only the adapter's data/grouped sheet and optional metadata sheet in the existing workbook owner. */
6
+ export declare function writeCanopyWorkbook(source: CanopyExport, grouped: GroupedReportSource | undefined, destination: OutputDestination, options: XlsxOptions, labels: CanopyWriteOptions["grouped"], about: readonly (readonly [string, string | number])[] | undefined): Promise<ExportResult>;
@@ -0,0 +1,52 @@
1
+ import { Workbook, addGroupedXlsx } from "../../xlsx/index.js";
2
+ import { portableWorkbook } from "../../xlsx/portable.js";
3
+ import { withDestination } from "../../core/sinks.js";
4
+ /** Compose only the adapter's data/grouped sheet and optional metadata sheet in the existing workbook owner. */
5
+ export async function writeCanopyWorkbook(source, grouped, destination, options, labels, about) {
6
+ const { sheet: sheetSettings = {}, columns: _columns, ...settings } = options;
7
+ const { name = "Data", ...sheet } = sheetSettings;
8
+ if (about && name.toLowerCase() === "about")
9
+ throw new TypeError("The optional About worksheet needs a distinct data-sheet name.");
10
+ if (grouped && settings.cellValueWriters !== undefined)
11
+ throw new TypeError("Grouped Canopy exports use resolved source values rather than custom cellValueWriters.");
12
+ return withDestination(destination, async (sink) => {
13
+ const workbookOptions = { ...portableWorkbook(settings), sink };
14
+ // Grouped worksheets generate native FormulaCells; flat tables keep the portable-value boundary.
15
+ const book = grouped ? new Workbook(workbookOptions) : Workbook.forTable(workbookOptions);
16
+ try {
17
+ let rows, columns;
18
+ if (grouped) {
19
+ const { conditionalFormats, ...groupedSheet } = sheet;
20
+ const written = await addGroupedXlsx(book, grouped, {
21
+ labelColumn: { header: labels?.labelColumn?.header ?? "Group", width: 18 },
22
+ subtotalLabel: labels?.subtotalLabel ?? (group => group.label + " total"),
23
+ grandTotalLabel: labels?.grandTotalLabel ?? (() => "Grand total"),
24
+ ...(labels?.includeGrandTotal === undefined ? {} : { includeGrandTotal: labels.includeGrandTotal }),
25
+ sheet: { ...groupedSheet, name }, ...(conditionalFormats === undefined ? {} : { conditionalFormats })
26
+ });
27
+ rows = written.rows;
28
+ columns = written.columns;
29
+ }
30
+ else {
31
+ const data = book.addWorksheet(name, { boldHeader: true, autoFilter: sheet.includeHeader !== false,
32
+ autoSize: { minWidth: 6, maxWidth: 54 }, ...sheet, columns: source.columns });
33
+ await data.addRows(source.rows());
34
+ await data.close();
35
+ rows = data.rowCount;
36
+ columns = source.columns.length;
37
+ }
38
+ if (about) {
39
+ const metadata = book.addWorksheet("About", { columns: [{ header: "Field", width: 18 }, { header: "Value", width: 72, wrapText: true }],
40
+ boldHeader: true, freezeHeader: true });
41
+ await metadata.addRows(about);
42
+ await metadata.close();
43
+ }
44
+ const result = await book.finish();
45
+ return { rows, columns, bytes: result.bytes };
46
+ }
47
+ catch (error) {
48
+ await book.discard(error);
49
+ throw error;
50
+ }
51
+ });
52
+ }
@@ -3,7 +3,8 @@ import { fontProgram } from "./font.js";
3
3
  import { resolveScalar, selectFont, standardCode, validateFonts } from "./font-support.js";
4
4
  import { pdfNumber, unicodeHex } from "./objects.js";
5
5
  import { checkAbort, pause, taskYieldDue } from "../core/iteration.js";
6
- const standardHexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
6
+ const hexBytes = Object.freeze(Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0")));
7
+ function cidHex(cid) { return hexBytes[cid >>> 8] + hexBytes[cid & 255]; }
7
8
  export class PdfFontResource {
8
9
  index;
9
10
  bold;
@@ -34,12 +35,16 @@ export class PdfFontResource {
34
35
  width(scalar) {
35
36
  if (this.shared)
36
37
  return this.shared.width(scalar);
37
- const existing = this.mappings.get(scalar);
38
- if (existing)
39
- return existing.width;
40
- const standard = this.standardWidths.get(scalar);
41
- if (standard !== undefined)
42
- return standard;
38
+ if (this.program) {
39
+ const existing = this.mappings.get(scalar);
40
+ if (existing)
41
+ return existing.width;
42
+ }
43
+ else {
44
+ const standard = this.standardWidths.get(scalar);
45
+ if (standard !== undefined)
46
+ return standard;
47
+ }
43
48
  const resolved = resolveScalar(scalar, this.program, this.bold);
44
49
  if (!resolved.supported) {
45
50
  if (resolved.code === "unpaired-surrogate")
@@ -52,7 +57,8 @@ export class PdfFontResource {
52
57
  }
53
58
  if (this.mappings.size >= 65535)
54
59
  throw new OfficeIMOError("RESOURCE_LIMIT", "A PDF font supports at most 65,535 distinct Unicode scalars.");
55
- const mapping = { cid: this.mappings.size + 1, glyph: resolved.glyph, width: resolved.width, text: String.fromCodePoint(scalar) };
60
+ const cid = this.mappings.size + 1;
61
+ const mapping = { cid, hex: cidHex(cid), glyph: resolved.glyph, width: resolved.width, text: String.fromCodePoint(scalar) };
56
62
  this.mappings.set(scalar, mapping);
57
63
  return mapping.width;
58
64
  }
@@ -65,8 +71,20 @@ export class PdfFontResource {
65
71
  let hex = "";
66
72
  for (const char of text) {
67
73
  const cp = char.codePointAt(0);
68
- this.width(cp);
69
- hex += this.program ? this.mappings.get(cp).cid.toString(16).padStart(4, "0") : standardHexBytes[standardCode(cp)];
74
+ if (this.program) {
75
+ let mapping = this.mappings.get(cp);
76
+ // Layout normally registered the scalar already; validate only a newly painted scalar.
77
+ if (!mapping) {
78
+ this.width(cp);
79
+ mapping = this.mappings.get(cp);
80
+ }
81
+ hex += mapping.hex;
82
+ }
83
+ else {
84
+ if (!this.standardWidths.has(cp))
85
+ this.width(cp);
86
+ hex += hexBytes[standardCode(cp)];
87
+ }
70
88
  }
71
89
  return "<" + hex + ">";
72
90
  }
@@ -81,10 +99,11 @@ export class PdfFontResource {
81
99
  if (!mapping) {
82
100
  if (this.mappings.size >= 65535)
83
101
  throw new OfficeIMOError("RESOURCE_LIMIT", "A PDF font supports at most 65,535 distinct CID mappings.");
84
- mapping = { cid: this.mappings.size + 1, glyph, width: this.program.widths[glyph], text };
102
+ const cid = this.mappings.size + 1;
103
+ mapping = { cid, hex: cidHex(cid), glyph, width: this.program.widths[glyph], text };
85
104
  this.mappings.set(key, mapping);
86
105
  }
87
- return "<" + mapping.cid.toString(16).padStart(4, "0") + ">";
106
+ return "<" + mapping.hex + ">";
88
107
  }
89
108
  async write(objects, compression) {
90
109
  checkAbort(this.signal);
@@ -133,7 +152,7 @@ export class PdfFontResource {
133
152
  const batch = mapped.slice(i, i + 100);
134
153
  cmap += batch.length + " beginbfchar\n";
135
154
  for (const [, m] of batch)
136
- cmap += "<" + m.cid.toString(16).padStart(4, "0") + "> <" + unicodeHex(m.text) + ">\n";
155
+ cmap += "<" + m.hex + "> <" + unicodeHex(m.text) + ">\n";
137
156
  cmap += "endbfchar\n";
138
157
  if (taskYieldDue())
139
158
  await pause();
@@ -184,7 +203,7 @@ export class PdfFontResources {
184
203
  if (!found)
185
204
  this.explicitSelections.set(explicit, selections);
186
205
  }
187
- const key = String(bold) + String(italic), existing = selections.get(key);
206
+ const key = (bold ? 2 : 0) | (italic ? 1 : 0), existing = selections.get(key);
188
207
  if (existing)
189
208
  return existing;
190
209
  const { font, syntheticBold, syntheticItalic } = explicit ? { font: explicit, syntheticBold: bold, syntheticItalic: italic } : selectFont(this.fonts, bold, italic);