@zyro-sec/latex 1.0.2 → 1.0.3

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.
@@ -1,298 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { parseLatex } from "./parser"
3
- import { LatexParseError } from "./types"
4
-
5
- describe("parseLatex", () => {
6
- test("parses fractions and scripts structurally", () => {
7
- expect(parseLatex(String.raw`\frac{x^2+1}{y_0}`)).toMatchObject({
8
- type: "fraction",
9
- bar: true,
10
- numerator: { type: "row" },
11
- denominator: { type: "scripts" },
12
- })
13
- })
14
-
15
- test("parses matrix environments into rows and cells", () => {
16
- expect(parseLatex(String.raw`\begin{pmatrix}a & b \\ c & d\end{pmatrix}`)).toMatchObject({
17
- type: "matrix",
18
- environment: "pmatrix",
19
- rows: [
20
- [
21
- { type: "symbol", value: "a" },
22
- { type: "symbol", value: "b" },
23
- ],
24
- [
25
- { type: "symbol", value: "c" },
26
- { type: "symbol", value: "d" },
27
- ],
28
- ],
29
- })
30
- })
31
-
32
- test("accepts array column specs and starred alignment environments", () => {
33
- expect(parseLatex(String.raw`\begin{array}{cc}a & b \\ c & d\end{array}`)).toMatchObject({
34
- type: "matrix",
35
- environment: "array",
36
- columns: "cc",
37
- rows: [
38
- [{}, {}],
39
- [{}, {}],
40
- ],
41
- })
42
- expect(parseLatex(String.raw`\begin{align*}a &= b \\ c &= d\end{align*}`)).toMatchObject({
43
- type: "matrix",
44
- environment: "align",
45
- })
46
- })
47
-
48
- test("preserves double norm delimiters without changing single bars", () => {
49
- expect(parseLatex(String.raw`\|v\|`, { strict: true })).toMatchObject({
50
- type: "row",
51
- body: [{ value: "║" }, { value: "v" }, { value: "║" }],
52
- })
53
- expect(parseLatex(String.raw`\left\|v\right\|`, { strict: true })).toMatchObject({
54
- type: "delimited",
55
- left: "║",
56
- right: "║",
57
- })
58
- expect(parseLatex(String.raw`\left|v\right|`, { strict: true })).toMatchObject({
59
- type: "delimited",
60
- left: "│",
61
- right: "│",
62
- })
63
- })
64
-
65
- test("matches the whole right command and keeps nested delimiters", () => {
66
- expect(parseLatex(String.raw`\left(A\rightarrow B\right)`, { strict: true })).toMatchObject({
67
- type: "delimited",
68
- left: "(",
69
- body: { type: "row", body: [{ value: "A" }, { value: "→" }, { value: "B" }] },
70
- right: ")",
71
- })
72
- expect(parseLatex(String.raw`\left(\left[A\right]\rightharpoonup B\right)`)).toMatchObject({
73
- type: "delimited",
74
- body: { type: "row", body: [{ type: "delimited" }, { value: "⇀" }, { value: "B" }] },
75
- })
76
- expect(() => parseLatex(String.raw`\left(A\rightarrow B`, { strict: true })).toThrow(/Missing \\right/)
77
- expect(() => parseLatex(String.raw`\left(A\rightward B\right)`, { strict: true })).toThrow(
78
- /Unsupported command \\rightward/,
79
- )
80
- })
81
-
82
- test("accepts empty leading, interior, and trailing environment cells", () => {
83
- expect(parseLatex(String.raw`\begin{aligned}&=x\\&=y\end{aligned}`, { strict: true })).toMatchObject({
84
- type: "matrix",
85
- environment: "aligned",
86
- rows: [
87
- [
88
- { type: "row", body: [] },
89
- { type: "row", body: [{ value: "=" }, { value: "x" }] },
90
- ],
91
- [
92
- { type: "row", body: [] },
93
- { type: "row", body: [{ value: "=" }, { value: "y" }] },
94
- ],
95
- ],
96
- })
97
- expect(parseLatex(String.raw`\begin{matrix}a&&\\&b&\end{matrix}`, { strict: true })).toMatchObject({
98
- type: "matrix",
99
- rows: [
100
- [{ value: "a" }, { type: "row", body: [] }, { type: "row", body: [] }],
101
- [{ type: "row", body: [] }, { value: "b" }, { type: "row", body: [] }],
102
- ],
103
- })
104
- expect(parseLatex(String.raw`\begin{matrix}a\\\end{matrix}`)).toMatchObject({ rows: [[{ value: "a" }]] })
105
- expect(parseLatex(String.raw`\begin{matrix}\\\end{matrix}`)).toMatchObject({ rows: [[{ type: "row", body: [] }]] })
106
- })
107
-
108
- test("parses displaylines as separate gathered rows", () => {
109
- expect(parseLatex(String.raw`\displaylines{x=1\\y=2}`, { strict: true })).toMatchObject({
110
- type: "matrix",
111
- environment: "gathered",
112
- rows: [
113
- [{ type: "row", body: [{ value: "x" }, { value: "=" }, { value: "1" }] }],
114
- [{ type: "row", body: [{ value: "y" }, { value: "=" }, { value: "2" }] }],
115
- ],
116
- })
117
- expect(parseLatex(String.raw`\displaylines{\frac{1}{2}\\{y}}+z`)).toMatchObject({
118
- type: "row",
119
- body: [{ type: "matrix", rows: [[{ type: "fraction" }], [{ value: "y" }]] }, { value: "+" }, { value: "z" }],
120
- })
121
- expect(() => parseLatex(String.raw`\displaylines[l]{x\\y}`, { strict: true })).toThrow(LatexParseError)
122
- expect(() => parseLatex(String.raw`\displaylines{x\\y`, { strict: true })).toThrow(LatexParseError)
123
- })
124
-
125
- test.each([
126
- ["", undefined],
127
- ["[]", undefined],
128
- ["[l]", "left"],
129
- ["[r]", "right"],
130
- ] as const)("parses continued fraction alignment %s before its arguments", (option, numeratorAlign) => {
131
- expect(parseLatex(String.raw`\cfrac${option}{1}{23}`, { strict: true })).toEqual({
132
- type: "fraction",
133
- numerator: { type: "symbol", value: "1", role: "ordinary" },
134
- denominator: {
135
- type: "row",
136
- body: [
137
- { type: "symbol", value: "2", role: "ordinary" },
138
- { type: "symbol", value: "3", role: "ordinary" },
139
- ],
140
- },
141
- bar: true,
142
- ...(numeratorAlign ? { numeratorAlign } : {}),
143
- })
144
- })
145
-
146
- test.each(["[c]", "[lr]", "[left]", "[l"])("rejects unsupported continued fraction alignment %s", (option) => {
147
- expect(() => parseLatex(String.raw`\cfrac${option}{1}{2}`, { strict: true })).toThrow(LatexParseError)
148
- })
149
-
150
- test("retains normalized array columns including edge and double rules", () => {
151
- expect(parseLatex(String.raw`\begin{array}{ | l || c r | }a&b&c\end{array}`, { strict: true })).toMatchObject({
152
- type: "matrix",
153
- environment: "array",
154
- columns: "|l||cr|",
155
- })
156
- })
157
-
158
- test.each(["", "||", "p{2cm}", "*{2}{c}", "c@{}c", "lXr"])("rejects unsupported array columns %s", (columns) => {
159
- expect(() => parseLatex(String.raw`\begin{array}{${columns}}a\end{array}`, { strict: true })).toThrow(
160
- LatexParseError,
161
- )
162
- })
163
-
164
- test("requires an array column specification", () => {
165
- expect(() => parseLatex(String.raw`\begin{array}a&b\end{array}`, { strict: true })).toThrow(LatexParseError)
166
- })
167
-
168
- test("emits structural braces while keeping annotations as scripts", () => {
169
- expect(parseLatex(String.raw`\overbrace{a+b}^{n}`, { strict: true })).toMatchObject({
170
- type: "scripts",
171
- base: { type: "brace", position: "over", body: { type: "row" } },
172
- superscript: { value: "n" },
173
- })
174
- expect(parseLatex(String.raw`\underbrace{x}_{k}`, { strict: true })).toMatchObject({
175
- type: "scripts",
176
- base: { type: "brace", position: "under", body: { value: "x" } },
177
- subscript: { value: "k" },
178
- })
179
- })
180
-
181
- test("recognizes named braces and rejects unsupported delimiter commands in strict mode", () => {
182
- expect(parseLatex(String.raw`\left\lbrace x\right\rbrace`, { strict: true })).toMatchObject({
183
- type: "delimited",
184
- left: "{",
185
- right: "}",
186
- })
187
- expect(parseLatex(String.raw`\lbrace x\rbrace`, { strict: true })).toMatchObject({
188
- type: "row",
189
- body: [{ value: "{" }, { value: "x" }, { value: "}" }],
190
- })
191
- for (const source of [
192
- String.raw`\left\unknown x\right)`,
193
- String.raw`\left(x\right\unknown`,
194
- String.raw`\big\unknown`,
195
- String.raw`\left(x\middle\unknown y\right)`,
196
- ]) {
197
- expect(() => parseLatex(source, { strict: true })).toThrow(/Unsupported delimiter \\unknown/)
198
- }
199
- })
200
-
201
- test("expands user macros", () => {
202
- expect(parseLatex(String.raw`\R \to \R`, { macros: { "\\R": String.raw`\mathbb{R}` } })).toMatchObject({
203
- type: "row",
204
- })
205
- })
206
-
207
- test("reports useful strict-mode errors", () => {
208
- expect(() => parseLatex(String.raw`\definitelyUnknown{x}`, { strict: true })).toThrow(LatexParseError)
209
- })
210
-
211
- test("keeps escaped braces inside raw text groups", () => {
212
- expect(parseLatex(String.raw`\text{left \{ only}`)).toMatchObject({
213
- type: "text",
214
- value: "left { only",
215
- })
216
- expect(parseLatex(String.raw`\text{right \} only}`)).toMatchObject({
217
- type: "text",
218
- value: "right } only",
219
- })
220
- })
221
-
222
- test("supports starred named operators and limits modifiers", () => {
223
- expect(parseLatex(String.raw`\operatorname*{arg\,max}_{x}`)).toMatchObject({
224
- type: "scripts",
225
- base: { type: "operator", value: "arg max", limits: true },
226
- })
227
- expect(parseLatex(String.raw`\int\limits_0^1`)).toMatchObject({
228
- type: "scripts",
229
- base: { type: "operator", value: "∫", limits: true },
230
- })
231
- expect(parseLatex(String.raw`\sum\nolimits_{i=1}`)).toMatchObject({
232
- type: "scripts",
233
- base: { type: "operator", value: "∑", limits: false },
234
- })
235
- })
236
-
237
- test("interprets operator spacing and preserves roman text whitespace", () => {
238
- expect(parseLatex(String.raw`\operatorname{arg\,max}`, { strict: true })).toEqual({
239
- type: "operator",
240
- value: "arg max",
241
- limits: false,
242
- })
243
- expect(parseLatex(String.raw`\textrm{ if }`, { strict: true })).toEqual({
244
- type: "variant",
245
- variant: "normal",
246
- body: { type: "text", value: " if " },
247
- })
248
- })
249
-
250
- test("accepts the control space in strict mode", () => {
251
- expect(parseLatex(String.raw`a\ b`, { strict: true })).toMatchObject({
252
- type: "row",
253
- body: [
254
- { type: "symbol", value: "a" },
255
- { type: "space", width: 1 },
256
- { type: "symbol", value: "b" },
257
- ],
258
- })
259
- expect(() => parseLatex(String.raw`\forall \varepsilon>0\ \exists K\in\mathbb{N}`, { strict: true })).not.toThrow()
260
- })
261
-
262
- test("accepts a backslash before a newline, a tab, or a line break as a control space", () => {
263
- for (const whitespace of ["\n", "\t", "\r\n"]) {
264
- expect(parseLatex(`a\\${whitespace}b`, { strict: true })).toMatchObject({
265
- type: "row",
266
- body: [
267
- { type: "symbol", value: "a" },
268
- { type: "space", width: 1 },
269
- { type: "symbol", value: "b" },
270
- ],
271
- })
272
- }
273
- })
274
-
275
- test("bounds source and recursive macro expansion", () => {
276
- expect(() => parseLatex("12345", { maxSourceLength: 4 })).toThrow(/4-character limit/)
277
- expect(() =>
278
- parseLatex(String.raw`\a`, {
279
- macros: { a: String.raw`\a\a` },
280
- maxExpandedLength: 64,
281
- }),
282
- ).toThrow(/64-character limit/)
283
- expect(() => parseLatex(String.raw`\a`, { macros: { a: "{{x}}" }, maxDepth: 1 })).toThrow(/1-level limit/)
284
- expect(() => parseLatex("x", { maxSourceLength: 0 })).toThrow(RangeError)
285
- })
286
-
287
- test("fails quickly when malformed environments cannot advance", () => {
288
- expect(() => parseLatex(String.raw`\begin{matrix}]`)).toThrow(/Missing \\end{matrix}/)
289
- expect(() => parseLatex(String.raw`\begin{matrix}x}`)).toThrow(/Unexpected "}" in matrix/)
290
- expect(() => parseLatex(String.raw`\begin{matrix}&}`)).toThrow(/Unexpected "}" in matrix/)
291
- })
292
-
293
- test("bounds structural nesting with a parse error instead of overflowing the stack", () => {
294
- const source = "{".repeat(80) + "x" + "}".repeat(80)
295
- expect(() => parseLatex(source, { maxDepth: 64 })).toThrow(/64-level limit/)
296
- expect(() => parseLatex(String.raw`\frac`.repeat(80) + "x", { maxDepth: 64 })).toThrow(/64-level limit/)
297
- })
298
- })
@@ -1,87 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { renderLatex, renderLatexToString } from "./render"
3
-
4
- describe("renderLatexToString", () => {
5
- test("renders a fraction with a centered rule", () => {
6
- expect(renderLatexToString(String.raw`\frac{x+1}{y-1}`)).toBe([" x + 1", "───────", " y - 1"].join("\n"))
7
- })
8
-
9
- test.each([
10
- [String.raw`E = mc^2`, "E = mc²"],
11
- [String.raw`a_n`, "aₙ"],
12
- [String.raw`x_i^2`, "x²ᵢ"],
13
- [String.raw`x^{}`, "x"],
14
- [String.raw`x_{}`, "x"],
15
- [String.raw`x^{}_{}`, "x"],
16
- [String.raw`x^m_1`, " m\nx\n 1"],
17
- [String.raw`x^2_q`, " 2\nx\n q"],
18
- [String.raw`x^{\frac{1}{2}}_1`, " 1\n ───\n 2\nx\n 1"],
19
- ])("compacts scripts only when every script is supported: %s", (source, expected) => {
20
- expect(renderLatexToString(source)).toBe(expected)
21
- })
22
-
23
- test("respects script and display mode options", () => {
24
- expect(renderLatexToString(String.raw`x_i^2`, { compactScripts: false })).toBe(" 2\nx\n i")
25
- expect(renderLatexToString(String.raw`\sum_1^n`, { displayMode: false })).toBe("∑ⁿ₁")
26
- expect(renderLatexToString(String.raw`\sum_1^n`, { compactScripts: false })).toBe("n\n∑\n1")
27
- })
28
-
29
- test("centers binomials around an empty math-axis row", () => {
30
- expect(renderLatexToString(String.raw`P = \binom{n}{k}`)).toBe([" ⎛ n ⎞", "P = ⎜ ⎟", " ⎝ k ⎠"].join("\n"))
31
- })
32
-
33
- test("renders roots with a vinculum", () => {
34
- expect(renderLatexToString(String.raw`\sqrt{x^2+y^2}`)).toBe([" ╭───────", "╰╯x² + y²"].join("\n"))
35
- })
36
-
37
- test("renders matrices with stretching delimiters", () => {
38
- expect(renderLatexToString(String.raw`\begin{pmatrix}a & b \\ c & d\end{pmatrix}`)).toBe(
39
- ["⎛a b⎞", "⎜ ⎟", "⎝c d⎠"].join("\n"),
40
- )
41
- })
42
-
43
- test("places display operator limits above and below", () => {
44
- expect(renderLatexToString(String.raw`\sum_{i=1}^{n} i^2`)).toBe([" n", " ∑ i²", "i = 1"].join("\n"))
45
- })
46
-
47
- test("returns intrinsic geometry and baseline", () => {
48
- const layout = renderLatex(String.raw`\frac{1}{2}`)
49
- expect(layout.width).toBe(3)
50
- expect(layout.height).toBe(3)
51
- expect(layout.baseline).toBe(1)
52
- })
53
-
54
- test("renders blackboard, calligraphic, and fraktur alphabets", () => {
55
- expect(renderLatexToString(String.raw`\mathbb{R} \to \mathcal{C} \times \mathfrak{g}`)).toBe("ℝ → 𝒞 × 𝔤")
56
- })
57
-
58
- test("preserves inherited styles through nested variants and colors", () => {
59
- const layout = renderLatex(String.raw`\mathbf{\mathsf{\textcolor{red}{\mathit{x}}}}`)
60
- expect(layout.cells[0][0]).toEqual({ char: "x", style: { bold: true, italic: true, color: "red" } })
61
- })
62
-
63
- test("renders nested fractions without flattening their structure", () => {
64
- const result = renderLatexToString(String.raw`\frac{1}{1+\frac{1}{x}}`)
65
- expect(result.split("\n")).toHaveLength(5)
66
- expect(result.match(/─/g)?.length).toBeGreaterThanOrEqual(10)
67
- })
68
-
69
- test("renders common textbook structures", () => {
70
- const result = renderLatexToString(String.raw`\left[\frac{-b \pm \sqrt{b^2-4ac}}{2a}\right]`)
71
- expect(result).toContain("±")
72
- expect(result).toContain("╰╯")
73
- expect(result).toContain("─")
74
- expect(result).toContain("⎡")
75
- expect(result).toContain("⎦")
76
- })
77
-
78
- test("places fallback combining negation after the base symbol", () => {
79
- const result = renderLatexToString(String.raw`\not\rightarrow`)
80
- expect(Array.from(result)).toEqual(["→", "̸"])
81
- })
82
-
83
- test("treats square brackets as ordinary interval delimiters", () => {
84
- expect(renderLatexToString(String.raw`x\in[0,1]`)).toBe("x ∈ [0,1]")
85
- expect(renderLatexToString(String.raw`[-1,1]`)).toBe("[-1,1]")
86
- })
87
- })
package/src/root.test.ts DELETED
@@ -1,69 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { renderLatex } from "./render"
3
-
4
- describe("root geometry", () => {
5
- test.each([
6
- ["x", String.raw`\frac{1}{2}`],
7
- ["x", String.raw`\sqrt{n}`],
8
- ["x", "123456789"],
9
- ["x", String.raw`\frac{123456789}{\frac{n}{m}}`],
10
- [String.raw`\frac{a}{b}`, "3"],
11
- [String.raw`\sqrt{\frac{a}{b}}`, String.raw`\sqrt{\frac{n}{m}}`],
12
- [String.raw`\text{界}`, String.raw`\text{次}`],
13
- ["", String.raw`\frac{1}{2}`],
14
- ])("preserves body %s and index %s", (bodySource, indexSource) => {
15
- const body = renderLatex(bodySource, { color: "red" })
16
- const index = renderLatex(indexSource, { color: "blue" })
17
- const root = renderLatex(String.raw`\sqrt[\textcolor{blue}{${indexSource}}]{\textcolor{red}{${bodySource}}}`)
18
- const bodyX = root.width - body.width
19
- const bodyY = root.height - body.height
20
-
21
- expect(root.cells).toHaveLength(root.height)
22
- expect(root.baseline).toBe(bodyY + body.baseline)
23
- expect(bodyX).toBeGreaterThan(index.width)
24
- expect(bodyY).toBeGreaterThanOrEqual(index.height)
25
- for (const row of root.cells) expect(row).toHaveLength(root.width)
26
- for (const [y, row] of body.cells.entries()) {
27
- for (const [x, cell] of row.entries()) expect(root.cells[bodyY + y][bodyX + x]).toEqual(cell)
28
- }
29
- for (const [y, row] of index.cells.entries()) {
30
- for (const [x, cell] of row.entries()) expect(root.cells[y][x]).toEqual(cell)
31
- }
32
- expect(root.cells.flat().filter((cell) => cell?.style?.color === "red")).toHaveLength(
33
- body.cells.flat().filter(Boolean).length,
34
- )
35
- expect(root.cells.flat().filter((cell) => cell?.style?.color === "blue")).toHaveLength(
36
- index.cells.flat().filter(Boolean).length,
37
- )
38
- })
39
-
40
- test("connects each nested overbar to a full-height stem", () => {
41
- const root = renderLatex(String.raw`\sqrt{\sqrt{\sqrt{x}}}`)
42
- expect(root.toString()).toBe([" ╭─────", " │ ╭───", " │ │ ╭─", "╰╯╰╯╰╯x"].join("\n"))
43
- expect(root.height).toBe(4)
44
- expect(root.baseline).toBe(3)
45
- for (const depth of [0, 1, 2]) {
46
- for (let y = depth; y < root.height; y++) expect(root.cells[y][depth * 2 + 1]).toBeDefined()
47
- }
48
- expect(root.cells.flat().filter((cell) => cell?.char === "x")).toHaveLength(1)
49
- })
50
-
51
- test("extends a fraction root below the math axis without moving its baseline", () => {
52
- const root = renderLatex(String.raw`\sqrt{\frac{a}{b}}`)
53
- expect(root.toString()).toBe([" ╭───", " │ a", " │───", "╰╯ b"].join("\n"))
54
- expect(root.height).toBe(4)
55
- expect(root.baseline).toBe(2)
56
- for (let y = 0; y < root.height; y++) expect(root.cells[y][1]).toBeDefined()
57
- expect(root.cells[root.baseline].map((cell) => cell?.char ?? " ").join("")).toContain("───")
58
- expect(root.cells[root.height - 1].some((cell) => cell?.char === "b")).toBe(true)
59
- })
60
-
61
- test.each([
62
- [String.raw`\sqrt{x}`, [" ╭─", "╰╯x"]],
63
- [String.raw`\sqrt[3]{x}`, ["3╭─", "╰╯x"]],
64
- [String.raw`\sqrt[\frac{1}{2}]{x}`, [" 1", "───", " 2 ╭─", " ╰╯x"]],
65
- [String.raw`\sqrt[\sqrt{n}]{x}`, [" ╭─", "╰╯n╭─", " ╰╯x"]],
66
- ])("uses the same connected construction for %s", (source, expected) => {
67
- expect(renderLatex(source).toString()).toBe(expected.join("\n"))
68
- })
69
- })