@f5-sales-demo/pi-utils 23.8.0 → 23.9.1
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/package.json +5 -3
- package/src/code-presentation.browser.ts +281 -0
- package/src/code-presentation.ts +307 -0
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"type": "module",
|
|
3
3
|
"name": "@f5-sales-demo/pi-utils",
|
|
4
|
-
"version": "23.
|
|
4
|
+
"version": "23.9.1",
|
|
5
5
|
"description": "Shared utilities for pi packages",
|
|
6
6
|
"homepage": "https://github.com/f5-sales-demo/xcsh",
|
|
7
7
|
"author": "Can Boluk",
|
|
@@ -34,12 +34,14 @@
|
|
|
34
34
|
"@f5-sales-demo/i18n-core": "1.0.59",
|
|
35
35
|
"beautiful-mermaid": "^1.1",
|
|
36
36
|
"handlebars": "^4.7.9",
|
|
37
|
+
"highlight.js": "11.11.1",
|
|
37
38
|
"winston": "^3.19",
|
|
38
|
-
"winston-daily-rotate-file": "^5.0"
|
|
39
|
+
"winston-daily-rotate-file": "^5.0",
|
|
40
|
+
"yaml": "2.9.0"
|
|
39
41
|
},
|
|
40
42
|
"devDependencies": {
|
|
41
43
|
"@types/bun": "1.4.2",
|
|
42
|
-
"@f5-sales-demo/pi-natives": "23.
|
|
44
|
+
"@f5-sales-demo/pi-natives": "23.9.1"
|
|
43
45
|
},
|
|
44
46
|
"engines": {
|
|
45
47
|
"bun": ">=1.4.2"
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
/** Browser adapter bundled by repository tooling for exports and vendored clients. */
|
|
2
|
+
import hljs from "highlight.js/lib/core";
|
|
3
|
+
import bash from "highlight.js/lib/languages/bash";
|
|
4
|
+
import css from "highlight.js/lib/languages/css";
|
|
5
|
+
import diff from "highlight.js/lib/languages/diff";
|
|
6
|
+
import javascript from "highlight.js/lib/languages/javascript";
|
|
7
|
+
import json from "highlight.js/lib/languages/json";
|
|
8
|
+
import markdown from "highlight.js/lib/languages/markdown";
|
|
9
|
+
import python from "highlight.js/lib/languages/python";
|
|
10
|
+
import typescript from "highlight.js/lib/languages/typescript";
|
|
11
|
+
import xml from "highlight.js/lib/languages/xml";
|
|
12
|
+
import yaml from "highlight.js/lib/languages/yaml";
|
|
13
|
+
import {
|
|
14
|
+
isCodeBlockComplete,
|
|
15
|
+
mapHttpCode,
|
|
16
|
+
normalizeCodeLanguage,
|
|
17
|
+
presentCode,
|
|
18
|
+
wrapCodeLine,
|
|
19
|
+
} from "./code-presentation";
|
|
20
|
+
|
|
21
|
+
export { isCodeBlockComplete, normalizeCodeLanguage, presentCode, wrapCodeLine };
|
|
22
|
+
|
|
23
|
+
export const CODE_PANEL_CSS: string = `
|
|
24
|
+
.markdown-root .md-code-panel { background:var(--code-bg,var(--toolPendingBg)); border:0; border-left:2px solid var(--mdCodeBlockBorder,var(--md-code-block-border,var(--subtle-gray))); border-radius:3px; padding:12px; overflow:hidden; }
|
|
25
|
+
.markdown-root .md-code-panel code { display:block; background:none; color:var(--mdCodeBlock,var(--md-code-block,var(--bright-white))); padding:0; white-space:pre-wrap; overflow-wrap:anywhere; tab-size:4; }
|
|
26
|
+
.markdown-root .md-code-panel code:has(.md-code-row) { white-space:normal; }
|
|
27
|
+
.markdown-root .md-code-row { display:block; position:relative; padding-left:3ch; white-space:pre; min-height:1lh; }
|
|
28
|
+
.markdown-root .md-code-continuation::before { content:"↪"; position:absolute; left:0; color:var(--mdCodeBlockBorder,var(--md-code-block-border,var(--cool-gray))); user-select:none; }
|
|
29
|
+
.markdown-root .hljs-comment,.markdown-root .hljs-quote { color:var(--syntaxComment,var(--syntax-comment)); }
|
|
30
|
+
.markdown-root .hljs-keyword,.markdown-root .hljs-literal { color:var(--syntaxKeyword,var(--syntax-keyword)); }
|
|
31
|
+
.markdown-root .hljs-control { color:var(--syntaxControl,var(--syntax-control)); }
|
|
32
|
+
.markdown-root .hljs-number { color:var(--syntaxNumber,var(--syntax-number)); }
|
|
33
|
+
.markdown-root .hljs-string { color:var(--syntaxString,var(--syntax-string)); }
|
|
34
|
+
.markdown-root .hljs-title,.markdown-root .hljs-function { color:var(--syntaxFunction,var(--syntax-function)); }
|
|
35
|
+
.markdown-root .hljs-type,.markdown-root .hljs-built_in,.markdown-root .hljs-title.class_ { color:var(--syntaxType,var(--syntax-type)); }
|
|
36
|
+
.markdown-root .hljs-attr,.markdown-root .hljs-variable,.markdown-root .hljs-property,.markdown-root .hljs-params { color:var(--syntaxVariable,var(--syntax-variable)); }
|
|
37
|
+
.markdown-root .hljs-operator { color:var(--syntaxOperator,var(--syntax-operator)); }
|
|
38
|
+
.markdown-root .hljs-punctuation { color:var(--syntaxPunctuation,var(--syntax-punctuation)); }
|
|
39
|
+
`;
|
|
40
|
+
|
|
41
|
+
for (const [name, grammar] of Object.entries({
|
|
42
|
+
css,
|
|
43
|
+
diff,
|
|
44
|
+
|
|
45
|
+
javascript,
|
|
46
|
+
json,
|
|
47
|
+
markdown,
|
|
48
|
+
python,
|
|
49
|
+
|
|
50
|
+
typescript,
|
|
51
|
+
xml,
|
|
52
|
+
yaml,
|
|
53
|
+
}))
|
|
54
|
+
hljs.registerLanguage(name, grammar);
|
|
55
|
+
hljs.registerLanguage("bash", api => {
|
|
56
|
+
const definition = bash(api);
|
|
57
|
+
definition.contains?.unshift({
|
|
58
|
+
scope: "string",
|
|
59
|
+
begin: /<<(-?)[ \t]*(['"])([A-Za-z_][\w]*)\2[ \t]*\n/,
|
|
60
|
+
end: /^\t*[A-Za-z_][\w]*$/,
|
|
61
|
+
"on:begin": (
|
|
62
|
+
match: RegExpMatchArray,
|
|
63
|
+
response: { data: { delimiter?: string; stripTabs?: boolean }; ignoreMatch(): void },
|
|
64
|
+
) => {
|
|
65
|
+
response.data.delimiter = match[3];
|
|
66
|
+
response.data.stripTabs = match[1] === "-";
|
|
67
|
+
},
|
|
68
|
+
"on:end": (
|
|
69
|
+
match: RegExpMatchArray,
|
|
70
|
+
response: { data: { delimiter?: string; stripTabs?: boolean }; ignoreMatch(): void },
|
|
71
|
+
) => {
|
|
72
|
+
const delimiter = response.data.stripTabs ? match[0].replace(/^\t+/, "") : match[0];
|
|
73
|
+
if (delimiter !== response.data.delimiter) response.ignoreMatch();
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
return definition;
|
|
77
|
+
});
|
|
78
|
+
hljs.registerLanguage("hcl", api => {
|
|
79
|
+
const interpolation = {
|
|
80
|
+
scope: "subst",
|
|
81
|
+
begin: /\$\{|%\{/,
|
|
82
|
+
end: /\}/,
|
|
83
|
+
contains: [
|
|
84
|
+
api.QUOTE_STRING_MODE,
|
|
85
|
+
api.C_NUMBER_MODE,
|
|
86
|
+
{ scope: "literal", match: /\b(?:true|false|null)\b/ },
|
|
87
|
+
{ scope: "control", match: /\b(?:for|in|if|else|endif|endfor)\b/ },
|
|
88
|
+
{ scope: "title.function", match: /[A-Za-z_][\w-]*(?=\s*\()/ },
|
|
89
|
+
{ scope: "variable", match: /[A-Za-z_][\w.-]*/ },
|
|
90
|
+
{ scope: "operator", match: /[+*/=!<>?:-]+/ },
|
|
91
|
+
],
|
|
92
|
+
};
|
|
93
|
+
return {
|
|
94
|
+
name: "HCL",
|
|
95
|
+
aliases: ["tf", "tfvars", "terraform"],
|
|
96
|
+
keywords: {
|
|
97
|
+
keyword: "resource data variable output locals provider terraform module dynamic",
|
|
98
|
+
literal: "true false null",
|
|
99
|
+
control: "for in if else endif endfor",
|
|
100
|
+
},
|
|
101
|
+
contains: [
|
|
102
|
+
api.HASH_COMMENT_MODE,
|
|
103
|
+
api.C_LINE_COMMENT_MODE,
|
|
104
|
+
api.C_BLOCK_COMMENT_MODE,
|
|
105
|
+
{
|
|
106
|
+
scope: "string",
|
|
107
|
+
begin: /<<-?([A-Za-z_][\w]*)\n/,
|
|
108
|
+
end: /^\s*[A-Za-z_][\w]*\s*$/,
|
|
109
|
+
contains: [interpolation],
|
|
110
|
+
"on:begin": (match: RegExpMatchArray, response: { data: { delimiter?: string }; ignoreMatch(): void }) => {
|
|
111
|
+
response.data.delimiter = match[1];
|
|
112
|
+
},
|
|
113
|
+
"on:end": (match: RegExpMatchArray, response: { data: { delimiter?: string }; ignoreMatch(): void }) => {
|
|
114
|
+
if (match[0].trim() !== response.data.delimiter) response.ignoreMatch();
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
{ scope: "string", begin: /"/, end: /"/, contains: [api.BACKSLASH_ESCAPE, interpolation] },
|
|
118
|
+
{ scope: "attr", match: /[A-Za-z_][\w-]*(?=\s*=)/ },
|
|
119
|
+
{ scope: "title.function", match: /[A-Za-z_][\w-]*(?=\s*\()/ },
|
|
120
|
+
api.C_NUMBER_MODE,
|
|
121
|
+
{ scope: "operator", match: /[+*/=!<>?:-]+/ },
|
|
122
|
+
{ scope: "punctuation", match: /[{}[\](),.]/ },
|
|
123
|
+
],
|
|
124
|
+
};
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
function escapeHtml(text: string): string {
|
|
128
|
+
return text
|
|
129
|
+
.replace(/&/g, "&")
|
|
130
|
+
.replace(/</g, "<")
|
|
131
|
+
.replace(/>/g, ">")
|
|
132
|
+
.replace(/"/g, """)
|
|
133
|
+
.replace(/'/g, "'");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function highlightCodeHtml(code: string, language: string): string {
|
|
137
|
+
const lang = normalizeCodeLanguage(language);
|
|
138
|
+
if (lang === "http")
|
|
139
|
+
return mapHttpCode(
|
|
140
|
+
code,
|
|
141
|
+
(text, category) =>
|
|
142
|
+
category
|
|
143
|
+
? `<span class="hljs-${category === "variable" ? "attr" : category}">${escapeHtml(text)}</span>`
|
|
144
|
+
: escapeHtml(text),
|
|
145
|
+
highlightCodeHtml,
|
|
146
|
+
);
|
|
147
|
+
if (!lang || !hljs.getLanguage(lang)) return escapeHtml(code);
|
|
148
|
+
try {
|
|
149
|
+
return hljs
|
|
150
|
+
.highlight(code, { language: lang, ignoreIllegals: true })
|
|
151
|
+
.value.replace(
|
|
152
|
+
/<span class="hljs-keyword">(if|else|elif|for|while|return|break|continue|import|from|then|fi|do|done|case|esac|try|except|finally|raise|yield|with)<\/span>/g,
|
|
153
|
+
'<span class="hljs-control">$1</span>',
|
|
154
|
+
);
|
|
155
|
+
} catch {
|
|
156
|
+
return escapeHtml(code);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function encodeMetadata(source: string): string {
|
|
161
|
+
return JSON.stringify(source).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026");
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function decodeMetadata(source: string | undefined): string {
|
|
165
|
+
try {
|
|
166
|
+
const value: unknown = JSON.parse(source ?? '""');
|
|
167
|
+
return typeof value === "string" ? value : "";
|
|
168
|
+
} catch {
|
|
169
|
+
return "";
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function renderCodePanel(source: string, info?: string, complete = true): string {
|
|
174
|
+
const view = presentCode(source, info, complete);
|
|
175
|
+
return `<pre class="md-code-panel"><code class="hljs${view.language ? ` language-${view.language}` : ""}" data-code-source="${escapeHtml(encodeMetadata(source))}" data-code-display="${escapeHtml(encodeMetadata(view.display))}">${highlightCodeHtml(view.display, view.language)}</code></pre>`;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Observe actual font/width; rewrap on resize and retain source-only clipboard data. */
|
|
179
|
+
export function installCodePanels(root: HTMLElement): () => void {
|
|
180
|
+
const win = root.ownerDocument.defaultView;
|
|
181
|
+
if (!win) return () => {};
|
|
182
|
+
const canvas = root.ownerDocument.createElement("canvas");
|
|
183
|
+
let disposed = false;
|
|
184
|
+
const layout = () => {
|
|
185
|
+
if (disposed) return;
|
|
186
|
+
const context = canvas.getContext("2d");
|
|
187
|
+
if (!context) return;
|
|
188
|
+
for (const code of root.querySelectorAll<HTMLElement>("pre code[data-code-source]")) {
|
|
189
|
+
if (code.clientWidth < 4) continue;
|
|
190
|
+
const style = win.getComputedStyle(code);
|
|
191
|
+
context.font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
|
|
192
|
+
const measure = (text: string) => context.measureText(text).width;
|
|
193
|
+
const width = Math.max(1, code.clientWidth - measure(" "));
|
|
194
|
+
const language = [...code.classList].find(c => c.startsWith("language-"))?.slice(9) ?? "";
|
|
195
|
+
const display = decodeMetadata(code.dataset.codeDisplay ?? code.dataset.codeSource);
|
|
196
|
+
// Highlight once, then slice the token DOM by UTF-16 offsets. This retains
|
|
197
|
+
// multiline grammar context and keeps visual gutters out of selectable text.
|
|
198
|
+
const fragment = root.ownerDocument.createElement("div");
|
|
199
|
+
fragment.innerHTML = highlightCodeHtml(display.replace(/\t/g, " "), language);
|
|
200
|
+
const walker = root.ownerDocument.createTreeWalker(fragment, win.NodeFilter.SHOW_TEXT);
|
|
201
|
+
const leaves: { text: string; start: number; end: number; classes: string }[] = [];
|
|
202
|
+
let offset = 0;
|
|
203
|
+
let node = walker.nextNode();
|
|
204
|
+
while (node) {
|
|
205
|
+
const text = node.textContent ?? "";
|
|
206
|
+
let element = node.parentElement;
|
|
207
|
+
const classes: string[] = [];
|
|
208
|
+
while (element && element !== fragment) {
|
|
209
|
+
if ([...element.classList].some(name => name.startsWith("hljs-"))) {
|
|
210
|
+
classes.push(...element.classList);
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
element = element.parentElement;
|
|
214
|
+
}
|
|
215
|
+
leaves.push({ text, start: offset, end: offset + text.length, classes: classes.join(" ") });
|
|
216
|
+
offset += text.length;
|
|
217
|
+
node = walker.nextNode();
|
|
218
|
+
}
|
|
219
|
+
const lines = display.replace(/\t/g, " ").split("\n");
|
|
220
|
+
let start = 0;
|
|
221
|
+
let html = "";
|
|
222
|
+
for (const [index, line] of lines.entries()) {
|
|
223
|
+
const leading = /^ */.exec(line)?.[0].length ?? 0;
|
|
224
|
+
const indentWidth = measure(line.slice(0, leading));
|
|
225
|
+
const indent = indentWidth < width / 2 ? leading : 0;
|
|
226
|
+
const indentPixels = indent ? indentWidth : 0;
|
|
227
|
+
for (const part of wrapCodeLine(line.slice(indent), width - indentPixels, measure)) {
|
|
228
|
+
const a = start + (part.continuation ? indent + part.start : 0);
|
|
229
|
+
const b = start + indent + part.end;
|
|
230
|
+
html += `<span class="md-code-row${part.continuation ? " md-code-continuation" : ""}" style="padding-left:calc(3ch + ${part.continuation ? indentPixels : 0}px)">`;
|
|
231
|
+
for (const leaf of leaves) {
|
|
232
|
+
if (leaf.end <= a || leaf.start >= b) continue;
|
|
233
|
+
html += `<span class="${leaf.classes}">${escapeHtml(leaf.text.slice(Math.max(0, a - leaf.start), Math.min(leaf.text.length, b - leaf.start)))}</span>`;
|
|
234
|
+
}
|
|
235
|
+
html += "</span>";
|
|
236
|
+
}
|
|
237
|
+
if (index < lines.length - 1) html += "\n";
|
|
238
|
+
start += line.length + 1;
|
|
239
|
+
}
|
|
240
|
+
code.innerHTML = html;
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
const copy = (event: ClipboardEvent) => {
|
|
244
|
+
const selection = win.getSelection();
|
|
245
|
+
const selectedCode = (node: Node | null | undefined) =>
|
|
246
|
+
(node?.nodeType === 1 ? (node as Element) : node?.parentElement)?.closest<HTMLElement>(
|
|
247
|
+
"code[data-code-source]",
|
|
248
|
+
);
|
|
249
|
+
const anchor = selectedCode(selection?.anchorNode);
|
|
250
|
+
const focus = selectedCode(selection?.focusNode);
|
|
251
|
+
if (
|
|
252
|
+
anchor &&
|
|
253
|
+
anchor === focus &&
|
|
254
|
+
root.contains(anchor) &&
|
|
255
|
+
selection &&
|
|
256
|
+
!selection.isCollapsed &&
|
|
257
|
+
event.clipboardData
|
|
258
|
+
) {
|
|
259
|
+
event.clipboardData.setData("text/plain", decodeMetadata(anchor.dataset.codeSource));
|
|
260
|
+
event.preventDefault();
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
root.addEventListener("copy", copy);
|
|
264
|
+
const observer = typeof ResizeObserver === "function" ? new ResizeObserver(layout) : undefined;
|
|
265
|
+
observer?.observe(root);
|
|
266
|
+
win.addEventListener("resize", layout);
|
|
267
|
+
const mutation = typeof MutationObserver === "function" ? new MutationObserver(layout) : undefined;
|
|
268
|
+
mutation?.observe(root.ownerDocument.documentElement, {
|
|
269
|
+
attributes: true,
|
|
270
|
+
attributeFilter: ["class", "style", "data-theme"],
|
|
271
|
+
});
|
|
272
|
+
void root.ownerDocument.fonts?.ready.then(layout);
|
|
273
|
+
layout();
|
|
274
|
+
return () => {
|
|
275
|
+
disposed = true;
|
|
276
|
+
observer?.disconnect();
|
|
277
|
+
mutation?.disconnect();
|
|
278
|
+
win.removeEventListener("resize", layout);
|
|
279
|
+
root.removeEventListener("copy", copy);
|
|
280
|
+
};
|
|
281
|
+
}
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/** Browser-safe display policy. Source is immutable; decorations never become code. */
|
|
2
|
+
import { isCollection, isPair, isScalar, parseAllDocuments } from "yaml";
|
|
3
|
+
|
|
4
|
+
const ALIASES: Record<string, string> = {
|
|
5
|
+
yml: "yaml",
|
|
6
|
+
tf: "hcl",
|
|
7
|
+
tfvars: "hcl",
|
|
8
|
+
terraform: "hcl",
|
|
9
|
+
sh: "bash",
|
|
10
|
+
shell: "bash",
|
|
11
|
+
zsh: "bash",
|
|
12
|
+
py: "python",
|
|
13
|
+
js: "javascript",
|
|
14
|
+
ts: "typescript",
|
|
15
|
+
cplusplus: "cpp",
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export function normalizeCodeLanguage(info?: string): string {
|
|
19
|
+
const first = (info ?? "").trim().split(/\s+/)[0]?.toLowerCase() ?? "";
|
|
20
|
+
return /^[a-z0-9+#._-]{1,20}$/.test(first) ? (ALIASES[first] ?? first) : "";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Offsets are UTF-16 indices. A formatted YAML document maps as a whole document. */
|
|
24
|
+
export interface CodeMapping {
|
|
25
|
+
sourceStart: number;
|
|
26
|
+
sourceEnd: number;
|
|
27
|
+
displayStart: number;
|
|
28
|
+
displayEnd: number;
|
|
29
|
+
}
|
|
30
|
+
export interface CodePresentation {
|
|
31
|
+
source: string;
|
|
32
|
+
display: string;
|
|
33
|
+
language: string;
|
|
34
|
+
formatted: boolean;
|
|
35
|
+
mapping: CodeMapping[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function isCodeBlockComplete(raw: string, indented = false): boolean {
|
|
39
|
+
if (indented) return true;
|
|
40
|
+
const opening = /^ {0,3}(`{3,}|~{3,})[^\n]*(?:\n|$)/.exec(raw);
|
|
41
|
+
if (!opening) return true;
|
|
42
|
+
const closing = new RegExp(`^ {0,3}${opening[1][0]}{${opening[1].length},}[ \\t]*$`);
|
|
43
|
+
return raw
|
|
44
|
+
.slice(opening[0].length)
|
|
45
|
+
.split("\n")
|
|
46
|
+
.some(line => closing.test(line));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Validate JSON grammar while emitting the original lexical tokens, never JS values. */
|
|
50
|
+
function formatJson(source: string): { display: string; mapping: CodeMapping[] } {
|
|
51
|
+
let position = 0;
|
|
52
|
+
let display = "";
|
|
53
|
+
const mapping: CodeMapping[] = [];
|
|
54
|
+
const whitespace = () => {
|
|
55
|
+
while (/[ \t\r\n]/.test(source[position] ?? "") && position < source.length) position++;
|
|
56
|
+
};
|
|
57
|
+
const emit = (start: number, end: number) => {
|
|
58
|
+
mapping.push({
|
|
59
|
+
sourceStart: start,
|
|
60
|
+
sourceEnd: end,
|
|
61
|
+
displayStart: display.length,
|
|
62
|
+
displayEnd: display.length + end - start,
|
|
63
|
+
});
|
|
64
|
+
display += source.slice(start, end);
|
|
65
|
+
};
|
|
66
|
+
const punctuation = (expected: string) => {
|
|
67
|
+
whitespace();
|
|
68
|
+
if (source[position] !== expected) throw new Error("Incomplete JSON");
|
|
69
|
+
emit(position, ++position);
|
|
70
|
+
};
|
|
71
|
+
const string = () => {
|
|
72
|
+
whitespace();
|
|
73
|
+
const match = /^"(?:[^"\\\x00-\x1f]|\\(?:["\\/bfnrt]|u[\da-fA-F]{4}))*"/.exec(source.slice(position));
|
|
74
|
+
if (!match) throw new Error("Invalid JSON string");
|
|
75
|
+
const start = position;
|
|
76
|
+
position += match[0].length;
|
|
77
|
+
emit(start, position);
|
|
78
|
+
};
|
|
79
|
+
const newline = (depth: number) => {
|
|
80
|
+
display += `\n${" ".repeat(depth)}`;
|
|
81
|
+
};
|
|
82
|
+
const value = (depth: number): void => {
|
|
83
|
+
if (depth > 200) throw new Error("JSON nesting limit");
|
|
84
|
+
whitespace();
|
|
85
|
+
const char = source[position];
|
|
86
|
+
if (char === "{") {
|
|
87
|
+
punctuation("{");
|
|
88
|
+
whitespace();
|
|
89
|
+
if (source[position] !== "}") {
|
|
90
|
+
while (true) {
|
|
91
|
+
newline(depth + 1);
|
|
92
|
+
string();
|
|
93
|
+
punctuation(":");
|
|
94
|
+
display += " ";
|
|
95
|
+
value(depth + 1);
|
|
96
|
+
whitespace();
|
|
97
|
+
if (source[position] !== ",") break;
|
|
98
|
+
punctuation(",");
|
|
99
|
+
}
|
|
100
|
+
newline(depth);
|
|
101
|
+
}
|
|
102
|
+
punctuation("}");
|
|
103
|
+
} else if (char === "[") {
|
|
104
|
+
punctuation("[");
|
|
105
|
+
whitespace();
|
|
106
|
+
if (source[position] !== "]") {
|
|
107
|
+
while (true) {
|
|
108
|
+
newline(depth + 1);
|
|
109
|
+
value(depth + 1);
|
|
110
|
+
whitespace();
|
|
111
|
+
if (source[position] !== ",") break;
|
|
112
|
+
punctuation(",");
|
|
113
|
+
}
|
|
114
|
+
newline(depth);
|
|
115
|
+
}
|
|
116
|
+
punctuation("]");
|
|
117
|
+
} else if (char === '"') string();
|
|
118
|
+
else {
|
|
119
|
+
const match = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(source.slice(position));
|
|
120
|
+
if (!match) throw new Error("Invalid JSON value");
|
|
121
|
+
const start = position;
|
|
122
|
+
position += match[0].length;
|
|
123
|
+
emit(start, position);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
value(0);
|
|
127
|
+
whitespace();
|
|
128
|
+
if (position !== source.length) throw new Error("Trailing JSON content");
|
|
129
|
+
return { display, mapping };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Preserve node types, order, metadata and lexical scalar values across YAML formatting. */
|
|
133
|
+
function yamlSignature(node: unknown): unknown {
|
|
134
|
+
if (isPair(node)) return [yamlSignature(node.key), yamlSignature(node.value)];
|
|
135
|
+
if (isScalar(node))
|
|
136
|
+
return [
|
|
137
|
+
"scalar",
|
|
138
|
+
typeof node.value,
|
|
139
|
+
String(node.value),
|
|
140
|
+
node.source,
|
|
141
|
+
node.tag,
|
|
142
|
+
node.anchor,
|
|
143
|
+
node.comment,
|
|
144
|
+
node.commentBefore,
|
|
145
|
+
];
|
|
146
|
+
if (isCollection(node))
|
|
147
|
+
return [
|
|
148
|
+
node.constructor.name,
|
|
149
|
+
node.tag,
|
|
150
|
+
node.anchor,
|
|
151
|
+
node.comment,
|
|
152
|
+
node.commentBefore,
|
|
153
|
+
node.items.map(yamlSignature),
|
|
154
|
+
];
|
|
155
|
+
if (node && typeof node === "object") {
|
|
156
|
+
const alias = node as { source?: string; comment?: string; commentBefore?: string };
|
|
157
|
+
return ["alias", alias.source, alias.comment, alias.commentBefore];
|
|
158
|
+
}
|
|
159
|
+
return node;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function formatYaml(source: string): string {
|
|
163
|
+
const options = { keepSourceTokens: true, intAsBigInt: true };
|
|
164
|
+
const docs = parseAllDocuments(source, options);
|
|
165
|
+
if (!docs.length || docs.some(doc => doc.errors.length || doc.warnings.length)) return source;
|
|
166
|
+
const signature = (documents: typeof docs) =>
|
|
167
|
+
JSON.stringify(
|
|
168
|
+
documents.map(doc => [doc.directives, doc.commentBefore, doc.comment, yamlSignature(doc.contents)]),
|
|
169
|
+
);
|
|
170
|
+
const before = signature(docs);
|
|
171
|
+
const block = (node: unknown): void => {
|
|
172
|
+
if (isPair(node)) {
|
|
173
|
+
block(node.key);
|
|
174
|
+
block(node.value);
|
|
175
|
+
} else if (isCollection(node)) {
|
|
176
|
+
node.flow = false;
|
|
177
|
+
node.items.forEach(block);
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
for (const doc of docs) block(doc.contents);
|
|
181
|
+
const display = docs.map(doc => doc.toString({ indent: 2, lineWidth: 0 })).join("");
|
|
182
|
+
const check = parseAllDocuments(display, options);
|
|
183
|
+
return check.every(doc => !doc.errors.length && !doc.warnings.length) && signature(check) === before
|
|
184
|
+
? display.replace(/\n$/, "")
|
|
185
|
+
: source;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function presentCode(source: string, info?: string, complete = true): CodePresentation {
|
|
189
|
+
const language = normalizeCodeLanguage(info);
|
|
190
|
+
let display = source;
|
|
191
|
+
let mapping: CodeMapping[] = [];
|
|
192
|
+
try {
|
|
193
|
+
if (complete && language === "json") ({ display, mapping } = formatJson(source));
|
|
194
|
+
else if (complete && language === "yaml") display = formatYaml(source);
|
|
195
|
+
} catch {
|
|
196
|
+
/* Invalid/incomplete/unsupported content always remains readable source. */
|
|
197
|
+
}
|
|
198
|
+
if (!mapping.length)
|
|
199
|
+
mapping = [{ sourceStart: 0, sourceEnd: source.length, displayStart: 0, displayEnd: display.length }];
|
|
200
|
+
return { source, display, language, formatted: display !== source, mapping };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export interface CodeSegment {
|
|
204
|
+
start: number;
|
|
205
|
+
end: number;
|
|
206
|
+
continuation: boolean;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** HTTP examples may omit a protocol version and use documented path placeholders. */
|
|
210
|
+
export function mapHttpCode(
|
|
211
|
+
source: string,
|
|
212
|
+
render: (text: string, category?: "keyword" | "string" | "number" | "variable" | "punctuation") => string,
|
|
213
|
+
body: (text: string, language: string) => string,
|
|
214
|
+
): string {
|
|
215
|
+
const separator = /\r?\n[ \t]*\r?\n/.exec(source);
|
|
216
|
+
const headers = separator ? source.slice(0, separator.index) : source;
|
|
217
|
+
let bodyLanguage = "";
|
|
218
|
+
let result = "";
|
|
219
|
+
for (const line of headers.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
|
|
220
|
+
const ending = /\r?\n$/.exec(line)?.[0] ?? "";
|
|
221
|
+
const content = line.slice(0, line.length - ending.length);
|
|
222
|
+
const request =
|
|
223
|
+
/^([ \t]*)(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS|CONNECT|TRACE)([ \t]+)(\S+)(?:([ \t]+)(HTTP\/\d(?:\.\d)?))?([ \t]*)$/.exec(
|
|
224
|
+
content,
|
|
225
|
+
);
|
|
226
|
+
const status = /^([ \t]*)(HTTP\/\d(?:\.\d)?)([ \t]+)(\d{3})(.*)$/.exec(content);
|
|
227
|
+
const header = /^([ \t]*)([\w-]+)(:)(.*)$/.exec(content);
|
|
228
|
+
if (request)
|
|
229
|
+
result +=
|
|
230
|
+
render(request[1]) +
|
|
231
|
+
render(request[2], "keyword") +
|
|
232
|
+
render(request[3]) +
|
|
233
|
+
render(request[4], "string") +
|
|
234
|
+
render(request[5] ?? "") +
|
|
235
|
+
render(request[6] ?? "", "keyword") +
|
|
236
|
+
render(request[7]);
|
|
237
|
+
else if (status)
|
|
238
|
+
result +=
|
|
239
|
+
render(status[1]) +
|
|
240
|
+
render(status[2], "keyword") +
|
|
241
|
+
render(status[3]) +
|
|
242
|
+
render(status[4], "number") +
|
|
243
|
+
render(status[5], "string");
|
|
244
|
+
else if (header) {
|
|
245
|
+
if (/^content-type$/i.test(header[2])) {
|
|
246
|
+
const mime = header[4].trim().split(";")[0].trim().toLowerCase();
|
|
247
|
+
bodyLanguage = /^(?:application|text)\/(?:json|[a-z0-9!#$&^_.+-]+\+json)$/.test(mime)
|
|
248
|
+
? "json"
|
|
249
|
+
: /^(?:application|text)\/(?:(?:x-)?ya?ml|[a-z0-9!#$&^_.+-]+\+yaml)$/.test(mime)
|
|
250
|
+
? "yaml"
|
|
251
|
+
: "";
|
|
252
|
+
}
|
|
253
|
+
result +=
|
|
254
|
+
render(header[1]) +
|
|
255
|
+
render(header[2], "variable") +
|
|
256
|
+
render(":", "punctuation") +
|
|
257
|
+
render(header[4], "string");
|
|
258
|
+
} else result += render(content);
|
|
259
|
+
result += render(ending);
|
|
260
|
+
}
|
|
261
|
+
return separator
|
|
262
|
+
? result + render(separator[0]) + body(source.slice(separator.index + separator[0].length), bodyLanguage)
|
|
263
|
+
: result;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Prefer token boundaries outside quoted literals. A hard wrap is explicitly visual. */
|
|
267
|
+
export function wrapCodeLine(
|
|
268
|
+
line: string,
|
|
269
|
+
width: number,
|
|
270
|
+
measure: (text: string) => number = text => [...text].length,
|
|
271
|
+
): CodeSegment[] {
|
|
272
|
+
const boundaries = new Set<number>();
|
|
273
|
+
let quote = "";
|
|
274
|
+
let escaped = false;
|
|
275
|
+
for (let i = 0; i < line.length; i++) {
|
|
276
|
+
const char = line[i];
|
|
277
|
+
if (escaped) {
|
|
278
|
+
escaped = false;
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
if (char === "\\") {
|
|
282
|
+
escaped = true;
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
if (quote) {
|
|
286
|
+
if (char === quote) quote = "";
|
|
287
|
+
} else if (char === '"' || char === "'" || char === "`") quote = char;
|
|
288
|
+
else if (/[\s,;{}[\]()=:+]/.test(char)) boundaries.add(i + 1);
|
|
289
|
+
}
|
|
290
|
+
const result: CodeSegment[] = [];
|
|
291
|
+
let start = 0;
|
|
292
|
+
while (start < line.length) {
|
|
293
|
+
let end = start;
|
|
294
|
+
let boundary = start;
|
|
295
|
+
for (const char of line.slice(start)) {
|
|
296
|
+
const next = end + char.length;
|
|
297
|
+
if (measure(line.slice(start, next)) > Math.max(1, width)) break;
|
|
298
|
+
end = next;
|
|
299
|
+
if (boundaries.has(end)) boundary = end;
|
|
300
|
+
}
|
|
301
|
+
if (end === start) end = start + (line.codePointAt(start)! > 0xffff ? 2 : 1);
|
|
302
|
+
if (end < line.length && boundary > start) end = boundary;
|
|
303
|
+
result.push({ start, end, continuation: start > 0 });
|
|
304
|
+
start = end;
|
|
305
|
+
}
|
|
306
|
+
return result.length ? result : [{ start: 0, end: 0, continuation: false }];
|
|
307
|
+
}
|