@yannosay/sinth 4.0.0 → 5.1.0
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 +83 -0
- package/DOCS.md +1359 -0
- package/README.md +83 -74
- package/bin/sinth.js +2 -1
- package/dist/cli/args.d.ts +11 -0
- package/dist/cli/args.js +74 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +437 -0
- package/dist/cli/templates.d.ts +10 -0
- package/dist/cli/templates.js +193 -0
- package/dist/cli/ui.d.ts +28 -0
- package/dist/cli/ui.js +61 -0
- package/dist/cli/update-check.d.ts +2 -0
- package/dist/cli/update-check.js +124 -0
- package/dist/compiler/ast.d.ts +315 -0
- package/dist/compiler/ast.js +4 -0
- package/dist/compiler/codegen.d.ts +143 -0
- package/dist/compiler/codegen.js +1326 -0
- package/dist/compiler/diagnostics.d.ts +36 -0
- package/dist/compiler/diagnostics.js +142 -0
- package/dist/compiler/elements.d.ts +14 -0
- package/dist/compiler/elements.js +78 -0
- package/dist/compiler/globals.d.ts +2 -0
- package/dist/compiler/globals.js +27 -0
- package/dist/compiler/html.d.ts +37 -0
- package/dist/compiler/html.js +152 -0
- package/dist/compiler/lexer.d.ts +42 -0
- package/dist/compiler/lexer.js +404 -0
- package/dist/compiler/parser.d.ts +95 -0
- package/dist/compiler/parser.js +1374 -0
- package/dist/compiler/prerender.d.ts +72 -0
- package/dist/compiler/prerender.js +910 -0
- package/dist/compiler/script-analysis.d.ts +6 -0
- package/dist/compiler/script-analysis.js +106 -0
- package/dist/compiler/style.d.ts +39 -0
- package/dist/compiler/style.js +463 -0
- package/dist/deploy/cloudflare.d.ts +9 -0
- package/dist/deploy/cloudflare.js +111 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +23 -0
- package/dist/project/build.d.ts +31 -0
- package/dist/project/build.js +425 -0
- package/dist/project/config.d.ts +33 -0
- package/dist/project/config.js +142 -0
- package/dist/project/project.d.ts +74 -0
- package/dist/project/project.js +535 -0
- package/dist/runtime/index.d.ts +68 -0
- package/dist/runtime/index.js +912 -0
- package/dist/server/client.d.ts +1 -0
- package/dist/server/client.js +112 -0
- package/dist/server/dev.d.ts +8 -0
- package/dist/server/dev.js +244 -0
- package/dist/server/preview.d.ts +6 -0
- package/dist/server/preview.js +106 -0
- package/dist/server/static.d.ts +10 -0
- package/dist/server/static.js +136 -0
- package/lib/ui/index.sinth +436 -0
- package/package.json +33 -15
- package/schema/sinth.config.schema.json +54 -0
- package/dist/browser/compile.js +0 -62
- package/dist/cli.js +0 -509
- package/dist/core/builtins.js +0 -117
- package/dist/core/cli-compiler.js +0 -683
- package/dist/core/compiler.js +0 -1428
- package/dist/core/expr.js +0 -125
- package/dist/core/head-builder.js +0 -130
- package/dist/core/lexer.js +0 -414
- package/dist/core/parser.js +0 -1665
- package/dist/core/runtime/custom-element.js +0 -81
- package/dist/core/runtime/functions.js +0 -99
- package/dist/core/runtime/helpers.js +0 -347
- package/dist/core/runtime/render.js +0 -136
- package/dist/core/style-processor.js +0 -317
- package/dist/core/types.js +0 -93
- package/dist/resolver.js +0 -175
- package/dist/server.js +0 -174
- package/dist/update-check.js +0 -109
- package/dist/utils.js +0 -80
|
@@ -0,0 +1,111 @@
|
|
|
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.defaultProjectName = defaultProjectName;
|
|
37
|
+
exports.deployToCloudflare = deployToCloudflare;
|
|
38
|
+
const child_process_1 = require("child_process");
|
|
39
|
+
const fs = __importStar(require("fs"));
|
|
40
|
+
const path = __importStar(require("path"));
|
|
41
|
+
const diagnostics_1 = require("../compiler/diagnostics");
|
|
42
|
+
const ui_1 = require("../cli/ui");
|
|
43
|
+
const PROJECT_NAME = /^[a-z0-9][a-z0-9-]{0,56}[a-z0-9]$/;
|
|
44
|
+
const BRANCH_NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,99}$/;
|
|
45
|
+
const ACCOUNT_ID = /^[a-f0-9]{32}$/;
|
|
46
|
+
const WRANGLER = "wrangler@4";
|
|
47
|
+
function defaultProjectName(root) {
|
|
48
|
+
let name = path.basename(root);
|
|
49
|
+
const pkg = path.join(root, "package.json");
|
|
50
|
+
if (fs.existsSync(pkg)) {
|
|
51
|
+
try {
|
|
52
|
+
const meta = JSON.parse(fs.readFileSync(pkg, "utf-8"));
|
|
53
|
+
if (meta.name)
|
|
54
|
+
name = meta.name.replace(/^@[^/]+\//, "");
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return sanitizeName(name);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return sanitizeName(name);
|
|
61
|
+
}
|
|
62
|
+
function sanitizeName(name) {
|
|
63
|
+
const cleaned = name.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 58);
|
|
64
|
+
return cleaned.length >= 2 ? cleaned : "sinth-site";
|
|
65
|
+
}
|
|
66
|
+
function runWrangler(args, cwd, env) {
|
|
67
|
+
for (const a of args) {
|
|
68
|
+
if (!/^[A-Za-z0-9@._/:=\\ -]+$/.test(a))
|
|
69
|
+
throw new diagnostics_1.SinthError("E1100", `Refusing to pass unsafe argument to wrangler: ${a}`);
|
|
70
|
+
}
|
|
71
|
+
const isWin = process.platform === "win32";
|
|
72
|
+
const cmd = isWin ? "npx.cmd" : "npx";
|
|
73
|
+
const quoted = isWin ? ["--yes", WRANGLER, ...args].map(a => (/\s/.test(a) ? `"${a}"` : a)) : ["--yes", WRANGLER, ...args];
|
|
74
|
+
return new Promise((resolve, reject) => {
|
|
75
|
+
const child = (0, child_process_1.spawn)(cmd, quoted, { cwd, env, stdio: "inherit", shell: isWin });
|
|
76
|
+
child.on("error", reject);
|
|
77
|
+
child.on("exit", code => resolve(code ?? 1));
|
|
78
|
+
});
|
|
79
|
+
}
|
|
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\"");
|
|
86
|
+
}
|
|
87
|
+
if (!BRANCH_NAME.test(branch))
|
|
88
|
+
throw new diagnostics_1.SinthError("E1102", `Invalid branch name '${branch}'`);
|
|
89
|
+
if (cf.accountId && !ACCOUNT_ID.test(cf.accountId))
|
|
90
|
+
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
|
+
const env = { ...process.env };
|
|
95
|
+
if (cf.accountId)
|
|
96
|
+
env.CLOUDFLARE_ACCOUNT_ID = cf.accountId;
|
|
97
|
+
if (opts.create) {
|
|
98
|
+
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);
|
|
100
|
+
if (code !== 0)
|
|
101
|
+
ui_1.log.warn("Project creation failed or the project already exists, continuing with the deploy");
|
|
102
|
+
}
|
|
103
|
+
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);
|
|
107
|
+
if (code !== 0) {
|
|
108
|
+
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
|
+
}
|
|
110
|
+
ui_1.log.success(`Deployed to Cloudflare Pages (${projectName})`);
|
|
111
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { parseSinth, Parser } from "./compiler/parser";
|
|
2
|
+
export { tokenize } from "./compiler/lexer";
|
|
3
|
+
export { compileModule, collectExports } from "./compiler/codegen";
|
|
4
|
+
export type { ModuleOutput, ModuleExports, ResolvedImport } from "./compiler/codegen";
|
|
5
|
+
export { SinthError, formatDiagnostic } from "./compiler/diagnostics";
|
|
6
|
+
export type { Diagnostic, Loc } from "./compiler/diagnostics";
|
|
7
|
+
export { compileStyle } from "./compiler/style";
|
|
8
|
+
export { loadConfig } from "./project/config";
|
|
9
|
+
export type { SinthConfig } from "./project/config";
|
|
10
|
+
export { Project } from "./project/project";
|
|
11
|
+
export { buildProject, checkProject } from "./project/build";
|
|
12
|
+
export type { BuildOutput } from "./project/build";
|
|
13
|
+
export type * from "./compiler/ast";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.checkProject = exports.buildProject = exports.Project = exports.loadConfig = exports.compileStyle = exports.formatDiagnostic = exports.SinthError = exports.collectExports = exports.compileModule = exports.tokenize = exports.Parser = exports.parseSinth = void 0;
|
|
4
|
+
var parser_1 = require("./compiler/parser");
|
|
5
|
+
Object.defineProperty(exports, "parseSinth", { enumerable: true, get: function () { return parser_1.parseSinth; } });
|
|
6
|
+
Object.defineProperty(exports, "Parser", { enumerable: true, get: function () { return parser_1.Parser; } });
|
|
7
|
+
var lexer_1 = require("./compiler/lexer");
|
|
8
|
+
Object.defineProperty(exports, "tokenize", { enumerable: true, get: function () { return lexer_1.tokenize; } });
|
|
9
|
+
var codegen_1 = require("./compiler/codegen");
|
|
10
|
+
Object.defineProperty(exports, "compileModule", { enumerable: true, get: function () { return codegen_1.compileModule; } });
|
|
11
|
+
Object.defineProperty(exports, "collectExports", { enumerable: true, get: function () { return codegen_1.collectExports; } });
|
|
12
|
+
var diagnostics_1 = require("./compiler/diagnostics");
|
|
13
|
+
Object.defineProperty(exports, "SinthError", { enumerable: true, get: function () { return diagnostics_1.SinthError; } });
|
|
14
|
+
Object.defineProperty(exports, "formatDiagnostic", { enumerable: true, get: function () { return diagnostics_1.formatDiagnostic; } });
|
|
15
|
+
var style_1 = require("./compiler/style");
|
|
16
|
+
Object.defineProperty(exports, "compileStyle", { enumerable: true, get: function () { return style_1.compileStyle; } });
|
|
17
|
+
var config_1 = require("./project/config");
|
|
18
|
+
Object.defineProperty(exports, "loadConfig", { enumerable: true, get: function () { return config_1.loadConfig; } });
|
|
19
|
+
var project_1 = require("./project/project");
|
|
20
|
+
Object.defineProperty(exports, "Project", { enumerable: true, get: function () { return project_1.Project; } });
|
|
21
|
+
var build_1 = require("./project/build");
|
|
22
|
+
Object.defineProperty(exports, "buildProject", { enumerable: true, get: function () { return build_1.buildProject; } });
|
|
23
|
+
Object.defineProperty(exports, "checkProject", { enumerable: true, get: function () { return build_1.checkProject; } });
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Diagnostic, SinthError } from "../compiler/diagnostics";
|
|
2
|
+
import { CompiledPage, PageInfo, Project } from "./project";
|
|
3
|
+
export interface OutputFile {
|
|
4
|
+
path: string;
|
|
5
|
+
contents: Uint8Array;
|
|
6
|
+
}
|
|
7
|
+
export interface PageOutput {
|
|
8
|
+
page: PageInfo;
|
|
9
|
+
html: string;
|
|
10
|
+
js?: string;
|
|
11
|
+
css?: string;
|
|
12
|
+
interactive: boolean;
|
|
13
|
+
bytes: number;
|
|
14
|
+
}
|
|
15
|
+
export interface BuildOutput {
|
|
16
|
+
pages: PageOutput[];
|
|
17
|
+
files: Map<string, OutputFile>;
|
|
18
|
+
warnings: Diagnostic[];
|
|
19
|
+
durationMs: number;
|
|
20
|
+
}
|
|
21
|
+
export interface BuildOptions {
|
|
22
|
+
write: boolean;
|
|
23
|
+
devClient?: string;
|
|
24
|
+
}
|
|
25
|
+
export declare function contentSecurityPolicy(pages: CompiledPage[], custom: boolean | string): string | undefined;
|
|
26
|
+
export declare function buildProject(project: Project, options: BuildOptions): Promise<BuildOutput>;
|
|
27
|
+
export declare function checkProject(project: Project): {
|
|
28
|
+
pages: PageInfo[];
|
|
29
|
+
warnings: Diagnostic[];
|
|
30
|
+
errors: SinthError[];
|
|
31
|
+
};
|
|
@@ -0,0 +1,425 @@
|
|
|
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.contentSecurityPolicy = contentSecurityPolicy;
|
|
37
|
+
exports.buildProject = buildProject;
|
|
38
|
+
exports.checkProject = checkProject;
|
|
39
|
+
const esbuild = __importStar(require("esbuild"));
|
|
40
|
+
const fs = __importStar(require("fs"));
|
|
41
|
+
const path = __importStar(require("path"));
|
|
42
|
+
const diagnostics_1 = require("../compiler/diagnostics");
|
|
43
|
+
const html_1 = require("../compiler/html");
|
|
44
|
+
const project_1 = require("./project");
|
|
45
|
+
const ASSET_LOADERS = {
|
|
46
|
+
".png": "file", ".jpg": "file", ".jpeg": "file", ".gif": "file", ".webp": "file", ".avif": "file", ".svg": "file",
|
|
47
|
+
".ico": "file", ".woff": "file", ".woff2": "file", ".ttf": "file", ".otf": "file", ".eot": "file", ".mp4": "file",
|
|
48
|
+
".webm": "file", ".mp3": "file", ".wav": "file", ".txt": "text",
|
|
49
|
+
};
|
|
50
|
+
function sinthPlugin(project, entries, injectCss = false) {
|
|
51
|
+
return {
|
|
52
|
+
name: "sinth",
|
|
53
|
+
setup(b) {
|
|
54
|
+
b.onResolve({ filter: /^sinth-runtime$/ }, () => ({ path: project_1.RUNTIME_PATH }));
|
|
55
|
+
b.onResolve({ filter: /^sinth-entry:/ }, a => ({ path: a.path.slice("sinth-entry:".length), namespace: "sinth-entry" }));
|
|
56
|
+
b.onLoad({ filter: /.*/, namespace: "sinth-entry" }, a => ({ contents: entries.get(a.path) ?? "", loader: "js", resolveDir: project.root }));
|
|
57
|
+
b.onResolve({ filter: /^sinth-css:/ }, a => ({ path: a.path.slice("sinth-css:".length), namespace: "sinth-css" }));
|
|
58
|
+
b.onLoad({ filter: /.*/, namespace: "sinth-css" }, a => (injectCss
|
|
59
|
+
? { contents: `import { injectCss } from "sinth-runtime";\ninjectCss(${JSON.stringify("sinth-" + a.path.length.toString(36) + "-" + path.basename(a.path))}, ${JSON.stringify(project.compile(a.path).css)});`, loader: "js", resolveDir: path.dirname(a.path) }
|
|
60
|
+
: { contents: project.compile(a.path).css, loader: "css", resolveDir: path.dirname(a.path) }));
|
|
61
|
+
if (injectCss) {
|
|
62
|
+
b.onLoad({ filter: /\.css$/ }, a => ({
|
|
63
|
+
contents: `import { injectCss } from "sinth-runtime";\ninjectCss(${JSON.stringify("sinth-css-" + path.basename(a.path))}, ${JSON.stringify(fs.readFileSync(a.path, "utf-8"))});`,
|
|
64
|
+
loader: "js",
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
b.onLoad({ filter: /\.sinth$/ }, a => ({ contents: project.compile(a.path).js, loader: "js", resolveDir: path.dirname(a.path) }));
|
|
68
|
+
b.onLoad({ filter: /\.s[ac]ss$/ }, a => {
|
|
69
|
+
const scss = project.scss();
|
|
70
|
+
if (!scss)
|
|
71
|
+
return { errors: [{ text: `Cannot compile ${path.basename(a.path)}: install 'sass' (npm install -D sass)` }] };
|
|
72
|
+
try {
|
|
73
|
+
return { contents: scss(fs.readFileSync(a.path, "utf-8"), a.path), loader: "css", resolveDir: path.dirname(a.path) };
|
|
74
|
+
}
|
|
75
|
+
catch (err) {
|
|
76
|
+
return { errors: [{ text: err.message }] };
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function findCustomElementFiles(project) {
|
|
83
|
+
const out = [];
|
|
84
|
+
const skip = new Set(["node_modules", ".git", ".sinth", ".wrangler"]);
|
|
85
|
+
const walk = (dir) => {
|
|
86
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
87
|
+
const full = path.join(dir, e.name);
|
|
88
|
+
if (e.isDirectory()) {
|
|
89
|
+
if (!skip.has(e.name) && full !== project.config.outDir)
|
|
90
|
+
walk(full);
|
|
91
|
+
}
|
|
92
|
+
else if (e.name.endsWith(".sinth")) {
|
|
93
|
+
const src = fs.readFileSync(full, "utf-8");
|
|
94
|
+
if (/\bcustom(-element)?\s+[A-Za-z]/.test(src) || /\bcomponent\s+[A-Z]\w*\s*(\([^)]*\))?\s*as\s*</.test(src))
|
|
95
|
+
out.push(full);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
walk(project.root);
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
async function buildCustomElements(project) {
|
|
103
|
+
const entries = new Map();
|
|
104
|
+
const entryPoints = {};
|
|
105
|
+
for (const file of findCustomElementFiles(project)) {
|
|
106
|
+
const parsed = project.getFile(file);
|
|
107
|
+
if (parsed.isPage)
|
|
108
|
+
continue;
|
|
109
|
+
project.compile(file);
|
|
110
|
+
for (const c of parsed.components) {
|
|
111
|
+
if (!c.customTag)
|
|
112
|
+
continue;
|
|
113
|
+
const key = "elements/" + c.customTag;
|
|
114
|
+
entries.set(key, `import ${JSON.stringify(file)};`);
|
|
115
|
+
entryPoints[key] = "sinth-entry:" + key;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (!entries.size)
|
|
119
|
+
return [];
|
|
120
|
+
try {
|
|
121
|
+
const result = await esbuild.build({
|
|
122
|
+
entryPoints, bundle: true, format: "esm", platform: "browser", target: project.config.target,
|
|
123
|
+
outdir: project.config.outDir, entryNames: "[dir]/[name]", minify: project.config.minify, write: false,
|
|
124
|
+
logLevel: "silent", charset: "utf8", legalComments: "none", loader: { ...ASSET_LOADERS, ".svg": "dataurl", ".png": "dataurl" },
|
|
125
|
+
plugins: [sinthPlugin(project, entries, true)], absWorkingDir: project.root,
|
|
126
|
+
});
|
|
127
|
+
return result.outputFiles;
|
|
128
|
+
}
|
|
129
|
+
catch (err) {
|
|
130
|
+
throw esbuildErrorToSinth(err, project);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function entryKey(page) {
|
|
134
|
+
const key = page.outFile.replace(/\.html$/, "").replace(/[^A-Za-z0-9/_-]/g, "_");
|
|
135
|
+
return key === "index" ? "index" : key.replace(/\/index$/, "/index");
|
|
136
|
+
}
|
|
137
|
+
function esbuildErrorToSinth(err, project) {
|
|
138
|
+
const failure = err;
|
|
139
|
+
const first = failure.errors?.[0];
|
|
140
|
+
if (!first)
|
|
141
|
+
return new diagnostics_1.SinthError("E0800", err.message ?? String(err));
|
|
142
|
+
const loc = first.location;
|
|
143
|
+
const missing = first.text.match(/Could not resolve "([^"]+)"/);
|
|
144
|
+
let hint;
|
|
145
|
+
if (missing && !missing[1].startsWith(".") && !missing[1].startsWith("/")) {
|
|
146
|
+
const name = missing[1].startsWith("@") ? missing[1].split("/").slice(0, 2).join("/") : missing[1].split("/")[0];
|
|
147
|
+
hint = `Install it with: npm install ${name}`;
|
|
148
|
+
}
|
|
149
|
+
const file = loc?.file ? path.resolve(project.root, loc.file.replace(/^[a-z-]+:/, "")) : undefined;
|
|
150
|
+
const isGenerated = !!file && file.endsWith(".sinth");
|
|
151
|
+
if (isGenerated && !missing) {
|
|
152
|
+
return new diagnostics_1.SinthError("E0899", `Internal compiler error: generated invalid JavaScript (${first.text})`, file ? { file, line: 1, col: 1 } : undefined, `Generated line ${loc?.line}: ${loc?.lineText?.trim().slice(0, 200)}. Please report this at https://github.com/Yannosay/sinth/issues`);
|
|
153
|
+
}
|
|
154
|
+
return new diagnostics_1.SinthError("E0800", first.text, file && !isGenerated ? { file, line: loc?.line ?? 1, col: (loc?.column ?? 0) + 1 } : undefined, hint);
|
|
155
|
+
}
|
|
156
|
+
function prepareOutDir(dir) {
|
|
157
|
+
if (!fs.existsSync(dir)) {
|
|
158
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const entries = fs.readdirSync(dir);
|
|
162
|
+
if (entries.length && !entries.includes("_sinth")) {
|
|
163
|
+
throw new diagnostics_1.SinthError("E0801", `Refusing to clear '${dir}': it is not empty and was not created by Sinth`, undefined, "Delete it yourself or set a different \"outDir\" in sinth.config.json");
|
|
164
|
+
}
|
|
165
|
+
for (const e of entries)
|
|
166
|
+
fs.rmSync(path.join(dir, e), { recursive: true, force: true });
|
|
167
|
+
}
|
|
168
|
+
function copyDir(src, dest, files, outDir) {
|
|
169
|
+
if (!fs.existsSync(src))
|
|
170
|
+
return;
|
|
171
|
+
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
|
|
172
|
+
if (entry.name.startsWith(".") && entry.name !== ".well-known")
|
|
173
|
+
continue;
|
|
174
|
+
const from = path.join(src, entry.name);
|
|
175
|
+
const to = path.join(dest, entry.name);
|
|
176
|
+
if (entry.isDirectory())
|
|
177
|
+
copyDir(from, to, files, outDir);
|
|
178
|
+
else if (entry.isFile() && !entry.name.endsWith(".sinth")) {
|
|
179
|
+
files.set(path.relative(outDir, to).replace(/\\/g, "/"), { path: to, contents: fs.readFileSync(from) });
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
function contentSecurityPolicy(pages, custom) {
|
|
184
|
+
if (custom === false)
|
|
185
|
+
return undefined;
|
|
186
|
+
if (typeof custom === "string")
|
|
187
|
+
return custom;
|
|
188
|
+
const scriptOrigins = new Set();
|
|
189
|
+
const styleOrigins = new Set();
|
|
190
|
+
let fonts = false;
|
|
191
|
+
for (const p of pages) {
|
|
192
|
+
for (const s of p.externalScripts)
|
|
193
|
+
scriptOrigins.add(originOf(s.src));
|
|
194
|
+
for (const s of p.externalStyles)
|
|
195
|
+
styleOrigins.add(originOf(s));
|
|
196
|
+
if (p.fonts.length)
|
|
197
|
+
fonts = true;
|
|
198
|
+
}
|
|
199
|
+
if (fonts)
|
|
200
|
+
styleOrigins.add("https://fonts.googleapis.com");
|
|
201
|
+
return [
|
|
202
|
+
"default-src 'self'",
|
|
203
|
+
`script-src 'self'${[...scriptOrigins].map(o => " " + o).join("")}`,
|
|
204
|
+
`style-src 'self' 'unsafe-inline'${[...styleOrigins].map(o => " " + o).join("")}`,
|
|
205
|
+
`font-src 'self' data:${fonts ? " https://fonts.gstatic.com" : ""}`,
|
|
206
|
+
"img-src 'self' data: blob: https:",
|
|
207
|
+
"media-src 'self' data: blob: https:",
|
|
208
|
+
"connect-src 'self' https: wss:",
|
|
209
|
+
"frame-src 'self' https:",
|
|
210
|
+
"object-src 'none'",
|
|
211
|
+
"base-uri 'self'",
|
|
212
|
+
"form-action 'self'",
|
|
213
|
+
"frame-ancestors 'self'",
|
|
214
|
+
].join("; ");
|
|
215
|
+
}
|
|
216
|
+
function originOf(url) {
|
|
217
|
+
try {
|
|
218
|
+
return new URL(url.startsWith("//") ? "https:" + url : url).origin;
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
return url;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
async function buildProject(project, options) {
|
|
225
|
+
const started = Date.now();
|
|
226
|
+
const cfg = project.config;
|
|
227
|
+
project.invalidate();
|
|
228
|
+
const pages = project.findPages();
|
|
229
|
+
if (!pages.length) {
|
|
230
|
+
throw new diagnostics_1.SinthError("E0802", fs.existsSync(cfg.pagesDir) ? `No pages found in ${path.relative(project.root, cfg.pagesDir) || "."}` : `No pages found (no ${path.relative(project.root, cfg.pagesDir) || "pages"}/ folder, and no .sinth file with markup in the project root)`, undefined, fs.existsSync(cfg.pagesDir)
|
|
231
|
+
? "Every .sinth file in this folder is a page (files starting with '_' are skipped). Add markup to pages/index.sinth, for example: Main { Heading { \"Hello\" } }"
|
|
232
|
+
: `Create ${path.relative(project.root, cfg.pagesDir) || "pages"}/index.sinth with some markup, for example: Main { Heading { "Hello" } }`);
|
|
233
|
+
}
|
|
234
|
+
const compiled = pages.map(p => project.compilePage(p));
|
|
235
|
+
const entries = new Map();
|
|
236
|
+
const entryPoints = {};
|
|
237
|
+
for (const c of compiled) {
|
|
238
|
+
const key = entryKey(c.page);
|
|
239
|
+
const lines = [];
|
|
240
|
+
for (const s of c.styleImports)
|
|
241
|
+
lines.push(`import ${JSON.stringify(s)};`);
|
|
242
|
+
if (c.interactive) {
|
|
243
|
+
lines.push(`import * as page from ${JSON.stringify(c.page.file)};`);
|
|
244
|
+
lines.push(`import { boot } from "sinth-runtime";`);
|
|
245
|
+
lines.push(`boot({ render: page.render, state: page.state, restore: page.restore, dev: ${project.dev} });`);
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
for (const f of c.graph)
|
|
249
|
+
if (project.compile(f).css)
|
|
250
|
+
lines.push(`import ${JSON.stringify("sinth-css:" + f)};`);
|
|
251
|
+
}
|
|
252
|
+
entries.set(key, lines.join("\n"));
|
|
253
|
+
entryPoints[key] = "sinth-entry:" + key;
|
|
254
|
+
}
|
|
255
|
+
let result;
|
|
256
|
+
try {
|
|
257
|
+
result = await esbuild.build({
|
|
258
|
+
entryPoints,
|
|
259
|
+
bundle: true,
|
|
260
|
+
format: "esm",
|
|
261
|
+
splitting: true,
|
|
262
|
+
platform: "browser",
|
|
263
|
+
target: cfg.target,
|
|
264
|
+
outdir: path.join(cfg.outDir, "_sinth"),
|
|
265
|
+
entryNames: project.dev ? "[dir]/[name]" : "[dir]/[name]-[hash]",
|
|
266
|
+
chunkNames: "chunks/[name]-[hash]",
|
|
267
|
+
assetNames: "assets/[name]-[hash]",
|
|
268
|
+
publicPath: cfg.base + "_sinth",
|
|
269
|
+
minify: cfg.minify,
|
|
270
|
+
sourcemap: cfg.sourcemap ? (project.dev ? "inline" : "linked") : false,
|
|
271
|
+
metafile: true,
|
|
272
|
+
write: false,
|
|
273
|
+
logLevel: "silent",
|
|
274
|
+
charset: "utf8",
|
|
275
|
+
legalComments: cfg.minify ? "none" : "eof",
|
|
276
|
+
loader: ASSET_LOADERS,
|
|
277
|
+
define: { "process.env.NODE_ENV": JSON.stringify(project.dev ? "development" : "production") },
|
|
278
|
+
plugins: [sinthPlugin(project, entries)],
|
|
279
|
+
absWorkingDir: project.root,
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
catch (err) {
|
|
283
|
+
throw esbuildErrorToSinth(err, project);
|
|
284
|
+
}
|
|
285
|
+
const files = new Map();
|
|
286
|
+
for (const f of result.outputFiles) {
|
|
287
|
+
files.set(path.relative(cfg.outDir, f.path).replace(/\\/g, "/"), { path: f.path, contents: f.contents });
|
|
288
|
+
}
|
|
289
|
+
const csp = contentSecurityPolicy(compiled, cfg.security.csp);
|
|
290
|
+
const pageOutputs = [];
|
|
291
|
+
const toUrl = (abs) => cfg.base + path.relative(cfg.outDir, path.resolve(project.root, abs)).replace(/\\/g, "/");
|
|
292
|
+
for (const c of compiled) {
|
|
293
|
+
const key = entryKey(c.page);
|
|
294
|
+
let jsOut;
|
|
295
|
+
let cssOut;
|
|
296
|
+
const preloads = [];
|
|
297
|
+
for (const [out, meta] of Object.entries(result.metafile.outputs)) {
|
|
298
|
+
if (meta.entryPoint !== "sinth-entry:" + key)
|
|
299
|
+
continue;
|
|
300
|
+
jsOut = out;
|
|
301
|
+
cssOut = meta.cssBundle;
|
|
302
|
+
for (const imp of meta.imports)
|
|
303
|
+
if (imp.kind === "import-statement" && !imp.external)
|
|
304
|
+
preloads.push(toUrl(imp.path));
|
|
305
|
+
}
|
|
306
|
+
const styles = [];
|
|
307
|
+
const inlineHead = [];
|
|
308
|
+
if (c.fonts.length) {
|
|
309
|
+
inlineHead.push('<link rel="preconnect" href="https://fonts.googleapis.com">', '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>');
|
|
310
|
+
for (const f of c.fonts)
|
|
311
|
+
styles.push((0, project_1.fontHref)(f));
|
|
312
|
+
}
|
|
313
|
+
styles.push(...c.externalStyles);
|
|
314
|
+
if (cssOut)
|
|
315
|
+
styles.push(toUrl(cssOut));
|
|
316
|
+
const scripts = c.externalScripts.map(s => ({ src: s.src, module: false, attrs: s.attrs }));
|
|
317
|
+
if (c.interactive && jsOut)
|
|
318
|
+
scripts.push({ src: toUrl(jsOut), module: true, attrs: {} });
|
|
319
|
+
if (options.devClient)
|
|
320
|
+
inlineHead.push(`<script type="module" src="${options.devClient}"></script>`);
|
|
321
|
+
if (!c.interactive && jsOut)
|
|
322
|
+
files.delete(path.relative(cfg.outDir, path.resolve(project.root, jsOut)).replace(/\\/g, "/"));
|
|
323
|
+
for (const inst of c.instances) {
|
|
324
|
+
const head = (0, html_1.buildHead)(inst.meta, v => project.resolveAsset(v, c.page.file));
|
|
325
|
+
const pageHead = inst.params && c.interactive
|
|
326
|
+
? [...inlineHead, '<script type="application/json" id="sinth-params">' + JSON.stringify(inst.params).replace(/</g, "\\u003c") + "</script>"]
|
|
327
|
+
: inlineHead;
|
|
328
|
+
const html = (0, html_1.renderDocument)(head, inst.prerendered, { styles, scripts, preloads: c.interactive ? preloads : [], inlineHead: pageHead });
|
|
329
|
+
files.set(inst.page.outFile, { path: path.join(cfg.outDir, inst.page.outFile), contents: Buffer.from(html) });
|
|
330
|
+
pageOutputs.push({
|
|
331
|
+
page: inst.page, html, interactive: c.interactive, bytes: Buffer.byteLength(html),
|
|
332
|
+
js: c.interactive && jsOut ? toUrl(jsOut) : undefined, css: cssOut ? toUrl(cssOut) : undefined,
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (!project.dev) {
|
|
337
|
+
for (const f of await buildCustomElements(project)) {
|
|
338
|
+
files.set(path.relative(cfg.outDir, f.path).replace(/\\/g, "/"), { path: f.path, contents: f.contents });
|
|
339
|
+
}
|
|
340
|
+
copyDir(cfg.publicDir, cfg.outDir, files, cfg.outDir);
|
|
341
|
+
for (const d of cfg.staticDirs)
|
|
342
|
+
copyDir(path.resolve(project.root, d), path.join(cfg.outDir, d), files, cfg.outDir);
|
|
343
|
+
if (cfg.security.headers && !files.has("_headers")) {
|
|
344
|
+
const lines = ["/*", " X-Content-Type-Options: nosniff", " Referrer-Policy: strict-origin-when-cross-origin", " X-Frame-Options: SAMEORIGIN", " Cross-Origin-Opener-Policy: same-origin"];
|
|
345
|
+
if (csp)
|
|
346
|
+
lines.push(` Content-Security-Policy: ${csp}`);
|
|
347
|
+
lines.push("", `${cfg.base}_sinth/*`, " Cache-Control: public, max-age=31536000, immutable", "");
|
|
348
|
+
files.set("_headers", { path: path.join(cfg.outDir, "_headers"), contents: Buffer.from(lines.join("\n")) });
|
|
349
|
+
}
|
|
350
|
+
if (cfg.site) {
|
|
351
|
+
const site = cfg.site.replace(/\/$/, "");
|
|
352
|
+
const urls = pageOutputs.filter(p => !/(^|\/)404$/.test(p.page.route)).map(p => ` <url><loc>${(0, html_1.escapeHtml)(site + p.page.route)}</loc></url>`);
|
|
353
|
+
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`) });
|
|
354
|
+
if (!files.has("robots.txt"))
|
|
355
|
+
files.set("robots.txt", { path: path.join(cfg.outDir, "robots.txt"), contents: Buffer.from(`User-agent: *\nAllow: /\n\nSitemap: ${site}/sitemap.xml\n`) });
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
if (options.write) {
|
|
359
|
+
prepareOutDir(cfg.outDir);
|
|
360
|
+
for (const f of files.values()) {
|
|
361
|
+
fs.mkdirSync(path.dirname(f.path), { recursive: true });
|
|
362
|
+
fs.writeFileSync(f.path, f.contents);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
const bundlerWarnings = result.warnings.map(w => ({
|
|
366
|
+
severity: "warning",
|
|
367
|
+
code: "W0800",
|
|
368
|
+
message: w.text,
|
|
369
|
+
loc: w.location?.file && !w.location.file.endsWith(".sinth") ? { file: path.resolve(project.root, w.location.file.replace(/^[a-z-]+:/, "")), line: w.location.line, col: w.location.column + 1 } : undefined,
|
|
370
|
+
}));
|
|
371
|
+
const warnings = dedupeWarnings([...compiled.flatMap(c => c.warnings), ...bundlerWarnings]);
|
|
372
|
+
return { pages: pageOutputs, files, warnings, durationMs: Date.now() - started };
|
|
373
|
+
}
|
|
374
|
+
function dedupeWarnings(list) {
|
|
375
|
+
const seen = new Set();
|
|
376
|
+
return list.filter(d => {
|
|
377
|
+
const key = `${d.code}${d.message}${d.loc?.file}${d.loc?.line}${d.loc?.col}`;
|
|
378
|
+
if (seen.has(key))
|
|
379
|
+
return false;
|
|
380
|
+
seen.add(key);
|
|
381
|
+
return true;
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
function checkProject(project) {
|
|
385
|
+
project.invalidate();
|
|
386
|
+
const pages = project.findPages();
|
|
387
|
+
const errors = [];
|
|
388
|
+
const warnings = [];
|
|
389
|
+
const pageFiles = new Set(pages.map(p => p.file));
|
|
390
|
+
for (const p of pages) {
|
|
391
|
+
try {
|
|
392
|
+
warnings.push(...project.compilePage(p).warnings);
|
|
393
|
+
}
|
|
394
|
+
catch (err) {
|
|
395
|
+
if (err instanceof diagnostics_1.SinthError)
|
|
396
|
+
errors.push(err);
|
|
397
|
+
else
|
|
398
|
+
throw err;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
const skip = new Set(["node_modules", ".git", ".sinth", ".wrangler"]);
|
|
402
|
+
const walk = (dir) => {
|
|
403
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
404
|
+
const full = path.join(dir, e.name);
|
|
405
|
+
if (e.isDirectory()) {
|
|
406
|
+
if (!skip.has(e.name) && full !== project.config.outDir)
|
|
407
|
+
walk(full);
|
|
408
|
+
}
|
|
409
|
+
else if (e.name.endsWith(".sinth") && !pageFiles.has(full)) {
|
|
410
|
+
try {
|
|
411
|
+
if (!project.getFile(full).isPage)
|
|
412
|
+
warnings.push(...project.compile(full).diagnostics.warnings);
|
|
413
|
+
}
|
|
414
|
+
catch (err) {
|
|
415
|
+
if (!(err instanceof diagnostics_1.SinthError))
|
|
416
|
+
throw err;
|
|
417
|
+
if (!errors.some(x => x.message === err.message && x.loc?.file === err.loc?.file))
|
|
418
|
+
errors.push(err);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
walk(project.root);
|
|
424
|
+
return { pages, warnings: dedupeWarnings(warnings), errors };
|
|
425
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export interface CloudflareConfig {
|
|
2
|
+
projectName?: string;
|
|
3
|
+
accountId?: string;
|
|
4
|
+
productionBranch?: string;
|
|
5
|
+
}
|
|
6
|
+
export interface SecurityConfig {
|
|
7
|
+
headers: boolean;
|
|
8
|
+
csp: boolean | string;
|
|
9
|
+
}
|
|
10
|
+
export interface SinthConfig {
|
|
11
|
+
outDir: string;
|
|
12
|
+
pagesDir: string;
|
|
13
|
+
publicDir: string;
|
|
14
|
+
staticDirs: string[];
|
|
15
|
+
libraryPaths: string[];
|
|
16
|
+
site?: string;
|
|
17
|
+
base: string;
|
|
18
|
+
minify: boolean;
|
|
19
|
+
sourcemap: boolean;
|
|
20
|
+
port: number;
|
|
21
|
+
host: string;
|
|
22
|
+
previewPort: number;
|
|
23
|
+
target: string[];
|
|
24
|
+
security: SecurityConfig;
|
|
25
|
+
cloudflare: CloudflareConfig;
|
|
26
|
+
}
|
|
27
|
+
export declare const DEFAULT_CONFIG: SinthConfig;
|
|
28
|
+
export interface LoadedConfig {
|
|
29
|
+
config: SinthConfig;
|
|
30
|
+
file?: string;
|
|
31
|
+
warnings: string[];
|
|
32
|
+
}
|
|
33
|
+
export declare function loadConfig(root: string, mode: "development" | "production"): LoadedConfig;
|