on-zero 0.4.25 → 0.4.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/dist/cjs/createUseQuery.cjs +28 -16
  2. package/dist/cjs/createUseQuery.native.js +42 -30
  3. package/dist/cjs/createUseQuery.native.js.map +1 -1
  4. package/dist/cjs/createZeroClient.cjs +13 -1
  5. package/dist/cjs/createZeroClient.native.js +13 -1
  6. package/dist/cjs/createZeroClient.native.js.map +1 -1
  7. package/dist/cjs/httpPull/auth.test.cjs +197 -0
  8. package/dist/cjs/httpPull/auth.test.native.js +279 -0
  9. package/dist/cjs/httpPull/auth.test.native.js.map +1 -0
  10. package/dist/cjs/httpPull/churn.test.cjs +132 -0
  11. package/dist/cjs/httpPull/churn.test.native.js +155 -0
  12. package/dist/cjs/httpPull/churn.test.native.js.map +1 -0
  13. package/dist/cjs/httpPull/fixtureSchema.cjs +76 -0
  14. package/dist/cjs/httpPull/fixtureSchema.native.js +82 -0
  15. package/dist/cjs/httpPull/fixtureSchema.native.js.map +1 -0
  16. package/dist/cjs/httpPull/fixtureServer.cjs +340 -0
  17. package/dist/cjs/httpPull/fixtureServer.native.js +534 -0
  18. package/dist/cjs/httpPull/fixtureServer.native.js.map +1 -0
  19. package/dist/cjs/httpPull/integration.test.cjs +53 -0
  20. package/dist/cjs/httpPull/integration.test.native.js +60 -0
  21. package/dist/cjs/httpPull/integration.test.native.js.map +1 -0
  22. package/dist/cjs/httpPull/rebase.test.cjs +360 -0
  23. package/dist/cjs/httpPull/rebase.test.native.js +420 -0
  24. package/dist/cjs/httpPull/rebase.test.native.js.map +1 -0
  25. package/dist/cjs/httpPull/relations.test.cjs +107 -0
  26. package/dist/cjs/httpPull/relations.test.native.js +119 -0
  27. package/dist/cjs/httpPull/relations.test.native.js.map +1 -0
  28. package/dist/cjs/httpPull/testHarness.cjs +100 -0
  29. package/dist/cjs/httpPull/testHarness.native.js +112 -0
  30. package/dist/cjs/httpPull/testHarness.native.js.map +1 -0
  31. package/dist/cjs/httpPull/transport.test.cjs +568 -0
  32. package/dist/cjs/httpPull/transport.test.native.js +655 -0
  33. package/dist/cjs/httpPull/transport.test.native.js.map +1 -0
  34. package/dist/cjs/httpPullTransport.cjs +432 -0
  35. package/dist/cjs/httpPullTransport.native.js +695 -0
  36. package/dist/cjs/httpPullTransport.native.js.map +1 -0
  37. package/dist/cjs/index.cjs +1 -0
  38. package/dist/cjs/index.native.js +1 -0
  39. package/dist/cjs/index.native.js.map +1 -1
  40. package/dist/cjs/multiInstanceNested.test.cjs +26 -0
  41. package/dist/cjs/multiInstanceNested.test.native.js +34 -0
  42. package/dist/cjs/multiInstanceNested.test.native.js.map +1 -1
  43. package/dist/esm/createUseQuery.mjs +28 -16
  44. package/dist/esm/createUseQuery.mjs.map +1 -1
  45. package/dist/esm/createUseQuery.native.js +42 -30
  46. package/dist/esm/createUseQuery.native.js.map +1 -1
  47. package/dist/esm/createZeroClient.mjs +13 -1
  48. package/dist/esm/createZeroClient.mjs.map +1 -1
  49. package/dist/esm/createZeroClient.native.js +13 -1
  50. package/dist/esm/createZeroClient.native.js.map +1 -1
  51. package/dist/esm/httpPull/auth.test.mjs +198 -0
  52. package/dist/esm/httpPull/auth.test.mjs.map +1 -0
  53. package/dist/esm/httpPull/auth.test.native.js +277 -0
  54. package/dist/esm/httpPull/auth.test.native.js.map +1 -0
  55. package/dist/esm/httpPull/churn.test.mjs +133 -0
  56. package/dist/esm/httpPull/churn.test.mjs.map +1 -0
  57. package/dist/esm/httpPull/churn.test.native.js +153 -0
  58. package/dist/esm/httpPull/churn.test.native.js.map +1 -0
  59. package/dist/esm/httpPull/fixtureSchema.mjs +50 -0
  60. package/dist/esm/httpPull/fixtureSchema.mjs.map +1 -0
  61. package/dist/esm/httpPull/fixtureSchema.native.js +53 -0
  62. package/dist/esm/httpPull/fixtureSchema.native.js.map +1 -0
  63. package/dist/esm/httpPull/fixtureServer.mjs +315 -0
  64. package/dist/esm/httpPull/fixtureServer.mjs.map +1 -0
  65. package/dist/esm/httpPull/fixtureServer.native.js +506 -0
  66. package/dist/esm/httpPull/fixtureServer.native.js.map +1 -0
  67. package/dist/esm/httpPull/integration.test.mjs +54 -0
  68. package/dist/esm/httpPull/integration.test.mjs.map +1 -0
  69. package/dist/esm/httpPull/integration.test.native.js +58 -0
  70. package/dist/esm/httpPull/integration.test.native.js.map +1 -0
  71. package/dist/esm/httpPull/rebase.test.mjs +361 -0
  72. package/dist/esm/httpPull/rebase.test.mjs.map +1 -0
  73. package/dist/esm/httpPull/rebase.test.native.js +418 -0
  74. package/dist/esm/httpPull/rebase.test.native.js.map +1 -0
  75. package/dist/esm/httpPull/relations.test.mjs +108 -0
  76. package/dist/esm/httpPull/relations.test.mjs.map +1 -0
  77. package/dist/esm/httpPull/relations.test.native.js +117 -0
  78. package/dist/esm/httpPull/relations.test.native.js.map +1 -0
  79. package/dist/esm/httpPull/testHarness.mjs +72 -0
  80. package/dist/esm/httpPull/testHarness.mjs.map +1 -0
  81. package/dist/esm/httpPull/testHarness.native.js +81 -0
  82. package/dist/esm/httpPull/testHarness.native.js.map +1 -0
  83. package/dist/esm/httpPull/transport.test.mjs +569 -0
  84. package/dist/esm/httpPull/transport.test.mjs.map +1 -0
  85. package/dist/esm/httpPull/transport.test.native.js +653 -0
  86. package/dist/esm/httpPull/transport.test.native.js.map +1 -0
  87. package/dist/esm/httpPullTransport.mjs +406 -0
  88. package/dist/esm/httpPullTransport.mjs.map +1 -0
  89. package/dist/esm/httpPullTransport.native.js +666 -0
  90. package/dist/esm/httpPullTransport.native.js.map +1 -0
  91. package/dist/esm/index.js +1 -0
  92. package/dist/esm/index.js.map +1 -1
  93. package/dist/esm/index.mjs +1 -0
  94. package/dist/esm/index.mjs.map +1 -1
  95. package/dist/esm/index.native.js +1 -0
  96. package/dist/esm/index.native.js.map +1 -1
  97. package/dist/esm/multiInstanceNested.test.mjs +27 -1
  98. package/dist/esm/multiInstanceNested.test.mjs.map +1 -1
  99. package/dist/esm/multiInstanceNested.test.native.js +35 -1
  100. package/dist/esm/multiInstanceNested.test.native.js.map +1 -1
  101. package/package.json +2 -2
  102. package/src/createUseQuery.tsx +40 -22
  103. package/src/createZeroClient.tsx +19 -0
  104. package/src/httpPull/auth.test.ts +208 -0
  105. package/src/httpPull/churn.test.ts +147 -0
  106. package/src/httpPull/fixtureSchema.ts +82 -0
  107. package/src/httpPull/fixtureServer.ts +391 -0
  108. package/src/httpPull/integration.test.ts +57 -0
  109. package/src/httpPull/rebase.test.ts +368 -0
  110. package/src/httpPull/relations.test.ts +135 -0
  111. package/src/httpPull/testHarness.ts +95 -0
  112. package/src/httpPull/transport.test.ts +577 -0
  113. package/src/httpPullTransport.ts +559 -0
  114. package/src/index.ts +1 -0
  115. package/src/multiInstanceNested.test.tsx +25 -1
  116. package/types/createUseQuery.d.ts.map +1 -1
  117. package/types/createZeroClient.d.ts +3 -1
  118. package/types/createZeroClient.d.ts.map +1 -1
  119. package/types/httpPull/auth.test.d.ts +2 -0
  120. package/types/httpPull/auth.test.d.ts.map +1 -0
  121. package/types/httpPull/churn.test.d.ts +2 -0
  122. package/types/httpPull/churn.test.d.ts.map +1 -0
  123. package/types/httpPull/fixtureSchema.d.ts +111 -0
  124. package/types/httpPull/fixtureSchema.d.ts.map +1 -0
  125. package/types/httpPull/fixtureServer.d.ts +14 -0
  126. package/types/httpPull/fixtureServer.d.ts.map +1 -0
  127. package/types/httpPull/integration.test.d.ts +2 -0
  128. package/types/httpPull/integration.test.d.ts.map +1 -0
  129. package/types/httpPull/rebase.test.d.ts +2 -0
  130. package/types/httpPull/rebase.test.d.ts.map +1 -0
  131. package/types/httpPull/relations.test.d.ts +2 -0
  132. package/types/httpPull/relations.test.d.ts.map +1 -0
  133. package/types/httpPull/testHarness.d.ts +32 -0
  134. package/types/httpPull/testHarness.d.ts.map +1 -0
  135. package/types/httpPull/transport.test.d.ts +2 -0
  136. package/types/httpPull/transport.test.d.ts.map +1 -0
  137. package/types/httpPullTransport.d.ts +13 -0
  138. package/types/httpPullTransport.d.ts.map +1 -0
  139. package/types/index.d.ts +1 -0
  140. package/types/index.d.ts.map +1 -1
@@ -0,0 +1,695 @@
1
+ "use strict";
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true
11
+ });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: () => from[key],
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
23
+ value: true
24
+ }), mod);
25
+ var httpPullTransport_exports = {};
26
+ __export(httpPullTransport_exports, {
27
+ ensureHttpPullTransport: () => ensureHttpPullTransport,
28
+ installHttpPullTransport: () => installHttpPullTransport
29
+ });
30
+ module.exports = __toCommonJS(httpPullTransport_exports);
31
+ function _assert_this_initialized(self) {
32
+ if (self === void 0) {
33
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
34
+ }
35
+ return self;
36
+ }
37
+ function _call_super(_this, derived, args) {
38
+ derived = _get_prototype_of(derived);
39
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
40
+ }
41
+ function _class_call_check(instance, Constructor) {
42
+ if (!(instance instanceof Constructor)) {
43
+ throw new TypeError("Cannot call a class as a function");
44
+ }
45
+ }
46
+ function _construct(Parent, args, Class) {
47
+ if (_is_native_reflect_construct()) {
48
+ _construct = Reflect.construct;
49
+ } else {
50
+ _construct = function construct(Parent2, args2, Class2) {
51
+ var a = [null];
52
+ a.push.apply(a, args2);
53
+ var Constructor = Function.bind.apply(Parent2, a);
54
+ var instance = new Constructor();
55
+ if (Class2) _set_prototype_of(instance, Class2.prototype);
56
+ return instance;
57
+ };
58
+ }
59
+ return _construct.apply(null, arguments);
60
+ }
61
+ function _defineProperties(target, props) {
62
+ for (var i = 0; i < props.length; i++) {
63
+ var descriptor = props[i];
64
+ descriptor.enumerable = descriptor.enumerable || false;
65
+ descriptor.configurable = true;
66
+ if ("value" in descriptor) descriptor.writable = true;
67
+ Object.defineProperty(target, descriptor.key, descriptor);
68
+ }
69
+ }
70
+ function _create_class(Constructor, protoProps, staticProps) {
71
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
72
+ if (staticProps) _defineProperties(Constructor, staticProps);
73
+ return Constructor;
74
+ }
75
+ function _define_property(obj, key, value) {
76
+ if (key in obj) {
77
+ Object.defineProperty(obj, key, {
78
+ value,
79
+ enumerable: true,
80
+ configurable: true,
81
+ writable: true
82
+ });
83
+ } else {
84
+ obj[key] = value;
85
+ }
86
+ return obj;
87
+ }
88
+ function _get_prototype_of(o) {
89
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o2) {
90
+ return o2.__proto__ || Object.getPrototypeOf(o2);
91
+ };
92
+ return _get_prototype_of(o);
93
+ }
94
+ function _inherits(subClass, superClass) {
95
+ if (typeof superClass !== "function" && superClass !== null) {
96
+ throw new TypeError("Super expression must either be null or a function");
97
+ }
98
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
99
+ constructor: {
100
+ value: subClass,
101
+ writable: true,
102
+ configurable: true
103
+ }
104
+ });
105
+ if (superClass) _set_prototype_of(subClass, superClass);
106
+ }
107
+ function _instanceof(left, right) {
108
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
109
+ return !!right[Symbol.hasInstance](left);
110
+ } else {
111
+ return left instanceof right;
112
+ }
113
+ }
114
+ function _is_native_function(fn) {
115
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
116
+ }
117
+ function _possible_constructor_return(self, call) {
118
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
119
+ return call;
120
+ }
121
+ return _assert_this_initialized(self);
122
+ }
123
+ function _set_prototype_of(o, p) {
124
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o2, p2) {
125
+ o2.__proto__ = p2;
126
+ return o2;
127
+ };
128
+ return _set_prototype_of(o, p);
129
+ }
130
+ function _type_of(obj) {
131
+ "@swc/helpers - typeof";
132
+
133
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
134
+ }
135
+ function _wrap_native_super(Class) {
136
+ var _cache = typeof Map === "function" ? /* @__PURE__ */new Map() : void 0;
137
+ _wrap_native_super = function wrapNativeSuper(Class2) {
138
+ if (Class2 === null || !_is_native_function(Class2)) return Class2;
139
+ if (typeof Class2 !== "function") {
140
+ throw new TypeError("Super expression must either be null or a function");
141
+ }
142
+ if (typeof _cache !== "undefined") {
143
+ if (_cache.has(Class2)) return _cache.get(Class2);
144
+ _cache.set(Class2, Wrapper);
145
+ }
146
+ function Wrapper() {
147
+ return _construct(Class2, arguments, _get_prototype_of(this).constructor);
148
+ }
149
+ Wrapper.prototype = Object.create(Class2.prototype, {
150
+ constructor: {
151
+ value: Wrapper,
152
+ enumerable: false,
153
+ writable: true,
154
+ configurable: true
155
+ }
156
+ });
157
+ return _set_prototype_of(Wrapper, Class2);
158
+ };
159
+ return _wrap_native_super(Class);
160
+ }
161
+ function _is_native_reflect_construct() {
162
+ try {
163
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
164
+ } catch (_) {}
165
+ return (_is_native_reflect_construct = function () {
166
+ return !!result;
167
+ })();
168
+ }
169
+ var COOKIE_WIDTH = 20;
170
+ function installHttpPullTransport(opts) {
171
+ var _class;
172
+ var previousWebSocket = globalThis.WebSocket;
173
+ var _opts_fetch;
174
+ var fetchImpl = (_opts_fetch = opts.fetch) !== null && _opts_fetch !== void 0 ? _opts_fetch : globalThis.fetch;
175
+ if (!fetchImpl) {
176
+ throw new Error("installHttpPullTransport requires a fetch implementation");
177
+ }
178
+ var state = {
179
+ origin: new URL(opts.origin),
180
+ originString: trimTrailingSlash(new URL(opts.origin).toString()),
181
+ fetch: fetchImpl,
182
+ nativeWebSocket: previousWebSocket,
183
+ sockets: /* @__PURE__ */new Set(),
184
+ pullIntervalMs: opts.pullIntervalMs,
185
+ nextPokeID: 0
186
+ };
187
+ var Shim = (_class = function _class2(url, protocols) {
188
+ "use strict";
189
+
190
+ _class_call_check(this, _class2);
191
+ if (shouldIntercept(state.origin, url)) {
192
+ return new ZeroHttpSocket(state, url, protocols);
193
+ }
194
+ if (!state.nativeWebSocket) {
195
+ throw new Error(`No native WebSocket available for ${String(url)}`);
196
+ }
197
+ return new state.nativeWebSocket(url, protocols);
198
+ }, _define_property(_class, "CONNECTING", 0), _define_property(_class, "OPEN", 1), _define_property(_class, "CLOSING", 2), _define_property(_class, "CLOSED", 3), _class);
199
+ globalThis.WebSocket = Shim;
200
+ return {
201
+ pull: async function () {
202
+ await Promise.all([...state.sockets].map(function (socket) {
203
+ return socket.pull();
204
+ }));
205
+ },
206
+ get connections() {
207
+ return state.sockets.size;
208
+ },
209
+ uninstall: function () {
210
+ if (globalThis.WebSocket === Shim) {
211
+ globalThis.WebSocket = previousWebSocket;
212
+ }
213
+ }
214
+ };
215
+ }
216
+ var transportsByOrigin = /* @__PURE__ */new Map();
217
+ function ensureHttpPullTransport(opts) {
218
+ var key = trimTrailingSlash(new URL(opts.origin).toString());
219
+ var existing = transportsByOrigin.get(key);
220
+ if (existing) return existing;
221
+ var transport = installHttpPullTransport(opts);
222
+ transportsByOrigin.set(key, transport);
223
+ return transport;
224
+ }
225
+ var ZeroHttpSocket = /* @__PURE__ */function () {
226
+ "use strict";
227
+
228
+ function ZeroHttpSocket2(state, url, protocols) {
229
+ var _this = this;
230
+ _class_call_check(this, ZeroHttpSocket2);
231
+ var _decoded_initConnectionMessage;
232
+ _define_property(this, "state", void 0);
233
+ _define_property(this, "CONNECTING", void 0);
234
+ _define_property(this, "OPEN", void 0);
235
+ _define_property(this, "CLOSING", void 0);
236
+ _define_property(this, "CLOSED", void 0);
237
+ _define_property(this, "url", void 0);
238
+ _define_property(this, "readyState", void 0);
239
+ _define_property(this, "connectURL", void 0);
240
+ _define_property(this, "authToken", void 0);
241
+ _define_property(this, "listeners", void 0);
242
+ _define_property(this, "clientID", void 0);
243
+ _define_property(this, "clientGroupID", void 0);
244
+ _define_property(this, "wsid", void 0);
245
+ _define_property(this, "cookie", void 0);
246
+ _define_property(this, "pendingGotQueriesPatch", void 0);
247
+ _define_property(this, "pullInFlight", void 0);
248
+ _define_property(this, "pullAfterCurrent", void 0);
249
+ _define_property(this, "pushChain", void 0);
250
+ _define_property(this, "nextLocalCookieID", void 0);
251
+ _define_property(this, "openTimer", void 0);
252
+ _define_property(this, "pullTimer", void 0);
253
+ this.state = state;
254
+ this.CONNECTING = 0;
255
+ this.OPEN = 1;
256
+ this.CLOSING = 2;
257
+ this.CLOSED = 3;
258
+ this.readyState = this.CONNECTING;
259
+ this.listeners = {
260
+ open: /* @__PURE__ */new Set(),
261
+ message: /* @__PURE__ */new Set(),
262
+ close: /* @__PURE__ */new Set(),
263
+ error: /* @__PURE__ */new Set()
264
+ };
265
+ this.pendingGotQueriesPatch = [];
266
+ this.pullAfterCurrent = false;
267
+ this.pushChain = Promise.resolve();
268
+ this.nextLocalCookieID = 0;
269
+ this.connectURL = toHttpURL(url);
270
+ this.url = String(url);
271
+ var _this_connectURL_searchParams_get;
272
+ this.clientID = (_this_connectURL_searchParams_get = this.connectURL.searchParams.get("clientID")) !== null && _this_connectURL_searchParams_get !== void 0 ? _this_connectURL_searchParams_get : "";
273
+ var _this_connectURL_searchParams_get1;
274
+ this.clientGroupID = (_this_connectURL_searchParams_get1 = this.connectURL.searchParams.get("clientGroupID")) !== null && _this_connectURL_searchParams_get1 !== void 0 ? _this_connectURL_searchParams_get1 : "";
275
+ var _this_connectURL_searchParams_get2;
276
+ this.wsid = (_this_connectURL_searchParams_get2 = this.connectURL.searchParams.get("wsid")) !== null && _this_connectURL_searchParams_get2 !== void 0 ? _this_connectURL_searchParams_get2 : `zero-http-${Date.now()}`;
277
+ var baseCookie = this.connectURL.searchParams.get("baseCookie");
278
+ this.cookie = baseCookie ? baseCookie : null;
279
+ var decoded = decodeSecProtocol(protocols);
280
+ this.authToken = decoded.authToken;
281
+ this.queueDesiredQueries((_decoded_initConnectionMessage = decoded.initConnectionMessage) === null || _decoded_initConnectionMessage === void 0 ? void 0 : _decoded_initConnectionMessage[1]);
282
+ this.state.sockets.add(this);
283
+ this.openTimer = setTimeout(function () {
284
+ return _this.open();
285
+ }, 0);
286
+ }
287
+ _create_class(ZeroHttpSocket2, [{
288
+ key: "addEventListener",
289
+ value: function addEventListener(type, listener) {
290
+ var _this_listeners_type;
291
+ if (listener) (_this_listeners_type = this.listeners[type]) === null || _this_listeners_type === void 0 ? void 0 : _this_listeners_type.add(listener);
292
+ }
293
+ }, {
294
+ key: "removeEventListener",
295
+ value: function removeEventListener(type, listener) {
296
+ var _this_listeners_type;
297
+ if (listener) (_this_listeners_type = this.listeners[type]) === null || _this_listeners_type === void 0 ? void 0 : _this_listeners_type.delete(listener);
298
+ }
299
+ }, {
300
+ key: "dispatchEvent",
301
+ value: function dispatchEvent(event) {
302
+ this.emit(event.type, event);
303
+ return true;
304
+ }
305
+ }, {
306
+ key: "send",
307
+ value: function send(data) {
308
+ if (this.readyState !== this.OPEN) {
309
+ throw new Error("cannot send on a socket that is not open");
310
+ }
311
+ var message = JSON.parse(data);
312
+ switch (message[0]) {
313
+ case "initConnection":
314
+ case "changeDesiredQueries":
315
+ this.queueDesiredQueries(message[1]);
316
+ this.requestPullAfterCurrent();
317
+ return;
318
+ case "updateAuth":
319
+ this.authToken = message[1].auth;
320
+ return;
321
+ case "push":
322
+ this.enqueuePush(message[1]);
323
+ return;
324
+ case "ping":
325
+ this.emitMessage(["pong", {}]);
326
+ return;
327
+ case "pull":
328
+ this.run(this.answerMutationRecoveryPull(message[1]));
329
+ return;
330
+ case "deleteClients":
331
+ case "ackMutationResponses":
332
+ return;
333
+ default:
334
+ throw new Error(`unsupported zero-http upstream message ${message[0]}`);
335
+ }
336
+ }
337
+ }, {
338
+ key: "close",
339
+ value: function close() {
340
+ var code = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 1e3,
341
+ reason = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
342
+ if (this.readyState === this.CLOSED) return;
343
+ if (this.openTimer) clearTimeout(this.openTimer);
344
+ if (this.pullTimer) clearInterval(this.pullTimer);
345
+ this.readyState = this.CLOSED;
346
+ this.state.sockets.delete(this);
347
+ this.emit("close", {
348
+ code,
349
+ reason,
350
+ wasClean: code <= 1001
351
+ });
352
+ }
353
+ }, {
354
+ key: "pull",
355
+ value: function pull() {
356
+ var _this = this;
357
+ if (this.readyState === this.CLOSED) return Promise.resolve();
358
+ if (this.pullInFlight) return this.pullInFlight;
359
+ this.pullInFlight = this.fetchPull(this.clientGroupID, this.cookie).then(function (response) {
360
+ if (response.unchanged) {
361
+ _this.emitGotQueriesPatch(response.cookie);
362
+ return;
363
+ }
364
+ _this.emitPoke(response);
365
+ }).catch(function (error) {
366
+ _this.fail(error);
367
+ throw error;
368
+ }).finally(async function () {
369
+ var pullAgain = _this.pullAfterCurrent;
370
+ _this.pullAfterCurrent = false;
371
+ _this.pullInFlight = void 0;
372
+ if (pullAgain && _this.readyState !== _this.CLOSED) await _this.pull();
373
+ });
374
+ return this.pullInFlight;
375
+ }
376
+ }, {
377
+ key: "open",
378
+ value: function open() {
379
+ var _this = this;
380
+ if (this.readyState !== this.CONNECTING) return;
381
+ this.readyState = this.OPEN;
382
+ this.emit("open", {});
383
+ this.emitMessage(["connected", {
384
+ wsid: this.wsid,
385
+ timestamp: Date.now()
386
+ }]);
387
+ setTimeout(function () {
388
+ return _this.run(_this.pull());
389
+ }, 0);
390
+ if (this.state.pullIntervalMs) {
391
+ this.pullTimer = setInterval(function () {
392
+ _this.run(_this.pull());
393
+ }, this.state.pullIntervalMs);
394
+ }
395
+ }
396
+ }, {
397
+ key: "queueDesiredQueries",
398
+ value: function queueDesiredQueries(body) {
399
+ var desiredQueriesPatch = body === null || body === void 0 ? void 0 : body.desiredQueriesPatch;
400
+ if (!Array.isArray(desiredQueriesPatch)) return;
401
+ this.pendingGotQueriesPatch.push(...gotQueriesPatch(desiredQueriesPatch));
402
+ }
403
+ }, {
404
+ key: "push",
405
+ value: async function push(body) {
406
+ var response = await this.postJSON("/push", body);
407
+ this.emitMessage(["pushResponse", response.pushResponse]);
408
+ this.requestPullAfterCurrent();
409
+ }
410
+ }, {
411
+ key: "enqueuePush",
412
+ value: function enqueuePush(body) {
413
+ var _this = this;
414
+ var nextPush = this.pushChain.then(async function () {
415
+ if (_this.readyState === _this.CLOSED) return;
416
+ await _this.push(body);
417
+ });
418
+ this.pushChain = nextPush.catch(function () {});
419
+ this.run(nextPush);
420
+ }
421
+ }, {
422
+ key: "requestPullAfterCurrent",
423
+ value: function requestPullAfterCurrent() {
424
+ if (this.pullInFlight) {
425
+ this.pullAfterCurrent = true;
426
+ return;
427
+ }
428
+ this.run(this.pull());
429
+ }
430
+ }, {
431
+ key: "answerMutationRecoveryPull",
432
+ value: async function answerMutationRecoveryPull(body) {
433
+ var response = await this.fetchPull(body.clientGroupID, body.cookie);
434
+ var cookie = toWebSocketCookie(response.cookie);
435
+ var _ref;
436
+ this.emitMessage(["pull", {
437
+ requestID: body.requestID,
438
+ cookie: (_ref = cookie !== null && cookie !== void 0 ? cookie : this.cookie) !== null && _ref !== void 0 ? _ref : "0",
439
+ lastMutationIDChanges: response.unchanged ? {} : response.lastMutationIDChanges
440
+ }]);
441
+ }
442
+ }, {
443
+ key: "fetchPull",
444
+ value: async function fetchPull(clientGroupID, cookie) {
445
+ return await this.postJSON("/pull", {
446
+ clientID: this.clientID,
447
+ clientGroupID,
448
+ cookie: toHttpCookie(cookie)
449
+ });
450
+ }
451
+ }, {
452
+ key: "postJSON",
453
+ value: async function postJSON(path, body) {
454
+ var response = await this.state.fetch(`${this.state.originString}${path}`, {
455
+ method: "POST",
456
+ headers: {
457
+ authorization: this.authToken ? `Bearer ${this.authToken}` : "",
458
+ "content-type": "application/json"
459
+ },
460
+ body: JSON.stringify(body)
461
+ });
462
+ if (!response.ok) {
463
+ throw new ZeroHttpResponseError(path, response.status);
464
+ }
465
+ return response.json();
466
+ }
467
+ }, {
468
+ key: "run",
469
+ value: function run(promise) {
470
+ var _this = this;
471
+ void promise.catch(function (error) {
472
+ return _this.fail(error);
473
+ });
474
+ }
475
+ }, {
476
+ key: "fail",
477
+ value: function fail(error) {
478
+ if (this.readyState === this.CLOSED) return;
479
+ if (isAuthHTTPError(error)) {
480
+ this.emitMessage(["error", {
481
+ kind: "Unauthorized",
482
+ message: error.message,
483
+ origin: "server"
484
+ }]);
485
+ if (this.readyState !== this.CLOSED) this.close(1e3, error.message);
486
+ return;
487
+ }
488
+ this.emit("error", {
489
+ error
490
+ });
491
+ this.close(1011, errorMessage(error));
492
+ }
493
+ }, {
494
+ key: "emitPoke",
495
+ value: function emitPoke(response) {
496
+ var nextCookie = toWebSocketCookie(response.cookie);
497
+ if (isStaleCookie(this.cookie, response.cookie)) {
498
+ throw new Error(`zero-http pull returned stale cookie ${response.cookie} for ${this.cookie}`);
499
+ }
500
+ var pokeID = `zero-http-${++this.state.nextPokeID}`;
501
+ var gotQueries = this.pendingGotQueriesPatch;
502
+ this.pendingGotQueriesPatch = [];
503
+ this.emitMessage(["pokeStart", {
504
+ pokeID,
505
+ baseCookie: this.cookie,
506
+ schemaVersions: {
507
+ minSupportedVersion: 1,
508
+ maxSupportedVersion: 1
509
+ },
510
+ timestamp: Date.now()
511
+ }]);
512
+ this.emitMessage(["pokePart", {
513
+ pokeID,
514
+ lastMutationIDChanges: response.lastMutationIDChanges,
515
+ rowsPatch: response.rowsPatch
516
+ }]);
517
+ if (gotQueries.length > 0) {
518
+ this.emitMessage(["pokePart", {
519
+ pokeID,
520
+ gotQueriesPatch: gotQueries
521
+ }]);
522
+ }
523
+ this.emitMessage(["pokeEnd", {
524
+ pokeID,
525
+ cookie: nextCookie
526
+ }]);
527
+ this.cookie = nextCookie;
528
+ }
529
+ }, {
530
+ key: "emitGotQueriesPatch",
531
+ value: function emitGotQueriesPatch(cookie) {
532
+ if (this.pendingGotQueriesPatch.length === 0) return;
533
+ var serverCookie = cookie !== null && cookie !== void 0 ? cookie : toHttpCookie(this.cookie);
534
+ if (serverCookie === null) return;
535
+ var nextCookie = toLocalWebSocketCookie(serverCookie, ++this.nextLocalCookieID);
536
+ var pokeID = `zero-http-${++this.state.nextPokeID}`;
537
+ var gotQueries = this.pendingGotQueriesPatch;
538
+ this.pendingGotQueriesPatch = [];
539
+ this.emitMessage(["pokeStart", {
540
+ pokeID,
541
+ baseCookie: this.cookie,
542
+ schemaVersions: {
543
+ minSupportedVersion: 1,
544
+ maxSupportedVersion: 1
545
+ },
546
+ timestamp: Date.now()
547
+ }]);
548
+ this.emitMessage(["pokePart", {
549
+ pokeID,
550
+ gotQueriesPatch: gotQueries
551
+ }]);
552
+ this.emitMessage(["pokeEnd", {
553
+ pokeID,
554
+ cookie: nextCookie
555
+ }]);
556
+ this.cookie = nextCookie;
557
+ }
558
+ }, {
559
+ key: "emitMessage",
560
+ value: function emitMessage(message) {
561
+ if (this.readyState !== this.OPEN) return;
562
+ this.emit("message", {
563
+ data: JSON.stringify(message)
564
+ });
565
+ }
566
+ }, {
567
+ key: "emit",
568
+ value: function emit(type, event) {
569
+ var handler = this[`on${type}`];
570
+ if (typeof handler === "function") handler.call(this, event);
571
+ var _iteratorNormalCompletion = true,
572
+ _didIteratorError = false,
573
+ _iteratorError = void 0;
574
+ try {
575
+ for (var _iterator = this.listeners[type][Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
576
+ var listener = _step.value;
577
+ if (typeof listener === "function") listener(event);else listener.handleEvent(event);
578
+ }
579
+ } catch (err) {
580
+ _didIteratorError = true;
581
+ _iteratorError = err;
582
+ } finally {
583
+ try {
584
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
585
+ _iterator.return();
586
+ }
587
+ } finally {
588
+ if (_didIteratorError) {
589
+ throw _iteratorError;
590
+ }
591
+ }
592
+ }
593
+ }
594
+ }]);
595
+ return ZeroHttpSocket2;
596
+ }();
597
+ function shouldIntercept(origin, url) {
598
+ var candidate = toHttpURL(url);
599
+ if (candidate.origin !== origin.origin) return false;
600
+ return candidate.pathname === `${trimTrailingSlash(origin.pathname)}/sync/v51/connect`;
601
+ }
602
+ function toHttpURL(url) {
603
+ var parsed = new URL(url);
604
+ if (parsed.protocol === "ws:") parsed.protocol = "http:";
605
+ if (parsed.protocol === "wss:") parsed.protocol = "https:";
606
+ return parsed;
607
+ }
608
+ function trimTrailingSlash(value) {
609
+ return value.endsWith("/") ? value.slice(0, -1) : value;
610
+ }
611
+ function decodeSecProtocol(protocols) {
612
+ var protocol = Array.isArray(protocols) ? protocols[0] : protocols;
613
+ if (!protocol) return {};
614
+ try {
615
+ var decoded = decodeURIComponent(protocol);
616
+ var json = new TextDecoder().decode(Uint8Array.from(globalThis.atob(decoded), function (char) {
617
+ return char.charCodeAt(0);
618
+ }));
619
+ var parsed = JSON.parse(json);
620
+ return {
621
+ authToken: parsed.authToken,
622
+ initConnectionMessage: Array.isArray(parsed.initConnectionMessage) ? parsed.initConnectionMessage : void 0
623
+ };
624
+ } catch (e) {
625
+ return {};
626
+ }
627
+ }
628
+ function gotQueriesPatch(patch) {
629
+ var got = [];
630
+ var _iteratorNormalCompletion = true,
631
+ _didIteratorError = false,
632
+ _iteratorError = void 0;
633
+ try {
634
+ for (var _iterator = patch[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
635
+ var op = _step.value;
636
+ if (op.op === "clear") got.push({
637
+ op: "clear"
638
+ });else if (op.hash) got.push({
639
+ op: op.op,
640
+ hash: op.hash
641
+ });
642
+ }
643
+ } catch (err) {
644
+ _didIteratorError = true;
645
+ _iteratorError = err;
646
+ } finally {
647
+ try {
648
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
649
+ _iterator.return();
650
+ }
651
+ } finally {
652
+ if (_didIteratorError) {
653
+ throw _iteratorError;
654
+ }
655
+ }
656
+ }
657
+ return got;
658
+ }
659
+ function toHttpCookie(cookie) {
660
+ if (cookie === null || cookie === "") return null;
661
+ var parsed = Number(cookie.slice(0, COOKIE_WIDTH));
662
+ if (!Number.isFinite(parsed)) {
663
+ throw new Error(`zero-http cookie is not numeric: ${cookie}`);
664
+ }
665
+ return parsed;
666
+ }
667
+ function toWebSocketCookie(cookie) {
668
+ return cookie === null ? null : String(cookie).padStart(COOKIE_WIDTH, "0");
669
+ }
670
+ function toLocalWebSocketCookie(cookie, localID) {
671
+ return `${String(cookie).padStart(COOKIE_WIDTH, "0")}#${String(localID).padStart(6, "0")}`;
672
+ }
673
+ function isStaleCookie(current, next) {
674
+ var currentNumber = toHttpCookie(current);
675
+ return currentNumber !== null && next <= currentNumber;
676
+ }
677
+ function errorMessage(error) {
678
+ return _instanceof(error, Error) ? error.message : String(error);
679
+ }
680
+ var ZeroHttpResponseError = /* @__PURE__ */function (Error1) {
681
+ "use strict";
682
+
683
+ _inherits(ZeroHttpResponseError2, Error1);
684
+ function ZeroHttpResponseError2(path, status) {
685
+ _class_call_check(this, ZeroHttpResponseError2);
686
+ var _this;
687
+ _this = _call_super(this, ZeroHttpResponseError2, [`zero-http ${path} failed with ${status}`]), _define_property(_this, "path", void 0), _define_property(_this, "status", void 0), _this.path = path, _this.status = status;
688
+ return _this;
689
+ }
690
+ return ZeroHttpResponseError2;
691
+ }(_wrap_native_super(Error));
692
+ function isAuthHTTPError(error) {
693
+ return _instanceof(error, ZeroHttpResponseError) && (error.status === 401 || error.status === 403);
694
+ }
695
+ //# sourceMappingURL=httpPullTransport.native.js.map