jskelet 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/AGENTS.md +127 -0
  2. package/CHANGELOG.md +40 -0
  3. package/LICENSE +21 -0
  4. package/README.md +342 -0
  5. package/bin/jskelet.mjs +104 -0
  6. package/docs/01-baslangic.md +285 -0
  7. package/docs/02-mimari.md +287 -0
  8. package/docs/03-routing.md +437 -0
  9. package/docs/04-render-ve-sablonlar.md +490 -0
  10. package/docs/05-islands.md +429 -0
  11. package/docs/06-cache.md +409 -0
  12. package/docs/07-yapilandirma.md +673 -0
  13. package/docs/08-build.md +366 -0
  14. package/docs/09-dev-araclari.md +302 -0
  15. package/docs/10-dagitim.md +329 -0
  16. package/docs/11-tasima.md +352 -0
  17. package/docs/README.md +82 -0
  18. package/package.json +97 -0
  19. package/src/build/build.mjs +138 -0
  20. package/src/build/ensure-build.mjs +15 -0
  21. package/src/build/paths.mjs +118 -0
  22. package/src/build/resolve-peer.mjs +36 -0
  23. package/src/build/tasks/client.mjs +268 -0
  24. package/src/build/tasks/css.mjs +124 -0
  25. package/src/build/tasks/fonts.mjs +146 -0
  26. package/src/build/tasks/icons.mjs +224 -0
  27. package/src/build/tasks/images.mjs +244 -0
  28. package/src/build/tasks/precompress.mjs +78 -0
  29. package/src/client/devtools/overlay.js +1763 -0
  30. package/src/client/devtools/report.html +185 -0
  31. package/src/client/devtools/report.js +712 -0
  32. package/src/client/dom.js +95 -0
  33. package/src/client/index.js +26 -0
  34. package/src/client/registry.js +223 -0
  35. package/src/client/safe-image.js +91 -0
  36. package/src/client/store.js +36 -0
  37. package/src/config/defaults.js +102 -0
  38. package/src/config/index.js +433 -0
  39. package/src/config/pattern.js +107 -0
  40. package/src/dev-server.mjs +383 -0
  41. package/src/http/control-flow.js +56 -0
  42. package/src/http/request-cache.js +46 -0
  43. package/src/index.js +35 -0
  44. package/src/init.mjs +220 -0
  45. package/src/log.mjs +332 -0
  46. package/src/logo.png +0 -0
  47. package/src/runtime/alias-hooks.mjs +119 -0
  48. package/src/runtime/register.mjs +4 -0
  49. package/src/server/assets.js +119 -0
  50. package/src/server/create-app.js +167 -0
  51. package/src/server/dev/devtools.js +383 -0
  52. package/src/server/dev/report.js +351 -0
  53. package/src/server/head-hints.js +132 -0
  54. package/src/server/html-cache.js +166 -0
  55. package/src/server/metadata.js +102 -0
  56. package/src/server/middleware/compression.js +205 -0
  57. package/src/server/middleware/dev-gate.js +62 -0
  58. package/src/server/middleware/headers.js +37 -0
  59. package/src/server/middleware/redirects.js +32 -0
  60. package/src/server/middleware/static-precompressed.js +100 -0
  61. package/src/server/middleware/upstream-proxy.js +141 -0
  62. package/src/server/prewarm.js +283 -0
  63. package/src/server/render.js +356 -0
  64. package/src/server/router.js +121 -0
  65. package/src/server/status-page.js +164 -0
  66. package/src/server/upstream-tracking.js +51 -0
  67. package/src/start.mjs +7 -0
  68. package/src/templates/layout.ejs +44 -0
  69. package/src/version.mjs +17 -0
  70. package/src/views/components/loader.js +85 -0
  71. package/src/views/helpers/html.js +102 -0
  72. package/src/views/helpers/tags.js +193 -0
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Phosphor SVG sprite üretimi.
3
+ *
4
+ * `@phosphor-icons/core` içindeki tek tek SVG'lerden, **yalnızca kaynakta
5
+ * kullanılan** ikonlar için `<symbol>` seti üretir. Tüm seti göndermek 1500+
6
+ * ikon, yani birkaç megabayt; kullanım taraması sprite'ı tipik olarak 10-30
7
+ * sembolde tutuyor.
8
+ *
9
+ * Sembol id'si: `<kebab-name>-<weight>` (örn. `arrow-right-bold`).
10
+ *
11
+ * Tarama statik metin üzerinden yapıldığı için adı çalışma anında hesaplanan
12
+ * bir `icon()` çağrısı sprite'a girmez. Bu yüzden ad taşıyan yapılandırma
13
+ * alanları (`icon: "XLogo"`) da ayrıca aranır ve `views/helpers/tags.js`
14
+ * dev'de eksik sembol için uyarır.
15
+ */
16
+ import fs from "node:fs";
17
+ import path from "node:path";
18
+ import { createRequire } from "node:module";
19
+ import { pruneAssets, writeAsset } from "../paths.mjs";
20
+ import * as log from "../../log.mjs";
21
+
22
+ const SCAN_EXTENSIONS = new Set([".ejs", ".js", ".mjs"]);
23
+
24
+ /** `icon({ … })` çağrısının tamamı; `name:` ifadesi ayrıca çözümlenir. */
25
+ const ICON_CALL = /icon\(\s*\{([^}]*)\}/g;
26
+ const ICON_NAME_EXPR = /name:\s*([^,}]+)/;
27
+ const ICON_WEIGHT = /weight:\s*["']([^"']+)["']/;
28
+ /** `data-icon="flag:fill"` ve JS nesnesindeki `"data-icon": "flag:fill"`. */
29
+ const ICON_ATTR = /data-icon"?\s*[:=]\s*["']([a-z0-9-]+)(?::([a-z]+))?["']/g;
30
+
31
+ /**
32
+ * İkon adı `icon()` çağrısına değişkenle geldiğinde (ör. `name: item.icon`)
33
+ * ad statik olarak görünmez. Bu tür adlar yapılandırma listelerinde
34
+ * `icon: "XLogo"` / `iconName: "XLogo"` biçiminde durur; sprite'a girmezlerse
35
+ * `<use>` boş kalır ve ikon görünmez.
36
+ */
37
+ const ICON_NAME_PROP = /\b(?:icon|iconName)\s*[:=]\s*["']([A-Z][A-Za-z0-9]*)["']/g;
38
+
39
+ /** Adın içinden çıkarılabilecek sabitler: `"X"`, `cond ? "A" : "B"`. */
40
+ const QUOTED_NAME = /["']([A-Z][A-Za-z0-9]*)["']/g;
41
+
42
+ const WEIGHTS = new Set(["thin", "light", "regular", "bold", "fill", "duotone"]);
43
+
44
+ /**
45
+ * `ArrowRightIcon` → `arrow-right`
46
+ * @param {string} name
47
+ * @returns {string}
48
+ */
49
+ function toKebab(name) {
50
+ return String(name)
51
+ .replace(/Icon$/, "")
52
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
53
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2")
54
+ .toLowerCase();
55
+ }
56
+
57
+ /**
58
+ * Paket, framework'ün değil **uygulamanın** node_modules'ünden çözülür:
59
+ * ikon seti uygulamanın devDependency'si.
60
+ *
61
+ * @param {string} root
62
+ * @returns {string | null}
63
+ */
64
+ function resolveIconAssets(root) {
65
+ const require = createRequire(path.join(root, "package.json"));
66
+
67
+ // Paketin `exports` haritası `./package.json` alt yolunu açmıyor, bu yüzden
68
+ // bilinen bir asset dosyası üzerinden çözülür.
69
+ try {
70
+ const probe = require.resolve(
71
+ "@phosphor-icons/core/assets/regular/house.svg",
72
+ );
73
+ return path.dirname(path.dirname(probe));
74
+ } catch {
75
+ // exports kapalıysa klasörü doğrudan ara.
76
+ }
77
+
78
+ const direct = path.join(
79
+ root,
80
+ "node_modules",
81
+ "@phosphor-icons",
82
+ "core",
83
+ "assets",
84
+ );
85
+
86
+ return fs.existsSync(direct) ? direct : null;
87
+ }
88
+
89
+ /**
90
+ * @param {string} dir
91
+ * @param {string[]} out
92
+ * @returns {string[]}
93
+ */
94
+ function collectFiles(dir, out = []) {
95
+ if (!fs.existsSync(dir)) return out;
96
+
97
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
98
+ const full = path.join(dir, entry.name);
99
+ if (entry.isDirectory()) {
100
+ collectFiles(full, out);
101
+ } else if (SCAN_EXTENSIONS.has(path.extname(entry.name))) {
102
+ out.push(full);
103
+ }
104
+ }
105
+
106
+ return out;
107
+ }
108
+
109
+ /**
110
+ * @param {string[]} scanDirs
111
+ * @returns {Set<string>} `name:weight` çiftleri
112
+ */
113
+ function scanUsedIcons(scanDirs) {
114
+ /** @type {Set<string>} */
115
+ const used = new Set();
116
+
117
+ // Adı değişkenle gelen çağrıların ağırlıkları: dolaylı bulunan adlar
118
+ // yalnızca bu ağırlıklarda üretilir, sprite gereksiz büyümez.
119
+ /** @type {Set<string>} */
120
+ const dynamicWeights = new Set();
121
+
122
+ /** @type {Set<string>} */
123
+ const indirectNames = new Set();
124
+
125
+ for (const dir of scanDirs) {
126
+ for (const file of collectFiles(dir)) {
127
+ const source = fs.readFileSync(file, "utf8");
128
+
129
+ for (const match of source.matchAll(ICON_CALL)) {
130
+ const raw = match[1].match(ICON_WEIGHT)?.[1] ?? "regular";
131
+ const weight = WEIGHTS.has(raw) ? raw : "regular";
132
+ const expression = match[1].match(ICON_NAME_EXPR)?.[1] ?? "";
133
+ const names = [...expression.matchAll(QUOTED_NAME)].map((m) => m[1]);
134
+
135
+ if (!names.length) {
136
+ dynamicWeights.add(weight);
137
+ continue;
138
+ }
139
+
140
+ for (const name of names) used.add(`${toKebab(name)}:${weight}`);
141
+ }
142
+
143
+ for (const match of source.matchAll(ICON_NAME_PROP)) {
144
+ indirectNames.add(toKebab(match[1]));
145
+ }
146
+
147
+ for (const match of source.matchAll(ICON_ATTR)) {
148
+ const weight = match[2] ?? "regular";
149
+ used.add(`${match[1]}:${WEIGHTS.has(weight) ? weight : "regular"}`);
150
+ }
151
+ }
152
+ }
153
+
154
+ if (!dynamicWeights.size) dynamicWeights.add("regular");
155
+
156
+ for (const name of indirectNames) {
157
+ for (const weight of dynamicWeights) used.add(`${name}:${weight}`);
158
+ }
159
+
160
+ return used;
161
+ }
162
+
163
+ /**
164
+ * @param {string} coreAssets
165
+ * @param {string} name kebab
166
+ * @param {string} weight
167
+ * @returns {string | null}
168
+ */
169
+ function readIconBody(coreAssets, name, weight) {
170
+ const fileName = weight === "regular" ? `${name}.svg` : `${name}-${weight}.svg`;
171
+ const filePath = path.join(coreAssets, weight, fileName);
172
+
173
+ if (!fs.existsSync(filePath)) return null;
174
+
175
+ const svg = fs.readFileSync(filePath, "utf8");
176
+ const inner = svg.replace(/^[\s\S]*?<svg[^>]*>/, "").replace(/<\/svg>\s*$/, "");
177
+ return inner.trim();
178
+ }
179
+
180
+ /**
181
+ * @param {import('../../config/index.js').ResolvedConfig} config
182
+ * @returns {Promise<Record<string, string>>}
183
+ */
184
+ export async function buildIconSprite(config) {
185
+ const coreAssets = resolveIconAssets(config.root);
186
+ if (!coreAssets) {
187
+ log.detail("@phosphor-icons/core kurulu değil, atlandı");
188
+ return {};
189
+ }
190
+
191
+ const scanDirs = (
192
+ config.icons?.scan ?? ["views", "client", "routes", "lib"]
193
+ ).map((dir) => path.resolve(config.root, dir));
194
+
195
+ pruneAssets(["sprite."]);
196
+
197
+ const used = [...scanUsedIcons(scanDirs)].sort();
198
+ const symbols = [];
199
+ const missing = [];
200
+
201
+ for (const entry of used) {
202
+ const [name, weight] = entry.split(":");
203
+ const body = readIconBody(coreAssets, name, weight);
204
+
205
+ if (!body) {
206
+ missing.push(entry);
207
+ continue;
208
+ }
209
+
210
+ symbols.push(
211
+ `<symbol id="${name}-${weight}" viewBox="0 0 256 256">${body}</symbol>`,
212
+ );
213
+ }
214
+
215
+ const sprite = `<svg xmlns="http://www.w3.org/2000/svg" style="display:none">${symbols.join("")}</svg>`;
216
+ const url = writeAsset("sprite.svg", sprite);
217
+
218
+ log.detail(`${symbols.length} symbols`);
219
+ if (missing.length) {
220
+ log.warn(`${missing.length} icons missing → ${missing.join(", ")}`);
221
+ }
222
+
223
+ return { "sprite.svg": url };
224
+ }
@@ -0,0 +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("görsel yok, atlandı");
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} optimize edilemedi (${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
+ }
@@ -0,0 +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
+ }