@yannosay/sinth 5.2.3 → 5.3.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +24 -23
  3. package/RUNTIME-EXCEPTION.md +25 -0
  4. package/dist/browser/compile.d.ts +35 -0
  5. package/dist/browser/compile.js +158 -0
  6. package/dist/browser/sinth.js +1492 -0
  7. package/dist/cli/index.js +3 -1
  8. package/dist/cli/templates.js +2 -2
  9. package/dist/cli/ui.d.ts +0 -1
  10. package/dist/cli/ui.js +1 -2
  11. package/dist/compiler/ast.d.ts +11 -0
  12. package/dist/compiler/codegen.d.ts +2 -87
  13. package/dist/compiler/codegen.js +49 -6
  14. package/dist/compiler/diagnostics.d.ts +0 -1
  15. package/dist/compiler/diagnostics.js +0 -4
  16. package/dist/compiler/html.d.ts +2 -0
  17. package/dist/compiler/html.js +11 -1
  18. package/dist/compiler/lexer.js +3 -0
  19. package/dist/compiler/parser.js +27 -1
  20. package/dist/compiler/prerender.js +4 -0
  21. package/dist/index.d.ts +2 -0
  22. package/dist/index.js +3 -1
  23. package/dist/project/build.d.ts +6 -0
  24. package/dist/project/build.js +69 -41
  25. package/dist/project/config.d.ts +1 -0
  26. package/dist/project/config.js +3 -2
  27. package/dist/project/project.d.ts +1 -0
  28. package/dist/project/project.js +2 -1
  29. package/dist/runtime/index.d.ts +6 -0
  30. package/dist/runtime/index.js +18 -2
  31. package/dist/runtime/router.d.ts +36 -0
  32. package/dist/runtime/router.js +215 -0
  33. package/dist/server/client.js +3 -1
  34. package/dist/server/dev.js +65 -25
  35. package/dist/server/functions.d.ts +49 -0
  36. package/dist/server/functions.js +309 -0
  37. package/dist/server/preview.d.ts +2 -0
  38. package/dist/server/preview.js +41 -18
  39. package/dist/server/static.d.ts +10 -0
  40. package/dist/server/static.js +25 -0
  41. package/package.json +22 -13
  42. package/schema/sinth.config.schema.json +2 -1
  43. package/DOCS.md +0 -1360
@@ -33,6 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.buildCustomElements = buildCustomElements;
36
37
  exports.contentSecurityPolicy = contentSecurityPolicy;
37
38
  exports.buildProject = buildProject;
38
39
  exports.checkProject = checkProject;
@@ -52,6 +53,7 @@ function sinthPlugin(project, entries, injectCss = false) {
52
53
  name: "sinth",
53
54
  setup(b) {
54
55
  b.onResolve({ filter: /^sinth-runtime$/ }, () => ({ path: project_1.RUNTIME_PATH }));
56
+ b.onResolve({ filter: /^sinth-router$/ }, () => ({ path: project_1.ROUTER_PATH }));
55
57
  b.onResolve({ filter: /^sinth-entry:/ }, a => ({ path: a.path.slice("sinth-entry:".length), namespace: "sinth-entry" }));
56
58
  b.onLoad({ filter: /.*/, namespace: "sinth-entry" }, a => ({ contents: entries.get(a.path) ?? "", loader: "js", resolveDir: project.root }));
57
59
  b.onResolve({ filter: /^sinth-css:/ }, a => ({ path: a.path.slice("sinth-css:".length), namespace: "sinth-css" }));
@@ -99,9 +101,14 @@ function findCustomElementFiles(project) {
99
101
  walk(project.root);
100
102
  return out;
101
103
  }
104
+ /**
105
+ * Bundles every component declared `as <tag-name>` into a standalone script per tag, plus
106
+ * `elements/index.js` that registers all of them, for use in any HTML page.
107
+ */
102
108
  async function buildCustomElements(project) {
103
109
  const entries = new Map();
104
110
  const entryPoints = {};
111
+ const all = new Set();
105
112
  for (const file of findCustomElementFiles(project)) {
106
113
  const parsed = project.getFile(file);
107
114
  if (parsed.isPage)
@@ -113,10 +120,15 @@ async function buildCustomElements(project) {
113
120
  const key = "elements/" + c.customTag;
114
121
  entries.set(key, `import ${JSON.stringify(file)};`);
115
122
  entryPoints[key] = "sinth-entry:" + key;
123
+ all.add(file);
116
124
  }
117
125
  }
118
126
  if (!entries.size)
119
127
  return [];
128
+ if (!entries.has("elements/index")) {
129
+ entries.set("elements/index", [...all].map(f => `import ${JSON.stringify(f)};`).join("\n"));
130
+ entryPoints["elements/index"] = "sinth-entry:elements/index";
131
+ }
120
132
  try {
121
133
  const result = await esbuild.build({
122
134
  entryPoints, bundle: true, format: "esm", platform: "browser", target: project.config.target,
@@ -159,17 +171,29 @@ function prepareOutDir(dir) {
159
171
  return;
160
172
  }
161
173
  const entries = fs.readdirSync(dir);
162
- if (entries.length && !entries.includes("_sinth")) {
174
+ if (entries.length && !entries.includes("_sinth") && !builtBySinth(dir, entries)) {
163
175
  throw new diagnostics_1.SinthError("E0801", `Refusing to clear '${dir}': it is not empty and was not created by Sinth`, undefined, "Delete it yourself or set a different \"outDir\" in sinth.config.json");
164
176
  }
165
177
  for (const e of entries)
166
178
  fs.rmSync(path.join(dir, e), { recursive: true, force: true });
167
179
  }
180
+ const JUNK_FILES = new Set([".ds_store", "thumbs.db", "desktop.ini", ".git", ".gitkeep", ".svn"]);
181
+ /** Pages carry `<meta name="generator" content="Sinth">`, so a fully static build is still recognized. */
182
+ function builtBySinth(dir, entries) {
183
+ return entries.filter(e => e.endsWith(".html")).slice(0, 5).some(e => {
184
+ try {
185
+ return /<meta name="generator" content="Sinth/.test(fs.readFileSync(path.join(dir, e), "utf-8").slice(0, 4096));
186
+ }
187
+ catch {
188
+ return false;
189
+ }
190
+ });
191
+ }
168
192
  function copyDir(src, dest, files, outDir) {
169
193
  if (!fs.existsSync(src))
170
194
  return;
171
195
  for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
172
- if (entry.name.startsWith(".") && entry.name !== ".well-known")
196
+ if (JUNK_FILES.has(entry.name.toLowerCase()))
173
197
  continue;
174
198
  const from = path.join(src, entry.name);
175
199
  const to = path.join(dest, entry.name);
@@ -226,7 +250,7 @@ async function buildProject(project, options) {
226
250
  const cfg = project.config;
227
251
  project.invalidate();
228
252
  const pages = project.findPages();
229
- if (!pages.length) {
253
+ if (!pages.length && !findCustomElementFiles(project).length) {
230
254
  throw new diagnostics_1.SinthError("E0802", fs.existsSync(cfg.pagesDir) ? `No pages found in ${path.relative(project.root, cfg.pagesDir) || "."}` : `No pages found (no ${path.relative(project.root, cfg.pagesDir) || "pages"}/ folder, and no .sinth file with markup in the project root)`, undefined, fs.existsSync(cfg.pagesDir)
231
255
  ? "Every .sinth file in this folder is a page (files starting with '_' are skipped). Add markup to pages/index.sinth, for example: Main { Heading { \"Hello\" } }"
232
256
  : `Create ${path.relative(project.root, cfg.pagesDir) || "pages"}/index.sinth with some markup, for example: Main { Heading { "Hello" } }`);
@@ -239,6 +263,8 @@ async function buildProject(project, options) {
239
263
  const lines = [];
240
264
  for (const s of c.styleImports)
241
265
  lines.push(`import ${JSON.stringify(s)};`);
266
+ if (cfg.router)
267
+ lines.push(`import "sinth-router";`);
242
268
  if (c.interactive) {
243
269
  lines.push(`import * as page from ${JSON.stringify(c.page.file)};`);
244
270
  lines.push(`import { boot } from "sinth-runtime";`);
@@ -252,36 +278,37 @@ async function buildProject(project, options) {
252
278
  entries.set(key, lines.join("\n"));
253
279
  entryPoints[key] = "sinth-entry:" + key;
254
280
  }
255
- let result;
256
- try {
257
- result = await esbuild.build({
258
- entryPoints,
259
- bundle: true,
260
- format: "esm",
261
- splitting: true,
262
- platform: "browser",
263
- target: cfg.target,
264
- outdir: path.join(cfg.outDir, "_sinth"),
265
- entryNames: project.dev ? "[dir]/[name]" : "[dir]/[name]-[hash]",
266
- chunkNames: "chunks/[name]-[hash]",
267
- assetNames: "assets/[name]-[hash]",
268
- publicPath: cfg.base + "_sinth",
269
- minify: cfg.minify,
270
- sourcemap: cfg.sourcemap ? (project.dev ? "inline" : "linked") : false,
271
- metafile: true,
272
- write: false,
273
- logLevel: "silent",
274
- charset: "utf8",
275
- legalComments: cfg.minify ? "none" : "eof",
276
- loader: ASSET_LOADERS,
277
- define: { "process.env.NODE_ENV": JSON.stringify(project.dev ? "development" : "production") },
278
- plugins: [sinthPlugin(project, entries)],
279
- absWorkingDir: project.root,
280
- });
281
- }
282
- catch (err) {
283
- throw esbuildErrorToSinth(err, project);
284
- }
281
+ let result = { outputFiles: [], metafile: { inputs: {}, outputs: {} }, warnings: [] };
282
+ if (compiled.length)
283
+ try {
284
+ result = await esbuild.build({
285
+ entryPoints,
286
+ bundle: true,
287
+ format: "esm",
288
+ splitting: true,
289
+ platform: "browser",
290
+ target: cfg.target,
291
+ outdir: path.join(cfg.outDir, "_sinth"),
292
+ entryNames: project.dev ? "[dir]/[name]" : "[dir]/[name]-[hash]",
293
+ chunkNames: "chunks/[name]-[hash]",
294
+ assetNames: "assets/[name]-[hash]",
295
+ publicPath: cfg.base + "_sinth",
296
+ minify: cfg.minify,
297
+ sourcemap: cfg.sourcemap ? (project.dev ? "inline" : "linked") : false,
298
+ metafile: true,
299
+ write: false,
300
+ logLevel: "silent",
301
+ charset: "utf8",
302
+ legalComments: cfg.minify ? "none" : "eof",
303
+ loader: ASSET_LOADERS,
304
+ define: { "process.env.NODE_ENV": JSON.stringify(project.dev ? "development" : "production") },
305
+ plugins: [sinthPlugin(project, entries)],
306
+ absWorkingDir: project.root,
307
+ });
308
+ }
309
+ catch (err) {
310
+ throw esbuildErrorToSinth(err, project);
311
+ }
285
312
  const files = new Map();
286
313
  for (const f of result.outputFiles) {
287
314
  files.set(path.relative(cfg.outDir, f.path).replace(/\\/g, "/"), { path: f.path, contents: f.contents });
@@ -314,29 +341,30 @@ async function buildProject(project, options) {
314
341
  if (cssOut)
315
342
  styles.push(toUrl(cssOut));
316
343
  const scripts = c.externalScripts.map(s => ({ src: s.src, module: false, attrs: s.attrs }));
317
- if (c.interactive && jsOut)
318
- scripts.push({ src: toUrl(jsOut), module: true, attrs: {} });
344
+ const shipsJs = !!jsOut && (c.interactive || cfg.router);
345
+ if (shipsJs && jsOut)
346
+ scripts.push({ src: toUrl(jsOut), module: true, attrs: { "data-sinth-entry": true } });
319
347
  if (options.devClient)
320
348
  inlineHead.push(`<script type="module" src="${options.devClient}"></script>`);
321
- if (!c.interactive && jsOut)
349
+ if (!shipsJs && jsOut)
322
350
  files.delete(path.relative(cfg.outDir, path.resolve(project.root, jsOut)).replace(/\\/g, "/"));
323
351
  for (const inst of c.instances) {
324
352
  const head = (0, html_1.buildHead)(inst.meta, v => project.resolveAsset(v, c.page.file));
325
353
  const pageHead = inst.params && c.interactive
326
354
  ? [...inlineHead, '<script type="application/json" id="sinth-params">' + JSON.stringify(inst.params).replace(/</g, "\\u003c") + "</script>"]
327
355
  : inlineHead;
328
- const html = (0, html_1.renderDocument)(head, inst.prerendered, { styles, scripts, preloads: c.interactive ? preloads : [], inlineHead: pageHead });
356
+ const html = (0, html_1.renderDocument)(head, inst.prerendered, { styles, scripts, preloads: shipsJs ? preloads : [], inlineHead: pageHead });
329
357
  files.set(inst.page.outFile, { path: path.join(cfg.outDir, inst.page.outFile), contents: Buffer.from(html) });
330
358
  pageOutputs.push({
331
359
  page: inst.page, html, interactive: c.interactive, bytes: Buffer.byteLength(html),
332
- js: c.interactive && jsOut ? toUrl(jsOut) : undefined, css: cssOut ? toUrl(cssOut) : undefined,
360
+ js: shipsJs && jsOut ? toUrl(jsOut) : undefined, css: cssOut ? toUrl(cssOut) : undefined,
333
361
  });
334
362
  }
335
363
  }
364
+ for (const f of await buildCustomElements(project)) {
365
+ files.set(path.relative(cfg.outDir, f.path).replace(/\\/g, "/"), { path: f.path, contents: f.contents });
366
+ }
336
367
  if (!project.dev) {
337
- for (const f of await buildCustomElements(project)) {
338
- files.set(path.relative(cfg.outDir, f.path).replace(/\\/g, "/"), { path: f.path, contents: f.contents });
339
- }
340
368
  copyDir(cfg.publicDir, cfg.outDir, files, cfg.outDir);
341
369
  for (const d of cfg.staticDirs)
342
370
  copyDir(path.resolve(project.root, d), path.join(cfg.outDir, d), files, cfg.outDir);
@@ -21,6 +21,7 @@ export interface SinthConfig {
21
21
  host: string;
22
22
  previewPort: number;
23
23
  target: string[];
24
+ router: boolean;
24
25
  security: SecurityConfig;
25
26
  cloudflare: CloudflareConfig;
26
27
  }
@@ -51,12 +51,13 @@ exports.DEFAULT_CONFIG = {
51
51
  host: "127.0.0.1",
52
52
  previewPort: 4000,
53
53
  target: ["es2020", "chrome90", "firefox90", "safari15", "edge90"],
54
+ router: true,
54
55
  security: { headers: true, csp: true },
55
56
  cloudflare: {},
56
57
  };
57
58
  const KNOWN_KEYS = new Set([
58
59
  "outDir", "pagesDir", "publicDir", "staticDirs", "libraryPaths", "site", "base", "minify", "sourcemap", "port", "host",
59
- "previewPort", "target", "security", "cloudflare", "development", "production", "$schema",
60
+ "previewPort", "target", "router", "security", "cloudflare", "development", "production", "$schema",
60
61
  "sharedRuntime", "inlineJS", "inlineCSS",
61
62
  ]);
62
63
  const LEGACY_KEYS = new Set(["sharedRuntime", "inlineJS", "inlineCSS"]);
@@ -77,7 +78,7 @@ function validate(raw, file, warnings) {
77
78
  check(k, "a string", str);
78
79
  for (const k of ["staticDirs", "libraryPaths", "target"])
79
80
  check(k, "an array of strings", strArr);
80
- for (const k of ["minify", "sourcemap"])
81
+ for (const k of ["minify", "sourcemap", "router"])
81
82
  check(k, "true or false", v => typeof v === "boolean");
82
83
  for (const k of ["port", "previewPort"])
83
84
  check(k, "a port number (1-65535)", v => Number.isInteger(v) && v > 0 && v < 65536);
@@ -6,6 +6,7 @@ import { ScssCompiler } from "../compiler/style";
6
6
  import { SinthConfig } from "./config";
7
7
  export declare const PACKAGE_ROOT: string;
8
8
  export declare const RUNTIME_PATH: string;
9
+ export declare const ROUTER_PATH: string;
9
10
  export declare const LIB_ROOT: string;
10
11
  export interface PageInfo {
11
12
  file: string;
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.Project = exports.LIB_ROOT = exports.RUNTIME_PATH = exports.PACKAGE_ROOT = void 0;
36
+ exports.Project = exports.LIB_ROOT = exports.ROUTER_PATH = exports.RUNTIME_PATH = exports.PACKAGE_ROOT = void 0;
37
37
  exports.routeParams = routeParams;
38
38
  exports.fontHref = fontHref;
39
39
  const fs = __importStar(require("fs"));
@@ -45,6 +45,7 @@ const prerender_1 = require("../compiler/prerender");
45
45
  const parser_1 = require("../compiler/parser");
46
46
  exports.PACKAGE_ROOT = path.resolve(__dirname, "..", "..");
47
47
  exports.RUNTIME_PATH = path.join(exports.PACKAGE_ROOT, "dist", "runtime", "index.js");
48
+ exports.ROUTER_PATH = path.join(exports.PACKAGE_ROOT, "dist", "runtime", "router.js");
48
49
  exports.LIB_ROOT = path.join(exports.PACKAGE_ROOT, "lib");
49
50
  const LEGACY_LIBRARIES = { SinthUI: "sinth:ui" };
50
51
  const IGNORED_DIRS = new Set(["node_modules", ".git", ".sinth", ".wrangler", ".vscode", ".idea"]);
@@ -13,6 +13,12 @@ export type Slots = Record<string, Render | undefined>;
13
13
  export type Component = (parent: ParentNode, props: Props, slots: Slots, fallthrough?: (el: Element) => void) => void;
14
14
  export declare function update(): void;
15
15
  export declare function schedule(): void;
16
+ /**
17
+ * Called by compiled code after state is assigned or mutated. Inside event handlers the handler's
18
+ * own update covers it; anywhere else (timers, callbacks, promise continuations) an update is
19
+ * scheduled for the next microtask, batched with any other changes.
20
+ */
21
+ export declare function changed<T>(value: T): T;
16
22
  export declare function toText(value: unknown): string;
17
23
  export declare function el(tag: string): HTMLElement;
18
24
  export declare function svg(tag: string): Element;
@@ -6,6 +6,7 @@ let updating = false;
6
6
  let rerun = false;
7
7
  let scheduled = false;
8
8
  let devMode = false;
9
+ let handling = 0;
9
10
  function createOwner(parent) {
10
11
  const owner = { parent, effects: [], children: [], cleanups: [], disposed: false, paused: false };
11
12
  if (parent)
@@ -107,6 +108,16 @@ export function schedule() {
107
108
  update();
108
109
  });
109
110
  }
111
+ /**
112
+ * Called by compiled code after state is assigned or mutated. Inside event handlers the handler's
113
+ * own update covers it; anywhere else (timers, callbacks, promise continuations) an update is
114
+ * scheduled for the next microtask, batched with any other changes.
115
+ */
116
+ export function changed(value) {
117
+ if (!handling && !updating)
118
+ schedule();
119
+ return value;
120
+ }
110
121
  function settle(result) {
111
122
  if (result && typeof result.then === "function") {
112
123
  result.then(schedule, (err) => {
@@ -332,12 +343,16 @@ export function on(node, event, handler, modifiers = []) {
332
343
  if (modifiers.includes("stop"))
333
344
  e.stopPropagation();
334
345
  let result;
346
+ handling++;
335
347
  try {
336
348
  result = handler(e);
337
349
  }
338
350
  catch (err) {
339
351
  reportError(err);
340
352
  }
353
+ finally {
354
+ handling--;
355
+ }
341
356
  update();
342
357
  settle(result);
343
358
  };
@@ -799,6 +814,7 @@ export function mount(target, render) {
799
814
  }
800
815
  export function boot(page) {
801
816
  devMode = !!page.dev;
817
+ routeParams = undefined;
802
818
  const g = globalThis;
803
819
  if (g.__sinth_hmr_state__ && page.restore) {
804
820
  page.restore(g.__sinth_hmr_state__);
@@ -809,8 +825,8 @@ export function boot(page) {
809
825
  const start = () => {
810
826
  const app = mount(document.body, page.render);
811
827
  g.__sinth_app__ = {
812
- dispose: () => {
813
- if (page.state)
828
+ dispose: (keepState = true) => {
829
+ if (keepState && page.state)
814
830
  g.__sinth_hmr_state__ = page.state();
815
831
  app.dispose();
816
832
  rootOwner = createOwner(null);
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Client-side navigation for multi-page Sinth sites.
3
+ *
4
+ * Same-origin links are fetched and swapped in place instead of triggering a full page load:
5
+ * the head is reconciled (title, meta, stylesheets), the prerendered body is shown at once and
6
+ * the next page's module boots on top of it. Anything unexpected falls back to a normal load.
7
+ */
8
+ interface RouterGlobal {
9
+ __sinth_router__?: boolean;
10
+ __sinth_app__?: {
11
+ dispose(keepState?: boolean): void;
12
+ };
13
+ }
14
+ interface HistoryState {
15
+ sinth: true;
16
+ scroll: number;
17
+ }
18
+ declare const ENTRY_ATTR = "data-sinth-entry";
19
+ declare const RELOAD_ATTR = "data-reload";
20
+ declare const PREFETCH_DELAY = 65;
21
+ declare const g: RouterGlobal;
22
+ declare const cache: Map<string, Promise<Response | null>>;
23
+ declare const executed: Set<string>;
24
+ declare let token: number;
25
+ declare let shown: string;
26
+ declare function pageKey(url: URL): string;
27
+ declare function eligible(a: HTMLAnchorElement, e?: MouseEvent): URL | null;
28
+ declare function load(url: URL): Promise<Response | null>;
29
+ declare function headKey(node: Element): string | null;
30
+ /** Brings the live head in line with the next document. New stylesheets load before the swap to avoid a flash of unstyled content. */
31
+ declare function syncHead(next: Document): Promise<void>;
32
+ declare function recreateScript(source: HTMLScriptElement): HTMLScriptElement;
33
+ declare function entryOf(doc: Document): string | null;
34
+ declare function saveScroll(): void;
35
+ declare function navigate(url: URL, mode: "push" | "pop", restore?: number): Promise<void>;
36
+ declare function start(): void;
@@ -0,0 +1,215 @@
1
+ "use strict";
2
+ /**
3
+ * Client-side navigation for multi-page Sinth sites.
4
+ *
5
+ * Same-origin links are fetched and swapped in place instead of triggering a full page load:
6
+ * the head is reconciled (title, meta, stylesheets), the prerendered body is shown at once and
7
+ * the next page's module boots on top of it. Anything unexpected falls back to a normal load.
8
+ */
9
+ const ENTRY_ATTR = "data-sinth-entry";
10
+ const RELOAD_ATTR = "data-reload";
11
+ const PREFETCH_DELAY = 65;
12
+ const g = globalThis;
13
+ const cache = new Map();
14
+ const executed = new Set();
15
+ let token = 0;
16
+ let shown = "";
17
+ function pageKey(url) {
18
+ return url.origin + url.pathname + url.search;
19
+ }
20
+ function eligible(a, e) {
21
+ if (e && (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey))
22
+ return null;
23
+ if (!a.href || a.hasAttribute("download") || a.hasAttribute(RELOAD_ATTR))
24
+ return null;
25
+ if (a.target && a.target !== "_self")
26
+ return null;
27
+ if ((a.getAttribute("rel") ?? "").split(/\s+/).includes("external"))
28
+ return null;
29
+ const url = new URL(a.href, location.href);
30
+ if (url.origin !== location.origin)
31
+ return null;
32
+ const last = url.pathname.slice(url.pathname.lastIndexOf("/") + 1);
33
+ if (/\.[a-z0-9]+$/i.test(last) && !/\.html?$/i.test(last))
34
+ return null;
35
+ if (pageKey(url) === shown && url.hash)
36
+ return null;
37
+ return url;
38
+ }
39
+ function load(url) {
40
+ const key = pageKey(url);
41
+ let pending = cache.get(key);
42
+ if (!pending) {
43
+ pending = fetch(key, { headers: { Accept: "text/html" }, credentials: "same-origin" })
44
+ .then(res => (res.headers.get("content-type") ?? "").includes("text/html") ? res : null)
45
+ .catch(() => null);
46
+ cache.set(key, pending);
47
+ pending.then(res => { if (!res || !res.ok)
48
+ cache.delete(key); });
49
+ }
50
+ return pending.then(res => res?.clone() ?? null);
51
+ }
52
+ function headKey(node) {
53
+ switch (node.tagName) {
54
+ case "TITLE": return null;
55
+ case "META": return "meta:" + (node.getAttribute("name") ?? node.getAttribute("property") ?? node.getAttribute("http-equiv") ?? node.getAttribute("charset") ?? "");
56
+ case "LINK": return "link:" + node.getAttribute("rel") + ":" + node.getAttribute("href");
57
+ case "SCRIPT": return node.id ? "script#" + node.id : "script:" + (node.getAttribute("src") ?? node.textContent);
58
+ case "STYLE": return "style:" + (node.id || node.textContent);
59
+ case "BASE": return "base";
60
+ default: return null;
61
+ }
62
+ }
63
+ /** Brings the live head in line with the next document. New stylesheets load before the swap to avoid a flash of unstyled content. */
64
+ async function syncHead(next) {
65
+ document.title = next.title;
66
+ const current = new Map();
67
+ for (const node of Array.from(document.head.children)) {
68
+ const key = headKey(node);
69
+ if (key)
70
+ current.set(key, node);
71
+ }
72
+ const loading = [];
73
+ const keep = new Set();
74
+ for (const node of Array.from(next.head.children)) {
75
+ const key = headKey(node);
76
+ if (!key)
77
+ continue;
78
+ const existing = current.get(key);
79
+ if (existing && (node.tagName !== "SCRIPT" || !node.id) && existing.outerHTML === node.outerHTML) {
80
+ keep.add(existing);
81
+ continue;
82
+ }
83
+ if (node.tagName === "SCRIPT" && node.type === "module" && node.hasAttribute(ENTRY_ATTR))
84
+ continue;
85
+ const clone = node.tagName === "SCRIPT" ? recreateScript(node) : document.importNode(node, true);
86
+ if (clone instanceof HTMLLinkElement && clone.rel === "stylesheet") {
87
+ loading.push(new Promise(resolve => { clone.onload = clone.onerror = resolve; }));
88
+ }
89
+ document.head.appendChild(clone);
90
+ keep.add(clone);
91
+ }
92
+ await Promise.all(loading);
93
+ for (const node of current.values()) {
94
+ if (keep.has(node) || (node.tagName === "STYLE" && node.id.startsWith("sinth-")))
95
+ continue;
96
+ if (node.tagName === "SCRIPT" && node.src.includes("/__sinth/"))
97
+ continue;
98
+ node.remove();
99
+ }
100
+ }
101
+ function recreateScript(source) {
102
+ const script = document.createElement("script");
103
+ for (const { name, value } of Array.from(source.attributes))
104
+ script.setAttribute(name, value);
105
+ script.textContent = source.textContent;
106
+ return script;
107
+ }
108
+ function entryOf(doc) {
109
+ const script = doc.querySelector(`script[type="module"][${ENTRY_ATTR}]`);
110
+ return script ? new URL(script.getAttribute("src") ?? "", location.href).href : null;
111
+ }
112
+ function scrollTo(url, restore) {
113
+ if (restore !== undefined) {
114
+ window.scrollTo(0, restore);
115
+ return;
116
+ }
117
+ const target = url.hash ? document.getElementById(decodeURIComponent(url.hash.slice(1))) : null;
118
+ if (target)
119
+ target.scrollIntoView();
120
+ else
121
+ window.scrollTo(0, 0);
122
+ }
123
+ function saveScroll() {
124
+ history.replaceState({ ...history.state, sinth: true, scroll: window.scrollY }, "");
125
+ }
126
+ async function navigate(url, mode, restore) {
127
+ const id = ++token;
128
+ const res = await load(url);
129
+ if (id !== token)
130
+ return;
131
+ if (!res) {
132
+ location.href = url.href;
133
+ return;
134
+ }
135
+ const doc = new DOMParser().parseFromString(await res.text(), "text/html");
136
+ if (id !== token)
137
+ return;
138
+ const generator = doc.querySelector('meta[name="generator"]')?.getAttribute("content") ?? "";
139
+ if (!generator.startsWith("Sinth") || doc.documentElement.hasAttribute(RELOAD_ATTR)) {
140
+ location.href = url.href;
141
+ return;
142
+ }
143
+ if (mode === "push") {
144
+ saveScroll();
145
+ history.pushState({ sinth: true, scroll: 0 }, "", url.href);
146
+ }
147
+ await syncHead(doc);
148
+ if (id !== token)
149
+ return;
150
+ g.__sinth_app__?.dispose(false);
151
+ g.__sinth_app__ = undefined;
152
+ document.documentElement.lang = doc.documentElement.lang;
153
+ document.documentElement.className = doc.documentElement.className;
154
+ document.body.className = doc.body.className;
155
+ document.body.replaceChildren(...Array.from(doc.body.childNodes).map(n => document.importNode(n, true)));
156
+ shown = pageKey(url);
157
+ scrollTo(url, restore);
158
+ const entry = entryOf(doc);
159
+ if (entry) {
160
+ const src = executed.has(entry) ? `${entry}${entry.includes("?") ? "&" : "?"}v=${id}` : entry;
161
+ executed.add(entry);
162
+ try {
163
+ await import(/* @vite-ignore */ src);
164
+ }
165
+ catch {
166
+ location.href = url.href;
167
+ return;
168
+ }
169
+ }
170
+ window.dispatchEvent(new CustomEvent("sinth:navigate", { detail: { url: url.href } }));
171
+ }
172
+ function start() {
173
+ if (g.__sinth_router__ || typeof history === "undefined" || !window.fetch || !window.DOMParser)
174
+ return;
175
+ g.__sinth_router__ = true;
176
+ shown = pageKey(new URL(location.href));
177
+ const first = entryOf(document);
178
+ if (first)
179
+ executed.add(first);
180
+ history.scrollRestoration = "manual";
181
+ history.replaceState({ ...history.state, sinth: true, scroll: window.scrollY }, "");
182
+ document.addEventListener("click", e => {
183
+ const a = e.target?.closest?.("a");
184
+ if (!(a instanceof HTMLAnchorElement))
185
+ return;
186
+ const url = eligible(a, e);
187
+ if (!url)
188
+ return;
189
+ e.preventDefault();
190
+ void navigate(url, "push");
191
+ });
192
+ let timer;
193
+ const prefetch = (e) => {
194
+ const a = e.target?.closest?.("a");
195
+ if (!(a instanceof HTMLAnchorElement))
196
+ return;
197
+ clearTimeout(timer);
198
+ timer = setTimeout(() => {
199
+ const url = eligible(a);
200
+ if (url && pageKey(url) !== shown)
201
+ void load(url);
202
+ }, PREFETCH_DELAY);
203
+ };
204
+ document.addEventListener("pointerover", prefetch, { passive: true });
205
+ document.addEventListener("focusin", prefetch, { passive: true });
206
+ document.addEventListener("touchstart", prefetch, { passive: true });
207
+ window.addEventListener("popstate", e => {
208
+ const url = new URL(location.href);
209
+ if (pageKey(url) === shown)
210
+ return;
211
+ void navigate(url, "pop", e.state?.scroll ?? 0);
212
+ });
213
+ window.addEventListener("pagehide", saveScroll);
214
+ }
215
+ start();
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DEV_CLIENT = void 0;
4
4
  exports.DEV_CLIENT = String.raw `
5
5
  const OVERLAY_ID = "__sinth_overlay";
6
- const state = { hashes: null, connected: false };
6
+ const state = { hashes: null, connected: false, base: "/" };
7
7
 
8
8
  function escapeHtml(s) {
9
9
  return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
@@ -11,6 +11,7 @@ function escapeHtml(s) {
11
11
 
12
12
  function currentRoute() {
13
13
  let p = location.pathname.replace(/\/index\.html$/, "/").replace(/\.html$/, "");
14
+ if (state.base !== "/" && p.startsWith(state.base)) p = p.slice(state.base.length - 1);
14
15
  if (p.length > 1 && p.endsWith("/")) p = p.slice(0, -1);
15
16
  return p || "/";
16
17
  }
@@ -101,6 +102,7 @@ function connect() {
101
102
  else apply(msg.pages);
102
103
  } else if (msg.type === "init") {
103
104
  state.hashes = msg.pages;
105
+ state.base = msg.base || "/";
104
106
  if (msg.error) showOverlay(msg.error.title, msg.error.message, "compile");
105
107
  }
106
108
  };