@docxkit/plugin-barcode 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025-PRESENT ntnyq <https://github.com/ntnyq>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,16 @@
1
+ # @docxkit/plugin-barcode
2
+
3
+ Linear barcode generation plugin for docx-kit.
4
+
5
+ ## Usage
6
+
7
+ ```ts
8
+ import { barcodePlugin } from '@docxkit/plugin-barcode'
9
+
10
+ const doc = createDocx()
11
+ .use(barcodePlugin())
12
+ .plugin('barcode', {
13
+ format: 'code128',
14
+ text: 'DOCX-KIT-2026',
15
+ })
16
+ ```
@@ -0,0 +1,1107 @@
1
+ import { LiteralUnion } from "@docxkit/core";
2
+ //#region ../../packages/types/dist/utility.d.ts
3
+ /** Hexadecimal CSS color string, e.g. `"#ff0000"`. */
4
+ type HexColor = `#${string}`;
5
+ /**
6
+ * A literal union type that still allows arbitrary string values.
7
+ * Useful for autocomplete-friendly APIs with extensible values.
8
+ *
9
+ * @template T — The literal subtype (e.g. `'Arial' | 'Calibri'`)
10
+ * @template U — The base type, defaults to `string`
11
+ */
12
+ type LiteralUnion$1<T extends U, U = string> = T | (U & {});
13
+ /**
14
+ * A value that might be synchronous or wrapped in a Promise.
15
+ *
16
+ * @template T — The inner value type
17
+ */
18
+ type MaybePromise<T> = Promise<T> | T;
19
+ /**
20
+ * Augments a base value type with theme token references.
21
+ *
22
+ * Lets users write `$colors.primary` in any style field that accepts the
23
+ * base type — the token is resolved at compile time against the document
24
+ * theme.
25
+ */
26
+ type StyleToken<T extends number | string> = T | ThemeToken;
27
+ /** Supported theme token categories (must match {@link resolveSingleToken}). */
28
+ type StyleTokenCategory = '$colors' | '$fonts' | '$fontSize' | '$spacing';
29
+ /**
30
+ * A `$category.key` reference to a theme token, e.g. `"$colors.primary"`,
31
+ * `"$fontSize.lg"`, `"$spacing.xl"`. Resolved at compile time by
32
+ * {@link resolveThemeTokens}.
33
+ */
34
+ type ThemeToken = `${StyleTokenCategory}.${string}`;
35
+ /**
36
+ * CSS-like length value.
37
+ *
38
+ * Supports bare numbers, explicit unit strings
39
+ * (`%`, `cm`, `in`, `mm`, `pt`, `px`), and theme token references
40
+ * (e.g. `"$spacing.lg"`, `"$fontSize.base"`).
41
+ *
42
+ * Bare-number conventions vary by context:
43
+ * - `fontSize` → interpreted as `pt`
44
+ * - spacing / indent → interpreted as `pt`
45
+ * - image size → interpreted as `px`
46
+ */
47
+ type UnitValue = `${number}%` | `${number}cm` | `${number}in` | `${number}mm` | `${number}pt` | `${number}px` | number | ThemeToken;
48
+ //#endregion
49
+ //#region ../../packages/types/dist/style.d.ts
50
+ /**
51
+ * A single border side descriptor.
52
+ *
53
+ * Follows the CSS `border` shorthand convention (style, width, color).
54
+ */
55
+ interface BorderRule {
56
+ /** Border color (e.g. `"#333"`, named color, or theme token like `"$colors.primary"`). */
57
+ color?: HexColor | StyleToken<string>;
58
+ /** Line style. */
59
+ style?: BorderStyle;
60
+ /** Line width (bare number treated as pt). */
61
+ width?: UnitValue;
62
+ }
63
+ /** Available border line styles. */
64
+ type BorderStyle = 'dashed' | 'dotted' | 'double' | 'none' | 'single';
65
+ /**
66
+ * Table-cell level style properties.
67
+ *
68
+ * Used by {@link compileCellStyle} for `TableCell` construction.
69
+ */
70
+ interface CellStyleRule {
71
+ /** Background / shading color (hex, named, or theme token like `"$colors.info"`). */
72
+ backgroundColor?: HexColor | StyleToken<string>;
73
+ /** Shorthand border for all four sides. */
74
+ border?: BorderRule;
75
+ /** Bottom border override. */
76
+ borderBottom?: BorderRule;
77
+ /** Left border override. */
78
+ borderLeft?: BorderRule;
79
+ /** Right border override. */
80
+ borderRight?: BorderRule;
81
+ /** Top border override. */
82
+ borderTop?: BorderRule;
83
+ /** Element height. */
84
+ height?: UnitValue;
85
+ /** Bottom margin (cell padding). */
86
+ marginBottom?: UnitValue;
87
+ /** Left margin (cell padding). */
88
+ marginLeft?: UnitValue;
89
+ /** Right margin (cell padding). */
90
+ marginRight?: UnitValue;
91
+ /** Top margin (cell padding). */
92
+ marginTop?: UnitValue;
93
+ /** Vertical alignment (mostly for table cells). */
94
+ verticalAlign?: VerticalAlign;
95
+ /** Element width. */
96
+ width?: UnitValue;
97
+ /**
98
+ * CSS-like margin shorthand (used as cell padding).
99
+ */
100
+ margin?: `${string} ${string}` | `${string} ${string} ${string} ${string}` | UnitValue;
101
+ }
102
+ /**
103
+ * CSS-like style descriptor for a run, paragraph, cell, or table.
104
+ *
105
+ * Combines text, paragraph, and cell-level properties.
106
+ * This is the user-facing style type — individual compiler functions
107
+ * narrow to {@link TextStyleRule}, {@link ParagraphStyleRule}, or
108
+ * {@link CellStyleRule} as appropriate.
109
+ */
110
+ interface DocxStyleRule extends CellStyleRule, ParagraphStyleRule, TextStyleRule {}
111
+ /**
112
+ * Font weight: keyword `"bold"` / `"normal"`, or numeric 100–900
113
+ * following the CSS `font-weight` spec.
114
+ */
115
+ type FontWeight = 'bold' | 'normal' | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
116
+ /** Text highlight / marker colors (matches Word highlight palette). */
117
+ type HighlightColor = 'black' | 'blue' | 'cyan' | 'darkBlue' | 'darkCyan' | 'darkGray' | 'darkGreen' | 'darkMagenta' | 'darkRed' | 'darkYellow' | 'green' | 'lightGray' | 'magenta' | 'none' | 'red' | 'white' | 'yellow';
118
+ /**
119
+ * Paragraph-level style properties.
120
+ *
121
+ * Used by {@link compileParagraphStyle} for `Paragraph` construction.
122
+ */
123
+ interface ParagraphStyleRule {
124
+ /** Shorthand border for all four sides. */
125
+ border?: BorderRule;
126
+ /** Bottom border override. */
127
+ borderBottom?: BorderRule;
128
+ /** Left border override. */
129
+ borderLeft?: BorderRule;
130
+ /** Right border override. */
131
+ borderRight?: BorderRule;
132
+ /** Top border override. */
133
+ borderTop?: BorderRule;
134
+ /** Keep lines together on same page. */
135
+ keepLines?: boolean;
136
+ /** Keep this paragraph with the next one. */
137
+ keepNext?: boolean;
138
+ /** Line height multiplier or explicit unit value. */
139
+ lineHeight?: number | UnitValue;
140
+ /** Bottom margin. */
141
+ marginBottom?: UnitValue;
142
+ /** Left margin. */
143
+ marginLeft?: UnitValue;
144
+ /** Right margin. */
145
+ marginRight?: UnitValue;
146
+ /** Top margin. */
147
+ marginTop?: UnitValue;
148
+ /** Outline level used by Word navigation and table-of-contents fields (0–9). */
149
+ outlineLevel?: number;
150
+ /** Force page break before this paragraph. */
151
+ pageBreakBefore?: boolean;
152
+ /** Custom tab stops for this paragraph. */
153
+ tabStops?: TabStopRule[];
154
+ /** Horizontal text alignment. */
155
+ textAlign?: TextAlign;
156
+ /** First-line indent. */
157
+ textIndent?: UnitValue;
158
+ /** Prevent isolated first or last lines across page boundaries. */
159
+ widowControl?: boolean;
160
+ /**
161
+ * CSS-like margin shorthand.
162
+ *
163
+ * Supports 1-value, 2-value, and 4-value string syntax
164
+ * (e.g. `"10pt"`, `"10pt 20pt"`, `"10pt 20pt 30pt 40pt"`).
165
+ */
166
+ margin?: `${string} ${string}` | `${string} ${string} ${string} ${string}` | UnitValue;
167
+ }
168
+ /**
169
+ * A map of class name → style rule.
170
+ *
171
+ * Used to define reusable named styles referenced via `className` on nodes.
172
+ *
173
+ * @example
174
+ * ```ts
175
+ * const styles = defineStyles({
176
+ * red: { color: '#ff0000' },
177
+ * big: { fontSize: 20 },
178
+ * })
179
+ * ```
180
+ */
181
+ type StyleSheet = Record<string, StyleSheetEntry>;
182
+ /**
183
+ * A single entry in the stylesheet.
184
+ *
185
+ * Extends {@link DocxStyleRule} with an optional `extends` property
186
+ * that allows style classes to inherit from other classes.
187
+ *
188
+ * @example
189
+ * ```ts
190
+ * defineStyles({
191
+ * baseText: { fontFamily: 'Arial', fontSize: 12, color: '#333' },
192
+ * heading: { extends: 'baseText', fontSize: 20, fontWeight: 'bold' },
193
+ * muted: { extends: 'baseText', color: '#888' },
194
+ * })
195
+ * ```
196
+ */
197
+ interface StyleSheetEntry extends DocxStyleRule {
198
+ /** Inherit style properties from one or more other style classes. */
199
+ extends?: string | string[];
200
+ }
201
+ /** A paragraph tab stop. */
202
+ interface TabStopRule {
203
+ /** Position from the paragraph's left edge. */
204
+ position: UnitValue;
205
+ /** Optional leader characters before the tab stop. */
206
+ leader?: 'dot' | 'hyphen' | 'middleDot' | 'none' | 'underscore';
207
+ /** Tab alignment. */
208
+ type: 'bar' | 'center' | 'clear' | 'decimal' | 'end' | 'left' | 'num' | 'right' | 'start';
209
+ }
210
+ /** Horizontal text alignment. */
211
+ type TextAlign = 'center' | 'justify' | 'left' | 'right';
212
+ /**
213
+ * Text-level style properties (font, color, size, weight, etc.).
214
+ *
215
+ * Used by {@link compileTextStyle} for `TextRun` construction.
216
+ *
217
+ * @remarks
218
+ * Convenience boolean shortcuts `bold` and `italic` are provided
219
+ * alongside the canonical `fontWeight` / `fontStyle` properties.
220
+ * When `bold: true` is set, it is equivalent to `fontWeight: 'bold'`.
221
+ * When `italic: true` is set, it is equivalent to `fontStyle: 'italic'`.
222
+ */
223
+ interface TextStyleRule {
224
+ /** Force text to uppercase (small caps-like). */
225
+ allCaps?: boolean;
226
+ /** Background / shading color (hex, named, or theme token like `"$colors.info"`). */
227
+ backgroundColor?: HexColor | StyleToken<string>;
228
+ /**
229
+ * Convenience boolean: `true` maps to `fontWeight: 'bold'`.
230
+ * Takes precedence over `fontWeight` when both are set.
231
+ */
232
+ bold?: boolean;
233
+ /** Raw OOXML character spacing in twips. Prefer `letterSpacing` for CSS units. */
234
+ characterSpacing?: number;
235
+ /** Text / foreground color (hex, named, or theme token like `"$colors.primary"`). */
236
+ color?: HexColor | StyleToken<string>;
237
+ /**
238
+ * Direct passthrough to the underlying `docx` library constructor options.
239
+ * Use for properties not yet covered by the CSS-like mapping.
240
+ */
241
+ docx?: Record<string, unknown>;
242
+ /** Double strikethrough toggle. */
243
+ doubleStrike?: boolean;
244
+ /** Embossed text effect. */
245
+ emboss?: boolean;
246
+ /**
247
+ * Font family name (e.g. `"Arial"`, or theme token like `"$fonts.heading"`).
248
+ */
249
+ fontFamily?: StyleToken<LiteralUnion$1<'Arial' | 'Calibri' | 'Times New Roman'>>;
250
+ /** Font size (bare number = pt). */
251
+ fontSize?: UnitValue;
252
+ /** Italic toggle (canonical form). Use `italic?: boolean` for convenience. */
253
+ fontStyle?: 'italic' | 'normal';
254
+ /** Font weight: keyword `"bold"` / `"normal"` or numeric 100–900. */
255
+ fontWeight?: FontWeight;
256
+ /** Text highlight color (background marker). */
257
+ highlight?: HighlightColor;
258
+ /** Imprinted (engraved) text effect. */
259
+ imprint?: boolean;
260
+ /**
261
+ * Convenience boolean: `true` maps to `fontStyle: 'italic'`.
262
+ * Takes precedence over `fontStyle` when both are set.
263
+ */
264
+ italic?: boolean;
265
+ /** CSS-like character spacing with unit conversion. */
266
+ letterSpacing?: UnitValue;
267
+ /** Right-to-left run direction. */
268
+ rightToLeft?: boolean;
269
+ /** Small caps text variant. */
270
+ smallCaps?: boolean;
271
+ /** Strikethrough toggle. */
272
+ strike?: boolean;
273
+ /** Sub-script text. */
274
+ subScript?: boolean;
275
+ /** Super-script text. */
276
+ superScript?: boolean;
277
+ /** Underline style. */
278
+ underline?: 'double' | 'single' | boolean;
279
+ }
280
+ /** Vertical alignment (for table cells). */
281
+ type VerticalAlign = 'bottom' | 'middle' | 'top';
282
+ //#endregion
283
+ //#region ../../packages/types/dist/dsl/nodes.d.ts
284
+ /**
285
+ * Common properties shared by all nodes.
286
+ *
287
+ * @template TStyles — The user's stylesheet type
288
+ */
289
+ interface BaseNode<TStyles extends StyleSheet = StyleSheet> {
290
+ /**
291
+ * CSS-like class name(s) referencing stylesheet entries.
292
+ *
293
+ * Can be a single string, an array, or a space-separated string.
294
+ */
295
+ className?: string | ClassName<TStyles> | ClassName<TStyles>[];
296
+ /** Optional unique identifier (for templating / references). */
297
+ id?: string;
298
+ /** Inline style override for this specific node. */
299
+ style?: DocxStyleRule;
300
+ }
301
+ /**
302
+ * Union of all top-level content node types.
303
+ *
304
+ * @template TStyles — The user's stylesheet type
305
+ */
306
+ type BlockNode<TStyles extends StyleSheet = StyleSheet> = BookmarkNode<TStyles> | BulletListNode<TStyles> | CheckboxNode<TStyles> | ColumnBreakNode | CommentNode<TStyles> | FootnoteNode<TStyles> | HeadingNode<TStyles> | HyperlinkNode<TStyles> | ImageNode<TStyles> | MathNode | NumberedListNode<TStyles> | PageBreakNode | ParagraphNode<TStyles> | PluginNode<string, unknown, TStyles> | RevisionNode<TStyles> | SectionBreakNode | TableNode<Record<string, unknown>, TStyles> | TextBoxNode<TStyles> | ThematicBreakNode<TStyles>;
307
+ /**
308
+ * A named bookmark that can be targeted by an internal hyperlink.
309
+ */
310
+ interface BookmarkNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
311
+ /** Text or styled text runs contained by the bookmark. */
312
+ children: (string | TextNode<TStyles>)[];
313
+ /** Stable bookmark name. */
314
+ name: string;
315
+ type: 'bookmark';
316
+ }
317
+ /**
318
+ * A structured list item (for rich bullet/numbered items).
319
+ *
320
+ * @template TStyles — The user's stylesheet type
321
+ */
322
+ interface BulletItem<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
323
+ /** Optional inline children override (instead of text). */
324
+ children?: InlineNode<TStyles>[];
325
+ /** Per-item nested list level (0–8). Overrides the list-level default. */
326
+ level?: number;
327
+ /** Item text content, used when `children` is absent. */
328
+ text?: string;
329
+ }
330
+ /**
331
+ * A bullet list node.
332
+ *
333
+ * Supports plain string items or structured items with children.
334
+ *
335
+ * @template TStyles — The user's stylesheet type
336
+ */
337
+ interface BulletListNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
338
+ /** List items — strings or structured items. */
339
+ items: (string | BulletItem<TStyles>)[];
340
+ type: 'bulletList';
341
+ /** Bullet character / style. Default: `'•'`. */
342
+ bullet?: string;
343
+ /** Nested list level (0 = top-level). */
344
+ level?: number;
345
+ }
346
+ /**
347
+ * A Word checkbox content control.
348
+ */
349
+ interface CheckboxNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
350
+ type: 'checkbox';
351
+ /** Accessible alias for the checkbox control. */
352
+ alias?: string;
353
+ /** Whether the checkbox is checked. */
354
+ checked?: boolean;
355
+ /** Checked-state glyph and font. */
356
+ checkedState?: CheckboxSymbol;
357
+ /** Optional label rendered after the checkbox. */
358
+ label?: string;
359
+ /** Unchecked-state glyph and font. */
360
+ uncheckedState?: CheckboxSymbol;
361
+ }
362
+ /** Checkbox glyph customization. */
363
+ interface CheckboxSymbol {
364
+ /** Font containing the glyph. */
365
+ font?: string;
366
+ /** Unicode code point expressed as a hexadecimal string. */
367
+ value?: string;
368
+ }
369
+ /**
370
+ * Extract valid class name keys from a stylesheet type.
371
+ *
372
+ * @template TStyles — The user's stylesheet type
373
+ */
374
+ type ClassName<TStyles extends StyleSheet> = Extract<keyof TStyles, string>;
375
+ /**
376
+ * A forced column break.
377
+ */
378
+ interface ColumnBreakNode {
379
+ type: 'columnBreak';
380
+ }
381
+ /**
382
+ * An annotated content range backed by a Word comment.
383
+ */
384
+ interface CommentNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
385
+ /** Comment author. */
386
+ author: string;
387
+ /** Annotated inline content. */
388
+ children: InlineNode<TStyles>[];
389
+ /** Comment body paragraphs or plain text. */
390
+ comment: (string | ParagraphNode<TStyles>)[];
391
+ type: 'comment';
392
+ /** ISO-8601 creation timestamp. */
393
+ date?: string;
394
+ /** Author initials. */
395
+ initials?: string;
396
+ }
397
+ /**
398
+ * A footnote reference and its document-level footnote content.
399
+ */
400
+ interface FootnoteNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
401
+ /** Footnote body paragraphs or plain text. */
402
+ content: (string | ParagraphNode<TStyles>)[];
403
+ type: 'footnote';
404
+ }
405
+ /**
406
+ * A heading node (h1–h6).
407
+ *
408
+ * @template TStyles — The user's stylesheet type
409
+ */
410
+ interface HeadingNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
411
+ /** Heading level (1 = largest, 6 = smallest). */
412
+ level: 1 | 2 | 3 | 4 | 5 | 6;
413
+ /** Heading text content. */
414
+ text: string;
415
+ type: 'heading';
416
+ }
417
+ /**
418
+ * A hyperlink node (inline content that creates a clickable link).
419
+ *
420
+ * @template TStyles — The user's stylesheet type
421
+ */
422
+ interface HyperlinkNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
423
+ /** Display text or inline children. */
424
+ children: (string | TextNode<TStyles>)[];
425
+ type: 'hyperlink';
426
+ /** Internal bookmark target (used instead of `url`). */
427
+ anchor?: string;
428
+ /** External link target URL. */
429
+ url?: string;
430
+ }
431
+ /**
432
+ * An image node.
433
+ *
434
+ * Supports raw bytes (`Uint8Array`, `ArrayBuffer`, `Blob`) or a file path string.
435
+ *
436
+ * @template TStyles — The user's stylesheet type
437
+ */
438
+ interface ImageNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
439
+ /** Image data as bytes, blob, or file path. */
440
+ data: string | ArrayBuffer | Blob | Uint8Array;
441
+ type: 'image';
442
+ /** Alt text for accessibility. */
443
+ alt?: string;
444
+ /** Display height. */
445
+ height?: UnitValue;
446
+ /** Image format hint. Auto-detected if omitted. */
447
+ imageType?: 'bmp' | 'gif' | 'jpeg' | 'jpg' | 'png';
448
+ /** Display width. */
449
+ width?: UnitValue;
450
+ /**
451
+ * Floating layout configuration.
452
+ *
453
+ * - `true` enables default floating
454
+ * - Object allows wrap mode and position offsets
455
+ */
456
+ floating?: boolean | {
457
+ /** Text wrap mode. */
458
+ wrap?: 'square' | 'tight' | 'topAndBottom';
459
+ /** Horizontal offset. */
460
+ x?: UnitValue;
461
+ /** Vertical offset. */
462
+ y?: UnitValue;
463
+ };
464
+ }
465
+ /**
466
+ * Union of inline content node types (appear inside paragraphs).
467
+ *
468
+ * @template TStyles — The user's stylesheet type
469
+ */
470
+ type InlineNode<TStyles extends StyleSheet = StyleSheet> = BookmarkNode<TStyles> | CheckboxNode<TStyles> | CommentNode<TStyles> | FootnoteNode<TStyles> | HyperlinkNode<TStyles> | ImageNode<TStyles> | MathNode | RevisionNode<TStyles> | TextNode<TStyles>;
471
+ /**
472
+ * A recursive expression used by {@link MathNode}.
473
+ */
474
+ type MathExpression = MathFractionExpression | MathFunctionExpression | MathIntegralExpression | MathRadicalExpression | MathScriptExpression | MathSumExpression | MathTextExpression;
475
+ /** A mathematical fraction. */
476
+ interface MathFractionExpression {
477
+ denominator: MathExpression[];
478
+ numerator: MathExpression[];
479
+ type: 'fraction';
480
+ }
481
+ /** A named mathematical function. */
482
+ interface MathFunctionExpression {
483
+ arguments: MathExpression[];
484
+ name: MathExpression[];
485
+ type: 'function';
486
+ }
487
+ /** A mathematical integral. */
488
+ interface MathIntegralExpression {
489
+ children: MathExpression[];
490
+ type: 'integral';
491
+ subScript?: MathExpression[];
492
+ superScript?: MathExpression[];
493
+ }
494
+ /**
495
+ * An Office Math (OMML) expression.
496
+ */
497
+ interface MathNode {
498
+ /** Structured mathematical expression tree. */
499
+ children: MathExpression[];
500
+ type: 'math';
501
+ }
502
+ /** A mathematical radical with an optional degree. */
503
+ interface MathRadicalExpression {
504
+ children: MathExpression[];
505
+ type: 'radical';
506
+ degree?: MathExpression[];
507
+ }
508
+ /** Subscript, superscript, or combined script. */
509
+ interface MathScriptExpression {
510
+ children: MathExpression[];
511
+ type: 'script';
512
+ subScript?: MathExpression[];
513
+ superScript?: MathExpression[];
514
+ }
515
+ /** A mathematical sum. */
516
+ interface MathSumExpression {
517
+ children: MathExpression[];
518
+ type: 'sum';
519
+ subScript?: MathExpression[];
520
+ superScript?: MathExpression[];
521
+ }
522
+ /** Plain text inside a mathematical expression. */
523
+ interface MathTextExpression {
524
+ text: string;
525
+ type: 'text';
526
+ }
527
+ /**
528
+ * A numbered / ordered list node.
529
+ *
530
+ * @template TStyles — The user's stylesheet type
531
+ */
532
+ interface NumberedListNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
533
+ /** List items. */
534
+ items: (string | BulletItem<TStyles>)[];
535
+ type: 'numberedList';
536
+ /** Nested list level (0 = top-level). */
537
+ level?: number;
538
+ /** Starting number (default: 1). */
539
+ start?: number;
540
+ /**
541
+ * Numbering format.
542
+ *
543
+ * {@link `LevelFormat.DECIMAL`} by default.
544
+ * e.g. `'decimal'`, `'upperRoman'`, `'lowerLetter'`
545
+ */
546
+ numberingFormat?: 'decimal' | 'lowerLetter' | 'lowerRoman' | 'upperLetter' | 'upperRoman';
547
+ }
548
+ /**
549
+ * A forced page break.
550
+ */
551
+ interface PageBreakNode {
552
+ type: 'pageBreak';
553
+ }
554
+ /**
555
+ * A paragraph containing text and/or inline children.
556
+ *
557
+ * @template TStyles — The user's stylesheet type
558
+ */
559
+ interface ParagraphNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
560
+ type: 'paragraph';
561
+ /** Inline children (text runs, inline images, etc.). */
562
+ children?: InlineNode<TStyles>[];
563
+ /** Plain-text content (used when `children` is not provided). */
564
+ text?: string;
565
+ }
566
+ /**
567
+ * A plugin-invocation node.
568
+ *
569
+ * Plugins extend the DSL with arbitrary content types.
570
+ *
571
+ * @template TName — Plugin name (string literal)
572
+ * @template TOptions — Plugin-specific options shape
573
+ * @template TStyles — The user's stylesheet type
574
+ */
575
+ interface PluginNode<TName extends string = string, TOptions = unknown, TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
576
+ /** Registered plugin name. */
577
+ name: TName;
578
+ /** Plugin-specific options. */
579
+ options: TOptions;
580
+ type: 'plugin';
581
+ }
582
+ /**
583
+ * An inserted or deleted text revision.
584
+ */
585
+ interface RevisionNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
586
+ /** Revision author. */
587
+ author: string;
588
+ /** Text or styled text runs in the revision. */
589
+ children: (string | TextNode<TStyles>)[];
590
+ /** ISO-8601 revision timestamp. */
591
+ date: string;
592
+ /** Document-unique revision identifier. */
593
+ revisionId: number;
594
+ /** Revision kind. */
595
+ type: 'deletedText' | 'insertedText';
596
+ }
597
+ /**
598
+ * Internal marker node that represents a section boundary.
599
+ *
600
+ * Created automatically by {@link DocxBuilder.section} — users should
601
+ * not create this node directly.
602
+ *
603
+ * When the compiler encounters this marker, it starts a new section
604
+ * with the provided configuration.
605
+ */
606
+ interface SectionBreakNode {
607
+ type: 'sectionBreak';
608
+ /** Optional per-section page/header/footer overrides. */
609
+ config?: SectionConfig;
610
+ }
611
+ /** Table-level border configuration. */
612
+ interface TableBordersConfig {
613
+ bottom?: BorderRule;
614
+ insideHorizontal?: BorderRule;
615
+ insideVertical?: BorderRule;
616
+ left?: BorderRule;
617
+ right?: BorderRule;
618
+ top?: BorderRule;
619
+ }
620
+ /** Per-cell style resolver. */
621
+ type TableCellStyleResolver<TData extends Record<string, unknown> = Record<string, unknown>> = (value: TData[keyof TData], row: TData, rowIndex: number, column: TableColumn<TData>) => DocxStyleRule;
622
+ /**
623
+ * A column definition for a table.
624
+ *
625
+ * @template TData — The row data type
626
+ */
627
+ interface TableColumn<TData extends Record<string, unknown> = Record<string, unknown>> {
628
+ /** Key in the data object this column maps to. */
629
+ key: Extract<keyof TData, string>;
630
+ /** Column header text. */
631
+ title: string;
632
+ /** Cell text alignment. */
633
+ align?: 'center' | 'left' | 'right';
634
+ /** Per-column data cell style or resolver. */
635
+ cellStyle?: DocxStyleRule | TableCellStyleResolver<TData>;
636
+ /**
637
+ * Span multiple columns horizontally.
638
+ *
639
+ * Applied to all cells in this column.
640
+ */
641
+ colSpan?: number;
642
+ /** Per-column header cell style. */
643
+ headerCellStyle?: DocxStyleRule;
644
+ /**
645
+ * Span multiple rows vertically (per-cell via data hints).
646
+ *
647
+ * Set a keyed `_${key}_rowSpan: N` hint on an individual data object,
648
+ * use `_rowSpan: N` for every cell in that row, or keep this as a static
649
+ * column default.
650
+ */
651
+ rowSpan?: number;
652
+ /** Column width. Supports percentage strings (e.g. `"30%"`). */
653
+ width?: UnitValue;
654
+ /**
655
+ * Custom cell renderer.
656
+ *
657
+ * Receives the raw value, full row data, and row index.
658
+ * Returns a string or inline nodes.
659
+ */
660
+ render?: (value: TData[keyof TData], row: TData, index: number) => string | InlineNode[];
661
+ }
662
+ /** Floating table positioning. */
663
+ interface TableFloatingOptions {
664
+ /** Bottom distance from surrounding text. */
665
+ bottomFromText?: UnitValue;
666
+ /** Horizontal anchor. */
667
+ horizontalAnchor?: 'margin' | 'page' | 'text';
668
+ /** Left distance from surrounding text. */
669
+ leftFromText?: UnitValue;
670
+ /** Whether the table may overlap other floating objects. */
671
+ overlap?: boolean;
672
+ /** Right distance from surrounding text. */
673
+ rightFromText?: UnitValue;
674
+ /** Top distance from surrounding text. */
675
+ topFromText?: UnitValue;
676
+ /** Vertical anchor. */
677
+ verticalAnchor?: 'margin' | 'page' | 'text';
678
+ /** Absolute horizontal offset. */
679
+ x?: UnitValue;
680
+ /** Absolute vertical offset. */
681
+ y?: UnitValue;
682
+ /** Relative horizontal placement. */
683
+ relativeHorizontalPosition?: 'center' | 'inside' | 'left' | 'outside' | 'right';
684
+ /** Relative vertical placement. */
685
+ relativeVerticalPosition?: 'bottom' | 'center' | 'inline' | 'inside' | 'outside' | 'top';
686
+ }
687
+ /** Native Word table-look flags. */
688
+ interface TableLookOptions {
689
+ firstColumn?: boolean;
690
+ firstRow?: boolean;
691
+ lastColumn?: boolean;
692
+ lastRow?: boolean;
693
+ noHBand?: boolean;
694
+ noVBand?: boolean;
695
+ }
696
+ /**
697
+ * A table node with column definitions and data rows.
698
+ *
699
+ * @template TData — The row data type
700
+ * @template TStyles — The user's stylesheet type
701
+ */
702
+ interface TableNode<TData extends Record<string, unknown> = Record<string, unknown>, TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
703
+ /** Column definitions. */
704
+ columns: TableColumn<TData>[];
705
+ /** Row data objects. */
706
+ data: TData[];
707
+ type: 'table';
708
+ /** Horizontal table alignment. */
709
+ alignment?: 'center' | 'left' | 'right';
710
+ /** Show table borders. */
711
+ bordered?: boolean;
712
+ /** Explicit outer and inner table borders. */
713
+ borders?: TableBordersConfig;
714
+ /** Default data cell style or per-cell resolver. */
715
+ cellStyle?: DocxStyleRule | TableCellStyleResolver<TData>;
716
+ /** Floating table positioning. Enables side-by-side layouts. */
717
+ floating?: TableFloatingOptions;
718
+ /** Show header row (default: `true`). */
719
+ header?: boolean;
720
+ /** Style for header cells. */
721
+ headerCellStyle?: DocxStyleRule;
722
+ /** Word table layout algorithm. */
723
+ layout?: 'autofit' | 'fixed';
724
+ /** Alternate row shading. */
725
+ striped?: boolean;
726
+ /** Native Word table style ID. */
727
+ styleName?: string;
728
+ /** Native Word table-look flags. */
729
+ tableLook?: TableLookOptions;
730
+ /** Render the table grid from right to left. */
731
+ visuallyRightToLeft?: boolean;
732
+ /** Overall table width. */
733
+ width?: UnitValue;
734
+ }
735
+ /**
736
+ * A legacy Word text box positioned as a block-level shape.
737
+ */
738
+ interface TextBoxNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
739
+ /** Text box dimensions and positioning. */
740
+ box: TextBoxOptions;
741
+ type: 'textBox';
742
+ /** Inline children (used instead of `text`). */
743
+ children?: InlineNode<TStyles>[];
744
+ /** Plain text content. */
745
+ text?: string;
746
+ }
747
+ /** Text box dimensions and positioning. */
748
+ interface TextBoxOptions {
749
+ /** Text box width. */
750
+ width: UnitValue;
751
+ /** Text box height. */
752
+ height?: UnitValue;
753
+ /** Horizontal offset. */
754
+ left?: UnitValue;
755
+ /** Shape positioning mode. */
756
+ position?: 'absolute' | 'relative' | 'static';
757
+ /** Vertical offset. */
758
+ top?: UnitValue;
759
+ /** Text wrapping behavior. */
760
+ wrap?: 'none' | 'square';
761
+ }
762
+ /**
763
+ * A text run node (inline content).
764
+ *
765
+ * @template TStyles — The user's stylesheet type
766
+ */
767
+ interface TextNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
768
+ /** Text content. */
769
+ text: string;
770
+ type: 'text';
771
+ }
772
+ /**
773
+ * A horizontal thematic break rendered as a paragraph border.
774
+ */
775
+ interface ThematicBreakNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
776
+ type: 'thematicBreak';
777
+ }
778
+ //#endregion
779
+ //#region ../../packages/types/dist/document.d.ts
780
+ /** OOXML document properties shown in Word's File → Info panel. */
781
+ interface DocumentMetadata {
782
+ /** Document author. */
783
+ creator?: string;
784
+ /** Application-specific string properties. */
785
+ customProperties?: Record<string, string>;
786
+ /** Document description / summary. */
787
+ description?: string;
788
+ /** Keywords / tags. */
789
+ keywords?: string[];
790
+ /** Last editor. */
791
+ lastModifiedBy?: string;
792
+ /** Document subject. */
793
+ subject?: string;
794
+ /** Document title. */
795
+ title?: string;
796
+ }
797
+ /**
798
+ * Top-level configuration passed to `createDocx()`.
799
+ *
800
+ * Covers page setup, stylesheet, theme tokens, element defaults,
801
+ * and document metadata.
802
+ *
803
+ * @template TStyles — The user's stylesheet type (inferred from `styles`).
804
+ */
805
+ interface DocxKitConfig<TStyles extends StyleSheet = StyleSheet> {
806
+ /** Font files embedded into the generated DOCX package. */
807
+ fonts?: EmbeddedFont[];
808
+ /** OOXML core properties (appear in File → Info). */
809
+ metadata?: DocumentMetadata;
810
+ /** Page dimensions and margins. */
811
+ page?: PageConfig;
812
+ /** Named style classes (class → style rule map). */
813
+ styles?: TStyles;
814
+ /** Semantic design tokens for theming. */
815
+ theme?: DocxTheme;
816
+ /** Default styles applied as base for each element type. */
817
+ defaults?: {
818
+ /** Default table cell style. */
819
+ cell?: DocxStyleRule;
820
+ /** Default image style (applied to the paragraph wrapping the image). */
821
+ image?: DocxStyleRule;
822
+ /** Default paragraph style. */
823
+ paragraph?: DocxStyleRule;
824
+ /** Default table style. */
825
+ table?: DocxStyleRule;
826
+ /** Default text run style. */
827
+ text?: DocxStyleRule;
828
+ };
829
+ /** Document-level Word feature switches. */
830
+ features?: {
831
+ /** Enable tracked revision display and behavior. */
832
+ trackRevisions?: boolean;
833
+ /** Ask Word to update fields when the document opens. */
834
+ updateFields?: boolean;
835
+ };
836
+ }
837
+ /**
838
+ * Theme tokens that can be referenced in styles via `$category.key` syntax.
839
+ *
840
+ * Allows defining a single source of truth for colors, fonts,
841
+ * font sizes, and spacing values. Token references are resolved
842
+ * at compile time by {@link resolveThemeTokens}.
843
+ */
844
+ interface DocxTheme {
845
+ /** Color palette tokens (name → hex). */
846
+ colors?: ThemeColors;
847
+ /** Font family tokens (name → font family string). */
848
+ fonts?: ThemeFonts;
849
+ /** Font size tokens (name → value). */
850
+ fontSize?: Record<string, UnitValue>;
851
+ /** Spacing tokens (name → value). */
852
+ spacing?: ThemeSpacing;
853
+ }
854
+ /** A TrueType/OpenType font embedded into the DOCX package. */
855
+ interface EmbeddedFont {
856
+ /** Raw font-file bytes. */
857
+ data: Uint8Array;
858
+ /** Font family name written to the OOXML font table. */
859
+ name: string;
860
+ }
861
+ /**
862
+ * Header/footer configuration for a section.
863
+ *
864
+ * Supports standard, first-page, and even-page variants.
865
+ */
866
+ interface HeaderFooterConfig {
867
+ /** Default header/footer (appears on all pages). */
868
+ default?: HeaderFooterContent;
869
+ /** Even-page header/footer (overrides default on even pages). */
870
+ even?: HeaderFooterContent;
871
+ /** First-page-only header/footer (overrides default on page 1). */
872
+ first?: HeaderFooterContent;
873
+ }
874
+ /**
875
+ * Content for a header or footer.
876
+ *
877
+ * Supports both simple text strings (backward compatible, each maps to a `Paragraph`)
878
+ * and full {@link BlockNode} elements (paragraphs, images, tables, etc.).
879
+ */
880
+ interface HeaderFooterContent {
881
+ /** Content items — strings (simple) or BlockNode objects (rich). */
882
+ children: (string | BlockNode)[];
883
+ }
884
+ /** Page orientation. */
885
+ type Orientation = 'landscape' | 'portrait';
886
+ /** Page border configuration. */
887
+ interface PageBorderConfig {
888
+ /** Bottom page border. */
889
+ bottom?: BorderRule;
890
+ /** Pages that display the border. */
891
+ display?: 'allPages' | 'firstPage' | 'notFirstPage';
892
+ /** Left page border. */
893
+ left?: BorderRule;
894
+ /** Measure border offsets from the page edge or text area. */
895
+ offsetFrom?: 'page' | 'text';
896
+ /** Right page border. */
897
+ right?: BorderRule;
898
+ /** Top page border. */
899
+ top?: BorderRule;
900
+ /** Render the border behind or in front of document content. */
901
+ zOrder?: 'back' | 'front';
902
+ }
903
+ /**
904
+ * Page configuration (size, orientation, margin).
905
+ */
906
+ interface PageConfig {
907
+ /** Page border configuration. */
908
+ borders?: PageBorderConfig;
909
+ /** Distance between the footer and the page edge. */
910
+ footerDistance?: UnitValue;
911
+ /** Extra gutter width for binding. */
912
+ gutter?: UnitValue;
913
+ /** Distance between the header and the page edge. */
914
+ headerDistance?: UnitValue;
915
+ /** Page orientation (`"portrait"` default). */
916
+ orientation?: Orientation;
917
+ /** Page-number sequence configuration for this section. */
918
+ pageNumber?: PageNumberConfig;
919
+ /** Page size: preset name or explicit dimensions. */
920
+ size?: PageSize | {
921
+ height: UnitValue;
922
+ width: UnitValue;
923
+ };
924
+ /**
925
+ * Page margin.
926
+ *
927
+ * Supports 1-value, 2-value, and 4-value shorthand
928
+ * (e.g. `"20mm"`, `"20mm 15mm"`, `"20mm 15mm 25mm 15mm"`).
929
+ */
930
+ margin?: `${string} ${string}` | `${string} ${string} ${string} ${string}` | UnitValue;
931
+ }
932
+ /** Per-section page-number sequence configuration. */
933
+ interface PageNumberConfig {
934
+ /** First page number in the section. */
935
+ start?: number;
936
+ /** Page number format. */
937
+ format?: 'decimal' | 'lowerLetter' | 'lowerRoman' | 'upperLetter' | 'upperRoman';
938
+ }
939
+ /** Available page size presets. */
940
+ type PageSize = 'A3' | 'A4' | 'Legal' | 'Letter';
941
+ /** An explicitly sized section column. */
942
+ interface SectionColumn {
943
+ /** Column width. */
944
+ width: UnitValue;
945
+ /** Space after this column. */
946
+ spacing?: UnitValue;
947
+ }
948
+ /** Multi-column layout for a section. */
949
+ interface SectionColumnsConfig {
950
+ /** Explicit column widths for unequal-width layouts. */
951
+ columns?: SectionColumn[];
952
+ /** Number of equal-width columns. */
953
+ count?: number;
954
+ /** Whether Word should keep columns equally sized. */
955
+ equalWidth?: boolean;
956
+ /** Draw a separator line between columns. */
957
+ separator?: boolean;
958
+ /** Default spacing between columns. */
959
+ spacing?: UnitValue;
960
+ }
961
+ /**
962
+ * Per-section configuration.
963
+ *
964
+ * Each call to `.section(config)` starts a new document section, which
965
+ * can have its own page setup, headers, and footers independent of other
966
+ * sections.
967
+ */
968
+ interface SectionConfig {
969
+ /** Multi-column layout. */
970
+ columns?: SectionColumnsConfig;
971
+ /** Section footer(s). */
972
+ footer?: HeaderFooterConfig;
973
+ /** Section header(s). */
974
+ header?: HeaderFooterConfig;
975
+ /** Line numbering. */
976
+ lineNumbers?: SectionLineNumberConfig;
977
+ /** Section-specific page dimensions (overrides document-level `page`). */
978
+ page?: PageConfig;
979
+ /** Section break behavior. */
980
+ type?: SectionType;
981
+ }
982
+ /** Line-numbering configuration for a section. */
983
+ interface SectionLineNumberConfig {
984
+ /** Number every Nth line. */
985
+ countBy?: number;
986
+ /** Distance between line numbers and text. */
987
+ distance?: UnitValue;
988
+ /** When line numbering restarts. */
989
+ restart?: 'continuous' | 'newPage' | 'newSection';
990
+ /** Starting line number. */
991
+ start?: number;
992
+ }
993
+ /** Section break behavior. */
994
+ type SectionType = 'continuous' | 'evenPage' | 'nextColumn' | 'nextPage' | 'oddPage';
995
+ /**
996
+ * Theme color palette — semantic color tokens referenced by name.
997
+ */
998
+ interface ThemeColors {
999
+ [name: string]: string;
1000
+ }
1001
+ /**
1002
+ * Theme font tokens — semantic font family names.
1003
+ */
1004
+ interface ThemeFonts {
1005
+ [name: string]: string;
1006
+ }
1007
+ /**
1008
+ * Theme spacing tokens — named spacing values.
1009
+ */
1010
+ interface ThemeSpacing {
1011
+ [name: string]: UnitValue;
1012
+ }
1013
+ //#endregion
1014
+ //#region ../../packages/types/dist/plugin.d.ts
1015
+ /**
1016
+ * A docx-kit plugin.
1017
+ *
1018
+ * Plugins have a unique `name`, an optional `setup` hook,
1019
+ * and a required `render` function that receives user options
1020
+ * and a rendering context.
1021
+ *
1022
+ * @template TName — The plugin name (string literal type)
1023
+ * @template TOptions — The shape of the user-provided options
1024
+ * @template TRender — The render output type produced by the plugin
1025
+ */
1026
+ interface DocxPlugin<TName extends string = string, TOptions = unknown, TRender = unknown> {
1027
+ /** Unique plugin name, used as the node discriminator. */
1028
+ name: TName;
1029
+ /** One-time setup called when the plugin is registered. */
1030
+ setup?: () => MaybePromise<void>;
1031
+ /**
1032
+ * Render plugin content into one or more `docx` objects
1033
+ * (Paragraph, Table, etc.).
1034
+ *
1035
+ * @param options - — User-provided plugin options
1036
+ * @param context - — Rendering context with helper utilities
1037
+ */
1038
+ render: (options: TOptions, context: PluginRenderContext) => MaybePromise<TRender>;
1039
+ }
1040
+ /**
1041
+ * Rendering context passed to a plugin's `render()` function.
1042
+ *
1043
+ * Provides access to the document config, image utilities,
1044
+ * and the ability to compile child nodes.
1045
+ */
1046
+ interface PluginRenderContext {
1047
+ /** The full document config. */
1048
+ config: DocxKitConfig;
1049
+ /** Compile a child node (useful for nesting). */
1050
+ compileNode: (node: BlockNode) => Promise<unknown>;
1051
+ /** Utility helpers. */
1052
+ utils: {
1053
+ image: {
1054
+ /**
1055
+ * Convert a Blob to raw image bytes.
1056
+ *
1057
+ * @param blob - The image data as a Blob
1058
+ * @returns A promise that resolves to a Uint8Array of the image bytes
1059
+ */
1060
+ fromBlob: (blob: Blob) => Promise<Uint8Array>;
1061
+ /**
1062
+ * Decode a base64 data-URL to raw image bytes.
1063
+ * Works in both browser and Node.js environments.
1064
+ */
1065
+ fromDataUrl: (dataUrl: string) => MaybePromise<Uint8Array>;
1066
+ };
1067
+ };
1068
+ }
1069
+ //#endregion
1070
+ //#region src/index.d.ts
1071
+ /** Common linear barcode formats, while retaining the full bwip-js catalog. */
1072
+ type BarcodeFormat = LiteralUnion<'code128' | 'code39' | 'code93' | 'ean13' | 'ean8' | 'interleaved2of5' | 'isbn' | 'itf14' | 'upca' | 'upce'>;
1073
+ /** Options for the barcode plugin. */
1074
+ interface BarcodeOptions {
1075
+ /** Value encoded by the barcode. */
1076
+ text: string;
1077
+ /** Paragraph alignment. @default "center" */
1078
+ alignment?: 'center' | 'left' | 'right';
1079
+ /** Background color as a hex string. @default "#FFFFFF" */
1080
+ backgroundColor?: string;
1081
+ /** Bar color as a hex string. @default "#000000" */
1082
+ barColor?: string;
1083
+ /** Bar height in millimeters. @default 12 */
1084
+ barHeight?: number;
1085
+ /** Optional caption below the barcode. */
1086
+ caption?: string;
1087
+ /** Barcode symbology. @default "code128" */
1088
+ format?: BarcodeFormat;
1089
+ /** Include the human-readable value below the bars. @default true */
1090
+ includeText?: boolean;
1091
+ /** Barcode rotation. @default "N" */
1092
+ rotate?: 'I' | 'L' | 'N' | 'R';
1093
+ /** Rasterization scale. @default 3 */
1094
+ scale?: number;
1095
+ /** Human-readable text color as a hex string. */
1096
+ textColor?: string;
1097
+ /** Display width in pixels. Defaults to the natural width, capped at 320. */
1098
+ width?: number;
1099
+ }
1100
+ /**
1101
+ * Create a barcode plugin instance.
1102
+ *
1103
+ * @returns A configured plugin for the `barcode` node name
1104
+ */
1105
+ declare function barcodePlugin(): DocxPlugin<"barcode", BarcodeOptions, unknown>;
1106
+ //#endregion
1107
+ export { BarcodeFormat, BarcodeOptions, barcodePlugin };
package/dist/index.js ADDED
@@ -0,0 +1,100 @@
1
+ import { createImageRun, dataUrlToUint8Array, definePlugin } from "@docxkit/core";
2
+ import { AlignmentType, Paragraph } from "docx";
3
+ //#region src/index.ts
4
+ /**
5
+ * Barcode plugin — embeds a linear barcode image in the document.
6
+ *
7
+ * Uses the optional `bwip-js` peer dependency and selects its Node.js or
8
+ * browser PNG renderer at runtime.
9
+ *
10
+ * @module plugins/barcode
11
+ */
12
+ /**
13
+ * Create a barcode plugin instance.
14
+ *
15
+ * @returns A configured plugin for the `barcode` node name
16
+ */
17
+ function barcodePlugin() {
18
+ return definePlugin({
19
+ name: "barcode",
20
+ async render(options) {
21
+ const rendered = await renderBarcode(options);
22
+ const width = options.width ?? Math.min(rendered.width, 320);
23
+ const height = Math.max(1, Math.round(rendered.height * (width / rendered.width)));
24
+ const alignment = toAlignment(options.alignment);
25
+ const paragraphs = [new Paragraph({
26
+ alignment,
27
+ children: [createImageRun({
28
+ data: rendered.data,
29
+ height,
30
+ type: "png",
31
+ width
32
+ })]
33
+ })];
34
+ if (options.caption) paragraphs.push(new Paragraph({
35
+ alignment,
36
+ text: options.caption
37
+ }));
38
+ return paragraphs;
39
+ }
40
+ });
41
+ }
42
+ async function loadBarcodeRenderer() {
43
+ try {
44
+ const module = await import("bwip-js");
45
+ return module.default ?? module;
46
+ } catch (err) {
47
+ throw new Error("The barcode plugin requires the optional \"bwip-js\" package. Install it before rendering barcodes.", { cause: err });
48
+ }
49
+ }
50
+ function normalizeColor(color) {
51
+ return color.replace(/^#/, "");
52
+ }
53
+ function readPngDimensions(data) {
54
+ if (!(data.length >= 24 && data[0] === 137 && data[1] === 80 && data[2] === 78 && data[3] === 71)) throw new Error("bwip-js did not return a valid PNG barcode image.");
55
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
56
+ return {
57
+ height: view.getUint32(20),
58
+ width: view.getUint32(16)
59
+ };
60
+ }
61
+ async function renderBarcode(options) {
62
+ const renderer = await loadBarcodeRenderer();
63
+ const renderOptions = {
64
+ backgroundcolor: normalizeColor(options.backgroundColor ?? "#FFFFFF"),
65
+ barcolor: normalizeColor(options.barColor ?? "#000000"),
66
+ bcid: options.format ?? "code128",
67
+ height: options.barHeight ?? 12,
68
+ includetext: options.includeText ?? true,
69
+ rotate: options.rotate ?? "N",
70
+ scale: options.scale ?? 3,
71
+ text: options.text,
72
+ textxalign: "center",
73
+ ...options.textColor ? { textcolor: normalizeColor(options.textColor) } : {}
74
+ };
75
+ if (renderer.toBuffer) {
76
+ const data = new Uint8Array(await renderer.toBuffer(renderOptions));
77
+ return {
78
+ data,
79
+ ...readPngDimensions(data)
80
+ };
81
+ }
82
+ if (renderer.toCanvas && typeof document !== "undefined") {
83
+ const canvas = renderer.toCanvas(document.createElement("canvas"), renderOptions);
84
+ return {
85
+ data: await dataUrlToUint8Array(canvas.toDataURL("image/png")),
86
+ height: canvas.height,
87
+ width: canvas.width
88
+ };
89
+ }
90
+ throw new Error("No compatible bwip-js PNG renderer is available.");
91
+ }
92
+ function toAlignment(alignment) {
93
+ switch (alignment) {
94
+ case "left": return AlignmentType.LEFT;
95
+ case "right": return AlignmentType.RIGHT;
96
+ default: return AlignmentType.CENTER;
97
+ }
98
+ }
99
+ //#endregion
100
+ export { barcodePlugin };
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@docxkit/plugin-barcode",
3
+ "type": "module",
4
+ "version": "0.4.0",
5
+ "description": "Linear barcode generation — docx-kit plugin",
6
+ "keywords": [
7
+ "barcode",
8
+ "docx",
9
+ "docx-kit",
10
+ "docx-kit-plugin"
11
+ ],
12
+ "license": "MIT",
13
+ "author": {
14
+ "name": "ntnyq",
15
+ "email": "ntnyq13@gmail.com"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/ntnyq/docx-kit",
20
+ "directory": "packages-plugins/barcode"
21
+ },
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ }
27
+ },
28
+ "main": "./dist/index.js",
29
+ "types": "./dist/index.d.ts",
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "sideEffects": false,
37
+ "peerDependencies": {
38
+ "bwip-js": ">=4.10.0",
39
+ "docx": "^9.7.1",
40
+ "@docxkit/core": "0.4.0"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "bwip-js": {
44
+ "optional": true
45
+ }
46
+ },
47
+ "devDependencies": {
48
+ "jszip": "^3.10.1",
49
+ "@docxkit/pdk": "0.4.0"
50
+ },
51
+ "scripts": {
52
+ "build": "tsdown",
53
+ "dev": "tsdown --watch"
54
+ }
55
+ }