docx-kit 0.0.0 → 0.1.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/dist/index.d.ts CHANGED
@@ -1,5 +1,1032 @@
1
- //#region src/index.d.ts
2
- declare const msg = "hello world";
3
- declare function greet(): string;
1
+ import { EChartsOption } from "echarts";
2
+
3
+ //#region src/types/utility.d.ts
4
+ /** Hexadecimal CSS color string, e.g. `"#ff0000"`. */
5
+ type HexColor = `#${string}`;
6
+ /**
7
+ * A literal union type that still allows arbitrary string values.
8
+ * Useful for autocomplete-friendly APIs with extensible values.
9
+ *
10
+ * @template T — The literal subtype (e.g. `'Arial' | 'Calibri'`)
11
+ * @template U — The base type, defaults to `string`
12
+ */
13
+ type LiteralUnion<T extends U, U = string> = T | (U & {});
14
+ /**
15
+ * A value that might be synchronous or wrapped in a Promise.
16
+ *
17
+ * @template T — The inner value type
18
+ */
19
+ type MaybePromise<T> = Promise<T> | T;
20
+ /**
21
+ * CSS-like length value.
22
+ *
23
+ * Supports bare numbers, and explicit unit strings:
24
+ * `%`, `cm`, `in`, `mm`, `pt`, `px`.
25
+ *
26
+ * Bare-number conventions vary by context:
27
+ * - `fontSize` → interpreted as `pt`
28
+ * - spacing / indent → interpreted as `pt`
29
+ * - image size → interpreted as `px`
30
+ */
31
+ type UnitValue = `${number}%` | `${number}cm` | `${number}in` | `${number}mm` | `${number}pt` | `${number}px` | number;
4
32
  //#endregion
5
- export { greet, msg };
33
+ //#region src/types/style.d.ts
34
+ /**
35
+ * A single border side descriptor.
36
+ *
37
+ * Follows the CSS `border` shorthand convention (style, width, color).
38
+ */
39
+ interface BorderRule {
40
+ /** Border color (e.g. `"#333"` or named color). */
41
+ color?: string | HexColor;
42
+ /** Line style. */
43
+ style?: BorderStyle;
44
+ /** Line width (bare number treated as pt). */
45
+ width?: UnitValue;
46
+ }
47
+ /** Available border line styles. */
48
+ type BorderStyle = 'dashed' | 'dotted' | 'double' | 'none' | 'single';
49
+ /**
50
+ * CSS-like style descriptor for a run, paragraph, cell, or table.
51
+ *
52
+ * Keys mirror familiar CSS property names. Unknown properties that don't
53
+ * map to Word XML are silently ignored.
54
+ */
55
+ interface DocxStyleRule {
56
+ /** Force text to uppercase (small caps-like). */
57
+ allCaps?: boolean;
58
+ /** Background / shading color. */
59
+ backgroundColor?: string | HexColor;
60
+ /** Shorthand border for all four sides. */
61
+ border?: BorderRule;
62
+ /** Bottom border override. */
63
+ borderBottom?: BorderRule;
64
+ /** Left border override. */
65
+ borderLeft?: BorderRule;
66
+ /** Right border override. */
67
+ borderRight?: BorderRule;
68
+ /** Top border override. */
69
+ borderTop?: BorderRule;
70
+ /** Text / foreground color. */
71
+ color?: string | HexColor;
72
+ /**
73
+ * Direct passthrough to the underlying `docx` library constructor options.
74
+ * Use for properties not yet covered by the CSS-like mapping.
75
+ */
76
+ docx?: Record<string, unknown>;
77
+ /** Font family name. */
78
+ fontFamily?: LiteralUnion<'Arial' | 'Calibri' | 'Times New Roman'>;
79
+ /** Font size (bare number = pt). */
80
+ fontSize?: UnitValue;
81
+ /** Italic toggle. */
82
+ fontStyle?: 'italic' | 'normal';
83
+ /** Font weight: keyword `"bold"` / `"normal"` or numeric 100–900. */
84
+ fontWeight?: FontWeight;
85
+ /** Element height. */
86
+ height?: UnitValue;
87
+ /** Character spacing. */
88
+ letterSpacing?: UnitValue;
89
+ /** Line height multiplier or explicit unit value. */
90
+ lineHeight?: number | UnitValue;
91
+ /** Bottom margin. */
92
+ marginBottom?: UnitValue;
93
+ /** Left margin. */
94
+ marginLeft?: UnitValue;
95
+ /** Right margin. */
96
+ marginRight?: UnitValue;
97
+ /** Top margin. */
98
+ marginTop?: UnitValue;
99
+ /** Strikethrough toggle. */
100
+ strike?: boolean;
101
+ /** Horizontal text alignment. */
102
+ textAlign?: TextAlign;
103
+ /** First-line indent. */
104
+ textIndent?: UnitValue;
105
+ /** Underline style. */
106
+ underline?: 'double' | 'single' | boolean;
107
+ /** Vertical alignment (mostly for table cells). */
108
+ verticalAlign?: VerticalAlign;
109
+ /** Element width. */
110
+ width?: UnitValue;
111
+ /**
112
+ * CSS-like margin shorthand.
113
+ *
114
+ * Supports 1-value, 2-value, and 4-value string syntax
115
+ * (e.g. `"10pt"`, `"10pt 20pt"`, `"10pt 20pt 30pt 40pt"`).
116
+ */
117
+ margin?: `${string} ${string}` | `${string} ${string} ${string} ${string}` | UnitValue;
118
+ /**
119
+ * CSS-like padding shorthand (same syntax as margin).
120
+ */
121
+ padding?: `${string} ${string}` | `${string} ${string} ${string} ${string}` | UnitValue;
122
+ }
123
+ /**
124
+ * Font weight: keyword `"bold"` / `"normal"`, or numeric 100–900
125
+ * following the CSS `font-weight` spec.
126
+ */
127
+ type FontWeight = 'bold' | 'normal' | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
128
+ /**
129
+ * A map of class name → style rule.
130
+ *
131
+ * Used to define reusable named styles referenced via `className` on nodes.
132
+ *
133
+ * @example
134
+ * ```ts
135
+ * const styles = defineStyles({
136
+ * red: { color: '#ff0000' },
137
+ * big: { fontSize: 20 },
138
+ * })
139
+ * ```
140
+ */
141
+ type StyleSheet = Record<string, DocxStyleRule>;
142
+ /** Horizontal text alignment. */
143
+ type TextAlign = 'center' | 'justify' | 'left' | 'right';
144
+ /** Vertical alignment (for table cells). */
145
+ type VerticalAlign = 'bottom' | 'middle' | 'top';
146
+ /**
147
+ * Define a type-safe stylesheet.
148
+ *
149
+ * `fontSize` defaults to pt when passed as a bare number.
150
+ *
151
+ * @param styles - — The stylesheet object
152
+ * @returns The same stylesheet with `const` type inference
153
+ *
154
+ * @example
155
+ * ```ts
156
+ * const styles = defineStyles({
157
+ * title: { fontSize: 28, fontWeight: 'bold' },
158
+ * body: { fontSize: 12, lineHeight: 1.5 },
159
+ * })
160
+ * ```
161
+ */
162
+ declare function defineStyles<const T extends StyleSheet>(styles: T): T;
163
+ //#endregion
164
+ //#region src/dsl/nodes.d.ts
165
+ /**
166
+ * Common properties shared by all nodes.
167
+ *
168
+ * @template TStyles — The user's stylesheet type
169
+ */
170
+ interface BaseNode<TStyles extends StyleSheet = StyleSheet> {
171
+ /**
172
+ * CSS-like class name(s) referencing stylesheet entries.
173
+ *
174
+ * Can be a single string, an array, or a space-separated string.
175
+ */
176
+ className?: string | ClassName<TStyles> | ClassName<TStyles>[];
177
+ /** Optional unique identifier (for templating / references). */
178
+ id?: string;
179
+ /** Inline style override for this specific node. */
180
+ style?: DocxStyleRule;
181
+ }
182
+ /**
183
+ * Union of all top-level content node types.
184
+ *
185
+ * @template TStyles — The user's stylesheet type
186
+ */
187
+ type BlockNode<TStyles extends StyleSheet = StyleSheet> = HeadingNode<TStyles> | ImageNode<TStyles> | PageBreakNode | ParagraphNode<TStyles> | PluginNode<string, unknown, TStyles> | TableNode<Record<string, unknown>, TStyles>;
188
+ /**
189
+ * Extract valid class name keys from a stylesheet type.
190
+ *
191
+ * @template TStyles — The user's stylesheet type
192
+ */
193
+ type ClassName<TStyles extends StyleSheet> = Extract<keyof TStyles, string>;
194
+ /**
195
+ * A heading node (h1–h6).
196
+ *
197
+ * @template TStyles — The user's stylesheet type
198
+ */
199
+ interface HeadingNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
200
+ /** Heading level (1 = largest, 6 = smallest). */
201
+ level: 1 | 2 | 3 | 4 | 5 | 6;
202
+ /** Heading text content. */
203
+ text: string;
204
+ type: 'heading';
205
+ }
206
+ /**
207
+ * An image node.
208
+ *
209
+ * Supports raw bytes (`Uint8Array`, `ArrayBuffer`, `Blob`) or a file path string.
210
+ *
211
+ * @template TStyles — The user's stylesheet type
212
+ */
213
+ interface ImageNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
214
+ /** Image data as bytes, blob, or file path. */
215
+ data: string | ArrayBuffer | Blob | Uint8Array;
216
+ type: 'image';
217
+ /** Alt text for accessibility. */
218
+ alt?: string;
219
+ /** Display height. */
220
+ height?: UnitValue;
221
+ /** Image format hint. Auto-detected if omitted. */
222
+ imageType?: 'bmp' | 'gif' | 'jpeg' | 'jpg' | 'png';
223
+ /** Display width. */
224
+ width?: UnitValue;
225
+ /**
226
+ * Floating layout configuration.
227
+ *
228
+ * - `true` enables default floating
229
+ * - Object allows wrap mode and position offsets
230
+ */
231
+ floating?: boolean | {
232
+ /** Text wrap mode. */wrap?: 'square' | 'tight' | 'topAndBottom'; /** Horizontal offset. */
233
+ x?: UnitValue; /** Vertical offset. */
234
+ y?: UnitValue;
235
+ };
236
+ }
237
+ /**
238
+ * Union of inline content node types (appear inside paragraphs).
239
+ *
240
+ * @template TStyles — The user's stylesheet type
241
+ */
242
+ type InlineNode<TStyles extends StyleSheet = StyleSheet> = ImageNode<TStyles> | TextNode<TStyles>;
243
+ /**
244
+ * A forced page break.
245
+ */
246
+ interface PageBreakNode {
247
+ type: 'pageBreak';
248
+ }
249
+ /**
250
+ * A paragraph containing text and/or inline children.
251
+ *
252
+ * @template TStyles — The user's stylesheet type
253
+ */
254
+ interface ParagraphNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
255
+ type: 'paragraph';
256
+ /** Inline children (text runs, inline images, etc.). */
257
+ children?: InlineNode<TStyles>[];
258
+ /** Plain-text content (used when `children` is not provided). */
259
+ text?: string;
260
+ }
261
+ /**
262
+ * A plugin-invocation node.
263
+ *
264
+ * Plugins extend the DSL with arbitrary content types.
265
+ *
266
+ * @template TName — Plugin name (string literal)
267
+ * @template TOptions — Plugin-specific options shape
268
+ * @template TStyles — The user's stylesheet type
269
+ */
270
+ interface PluginNode<TName extends string = string, TOptions = unknown, TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
271
+ /** Registered plugin name. */
272
+ name: TName;
273
+ /** Plugin-specific options. */
274
+ options: TOptions;
275
+ type: 'plugin';
276
+ }
277
+ /**
278
+ * A column definition for a table.
279
+ *
280
+ * @template TData — The row data type
281
+ */
282
+ interface TableColumn<TData extends Record<string, unknown> = Record<string, unknown>> {
283
+ /** Key in the data object this column maps to. */
284
+ key: Extract<keyof TData, string>;
285
+ /** Column header text. */
286
+ title: string;
287
+ /** Cell text alignment. */
288
+ align?: 'center' | 'left' | 'right';
289
+ /** Column width. Supports percentage strings (e.g. `"30%"`). */
290
+ width?: UnitValue;
291
+ /**
292
+ * Custom cell renderer.
293
+ *
294
+ * Receives the raw value, full row data, and row index.
295
+ * Returns a string or inline nodes.
296
+ */
297
+ render?: (value: TData[keyof TData], row: TData, index: number) => string | InlineNode[];
298
+ }
299
+ /**
300
+ * A table node with column definitions and data rows.
301
+ *
302
+ * @template TData — The row data type
303
+ * @template TStyles — The user's stylesheet type
304
+ */
305
+ interface TableNode<TData extends Record<string, unknown> = Record<string, unknown>, TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
306
+ /** Column definitions. */
307
+ columns: TableColumn<TData>[];
308
+ /** Row data objects. */
309
+ data: TData[];
310
+ type: 'table';
311
+ /** Show table borders. */
312
+ bordered?: boolean;
313
+ /** Default cell style for data rows. */
314
+ cellStyle?: DocxStyleRule;
315
+ /** Show header row (default: `true`). */
316
+ header?: boolean;
317
+ /** Style for header cells. */
318
+ headerCellStyle?: DocxStyleRule;
319
+ /** Alternate row shading. */
320
+ striped?: boolean;
321
+ }
322
+ /**
323
+ * A text run node (inline content).
324
+ *
325
+ * @template TStyles — The user's stylesheet type
326
+ */
327
+ interface TextNode<TStyles extends StyleSheet = StyleSheet> extends BaseNode<TStyles> {
328
+ /** Text content. */
329
+ text: string;
330
+ type: 'text';
331
+ }
332
+ //#endregion
333
+ //#region src/types/document.d.ts
334
+ /**
335
+ * Top-level configuration passed to `createDocx()`.
336
+ *
337
+ * Covers page setup, stylesheet, theme tokens, element defaults,
338
+ * and document metadata.
339
+ *
340
+ * @template TStyles — The user's stylesheet type (inferred from `styles`).
341
+ */
342
+ interface DocxKitConfig<TStyles extends StyleSheet = StyleSheet> {
343
+ /** Page dimensions and margins. */
344
+ page?: PageConfig;
345
+ /** Named style classes (class → style rule map). */
346
+ styles?: TStyles;
347
+ /** Semantic design tokens for theming. */
348
+ theme?: DocxTheme;
349
+ /** Default styles applied as base for each element type. */
350
+ defaults?: {
351
+ /** Default table cell style. */cell?: DocxStyleRule; /** Default paragraph style. */
352
+ paragraph?: DocxStyleRule; /** Default table style. */
353
+ table?: DocxStyleRule; /** Default text run style. */
354
+ text?: DocxStyleRule;
355
+ };
356
+ /** OOXML core properties (appear in File → Info). */
357
+ metadata?: {
358
+ /** Document author. */creator?: string; /** Document description / summary. */
359
+ description?: string; /** Keywords / tags. */
360
+ keywords?: string[]; /** Last editor. */
361
+ lastModifiedBy?: string; /** Document subject. */
362
+ subject?: string; /** Document title. */
363
+ title?: string;
364
+ };
365
+ }
366
+ /**
367
+ * Theme tokens that can be referenced in styles.
368
+ *
369
+ * Allows defining a single source of truth for colors, fonts,
370
+ * font sizes, and spacing values.
371
+ */
372
+ interface DocxTheme {
373
+ /** Color palette (name → hex). */
374
+ colors?: Record<string, string>;
375
+ /** Font family tokens (name → font family). */
376
+ fontFamily?: Record<string, string>;
377
+ /** Font size tokens (name → value). */
378
+ fontSize?: Record<string, UnitValue>;
379
+ /** Spacing tokens (name → value). */
380
+ spacing?: Record<string, UnitValue>;
381
+ }
382
+ /** Page orientation. */
383
+ type Orientation = 'landscape' | 'portrait';
384
+ /**
385
+ * Page configuration (size, orientation, margin).
386
+ */
387
+ interface PageConfig {
388
+ /** Page orientation (`"portrait"` default). */
389
+ orientation?: Orientation;
390
+ /** Page size: preset name or explicit dimensions. */
391
+ size?: PageSize | {
392
+ height: UnitValue;
393
+ width: UnitValue;
394
+ };
395
+ /**
396
+ * Page margin.
397
+ *
398
+ * Supports 1-value, 2-value, and 4-value shorthand
399
+ * (e.g. `"20mm"`, `"20mm 15mm"`, `"20mm 15mm 25mm 15mm"`).
400
+ */
401
+ margin?: `${string} ${string}` | `${string} ${string} ${string} ${string}` | UnitValue;
402
+ }
403
+ /** Available page size presets. */
404
+ type PageSize = 'A3' | 'A4' | 'Legal' | 'Letter';
405
+ //#endregion
406
+ //#region src/types/plugin.d.ts
407
+ /**
408
+ * A docx-kit plugin.
409
+ *
410
+ * Plugins have a unique `name`, an optional `setup` hook,
411
+ * and a required `render` function that receives user options
412
+ * and a rendering context.
413
+ *
414
+ * @template TName — The plugin name (string literal type)
415
+ * @template TOptions — The shape of the user-provided options
416
+ */
417
+ interface DocxPlugin<TName extends string = string, TOptions = unknown> {
418
+ /** Unique plugin name, used as the node discriminator. */
419
+ name: TName;
420
+ /** One-time setup called when the plugin is registered. */
421
+ setup?: () => MaybePromise<void>;
422
+ /**
423
+ * Render plugin content into one or more `docx` objects
424
+ * (Paragraph, Table, etc.).
425
+ *
426
+ * @param options - — User-provided plugin options
427
+ * @param context - — Rendering context with helper utilities
428
+ */
429
+ render: (options: TOptions, context: PluginRenderContext) => MaybePromise<unknown>;
430
+ }
431
+ /**
432
+ * Type-level map of plugin name → options type.
433
+ *
434
+ * Constructed via `Builder.use()` chaining.
435
+ */
436
+ type PluginRegistry = Record<string, unknown>;
437
+ /**
438
+ * Rendering context passed to a plugin's `render()` function.
439
+ *
440
+ * Provides access to the document config, image utilities,
441
+ * and the ability to compile child nodes.
442
+ */
443
+ interface PluginRenderContext {
444
+ /** The full document config. */
445
+ config: DocxKitConfig;
446
+ /** Compile a child node (useful for nesting). */
447
+ compileNode: (node: BlockNode) => Promise<unknown>;
448
+ /** Utility helpers. */
449
+ utils: {
450
+ image: {
451
+ /** Convert a Blob to raw image bytes. */fromBlob: (blob: Blob) => Promise<Uint8Array>;
452
+ /**
453
+ * Decode a base64 data-URL to raw image bytes.
454
+ * Works in both browser and Node.js environments.
455
+ */
456
+ fromDataUrl: (dataUrl: string) => MaybePromise<Uint8Array>;
457
+ };
458
+ };
459
+ }
460
+ /**
461
+ * Define a type-safe plugin with full inference.
462
+ *
463
+ * @param plugin - — The plugin definition object
464
+ * @returns The same plugin with `const` type inference
465
+ *
466
+ * @example
467
+ * ```ts
468
+ * const myPlugin = definePlugin<'badge', { text: string }>({
469
+ * name: 'badge',
470
+ * render: async (opts, ctx) => {
471
+ * // ... render logic
472
+ * return new Paragraph({ text: opts.text })
473
+ * },
474
+ * })
475
+ * ```
476
+ */
477
+ declare function definePlugin<const TName extends string, TOptions>(plugin: DocxPlugin<TName, TOptions>): DocxPlugin<TName, TOptions>;
478
+ //#endregion
479
+ //#region src/builder/DocxBuilder.d.ts
480
+ /**
481
+ * Fluent document builder.
482
+ *
483
+ * Use `createDocx()` to instantiate, then chain `.h1()`, `.p()`, `.table()`,
484
+ * etc. to build content. Call `.save()`, `.toBlob()`, `.toBuffer()`, or
485
+ * `.toBase64()` to export the document.
486
+ *
487
+ * @template TStyles — Inferred stylesheet type from `config.styles`
488
+ * @template TPlugins — Accumulated plugin registry (built via `.use()`)
489
+ */
490
+ declare class DocxBuilder<TStyles extends StyleSheet = StyleSheet, TPlugins extends PluginRegistry = Record<never, never>> {
491
+ private readonly config;
492
+ private readonly nodes;
493
+ private readonly pendingSetups;
494
+ private readonly pluginMap;
495
+ constructor(config?: DocxKitConfig<TStyles>);
496
+ /**
497
+ * Add a raw DSL node to the document.
498
+ *
499
+ * @param node - — Any block-level node
500
+ * @returns The builder (for chaining)
501
+ *
502
+ * @example
503
+ * ```ts
504
+ * doc.add({ type: 'heading', level: 2, text: 'Section' })
505
+ * doc.add({ type: 'pageBreak' })
506
+ * ```
507
+ */
508
+ add(node: BlockNode<TStyles>): this;
509
+ /**
510
+ * Add a level-1 heading.
511
+ *
512
+ * @param text - — Heading text
513
+ * @param options - — Optional style overrides (className, id, style)
514
+ * @returns The builder (for chaining)
515
+ *
516
+ * @example
517
+ * ```ts
518
+ * doc.h1('Introduction', { className: 'title' })
519
+ * ```
520
+ */
521
+ h1(text: string, options?: Omit<Partial<HeadingNode<TStyles>>, 'level' | 'text' | 'type'>): this;
522
+ /**
523
+ * Add a level-2 heading.
524
+ *
525
+ * @param text - — Heading text
526
+ * @param options - — Optional style overrides
527
+ * @returns The builder (for chaining)
528
+ */
529
+ h2(text: string, options?: Omit<Partial<HeadingNode<TStyles>>, 'level' | 'text' | 'type'>): this;
530
+ /**
531
+ * Add a level-3 heading.
532
+ *
533
+ * @param text - — Heading text
534
+ * @param options - — Optional style overrides
535
+ * @returns The builder (for chaining)
536
+ */
537
+ h3(text: string, options?: Omit<Partial<HeadingNode<TStyles>>, 'level' | 'text' | 'type'>): this;
538
+ /**
539
+ * Add a level-4 heading.
540
+ *
541
+ * @param text - — Heading text
542
+ * @param options - — Optional style overrides
543
+ * @returns The builder (for chaining)
544
+ */
545
+ h4(text: string, options?: Omit<Partial<HeadingNode<TStyles>>, 'level' | 'text' | 'type'>): this;
546
+ /**
547
+ * Add a level-5 heading.
548
+ *
549
+ * @param text - — Heading text
550
+ * @param options - — Optional style overrides
551
+ * @returns The builder (for chaining)
552
+ */
553
+ h5(text: string, options?: Omit<Partial<HeadingNode<TStyles>>, 'level' | 'text' | 'type'>): this;
554
+ /**
555
+ * Add a level-6 heading.
556
+ *
557
+ * @param text - — Heading text
558
+ * @param options - — Optional style overrides
559
+ * @returns The builder (for chaining)
560
+ */
561
+ h6(text: string, options?: Omit<Partial<HeadingNode<TStyles>>, 'level' | 'text' | 'type'>): this;
562
+ /**
563
+ * Add an image node.
564
+ *
565
+ * @param options - — Image node options (data, width, height, etc.)
566
+ * @returns The builder (for chaining)
567
+ *
568
+ * @example
569
+ * ```ts
570
+ * doc.image({ data: imageBytes, width: 400, height: 300 })
571
+ * ```
572
+ */
573
+ image(options: Omit<ImageNode<TStyles>, 'type'>): this;
574
+ /**
575
+ * Add a paragraph.
576
+ *
577
+ * @param text - — Paragraph text content
578
+ * @param options - — Optional style overrides (className, id, style)
579
+ * @returns The builder (for chaining)
580
+ *
581
+ * @example
582
+ * ```ts
583
+ * doc.p('Hello world', { className: 'body', style: { textAlign: 'center' } })
584
+ * ```
585
+ */
586
+ p(text: string, options?: Omit<Partial<ParagraphNode<TStyles>>, 'text' | 'type'>): this;
587
+ /**
588
+ * Add a forced page break.
589
+ *
590
+ * @returns The builder (for chaining)
591
+ *
592
+ * @example
593
+ * ```ts
594
+ * doc.h1('Chapter 1').pageBreak().h1('Chapter 2')
595
+ * ```
596
+ */
597
+ pageBreak(): this;
598
+ /**
599
+ * Invoke a registered plugin.
600
+ *
601
+ * @param name - — Plugin name (must match a previously registered plugin)
602
+ * @param options - — Plugin-specific options
603
+ * @param style - — Optional inline style for the plugin's container
604
+ * @returns The builder (for chaining)
605
+ *
606
+ * @example
607
+ * ```ts
608
+ * doc.use(qrcodePlugin()).plugin('qrcode', { text: 'https://example.com' })
609
+ * ```
610
+ */
611
+ plugin<TName extends string & keyof TPlugins>(name: TName, options: TPlugins[TName], style?: DocxStyleRule): this;
612
+ /**
613
+ * Save the document to a file (Node.js only).
614
+ *
615
+ * **⚠️ Not available in browser environments.**
616
+ * Use {@link toBlob} and trigger a download instead.
617
+ *
618
+ * @param filename - — Output file path (e.g. `"report.docx"`)
619
+ *
620
+ * @example
621
+ * ```ts
622
+ * await doc.save('output.docx')
623
+ * ```
624
+ */
625
+ save(filename: string): Promise<void>;
626
+ /**
627
+ * Add a table.
628
+ *
629
+ * @param options - — Table node options (columns, data, style, etc.)
630
+ * @returns The builder (for chaining)
631
+ *
632
+ * @example
633
+ * ```ts
634
+ * doc.table({
635
+ * columns: [
636
+ * { key: 'name', title: 'Name' },
637
+ * { key: 'value', title: 'Value', align: 'right' },
638
+ * ],
639
+ * data: [{ name: 'Revenue', value: '$1.2M' }],
640
+ * headerCellStyle: { fontWeight: 'bold' },
641
+ * })
642
+ * ```
643
+ */
644
+ table<TData extends Record<string, unknown>>(options: Omit<TableNode<TData, TStyles>, 'type'>): this;
645
+ /**
646
+ * Export the document as a base64-encoded string.
647
+ *
648
+ * @returns Base64-encoded .docx data
649
+ *
650
+ * @example
651
+ * ```ts
652
+ * const b64 = await doc.toBase64()
653
+ * // Send b64 over HTTP or store in a database
654
+ * ```
655
+ */
656
+ toBase64(): Promise<string>;
657
+ /**
658
+ * Export the document as a `Blob` (browser-friendly).
659
+ *
660
+ * @returns A `Blob` containing the .docx binary
661
+ *
662
+ * @example
663
+ * ```ts
664
+ * const blob = await doc.toBlob()
665
+ * const url = URL.createObjectURL(blob)
666
+ * ```
667
+ */
668
+ toBlob(): Promise<Blob>;
669
+ /**
670
+ * Export the document as a `Uint8Array` (alias for {@link toUint8Array}).
671
+ *
672
+ * **Note:** Despite the name, this returns a standard `Uint8Array`,
673
+ * not a Node.js `Buffer`. Prefer using {@link toUint8Array} for clarity.
674
+ *
675
+ * @returns Raw .docx bytes
676
+ *
677
+ * @example
678
+ * ```ts
679
+ * const bytes = await doc.toBuffer()
680
+ * fs.writeFileSync('output.docx', bytes)
681
+ * ```
682
+ */
683
+ toBuffer(): Promise<Uint8Array>;
684
+ /**
685
+ * Compile and return the internal `docx` {@link Document} instance.
686
+ *
687
+ * Useful if you need to further manipulate the document with the
688
+ * raw `docx` library before packaging.
689
+ *
690
+ * @returns A `docx` `Document` object
691
+ */
692
+ toDocument(): Promise<import("docx").Document>;
693
+ /**
694
+ * Serialize the builder state to a JSON-friendly object.
695
+ *
696
+ * Useful for debugging, serialization, or AI-driven document generation.
697
+ *
698
+ * @returns The config + content node array as a plain object
699
+ */
700
+ toJSON(): {
701
+ content: BlockNode<TStyles>[];
702
+ page?: PageConfig;
703
+ styles?: TStyles | undefined;
704
+ theme?: DocxTheme;
705
+ defaults?: {
706
+ cell?: DocxStyleRule;
707
+ paragraph?: DocxStyleRule;
708
+ table?: DocxStyleRule;
709
+ text?: DocxStyleRule;
710
+ };
711
+ metadata?: {
712
+ creator?: string;
713
+ description?: string;
714
+ keywords?: string[];
715
+ lastModifiedBy?: string;
716
+ subject?: string;
717
+ title?: string;
718
+ };
719
+ };
720
+ /**
721
+ * Export the document as a `Uint8Array` (browser & Node.js).
722
+ *
723
+ * This is the preferred cross-platform export method.
724
+ *
725
+ * @returns Raw .docx bytes
726
+ *
727
+ * @example
728
+ * ```ts
729
+ * const bytes = await doc.toUint8Array()
730
+ * // In Node.js: import { writeFileSync } from 'node:fs'
731
+ * // In browser: trigger a download
732
+ * ```
733
+ */
734
+ toUint8Array(): Promise<Uint8Array>;
735
+ /**
736
+ * Register a plugin.
737
+ *
738
+ * The plugin's name and options type are accumulated into the builder's
739
+ * type-level plugin registry, enabling type-safe `.plugin()` calls.
740
+ *
741
+ * @param plugin - — The plugin definition returned by `definePlugin()`
742
+ * @returns The builder with the plugin type merged into `TPlugins`
743
+ *
744
+ * @example
745
+ * ```ts
746
+ * const doc = createDocx()
747
+ * .use(qrcodePlugin())
748
+ * .plugin('qrcode', { text: 'https://example.com' })
749
+ * ```
750
+ */
751
+ use<TName extends string, TOptions>(plugin: DocxPlugin<TName, TOptions>): DocxBuilder<TStyles, Record<TName, TOptions> & TPlugins>;
752
+ }
753
+ //#endregion
754
+ //#region src/errors.d.ts
755
+ /**
756
+ * Error handling types and classes for docx-kit.
757
+ *
758
+ * @module errors
759
+ */
760
+ /**
761
+ * Well-known error codes used throughout the library.
762
+ *
763
+ * Consumers can match against these codes for structured error handling.
764
+ */
765
+ declare const ERROR_CODES: {
766
+ /** Document export failed. */readonly EXPORT_FAILED: "EXPORT_FAILED"; /** Image data is empty, corrupt, or unsupported. */
767
+ readonly IMAGE_INVALID_DATA: "IMAGE_INVALID_DATA"; /** A plugin node referenced an unregistered plugin. */
768
+ readonly PLUGIN_NOT_REGISTERED: "PLUGIN_NOT_REGISTERED"; /** A plugin's `render()` method threw an error. */
769
+ readonly PLUGIN_RENDER_FAILED: "PLUGIN_RENDER_FAILED"; /** A `className` referenced a stylesheet key that doesn't exist. */
770
+ readonly STYLE_UNKNOWN_CLASS: "STYLE_UNKNOWN_CLASS"; /** Table was created with no columns. */
771
+ readonly TABLE_INVALID_COLUMNS: "TABLE_INVALID_COLUMNS"; /** Encountered a node type that has no registered compiler. */
772
+ readonly UNKNOWN_NODE_TYPE: "UNKNOWN_NODE_TYPE";
773
+ };
774
+ /** Union type of all known error codes. */
775
+ type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
776
+ /**
777
+ * Structured error class for docx-kit.
778
+ *
779
+ * Carries a machine-readable `code`, a human-readable `message`,
780
+ * and optionally the underlying `cause`.
781
+ *
782
+ * @example
783
+ * ```ts
784
+ * try {
785
+ * await doc.save('output.docx')
786
+ * } catch (err) {
787
+ * if (err instanceof DocxKitError && err.code === ERROR_CODES.EXPORT_FAILED) {
788
+ * console.error('Export failed:', err.message)
789
+ * }
790
+ * }
791
+ * ```
792
+ */
793
+ declare class DocxKitError extends Error {
794
+ /** The underlying error that caused this failure (if any). */
795
+ readonly cause: unknown;
796
+ /** Machine-readable error code. */
797
+ readonly code: string | ErrorCode;
798
+ /**
799
+ * @param code - — Known error code from {@link ERROR_CODES}
800
+ * @param message - — Human-readable description
801
+ * @param cause - — Optional underlying error
802
+ */
803
+ constructor(code: string | ErrorCode, message: string, cause?: unknown);
804
+ }
805
+ //#endregion
806
+ //#region src/plugins/qrcode/index.d.ts
807
+ /**
808
+ * QR Code plugin — embeds a QR code image in the document.
809
+ *
810
+ * Uses the `qrcode` package (peer dependency) to generate
811
+ * a QR code PNG and renders it as an inline `ImageRun`.
812
+ *
813
+ * @module plugins/qrcode
814
+ *
815
+ * @example
816
+ * ```ts
817
+ * const doc = createDocx()
818
+ * .use(qrcodePlugin())
819
+ * .h1('Scan Me')
820
+ * .plugin('qrcode', { text: 'https://example.com', caption: 'Visit us' })
821
+ * .save('qrcode.docx')
822
+ * ```
823
+ */
824
+ /**
825
+ * Options for the QRCode plugin.
826
+ */
827
+ interface QRCodePluginOptions {
828
+ /** The text / URL to encode. */
829
+ text: string;
830
+ /** Optional caption text displayed below the QR code. */
831
+ caption?: string;
832
+ /**
833
+ * QR error correction level.
834
+ *
835
+ * - `"L"` — ~7% recovery
836
+ * - `"M"` — ~15% recovery
837
+ * - `"Q"` — ~25% recovery
838
+ * - `"H"` — ~30% recovery
839
+ *
840
+ * @default "M"
841
+ */
842
+ errorCorrectionLevel?: 'H' | 'L' | 'M' | 'Q';
843
+ /** QR code margin (in modules). @default 1 */
844
+ margin?: number;
845
+ /** QR code image size in pixels. @default 128 */
846
+ size?: number;
847
+ }
848
+ /**
849
+ * Create a QRCode plugin instance.
850
+ *
851
+ * The plugin dynamically imports the `qrcode` package at render time,
852
+ * keeping it an optional peer dependency of docx-kit core.
853
+ *
854
+ * @returns A configured DocxPlugin for `'qrcode'`
855
+ *
856
+ * @example
857
+ * ```ts
858
+ * import { createDocx, qrcodePlugin } from 'docx-kit'
859
+ *
860
+ * const doc = createDocx()
861
+ * .use(qrcodePlugin())
862
+ * .plugin('qrcode', {
863
+ * text: 'https://example.com',
864
+ * size: 256,
865
+ * errorCorrectionLevel: 'H',
866
+ * caption: 'Scan to visit',
867
+ * })
868
+ * ```
869
+ */
870
+ declare function qrcodePlugin(): DocxPlugin<"qrcode", QRCodePluginOptions>;
871
+ //#endregion
872
+ //#region src/utils/dataUrl.d.ts
873
+ /**
874
+ * Cross-platform base64 data-URL decoder.
875
+ *
876
+ * Auto-detects the runtime environment and uses the appropriate
877
+ * implementation:
878
+ * - **Node.js**: `Buffer.from(base64, 'base64')`
879
+ * - **Browser**: `atob(base64)` + manual byte population
880
+ *
881
+ * This is the internal shared version used by the compiler and
882
+ * built-in plugins. For platform-specific direct access, import
883
+ * from `'docx-kit/node'` or `'docx-kit/browser'`.
884
+ *
885
+ * @module utils/dataUrl
886
+ */
887
+ /**
888
+ * Decode a base64 data-URL to raw bytes (works in both browser & Node.js).
889
+ *
890
+ * Strips the `"data:*;base64,"` prefix and decodes using the appropriate
891
+ * runtime API.
892
+ *
893
+ * @param dataUrl - — A base64 data-URI string (e.g. `"data:image/png;base64,iVBO..."`)
894
+ * @returns Raw bytes as `Uint8Array`
895
+ *
896
+ * @example
897
+ * ```ts
898
+ * import { dataUrlToUint8Array } from 'docx-kit'
899
+ *
900
+ * const bytes = await dataUrlToUint8Array('data:image/png;base64,iVBORw...')
901
+ * ```
902
+ */
903
+ declare function dataUrlToUint8Array(dataUrl: string): Promise<Uint8Array>;
904
+ //#endregion
905
+ //#region src/plugins/echarts/index.d.ts
906
+ /**
907
+ * Options for the ECharts plugin.
908
+ */
909
+ interface EChartsPluginOptions {
910
+ /** Full ECharts option object (series, axes, title, etc.). */
911
+ option: EChartsOption;
912
+ /** Optional caption text displayed below the chart. */
913
+ caption?: string;
914
+ /** Chart height in pixels. @default 360 */
915
+ height?: number;
916
+ /** Output image format. @default "png" */
917
+ imageType?: 'png' | 'svg';
918
+ /** ECharts rendering engine. @default "canvas" */
919
+ renderer?: 'canvas' | 'svg';
920
+ /** Chart width in pixels. @default 640 */
921
+ width?: number;
922
+ }
923
+ /**
924
+ * Create an ECharts plugin instance.
925
+ *
926
+ * The plugin renders charts using the browser DOM. In Node.js
927
+ * environments, it throws an error prompting the user to provide
928
+ * a server-side canvas implementation.
929
+ *
930
+ * @returns A configured DocxPlugin for `'echarts'`
931
+ *
932
+ * @example
933
+ * ```ts
934
+ * import { createDocx, echartsPlugin } from 'docx-kit'
935
+ *
936
+ * const doc = createDocx()
937
+ * .use(echartsPlugin())
938
+ * .plugin('echarts', {
939
+ * option: {
940
+ * title: { text: 'Revenue' },
941
+ * xAxis: { type: 'category', data: ['Q1', 'Q2', 'Q3', 'Q4'] },
942
+ * yAxis: { type: 'value' },
943
+ * series: [{ data: [820, 932, 901, 1347], type: 'line' }],
944
+ * },
945
+ * caption: 'Quarterly revenue trend',
946
+ * })
947
+ * ```
948
+ */
949
+ declare function echartsPlugin(): DocxPlugin<"echarts", EChartsPluginOptions>;
950
+ //#endregion
951
+ //#region src/builder/createDocx.d.ts
952
+ /**
953
+ * JSON schema for `renderDocx()`.
954
+ *
955
+ * The schema is deliberately simple — a flat config object plus an
956
+ * ordered array of block nodes. This makes it easy to generate from
957
+ * AI / LLMs or store as JSON.
958
+ *
959
+ * @template TStyles — The user's stylesheet type
960
+ */
961
+ interface DocxSchema<TStyles extends StyleSheet = StyleSheet> {
962
+ /** Ordered array of block nodes. */
963
+ content: BlockNode<TStyles>[];
964
+ /** Optional page configuration. */
965
+ page?: DocxKitConfig<TStyles>['page'];
966
+ /** Named stylesheet entries. */
967
+ styles?: TStyles;
968
+ }
969
+ /**
970
+ * Create a new DocxBuilder with optional configuration.
971
+ *
972
+ * This is the primary entry point for the fluent builder API.
973
+ * Chain `.h1()`, `.p()`, `.table()`, etc. and call `.save()`
974
+ * or `.toBlob()` to export.
975
+ *
976
+ * @param config - — Document configuration (page, styles, metadata, theme, defaults)
977
+ * @returns A new `DocxBuilder` instance
978
+ *
979
+ * @example
980
+ * ```ts
981
+ * const styles = defineStyles({
982
+ * title: { fontSize: 28, fontWeight: 'bold' },
983
+ * body: { fontSize: 12, lineHeight: 1.5 },
984
+ * })
985
+ *
986
+ * const doc = createDocx({
987
+ * styles,
988
+ * page: { size: 'A4', margin: '20mm' },
989
+ * metadata: { title: 'Report', creator: 'docx-kit' },
990
+ * })
991
+ *
992
+ * await doc
993
+ * .h1('Annual Report', { className: 'title' })
994
+ * .p('Lorem ipsum...', { className: 'body' })
995
+ * .save('report.docx')
996
+ * ```
997
+ */
998
+ declare function createDocx<const TStyles extends StyleSheet = StyleSheet>(config?: DocxKitConfig<TStyles>): DocxBuilder<TStyles, Record<never, never>>;
999
+ /**
1000
+ * Render a document from a JSON schema (AI-friendly / serializable DSL).
1001
+ *
1002
+ * Unlike `createDocx()`, this accepts a single JSON-serializable object
1003
+ * with `content` (node array), optional `styles`, and optional `page` config.
1004
+ * Ideal for AI-driven document generation or API integrations.
1005
+ *
1006
+ * @param schema - — The `DocxSchema` object
1007
+ * @returns A `DocxBuilder` instance (ready to export)
1008
+ *
1009
+ * @example
1010
+ * ```ts
1011
+ * const blob = await renderDocx({
1012
+ * page: { size: 'A4', margin: '20mm' },
1013
+ * styles: {
1014
+ * h1: { fontSize: 24, fontWeight: 'bold' },
1015
+ * p: { fontSize: 12 },
1016
+ * },
1017
+ * content: [
1018
+ * { type: 'heading', level: 1, text: 'Report', className: 'h1' },
1019
+ * { type: 'paragraph', text: 'This is a report generated via JSON DSL.', className: 'p' },
1020
+ * { type: 'pageBreak' },
1021
+ * {
1022
+ * type: 'table',
1023
+ * columns: [{ key: 'name', title: 'Name' }, { key: 'value', title: 'Value' }],
1024
+ * data: [{ name: 'Revenue', value: '$1.2M' }],
1025
+ * },
1026
+ * ],
1027
+ * }).toBlob()
1028
+ * ```
1029
+ */
1030
+ declare function renderDocx<const TStyles extends StyleSheet = StyleSheet>(schema: DocxSchema<TStyles>): DocxBuilder<TStyles>;
1031
+ //#endregion
1032
+ export { type BaseNode, type BlockNode, type BorderRule, type BorderStyle, type ClassName, DocxBuilder, type DocxKitConfig, DocxKitError, type DocxPlugin, type DocxSchema, type DocxStyleRule, type DocxTheme, type EChartsPluginOptions, ERROR_CODES, type ErrorCode, type FontWeight, type HeadingNode, type ImageNode, type InlineNode, type Orientation, type PageBreakNode, type PageConfig, type PageSize, type ParagraphNode, type PluginNode, type PluginRegistry, type PluginRenderContext, type QRCodePluginOptions, type StyleSheet, type TableColumn, type TableNode, type TextAlign, type TextNode, type VerticalAlign, createDocx, dataUrlToUint8Array, definePlugin, defineStyles, echartsPlugin, qrcodePlugin, renderDocx };