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,356 +1,356 @@
1
- /**
2
- * Dinamik Open Graph görselleri — Next.js `ImageResponse` /
3
- * `opengraph-image.tsx` karşılığı.
4
- *
5
- * JSX yok: ya hazır kart alanları (`title`, `description`, `siteName`) ya da
6
- * ham `svg` verilir. sharp (opsiyonel peer) varsa PNG üretilir; yoksa SVG
7
- * döner. Sosyal kazıyıcıların çoğu PNG beklediği için prod'da sharp önerilir.
8
- *
9
- * Domain bilgisi taşınmaz — metin, renk ve SVG uygulama tarafındandır.
10
- */
11
- import { tryImportFromApp } from "../build/resolve-peer.mjs";
12
- import { getConfig } from "../config/index.js";
13
- import { isNotFoundError } from "../http/control-flow.js";
14
-
15
- /** @type {((input: Buffer, opts?: object) => import('sharp').Sharp) | null | undefined} */
16
- let sharpModule;
17
-
18
- /** Sosyal kartlar için yaygın boyut (Facebook / X / LinkedIn). */
19
- export const OG_SIZE = Object.freeze({ width: 1200, height: 630 });
20
-
21
- const DEFAULT_CACHE =
22
- "public, max-age=0, s-maxage=86400, stale-while-revalidate=604800";
23
-
24
- /**
25
- * @typedef {object} OgCardOptions
26
- * @property {string} [title]
27
- * @property {string} [description]
28
- * @property {string} [siteName]
29
- * @property {string} [background] Düz SVG rengi (`#0f172a`)
30
- * @property {string} [color] Ana metin rengi
31
- * @property {string} [mutedColor] Açıklama / site adı
32
- * @property {string} [accent] Sol şerit rengi
33
- */
34
-
35
- /**
36
- * @typedef {OgCardOptions & {
37
- * svg?: string,
38
- * width?: number,
39
- * height?: number,
40
- * format?: 'png' | 'svg',
41
- * cacheControl?: string,
42
- * }} OgImageOptions
43
- */
44
-
45
- /**
46
- * @typedef {object} OgImageResult
47
- * @property {Buffer} body
48
- * @property {string} contentType
49
- * @property {number} width
50
- * @property {number} height
51
- */
52
-
53
- /**
54
- * XML metin kaçışı — kullanıcı başlığı SVG'ye gömülür.
55
- * @param {unknown} value
56
- * @returns {string}
57
- */
58
- export function escapeXml(value) {
59
- return String(value ?? "")
60
- .replace(/&/g, "&")
61
- .replace(/</g, "&lt;")
62
- .replace(/>/g, "&gt;")
63
- .replace(/"/g, "&quot;")
64
- .replace(/'/g, "&apos;");
65
- }
66
-
67
- /**
68
- * Kelime sınırında satır kır. Uzun kelime kesilir; taşan içerik son satırda `…`.
69
- * @param {string} text
70
- * @param {number} maxChars
71
- * @param {number} maxLines
72
- * @returns {string[]}
73
- */
74
- export function wrapText(text, maxChars, maxLines) {
75
- const words = String(text ?? "")
76
- .trim()
77
- .split(/\s+/)
78
- .filter(Boolean);
79
- if (!words.length || maxLines < 1 || maxChars < 1) return [];
80
-
81
- /** @type {string[]} */
82
- const lines = [];
83
- let current = "";
84
- let overflow = false;
85
-
86
- const pushCurrent = () => {
87
- if (!current) return;
88
- lines.push(current);
89
- current = "";
90
- };
91
-
92
- for (const word of words) {
93
- if (lines.length >= maxLines) {
94
- overflow = true;
95
- break;
96
- }
97
-
98
- const candidate = current ? `${current} ${word}` : word;
99
- if (candidate.length <= maxChars) {
100
- current = candidate;
101
- continue;
102
- }
103
-
104
- pushCurrent();
105
- if (lines.length >= maxLines) {
106
- overflow = true;
107
- break;
108
- }
109
-
110
- if (word.length <= maxChars) {
111
- current = word;
112
- continue;
113
- }
114
-
115
- let rest = word;
116
- while (rest.length > maxChars) {
117
- if (lines.length >= maxLines) {
118
- overflow = true;
119
- rest = "";
120
- break;
121
- }
122
- lines.push(rest.slice(0, maxChars));
123
- rest = rest.slice(maxChars);
124
- }
125
- current = rest;
126
- }
127
-
128
- if (current && lines.length < maxLines) {
129
- lines.push(current);
130
- } else if (current) {
131
- overflow = true;
132
- }
133
-
134
- if (overflow && lines.length) {
135
- const last = lines[lines.length - 1];
136
- const base = last.endsWith("…") ? last.slice(0, -1) : last;
137
- const trimmed = base.slice(0, Math.max(1, maxChars - 1));
138
- lines[lines.length - 1] = `${trimmed}…`;
139
- }
140
-
141
- return lines;
142
- }
143
-
144
- /**
145
- * Hazır kart SVG'si. Uygulama kendi SVG'sini vermek isterse `svg` kullanır.
146
- * @param {OgCardOptions & { width?: number, height?: number }} options
147
- * @returns {string}
148
- */
149
- export function buildOgSvg(options = {}) {
150
- const width = options.width ?? OG_SIZE.width;
151
- const height = options.height ?? OG_SIZE.height;
152
- const background = options.background ?? "#0f172a";
153
- const color = options.color ?? "#f8fafc";
154
- const muted = options.mutedColor ?? "#94a3b8";
155
- const accent = options.accent ?? "#38bdf8";
156
-
157
- const titleLines = wrapText(options.title ?? "", 28, 3);
158
- const descLines = wrapText(options.description ?? "", 52, 2);
159
- const siteName = options.siteName ? escapeXml(options.siteName) : "";
160
-
161
- const titleTs = titleLines
162
- .map((line, i) => {
163
- const dy = i === 0 ? 0 : 72;
164
- return `<tspan x="80" dy="${dy}">${escapeXml(line)}</tspan>`;
165
- })
166
- .join("");
167
-
168
- const descTs = descLines
169
- .map((line, i) => {
170
- const dy = i === 0 ? 0 : 40;
171
- return `<tspan x="80" dy="${dy}">${escapeXml(line)}</tspan>`;
172
- })
173
- .join("");
174
-
175
- const titleY = 200;
176
- const descY = titleY + Math.max(titleLines.length, 1) * 72 + 36;
177
-
178
- return (
179
- `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
180
- `<rect width="100%" height="100%" fill="${escapeXml(background)}"/>` +
181
- `<rect x="0" y="0" width="14" height="${height}" fill="${escapeXml(accent)}"/>` +
182
- (titleTs
183
- ? `<text x="80" y="${titleY}" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="64" font-weight="700" fill="${escapeXml(color)}">${titleTs}</text>`
184
- : "") +
185
- (descTs
186
- ? `<text x="80" y="${descY}" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="30" font-weight="400" fill="${escapeXml(muted)}">${descTs}</text>`
187
- : "") +
188
- (siteName
189
- ? `<text x="80" y="${height - 64}" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="24" font-weight="600" fill="${escapeXml(muted)}">${siteName}</text>`
190
- : "") +
191
- `</svg>`
192
- );
193
- }
194
-
195
- /**
196
- * @returns {Promise<((input: Buffer, opts?: object) => import('sharp').Sharp) | null>}
197
- */
198
- async function loadSharp() {
199
- if (sharpModule !== undefined) return sharpModule;
200
-
201
- /** @type {any} */
202
- let mod = null;
203
- try {
204
- mod = await tryImportFromApp(getConfig().root, "sharp");
205
- } catch {
206
- // Config yoksa (birim test) doğrudan çözümle.
207
- try {
208
- mod = await import("sharp");
209
- } catch {
210
- mod = null;
211
- }
212
- }
213
-
214
- sharpModule = mod?.default ?? mod ?? null;
215
- return sharpModule;
216
- }
217
-
218
- /**
219
- * SVG veya kart alanlarından PNG/SVG gövde üretir.
220
- * @param {OgImageOptions} [options]
221
- * @returns {Promise<OgImageResult>}
222
- */
223
- export async function ogImage(options = {}) {
224
- const width = options.width ?? OG_SIZE.width;
225
- const height = options.height ?? OG_SIZE.height;
226
- const svg =
227
- typeof options.svg === "string" && options.svg.trim()
228
- ? options.svg
229
- : buildOgSvg({ ...options, width, height });
230
-
231
- const preferSvg = options.format === "svg";
232
- const sharp = preferSvg ? null : await loadSharp();
233
-
234
- if (!sharp) {
235
- return {
236
- body: Buffer.from(svg, "utf8"),
237
- contentType: "image/svg+xml; charset=utf-8",
238
- width,
239
- height,
240
- };
241
- }
242
-
243
- const body = await sharp(Buffer.from(svg, "utf8"))
244
- .resize(width, height, { fit: "fill" })
245
- .png()
246
- .toBuffer();
247
-
248
- return {
249
- body,
250
- contentType: "image/png",
251
- width,
252
- height,
253
- };
254
- }
255
-
256
- /**
257
- * Express yanıtına OG görseli basar.
258
- * @param {import('express').Response} res
259
- * @param {OgImageOptions} [options]
260
- * @returns {Promise<OgImageResult>}
261
- */
262
- export async function sendOgImage(res, options = {}) {
263
- const result = await ogImage(options);
264
- const cacheControl = options.cacheControl ?? DEFAULT_CACHE;
265
-
266
- res.status(200);
267
- res.setHeader("Content-Type", result.contentType);
268
- res.setHeader("Cache-Control", cacheControl);
269
- res.setHeader("Content-Length", String(result.body.length));
270
- // Kazıyıcılar ve CDN'ler için boyut ipucu (meta ile de verilir).
271
- res.setHeader("X-Og-Width", String(result.width));
272
- res.setHeader("X-Og-Height", String(result.height));
273
- res.end(result.body);
274
- return result;
275
- }
276
-
277
- /**
278
- * Next `opengraph-image` route handler'ına yakın Express sarmalayıcı.
279
- *
280
- * Factory `null` dönerse veya `notFound()` fırlatırsa 404.
281
- *
282
- * @param {(ctx: { params: Record<string, string>, query: import('express').Request['query'], req: import('express').Request }) =>
283
- * OgImageOptions | null | Promise<OgImageOptions | null>} factory
284
- * @param {OgImageOptions} [defaults] Her istekte birleşen varsayılanlar
285
- * @returns {import('express').RequestHandler}
286
- */
287
- export function ogHandler(factory, defaults = {}) {
288
- return async (req, res, next) => {
289
- try {
290
- const result = await factory({
291
- params: req.params ?? {},
292
- query: req.query,
293
- req,
294
- });
295
- if (result == null) {
296
- res.status(404).end();
297
- return;
298
- }
299
- await sendOgImage(res, { ...defaults, ...result });
300
- } catch (error) {
301
- if (isNotFoundError(error)) {
302
- res.status(404).end();
303
- return;
304
- }
305
- next(error);
306
- }
307
- };
308
- }
309
-
310
- /**
311
- * Next.js `new ImageResponse(...)` DX'si. JSX yok — ilk argüman SVG string
312
- * veya kart alanları nesnesi.
313
- *
314
- * @example
315
- * ```js
316
- * return new ImageResponse(
317
- * { title: post.title, description: post.excerpt, siteName: "Blog" },
318
- * { width: 1200, height: 630 },
319
- * );
320
- * // handler içinde: await image.send(res)
321
- * ```
322
- */
323
- export class ImageResponse {
324
- /** @type {OgImageOptions} */
325
- #options;
326
-
327
- /**
328
- * @param {string | OgCardOptions} element
329
- * @param {Omit<OgImageOptions, keyof OgCardOptions | 'svg'> & { width?: number, height?: number }} [init]
330
- */
331
- constructor(element, init = {}) {
332
- if (typeof element === "string") {
333
- this.#options = { ...init, svg: element };
334
- } else {
335
- this.#options = { ...element, ...init };
336
- }
337
- }
338
-
339
- /** @returns {OgImageOptions} */
340
- get options() {
341
- return this.#options;
342
- }
343
-
344
- /** @returns {Promise<OgImageResult>} */
345
- async buffer() {
346
- return ogImage(this.#options);
347
- }
348
-
349
- /**
350
- * @param {import('express').Response} res
351
- * @returns {Promise<OgImageResult>}
352
- */
353
- async send(res) {
354
- return sendOgImage(res, this.#options);
355
- }
356
- }
1
+ /**
2
+ * Dinamik Open Graph görselleri — Next.js `ImageResponse` /
3
+ * `opengraph-image.tsx` karşılığı.
4
+ *
5
+ * JSX yok: ya hazır kart alanları (`title`, `description`, `siteName`) ya da
6
+ * ham `svg` verilir. sharp (opsiyonel peer) varsa PNG üretilir; yoksa SVG
7
+ * döner. Sosyal kazıyıcıların çoğu PNG beklediği için prod'da sharp önerilir.
8
+ *
9
+ * Domain bilgisi taşınmaz — metin, renk ve SVG uygulama tarafındandır.
10
+ */
11
+ import { tryImportFromApp } from "../build/resolve-peer.mjs";
12
+ import { getConfig } from "../config/index.js";
13
+ import { isNotFoundError } from "../http/control-flow.js";
14
+
15
+ /** @type {((input: Buffer, opts?: object) => import('sharp').Sharp) | null | undefined} */
16
+ let sharpModule;
17
+
18
+ /** Sosyal kartlar için yaygın boyut (Facebook / X / LinkedIn). */
19
+ export const OG_SIZE = Object.freeze({ width: 1200, height: 630 });
20
+
21
+ const DEFAULT_CACHE =
22
+ "public, max-age=0, s-maxage=86400, stale-while-revalidate=604800";
23
+
24
+ /**
25
+ * @typedef {object} OgCardOptions
26
+ * @property {string} [title]
27
+ * @property {string} [description]
28
+ * @property {string} [siteName]
29
+ * @property {string} [background] Düz SVG rengi (`#0f172a`)
30
+ * @property {string} [color] Ana metin rengi
31
+ * @property {string} [mutedColor] Açıklama / site adı
32
+ * @property {string} [accent] Sol şerit rengi
33
+ */
34
+
35
+ /**
36
+ * @typedef {OgCardOptions & {
37
+ * svg?: string,
38
+ * width?: number,
39
+ * height?: number,
40
+ * format?: 'png' | 'svg',
41
+ * cacheControl?: string,
42
+ * }} OgImageOptions
43
+ */
44
+
45
+ /**
46
+ * @typedef {object} OgImageResult
47
+ * @property {Buffer} body
48
+ * @property {string} contentType
49
+ * @property {number} width
50
+ * @property {number} height
51
+ */
52
+
53
+ /**
54
+ * XML metin kaçışı — kullanıcı başlığı SVG'ye gömülür.
55
+ * @param {unknown} value
56
+ * @returns {string}
57
+ */
58
+ export function escapeXml(value) {
59
+ return String(value ?? "")
60
+ .replace(/&/g, "&amp;")
61
+ .replace(/</g, "&lt;")
62
+ .replace(/>/g, "&gt;")
63
+ .replace(/"/g, "&quot;")
64
+ .replace(/'/g, "&apos;");
65
+ }
66
+
67
+ /**
68
+ * Kelime sınırında satır kır. Uzun kelime kesilir; taşan içerik son satırda `…`.
69
+ * @param {string} text
70
+ * @param {number} maxChars
71
+ * @param {number} maxLines
72
+ * @returns {string[]}
73
+ */
74
+ export function wrapText(text, maxChars, maxLines) {
75
+ const words = String(text ?? "")
76
+ .trim()
77
+ .split(/\s+/)
78
+ .filter(Boolean);
79
+ if (!words.length || maxLines < 1 || maxChars < 1) return [];
80
+
81
+ /** @type {string[]} */
82
+ const lines = [];
83
+ let current = "";
84
+ let overflow = false;
85
+
86
+ const pushCurrent = () => {
87
+ if (!current) return;
88
+ lines.push(current);
89
+ current = "";
90
+ };
91
+
92
+ for (const word of words) {
93
+ if (lines.length >= maxLines) {
94
+ overflow = true;
95
+ break;
96
+ }
97
+
98
+ const candidate = current ? `${current} ${word}` : word;
99
+ if (candidate.length <= maxChars) {
100
+ current = candidate;
101
+ continue;
102
+ }
103
+
104
+ pushCurrent();
105
+ if (lines.length >= maxLines) {
106
+ overflow = true;
107
+ break;
108
+ }
109
+
110
+ if (word.length <= maxChars) {
111
+ current = word;
112
+ continue;
113
+ }
114
+
115
+ let rest = word;
116
+ while (rest.length > maxChars) {
117
+ if (lines.length >= maxLines) {
118
+ overflow = true;
119
+ rest = "";
120
+ break;
121
+ }
122
+ lines.push(rest.slice(0, maxChars));
123
+ rest = rest.slice(maxChars);
124
+ }
125
+ current = rest;
126
+ }
127
+
128
+ if (current && lines.length < maxLines) {
129
+ lines.push(current);
130
+ } else if (current) {
131
+ overflow = true;
132
+ }
133
+
134
+ if (overflow && lines.length) {
135
+ const last = lines[lines.length - 1];
136
+ const base = last.endsWith("…") ? last.slice(0, -1) : last;
137
+ const trimmed = base.slice(0, Math.max(1, maxChars - 1));
138
+ lines[lines.length - 1] = `${trimmed}…`;
139
+ }
140
+
141
+ return lines;
142
+ }
143
+
144
+ /**
145
+ * Hazır kart SVG'si. Uygulama kendi SVG'sini vermek isterse `svg` kullanır.
146
+ * @param {OgCardOptions & { width?: number, height?: number }} options
147
+ * @returns {string}
148
+ */
149
+ export function buildOgSvg(options = {}) {
150
+ const width = options.width ?? OG_SIZE.width;
151
+ const height = options.height ?? OG_SIZE.height;
152
+ const background = options.background ?? "#0f172a";
153
+ const color = options.color ?? "#f8fafc";
154
+ const muted = options.mutedColor ?? "#94a3b8";
155
+ const accent = options.accent ?? "#38bdf8";
156
+
157
+ const titleLines = wrapText(options.title ?? "", 28, 3);
158
+ const descLines = wrapText(options.description ?? "", 52, 2);
159
+ const siteName = options.siteName ? escapeXml(options.siteName) : "";
160
+
161
+ const titleTs = titleLines
162
+ .map((line, i) => {
163
+ const dy = i === 0 ? 0 : 72;
164
+ return `<tspan x="80" dy="${dy}">${escapeXml(line)}</tspan>`;
165
+ })
166
+ .join("");
167
+
168
+ const descTs = descLines
169
+ .map((line, i) => {
170
+ const dy = i === 0 ? 0 : 40;
171
+ return `<tspan x="80" dy="${dy}">${escapeXml(line)}</tspan>`;
172
+ })
173
+ .join("");
174
+
175
+ const titleY = 200;
176
+ const descY = titleY + Math.max(titleLines.length, 1) * 72 + 36;
177
+
178
+ return (
179
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
180
+ `<rect width="100%" height="100%" fill="${escapeXml(background)}"/>` +
181
+ `<rect x="0" y="0" width="14" height="${height}" fill="${escapeXml(accent)}"/>` +
182
+ (titleTs
183
+ ? `<text x="80" y="${titleY}" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="64" font-weight="700" fill="${escapeXml(color)}">${titleTs}</text>`
184
+ : "") +
185
+ (descTs
186
+ ? `<text x="80" y="${descY}" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="30" font-weight="400" fill="${escapeXml(muted)}">${descTs}</text>`
187
+ : "") +
188
+ (siteName
189
+ ? `<text x="80" y="${height - 64}" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="24" font-weight="600" fill="${escapeXml(muted)}">${siteName}</text>`
190
+ : "") +
191
+ `</svg>`
192
+ );
193
+ }
194
+
195
+ /**
196
+ * @returns {Promise<((input: Buffer, opts?: object) => import('sharp').Sharp) | null>}
197
+ */
198
+ async function loadSharp() {
199
+ if (sharpModule !== undefined) return sharpModule;
200
+
201
+ /** @type {any} */
202
+ let mod = null;
203
+ try {
204
+ mod = await tryImportFromApp(getConfig().root, "sharp");
205
+ } catch {
206
+ // Config yoksa (birim test) doğrudan çözümle.
207
+ try {
208
+ mod = await import("sharp");
209
+ } catch {
210
+ mod = null;
211
+ }
212
+ }
213
+
214
+ sharpModule = mod?.default ?? mod ?? null;
215
+ return sharpModule;
216
+ }
217
+
218
+ /**
219
+ * SVG veya kart alanlarından PNG/SVG gövde üretir.
220
+ * @param {OgImageOptions} [options]
221
+ * @returns {Promise<OgImageResult>}
222
+ */
223
+ export async function ogImage(options = {}) {
224
+ const width = options.width ?? OG_SIZE.width;
225
+ const height = options.height ?? OG_SIZE.height;
226
+ const svg =
227
+ typeof options.svg === "string" && options.svg.trim()
228
+ ? options.svg
229
+ : buildOgSvg({ ...options, width, height });
230
+
231
+ const preferSvg = options.format === "svg";
232
+ const sharp = preferSvg ? null : await loadSharp();
233
+
234
+ if (!sharp) {
235
+ return {
236
+ body: Buffer.from(svg, "utf8"),
237
+ contentType: "image/svg+xml; charset=utf-8",
238
+ width,
239
+ height,
240
+ };
241
+ }
242
+
243
+ const body = await sharp(Buffer.from(svg, "utf8"))
244
+ .resize(width, height, { fit: "fill" })
245
+ .png()
246
+ .toBuffer();
247
+
248
+ return {
249
+ body,
250
+ contentType: "image/png",
251
+ width,
252
+ height,
253
+ };
254
+ }
255
+
256
+ /**
257
+ * Express yanıtına OG görseli basar.
258
+ * @param {import('express').Response} res
259
+ * @param {OgImageOptions} [options]
260
+ * @returns {Promise<OgImageResult>}
261
+ */
262
+ export async function sendOgImage(res, options = {}) {
263
+ const result = await ogImage(options);
264
+ const cacheControl = options.cacheControl ?? DEFAULT_CACHE;
265
+
266
+ res.status(200);
267
+ res.setHeader("Content-Type", result.contentType);
268
+ res.setHeader("Cache-Control", cacheControl);
269
+ res.setHeader("Content-Length", String(result.body.length));
270
+ // Kazıyıcılar ve CDN'ler için boyut ipucu (meta ile de verilir).
271
+ res.setHeader("X-Og-Width", String(result.width));
272
+ res.setHeader("X-Og-Height", String(result.height));
273
+ res.end(result.body);
274
+ return result;
275
+ }
276
+
277
+ /**
278
+ * Next `opengraph-image` route handler'ına yakın Express sarmalayıcı.
279
+ *
280
+ * Factory `null` dönerse veya `notFound()` fırlatırsa 404.
281
+ *
282
+ * @param {(ctx: { params: Record<string, string>, query: import('express').Request['query'], req: import('express').Request }) =>
283
+ * OgImageOptions | null | Promise<OgImageOptions | null>} factory
284
+ * @param {OgImageOptions} [defaults] Her istekte birleşen varsayılanlar
285
+ * @returns {import('express').RequestHandler}
286
+ */
287
+ export function ogHandler(factory, defaults = {}) {
288
+ return async (req, res, next) => {
289
+ try {
290
+ const result = await factory({
291
+ params: req.params ?? {},
292
+ query: req.query,
293
+ req,
294
+ });
295
+ if (result == null) {
296
+ res.status(404).end();
297
+ return;
298
+ }
299
+ await sendOgImage(res, { ...defaults, ...result });
300
+ } catch (error) {
301
+ if (isNotFoundError(error)) {
302
+ res.status(404).end();
303
+ return;
304
+ }
305
+ next(error);
306
+ }
307
+ };
308
+ }
309
+
310
+ /**
311
+ * Next.js `new ImageResponse(...)` DX'si. JSX yok — ilk argüman SVG string
312
+ * veya kart alanları nesnesi.
313
+ *
314
+ * @example
315
+ * ```js
316
+ * return new ImageResponse(
317
+ * { title: post.title, description: post.excerpt, siteName: "Blog" },
318
+ * { width: 1200, height: 630 },
319
+ * );
320
+ * // handler içinde: await image.send(res)
321
+ * ```
322
+ */
323
+ export class ImageResponse {
324
+ /** @type {OgImageOptions} */
325
+ #options;
326
+
327
+ /**
328
+ * @param {string | OgCardOptions} element
329
+ * @param {Omit<OgImageOptions, keyof OgCardOptions | 'svg'> & { width?: number, height?: number }} [init]
330
+ */
331
+ constructor(element, init = {}) {
332
+ if (typeof element === "string") {
333
+ this.#options = { ...init, svg: element };
334
+ } else {
335
+ this.#options = { ...element, ...init };
336
+ }
337
+ }
338
+
339
+ /** @returns {OgImageOptions} */
340
+ get options() {
341
+ return this.#options;
342
+ }
343
+
344
+ /** @returns {Promise<OgImageResult>} */
345
+ async buffer() {
346
+ return ogImage(this.#options);
347
+ }
348
+
349
+ /**
350
+ * @param {import('express').Response} res
351
+ * @returns {Promise<OgImageResult>}
352
+ */
353
+ async send(res) {
354
+ return sendOgImage(res, this.#options);
355
+ }
356
+ }