rtf-codec 0.0.0 → 1.0.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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +208 -0
  3. package/dist/base64.cjs +66 -0
  4. package/dist/base64.d.cts +7 -0
  5. package/dist/base64.d.ts +7 -0
  6. package/dist/base64.js +62 -0
  7. package/dist/bytes.cjs +25 -0
  8. package/dist/bytes.d.cts +6 -0
  9. package/dist/bytes.d.ts +6 -0
  10. package/dist/bytes.js +22 -0
  11. package/dist/codec.cjs +29 -0
  12. package/dist/codec.d.cts +2308 -0
  13. package/dist/codec.d.ts +2308 -0
  14. package/dist/codec.js +26 -0
  15. package/dist/codepage.cjs +98 -0
  16. package/dist/codepage.d.cts +10 -0
  17. package/dist/codepage.d.ts +10 -0
  18. package/dist/codepage.js +92 -0
  19. package/dist/diagnostics-DdDFJLNO.d.cts +51 -0
  20. package/dist/diagnostics-DdDFJLNO.d.ts +51 -0
  21. package/dist/diagnostics.cjs +75 -0
  22. package/dist/diagnostics.d.cts +2 -0
  23. package/dist/diagnostics.d.ts +2 -0
  24. package/dist/diagnostics.js +67 -0
  25. package/dist/group.cjs +40 -0
  26. package/dist/group.d.cts +11 -0
  27. package/dist/group.d.ts +11 -0
  28. package/dist/group.js +38 -0
  29. package/dist/header.cjs +378 -0
  30. package/dist/header.d.cts +43 -0
  31. package/dist/header.d.ts +43 -0
  32. package/dist/header.js +376 -0
  33. package/dist/index.cjs +28 -0
  34. package/dist/index.d.cts +8 -0
  35. package/dist/index.d.ts +8 -0
  36. package/dist/index.js +8 -0
  37. package/dist/list-id.cjs +30 -0
  38. package/dist/list-id.d.cts +16 -0
  39. package/dist/list-id.d.ts +16 -0
  40. package/dist/list-id.js +27 -0
  41. package/dist/options.cjs +7 -0
  42. package/dist/options.d.cts +18 -0
  43. package/dist/options.d.ts +18 -0
  44. package/dist/options.js +5 -0
  45. package/dist/read.cjs +854 -0
  46. package/dist/read.d.cts +16 -0
  47. package/dist/read.d.ts +16 -0
  48. package/dist/read.js +852 -0
  49. package/dist/tokenize.cjs +155 -0
  50. package/dist/tokenize.d.cts +25 -0
  51. package/dist/tokenize.d.ts +25 -0
  52. package/dist/tokenize.js +154 -0
  53. package/dist/units.cjs +43 -0
  54. package/dist/units.d.cts +17 -0
  55. package/dist/units.d.ts +17 -0
  56. package/dist/units.js +29 -0
  57. package/dist/write.cjs +364 -0
  58. package/dist/write.d.cts +7 -0
  59. package/dist/write.d.ts +7 -0
  60. package/dist/write.js +362 -0
  61. package/package.json +95 -2
package/dist/read.js ADDED
@@ -0,0 +1,852 @@
1
+ import { bytesToBase64, hexToBytes } from "./base64.js";
2
+ import { RtfDiagnosticCodes, RtfInputTooLargeError, RtfNestingLimitExceededError, RtfNotAnRtfDocumentError } from "./diagnostics.js";
3
+ import { appendBytes, asciiStringFromBytes, rtfBytesFromLatin1 } from "./bytes.js";
4
+ import { decodeCodepageBytes } from "./codepage.js";
5
+ import { groupHead, matchingGroupEnd } from "./group.js";
6
+ import { halfPointsToPoints, pixelsToPoints, twipsToPoints } from "./units.js";
7
+ import { HEADER_DESTINATIONS, readRtfHeader } from "./header.js";
8
+ import { mintRtfListNumId } from "./list-id.js";
9
+ import "./options.js";
10
+ import { tokenizeRtf } from "./tokenize.js";
11
+ import { assembleTree } from "document-schema.js";
12
+ //#region src/read.ts
13
+ const DESTINATION_KINDS = /* @__PURE__ */ new Map([
14
+ ["fldrslt", "body"],
15
+ ["ud", "body"],
16
+ ["shppict", "body"],
17
+ ["field", "body"],
18
+ ["pict", "picture"],
19
+ ["fldinst", "fieldInstruction"],
20
+ ["listtext", "listText"],
21
+ ["pntext", "listText"],
22
+ ["upr", "unicodeWrapper"],
23
+ ["footnote", "skip"],
24
+ ["header", "skip"],
25
+ ["headerl", "skip"],
26
+ ["headerr", "skip"],
27
+ ["headerf", "skip"],
28
+ ["footer", "skip"],
29
+ ["footerl", "skip"],
30
+ ["footerr", "skip"],
31
+ ["footerf", "skip"],
32
+ ["ftnsep", "skip"],
33
+ ["ftnsepc", "skip"],
34
+ ["ftncn", "skip"],
35
+ ["aftnsep", "skip"],
36
+ ["aftnsepc", "skip"],
37
+ ["aftncn", "skip"],
38
+ ["annotation", "skip"],
39
+ ["atnid", "skip"],
40
+ ["atnauthor", "skip"],
41
+ ["atnref", "skip"],
42
+ ["atndate", "skip"],
43
+ ["atnparent", "skip"],
44
+ ["atnicn", "skip"],
45
+ ["bkmkstart", "skip"],
46
+ ["bkmkend", "skip"],
47
+ ["object", "skip"],
48
+ ["objdata", "skip"],
49
+ ["objclass", "skip"],
50
+ ["objname", "skip"],
51
+ ["do", "skip"],
52
+ ["shp", "skip"],
53
+ ["shptxt", "skip"],
54
+ ["shpinst", "skip"],
55
+ ["nonshppict", "skip"],
56
+ ["xe", "skip"],
57
+ ["tc", "skip"],
58
+ ["tcn", "skip"],
59
+ ["pn", "skip"],
60
+ ["pnseclvl", "skip"],
61
+ ["template", "skip"],
62
+ ["comment", "skip"],
63
+ ["falt", "skip"],
64
+ ["panose", "skip"],
65
+ ["fname", "skip"]
66
+ ]);
67
+ const SILENT_SKIP_DESTINATIONS = /* @__PURE__ */ new Set([
68
+ "pn",
69
+ "pnseclvl",
70
+ "nonshppict",
71
+ "falt",
72
+ "panose",
73
+ "fname",
74
+ "atnid",
75
+ "atnauthor",
76
+ "atnref",
77
+ "atndate",
78
+ "atnparent",
79
+ "atnicn",
80
+ "objclass",
81
+ "objname",
82
+ "objdata",
83
+ "shpinst",
84
+ "shptxt",
85
+ "ftnsep",
86
+ "ftnsepc",
87
+ "ftncn",
88
+ "aftnsep",
89
+ "aftnsepc",
90
+ "aftncn",
91
+ "template",
92
+ "comment",
93
+ "xe",
94
+ "tc",
95
+ "tcn"
96
+ ]);
97
+ const SPECIAL_CHARACTER_TEXT = /* @__PURE__ */ new Map([
98
+ ["tab", " "],
99
+ ["line", "\n"],
100
+ ["softline", "\n"],
101
+ ["emdash", "—"],
102
+ ["endash", "–"],
103
+ ["bullet", "•"],
104
+ ["lquote", "‘"],
105
+ ["rquote", "’"],
106
+ ["ldblquote", "“"],
107
+ ["rdblquote", "”"],
108
+ ["emspace", " "],
109
+ ["enspace", " "],
110
+ ["qmspace", " "],
111
+ ["zwj", "‍"],
112
+ ["zwnj", "‌"],
113
+ ["ltrmark", "‎"],
114
+ ["rtlmark", "‏"]
115
+ ]);
116
+ const SPECIAL_SYMBOL_TEXT = /* @__PURE__ */ new Map([
117
+ ["~", "\xA0"],
118
+ ["-", "­"],
119
+ ["_", "‑"],
120
+ ["\\", "\\"],
121
+ ["{", "{"],
122
+ ["}", "}"]
123
+ ]);
124
+ const ALIGNMENTS = /* @__PURE__ */ new Map([
125
+ ["ql", "left"],
126
+ ["qc", "center"],
127
+ ["qr", "right"],
128
+ ["qj", "justify"]
129
+ ]);
130
+ const PICTURE_FORMATS = /* @__PURE__ */ new Map([["pngblip", "png"], ["jpegblip", "jpeg"]]);
131
+ function defaultCharacterState() {
132
+ return {
133
+ bold: false,
134
+ italic: false,
135
+ underline: false,
136
+ strike: false,
137
+ hidden: false,
138
+ fontIndex: void 0,
139
+ sizeHalfPoints: 24,
140
+ colorIndex: void 0
141
+ };
142
+ }
143
+ function defaultParagraphState() {
144
+ return {
145
+ alignment: void 0,
146
+ indentLeftTwips: 0,
147
+ indentFirstLineTwips: 0,
148
+ spaceBeforeTwips: 0,
149
+ spaceAfterTwips: 0,
150
+ lineSpacingTwips: void 0,
151
+ lineSpacingIsMultiple: false,
152
+ styleIndex: void 0,
153
+ outlineLevel: void 0,
154
+ listOverrideIndex: void 0,
155
+ listLevel: 0,
156
+ inTable: false,
157
+ pageBreakBefore: false
158
+ };
159
+ }
160
+ function cloneGroupState(state) {
161
+ return {
162
+ destination: state.destination,
163
+ uc: state.uc,
164
+ char: { ...state.char },
165
+ para: { ...state.para },
166
+ field: state.field,
167
+ picture: state.picture,
168
+ inUnicodeWrapper: state.inUnicodeWrapper
169
+ };
170
+ }
171
+ function runKey(char, fontName, color, hyperlink) {
172
+ return [
173
+ char.bold ? "b" : "",
174
+ char.italic ? "i" : "",
175
+ char.underline ? "u" : "",
176
+ char.strike ? "s" : "",
177
+ fontName ?? "",
178
+ String(char.sizeHalfPoints),
179
+ color === void 0 ? "" : `${String(color.r)},${String(color.g)},${String(color.b)}`,
180
+ hyperlink ?? ""
181
+ ].join("|");
182
+ }
183
+ const HYPERLINK_TARGET = /HYPERLINK\s+"([^"]*)"/i;
184
+ const HYPERLINK_BARE_TARGET = /HYPERLINK\s+([^\s"\\]\S*)/i;
185
+ const HYPERLINK_ANCHOR = /\\l\s+"([^"]*)"/i;
186
+ function hyperlinkFromInstruction(instruction) {
187
+ const quoted = HYPERLINK_TARGET.exec(instruction);
188
+ const anchor = HYPERLINK_ANCHOR.exec(instruction);
189
+ const target = quoted?.[1] ?? HYPERLINK_BARE_TARGET.exec(instruction)?.[1];
190
+ if (target === void 0) return anchor?.[1] === void 0 ? void 0 : `#${anchor[1]}`;
191
+ return anchor?.[1] === void 0 ? target : `${target}#${anchor[1]}`;
192
+ }
193
+ function skipUnicodeFallback(tokens, from, count) {
194
+ let { index, textOffset } = from;
195
+ let remaining = count;
196
+ while (remaining > 0 && index < tokens.length) {
197
+ const token = tokens[index];
198
+ if (token === void 0) break;
199
+ if (token.kind === "groupStart" || token.kind === "groupEnd") break;
200
+ if (token.kind === "text") {
201
+ const available = token.bytes.length - textOffset;
202
+ const consumed = Math.min(available, remaining);
203
+ remaining -= consumed;
204
+ textOffset += consumed;
205
+ if (textOffset >= token.bytes.length) {
206
+ index += 1;
207
+ textOffset = 0;
208
+ }
209
+ continue;
210
+ }
211
+ remaining -= 1;
212
+ index += 1;
213
+ textOffset = 0;
214
+ }
215
+ return {
216
+ index,
217
+ textOffset
218
+ };
219
+ }
220
+ var ContentBuilder = class {
221
+ header;
222
+ sink;
223
+ sections = [];
224
+ blocks = [];
225
+ runs = [];
226
+ pendingRunKey;
227
+ pendingRunText = "";
228
+ pendingRunFields = {};
229
+ tableRows = [];
230
+ tableColumnRights = [];
231
+ rowCells = [];
232
+ cellBlocks = [];
233
+ pendingCellRights = [];
234
+ rowLeftTwips = 0;
235
+ constructor(header, sink) {
236
+ this.header = header;
237
+ this.sink = sink;
238
+ }
239
+ appendText(text, char, hyperlink) {
240
+ if (text.length === 0 || char.hidden) return;
241
+ const fontName = char.fontIndex === void 0 ? void 0 : this.header.fonts.get(char.fontIndex)?.name;
242
+ const color = char.colorIndex === void 0 ? void 0 : this.header.colors[char.colorIndex];
243
+ const key = runKey(char, fontName, color, hyperlink);
244
+ if (this.pendingRunKey !== key) {
245
+ this.flushRun();
246
+ this.pendingRunKey = key;
247
+ this.pendingRunFields = buildRunFields(char, fontName, color, hyperlink);
248
+ }
249
+ this.pendingRunText += text;
250
+ }
251
+ flushRun() {
252
+ if (this.pendingRunText.length > 0) this.runs.push({
253
+ ...this.pendingRunFields,
254
+ text: this.pendingRunText
255
+ });
256
+ this.pendingRunText = "";
257
+ this.pendingRunKey = void 0;
258
+ this.pendingRunFields = {};
259
+ }
260
+ endParagraph(para, force) {
261
+ this.flushRun();
262
+ if (!force && this.runs.length === 0) return;
263
+ const target = para.inTable ? this.cellBlocks : this.blocks;
264
+ if (!para.inTable) this.closeTable();
265
+ target.push(this.buildParagraph(para));
266
+ this.runs = [];
267
+ }
268
+ buildParagraph(para) {
269
+ const style = para.styleIndex === void 0 ? void 0 : this.header.styles.get(para.styleIndex);
270
+ const headingLevel = para.outlineLevel === void 0 ? style?.headingLevel : para.outlineLevel + 1;
271
+ const paragraph = {
272
+ kind: "paragraph",
273
+ runs: this.runs
274
+ };
275
+ const withStyle = style?.name === void 0 || style.name.length === 0 ? paragraph : {
276
+ ...paragraph,
277
+ styleId: style.name
278
+ };
279
+ return {
280
+ ...headingLevel === void 0 ? withStyle : {
281
+ ...withStyle,
282
+ headingLevel
283
+ },
284
+ ...para.alignment === void 0 ? {} : { alignment: para.alignment },
285
+ ...para.indentLeftTwips === 0 ? {} : { indentLeftPt: twipsToPoints(para.indentLeftTwips) },
286
+ ...para.indentFirstLineTwips === 0 ? {} : { indentFirstLinePt: twipsToPoints(para.indentFirstLineTwips) },
287
+ ...para.spaceBeforeTwips === 0 ? {} : { spacingBeforePt: twipsToPoints(para.spaceBeforeTwips) },
288
+ ...para.spaceAfterTwips === 0 ? {} : { spacingAfterPt: twipsToPoints(para.spaceAfterTwips) },
289
+ ...this.lineSpacingFields(para),
290
+ ...para.pageBreakBefore ? { pageBreakBefore: true } : {},
291
+ ...this.listFields(para)
292
+ };
293
+ }
294
+ lineSpacingFields(para) {
295
+ const value = para.lineSpacingTwips;
296
+ if (value === void 0 || value === 0 || !para.lineSpacingIsMultiple) return {};
297
+ const multiple = Math.abs(value) / 240;
298
+ return multiple > 0 ? { lineSpacing: multiple } : {};
299
+ }
300
+ listFields(para) {
301
+ const overrideIndex = para.listOverrideIndex;
302
+ if (overrideIndex === void 0 || overrideIndex === 0) return {};
303
+ const list = this.header.lists.get(overrideIndex);
304
+ const level = list?.levels[para.listLevel] ?? list?.levels[0];
305
+ const type = level?.numberFormat === 23 ? "bullet" : "ordered";
306
+ return { list: {
307
+ numId: mintRtfListNumId({
308
+ listOverrideIndex: overrideIndex,
309
+ type,
310
+ ...level?.startAt === void 0 ? {} : { start: level.startAt }
311
+ }),
312
+ level: para.listLevel
313
+ } };
314
+ }
315
+ startRowDefinition() {
316
+ this.pendingCellRights = [];
317
+ this.rowLeftTwips = 0;
318
+ }
319
+ setRowLeft(twips) {
320
+ this.rowLeftTwips = twips;
321
+ }
322
+ addCellBoundary(rightTwips) {
323
+ this.pendingCellRights.push(rightTwips);
324
+ }
325
+ endCell(para) {
326
+ this.endParagraph(para, false);
327
+ this.rowCells.push({ blocks: this.cellBlocks });
328
+ this.cellBlocks = [];
329
+ }
330
+ endRow(para) {
331
+ if (this.cellBlocks.length > 0 || this.pendingRunText.length > 0) this.endCell(para);
332
+ if (this.rowCells.length === 0) {
333
+ this.sink({
334
+ code: RtfDiagnosticCodes.TABLE_ROW_WITHOUT_DEFINITION,
335
+ severity: "warning",
336
+ message: "a \\row closed a table row that contained no \\cell marks"
337
+ });
338
+ return;
339
+ }
340
+ this.tableRows.push({ cells: this.rowCells });
341
+ if (this.tableColumnRights.length === 0) this.tableColumnRights = [...this.pendingCellRights];
342
+ this.rowCells = [];
343
+ }
344
+ closeTable() {
345
+ if (this.tableRows.length === 0) return;
346
+ const columnCount = Math.max(...this.tableRows.map((row) => row.cells.length));
347
+ this.blocks.push({
348
+ kind: "table",
349
+ rows: this.tableRows,
350
+ columnWidthsPt: this.columnWidths(columnCount)
351
+ });
352
+ this.tableRows = [];
353
+ this.tableColumnRights = [];
354
+ }
355
+ columnWidths(columnCount) {
356
+ const rights = this.tableColumnRights;
357
+ const widths = [];
358
+ let previous = this.rowLeftTwips;
359
+ for (const right of rights.slice(0, columnCount)) {
360
+ widths.push(twipsToPoints(right - previous));
361
+ previous = right;
362
+ }
363
+ const usable = twipsToPoints(this.header.page.paperWidthTwips - this.header.page.marginLeftTwips - this.header.page.marginRightTwips);
364
+ if (widths.length !== columnCount || widths.some((width) => width <= 0)) {
365
+ this.sink({
366
+ code: RtfDiagnosticCodes.TABLE_COLUMN_WIDTH_INVALID,
367
+ severity: "warning",
368
+ message: "the row's \\cellxN boundaries do not describe increasing column widths for every column; falling back to an even split of the page's text width"
369
+ });
370
+ return Array.from({ length: columnCount }, () => usable / columnCount);
371
+ }
372
+ return widths;
373
+ }
374
+ addBlock(block) {
375
+ this.flushRun();
376
+ this.blocks.push(block);
377
+ }
378
+ endSection(pageSize, margins, para) {
379
+ this.endParagraph(para, false);
380
+ this.closeTable();
381
+ if (this.blocks.length === 0 && this.sections.length > 0) return;
382
+ this.sections.push({
383
+ pageSize,
384
+ margins,
385
+ blocks: this.blocks
386
+ });
387
+ this.blocks = [];
388
+ }
389
+ finish(metadata, pageSize, margins, para) {
390
+ this.endSection(pageSize, margins, para);
391
+ if (this.sections.length === 0) this.sections.push({
392
+ pageSize,
393
+ margins,
394
+ blocks: []
395
+ });
396
+ return {
397
+ kind: "wordprocessing",
398
+ metadata,
399
+ sections: this.sections
400
+ };
401
+ }
402
+ };
403
+ function buildRunFields(char, fontName, color, hyperlink) {
404
+ return {
405
+ ...char.bold ? { bold: true } : {},
406
+ ...char.italic ? { italic: true } : {},
407
+ ...char.underline ? { underline: true } : {},
408
+ ...char.strike ? { strike: true } : {},
409
+ ...fontName === void 0 || fontName.length === 0 ? {} : { fontFamily: fontName },
410
+ sizePt: halfPointsToPoints(char.sizeHalfPoints),
411
+ ...color === void 0 ? {} : { color },
412
+ ...hyperlink === void 0 ? {} : { hyperlink }
413
+ };
414
+ }
415
+ function buildPicture(picture, sink) {
416
+ if (picture.format === void 0) {
417
+ sink({
418
+ code: RtfDiagnosticCodes.UNSUPPORTED_PICTURE_FORMAT,
419
+ severity: "warning",
420
+ message: `a \\pict destination declared ${picture.unsupportedFormat ?? "no"} picture format; ContentImageBlock carries PNG and JPEG only, so this picture is dropped`
421
+ });
422
+ return;
423
+ }
424
+ const bytes = picture.binary.length > 0 ? Uint8Array.from(picture.binary) : hexToBytes(picture.hex);
425
+ if (bytes.length === 0) {
426
+ sink({
427
+ code: RtfDiagnosticCodes.UNSUPPORTED_PICTURE_FORMAT,
428
+ severity: "warning",
429
+ message: "a \\pict destination carried no picture payload"
430
+ });
431
+ return;
432
+ }
433
+ const scaleX = picture.scaleXPercent / 100;
434
+ const scaleY = picture.scaleYPercent / 100;
435
+ const widthPt = picture.widthGoalTwips === void 0 ? picture.widthPixels === void 0 ? void 0 : pixelsToPoints(picture.widthPixels) : twipsToPoints(picture.widthGoalTwips);
436
+ const heightPt = picture.heightGoalTwips === void 0 ? picture.heightPixels === void 0 ? void 0 : pixelsToPoints(picture.heightPixels) : twipsToPoints(picture.heightGoalTwips);
437
+ if (widthPt === void 0 || heightPt === void 0) {
438
+ sink({
439
+ code: RtfDiagnosticCodes.PICTURE_SIZE_UNSTATED,
440
+ severity: "warning",
441
+ message: "a \\pict destination stated neither \\picwgoalN/\\pichgoalN nor \\picwN/\\pichN, so its rendered size is unknown and the picture is dropped; decoding the payload's own intrinsic size would need an image decoder this package deliberately does not carry"
442
+ });
443
+ return;
444
+ }
445
+ const scaledWidth = widthPt * scaleX;
446
+ const scaledHeight = heightPt * scaleY;
447
+ if (scaledWidth <= 0 || scaledHeight <= 0) {
448
+ sink({
449
+ code: RtfDiagnosticCodes.PICTURE_SIZE_UNSTATED,
450
+ severity: "warning",
451
+ message: "a \\pict destination's stated size scaled to zero or less, which ContentImageBlock cannot express"
452
+ });
453
+ return;
454
+ }
455
+ return {
456
+ kind: "image",
457
+ format: picture.format,
458
+ base64: bytesToBase64(bytes),
459
+ widthPt: scaledWidth,
460
+ heightPt: scaledHeight
461
+ };
462
+ }
463
+ function defaultPictureState() {
464
+ return {
465
+ format: void 0,
466
+ unsupportedFormat: void 0,
467
+ widthGoalTwips: void 0,
468
+ heightGoalTwips: void 0,
469
+ widthPixels: void 0,
470
+ heightPixels: void 0,
471
+ scaleXPercent: 100,
472
+ scaleYPercent: 100,
473
+ hex: "",
474
+ binary: []
475
+ };
476
+ }
477
+ function toggleValue(param) {
478
+ return param === void 0 || param !== 0;
479
+ }
480
+ function readRtfDetail(input, options) {
481
+ options.signal?.throwIfAborted();
482
+ const maxInputBytes = options.maxInputBytes ?? 67108864;
483
+ if (input.length > maxInputBytes) throw new RtfInputTooLargeError(input.length, maxInputBytes);
484
+ const maxGroupDepth = options.maxGroupDepth ?? 256;
485
+ const diagnostics = [];
486
+ const callerSink = options.sink;
487
+ const sink = (diagnostic) => {
488
+ diagnostics.push(diagnostic);
489
+ callerSink?.(diagnostic);
490
+ };
491
+ const tokens = tokenizeRtf(input);
492
+ assertRtfHeaderPresent(tokens);
493
+ const header = readRtfHeader(tokens, sink);
494
+ const builder = new ContentBuilder(header, sink);
495
+ const pageSize = {
496
+ widthPt: twipsToPoints(header.page.paperWidthTwips),
497
+ heightPt: twipsToPoints(header.page.paperHeightTwips)
498
+ };
499
+ const margins = {
500
+ topPt: twipsToPoints(header.page.marginTopTwips),
501
+ rightPt: twipsToPoints(header.page.marginRightTwips),
502
+ bottomPt: twipsToPoints(header.page.marginBottomTwips),
503
+ leftPt: twipsToPoints(header.page.marginLeftTwips)
504
+ };
505
+ const root = {
506
+ destination: "body",
507
+ uc: 1,
508
+ char: defaultCharacterState(),
509
+ para: defaultParagraphState(),
510
+ field: void 0,
511
+ picture: void 0,
512
+ inUnicodeWrapper: false
513
+ };
514
+ const stack = [root];
515
+ let state = root;
516
+ let pendingBytes = [];
517
+ const activeCodepage = () => {
518
+ return (state.char.fontIndex === void 0 ? void 0 : header.fonts.get(state.char.fontIndex)?.codepage) ?? header.codepage;
519
+ };
520
+ const flushBytes = () => {
521
+ if (pendingBytes.length === 0) return;
522
+ const text = decodeCodepageBytes(Uint8Array.from(pendingBytes), activeCodepage(), sink);
523
+ pendingBytes = [];
524
+ emitText(text);
525
+ };
526
+ const emitText = (text) => {
527
+ if (state.destination === "body") {
528
+ const hyperlink = state.field === void 0 ? void 0 : hyperlinkFromInstruction(state.field.instruction);
529
+ builder.appendText(text, state.char, hyperlink);
530
+ return;
531
+ }
532
+ if (state.destination === "fieldInstruction" && state.field !== void 0) state.field.instruction += text;
533
+ };
534
+ let index = 0;
535
+ let textOffset = 0;
536
+ while (index < tokens.length) {
537
+ const token = tokens[index];
538
+ if (token === void 0) break;
539
+ if (token.kind === "groupStart") {
540
+ flushBytes();
541
+ const head = groupHead(tokens, index);
542
+ const known = head.destination === void 0 ? void 0 : DESTINATION_KINDS.get(head.destination);
543
+ const isHeaderTable = head.destination !== void 0 && HEADER_DESTINATIONS.has(head.destination);
544
+ const wrapperChild = state.inUnicodeWrapper;
545
+ const kind = isHeaderTable || wrapperChild && head.destination !== "ud" ? "skip" : known ?? (head.ignorable ? "skip" : state.destination);
546
+ if (head.destination !== void 0 && !isHeaderTable) {
547
+ if (head.ignorable && known === void 0) sink({
548
+ code: RtfDiagnosticCodes.UNKNOWN_DESTINATION_SKIPPED,
549
+ severity: "info",
550
+ message: `the ignorable destination \\${head.destination} is not recognised and its content is discarded, as the specification requires`
551
+ });
552
+ else if (known === "skip" && !SILENT_SKIP_DESTINATIONS.has(head.destination)) sink({
553
+ code: RtfDiagnosticCodes.CONTENT_DESTINATION_SKIPPED,
554
+ severity: "warning",
555
+ message: `the \\${head.destination} destination's content is discarded: no ContentDocument position carries it`
556
+ });
557
+ }
558
+ if (kind === "skip") {
559
+ index = matchingGroupEnd(tokens, index) + 1;
560
+ textOffset = 0;
561
+ continue;
562
+ }
563
+ if (stack.length >= maxGroupDepth) throw new RtfNestingLimitExceededError(maxGroupDepth);
564
+ const child = cloneGroupState(state);
565
+ child.inUnicodeWrapper = kind === "unicodeWrapper";
566
+ if (known !== void 0) {
567
+ child.destination = kind;
568
+ if (head.destination === "field") child.field = { instruction: "" };
569
+ if (kind === "picture") child.picture = defaultPictureState();
570
+ index = head.contentStart;
571
+ } else index += 1;
572
+ stack.push(child);
573
+ state = child;
574
+ textOffset = 0;
575
+ continue;
576
+ }
577
+ if (token.kind === "groupEnd") {
578
+ flushBytes();
579
+ if (state.destination === "picture" && state.picture !== void 0) {
580
+ const image = buildPicture(state.picture, sink);
581
+ if (image !== void 0) builder.addBlock(image);
582
+ }
583
+ if (stack.length > 1) {
584
+ stack.pop();
585
+ const parent = stack[stack.length - 1];
586
+ if (parent !== void 0) state = parent;
587
+ } else sink({
588
+ code: RtfDiagnosticCodes.UNBALANCED_GROUP,
589
+ severity: "warning",
590
+ message: "a closing brace appeared with no group open; the extra brace is ignored",
591
+ tokenIndex: index
592
+ });
593
+ index += 1;
594
+ textOffset = 0;
595
+ continue;
596
+ }
597
+ if (token.kind === "text") {
598
+ const slice = textOffset === 0 ? token.bytes : token.bytes.subarray(textOffset);
599
+ if (state.destination === "picture" && state.picture !== void 0) state.picture.hex += asciiStringFromBytes(slice);
600
+ else appendBytes(pendingBytes, slice);
601
+ index += 1;
602
+ textOffset = 0;
603
+ continue;
604
+ }
605
+ if (token.kind === "binary") {
606
+ if (state.destination === "picture" && state.picture !== void 0) appendBytes(state.picture.binary, token.bytes);
607
+ index += 1;
608
+ continue;
609
+ }
610
+ if (token.kind === "hex") {
611
+ if (state.destination === "picture" && state.picture !== void 0) state.picture.binary.push(token.byte);
612
+ else pendingBytes.push(token.byte);
613
+ index += 1;
614
+ continue;
615
+ }
616
+ if (token.kind === "controlSymbol") {
617
+ const text = SPECIAL_SYMBOL_TEXT.get(token.symbol);
618
+ if (text !== void 0) {
619
+ flushBytes();
620
+ emitText(text);
621
+ }
622
+ index += 1;
623
+ continue;
624
+ }
625
+ if (token.name === "u") {
626
+ flushBytes();
627
+ const code = token.param;
628
+ if (code !== void 0) emitText(String.fromCharCode(code < 0 ? code + 65536 : code));
629
+ const skipped = skipUnicodeFallback(tokens, {
630
+ index: index + 1,
631
+ textOffset: 0
632
+ }, state.uc);
633
+ index = skipped.index;
634
+ textOffset = skipped.textOffset;
635
+ continue;
636
+ }
637
+ const special = SPECIAL_CHARACTER_TEXT.get(token.name);
638
+ if (special !== void 0) {
639
+ flushBytes();
640
+ emitText(special);
641
+ index += 1;
642
+ continue;
643
+ }
644
+ flushBytes();
645
+ applyControlWord(token.name, token.param, state, builder, header, sink);
646
+ index += 1;
647
+ }
648
+ flushBytes();
649
+ if (stack.length > 1) sink({
650
+ code: RtfDiagnosticCodes.UNBALANCED_GROUP,
651
+ severity: "warning",
652
+ message: `${String(stack.length - 1)} group(s) were still open at the end of the input; each is treated as closing there`
653
+ });
654
+ return {
655
+ document: builder.finish(header.metadata, pageSize, margins, root.para),
656
+ diagnostics
657
+ };
658
+ }
659
+ function assertRtfHeaderPresent(tokens) {
660
+ const first = tokens[0];
661
+ const second = tokens[1];
662
+ if (first?.kind !== "groupStart" || second?.kind !== "controlWord" || second.name !== "rtf") throw new RtfNotAnRtfDocumentError();
663
+ }
664
+ function applyPictureControlWord(name, param, picture) {
665
+ const format = PICTURE_FORMATS.get(name);
666
+ if (format !== void 0) {
667
+ picture.format = format;
668
+ return;
669
+ }
670
+ switch (name) {
671
+ case "emfblip":
672
+ case "macpict":
673
+ case "wmetafile":
674
+ case "pmmetafile":
675
+ case "dibitmap":
676
+ case "wbitmap":
677
+ picture.unsupportedFormat = `\\${name}`;
678
+ return;
679
+ case "picwgoal":
680
+ picture.widthGoalTwips = param;
681
+ return;
682
+ case "pichgoal":
683
+ picture.heightGoalTwips = param;
684
+ return;
685
+ case "picw":
686
+ picture.widthPixels = param;
687
+ return;
688
+ case "pich":
689
+ picture.heightPixels = param;
690
+ return;
691
+ case "picscalex":
692
+ if (param !== void 0) picture.scaleXPercent = param;
693
+ return;
694
+ case "picscaley":
695
+ if (param !== void 0) picture.scaleYPercent = param;
696
+ return;
697
+ default: return;
698
+ }
699
+ }
700
+ function applyCharacterControlWord(name, param, state, header) {
701
+ switch (name) {
702
+ case "plain":
703
+ state.char = defaultCharacterState();
704
+ return true;
705
+ case "b":
706
+ state.char.bold = toggleValue(param);
707
+ return true;
708
+ case "i":
709
+ state.char.italic = toggleValue(param);
710
+ return true;
711
+ case "strike":
712
+ state.char.strike = toggleValue(param);
713
+ return true;
714
+ case "v":
715
+ state.char.hidden = toggleValue(param);
716
+ return true;
717
+ case "ulnone":
718
+ state.char.underline = false;
719
+ return true;
720
+ case "f":
721
+ state.char.fontIndex = param ?? header.defaultFontIndex;
722
+ return true;
723
+ case "fs":
724
+ state.char.sizeHalfPoints = param ?? 24;
725
+ return true;
726
+ case "cf":
727
+ state.char.colorIndex = param;
728
+ return true;
729
+ case "uc":
730
+ if (param !== void 0 && param >= 0) state.uc = param;
731
+ return true;
732
+ default:
733
+ if (name.startsWith("ul") && name !== "ulc") {
734
+ state.char.underline = toggleValue(param);
735
+ return true;
736
+ }
737
+ return false;
738
+ }
739
+ }
740
+ function applyParagraphControlWord(name, param, state) {
741
+ const alignment = ALIGNMENTS.get(name);
742
+ if (alignment !== void 0) {
743
+ state.para.alignment = alignment;
744
+ return true;
745
+ }
746
+ switch (name) {
747
+ case "pard":
748
+ state.para = defaultParagraphState();
749
+ return true;
750
+ case "s":
751
+ state.para.styleIndex = param;
752
+ return true;
753
+ case "outlinelevel":
754
+ state.para.outlineLevel = param === void 0 || param > 8 ? void 0 : param;
755
+ return true;
756
+ case "li":
757
+ case "lin":
758
+ state.para.indentLeftTwips = param ?? 0;
759
+ return true;
760
+ case "fi":
761
+ state.para.indentFirstLineTwips = param ?? 0;
762
+ return true;
763
+ case "sb":
764
+ state.para.spaceBeforeTwips = param ?? 0;
765
+ return true;
766
+ case "sa":
767
+ state.para.spaceAfterTwips = param ?? 0;
768
+ return true;
769
+ case "sl":
770
+ state.para.lineSpacingTwips = param;
771
+ return true;
772
+ case "slmult":
773
+ state.para.lineSpacingIsMultiple = toggleValue(param);
774
+ return true;
775
+ case "pagebb":
776
+ state.para.pageBreakBefore = true;
777
+ return true;
778
+ case "ls":
779
+ state.para.listOverrideIndex = param;
780
+ return true;
781
+ case "ilvl":
782
+ state.para.listLevel = param ?? 0;
783
+ return true;
784
+ case "intbl":
785
+ state.para.inTable = true;
786
+ return true;
787
+ default: return false;
788
+ }
789
+ }
790
+ function applyStructureControlWord(name, param, state, builder, sink) {
791
+ switch (name) {
792
+ case "par":
793
+ builder.endParagraph(state.para, true);
794
+ return true;
795
+ case "trowd":
796
+ state.para.inTable = true;
797
+ builder.startRowDefinition();
798
+ return true;
799
+ case "trleft":
800
+ builder.setRowLeft(param ?? 0);
801
+ return true;
802
+ case "cellx":
803
+ if (param !== void 0) builder.addCellBoundary(param);
804
+ return true;
805
+ case "cell":
806
+ builder.endCell(state.para);
807
+ return true;
808
+ case "row":
809
+ builder.endRow(state.para);
810
+ state.para.inTable = false;
811
+ return true;
812
+ case "nestcell":
813
+ case "nestrow":
814
+ sink({
815
+ code: RtfDiagnosticCodes.NESTED_TABLE_FLATTENED,
816
+ severity: "warning",
817
+ message: "a nested table's cell/row marks are read as ordinary cell content; the inner table's own structure is not reconstructed"
818
+ });
819
+ return true;
820
+ case "page":
821
+ builder.endParagraph(state.para, false);
822
+ builder.addBlock({ kind: "pageBreak" });
823
+ return true;
824
+ case "sect":
825
+ builder.endParagraph(state.para, true);
826
+ return true;
827
+ case "sectd": return true;
828
+ default: return false;
829
+ }
830
+ }
831
+ function applyControlWord(name, param, state, builder, header, sink) {
832
+ const picture = state.picture;
833
+ if (state.destination === "picture" && picture !== void 0) {
834
+ applyPictureControlWord(name, param, picture);
835
+ return;
836
+ }
837
+ if (applyCharacterControlWord(name, param, state, header)) return;
838
+ if (applyParagraphControlWord(name, param, state)) return;
839
+ applyStructureControlWord(name, param, state, builder, sink);
840
+ }
841
+ function readRtfContent(input, options = {}) {
842
+ return readRtfDetail(typeof input === "string" ? rtfBytesFromLatin1(input) : input, options);
843
+ }
844
+ function readRtf(input, options = {}) {
845
+ const { document, diagnostics } = readRtfContent(input, options);
846
+ return {
847
+ documentPackage: assembleTree(document),
848
+ diagnostics
849
+ };
850
+ }
851
+ //#endregion
852
+ export { readRtf, readRtfContent };