@yannosay/sinth 5.3.2 → 5.3.3

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.
@@ -42,31 +42,72 @@ const fs = __importStar(require("fs"));
42
42
  const path = __importStar(require("path"));
43
43
  const diagnostics_1 = require("../compiler/diagnostics");
44
44
  const html_1 = require("../compiler/html");
45
+ const platforms_1 = require("../deploy/platforms");
46
+ const config_1 = require("./config");
45
47
  const project_1 = require("./project");
46
48
  const ASSET_LOADERS = {
47
49
  ".png": "file", ".jpg": "file", ".jpeg": "file", ".gif": "file", ".webp": "file", ".avif": "file", ".svg": "file",
48
50
  ".ico": "file", ".woff": "file", ".woff2": "file", ".ttf": "file", ".otf": "file", ".eot": "file", ".mp4": "file",
49
51
  ".webm": "file", ".mp3": "file", ".wav": "file", ".txt": "text",
50
52
  };
53
+ /**
54
+ * A short id for a virtual CSS module. esbuild prints module paths in comments in unminified
55
+ * output, so ids never contain absolute paths of the build machine.
56
+ */
57
+ function cssModuleId(project, file) {
58
+ const rel = path.relative(project.root, file);
59
+ if (!rel.startsWith("..") && !path.isAbsolute(rel))
60
+ return rel.split(path.sep).join("/");
61
+ const parts = file.split(/[\\/]/);
62
+ const nm = parts.lastIndexOf("node_modules");
63
+ return nm !== -1 ? parts.slice(nm).join("/") : "external/" + parts.slice(-2).join("/");
64
+ }
51
65
  function sinthPlugin(project, entries, injectCss = false) {
66
+ const cssFiles = new Map();
52
67
  return {
53
68
  name: "sinth",
54
69
  setup(b) {
55
- b.onResolve({ filter: /^sinth-runtime$/ }, () => ({ path: project_1.RUNTIME_PATH }));
56
- b.onResolve({ filter: /^sinth-router$/ }, () => ({ path: project_1.ROUTER_PATH }));
70
+ b.onResolve({ filter: /^sinth-(runtime|router)$/ }, a => ({ path: a.path, namespace: "sinth-builtin" }));
71
+ b.onLoad({ filter: /.*/, namespace: "sinth-builtin" }, a => {
72
+ const file = a.path === "sinth-router" ? project_1.ROUTER_PATH : project_1.RUNTIME_PATH;
73
+ return { contents: fs.readFileSync(file, "utf-8"), loader: "js", resolveDir: path.dirname(file) };
74
+ });
57
75
  b.onResolve({ filter: /^sinth-entry:/ }, a => ({ path: a.path.slice("sinth-entry:".length), namespace: "sinth-entry" }));
58
76
  b.onLoad({ filter: /.*/, namespace: "sinth-entry" }, a => ({ contents: entries.get(a.path) ?? "", loader: "js", resolveDir: project.root }));
59
- b.onResolve({ filter: /^sinth-css:/ }, a => ({ path: a.path.slice("sinth-css:".length), namespace: "sinth-css" }));
60
- b.onLoad({ filter: /.*/, namespace: "sinth-css" }, a => (injectCss
61
- ? { contents: `import { injectCss } from "sinth-runtime";\ninjectCss(${JSON.stringify("sinth-" + a.path.length.toString(36) + "-" + path.basename(a.path))}, ${JSON.stringify(project.compile(a.path).css)});`, loader: "js", resolveDir: path.dirname(a.path) }
62
- : { contents: project.compile(a.path).css, loader: "css", resolveDir: path.dirname(a.path) }));
77
+ b.onResolve({ filter: /^sinth-css:/ }, a => {
78
+ const file = a.path.slice("sinth-css:".length);
79
+ const id = cssModuleId(project, file);
80
+ cssFiles.set(id, file);
81
+ return { path: id, namespace: "sinth-css" };
82
+ });
83
+ b.onLoad({ filter: /.*/, namespace: "sinth-css" }, a => {
84
+ const file = cssFiles.get(a.path) ?? path.resolve(project.root, a.path);
85
+ return injectCss
86
+ ? { contents: `import { injectCss } from "sinth-runtime";\ninjectCss(${JSON.stringify("sinth-css-" + a.path.replace(/[^\w-]+/g, "-"))}, ${JSON.stringify(project.compile(file).css)});`, loader: "js", resolveDir: path.dirname(file) }
87
+ : { contents: project.compile(file).css, loader: "css", resolveDir: path.dirname(file) };
88
+ });
63
89
  if (injectCss) {
64
90
  b.onLoad({ filter: /\.css$/ }, a => ({
65
91
  contents: `import { injectCss } from "sinth-runtime";\ninjectCss(${JSON.stringify("sinth-css-" + path.basename(a.path))}, ${JSON.stringify(fs.readFileSync(a.path, "utf-8"))});`,
66
92
  loader: "js",
67
93
  }));
68
94
  }
69
- b.onLoad({ filter: /\.sinth$/ }, a => ({ contents: project.compile(a.path).js, loader: "js", resolveDir: path.dirname(a.path) }));
95
+ b.onLoad({ filter: /\.sinth$/, namespace: "file" }, a => ({ contents: project.compile(a.path).js, loader: "js", resolveDir: path.dirname(a.path) }));
96
+ // .sinth files outside the project (built-in libraries, linked packages) get a short id too.
97
+ b.onResolve({ filter: /\.sinth$/ }, a => {
98
+ if (a.namespace !== "file" && a.namespace !== "sinth-entry" && a.namespace !== "sinth-module")
99
+ return undefined;
100
+ const file = path.isAbsolute(a.path) ? a.path : path.resolve(a.resolveDir, a.path);
101
+ const id = cssModuleId(project, file);
102
+ if (!id.startsWith("node_modules/") && !id.startsWith("external/"))
103
+ return undefined;
104
+ cssFiles.set(id, file);
105
+ return { path: id, namespace: "sinth-module" };
106
+ });
107
+ b.onLoad({ filter: /.*/, namespace: "sinth-module" }, a => {
108
+ const file = cssFiles.get(a.path);
109
+ return { contents: project.compile(file).js, loader: "js", resolveDir: path.dirname(file) };
110
+ });
70
111
  b.onLoad({ filter: /\.s[ac]ss$/ }, a => {
71
112
  const scss = project.scss();
72
113
  if (!scss)
@@ -251,9 +292,12 @@ async function buildProject(project, options) {
251
292
  project.invalidate();
252
293
  const pages = project.findPages();
253
294
  if (!pages.length && !findCustomElementFiles(project).length) {
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)
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\" } }"
256
- : `Create ${path.relative(project.root, cfg.pagesDir) || "pages"}/index.sinth with some markup, for example: Main { Heading { "Hello" } }`);
295
+ const rel = (p) => path.relative(project.root, p).split(path.sep).join("/");
296
+ const pagesRel = rel(cfg.pagesDir) || "pages";
297
+ const where = rel(cfg.srcDir) ? rel(cfg.srcDir) + "/" : "the project root";
298
+ throw new diagnostics_1.SinthError("E0802", fs.existsSync(cfg.pagesDir) ? `No pages found in ${pagesRel}` : `No pages found (no ${pagesRel}/ folder, and no .sinth file with markup in ${where})`, undefined, fs.existsSync(cfg.pagesDir)
299
+ ? `Every .sinth file in this folder is a page (files starting with '_' are skipped). Add markup to ${pagesRel}/index.sinth, for example: Main { Heading { "Hello" } }`
300
+ : `Create ${pagesRel}/index.sinth with some markup, for example: Main { Heading { "Hello" } }`);
257
301
  }
258
302
  const compiled = pages.map(p => project.compilePage(p));
259
303
  const entries = new Map();
@@ -367,14 +411,13 @@ async function buildProject(project, options) {
367
411
  if (!project.dev) {
368
412
  copyDir(cfg.publicDir, cfg.outDir, files, cfg.outDir);
369
413
  for (const d of cfg.staticDirs)
370
- copyDir(path.resolve(project.root, d), path.join(cfg.outDir, d), files, cfg.outDir);
371
- if (cfg.security.headers && !files.has("_headers")) {
372
- const lines = ["/*", " X-Content-Type-Options: nosniff", " Referrer-Policy: strict-origin-when-cross-origin", " X-Frame-Options: SAMEORIGIN", " Cross-Origin-Opener-Policy: same-origin"];
373
- if (csp)
374
- lines.push(` Content-Security-Policy: ${csp}`);
375
- lines.push("", `${cfg.base}_sinth/*`, " Cache-Control: public, max-age=31536000, immutable", "");
376
- files.set("_headers", { path: path.join(cfg.outDir, "_headers"), contents: Buffer.from(lines.join("\n")) });
414
+ copyDir((0, config_1.staticDirPath)(cfg, d), path.join(cfg.outDir, d), files, cfg.outDir);
415
+ if (cfg.security.headers && (0, platforms_1.readsHeadersFile)(cfg.platform) && !files.has("_headers")) {
416
+ files.set("_headers", { path: path.join(cfg.outDir, "_headers"), contents: Buffer.from((0, platforms_1.headersFile)((0, platforms_1.securityHeaders)(csp), cfg.base)) });
377
417
  }
418
+ // GitHub Pages runs Jekyll by default, which drops folders starting with "_" such as _sinth/.
419
+ if (cfg.platform === "github-pages" && !files.has(".nojekyll"))
420
+ files.set(".nojekyll", { path: path.join(cfg.outDir, ".nojekyll"), contents: Buffer.alloc(0) });
378
421
  if (cfg.site) {
379
422
  const site = cfg.site.replace(/\/$/, "");
380
423
  const urls = pageOutputs.filter(p => !/(^|\/)404$/.test(p.page.route)).map(p => ` <url><loc>${(0, html_1.escapeHtml)(site + p.page.route)}</loc></url>`);
@@ -390,13 +433,14 @@ async function buildProject(project, options) {
390
433
  fs.writeFileSync(f.path, f.contents);
391
434
  }
392
435
  }
436
+ const platformWarnings = project.dev ? [] : await (0, platforms_1.writePlatformOutput)(project, files, cfg.security.headers ? (0, platforms_1.securityHeaders)(csp) : {}, options.write);
393
437
  const bundlerWarnings = result.warnings.map(w => ({
394
438
  severity: "warning",
395
439
  code: "W0800",
396
440
  message: w.text,
397
441
  loc: w.location?.file && !w.location.file.endsWith(".sinth") ? { file: path.resolve(project.root, w.location.file.replace(/^[a-z-]+:/, "")), line: w.location.line, col: w.location.column + 1 } : undefined,
398
442
  }));
399
- const warnings = dedupeWarnings([...compiled.flatMap(c => c.warnings), ...bundlerWarnings]);
443
+ const warnings = dedupeWarnings([...compiled.flatMap(c => c.warnings), ...bundlerWarnings, ...platformWarnings]);
400
444
  return { pages: pageOutputs, files, warnings, durationMs: Date.now() - started };
401
445
  }
402
446
  function dedupeWarnings(list) {
@@ -7,7 +7,13 @@ export interface SecurityConfig {
7
7
  headers: boolean;
8
8
  csp: boolean | string;
9
9
  }
10
+ /** Where the site is hosted. Decides which host-specific files the build writes and how `sinth deploy` uploads. */
11
+ export type Platform = "cloudflare" | "cloudflare-workers" | "vercel" | "netlify" | "github-pages" | "static";
12
+ export declare const PLATFORMS: Platform[];
10
13
  export interface SinthConfig {
14
+ platform: Platform;
15
+ /** Folder holding pages, components, libraries and assets: the project root, or app/ (absolute after loading). */
16
+ srcDir: string;
11
17
  outDir: string;
12
18
  pagesDir: string;
13
19
  publicDir: string;
@@ -32,3 +38,10 @@ export interface LoadedConfig {
32
38
  warnings: string[];
33
39
  }
34
40
  export declare function loadConfig(root: string, mode: "development" | "production"): LoadedConfig;
41
+ /**
42
+ * Uses app/ as the source folder (like Nuxt) when it exists and the root has no pages/ folder and
43
+ * no .sinth files of its own, so projects that keep everything in the root are unaffected.
44
+ */
45
+ export declare function detectSrcDir(root: string): string;
46
+ /** Resolves a static asset folder (like "assets") inside the source folder. */
47
+ export declare function staticDirPath(config: SinthConfig, dir: string): string;
@@ -33,12 +33,17 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.DEFAULT_CONFIG = void 0;
36
+ exports.DEFAULT_CONFIG = exports.PLATFORMS = void 0;
37
37
  exports.loadConfig = loadConfig;
38
+ exports.detectSrcDir = detectSrcDir;
39
+ exports.staticDirPath = staticDirPath;
38
40
  const fs = __importStar(require("fs"));
39
41
  const path = __importStar(require("path"));
40
42
  const diagnostics_1 = require("../compiler/diagnostics");
43
+ exports.PLATFORMS = ["cloudflare", "cloudflare-workers", "vercel", "netlify", "github-pages", "static"];
41
44
  exports.DEFAULT_CONFIG = {
45
+ platform: "cloudflare",
46
+ srcDir: ".",
42
47
  outDir: "dist",
43
48
  pagesDir: "pages",
44
49
  publicDir: "public",
@@ -56,7 +61,7 @@ exports.DEFAULT_CONFIG = {
56
61
  cloudflare: {},
57
62
  };
58
63
  const KNOWN_KEYS = new Set([
59
- "outDir", "pagesDir", "publicDir", "staticDirs", "libraryPaths", "site", "base", "minify", "sourcemap", "port", "host",
64
+ "platform", "srcDir", "outDir", "pagesDir", "publicDir", "staticDirs", "libraryPaths", "site", "base", "minify", "sourcemap", "port", "host",
60
65
  "previewPort", "target", "router", "security", "cloudflare", "development", "production", "$schema",
61
66
  "sharedRuntime", "inlineJS", "inlineCSS",
62
67
  ]);
@@ -74,7 +79,7 @@ function validate(raw, file, warnings) {
74
79
  };
75
80
  const str = (v) => typeof v === "string";
76
81
  const strArr = (v) => Array.isArray(v) && v.every(x => typeof x === "string");
77
- for (const k of ["outDir", "pagesDir", "publicDir", "site", "base", "host"])
82
+ for (const k of ["srcDir", "outDir", "pagesDir", "publicDir", "site", "base", "host"])
78
83
  check(k, "a string", str);
79
84
  for (const k of ["staticDirs", "libraryPaths", "target"])
80
85
  check(k, "an array of strings", strArr);
@@ -82,6 +87,7 @@ function validate(raw, file, warnings) {
82
87
  check(k, "true or false", v => typeof v === "boolean");
83
88
  for (const k of ["port", "previewPort"])
84
89
  check(k, "a port number (1-65535)", v => Number.isInteger(v) && v > 0 && v < 65536);
90
+ check("platform", `one of ${exports.PLATFORMS.map(p => `"${p}"`).join(", ")}`, v => exports.PLATFORMS.includes(v));
85
91
  check("site", "an absolute URL like https://example.com", v => typeof v === "string" && /^https?:\/\/[^\s]+$/.test(v));
86
92
  }
87
93
  function loadConfig(root, mode) {
@@ -118,19 +124,58 @@ function loadConfig(root, mode) {
118
124
  merged.minify = true;
119
125
  if (mode === "development" && raw.sourcemap === undefined && envOverrides.sourcemap === undefined)
120
126
  merged.sourcemap = true;
121
- merged.staticDirs = merged.staticDirs.map(d => d.replace(/^\.\//, ""));
122
- merged.libraryPaths = merged.libraryPaths.map(d => path.resolve(root, d));
127
+ const srcSet = raw.srcDir !== undefined || envOverrides.srcDir !== undefined;
128
+ merged.srcDir = path.resolve(root, srcSet ? merged.srcDir : detectSrcDir(root));
129
+ const src = merged.srcDir;
130
+ merged.staticDirs = merged.staticDirs.map(d => d.replace(/^\.\//, "").replace(/\/+$/, ""));
131
+ merged.libraryPaths = merged.libraryPaths.map(d => path.resolve(src, d));
123
132
  merged.outDir = path.resolve(root, merged.outDir);
124
- merged.pagesDir = path.resolve(root, merged.pagesDir);
133
+ merged.pagesDir = path.resolve(src, merged.pagesDir);
134
+ const publicSet = raw.publicDir !== undefined || envOverrides.publicDir !== undefined;
125
135
  merged.publicDir = path.resolve(root, merged.publicDir);
136
+ // Like Nuxt, public/ normally sits next to app/, but app/public works too.
137
+ if (!publicSet && src !== path.resolve(root) && !isDir(merged.publicDir) && isDir(path.join(src, "public")))
138
+ merged.publicDir = path.join(src, "public");
126
139
  if (!merged.base.startsWith("/"))
127
140
  merged.base = "/" + merged.base;
128
141
  if (!merged.base.endsWith("/"))
129
142
  merged.base += "/";
143
+ if (!isDir(src) && srcSet)
144
+ throw new diagnostics_1.SinthError("E0903", `srcDir '${path.relative(root, src) || "."}' does not exist`, { file, line: 1, col: 1 });
130
145
  if (merged.outDir === path.resolve(root))
131
146
  throw new diagnostics_1.SinthError("E0902", "outDir cannot be the project root", { file, line: 1, col: 1 });
132
147
  return { config: merged, file: fs.existsSync(file) ? file : undefined, warnings };
133
148
  }
149
+ function isDir(p) {
150
+ try {
151
+ return fs.statSync(p).isDirectory();
152
+ }
153
+ catch {
154
+ return false;
155
+ }
156
+ }
157
+ /**
158
+ * Uses app/ as the source folder (like Nuxt) when it exists and the root has no pages/ folder and
159
+ * no .sinth files of its own, so projects that keep everything in the root are unaffected.
160
+ */
161
+ function detectSrcDir(root) {
162
+ if (!isDir(path.join(root, "app")))
163
+ return ".";
164
+ if (isDir(path.join(root, "pages")))
165
+ return ".";
166
+ try {
167
+ if (fs.readdirSync(root).some(f => f.endsWith(".sinth")))
168
+ return ".";
169
+ }
170
+ catch {
171
+ return ".";
172
+ }
173
+ return "app";
174
+ }
175
+ /** Resolves a static asset folder (like "assets") inside the source folder. */
176
+ function staticDirPath(config, dir) {
177
+ return path.resolve(config.srcDir, dir);
178
+ }
134
179
  function stripNested(raw) {
135
180
  const out = {};
136
181
  for (const [k, v] of Object.entries(raw)) {
@@ -47,7 +47,8 @@ export declare class Project {
47
47
  invalidate(): void;
48
48
  getFile(file: string): SinthFile;
49
49
  /**
50
- * A file is a page when it lives in the pages folder (or, without one, in the project root),
50
+ * A file is a page when it lives in the pages folder (or, without one, in the source folder: the
51
+ * project root or app/),
51
52
  * is not hidden behind a leading underscore, and is not a pure component module.
52
53
  */
53
54
  private isPageFile;
@@ -68,6 +69,11 @@ export declare class Project {
68
69
  compilePage(page: PageInfo): CompiledPage;
69
70
  private expandParams;
70
71
  private needsRuntime;
72
+ /**
73
+ * `/components/Card.sinth` in an import means the source folder (the root or app/). Files that
74
+ * only exist in the project root (for example styles next to app/) still resolve.
75
+ */
76
+ private rootPath;
71
77
  resolveAsset(value: string, fromFile: string): string;
72
78
  }
73
79
  export declare function routeParams(rel: string): string[];
@@ -43,6 +43,7 @@ const codegen_1 = require("../compiler/codegen");
43
43
  const diagnostics_1 = require("../compiler/diagnostics");
44
44
  const prerender_1 = require("../compiler/prerender");
45
45
  const parser_1 = require("../compiler/parser");
46
+ const config_1 = require("./config");
46
47
  exports.PACKAGE_ROOT = path.resolve(__dirname, "..", "..");
47
48
  exports.RUNTIME_PATH = path.join(exports.PACKAGE_ROOT, "dist", "runtime", "index.js");
48
49
  exports.ROUTER_PATH = path.join(exports.PACKAGE_ROOT, "dist", "runtime", "router.js");
@@ -92,13 +93,14 @@ class Project {
92
93
  return parsed;
93
94
  }
94
95
  /**
95
- * A file is a page when it lives in the pages folder (or, without one, in the project root),
96
+ * A file is a page when it lives in the pages folder (or, without one, in the source folder: the
97
+ * project root or app/),
96
98
  * is not hidden behind a leading underscore, and is not a pure component module.
97
99
  */
98
100
  isPageFile(abs, parsed) {
99
101
  const pagesDir = this.config.pagesDir;
100
102
  const hasPagesDir = fs.existsSync(pagesDir);
101
- const base = hasPagesDir ? pagesDir : this.root;
103
+ const base = hasPagesDir ? pagesDir : this.config.srcDir;
102
104
  const rel = relativeInside(base, abs);
103
105
  if (!rel)
104
106
  return false;
@@ -124,7 +126,7 @@ class Project {
124
126
  const sass = load("sass");
125
127
  this.scssCompiler = (src, file) => {
126
128
  try {
127
- return sass.compileString(src, { loadPaths: [path.dirname(file), this.root], style: "expanded" }).css;
129
+ return sass.compileString(src, { loadPaths: [path.dirname(file), this.config.srcDir, this.root], style: "expanded" }).css;
128
130
  }
129
131
  catch (err) {
130
132
  throw new diagnostics_1.SinthError("E0402", `SCSS error: ${err.message.split("\n")[0]}`, { file, line: 1, col: 1 });
@@ -141,7 +143,7 @@ class Project {
141
143
  }
142
144
  findPages() {
143
145
  const pagesDir = this.config.pagesDir;
144
- const base = fs.existsSync(pagesDir) ? pagesDir : this.root;
146
+ const base = fs.existsSync(pagesDir) ? pagesDir : this.config.srcDir;
145
147
  const out = [];
146
148
  const walk = (dir) => {
147
149
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
@@ -149,7 +151,7 @@ class Project {
149
151
  if (entry.isDirectory()) {
150
152
  if (IGNORED_DIRS.has(entry.name) || entry.name.startsWith(".") || full === this.config.outDir)
151
153
  continue;
152
- if (base === this.root && ROOT_MODULE_DIRS.has(entry.name))
154
+ if (base === this.config.srcDir && ROOT_MODULE_DIRS.has(entry.name))
153
155
  continue;
154
156
  walk(full);
155
157
  }
@@ -164,7 +166,7 @@ class Project {
164
166
  return out.sort((a, b) => a.route.localeCompare(b.route));
165
167
  }
166
168
  pagesBase() {
167
- return fs.existsSync(this.config.pagesDir) ? this.config.pagesDir : this.root;
169
+ return fs.existsSync(this.config.pagesDir) ? this.config.pagesDir : this.config.srcDir;
168
170
  }
169
171
  pageInfo(file, base = this.pagesBase()) {
170
172
  const rel = path.relative(base, file).replace(/\\/g, "/").replace(/\.sinth$/, "");
@@ -259,7 +261,7 @@ class Project {
259
261
  const isRelative = source.startsWith("./") || source.startsWith("../");
260
262
  const isRootAbs = source.startsWith("/") && !source.startsWith("//");
261
263
  const isUrl = /^(https?:)?\/\//.test(source);
262
- const localBase = isRootAbs ? path.join(this.root, source) : path.resolve(path.dirname(from), source);
264
+ const localBase = isRootAbs ? this.rootPath(source) : path.resolve(path.dirname(from), source);
263
265
  switch (decl.kind) {
264
266
  case "style": {
265
267
  if (isUrl)
@@ -488,19 +490,31 @@ class Project {
488
490
  };
489
491
  return visit(path.resolve(pageFile));
490
492
  }
493
+ /**
494
+ * `/components/Card.sinth` in an import means the source folder (the root or app/). Files that
495
+ * only exist in the project root (for example styles next to app/) still resolve.
496
+ */
497
+ rootPath(source) {
498
+ const inSrc = path.join(this.config.srcDir, source);
499
+ if (this.config.srcDir === path.resolve(this.root))
500
+ return inSrc;
501
+ const inRoot = path.join(this.root, source);
502
+ const exists = (p) => fs.existsSync(p) || (fs.existsSync(path.dirname(p)) && fs.readdirSync(path.dirname(p)).some(f => f.startsWith(path.basename(p) + ".")));
503
+ return !exists(inSrc) && exists(inRoot) ? inRoot : inSrc;
504
+ }
491
505
  resolveAsset(value, fromFile) {
492
506
  if (/^([a-z]+:|\/\/|#|data:)/i.test(value) || value.startsWith("/"))
493
507
  return value;
494
- const candidates = [path.resolve(path.dirname(fromFile), value), path.resolve(this.root, value)];
508
+ const candidates = [path.resolve(path.dirname(fromFile), value), path.resolve(this.config.srcDir, value), path.resolve(this.root, value)];
495
509
  for (const c of candidates) {
496
510
  if (!fs.existsSync(c))
497
511
  continue;
498
512
  if (c.startsWith(this.config.publicDir + path.sep))
499
513
  return this.config.base + path.relative(this.config.publicDir, c).replace(/\\/g, "/");
500
514
  for (const d of this.config.staticDirs) {
501
- const dir = path.resolve(this.root, d);
515
+ const dir = (0, config_1.staticDirPath)(this.config, d);
502
516
  if (c.startsWith(dir + path.sep))
503
- return this.config.base + path.relative(this.root, c).replace(/\\/g, "/");
517
+ return this.config.base + d + "/" + path.relative(dir, c).replace(/\\/g, "/");
504
518
  }
505
519
  }
506
520
  return this.config.base + value.replace(/^\.\//, "");
@@ -413,27 +413,38 @@ export function model(node, get, set, numeric = false) {
413
413
  return;
414
414
  }
415
415
  const isNumber = numeric || type === "number" || type === "range";
416
+ // The value last written to or read from the field. The field is only overwritten when the bound
417
+ // value changes from it, so typing (an empty number field, "1." on the way to "1.5") is not undone.
418
+ const NONE = {};
419
+ let synced = NONE;
416
420
  effect(() => {
417
421
  const v = get();
422
+ if (Object.is(v, synced))
423
+ return;
424
+ synced = v;
418
425
  const str = v === null || v === undefined ? "" : String(v);
419
426
  if (input.value !== str && !(isNumber && Number(input.value) === v && input.value !== "")) {
420
427
  input.value = str;
421
428
  }
422
429
  });
430
+ const write = (v) => {
431
+ synced = v;
432
+ set(v);
433
+ };
423
434
  const evt = tag === "SELECT" || type === "range" || type === "color" || type === "date" || type === "file" ? "change" : "input";
424
435
  on(node, evt, () => {
425
436
  if (!isNumber) {
426
- set(input.value);
437
+ write(input.value);
427
438
  return;
428
439
  }
429
440
  if (input.value === "")
430
441
  return;
431
442
  const n = Number(input.value);
432
443
  if (!Number.isNaN(n))
433
- set(n);
444
+ write(n);
434
445
  });
435
446
  if (evt === "change" && type === "range")
436
- on(node, "input", () => set(Number(input.value)));
447
+ on(node, "input", () => write(Number(input.value)));
437
448
  }
438
449
  export function ref(node, set) {
439
450
  set(node);
@@ -673,11 +684,16 @@ export function slot(parent, slots, name, fallback) {
673
684
  fallback(parent);
674
685
  }
675
686
  export function onMount(fn) {
687
+ // The callback runs after the current render, when `current` is no longer this component's
688
+ // owner, so the owner is captured now. A returned cleanup runs when the component is removed.
689
+ const owner = current;
676
690
  queueMicrotask(() => {
691
+ if (owner.disposed)
692
+ return;
677
693
  try {
678
- const cleanup = fn();
694
+ const cleanup = withOwner(owner, fn);
679
695
  if (typeof cleanup === "function")
680
- current.cleanups.push(cleanup);
696
+ owner.cleanups.push(cleanup);
681
697
  settle(cleanup);
682
698
  }
683
699
  catch (err) {
@@ -752,6 +768,8 @@ export function persist(key, get) {
752
768
  });
753
769
  }
754
770
  const memoCache = new Map();
771
+ /** Results kept per memoized function; the oldest are dropped beyond this. */
772
+ const MEMO_LIMIT = 500;
755
773
  export function memo(site, fn, args) {
756
774
  let cache = memoCache.get(site);
757
775
  if (!cache) {
@@ -768,6 +786,8 @@ export function memo(site, fn, args) {
768
786
  if (cache.has(key))
769
787
  return cache.get(key);
770
788
  const value = fn();
789
+ if (cache.size >= MEMO_LIMIT)
790
+ cache.delete(cache.keys().next().value);
771
791
  cache.set(key, value);
772
792
  return value;
773
793
  }
@@ -776,6 +796,8 @@ export function range(a, b, step = 1) {
776
796
  const endN = b === undefined ? a : b;
777
797
  if (step === 0)
778
798
  throw new Error("range() step cannot be 0");
799
+ if (!Number.isFinite(startN) || !Number.isFinite(endN) || !Number.isFinite(step))
800
+ throw new Error("range() needs finite numbers");
779
801
  const out = [];
780
802
  if (step > 0)
781
803
  for (let i = startN; i < endN; i += step)
@@ -114,7 +114,15 @@ function scrollTo(url, restore) {
114
114
  window.scrollTo(0, restore);
115
115
  return;
116
116
  }
117
- const target = url.hash ? document.getElementById(decodeURIComponent(url.hash.slice(1))) : null;
117
+ let target = null;
118
+ if (url.hash) {
119
+ try {
120
+ target = document.getElementById(decodeURIComponent(url.hash.slice(1)));
121
+ }
122
+ catch {
123
+ target = document.getElementById(url.hash.slice(1));
124
+ }
125
+ }
118
126
  if (target)
119
127
  target.scrollIntoView();
120
128
  else
@@ -132,6 +140,14 @@ async function navigate(url, mode, restore) {
132
140
  location.href = url.href;
133
141
  return;
134
142
  }
143
+ // Follow server redirects (e.g. /about/ -> /about) so the address bar shows the final URL.
144
+ if (res.redirected && res.url) {
145
+ const final = new URL(res.url);
146
+ if (final.origin === location.origin) {
147
+ final.hash = url.hash;
148
+ url = final;
149
+ }
150
+ }
135
151
  const doc = new DOMParser().parseFromString(await res.text(), "text/html");
136
152
  if (id !== token)
137
153
  return;
@@ -42,6 +42,7 @@ const path = __importStar(require("path"));
42
42
  const diagnostics_1 = require("../compiler/diagnostics");
43
43
  const html_1 = require("../compiler/html");
44
44
  const build_1 = require("../project/build");
45
+ const config_1 = require("../project/config");
45
46
  const ui_1 = require("../cli/ui");
46
47
  const client_1 = require("./client");
47
48
  const functions_1 = require("./functions");
@@ -149,7 +150,7 @@ async function startDevServer(project, opts) {
149
150
  if (mem)
150
151
  return { status: 200, body: mem.contents, type: (0, static_1.mimeType)(sitePath), headers: NO_STORE };
151
152
  const fromPublic = (0, static_1.fileIfExists)((0, static_1.safeJoin)(cfg.publicDir, sitePath));
152
- const fromStatic = cfg.staticDirs.some(d => sitePath.startsWith("/" + d + "/")) ? (0, static_1.fileIfExists)((0, static_1.safeJoin)(project.root, sitePath)) : null;
153
+ const fromStatic = cfg.staticDirs.some(d => sitePath.startsWith("/" + d + "/")) ? (0, static_1.fileIfExists)((0, static_1.safeJoin)(cfg.srcDir, sitePath)) : null;
153
154
  const file = fromPublic ?? fromStatic;
154
155
  if (file)
155
156
  return { status: 200, body: fs.readFileSync(file), type: (0, static_1.mimeType)(file), headers: NO_STORE };
@@ -219,7 +220,7 @@ async function startDevServer(project, opts) {
219
220
  clearTimeout(timers.get(file));
220
221
  timers.set(file, setTimeout(() => {
221
222
  timers.delete(file);
222
- const inStatic = file.startsWith(cfg.publicDir + path.sep) || cfg.staticDirs.some(d => file.startsWith(path.resolve(project.root, d) + path.sep));
223
+ const inStatic = file.startsWith(cfg.publicDir + path.sep) || cfg.staticDirs.some(d => file.startsWith((0, config_1.staticDirPath)(cfg, d) + path.sep));
223
224
  if (inStatic && !file.endsWith(".css") && !file.endsWith(".sinth")) {
224
225
  broadcast({ type: "reload" });
225
226
  return;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Routing for `functions/`, following the Cloudflare Pages Functions conventions. This file has no
3
+ * Node.js imports: the dev and preview servers use it, and `platform: "cloudflare-workers"` bundles
4
+ * it into the deployed Worker, so routes behave the same everywhere.
5
+ */
6
+ export type Segment = {
7
+ kind: "static";
8
+ value: string;
9
+ } | {
10
+ kind: "param";
11
+ name: string;
12
+ } | {
13
+ kind: "catchall";
14
+ name: string;
15
+ };
16
+ export type Params = Record<string, string | string[]>;
17
+ export interface FunctionContext {
18
+ request: Request;
19
+ params: Params;
20
+ env: Record<string, unknown>;
21
+ data: Record<string, unknown>;
22
+ functionPath: string;
23
+ next(input?: Request | string, init?: RequestInit): Promise<Response>;
24
+ waitUntil(promise: Promise<unknown>): void;
25
+ passThroughOnException(): void;
26
+ }
27
+ export type Handler = (context: FunctionContext) => Response | Promise<Response>;
28
+ export type FunctionModule = Record<string, unknown>;
29
+ export interface RouteDef {
30
+ /** Path inside functions/, e.g. "api/users/[id].ts". */
31
+ rel: string;
32
+ segments: Segment[];
33
+ middleware: boolean;
34
+ }
35
+ export interface LoadedRoute extends RouteDef {
36
+ module: FunctionModule;
37
+ }
38
+ export interface DispatchOptions {
39
+ env: Record<string, unknown>;
40
+ /** Serves a static file or page; used by `next()` when no further handler applies. */
41
+ assets(request: Request): Promise<Response>;
42
+ waitUntil(promise: Promise<unknown>): void;
43
+ passThroughOnException?(): void;
44
+ }
45
+ export declare const FUNCTION_FILE: RegExp;
46
+ export declare function isFunctionFile(name: string): boolean;
47
+ export declare function routeDef(rel: string): RouteDef;
48
+ /** More specific routes first: longer paths, then static before [param] before [[catchall]]. */
49
+ export declare function compareRoutes(a: RouteDef, b: RouteDef): number;
50
+ export declare function matchRoute(route: RouteDef, parts: string[], prefixOnly: boolean): Params | null;
51
+ /**
52
+ * URL patterns that can reach a function, for hosts that only invoke code for some paths
53
+ * (Cloudflare Workers `run_worker_first`). Returns ["/*"] when a route can match anything.
54
+ */
55
+ export declare function routePatterns(routes: RouteDef[]): string[];
56
+ /**
57
+ * Runs the middleware chain and the matching route. Returns null when no function applies, so the
58
+ * caller serves the request as a static file.
59
+ */
60
+ export declare function dispatch(routes: LoadedRoute[], request: Request, opts: DispatchOptions): Promise<Response | null>;