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
package/src/init.mjs ADDED
@@ -0,0 +1,220 @@
1
+ /**
2
+ * `jskelet init` — bulunduğun dizine çalışan bir minimum iskelet kurar.
3
+ *
4
+ * Var olan dosyaların üzerine yazmaz: komutu ikinci kez çalıştırmak yalnızca
5
+ * eksikleri tamamlar. Amaç, "kurulum yaptım ama hiçbir şey çalışmıyor"
6
+ * aşamasını tamamen atlamak — `jskelet dev` hemen ardından çalışır.
7
+ */
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import * as log from "./log.mjs";
11
+
12
+ /** @type {Record<string, string>} */
13
+ const FILES = {
14
+ "jskelet.config.mjs": `/**
15
+ * JSkelet yapılandırması. Tüm alanlar opsiyoneldir; bu dosyayı silseniz de
16
+ * uygulama varsayılanlarla çalışır.
17
+ *
18
+ * Ayrıntılar: node_modules/jskelet/docs/07-yapilandirma.md
19
+ */
20
+ export default {
21
+ brand: { lang: "tr" },
22
+
23
+ /** Üçüncü taraf kaynaklar; \`<head>\`e preconnect olarak basılır. */
24
+ preconnect: [],
25
+
26
+ async cache() {
27
+ return {
28
+ /** Sayfa HTML'inin önbellekte kalma süresi (saniye). */
29
+ html: { "/": 60 },
30
+ };
31
+ },
32
+
33
+ hooks: {
34
+ /** Her sayfanın metadata varsayılanı. */
35
+ metadata() {
36
+ return {
37
+ titleTemplate: "%s | JSkelet",
38
+ description: "JSkelet ile kurulmuş bir site.",
39
+ };
40
+ },
41
+
42
+ /** Layout'a her render'da eklenen local'ler. */
43
+ layoutContext() {
44
+ return { bodyClass: "min-h-full" };
45
+ },
46
+
47
+ /** 404 sayfası. */
48
+ notFound() {
49
+ return {
50
+ view: "pages/not-found",
51
+ metadata: { title: "Sayfa bulunamadı", robots: { index: false } },
52
+ };
53
+ },
54
+ },
55
+ };
56
+ `,
57
+
58
+ "routes/10-pages.mjs": `/**
59
+ * Route modülü. Default export \`(app, api)\` alır; \`api.route()\` controller'ı
60
+ * HTML cache'i, notFound/redirect akışı ve sıkıştırmayla sarar.
61
+ *
62
+ * Dosya adındaki sayısal önek yükleme sırasını belirler: yakalayıcı
63
+ * ("/:slug" gibi) route'lar daha yüksek numarada olmalı.
64
+ */
65
+ export default function register(app, { route }) {
66
+ app.get(
67
+ "/",
68
+ route(
69
+ async () => ({
70
+ view: "pages/home",
71
+ metadata: { title: "Ana sayfa" },
72
+ data: { message: "JSkelet çalışıyor." },
73
+ }),
74
+ { revalidate: 60 },
75
+ ),
76
+ );
77
+ }
78
+ `,
79
+
80
+ "views/pages/home.ejs": `<section class="wrapper">
81
+ <h1><%= metadata.title %></h1>
82
+ <p><%= message %></p>
83
+ <div data-island="counter" data-island-props='{"start":0}'></div>
84
+ </section>
85
+ `,
86
+
87
+ "views/pages/not-found.ejs": `<section class="wrapper">
88
+ <h1>404</h1>
89
+ <p>Aradığınız sayfa bulunamadı.</p>
90
+ <p><a href="/">Ana sayfaya dön</a></p>
91
+ </section>
92
+ `,
93
+
94
+ "views/components/button.js": `import { attrs, esc } from "jskelet/html";
95
+
96
+ /**
97
+ * \`views/components/**\` altındaki her named export şablonlarda doğrudan
98
+ * kullanılabilir: \`<%- button({ text: "Kaydet" }) %>\`. Import gerekmez.
99
+ *
100
+ * @param {{ text: string, href?: string, class?: string }} props
101
+ * @returns {string}
102
+ */
103
+ export function button({ text, href, class: className }) {
104
+ const tag = href ? "a" : "button";
105
+ return \`<\${tag}\${attrs({ href, class: className })}>\${esc(text)}</\${tag}>\`;
106
+ }
107
+ `,
108
+
109
+ "client/entries/main.js": `import { registerAll, start } from "jskelet/client";
110
+
111
+ /**
112
+ * Island kaydı. Değerler dinamik import: modül yalnızca sayfada o island
113
+ * gerçekten varsa ve görünür olduğunda indirilir.
114
+ */
115
+ registerAll({
116
+ counter: () => import("../islands/counter.js"),
117
+ });
118
+
119
+ start();
120
+ `,
121
+
122
+ "client/islands/counter.js": `/**
123
+ * Island sözleşmesi: \`mount(element, props)\` adlı named export.
124
+ * Dönen fonksiyon (varsa) temizlik için ayrılmıştır.
125
+ *
126
+ * @param {HTMLElement} element
127
+ * @param {{ start?: number }} props
128
+ */
129
+ export function mount(element, props) {
130
+ let value = props.start ?? 0;
131
+
132
+ const button = document.createElement("button");
133
+ button.type = "button";
134
+
135
+ const paint = () => {
136
+ button.textContent = \`Tıklama: \${value}\`;
137
+ };
138
+
139
+ button.addEventListener("click", () => {
140
+ value += 1;
141
+ paint();
142
+ });
143
+
144
+ paint();
145
+ element.append(button);
146
+ }
147
+ `,
148
+
149
+ "styles/globals.css": `@import "tailwindcss" source(none);
150
+
151
+ /**
152
+ * Tailwind'in sınıf taraması bu direktiflere bağlıdır. Otomatik tespit
153
+ * yalnızca bu dosyanın bulunduğu dizini tarar; şablonlarda geçen varyantlar
154
+ * (data-[active=false]:… gibi) aksi hâlde sessizce düşer.
155
+ */
156
+ @source "../views";
157
+ @source "../client";
158
+ @source "../routes";
159
+
160
+ body {
161
+ margin: 0;
162
+ font-family: system-ui, sans-serif;
163
+ }
164
+
165
+ .wrapper {
166
+ max-width: 64rem;
167
+ margin-inline: auto;
168
+ padding: 2rem 1rem;
169
+ }
170
+ `,
171
+
172
+ "jsconfig.json": `{
173
+ "compilerOptions": {
174
+ "checkJs": true,
175
+ "module": "esnext",
176
+ "moduleResolution": "bundler",
177
+ "target": "es2022",
178
+ "baseUrl": ".",
179
+ "paths": { "@/*": ["./*"] }
180
+ },
181
+ "exclude": ["node_modules", "public/assets"]
182
+ }
183
+ `,
184
+
185
+ ".gitignore": `node_modules/
186
+ .jskelet/
187
+ public/assets/
188
+ .env
189
+ `,
190
+ };
191
+
192
+ /**
193
+ * @param {string} root
194
+ * @returns {Promise<void>}
195
+ */
196
+ export async function init(root) {
197
+ log.section("init");
198
+
199
+ const created = [];
200
+ const skipped = [];
201
+
202
+ for (const [relative, contents] of Object.entries(FILES)) {
203
+ const target = path.join(root, relative);
204
+
205
+ if (fs.existsSync(target)) {
206
+ skipped.push(relative);
207
+ continue;
208
+ }
209
+
210
+ fs.mkdirSync(path.dirname(target), { recursive: true });
211
+ fs.writeFileSync(target, contents);
212
+ created.push(relative);
213
+ }
214
+
215
+ for (const file of created) log.line(`+ ${file}`);
216
+ if (skipped.length) log.warn(`${skipped.length} dosya zaten vardı, atlandı`);
217
+
218
+ log.line("");
219
+ log.line("sıradaki adım: npx jskelet dev");
220
+ }
package/src/log.mjs ADDED
@@ -0,0 +1,332 @@
1
+ /**
2
+ * JSkelet konsol çıktısı.
3
+ *
4
+ * İki ayrı bölge vardır ve karışmazlar:
5
+ * 1. Başlangıç — banner, hizalı build satırları, "Ready" özeti.
6
+ * 2. Çalışma anı — zaman damgalı, tek satırlık olaylar (HTTP, rebuild, restart).
7
+ *
8
+ * Renk anlam taşır: ✓ yeşil, ✖ kırmızı, ⚠ sarı, ↻ cyan; süre ve yol gri,
9
+ * önemli değerler beyaz/bold. Dekoratif renk kullanılmaz.
10
+ *
11
+ * Build ve dev script'leri bu modülü paylaşır; alt süreçlerde renk
12
+ * algılanamadığı için `JSKELET_COLOR=1` ile zorlanabilir.
13
+ */
14
+ import process from "node:process";
15
+
16
+ const stream = process.stdout;
17
+ const isTTY = Boolean(stream.isTTY);
18
+ const useColor =
19
+ !process.env.NO_COLOR && (isTTY || process.env.JSKELET_COLOR === "1");
20
+
21
+ /**
22
+ * @param {string} open
23
+ * @returns {(text: string) => string}
24
+ */
25
+ function color(open) {
26
+ return (text) => (useColor ? `\u001b[${open}m${text}\u001b[0m` : String(text));
27
+ }
28
+
29
+ export const c = {
30
+ bold: color("1"),
31
+ dim: color("2"),
32
+ red: color("31"),
33
+ green: color("32"),
34
+ yellow: color("33"),
35
+ blue: color("34"),
36
+ magenta: color("35"),
37
+ cyan: color("36"),
38
+ gray: color("90"),
39
+ };
40
+
41
+ export const symbols = {
42
+ ok: c.green("✓"),
43
+ fail: c.red("✖"),
44
+ warn: c.yellow("⚠"),
45
+ cycle: c.cyan("↻"),
46
+ ready: c.green("✔"),
47
+ arrow: c.cyan("→"),
48
+ };
49
+
50
+ const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
51
+
52
+ /** Hizalama genişlikleri: her satır aynı ızgaraya oturur. */
53
+ const LABEL = 12;
54
+ const DETAIL = 20;
55
+ const TIME = 7;
56
+
57
+ /** @param {number} value */
58
+ export function ms(value) {
59
+ return value >= 1000 ? `${(value / 1000).toFixed(2)}s` : `${Math.round(value)}ms`;
60
+ }
61
+
62
+ /** @param {number} bytes */
63
+ export function size(bytes) {
64
+ return bytes >= 1024 * 1024
65
+ ? `${(bytes / 1024 / 1024).toFixed(2)} MB`
66
+ : `${(bytes / 1024).toFixed(1)} kB`;
67
+ }
68
+
69
+ /** @param {string} text */
70
+ function write(text) {
71
+ stream.write(text);
72
+ }
73
+
74
+ function clearLine() {
75
+ if (isTTY) write("\r\u001b[2K");
76
+ }
77
+
78
+ /** @returns {string} `01:49:02` */
79
+ export function clock() {
80
+ return new Date().toLocaleTimeString("tr-TR", { hour12: false });
81
+ }
82
+
83
+ /**
84
+ * @param {string} version
85
+ * @param {string} mode
86
+ * @param {string} [root]
87
+ */
88
+ export function banner(version, mode, root) {
89
+ write(`\n ${c.bold(c.cyan("◆ JSkelet"))} ${c.bold(version)}\n`);
90
+ write(` ${c.dim(mode)}${root ? ` ${c.gray("·")} ${c.gray(root)}` : ""}\n`);
91
+ }
92
+
93
+ /** @param {string} title */
94
+ export function section(title) {
95
+ write(`\n ${c.bold(c.gray(title.toUpperCase()))}\n`);
96
+ }
97
+
98
+ /**
99
+ * Hizalı build satırı.
100
+ * @param {string} symbol
101
+ * @param {string} label
102
+ * @param {string} detail
103
+ * @param {string} time
104
+ */
105
+ function row(symbol, label, detail, time) {
106
+ return (
107
+ ` ${symbol} ${c.bold(label.padEnd(LABEL))} ` +
108
+ `${detail.padEnd(DETAIL)} ${c.gray(time.padStart(TIME))}`
109
+ );
110
+ }
111
+
112
+ /**
113
+ * Adım sürerken biriken ek satırlar; spinner'ı bozmasın diye adım bitince
114
+ * dökülür. İlk ayrıntı satırı hizalı sütuna yazılır, kalanlar altına.
115
+ *
116
+ * @type {string[] | null}
117
+ */
118
+ let pending = null;
119
+
120
+ function flush() {
121
+ const lines = pending?.slice(1) ?? [];
122
+ pending = null;
123
+ for (const line of lines) write(` ${c.gray("·")} ${c.dim(line)}\n`);
124
+ }
125
+
126
+ /**
127
+ * Build adımı. TTY'de spinner döner; bitince satır aynı ızgaraya oturur.
128
+ *
129
+ * @param {string} label
130
+ * @returns {{ done: (detail?: string) => number, fail: (error: unknown) => void }}
131
+ */
132
+ export function task(label) {
133
+ pending = [];
134
+
135
+ const started = Date.now();
136
+ let frame = 0;
137
+
138
+ const paint = () => {
139
+ clearLine();
140
+ write(row(c.cyan(FRAMES[frame]), label, c.dim(pending?.[0] ?? ""), ""));
141
+ frame = (frame + 1) % FRAMES.length;
142
+ };
143
+
144
+ /** @type {NodeJS.Timeout | null} */
145
+ let timer = null;
146
+ if (isTTY) {
147
+ paint();
148
+ timer = setInterval(paint, 80);
149
+ timer.unref?.();
150
+ }
151
+
152
+ const finish = (line) => {
153
+ if (timer) clearInterval(timer);
154
+ clearLine();
155
+ write(`${line}\n`);
156
+ flush();
157
+ };
158
+
159
+ return {
160
+ done(detail) {
161
+ const elapsed = Date.now() - started;
162
+ finish(row(symbols.ok, label, detail ?? pending?.[0] ?? "", ms(elapsed)));
163
+ return elapsed;
164
+ },
165
+ fail(error) {
166
+ finish(row(symbols.fail, label, c.red(String(error?.message ?? error)), ""));
167
+ },
168
+ };
169
+ }
170
+
171
+ /**
172
+ * Adımın sütununa yazılacak kısa özet; ikinci ve sonraki çağrılar alt satıra
173
+ * düşer. Adım dışında çağrılırsa doğrudan basılır.
174
+ *
175
+ * @param {string} text
176
+ */
177
+ export function detail(text) {
178
+ if (pending) {
179
+ pending.push(text);
180
+ return;
181
+ }
182
+ write(` ${c.gray("·")} ${c.dim(text)}\n`);
183
+ }
184
+
185
+ /**
186
+ * Sütuna yazılacak özeti, adım içinde daha önce ayrıntı basılmış olsa bile
187
+ * öne alır (ör. font indirme satırlarından sonra "4/4 weights").
188
+ *
189
+ * @param {string} text
190
+ */
191
+ export function summary(text) {
192
+ if (pending) {
193
+ pending.unshift(text);
194
+ return;
195
+ }
196
+ detail(text);
197
+ }
198
+
199
+ /** @param {string} text */
200
+ export function warn(text) {
201
+ if (pending) {
202
+ pending.push(`${symbols.warn} ${text}`);
203
+ return;
204
+ }
205
+ write(` ${symbols.warn} ${text}\n`);
206
+ }
207
+
208
+ /**
209
+ * Bölüm gövdesindeki düz satır (ör. çıktı boyutları).
210
+ * @param {string} text
211
+ */
212
+ export function line(text) {
213
+ write(` ${c.dim(text)}\n`);
214
+ }
215
+
216
+ /** @param {string} text */
217
+ export function error(text) {
218
+ write(` ${symbols.fail} ${c.red(text)}\n`);
219
+ }
220
+
221
+ /**
222
+ * Başlangıç özeti: süre, adres ve watch durumu.
223
+ *
224
+ * @param {{ elapsed: number, url?: string | null, watching?: boolean, label?: string }} info
225
+ */
226
+ export function ready({ elapsed, url, watching, label = "Ready" }) {
227
+ write(`\n ${symbols.ready} ${c.bold(`${label} in ${ms(elapsed)}`)}\n`);
228
+ if (url) write(` ${symbols.arrow} ${c.cyan(url)}\n`);
229
+ if (watching) write(` ${symbols.cycle} ${c.dim("Watching for changes")}\n`);
230
+ write("\n");
231
+ }
232
+
233
+ /**
234
+ * Çalışma anı olayı: `01:49:03 ✓ css rebuilt 195.9 kB 150ms`
235
+ *
236
+ * Hizalama ANSI kodlarından etkilenmesin diye `message` düz metin olmalı;
237
+ * ek bilgi `note` ile geçilir.
238
+ *
239
+ * @param {{ symbol?: string, scope: string, message: string, note?: string, time?: number | null }} info
240
+ */
241
+ export function event({ symbol = symbols.ok, scope, message, note, time = null }) {
242
+ const body = `${message}${note ? ` ${note}` : ""}`;
243
+ const padding = " ".repeat(Math.max(1, DETAIL - body.length));
244
+
245
+ write(
246
+ `${c.gray(clock())} ${symbol} ${c.bold(scope.padEnd(10))} ` +
247
+ `${message}${note ? ` ${c.dim(note)}` : ""}${padding}` +
248
+ `${c.gray((time == null ? "" : ms(time)).padStart(TIME))}\n`,
249
+ );
250
+ }
251
+
252
+ /**
253
+ * HTTP isteği. Cache bilgisi yalnızca gerçekten anlamlıysa (HIT) gösterilir;
254
+ * her satıra MISS yazmak akışı okunmaz hâle getiriyor.
255
+ *
256
+ * @param {{ method: string, url: string, status: number, ms: number, cache?: string | null }} info
257
+ */
258
+ export function http(info) {
259
+ const tint =
260
+ info.status >= 500 ? c.red : info.status >= 400 ? c.yellow : c.green;
261
+
262
+ write(
263
+ `${c.gray(clock())} ${c.bold(info.method.padEnd(6))}` +
264
+ `${c.gray(truncate(info.url, 28).padEnd(30))}` +
265
+ `${tint(String(info.status))} ${c.gray(ms(info.ms).padStart(TIME))}` +
266
+ `${info.cache === "HIT" ? ` ${c.dim("cached")}` : ""}\n`,
267
+ );
268
+ }
269
+
270
+ /**
271
+ * @param {string} text
272
+ * @param {number} max
273
+ */
274
+ function truncate(text, max) {
275
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
276
+ }
277
+
278
+ /** Kutunun içi sabit genişlikte; uzun satırlar kırpılır. */
279
+ const BOX = 52;
280
+
281
+ /**
282
+ * Çerçeveli hata kutusu — kendi framework'ünü geliştirirken hatanın
283
+ * akış içinde kaybolmaması için.
284
+ *
285
+ * @param {{ title: string, name: string, message: string, lines?: string[] }} info
286
+ */
287
+ export function errorBox({ title, name, message, lines = [] }) {
288
+ const top = `┌─ ${title} ${"─".repeat(Math.max(0, BOX - title.length - 3))}┐`;
289
+ const bottom = `└${"─".repeat(BOX)}┘`;
290
+
291
+ /** @param {string} text @param {(value: string) => string} [tint] */
292
+ const line = (text, tint = (value) => value) => {
293
+ const clipped = truncate(text, BOX - 4);
294
+ write(
295
+ `${c.red("│")} ${tint(clipped)}${" ".repeat(BOX - 4 - clipped.length)} ${c.red("│")}\n`,
296
+ );
297
+ };
298
+
299
+ write(`\n${c.red(top)}\n`);
300
+ line("");
301
+ line(name, (value) => c.bold(c.red(value)));
302
+ for (const part of wrap(message, BOX - 4)) line(part);
303
+ if (lines.length) {
304
+ line("");
305
+ for (const part of lines) line(part, c.gray);
306
+ }
307
+ line("");
308
+ write(`${c.red(bottom)}\n\n`);
309
+ }
310
+
311
+ /**
312
+ * @param {string} text
313
+ * @param {number} max
314
+ * @returns {string[]}
315
+ */
316
+ function wrap(text, max) {
317
+ /** @type {string[]} */
318
+ const out = [];
319
+ let current = "";
320
+
321
+ for (const word of String(text).split(/\s+/)) {
322
+ if (!current.length) current = word;
323
+ else if (`${current} ${word}`.length <= max) current += ` ${word}`;
324
+ else {
325
+ out.push(current);
326
+ current = word;
327
+ }
328
+ }
329
+
330
+ if (current) out.push(current);
331
+ return out.length ? out : [""];
332
+ }
package/src/logo.png ADDED
Binary file
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Node ESM resolve hook'ları. İki iş yapar:
3
+ *
4
+ * 1. `jsconfig.json` / `tsconfig.json` içindeki `compilerOptions.paths`
5
+ * alias'larını çözer (`@/lib/x` → `<root>/lib/x`). Editör ve çalışma zamanı
6
+ * aynı dosyadan beslendiği için ikisi birbirinden ayrışmaz.
7
+ * 2. Uzantısız göreli import'lara uzantı ekler (`./cache` → `./cache.js`).
8
+ * Node ESM bunu yapmaz; bundler'dan taşınan kodda en sık karşılaşılan
9
+ * kırılma noktası bu.
10
+ *
11
+ * `node --import jskelet/register` ile kurulur.
12
+ */
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import process from "node:process";
16
+ import { fileURLToPath, pathToFileURL } from "node:url";
17
+
18
+ const ROOT = process.cwd();
19
+
20
+ /** Uzantısız hedefler için denenecek sıra. */
21
+ const EXTENSIONS = [".js", ".mjs", ".json", "/index.js", "/index.mjs"];
22
+
23
+ /**
24
+ * @returns {{ prefix: string, target: string }[]}
25
+ */
26
+ function readAliases() {
27
+ for (const name of ["jsconfig.json", "tsconfig.json"]) {
28
+ const file = path.join(ROOT, name);
29
+ if (!fs.existsSync(file)) continue;
30
+
31
+ try {
32
+ // Yorum içerebilen tsconfig'ler için kaba ama yeterli bir temizlik;
33
+ // tam bir JSON5 ayrıştırıcısı bağımlılık eklemeye değmiyor.
34
+ const raw = fs
35
+ .readFileSync(file, "utf8")
36
+ .replace(/\/\*[\s\S]*?\*\//g, "")
37
+ .replace(/^\s*\/\/.*$/gm, "");
38
+
39
+ const config = JSON.parse(raw);
40
+ const baseUrl = path.resolve(ROOT, config.compilerOptions?.baseUrl ?? ".");
41
+ const paths = config.compilerOptions?.paths ?? {};
42
+
43
+ /** @type {{ prefix: string, target: string }[]} */
44
+ const aliases = [];
45
+
46
+ for (const [pattern, targets] of Object.entries(paths)) {
47
+ const target = Array.isArray(targets) ? targets[0] : targets;
48
+ if (!pattern.endsWith("/*") || typeof target !== "string") continue;
49
+
50
+ aliases.push({
51
+ prefix: pattern.slice(0, -1),
52
+ target: path.resolve(baseUrl, target.slice(0, -1)),
53
+ });
54
+ }
55
+
56
+ // Uzun önek önce: `@flags/` `@/`den önce denenmeli, yoksa `@/` yakalar.
57
+ return aliases.sort((a, b) => b.prefix.length - a.prefix.length);
58
+ } catch (error) {
59
+ console.warn(`[alias] ${name} okunamadı, alias'lar devre dışı`, error);
60
+ return [];
61
+ }
62
+ }
63
+
64
+ return [];
65
+ }
66
+
67
+ const ALIASES = readAliases();
68
+
69
+ /**
70
+ * @param {string} filePath
71
+ * @returns {boolean}
72
+ */
73
+ function isFile(filePath) {
74
+ try {
75
+ return fs.statSync(filePath).isFile();
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+
81
+ /**
82
+ * @param {string} filePath
83
+ * @returns {string | null}
84
+ */
85
+ function resolveFile(filePath) {
86
+ if (path.extname(filePath) && isFile(filePath)) return filePath;
87
+
88
+ for (const suffix of EXTENSIONS) {
89
+ const candidate = `${filePath}${suffix}`;
90
+ if (isFile(candidate)) return candidate;
91
+ }
92
+
93
+ return isFile(filePath) ? filePath : null;
94
+ }
95
+
96
+ export async function resolve(specifier, context, nextResolve) {
97
+ for (const { prefix, target } of ALIASES) {
98
+ if (!specifier.startsWith(prefix)) continue;
99
+
100
+ const base = path.join(target, specifier.slice(prefix.length));
101
+ const resolved = resolveFile(base);
102
+
103
+ return nextResolve(pathToFileURL(resolved ?? base).href, context);
104
+ }
105
+
106
+ if (
107
+ (specifier.startsWith("./") || specifier.startsWith("../")) &&
108
+ !path.extname(specifier) &&
109
+ context.parentURL?.startsWith("file:")
110
+ ) {
111
+ const parentDir = path.dirname(fileURLToPath(context.parentURL));
112
+ const base = path.resolve(parentDir, specifier);
113
+ const resolved = resolveFile(base);
114
+
115
+ if (resolved) return nextResolve(pathToFileURL(resolved).href, context);
116
+ }
117
+
118
+ return nextResolve(specifier, context);
119
+ }
@@ -0,0 +1,4 @@
1
+ /** `node --import jskelet/register` ile alias hook'unu kaydeder. */
2
+ import { register } from "node:module";
3
+
4
+ register("./alias-hooks.mjs", import.meta.url);