@ably/ai-transport 0.0.1 → 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/README.md +54 -47
- package/dist/ably-ai-transport.js +1006 -539
- package/dist/ably-ai-transport.js.map +1 -1
- package/dist/ably-ai-transport.umd.cjs +1 -1
- package/dist/ably-ai-transport.umd.cjs.map +1 -1
- package/dist/constants.d.ts +4 -0
- package/dist/core/codec/types.d.ts +19 -2
- package/dist/core/transport/decode-history.d.ts +8 -6
- package/dist/core/transport/headers.d.ts +4 -2
- package/dist/core/transport/index.d.ts +4 -1
- package/dist/core/transport/pipe-stream.d.ts +3 -2
- package/dist/core/transport/stream-router.d.ts +11 -1
- package/dist/core/transport/tree.d.ts +171 -0
- package/dist/core/transport/turn-manager.d.ts +4 -1
- package/dist/core/transport/types.d.ts +270 -119
- package/dist/core/transport/view.d.ts +166 -0
- package/dist/errors.d.ts +19 -2
- package/dist/index.d.ts +3 -1
- package/dist/react/ably-ai-transport-react.js +1019 -486
- package/dist/react/ably-ai-transport-react.js.map +1 -1
- package/dist/react/ably-ai-transport-react.umd.cjs +1 -1
- package/dist/react/ably-ai-transport-react.umd.cjs.map +1 -1
- package/dist/react/contexts/transport-context.d.ts +31 -0
- package/dist/react/contexts/transport-provider.d.ts +49 -0
- package/dist/react/create-transport-hooks.d.ts +124 -0
- package/dist/react/index.d.ts +14 -8
- package/dist/react/use-ably-messages.d.ts +14 -8
- package/dist/react/use-active-turns.d.ts +7 -3
- package/dist/react/use-client-transport.d.ts +78 -5
- package/dist/react/use-create-view.d.ts +22 -0
- package/dist/react/use-tree.d.ts +20 -0
- package/dist/react/use-view.d.ts +79 -0
- package/dist/vercel/ably-ai-transport-vercel.js +1478 -842
- package/dist/vercel/ably-ai-transport-vercel.js.map +1 -1
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs +1 -1
- package/dist/vercel/ably-ai-transport-vercel.umd.cjs.map +1 -1
- package/dist/vercel/codec/tool-transitions.d.ts +50 -0
- package/dist/vercel/index.d.ts +3 -0
- package/dist/vercel/react/ably-ai-transport-vercel-react.js +9099 -852
- package/dist/vercel/react/ably-ai-transport-vercel-react.js.map +1 -1
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs +45 -1
- package/dist/vercel/react/ably-ai-transport-vercel-react.umd.cjs.map +1 -1
- package/dist/vercel/react/contexts/chat-transport-context.d.ts +32 -0
- package/dist/vercel/react/contexts/chat-transport-provider.d.ts +84 -0
- package/dist/vercel/react/index.d.ts +5 -0
- package/dist/vercel/react/use-chat-transport.d.ts +61 -20
- package/dist/vercel/react/use-message-sync.d.ts +41 -9
- package/dist/vercel/react/use-staged-add-tool-approval-response.d.ts +30 -0
- package/dist/vercel/tool-approvals.d.ts +124 -0
- package/dist/vercel/tool-events.d.ts +26 -0
- package/dist/vercel/transport/chat-transport.d.ts +33 -11
- package/dist/vercel/transport/index.d.ts +5 -2
- package/package.json +23 -17
- package/src/constants.ts +6 -0
- package/src/core/codec/encoder.ts +10 -1
- package/src/core/codec/types.ts +19 -3
- package/src/core/transport/client-transport.ts +382 -364
- package/src/core/transport/decode-history.ts +229 -81
- package/src/core/transport/headers.ts +6 -2
- package/src/core/transport/index.ts +13 -5
- package/src/core/transport/pipe-stream.ts +8 -5
- package/src/core/transport/server-transport.ts +212 -58
- package/src/core/transport/stream-router.ts +21 -3
- package/src/core/transport/{conversation-tree.ts → tree.ts} +192 -77
- package/src/core/transport/turn-manager.ts +28 -10
- package/src/core/transport/types.ts +318 -139
- package/src/core/transport/view.ts +840 -0
- package/src/errors.ts +21 -1
- package/src/index.ts +10 -5
- package/src/react/contexts/transport-context.ts +37 -0
- package/src/react/contexts/transport-provider.tsx +164 -0
- package/src/react/create-transport-hooks.ts +144 -0
- package/src/react/index.ts +15 -8
- package/src/react/use-ably-messages.ts +34 -16
- package/src/react/use-active-turns.ts +28 -17
- package/src/react/use-client-transport.ts +184 -24
- package/src/react/use-create-view.ts +68 -0
- package/src/react/use-tree.ts +53 -0
- package/src/react/use-view.ts +233 -0
- package/src/react/vite.config.ts +4 -1
- package/src/vercel/codec/accumulator.ts +64 -79
- package/src/vercel/codec/decoder.ts +11 -8
- package/src/vercel/codec/encoder.ts +68 -54
- package/src/vercel/codec/index.ts +0 -2
- package/src/vercel/codec/tool-transitions.ts +122 -0
- package/src/vercel/index.ts +17 -0
- package/src/vercel/react/contexts/chat-transport-context.ts +40 -0
- package/src/vercel/react/contexts/chat-transport-provider.tsx +122 -0
- package/src/vercel/react/index.ts +14 -0
- package/src/vercel/react/use-chat-transport.ts +164 -42
- package/src/vercel/react/use-message-sync.ts +77 -19
- package/src/vercel/react/use-staged-add-tool-approval-response.ts +87 -0
- package/src/vercel/react/vite.config.ts +4 -2
- package/src/vercel/tool-approvals.ts +380 -0
- package/src/vercel/tool-events.ts +53 -0
- package/src/vercel/transport/chat-transport.ts +225 -79
- package/src/vercel/transport/index.ts +14 -3
- package/dist/core/transport/conversation-tree.d.ts +0 -9
- package/dist/react/use-conversation-tree.d.ts +0 -20
- package/dist/react/use-edit.d.ts +0 -7
- package/dist/react/use-history.d.ts +0 -19
- package/dist/react/use-messages.d.ts +0 -7
- package/dist/react/use-regenerate.d.ts +0 -7
- package/dist/react/use-send.d.ts +0 -7
- package/src/react/use-conversation-tree.ts +0 -71
- package/src/react/use-edit.ts +0 -24
- package/src/react/use-history.ts +0 -111
- package/src/react/use-messages.ts +0 -32
- package/src/react/use-regenerate.ts +0 -24
- package/src/react/use-send.ts +0 -25
|
@@ -1,103 +1,106 @@
|
|
|
1
1
|
import * as e from "ably";
|
|
2
2
|
//#region src/constants.ts
|
|
3
|
-
var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-ably-turn-id",
|
|
4
|
-
return e[e.BadRequest = 4e4] = "BadRequest", e[e.InvalidArgument = 40003] = "InvalidArgument", e[e.EncoderRecoveryFailed = 104e3] = "EncoderRecoveryFailed", e[e.TransportSubscriptionError = 104001] = "TransportSubscriptionError", e[e.CancelListenerError = 104002] = "CancelListenerError", e[e.TurnLifecycleError = 104003] = "TurnLifecycleError", e[e.TransportClosed = 104004] = "TransportClosed", e[e.TransportSendFailed = 104005] = "TransportSendFailed", e;
|
|
5
|
-
}({}),
|
|
3
|
+
var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-ably-discrete", a = "x-ably-turn-id", o = "x-ably-msg-id", s = "x-ably-turn-client-id", c = "x-ably-role", l = "x-ably-amend", u = "x-ably-cancel-turn-id", d = "x-ably-cancel-own", f = "x-ably-cancel-all", p = "x-ably-cancel-client-id", m = "x-ably-parent", h = "x-ably-fork-of", g = "x-ably-turn-reason", _ = "x-ably-cancel", v = "x-ably-turn-start", y = "x-ably-turn-end", b = "x-ably-abort", x = "x-ably-error", S = "x-domain-", C = /* @__PURE__ */ function(e) {
|
|
4
|
+
return e[e.BadRequest = 4e4] = "BadRequest", e[e.InvalidArgument = 40003] = "InvalidArgument", e[e.EncoderRecoveryFailed = 104e3] = "EncoderRecoveryFailed", e[e.TransportSubscriptionError = 104001] = "TransportSubscriptionError", e[e.CancelListenerError = 104002] = "CancelListenerError", e[e.TurnLifecycleError = 104003] = "TurnLifecycleError", e[e.TransportClosed = 104004] = "TransportClosed", e[e.TransportSendFailed = 104005] = "TransportSendFailed", e[e.ChannelContinuityLost = 104006] = "ChannelContinuityLost", e[e.ChannelNotReady = 104007] = "ChannelNotReady", e[e.StreamError = 104008] = "StreamError", e;
|
|
5
|
+
}({}), ee = (e, t) => e.code === t, w = (e) => {
|
|
6
6
|
let t = e.extras;
|
|
7
7
|
if (!t || typeof t != "object") return {};
|
|
8
8
|
let n = t.headers;
|
|
9
9
|
return !n || typeof n != "object" ? {} : n;
|
|
10
|
-
},
|
|
10
|
+
}, T = (e) => {
|
|
11
11
|
if (e !== void 0) try {
|
|
12
12
|
return JSON.parse(e);
|
|
13
13
|
} catch {
|
|
14
14
|
return;
|
|
15
15
|
}
|
|
16
|
-
},
|
|
16
|
+
}, E = (e, t) => ({
|
|
17
17
|
...e,
|
|
18
18
|
...t
|
|
19
|
-
}),
|
|
19
|
+
}), te = (e) => {
|
|
20
20
|
if (e !== void 0) return e === "true";
|
|
21
|
-
}, D = (e, t) => e[
|
|
21
|
+
}, D = (e, t) => e[S + t], O = (e) => {
|
|
22
22
|
let t = {};
|
|
23
23
|
for (let n in e) Object.prototype.hasOwnProperty.call(e, n) && e[n] !== void 0 && (t[n] = e[n]);
|
|
24
24
|
return t;
|
|
25
25
|
}, k = (e) => ({
|
|
26
26
|
str: (t) => D(e, t),
|
|
27
27
|
strOr: (t, n) => D(e, t) ?? n,
|
|
28
|
-
bool: (t) =>
|
|
29
|
-
json: (t) =>
|
|
28
|
+
bool: (t) => te(D(e, t)),
|
|
29
|
+
json: (t) => T(D(e, t))
|
|
30
30
|
}), A = () => {
|
|
31
31
|
let e = {}, t = {
|
|
32
|
-
str: (n, r) => (r !== void 0 && (e[
|
|
33
|
-
bool: (n, r) => (r !== void 0 && (e[
|
|
34
|
-
json: (n, r) => (r != null && (e[
|
|
32
|
+
str: (n, r) => (r !== void 0 && (e[S + n] = r), t),
|
|
33
|
+
bool: (n, r) => (r !== void 0 && (e[S + n] = String(r)), t),
|
|
34
|
+
json: (n, r) => (r != null && (e[S + n] = JSON.stringify(r)), t),
|
|
35
35
|
build: () => e
|
|
36
36
|
};
|
|
37
37
|
return t;
|
|
38
38
|
}, j = (e) => {
|
|
39
39
|
let t = {
|
|
40
|
-
[
|
|
41
|
-
[
|
|
42
|
-
[
|
|
40
|
+
[c]: e.role,
|
|
41
|
+
[a]: e.turnId,
|
|
42
|
+
[o]: e.msgId
|
|
43
43
|
};
|
|
44
|
-
return e.turnClientId !== void 0 && (t[
|
|
45
|
-
}, M = async (e, t, n, r, i) => {
|
|
46
|
-
|
|
47
|
-
let
|
|
44
|
+
return e.turnClientId !== void 0 && (t[s] = e.turnClientId), e.parent && (t[m] = e.parent), e.forkOf && (t[h] = e.forkOf), e.amend && (t[l] = e.amend), t;
|
|
45
|
+
}, M = async (e, t, n, r, i, a) => {
|
|
46
|
+
a?.trace("pipeStream();");
|
|
47
|
+
let o = e.getReader(), s, c = n ? new Promise((e) => {
|
|
48
48
|
if (n.aborted) {
|
|
49
49
|
e();
|
|
50
50
|
return;
|
|
51
51
|
}
|
|
52
|
-
|
|
52
|
+
s = () => {
|
|
53
53
|
e();
|
|
54
|
-
}, n.addEventListener("abort",
|
|
55
|
-
}) : new Promise(() => {}),
|
|
54
|
+
}, n.addEventListener("abort", s, { once: !0 });
|
|
55
|
+
}) : new Promise(() => {}), l = "complete", u;
|
|
56
56
|
try {
|
|
57
57
|
for (;;) {
|
|
58
|
-
let e = await Promise.race([
|
|
58
|
+
let e = await Promise.race([o.read(), c.then(() => "aborted")]);
|
|
59
59
|
if (e === "aborted") {
|
|
60
|
-
|
|
60
|
+
l = "cancelled", a?.debug("pipeStream(); stream cancelled by abort signal"), r && await r(async (e) => t.appendEvent(e)), await t.abort("cancelled");
|
|
61
61
|
break;
|
|
62
62
|
}
|
|
63
|
-
let { done: n, value:
|
|
63
|
+
let { done: n, value: s } = e;
|
|
64
64
|
if (n) {
|
|
65
|
-
await t.close(),
|
|
65
|
+
await t.close(), a?.debug("pipeStream(); stream completed");
|
|
66
66
|
break;
|
|
67
67
|
}
|
|
68
|
-
await t.appendEvent(
|
|
68
|
+
await t.appendEvent(s, i?.(s));
|
|
69
69
|
}
|
|
70
70
|
} catch (e) {
|
|
71
|
-
|
|
72
|
-
let n = e instanceof Error ? e.message : String(e);
|
|
73
|
-
i?.error("pipeStream(); stream error", { error: n });
|
|
71
|
+
l = "error", u = e instanceof Error ? e : Error(String(e)), a?.error("pipeStream(); stream error", { error: u.message });
|
|
74
72
|
try {
|
|
75
73
|
await t.close();
|
|
76
74
|
} catch {}
|
|
77
75
|
} finally {
|
|
78
|
-
|
|
76
|
+
s && n?.removeEventListener("abort", s), o.releaseLock();
|
|
79
77
|
}
|
|
80
|
-
return {
|
|
81
|
-
|
|
78
|
+
return {
|
|
79
|
+
reason: l,
|
|
80
|
+
error: u
|
|
81
|
+
};
|
|
82
|
+
}, ne = class {
|
|
82
83
|
constructor(e, t) {
|
|
83
84
|
this._activeTurns = /* @__PURE__ */ new Map(), this._channel = e, this._logger = t?.withContext({ component: "TurnManager" });
|
|
84
85
|
}
|
|
85
|
-
async startTurn(e, t, n) {
|
|
86
|
+
async startTurn(e, t, n, r) {
|
|
86
87
|
this._logger?.trace("DefaultTurnManager.startTurn();", {
|
|
87
88
|
turnId: e,
|
|
88
89
|
clientId: t
|
|
89
90
|
});
|
|
90
|
-
let
|
|
91
|
-
|
|
92
|
-
controller:
|
|
93
|
-
clientId:
|
|
94
|
-
})
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
91
|
+
let i = n ?? new AbortController(), o = t ?? "";
|
|
92
|
+
this._activeTurns.set(e, {
|
|
93
|
+
controller: i,
|
|
94
|
+
clientId: o
|
|
95
|
+
});
|
|
96
|
+
let c = {
|
|
97
|
+
[a]: e,
|
|
98
|
+
[s]: o
|
|
99
|
+
};
|
|
100
|
+
return r?.parent !== void 0 && (c[m] = r.parent), r?.forkOf !== void 0 && (c[h] = r.forkOf), await this._channel.publish({
|
|
101
|
+
name: v,
|
|
102
|
+
extras: { headers: c }
|
|
103
|
+
}), this._logger?.debug("DefaultTurnManager.startTurn(); turn started", { turnId: e }), i.signal;
|
|
101
104
|
}
|
|
102
105
|
async endTurn(e, t) {
|
|
103
106
|
this._logger?.trace("DefaultTurnManager.endTurn();", {
|
|
@@ -106,11 +109,11 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
106
109
|
});
|
|
107
110
|
let n = this._activeTurns.get(e)?.clientId ?? "";
|
|
108
111
|
await this._channel.publish({
|
|
109
|
-
name:
|
|
112
|
+
name: y,
|
|
110
113
|
extras: { headers: {
|
|
111
|
-
[
|
|
112
|
-
[
|
|
113
|
-
[
|
|
114
|
+
[a]: e,
|
|
115
|
+
[s]: n,
|
|
116
|
+
[g]: t
|
|
114
117
|
} }
|
|
115
118
|
}), this._activeTurns.delete(e), this._logger?.debug("DefaultTurnManager.endTurn(); turn ended", {
|
|
116
119
|
turnId: e,
|
|
@@ -134,30 +137,38 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
134
137
|
for (let e of this._activeTurns.values()) e.controller.abort();
|
|
135
138
|
this._activeTurns.clear();
|
|
136
139
|
}
|
|
137
|
-
},
|
|
140
|
+
}, re = (e, t) => new ne(e, t), N = /* @__PURE__ */ function(e) {
|
|
141
|
+
return e.READY = "ready", e.CLOSED = "closed", e;
|
|
142
|
+
}(N || {}), P = /* @__PURE__ */ function(e) {
|
|
143
|
+
return e.INITIALIZED = "initialized", e.STARTED = "started", e.ENDED = "ended", e;
|
|
144
|
+
}(P || {}), ie = class {
|
|
138
145
|
constructor(t) {
|
|
139
|
-
this._registeredTurns = /* @__PURE__ */ new Map(), this._channel = t.channel, this._codec = t.codec, this._logger = t.logger?.withContext({ component: "ServerTransport" }), this._onError = t.onError, this._turnManager =
|
|
146
|
+
this._registeredTurns = /* @__PURE__ */ new Map(), this._state = N.READY, this._channel = t.channel, this._codec = t.codec, this._logger = t.logger?.withContext({ component: "ServerTransport" }), this._onError = t.onError, this._turnManager = re(this._channel, this._logger), this._channelListener = (e) => {
|
|
140
147
|
this._handleChannelMessage(e);
|
|
141
|
-
}, this._attachPromise = this._channel.subscribe(
|
|
142
|
-
let n = new e.ErrorInfo(`unable to subscribe to cancel messages; ${t instanceof Error ? t.message : String(t)}`,
|
|
148
|
+
}, this._attachPromise = this._channel.subscribe(_, this._channelListener).then(() => {}, (t) => {
|
|
149
|
+
let n = new e.ErrorInfo(`unable to subscribe to cancel messages; ${t instanceof Error ? t.message : String(t)}`, C.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
143
150
|
this._logger?.error("DefaultServerTransport(); subscribe failed"), this._onError?.(n);
|
|
144
|
-
}), this.
|
|
151
|
+
}), this._hasAttachedOnce = this._channel.state === "attached", this._onChannelStateChange = (e) => {
|
|
152
|
+
this._handleChannelStateChange(e);
|
|
153
|
+
}, this._channel.on(this._onChannelStateChange), this._logger?.debug("DefaultServerTransport(); transport created");
|
|
145
154
|
}
|
|
146
155
|
newTurn(e) {
|
|
147
156
|
return this._logger?.trace("DefaultServerTransport.newTurn();", { turnId: e.turnId }), this._createTurn(e);
|
|
148
157
|
}
|
|
149
158
|
close() {
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
159
|
+
if (this._state !== N.CLOSED) {
|
|
160
|
+
this._state = N.CLOSED, this._logger?.trace("DefaultServerTransport.close();"), this._channel.unsubscribe(_, this._channelListener), this._channel.off(this._onChannelStateChange);
|
|
161
|
+
for (let e of this._registeredTurns.values()) e.controller.abort();
|
|
162
|
+
this._registeredTurns.clear(), this._turnManager.close(), this._logger?.debug("DefaultServerTransport.close(); transport closed");
|
|
163
|
+
}
|
|
153
164
|
}
|
|
154
165
|
_resolveFilter(e, t) {
|
|
155
166
|
let n = [...this._registeredTurns.keys()];
|
|
156
167
|
return e.all ? n : e.own && t ? n.filter((e) => this._registeredTurns.get(e)?.clientId === t) : e.clientId ? n.filter((t) => this._registeredTurns.get(t)?.clientId === e.clientId) : e.turnId && this._registeredTurns.has(e.turnId) ? [e.turnId] : [];
|
|
157
168
|
}
|
|
158
169
|
async _handleCancelMessage(t) {
|
|
159
|
-
let n =
|
|
160
|
-
n["x-ably-cancel-turn-id"] ? r.turnId = n[
|
|
170
|
+
let n = w(t), r = {};
|
|
171
|
+
n["x-ably-cancel-turn-id"] ? r.turnId = n[u] : n["x-ably-cancel-own"] === "true" ? r.own = !0 : n["x-ably-cancel-client-id"] ? r.clientId = n[p] : n["x-ably-cancel-all"] === "true" && (r.all = !0);
|
|
161
172
|
let i = this._resolveFilter(r, t.clientId);
|
|
162
173
|
if (i.length === 0) return;
|
|
163
174
|
this._logger?.debug("DefaultServerTransport._handleCancelMessage(); matched turns", {
|
|
@@ -184,113 +195,174 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
184
195
|
}
|
|
185
196
|
n.controller.abort(), this._logger?.debug("DefaultServerTransport._handleCancelMessage(); turn aborted", { turnId: t });
|
|
186
197
|
} catch (r) {
|
|
187
|
-
let i = new e.ErrorInfo(`unable to process cancel for turn ${t}; onCancel handler threw: ${r instanceof Error ? r.message : String(r)}`,
|
|
198
|
+
let i = new e.ErrorInfo(`unable to process cancel for turn ${t}; onCancel handler threw: ${r instanceof Error ? r.message : String(r)}`, C.CancelListenerError, 500, r instanceof e.ErrorInfo ? r : void 0);
|
|
188
199
|
this._logger?.error("DefaultServerTransport._handleCancelMessage(); onCancel threw", { turnId: t }), (n.onError ?? this._onError)?.(i);
|
|
189
200
|
}
|
|
190
201
|
}
|
|
191
202
|
}
|
|
203
|
+
_handleChannelStateChange(t) {
|
|
204
|
+
if (this._state === N.CLOSED) return;
|
|
205
|
+
let { current: n, resumed: r } = t;
|
|
206
|
+
if (n === "attached" && !this._hasAttachedOnce) {
|
|
207
|
+
this._hasAttachedOnce = !0;
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
|
|
211
|
+
this._logger?.error("DefaultServerTransport._handleChannelStateChange(); channel continuity lost", {
|
|
212
|
+
current: n,
|
|
213
|
+
resumed: r,
|
|
214
|
+
previous: t.previous
|
|
215
|
+
});
|
|
216
|
+
let i = new e.ErrorInfo(`unable to deliver cancel messages; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, C.ChannelContinuityLost, 500, t.reason);
|
|
217
|
+
this._onError?.(i);
|
|
218
|
+
}
|
|
192
219
|
_handleChannelMessage(t) {
|
|
193
220
|
try {
|
|
194
221
|
t.name === "x-ably-cancel" && this._handleCancelMessage(t).catch((t) => {
|
|
195
|
-
let n = new e.ErrorInfo(`unable to route cancel message; ${t instanceof Error ? t.message : String(t)}`,
|
|
222
|
+
let n = new e.ErrorInfo(`unable to route cancel message; ${t instanceof Error ? t.message : String(t)}`, C.CancelListenerError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
196
223
|
this._logger?.error("DefaultServerTransport._handleChannelMessage(); cancel routing error"), this._onError?.(n);
|
|
197
224
|
});
|
|
198
225
|
} catch (t) {
|
|
199
|
-
let n = new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`,
|
|
226
|
+
let n = new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, C.TransportSubscriptionError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
200
227
|
this._logger?.error("DefaultServerTransport._handleChannelMessage(); subscription error"), this._onError?.(n);
|
|
201
228
|
}
|
|
202
229
|
}
|
|
203
230
|
_createTurn(t) {
|
|
204
|
-
let { turnId: n, clientId: r, onMessage: i, onAbort: a, onCancel: o, onError: s, parent: c, forkOf: l } = t,
|
|
231
|
+
let { turnId: n, clientId: r, onMessage: i, onAbort: a, onCancel: o, onError: s, parent: c, forkOf: l, signal: u } = t, d = new AbortController(), f = P.INITIALIZED, p = u ? AbortSignal.any([d.signal, u]) : d.signal, m = {
|
|
205
232
|
turnId: n,
|
|
206
233
|
clientId: r ?? "",
|
|
207
|
-
controller:
|
|
234
|
+
controller: d,
|
|
235
|
+
signal: p,
|
|
208
236
|
onCancel: o,
|
|
209
237
|
onError: s
|
|
210
238
|
};
|
|
211
|
-
this._registeredTurns.set(n,
|
|
212
|
-
let
|
|
239
|
+
this._registeredTurns.set(n, m);
|
|
240
|
+
let h = this._logger, g = this._turnManager, _ = this._attachPromise, v = this._codec, y = this._channel, b = this._registeredTurns;
|
|
213
241
|
return {
|
|
214
242
|
get turnId() {
|
|
215
243
|
return n;
|
|
216
244
|
},
|
|
217
245
|
get abortSignal() {
|
|
218
|
-
return
|
|
246
|
+
return p;
|
|
219
247
|
},
|
|
220
248
|
start: async () => {
|
|
221
|
-
if (
|
|
222
|
-
if (
|
|
223
|
-
|
|
249
|
+
if (h?.trace("Turn.start();", { turnId: n }), p.aborted) throw new e.ErrorInfo(`unable to start turn; turn ${n} was cancelled before start()`, C.InvalidArgument, 400);
|
|
250
|
+
if (f === P.INITIALIZED) {
|
|
251
|
+
f = P.STARTED;
|
|
224
252
|
try {
|
|
225
|
-
await
|
|
253
|
+
await g.startTurn(n, r, d, {
|
|
254
|
+
parent: c,
|
|
255
|
+
forkOf: l
|
|
256
|
+
});
|
|
226
257
|
} catch (t) {
|
|
227
|
-
let r = new e.ErrorInfo(`unable to publish turn-start for turn ${n}; ${t instanceof Error ? t.message : String(t)}`,
|
|
228
|
-
throw
|
|
258
|
+
let r = new e.ErrorInfo(`unable to publish turn-start for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, C.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
259
|
+
throw h?.error("Turn.start(); failed to publish turn-start", { turnId: n }), r;
|
|
229
260
|
}
|
|
230
|
-
|
|
261
|
+
h?.debug("Turn.start(); turn started", { turnId: n });
|
|
231
262
|
}
|
|
232
263
|
},
|
|
233
264
|
addMessages: async (t, r) => {
|
|
234
|
-
if (
|
|
265
|
+
if (h?.trace("Turn.addMessages();", {
|
|
235
266
|
turnId: n,
|
|
236
267
|
count: t.length
|
|
237
|
-
}),
|
|
238
|
-
await
|
|
268
|
+
}), f === P.INITIALIZED) throw new e.ErrorInfo(`unable to add messages; start() must be called before addMessages() (turn ${n})`, C.InvalidArgument, 400);
|
|
269
|
+
await _;
|
|
239
270
|
let a = [];
|
|
240
|
-
|
|
241
|
-
let
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
271
|
+
try {
|
|
272
|
+
for (let e of t) {
|
|
273
|
+
let t = E(j({
|
|
274
|
+
role: "user",
|
|
275
|
+
turnId: n,
|
|
276
|
+
msgId: e.msgId,
|
|
277
|
+
turnClientId: r?.clientId,
|
|
278
|
+
parent: e.parentId ?? c,
|
|
279
|
+
forkOf: e.forkOf ?? l
|
|
280
|
+
}), e.headers);
|
|
281
|
+
await v.createEncoder(y, {
|
|
282
|
+
extras: { headers: t },
|
|
283
|
+
onMessage: i
|
|
284
|
+
}).writeMessages([e.message], r?.clientId ? { clientId: r.clientId } : void 0), a.push(e.msgId);
|
|
285
|
+
}
|
|
286
|
+
} catch (t) {
|
|
287
|
+
let r = new e.ErrorInfo(`unable to publish messages for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, C.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
288
|
+
throw h?.error("Turn.addMessages(); publish failed", { turnId: n }), r;
|
|
253
289
|
}
|
|
254
|
-
return
|
|
290
|
+
return h?.debug("Turn.addMessages(); messages published", {
|
|
255
291
|
turnId: n,
|
|
256
292
|
count: t.length
|
|
257
293
|
}), { msgIds: a };
|
|
258
294
|
},
|
|
295
|
+
addEvents: async (t) => {
|
|
296
|
+
if (h?.trace("Turn.addEvents();", {
|
|
297
|
+
turnId: n,
|
|
298
|
+
count: t.length
|
|
299
|
+
}), f === P.INITIALIZED) throw new e.ErrorInfo(`unable to add events; start() must be called before addEvents() (turn ${n})`, C.InvalidArgument, 400);
|
|
300
|
+
await _;
|
|
301
|
+
let r = g.getClientId(n);
|
|
302
|
+
try {
|
|
303
|
+
for (let e of t) {
|
|
304
|
+
let t = j({
|
|
305
|
+
role: "assistant",
|
|
306
|
+
turnId: n,
|
|
307
|
+
msgId: e.msgId,
|
|
308
|
+
turnClientId: r,
|
|
309
|
+
amend: e.msgId
|
|
310
|
+
}), a = v.createEncoder(y, {
|
|
311
|
+
extras: { headers: t },
|
|
312
|
+
onMessage: i
|
|
313
|
+
});
|
|
314
|
+
for (let t of e.events) await a.writeEvent(t);
|
|
315
|
+
await a.close();
|
|
316
|
+
}
|
|
317
|
+
} catch (t) {
|
|
318
|
+
let r = new e.ErrorInfo(`unable to publish events for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, C.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
319
|
+
throw h?.error("Turn.addEvents(); publish failed", { turnId: n }), r;
|
|
320
|
+
}
|
|
321
|
+
h?.debug("Turn.addEvents(); events published", {
|
|
322
|
+
turnId: n,
|
|
323
|
+
count: t.length
|
|
324
|
+
});
|
|
325
|
+
},
|
|
259
326
|
streamResponse: async (t, r) => {
|
|
260
|
-
if (
|
|
261
|
-
await
|
|
262
|
-
let o =
|
|
327
|
+
if (h?.trace("Turn.streamResponse();", { turnId: n }), f === P.INITIALIZED) throw new e.ErrorInfo(`unable to stream response; start() must be called before streamResponse() (turn ${n})`, C.InvalidArgument, 400);
|
|
328
|
+
await _;
|
|
329
|
+
let o = g.getClientId(n), u = r?.parent === void 0 ? c : r.parent, d = crypto.randomUUID(), m = j({
|
|
263
330
|
role: "assistant",
|
|
264
331
|
turnId: n,
|
|
265
|
-
msgId:
|
|
266
|
-
turnClientId:
|
|
332
|
+
msgId: d,
|
|
333
|
+
turnClientId: o,
|
|
267
334
|
parent: u,
|
|
268
335
|
forkOf: r?.forkOf ?? l
|
|
269
|
-
}),
|
|
270
|
-
extras: { headers:
|
|
271
|
-
onMessage: i
|
|
272
|
-
|
|
273
|
-
|
|
336
|
+
}), b = await M(t, v.createEncoder(y, {
|
|
337
|
+
extras: { headers: m },
|
|
338
|
+
onMessage: i,
|
|
339
|
+
messageId: d
|
|
340
|
+
}), p, a, r?.resolveWriteOptions, h);
|
|
341
|
+
if (b.error) {
|
|
342
|
+
let t = new e.ErrorInfo(`unable to stream response for turn ${n}; ${b.error.message}`, C.StreamError, 500, b.error instanceof e.ErrorInfo ? b.error : void 0);
|
|
343
|
+
h?.error("Turn.streamResponse(); stream error", { turnId: n }), s?.(t);
|
|
344
|
+
}
|
|
345
|
+
return h?.debug("Turn.streamResponse(); stream finished", {
|
|
274
346
|
turnId: n,
|
|
275
|
-
reason:
|
|
276
|
-
}),
|
|
347
|
+
reason: b.reason
|
|
348
|
+
}), b;
|
|
277
349
|
},
|
|
278
350
|
end: async (t) => {
|
|
279
|
-
if (
|
|
351
|
+
if (h?.trace("Turn.end();", {
|
|
280
352
|
turnId: n,
|
|
281
353
|
reason: t
|
|
282
|
-
}),
|
|
283
|
-
if (
|
|
284
|
-
f =
|
|
354
|
+
}), f === P.INITIALIZED) throw new e.ErrorInfo(`unable to end turn; start() must be called before end() (turn ${n})`, C.InvalidArgument, 400);
|
|
355
|
+
if (f !== P.ENDED) {
|
|
356
|
+
f = P.ENDED;
|
|
285
357
|
try {
|
|
286
|
-
await
|
|
358
|
+
await g.endTurn(n, t);
|
|
287
359
|
} catch (t) {
|
|
288
|
-
let r = new e.ErrorInfo(`unable to publish turn-end for turn ${n}; ${t instanceof Error ? t.message : String(t)}`,
|
|
289
|
-
throw
|
|
360
|
+
let r = new e.ErrorInfo(`unable to publish turn-end for turn ${n}; ${t instanceof Error ? t.message : String(t)}`, C.TurnLifecycleError, 500, t instanceof e.ErrorInfo ? t : void 0);
|
|
361
|
+
throw h?.error("Turn.end(); failed to publish turn-end", { turnId: n }), r;
|
|
290
362
|
} finally {
|
|
291
|
-
|
|
363
|
+
b.delete(n);
|
|
292
364
|
}
|
|
293
|
-
|
|
365
|
+
h?.debug("Turn.end(); turn ended", {
|
|
294
366
|
turnId: n,
|
|
295
367
|
reason: t
|
|
296
368
|
});
|
|
@@ -298,68 +370,68 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
298
370
|
}
|
|
299
371
|
};
|
|
300
372
|
}
|
|
301
|
-
},
|
|
373
|
+
}, ae = (e) => new ie(e), F = (e) => ({
|
|
302
374
|
logAction: (t, n, r) => {
|
|
303
375
|
e.error(n, { detail: r });
|
|
304
376
|
},
|
|
305
377
|
shouldLog: () => !0
|
|
306
|
-
}),
|
|
378
|
+
}), I = e.Realtime.EventEmitter, L = class extends I {
|
|
307
379
|
constructor(e) {
|
|
308
|
-
super(
|
|
380
|
+
super(F(e));
|
|
309
381
|
}
|
|
310
|
-
},
|
|
382
|
+
}, R = /* @__PURE__ */ function(e) {
|
|
311
383
|
return e.Trace = "trace", e.Debug = "debug", e.Info = "info", e.Warn = "warn", e.Error = "error", e.Silent = "silent", e;
|
|
312
|
-
}({}),
|
|
384
|
+
}({}), z = (e, t, n) => {
|
|
313
385
|
let r = n ? `, context: ${JSON.stringify(n)}` : "", i = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${t.valueOf().toUpperCase()} ably-ai-transport: ${e}${r}`;
|
|
314
386
|
switch (t) {
|
|
315
|
-
case
|
|
316
|
-
case
|
|
387
|
+
case R.Trace:
|
|
388
|
+
case R.Debug:
|
|
317
389
|
console.log(i);
|
|
318
390
|
break;
|
|
319
|
-
case
|
|
391
|
+
case R.Info:
|
|
320
392
|
console.info(i);
|
|
321
393
|
break;
|
|
322
|
-
case
|
|
394
|
+
case R.Warn:
|
|
323
395
|
console.warn(i);
|
|
324
396
|
break;
|
|
325
|
-
case
|
|
397
|
+
case R.Error:
|
|
326
398
|
console.error(i);
|
|
327
399
|
break;
|
|
328
|
-
case
|
|
400
|
+
case R.Silent: break;
|
|
329
401
|
}
|
|
330
|
-
},
|
|
402
|
+
}, B = (e) => new U(e.logHandler ?? z, e.logLevel), V = /* @__PURE__ */ function(e) {
|
|
331
403
|
return e[e.Trace = 0] = "Trace", e[e.Debug = 1] = "Debug", e[e.Info = 2] = "Info", e[e.Warn = 3] = "Warn", e[e.Error = 4] = "Error", e[e.Silent = 5] = "Silent", e;
|
|
332
|
-
}(
|
|
333
|
-
[
|
|
334
|
-
[
|
|
335
|
-
[
|
|
336
|
-
[
|
|
337
|
-
[
|
|
338
|
-
[
|
|
339
|
-
]),
|
|
404
|
+
}(V || {}), H = new Map([
|
|
405
|
+
[R.Trace, V.Trace],
|
|
406
|
+
[R.Debug, V.Debug],
|
|
407
|
+
[R.Info, V.Info],
|
|
408
|
+
[R.Warn, V.Warn],
|
|
409
|
+
[R.Error, V.Error],
|
|
410
|
+
[R.Silent, V.Silent]
|
|
411
|
+
]), U = class t {
|
|
340
412
|
constructor(t, n, r) {
|
|
341
413
|
this._handler = t, this._context = r;
|
|
342
|
-
let i =
|
|
343
|
-
if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`,
|
|
414
|
+
let i = H.get(n);
|
|
415
|
+
if (i === void 0) throw new e.ErrorInfo(`unable to create logger; invalid log level: ${n}`, C.InvalidArgument, 400);
|
|
344
416
|
this._levelNumber = i;
|
|
345
417
|
}
|
|
346
418
|
trace(e, t) {
|
|
347
|
-
this._write(e,
|
|
419
|
+
this._write(e, R.Trace, V.Trace, t);
|
|
348
420
|
}
|
|
349
421
|
debug(e, t) {
|
|
350
|
-
this._write(e,
|
|
422
|
+
this._write(e, R.Debug, V.Debug, t);
|
|
351
423
|
}
|
|
352
424
|
info(e, t) {
|
|
353
|
-
this._write(e,
|
|
425
|
+
this._write(e, R.Info, V.Info, t);
|
|
354
426
|
}
|
|
355
427
|
warn(e, t) {
|
|
356
|
-
this._write(e,
|
|
428
|
+
this._write(e, R.Warn, V.Warn, t);
|
|
357
429
|
}
|
|
358
430
|
error(e, t) {
|
|
359
|
-
this._write(e,
|
|
431
|
+
this._write(e, R.Error, V.Error, t);
|
|
360
432
|
}
|
|
361
433
|
withContext(e) {
|
|
362
|
-
let n = [...
|
|
434
|
+
let n = [...H.entries()].find(([, e]) => e === this._levelNumber)?.[0] ?? R.Error;
|
|
363
435
|
return new t(this._handler, n, this._mergeContext(e));
|
|
364
436
|
}
|
|
365
437
|
_write(e, t, n, r) {
|
|
@@ -371,9 +443,58 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
371
443
|
...e
|
|
372
444
|
} : this._context : e ?? void 0;
|
|
373
445
|
}
|
|
374
|
-
},
|
|
446
|
+
}, W = class {
|
|
375
447
|
constructor(e, t) {
|
|
376
|
-
this.
|
|
448
|
+
this._turns = /* @__PURE__ */ new Map(), this._isTerminal = e, this._logger = t;
|
|
449
|
+
}
|
|
450
|
+
createStream(t) {
|
|
451
|
+
this._logger.trace("StreamRouter.createStream();", { turnId: t });
|
|
452
|
+
let n = {}, r = new ReadableStream({ start(e) {
|
|
453
|
+
n.controller = e;
|
|
454
|
+
} });
|
|
455
|
+
if (!n.controller) throw new e.ErrorInfo("unable to create stream; ReadableStream start() was not called synchronously", C.TransportSubscriptionError, 500);
|
|
456
|
+
return this._turns.set(t, {
|
|
457
|
+
controller: n.controller,
|
|
458
|
+
turnId: t
|
|
459
|
+
}), r;
|
|
460
|
+
}
|
|
461
|
+
closeStream(e) {
|
|
462
|
+
let t = this._turns.get(e);
|
|
463
|
+
if (!t) return !1;
|
|
464
|
+
this._logger.debug("StreamRouter.closeStream(); closing stream", { turnId: e });
|
|
465
|
+
try {
|
|
466
|
+
t.controller.close();
|
|
467
|
+
} catch {}
|
|
468
|
+
return this._turns.delete(e), !0;
|
|
469
|
+
}
|
|
470
|
+
errorStream(e, t) {
|
|
471
|
+
let n = this._turns.get(e);
|
|
472
|
+
if (!n) return !1;
|
|
473
|
+
this._logger.debug("StreamRouter.errorStream(); erroring stream", { turnId: e });
|
|
474
|
+
try {
|
|
475
|
+
n.controller.error(t);
|
|
476
|
+
} catch {}
|
|
477
|
+
return this._turns.delete(e), !0;
|
|
478
|
+
}
|
|
479
|
+
route(e, t) {
|
|
480
|
+
let n = this._turns.get(e);
|
|
481
|
+
if (!n) return !1;
|
|
482
|
+
try {
|
|
483
|
+
n.controller.enqueue(t);
|
|
484
|
+
} catch {
|
|
485
|
+
return this._turns.delete(e), !1;
|
|
486
|
+
}
|
|
487
|
+
return this._isTerminal(t) && this.closeStream(e), !0;
|
|
488
|
+
}
|
|
489
|
+
has(e) {
|
|
490
|
+
return this._turns.has(e);
|
|
491
|
+
}
|
|
492
|
+
}, G = (e, t) => new W(e, t), K = class {
|
|
493
|
+
get structuralVersion() {
|
|
494
|
+
return this._structuralVersion;
|
|
495
|
+
}
|
|
496
|
+
constructor(e) {
|
|
497
|
+
this._nodeIndex = /* @__PURE__ */ new Map(), this._sortedList = [], this._parentIndex = /* @__PURE__ */ new Map(), this._turnClientIds = /* @__PURE__ */ new Map(), this._seqCounter = 0, this._structuralVersion = 0, this._logger = e, this._emitter = new L(e);
|
|
377
498
|
}
|
|
378
499
|
_compareNodes(e, t) {
|
|
379
500
|
let n = e.node.serial, r = t.node.serial;
|
|
@@ -432,7 +553,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
432
553
|
}
|
|
433
554
|
return !1;
|
|
434
555
|
}
|
|
435
|
-
|
|
556
|
+
getGroupRoot(e) {
|
|
436
557
|
let t = this._nodeIndex.get(e);
|
|
437
558
|
if (!t) return e;
|
|
438
559
|
let n = t.node, r = new Set([n.msgId]);
|
|
@@ -443,75 +564,63 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
443
564
|
}
|
|
444
565
|
return n.msgId;
|
|
445
566
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
567
|
+
flattenNodes(e) {
|
|
568
|
+
this._logger.trace("DefaultTree.flattenNodes();");
|
|
569
|
+
let t = [], n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Map();
|
|
570
|
+
for (let i of this._sortedList) {
|
|
571
|
+
let a = i.node, { msgId: o, parentId: s } = a;
|
|
572
|
+
if (s !== void 0 && !n.has(s)) continue;
|
|
573
|
+
let c = this._getSiblingGroup(o);
|
|
574
|
+
if (c.length > 1) {
|
|
575
|
+
let t = this.getGroupRoot(o), n = r.get(t);
|
|
576
|
+
if (n === void 0) {
|
|
577
|
+
let i = e.get(t);
|
|
578
|
+
if (i && c.some((e) => e.msgId === i)) n = i;
|
|
579
|
+
else {
|
|
580
|
+
let e = c.at(-1);
|
|
581
|
+
if (!e) break;
|
|
582
|
+
n = e.msgId;
|
|
583
|
+
}
|
|
584
|
+
r.set(t, n);
|
|
458
585
|
}
|
|
459
|
-
if (
|
|
586
|
+
if (o !== n) continue;
|
|
460
587
|
}
|
|
461
|
-
|
|
588
|
+
n.add(o), t.push(a);
|
|
462
589
|
}
|
|
463
|
-
return
|
|
590
|
+
return t;
|
|
464
591
|
}
|
|
465
592
|
getSiblings(e) {
|
|
466
|
-
return this._getSiblingGroup(e).map((e) => e.message);
|
|
593
|
+
return this._logger.trace("DefaultTree.getSiblings();", { msgId: e }), this._getSiblingGroup(e).map((e) => e.message);
|
|
594
|
+
}
|
|
595
|
+
getSiblingNodes(e) {
|
|
596
|
+
return this._getSiblingGroup(e);
|
|
467
597
|
}
|
|
468
598
|
hasSiblings(e) {
|
|
469
599
|
return this._getSiblingGroup(e).length > 1;
|
|
470
600
|
}
|
|
471
|
-
getSelectedIndex(e) {
|
|
472
|
-
let t = this._getSiblingGroup(e);
|
|
473
|
-
if (t.length <= 1) return 0;
|
|
474
|
-
let n = this._getGroupRoot(e), r = this._selections.get(n);
|
|
475
|
-
return r === void 0 ? t.length - 1 : Math.max(0, Math.min(r, t.length - 1));
|
|
476
|
-
}
|
|
477
|
-
select(e, t) {
|
|
478
|
-
this._logger.debug("ConversationTree.select();", {
|
|
479
|
-
msgId: e,
|
|
480
|
-
index: t
|
|
481
|
-
});
|
|
482
|
-
let n = this._getSiblingGroup(e);
|
|
483
|
-
if (n.length <= 1) return;
|
|
484
|
-
let r = this._getGroupRoot(e);
|
|
485
|
-
this._selections.set(r, Math.max(0, Math.min(t, n.length - 1)));
|
|
486
|
-
}
|
|
487
601
|
getNode(e) {
|
|
488
|
-
return this._nodeIndex.get(e)?.node;
|
|
489
|
-
}
|
|
490
|
-
getNodeByKey(e) {
|
|
491
|
-
let t = this._codecKeyIndex.get(e);
|
|
492
|
-
if (t) return this._nodeIndex.get(t)?.node;
|
|
602
|
+
return this._logger.trace("DefaultTree.getNode();", { msgId: e }), this._nodeIndex.get(e)?.node;
|
|
493
603
|
}
|
|
494
604
|
getHeaders(e) {
|
|
495
|
-
return this._nodeIndex.get(e)?.node.headers;
|
|
605
|
+
return this._logger.trace("DefaultTree.getHeaders();", { msgId: e }), this._nodeIndex.get(e)?.node.headers;
|
|
496
606
|
}
|
|
497
607
|
upsert(e, t, n, r) {
|
|
498
|
-
let i = n["x-ably-parent"] ?? void 0, a = n["x-ably-fork-of"] ?? void 0;
|
|
499
|
-
this._codecKeyIndex.set(this._getKey(t), e);
|
|
500
|
-
let o = this._nodeIndex.get(e);
|
|
608
|
+
let i = n["x-ably-parent"] ?? void 0, a = n["x-ably-fork-of"] ?? void 0, o = this._nodeIndex.get(e);
|
|
501
609
|
if (o) {
|
|
502
|
-
o.node.message = t, Object.keys(n).length > 0 && (o.node.headers = { ...n }), r && !o.node.serial && (this._logger.debug("
|
|
610
|
+
o.node.message = t, Object.keys(n).length > 0 && (o.node.headers = { ...n }), r && !o.node.serial && (this._logger.debug("Tree.upsert(); promoting serial", {
|
|
503
611
|
msgId: e,
|
|
504
612
|
serial: r
|
|
505
|
-
}), o.node.serial = r, this._removeSorted(o), this._insertSorted(o));
|
|
613
|
+
}), o.node.serial = r, this._removeSorted(o), this._insertSorted(o), this._structuralVersion++), this._emitter.emit("update");
|
|
506
614
|
return;
|
|
507
615
|
}
|
|
508
|
-
this._logger.trace("
|
|
616
|
+
this._logger.trace("Tree.upsert(); inserting new node", {
|
|
509
617
|
msgId: e,
|
|
510
618
|
parentId: i,
|
|
511
619
|
forkOf: a
|
|
512
620
|
});
|
|
513
621
|
let s = {
|
|
514
622
|
node: {
|
|
623
|
+
kind: "message",
|
|
515
624
|
message: t,
|
|
516
625
|
msgId: e,
|
|
517
626
|
parentId: i,
|
|
@@ -521,217 +630,580 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
521
630
|
},
|
|
522
631
|
insertSeq: this._seqCounter++
|
|
523
632
|
};
|
|
524
|
-
this._nodeIndex.set(e, s), this._addToParentIndex(i, e), this._insertSorted(s);
|
|
633
|
+
this._nodeIndex.set(e, s), this._addToParentIndex(i, e), this._insertSorted(s), this._structuralVersion++, this._emitter.emit("update");
|
|
525
634
|
}
|
|
526
635
|
delete(e) {
|
|
527
636
|
let t = this._nodeIndex.get(e);
|
|
528
637
|
if (!t) return;
|
|
529
|
-
this._logger.debug("
|
|
530
|
-
let { node: n } = t
|
|
531
|
-
this.
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
638
|
+
this._logger.debug("Tree.delete();", { msgId: e });
|
|
639
|
+
let { node: n } = t;
|
|
640
|
+
this._removeFromParentIndex(n.parentId, e), this._removeSorted(t), this._nodeIndex.delete(e), this._structuralVersion++, this._emitter.emit("update");
|
|
641
|
+
}
|
|
642
|
+
getActiveTurnIds() {
|
|
643
|
+
this._logger.trace("DefaultTree.getActiveTurnIds();");
|
|
644
|
+
let e = /* @__PURE__ */ new Map();
|
|
645
|
+
for (let [t, n] of this._turnClientIds) {
|
|
646
|
+
let r = e.get(n);
|
|
647
|
+
r || (r = /* @__PURE__ */ new Set(), e.set(n, r)), r.add(t);
|
|
648
|
+
}
|
|
649
|
+
return e;
|
|
650
|
+
}
|
|
651
|
+
on(e, t) {
|
|
652
|
+
let n = t;
|
|
653
|
+
return this._emitter.on(e, n), () => {
|
|
654
|
+
this._emitter.off(e, n);
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
emitAblyMessage(e) {
|
|
658
|
+
this._logger.trace("DefaultTree.emitAblyMessage();"), this._emitter.emit("ably-message", e);
|
|
659
|
+
}
|
|
660
|
+
emitTurn(e) {
|
|
661
|
+
this._logger.trace("DefaultTree.emitTurn();", { turnId: e.turnId }), this._emitter.emit("turn", e);
|
|
662
|
+
}
|
|
663
|
+
trackTurn(e, t) {
|
|
664
|
+
this._logger.trace("DefaultTree.trackTurn();", {
|
|
665
|
+
turnId: e,
|
|
666
|
+
clientId: t
|
|
667
|
+
}), this._turnClientIds.set(e, t);
|
|
668
|
+
}
|
|
669
|
+
untrackTurn(e) {
|
|
670
|
+
this._logger.trace("DefaultTree.untrackTurn();", { turnId: e }), this._turnClientIds.delete(e);
|
|
671
|
+
}
|
|
672
|
+
}, q = (e) => new K(e), oe = (e) => {
|
|
673
|
+
let t = [...e.rawMessages].toReversed(), n = e.codec.createDecoder(), r = /* @__PURE__ */ new Map(), i = e.codec.createAccumulator(), s = 0, c = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), d = [], f = [];
|
|
674
|
+
for (let p of t) {
|
|
675
|
+
let t = n.decode(p), m = w(p), h = m[a], g = m[o], _ = p.serial, v = m[l];
|
|
676
|
+
if (v) {
|
|
677
|
+
for (let e of r.values()) if (e.msgHeaders.has(v)) {
|
|
678
|
+
let n = [...e.msgHeaders.keys()].indexOf(v), r = n === -1 ? void 0 : e.accumulator.messages[n];
|
|
679
|
+
r && e.accumulator.initMessage(v, r), e.accumulator.processOutputs(t), f.push({
|
|
680
|
+
accumulator: e.accumulator,
|
|
681
|
+
messageId: v
|
|
682
|
+
});
|
|
683
|
+
break;
|
|
684
|
+
}
|
|
685
|
+
continue;
|
|
686
|
+
}
|
|
687
|
+
if (h) {
|
|
688
|
+
let n = r.get(h);
|
|
539
689
|
if (n || (n = {
|
|
540
690
|
accumulator: e.codec.createAccumulator(),
|
|
541
691
|
firstSeen: s++,
|
|
542
692
|
msgHeaders: /* @__PURE__ */ new Map(),
|
|
543
693
|
msgSerials: /* @__PURE__ */ new Map()
|
|
544
|
-
}, r.set(
|
|
545
|
-
let e = n.msgHeaders.get(
|
|
546
|
-
e ? Object.keys(
|
|
694
|
+
}, r.set(h, n)), g) {
|
|
695
|
+
let e = n.msgHeaders.get(g);
|
|
696
|
+
e ? Object.keys(m).length > 0 && Object.assign(e, m) : (n.msgHeaders.set(g, { ...m }), _ && n.msgSerials.set(g, _));
|
|
547
697
|
}
|
|
548
698
|
n.accumulator.processOutputs(t);
|
|
549
|
-
} else
|
|
550
|
-
|
|
551
|
-
let t
|
|
552
|
-
|
|
699
|
+
} else {
|
|
700
|
+
i.processOutputs(t);
|
|
701
|
+
for (let e of t) if (e.kind === "message" && g) {
|
|
702
|
+
d.push(g);
|
|
703
|
+
let e = c.get(g);
|
|
704
|
+
e ? Object.keys(m).length > 0 && Object.assign(e, m) : (c.set(g, { ...m }), _ && u.set(g, _));
|
|
705
|
+
}
|
|
553
706
|
}
|
|
554
707
|
}
|
|
555
|
-
let
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
708
|
+
for (let { accumulator: e, messageId: t } of f) e.completeMessage(t);
|
|
709
|
+
let p = [];
|
|
710
|
+
for (let [e, t] of i.completedMessages.entries()) {
|
|
711
|
+
let n = d[e];
|
|
712
|
+
p.push({
|
|
559
713
|
message: t,
|
|
560
|
-
headers: c.get(n) ?? {},
|
|
561
|
-
serial:
|
|
714
|
+
headers: n ? c.get(n) ?? {} : {},
|
|
715
|
+
serial: n ? u.get(n) ?? "" : ""
|
|
562
716
|
});
|
|
563
717
|
}
|
|
564
|
-
let
|
|
565
|
-
for (let
|
|
566
|
-
let
|
|
567
|
-
for (let
|
|
568
|
-
let
|
|
569
|
-
if (
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
if (!r.has(a) && c) {
|
|
581
|
-
let [e, n] = c;
|
|
582
|
-
r.set(a, n);
|
|
583
|
-
let o = t.msgSerials.get(e);
|
|
584
|
-
o && i.set(a, o), s++;
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
for (let n of t.accumulator.completedMessages) {
|
|
588
|
-
let t = e.getMessageKey(n);
|
|
589
|
-
u.push({
|
|
590
|
-
message: n,
|
|
591
|
-
headers: r.get(t) ?? {},
|
|
592
|
-
serial: i.get(t) ?? ""
|
|
718
|
+
let m = [...r.values()].toSorted((e, t) => e.firstSeen - t.firstSeen);
|
|
719
|
+
for (let e of m) {
|
|
720
|
+
let t = [...e.msgHeaders.entries()], n = 0;
|
|
721
|
+
for (let r of e.accumulator.completedMessages) {
|
|
722
|
+
let i = t[n];
|
|
723
|
+
if (i) {
|
|
724
|
+
let [t, a] = i;
|
|
725
|
+
p.push({
|
|
726
|
+
message: r,
|
|
727
|
+
headers: a,
|
|
728
|
+
serial: e.msgSerials.get(t) ?? ""
|
|
729
|
+
}), n++;
|
|
730
|
+
} else p.push({
|
|
731
|
+
message: r,
|
|
732
|
+
headers: {},
|
|
733
|
+
serial: ""
|
|
593
734
|
});
|
|
594
735
|
}
|
|
595
736
|
}
|
|
596
|
-
return
|
|
597
|
-
},
|
|
598
|
-
e.rawMessages.
|
|
599
|
-
let
|
|
600
|
-
|
|
737
|
+
return p.toReversed();
|
|
738
|
+
}, se = (e) => {
|
|
739
|
+
if (e.cachedDecode && e.cachedAtRawLength === e.rawMessages.length) return e.cachedDecode;
|
|
740
|
+
let t = oe(e);
|
|
741
|
+
return e.cachedDecode = t, e.cachedAtRawLength = e.rawMessages.length, t;
|
|
742
|
+
}, J = (e, t) => {
|
|
743
|
+
for (let r of t) {
|
|
744
|
+
let t = w(r), i = t[o];
|
|
745
|
+
if (!i || t["x-ably-amend"]) continue;
|
|
746
|
+
let a = r.action, s = a === "message.create" && "x-ably-discrete" in t, c = t["x-ably-stream"] === "true" && (a === "message.create" || a === "message.update" || a === "message.append"), l = t[n], u = l === "finished" || l === "aborted";
|
|
747
|
+
(s || c) && e.startedMsgIds.add(i), (s || u) && e.terminatedMsgIds.add(i), e.startedMsgIds.has(i) && e.terminatedMsgIds.has(i) && e.completedMsgIds.add(i);
|
|
748
|
+
}
|
|
749
|
+
}, Y = async (e, t, n) => {
|
|
750
|
+
e.rawMessages.push(...t.items), e.lastAblyPage = t, J(e, t.items);
|
|
751
|
+
let r = e.returnedCount + n;
|
|
752
|
+
for (; e.completedMsgIds.size < r && t.hasNext();) {
|
|
601
753
|
e.logger.debug("decodeHistory.fetchUntilLimit(); fetching next page", {
|
|
602
754
|
collected: e.rawMessages.length,
|
|
603
|
-
|
|
755
|
+
completed: e.completedMsgIds.size
|
|
604
756
|
});
|
|
605
757
|
let n = await t.next();
|
|
606
758
|
if (!n) break;
|
|
607
|
-
t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n,
|
|
759
|
+
t = n, e.rawMessages.push(...n.items), e.lastAblyPage = n, J(e, n.items);
|
|
608
760
|
}
|
|
609
|
-
},
|
|
610
|
-
let n =
|
|
761
|
+
}, X = (e, t) => {
|
|
762
|
+
let n = se(e), r = n.slice(e.returnedCount, e.returnedCount + t), i = [...r].toReversed();
|
|
611
763
|
e.returnedCount += r.length;
|
|
612
764
|
let a = n.length > e.returnedCount, o = e.lastAblyPage?.hasNext() ?? !1, s = e.rawMessages.length - e.returnedRawCount > 0 ? e.rawMessages.slice(e.returnedRawCount).toReversed() : [];
|
|
613
765
|
return e.returnedRawCount = e.rawMessages.length, {
|
|
614
|
-
items: i.map((e) =>
|
|
615
|
-
|
|
616
|
-
|
|
766
|
+
items: i.map((e) => ({
|
|
767
|
+
message: e.message,
|
|
768
|
+
headers: e.headers,
|
|
769
|
+
serial: e.serial
|
|
770
|
+
})),
|
|
617
771
|
rawMessages: s,
|
|
618
772
|
hasNext: () => a || o,
|
|
619
773
|
next: async () => {
|
|
620
|
-
if (a) return
|
|
774
|
+
if (a) return X(e, t);
|
|
621
775
|
if (!o || !e.lastAblyPage) return;
|
|
622
776
|
let n = await e.lastAblyPage.next();
|
|
623
|
-
if (n) return await
|
|
777
|
+
if (n) return await Y(e, n, t), X(e, t);
|
|
624
778
|
}
|
|
625
779
|
};
|
|
626
|
-
},
|
|
780
|
+
}, ce = async (e, t, n, r) => {
|
|
627
781
|
let i = n?.limit ?? 100, a = {
|
|
628
782
|
codec: t,
|
|
629
783
|
rawMessages: [],
|
|
630
784
|
returnedCount: 0,
|
|
631
785
|
returnedRawCount: 0,
|
|
632
786
|
lastAblyPage: void 0,
|
|
633
|
-
|
|
787
|
+
cachedDecode: void 0,
|
|
788
|
+
cachedAtRawLength: 0,
|
|
789
|
+
startedMsgIds: /* @__PURE__ */ new Set(),
|
|
790
|
+
terminatedMsgIds: /* @__PURE__ */ new Set(),
|
|
791
|
+
completedMsgIds: /* @__PURE__ */ new Set(),
|
|
634
792
|
logger: r
|
|
635
793
|
};
|
|
636
794
|
r.trace("decodeHistory();", { limit: i });
|
|
637
795
|
let o = i * 10;
|
|
638
|
-
return await e.attach(), await
|
|
796
|
+
return await e.attach(), await Y(a, await e.history({
|
|
639
797
|
untilAttach: !0,
|
|
640
798
|
limit: o
|
|
641
|
-
}), i),
|
|
642
|
-
},
|
|
643
|
-
constructor(e
|
|
644
|
-
this.
|
|
799
|
+
}), i), X(a, i);
|
|
800
|
+
}, le = class {
|
|
801
|
+
constructor(e) {
|
|
802
|
+
this._branchSelections = /* @__PURE__ */ new Map(), this._withheldMsgIds = /* @__PURE__ */ new Set(), this._lastVisibleIds = [], this._lastVisibleMessages = [], this._lastVisibleTurnIds = /* @__PURE__ */ new Set(), this._hasMoreHistory = !1, this._withheldBuffer = [], this._unsubs = [], this._cachedNodes = [], this._lastStructuralVersion = -1, this._loadingOlder = !1, this._processingHistory = !1, this._closed = !1, this._tree = e.tree, this._channel = e.channel, this._codec = e.codec, this._sendDelegate = e.sendDelegate, this._onClose = e.onClose, this._logger = e.logger.withContext({ component: "View" }), this._logger.trace("DefaultView();"), this._emitter = new L(this._logger), this._cachedNodes = this._computeFlatNodes(), this._lastStructuralVersion = this._tree.structuralVersion, this._updateVisibleSnapshot(this._cachedNodes), this._unsubs.push(this._tree.on("update", () => {
|
|
803
|
+
this._onTreeUpdate();
|
|
804
|
+
}), this._tree.on("ably-message", (e) => {
|
|
805
|
+
this._onTreeAblyMessage(e);
|
|
806
|
+
}), this._tree.on("turn", (e) => {
|
|
807
|
+
this._onTreeTurn(e);
|
|
808
|
+
}));
|
|
645
809
|
}
|
|
646
|
-
|
|
647
|
-
this.
|
|
648
|
-
let n = {}, r = new ReadableStream({ start(e) {
|
|
649
|
-
n.controller = e;
|
|
650
|
-
} });
|
|
651
|
-
if (!n.controller) throw new e.ErrorInfo("unable to create stream; ReadableStream start() was not called synchronously", x.TransportSubscriptionError, 500);
|
|
652
|
-
return this._turns.set(t, {
|
|
653
|
-
controller: n.controller,
|
|
654
|
-
turnId: t
|
|
655
|
-
}), r;
|
|
810
|
+
getMessages() {
|
|
811
|
+
return this.flattenNodes().map((e) => e.message);
|
|
656
812
|
}
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
if (!t) return !1;
|
|
660
|
-
this._logger.debug("StreamRouter.closeStream(); closing stream", { turnId: e });
|
|
661
|
-
try {
|
|
662
|
-
t.controller.close();
|
|
663
|
-
} catch {}
|
|
664
|
-
return this._turns.delete(e), !0;
|
|
813
|
+
flattenNodes() {
|
|
814
|
+
return this._cachedNodes;
|
|
665
815
|
}
|
|
666
|
-
|
|
667
|
-
let
|
|
668
|
-
|
|
816
|
+
_computeFlatNodes() {
|
|
817
|
+
let e = this._tree.flattenNodes(this._resolveSelections());
|
|
818
|
+
return this._withheldMsgIds.size === 0 ? e : e.filter((e) => !this._withheldMsgIds.has(e.msgId));
|
|
819
|
+
}
|
|
820
|
+
hasOlder() {
|
|
821
|
+
return this._withheldBuffer.length > 0 || this._hasMoreHistory;
|
|
822
|
+
}
|
|
823
|
+
async loadOlder(e = 100) {
|
|
824
|
+
if (!(this._closed || this._loadingOlder)) {
|
|
825
|
+
this._loadingOlder = !0, this._logger.trace("DefaultView.loadOlder();", { limit: e });
|
|
826
|
+
try {
|
|
827
|
+
if (this._withheldBuffer.length > 0) {
|
|
828
|
+
let t = this._withheldBuffer.splice(-e, e);
|
|
829
|
+
this._releaseWithheld(t);
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
if (!this._hasMoreHistory && !this._lastHistoryPage) {
|
|
833
|
+
await this._loadFirstPage(e);
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
if (!this._hasMoreHistory) return;
|
|
837
|
+
if (!this._lastHistoryPage?.hasNext()) {
|
|
838
|
+
this._hasMoreHistory = !1;
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
let t = await this._lastHistoryPage.next();
|
|
842
|
+
if (this._closed || !t) {
|
|
843
|
+
t || (this._hasMoreHistory = !1);
|
|
844
|
+
return;
|
|
845
|
+
}
|
|
846
|
+
await this._loadAndReveal(t, e);
|
|
847
|
+
} catch (e) {
|
|
848
|
+
throw this._logger.error("DefaultView.loadOlder(); failed", { error: e }), e;
|
|
849
|
+
} finally {
|
|
850
|
+
this._loadingOlder = !1;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
select(e, t) {
|
|
855
|
+
this._logger.trace("DefaultView.select();", {
|
|
856
|
+
msgId: e,
|
|
857
|
+
index: t
|
|
858
|
+
});
|
|
859
|
+
let n = this._tree.getSiblingNodes(e);
|
|
860
|
+
if (n.length <= 1) return;
|
|
861
|
+
let r = this._tree.getGroupRoot(e), i = Math.max(0, Math.min(t, n.length - 1)), a = n[i];
|
|
862
|
+
a && (this._branchSelections.set(r, {
|
|
863
|
+
kind: "user",
|
|
864
|
+
selectedId: a.msgId
|
|
865
|
+
}), this._logger.debug("DefaultView.select();", {
|
|
866
|
+
msgId: e,
|
|
867
|
+
index: i,
|
|
868
|
+
selectedId: a.msgId
|
|
869
|
+
}), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update"));
|
|
870
|
+
}
|
|
871
|
+
getSelectedIndex(e) {
|
|
872
|
+
this._logger.trace("DefaultView.getSelectedIndex();", { msgId: e });
|
|
873
|
+
let t = this._tree.getSiblingNodes(e);
|
|
874
|
+
if (t.length <= 1) return 0;
|
|
875
|
+
let n = this._tree.getGroupRoot(e), r = this._branchSelections.get(n);
|
|
876
|
+
if (!r || r.kind === "pending") return t.length - 1;
|
|
877
|
+
let i = t.findIndex((e) => e.msgId === r.selectedId);
|
|
878
|
+
return i === -1 ? t.length - 1 : i;
|
|
879
|
+
}
|
|
880
|
+
getSiblings(e) {
|
|
881
|
+
return this._tree.getSiblings(e);
|
|
882
|
+
}
|
|
883
|
+
hasSiblings(e) {
|
|
884
|
+
return this._tree.hasSiblings(e);
|
|
885
|
+
}
|
|
886
|
+
getNode(e) {
|
|
887
|
+
return this._tree.getNode(e);
|
|
888
|
+
}
|
|
889
|
+
async send(t, n) {
|
|
890
|
+
if (this._logger.trace("DefaultView.send();"), this._closed) throw new e.ErrorInfo("unable to send; view is closed", C.InvalidArgument, 400);
|
|
891
|
+
let r = this.flattenNodes(), i = await this._sendDelegate(t, n, r);
|
|
892
|
+
if (n?.forkOf) {
|
|
893
|
+
let e = this._tree.getGroupRoot(n.forkOf);
|
|
894
|
+
if (i.optimisticMsgIds.length > 0) {
|
|
895
|
+
let t = i.optimisticMsgIds.at(-1);
|
|
896
|
+
t && (this._branchSelections.set(e, {
|
|
897
|
+
kind: "auto",
|
|
898
|
+
selectedId: t
|
|
899
|
+
}), this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update"));
|
|
900
|
+
} else {
|
|
901
|
+
this._branchSelections.set(e, {
|
|
902
|
+
kind: "pending",
|
|
903
|
+
turnId: i.turnId
|
|
904
|
+
}), this._logger.debug("DefaultView.send(); deferring fork auto-selection", {
|
|
905
|
+
forkOf: n.forkOf,
|
|
906
|
+
groupRoot: e,
|
|
907
|
+
turnId: i.turnId
|
|
908
|
+
});
|
|
909
|
+
let t = this._tree.on("turn", (n) => {
|
|
910
|
+
if (n.type !== "x-ably-turn-end" || n.turnId !== i.turnId) return;
|
|
911
|
+
let r = this._branchSelections.get(e);
|
|
912
|
+
r?.kind === "pending" && r.turnId === i.turnId && this._branchSelections.delete(e), t();
|
|
913
|
+
let a = this._unsubs.indexOf(t);
|
|
914
|
+
a !== -1 && this._unsubs.splice(a, 1);
|
|
915
|
+
});
|
|
916
|
+
this._unsubs.push(t);
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
return i;
|
|
920
|
+
}
|
|
921
|
+
async regenerate(t, n) {
|
|
922
|
+
this._logger.trace("DefaultView.regenerate();", { messageId: t });
|
|
923
|
+
let r = this._tree.getNode(t);
|
|
924
|
+
if (!r) throw new e.ErrorInfo(`unable to regenerate; message not found in tree: ${t}`, C.InvalidArgument, 400);
|
|
925
|
+
let i = r.parentId;
|
|
926
|
+
return this.send([], {
|
|
927
|
+
...n,
|
|
928
|
+
body: {
|
|
929
|
+
history: this._getHistoryBefore(t),
|
|
930
|
+
...n?.body
|
|
931
|
+
},
|
|
932
|
+
forkOf: t,
|
|
933
|
+
parent: i
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
async edit(t, n, r) {
|
|
937
|
+
this._logger.trace("DefaultView.edit();", { messageId: t });
|
|
938
|
+
let i = this._tree.getNode(t);
|
|
939
|
+
if (!i) throw new e.ErrorInfo(`unable to edit; message not found in tree: ${t}`, C.InvalidArgument, 400);
|
|
940
|
+
let a = i.parentId;
|
|
941
|
+
return this.send(n, {
|
|
942
|
+
...r,
|
|
943
|
+
body: {
|
|
944
|
+
history: this._getHistoryBefore(t),
|
|
945
|
+
...r?.body
|
|
946
|
+
},
|
|
947
|
+
forkOf: t,
|
|
948
|
+
parent: a
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
async update(t, n, r) {
|
|
952
|
+
if (this._closed) throw new e.ErrorInfo("unable to update; view is closed", C.InvalidArgument, 400);
|
|
953
|
+
this._logger.trace("DefaultView.update();", {
|
|
954
|
+
msgId: t,
|
|
955
|
+
eventCount: n.length
|
|
956
|
+
});
|
|
957
|
+
let i = [{
|
|
958
|
+
kind: "event",
|
|
959
|
+
msgId: t,
|
|
960
|
+
events: n
|
|
961
|
+
}];
|
|
962
|
+
return this._sendDelegate([], r, this.flattenNodes(), i);
|
|
963
|
+
}
|
|
964
|
+
_getHistoryBefore(e) {
|
|
965
|
+
this._logger.trace("DefaultView._getHistoryBefore();", { messageId: e });
|
|
966
|
+
let t = this.flattenNodes(), n = t.findIndex((t) => t.msgId === e);
|
|
967
|
+
return n === -1 ? (this._logger.warn("DefaultView._getHistoryBefore(); target not in visible nodes, returning full list", { messageId: e }), t) : t.slice(0, n);
|
|
968
|
+
}
|
|
969
|
+
getActiveTurnIds() {
|
|
970
|
+
this._logger.trace("DefaultView.getActiveTurnIds();");
|
|
971
|
+
let e = this._tree.getActiveTurnIds();
|
|
972
|
+
if (this._withheldMsgIds.size === 0) return e;
|
|
973
|
+
let t = /* @__PURE__ */ new Map();
|
|
974
|
+
for (let [n, r] of e) {
|
|
975
|
+
let e = /* @__PURE__ */ new Set();
|
|
976
|
+
for (let t of r) this._lastVisibleTurnIds.has(t) && e.add(t);
|
|
977
|
+
e.size > 0 && t.set(n, e);
|
|
978
|
+
}
|
|
979
|
+
return t;
|
|
980
|
+
}
|
|
981
|
+
on(e, t) {
|
|
982
|
+
let n = t;
|
|
983
|
+
return this._emitter.on(e, n), () => {
|
|
984
|
+
this._emitter.off(e, n);
|
|
985
|
+
};
|
|
986
|
+
}
|
|
987
|
+
close() {
|
|
988
|
+
this._logger.info("DefaultView.close();"), this._closed = !0, this._loadingOlder = !1;
|
|
989
|
+
for (let e of this._unsubs) e();
|
|
990
|
+
this._unsubs.length = 0, this._emitter.off(), this._branchSelections.clear(), this._withheldMsgIds.clear(), this._withheldBuffer.length = 0, this._onClose?.();
|
|
991
|
+
}
|
|
992
|
+
async _loadFirstPage(e) {
|
|
993
|
+
let t = new Set(this._tree.flattenNodes(this._resolveSelections()).map((e) => e.msgId)), n = await ce(this._channel, this._codec, { limit: e }, this._logger);
|
|
994
|
+
if (this._closed) return;
|
|
995
|
+
let { newVisible: r, lastPage: i } = await this._loadUntilVisible(n, e, t);
|
|
996
|
+
if (this._closed) return;
|
|
997
|
+
this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext();
|
|
998
|
+
let a = r.slice(-e), o = r.slice(0, -e);
|
|
999
|
+
for (let e of o) this._withheldMsgIds.add(e.msgId);
|
|
1000
|
+
this._withheldBuffer.push(...o), this._releaseWithheld(a);
|
|
1001
|
+
}
|
|
1002
|
+
async _loadAndReveal(e, t) {
|
|
1003
|
+
let n = new Set(this._tree.flattenNodes(this._resolveSelections()).map((e) => e.msgId)), { newVisible: r, lastPage: i } = await this._loadUntilVisible(e, t, n);
|
|
1004
|
+
if (this._closed) return;
|
|
1005
|
+
this._lastHistoryPage = i, this._hasMoreHistory = i.hasNext();
|
|
1006
|
+
let a = r.slice(-t), o = r.slice(0, -t);
|
|
1007
|
+
for (let e of o) this._withheldMsgIds.add(e.msgId);
|
|
1008
|
+
this._withheldBuffer.push(...o), this._releaseWithheld(a);
|
|
1009
|
+
}
|
|
1010
|
+
_processHistoryPage(e) {
|
|
1011
|
+
this._processingHistory = !0;
|
|
669
1012
|
try {
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
1013
|
+
for (let t of e.items) {
|
|
1014
|
+
let e = t.headers[o];
|
|
1015
|
+
e && this._tree.upsert(e, t.message, t.headers, t.serial);
|
|
1016
|
+
}
|
|
1017
|
+
for (let t of e.rawMessages) this._tree.emitAblyMessage(t);
|
|
1018
|
+
} finally {
|
|
1019
|
+
this._processingHistory = !1;
|
|
673
1020
|
}
|
|
674
|
-
return this._isTerminal(t) && this.closeStream(e), !0;
|
|
675
1021
|
}
|
|
676
|
-
|
|
677
|
-
|
|
1022
|
+
async _loadUntilVisible(e, t, n) {
|
|
1023
|
+
this._processHistoryPage(e);
|
|
1024
|
+
let r = e, i = () => {
|
|
1025
|
+
let e = 0;
|
|
1026
|
+
for (let t of this._tree.flattenNodes(this._resolveSelections())) n.has(t.msgId) || e++;
|
|
1027
|
+
return e;
|
|
1028
|
+
};
|
|
1029
|
+
for (; i() < t && r.hasNext();) {
|
|
1030
|
+
let e = await r.next();
|
|
1031
|
+
if (!e || this._closed) break;
|
|
1032
|
+
this._processHistoryPage(e), r = e;
|
|
1033
|
+
}
|
|
1034
|
+
return {
|
|
1035
|
+
newVisible: this._tree.flattenNodes(this._resolveSelections()).filter((e) => !n.has(e.msgId)),
|
|
1036
|
+
lastPage: r
|
|
1037
|
+
};
|
|
1038
|
+
}
|
|
1039
|
+
_releaseWithheld(e) {
|
|
1040
|
+
for (let t of e) this._withheldMsgIds.delete(t.msgId);
|
|
1041
|
+
e.length > 0 && (this._cachedNodes = this._computeFlatNodes(), this._updateVisibleSnapshot(this._cachedNodes), this._emitter.emit("update"));
|
|
1042
|
+
}
|
|
1043
|
+
_updateVisibleSnapshot(e) {
|
|
1044
|
+
let t = e ?? this.flattenNodes();
|
|
1045
|
+
this._lastVisibleIds = t.map((e) => e.msgId), this._lastVisibleMessages = t.map((e) => e.message), this._lastVisibleTurnIds = /* @__PURE__ */ new Set();
|
|
1046
|
+
for (let e of t) {
|
|
1047
|
+
let t = e.headers[a];
|
|
1048
|
+
t && this._lastVisibleTurnIds.add(t);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
_onTreeUpdate() {
|
|
1052
|
+
if (this._processingHistory) return;
|
|
1053
|
+
let e = this._tree.structuralVersion;
|
|
1054
|
+
if (e === this._lastStructuralVersion) {
|
|
1055
|
+
this._cachedNodes.some((e, t) => e.message !== this._lastVisibleMessages[t]) && (this._lastVisibleMessages = this._cachedNodes.map((e) => e.message), this._cachedNodes = [...this._cachedNodes], this._emitter.emit("update"));
|
|
1056
|
+
return;
|
|
1057
|
+
}
|
|
1058
|
+
this._lastStructuralVersion = e, this._pinBranchSelections(), this._resolvePendingSelections();
|
|
1059
|
+
let t = this._computeFlatNodes(), n = t.map((e) => e.msgId), r = t.map((e) => e.message);
|
|
1060
|
+
this._visibleChanged(n, r) && (this._cachedNodes = t, this._updateVisibleSnapshot(t), this._emitter.emit("update"));
|
|
1061
|
+
}
|
|
1062
|
+
_resolveSelections() {
|
|
1063
|
+
let e = /* @__PURE__ */ new Map();
|
|
1064
|
+
for (let [t, n] of this._branchSelections) n.kind !== "pending" && e.set(t, n.selectedId);
|
|
1065
|
+
return e;
|
|
1066
|
+
}
|
|
1067
|
+
_pinBranchSelections() {
|
|
1068
|
+
for (let e of this._lastVisibleIds) {
|
|
1069
|
+
if (!this._tree.hasSiblings(e)) continue;
|
|
1070
|
+
let t = this._tree.getGroupRoot(e), n = this._branchSelections.get(t);
|
|
1071
|
+
if (n?.kind === "pending") {
|
|
1072
|
+
let r = this._tree.getSiblingNodes(e).at(-1);
|
|
1073
|
+
r && r.msgId !== e && r.headers["x-ably-turn-id"] === n.turnId && (this._logger.debug("DefaultView._pinBranchSelections(); auto-selecting pending fork", {
|
|
1074
|
+
msgId: e,
|
|
1075
|
+
newestId: r.msgId,
|
|
1076
|
+
turnId: n.turnId
|
|
1077
|
+
}), this._branchSelections.set(t, {
|
|
1078
|
+
kind: "auto",
|
|
1079
|
+
selectedId: r.msgId
|
|
1080
|
+
}));
|
|
1081
|
+
continue;
|
|
1082
|
+
}
|
|
1083
|
+
n || this._branchSelections.set(t, {
|
|
1084
|
+
kind: "pinned",
|
|
1085
|
+
selectedId: e
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
_resolvePendingSelections() {
|
|
1090
|
+
for (let [e, t] of this._branchSelections) {
|
|
1091
|
+
if (t.kind !== "pending") continue;
|
|
1092
|
+
let n = this._tree.getSiblingNodes(e);
|
|
1093
|
+
if (n.length <= 1) continue;
|
|
1094
|
+
let r = n.at(-1);
|
|
1095
|
+
!r || r.msgId === e || r.headers["x-ably-turn-id"] === t.turnId && (this._logger.debug("DefaultView._resolvePendingSelections(); resolving off-branch pending", {
|
|
1096
|
+
groupRoot: e,
|
|
1097
|
+
newestId: r.msgId,
|
|
1098
|
+
turnId: t.turnId
|
|
1099
|
+
}), this._branchSelections.set(e, {
|
|
1100
|
+
kind: "auto",
|
|
1101
|
+
selectedId: r.msgId
|
|
1102
|
+
}));
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
_onTreeAblyMessage(e) {
|
|
1106
|
+
let t = w(e)[o];
|
|
1107
|
+
if (!t) {
|
|
1108
|
+
this._emitter.emit("ably-message", e);
|
|
1109
|
+
return;
|
|
1110
|
+
}
|
|
1111
|
+
this._lastVisibleIds.includes(t) && this._emitter.emit("ably-message", e);
|
|
1112
|
+
}
|
|
1113
|
+
_onTreeTurn(e) {
|
|
1114
|
+
if (this._lastVisibleTurnIds.has(e.turnId)) {
|
|
1115
|
+
this._emitter.emit("turn", e);
|
|
1116
|
+
return;
|
|
1117
|
+
}
|
|
1118
|
+
e.type === "x-ably-turn-start" && this._isTurnStartVisible(e) && (this._lastVisibleTurnIds.add(e.turnId), this._emitter.emit("turn", e));
|
|
678
1119
|
}
|
|
679
|
-
|
|
1120
|
+
_isTurnStartVisible(e) {
|
|
1121
|
+
let { parent: t } = e;
|
|
1122
|
+
return t === void 0 ? !0 : this._lastVisibleIds.includes(t);
|
|
1123
|
+
}
|
|
1124
|
+
_visibleChanged(e, t) {
|
|
1125
|
+
if (e.length !== this._lastVisibleIds.length) return !0;
|
|
1126
|
+
for (let [t, n] of e.entries()) if (n !== this._lastVisibleIds[t]) return !0;
|
|
1127
|
+
for (let [e, n] of t.entries()) if (n !== this._lastVisibleMessages[e]) return !0;
|
|
1128
|
+
return !1;
|
|
1129
|
+
}
|
|
1130
|
+
}, Z = (e) => new le(e), ue = () => {}, Q = /* @__PURE__ */ function(e) {
|
|
1131
|
+
return e.READY = "ready", e.CLOSED = "closed", e;
|
|
1132
|
+
}(Q || {}), de = class {
|
|
680
1133
|
constructor(e) {
|
|
681
|
-
if (this._ownMsgIds = /* @__PURE__ */ new Set(), this._ownTurnIds = /* @__PURE__ */ new Set(), this.
|
|
1134
|
+
if (this._ownMsgIds = /* @__PURE__ */ new Set(), this._ownTurnIds = /* @__PURE__ */ new Set(), this._turnMsgIds = /* @__PURE__ */ new Map(), this._turnObservers = /* @__PURE__ */ new Map(), this._closeResolvers = [], this._views = /* @__PURE__ */ new Set(), this._state = Q.READY, this._pendingLocalEvents = [], this._channel = e.channel, this._codec = e.codec, this._clientId = e.clientId, this._api = e.api, this._credentials = e.credentials, this._headersFn = typeof e.headers == "function" ? e.headers : e.headers ? () => e.headers : void 0, this._bodyFn = typeof e.body == "function" ? e.body : e.body ? () => e.body : void 0, this._fetchFn = e.fetch ?? globalThis.fetch.bind(globalThis), this._logger = (e.logger ?? B({ logLevel: R.Silent })).withContext({ component: "ClientTransport" }), this._emitter = new L(this._logger), this._hasAttachedOnce = this._channel.state === "attached", this._tree = q(this._logger), this._view = Z({
|
|
1135
|
+
tree: this._tree,
|
|
1136
|
+
channel: this._channel,
|
|
1137
|
+
codec: this._codec,
|
|
1138
|
+
sendDelegate: this._internalSend.bind(this),
|
|
1139
|
+
logger: this._logger,
|
|
1140
|
+
onClose: () => this._views.delete(this._view)
|
|
1141
|
+
}), this._router = G(this._codec.isTerminal.bind(this._codec), this._logger), this._decoder = this._codec.createDecoder(), this._views.add(this._view), this.tree = this._tree, this.view = this._view, e.messages) {
|
|
682
1142
|
let t;
|
|
683
1143
|
for (let n of e.messages) {
|
|
684
|
-
let e =
|
|
685
|
-
t && (r[
|
|
1144
|
+
let e = crypto.randomUUID(), r = { [o]: e };
|
|
1145
|
+
t && (r[m] = t), this._tree.upsert(e, n, r), t = e;
|
|
686
1146
|
}
|
|
687
|
-
this._emitter.emit("message");
|
|
688
1147
|
}
|
|
689
1148
|
this._onMessage = (e) => {
|
|
690
1149
|
this._handleMessage(e);
|
|
691
|
-
}, this._attachPromise = this._channel.subscribe(this._onMessage)
|
|
1150
|
+
}, this._attachPromise = this._channel.subscribe(this._onMessage), this._onChannelStateChange = (e) => {
|
|
1151
|
+
this._handleChannelStateChange(e);
|
|
1152
|
+
}, this._channel.on(this._onChannelStateChange);
|
|
692
1153
|
}
|
|
693
1154
|
_handleMessage(t) {
|
|
694
|
-
if (
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
if (
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
1155
|
+
if (this._state !== Q.CLOSED) try {
|
|
1156
|
+
if (t.name === "x-ably-turn-start") {
|
|
1157
|
+
let e = w(t), n = e[a], r = e["x-ably-turn-client-id"] ?? "";
|
|
1158
|
+
if (n) {
|
|
1159
|
+
this._tree.trackTurn(n, r);
|
|
1160
|
+
let t = e[m], i = e[h];
|
|
1161
|
+
this._tree.emitTurn({
|
|
1162
|
+
type: v,
|
|
701
1163
|
turnId: n,
|
|
702
|
-
clientId: r
|
|
703
|
-
|
|
704
|
-
|
|
1164
|
+
clientId: r,
|
|
1165
|
+
...t !== void 0 && { parent: t },
|
|
1166
|
+
...i !== void 0 && { forkOf: i }
|
|
1167
|
+
});
|
|
705
1168
|
}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
turnId: n,
|
|
718
|
-
clientId: r,
|
|
719
|
-
reason: a
|
|
720
|
-
});
|
|
1169
|
+
this._tree.emitAblyMessage(t);
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
if (t.name === "x-ably-turn-end") {
|
|
1173
|
+
let e = w(t), n = e[a], r = e["x-ably-turn-client-id"] ?? "", i = e["x-ably-turn-reason"] ?? "complete";
|
|
1174
|
+
if (n) {
|
|
1175
|
+
this._router.closeStream(n), this._turnObservers.delete(n), this._tree.untrackTurn(n);
|
|
1176
|
+
let e = this._turnMsgIds.get(n);
|
|
1177
|
+
if (e) {
|
|
1178
|
+
for (let t of e) this._ownMsgIds.delete(t);
|
|
1179
|
+
this._turnMsgIds.delete(n);
|
|
721
1180
|
}
|
|
722
|
-
|
|
1181
|
+
this._ownTurnIds.delete(n), this._tree.emitTurn({
|
|
1182
|
+
type: y,
|
|
1183
|
+
turnId: n,
|
|
1184
|
+
clientId: r,
|
|
1185
|
+
reason: i
|
|
1186
|
+
});
|
|
723
1187
|
}
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
for (let i of e) i.kind === "message" ? this._handleMessageOutput(i.message, n, r, t.action) : this._handleEventOutput(i, n);
|
|
727
|
-
} catch (t) {
|
|
728
|
-
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
729
|
-
this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, x.TransportSubscriptionError, 500, n));
|
|
1188
|
+
this._tree.emitAblyMessage(t);
|
|
1189
|
+
return;
|
|
730
1190
|
}
|
|
1191
|
+
let e = this._decoder.decode(t), n = w(t), r = t.serial, i = n[l];
|
|
1192
|
+
if (i) {
|
|
1193
|
+
for (let t of e) t.kind === "event" && this._handleAmendmentEvent(i, t);
|
|
1194
|
+
return;
|
|
1195
|
+
}
|
|
1196
|
+
let o = n[a];
|
|
1197
|
+
o && this._updateTurnObserverHeaders(o, n, r);
|
|
1198
|
+
for (let i of e) i.kind === "message" ? this._handleMessageOutput(i.message, n, r, t.action) : this._handleEventOutput(i, n);
|
|
1199
|
+
this._tree.emitAblyMessage(t);
|
|
1200
|
+
} catch (t) {
|
|
1201
|
+
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
1202
|
+
this._emitter.emit("error", new e.ErrorInfo(`unable to process channel message; ${t instanceof Error ? t.message : String(t)}`, C.TransportSubscriptionError, 500, n));
|
|
731
1203
|
}
|
|
732
1204
|
}
|
|
733
1205
|
_handleMessageOutput(e, t, n, r) {
|
|
734
|
-
let i = t[
|
|
1206
|
+
let i = t[o];
|
|
735
1207
|
if (i && this._ownMsgIds.has(i)) {
|
|
736
1208
|
this._upsertAndNotify(e, t, n);
|
|
737
1209
|
return;
|
|
@@ -740,7 +1212,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
740
1212
|
}
|
|
741
1213
|
_handleEventOutput(e, t) {
|
|
742
1214
|
if (e.kind !== "event") return;
|
|
743
|
-
let n = e.event, r = t[
|
|
1215
|
+
let n = e.event, r = t[a];
|
|
744
1216
|
if (r) {
|
|
745
1217
|
if (this._router.route(r, n)) {
|
|
746
1218
|
this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r);
|
|
@@ -749,9 +1221,38 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
749
1221
|
this._ownTurnIds.has(r) && !this._turnObservers.has(r) || (this._accumulateAndEmit(r, e), this._codec.isTerminal(n) && this._turnObservers.delete(r));
|
|
750
1222
|
}
|
|
751
1223
|
}
|
|
1224
|
+
_handleAmendmentEvent(e, t) {
|
|
1225
|
+
this._logger.trace("ClientTransport._handleAmendmentEvent();", { targetMsgId: e });
|
|
1226
|
+
let n = this._tree.getNode(e);
|
|
1227
|
+
if (!n) {
|
|
1228
|
+
this._logger.debug("ClientTransport._handleAmendmentEvent(); target not found, dropping", { targetMsgId: e });
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
let r = this._codec.createAccumulator();
|
|
1232
|
+
r.initMessage(e, n.message), r.processOutputs([t]);
|
|
1233
|
+
let i = r.messages.at(-1);
|
|
1234
|
+
i && this._tree.upsert(e, i, n.headers, n.serial);
|
|
1235
|
+
}
|
|
1236
|
+
_handleChannelStateChange(t) {
|
|
1237
|
+
if (this._state === Q.CLOSED) return;
|
|
1238
|
+
let { current: n, resumed: r } = t;
|
|
1239
|
+
if (n === "attached" && !this._hasAttachedOnce) {
|
|
1240
|
+
this._hasAttachedOnce = !0;
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1243
|
+
if (!(n === "failed" || n === "suspended" || n === "detached" || n === "attached" && !r)) return;
|
|
1244
|
+
this._logger.error("ClientTransport._handleChannelStateChange(); channel continuity lost", {
|
|
1245
|
+
current: n,
|
|
1246
|
+
resumed: r,
|
|
1247
|
+
previous: t.previous
|
|
1248
|
+
});
|
|
1249
|
+
let i = new e.ErrorInfo(`unable to deliver events; channel continuity lost (${n}${n === "attached" ? ", resumed: false" : ""})`, C.ChannelContinuityLost, 500, t.reason);
|
|
1250
|
+
for (let e of this._ownTurnIds) this._router.errorStream(e, i);
|
|
1251
|
+
this._emitter.emit("error", i);
|
|
1252
|
+
}
|
|
752
1253
|
_upsertAndNotify(e, t, n) {
|
|
753
|
-
let r =
|
|
754
|
-
this._tree.upsert(
|
|
1254
|
+
let r = t[o];
|
|
1255
|
+
r && this._tree.upsert(r, e, t, n);
|
|
755
1256
|
}
|
|
756
1257
|
_updateTurnObserverHeaders(e, t, n) {
|
|
757
1258
|
let r = this._turnObservers.get(e);
|
|
@@ -764,269 +1265,234 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
764
1265
|
_accumulateAndEmit(e, t) {
|
|
765
1266
|
let n = this._turnObservers.get(e);
|
|
766
1267
|
if (!n) return;
|
|
1268
|
+
let r = n.headers[o];
|
|
1269
|
+
if (r) {
|
|
1270
|
+
let e = this._tree.getNode(r);
|
|
1271
|
+
e && n.accumulator.initMessage(r, e.message);
|
|
1272
|
+
}
|
|
767
1273
|
n.accumulator.processOutputs([t]);
|
|
768
|
-
let
|
|
769
|
-
if (
|
|
770
|
-
let
|
|
1274
|
+
let i = n.accumulator.messages;
|
|
1275
|
+
if (i.length === 0) return;
|
|
1276
|
+
let a;
|
|
771
1277
|
try {
|
|
772
|
-
|
|
1278
|
+
a = structuredClone(i.at(-1));
|
|
773
1279
|
} catch {
|
|
774
|
-
|
|
1280
|
+
a = i.at(-1);
|
|
1281
|
+
}
|
|
1282
|
+
if (a) {
|
|
1283
|
+
let e = n.headers[o];
|
|
1284
|
+
e && this._tree.upsert(e, a, { ...n.headers }, n.serial);
|
|
775
1285
|
}
|
|
776
|
-
i && (this._tree.upsert(n.headers["x-ably-msg-id"] ?? this._codec.getMessageKey(i), i, { ...n.headers }, n.serial), this._emitter.emit("message"));
|
|
777
1286
|
}
|
|
778
1287
|
async _publishCancel(e) {
|
|
779
1288
|
this._logger.trace("ClientTransport._publishCancel();", { filter: e });
|
|
780
1289
|
let t = {};
|
|
781
|
-
e.turnId ? t[
|
|
782
|
-
name:
|
|
1290
|
+
e.turnId ? t[u] = e.turnId : e.own ? t[d] = "true" : e.clientId ? t[p] = e.clientId : e.all && (t[f] = "true"), await this._channel.publish({
|
|
1291
|
+
name: _,
|
|
783
1292
|
extras: { headers: t }
|
|
784
1293
|
});
|
|
785
1294
|
}
|
|
786
1295
|
_closeMatchingTurnStreams(e) {
|
|
787
|
-
|
|
788
|
-
else if (e.own) for (let e of this._ownTurnIds) this._router.closeStream(e);
|
|
789
|
-
else if (e.clientId) for (let [t, n] of this._turnClientIds) n === e.clientId && this._router.closeStream(t);
|
|
790
|
-
else e.turnId && this._router.closeStream(e.turnId);
|
|
1296
|
+
for (let t of this._getMatchingTurnIds(e)) this._router.closeStream(t);
|
|
791
1297
|
}
|
|
792
1298
|
_getMatchingTurnIds(e) {
|
|
793
|
-
let t = /* @__PURE__ */ new Set();
|
|
794
|
-
if (e.all) for (let e of
|
|
795
|
-
else if (e.own)
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
_getHistoryBefore(e) {
|
|
807
|
-
let t = this._getMessagesWithHeaders(), n = t.findIndex((t) => t.headers?.[a] === e);
|
|
808
|
-
return n === -1 ? t : t.slice(0, n);
|
|
809
|
-
}
|
|
810
|
-
_processHistoryPage(e) {
|
|
811
|
-
for (let [t, n] of e.items.entries()) {
|
|
812
|
-
let r = e.itemHeaders?.[t] ?? {}, i = e.itemSerials?.[t], a = this._codec.getMessageKey(n), o = r["x-ably-msg-id"] ?? a;
|
|
813
|
-
this._tree.upsert(o, n, r, i);
|
|
814
|
-
}
|
|
815
|
-
this._emitter.emit("message"), e.rawMessages && e.rawMessages.length > 0 && (this._ablyMessages.unshift(...e.rawMessages), this._emitter.emit("ably-message"));
|
|
816
|
-
}
|
|
817
|
-
async _loadUntilVisible(e, t, n) {
|
|
818
|
-
this._processHistoryPage(e);
|
|
819
|
-
let r = e, i = () => {
|
|
820
|
-
let e = 0;
|
|
821
|
-
for (let t of this._tree.flatten()) n.has(this._codec.getMessageKey(t)) || e++;
|
|
822
|
-
return e;
|
|
823
|
-
};
|
|
824
|
-
for (; i() < t && r.hasNext();) {
|
|
825
|
-
let e = await r.next();
|
|
826
|
-
if (!e) break;
|
|
827
|
-
this._processHistoryPage(e), r = e;
|
|
1299
|
+
let t = /* @__PURE__ */ new Set(), n = this._tree.getActiveTurnIds();
|
|
1300
|
+
if (e.all) for (let e of n.values()) for (let n of e) t.add(n);
|
|
1301
|
+
else if (e.own) {
|
|
1302
|
+
let e = n.get(this._clientId ?? "");
|
|
1303
|
+
if (e) for (let n of e) t.add(n);
|
|
1304
|
+
} else if (e.clientId) {
|
|
1305
|
+
let r = n.get(e.clientId);
|
|
1306
|
+
if (r) for (let e of r) t.add(e);
|
|
1307
|
+
} else if (e.turnId) {
|
|
1308
|
+
for (let r of n.values()) if (r.has(e.turnId)) {
|
|
1309
|
+
t.add(e.turnId);
|
|
1310
|
+
break;
|
|
1311
|
+
}
|
|
828
1312
|
}
|
|
829
|
-
return
|
|
830
|
-
newVisible: this._tree.flatten().filter((e) => !n.has(this._codec.getMessageKey(e))),
|
|
831
|
-
lastPage: r
|
|
832
|
-
};
|
|
833
|
-
}
|
|
834
|
-
_releaseWithheld(e) {
|
|
835
|
-
for (let t of e) this._withheldKeys.delete(this._codec.getMessageKey(t));
|
|
836
|
-
e.length > 0 && this._emitter.emit("message");
|
|
1313
|
+
return t;
|
|
837
1314
|
}
|
|
838
|
-
|
|
839
|
-
if (this.
|
|
840
|
-
this._logger.trace("
|
|
841
|
-
let
|
|
842
|
-
|
|
843
|
-
|
|
1315
|
+
createView() {
|
|
1316
|
+
if (this._state === Q.CLOSED) throw new e.ErrorInfo("unable to create view; transport is closed", C.TransportClosed, 400);
|
|
1317
|
+
this._logger.trace("DefaultClientTransport.createView();");
|
|
1318
|
+
let t = Z({
|
|
1319
|
+
tree: this._tree,
|
|
1320
|
+
channel: this._channel,
|
|
1321
|
+
codec: this._codec,
|
|
1322
|
+
sendDelegate: this._internalSend.bind(this),
|
|
1323
|
+
logger: this._logger,
|
|
1324
|
+
onClose: () => this._views.delete(t)
|
|
1325
|
+
});
|
|
1326
|
+
return this._views.add(t), t;
|
|
1327
|
+
}
|
|
1328
|
+
async _internalSend(t, n, r, i) {
|
|
1329
|
+
if (this._state === Q.CLOSED || (await this._attachPromise, this._state === Q.CLOSED)) throw new e.ErrorInfo("unable to send; transport is closed", C.TransportClosed, 400);
|
|
1330
|
+
let a = this._channel.state;
|
|
1331
|
+
if (a !== "attached" && a !== "attaching") throw new e.ErrorInfo(`unable to send; channel is ${a}`, C.ChannelNotReady, 400);
|
|
1332
|
+
this._logger.trace("ClientTransport._internalSend();");
|
|
1333
|
+
let o = Array.isArray(t) ? t : [t], s = crypto.randomUUID();
|
|
1334
|
+
this._ownTurnIds.add(s), this._tree.trackTurn(s, this._clientId ?? "");
|
|
1335
|
+
let c = this._pendingLocalEvents;
|
|
1336
|
+
this._pendingLocalEvents = [], i && i.length > 0 && this._applyEventsToTree(i);
|
|
1337
|
+
let l = [...c, ...i ?? []], u = /* @__PURE__ */ new Set(), d = [], f = r, p;
|
|
844
1338
|
if (n?.parent === void 0 && !n?.forkOf) {
|
|
845
|
-
let e =
|
|
846
|
-
|
|
847
|
-
let t = e.at(-1);
|
|
848
|
-
if (t) {
|
|
849
|
-
let e = this._codec.getMessageKey(t);
|
|
850
|
-
u = this._tree.getNodeByKey(e)?.msgId ?? e;
|
|
851
|
-
}
|
|
852
|
-
}
|
|
1339
|
+
let e = f.at(-1);
|
|
1340
|
+
e && (p = e.msgId);
|
|
853
1341
|
}
|
|
854
|
-
let
|
|
855
|
-
for (let e of
|
|
1342
|
+
let m = n?.parent === void 0 ? p : n.parent;
|
|
1343
|
+
for (let e of o) {
|
|
856
1344
|
let t = crypto.randomUUID();
|
|
857
|
-
this._ownMsgIds.add(t),
|
|
858
|
-
let r = n?.parent === void 0 ?
|
|
1345
|
+
this._ownMsgIds.add(t), u.add(t);
|
|
1346
|
+
let r = n?.parent === void 0 ? p : n.parent, i = j({
|
|
859
1347
|
role: "user",
|
|
860
|
-
turnId:
|
|
1348
|
+
turnId: s,
|
|
861
1349
|
msgId: t,
|
|
862
1350
|
turnClientId: this._clientId,
|
|
863
1351
|
parent: r,
|
|
864
1352
|
forkOf: n?.forkOf
|
|
865
1353
|
});
|
|
866
|
-
this._upsertAndNotify(e,
|
|
867
|
-
|
|
868
|
-
[a]: t,
|
|
869
|
-
[s]: "user"
|
|
870
|
-
};
|
|
871
|
-
r && (d[f] = r), c.push({
|
|
1354
|
+
this._upsertAndNotify(e, i), d.push({
|
|
1355
|
+
kind: "message",
|
|
872
1356
|
message: e,
|
|
873
|
-
|
|
874
|
-
|
|
1357
|
+
msgId: t,
|
|
1358
|
+
parentId: r,
|
|
1359
|
+
forkOf: n?.forkOf,
|
|
1360
|
+
headers: i,
|
|
1361
|
+
serial: void 0
|
|
1362
|
+
}), n?.parent === void 0 && !n?.forkOf && (p = t);
|
|
875
1363
|
}
|
|
876
|
-
this._turnMsgIds.set(
|
|
877
|
-
let
|
|
1364
|
+
this._turnMsgIds.set(s, u);
|
|
1365
|
+
let h = this._router.createStream(s), g = this._headersFn?.() ?? {}, _ = {
|
|
878
1366
|
...this._bodyFn?.() ?? {},
|
|
879
|
-
history:
|
|
1367
|
+
history: f,
|
|
880
1368
|
...n?.body,
|
|
881
|
-
turnId:
|
|
1369
|
+
turnId: s,
|
|
882
1370
|
clientId: this._clientId,
|
|
883
|
-
messages:
|
|
1371
|
+
messages: d,
|
|
884
1372
|
...n?.forkOf !== void 0 && { forkOf: n.forkOf },
|
|
885
|
-
...
|
|
886
|
-
|
|
887
|
-
|
|
1373
|
+
...m !== void 0 && { parent: m },
|
|
1374
|
+
...l.length > 0 && { events: l }
|
|
1375
|
+
}, v = {
|
|
1376
|
+
...g,
|
|
888
1377
|
...n?.headers
|
|
889
1378
|
};
|
|
890
1379
|
return this._fetchFn(this._api, {
|
|
891
1380
|
method: "POST",
|
|
892
1381
|
headers: {
|
|
893
1382
|
"Content-Type": "application/json",
|
|
894
|
-
...
|
|
1383
|
+
...v
|
|
895
1384
|
},
|
|
896
|
-
body: JSON.stringify(
|
|
1385
|
+
body: JSON.stringify(_),
|
|
897
1386
|
...this._credentials ? { credentials: this._credentials } : {}
|
|
898
1387
|
}).then((t) => {
|
|
899
|
-
|
|
1388
|
+
if (!t.ok) {
|
|
1389
|
+
let n = new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} returned ${String(t.status)} ${t.statusText}`, C.TransportSendFailed, t.status);
|
|
1390
|
+
this._emitter.emit("error", n), this._router.errorStream(s, n);
|
|
1391
|
+
}
|
|
900
1392
|
}).catch((t) => {
|
|
901
|
-
let n = t instanceof e.ErrorInfo ? t : void 0;
|
|
902
|
-
this._emitter.emit("error",
|
|
1393
|
+
let n = t instanceof e.ErrorInfo ? t : void 0, r = new e.ErrorInfo(`unable to send; HTTP POST to ${this._api} failed: ${t instanceof Error ? t.message : String(t)}`, C.TransportSendFailed, 500, n);
|
|
1394
|
+
this._emitter.emit("error", r), this._router.errorStream(s, r);
|
|
903
1395
|
}), {
|
|
904
|
-
stream:
|
|
905
|
-
turnId:
|
|
906
|
-
cancel: async () => this.cancel({ turnId:
|
|
1396
|
+
stream: h,
|
|
1397
|
+
turnId: s,
|
|
1398
|
+
cancel: async () => this.cancel({ turnId: s }),
|
|
1399
|
+
optimisticMsgIds: [...u]
|
|
907
1400
|
};
|
|
908
1401
|
}
|
|
909
|
-
async regenerate(e, t) {
|
|
910
|
-
this._logger.trace("ClientTransport.regenerate();", { messageId: e });
|
|
911
|
-
let n = this._tree.getNode(e)?.parentId;
|
|
912
|
-
return this.send([], {
|
|
913
|
-
...t,
|
|
914
|
-
body: {
|
|
915
|
-
history: this._getHistoryBefore(e),
|
|
916
|
-
...t?.body
|
|
917
|
-
},
|
|
918
|
-
forkOf: e,
|
|
919
|
-
parent: n
|
|
920
|
-
});
|
|
921
|
-
}
|
|
922
|
-
async edit(e, t, n) {
|
|
923
|
-
this._logger.trace("ClientTransport.edit();", { messageId: e });
|
|
924
|
-
let r = this._tree.getNode(e)?.parentId;
|
|
925
|
-
return this.send(t, {
|
|
926
|
-
...n,
|
|
927
|
-
body: {
|
|
928
|
-
history: this._getHistoryBefore(e),
|
|
929
|
-
...n?.body
|
|
930
|
-
},
|
|
931
|
-
forkOf: e,
|
|
932
|
-
parent: r
|
|
933
|
-
});
|
|
934
|
-
}
|
|
935
1402
|
async cancel(e) {
|
|
936
|
-
if (this.
|
|
1403
|
+
if (this._state === Q.CLOSED) return;
|
|
937
1404
|
let t = e ?? { own: !0 };
|
|
938
1405
|
this._logger.debug("ClientTransport.cancel();", { filter: t }), await this._publishCancel(t), this._closeMatchingTurnStreams(t);
|
|
939
1406
|
}
|
|
1407
|
+
stageEvents(e, t) {
|
|
1408
|
+
if (this._logger.trace("ClientTransport.stageEvents();", {
|
|
1409
|
+
msgId: e,
|
|
1410
|
+
eventCount: t.length
|
|
1411
|
+
}), this._state === Q.CLOSED) {
|
|
1412
|
+
this._logger.warn("ClientTransport.stageEvents(); transport is closed", { msgId: e });
|
|
1413
|
+
return;
|
|
1414
|
+
}
|
|
1415
|
+
if (!this._tree.getNode(e)) {
|
|
1416
|
+
this._logger.warn("ClientTransport.stageEvents(); msgId not found in tree", { msgId: e });
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
if (t.length === 0) return;
|
|
1420
|
+
let n = {
|
|
1421
|
+
kind: "event",
|
|
1422
|
+
msgId: e,
|
|
1423
|
+
events: t
|
|
1424
|
+
};
|
|
1425
|
+
this._applyEventsToTree([n]), this._pendingLocalEvents.push(n);
|
|
1426
|
+
}
|
|
1427
|
+
stageMessage(e, t) {
|
|
1428
|
+
if (this._logger.trace("ClientTransport.stageMessage();", { msgId: e }), this._state === Q.CLOSED) {
|
|
1429
|
+
this._logger.warn("ClientTransport.stageMessage(); transport is closed", { msgId: e });
|
|
1430
|
+
return;
|
|
1431
|
+
}
|
|
1432
|
+
let n = this._tree.getNode(e);
|
|
1433
|
+
if (!n) {
|
|
1434
|
+
this._logger.warn("ClientTransport.stageMessage(); msgId not found in tree", { msgId: e });
|
|
1435
|
+
return;
|
|
1436
|
+
}
|
|
1437
|
+
this._tree.upsert(e, t, n.headers, n.serial);
|
|
1438
|
+
}
|
|
1439
|
+
_applyEventsToTree(e) {
|
|
1440
|
+
for (let t of e) {
|
|
1441
|
+
let e = this._tree.getNode(t.msgId);
|
|
1442
|
+
if (!e) continue;
|
|
1443
|
+
let n = t.events.map((e) => ({
|
|
1444
|
+
kind: "event",
|
|
1445
|
+
event: e,
|
|
1446
|
+
messageId: t.msgId
|
|
1447
|
+
})), r = this._codec.createAccumulator();
|
|
1448
|
+
r.initMessage(t.msgId, e.message), r.processOutputs(n);
|
|
1449
|
+
let i = r.messages.at(-1);
|
|
1450
|
+
i && this._tree.upsert(t.msgId, i, e.headers, e.serial);
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
940
1453
|
async waitForTurn(e) {
|
|
941
|
-
if (this.
|
|
1454
|
+
if (this._state === Q.CLOSED) return;
|
|
942
1455
|
let t = e ?? { own: !0 }, n = this._getMatchingTurnIds(t);
|
|
943
1456
|
if (n.size !== 0) return this._logger.debug("ClientTransport.waitForTurn();", { turnIds: [...n] }), new Promise((e) => {
|
|
944
|
-
let t = (
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
1457
|
+
let t = !1, r = () => {
|
|
1458
|
+
if (t) return;
|
|
1459
|
+
t = !0, i();
|
|
1460
|
+
let n = this._closeResolvers.indexOf(r);
|
|
1461
|
+
n !== -1 && this._closeResolvers.splice(n, 1), e();
|
|
1462
|
+
}, i = this._tree.on("turn", (e) => {
|
|
1463
|
+
e.type === "x-ably-turn-end" && (n.delete(e.turnId), n.size === 0 && r());
|
|
1464
|
+
});
|
|
1465
|
+
this._closeResolvers.push(r);
|
|
948
1466
|
});
|
|
949
1467
|
}
|
|
950
1468
|
on(e, t) {
|
|
951
|
-
if (this.
|
|
1469
|
+
if (this._state === Q.CLOSED) return ue;
|
|
952
1470
|
let n = t;
|
|
953
1471
|
return this._emitter.on(e, n), () => {
|
|
954
1472
|
this._emitter.off(e, n);
|
|
955
1473
|
};
|
|
956
1474
|
}
|
|
957
|
-
getTree() {
|
|
958
|
-
return this._tree;
|
|
959
|
-
}
|
|
960
|
-
getActiveTurnIds() {
|
|
961
|
-
let e = /* @__PURE__ */ new Map();
|
|
962
|
-
for (let [t, n] of this._turnClientIds) {
|
|
963
|
-
let r = e.get(n);
|
|
964
|
-
r || (r = /* @__PURE__ */ new Set(), e.set(n, r)), r.add(t);
|
|
965
|
-
}
|
|
966
|
-
return e;
|
|
967
|
-
}
|
|
968
|
-
getMessageHeaders(e) {
|
|
969
|
-
let t = this._codec.getMessageKey(e);
|
|
970
|
-
return this._tree.getNodeByKey(t)?.headers;
|
|
971
|
-
}
|
|
972
|
-
getMessages() {
|
|
973
|
-
return this._withheldKeys.size === 0 ? this._tree.flatten() : this._tree.flatten().filter((e) => !this._withheldKeys.has(this._codec.getMessageKey(e)));
|
|
974
|
-
}
|
|
975
|
-
getMessagesWithHeaders() {
|
|
976
|
-
return this._getMessagesWithHeaders();
|
|
977
|
-
}
|
|
978
|
-
getAblyMessages() {
|
|
979
|
-
return [...this._ablyMessages];
|
|
980
|
-
}
|
|
981
|
-
async history(t) {
|
|
982
|
-
if (this._closed) throw new e.ErrorInfo("unable to load history; transport is closed", x.TransportClosed, 400);
|
|
983
|
-
this._logger.trace("ClientTransport.history();", { limit: t?.limit });
|
|
984
|
-
let n = t?.limit ?? 100, r = new Set(this._tree.flatten().map((e) => this._codec.getMessageKey(e))), i = await X(this._channel, this._codec, t, this._logger), a = await this._loadUntilVisible(i, n, r);
|
|
985
|
-
i = a.lastPage;
|
|
986
|
-
let o = a.newVisible;
|
|
987
|
-
for (let e of o) this._withheldKeys.add(this._codec.getMessageKey(e));
|
|
988
|
-
let s = o.slice(-n), c = o.slice(0, -n);
|
|
989
|
-
this._releaseWithheld(s);
|
|
990
|
-
let l = (e) => ({
|
|
991
|
-
items: e,
|
|
992
|
-
hasNext: () => c.length > 0 || i.hasNext(),
|
|
993
|
-
next: async () => {
|
|
994
|
-
if (c.length > 0) {
|
|
995
|
-
let e = c.splice(-n, n);
|
|
996
|
-
return this._releaseWithheld(e), l(e);
|
|
997
|
-
}
|
|
998
|
-
if (!i.hasNext()) return;
|
|
999
|
-
let e = await i.next();
|
|
1000
|
-
if (!e) return;
|
|
1001
|
-
let t = new Set(r);
|
|
1002
|
-
for (let e of this._tree.flatten()) t.add(this._codec.getMessageKey(e));
|
|
1003
|
-
let a = await this._loadUntilVisible(e, n, t);
|
|
1004
|
-
i = a.lastPage;
|
|
1005
|
-
let o = a.newVisible;
|
|
1006
|
-
for (let e of o) this._withheldKeys.add(this._codec.getMessageKey(e));
|
|
1007
|
-
let s = o.splice(-n, n);
|
|
1008
|
-
if (c.push(...o), this._releaseWithheld(s), s.length !== 0) return l(s);
|
|
1009
|
-
}
|
|
1010
|
-
});
|
|
1011
|
-
return l(s);
|
|
1012
|
-
}
|
|
1013
1475
|
async close(e) {
|
|
1014
|
-
if (
|
|
1015
|
-
if (this.
|
|
1476
|
+
if (this._state !== Q.CLOSED) {
|
|
1477
|
+
if (this._state = Q.CLOSED, this._logger.info("ClientTransport.close();"), e?.cancel) {
|
|
1016
1478
|
try {
|
|
1017
1479
|
await this._publishCancel(e.cancel);
|
|
1018
1480
|
} catch {}
|
|
1019
1481
|
this._closeMatchingTurnStreams(e.cancel);
|
|
1020
1482
|
}
|
|
1021
|
-
this._channel.unsubscribe(this._onMessage);
|
|
1483
|
+
this._channel.unsubscribe(this._onMessage), this._channel.off(this._onChannelStateChange);
|
|
1022
1484
|
for (let e of this._ownTurnIds) this._router.closeStream(e);
|
|
1023
|
-
this._turnObservers.clear(), this._emitter.off()
|
|
1485
|
+
this._turnObservers.clear(), this._emitter.off();
|
|
1486
|
+
for (let e of this._views) e.close();
|
|
1487
|
+
this._views.clear();
|
|
1488
|
+
for (let e of this._closeResolvers) e();
|
|
1489
|
+
this._closeResolvers.length = 0, this._ownTurnIds.clear(), this._ownMsgIds.clear(), this._turnMsgIds.clear();
|
|
1024
1490
|
}
|
|
1025
1491
|
}
|
|
1026
|
-
},
|
|
1492
|
+
}, fe = (e) => new de(e), pe = (e) => [{
|
|
1027
1493
|
kind: "event",
|
|
1028
1494
|
event: e
|
|
1029
|
-
}],
|
|
1495
|
+
}], me = class {
|
|
1030
1496
|
constructor(e, t = {}) {
|
|
1031
1497
|
this._serialState = /* @__PURE__ */ new Map(), this._hooks = e, this._onStreamUpdate = t.onStreamUpdate, this._onStreamDelete = t.onStreamDelete, this._logger = t.logger?.withContext({ component: "DecoderCore" });
|
|
1032
1498
|
}
|
|
@@ -1055,7 +1521,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1055
1521
|
break;
|
|
1056
1522
|
default: return [];
|
|
1057
1523
|
}
|
|
1058
|
-
let r =
|
|
1524
|
+
let r = w(e)[o];
|
|
1059
1525
|
if (r) for (let e of n) e.kind === "event" && (e.messageId = r);
|
|
1060
1526
|
return n;
|
|
1061
1527
|
}
|
|
@@ -1063,7 +1529,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1063
1529
|
return {
|
|
1064
1530
|
name: e.name ?? "",
|
|
1065
1531
|
data: e.data,
|
|
1066
|
-
headers:
|
|
1532
|
+
headers: w(e)
|
|
1067
1533
|
};
|
|
1068
1534
|
}
|
|
1069
1535
|
_stringData(e) {
|
|
@@ -1103,7 +1569,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1103
1569
|
if (!t) return [];
|
|
1104
1570
|
let r = this._serialState.get(t);
|
|
1105
1571
|
if (!r) return this._decodeUpdate(e);
|
|
1106
|
-
let i =
|
|
1572
|
+
let i = w(e), a = typeof e.data == "string" ? e.data : "", o = i[n], s = [];
|
|
1107
1573
|
return a.length > 0 && (r.accumulated += a, s.push(...this._hooks.buildDeltaEvents(r, a))), o === "finished" && !r.closed ? (r.closed = !0, s.push(...this._hooks.buildEndEvents(r, i)), this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream finished", { streamId: r.streamId })) : o === "aborted" && !r.closed && (r.closed = !0, this._logger?.debug("DefaultDecoderCore._decodeAppend(); stream aborted", { streamId: r.streamId })), s;
|
|
1108
1574
|
}
|
|
1109
1575
|
_decodeUpdate(e) {
|
|
@@ -1143,7 +1609,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1143
1609
|
let n = this._serialState.get(t);
|
|
1144
1610
|
return this._invokeOnStreamDelete(t, n), n && (n.accumulated = "", n.closed = !0), this._logger?.debug("DefaultDecoderCore._decodeDelete();", { serial: t }), [];
|
|
1145
1611
|
}
|
|
1146
|
-
},
|
|
1612
|
+
}, he = (e, t = {}) => new me(e, t), ge = class {
|
|
1147
1613
|
constructor(e, t = {}) {
|
|
1148
1614
|
this._trackers = /* @__PURE__ */ new Map(), this._pending = [], this._closed = !1, this._writer = e, this._defaultClientId = t.clientId, this._defaultExtras = t.extras, this._onMessageHook = t.onMessage ?? (() => {}), this._logger = t.logger?.withContext({ component: "EncoderCore" });
|
|
1149
1615
|
}
|
|
@@ -1155,6 +1621,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1155
1621
|
async publishDiscreteBatch(e, t) {
|
|
1156
1622
|
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.publishDiscreteBatch();", { count: e.length });
|
|
1157
1623
|
let n = e.map((e) => this._buildDiscreteMessage(e, t));
|
|
1624
|
+
for (let e of n) e.extras.headers[i] = "true";
|
|
1158
1625
|
return this._writer.publish(n);
|
|
1159
1626
|
}
|
|
1160
1627
|
async startStream(i, a, o) {
|
|
@@ -1172,7 +1639,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1172
1639
|
};
|
|
1173
1640
|
this._invokeOnMessage(l);
|
|
1174
1641
|
let u = (await this._writer.publish(l)).serials[0];
|
|
1175
|
-
if (!u) throw new e.ErrorInfo(`unable to start stream; no serial returned for stream '${a.name}' (streamId: ${i})`,
|
|
1642
|
+
if (!u) throw new e.ErrorInfo(`unable to start stream; no serial returned for stream '${a.name}' (streamId: ${i})`, C.BadRequest, 400);
|
|
1176
1643
|
this._trackers.set(i, {
|
|
1177
1644
|
serial: u,
|
|
1178
1645
|
name: a.name,
|
|
@@ -1189,7 +1656,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1189
1656
|
appendStream(t, n) {
|
|
1190
1657
|
this._assertNotClosed();
|
|
1191
1658
|
let r = this._trackers.get(t);
|
|
1192
|
-
if (!r) throw new e.ErrorInfo(`unable to append to stream; no active stream for streamId '${t}'`,
|
|
1659
|
+
if (!r) throw new e.ErrorInfo(`unable to append to stream; no active stream for streamId '${t}'`, C.InvalidArgument, 400);
|
|
1193
1660
|
r.accumulated += n;
|
|
1194
1661
|
let i = {
|
|
1195
1662
|
serial: r.serial,
|
|
@@ -1206,7 +1673,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1206
1673
|
async closeStream(t, r) {
|
|
1207
1674
|
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.closeStream();", { streamId: t });
|
|
1208
1675
|
let i = this._trackers.get(t);
|
|
1209
|
-
if (!i) throw new e.ErrorInfo(`unable to close stream; no active stream for streamId '${t}'`,
|
|
1676
|
+
if (!i) throw new e.ErrorInfo(`unable to close stream; no active stream for streamId '${t}'`, C.InvalidArgument, 400);
|
|
1210
1677
|
i.accumulated += r.data;
|
|
1211
1678
|
let a = this._buildClosingHeaders(i, r.headers ?? {});
|
|
1212
1679
|
a[n] = "finished";
|
|
@@ -1225,7 +1692,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1225
1692
|
async abortStream(t, r) {
|
|
1226
1693
|
this._assertNotClosed(), this._logger?.trace("DefaultEncoderCore.abortStream();", { streamId: t });
|
|
1227
1694
|
let i = this._trackers.get(t);
|
|
1228
|
-
if (!i) throw new e.ErrorInfo(`unable to abort stream; no active stream for streamId '${t}'`,
|
|
1695
|
+
if (!i) throw new e.ErrorInfo(`unable to abort stream; no active stream for streamId '${t}'`, C.InvalidArgument, 400);
|
|
1229
1696
|
i.aborted = !0;
|
|
1230
1697
|
let a = this._buildClosingHeaders(i, {}, r);
|
|
1231
1698
|
a[n] = "aborted";
|
|
@@ -1307,7 +1774,7 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1307
1774
|
}
|
|
1308
1775
|
if (a.length > 0) {
|
|
1309
1776
|
let t = a.map((e) => e.streamId).join(", ");
|
|
1310
|
-
throw this._logger?.error("DefaultEncoderCore._flushPending(); recovery failed", { failedStreams: t }), new e.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${t}`,
|
|
1777
|
+
throw this._logger?.error("DefaultEncoderCore._flushPending(); recovery failed", { failedStreams: t }), new e.ErrorInfo(`unable to flush pending appends; recovery failed for stream(s): ${t}`, C.EncoderRecoveryFailed, 500);
|
|
1311
1778
|
}
|
|
1312
1779
|
}
|
|
1313
1780
|
async close() {
|
|
@@ -1329,17 +1796,17 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1329
1796
|
}
|
|
1330
1797
|
}
|
|
1331
1798
|
_assertNotClosed() {
|
|
1332
|
-
if (this._closed) throw new e.ErrorInfo("unable to write to encoder; encoder has been closed",
|
|
1799
|
+
if (this._closed) throw new e.ErrorInfo("unable to write to encoder; encoder has been closed", C.InvalidArgument, 400);
|
|
1333
1800
|
}
|
|
1334
1801
|
_resolveClientId(e) {
|
|
1335
1802
|
return e?.clientId ?? this._defaultClientId;
|
|
1336
1803
|
}
|
|
1337
1804
|
_buildHeaders(e, t) {
|
|
1338
1805
|
let n = {
|
|
1339
|
-
...
|
|
1806
|
+
...E(this._defaultExtras?.headers, t?.extras?.headers),
|
|
1340
1807
|
...e
|
|
1341
1808
|
};
|
|
1342
|
-
return t?.messageId !== void 0 && (n[
|
|
1809
|
+
return t?.messageId !== void 0 && (n[o] = t.messageId), n;
|
|
1343
1810
|
}
|
|
1344
1811
|
_buildDiscreteMessage(e, n) {
|
|
1345
1812
|
let r = this._buildHeaders(e.headers ?? {}, n);
|
|
@@ -1356,10 +1823,10 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1356
1823
|
return this._invokeOnMessage(a), a;
|
|
1357
1824
|
}
|
|
1358
1825
|
_buildClosingHeaders(e, t, n) {
|
|
1359
|
-
let r = { ...e.persistentHeaders }, i =
|
|
1826
|
+
let r = { ...e.persistentHeaders }, i = E(this._defaultExtras?.headers, n?.extras?.headers);
|
|
1360
1827
|
return Object.assign(r, i), Object.assign(r, t), r;
|
|
1361
1828
|
}
|
|
1362
|
-
},
|
|
1829
|
+
}, $ = (e, t = {}) => new ge(e, t), _e = class {
|
|
1363
1830
|
constructor(e) {
|
|
1364
1831
|
this._emitted = /* @__PURE__ */ new Map(), this._phases = e;
|
|
1365
1832
|
}
|
|
@@ -1381,8 +1848,8 @@ var t = "x-ably-stream", n = "x-ably-status", r = "x-ably-stream-id", i = "x-abl
|
|
|
1381
1848
|
let t = this._emitted.get(e);
|
|
1382
1849
|
return t || (t = /* @__PURE__ */ new Set(), this._emitted.set(e, t)), t;
|
|
1383
1850
|
}
|
|
1384
|
-
},
|
|
1851
|
+
}, ve = (e) => new _e(e);
|
|
1385
1852
|
//#endregion
|
|
1386
|
-
export {
|
|
1853
|
+
export { S as DOMAIN_HEADER_PREFIX, b as EVENT_ABORT, _ as EVENT_CANCEL, x as EVENT_ERROR, y as EVENT_TURN_END, v as EVENT_TURN_START, C as ErrorCode, L as EventEmitter, f as HEADER_CANCEL_ALL, p as HEADER_CANCEL_CLIENT_ID, d as HEADER_CANCEL_OWN, u as HEADER_CANCEL_TURN_ID, h as HEADER_FORK_OF, o as HEADER_MSG_ID, m as HEADER_PARENT, c as HEADER_ROLE, n as HEADER_STATUS, t as HEADER_STREAM, r as HEADER_STREAM_ID, s as HEADER_TURN_CLIENT_ID, a as HEADER_TURN_ID, g as HEADER_TURN_REASON, R as LogLevel, j as buildTransportHeaders, z as consoleLogger, fe as createClientTransport, he as createDecoderCore, $ as createEncoderCore, ve as createLifecycleTracker, ae as createServerTransport, ee as errorInfoIs, pe as eventOutput, w as getHeaders, k as headerReader, A as headerWriter, B as makeLogger, E as mergeHeaders, O as stripUndefined };
|
|
1387
1854
|
|
|
1388
1855
|
//# sourceMappingURL=ably-ai-transport.js.map
|