@evotecit/officeimo 0.1.2 → 0.1.4

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 (54) hide show
  1. package/README.md +59 -51
  2. package/bundles/officeimo-canopyx.js +1553 -314
  3. package/bundles/officeimo-canopyx.mjs +1497 -269
  4. package/bundles/officeimo-csv.js +18 -15
  5. package/bundles/officeimo-csv.mjs +16 -13
  6. package/bundles/officeimo-datatables.js +463 -301
  7. package/bundles/officeimo-datatables.mjs +420 -259
  8. package/bundles/officeimo-pdf.js +148 -65
  9. package/bundles/officeimo-pdf.mjs +124 -41
  10. package/bundles/officeimo-xlsx.js +177 -101
  11. package/bundles/officeimo-xlsx.mjs +149 -74
  12. package/bundles/officeimo.js +461 -299
  13. package/bundles/officeimo.mjs +419 -258
  14. package/dist/csv/index.js +16 -13
  15. package/dist/integrations/canopyx/diagnostics.d.ts +3 -0
  16. package/dist/integrations/canopyx/diagnostics.js +17 -0
  17. package/dist/integrations/canopyx/grouping.d.ts +6 -0
  18. package/dist/integrations/canopyx/grouping.js +198 -0
  19. package/dist/integrations/canopyx/index.d.ts +2 -2
  20. package/dist/integrations/canopyx/index.js +89 -15
  21. package/dist/integrations/canopyx/metadata.d.ts +4 -0
  22. package/dist/integrations/canopyx/metadata.js +51 -0
  23. package/dist/integrations/canopyx/pdf-layout.d.ts +5 -0
  24. package/dist/integrations/canopyx/pdf-layout.js +97 -0
  25. package/dist/integrations/canopyx/pdf-number.d.ts +3 -0
  26. package/dist/integrations/canopyx/pdf-number.js +64 -0
  27. package/dist/integrations/canopyx/pivot.d.ts +15 -0
  28. package/dist/integrations/canopyx/pivot.js +67 -0
  29. package/dist/integrations/canopyx/presentation.d.ts +8 -0
  30. package/dist/integrations/canopyx/presentation.js +40 -0
  31. package/dist/integrations/canopyx/rule-predicates.d.ts +3 -0
  32. package/dist/integrations/canopyx/rule-predicates.js +110 -0
  33. package/dist/integrations/canopyx/rules.d.ts +6 -0
  34. package/dist/integrations/canopyx/rules.js +176 -0
  35. package/dist/integrations/canopyx/source.js +69 -31
  36. package/dist/integrations/canopyx/types.d.ts +134 -10
  37. package/dist/integrations/canopyx/workbook.d.ts +6 -0
  38. package/dist/integrations/canopyx/workbook.js +52 -0
  39. package/dist/opc/index.js +9 -0
  40. package/dist/pdf/font-resources.js +33 -14
  41. package/dist/pdf/pages.js +60 -14
  42. package/dist/pdf/table-band-flow.js +7 -2
  43. package/dist/pdf/table-band-plan.js +9 -1
  44. package/dist/pdf/table-layout.js +6 -2
  45. package/dist/pdf/table-structure.js +9 -8
  46. package/dist/xlsx/index.d.ts +1 -1
  47. package/dist/xlsx/options.js +1 -1
  48. package/dist/xlsx/outlines.d.ts +3 -0
  49. package/dist/xlsx/outlines.js +39 -0
  50. package/dist/xlsx/types.d.ts +9 -0
  51. package/dist/xlsx/values.js +11 -2
  52. package/dist/xlsx/workbook.js +2 -0
  53. package/dist/xlsx/worksheet.js +14 -6
  54. package/package.json +2 -2
@@ -0,0 +1,64 @@
1
+ import { ExportCell } from "../../core/index.js";
2
+ /** Fixed numeric formats affect PDF text, not the frozen numeric value used by other writers. */
3
+ function numericProfile(format) {
4
+ if (format === undefined)
5
+ return undefined;
6
+ const match = /^((?:"[^"\\]*")*)(#,##)?0(?:\.([0#]+))?(%)?((?:"[^"\\]*")*)$/.exec(format);
7
+ if (!match || (match[3]?.length ?? 0) > 10)
8
+ return undefined;
9
+ return { minimumFractionDigits: (match[3]?.match(/0/g) ?? []).length, maximumFractionDigits: match[3]?.length ?? 0,
10
+ percent: !!match[4], grouping: !!match[2], prefix: match[1].replace(/"/g, ""), suffix: match[5].replace(/"/g, "") };
11
+ }
12
+ /** Preserve the captured decimal convention across a column, including whole percentages without a separator. */
13
+ export function canopyPdfNumbers(sample, columns) {
14
+ const formatters = new Map();
15
+ const decimal = columns.map((column, index) => {
16
+ let fallback = ".";
17
+ for (const row of sample) {
18
+ const cell = row[index];
19
+ if (!(cell instanceof ExportCell) || typeof cell.value !== "number")
20
+ continue;
21
+ const profile = numericProfile(cell.presentation?.numberFormat ?? column.format);
22
+ if (!profile?.maximumFractionDigits)
23
+ continue;
24
+ const match = /([.,])(\d+)[^\d.,]*$/.exec(cell.text ?? "");
25
+ if (match && match[2].length <= profile.maximumFractionDigits) {
26
+ const numeric = /([+-]?\d[\d.,]*)[^\d]*$/.exec(cell.text ?? "")?.[1] ?? "";
27
+ const scaled = cell.value * (profile.percent ? 100 : 1);
28
+ if (/^[+-]?\d{1,3}(?:,\d{3})+$/.test(numeric) || /^[+-]?\d{1,3}(?:\.\d{3})+$/.test(numeric)) {
29
+ if (Math.abs(Number(numeric.replace(/[.,]/g, "")) - scaled) < .5) {
30
+ fallback = match[1] === "," ? "." : ",";
31
+ continue;
32
+ }
33
+ }
34
+ return match[1];
35
+ }
36
+ }
37
+ return fallback;
38
+ });
39
+ return row => row.map((value, index) => {
40
+ if (!(value instanceof ExportCell) || typeof value.value !== "number")
41
+ return value;
42
+ const profile = numericProfile(value.presentation?.numberFormat ?? columns[index].format);
43
+ if (!profile)
44
+ return value;
45
+ const captured = /^([^0-9+-]*)([+-]?\d[\d., \u00a0\u202f]*?)([^0-9]*)$/.exec(value.text ?? "");
46
+ if (value.text && !captured)
47
+ return value;
48
+ const key = [decimal[index], profile.minimumFractionDigits, profile.maximumFractionDigits, profile.grouping].join(":");
49
+ let formatter = formatters.get(key);
50
+ if (!formatter) {
51
+ formatter = new Intl.NumberFormat(decimal[index] === "," ? "de-DE" : "en-US", {
52
+ minimumFractionDigits: profile.minimumFractionDigits, maximumFractionDigits: profile.maximumFractionDigits, useGrouping: profile.grouping
53
+ });
54
+ formatters.set(key, formatter);
55
+ }
56
+ const formatted = formatter.format(value.value * (profile.percent ? 100 : 1));
57
+ const prefix = profile.prefix || captured?.[1] || "";
58
+ let suffix = profile.suffix || captured?.[3] || "";
59
+ if (profile.percent && !profile.suffix)
60
+ suffix = suffix.replace(/%/g, "");
61
+ return new ExportCell(value.value, { text: prefix + formatted + (profile.percent ? "%" : "") + suffix,
62
+ ...(value.presentation ? { presentation: value.presentation } : {}), ...(value.link ? { link: value.link } : {}) });
63
+ });
64
+ }
@@ -0,0 +1,15 @@
1
+ import type { PortableSheetOptions } from "../../xlsx/index.js";
2
+ import type { CanopyCapture, CanopyExportColumn, CanopyExportRow } from "./types.js";
3
+ /** One serial enumeration's current metadata; the worksheet serializes each yielded row before requesting the next. */
4
+ export interface CanopyPivotMapping {
5
+ readonly columns: readonly CanopyExportColumn[];
6
+ readonly sheet: PortableSheetOptions;
7
+ observe(row: CanopyExportRow): void;
8
+ }
9
+ /** Qualify the explicit pivot path before flat/grouped handling; never evaluate query or aggregate data. */
10
+ export declare function canopyPivot(request: CanopyCapture["request"]): CanopyPivotMapping | undefined;
11
+ /** Per-cell formats preserve already-computed fractional percentages, ranks and differences. */
12
+ export declare function pivotNumberFormat(cell: {
13
+ readonly mode?: string;
14
+ readonly numberFormat?: string;
15
+ }): string;
@@ -0,0 +1,67 @@
1
+ function presentation(input, axes) {
2
+ const { axisKey, outlineLevel, summary, grandTotal, hidden, collapsed } = input;
3
+ if (typeof axisKey !== "string" || !axes.has(axisKey) || !Number.isInteger(outlineLevel) || outlineLevel < 0 || outlineLevel > 7 ||
4
+ [summary, grandTotal, hidden, collapsed].some(flag => typeof flag !== "boolean"))
5
+ throw new TypeError("Invalid frozen Canopy pivot axis presentation.");
6
+ return Object.freeze({ level: outlineLevel, hidden: hidden, collapsed: collapsed });
7
+ }
8
+ /** Qualify the explicit pivot path before flat/grouped handling; never evaluate query or aggregate data. */
9
+ export function canopyPivot(request) {
10
+ if (request.pivot === undefined)
11
+ return undefined;
12
+ const pivot = request.pivot;
13
+ if (!pivot || typeof pivot !== "object" || request.grouping !== undefined || !Array.isArray(request.columns) ||
14
+ request.scope !== "filtered" || !Number.isSafeInteger(request.recordCount) || request.recordCount < 0 ||
15
+ !pivot.definition || !Array.isArray(pivot.definition.rows) || pivot.definition.rows.length > 4 ||
16
+ !Array.isArray(pivot.definition.columns) || pivot.definition.columns.length > 2 ||
17
+ !Array.isArray(pivot.definition.values) || !pivot.definition.values.length || pivot.definition.values.length > 32 ||
18
+ pivot.definition.values.some(value => typeof value !== "string") ||
19
+ !Number.isSafeInteger(pivot.distinctColumns) || pivot.distinctColumns < 0 || typeof pivot.columnsLimited !== "boolean" ||
20
+ !Array.isArray(pivot.retainedColumns) || !Array.isArray(pivot.columnGroups))
21
+ throw new TypeError("Invalid explicit Canopy pivot descriptor.");
22
+ const axes = (nodes) => {
23
+ if (!Array.isArray(nodes) || nodes.length > 100001)
24
+ throw new TypeError("Pivot axes require bounded accepted identities.");
25
+ const keys = new Set();
26
+ for (const node of nodes) {
27
+ if (!node || typeof node.key !== "string" || !node.key || keys.has(node.key) || !Array.isArray(node.path) || typeof node.other !== "boolean")
28
+ throw new TypeError("Invalid or duplicate Canopy pivot axis identity.");
29
+ keys.add(node.key);
30
+ }
31
+ for (const node of nodes)
32
+ if (node.parent !== undefined && !keys.has(node.parent))
33
+ throw new TypeError("Unknown Canopy pivot parent identity.");
34
+ return keys;
35
+ };
36
+ const rowKeys = axes(pivot.rowAxis), columnKeys = axes(pivot.columnAxis);
37
+ const columns = request.columns.map((column, index) => {
38
+ if (index === 0 && column.axisKey === undefined && column.kind === "text")
39
+ return Object.freeze({ ...column });
40
+ const outline = presentation(column, columnKeys);
41
+ return Object.freeze({ ...column, outlineLevel: outline.level, hidden: outline.hidden, collapsed: outline.collapsed });
42
+ });
43
+ // Ranges are descriptor metadata, not another body. Validate them against the same ordered columns.
44
+ if (pivot.columnGroups.length > columns.length)
45
+ throw new RangeError("Pivot column group count exceeds projected columns.");
46
+ for (const group of pivot.columnGroups) {
47
+ if (!group || !columnKeys.has(group.key) || !Number.isSafeInteger(group.firstColumn) || group.firstColumn < 0 ||
48
+ !Number.isSafeInteger(group.columnCount) || group.columnCount < 1 || group.firstColumn + group.columnCount > columns.length ||
49
+ !Number.isInteger(group.depth) || group.depth < 1 || group.depth > 7 ||
50
+ typeof group.hidden !== "boolean" || typeof group.collapsed !== "boolean")
51
+ throw new TypeError("Invalid Canopy pivot column range.");
52
+ }
53
+ let current;
54
+ const sheet = Object.freeze({ outlineSummaryBelow: false, outlineSummaryRight: false,
55
+ maxOutlineLevel: 7, rowOutline: () => current,
56
+ columnOutlines: Object.freeze(columns.flatMap((column, firstColumn) => column.axisKey === undefined ? [] :
57
+ [Object.freeze({ firstColumn, columnCount: 1, level: column.outlineLevel, hidden: column.hidden, collapsed: column.collapsed })])) });
58
+ return Object.freeze({ columns: Object.freeze(columns), sheet,
59
+ observe(row) { current = presentation(row, rowKeys); } });
60
+ }
61
+ /** Per-cell formats preserve already-computed fractional percentages, ranks and differences. */
62
+ export function pivotNumberFormat(cell) {
63
+ if (!["value", "percentGrandTotal", "percentParent", "percentColumn", "percentRow", "runningTotal", "rank", "difference", "percentChange"].includes(cell.mode ?? "") ||
64
+ typeof cell.numberFormat !== "string" || !cell.numberFormat.length)
65
+ throw new TypeError("Numeric pivot cells require a frozen mode and native numberFormat.");
66
+ return cell.numberFormat;
67
+ }
@@ -0,0 +1,8 @@
1
+ import type { CanopyExportColumn, CanopyNumberFormat, CanopyDiagnostic } from "./types.js";
2
+ /** Calibri 11, 96-DPI CSS pixels, seven-pixel maximum digit and five-pixel cell padding.
3
+ * Quantize to native 1/256-character units; this is a reproducible profile, not pixel-identical rendering. */
4
+ export declare function canopyXlsxWidth(pixels: number): number;
5
+ /** Escape literal prefixes/suffixes; no browser formatter or CSS becomes workbook code. */
6
+ export declare function canopyNumberFormat(input: CanopyNumberFormat, report: (diagnostic: CanopyDiagnostic) => void, id: string): string | undefined;
7
+ /** Only a contiguous leading left pin can be represented by an Excel freeze pane. */
8
+ export declare function canopyPins(columns: readonly CanopyExportColumn[], report: (diagnostic: CanopyDiagnostic) => void): number;
@@ -0,0 +1,40 @@
1
+ /** Calibri 11, 96-DPI CSS pixels, seven-pixel maximum digit and five-pixel cell padding.
2
+ * Quantize to native 1/256-character units; this is a reproducible profile, not pixel-identical rendering. */
3
+ export function canopyXlsxWidth(pixels) {
4
+ const width = Math.floor((pixels < 12 ? pixels / 12 : (pixels - 5) / 7) * 256) / 256;
5
+ if (!Number.isFinite(width) || width <= 0 || width > 255)
6
+ throw new RangeError("Captured width exceeds the Calibri-11 XLSX width profile.");
7
+ return width;
8
+ }
9
+ /** Escape literal prefixes/suffixes; no browser formatter or CSS becomes workbook code. */
10
+ export function canopyNumberFormat(input, report, id) {
11
+ if (!input || typeof input !== "object" || Array.isArray(input))
12
+ throw new TypeError("Canopy numeric format must be an object.");
13
+ if (Object.keys(input).some(key => !["minimumFractionDigits", "maximumFractionDigits", "prefix", "suffix"].includes(key))) {
14
+ report({ code: "UNSUPPORTED_NUMBER_FORMAT", columnId: id });
15
+ return undefined;
16
+ }
17
+ const { minimumFractionDigits: minimum = 0, maximumFractionDigits: maximum = 3, prefix = "", suffix = "" } = input;
18
+ if (!Number.isInteger(minimum) || !Number.isInteger(maximum) || minimum < 0 || maximum < minimum || maximum > 10 ||
19
+ typeof prefix !== "string" || typeof suffix !== "string" || prefix.length > 16 || suffix.length > 16)
20
+ throw new TypeError("Canopy numeric fraction bounds must be ordered integers from zero through ten, with literal affixes of at most sixteen characters.");
21
+ const literal = (value) => value ? '"' + value.replace(/"/g, '"\\""') + '"' : "";
22
+ return literal(prefix) + "0" + (maximum ? "." + "0".repeat(minimum) + "#".repeat(maximum - minimum) : "") + literal(suffix);
23
+ }
24
+ /** Only a contiguous leading left pin can be represented by an Excel freeze pane. */
25
+ export function canopyPins(columns, report) {
26
+ let leading = 0, ended = false;
27
+ for (const column of columns) {
28
+ const pin = column.pinned;
29
+ if (pin !== undefined && pin !== null && pin !== "left" && pin !== "right")
30
+ throw new TypeError("Invalid Canopy pin.");
31
+ if (!ended && pin === "left")
32
+ leading++;
33
+ else {
34
+ ended = true;
35
+ if (pin === "left" || pin === "right")
36
+ report({ code: "UNREPRESENTABLE_PIN:" + pin, columnId: column.id });
37
+ }
38
+ }
39
+ return leading;
40
+ }
@@ -0,0 +1,3 @@
1
+ import type { CanopyCapture, CanopyRulePredicate, CanopySourceOptions } from "./types.js";
2
+ /** Compile only comparisons whose raw types and native encodings have a faithful bounded mapping. */
3
+ export declare function canopyPredicate(request: CanopyCapture["request"], grouped: boolean, options: CanopySourceOptions, root: CanopyRulePredicate, unsupported: (code: string) => never, cellTypes: Map<number, "number" | "date">): string;
@@ -0,0 +1,110 @@
1
+ import { columnName, excelDate } from "../../xlsx/values.js";
2
+ import { captureFields } from "../../internal/capture.js";
3
+ import { datetime } from "./dates.js";
4
+ /** Compile only comparisons whose raw types and native encodings have a faithful bounded mapping. */
5
+ export function canopyPredicate(request, grouped, options, root, unsupported, cellTypes) {
6
+ let nodes = 0;
7
+ const operations = { eq: "=", ne: "<>", gt: ">", ge: ">=", lt: "<", le: "<=" };
8
+ const numeric = (value) => {
9
+ const number = typeof value === "boolean" ? Number(value) : typeof value === "string" ? Number(value) : value;
10
+ // Use platform decimal conversion; separator/culture profiles need a diagnostic, not a second parser.
11
+ if (typeof value === "string") {
12
+ const text = value.trim().toLowerCase();
13
+ if (Number.parseFloat(value) !== number || ["0x", "0b", "0o"].some(prefix => text.startsWith(prefix)))
14
+ return unsupported("UNSUPPORTED_NUMERIC_RULE_LITERAL");
15
+ }
16
+ if (!Number.isFinite(number) || Math.abs(number) > Number.MAX_SAFE_INTEGER)
17
+ throw new TypeError("Canopy rule comparison values must be finite safe-range numbers.");
18
+ return number;
19
+ };
20
+ const date = (value) => {
21
+ if (options.datetime !== "typed" || (options.xlsx?.dateMode ?? request.timeZone) !== "utc")
22
+ return unsupported("DATETIME_RULE_REQUIRES_TYPED_UTC");
23
+ if (typeof value === "boolean")
24
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
25
+ if (typeof value === "number" && !Number.isSafeInteger(value))
26
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
27
+ try {
28
+ const literal = typeof value === "number" ? new Date(value).toISOString() : value;
29
+ const captured = datetime(literal, "typed", "utc");
30
+ if (!(captured instanceof Date))
31
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
32
+ const serial = excelDate(captured, "utc");
33
+ if (serial === null)
34
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
35
+ return serial;
36
+ }
37
+ catch (error) {
38
+ if (!(error instanceof TypeError) && !(error instanceof RangeError))
39
+ throw error;
40
+ return unsupported("UNSUPPORTED_DATETIME_RULE_LITERAL");
41
+ }
42
+ };
43
+ const leaf = (input) => {
44
+ if (++nodes > 64)
45
+ return unsupported("RULE_PREDICATE_LIMIT");
46
+ const filter = captureFields(input, ["column", "operator", "values"]), operation = operations[filter.operator];
47
+ if (Object.keys(filter).some(key => !["column", "operator", "values"].includes(key)))
48
+ return unsupported("UNSUPPORTED_RULE_FILTER_OPTIONS");
49
+ const index = request.columns.findIndex(column => column.id === filter.column);
50
+ if (index < 0)
51
+ return unsupported("RULE_COLUMN_NOT_EXPORTED:" + filter.column);
52
+ const column = request.columns[index], letter = columnName(index + 1 + (grouped ? 1 : 0));
53
+ const reference = "INDEX($" + letter + ":$" + letter + ",ROW())", present = "NOT(ISBLANK(" + reference + "))";
54
+ if (column.kind === "number")
55
+ cellTypes.set(index, "number");
56
+ if (column.kind === "datetime") {
57
+ if (options.datetime !== "typed" || (options.xlsx?.dateMode ?? request.timeZone) !== "utc")
58
+ return unsupported("DATETIME_RULE_REQUIRES_TYPED_UTC");
59
+ cellTypes.set(index, "date");
60
+ }
61
+ if (filter.operator === "isNull" || filter.operator === "isNotNull") {
62
+ if (filter.values !== undefined && filter.values.length)
63
+ return unsupported("UNSUPPORTED_NULL_RULE_OPERANDS");
64
+ return filter.operator === "isNull" ? "ISBLANK(" + reference + ")" : present;
65
+ }
66
+ if (!operation || !Array.isArray(filter.values) || filter.values.length !== 1)
67
+ return unsupported("UNSUPPORTED_RULE_FILTER:" + filter.operator);
68
+ const value = filter.values[0];
69
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean")
70
+ throw new TypeError("Canopy rule values must be portable scalars.");
71
+ if (column.kind === "number" || column.kind === "datetime") {
72
+ const operand = column.kind === "number" ? numeric(value) : date(value);
73
+ return "AND(" + present + ",ISNUMBER(" + reference + ")," + reference + operation + String(operand) + ")";
74
+ }
75
+ if (filter.operator !== "eq" && filter.operator !== "ne")
76
+ return unsupported("UNSUPPORTED_TEXT_RULE_COMPARISON");
77
+ // Canopy's Unicode text folding is not the native workbook's comparison contract.
78
+ if (typeof value === "string")
79
+ return unsupported("UNQUALIFIED_NATIVE_TEXT_COMPARISON");
80
+ const kind = typeof value === "boolean" ? "ISLOGICAL" : "ISNUMBER";
81
+ const literal = typeof value === "boolean" ? value ? "TRUE" : "FALSE" : String(numeric(value));
82
+ const sameType = kind + "(" + reference + ")", comparison = reference + operation + literal;
83
+ return filter.operator === "eq" ? "AND(" + present + "," + sameType + "," + comparison + ")"
84
+ : "AND(" + present + ",OR(NOT(" + sameType + ")," + comparison + "))";
85
+ };
86
+ const visit = (input, depth) => {
87
+ if (depth > 4 || ++nodes > 64)
88
+ return unsupported("RULE_PREDICATE_LIMIT");
89
+ if (!input || typeof input !== "object")
90
+ throw new TypeError("Canopy rule predicate must be an object.");
91
+ const captured = captureFields(input, ["operator", "filters", "groups"]);
92
+ if (captured.operator !== "and" && captured.operator !== "or")
93
+ return unsupported("UNSUPPORTED_RULE_BOOLEAN:" + captured.operator);
94
+ const filters = captured.filters ?? [], groups = captured.groups ?? [];
95
+ if (!Array.isArray(filters) || !Array.isArray(groups))
96
+ throw new TypeError("Canopy predicate filters and groups must be arrays.");
97
+ const terms = [];
98
+ for (const filter of filters)
99
+ terms.push(leaf(filter));
100
+ for (const group of groups)
101
+ terms.push(visit(group, depth + 1));
102
+ if (!terms.length)
103
+ return unsupported("EMPTY_RULE_PREDICATE");
104
+ return captured.operator.toUpperCase() + "(" + terms.join(",") + ")";
105
+ };
106
+ const formula = visit(root, 1);
107
+ if (formula.length > 8192)
108
+ return unsupported("RULE_FORMULA_LIMIT");
109
+ return formula;
110
+ }
@@ -0,0 +1,6 @@
1
+ import type { CellPresentation } from "../../core/index.js";
2
+ import type { ConditionalFormat } from "../../xlsx/index.js";
3
+ import type { CanopyCapture, CanopyDiagnostic, CanopyFormat, CanopySourceOptions } from "./types.js";
4
+ /** Compile declarations in source order, then emit native target/aspect priorities.
5
+ * Data-column selectors let grouped writers exclude generated headings, subtotals and grand totals. */
6
+ export declare function canopyRules(request: CanopyCapture["request"], format: CanopyFormat, grouped: boolean, tones: ReadonlyMap<string, Readonly<CellPresentation>>, report: (diagnostic: CanopyDiagnostic) => void, options?: CanopySourceOptions, cellTypes?: Map<number, "number" | "date">): readonly ConditionalFormat[];
@@ -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
+ }