@mralfarrakhan/svork 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,2494 @@
1
+ import { parse } from "svelte/compiler";
2
+ import minpath from "node:path";
3
+ import minproc from "node:process";
4
+ import { fileURLToPath as urlToPath } from "node:url";
5
+ import remarkParse from "remark-parse";
6
+ import remarkRehype from "remark-rehype";
7
+ import rehypeRaw from "rehype-raw";
8
+ import rehypeStringify from "rehype-stringify";
9
+ import yaml from "js-yaml";
10
+ //#region \0rolldown/runtime.js
11
+ var __create = Object.create;
12
+ var __defProp = Object.defineProperty;
13
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
+ var __getOwnPropNames = Object.getOwnPropertyNames;
15
+ var __getProtoOf = Object.getPrototypeOf;
16
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
17
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
20
+ key = keys[i];
21
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
22
+ get: ((k) => from[k]).bind(null, key),
23
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
24
+ });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
29
+ value: mod,
30
+ enumerable: true
31
+ }) : target, mod));
32
+ //#endregion
33
+ //#region node_modules/bail/index.js
34
+ /**
35
+ * Throw a given error.
36
+ *
37
+ * @param {Error|null|undefined} [error]
38
+ * Maybe error.
39
+ * @returns {asserts error is null|undefined}
40
+ */
41
+ function bail(error) {
42
+ if (error) throw error;
43
+ }
44
+ //#endregion
45
+ //#region node_modules/extend/index.js
46
+ var require_extend = /* @__PURE__ */ __commonJSMin(((exports, module) => {
47
+ var hasOwn = Object.prototype.hasOwnProperty;
48
+ var toStr = Object.prototype.toString;
49
+ var defineProperty = Object.defineProperty;
50
+ var gOPD = Object.getOwnPropertyDescriptor;
51
+ var isArray = function isArray(arr) {
52
+ if (typeof Array.isArray === "function") return Array.isArray(arr);
53
+ return toStr.call(arr) === "[object Array]";
54
+ };
55
+ var isPlainObject = function isPlainObject(obj) {
56
+ if (!obj || toStr.call(obj) !== "[object Object]") return false;
57
+ var hasOwnConstructor = hasOwn.call(obj, "constructor");
58
+ var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, "isPrototypeOf");
59
+ if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) return false;
60
+ var key;
61
+ for (key in obj);
62
+ return typeof key === "undefined" || hasOwn.call(obj, key);
63
+ };
64
+ var setProperty = function setProperty(target, options) {
65
+ if (defineProperty && options.name === "__proto__") defineProperty(target, options.name, {
66
+ enumerable: true,
67
+ configurable: true,
68
+ value: options.newValue,
69
+ writable: true
70
+ });
71
+ else target[options.name] = options.newValue;
72
+ };
73
+ var getProperty = function getProperty(obj, name) {
74
+ if (name === "__proto__") {
75
+ if (!hasOwn.call(obj, name)) return;
76
+ else if (gOPD) return gOPD(obj, name).value;
77
+ }
78
+ return obj[name];
79
+ };
80
+ module.exports = function extend() {
81
+ var options, name, src, copy, copyIsArray, clone;
82
+ var target = arguments[0];
83
+ var i = 1;
84
+ var length = arguments.length;
85
+ var deep = false;
86
+ if (typeof target === "boolean") {
87
+ deep = target;
88
+ target = arguments[1] || {};
89
+ i = 2;
90
+ }
91
+ if (target == null || typeof target !== "object" && typeof target !== "function") target = {};
92
+ for (; i < length; ++i) {
93
+ options = arguments[i];
94
+ if (options != null) for (name in options) {
95
+ src = getProperty(target, name);
96
+ copy = getProperty(options, name);
97
+ if (target !== copy) {
98
+ if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
99
+ if (copyIsArray) {
100
+ copyIsArray = false;
101
+ clone = src && isArray(src) ? src : [];
102
+ } else clone = src && isPlainObject(src) ? src : {};
103
+ setProperty(target, {
104
+ name,
105
+ newValue: extend(deep, clone, copy)
106
+ });
107
+ } else if (typeof copy !== "undefined") setProperty(target, {
108
+ name,
109
+ newValue: copy
110
+ });
111
+ }
112
+ }
113
+ }
114
+ return target;
115
+ };
116
+ }));
117
+ //#endregion
118
+ //#region node_modules/is-plain-obj/index.js
119
+ function isPlainObject(value) {
120
+ if (typeof value !== "object" || value === null) return false;
121
+ const prototype = Object.getPrototypeOf(value);
122
+ return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
123
+ }
124
+ //#endregion
125
+ //#region node_modules/trough/lib/index.js
126
+ /**
127
+ * @typedef {(error?: Error | null | undefined, ...output: Array<any>) => void} Callback
128
+ * Callback.
129
+ *
130
+ * @typedef {(...input: Array<any>) => any} Middleware
131
+ * Ware.
132
+ *
133
+ * @typedef Pipeline
134
+ * Pipeline.
135
+ * @property {Run} run
136
+ * Run the pipeline.
137
+ * @property {Use} use
138
+ * Add middleware.
139
+ *
140
+ * @typedef {(...input: Array<any>) => void} Run
141
+ * Call all middleware.
142
+ *
143
+ * Calls `done` on completion with either an error or the output of the
144
+ * last middleware.
145
+ *
146
+ * > 👉 **Note**: as the length of input defines whether async functions get a
147
+ * > `next` function,
148
+ * > it’s recommended to keep `input` at one value normally.
149
+
150
+ *
151
+ * @typedef {(fn: Middleware) => Pipeline} Use
152
+ * Add middleware.
153
+ */
154
+ /**
155
+ * Create new middleware.
156
+ *
157
+ * @returns {Pipeline}
158
+ * Pipeline.
159
+ */
160
+ function trough() {
161
+ /** @type {Array<Middleware>} */
162
+ const fns = [];
163
+ /** @type {Pipeline} */
164
+ const pipeline = {
165
+ run,
166
+ use
167
+ };
168
+ return pipeline;
169
+ /** @type {Run} */
170
+ function run(...values) {
171
+ let middlewareIndex = -1;
172
+ /** @type {Callback} */
173
+ const callback = values.pop();
174
+ if (typeof callback !== "function") throw new TypeError("Expected function as last argument, not " + callback);
175
+ next(null, ...values);
176
+ /**
177
+ * Run the next `fn`, or we’re done.
178
+ *
179
+ * @param {Error | null | undefined} error
180
+ * @param {Array<any>} output
181
+ */
182
+ function next(error, ...output) {
183
+ const fn = fns[++middlewareIndex];
184
+ let index = -1;
185
+ if (error) {
186
+ callback(error);
187
+ return;
188
+ }
189
+ while (++index < values.length) if (output[index] === null || output[index] === void 0) output[index] = values[index];
190
+ values = output;
191
+ if (fn) wrap(fn, next)(...output);
192
+ else callback(null, ...output);
193
+ }
194
+ }
195
+ /** @type {Use} */
196
+ function use(middelware) {
197
+ if (typeof middelware !== "function") throw new TypeError("Expected `middelware` to be a function, not " + middelware);
198
+ fns.push(middelware);
199
+ return pipeline;
200
+ }
201
+ }
202
+ /**
203
+ * Wrap `middleware` into a uniform interface.
204
+ *
205
+ * You can pass all input to the resulting function.
206
+ * `callback` is then called with the output of `middleware`.
207
+ *
208
+ * If `middleware` accepts more arguments than the later given in input,
209
+ * an extra `done` function is passed to it after that input,
210
+ * which must be called by `middleware`.
211
+ *
212
+ * The first value in `input` is the main input value.
213
+ * All other input values are the rest input values.
214
+ * The values given to `callback` are the input values,
215
+ * merged with every non-nullish output value.
216
+ *
217
+ * * if `middleware` throws an error,
218
+ * returns a promise that is rejected,
219
+ * or calls the given `done` function with an error,
220
+ * `callback` is called with that error
221
+ * * if `middleware` returns a value or returns a promise that is resolved,
222
+ * that value is the main output value
223
+ * * if `middleware` calls `done`,
224
+ * all non-nullish values except for the first one (the error) overwrite the
225
+ * output values
226
+ *
227
+ * @param {Middleware} middleware
228
+ * Function to wrap.
229
+ * @param {Callback} callback
230
+ * Callback called with the output of `middleware`.
231
+ * @returns {Run}
232
+ * Wrapped middleware.
233
+ */
234
+ function wrap(middleware, callback) {
235
+ /** @type {boolean} */
236
+ let called;
237
+ return wrapped;
238
+ /**
239
+ * Call `middleware`.
240
+ * @this {any}
241
+ * @param {Array<any>} parameters
242
+ * @returns {void}
243
+ */
244
+ function wrapped(...parameters) {
245
+ const fnExpectsCallback = middleware.length > parameters.length;
246
+ /** @type {any} */
247
+ let result;
248
+ if (fnExpectsCallback) parameters.push(done);
249
+ try {
250
+ result = middleware.apply(this, parameters);
251
+ } catch (error) {
252
+ const exception = error;
253
+ if (fnExpectsCallback && called) throw exception;
254
+ return done(exception);
255
+ }
256
+ if (!fnExpectsCallback) if (result && result.then && typeof result.then === "function") result.then(then, done);
257
+ else if (result instanceof Error) done(result);
258
+ else then(result);
259
+ }
260
+ /**
261
+ * Call `callback`, only once.
262
+ *
263
+ * @type {Callback}
264
+ */
265
+ function done(error, ...output) {
266
+ if (!called) {
267
+ called = true;
268
+ callback(error, ...output);
269
+ }
270
+ }
271
+ /**
272
+ * Call `done` with one value.
273
+ *
274
+ * @param {any} [value]
275
+ */
276
+ function then(value) {
277
+ done(null, value);
278
+ }
279
+ }
280
+ //#endregion
281
+ //#region node_modules/unist-util-stringify-position/lib/index.js
282
+ /**
283
+ * @typedef {import('unist').Node} Node
284
+ * @typedef {import('unist').Point} Point
285
+ * @typedef {import('unist').Position} Position
286
+ */
287
+ /**
288
+ * @typedef NodeLike
289
+ * @property {string} type
290
+ * @property {PositionLike | null | undefined} [position]
291
+ *
292
+ * @typedef PointLike
293
+ * @property {number | null | undefined} [line]
294
+ * @property {number | null | undefined} [column]
295
+ * @property {number | null | undefined} [offset]
296
+ *
297
+ * @typedef PositionLike
298
+ * @property {PointLike | null | undefined} [start]
299
+ * @property {PointLike | null | undefined} [end]
300
+ */
301
+ /**
302
+ * Serialize the positional info of a point, position (start and end points),
303
+ * or node.
304
+ *
305
+ * @param {Node | NodeLike | Point | PointLike | Position | PositionLike | null | undefined} [value]
306
+ * Node, position, or point.
307
+ * @returns {string}
308
+ * Pretty printed positional info of a node (`string`).
309
+ *
310
+ * In the format of a range `ls:cs-le:ce` (when given `node` or `position`)
311
+ * or a point `l:c` (when given `point`), where `l` stands for line, `c` for
312
+ * column, `s` for `start`, and `e` for end.
313
+ * An empty string (`''`) is returned if the given value is neither `node`,
314
+ * `position`, nor `point`.
315
+ */
316
+ function stringifyPosition(value) {
317
+ if (!value || typeof value !== "object") return "";
318
+ if ("position" in value || "type" in value) return position(value.position);
319
+ if ("start" in value || "end" in value) return position(value);
320
+ if ("line" in value || "column" in value) return point(value);
321
+ return "";
322
+ }
323
+ /**
324
+ * @param {Point | PointLike | null | undefined} point
325
+ * @returns {string}
326
+ */
327
+ function point(point) {
328
+ return index(point && point.line) + ":" + index(point && point.column);
329
+ }
330
+ /**
331
+ * @param {Position | PositionLike | null | undefined} pos
332
+ * @returns {string}
333
+ */
334
+ function position(pos) {
335
+ return point(pos && pos.start) + "-" + point(pos && pos.end);
336
+ }
337
+ /**
338
+ * @param {number | null | undefined} value
339
+ * @returns {number}
340
+ */
341
+ function index(value) {
342
+ return value && typeof value === "number" ? value : 1;
343
+ }
344
+ //#endregion
345
+ //#region node_modules/vfile-message/lib/index.js
346
+ /**
347
+ * @import {Node, Point, Position} from 'unist'
348
+ */
349
+ /**
350
+ * @typedef {object & {type: string, position?: Position | undefined}} NodeLike
351
+ *
352
+ * @typedef Options
353
+ * Configuration.
354
+ * @property {Array<Node> | null | undefined} [ancestors]
355
+ * Stack of (inclusive) ancestor nodes surrounding the message (optional).
356
+ * @property {Error | null | undefined} [cause]
357
+ * Original error cause of the message (optional).
358
+ * @property {Point | Position | null | undefined} [place]
359
+ * Place of message (optional).
360
+ * @property {string | null | undefined} [ruleId]
361
+ * Category of message (optional, example: `'my-rule'`).
362
+ * @property {string | null | undefined} [source]
363
+ * Namespace of who sent the message (optional, example: `'my-package'`).
364
+ */
365
+ /**
366
+ * Message.
367
+ */
368
+ var VFileMessage = class extends Error {
369
+ /**
370
+ * Create a message for `reason`.
371
+ *
372
+ * > 🪦 **Note**: also has obsolete signatures.
373
+ *
374
+ * @overload
375
+ * @param {string} reason
376
+ * @param {Options | null | undefined} [options]
377
+ * @returns
378
+ *
379
+ * @overload
380
+ * @param {string} reason
381
+ * @param {Node | NodeLike | null | undefined} parent
382
+ * @param {string | null | undefined} [origin]
383
+ * @returns
384
+ *
385
+ * @overload
386
+ * @param {string} reason
387
+ * @param {Point | Position | null | undefined} place
388
+ * @param {string | null | undefined} [origin]
389
+ * @returns
390
+ *
391
+ * @overload
392
+ * @param {string} reason
393
+ * @param {string | null | undefined} [origin]
394
+ * @returns
395
+ *
396
+ * @overload
397
+ * @param {Error | VFileMessage} cause
398
+ * @param {Node | NodeLike | null | undefined} parent
399
+ * @param {string | null | undefined} [origin]
400
+ * @returns
401
+ *
402
+ * @overload
403
+ * @param {Error | VFileMessage} cause
404
+ * @param {Point | Position | null | undefined} place
405
+ * @param {string | null | undefined} [origin]
406
+ * @returns
407
+ *
408
+ * @overload
409
+ * @param {Error | VFileMessage} cause
410
+ * @param {string | null | undefined} [origin]
411
+ * @returns
412
+ *
413
+ * @param {Error | VFileMessage | string} causeOrReason
414
+ * Reason for message, should use markdown.
415
+ * @param {Node | NodeLike | Options | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
416
+ * Configuration (optional).
417
+ * @param {string | null | undefined} [origin]
418
+ * Place in code where the message originates (example:
419
+ * `'my-package:my-rule'` or `'my-rule'`).
420
+ * @returns
421
+ * Instance of `VFileMessage`.
422
+ */
423
+ constructor(causeOrReason, optionsOrParentOrPlace, origin) {
424
+ super();
425
+ if (typeof optionsOrParentOrPlace === "string") {
426
+ origin = optionsOrParentOrPlace;
427
+ optionsOrParentOrPlace = void 0;
428
+ }
429
+ /** @type {string} */
430
+ let reason = "";
431
+ /** @type {Options} */
432
+ let options = {};
433
+ let legacyCause = false;
434
+ if (optionsOrParentOrPlace) if ("line" in optionsOrParentOrPlace && "column" in optionsOrParentOrPlace) options = { place: optionsOrParentOrPlace };
435
+ else if ("start" in optionsOrParentOrPlace && "end" in optionsOrParentOrPlace) options = { place: optionsOrParentOrPlace };
436
+ else if ("type" in optionsOrParentOrPlace) options = {
437
+ ancestors: [optionsOrParentOrPlace],
438
+ place: optionsOrParentOrPlace.position
439
+ };
440
+ else options = { ...optionsOrParentOrPlace };
441
+ if (typeof causeOrReason === "string") reason = causeOrReason;
442
+ else if (!options.cause && causeOrReason) {
443
+ legacyCause = true;
444
+ reason = causeOrReason.message;
445
+ options.cause = causeOrReason;
446
+ }
447
+ if (!options.ruleId && !options.source && typeof origin === "string") {
448
+ const index = origin.indexOf(":");
449
+ if (index === -1) options.ruleId = origin;
450
+ else {
451
+ options.source = origin.slice(0, index);
452
+ options.ruleId = origin.slice(index + 1);
453
+ }
454
+ }
455
+ if (!options.place && options.ancestors && options.ancestors) {
456
+ const parent = options.ancestors[options.ancestors.length - 1];
457
+ if (parent) options.place = parent.position;
458
+ }
459
+ const start = options.place && "start" in options.place ? options.place.start : options.place;
460
+ /**
461
+ * Stack of ancestor nodes surrounding the message.
462
+ *
463
+ * @type {Array<Node> | undefined}
464
+ */
465
+ this.ancestors = options.ancestors || void 0;
466
+ /**
467
+ * Original error cause of the message.
468
+ *
469
+ * @type {Error | undefined}
470
+ */
471
+ this.cause = options.cause || void 0;
472
+ /**
473
+ * Starting column of message.
474
+ *
475
+ * @type {number | undefined}
476
+ */
477
+ this.column = start ? start.column : void 0;
478
+ /**
479
+ * State of problem.
480
+ *
481
+ * * `true` — error, file not usable
482
+ * * `false` — warning, change may be needed
483
+ * * `undefined` — change likely not needed
484
+ *
485
+ * @type {boolean | null | undefined}
486
+ */
487
+ this.fatal = void 0;
488
+ /**
489
+ * Path of a file (used throughout the `VFile` ecosystem).
490
+ *
491
+ * @type {string | undefined}
492
+ */
493
+ this.file = "";
494
+ /**
495
+ * Reason for message.
496
+ *
497
+ * @type {string}
498
+ */
499
+ this.message = reason;
500
+ /**
501
+ * Starting line of error.
502
+ *
503
+ * @type {number | undefined}
504
+ */
505
+ this.line = start ? start.line : void 0;
506
+ /**
507
+ * Serialized positional info of message.
508
+ *
509
+ * On normal errors, this would be something like `ParseError`, buit in
510
+ * `VFile` messages we use this space to show where an error happened.
511
+ */
512
+ this.name = stringifyPosition(options.place) || "1:1";
513
+ /**
514
+ * Place of message.
515
+ *
516
+ * @type {Point | Position | undefined}
517
+ */
518
+ this.place = options.place || void 0;
519
+ /**
520
+ * Reason for message, should use markdown.
521
+ *
522
+ * @type {string}
523
+ */
524
+ this.reason = this.message;
525
+ /**
526
+ * Category of message (example: `'my-rule'`).
527
+ *
528
+ * @type {string | undefined}
529
+ */
530
+ this.ruleId = options.ruleId || void 0;
531
+ /**
532
+ * Namespace of message (example: `'my-package'`).
533
+ *
534
+ * @type {string | undefined}
535
+ */
536
+ this.source = options.source || void 0;
537
+ /**
538
+ * Stack of message.
539
+ *
540
+ * This is used by normal errors to show where something happened in
541
+ * programming code, irrelevant for `VFile` messages,
542
+ *
543
+ * @type {string}
544
+ */
545
+ this.stack = legacyCause && options.cause && typeof options.cause.stack === "string" ? options.cause.stack : "";
546
+ /**
547
+ * Specify the source value that’s being reported, which is deemed
548
+ * incorrect.
549
+ *
550
+ * @type {string | undefined}
551
+ */
552
+ this.actual = void 0;
553
+ /**
554
+ * Suggest acceptable values that can be used instead of `actual`.
555
+ *
556
+ * @type {Array<string> | undefined}
557
+ */
558
+ this.expected = void 0;
559
+ /**
560
+ * Long form description of the message (you should use markdown).
561
+ *
562
+ * @type {string | undefined}
563
+ */
564
+ this.note = void 0;
565
+ /**
566
+ * Link to docs for the message.
567
+ *
568
+ * > 👉 **Note**: this must be an absolute URL that can be passed as `x`
569
+ * > to `new URL(x)`.
570
+ *
571
+ * @type {string | undefined}
572
+ */
573
+ this.url = void 0;
574
+ }
575
+ };
576
+ VFileMessage.prototype.file = "";
577
+ VFileMessage.prototype.name = "";
578
+ VFileMessage.prototype.reason = "";
579
+ VFileMessage.prototype.message = "";
580
+ VFileMessage.prototype.stack = "";
581
+ VFileMessage.prototype.column = void 0;
582
+ VFileMessage.prototype.line = void 0;
583
+ VFileMessage.prototype.ancestors = void 0;
584
+ VFileMessage.prototype.cause = void 0;
585
+ VFileMessage.prototype.fatal = void 0;
586
+ VFileMessage.prototype.place = void 0;
587
+ VFileMessage.prototype.ruleId = void 0;
588
+ VFileMessage.prototype.source = void 0;
589
+ //#endregion
590
+ //#region node_modules/vfile/lib/minurl.shared.js
591
+ /**
592
+ * Checks if a value has the shape of a WHATWG URL object.
593
+ *
594
+ * Using a symbol or instanceof would not be able to recognize URL objects
595
+ * coming from other implementations (e.g. in Electron), so instead we are
596
+ * checking some well known properties for a lack of a better test.
597
+ *
598
+ * We use `href` and `protocol` as they are the only properties that are
599
+ * easy to retrieve and calculate due to the lazy nature of the getters.
600
+ *
601
+ * We check for auth attribute to distinguish legacy url instance with
602
+ * WHATWG URL instance.
603
+ *
604
+ * @param {unknown} fileUrlOrPath
605
+ * File path or URL.
606
+ * @returns {fileUrlOrPath is URL}
607
+ * Whether it’s a URL.
608
+ */
609
+ function isUrl(fileUrlOrPath) {
610
+ return Boolean(fileUrlOrPath !== null && typeof fileUrlOrPath === "object" && "href" in fileUrlOrPath && fileUrlOrPath.href && "protocol" in fileUrlOrPath && fileUrlOrPath.protocol && fileUrlOrPath.auth === void 0);
611
+ }
612
+ //#endregion
613
+ //#region node_modules/vfile/lib/index.js
614
+ /**
615
+ * @import {Node, Point, Position} from 'unist'
616
+ * @import {Options as MessageOptions} from 'vfile-message'
617
+ * @import {Compatible, Data, Map, Options, Value} from 'vfile'
618
+ */
619
+ /**
620
+ * @typedef {object & {type: string, position?: Position | undefined}} NodeLike
621
+ */
622
+ /**
623
+ * Order of setting (least specific to most), we need this because otherwise
624
+ * `{stem: 'a', path: '~/b.js'}` would throw, as a path is needed before a
625
+ * stem can be set.
626
+ */
627
+ const order = [
628
+ "history",
629
+ "path",
630
+ "basename",
631
+ "stem",
632
+ "extname",
633
+ "dirname"
634
+ ];
635
+ var VFile = class {
636
+ /**
637
+ * Create a new virtual file.
638
+ *
639
+ * `options` is treated as:
640
+ *
641
+ * * `string` or `Uint8Array` — `{value: options}`
642
+ * * `URL` — `{path: options}`
643
+ * * `VFile` — shallow copies its data over to the new file
644
+ * * `object` — all fields are shallow copied over to the new file
645
+ *
646
+ * Path related fields are set in the following order (least specific to
647
+ * most specific): `history`, `path`, `basename`, `stem`, `extname`,
648
+ * `dirname`.
649
+ *
650
+ * You cannot set `dirname` or `extname` without setting either `history`,
651
+ * `path`, `basename`, or `stem` too.
652
+ *
653
+ * @param {Compatible | null | undefined} [value]
654
+ * File value.
655
+ * @returns
656
+ * New instance.
657
+ */
658
+ constructor(value) {
659
+ /** @type {Options | VFile} */
660
+ let options;
661
+ if (!value) options = {};
662
+ else if (isUrl(value)) options = { path: value };
663
+ else if (typeof value === "string" || isUint8Array$1(value)) options = { value };
664
+ else options = value;
665
+ /**
666
+ * Base of `path` (default: `process.cwd()` or `'/'` in browsers).
667
+ *
668
+ * @type {string}
669
+ */
670
+ this.cwd = "cwd" in options ? "" : minproc.cwd();
671
+ /**
672
+ * Place to store custom info (default: `{}`).
673
+ *
674
+ * It’s OK to store custom data directly on the file but moving it to
675
+ * `data` is recommended.
676
+ *
677
+ * @type {Data}
678
+ */
679
+ this.data = {};
680
+ /**
681
+ * List of file paths the file moved between.
682
+ *
683
+ * The first is the original path and the last is the current path.
684
+ *
685
+ * @type {Array<string>}
686
+ */
687
+ this.history = [];
688
+ /**
689
+ * List of messages associated with the file.
690
+ *
691
+ * @type {Array<VFileMessage>}
692
+ */
693
+ this.messages = [];
694
+ /**
695
+ * Raw value.
696
+ *
697
+ * @type {Value}
698
+ */
699
+ this.value;
700
+ /**
701
+ * Source map.
702
+ *
703
+ * This type is equivalent to the `RawSourceMap` type from the `source-map`
704
+ * module.
705
+ *
706
+ * @type {Map | null | undefined}
707
+ */
708
+ this.map;
709
+ /**
710
+ * Custom, non-string, compiled, representation.
711
+ *
712
+ * This is used by unified to store non-string results.
713
+ * One example is when turning markdown into React nodes.
714
+ *
715
+ * @type {unknown}
716
+ */
717
+ this.result;
718
+ /**
719
+ * Whether a file was saved to disk.
720
+ *
721
+ * This is used by vfile reporters.
722
+ *
723
+ * @type {boolean}
724
+ */
725
+ this.stored;
726
+ let index = -1;
727
+ while (++index < order.length) {
728
+ const field = order[index];
729
+ if (field in options && options[field] !== void 0 && options[field] !== null) this[field] = field === "history" ? [...options[field]] : options[field];
730
+ }
731
+ /** @type {string} */
732
+ let field;
733
+ for (field in options) if (!order.includes(field)) this[field] = options[field];
734
+ }
735
+ /**
736
+ * Get the basename (including extname) (example: `'index.min.js'`).
737
+ *
738
+ * @returns {string | undefined}
739
+ * Basename.
740
+ */
741
+ get basename() {
742
+ return typeof this.path === "string" ? minpath.basename(this.path) : void 0;
743
+ }
744
+ /**
745
+ * Set basename (including extname) (`'index.min.js'`).
746
+ *
747
+ * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
748
+ * on windows).
749
+ * Cannot be nullified (use `file.path = file.dirname` instead).
750
+ *
751
+ * @param {string} basename
752
+ * Basename.
753
+ * @returns {undefined}
754
+ * Nothing.
755
+ */
756
+ set basename(basename) {
757
+ assertNonEmpty(basename, "basename");
758
+ assertPart(basename, "basename");
759
+ this.path = minpath.join(this.dirname || "", basename);
760
+ }
761
+ /**
762
+ * Get the parent path (example: `'~'`).
763
+ *
764
+ * @returns {string | undefined}
765
+ * Dirname.
766
+ */
767
+ get dirname() {
768
+ return typeof this.path === "string" ? minpath.dirname(this.path) : void 0;
769
+ }
770
+ /**
771
+ * Set the parent path (example: `'~'`).
772
+ *
773
+ * Cannot be set if there’s no `path` yet.
774
+ *
775
+ * @param {string | undefined} dirname
776
+ * Dirname.
777
+ * @returns {undefined}
778
+ * Nothing.
779
+ */
780
+ set dirname(dirname) {
781
+ assertPath(this.basename, "dirname");
782
+ this.path = minpath.join(dirname || "", this.basename);
783
+ }
784
+ /**
785
+ * Get the extname (including dot) (example: `'.js'`).
786
+ *
787
+ * @returns {string | undefined}
788
+ * Extname.
789
+ */
790
+ get extname() {
791
+ return typeof this.path === "string" ? minpath.extname(this.path) : void 0;
792
+ }
793
+ /**
794
+ * Set the extname (including dot) (example: `'.js'`).
795
+ *
796
+ * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
797
+ * on windows).
798
+ * Cannot be set if there’s no `path` yet.
799
+ *
800
+ * @param {string | undefined} extname
801
+ * Extname.
802
+ * @returns {undefined}
803
+ * Nothing.
804
+ */
805
+ set extname(extname) {
806
+ assertPart(extname, "extname");
807
+ assertPath(this.dirname, "extname");
808
+ if (extname) {
809
+ if (extname.codePointAt(0) !== 46) throw new Error("`extname` must start with `.`");
810
+ if (extname.includes(".", 1)) throw new Error("`extname` cannot contain multiple dots");
811
+ }
812
+ this.path = minpath.join(this.dirname, this.stem + (extname || ""));
813
+ }
814
+ /**
815
+ * Get the full path (example: `'~/index.min.js'`).
816
+ *
817
+ * @returns {string}
818
+ * Path.
819
+ */
820
+ get path() {
821
+ return this.history[this.history.length - 1];
822
+ }
823
+ /**
824
+ * Set the full path (example: `'~/index.min.js'`).
825
+ *
826
+ * Cannot be nullified.
827
+ * You can set a file URL (a `URL` object with a `file:` protocol) which will
828
+ * be turned into a path with `url.fileURLToPath`.
829
+ *
830
+ * @param {URL | string} path
831
+ * Path.
832
+ * @returns {undefined}
833
+ * Nothing.
834
+ */
835
+ set path(path) {
836
+ if (isUrl(path)) path = urlToPath(path);
837
+ assertNonEmpty(path, "path");
838
+ if (this.path !== path) this.history.push(path);
839
+ }
840
+ /**
841
+ * Get the stem (basename w/o extname) (example: `'index.min'`).
842
+ *
843
+ * @returns {string | undefined}
844
+ * Stem.
845
+ */
846
+ get stem() {
847
+ return typeof this.path === "string" ? minpath.basename(this.path, this.extname) : void 0;
848
+ }
849
+ /**
850
+ * Set the stem (basename w/o extname) (example: `'index.min'`).
851
+ *
852
+ * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
853
+ * on windows).
854
+ * Cannot be nullified (use `file.path = file.dirname` instead).
855
+ *
856
+ * @param {string} stem
857
+ * Stem.
858
+ * @returns {undefined}
859
+ * Nothing.
860
+ */
861
+ set stem(stem) {
862
+ assertNonEmpty(stem, "stem");
863
+ assertPart(stem, "stem");
864
+ this.path = minpath.join(this.dirname || "", stem + (this.extname || ""));
865
+ }
866
+ /**
867
+ * Create a fatal message for `reason` associated with the file.
868
+ *
869
+ * The `fatal` field of the message is set to `true` (error; file not usable)
870
+ * and the `file` field is set to the current file path.
871
+ * The message is added to the `messages` field on `file`.
872
+ *
873
+ * > 🪦 **Note**: also has obsolete signatures.
874
+ *
875
+ * @overload
876
+ * @param {string} reason
877
+ * @param {MessageOptions | null | undefined} [options]
878
+ * @returns {never}
879
+ *
880
+ * @overload
881
+ * @param {string} reason
882
+ * @param {Node | NodeLike | null | undefined} parent
883
+ * @param {string | null | undefined} [origin]
884
+ * @returns {never}
885
+ *
886
+ * @overload
887
+ * @param {string} reason
888
+ * @param {Point | Position | null | undefined} place
889
+ * @param {string | null | undefined} [origin]
890
+ * @returns {never}
891
+ *
892
+ * @overload
893
+ * @param {string} reason
894
+ * @param {string | null | undefined} [origin]
895
+ * @returns {never}
896
+ *
897
+ * @overload
898
+ * @param {Error | VFileMessage} cause
899
+ * @param {Node | NodeLike | null | undefined} parent
900
+ * @param {string | null | undefined} [origin]
901
+ * @returns {never}
902
+ *
903
+ * @overload
904
+ * @param {Error | VFileMessage} cause
905
+ * @param {Point | Position | null | undefined} place
906
+ * @param {string | null | undefined} [origin]
907
+ * @returns {never}
908
+ *
909
+ * @overload
910
+ * @param {Error | VFileMessage} cause
911
+ * @param {string | null | undefined} [origin]
912
+ * @returns {never}
913
+ *
914
+ * @param {Error | VFileMessage | string} causeOrReason
915
+ * Reason for message, should use markdown.
916
+ * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
917
+ * Configuration (optional).
918
+ * @param {string | null | undefined} [origin]
919
+ * Place in code where the message originates (example:
920
+ * `'my-package:my-rule'` or `'my-rule'`).
921
+ * @returns {never}
922
+ * Never.
923
+ * @throws {VFileMessage}
924
+ * Message.
925
+ */
926
+ fail(causeOrReason, optionsOrParentOrPlace, origin) {
927
+ const message = this.message(causeOrReason, optionsOrParentOrPlace, origin);
928
+ message.fatal = true;
929
+ throw message;
930
+ }
931
+ /**
932
+ * Create an info message for `reason` associated with the file.
933
+ *
934
+ * The `fatal` field of the message is set to `undefined` (info; change
935
+ * likely not needed) and the `file` field is set to the current file path.
936
+ * The message is added to the `messages` field on `file`.
937
+ *
938
+ * > 🪦 **Note**: also has obsolete signatures.
939
+ *
940
+ * @overload
941
+ * @param {string} reason
942
+ * @param {MessageOptions | null | undefined} [options]
943
+ * @returns {VFileMessage}
944
+ *
945
+ * @overload
946
+ * @param {string} reason
947
+ * @param {Node | NodeLike | null | undefined} parent
948
+ * @param {string | null | undefined} [origin]
949
+ * @returns {VFileMessage}
950
+ *
951
+ * @overload
952
+ * @param {string} reason
953
+ * @param {Point | Position | null | undefined} place
954
+ * @param {string | null | undefined} [origin]
955
+ * @returns {VFileMessage}
956
+ *
957
+ * @overload
958
+ * @param {string} reason
959
+ * @param {string | null | undefined} [origin]
960
+ * @returns {VFileMessage}
961
+ *
962
+ * @overload
963
+ * @param {Error | VFileMessage} cause
964
+ * @param {Node | NodeLike | null | undefined} parent
965
+ * @param {string | null | undefined} [origin]
966
+ * @returns {VFileMessage}
967
+ *
968
+ * @overload
969
+ * @param {Error | VFileMessage} cause
970
+ * @param {Point | Position | null | undefined} place
971
+ * @param {string | null | undefined} [origin]
972
+ * @returns {VFileMessage}
973
+ *
974
+ * @overload
975
+ * @param {Error | VFileMessage} cause
976
+ * @param {string | null | undefined} [origin]
977
+ * @returns {VFileMessage}
978
+ *
979
+ * @param {Error | VFileMessage | string} causeOrReason
980
+ * Reason for message, should use markdown.
981
+ * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
982
+ * Configuration (optional).
983
+ * @param {string | null | undefined} [origin]
984
+ * Place in code where the message originates (example:
985
+ * `'my-package:my-rule'` or `'my-rule'`).
986
+ * @returns {VFileMessage}
987
+ * Message.
988
+ */
989
+ info(causeOrReason, optionsOrParentOrPlace, origin) {
990
+ const message = this.message(causeOrReason, optionsOrParentOrPlace, origin);
991
+ message.fatal = void 0;
992
+ return message;
993
+ }
994
+ /**
995
+ * Create a message for `reason` associated with the file.
996
+ *
997
+ * The `fatal` field of the message is set to `false` (warning; change may be
998
+ * needed) and the `file` field is set to the current file path.
999
+ * The message is added to the `messages` field on `file`.
1000
+ *
1001
+ * > 🪦 **Note**: also has obsolete signatures.
1002
+ *
1003
+ * @overload
1004
+ * @param {string} reason
1005
+ * @param {MessageOptions | null | undefined} [options]
1006
+ * @returns {VFileMessage}
1007
+ *
1008
+ * @overload
1009
+ * @param {string} reason
1010
+ * @param {Node | NodeLike | null | undefined} parent
1011
+ * @param {string | null | undefined} [origin]
1012
+ * @returns {VFileMessage}
1013
+ *
1014
+ * @overload
1015
+ * @param {string} reason
1016
+ * @param {Point | Position | null | undefined} place
1017
+ * @param {string | null | undefined} [origin]
1018
+ * @returns {VFileMessage}
1019
+ *
1020
+ * @overload
1021
+ * @param {string} reason
1022
+ * @param {string | null | undefined} [origin]
1023
+ * @returns {VFileMessage}
1024
+ *
1025
+ * @overload
1026
+ * @param {Error | VFileMessage} cause
1027
+ * @param {Node | NodeLike | null | undefined} parent
1028
+ * @param {string | null | undefined} [origin]
1029
+ * @returns {VFileMessage}
1030
+ *
1031
+ * @overload
1032
+ * @param {Error | VFileMessage} cause
1033
+ * @param {Point | Position | null | undefined} place
1034
+ * @param {string | null | undefined} [origin]
1035
+ * @returns {VFileMessage}
1036
+ *
1037
+ * @overload
1038
+ * @param {Error | VFileMessage} cause
1039
+ * @param {string | null | undefined} [origin]
1040
+ * @returns {VFileMessage}
1041
+ *
1042
+ * @param {Error | VFileMessage | string} causeOrReason
1043
+ * Reason for message, should use markdown.
1044
+ * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
1045
+ * Configuration (optional).
1046
+ * @param {string | null | undefined} [origin]
1047
+ * Place in code where the message originates (example:
1048
+ * `'my-package:my-rule'` or `'my-rule'`).
1049
+ * @returns {VFileMessage}
1050
+ * Message.
1051
+ */
1052
+ message(causeOrReason, optionsOrParentOrPlace, origin) {
1053
+ const message = new VFileMessage(causeOrReason, optionsOrParentOrPlace, origin);
1054
+ if (this.path) {
1055
+ message.name = this.path + ":" + message.name;
1056
+ message.file = this.path;
1057
+ }
1058
+ message.fatal = false;
1059
+ this.messages.push(message);
1060
+ return message;
1061
+ }
1062
+ /**
1063
+ * Serialize the file.
1064
+ *
1065
+ * > **Note**: which encodings are supported depends on the engine.
1066
+ * > For info on Node.js, see:
1067
+ * > <https://nodejs.org/api/util.html#whatwg-supported-encodings>.
1068
+ *
1069
+ * @param {string | null | undefined} [encoding='utf8']
1070
+ * Character encoding to understand `value` as when it’s a `Uint8Array`
1071
+ * (default: `'utf-8'`).
1072
+ * @returns {string}
1073
+ * Serialized file.
1074
+ */
1075
+ toString(encoding) {
1076
+ if (this.value === void 0) return "";
1077
+ if (typeof this.value === "string") return this.value;
1078
+ return new TextDecoder(encoding || void 0).decode(this.value);
1079
+ }
1080
+ };
1081
+ /**
1082
+ * Assert that `part` is not a path (as in, does not contain `path.sep`).
1083
+ *
1084
+ * @param {string | null | undefined} part
1085
+ * File path part.
1086
+ * @param {string} name
1087
+ * Part name.
1088
+ * @returns {undefined}
1089
+ * Nothing.
1090
+ */
1091
+ function assertPart(part, name) {
1092
+ if (part && part.includes(minpath.sep)) throw new Error("`" + name + "` cannot be a path: did not expect `" + minpath.sep + "`");
1093
+ }
1094
+ /**
1095
+ * Assert that `part` is not empty.
1096
+ *
1097
+ * @param {string | undefined} part
1098
+ * Thing.
1099
+ * @param {string} name
1100
+ * Part name.
1101
+ * @returns {asserts part is string}
1102
+ * Nothing.
1103
+ */
1104
+ function assertNonEmpty(part, name) {
1105
+ if (!part) throw new Error("`" + name + "` cannot be empty");
1106
+ }
1107
+ /**
1108
+ * Assert `path` exists.
1109
+ *
1110
+ * @param {string | undefined} path
1111
+ * Path.
1112
+ * @param {string} name
1113
+ * Dependency name.
1114
+ * @returns {asserts path is string}
1115
+ * Nothing.
1116
+ */
1117
+ function assertPath(path, name) {
1118
+ if (!path) throw new Error("Setting `" + name + "` requires `path` to be set too");
1119
+ }
1120
+ /**
1121
+ * Assert `value` is an `Uint8Array`.
1122
+ *
1123
+ * @param {unknown} value
1124
+ * thing.
1125
+ * @returns {value is Uint8Array}
1126
+ * Whether `value` is an `Uint8Array`.
1127
+ */
1128
+ function isUint8Array$1(value) {
1129
+ return Boolean(value && typeof value === "object" && "byteLength" in value && "byteOffset" in value);
1130
+ }
1131
+ //#endregion
1132
+ //#region node_modules/unified/lib/callable-instance.js
1133
+ const CallableInstance = (function(property) {
1134
+ const proto = this.constructor.prototype;
1135
+ const value = proto[property];
1136
+ /** @type {(...parameters: Array<unknown>) => unknown} */
1137
+ const apply = function() {
1138
+ return value.apply(apply, arguments);
1139
+ };
1140
+ Object.setPrototypeOf(apply, proto);
1141
+ return apply;
1142
+ });
1143
+ //#endregion
1144
+ //#region node_modules/unified/lib/index.js
1145
+ /**
1146
+ * @typedef {import('trough').Pipeline} Pipeline
1147
+ *
1148
+ * @typedef {import('unist').Node} Node
1149
+ *
1150
+ * @typedef {import('vfile').Compatible} Compatible
1151
+ * @typedef {import('vfile').Value} Value
1152
+ *
1153
+ * @typedef {import('../index.js').CompileResultMap} CompileResultMap
1154
+ * @typedef {import('../index.js').Data} Data
1155
+ * @typedef {import('../index.js').Settings} Settings
1156
+ */
1157
+ /**
1158
+ * @typedef {CompileResultMap[keyof CompileResultMap]} CompileResults
1159
+ * Acceptable results from compilers.
1160
+ *
1161
+ * To register custom results, add them to
1162
+ * {@linkcode CompileResultMap}.
1163
+ */
1164
+ /**
1165
+ * @template {Node} [Tree=Node]
1166
+ * The node that the compiler receives (default: `Node`).
1167
+ * @template {CompileResults} [Result=CompileResults]
1168
+ * The thing that the compiler yields (default: `CompileResults`).
1169
+ * @callback Compiler
1170
+ * A **compiler** handles the compiling of a syntax tree to something else
1171
+ * (in most cases, text) (TypeScript type).
1172
+ *
1173
+ * It is used in the stringify phase and called with a {@linkcode Node}
1174
+ * and {@linkcode VFile} representation of the document to compile.
1175
+ * It should return the textual representation of the given tree (typically
1176
+ * `string`).
1177
+ *
1178
+ * > **Note**: unified typically compiles by serializing: most compilers
1179
+ * > return `string` (or `Uint8Array`).
1180
+ * > Some compilers, such as the one configured with
1181
+ * > [`rehype-react`][rehype-react], return other values (in this case, a
1182
+ * > React tree).
1183
+ * > If you’re using a compiler that doesn’t serialize, expect different
1184
+ * > result values.
1185
+ * >
1186
+ * > To register custom results in TypeScript, add them to
1187
+ * > {@linkcode CompileResultMap}.
1188
+ *
1189
+ * [rehype-react]: https://github.com/rehypejs/rehype-react
1190
+ * @param {Tree} tree
1191
+ * Tree to compile.
1192
+ * @param {VFile} file
1193
+ * File associated with `tree`.
1194
+ * @returns {Result}
1195
+ * New content: compiled text (`string` or `Uint8Array`, for `file.value`) or
1196
+ * something else (for `file.result`).
1197
+ */
1198
+ /**
1199
+ * @template {Node} [Tree=Node]
1200
+ * The node that the parser yields (default: `Node`)
1201
+ * @callback Parser
1202
+ * A **parser** handles the parsing of text to a syntax tree.
1203
+ *
1204
+ * It is used in the parse phase and is called with a `string` and
1205
+ * {@linkcode VFile} of the document to parse.
1206
+ * It must return the syntax tree representation of the given file
1207
+ * ({@linkcode Node}).
1208
+ * @param {string} document
1209
+ * Document to parse.
1210
+ * @param {VFile} file
1211
+ * File associated with `document`.
1212
+ * @returns {Tree}
1213
+ * Node representing the given file.
1214
+ */
1215
+ /**
1216
+ * @typedef {(
1217
+ * Plugin<Array<any>, any, any> |
1218
+ * PluginTuple<Array<any>, any, any> |
1219
+ * Preset
1220
+ * )} Pluggable
1221
+ * Union of the different ways to add plugins and settings.
1222
+ */
1223
+ /**
1224
+ * @typedef {Array<Pluggable>} PluggableList
1225
+ * List of plugins and presets.
1226
+ */
1227
+ /**
1228
+ * @template {Array<unknown>} [PluginParameters=[]]
1229
+ * Arguments passed to the plugin (default: `[]`, the empty tuple).
1230
+ * @template {Node | string | undefined} [Input=Node]
1231
+ * Value that is expected as input (default: `Node`).
1232
+ *
1233
+ * * If the plugin returns a {@linkcode Transformer}, this
1234
+ * should be the node it expects.
1235
+ * * If the plugin sets a {@linkcode Parser}, this should be
1236
+ * `string`.
1237
+ * * If the plugin sets a {@linkcode Compiler}, this should be the
1238
+ * node it expects.
1239
+ * @template [Output=Input]
1240
+ * Value that is yielded as output (default: `Input`).
1241
+ *
1242
+ * * If the plugin returns a {@linkcode Transformer}, this
1243
+ * should be the node that that yields.
1244
+ * * If the plugin sets a {@linkcode Parser}, this should be the
1245
+ * node that it yields.
1246
+ * * If the plugin sets a {@linkcode Compiler}, this should be
1247
+ * result it yields.
1248
+ * @typedef {(
1249
+ * (this: Processor, ...parameters: PluginParameters) =>
1250
+ * Input extends string ? // Parser.
1251
+ * Output extends Node | undefined ? undefined | void : never :
1252
+ * Output extends CompileResults ? // Compiler.
1253
+ * Input extends Node | undefined ? undefined | void : never :
1254
+ * Transformer<
1255
+ * Input extends Node ? Input : Node,
1256
+ * Output extends Node ? Output : Node
1257
+ * > | undefined | void
1258
+ * )} Plugin
1259
+ * Single plugin.
1260
+ *
1261
+ * Plugins configure the processors they are applied on in the following
1262
+ * ways:
1263
+ *
1264
+ * * they change the processor, such as the parser, the compiler, or by
1265
+ * configuring data
1266
+ * * they specify how to handle trees and files
1267
+ *
1268
+ * In practice, they are functions that can receive options and configure the
1269
+ * processor (`this`).
1270
+ *
1271
+ * > **Note**: plugins are called when the processor is *frozen*, not when
1272
+ * > they are applied.
1273
+ */
1274
+ /**
1275
+ * Tuple of a plugin and its configuration.
1276
+ *
1277
+ * The first item is a plugin, the rest are its parameters.
1278
+ *
1279
+ * @template {Array<unknown>} [TupleParameters=[]]
1280
+ * Arguments passed to the plugin (default: `[]`, the empty tuple).
1281
+ * @template {Node | string | undefined} [Input=undefined]
1282
+ * Value that is expected as input (optional).
1283
+ *
1284
+ * * If the plugin returns a {@linkcode Transformer}, this
1285
+ * should be the node it expects.
1286
+ * * If the plugin sets a {@linkcode Parser}, this should be
1287
+ * `string`.
1288
+ * * If the plugin sets a {@linkcode Compiler}, this should be the
1289
+ * node it expects.
1290
+ * @template [Output=undefined] (optional).
1291
+ * Value that is yielded as output.
1292
+ *
1293
+ * * If the plugin returns a {@linkcode Transformer}, this
1294
+ * should be the node that that yields.
1295
+ * * If the plugin sets a {@linkcode Parser}, this should be the
1296
+ * node that it yields.
1297
+ * * If the plugin sets a {@linkcode Compiler}, this should be
1298
+ * result it yields.
1299
+ * @typedef {(
1300
+ * [
1301
+ * plugin: Plugin<TupleParameters, Input, Output>,
1302
+ * ...parameters: TupleParameters
1303
+ * ]
1304
+ * )} PluginTuple
1305
+ */
1306
+ /**
1307
+ * @typedef Preset
1308
+ * Sharable configuration.
1309
+ *
1310
+ * They can contain plugins and settings.
1311
+ * @property {PluggableList | undefined} [plugins]
1312
+ * List of plugins and presets (optional).
1313
+ * @property {Settings | undefined} [settings]
1314
+ * Shared settings for parsers and compilers (optional).
1315
+ */
1316
+ /**
1317
+ * @template {VFile} [File=VFile]
1318
+ * The file that the callback receives (default: `VFile`).
1319
+ * @callback ProcessCallback
1320
+ * Callback called when the process is done.
1321
+ *
1322
+ * Called with either an error or a result.
1323
+ * @param {Error | undefined} [error]
1324
+ * Fatal error (optional).
1325
+ * @param {File | undefined} [file]
1326
+ * Processed file (optional).
1327
+ * @returns {undefined}
1328
+ * Nothing.
1329
+ */
1330
+ /**
1331
+ * @template {Node} [Tree=Node]
1332
+ * The tree that the callback receives (default: `Node`).
1333
+ * @callback RunCallback
1334
+ * Callback called when transformers are done.
1335
+ *
1336
+ * Called with either an error or results.
1337
+ * @param {Error | undefined} [error]
1338
+ * Fatal error (optional).
1339
+ * @param {Tree | undefined} [tree]
1340
+ * Transformed tree (optional).
1341
+ * @param {VFile | undefined} [file]
1342
+ * File (optional).
1343
+ * @returns {undefined}
1344
+ * Nothing.
1345
+ */
1346
+ /**
1347
+ * @template {Node} [Output=Node]
1348
+ * Node type that the transformer yields (default: `Node`).
1349
+ * @callback TransformCallback
1350
+ * Callback passed to transforms.
1351
+ *
1352
+ * If the signature of a `transformer` accepts a third argument, the
1353
+ * transformer may perform asynchronous operations, and must call it.
1354
+ * @param {Error | undefined} [error]
1355
+ * Fatal error to stop the process (optional).
1356
+ * @param {Output | undefined} [tree]
1357
+ * New, changed, tree (optional).
1358
+ * @param {VFile | undefined} [file]
1359
+ * New, changed, file (optional).
1360
+ * @returns {undefined}
1361
+ * Nothing.
1362
+ */
1363
+ /**
1364
+ * @template {Node} [Input=Node]
1365
+ * Node type that the transformer expects (default: `Node`).
1366
+ * @template {Node} [Output=Input]
1367
+ * Node type that the transformer yields (default: `Input`).
1368
+ * @callback Transformer
1369
+ * Transformers handle syntax trees and files.
1370
+ *
1371
+ * They are functions that are called each time a syntax tree and file are
1372
+ * passed through the run phase.
1373
+ * When an error occurs in them (either because it’s thrown, returned,
1374
+ * rejected, or passed to `next`), the process stops.
1375
+ *
1376
+ * The run phase is handled by [`trough`][trough], see its documentation for
1377
+ * the exact semantics of these functions.
1378
+ *
1379
+ * > **Note**: you should likely ignore `next`: don’t accept it.
1380
+ * > it supports callback-style async work.
1381
+ * > But promises are likely easier to reason about.
1382
+ *
1383
+ * [trough]: https://github.com/wooorm/trough#function-fninput-next
1384
+ * @param {Input} tree
1385
+ * Tree to handle.
1386
+ * @param {VFile} file
1387
+ * File to handle.
1388
+ * @param {TransformCallback<Output>} next
1389
+ * Callback.
1390
+ * @returns {(
1391
+ * Promise<Output | undefined | void> |
1392
+ * Promise<never> | // For some reason this is needed separately.
1393
+ * Output |
1394
+ * Error |
1395
+ * undefined |
1396
+ * void
1397
+ * )}
1398
+ * If you accept `next`, nothing.
1399
+ * Otherwise:
1400
+ *
1401
+ * * `Error` — fatal error to stop the process
1402
+ * * `Promise<undefined>` or `undefined` — the next transformer keeps using
1403
+ * same tree
1404
+ * * `Promise<Node>` or `Node` — new, changed, tree
1405
+ */
1406
+ /**
1407
+ * @template {Node | undefined} ParseTree
1408
+ * Output of `parse`.
1409
+ * @template {Node | undefined} HeadTree
1410
+ * Input for `run`.
1411
+ * @template {Node | undefined} TailTree
1412
+ * Output for `run`.
1413
+ * @template {Node | undefined} CompileTree
1414
+ * Input of `stringify`.
1415
+ * @template {CompileResults | undefined} CompileResult
1416
+ * Output of `stringify`.
1417
+ * @template {Node | string | undefined} Input
1418
+ * Input of plugin.
1419
+ * @template Output
1420
+ * Output of plugin (optional).
1421
+ * @typedef {(
1422
+ * Input extends string
1423
+ * ? Output extends Node | undefined
1424
+ * ? // Parser.
1425
+ * Processor<
1426
+ * Output extends undefined ? ParseTree : Output,
1427
+ * HeadTree,
1428
+ * TailTree,
1429
+ * CompileTree,
1430
+ * CompileResult
1431
+ * >
1432
+ * : // Unknown.
1433
+ * Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>
1434
+ * : Output extends CompileResults
1435
+ * ? Input extends Node | undefined
1436
+ * ? // Compiler.
1437
+ * Processor<
1438
+ * ParseTree,
1439
+ * HeadTree,
1440
+ * TailTree,
1441
+ * Input extends undefined ? CompileTree : Input,
1442
+ * Output extends undefined ? CompileResult : Output
1443
+ * >
1444
+ * : // Unknown.
1445
+ * Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>
1446
+ * : Input extends Node | undefined
1447
+ * ? Output extends Node | undefined
1448
+ * ? // Transform.
1449
+ * Processor<
1450
+ * ParseTree,
1451
+ * HeadTree extends undefined ? Input : HeadTree,
1452
+ * Output extends undefined ? TailTree : Output,
1453
+ * CompileTree,
1454
+ * CompileResult
1455
+ * >
1456
+ * : // Unknown.
1457
+ * Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>
1458
+ * : // Unknown.
1459
+ * Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>
1460
+ * )} UsePlugin
1461
+ * Create a processor based on the input/output of a {@link Plugin plugin}.
1462
+ */
1463
+ /**
1464
+ * @template {CompileResults | undefined} Result
1465
+ * Node type that the transformer yields.
1466
+ * @typedef {(
1467
+ * Result extends Value | undefined ?
1468
+ * VFile :
1469
+ * VFile & {result: Result}
1470
+ * )} VFileWithOutput
1471
+ * Type to generate a {@linkcode VFile} corresponding to a compiler result.
1472
+ *
1473
+ * If a result that is not acceptable on a `VFile` is used, that will
1474
+ * be stored on the `result` field of {@linkcode VFile}.
1475
+ */
1476
+ var import_extend = /* @__PURE__ */ __toESM(require_extend(), 1);
1477
+ const own = {}.hasOwnProperty;
1478
+ /**
1479
+ * Create a new processor.
1480
+ *
1481
+ * @example
1482
+ * This example shows how a new processor can be created (from `remark`) and linked
1483
+ * to **stdin**(4) and **stdout**(4).
1484
+ *
1485
+ * ```js
1486
+ * import process from 'node:process'
1487
+ * import concatStream from 'concat-stream'
1488
+ * import {remark} from 'remark'
1489
+ *
1490
+ * process.stdin.pipe(
1491
+ * concatStream(function (buf) {
1492
+ * process.stdout.write(String(remark().processSync(buf)))
1493
+ * })
1494
+ * )
1495
+ * ```
1496
+ *
1497
+ * @returns
1498
+ * New *unfrozen* processor (`processor`).
1499
+ *
1500
+ * This processor is configured to work the same as its ancestor.
1501
+ * When the descendant processor is configured in the future it does not
1502
+ * affect the ancestral processor.
1503
+ */
1504
+ const unified = new class Processor extends CallableInstance {
1505
+ /**
1506
+ * Create a processor.
1507
+ */
1508
+ constructor() {
1509
+ super("copy");
1510
+ /**
1511
+ * Compiler to use (deprecated).
1512
+ *
1513
+ * @deprecated
1514
+ * Use `compiler` instead.
1515
+ * @type {(
1516
+ * Compiler<
1517
+ * CompileTree extends undefined ? Node : CompileTree,
1518
+ * CompileResult extends undefined ? CompileResults : CompileResult
1519
+ * > |
1520
+ * undefined
1521
+ * )}
1522
+ */
1523
+ this.Compiler = void 0;
1524
+ /**
1525
+ * Parser to use (deprecated).
1526
+ *
1527
+ * @deprecated
1528
+ * Use `parser` instead.
1529
+ * @type {(
1530
+ * Parser<ParseTree extends undefined ? Node : ParseTree> |
1531
+ * undefined
1532
+ * )}
1533
+ */
1534
+ this.Parser = void 0;
1535
+ /**
1536
+ * Internal list of configured plugins.
1537
+ *
1538
+ * @deprecated
1539
+ * This is a private internal property and should not be used.
1540
+ * @type {Array<PluginTuple<Array<unknown>>>}
1541
+ */
1542
+ this.attachers = [];
1543
+ /**
1544
+ * Compiler to use.
1545
+ *
1546
+ * @type {(
1547
+ * Compiler<
1548
+ * CompileTree extends undefined ? Node : CompileTree,
1549
+ * CompileResult extends undefined ? CompileResults : CompileResult
1550
+ * > |
1551
+ * undefined
1552
+ * )}
1553
+ */
1554
+ this.compiler = void 0;
1555
+ /**
1556
+ * Internal state to track where we are while freezing.
1557
+ *
1558
+ * @deprecated
1559
+ * This is a private internal property and should not be used.
1560
+ * @type {number}
1561
+ */
1562
+ this.freezeIndex = -1;
1563
+ /**
1564
+ * Internal state to track whether we’re frozen.
1565
+ *
1566
+ * @deprecated
1567
+ * This is a private internal property and should not be used.
1568
+ * @type {boolean | undefined}
1569
+ */
1570
+ this.frozen = void 0;
1571
+ /**
1572
+ * Internal state.
1573
+ *
1574
+ * @deprecated
1575
+ * This is a private internal property and should not be used.
1576
+ * @type {Data}
1577
+ */
1578
+ this.namespace = {};
1579
+ /**
1580
+ * Parser to use.
1581
+ *
1582
+ * @type {(
1583
+ * Parser<ParseTree extends undefined ? Node : ParseTree> |
1584
+ * undefined
1585
+ * )}
1586
+ */
1587
+ this.parser = void 0;
1588
+ /**
1589
+ * Internal list of configured transformers.
1590
+ *
1591
+ * @deprecated
1592
+ * This is a private internal property and should not be used.
1593
+ * @type {Pipeline}
1594
+ */
1595
+ this.transformers = trough();
1596
+ }
1597
+ /**
1598
+ * Copy a processor.
1599
+ *
1600
+ * @deprecated
1601
+ * This is a private internal method and should not be used.
1602
+ * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
1603
+ * New *unfrozen* processor ({@linkcode Processor}) that is
1604
+ * configured to work the same as its ancestor.
1605
+ * When the descendant processor is configured in the future it does not
1606
+ * affect the ancestral processor.
1607
+ */
1608
+ copy() {
1609
+ const destination = new Processor();
1610
+ let index = -1;
1611
+ while (++index < this.attachers.length) {
1612
+ const attacher = this.attachers[index];
1613
+ destination.use(...attacher);
1614
+ }
1615
+ destination.data((0, import_extend.default)(true, {}, this.namespace));
1616
+ return destination;
1617
+ }
1618
+ /**
1619
+ * Configure the processor with info available to all plugins.
1620
+ * Information is stored in an object.
1621
+ *
1622
+ * Typically, options can be given to a specific plugin, but sometimes it
1623
+ * makes sense to have information shared with several plugins.
1624
+ * For example, a list of HTML elements that are self-closing, which is
1625
+ * needed during all phases.
1626
+ *
1627
+ * > **Note**: setting information cannot occur on *frozen* processors.
1628
+ * > Call the processor first to create a new unfrozen processor.
1629
+ *
1630
+ * > **Note**: to register custom data in TypeScript, augment the
1631
+ * > {@linkcode Data} interface.
1632
+ *
1633
+ * @example
1634
+ * This example show how to get and set info:
1635
+ *
1636
+ * ```js
1637
+ * import {unified} from 'unified'
1638
+ *
1639
+ * const processor = unified().data('alpha', 'bravo')
1640
+ *
1641
+ * processor.data('alpha') // => 'bravo'
1642
+ *
1643
+ * processor.data() // => {alpha: 'bravo'}
1644
+ *
1645
+ * processor.data({charlie: 'delta'})
1646
+ *
1647
+ * processor.data() // => {charlie: 'delta'}
1648
+ * ```
1649
+ *
1650
+ * @template {keyof Data} Key
1651
+ *
1652
+ * @overload
1653
+ * @returns {Data}
1654
+ *
1655
+ * @overload
1656
+ * @param {Data} dataset
1657
+ * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
1658
+ *
1659
+ * @overload
1660
+ * @param {Key} key
1661
+ * @returns {Data[Key]}
1662
+ *
1663
+ * @overload
1664
+ * @param {Key} key
1665
+ * @param {Data[Key]} value
1666
+ * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
1667
+ *
1668
+ * @param {Data | Key} [key]
1669
+ * Key to get or set, or entire dataset to set, or nothing to get the
1670
+ * entire dataset (optional).
1671
+ * @param {Data[Key]} [value]
1672
+ * Value to set (optional).
1673
+ * @returns {unknown}
1674
+ * The current processor when setting, the value at `key` when getting, or
1675
+ * the entire dataset when getting without key.
1676
+ */
1677
+ data(key, value) {
1678
+ if (typeof key === "string") {
1679
+ if (arguments.length === 2) {
1680
+ assertUnfrozen("data", this.frozen);
1681
+ this.namespace[key] = value;
1682
+ return this;
1683
+ }
1684
+ return own.call(this.namespace, key) && this.namespace[key] || void 0;
1685
+ }
1686
+ if (key) {
1687
+ assertUnfrozen("data", this.frozen);
1688
+ this.namespace = key;
1689
+ return this;
1690
+ }
1691
+ return this.namespace;
1692
+ }
1693
+ /**
1694
+ * Freeze a processor.
1695
+ *
1696
+ * Frozen processors are meant to be extended and not to be configured
1697
+ * directly.
1698
+ *
1699
+ * When a processor is frozen it cannot be unfrozen.
1700
+ * New processors working the same way can be created by calling the
1701
+ * processor.
1702
+ *
1703
+ * It’s possible to freeze processors explicitly by calling `.freeze()`.
1704
+ * Processors freeze automatically when `.parse()`, `.run()`, `.runSync()`,
1705
+ * `.stringify()`, `.process()`, or `.processSync()` are called.
1706
+ *
1707
+ * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
1708
+ * The current processor.
1709
+ */
1710
+ freeze() {
1711
+ if (this.frozen) return this;
1712
+ const self = this;
1713
+ while (++this.freezeIndex < this.attachers.length) {
1714
+ const [attacher, ...options] = this.attachers[this.freezeIndex];
1715
+ if (options[0] === false) continue;
1716
+ if (options[0] === true) options[0] = void 0;
1717
+ const transformer = attacher.call(self, ...options);
1718
+ if (typeof transformer === "function") this.transformers.use(transformer);
1719
+ }
1720
+ this.frozen = true;
1721
+ this.freezeIndex = Number.POSITIVE_INFINITY;
1722
+ return this;
1723
+ }
1724
+ /**
1725
+ * Parse text to a syntax tree.
1726
+ *
1727
+ * > **Note**: `parse` freezes the processor if not already *frozen*.
1728
+ *
1729
+ * > **Note**: `parse` performs the parse phase, not the run phase or other
1730
+ * > phases.
1731
+ *
1732
+ * @param {Compatible | undefined} [file]
1733
+ * file to parse (optional); typically `string` or `VFile`; any value
1734
+ * accepted as `x` in `new VFile(x)`.
1735
+ * @returns {ParseTree extends undefined ? Node : ParseTree}
1736
+ * Syntax tree representing `file`.
1737
+ */
1738
+ parse(file) {
1739
+ this.freeze();
1740
+ const realFile = vfile(file);
1741
+ const parser = this.parser || this.Parser;
1742
+ assertParser("parse", parser);
1743
+ return parser(String(realFile), realFile);
1744
+ }
1745
+ /**
1746
+ * Process the given file as configured on the processor.
1747
+ *
1748
+ * > **Note**: `process` freezes the processor if not already *frozen*.
1749
+ *
1750
+ * > **Note**: `process` performs the parse, run, and stringify phases.
1751
+ *
1752
+ * @overload
1753
+ * @param {Compatible | undefined} file
1754
+ * @param {ProcessCallback<VFileWithOutput<CompileResult>>} done
1755
+ * @returns {undefined}
1756
+ *
1757
+ * @overload
1758
+ * @param {Compatible | undefined} [file]
1759
+ * @returns {Promise<VFileWithOutput<CompileResult>>}
1760
+ *
1761
+ * @param {Compatible | undefined} [file]
1762
+ * File (optional); typically `string` or `VFile`]; any value accepted as
1763
+ * `x` in `new VFile(x)`.
1764
+ * @param {ProcessCallback<VFileWithOutput<CompileResult>> | undefined} [done]
1765
+ * Callback (optional).
1766
+ * @returns {Promise<VFile> | undefined}
1767
+ * Nothing if `done` is given.
1768
+ * Otherwise a promise, rejected with a fatal error or resolved with the
1769
+ * processed file.
1770
+ *
1771
+ * The parsed, transformed, and compiled value is available at
1772
+ * `file.value` (see note).
1773
+ *
1774
+ * > **Note**: unified typically compiles by serializing: most
1775
+ * > compilers return `string` (or `Uint8Array`).
1776
+ * > Some compilers, such as the one configured with
1777
+ * > [`rehype-react`][rehype-react], return other values (in this case, a
1778
+ * > React tree).
1779
+ * > If you’re using a compiler that doesn’t serialize, expect different
1780
+ * > result values.
1781
+ * >
1782
+ * > To register custom results in TypeScript, add them to
1783
+ * > {@linkcode CompileResultMap}.
1784
+ *
1785
+ * [rehype-react]: https://github.com/rehypejs/rehype-react
1786
+ */
1787
+ process(file, done) {
1788
+ const self = this;
1789
+ this.freeze();
1790
+ assertParser("process", this.parser || this.Parser);
1791
+ assertCompiler("process", this.compiler || this.Compiler);
1792
+ return done ? executor(void 0, done) : new Promise(executor);
1793
+ /**
1794
+ * @param {((file: VFileWithOutput<CompileResult>) => undefined | void) | undefined} resolve
1795
+ * @param {(error: Error | undefined) => undefined | void} reject
1796
+ * @returns {undefined}
1797
+ */
1798
+ function executor(resolve, reject) {
1799
+ const realFile = vfile(file);
1800
+ const parseTree = self.parse(realFile);
1801
+ self.run(parseTree, realFile, function(error, tree, file) {
1802
+ if (error || !tree || !file) return realDone(error);
1803
+ const compileTree = tree;
1804
+ const compileResult = self.stringify(compileTree, file);
1805
+ if (looksLikeAValue(compileResult)) file.value = compileResult;
1806
+ else file.result = compileResult;
1807
+ realDone(error, file);
1808
+ });
1809
+ /**
1810
+ * @param {Error | undefined} error
1811
+ * @param {VFileWithOutput<CompileResult> | undefined} [file]
1812
+ * @returns {undefined}
1813
+ */
1814
+ function realDone(error, file) {
1815
+ if (error || !file) reject(error);
1816
+ else if (resolve) resolve(file);
1817
+ else done(void 0, file);
1818
+ }
1819
+ }
1820
+ }
1821
+ /**
1822
+ * Process the given file as configured on the processor.
1823
+ *
1824
+ * An error is thrown if asynchronous transforms are configured.
1825
+ *
1826
+ * > **Note**: `processSync` freezes the processor if not already *frozen*.
1827
+ *
1828
+ * > **Note**: `processSync` performs the parse, run, and stringify phases.
1829
+ *
1830
+ * @param {Compatible | undefined} [file]
1831
+ * File (optional); typically `string` or `VFile`; any value accepted as
1832
+ * `x` in `new VFile(x)`.
1833
+ * @returns {VFileWithOutput<CompileResult>}
1834
+ * The processed file.
1835
+ *
1836
+ * The parsed, transformed, and compiled value is available at
1837
+ * `file.value` (see note).
1838
+ *
1839
+ * > **Note**: unified typically compiles by serializing: most
1840
+ * > compilers return `string` (or `Uint8Array`).
1841
+ * > Some compilers, such as the one configured with
1842
+ * > [`rehype-react`][rehype-react], return other values (in this case, a
1843
+ * > React tree).
1844
+ * > If you’re using a compiler that doesn’t serialize, expect different
1845
+ * > result values.
1846
+ * >
1847
+ * > To register custom results in TypeScript, add them to
1848
+ * > {@linkcode CompileResultMap}.
1849
+ *
1850
+ * [rehype-react]: https://github.com/rehypejs/rehype-react
1851
+ */
1852
+ processSync(file) {
1853
+ /** @type {boolean} */
1854
+ let complete = false;
1855
+ /** @type {VFileWithOutput<CompileResult> | undefined} */
1856
+ let result;
1857
+ this.freeze();
1858
+ assertParser("processSync", this.parser || this.Parser);
1859
+ assertCompiler("processSync", this.compiler || this.Compiler);
1860
+ this.process(file, realDone);
1861
+ assertDone("processSync", "process", complete);
1862
+ return result;
1863
+ /**
1864
+ * @type {ProcessCallback<VFileWithOutput<CompileResult>>}
1865
+ */
1866
+ function realDone(error, file) {
1867
+ complete = true;
1868
+ bail(error);
1869
+ result = file;
1870
+ }
1871
+ }
1872
+ /**
1873
+ * Run *transformers* on a syntax tree.
1874
+ *
1875
+ * > **Note**: `run` freezes the processor if not already *frozen*.
1876
+ *
1877
+ * > **Note**: `run` performs the run phase, not other phases.
1878
+ *
1879
+ * @overload
1880
+ * @param {HeadTree extends undefined ? Node : HeadTree} tree
1881
+ * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done
1882
+ * @returns {undefined}
1883
+ *
1884
+ * @overload
1885
+ * @param {HeadTree extends undefined ? Node : HeadTree} tree
1886
+ * @param {Compatible | undefined} file
1887
+ * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done
1888
+ * @returns {undefined}
1889
+ *
1890
+ * @overload
1891
+ * @param {HeadTree extends undefined ? Node : HeadTree} tree
1892
+ * @param {Compatible | undefined} [file]
1893
+ * @returns {Promise<TailTree extends undefined ? Node : TailTree>}
1894
+ *
1895
+ * @param {HeadTree extends undefined ? Node : HeadTree} tree
1896
+ * Tree to transform and inspect.
1897
+ * @param {(
1898
+ * RunCallback<TailTree extends undefined ? Node : TailTree> |
1899
+ * Compatible
1900
+ * )} [file]
1901
+ * File associated with `node` (optional); any value accepted as `x` in
1902
+ * `new VFile(x)`.
1903
+ * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} [done]
1904
+ * Callback (optional).
1905
+ * @returns {Promise<TailTree extends undefined ? Node : TailTree> | undefined}
1906
+ * Nothing if `done` is given.
1907
+ * Otherwise, a promise rejected with a fatal error or resolved with the
1908
+ * transformed tree.
1909
+ */
1910
+ run(tree, file, done) {
1911
+ assertNode(tree);
1912
+ this.freeze();
1913
+ const transformers = this.transformers;
1914
+ if (!done && typeof file === "function") {
1915
+ done = file;
1916
+ file = void 0;
1917
+ }
1918
+ return done ? executor(void 0, done) : new Promise(executor);
1919
+ /**
1920
+ * @param {(
1921
+ * ((tree: TailTree extends undefined ? Node : TailTree) => undefined | void) |
1922
+ * undefined
1923
+ * )} resolve
1924
+ * @param {(error: Error) => undefined | void} reject
1925
+ * @returns {undefined}
1926
+ */
1927
+ function executor(resolve, reject) {
1928
+ const realFile = vfile(file);
1929
+ transformers.run(tree, realFile, realDone);
1930
+ /**
1931
+ * @param {Error | undefined} error
1932
+ * @param {Node} outputTree
1933
+ * @param {VFile} file
1934
+ * @returns {undefined}
1935
+ */
1936
+ function realDone(error, outputTree, file) {
1937
+ const resultingTree = outputTree || tree;
1938
+ if (error) reject(error);
1939
+ else if (resolve) resolve(resultingTree);
1940
+ else done(void 0, resultingTree, file);
1941
+ }
1942
+ }
1943
+ }
1944
+ /**
1945
+ * Run *transformers* on a syntax tree.
1946
+ *
1947
+ * An error is thrown if asynchronous transforms are configured.
1948
+ *
1949
+ * > **Note**: `runSync` freezes the processor if not already *frozen*.
1950
+ *
1951
+ * > **Note**: `runSync` performs the run phase, not other phases.
1952
+ *
1953
+ * @param {HeadTree extends undefined ? Node : HeadTree} tree
1954
+ * Tree to transform and inspect.
1955
+ * @param {Compatible | undefined} [file]
1956
+ * File associated with `node` (optional); any value accepted as `x` in
1957
+ * `new VFile(x)`.
1958
+ * @returns {TailTree extends undefined ? Node : TailTree}
1959
+ * Transformed tree.
1960
+ */
1961
+ runSync(tree, file) {
1962
+ /** @type {boolean} */
1963
+ let complete = false;
1964
+ /** @type {(TailTree extends undefined ? Node : TailTree) | undefined} */
1965
+ let result;
1966
+ this.run(tree, file, realDone);
1967
+ assertDone("runSync", "run", complete);
1968
+ return result;
1969
+ /**
1970
+ * @type {RunCallback<TailTree extends undefined ? Node : TailTree>}
1971
+ */
1972
+ function realDone(error, tree) {
1973
+ bail(error);
1974
+ result = tree;
1975
+ complete = true;
1976
+ }
1977
+ }
1978
+ /**
1979
+ * Compile a syntax tree.
1980
+ *
1981
+ * > **Note**: `stringify` freezes the processor if not already *frozen*.
1982
+ *
1983
+ * > **Note**: `stringify` performs the stringify phase, not the run phase
1984
+ * > or other phases.
1985
+ *
1986
+ * @param {CompileTree extends undefined ? Node : CompileTree} tree
1987
+ * Tree to compile.
1988
+ * @param {Compatible | undefined} [file]
1989
+ * File associated with `node` (optional); any value accepted as `x` in
1990
+ * `new VFile(x)`.
1991
+ * @returns {CompileResult extends undefined ? Value : CompileResult}
1992
+ * Textual representation of the tree (see note).
1993
+ *
1994
+ * > **Note**: unified typically compiles by serializing: most compilers
1995
+ * > return `string` (or `Uint8Array`).
1996
+ * > Some compilers, such as the one configured with
1997
+ * > [`rehype-react`][rehype-react], return other values (in this case, a
1998
+ * > React tree).
1999
+ * > If you’re using a compiler that doesn’t serialize, expect different
2000
+ * > result values.
2001
+ * >
2002
+ * > To register custom results in TypeScript, add them to
2003
+ * > {@linkcode CompileResultMap}.
2004
+ *
2005
+ * [rehype-react]: https://github.com/rehypejs/rehype-react
2006
+ */
2007
+ stringify(tree, file) {
2008
+ this.freeze();
2009
+ const realFile = vfile(file);
2010
+ const compiler = this.compiler || this.Compiler;
2011
+ assertCompiler("stringify", compiler);
2012
+ assertNode(tree);
2013
+ return compiler(tree, realFile);
2014
+ }
2015
+ /**
2016
+ * Configure the processor to use a plugin, a list of usable values, or a
2017
+ * preset.
2018
+ *
2019
+ * If the processor is already using a plugin, the previous plugin
2020
+ * configuration is changed based on the options that are passed in.
2021
+ * In other words, the plugin is not added a second time.
2022
+ *
2023
+ * > **Note**: `use` cannot be called on *frozen* processors.
2024
+ * > Call the processor first to create a new unfrozen processor.
2025
+ *
2026
+ * @example
2027
+ * There are many ways to pass plugins to `.use()`.
2028
+ * This example gives an overview:
2029
+ *
2030
+ * ```js
2031
+ * import {unified} from 'unified'
2032
+ *
2033
+ * unified()
2034
+ * // Plugin with options:
2035
+ * .use(pluginA, {x: true, y: true})
2036
+ * // Passing the same plugin again merges configuration (to `{x: true, y: false, z: true}`):
2037
+ * .use(pluginA, {y: false, z: true})
2038
+ * // Plugins:
2039
+ * .use([pluginB, pluginC])
2040
+ * // Two plugins, the second with options:
2041
+ * .use([pluginD, [pluginE, {}]])
2042
+ * // Preset with plugins and settings:
2043
+ * .use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}})
2044
+ * // Settings only:
2045
+ * .use({settings: {position: false}})
2046
+ * ```
2047
+ *
2048
+ * @template {Array<unknown>} [Parameters=[]]
2049
+ * @template {Node | string | undefined} [Input=undefined]
2050
+ * @template [Output=Input]
2051
+ *
2052
+ * @overload
2053
+ * @param {Preset | null | undefined} [preset]
2054
+ * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
2055
+ *
2056
+ * @overload
2057
+ * @param {PluggableList} list
2058
+ * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
2059
+ *
2060
+ * @overload
2061
+ * @param {Plugin<Parameters, Input, Output>} plugin
2062
+ * @param {...(Parameters | [boolean])} parameters
2063
+ * @returns {UsePlugin<ParseTree, HeadTree, TailTree, CompileTree, CompileResult, Input, Output>}
2064
+ *
2065
+ * @param {PluggableList | Plugin | Preset | null | undefined} value
2066
+ * Usable value.
2067
+ * @param {...unknown} parameters
2068
+ * Parameters, when a plugin is given as a usable value.
2069
+ * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
2070
+ * Current processor.
2071
+ */
2072
+ use(value, ...parameters) {
2073
+ const attachers = this.attachers;
2074
+ const namespace = this.namespace;
2075
+ assertUnfrozen("use", this.frozen);
2076
+ if (value === null || value === void 0) {} else if (typeof value === "function") addPlugin(value, parameters);
2077
+ else if (typeof value === "object") if (Array.isArray(value)) addList(value);
2078
+ else addPreset(value);
2079
+ else throw new TypeError("Expected usable value, not `" + value + "`");
2080
+ return this;
2081
+ /**
2082
+ * @param {Pluggable} value
2083
+ * @returns {undefined}
2084
+ */
2085
+ function add(value) {
2086
+ if (typeof value === "function") addPlugin(value, []);
2087
+ else if (typeof value === "object") if (Array.isArray(value)) {
2088
+ const [plugin, ...parameters] = value;
2089
+ addPlugin(plugin, parameters);
2090
+ } else addPreset(value);
2091
+ else throw new TypeError("Expected usable value, not `" + value + "`");
2092
+ }
2093
+ /**
2094
+ * @param {Preset} result
2095
+ * @returns {undefined}
2096
+ */
2097
+ function addPreset(result) {
2098
+ if (!("plugins" in result) && !("settings" in result)) throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");
2099
+ addList(result.plugins);
2100
+ if (result.settings) namespace.settings = (0, import_extend.default)(true, namespace.settings, result.settings);
2101
+ }
2102
+ /**
2103
+ * @param {PluggableList | null | undefined} plugins
2104
+ * @returns {undefined}
2105
+ */
2106
+ function addList(plugins) {
2107
+ let index = -1;
2108
+ if (plugins === null || plugins === void 0) {} else if (Array.isArray(plugins)) while (++index < plugins.length) {
2109
+ const thing = plugins[index];
2110
+ add(thing);
2111
+ }
2112
+ else throw new TypeError("Expected a list of plugins, not `" + plugins + "`");
2113
+ }
2114
+ /**
2115
+ * @param {Plugin} plugin
2116
+ * @param {Array<unknown>} parameters
2117
+ * @returns {undefined}
2118
+ */
2119
+ function addPlugin(plugin, parameters) {
2120
+ let index = -1;
2121
+ let entryIndex = -1;
2122
+ while (++index < attachers.length) if (attachers[index][0] === plugin) {
2123
+ entryIndex = index;
2124
+ break;
2125
+ }
2126
+ if (entryIndex === -1) attachers.push([plugin, ...parameters]);
2127
+ else if (parameters.length > 0) {
2128
+ let [primary, ...rest] = parameters;
2129
+ const currentPrimary = attachers[entryIndex][1];
2130
+ if (isPlainObject(currentPrimary) && isPlainObject(primary)) primary = (0, import_extend.default)(true, currentPrimary, primary);
2131
+ attachers[entryIndex] = [
2132
+ plugin,
2133
+ primary,
2134
+ ...rest
2135
+ ];
2136
+ }
2137
+ }
2138
+ }
2139
+ }().freeze();
2140
+ /**
2141
+ * Assert a parser is available.
2142
+ *
2143
+ * @param {string} name
2144
+ * @param {unknown} value
2145
+ * @returns {asserts value is Parser}
2146
+ */
2147
+ function assertParser(name, value) {
2148
+ if (typeof value !== "function") throw new TypeError("Cannot `" + name + "` without `parser`");
2149
+ }
2150
+ /**
2151
+ * Assert a compiler is available.
2152
+ *
2153
+ * @param {string} name
2154
+ * @param {unknown} value
2155
+ * @returns {asserts value is Compiler}
2156
+ */
2157
+ function assertCompiler(name, value) {
2158
+ if (typeof value !== "function") throw new TypeError("Cannot `" + name + "` without `compiler`");
2159
+ }
2160
+ /**
2161
+ * Assert the processor is not frozen.
2162
+ *
2163
+ * @param {string} name
2164
+ * @param {unknown} frozen
2165
+ * @returns {asserts frozen is false}
2166
+ */
2167
+ function assertUnfrozen(name, frozen) {
2168
+ if (frozen) throw new Error("Cannot call `" + name + "` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.");
2169
+ }
2170
+ /**
2171
+ * Assert `node` is a unist node.
2172
+ *
2173
+ * @param {unknown} node
2174
+ * @returns {asserts node is Node}
2175
+ */
2176
+ function assertNode(node) {
2177
+ if (!isPlainObject(node) || typeof node.type !== "string") throw new TypeError("Expected node, got `" + node + "`");
2178
+ }
2179
+ /**
2180
+ * Assert that `complete` is `true`.
2181
+ *
2182
+ * @param {string} name
2183
+ * @param {string} asyncName
2184
+ * @param {unknown} complete
2185
+ * @returns {asserts complete is true}
2186
+ */
2187
+ function assertDone(name, asyncName, complete) {
2188
+ if (!complete) throw new Error("`" + name + "` finished async. Use `" + asyncName + "` instead");
2189
+ }
2190
+ /**
2191
+ * @param {Compatible | undefined} [value]
2192
+ * @returns {VFile}
2193
+ */
2194
+ function vfile(value) {
2195
+ return looksLikeAVFile(value) ? value : new VFile(value);
2196
+ }
2197
+ /**
2198
+ * @param {Compatible | undefined} [value]
2199
+ * @returns {value is VFile}
2200
+ */
2201
+ function looksLikeAVFile(value) {
2202
+ return Boolean(value && typeof value === "object" && "message" in value && "messages" in value);
2203
+ }
2204
+ /**
2205
+ * @param {unknown} [value]
2206
+ * @returns {value is Value}
2207
+ */
2208
+ function looksLikeAValue(value) {
2209
+ return typeof value === "string" || isUint8Array(value);
2210
+ }
2211
+ /**
2212
+ * Assert `value` is an `Uint8Array`.
2213
+ *
2214
+ * @param {unknown} value
2215
+ * thing.
2216
+ * @returns {value is Uint8Array}
2217
+ * Whether `value` is an `Uint8Array`.
2218
+ */
2219
+ function isUint8Array(value) {
2220
+ return Boolean(value && typeof value === "object" && "byteLength" in value && "byteOffset" in value);
2221
+ }
2222
+ //#endregion
2223
+ //#region src/markdown.ts
2224
+ const genId = () => `SVELTE_${Math.random().toString(36).slice(2, 10)}_${Date.now().toString(36)}`;
2225
+ const escapeSvelteText = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\{/g, "&#123;").replace(/\}/g, "&#125;");
2226
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2227
+ const escapeHtmlAttribute = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
2228
+ const escapeHtmlText = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
2229
+ const getExpressionSurrogate = (source) => {
2230
+ const expression = source.slice(1, -1).trim();
2231
+ if (/^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/.test(expression)) return expression.replace(/\./g, " ");
2232
+ const stringMatch = expression.match(/^(['"`])(.+)\1$/);
2233
+ if (stringMatch) return stringMatch[2];
2234
+ return "";
2235
+ };
2236
+ const getComponentSurrogate = (source) => {
2237
+ if (source.startsWith("</")) return "";
2238
+ const match = source.match(/^<([A-Z][\w.$]*)\b/);
2239
+ if (!match) return "";
2240
+ return match[1].split(".").filter(Boolean).join(" ");
2241
+ };
2242
+ const getPlaceholderReplacement = (token, type, original) => {
2243
+ if (type !== "Expression" && type !== "ComponentBoundary") return token;
2244
+ const surrogate = type === "Expression" ? getExpressionSurrogate(original) : getComponentSurrogate(original);
2245
+ return `<svork-placeholder data-svork-id="${escapeHtmlAttribute(token)}">${escapeHtmlText(surrogate)}</svork-placeholder>`;
2246
+ };
2247
+ const isSvelteAttribute = (attr) => {
2248
+ if (!attr || attr.type !== "Attribute") return true;
2249
+ if (Array.isArray(attr.value)) return attr.value.some((valueNode) => valueNode?.type !== "Text");
2250
+ return attr.value?.type === "ExpressionTag";
2251
+ };
2252
+ const maskRange = (chars, start, end) => {
2253
+ for (let i = start; i < end; i++) if (chars[i] !== "\n" && chars[i] !== "\r") chars[i] = " ";
2254
+ };
2255
+ const overlapsRange = (ranges, start, end) => ranges.some((range) => start < range.end && end > range.start);
2256
+ const getScriptRanges = (source) => {
2257
+ const ranges = [];
2258
+ const scriptRegex = /<script\b[\s\S]*?<\/script>/gi;
2259
+ let match;
2260
+ while (match = scriptRegex.exec(source)) ranges.push({
2261
+ start: match.index,
2262
+ end: match.index + match[0].length
2263
+ });
2264
+ return ranges;
2265
+ };
2266
+ const maskMarkdownCodeForSvelteParse = (source) => {
2267
+ const chars = source.split("");
2268
+ const maskedRanges = [];
2269
+ const lines = source.matchAll(/[^\n]*(?:\n|$)/g);
2270
+ let fence = null;
2271
+ for (const lineMatch of lines) {
2272
+ const line = lineMatch[0];
2273
+ const lineStart = lineMatch.index ?? 0;
2274
+ if (line === "" && lineStart === source.length) continue;
2275
+ if (fence) {
2276
+ const closeMarker = line.match(/^( {0,3})(`{3,}|~{3,})\s*(?:\n|$)/)?.[2];
2277
+ if (closeMarker && closeMarker[0] === fence.marker && closeMarker.length >= fence.length) {
2278
+ const end = lineStart + line.length;
2279
+ maskedRanges.push({
2280
+ start: fence.start,
2281
+ end
2282
+ });
2283
+ maskRange(chars, fence.start, end);
2284
+ fence = null;
2285
+ }
2286
+ continue;
2287
+ }
2288
+ const openMarker = line.match(/^( {0,3})(`{3,}|~{3,})/)?.[2];
2289
+ if (openMarker) fence = {
2290
+ marker: openMarker[0],
2291
+ length: openMarker.length,
2292
+ start: lineStart
2293
+ };
2294
+ }
2295
+ if (fence) {
2296
+ maskedRanges.push({
2297
+ start: fence.start,
2298
+ end: source.length
2299
+ });
2300
+ maskRange(chars, fence.start, source.length);
2301
+ }
2302
+ const ignoredInlineRanges = maskedRanges.concat(getScriptRanges(source));
2303
+ const inlineCodeRegex = /(`+)([^\n]*?)\1/g;
2304
+ let inlineMatch;
2305
+ while (inlineMatch = inlineCodeRegex.exec(source)) {
2306
+ const start = inlineMatch.index;
2307
+ const end = start + inlineMatch[0].length;
2308
+ if (overlapsRange(ignoredInlineRanges, start, end)) continue;
2309
+ maskRange(chars, start, end);
2310
+ }
2311
+ return chars.join("");
2312
+ };
2313
+ const escapeSvelteTextBraces = (value) => value.replace(/\{/g, "&#123;").replace(/\}/g, "&#125;");
2314
+ function escapeBracesPlugin() {
2315
+ return (tree) => {
2316
+ const SKIP = new Set(["script", "style"]);
2317
+ const escapeProperties = (properties) => {
2318
+ if (!properties) return;
2319
+ for (const [key, value] of Object.entries(properties)) if (typeof value === "string") properties[key] = escapeSvelteTextBraces(value);
2320
+ else if (Array.isArray(value)) properties[key] = value.map((item) => typeof item === "string" ? escapeSvelteTextBraces(item) : item);
2321
+ };
2322
+ const visit = (node, ancestors) => {
2323
+ if (!node) return;
2324
+ if (node.type === "element") escapeProperties(node.properties);
2325
+ if (node.type === "text") {
2326
+ if (!ancestors.some((a) => a?.type === "element" && typeof a.tagName === "string" && SKIP.has(a.tagName)) && typeof node.value === "string" && (node.value.includes("{") || node.value.includes("}"))) node.value = escapeSvelteTextBraces(node.value);
2327
+ }
2328
+ for (const key of Object.keys(node)) {
2329
+ const child = node[key];
2330
+ if (Array.isArray(child)) for (const c of child) visit(c, ancestors.concat(node));
2331
+ else if (child && typeof child === "object" && child.type) visit(child, ancestors.concat(node));
2332
+ }
2333
+ };
2334
+ visit(tree, []);
2335
+ };
2336
+ }
2337
+ const svelteMarkdown = (options) => {
2338
+ const hasWantedExt = (s) => (options?.extensions ?? [".md"]).some((e) => s.endsWith(e.trim()));
2339
+ const FRONTMATTER_REGEX = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
2340
+ const mdCompiler = unified().use(remarkParse).use(options?.remarkPlugins ?? []).use(remarkRehype, { allowDangerousHtml: true }).use(rehypeRaw).use(options?.rehypePlugins ?? []).use(escapeBracesPlugin).use(rehypeStringify, { allowDangerousHtml: true });
2341
+ return {
2342
+ name: "svelteMarkdown",
2343
+ markup: async ({ content, filename }) => {
2344
+ if (!filename || !hasWantedExt(filename)) return;
2345
+ let metadata = {};
2346
+ let workingString = content;
2347
+ const fmMatch = workingString.match(FRONTMATTER_REGEX);
2348
+ if (fmMatch) {
2349
+ try {
2350
+ metadata = yaml.load(fmMatch[1]) ?? {};
2351
+ } catch (e) {
2352
+ console.error(`[svelteMarkdown] Frontmatter YAML parsing error in ${filename}:`, e);
2353
+ }
2354
+ workingString = workingString.slice(fmMatch[0].length);
2355
+ }
2356
+ const finalize = async (markdownSource, placeholderMap = /* @__PURE__ */ new Map()) => {
2357
+ let compiled = String(await mdCompiler.process(markdownSource));
2358
+ compiled = compiled.replace(/(&amp;#123;|&#x26;#123;)/g, "&#123;").replace(/(&amp;#125;|&#x26;#125;)/g, "&#125;");
2359
+ let restored = compiled;
2360
+ const metadataString = `\nexport const metadata = ${JSON.stringify(metadata)};\n`;
2361
+ for (const [placeholder, info] of placeholderMap.entries()) {
2362
+ const escPlaceholder = escapeRegExp(placeholder);
2363
+ const markerPattern = `<svork-placeholder\\s+data-svork-id=(["'])${escPlaceholder}\\1[^>]*>[\\s\\S]*?<\\/svork-placeholder>`;
2364
+ const markerRegex = new RegExp(markerPattern, "g");
2365
+ if (info.type === "ComponentBoundary" || info.type === "InstanceScript" || info.type === "ModuleScript" || info.type === "EscapedText") {
2366
+ const pMarkerRegex = new RegExp(`<p>\\s*${markerPattern}\\s*</p>`, "g");
2367
+ if (pMarkerRegex.test(restored)) {
2368
+ restored = restored.replace(pMarkerRegex, () => info.original);
2369
+ continue;
2370
+ }
2371
+ }
2372
+ if (markerRegex.test(restored)) {
2373
+ restored = restored.replace(markerRegex, () => info.original);
2374
+ continue;
2375
+ }
2376
+ if (info.type === "InstanceScript" || info.type === "ModuleScript" || info.type === "ComponentBoundary" || info.type === "EscapedText") {
2377
+ const escapedReplacement = escapeRegExp(info.replacement);
2378
+ const pRegex = new RegExp(`<p>\\s*${escapedReplacement}\\s*</p>`, "g");
2379
+ if (pRegex.test(restored)) {
2380
+ restored = restored.replace(pRegex, () => info.original);
2381
+ continue;
2382
+ }
2383
+ }
2384
+ if (info.type === "Expression") {
2385
+ const quotedRegex = new RegExp(`(["'])${escPlaceholder}\\1`, "g");
2386
+ if (quotedRegex.test(restored)) {
2387
+ restored = restored.replace(quotedRegex, () => info.original);
2388
+ continue;
2389
+ }
2390
+ const braceWrappedRegex = new RegExp(`\\{\\s*${escPlaceholder}\\s*\\}`, "g");
2391
+ if (braceWrappedRegex.test(restored)) {
2392
+ restored = restored.replace(braceWrappedRegex, () => info.original);
2393
+ continue;
2394
+ }
2395
+ }
2396
+ restored = restored.replace(new RegExp(placeholder, "g"), () => info.original);
2397
+ }
2398
+ restored = `<script module lang="ts">${metadataString}<\/script>\n` + restored;
2399
+ return restored;
2400
+ };
2401
+ let root;
2402
+ try {
2403
+ root = parse(maskMarkdownCodeForSvelteParse(workingString), { modern: true });
2404
+ } catch (err) {
2405
+ console.warn(`[svelteMarkdown] Svelte AST parsing failed for ${filename}, executing full-text fallback compilation.`);
2406
+ return { code: await finalize(workingString) };
2407
+ }
2408
+ const targets = [];
2409
+ if (root.instance) targets.push({
2410
+ type: "InstanceScript",
2411
+ start: root.instance.start,
2412
+ end: root.instance.end
2413
+ });
2414
+ if (root.module) targets.push({
2415
+ type: "ModuleScript",
2416
+ start: root.module.start,
2417
+ end: root.module.end
2418
+ });
2419
+ const getFragmentBounds = (frag) => {
2420
+ if (frag && Array.isArray(frag.nodes) && frag.nodes.length > 0) return {
2421
+ start: frag.nodes[0].start,
2422
+ end: frag.nodes[frag.nodes.length - 1].end
2423
+ };
2424
+ return null;
2425
+ };
2426
+ const walk = (node) => {
2427
+ if (!node) return;
2428
+ if (node.type === "ExpressionTag") {
2429
+ targets.push({
2430
+ type: "Expression",
2431
+ start: node.start,
2432
+ end: node.end
2433
+ });
2434
+ return;
2435
+ }
2436
+ if (node.type === "RegularElement") {
2437
+ if (node.attributes?.some((attr) => isSvelteAttribute(attr))) {
2438
+ targets.push({
2439
+ type: "EscapedText",
2440
+ start: node.start,
2441
+ end: node.end
2442
+ });
2443
+ return;
2444
+ }
2445
+ }
2446
+ if (node.type === "Component") {
2447
+ const bounds = getFragmentBounds(node.fragment);
2448
+ if (bounds) {
2449
+ targets.push({
2450
+ type: "ComponentBoundary",
2451
+ start: node.start,
2452
+ end: bounds.start
2453
+ });
2454
+ targets.push({
2455
+ type: "ComponentBoundary",
2456
+ start: bounds.end,
2457
+ end: node.end
2458
+ });
2459
+ walk(node.fragment);
2460
+ } else targets.push({
2461
+ type: "ComponentBoundary",
2462
+ start: node.start,
2463
+ end: node.end
2464
+ });
2465
+ return;
2466
+ }
2467
+ if (node.fragment) walk(node.fragment);
2468
+ if (Array.isArray(node.nodes)) for (const child of node.nodes) walk(child);
2469
+ };
2470
+ walk(root.fragment);
2471
+ const validTargets = targets.filter((t) => t.start < t.end);
2472
+ validTargets.sort((a, b) => b.start - a.start);
2473
+ const placeholderMap = /* @__PURE__ */ new Map();
2474
+ let substitutedString = workingString;
2475
+ for (let i = 0; i < validTargets.length; i++) {
2476
+ const target = validTargets[i];
2477
+ const originalSource = substitutedString.slice(target.start, target.end);
2478
+ const original = target.type === "EscapedText" ? escapeSvelteText(originalSource) : originalSource;
2479
+ const id = genId();
2480
+ const placeholder = `SVELTE_${target.type.toUpperCase()}_${id}_${i}_SVELTE`;
2481
+ const replacement = getPlaceholderReplacement(placeholder, target.type, original);
2482
+ placeholderMap.set(placeholder, {
2483
+ original,
2484
+ replacement,
2485
+ type: target.type
2486
+ });
2487
+ substitutedString = substitutedString.slice(0, target.start) + replacement + substitutedString.slice(target.end);
2488
+ }
2489
+ return { code: await finalize(substitutedString, placeholderMap) };
2490
+ }
2491
+ };
2492
+ };
2493
+ //#endregion
2494
+ export { svelteMarkdown };