@yannosay/sinth 1.11.6 → 1.12.1

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/src/resolver.ts DELETED
@@ -1,150 +0,0 @@
1
- import * as fs from "fs";
2
- import * as path from "path";
3
- import { SinthFile, CompDef, CustomElInfo, SinthError, SinthWarning } from "./core/types.ts";
4
- import { Lexer } from "./core/lexer.ts";
5
- import { Parser } from "./core/parser.ts";
6
- import { BUILTIN_MAP } from "./core/builtins.ts";
7
-
8
-
9
-
10
- export interface ResolverConfig { projectRoot: string; libraryPaths: string[] }
11
-
12
- export interface ResolvedImports {
13
- allDefs: Map<string, CompDef>;
14
- customEls: Map<string, CustomElInfo>;
15
- cssLinks: string[];
16
- jsLinks: { src: string; attrs: Record<string, string> }[];
17
- }
18
-
19
- export const IMPORT_STACK: string[] = [];
20
-
21
- export function parseFile(filePath: string): SinthFile {
22
- if (!fs.existsSync(filePath)) throw new SinthError(`File not found: ${filePath}`);
23
- const src = fs.readFileSync(filePath, "utf-8");
24
- const srcLines = src.split("\n");
25
- try {
26
- const tokens = new Lexer(src, filePath).tokenize();
27
- return new Parser(tokens, filePath).parse();
28
- } catch (e) {
29
- if (e instanceof SinthError) throw e.withSource(srcLines);
30
- throw e;
31
- }
32
- }
33
-
34
- export function resolveImports(
35
- file: SinthFile,
36
- cfg: ResolverConfig,
37
- visited: Set<string> = new Set(),
38
- ): ResolvedImports {
39
- const allDefs = new Map<string, CompDef>();
40
- const customEls = new Map<string, CustomElInfo>();
41
- const cssLinks: string[] = [];
42
- const jsLinks: { src: string; attrs: Record<string, string> }[] = [];
43
-
44
- for (const def of file.defs) {
45
- if (BUILTIN_MAP[def.name]) {
46
- throw new SinthError(`'${def.name}' is a built-in Sinth component and cannot be redefined.`, def.loc);
47
- }
48
- if (allDefs.has(def.name)) throw new SinthError(`Duplicate component definition '${def.name}'`, def.loc);
49
- allDefs.set(def.name, def);
50
- }
51
-
52
- for (const el of file.customEls) {
53
- customEls.set(el.sinthName, { tagName: el.tagName, params: el.params });
54
- }
55
-
56
- if (!file.isPage && file.meta.length > 0) {
57
- for (const m of file.meta) {
58
- SinthWarning.emit(`Metadata '${m.key}' in component file '${file.filePath}' has no effect.`, m.loc);
59
- }
60
- }
61
-
62
- for (const imp of file.imports) {
63
- if (imp.kind === "css") {
64
- const r = resolveRelative(imp.path, file.filePath);
65
- if (!cssLinks.includes(r)) cssLinks.push(r);
66
-
67
- } else if (imp.kind === "js") {
68
- const src = resolveLibrary(imp.name, cfg);
69
- jsLinks.push({ src, attrs: {} });
70
-
71
- for (const libDir of cfg.libraryPaths) {
72
- const companion = path.join(libDir, imp.name + ".sinth");
73
- if (fs.existsSync(companion) && !visited.has(companion)) {
74
- visited.add(companion);
75
- IMPORT_STACK.push(companion);
76
- const sub = resolveImports(parseFile(companion), cfg, visited);
77
- IMPORT_STACK.pop();
78
- for (const [n, d] of sub.allDefs) allDefs.set(n, d);
79
- for (const [n, e] of sub.customEls) customEls.set(n, e);
80
- }
81
- }
82
-
83
- } else if (imp.kind === "sinth") {
84
- const resolved = resolveSinthPath(imp.path, file.filePath, cfg);
85
-
86
- if (IMPORT_STACK.includes(resolved)) {
87
- throw new SinthError(
88
- `Circular import: ${[...IMPORT_STACK, resolved].join(" → ")}`
89
- );
90
- }
91
- if (visited.has(resolved)) continue;
92
- visited.add(resolved);
93
-
94
- IMPORT_STACK.push(resolved);
95
- const imported = parseFile(resolved);
96
- IMPORT_STACK.pop();
97
-
98
- const sub = resolveImports(imported, cfg, visited);
99
- for (const [name, def] of sub.allDefs) {
100
- if (allDefs.has(name)) throw new SinthError(`Component '${name}' defined in multiple imported files.`);
101
- allDefs.set(name, def);
102
- }
103
- for (const [n, e] of sub.customEls) customEls.set(n, e);
104
- for (const l of sub.cssLinks) if (!cssLinks.includes(l)) cssLinks.push(l);
105
- for (const j of sub.jsLinks) jsLinks.push(j);
106
- }
107
- }
108
-
109
- return { allDefs, customEls, cssLinks, jsLinks };
110
- }
111
-
112
- export function resolveRelative(p: string, fromFile: string): string {
113
- if (p.startsWith("./") || p.startsWith("../")) return path.resolve(path.dirname(fromFile), p);
114
- return p;
115
- }
116
-
117
- export function resolveLibrary(name: string, cfg: ResolverConfig): string {
118
- const base = name.endsWith(".js") ? name : name + ".js";
119
- for (const libDir of cfg.libraryPaths) {
120
- const c = path.join(libDir, base);
121
- if (fs.existsSync(c)) return c;
122
- }
123
- return `/libraries/${base}`;
124
- }
125
-
126
- export function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): string {
127
- if (p.startsWith("./") || p.startsWith("../")) {
128
- const r = path.resolve(path.dirname(fromFile), p);
129
- if (fs.existsSync(r)) return r;
130
- const w = r.endsWith(".sinth") ? "" : r + ".sinth";
131
- if (w && fs.existsSync(w)) return w;
132
- throw new SinthError(`Cannot resolve import '${p}' from '${fromFile}'`);
133
- }
134
-
135
- const relToFile = path.resolve(path.dirname(fromFile), p);
136
- if (fs.existsSync(relToFile)) return relToFile;
137
- const relToFileExt = relToFile.endsWith(".sinth") ? relToFile : relToFile + ".sinth";
138
- if (fs.existsSync(relToFileExt)) return relToFileExt;
139
-
140
- for (const libDir of cfg.libraryPaths) {
141
- const c1 = path.join(libDir, p);
142
- if (fs.existsSync(c1)) return c1;
143
- const c2 = c1.endsWith(".sinth") ? c1 : c1 + ".sinth";
144
- if (fs.existsSync(c2)) return c2;
145
- }
146
-
147
- throw new SinthError(
148
- `Cannot resolve import '${p}'\n Tried: ${relToFileExt}\n Library paths: ${cfg.libraryPaths.join(", ")}`
149
- );
150
- }
package/src/server.ts DELETED
@@ -1,129 +0,0 @@
1
- import * as http from "http";
2
- import * as path from "path";
3
- import * as fs from "fs";
4
- import { compileFile, CompileOptions, findSinthPages, minifyHTML } from "./core/cli-compiler.ts";
5
-
6
-
7
-
8
- export const LIVE_RELOAD_SCRIPT = `<script>
9
- (function(){
10
- var es = new EventSource('/__sinth_sse__');
11
- es.onmessage = function() { location.reload(); };
12
- es.onerror = function() { setTimeout(function() { location.reload(); }, 1000); };
13
- })();
14
- </script>`;
15
-
16
- export async function startDevServer(opts: CompileOptions & { port: number; files?: string[] }): Promise<void> {
17
- const clients: http.ServerResponse[] = [];
18
- const cache = new Map<string, string>();
19
-
20
- function notify(): void {
21
- for (const c of clients) { try { c.write("data: reload\n\n"); } catch {} }
22
- }
23
-
24
- function compileAll(): void {
25
- cache.clear();
26
- const pages = (opts.files && opts.files.length > 0)
27
- ? opts.files.filter(f => fs.existsSync(f))
28
- : findSinthPages(opts.projectRoot, opts.outDir);
29
- for (const p of pages) {
30
- try {
31
- const result = compileFile(p, { ...opts, checkOnly: false });
32
- if (!result) continue;
33
- const html = result.html;
34
- const rel = path.relative(opts.projectRoot, p).replace(/\.sinth$/, ".html").replace(/\\/g, "/");
35
- const url = "/" + rel;
36
- cache.set(url, html + LIVE_RELOAD_SCRIPT);
37
- if (rel === "index.html" || rel.endsWith("/index.html")) {
38
- cache.set("/", html + LIVE_RELOAD_SCRIPT);
39
- }
40
- } catch (e: unknown) {
41
- process.stderr.write(`\x1b[31m${(e as Error).message}\x1b[0m\n`);
42
- }
43
- }
44
- }
45
-
46
- compileAll();
47
-
48
- const resolvedOut = path.resolve(opts.outDir);
49
- let watchReady = false;
50
- const pending = new Map<string, NodeJS.Timeout>();
51
- const DEBOUNCE_MS = 300;
52
-
53
- try {
54
- fs.watch(opts.projectRoot, { recursive: true }, (_, filename) => {
55
- if (!filename) return;
56
- const abs = path.resolve(opts.projectRoot, filename);
57
- if (abs.startsWith(resolvedOut + path.sep) || abs === resolvedOut) return;
58
- if (pending.has(abs)) {
59
- clearTimeout(pending.get(abs)!);
60
- }
61
- pending.set(abs, setTimeout(() => {
62
- pending.delete(abs);
63
- process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${filename}\n`);
64
- compileAll(); notify();
65
- }, DEBOUNCE_MS));
66
- });
67
- watchReady = true;
68
- } catch {}
69
-
70
- if (!watchReady) {
71
- const mtimes = new Map<string, number>();
72
- const poller = setInterval(() => {
73
- const pages = (opts.files && opts.files.length > 0)
74
- ? opts.files : findSinthPages(opts.projectRoot, opts.outDir);
75
- for (const p of pages) {
76
- try {
77
- const mtime = fs.statSync(p).mtimeMs;
78
- if (mtimes.get(p) !== mtime) {
79
- mtimes.set(p, mtime);
80
- process.stdout.write(`\x1b[36m[sinth]\x1b[0m Changed: ${path.relative(opts.projectRoot, p)}\n`);
81
- compileAll(); notify(); break;
82
- }
83
- } catch {}
84
- }
85
- }, 500);
86
- process.on("exit", () => clearInterval(poller));
87
- }
88
-
89
- const EXT_TYPES: Record<string, string> = {
90
- ".css": "text/css", ".js": "application/javascript",
91
- ".png": "image/png", ".svg": "image/svg+xml", ".ico": "image/x-icon",
92
- ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
93
- ".gif": "image/gif", ".webp": "image/webp",
94
- ".woff2": "font/woff2", ".woff": "font/woff", ".ttf": "font/ttf",
95
- ".json": "application/json", ".xml": "application/xml",
96
- };
97
-
98
- const server = http.createServer((req, res) => {
99
- const reqUrl = (req.url ?? "/").split("?")[0];
100
-
101
- if (reqUrl === "/__sinth_sse__") {
102
- res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "Connection": "keep-alive" });
103
- clients.push(res);
104
- req.on("close", () => { const i = clients.indexOf(res); if (i !== -1) clients.splice(i, 1); });
105
- return;
106
- }
107
-
108
- const cached = cache.get(reqUrl) ??
109
- cache.get(reqUrl.endsWith("/") ? reqUrl + "index.html" : reqUrl + ".html");
110
- if (cached) { res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); res.end(cached); return; }
111
-
112
- let filePath = path.join(opts.projectRoot, reqUrl);
113
- if (reqUrl.endsWith("/")) filePath = path.join(filePath, "index.html");
114
- if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
115
- const ctype = EXT_TYPES[path.extname(filePath).toLowerCase()] ?? "application/octet-stream";
116
- res.writeHead(200, { "Content-Type": ctype });
117
- res.end(fs.readFileSync(filePath));
118
- return;
119
- }
120
-
121
- res.writeHead(404, { "Content-Type": "text/plain" }); res.end("404 Not Found");
122
- });
123
-
124
- server.listen(opts.port, () => {
125
- process.stdout.write(
126
- `\x1b[32m[sinth dev]\x1b[0m Serving at \x1b[4mhttp://localhost:${opts.port}\x1b[0m\n`
127
- );
128
- });
129
- }
package/src/utils.ts DELETED
@@ -1,77 +0,0 @@
1
- import { Literal, SinthWarning } from "./core/types.ts";
2
-
3
-
4
- export function fnv1a(s: string): string {
5
- let h = 0x811c9dc5;
6
- for (let i = 0; i < s.length; i++) {
7
- h ^= s.charCodeAt(i);
8
- h = Math.imul(h, 0x01000193) >>> 0;
9
- }
10
- return h.toString(16).padStart(8, "0").slice(0, 8);
11
- }
12
-
13
- export function camelToKebab(s: string): string {
14
- const vp = s.match(/^(Webkit|Moz|Ms)(.+)$/);
15
- if (vp) return `-${vp[1].toLowerCase()}-${camelToKebab(vp[2])}`;
16
- return s.replace(/([A-Z])/g, m => `-${m.toLowerCase()}`);
17
- }
18
-
19
- export function tagNameToPascal(tag: string): string {
20
- return tag.split("-").map(p => p.charAt(0).toUpperCase() + p.slice(1)).join("");
21
- }
22
-
23
- export function esc(s: string): string {
24
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
25
- }
26
-
27
- export function escAttr(s: string): string {
28
- return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
29
- }
30
-
31
- export function litToString(lit: Literal): string {
32
- switch (lit.kind) {
33
- case "str": return lit.value;
34
- case "num": return String(lit.value);
35
- case "bool": return String(lit.value);
36
- case "null": return "";
37
- }
38
- }
39
-
40
- export function interpolateAttr(text: string, params: Map<string, string>): string {
41
- let s = text.replace(/\\\{/g, "\x00LB\x00");
42
- s = s.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_, n) => params.get(n) ?? `{${n}}`);
43
- return s.replace(/\x00LB\x00/g, "{");
44
- }
45
-
46
- export function renderText(text: string, params: Map<string, string>): string {
47
- const rawSlots = new Map<string, string>();
48
- let counter = 0;
49
-
50
- let s = text.replace(/\\\$/g, "\x00DOLLAR\x00");
51
-
52
- s = s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, n) => {
53
- const val = params.get(n);
54
- if (val === undefined) return `$${n}`;
55
- if (n === "slot") {
56
- const ph = `\x00RAW${counter++}\x00`;
57
- rawSlots.set(ph, val);
58
- return ph;
59
- }
60
- return val;
61
- });
62
-
63
- s = esc(s);
64
-
65
- for (const [ph, val] of rawSlots) s = s.replace(ph, val);
66
- s = s.replace(/\x00DOLLAR\x00/g, "$");
67
-
68
- const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
69
- let m: RegExpExecArray | null;
70
- while ((m = braceRe.exec(s)) !== null) {
71
- SinthWarning.emit(
72
- `Use $param for text interpolation; {param} is for attributes. Found '${m[0]}' in text.`
73
- );
74
- }
75
-
76
- return s;
77
- }
package/tsconfig.json DELETED
@@ -1,27 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "commonjs",
5
- "lib": ["ES2020"],
6
- "outDir": "./dist",
7
- "rootDir": "./src",
8
- "strict": true,
9
- "esModuleInterop": true,
10
- "skipLibCheck": true,
11
- "noImplicitAny": true,
12
- "strictNullChecks": true,
13
- "allowImportingTsExtensions": true,
14
- "noEmit": true,
15
- "types": ["node"],
16
- "typeRoots": ["./node_modules/@types", "../node_modules/@types"]
17
- },
18
- "include": ["src/**/*"],
19
- "exclude": ["node_modules", "dist"],
20
- "ts-node": {
21
- "compilerOptions": {
22
- "module": "commonjs"
23
- },
24
- "esm": false,
25
- "transpileOnly": true
26
- }
27
- }