jskelet 0.2.5 → 0.3.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.
Files changed (106) hide show
  1. package/AGENTS.md +132 -132
  2. package/CHANGELOG.md +408 -383
  3. package/LICENSE +21 -21
  4. package/bin/jskelet.mjs +103 -103
  5. package/docs/01-baslangic.md +285 -285
  6. package/docs/02-mimari.md +293 -287
  7. package/docs/03-routing.md +486 -480
  8. package/docs/04-render-ve-sablonlar.md +490 -490
  9. package/docs/05-islands.md +482 -482
  10. package/docs/06-cache.md +1231 -1209
  11. package/docs/07-yapilandirma.md +44 -21
  12. package/docs/08-build.md +366 -366
  13. package/docs/09-dev-araclari.md +335 -335
  14. package/docs/10-dagitim.md +329 -329
  15. package/docs/11-tasima.md +1 -0
  16. package/docs/12-panel-ve-oturum.md +384 -384
  17. package/docs/README.md +105 -105
  18. package/docs/en/01-getting-started.md +292 -292
  19. package/docs/en/02-architecture.md +311 -305
  20. package/docs/en/03-routing.md +503 -497
  21. package/docs/en/04-rendering.md +504 -504
  22. package/docs/en/05-islands.md +492 -492
  23. package/docs/en/06-caching.md +1197 -1198
  24. package/docs/en/07-configuration.md +1009 -986
  25. package/docs/en/08-build.md +383 -383
  26. package/docs/en/09-dev-tools.md +342 -342
  27. package/docs/en/10-deployment.md +332 -332
  28. package/docs/en/11-migration.md +360 -359
  29. package/docs/en/12-dashboards-and-sessions.md +392 -392
  30. package/docs/en/README.md +112 -112
  31. package/package.json +102 -102
  32. package/src/build/ensure-build.mjs +15 -15
  33. package/src/build/paths.mjs +143 -143
  34. package/src/build/resolve-peer.mjs +36 -36
  35. package/src/build/tasks/client.mjs +268 -268
  36. package/src/build/tasks/css.mjs +124 -124
  37. package/src/build/tasks/fonts.mjs +146 -146
  38. package/src/build/tasks/icons.mjs +224 -224
  39. package/src/build/tasks/images.mjs +244 -244
  40. package/src/build/tasks/precompress.mjs +78 -78
  41. package/src/client/{cache-panel → admin}/i18n.js +764 -670
  42. package/src/client/{cache-panel → admin}/login.html +74 -74
  43. package/src/client/{cache-panel → admin}/panel.css +809 -756
  44. package/src/client/admin/panel.html +495 -0
  45. package/src/client/{cache-panel → admin}/panel.js +1251 -915
  46. package/src/client/devtools/report.html +185 -185
  47. package/src/client/devtools/report.js +725 -725
  48. package/src/client/dom.js +95 -95
  49. package/src/client/form.js +192 -192
  50. package/src/client/index.js +35 -35
  51. package/src/client/registry.js +297 -297
  52. package/src/client/safe-image.js +91 -91
  53. package/src/client/store.js +36 -36
  54. package/src/client/swap.js +188 -188
  55. package/src/config/defaults.js +16 -7
  56. package/src/config/index.js +38 -22
  57. package/src/config/pattern.js +107 -107
  58. package/src/http/control-flow.js +71 -71
  59. package/src/http/cookies.js +257 -257
  60. package/src/http/request-cache.js +46 -46
  61. package/src/http/request-context.js +162 -162
  62. package/src/index.js +83 -83
  63. package/src/init.mjs +221 -221
  64. package/src/log.mjs +58 -0
  65. package/src/runtime/alias-hooks.mjs +119 -119
  66. package/src/runtime/register.mjs +4 -4
  67. package/src/server/admin/actions.js +229 -0
  68. package/src/server/admin/auth.js +125 -0
  69. package/src/server/admin/event-log.js +151 -0
  70. package/src/server/admin/gate.js +209 -0
  71. package/src/server/admin/inventory.js +188 -0
  72. package/src/server/admin/mount.js +56 -0
  73. package/src/server/admin/router.js +216 -0
  74. package/src/server/admin/snapshot.js +241 -0
  75. package/src/server/assets.js +147 -147
  76. package/src/server/cache-deps.js +42 -42
  77. package/src/server/cloudflare.js +607 -607
  78. package/src/server/create-app.js +295 -291
  79. package/src/server/data-cache.js +462 -462
  80. package/src/server/dev/report.js +369 -369
  81. package/src/server/dev/socket.js +170 -170
  82. package/src/server/dev/version-check.mjs +139 -139
  83. package/src/server/html-cache.js +817 -817
  84. package/src/server/metadata.js +102 -102
  85. package/src/server/middleware/compression.js +205 -205
  86. package/src/server/middleware/csrf.js +134 -134
  87. package/src/server/middleware/dev-gate.js +62 -62
  88. package/src/server/middleware/headers.js +37 -37
  89. package/src/server/middleware/redirects.js +32 -32
  90. package/src/server/middleware/static-precompressed.js +100 -100
  91. package/src/server/middleware/trailing-slash.js +53 -0
  92. package/src/server/middleware/upstream-proxy.js +141 -141
  93. package/src/server/prewarm.js +601 -601
  94. package/src/server/redis.js +569 -569
  95. package/src/server/router.js +128 -128
  96. package/src/server/status-page.js +164 -164
  97. package/src/server/upstream-limiter.js +376 -376
  98. package/src/server/upstream-tracking.js +166 -166
  99. package/src/start.mjs +7 -7
  100. package/src/templates/layout.ejs +44 -44
  101. package/src/version.mjs +31 -31
  102. package/src/views/components/loader.js +85 -85
  103. package/src/views/helpers/html.js +102 -102
  104. package/src/views/helpers/tags.js +245 -245
  105. package/src/client/cache-panel/panel.html +0 -308
  106. package/src/server/cache-panel.js +0 -759
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Admin paneli Express router'ı.
3
+ */
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import express from "express";
7
+ import { FRAMEWORK_ROOT } from "../../config/index.js";
8
+ import {
9
+ ACTION_HEADER,
10
+ authenticated,
11
+ clearSessionCookie,
12
+ createSession,
13
+ destroySession,
14
+ passwordMatches,
15
+ sessionCookie,
16
+ } from "./auth.js";
17
+ import { clearOffender, gateMiddleware, noteFailure } from "./gate.js";
18
+ import { snapshot } from "./snapshot.js";
19
+ import { runAction } from "./actions.js";
20
+ import {
21
+ list as listLogs,
22
+ subscribeLive,
23
+ } from "./event-log.js";
24
+ import {
25
+ listExpressRoutes,
26
+ listRouteModules,
27
+ listViews,
28
+ routeActivity,
29
+ } from "./inventory.js";
30
+ import {
31
+ cloudflareConfigured,
32
+ fetchCacheAnalytics,
33
+ fetchCloudflareOverview,
34
+ fetchPathEdges,
35
+ } from "../cloudflare.js";
36
+
37
+ const PANEL_DIR = path.join(FRAMEWORK_ROOT, "src", "client", "admin");
38
+
39
+ /**
40
+ * @param {() => typeof import('../../config/defaults.js').DEFAULT_ADMIN} getSettings
41
+ * @param {import('express').Express} app
42
+ * @returns {import('express').Router}
43
+ */
44
+ export function createAdminRouter(getSettings, app) {
45
+ const api = express.Router();
46
+
47
+ api.use((req, res, next) => {
48
+ res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
49
+ res.setHeader("X-Robots-Tag", "noindex, nofollow, noarchive, nosnippet");
50
+ res.setHeader("Referrer-Policy", "no-referrer");
51
+ next();
52
+ });
53
+
54
+ api.use(gateMiddleware(getSettings));
55
+
56
+ // Soft page routes → aynı shell (client path ile sekme seçer).
57
+ // JSON API'ler ayrı `/api/*` altında: `/logs` hem sayfa hem döküm olamaz.
58
+ const shellPages = ["/", "/cache", "/routes", "/views", "/logs", "/system"];
59
+ for (const page of shellPages) {
60
+ api.get(page, (req, res) => {
61
+ const settings = getSettings();
62
+ const bare = req.originalUrl.split("?")[0];
63
+ if (page === "/" && !bare.endsWith("/")) {
64
+ res.redirect(302, `${settings.basePath}/`);
65
+ return;
66
+ }
67
+
68
+ res.type("html");
69
+ sendFile(res, authenticated(req) ? "panel.html" : "login.html");
70
+ });
71
+ }
72
+
73
+ api.get("/panel.css", (req, res) => {
74
+ res.type("text/css");
75
+ sendFile(res, "panel.css");
76
+ });
77
+
78
+ api.get("/i18n.js", (req, res) => {
79
+ res.type("application/javascript");
80
+ sendFile(res, "i18n.js");
81
+ });
82
+
83
+ api.get("/logo.png", (req, res) => {
84
+ res.type("image/png");
85
+ fs.createReadStream(path.join(FRAMEWORK_ROOT, "src", "logo.png")).pipe(res);
86
+ });
87
+
88
+ api.post("/login", express.json({ limit: "4kb" }), (req, res) => {
89
+ const settings = getSettings();
90
+ const password = typeof req.body?.password === "string" ? req.body.password : "";
91
+
92
+ if (!passwordMatches(password)) {
93
+ noteFailure(req, password ? "wrong password" : "empty password", settings);
94
+ res.status(401).json({ ok: false, message: "Invalid password" });
95
+ return;
96
+ }
97
+
98
+ const { token, maxAge } = createSession(settings.sessionHours);
99
+ clearOffender(req);
100
+ res.setHeader("Set-Cookie", sessionCookie(settings.basePath, token, maxAge));
101
+ res.json({ ok: true });
102
+ });
103
+
104
+ api.use((req, res, next) => {
105
+ if (authenticated(req)) return next();
106
+
107
+ if (req.method !== "GET" && req.method !== "HEAD") {
108
+ noteFailure(req, `unauthenticated ${req.method} ${req.path}`, getSettings());
109
+ }
110
+
111
+ res.status(404).type("text/plain").send("Not Found");
112
+ });
113
+
114
+ api.post("/logout", (req, res) => {
115
+ const settings = getSettings();
116
+ destroySession(req);
117
+ res.setHeader("Set-Cookie", clearSessionCookie(settings.basePath));
118
+ res.json({ ok: true });
119
+ });
120
+
121
+ api.get("/panel.js", (req, res) => {
122
+ res.type("application/javascript");
123
+ sendFile(res, "panel.js");
124
+ });
125
+
126
+ api.get("/data", async (req, res) => {
127
+ const query = typeof req.query.q === "string" ? req.query.q : "";
128
+ res.json(await snapshot(query));
129
+ });
130
+
131
+ api.get("/api/routes", (req, res) => {
132
+ res.json({
133
+ routes: listExpressRoutes(app),
134
+ modules: listRouteModules(),
135
+ activity: routeActivity(),
136
+ });
137
+ });
138
+
139
+ api.get("/api/views", (req, res) => {
140
+ res.json({ views: listViews() });
141
+ });
142
+
143
+ api.get("/api/logs", (req, res) => {
144
+ const after = Number(req.query.after) || 0;
145
+ const limit = Number(req.query.limit) || 200;
146
+ res.json({ entries: listLogs(after, limit) });
147
+ });
148
+
149
+ api.get("/api/logs/stream", (req, res) => {
150
+ res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
151
+ res.setHeader("Cache-Control", "no-store, no-cache");
152
+ res.setHeader("Connection", "keep-alive");
153
+ res.flushHeaders?.();
154
+
155
+ const replay = listLogs(0, 100);
156
+ for (const entry of replay) {
157
+ res.write(`data: ${JSON.stringify(entry)}\n\n`);
158
+ }
159
+
160
+ const unsubscribe = subscribeLive((entry) => {
161
+ res.write(`data: ${JSON.stringify(entry)}\n\n`);
162
+ });
163
+
164
+ const heartbeat = setInterval(() => {
165
+ res.write(": ping\n\n");
166
+ }, 15000);
167
+
168
+ req.on("close", () => {
169
+ clearInterval(heartbeat);
170
+ unsubscribe();
171
+ });
172
+ });
173
+
174
+ api.get("/cloudflare", async (req, res) => {
175
+ res.json(await fetchCloudflareOverview({ force: req.query.force === "1" }));
176
+ });
177
+
178
+ api.post("/cloudflare/analytics", express.json({ limit: "8kb" }), async (req, res) => {
179
+ if (!cloudflareConfigured()) {
180
+ res.json({ ok: false, error: "not configured" });
181
+ return;
182
+ }
183
+
184
+ const hours = Number(req.body?.hours) || undefined;
185
+ const pathValue = typeof req.body?.path === "string" ? req.body.path.trim() : "";
186
+ res.json(
187
+ pathValue
188
+ ? await fetchPathEdges({ path: pathValue, hours })
189
+ : await fetchCacheAnalytics({ hours }),
190
+ );
191
+ });
192
+
193
+ api.post("/action", express.json({ limit: "64kb" }), async (req, res) => {
194
+ if (req.get(ACTION_HEADER) !== "1") {
195
+ res.status(404).type("text/plain").send("Not Found");
196
+ return;
197
+ }
198
+
199
+ try {
200
+ res.json(await runAction(req.body ?? {}, req));
201
+ } catch (error) {
202
+ console.error("[admin] action failed", error);
203
+ res.status(500).json({ ok: false, message: "Action failed, see server logs" });
204
+ }
205
+ });
206
+
207
+ return api;
208
+ }
209
+
210
+ /**
211
+ * @param {import('express').Response} res
212
+ * @param {string} name
213
+ */
214
+ function sendFile(res, name) {
215
+ fs.createReadStream(path.join(PANEL_DIR, name)).pipe(res);
216
+ }
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Admin paneli cache / host / process dökümü.
3
+ *
4
+ * HTML gövdesi ve veri değerleri dönmez — yalnızca meta.
5
+ * System sayfasındaki çubuklar **bu sürecin** payını gösterir (makine
6
+ * toplamına oranla), host'un genel doluluğunu değil.
7
+ */
8
+ import fs from "node:fs";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ import process from "node:process";
12
+ import { getConfig } from "../../config/index.js";
13
+ import {
14
+ FRAMEWORK_HOMEPAGE,
15
+ FRAMEWORK_LICENSE,
16
+ FRAMEWORK_NODE_RANGE,
17
+ FRAMEWORK_VERSION,
18
+ } from "../../version.mjs";
19
+ import {
20
+ getHtmlCacheEntries,
21
+ getHtmlCacheSize,
22
+ } from "../html-cache.js";
23
+ import {
24
+ getDataCacheEntries,
25
+ getDataCacheSize,
26
+ } from "../data-cache.js";
27
+ import { getRedisDetails, getRedisStatus } from "../redis.js";
28
+ import { getUpstreamLimiterStatus } from "../upstream-limiter.js";
29
+ import { getCloudflareStatus } from "../cloudflare.js";
30
+ import { prewarmProgress } from "../prewarm.js";
31
+
32
+ /** Listelerin üst sınırı: veri önbelleğinde on binlerce anahtar olabiliyor. */
33
+ const MAX_LISTED = 500;
34
+
35
+ /** Disk ölçümünde atlanan dizinler — node_modules her poll'da taranmasın. */
36
+ const SKIP_DIRS = new Set([
37
+ "node_modules",
38
+ ".git",
39
+ ".hg",
40
+ ".svn",
41
+ "coverage",
42
+ ".turbo",
43
+ ".next",
44
+ ]);
45
+
46
+ export const BOOT_ID = `${Date.now()}-${process.pid}`;
47
+
48
+ /** @type {{ usage: NodeJS.CpuUsage; at: number } | null} */
49
+ let cpuSample = null;
50
+
51
+ /** @type {{ at: number, bytes: number, root: string } | null} */
52
+ let diskSample = null;
53
+
54
+ /**
55
+ * @param {string} query Anahtar filtresi (boş → filtre yok).
56
+ * @returns {Promise<object>}
57
+ */
58
+ export async function snapshot(query) {
59
+ const term = query.trim().toLowerCase();
60
+ /** @param {{ key: string }} entry */
61
+ const matches = (entry) => !term || entry.key.toLowerCase().includes(term);
62
+
63
+ const html = getHtmlCacheEntries();
64
+ const data = getDataCacheEntries();
65
+
66
+ const htmlMatched = html.filter(matches);
67
+ const dataMatched = data.filter(matches);
68
+ const usage = process.memoryUsage();
69
+ const host = await hostStatus();
70
+ const cpuPercent = sampleProcessCpu(host.cpus);
71
+ const appDiskBytes = await sampleAppDisk(getConfig().root);
72
+
73
+ return {
74
+ boot: BOOT_ID,
75
+ generatedAt: Date.now(),
76
+ release: {
77
+ version: FRAMEWORK_VERSION,
78
+ license: FRAMEWORK_LICENSE,
79
+ node: FRAMEWORK_NODE_RANGE,
80
+ homepage: FRAMEWORK_HOMEPAGE,
81
+ },
82
+ host,
83
+ process: {
84
+ pid: process.pid,
85
+ node: process.version,
86
+ uptime: process.uptime(),
87
+ env: process.env.NODE_ENV ?? "production",
88
+ memory: { rss: usage.rss, heapUsed: usage.heapUsed },
89
+ /** 0–100: bu sürecin tüm çekirdek kapasitesine oranı. */
90
+ cpuPercent,
91
+ /** Proje kökünün (node_modules hariç) disk boyutu. */
92
+ diskBytes: appDiskBytes,
93
+ },
94
+ html: {
95
+ size: getHtmlCacheSize(),
96
+ maxEntries: getConfig().htmlMaxEntries,
97
+ bytes: html.reduce((total, entry) => total + entry.bytes, 0),
98
+ stale: html.filter((entry) => entry.stale).length,
99
+ matched: htmlMatched.length,
100
+ entries: htmlMatched
101
+ .sort((a, b) => b.bytes - a.bytes)
102
+ .slice(0, MAX_LISTED)
103
+ .map((entry) => ({
104
+ ...entry,
105
+ url: entry.key.endsWith("?") ? entry.key.slice(0, -1) : entry.key,
106
+ })),
107
+ },
108
+ data: {
109
+ size: getDataCacheSize(),
110
+ maxEntries: Number(getConfig().data?.maxEntries) || 0,
111
+ stale: data.filter((entry) => entry.stale).length,
112
+ matched: dataMatched.length,
113
+ entries: dataMatched
114
+ .sort((a, b) => a.expiresIn - b.expiresIn)
115
+ .slice(0, MAX_LISTED),
116
+ },
117
+ redis: { ...getRedisStatus(), ...getRedisDetails() },
118
+ cloudflare: getCloudflareStatus(),
119
+ upstream: getUpstreamLimiterStatus(),
120
+ prewarm: { ...prewarmProgress },
121
+ };
122
+ }
123
+
124
+ /**
125
+ * İki örnek arasındaki `process.cpuUsage` farkından süreç CPU yüzdesi.
126
+ * İlk çağrıda örnek alınır ve 0 döner — panelin bir sonraki turunda anlamlı.
127
+ *
128
+ * @param {number} cores
129
+ * @returns {number}
130
+ */
131
+ function sampleProcessCpu(cores) {
132
+ const now = Date.now();
133
+ const current = process.cpuUsage();
134
+
135
+ if (!cpuSample) {
136
+ cpuSample = { usage: current, at: now };
137
+ return 0;
138
+ }
139
+
140
+ const elapsedMs = now - cpuSample.at;
141
+ const delta = process.cpuUsage(cpuSample.usage);
142
+ cpuSample = { usage: current, at: now };
143
+
144
+ if (elapsedMs <= 0 || cores <= 0) return 0;
145
+
146
+ // user+system mikro-saniye → ms; duvar süresi × çekirdek = kapasite.
147
+ const cpuMs = (delta.user + delta.system) / 1000;
148
+ const capacityMs = elapsedMs * cores;
149
+ return Math.max(0, Math.min(100, (cpuMs / capacityMs) * 100));
150
+ }
151
+
152
+ /**
153
+ * Proje kökünün boyutu (ağır dizinler atlanır). 60 sn önbellek.
154
+ *
155
+ * @param {string} root
156
+ * @returns {Promise<number>}
157
+ */
158
+ async function sampleAppDisk(root) {
159
+ if (diskSample && diskSample.root === root && Date.now() - diskSample.at < 60_000) {
160
+ return diskSample.bytes;
161
+ }
162
+
163
+ const bytes = await measureDir(root);
164
+ diskSample = { at: Date.now(), bytes, root };
165
+ return bytes;
166
+ }
167
+
168
+ /**
169
+ * @param {string} dir
170
+ * @returns {Promise<number>}
171
+ */
172
+ async function measureDir(dir) {
173
+ let total = 0;
174
+
175
+ /** @type {string[]} */
176
+ const stack = [dir];
177
+
178
+ while (stack.length) {
179
+ const current = stack.pop();
180
+ if (!current) continue;
181
+
182
+ let entries;
183
+ try {
184
+ entries = await fs.promises.readdir(current, { withFileTypes: true });
185
+ } catch {
186
+ continue;
187
+ }
188
+
189
+ for (const entry of entries) {
190
+ if (entry.name === "." || entry.name === "..") continue;
191
+ if (entry.isDirectory() && SKIP_DIRS.has(entry.name)) continue;
192
+
193
+ const full = path.join(current, entry.name);
194
+ if (entry.isDirectory()) {
195
+ stack.push(full);
196
+ continue;
197
+ }
198
+ if (!entry.isFile()) continue;
199
+
200
+ try {
201
+ const stats = await fs.promises.stat(full);
202
+ total += stats.size;
203
+ } catch {
204
+ // silinmiş / erişilemeyen dosya
205
+ }
206
+ }
207
+ }
208
+
209
+ return total;
210
+ }
211
+
212
+ /**
213
+ * @returns {Promise<object>}
214
+ */
215
+ async function hostStatus() {
216
+ const total = os.totalmem();
217
+ const free = os.freemem();
218
+
219
+ /** @type {{ path: string, total: number, free: number } | null} */
220
+ let disk = null;
221
+
222
+ try {
223
+ const root = getConfig().root;
224
+ const stats = await fs.promises.statfs(root);
225
+ disk = {
226
+ path: root,
227
+ total: stats.blocks * stats.bsize,
228
+ free: stats.bavail * stats.bsize,
229
+ };
230
+ } catch {
231
+ disk = null;
232
+ }
233
+
234
+ return {
235
+ platform: `${os.platform()} ${os.arch()}`,
236
+ cpus: os.cpus().length,
237
+ load: os.loadavg()[0],
238
+ memory: { total, free, used: total - free },
239
+ disk,
240
+ };
241
+ }