@tallyui/pos 3.12.0 → 3.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.
Files changed (89) hide show
  1. package/dist/index.d.ts +1844 -359
  2. package/dist/index.js +4620 -2211
  3. package/package.json +12 -6
  4. package/src/app-settings/app-settings.ts +108 -0
  5. package/src/app-settings/index.ts +8 -0
  6. package/src/app-settings/use-app-settings.ts +23 -0
  7. package/src/cashier/can.ts +12 -0
  8. package/src/cashier/index.ts +2 -0
  9. package/src/cashier/use-cashier.ts +81 -0
  10. package/src/csv/csv.ts +33 -0
  11. package/src/csv/index.ts +2 -0
  12. package/src/customer-display/display-link.ts +72 -0
  13. package/src/customer-display/display-state.ts +30 -0
  14. package/src/customer-display/index.ts +13 -0
  15. package/src/customer-display/protocol.ts +87 -0
  16. package/src/customer-display/snapshot.ts +65 -0
  17. package/src/customer-display/transport.ts +54 -0
  18. package/src/customer-display/use-customer-display.ts +36 -0
  19. package/src/index.ts +73 -10
  20. package/src/order/order-builder.ts +11 -1
  21. package/src/order/order-drafts.ts +16 -0
  22. package/src/order/types.ts +6 -3
  23. package/src/outbox/index.ts +5 -1
  24. package/src/outbox/outbox-health.ts +40 -0
  25. package/src/outbox/register-outbox.ts +59 -6
  26. package/src/outbox/safe-error.ts +11 -0
  27. package/src/outbox/types.ts +3 -1
  28. package/src/outbox/use-outbox-health.ts +22 -0
  29. package/src/outbox/use-register-outbox.ts +6 -0
  30. package/src/payment-driver/index.ts +8 -0
  31. package/src/payment-driver/registry.ts +39 -0
  32. package/src/payment-driver/simulated-driver.ts +104 -0
  33. package/src/payment-driver/types.ts +73 -0
  34. package/src/pos-order/__fixtures__/order-create-v7.json +97 -0
  35. package/src/pos-order/command.ts +36 -16
  36. package/src/pos-order/finalize.ts +7 -3
  37. package/src/pos-order/index.ts +1 -0
  38. package/src/pos-order/note-delivery.ts +13 -0
  39. package/src/pos-order/reopen.ts +3 -2
  40. package/src/pos-order/schema.ts +5 -4
  41. package/src/pos-order/types.ts +3 -2
  42. package/src/print/escpos/code-page.ts +48 -0
  43. package/src/print/escpos/commands.ts +53 -0
  44. package/src/print/escpos/encode.ts +127 -0
  45. package/src/print/escpos/index.ts +7 -0
  46. package/src/print/escpos/transport.ts +45 -0
  47. package/src/print/index.ts +12 -0
  48. package/src/print/print-queue.ts +67 -0
  49. package/src/print/printer-profiles.ts +71 -0
  50. package/src/print/system-transport.ts +101 -0
  51. package/src/print/types.ts +44 -0
  52. package/src/receipt/reprint.ts +2 -1
  53. package/src/receipt/types.ts +2 -0
  54. package/src/receipt-template/default-templates.ts +78 -0
  55. package/src/receipt-template/index.ts +15 -0
  56. package/src/receipt-template/parse-xml.ts +175 -0
  57. package/src/receipt-template/render-html.ts +152 -0
  58. package/src/receipt-template/render-receipt.ts +19 -0
  59. package/src/receipt-template/render-template.ts +35 -0
  60. package/src/receipt-template/sanitize-html.ts +146 -0
  61. package/src/receipt-template/template-data.ts +97 -0
  62. package/src/receipt-template/types.ts +49 -0
  63. package/src/refund/index.ts +2 -0
  64. package/src/refund/refundable-lines.ts +91 -0
  65. package/src/register/export-csv.ts +24 -35
  66. package/src/register/float-suggestion.ts +22 -0
  67. package/src/register/handover.ts +103 -0
  68. package/src/register/index.ts +10 -3
  69. package/src/register/register-adoption.ts +71 -2
  70. package/src/register/register-commands.ts +7 -4
  71. package/src/register/register-count.helpers.ts +4 -0
  72. package/src/register/session-store.ts +4 -1
  73. package/src/register/use-register-session.ts +112 -28
  74. package/src/reports/adapters.ts +67 -0
  75. package/src/reports/index.ts +5 -0
  76. package/src/reports/presets.ts +27 -0
  77. package/src/reports/sales-figures.ts +187 -0
  78. package/src/reports/types.ts +63 -0
  79. package/src/sale/in-cart.ts +18 -0
  80. package/src/sale/index.ts +5 -1
  81. package/src/sale/open-sales.ts +40 -0
  82. package/src/sale/use-sale.ts +72 -8
  83. package/src/scanner/index.ts +6 -0
  84. package/src/scanner/scan-session.ts +84 -0
  85. package/src/scanner/use-barcode-scanner.ts +61 -0
  86. package/src/scanner/wedge-detector.ts +137 -0
  87. package/src/tender/cash-rounding.ts +74 -0
  88. package/src/tender/index.ts +4 -0
  89. package/src/tender/payment-legs.ts +48 -0
@@ -0,0 +1,175 @@
1
+ // Ported from WCPOS v2 packages/receipt-renderer/src/parse-xml.ts (monorepo main 5ac185b0, MIT).
2
+ // Native DOMParser, else @xmldom/xmldom (React Native).
3
+ import { DOMParser as XmlDOMParser } from '@xmldom/xmldom';
4
+ import type { ColNode, DrawerConnector, ReceiptNode, RowNode, ThermalNode } from './types';
5
+
6
+ /** Parse a thermal XML template string into an AST using the native DOMParser or xmldom. */
7
+ export function parseXml(xml: string): ReceiptNode {
8
+ const doc = parseXmlDocument(xml);
9
+ const errorNode = doc.getElementsByTagName('parsererror')[0];
10
+ if (errorNode) throw new Error(`XML parse error: ${errorNode.textContent}`);
11
+ const root = doc.documentElement;
12
+ if (root.tagName !== 'receipt') {
13
+ throw new Error(`Expected <receipt> root element, got <${root.tagName}>`);
14
+ }
15
+ return { type: 'receipt', paperWidth: intAttr(root, 'paper-width', 48), children: parseChildren(root) };
16
+ }
17
+
18
+ function parseChildren(parent: Element): ThermalNode[] {
19
+ const nodes: ThermalNode[] = [];
20
+ for (const child of Array.from(parent.childNodes)) {
21
+ if (child.nodeType === 3 /* TEXT_NODE */) {
22
+ const text = child.textContent ?? '';
23
+ // Skip indentation, but preserve non-empty text so spaces around inline elements survive.
24
+ if (/\S/.test(text)) nodes.push({ type: 'raw-text', value: text });
25
+ continue;
26
+ }
27
+ if (child.nodeType !== 1 /* ELEMENT_NODE */) continue;
28
+ const el = child as Element;
29
+ const tag = el.tagName.toLowerCase();
30
+ switch (tag) {
31
+ case 'text':
32
+ nodes.push({ type: 'text', children: parseChildren(el) });
33
+ break;
34
+ case 'bold':
35
+ nodes.push({ type: 'bold', children: parseChildren(el) });
36
+ break;
37
+ case 'underline':
38
+ nodes.push({ type: 'underline', children: parseChildren(el) });
39
+ break;
40
+ case 'invert':
41
+ nodes.push({ type: 'invert', children: parseChildren(el) });
42
+ break;
43
+ case 'size': {
44
+ const w = intAttr(el, 'width', 1);
45
+ nodes.push({ type: 'size', width: w, height: intAttr(el, 'height', w), children: parseChildren(el) });
46
+ break;
47
+ }
48
+ case 'align': {
49
+ const modeAttr = el.getAttribute('mode');
50
+ const validModes = ['left', 'center', 'right'] as const;
51
+ const mode = validModes.includes(modeAttr as (typeof validModes)[number])
52
+ ? (modeAttr as 'left' | 'center' | 'right') : 'left';
53
+ nodes.push({ type: 'align', mode, children: parseChildren(el) });
54
+ break;
55
+ }
56
+ case 'row':
57
+ nodes.push({ type: 'row', children: parseRowChildren(el) } as RowNode);
58
+ break;
59
+ case 'col':
60
+ break;
61
+ case 'line': {
62
+ const styleAttr = el.getAttribute('style');
63
+ const validStyles = ['single', 'double', 'dashed', 'dotted'] as const;
64
+ nodes.push({
65
+ type: 'line',
66
+ style: validStyles.includes(styleAttr as (typeof validStyles)[number])
67
+ ? (styleAttr as (typeof validStyles)[number]) : 'single',
68
+ });
69
+ break;
70
+ }
71
+ case 'barcode':
72
+ if (isQrBarcodeType(el.getAttribute('type') ?? 'code128')) {
73
+ nodes.push({
74
+ type: 'qrcode', size: heightToQrSize(intAttr(el, 'height', 40)), value: (el.textContent ?? '').trim(),
75
+ });
76
+ } else {
77
+ nodes.push({
78
+ type: 'barcode', barcodeType: el.getAttribute('type') ?? 'code128',
79
+ height: intAttr(el, 'height', 40), value: (el.textContent ?? '').trim(),
80
+ });
81
+ }
82
+ break;
83
+ case 'qrcode':
84
+ nodes.push({ type: 'qrcode', size: intAttr(el, 'size', 4), value: (el.textContent ?? '').trim() });
85
+ break;
86
+ case 'image':
87
+ nodes.push({ type: 'image', src: el.getAttribute('src') ?? '', width: intAttr(el, 'width', 200) });
88
+ break;
89
+ case 'cut': {
90
+ const cutAttr = el.getAttribute('type');
91
+ const validCuts = ['full', 'partial'] as const;
92
+ nodes.push({
93
+ type: 'cut',
94
+ cutType: validCuts.includes(cutAttr as (typeof validCuts)[number])
95
+ ? (cutAttr as 'full' | 'partial') : 'partial',
96
+ });
97
+ break;
98
+ }
99
+ case 'feed':
100
+ nodes.push({ type: 'feed', lines: intAttr(el, 'lines', 1) });
101
+ break;
102
+ case 'drawer':
103
+ nodes.push({ type: 'drawer', ...(drawerConnectorAttr(el) ? { connector: drawerConnectorAttr(el) } : {}) });
104
+ break;
105
+ default:
106
+ nodes.push(...parseChildren(el));
107
+ }
108
+ }
109
+ return nodes;
110
+ }
111
+
112
+ function drawerConnectorAttr(el: Element): DrawerConnector | undefined {
113
+ const connector = el.getAttribute('connector')?.trim();
114
+ return connector === 'pin2' || connector === 'pin5' ? connector : undefined;
115
+ }
116
+
117
+ function isQrBarcodeType(type: string): boolean {
118
+ return type.trim().toLowerCase() === 'qrcode' || type.trim().toLowerCase() === 'qr';
119
+ }
120
+
121
+ function heightToQrSize(height: number): number {
122
+ return Number.isFinite(height) && height > 0 ? Math.max(2, Math.min(10, Math.round(height / 10))) : 4;
123
+ }
124
+
125
+ function parseRowChildren(row: Element): ColNode[] {
126
+ const cols: ColNode[] = [];
127
+ for (const child of Array.from(row.childNodes)) {
128
+ if (child.nodeType !== 1 /* ELEMENT_NODE */) continue;
129
+ const el = child as Element;
130
+ if (el.tagName.toLowerCase() === 'col') {
131
+ const rawWidth = el.getAttribute('width');
132
+ const width: number | '*' = rawWidth === '*' ? '*' : intAttr(el, 'width', 12);
133
+ cols.push({
134
+ type: 'col', width,
135
+ align: (['left', 'right'] as const).includes(el.getAttribute('align') as 'left' | 'right')
136
+ ? (el.getAttribute('align') as 'left' | 'right') : 'left',
137
+ children: parseChildren(el),
138
+ });
139
+ }
140
+ }
141
+ return cols;
142
+ }
143
+
144
+ function parseXmlDocument(xml: string): Document {
145
+ if (typeof DOMParser !== 'undefined') {
146
+ return new DOMParser().parseFromString(xml, 'text/xml');
147
+ }
148
+
149
+ const errors: string[] = [];
150
+ let doc: Document | undefined;
151
+ try {
152
+ doc = new XmlDOMParser({
153
+ onError: (_level: string, message: unknown) => errors.push(String(message)),
154
+ } as unknown as ConstructorParameters<typeof XmlDOMParser>[0]).parseFromString(
155
+ xml,
156
+ 'text/xml'
157
+ ) as unknown as Document;
158
+ } catch (error) {
159
+ errors.push(error instanceof Error ? error.message : String(error));
160
+ }
161
+
162
+ if (errors.length > 0 || !doc) {
163
+ throw new Error(`XML parse error: ${errors.join('; ') || 'invalid document'}`);
164
+ }
165
+
166
+ return doc;
167
+ }
168
+
169
+ function intAttr(el: Element, name: string, fallback: number): number {
170
+ const raw = el.getAttribute(name)?.trim();
171
+ if (raw == null) return fallback;
172
+ if (!/^[1-9]\d*$/.test(raw)) return fallback;
173
+ const n = Number(raw);
174
+ return Number.isSafeInteger(n) ? n : fallback;
175
+ }
@@ -0,0 +1,152 @@
1
+ // Ported from WCPOS v2 packages/receipt-renderer/src/render-html.ts (monorepo main 5ac185b0, MIT).
2
+ // Barcode SVG generation and options omitted; codes render pending placeholders.
3
+ import type { ColNode, ReceiptNode, RowNode, ThermalNode } from './types';
4
+
5
+ // 80mm paper at 203 DPI prints ~576 dots wide; 58mm prints ~384 dots.
6
+ // The AST gives character width: anything >= 40 chars is treated as 80mm.
7
+ const DOT_BUDGET_WIDE = 576;
8
+ const DOT_BUDGET_NARROW = 384;
9
+ const NARROW_PAPER_THRESHOLD_CHARS = 40;
10
+
11
+ export function renderHtml(ast: ReceiptNode): string {
12
+ const widthChars = safeInteger(ast.paperWidth, 48, 16, 120);
13
+ const inner = renderNodes(ast.children, widthChars);
14
+ return `<div style="width: ${widthChars}ch; font-family: 'Courier New', Courier, monospace; font-size: 13px; ` +
15
+ 'line-height: 1.4; background: #fff; color: #000; padding: 16px 12px; overflow: hidden; ' +
16
+ `white-space: pre-wrap; overflow-wrap: anywhere;">${inner}</div>`;
17
+ }
18
+
19
+ function renderNodes(nodes: ThermalNode[], widthChars: number): string {
20
+ return nodes.map((node) => renderNode(node, widthChars)).join('');
21
+ }
22
+
23
+ function renderNode(node: ThermalNode, widthChars: number): string {
24
+ switch (node.type) {
25
+ case 'raw-text':
26
+ return escapeHtml(node.value);
27
+ case 'text':
28
+ return `<div>${renderNodes(node.children, widthChars)}</div>`;
29
+ case 'bold':
30
+ return `<strong>${renderNodes(node.children, widthChars)}</strong>`;
31
+ case 'underline':
32
+ return `<span style="text-decoration: underline">${renderNodes(node.children, widthChars)}</span>`;
33
+ case 'invert':
34
+ // Inline-block keeps block <text> children from collapsing the reversed background to zero width.
35
+ return '<span style="display: inline-block; background: #000; color: #fff; padding: 0 4px">' +
36
+ `${renderNodes(node.children, widthChars)}</span>`;
37
+ case 'size':
38
+ return `<span style="font-size: ${safeFloat(node.width, 1, 0.5, 8)}em; line-height: 1.2">` +
39
+ `${renderNodes(node.children, widthChars)}</span>`;
40
+ case 'align':
41
+ return `<div style="text-align: ${safeAlign(node.mode)}">${renderNodes(node.children, widthChars)}</div>`;
42
+ case 'row':
43
+ return renderRow(node, widthChars);
44
+ case 'col':
45
+ return renderCol(node, widthChars);
46
+ case 'line':
47
+ if (node.style === 'double') return '<hr style="border: none; border-top: 3px double #000; margin: 4px 0" />';
48
+ if (node.style === 'dashed') return '<hr style="border: none; border-top: 1px dashed #000; margin: 4px 0" />';
49
+ if (node.style === 'dotted') return '<hr style="border: none; border-top: 1px dotted #000; margin: 4px 0" />';
50
+ return '<hr style="border: none; border-top: 1px solid #000; margin: 4px 0" />';
51
+ case 'barcode':
52
+ return pendingCode(isQrBarcodeType(node.barcodeType) ? 'qrcode' : 'barcode', node.value);
53
+ case 'qrcode':
54
+ return pendingCode('qrcode', node.value);
55
+ case 'image': {
56
+ const safeSrc = safeImageSrc(node.src);
57
+ if (!safeSrc) return '';
58
+ const widthDots = safeInteger(node.width, 200, 1, 2000);
59
+ const widthCh = dotsToCh(widthDots, widthChars);
60
+ return `<div style="text-align: center; padding: 8px 0"><img src="${safeSrc}" ` +
61
+ `style="width: min(100%, ${widthCh.toFixed(2)}ch); height: auto" /></div>`;
62
+ }
63
+ case 'cut':
64
+ return '<div style="border-top: 1px dashed #ccc; margin: 12px 0; position: relative">' +
65
+ '<span style="position: absolute; top: -8px; left: -4px; font-size: 14px">&#9986;</span></div>';
66
+ case 'feed':
67
+ return `<div style="height: ${(safeInteger(node.lines, 1, 1, 50) * 1.4).toFixed(1)}em"></div>`;
68
+ case 'drawer':
69
+ return '';
70
+ case 'receipt':
71
+ return renderNodes(node.children, widthChars);
72
+ default:
73
+ return '';
74
+ }
75
+ }
76
+
77
+ function pendingCode(kind: 'barcode' | 'qrcode', value: string): string {
78
+ const text = value.trim();
79
+ if (!text) return '';
80
+ const safeKind = kind === 'qrcode' ? 'qrcode' : 'barcode';
81
+ return `<div data-barcode-kind="${safeKind}" data-barcode-value="${escapeHtml(text)}" ` +
82
+ 'data-barcode-pending="true" style="text-align: center; padding: 8px 0">' +
83
+ `<code>${escapeHtml(text)}</code></div>`;
84
+ }
85
+
86
+ function renderRow(node: RowNode, widthChars: number): string {
87
+ const cols = node.children.map((col) => renderCol(col, widthChars)).join('');
88
+ return `<div style="display: flex">${cols}</div>`;
89
+ }
90
+
91
+ function renderCol(node: ColNode, widthChars: number): string {
92
+ const flex = node.width === '*' ? 'flex: 1' : `flex: 0 0 ${safeInteger(node.width, 12, 1, 120)}ch`;
93
+ return `<span style="${flex}; text-align: ${safeAlign(node.align)}; overflow: hidden">` +
94
+ `${renderNodes(node.children, widthChars)}</span>`;
95
+ }
96
+
97
+ function safeInteger(value: unknown, fallback: number, min: number, max: number): number {
98
+ const n = Math.trunc(Number(value));
99
+ return Number.isFinite(n) && n >= min && n <= max ? n : fallback;
100
+ }
101
+
102
+ function safeFloat(value: unknown, fallback: number, min: number, max: number): number {
103
+ const n = Number(value);
104
+ return Number.isFinite(n) && n >= min && n <= max ? n : fallback;
105
+ }
106
+
107
+ function safeAlign(value: unknown): 'left' | 'center' | 'right' {
108
+ return value === 'left' || value === 'center' || value === 'right' ? value : 'left';
109
+ }
110
+
111
+ function isQrBarcodeType(type: string): boolean {
112
+ const normalized = type.trim().toLowerCase();
113
+ return normalized === 'qrcode' || normalized === 'qr';
114
+ }
115
+
116
+ /** Convert printer dots to ch units relative to the receipt's character width. */
117
+ function dotsToCh(dots: number, paperWidthChars: number): number {
118
+ const dotBudget = paperWidthChars >= NARROW_PAPER_THRESHOLD_CHARS ? DOT_BUDGET_WIDE : DOT_BUDGET_NARROW;
119
+ return (dots * paperWidthChars) / dotBudget;
120
+ }
121
+
122
+ function safeImageSrc(src: unknown): string {
123
+ if (typeof src !== 'string') return '';
124
+ const value = src.trim();
125
+ const isHttpUrl = /^https?:\/\//i.test(value);
126
+ const isSafeDataUri = /^data:image\/(?:png|jpe?g|gif);base64,[A-Za-z0-9+/=]+$/i.test(value);
127
+ const isSafeRootRelative = isSafeRootRelativeImageSrc(value);
128
+ return isHttpUrl || isSafeDataUri || isSafeRootRelative ? escapeHtml(value) : '';
129
+ }
130
+
131
+ function isSafeRootRelativeImageSrc(value: string): boolean {
132
+ if (value.startsWith('//')) return false;
133
+ if (value.includes('\\')) return false;
134
+ const path = value.split(/[?#]/, 1)[0];
135
+ const suffix = value.slice(path.length);
136
+ let decodedPath: string;
137
+ try {
138
+ decodedPath = decodeURIComponent(path);
139
+ } catch {
140
+ return false;
141
+ }
142
+ if (decodedPath.includes('\\')) return false;
143
+ const segments = decodedPath.split('/');
144
+ if (segments.includes('..') || segments.includes('.')) return false;
145
+ return /^\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]+$/.test(path) &&
146
+ (suffix === '' || /^[?#][A-Za-z0-9._~!$&'()*+,;=:@%/?#-]+$/.test(suffix));
147
+ }
148
+
149
+ function escapeHtml(str: string): string {
150
+ return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
151
+ .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
152
+ }
@@ -0,0 +1,19 @@
1
+ import type { ReceiptData } from '../receipt/types';
2
+ import { DEFAULT_RECEIPT_TEMPLATES } from './default-templates';
3
+ import type { ReceiptPaper } from './default-templates';
4
+ import { renderThermalPreview } from './render-template';
5
+ import { receiptTemplateData } from './template-data';
6
+ import type { ReceiptTemplateOptions } from './template-data';
7
+
8
+ export interface RenderReceiptOptions extends ReceiptTemplateOptions {
9
+ /** Default '80mm'. Picks DEFAULT_RECEIPT_TEMPLATES[paper] when no template is given. */
10
+ paper?: ReceiptPaper;
11
+ /** A thermal-XML Mustache template over ReceiptTemplateData. */
12
+ template?: string;
13
+ }
14
+
15
+ /** receiptTemplateData, then renderThermalPreview (sanitized). Needs a global DOMParser (browsers, jsdom). */
16
+ export function renderReceiptHtml(receipt: ReceiptData, options: RenderReceiptOptions = {}): string {
17
+ const template = options.template ?? DEFAULT_RECEIPT_TEMPLATES[options.paper ?? '80mm'];
18
+ return renderThermalPreview(template, receiptTemplateData(receipt, options));
19
+ }
@@ -0,0 +1,35 @@
1
+ // Ported from WCPOS v2 packages/receipt-renderer/src/render-template.ts (monorepo main 5ac185b0, MIT).
2
+ // Uses object data; barcode resolution and SVG sanitization options omitted.
3
+ import Mustache from 'mustache';
4
+ import { parseXml } from './parse-xml';
5
+ import { renderHtml } from './render-html';
6
+ import { sanitizeHtml } from './sanitize-html';
7
+ import type { SanitizeHtmlOptions } from './sanitize-html';
8
+
9
+ export interface RenderSanitizeOptions extends SanitizeHtmlOptions {
10
+ /** Disable sanitization only for trusted test/debug output. Defaults to true. */
11
+ sanitize?: boolean;
12
+ }
13
+
14
+ /** Mustache only. */
15
+ export function renderReceiptTemplate(template: string, data: object): string {
16
+ return Mustache.render(template, data);
17
+ }
18
+
19
+ /** Mustache HTML template, then sanitize (unless sanitize === false). No <barcode>/<qrcode> resolution. */
20
+ export function renderLogiclessTemplate(
21
+ template: string, data: object, options: RenderSanitizeOptions = {},
22
+ ): string {
23
+ const html = Mustache.render(template, data);
24
+ return options.sanitize === false ? html : sanitizeHtml(html, options);
25
+ }
26
+
27
+ /** Mustache, then parseXml, then renderHtml, then sanitize (unless sanitize === false). */
28
+ export function renderThermalPreview(
29
+ template: string, data: object, options: RenderSanitizeOptions = {},
30
+ ): string {
31
+ const resolved = Mustache.render(template, data);
32
+ const ast = parseXml(resolved);
33
+ const html = renderHtml(ast);
34
+ return options.sanitize === false ? html : sanitizeHtml(html, options);
35
+ }
@@ -0,0 +1,146 @@
1
+ // Ported from WCPOS v2 packages/receipt-renderer/src/sanitize-html.ts (monorepo main 5ac185b0, MIT).
2
+ // All three runtime paths ported: DOMPurify, DOM walk, xmldom.
3
+ import { DOMParser as XmlDOMParser, XMLSerializer as XmlSerializer } from '@xmldom/xmldom';
4
+ import createDOMPurify from 'dompurify';
5
+
6
+ export interface SanitizeHtmlOptions {
7
+ /** Additional tag names to allow beyond DOMPurify's default HTML profile. */
8
+ addTags?: string[];
9
+ /** Additional attribute names to allow beyond DOMPurify's default HTML profile. */
10
+ addAttributes?: string[];
11
+ }
12
+
13
+ /**
14
+ * Sanitize rendered receipt HTML before it is inserted into an admin/browser DOM
15
+ * (or a native WebView via `srcDoc`).
16
+ *
17
+ * The default profile deliberately excludes SVG/MathML and strips scripts,
18
+ * event handlers, and unsafe URL protocols while preserving normal receipt HTML.
19
+ *
20
+ * Three execution paths, in priority order:
21
+ * 1. Browser/DOM with `window.document` → DOMPurify (the strongest profile).
22
+ * 2. A runtime that exposes a global `DOMParser` (e.g. jsdom/SSR) → DOM walk.
23
+ * 3. React Native, which has neither → parse via `@xmldom/xmldom` and walk.
24
+ *
25
+ * The xmldom fallback mirrors `parse-xml.ts`, which already uses xmldom on
26
+ * native. Without it, native runtimes hit the escaped-text last resort and the
27
+ * receipt preview renders raw HTML markup as visible text instead of HTML.
28
+ */
29
+ export function sanitizeHtml(html: string, options: SanitizeHtmlOptions = {}): string {
30
+ const win = globalThis.window;
31
+
32
+ if (win?.document) {
33
+ const purify = createDOMPurify(win);
34
+ return purify.sanitize(html, {
35
+ USE_PROFILES: { html: true },
36
+ ADD_TAGS: options.addTags,
37
+ ADD_ATTR: options.addAttributes,
38
+ });
39
+ }
40
+
41
+ const parsed = parseHtmlForSanitize(html);
42
+ if (!parsed) {
43
+ // Last-resort non-DOM fallback for SSR/build tooling: return escaped text instead of unsafe markup.
44
+ return escapeHtml(html);
45
+ }
46
+
47
+ sanitizeParsedBody(parsed.body, options);
48
+ return parsed.serialize();
49
+ }
50
+
51
+ const URL_BEARING_ATTRIBUTES = new Set(['href', 'src', 'action', 'formaction', 'xlink:href']);
52
+
53
+ /** Executable, document-control, remote-fetch and SVG/MathML tags stripped unless explicitly allow-listed. */
54
+ const DANGEROUS_TAGS = new Set([
55
+ 'script', 'iframe', 'object', 'embed', 'style', 'link', 'meta', 'base', 'svg', 'math',
56
+ ]);
57
+
58
+ const XHTML_NAMESPACE_ATTR = / xmlns="http:\/\/www\.w3\.org\/1999\/xhtml"/g;
59
+
60
+ function hasUnsafeProtocol(raw: string): boolean {
61
+ // eslint-disable-next-line no-control-regex -- Strip control characters before checking URL protocols, as in v2.
62
+ const normalized = raw.replace(/[\u0000-\u001F\u007F\s]+/g, '').toLowerCase();
63
+ return normalized.startsWith('javascript:') || normalized.startsWith('vbscript:') || normalized.startsWith('data:');
64
+ }
65
+
66
+ interface ParsedHtml {
67
+ body: Element;
68
+ serialize: () => string;
69
+ }
70
+
71
+ /**
72
+ * Parse `html` into a DOM `<body>` and return a serializer for its inner HTML.
73
+ * Uses the native `DOMParser` when present, and falls back to `@xmldom/xmldom`
74
+ * for React Native runtimes that do not provide browser DOM globals. Returns
75
+ * `null` when no parser can produce a document (callers escape as a last resort).
76
+ */
77
+ function parseHtmlForSanitize(html: string): ParsedHtml | null {
78
+ const source = `<!doctype html><html><body>${html}</body></html>`;
79
+
80
+ if (typeof DOMParser !== 'undefined') {
81
+ const doc = new DOMParser().parseFromString(source, 'text/html');
82
+ const body = doc.body ?? doc.getElementsByTagName('body')[0];
83
+ if (!body) return null;
84
+ return { body, serialize: () => body.innerHTML };
85
+ }
86
+
87
+ try {
88
+ const errors: string[] = [];
89
+ const doc = new XmlDOMParser({
90
+ onError: (_level: string, message: unknown) => errors.push(String(message)),
91
+ } as unknown as ConstructorParameters<typeof XmlDOMParser>[0]).parseFromString(
92
+ source,
93
+ 'text/html'
94
+ ) as unknown as Document;
95
+
96
+ const body = doc.getElementsByTagName('body')[0] as unknown as Element | undefined;
97
+ if (!body) return null;
98
+
99
+ const serializer = new XmlSerializer();
100
+ return {
101
+ body,
102
+ serialize: () => {
103
+ let inner = '';
104
+ for (const child of Array.from(body.childNodes)) {
105
+ inner += serializer.serializeToString(
106
+ child as unknown as Parameters<typeof serializer.serializeToString>[0]
107
+ );
108
+ }
109
+ // xmldom annotates serialized HTML nodes with the XHTML namespace; the
110
+ // attribute is inert in a WebView but noisy, so drop it.
111
+ // codeql[js/unsafe-html] Safe because sanitizeParsedBody() removes dangerous
112
+ // elements, event handlers, and unsafe URL protocols before serialize() runs.
113
+ return inner.replace(XHTML_NAMESPACE_ATTR, '');
114
+ },
115
+ };
116
+ } catch {
117
+ return null;
118
+ }
119
+ }
120
+
121
+ /** Remove dangerous elements, event-handler attributes, and unsafe-protocol URLs from the parsed body. */
122
+ function sanitizeParsedBody(body: Element, options: SanitizeHtmlOptions): void {
123
+ const allowedExtraTags = new Set((options.addTags ?? []).map((tag) => tag.toLowerCase()));
124
+ const allowedExtraAttrs = new Set((options.addAttributes ?? []).map((attr) => attr.toLowerCase()));
125
+ for (const el of Array.from(body.getElementsByTagName('*'))) {
126
+ const tag = el.tagName.toLowerCase();
127
+ if (DANGEROUS_TAGS.has(tag) && !allowedExtraTags.has(tag)) el.parentNode?.removeChild(el);
128
+ }
129
+ for (const el of Array.from(body.getElementsByTagName('*'))) {
130
+ if (!el.attributes) continue;
131
+ for (const attr of Array.from(el.attributes)) {
132
+ const name = attr.name.toLowerCase();
133
+ const value = (attr.value ?? '').trim();
134
+ if (name.startsWith('on') && !allowedExtraAttrs.has(name)) {
135
+ el.removeAttribute(attr.name);
136
+ continue;
137
+ }
138
+ if (URL_BEARING_ATTRIBUTES.has(name) && hasUnsafeProtocol(value)) el.removeAttribute(attr.name);
139
+ }
140
+ }
141
+ }
142
+
143
+ function escapeHtml(str: string): string {
144
+ return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
145
+ .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
146
+ }
@@ -0,0 +1,97 @@
1
+ import { formatMoney } from '@tallyui/core';
2
+ import type { ReceiptData } from '../receipt/types';
3
+
4
+ export interface ReceiptTemplateRow { label: string; amount: string }
5
+ export interface ReceiptTemplateLine {
6
+ name: string;
7
+ /** `Name: value` per variant option, in `attributes` order. */
8
+ options: { text: string }[];
9
+ /** `<quantity> × <unit price>`. */
10
+ detail: string;
11
+ /** displayAmountMinor, before any discount. */
12
+ amount: string;
13
+ /** The line's own displayDiscounts; amount carries a leading `−`. */
14
+ discounts: ReceiptTemplateRow[];
15
+ }
16
+ export interface ReceiptTemplateData {
17
+ store: { name: string; addressLines: { line: string }[] };
18
+ document: { title: string; isReprint: boolean; reprintCount: number };
19
+ order: { number: string; date: string };
20
+ cashier: string;
21
+ register: string;
22
+ customer: string;
23
+ lines: ReceiptTemplateLine[];
24
+ subtotal: string;
25
+ lineDiscount: string;
26
+ orderDiscount: string;
27
+ charges: ReceiptTemplateRow[];
28
+ taxes: ReceiptTemplateRow[];
29
+ total: string;
30
+ payments: { method: string; amount: string; reference: string }[];
31
+ change: string;
32
+ note: string;
33
+ qrPayload: string;
34
+ }
35
+ export interface ReceiptTemplateOptions {
36
+ /** Default: formatMoney({ amount: minor, currency }) ?? ''. */
37
+ formatMoney?: (minor: number, currency: string) => string;
38
+ /** Default: Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' });
39
+ * an unparseable date is returned as given. */
40
+ formatDate?: (iso: string) => string;
41
+ /** Default: 'cash' → 'Cash', 'external' → 'Card terminal', anything else as given. */
42
+ paymentLabel?: (method: string) => string;
43
+ }
44
+
45
+ export function receiptTemplateData(receipt: ReceiptData, options: ReceiptTemplateOptions = {}): ReceiptTemplateData {
46
+ const money = (minor: number) => options.formatMoney
47
+ ? options.formatMoney(minor, receipt.currency) : formatMoney({ amount: minor, currency: receipt.currency }) ?? '';
48
+ const date = options.formatDate ?? ((iso: string) => {
49
+ const parsed = new Date(iso);
50
+ return Number.isNaN(parsed.getTime()) ? iso
51
+ : new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(parsed);
52
+ });
53
+ const paymentLabel = options.paymentLabel ?? ((method: string) =>
54
+ method === 'cash' ? 'Cash' : method === 'external' ? 'Card terminal' : method);
55
+ const titles = {
56
+ sale: 'Receipt', refund: 'Refund', void: 'Void', cancellation: 'Cancellation', closure: 'Z report', x_report: 'X report',
57
+ };
58
+ const { header, fiscal, totals } = receipt;
59
+ const lineDiscountMinor = totals.discountMinor - receipt.orderDiscountMinor;
60
+ return {
61
+ store: {
62
+ name: header.storeName,
63
+ addressLines: (header.storeAddress ?? '').split('\n').map((line) => line.trim())
64
+ .filter((line) => line !== '').map((line) => ({ line })),
65
+ },
66
+ document: { title: titles[fiscal.document_type], isReprint: fiscal.is_reprint, reprintCount: fiscal.reprint_count },
67
+ order: { number: header.orderNumber, date: date(header.date) },
68
+ cashier: header.cashier ?? '',
69
+ register: receipt.register.name,
70
+ customer: header.customer ?? '',
71
+ lines: receipt.lineItems.map((line) => ({
72
+ name: line.name,
73
+ options: Object.entries(line.attributes ?? {}).map(([name, value]) => ({ text: `${name}: ${value}` })),
74
+ detail: `${line.quantity} × ${money(line.unitPriceMinor)}`,
75
+ amount: money(line.displayAmountMinor),
76
+ discounts: line.displayDiscounts.map((discount) => ({
77
+ label: discount.label, amount: `−${money(discount.amountMinor)}`,
78
+ })),
79
+ })),
80
+ subtotal: money(totals.subtotalMinor),
81
+ lineDiscount: lineDiscountMinor > 0 ? `−${money(lineDiscountMinor)}` : '',
82
+ orderDiscount: receipt.orderDiscountMinor > 0 ? `−${money(receipt.orderDiscountMinor)}` : '',
83
+ charges: [...receipt.fees, ...receipt.shipping].map((charge) => ({
84
+ label: charge.name, amount: money(charge.amountMinor),
85
+ })),
86
+ taxes: totals.taxLines.map((tax) => ({
87
+ label: (totals.taxInclusive ? 'incl. ' : '') + tax.label, amount: money(tax.amountMinor),
88
+ })),
89
+ total: money(totals.totalMinor),
90
+ payments: receipt.payments.map((payment) => ({
91
+ method: paymentLabel(payment.method), amount: money(payment.amountMinor), reference: payment.reference ?? '',
92
+ })),
93
+ change: receipt.changeDueMinor > 0 ? money(receipt.changeDueMinor) : '',
94
+ note: receipt.footer.note ?? '',
95
+ qrPayload: fiscal.qr_payload,
96
+ };
97
+ }
@@ -0,0 +1,49 @@
1
+ // Ported from WCPOS v2 packages/receipt-renderer/src/types.ts (monorepo main 5ac185b0, MIT).
2
+ // AST shapes unchanged; ESC/POS image and barcode encoding types omitted.
3
+ export type DrawerConnector = 'pin2' | 'pin5';
4
+
5
+ export type ThermalNode =
6
+ | ReceiptNode | TextNode | RawTextNode | BoldNode | UnderlineNode | InvertNode
7
+ | SizeNode | AlignNode | RowNode | ColNode | LineNode | BarcodeNode | QrcodeNode
8
+ | ImageNode | CutNode | FeedNode | DrawerNode;
9
+
10
+ export interface ReceiptNode {
11
+ type: 'receipt';
12
+ paperWidth: number;
13
+ children: ThermalNode[];
14
+ }
15
+ export interface RawTextNode { type: 'raw-text'; value: string }
16
+ export interface TextNode { type: 'text'; children: ThermalNode[] }
17
+ export interface BoldNode { type: 'bold'; children: ThermalNode[] }
18
+ export interface UnderlineNode { type: 'underline'; children: ThermalNode[] }
19
+ export interface InvertNode { type: 'invert'; children: ThermalNode[] }
20
+ export interface SizeNode {
21
+ type: 'size';
22
+ width: number;
23
+ height: number;
24
+ children: ThermalNode[];
25
+ }
26
+ export interface AlignNode {
27
+ type: 'align';
28
+ mode: 'left' | 'center' | 'right';
29
+ children: ThermalNode[];
30
+ }
31
+ export interface RowNode { type: 'row'; children: ColNode[] }
32
+ export interface ColNode {
33
+ type: 'col';
34
+ width: number | '*';
35
+ align: 'left' | 'right';
36
+ children: ThermalNode[];
37
+ }
38
+ export interface LineNode { type: 'line'; style: 'single' | 'double' | 'dashed' | 'dotted' }
39
+ export interface BarcodeNode {
40
+ type: 'barcode';
41
+ barcodeType: string;
42
+ height: number;
43
+ value: string;
44
+ }
45
+ export interface QrcodeNode { type: 'qrcode'; size: number; value: string }
46
+ export interface ImageNode { type: 'image'; src: string; width: number }
47
+ export interface CutNode { type: 'cut'; cutType: 'full' | 'partial' }
48
+ export interface FeedNode { type: 'feed'; lines: number }
49
+ export interface DrawerNode { type: 'drawer'; connector?: DrawerConnector }