@lowdefy/client-core 0.0.0-experimental-20261019052246

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 (52) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +9 -0
  3. package/dist/auth/createAuthFetchOptions.js +56 -0
  4. package/dist/auth/createAuthMethods.js +1070 -0
  5. package/dist/auth/createPkceChallenge.js +57 -0
  6. package/dist/auth/endBearerSession.js +26 -0
  7. package/dist/auth/getAuthorizationHeaders.js +31 -0
  8. package/dist/auth/validateAuthTransport.js +41 -0
  9. package/dist/claimCallerReload.js +41 -0
  10. package/dist/createCallAPI.js +39 -0
  11. package/dist/createCallRequest.js +34 -0
  12. package/dist/createHandleError.js +90 -0
  13. package/dist/createLowdefyCore.js +124 -0
  14. package/dist/createPageLifecycleManager.js +173 -0
  15. package/dist/getActiveLocale.js +26 -0
  16. package/dist/getContextKey.js +29 -0
  17. package/dist/hasOtherRoles.js +30 -0
  18. package/dist/index.js +32 -0
  19. package/dist/isOtherCaller.js +29 -0
  20. package/dist/recordCallerStamp.js +31 -0
  21. package/dist/recorder/buildEngineRecord.js +34 -0
  22. package/dist/recorder/buildInteractionRecord.js +60 -0
  23. package/dist/recorder/buildTraceEvent.js +62 -0
  24. package/dist/recorder/chunkRecords.js +78 -0
  25. package/dist/recorder/collectEventActions.js +22 -0
  26. package/dist/recorder/collectEventEndpoints.js +39 -0
  27. package/dist/recorder/collectEventRequests.js +38 -0
  28. package/dist/recorder/createPairingBuffer.js +177 -0
  29. package/dist/recorder/createPasswordRedactor.js +64 -0
  30. package/dist/recorder/createRecordBatcher.js +50 -0
  31. package/dist/recorder/createRecordingSession.js +60 -0
  32. package/dist/recorder/diffStateWrites.js +86 -0
  33. package/dist/recorder/isEventCall.js +26 -0
  34. package/dist/recorder/jsonType.js +35 -0
  35. package/dist/recorder/sendRecords.js +39 -0
  36. package/dist/recorder/toJsonSafe.js +26 -0
  37. package/dist/request.js +127 -0
  38. package/dist/setLowdefyUser.js +32 -0
  39. package/dist/shouldReloadForAuthError.js +39 -0
  40. package/dist/shouldReloadForBuild.js +45 -0
  41. package/dist/shouldReloadForCaller.js +50 -0
  42. package/dist/storage/clearUserStorage.js +36 -0
  43. package/dist/storage/clearUserStorageOnOwnerChange.js +42 -0
  44. package/dist/storage/createStorage.js +51 -0
  45. package/dist/storage/listUserStorageKeys.js +36 -0
  46. package/dist/storage/userStorageKey.js +24 -0
  47. package/dist/storage/userStoragePrefix.js +25 -0
  48. package/dist/test/createMemoryStore.js +40 -0
  49. package/dist/updateLowdefyPage.js +44 -0
  50. package/dist/url.js +29 -0
  51. package/dist/websocket/createWebSocketClient.js +428 -0
  52. package/package.json +57 -0
@@ -0,0 +1,428 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { decodeServerError } from '@lowdefy/engine';
16
+ import { ServiceError } from '@lowdefy/errors';
17
+ import { type } from '@lowdefy/helpers';
18
+ import getAuthorizationHeaders from '../auth/getAuthorizationHeaders.js';
19
+ const ACK_TIMEOUT_MS = 10 * 1000;
20
+ const IDLE_CLOSE_GRACE_MS = 5 * 1000;
21
+ const RECONNECT_BASE_MS = 500;
22
+ const RECONNECT_CAP_MS = 15 * 1000;
23
+ // A connection that stays open this long resets the reconnect backoff. A
24
+ // server that accepts connections and drops them straight away keeps backing
25
+ // off instead of being retried every half second.
26
+ const STABLE_CONNECTION_MS = 10 * 1000;
27
+ // The server closes with this code when the socket's caller signed out or
28
+ // changed (user, organization or roles). The client reconnects straight away,
29
+ // which authenticates afresh, and resubscribes as the new caller.
30
+ const CALLER_CHANGED_CODE = 4401;
31
+ // A connection closed for a caller change again within this long of opening
32
+ // reconnects with the normal backoff, so a server that keeps closing for that
33
+ // reason does not get a tight reconnect loop.
34
+ const CALLER_CHANGE_REPEAT_MS = 30 * 1000;
35
+ // One websocket per browser tab, shared by all channels, created lazily on
36
+ // the first subscribe or publish. Connections are ephemeral in production
37
+ // (serverless platforms close them at function max duration), so reconnect
38
+ // with backoff and resubscribe is the steady state, not an edge case.
39
+ // The host gives the WebSocket constructor and turns the API path into the
40
+ // socket's URL.
41
+ function createWebSocketClient(lowdefy) {
42
+ const { host } = lowdefy._internal;
43
+ // websocketId → { websocketId, payload, handlers, requestId, ackTimer, pending }
44
+ // requestId names the last subscribe frame sent, which the server echoes in
45
+ // its reply. ackTimer runs while that frame waits for its ack. pending holds
46
+ // the subscribe promise's { resolve, reject } until the first ack, then is
47
+ // null.
48
+ const subscriptions = new Map();
49
+ // requestId → { frame, sent, resolve, reject, timer } for publishes waiting
50
+ // for their ack. A publish made while disconnected is sent when the
51
+ // connection opens, unless it timed out first.
52
+ const pendingPublishes = new Map();
53
+ let socket = null;
54
+ let openPromise = null;
55
+ let reconnectAttempt = 0;
56
+ let reconnectTimer = null;
57
+ let idleTimer = null;
58
+ let stableTimer = null;
59
+ // When the current connection opened, and whether it was opened by the
60
+ // reconnect that follows a caller change.
61
+ let openedAt = null;
62
+ let reconnectingAfterCallerChange = false;
63
+ let publishCounter = 0;
64
+ let subscribeCounter = 0;
65
+ function url() {
66
+ return host.websocketUrl(`${lowdefy.apiBase ?? ''}/api/websocket`);
67
+ }
68
+ // A browser sends the session cookie on the upgrade itself. A bearer host
69
+ // sends its token as a header, which React Native's WebSocket takes as a
70
+ // third argument; it is read on every connect, so a reconnect after a caller
71
+ // change authenticates with the token held then.
72
+ function createSocket() {
73
+ const headers = getAuthorizationHeaders({
74
+ host
75
+ });
76
+ if (type.isNone(headers.Authorization)) {
77
+ return new host.WebSocket(url());
78
+ }
79
+ return new host.WebSocket(url(), undefined, {
80
+ headers
81
+ });
82
+ }
83
+ function clearIdleTimer() {
84
+ if (idleTimer) {
85
+ clearTimeout(idleTimer);
86
+ idleTimer = null;
87
+ }
88
+ }
89
+ function isIdle() {
90
+ return subscriptions.size === 0 && pendingPublishes.size === 0;
91
+ }
92
+ function scheduleIdleClose() {
93
+ clearIdleTimer();
94
+ if (!isIdle()) {
95
+ return;
96
+ }
97
+ // Grace period so rapid page navigation doesn't thrash connections.
98
+ idleTimer = setTimeout(()=>{
99
+ if (isIdle() && socket) {
100
+ // The close event arrives after the closing handshake, when a new
101
+ // socket may already be connecting or open. This socket is finished
102
+ // with, so its events must not reach the client state that now
103
+ // belongs to the new socket.
104
+ socket.onclose = null;
105
+ socket.onmessage = null;
106
+ clearTimeout(stableTimer);
107
+ reconnectingAfterCallerChange = false;
108
+ socket.close();
109
+ socket = null;
110
+ openPromise = null;
111
+ }
112
+ }, IDLE_CLOSE_GRACE_MS);
113
+ }
114
+ function isSocketOpen() {
115
+ return socket !== null && socket.readyState === host.WebSocket.OPEN;
116
+ }
117
+ function sendPublish(pending) {
118
+ pending.sent = true;
119
+ socket.send(JSON.stringify(pending.frame));
120
+ }
121
+ function hasUnsentPublishes() {
122
+ return [
123
+ ...pendingPublishes.values()
124
+ ].some((pending)=>!pending.sent);
125
+ }
126
+ function sendUnsentPublishes() {
127
+ pendingPublishes.forEach((pending)=>{
128
+ if (!pending.sent) {
129
+ sendPublish(pending);
130
+ }
131
+ });
132
+ }
133
+ function clearAckTimer(subscription) {
134
+ clearTimeout(subscription.ackTimer);
135
+ subscription.ackTimer = null;
136
+ }
137
+ function handleAckTimeout(subscription) {
138
+ subscription.ackTimer = null;
139
+ const error = new ServiceError(`Subscribe to "${subscription.websocketId}" timed out.`, {
140
+ service: 'WebSocket'
141
+ });
142
+ if (subscription.pending) {
143
+ subscriptions.delete(subscription.websocketId);
144
+ // The server handles the frame late, or not yet, and would open the feed
145
+ // for a caller that has given up on it.
146
+ if (isSocketOpen()) {
147
+ socket.send(JSON.stringify({
148
+ type: 'unsubscribe',
149
+ websocketId: subscription.websocketId
150
+ }));
151
+ }
152
+ scheduleIdleClose();
153
+ subscription.pending.reject(error);
154
+ return;
155
+ }
156
+ subscription.handlers.onError(error.message);
157
+ }
158
+ // Every path that removes a subscription from the map or answers its
159
+ // subscribe clears this timer, so a timer that fires always belongs to the
160
+ // subscription currently in the map.
161
+ function startAckTimer(subscription) {
162
+ clearAckTimer(subscription);
163
+ subscription.ackTimer = setTimeout(()=>handleAckTimeout(subscription), ACK_TIMEOUT_MS);
164
+ }
165
+ function sendSubscribe(subscription) {
166
+ const { payload, websocketId } = subscription;
167
+ subscribeCounter += 1;
168
+ subscription.requestId = `s${subscribeCounter}`;
169
+ startAckTimer(subscription);
170
+ socket.send(JSON.stringify({
171
+ type: 'subscribe',
172
+ websocketId,
173
+ payload,
174
+ requestId: subscription.requestId
175
+ }));
176
+ }
177
+ // A reply to an earlier subscribe frame for the same feed, one that a newer
178
+ // subscribe or a resubscribe replaced, does not answer this subscription. A
179
+ // server that does not echo requestId answers by websocketId alone.
180
+ function answersSubscription(subscription, requestId) {
181
+ return type.isNone(requestId) || requestId === subscription.requestId;
182
+ }
183
+ function settlePublish(requestId) {
184
+ const pending = pendingPublishes.get(requestId);
185
+ clearTimeout(pending.timer);
186
+ pendingPublishes.delete(requestId);
187
+ scheduleIdleClose();
188
+ return pending;
189
+ }
190
+ // A caller that unsubscribed, or whose subscribe was replaced by a newer one
191
+ // to the same feed, no longer wants this subscription, so its subscribe
192
+ // promise settles without an error.
193
+ function releaseSubscription(subscription) {
194
+ clearAckTimer(subscription);
195
+ if (subscription.pending) {
196
+ subscription.pending.resolve();
197
+ subscription.pending = null;
198
+ }
199
+ }
200
+ function resubscribeAll() {
201
+ subscriptions.forEach(sendSubscribe);
202
+ }
203
+ function handleFrame(frame) {
204
+ const { error: errorPayload, message, payload, requestId, websocketId } = frame;
205
+ const subscription = subscriptions.get(websocketId);
206
+ switch(frame.type){
207
+ case 'message':
208
+ subscription?.handlers.onMessage(payload);
209
+ return;
210
+ case 'subscribed':
211
+ if (!subscription || !answersSubscription(subscription, requestId)) {
212
+ return;
213
+ }
214
+ clearAckTimer(subscription);
215
+ if (subscription.pending) {
216
+ subscription.pending.resolve();
217
+ subscription.pending = null;
218
+ }
219
+ subscription.handlers.onConnected();
220
+ return;
221
+ case 'unsubscribed':
222
+ return;
223
+ case 'published':
224
+ if (pendingPublishes.has(requestId)) {
225
+ settlePublish(requestId).resolve();
226
+ }
227
+ return;
228
+ case 'error':
229
+ {
230
+ // Reply frames carry the error payload; broadcasts and frame-format
231
+ // errors carry only a message string.
232
+ const error = errorPayload ? decodeServerError(errorPayload) : new ServiceError(message ?? 'WebSocket error.', {
233
+ service: 'WebSocket'
234
+ });
235
+ if (!type.isNone(requestId) && pendingPublishes.has(requestId)) {
236
+ settlePublish(requestId).reject(error);
237
+ return;
238
+ }
239
+ if (!subscription) {
240
+ lowdefy._internal.logger.warn(error);
241
+ return;
242
+ }
243
+ // A broadcast from the feed's source carries no requestId.
244
+ if (type.isNone(requestId)) {
245
+ subscription.handlers.onError(error.message);
246
+ return;
247
+ }
248
+ if (requestId !== subscription.requestId) {
249
+ return;
250
+ }
251
+ clearAckTimer(subscription);
252
+ if (subscription.pending) {
253
+ subscriptions.delete(websocketId);
254
+ scheduleIdleClose();
255
+ subscription.pending.reject(error);
256
+ return;
257
+ }
258
+ subscription.handlers.onError(error.message);
259
+ return;
260
+ }
261
+ default:
262
+ }
263
+ }
264
+ function handleClose(event) {
265
+ socket = null;
266
+ openPromise = null;
267
+ clearTimeout(stableTimer);
268
+ subscriptions.forEach((subscription)=>{
269
+ // A resubscribe lost with the connection is sent again, with a new ack
270
+ // timer, when the connection reopens. A subscribe whose caller still
271
+ // waits keeps its timer, so it fails if no connection opens in time.
272
+ if (!subscription.pending) {
273
+ clearAckTimer(subscription);
274
+ }
275
+ subscription.handlers.onDisconnected();
276
+ });
277
+ if (subscriptions.size === 0 && !hasUnsentPublishes()) {
278
+ return;
279
+ }
280
+ // A caller change is not a failing server, so the first reconnect after
281
+ // one does not back off.
282
+ if (event.code === CALLER_CHANGED_CODE) {
283
+ const repeated = reconnectingAfterCallerChange && Date.now() - openedAt < CALLER_CHANGE_REPEAT_MS;
284
+ if (!repeated) {
285
+ reconnectAttempt = 0;
286
+ }
287
+ reconnectingAfterCallerChange = true;
288
+ } else {
289
+ reconnectingAfterCallerChange = false;
290
+ }
291
+ // Capped exponential backoff with full jitter.
292
+ const base = Math.min(RECONNECT_BASE_MS * 2 ** reconnectAttempt, RECONNECT_CAP_MS);
293
+ const delay = Math.random() * base;
294
+ reconnectAttempt += 1;
295
+ reconnectTimer = setTimeout(()=>{
296
+ reconnectTimer = null;
297
+ connect();
298
+ }, delay);
299
+ }
300
+ function connect() {
301
+ if (openPromise) {
302
+ return openPromise;
303
+ }
304
+ clearIdleTimer();
305
+ openPromise = new Promise((resolve, reject)=>{
306
+ const ws = createSocket();
307
+ ws.onopen = ()=>{
308
+ socket = ws;
309
+ openedAt = Date.now();
310
+ stableTimer = setTimeout(()=>{
311
+ reconnectAttempt = 0;
312
+ }, STABLE_CONNECTION_MS);
313
+ resubscribeAll();
314
+ sendUnsentPublishes();
315
+ // Everything that asked for this connection may have finished while
316
+ // it was opening.
317
+ scheduleIdleClose();
318
+ resolve();
319
+ };
320
+ ws.onmessage = (event)=>{
321
+ let frame;
322
+ try {
323
+ frame = JSON.parse(event.data);
324
+ } catch (e) {
325
+ return;
326
+ }
327
+ handleFrame(frame);
328
+ };
329
+ ws.onclose = (event)=>{
330
+ if (socket !== ws) {
331
+ // Never opened — treat as a failed connect and retry.
332
+ openPromise = null;
333
+ reject(new ServiceError('Connection failed.', {
334
+ service: 'WebSocket'
335
+ }));
336
+ }
337
+ handleClose(event);
338
+ };
339
+ ws.onerror = ()=>{
340
+ // onclose always follows onerror — reconnect is handled there.
341
+ };
342
+ });
343
+ // Connection errors surface through subscribe/publish ack timeouts.
344
+ openPromise.catch(()=>{});
345
+ return openPromise;
346
+ }
347
+ function subscribe({ handlers, payload, websocketId }) {
348
+ clearIdleTimer();
349
+ const previous = subscriptions.get(websocketId);
350
+ if (previous) {
351
+ releaseSubscription(previous);
352
+ }
353
+ return new Promise((resolve, reject)=>{
354
+ const subscription = {
355
+ websocketId,
356
+ payload,
357
+ handlers,
358
+ ackTimer: null,
359
+ pending: {
360
+ resolve,
361
+ reject
362
+ }
363
+ };
364
+ subscriptions.set(websocketId, subscription);
365
+ if (isSocketOpen()) {
366
+ sendSubscribe(subscription);
367
+ return;
368
+ }
369
+ // The frame is sent by resubscribeAll when the connection opens, which
370
+ // restarts the ack timer. Until then the timer bounds the wait for a
371
+ // connection.
372
+ startAckTimer(subscription);
373
+ connect();
374
+ });
375
+ }
376
+ function unsubscribe({ websocketId }) {
377
+ const subscription = subscriptions.get(websocketId);
378
+ if (!subscription) {
379
+ return;
380
+ }
381
+ releaseSubscription(subscription);
382
+ subscriptions.delete(websocketId);
383
+ if (isSocketOpen()) {
384
+ socket.send(JSON.stringify({
385
+ type: 'unsubscribe',
386
+ websocketId
387
+ }));
388
+ }
389
+ scheduleIdleClose();
390
+ }
391
+ function publish({ payload, websocketId }) {
392
+ clearIdleTimer();
393
+ publishCounter += 1;
394
+ const requestId = `p${publishCounter}`;
395
+ return new Promise((resolve, reject)=>{
396
+ const timer = setTimeout(()=>{
397
+ settlePublish(requestId).reject(new ServiceError(`Publish to "${websocketId}" timed out.`, {
398
+ service: 'WebSocket'
399
+ }));
400
+ }, ACK_TIMEOUT_MS);
401
+ const pending = {
402
+ frame: {
403
+ type: 'publish',
404
+ websocketId,
405
+ requestId,
406
+ payload
407
+ },
408
+ sent: false,
409
+ resolve,
410
+ reject,
411
+ timer
412
+ };
413
+ pendingPublishes.set(requestId, pending);
414
+ if (isSocketOpen()) {
415
+ sendPublish(pending);
416
+ return;
417
+ }
418
+ connect();
419
+ });
420
+ }
421
+ return {
422
+ connect,
423
+ publish,
424
+ subscribe,
425
+ unsubscribe
426
+ };
427
+ }
428
+ export default createWebSocketClient;
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@lowdefy/client-core",
3
+ "version": "0.0.0-experimental-20261019052246",
4
+ "license": "Apache-2.0",
5
+ "description": "Lowdefy Client Core - the platform-free half of the Lowdefy client, shared by its renderers",
6
+ "homepage": "https://lowdefy.com",
7
+ "keywords": [
8
+ "lowdefy"
9
+ ],
10
+ "bugs": {
11
+ "url": "https://github.com/lowdefy/lowdefy/issues"
12
+ },
13
+ "contributors": [
14
+ {
15
+ "name": "Sam Tolmay",
16
+ "url": "https://github.com/SamTolmay"
17
+ },
18
+ {
19
+ "name": "Gerrie van Wyk",
20
+ "url": "https://github.com/Gervwyk"
21
+ }
22
+ ],
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/lowdefy/lowdefy.git"
26
+ },
27
+ "type": "module",
28
+ "exports": {
29
+ ".": "./dist/index.js",
30
+ "./*": "./dist/*"
31
+ },
32
+ "files": [
33
+ "dist/*"
34
+ ],
35
+ "dependencies": {
36
+ "@lowdefy/engine": "0.0.0-experimental-20261019052246",
37
+ "@lowdefy/errors": "0.0.0-experimental-20261019052246",
38
+ "@lowdefy/helpers": "0.0.0-experimental-20261019052246",
39
+ "@lowdefy/logger": "0.0.0-experimental-20261019052246"
40
+ },
41
+ "devDependencies": {
42
+ "@jest/globals": "28.1.3",
43
+ "@swc/cli": "0.8.1",
44
+ "@swc/core": "1.15.32",
45
+ "@swc/jest": "0.2.39",
46
+ "jest": "28.1.3",
47
+ "jest-environment-jsdom": "28.1.3"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "scripts": {
53
+ "build": "swc src --out-dir dist --config-file ../../.swcrc --cli-config-file ../../.swc-cli.json",
54
+ "clean": "rm -rf dist",
55
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
56
+ }
57
+ }