kuza-lang 0.4.0 → 0.5.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/README.md +118 -88
- package/dist/ask.js +108 -0
- package/dist/config.js +56 -0
- package/dist/index.js +345 -183
- package/dist/scaffold.js +82 -0
- package/package.json +5 -2
- package/scripts/postinstall.mjs +39 -0
- package/templates/START.md +133 -0
- package/templates/index.html +19 -0
- package/templates/main-script.kuza +14 -0
- package/templates/main.kuza +36 -0
- package/templates/public/favicon.svg +4 -0
package/dist/index.js
CHANGED
|
@@ -2,22 +2,41 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* ТОЧКА ВХОДА CLI.
|
|
4
4
|
*
|
|
5
|
-
* kuza
|
|
6
|
-
* kuza
|
|
7
|
-
* kuza
|
|
8
|
-
* kuza build
|
|
9
|
-
* kuza
|
|
10
|
-
* kuza
|
|
11
|
-
* kuza
|
|
12
|
-
* kuza
|
|
5
|
+
* kuza / kuza repl консоль
|
|
6
|
+
* kuza new <dir> новый проект (alias: init, create)
|
|
7
|
+
* kuza start / dev localhost
|
|
8
|
+
* kuza build dist/
|
|
9
|
+
* kuza check проверка без запуска
|
|
10
|
+
* kuza serve server.kuza backend
|
|
11
|
+
* kuza ai "вопрос" --file ... ИИ, который читает файлы проекта
|
|
12
|
+
* kuza help справка
|
|
13
13
|
*/
|
|
14
|
-
import { existsSync, readFileSync, watchFile, writeFileSync } from "node:fs";
|
|
15
|
-
import { basename, dirname, extname, join, resolve } from "node:path";
|
|
16
|
-
import {
|
|
14
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, watchFile, writeFileSync, } from "node:fs";
|
|
15
|
+
import { basename, dirname, extname, join, relative, resolve } from "node:path";
|
|
16
|
+
import { createServer } from "node:http";
|
|
17
|
+
import { FILE_EXT, NAME, VERSION, compile, formatDiagnostic, run } from "kuza-core";
|
|
18
|
+
import { applyBuildHooks, applyCompileHooks, applyRunHooks, loadProjectConfig, } from "./config.js";
|
|
19
|
+
import { runAiQuestion } from "./ask.js";
|
|
17
20
|
import { startRepl } from "./repl.js";
|
|
18
21
|
import { t } from "./i18n.js";
|
|
19
22
|
import { bold, code, danger, dim, primary, printBanner, success, warning, } from "./ui.js";
|
|
23
|
+
import { scaffoldProject } from "./scaffold.js";
|
|
20
24
|
const argv = process.argv.slice(2);
|
|
25
|
+
let cachedConfig;
|
|
26
|
+
const MIME = {
|
|
27
|
+
".html": "text/html; charset=utf-8",
|
|
28
|
+
".js": "text/javascript; charset=utf-8",
|
|
29
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
30
|
+
".css": "text/css; charset=utf-8",
|
|
31
|
+
".json": "application/json; charset=utf-8",
|
|
32
|
+
".svg": "image/svg+xml",
|
|
33
|
+
".png": "image/png",
|
|
34
|
+
".jpg": "image/jpeg",
|
|
35
|
+
".jpeg": "image/jpeg",
|
|
36
|
+
".ico": "image/x-icon",
|
|
37
|
+
".woff2": "font/woff2",
|
|
38
|
+
".txt": "text/plain; charset=utf-8",
|
|
39
|
+
};
|
|
21
40
|
function printEntry(entry) {
|
|
22
41
|
switch (entry.type) {
|
|
23
42
|
case "error":
|
|
@@ -39,34 +58,52 @@ function usage() {
|
|
|
39
58
|
console.log(bold(`${NAME} ${VERSION}`) + dim(` — ${t("running")} ${NAME}-программы`));
|
|
40
59
|
console.log("");
|
|
41
60
|
console.log(` ${primary("kuza")} ${dim("открыть консоль (REPL)")}`);
|
|
42
|
-
console.log(` ${primary("kuza")}
|
|
43
|
-
console.log(` ${primary("kuza")}
|
|
44
|
-
console.log(` ${primary("kuza")} build
|
|
45
|
-
console.log(` ${primary("kuza")}
|
|
46
|
-
console.log(` ${primary("kuza")}
|
|
47
|
-
console.log(` ${primary("kuza")}
|
|
61
|
+
console.log(` ${primary("kuza")} new my-site ${dim("создать сайт в ./my-site")}`);
|
|
62
|
+
console.log(` ${primary("kuza")} start ${dim("localhost (алиас: dev)")}`);
|
|
63
|
+
console.log(` ${primary("kuza")} build ${dim("собрать сайт в dist/")}`);
|
|
64
|
+
console.log(` ${primary("kuza")} check ${dim("проверить все .kuza-файлы")}`);
|
|
65
|
+
console.log(` ${primary("kuza")} serve ${ex} ${dim("запустить HTTP-сервер")}`);
|
|
66
|
+
console.log(` ${primary("kuza")} ai "вопрос" ${dim("ИИ, который читает файлы проекта")}`);
|
|
67
|
+
console.log(` ${primary("kuza")} run ${ex} ${dim("выполнить файл")}`);
|
|
68
|
+
console.log(` ${primary("kuza")} build ${ex} ${dim("собрать консольную программу")}`);
|
|
48
69
|
console.log(` ${primary("kuza")} help ${dim("эта справка")}`);
|
|
49
70
|
console.log("");
|
|
50
|
-
console.log(dim("
|
|
71
|
+
console.log(dim("Первый сайт: ") + code("npm install kuza-lang && npm run dev"));
|
|
72
|
+
console.log(dim("Документация: ") + code("START.md") + dim(" после установки"));
|
|
51
73
|
console.log("");
|
|
52
74
|
}
|
|
53
75
|
function fail(text) {
|
|
54
76
|
console.error(danger(text));
|
|
55
77
|
process.exitCode = 1;
|
|
56
78
|
}
|
|
57
|
-
|
|
79
|
+
async function config() {
|
|
80
|
+
if (!cachedConfig)
|
|
81
|
+
cachedConfig = await loadProjectConfig(process.cwd());
|
|
82
|
+
for (const warningText of cachedConfig.warnings)
|
|
83
|
+
console.log(warning(warningText));
|
|
84
|
+
return cachedConfig;
|
|
85
|
+
}
|
|
86
|
+
/** Читать use "./helpers.kuza" относительно запускаемого файла. */
|
|
58
87
|
function moduleResolver(entryPath) {
|
|
59
88
|
return (specifier) => readFileSync(resolve(dirname(entryPath), specifier), "utf8");
|
|
60
89
|
}
|
|
90
|
+
function compileSource(source, filename, cfg, standalone = true) {
|
|
91
|
+
const prepared = applyCompileHooks(cfg, { source, filename });
|
|
92
|
+
return compile(prepared, {
|
|
93
|
+
standalone,
|
|
94
|
+
filename,
|
|
95
|
+
resolveModule: moduleResolver(filename),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
61
98
|
async function runFile(file) {
|
|
62
99
|
const path = resolve(file);
|
|
63
100
|
if (!existsSync(path)) {
|
|
64
101
|
fail(`${t("fileNotFound")}: ${file}`);
|
|
65
102
|
return;
|
|
66
103
|
}
|
|
104
|
+
const cfg = await config();
|
|
67
105
|
const source = readFileSync(path, "utf8");
|
|
68
|
-
const
|
|
69
|
-
const compiled = compile(source, compileOptions);
|
|
106
|
+
const compiled = compileSource(source, path, cfg);
|
|
70
107
|
if (!compiled.ok) {
|
|
71
108
|
console.error(danger(`${t("compileError")}: ${basename(path)}`));
|
|
72
109
|
console.error(danger(formatDiagnostic(compiled.errors[0], source)));
|
|
@@ -74,47 +111,128 @@ async function runFile(file) {
|
|
|
74
111
|
return;
|
|
75
112
|
}
|
|
76
113
|
console.log(dim(`${t("running")} ${basename(path)}`));
|
|
77
|
-
const result = await run(source,
|
|
114
|
+
const result = (await run(source, {
|
|
115
|
+
filename: path,
|
|
116
|
+
resolveModule: moduleResolver(path),
|
|
117
|
+
}));
|
|
118
|
+
applyRunHooks(cfg, { result, filename: path });
|
|
78
119
|
for (const entry of result.output)
|
|
79
120
|
printEntry(entry);
|
|
80
121
|
process.exitCode = result.ok ? 0 : 1;
|
|
81
122
|
}
|
|
82
123
|
/**
|
|
83
|
-
*
|
|
84
|
-
*
|
|
85
|
-
* Каркас — обычный HTML, внутри body которого стоит метка `{main.kuza}`.
|
|
86
|
-
* Если каркаса нет, генерируем минимальный сами.
|
|
124
|
+
* Вставить скомпилированный код в index.html. Метка {main.kuza} — обычный
|
|
125
|
+
* HTML-комментарий/плейсхолдер, поэтому каркас остаётся нормальной страницей.
|
|
87
126
|
*/
|
|
88
|
-
function pageHtml(code,
|
|
89
|
-
const tag = `<script>\n${code}</script>`;
|
|
127
|
+
function pageHtml(code, dir, scriptName) {
|
|
128
|
+
const tag = `<script>\n// ${NAME} ${VERSION}: собрано из ${scriptName}. Правь .kuza-файл, а не этот файл.\n${code}</script>`;
|
|
90
129
|
const shellPath = join(dir, "index.html");
|
|
91
130
|
if (existsSync(shellPath)) {
|
|
92
|
-
|
|
93
|
-
const marker
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
131
|
+
let shell = readFileSync(shellPath, "utf8");
|
|
132
|
+
for (const marker of [`{${scriptName}}`, `{main${FILE_EXT}}`, "{kuza}"]) {
|
|
133
|
+
if (shell.includes(marker))
|
|
134
|
+
return shell.split(marker).join(tag);
|
|
135
|
+
}
|
|
136
|
+
if (shell.includes("</body>"))
|
|
137
|
+
return shell.replace("</body>", `${tag}\n</body>`);
|
|
138
|
+
return `${shell}\n${tag}\n`;
|
|
139
|
+
}
|
|
140
|
+
return `<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n<title>${NAME}</title>\n<script src="https://cdn.tailwindcss.com"></script>\n</head>\n<body>\n${tag}\n</body>\n</html>\n`;
|
|
141
|
+
}
|
|
142
|
+
const LIVE_RELOAD = '<script>(function(){let last=null;async function check(){try{const r=await fetch("/__kuza/reload?path="+encodeURIComponent(location.pathname),{cache:"no-store"});const d=await r.json();if(last!==null&&d.mtime!==last)location.reload();last=d.mtime;}catch(e){}}setInterval(check,700);check();})();</script>';
|
|
143
|
+
/** Все страницы проекта: главная + pages/*.kuza. */
|
|
144
|
+
function projectPages(dir) {
|
|
145
|
+
const pages = new Map();
|
|
146
|
+
for (const name of [`main${FILE_EXT}`, `index${FILE_EXT}`]) {
|
|
147
|
+
const path = join(dir, name);
|
|
148
|
+
if (existsSync(path)) {
|
|
149
|
+
pages.set("/", path);
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const pagesDir = join(dir, "pages");
|
|
154
|
+
if (existsSync(pagesDir)) {
|
|
155
|
+
for (const name of readdirSync(pagesDir)) {
|
|
156
|
+
if (!name.endsWith(FILE_EXT))
|
|
157
|
+
continue;
|
|
158
|
+
const route = name === `index${FILE_EXT}` ? "index" : name.slice(0, -FILE_EXT.length);
|
|
159
|
+
pages.set(`/${route}`, join(pagesDir, name));
|
|
100
160
|
}
|
|
101
|
-
return { html: `${shell}\n${tag}\n`, shell: "index.html" };
|
|
102
161
|
}
|
|
103
|
-
|
|
104
|
-
|
|
162
|
+
return pages;
|
|
163
|
+
}
|
|
164
|
+
function projectEntry(dir = process.cwd()) {
|
|
165
|
+
return projectPages(dir).get("/");
|
|
166
|
+
}
|
|
167
|
+
function relativeEntries(dir = process.cwd()) {
|
|
168
|
+
return [...projectPages(dir).entries()].map(([route, path]) => `${route} → ${relative(dir, path)}`);
|
|
169
|
+
}
|
|
170
|
+
function mtimeOf(path) {
|
|
171
|
+
try {
|
|
172
|
+
return statSync(path).mtimeMs;
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
return 0;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function startDevServer(file, portArg) {
|
|
179
|
+
const dir = file ? dirname(resolve(file)) : process.cwd();
|
|
180
|
+
const pages = projectPages(dir);
|
|
181
|
+
const cfg = await config();
|
|
182
|
+
const port = Number(portArg ?? process.env.PORT ?? 5173);
|
|
183
|
+
const server = createServer((request, response) => {
|
|
184
|
+
const urlPath = decodeURIComponent((request.url || "/").split("?")[0] || "/");
|
|
185
|
+
if (urlPath === "/__kuza/reload") {
|
|
186
|
+
const raw = (request.url || "").split("?")[1] || "";
|
|
187
|
+
const wanted = new URLSearchParams(raw).get("path") || "/";
|
|
188
|
+
const source = pages.get(wanted) ?? pages.get(wanted.replace(/\.html$/, "")) ?? pages.get("/");
|
|
189
|
+
response.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
190
|
+
response.end(JSON.stringify({ mtime: source ? mtimeOf(source) : 0 }));
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
const pageKey = urlPath.replace(/\.html$/, "");
|
|
194
|
+
const sourcePath = pages.get(pageKey) ?? (pageKey === "/" ? pages.get("/") : undefined);
|
|
195
|
+
if (sourcePath) {
|
|
196
|
+
const source = readFileSync(sourcePath, "utf8");
|
|
197
|
+
const compiled = compileSource(source, sourcePath, cfg);
|
|
198
|
+
if (!compiled.ok) {
|
|
199
|
+
response.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
|
|
200
|
+
response.end(formatDiagnostic(compiled.errors[0], source));
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const html = pageHtml(compiled.code, dir, basename(sourcePath)).replace("</body>", `${LIVE_RELOAD}\n</body>`);
|
|
204
|
+
response.writeHead(200, {
|
|
205
|
+
"content-type": "text/html; charset=utf-8",
|
|
206
|
+
"cache-control": "no-store",
|
|
207
|
+
});
|
|
208
|
+
response.end(html);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const asset = [resolve(dir, `.${urlPath}`), resolve(dir, "public", `.${urlPath}`)].find((candidate) => candidate.startsWith(dir) && existsSync(candidate) && statSync(candidate).isFile());
|
|
212
|
+
if (asset) {
|
|
213
|
+
response.writeHead(200, {
|
|
214
|
+
"content-type": MIME[extname(asset)] ?? "application/octet-stream",
|
|
215
|
+
});
|
|
216
|
+
response.end(readFileSync(asset));
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
|
|
220
|
+
response.end("Not found");
|
|
221
|
+
});
|
|
222
|
+
server.listen(port, "127.0.0.1", () => {
|
|
223
|
+
console.log(success(`Kuza dev server: http://localhost:${port}`));
|
|
224
|
+
console.log(dim("Страницы: " + relativeEntries(dir).join(", ")));
|
|
225
|
+
console.log(dim("Измени .kuza — браузер обновится сам. Ctrl+C — остановить."));
|
|
226
|
+
});
|
|
105
227
|
}
|
|
106
|
-
function buildFile(file, web) {
|
|
228
|
+
function buildFile(file, web, cfg, outputFile) {
|
|
107
229
|
const path = resolve(file);
|
|
108
230
|
if (!existsSync(path)) {
|
|
109
231
|
fail(`${t("fileNotFound")}: ${file}`);
|
|
110
232
|
return;
|
|
111
233
|
}
|
|
112
234
|
const source = readFileSync(path, "utf8");
|
|
113
|
-
const compiled =
|
|
114
|
-
standalone: true,
|
|
115
|
-
filename: path,
|
|
116
|
-
resolveModule: moduleResolver(path),
|
|
117
|
-
});
|
|
235
|
+
const compiled = compileSource(source, path, cfg);
|
|
118
236
|
if (!compiled.ok) {
|
|
119
237
|
console.error(danger(`${t("compileError")}: ${basename(path)}`));
|
|
120
238
|
console.error(danger(formatDiagnostic(compiled.errors[0], source)));
|
|
@@ -122,22 +240,69 @@ function buildFile(file, web) {
|
|
|
122
240
|
return;
|
|
123
241
|
}
|
|
124
242
|
const base = path.slice(0, path.length - extname(path).length);
|
|
125
|
-
const outPath = web ? `${base}.html` : `${base}.js
|
|
243
|
+
const outPath = outputFile ?? (web ? `${base}.html` : `${base}.js`);
|
|
244
|
+
mkdirSync(dirname(outPath), { recursive: true });
|
|
245
|
+
const code = applyBuildHooks(cfg, { code: compiled.code, filename: path, output: outPath });
|
|
126
246
|
if (web) {
|
|
127
|
-
const page = pageHtml(
|
|
128
|
-
writeFileSync(outPath, page
|
|
247
|
+
const page = pageHtml(code, dirname(path), basename(path));
|
|
248
|
+
writeFileSync(outPath, page, "utf8");
|
|
129
249
|
console.log(success(`✓ ${t("built")} ${outPath}`));
|
|
130
|
-
|
|
131
|
-
console.log(dim(`Каркас: ${page.shell}`));
|
|
132
|
-
console.log(dim(`${t("openInBrowser")}: `) + code(`"${basename(outPath)}"`));
|
|
250
|
+
console.log(dim(`${t("openInBrowser")}: `) + code2(`"${relative(process.cwd(), outPath)}"`));
|
|
133
251
|
return;
|
|
134
252
|
}
|
|
135
|
-
writeFileSync(outPath,
|
|
253
|
+
writeFileSync(outPath, code, "utf8");
|
|
136
254
|
console.log(success(`✓ ${t("built")} ${outPath}`));
|
|
137
|
-
console.log(dim(`${t("runWithNode")}: `) +
|
|
255
|
+
console.log(dim(`${t("runWithNode")}: `) + code2(`node "${relative(process.cwd(), outPath)}"`));
|
|
256
|
+
}
|
|
257
|
+
function code2(value) {
|
|
258
|
+
return code(value);
|
|
259
|
+
}
|
|
260
|
+
function copyDir(from, to) {
|
|
261
|
+
if (!existsSync(from))
|
|
262
|
+
return;
|
|
263
|
+
mkdirSync(to, { recursive: true });
|
|
264
|
+
for (const entry of readdirSync(from)) {
|
|
265
|
+
const source = join(from, entry);
|
|
266
|
+
const target = join(to, entry);
|
|
267
|
+
if (statSync(source).isDirectory())
|
|
268
|
+
copyDir(source, target);
|
|
269
|
+
else
|
|
270
|
+
copyFileSync(source, target);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
async function buildProject() {
|
|
274
|
+
const dir = process.cwd();
|
|
275
|
+
const cfg = await config();
|
|
276
|
+
const pages = projectPages(dir);
|
|
277
|
+
if (pages.size === 0) {
|
|
278
|
+
fail(`Не найден main${FILE_EXT}. Запусти kuza new.`);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
const dist = join(dir, "dist");
|
|
282
|
+
mkdirSync(dist, { recursive: true });
|
|
283
|
+
for (const [route, sourcePath] of pages) {
|
|
284
|
+
const source = readFileSync(sourcePath, "utf8");
|
|
285
|
+
const compiled = compileSource(source, sourcePath, cfg);
|
|
286
|
+
if (!compiled.ok) {
|
|
287
|
+
console.error(danger(`${t("compileError")}: ${relative(dir, sourcePath)}`));
|
|
288
|
+
console.error(danger(formatDiagnostic(compiled.errors[0], source)));
|
|
289
|
+
process.exitCode = 1;
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
const output = route === "/" ? join(dist, "index.html") : join(dist, route, "index.html");
|
|
293
|
+
mkdirSync(dirname(output), { recursive: true });
|
|
294
|
+
const js = applyBuildHooks(cfg, {
|
|
295
|
+
code: compiled.code,
|
|
296
|
+
filename: sourcePath,
|
|
297
|
+
output,
|
|
298
|
+
});
|
|
299
|
+
writeFileSync(output, pageHtml(js, dir, basename(sourcePath)), "utf8");
|
|
300
|
+
console.log(success(`✓ ${output}`));
|
|
301
|
+
}
|
|
302
|
+
copyDir(join(dir, "public"), dist);
|
|
303
|
+
console.log(dim("Готово. Открой dist/index.html или запусти kuza start."));
|
|
138
304
|
}
|
|
139
|
-
|
|
140
|
-
function watchProject(file, web) {
|
|
305
|
+
function watchProject(file, web, cfg) {
|
|
141
306
|
const path = resolve(file);
|
|
142
307
|
if (!existsSync(path)) {
|
|
143
308
|
fail(`${t("fileNotFound")}: ${file}`);
|
|
@@ -145,7 +310,7 @@ function watchProject(file, web) {
|
|
|
145
310
|
}
|
|
146
311
|
const rebuild = () => {
|
|
147
312
|
process.exitCode = 0;
|
|
148
|
-
buildFile(file, web);
|
|
313
|
+
buildFile(file, web, cfg);
|
|
149
314
|
};
|
|
150
315
|
rebuild();
|
|
151
316
|
watchFile(path, { interval: 400 }, (current, previous) => {
|
|
@@ -156,127 +321,76 @@ function watchProject(file, web) {
|
|
|
156
321
|
});
|
|
157
322
|
console.log(dim(t("watching")));
|
|
158
323
|
}
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
const
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
page >> "Мой сайт на ${NAME}";
|
|
191
|
-
|
|
192
|
-
body >> [
|
|
193
|
-
heading >> "Привет! Это сайт на ${NAME}";
|
|
194
|
-
para >> "Страница собирается из вложенных блоков, как в React, только без сборщика.";
|
|
195
|
-
|
|
196
|
-
row >> [
|
|
197
|
-
Card<"Первый">;
|
|
198
|
-
Card<"Второй">;
|
|
199
|
-
Card<"Третий">;
|
|
200
|
-
];
|
|
201
|
-
|
|
202
|
-
column >> [
|
|
203
|
-
heading >> "Счётчик: {count}";
|
|
204
|
-
button >> <"Прибавить", increase>;
|
|
205
|
-
button >> <"Сбросить", reset>;
|
|
206
|
-
];
|
|
207
|
-
|
|
208
|
-
field >> <"Как тебя зовут?", "name">;
|
|
209
|
-
button >> <"Поздороваться", greet>;
|
|
210
|
-
|
|
211
|
-
?greeting != "" >> [
|
|
212
|
-
card >> [ para >> greeting; ];
|
|
213
|
-
];
|
|
214
|
-
];
|
|
215
|
-
|
|
216
|
-
render;
|
|
217
|
-
];
|
|
218
|
-
|
|
219
|
-
func increase<> >> [
|
|
220
|
-
count = count + 1;
|
|
221
|
-
draw<>;
|
|
222
|
-
];
|
|
223
|
-
|
|
224
|
-
func reset<> >> [
|
|
225
|
-
count = 0;
|
|
226
|
-
draw<>;
|
|
227
|
-
];
|
|
228
|
-
|
|
229
|
-
func greet<> >> [
|
|
230
|
-
:name = fieldValue >> "name";
|
|
231
|
-
?len >> name > 0 >> [
|
|
232
|
-
greeting = "Привет, " + name + "!";
|
|
233
|
-
];
|
|
234
|
-
draw<>;
|
|
235
|
-
];
|
|
236
|
-
|
|
237
|
-
draw<>;
|
|
238
|
-
`;
|
|
239
|
-
/** Каркас страницы: почти пустой HTML с точкой вставки {main.kuza}. */
|
|
240
|
-
const SHELL_SAMPLE = `<!doctype html>
|
|
241
|
-
<html lang="ru">
|
|
242
|
-
<head>
|
|
243
|
-
<meta charset="utf-8">
|
|
244
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
245
|
-
<title>Мой сайт на ${NAME}</title>
|
|
246
|
-
</head>
|
|
247
|
-
<body>
|
|
248
|
-
<!-- Сюда попадёт собранный ${NAME}. Метку не удаляй. -->
|
|
249
|
-
{main${FILE_EXT}}
|
|
250
|
-
</body>
|
|
251
|
-
</html>
|
|
252
|
-
`;
|
|
253
|
-
function initProject(target, web) {
|
|
254
|
-
const dir = target ? resolve(target) : process.cwd();
|
|
255
|
-
const file = join(dir, `main${FILE_EXT}`);
|
|
256
|
-
const shellFile = join(dir, "index.html");
|
|
257
|
-
if (existsSync(file)) {
|
|
258
|
-
console.log(warning(`${t("initExists")}: ${file}`));
|
|
259
|
-
return;
|
|
324
|
+
async function checkProject() {
|
|
325
|
+
const dir = process.cwd();
|
|
326
|
+
const cfg = await config();
|
|
327
|
+
const files = [];
|
|
328
|
+
const collect = (folder) => {
|
|
329
|
+
if (!existsSync(folder))
|
|
330
|
+
return;
|
|
331
|
+
for (const name of readdirSync(folder)) {
|
|
332
|
+
const path = join(folder, name);
|
|
333
|
+
if (statSync(path).isDirectory())
|
|
334
|
+
collect(path);
|
|
335
|
+
else if (name.endsWith(FILE_EXT))
|
|
336
|
+
files.push(path);
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
collect(dir);
|
|
340
|
+
const filtered = files.filter((path) => !path.includes(`${dirname(dir)}\\`));
|
|
341
|
+
if (filtered.length === 0)
|
|
342
|
+
filtered.push(...projectPages(dir).values());
|
|
343
|
+
let errors = 0;
|
|
344
|
+
for (const path of filtered) {
|
|
345
|
+
const source = readFileSync(path, "utf8");
|
|
346
|
+
const result = compileSource(source, path, cfg, false);
|
|
347
|
+
if (result.ok) {
|
|
348
|
+
console.log(success(`✓ ${relative(dir, path)}`));
|
|
349
|
+
}
|
|
350
|
+
else {
|
|
351
|
+
errors++;
|
|
352
|
+
console.error(danger(`✕ ${relative(dir, path)}`));
|
|
353
|
+
console.error(danger(formatDiagnostic(result.errors[0], source)));
|
|
354
|
+
}
|
|
260
355
|
}
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
356
|
+
console.log(errors === 0 ? success("✓ Всё компилируется") : danger(`Ошибок: ${errors}`));
|
|
357
|
+
if (errors > 0)
|
|
358
|
+
process.exitCode = 1;
|
|
359
|
+
}
|
|
360
|
+
async function serveCommand(file) {
|
|
361
|
+
const path = resolve(file);
|
|
362
|
+
if (!existsSync(path)) {
|
|
363
|
+
fail(`${t("fileNotFound")}: ${file}`);
|
|
364
|
+
return;
|
|
265
365
|
}
|
|
266
|
-
|
|
267
|
-
|
|
366
|
+
const cfg = await config();
|
|
367
|
+
const source = readFileSync(path, "utf8");
|
|
368
|
+
const compiled = compileSource(source, path, cfg);
|
|
369
|
+
if (!compiled.ok) {
|
|
370
|
+
console.error(danger(formatDiagnostic(compiled.errors[0], source)));
|
|
371
|
+
process.exitCode = 1;
|
|
268
372
|
return;
|
|
269
373
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
374
|
+
const result = await run(source, { filename: path, resolveModule: moduleResolver(path) });
|
|
375
|
+
for (const entry of result.output)
|
|
376
|
+
printEntry(entry);
|
|
377
|
+
applyRunHooks(cfg, { result, filename: path });
|
|
378
|
+
// Даём динамическому import("node:http") момент на запуск слушателя.
|
|
379
|
+
await new Promise((done) => setTimeout(done, 100));
|
|
380
|
+
}
|
|
381
|
+
function scaffoldCommand(target, web, force) {
|
|
382
|
+
const dir = target ? resolve(target) : process.cwd();
|
|
383
|
+
const created = scaffoldProject(dir, { scriptOnly: !web, force });
|
|
384
|
+
if (created.length === 0) {
|
|
385
|
+
console.log(warning("Файлы уже есть — ничего не перезаписано."));
|
|
386
|
+
return;
|
|
273
387
|
}
|
|
274
|
-
console.log(
|
|
275
|
-
|
|
388
|
+
console.log(success(`✓ Создано: ${created.join(", ")}`));
|
|
389
|
+
console.log(dim("Дальше: ") + code("cd " + relative(process.cwd(), dir) + " && npm install && npm run dev"));
|
|
276
390
|
}
|
|
277
391
|
async function main() {
|
|
278
392
|
const [first, ...rest] = argv;
|
|
279
|
-
if (!first) {
|
|
393
|
+
if (!first || first === "repl") {
|
|
280
394
|
printBanner();
|
|
281
395
|
await startRepl();
|
|
282
396
|
return;
|
|
@@ -289,22 +403,74 @@ async function main() {
|
|
|
289
403
|
usage();
|
|
290
404
|
return;
|
|
291
405
|
}
|
|
292
|
-
if (first === "
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
406
|
+
if (first === "new" || first === "create" || first === "init") {
|
|
407
|
+
scaffoldCommand(rest.find((arg) => !arg.startsWith("--")), !rest.includes("--script"), rest.includes("--force"));
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
if (first === "start" || first === "dev") {
|
|
411
|
+
const target = rest.find((arg) => !arg.startsWith("--") && !arg.startsWith("--port="));
|
|
412
|
+
const portArg = rest.find((arg) => arg.startsWith("--port="))?.slice("--port=".length);
|
|
413
|
+
const file = target ?? projectEntry();
|
|
414
|
+
if (!file && !target)
|
|
415
|
+
return fail(`Не найден main${FILE_EXT}. Запусти kuza new.`);
|
|
416
|
+
await startDevServer(file, portArg);
|
|
298
417
|
return;
|
|
299
418
|
}
|
|
300
419
|
if (first === "build") {
|
|
301
|
-
const web = rest.includes("--web");
|
|
302
420
|
const target = rest.find((arg) => !arg.startsWith("--"));
|
|
303
421
|
if (!target) {
|
|
304
|
-
|
|
422
|
+
await buildProject();
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
await buildFile(target, rest.includes("--web"), await config());
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
if (first === "check" || first === "doctor") {
|
|
429
|
+
await checkProject();
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
if (first === "serve") {
|
|
433
|
+
const target = rest.find((arg) => !arg.startsWith("--")) || projectEntry();
|
|
434
|
+
if (!target)
|
|
435
|
+
return fail(`Укажи серверный файл: kuza serve server${FILE_EXT}`);
|
|
436
|
+
await serveCommand(target);
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
if (first === "ai" || first === "ask") {
|
|
440
|
+
const files = [];
|
|
441
|
+
const words = [];
|
|
442
|
+
for (let index = 0; index < rest.length; index++) {
|
|
443
|
+
const arg = rest[index];
|
|
444
|
+
if (arg === "--file" || arg === "-f") {
|
|
445
|
+
const next = rest[++index];
|
|
446
|
+
if (next)
|
|
447
|
+
files.push(next);
|
|
448
|
+
}
|
|
449
|
+
else if (!arg.startsWith("--")) {
|
|
450
|
+
words.push(arg);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
if (words.length === 0) {
|
|
454
|
+
fail('Спроси что-нибудь: kuza ai "объясни main.kuza"');
|
|
305
455
|
return;
|
|
306
456
|
}
|
|
307
|
-
|
|
457
|
+
await runAiQuestion(words.join(" "), files);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (first === "docs") {
|
|
461
|
+
const start = join(process.cwd(), "START.md");
|
|
462
|
+
if (existsSync(start))
|
|
463
|
+
console.log(start);
|
|
464
|
+
else
|
|
465
|
+
console.log("https://github.com/kuza-lang/kuza/blob/main/docs/commands.md");
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
if (first === "run") {
|
|
469
|
+
if (!rest[0]) {
|
|
470
|
+
fail(`Укажи файл: ${NAME.toLowerCase()} run main${FILE_EXT}`);
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
await runFile(rest[0]);
|
|
308
474
|
return;
|
|
309
475
|
}
|
|
310
476
|
if (first === "watch") {
|
|
@@ -314,11 +480,7 @@ async function main() {
|
|
|
314
480
|
fail(`Укажи файл: ${NAME.toLowerCase()} watch main${FILE_EXT}`);
|
|
315
481
|
return;
|
|
316
482
|
}
|
|
317
|
-
watchProject(target, web);
|
|
318
|
-
return;
|
|
319
|
-
}
|
|
320
|
-
if (first === "init") {
|
|
321
|
-
initProject(rest.find((arg) => !arg.startsWith("--")), rest.includes("--web"));
|
|
483
|
+
watchProject(target, web, await config());
|
|
322
484
|
return;
|
|
323
485
|
}
|
|
324
486
|
if (first.endsWith(FILE_EXT)) {
|