@supapower/worker 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 2026 Aboviq AB
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/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ Supapower Worker
2
+ Copyright 2026 Aboviq AB
3
+
4
+ This product includes software developed at Aboviq AB (https://www.aboviq.com/).
5
+
6
+ This product includes software developed by ElectricSQL
7
+ (https://github.com/electric-sql/pglite), licensed under the Apache License,
8
+ Version 2.0. Portions of src/shared-worker.ts are derived from
9
+ packages/pglite/src/worker/index.ts and have been modified.
package/README.md ADDED
@@ -0,0 +1,112 @@
1
+ # `@supapower/worker`
2
+
3
+ A more stable drop-in replacement for PGlite's built-in
4
+ [multi-tab worker](https://pglite.dev/docs/multi-tab-worker): one `SharedWorker` hosts the
5
+ [PGlite](https://pglite.dev/) database for every tab, so the database is never owned by a particular
6
+ tab and never has to be handed over when one closes, with PGlite's own dedicated-worker setup as an
7
+ automatic fallback for browsers without `SharedWorker` (or where it fails to start). Works with plain
8
+ PGlite - [Supapower](https://github.com/aboviq/supapower/tree/main/packages/supapower#readme) is not
9
+ required.
10
+
11
+ > **Status:** Below 1.0.0. The public API may still change.
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install @supapower/worker @electric-sql/pglite
17
+ ```
18
+
19
+ `@electric-sql/pglite` is a peer dependency - install it alongside this package. The peer range is
20
+ `>=0.5.8 <0.6.0`: this package depends on PGlite's _internal_ worker handshake, which is only
21
+ guaranteed to stay compatible within a minor version.
22
+
23
+ (of course, you can use the package manager of your choice, e.g. `bun` or `pnpm`)
24
+
25
+ ## Usage
26
+
27
+ ### 1. Write the worker script
28
+
29
+ ```ts
30
+ // ./pglite-worker.ts
31
+ import { worker } from '@supapower/worker/worker';
32
+ import { PGlite } from '@electric-sql/pglite';
33
+
34
+ worker({
35
+ async init(options) {
36
+ return await PGlite.create(options);
37
+ },
38
+ });
39
+ ```
40
+
41
+ `worker()` detects at runtime whether it is running as a `SharedWorker` or a dedicated `Worker` and
42
+ speaks the right protocol for each - the same script works for both, so there is only ever one
43
+ worker file to write.
44
+
45
+ ### 2. Connect from the tab
46
+
47
+ ```ts
48
+ // ./pglite.ts
49
+ import { createPGliteWorker } from '@supapower/worker';
50
+
51
+ export const pg = await createPGliteWorker(
52
+ {
53
+ shared: () =>
54
+ new SharedWorker(new URL('./pglite-worker.ts', import.meta.url), { type: 'module' }),
55
+ fallback: () => new Worker(new URL('./pglite-worker.ts', import.meta.url), { type: 'module' }),
56
+ },
57
+ { id: 'my-app' },
58
+ );
59
+
60
+ console.log('Transport:', pg.transport); // 'shared-worker' or 'worker'
61
+ ```
62
+
63
+ `id` is **required**. It is the only value that makes both transports agree on one election lock and
64
+ one broadcast channel - `PGliteWorker`'s own default id is derived from _its own_ `import.meta.url`,
65
+ which differs between the shared and the fallback worker scripts and would otherwise let the two open
66
+ the same `dataDir` as if they were unrelated databases. Pick one stable id per database your app
67
+ opens.
68
+
69
+ The returned `pg` **is** a [`PGliteWorker`](https://pglite.dev/docs/multi-tab-worker) - every method,
70
+ extension and the `live` query API work exactly as documented there, and any code written against
71
+ PGlite's own multi-tab worker keeps working unchanged. `pg.transport` reports which side actually
72
+ won: `'shared-worker'` when the `SharedWorker` started within `sharedWorkerTimeout` (10 seconds by
73
+ default), `'worker'` otherwise.
74
+
75
+ ### 3. (Optional) Sync with Supapower
76
+
77
+ Nothing above needs [Supapower](https://github.com/aboviq/supapower/tree/main/packages/supapower#readme) -
78
+ `pg` is a plain `PGliteWorker` and works with any PGlite extension. Apps that do use it wire it up the
79
+ same way as with PGlite's own worker:
80
+
81
+ ```ts
82
+ import { extensions } from '@supapower/vue'; // or `@supapower/react`, or plain `supapower`
83
+
84
+ export const pg = await createPGliteWorker(
85
+ { shared: () => new SharedWorker(/* … */), fallback: () => new Worker(/* … */) },
86
+ { id: 'my-app', extensions },
87
+ );
88
+
89
+ const sync = await pg.supapower.sync({ supabase, tables: ['todos'] });
90
+ ```
91
+
92
+ `extensions` goes on this, the client side, call - not inside the worker's `init()` - the same rule
93
+ as `PGliteWorker.create` itself, since `createPGliteWorker` strips `extensions` before forwarding the
94
+ rest of the options to the worker.
95
+
96
+ ## What differs from PGlite's own multi-tab worker
97
+
98
+ - **One worker instance for every tab.** PGlite's dedicated-worker transport elects one _tab_ to host
99
+ the database and hands it over when that tab closes. A `SharedWorker` is not owned by any tab, so
100
+ there is nothing to hand over - it simply outlives every tab until the last one disconnects.
101
+ - **`pg.isLeader` is always `false` on the shared transport.** There is only ever one `SharedWorker`
102
+ instance per database, so there is nothing to elect a leader among. Code that reads `isLeader` to
103
+ decide who does work needs a different signal on this transport - Supapower's own outgoing-sync
104
+ leadership already handles this by electing on tab visibility instead, see
105
+ [Multi-tab behavior](https://github.com/aboviq/supapower/tree/main/packages/supapower#multi-tab-behavior)
106
+ in its README.
107
+ - **Safari ignores the `SharedWorker` constructor's `name` option.** Separate two databases by using
108
+ a different worker script URL and a different `id`, not by `name`.
109
+
110
+ ## License
111
+
112
+ Apache-2.0
@@ -0,0 +1,21 @@
1
+ /** Which side actually ended up hosting the database. */
2
+ export type WorkerTransport = 'shared-worker' | 'worker';
3
+ export interface WorkerFactories {
4
+ /** Tried first. Build the SharedWorker at the call site so bundlers can see it. */
5
+ shared: () => SharedWorker;
6
+ /** Used when SharedWorker is missing or fails to start. */
7
+ fallback: () => Worker;
8
+ }
9
+ export interface WorkerConnection<T> {
10
+ transport: WorkerTransport;
11
+ db: T;
12
+ }
13
+ /**
14
+ * Connects through a `SharedWorker`, falling back to a dedicated `Worker`
15
+ * when the shared transport is unavailable or fails to start in time.
16
+ *
17
+ * @param timeout Milliseconds allowed for the SharedWorker's script load and
18
+ * handshake, not for the database itself to finish booting.
19
+ */
20
+ export declare function connectWithFallback<T>(workers: WorkerFactories, connect: (worker: Worker) => Promise<T>, timeout: number): Promise<WorkerConnection<T>>;
21
+ //# sourceMappingURL=connect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAAA,yDAAyD;AACzD,MAAM,MAAM,eAAe,GAAG,eAAe,GAAG,QAAQ,CAAC;AAEzD,MAAM,WAAW,eAAe;IAC9B,mFAAmF;IACnF,MAAM,EAAE,MAAM,YAAY,CAAC;IAC3B,2DAA2D;IAC3D,QAAQ,EAAE,MAAM,MAAM,CAAC;CACxB;AAED,MAAM,WAAW,gBAAgB,CAAC,CAAC;IACjC,SAAS,EAAE,eAAe,CAAC;IAC3B,EAAE,EAAE,CAAC,CAAC;CACP;AA+CD;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CAAC,CAAC,EACzC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,EACvC,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CA8B9B"}
@@ -0,0 +1,67 @@
1
+ /** A `Worker`-shaped facade over one `SharedWorker` client port. */
2
+ function portAsWorker(port) {
3
+ let started = false;
4
+ const ensureStarted = () => {
5
+ if (!started) {
6
+ started = true;
7
+ // Deferred to the first listener, so no message dispatched by the
8
+ // SharedWorker before `PGliteWorker` is listening is ever dropped.
9
+ port.start();
10
+ }
11
+ };
12
+ return {
13
+ addEventListener(...args) {
14
+ ensureStarted();
15
+ port.addEventListener(...args);
16
+ },
17
+ removeEventListener(...args) {
18
+ port.removeEventListener(...args);
19
+ },
20
+ postMessage(...args) {
21
+ port.postMessage(...args);
22
+ },
23
+ terminate() {
24
+ // Closes only this tab's port - the other tabs, and the shared
25
+ // database, are unaffected.
26
+ port.close();
27
+ },
28
+ };
29
+ }
30
+ function rejectAfter(ms) {
31
+ let timer;
32
+ const promise = new Promise((_resolve, reject) => {
33
+ timer = setTimeout(() => reject(new Error(`Timed out waiting for the SharedWorker after ${ms}ms`)), ms);
34
+ });
35
+ return { promise, cancel: () => clearTimeout(timer) };
36
+ }
37
+ /**
38
+ * Connects through a `SharedWorker`, falling back to a dedicated `Worker`
39
+ * when the shared transport is unavailable or fails to start in time.
40
+ *
41
+ * @param timeout Milliseconds allowed for the SharedWorker's script load and
42
+ * handshake, not for the database itself to finish booting.
43
+ */
44
+ export async function connectWithFallback(workers, connect, timeout) {
45
+ let sw;
46
+ try {
47
+ // `workers.shared()` throws synchronously when `SharedWorker` is
48
+ // undefined, so there is no separate feature test to do first.
49
+ sw = workers.shared();
50
+ const failed = new Promise((_resolve, reject) => {
51
+ sw?.addEventListener('error', () => reject(new Error('SharedWorker failed to load')), {
52
+ once: true,
53
+ });
54
+ });
55
+ const shim = portAsWorker(sw.port);
56
+ const timedOut = rejectAfter(timeout);
57
+ const db = await Promise.race([connect(shim), failed, timedOut.promise]).finally(() => timedOut.cancel());
58
+ return { transport: 'shared-worker', db };
59
+ }
60
+ catch {
61
+ // Falling back is the point of this function - never rethrow here.
62
+ sw?.port.close();
63
+ }
64
+ const worker = workers.fallback();
65
+ return { transport: 'worker', db: await connect(worker) };
66
+ }
67
+ //# sourceMappingURL=connect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect.js","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAeA,oEAAoE;AACpE,SAAS,YAAY,CAAC,IAAiB;IACrC,IAAI,OAAO,GAAG,KAAK,CAAC;IAEpB,MAAM,aAAa,GAAG,GAAG,EAAE;QACzB,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,IAAI,CAAC;YACf,kEAAkE;YAClE,mEAAmE;YACnE,IAAI,CAAC,KAAK,EAAE,CAAC;QACf,CAAC;IACH,CAAC,CAAC;IAEF,OAAO;QACL,gBAAgB,CAAC,GAAG,IAAiD;YACnE,aAAa,EAAE,CAAC;YAChB,IAAI,CAAC,gBAAgB,CAAC,GAAG,IAA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,IAAI,GAAG,YAAY,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC;QACnC,MAAM,QAAQ,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC;QAEtC,MAAM,EAAE,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,CACpF,QAAQ,CAAC,MAAM,EAAE,CAClB,CAAC;QAEF,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,EAAE,CAAC;IAC5C,CAAC;IAAC,MAAM,CAAC;QACP,mEAAmE;QACnE,EAAE,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;IAED,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;IAElC,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;AAC5D,CAAC"}
@@ -0,0 +1,32 @@
1
+ import type { Extensions, PGliteInterfaceExtensions } from '@electric-sql/pglite';
2
+ import type { PGliteWorker, PGliteWorkerOptions } from '@electric-sql/pglite/worker';
3
+ import { type WorkerFactories, type WorkerTransport } from './connect.js';
4
+ export type { WorkerFactories, WorkerTransport } from './connect.js';
5
+ export interface SupapowerWorkerOptions<E extends Extensions = Extensions> extends PGliteWorkerOptions<E> {
6
+ /** Required: groups every tab of this database across both transports. */
7
+ id: string;
8
+ /**
9
+ * Milliseconds to wait for the SharedWorker handshake before falling back
10
+ * to PGlite's dedicated worker.
11
+ *
12
+ * @default 10000
13
+ */
14
+ sharedWorkerTimeout?: number;
15
+ }
16
+ /** What {@link createPGliteWorker} resolves to. */
17
+ export type SupapowerWorker<O extends SupapowerWorkerOptions> = PGliteWorker & PGliteInterfaceExtensions<O['extensions']> & {
18
+ readonly transport: WorkerTransport;
19
+ };
20
+ /**
21
+ * Opens a multi-tab PGlite database over a `SharedWorker`, falling back to
22
+ * PGlite's own dedicated-worker transport when the browser has no
23
+ * `SharedWorker`, or the shared one fails to start in time.
24
+ *
25
+ * `id` is required: it is the only value that makes both transports agree on
26
+ * one election lock and one broadcast channel. PGlite's own default id is
27
+ * derived from *its own* `import.meta.url`, which differs between the shared
28
+ * and the fallback worker scripts and would let the two open the same
29
+ * `dataDir` as if they were unrelated databases.
30
+ */
31
+ export declare function createPGliteWorker<O extends SupapowerWorkerOptions>(workers: WorkerFactories, options: O): Promise<SupapowerWorker<O>>;
32
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AAClF,OAAO,KAAK,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAErF,OAAO,EAAuB,KAAK,eAAe,EAAE,KAAK,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/F,YAAY,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAErE,MAAM,WAAW,sBAAsB,CACrC,CAAC,SAAS,UAAU,GAAG,UAAU,CACjC,SAAQ,mBAAmB,CAAC,CAAC,CAAC;IAC9B,0EAA0E;IAC1E,EAAE,EAAE,MAAM,CAAC;IACX;;;;;OAKG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,mDAAmD;AACnD,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,sBAAsB,IAAI,YAAY,GACxE,yBAAyB,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,GAAG;IAAE,QAAQ,CAAC,SAAS,EAAE,eAAe,CAAA;CAAE,CAAC;AAEzF;;;;;;;;;;GAUG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,SAAS,sBAAsB,EACvE,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,CAAC,GACT,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAiB7B"}
package/dist/index.js ADDED
@@ -0,0 +1,24 @@
1
+ import { connectWithFallback } from './connect.js';
2
+ /**
3
+ * Opens a multi-tab PGlite database over a `SharedWorker`, falling back to
4
+ * PGlite's own dedicated-worker transport when the browser has no
5
+ * `SharedWorker`, or the shared one fails to start in time.
6
+ *
7
+ * `id` is required: it is the only value that makes both transports agree on
8
+ * one election lock and one broadcast channel. PGlite's own default id is
9
+ * derived from *its own* `import.meta.url`, which differs between the shared
10
+ * and the fallback worker scripts and would let the two open the same
11
+ * `dataDir` as if they were unrelated databases.
12
+ */
13
+ export async function createPGliteWorker(workers, options) {
14
+ // Dynamic: loading `@electric-sql/pglite/worker`'s runtime code is deferred
15
+ // to the call, not module scope, so this module stays importable under
16
+ // Node/Bun (SSR, `bun test`) without pulling in browser worker plumbing.
17
+ // Hoisted ahead of `connectWithFallback` so the `connect` callback below,
18
+ // which is invoked synchronously inside it, already has `PGliteWorker`.
19
+ const { PGliteWorker: PGliteWorkerClass } = await import('@electric-sql/pglite/worker');
20
+ const { transport, db } = await connectWithFallback(workers, (worker) => PGliteWorkerClass.create(worker, options), options.sharedWorkerTimeout ?? 10_000);
21
+ Object.defineProperty(db, 'transport', { value: transport, enumerable: true });
22
+ return db;
23
+ }
24
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mBAAmB,EAA8C,MAAM,cAAc,CAAC;AAsB/F;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,OAAwB,EACxB,OAAU;IAEV,4EAA4E;IAC5E,uEAAuE;IACvE,yEAAyE;IACzE,0EAA0E;IAC1E,wEAAwE;IACxE,MAAM,EAAE,YAAY,EAAE,iBAAiB,EAAE,GAAG,MAAM,MAAM,CAAC,6BAA6B,CAAC,CAAC;IAExF,MAAM,EAAE,SAAS,EAAE,EAAE,EAAE,GAAG,MAAM,mBAAmB,CACjD,OAAO,EACP,CAAC,MAAM,EAAE,EAAE,CAAC,iBAAiB,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACrD,OAAO,CAAC,mBAAmB,IAAI,MAAM,CACtC,CAAC;IAEF,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,WAAW,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;IAE/E,OAAO,EAAwB,CAAC;AAClC,CAAC"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The wire protocol identifiers `PGliteWorker` itself expects, keyed by the
3
+ * `id` option the client sent. Both transports - the SharedWorker and
4
+ * PGlite's own dedicated worker - use these same names, which is what lets a
5
+ * client fall back from one to the other without the two ever colliding.
6
+ */
7
+ /** The lock a leader-election-style worker holds for as long as it runs. */
8
+ export declare function electionLockId(id: string): string;
9
+ /** The broadcast channel every tab of a group listens on. */
10
+ export declare function broadcastChannelId(id: string): string;
11
+ /** The channel a single tab receives RPC responses and notifications on. */
12
+ export declare function tabChannelId(tabId: string): string;
13
+ /** Held by a tab for as long as it is open, so its worker side can detect closure. */
14
+ export declare function tabCloseLockId(tabId: string): string;
15
+ /**
16
+ * Resolves once the named lock is granted; the returned function releases it.
17
+ *
18
+ * PGlite's own worker helper, retyped so the release function is never
19
+ * `undefined` - the promise inside `request`'s callback never resolves until
20
+ * `release` has been captured.
21
+ */
22
+ export declare function acquireLock(name: string): Promise<() => void>;
23
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,4EAA4E;AAC5E,wBAAgB,cAAc,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAEjD;AAED,6DAA6D;AAC7D,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAErD;AAED,4EAA4E;AAC5E,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,sFAAsF;AACtF,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEpD;AAOD;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,CAAC,CAY7D"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The wire protocol identifiers `PGliteWorker` itself expects, keyed by the
3
+ * `id` option the client sent. Both transports - the SharedWorker and
4
+ * PGlite's own dedicated worker - use these same names, which is what lets a
5
+ * client fall back from one to the other without the two ever colliding.
6
+ */
7
+ /** The lock a leader-election-style worker holds for as long as it runs. */
8
+ export function electionLockId(id) {
9
+ return `pglite-election-lock:${id}`;
10
+ }
11
+ /** The broadcast channel every tab of a group listens on. */
12
+ export function broadcastChannelId(id) {
13
+ return `pglite-broadcast:${id}`;
14
+ }
15
+ /** The channel a single tab receives RPC responses and notifications on. */
16
+ export function tabChannelId(tabId) {
17
+ return `pglite-tab:${tabId}`;
18
+ }
19
+ /** Held by a tab for as long as it is open, so its worker side can detect closure. */
20
+ export function tabCloseLockId(tabId) {
21
+ return `pglite-tab-close:${tabId}`;
22
+ }
23
+ /**
24
+ * Resolves once the named lock is granted; the returned function releases it.
25
+ *
26
+ * PGlite's own worker helper, retyped so the release function is never
27
+ * `undefined` - the promise inside `request`'s callback never resolves until
28
+ * `release` has been captured.
29
+ */
30
+ export function acquireLock(name) {
31
+ const { navigator } = globalThis;
32
+ return new Promise((resolve) => {
33
+ void navigator.locks.request(name, () => new Promise((release) => {
34
+ resolve(release);
35
+ }));
36
+ });
37
+ }
38
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,4EAA4E;AAC5E,MAAM,UAAU,cAAc,CAAC,EAAU;IACvC,OAAO,wBAAwB,EAAE,EAAE,CAAC;AACtC,CAAC;AAED,6DAA6D;AAC7D,MAAM,UAAU,kBAAkB,CAAC,EAAU;IAC3C,OAAO,oBAAoB,EAAE,EAAE,CAAC;AAClC,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,YAAY,CAAC,KAAa;IACxC,OAAO,cAAc,KAAK,EAAE,CAAC;AAC/B,CAAC;AAED,sFAAsF;AACtF,MAAM,UAAU,cAAc,CAAC,KAAa;IAC1C,OAAO,oBAAoB,KAAK,EAAE,CAAC;AACrC,CAAC;AAOD;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,MAAM,EAAE,SAAS,EAAE,GAAG,UAAmD,CAAC;IAE1E,OAAO,IAAI,OAAO,CAAa,CAAC,OAAO,EAAE,EAAE;QACzC,KAAK,SAAS,CAAC,KAAK,CAAC,OAAO,CAC1B,IAAI,EACJ,GAAG,EAAE,CACH,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;YAC5B,OAAO,CAAC,OAAO,CAAC,CAAC;QACnB,CAAC,CAAC,CACL,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The SharedWorker side of a multi-tab PGlite database: one instance serves
3
+ * every tab of one browser context, so the database is never owned by a
4
+ * particular tab and is never handed over when one closes.
5
+ *
6
+ * `connectTab` and `makeWorkerApi` below are derived from
7
+ * `@electric-sql/pglite`'s `packages/pglite/src/worker/index.ts`
8
+ * (Apache-2.0, copyright ElectricSQL) and have been modified to use this
9
+ * package's id helpers. Everything else - the per-port handshake in
10
+ * {@link createConnectHandler} and {@link sharedWorker} - is new: it
11
+ * replaces upstream's `postMessage`-based single-client handshake and
12
+ * leader election, neither of which apply here since exactly one
13
+ * SharedWorker already exists per origin and database id.
14
+ */
15
+ import type { WorkerOptions } from '@electric-sql/pglite/worker';
16
+ /**
17
+ * Builds the per-port connection handler for one database group.
18
+ *
19
+ * The database boots once, on the first port to send `init`; every port -
20
+ * including ones that connect long after that - gets `here` then `ready`.
21
+ */
22
+ export declare function createConnectHandler(options: WorkerOptions): (port: MessagePort) => void;
23
+ /** Runs a `WorkerOptions.init`-configured PGlite database as a SharedWorker. */
24
+ export declare function sharedWorker(options: WorkerOptions): void;
25
+ //# sourceMappingURL=shared-worker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared-worker.d.ts","sourceRoot":"","sources":["../src/shared-worker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AA+NjE;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,aAAa,GAAG,CAAC,IAAI,EAAE,WAAW,KAAK,IAAI,CA2ExF;AAED,gFAAgF;AAChF,wBAAgB,YAAY,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI,CAYzD"}
@@ -0,0 +1,236 @@
1
+ /**
2
+ * The SharedWorker side of a multi-tab PGlite database: one instance serves
3
+ * every tab of one browser context, so the database is never owned by a
4
+ * particular tab and is never handed over when one closes.
5
+ *
6
+ * `connectTab` and `makeWorkerApi` below are derived from
7
+ * `@electric-sql/pglite`'s `packages/pglite/src/worker/index.ts`
8
+ * (Apache-2.0, copyright ElectricSQL) and have been modified to use this
9
+ * package's id helpers. Everything else - the per-port handshake in
10
+ * {@link createConnectHandler} and {@link sharedWorker} - is new: it
11
+ * replaces upstream's `postMessage`-based single-client handshake and
12
+ * leader election, neither of which apply here since exactly one
13
+ * SharedWorker already exists per origin and database id.
14
+ */
15
+ import { acquireLock, broadcastChannelId, electionLockId, tabChannelId, tabCloseLockId, } from './protocol.js';
16
+ function connectTab(tabId, pg, connectedTabs) {
17
+ if (connectedTabs.has(tabId)) {
18
+ return;
19
+ }
20
+ connectedTabs.add(tabId);
21
+ const tabChannel = new BroadcastChannel(tabChannelId(tabId));
22
+ // The tab-close lock is held by the client for as long as it is open, so
23
+ // it becomes available the moment the tab (or its `PGliteWorker`) closes.
24
+ // oxlint-disable-next-line promise/always-return -- fire-and-forget cleanup, nothing to chain onto.
25
+ void acquireLock(tabCloseLockId(tabId)).then(() => {
26
+ tabChannel.close();
27
+ connectedTabs.delete(tabId);
28
+ });
29
+ const api = makeWorkerApi(tabId, pg);
30
+ tabChannel.addEventListener('message', async (event) => {
31
+ const msg = event.data;
32
+ if (msg.type !== 'rpc-call') {
33
+ return;
34
+ }
35
+ await pg.waitReady;
36
+ const { callId, method, args } = msg;
37
+ try {
38
+ // @ts-ignore no apparent reason why it fails
39
+ const result = (await api[method](...args));
40
+ tabChannel.postMessage({
41
+ type: 'rpc-return',
42
+ callId,
43
+ result,
44
+ });
45
+ }
46
+ catch (error) {
47
+ // oxlint-disable-next-line no-console
48
+ console.error(error);
49
+ tabChannel.postMessage({
50
+ type: 'rpc-error',
51
+ callId,
52
+ error: { message: error.message },
53
+ });
54
+ }
55
+ });
56
+ // Send a message to the tab to let it know it's connected
57
+ tabChannel.postMessage({ type: 'connected' });
58
+ }
59
+ function makeWorkerApi(tabId, db) {
60
+ let queryLockRelease = null;
61
+ let transactionLockRelease = null;
62
+ // If the tab is closed while it is holding a lock, release the locks and
63
+ // roll back any pending transaction.
64
+ // oxlint-disable-next-line promise/always-return -- fire-and-forget cleanup, nothing to chain onto.
65
+ void acquireLock(tabCloseLockId(tabId)).then(() => {
66
+ if (transactionLockRelease) {
67
+ void db.exec('ROLLBACK');
68
+ }
69
+ queryLockRelease?.();
70
+ transactionLockRelease?.();
71
+ });
72
+ return {
73
+ async getDebugLevel() {
74
+ return db.debug;
75
+ },
76
+ async close() {
77
+ await db.close();
78
+ },
79
+ async execProtocol(message) {
80
+ const { messages, data } = await db.execProtocol(message);
81
+ if (data.byteLength !== data.buffer.byteLength) {
82
+ const buffer = new ArrayBuffer(data.byteLength);
83
+ const dataCopy = new Uint8Array(buffer);
84
+ dataCopy.set(data);
85
+ return { messages, data: dataCopy };
86
+ }
87
+ return { messages, data };
88
+ },
89
+ async execProtocolStream(message) {
90
+ return await db.execProtocolStream(message);
91
+ },
92
+ async execProtocolRawStream(message, options) {
93
+ return await db.execProtocolRawStream(message, options);
94
+ },
95
+ async execProtocolRaw(message) {
96
+ const result = await db.execProtocolRaw(message);
97
+ if (result.byteLength !== result.buffer.byteLength) {
98
+ // The data is a slice of a larger buffer, potentially the whole
99
+ // memory of the WASM module - copy it out before it is sent.
100
+ const buffer = new ArrayBuffer(result.byteLength);
101
+ const resultCopy = new Uint8Array(buffer);
102
+ resultCopy.set(result);
103
+ return resultCopy;
104
+ }
105
+ return result;
106
+ },
107
+ async dumpDataDir(compression) {
108
+ return await db.dumpDataDir(compression);
109
+ },
110
+ async syncToFs() {
111
+ return await db.syncToFs();
112
+ },
113
+ // oxlint-disable-next-line no-underscore-dangle -- PGlite's own method name.
114
+ async _handleBlob(blob) {
115
+ // oxlint-disable-next-line no-underscore-dangle -- PGlite's own method name.
116
+ return await db._handleBlob(blob);
117
+ },
118
+ // oxlint-disable-next-line no-underscore-dangle -- PGlite's own method name.
119
+ async _getWrittenBlob() {
120
+ // oxlint-disable-next-line no-underscore-dangle -- PGlite's own method name.
121
+ return await db._getWrittenBlob();
122
+ },
123
+ // oxlint-disable-next-line no-underscore-dangle -- PGlite's own method name.
124
+ async _cleanupBlob() {
125
+ // oxlint-disable-next-line no-underscore-dangle -- PGlite's own method name.
126
+ return await db._cleanupBlob();
127
+ },
128
+ // oxlint-disable-next-line no-underscore-dangle -- PGlite's own method name.
129
+ async _checkReady() {
130
+ // oxlint-disable-next-line no-underscore-dangle -- PGlite's own method name.
131
+ return await db._checkReady();
132
+ },
133
+ async _acquireQueryLock() {
134
+ return new Promise((resolve) => {
135
+ // oxlint-disable-next-line no-underscore-dangle -- PGlite's own method name.
136
+ void db._runExclusiveQuery(() => new Promise((release) => {
137
+ queryLockRelease = release;
138
+ resolve();
139
+ }));
140
+ });
141
+ },
142
+ async _releaseQueryLock() {
143
+ queryLockRelease?.();
144
+ queryLockRelease = null;
145
+ },
146
+ async _acquireTransactionLock() {
147
+ return new Promise((resolve) => {
148
+ // oxlint-disable-next-line no-underscore-dangle -- PGlite's own method name.
149
+ void db._runExclusiveTransaction(() => new Promise((release) => {
150
+ transactionLockRelease = release;
151
+ resolve();
152
+ }));
153
+ });
154
+ },
155
+ async _releaseTransactionLock() {
156
+ transactionLockRelease?.();
157
+ transactionLockRelease = null;
158
+ },
159
+ };
160
+ }
161
+ /**
162
+ * Builds the per-port connection handler for one database group.
163
+ *
164
+ * The database boots once, on the first port to send `init`; every port -
165
+ * including ones that connect long after that - gets `here` then `ready`.
166
+ */
167
+ export function createConnectHandler(options) {
168
+ const scope = globalThis;
169
+ let idResolve;
170
+ const idPromise = new Promise((resolve) => {
171
+ idResolve = resolve;
172
+ });
173
+ let started = false;
174
+ let dbPromise;
175
+ const connectedTabs = new Set();
176
+ const start = async (id, initOptions) => {
177
+ // Guards the case where a tab already fell back to a dedicated worker
178
+ // and owns this database: this worker then simply waits here forever,
179
+ // while its own clients still reach the real owner over the broadcast
180
+ // channel, because both transports speak the same protocol under the
181
+ // same ids.
182
+ await acquireLock(electionLockId(id));
183
+ dbPromise = options.init(initOptions);
184
+ const channel = new BroadcastChannel(broadcastChannelId(id));
185
+ channel.addEventListener('message', (event) => {
186
+ const msg = event.data;
187
+ if (msg.type === 'tab-here') {
188
+ void dbPromise?.then((db) => connectTab(msg.id, db, connectedTabs));
189
+ }
190
+ });
191
+ // Tabs left over from a previous worker generation reset and re-announce
192
+ // themselves - `PGliteWorker` re-sends `tab-here` every 16ms until it is
193
+ // connected - so this goes out before the database has finished booting.
194
+ channel.postMessage({ type: 'leader-here', id });
195
+ const db = await dbPromise;
196
+ db.onNotification((notifyChannel, payload) => {
197
+ channel.postMessage({ type: 'notify', channel: notifyChannel, payload });
198
+ });
199
+ };
200
+ return (port) => {
201
+ port.start();
202
+ port.postMessage({ type: 'here' });
203
+ let initialized = false;
204
+ port.addEventListener('message', (event) => {
205
+ const msg = event.data;
206
+ if (msg.type !== 'init' || initialized) {
207
+ return;
208
+ }
209
+ initialized = true;
210
+ if (!started) {
211
+ started = true;
212
+ const initOptions = msg.options;
213
+ const id = initOptions.id ?? `${scope.location.href}:${initOptions.dataDir ?? ''}`;
214
+ idResolve(id);
215
+ void start(id, initOptions);
216
+ }
217
+ // oxlint-disable-next-line promise/always-return -- fire-and-forget reply, nothing to chain onto.
218
+ void idPromise.then((id) => {
219
+ port.postMessage({ type: 'ready', id });
220
+ });
221
+ });
222
+ };
223
+ }
224
+ /** Runs a `WorkerOptions.init`-configured PGlite database as a SharedWorker. */
225
+ export function sharedWorker(options) {
226
+ const scope = globalThis;
227
+ const handleConnect = createConnectHandler(options);
228
+ // oxlint-disable-next-line unicorn/prefer-add-event-listener -- the standard SharedWorker handshake API.
229
+ scope.onconnect = (event) => {
230
+ const port = event.ports[0];
231
+ if (port) {
232
+ handleConnect(port);
233
+ }
234
+ };
235
+ }
236
+ //# sourceMappingURL=shared-worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared-worker.js","sourceRoot":"","sources":["../src/shared-worker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAKH,OAAO,EACL,WAAW,EACX,kBAAkB,EAClB,cAAc,EACd,YAAY,EACZ,cAAc,GACf,MAAM,eAAe,CAAC;AAIvB,SAAS,UAAU,CAAC,KAAa,EAAE,EAAU,EAAE,aAA0B;IACvE,IAAI,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;QAC7B,OAAO;IACT,CAAC;IAED,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAEzB,MAAM,UAAU,GAAG,IAAI,gBAAgB,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;IAE7D,yEAAyE;IACzE,0EAA0E;IAC1E,oGAAoG;IAC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AC,IAAI,CAAC,CAAC;QACtB,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,11 @@
1
+ import type { WorkerOptions } from '@electric-sql/pglite/worker';
2
+ /**
3
+ * The one worker entry point for `@supapower/worker`.
4
+ *
5
+ * Runs as a `SharedWorker` when the script is loaded as one - PGlite's own
6
+ * `worker()` calls the global `postMessage`, which does not exist in a
7
+ * SharedWorker scope, so the branch below is required, not cosmetic - and
8
+ * falls back to PGlite's own dedicated worker otherwise.
9
+ */
10
+ export declare function worker(options: WorkerOptions): Promise<void>;
11
+ //# sourceMappingURL=worker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAEjE;;;;;;;GAOG;AACH,wBAAsB,MAAM,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAiBlE"}
package/dist/worker.js ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The one worker entry point for `@supapower/worker`.
3
+ *
4
+ * Runs as a `SharedWorker` when the script is loaded as one - PGlite's own
5
+ * `worker()` calls the global `postMessage`, which does not exist in a
6
+ * SharedWorker scope, so the branch below is required, not cosmetic - and
7
+ * falls back to PGlite's own dedicated worker otherwise.
8
+ */
9
+ export async function worker(options) {
10
+ if ('SharedWorkerGlobalScope' in globalThis) {
11
+ // Dynamic: `./shared-worker.js` touches `BroadcastChannel`/`navigator.locks`
12
+ // at import time in some bundlers' eager-eval mode, so it must load lazily
13
+ // to keep this module importable from Node/Bun outside a worker.
14
+ const { sharedWorker } = await import('./shared-worker.js');
15
+ sharedWorker(options);
16
+ return;
17
+ }
18
+ // Dynamic for the same reason: PGlite's dedicated-worker entry point pulls
19
+ // in browser-only worker plumbing that must not run outside a worker scope.
20
+ const { worker: dedicatedWorker } = await import('@electric-sql/pglite/worker');
21
+ await dedicatedWorker(options);
22
+ }
23
+ //# sourceMappingURL=worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.js","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,OAAsB;IACjD,IAAI,yBAAyB,IAAI,UAAU,EAAE,CAAC;QAC5C,6EAA6E;QAC7E,2EAA2E;QAC3E,iEAAiE;QACjE,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,MAAM,CAAC,oBAAoB,CAAC,CAAC;QAE5D,YAAY,CAAC,OAAO,CAAC,CAAC;QAEtB,OAAO;IACT,CAAC;IAED,2EAA2E;IAC3E,4EAA4E;IAC5E,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,GAAG,MAAM,MAAM,CAAC,6BAA6B,CAAC,CAAC;IAEhF,MAAM,eAAe,CAAC,OAAO,CAAC,CAAC;AACjC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@supapower/worker",
3
+ "version": "0.1.0",
4
+ "description": "A more stable drop-in replacement for PGlite's built-in multi-tab worker, using a SharedWorker with automatic fallback",
5
+ "keywords": [
6
+ "local-first",
7
+ "multi-tab",
8
+ "pglite",
9
+ "shared-worker",
10
+ "supapower",
11
+ "worker"
12
+ ],
13
+ "homepage": "https://github.com/aboviq/supapower/tree/main/packages/worker#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/aboviq/supapower/issues"
16
+ },
17
+ "license": "Apache-2.0",
18
+ "author": "Aboviq AB",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/aboviq/supapower.git",
22
+ "directory": "packages/worker"
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "LICENSE",
27
+ "NOTICE",
28
+ "README.md"
29
+ ],
30
+ "type": "module",
31
+ "sideEffects": false,
32
+ "main": "./dist/index.js",
33
+ "types": "./dist/index.d.ts",
34
+ "exports": {
35
+ ".": {
36
+ "types": "./dist/index.d.ts",
37
+ "default": "./dist/index.js"
38
+ },
39
+ "./worker": {
40
+ "types": "./dist/worker.d.ts",
41
+ "default": "./dist/worker.js"
42
+ },
43
+ "./package.json": "./package.json"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "scripts": {
49
+ "build": "tsc --project tsconfig.build.json",
50
+ "clean": "rm -rf dist *.tsbuildinfo",
51
+ "typecheck": "tsc --project tsconfig.json"
52
+ },
53
+ "devDependencies": {
54
+ "@electric-sql/pglite": "^0.5.8"
55
+ },
56
+ "peerDependencies": {
57
+ "@electric-sql/pglite": ">=0.5.8 <0.6.0"
58
+ },
59
+ "engines": {
60
+ "node": ">=22"
61
+ }
62
+ }