@xrystal/core 3.38.3 → 3.39.0
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.
- package/README.md +339 -38
- package/package.json +1 -1
- package/x/dist/project/index.js +1 -1
package/README.md
CHANGED
|
@@ -7,13 +7,28 @@
|
|
|
7
7
|
|
|
8
8
|
---
|
|
9
9
|
|
|
10
|
+
## Why / Neden
|
|
11
|
+
|
|
12
|
+
**EN:** `@xrystal/core` is a **kernel**, not only a GitHub template. Most teams already have their own repo layout, CI, Docker, or monorepo — they only need the runtime: DI, `tmp.yml`, `ctr()`, DTO, logger, i18n, trace. Use `xcore create` if you want a starter; otherwise add the package to **your** project and seed `x/tmp.yml`.
|
|
13
|
+
|
|
14
|
+
**TR:** `@xrystal/core` bir **kernel** — sadece GitHub template değil. Çoğu ekipte zaten kendi repo düzeni, CI, Docker veya monorepo vardır; ihtiyaç duyulan şey runtime: DI, `tmp.yml`, `ctr()`, DTO, logger, i18n, trace. Sıfırdan başlıyorsan `xcore create`; mevcut projende sadece paketi kur + `xcore tmp` yeter.
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
# EN: existing project — kernel only · TR: mevcut proje — sadece kernel
|
|
18
|
+
bun add @xrystal/core
|
|
19
|
+
npx xcore tmp # seed x/tmp.yml into YOUR layout
|
|
20
|
+
# wire coreLoader + dtoMiddleware in your entry file
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
10
25
|
## Quick start / Hızlı başlangıç
|
|
11
26
|
|
|
12
|
-
### Path A — `create` (
|
|
27
|
+
### Path A — `create` (starter template / başlangıç şablonu)
|
|
13
28
|
|
|
14
|
-
**EN:**
|
|
29
|
+
**EN:** Optional — clone GitHub template when you have no project yet.
|
|
15
30
|
|
|
16
|
-
**TR:**
|
|
31
|
+
**TR:** İsteğe bağlı — henüz proje yoksa GitHub template klonla.
|
|
17
32
|
|
|
18
33
|
```bash
|
|
19
34
|
mkdir my-api && cd my-api
|
|
@@ -28,11 +43,11 @@ bun run dev
|
|
|
28
43
|
npx xcore doctor # EN: setup check · TR: kurulum kontrolü
|
|
29
44
|
```
|
|
30
45
|
|
|
31
|
-
### Path B —
|
|
46
|
+
### Path B — Your project + kernel (most common / en yaygın)
|
|
32
47
|
|
|
33
|
-
**EN:**
|
|
48
|
+
**EN:** Keep your folder names — only add `tmp.yml`, `coreLoader`, controllers.
|
|
34
49
|
|
|
35
|
-
**TR:**
|
|
50
|
+
**TR:** Kendi klasör adların kalsın — sadece `tmp.yml`, `coreLoader`, controller ekle.
|
|
36
51
|
|
|
37
52
|
```bash
|
|
38
53
|
mkdir my-api && cd my-api
|
|
@@ -72,9 +87,7 @@ my-api/
|
|
|
72
87
|
│ ├── index.ts # EN: dev entry (xcore dev) · TR: dev girişi
|
|
73
88
|
│ └── controllers/
|
|
74
89
|
└── x/
|
|
75
|
-
├── tmp.yml # EN: single config source · TR: tek
|
|
76
|
-
├── environments/ # .dev.env, .prod.env
|
|
77
|
-
└── tests/
|
|
90
|
+
├── tmp.yml # EN: single config source · TR: tek diğerleri
|
|
78
91
|
```
|
|
79
92
|
|
|
80
93
|
### Minimal `x/tmp.yml`
|
|
@@ -140,16 +153,163 @@ bun run dev
|
|
|
140
153
|
|
|
141
154
|
---
|
|
142
155
|
|
|
156
|
+
## Platform features / Platform özellikleri
|
|
157
|
+
|
|
158
|
+
**EN:** What the kernel gives you — one line each + minimal example.
|
|
159
|
+
|
|
160
|
+
**TR:** Kernel'in verdiği yetenekler — tek satır + kısa örnek.
|
|
161
|
+
|
|
162
|
+
| Feature / Özellik | EN | TR | Example / Örnek |
|
|
163
|
+
|-------------------|----|----|-----------------|
|
|
164
|
+
| **Boot / DI** | Awilix loaders: System, Logger, Kafka, Dto, i18n, … | Awilix loader'lar | `await coreLoader({})` |
|
|
165
|
+
| **Live `tmp.yml`** | Edit file → loaders re-sync without restart | Dosya değişince loader sync | `logLevel: debug` → save → logger updates |
|
|
166
|
+
| **`ctr()` pipeline** | `checks → logic → response`, no `res.json()` | Endpoint pipeline | `list = this.ctr({ logic: async () => ({ data: [] }) })` |
|
|
167
|
+
| **DTO responses** | Standard API shape via `@xrystal/dto` | Standart API cevabı | `return { data: [], message: '@successfully user' }` |
|
|
168
|
+
| **Trace** | `requestId` per request/job (ALS) | İstek/job trace id | `req.requestId` · `runWithTrace('job-1', fn)` |
|
|
169
|
+
| **i18n** | i18next + 50+ business message keys | Çok dilli mesajlar | `'@successfully user'` · `req.t('responseMessage.successfully')` |
|
|
170
|
+
| **G store** | App-wide state from `tmp.yml` vars | Global state | `G.get('maintenance')` · `checks: () => G.get('x') ? fail : true` |
|
|
171
|
+
| **Logger** | Winston: console + daily rotate files | Dosya + konsol log | `this.logger.log(LoggerLayerEnum.INFO, 'ok')` |
|
|
172
|
+
| **Kafka logs** | Structured logs → Kafka topic | Log → Kafka | `loaders.loggers` + `configs.kafkaLogsTopic` in env |
|
|
173
|
+
| **HTTP client** | Retries + circuit breaker + trace header | Dayanıklı outbound HTTP | extend `BaseApiClient` from loader/clients |
|
|
174
|
+
| **Scope validate** | OAuth-style `resource:permission` check | Scope doğrulama | `validateScopes({ scopes, resources, permissions })` |
|
|
175
|
+
| **Realtime** | Same `ctr()` for ws / socket.io | HTTP + ws aynı kalıp | `ctr({ logic }, { protocol: 'ws' })` — [guide](#realtime--websocket--socketio) |
|
|
176
|
+
| **CLI** | dev, build, start, test, doctor, tmp | Servis toolchain | `"dev": "xcore dev"` in your `package.json` |
|
|
177
|
+
| **Shutdown** | Graceful cleanup on SIGTERM | Temiz kapanış | auto via `registerGracefulShutdown()` on boot |
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
// EN: minimal kernel boot in ANY entry file · TR: herhangi bir giriş dosyasında
|
|
181
|
+
import coreLoader from '@xrystal/core'
|
|
182
|
+
import { dtoMiddleware, G, runWithTrace } from '@xrystal/core/utils'
|
|
183
|
+
import Controller from '@xrystal/core/loader/controller'
|
|
184
|
+
|
|
185
|
+
await coreLoader({})
|
|
186
|
+
|
|
187
|
+
class HealthController extends Controller {
|
|
188
|
+
check = this.ctr({
|
|
189
|
+
checks: () => G.get('maintenance') ? { message: '@unsuccessful maintenance' } : true,
|
|
190
|
+
logic: async ({ req }) => ({
|
|
191
|
+
data: { ok: true, trace: req.requestId },
|
|
192
|
+
message: '@successfully',
|
|
193
|
+
}),
|
|
194
|
+
})
|
|
195
|
+
}
|
|
196
|
+
export const healthCtrl = new HealthController()
|
|
197
|
+
|
|
198
|
+
await runWithTrace('nightly-job', async () => {
|
|
199
|
+
// EN: cron/queue jobs get trace too · TR: cron/queue job'ları da trace alır
|
|
200
|
+
})
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
---
|
|
204
|
+
|
|
205
|
+
## Framework quickstarts / Framework hızlı başlangıç
|
|
206
|
+
|
|
207
|
+
**EN:** Same kernel — swap only `framework` in `tmp.yml` + middleware line.
|
|
208
|
+
|
|
209
|
+
**TR:** Aynı kernel — sadece `tmp.yml` → `framework` ve middleware satırı değişir.
|
|
210
|
+
|
|
211
|
+
### Elysia (default)
|
|
212
|
+
|
|
213
|
+
```yaml
|
|
214
|
+
# x/tmp.yml
|
|
215
|
+
configs:
|
|
216
|
+
service:
|
|
217
|
+
framework: elysia
|
|
218
|
+
paths: { root: ./x, source: ./source }
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
import { Elysia } from 'elysia'
|
|
223
|
+
import coreLoader from '@xrystal/core'
|
|
224
|
+
import { dtoMiddleware } from '@xrystal/core/utils'
|
|
225
|
+
import { userCtrl } from './controllers/user'
|
|
226
|
+
|
|
227
|
+
await coreLoader({})
|
|
228
|
+
new Elysia().use(dtoMiddleware()).get('/users', userCtrl.list).listen(3000)
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
### Express
|
|
232
|
+
|
|
233
|
+
```yaml
|
|
234
|
+
configs:
|
|
235
|
+
service:
|
|
236
|
+
framework: express
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
```typescript
|
|
240
|
+
import express from 'express'
|
|
241
|
+
import coreLoader from '@xrystal/core'
|
|
242
|
+
import { dtoMiddleware } from '@xrystal/core/utils'
|
|
243
|
+
import { userCtrl } from './controllers/user'
|
|
244
|
+
|
|
245
|
+
await coreLoader({})
|
|
246
|
+
const app = express()
|
|
247
|
+
app.use(dtoMiddleware('express'))
|
|
248
|
+
app.get('/users', userCtrl.list)
|
|
249
|
+
app.listen(3000)
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
### Node (raw http)
|
|
253
|
+
|
|
254
|
+
```yaml
|
|
255
|
+
configs:
|
|
256
|
+
service:
|
|
257
|
+
framework: node
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
```typescript
|
|
261
|
+
import http from 'node:http'
|
|
262
|
+
import coreLoader from '@xrystal/core'
|
|
263
|
+
import { userCtrl } from './controllers/user'
|
|
264
|
+
|
|
265
|
+
await coreLoader({})
|
|
266
|
+
http.createServer((req, res) => userCtrl.list(req, res)).listen(3000)
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
### Fetch / Bun.serve
|
|
270
|
+
|
|
271
|
+
```yaml
|
|
272
|
+
configs:
|
|
273
|
+
service:
|
|
274
|
+
framework: fetch
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
```typescript
|
|
278
|
+
import coreLoader from '@xrystal/core'
|
|
279
|
+
import { userCtrl } from './controllers/user'
|
|
280
|
+
|
|
281
|
+
await coreLoader({})
|
|
282
|
+
Bun.serve({ fetch: (req) => userCtrl.list(req) })
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
`fetch` — no global middleware; `ctr()` attaches builder per request.
|
|
286
|
+
|
|
287
|
+
**EN:** WebSocket & Socket.IO — full guide at the end: [Realtime](#realtime--websocket--socketio).
|
|
288
|
+
|
|
289
|
+
**TR:** WebSocket & Socket.IO — tam rehber sonda: [Realtime](#realtime--websocket--socketio).
|
|
290
|
+
|
|
291
|
+
| Framework | `tmp.yml` | Middleware |
|
|
292
|
+
|-----------|-----------|------------|
|
|
293
|
+
| elysia | `framework: elysia` | `dtoMiddleware()` |
|
|
294
|
+
| express | `framework: express` | `dtoMiddleware('express')` |
|
|
295
|
+
| node | `framework: node` | `dtoMiddleware('node')` |
|
|
296
|
+
| fetch | `framework: fetch` | — (per-request in `ctr`) |
|
|
297
|
+
|
|
298
|
+
---
|
|
299
|
+
|
|
143
300
|
## Reference / Referans
|
|
144
301
|
|
|
145
302
|
| Topic / Konu | Section / Bölüm |
|
|
146
303
|
|--------------|-----------------|
|
|
304
|
+
| Why kernel vs template | [Why](#why--neden) |
|
|
305
|
+
| All platform capabilities | [Platform features](#platform-features--platform-özellikleri) |
|
|
306
|
+
| Per-framework boot | [Framework quickstarts](#framework-quickstarts--framework-hızlı-başlangıç) |
|
|
147
307
|
| Controller, `ctr()` | [Controller](#controller) |
|
|
148
|
-
| Express / Elysia | [Framework](#express--elysia) |
|
|
308
|
+
| Express / Elysia detail | [Framework](#express--elysia) |
|
|
149
309
|
| DI, boot, tmp watch | [DI](#di--tmpyml) |
|
|
150
310
|
| Locale / dil | [i18n](#i18n--locale) |
|
|
151
311
|
| Global state | [G store](#g-store) |
|
|
152
|
-
| WebSocket | [Realtime](#realtime) |
|
|
312
|
+
| WebSocket & Socket.IO | [Realtime](#realtime--websocket--socketio) |
|
|
153
313
|
| API response shape | [DTO](#dto-responses--dto-cevapları) |
|
|
154
314
|
| End-to-end flow | [Usage guide](#usage-guide--kullanım-rehberi) |
|
|
155
315
|
|
|
@@ -190,9 +350,9 @@ app.get('/users', userCtrl.list)
|
|
|
190
350
|
|
|
191
351
|
## Express & Elysia
|
|
192
352
|
|
|
193
|
-
**EN:** `tmp.yml` → `configs.service.framework` picks the HTTP
|
|
353
|
+
**EN:** See [Framework quickstarts](#framework-quickstarts--framework-hızlı-başlangıç) for copy-paste per stack. `tmp.yml` → `configs.service.framework` picks the HTTP layer.
|
|
194
354
|
|
|
195
|
-
**TR:** `tmp.yml` → `
|
|
355
|
+
**TR:** Kopyala-yapıştır örnekler için [Framework hızlı başlangıç](#framework-quickstarts--framework-hızlı-başlangıç). `tmp.yml` → `framework` HTTP katmanını seçer.
|
|
196
356
|
|
|
197
357
|
**Express**
|
|
198
358
|
|
|
@@ -238,9 +398,9 @@ new Elysia().use(dtoMiddleware()).get('/users', userCtrl.list).listen(3000)
|
|
|
238
398
|
| node | `dtoMiddleware('node')` | Raw `createServer` | Ham HTTP |
|
|
239
399
|
| fetch | none | `ctr()` attaches builder per request | Request başına builder |
|
|
240
400
|
|
|
241
|
-
**EN:** Realtime (ws / socket.io) is separate from HTTP
|
|
401
|
+
**EN:** Realtime (ws / socket.io) is separate from HTTP — full guide at the end: [Realtime](#realtime--websocket--socketio).
|
|
242
402
|
|
|
243
|
-
**TR:** Realtime (ws / socket.io) HTTP
|
|
403
|
+
**TR:** Realtime (ws / socket.io) HTTP'den ayrı — tam rehber sonda: [Realtime](#realtime--websocket--socketio).
|
|
244
404
|
|
|
245
405
|
---
|
|
246
406
|
|
|
@@ -334,27 +494,6 @@ checks: () => G.get('maintenance') ? { message: '@unsuccessful maintenance' } :
|
|
|
334
494
|
|
|
335
495
|
---
|
|
336
496
|
|
|
337
|
-
## Realtime
|
|
338
|
-
|
|
339
|
-
**EN:** Not HTTP — use `protocol: 'ws'` or `'socketio'` on `ctr()`. Set `protocols` in `tmp.yml`.
|
|
340
|
-
|
|
341
|
-
**TR:** HTTP değil — `ctr()` üzerinde `protocol: 'ws'` veya `'socketio'`. `tmp.yml` → `protocols`.
|
|
342
|
-
|
|
343
|
-
```typescript
|
|
344
|
-
onMessage = this.ctr({ logic: async () => ({ ok: true }) }, { protocol: 'ws' })
|
|
345
|
-
|
|
346
|
-
wss.on('connection', (socket) => {
|
|
347
|
-
realtimeMiddleware()(socket, () => {})
|
|
348
|
-
socket.on('message', chatCtrl.onMessage.with(socket))
|
|
349
|
-
})
|
|
350
|
-
```
|
|
351
|
-
|
|
352
|
-
```yaml
|
|
353
|
-
protocols: [http, ws] # EN: or [http, socketio] · TR: veya [http, socketio]
|
|
354
|
-
```
|
|
355
|
-
|
|
356
|
-
---
|
|
357
|
-
|
|
358
497
|
## DTO responses / DTO cevapları
|
|
359
498
|
|
|
360
499
|
**EN:** Standard `{ success, message, data, … }` via `@xrystal/dto`. `dtoMiddleware()` attaches builder; `ctr()` dispatches the result.
|
|
@@ -372,9 +511,9 @@ Details / detay: [`@xrystal/dto`](https://www.npmjs.com/package/@xrystal/dto)
|
|
|
372
511
|
**TR:** Servis yazarken tipik akış.
|
|
373
512
|
|
|
374
513
|
```
|
|
375
|
-
1.
|
|
514
|
+
1. Your repo + bun add @xrystal/core + xcore tmp (or xcore create for greenfield)
|
|
376
515
|
2. tmp.yml → framework, loaders, paths
|
|
377
|
-
3. coreLoader() → once at top of index.ts
|
|
516
|
+
3. coreLoader() → once at top of YOUR index.ts
|
|
378
517
|
4. Controller → ctr() per endpoint
|
|
379
518
|
5. Framework → dtoMiddleware + routes
|
|
380
519
|
6. xcore dev → develop
|
|
@@ -454,6 +593,168 @@ class UserController extends Controller {
|
|
|
454
593
|
|
|
455
594
|
---
|
|
456
595
|
|
|
596
|
+
## Realtime — WebSocket & Socket.IO
|
|
597
|
+
|
|
598
|
+
**EN:** HTTP framework (`express`, `elysia`, …) and realtime are **separate axes**. Realtime uses `protocol: 'ws'` or `'socketio'` on `ctr()` — not `framework` in `tmp.yml`. Integration tests cover both pipelines (34 tests pass).
|
|
599
|
+
|
|
600
|
+
**TR:** HTTP framework (`express`, `elysia`, …) ile realtime **ayrı eksenler**. Realtime `ctr()` üzerinde `protocol: 'ws'` veya `'socketio'` kullanır — `tmp.yml`'deki `framework` değil. Her iki pipeline integration test ile doğrulanır (34 test geçer).
|
|
601
|
+
|
|
602
|
+
### HTTP vs realtime / HTTP vs realtime
|
|
603
|
+
|
|
604
|
+
| Axis / Eksen | `tmp.yml` | Middleware | Dispatch |
|
|
605
|
+
|--------------|-----------|------------|----------|
|
|
606
|
+
| **HTTP** | `framework: elysia` | `dtoMiddleware()` | `res.json()` / Elysia set |
|
|
607
|
+
| **WebSocket** | `protocols: [http, ws]` | `realtimeMiddleware()` | `socket.send(JSON)` |
|
|
608
|
+
| **Socket.IO** | `protocols: [http, socketio]` | `realtimeMiddleware('socketio')` | `socket.emit(event, payload)` |
|
|
609
|
+
|
|
610
|
+
**EN:** Same controller class can serve HTTP **and** realtime — different properties, different `protocol` on `ctr()`.
|
|
611
|
+
|
|
612
|
+
**TR:** Aynı controller sınıfı HTTP **ve** realtime verebilir — farklı property, farklı `protocol`.
|
|
613
|
+
|
|
614
|
+
### 3-step pattern / 3 adım kalıbı
|
|
615
|
+
|
|
616
|
+
```
|
|
617
|
+
1. realtimeMiddleware() → socket'a builder tak
|
|
618
|
+
2. ctr({ logic }, { protocol }) → checks + logic + i18n (isteğe bağlı)
|
|
619
|
+
3. dispatch otomatik → ws: send · socketio: emit
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
### `tmp.yml` — `protocols`
|
|
623
|
+
|
|
624
|
+
```yaml
|
|
625
|
+
configs:
|
|
626
|
+
service:
|
|
627
|
+
framework: elysia # EN: HTTP only · TR: sadece HTTP
|
|
628
|
+
protocols: [http, ws] # EN: or [http, socketio] · TR: veya [http, socketio]
|
|
629
|
+
```
|
|
630
|
+
|
|
631
|
+
| `protocols` in tmp.yml | `realtimeMiddleware()` |
|
|
632
|
+
|------------------------|-------------------------|
|
|
633
|
+
| `[http, ws]` | `realtimeMiddleware()` → auto **ws** |
|
|
634
|
+
| `[http, socketio]` | `realtimeMiddleware()` → auto **socketio** |
|
|
635
|
+
| `[http, ws, socketio]` | **Must specify:** `realtimeMiddleware('ws')` or `realtimeMiddleware('socketio')` |
|
|
636
|
+
|
|
637
|
+
### Native WebSocket (ws)
|
|
638
|
+
|
|
639
|
+
```typescript
|
|
640
|
+
// source/controllers/chat.ts
|
|
641
|
+
import Controller from '@xrystal/core/loader/controller'
|
|
642
|
+
|
|
643
|
+
class ChatController extends Controller {
|
|
644
|
+
onMessage = this.ctr({
|
|
645
|
+
logic: async ({ req }) => ({
|
|
646
|
+
data: { echo: req.body },
|
|
647
|
+
message: '@successfully',
|
|
648
|
+
}),
|
|
649
|
+
}, { protocol: 'ws' })
|
|
650
|
+
}
|
|
651
|
+
export const chatCtrl = new ChatController()
|
|
652
|
+
```
|
|
653
|
+
|
|
654
|
+
```typescript
|
|
655
|
+
// source/index.ts — Express + ws on same port (example)
|
|
656
|
+
import { WebSocketServer } from 'ws'
|
|
657
|
+
import express from 'express'
|
|
658
|
+
import coreLoader from '@xrystal/core'
|
|
659
|
+
import { dtoMiddleware, realtimeMiddleware } from '@xrystal/core/utils'
|
|
660
|
+
import { chatCtrl } from './controllers/chat'
|
|
661
|
+
|
|
662
|
+
await coreLoader({})
|
|
663
|
+
|
|
664
|
+
const app = express()
|
|
665
|
+
app.use(dtoMiddleware('express'))
|
|
666
|
+
|
|
667
|
+
const server = app.listen(3000)
|
|
668
|
+
const wss = new WebSocketServer({ server })
|
|
669
|
+
|
|
670
|
+
wss.on('connection', (socket) => {
|
|
671
|
+
realtimeMiddleware()(socket, () => {}) // 1) builder attach
|
|
672
|
+
socket.on('message', chatCtrl.onMessage.with(socket)) // 2) ctr + 3) auto send
|
|
673
|
+
})
|
|
674
|
+
```
|
|
675
|
+
|
|
676
|
+
**EN:** `with(socket)` binds the socket for that event — core calls `socket.send(JSON)` after `ctr()` finishes.
|
|
677
|
+
|
|
678
|
+
**TR:** `with(socket)` socket'ı o event'e bağlar — `ctr()` bitince core `socket.send(JSON)` çağırır.
|
|
679
|
+
|
|
680
|
+
### Socket.IO
|
|
681
|
+
|
|
682
|
+
```typescript
|
|
683
|
+
class ChatController extends Controller {
|
|
684
|
+
onChat = this.ctr({
|
|
685
|
+
logic: async () => ({ data: { ok: true }, message: '@successfully' }),
|
|
686
|
+
}, { protocol: 'socketio' })
|
|
687
|
+
}
|
|
688
|
+
```
|
|
689
|
+
|
|
690
|
+
```typescript
|
|
691
|
+
import { Server } from 'socket.io'
|
|
692
|
+
import coreLoader from '@xrystal/core'
|
|
693
|
+
import { realtimeMiddleware } from '@xrystal/core/utils'
|
|
694
|
+
import { chatCtrl } from './controllers/chat'
|
|
695
|
+
|
|
696
|
+
await coreLoader({})
|
|
697
|
+
|
|
698
|
+
const io = new Server(3001, { cors: { origin: '*' } })
|
|
699
|
+
|
|
700
|
+
io.use((socket, next) => realtimeMiddleware('socketio')(socket, next)) // 1) builder
|
|
701
|
+
io.on('connection', (socket) => {
|
|
702
|
+
socket.on('chat', chatCtrl.onChat.with(socket)) // 2+3) ctr → emit
|
|
703
|
+
})
|
|
704
|
+
```
|
|
705
|
+
|
|
706
|
+
**EN:** Default emit event comes from Dto config (`socket.event`, default `'response'`). Override in `tmp.yml` → `loaders.dto`.
|
|
707
|
+
|
|
708
|
+
**TR:** Varsayılan emit event'i Dto config'den gelir (`socket.event`, default `'response'`). `tmp.yml` → `loaders.dto` ile override.
|
|
709
|
+
|
|
710
|
+
### Without controller / Controller olmadan
|
|
711
|
+
|
|
712
|
+
**EN:** Plain function — use `runAction` when you don't need `checks` / i18n / `this.logger`.
|
|
713
|
+
|
|
714
|
+
**TR:** Düz fonksiyon — `checks` / i18n / `this.logger` gerekmiyorsa `runAction`.
|
|
715
|
+
|
|
716
|
+
```typescript
|
|
717
|
+
import { runAction, getDtoRuntime } from '@xrystal/core/utils'
|
|
718
|
+
|
|
719
|
+
// WebSocket
|
|
720
|
+
socket.on('message', () =>
|
|
721
|
+
runAction({ protocol: 'ws', socket }, async () => {
|
|
722
|
+
return socket.builder.as.ok({ ping: 1 }).build()
|
|
723
|
+
}),
|
|
724
|
+
)
|
|
725
|
+
|
|
726
|
+
// Socket.IO
|
|
727
|
+
socket.on('ping', () =>
|
|
728
|
+
runAction({ protocol: 'socketio', socket }, async () => {
|
|
729
|
+
return getDtoRuntime().forSocket(socket).builder.as.ok({ pong: true }).build()
|
|
730
|
+
}),
|
|
731
|
+
)
|
|
732
|
+
```
|
|
733
|
+
|
|
734
|
+
### ws vs Socket.IO — transport farkı
|
|
735
|
+
|
|
736
|
+
| | WebSocket (ws) | Socket.IO |
|
|
737
|
+
|---|----------------|-----------|
|
|
738
|
+
| Wire / Kablo | `socket.send(JSON string)` | `socket.emit(event, object)` |
|
|
739
|
+
| `ctr()` protocol | `{ protocol: 'ws' }` | `{ protocol: 'socketio' }` |
|
|
740
|
+
| Middleware | `realtimeMiddleware()` or `realtimeMiddleware('ws')` | `realtimeMiddleware('socketio')` |
|
|
741
|
+
| Same `FinalResult` | ✅ same builder | ✅ same builder |
|
|
742
|
+
|
|
743
|
+
**EN:** Pick **ws** for native WebSocket clients. Pick **socket.io** when you need rooms, fallback transport, or existing Socket.IO clients.
|
|
744
|
+
|
|
745
|
+
**TR:** Native WebSocket client → **ws**. Room, fallback transport veya mevcut Socket.IO client → **socket.io**.
|
|
746
|
+
|
|
747
|
+
### Same logic, two protocols / Aynı logic, iki protocol
|
|
748
|
+
|
|
749
|
+
```typescript
|
|
750
|
+
class ChatController extends Controller {
|
|
751
|
+
onWs = this.ctr({ logic: async () => ({ data: { via: 'ws' } }) }, { protocol: 'ws' })
|
|
752
|
+
onSio = this.ctr({ logic: async () => ({ data: { via: 'socketio' } }) }, { protocol: 'socketio' })
|
|
753
|
+
}
|
|
754
|
+
```
|
|
755
|
+
|
|
756
|
+
---
|
|
757
|
+
|
|
457
758
|
## Maintainer note / Geliştirici notu
|
|
458
759
|
|
|
459
760
|
**EN:** This repo is the `@xrystal/core` source. npm publish and build pipeline live in repo scripts (`release:prepare`, `x/bin/scripts/`) — not needed for library consumers.
|
package/package.json
CHANGED
package/x/dist/project/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
import A from"path";import{fileURLToPath as O}from"node:url";import{System as Q,Configs as V,Logger as W,Events as X,Localizations as Y,DtoRuntime as Z,Clients as _,Controller as $,KafkaForCore as v}from"../loader";import{Constants as z,getCore as F,x as K}from"../utils";import{ensureCoreTmpEntry as U,isCorePackageRoot as b}from"../utils/helpers/core/tmp-layout";import{getTmpSnapshot as j}from"../utils/helpers/tmp/tmp-loader";export{ensureCoreTmpEntry,isCorePackageRoot}from"../utils/helpers/core/tmp-layout";export{getTmpSnapshot}from"../utils/helpers/tmp/tmp-loader";export const core=F(),coreInit=async(B)=>{const{locales:q}=B;if(q)globalThis.__LOCAL_MESSAGES__=q};let I=!1;const J=A.dirname(O(import.meta.url)),k=A.join(J,"..","loader","**/*.{ts,js}"),x=A.join(J,"..","utils","**/class.x.{ts,js}"),G=async(B={})=>{if(I)return core;const q=process.cwd();if(b(q))U(q);j();try{await(await K.load([k],{exclude:[x]})).initialize([{service:Q,props:{core}},{service:V,props:{}},{service:v,props:{}},{service:W,props:{}},{service:X,props:{}},{service:Y,props:{}},{service:Z,props:{}},{service:$,props:{}},{service:_,props:{}}]);I=!0;return core}catch(w){const N=w instanceof Error?w.message:String(w);console.error(`[${z.packageName} core failure]: ${N}`);throw w}};export default G;
|