hypotes 0.1.0 → 0.2.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.
package/dist/register.js CHANGED
@@ -1,6 +1,342 @@
1
1
  import { n as ModuleMocks, t as MOCKS_KEY } from "./mocks-ciQvBYVw.js";
2
2
  import { createRequire, getSourceMapsSupport, registerHooks, setSourceMapsSupport } from "node:module";
3
+ import { Buffer } from "node:buffer";
3
4
  import { fileURLToPath } from "node:url";
5
+ // source/source-map.ts
6
+ const STRIDE = 5;
7
+ const SOURCE_MAPPING_URL = "//# sourceMappingURL=";
8
+ /** The starts of a source map's base64 data URL, as tools write it */
9
+ const DATA_URLS = ["data:application/json;base64,", "data:application/json;charset=utf-8;base64,"];
10
+ const COMMA = 44;
11
+ const SEMICOLON = 59;
12
+ const NO_OFFSET = {
13
+ column: 0,
14
+ source: 0,
15
+ name: 0
16
+ };
17
+ /**
18
+ * The code without the inline source map at its end, and that map, unless
19
+ * it doesn't parse or isn't a source map. A map comment that isn't on the
20
+ * code's last line, but for whitespace, stays in the code.
21
+ */
22
+ function splitInlineMap(text) {
23
+ const end = trimmedEnd(text);
24
+ if (end === 0 || !isBase64Digit(text.codePointAt(end - 1) ?? 0)) return {
25
+ code: text,
26
+ map: void 0
27
+ };
28
+ const index = lastIndexOf(text, SOURCE_MAPPING_URL);
29
+ if (index === -1) return {
30
+ code: text,
31
+ map: void 0
32
+ };
33
+ const data = dataUrlData(text, index + 21, end);
34
+ if (data === void 0) return {
35
+ code: text,
36
+ map: void 0
37
+ };
38
+ const code = text.slice(0, index);
39
+ try {
40
+ const json = Buffer.from(data, "base64").toString("utf8");
41
+ const map = JSON.parse(json);
42
+ return {
43
+ code,
44
+ map: isIncomingSourceMap(map) ? map : void 0
45
+ };
46
+ } catch {
47
+ return {
48
+ code,
49
+ map: void 0
50
+ };
51
+ }
52
+ }
53
+ /**
54
+ * The decoded map of the hoisted code, through the incoming map, to where
55
+ * that one maps it
56
+ */
57
+ function chainSourceMap(map, incoming) {
58
+ const index = indexSourceMap(incoming);
59
+ const sources = new IndexedSources(index.sources);
60
+ const names = new Names();
61
+ const mappings = map.mappings.map((line) => chainLine(line, map.names, index, sources, names));
62
+ const { sourcesContent } = index;
63
+ const sourceRoot = "sources" in incoming && typeof incoming.sourceRoot === "string" ? { sourceRoot: incoming.sourceRoot } : {};
64
+ return {
65
+ file: map.file,
66
+ ...sourceRoot,
67
+ sources: sources.values(),
68
+ sourcesContent: sourcesContent === void 0 ? void 0 : sources.indices().map((source) => sourcesContent[source] ?? null),
69
+ names: names.values(),
70
+ mappings
71
+ };
72
+ }
73
+ /**
74
+ * The segments of a line of the map of the hoisted code, through the
75
+ * incoming map. A segment without a source stays as it is. A segment's name
76
+ * is the incoming map's, or its own.
77
+ */
78
+ function chainLine(line, mapNames, index, sources, names) {
79
+ const chained = [];
80
+ for (const segment of line) {
81
+ if (segment.length === 1) {
82
+ chained.push(segment);
83
+ continue;
84
+ }
85
+ const [column, , originalLine, originalColumn, nameIndex] = segment;
86
+ const segments = index.lines[originalLine];
87
+ if (segments === void 0) continue;
88
+ const found = findSegment(segments, originalColumn);
89
+ if (found === -1) continue;
90
+ const source = sources.indexOf(segments[found + 1]);
91
+ const incomingName = segments[found + 4];
92
+ const name = incomingName === -1 ? nameIndex === void 0 ? void 0 : mapNames[nameIndex] : index.names[incomingName];
93
+ chained.push(name === void 0 ? [
94
+ column,
95
+ source,
96
+ segments[found + 2],
97
+ segments[found + 3]
98
+ ] : [
99
+ column,
100
+ source,
101
+ segments[found + 2],
102
+ segments[found + 3],
103
+ names.indexOf(name)
104
+ ]);
105
+ }
106
+ return chained;
107
+ }
108
+ /** Where the whitespace at the end of the text starts */
109
+ function trimmedEnd(text) {
110
+ let end = text.length;
111
+ while (end > 0 && isWhitespace(text.codePointAt(end - 1) ?? 0)) end--;
112
+ return end;
113
+ }
114
+ function isWhitespace(code) {
115
+ return code === 9 || code === 10 || code === 13 || code === 32;
116
+ }
117
+ /** Whether the code is that of a digit of base64, or its padding */
118
+ function isBase64Digit(code) {
119
+ return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 43 || code === 47 || code === 61;
120
+ }
121
+ /**
122
+ * The index of the last occurrence of the search string, which this finds
123
+ * by searching forwards from each occurrence: V8 searches forwards several
124
+ * times as fast as backwards, through a map's base64 as well
125
+ */
126
+ function lastIndexOf(text, search) {
127
+ let index = text.indexOf(search);
128
+ if (index === -1) return -1;
129
+ let next = text.indexOf(search, index + 1);
130
+ while (next !== -1) {
131
+ index = next;
132
+ next = text.indexOf(search, index + 1);
133
+ }
134
+ return index;
135
+ }
136
+ /**
137
+ * The data of a base64 data URL of JSON from the start up to the end, if
138
+ * the URL is one, and on the text's last line
139
+ */
140
+ function dataUrlData(text, start, end) {
141
+ const prefix = DATA_URLS.find((url) => text.startsWith(url, start));
142
+ if (prefix === void 0) return;
143
+ const dataStart = start + prefix.length;
144
+ const lineEnd = text.indexOf("\n", dataStart);
145
+ if (lineEnd !== -1 && lineEnd < end) return;
146
+ return text.slice(dataStart, end);
147
+ }
148
+ function isIncomingSourceMap(value) {
149
+ if (typeof value !== "object" || value === null) return false;
150
+ if ("sections" in value) return Array.isArray(value.sections) && value.sections.every(isSection);
151
+ return isModuleSourceMap(value);
152
+ }
153
+ function isSection(value) {
154
+ if (typeof value !== "object" || value === null) return false;
155
+ const { offset, map } = value;
156
+ return typeof offset === "object" && offset !== null && Number.isInteger(offset.line) && Number.isInteger(offset.column) && isModuleSourceMap(map);
157
+ }
158
+ function isModuleSourceMap(value) {
159
+ if (typeof value !== "object" || value === null) return false;
160
+ const { sources, mappings, names, sourcesContent } = value;
161
+ return typeof mappings === "string" && Array.isArray(sources) && (names === void 0 || Array.isArray(names)) && (sourcesContent === void 0 || Array.isArray(sourcesContent));
162
+ }
163
+ /**
164
+ * Decodes the incoming map by line, with the segments of each section of an
165
+ * index map moved to where the section starts
166
+ */
167
+ function indexSourceMap(map) {
168
+ if (!("sections" in map)) return {
169
+ lines: decodeMappings(map.mappings, NO_OFFSET),
170
+ sources: map.sources,
171
+ sourcesContent: map.sourcesContent,
172
+ names: map.names ?? []
173
+ };
174
+ const lines = [];
175
+ const sources = [];
176
+ const sourcesContent = [];
177
+ const names = [];
178
+ let hasContent = false;
179
+ for (const { offset, map: section } of map.sections) {
180
+ addSection(lines, decodeMappings(section.mappings, {
181
+ column: offset.column,
182
+ source: sources.length,
183
+ name: names.length
184
+ }), offset.line);
185
+ hasContent ||= section.sourcesContent !== void 0;
186
+ for (const [index, source] of section.sources.entries()) {
187
+ sources.push(source);
188
+ sourcesContent.push(section.sourcesContent?.[index] ?? null);
189
+ }
190
+ names.push(...section.names ?? []);
191
+ }
192
+ return {
193
+ lines,
194
+ sources,
195
+ sourcesContent: hasContent ? sourcesContent : void 0,
196
+ names
197
+ };
198
+ }
199
+ /**
200
+ * Adds the lines of a section from the line where it starts, where the
201
+ * section before it may end
202
+ */
203
+ function addSection(lines, section, start) {
204
+ while (lines.length < start) lines.push([]);
205
+ for (const [index, segments] of section.entries()) {
206
+ const line = lines[start + index];
207
+ if (line === void 0) lines.push(segments);
208
+ else line.push(...segments);
209
+ }
210
+ }
211
+ /**
212
+ * Decodes the segments of mappings that map to a source, by line, moved by
213
+ * the offset. Invalid mappings decode to positions that map nowhere useful,
214
+ * rather than throwing, as Node's own decoding does.
215
+ */
216
+ function decodeMappings(mappings, offset) {
217
+ const { length } = mappings;
218
+ const lines = [];
219
+ const fields = [
220
+ 0,
221
+ 0,
222
+ 0,
223
+ 0,
224
+ 0
225
+ ];
226
+ let segments = [];
227
+ let fieldCount = 0;
228
+ let column = offset.column;
229
+ let source = offset.source;
230
+ let originalLine = 0;
231
+ let originalColumn = 0;
232
+ let name = offset.name;
233
+ let value = 0;
234
+ let shift = 0;
235
+ for (let index = 0; index <= length; index++) {
236
+ const char = index < length ? mappings.charCodeAt(index) : SEMICOLON;
237
+ if (char === COMMA || char === SEMICOLON) {
238
+ if (fieldCount > 0) column += fields[0];
239
+ if (fieldCount >= 4) {
240
+ source += fields[1];
241
+ originalLine += fields[2];
242
+ originalColumn += fields[3];
243
+ if (fieldCount >= 5) name += fields[4];
244
+ segments.push(column, source, originalLine, originalColumn, fieldCount >= 5 ? name : -1);
245
+ }
246
+ fieldCount = 0;
247
+ if (char === SEMICOLON) {
248
+ lines.push(segments);
249
+ segments = [];
250
+ column = 0;
251
+ }
252
+ continue;
253
+ }
254
+ const digit = base64Value(char);
255
+ value += (digit & 31) << shift;
256
+ if ((digit & 32) === 0) {
257
+ fields[fieldCount++] = value & 1 ? -(value >>> 1) : value >>> 1;
258
+ value = 0;
259
+ shift = 0;
260
+ } else shift += 5;
261
+ }
262
+ return lines;
263
+ }
264
+ /** The value of a base64 digit, from its code */
265
+ function base64Value(code) {
266
+ if (code >= 97) return code - 97 + 26;
267
+ if (code >= 65) return code - 65;
268
+ if (code >= 48) return code - 48 + 52;
269
+ return code === 43 ? 62 : 63;
270
+ }
271
+ /**
272
+ * The offset in a line's segments of the last segment at or before the
273
+ * column, or -1, by a binary search of the segments, which are in order
274
+ */
275
+ function findSegment(segments, column) {
276
+ let low = 0;
277
+ let high = segments.length / STRIDE - 1;
278
+ let found = -1;
279
+ while (low <= high) {
280
+ const middle = low + high >>> 1;
281
+ if (segments[middle * STRIDE] <= column) {
282
+ found = middle * STRIDE;
283
+ low = middle + 1;
284
+ } else high = middle - 1;
285
+ }
286
+ return found;
287
+ }
288
+ /**
289
+ * The sources of the incoming map that the chained map refers to, in the
290
+ * order that they're first referred to
291
+ */
292
+ var IndexedSources = class {
293
+ #incoming;
294
+ /** The index of each incoming source among the chained map's, or -1 */
295
+ #indices;
296
+ #values = [];
297
+ #incomingIndices = [];
298
+ constructor(incoming) {
299
+ this.#incoming = incoming;
300
+ this.#indices = new Int32Array(incoming.length).fill(-1);
301
+ }
302
+ /** The index in the chained map of the incoming source at the index */
303
+ indexOf(incoming) {
304
+ let index = this.#indices[incoming];
305
+ if (index === -1) {
306
+ index = this.#values.push(this.#incoming[incoming] ?? null) - 1;
307
+ this.#incomingIndices.push(incoming);
308
+ this.#indices[incoming] = index;
309
+ }
310
+ return index;
311
+ }
312
+ /**
313
+ * The sources, by their index in the chained map. One may be null, as
314
+ * in the incoming map, which magic-string's types leave out.
315
+ */
316
+ values() {
317
+ return this.#values;
318
+ }
319
+ /** The index of each source in the incoming map */
320
+ indices() {
321
+ return this.#incomingIndices;
322
+ }
323
+ };
324
+ /** The names of the chained map, in the order that they're first given */
325
+ var Names = class {
326
+ #indices = /* @__PURE__ */ new Map();
327
+ #values = [];
328
+ indexOf(name) {
329
+ let index = this.#indices.get(name);
330
+ if (index === void 0) {
331
+ index = this.#values.push(name) - 1;
332
+ this.#indices.set(name, index);
333
+ }
334
+ return index;
335
+ }
336
+ values() {
337
+ return this.#values;
338
+ }
339
+ };
4
340
  // source/hoist.ts
5
341
  /**
6
342
  * A call that the transform looks for, before it parses the module, with
@@ -37,9 +373,9 @@ let dependencies;
37
373
  function hoistModule(url, loaded) {
38
374
  const { format, source } = loaded;
39
375
  if (source === void 0 || format !== "module" && format !== "module-typescript" || !url.startsWith("file:") || url.includes("/node_modules/")) return loaded;
40
- const code = typeof source === "string" ? source : decoder.decode(source);
41
- if (!MOCK_CALL.test(code)) return loaded;
42
- const hoisted = hoistMocks(code, url);
376
+ const text = typeof source === "string" ? source : decoder.decode(source);
377
+ if (!MOCK_CALL.test(text)) return loaded;
378
+ const hoisted = hoistMocks(splitInlineMap(text), url);
43
379
  if (hoisted === void 0) return loaded;
44
380
  if (!getSourceMapsSupport().enabled) setSourceMapsSupport(true);
45
381
  return {
@@ -51,10 +387,11 @@ function hoistModule(url, loaded) {
51
387
  function loadDependencies() {
52
388
  if (dependencies === void 0) try {
53
389
  const { parseSync, Visitor } = require("oxc-parser");
54
- const { MagicString } = require("magic-string");
390
+ const { MagicString, SourceMap } = require("magic-string");
55
391
  dependencies = {
56
392
  MagicString,
57
393
  parseSync,
394
+ SourceMap,
58
395
  Visitor
59
396
  };
60
397
  } catch (error) {
@@ -64,11 +401,12 @@ function loadDependencies() {
64
401
  return dependencies;
65
402
  }
66
403
  /**
67
- * The module's code, with its mocks hoisted, and its source map, unless it
68
- * doesn't parse, which Node reports as it compiles it, or doesn't call `vi`
404
+ * The module's code, with its mocks hoisted, and its source map, chained to
405
+ * the map that the code came with, unless it doesn't parse, which Node
406
+ * reports as it compiles it, or doesn't call `vi`
69
407
  */
70
- function hoistMocks(code, url) {
71
- const { MagicString, parseSync, Visitor } = loadDependencies();
408
+ function hoistMocks({ code, map: incoming }, url) {
409
+ const { MagicString, SourceMap, parseSync, Visitor } = loadDependencies();
72
410
  const path = fileURLToPath(url);
73
411
  const { errors, module, program } = parseSync(path, code, { sourceType: "module" });
74
412
  if (errors.length > 0) return;
@@ -80,11 +418,28 @@ function hoistMocks(code, url) {
80
418
  const paths = resolvePaths(s, calls, code);
81
419
  wrapDynamicImports(s, module.dynamicImports, paths);
82
420
  if (hoisted.length > 0) hoist(s, program, hoisted, code, path);
83
- const map = s.generateMap({
421
+ const decoded = s.generateDecodedMap({
84
422
  source: url,
85
423
  hires: "boundary"
86
424
  });
87
- return `${s.toString()}\n//# sourceMappingURL=${map.toUrl()}\n`;
425
+ const map = incoming === void 0 ? new SourceMap(decoded) : encodeChained(SourceMap, chainSourceMap(decoded, incoming));
426
+ return `${s.toString()}\n//# sourceMappingURL=${dataUrlOf(map)}\n`;
427
+ }
428
+ /**
429
+ * The map as a base64 data URL, as magic-string's `toUrl()` writes it, but
430
+ * with Buffer, which took a third of the time of its `btoa()` of the
431
+ * escaped JSON
432
+ */
433
+ function dataUrlOf(map) {
434
+ return `data:application/json;charset=utf-8;base64,${Buffer.from(map.toString()).toString("base64")}`;
435
+ }
436
+ /**
437
+ * Encodes a chained map with magic-string's, which takes decoded mappings,
438
+ * but not the `sourceRoot` of its sources
439
+ */
440
+ function encodeChained(SourceMap, { sourceRoot, ...map }) {
441
+ const encoded = new SourceMap(map);
442
+ return sourceRoot === void 0 ? encoded : Object.assign(encoded, { sourceRoot });
88
443
  }
89
444
  /** The module's calls of the methods of `vi` that mock, in order */
90
445
  function callsOf(program, Visitor) {
@@ -0,0 +1,8 @@
1
+ import { type TestEvent } from 'node:test/reporters';
2
+ /**
3
+ * The reporter, as `--test-reporter=hypotes/reporter` loads it, and as the
4
+ * stream of node:test's `run()` composes it. Besides the files' rows, the
5
+ * errors and the totals, it prints what tests write to stdout and stderr,
6
+ * their diagnostics, and the coverage as node:test's `spec` does.
7
+ */
8
+ export default function reporter(source: AsyncIterable<TestEvent>): AsyncGenerator<string, void>;