@yannosay/sinth 5.3.2 → 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 (46) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +16 -4
  3. package/dist/browser/sinth.js +630 -81
  4. package/dist/cli/index.js +52 -10
  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 +42 -5
  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/cloudflare.d.ts +2 -0
  15. package/dist/deploy/cloudflare.js +103 -18
  16. package/dist/deploy/platforms.d.ts +20 -0
  17. package/dist/deploy/platforms.js +212 -0
  18. package/dist/deploy/redirects.d.ts +31 -0
  19. package/dist/deploy/redirects.js +102 -0
  20. package/dist/project/build.js +104 -18
  21. package/dist/project/config.d.ts +19 -0
  22. package/dist/project/config.js +66 -8
  23. package/dist/project/env.d.ts +11 -0
  24. package/dist/project/env.js +84 -0
  25. package/dist/project/project.d.ts +7 -1
  26. package/dist/project/project.js +37 -10
  27. package/dist/runtime/index.js +48 -8
  28. package/dist/runtime/router.js +17 -1
  29. package/dist/server/dev.d.ts +4 -0
  30. package/dist/server/dev.js +35 -11
  31. package/dist/server/functions-router.d.ts +60 -0
  32. package/dist/server/functions-router.js +161 -0
  33. package/dist/server/functions.d.ts +8 -12
  34. package/dist/server/functions.js +43 -133
  35. package/dist/server/preview.d.ts +3 -0
  36. package/dist/server/preview.js +8 -1
  37. package/dist/server/static.d.ts +9 -0
  38. package/dist/server/static.js +24 -1
  39. package/lib/ui/index.sinth +533 -24
  40. package/package.json +2 -1
  41. package/schema/sinth.config.schema.json +30 -1
  42. package/skills/agents.md +62 -0
  43. package/skills/sinth/SKILL.md +125 -0
  44. package/skills/sinth/references/language.md +175 -0
  45. package/skills/sinth/references/project-and-deploy.md +87 -0
  46. package/skills/sinth/references/ui.md +95 -0
@@ -34,16 +34,20 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.defaultProjectName = defaultProjectName;
37
+ exports.deploy = deploy;
37
38
  exports.deployToCloudflare = deployToCloudflare;
38
39
  const child_process_1 = require("child_process");
39
40
  const fs = __importStar(require("fs"));
40
41
  const path = __importStar(require("path"));
41
42
  const diagnostics_1 = require("../compiler/diagnostics");
42
43
  const ui_1 = require("../cli/ui");
44
+ const platforms_1 = require("./platforms");
43
45
  const PROJECT_NAME = /^[a-z0-9][a-z0-9-]{0,56}[a-z0-9]$/;
44
46
  const BRANCH_NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,99}$/;
45
47
  const ACCOUNT_ID = /^[a-f0-9]{32}$/;
46
48
  const WRANGLER = "wrangler@4";
49
+ const VERCEL = "vercel@latest";
50
+ const NETLIFY = "netlify-cli@latest";
47
51
  function defaultProjectName(root) {
48
52
  let name = path.basename(root);
49
53
  const pkg = path.join(root, "package.json");
@@ -63,49 +67,130 @@ function sanitizeName(name) {
63
67
  const cleaned = name.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 58);
64
68
  return cleaned.length >= 2 ? cleaned : "sinth-site";
65
69
  }
66
- function runWrangler(args, cwd, env) {
70
+ /** Runs a host's CLI through npx, so it does not have to be installed. */
71
+ function runNpx(pkg, args, cwd, env) {
67
72
  for (const a of args) {
68
73
  if (!/^[A-Za-z0-9@._/:=\\ -]+$/.test(a))
69
- throw new diagnostics_1.SinthError("E1100", `Refusing to pass unsafe argument to wrangler: ${a}`);
74
+ throw new diagnostics_1.SinthError("E1100", `Refusing to pass unsafe argument to ${pkg}: ${a}`);
70
75
  }
71
76
  const isWin = process.platform === "win32";
72
77
  const cmd = isWin ? "npx.cmd" : "npx";
73
- const quoted = isWin ? ["--yes", WRANGLER, ...args].map(a => (/\s/.test(a) ? `"${a}"` : a)) : ["--yes", WRANGLER, ...args];
78
+ const quoted = isWin ? ["--yes", pkg, ...args].map(a => (/\s/.test(a) ? `"${a}"` : a)) : ["--yes", pkg, ...args];
74
79
  return new Promise((resolve, reject) => {
75
80
  const child = (0, child_process_1.spawn)(cmd, quoted, { cwd, env, stdio: "inherit", shell: isWin });
76
81
  child.on("error", reject);
77
82
  child.on("exit", code => resolve(code ?? 1));
78
83
  });
79
84
  }
80
- async function deployToCloudflare(root, outDir, config, opts) {
81
- const cf = config.cloudflare;
82
- const projectName = opts.projectName ?? cf.projectName ?? defaultProjectName(root);
83
- const branch = opts.branch ?? (opts.preview ? "preview" : cf.productionBranch ?? "main");
84
- if (!PROJECT_NAME.test(projectName)) {
85
- throw new diagnostics_1.SinthError("E1101", `Invalid Cloudflare Pages project name '${projectName}'`, undefined, "Use 2-58 lowercase letters, numbers and dashes, e.g. \"my-site\"");
85
+ function assertBuilt(outDir) {
86
+ if (!fs.existsSync(outDir) || (!fs.existsSync(path.join(outDir, "index.html")) && !fs.readdirSync(outDir).some(f => f.endsWith(".html")))) {
87
+ throw new diagnostics_1.SinthError("E1104", `Nothing to deploy in ${outDir}`, undefined, "Run sinth build first, or deploy without --skip-build");
86
88
  }
87
- if (!BRANCH_NAME.test(branch))
88
- throw new diagnostics_1.SinthError("E1102", `Invalid branch name '${branch}'`);
89
+ }
90
+ function cloudflareEnv(config) {
91
+ const cf = config.cloudflare;
89
92
  if (cf.accountId && !ACCOUNT_ID.test(cf.accountId))
90
93
  throw new diagnostics_1.SinthError("E1103", "cloudflare.accountId must be a 32-character hex ID from the Cloudflare dashboard");
91
- if (!fs.existsSync(path.join(outDir, "index.html")) && !fs.readdirSync(outDir).some(f => f.endsWith(".html"))) {
92
- throw new diagnostics_1.SinthError("E1104", `Nothing to deploy in ${outDir}`);
93
- }
94
94
  const env = { ...process.env };
95
95
  if (cf.accountId)
96
96
  env.CLOUDFLARE_ACCOUNT_ID = cf.accountId;
97
+ if (!env.CLOUDFLARE_API_TOKEN)
98
+ ui_1.log.step(ui_1.c.gray("Using your wrangler login. In CI, set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID."));
99
+ return env;
100
+ }
101
+ function projectNameFor(root, config, opts, what) {
102
+ const name = opts.projectName ?? config.cloudflare.projectName ?? defaultProjectName(root);
103
+ if (!PROJECT_NAME.test(name)) {
104
+ throw new diagnostics_1.SinthError("E1101", `Invalid ${what} name '${name}'`, undefined, "Use 2-58 lowercase letters, numbers and dashes, e.g. \"my-site\"");
105
+ }
106
+ return name;
107
+ }
108
+ /** Uploads a finished build to the host set by `platform`. */
109
+ async function deploy(root, config, opts) {
110
+ const platform = config.platform;
111
+ switch (platform) {
112
+ case "cloudflare":
113
+ return deployToCloudflare(root, config.outDir, config, opts);
114
+ case "cloudflare-workers":
115
+ return deployToWorkers(root, config, opts);
116
+ case "vercel":
117
+ return deployToVercel(root, opts);
118
+ case "netlify":
119
+ return deployToNetlify(root, config, opts);
120
+ case "github-pages":
121
+ case "static":
122
+ throw new diagnostics_1.SinthError("E1106", `sinth deploy has no upload step for platform "${platform}"`, undefined, platform === "github-pages"
123
+ ? "Publish dist/ with GitHub Actions (actions/upload-pages-artifact and actions/deploy-pages). See https://sinth.yannosay.com/docs/production/deploy"
124
+ : "Upload the contents of your outDir to your host, or set \"platform\" in sinth.config.json");
125
+ }
126
+ }
127
+ async function deployToCloudflare(root, outDir, config, opts) {
128
+ const cf = config.cloudflare;
129
+ const projectName = projectNameFor(root, config, opts, "Cloudflare Pages project");
130
+ const branch = opts.branch ?? (opts.preview ? "preview" : cf.productionBranch ?? "main");
131
+ if (!BRANCH_NAME.test(branch))
132
+ throw new diagnostics_1.SinthError("E1102", `Invalid branch name '${branch}'`);
133
+ assertBuilt(outDir);
134
+ const env = cloudflareEnv(config);
97
135
  if (opts.create) {
98
136
  ui_1.log.info(`Creating Cloudflare Pages project ${ui_1.c.bold(projectName)}`);
99
- const code = await runWrangler(["pages", "project", "create", projectName, "--production-branch", cf.productionBranch ?? "main"], root, env);
137
+ const code = await runNpx(WRANGLER, ["pages", "project", "create", projectName, "--production-branch", cf.productionBranch ?? "main"], root, env);
100
138
  if (code !== 0)
101
139
  ui_1.log.warn("Project creation failed or the project already exists, continuing with the deploy");
102
140
  }
103
141
  ui_1.log.info(`Deploying ${ui_1.c.bold(path.relative(root, outDir) || outDir)} to ${ui_1.c.bold(projectName)} ${ui_1.c.gray(`(branch ${branch})`)}`);
104
- if (!env.CLOUDFLARE_API_TOKEN)
105
- ui_1.log.step(ui_1.c.gray("Using your wrangler login. In CI, set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID."));
106
- const code = await runWrangler(["pages", "deploy", path.relative(root, outDir) || ".", "--project-name", projectName, "--branch", branch, "--commit-dirty=true"], root, env);
142
+ const code = await runNpx(WRANGLER, ["pages", "deploy", path.relative(root, outDir) || ".", "--project-name", projectName, "--branch", branch, "--commit-dirty=true"], root, env);
107
143
  if (code !== 0) {
108
144
  throw new diagnostics_1.SinthError("E1105", "Cloudflare deployment failed", undefined, `Check the output above. Not logged in? Run: npx ${WRANGLER} login. New project? Run: sinth deploy --create`);
109
145
  }
110
146
  ui_1.log.success(`Deployed to Cloudflare Pages (${projectName})`);
111
147
  }
148
+ async function deployToWorkers(root, config, opts) {
149
+ assertBuilt(config.outDir);
150
+ const env = cloudflareEnv(config);
151
+ const own = (0, platforms_1.userWranglerConfig)(root);
152
+ const configFile = own ?? path.join(root, platforms_1.DEPLOY_DIR, "wrangler.json");
153
+ if (!fs.existsSync(configFile))
154
+ throw new diagnostics_1.SinthError("E1104", "No Worker config found", undefined, "Run sinth build with \"platform\": \"cloudflare-workers\" first");
155
+ const args = opts.preview ? ["versions", "upload"] : ["deploy"];
156
+ args.push("--config", path.relative(root, configFile));
157
+ if (opts.projectName)
158
+ args.push("--name", projectNameFor(root, config, opts, "Worker"));
159
+ ui_1.log.info(`${opts.preview ? "Uploading a preview version of" : "Deploying"} the Worker ${ui_1.c.gray(`(config ${path.relative(root, configFile)})`)}`);
160
+ if (own)
161
+ ui_1.log.step(ui_1.c.gray(`Using your ${path.basename(own)}. It should point "assets.directory" at ${path.relative(root, config.outDir)}; see the deploy docs.`));
162
+ const code = await runNpx(WRANGLER, args, root, env);
163
+ if (code !== 0)
164
+ throw new diagnostics_1.SinthError("E1105", "Cloudflare Workers deployment failed", undefined, `Check the output above. Not logged in? Run: npx ${WRANGLER} login`);
165
+ ui_1.log.success(opts.preview ? "Uploaded a preview version to Cloudflare Workers" : "Deployed to Cloudflare Workers");
166
+ }
167
+ async function deployToVercel(root, opts) {
168
+ if (!fs.existsSync(path.join(root, ".vercel", "output", "config.json"))) {
169
+ throw new diagnostics_1.SinthError("E1104", "No Vercel build output found", undefined, "Run sinth build with \"platform\": \"vercel\" first");
170
+ }
171
+ const args = ["deploy", "--prebuilt"];
172
+ if (!opts.preview)
173
+ args.push("--prod");
174
+ ui_1.log.info(`Deploying ${ui_1.c.bold(".vercel/output")} to Vercel${opts.preview ? " (preview)" : ""}`);
175
+ if (!process.env.VERCEL_TOKEN)
176
+ ui_1.log.step(ui_1.c.gray("Using your Vercel login. The first deploy asks which project to link."));
177
+ else
178
+ args.push("--token", process.env.VERCEL_TOKEN);
179
+ const code = await runNpx(VERCEL, args, root, { ...process.env });
180
+ if (code !== 0)
181
+ throw new diagnostics_1.SinthError("E1105", "Vercel deployment failed", undefined, `Check the output above. Not logged in? Run: npx ${VERCEL} login`);
182
+ ui_1.log.success("Deployed to Vercel");
183
+ }
184
+ async function deployToNetlify(root, config, opts) {
185
+ assertBuilt(config.outDir);
186
+ const args = ["deploy", "--dir", path.relative(root, config.outDir) || ".", "--no-build"];
187
+ if (!opts.preview)
188
+ args.push("--prod");
189
+ ui_1.log.info(`Deploying ${ui_1.c.bold(path.relative(root, config.outDir))} to Netlify${opts.preview ? " (draft)" : ""}`);
190
+ if (!process.env.NETLIFY_AUTH_TOKEN)
191
+ ui_1.log.step(ui_1.c.gray("Using your Netlify login. In CI, set NETLIFY_AUTH_TOKEN and NETLIFY_SITE_ID."));
192
+ const code = await runNpx(NETLIFY, args, root, { ...process.env });
193
+ if (code !== 0)
194
+ throw new diagnostics_1.SinthError("E1105", "Netlify deployment failed", undefined, `Check the output above. Not logged in? Run: npx ${NETLIFY} login`);
195
+ ui_1.log.success("Deployed to Netlify");
196
+ }
@@ -0,0 +1,20 @@
1
+ import { Diagnostic } from "../compiler/diagnostics";
2
+ import type { OutputFile } from "../project/build";
3
+ import { Platform } from "../project/config";
4
+ import type { Project } from "../project/project";
5
+ import { scanFunctions } from "../server/functions";
6
+ export declare const DEPLOY_DIR: string;
7
+ /** Hosts that read a `_headers` file from the output folder. */
8
+ export declare function readsHeadersFile(platform: Platform): boolean;
9
+ /** Hosts that can run the server routes in functions/. */
10
+ export declare function runsFunctions(platform: Platform): boolean;
11
+ export declare function securityHeaders(csp: string | undefined): Record<string, string>;
12
+ /** A `_headers` file (Cloudflare Pages and Workers, Netlify). */
13
+ export declare function headersFile(headers: Record<string, string>, base: string): string;
14
+ export declare function functionRoutes(project: Project): ReturnType<typeof scanFunctions>;
15
+ /**
16
+ * Writes host-specific output next to the regular build: `.vercel/output` for Vercel and the
17
+ * Worker plus its wrangler config for Cloudflare Workers. Returns warnings for the build summary.
18
+ */
19
+ export declare function writePlatformOutput(project: Project, files: Map<string, OutputFile>, headers: Record<string, string>, write: boolean): Promise<Diagnostic[]>;
20
+ export declare function userWranglerConfig(root: string): string | undefined;
@@ -0,0 +1,212 @@
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.DEPLOY_DIR = void 0;
37
+ exports.readsHeadersFile = readsHeadersFile;
38
+ exports.runsFunctions = runsFunctions;
39
+ exports.securityHeaders = securityHeaders;
40
+ exports.headersFile = headersFile;
41
+ exports.functionRoutes = functionRoutes;
42
+ exports.writePlatformOutput = writePlatformOutput;
43
+ exports.userWranglerConfig = userWranglerConfig;
44
+ const esbuild = __importStar(require("esbuild"));
45
+ const fs = __importStar(require("fs"));
46
+ const path = __importStar(require("path"));
47
+ const diagnostics_1 = require("../compiler/diagnostics");
48
+ const functions_1 = require("../server/functions");
49
+ const functions_router_1 = require("../server/functions-router");
50
+ const cloudflare_1 = require("./cloudflare");
51
+ const redirects_1 = require("./redirects");
52
+ /** Wrangler compatibility date for generated Worker configs. */
53
+ const COMPATIBILITY_DATE = "2025-09-01";
54
+ const IMMUTABLE = "public, max-age=31536000, immutable";
55
+ exports.DEPLOY_DIR = path.join(".sinth", "deploy");
56
+ /** Hosts that read a `_headers` file from the output folder. */
57
+ function readsHeadersFile(platform) {
58
+ return platform === "cloudflare" || platform === "cloudflare-workers" || platform === "netlify" || platform === "static";
59
+ }
60
+ /** Hosts that can run the server routes in functions/. */
61
+ function runsFunctions(platform) {
62
+ return platform === "cloudflare" || platform === "cloudflare-workers";
63
+ }
64
+ function securityHeaders(csp) {
65
+ const headers = {
66
+ "X-Content-Type-Options": "nosniff",
67
+ "Referrer-Policy": "strict-origin-when-cross-origin",
68
+ "X-Frame-Options": "SAMEORIGIN",
69
+ "Cross-Origin-Opener-Policy": "same-origin",
70
+ };
71
+ if (csp)
72
+ headers["Content-Security-Policy"] = csp;
73
+ return headers;
74
+ }
75
+ /** A `_headers` file (Cloudflare Pages and Workers, Netlify). */
76
+ function headersFile(headers, base) {
77
+ const lines = ["/*", ...Object.entries(headers).map(([k, v]) => ` ${k}: ${v}`)];
78
+ lines.push("", `${base}_sinth/*`, ` Cache-Control: ${IMMUTABLE}`, "");
79
+ return lines.join("\n");
80
+ }
81
+ function functionRoutes(project) {
82
+ return (0, functions_1.scanFunctions)(path.join(project.root, functions_1.FUNCTIONS_DIR));
83
+ }
84
+ /**
85
+ * Writes host-specific output next to the regular build: `.vercel/output` for Vercel and the
86
+ * Worker plus its wrangler config for Cloudflare Workers. Returns warnings for the build summary.
87
+ */
88
+ async function writePlatformOutput(project, files, headers, write) {
89
+ const cfg = project.config;
90
+ const warnings = [];
91
+ const routes = functionRoutes(project);
92
+ if (routes.length && !runsFunctions(cfg.platform)) {
93
+ warnings.push({
94
+ severity: "warning", code: "W0810",
95
+ message: `The routes in ${functions_1.FUNCTIONS_DIR}/ are not deployed on platform "${cfg.platform}"`,
96
+ hint: "Server functions run on Cloudflare: set \"platform\" to \"cloudflare\" or \"cloudflare-workers\" in sinth.config.json",
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
+ }
106
+ if (!write)
107
+ return warnings;
108
+ if (cfg.platform === "vercel")
109
+ writeVercelOutput(project, files, headers);
110
+ if (cfg.platform === "cloudflare-workers")
111
+ await writeWorker(project, routes);
112
+ return warnings;
113
+ }
114
+ /** Vercel Build Output API v3: https://vercel.com/docs/build-output-api */
115
+ function writeVercelOutput(project, files, headers) {
116
+ const cfg = project.config;
117
+ const out = path.join(project.root, ".vercel", "output");
118
+ fs.rmSync(out, { recursive: true, force: true });
119
+ const prefix = cfg.base.replace(/^\/|\/$/g, "");
120
+ const staticDir = path.join(out, "static", prefix);
121
+ const overrides = {};
122
+ for (const [rel, f] of files) {
123
+ const target = path.join(staticDir, rel);
124
+ fs.mkdirSync(path.dirname(target), { recursive: true });
125
+ fs.writeFileSync(target, f.contents);
126
+ // Clean URLs: /about serves about.html. index.html files are served for their folder already.
127
+ if (rel.endsWith(".html") && !/(^|\/)(index|404)\.html$/.test(rel)) {
128
+ const key = (prefix ? prefix + "/" : "") + rel;
129
+ overrides[key] = { path: key.slice(0, -5) };
130
+ }
131
+ }
132
+ const escapedBase = cfg.base.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
133
+ const routes = [
134
+ { src: `^${escapedBase}_sinth/(.*)$`, headers: { "Cache-Control": IMMUTABLE }, continue: true },
135
+ ];
136
+ if (Object.keys(headers).length)
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));
139
+ routes.push({ handle: "filesystem" });
140
+ if (files.has("404.html"))
141
+ routes.push({ src: "^/(.*)$", status: 404, dest: `${cfg.base}404.html` });
142
+ const config = { version: 3, routes, overrides };
143
+ fs.writeFileSync(path.join(out, "config.json"), JSON.stringify(config, null, 2) + "\n");
144
+ }
145
+ function userWranglerConfig(root) {
146
+ return ["wrangler.jsonc", "wrangler.json", "wrangler.toml"].map(f => path.join(root, f)).find(f => fs.existsSync(f));
147
+ }
148
+ /**
149
+ * Cloudflare Workers with static assets. With functions/, the routes are bundled into a Worker that
150
+ * runs only for their URLs; everything else is served straight from the assets.
151
+ */
152
+ async function writeWorker(project, routes) {
153
+ const cfg = project.config;
154
+ const dir = path.join(project.root, exports.DEPLOY_DIR);
155
+ fs.rmSync(dir, { recursive: true, force: true });
156
+ fs.mkdirSync(dir, { recursive: true });
157
+ const rel = (p) => path.relative(dir, p).split(path.sep).join("/") || ".";
158
+ const assets = {
159
+ directory: rel(cfg.outDir),
160
+ not_found_handling: "404-page",
161
+ html_handling: "auto-trailing-slash",
162
+ };
163
+ const config = {
164
+ $schema: rel(path.join(project.root, "node_modules", "wrangler", "config-schema.json")),
165
+ name: workerName(project),
166
+ compatibility_date: COMPATIBILITY_DATE,
167
+ assets,
168
+ };
169
+ if (!fs.existsSync(path.join(project.root, "node_modules", "wrangler")))
170
+ delete config.$schema;
171
+ if (routes.length) {
172
+ await bundleWorker(project, routes, path.join(dir, "worker.js"));
173
+ config.main = "worker.js";
174
+ assets.binding = "ASSETS";
175
+ assets.run_worker_first = (0, functions_router_1.routePatterns)(routes).map(p => (cfg.base === "/" ? p : cfg.base.slice(0, -1) + p));
176
+ }
177
+ fs.writeFileSync(path.join(dir, "wrangler.json"), JSON.stringify(config, null, 2) + "\n");
178
+ }
179
+ function workerName(project) {
180
+ return project.config.cloudflare.projectName ?? (0, cloudflare_1.defaultProjectName)(project.root);
181
+ }
182
+ async function bundleWorker(project, routes, outfile) {
183
+ const router = path.join(__dirname, "..", "server", "functions-router.js");
184
+ const imports = routes.map((r, i) => `import * as m${i} from ${JSON.stringify(r.file)};`);
185
+ const table = routes.map((r, i) => ` { rel: ${JSON.stringify(r.rel)}, segments: ${JSON.stringify(r.segments)}, middleware: ${r.middleware}, module: m${i} },`);
186
+ const contents = [
187
+ `import { dispatch } from ${JSON.stringify(router)};`,
188
+ ...imports,
189
+ "const routes = [",
190
+ ...table,
191
+ "];",
192
+ "export default {",
193
+ " async fetch(request, env, ctx) {",
194
+ " const assets = r => env.ASSETS.fetch(r);",
195
+ " const response = await dispatch(routes, request, { env, assets, waitUntil: p => ctx.waitUntil(p), passThroughOnException: () => ctx.passThroughOnException() });",
196
+ " return response ?? assets(request);",
197
+ " },",
198
+ "};",
199
+ ].join("\n");
200
+ try {
201
+ await esbuild.build({
202
+ stdin: { contents, resolveDir: project.root, sourcefile: "sinth-worker.js", loader: "js" },
203
+ bundle: true, format: "esm", platform: "neutral", target: "es2022", outfile,
204
+ mainFields: ["module", "main"], conditions: ["workerd", "worker", "browser"],
205
+ minify: project.config.minify, logLevel: "silent", absWorkingDir: project.root,
206
+ });
207
+ }
208
+ catch (err) {
209
+ const first = err.errors?.[0];
210
+ throw new diagnostics_1.SinthError("E0803", `Function build failed: ${first?.text ?? err.message}`, first?.location ? { file: path.resolve(project.root, first.location.file), line: first.location.line, col: first.location.column + 1 } : undefined);
211
+ }
212
+ }
@@ -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
+ }