@skathi-native/cli 0.0.0 → 0.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/vitecompat.ts ADDED
@@ -0,0 +1,1151 @@
1
+ // Vite parity for the builders (prod.ts and build.ts), so an import means the same in both:
2
+ // ?raw (text), ?url / assets (URL; `sk build` packs the file), .svg (a component with
3
+ // vite-svg-loader, else a URL), import.meta.glob (expanded at load time), ?worker (a constructor
4
+ // throwing a named NotSupportedError), .wasm (a stub with an advisory). Unsupported shapes fail by name.
5
+
6
+ import { existsSync, readFileSync, realpathSync, statSync } from "fs";
7
+ import { parse as parseSfc, type SFCTemplateBlock } from "@vue/compiler-sfc";
8
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "path";
9
+
10
+ const J = (v: unknown) => JSON.stringify(v);
11
+ const posix = (p: string) => p.split(sep).join("/");
12
+
13
+ /** The `fs` compileScript resolves imported types through; `fileExists` is files only (`from "."` must land on ./index.ts). */
14
+ export const SFC_FS = {
15
+ fileExists: (file: string) => {
16
+ try {
17
+ return statSync(file).isFile();
18
+ } catch {
19
+ return false;
20
+ }
21
+ },
22
+ readFile: (file: string) => {
23
+ try {
24
+ return readFileSync(file, "utf-8");
25
+ } catch {
26
+ return undefined;
27
+ }
28
+ },
29
+ realpath: (file: string) => {
30
+ try {
31
+ return realpathSync.native(file);
32
+ } catch {
33
+ return file;
34
+ }
35
+ },
36
+ };
37
+
38
+ /** Keys the builders own; an app may not redefine them. */
39
+ const RESERVED_DEFINES = new Set([
40
+ "__DEV__",
41
+ "process.env.NODE_ENV",
42
+ "import.meta",
43
+ "import.meta.url",
44
+ "import.meta.hot",
45
+ "import.meta.env",
46
+ "import.meta.glob",
47
+ ]);
48
+ const DEFINE_KEY = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/;
49
+ const IDENT_PATH = DEFINE_KEY;
50
+
51
+ /** Is `code` a value Bun's `define` inserts as code? Anything but JSON or an identifier path becomes a string literal, so it is refused. */
52
+ function isDefineCode(code: string): boolean {
53
+ if (IDENT_PATH.test(code)) return true;
54
+ try {
55
+ JSON.parse(code);
56
+ return true;
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ export interface AppDefines {
63
+ defines: Record<string, string>;
64
+ errors: string[];
65
+ }
66
+
67
+ /** Vite's `define` from `sk.config.json` and the command line; `--define K=V` wins over the file. */
68
+ export function appDefines(configDefine: unknown, cli: string[], where = "sk.config.json"): AppDefines {
69
+ const defines: Record<string, string> = {};
70
+ const errors: string[] = [];
71
+ const put = (key: string, code: string, from: string) => {
72
+ if (!DEFINE_KEY.test(key)) {
73
+ errors.push(`${from}: define key ${J(key)} is not an identifier or a dotted path`);
74
+ return;
75
+ }
76
+ if (RESERVED_DEFINES.has(key)) {
77
+ errors.push(`${from}: define ${J(key)} is set by the builder and cannot be overridden`);
78
+ return;
79
+ }
80
+ if (!isDefineCode(code)) {
81
+ errors.push(
82
+ `${from}: define ${key} = ${J(code)} is neither JSON nor an identifier — Bun would insert it as a ` +
83
+ `string. A string value must carry its own quotes (Vite's rule): ${J(J(code))}`,
84
+ );
85
+ return;
86
+ }
87
+ defines[key] = code;
88
+ };
89
+ if (configDefine !== undefined) {
90
+ if (!configDefine || typeof configDefine !== "object" || Array.isArray(configDefine)) {
91
+ errors.push(`${where}: "define" must be an object`);
92
+ } else {
93
+ for (const [k, v] of Object.entries(configDefine as Record<string, unknown>)) {
94
+ if (k.startsWith("$")) continue;
95
+ put(k, typeof v === "string" ? v : J(v), `${where} "define"`);
96
+ }
97
+ }
98
+ }
99
+ for (const arg of cli) {
100
+ const i = arg.indexOf("=");
101
+ if (i <= 0) {
102
+ errors.push(`--define ${J(arg)}: expected KEY=VALUE`);
103
+ continue;
104
+ }
105
+ put(arg.slice(0, i).trim(), arg.slice(i + 1), "--define");
106
+ }
107
+ return { defines, errors };
108
+ }
109
+
110
+ export function takeDefineArgs(argv: string[]): { defines: string[]; rest: string[] } {
111
+ const defines: string[] = [];
112
+ const rest: string[] = [];
113
+ for (let i = 0; i < argv.length; i++) {
114
+ const a = argv[i]!;
115
+ if (a === "--define") {
116
+ if (i + 1 < argv.length) defines.push(argv[++i]!);
117
+ } else if (a.startsWith("--define=")) defines.push(a.slice("--define=".length));
118
+ else rest.push(a);
119
+ }
120
+ return { defines, rest };
121
+ }
122
+
123
+ export const ASSET_EXT =
124
+ /\.(apng|bmp|png|jpe?g|jfif|pjpeg|pjp|gif|ico|webp|avif|cur|jxl|mp4|webm|ogg|mp3|wav|flac|aac|opus|mov|m4a|vtt|woff2?|eot|ttf|otf|webmanifest|pdf|txt)$/i;
125
+
126
+ /**
127
+ * The payload key and URL of an imported file: root-relative inside the document root (one URL
128
+ * works dev and packaged), else a content-addressed `_vn/fs/` key.
129
+ */
130
+ export function assetKey(absPath: string, docRoot: string): { key: string; url: string } {
131
+ const rel = relative(docRoot, absPath);
132
+ let key: string;
133
+ if (!rel || rel.startsWith("..") || isAbsolute(rel)) {
134
+ const h = Bun.hash(posix(resolve(absPath)).toLowerCase())
135
+ .toString(16)
136
+ .slice(0, 8);
137
+ key = `_vn/fs/${h}/${basename(absPath)}`;
138
+ } else {
139
+ key = posix(rel);
140
+ }
141
+ const url = "/" + key.split("/").map(encodeURIComponent).join("/");
142
+ return { key, url };
143
+ }
144
+
145
+ type Lit = string | number | boolean | null | Lit[] | { [k: string]: Lit };
146
+
147
+ class LitParser {
148
+ i = 0;
149
+ constructor(readonly s: string) {}
150
+ ws() {
151
+ for (;;) {
152
+ while (this.i < this.s.length && /\s/.test(this.s[this.i]!)) this.i++;
153
+ if (this.s.startsWith("//", this.i)) {
154
+ const nl = this.s.indexOf("\n", this.i);
155
+ this.i = nl < 0 ? this.s.length : nl + 1;
156
+ } else if (this.s.startsWith("/*", this.i)) {
157
+ const end = this.s.indexOf("*/", this.i + 2);
158
+ this.i = end < 0 ? this.s.length : end + 2;
159
+ } else return;
160
+ }
161
+ }
162
+ fail(what: string): never {
163
+ throw new Error(`${what} at offset ${this.i}`);
164
+ }
165
+ value(): Lit {
166
+ this.ws();
167
+ const c = this.s[this.i];
168
+ if (c === "'" || c === '"' || c === "`") return this.str();
169
+ if (c === "[") {
170
+ this.i++;
171
+ const out: Lit[] = [];
172
+ for (;;) {
173
+ this.ws();
174
+ if (this.s[this.i] === "]") {
175
+ this.i++;
176
+ return out;
177
+ }
178
+ out.push(this.value());
179
+ this.ws();
180
+ if (this.s[this.i] === ",") this.i++;
181
+ else if (this.s[this.i] !== "]") this.fail("expected , or ]");
182
+ }
183
+ }
184
+ if (c === "{") {
185
+ this.i++;
186
+ const out: { [k: string]: Lit } = {};
187
+ for (;;) {
188
+ this.ws();
189
+ if (this.s[this.i] === "}") {
190
+ this.i++;
191
+ return out;
192
+ }
193
+ let key: string;
194
+ const q = this.s[this.i];
195
+ if (q === "'" || q === '"') key = this.str();
196
+ else {
197
+ const m = /^[A-Za-z_$][\w$]*/.exec(this.s.slice(this.i));
198
+ if (!m) this.fail("expected a property name");
199
+ key = m[0];
200
+ this.i += key.length;
201
+ }
202
+ this.ws();
203
+ if (this.s[this.i] !== ":") this.fail(`expected : after ${key}`);
204
+ this.i++;
205
+ out[key] = this.value();
206
+ this.ws();
207
+ if (this.s[this.i] === ",") this.i++;
208
+ else if (this.s[this.i] !== "}") this.fail("expected , or }");
209
+ }
210
+ }
211
+ const m = /^(true|false|null|-?\d+(\.\d+)?)/.exec(this.s.slice(this.i));
212
+ if (m) {
213
+ this.i += m[0].length;
214
+ return JSON.parse(m[0]);
215
+ }
216
+ this.fail("not a literal (import.meta.glob arguments must be literals — Vite's rule too)");
217
+ }
218
+ str(): string {
219
+ const q = this.s[this.i++]!;
220
+ let out = "";
221
+ while (this.i < this.s.length && this.s[this.i] !== q) {
222
+ const ch = this.s[this.i]!;
223
+ if (q === "`" && ch === "$" && this.s[this.i + 1] === "{") this.fail("template interpolation in a glob argument");
224
+ if (ch === "\\") {
225
+ out += this.s[this.i + 1] ?? "";
226
+ this.i += 2;
227
+ } else {
228
+ out += ch;
229
+ this.i++;
230
+ }
231
+ }
232
+ if (this.s[this.i] !== q) this.fail("unterminated string");
233
+ this.i++;
234
+ return out;
235
+ }
236
+ }
237
+
238
+ function closingParen(s: string, open: number): number {
239
+ let depth = 0;
240
+ for (let i = open; i < s.length; i++) {
241
+ const c = s[i]!;
242
+ if (c === "'" || c === '"' || c === "`") {
243
+ for (i++; i < s.length && s[i] !== c; i++) if (s[i] === "\\") i++;
244
+ } else if (c === "/" && s[i + 1] === "/") {
245
+ const nl = s.indexOf("\n", i);
246
+ i = nl < 0 ? s.length : nl;
247
+ } else if (c === "/" && s[i + 1] === "*") {
248
+ const end = s.indexOf("*/", i + 2);
249
+ i = end < 0 ? s.length : end + 1;
250
+ } else if (c === "(" || c === "[" || c === "{") depth++;
251
+ else if (c === ")" || c === "]" || c === "}") {
252
+ depth--;
253
+ if (depth === 0) return i + 1;
254
+ }
255
+ }
256
+ return -1;
257
+ }
258
+
259
+ const GLOB_OPTIONS = new Set(["eager", "import", "query", "as", "exhaustive", "base"]);
260
+ const GLOB_CHAR = /[*?[\]{}!]/;
261
+
262
+ export interface GlobContext {
263
+ file: string;
264
+ docRoot: string;
265
+ /** Dev form: import each match by importer-relative path (prod imports by absolute path). */
266
+ relativeSpecs?: boolean | undefined;
267
+ }
268
+
269
+ function splitGlob(pattern: string): [string, string] {
270
+ const segs = pattern.split("/");
271
+ const at = segs.findIndex((s) => GLOB_CHAR.test(s));
272
+ if (at < 0) return [segs.slice(0, -1).join("/") || ".", segs[segs.length - 1]!];
273
+ return [segs.slice(0, at).join("/") || ".", segs.slice(at).join("/")];
274
+ }
275
+
276
+ function globBase(pattern: string, ctx: GlobContext): string {
277
+ if (pattern.startsWith("./") || pattern.startsWith("../")) return dirname(ctx.file);
278
+ if (pattern.startsWith("/")) return ctx.docRoot;
279
+ throw new Error(
280
+ `import.meta.glob(${J(pattern)}): only relative ("./", "../") and root ("/") patterns are supported — ` +
281
+ `an alias pattern needs resolving first, which Skathi's builder does not do yet`,
282
+ );
283
+ }
284
+
285
+ function globFiles(pattern: string, ctx: GlobContext, exhaustive: boolean): string[] {
286
+ const base = globBase(pattern, ctx);
287
+ const [dir, glob] = splitGlob(pattern.startsWith("/") ? "." + pattern : pattern);
288
+ const cwd = resolve(base, dir);
289
+ if (!existsSync(cwd)) return [];
290
+ const out: string[] = [];
291
+ const throughModules = exhaustive || pattern.includes("node_modules");
292
+ for (const rel of new Bun.Glob(glob).scanSync({ cwd, onlyFiles: true, dot: exhaustive })) {
293
+ const p = posix(rel);
294
+ if (!throughModules && p.split("/").includes("node_modules")) continue;
295
+ out.push(resolve(cwd, rel));
296
+ }
297
+ return out;
298
+ }
299
+
300
+ function queryString(q: Lit | undefined): string {
301
+ if (q === undefined || q === null || q === "") return "";
302
+ if (typeof q === "string") return q.startsWith("?") ? q : `?${q}`;
303
+ if (typeof q === "object" && !Array.isArray(q)) {
304
+ const parts = Object.entries(q).map(([k, v]) => (v === true || v === "" ? k : `${k}=${String(v)}`));
305
+ return parts.length ? `?${parts.join("&")}` : "";
306
+ }
307
+ throw new Error(`import.meta.glob: "query" must be a string or an object`);
308
+ }
309
+
310
+ /**
311
+ * Expands every `import.meta.glob(...)` in `src` as Vite does; `null` when there is nothing to
312
+ * expand. `base` rebases the keys; `node_modules` is skipped unless named or `exhaustive`.
313
+ */
314
+ export function expandGlobs(src: string, ctx: GlobContext): { code: string; count: number; files: number } | null {
315
+ if (!src.includes("import.meta.glob")) return null;
316
+ const re = /\bimport\.meta\.glob\b/g;
317
+ const header: string[] = [];
318
+ let out = "";
319
+ let last = 0;
320
+ let call = 0;
321
+ let files = 0;
322
+ const lineOf = (i: number) => src.slice(0, i).split("\n").length;
323
+ for (let m = re.exec(src); m; m = re.exec(src)) {
324
+ const start = m.index;
325
+ let i = start + m[0].length;
326
+ while (/\s/.test(src[i] ?? "")) i++;
327
+ if (src[i] === "<") {
328
+ let depth = 0;
329
+ for (; i < src.length; i++) {
330
+ if (src[i] === "<") depth++;
331
+ else if (src[i] === ">" && --depth === 0) {
332
+ i++;
333
+ break;
334
+ }
335
+ }
336
+ while (/\s/.test(src[i] ?? "")) i++;
337
+ }
338
+ if (src[i] !== "(") continue; // a mention, not a call (`typeof import.meta.glob`)
339
+ const end = closingParen(src, i);
340
+ const where = `${ctx.file}:${lineOf(start)}`;
341
+ if (end < 0) throw new Error(`${where}: unterminated import.meta.glob(`);
342
+ const p = new LitParser(src.slice(i + 1, end - 1));
343
+ let patterns: Lit;
344
+ let options: Lit = {};
345
+ try {
346
+ patterns = p.value();
347
+ p.ws();
348
+ if (p.s[p.i] === ",") {
349
+ p.i++;
350
+ p.ws();
351
+ if (p.i < p.s.length) options = p.value();
352
+ }
353
+ p.ws();
354
+ if (p.s[p.i] === ",") p.i++;
355
+ p.ws();
356
+ if (p.i < p.s.length) p.fail("unexpected trailing argument");
357
+ } catch (e) {
358
+ throw new Error(`${where}: import.meta.glob: ${(e as Error).message}`);
359
+ }
360
+ const list = typeof patterns === "string" ? [patterns] : patterns;
361
+ if (!Array.isArray(list) || !list.every((x) => typeof x === "string") || !list.length) {
362
+ throw new Error(`${where}: import.meta.glob: the first argument must be a string or an array of strings`);
363
+ }
364
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
365
+ throw new Error(`${where}: import.meta.glob: the options must be an object literal`);
366
+ }
367
+ const opts = options as Record<string, Lit>;
368
+ for (const k of Object.keys(opts)) {
369
+ if (!GLOB_OPTIONS.has(k)) throw new Error(`${where}: import.meta.glob: unknown option ${J(k)}`);
370
+ }
371
+ let importName = opts.import as string | undefined;
372
+ let query = opts.query;
373
+ if (opts.as !== undefined) {
374
+ // Vite 4's `as`, deprecated in Vite 5: `as: "raw" | "url"` == query + default.
375
+ if (opts.as !== "raw" && opts.as !== "url") {
376
+ throw new Error(`${where}: import.meta.glob: "as" must be "raw" or "url"`);
377
+ }
378
+ query = `?${opts.as}`;
379
+ importName ??= "default";
380
+ }
381
+ const qs = (() => {
382
+ try {
383
+ return queryString(query);
384
+ } catch (e) {
385
+ throw new Error(`${where}: ${(e as Error).message}`);
386
+ }
387
+ })();
388
+ const eager = opts.eager === true;
389
+ const exhaustive = opts.exhaustive === true;
390
+ const positive = (list as string[]).filter((x) => !x.startsWith("!"));
391
+ const negative = (list as string[]).filter((x) => x.startsWith("!")).map((x) => x.slice(1));
392
+ const matched = new Set<string>();
393
+ try {
394
+ for (const pat of positive) for (const f of globFiles(pat, ctx, exhaustive)) matched.add(f);
395
+ for (const pat of negative) for (const f of globFiles(pat, ctx, true)) matched.delete(f);
396
+ } catch (e) {
397
+ throw new Error(`${where}: ${(e as Error).message}`);
398
+ }
399
+ matched.delete(resolve(ctx.file));
400
+ const rooted = positive[0]!.startsWith("/");
401
+ const keyBase =
402
+ typeof opts.base === "string"
403
+ ? resolve(opts.base.startsWith("/") ? ctx.docRoot : dirname(ctx.file), opts.base.replace(/^\//, "./"))
404
+ : rooted
405
+ ? ctx.docRoot
406
+ : dirname(ctx.file);
407
+ const keyed = [...matched].map((f) => {
408
+ const rel = posix(relative(keyBase, f));
409
+ const key = rooted && opts.base === undefined ? `/${rel}` : rel.startsWith("../") ? rel : `./${rel}`;
410
+ if (!ctx.relativeSpecs) return { key, spec: posix(f) + qs };
411
+ const near = posix(relative(dirname(ctx.file), f));
412
+ return { key, spec: (near.startsWith("../") ? near : `./${near}`) + qs };
413
+ });
414
+ keyed.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
415
+ const entries = keyed.map(({ key, spec }, n) => {
416
+ if (eager) {
417
+ const v = `__sk_glob_${call}_${n}`;
418
+ header.push(
419
+ importName && importName !== "*"
420
+ ? `import { ${importName === "default" ? "default" : importName} as ${v} } from ${J(spec)};`
421
+ : `import * as ${v} from ${J(spec)};`,
422
+ );
423
+ return `${J(key)}: ${v}`;
424
+ }
425
+ const load = `() => import(${J(spec)})`;
426
+ return `${J(key)}: ${importName && importName !== "*" ? `${load}.then((m) => m[${J(importName)}])` : load}`;
427
+ });
428
+ files += keyed.length;
429
+ out += src.slice(last, start) + `({ ${entries.join(", ")} })`;
430
+ last = end;
431
+ re.lastIndex = end;
432
+ call++;
433
+ }
434
+ if (!call) return null;
435
+ out += src.slice(last);
436
+ // A shebang has to stay on line 1.
437
+ const bang = out.startsWith("#!") ? out.indexOf("\n") + 1 : 0;
438
+ const code = out.slice(0, bang) + header.join("\n") + (header.length ? "\n" : "") + out.slice(bang);
439
+ return { code, count: call, files };
440
+ }
441
+
442
+ /** The advisory prefix runtime.ts's `warnCompat` uses — one grep finds both. */
443
+ const ADVISE = "[skathi compat]";
444
+
445
+ function notSupportedError(what: string, why: string): string {
446
+ const msg = `${what}: ${why}`;
447
+ return (
448
+ `(() => { const m = ${J(msg)}; console.warn(${J(ADVISE + " ")} + m); ` +
449
+ `return typeof DOMException === "function" ? new DOMException(m, "NotSupportedError") ` +
450
+ `: Object.assign(new Error(m), { name: "NotSupportedError" }); })()`
451
+ );
452
+ }
453
+
454
+ const WORKERS_WHY = "Skathi has no Web Workers yet — run the work on the main thread for now";
455
+
456
+ export function workerStubModule(id: string, url = false): string {
457
+ if (url) {
458
+ return `console.warn(${J(`${ADVISE} ${id}?worker&url: ${WORKERS_WHY}`)});\nexport default ${J(`sk-unsupported:worker/${id}`)};\n`;
459
+ }
460
+ return (
461
+ `export default class SkWorkerUnavailable {\n` +
462
+ ` constructor() { throw ${notSupportedError(`new Worker(${id}?worker)`, WORKERS_WHY)}; }\n` +
463
+ `}\n`
464
+ );
465
+ }
466
+
467
+ /** `new Worker(new URL("./w.ts", import.meta.url))` becomes the same named-error class as `?worker`. */
468
+ export function stubWorkerUrls(src: string, file: string): { code: string; count: number } | null {
469
+ if (!/\bnew\s+(?:Shared)?Worker\s*\(\s*new\s+URL\s*\(/.test(src)) return null;
470
+ let count = 0;
471
+ const code = src.replace(
472
+ /\bnew\s+(Shared)?Worker\s*\(\s*(new\s+URL\s*\(\s*(['"`])([^'"`]+)\3\s*,\s*import\.meta\.url\s*\))/g,
473
+ (_m, shared: string | undefined, urlExpr: string, _q: string, spec: string) => {
474
+ count++;
475
+ const what = `new ${shared ? "Shared" : ""}Worker(new URL(${J(spec)}, import.meta.url)) in ${file}`;
476
+ return `new (class SkWorkerUnavailable { constructor() { throw ${notSupportedError(what, WORKERS_WHY)}; } })(${urlExpr}`;
477
+ },
478
+ );
479
+ return count ? { code, count } : null;
480
+ }
481
+
482
+ const WASM_WHY = "WebAssembly is out of scope for Skathi; " + "the native replacement is a host binding";
483
+
484
+ export function wasmStubModule(id: string, query: Set<string>): string {
485
+ const advise = `console.warn(${J(`${ADVISE} ${id}: not bundled — ${WASM_WHY}`)});\n`;
486
+ if (query.has("url")) return advise + `export default ${J(`sk-unsupported:wasm/${id}`)};\n`;
487
+ return advise + `export default function init() { return Promise.reject(${notSupportedError(id, WASM_WHY)}); }\n`;
488
+ }
489
+
490
+ export function svgDefaultOf(appPkg: Record<string, unknown> | null): "component" | "url" {
491
+ if (!appPkg) return "url";
492
+ for (const k of ["dependencies", "devDependencies"]) {
493
+ const deps = appPkg[k];
494
+ if (deps && typeof deps === "object" && "vite-svg-loader" in (deps as object)) return "component";
495
+ }
496
+ return "url";
497
+ }
498
+
499
+ export function svgAsSfc(svg: string): string {
500
+ const body = svg
501
+ .replace(/<\?xml[\s\S]*?\?>/g, "")
502
+ .replace(/<!DOCTYPE[^>]*>/gi, "")
503
+ .replace(/<!--[\s\S]*?-->/g, "")
504
+ // vite-svg-loader's rewrite: a `<style>` inside the SVG must survive the template compiler.
505
+ .replace(/<style/g, '<component is="style"')
506
+ .replace(/<\/style>/g, "</component>")
507
+ .trim();
508
+ return `<template>${body}</template>`;
509
+ }
510
+
511
+ export interface ShapesOptions {
512
+ sourceLoaded?: ((file: string, source: string, transformed: string) => void) | undefined;
513
+ /** The document root: where `sk.config.json` / `index.html` live. URLs and `/` globs start here. */
514
+ docRoot: string;
515
+ wsRoot: string;
516
+ svgDefault: "component" | "url";
517
+ compileSfc: (
518
+ absPath: string,
519
+ source: string,
520
+ ) => { contents: string; loader: "js" | "ts" } | Promise<{ contents: string; loader: "js" | "ts" }>;
521
+ assets: Map<string, string>;
522
+ notes: Map<string, number>;
523
+ /** The dev builder: one module per file, imports left to its registry. */
524
+ dev?: boolean | undefined;
525
+ /** Called with each file a `?query` import builds into its importer, so a watcher can rebuild the importer. */
526
+ inlined?: ((absPath: string) => void) | undefined;
527
+ }
528
+
529
+ /**
530
+ * Resolves an import specifier as the bundler does (tsconfig `paths`, package `exports`, browser
531
+ * field). build.ts calls it directly because its per-module builds leave imports external.
532
+ */
533
+ export function resolveImport(spec: string, fromDir: string): string | null {
534
+ try {
535
+ return Bun.resolveSync(spec, fromDir);
536
+ } catch {
537
+ return null;
538
+ }
539
+ }
540
+
541
+ export const importerDir = (args: { resolveDir?: string; importer?: string }, fallback: string) =>
542
+ args.resolveDir || (args.importer ? dirname(args.importer) : fallback);
543
+
544
+ const NS = "sk-vite";
545
+ const KINDS = ["raw", "url", "inline", "worker", "sharedworker", "component", "init"];
546
+
547
+ function note(o: ShapesOptions, what: string) {
548
+ o.notes.set(what, (o.notes.get(what) ?? 0) + 1);
549
+ }
550
+
551
+ export function loaderOf(path: string): "ts" | "tsx" | "js" | "jsx" {
552
+ const ext = extname(path).toLowerCase();
553
+ if (ext === ".tsx") return "tsx";
554
+ if (ext === ".jsx") return "jsx";
555
+ if (ext === ".ts" || ext === ".mts" || ext === ".cts") return "ts";
556
+ return "js";
557
+ }
558
+
559
+ export function transformSource(
560
+ code: string,
561
+ file: string,
562
+ o: Pick<ShapesOptions, "docRoot" | "wsRoot" | "notes" | "dev">,
563
+ ): string | null {
564
+ let changed = false;
565
+ const add = (what: string, n: number) => o.notes.set(what, (o.notes.get(what) ?? 0) + n);
566
+ const g = expandGlobs(code, { file, docRoot: o.docRoot, relativeSpecs: o.dev });
567
+ if (g) {
568
+ code = g.code;
569
+ changed = true;
570
+ add("import.meta.glob calls expanded", g.count);
571
+ add("import.meta.glob files matched", g.files);
572
+ }
573
+ const w = stubWorkerUrls(code, posix(relative(o.wsRoot, file)));
574
+ if (w) {
575
+ code = w.code;
576
+ changed = true;
577
+ add("new Worker(new URL(…)) stubbed (no Workers yet)", w.count);
578
+ }
579
+ return changed ? code : null;
580
+ }
581
+
582
+ /** Bun plugin for the import shapes above. Register it BEFORE the SFC plugin. */
583
+ export function viteShapesPlugin(o: ShapesOptions) {
584
+ const idOf = (abs: string) => posix(relative(o.wsRoot, abs));
585
+ const urlModule = (abs: string) => {
586
+ const { key, url } = assetKey(abs, o.docRoot);
587
+ o.assets.set(key, realpathSync(abs));
588
+ return `export default ${J(url)};\n`;
589
+ };
590
+ return {
591
+ name: "sk-vite-shapes",
592
+ setup(build: Bun.PluginBuilder) {
593
+ // A `?query` specifier: the query stays in the path of our own namespace, since Bun keys modules
594
+ // by path (`a.svg?raw` and `a.svg` would collapse) and pluginData does not reach onLoad in Bun 1.4.
595
+ build.onResolve({ filter: /\?[\w&=.-]+$/ }, (args: Bun.OnResolveArgs) => {
596
+ const q = args.path.lastIndexOf("?");
597
+ const bare = args.path.slice(0, q);
598
+ const params = new Set(
599
+ args.path
600
+ .slice(q + 1)
601
+ .split("&")
602
+ .map((p: string) => p.split("=")[0]),
603
+ );
604
+ if (![...params].some((p) => KINDS.includes(p as string))) return undefined;
605
+ const real = resolveImport(bare, importerDir(args, o.docRoot));
606
+ if (real === null) return undefined; // let Bun report the unresolvable import itself
607
+ o.inlined?.(real);
608
+ return { path: `${real}?${args.path.slice(q + 1)}`, namespace: NS };
609
+ });
610
+ build.onLoad({ filter: /.*/, namespace: NS }, async (args: Bun.OnLoadArgs) => {
611
+ const q = args.path.lastIndexOf("?");
612
+ const file = args.path.slice(0, q);
613
+ const params = new Set<string>(
614
+ args.path
615
+ .slice(q + 1)
616
+ .split("&")
617
+ .map((p: string) => p.split("=")[0]!),
618
+ );
619
+ const id = idOf(file);
620
+ const isWasm = /\.wasm$/i.test(file);
621
+ if (params.has("worker") || params.has("sharedworker")) {
622
+ note(o, `?worker stubbed (no Workers yet)`);
623
+ return { contents: workerStubModule(id, params.has("url")), loader: "js" };
624
+ }
625
+ if (isWasm) {
626
+ note(o, `.wasm stubbed (WebAssembly out of scope)`);
627
+ return { contents: wasmStubModule(id, params), loader: "js" };
628
+ }
629
+ if (params.has("raw")) {
630
+ note(o, `?raw`);
631
+ return { contents: `export default ${J(await Bun.file(file).text())};\n`, loader: "js" };
632
+ }
633
+ if (params.has("component") && /\.svg$/i.test(file)) {
634
+ note(o, `.svg as a component`);
635
+ return o.compileSfc(file + ".vue", svgAsSfc(await Bun.file(file).text()));
636
+ }
637
+ if (params.has("inline")) {
638
+ note(o, `?inline`);
639
+ if (/\.css$/i.test(file))
640
+ return { contents: `export default ${J(await Bun.file(file).text())};\n`, loader: "js" };
641
+ const bytes = Buffer.from(await Bun.file(file).arrayBuffer());
642
+ const mime = Bun.file(file).type.split(";")[0] || "application/octet-stream";
643
+ return {
644
+ contents: `export default ${J(`data:${mime};base64,${bytes.toString("base64")}`)};\n`,
645
+ loader: "js",
646
+ };
647
+ }
648
+ note(o, `?url (packed as an asset)`);
649
+ return { contents: urlModule(file), loader: "js" };
650
+ });
651
+ build.onLoad({ filter: /\.svg$/i }, async (args: Bun.OnLoadArgs) => {
652
+ if (o.svgDefault === "component") {
653
+ note(o, `.svg as a component`);
654
+ return o.compileSfc(args.path + ".vue", svgAsSfc(await Bun.file(args.path).text()));
655
+ }
656
+ note(o, `asset URL (packed as an asset)`);
657
+ return { contents: urlModule(args.path), loader: "js" };
658
+ });
659
+ // Any other asset: its URL (Bun's file loader would emit a hashed copy nothing packs).
660
+ build.onLoad({ filter: ASSET_EXT }, (args: Bun.OnLoadArgs) => {
661
+ note(o, `asset URL (packed as an asset)`);
662
+ return { contents: urlModule(args.path), loader: "js" };
663
+ });
664
+ build.onLoad({ filter: /\.wasm$/i }, (args: Bun.OnLoadArgs) => {
665
+ note(o, `.wasm stubbed (WebAssembly out of scope)`);
666
+ return { contents: wasmStubModule(idOf(args.path), new Set()), loader: "js" };
667
+ });
668
+ build.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (args: Bun.OnLoadArgs) => {
669
+ const src = await Bun.file(args.path).text();
670
+ const code =
671
+ src.includes("import.meta.glob") || src.includes("new URL") ? transformSource(src, args.path, o) : null;
672
+ o.sourceLoaded?.(args.path, src, code ?? src);
673
+ return code === null ? undefined : { contents: code, loader: loaderOf(args.path) };
674
+ });
675
+ },
676
+ };
677
+ }
678
+
679
+ export const LEAF_IMPORT = new RegExp(`\\.(?:json|svg|wasm)$|${ASSET_EXT.source}`, "i");
680
+
681
+ export interface DevImportsOptions {
682
+ srcDir: string;
683
+ preseeded: (spec: string) => boolean;
684
+ inlined?: (absPath: string) => void;
685
+ /** Registry id of the npm module a bare import outside the source root loads; undefined leaves the specifier as written. */
686
+ npmId?: (spec: string, absPath: string, fromDir: string) => string | undefined;
687
+ }
688
+
689
+ /**
690
+ * The dev builder's resolution: each file is built with every import external, so this does what
691
+ * prod's bundle does. A tsconfig `paths` alias into the source root becomes the importer-relative
692
+ * path (one graph edge, one instance); data and asset files are built into the importer (register
693
+ * `viteShapesPlugin` first); an npm import gets the id `npmId` gives it.
694
+ */
695
+ export function devImportsPlugin(o: DevImportsOptions) {
696
+ const inSrc = (abs: string) => {
697
+ const rel = relative(o.srcDir, abs);
698
+ return !!rel && !rel.startsWith("..") && !isAbsolute(rel);
699
+ };
700
+ return {
701
+ name: "sk-dev-imports",
702
+ setup(build: Bun.PluginBuilder) {
703
+ build.onResolve({ filter: LEAF_IMPORT }, (args: Bun.OnResolveArgs) => {
704
+ if (args.kind === "entry-point-build") return undefined;
705
+ const abs = resolveImport(args.path, importerDir(args, o.srcDir));
706
+ if (abs === null || !isAbsolute(abs)) return undefined; // external: build.ts reports the miss
707
+ o.inlined?.(abs);
708
+ return { path: abs };
709
+ });
710
+ // Bare specifiers only: an absolute path is the entry point (Windows `C:\…` starts with a letter).
711
+ // `node:` stays out of the filter: a plugin that sees Bun's own `node:module` import makes it a real require.
712
+ build.onResolve({ filter: /^(?!node:)[^./\\]/ }, (args: Bun.OnResolveArgs) => {
713
+ if (args.kind === "entry-point-build" || isAbsolute(args.path) || o.preseeded(args.path)) return undefined;
714
+ const from = importerDir(args, o.srcDir);
715
+ const abs = resolveImport(args.path, from);
716
+ if (abs === null || !isAbsolute(abs)) return undefined;
717
+ if (!inSrc(abs)) {
718
+ if (/\.css$/i.test(abs)) return undefined;
719
+ const id = o.npmId?.(args.path, abs, from);
720
+ return id === undefined ? undefined : { path: id, external: true };
721
+ }
722
+ const rel = posix(relative(from, abs));
723
+ return { path: rel.startsWith("../") ? rel : `./${rel}`, external: true };
724
+ });
725
+ },
726
+ };
727
+ }
728
+
729
+ export const GLOB_TRIPWIRE = "__sk_import_meta_glob_unexpanded";
730
+
731
+ // Bun builds each `import * as ns` / `import()` namespace as a plain `{}` without `__esModule` or
732
+ // toStringTag "Module", so Vue's defineAsyncComponent mounts the namespace itself. Mark them as modules.
733
+
734
+ const BUN_EXPORT_HELPER =
735
+ /(\(\s*([\w$]+)\s*,\s*([\w$]+)\s*\)\s*=>\s*\{)(\s*for\s*\(\s*var\s+([\w$]+)\s+in\s+\3\s*\)\s*[\w$]+\(\s*\2\s*,\s*\5\s*,\s*\{\s*get\s*:\s*\3\[\5\]\s*,\s*enumerable\s*:\s*(?:!0|true)\s*,\s*configurable\s*:\s*(?:!0|true))/g;
736
+ const BUN_EXPORT_SIGNATURE =
737
+ /get\s*:\s*([\w$]+)\[([\w$]+)\]\s*,\s*enumerable\s*:\s*(?:!0|true)\s*,\s*configurable\s*:\s*(?:!0|true)\s*,\s*set\s*:\s*[\w$]+\.bind\(\s*\1\s*,\s*\2\s*\)/;
738
+
739
+ /** Makes every namespace object a bundle builds look like a module namespace. Throws on an unrecognised `__export` helper shape, so a Bun upgrade fails the build. */
740
+ export function tagModuleNamespaces(bundle: string): { code: string; count: number } {
741
+ let count = 0;
742
+ const code = bundle.replace(BUN_EXPORT_HELPER, (_m, head: string, target: string, _all: string, loop: string) => {
743
+ count++;
744
+ return (
745
+ `${head}Object.setPrototypeOf(${target},null),` +
746
+ `Object.defineProperty(${target},Symbol.toStringTag,{value:"Module"});${loop}`
747
+ );
748
+ });
749
+ if (count === 0 && BUN_EXPORT_SIGNATURE.test(bundle)) {
750
+ throw new Error(
751
+ "the bundle's __export helper is not in the shape vitecompat.ts tagModuleNamespaces knows: " +
752
+ 'namespace objects would lack Symbol.toStringTag "Module", and defineAsyncComponent(() => import(…)) ' +
753
+ "would render nothing — update BUN_EXPORT_HELPER for this Bun version",
754
+ );
755
+ }
756
+ return { code, count };
757
+ }
758
+
759
+ const DYNAMIC_IMPORT = /(?<![\w$.])import\(\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*\)/g;
760
+ const DYNAMIC_IMPORT_ANY = /(?<![\w$.])import\(\s*(?!["'])/g;
761
+ const NODE_MODE_TO_ESM = /\b__toESM\((require\(\s*(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*\))\s*,\s*1\s*\)/g;
762
+
763
+ /**
764
+ * The dev builder's per-module CJS, corrected to bundler ESM semantics: `__toESM(require(x), 1)`
765
+ * makes `default` the whole `module.exports`, so the `1` is dropped; `import("./X.vue")` becomes a
766
+ * promise of the exports through the registry `require`. Returns the body and the count of
767
+ * `import(...)` with a non-literal specifier (these still reject at runtime).
768
+ */
769
+ export function devEsmInterop(body: string): { code: string; unresolved: number } {
770
+ let code = body.replace(NODE_MODE_TO_ESM, "__toESM($1)");
771
+ let dynamic = false;
772
+ code = code.replace(DYNAMIC_IMPORT, (_m, spec: string) => {
773
+ dynamic = true;
774
+ return `Promise.resolve().then(() => __skImportNs(require(${spec})))`;
775
+ });
776
+ if (dynamic) {
777
+ code +=
778
+ "\nfunction __skImportNs(m) {\n" +
779
+ ' return m && (m.__esModule || m[Symbol.toStringTag] === "Module") ? m : ' +
780
+ 'Object.defineProperty(Object.assign(Object.create(null), m, { default: m }), Symbol.toStringTag, { value: "Module" });\n' +
781
+ "}\n";
782
+ }
783
+ const unresolved = (code.match(DYNAMIC_IMPORT_ANY) ?? []).length;
784
+ return { code, unresolved };
785
+ }
786
+
787
+ const IMPORT_RULE = /@import\s+(?:url\(\s*(['"]?)([^'")]+)\1\s*\)|(['"])([^'"]+)\3)\s*([^;]*);/g;
788
+
789
+ const CSS_URL = /\/\*[\s\S]*?\*\/|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\burl\(\s*(['"]?)([^'")]*)\1\s*\)/gi;
790
+
791
+ /**
792
+ * Rewrites a sheet's relative `url()`s as Vite does: resolved against the sheet's file and made
793
+ * root-relative. Absolute, rooted, `data:`, `#fragment`, aliased URLs and `@import url(...)` are left alone.
794
+ */
795
+ export function rebaseCssUrls(css: string, from: string, docRoot: string, assets?: Map<string, string>): string {
796
+ if (!/url\(/i.test(css)) return css;
797
+ const dir = dirname(from.replace(/\?.*$/, ""));
798
+ return css.replace(CSS_URL, (whole, q: string, url: string, at: number, all: string) => {
799
+ if (url === undefined) return whole;
800
+ const u = url.trim();
801
+ if (!u || u.includes("(") || u.startsWith("//") || /^([a-z][a-z0-9+.-]*:|[#~@]|%23)/i.test(u)) return whole;
802
+ if (/@import\s*$/i.test(all.slice(Math.max(0, at - 16), at))) return whole;
803
+ const [path, tail] = (() => {
804
+ const i = u.search(/[?#]/);
805
+ return i < 0 ? [u, ""] : [u.slice(0, i), u.slice(i)];
806
+ })();
807
+ let decoded: string;
808
+ try {
809
+ decoded = decodeURIComponent(path);
810
+ } catch {
811
+ return whole;
812
+ }
813
+ const abs = u.startsWith("/") ? resolve(docRoot, "." + decoded) : resolve(dir, decoded);
814
+ if (assets && existsSync(abs) && statSync(abs).isFile()) {
815
+ const { key, url: packedUrl } = assetKey(abs, docRoot);
816
+ assets.set(key, abs);
817
+ return `url(${q || '"'}${packedUrl}${tail}${q || '"'})`;
818
+ }
819
+ if (u.startsWith("/")) return whole;
820
+ const rel = relative(resolve(docRoot), abs);
821
+ const out =
822
+ rel && !rel.startsWith("..") && !isAbsolute(rel)
823
+ ? `/${rel.split(sep).join("/")}`
824
+ : `file:///${abs.split(sep).join("/").replace(/^\/+/, "")}`;
825
+ return `url(${q || '"'}${out}${tail}${q || '"'})`;
826
+ });
827
+ }
828
+
829
+ /** Inlines every local `@import` in `css` recursively, as postcss-import does (sk-css would drop it as an unknown at-rule). */
830
+ export function inlineCssImports(
831
+ css: string,
832
+ from: string,
833
+ docRoot: string,
834
+ warn: (m: string) => void,
835
+ seen: Set<string> = new Set([resolve(from)]),
836
+ assets?: Map<string, string>,
837
+ ): string {
838
+ css = rebaseCssUrls(css, from, docRoot, assets);
839
+ if (!css.includes("@import")) return css;
840
+ return css.replace(
841
+ IMPORT_RULE,
842
+ (whole, _q1, urlSpec: string | undefined, _q2, strSpec: string | undefined, media: string) => {
843
+ const spec = (urlSpec ?? strSpec ?? "").trim();
844
+ if (/^(https?:)?\/\//i.test(spec) || spec.startsWith("data:")) return whole;
845
+ let target: string | null = null;
846
+ const clean = spec.replace(/^~/, "").replace(/[?#].*$/, "");
847
+ try {
848
+ if (clean.startsWith("/")) target = join(docRoot, clean);
849
+ else if (clean.startsWith(".")) target = resolve(dirname(from), clean);
850
+ else target = resolveImport(clean, dirname(from));
851
+ } catch {
852
+ target = null;
853
+ }
854
+ if (!target || !existsSync(target)) {
855
+ warn(`${from}: @import ${J(spec)} does not resolve to a file — dropped`);
856
+ return "";
857
+ }
858
+ const abs = resolve(target);
859
+ if (seen.has(abs)) return ""; // a cycle, or a second import of the same sheet: postcss-import skips it too
860
+ seen.add(abs);
861
+ const inner = inlineCssImports(readFileSync(abs, "utf8"), abs, docRoot, warn, seen, assets);
862
+ const m = media.trim();
863
+ return m && !/^(layer|supports)\b/.test(m) ? `@media ${m} {\n${inner}\n}` : inner;
864
+ },
865
+ );
866
+ }
867
+
868
+ export interface CssPiece {
869
+ text: string;
870
+ from: string;
871
+ }
872
+ export interface LiftedHtml {
873
+ /** `<style>` and local `<link rel=stylesheet>` in `<head>`, document order, AHEAD of the bundle's CSS. */
874
+ headCss: CssPiece[];
875
+ /** The same in `<body>`: AFTER it. */
876
+ bodyCss: CssPiece[];
877
+ /** Inline classic `<script>`s, document order, run before the entry module. */
878
+ scripts: { text: string; label: string }[];
879
+ rootClasses: string[];
880
+ rootAttrs: Record<string, string>;
881
+ mountElement?: { tag: string; attrs: Record<string, string> };
882
+ svgDefinitions?: string[];
883
+ advisories: string[];
884
+ }
885
+
886
+ function attrsOf(tag: string): Record<string, string> {
887
+ const out: Record<string, string> = {};
888
+ const re = /([^\s=<>"'/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
889
+ const inner = tag.replace(/^<\s*[\w-]+/, "").replace(/\/?>$/, "");
890
+ for (let m = re.exec(inner); m; m = re.exec(inner)) out[m[1]!.toLowerCase()] = m[2] ?? m[3] ?? m[4] ?? "";
891
+ return out;
892
+ }
893
+
894
+ /** What a Vite app's `index.html` contributes; the rest is named in `advisories`. */
895
+ export function liftIndexHtml(htmlPath: string, docRoot: string): LiftedHtml {
896
+ const raw = readFileSync(htmlPath, "utf8");
897
+ const html = raw.replace(/<!--[\s\S]*?-->/g, (c) => " ".repeat(c.length));
898
+ const out: LiftedHtml = { headCss: [], bodyCss: [], scripts: [], rootClasses: [], rootAttrs: {}, advisories: [] };
899
+ const bodyAt = (() => {
900
+ const m = /<body\b[^>]*>/i.exec(html);
901
+ return m ? m.index : html.search(/<\/head>/i);
902
+ })();
903
+ const inBody = (i: number) => bodyAt >= 0 && i >= bodyAt;
904
+ const label = (i: number) => `index.html:${raw.slice(0, i).split("\n").length}`;
905
+
906
+ const htmlTag = /<html\b[^>]*>/i.exec(html);
907
+ if (htmlTag) {
908
+ const a = attrsOf(htmlTag[0]);
909
+ if (a.class) out.rootClasses.push(...a.class.split(/\s+/).filter(Boolean));
910
+ }
911
+ const bodyTag = /<body\b[^>]*>/i.exec(html);
912
+ if (bodyTag) {
913
+ const a = attrsOf(bodyTag[0]);
914
+ if (a.class) out.rootClasses.push(...a.class.split(/\s+/).filter(Boolean));
915
+ const other = Object.keys(a).filter((k) => k !== "class");
916
+ if (other.length) out.advisories.push(`<body ${other.join(" ")}>: only "class" is carried to the root`);
917
+ }
918
+
919
+ const re = /<style\b([^>]*)>([\s\S]*?)<\/style\s*>|<link\b[^>]*>|<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
920
+ for (let m = re.exec(html); m; m = re.exec(html)) {
921
+ const at = m.index;
922
+ const sink = inBody(at) ? out.bodyCss : out.headCss;
923
+ if (m[0].toLowerCase().startsWith("<style")) {
924
+ const a = attrsOf(`<style${m[1]}>`);
925
+ const text = raw
926
+ .slice(at, at + m[0].length)
927
+ .replace(/^<style\b[^>]*>/i, "")
928
+ .replace(/<\/style\s*>$/i, "");
929
+ sink.push({ text: a.media ? `@media ${a.media} {\n${text}\n}` : text, from: `${htmlPath}?style@${label(at)}` });
930
+ } else if (m[0].toLowerCase().startsWith("<link")) {
931
+ const a = attrsOf(m[0]);
932
+ const rel = (a.rel ?? "").toLowerCase().split(/\s+/);
933
+ if (!rel.includes("stylesheet")) continue; // icons, manifest, preconnect: nothing to lift
934
+ const href = a.href ?? "";
935
+ if (/^(https?:)?\/\//i.test(href)) {
936
+ out.advisories.push(
937
+ `${label(at)}: remote stylesheet ${href} is not loaded — Skathi has no network stylesheets`,
938
+ );
939
+ continue;
940
+ }
941
+ const clean = href.replace(/[?#].*$/, "");
942
+ const abs = clean.startsWith("/") ? join(docRoot, clean) : resolve(dirname(htmlPath), clean);
943
+ if (!existsSync(abs)) {
944
+ out.advisories.push(`${label(at)}: <link rel=stylesheet href=${J(href)}> names no file — skipped`);
945
+ continue;
946
+ }
947
+ const text = readFileSync(abs, "utf8");
948
+ sink.push({ text: a.media ? `@media ${a.media} {\n${text}\n}` : text, from: abs });
949
+ } else {
950
+ const a = attrsOf(`<script${m[3]}>`);
951
+ const type = (a.type ?? "").toLowerCase();
952
+ if (a.src !== undefined) {
953
+ if (type !== "module")
954
+ out.advisories.push(`${label(at)}: <script src=${J(a.src)}> is not run — only the entry module is`);
955
+ continue; // the module entry: Skathi already knows its entry
956
+ }
957
+ const text = raw
958
+ .slice(at, at + m[0].length)
959
+ .replace(/^<script\b[^>]*>/i, "")
960
+ .replace(/<\/script\s*>$/i, "");
961
+ if (!text.trim()) continue;
962
+ if (type === "" || type === "text/javascript" || type === "application/javascript") {
963
+ out.scripts.push({ text, label: label(at) });
964
+ } else if (type === "module") {
965
+ out.advisories.push(
966
+ `${label(at)}: an inline <script type="module"> is not run — move it into the entry module`,
967
+ );
968
+ }
969
+ }
970
+ }
971
+
972
+ const appTag = /<([\w-]+)\b[^>]*\bid\s*=\s*["']app["'][^>]*>/i.exec(html);
973
+ if (appTag) out.mountElement = { tag: appTag[1]!.toLowerCase(), attrs: attrsOf(appTag[0]) };
974
+ out.svgDefinitions = [...html.matchAll(/<svg\b[^>]*>[\s\S]*?<\/svg\s*>/gi)]
975
+ .filter((match) => inBody(match.index ?? 0) && /<(?:defs|filter)\b/i.test(match[0]))
976
+ .map((match) => raw.slice(match.index!, match.index! + match[0].length));
977
+ if (bodyTag) {
978
+ const body = html
979
+ .slice(bodyTag.index + bodyTag[0].length)
980
+ .replace(re, "")
981
+ .replace(/<svg\b[^>]*>[\s\S]*?<\/svg\s*>/gi, (svg) => (/<(?:defs|filter)\b/i.test(svg) ? "" : svg));
982
+ const tags = new Set<string>();
983
+ for (const t of body.matchAll(/<([a-zA-Z][\w-]*)\b([^>]*)>/g)) {
984
+ if (/\bid\s*=\s*["']app["']/i.test(t[2] ?? "")) continue;
985
+ tags.add(t[1]!.toLowerCase());
986
+ }
987
+ if (tags.size) {
988
+ const named = [...tags].slice(0, 6).map((t) => `<${t}>`);
989
+ out.advisories.push(
990
+ `<body> markup is not rendered — the window is the root (${named.join(", ")}${tags.size > 6 ? ", …" : ""})`,
991
+ );
992
+ }
993
+ }
994
+ return out;
995
+ }
996
+
997
+ type StaticSvgNode = NonNullable<SFCTemplateBlock["ast"]>["children"][number];
998
+
999
+ /** Static SVG definitions become real DOM nodes: the runtime has no innerHTML parser. v-pre makes Vue syntax literal. */
1000
+ function staticSvgDom(svg: string): string {
1001
+ const { descriptor, errors } = parseSfc(`<template><div v-pre>${svg}</div></template>`, {
1002
+ templateParseOptions: { whitespace: "preserve", comments: true },
1003
+ });
1004
+ if (errors.length) {
1005
+ throw new Error(`index.html: SVG definitions did not parse: ${errors.map(String).join("; ")}`);
1006
+ }
1007
+ const wrapper = descriptor.template?.ast?.children.find((node) => node.type === 1);
1008
+ if (!wrapper || wrapper.type !== 1) throw new Error("index.html: SVG definitions have no root");
1009
+ const namespaces = [
1010
+ "http://www.w3.org/1999/xhtml",
1011
+ "http://www.w3.org/2000/svg",
1012
+ "http://www.w3.org/1998/Math/MathML",
1013
+ ];
1014
+ const lines = ["{"];
1015
+ let next = 0;
1016
+ const append = (node: StaticSvgNode, parent: string): void => {
1017
+ if (node.type === 1) {
1018
+ const name = `svg${next++}`;
1019
+ lines.push(`const ${name} = document.createElementNS(${J(namespaces[node.ns])}, ${J(node.tag)});`);
1020
+ for (const prop of node.props) {
1021
+ if (prop.type !== 6) continue;
1022
+ const key = prop.name;
1023
+ const value = prop.value?.content ?? "";
1024
+ const namespace =
1025
+ key === "xmlns" || key.startsWith("xmlns:")
1026
+ ? "http://www.w3.org/2000/xmlns/"
1027
+ : key.startsWith("xlink:")
1028
+ ? "http://www.w3.org/1999/xlink"
1029
+ : key.startsWith("xml:")
1030
+ ? "http://www.w3.org/XML/1998/namespace"
1031
+ : null;
1032
+ lines.push(
1033
+ namespace
1034
+ ? `${name}.setAttributeNS(${J(namespace)}, ${J(key)}, ${J(value)});`
1035
+ : `${name}.setAttribute(${J(key)}, ${J(value)});`,
1036
+ );
1037
+ }
1038
+ for (const child of node.children) append(child, name);
1039
+ lines.push(`${parent}.appendChild(${name});`);
1040
+ } else if (node.type === 2) {
1041
+ lines.push(`${parent}.appendChild(document.createTextNode(${J(node.content)}));`);
1042
+ }
1043
+ };
1044
+ for (const child of wrapper.children) append(child, "document.body");
1045
+ lines.push("}");
1046
+ return lines.join("\n");
1047
+ }
1048
+
1049
+ export function htmlPreludeModule(lifted: LiftedHtml): string {
1050
+ const lines: string[] = [
1051
+ // The runtime first: it installs `document.documentElement`, which buffers classes until the window root exists.
1052
+ `import "@skathi-native/runtime";`,
1053
+ ];
1054
+ if (lifted.rootClasses.length) lines.push(`document.documentElement.classList.add(...${J(lifted.rootClasses)});`);
1055
+ for (const [k, v] of Object.entries(lifted.rootAttrs)) {
1056
+ lines.push(`document.documentElement.setAttribute(${J(k)}, ${J(v)});`);
1057
+ }
1058
+ if (lifted.mountElement) {
1059
+ const mount = lifted.mountElement;
1060
+ lines.push(`{ const mount = document.getElementById("app") || document.createElement(${J(mount.tag)});`);
1061
+ for (const [k, v] of Object.entries(mount.attrs)) lines.push(`mount.setAttribute(${J(k)}, ${J(v)});`);
1062
+ lines.push(`if (!mount.parentNode) document.body.appendChild(mount); }`);
1063
+ }
1064
+ for (const svg of lifted.svgDefinitions ?? []) lines.push(staticSvgDom(svg));
1065
+ for (const s of lifted.scripts) {
1066
+ // Global scope, as a classic <script> has (indirect eval); a throw is reported, the next script still runs.
1067
+ lines.push(
1068
+ `try { (0, eval)(${J(s.text)}); } catch (e) { console.error(${J(`[index.html] ${s.label}: `)} + ((e && e.stack) || e)); }`,
1069
+ );
1070
+ }
1071
+ return lines.join("\n") + "\n";
1072
+ }
1073
+
1074
+ const major = (v: string | undefined) => {
1075
+ const m = /(\d+)/.exec(v ?? "");
1076
+ return m ? Number(m[1]) : NaN;
1077
+ };
1078
+
1079
+ function versionAt(pkgJson: string): string | undefined {
1080
+ try {
1081
+ return JSON.parse(readFileSync(pkgJson, "utf8")).version;
1082
+ } catch {
1083
+ return undefined;
1084
+ }
1085
+ }
1086
+
1087
+ function pkgJsonOf(entry: string, name: string): string | undefined {
1088
+ let dir = dirname(entry);
1089
+ for (;;) {
1090
+ const candidate = join(dir, "package.json");
1091
+ if (existsSync(candidate)) {
1092
+ try {
1093
+ if (JSON.parse(readFileSync(candidate, "utf8")).name === name) return candidate;
1094
+ } catch {}
1095
+ }
1096
+ const up = dirname(dir);
1097
+ if (up === dir) return undefined;
1098
+ dir = up;
1099
+ }
1100
+ }
1101
+
1102
+ export interface FrameworkDep {
1103
+ path: string;
1104
+ from: "app" | "@skathi-native/runtime";
1105
+ version?: string | undefined;
1106
+ warning?: string | undefined;
1107
+ }
1108
+
1109
+ /** Which copy of `name` (pinia / vue-router) the builders use: the app's own when declared and installed, else Skathi's. */
1110
+ export function frameworkDep(
1111
+ name: string,
1112
+ appPkg: Record<string, unknown> | null,
1113
+ appResolve: (spec: string) => string,
1114
+ runtimeResolve: (spec: string) => string,
1115
+ ): FrameworkDep {
1116
+ const runtimePath = runtimeResolve(name);
1117
+ const runtimeVersion = versionAt(pkgJsonOf(runtimePath, name) ?? "");
1118
+ let declared: string | undefined;
1119
+ for (const k of ["dependencies", "devDependencies", "peerDependencies"]) {
1120
+ const deps = appPkg?.[k] as Record<string, string> | undefined;
1121
+ if (deps && typeof deps[name] === "string") {
1122
+ declared = deps[name];
1123
+ break;
1124
+ }
1125
+ }
1126
+ if (declared === undefined) return { path: runtimePath, from: "@skathi-native/runtime", version: runtimeVersion };
1127
+ let appPath: string | undefined;
1128
+ try {
1129
+ appPath = appResolve(name);
1130
+ } catch {
1131
+ appPath = undefined;
1132
+ }
1133
+ if (!appPath) {
1134
+ const warning =
1135
+ major(declared) !== major(runtimeVersion)
1136
+ ? `the app declares ${name} ${declared} but it is not installed — using Skathi's ${name} ${runtimeVersion} (a different major)`
1137
+ : undefined;
1138
+ return { path: runtimePath, from: "@skathi-native/runtime", version: runtimeVersion, warning };
1139
+ }
1140
+ const appVersion = versionAt(pkgJsonOf(appPath, name) ?? "");
1141
+ return { path: appPath, from: "app", version: appVersion };
1142
+ }
1143
+
1144
+ export function readPackageJson(dir: string): Record<string, unknown> | null {
1145
+ try {
1146
+ const v = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
1147
+ return v && typeof v === "object" ? v : null;
1148
+ } catch {
1149
+ return null;
1150
+ }
1151
+ }