@shadow-js/vite 1.0.4 → 1.0.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.5
4
+
5
+ ### Fixed
6
+
7
+ - MDX compile errors and warnings no longer report positions of the generated JSX as positions of the `.mdx` file.
8
+ - MDX source maps point at the `.mdx` file for imports, exports and copied JavaScript.
9
+
3
10
  ## 1.0.4
4
11
 
5
12
  ### Changed
package/README.md CHANGED
@@ -124,9 +124,9 @@ export default defineConfig({
124
124
 
125
125
  ## Hot updates
126
126
 
127
- The plugin turns on the compiler's `hmr` option in `vite dev` (never in a build, for SSR transforms
128
- or under a test runner). The compiled module registers its top-level components with
129
- `@shadow-js/web/hmr`, so an edit re-renders the instances of the edited component while parents and
127
+ The plugin turns on the compiler's `hmr` option in `vite dev` (not in a build unless `dev: true` forces development output,
128
+ never for SSR transforms, and not under a test runner unless `hmr: true` asks for it; `hmr: false` or `dev: false` turns it
129
+ off). The compiled module registers its top-level components with `@shadow-js/web/hmr`, so an edit re-renders the instances of the edited component while parents and
130
130
  siblings keep their state; a module that exports only components accepts its own update. This is
131
131
  covered by the unit tests of the compiler and of the plugin (`[HMR-01]` to `[HMR-06]`, `[VIT-04]`).
132
132
  The browser test tier also exercises hot updates in a real browser.
@@ -0,0 +1,40 @@
1
+ /** What `astring`, the JavaScript printer of `@mdx-js/mdx`, hands to `addMapping`. */
2
+ interface Mapping {
3
+ readonly generated: {
4
+ readonly line: number;
5
+ readonly column: number;
6
+ };
7
+ readonly original: {
8
+ readonly line: number;
9
+ readonly column: number;
10
+ } | null;
11
+ readonly source?: string;
12
+ readonly name?: string;
13
+ }
14
+ /**
15
+ * The `SourceMapGenerator` the MDX plugin hands to `@mdx-js/mdx`, which uses it to record where each piece
16
+ * of the JSX it prints came from. It has the part of the interface of the generator of the `source-map`
17
+ * package that the printer calls (`addMapping`, `toJSON`), so the plugin needs no such package: `@mdx-js/mdx`
18
+ * brings its own, which a package manager need not hoist to where this plugin can import it.
19
+ *
20
+ * @internal
21
+ */
22
+ export declare class MappingCollector {
23
+ #private;
24
+ /** @param options `file` is the name of the generated file. */
25
+ constructor(options?: {
26
+ readonly file?: string;
27
+ });
28
+ /** Records that the generated position came from the original one. A mapping without an original is skipped. */
29
+ addMapping(mapping: Mapping): void;
30
+ /** The map as a version 3 source map object. */
31
+ toJSON(): {
32
+ version: 3;
33
+ file?: string;
34
+ sources: string[];
35
+ names: string[];
36
+ mappings: string;
37
+ };
38
+ }
39
+ export {};
40
+ //# sourceMappingURL=source-maps.d.ts.map
@@ -0,0 +1,297 @@
1
+ // src/internal/source-maps.ts
2
+ const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3
+ const VLQ_BASE_SHIFT = 5;
4
+ const VLQ_BASE = 32;
5
+ const VLQ_MASK = 31;
6
+ const VLQ_CONTINUE = VLQ_BASE;
7
+ /** Appends one signed number, as a base 64 VLQ, to `out`. */
8
+ function writeVlq(out, value) {
9
+ let rest = value < 0 ? -value << 1 | 1 : value << 1;
10
+ do {
11
+ let digit = rest & VLQ_MASK;
12
+ rest >>>= VLQ_BASE_SHIFT;
13
+ if (rest > 0) digit |= VLQ_CONTINUE;
14
+ out.push(BASE64.charAt(digit));
15
+ } while (rest > 0);
16
+ }
17
+ /**
18
+ * Decodes the `mappings` of a source map.
19
+ *
20
+ * @param mappings The `mappings` string: lines separated by `;`, segments by `,`.
21
+ * @returns One list of segments per generated line.
22
+ * @throws SyntaxError when a character is not base 64 or a number is cut off.
23
+ * @internal
24
+ */
25
+ function decodeMappings(mappings) {
26
+ const lines = [];
27
+ let line = [];
28
+ let column = 0;
29
+ let source = 0;
30
+ let sourceLine = 0;
31
+ let sourceColumn = 0;
32
+ let name = 0;
33
+ let numbers = [];
34
+ let value = 0;
35
+ let shift = 0;
36
+ const finishSegment = () => {
37
+ if (numbers.length === 0) return;
38
+ const [dc = 0, ds, dl, dk, dn] = numbers;
39
+ column += dc;
40
+ if (numbers.length === 1) line.push([column]);
41
+ else if (numbers.length !== 4 && numbers.length !== 5 || ds === void 0 || dl === void 0 || dk === void 0) throw new SyntaxError(`source map: a segment has ${numbers.length} fields.`);
42
+ else {
43
+ source += ds;
44
+ sourceLine += dl;
45
+ sourceColumn += dk;
46
+ if (dn === void 0) line.push([
47
+ column,
48
+ source,
49
+ sourceLine,
50
+ sourceColumn
51
+ ]);
52
+ else {
53
+ name += dn;
54
+ line.push([
55
+ column,
56
+ source,
57
+ sourceLine,
58
+ sourceColumn,
59
+ name
60
+ ]);
61
+ }
62
+ }
63
+ numbers = [];
64
+ };
65
+ for (let i = 0; i < mappings.length; i += 1) {
66
+ const char = mappings.charAt(i);
67
+ if (char === ";" || char === ",") {
68
+ if (shift !== 0) throw new SyntaxError("source map: a number is cut off.");
69
+ finishSegment();
70
+ if (char === ";") {
71
+ lines.push(line);
72
+ line = [];
73
+ column = 0;
74
+ }
75
+ continue;
76
+ }
77
+ const digit = BASE64.indexOf(char);
78
+ if (digit === -1) throw new SyntaxError(`source map: "${char}" is not a base 64 digit.`);
79
+ value += (digit & VLQ_MASK) * 2 ** shift;
80
+ if ((digit & VLQ_CONTINUE) !== 0) shift += VLQ_BASE_SHIFT;
81
+ else {
82
+ numbers.push(value % 2 === 1 ? -Math.floor(value / 2) : value / 2);
83
+ value = 0;
84
+ shift = 0;
85
+ }
86
+ }
87
+ if (shift !== 0) throw new SyntaxError("source map: a number is cut off.");
88
+ finishSegment();
89
+ lines.push(line);
90
+ return lines;
91
+ }
92
+ /**
93
+ * Encodes decoded mappings.
94
+ *
95
+ * @param lines One list of segments per generated line, each list sorted by generated column.
96
+ * @returns The `mappings` string.
97
+ * @internal
98
+ */
99
+ function encodeMappings(lines) {
100
+ const out = [];
101
+ let source = 0;
102
+ let sourceLine = 0;
103
+ let sourceColumn = 0;
104
+ let name = 0;
105
+ lines.forEach((line, index) => {
106
+ if (index > 0) out.push(";");
107
+ let column = 0;
108
+ line.forEach((segment, position) => {
109
+ if (position > 0) out.push(",");
110
+ writeVlq(out, segment[0] - column);
111
+ column = segment[0];
112
+ if (segment.length === 1) return;
113
+ writeVlq(out, segment[1] - source);
114
+ writeVlq(out, segment[2] - sourceLine);
115
+ writeVlq(out, segment[3] - sourceColumn);
116
+ source = segment[1];
117
+ sourceLine = segment[2];
118
+ sourceColumn = segment[3];
119
+ if (segment.length === 5) {
120
+ writeVlq(out, segment[4] - name);
121
+ name = segment[4];
122
+ }
123
+ });
124
+ });
125
+ return out.join("");
126
+ }
127
+ /** The last segment of a line that starts at or before `column` and maps to a source position. */
128
+ function segmentAt(line, column) {
129
+ if (line === void 0) return void 0;
130
+ let low = 0;
131
+ let high = line.length - 1;
132
+ let found;
133
+ while (low <= high) {
134
+ const middle = low + high >> 1;
135
+ const segment = line[middle];
136
+ if (segment === void 0) break;
137
+ if (segment[0] <= column) {
138
+ if (segment.length > 1) found = segment;
139
+ low = middle + 1;
140
+ } else high = middle - 1;
141
+ }
142
+ return found;
143
+ }
144
+ /**
145
+ * Composes two maps into one that points at the first text. `outer` maps the final code to the middle
146
+ * text (the JSX), `inner` maps the middle text to the original (the `.mdx` file). A position of the final
147
+ * code that falls where `inner` maps nothing gets no mapping. A name recorded by `inner` wins, because it is
148
+ * the earlier spelling.
149
+ *
150
+ * @param outer Final code to middle text.
151
+ * @param inner Middle text to original text; the original is its only source.
152
+ * @param source The name of the original file.
153
+ * @param content The text of the original file.
154
+ * @param file The name of the final file, if known.
155
+ * @returns The map from the final code to the original file.
156
+ * @internal
157
+ */
158
+ function composeToSource(outer, inner, source, content, file) {
159
+ const inside = decodeMappings(inner.mappings);
160
+ const names = [...inner.names ?? []];
161
+ const known = new Map(names.map((name, index) => [name, index]));
162
+ const nameIndex = (name) => {
163
+ const existing = known.get(name);
164
+ if (existing !== void 0) return existing;
165
+ names.push(name);
166
+ known.set(name, names.length - 1);
167
+ return names.length - 1;
168
+ };
169
+ const lines = decodeMappings(outer.mappings).map((line) => {
170
+ const out = [];
171
+ for (const segment of line) {
172
+ if (segment.length === 1) continue;
173
+ const target = segmentAt(inside[segment[2]], segment[3]);
174
+ if (target === void 0) continue;
175
+ if (target.length === 5) {
176
+ out.push([
177
+ segment[0],
178
+ 0,
179
+ target[2],
180
+ target[3],
181
+ target[4]
182
+ ]);
183
+ continue;
184
+ }
185
+ const outerName = segment.length === 5 ? outer.names?.[segment[4]] : void 0;
186
+ out.push(outerName === void 0 ? [
187
+ segment[0],
188
+ 0,
189
+ target[2],
190
+ target[3]
191
+ ] : [
192
+ segment[0],
193
+ 0,
194
+ target[2],
195
+ target[3],
196
+ nameIndex(outerName)
197
+ ]);
198
+ }
199
+ return out;
200
+ });
201
+ const composed = {
202
+ version: 3,
203
+ sources: [source],
204
+ sourcesContent: [content],
205
+ names,
206
+ mappings: encodeMappings(lines)
207
+ };
208
+ if (file !== void 0) composed.file = file;
209
+ return composed;
210
+ }
211
+ /**
212
+ * The map of `@mdx-js/mdx` as a complete map of the original file: its one source named and embedded.
213
+ *
214
+ * @param map Middle text to original text; the original is its only source.
215
+ * @param source The name of the original file.
216
+ * @param content The text of the original file.
217
+ * @returns The map.
218
+ * @internal
219
+ */
220
+ function mapOfSource(map, source, content) {
221
+ return {
222
+ version: 3,
223
+ sources: [source],
224
+ sourcesContent: [content],
225
+ names: [...map.names ?? []],
226
+ mappings: map.mappings
227
+ };
228
+ }
229
+ /**
230
+ * The `SourceMapGenerator` the MDX plugin hands to `@mdx-js/mdx`, which uses it to record where each piece
231
+ * of the JSX it prints came from. It has the part of the interface of the generator of the `source-map`
232
+ * package that the printer calls (`addMapping`, `toJSON`), so the plugin needs no such package: `@mdx-js/mdx`
233
+ * brings its own, which a package manager need not hoist to where this plugin can import it.
234
+ *
235
+ * @internal
236
+ */
237
+ var MappingCollector = class {
238
+ #file;
239
+ #sources = [];
240
+ #names = [];
241
+ #entries = [];
242
+ /** @param options `file` is the name of the generated file. */
243
+ constructor(options) {
244
+ this.#file = options?.file;
245
+ }
246
+ /** Records that the generated position came from the original one. A mapping without an original is skipped. */
247
+ addMapping(mapping) {
248
+ if (mapping.original === null) return;
249
+ const origin = mapping.source ?? this.#file ?? "";
250
+ let source = this.#sources.indexOf(origin);
251
+ if (source === -1) source = this.#sources.push(origin) - 1;
252
+ let name;
253
+ if (mapping.name !== void 0) {
254
+ name = this.#names.indexOf(mapping.name);
255
+ if (name === -1) name = this.#names.push(mapping.name) - 1;
256
+ }
257
+ this.#entries.push({
258
+ line: mapping.generated.line - 1,
259
+ column: mapping.generated.column,
260
+ source,
261
+ sourceLine: mapping.original.line - 1,
262
+ sourceColumn: mapping.original.column,
263
+ name
264
+ });
265
+ }
266
+ /** The map as a version 3 source map object. */
267
+ toJSON() {
268
+ const lines = [];
269
+ const sorted = [...this.#entries].sort((a, b) => a.line - b.line || a.column - b.column);
270
+ for (const entry of sorted) {
271
+ while (lines.length <= entry.line) lines.push([]);
272
+ lines[entry.line]?.push(entry.name === void 0 ? [
273
+ entry.column,
274
+ entry.source,
275
+ entry.sourceLine,
276
+ entry.sourceColumn
277
+ ] : [
278
+ entry.column,
279
+ entry.source,
280
+ entry.sourceLine,
281
+ entry.sourceColumn,
282
+ entry.name
283
+ ]);
284
+ }
285
+ const map = {
286
+ version: 3,
287
+ sources: [...this.#sources],
288
+ names: [...this.#names],
289
+ mappings: encodeMappings(lines)
290
+ };
291
+ if (this.#file !== void 0) map.file = this.#file;
292
+ return map;
293
+ }
294
+ };
295
+ export { MappingCollector, composeToSource, decodeMappings, encodeMappings, mapOfSource };
296
+
297
+ //# sourceMappingURL=source-maps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"source-maps.js","names":[],"sources":["../../../src/internal/source-maps.ts"],"sourcesContent":["/**\n * Source map helpers of the MDX plugin. `@mdx-js/mdx` turns the `.mdx` text into JSX, and the ShadowJS\n * compiler turns that JSX into the final code, so the plugin holds two maps: final code to JSX, and JSX\n * to `.mdx`. Build tools need the one map from the final code to the `.mdx` file, which {@link composeToSource}\n * builds. The helpers read and write the map format (version 3, base 64 VLQ) themselves: the plugin has\n * no runtime dependency besides the compiler, and the work is a few lines.\n */\n\n/** One decoded segment: generated column, then (source index, line, column and optionally a name index). */\nexport type Segment =\n | readonly [number]\n | readonly [number, number, number, number]\n | readonly [number, number, number, number, number];\n\n/** The parts of a version 3 source map this module reads. */\nexport interface RawMap {\n readonly mappings: string;\n readonly names?: readonly string[];\n}\n\n/** A version 3 source map this module writes. */\nexport interface ComposedMap {\n version: 3;\n file?: string;\n sources: string[];\n sourcesContent: string[];\n names: string[];\n mappings: string;\n}\n\nconst BASE64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nconst VLQ_BASE_SHIFT = 5;\nconst VLQ_BASE = 1 << VLQ_BASE_SHIFT;\nconst VLQ_MASK = VLQ_BASE - 1;\nconst VLQ_CONTINUE = VLQ_BASE;\n\n/** Appends one signed number, as a base 64 VLQ, to `out`. */\nfunction writeVlq(out: string[], value: number): void {\n let rest = value < 0 ? (-value << 1) | 1 : value << 1;\n do {\n let digit = rest & VLQ_MASK;\n rest >>>= VLQ_BASE_SHIFT;\n if (rest > 0) digit |= VLQ_CONTINUE;\n out.push(BASE64.charAt(digit));\n } while (rest > 0);\n}\n\n/**\n * Decodes the `mappings` of a source map.\n *\n * @param mappings The `mappings` string: lines separated by `;`, segments by `,`.\n * @returns One list of segments per generated line.\n * @throws SyntaxError when a character is not base 64 or a number is cut off.\n * @internal\n */\nexport function decodeMappings(mappings: string): Segment[][] {\n const lines: Segment[][] = [];\n let line: Segment[] = [];\n let column = 0;\n let source = 0;\n let sourceLine = 0;\n let sourceColumn = 0;\n let name = 0;\n let numbers: number[] = [];\n let value = 0;\n let shift = 0;\n const finishSegment = (): void => {\n if (numbers.length === 0) return;\n const [dc = 0, ds, dl, dk, dn] = numbers;\n column += dc;\n if (numbers.length === 1) {\n line.push([column]);\n } else if (\n (numbers.length !== 4 && numbers.length !== 5) ||\n ds === undefined ||\n dl === undefined ||\n dk === undefined\n ) {\n throw new SyntaxError(`source map: a segment has ${numbers.length} fields.`);\n } else {\n source += ds;\n sourceLine += dl;\n sourceColumn += dk;\n if (dn === undefined) {\n line.push([column, source, sourceLine, sourceColumn]);\n } else {\n name += dn;\n line.push([column, source, sourceLine, sourceColumn, name]);\n }\n }\n numbers = [];\n };\n for (let i = 0; i < mappings.length; i += 1) {\n const char = mappings.charAt(i);\n if (char === \";\" || char === \",\") {\n if (shift !== 0) throw new SyntaxError(\"source map: a number is cut off.\");\n finishSegment();\n if (char === \";\") {\n lines.push(line);\n line = [];\n column = 0;\n }\n continue;\n }\n const digit = BASE64.indexOf(char);\n if (digit === -1) throw new SyntaxError(`source map: \"${char}\" is not a base 64 digit.`);\n value += (digit & VLQ_MASK) * 2 ** shift;\n if ((digit & VLQ_CONTINUE) !== 0) {\n shift += VLQ_BASE_SHIFT;\n } else {\n numbers.push(value % 2 === 1 ? -Math.floor(value / 2) : value / 2);\n value = 0;\n shift = 0;\n }\n }\n if (shift !== 0) throw new SyntaxError(\"source map: a number is cut off.\");\n finishSegment();\n lines.push(line);\n return lines;\n}\n\n/**\n * Encodes decoded mappings.\n *\n * @param lines One list of segments per generated line, each list sorted by generated column.\n * @returns The `mappings` string.\n * @internal\n */\nexport function encodeMappings(lines: readonly (readonly Segment[])[]): string {\n const out: string[] = [];\n let source = 0;\n let sourceLine = 0;\n let sourceColumn = 0;\n let name = 0;\n lines.forEach((line, index) => {\n if (index > 0) out.push(\";\");\n let column = 0;\n line.forEach((segment, position) => {\n if (position > 0) out.push(\",\");\n writeVlq(out, segment[0] - column);\n column = segment[0];\n if (segment.length === 1) return;\n writeVlq(out, segment[1] - source);\n writeVlq(out, segment[2] - sourceLine);\n writeVlq(out, segment[3] - sourceColumn);\n source = segment[1];\n sourceLine = segment[2];\n sourceColumn = segment[3];\n if (segment.length === 5) {\n writeVlq(out, segment[4] - name);\n name = segment[4];\n }\n });\n });\n return out.join(\"\");\n}\n\n/** The last segment of a line that starts at or before `column` and maps to a source position. */\nfunction segmentAt(\n line: readonly Segment[] | undefined,\n column: number,\n): Exclude<Segment, readonly [number]> | undefined {\n if (line === undefined) return undefined;\n let low = 0;\n let high = line.length - 1;\n let found: Exclude<Segment, readonly [number]> | undefined;\n while (low <= high) {\n const middle = (low + high) >> 1;\n const segment = line[middle];\n if (segment === undefined) break;\n if (segment[0] <= column) {\n if (segment.length > 1) found = segment as Exclude<Segment, readonly [number]>;\n low = middle + 1;\n } else {\n high = middle - 1;\n }\n }\n return found;\n}\n\n/**\n * Composes two maps into one that points at the first text. `outer` maps the final code to the middle\n * text (the JSX), `inner` maps the middle text to the original (the `.mdx` file). A position of the final\n * code that falls where `inner` maps nothing gets no mapping. A name recorded by `inner` wins, because it is\n * the earlier spelling.\n *\n * @param outer Final code to middle text.\n * @param inner Middle text to original text; the original is its only source.\n * @param source The name of the original file.\n * @param content The text of the original file.\n * @param file The name of the final file, if known.\n * @returns The map from the final code to the original file.\n * @internal\n */\nexport function composeToSource(\n outer: RawMap,\n inner: RawMap,\n source: string,\n content: string,\n file?: string,\n): ComposedMap {\n const inside = decodeMappings(inner.mappings);\n const names = [...(inner.names ?? [])];\n const known = new Map<string, number>(names.map((name, index) => [name, index]));\n const nameIndex = (name: string): number => {\n const existing = known.get(name);\n if (existing !== undefined) return existing;\n names.push(name);\n known.set(name, names.length - 1);\n return names.length - 1;\n };\n const lines = decodeMappings(outer.mappings).map((line) => {\n const out: Segment[] = [];\n for (const segment of line) {\n if (segment.length === 1) continue;\n const target = segmentAt(inside[segment[2]], segment[3]);\n if (target === undefined) continue;\n if (target.length === 5) {\n out.push([segment[0], 0, target[2], target[3], target[4]]);\n continue;\n }\n const outerName = segment.length === 5 ? outer.names?.[segment[4]] : undefined;\n out.push(\n outerName === undefined\n ? [segment[0], 0, target[2], target[3]]\n : [segment[0], 0, target[2], target[3], nameIndex(outerName)],\n );\n }\n return out;\n });\n const composed: ComposedMap = {\n version: 3,\n sources: [source],\n sourcesContent: [content],\n names,\n mappings: encodeMappings(lines),\n };\n if (file !== undefined) composed.file = file;\n return composed;\n}\n\n/**\n * The map of `@mdx-js/mdx` as a complete map of the original file: its one source named and embedded.\n *\n * @param map Middle text to original text; the original is its only source.\n * @param source The name of the original file.\n * @param content The text of the original file.\n * @returns The map.\n * @internal\n */\nexport function mapOfSource(map: RawMap, source: string, content: string): ComposedMap {\n return {\n version: 3,\n sources: [source],\n sourcesContent: [content],\n names: [...(map.names ?? [])],\n mappings: map.mappings,\n };\n}\n\n/** What `astring`, the JavaScript printer of `@mdx-js/mdx`, hands to `addMapping`. */\ninterface Mapping {\n readonly generated: { readonly line: number; readonly column: number };\n readonly original: { readonly line: number; readonly column: number } | null;\n readonly source?: string;\n readonly name?: string;\n}\n\n/**\n * The `SourceMapGenerator` the MDX plugin hands to `@mdx-js/mdx`, which uses it to record where each piece\n * of the JSX it prints came from. It has the part of the interface of the generator of the `source-map`\n * package that the printer calls (`addMapping`, `toJSON`), so the plugin needs no such package: `@mdx-js/mdx`\n * brings its own, which a package manager need not hoist to where this plugin can import it.\n *\n * @internal\n */\nexport class MappingCollector {\n readonly #file: string | undefined;\n readonly #sources: string[] = [];\n readonly #names: string[] = [];\n readonly #entries: Array<{\n line: number;\n column: number;\n source: number;\n sourceLine: number;\n sourceColumn: number;\n name: number | undefined;\n }> = [];\n\n /** @param options `file` is the name of the generated file. */\n constructor(options?: { readonly file?: string }) {\n this.#file = options?.file;\n }\n\n /** Records that the generated position came from the original one. A mapping without an original is skipped. */\n addMapping(mapping: Mapping): void {\n if (mapping.original === null) return;\n const origin = mapping.source ?? this.#file ?? \"\";\n let source = this.#sources.indexOf(origin);\n if (source === -1) source = this.#sources.push(origin) - 1;\n let name: number | undefined;\n if (mapping.name !== undefined) {\n name = this.#names.indexOf(mapping.name);\n if (name === -1) name = this.#names.push(mapping.name) - 1;\n }\n this.#entries.push({\n line: mapping.generated.line - 1,\n column: mapping.generated.column,\n source,\n sourceLine: mapping.original.line - 1,\n sourceColumn: mapping.original.column,\n name,\n });\n }\n\n /** The map as a version 3 source map object. */\n toJSON(): { version: 3; file?: string; sources: string[]; names: string[]; mappings: string } {\n const lines: Segment[][] = [];\n // The printer emits in order, but a stable sort keeps the map valid whatever the order.\n const sorted = [...this.#entries].sort((a, b) => a.line - b.line || a.column - b.column);\n for (const entry of sorted) {\n while (lines.length <= entry.line) lines.push([]);\n lines[entry.line]?.push(\n entry.name === undefined\n ? [entry.column, entry.source, entry.sourceLine, entry.sourceColumn]\n : [entry.column, entry.source, entry.sourceLine, entry.sourceColumn, entry.name],\n );\n }\n const map: {\n version: 3;\n file?: string;\n sources: string[];\n names: string[];\n mappings: string;\n } = {\n version: 3,\n sources: [...this.#sources],\n names: [...this.#names],\n mappings: encodeMappings(lines),\n };\n if (this.#file !== undefined) map.file = this.#file;\n return map;\n }\n}\n"],"mappings":";AA8BA,MAAM,SAAS;AACf,MAAM,iBAAiB;AACvB,MAAM,WAAW;AACjB,MAAM,WAAW;AACjB,MAAM,eAAe;;AAGrB,SAAS,SAAS,KAAe,OAAqB;CACpD,IAAI,OAAO,QAAQ,IAAK,CAAC,SAAS,IAAK,IAAI,SAAS;CACpD,GAAG;EACD,IAAI,QAAQ,OAAO;EACnB,UAAU;EACV,IAAI,OAAO,GAAG,SAAS;EACvB,IAAI,KAAK,OAAO,OAAO,KAAK,CAAC;CAC/B,SAAS,OAAO;AAClB;;;;;;;;;AAUA,SAAgB,eAAe,UAA+B;CAC5D,MAAM,QAAqB,CAAC;CAC5B,IAAI,OAAkB,CAAC;CACvB,IAAI,SAAS;CACb,IAAI,SAAS;CACb,IAAI,aAAa;CACjB,IAAI,eAAe;CACnB,IAAI,OAAO;CACX,IAAI,UAAoB,CAAC;CACzB,IAAI,QAAQ;CACZ,IAAI,QAAQ;CACZ,MAAM,sBAA4B;EAChC,IAAI,QAAQ,WAAW,GAAG;EAC1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1B,OAAO,CAAC,GAAG,KAAK,MAAM;GACtB,UAAU,eAAe,KAAK;EAChC;EACA,IAAI,KAAK,UAAU,KAAA,GAAW,IAAI,OAAO,KAAK;EAC9C,OAAO;CACT;AACF"}
package/dist/dev/mdx.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { MappingCollector } from "./internal/source-maps.js";
1
2
  import { CompilerPlugin } from "@shadow-js/compiler";
2
3
  import { Plugin } from "vite";
3
4
  /**
@@ -10,6 +11,8 @@ import { Plugin } from "vite";
10
11
  /** The file `@mdx-js/mdx` answers: a `VFile`, whose `value` holds the code. */
11
12
  interface MdxOutput {
12
13
  readonly value: string | Uint8Array;
14
+ /** The source map of `value` to the MDX file, when the options carried a `SourceMapGenerator` that records one. */
15
+ readonly map?: unknown;
13
16
  }
14
17
  /** What `compile` of `@mdx-js/mdx` accepts (the options this plugin sets, and the lists it hands on). */
15
18
  interface MdxCompileOptions {
@@ -22,6 +25,8 @@ interface MdxCompileOptions {
22
25
  readonly recmaPlugins?: readonly unknown[];
23
26
  readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;
24
27
  readonly providerImportSource?: string;
28
+ /** Asks for a source map from the JSX to the MDX file (`file.map` of the answer). */
29
+ readonly SourceMapGenerator: typeof MappingCollector;
25
30
  }
26
31
  /** `compile` of `@mdx-js/mdx`, or a function with its shape. @since 1.0.0 */
27
32
  export type MdxCompile = (file: {
package/dist/dev/mdx.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { moduleFile } from "./internal/ids.js";
2
+ import { MappingCollector, composeToSource, mapOfSource } from "./internal/source-maps.js";
2
3
  import { CompileError, compile, validatePlugins } from "@shadow-js/compiler";
3
4
  // src/mdx.ts
4
5
  function isNode(value) {
@@ -163,6 +164,7 @@ function shadowMdx(options = {}) {
163
164
  compileMdx ??= typeof options.mdx === "function" ? Promise.resolve(options.mdx) : loadMdx(options.mdx ?? "@mdx-js/mdx");
164
165
  const mdx = await compileMdx;
165
166
  let jsx;
167
+ let mdxMap;
166
168
  try {
167
169
  const output = await mdx({
168
170
  value: code,
@@ -176,9 +178,11 @@ function shadowMdx(options = {}) {
176
178
  ...options.rehypePlugins === void 0 ? {} : { rehypePlugins: options.rehypePlugins },
177
179
  recmaPlugins: [...options.recmaPlugins ?? [], elementsPlugin(options.elements ?? "overridable", dynamicSourceOf(options.moduleName))],
178
180
  ...options.remarkRehypeOptions === void 0 ? {} : { remarkRehypeOptions: options.remarkRehypeOptions },
179
- ...options.providerImportSource === void 0 ? {} : { providerImportSource: options.providerImportSource }
181
+ ...options.providerImportSource === void 0 ? {} : { providerImportSource: options.providerImportSource },
182
+ SourceMapGenerator: MappingCollector
180
183
  });
181
184
  jsx = typeof output.value === "string" ? output.value : Buffer.from(output.value).toString("utf8");
185
+ mdxMap = rawMapOf(output.map);
182
186
  } catch (error) {
183
187
  const found = error;
184
188
  const position = typeof found.line === "number" && found.line > 0 ? {
@@ -197,24 +201,32 @@ function shadowMdx(options = {}) {
197
201
  ...options.moduleName === void 0 ? {} : { moduleName: options.moduleName },
198
202
  ...plugins.length > 0 ? { plugins } : {}
199
203
  });
200
- for (const diagnostic of result.diagnostics) if (diagnostic.severity === "warning") this.warn(diagnostic.message, {
201
- line: diagnostic.line,
202
- column: diagnostic.column
203
- });
204
+ for (const diagnostic of result.diagnostics) if (diagnostic.severity === "warning") this.warn(diagnostic.message);
205
+ if (!result.transformed) return {
206
+ code: jsx,
207
+ map: mdxMap === void 0 ? null : mapOfSource(mdxMap, file, code)
208
+ };
204
209
  return {
205
- code: result.transformed ? result.code : jsx,
206
- map: result.transformed ? result.map : null
210
+ code: result.code,
211
+ map: result.map === null || mdxMap === void 0 ? result.map : composeToSource(result.map, mdxMap, file, code)
207
212
  };
208
213
  } catch (error) {
209
- if (error instanceof CompileError) return this.error(error.message, error.diagnostic.line === 0 ? void 0 : {
210
- line: error.diagnostic.line,
211
- column: error.diagnostic.column
212
- });
214
+ if (error instanceof CompileError) return this.error(error.message);
213
215
  throw error;
214
216
  }
215
217
  }
216
218
  };
217
219
  }
220
+ /** Reads the map `@mdx-js/mdx` answers with, or `undefined` when it gave none that can be used. */
221
+ function rawMapOf(value) {
222
+ if (typeof value !== "object" || value === null) return void 0;
223
+ const { mappings, names } = value;
224
+ if (typeof mappings !== "string") return void 0;
225
+ return {
226
+ mappings,
227
+ names: Array.isArray(names) ? names.filter((name) => typeof name === "string") : []
228
+ };
229
+ }
218
230
  /** The same pattern without the `g` and `y` flags, so `test()` does not remember where the last call ended. */
219
231
  function statelessPattern(pattern) {
220
232
  return pattern.global || pattern.sticky ? new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, "")) : pattern;
@@ -1 +1 @@
1
- {"version":3,"file":"mdx.js","names":[],"sources":["../../src/mdx.ts"],"sourcesContent":["import { CompileError, type CompilerPlugin, compile, validatePlugins } from \"@shadow-js/compiler\";\nimport type { Plugin } from \"vite\";\nimport { moduleFile } from \"./internal/ids\";\n\n/**\n * `shadowMdx()`: a Vite plugin that turns `.mdx` (and `.md`) files into ShadowJS components. MDX is compiled to JSX by\n * `@mdx-js/mdx`, an optional peer, and the JSX goes through the ShadowJS compiler in the same step, so an MDX file needs no\n * other plugin to be compiled. The default export of a module is the component; the `export`s of the file (a `frontmatter`\n * from `remark-mdx-frontmatter`, a `meta` object) are named exports.\n * @packageDocumentation\n */\n\n/** The file `@mdx-js/mdx` answers: a `VFile`, whose `value` holds the code. */\ninterface MdxOutput {\n readonly value: string | Uint8Array;\n}\n\n/** What `compile` of `@mdx-js/mdx` accepts (the options this plugin sets, and the lists it hands on). */\ninterface MdxCompileOptions {\n readonly jsx: true;\n readonly jsxImportSource: string;\n readonly development: false;\n readonly format: \"mdx\" | \"md\";\n readonly remarkPlugins?: readonly unknown[];\n readonly rehypePlugins?: readonly unknown[];\n readonly recmaPlugins?: readonly unknown[];\n readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;\n readonly providerImportSource?: string;\n}\n\n/** `compile` of `@mdx-js/mdx`, or a function with its shape. @since 1.0.0 */\nexport type MdxCompile = (\n file: { readonly value: string; readonly path: string },\n options: MdxCompileOptions,\n) => Promise<MdxOutput>;\n\n/** Options of {@link shadowMdx}. @since 1.0.0 */\nexport interface ShadowMdxOptions {\n /** Files to compile, matched against the module id without its query string. Default `/\\.mdx$/`. Add `.md` to read Markdown files too. */\n readonly include?: RegExp;\n /** Files to skip; checked first. Default: any path with a `node_modules` segment. */\n readonly exclude?: RegExp;\n /** Plugins of the Markdown syntax tree (`remark-frontmatter`, `remark-mdx-frontmatter`, `remark-gfm`, ...), as `@mdx-js/mdx` takes them. */\n readonly remarkPlugins?: readonly unknown[];\n /** Plugins of the HTML syntax tree (`rehype-slug`, `rehype-autolink-headings`, ...). */\n readonly rehypePlugins?: readonly unknown[];\n /** Plugins of the JavaScript syntax tree. They run before the plugin's own pass over the elements. */\n readonly recmaPlugins?: readonly unknown[];\n /**\n * How the elements of Markdown (`h1`, `p`, `a`, `code`, ...) are rendered.\n *\n * - `\"overridable\"`: each one is looked up in the `components` prop (and the provider), so an app can replace `a` or `h1`\n * for every page. Each looked-up element is rendered by `Dynamic`.\n * - `\"static\"`: each one is a plain element in the page's template, cloned in one call. The `components` prop still\n * supplies components the file names itself (`<Chart />`) and the `wrapper`, but cannot replace `h1` or `a`.\n *\n * Choose `\"static\"` for pages that never replace a Markdown element: documentation and blog posts render faster and ship\n * less code.\n * @default \"overridable\"\n */\n readonly elements?: \"overridable\" | \"static\";\n /** Options of `remark-rehype`. */\n readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;\n /**\n * A module that exports `useMDXComponents`, whose components every MDX file may use without a `components` prop (the\n * way `@mdx-js/react` works for React). Default: none; pass `components` to the file's component instead.\n */\n readonly providerImportSource?: string;\n /** `@mdx-js/mdx`, by module name, or your own `compile`. Default `\"@mdx-js/mdx\"`. */\n readonly mdx?: string | MdxCompile;\n /** Compiler plugins that run on the JSX of every MDX file (see `ShadowPluginOptions.plugins`). */\n readonly plugins?: readonly CompilerPlugin[];\n /**\n * Module the compiled code imports its runtime helpers from. Default `\"@shadow-js/web\"` (`\"@shadow-js/web/server\"` for SSR).\n * With `elements: \"overridable\"` the file also imports `Dynamic` from it, so a custom module must export `Dynamic`;\n * `\"@shadow-js/web/server\"` has none, so `Dynamic` is then imported from `\"@shadow-js/web\"`.\n */\n readonly moduleName?: string;\n}\n\n/** A node of the JavaScript syntax tree `@mdx-js/mdx` hands to recma plugins (ESTree with JSX), read structurally. */\ninterface EsNode {\n type: string;\n [key: string]: unknown;\n}\n\nfunction isNode(value: unknown): value is EsNode {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { type?: unknown }).type === \"string\"\n );\n}\n\n/**\n * The module `Dynamic` is imported from: the one `moduleName` names, so a project that points the runtime at\n * its own module (an alias, a re-export) does not need `@shadow-js/web` resolvable as well. The one exception\n * is the SSR helpers entry `@shadow-js/web/server`: it holds the server helpers and no `Dynamic`, which the\n * main entry provides (and Vite resolves to its server build in an SSR build).\n */\nfunction dynamicSourceOf(moduleName: string | undefined): string {\n if (moduleName === undefined || moduleName === \"@shadow-js/web/server\") return \"@shadow-js/web\";\n return moduleName;\n}\n\n/** The identifier `@mdx-js/mdx` binds the element lookup table to. */\nconst LOOKUP = \"_components\";\n/** The local name of `Dynamic`: it cannot clash with a name the file exports or imports. */\nconst DYNAMIC = \"_ShadowDynamic\";\n\n/**\n * Rewrites the elements `@mdx-js/mdx` looks up in its table (`<_components.h1>`): into plain `<h1>` for `\"static\"`, into\n * `<Dynamic component={_components.h1}>` for `\"overridable\"`. The lookup yields a string for a default element and a\n * function for an override, and a ShadowJS component tag must be a function.\n */\nfunction elementsPlugin(\n mode: \"overridable\" | \"static\",\n dynamicSource: string,\n): () => (tree: EsNode) => void {\n return () => (tree) => {\n let rewritten = 0;\n const pending: unknown[] = [tree];\n while (pending.length > 0) {\n const node = pending.pop();\n if (Array.isArray(node)) {\n for (const child of node) pending.push(child);\n continue;\n }\n if (!isNode(node)) continue;\n if (node.type === \"JSXElement\") {\n const opening = node[\"openingElement\"];\n const closing = node[\"closingElement\"];\n if (isNode(opening) && lookupName(opening[\"name\"]) !== undefined) {\n const tag = lookupName(opening[\"name\"]) as string;\n if (mode === \"static\") {\n opening[\"name\"] = identifier(tag);\n } else {\n opening[\"name\"] = identifier(DYNAMIC);\n const attributes = opening[\"attributes\"] as unknown[];\n attributes.unshift({\n type: \"JSXAttribute\",\n name: identifier(\"component\"),\n value: {\n type: \"JSXExpressionContainer\",\n expression: {\n type: \"MemberExpression\",\n object: { type: \"Identifier\", name: LOOKUP },\n property: { type: \"Identifier\", name: tag },\n computed: false,\n optional: false,\n },\n },\n });\n rewritten += 1;\n }\n if (isNode(closing)) closing[\"name\"] = identifier(mode === \"static\" ? tag : DYNAMIC);\n }\n }\n for (const value of Object.values(node)) {\n if (typeof value === \"object\" && value !== null) pending.push(value);\n }\n }\n if (rewritten > 0) {\n const body = tree[\"body\"] as unknown[];\n body.unshift({\n type: \"ImportDeclaration\",\n specifiers: [\n {\n type: \"ImportSpecifier\",\n imported: { type: \"Identifier\", name: \"Dynamic\" },\n local: { type: \"Identifier\", name: DYNAMIC },\n },\n ],\n source: { type: \"Literal\", value: dynamicSource, raw: JSON.stringify(dynamicSource) },\n attributes: [],\n });\n }\n };\n}\n\n/** The element name of `_components.name` as a JSX tag name, otherwise `undefined`. */\nfunction lookupName(name: unknown): string | undefined {\n if (!isNode(name) || name.type !== \"JSXMemberExpression\") return undefined;\n const object = name[\"object\"];\n const property = name[\"property\"];\n if (!isNode(object) || object.type !== \"JSXIdentifier\" || object[\"name\"] !== LOOKUP)\n return undefined;\n return isNode(property) && typeof property[\"name\"] === \"string\" ? property[\"name\"] : undefined;\n}\n\nfunction identifier(name: string): EsNode {\n return { type: \"JSXIdentifier\", name };\n}\n\nconst DEFAULT_INCLUDE = /\\.mdx$/;\nconst DEFAULT_EXCLUDE = /[\\\\/]node_modules[\\\\/]/;\n\n/** `@mdx-js/mdx` warns with a position; so do the errors of its parsers. */\ninterface Positioned {\n readonly message?: string;\n readonly line?: number | null;\n readonly column?: number | null;\n readonly reason?: string;\n}\n\nasync function loadMdx(specifier: string): Promise<MdxCompile> {\n let loaded: { compile?: unknown };\n try {\n loaded = (await import(specifier)) as { compile?: unknown };\n } catch (cause) {\n throw new Error(\n `shadowMdx: cannot load \"${specifier}\". Install it with \"npm install --save-dev ${specifier}\", or pass your own function as mdx.`,\n { cause },\n );\n }\n if (typeof loaded.compile !== \"function\") {\n throw new TypeError(`shadowMdx: the module \"${specifier}\" has no compile function.`);\n }\n const compileMdx = loaded.compile;\n return (file, options) =>\n Reflect.apply(compileMdx, undefined, [file, options]) as Promise<MdxOutput>;\n}\n\n/**\n * Creates the plugin that compiles MDX to ShadowJS components. It runs before Vite's own handling (`enforce: \"pre\"`), so Vite\n * never sees MDX or JSX. A file is compiled for the browser, or for the server in an SSR build; a syntax error in the MDX is\n * reported with its file, line and column. Hot updates reload the page: an MDX file has no component state worth keeping.\n *\n * @param options Which files, the remark, rehype and recma plugins, and the MDX compiler.\n * @returns A Vite plugin named `shadowjs-mdx`.\n * @throws TypeError when `include` or `exclude` is not a `RegExp`, or `plugins` is not a list of valid compiler plugins.\n * @example\n * // vite.config.ts\n * import { shadow } from \"@shadow-js/vite\";\n * import { shadowMdx } from \"@shadow-js/vite/mdx\";\n * import remarkFrontmatter from \"remark-frontmatter\";\n * import remarkMdxFrontmatter from \"remark-mdx-frontmatter\";\n *\n * export default {\n * plugins: [\n * shadowMdx({ remarkPlugins: [remarkFrontmatter, remarkMdxFrontmatter] }),\n * shadow(),\n * ],\n * };\n * @since 1.0.0\n */\nexport function shadowMdx(options: ShadowMdxOptions = {}): Plugin {\n for (const name of [\"include\", \"exclude\"] as const) {\n const value = options[name];\n if (value !== undefined && !(value instanceof RegExp)) {\n throw new TypeError(`shadowMdx(): \"${name}\" must be a RegExp (got ${typeof value}).`);\n }\n }\n const plugins =\n options.plugins === undefined ? [] : validatePlugins(options.plugins, \"shadowMdx(): plugins\");\n const include = statelessPattern(options.include ?? DEFAULT_INCLUDE);\n const exclude = statelessPattern(options.exclude ?? DEFAULT_EXCLUDE);\n let compileMdx: Promise<MdxCompile> | undefined;\n let dev = false;\n return {\n name: \"shadowjs-mdx\",\n enforce: \"pre\",\n config(_config, env) {\n dev = env.command === \"serve\";\n },\n async transform(code, id, transformOptions) {\n const { file, skip } = moduleFile(id);\n if (skip || exclude.test(file) || !include.test(file)) return null;\n compileMdx ??=\n typeof options.mdx === \"function\"\n ? Promise.resolve(options.mdx)\n : loadMdx(options.mdx ?? \"@mdx-js/mdx\");\n const mdx = await compileMdx;\n let jsx: string;\n try {\n const output = await mdx(\n { value: code, path: file },\n {\n jsx: true,\n jsxImportSource: options.moduleName ?? \"@shadow-js/web\",\n development: false,\n format: file.endsWith(\".mdx\") ? \"mdx\" : \"md\",\n ...(options.remarkPlugins === undefined\n ? {}\n : { remarkPlugins: options.remarkPlugins }),\n ...(options.rehypePlugins === undefined\n ? {}\n : { rehypePlugins: options.rehypePlugins }),\n recmaPlugins: [\n ...(options.recmaPlugins ?? []),\n elementsPlugin(\n options.elements ?? \"overridable\",\n dynamicSourceOf(options.moduleName),\n ),\n ],\n ...(options.remarkRehypeOptions === undefined\n ? {}\n : { remarkRehypeOptions: options.remarkRehypeOptions }),\n ...(options.providerImportSource === undefined\n ? {}\n : { providerImportSource: options.providerImportSource }),\n },\n );\n jsx =\n typeof output.value === \"string\"\n ? output.value\n : Buffer.from(output.value).toString(\"utf8\");\n } catch (error) {\n const found = error as Positioned;\n const position =\n typeof found.line === \"number\" && found.line > 0\n ? { line: found.line, column: Math.max((found.column ?? 1) - 1, 0) }\n : undefined;\n return this.error(found.reason ?? found.message ?? String(error), position);\n }\n try {\n const result = compile(jsx, {\n filename: `${file}.tsx`,\n generate: transformOptions?.ssr === true ? \"ssr\" : \"dom\",\n dev,\n autoReactive: true,\n hmr: false,\n ...(options.moduleName === undefined ? {} : { moduleName: options.moduleName }),\n ...(plugins.length > 0 ? { plugins } : {}),\n });\n for (const diagnostic of result.diagnostics) {\n if (diagnostic.severity === \"warning\") {\n this.warn(diagnostic.message, { line: diagnostic.line, column: diagnostic.column });\n }\n }\n return {\n code: result.transformed ? result.code : jsx,\n map: result.transformed ? result.map : null,\n };\n } catch (error) {\n if (error instanceof CompileError) {\n return this.error(\n error.message,\n error.diagnostic.line === 0\n ? undefined\n : { line: error.diagnostic.line, column: error.diagnostic.column },\n );\n }\n throw error;\n }\n },\n };\n}\n\n/** The same pattern without the `g` and `y` flags, so `test()` does not remember where the last call ended. */\nfunction statelessPattern(pattern: RegExp): RegExp {\n return pattern.global || pattern.sticky\n ? new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, \"\"))\n : pattern;\n}\n"],"mappings":";;;AAsFA,SAAS,OAAO,OAAiC;CAC/C,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA6B,SAAS;AAElD;;;;;;;AAQA,SAAS,gBAAgB,YAAwC;CAC/D,IAAI,eAAe,KAAA,KAAa,eAAe,yBAAyB,OAAO;CAC/E,OAAO;AACT;;AAGA,MAAM,SAAS;;AAEf,MAAM,UAAU;;;;;;AAOhB,SAAS,eACP,MACA,eAC8B;CAC9B,cAAc,SAAS;EACrB,IAAI,YAAY;EAChB,MAAM,UAAqB,CAAC,IAAI;EAChC,OAAO,QAAQ,SAAS,GAAG;GACzB,MAAM,OAAO,QAAQ,IAAI;GACzB,IAAI,MAAM,QAAQ,IAAI,GAAG;IACvB,KAAK,MAAM,SAAS,MAAM,QAAQ,KAAK,KAAK;IAC5C;GACF;GACA,IAAI,CAAC,OAAO,IAAI,GAAG;GACnB,IAAI,KAAK,SAAS,cAAc;IAC9B,MAAM,UAAU,KAAK;IACrB,MAAM,UAAU,KAAK;IACrB,IAAI,OAAO,OAAO,KAAK,WAAW,QAAQ,OAAO,MAAM,KAAA,GAAW;KAChE,MAAM,MAAM,WAAW,QAAQ,OAAO;KACtC,IAAI,SAAS,UACX,QAAQ,UAAU,WAAW,GAAG;UAC3B;MACL,QA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W,aAAa,WAC1B,KAAK,KAAK,WAAW,SAAS;KAAE,MAAM,WAAW;KAAM,QAAQ,WAAW;IAAO,CAAC;IAGtF,OAAO;KACL,MAAM,OAAO,cAAc,OAAO,OAAO;KACzC,KAAK,OAAO,cAAc,OAAO,MAAM;IACzC;GACF,SAAS,OAAO;IACd,IAAI,iBAAiB,cACnB,OAAO,KAAK,MACV,MAAM,SACN,MAAM,WAAW,SAAS,IACtB,KAAA,IACA;KAAE,MAAM,MAAM,WAAW;KAAM,QAAQ,MAAM,WAAW;IAAO,CACrE;IAEF,MAAM;GACR;EACF;CACF;AACF;;AAGA,SAAS,iBAAiB,SAAyB;CACjD,OAAO,QAAQ,UAAU,QAAQ,SAC7B,IAAI,OAAO,QAAQ,QAAQ,QAAQ,MAAM,QAAQ,SAAS,EAAE,CAAC,IAC7D;AACN"}
1
+ {"version":3,"file":"mdx.js","names":[],"sources":["../../src/mdx.ts"],"sourcesContent":["import { CompileError, type CompilerPlugin, compile, validatePlugins } from \"@shadow-js/compiler\";\nimport type { Plugin } from \"vite\";\nimport { moduleFile } from \"./internal/ids\";\nimport {\n composeToSource,\n MappingCollector,\n mapOfSource,\n type RawMap,\n} from \"./internal/source-maps\";\n\n/**\n * `shadowMdx()`: a Vite plugin that turns `.mdx` (and `.md`) files into ShadowJS components. MDX is compiled to JSX by\n * `@mdx-js/mdx`, an optional peer, and the JSX goes through the ShadowJS compiler in the same step, so an MDX file needs no\n * other plugin to be compiled. The default export of a module is the component; the `export`s of the file (a `frontmatter`\n * from `remark-mdx-frontmatter`, a `meta` object) are named exports.\n * @packageDocumentation\n */\n\n/** The file `@mdx-js/mdx` answers: a `VFile`, whose `value` holds the code. */\ninterface MdxOutput {\n readonly value: string | Uint8Array;\n /** The source map of `value` to the MDX file, when the options carried a `SourceMapGenerator` that records one. */\n readonly map?: unknown;\n}\n\n/** What `compile` of `@mdx-js/mdx` accepts (the options this plugin sets, and the lists it hands on). */\ninterface MdxCompileOptions {\n readonly jsx: true;\n readonly jsxImportSource: string;\n readonly development: false;\n readonly format: \"mdx\" | \"md\";\n readonly remarkPlugins?: readonly unknown[];\n readonly rehypePlugins?: readonly unknown[];\n readonly recmaPlugins?: readonly unknown[];\n readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;\n readonly providerImportSource?: string;\n /** Asks for a source map from the JSX to the MDX file (`file.map` of the answer). */\n readonly SourceMapGenerator: typeof MappingCollector;\n}\n\n/** `compile` of `@mdx-js/mdx`, or a function with its shape. @since 1.0.0 */\nexport type MdxCompile = (\n file: { readonly value: string; readonly path: string },\n options: MdxCompileOptions,\n) => Promise<MdxOutput>;\n\n/** Options of {@link shadowMdx}. @since 1.0.0 */\nexport interface ShadowMdxOptions {\n /** Files to compile, matched against the module id without its query string. Default `/\\.mdx$/`. Add `.md` to read Markdown files too. */\n readonly include?: RegExp;\n /** Files to skip; checked first. Default: any path with a `node_modules` segment. */\n readonly exclude?: RegExp;\n /** Plugins of the Markdown syntax tree (`remark-frontmatter`, `remark-mdx-frontmatter`, `remark-gfm`, ...), as `@mdx-js/mdx` takes them. */\n readonly remarkPlugins?: readonly unknown[];\n /** Plugins of the HTML syntax tree (`rehype-slug`, `rehype-autolink-headings`, ...). */\n readonly rehypePlugins?: readonly unknown[];\n /** Plugins of the JavaScript syntax tree. They run before the plugin's own pass over the elements. */\n readonly recmaPlugins?: readonly unknown[];\n /**\n * How the elements of Markdown (`h1`, `p`, `a`, `code`, ...) are rendered.\n *\n * - `\"overridable\"`: each one is looked up in the `components` prop (and the provider), so an app can replace `a` or `h1`\n * for every page. Each looked-up element is rendered by `Dynamic`.\n * - `\"static\"`: each one is a plain element in the page's template, cloned in one call. The `components` prop still\n * supplies components the file names itself (`<Chart />`) and the `wrapper`, but cannot replace `h1` or `a`.\n *\n * Choose `\"static\"` for pages that never replace a Markdown element: documentation and blog posts render faster and ship\n * less code.\n * @default \"overridable\"\n */\n readonly elements?: \"overridable\" | \"static\";\n /** Options of `remark-rehype`. */\n readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;\n /**\n * A module that exports `useMDXComponents`, whose components every MDX file may use without a `components` prop (the\n * way `@mdx-js/react` works for React). Default: none; pass `components` to the file's component instead.\n */\n readonly providerImportSource?: string;\n /** `@mdx-js/mdx`, by module name, or your own `compile`. Default `\"@mdx-js/mdx\"`. */\n readonly mdx?: string | MdxCompile;\n /** Compiler plugins that run on the JSX of every MDX file (see `ShadowPluginOptions.plugins`). */\n readonly plugins?: readonly CompilerPlugin[];\n /**\n * Module the compiled code imports its runtime helpers from. Default `\"@shadow-js/web\"` (`\"@shadow-js/web/server\"` for SSR).\n * With `elements: \"overridable\"` the file also imports `Dynamic` from it, so a custom module must export `Dynamic`;\n * `\"@shadow-js/web/server\"` has none, so `Dynamic` is then imported from `\"@shadow-js/web\"`.\n */\n readonly moduleName?: string;\n}\n\n/** A node of the JavaScript syntax tree `@mdx-js/mdx` hands to recma plugins (ESTree with JSX), read structurally. */\ninterface EsNode {\n type: string;\n [key: string]: unknown;\n}\n\nfunction isNode(value: unknown): value is EsNode {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { type?: unknown }).type === \"string\"\n );\n}\n\n/**\n * The module `Dynamic` is imported from: the one `moduleName` names, so a project that points the runtime at\n * its own module (an alias, a re-export) does not need `@shadow-js/web` resolvable as well. The one exception\n * is the SSR helpers entry `@shadow-js/web/server`: it holds the server helpers and no `Dynamic`, which the\n * main entry provides (and Vite resolves to its server build in an SSR build).\n */\nfunction dynamicSourceOf(moduleName: string | undefined): string {\n if (moduleName === undefined || moduleName === \"@shadow-js/web/server\") return \"@shadow-js/web\";\n return moduleName;\n}\n\n/** The identifier `@mdx-js/mdx` binds the element lookup table to. */\nconst LOOKUP = \"_components\";\n/** The local name of `Dynamic`: it cannot clash with a name the file exports or imports. */\nconst DYNAMIC = \"_ShadowDynamic\";\n\n/**\n * Rewrites the elements `@mdx-js/mdx` looks up in its table (`<_components.h1>`): into plain `<h1>` for `\"static\"`, into\n * `<Dynamic component={_components.h1}>` for `\"overridable\"`. The lookup yields a string for a default element and a\n * function for an override, and a ShadowJS component tag must be a function.\n */\nfunction elementsPlugin(\n mode: \"overridable\" | \"static\",\n dynamicSource: string,\n): () => (tree: EsNode) => void {\n return () => (tree) => {\n let rewritten = 0;\n const pending: unknown[] = [tree];\n while (pending.length > 0) {\n const node = pending.pop();\n if (Array.isArray(node)) {\n for (const child of node) pending.push(child);\n continue;\n }\n if (!isNode(node)) continue;\n if (node.type === \"JSXElement\") {\n const opening = node[\"openingElement\"];\n const closing = node[\"closingElement\"];\n if (isNode(opening) && lookupName(opening[\"name\"]) !== undefined) {\n const tag = lookupName(opening[\"name\"]) as string;\n if (mode === \"static\") {\n opening[\"name\"] = identifier(tag);\n } else {\n opening[\"name\"] = identifier(DYNAMIC);\n const attributes = opening[\"attributes\"] as unknown[];\n attributes.unshift({\n type: \"JSXAttribute\",\n name: identifier(\"component\"),\n value: {\n type: \"JSXExpressionContainer\",\n expression: {\n type: \"MemberExpression\",\n object: { type: \"Identifier\", name: LOOKUP },\n property: { type: \"Identifier\", name: tag },\n computed: false,\n optional: false,\n },\n },\n });\n rewritten += 1;\n }\n if (isNode(closing)) closing[\"name\"] = identifier(mode === \"static\" ? tag : DYNAMIC);\n }\n }\n for (const value of Object.values(node)) {\n if (typeof value === \"object\" && value !== null) pending.push(value);\n }\n }\n if (rewritten > 0) {\n const body = tree[\"body\"] as unknown[];\n body.unshift({\n type: \"ImportDeclaration\",\n specifiers: [\n {\n type: \"ImportSpecifier\",\n imported: { type: \"Identifier\", name: \"Dynamic\" },\n local: { type: \"Identifier\", name: DYNAMIC },\n },\n ],\n source: { type: \"Literal\", value: dynamicSource, raw: JSON.stringify(dynamicSource) },\n attributes: [],\n });\n }\n };\n}\n\n/** The element name of `_components.name` as a JSX tag name, otherwise `undefined`. */\nfunction lookupName(name: unknown): string | undefined {\n if (!isNode(name) || name.type !== \"JSXMemberExpression\") return undefined;\n const object = name[\"object\"];\n const property = name[\"property\"];\n if (!isNode(object) || object.type !== \"JSXIdentifier\" || object[\"name\"] !== LOOKUP)\n return undefined;\n return isNode(property) && typeof property[\"name\"] === \"string\" ? property[\"name\"] : undefined;\n}\n\nfunction identifier(name: string): EsNode {\n return { type: \"JSXIdentifier\", name };\n}\n\nconst DEFAULT_INCLUDE = /\\.mdx$/;\nconst DEFAULT_EXCLUDE = /[\\\\/]node_modules[\\\\/]/;\n\n/** `@mdx-js/mdx` warns with a position; so do the errors of its parsers. */\ninterface Positioned {\n readonly message?: string;\n readonly line?: number | null;\n readonly column?: number | null;\n readonly reason?: string;\n}\n\nasync function loadMdx(specifier: string): Promise<MdxCompile> {\n let loaded: { compile?: unknown };\n try {\n loaded = (await import(specifier)) as { compile?: unknown };\n } catch (cause) {\n throw new Error(\n `shadowMdx: cannot load \"${specifier}\". Install it with \"npm install --save-dev ${specifier}\", or pass your own function as mdx.`,\n { cause },\n );\n }\n if (typeof loaded.compile !== \"function\") {\n throw new TypeError(`shadowMdx: the module \"${specifier}\" has no compile function.`);\n }\n const compileMdx = loaded.compile;\n return (file, options) =>\n Reflect.apply(compileMdx, undefined, [file, options]) as Promise<MdxOutput>;\n}\n\n/**\n * Creates the plugin that compiles MDX to ShadowJS components. It runs before Vite's own handling (`enforce: \"pre\"`), so Vite\n * never sees MDX or JSX. A file is compiled for the browser, or for the server in an SSR build; a syntax error in the MDX is\n * reported with its file, line and column. Hot updates reload the page: an MDX file has no component state worth keeping.\n *\n * @param options Which files, the remark, rehype and recma plugins, and the MDX compiler.\n * @returns A Vite plugin named `shadowjs-mdx`.\n * @throws TypeError when `include` or `exclude` is not a `RegExp`, or `plugins` is not a list of valid compiler plugins.\n * @example\n * // vite.config.ts\n * import { shadow } from \"@shadow-js/vite\";\n * import { shadowMdx } from \"@shadow-js/vite/mdx\";\n * import remarkFrontmatter from \"remark-frontmatter\";\n * import remarkMdxFrontmatter from \"remark-mdx-frontmatter\";\n *\n * export default {\n * plugins: [\n * shadowMdx({ remarkPlugins: [remarkFrontmatter, remarkMdxFrontmatter] }),\n * shadow(),\n * ],\n * };\n * @since 1.0.0\n */\nexport function shadowMdx(options: ShadowMdxOptions = {}): Plugin {\n for (const name of [\"include\", \"exclude\"] as const) {\n const value = options[name];\n if (value !== undefined && !(value instanceof RegExp)) {\n throw new TypeError(`shadowMdx(): \"${name}\" must be a RegExp (got ${typeof value}).`);\n }\n }\n const plugins =\n options.plugins === undefined ? [] : validatePlugins(options.plugins, \"shadowMdx(): plugins\");\n const include = statelessPattern(options.include ?? DEFAULT_INCLUDE);\n const exclude = statelessPattern(options.exclude ?? DEFAULT_EXCLUDE);\n let compileMdx: Promise<MdxCompile> | undefined;\n let dev = false;\n return {\n name: \"shadowjs-mdx\",\n enforce: \"pre\",\n config(_config, env) {\n dev = env.command === \"serve\";\n },\n async transform(code, id, transformOptions) {\n const { file, skip } = moduleFile(id);\n if (skip || exclude.test(file) || !include.test(file)) return null;\n compileMdx ??=\n typeof options.mdx === \"function\"\n ? Promise.resolve(options.mdx)\n : loadMdx(options.mdx ?? \"@mdx-js/mdx\");\n const mdx = await compileMdx;\n let jsx: string;\n let mdxMap: RawMap | undefined;\n try {\n const output = await mdx(\n { value: code, path: file },\n {\n jsx: true,\n jsxImportSource: options.moduleName ?? \"@shadow-js/web\",\n development: false,\n format: file.endsWith(\".mdx\") ? \"mdx\" : \"md\",\n ...(options.remarkPlugins === undefined\n ? {}\n : { remarkPlugins: options.remarkPlugins }),\n ...(options.rehypePlugins === undefined\n ? {}\n : { rehypePlugins: options.rehypePlugins }),\n recmaPlugins: [\n ...(options.recmaPlugins ?? []),\n elementsPlugin(\n options.elements ?? \"overridable\",\n dynamicSourceOf(options.moduleName),\n ),\n ],\n ...(options.remarkRehypeOptions === undefined\n ? {}\n : { remarkRehypeOptions: options.remarkRehypeOptions }),\n ...(options.providerImportSource === undefined\n ? {}\n : { providerImportSource: options.providerImportSource }),\n SourceMapGenerator: MappingCollector,\n },\n );\n jsx =\n typeof output.value === \"string\"\n ? output.value\n : Buffer.from(output.value).toString(\"utf8\");\n mdxMap = rawMapOf(output.map);\n } catch (error) {\n const found = error as Positioned;\n const position =\n typeof found.line === \"number\" && found.line > 0\n ? { line: found.line, column: Math.max((found.column ?? 1) - 1, 0) }\n : undefined;\n return this.error(found.reason ?? found.message ?? String(error), position);\n }\n try {\n const result = compile(jsx, {\n filename: `${file}.tsx`,\n generate: transformOptions?.ssr === true ? \"ssr\" : \"dom\",\n dev,\n autoReactive: true,\n hmr: false,\n ...(options.moduleName === undefined ? {} : { moduleName: options.moduleName }),\n ...(plugins.length > 0 ? { plugins } : {}),\n });\n // The positions of the JSX pass are those of the JSX that `@mdx-js/mdx` wrote, not of the MDX file the build\n // names: passed on, they would point at lines and columns of the generated code (the message carries them).\n for (const diagnostic of result.diagnostics) {\n if (diagnostic.severity === \"warning\") this.warn(diagnostic.message);\n }\n // Without JSX to compile the code is what `@mdx-js/mdx` wrote, and its own map already points at the file.\n if (!result.transformed) {\n return { code: jsx, map: mdxMap === undefined ? null : mapOfSource(mdxMap, file, code) };\n }\n // A map from the final code to the JSX is of no use to a debugger: compose it with the one from the JSX\n // to the MDX file. When `@mdx-js/mdx` (or a replacement given as `mdx`) answered no map, it stays as it was.\n return {\n code: result.code,\n map:\n result.map === null || mdxMap === undefined\n ? result.map\n : composeToSource(result.map, mdxMap, file, code),\n };\n } catch (error) {\n if (error instanceof CompileError) return this.error(error.message);\n throw error;\n }\n },\n };\n}\n\n/** Reads the map `@mdx-js/mdx` answers with, or `undefined` when it gave none that can be used. */\nfunction rawMapOf(value: unknown): RawMap | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n const { mappings, names } = value as { mappings?: unknown; names?: unknown };\n if (typeof mappings !== \"string\") return undefined;\n return {\n mappings,\n names: Array.isArray(names)\n ? names.filter((name): name is string => typeof name === \"string\")\n : [],\n };\n}\n\n/** The same pattern without the `g` and `y` flags, so `test()` does not remember where the last call ended. */\nfunction statelessPattern(pattern: RegExp): RegExp {\n return pattern.global || pattern.s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IAAI,iBAAiB,cAAc,OAAO,KAAK,MAAM,MAAM,OAAO;IAClE,MAAM;GACR;EACF;CACF;AACF;;AAGA,SAAS,SAAS,OAAoC;CACpD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,KAAA;CACxD,MAAM,EAAE,UAAU,UAAU;CAC5B,IAAI,OAAO,aAAa,UAAU,OAAO,KAAA;CACzC,OAAO;EACL;EACA,OAAO,MAAM,QAAQ,KAAK,IACtB,MAAM,QAAQ,SAAyB,OAAO,SAAS,QAAQ,IAC/D,CAAC;CACP;AACF;;AAGA,SAAS,iBAAiB,SAAyB;CACjD,OAAO,QAAQ,UAAU,QAAQ,SAC7B,IAAI,OAAO,QAAQ,QAAQ,QAAQ,MAAM,QAAQ,SAAS,EAAE,CAAC,IAC7D;AACN"}
@@ -0,0 +1,2 @@
1
+ const e=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`;function t(t,n){let r=n<0?-n<<1|1:n<<1;do{let n=r&31;r>>>=5,r>0&&(n|=32),t.push(e.charAt(n))}while(r>0)}function n(t){let n=[],r=[],i=0,a=0,o=0,s=0,c=0,l=[],u=0,d=0,f=()=>{if(l.length===0)return;let[e=0,t,n,u,d]=l;if(i+=e,l.length===1)r.push([i]);else if(l.length!==4&&l.length!==5||t===void 0||n===void 0||u===void 0)throw SyntaxError(`source map: a segment has ${l.length} fields.`);else a+=t,o+=n,s+=u,d===void 0?r.push([i,a,o,s]):(c+=d,r.push([i,a,o,s,c]));l=[]};for(let a=0;a<t.length;a+=1){let o=t.charAt(a);if(o===`;`||o===`,`){if(d!==0)throw SyntaxError(`source map: a number is cut off.`);f(),o===`;`&&(n.push(r),r=[],i=0);continue}let s=e.indexOf(o);if(s===-1)throw SyntaxError(`source map: "${o}" is not a base 64 digit.`);u+=(s&31)*2**d,s&32?d+=5:(l.push(u%2==1?-Math.floor(u/2):u/2),u=0,d=0)}if(d!==0)throw SyntaxError(`source map: a number is cut off.`);return f(),n.push(r),n}function r(e){let n=[],r=0,i=0,a=0,o=0;return e.forEach((e,s)=>{s>0&&n.push(`;`);let c=0;e.forEach((e,s)=>{s>0&&n.push(`,`),t(n,e[0]-c),c=e[0],e.length!==1&&(t(n,e[1]-r),t(n,e[2]-i),t(n,e[3]-a),r=e[1],i=e[2],a=e[3],e.length===5&&(t(n,e[4]-o),o=e[4]))})}),n.join(``)}function i(e,t){if(e===void 0)return;let n=0,r=e.length-1,i;for(;n<=r;){let a=n+r>>1,o=e[a];if(o===void 0)break;o[0]<=t?(o.length>1&&(i=o),n=a+1):r=a-1}return i}function a(e,t,a,o,s){let c=n(t.mappings),l=[...t.names??[]],u=new Map(l.map((e,t)=>[e,t])),d=e=>{let t=u.get(e);return t===void 0?(l.push(e),u.set(e,l.length-1),l.length-1):t},f=n(e.mappings).map(t=>{let n=[];for(let r of t){if(r.length===1)continue;let t=i(c[r[2]],r[3]);if(t===void 0)continue;if(t.length===5){n.push([r[0],0,t[2],t[3],t[4]]);continue}let a=r.length===5?e.names?.[r[4]]:void 0;n.push(a===void 0?[r[0],0,t[2],t[3]]:[r[0],0,t[2],t[3],d(a)])}return n}),p={version:3,sources:[a],sourcesContent:[o],names:l,mappings:r(f)};return s!==void 0&&(p.file=s),p}function o(e,t,n){return{version:3,sources:[t],sourcesContent:[n],names:[...e.names??[]],mappings:e.mappings}}var s=class{#e;#t=[];#n=[];#r=[];constructor(e){this.#e=e?.file}addMapping(e){if(e.original===null)return;let t=e.source??this.#e??``,n=this.#t.indexOf(t);n===-1&&(n=this.#t.push(t)-1);let r;e.name!==void 0&&(r=this.#n.indexOf(e.name),r===-1&&(r=this.#n.push(e.name)-1)),this.#r.push({line:e.generated.line-1,column:e.generated.column,source:n,sourceLine:e.original.line-1,sourceColumn:e.original.column,name:r})}toJSON(){let e=[],t=[...this.#r].sort((e,t)=>e.line-t.line||e.column-t.column);for(let n of t){for(;e.length<=n.line;)e.push([]);e[n.line]?.push(n.name===void 0?[n.column,n.source,n.sourceLine,n.sourceColumn]:[n.column,n.source,n.sourceLine,n.sourceColumn,n.name])}let n={version:3,sources:[...this.#t],names:[...this.#n],mappings:r(e)};return this.#e!==void 0&&(n.file=this.#e),n}};export{s as MappingCollector,a as composeToSource,n as decodeMappings,r as encodeMappings,o as mapOfSource};
2
+ //# sourceMappingURL=source-maps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"source-maps.js","names":["BASE64","writeVlq","rest","value","digit","out","decodeMappings","lines","line","column","source","sourceLine","sourceColumn","name","numbers","shift","finishSegment","dc","ds","dl","dk","dn","i","mappings","char","encodeMappings","index","position","segment","segmentAt","low","high","found","middle","composeToSource","inside","inner","names","known","nameIndex","existing","outer","target","outerName","composed","content","file","mapOfSource","map","MappingCollector","#file","options","mapping","origin","#sources","#names","#entries","sorted","a","b","entry"],"sources":["../../../src/internal/source-maps.ts"],"sourcesContent":["/**\n * Source map helpers of the MDX plugin. `@mdx-js/mdx` turns the `.mdx` text into JSX, and the ShadowJS\n * compiler turns that JSX into the final code, so the plugin holds two maps: final code to JSX, and JSX\n * to `.mdx`. Build tools need the one map from the final code to the `.mdx` file, which {@link composeToSource}\n * builds. The helpers read and write the map format (version 3, base 64 VLQ) themselves: the plugin has\n * no runtime dependency besides the compiler, and the work is a few lines.\n */\n\n/** One decoded segment: generated column, then (source index, line, column and optionally a name index). */\nexport type Segment =\n | readonly [number]\n | readonly [number, number, number, number]\n | readonly [number, number, number, number, number];\n\n/** The parts of a version 3 source map this module reads. */\nexport interface RawMap {\n readonly mappings: string;\n readonly names?: readonly string[];\n}\n\n/** A version 3 source map this module writes. */\nexport interface ComposedMap {\n version: 3;\n file?: string;\n sources: string[];\n sourcesContent: string[];\n names: string[];\n mappings: string;\n}\n\nconst BASE64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nconst VLQ_BASE_SHIFT = 5;\nconst VLQ_BASE = 1 << VLQ_BASE_SHIFT;\nconst VLQ_MASK = VLQ_BASE - 1;\nconst VLQ_CONTINUE = VLQ_BASE;\n\n/** Appends one signed number, as a base 64 VLQ, to `out`. */\nfunction writeVlq(out: string[], value: number): void {\n let rest = value < 0 ? (-value << 1) | 1 : value << 1;\n do {\n let digit = rest & VLQ_MASK;\n rest >>>= VLQ_BASE_SHIFT;\n if (rest > 0) digit |= VLQ_CONTINUE;\n out.push(BASE64.charAt(digit));\n } while (rest > 0);\n}\n\n/**\n * Decodes the `mappings` of a source map.\n *\n * @param mappings The `mappings` string: lines separated by `;`, segments by `,`.\n * @returns One list of segments per generated line.\n * @throws SyntaxError when a character is not base 64 or a number is cut off.\n * @internal\n */\nexport function decodeMappings(mappings: string): Segment[][] {\n const lines: Segment[][] = [];\n let line: Segment[] = [];\n let column = 0;\n let source = 0;\n let sourceLine = 0;\n let sourceColumn = 0;\n let name = 0;\n let numbers: number[] = [];\n let value = 0;\n let shift = 0;\n const finishSegment = (): void => {\n if (numbers.length === 0) return;\n const [dc = 0, ds, dl, dk, dn] = numbers;\n column += dc;\n if (numbers.length === 1) {\n line.push([column]);\n } else if (\n (numbers.length !== 4 && numbers.length !== 5) ||\n ds === undefined ||\n dl === undefined ||\n dk === undefined\n ) {\n throw new SyntaxError(`source map: a segment has ${numbers.length} fields.`);\n } else {\n source += ds;\n sourceLine += dl;\n sourceColumn += dk;\n if (dn === undefined) {\n line.push([column, source, sourceLine, sourceColumn]);\n } else {\n name += dn;\n line.push([column, source, sourceLine, sourceColumn, name]);\n }\n }\n numbers = [];\n };\n for (let i = 0; i < mappings.length; i += 1) {\n const char = mappings.charAt(i);\n if (char === \";\" || char === \",\") {\n if (shift !== 0) throw new SyntaxError(\"source map: a number is cut off.\");\n finishSegment();\n if (char === \";\") {\n lines.push(line);\n line = [];\n column = 0;\n }\n continue;\n }\n const digit = BASE64.indexOf(char);\n if (digit === -1) throw new SyntaxError(`source map: \"${char}\" is not a base 64 digit.`);\n value += (digit & VLQ_MASK) * 2 ** shift;\n if ((digit & VLQ_CONTINUE) !== 0) {\n shift += VLQ_BASE_SHIFT;\n } else {\n numbers.push(value % 2 === 1 ? -Math.floor(value / 2) : value / 2);\n value = 0;\n shift = 0;\n }\n }\n if (shift !== 0) throw new SyntaxError(\"source map: a number is cut off.\");\n finishSegment();\n lines.push(line);\n return lines;\n}\n\n/**\n * Encodes decoded mappings.\n *\n * @param lines One list of segments per generated line, each list sorted by generated column.\n * @returns The `mappings` string.\n * @internal\n */\nexport function encodeMappings(lines: readonly (readonly Segment[])[]): string {\n const out: string[] = [];\n let source = 0;\n let sourceLine = 0;\n let sourceColumn = 0;\n let name = 0;\n lines.forEach((line, index) => {\n if (index > 0) out.push(\";\");\n let column = 0;\n line.forEach((segment, position) => {\n if (position > 0) out.push(\",\");\n writeVlq(out, segment[0] - column);\n column = segment[0];\n if (segment.length === 1) return;\n writeVlq(out, segment[1] - source);\n writeVlq(out, segment[2] - sourceLine);\n writeVlq(out, segment[3] - sourceColumn);\n source = segment[1];\n sourceLine = segment[2];\n sourceColumn = segment[3];\n if (segment.length === 5) {\n writeVlq(out, segment[4] - name);\n name = segment[4];\n }\n });\n });\n return out.join(\"\");\n}\n\n/** The last segment of a line that starts at or before `column` and maps to a source position. */\nfunction segmentAt(\n line: readonly Segment[] | undefined,\n column: number,\n): Exclude<Segment, readonly [number]> | undefined {\n if (line === undefined) return undefined;\n let low = 0;\n let high = line.length - 1;\n let found: Exclude<Segment, readonly [number]> | undefined;\n while (low <= high) {\n const middle = (low + high) >> 1;\n const segment = line[middle];\n if (segment === undefined) break;\n if (segment[0] <= column) {\n if (segment.length > 1) found = segment as Exclude<Segment, readonly [number]>;\n low = middle + 1;\n } else {\n high = middle - 1;\n }\n }\n return found;\n}\n\n/**\n * Composes two maps into one that points at the first text. `outer` maps the final code to the middle\n * text (the JSX), `inner` maps the middle text to the original (the `.mdx` file). A position of the final\n * code that falls where `inner` maps nothing gets no mapping. A name recorded by `inner` wins, because it is\n * the earlier spelling.\n *\n * @param outer Final code to middle text.\n * @param inner Middle text to original text; the original is its only source.\n * @param source The name of the original file.\n * @param content The text of the original file.\n * @param file The name of the final file, if known.\n * @returns The map from the final code to the original file.\n * @internal\n */\nexport function composeToSource(\n outer: RawMap,\n inner: RawMap,\n source: string,\n content: string,\n file?: string,\n): ComposedMap {\n const inside = decodeMappings(inner.mappings);\n const names = [...(inner.names ?? [])];\n const known = new Map<string, number>(names.map((name, index) => [name, index]));\n const nameIndex = (name: string): number => {\n const existing = known.get(name);\n if (existing !== undefined) return existing;\n names.push(name);\n known.set(name, names.length - 1);\n return names.length - 1;\n };\n const lines = decodeMappings(outer.mappings).map((line) => {\n const out: Segment[] = [];\n for (const segment of line) {\n if (segment.length === 1) continue;\n const target = segmentAt(inside[segment[2]], segment[3]);\n if (target === undefined) continue;\n if (target.length === 5) {\n out.push([segment[0], 0, target[2], target[3], target[4]]);\n continue;\n }\n const outerName = segment.length === 5 ? outer.names?.[segment[4]] : undefined;\n out.push(\n outerName === undefined\n ? [segment[0], 0, target[2], target[3]]\n : [segment[0], 0, target[2], target[3], nameIndex(outerName)],\n );\n }\n return out;\n });\n const composed: ComposedMap = {\n version: 3,\n sources: [source],\n sourcesContent: [content],\n names,\n mappings: encodeMappings(lines),\n };\n if (file !== undefined) composed.file = file;\n return composed;\n}\n\n/**\n * The map of `@mdx-js/mdx` as a complete map of the original file: its one source named and embedded.\n *\n * @param map Middle text to original text; the original is its only source.\n * @param source The name of the original file.\n * @param content The text of the original file.\n * @returns The map.\n * @internal\n */\nexport function mapOfSource(map: RawMap, source: string, content: string): ComposedMap {\n return {\n version: 3,\n sources: [source],\n sourcesContent: [content],\n names: [...(map.names ?? [])],\n mappings: map.mappings,\n };\n}\n\n/** What `astring`, the JavaScript printer of `@mdx-js/mdx`, hands to `addMapping`. */\ninterface Mapping {\n readonly generated: { readonly line: number; readonly column: number };\n readonly original: { readonly line: number; readonly column: number } | null;\n readonly source?: string;\n readonly name?: string;\n}\n\n/**\n * The `SourceMapGenerator` the MDX plugin hands to `@mdx-js/mdx`, which uses it to record where each piece\n * of the JSX it prints came from. It has the part of the interface of the generator of the `source-map`\n * package that the printer calls (`addMapping`, `toJSON`), so the plugin needs no such package: `@mdx-js/mdx`\n * brings its own, which a package manager need not hoist to where this plugin can import it.\n *\n * @internal\n */\nexport class MappingCollector {\n readonly #file: string | undefined;\n readonly #sources: string[] = [];\n readonly #names: string[] = [];\n readonly #entries: Array<{\n line: number;\n column: number;\n source: number;\n sourceLine: number;\n sourceColumn: number;\n name: number | undefined;\n }> = [];\n\n /** @param options `file` is the name of the generated file. */\n constructor(options?: { readonly file?: string }) {\n this.#file = options?.file;\n }\n\n /** Records that the generated position came from the original one. A mapping without an original is skipped. */\n addMapping(mapping: Mapping): void {\n if (mapping.original === null) return;\n const origin = mapping.source ?? this.#file ?? \"\";\n let source = this.#sources.indexOf(origin);\n if (source === -1) source = this.#sources.push(origin) - 1;\n let name: number | undefined;\n if (mapping.name !== undefined) {\n name = this.#names.indexOf(mapping.name);\n if (name === -1) name = this.#names.push(mapping.name) - 1;\n }\n this.#entries.push({\n line: mapping.generated.line - 1,\n column: mapping.generated.column,\n source,\n sourceLine: mapping.original.line - 1,\n sourceColumn: mapping.original.column,\n name,\n });\n }\n\n /** The map as a version 3 source map object. */\n toJSON(): { version: 3; file?: string; sources: string[]; names: string[]; mappings: string } {\n const lines: Segment[][] = [];\n // The printer emits in order, but a stable sort keeps the map valid whatever the order.\n const sorted = [...this.#entries].sort((a, b) => a.line - b.line || a.column - b.column);\n for (const entry of sorted) {\n while (lines.length <= entry.line) lines.push([]);\n lines[entry.line]?.push(\n entry.name === undefined\n ? [entry.column, entry.source, entry.sourceLine, entry.sourceColumn]\n : [entry.column, entry.source, entry.sourceLine, entry.sourceColumn, entry.name],\n );\n }\n const map: {\n version: 3;\n file?: string;\n sources: string[];\n names: string[];\n mappings: string;\n } = {\n version: 3,\n sources: [...this.#sources],\n names: [...this.#names],\n mappings: encodeMappings(lines),\n };\n if (this.#file !== undefined) map.file = this.#file;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S,CAAC,GAAG,KAAKD,EAAQ,CAAC,CAAC,MAAM,EAAG,IAAME,EAAE,KAAOC,EAAE,MAAQD,EAAE,OAASC,EAAE,MAAM,EACvF,IAAK,IAAMC,KAASH,EAAQ,CAC1B,KAAOlD,EAAM,QAAUqD,EAAM,MAAMrD,EAAM,KAAK,CAAC,CAAC,EAChDA,EAAMqD,EAAM,KAAK,EAAE,KACjBA,EAAM,OAAS,IAAA,GACX,CAACA,EAAM,OAAQA,EAAM,OAAQA,EAAM,WAAYA,EAAM,YAAY,EACjE,CAACA,EAAM,OAAQA,EAAM,OAAQA,EAAM,WAAYA,EAAM,aAAcA,EAAM,IAAI,CACnF,CACF,CACA,IAAMZ,EAMF,CACF,QAAS,EACT,QAAS,CAAC,GAAG,KAAKM,EAAQ,EAC1B,MAAO,CAAC,GAAG,KAAKC,EAAM,EACtB,SAAU9B,EAAelB,CAAK,CAChC,EAEA,OADI,KAAK2C,KAAU,IAAA,KAAW,EAAI,KAAO,KAAKA,IACvCF,CACT,CACF,E"}
package/dist/prod/mdx.js CHANGED
@@ -1,2 +1,2 @@
1
- import{moduleFile as e}from"./internal/ids.js";import{CompileError as t,compile as n,validatePlugins as r}from"@shadow-js/compiler";function i(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function a(e){return e===void 0||e===`@shadow-js/web/server`?`@shadow-js/web`:e}const o=`_components`,s=`_ShadowDynamic`;function c(e,t){return()=>n=>{let r=0,a=[n];for(;a.length>0;){let t=a.pop();if(Array.isArray(t))for(let e of t)a.push(e);else if(i(t)){if(t.type===`JSXElement`){let n=t.openingElement,a=t.closingElement;if(i(n)&&l(n.name)!==void 0){let t=l(n.name);e===`static`?n.name=u(t):(n.name=u(s),n.attributes.unshift({type:`JSXAttribute`,name:u(`component`),value:{type:`JSXExpressionContainer`,expression:{type:`MemberExpression`,object:{type:`Identifier`,name:o},property:{type:`Identifier`,name:t},computed:!1,optional:!1}}}),r+=1),i(a)&&(a.name=u(e===`static`?t:s))}}for(let e of Object.values(t))typeof e==`object`&&e&&a.push(e)}}r>0&&n.body.unshift({type:`ImportDeclaration`,specifiers:[{type:`ImportSpecifier`,imported:{type:`Identifier`,name:`Dynamic`},local:{type:`Identifier`,name:s}}],source:{type:`Literal`,value:t,raw:JSON.stringify(t)},attributes:[]})}}function l(e){if(!i(e)||e.type!==`JSXMemberExpression`)return;let t=e.object,n=e.property;if(i(t)&&t.type===`JSXIdentifier`&&t.name===o)return i(n)&&typeof n.name==`string`?n.name:void 0}function u(e){return{type:`JSXIdentifier`,name:e}}const d=/\.mdx$/,f=/[\\/]node_modules[\\/]/;async function p(e){let t;try{t=await import(e)}catch(t){throw Error(`shadowMdx: cannot load "${e}". Install it with "npm install --save-dev ${e}", or pass your own function as mdx.`,{cause:t})}if(typeof t.compile!=`function`)throw TypeError(`shadowMdx: the module "${e}" has no compile function.`);let n=t.compile;return(e,t)=>Reflect.apply(n,void 0,[e,t])}function m(i={}){for(let e of[`include`,`exclude`]){let t=i[e];if(t!==void 0&&!(t instanceof RegExp))throw TypeError(`shadowMdx(): "${e}" must be a RegExp (got ${typeof t}).`)}let o=i.plugins===void 0?[]:r(i.plugins,`shadowMdx(): plugins`),s=h(i.include??d),l=h(i.exclude??f),u,m=!1;return{name:`shadowjs-mdx`,enforce:`pre`,config(e,t){m=t.command===`serve`},async transform(r,d,f){let{file:h,skip:g}=e(d);if(g||l.test(h)||!s.test(h))return null;u??=typeof i.mdx==`function`?Promise.resolve(i.mdx):p(i.mdx??`@mdx-js/mdx`);let _=await u,v;try{let e=await _({value:r,path:h},{jsx:!0,jsxImportSource:i.moduleName??`@shadow-js/web`,development:!1,format:h.endsWith(`.mdx`)?`mdx`:`md`,...i.remarkPlugins===void 0?{}:{remarkPlugins:i.remarkPlugins},...i.rehypePlugins===void 0?{}:{rehypePlugins:i.rehypePlugins},recmaPlugins:[...i.recmaPlugins??[],c(i.elements??`overridable`,a(i.moduleName))],...i.remarkRehypeOptions===void 0?{}:{remarkRehypeOptions:i.remarkRehypeOptions},...i.providerImportSource===void 0?{}:{providerImportSource:i.providerImportSource}});v=typeof e.value==`string`?e.value:Buffer.from(e.value).toString(`utf8`)}catch(e){let t=e,n=typeof t.line==`number`&&t.line>0?{line:t.line,column:Math.max((t.column??1)-1,0)}:void 0;return this.error(t.reason??t.message??String(e),n)}try{let e=n(v,{filename:`${h}.tsx`,generate:f?.ssr===!0?`ssr`:`dom`,dev:m,autoReactive:!0,hmr:!1,...i.moduleName===void 0?{}:{moduleName:i.moduleName},...o.length>0?{plugins:o}:{}});for(let t of e.diagnostics)t.severity===`warning`&&this.warn(t.message,{line:t.line,column:t.column});return{code:e.transformed?e.code:v,map:e.transformed?e.map:null}}catch(e){if(e instanceof t)return this.error(e.message,e.diagnostic.line===0?void 0:{line:e.diagnostic.line,column:e.diagnostic.column});throw e}}}}function h(e){return e.global||e.sticky?new RegExp(e.source,e.flags.replace(/[gy]/g,``)):e}export{m as shadowMdx};
1
+ import{moduleFile as e}from"./internal/ids.js";import{MappingCollector as t,composeToSource as n,mapOfSource as r}from"./internal/source-maps.js";import{CompileError as i,compile as a,validatePlugins as o}from"@shadow-js/compiler";function s(e){return typeof e==`object`&&!!e&&typeof e.type==`string`}function c(e){return e===void 0||e===`@shadow-js/web/server`?`@shadow-js/web`:e}const l=`_components`,u=`_ShadowDynamic`;function d(e,t){return()=>n=>{let r=0,i=[n];for(;i.length>0;){let t=i.pop();if(Array.isArray(t))for(let e of t)i.push(e);else if(s(t)){if(t.type===`JSXElement`){let n=t.openingElement,i=t.closingElement;if(s(n)&&f(n.name)!==void 0){let t=f(n.name);e===`static`?n.name=p(t):(n.name=p(u),n.attributes.unshift({type:`JSXAttribute`,name:p(`component`),value:{type:`JSXExpressionContainer`,expression:{type:`MemberExpression`,object:{type:`Identifier`,name:l},property:{type:`Identifier`,name:t},computed:!1,optional:!1}}}),r+=1),s(i)&&(i.name=p(e===`static`?t:u))}}for(let e of Object.values(t))typeof e==`object`&&e&&i.push(e)}}r>0&&n.body.unshift({type:`ImportDeclaration`,specifiers:[{type:`ImportSpecifier`,imported:{type:`Identifier`,name:`Dynamic`},local:{type:`Identifier`,name:u}}],source:{type:`Literal`,value:t,raw:JSON.stringify(t)},attributes:[]})}}function f(e){if(!s(e)||e.type!==`JSXMemberExpression`)return;let t=e.object,n=e.property;if(s(t)&&t.type===`JSXIdentifier`&&t.name===l)return s(n)&&typeof n.name==`string`?n.name:void 0}function p(e){return{type:`JSXIdentifier`,name:e}}const m=/\.mdx$/,h=/[\\/]node_modules[\\/]/;async function g(e){let t;try{t=await import(e)}catch(t){throw Error(`shadowMdx: cannot load "${e}". Install it with "npm install --save-dev ${e}", or pass your own function as mdx.`,{cause:t})}if(typeof t.compile!=`function`)throw TypeError(`shadowMdx: the module "${e}" has no compile function.`);let n=t.compile;return(e,t)=>Reflect.apply(n,void 0,[e,t])}function _(s={}){for(let e of[`include`,`exclude`]){let t=s[e];if(t!==void 0&&!(t instanceof RegExp))throw TypeError(`shadowMdx(): "${e}" must be a RegExp (got ${typeof t}).`)}let l=s.plugins===void 0?[]:o(s.plugins,`shadowMdx(): plugins`),u=y(s.include??m),f=y(s.exclude??h),p,_=!1;return{name:`shadowjs-mdx`,enforce:`pre`,config(e,t){_=t.command===`serve`},async transform(o,m,h){let{file:y,skip:b}=e(m);if(b||f.test(y)||!u.test(y))return null;p??=typeof s.mdx==`function`?Promise.resolve(s.mdx):g(s.mdx??`@mdx-js/mdx`);let x=await p,S,C;try{let e=await x({value:o,path:y},{jsx:!0,jsxImportSource:s.moduleName??`@shadow-js/web`,development:!1,format:y.endsWith(`.mdx`)?`mdx`:`md`,...s.remarkPlugins===void 0?{}:{remarkPlugins:s.remarkPlugins},...s.rehypePlugins===void 0?{}:{rehypePlugins:s.rehypePlugins},recmaPlugins:[...s.recmaPlugins??[],d(s.elements??`overridable`,c(s.moduleName))],...s.remarkRehypeOptions===void 0?{}:{remarkRehypeOptions:s.remarkRehypeOptions},...s.providerImportSource===void 0?{}:{providerImportSource:s.providerImportSource},SourceMapGenerator:t});S=typeof e.value==`string`?e.value:Buffer.from(e.value).toString(`utf8`),C=v(e.map)}catch(e){let t=e,n=typeof t.line==`number`&&t.line>0?{line:t.line,column:Math.max((t.column??1)-1,0)}:void 0;return this.error(t.reason??t.message??String(e),n)}try{let e=a(S,{filename:`${y}.tsx`,generate:h?.ssr===!0?`ssr`:`dom`,dev:_,autoReactive:!0,hmr:!1,...s.moduleName===void 0?{}:{moduleName:s.moduleName},...l.length>0?{plugins:l}:{}});for(let t of e.diagnostics)t.severity===`warning`&&this.warn(t.message);return e.transformed?{code:e.code,map:e.map===null||C===void 0?e.map:n(e.map,C,y,o)}:{code:S,map:C===void 0?null:r(C,y,o)}}catch(e){if(e instanceof i)return this.error(e.message);throw e}}}}function v(e){if(typeof e!=`object`||!e)return;let{mappings:t,names:n}=e;if(typeof t==`string`)return{mappings:t,names:Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}}function y(e){return e.global||e.sticky?new RegExp(e.source,e.flags.replace(/[gy]/g,``)):e}export{_ as shadowMdx};
2
2
  //# sourceMappingURL=mdx.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mdx.js","names":["isNode","value","dynamicSourceOf","moduleName","LOOKUP","DYNAMIC","elementsPlugin","rewritten","pending","tree","node","child","opening","\"openingElement\"","closing","\"closingElement\"","lookupName","\"name\"","tag","mode","identifier","\"attributes\"","\"body\"","dynamicSource","name","object","\"object\"","property","\"property\"","DEFAULT_INCLUDE","DEFAULT_EXCLUDE","loadMdx","loaded","specifier","cause","compileMdx","file","options","shadowMdx","plugins","validatePlugins","include","statelessPattern","exclude","dev","env","moduleFile","id","skip","mdx","jsx","output","code","error","found","position","result","compile","transformOptions","diagnostic","CompileError","pattern"],"sources":["../../src/mdx.ts"],"sourcesContent":["import { CompileError, type CompilerPlugin, compile, validatePlugins } from \"@shadow-js/compiler\";\nimport type { Plugin } from \"vite\";\nimport { moduleFile } from \"./internal/ids\";\n\n/**\n * `shadowMdx()`: a Vite plugin that turns `.mdx` (and `.md`) files into ShadowJS components. MDX is compiled to JSX by\n * `@mdx-js/mdx`, an optional peer, and the JSX goes through the ShadowJS compiler in the same step, so an MDX file needs no\n * other plugin to be compiled. The default export of a module is the component; the `export`s of the file (a `frontmatter`\n * from `remark-mdx-frontmatter`, a `meta` object) are named exports.\n * @packageDocumentation\n */\n\n/** The file `@mdx-js/mdx` answers: a `VFile`, whose `value` holds the code. */\ninterface MdxOutput {\n readonly value: string | Uint8Array;\n}\n\n/** What `compile` of `@mdx-js/mdx` accepts (the options this plugin sets, and the lists it hands on). */\ninterface MdxCompileOptions {\n readonly jsx: true;\n readonly jsxImportSource: string;\n readonly development: false;\n readonly format: \"mdx\" | \"md\";\n readonly remarkPlugins?: readonly unknown[];\n readonly rehypePlugins?: readonly unknown[];\n readonly recmaPlugins?: readonly unknown[];\n readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;\n readonly providerImportSource?: string;\n}\n\n/** `compile` of `@mdx-js/mdx`, or a function with its shape. @since 1.0.0 */\nexport type MdxCompile = (\n file: { readonly value: string; readonly path: string },\n options: MdxCompileOptions,\n) => Promise<MdxOutput>;\n\n/** Options of {@link shadowMdx}. @since 1.0.0 */\nexport interface ShadowMdxOptions {\n /** Files to compile, matched against the module id without its query string. Default `/\\.mdx$/`. Add `.md` to read Markdown files too. */\n readonly include?: RegExp;\n /** Files to skip; checked first. Default: any path with a `node_modules` segment. */\n readonly exclude?: RegExp;\n /** Plugins of the Markdown syntax tree (`remark-frontmatter`, `remark-mdx-frontmatter`, `remark-gfm`, ...), as `@mdx-js/mdx` takes them. */\n readonly remarkPlugins?: readonly unknown[];\n /** Plugins of the HTML syntax tree (`rehype-slug`, `rehype-autolink-headings`, ...). */\n readonly rehypePlugins?: readonly unknown[];\n /** Plugins of the JavaScript syntax tree. They run before the plugin's own pass over the elements. */\n readonly recmaPlugins?: readonly unknown[];\n /**\n * How the elements of Markdown (`h1`, `p`, `a`, `code`, ...) are rendered.\n *\n * - `\"overridable\"`: each one is looked up in the `components` prop (and the provider), so an app can replace `a` or `h1`\n * for every page. Each looked-up element is rendered by `Dynamic`.\n * - `\"static\"`: each one is a plain element in the page's template, cloned in one call. The `components` prop still\n * supplies components the file names itself (`<Chart />`) and the `wrapper`, but cannot replace `h1` or `a`.\n *\n * Choose `\"static\"` for pages that never replace a Markdown element: documentation and blog posts render faster and ship\n * less code.\n * @default \"overridable\"\n */\n readonly elements?: \"overridable\" | \"static\";\n /** Options of `remark-rehype`. */\n readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;\n /**\n * A module that exports `useMDXComponents`, whose components every MDX file may use without a `components` prop (the\n * way `@mdx-js/react` works for React). Default: none; pass `components` to the file's component instead.\n */\n readonly providerImportSource?: string;\n /** `@mdx-js/mdx`, by module name, or your own `compile`. Default `\"@mdx-js/mdx\"`. */\n readonly mdx?: string | MdxCompile;\n /** Compiler plugins that run on the JSX of every MDX file (see `ShadowPluginOptions.plugins`). */\n readonly plugins?: readonly CompilerPlugin[];\n /**\n * Module the compiled code imports its runtime helpers from. Default `\"@shadow-js/web\"` (`\"@shadow-js/web/server\"` for SSR).\n * With `elements: \"overridable\"` the file also imports `Dynamic` from it, so a custom module must export `Dynamic`;\n * `\"@shadow-js/web/server\"` has none, so `Dynamic` is then imported from `\"@shadow-js/web\"`.\n */\n readonly moduleName?: string;\n}\n\n/** A node of the JavaScript syntax tree `@mdx-js/mdx` hands to recma plugins (ESTree with JSX), read structurally. */\ninterface EsNode {\n type: string;\n [key: string]: unknown;\n}\n\nfunction isNode(value: unknown): value is EsNode {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { type?: unknown }).type === \"string\"\n );\n}\n\n/**\n * The module `Dynamic` is imported from: the one `moduleName` names, so a project that points the runtime at\n * its own module (an alias, a re-export) does not need `@shadow-js/web` resolvable as well. The one exception\n * is the SSR helpers entry `@shadow-js/web/server`: it holds the server helpers and no `Dynamic`, which the\n * main entry provides (and Vite resolves to its server build in an SSR build).\n */\nfunction dynamicSourceOf(moduleName: string | undefined): string {\n if (moduleName === undefined || moduleName === \"@shadow-js/web/server\") return \"@shadow-js/web\";\n return moduleName;\n}\n\n/** The identifier `@mdx-js/mdx` binds the element lookup table to. */\nconst LOOKUP = \"_components\";\n/** The local name of `Dynamic`: it cannot clash with a name the file exports or imports. */\nconst DYNAMIC = \"_ShadowDynamic\";\n\n/**\n * Rewrites the elements `@mdx-js/mdx` looks up in its table (`<_components.h1>`): into plain `<h1>` for `\"static\"`, into\n * `<Dynamic component={_components.h1}>` for `\"overridable\"`. The lookup yields a string for a default element and a\n * function for an override, and a ShadowJS component tag must be a function.\n */\nfunction elementsPlugin(\n mode: \"overridable\" | \"static\",\n dynamicSource: string,\n): () => (tree: EsNode) => void {\n return () => (tree) => {\n let rewritten = 0;\n const pending: unknown[] = [tree];\n while (pending.length > 0) {\n const node = pending.pop();\n if (Array.isArray(node)) {\n for (const child of node) pending.push(child);\n continue;\n }\n if (!isNode(node)) continue;\n if (node.type === \"JSXElement\") {\n const opening = node[\"openingElement\"];\n const closing = node[\"closingElement\"];\n if (isNode(opening) && lookupName(opening[\"name\"]) !== undefined) {\n const tag = lookupName(opening[\"name\"]) as string;\n if (mode === \"static\") {\n opening[\"name\"] = identifier(tag);\n } else {\n opening[\"name\"] = identifier(DYNAMIC);\n const attributes = opening[\"attributes\"] as unknown[];\n attributes.unshift({\n type: \"JSXAttribute\",\n name: identifier(\"component\"),\n value: {\n type: \"JSXExpressionContainer\",\n expression: {\n type: \"MemberExpression\",\n object: { type: \"Identifier\", name: LOOKUP },\n property: { type: \"Identifier\", name: tag },\n computed: false,\n optional: false,\n },\n },\n });\n rewritten += 1;\n }\n if (isNode(closing)) closing[\"name\"] = identifier(mode === \"static\" ? tag : DYNAMIC);\n }\n }\n for (const value of Object.values(node)) {\n if (typeof value === \"object\" && value !== null) pending.push(value);\n }\n }\n if (rewritten > 0) {\n const body = tree[\"body\"] as unknown[];\n body.unshift({\n type: \"ImportDeclaration\",\n specifiers: [\n {\n type: \"ImportSpecifier\",\n imported: { type: \"Identifier\", name: \"Dynamic\" },\n local: { type: \"Identifier\", name: DYNAMIC },\n },\n ],\n source: { type: \"Literal\", value: dynamicSource, raw: JSON.stringify(dynamicSource) },\n attributes: [],\n });\n }\n };\n}\n\n/** The element name of `_components.name` as a JSX tag name, otherwise `undefined`. */\nfunction lookupName(name: unknown): string | undefined {\n if (!isNode(name) || name.type !== \"JSXMemberExpression\") return undefined;\n const object = name[\"object\"];\n const property = name[\"property\"];\n if (!isNode(object) || object.type !== \"JSXIdentifier\" || object[\"name\"] !== LOOKUP)\n return undefined;\n return isNode(property) && typeof property[\"name\"] === \"string\" ? property[\"name\"] : undefined;\n}\n\nfunction identifier(name: string): EsNode {\n return { type: \"JSXIdentifier\", name };\n}\n\nconst DEFAULT_INCLUDE = /\\.mdx$/;\nconst DEFAULT_EXCLUDE = /[\\\\/]node_modules[\\\\/]/;\n\n/** `@mdx-js/mdx` warns with a position; so do the errors of its parsers. */\ninterface Positioned {\n readonly message?: string;\n readonly line?: number | null;\n readonly column?: number | null;\n readonly reason?: string;\n}\n\nasync function loadMdx(specifier: string): Promise<MdxCompile> {\n let loaded: { compile?: unknown };\n try {\n loaded = (await import(specifier)) as { compile?: unknown };\n } catch (cause) {\n throw new Error(\n `shadowMdx: cannot load \"${specifier}\". Install it with \"npm install --save-dev ${specifier}\", or pass your own function as mdx.`,\n { cause },\n );\n }\n if (typeof loaded.compile !== \"function\") {\n throw new TypeError(`shadowMdx: the module \"${specifier}\" has no compile function.`);\n }\n const compileMdx = loaded.compile;\n return (file, options) =>\n Reflect.apply(compileMdx, undefined, [file, options]) as Promise<MdxOutput>;\n}\n\n/**\n * Creates the plugin that compiles MDX to ShadowJS components. It runs before Vite's own handling (`enforce: \"pre\"`), so Vite\n * never sees MDX or JSX. A file is compiled for the browser, or for the server in an SSR build; a syntax error in the MDX is\n * reported with its file, line and column. Hot updates reload the page: an MDX file has no component state worth keeping.\n *\n * @param options Which files, the remark, rehype and recma plugins, and the MDX compiler.\n * @returns A Vite plugin named `shadowjs-mdx`.\n * @throws TypeError when `include` or `exclude` is not a `RegExp`, or `plugins` is not a list of valid compiler plugins.\n * @example\n * // vite.config.ts\n * import { shadow } from \"@shadow-js/vite\";\n * import { shadowMdx } from \"@shadow-js/vite/mdx\";\n * import remarkFrontmatter from \"remark-frontmatter\";\n * import remarkMdxFrontmatter from \"remark-mdx-frontmatter\";\n *\n * export default {\n * plugins: [\n * shadowMdx({ remarkPlugins: [remarkFrontmatter, remarkMdxFrontmatter] }),\n * shadow(),\n * ],\n * };\n * @since 1.0.0\n */\nexport function shadowMdx(options: ShadowMdxOptions = {}): Plugin {\n for (const name of [\"include\", \"exclude\"] as const) {\n const value = options[name];\n if (value !== undefined && !(value instanceof RegExp)) {\n throw new TypeError(`shadowMdx(): \"${name}\" must be a RegExp (got ${typeof value}).`);\n }\n }\n const plugins =\n options.plugins === undefined ? [] : validatePlugins(options.plugins, \"shadowMdx(): plugins\");\n const include = statelessPattern(options.include ?? DEFAULT_INCLUDE);\n const exclude = statelessPattern(options.exclude ?? DEFAULT_EXCLUDE);\n let compileMdx: Promise<MdxCompile> | undefined;\n let dev = false;\n return {\n name: \"shadowjs-mdx\",\n enforce: \"pre\",\n config(_config, env) {\n dev = env.command === \"serve\";\n },\n async transform(code, id, transformOptions) {\n const { file, skip } = moduleFile(id);\n if (skip || exclude.test(file) || !include.test(file)) return null;\n compileMdx ??=\n typeof options.mdx === \"function\"\n ? Promise.resolve(options.mdx)\n : loadMdx(options.mdx ?? \"@mdx-js/mdx\");\n const mdx = await compileMdx;\n let jsx: string;\n try {\n const output = await mdx(\n { value: code, path: file },\n {\n jsx: true,\n jsxImportSource: options.moduleName ?? \"@shadow-js/web\",\n development: false,\n format: file.endsWith(\".mdx\") ? \"mdx\" : \"md\",\n ...(options.remarkPlugins === undefined\n ? {}\n : { remarkPlugins: options.remarkPlugins }),\n ...(options.rehypePlugins === undefined\n ? {}\n : { rehypePlugins: options.rehypePlugins }),\n recmaPlugins: [\n ...(options.recmaPlugins ?? []),\n elementsPlugin(\n options.elements ?? \"overridable\",\n dynamicSourceOf(options.moduleName),\n ),\n ],\n ...(options.remarkRehypeOptions === undefined\n ? {}\n : { remarkRehypeOptions: options.remarkRehypeOptions }),\n ...(options.providerImportSource === undefined\n ? {}\n : { providerImportSource: options.providerImportSource }),\n },\n );\n jsx =\n typeof output.value === \"string\"\n ? output.value\n : Buffer.from(output.value).toString(\"utf8\");\n } catch (error) {\n const found = error as Positioned;\n const position =\n typeof found.line === \"number\" && found.line > 0\n ? { line: found.line, column: Math.max((found.column ?? 1) - 1, 0) }\n : undefined;\n return this.error(found.reason ?? found.message ?? String(error), position);\n }\n try {\n const result = compile(jsx, {\n filename: `${file}.tsx`,\n generate: transformOptions?.ssr === true ? \"ssr\" : \"dom\",\n dev,\n autoReactive: true,\n hmr: false,\n ...(options.moduleName === undefined ? {} : { moduleName: options.moduleName }),\n ...(plugins.length > 0 ? { plugins } : {}),\n });\n for (const diagnostic of result.diagnostics) {\n if (diagnostic.severity === \"warning\") {\n this.warn(diagnostic.message, { line: diagnostic.line, column: diagnostic.column });\n }\n }\n return {\n code: result.transformed ? result.code : jsx,\n map: result.transformed ? result.map : null,\n };\n } catch (error) {\n if (error instanceof CompileError) {\n return this.error(\n error.message,\n error.diagnostic.line === 0\n ? undefined\n : { line: error.diagnostic.line, column: error.diagnostic.column },\n );\n }\n throw error;\n }\n },\n };\n}\n\n/** The same pattern without the `g` and `y` flags, so `test()` does not remember where the last call ended. */\nfunction statelessPattern(pattern: RegExp): RegExp {\n return pattern.global || pattern.sticky\n ? new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, \"\"))\n : pattern;\n}\n"],"mappings":"A,oIAsFA,SAASA,EAAO,EAAiC,CAC/C,OACE,OAAOC,GAAU,YACjBA,GACA,OAAQA,EAA6B,MAAS,QAElD,CAQA,SAASC,EAAgB,EAAwC,CAE/D,OADIC,IAAe,IAAA,IAAaA,IAAe,wB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AMC,EAAQD,EACRE,EACJ,OAAOD,EAAM,MAAS,UAAYA,EAAM,KAAO,EAC3C,CAAE,KAAMA,EAAM,KAAM,OAAQ,KAAK,KAAKA,EAAM,QAAU,GAAK,EAAG,CAAC,CAAE,EACjE,IAAA,GACN,OAAO,KAAK,MAAMA,EAAM,QAAUA,EAAM,SAAW,OAAOD,CAAK,EAAGE,CAAQ,CAC5E,CACA,GAAI,CACF,IAAMC,EAASC,EAAQP,EAAK,CAC1B,SAAU,GAAGd,EAAK,MAClB,SAAUsB,GAAkB,MAAQ,GAAO,MAAQ,MACnD,MACA,aAAc,GACd,IAAK,GACL,GAAIrB,EAAQ,aAAe,IAAA,GAAY,CAAC,EAAI,CAAE,WAAYA,EAAQ,UAAW,EAC7E,GAAIE,EAAQ,OAAS,EAAI,CAAE,SAAQ,EAAI,CAAC,CAC1C,CAAC,EACD,IAAK,IAAMoB,KAAcH,EAAO,YAC1BG,EAAW,WAAa,WAC1B,KAAK,KAAKA,EAAW,QAAS,CAAE,KAAMA,EAAW,KAAM,OAAQA,EAAW,MAAO,CAAC,EAGtF,MAAO,CACL,KAAMH,EAAO,YAAcA,EAAO,KAAON,EACzC,IAAKM,EAAO,YAAcA,EAAO,IAAM,IACzC,CACF,OAASH,EAAO,CACd,GAAIA,aAAiBO,EACnB,OAAO,KAAK,MACVP,EAAM,QACNA,EAAM,WAAW,OAAS,EACtB,IAAA,GACA,CAAE,KAAMA,EAAM,WAAW,KAAM,OAAQA,EAAM,WAAW,MAAO,CACrE,EAEF,MAAMA,CACR,CACF,CACF,CACF,CAGA,SAASX,EAAiB,EAAyB,CACjD,OAAOmB,EAAQ,QAAUA,EAAQ,OAC7B,IAAI,OAAOA,EAAQ,OAAQA,EAAQ,MAAM,QAAQ,QAAS,EAAE,CAAC,EAC7DA,CACN,C"}
1
+ {"version":3,"file":"mdx.js","names":["isNode","value","dynamicSourceOf","moduleName","LOOKUP","DYNAMIC","elementsPlugin","rewritten","pending","tree","node","child","opening","\"openingElement\"","closing","\"closingElement\"","lookupName","\"name\"","tag","mode","identifier","\"attributes\"","\"body\"","dynamicSource","name","object","\"object\"","property","\"property\"","DEFAULT_INCLUDE","DEFAULT_EXCLUDE","loadMdx","loaded","specifier","cause","compileMdx","file","options","shadowMdx","plugins","validatePlugins","include","statelessPattern","exclude","dev","env","moduleFile","id","skip","mdx","jsx","mdxMap","output","code","MappingCollector","rawMapOf","error","found","position","result","compile","transformOptions","diagnostic","composeToSource","mapOfSource","CompileError","mappings","names","pattern"],"sources":["../../src/mdx.ts"],"sourcesContent":["import { CompileError, type CompilerPlugin, compile, validatePlugins } from \"@shadow-js/compiler\";\nimport type { Plugin } from \"vite\";\nimport { moduleFile } from \"./internal/ids\";\nimport {\n composeToSource,\n MappingCollector,\n mapOfSource,\n type RawMap,\n} from \"./internal/source-maps\";\n\n/**\n * `shadowMdx()`: a Vite plugin that turns `.mdx` (and `.md`) files into ShadowJS components. MDX is compiled to JSX by\n * `@mdx-js/mdx`, an optional peer, and the JSX goes through the ShadowJS compiler in the same step, so an MDX file needs no\n * other plugin to be compiled. The default export of a module is the component; the `export`s of the file (a `frontmatter`\n * from `remark-mdx-frontmatter`, a `meta` object) are named exports.\n * @packageDocumentation\n */\n\n/** The file `@mdx-js/mdx` answers: a `VFile`, whose `value` holds the code. */\ninterface MdxOutput {\n readonly value: string | Uint8Array;\n /** The source map of `value` to the MDX file, when the options carried a `SourceMapGenerator` that records one. */\n readonly map?: unknown;\n}\n\n/** What `compile` of `@mdx-js/mdx` accepts (the options this plugin sets, and the lists it hands on). */\ninterface MdxCompileOptions {\n readonly jsx: true;\n readonly jsxImportSource: string;\n readonly development: false;\n readonly format: \"mdx\" | \"md\";\n readonly remarkPlugins?: readonly unknown[];\n readonly rehypePlugins?: readonly unknown[];\n readonly recmaPlugins?: readonly unknown[];\n readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;\n readonly providerImportSource?: string;\n /** Asks for a source map from the JSX to the MDX file (`file.map` of the answer). */\n readonly SourceMapGenerator: typeof MappingCollector;\n}\n\n/** `compile` of `@mdx-js/mdx`, or a function with its shape. @since 1.0.0 */\nexport type MdxCompile = (\n file: { readonly value: string; readonly path: string },\n options: MdxCompileOptions,\n) => Promise<MdxOutput>;\n\n/** Options of {@link shadowMdx}. @since 1.0.0 */\nexport interface ShadowMdxOptions {\n /** Files to compile, matched against the module id without its query string. Default `/\\.mdx$/`. Add `.md` to read Markdown files too. */\n readonly include?: RegExp;\n /** Files to skip; checked first. Default: any path with a `node_modules` segment. */\n readonly exclude?: RegExp;\n /** Plugins of the Markdown syntax tree (`remark-frontmatter`, `remark-mdx-frontmatter`, `remark-gfm`, ...), as `@mdx-js/mdx` takes them. */\n readonly remarkPlugins?: readonly unknown[];\n /** Plugins of the HTML syntax tree (`rehype-slug`, `rehype-autolink-headings`, ...). */\n readonly rehypePlugins?: readonly unknown[];\n /** Plugins of the JavaScript syntax tree. They run before the plugin's own pass over the elements. */\n readonly recmaPlugins?: readonly unknown[];\n /**\n * How the elements of Markdown (`h1`, `p`, `a`, `code`, ...) are rendered.\n *\n * - `\"overridable\"`: each one is looked up in the `components` prop (and the provider), so an app can replace `a` or `h1`\n * for every page. Each looked-up element is rendered by `Dynamic`.\n * - `\"static\"`: each one is a plain element in the page's template, cloned in one call. The `components` prop still\n * supplies components the file names itself (`<Chart />`) and the `wrapper`, but cannot replace `h1` or `a`.\n *\n * Choose `\"static\"` for pages that never replace a Markdown element: documentation and blog posts render faster and ship\n * less code.\n * @default \"overridable\"\n */\n readonly elements?: \"overridable\" | \"static\";\n /** Options of `remark-rehype`. */\n readonly remarkRehypeOptions?: Readonly<Record<string, unknown>>;\n /**\n * A module that exports `useMDXComponents`, whose components every MDX file may use without a `components` prop (the\n * way `@mdx-js/react` works for React). Default: none; pass `components` to the file's component instead.\n */\n readonly providerImportSource?: string;\n /** `@mdx-js/mdx`, by module name, or your own `compile`. Default `\"@mdx-js/mdx\"`. */\n readonly mdx?: string | MdxCompile;\n /** Compiler plugins that run on the JSX of every MDX file (see `ShadowPluginOptions.plugins`). */\n readonly plugins?: readonly CompilerPlugin[];\n /**\n * Module the compiled code imports its runtime helpers from. Default `\"@shadow-js/web\"` (`\"@shadow-js/web/server\"` for SSR).\n * With `elements: \"overridable\"` the file also imports `Dynamic` from it, so a custom module must export `Dynamic`;\n * `\"@shadow-js/web/server\"` has none, so `Dynamic` is then imported from `\"@shadow-js/web\"`.\n */\n readonly moduleName?: string;\n}\n\n/** A node of the JavaScript syntax tree `@mdx-js/mdx` hands to recma plugins (ESTree with JSX), read structurally. */\ninterface EsNode {\n type: string;\n [key: string]: unknown;\n}\n\nfunction isNode(value: unknown): value is EsNode {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { type?: unknown }).type === \"string\"\n );\n}\n\n/**\n * The module `Dynamic` is imported from: the one `moduleName` names, so a project that points the runtime at\n * its own module (an alias, a re-export) does not need `@shadow-js/web` resolvable as well. The one exception\n * is the SSR helpers entry `@shadow-js/web/server`: it holds the server helpers and no `Dynamic`, which the\n * main entry provides (and Vite resolves to its server build in an SSR build).\n */\nfunction dynamicSourceOf(moduleName: string | undefined): string {\n if (moduleName === undefined || moduleName === \"@shadow-js/web/server\") return \"@shadow-js/web\";\n return moduleName;\n}\n\n/** The identifier `@mdx-js/mdx` binds the element lookup table to. */\nconst LOOKUP = \"_components\";\n/** The local name of `Dynamic`: it cannot clash with a name the file exports or imports. */\nconst DYNAMIC = \"_ShadowDynamic\";\n\n/**\n * Rewrites the elements `@mdx-js/mdx` looks up in its table (`<_components.h1>`): into plain `<h1>` for `\"static\"`, into\n * `<Dynamic component={_components.h1}>` for `\"overridable\"`. The lookup yields a string for a default element and a\n * function for an override, and a ShadowJS component tag must be a function.\n */\nfunction elementsPlugin(\n mode: \"overridable\" | \"static\",\n dynamicSource: string,\n): () => (tree: EsNode) => void {\n return () => (tree) => {\n let rewritten = 0;\n const pending: unknown[] = [tree];\n while (pending.length > 0) {\n const node = pending.pop();\n if (Array.isArray(node)) {\n for (const child of node) pending.push(child);\n continue;\n }\n if (!isNode(node)) continue;\n if (node.type === \"JSXElement\") {\n const opening = node[\"openingElement\"];\n const closing = node[\"closingElement\"];\n if (isNode(opening) && lookupName(opening[\"name\"]) !== undefined) {\n const tag = lookupName(opening[\"name\"]) as string;\n if (mode === \"static\") {\n opening[\"name\"] = identifier(tag);\n } else {\n opening[\"name\"] = identifier(DYNAMIC);\n const attributes = opening[\"attributes\"] as unknown[];\n attributes.unshift({\n type: \"JSXAttribute\",\n name: identifier(\"component\"),\n value: {\n type: \"JSXExpressionContainer\",\n expression: {\n type: \"MemberExpression\",\n object: { type: \"Identifier\", name: LOOKUP },\n property: { type: \"Identifier\", name: tag },\n computed: false,\n optional: false,\n },\n },\n });\n rewritten += 1;\n }\n if (isNode(closing)) closing[\"name\"] = identifier(mode === \"static\" ? tag : DYNAMIC);\n }\n }\n for (const value of Object.values(node)) {\n if (typeof value === \"object\" && value !== null) pending.push(value);\n }\n }\n if (rewritten > 0) {\n const body = tree[\"body\"] as unknown[];\n body.unshift({\n type: \"ImportDeclaration\",\n specifiers: [\n {\n type: \"ImportSpecifier\",\n imported: { type: \"Identifier\", name: \"Dynamic\" },\n local: { type: \"Identifier\", name: DYNAMIC },\n },\n ],\n source: { type: \"Literal\", value: dynamicSource, raw: JSON.stringify(dynamicSource) },\n attributes: [],\n });\n }\n };\n}\n\n/** The element name of `_components.name` as a JSX tag name, otherwise `undefined`. */\nfunction lookupName(name: unknown): string | undefined {\n if (!isNode(name) || name.type !== \"JSXMemberExpression\") return undefined;\n const object = name[\"object\"];\n const property = name[\"property\"];\n if (!isNode(object) || object.type !== \"JSXIdentifier\" || object[\"name\"] !== LOOKUP)\n return undefined;\n return isNode(property) && typeof property[\"name\"] === \"string\" ? property[\"name\"] : undefined;\n}\n\nfunction identifier(name: string): EsNode {\n return { type: \"JSXIdentifier\", name };\n}\n\nconst DEFAULT_INCLUDE = /\\.mdx$/;\nconst DEFAULT_EXCLUDE = /[\\\\/]node_modules[\\\\/]/;\n\n/** `@mdx-js/mdx` warns with a position; so do the errors of its parsers. */\ninterface Positioned {\n readonly message?: string;\n readonly line?: number | null;\n readonly column?: number | null;\n readonly reason?: string;\n}\n\nasync function loadMdx(specifier: string): Promise<MdxCompile> {\n let loaded: { compile?: unknown };\n try {\n loaded = (await import(specifier)) as { compile?: unknown };\n } catch (cause) {\n throw new Error(\n `shadowMdx: cannot load \"${specifier}\". Install it with \"npm install --save-dev ${specifier}\", or pass your own function as mdx.`,\n { cause },\n );\n }\n if (typeof loaded.compile !== \"function\") {\n throw new TypeError(`shadowMdx: the module \"${specifier}\" has no compile function.`);\n }\n const compileMdx = loaded.compile;\n return (file, options) =>\n Reflect.apply(compileMdx, undefined, [file, options]) as Promise<MdxOutput>;\n}\n\n/**\n * Creates the plugin that compiles MDX to ShadowJS components. It runs before Vite's own handling (`enforce: \"pre\"`), so Vite\n * never sees MDX or JSX. A file is compiled for the browser, or for the server in an SSR build; a syntax error in the MDX is\n * reported with its file, line and column. Hot updates reload the page: an MDX file has no component state worth keeping.\n *\n * @param options Which files, the remark, rehype and recma plugins, and the MDX compiler.\n * @returns A Vite plugin named `shadowjs-mdx`.\n * @throws TypeError when `include` or `exclude` is not a `RegExp`, or `plugins` is not a list of valid compiler plugins.\n * @example\n * // vite.config.ts\n * import { shadow } from \"@shadow-js/vite\";\n * import { shadowMdx } from \"@shadow-js/vite/mdx\";\n * import remarkFrontmatter from \"remark-frontmatter\";\n * import remarkMdxFrontmatter from \"remark-mdx-frontmatter\";\n *\n * export default {\n * plugins: [\n * shadowMdx({ remarkPlugins: [remarkFrontmatter, remarkMdxFrontmatter] }),\n * shadow(),\n * ],\n * };\n * @since 1.0.0\n */\nexport function shadowMdx(options: ShadowMdxOptions = {}): Plugin {\n for (const name of [\"include\", \"exclude\"] as const) {\n const value = options[name];\n if (value !== undefined && !(value instanceof RegExp)) {\n throw new TypeError(`shadowMdx(): \"${name}\" must be a RegExp (got ${typeof value}).`);\n }\n }\n const plugins =\n options.plugins === undefined ? [] : validatePlugins(options.plugins, \"shadowMdx(): plugins\");\n const include = statelessPattern(options.include ?? DEFAULT_INCLUDE);\n const exclude = statelessPattern(options.exclude ?? DEFAULT_EXCLUDE);\n let compileMdx: Promise<MdxCompile> | undefined;\n let dev = false;\n return {\n name: \"shadowjs-mdx\",\n enforce: \"pre\",\n config(_config, env) {\n dev = env.command === \"serve\";\n },\n async transform(code, id, transformOptions) {\n const { file, skip } = moduleFile(id);\n if (skip || exclude.test(file) || !include.test(file)) return null;\n compileMdx ??=\n typeof options.mdx === \"function\"\n ? Promise.resolve(options.mdx)\n : loadMdx(options.mdx ?? \"@mdx-js/mdx\");\n const mdx = await compileMdx;\n let jsx: string;\n let mdxMap: RawMap | undefined;\n try {\n const output = await mdx(\n { value: code, path: file },\n {\n jsx: true,\n jsxImportSource: options.moduleName ?? \"@shadow-js/web\",\n development: false,\n format: file.endsWith(\".mdx\") ? \"mdx\" : \"md\",\n ...(options.remarkPlugins === undefined\n ? {}\n : { remarkPlugins: options.remarkPlugins }),\n ...(options.rehypePlugins === undefined\n ? {}\n : { rehypePlugins: options.rehypePlugins }),\n recmaPlugins: [\n ...(options.recmaPlugins ?? []),\n elementsPlugin(\n options.elements ?? \"overridable\",\n dynamicSourceOf(options.moduleName),\n ),\n ],\n ...(options.remarkRehypeOptions === undefined\n ? {}\n : { remarkRehypeOptions: options.remarkRehypeOptions }),\n ...(options.providerImportSource === undefined\n ? {}\n : { providerImportSource: options.providerImportSource }),\n SourceMapGenerator: MappingCollector,\n },\n );\n jsx =\n typeof output.value === \"string\"\n ? output.value\n : Buffer.from(output.value).toString(\"utf8\");\n mdxMap = rawMapOf(output.map);\n } catch (error) {\n const found = error as Positioned;\n const position =\n typeof found.line === \"number\" && found.line > 0\n ? { line: found.line, column: Math.max((found.column ?? 1) - 1, 0) }\n : undefined;\n return this.error(found.reason ?? found.message ?? String(error), position);\n }\n try {\n const result = compile(jsx, {\n filename: `${file}.tsx`,\n generate: transformOptions?.ssr === true ? \"ssr\" : \"dom\",\n dev,\n autoReactive: true,\n hmr: false,\n ...(options.moduleName === undefined ? {} : { moduleName: options.moduleName }),\n ...(plugins.length > 0 ? { plugins } : {}),\n });\n // The positions of the JSX pass are those of the JSX that `@mdx-js/mdx` wrote, not of the MDX file the build\n // names: passed on, they would point at lines and columns of the generated code (the message carries them).\n for (const diagnostic of result.diagnostics) {\n if (diagnostic.severity === \"warning\") this.warn(diagnostic.message);\n }\n // Without JSX to compile the code is what `@mdx-js/mdx` wrote, and its own map already points at the file.\n if (!result.transformed) {\n return { code: jsx, map: mdxMap === undefined ? null : mapOfSource(mdxMap, file, code) };\n }\n // A map from the final code to the JSX is of no use to a debugger: compose it with the one from the JSX\n // to the MDX file. When `@mdx-js/mdx` (or a replacement given as `mdx`) answered no map, it stays as it was.\n return {\n code: result.code,\n map:\n result.map === null || mdxMap === undefined\n ? result.map\n : composeToSource(result.map, mdxMap, file, code),\n };\n } catch (error) {\n if (error instanceof CompileError) return this.error(error.message);\n throw error;\n }\n },\n };\n}\n\n/** Reads the map `@mdx-js/mdx` answers with, or `undefined` when it gave none that can be used. */\nfunction rawMapOf(value: unknown): RawMap | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n const { mappings, names } = value as { mappings?: unknown; names?: unknown };\n if (typeof mappings !== \"string\") return undefined;\n return {\n mappings,\n names: Array.isArray(names)\n ? names.filter((name): name is string => typeof name === \"string\")\n : [],\n };\n}\n\n/** The same pattern without the `g` and `y` flags, so `test()` does not remember where the last call ended. */\nfunction statelessPattern(pattern: RegExp): RegExp {\n return pattern.global || pattern.sticky\n ? new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, \"\"))\n : pattern;\n}\n"],"mappings":"A,uOAgGA,SAASA,EAAO,EAAiC,CAC/C,OACE,OAAOC,GAAU,YACjBA,GACA,OAAQA,EAA6B,MAAS,QAElD,CAQA,SAASC,EAAgB,EAAwC,CAE/D,OADIC,IAAe,IAAA,IAAaA,IAAe,wBAA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,OAAO3C,GAAS,QAAQ,EAC/D,CAAC,CACP,CACF,CAGA,SAASkB,EAAiB,EAAyB,CACjD,OAAO0B,EAAQ,QAAUA,EAAQ,OAC7B,IAAI,OAAOA,EAAQ,OAAQA,EAAQ,MAAM,QAAQ,QAAS,EAAE,CAAC,EAC7DA,CACN,C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shadow-js/vite",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "A Vite plugin that compiles your JSX, builds for server rendering and sets up Vitest",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -38,12 +38,12 @@
38
38
  "typecheck": "tsc -p tsconfig.json"
39
39
  },
40
40
  "dependencies": {
41
- "@shadow-js/compiler": "1.0.4"
41
+ "@shadow-js/compiler": "1.0.5"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "vite": "^7.0.0 || ^8.0.0",
45
45
  "@mdx-js/mdx": "^3.0.0",
46
- "@shadow-js/web": "^1.0.4"
46
+ "@shadow-js/web": "^1.0.5"
47
47
  },
48
48
  "peerDependenciesMeta": {
49
49
  "vite": {
@@ -64,7 +64,7 @@
64
64
  "@types/node": "^24.0.0",
65
65
  "esbuild": "0.27.0",
66
66
  "fast-check": "^4.10.2",
67
- "happy-dom": "^21.0.3",
67
+ "happy-dom": "21.0.4",
68
68
  "remark-frontmatter": "5.0.0",
69
69
  "remark-gfm": "4.0.1",
70
70
  "remark-mdx-frontmatter": "6.0.0",