jskelet 0.6.1 → 0.6.3

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 (155) hide show
  1. package/AGENTS.md +136 -136
  2. package/CHANGELOG.md +620 -596
  3. package/LICENSE +21 -21
  4. package/bin/jskelet.mjs +130 -130
  5. package/docs/01-baslangic.md +291 -291
  6. package/docs/02-mimari.md +310 -309
  7. package/docs/03-routing.md +515 -515
  8. package/docs/04-render-ve-sablonlar.md +661 -661
  9. package/docs/05-islands.md +486 -486
  10. package/docs/06-cache.md +1443 -1423
  11. package/docs/07-yapilandirma.md +12 -6
  12. package/docs/08-build.md +429 -428
  13. package/docs/09-dev-araclari.md +364 -364
  14. package/docs/10-dagitim.md +338 -338
  15. package/docs/12-panel-ve-oturum.md +478 -478
  16. package/docs/README.md +83 -83
  17. package/docs/en/01-getting-started.md +298 -298
  18. package/docs/en/02-architecture.md +329 -328
  19. package/docs/en/03-routing.md +531 -531
  20. package/docs/en/04-rendering.md +669 -669
  21. package/docs/en/05-islands.md +497 -497
  22. package/docs/en/06-caching.md +1453 -1431
  23. package/docs/en/07-configuration.md +1219 -1214
  24. package/docs/en/08-build.md +447 -446
  25. package/docs/en/09-dev-tools.md +373 -373
  26. package/docs/en/10-deployment.md +340 -340
  27. package/docs/en/11-migration.md +398 -398
  28. package/docs/en/12-dashboards-and-sessions.md +488 -488
  29. package/docs/en/README.md +87 -87
  30. package/package.json +137 -137
  31. package/src/build/ensure-build.mjs +19 -19
  32. package/src/build/paths.mjs +153 -153
  33. package/src/build/resolve-peer.mjs +36 -36
  34. package/src/build/tasks/client.mjs +349 -349
  35. package/src/build/tasks/css.mjs +235 -235
  36. package/src/build/tasks/fonts.mjs +146 -146
  37. package/src/build/tasks/icons.mjs +357 -357
  38. package/src/build/tasks/images.mjs +244 -244
  39. package/src/build/tasks/precompress.mjs +78 -78
  40. package/src/build/tasks/templates.mjs +20 -20
  41. package/src/client/admin/i18n.js +764 -764
  42. package/src/client/admin/login.html +74 -74
  43. package/src/client/admin/panel.css +809 -809
  44. package/src/client/admin/panel.html +495 -495
  45. package/src/client/admin/panel.js +1251 -1251
  46. package/src/client/devtools/report.html +185 -185
  47. package/src/client/devtools/report.js +745 -745
  48. package/src/client/devtools/seo.js +628 -628
  49. package/src/client/dom.js +95 -95
  50. package/src/client/form.js +192 -192
  51. package/src/client/index.js +45 -45
  52. package/src/client/registry.js +305 -305
  53. package/src/client/safe-image.js +91 -91
  54. package/src/client/shared-cookie.js +225 -225
  55. package/src/client/store.js +36 -36
  56. package/src/client/swap.js +188 -188
  57. package/src/compile/codegen.js +336 -336
  58. package/src/compile/compile-all.js +149 -149
  59. package/src/compile/errors.js +66 -66
  60. package/src/compile/expr.js +409 -409
  61. package/src/compile/index.js +17 -17
  62. package/src/compile/parse.js +541 -541
  63. package/src/compile/resolve.js +211 -211
  64. package/src/compile/scan-exports.js +51 -51
  65. package/src/config/defaults.js +17 -1
  66. package/src/config/index.js +13 -0
  67. package/src/config/pattern.js +107 -107
  68. package/src/generate.mjs +163 -163
  69. package/src/http/control-flow.js +71 -71
  70. package/src/http/cookies-entry.js +21 -21
  71. package/src/http/cookies.js +277 -277
  72. package/src/http/request-cache.js +46 -46
  73. package/src/http/request-context.js +165 -165
  74. package/src/http/shared-cookie.js +178 -178
  75. package/src/index.js +101 -101
  76. package/src/init.mjs +230 -230
  77. package/src/migrate/apply.mjs +262 -262
  78. package/src/migrate/babel.mjs +79 -79
  79. package/src/migrate/classify.mjs +155 -155
  80. package/src/migrate/config.mjs +126 -126
  81. package/src/migrate/fs-walk.mjs +191 -191
  82. package/src/migrate/parse.mjs +26 -26
  83. package/src/migrate/scan.mjs +177 -177
  84. package/src/migrate/transform/expr-source.mjs +168 -168
  85. package/src/migrate/transform/island.mjs +67 -67
  86. package/src/migrate/transform/jsx-to-component.mjs +302 -302
  87. package/src/migrate/transform/jsx-to-jsk.mjs +330 -330
  88. package/src/migrate/transform/page-split.mjs +435 -435
  89. package/src/migrate/write.mjs +81 -81
  90. package/src/migrate.mjs +171 -171
  91. package/src/runtime/alias-hooks.mjs +119 -119
  92. package/src/runtime/register.mjs +4 -4
  93. package/src/server/admin/actions.js +229 -229
  94. package/src/server/admin/auth.js +125 -125
  95. package/src/server/admin/event-log.js +151 -151
  96. package/src/server/admin/gate.js +209 -209
  97. package/src/server/admin/inventory.js +188 -188
  98. package/src/server/admin/mount.js +56 -56
  99. package/src/server/admin/router.js +216 -216
  100. package/src/server/admin/snapshot.js +241 -241
  101. package/src/server/assets.js +147 -147
  102. package/src/server/auth/handoff.js +309 -309
  103. package/src/server/cache-blob.js +70 -0
  104. package/src/server/cache-deps.js +42 -42
  105. package/src/server/cache-vary.js +113 -113
  106. package/src/server/cloudflare.js +607 -607
  107. package/src/server/create-app.js +366 -366
  108. package/src/server/data-cache.js +553 -462
  109. package/src/server/dev/report.js +485 -485
  110. package/src/server/dev/socket.js +170 -170
  111. package/src/server/dev/version-check.mjs +139 -139
  112. package/src/server/disk-cache.js +233 -0
  113. package/src/server/ejs-adapter.js +59 -59
  114. package/src/server/html-cache.js +1196 -1122
  115. package/src/server/image-optimizer.js +500 -407
  116. package/src/server/logs/access-middleware.js +66 -66
  117. package/src/server/logs/file-sink.js +193 -66
  118. package/src/server/logs/pipeline.js +165 -158
  119. package/src/server/logs/s3-put.js +214 -214
  120. package/src/server/logs/s3-sink.js +112 -112
  121. package/src/server/metadata.js +102 -102
  122. package/src/server/middleware/compression.js +205 -205
  123. package/src/server/middleware/csrf.js +134 -134
  124. package/src/server/middleware/dev-gate.js +75 -75
  125. package/src/server/middleware/headers.js +37 -37
  126. package/src/server/middleware/redirects.js +32 -32
  127. package/src/server/middleware/robots-txt.js +341 -341
  128. package/src/server/middleware/static-precompressed.js +121 -100
  129. package/src/server/middleware/trailing-slash.js +53 -53
  130. package/src/server/middleware/upstream-proxy.js +141 -141
  131. package/src/server/og-image.js +356 -356
  132. package/src/server/port-guard.js +255 -255
  133. package/src/server/prewarm.js +1082 -1058
  134. package/src/server/redis.js +588 -569
  135. package/src/server/render.js +4 -4
  136. package/src/server/router.js +157 -157
  137. package/src/server/status-page.js +265 -265
  138. package/src/server/upstream-limiter.js +376 -376
  139. package/src/server/upstream-tracking.js +166 -166
  140. package/src/shared/cookie-domain.js +66 -66
  141. package/src/start.mjs +22 -22
  142. package/src/templates/layout.ejs +30 -30
  143. package/src/templates/layout.jsk +30 -30
  144. package/src/version.mjs +31 -31
  145. package/src/views/components/loader.js +101 -101
  146. package/src/views/helpers/html.js +102 -102
  147. package/src/views/helpers/tags.js +375 -375
  148. package/types/config/defaults.d.ts +15 -1
  149. package/types/config/index.d.ts +8 -0
  150. package/types/server/cache-blob.d.ts +13 -0
  151. package/types/server/data-cache.d.ts +9 -0
  152. package/types/server/disk-cache.d.ts +36 -0
  153. package/types/server/html-cache.d.ts +26 -3
  154. package/types/server/logs/file-sink.d.ts +16 -5
  155. package/types/server/redis.d.ts +2 -1
@@ -1,244 +1,244 @@
1
- /**
2
- * `next/image` optimizer'ının build zamanı karşılığı.
3
- *
4
- * `public/` altındaki elle konmuş raster görseller (png/jpg) için birkaç
5
- * genişlikte webp üretir ve `images.json` manifest'ine yazar.
6
- * `views/helpers/tags.js` → `image()` bu manifest'e bakıp `srcset` + intrinsic
7
- * `width`/`height` ekler; çağıran taraf hiçbir şey değiştirmez.
8
- *
9
- * Çıktılar hash'li olarak `public/assets/img/` altına düşer, yani `immutable`
10
- * cache ve precompress kapsamına girerler. Kaynak dosyalar olduğu yerde kalır:
11
- * manifest'te olmayan bir görsel her zaman orijinaliyle servis edilir.
12
- *
13
- * Manifest'e kodlayıcı imzası (`webp-q78-e4`) yazılır. Kalite ayarı değişince
14
- * imza da değişir ve tüm görseller yeniden kodlanır; aksi hâlde eski ayarla
15
- * üretilmiş çıktılar sessizce kalırdı.
16
- */
17
- import fs from "node:fs";
18
- import path from "node:path";
19
- import { hash, paths } from "../paths.mjs";
20
- import * as log from "../../log.mjs";
21
-
22
- const SOURCE = /\.(?:png|jpe?g)$/i;
23
-
24
- /** Build çıktısı ve ikon setleri taranmaz. */
25
- const DEFAULT_SKIP = ["assets", "fonts"];
26
-
27
- /** Yaygın kırılma noktaları; kaynaktan büyük olanlar elenir. */
28
- const DEFAULT_WIDTHS = [400, 640, 960, 1280, 1920];
29
-
30
- /** Retina ekranlarda bile bunun üstü israf. */
31
- const MAX_WIDTH = 1920;
32
-
33
- /**
34
- * @typedef {{ width: number, height: number, hash: string,
35
- * variants: { width: number, url: string }[] }} ImageEntry
36
- */
37
-
38
- /**
39
- * @param {string} dir
40
- * @param {Set<string>} skip
41
- * @returns {string[]}
42
- */
43
- function collect(dir, skip) {
44
- if (!fs.existsSync(dir)) return [];
45
-
46
- /** @type {string[]} */
47
- const files = [];
48
-
49
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
50
- if (entry.isDirectory()) {
51
- if (skip.has(entry.name)) continue;
52
- files.push(...collect(path.join(dir, entry.name), skip));
53
- } else if (SOURCE.test(entry.name)) {
54
- files.push(path.join(dir, entry.name));
55
- }
56
- }
57
-
58
- return files;
59
- }
60
-
61
- /**
62
- * `…\public\hero\a.png` → `/hero/a.png`
63
- * @param {string} file
64
- * @returns {string}
65
- */
66
- function publicUrl(file) {
67
- return `/${path.relative(paths.public, file).split(path.sep).join("/")}`;
68
- }
69
-
70
- /**
71
- * Üretilecek genişlikler: kaynaktan büyük olanlar atılır, kaynağın kendi
72
- * genişliği (MAX_WIDTH ile sınırlı) her zaman listeye girer.
73
- *
74
- * @param {number} intrinsic
75
- * @param {number[]} widths
76
- * @returns {number[]}
77
- */
78
- function targetWidths(intrinsic, widths) {
79
- const capped = Math.min(intrinsic, MAX_WIDTH);
80
- const out = widths.filter((width) => width < capped);
81
- out.push(capped);
82
- return out;
83
- }
84
-
85
- /**
86
- * @param {import('../../config/index.js').ResolvedConfig} config
87
- * @param {typeof import('sharp')} sharp
88
- * @returns {Promise<Record<string, string>>} Ana manifest'e katkı yok; görsel
89
- * manifest'i ayrı dosyaya yazılır.
90
- */
91
- export async function buildImages(config, sharp) {
92
- const widths = config.images?.widths ?? DEFAULT_WIDTHS;
93
- const quality = config.images?.quality ?? 78;
94
- const encoder = `webp-q${quality}-e4`;
95
- const webpOptions = { quality, effort: 4 };
96
-
97
- const skip = new Set([...DEFAULT_SKIP, ...(config.images?.skip ?? [])]);
98
- const manifestPath = path.join(paths.generated, "images.json");
99
- const outDir = path.join(paths.assets, "img");
100
-
101
- const sources = collect(paths.public, skip);
102
- if (!sources.length) {
103
- log.detail("no images, skipped");
104
- return {};
105
- }
106
-
107
- fs.mkdirSync(outDir, { recursive: true });
108
-
109
- /** @type {Record<string, ImageEntry>} */
110
- let cached = {};
111
- try {
112
- const data = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
113
- if (data.encoder === encoder) cached = data.images;
114
- } catch {
115
- // Manifest yok ya da kodlayıcı değişti: hepsi yeniden kodlanır.
116
- }
117
-
118
- /** @type {Record<string, ImageEntry>} */
119
- const images = {};
120
-
121
- let encoded = 0;
122
- let sourceBytes = 0;
123
- let outputBytes = 0;
124
-
125
- /** @param {ImageEntry} entry */
126
- const variantBytes = (entry) =>
127
- entry.variants.reduce(
128
- (sum, variant) =>
129
- sum + fs.statSync(path.join(paths.public, variant.url.slice(1))).size,
130
- 0,
131
- );
132
-
133
- for (const file of sources) {
134
- const url = publicUrl(file);
135
- const source = fs.readFileSync(file);
136
- const digest = hash(source);
137
- const previous = cached[url];
138
-
139
- // Kaynak değişmediyse ve çıktılar hâlâ yerindeyse yeniden kodlamak
140
- // boşa CPU; büyük bir public/ dizininde build süresini dakikalara çıkarır.
141
- if (
142
- previous?.hash === digest &&
143
- previous.variants.every((variant) =>
144
- fs.existsSync(path.join(paths.public, variant.url.slice(1))),
145
- )
146
- ) {
147
- images[url] = previous;
148
- sourceBytes += source.length;
149
- outputBytes += variantBytes(previous);
150
- continue;
151
- }
152
-
153
- try {
154
- const entry = await encode(sharp, {
155
- file,
156
- source,
157
- digest,
158
- widths,
159
- webpOptions,
160
- outDir,
161
- });
162
- if (!entry) continue;
163
-
164
- images[url] = entry;
165
- encoded += 1;
166
- sourceBytes += source.length;
167
- outputBytes += variantBytes(entry);
168
- } catch (error) {
169
- // Bozuk/okunamayan tek bir görsel build'i düşürmesin: manifest'te yer
170
- // almazsa orijinal dosya servis edilmeye devam eder.
171
- log.warn(`${url} could not be optimized (${error.message})`);
172
- }
173
- }
174
-
175
- pruneOutputs(
176
- outDir,
177
- new Set(
178
- Object.values(images).flatMap((entry) =>
179
- entry.variants.map((variant) => variant.url),
180
- ),
181
- ),
182
- );
183
-
184
- fs.mkdirSync(paths.generated, { recursive: true });
185
- fs.writeFileSync(
186
- manifestPath,
187
- `${JSON.stringify({ encoder, images }, null, 2)}\n`,
188
- );
189
-
190
- const total = Object.keys(images).length;
191
- const saved = sourceBytes - outputBytes;
192
- log.detail(
193
- `${total} images${encoded ? ` (${encoded} encoded)` : " (cached)"}, ` +
194
- `${log.size(Math.max(saved, 0))} saved`,
195
- );
196
-
197
- return {};
198
- }
199
-
200
- /**
201
- * Manifest'te artık geçmeyen eski çıktıları siler.
202
- *
203
- * @param {string} outDir
204
- * @param {Set<string>} keep public URL kümesi
205
- */
206
- function pruneOutputs(outDir, keep) {
207
- if (!fs.existsSync(outDir)) return;
208
- for (const file of fs.readdirSync(outDir)) {
209
- if (!keep.has(`/assets/img/${file}`)) {
210
- fs.rmSync(path.join(outDir, file), { force: true });
211
- }
212
- }
213
- }
214
-
215
- /**
216
- * @param {typeof import('sharp')} sharp
217
- * @param {{ file: string, source: Buffer, digest: string, widths: number[],
218
- * webpOptions: object, outDir: string }} job
219
- * @returns {Promise<ImageEntry | null>}
220
- */
221
- async function encode(sharp, job) {
222
- const { width, height } = await sharp(job.source, { failOn: "none" }).metadata();
223
- if (!width || !height) return null;
224
-
225
- const base = path.basename(job.file, path.extname(job.file));
226
-
227
- /** @type {{ width: number, url: string }[]} */
228
- const variants = [];
229
-
230
- for (const target of targetWidths(width, job.widths)) {
231
- const buffer = await sharp(job.source, { failOn: "none" })
232
- .resize({ width: target, withoutEnlargement: true })
233
- .webp(job.webpOptions)
234
- .toBuffer();
235
-
236
- // Hash kaynak + genişlikten türetilir: aynı içerik her build'de aynı
237
- // dosya adını verir, `immutable` cache bayatlamaz.
238
- const fileName = `${base}-${target}.${hash(`${job.digest}:${target}`)}.webp`;
239
- fs.writeFileSync(path.join(job.outDir, fileName), buffer);
240
- variants.push({ width: target, url: `/assets/img/${fileName}` });
241
- }
242
-
243
- return { width, height, hash: job.digest, variants };
244
- }
1
+ /**
2
+ * `next/image` optimizer'ının build zamanı karşılığı.
3
+ *
4
+ * `public/` altındaki elle konmuş raster görseller (png/jpg) için birkaç
5
+ * genişlikte webp üretir ve `images.json` manifest'ine yazar.
6
+ * `views/helpers/tags.js` → `image()` bu manifest'e bakıp `srcset` + intrinsic
7
+ * `width`/`height` ekler; çağıran taraf hiçbir şey değiştirmez.
8
+ *
9
+ * Çıktılar hash'li olarak `public/assets/img/` altına düşer, yani `immutable`
10
+ * cache ve precompress kapsamına girerler. Kaynak dosyalar olduğu yerde kalır:
11
+ * manifest'te olmayan bir görsel her zaman orijinaliyle servis edilir.
12
+ *
13
+ * Manifest'e kodlayıcı imzası (`webp-q78-e4`) yazılır. Kalite ayarı değişince
14
+ * imza da değişir ve tüm görseller yeniden kodlanır; aksi hâlde eski ayarla
15
+ * üretilmiş çıktılar sessizce kalırdı.
16
+ */
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ import { hash, paths } from "../paths.mjs";
20
+ import * as log from "../../log.mjs";
21
+
22
+ const SOURCE = /\.(?:png|jpe?g)$/i;
23
+
24
+ /** Build çıktısı ve ikon setleri taranmaz. */
25
+ const DEFAULT_SKIP = ["assets", "fonts"];
26
+
27
+ /** Yaygın kırılma noktaları; kaynaktan büyük olanlar elenir. */
28
+ const DEFAULT_WIDTHS = [400, 640, 960, 1280, 1920];
29
+
30
+ /** Retina ekranlarda bile bunun üstü israf. */
31
+ const MAX_WIDTH = 1920;
32
+
33
+ /**
34
+ * @typedef {{ width: number, height: number, hash: string,
35
+ * variants: { width: number, url: string }[] }} ImageEntry
36
+ */
37
+
38
+ /**
39
+ * @param {string} dir
40
+ * @param {Set<string>} skip
41
+ * @returns {string[]}
42
+ */
43
+ function collect(dir, skip) {
44
+ if (!fs.existsSync(dir)) return [];
45
+
46
+ /** @type {string[]} */
47
+ const files = [];
48
+
49
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
50
+ if (entry.isDirectory()) {
51
+ if (skip.has(entry.name)) continue;
52
+ files.push(...collect(path.join(dir, entry.name), skip));
53
+ } else if (SOURCE.test(entry.name)) {
54
+ files.push(path.join(dir, entry.name));
55
+ }
56
+ }
57
+
58
+ return files;
59
+ }
60
+
61
+ /**
62
+ * `…\public\hero\a.png` → `/hero/a.png`
63
+ * @param {string} file
64
+ * @returns {string}
65
+ */
66
+ function publicUrl(file) {
67
+ return `/${path.relative(paths.public, file).split(path.sep).join("/")}`;
68
+ }
69
+
70
+ /**
71
+ * Üretilecek genişlikler: kaynaktan büyük olanlar atılır, kaynağın kendi
72
+ * genişliği (MAX_WIDTH ile sınırlı) her zaman listeye girer.
73
+ *
74
+ * @param {number} intrinsic
75
+ * @param {number[]} widths
76
+ * @returns {number[]}
77
+ */
78
+ function targetWidths(intrinsic, widths) {
79
+ const capped = Math.min(intrinsic, MAX_WIDTH);
80
+ const out = widths.filter((width) => width < capped);
81
+ out.push(capped);
82
+ return out;
83
+ }
84
+
85
+ /**
86
+ * @param {import('../../config/index.js').ResolvedConfig} config
87
+ * @param {typeof import('sharp')} sharp
88
+ * @returns {Promise<Record<string, string>>} Ana manifest'e katkı yok; görsel
89
+ * manifest'i ayrı dosyaya yazılır.
90
+ */
91
+ export async function buildImages(config, sharp) {
92
+ const widths = config.images?.widths ?? DEFAULT_WIDTHS;
93
+ const quality = config.images?.quality ?? 78;
94
+ const encoder = `webp-q${quality}-e4`;
95
+ const webpOptions = { quality, effort: 4 };
96
+
97
+ const skip = new Set([...DEFAULT_SKIP, ...(config.images?.skip ?? [])]);
98
+ const manifestPath = path.join(paths.generated, "images.json");
99
+ const outDir = path.join(paths.assets, "img");
100
+
101
+ const sources = collect(paths.public, skip);
102
+ if (!sources.length) {
103
+ log.detail("no images, skipped");
104
+ return {};
105
+ }
106
+
107
+ fs.mkdirSync(outDir, { recursive: true });
108
+
109
+ /** @type {Record<string, ImageEntry>} */
110
+ let cached = {};
111
+ try {
112
+ const data = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
113
+ if (data.encoder === encoder) cached = data.images;
114
+ } catch {
115
+ // Manifest yok ya da kodlayıcı değişti: hepsi yeniden kodlanır.
116
+ }
117
+
118
+ /** @type {Record<string, ImageEntry>} */
119
+ const images = {};
120
+
121
+ let encoded = 0;
122
+ let sourceBytes = 0;
123
+ let outputBytes = 0;
124
+
125
+ /** @param {ImageEntry} entry */
126
+ const variantBytes = (entry) =>
127
+ entry.variants.reduce(
128
+ (sum, variant) =>
129
+ sum + fs.statSync(path.join(paths.public, variant.url.slice(1))).size,
130
+ 0,
131
+ );
132
+
133
+ for (const file of sources) {
134
+ const url = publicUrl(file);
135
+ const source = fs.readFileSync(file);
136
+ const digest = hash(source);
137
+ const previous = cached[url];
138
+
139
+ // Kaynak değişmediyse ve çıktılar hâlâ yerindeyse yeniden kodlamak
140
+ // boşa CPU; büyük bir public/ dizininde build süresini dakikalara çıkarır.
141
+ if (
142
+ previous?.hash === digest &&
143
+ previous.variants.every((variant) =>
144
+ fs.existsSync(path.join(paths.public, variant.url.slice(1))),
145
+ )
146
+ ) {
147
+ images[url] = previous;
148
+ sourceBytes += source.length;
149
+ outputBytes += variantBytes(previous);
150
+ continue;
151
+ }
152
+
153
+ try {
154
+ const entry = await encode(sharp, {
155
+ file,
156
+ source,
157
+ digest,
158
+ widths,
159
+ webpOptions,
160
+ outDir,
161
+ });
162
+ if (!entry) continue;
163
+
164
+ images[url] = entry;
165
+ encoded += 1;
166
+ sourceBytes += source.length;
167
+ outputBytes += variantBytes(entry);
168
+ } catch (error) {
169
+ // Bozuk/okunamayan tek bir görsel build'i düşürmesin: manifest'te yer
170
+ // almazsa orijinal dosya servis edilmeye devam eder.
171
+ log.warn(`${url} could not be optimized (${error.message})`);
172
+ }
173
+ }
174
+
175
+ pruneOutputs(
176
+ outDir,
177
+ new Set(
178
+ Object.values(images).flatMap((entry) =>
179
+ entry.variants.map((variant) => variant.url),
180
+ ),
181
+ ),
182
+ );
183
+
184
+ fs.mkdirSync(paths.generated, { recursive: true });
185
+ fs.writeFileSync(
186
+ manifestPath,
187
+ `${JSON.stringify({ encoder, images }, null, 2)}\n`,
188
+ );
189
+
190
+ const total = Object.keys(images).length;
191
+ const saved = sourceBytes - outputBytes;
192
+ log.detail(
193
+ `${total} images${encoded ? ` (${encoded} encoded)` : " (cached)"}, ` +
194
+ `${log.size(Math.max(saved, 0))} saved`,
195
+ );
196
+
197
+ return {};
198
+ }
199
+
200
+ /**
201
+ * Manifest'te artık geçmeyen eski çıktıları siler.
202
+ *
203
+ * @param {string} outDir
204
+ * @param {Set<string>} keep public URL kümesi
205
+ */
206
+ function pruneOutputs(outDir, keep) {
207
+ if (!fs.existsSync(outDir)) return;
208
+ for (const file of fs.readdirSync(outDir)) {
209
+ if (!keep.has(`/assets/img/${file}`)) {
210
+ fs.rmSync(path.join(outDir, file), { force: true });
211
+ }
212
+ }
213
+ }
214
+
215
+ /**
216
+ * @param {typeof import('sharp')} sharp
217
+ * @param {{ file: string, source: Buffer, digest: string, widths: number[],
218
+ * webpOptions: object, outDir: string }} job
219
+ * @returns {Promise<ImageEntry | null>}
220
+ */
221
+ async function encode(sharp, job) {
222
+ const { width, height } = await sharp(job.source, { failOn: "none" }).metadata();
223
+ if (!width || !height) return null;
224
+
225
+ const base = path.basename(job.file, path.extname(job.file));
226
+
227
+ /** @type {{ width: number, url: string }[]} */
228
+ const variants = [];
229
+
230
+ for (const target of targetWidths(width, job.widths)) {
231
+ const buffer = await sharp(job.source, { failOn: "none" })
232
+ .resize({ width: target, withoutEnlargement: true })
233
+ .webp(job.webpOptions)
234
+ .toBuffer();
235
+
236
+ // Hash kaynak + genişlikten türetilir: aynı içerik her build'de aynı
237
+ // dosya adını verir, `immutable` cache bayatlamaz.
238
+ const fileName = `${base}-${target}.${hash(`${job.digest}:${target}`)}.webp`;
239
+ fs.writeFileSync(path.join(job.outDir, fileName), buffer);
240
+ variants.push({ width: target, url: `/assets/img/${fileName}` });
241
+ }
242
+
243
+ return { width, height, hash: job.digest, variants };
244
+ }
@@ -1,78 +1,78 @@
1
- /**
2
- * Build çıktısı varlıkların brotli/gzip kopyalarını üretir.
3
- *
4
- * Yalnızca `public/assets/` kapsanır: oradaki dosyalar hash'li ve `immutable`,
5
- * yani içerikleri hiç değişmiyor ve her istekte yeniden sıkıştırmak boşa CPU.
6
- * Build'de bir kez kalite 11 ile sıkıştırmak hem sunucu yükünü sıfırlar hem de
7
- * çalışma anında göze alınamayacak bir oran verir (istek anındaki kalite 5'e
8
- * karşı). `public/` altındaki elle konmuş dosyalar küçük ve seyrek istendiği
9
- * için çalışma anındaki sıkıştırmaya bırakılır.
10
- *
11
- * `server/middleware/static-precompressed.js` bu dosyaları servis eder.
12
- */
13
- import fs from "node:fs";
14
- import path from "node:path";
15
- import zlib from "node:zlib";
16
- import { paths } from "../paths.mjs";
17
- import * as log from "../../log.mjs";
18
-
19
- /** Zaten sıkışık formatları (woff2, png, jpg, webp) tekrar sıkıştırmak anlamsız. */
20
- const COMPRESSIBLE = /\.(?:css|js|mjs|svg|json|xml|txt|map)$/i;
21
-
22
- /** Bu boyutun altında sıkıştırma kazancı başlık maliyetini karşılamıyor. */
23
- const MIN_BYTES = 1024;
24
-
25
- const BROTLI_OPTIONS = {
26
- params: {
27
- [zlib.constants.BROTLI_PARAM_QUALITY]: 11,
28
- [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
29
- },
30
- };
31
-
32
- /**
33
- * @param {string} dir
34
- * @returns {string[]}
35
- */
36
- function collect(dir) {
37
- if (!fs.existsSync(dir)) return [];
38
-
39
- /** @type {string[]} */
40
- const files = [];
41
-
42
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
43
- const full = path.join(dir, entry.name);
44
-
45
- if (entry.isDirectory()) files.push(...collect(full));
46
- else if (COMPRESSIBLE.test(entry.name)) files.push(full);
47
- }
48
-
49
- return files;
50
- }
51
-
52
- export async function precompressAssets() {
53
- // Önceki turdan kalan kopyalar kaynak değişince bayatlamasın.
54
- for (const file of collect(paths.assets)) {
55
- for (const ext of [".br", ".gz"]) {
56
- fs.rmSync(file + ext, { force: true });
57
- }
58
- }
59
-
60
- let count = 0;
61
- let saved = 0;
62
-
63
- for (const file of collect(paths.assets)) {
64
- const source = fs.readFileSync(file);
65
- if (source.length < MIN_BYTES) continue;
66
-
67
- const br = zlib.brotliCompressSync(source, BROTLI_OPTIONS);
68
- const gz = zlib.gzipSync(source, { level: 9 });
69
-
70
- fs.writeFileSync(`${file}.br`, br);
71
- fs.writeFileSync(`${file}.gz`, gz);
72
-
73
- count += 1;
74
- saved += source.length - br.length;
75
- }
76
-
77
- log.detail(`${count} files, ${log.size(saved)}`);
78
- }
1
+ /**
2
+ * Build çıktısı varlıkların brotli/gzip kopyalarını üretir.
3
+ *
4
+ * Yalnızca `public/assets/` kapsanır: oradaki dosyalar hash'li ve `immutable`,
5
+ * yani içerikleri hiç değişmiyor ve her istekte yeniden sıkıştırmak boşa CPU.
6
+ * Build'de bir kez kalite 11 ile sıkıştırmak hem sunucu yükünü sıfırlar hem de
7
+ * çalışma anında göze alınamayacak bir oran verir (istek anındaki kalite 5'e
8
+ * karşı). `public/` altındaki elle konmuş dosyalar küçük ve seyrek istendiği
9
+ * için çalışma anındaki sıkıştırmaya bırakılır.
10
+ *
11
+ * `server/middleware/static-precompressed.js` bu dosyaları servis eder.
12
+ */
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import zlib from "node:zlib";
16
+ import { paths } from "../paths.mjs";
17
+ import * as log from "../../log.mjs";
18
+
19
+ /** Zaten sıkışık formatları (woff2, png, jpg, webp) tekrar sıkıştırmak anlamsız. */
20
+ const COMPRESSIBLE = /\.(?:css|js|mjs|svg|json|xml|txt|map)$/i;
21
+
22
+ /** Bu boyutun altında sıkıştırma kazancı başlık maliyetini karşılamıyor. */
23
+ const MIN_BYTES = 1024;
24
+
25
+ const BROTLI_OPTIONS = {
26
+ params: {
27
+ [zlib.constants.BROTLI_PARAM_QUALITY]: 11,
28
+ [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
29
+ },
30
+ };
31
+
32
+ /**
33
+ * @param {string} dir
34
+ * @returns {string[]}
35
+ */
36
+ function collect(dir) {
37
+ if (!fs.existsSync(dir)) return [];
38
+
39
+ /** @type {string[]} */
40
+ const files = [];
41
+
42
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
43
+ const full = path.join(dir, entry.name);
44
+
45
+ if (entry.isDirectory()) files.push(...collect(full));
46
+ else if (COMPRESSIBLE.test(entry.name)) files.push(full);
47
+ }
48
+
49
+ return files;
50
+ }
51
+
52
+ export async function precompressAssets() {
53
+ // Önceki turdan kalan kopyalar kaynak değişince bayatlamasın.
54
+ for (const file of collect(paths.assets)) {
55
+ for (const ext of [".br", ".gz"]) {
56
+ fs.rmSync(file + ext, { force: true });
57
+ }
58
+ }
59
+
60
+ let count = 0;
61
+ let saved = 0;
62
+
63
+ for (const file of collect(paths.assets)) {
64
+ const source = fs.readFileSync(file);
65
+ if (source.length < MIN_BYTES) continue;
66
+
67
+ const br = zlib.brotliCompressSync(source, BROTLI_OPTIONS);
68
+ const gz = zlib.gzipSync(source, { level: 9 });
69
+
70
+ fs.writeFileSync(`${file}.br`, br);
71
+ fs.writeFileSync(`${file}.gz`, gz);
72
+
73
+ count += 1;
74
+ saved += source.length - br.length;
75
+ }
76
+
77
+ log.detail(`${count} files, ${log.size(saved)}`);
78
+ }