@yannosay/sinth 5.3.3 → 5.3.4

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 (39) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +4 -2
  3. package/dist/browser/sinth.js +596 -69
  4. package/dist/cli/index.js +35 -3
  5. package/dist/cli/skill.d.ts +10 -0
  6. package/dist/cli/skill.js +106 -0
  7. package/dist/cli/templates.js +1 -1
  8. package/dist/compiler/codegen.js +4 -2
  9. package/dist/compiler/elements.d.ts +6 -0
  10. package/dist/compiler/elements.js +12 -0
  11. package/dist/compiler/html.d.ts +2 -0
  12. package/dist/compiler/html.js +7 -0
  13. package/dist/compiler/prerender.js +5 -3
  14. package/dist/deploy/platforms.js +9 -0
  15. package/dist/deploy/redirects.d.ts +31 -0
  16. package/dist/deploy/redirects.js +102 -0
  17. package/dist/project/build.js +44 -2
  18. package/dist/project/config.d.ts +6 -0
  19. package/dist/project/config.js +15 -2
  20. package/dist/project/env.d.ts +11 -0
  21. package/dist/project/env.js +84 -0
  22. package/dist/project/project.js +13 -0
  23. package/dist/runtime/index.js +21 -3
  24. package/dist/server/dev.d.ts +4 -0
  25. package/dist/server/dev.js +32 -9
  26. package/dist/server/functions.d.ts +2 -1
  27. package/dist/server/functions.js +15 -17
  28. package/dist/server/preview.d.ts +3 -0
  29. package/dist/server/preview.js +8 -1
  30. package/dist/server/static.d.ts +9 -0
  31. package/dist/server/static.js +24 -1
  32. package/lib/ui/index.sinth +533 -24
  33. package/package.json +1 -1
  34. package/schema/sinth.config.schema.json +27 -0
  35. package/skills/agents.md +15 -9
  36. package/skills/sinth/SKILL.md +66 -24
  37. package/skills/sinth/references/language.md +2 -1
  38. package/skills/sinth/references/project-and-deploy.md +18 -2
  39. package/skills/sinth/references/ui.md +95 -0
package/dist/cli/index.js CHANGED
@@ -47,6 +47,7 @@ const preview_1 = require("../server/preview");
47
47
  const args_1 = require("./args");
48
48
  const templates_1 = require("./templates");
49
49
  const ui_1 = require("./ui");
50
+ const skill_1 = require("./skill");
50
51
  const update_check_1 = require("./update-check");
51
52
  const VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "..", "package.json"), "utf-8")).version;
52
53
  const ROOT_FLAG = {
@@ -165,6 +166,8 @@ const commands = {
165
166
  open: !!args.flags.open,
166
167
  base: project.config.base,
167
168
  root: project.root,
169
+ redirects: project.config.redirects,
170
+ allowedHosts: project.config.allowedHosts,
168
171
  });
169
172
  return -1;
170
173
  },
@@ -201,15 +204,20 @@ const commands = {
201
204
  },
202
205
  check: {
203
206
  summary: "Type-check every page without writing output",
204
- usage: "sinth check [--json]",
205
- flags: { ...ROOT_FLAG, json: { type: "boolean", description: "Print diagnostics as JSON (for editors)" } },
207
+ usage: "sinth check [--json] [--max-warnings n]",
208
+ flags: {
209
+ ...ROOT_FLAG,
210
+ json: { type: "boolean", description: "Print diagnostics as JSON (for editors and AI agents)" },
211
+ "max-warnings": { type: "number", description: "Fail when there are more warnings than this (use 0 in CI)" },
212
+ },
206
213
  async run(args) {
214
+ const maxWarnings = args.flags["max-warnings"] === undefined ? Infinity : Number(args.flags["max-warnings"]);
207
215
  if (args.flags.json) {
208
216
  const root = projectRoot(args);
209
217
  const { config } = (0, config_1.loadConfig)(root, "production");
210
218
  const result = (0, build_1.checkProject)(new project_1.Project(root, config, false));
211
219
  process.stdout.write(JSON.stringify({ version: 1, errors: result.errors.map(e => e.diagnostic), warnings: result.warnings }) + "\n");
212
- return result.errors.length ? 1 : 0;
220
+ return result.errors.length || result.warnings.length > maxWarnings ? 1 : 0;
213
221
  }
214
222
  console.log(`\n ${(0, ui_1.brand)("check", VERSION)}\n`);
215
223
  const project = openProject(args, "production");
@@ -223,10 +231,33 @@ const commands = {
223
231
  ui_1.log.error(`${result.errors.length} error(s) in ${result.pages.length} page(s)`);
224
232
  return 1;
225
233
  }
234
+ if (result.warnings.length > maxWarnings) {
235
+ ui_1.log.error(`${result.warnings.length} warning(s), more than the allowed ${maxWarnings}`);
236
+ return 1;
237
+ }
226
238
  ui_1.log.success(`${result.pages.length} page(s) checked, no errors${result.warnings.length ? `, ${result.warnings.length} warning(s)` : ""} ${ui_1.c.gray((0, ui_1.formatMs)(Date.now() - started))}`);
227
239
  return 0;
228
240
  },
229
241
  },
242
+ skill: {
243
+ summary: "Teach your AI coding agent Sinth (installs the Sinth skill)",
244
+ usage: "sinth skill [--claude | --agents] [--global]",
245
+ flags: {
246
+ ...ROOT_FLAG,
247
+ claude: { type: "boolean", description: "Install for Claude Code (.claude/skills/sinth)" },
248
+ agents: { type: "boolean", description: "Install for other agents (.agents/skills/sinth and AGENTS.md)" },
249
+ global: { type: "boolean", description: "Install for all projects (~/.claude/skills/sinth)" },
250
+ },
251
+ async run(args) {
252
+ console.log(`\n ${(0, ui_1.brand)("skill", VERSION)}\n`);
253
+ const result = (0, skill_1.installSkill)(projectRoot(args), {
254
+ claude: !!args.flags.claude, agents: !!args.flags.agents, global: !!args.flags.global,
255
+ }, VERSION);
256
+ for (const line of result)
257
+ console.log(line);
258
+ return 0;
259
+ },
260
+ },
230
261
  create: {
231
262
  summary: "Create a new Sinth project",
232
263
  usage: "sinth create [name] [--template starter|minimal|blank] [--yes]",
@@ -391,6 +422,7 @@ async function createProject(args) {
391
422
  console.log(` cd ${path.relative(process.cwd(), dir)}`);
392
423
  console.log(" npm install");
393
424
  console.log(` ${ui_1.c.cyan("npm run dev")}\n`);
425
+ console.log(` ${ui_1.c.gray("Building with an AI agent? Run")} npx sinth skill ${ui_1.c.gray("to teach it Sinth.")}\n`);
394
426
  return 0;
395
427
  }
396
428
  function printHelp(command) {
@@ -0,0 +1,10 @@
1
+ export interface SkillOptions {
2
+ claude: boolean;
3
+ agents: boolean;
4
+ global: boolean;
5
+ }
6
+ /**
7
+ * Installs the Sinth skill that ships with this package, so it always matches the installed
8
+ * compiler. Returns the lines to print.
9
+ */
10
+ export declare function installSkill(root: string, opts: SkillOptions, version: string): string[];
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.installSkill = installSkill;
37
+ const fs = __importStar(require("fs"));
38
+ const os = __importStar(require("os"));
39
+ const path = __importStar(require("path"));
40
+ const diagnostics_1 = require("../compiler/diagnostics");
41
+ const project_1 = require("../project/project");
42
+ const ui_1 = require("./ui");
43
+ const SKILL_SOURCE = path.join(project_1.PACKAGE_ROOT, "skills", "sinth");
44
+ const AGENTS_SECTION = [
45
+ "## Sinth",
46
+ "",
47
+ "This project uses Sinth (.sinth files). Before working on it, read `.agents/skills/sinth/SKILL.md` and follow it. More detail is in `.agents/skills/sinth/references/`.",
48
+ "",
49
+ ].join("\n");
50
+ function copyDir(from, to) {
51
+ let count = 0;
52
+ fs.mkdirSync(to, { recursive: true });
53
+ for (const e of fs.readdirSync(from, { withFileTypes: true })) {
54
+ const src = path.join(from, e.name);
55
+ const dest = path.join(to, e.name);
56
+ if (e.isDirectory())
57
+ count += copyDir(src, dest);
58
+ else {
59
+ fs.copyFileSync(src, dest);
60
+ count++;
61
+ }
62
+ }
63
+ return count;
64
+ }
65
+ /** Adds or replaces the "## Sinth" section of AGENTS.md, which Codex, Cursor, Copilot and others read. */
66
+ function writeAgentsSection(file) {
67
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : "";
68
+ const start = existing.search(/^## Sinth\s*$/m);
69
+ let next;
70
+ if (start === -1)
71
+ next = (existing.trim() ? existing.replace(/\s*$/, "\n\n") : "# Agent instructions\n\n") + AGENTS_SECTION;
72
+ else {
73
+ const rest = existing.slice(start + 1);
74
+ const end = rest.search(/^## /m);
75
+ next = existing.slice(0, start) + AGENTS_SECTION + (end === -1 ? "" : "\n" + rest.slice(end));
76
+ }
77
+ fs.writeFileSync(file, next);
78
+ }
79
+ /**
80
+ * Installs the Sinth skill that ships with this package, so it always matches the installed
81
+ * compiler. Returns the lines to print.
82
+ */
83
+ function installSkill(root, opts, version) {
84
+ if (!fs.existsSync(path.join(SKILL_SOURCE, "SKILL.md")))
85
+ throw new diagnostics_1.SinthError("E1310", "The Sinth skill is missing from this installation", undefined, "Reinstall @yannosay/sinth");
86
+ const forClaude = opts.global || opts.claude || (!opts.agents && (fs.existsSync(path.join(root, ".claude")) || fs.existsSync(path.join(root, "CLAUDE.md"))));
87
+ const targets = [];
88
+ if (opts.global)
89
+ targets.push({ label: "Claude Code (all projects)", dir: path.join(os.homedir(), ".claude", "skills", "sinth") });
90
+ else if (forClaude)
91
+ targets.push({ label: "Claude Code", dir: path.join(root, ".claude", "skills", "sinth") });
92
+ if (opts.agents || (!forClaude && !opts.global))
93
+ targets.push({ label: "AGENTS.md agents (Codex, Cursor, Copilot, Gemini, ...)", dir: path.join(root, ".agents", "skills", "sinth") });
94
+ const out = [];
95
+ const show = (p) => (p.startsWith(root + path.sep) ? path.relative(root, p) : p.startsWith(os.homedir()) ? "~" + p.slice(os.homedir().length) : p).replace(/\\/g, "/");
96
+ for (const t of targets) {
97
+ copyDir(SKILL_SOURCE, t.dir);
98
+ out.push(` ${ui_1.c.green("✓")} ${ui_1.c.bold(`Sinth skill ${version}`)} installed for ${t.label}`, ` ${ui_1.c.gray(show(t.dir))}`);
99
+ if (t.dir.includes(`${path.sep}.agents${path.sep}`)) {
100
+ writeAgentsSection(path.join(root, "AGENTS.md"));
101
+ out.push(` ${ui_1.c.gray("AGENTS.md points your agent to it")}`);
102
+ }
103
+ }
104
+ out.push("", " Your agent now knows Sinth's syntax and components, checks each change with", ` ${ui_1.c.cyan("sinth check")} and keeps code small by reaching for ${ui_1.c.cyan("sinth:ui")} first.`, "", ` ${ui_1.c.bold("Try asking it")}`, ` ${ui_1.c.gray("›")} Add a contact form with validation to the home page`, ` ${ui_1.c.gray("›")} Build a dashboard page with a sortable table and a settings modal`, ` ${ui_1.c.gray("›")} Deploy this site to Cloudflare`, "", ` ${ui_1.c.gray("Run this again after updating Sinth to refresh the skill.")}`, "");
105
+ return out;
106
+ }
@@ -24,7 +24,7 @@ function templateFiles(template, name, version) {
24
24
  scripts: { dev: "sinth dev", build: "sinth build", preview: "sinth preview", check: "sinth check", deploy: "sinth deploy" },
25
25
  devDependencies: { "@yannosay/sinth": `^${version.replace(/-.*$/, "")}` },
26
26
  }, null, 2) + "\n",
27
- ".gitignore": "node_modules/\ndist/\n.sinth/\n.wrangler/\n.dev.vars\n.env\n",
27
+ ".gitignore": "node_modules/\ndist/\n.sinth/\n.wrangler/\n.vercel/\n.dev.vars\n.env\n.env.local\n.env.*.local\n",
28
28
  "README.md": `# ${name}\n\nBuilt with [Sinth](https://sinth.yannosay.com).\n\n\`\`\`bash\nnpm install\nnpm run dev # http://localhost:3000\nnpm run build # production build in dist/\nnpm run deploy # deploy to Cloudflare Pages\n\`\`\`\n`,
29
29
  "public/robots.txt": "User-agent: *\nAllow: /\n",
30
30
  };
@@ -489,8 +489,10 @@ class ModuleCompiler {
489
489
  switch (node.k) {
490
490
  case "text":
491
491
  return this.genText(node.expr, parent, ctx);
492
- case "element":
493
- return this.genElement(node, parent, ctx, roots);
492
+ case "element": {
493
+ const value = (0, elements_1.bareValueRef)(node, n => { const b = ctx.scope.lookup(n); return !!b && b.kind !== "component"; });
494
+ return value ? this.genText(value, parent, ctx) : this.genElement(node, parent, ctx, roots);
495
+ }
494
496
  case "if":
495
497
  return this.genIf(node, parent, ctx, !!roots);
496
498
  case "for":
@@ -1,3 +1,4 @@
1
+ import type { ElementNode, Expr } from "./ast";
1
2
  export interface ElementInfo {
2
3
  tag: string;
3
4
  className?: string;
@@ -12,3 +13,8 @@ export declare const INLINE_STYLE_PROPS: ReadonlySet<string>;
12
13
  export declare const URL_ATTRS: ReadonlySet<string>;
13
14
  export declare const BOOLEAN_ATTRS: ReadonlySet<string>;
14
15
  export declare function attrNameToHtml(name: string): string;
16
+ /**
17
+ * A capitalized name written as a child, like `P { API_URL }`, parses as an element. When it is not
18
+ * an element but a value in scope (a constant, an import from sinth:env, ...), it is text instead.
19
+ */
20
+ export declare function bareValueRef(node: ElementNode, isValue: (name: string) => boolean): Expr | null;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BOOLEAN_ATTRS = exports.URL_ATTRS = exports.INLINE_STYLE_PROPS = exports.VOID_TAGS = exports.SPECIAL_ELEMENTS = exports.ELEMENTS = void 0;
4
4
  exports.attrNameToHtml = attrNameToHtml;
5
+ exports.bareValueRef = bareValueRef;
5
6
  const e = (tag, extra = {}) => ({ tag, ...extra });
6
7
  exports.ELEMENTS = {
7
8
  Main: e("main"), Header: e("header"), Footer: e("footer"), Nav: e("nav"), Section: e("section"), Article: e("article"),
@@ -76,3 +77,14 @@ function attrNameToHtml(name) {
76
77
  };
77
78
  return map[name] ?? name;
78
79
  }
80
+ /**
81
+ * A capitalized name written as a child, like `P { API_URL }`, parses as an element. When it is not
82
+ * an element but a value in scope (a constant, an import from sinth:env, ...), it is text instead.
83
+ */
84
+ function bareValueRef(node, isValue) {
85
+ if (node.attrs.length || node.children.length || node.slots.length || node.hasBody || node.name.includes("."))
86
+ return null;
87
+ if (exports.ELEMENTS[node.name] || exports.SPECIAL_ELEMENTS.has(node.name) || !isValue(node.name))
88
+ return null;
89
+ return { k: "id", name: node.name, loc: node.loc };
90
+ }
@@ -1,6 +1,8 @@
1
1
  import { MetaEntry } from "./ast";
2
2
  export declare function escapeHtml(s: string): string;
3
3
  export declare function escapeAttr(s: string): string;
4
+ /** True for URLs that run script when followed (javascript:, vbscript:, data:text/html, ...). Mirrors the runtime check. */
5
+ export declare function isUnsafeUrl(value: string): boolean;
4
6
  export declare function hashString(s: string): string;
5
7
  export interface HeadData {
6
8
  title?: string;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.escapeHtml = escapeHtml;
4
4
  exports.escapeAttr = escapeAttr;
5
+ exports.isUnsafeUrl = isUnsafeUrl;
5
6
  exports.hashString = hashString;
6
7
  exports.buildHead = buildHead;
7
8
  exports.renderDocument = renderDocument;
@@ -12,6 +13,12 @@ function escapeHtml(s) {
12
13
  function escapeAttr(s) {
13
14
  return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
14
15
  }
16
+ const UNSAFE_URL = /^(javascript:|vbscript:|data:(?!image\/(png|gif|jpe?g|webp|avif|svg\+xml)[;,]|video\/|audio\/))/i;
17
+ /** True for URLs that run script when followed (javascript:, vbscript:, data:text/html, ...). Mirrors the runtime check. */
18
+ function isUnsafeUrl(value) {
19
+ // eslint-disable-next-line no-control-regex
20
+ return UNSAFE_URL.test(value.replace(/[\u0000- \u007f]/g, ""));
21
+ }
15
22
  function hashString(s) {
16
23
  let h1 = 0x811c9dc5;
17
24
  let h2 = 0x01000193;
@@ -521,8 +521,10 @@ class Prerenderer {
521
521
  }
522
522
  return (0, html_1.escapeHtml)(toText(v));
523
523
  }
524
- case "element":
525
- return this.renderElement(node, scope);
524
+ case "element": {
525
+ const value = (0, elements_1.bareValueRef)(node, n => !this.components(scope.file).has(n) && !!scope.env.find(n));
526
+ return value ? this.renderNode({ k: "text", expr: value, loc: node.loc }, scope) : this.renderElement(node, scope);
527
+ }
526
528
  case "if": {
527
529
  for (const br of node.branches) {
528
530
  const t = br.test ? this.eval(br.test, scope.env, scope.file) : true;
@@ -684,7 +686,7 @@ class Prerenderer {
684
686
  if (/^on/i.test(name))
685
687
  continue;
686
688
  const str = v === true ? "" : typeof v === "object" ? JSON.stringify(v) : String(v);
687
- attrs.set(name, /^(href|src|action|formaction|poster)$/.test(name) && /^\s*(javascript|vbscript):/i.test(str) ? "about:blank#blocked" : str);
689
+ attrs.set(name, elements_1.URL_ATTRS.has(name) && (0, html_1.isUnsafeUrl)(str) ? "about:blank#blocked" : str);
688
690
  }
689
691
  const cls = classes.filter(Boolean).join(" ");
690
692
  if (cls)
@@ -48,6 +48,7 @@ const diagnostics_1 = require("../compiler/diagnostics");
48
48
  const functions_1 = require("../server/functions");
49
49
  const functions_router_1 = require("../server/functions-router");
50
50
  const cloudflare_1 = require("./cloudflare");
51
+ const redirects_1 = require("./redirects");
51
52
  /** Wrangler compatibility date for generated Worker configs. */
52
53
  const COMPATIBILITY_DATE = "2025-09-01";
53
54
  const IMMUTABLE = "public, max-age=31536000, immutable";
@@ -95,6 +96,13 @@ async function writePlatformOutput(project, files, headers, write) {
95
96
  hint: "Server functions run on Cloudflare: set \"platform\" to \"cloudflare\" or \"cloudflare-workers\" in sinth.config.json",
96
97
  });
97
98
  }
99
+ if (cfg.platform === "github-pages") {
100
+ const patterns = cfg.redirects.filter(r => (0, redirects_1.isPattern)(r.from)).map(r => r.from);
101
+ if (patterns.length)
102
+ warnings.push({ severity: "warning", code: "W0811", message: `GitHub Pages cannot redirect patterns: ${patterns.join(", ")}`, hint: "Exact paths become redirect pages; patterns with :params or * need a host with server-side redirects" });
103
+ if (Object.keys(cfg.headers).length)
104
+ warnings.push({ severity: "warning", code: "W0811", message: "GitHub Pages ignores the \"headers\" option", hint: "Custom response headers need Cloudflare, Netlify or Vercel" });
105
+ }
98
106
  if (!write)
99
107
  return warnings;
100
108
  if (cfg.platform === "vercel")
@@ -127,6 +135,7 @@ function writeVercelOutput(project, files, headers) {
127
135
  ];
128
136
  if (Object.keys(headers).length)
129
137
  routes.push({ src: "^/(.*)$", headers, continue: true });
138
+ routes.push(...(0, redirects_1.vercelHeaderRoutes)(cfg.headers, cfg.base), ...(0, redirects_1.vercelRedirectRoutes)(cfg.redirects, cfg.base));
130
139
  routes.push({ handle: "filesystem" });
131
140
  if (files.has("404.html"))
132
141
  routes.push({ src: "^/(.*)$", status: 404, dest: `${cfg.base}404.html` });
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Redirects and custom headers from sinth.config.json. The same rules are applied by `sinth dev`,
3
+ * `sinth preview` and every deploy target, so a redirect behaves the same locally and in production.
4
+ *
5
+ * "redirects": { "/old": "/new", "/blog/:slug": "/posts/:slug", "/docs/*": { "to": "https://docs.example.com/:splat", "status": 302 } }
6
+ * "headers": { "/api/*": { "Access-Control-Allow-Origin": "*" } }
7
+ */
8
+ export interface Redirect {
9
+ from: string;
10
+ to: string;
11
+ status: number;
12
+ }
13
+ export type HeaderRules = Record<string, Record<string, string>>;
14
+ export declare const REDIRECT_STATUSES: number[];
15
+ /** True when the pattern has `:params` or a `*` splat. */
16
+ export declare function isPattern(from: string): boolean;
17
+ /** Finds the redirect for a site path (without the base). Returns the target with params filled in. */
18
+ export declare function matchRedirect(rules: Redirect[], sitePath: string, search?: string): {
19
+ location: string;
20
+ status: number;
21
+ } | null;
22
+ /** A `_redirects` file (Cloudflare Pages and Workers, Netlify). */
23
+ export declare function redirectsFile(rules: Redirect[], base: string): string;
24
+ /** Extra rules for a `_headers` file. */
25
+ export declare function headerRulesFile(rules: HeaderRules, base: string): string;
26
+ /** Vercel Build Output API routes for the redirects (placed before the filesystem). */
27
+ export declare function vercelRedirectRoutes(rules: Redirect[], base: string): Record<string, unknown>[];
28
+ /** Vercel routes that add the custom headers. `*` matches any characters. */
29
+ export declare function vercelHeaderRoutes(rules: HeaderRules, base: string): Record<string, unknown>[];
30
+ /** A static page that redirects, for hosts without server-side redirects (GitHub Pages). */
31
+ export declare function redirectPage(to: string): string;
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ /**
3
+ * Redirects and custom headers from sinth.config.json. The same rules are applied by `sinth dev`,
4
+ * `sinth preview` and every deploy target, so a redirect behaves the same locally and in production.
5
+ *
6
+ * "redirects": { "/old": "/new", "/blog/:slug": "/posts/:slug", "/docs/*": { "to": "https://docs.example.com/:splat", "status": 302 } }
7
+ * "headers": { "/api/*": { "Access-Control-Allow-Origin": "*" } }
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.REDIRECT_STATUSES = void 0;
11
+ exports.isPattern = isPattern;
12
+ exports.matchRedirect = matchRedirect;
13
+ exports.redirectsFile = redirectsFile;
14
+ exports.headerRulesFile = headerRulesFile;
15
+ exports.vercelRedirectRoutes = vercelRedirectRoutes;
16
+ exports.vercelHeaderRoutes = vercelHeaderRoutes;
17
+ exports.redirectPage = redirectPage;
18
+ exports.REDIRECT_STATUSES = [301, 302, 303, 307, 308];
19
+ /** True when the pattern has `:params` or a `*` splat. */
20
+ function isPattern(from) {
21
+ return /(^|\/):[A-Za-z_]|\*/.test(from);
22
+ }
23
+ function compile(r) {
24
+ const names = [];
25
+ const source = r.from.split("/").map(part => {
26
+ if (part === "*") {
27
+ names.push("splat");
28
+ return "(.*)";
29
+ }
30
+ const param = part.match(/^:([A-Za-z_]\w*)$/);
31
+ if (param) {
32
+ names.push(param[1]);
33
+ return "([^/]+)";
34
+ }
35
+ return part.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, () => {
36
+ names.push("splat");
37
+ return "(.*)";
38
+ });
39
+ }).join("/");
40
+ return { ...r, regex: new RegExp(`^${source}/?$`), names };
41
+ }
42
+ /** Param names with their group index, longest first so ":id" never replaces part of ":idx". */
43
+ function byLength(names) {
44
+ return names.map((n, i) => [n, i]).sort((a, b) => b[0].length - a[0].length);
45
+ }
46
+ function withBase(p, base) {
47
+ return base !== "/" && p.startsWith("/") && !p.startsWith("//") ? base.slice(0, -1) + p : p;
48
+ }
49
+ /** Finds the redirect for a site path (without the base). Returns the target with params filled in. */
50
+ function matchRedirect(rules, sitePath, search = "") {
51
+ for (const r of rules) {
52
+ const c = compile(r);
53
+ const m = c.regex.exec(sitePath);
54
+ if (!m)
55
+ continue;
56
+ let to = r.to;
57
+ for (const [name, i] of byLength(c.names))
58
+ to = to.split(":" + name).join(m[i + 1] ?? "");
59
+ if (search && !to.includes("?"))
60
+ to += search;
61
+ return { location: to, status: r.status };
62
+ }
63
+ return null;
64
+ }
65
+ /** A `_redirects` file (Cloudflare Pages and Workers, Netlify). */
66
+ function redirectsFile(rules, base) {
67
+ return rules.map(r => `${withBase(r.from, base)} ${withBase(r.to, base)} ${r.status}`).join("\n") + "\n";
68
+ }
69
+ /** Extra rules for a `_headers` file. */
70
+ function headerRulesFile(rules, base) {
71
+ const out = [];
72
+ for (const [pattern, headers] of Object.entries(rules)) {
73
+ out.push(withBase(pattern, base));
74
+ for (const [k, v] of Object.entries(headers))
75
+ out.push(` ${k}: ${v}`);
76
+ out.push("");
77
+ }
78
+ return out.join("\n");
79
+ }
80
+ /** Vercel Build Output API routes for the redirects (placed before the filesystem). */
81
+ function vercelRedirectRoutes(rules, base) {
82
+ return rules.map(r => {
83
+ const c = compile({ ...r, from: withBase(r.from, base) });
84
+ let dest = withBase(r.to, base);
85
+ for (const [name, i] of byLength(c.names))
86
+ dest = dest.split(":" + name).join("$" + (i + 1));
87
+ return { src: c.regex.source, status: r.status, headers: { Location: dest } };
88
+ });
89
+ }
90
+ /** Vercel routes that add the custom headers. `*` matches any characters. */
91
+ function vercelHeaderRoutes(rules, base) {
92
+ return Object.entries(rules).map(([pattern, headers]) => ({
93
+ src: "^" + withBase(pattern, base).replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*") + "$",
94
+ headers,
95
+ continue: true,
96
+ }));
97
+ }
98
+ /** A static page that redirects, for hosts without server-side redirects (GitHub Pages). */
99
+ function redirectPage(to) {
100
+ const esc = to.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
101
+ return `<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="utf-8">\n <title>Redirecting</title>\n <meta http-equiv="refresh" content="0; url=${esc}">\n <link rel="canonical" href="${esc}">\n <meta name="robots" content="noindex">\n</head>\n<body>\n<a href="${esc}">Continue to ${esc}</a>\n</body>\n</html>\n`;
102
+ }
@@ -43,6 +43,7 @@ const path = __importStar(require("path"));
43
43
  const diagnostics_1 = require("../compiler/diagnostics");
44
44
  const html_1 = require("../compiler/html");
45
45
  const platforms_1 = require("../deploy/platforms");
46
+ const redirects_1 = require("../deploy/redirects");
46
47
  const config_1 = require("./config");
47
48
  const project_1 = require("./project");
48
49
  const ASSET_LOADERS = {
@@ -359,6 +360,7 @@ async function buildProject(project, options) {
359
360
  }
360
361
  const csp = contentSecurityPolicy(compiled, cfg.security.csp);
361
362
  const pageOutputs = [];
363
+ const summaries = [];
362
364
  const toUrl = (abs) => cfg.base + path.relative(cfg.outDir, path.resolve(project.root, abs)).replace(/\\/g, "/");
363
365
  for (const c of compiled) {
364
366
  const key = entryKey(c.page);
@@ -394,6 +396,7 @@ async function buildProject(project, options) {
394
396
  files.delete(path.relative(cfg.outDir, path.resolve(project.root, jsOut)).replace(/\\/g, "/"));
395
397
  for (const inst of c.instances) {
396
398
  const head = (0, html_1.buildHead)(inst.meta, v => project.resolveAsset(v, c.page.file));
399
+ summaries.push({ route: inst.page.route, title: head.title, description: head.metaNames.find(([k]) => k === "description")?.[1] });
397
400
  const pageHead = inst.params && c.interactive
398
401
  ? [...inlineHead, '<script type="application/json" id="sinth-params">' + JSON.stringify(inst.params).replace(/</g, "\\u003c") + "</script>"]
399
402
  : inlineHead;
@@ -412,8 +415,29 @@ async function buildProject(project, options) {
412
415
  copyDir(cfg.publicDir, cfg.outDir, files, cfg.outDir);
413
416
  for (const d of cfg.staticDirs)
414
417
  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)) });
418
+ if ((0, platforms_1.readsHeadersFile)(cfg.platform)) {
419
+ // Sinth's rules come first; a _headers file from public/ is appended so both apply.
420
+ const own = (cfg.security.headers ? (0, platforms_1.headersFile)((0, platforms_1.securityHeaders)(csp), cfg.base) : "") + (0, redirects_1.headerRulesFile)(cfg.headers, cfg.base);
421
+ const user = files.get("_headers");
422
+ if (own.trim())
423
+ files.set("_headers", { path: path.join(cfg.outDir, "_headers"), contents: Buffer.from(own + (user ? "\n" + Buffer.from(user.contents).toString("utf-8") : "")) });
424
+ }
425
+ if (cfg.redirects.length) {
426
+ if (cfg.platform === "github-pages") {
427
+ for (const r of cfg.redirects) {
428
+ if ((0, redirects_1.isPattern)(r.from))
429
+ continue;
430
+ const rel = r.from.replace(/^\/+|\/+$/g, "");
431
+ const target = r.to.startsWith("/") && !r.to.startsWith("//") ? cfg.base + r.to.slice(1) : r.to;
432
+ const out = (rel ? rel + "/" : "") + "index.html";
433
+ if (!files.has(out))
434
+ files.set(out, { path: path.join(cfg.outDir, out), contents: Buffer.from((0, redirects_1.redirectPage)(target)) });
435
+ }
436
+ }
437
+ else if (cfg.platform !== "vercel") {
438
+ const user = files.get("_redirects");
439
+ files.set("_redirects", { path: path.join(cfg.outDir, "_redirects"), contents: Buffer.from((0, redirects_1.redirectsFile)(cfg.redirects, cfg.base) + (user ? Buffer.from(user.contents).toString("utf-8") : "")) });
440
+ }
417
441
  }
418
442
  // GitHub Pages runs Jekyll by default, which drops folders starting with "_" such as _sinth/.
419
443
  if (cfg.platform === "github-pages" && !files.has(".nojekyll"))
@@ -422,6 +446,8 @@ async function buildProject(project, options) {
422
446
  const site = cfg.site.replace(/\/$/, "");
423
447
  const urls = pageOutputs.filter(p => !/(^|\/)404$/.test(p.page.route)).map(p => ` <url><loc>${(0, html_1.escapeHtml)(site + p.page.route)}</loc></url>`);
424
448
  files.set("sitemap.xml", { path: path.join(cfg.outDir, "sitemap.xml"), contents: Buffer.from(`<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls.join("\n")}\n</urlset>\n`) });
449
+ if (!files.has("llms.txt"))
450
+ files.set("llms.txt", { path: path.join(cfg.outDir, "llms.txt"), contents: Buffer.from(llmsTxt(site, summaries)) });
425
451
  if (!files.has("robots.txt"))
426
452
  files.set("robots.txt", { path: path.join(cfg.outDir, "robots.txt"), contents: Buffer.from(`User-agent: *\nAllow: /\n\nSitemap: ${site}/sitemap.xml\n`) });
427
453
  }
@@ -443,6 +469,22 @@ async function buildProject(project, options) {
443
469
  const warnings = dedupeWarnings([...compiled.flatMap(c => c.warnings), ...bundlerWarnings, ...platformWarnings]);
444
470
  return { pages: pageOutputs, files, warnings, durationMs: Date.now() - started };
445
471
  }
472
+ /**
473
+ * An llms.txt (https://llmstxt.org) index of the site for AI assistants and answer engines: the home
474
+ * page's title and description, then one line per page.
475
+ */
476
+ function llmsTxt(site, pages) {
477
+ const visible = pages.filter(p => !/(^|\/)404$/.test(p.route)).sort((a, b) => a.route.localeCompare(b.route));
478
+ const home = visible.find(p => p.route === "/");
479
+ const oneLine = (s) => s.replace(/\s+/g, " ").trim();
480
+ const lines = [`# ${oneLine(home?.title ?? new URL(site).hostname)}`, ""];
481
+ if (home?.description)
482
+ lines.push(`> ${oneLine(home.description)}`, "");
483
+ lines.push("## Pages", "");
484
+ for (const p of visible)
485
+ lines.push(`- [${oneLine(p.title ?? p.route)}](${site}${p.route})${p.description ? ": " + oneLine(p.description) : ""}`);
486
+ return lines.join("\n") + "\n";
487
+ }
446
488
  function dedupeWarnings(list) {
447
489
  const seen = new Set();
448
490
  return list.filter(d => {
@@ -1,3 +1,4 @@
1
+ import { HeaderRules, Redirect } from "../deploy/redirects";
1
2
  export interface CloudflareConfig {
2
3
  projectName?: string;
3
4
  accountId?: string;
@@ -30,6 +31,11 @@ export interface SinthConfig {
30
31
  router: boolean;
31
32
  security: SecurityConfig;
32
33
  cloudflare: CloudflareConfig;
34
+ /** Normalized from the config's object form (`{ "/old": "/new" }`). */
35
+ redirects: Redirect[];
36
+ headers: HeaderRules;
37
+ /** Extra host names the dev and preview servers answer to (DNS rebinding protection), or true for any. */
38
+ allowedHosts: string[] | true;
33
39
  }
34
40
  export declare const DEFAULT_CONFIG: SinthConfig;
35
41
  export interface LoadedConfig {
@@ -40,6 +40,7 @@ exports.staticDirPath = staticDirPath;
40
40
  const fs = __importStar(require("fs"));
41
41
  const path = __importStar(require("path"));
42
42
  const diagnostics_1 = require("../compiler/diagnostics");
43
+ const redirects_1 = require("../deploy/redirects");
43
44
  exports.PLATFORMS = ["cloudflare", "cloudflare-workers", "vercel", "netlify", "github-pages", "static"];
44
45
  exports.DEFAULT_CONFIG = {
45
46
  platform: "cloudflare",
@@ -59,10 +60,13 @@ exports.DEFAULT_CONFIG = {
59
60
  router: true,
60
61
  security: { headers: true, csp: true },
61
62
  cloudflare: {},
63
+ redirects: [],
64
+ headers: {},
65
+ allowedHosts: [],
62
66
  };
63
67
  const KNOWN_KEYS = new Set([
64
68
  "platform", "srcDir", "outDir", "pagesDir", "publicDir", "staticDirs", "libraryPaths", "site", "base", "minify", "sourcemap", "port", "host",
65
- "previewPort", "target", "router", "security", "cloudflare", "development", "production", "$schema",
69
+ "previewPort", "target", "router", "security", "cloudflare", "development", "production", "$schema", "redirects", "headers", "allowedHosts",
66
70
  "sharedRuntime", "inlineJS", "inlineCSS",
67
71
  ]);
68
72
  const LEGACY_KEYS = new Set(["sharedRuntime", "inlineJS", "inlineCSS"]);
@@ -89,6 +93,13 @@ function validate(raw, file, warnings) {
89
93
  check(k, "a port number (1-65535)", v => Number.isInteger(v) && v > 0 && v < 65536);
90
94
  check("platform", `one of ${exports.PLATFORMS.map(p => `"${p}"`).join(", ")}`, v => exports.PLATFORMS.includes(v));
91
95
  check("site", "an absolute URL like https://example.com", v => typeof v === "string" && /^https?:\/\/[^\s]+$/.test(v));
96
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
97
+ check("redirects", 'an object like { "/old": "/new" } (status 301, 302, 303, 307 or 308)', v => isObj(v) && Object.entries(v).every(([from, to]) => from.startsWith("/") && (typeof to === "string" || (isObj(to) && typeof to.to === "string" && (to.status === undefined || redirects_1.REDIRECT_STATUSES.includes(to.status))))));
98
+ check("allowedHosts", "an array of host names or true", v => v === true || (Array.isArray(v) && v.every(x => typeof x === "string")));
99
+ check("headers", 'an object like { "/api/*": { "Cache-Control": "no-store" } }', v => isObj(v) && Object.entries(v).every(([p, h]) => p.startsWith("/") && isObj(h) && Object.entries(h).every(([k, x]) => /^[A-Za-z0-9-]+$/.test(k) && typeof x === "string" && !/[\r\n]/.test(x))));
100
+ }
101
+ function normalizeRedirects(raw) {
102
+ return Object.entries(raw ?? {}).map(([from, to]) => (typeof to === "string" ? { from, to, status: 301 } : { from, to: to.to, status: to.status ?? 301 }));
92
103
  }
93
104
  function loadConfig(root, mode) {
94
105
  const warnings = [];
@@ -119,6 +130,8 @@ function loadConfig(root, mode) {
119
130
  ...stripNested(envOverrides),
120
131
  security: { ...exports.DEFAULT_CONFIG.security, ...(raw.security ?? {}), ...(envOverrides.security ?? {}) },
121
132
  cloudflare: { ...(raw.cloudflare ?? {}) },
133
+ redirects: normalizeRedirects({ ...(raw.redirects ?? {}), ...(envOverrides.redirects ?? {}) }),
134
+ headers: { ...(raw.headers ?? {}), ...(envOverrides.headers ?? {}) },
122
135
  };
123
136
  if (mode === "production" && raw.minify === undefined && envOverrides.minify === undefined)
124
137
  merged.minify = true;
@@ -179,7 +192,7 @@ function staticDirPath(config, dir) {
179
192
  function stripNested(raw) {
180
193
  const out = {};
181
194
  for (const [k, v] of Object.entries(raw)) {
182
- if (k === "development" || k === "production" || k === "security" || k === "cloudflare" || k === "$schema" || LEGACY_KEYS.has(k))
195
+ if (k === "development" || k === "production" || k === "security" || k === "cloudflare" || k === "redirects" || k === "headers" || k === "$schema" || LEGACY_KEYS.has(k))
183
196
  continue;
184
197
  if (v !== undefined)
185
198
  out[k] = v;