@sebspark/pg-live 0.0.0-stage → 0.0.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 +201 -0
- package/README.md +245 -2
- package/dist/index.d.mts +94 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +311 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +42 -4
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 [2026] [SEB]
|
|
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
CHANGED
|
@@ -1,3 +1,246 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @sebspark/pg-live
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Share live Postgres rows between the processes that change them and the processes that read them. Built on Postgres `LISTEN` / `NOTIFY` and [node-postgres](https://node-postgres.com).
|
|
4
|
+
|
|
5
|
+
One live table definition is used on both sides:
|
|
6
|
+
|
|
7
|
+
- **Producers** write rows and notify, in the same transaction: `writeAndNotify()`. The notification carries the changed rows themselves, so consumers rarely need to touch the database.
|
|
8
|
+
- **Consumers** keep all rows of a table in memory and apply each change as it arrives: `live()`. They hydrate once with one `SELECT` at startup, look rows up in O(1) by key, and get told exactly what changed.
|
|
9
|
+
|
|
10
|
+
Made for hot paths that cannot afford a database round trip per lookup. For example, a service updates user preferences through `writeAndNotify()`, while every worker that decides on incoming events whether to notify a user holds all preferences in memory with `live()`.
|
|
11
|
+
|
|
12
|
+
## The cost: memory
|
|
13
|
+
|
|
14
|
+
Every consumer process holds every row of the table in memory, so lookups take micro- rather than milliseconds. That speed is paid for in memory, once per process.
|
|
15
|
+
|
|
16
|
+
For example, 700,000 users with an id, a push token, an X-Wing public key (1,216 bytes, base64) and a locale take about 2 KB each in Node, around 1.3 GB of heap per consumer. With four consumers, that is over 5 GB.
|
|
17
|
+
|
|
18
|
+
It is worth it only where lookups must take micro- to milliseconds, faster than a round trip to the database allows. Otherwise, query the database.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
npm install @sebspark/pg-live pg
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Define a live table
|
|
27
|
+
|
|
28
|
+
A live table is shared by the processes that write and the processes that read, so both agree on the table, the channel and the shape of a row. It holds all rows of one table: no joins, no filters.
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { defineTable } from '@sebspark/pg-live'
|
|
32
|
+
|
|
33
|
+
type UserPrefs = {
|
|
34
|
+
user_id: string
|
|
35
|
+
channels: string[]
|
|
36
|
+
quiet_hours: { from: string; to: string } | null
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const userPrefs = defineTable<UserPrefs>({
|
|
40
|
+
table: 'user_preferences',
|
|
41
|
+
key: 'user_id', // must be a property of UserPrefs
|
|
42
|
+
})
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
| Option | Meaning |
|
|
46
|
+
| --- | --- |
|
|
47
|
+
| `table` | Table to keep live. May be schema-qualified, e.g. `app.user_preferences`. |
|
|
48
|
+
| `key` | Column that identifies a row, usually the primary key. |
|
|
49
|
+
| `channel` | Optional. Channel the changes are sent on. Default: `<table>_changed`. |
|
|
50
|
+
|
|
51
|
+
### Row shape
|
|
52
|
+
|
|
53
|
+
A row is the table row as JSON (`to_jsonb`), whether it arrived at startup, in a notification, or when read by key. pg-live supports simple column types and `json`/`jsonb`: text, numbers, booleans and arrays arrive as their JSON values, `json`/`jsonb` as the JSON they hold, and timestamps as ISO strings.
|
|
54
|
+
|
|
55
|
+
### Typing rows
|
|
56
|
+
|
|
57
|
+
Declare the row type with a type parameter, `defineTable<UserPrefs>(...)`, and it flows to every API that uses it: `has(key)`, `get(key)`, the events, and the keys returned to `writeAndNotify`. The rows are trusted to match, the same way a typed query result is. Without a type parameter, rows are plain JSON objects.
|
|
58
|
+
|
|
59
|
+
Keys are typed loosely: as the type of any column, not just the key column's. TypeScript cannot infer the key's own type once the row type is given explicitly, so `get(['push'])` compiles. Precise key types come from [@sebspark/drizzle-live](../drizzle-live), which derives them from the schema.
|
|
60
|
+
|
|
61
|
+
For typed rows derived from a Drizzle schema, with Drizzle's casing, see [@sebspark/drizzle-live](../drizzle-live).
|
|
62
|
+
|
|
63
|
+
## Read and stay updated
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
import { Pool } from 'pg'
|
|
67
|
+
import { createListener, live } from '@sebspark/pg-live'
|
|
68
|
+
import { userPrefs } from './tables'
|
|
69
|
+
|
|
70
|
+
const pool = new Pool({ connectionString })
|
|
71
|
+
const listener = createListener({ connectionString }) // one per process
|
|
72
|
+
|
|
73
|
+
const prefs = await live(userPrefs, { pool, listener })
|
|
74
|
+
|
|
75
|
+
prefs.has(userId) // whether a row exists for a key
|
|
76
|
+
prefs.get(userId) // current row for a key, or undefined
|
|
77
|
+
|
|
78
|
+
prefs.on('add', (row) => {}) // a row that was not in the map
|
|
79
|
+
prefs.on('update', (row) => {}) // a row that was in the map and changed
|
|
80
|
+
prefs.on('delete', (key) => {}) // a row that no longer exists
|
|
81
|
+
|
|
82
|
+
prefs.on('change', (type, payload) => {
|
|
83
|
+
// every add, update and delete; payload is a row, or a key for 'delete'
|
|
84
|
+
if (type === 'delete') forget(payload)
|
|
85
|
+
else remember(payload)
|
|
86
|
+
})
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`await live()` resolves when the table is hydrated, so `get` is ready to use from then on. The events report changes from then on; the rows loaded at startup do not emit `add`. A row that arrives identical to the one already in the map changes nothing and emits nothing.
|
|
90
|
+
|
|
91
|
+
The returned object exposes only reads and events. The rows live in a `Map` that only pg-live writes to, so a consumer cannot change its copy by mistake:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
type Events<T, K extends keyof T> = { add: T; update: T; delete: T[K] }
|
|
95
|
+
|
|
96
|
+
type ChangeListener<T, K extends keyof T> = (
|
|
97
|
+
...args: { [E in keyof Events<T, K>]: [type: E, payload: Events<T, K>[E]] }[keyof Events<T, K>]
|
|
98
|
+
) => void
|
|
99
|
+
|
|
100
|
+
type Live<T, K extends keyof T> = Pick<Map<T[K], T>, 'has' | 'get'> & {
|
|
101
|
+
on<E extends keyof Events<T, K>>(event: E, listener: (payload: Events<T, K>[E]) => void): Live<T, K>
|
|
102
|
+
on(event: 'change', listener: ChangeListener<T, K>): Live<T, K>
|
|
103
|
+
on(event: 'error', listener: (error: unknown) => void): Live<T, K>
|
|
104
|
+
// once and off have the same signatures
|
|
105
|
+
close(): Promise<void>
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`on`, `once` and `off` behave like Node's `EventEmitter`, but only accept these four events and `error`, so a misspelled event name is a type error. In a `change` listener, checking `type` narrows `payload`.
|
|
110
|
+
|
|
111
|
+
### What `live()` does
|
|
112
|
+
|
|
113
|
+
1. Makes sure the shared listener runs `LISTEN` on the table's channel.
|
|
114
|
+
2. Only after `LISTEN` is active, reads all rows in one query and fills the map. Notifications that arrive meanwhile are held and applied after, so no change slips in between the read and the subscription.
|
|
115
|
+
3. On each notification:
|
|
116
|
+
- rows in the payload are applied directly, without touching the database;
|
|
117
|
+
- keys in the payload are read in one query (`WHERE key = ANY(...)`). A key that no longer exists is deleted;
|
|
118
|
+
- deleted keys are removed from the map.
|
|
119
|
+
4. Emits `add`, `update` or `delete` for every row that changed, each followed by `change`.
|
|
120
|
+
5. On reconnect, re-runs `LISTEN` and reads all rows again, because notifications sent while disconnected are not replayed. Events are emitted for the difference between before and after.
|
|
121
|
+
|
|
122
|
+
Changes to the same key are applied in the order Postgres delivered them. A key that is being read when a new change for it arrives is handled after that read, so every key ends at its latest committed state.
|
|
123
|
+
|
|
124
|
+
### Options
|
|
125
|
+
|
|
126
|
+
| Option | Meaning |
|
|
127
|
+
| --- | --- |
|
|
128
|
+
| `pool` | `pg` Pool used for hydration and for reading rows by key. |
|
|
129
|
+
| `listener` | Shared listener from `createListener()`. |
|
|
130
|
+
|
|
131
|
+
### Errors
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
prefs.on('error', (error) => {
|
|
135
|
+
logger.error(error) // e.g. the rows could not be read again after a reconnect
|
|
136
|
+
})
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
A lost connection is not an error: the listener reconnects on its own, and the table loads again. Errors are what pg-live cannot recover from, such as a failed read.
|
|
140
|
+
|
|
141
|
+
Once `live()` has resolved, errors happen in the background, with no caller to reject to. They are reported on the live object, like Node's `EventEmitter`: with an `error` listener, they go to it; without one, the error is thrown and ends the process. If loading fails before `live()` resolves, `live()` rejects instead.
|
|
142
|
+
|
|
143
|
+
### The shared listener
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
const listener = createListener({ connectionString })
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`LISTEN` needs a long-lived session. `createListener()` opens one dedicated connection per process and serves every live table and channel over it, so the number of connections to Postgres does not grow with the number of tables. Do not point it at a pooler in transaction mode.
|
|
150
|
+
|
|
151
|
+
If the connection is lost, the listener reconnects on its own, retrying with a growing delay of up to 5 seconds, and every live table using it hydrates again.
|
|
152
|
+
|
|
153
|
+
## Write and notify
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
import { writeAndNotify } from '@sebspark/pg-live'
|
|
157
|
+
import { userPrefs } from './tables'
|
|
158
|
+
|
|
159
|
+
await writeAndNotify(pool, userPrefs, async (tx) => {
|
|
160
|
+
await tx.query(
|
|
161
|
+
'UPDATE user_preferences SET channels = $1 WHERE user_id = $2',
|
|
162
|
+
[channels, userId]
|
|
163
|
+
)
|
|
164
|
+
return [userId] // keys of the rows you changed or deleted
|
|
165
|
+
})
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`tx` is a `pg` client inside the transaction. The callback returns the keys of the rows it changed or deleted. Return them as the key column's values, with their JSON type: a number for an `integer` key, not a string. A key that matches no row is sent as deleted, so returning `'42'` for row `42` makes every listener drop it. pg-live's loose key typing will not catch this.
|
|
169
|
+
|
|
170
|
+
`writeAndNotify` runs the callback in a transaction. Before commit, in the same transaction, it reads the returned keys and sends:
|
|
171
|
+
|
|
172
|
+
- rows that exist, as rows;
|
|
173
|
+
- keys that no longer exist, as deleted.
|
|
174
|
+
|
|
175
|
+
Payloads are split into several notifications when needed to stay under the size limit. A single row too big for a notification is sent as its key, and listeners read it.
|
|
176
|
+
|
|
177
|
+
The notifications are delivered only if the transaction commits, so listeners never see a change that was rolled back.
|
|
178
|
+
|
|
179
|
+
## Building blocks
|
|
180
|
+
|
|
181
|
+
Integrations such as [@sebspark/drizzle-live](../drizzle-live) build on these pieces.
|
|
182
|
+
|
|
183
|
+
A live table is a plain object, so an integration can build one directly instead of using `defineTable`. Besides `table` and `channel`, it holds:
|
|
184
|
+
|
|
185
|
+
- `key`: the row property that identifies a row;
|
|
186
|
+
- `column`: the column that holds the key in the table;
|
|
187
|
+
- `fromDb(row)`: turns a row as Postgres sends it (`to_jsonb`, keyed by column name) into a row of the live table.
|
|
188
|
+
|
|
189
|
+
`defineTable` sets `column` to `key`, and `fromDb` to return the row as it is.
|
|
190
|
+
|
|
191
|
+
`writeAndNotify` is built from a smaller piece that notifies inside a transaction you already have open:
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
import { notifyChanges, type Query } from '@sebspark/pg-live'
|
|
195
|
+
|
|
196
|
+
// Runs SQL with $1, $2... parameters in the transaction you have open
|
|
197
|
+
const query: Query = async (text, params) => (await client.query(text, params)).rows
|
|
198
|
+
|
|
199
|
+
await notifyChanges(query, userPrefs, [userId])
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## Schema changes
|
|
203
|
+
|
|
204
|
+
Producers and consumers deploy separately, so for a while they run against different versions of the table. pg-live always sends the row as it is in the database when it is read, not what the producer wrote, so the shape of a row follows the table's current schema.
|
|
205
|
+
|
|
206
|
+
To add a column:
|
|
207
|
+
|
|
208
|
+
1. **Add the column**, nullable or with a default. From then on every row pg-live reads or sends includes it. Old consumers receive a property they don't know about, which is harmless.
|
|
209
|
+
2. **Deploy consumers** that accept the column being empty.
|
|
210
|
+
3. **Deploy producers** that write it.
|
|
211
|
+
|
|
212
|
+
Until each row changes again, or the consumer hydrates again on reconnect or restart, a running consumer holds rows from before the column was added. Adding a column changes no rows, so nothing is notified. "Empty" therefore means two things: the property is missing on rows that have not changed, and `null` (or the default) on rows that have. Type the column as optional and nullable, e.g. `newColumn?: string | null`, and treat both the same. The first change to each such row emits `update`, because the row gained the property.
|
|
213
|
+
|
|
214
|
+
Other changes go the other way round:
|
|
215
|
+
|
|
216
|
+
- **Drop a column:** stop writing it, deploy consumers that no longer read it, then drop it.
|
|
217
|
+
- **Rename a column:** add the new column, copy the data, move producers and consumers over, then drop the old one. Never rename in place.
|
|
218
|
+
- **Change the key column:** treat it as a new live table on a new channel.
|
|
219
|
+
|
|
220
|
+
## Guarantees and limits
|
|
221
|
+
|
|
222
|
+
Consumers are eventually consistent with the database: after a transaction commits, consumers still read the old rows until its notification reaches them. This includes a consumer in the process that wrote, so a `get` straight after `await writeAndNotify()` can return the old row. Every consumer applies changes in commit order and ends on the rows the database has.
|
|
223
|
+
|
|
224
|
+
These come from Postgres `NOTIFY` behaviour:
|
|
225
|
+
|
|
226
|
+
- Notifications are delivered after the sending transaction commits, in commit order.
|
|
227
|
+
- Payload must be shorter than 8000 bytes in the default configuration. `pg-live` splits payloads to stay under it. A row too big for a notification is sent as its key, but a single key cannot be split: a key of 8000 bytes or more makes `writeAndNotify` fail.
|
|
228
|
+
- There is no replay. A listener that is not connected misses notifications. That is why `live()` hydrates again on reconnect.
|
|
229
|
+
- If the notification queue is full, transactions that call `NOTIFY` fail at commit.
|
|
230
|
+
|
|
231
|
+
## Graceful shutdown
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
process.on('SIGTERM', async () => {
|
|
235
|
+
await prefs.close() // stop applying changes to this table
|
|
236
|
+
await listener.close() // UNLISTEN and release the dedicated connection
|
|
237
|
+
// ... then close the HTTP server and pool
|
|
238
|
+
})
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
## Non-goals
|
|
242
|
+
|
|
243
|
+
- Not for joins, filters or computed columns. A live table is all rows of one table.
|
|
244
|
+
- Not for tables written outside pg-live. Every write must go through `writeAndNotify`, or listeners will not hear about it.
|
|
245
|
+
- Not a durable message queue. If delivery must not be missed, use an outbox table or a real queue.
|
|
246
|
+
- Not a query builder or ORM.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { Pool, PoolClient } from "pg";
|
|
2
|
+
type Subscriber = {
|
|
3
|
+
onNotify: (payload: string) => void;
|
|
4
|
+
/** Called after a lost connection is back and listening again. */
|
|
5
|
+
onReconnect: () => void;
|
|
6
|
+
};
|
|
7
|
+
type Listener = {
|
|
8
|
+
/** Listens on `channel` until the returned function is called. */
|
|
9
|
+
listen: (channel: string, subscriber: Subscriber) => Promise<() => Promise<void>>;
|
|
10
|
+
/** Stops listening and releases the connection. */
|
|
11
|
+
close: () => Promise<void>;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* One dedicated connection per process for `LISTEN`, shared by every live
|
|
15
|
+
* table and channel.
|
|
16
|
+
*/
|
|
17
|
+
export declare const createListener: ({ connectionString }: {
|
|
18
|
+
connectionString: string;
|
|
19
|
+
}) => Listener;
|
|
20
|
+
/** A table row as Postgres sends it: `to_jsonb(row)`, keyed by column name. */
|
|
21
|
+
type DbRow = Record<string, unknown>;
|
|
22
|
+
/** A table kept live: shared by the processes that write and those that read. */
|
|
23
|
+
type LiveTable<T, K extends keyof T> = {
|
|
24
|
+
table: string;
|
|
25
|
+
channel: string;
|
|
26
|
+
/** Property of a row that identifies it. */
|
|
27
|
+
key: K;
|
|
28
|
+
/** Column in the table that holds the key. */
|
|
29
|
+
column: string;
|
|
30
|
+
/** Turns a row as Postgres sends it into a row of the live table. */
|
|
31
|
+
fromDb: (row: DbRow) => T;
|
|
32
|
+
};
|
|
33
|
+
type TableOptions<T> = {
|
|
34
|
+
/** Table to keep live. May be schema-qualified, e.g. `app.user_preferences`. */
|
|
35
|
+
table: string;
|
|
36
|
+
/** Column that identifies a row, usually the primary key. */
|
|
37
|
+
key: keyof T & string;
|
|
38
|
+
/** Channel the changes are sent on. Default: `<table>_changed`. */
|
|
39
|
+
channel?: string;
|
|
40
|
+
};
|
|
41
|
+
/** Defines a live table. Declare the row type with a type parameter. */
|
|
42
|
+
export declare const defineTable: <T = DbRow>({ table, key, channel }: TableOptions<T>) => LiveTable<T, keyof T & string>;
|
|
43
|
+
/** The payload of each event: the row for `add` and `update`, the key for `delete`. */
|
|
44
|
+
type Events<T, K extends keyof T> = {
|
|
45
|
+
add: T;
|
|
46
|
+
update: T;
|
|
47
|
+
delete: T[K];
|
|
48
|
+
};
|
|
49
|
+
/** Listener for `change`: called with the event type, and its payload narrowed by that type. */
|
|
50
|
+
type ChangeListener<T, K extends keyof T> = (...args: { [E in keyof Events<T, K>]: [type: E, payload: Events<T, K>[E]]; }[keyof Events<T, K>]) => void;
|
|
51
|
+
type Subscribe<T, K extends keyof T> = {
|
|
52
|
+
<E extends keyof Events<T, K>>(event: E, listener: (payload: Events<T, K>[E]) => void): Live<T, K>;
|
|
53
|
+
(event: 'change', listener: ChangeListener<T, K>): Live<T, K>;
|
|
54
|
+
(event: 'error', listener: (error: unknown) => void): Live<T, K>;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* All rows of a live table, kept current. Exposes only reads and events; the
|
|
58
|
+
* rows are written by pg-live alone.
|
|
59
|
+
*/
|
|
60
|
+
type Live<T, K extends keyof T> = Pick<Map<T[K], T>, 'has' | 'get'> & {
|
|
61
|
+
on: Subscribe<T, K>;
|
|
62
|
+
once: Subscribe<T, K>;
|
|
63
|
+
off: Subscribe<T, K>;
|
|
64
|
+
/**
|
|
65
|
+
* Stops applying changes and removes all listeners. Safe to call more than
|
|
66
|
+
* once: every call resolves when closing has finished.
|
|
67
|
+
*/
|
|
68
|
+
close(): Promise<void>;
|
|
69
|
+
};
|
|
70
|
+
type LiveOptions = {
|
|
71
|
+
/** Pool used for hydration and for reading rows by key. */
|
|
72
|
+
pool: Pool;
|
|
73
|
+
/** Shared listener from `createListener()`. */
|
|
74
|
+
listener: Listener;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Keeps all rows of `table` in memory and applies every change as it arrives.
|
|
78
|
+
* Resolves when the rows are loaded; errors after that are emitted as `error`.
|
|
79
|
+
*/
|
|
80
|
+
export declare const live: <T, K extends keyof T>(table: LiveTable<T, K>, { pool, listener }: LiveOptions) => Promise<Live<T, K>>;
|
|
81
|
+
/** Runs SQL with `$1`, `$2`... parameters in an open transaction and returns its rows. */
|
|
82
|
+
type Query = (text: string, params: unknown[]) => Promise<Record<string, unknown>[]>;
|
|
83
|
+
/**
|
|
84
|
+
* Notifies listeners of the rows with `keys`, inside a transaction you already
|
|
85
|
+
* have open: rows that exist are sent as rows, the others as deleted.
|
|
86
|
+
*/
|
|
87
|
+
export declare const notifyChanges: <T, K extends keyof T>(query: Query, table: LiveTable<T, K>, keys: T[K][]) => Promise<void>;
|
|
88
|
+
/**
|
|
89
|
+
* Runs `write` in a transaction and notifies listeners of the keys it returns.
|
|
90
|
+
* The notifications are delivered only if the transaction commits.
|
|
91
|
+
*/
|
|
92
|
+
export declare const writeAndNotify: <T, K extends keyof T>(pool: Pool, table: LiveTable<T, K>, write: (tx: PoolClient) => Promise<T[K][]>) => Promise<void>;
|
|
93
|
+
export type { ChangeListener, Events, Listener, Live, LiveOptions, LiveTable, Query, TableOptions };
|
|
94
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/listener.ts","../src/table.ts","../src/types.ts","../src/live.ts","../src/write.ts"],"mappings":";KAIY;EACV,WAAW;;EAEX;;KAGU;;EAEV,SACE,iBACA,YAAY,eACT,cAAc;;EAEnB,aAAa;;;;;;qBASF,mBAAc;EAGzB;MACE;;KC7BQ,QAAQ;;KAMR,UAAU,GAAG,gBAAgB;EACvC;EACA;;EAEA,KAAK;;EAEL;;EAEA,SAAS,KAAK,UAAU;;KAGd,aAAa;;EAEvB;;EAEA,WAAW;;EAEX;;;qBAIW,cAAe,IAAI,SAAK,OAAA,KAAA,WAIlC,aAAa,OAAK,UAAU,SAAS;;KC/B5B,OAAO,GAAG,gBAAgB;EAAO,KAAK;EAAG,QAAQ;EAAG,QAAQ,EAAE;;;KAG9D,eAAe,GAAG,gBAAgB,SACzC,SACA,WAAW,OAAO,GAAG,MAAM,MAAM,GAAG,SAAS,OAAO,GAAG,GAAG,aACrD,OAAO,GAAG;KAGf,UAAU,GAAG,gBAAgB;GAC/B,gBAAgB,OAAO,GAAG,IACzB,OAAO,GACP,WAAW,SAAS,OAAO,GAAG,GAAG,cAChC,KAAK,GAAG;GACV,iBAAiB,UAAU,eAAe,GAAG,KAAK,KAAK,GAAG;GAC1D,gBAAgB,WAAW,0BAA0B,KAAK,GAAG;;;;;;KAOpD,KAAK,GAAG,gBAAgB,KAAK,KAAK,IAAI,EAAE,IAAI;EACtD,IAAI,UAAU,GAAG;EACjB,MAAM,UAAU,GAAG;EACnB,KAAK,UAAU,GAAG;;;;;EAKlB,SAAS;;KCxBC;;EAEV,MAAM;;EAEN,UAAU;;;;;;qBAOC,OAAc,GAAG,gBAAgB,GAAC,OACtC,UAAU,GAAG,MAAE,MAAA,YACF,gBACnB,QAAQ,KAAK,GAAG;;KChBP,SACV,cACA,sBACG,QAAQ;;;;;qBAMA,gBAAuB,GAAG,gBAAgB,GAAC,OAC/C,OAAK,OACL,UAAU,GAAG,IAAE,MAChB,EAAE,SAAI;;;;;qBAqBD,iBAAwB,GAAG,gBAAgB,GAAC,MACjD,MAAI,OACH,UAAU,GAAG,IAAE,QACd,IAAI,eAAe,QAAQ,EAAE,UAAK"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
import { setTimeout } from "node:timers/promises";
|
|
2
|
+
import { Client } from "pg";
|
|
3
|
+
import { EventEmitter } from "node:events";
|
|
4
|
+
import { isDeepStrictEqual } from "node:util";
|
|
5
|
+
// src/table.ts
|
|
6
|
+
const isDbRow = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7
|
+
/** Defines a live table. Declare the row type with a type parameter. */
|
|
8
|
+
const defineTable = ({ table, key, channel = `${table}_changed` }) => ({
|
|
9
|
+
table,
|
|
10
|
+
channel,
|
|
11
|
+
key,
|
|
12
|
+
column: key,
|
|
13
|
+
fromDb: (row) => row
|
|
14
|
+
});
|
|
15
|
+
/** Quotes an identifier, keeping a schema prefix: `app.t` becomes `"app"."t"`. */
|
|
16
|
+
const quoteIdent = (name) => name.split(".").map((part) => `"${part.replaceAll("\"", "\"\"")}"`).join(".");
|
|
17
|
+
/** Selects rows of a live table as Postgres sends them, one `row` column per row. */
|
|
18
|
+
const selectRows = ({ table, column }, byKey = false) => `SELECT to_jsonb(t) AS row FROM ${quoteIdent(table)} t` + (byKey ? ` WHERE t.${quoteIdent(column)} = ANY($1)` : "");
|
|
19
|
+
// src/listener.ts
|
|
20
|
+
const MAX_RETRY_DELAY_MS = 5e3;
|
|
21
|
+
/**
|
|
22
|
+
* One dedicated connection per process for `LISTEN`, shared by every live
|
|
23
|
+
* table and channel.
|
|
24
|
+
*/
|
|
25
|
+
const createListener = ({ connectionString }) => {
|
|
26
|
+
const channels = /* @__PURE__ */ new Map();
|
|
27
|
+
const subscribers = () => [...channels.values()].flatMap((set) => [...set]);
|
|
28
|
+
let client;
|
|
29
|
+
let closed = false;
|
|
30
|
+
const connect = async () => {
|
|
31
|
+
const connection = new Client({ connectionString });
|
|
32
|
+
connection.on("notification", ({ channel, payload = "" }) => {
|
|
33
|
+
for (const subscriber of channels.get(channel) ?? []) subscriber.onNotify(payload);
|
|
34
|
+
});
|
|
35
|
+
connection.on("error", () => lost(connection));
|
|
36
|
+
connection.on("end", () => lost(connection));
|
|
37
|
+
await connection.connect();
|
|
38
|
+
for (const channel of channels.keys()) await connection.query(`LISTEN ${quoteIdent(channel)}`);
|
|
39
|
+
return connection;
|
|
40
|
+
};
|
|
41
|
+
let current;
|
|
42
|
+
const connected = () => {
|
|
43
|
+
client ??= connect().then((connection) => {
|
|
44
|
+
current = connection;
|
|
45
|
+
return connection;
|
|
46
|
+
});
|
|
47
|
+
return client;
|
|
48
|
+
};
|
|
49
|
+
const lost = async (connection) => {
|
|
50
|
+
if (closed || connection !== current) return;
|
|
51
|
+
current = void 0;
|
|
52
|
+
client = void 0;
|
|
53
|
+
for (let delay = 100; !closed; delay = Math.min(delay * 2, MAX_RETRY_DELAY_MS)) try {
|
|
54
|
+
await connected();
|
|
55
|
+
for (const subscriber of subscribers()) subscriber.onReconnect();
|
|
56
|
+
return;
|
|
57
|
+
} catch {
|
|
58
|
+
client = void 0;
|
|
59
|
+
await setTimeout(delay);
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const listen = async (channel, subscriber) => {
|
|
63
|
+
const listeners = channels.get(channel) ?? /* @__PURE__ */ new Set();
|
|
64
|
+
listeners.add(subscriber);
|
|
65
|
+
channels.set(channel, listeners);
|
|
66
|
+
await (await connected()).query(`LISTEN ${quoteIdent(channel)}`);
|
|
67
|
+
return async () => {
|
|
68
|
+
listeners.delete(subscriber);
|
|
69
|
+
if (listeners.size > 0 || closed) return;
|
|
70
|
+
channels.delete(channel);
|
|
71
|
+
await current?.query(`UNLISTEN ${quoteIdent(channel)}`);
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
const close = async () => {
|
|
75
|
+
if (closed) return;
|
|
76
|
+
closed = true;
|
|
77
|
+
channels.clear();
|
|
78
|
+
await (await client?.catch(() => void 0))?.end();
|
|
79
|
+
};
|
|
80
|
+
return {
|
|
81
|
+
listen,
|
|
82
|
+
close
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
// src/payload.ts
|
|
86
|
+
/** Postgres rejects payloads of 8000 bytes or more in its default configuration. */
|
|
87
|
+
const DEFAULT_LIMIT = 8e3;
|
|
88
|
+
const serialize = ({ r, k, d }) => JSON.stringify({
|
|
89
|
+
...r.length > 0 && { r },
|
|
90
|
+
...k.length > 0 && { k },
|
|
91
|
+
...d.length > 0 && { d }
|
|
92
|
+
});
|
|
93
|
+
const isEmpty = ({ r, k, d }) => r.length + k.length + d.length === 0;
|
|
94
|
+
/**
|
|
95
|
+
* Splits a change into notification payloads that each stay under `limit`
|
|
96
|
+
* bytes. A row too big to fit on its own is sent as its key instead.
|
|
97
|
+
*/
|
|
98
|
+
const encodeChanges = ({ rows, deleted }, key, limit = DEFAULT_LIMIT) => {
|
|
99
|
+
const fits = (wire) => Buffer.byteLength(serialize(wire), "utf8") < limit;
|
|
100
|
+
const payloads = [];
|
|
101
|
+
let current = {
|
|
102
|
+
r: [],
|
|
103
|
+
k: [],
|
|
104
|
+
d: []
|
|
105
|
+
};
|
|
106
|
+
const pack = (field, value) => {
|
|
107
|
+
field(current).push(value);
|
|
108
|
+
if (fits(current)) return;
|
|
109
|
+
field(current).pop();
|
|
110
|
+
if (!isEmpty(current)) payloads.push(serialize(current));
|
|
111
|
+
current = {
|
|
112
|
+
r: [],
|
|
113
|
+
k: [],
|
|
114
|
+
d: []
|
|
115
|
+
};
|
|
116
|
+
field(current).push(value);
|
|
117
|
+
};
|
|
118
|
+
for (const row of rows) if (fits({
|
|
119
|
+
r: [row],
|
|
120
|
+
k: [],
|
|
121
|
+
d: []
|
|
122
|
+
})) pack((wire) => wire.r, row);
|
|
123
|
+
else pack((wire) => wire.k, row[key]);
|
|
124
|
+
for (const id of deleted) pack((wire) => wire.d, id);
|
|
125
|
+
if (!isEmpty(current)) payloads.push(serialize(current));
|
|
126
|
+
return payloads;
|
|
127
|
+
};
|
|
128
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
129
|
+
const isOptionalArray = (value) => value === void 0 || Array.isArray(value);
|
|
130
|
+
/**
|
|
131
|
+
* Reads a payload written by `encodeChanges`. The rows'
|
|
132
|
+
* type is declared by the caller through the live table.
|
|
133
|
+
*/
|
|
134
|
+
const decodeChange = (payload) => {
|
|
135
|
+
const wire = JSON.parse(payload);
|
|
136
|
+
if (!isRecord(wire)) throw new Error(`Not a pg-live payload: ${payload}`);
|
|
137
|
+
const { r, k, d } = wire;
|
|
138
|
+
if (!isOptionalArray(r) || !isOptionalArray(k) || !isOptionalArray(d)) throw new Error(`Not a pg-live payload: ${payload}`);
|
|
139
|
+
return {
|
|
140
|
+
rows: r ?? [],
|
|
141
|
+
keys: k ?? [],
|
|
142
|
+
deleted: d ?? []
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
// src/store.ts
|
|
146
|
+
var LiveTable = class {
|
|
147
|
+
#rows;
|
|
148
|
+
#events;
|
|
149
|
+
#close;
|
|
150
|
+
constructor(rows, events, close) {
|
|
151
|
+
this.#rows = rows;
|
|
152
|
+
this.#events = events;
|
|
153
|
+
this.#close = close;
|
|
154
|
+
}
|
|
155
|
+
has(key) {
|
|
156
|
+
return this.#rows.has(key);
|
|
157
|
+
}
|
|
158
|
+
get(key) {
|
|
159
|
+
return this.#rows.get(key);
|
|
160
|
+
}
|
|
161
|
+
on(event, listener) {
|
|
162
|
+
this.#events.on(event, listener);
|
|
163
|
+
return this;
|
|
164
|
+
}
|
|
165
|
+
once(event, listener) {
|
|
166
|
+
this.#events.once(event, listener);
|
|
167
|
+
return this;
|
|
168
|
+
}
|
|
169
|
+
off(event, listener) {
|
|
170
|
+
this.#events.off(event, listener);
|
|
171
|
+
return this;
|
|
172
|
+
}
|
|
173
|
+
close() {
|
|
174
|
+
return this.#close();
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
/**
|
|
178
|
+
* The in-memory rows behind `live()`. `live` is handed to consumers; `upsert`,
|
|
179
|
+
* `remove`, `replaceAll` and `fail` are for pg-live only.
|
|
180
|
+
*/
|
|
181
|
+
const createStore = (key, onClose = () => {}) => {
|
|
182
|
+
const rows = /* @__PURE__ */ new Map();
|
|
183
|
+
const events = new EventEmitter();
|
|
184
|
+
let closed = false;
|
|
185
|
+
const upsert = (row) => {
|
|
186
|
+
if (closed) return;
|
|
187
|
+
const id = row[key];
|
|
188
|
+
const exists = rows.has(id);
|
|
189
|
+
if (exists && isDeepStrictEqual(rows.get(id), row)) return;
|
|
190
|
+
const type = exists ? "update" : "add";
|
|
191
|
+
rows.set(id, row);
|
|
192
|
+
events.emit(type, row);
|
|
193
|
+
events.emit("change", type, row);
|
|
194
|
+
};
|
|
195
|
+
const remove = (id) => {
|
|
196
|
+
if (closed || !rows.delete(id)) return;
|
|
197
|
+
events.emit("delete", id);
|
|
198
|
+
events.emit("change", "delete", id);
|
|
199
|
+
};
|
|
200
|
+
const replaceAll = (next) => {
|
|
201
|
+
if (closed) return;
|
|
202
|
+
const nextIds = new Set(next.map((row) => row[key]));
|
|
203
|
+
for (const id of [...rows.keys()]) if (!nextIds.has(id)) remove(id);
|
|
204
|
+
for (const row of next) upsert(row);
|
|
205
|
+
};
|
|
206
|
+
const fail = (error) => {
|
|
207
|
+
if (closed) return;
|
|
208
|
+
events.emit("error", error);
|
|
209
|
+
};
|
|
210
|
+
let closing;
|
|
211
|
+
return {
|
|
212
|
+
live: new LiveTable(rows, events, () => {
|
|
213
|
+
closing ??= (async () => {
|
|
214
|
+
closed = true;
|
|
215
|
+
events.removeAllListeners();
|
|
216
|
+
await onClose();
|
|
217
|
+
})();
|
|
218
|
+
return closing;
|
|
219
|
+
}),
|
|
220
|
+
upsert,
|
|
221
|
+
remove,
|
|
222
|
+
replaceAll,
|
|
223
|
+
fail
|
|
224
|
+
};
|
|
225
|
+
};
|
|
226
|
+
// src/live.ts
|
|
227
|
+
/**
|
|
228
|
+
* Keeps all rows of `table` in memory and applies every change as it arrives.
|
|
229
|
+
* Resolves when the rows are loaded; errors after that are emitted as `error`.
|
|
230
|
+
*/
|
|
231
|
+
const live = async (table, { pool, listener }) => {
|
|
232
|
+
const read = async (keys) => {
|
|
233
|
+
const { rows } = await pool.query(selectRows(table, keys !== void 0), keys === void 0 ? [] : [keys]);
|
|
234
|
+
return rows.map(({ row }) => table.fromDb(row));
|
|
235
|
+
};
|
|
236
|
+
let unlisten = async () => {};
|
|
237
|
+
const store = createStore(table.key, () => unlisten());
|
|
238
|
+
const report = (error) => {
|
|
239
|
+
setImmediate(() => store.fail(error));
|
|
240
|
+
};
|
|
241
|
+
const hydrate = async () => store.replaceAll(await read());
|
|
242
|
+
const apply = async (payload) => {
|
|
243
|
+
const { rows, keys, deleted } = decodeChange(payload);
|
|
244
|
+
for (const row of rows) store.upsert(table.fromDb(row));
|
|
245
|
+
for (const key of deleted) store.remove(key);
|
|
246
|
+
if (keys.length === 0) return;
|
|
247
|
+
const found = await read(keys);
|
|
248
|
+
for (const row of found) store.upsert(row);
|
|
249
|
+
const existing = new Set(found.map((row) => row[table.key]));
|
|
250
|
+
for (const key of keys) if (!existing.has(key)) store.remove(key);
|
|
251
|
+
};
|
|
252
|
+
let queue = Promise.resolve();
|
|
253
|
+
const enqueue = (task) => {
|
|
254
|
+
queue = queue.then(task).catch(report);
|
|
255
|
+
};
|
|
256
|
+
const loaded = listener.listen(table.channel, {
|
|
257
|
+
onNotify: (payload) => enqueue(() => apply(payload)),
|
|
258
|
+
onReconnect: () => enqueue(hydrate)
|
|
259
|
+
}).then(async (stop) => {
|
|
260
|
+
unlisten = stop;
|
|
261
|
+
await hydrate();
|
|
262
|
+
});
|
|
263
|
+
queue = loaded.catch(() => {});
|
|
264
|
+
await loaded.catch(async (error) => {
|
|
265
|
+
await store.live.close();
|
|
266
|
+
throw error;
|
|
267
|
+
});
|
|
268
|
+
return store.live;
|
|
269
|
+
};
|
|
270
|
+
// src/write.ts
|
|
271
|
+
/**
|
|
272
|
+
* Notifies listeners of the rows with `keys`, inside a transaction you already
|
|
273
|
+
* have open: rows that exist are sent as rows, the others as deleted.
|
|
274
|
+
*/
|
|
275
|
+
const notifyChanges = async (query, table, keys) => {
|
|
276
|
+
if (keys.length === 0) return;
|
|
277
|
+
const rows = (await query(selectRows(table, true), [keys])).map(({ row }) => row).filter(isDbRow);
|
|
278
|
+
const existing = new Set(rows.map((row) => row[table.column]));
|
|
279
|
+
const deleted = keys.filter((key) => !existing.has(key));
|
|
280
|
+
for (const payload of encodeChanges({
|
|
281
|
+
rows,
|
|
282
|
+
deleted
|
|
283
|
+
}, table.column)) await query("SELECT pg_notify($1, $2)", [table.channel, payload]);
|
|
284
|
+
};
|
|
285
|
+
/**
|
|
286
|
+
* Runs `write` in a transaction and notifies listeners of the keys it returns.
|
|
287
|
+
* The notifications are delivered only if the transaction commits.
|
|
288
|
+
*/
|
|
289
|
+
const writeAndNotify = async (pool, table, write) => {
|
|
290
|
+
const client = await pool.connect();
|
|
291
|
+
const query = async (text, params) => (await client.query(text, params)).rows;
|
|
292
|
+
const ignoreConnectionError = () => {};
|
|
293
|
+
client.on("error", ignoreConnectionError);
|
|
294
|
+
let broken = false;
|
|
295
|
+
try {
|
|
296
|
+
await client.query("BEGIN");
|
|
297
|
+
await notifyChanges(query, table, await write(client));
|
|
298
|
+
await client.query("COMMIT");
|
|
299
|
+
} catch (error) {
|
|
300
|
+
await client.query("ROLLBACK").catch(() => {
|
|
301
|
+
broken = true;
|
|
302
|
+
});
|
|
303
|
+
throw error;
|
|
304
|
+
} finally {
|
|
305
|
+
client.off("error", ignoreConnectionError);
|
|
306
|
+
client.release(broken);
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
export { createListener, defineTable, live, notifyChanges, writeAndNotify };
|
|
310
|
+
|
|
311
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/table.ts","../src/listener.ts","../src/payload.ts","../src/store.ts","../src/live.ts","../src/write.ts"],"sourcesContent":["/** A table row as Postgres sends it: `to_jsonb(row)`, keyed by column name. */\nexport type DbRow = Record<string, unknown>\n\nexport const isDbRow = (value: unknown): value is DbRow =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** A table kept live: shared by the processes that write and those that read. */\nexport type LiveTable<T, K extends keyof T> = {\n table: string\n channel: string\n /** Property of a row that identifies it. */\n key: K\n /** Column in the table that holds the key. */\n column: string\n /** Turns a row as Postgres sends it into a row of the live table. */\n fromDb: (row: DbRow) => T\n}\n\nexport type TableOptions<T> = {\n /** Table to keep live. May be schema-qualified, e.g. `app.user_preferences`. */\n table: string\n /** Column that identifies a row, usually the primary key. */\n key: keyof T & string\n /** Channel the changes are sent on. Default: `<table>_changed`. */\n channel?: string\n}\n\n/** Defines a live table. Declare the row type with a type parameter. */\nexport const defineTable = <T = DbRow>({\n table,\n key,\n channel = `${table}_changed`,\n}: TableOptions<T>): LiveTable<T, keyof T & string> => ({\n table,\n channel,\n key,\n column: key,\n // biome-ignore lint/plugin/no-type-assertion: the caller declares the row type through the type parameter\n fromDb: (row) => row as T,\n})\n\n/** Quotes an identifier, keeping a schema prefix: `app.t` becomes `\"app\".\"t\"`. */\nexport const quoteIdent = (name: string) =>\n name\n .split('.')\n .map((part) => `\"${part.replaceAll('\"', '\"\"')}\"`)\n .join('.')\n\n/** Selects rows of a live table as Postgres sends them, one `row` column per row. */\nexport const selectRows = <T, K extends keyof T>(\n { table, column }: LiveTable<T, K>,\n byKey = false\n) =>\n `SELECT to_jsonb(t) AS row FROM ${quoteIdent(table)} t` +\n (byKey ? ` WHERE t.${quoteIdent(column)} = ANY($1)` : '')\n","import { setTimeout } from 'node:timers/promises'\nimport { Client } from 'pg'\nimport { quoteIdent } from './table'\n\nexport type Subscriber = {\n onNotify: (payload: string) => void\n /** Called after a lost connection is back and listening again. */\n onReconnect: () => void\n}\n\nexport type Listener = {\n /** Listens on `channel` until the returned function is called. */\n listen: (\n channel: string,\n subscriber: Subscriber\n ) => Promise<() => Promise<void>>\n /** Stops listening and releases the connection. */\n close: () => Promise<void>\n}\n\nconst MAX_RETRY_DELAY_MS = 5000\n\n/**\n * One dedicated connection per process for `LISTEN`, shared by every live\n * table and channel.\n */\nexport const createListener = ({\n connectionString,\n}: {\n connectionString: string\n}): Listener => {\n const channels = new Map<string, Set<Subscriber>>()\n const subscribers = () => [...channels.values()].flatMap((set) => [...set])\n let client: Promise<Client> | undefined\n let closed = false\n\n const connect = async (): Promise<Client> => {\n const connection = new Client({ connectionString })\n connection.on('notification', ({ channel, payload = '' }) => {\n for (const subscriber of channels.get(channel) ?? []) {\n subscriber.onNotify(payload)\n }\n })\n // A lost connection is recovered by reconnecting, so it is not reported\n connection.on('error', () => lost(connection))\n connection.on('end', () => lost(connection))\n await connection.connect()\n for (const channel of channels.keys()) {\n await connection.query(`LISTEN ${quoteIdent(channel)}`)\n }\n return connection\n }\n\n let current: Client | undefined\n const connected = () => {\n client ??= connect().then((connection) => {\n current = connection\n return connection\n })\n return client\n }\n\n const lost = async (connection: Client) => {\n if (closed || connection !== current) return\n current = undefined\n client = undefined\n\n for (\n let delay = 100;\n !closed;\n delay = Math.min(delay * 2, MAX_RETRY_DELAY_MS)\n ) {\n try {\n await connected()\n for (const subscriber of subscribers()) subscriber.onReconnect()\n return\n } catch {\n client = undefined\n await setTimeout(delay)\n }\n }\n }\n\n const listen = async (channel: string, subscriber: Subscriber) => {\n const listeners = channels.get(channel) ?? new Set()\n listeners.add(subscriber)\n channels.set(channel, listeners)\n await (await connected()).query(`LISTEN ${quoteIdent(channel)}`)\n\n return async () => {\n listeners.delete(subscriber)\n if (listeners.size > 0 || closed) return\n channels.delete(channel)\n await current?.query(`UNLISTEN ${quoteIdent(channel)}`)\n }\n }\n\n const close = async () => {\n if (closed) return\n closed = true\n channels.clear()\n await (await client?.catch(() => undefined))?.end()\n }\n\n return { listen, close }\n}\n","/** Postgres rejects payloads of 8000 bytes or more in its default configuration. */\nconst DEFAULT_LIMIT = 8000\n\n/** A change as listeners see it. `keys` are rows too big to send; read them by key. */\nexport type Change<Row, Key> = {\n rows: Row[]\n keys: Key[]\n deleted: Key[]\n}\n\n// The wire format: short field names, empty fields left out\ntype Wire<T, K extends keyof T> = { r: T[]; k: T[K][]; d: T[K][] }\n\nconst serialize = <T, K extends keyof T>({ r, k, d }: Wire<T, K>) =>\n JSON.stringify({\n ...(r.length > 0 && { r }),\n ...(k.length > 0 && { k }),\n ...(d.length > 0 && { d }),\n })\n\nconst isEmpty = <T, K extends keyof T>({ r, k, d }: Wire<T, K>) =>\n r.length + k.length + d.length === 0\n\n/**\n * Splits a change into notification payloads that each stay under `limit`\n * bytes. A row too big to fit on its own is sent as its key instead.\n */\nexport const encodeChanges = <T, K extends keyof T>(\n { rows, deleted }: { rows: T[]; deleted: T[K][] },\n key: K,\n limit = DEFAULT_LIMIT\n): string[] => {\n const fits = (wire: Wire<T, K>) =>\n Buffer.byteLength(serialize(wire), 'utf8') < limit\n\n const payloads: string[] = []\n let current: Wire<T, K> = { r: [], k: [], d: [] }\n\n const pack = <V>(field: (wire: Wire<T, K>) => V[], value: V) => {\n field(current).push(value)\n if (fits(current)) return\n field(current).pop()\n if (!isEmpty(current)) payloads.push(serialize(current))\n current = { r: [], k: [], d: [] }\n field(current).push(value)\n }\n\n for (const row of rows) {\n if (fits({ r: [row], k: [], d: [] })) pack((wire) => wire.r, row)\n else pack((wire) => wire.k, row[key])\n }\n for (const id of deleted) pack((wire) => wire.d, id)\n\n if (!isEmpty(current)) payloads.push(serialize(current))\n return payloads\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst isOptionalArray = <V>(value: unknown): value is V[] | undefined =>\n value === undefined || Array.isArray(value)\n\n/**\n * Reads a payload written by `encodeChanges`. The rows'\n * type is declared by the caller through the live table.\n */\nexport const decodeChange = <Row, Key>(payload: string): Change<Row, Key> => {\n const wire: unknown = JSON.parse(payload)\n if (!isRecord(wire)) throw new Error(`Not a pg-live payload: ${payload}`)\n\n const { r, k, d } = wire\n if (\n !isOptionalArray<Row>(r) ||\n !isOptionalArray<Key>(k) ||\n !isOptionalArray<Key>(d)\n ) {\n throw new Error(`Not a pg-live payload: ${payload}`)\n }\n\n return { rows: r ?? [], keys: k ?? [], deleted: d ?? [] }\n}\n","import { EventEmitter } from 'node:events'\nimport { isDeepStrictEqual } from 'node:util'\nimport type { ChangeListener, Events, Live } from './types'\n\ntype AnyListener<T, K extends keyof T> =\n | ((payload: Events<T, K>[keyof Events<T, K>]) => void)\n | ChangeListener<T, K>\n | ((error: unknown) => void)\n\ntype EventName<T, K extends keyof T> = keyof Events<T, K> | 'change' | 'error'\n\nclass LiveTable<T, K extends keyof T> {\n readonly #rows: ReadonlyMap<T[K], T>\n readonly #events: EventEmitter\n readonly #close: () => Promise<void>\n\n constructor(\n rows: ReadonlyMap<T[K], T>,\n events: EventEmitter,\n close: () => Promise<void>\n ) {\n this.#rows = rows\n this.#events = events\n this.#close = close\n }\n\n has(key: T[K]): boolean {\n return this.#rows.has(key)\n }\n\n get(key: T[K]): T | undefined {\n return this.#rows.get(key)\n }\n\n on<E extends keyof Events<T, K>>(\n event: E,\n listener: (payload: Events<T, K>[E]) => void\n ): this\n on(event: 'change', listener: ChangeListener<T, K>): this\n on(event: 'error', listener: (error: unknown) => void): this\n on(event: EventName<T, K>, listener: AnyListener<T, K>): this {\n this.#events.on(event, listener)\n return this\n }\n\n once<E extends keyof Events<T, K>>(\n event: E,\n listener: (payload: Events<T, K>[E]) => void\n ): this\n once(event: 'change', listener: ChangeListener<T, K>): this\n once(event: 'error', listener: (error: unknown) => void): this\n once(event: EventName<T, K>, listener: AnyListener<T, K>): this {\n this.#events.once(event, listener)\n return this\n }\n\n off<E extends keyof Events<T, K>>(\n event: E,\n listener: (payload: Events<T, K>[E]) => void\n ): this\n off(event: 'change', listener: ChangeListener<T, K>): this\n off(event: 'error', listener: (error: unknown) => void): this\n off(event: EventName<T, K>, listener: AnyListener<T, K>): this {\n this.#events.off(event, listener)\n return this\n }\n\n close(): Promise<void> {\n return this.#close()\n }\n}\n\n/**\n * The in-memory rows behind `live()`. `live` is handed to consumers; `upsert`,\n * `remove`, `replaceAll` and `fail` are for pg-live only.\n */\nexport const createStore = <T, K extends keyof T>(\n key: K,\n onClose: () => void | Promise<void> = () => {}\n) => {\n const rows = new Map<T[K], T>()\n const events = new EventEmitter()\n let closed = false\n\n const upsert = (row: T) => {\n if (closed) return\n const id = row[key]\n const exists = rows.has(id)\n if (exists && isDeepStrictEqual(rows.get(id), row)) return\n const type = exists ? 'update' : 'add'\n rows.set(id, row)\n events.emit(type, row)\n events.emit('change', type, row)\n }\n\n const remove = (id: T[K]) => {\n if (closed || !rows.delete(id)) return\n events.emit('delete', id)\n events.emit('change', 'delete', id)\n }\n\n // Applies a full read of the table, emitting only what differs\n const replaceAll = (next: T[]) => {\n if (closed) return\n const nextIds = new Set(next.map((row) => row[key]))\n for (const id of [...rows.keys()]) {\n if (!nextIds.has(id)) remove(id)\n }\n for (const row of next) upsert(row)\n }\n\n // Reports an error like EventEmitter: to `error` listeners, or thrown if there are none\n const fail = (error: unknown) => {\n if (closed) return\n events.emit('error', error)\n }\n\n let closing: Promise<void> | undefined\n const live: Live<T, K> = new LiveTable<T, K>(rows, events, () => {\n closing ??= (async () => {\n closed = true\n events.removeAllListeners()\n await onClose()\n })()\n return closing\n })\n\n return { live, upsert, remove, replaceAll, fail }\n}\n","import type { Pool } from 'pg'\nimport type { Listener } from './listener'\nimport { decodeChange } from './payload'\nimport { createStore } from './store'\nimport { type DbRow, type LiveTable, selectRows } from './table'\nimport type { Live } from './types'\n\nexport type LiveOptions = {\n /** Pool used for hydration and for reading rows by key. */\n pool: Pool\n /** Shared listener from `createListener()`. */\n listener: Listener\n}\n\n/**\n * Keeps all rows of `table` in memory and applies every change as it arrives.\n * Resolves when the rows are loaded; errors after that are emitted as `error`.\n */\nexport const live = async <T, K extends keyof T>(\n table: LiveTable<T, K>,\n { pool, listener }: LiveOptions\n): Promise<Live<T, K>> => {\n const read = async (keys?: T[K][]) => {\n const { rows } = await pool.query<{ row: DbRow }>(\n selectRows(table, keys !== undefined),\n keys === undefined ? [] : [keys]\n )\n return rows.map(({ row }) => table.fromDb(row))\n }\n\n let unlisten = async () => {}\n const store = createStore<T, K>(table.key, () => unlisten())\n\n // On a later tick, so a thrown error (no `error` listener) cannot stop the\n // queue below or the listener's reconnects\n const report = (error: unknown) => {\n setImmediate(() => store.fail(error))\n }\n\n const hydrate = async () => store.replaceAll(await read())\n\n const apply = async (payload: string) => {\n const { rows, keys, deleted } = decodeChange<DbRow, T[K]>(payload)\n for (const row of rows) store.upsert(table.fromDb(row))\n for (const key of deleted) store.remove(key)\n if (keys.length === 0) return\n\n const found = await read(keys)\n for (const row of found) store.upsert(row)\n const existing = new Set(found.map((row) => row[table.key]))\n for (const key of keys) if (!existing.has(key)) store.remove(key)\n }\n\n // Changes are applied one at a time, in the order they arrived\n let queue: Promise<void> = Promise.resolve()\n const enqueue = (task: () => Promise<void>) => {\n queue = queue.then(task).catch(report)\n }\n\n // Listen before reading, so no change slips in between\n const listening = listener.listen(table.channel, {\n onNotify: (payload) => enqueue(() => apply(payload)),\n onReconnect: () => enqueue(hydrate),\n })\n const loaded = listening.then(async (stop) => {\n unlisten = stop\n await hydrate()\n })\n queue = loaded.catch(() => {})\n\n await loaded.catch(async (error) => {\n // Stop listening for a table that never loaded, then report why\n await store.live.close()\n throw error\n })\n return store.live\n}\n","import type { Pool, PoolClient } from 'pg'\nimport { encodeChanges } from './payload'\nimport { type DbRow, isDbRow, type LiveTable, selectRows } from './table'\n\n/** Runs SQL with `$1`, `$2`... parameters in an open transaction and returns its rows. */\nexport type Query = (\n text: string,\n params: unknown[]\n) => Promise<Record<string, unknown>[]>\n\n/**\n * Notifies listeners of the rows with `keys`, inside a transaction you already\n * have open: rows that exist are sent as rows, the others as deleted.\n */\nexport const notifyChanges = async <T, K extends keyof T>(\n query: Query,\n table: LiveTable<T, K>,\n keys: T[K][]\n) => {\n if (keys.length === 0) return\n\n const found = await query(selectRows(table, true), [keys])\n const rows = found.map(({ row }) => row).filter(isDbRow)\n const existing = new Set(rows.map((row) => row[table.column]))\n const deleted = keys.filter((key) => !existing.has(key))\n\n for (const payload of encodeChanges<DbRow, string>(\n { rows, deleted },\n table.column\n )) {\n await query('SELECT pg_notify($1, $2)', [table.channel, payload])\n }\n}\n\n/**\n * Runs `write` in a transaction and notifies listeners of the keys it returns.\n * The notifications are delivered only if the transaction commits.\n */\nexport const writeAndNotify = async <T, K extends keyof T>(\n pool: Pool,\n table: LiveTable<T, K>,\n write: (tx: PoolClient) => Promise<T[K][]>\n) => {\n const client = await pool.connect()\n const query: Query = async (text, params) =>\n (await client.query(text, params)).rows\n\n // A lost connection also surfaces as an error from the query in flight;\n // without a listener, pg's client error event would end the process\n const ignoreConnectionError = () => {}\n client.on('error', ignoreConnectionError)\n let broken = false\n\n try {\n await client.query('BEGIN')\n await notifyChanges(query, table, await write(client))\n await client.query('COMMIT')\n } catch (error) {\n await client.query('ROLLBACK').catch(() => {\n broken = true\n })\n throw error\n } finally {\n client.off('error', ignoreConnectionError)\n // A broken client is destroyed rather than returned to the pool\n client.release(broken)\n }\n}\n"],"mappings":";;;;;AAGA,MAAa,WAAW,UACtB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;AAwBrE,MAAa,eAA0B,EACrC,OACA,KACA,UAAU,GAAG,MAAM,iBACmC;CACtD;CACA;CACA;CACA,QAAQ;CAER,SAAS,QAAQ;AACnB;;AAGA,MAAa,cAAc,SACzB,KACG,MAAM,GAAG,CAAC,CACV,KAAK,SAAS,IAAI,KAAK,WAAW,MAAK,MAAI,EAAE,EAAE,CAAC,CAChD,KAAK,GAAG;;AAGb,MAAa,cACX,EAAE,OAAO,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;EAC1B,MAAM,cAAc,OAAO,OAAO,MAAM,MAAM,MAAM,CAAC;EACrD,MAAM,OAAO,MAAM,QAAQ;CAC7B,SAAS,OAAO;EACd,MAAM,OAAO,MAAM,UAAU,CAAC,CAAC,YAAY;GACzC,SAAS;EACX,CAAC;EACD,MAAM;CACR,UAAU;EACR,OAAO,IAAI,SAAS,qBAAqB;EAEzC,OAAO,QAAQ,MAAM;CACvB;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sebspark/pg-live",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.mjs",
|
|
7
|
+
"types": "dist/index.d.mts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"@sebspark/source": "./src/index.ts",
|
|
11
|
+
"types": "./dist/index.d.mts",
|
|
12
|
+
"import": "./dist/index.mjs"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "spark-build src/index.ts",
|
|
20
|
+
"dev": "tsc --watch --noEmit",
|
|
21
|
+
"lint": "biome check --write .",
|
|
22
|
+
"test": "vitest run --passWithNoTests --coverage --fsModuleCachePath node_modules/.vitest-cache",
|
|
23
|
+
"test:e2e": "vitest --config vitest.config.e2e.ts --run --fsModuleCachePath node_modules/.vitest-cache",
|
|
24
|
+
"typecheck": "tsc --noEmit -p . && vitest --typecheck.only --passWithNoTests --run --fsModuleCachePath node_modules/.vitest-cache"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@biomejs/biome": "2.6.8",
|
|
28
|
+
"@sebspark/expect-eventually": "0.1.17",
|
|
29
|
+
"@sebspark/tsconfig": "3.0.31",
|
|
30
|
+
"@testcontainers/postgresql": "12.2.2",
|
|
31
|
+
"@types/pg": "8.23.1",
|
|
32
|
+
"pg": "8.23.1",
|
|
33
|
+
"typescript": "7.0.2",
|
|
34
|
+
"vite": "8.3.8",
|
|
35
|
+
"vitest": "5.1.1"
|
|
36
|
+
},
|
|
37
|
+
"repository": {
|
|
38
|
+
"type": "git",
|
|
39
|
+
"url": "https://github.com/seb-oss/Spark-packages.git"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"pg": ">=8"
|
|
43
|
+
}
|
|
44
|
+
}
|