jskelet 0.2.3 → 0.2.5

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 (91) hide show
  1. package/AGENTS.md +132 -132
  2. package/CHANGELOG.md +15 -0
  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 +287 -287
  7. package/docs/03-routing.md +480 -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 +1209 -1202
  11. package/docs/08-build.md +366 -366
  12. package/docs/09-dev-araclari.md +335 -335
  13. package/docs/10-dagitim.md +329 -329
  14. package/docs/12-panel-ve-oturum.md +384 -384
  15. package/docs/README.md +105 -105
  16. package/docs/en/01-getting-started.md +292 -292
  17. package/docs/en/02-architecture.md +305 -305
  18. package/docs/en/03-routing.md +497 -497
  19. package/docs/en/04-rendering.md +504 -504
  20. package/docs/en/05-islands.md +492 -492
  21. package/docs/en/06-caching.md +1239 -1232
  22. package/docs/en/07-configuration.md +986 -986
  23. package/docs/en/08-build.md +383 -383
  24. package/docs/en/09-dev-tools.md +342 -342
  25. package/docs/en/10-deployment.md +332 -332
  26. package/docs/en/11-migration.md +359 -359
  27. package/docs/en/12-dashboards-and-sessions.md +392 -392
  28. package/docs/en/README.md +112 -112
  29. package/package.json +102 -102
  30. package/src/build/ensure-build.mjs +15 -15
  31. package/src/build/paths.mjs +143 -143
  32. package/src/build/resolve-peer.mjs +36 -36
  33. package/src/build/tasks/client.mjs +268 -268
  34. package/src/build/tasks/css.mjs +124 -124
  35. package/src/build/tasks/fonts.mjs +146 -146
  36. package/src/build/tasks/icons.mjs +224 -224
  37. package/src/build/tasks/images.mjs +244 -244
  38. package/src/build/tasks/precompress.mjs +78 -78
  39. package/src/client/cache-panel/i18n.js +670 -0
  40. package/src/client/cache-panel/login.html +74 -71
  41. package/src/client/cache-panel/panel.css +756 -740
  42. package/src/client/cache-panel/panel.html +308 -307
  43. package/src/client/cache-panel/panel.js +915 -808
  44. package/src/client/devtools/report.html +185 -185
  45. package/src/client/devtools/report.js +725 -725
  46. package/src/client/dom.js +95 -95
  47. package/src/client/form.js +192 -192
  48. package/src/client/index.js +35 -35
  49. package/src/client/registry.js +297 -297
  50. package/src/client/safe-image.js +91 -91
  51. package/src/client/store.js +36 -36
  52. package/src/client/swap.js +188 -188
  53. package/src/config/pattern.js +107 -107
  54. package/src/http/control-flow.js +71 -71
  55. package/src/http/cookies.js +257 -257
  56. package/src/http/request-cache.js +46 -46
  57. package/src/http/request-context.js +162 -162
  58. package/src/index.js +83 -83
  59. package/src/init.mjs +221 -221
  60. package/src/runtime/alias-hooks.mjs +119 -119
  61. package/src/runtime/register.mjs +4 -4
  62. package/src/server/assets.js +147 -147
  63. package/src/server/cache-deps.js +42 -42
  64. package/src/server/cache-panel.js +759 -738
  65. package/src/server/cloudflare.js +607 -595
  66. package/src/server/create-app.js +291 -291
  67. package/src/server/data-cache.js +462 -462
  68. package/src/server/dev/report.js +369 -369
  69. package/src/server/dev/socket.js +170 -170
  70. package/src/server/dev/version-check.mjs +139 -139
  71. package/src/server/html-cache.js +817 -817
  72. package/src/server/metadata.js +102 -102
  73. package/src/server/middleware/compression.js +205 -205
  74. package/src/server/middleware/csrf.js +134 -134
  75. package/src/server/middleware/dev-gate.js +62 -62
  76. package/src/server/middleware/headers.js +37 -37
  77. package/src/server/middleware/redirects.js +32 -32
  78. package/src/server/middleware/static-precompressed.js +100 -100
  79. package/src/server/middleware/upstream-proxy.js +141 -141
  80. package/src/server/prewarm.js +601 -601
  81. package/src/server/redis.js +569 -569
  82. package/src/server/router.js +128 -128
  83. package/src/server/status-page.js +164 -164
  84. package/src/server/upstream-limiter.js +376 -376
  85. package/src/server/upstream-tracking.js +166 -166
  86. package/src/start.mjs +7 -7
  87. package/src/templates/layout.ejs +44 -44
  88. package/src/version.mjs +31 -31
  89. package/src/views/components/loader.js +85 -85
  90. package/src/views/helpers/html.js +102 -102
  91. package/src/views/helpers/tags.js +245 -245
@@ -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
+ }