@spear340000/core 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # @spear340000/core
2
+
3
+ RouteFlow 프레임워크 코어.
4
+
5
+ ## 설치
6
+
7
+ ```bash
8
+ pnpm add @spear340000/core reflect-metadata
9
+ ```
10
+
11
+ `tsconfig.json`에 반드시 추가:
12
+
13
+ ```json
14
+ {
15
+ "compilerOptions": {
16
+ "experimentalDecorators": true,
17
+ "emitDecoratorMetadata": true
18
+ }
19
+ }
20
+ ```
21
+
22
+ ## 기본 사용법
23
+
24
+ ```typescript
25
+ import 'reflect-metadata'
26
+ import { createApp, Reactive, Route } from '@spear340000/core'
27
+ import { MemoryAdapter } from '@spear340000/core/adapters'
28
+ import type { Context } from '@spear340000/core'
29
+
30
+ const adapter = new MemoryAdapter()
31
+
32
+ class OrderController {
33
+ // 일반 REST
34
+ @Route('GET', '/orders/:userId')
35
+ async getOrders(ctx: Context) {
36
+ return db.query('SELECT * FROM orders WHERE user_id = $1', [ctx.params.userId])
37
+ }
38
+
39
+ // 반응형 — DB 변경 시 구독 클라이언트에 자동 푸시
40
+ @Reactive({
41
+ watch: 'orders',
42
+ filter: (event, ctx) => {
43
+ const row = event.newRow as { user_id: string } | null
44
+ return row?.user_id === ctx.params.userId
45
+ },
46
+ })
47
+ @Route('GET', '/orders/:userId/live')
48
+ async getLiveOrders(ctx: Context) {
49
+ return db.query('SELECT * FROM orders WHERE user_id = $1', [ctx.params.userId])
50
+ }
51
+ }
52
+
53
+ const app = createApp({ adapter, port: 3000 })
54
+ app.register(OrderController)
55
+ await app.listen()
56
+ ```
57
+
58
+ ## Transport
59
+
60
+ | 옵션 | 설명 |
61
+ |---|---|
62
+ | `'websocket'` (기본) | WS 업그레이드, 양방향 |
63
+ | `'sse'` | `GET /_sse/subscribe?path=...`, 단방향, HTTP/1.1 호환 |
64
+
65
+ ```typescript
66
+ createApp({ adapter, transport: 'sse', port: 3000 })
67
+ ```
68
+
69
+ ## API
70
+
71
+ ### `createApp(options)`
72
+
73
+ | 필드 | 타입 | 기본값 | 설명 |
74
+ |---|---|---|---|
75
+ | `adapter` | `DatabaseAdapter` | — | DB 어댑터 인스턴스 |
76
+ | `transport` | `'websocket' \| 'sse'` | `'websocket'` | 실시간 전송 방식 |
77
+ | `port` | `number` | `3000` | 리슨 포트 |
78
+
79
+ ### `@Route(method, path)`
80
+
81
+ 메서드를 HTTP 엔드포인트로 등록. Fastify 스타일 경로 파라미터(`:param`) 지원.
82
+
83
+ ### `@Reactive(options)`
84
+
85
+ `@Route`와 함께 사용. DB 변경 시 핸들러를 재실행하여 결과를 구독자에게 푸시.
86
+
87
+ | 필드 | 타입 | 설명 |
88
+ |---|---|---|
89
+ | `watch` | `string \| string[]` | 감시할 테이블명 |
90
+ | `filter` | `(event, ctx) => boolean` | 구독자별 필터 함수 |
91
+ | `debounce` | `number` | 디바운스 ms |
92
+
93
+ ### `MemoryAdapter`
94
+
95
+ DB 없이 테스트/개발용. `emit(table, event)`로 변경 이벤트를 수동 발생.
96
+
97
+ ### `PollingAdapter`
98
+
99
+ 네이티브 RouteFlow 어댑터가 아직 없는 DB를 연결할 때 사용하는 범용 어댑터.
100
+
101
+ ```typescript
102
+ import { PollingAdapter } from '@spear340000/core/adapters'
103
+
104
+ const adapter = new PollingAdapter<string>({
105
+ intervalMs: 1_000,
106
+ async readChanges({ table, cursor }) {
107
+ const changes = await fetchChangeFeed(table, cursor)
108
+ return {
109
+ cursor: changes.at(-1)?.cursor ?? cursor,
110
+ events: changes.map((change) => ({
111
+ operation: change.operation,
112
+ newRow: change.newRow,
113
+ oldRow: change.oldRow,
114
+ })),
115
+ }
116
+ },
117
+ })
118
+ ```
119
+
120
+ ### 지원 매트릭스
121
+
122
+ `@spear340000/core`에서 바로 조회 가능:
123
+
124
+ ```typescript
125
+ import {
126
+ SUPPORTED_DATABASES,
127
+ getDatabaseSupport,
128
+ listOfficialDatabases,
129
+ } from '@spear340000/core'
130
+
131
+ console.log(SUPPORTED_DATABASES.length) // 28
132
+ console.log(listOfficialDatabases().map((db) => db.name))
133
+ console.log(getDatabaseSupport('MongoDB'))
134
+ ```
135
+
136
+ ### 공식 지원
137
+
138
+ | DB | tier | 대표 연결 방식 |
139
+ |---|---|---|
140
+ | PostgreSQL | `official` | native adapter |
141
+ | MySQL | `official` | native adapter |
142
+ | MongoDB | `official` | native adapter |
143
+ | Redis | `official` | native adapter |
144
+ | DynamoDB | `official` | native adapter |
145
+ | Elasticsearch | `official` | native adapter |
146
+ | OpenSearch | `official` | native adapter |
147
+ | Snowflake | `official` | native adapter |
148
+
149
+ 공식 지원 DB:
150
+
151
+ - PostgreSQL, MySQL, MongoDB, Redis
152
+ - DynamoDB
153
+ - Elasticsearch, OpenSearch
154
+ - Snowflake
155
+
156
+ 그 외 등록된 DB는 실험적/보류 상태로 매트릭스에만 남아 있습니다.
@@ -0,0 +1,82 @@
1
+ import { D as DatabaseAdapter, C as ChangeEvent } from '../types-tPDla8AE.mjs';
2
+
3
+ /**
4
+ * In-memory database adapter for testing and local development.
5
+ * No real database connection is needed — changes are triggered manually via `emit()`.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const adapter = new MemoryAdapter()
10
+ * await adapter.connect()
11
+ *
12
+ * adapter.onChange('orders', (event) => console.log(event))
13
+ *
14
+ * adapter.emit('orders', { operation: 'INSERT', newRow: { id: 1 }, oldRow: null })
15
+ * ```
16
+ */
17
+ declare class MemoryAdapter implements DatabaseAdapter {
18
+ private readonly listeners;
19
+ private connected;
20
+ /** No-op — MemoryAdapter requires no real connection. */
21
+ connect(): Promise<void>;
22
+ /** No-op — clears all listeners on disconnect. */
23
+ disconnect(): Promise<void>;
24
+ /**
25
+ * Register a listener for changes on a specific table.
26
+ * @returns An unsubscribe function.
27
+ */
28
+ onChange(table: string, callback: (event: ChangeEvent) => void): () => void;
29
+ /**
30
+ * Manually emit a change event on a table.
31
+ * Useful in tests and examples to simulate DB changes without a real database.
32
+ *
33
+ * @param table - Table name to emit the event on
34
+ * @param event - Change event data (table and timestamp are filled in automatically)
35
+ */
36
+ emit(table: string, event: Omit<ChangeEvent, 'table' | 'timestamp'>): void;
37
+ /** Returns true if connect() has been called and disconnect() has not. */
38
+ get isConnected(): boolean;
39
+ }
40
+
41
+ interface PollingReadResult<T = unknown, TCursor = unknown> {
42
+ events: Array<Omit<ChangeEvent<T>, 'table' | 'timestamp'> & Partial<Pick<ChangeEvent<T>, 'table' | 'timestamp'>>>;
43
+ cursor?: TCursor;
44
+ }
45
+ interface PollingReadContext<TCursor = unknown> {
46
+ cursor: TCursor | undefined;
47
+ table: string;
48
+ }
49
+ interface PollingAdapterOptions<TCursor = unknown> {
50
+ intervalMs?: number;
51
+ now?: () => number;
52
+ onError?: (error: unknown, context: {
53
+ table: string;
54
+ }) => void;
55
+ readChanges: (context: PollingReadContext<TCursor>) => Promise<PollingReadResult<unknown, TCursor>>;
56
+ }
57
+ /**
58
+ * Generic polling-based adapter for databases without a native RouteFlow adapter yet.
59
+ * It works with any backend as long as callers can periodically read a change feed.
60
+ */
61
+ declare class PollingAdapter<TCursor = unknown> implements DatabaseAdapter {
62
+ private readonly listeners;
63
+ private readonly cursors;
64
+ private readonly timers;
65
+ private readonly activeTables;
66
+ private readonly intervalMs;
67
+ private readonly now;
68
+ private readonly readChanges;
69
+ private readonly onError?;
70
+ private connected;
71
+ constructor(options: PollingAdapterOptions<TCursor>);
72
+ connect(): Promise<void>;
73
+ disconnect(): Promise<void>;
74
+ onChange(table: string, callback: (event: ChangeEvent) => void): () => void;
75
+ private ensurePolling;
76
+ private stopPolling;
77
+ private scheduleNext;
78
+ private poll;
79
+ private emit;
80
+ }
81
+
82
+ export { MemoryAdapter, PollingAdapter, type PollingAdapterOptions, type PollingReadContext, type PollingReadResult };
@@ -0,0 +1,82 @@
1
+ import { D as DatabaseAdapter, C as ChangeEvent } from '../types-tPDla8AE.js';
2
+
3
+ /**
4
+ * In-memory database adapter for testing and local development.
5
+ * No real database connection is needed — changes are triggered manually via `emit()`.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const adapter = new MemoryAdapter()
10
+ * await adapter.connect()
11
+ *
12
+ * adapter.onChange('orders', (event) => console.log(event))
13
+ *
14
+ * adapter.emit('orders', { operation: 'INSERT', newRow: { id: 1 }, oldRow: null })
15
+ * ```
16
+ */
17
+ declare class MemoryAdapter implements DatabaseAdapter {
18
+ private readonly listeners;
19
+ private connected;
20
+ /** No-op — MemoryAdapter requires no real connection. */
21
+ connect(): Promise<void>;
22
+ /** No-op — clears all listeners on disconnect. */
23
+ disconnect(): Promise<void>;
24
+ /**
25
+ * Register a listener for changes on a specific table.
26
+ * @returns An unsubscribe function.
27
+ */
28
+ onChange(table: string, callback: (event: ChangeEvent) => void): () => void;
29
+ /**
30
+ * Manually emit a change event on a table.
31
+ * Useful in tests and examples to simulate DB changes without a real database.
32
+ *
33
+ * @param table - Table name to emit the event on
34
+ * @param event - Change event data (table and timestamp are filled in automatically)
35
+ */
36
+ emit(table: string, event: Omit<ChangeEvent, 'table' | 'timestamp'>): void;
37
+ /** Returns true if connect() has been called and disconnect() has not. */
38
+ get isConnected(): boolean;
39
+ }
40
+
41
+ interface PollingReadResult<T = unknown, TCursor = unknown> {
42
+ events: Array<Omit<ChangeEvent<T>, 'table' | 'timestamp'> & Partial<Pick<ChangeEvent<T>, 'table' | 'timestamp'>>>;
43
+ cursor?: TCursor;
44
+ }
45
+ interface PollingReadContext<TCursor = unknown> {
46
+ cursor: TCursor | undefined;
47
+ table: string;
48
+ }
49
+ interface PollingAdapterOptions<TCursor = unknown> {
50
+ intervalMs?: number;
51
+ now?: () => number;
52
+ onError?: (error: unknown, context: {
53
+ table: string;
54
+ }) => void;
55
+ readChanges: (context: PollingReadContext<TCursor>) => Promise<PollingReadResult<unknown, TCursor>>;
56
+ }
57
+ /**
58
+ * Generic polling-based adapter for databases without a native RouteFlow adapter yet.
59
+ * It works with any backend as long as callers can periodically read a change feed.
60
+ */
61
+ declare class PollingAdapter<TCursor = unknown> implements DatabaseAdapter {
62
+ private readonly listeners;
63
+ private readonly cursors;
64
+ private readonly timers;
65
+ private readonly activeTables;
66
+ private readonly intervalMs;
67
+ private readonly now;
68
+ private readonly readChanges;
69
+ private readonly onError?;
70
+ private connected;
71
+ constructor(options: PollingAdapterOptions<TCursor>);
72
+ connect(): Promise<void>;
73
+ disconnect(): Promise<void>;
74
+ onChange(table: string, callback: (event: ChangeEvent) => void): () => void;
75
+ private ensurePolling;
76
+ private stopPolling;
77
+ private scheduleNext;
78
+ private poll;
79
+ private emit;
80
+ }
81
+
82
+ export { MemoryAdapter, PollingAdapter, type PollingAdapterOptions, type PollingReadContext, type PollingReadResult };
@@ -0,0 +1,170 @@
1
+ 'use strict';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
5
+
6
+ // src/adapter/memory-adapter.ts
7
+ var MemoryAdapter = class {
8
+ static {
9
+ __name(this, "MemoryAdapter");
10
+ }
11
+ listeners = /* @__PURE__ */ new Map();
12
+ connected = false;
13
+ /** No-op — MemoryAdapter requires no real connection. */
14
+ async connect() {
15
+ this.connected = true;
16
+ }
17
+ /** No-op — clears all listeners on disconnect. */
18
+ async disconnect() {
19
+ this.listeners.clear();
20
+ this.connected = false;
21
+ }
22
+ /**
23
+ * Register a listener for changes on a specific table.
24
+ * @returns An unsubscribe function.
25
+ */
26
+ onChange(table, callback) {
27
+ if (!this.listeners.has(table)) {
28
+ this.listeners.set(table, /* @__PURE__ */ new Set());
29
+ }
30
+ this.listeners.get(table).add(callback);
31
+ return () => {
32
+ this.listeners.get(table)?.delete(callback);
33
+ };
34
+ }
35
+ /**
36
+ * Manually emit a change event on a table.
37
+ * Useful in tests and examples to simulate DB changes without a real database.
38
+ *
39
+ * @param table - Table name to emit the event on
40
+ * @param event - Change event data (table and timestamp are filled in automatically)
41
+ */
42
+ emit(table, event) {
43
+ const fullEvent = {
44
+ ...event,
45
+ table,
46
+ timestamp: Date.now()
47
+ };
48
+ const callbacks = this.listeners.get(table);
49
+ if (!callbacks) return;
50
+ for (const cb of callbacks) {
51
+ cb(fullEvent);
52
+ }
53
+ }
54
+ /** Returns true if connect() has been called and disconnect() has not. */
55
+ get isConnected() {
56
+ return this.connected;
57
+ }
58
+ };
59
+
60
+ // src/adapter/polling-adapter.ts
61
+ var PollingAdapter = class {
62
+ static {
63
+ __name(this, "PollingAdapter");
64
+ }
65
+ listeners = /* @__PURE__ */ new Map();
66
+ cursors = /* @__PURE__ */ new Map();
67
+ timers = /* @__PURE__ */ new Map();
68
+ activeTables = /* @__PURE__ */ new Set();
69
+ intervalMs;
70
+ now;
71
+ readChanges;
72
+ onError;
73
+ connected = false;
74
+ constructor(options) {
75
+ this.intervalMs = options.intervalMs ?? 1e3;
76
+ this.now = options.now ?? (() => Date.now());
77
+ this.readChanges = options.readChanges;
78
+ this.onError = options.onError;
79
+ }
80
+ async connect() {
81
+ this.connected = true;
82
+ for (const table of this.listeners.keys()) {
83
+ this.ensurePolling(table);
84
+ }
85
+ }
86
+ async disconnect() {
87
+ this.connected = false;
88
+ for (const timer of this.timers.values()) {
89
+ clearTimeout(timer);
90
+ }
91
+ this.timers.clear();
92
+ this.activeTables.clear();
93
+ }
94
+ onChange(table, callback) {
95
+ if (!this.listeners.has(table)) {
96
+ this.listeners.set(table, /* @__PURE__ */ new Set());
97
+ }
98
+ this.listeners.get(table).add(callback);
99
+ this.ensurePolling(table);
100
+ return () => {
101
+ const callbacks = this.listeners.get(table);
102
+ if (!callbacks) return;
103
+ callbacks.delete(callback);
104
+ if (callbacks.size === 0) {
105
+ this.listeners.delete(table);
106
+ this.stopPolling(table);
107
+ }
108
+ };
109
+ }
110
+ ensurePolling(table) {
111
+ if (!this.connected || this.activeTables.has(table)) return;
112
+ this.activeTables.add(table);
113
+ void this.poll(table);
114
+ }
115
+ stopPolling(table) {
116
+ const timer = this.timers.get(table);
117
+ if (timer) clearTimeout(timer);
118
+ this.timers.delete(table);
119
+ this.activeTables.delete(table);
120
+ this.cursors.delete(table);
121
+ }
122
+ scheduleNext(table) {
123
+ if (!this.connected || !this.listeners.has(table)) {
124
+ this.stopPolling(table);
125
+ return;
126
+ }
127
+ const timer = setTimeout(() => {
128
+ void this.poll(table);
129
+ }, this.intervalMs);
130
+ this.timers.set(table, timer);
131
+ }
132
+ async poll(table) {
133
+ if (!this.connected || !this.listeners.has(table)) {
134
+ this.stopPolling(table);
135
+ return;
136
+ }
137
+ try {
138
+ const result = await this.readChanges({
139
+ table,
140
+ cursor: this.cursors.get(table)
141
+ });
142
+ this.cursors.set(table, result.cursor);
143
+ for (const event of result.events) {
144
+ this.emit(table, event);
145
+ }
146
+ } catch (error) {
147
+ this.onError?.(error, { table });
148
+ } finally {
149
+ this.activeTables.delete(table);
150
+ this.scheduleNext(table);
151
+ }
152
+ }
153
+ emit(defaultTable, event) {
154
+ const fullEvent = {
155
+ ...event,
156
+ table: event.table ?? defaultTable,
157
+ timestamp: event.timestamp ?? this.now()
158
+ };
159
+ const callbacks = this.listeners.get(fullEvent.table);
160
+ if (!callbacks) return;
161
+ for (const callback of callbacks) {
162
+ callback(fullEvent);
163
+ }
164
+ }
165
+ };
166
+
167
+ exports.MemoryAdapter = MemoryAdapter;
168
+ exports.PollingAdapter = PollingAdapter;
169
+ //# sourceMappingURL=index.js.map
170
+ //# sourceMappingURL=index.js.map