-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
320 lines (291 loc) · 8.32 KB
/
worker.js
File metadata and controls
320 lines (291 loc) · 8.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
let currentJobId = 0;
const TARGET_CHUNK_BYTES = 1000000;
self.onmessage = async (e) => {
const { type, jobId, text } = e.data || {};
if (type !== "format") return;
currentJobId = jobId;
try {
post({ type: "progress", jobId, percent: 5, stage: "Parsing…" });
const t0 = performance.now();
// 1) Parse (native is fastest)
const obj = JSON.parse(text);
// 2) Pretty print
post({ type: "progress", jobId, percent: 20, stage: "Formatting…" });
const pretty = JSON.stringify(obj, null, 2);
const totalChars = pretty.length;
// 3) Stream by byte-sized chunks (not lines)
post({
type: "progress",
jobId,
percent: 35,
stage: "Highlighting…",
detail: bytesLabel(totalChars),
});
// Pre-encode for near-constant-time substring -> bytes estimation
// JS strings are UTF-16; we’ll approximate byte splits by char length,
// then snap to nearest newline to preserve line integrity.
const indices = computeChunkBoundaries(pretty, TARGET_CHUNK_BYTES);
const totalChunks = indices.length - 1;
for (let i = 0; i < totalChunks; i++) {
if (currentJobId !== jobId) return;
const start = indices[i];
const end = indices[i + 1];
const slice = pretty.slice(start, end);
// Single-pass tokenize + escape within this slice
const html = highlightChunk(slice);
post({ type: "chunk", jobId, index: i, html });
// Yield to keep under frame budget
// Microtask for small slices, small timeout for very large ones
if (html.length > 150_000) {
await delay(1);
} else {
await Promise.resolve();
}
const pct = 35 + Math.round(((i + 1) / totalChunks) * 60);
post({
type: "progress",
jobId,
percent: Math.min(97, pct),
stage: "Highlighting…",
detail: `${i + 1}/${totalChunks} chunks`,
});
}
if (currentJobId !== jobId) return;
const ms = Math.round(performance.now() - t0);
post({
type: "done",
jobId,
formatted: pretty,
highlighted: true,
totalLines: pretty.split("\n").length,
ms,
});
} catch (err) {
post({ type: "error", jobId, message: err?.message || String(err) });
}
};
function post(msg) {
self.postMessage(msg);
}
function delay(ms) {
return new Promise((r) => setTimeout(r, ms));
}
function bytesLabel(n) {
const kb = n / 1024;
return kb < 1024 ? `${kb.toFixed(1)}KB` : `${(kb / 1024).toFixed(1)}MB`;
}
function computeChunkBoundaries(str, targetBytes) {
const len = str.length;
if (len <= targetBytes) return [0, len];
const idx = [0];
let pos = 0;
while (pos < len) {
let next = pos + targetBytes;
if (next >= len) {
idx.push(len);
break;
}
// snap to newline boundary nearby to avoid split mid-line
let snap = next;
// look forward a bit
for (let j = 0; j < 2000 && snap < len; j++, snap++) {
if (str.charCodeAt(snap) === 10) {
next = snap + 1;
break;
}
}
if (next === pos + targetBytes) {
// look backward a bit if no forward newline found
snap = next;
for (let j = 0; j < 2000 && snap > pos; j++, snap--) {
if (str.charCodeAt(snap) === 10) {
next = snap + 1;
break;
}
}
}
idx.push(next);
pos = next;
}
return idx;
}
// Fast escape
function esc(s) {
return s.replace(/[&<>]/g, (c) =>
c === "&" ? "&" : c === "<" ? "<" : ">"
);
}
// Single-pass tokenizer over a chunk: highlights values, not keys
function highlightChunk(src) {
let out = "";
let i = 0;
const n = src.length;
// states
const S_TEXT = 0,
S_STRING = 1,
S_STRING_ESC = 2;
let state = S_TEXT;
while (i < n) {
const ch = src.charCodeAt(i);
if (state === S_TEXT) {
if (ch === 34 /* " */) {
// string start - decide later if value or key by looking behind for colon
// we’ll capture the raw string then decide based on preceding colon+whitespace
const start = i;
i++; // consume "
let s = '"';
state = S_STRING;
// collect string
while (i < n && state !== S_TEXT) {
const c = src.charCodeAt(i++);
if (state === S_STRING) {
if (c === 92) {
// \
state = S_STRING_ESC;
s += "\\";
} else if (c === 34) {
// "
s += '"';
state = S_TEXT;
break;
} else {
s += String.fromCharCode(c);
}
} else {
// ESC
s += String.fromCharCode(c);
state = S_STRING;
}
}
// determine if this string is a value (after colon) or key (before colon)
// look backward from start for non-space; if it’s a colon, treat as value
let j = start - 1;
while (j >= 0) {
const cj = src.charCodeAt(j);
if (cj === 32 || cj === 9 || cj === 13 || cj === 10) {
j--;
continue;
}
if (cj === 58 /* : */) {
out += `<span class="jv-string">${esc(s)}</span>`;
} else {
out += esc(s);
}
break;
}
if (j < 0) {
// beginning of chunk, unknown context -> emit raw escaped
out += esc(s);
}
continue;
}
// numbers / booleans / null only in value position (after colon)
if (isValueNumberStart(src, i)) {
const { token, next } = readNumber(src, i);
out += `<span class="jv-number">${esc(token)}</span>`;
i = next;
continue;
}
if (isValueKeyword(src, i, "true")) {
out += `<span class="jv-boolean">true</span>`;
i += 4;
continue;
}
if (isValueKeyword(src, i, "false")) {
out += `<span class="jv-boolean">false</span>`;
i += 5;
continue;
}
if (isValueKeyword(src, i, "null")) {
out += `<span class="jv-null">null</span>`;
i += 4;
continue;
}
// punctuation
if (ch === 123 || ch === 125 || ch === 91 || ch === 93 || ch === 44) {
out += `<span class="jv-punc">${esc(src[i])}</span>`;
i++;
continue;
}
// other
out += esc(src[i]);
i++;
continue;
}
// shouldn't get here; string handled inline
i++;
}
return out;
}
function isValueNumberStart(src, i) {
// check we are after a colon (value context)
let k = i - 1;
while (k >= 0) {
const c = src.charCodeAt(k);
if (c === 32 || c === 9 || c === 13 || c === 10) {
k--;
continue;
}
if (c === 58) break; // colon
return false;
}
const ch = src.charCodeAt(i);
return ch === 45 /* - */ || (ch >= 48 && ch <= 57); // digit
}
function readNumber(src, i) {
const start = i;
let ch = src.charCodeAt(i);
if (ch === 45) i++; // -
// int
while (i < src.length) {
ch = src.charCodeAt(i);
if (ch < 48 || ch > 57) break;
i++;
}
// frac
if (src.charCodeAt(i) === 46 /* . */) {
i++;
while (i < src.length) {
ch = src.charCodeAt(i);
if (ch < 48 || ch > 57) break;
i++;
}
}
// exp
const e = src.charCodeAt(i);
if (e === 101 || e === 69) {
// e/E
i++;
const sgn = src.charCodeAt(i);
if (sgn === 43 || sgn === 45) i++;
while (i < src.length) {
ch = src.charCodeAt(i);
if (ch < 48 || ch > 57) break;
i++;
}
}
return { token: src.slice(start, i), next: i };
}
function isValueKeyword(src, i, kw) {
// must be after colon (value context) and exact match
let k = i - 1;
while (k >= 0) {
const c = src.charCodeAt(k);
if (c === 32 || c === 9 || c === 13 || c === 10) {
k--;
continue;
}
if (c === 58) break;
return false;
}
if (src.substr(i, kw.length) !== kw) return false;
const end = i + kw.length;
const b = src.charCodeAt(end);
// boundary char
return (
!(b >= 48 && b <= 57) &&
!(b >= 65 && b <= 90) &&
!(b >= 97 && b <= 122) &&
b !== 95
);
}