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,357 +1,357 @@
1
- /**
2
- * SVG ikon sprite üretimi.
3
- *
4
- * Kaynak XOR seçilir: uygulama kökünde `icons/` (veya `icons.dir`) dizini
5
- * varsa yalnızca oradaki düz SVG'ler; yoksa `@phosphor-icons/core`. İkisi
6
- * birleştirilmez — boş bir `icons/` dizini Phosphor'a düşmez.
7
- *
8
- * Yalnızca kaynakta kullanılan ikonlar `<symbol>` olur. Tüm seti göndermek
9
- * 1500+ ikon, yani birkaç megabayt; kullanım taraması sprite'ı tipik olarak
10
- * 10-30 sembolde tutuyor. Çıktı `public/assets/` altında hash'li
11
- * `sprite.svg` olduğu için mevcut precompress kapsamına girer.
12
- *
13
- * Sembol id'si: `<kebab-name>-<weight>` (örn. `arrow-right-bold`).
14
- * Yerel dosya adı: `house.svg` → `house:regular`, `house-bold.svg` → `house:bold`.
15
- *
16
- * Tarama statik metin üzerinden yapıldığı için adı çalışma anında hesaplanan
17
- * bir `icon()` çağrısı sprite'a girmez. Bu yüzden ad taşıyan yapılandırma
18
- * alanları (`icon: "XLogo"`) da ayrıca aranır ve `views/helpers/tags.js`
19
- * dev'de eksik sembol için uyarır.
20
- */
21
- import fs from "node:fs";
22
- import path from "node:path";
23
- import { createRequire } from "node:module";
24
- import { pruneAssets, writeAsset } from "../paths.mjs";
25
- import * as log from "../../log.mjs";
26
-
27
- const SCAN_EXTENSIONS = new Set([".ejs", ".jsk", ".js", ".mjs", ".ts", ".mts"]);
28
-
29
- /** `icon({ … })` çağrısının tamamı; `name:` ifadesi ayrıca çözümlenir. */
30
- const ICON_CALL = /icon\(\s*\{([^}]*)\}/g;
31
- const ICON_NAME_EXPR = /name:\s*([^,}]+)/;
32
- const ICON_WEIGHT = /weight:\s*["']([^"']+)["']/;
33
- /** `.jsk` / JSX tarzı `<Icon name="Moon" />` ve isteğe bağlı `weight="bold"`. */
34
- const ICON_TAG =
35
- /<Icon\b[^>]*\bname=["']([A-Z][A-Za-z0-9]*)["'][^>]*(?:\bweight=["']([a-z]+)["'])?/gi;
36
- /** `data-icon="flag:fill"` ve JS nesnesindeki `"data-icon": "flag:fill"`. */
37
- const ICON_ATTR = /data-icon"?\s*[:=]\s*["']([a-z0-9-]+)(?::([a-z]+))?["']/g;
38
-
39
- /**
40
- * İkon adı `icon()` çağrısına değişkenle geldiğinde (ör. `name: item.icon`)
41
- * ad statik olarak görünmez. Bu tür adlar yapılandırma listelerinde
42
- * `icon: "XLogo"` / `iconName: "XLogo"` biçiminde durur; sprite'a girmezlerse
43
- * `<use>` boş kalır ve ikon görünmez.
44
- */
45
- const ICON_NAME_PROP = /\b(?:icon|iconName)\s*[:=]\s*["']([A-Z][A-Za-z0-9]*)["']/g;
46
-
47
- /** Adın içinden çıkarılabilecek sabitler: `"X"`, `cond ? "A" : "B"`. */
48
- const QUOTED_NAME = /["']([A-Z][A-Za-z0-9]*)["']/g;
49
-
50
- const WEIGHTS = new Set(["thin", "light", "regular", "bold", "fill", "duotone"]);
51
-
52
- const DEFAULT_VIEWBOX = "0 0 256 256";
53
-
54
- /**
55
- * `ArrowRightIcon` → `arrow-right`
56
- * @param {string} name
57
- * @returns {string}
58
- */
59
- function toKebab(name) {
60
- return String(name)
61
- .replace(/Icon$/, "")
62
- .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
63
- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2")
64
- .toLowerCase();
65
- }
66
-
67
- /**
68
- * Düz dizin dosya adı → `name` + `weight`.
69
- * `house.svg` / `house-regular.svg` → regular; `arrow-right-bold.svg` → bold.
70
- *
71
- * @param {string} fileName uzantılı veya uzantısız
72
- * @returns {{ name: string, weight: string } | null}
73
- */
74
- export function parseIconFileName(fileName) {
75
- const base = String(fileName).replace(/\.svg$/i, "");
76
- if (!base) return null;
77
-
78
- let name = base;
79
- let weight = "regular";
80
-
81
- const dash = base.lastIndexOf("-");
82
- if (dash > 0) {
83
- const maybeWeight = base.slice(dash + 1);
84
- if (WEIGHTS.has(maybeWeight)) {
85
- name = base.slice(0, dash);
86
- weight = maybeWeight;
87
- }
88
- }
89
-
90
- // kebab: harf/rakam segmentleri, başta/sonda tire yok
91
- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) return null;
92
-
93
- return { name, weight };
94
- }
95
-
96
- /**
97
- * @param {import('../../config/index.js').ResolvedConfig} config
98
- * @returns {string | null} mutlak dizin; yoksa veya dizin değilse null
99
- */
100
- function resolveLocalIconsDir(config) {
101
- const relative = config.icons?.dir ?? "icons";
102
- const dir = path.resolve(config.root, relative);
103
- try {
104
- if (fs.statSync(dir).isDirectory()) return dir;
105
- } catch {
106
- // yok
107
- }
108
- return null;
109
- }
110
-
111
- /**
112
- * Paket, framework'ün değil **uygulamanın** node_modules'ünden çözülür:
113
- * ikon seti uygulamanın devDependency'si.
114
- *
115
- * @param {string} root
116
- * @returns {string | null}
117
- */
118
- function resolveIconAssets(root) {
119
- const require = createRequire(path.join(root, "package.json"));
120
-
121
- // Paketin `exports` haritası `./package.json` alt yolunu açmıyor, bu yüzden
122
- // bilinen bir asset dosyası üzerinden çözülür.
123
- try {
124
- const probe = require.resolve(
125
- "@phosphor-icons/core/assets/regular/house.svg",
126
- );
127
- return path.dirname(path.dirname(probe));
128
- } catch {
129
- // exports kapalıysa klasörü doğrudan ara.
130
- }
131
-
132
- const direct = path.join(
133
- root,
134
- "node_modules",
135
- "@phosphor-icons",
136
- "core",
137
- "assets",
138
- );
139
-
140
- return fs.existsSync(direct) ? direct : null;
141
- }
142
-
143
- /**
144
- * @param {string} dir
145
- * @param {string[]} out
146
- * @returns {string[]}
147
- */
148
- function collectFiles(dir, out = []) {
149
- if (!fs.existsSync(dir)) return out;
150
-
151
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
152
- const full = path.join(dir, entry.name);
153
- if (entry.isDirectory()) {
154
- collectFiles(full, out);
155
- } else if (SCAN_EXTENSIONS.has(path.extname(entry.name))) {
156
- out.push(full);
157
- }
158
- }
159
-
160
- return out;
161
- }
162
-
163
- /**
164
- * @param {string[]} scanDirs
165
- * @returns {Set<string>} `name:weight` çiftleri
166
- */
167
- function scanUsedIcons(scanDirs) {
168
- /** @type {Set<string>} */
169
- const used = new Set();
170
-
171
- // Adı değişkenle gelen çağrıların ağırlıkları: dolaylı bulunan adlar
172
- // yalnızca bu ağırlıklarda üretilir, sprite gereksiz büyümez.
173
- /** @type {Set<string>} */
174
- const dynamicWeights = new Set();
175
-
176
- /** @type {Set<string>} */
177
- const indirectNames = new Set();
178
-
179
- for (const dir of scanDirs) {
180
- for (const file of collectFiles(dir)) {
181
- const source = fs.readFileSync(file, "utf8");
182
-
183
- for (const match of source.matchAll(ICON_CALL)) {
184
- const raw = match[1].match(ICON_WEIGHT)?.[1] ?? "regular";
185
- const weight = WEIGHTS.has(raw) ? raw : "regular";
186
- const expression = match[1].match(ICON_NAME_EXPR)?.[1] ?? "";
187
- const names = [...expression.matchAll(QUOTED_NAME)].map((m) => m[1]);
188
-
189
- if (!names.length) {
190
- dynamicWeights.add(weight);
191
- continue;
192
- }
193
-
194
- for (const name of names) used.add(`${toKebab(name)}:${weight}`);
195
- }
196
-
197
- for (const match of source.matchAll(ICON_TAG)) {
198
- const weight = match[2] ?? "regular";
199
- used.add(
200
- `${toKebab(match[1])}:${WEIGHTS.has(weight) ? weight : "regular"}`,
201
- );
202
- }
203
-
204
- for (const match of source.matchAll(ICON_NAME_PROP)) {
205
- indirectNames.add(toKebab(match[1]));
206
- }
207
-
208
- for (const match of source.matchAll(ICON_ATTR)) {
209
- const weight = match[2] ?? "regular";
210
- used.add(`${match[1]}:${WEIGHTS.has(weight) ? weight : "regular"}`);
211
- }
212
- }
213
- }
214
-
215
- if (!dynamicWeights.size) dynamicWeights.add("regular");
216
-
217
- for (const name of indirectNames) {
218
- for (const weight of dynamicWeights) used.add(`${name}:${weight}`);
219
- }
220
-
221
- return used;
222
- }
223
-
224
- /**
225
- * @param {string} svg
226
- * @returns {{ body: string, viewBox: string }}
227
- */
228
- function parseSvgParts(svg) {
229
- const open = svg.match(/<svg\b[^>]*>/i)?.[0] ?? "";
230
- const viewBox =
231
- open.match(/\bviewBox\s*=\s*["']([^"']+)["']/i)?.[1]?.trim() ||
232
- DEFAULT_VIEWBOX;
233
- const body = svg
234
- .replace(/^[\s\S]*?<svg[^>]*>/i, "")
235
- .replace(/<\/svg>\s*$/i, "")
236
- .trim();
237
- return { body, viewBox };
238
- }
239
-
240
- /**
241
- * Düz `icons/` altındaki `*.svg` dosyalarından `name:weight` → parça haritası.
242
- *
243
- * @param {string} dir
244
- * @returns {Map<string, { body: string, viewBox: string }>}
245
- */
246
- function indexLocalIcons(dir) {
247
- /** @type {Map<string, { body: string, viewBox: string }>} */
248
- const index = new Map();
249
-
250
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
251
- if (!entry.isFile() || path.extname(entry.name).toLowerCase() !== ".svg") {
252
- continue;
253
- }
254
-
255
- const parsed = parseIconFileName(entry.name);
256
- if (!parsed) {
257
- log.warn(`icon file ignored (bad name) → ${entry.name}`);
258
- continue;
259
- }
260
-
261
- const key = `${parsed.name}:${parsed.weight}`;
262
- const svg = fs.readFileSync(path.join(dir, entry.name), "utf8");
263
- index.set(key, parseSvgParts(svg));
264
- }
265
-
266
- return index;
267
- }
268
-
269
- /**
270
- * @param {string} coreAssets
271
- * @param {string} name kebab
272
- * @param {string} weight
273
- * @returns {{ body: string, viewBox: string } | null}
274
- */
275
- function readPhosphorIcon(coreAssets, name, weight) {
276
- const fileName = weight === "regular" ? `${name}.svg` : `${name}-${weight}.svg`;
277
- const filePath = path.join(coreAssets, weight, fileName);
278
-
279
- if (!fs.existsSync(filePath)) return null;
280
-
281
- return parseSvgParts(fs.readFileSync(filePath, "utf8"));
282
- }
283
-
284
- /**
285
- * @param {Map<string, { body: string, viewBox: string }>} index
286
- * @param {string} name
287
- * @param {string} weight
288
- * @returns {{ body: string, viewBox: string } | null}
289
- */
290
- function readLocalIcon(index, name, weight) {
291
- const exact = index.get(`${name}:${weight}`);
292
- if (exact) return exact;
293
-
294
- // `house.svg` regular sayılır; tarama `house:regular` ister.
295
- if (weight === "regular") return index.get(`${name}:regular`) ?? null;
296
-
297
- return null;
298
- }
299
-
300
- /**
301
- * @param {import('../../config/index.js').ResolvedConfig} config
302
- * @returns {Promise<Record<string, string>>}
303
- */
304
- export async function buildIconSprite(config) {
305
- const localDir = resolveLocalIconsDir(config);
306
- /** @type {Map<string, { body: string, viewBox: string }> | null} */
307
- let localIndex = null;
308
- /** @type {string | null} */
309
- let coreAssets = null;
310
-
311
- if (localDir) {
312
- localIndex = indexLocalIcons(localDir);
313
- const rel = path.relative(config.root, localDir) || ".";
314
- log.detail(`icons from ${rel} (${localIndex.size} files)`);
315
- } else {
316
- coreAssets = resolveIconAssets(config.root);
317
- if (!coreAssets) {
318
- log.detail("@phosphor-icons/core not installed, skipped");
319
- return {};
320
- }
321
- }
322
-
323
- const scanDirs = (
324
- config.icons?.scan ?? ["views", "client", "routes", "lib", "features", "shared"]
325
- ).map((dir) => path.resolve(config.root, dir));
326
-
327
- const used = [...scanUsedIcons(scanDirs)].sort();
328
- const symbols = [];
329
- const missing = [];
330
-
331
- for (const entry of used) {
332
- const [name, weight] = entry.split(":");
333
- const parts = localIndex
334
- ? readLocalIcon(localIndex, name, weight)
335
- : readPhosphorIcon(/** @type {string} */ (coreAssets), name, weight);
336
-
337
- if (!parts?.body) {
338
- missing.push(entry);
339
- continue;
340
- }
341
-
342
- symbols.push(
343
- `<symbol id="${name}-${weight}" viewBox="${parts.viewBox}">${parts.body}</symbol>`,
344
- );
345
- }
346
-
347
- const sprite = `<svg xmlns="http://www.w3.org/2000/svg" style="display:none">${symbols.join("")}</svg>`;
348
- const url = writeAsset("sprite.svg", sprite);
349
- pruneAssets(["sprite."], { keep: [path.basename(url)] });
350
-
351
- log.detail(`${symbols.length} symbols`);
352
- if (missing.length) {
353
- log.warn(`${missing.length} icons missing → ${missing.join(", ")}`);
354
- }
355
-
356
- return { "sprite.svg": url };
357
- }
1
+ /**
2
+ * SVG ikon sprite üretimi.
3
+ *
4
+ * Kaynak XOR seçilir: uygulama kökünde `icons/` (veya `icons.dir`) dizini
5
+ * varsa yalnızca oradaki düz SVG'ler; yoksa `@phosphor-icons/core`. İkisi
6
+ * birleştirilmez — boş bir `icons/` dizini Phosphor'a düşmez.
7
+ *
8
+ * Yalnızca kaynakta kullanılan ikonlar `<symbol>` olur. Tüm seti göndermek
9
+ * 1500+ ikon, yani birkaç megabayt; kullanım taraması sprite'ı tipik olarak
10
+ * 10-30 sembolde tutuyor. Çıktı `public/assets/` altında hash'li
11
+ * `sprite.svg` olduğu için mevcut precompress kapsamına girer.
12
+ *
13
+ * Sembol id'si: `<kebab-name>-<weight>` (örn. `arrow-right-bold`).
14
+ * Yerel dosya adı: `house.svg` → `house:regular`, `house-bold.svg` → `house:bold`.
15
+ *
16
+ * Tarama statik metin üzerinden yapıldığı için adı çalışma anında hesaplanan
17
+ * bir `icon()` çağrısı sprite'a girmez. Bu yüzden ad taşıyan yapılandırma
18
+ * alanları (`icon: "XLogo"`) da ayrıca aranır ve `views/helpers/tags.js`
19
+ * dev'de eksik sembol için uyarır.
20
+ */
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+ import { createRequire } from "node:module";
24
+ import { pruneAssets, writeAsset } from "../paths.mjs";
25
+ import * as log from "../../log.mjs";
26
+
27
+ const SCAN_EXTENSIONS = new Set([".ejs", ".jsk", ".js", ".mjs", ".ts", ".mts"]);
28
+
29
+ /** `icon({ … })` çağrısının tamamı; `name:` ifadesi ayrıca çözümlenir. */
30
+ const ICON_CALL = /icon\(\s*\{([^}]*)\}/g;
31
+ const ICON_NAME_EXPR = /name:\s*([^,}]+)/;
32
+ const ICON_WEIGHT = /weight:\s*["']([^"']+)["']/;
33
+ /** `.jsk` / JSX tarzı `<Icon name="Moon" />` ve isteğe bağlı `weight="bold"`. */
34
+ const ICON_TAG =
35
+ /<Icon\b[^>]*\bname=["']([A-Z][A-Za-z0-9]*)["'][^>]*(?:\bweight=["']([a-z]+)["'])?/gi;
36
+ /** `data-icon="flag:fill"` ve JS nesnesindeki `"data-icon": "flag:fill"`. */
37
+ const ICON_ATTR = /data-icon"?\s*[:=]\s*["']([a-z0-9-]+)(?::([a-z]+))?["']/g;
38
+
39
+ /**
40
+ * İkon adı `icon()` çağrısına değişkenle geldiğinde (ör. `name: item.icon`)
41
+ * ad statik olarak görünmez. Bu tür adlar yapılandırma listelerinde
42
+ * `icon: "XLogo"` / `iconName: "XLogo"` biçiminde durur; sprite'a girmezlerse
43
+ * `<use>` boş kalır ve ikon görünmez.
44
+ */
45
+ const ICON_NAME_PROP = /\b(?:icon|iconName)\s*[:=]\s*["']([A-Z][A-Za-z0-9]*)["']/g;
46
+
47
+ /** Adın içinden çıkarılabilecek sabitler: `"X"`, `cond ? "A" : "B"`. */
48
+ const QUOTED_NAME = /["']([A-Z][A-Za-z0-9]*)["']/g;
49
+
50
+ const WEIGHTS = new Set(["thin", "light", "regular", "bold", "fill", "duotone"]);
51
+
52
+ const DEFAULT_VIEWBOX = "0 0 256 256";
53
+
54
+ /**
55
+ * `ArrowRightIcon` → `arrow-right`
56
+ * @param {string} name
57
+ * @returns {string}
58
+ */
59
+ function toKebab(name) {
60
+ return String(name)
61
+ .replace(/Icon$/, "")
62
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
63
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2")
64
+ .toLowerCase();
65
+ }
66
+
67
+ /**
68
+ * Düz dizin dosya adı → `name` + `weight`.
69
+ * `house.svg` / `house-regular.svg` → regular; `arrow-right-bold.svg` → bold.
70
+ *
71
+ * @param {string} fileName uzantılı veya uzantısız
72
+ * @returns {{ name: string, weight: string } | null}
73
+ */
74
+ export function parseIconFileName(fileName) {
75
+ const base = String(fileName).replace(/\.svg$/i, "");
76
+ if (!base) return null;
77
+
78
+ let name = base;
79
+ let weight = "regular";
80
+
81
+ const dash = base.lastIndexOf("-");
82
+ if (dash > 0) {
83
+ const maybeWeight = base.slice(dash + 1);
84
+ if (WEIGHTS.has(maybeWeight)) {
85
+ name = base.slice(0, dash);
86
+ weight = maybeWeight;
87
+ }
88
+ }
89
+
90
+ // kebab: harf/rakam segmentleri, başta/sonda tire yok
91
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) return null;
92
+
93
+ return { name, weight };
94
+ }
95
+
96
+ /**
97
+ * @param {import('../../config/index.js').ResolvedConfig} config
98
+ * @returns {string | null} mutlak dizin; yoksa veya dizin değilse null
99
+ */
100
+ function resolveLocalIconsDir(config) {
101
+ const relative = config.icons?.dir ?? "icons";
102
+ const dir = path.resolve(config.root, relative);
103
+ try {
104
+ if (fs.statSync(dir).isDirectory()) return dir;
105
+ } catch {
106
+ // yok
107
+ }
108
+ return null;
109
+ }
110
+
111
+ /**
112
+ * Paket, framework'ün değil **uygulamanın** node_modules'ünden çözülür:
113
+ * ikon seti uygulamanın devDependency'si.
114
+ *
115
+ * @param {string} root
116
+ * @returns {string | null}
117
+ */
118
+ function resolveIconAssets(root) {
119
+ const require = createRequire(path.join(root, "package.json"));
120
+
121
+ // Paketin `exports` haritası `./package.json` alt yolunu açmıyor, bu yüzden
122
+ // bilinen bir asset dosyası üzerinden çözülür.
123
+ try {
124
+ const probe = require.resolve(
125
+ "@phosphor-icons/core/assets/regular/house.svg",
126
+ );
127
+ return path.dirname(path.dirname(probe));
128
+ } catch {
129
+ // exports kapalıysa klasörü doğrudan ara.
130
+ }
131
+
132
+ const direct = path.join(
133
+ root,
134
+ "node_modules",
135
+ "@phosphor-icons",
136
+ "core",
137
+ "assets",
138
+ );
139
+
140
+ return fs.existsSync(direct) ? direct : null;
141
+ }
142
+
143
+ /**
144
+ * @param {string} dir
145
+ * @param {string[]} out
146
+ * @returns {string[]}
147
+ */
148
+ function collectFiles(dir, out = []) {
149
+ if (!fs.existsSync(dir)) return out;
150
+
151
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
152
+ const full = path.join(dir, entry.name);
153
+ if (entry.isDirectory()) {
154
+ collectFiles(full, out);
155
+ } else if (SCAN_EXTENSIONS.has(path.extname(entry.name))) {
156
+ out.push(full);
157
+ }
158
+ }
159
+
160
+ return out;
161
+ }
162
+
163
+ /**
164
+ * @param {string[]} scanDirs
165
+ * @returns {Set<string>} `name:weight` çiftleri
166
+ */
167
+ function scanUsedIcons(scanDirs) {
168
+ /** @type {Set<string>} */
169
+ const used = new Set();
170
+
171
+ // Adı değişkenle gelen çağrıların ağırlıkları: dolaylı bulunan adlar
172
+ // yalnızca bu ağırlıklarda üretilir, sprite gereksiz büyümez.
173
+ /** @type {Set<string>} */
174
+ const dynamicWeights = new Set();
175
+
176
+ /** @type {Set<string>} */
177
+ const indirectNames = new Set();
178
+
179
+ for (const dir of scanDirs) {
180
+ for (const file of collectFiles(dir)) {
181
+ const source = fs.readFileSync(file, "utf8");
182
+
183
+ for (const match of source.matchAll(ICON_CALL)) {
184
+ const raw = match[1].match(ICON_WEIGHT)?.[1] ?? "regular";
185
+ const weight = WEIGHTS.has(raw) ? raw : "regular";
186
+ const expression = match[1].match(ICON_NAME_EXPR)?.[1] ?? "";
187
+ const names = [...expression.matchAll(QUOTED_NAME)].map((m) => m[1]);
188
+
189
+ if (!names.length) {
190
+ dynamicWeights.add(weight);
191
+ continue;
192
+ }
193
+
194
+ for (const name of names) used.add(`${toKebab(name)}:${weight}`);
195
+ }
196
+
197
+ for (const match of source.matchAll(ICON_TAG)) {
198
+ const weight = match[2] ?? "regular";
199
+ used.add(
200
+ `${toKebab(match[1])}:${WEIGHTS.has(weight) ? weight : "regular"}`,
201
+ );
202
+ }
203
+
204
+ for (const match of source.matchAll(ICON_NAME_PROP)) {
205
+ indirectNames.add(toKebab(match[1]));
206
+ }
207
+
208
+ for (const match of source.matchAll(ICON_ATTR)) {
209
+ const weight = match[2] ?? "regular";
210
+ used.add(`${match[1]}:${WEIGHTS.has(weight) ? weight : "regular"}`);
211
+ }
212
+ }
213
+ }
214
+
215
+ if (!dynamicWeights.size) dynamicWeights.add("regular");
216
+
217
+ for (const name of indirectNames) {
218
+ for (const weight of dynamicWeights) used.add(`${name}:${weight}`);
219
+ }
220
+
221
+ return used;
222
+ }
223
+
224
+ /**
225
+ * @param {string} svg
226
+ * @returns {{ body: string, viewBox: string }}
227
+ */
228
+ function parseSvgParts(svg) {
229
+ const open = svg.match(/<svg\b[^>]*>/i)?.[0] ?? "";
230
+ const viewBox =
231
+ open.match(/\bviewBox\s*=\s*["']([^"']+)["']/i)?.[1]?.trim() ||
232
+ DEFAULT_VIEWBOX;
233
+ const body = svg
234
+ .replace(/^[\s\S]*?<svg[^>]*>/i, "")
235
+ .replace(/<\/svg>\s*$/i, "")
236
+ .trim();
237
+ return { body, viewBox };
238
+ }
239
+
240
+ /**
241
+ * Düz `icons/` altındaki `*.svg` dosyalarından `name:weight` → parça haritası.
242
+ *
243
+ * @param {string} dir
244
+ * @returns {Map<string, { body: string, viewBox: string }>}
245
+ */
246
+ function indexLocalIcons(dir) {
247
+ /** @type {Map<string, { body: string, viewBox: string }>} */
248
+ const index = new Map();
249
+
250
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
251
+ if (!entry.isFile() || path.extname(entry.name).toLowerCase() !== ".svg") {
252
+ continue;
253
+ }
254
+
255
+ const parsed = parseIconFileName(entry.name);
256
+ if (!parsed) {
257
+ log.warn(`icon file ignored (bad name) → ${entry.name}`);
258
+ continue;
259
+ }
260
+
261
+ const key = `${parsed.name}:${parsed.weight}`;
262
+ const svg = fs.readFileSync(path.join(dir, entry.name), "utf8");
263
+ index.set(key, parseSvgParts(svg));
264
+ }
265
+
266
+ return index;
267
+ }
268
+
269
+ /**
270
+ * @param {string} coreAssets
271
+ * @param {string} name kebab
272
+ * @param {string} weight
273
+ * @returns {{ body: string, viewBox: string } | null}
274
+ */
275
+ function readPhosphorIcon(coreAssets, name, weight) {
276
+ const fileName = weight === "regular" ? `${name}.svg` : `${name}-${weight}.svg`;
277
+ const filePath = path.join(coreAssets, weight, fileName);
278
+
279
+ if (!fs.existsSync(filePath)) return null;
280
+
281
+ return parseSvgParts(fs.readFileSync(filePath, "utf8"));
282
+ }
283
+
284
+ /**
285
+ * @param {Map<string, { body: string, viewBox: string }>} index
286
+ * @param {string} name
287
+ * @param {string} weight
288
+ * @returns {{ body: string, viewBox: string } | null}
289
+ */
290
+ function readLocalIcon(index, name, weight) {
291
+ const exact = index.get(`${name}:${weight}`);
292
+ if (exact) return exact;
293
+
294
+ // `house.svg` regular sayılır; tarama `house:regular` ister.
295
+ if (weight === "regular") return index.get(`${name}:regular`) ?? null;
296
+
297
+ return null;
298
+ }
299
+
300
+ /**
301
+ * @param {import('../../config/index.js').ResolvedConfig} config
302
+ * @returns {Promise<Record<string, string>>}
303
+ */
304
+ export async function buildIconSprite(config) {
305
+ const localDir = resolveLocalIconsDir(config);
306
+ /** @type {Map<string, { body: string, viewBox: string }> | null} */
307
+ let localIndex = null;
308
+ /** @type {string | null} */
309
+ let coreAssets = null;
310
+
311
+ if (localDir) {
312
+ localIndex = indexLocalIcons(localDir);
313
+ const rel = path.relative(config.root, localDir) || ".";
314
+ log.detail(`icons from ${rel} (${localIndex.size} files)`);
315
+ } else {
316
+ coreAssets = resolveIconAssets(config.root);
317
+ if (!coreAssets) {
318
+ log.detail("@phosphor-icons/core not installed, skipped");
319
+ return {};
320
+ }
321
+ }
322
+
323
+ const scanDirs = (
324
+ config.icons?.scan ?? ["views", "client", "routes", "lib", "features", "shared"]
325
+ ).map((dir) => path.resolve(config.root, dir));
326
+
327
+ const used = [...scanUsedIcons(scanDirs)].sort();
328
+ const symbols = [];
329
+ const missing = [];
330
+
331
+ for (const entry of used) {
332
+ const [name, weight] = entry.split(":");
333
+ const parts = localIndex
334
+ ? readLocalIcon(localIndex, name, weight)
335
+ : readPhosphorIcon(/** @type {string} */ (coreAssets), name, weight);
336
+
337
+ if (!parts?.body) {
338
+ missing.push(entry);
339
+ continue;
340
+ }
341
+
342
+ symbols.push(
343
+ `<symbol id="${name}-${weight}" viewBox="${parts.viewBox}">${parts.body}</symbol>`,
344
+ );
345
+ }
346
+
347
+ const sprite = `<svg xmlns="http://www.w3.org/2000/svg" style="display:none">${symbols.join("")}</svg>`;
348
+ const url = writeAsset("sprite.svg", sprite);
349
+ pruneAssets(["sprite."], { keep: [path.basename(url)] });
350
+
351
+ log.detail(`${symbols.length} symbols`);
352
+ if (missing.length) {
353
+ log.warn(`${missing.length} icons missing → ${missing.join(", ")}`);
354
+ }
355
+
356
+ return { "sprite.svg": url };
357
+ }