@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.
- package/CHANGELOG.md +48 -0
- package/README.md +4 -2
- package/dist/browser/sinth.js +596 -69
- package/dist/cli/index.js +35 -3
- package/dist/cli/skill.d.ts +10 -0
- package/dist/cli/skill.js +106 -0
- package/dist/cli/templates.js +1 -1
- package/dist/compiler/codegen.js +4 -2
- package/dist/compiler/elements.d.ts +6 -0
- package/dist/compiler/elements.js +12 -0
- package/dist/compiler/html.d.ts +2 -0
- package/dist/compiler/html.js +7 -0
- package/dist/compiler/prerender.js +5 -3
- package/dist/deploy/platforms.js +9 -0
- package/dist/deploy/redirects.d.ts +31 -0
- package/dist/deploy/redirects.js +102 -0
- package/dist/project/build.js +44 -2
- package/dist/project/config.d.ts +6 -0
- package/dist/project/config.js +15 -2
- package/dist/project/env.d.ts +11 -0
- package/dist/project/env.js +84 -0
- package/dist/project/project.js +13 -0
- package/dist/runtime/index.js +21 -3
- package/dist/server/dev.d.ts +4 -0
- package/dist/server/dev.js +32 -9
- package/dist/server/functions.d.ts +2 -1
- package/dist/server/functions.js +15 -17
- package/dist/server/preview.d.ts +3 -0
- package/dist/server/preview.js +8 -1
- package/dist/server/static.d.ts +9 -0
- package/dist/server/static.js +24 -1
- package/lib/ui/index.sinth +533 -24
- package/package.json +1 -1
- package/schema/sinth.config.schema.json +27 -0
- package/skills/agents.md +15 -9
- package/skills/sinth/SKILL.md +66 -24
- package/skills/sinth/references/language.md +2 -1
- package/skills/sinth/references/project-and-deploy.md +18 -2
- package/skills/sinth/references/ui.md +95 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Only variables with this prefix reach the browser through `import { ... } from "sinth:env"`. */
|
|
2
|
+
export declare const PUBLIC_PREFIX = "PUBLIC_";
|
|
3
|
+
/** Parses a dotenv file: `KEY=value`, `export KEY=value`, quoted values and `#` comments. */
|
|
4
|
+
export declare function parseEnvFile(file: string): Record<string, string>;
|
|
5
|
+
/**
|
|
6
|
+
* Variables from `.env`, `.env.local`, `.env.<mode>` and `.env.<mode>.local` (later files win), with
|
|
7
|
+
* the process environment taking precedence over all files, like Vite and Next.js.
|
|
8
|
+
*/
|
|
9
|
+
export declare function loadEnv(root: string, mode: "development" | "production"): Record<string, string>;
|
|
10
|
+
/** The variables that are safe to inline into pages: those starting with PUBLIC_. */
|
|
11
|
+
export declare function publicEnv(root: string, mode: "development" | "production"): Record<string, string>;
|
|
@@ -0,0 +1,84 @@
|
|
|
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.PUBLIC_PREFIX = void 0;
|
|
37
|
+
exports.parseEnvFile = parseEnvFile;
|
|
38
|
+
exports.loadEnv = loadEnv;
|
|
39
|
+
exports.publicEnv = publicEnv;
|
|
40
|
+
const fs = __importStar(require("fs"));
|
|
41
|
+
const path = __importStar(require("path"));
|
|
42
|
+
/** Only variables with this prefix reach the browser through `import { ... } from "sinth:env"`. */
|
|
43
|
+
exports.PUBLIC_PREFIX = "PUBLIC_";
|
|
44
|
+
/** Parses a dotenv file: `KEY=value`, `export KEY=value`, quoted values and `#` comments. */
|
|
45
|
+
function parseEnvFile(file) {
|
|
46
|
+
const vars = {};
|
|
47
|
+
if (!fs.existsSync(file))
|
|
48
|
+
return vars;
|
|
49
|
+
for (const line of fs.readFileSync(file, "utf-8").split(/\r?\n/)) {
|
|
50
|
+
const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/);
|
|
51
|
+
if (!m)
|
|
52
|
+
continue;
|
|
53
|
+
let value = m[2];
|
|
54
|
+
const quote = value[0];
|
|
55
|
+
const close = quote === '"' || quote === "'" || quote === "`" ? value.indexOf(quote, 1) : -1;
|
|
56
|
+
if (close > 0)
|
|
57
|
+
value = quote === '"' ? value.slice(1, close).replace(/\\n/g, "\n") : value.slice(1, close);
|
|
58
|
+
else
|
|
59
|
+
value = value.replace(/(^|\s+)#.*$/, "");
|
|
60
|
+
vars[m[1]] = value;
|
|
61
|
+
}
|
|
62
|
+
return vars;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Variables from `.env`, `.env.local`, `.env.<mode>` and `.env.<mode>.local` (later files win), with
|
|
66
|
+
* the process environment taking precedence over all files, like Vite and Next.js.
|
|
67
|
+
*/
|
|
68
|
+
function loadEnv(root, mode) {
|
|
69
|
+
const merged = {};
|
|
70
|
+
for (const name of [".env", ".env.local", `.env.${mode}`, `.env.${mode}.local`])
|
|
71
|
+
Object.assign(merged, parseEnvFile(path.join(root, name)));
|
|
72
|
+
for (const [k, v] of Object.entries(process.env))
|
|
73
|
+
if (v !== undefined && (k in merged || k.startsWith(exports.PUBLIC_PREFIX)))
|
|
74
|
+
merged[k] = v;
|
|
75
|
+
return merged;
|
|
76
|
+
}
|
|
77
|
+
/** The variables that are safe to inline into pages: those starting with PUBLIC_. */
|
|
78
|
+
function publicEnv(root, mode) {
|
|
79
|
+
const out = {};
|
|
80
|
+
for (const [k, v] of Object.entries(loadEnv(root, mode)))
|
|
81
|
+
if (k.startsWith(exports.PUBLIC_PREFIX))
|
|
82
|
+
out[k] = v;
|
|
83
|
+
return out;
|
|
84
|
+
}
|
package/dist/project/project.js
CHANGED
|
@@ -44,6 +44,7 @@ const diagnostics_1 = require("../compiler/diagnostics");
|
|
|
44
44
|
const prerender_1 = require("../compiler/prerender");
|
|
45
45
|
const parser_1 = require("../compiler/parser");
|
|
46
46
|
const config_1 = require("./config");
|
|
47
|
+
const env_1 = require("./env");
|
|
47
48
|
exports.PACKAGE_ROOT = path.resolve(__dirname, "..", "..");
|
|
48
49
|
exports.RUNTIME_PATH = path.join(exports.PACKAGE_ROOT, "dist", "runtime", "index.js");
|
|
49
50
|
exports.ROUTER_PATH = path.join(exports.PACKAGE_ROOT, "dist", "runtime", "router.js");
|
|
@@ -249,6 +250,18 @@ class Project {
|
|
|
249
250
|
source = mapped;
|
|
250
251
|
decl = { ...decl, kind: "sinth", source, sideEffect: true };
|
|
251
252
|
}
|
|
253
|
+
if (source === "sinth:env") {
|
|
254
|
+
const env = (0, env_1.publicEnv)(this.root, this.dev ? "development" : "production");
|
|
255
|
+
for (const s of decl.named) {
|
|
256
|
+
if (s.name in env)
|
|
257
|
+
continue;
|
|
258
|
+
const near = (0, diagnostics_1.suggest)(s.name, Object.keys(env));
|
|
259
|
+
throw new diagnostics_1.SinthError("E0607", `Environment variable '${s.name}' is not set`, s.loc, near ? `Did you mean '${near}'?`
|
|
260
|
+
: !s.name.startsWith(env_1.PUBLIC_PREFIX) ? `Only variables starting with ${env_1.PUBLIC_PREFIX} are available in pages, so secrets never reach the browser. Rename it to ${env_1.PUBLIC_PREFIX}${s.name}`
|
|
261
|
+
: `Add ${s.name}=... to .env (or .env.production for builds), or set it in the environment of the build`);
|
|
262
|
+
}
|
|
263
|
+
return { decl: { ...decl, kind: "json" }, kind: "json", specifier: "sinth:env", json: env };
|
|
264
|
+
}
|
|
252
265
|
if (source.startsWith("sinth:")) {
|
|
253
266
|
const name = source.slice(6);
|
|
254
267
|
const target = this.resolveFile(path.join(exports.LIB_ROOT, name), [".sinth"]);
|
package/dist/runtime/index.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
const SVG_NS = "http://www.w3.org/2000/svg";
|
|
2
|
-
|
|
2
|
+
// Browsers ignore control characters and whitespace inside a URL scheme ("java\tscript:"), so they are
|
|
3
|
+
// removed before the check. Keep in sync with isUnsafeUrl() in compiler/html.ts.
|
|
4
|
+
const BLOCKED_URL = /^(javascript:|vbscript:|data:(?!image\/(png|gif|jpe?g|webp|avif|svg\+xml)[;,]|video\/|audio\/))/i;
|
|
5
|
+
// eslint-disable-next-line no-control-regex
|
|
6
|
+
const URL_NOISE = /[\u0000- \u007f]/g;
|
|
3
7
|
let rootOwner = createOwner(null);
|
|
4
8
|
let current = rootOwner;
|
|
5
9
|
let updating = false;
|
|
@@ -184,7 +188,7 @@ export function text(parent, get) {
|
|
|
184
188
|
});
|
|
185
189
|
}
|
|
186
190
|
export function sanitizeUrl(value) {
|
|
187
|
-
if (BLOCKED_URL.test(value)) {
|
|
191
|
+
if (BLOCKED_URL.test(value.replace(URL_NOISE, ""))) {
|
|
188
192
|
if (devMode)
|
|
189
193
|
console.warn(`[sinth] Blocked unsafe URL: ${value.slice(0, 64)}`);
|
|
190
194
|
return "about:blank#blocked";
|
|
@@ -431,6 +435,18 @@ export function model(node, get, set, numeric = false) {
|
|
|
431
435
|
synced = v;
|
|
432
436
|
set(v);
|
|
433
437
|
};
|
|
438
|
+
if (tag === "SELECT" && typeof MutationObserver !== "undefined") {
|
|
439
|
+
// Options rendered by a loop, or loaded later, can appear after the value was applied: select the
|
|
440
|
+
// bound value again once an option for it exists.
|
|
441
|
+
const select = node;
|
|
442
|
+
new MutationObserver(() => {
|
|
443
|
+
if (synced === NONE)
|
|
444
|
+
return;
|
|
445
|
+
const str = synced === null || synced === undefined ? "" : String(synced);
|
|
446
|
+
if (select.value !== str && Array.from(select.options).some(o => o.value === str))
|
|
447
|
+
select.value = str;
|
|
448
|
+
}).observe(select, { childList: true, subtree: true, attributes: true, attributeFilter: ["value"] });
|
|
449
|
+
}
|
|
434
450
|
const evt = tag === "SELECT" || type === "range" || type === "color" || type === "date" || type === "file" ? "change" : "input";
|
|
435
451
|
on(node, evt, () => {
|
|
436
452
|
if (!isNumber) {
|
|
@@ -493,8 +509,10 @@ export function when(parent, branches, options = {}) {
|
|
|
493
509
|
const leaving = Array.from(takeRange(start, end).childNodes);
|
|
494
510
|
for (const n of leaving) {
|
|
495
511
|
start.parentNode?.insertBefore(n, start);
|
|
496
|
-
if (n instanceof Element && options.transition)
|
|
512
|
+
if (n instanceof Element && options.transition) {
|
|
497
513
|
n.classList.add(`${options.transition}-leave`);
|
|
514
|
+
n.setAttribute("inert", "");
|
|
515
|
+
}
|
|
498
516
|
}
|
|
499
517
|
setTimeout(() => {
|
|
500
518
|
for (const n of leaving)
|
package/dist/server/dev.d.ts
CHANGED
|
@@ -5,4 +5,8 @@ export interface DevServerOptions {
|
|
|
5
5
|
open: boolean;
|
|
6
6
|
}
|
|
7
7
|
export declare function startDevServer(project: Project, opts: DevServerOptions): Promise<void>;
|
|
8
|
+
/**
|
|
9
|
+
* Opens a URL in the default browser. On Windows this avoids `cmd /c start`, which would interpret
|
|
10
|
+
* characters such as & and ^ in the URL as shell syntax.
|
|
11
|
+
*/
|
|
8
12
|
export declare function openBrowser(url: string): void;
|
package/dist/server/dev.js
CHANGED
|
@@ -46,6 +46,7 @@ const config_1 = require("../project/config");
|
|
|
46
46
|
const ui_1 = require("../cli/ui");
|
|
47
47
|
const client_1 = require("./client");
|
|
48
48
|
const functions_1 = require("./functions");
|
|
49
|
+
const redirects_1 = require("../deploy/redirects");
|
|
49
50
|
const static_1 = require("./static");
|
|
50
51
|
const CLIENT_URL = "/__sinth/client.js";
|
|
51
52
|
const HTML = "text/html; charset=utf-8";
|
|
@@ -69,7 +70,7 @@ async function startDevServer(project, opts) {
|
|
|
69
70
|
let lastError = null;
|
|
70
71
|
let hashes = [];
|
|
71
72
|
let building = null;
|
|
72
|
-
let pending =
|
|
73
|
+
let pending = null;
|
|
73
74
|
const broadcast = (msg) => {
|
|
74
75
|
const data = `data: ${JSON.stringify(msg)}\n\n`;
|
|
75
76
|
for (const res of clients)
|
|
@@ -112,14 +113,15 @@ async function startDevServer(project, opts) {
|
|
|
112
113
|
};
|
|
113
114
|
const queueRebuild = (file) => {
|
|
114
115
|
if (building) {
|
|
115
|
-
pending =
|
|
116
|
+
pending = file;
|
|
116
117
|
return;
|
|
117
118
|
}
|
|
118
119
|
building = rebuild(file).finally(() => {
|
|
119
120
|
building = null;
|
|
120
|
-
if (pending) {
|
|
121
|
-
|
|
122
|
-
|
|
121
|
+
if (pending !== null) {
|
|
122
|
+
const next = pending;
|
|
123
|
+
pending = null;
|
|
124
|
+
queueRebuild(next);
|
|
123
125
|
}
|
|
124
126
|
});
|
|
125
127
|
};
|
|
@@ -158,9 +160,15 @@ async function startDevServer(project, opts) {
|
|
|
158
160
|
};
|
|
159
161
|
const functions = new functions_1.FunctionsHost(project.root);
|
|
160
162
|
const handle = async (req, res) => {
|
|
163
|
+
if (!(0, static_1.hostAllowed)(req.headers.host, cfg.allowedHosts === true || [...cfg.allowedHosts, opts.host]))
|
|
164
|
+
return (0, static_1.forbiddenHost)(res, req.headers.host);
|
|
161
165
|
const urlPath = (0, static_1.decodePath)(req.url);
|
|
162
166
|
if (!urlPath)
|
|
163
167
|
return (0, static_1.send)(res, 400, "Bad request", "text/plain");
|
|
168
|
+
const sitePath = (0, static_1.stripBase)(urlPath, cfg.base);
|
|
169
|
+
const redirect = sitePath === null ? null : (0, redirects_1.matchRedirect)(cfg.redirects, sitePath, (req.url ?? "").match(/\?[^#]*/)?.[0]);
|
|
170
|
+
if (redirect)
|
|
171
|
+
return (0, static_1.send)(res, redirect.status, "", "text/plain", { Location: redirect.location });
|
|
164
172
|
if (urlPath === "/__sinth/events") {
|
|
165
173
|
res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive" });
|
|
166
174
|
res.write(`data: ${JSON.stringify({ type: "init", pages: hashes, error: lastError, base: cfg.base })}\n\n`);
|
|
@@ -215,7 +223,8 @@ async function startDevServer(project, opts) {
|
|
|
215
223
|
ui_1.log.warn(`Port ${opts.port} is in use, using ${port} instead`);
|
|
216
224
|
const timers = new Map();
|
|
217
225
|
const onChange = (file) => {
|
|
218
|
-
|
|
226
|
+
const isEnv = /^\.env(\..+)?$/.test(path.basename(file)) || path.basename(file) === ".dev.vars";
|
|
227
|
+
if (IGNORED.test(path.relative(project.root, file)) || file.startsWith(cfg.outDir) || (!WATCHED_EXT.test(file) && !isEnv))
|
|
219
228
|
return;
|
|
220
229
|
clearTimeout(timers.get(file));
|
|
221
230
|
timers.set(file, setTimeout(() => {
|
|
@@ -230,6 +239,12 @@ async function startDevServer(project, opts) {
|
|
|
230
239
|
ui_1.log.success(`${ui_1.c.gray(path.relative(project.root, file).replace(/\\/g, "/"))} ${ui_1.c.dim("reloaded")}`);
|
|
231
240
|
return;
|
|
232
241
|
}
|
|
242
|
+
if (isEnv) {
|
|
243
|
+
functions.invalidate();
|
|
244
|
+
ui_1.log.success(`${ui_1.c.gray(path.basename(file))} ${ui_1.c.dim("reloaded")}`);
|
|
245
|
+
queueRebuild();
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
233
248
|
if (path.basename(file) === "sinth.config.json") {
|
|
234
249
|
ui_1.log.warn("sinth.config.json changed. Restart the dev server to apply it.");
|
|
235
250
|
return;
|
|
@@ -276,10 +291,18 @@ async function startDevServer(project, opts) {
|
|
|
276
291
|
process.on("SIGINT", shutdown);
|
|
277
292
|
process.on("SIGTERM", shutdown);
|
|
278
293
|
}
|
|
294
|
+
/**
|
|
295
|
+
* Opens a URL in the default browser. On Windows this avoids `cmd /c start`, which would interpret
|
|
296
|
+
* characters such as & and ^ in the URL as shell syntax.
|
|
297
|
+
*/
|
|
279
298
|
function openBrowser(url) {
|
|
299
|
+
if (!/^https?:\/\//.test(url))
|
|
300
|
+
return;
|
|
280
301
|
Promise.resolve().then(() => __importStar(require("child_process"))).then(cp => {
|
|
281
|
-
const cmd = process.platform === "win32" ? "
|
|
282
|
-
|
|
283
|
-
cp.spawn(cmd, args, { stdio: "ignore", detached: true })
|
|
302
|
+
const [cmd, args] = process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
|
|
303
|
+
: process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
|
|
304
|
+
const child = cp.spawn(cmd, args, { stdio: "ignore", detached: true });
|
|
305
|
+
child.on("error", () => ui_1.log.warn(`Could not open a browser. Open ${url} yourself.`));
|
|
306
|
+
child.unref();
|
|
284
307
|
}).catch(() => undefined);
|
|
285
308
|
}
|
|
@@ -21,12 +21,13 @@ export declare function scanFunctions(dir: string): (RouteDef & {
|
|
|
21
21
|
})[];
|
|
22
22
|
export declare class FunctionsHost {
|
|
23
23
|
private readonly root;
|
|
24
|
+
private readonly mode;
|
|
24
25
|
private routes;
|
|
25
26
|
private modules;
|
|
26
27
|
private building;
|
|
27
28
|
readonly dir: string;
|
|
28
29
|
private readonly cacheDir;
|
|
29
|
-
constructor(root: string);
|
|
30
|
+
constructor(root: string, mode?: "development" | "production");
|
|
30
31
|
get enabled(): boolean;
|
|
31
32
|
invalidate(): void;
|
|
32
33
|
private scan;
|
package/dist/server/functions.js
CHANGED
|
@@ -43,6 +43,8 @@ const fs = __importStar(require("fs"));
|
|
|
43
43
|
const path = __importStar(require("path"));
|
|
44
44
|
const diagnostics_1 = require("../compiler/diagnostics");
|
|
45
45
|
const ui_1 = require("../cli/ui");
|
|
46
|
+
const env_1 = require("../project/env");
|
|
47
|
+
const static_1 = require("./static");
|
|
46
48
|
const functions_router_1 = require("./functions-router");
|
|
47
49
|
/**
|
|
48
50
|
* Server routes in `functions/`, following the Cloudflare Pages Functions conventions so the same
|
|
@@ -73,30 +75,21 @@ function scanFunctions(dir) {
|
|
|
73
75
|
walk(dir);
|
|
74
76
|
return routes.sort(functions_router_1.compareRoutes);
|
|
75
77
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
const file = path.join(root, name);
|
|
80
|
-
if (!fs.existsSync(file))
|
|
81
|
-
continue;
|
|
82
|
-
for (const line of fs.readFileSync(file, "utf-8").split(/\r?\n/)) {
|
|
83
|
-
const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/);
|
|
84
|
-
if (!m || m[1] in vars)
|
|
85
|
-
continue;
|
|
86
|
-
vars[m[1]] = m[2].replace(/^(["'])(.*)\1$/, "$2");
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
return vars;
|
|
78
|
+
/** Server-side variables: `.dev.vars` (Wrangler's file) wins over the .env files. */
|
|
79
|
+
function readDevVars(root, mode) {
|
|
80
|
+
return { ...(0, env_1.loadEnv)(root, mode), ...(0, env_1.parseEnvFile)(path.join(root, ".dev.vars")) };
|
|
90
81
|
}
|
|
91
82
|
class FunctionsHost {
|
|
92
83
|
root;
|
|
84
|
+
mode;
|
|
93
85
|
routes = null;
|
|
94
86
|
modules = new Map();
|
|
95
87
|
building = null;
|
|
96
88
|
dir;
|
|
97
89
|
cacheDir;
|
|
98
|
-
constructor(root) {
|
|
90
|
+
constructor(root, mode = "development") {
|
|
99
91
|
this.root = root;
|
|
92
|
+
this.mode = mode;
|
|
100
93
|
this.dir = path.join(root, exports.FUNCTIONS_DIR);
|
|
101
94
|
this.cacheDir = path.join(root, ".sinth", "functions");
|
|
102
95
|
if (!globalThis.crypto)
|
|
@@ -170,7 +163,7 @@ class FunctionsHost {
|
|
|
170
163
|
const mod = this.modules.get(r.file);
|
|
171
164
|
return mod ? [{ ...r, module: mod }] : [];
|
|
172
165
|
});
|
|
173
|
-
const env = { ...readDevVars(this.root), ASSETS: { fetch: (input, init) => assets(new Request(input, init)) } };
|
|
166
|
+
const env = { ...readDevVars(this.root, this.mode), ASSETS: { fetch: (input, init) => assets(new Request(input, init)) } };
|
|
174
167
|
return (0, functions_router_1.dispatch)(loaded, request, {
|
|
175
168
|
env,
|
|
176
169
|
assets,
|
|
@@ -191,8 +184,13 @@ async function toRequest(req) {
|
|
|
191
184
|
let body;
|
|
192
185
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
193
186
|
const chunks = [];
|
|
194
|
-
|
|
187
|
+
let size = 0;
|
|
188
|
+
for await (const chunk of req) {
|
|
189
|
+
size += chunk.byteLength;
|
|
190
|
+
if (size > static_1.MAX_BODY_BYTES)
|
|
191
|
+
throw new diagnostics_1.SinthError("E0804", `Request body is larger than ${static_1.MAX_BODY_BYTES / 1024 / 1024} MB`);
|
|
195
192
|
chunks.push(chunk);
|
|
193
|
+
}
|
|
196
194
|
body = Buffer.concat(chunks);
|
|
197
195
|
}
|
|
198
196
|
return new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, { method: req.method, headers, body });
|
package/dist/server/preview.d.ts
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
+
import { Redirect } from "../deploy/redirects";
|
|
1
2
|
export interface PreviewOptions {
|
|
2
3
|
port: number;
|
|
3
4
|
host: string;
|
|
4
5
|
open: boolean;
|
|
5
6
|
base: string;
|
|
6
7
|
root: string;
|
|
8
|
+
redirects: Redirect[];
|
|
9
|
+
allowedHosts: string[] | true;
|
|
7
10
|
}
|
|
8
11
|
export declare function startPreview(outDir: string, opts: PreviewOptions): Promise<void>;
|
package/dist/server/preview.js
CHANGED
|
@@ -41,6 +41,7 @@ const diagnostics_1 = require("../compiler/diagnostics");
|
|
|
41
41
|
const ui_1 = require("../cli/ui");
|
|
42
42
|
const dev_1 = require("./dev");
|
|
43
43
|
const functions_1 = require("./functions");
|
|
44
|
+
const redirects_1 = require("../deploy/redirects");
|
|
44
45
|
const static_1 = require("./static");
|
|
45
46
|
function parseHeadersFile(file) {
|
|
46
47
|
if (!fs.existsSync(file))
|
|
@@ -91,11 +92,17 @@ async function startPreview(outDir, opts) {
|
|
|
91
92
|
const notFound = (0, static_1.fileIfExists)(path.join(outDir, "404.html"));
|
|
92
93
|
return { status: 404, body: notFound ? fs.readFileSync(notFound) : "404 Not Found", type: notFound ? "text/html; charset=utf-8" : "text/plain", headers: headersFor(urlPath) };
|
|
93
94
|
};
|
|
94
|
-
const functions = new functions_1.FunctionsHost(opts.root);
|
|
95
|
+
const functions = new functions_1.FunctionsHost(opts.root, "production");
|
|
95
96
|
const handle = async (req, res) => {
|
|
97
|
+
if (!(0, static_1.hostAllowed)(req.headers.host, opts.allowedHosts === true || [...opts.allowedHosts, opts.host]))
|
|
98
|
+
return (0, static_1.forbiddenHost)(res, req.headers.host);
|
|
96
99
|
const urlPath = (0, static_1.decodePath)(req.url);
|
|
97
100
|
if (!urlPath)
|
|
98
101
|
return (0, static_1.send)(res, 400, "Bad request", "text/plain");
|
|
102
|
+
const sitePath = (0, static_1.stripBase)(urlPath, opts.base);
|
|
103
|
+
const redirect = sitePath === null ? null : (0, redirects_1.matchRedirect)(opts.redirects, sitePath, (req.url ?? "").match(/\?[^#]*/)?.[0]);
|
|
104
|
+
if (redirect)
|
|
105
|
+
return (0, static_1.send)(res, redirect.status, "", "text/plain", { Location: redirect.location });
|
|
99
106
|
const head = req.method === "HEAD";
|
|
100
107
|
if (functions.enabled) {
|
|
101
108
|
const response = await functions.handle(await (0, functions_1.toRequest)(req), async (r) => (0, static_1.assetResponse)(resolve((0, static_1.decodePath)(new URL(r.url).pathname) ?? "/")));
|
package/dist/server/static.d.ts
CHANGED
|
@@ -17,4 +17,13 @@ export declare function sendAsset(res: http.ServerResponse, asset: Asset, head?:
|
|
|
17
17
|
export declare function assetResponse(asset: Asset): Response;
|
|
18
18
|
export declare function routeCandidates(urlPath: string): string[];
|
|
19
19
|
export declare function listen(server: http.Server, port: number, host: string, attempts?: number): Promise<number>;
|
|
20
|
+
/**
|
|
21
|
+
* Guards the local servers against DNS rebinding: a page on another site cannot reach them through a
|
|
22
|
+
* domain it controls. IP addresses, localhost and *.localhost are always allowed; other names (a
|
|
23
|
+
* tunnel, a custom dev domain) need "allowedHosts" in sinth.config.json, or `true` to allow any.
|
|
24
|
+
*/
|
|
25
|
+
export declare function hostAllowed(hostHeader: string | undefined, allowed: string[] | true): boolean;
|
|
26
|
+
export declare function forbiddenHost(res: http.ServerResponse, host: string | undefined): void;
|
|
27
|
+
/** Largest request body the local servers accept (functions/ requests). */
|
|
28
|
+
export declare const MAX_BODY_BYTES: number;
|
|
20
29
|
export declare function displayHost(host: string): string;
|
package/dist/server/static.js
CHANGED
|
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.MIME = void 0;
|
|
36
|
+
exports.MAX_BODY_BYTES = exports.MIME = void 0;
|
|
37
37
|
exports.mimeType = mimeType;
|
|
38
38
|
exports.decodePath = decodePath;
|
|
39
39
|
exports.safeJoin = safeJoin;
|
|
@@ -44,6 +44,8 @@ exports.sendAsset = sendAsset;
|
|
|
44
44
|
exports.assetResponse = assetResponse;
|
|
45
45
|
exports.routeCandidates = routeCandidates;
|
|
46
46
|
exports.listen = listen;
|
|
47
|
+
exports.hostAllowed = hostAllowed;
|
|
48
|
+
exports.forbiddenHost = forbiddenHost;
|
|
47
49
|
exports.displayHost = displayHost;
|
|
48
50
|
const fs = __importStar(require("fs"));
|
|
49
51
|
const path = __importStar(require("path"));
|
|
@@ -156,6 +158,27 @@ function listen(server, port, host, attempts = 10) {
|
|
|
156
158
|
tryListen();
|
|
157
159
|
});
|
|
158
160
|
}
|
|
161
|
+
/**
|
|
162
|
+
* Guards the local servers against DNS rebinding: a page on another site cannot reach them through a
|
|
163
|
+
* domain it controls. IP addresses, localhost and *.localhost are always allowed; other names (a
|
|
164
|
+
* tunnel, a custom dev domain) need "allowedHosts" in sinth.config.json, or `true` to allow any.
|
|
165
|
+
*/
|
|
166
|
+
function hostAllowed(hostHeader, allowed) {
|
|
167
|
+
if (allowed === true || !hostHeader)
|
|
168
|
+
return true;
|
|
169
|
+
const host = hostHeader.replace(/:\d+$/, "").replace(/^\[|\]$/g, "").toLowerCase();
|
|
170
|
+
if (host === "localhost" || host.endsWith(".localhost") || /^[\d.]+$/.test(host) || host.includes(":"))
|
|
171
|
+
return true;
|
|
172
|
+
return allowed.some(a => {
|
|
173
|
+
const name = a.toLowerCase();
|
|
174
|
+
return name.startsWith(".") ? host === name.slice(1) || host.endsWith(name) : host === name;
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
function forbiddenHost(res, host) {
|
|
178
|
+
send(res, 403, `Blocked request for host "${host}". Add it to "allowedHosts" in sinth.config.json to allow it.`, "text/plain; charset=utf-8");
|
|
179
|
+
}
|
|
180
|
+
/** Largest request body the local servers accept (functions/ requests). */
|
|
181
|
+
exports.MAX_BODY_BYTES = 64 * 1024 * 1024;
|
|
159
182
|
function displayHost(host) {
|
|
160
183
|
return host === "127.0.0.1" || host === "::1" || host === "0.0.0.0" || host === "::" ? "localhost" : host;
|
|
161
184
|
}
|