jskelet 0.2.5 → 0.3.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 (106) hide show
  1. package/AGENTS.md +132 -132
  2. package/CHANGELOG.md +403 -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 +756 -670
  42. package/src/client/{cache-panel → admin}/login.html +74 -74
  43. package/src/client/{cache-panel → admin}/panel.css +804 -756
  44. package/src/client/admin/panel.html +486 -0
  45. package/src/client/{cache-panel → admin}/panel.js +1242 -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 +126 -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
@@ -1,369 +1,369 @@
1
- /**
2
- * "Detaylı İncele" raporunun veri katmanı.
3
- *
4
- * Overlay baloncuğu anlık durumu gösterir; bu modül ise sitenin tamamına
5
- * bakan bir görünüm üretir: gezilen her sayfanın Web Vitals ölçümleri, SSR
6
- * çıktısının boyutu, island (CSR) durumu, tarayıcı ve sunucu tarafındaki API
7
- * çağrıları, build çıktısındaki chunk/varlık kırılımı ve HTML önbelleği.
8
- *
9
- * Yalnızca development'ta yüklenir (devtools ile birlikte mount edilir),
10
- * üretim çıktısına girmez.
11
- */
12
- import fs from "node:fs";
13
- import path from "node:path";
14
- import zlib from "node:zlib";
15
- import { getHtmlCacheEntries, getHtmlCacheSize } from "../html-cache.js";
16
- import { getDataCacheSize, getDataCacheStats } from "../data-cache.js";
17
- import { getRedisStatus } from "../redis.js";
18
- import { getUpstreamLimiterStatus } from "../upstream-limiter.js";
19
- import { prewarmProgress } from "../prewarm.js";
20
- import { getConfig } from "../../config/index.js";
21
-
22
- /** Yollar config'ten: framework paket içine taşındığında `../..` sayan her hesap bozulur. */
23
- const ROOT = getConfig().root;
24
- const PUBLIC_DIR = getConfig().dirs.public;
25
- const GENERATED_DIR = getConfig().dirs.generated;
26
-
27
- /* ------------------------------------------------------------- sayfa ölçümleri */
28
-
29
- /**
30
- * @typedef {{
31
- * url: string,
32
- * title: string | null,
33
- * at: number,
34
- * visits: number,
35
- * metrics: Record<string, number | null>,
36
- * resources: { count: number, bytes: number, byType: Record<string, { count: number, bytes: number }> },
37
- * islands: { total: number, ready: number, names: string[] },
38
- * api: { url: string, ms: number, status: number, bytes: number, initiator: string }[],
39
- * html: { bytes: number | null, cache: string | null, ms: number | null },
40
- * }} PageReport
41
- */
42
-
43
- /** @type {Map<string, PageReport>} */
44
- const pages = new Map();
45
-
46
- /** Tarayıcıdan gelen ölçüm paketini saklar. En yeni paket öncekini ezer. */
47
- export function recordPageReport(payload) {
48
- if (!payload?.url) return;
49
-
50
- let url;
51
- try {
52
- url = new URL(payload.url).pathname + new URL(payload.url).search;
53
- } catch {
54
- url = String(payload.url);
55
- }
56
-
57
- const previous = pages.get(url);
58
-
59
- pages.set(url, {
60
- url,
61
- title: payload.title ?? previous?.title ?? null,
62
- at: Date.now(),
63
- visits: (previous?.visits ?? 0) + 1,
64
- metrics: payload.metrics ?? {},
65
- resources: payload.resources ?? { count: 0, bytes: 0, byType: {} },
66
- islands: payload.islands ?? { total: 0, ready: 0, names: [] },
67
- api: Array.isArray(payload.api) ? payload.api.slice(0, 100) : [],
68
- html: previous?.html ?? { bytes: null, cache: null, ms: null },
69
- });
70
- }
71
-
72
- /** Ölçümler tarayıcı sekmesinde değil sunucuda durur; sıfırlama da buradan. */
73
- export function clearPageReports() {
74
- pages.clear();
75
- serverApiCalls.length = 0;
76
- }
77
-
78
- /* --------------------------------------------------- sunucu tarafı API çağrıları */
79
-
80
- /**
81
- * @type {{ url: string, host: string, method: string, status: number, ms: number,
82
- * bytes: number, at: number, error: string | null }[]}
83
- */
84
- const serverApiCalls = [];
85
- const MAX_API_CALLS = 300;
86
-
87
- /**
88
- * SSR sırasında yapılan dış çağrıları ölçer. `globalThis.fetch` sarılır;
89
- * yalnızca dev'de çağrıldığı için üretim yolu dokunulmaz kalır.
90
- */
91
- export function trackServerFetch() {
92
- const original = globalThis.fetch;
93
- if (original.__jskeletWrapped) return;
94
-
95
- /** @type {typeof fetch} */
96
- const wrapped = async (input, init) => {
97
- const url = typeof input === "string" ? input : (input?.url ?? String(input));
98
- const started = Date.now();
99
-
100
- // Kendi sunucumuza yapılan istekler (ısıtma, sağlık kontrolü) API sayılmaz.
101
- const isSelf = /^https?:\/\/(127\.0\.0\.1|localhost)/i.test(url);
102
-
103
- try {
104
- const response = await original(input, init);
105
- if (!isSelf) {
106
- push({
107
- url,
108
- method: init?.method ?? "GET",
109
- status: response.status,
110
- ms: Date.now() - started,
111
- bytes: Number(response.headers.get("content-length") ?? 0),
112
- error: response.ok ? null : `HTTP ${response.status}`,
113
- });
114
- }
115
- return response;
116
- } catch (error) {
117
- if (!isSelf) {
118
- push({
119
- url,
120
- method: init?.method ?? "GET",
121
- status: 0,
122
- ms: Date.now() - started,
123
- bytes: 0,
124
- error: error instanceof Error ? error.message : String(error),
125
- });
126
- }
127
- throw error;
128
- }
129
- };
130
-
131
- wrapped.__jskeletWrapped = true;
132
- globalThis.fetch = wrapped;
133
- }
134
-
135
- /** @param {{ url: string, method: string, status: number, ms: number, bytes: number, error: string | null }} call */
136
- function push(call) {
137
- let host = "—";
138
- try {
139
- host = new URL(call.url).host;
140
- } catch {
141
- // Göreli adres: host bilinmiyor.
142
- }
143
-
144
- serverApiCalls.push({ ...call, host, at: Date.now() });
145
- while (serverApiCalls.length > MAX_API_CALLS) serverApiCalls.shift();
146
- }
147
-
148
- /* ------------------------------------------------------------ build çıktısı */
149
-
150
- /** Boyut hesapları dosya değişmedikçe tekrarlanmaz. */
151
- const sizeCache = new Map();
152
-
153
- /**
154
- * @param {string} file mutlak yol
155
- * @returns {{ bytes: number, gzip: number, brotli: number | null } | null}
156
- */
157
- function measure(file) {
158
- let stat;
159
- try {
160
- stat = fs.statSync(file);
161
- } catch {
162
- return null;
163
- }
164
-
165
- const key = `${file}:${stat.size}:${stat.mtimeMs}`;
166
- const hit = sizeCache.get(key);
167
- if (hit) return hit;
168
-
169
- let gzip = 0;
170
- let brotli = null;
171
-
172
- try {
173
- const buffer = fs.readFileSync(file);
174
- // Build önceden sıkıştırılmış eşlerini üretiyorsa onları kullan; yoksa
175
- // gzip'i burada hesapla (rapor tek seferlik, maliyeti kabul edilebilir).
176
- brotli = statSize(`${file}.br`);
177
- gzip = statSize(`${file}.gz`) ?? zlib.gzipSync(buffer, { level: 6 }).length;
178
- } catch {
179
- return null;
180
- }
181
-
182
- const value = { bytes: stat.size, gzip, brotli };
183
- sizeCache.set(key, value);
184
- return value;
185
- }
186
-
187
- /** @param {string} file @returns {number | null} */
188
- function statSize(file) {
189
- try {
190
- return fs.statSync(file).size;
191
- } catch {
192
- return null;
193
- }
194
- }
195
-
196
- /** @returns {Record<string, string>} */
197
- function readJson(file, fallback) {
198
- try {
199
- return JSON.parse(fs.readFileSync(file, "utf8"));
200
- } catch {
201
- return fallback;
202
- }
203
- }
204
-
205
- /**
206
- * Manifest girdileri + boyutları. Yol public/ altına göre çözülür.
207
- */
208
- function assets() {
209
- const manifest = readJson(path.join(GENERATED_DIR, "manifest.json"), {});
210
-
211
- return Object.entries(manifest).map(([name, url]) => {
212
- const size = measure(path.join(PUBLIC_DIR, url.replace(/^\//, "")));
213
- return {
214
- name,
215
- url,
216
- kind: path.extname(url).slice(1) || "other",
217
- bytes: size?.bytes ?? null,
218
- gzip: size?.gzip ?? null,
219
- brotli: size?.brotli ?? null,
220
- };
221
- });
222
- }
223
-
224
- /**
225
- * esbuild metafile'ından chunk analizi: her çıktı için boyut, hangi
226
- * kaynaklardan oluştuğu ve hangi chunk'ları import ettiği.
227
- */
228
- function chunks() {
229
- const metafile = readJson(path.join(GENERATED_DIR, "metafile.json"), null);
230
- if (!metafile?.outputs) return { outputs: [], groups: [], available: false };
231
-
232
- /** @type {Record<string, number>} */
233
- const groups = {};
234
-
235
- const outputs = Object.entries(metafile.outputs)
236
- .filter(([file]) => file.endsWith(".js") || file.endsWith(".css"))
237
- .map(([file, output]) => {
238
- const size = measure(path.join(ROOT, file));
239
-
240
- const inputs = Object.entries(output.inputs ?? {})
241
- .map(([source, info]) => ({ source, bytes: info.bytesInOutput ?? 0 }))
242
- .filter((input) => input.bytes > 0)
243
- .sort((a, b) => b.bytes - a.bytes);
244
-
245
- for (const input of inputs) {
246
- const group = groupOf(input.source);
247
- groups[group] = (groups[group] ?? 0) + input.bytes;
248
- }
249
-
250
- return {
251
- file: `/${file.split(path.sep).join("/").replace(/^public\//, "")}`,
252
- entry: output.entryPoint ?? null,
253
- isChunk: file.includes("chunks"),
254
- bytes: output.bytes,
255
- gzip: size?.gzip ?? null,
256
- brotli: size?.brotli ?? null,
257
- imports: (output.imports ?? [])
258
- .filter((item) => item.kind !== "file-loader")
259
- .map((item) => ({
260
- path: `/${item.path.split(path.sep).join("/").replace(/^public\//, "")}`,
261
- kind: item.kind,
262
- })),
263
- inputs: inputs.slice(0, 40),
264
- inputCount: inputs.length,
265
- };
266
- })
267
- .sort((a, b) => b.bytes - a.bytes);
268
-
269
- return {
270
- available: true,
271
- outputs,
272
- groups: Object.entries(groups)
273
- .map(([name, bytes]) => ({ name, bytes }))
274
- .sort((a, b) => b.bytes - a.bytes),
275
- };
276
- }
277
-
278
- /**
279
- * Kaynak dosyayı okunur bir gruba indirger: paket adı ya da üst klasör.
280
- * @param {string} source
281
- */
282
- function groupOf(source) {
283
- const normalized = source.split(path.sep).join("/");
284
- const modules = normalized.lastIndexOf("node_modules/");
285
-
286
- if (modules >= 0) {
287
- const rest = normalized.slice(modules + "node_modules/".length).split("/");
288
- return rest[0].startsWith("@") ? `${rest[0]}/${rest[1]}` : rest[0];
289
- }
290
-
291
- const parts = normalized.split("/").filter(Boolean);
292
- return parts.slice(0, 2).join("/") || normalized;
293
- }
294
-
295
- /* ------------------------------------------------------------------- rapor */
296
-
297
- /**
298
- * Rapor sayfasının tek veri kaynağı.
299
- * @param {{ requests: object[], errors: object[] }} devtools
300
- */
301
- export function buildReport(devtools) {
302
- const usage = process.memoryUsage();
303
-
304
- // SSR ölçümleri: ısıtma turu her sayfanın HTML boyutunu ve render süresini
305
- // biliyor; gezilen sayfalarla eşleştirilir.
306
- const warmByPath = new Map(
307
- (prewarmProgress.entries ?? []).map((entry) => [entry.path, entry]),
308
- );
309
-
310
- const pageList = [...pages.values()].map((page) => {
311
- const warm = warmByPath.get(page.url.split("?")[0]);
312
- return {
313
- ...page,
314
- html: warm
315
- ? { bytes: warm.bytes, cache: warm.cache, ms: warm.ms }
316
- : page.html,
317
- };
318
- });
319
-
320
- // Hiç gezilmemiş ama ısıtılmış sayfalar da listelenir: SSR tarafı bilinir,
321
- // istemci ölçümleri boş kalır.
322
- for (const entry of prewarmProgress.entries ?? []) {
323
- if (pages.has(entry.path)) continue;
324
- pageList.push({
325
- url: entry.path,
326
- title: null,
327
- at: prewarmProgress.finishedAt ?? prewarmProgress.startedAt,
328
- visits: 0,
329
- metrics: {},
330
- resources: { count: 0, bytes: 0, byType: {} },
331
- islands: { total: 0, ready: 0, names: [] },
332
- api: [],
333
- html: { bytes: entry.bytes, cache: entry.cache, ms: entry.ms },
334
- });
335
- }
336
-
337
- return {
338
- generatedAt: Date.now(),
339
- process: {
340
- pid: process.pid,
341
- node: process.version,
342
- uptime: process.uptime(),
343
- memory: { rss: usage.rss, heapUsed: usage.heapUsed },
344
- env: process.env.NODE_ENV ?? "development",
345
- },
346
- pages: pageList.sort((a, b) => (b.visits - a.visits) || b.at - a.at),
347
- serverApi: serverApiCalls.slice().reverse(),
348
- build: { assets: assets(), ...chunks() },
349
- cache: {
350
- size: getHtmlCacheSize(),
351
- entries: getHtmlCacheEntries(),
352
- // Veri önbelleğinden yalnızca sayaç: uzun kuyruklu bir sitede on
353
- // binlerce anahtar oluyor ve dökümü rapora koymak faydasız bir yük.
354
- data: getDataCacheSize(),
355
- // Sayaçlar dökümün yerine geçmiyor, onu tamamlıyor: "kaç girdi var"
356
- // sorusundan çok "kaç okuma upstream'e gitti" sorusu karar veriyor.
357
- dataStats: getDataCacheStats(),
358
- // Paylaşımlı kademe kapalıyken de basılır: "Redis'i açtım ama neden
359
- // çalışmıyor" sorusunun cevabı en çok burada aranıyor.
360
- redis: getRedisStatus(),
361
- },
362
- // Hız freninin o anki durumu. 429 fırtınasında "şu an saniyede kaça
363
- // indi" bilgisi olmadan ayar yapmak körlemesine oluyor.
364
- upstream: getUpstreamLimiterStatus(),
365
- prewarm: { ...prewarmProgress },
366
- requests: devtools.requests,
367
- errors: devtools.errors,
368
- };
369
- }
1
+ /**
2
+ * "Detaylı İncele" raporunun veri katmanı.
3
+ *
4
+ * Overlay baloncuğu anlık durumu gösterir; bu modül ise sitenin tamamına
5
+ * bakan bir görünüm üretir: gezilen her sayfanın Web Vitals ölçümleri, SSR
6
+ * çıktısının boyutu, island (CSR) durumu, tarayıcı ve sunucu tarafındaki API
7
+ * çağrıları, build çıktısındaki chunk/varlık kırılımı ve HTML önbelleği.
8
+ *
9
+ * Yalnızca development'ta yüklenir (devtools ile birlikte mount edilir),
10
+ * üretim çıktısına girmez.
11
+ */
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+ import zlib from "node:zlib";
15
+ import { getHtmlCacheEntries, getHtmlCacheSize } from "../html-cache.js";
16
+ import { getDataCacheSize, getDataCacheStats } from "../data-cache.js";
17
+ import { getRedisStatus } from "../redis.js";
18
+ import { getUpstreamLimiterStatus } from "../upstream-limiter.js";
19
+ import { prewarmProgress } from "../prewarm.js";
20
+ import { getConfig } from "../../config/index.js";
21
+
22
+ /** Yollar config'ten: framework paket içine taşındığında `../..` sayan her hesap bozulur. */
23
+ const ROOT = getConfig().root;
24
+ const PUBLIC_DIR = getConfig().dirs.public;
25
+ const GENERATED_DIR = getConfig().dirs.generated;
26
+
27
+ /* ------------------------------------------------------------- sayfa ölçümleri */
28
+
29
+ /**
30
+ * @typedef {{
31
+ * url: string,
32
+ * title: string | null,
33
+ * at: number,
34
+ * visits: number,
35
+ * metrics: Record<string, number | null>,
36
+ * resources: { count: number, bytes: number, byType: Record<string, { count: number, bytes: number }> },
37
+ * islands: { total: number, ready: number, names: string[] },
38
+ * api: { url: string, ms: number, status: number, bytes: number, initiator: string }[],
39
+ * html: { bytes: number | null, cache: string | null, ms: number | null },
40
+ * }} PageReport
41
+ */
42
+
43
+ /** @type {Map<string, PageReport>} */
44
+ const pages = new Map();
45
+
46
+ /** Tarayıcıdan gelen ölçüm paketini saklar. En yeni paket öncekini ezer. */
47
+ export function recordPageReport(payload) {
48
+ if (!payload?.url) return;
49
+
50
+ let url;
51
+ try {
52
+ url = new URL(payload.url).pathname + new URL(payload.url).search;
53
+ } catch {
54
+ url = String(payload.url);
55
+ }
56
+
57
+ const previous = pages.get(url);
58
+
59
+ pages.set(url, {
60
+ url,
61
+ title: payload.title ?? previous?.title ?? null,
62
+ at: Date.now(),
63
+ visits: (previous?.visits ?? 0) + 1,
64
+ metrics: payload.metrics ?? {},
65
+ resources: payload.resources ?? { count: 0, bytes: 0, byType: {} },
66
+ islands: payload.islands ?? { total: 0, ready: 0, names: [] },
67
+ api: Array.isArray(payload.api) ? payload.api.slice(0, 100) : [],
68
+ html: previous?.html ?? { bytes: null, cache: null, ms: null },
69
+ });
70
+ }
71
+
72
+ /** Ölçümler tarayıcı sekmesinde değil sunucuda durur; sıfırlama da buradan. */
73
+ export function clearPageReports() {
74
+ pages.clear();
75
+ serverApiCalls.length = 0;
76
+ }
77
+
78
+ /* --------------------------------------------------- sunucu tarafı API çağrıları */
79
+
80
+ /**
81
+ * @type {{ url: string, host: string, method: string, status: number, ms: number,
82
+ * bytes: number, at: number, error: string | null }[]}
83
+ */
84
+ const serverApiCalls = [];
85
+ const MAX_API_CALLS = 300;
86
+
87
+ /**
88
+ * SSR sırasında yapılan dış çağrıları ölçer. `globalThis.fetch` sarılır;
89
+ * yalnızca dev'de çağrıldığı için üretim yolu dokunulmaz kalır.
90
+ */
91
+ export function trackServerFetch() {
92
+ const original = globalThis.fetch;
93
+ if (original.__jskeletWrapped) return;
94
+
95
+ /** @type {typeof fetch} */
96
+ const wrapped = async (input, init) => {
97
+ const url = typeof input === "string" ? input : (input?.url ?? String(input));
98
+ const started = Date.now();
99
+
100
+ // Kendi sunucumuza yapılan istekler (ısıtma, sağlık kontrolü) API sayılmaz.
101
+ const isSelf = /^https?:\/\/(127\.0\.0\.1|localhost)/i.test(url);
102
+
103
+ try {
104
+ const response = await original(input, init);
105
+ if (!isSelf) {
106
+ push({
107
+ url,
108
+ method: init?.method ?? "GET",
109
+ status: response.status,
110
+ ms: Date.now() - started,
111
+ bytes: Number(response.headers.get("content-length") ?? 0),
112
+ error: response.ok ? null : `HTTP ${response.status}`,
113
+ });
114
+ }
115
+ return response;
116
+ } catch (error) {
117
+ if (!isSelf) {
118
+ push({
119
+ url,
120
+ method: init?.method ?? "GET",
121
+ status: 0,
122
+ ms: Date.now() - started,
123
+ bytes: 0,
124
+ error: error instanceof Error ? error.message : String(error),
125
+ });
126
+ }
127
+ throw error;
128
+ }
129
+ };
130
+
131
+ wrapped.__jskeletWrapped = true;
132
+ globalThis.fetch = wrapped;
133
+ }
134
+
135
+ /** @param {{ url: string, method: string, status: number, ms: number, bytes: number, error: string | null }} call */
136
+ function push(call) {
137
+ let host = "—";
138
+ try {
139
+ host = new URL(call.url).host;
140
+ } catch {
141
+ // Göreli adres: host bilinmiyor.
142
+ }
143
+
144
+ serverApiCalls.push({ ...call, host, at: Date.now() });
145
+ while (serverApiCalls.length > MAX_API_CALLS) serverApiCalls.shift();
146
+ }
147
+
148
+ /* ------------------------------------------------------------ build çıktısı */
149
+
150
+ /** Boyut hesapları dosya değişmedikçe tekrarlanmaz. */
151
+ const sizeCache = new Map();
152
+
153
+ /**
154
+ * @param {string} file mutlak yol
155
+ * @returns {{ bytes: number, gzip: number, brotli: number | null } | null}
156
+ */
157
+ function measure(file) {
158
+ let stat;
159
+ try {
160
+ stat = fs.statSync(file);
161
+ } catch {
162
+ return null;
163
+ }
164
+
165
+ const key = `${file}:${stat.size}:${stat.mtimeMs}`;
166
+ const hit = sizeCache.get(key);
167
+ if (hit) return hit;
168
+
169
+ let gzip = 0;
170
+ let brotli = null;
171
+
172
+ try {
173
+ const buffer = fs.readFileSync(file);
174
+ // Build önceden sıkıştırılmış eşlerini üretiyorsa onları kullan; yoksa
175
+ // gzip'i burada hesapla (rapor tek seferlik, maliyeti kabul edilebilir).
176
+ brotli = statSize(`${file}.br`);
177
+ gzip = statSize(`${file}.gz`) ?? zlib.gzipSync(buffer, { level: 6 }).length;
178
+ } catch {
179
+ return null;
180
+ }
181
+
182
+ const value = { bytes: stat.size, gzip, brotli };
183
+ sizeCache.set(key, value);
184
+ return value;
185
+ }
186
+
187
+ /** @param {string} file @returns {number | null} */
188
+ function statSize(file) {
189
+ try {
190
+ return fs.statSync(file).size;
191
+ } catch {
192
+ return null;
193
+ }
194
+ }
195
+
196
+ /** @returns {Record<string, string>} */
197
+ function readJson(file, fallback) {
198
+ try {
199
+ return JSON.parse(fs.readFileSync(file, "utf8"));
200
+ } catch {
201
+ return fallback;
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Manifest girdileri + boyutları. Yol public/ altına göre çözülür.
207
+ */
208
+ function assets() {
209
+ const manifest = readJson(path.join(GENERATED_DIR, "manifest.json"), {});
210
+
211
+ return Object.entries(manifest).map(([name, url]) => {
212
+ const size = measure(path.join(PUBLIC_DIR, url.replace(/^\//, "")));
213
+ return {
214
+ name,
215
+ url,
216
+ kind: path.extname(url).slice(1) || "other",
217
+ bytes: size?.bytes ?? null,
218
+ gzip: size?.gzip ?? null,
219
+ brotli: size?.brotli ?? null,
220
+ };
221
+ });
222
+ }
223
+
224
+ /**
225
+ * esbuild metafile'ından chunk analizi: her çıktı için boyut, hangi
226
+ * kaynaklardan oluştuğu ve hangi chunk'ları import ettiği.
227
+ */
228
+ function chunks() {
229
+ const metafile = readJson(path.join(GENERATED_DIR, "metafile.json"), null);
230
+ if (!metafile?.outputs) return { outputs: [], groups: [], available: false };
231
+
232
+ /** @type {Record<string, number>} */
233
+ const groups = {};
234
+
235
+ const outputs = Object.entries(metafile.outputs)
236
+ .filter(([file]) => file.endsWith(".js") || file.endsWith(".css"))
237
+ .map(([file, output]) => {
238
+ const size = measure(path.join(ROOT, file));
239
+
240
+ const inputs = Object.entries(output.inputs ?? {})
241
+ .map(([source, info]) => ({ source, bytes: info.bytesInOutput ?? 0 }))
242
+ .filter((input) => input.bytes > 0)
243
+ .sort((a, b) => b.bytes - a.bytes);
244
+
245
+ for (const input of inputs) {
246
+ const group = groupOf(input.source);
247
+ groups[group] = (groups[group] ?? 0) + input.bytes;
248
+ }
249
+
250
+ return {
251
+ file: `/${file.split(path.sep).join("/").replace(/^public\//, "")}`,
252
+ entry: output.entryPoint ?? null,
253
+ isChunk: file.includes("chunks"),
254
+ bytes: output.bytes,
255
+ gzip: size?.gzip ?? null,
256
+ brotli: size?.brotli ?? null,
257
+ imports: (output.imports ?? [])
258
+ .filter((item) => item.kind !== "file-loader")
259
+ .map((item) => ({
260
+ path: `/${item.path.split(path.sep).join("/").replace(/^public\//, "")}`,
261
+ kind: item.kind,
262
+ })),
263
+ inputs: inputs.slice(0, 40),
264
+ inputCount: inputs.length,
265
+ };
266
+ })
267
+ .sort((a, b) => b.bytes - a.bytes);
268
+
269
+ return {
270
+ available: true,
271
+ outputs,
272
+ groups: Object.entries(groups)
273
+ .map(([name, bytes]) => ({ name, bytes }))
274
+ .sort((a, b) => b.bytes - a.bytes),
275
+ };
276
+ }
277
+
278
+ /**
279
+ * Kaynak dosyayı okunur bir gruba indirger: paket adı ya da üst klasör.
280
+ * @param {string} source
281
+ */
282
+ function groupOf(source) {
283
+ const normalized = source.split(path.sep).join("/");
284
+ const modules = normalized.lastIndexOf("node_modules/");
285
+
286
+ if (modules >= 0) {
287
+ const rest = normalized.slice(modules + "node_modules/".length).split("/");
288
+ return rest[0].startsWith("@") ? `${rest[0]}/${rest[1]}` : rest[0];
289
+ }
290
+
291
+ const parts = normalized.split("/").filter(Boolean);
292
+ return parts.slice(0, 2).join("/") || normalized;
293
+ }
294
+
295
+ /* ------------------------------------------------------------------- rapor */
296
+
297
+ /**
298
+ * Rapor sayfasının tek veri kaynağı.
299
+ * @param {{ requests: object[], errors: object[] }} devtools
300
+ */
301
+ export function buildReport(devtools) {
302
+ const usage = process.memoryUsage();
303
+
304
+ // SSR ölçümleri: ısıtma turu her sayfanın HTML boyutunu ve render süresini
305
+ // biliyor; gezilen sayfalarla eşleştirilir.
306
+ const warmByPath = new Map(
307
+ (prewarmProgress.entries ?? []).map((entry) => [entry.path, entry]),
308
+ );
309
+
310
+ const pageList = [...pages.values()].map((page) => {
311
+ const warm = warmByPath.get(page.url.split("?")[0]);
312
+ return {
313
+ ...page,
314
+ html: warm
315
+ ? { bytes: warm.bytes, cache: warm.cache, ms: warm.ms }
316
+ : page.html,
317
+ };
318
+ });
319
+
320
+ // Hiç gezilmemiş ama ısıtılmış sayfalar da listelenir: SSR tarafı bilinir,
321
+ // istemci ölçümleri boş kalır.
322
+ for (const entry of prewarmProgress.entries ?? []) {
323
+ if (pages.has(entry.path)) continue;
324
+ pageList.push({
325
+ url: entry.path,
326
+ title: null,
327
+ at: prewarmProgress.finishedAt ?? prewarmProgress.startedAt,
328
+ visits: 0,
329
+ metrics: {},
330
+ resources: { count: 0, bytes: 0, byType: {} },
331
+ islands: { total: 0, ready: 0, names: [] },
332
+ api: [],
333
+ html: { bytes: entry.bytes, cache: entry.cache, ms: entry.ms },
334
+ });
335
+ }
336
+
337
+ return {
338
+ generatedAt: Date.now(),
339
+ process: {
340
+ pid: process.pid,
341
+ node: process.version,
342
+ uptime: process.uptime(),
343
+ memory: { rss: usage.rss, heapUsed: usage.heapUsed },
344
+ env: process.env.NODE_ENV ?? "development",
345
+ },
346
+ pages: pageList.sort((a, b) => (b.visits - a.visits) || b.at - a.at),
347
+ serverApi: serverApiCalls.slice().reverse(),
348
+ build: { assets: assets(), ...chunks() },
349
+ cache: {
350
+ size: getHtmlCacheSize(),
351
+ entries: getHtmlCacheEntries(),
352
+ // Veri önbelleğinden yalnızca sayaç: uzun kuyruklu bir sitede on
353
+ // binlerce anahtar oluyor ve dökümü rapora koymak faydasız bir yük.
354
+ data: getDataCacheSize(),
355
+ // Sayaçlar dökümün yerine geçmiyor, onu tamamlıyor: "kaç girdi var"
356
+ // sorusundan çok "kaç okuma upstream'e gitti" sorusu karar veriyor.
357
+ dataStats: getDataCacheStats(),
358
+ // Paylaşımlı kademe kapalıyken de basılır: "Redis'i açtım ama neden
359
+ // çalışmıyor" sorusunun cevabı en çok burada aranıyor.
360
+ redis: getRedisStatus(),
361
+ },
362
+ // Hız freninin o anki durumu. 429 fırtınasında "şu an saniyede kaça
363
+ // indi" bilgisi olmadan ayar yapmak körlemesine oluyor.
364
+ upstream: getUpstreamLimiterStatus(),
365
+ prewarm: { ...prewarmProgress },
366
+ requests: devtools.requests,
367
+ errors: devtools.errors,
368
+ };
369
+ }