@yannosay/sinth 4.1.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.
Files changed (78) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/DOCS.md +1359 -0
  3. package/README.md +83 -74
  4. package/bin/sinth.js +2 -1
  5. package/dist/cli/args.d.ts +11 -0
  6. package/dist/cli/args.js +74 -0
  7. package/dist/cli/index.d.ts +1 -0
  8. package/dist/cli/index.js +437 -0
  9. package/dist/cli/templates.d.ts +10 -0
  10. package/dist/cli/templates.js +193 -0
  11. package/dist/cli/ui.d.ts +28 -0
  12. package/dist/cli/ui.js +61 -0
  13. package/dist/cli/update-check.d.ts +2 -0
  14. package/dist/cli/update-check.js +124 -0
  15. package/dist/compiler/ast.d.ts +315 -0
  16. package/dist/compiler/ast.js +4 -0
  17. package/dist/compiler/codegen.d.ts +143 -0
  18. package/dist/compiler/codegen.js +1326 -0
  19. package/dist/compiler/diagnostics.d.ts +36 -0
  20. package/dist/compiler/diagnostics.js +142 -0
  21. package/dist/compiler/elements.d.ts +14 -0
  22. package/dist/compiler/elements.js +78 -0
  23. package/dist/compiler/globals.d.ts +2 -0
  24. package/dist/compiler/globals.js +27 -0
  25. package/dist/compiler/html.d.ts +37 -0
  26. package/dist/compiler/html.js +152 -0
  27. package/dist/compiler/lexer.d.ts +42 -0
  28. package/dist/compiler/lexer.js +404 -0
  29. package/dist/compiler/parser.d.ts +95 -0
  30. package/dist/compiler/parser.js +1374 -0
  31. package/dist/compiler/prerender.d.ts +72 -0
  32. package/dist/compiler/prerender.js +910 -0
  33. package/dist/compiler/script-analysis.d.ts +6 -0
  34. package/dist/compiler/script-analysis.js +106 -0
  35. package/dist/compiler/style.d.ts +39 -0
  36. package/dist/compiler/style.js +463 -0
  37. package/dist/deploy/cloudflare.d.ts +9 -0
  38. package/dist/deploy/cloudflare.js +111 -0
  39. package/dist/index.d.ts +13 -0
  40. package/dist/index.js +23 -0
  41. package/dist/project/build.d.ts +31 -0
  42. package/dist/project/build.js +425 -0
  43. package/dist/project/config.d.ts +33 -0
  44. package/dist/project/config.js +142 -0
  45. package/dist/project/project.d.ts +74 -0
  46. package/dist/project/project.js +535 -0
  47. package/dist/runtime/index.d.ts +68 -0
  48. package/dist/runtime/index.js +912 -0
  49. package/dist/server/client.d.ts +1 -0
  50. package/dist/server/client.js +112 -0
  51. package/dist/server/dev.d.ts +8 -0
  52. package/dist/server/dev.js +244 -0
  53. package/dist/server/preview.d.ts +6 -0
  54. package/dist/server/preview.js +106 -0
  55. package/dist/server/static.d.ts +10 -0
  56. package/dist/server/static.js +136 -0
  57. package/lib/ui/index.sinth +436 -0
  58. package/package.json +33 -15
  59. package/schema/sinth.config.schema.json +54 -0
  60. package/dist/browser/compile.js +0 -63
  61. package/dist/cli.js +0 -509
  62. package/dist/core/builtins.js +0 -117
  63. package/dist/core/cli-compiler.js +0 -705
  64. package/dist/core/compiler.js +0 -1489
  65. package/dist/core/expr.js +0 -129
  66. package/dist/core/head-builder.js +0 -130
  67. package/dist/core/lexer.js +0 -410
  68. package/dist/core/parser.js +0 -1646
  69. package/dist/core/runtime/custom-element.js +0 -81
  70. package/dist/core/runtime/functions.js +0 -99
  71. package/dist/core/runtime/helpers.js +0 -347
  72. package/dist/core/runtime/render.js +0 -136
  73. package/dist/core/style-processor.js +0 -317
  74. package/dist/core/types.js +0 -93
  75. package/dist/resolver.js +0 -175
  76. package/dist/server.js +0 -174
  77. package/dist/update-check.js +0 -109
  78. package/dist/utils.js +0 -80
@@ -1,317 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SINTH_PSEUDO_ELEMENT = exports.SINTH_PSEUDO_CLASS = void 0;
4
- exports.sinthCompToSelector = sinthCompToSelector;
5
- exports.preprocessSinthStyle = preprocessSinthStyle;
6
- exports.parseSinthMediaParams = parseSinthMediaParams;
7
- exports.convertCSSProps = convertCSSProps;
8
- exports.processStyleBlock = processStyleBlock;
9
- exports.scopeCSS = scopeCSS;
10
- exports.processRules = processRules;
11
- exports.scopeSelectors = scopeSelectors;
12
- exports.findCSSBrace = findCSSBrace;
13
- exports.extractCSSBlock = extractCSSBlock;
14
- const builtins_1 = require("./builtins");
15
- const types_1 = require("./types");
16
- const utils_1 = require("../utils");
17
- /**
18
- * for who's reading this: this maps Sinth Style pseudo-class shorthand keywords to real CSS pseudo-classes.
19
- * these are used inside component style blocks, for example: onHover { color: "blue" }
20
- */
21
- exports.SINTH_PSEUDO_CLASS = {
22
- onHover: ":hover",
23
- onFocus: ":focus",
24
- onActive: ":active",
25
- onVisited: ":visited",
26
- onChecked: ":checked",
27
- onDisabled: ":disabled",
28
- onEnabled: ":enabled",
29
- onRequired: ":required",
30
- onOptional: ":optional",
31
- onValid: ":valid",
32
- onInvalid: ":invalid",
33
- onPlaceholderShown: ":placeholder-shown",
34
- onFocusWithin: ":focus-within",
35
- onFocusVisible: ":focus-visible",
36
- onFirst: ":first-child",
37
- onLast: ":last-child",
38
- onFirstOfType: ":first-of-type",
39
- onLastOfType: ":last-of-type",
40
- onEmpty: ":empty",
41
- onTarget: ":target",
42
- onLink: ":link",
43
- };
44
- exports.SINTH_PSEUDO_ELEMENT = {
45
- before: "::before",
46
- after: "::after",
47
- placeholder: "::placeholder",
48
- selection: "::selection",
49
- firstLine: "::first-line",
50
- firstLetter: "::first-letter",
51
- marker: "::marker",
52
- backdrop: "::backdrop",
53
- };
54
- function sinthCompToSelector(name) {
55
- const info = builtins_1.BUILTIN_MAP[name];
56
- if (!info)
57
- return name.toLowerCase();
58
- if (info.defaultClass) {
59
- const classes = info.defaultClass.split(" ").map(c => `.${c}`).join("");
60
- return `${info.tag}${classes}`;
61
- }
62
- return info.tag;
63
- }
64
- /**
65
- * supported conversions:
66
- * - component names as selectors: `Paragraph { ... }` → `p { ... }`
67
- * - pseudo-class shorthands: `onHover { ... }` → `&:hover { ... }`
68
- * - pseudo-element shorthands: `before { ... }` → `&::before { ... }`
69
- * - media queries: `media(maxWidth: "600px") { ... }` → `@media (max-width: 600px) { ... }`
70
- * - CSS custom properties: `var --primary: "#3b82f6"` → `--primary: #3b82f6;`
71
- */
72
- function preprocessSinthStyle(raw) {
73
- const lines = raw.split("\n");
74
- const result = [];
75
- for (const line of lines) {
76
- const trimmed = line.trim();
77
- const indent = line.match(/^(\s*)/)?.[1] ?? "";
78
- if (!trimmed) {
79
- result.push(line);
80
- continue;
81
- }
82
- if (trimmed.startsWith("--") && !trimmed.startsWith("--[")) {
83
- continue;
84
- }
85
- if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*")) {
86
- result.push(line);
87
- continue;
88
- }
89
- const mediaMatch = trimmed.match(/^media\s*\(([^)]+)\)\s*(\{?\s*)$/);
90
- if (mediaMatch) {
91
- const params = parseSinthMediaParams(mediaMatch[1]);
92
- result.push(`${indent}@media (${params}) {`);
93
- continue;
94
- }
95
- const blockMatch = trimmed.match(/^([a-zA-Z][a-zA-Z0-9]*)(\s*\{\s*)$/);
96
- if (blockMatch) {
97
- const keyword = blockMatch[1];
98
- const pseudoCls = exports.SINTH_PSEUDO_CLASS[keyword];
99
- if (pseudoCls) {
100
- result.push(`${indent}&${pseudoCls} {`);
101
- continue;
102
- }
103
- const pseudoEl = exports.SINTH_PSEUDO_ELEMENT[keyword];
104
- if (pseudoEl) {
105
- result.push(`${indent}&${pseudoEl} {`);
106
- continue;
107
- }
108
- if (/^[A-Z]/.test(keyword) && builtins_1.BUILTIN_MAP[keyword]) {
109
- result.push(`${indent}${sinthCompToSelector(keyword)} {`);
110
- continue;
111
- }
112
- }
113
- const varPropMatch = trimmed.match(/^var\s+(--[a-zA-Z][a-zA-Z0-9-]*)\s*:\s*["']?([^"';]+)["']?\s*;?\s*$/);
114
- if (varPropMatch) {
115
- result.push(`${indent}${varPropMatch[1]}: ${varPropMatch[2].trim()};`);
116
- continue;
117
- }
118
- result.push(line);
119
- }
120
- return result.join("\n");
121
- }
122
- function parseSinthMediaParams(params) {
123
- const parts = params.split(",").map(p => {
124
- const m = p.trim().match(/^([a-zA-Z]+)\s*:\s*["']?([^"',]+)["']?\s*$/);
125
- if (!m)
126
- return p.trim();
127
- return `${(0, utils_1.camelToKebab)(m[1])}: ${m[2].trim()}`;
128
- });
129
- return parts.join(") and (");
130
- }
131
- // style processor
132
- function convertCSSProps(css) {
133
- return css.split("\n").map(line => {
134
- const trimmed = line.trim();
135
- if (!trimmed)
136
- return line;
137
- if (trimmed === "}" || trimmed.startsWith("}"))
138
- return line;
139
- if (trimmed.startsWith("//") || trimmed.startsWith("/*") || trimmed.startsWith("*"))
140
- return line;
141
- if (trimmed.startsWith("@"))
142
- return line;
143
- if (trimmed.includes("{"))
144
- return line;
145
- const m = line.match(/^(\s*)([a-zA-Z][a-zA-Z0-9-]*)(\s*:\s*)(.+?)(\s*;?\s*)$/);
146
- if (!m)
147
- return line;
148
- const [, indent, rawProp, , rawVal] = m;
149
- const hasCamelCase = /[a-z][A-Z]/.test(rawProp) || /^[A-Z]/.test(rawProp);
150
- const hasQuotedVal = /^["']/.test(rawVal.trim());
151
- if (!hasCamelCase && !hasQuotedVal)
152
- return line;
153
- let val = rawVal.trim();
154
- if (val.endsWith(";"))
155
- val = val.slice(0, -1).trimEnd();
156
- if ((val.startsWith('"') && val.endsWith('"')) ||
157
- (val.startsWith("'") && val.endsWith("'"))) {
158
- val = val.slice(1, -1);
159
- }
160
- return `${indent}${(0, utils_1.camelToKebab)(rawProp)}: ${val};`;
161
- }).join("\n");
162
- }
163
- function processStyleBlock(block, hash, params = new Map()) {
164
- let raw = block.raw;
165
- if (params.size > 0)
166
- raw = (0, utils_1.interpolateAttr)(raw, params); // interpolate {param} placeholders
167
- // this allows dynamic values in styles
168
- raw = preprocessSinthStyle(raw); // sinth style preprocessing
169
- if (block.lang === "css" && raw.includes("&")) { // warn if & in plain CSS
170
- types_1.SinthWarning.emit(`'&' (CSS nesting) found in style block. Nested selectors require a modern browser or lang="scss".`, block.loc);
171
- }
172
- let css = convertCSSProps(raw);
173
- // SCSS compilation
174
- if (block.lang === "scss") {
175
- let sass;
176
- try {
177
- // eslint-disable-next-line @typescript-eslint/no-require-imports
178
- sass = require("sass");
179
- }
180
- catch {
181
- throw new types_1.SinthError(`style lang="scss" requires the 'sass' package to be installed.\n` +
182
- `Run: npm install sass`, block.loc);
183
- }
184
- try {
185
- css = sass.compileString(css).css;
186
- }
187
- catch (e) {
188
- const err = e;
189
- throw new types_1.SinthError(`SCSS compilation failed: ${err.message ?? String(e)}`);
190
- }
191
- }
192
- if (block.target) {
193
- const selector = sinthCompToSelector(block.target);
194
- css = `${selector} {\n${css}\n}`;
195
- }
196
- // scope (except it is global)
197
- if (!block.global)
198
- css = scopeCSS(css, hash);
199
- return css;
200
- }
201
- function scopeCSS(css, hash) {
202
- return processRules(css, `[data-s="${hash}"]`);
203
- }
204
- function processRules(css, attr) {
205
- let out = "", i = 0;
206
- while (i < css.length) {
207
- if (/\s/.test(css[i])) {
208
- out += css[i++];
209
- continue;
210
- }
211
- if (css[i] === "/" && css[i + 1] === "*") {
212
- const end = css.indexOf("*/", i + 2);
213
- if (end === -1) {
214
- out += css.substring(i);
215
- break;
216
- }
217
- out += css.substring(i, end + 2);
218
- i = end + 2;
219
- continue;
220
- }
221
- const braceIdx = findCSSBrace(css, i);
222
- if (braceIdx === -1) {
223
- out += css.substring(i);
224
- break;
225
- }
226
- const selector = css.substring(i, braceIdx).trim();
227
- const { content, end } = extractCSSBlock(css, braceIdx);
228
- if (/^@(-webkit-|-moz-)?keyframes/.test(selector)) {
229
- out += `${selector} {${content}}\n`;
230
- }
231
- else if (/^@(media|supports|layer|container)/.test(selector)) {
232
- out += `${selector} {\n${processRules(content, attr)}\n}\n`;
233
- }
234
- else if (selector.startsWith("@")) {
235
- out += `${selector} {${content}}\n`;
236
- }
237
- else if (selector.length > 0) {
238
- out += `${scopeSelectors(selector, attr)} {${content}}\n`;
239
- }
240
- i = end;
241
- }
242
- return out;
243
- }
244
- function scopeSelectors(selList, attr) {
245
- return selList
246
- .split(",")
247
- .map(s => {
248
- s = s.trim();
249
- if (!s)
250
- return "";
251
- if (/^(html|body|:root)(\s|$|{|,)/.test(s))
252
- return s;
253
- const m = s.match(/^(.*?)((?::{1,2}[a-zA-Z-]+(?:\([^)]*\))?)+)$/);
254
- if (m && m[1].trim()) {
255
- return `${attr} ${m[1].trimEnd()}${m[2]}, ${m[1].trimEnd()}${attr}${m[2]}`;
256
- }
257
- return `${attr} ${s}, ${s}${attr}`;
258
- })
259
- .filter(Boolean)
260
- .join(",\n");
261
- }
262
- function findCSSBrace(css, from) {
263
- let i = from;
264
- while (i < css.length) {
265
- if (css[i] === '"' || css[i] === "'") {
266
- const q = css[i++];
267
- while (i < css.length && css[i] !== q) {
268
- if (css[i] === "\\")
269
- i++;
270
- i++;
271
- }
272
- i++;
273
- }
274
- else if (css[i] === "{") {
275
- return i;
276
- }
277
- else {
278
- i++;
279
- }
280
- }
281
- return -1;
282
- }
283
- function extractCSSBlock(css, openBrace) {
284
- let i = openBrace + 1, depth = 1;
285
- while (i < css.length && depth > 0) {
286
- if (css[i] === '"' || css[i] === "'") {
287
- const q = css[i++];
288
- while (i < css.length && css[i] !== q) {
289
- if (css[i] === "\\")
290
- i++;
291
- i++;
292
- }
293
- i++;
294
- }
295
- else if (css[i] === "/" && css[i + 1] === "*") {
296
- i += 2;
297
- while (i < css.length - 1 && !(css[i] === "*" && css[i + 1] === "/"))
298
- i++;
299
- i += 2;
300
- }
301
- else if (css[i] === "{") {
302
- depth++;
303
- i++;
304
- }
305
- else if (css[i] === "}") {
306
- depth--;
307
- if (depth > 0)
308
- i++;
309
- else
310
- break;
311
- }
312
- else {
313
- i++;
314
- }
315
- }
316
- return { content: css.substring(openBrace + 1, i), end: i + 1 };
317
- }
@@ -1,93 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- // Sinth Compiler
4
- Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.SinthWarning = exports.SinthError = exports.TT = void 0;
6
- var TT;
7
- (function (TT) {
8
- TT[TT["LBRACE"] = 0] = "LBRACE";
9
- TT[TT["RBRACE"] = 1] = "RBRACE";
10
- TT[TT["LPAREN"] = 2] = "LPAREN";
11
- TT[TT["RPAREN"] = 3] = "RPAREN";
12
- TT[TT["COLON"] = 4] = "COLON";
13
- TT[TT["COMMA"] = 5] = "COMMA";
14
- TT[TT["EQUALS"] = 6] = "EQUALS";
15
- TT[TT["DOT"] = 7] = "DOT";
16
- TT[TT["LBRACKET"] = 8] = "LBRACKET";
17
- TT[TT["RBRACKET"] = 9] = "RBRACKET";
18
- TT[TT["STRING"] = 10] = "STRING";
19
- TT[TT["NUMBER"] = 11] = "NUMBER";
20
- TT[TT["BOOL_TRUE"] = 12] = "BOOL_TRUE";
21
- TT[TT["BOOL_FALSE"] = 13] = "BOOL_FALSE";
22
- TT[TT["NULL_LIT"] = 14] = "NULL_LIT";
23
- TT[TT["RAW_BLOCK"] = 15] = "RAW_BLOCK";
24
- TT[TT["IDENT"] = 16] = "IDENT";
25
- TT[TT["KW_IMPORT"] = 17] = "KW_IMPORT";
26
- TT[TT["KW_AS"] = 18] = "KW_AS";
27
- TT[TT["KW_CSS"] = 19] = "KW_CSS";
28
- TT[TT["KW_COMPONENT"] = 20] = "KW_COMPONENT";
29
- TT[TT["KW_STYLE"] = 21] = "KW_STYLE";
30
- TT[TT["KW_SCRIPT"] = 22] = "KW_SCRIPT";
31
- TT[TT["KW_GLOBAL"] = 23] = "KW_GLOBAL";
32
- TT[TT["KW_PAGE"] = 24] = "KW_PAGE";
33
- TT[TT["KW_LANG"] = 25] = "KW_LANG";
34
- TT[TT["KW_CUSTOM_EL"] = 26] = "KW_CUSTOM_EL";
35
- TT[TT["KW_CUSTOM"] = 27] = "KW_CUSTOM";
36
- TT[TT["KW_IF"] = 28] = "KW_IF";
37
- TT[TT["KW_ELSE"] = 29] = "KW_ELSE";
38
- TT[TT["KW_FOR"] = 30] = "KW_FOR";
39
- TT[TT["KW_IN"] = 31] = "KW_IN";
40
- TT[TT["KW_REMOVE"] = 32] = "KW_REMOVE";
41
- TT[TT["KW_FUNCTION"] = 33] = "KW_FUNCTION";
42
- TT[TT["KW_RETURN"] = 34] = "KW_RETURN";
43
- TT[TT["OP_PLUS"] = 35] = "OP_PLUS";
44
- TT[TT["OP_MINUS"] = 36] = "OP_MINUS";
45
- TT[TT["OP_STAR"] = 37] = "OP_STAR";
46
- TT[TT["OP_SLASH"] = 38] = "OP_SLASH";
47
- TT[TT["OP_MOD"] = 39] = "OP_MOD";
48
- TT[TT["OP_SEMI"] = 40] = "OP_SEMI";
49
- TT[TT["OP_LT"] = 41] = "OP_LT";
50
- TT[TT["OP_GT"] = 42] = "OP_GT";
51
- TT[TT["OP_NEQ"] = 43] = "OP_NEQ";
52
- TT[TT["OP_EQEQ"] = 44] = "OP_EQEQ";
53
- TT[TT["OP_LTEQ"] = 45] = "OP_LTEQ";
54
- TT[TT["OP_GTEQ"] = 46] = "OP_GTEQ";
55
- TT[TT["OP_ARROW"] = 47] = "OP_ARROW";
56
- TT[TT["OP_NOT"] = 48] = "OP_NOT";
57
- TT[TT["EOF"] = 49] = "EOF";
58
- })(TT || (exports.TT = TT = {}));
59
- class SinthError extends Error {
60
- constructor(rawMsg, loc, sourceLine) {
61
- super(SinthError.buildMessage(rawMsg, loc, sourceLine));
62
- this.rawMsg = rawMsg;
63
- this.loc = loc;
64
- this.sourceLine = sourceLine;
65
- Object.setPrototypeOf(this, SinthError.prototype);
66
- }
67
- static buildMessage(msg, loc, sourceLine) {
68
- let s = `Error: ${msg}`;
69
- if (loc) {
70
- s += `\n at: ${loc.file} (line ${loc.line}, col ${loc.col})`;
71
- if (sourceLine !== undefined) {
72
- const lineNum = String(loc.line).padStart(4);
73
- const pointer = " ".repeat(Math.max(0, loc.col - 1)) + "^";
74
- s += `\n${lineNum} | ${sourceLine}\n | ${pointer}`;
75
- }
76
- }
77
- return s;
78
- }
79
- withSource(lines) {
80
- if (!this.loc || this.sourceLine !== undefined)
81
- return this;
82
- const line = lines[this.loc.line - 1] ?? "";
83
- return new SinthError(this.rawMsg, this.loc, line);
84
- }
85
- }
86
- exports.SinthError = SinthError;
87
- class SinthWarning {
88
- static emit(msg, loc) {
89
- const where = loc ? `\n at: ${loc.file}:${loc.line}` : "";
90
- process.stderr.write(`\x1b[33mWarning:\x1b[0m ${msg}${where}\n`);
91
- }
92
- }
93
- exports.SinthWarning = SinthWarning;
package/dist/resolver.js DELETED
@@ -1,175 +0,0 @@
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.IMPORT_STACK = void 0;
37
- exports.parseFile = parseFile;
38
- exports.resolveImports = resolveImports;
39
- exports.resolveRelative = resolveRelative;
40
- exports.resolveLibrary = resolveLibrary;
41
- exports.resolveSinthPath = resolveSinthPath;
42
- const fs = __importStar(require("fs"));
43
- const path = __importStar(require("path"));
44
- const types_1 = require("./core/types");
45
- const lexer_1 = require("./core/lexer");
46
- const parser_1 = require("./core/parser");
47
- const builtins_1 = require("./core/builtins");
48
- exports.IMPORT_STACK = [];
49
- function parseFile(filePath) {
50
- if (!fs.existsSync(filePath))
51
- throw new types_1.SinthError(`File not found: ${filePath}`);
52
- const src = fs.readFileSync(filePath, "utf-8");
53
- const srcLines = src.split("\n");
54
- try {
55
- const tokens = new lexer_1.Lexer(src, filePath).tokenize();
56
- return new parser_1.Parser(tokens, filePath).parse();
57
- }
58
- catch (e) {
59
- if (e instanceof types_1.SinthError)
60
- throw e.withSource(srcLines);
61
- throw e;
62
- }
63
- }
64
- function resolveImports(file, cfg, visited = new Set()) {
65
- const allDefs = new Map();
66
- const customEls = new Map();
67
- const cssLinks = [];
68
- const jsLinks = [];
69
- for (const def of file.defs) {
70
- if (builtins_1.BUILTIN_MAP[def.name]) {
71
- throw new types_1.SinthError(`'${def.name}' is a built-in Sinth component and cannot be redefined.`, def.loc);
72
- }
73
- if (allDefs.has(def.name))
74
- throw new types_1.SinthError(`Duplicate component definition '${def.name}'`, def.loc);
75
- allDefs.set(def.name, def);
76
- }
77
- for (const el of file.customEls) {
78
- customEls.set(el.sinthName, { tagName: el.tagName, params: el.params });
79
- }
80
- if (!file.isPage && file.meta.length > 0) {
81
- for (const m of file.meta) {
82
- types_1.SinthWarning.emit(`Metadata '${m.key}' in component file '${file.filePath}' has no effect.`, m.loc);
83
- }
84
- }
85
- for (const imp of file.imports) {
86
- if (imp.kind === "css") {
87
- const r = resolveRelative(imp.path, file.filePath);
88
- if (!cssLinks.includes(r))
89
- cssLinks.push(r);
90
- }
91
- else if (imp.kind === "js") {
92
- const src = resolveLibrary(imp.name, cfg);
93
- jsLinks.push({ src, attrs: {} });
94
- for (const libDir of cfg.libraryPaths) {
95
- const companion = path.join(libDir, imp.name + ".sinth");
96
- if (fs.existsSync(companion) && !visited.has(companion)) {
97
- visited.add(companion);
98
- exports.IMPORT_STACK.push(companion);
99
- const sub = resolveImports(parseFile(companion), cfg, visited);
100
- exports.IMPORT_STACK.pop();
101
- for (const [n, d] of sub.allDefs)
102
- allDefs.set(n, d);
103
- for (const [n, e] of sub.customEls)
104
- customEls.set(n, e);
105
- }
106
- }
107
- }
108
- else if (imp.kind === "sinth") {
109
- const resolved = resolveSinthPath(imp.path, file.filePath, cfg);
110
- if (exports.IMPORT_STACK.includes(resolved)) {
111
- throw new types_1.SinthError(`Circular import: ${[...exports.IMPORT_STACK, resolved].join(" → ")}`);
112
- }
113
- if (visited.has(resolved))
114
- continue;
115
- visited.add(resolved);
116
- exports.IMPORT_STACK.push(resolved);
117
- const imported = parseFile(resolved);
118
- exports.IMPORT_STACK.pop();
119
- const sub = resolveImports(imported, cfg, visited);
120
- for (const [name, def] of sub.allDefs) {
121
- if (allDefs.has(name))
122
- throw new types_1.SinthError(`Component '${name}' defined in multiple imported files.`);
123
- allDefs.set(name, def);
124
- }
125
- for (const [n, e] of sub.customEls)
126
- customEls.set(n, e);
127
- for (const l of sub.cssLinks)
128
- if (!cssLinks.includes(l))
129
- cssLinks.push(l);
130
- for (const j of sub.jsLinks)
131
- jsLinks.push(j);
132
- }
133
- }
134
- return { allDefs, customEls, cssLinks, jsLinks };
135
- }
136
- function resolveRelative(p, fromFile) {
137
- if (p.startsWith("./") || p.startsWith("../"))
138
- return path.resolve(path.dirname(fromFile), p);
139
- return p;
140
- }
141
- function resolveLibrary(name, cfg) {
142
- const base = name.endsWith(".js") ? name : name + ".js";
143
- for (const libDir of cfg.libraryPaths) {
144
- const c = path.join(libDir, base);
145
- if (fs.existsSync(c))
146
- return c;
147
- }
148
- return `/libraries/${base}`;
149
- }
150
- function resolveSinthPath(p, fromFile, cfg) {
151
- if (p.startsWith("./") || p.startsWith("../")) {
152
- const r = path.resolve(path.dirname(fromFile), p);
153
- if (fs.existsSync(r))
154
- return r;
155
- const w = r.endsWith(".sinth") ? "" : r + ".sinth";
156
- if (w && fs.existsSync(w))
157
- return w;
158
- throw new types_1.SinthError(`Cannot resolve import '${p}' from '${fromFile}'`);
159
- }
160
- const relToFile = path.resolve(path.dirname(fromFile), p);
161
- if (fs.existsSync(relToFile))
162
- return relToFile;
163
- const relToFileExt = relToFile.endsWith(".sinth") ? relToFile : relToFile + ".sinth";
164
- if (fs.existsSync(relToFileExt))
165
- return relToFileExt;
166
- for (const libDir of cfg.libraryPaths) {
167
- const c1 = path.join(libDir, p);
168
- if (fs.existsSync(c1))
169
- return c1;
170
- const c2 = c1.endsWith(".sinth") ? c1 : c1 + ".sinth";
171
- if (fs.existsSync(c2))
172
- return c2;
173
- }
174
- throw new types_1.SinthError(`Cannot resolve import '${p}'\n Tried: ${relToFileExt}\n Library paths: ${cfg.libraryPaths.join(", ")}`);
175
- }