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,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
+ }