@krate/runtime 0.5.0-alpha.4 → 0.5.0-beta.2

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 (165) hide show
  1. package/dist/action-context.d.ts +5 -1
  2. package/dist/action-context.js +33 -3
  3. package/dist/action-context.test.js +26 -1
  4. package/dist/actions.d.ts +12 -1
  5. package/dist/actions.js +84 -4
  6. package/dist/actions.test.js +61 -1
  7. package/dist/assets-static.d.ts +5 -0
  8. package/dist/assets-static.js +31 -0
  9. package/dist/boundary.d.ts +12 -0
  10. package/dist/boundary.js +53 -13
  11. package/dist/cache-adapter.d.ts +113 -0
  12. package/dist/cache-adapter.js +217 -0
  13. package/dist/cache-adapter.test.d.ts +1 -0
  14. package/dist/cache-adapter.test.js +244 -0
  15. package/dist/cache-redis.d.ts +27 -0
  16. package/dist/cache-redis.js +110 -0
  17. package/dist/cache-scope.d.ts +25 -9
  18. package/dist/cache-scope.js +64 -13
  19. package/dist/cache.d.ts +1 -0
  20. package/dist/cache.js +3 -3
  21. package/dist/cache.test.js +16 -0
  22. package/dist/class-component.js +6 -0
  23. package/dist/class-component.test.js +53 -2
  24. package/dist/class-helpers.d.ts +4 -4
  25. package/dist/class-helpers.js +357 -32
  26. package/dist/class-helpers.test.d.ts +1 -0
  27. package/dist/class-helpers.test.js +169 -0
  28. package/dist/context.d.ts +16 -2
  29. package/dist/context.js +44 -3
  30. package/dist/dev-overlay.js +85 -12
  31. package/dist/dev-overlay.test.js +22 -0
  32. package/dist/dom.d.ts +15 -0
  33. package/dist/dom.js +97 -3
  34. package/dist/effect-errors.test.d.ts +1 -0
  35. package/dist/effect-errors.test.js +163 -0
  36. package/dist/effects.d.ts +8 -0
  37. package/dist/effects.js +13 -0
  38. package/dist/error-overlay.js +7 -7
  39. package/dist/handler-html.d.ts +63 -0
  40. package/dist/handler-html.js +285 -0
  41. package/dist/handler-html.test.d.ts +1 -0
  42. package/dist/handler-html.test.js +256 -0
  43. package/dist/handler-routing.d.ts +83 -0
  44. package/dist/handler-routing.js +579 -0
  45. package/dist/handler-routing.test.d.ts +1 -0
  46. package/dist/handler-routing.test.js +99 -0
  47. package/dist/handler-segments.d.ts +43 -0
  48. package/dist/handler-segments.js +115 -0
  49. package/dist/handler-segments.test.d.ts +1 -0
  50. package/dist/handler-segments.test.js +217 -0
  51. package/dist/head-tags.d.ts +51 -0
  52. package/dist/head-tags.js +329 -0
  53. package/dist/head-tags.test.d.ts +1 -0
  54. package/dist/head-tags.test.js +131 -0
  55. package/dist/highlight-bind.d.ts +42 -0
  56. package/dist/highlight-bind.js +176 -0
  57. package/dist/highlight-bind.test.d.ts +1 -0
  58. package/dist/highlight-bind.test.js +124 -0
  59. package/dist/highlight.d.ts +93 -0
  60. package/dist/highlight.js +426 -0
  61. package/dist/highlight.test.d.ts +1 -0
  62. package/dist/highlight.test.js +56 -0
  63. package/dist/hints.d.ts +19 -0
  64. package/dist/hints.js +97 -0
  65. package/dist/hook-args.d.ts +7 -0
  66. package/dist/hook-args.js +10 -0
  67. package/dist/htmlspec-attributes.d.ts +1 -0
  68. package/dist/htmlspec-attributes.js +159 -0
  69. package/dist/index.d.ts +4 -0
  70. package/dist/index.js +3 -0
  71. package/dist/jsx-types.d.ts +11 -0
  72. package/dist/krate-core.js +2 -0
  73. package/dist/krate-dev.js +75 -12
  74. package/dist/krate-f-actions.js +2 -0
  75. package/dist/krate-f-classes.js +8 -0
  76. package/dist/krate-f-helpers.js +2 -0
  77. package/dist/krate-f-highlight.js +2 -0
  78. package/dist/krate-f-list.js +2 -0
  79. package/dist/krate-f-navigation.js +2 -0
  80. package/dist/krate-f-router-lite.js +2 -0
  81. package/dist/krate-f-router.js +2 -0
  82. package/dist/krate-features.json +493 -0
  83. package/dist/krate-hydrate-lite.js +5 -5
  84. package/dist/krate-hydrate.js +5 -5
  85. package/dist/krate-runtime.js +5 -5
  86. package/dist/list.js +4 -2
  87. package/dist/metadata-routes.d.ts +75 -0
  88. package/dist/metadata-routes.js +76 -0
  89. package/dist/metadata.d.ts +222 -0
  90. package/dist/metadata.js +452 -0
  91. package/dist/metadata.test.d.ts +1 -0
  92. package/dist/metadata.test.js +167 -0
  93. package/dist/navigation-server.d.ts +27 -0
  94. package/dist/navigation-server.js +90 -0
  95. package/dist/navigation.d.ts +37 -0
  96. package/dist/navigation.js +195 -0
  97. package/dist/navigation.test.d.ts +1 -0
  98. package/dist/navigation.test.js +130 -0
  99. package/dist/node-server.d.ts +22 -0
  100. package/dist/node-server.js +436 -0
  101. package/dist/node-server.test.d.ts +1 -0
  102. package/dist/node-server.test.js +492 -0
  103. package/dist/og-files.d.ts +2 -0
  104. package/dist/og-files.js +19 -0
  105. package/dist/og.d.ts +56 -0
  106. package/dist/og.js +156 -0
  107. package/dist/patterns.test.d.ts +1 -0
  108. package/dist/patterns.test.js +98 -0
  109. package/dist/react.d.ts +47 -0
  110. package/dist/react.js +59 -1
  111. package/dist/react19.test.d.ts +1 -0
  112. package/dist/react19.test.js +176 -0
  113. package/dist/reactivity-core.test.d.ts +1 -0
  114. package/dist/reactivity-core.test.js +152 -0
  115. package/dist/reconcile.js +4 -2
  116. package/dist/request-context.d.ts +23 -0
  117. package/dist/request-context.js +45 -0
  118. package/dist/resp.d.ts +55 -0
  119. package/dist/resp.js +239 -0
  120. package/dist/router-layout.test.js +70 -0
  121. package/dist/router-nav.test.js +65 -0
  122. package/dist/router-speculation.test.d.ts +1 -0
  123. package/dist/router-speculation.test.js +25 -0
  124. package/dist/router-styles.test.d.ts +1 -0
  125. package/dist/router-styles.test.js +98 -0
  126. package/dist/router.js +175 -36
  127. package/dist/segmented-lru.d.ts +19 -0
  128. package/dist/segmented-lru.js +87 -0
  129. package/dist/server-async.test.js +43 -1
  130. package/dist/server-handler.d.ts +165 -0
  131. package/dist/server-handler.js +1826 -0
  132. package/dist/server-handler.test.d.ts +1 -0
  133. package/dist/server-handler.test.js +522 -0
  134. package/dist/server-highlight.test.d.ts +1 -0
  135. package/dist/server-highlight.test.js +32 -0
  136. package/dist/server-renderer.js +165 -720
  137. package/dist/server-renderer.test.d.ts +1 -0
  138. package/dist/server-renderer.test.js +266 -0
  139. package/dist/server.d.ts +13 -1
  140. package/dist/server.js +131 -16
  141. package/dist/server.test.js +20 -0
  142. package/dist/sha256.d.ts +1 -0
  143. package/dist/sha256.js +66 -0
  144. package/dist/sha256.test.d.ts +1 -0
  145. package/dist/sha256.test.js +13 -0
  146. package/dist/shared-isr.d.ts +31 -0
  147. package/dist/shared-isr.js +142 -0
  148. package/dist/signal.d.ts +3 -2
  149. package/dist/signal.js +163 -23
  150. package/dist/slots.js +12 -1
  151. package/dist/ssr-core-behavior.test.d.ts +1 -0
  152. package/dist/ssr-core-behavior.test.js +620 -0
  153. package/dist/ssr-core.d.ts +175 -0
  154. package/dist/ssr-core.js +940 -0
  155. package/dist/ssr-core.test.d.ts +1 -0
  156. package/dist/ssr-core.test.js +324 -0
  157. package/dist/static-memory.d.ts +3 -0
  158. package/dist/static-memory.js +47 -0
  159. package/dist/static-memory.test.d.ts +1 -0
  160. package/dist/static-memory.test.js +26 -0
  161. package/dist/test-redis.d.ts +12 -0
  162. package/dist/test-redis.js +131 -0
  163. package/dist/use-id.d.ts +8 -0
  164. package/dist/use-id.js +40 -0
  165. package/package.json +30 -2
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,124 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { krateHighlight, krateHighlightInit } from "./highlight-bind";
3
+ // A fake language chunk: wraps each line in a span so output is easy to read.
4
+ function chunk(calls) {
5
+ return {
6
+ trimSpace: (s) => s.trim(),
7
+ highlight: (code, lang) => {
8
+ calls.push(code);
9
+ if (code.length > 100)
10
+ return null;
11
+ return code
12
+ .split("\n")
13
+ .map((l) => `<span class="line"><span class="cl"><span class="k">${l}</span></span></span>`)
14
+ .join("");
15
+ },
16
+ };
17
+ }
18
+ function mount(initial, lang = "ts") {
19
+ document.body.innerHTML = `<pre class="chroma"><code data-krate-hl="${lang}" class="language-${lang}"><!--k:b-->${initial}<!--/k:b--></code></pre>`;
20
+ const code = document.querySelector("code");
21
+ const start = code.firstChild;
22
+ // What kbindText does: update the text node after the start marker, or add one.
23
+ const set = (s) => {
24
+ if (start.nextSibling && start.nextSibling.nodeType === 3)
25
+ start.nextSibling.textContent = s;
26
+ else
27
+ start.parentNode.insertBefore(document.createTextNode(s), start.nextSibling);
28
+ };
29
+ return { code, start, set };
30
+ }
31
+ const settle = async (ms) => {
32
+ await vi.advanceTimersByTimeAsync(ms);
33
+ await Promise.resolve();
34
+ };
35
+ describe("krateHighlightInit", () => {
36
+ const calls = [];
37
+ beforeEach(() => {
38
+ calls.length = 0;
39
+ vi.useFakeTimers();
40
+ window.__KRATE_HL = { ts: "/chunks/hl-ts.js" };
41
+ window.__KRATE_HL_LOAD = async () => chunk(calls);
42
+ });
43
+ afterEach(() => {
44
+ vi.useRealTimers();
45
+ delete window.__KRATE_HL;
46
+ delete window.__KRATE_HL_LOAD;
47
+ document.body.innerHTML = "";
48
+ });
49
+ it("shows the plain text, then swaps in highlighted markup", async () => {
50
+ const { code } = mount("let a = 1");
51
+ krateHighlightInit();
52
+ expect(code.querySelector(".line")).toBeNull();
53
+ await settle(1);
54
+ expect(code.innerHTML).toContain('<span class="k">let a = 1</span>');
55
+ expect(calls).toEqual(["let a = 1"]);
56
+ expect(code.textContent).toBe("let a = 1");
57
+ });
58
+ it("debounces fast updates and keeps the markers", async () => {
59
+ const { code, set } = mount("a");
60
+ krateHighlightInit();
61
+ await settle(1);
62
+ for (const v of ["b", "bc", "bcd"]) {
63
+ set(v);
64
+ await Promise.resolve();
65
+ await settle(30);
66
+ }
67
+ expect(code.querySelector(".line")).toBeNull();
68
+ expect(code.textContent).toBe("bcd");
69
+ await settle(200);
70
+ expect(calls).toEqual(["a", "bcd"]);
71
+ expect(code.textContent).toBe("bcd");
72
+ expect(code.firstChild.nodeType).toBe(8);
73
+ expect(code.lastChild.nodeType).toBe(8);
74
+ });
75
+ it("drops the previous highlighted markup when the slot writes new text", async () => {
76
+ const { code, set } = mount("one\ntwo");
77
+ krateHighlightInit();
78
+ await settle(1);
79
+ expect(code.querySelectorAll(".line")).toHaveLength(2);
80
+ set("three");
81
+ await settle(0);
82
+ expect(code.textContent).toBe("three");
83
+ await settle(200);
84
+ expect(code.querySelectorAll(".line")).toHaveLength(1);
85
+ expect(code.textContent).toBe("three");
86
+ });
87
+ it("does not highlight again when the code has not changed", async () => {
88
+ document.body.innerHTML =
89
+ '<pre class="chroma"><code data-krate-hl="ts"><!--k:b--><span class="line"><span class="cl">x</span></span><!--/k:b--></code></pre>';
90
+ const code = document.querySelector("code");
91
+ krateHighlightInit();
92
+ await settle(500);
93
+ expect(calls).toEqual([]);
94
+ // a second init is a no-op too
95
+ krateHighlightInit();
96
+ await settle(500);
97
+ expect(calls).toEqual([]);
98
+ expect(code.innerHTML).toContain("line");
99
+ });
100
+ it("leaves plain text when the text is too large or the language is unavailable", async () => {
101
+ const big = mount("x".repeat(200));
102
+ krateHighlightInit();
103
+ await settle(1);
104
+ expect(big.code.querySelector(".line")).toBeNull();
105
+ expect(big.code.textContent).toBe("x".repeat(200));
106
+ const none = mount("let a", "zz");
107
+ krateHighlightInit();
108
+ await settle(1);
109
+ expect(none.code.querySelector(".line")).toBeNull();
110
+ });
111
+ it("binds code that is added to the page later", async () => {
112
+ document.body.innerHTML = "<main></main>";
113
+ krateHighlightInit();
114
+ const main = document.querySelector("main");
115
+ main.innerHTML = '<pre class="chroma"><code data-krate-hl="ts"><!--k:z-->late<!--/k:z--></code></pre>';
116
+ await settle(5);
117
+ expect(main.querySelector(".line")).not.toBeNull();
118
+ expect(calls).toEqual(["late"]);
119
+ });
120
+ it("highlights on demand through krateHighlight", async () => {
121
+ expect(await krateHighlight(" a\n", "ts")).toContain('<span class="k">a</span>');
122
+ expect(await krateHighlight("a", "unknown")).toBeNull();
123
+ });
124
+ });
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Syntax highlighting that matches chroma, the highlighter Krate uses at build
3
+ * time. The compiler turns the chroma lexers a site needs into small tables
4
+ * (rule lists with JavaScript regular expressions); this file runs them. It
5
+ * follows chroma's RegexLexer state machine and its HTML formatter, so for the
6
+ * same code and language the markup is identical to what a build produces:
7
+ * one `<span class="line"><span class="cl">` per line and one classed span per
8
+ * token, coloured by the same stylesheet in light and dark.
9
+ *
10
+ * Nothing here touches the DOM or any global, so it runs unchanged on the
11
+ * server (SSR sidecars) and in the browser.
12
+ */
13
+ /** One rule: [pattern, emitter, mutator steps]. A missing pattern ("") always matches. */
14
+ type TableRule = [string, Emit?, number[]?];
15
+ /** Token type index, -1 (emit nothing), or an array starting with an emitter code. */
16
+ type Emit = number | EmitArray | null | undefined;
17
+ type EmitArray = [number, ...unknown[]];
18
+ /** A lexer as the compiler exports it. */
19
+ export interface HighlightTable {
20
+ /** Lexer name. */
21
+ n: string;
22
+ /** CSS class of each token type. */
23
+ t: string[];
24
+ /** Rules by state index; state 0 is "root". */
25
+ s: TableRule[][];
26
+ /** Add a trailing newline when the text lacks one. */
27
+ e?: 1;
28
+ /** Markdown: lex a leading YAML frontmatter block first. */
29
+ f?: 1;
30
+ /** Picks a sublexer by name at run time (fenced code blocks). */
31
+ g?: 1;
32
+ /** Names of tables this one calls into. */
33
+ d?: string[];
34
+ }
35
+ /** Longest text the highlighter will take; above this callers show plain text. */
36
+ export declare const HIGHLIGHT_MAX_LENGTH = 65536;
37
+ /**
38
+ * Most time one highlight call may spend. Lexers can be slow on hostile input
39
+ * (a long line of unmatched characters makes some rules rescan it for every
40
+ * character), so the work is checked against this between tokens and the call
41
+ * gives up, returning null, when it runs out.
42
+ */
43
+ export declare const HIGHLIGHT_BUDGET_MS = 400;
44
+ /**
45
+ * Longest line the highlighter will take. A few lexer rules rescan the rest of
46
+ * a line for every character they fail on, so their cost grows with the square
47
+ * of the line length; capping it keeps one match attempt cheap. Lines this long
48
+ * are data or minified code, which is not worth colouring.
49
+ */
50
+ export declare const HIGHLIGHT_MAX_LINE = 2000;
51
+ /**
52
+ * Registers a lexer table and the language names that select it. Names are
53
+ * matched case-insensitively.
54
+ */
55
+ export declare function registerLanguage(table: HighlightTable, names?: string[]): void;
56
+ /** True when a language name selects a registered lexer. */
57
+ export declare function hasLanguage(lang: string): boolean;
58
+ /**
59
+ * Tells the tokenizer which names chroma itself would resolve to a lexer. A
60
+ * fence naming a lexer that chroma has but that is not loaded cannot be
61
+ * highlighted exactly, so the whole snippet is left as plain text.
62
+ */
63
+ export declare function setFenceResolver(known: (name: string) => boolean): void;
64
+ /** HTML-escapes the way Go's html.EscapeString does. */
65
+ export declare function escapeHTML(s: string): string;
66
+ /** Parses a line spec such as "1,3-5" into 1-based inclusive ranges. */
67
+ export declare function parseLineRanges(spec: string): [number, number][];
68
+ /** Whitespace as Go's strings.TrimSpace sees it. */
69
+ export declare function trimSpace(s: string): string;
70
+ /**
71
+ * Highlights code, returning the inner HTML of a highlighted block (the lines
72
+ * and token spans, without the surrounding pre and code) or null when this
73
+ * text cannot be highlighted exactly: the language is not loaded, the text is
74
+ * longer than maxLength (HIGHLIGHT_MAX_LENGTH by default), has a line longer than
75
+ * maxLine (HIGHLIGHT_MAX_LINE), highlighting took
76
+ * longer than budgetMs (HIGHLIGHT_BUDGET_MS), or a fenced block names a language that is
77
+ * not loaded. A null result means "show it as plain text".
78
+ *
79
+ * Output matches the markup the compiler writes for the same code.
80
+ */
81
+ export declare function highlight(code: string, lang: string, lines?: string, limits?: {
82
+ maxLength?: number;
83
+ maxLine?: number;
84
+ budgetMs?: number;
85
+ }): string | null;
86
+ /**
87
+ * HTML for text in a language chroma does not know: its fallback lexer writes
88
+ * the text as line wrappers with no token spans.
89
+ */
90
+ export declare function plainLines(code: string, lines?: string): string;
91
+ /** Names of the registered languages, for tests. */
92
+ export declare function loadedLanguages(): string[];
93
+ export {};
@@ -0,0 +1,426 @@
1
+ /**
2
+ * Syntax highlighting that matches chroma, the highlighter Krate uses at build
3
+ * time. The compiler turns the chroma lexers a site needs into small tables
4
+ * (rule lists with JavaScript regular expressions); this file runs them. It
5
+ * follows chroma's RegexLexer state machine and its HTML formatter, so for the
6
+ * same code and language the markup is identical to what a build produces:
7
+ * one `<span class="line"><span class="cl">` per line and one classed span per
8
+ * token, coloured by the same stylesheet in light and dark.
9
+ *
10
+ * Nothing here touches the DOM or any global, so it runs unchanged on the
11
+ * server (SSR sidecars) and in the browser.
12
+ */
13
+ const BY_GROUPS = 0;
14
+ const USING_SELF = 1;
15
+ const USING = 2;
16
+ const USING_GROUP = 3;
17
+ const USING_MAP = 4;
18
+ const MUT_POP = -1;
19
+ const MUT_SELF = -2;
20
+ /** Longest text the highlighter will take; above this callers show plain text. */
21
+ export const HIGHLIGHT_MAX_LENGTH = 65536;
22
+ /**
23
+ * Most time one highlight call may spend. Lexers can be slow on hostile input
24
+ * (a long line of unmatched characters makes some rules rescan it for every
25
+ * character), so the work is checked against this between tokens and the call
26
+ * gives up, returning null, when it runs out.
27
+ */
28
+ export const HIGHLIGHT_BUDGET_MS = 400;
29
+ /**
30
+ * Longest line the highlighter will take. A few lexer rules rescan the rest of
31
+ * a line for every character they fail on, so their cost grows with the square
32
+ * of the line length; capping it keeps one match attempt cheap. Lines this long
33
+ * are data or minified code, which is not worth colouring.
34
+ */
35
+ export const HIGHLIGHT_MAX_LINE = 2000;
36
+ let deadline = Infinity;
37
+ let steps = 0;
38
+ const REGISTRY_KEY = Symbol.for("krate.highlight.registry");
39
+ const registry = globalThis[REGISTRY_KEY] || {
40
+ lexers: new Map(),
41
+ langKeys: new Map(),
42
+ };
43
+ globalThis[REGISTRY_KEY] = registry;
44
+ const lexers = registry.lexers;
45
+ const langKeys = registry.langKeys;
46
+ /**
47
+ * Registers a lexer table and the language names that select it. Names are
48
+ * matched case-insensitively.
49
+ */
50
+ export function registerLanguage(table, names) {
51
+ const key = table.n.toLowerCase();
52
+ lexers.set(key, { table, res: table.s.map(() => []) });
53
+ langKeys.set(key, key);
54
+ if (names)
55
+ for (const n of names)
56
+ langKeys.set(n.toLowerCase(), key);
57
+ }
58
+ /** True when a language name selects a registered lexer. */
59
+ export function hasLanguage(lang) {
60
+ return langKeys.has(lang.trim().toLowerCase());
61
+ }
62
+ function lexerFor(name) {
63
+ const key = langKeys.get(name.trim().toLowerCase());
64
+ return key === undefined ? undefined : lexers.get(key);
65
+ }
66
+ function ensureLF(text) {
67
+ if (text.indexOf("\r") < 0)
68
+ return text;
69
+ return text.replace(/\r\n?/g, "\n");
70
+ }
71
+ function regexFor(lx, state, i) {
72
+ const row = lx.res[state];
73
+ const cached = row[i];
74
+ if (cached)
75
+ return cached;
76
+ const re = new RegExp(lx.table.s[state][i][0], "yu");
77
+ row[i] = re;
78
+ return re;
79
+ }
80
+ /** Thrown when text cannot be highlighted exactly: a language is not loaded or time ran out. */
81
+ class Incomplete extends Error {
82
+ }
83
+ function remapClass(table, idx) {
84
+ return table.t[idx];
85
+ }
86
+ /** Runs a lexer over text, appending tokens to out. Mirrors chroma's RegexLexer. */
87
+ function lex(lx, text, startState, nested, out) {
88
+ const table = lx.table;
89
+ if (!nested)
90
+ text = ensureLF(text);
91
+ let added = false;
92
+ if (!nested && table.e && !text.endsWith("\n")) {
93
+ text += "\n";
94
+ added = true;
95
+ }
96
+ const end = text.length - (added ? 1 : 0);
97
+ const stack = [startState];
98
+ let pos = 0;
99
+ while (pos < end && stack.length > 0) {
100
+ if ((++steps & 3) === 0 && Date.now() > deadline)
101
+ throw new Incomplete("time");
102
+ const state = stack[stack.length - 1];
103
+ const rules = table.s[state];
104
+ let m = null;
105
+ let rule;
106
+ for (let i = 0; i < rules.length; i++) {
107
+ const r = rules[i];
108
+ if (r[0] === "") {
109
+ m = [""];
110
+ rule = r;
111
+ break;
112
+ }
113
+ const re = regexFor(lx, state, i);
114
+ re.lastIndex = pos;
115
+ m = re.exec(text);
116
+ if (m !== null) {
117
+ rule = r;
118
+ break;
119
+ }
120
+ }
121
+ if (m === null || rule === undefined) {
122
+ if (text.charCodeAt(pos) === 10 && state !== startState) {
123
+ stack.length = 0;
124
+ stack.push(startState);
125
+ continue;
126
+ }
127
+ const cp = text.codePointAt(pos);
128
+ const n = cp > 0xffff ? 2 : 1;
129
+ out.push(["err", text.substr(pos, n)]);
130
+ pos += n;
131
+ continue;
132
+ }
133
+ pos += m[0].length;
134
+ const mut = rule[2];
135
+ if (mut !== undefined) {
136
+ for (let i = 0; i < mut.length; i++) {
137
+ const step = mut[i];
138
+ if (step === MUT_POP)
139
+ stack.pop();
140
+ else if (step === MUT_SELF)
141
+ stack.push(state);
142
+ else
143
+ stack.push(step);
144
+ }
145
+ }
146
+ const emit = rule[1];
147
+ if (emit !== undefined && emit !== null)
148
+ emitTokens(lx, emit, m, out);
149
+ }
150
+ if (pos < text.length && stack.length === 0)
151
+ out.push(["err", text.slice(pos)]);
152
+ }
153
+ function group(m, i) {
154
+ const v = m[i];
155
+ return v === undefined ? "" : v;
156
+ }
157
+ function emitTokens(lx, emit, groups, out) {
158
+ const table = lx.table;
159
+ if (typeof emit === "number") {
160
+ if (emit >= 0)
161
+ out.push([table.t[emit], group(groups, 0)]);
162
+ return;
163
+ }
164
+ if (emit === null || emit === undefined)
165
+ return;
166
+ switch (emit[0]) {
167
+ case BY_GROUPS: {
168
+ for (let i = 1; i < emit.length; i++) {
169
+ const e = emit[i];
170
+ if (e === null || e === undefined)
171
+ continue;
172
+ emitTokens(lx, e, [group(groups, i)], out);
173
+ }
174
+ return;
175
+ }
176
+ case USING_SELF:
177
+ lex(lx, group(groups, 0), emit[1], true, out);
178
+ return;
179
+ case USING: {
180
+ const sub = lexerFor(emit[1]);
181
+ if (!sub)
182
+ throw new Incomplete(emit[1]);
183
+ lexTop(sub, group(groups, 0), true, out);
184
+ return;
185
+ }
186
+ case USING_MAP: {
187
+ const sub = lexerFor(emit[1]);
188
+ if (!sub)
189
+ throw new Incomplete(emit[1]);
190
+ const tmp = [];
191
+ lexTop(sub, group(groups, 0), true, tmp);
192
+ const pair = emit[2];
193
+ const from = remapClass(table, pair[0]);
194
+ const to = remapClass(table, pair[1]);
195
+ for (const t of tmp)
196
+ out.push(t[0] === from ? [to, t[1]] : t);
197
+ return;
198
+ }
199
+ case USING_GROUP: {
200
+ const nameGroup = emit[1];
201
+ const codeGroup = emit[2];
202
+ const name = group(groups, nameGroup);
203
+ const sub = fenceLexer(name);
204
+ for (let i = 3; i < emit.length; i++) {
205
+ const gi = i - 2; // group number of this emitter
206
+ if (gi === codeGroup && sub) {
207
+ lexTop(sub, group(groups, codeGroup), false, out);
208
+ }
209
+ else {
210
+ const e = emit[i];
211
+ if (e !== null && e !== undefined)
212
+ emitTokens(lx, e, [group(groups, gi)], out);
213
+ }
214
+ }
215
+ return;
216
+ }
217
+ }
218
+ }
219
+ /**
220
+ * Tells the tokenizer which names chroma itself would resolve to a lexer. A
221
+ * fence naming a lexer that chroma has but that is not loaded cannot be
222
+ * highlighted exactly, so the whole snippet is left as plain text.
223
+ */
224
+ export function setFenceResolver(known) {
225
+ registry.fenceKnown = known;
226
+ }
227
+ function fenceLexer(name) {
228
+ const lx = lexerFor(name);
229
+ if (lx)
230
+ return lx;
231
+ if (registry.fenceKnown && registry.fenceKnown(name))
232
+ throw new Incomplete(name);
233
+ return undefined;
234
+ }
235
+ const ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&#34;", "'": "&#39;" };
236
+ /** HTML-escapes the way Go's html.EscapeString does. */
237
+ export function escapeHTML(s) {
238
+ return s.replace(/[&<>"']/g, (c) => ESC[c]);
239
+ }
240
+ /** Parses a line spec such as "1,3-5" into 1-based inclusive ranges. */
241
+ export function parseLineRanges(spec) {
242
+ const out = [];
243
+ for (let part of spec.split(",")) {
244
+ part = part.trim();
245
+ if (part === "")
246
+ continue;
247
+ const dash = part.indexOf("-");
248
+ const lo = dash < 0 ? part : part.slice(0, dash);
249
+ const a = atoi(lo.trim());
250
+ if (a === null || a < 1)
251
+ continue;
252
+ let b = a;
253
+ if (dash >= 0) {
254
+ const hi = atoi(part.slice(dash + 1).trim());
255
+ if (hi === null || hi < a)
256
+ continue;
257
+ b = hi;
258
+ }
259
+ out.push([a, b]);
260
+ }
261
+ return out;
262
+ }
263
+ function atoi(s) {
264
+ if (!/^[+-]?\d+$/.test(s))
265
+ return null;
266
+ const n = Number(s);
267
+ return Number.isSafeInteger(n) ? n : null;
268
+ }
269
+ /** Splits tokens at newlines the way chroma.SplitTokensIntoLines does. */
270
+ function splitLines(tokens) {
271
+ const out = [];
272
+ let line = [];
273
+ outer: for (const tok of tokens) {
274
+ let value = tok[1];
275
+ let nl = value.indexOf("\n");
276
+ while (nl >= 0) {
277
+ line.push([tok[0], value.slice(0, nl + 1)]);
278
+ out.push(line);
279
+ line = [];
280
+ value = value.slice(nl + 1);
281
+ if (value.length === 0)
282
+ continue outer;
283
+ nl = value.indexOf("\n");
284
+ }
285
+ line.push([tok[0], value]);
286
+ }
287
+ if (line.length > 0)
288
+ out.push(line);
289
+ if (out.length > 0) {
290
+ const last = out[out.length - 1];
291
+ if (last.length === 1 && last[0][1] === "")
292
+ out.pop();
293
+ }
294
+ return out;
295
+ }
296
+ function shouldHighlight(ranges, idx, line) {
297
+ while (idx < ranges.length && line > ranges[idx][1])
298
+ idx++;
299
+ if (idx < ranges.length && line >= ranges[idx][0] && line <= ranges[idx][1])
300
+ return [true, idx];
301
+ return [false, idx];
302
+ }
303
+ /** Writes tokens as chroma's HTML formatter does (class mode, no line numbers). */
304
+ function format(tokens, ranges) {
305
+ const lines = splitLines(tokens);
306
+ let html = "";
307
+ let idx = 0;
308
+ for (let i = 0; i < lines.length; i++) {
309
+ const [hl, next] = shouldHighlight(ranges, idx, i + 1);
310
+ idx = next;
311
+ html += hl ? '<span class="line hl"><span class="cl">' : '<span class="line"><span class="cl">';
312
+ for (const [cls, value] of lines[i]) {
313
+ if (cls === null)
314
+ continue;
315
+ const text = escapeHTML(value);
316
+ html += cls === "" ? text : '<span class="' + cls + '">' + text + "</span>";
317
+ }
318
+ html += "</span></span>";
319
+ }
320
+ return html;
321
+ }
322
+ /** Whitespace as Go's strings.TrimSpace sees it. */
323
+ export function trimSpace(s) {
324
+ return s.replace(SPACE_EDGES, "");
325
+ }
326
+ const SPACE_EDGES = new RegExp("^[" + "\\t-\\r \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000" + "]+|[" +
327
+ "\\t-\\r \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000" + "]+$", "g");
328
+ /**
329
+ * Highlights code, returning the inner HTML of a highlighted block (the lines
330
+ * and token spans, without the surrounding pre and code) or null when this
331
+ * text cannot be highlighted exactly: the language is not loaded, the text is
332
+ * longer than maxLength (HIGHLIGHT_MAX_LENGTH by default), has a line longer than
333
+ * maxLine (HIGHLIGHT_MAX_LINE), highlighting took
334
+ * longer than budgetMs (HIGHLIGHT_BUDGET_MS), or a fenced block names a language that is
335
+ * not loaded. A null result means "show it as plain text".
336
+ *
337
+ * Output matches the markup the compiler writes for the same code.
338
+ */
339
+ export function highlight(code, lang, lines, limits = {}) {
340
+ if (code.length > (limits.maxLength ?? HIGHLIGHT_MAX_LENGTH))
341
+ return null;
342
+ const lx = lexerFor(lang);
343
+ if (!lx)
344
+ return null;
345
+ if (longestLine(code) > (limits.maxLine ?? HIGHLIGHT_MAX_LINE))
346
+ return null;
347
+ const out = [];
348
+ deadline = Date.now() + (limits.budgetMs ?? HIGHLIGHT_BUDGET_MS);
349
+ try {
350
+ lexTop(lx, code, false, out);
351
+ }
352
+ catch (e) {
353
+ if (e instanceof Incomplete)
354
+ return null;
355
+ throw e;
356
+ }
357
+ finally {
358
+ deadline = Infinity;
359
+ }
360
+ return format(out, lines ? parseLineRanges(lines).sort((a, b) => a[0] - b[0]) : []);
361
+ }
362
+ function longestLine(s) {
363
+ let best = 0;
364
+ let run = 0;
365
+ for (let i = 0; i < s.length; i++) {
366
+ const c = s.charCodeAt(i);
367
+ if (c === 10 || c === 13) {
368
+ if (run > best)
369
+ best = run;
370
+ run = 0;
371
+ }
372
+ else
373
+ run++;
374
+ }
375
+ return run > best ? run : best;
376
+ }
377
+ /** Highlights text with a lexer, handling the markdown frontmatter wrapper. */
378
+ function lexTop(lx, code, nested, out) {
379
+ if (lx.table.f) {
380
+ const split = splitFrontmatter(code);
381
+ const yaml = split && lexerFor("yaml");
382
+ if (split && yaml) {
383
+ lex(yaml, split[0], 0, nested, out);
384
+ lex(lx, split[1], 0, nested, out);
385
+ return;
386
+ }
387
+ }
388
+ lex(lx, code, 0, nested, out);
389
+ }
390
+ function splitFrontmatter(text) {
391
+ if (!text.startsWith("---\n") && !text.startsWith("---\r\n"))
392
+ return null;
393
+ let lineEnd = text.indexOf("\n");
394
+ if (lineEnd < 0)
395
+ return null;
396
+ if (text.slice(0, lineEnd).replace(/\r$/, "") !== "---")
397
+ return null;
398
+ for (let pos = lineEnd + 1; pos < text.length;) {
399
+ const next = text.indexOf("\n", pos);
400
+ if (next < 0)
401
+ break;
402
+ lineEnd = next;
403
+ const line = text.slice(pos, lineEnd).replace(/\r$/, "");
404
+ if (line === "---")
405
+ return [text.slice(0, lineEnd + 1), text.slice(lineEnd + 1)];
406
+ pos = lineEnd + 1;
407
+ }
408
+ return null;
409
+ }
410
+ /**
411
+ * HTML for text in a language chroma does not know: its fallback lexer writes
412
+ * the text as line wrappers with no token spans.
413
+ */
414
+ export function plainLines(code, lines) {
415
+ const out = [];
416
+ const text = ensureLF(code);
417
+ const re = /[^\n]+|\n/g;
418
+ let m;
419
+ while ((m = re.exec(text)) !== null)
420
+ out.push(["", m[0]]);
421
+ return format(out, lines ? parseLineRanges(lines).sort((a, b) => a[0] - b[0]) : []);
422
+ }
423
+ /** Names of the registered languages, for tests. */
424
+ export function loadedLanguages() {
425
+ return [...lexers.keys()];
426
+ }
@@ -0,0 +1 @@
1
+ export {};