@codex-app-sdk/web 0.0.0-stage → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # `@codex-app-sdk/web`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Framework-neutral WebSocket transport for browser Codex surfaces.
4
+
5
+ ```bash
6
+ npm install @codex-app-sdk/core @codex-app-sdk/web
7
+ ```
8
+
9
+ - `@codex-app-sdk/web/client` creates a reconnecting browser-side
10
+ `CodexSurfaceRendererApi`.
11
+ - `@codex-app-sdk/web/server` binds an already accepted socket to a
12
+ host-authorized surface lease.
13
+ - `@codex-app-sdk/web/protocol` exports versioned envelopes for custom
14
+ transport integrations.
15
+
16
+ Both endpoints default to a 64 MiB message ceiling. The server adapter can wrap
17
+ the EventEmitter-style subset implemented by `ws`, or the host can implement
18
+ `CodexWebSocketPort` for another library.
19
+
20
+ The package does not create an HTTP server, parse cookies, authenticate users,
21
+ store tokens, manage `codexHome` directories, pool app-server processes, create
22
+ upload routes, or depend on Express or a WebSocket implementation. Those are
23
+ host-application responsibilities.
24
+
25
+ See the [web integration
26
+ guide](https://codex-app-sdk.github.io/codex-app-sdk/guide/web.html), [web
27
+ API](https://codex-app-sdk.github.io/codex-app-sdk/api/web.html), and [Basic Express
28
+ sample](https://github.com/codex-app-sdk/codex-app-sdk/tree/main/samples/web/basic).
@@ -0,0 +1,20 @@
1
+ //#region src/socket-port.ts
2
+ var e = 64 * 1024 * 1024;
3
+ function t(e, t) {
4
+ let n;
5
+ if (typeof e == "string") n = e;
6
+ else if (e instanceof ArrayBuffer) n = new TextDecoder().decode(e);
7
+ else if (ArrayBuffer.isView(e)) n = new TextDecoder().decode(e);
8
+ else throw TypeError("Codex WebSocket messages must contain text or UTF-8 bytes");
9
+ if (new TextEncoder().encode(n).byteLength > t) throw RangeError(`Codex WebSocket message exceeds the ${t} byte limit`);
10
+ return n;
11
+ }
12
+ function n(e, t, n) {
13
+ if (e === void 0) return t;
14
+ if (!Number.isSafeInteger(e) || e <= 0) throw TypeError(`${n} must be a positive integer`);
15
+ return e;
16
+ }
17
+ //#endregion
18
+ export { e as n, n as r, t };
19
+
20
+ //# sourceMappingURL=socket-port-QOPQStPy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"socket-port-QOPQStPy.js","names":[],"sources":["../../src/socket-port.ts"],"sourcesContent":["export type CodexWebSocketClose = {\n code?: number;\n reason?: string;\n wasClean?: boolean;\n};\n\n/** Minimal socket seam implemented by browser WebSocket, `ws`, or another host adapter. */\nexport type CodexWebSocketPort = {\n send(data: string): void;\n close(code?: number, reason?: string): void;\n onMessage(listener: (data: unknown) => void): () => void;\n onClose(listener: (event: CodexWebSocketClose) => void): () => void;\n onError?(listener: (error: unknown) => void): () => void;\n};\n\nexport const defaultCodexWebSocketMaximumMessageBytes = 64 * 1024 * 1024;\n\nexport function codexWebSocketText(data: unknown, maximumBytes: number): string {\n let value: string;\n if (typeof data === 'string') {\n value = data;\n } else if (data instanceof ArrayBuffer) {\n value = new TextDecoder().decode(data);\n } else if (ArrayBuffer.isView(data)) {\n value = new TextDecoder().decode(data);\n } else {\n throw new TypeError('Codex WebSocket messages must contain text or UTF-8 bytes');\n }\n if (new TextEncoder().encode(value).byteLength > maximumBytes) {\n throw new RangeError(`Codex WebSocket message exceeds the ${maximumBytes} byte limit`);\n }\n return value;\n}\n\nexport function positiveWebSocketLimit(\n value: number | undefined,\n fallback: number,\n label: string,\n): number {\n if (value === undefined) return fallback;\n if (!Number.isSafeInteger(value) || value <= 0) throw new TypeError(`${label} must be a positive integer`);\n return value;\n}\n"],"mappings":";AAeA,IAAa,IAA2C,KAAK,OAAO;AAEpE,SAAgB,EAAmB,GAAe,GAA8B;CAC9E,IAAI;CACJ,IAAI,OAAO,KAAS,UAClB,IAAQ;MACH,IAAI,aAAgB,aACzB,IAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,CAAI;MAChC,IAAI,YAAY,OAAO,CAAI,GAChC,IAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,CAAI;MAErC,MAAU,UAAU,2DAA2D;CAEjF,IAAI,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,CAAC,CAAC,aAAa,GAC/C,MAAU,WAAW,uCAAuC,EAAa,YAAY;CAEvF,OAAO;AACT;AAEA,SAAgB,EACd,GACA,GACA,GACQ;CACR,IAAI,MAAU,KAAA,GAAW,OAAO;CAChC,IAAI,CAAC,OAAO,cAAc,CAAK,KAAK,KAAS,GAAG,MAAU,UAAU,GAAG,EAAM,4BAA4B;CACzG,OAAO;AACT"}
@@ -0,0 +1,31 @@
1
+ import type { CodexSurfaceRendererApi } from '@codex-app-sdk/core/surface';
2
+ import { type CodexWebSocketErrorPayload } from './protocol';
3
+ import { type CodexWebSocketPort } from './socket-port';
4
+ type Awaitable<Value> = Value | Promise<Value>;
5
+ export type CodexWebReconnectOptions = {
6
+ maxAttempts?: number;
7
+ initialDelayMs?: number;
8
+ maximumDelayMs?: number;
9
+ };
10
+ export type CreateCodexWebSurfaceClientOptions = {
11
+ createSocket(): Awaitable<CodexWebSocketPort>;
12
+ maxMessageBytes?: number;
13
+ reconnect?: boolean | CodexWebReconnectOptions;
14
+ requestTimeoutMs?: number;
15
+ };
16
+ export type CodexWebSurfaceClientConnectionState = 'closed' | 'connecting' | 'disconnected' | 'ready';
17
+ export type CodexWebSurfaceClient = CodexSurfaceRendererApi & {
18
+ disconnect(code?: number, reason?: string): void;
19
+ getConnectionState(): CodexWebSurfaceClientConnectionState;
20
+ };
21
+ export declare class CodexWebSocketRemoteError extends Error {
22
+ readonly code: CodexWebSocketErrorPayload['code'];
23
+ constructor(error: CodexWebSocketErrorPayload);
24
+ }
25
+ export declare class CodexWebSocketTransportError extends Error {
26
+ constructor(message: string);
27
+ }
28
+ export declare function createCodexWebSurfaceClient(options: CreateCodexWebSurfaceClientOptions): CodexWebSurfaceClient;
29
+ export declare function createCodexBrowserWebSocketPort(socket: WebSocket): CodexWebSocketPort;
30
+ export type { CodexWebSocketClose, CodexWebSocketPort, } from './socket-port';
31
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAEV,uBAAuB,EAGxB,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAGL,KAAK,0BAA0B,EAChC,MAAM,YAAY,CAAC;AACpB,OAAO,EAKL,KAAK,kBAAkB,EACxB,MAAM,eAAe,CAAC;AAEvB,KAAK,SAAS,CAAC,KAAK,IAAI,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;AAE/C,MAAM,MAAM,wBAAwB,GAAG;IACrC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,kCAAkC,GAAG;IAC/C,YAAY,IAAI,SAAS,CAAC,kBAAkB,CAAC,CAAC;IAC9C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,SAAS,CAAC,EAAE,OAAO,GAAG,wBAAwB,CAAC;IAC/C,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF,MAAM,MAAM,oCAAoC,GAC5C,QAAQ,GACR,YAAY,GACZ,cAAc,GACd,OAAO,CAAC;AAEZ,MAAM,MAAM,qBAAqB,GAAG,uBAAuB,GAAG;IAC5D,UAAU,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACjD,kBAAkB,IAAI,oCAAoC,CAAC;CAC5D,CAAC;AAEF,qBAAa,yBAA0B,SAAQ,KAAK;IAClD,QAAQ,CAAC,IAAI,EAAE,0BAA0B,CAAC,MAAM,CAAC,CAAC;gBAEtC,KAAK,EAAE,0BAA0B;CAK9C;AAED,qBAAa,4BAA6B,SAAQ,KAAK;gBACzC,OAAO,EAAE,MAAM;CAI5B;AAID,wBAAgB,2BAA2B,CACzC,OAAO,EAAE,kCAAkC,GAC1C,qBAAqB,CAcvB;AAED,wBAAgB,+BAA+B,CAAC,MAAM,EAAE,SAAS,GAAG,kBAAkB,CAYrF;AAuXD,YAAY,EACV,mBAAmB,EACnB,kBAAkB,GACnB,MAAM,eAAe,CAAC"}
package/dist/client.js ADDED
@@ -0,0 +1,289 @@
1
+ import { encodeCodexWebSocketMessage as e } from "./protocol.js";
2
+ import { n as t, r as n, t as r } from "./chunks/socket-port-QOPQStPy.js";
3
+ import { codexSurfaceBridgeOperations as i, createCodexSurfaceStateMirror as a } from "@codex-app-sdk/core/surface-bridge";
4
+ //#region src/client.ts
5
+ var o = class extends Error {
6
+ code;
7
+ constructor(e) {
8
+ super(e.message), this.name = "CodexWebSocketRemoteError", this.code = e.code;
9
+ }
10
+ }, s = class extends Error {
11
+ constructor(e) {
12
+ super(e), this.name = "CodexWebSocketTransportError";
13
+ }
14
+ }, c = 6e4;
15
+ function l(e) {
16
+ let t = new d(e), n = {
17
+ disconnect: (e, n) => t.disconnect(e, n),
18
+ getConnectionState: () => t.connectionState,
19
+ onEvent: (e) => t.onEvent(e),
20
+ onStateChange: (e) => t.onStateChange(e)
21
+ };
22
+ for (let e of i) n[e] = e === "connect" ? () => t.connect() : (...n) => t.invoke(e, n);
23
+ return Object.freeze(n);
24
+ }
25
+ function u(e) {
26
+ return {
27
+ send: (t) => e.send(t),
28
+ close: (t, n) => e.close(t, n),
29
+ onMessage: (t) => f(e, "message", (e) => t(e.data)),
30
+ onClose: (t) => f(e, "close", (e) => t({
31
+ code: e.code,
32
+ reason: e.reason,
33
+ wasClean: e.wasClean
34
+ })),
35
+ onError: (t) => f(e, "error", t)
36
+ };
37
+ }
38
+ var d = class {
39
+ #e;
40
+ #t;
41
+ #n;
42
+ #r;
43
+ #i = /* @__PURE__ */ new Set();
44
+ #a = /* @__PURE__ */ new Set();
45
+ #o = /* @__PURE__ */ new Map();
46
+ #s = [];
47
+ #c = null;
48
+ #l = null;
49
+ #u = null;
50
+ #d = null;
51
+ #f = a();
52
+ #p = !1;
53
+ #m = 0;
54
+ #h = !1;
55
+ #g = 0;
56
+ #_ = null;
57
+ connectionState = "disconnected";
58
+ constructor(e) {
59
+ this.#e = e.createSocket, this.#t = n(e.maxMessageBytes, t, "Codex WebSocket message byte limit"), this.#n = n(e.requestTimeoutMs, c, "Codex WebSocket request timeout"), this.#r = p(e.reconnect);
60
+ }
61
+ connect() {
62
+ return this.#h = !1, this.#O(), this.connectionState === "ready" && this.#d ? Promise.resolve(this.#d) : this.#v();
63
+ }
64
+ async invoke(t, n) {
65
+ await this.connect();
66
+ let r = this.#c;
67
+ if (!r || this.connectionState !== "ready") throw new s("Codex WebSocket is not connected");
68
+ let i = g(++this.#m), a = new Promise((e, n) => {
69
+ let r = setTimeout(() => {
70
+ this.#o.delete(i), n(new o({
71
+ code: "request_timeout",
72
+ message: `Codex WebSocket request '${t}' timed out`
73
+ }));
74
+ }, this.#n);
75
+ this.#o.set(i, {
76
+ resolve: e,
77
+ reject: n,
78
+ timeout: r
79
+ });
80
+ });
81
+ try {
82
+ r.send(e({
83
+ version: 1,
84
+ type: "request",
85
+ id: i,
86
+ operation: t,
87
+ args: _(n)
88
+ }));
89
+ } catch (e) {
90
+ this.#E(i, S(e));
91
+ }
92
+ return a;
93
+ }
94
+ onStateChange(e) {
95
+ return this.#i.add(e), () => this.#i.delete(e);
96
+ }
97
+ onEvent(e) {
98
+ return this.#a.add(e), () => this.#a.delete(e);
99
+ }
100
+ disconnect(e = 1e3, t = "Codex web client disconnected") {
101
+ this.#h = !0, this.#O();
102
+ let n = this.#c;
103
+ n && n.close(e, t), this.#S({
104
+ code: e,
105
+ reason: t,
106
+ wasClean: !0
107
+ }, n), this.connectionState = "closed";
108
+ }
109
+ #v() {
110
+ if (this.#l) return this.#l;
111
+ this.connectionState = "connecting";
112
+ let e = this.#y();
113
+ return this.#l = e, e.finally(() => {
114
+ this.#l === e && (this.#l = null);
115
+ }).catch(() => void 0), e;
116
+ }
117
+ async #y() {
118
+ let e;
119
+ try {
120
+ e = await this.#e();
121
+ } catch (e) {
122
+ throw this.connectionState = "disconnected", this.#D(), S(e);
123
+ }
124
+ if (this.#h) throw e.close(1e3, "Codex web client is closed"), new s("Codex web client is closed");
125
+ return this.#b(e), new Promise((t, n) => {
126
+ this.#u = {
127
+ socket: e,
128
+ resolve: t,
129
+ reject: n
130
+ };
131
+ });
132
+ }
133
+ #b(e) {
134
+ this.#k(), this.#c = e, this.#s.push(e.onMessage((t) => this.#x(t, e)), e.onClose((t) => this.#S(t, e))), e.onError && this.#s.push(e.onError((t) => {
135
+ this.#S({
136
+ reason: C(t),
137
+ wasClean: !1
138
+ }, e);
139
+ }));
140
+ }
141
+ #x(e, t) {
142
+ if (t !== this.#c || this.#h) return;
143
+ let n;
144
+ try {
145
+ let t = JSON.parse(r(e, this.#t));
146
+ if (!v(t) || t.version !== 1) throw TypeError("Invalid Codex WebSocket response");
147
+ n = t;
148
+ } catch (e) {
149
+ t.close(4400, "Invalid Codex WebSocket response"), this.#S({
150
+ code: 4400,
151
+ reason: C(e)
152
+ }, t);
153
+ return;
154
+ }
155
+ if (n.type === "ready" && v(n.snapshot) && y(n.stateVersion)) {
156
+ let e = this.#C(n.snapshot, n.stateVersion);
157
+ this.#p = !1, this.connectionState = "ready", this.#g = 0, this.#T(e);
158
+ let r = this.#u;
159
+ this.#u = null, r?.socket === t && r.resolve(e), n.stateVersion !== void 0 && this.#w(t);
160
+ return;
161
+ }
162
+ if (n.type === "snapshot" && v(n.snapshot) && y(n.stateVersion)) {
163
+ this.#T(this.#C(n.snapshot, n.stateVersion));
164
+ return;
165
+ }
166
+ if (n.type === "statePatch" && this.#p && b(n.patch)) {
167
+ let e = this.#f.receive(n.patch);
168
+ e.status === "applied" ? (this.#d = e.snapshot, this.#T(e.snapshot)) : e.status === "resync" && (t.close(4001, "Codex state stream desynchronized"), this.#S({
169
+ code: 4001,
170
+ reason: "Codex state stream desynchronized"
171
+ }, t));
172
+ return;
173
+ }
174
+ if (n.type === "event" && v(n.event)) {
175
+ for (let e of this.#a) e(n.event);
176
+ return;
177
+ }
178
+ if (n.type === "response" && typeof n.id == "string" && typeof n.ok == "boolean") {
179
+ let e = this.#o.get(n.id);
180
+ if (!e) return;
181
+ this.#o.delete(n.id), clearTimeout(e.timeout), n.ok ? e.resolve(n.result) : x(n.error) ? e.reject(new o(n.error)) : e.reject(new s("Codex WebSocket returned an invalid error"));
182
+ return;
183
+ }
184
+ t.close(4400, "Invalid Codex WebSocket response"), this.#S({
185
+ code: 4400,
186
+ reason: "Invalid Codex WebSocket response"
187
+ }, t);
188
+ }
189
+ #S(e, t) {
190
+ if (t && t !== this.#c) return;
191
+ t === this.#c && (this.#c = null), this.#k();
192
+ let n = new s(e.reason?.trim() || `Codex WebSocket closed${e.code ? ` (${e.code})` : ""}`), r = this.#u;
193
+ this.#u = null, r && (!t || r.socket === t) && r.reject(n);
194
+ for (let e of [...this.#o.keys()]) this.#E(e, n);
195
+ if (this.#h) {
196
+ this.connectionState = "closed";
197
+ return;
198
+ }
199
+ this.connectionState = "disconnected", h(e) && this.#D();
200
+ }
201
+ #C(e, t) {
202
+ let n = t === void 0 ? e : this.#f.reset({
203
+ version: t,
204
+ snapshot: e
205
+ });
206
+ return this.#d = n, n;
207
+ }
208
+ #w(t) {
209
+ try {
210
+ t.send(e({
211
+ version: 1,
212
+ type: "enableStatePatches"
213
+ })), this.#p = !0;
214
+ } catch {}
215
+ }
216
+ #T(e) {
217
+ for (let t of this.#i) t(e);
218
+ }
219
+ #E(e, t) {
220
+ let n = this.#o.get(e);
221
+ n && (this.#o.delete(e), clearTimeout(n.timeout), n.reject(t));
222
+ }
223
+ #D() {
224
+ let e = this.#r;
225
+ if (!e || this.#h || this.#_ || this.#g >= e.maxAttempts) return;
226
+ let t = Math.min(e.initialDelayMs * 2 ** this.#g, e.maximumDelayMs);
227
+ this.#g += 1, this.#_ = setTimeout(() => {
228
+ this.#_ = null, this.#v().catch(() => void 0);
229
+ }, t);
230
+ }
231
+ #O() {
232
+ this.#_ &&= (clearTimeout(this.#_), null);
233
+ }
234
+ #k() {
235
+ for (let e of this.#s.splice(0)) e();
236
+ }
237
+ };
238
+ function f(e, t, n) {
239
+ return e.addEventListener(t, n), () => e.removeEventListener(t, n);
240
+ }
241
+ function p(e) {
242
+ if (!e) return null;
243
+ let t = e === !0 ? {} : e;
244
+ return {
245
+ maxAttempts: m(t.maxAttempts, 8, "Reconnect maximum attempts"),
246
+ initialDelayMs: n(t.initialDelayMs, 250, "Reconnect initial delay"),
247
+ maximumDelayMs: n(t.maximumDelayMs, 5e3, "Reconnect maximum delay")
248
+ };
249
+ }
250
+ function m(e, t, n) {
251
+ if (e === void 0) return t;
252
+ if (!Number.isSafeInteger(e) || e < 0) throw TypeError(`${n} must be a non-negative integer`);
253
+ return e;
254
+ }
255
+ function h(e) {
256
+ return e.code === 1e3 ? !1 : e.code === void 0 || e.code < 4400 || e.code > 4499;
257
+ }
258
+ function g(e) {
259
+ return `codex-${e}-${globalThis.crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2)}`;
260
+ }
261
+ function _(e) {
262
+ let t = e.length;
263
+ for (; t > 0 && e[t - 1] === void 0;) --t;
264
+ return e.slice(0, t);
265
+ }
266
+ function v(e) {
267
+ if (!e || typeof e != "object" || Array.isArray(e)) return !1;
268
+ let t = Object.getPrototypeOf(e);
269
+ return t === Object.prototype || t === null;
270
+ }
271
+ function y(e) {
272
+ return e === void 0 || Number.isSafeInteger(e);
273
+ }
274
+ function b(e) {
275
+ return v(e) && Number.isSafeInteger(e.version) && Array.isArray(e.changes);
276
+ }
277
+ function x(e) {
278
+ return !v(e) || typeof e.message != "string" ? !1 : e.code === "invalid_request" || e.code === "operation_failed" || e.code === "request_timeout" || e.code === "transport_closed";
279
+ }
280
+ function S(e) {
281
+ return e instanceof s ? e : new s(C(e));
282
+ }
283
+ function C(e) {
284
+ return e instanceof Error ? e.message : String(e);
285
+ }
286
+ //#endregion
287
+ export { o as CodexWebSocketRemoteError, s as CodexWebSocketTransportError, u as createCodexBrowserWebSocketPort, l as createCodexWebSurfaceClient };
288
+
289
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","names":["#createSocket","#maxMessageBytes","#requestTimeoutMs","#reconnect","#stateListeners","#eventListeners","#pending","#socketUnsubscribers","#state","#manualClose","#clearReconnectTimer","#latestSnapshot","#beginConnect","#socket","#requestSequence","#rejectPending","#handleClose","#connectPromise","#open","#scheduleReconnect","#replaceSocket","#readyWaiter","#clearSocketListeners","#receive","#adoptSnapshot","#streamingPatches","#reconnectAttempts","#emitSnapshot","#enableStatePatches","#reconnectTimer"],"sources":["../src/client.ts"],"sourcesContent":["import {\n codexSurfaceBridgeOperations,\n type CodexSurfaceBridgeOperation,\n type CodexSurfaceBridgeOperationArguments,\n type CodexSurfaceBridgeOperationResult,\n} from '@codex-app-sdk/core/surface-bridge';\nimport type {\n CodexSurfaceEvent,\n CodexSurfaceRendererApi,\n CodexSurfaceSnapshot,\n CodexSurfaceStatePatch,\n} from '@codex-app-sdk/core/surface';\nimport { createCodexSurfaceStateMirror } from '@codex-app-sdk/core/surface-bridge';\nimport {\n codexWebSocketProtocolVersion,\n encodeCodexWebSocketMessage,\n type CodexWebSocketErrorPayload,\n} from './protocol';\nimport {\n codexWebSocketText,\n defaultCodexWebSocketMaximumMessageBytes,\n positiveWebSocketLimit,\n type CodexWebSocketClose,\n type CodexWebSocketPort,\n} from './socket-port';\n\ntype Awaitable<Value> = Value | Promise<Value>;\n\nexport type CodexWebReconnectOptions = {\n maxAttempts?: number;\n initialDelayMs?: number;\n maximumDelayMs?: number;\n};\n\nexport type CreateCodexWebSurfaceClientOptions = {\n createSocket(): Awaitable<CodexWebSocketPort>;\n maxMessageBytes?: number;\n reconnect?: boolean | CodexWebReconnectOptions;\n requestTimeoutMs?: number;\n};\n\nexport type CodexWebSurfaceClientConnectionState =\n | 'closed'\n | 'connecting'\n | 'disconnected'\n | 'ready';\n\nexport type CodexWebSurfaceClient = CodexSurfaceRendererApi & {\n disconnect(code?: number, reason?: string): void;\n getConnectionState(): CodexWebSurfaceClientConnectionState;\n};\n\nexport class CodexWebSocketRemoteError extends Error {\n readonly code: CodexWebSocketErrorPayload['code'];\n\n constructor(error: CodexWebSocketErrorPayload) {\n super(error.message);\n this.name = 'CodexWebSocketRemoteError';\n this.code = error.code;\n }\n}\n\nexport class CodexWebSocketTransportError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CodexWebSocketTransportError';\n }\n}\n\nconst defaultRequestTimeoutMs = 60_000;\n\nexport function createCodexWebSurfaceClient(\n options: CreateCodexWebSurfaceClientOptions,\n): CodexWebSurfaceClient {\n const transport = new ClientTransport(options);\n const api: Record<string, unknown> = {\n disconnect: (code?: number, reason?: string) => transport.disconnect(code, reason),\n getConnectionState: () => transport.connectionState,\n onEvent: (listener: (event: CodexSurfaceEvent) => void) => transport.onEvent(listener),\n onStateChange: (listener: (snapshot: CodexSurfaceSnapshot) => void) => transport.onStateChange(listener),\n };\n for (const operation of codexSurfaceBridgeOperations) {\n api[operation] = operation === 'connect'\n ? () => transport.connect()\n : (...args: unknown[]) => transport.invoke(operation, args);\n }\n return Object.freeze(api) as CodexWebSurfaceClient;\n}\n\nexport function createCodexBrowserWebSocketPort(socket: WebSocket): CodexWebSocketPort {\n return {\n send: (data) => socket.send(data),\n close: (code, reason) => socket.close(code, reason),\n onMessage: (listener) => listenBrowserSocket(socket, 'message', (event) => listener(event.data)),\n onClose: (listener) => listenBrowserSocket(socket, 'close', (event) => listener({\n code: event.code,\n reason: event.reason,\n wasClean: event.wasClean,\n })),\n onError: (listener) => listenBrowserSocket(socket, 'error', listener),\n };\n}\n\nclass ClientTransport {\n readonly #createSocket: CreateCodexWebSurfaceClientOptions['createSocket'];\n readonly #maxMessageBytes: number;\n readonly #requestTimeoutMs: number;\n readonly #reconnect: Required<CodexWebReconnectOptions> | null;\n readonly #stateListeners = new Set<(snapshot: CodexSurfaceSnapshot) => void>();\n readonly #eventListeners = new Set<(event: CodexSurfaceEvent) => void>();\n readonly #pending = new Map<string, PendingRequest>();\n readonly #socketUnsubscribers: Array<() => void> = [];\n #socket: CodexWebSocketPort | null = null;\n #connectPromise: Promise<CodexSurfaceSnapshot> | null = null;\n #readyWaiter: ReadyWaiter | null = null;\n #latestSnapshot: CodexSurfaceSnapshot | null = null;\n readonly #state = createCodexSurfaceStateMirror();\n #streamingPatches = false;\n #requestSequence = 0;\n #manualClose = false;\n #reconnectAttempts = 0;\n #reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n connectionState: CodexWebSurfaceClientConnectionState = 'disconnected';\n\n constructor(options: CreateCodexWebSurfaceClientOptions) {\n this.#createSocket = options.createSocket;\n this.#maxMessageBytes = positiveWebSocketLimit(\n options.maxMessageBytes,\n defaultCodexWebSocketMaximumMessageBytes,\n 'Codex WebSocket message byte limit',\n );\n this.#requestTimeoutMs = positiveWebSocketLimit(\n options.requestTimeoutMs,\n defaultRequestTimeoutMs,\n 'Codex WebSocket request timeout',\n );\n this.#reconnect = reconnectOptions(options.reconnect);\n }\n\n connect(): Promise<CodexSurfaceSnapshot> {\n this.#manualClose = false;\n this.#clearReconnectTimer();\n if (this.connectionState === 'ready' && this.#latestSnapshot) {\n return Promise.resolve(this.#latestSnapshot);\n }\n return this.#beginConnect();\n }\n\n async invoke<Name extends CodexSurfaceBridgeOperation>(\n operation: Name,\n args: readonly unknown[],\n ): Promise<CodexSurfaceBridgeOperationResult<Name>> {\n await this.connect();\n const socket = this.#socket;\n if (!socket || this.connectionState !== 'ready') {\n throw new CodexWebSocketTransportError('Codex WebSocket is not connected');\n }\n const id = requestId(++this.#requestSequence);\n const result = new Promise<CodexSurfaceBridgeOperationResult<Name>>((resolve, reject) => {\n const timeout = setTimeout(() => {\n this.#pending.delete(id);\n reject(new CodexWebSocketRemoteError({\n code: 'request_timeout',\n message: `Codex WebSocket request '${operation}' timed out`,\n }));\n }, this.#requestTimeoutMs);\n this.#pending.set(id, {\n resolve: resolve as (value: unknown) => void,\n reject,\n timeout,\n });\n });\n try {\n socket.send(encodeCodexWebSocketMessage({\n version: codexWebSocketProtocolVersion,\n type: 'request',\n id,\n operation,\n args: webSocketArguments(args) as CodexSurfaceBridgeOperationArguments<Name>,\n }));\n } catch (error) {\n this.#rejectPending(id, transportError(error));\n }\n return result;\n }\n\n onStateChange(listener: (snapshot: CodexSurfaceSnapshot) => void): () => void {\n this.#stateListeners.add(listener);\n return () => this.#stateListeners.delete(listener);\n }\n\n onEvent(listener: (event: CodexSurfaceEvent) => void): () => void {\n this.#eventListeners.add(listener);\n return () => this.#eventListeners.delete(listener);\n }\n\n disconnect(code = 1000, reason = 'Codex web client disconnected'): void {\n this.#manualClose = true;\n this.#clearReconnectTimer();\n const socket = this.#socket;\n if (socket) socket.close(code, reason);\n this.#handleClose({ code, reason, wasClean: true }, socket);\n this.connectionState = 'closed';\n }\n\n #beginConnect(): Promise<CodexSurfaceSnapshot> {\n if (this.#connectPromise) return this.#connectPromise;\n this.connectionState = 'connecting';\n const connecting = this.#open();\n this.#connectPromise = connecting;\n void connecting.finally(() => {\n if (this.#connectPromise === connecting) this.#connectPromise = null;\n }).catch(() => undefined);\n return connecting;\n }\n\n async #open(): Promise<CodexSurfaceSnapshot> {\n let socket: CodexWebSocketPort;\n try {\n socket = await this.#createSocket();\n } catch (error) {\n this.connectionState = 'disconnected';\n this.#scheduleReconnect();\n throw transportError(error);\n }\n if (this.#manualClose) {\n socket.close(1000, 'Codex web client is closed');\n throw new CodexWebSocketTransportError('Codex web client is closed');\n }\n this.#replaceSocket(socket);\n return new Promise<CodexSurfaceSnapshot>((resolve, reject) => {\n this.#readyWaiter = { socket, resolve, reject };\n });\n }\n\n #replaceSocket(socket: CodexWebSocketPort): void {\n this.#clearSocketListeners();\n this.#socket = socket;\n this.#socketUnsubscribers.push(\n socket.onMessage((data) => this.#receive(data, socket)),\n socket.onClose((close) => this.#handleClose(close, socket)),\n );\n if (socket.onError) {\n this.#socketUnsubscribers.push(socket.onError((error) => {\n this.#handleClose({ reason: errorMessage(error), wasClean: false }, socket);\n }));\n }\n }\n\n #receive(data: unknown, socket: CodexWebSocketPort): void {\n if (socket !== this.#socket || this.#manualClose) return;\n let message: Record<string, unknown>;\n try {\n const value = JSON.parse(codexWebSocketText(data, this.#maxMessageBytes)) as unknown;\n if (!isPlainObject(value) || value.version !== codexWebSocketProtocolVersion) {\n throw new TypeError('Invalid Codex WebSocket response');\n }\n message = value;\n } catch (error) {\n socket.close(4400, 'Invalid Codex WebSocket response');\n this.#handleClose({ code: 4400, reason: errorMessage(error) }, socket);\n return;\n }\n\n if (message.type === 'ready' && isPlainObject(message.snapshot) && isOptionalStateVersion(message.stateVersion)) {\n const snapshot = this.#adoptSnapshot(message.snapshot as CodexSurfaceSnapshot, message.stateVersion);\n this.#streamingPatches = false;\n this.connectionState = 'ready';\n this.#reconnectAttempts = 0;\n this.#emitSnapshot(snapshot);\n const waiter = this.#readyWaiter;\n this.#readyWaiter = null;\n if (waiter?.socket === socket) waiter.resolve(snapshot);\n // Servers that can stream patches advertise a state version; older ones keep sending snapshots.\n if (message.stateVersion !== undefined) this.#enableStatePatches(socket);\n return;\n }\n if (message.type === 'snapshot' && isPlainObject(message.snapshot) && isOptionalStateVersion(message.stateVersion)) {\n this.#emitSnapshot(this.#adoptSnapshot(message.snapshot as CodexSurfaceSnapshot, message.stateVersion));\n return;\n }\n if (message.type === 'statePatch' && this.#streamingPatches && isStatePatch(message.patch)) {\n const result = this.#state.receive(message.patch);\n if (result.status === 'applied') {\n this.#latestSnapshot = result.snapshot;\n this.#emitSnapshot(result.snapshot);\n } else if (result.status === 'resync') {\n // A fresh connection starts from a new versioned snapshot.\n socket.close(4001, 'Codex state stream desynchronized');\n this.#handleClose({ code: 4001, reason: 'Codex state stream desynchronized' }, socket);\n }\n return;\n }\n if (message.type === 'event' && isPlainObject(message.event)) {\n for (const listener of this.#eventListeners) listener(message.event as CodexSurfaceEvent);\n return;\n }\n if (message.type === 'response' && typeof message.id === 'string' && typeof message.ok === 'boolean') {\n const pending = this.#pending.get(message.id);\n if (!pending) return;\n this.#pending.delete(message.id);\n clearTimeout(pending.timeout);\n if (message.ok) {\n pending.resolve(message.result);\n } else if (isRemoteError(message.error)) {\n pending.reject(new CodexWebSocketRemoteError(message.error));\n } else {\n pending.reject(new CodexWebSocketTransportError('Codex WebSocket returned an invalid error'));\n }\n return;\n }\n socket.close(4400, 'Invalid Codex WebSocket response');\n this.#handleClose({ code: 4400, reason: 'Invalid Codex WebSocket response' }, socket);\n }\n\n #handleClose(close: CodexWebSocketClose, socket: CodexWebSocketPort | null): void {\n if (socket && socket !== this.#socket) return;\n if (socket === this.#socket) this.#socket = null;\n this.#clearSocketListeners();\n const error = new CodexWebSocketTransportError(\n close.reason?.trim() || `Codex WebSocket closed${close.code ? ` (${close.code})` : ''}`,\n );\n const waiter = this.#readyWaiter;\n this.#readyWaiter = null;\n if (waiter && (!socket || waiter.socket === socket)) waiter.reject(error);\n for (const id of [...this.#pending.keys()]) this.#rejectPending(id, error);\n if (this.#manualClose) {\n this.connectionState = 'closed';\n return;\n }\n this.connectionState = 'disconnected';\n if (shouldReconnect(close)) this.#scheduleReconnect();\n }\n\n #adoptSnapshot(snapshot: CodexSurfaceSnapshot, stateVersion: number | undefined): CodexSurfaceSnapshot {\n const adopted = stateVersion === undefined\n ? snapshot\n : this.#state.reset({ version: stateVersion, snapshot });\n this.#latestSnapshot = adopted;\n return adopted;\n }\n\n #enableStatePatches(socket: CodexWebSocketPort): void {\n try {\n socket.send(encodeCodexWebSocketMessage({ version: codexWebSocketProtocolVersion, type: 'enableStatePatches' }));\n this.#streamingPatches = true;\n } catch {\n // The session simply stays on snapshots.\n }\n }\n\n #emitSnapshot(snapshot: CodexSurfaceSnapshot): void {\n for (const listener of this.#stateListeners) listener(snapshot);\n }\n\n #rejectPending(id: string, error: Error): void {\n const pending = this.#pending.get(id);\n if (!pending) return;\n this.#pending.delete(id);\n clearTimeout(pending.timeout);\n pending.reject(error);\n }\n\n #scheduleReconnect(): void {\n const options = this.#reconnect;\n if (!options || this.#manualClose || this.#reconnectTimer) return;\n if (this.#reconnectAttempts >= options.maxAttempts) return;\n const delay = Math.min(\n options.initialDelayMs * (2 ** this.#reconnectAttempts),\n options.maximumDelayMs,\n );\n this.#reconnectAttempts += 1;\n this.#reconnectTimer = setTimeout(() => {\n this.#reconnectTimer = null;\n void this.#beginConnect().catch(() => undefined);\n }, delay);\n }\n\n #clearReconnectTimer(): void {\n if (!this.#reconnectTimer) return;\n clearTimeout(this.#reconnectTimer);\n this.#reconnectTimer = null;\n }\n\n #clearSocketListeners(): void {\n for (const unsubscribe of this.#socketUnsubscribers.splice(0)) unsubscribe();\n }\n}\n\ntype PendingRequest = {\n resolve(value: unknown): void;\n reject(error: unknown): void;\n timeout: ReturnType<typeof setTimeout>;\n};\n\ntype ReadyWaiter = {\n socket: CodexWebSocketPort;\n resolve(snapshot: CodexSurfaceSnapshot): void;\n reject(error: unknown): void;\n};\n\nfunction listenBrowserSocket<Type extends keyof WebSocketEventMap>(\n socket: WebSocket,\n type: Type,\n listener: (event: WebSocketEventMap[Type]) => void,\n): () => void {\n socket.addEventListener(type, listener);\n return () => socket.removeEventListener(type, listener);\n}\n\nfunction reconnectOptions(\n value: CreateCodexWebSurfaceClientOptions['reconnect'],\n): Required<CodexWebReconnectOptions> | null {\n if (!value) return null;\n const options = value === true ? {} : value;\n return {\n maxAttempts: nonNegativeInteger(options.maxAttempts, 8, 'Reconnect maximum attempts'),\n initialDelayMs: positiveWebSocketLimit(options.initialDelayMs, 250, 'Reconnect initial delay'),\n maximumDelayMs: positiveWebSocketLimit(options.maximumDelayMs, 5_000, 'Reconnect maximum delay'),\n };\n}\n\nfunction nonNegativeInteger(value: number | undefined, fallback: number, label: string): number {\n if (value === undefined) return fallback;\n if (!Number.isSafeInteger(value) || value < 0) throw new TypeError(`${label} must be a non-negative integer`);\n return value;\n}\n\nfunction shouldReconnect(close: CodexWebSocketClose): boolean {\n if (close.code === 1000) return false;\n return close.code === undefined || close.code < 4400 || close.code > 4499;\n}\n\nfunction requestId(sequence: number): string {\n const random = globalThis.crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2);\n return `codex-${sequence}-${random}`;\n}\n\nfunction webSocketArguments(args: readonly unknown[]): unknown[] {\n let length = args.length;\n while (length > 0 && args[length - 1] === undefined) length -= 1;\n return args.slice(0, length);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value) as object | null;\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isOptionalStateVersion(value: unknown): value is number | undefined {\n return value === undefined || Number.isSafeInteger(value);\n}\n\nfunction isStatePatch(value: unknown): value is CodexSurfaceStatePatch {\n return isPlainObject(value) && Number.isSafeInteger(value.version) && Array.isArray(value.changes);\n}\n\nfunction isRemoteError(value: unknown): value is CodexWebSocketErrorPayload {\n if (!isPlainObject(value) || typeof value.message !== 'string') return false;\n return value.code === 'invalid_request'\n || value.code === 'operation_failed'\n || value.code === 'request_timeout'\n || value.code === 'transport_closed';\n}\n\nfunction transportError(error: unknown): CodexWebSocketTransportError {\n return error instanceof CodexWebSocketTransportError\n ? error\n : new CodexWebSocketTransportError(errorMessage(error));\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nexport type {\n CodexWebSocketClose,\n CodexWebSocketPort,\n} from './socket-port';\n"],"mappings":";;;;AAoDA,IAAa,IAAb,cAA+C,MAAM;CACnD;CAEA,YAAY,GAAmC;EAG7C,AAFA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AS,EAAc,GAAqD;CAE1E,OADI,CAAC,EAAc,CAAK,KAAK,OAAO,EAAM,WAAY,WAAiB,KAChE,EAAM,SAAS,qBACjB,EAAM,SAAS,sBACf,EAAM,SAAS,qBACf,EAAM,SAAS;AACtB;AAEA,SAAS,EAAe,GAA8C;CACpE,OAAO,aAAiB,IACpB,IACA,IAAI,EAA6B,EAAa,CAAK,CAAC;AAC1D;AAEA,SAAS,EAAa,GAAwB;CAC5C,OAAO,aAAiB,QAAQ,EAAM,UAAU,OAAO,CAAK;AAC9D"}
@@ -0,0 +1,4 @@
1
+ export { createCodexBrowserWebSocketPort, createCodexWebSurfaceClient, CodexWebSocketRemoteError, CodexWebSocketTransportError, type CodexWebReconnectOptions, type CodexWebSocketClose, type CodexWebSocketPort, type CodexWebSurfaceClient, type CodexWebSurfaceClientConnectionState, type CreateCodexWebSurfaceClientOptions, } from './client';
2
+ export { bindCodexWebSocket, createCodexNodeWebSocketPort, isAllowedCodexWebSocketOrigin, type BindCodexWebSocketOptions, type CodexWebSocketBinding, type CodexNodeWebSocketLike, type CodexWebSocketSessionLease, type CodexWebSocketSessionRelease, type CodexWebSocketUpgradeRequest, } from './server';
3
+ export { codexWebSocketProtocolVersion, encodeCodexWebSocketMessage, type CodexWebSocketClientMessage, type CodexWebSocketErrorPayload, type CodexWebSocketEvent, type CodexWebSocketFailure, type CodexWebSocketReady, type CodexWebSocketRequest, type CodexWebSocketServerMessage, type CodexWebSocketEnableStatePatches, type CodexWebSocketSnapshot, type CodexWebSocketStatePatch, type CodexWebSocketSuccess, } from './protocol';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,2BAA2B,EAC3B,yBAAyB,EACzB,4BAA4B,EAC5B,KAAK,wBAAwB,EAC7B,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,EACvB,KAAK,qBAAqB,EAC1B,KAAK,oCAAoC,EACzC,KAAK,kCAAkC,GACxC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,kBAAkB,EAClB,4BAA4B,EAC5B,6BAA6B,EAC7B,KAAK,yBAAyB,EAC9B,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,EAC3B,KAAK,0BAA0B,EAC/B,KAAK,4BAA4B,EACjC,KAAK,4BAA4B,GAClC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,6BAA6B,EAC7B,2BAA2B,EAC3B,KAAK,2BAA2B,EAChC,KAAK,0BAA0B,EAC/B,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,2BAA2B,EAChC,KAAK,gCAAgC,EACrC,KAAK,sBAAsB,EAC3B,KAAK,wBAAwB,EAC7B,KAAK,qBAAqB,GAC3B,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ import { codexWebSocketProtocolVersion as e, encodeCodexWebSocketMessage as t } from "./protocol.js";
2
+ import { CodexWebSocketRemoteError as n, CodexWebSocketTransportError as r, createCodexBrowserWebSocketPort as i, createCodexWebSurfaceClient as a } from "./client.js";
3
+ import { bindCodexWebSocket as o, createCodexNodeWebSocketPort as s, isAllowedCodexWebSocketOrigin as c } from "./server.js";
4
+ export { n as CodexWebSocketRemoteError, r as CodexWebSocketTransportError, o as bindCodexWebSocket, e as codexWebSocketProtocolVersion, i as createCodexBrowserWebSocketPort, s as createCodexNodeWebSocketPort, a as createCodexWebSurfaceClient, t as encodeCodexWebSocketMessage, c as isAllowedCodexWebSocketOrigin };
@@ -0,0 +1,66 @@
1
+ import type { CodexSurfaceBridgeOperation, CodexSurfaceBridgeOperationResult } from '@codex-app-sdk/core/surface-bridge';
2
+ import type { CodexSurfaceEvent, CodexSurfaceSnapshot, CodexSurfaceStatePatch } from '@codex-app-sdk/core/surface';
3
+ export declare const codexWebSocketProtocolVersion: 1;
4
+ export type CodexWebSocketRequest = {
5
+ version: typeof codexWebSocketProtocolVersion;
6
+ type: 'request';
7
+ id: string;
8
+ operation: CodexSurfaceBridgeOperation;
9
+ args: unknown[];
10
+ };
11
+ export type CodexWebSocketReady = {
12
+ version: typeof codexWebSocketProtocolVersion;
13
+ type: 'ready';
14
+ snapshot: CodexSurfaceSnapshot;
15
+ /**
16
+ * Present when the server can stream state patches. A client that supports
17
+ * them answers with `enableStatePatches`; others ignore it and keep
18
+ * receiving `snapshot` messages.
19
+ */
20
+ stateVersion?: number;
21
+ };
22
+ export type CodexWebSocketSuccess<Name extends CodexSurfaceBridgeOperation = CodexSurfaceBridgeOperation> = {
23
+ version: typeof codexWebSocketProtocolVersion;
24
+ type: 'response';
25
+ id: string;
26
+ ok: true;
27
+ result: CodexSurfaceBridgeOperationResult<Name>;
28
+ };
29
+ export type CodexWebSocketErrorPayload = {
30
+ code: 'invalid_request' | 'operation_failed' | 'request_timeout' | 'transport_closed';
31
+ message: string;
32
+ };
33
+ export type CodexWebSocketFailure = {
34
+ version: typeof codexWebSocketProtocolVersion;
35
+ type: 'response';
36
+ id: string;
37
+ ok: false;
38
+ error: CodexWebSocketErrorPayload;
39
+ };
40
+ export type CodexWebSocketSnapshot = {
41
+ version: typeof codexWebSocketProtocolVersion;
42
+ type: 'snapshot';
43
+ snapshot: CodexSurfaceSnapshot;
44
+ /** Present on the base snapshot that starts a patch stream; patches continue from it. */
45
+ stateVersion?: number;
46
+ };
47
+ export type CodexWebSocketEvent = {
48
+ version: typeof codexWebSocketProtocolVersion;
49
+ type: 'event';
50
+ event: CodexSurfaceEvent;
51
+ };
52
+ /** Client opt-in, sent only after a `ready` that carries `stateVersion`. */
53
+ export type CodexWebSocketEnableStatePatches = {
54
+ version: typeof codexWebSocketProtocolVersion;
55
+ type: 'enableStatePatches';
56
+ };
57
+ /** Sent instead of `snapshot` once a client has enabled state patches. */
58
+ export type CodexWebSocketStatePatch = {
59
+ version: typeof codexWebSocketProtocolVersion;
60
+ type: 'statePatch';
61
+ patch: CodexSurfaceStatePatch;
62
+ };
63
+ export type CodexWebSocketClientMessage = CodexWebSocketRequest;
64
+ export type CodexWebSocketServerMessage = CodexWebSocketReady | CodexWebSocketSuccess | CodexWebSocketFailure | CodexWebSocketSnapshot | CodexWebSocketEvent;
65
+ export declare function encodeCodexWebSocketMessage(message: CodexWebSocketClientMessage | CodexWebSocketServerMessage | CodexWebSocketEnableStatePatches | CodexWebSocketStatePatch): string;
66
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,2BAA2B,EAC3B,iCAAiC,EAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,KAAK,EACV,iBAAiB,EACjB,oBAAoB,EACpB,sBAAsB,EACvB,MAAM,6BAA6B,CAAC;AAErC,eAAO,MAAM,6BAA6B,EAAG,CAAU,CAAC;AAExD,MAAM,MAAM,qBAAqB,GAAG;IAClC,OAAO,EAAE,OAAO,6BAA6B,CAAC;IAC9C,IAAI,EAAE,SAAS,CAAC;IAChB,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,2BAA2B,CAAC;IACvC,IAAI,EAAE,OAAO,EAAE,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IAChC,OAAO,EAAE,OAAO,6BAA6B,CAAC;IAC9C,IAAI,EAAE,OAAO,CAAC;IACd,QAAQ,EAAE,oBAAoB,CAAC;IAC/B;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,qBAAqB,CAAC,IAAI,SAAS,2BAA2B,GAAG,2BAA2B,IAAI;IAC1G,OAAO,EAAE,OAAO,6BAA6B,CAAC;IAC9C,IAAI,EAAE,UAAU,CAAC;IACjB,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,I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AAgB,2BAA2B,CACzC,OAAO,EACH,2BAA2B,GAC3B,2BAA2B,GAC3B,gCAAgC,GAChC,wBAAwB,GAC3B,MAAM,CAER"}
@@ -0,0 +1,9 @@
1
+ //#region src/protocol.ts
2
+ var e = 1;
3
+ function t(e) {
4
+ return JSON.stringify(e);
5
+ }
6
+ //#endregion
7
+ export { e as codexWebSocketProtocolVersion, t as encodeCodexWebSocketMessage };
8
+
9
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","names":[],"sources":["../src/protocol.ts"],"sourcesContent":["import type {\n CodexSurfaceBridgeOperation,\n CodexSurfaceBridgeOperationResult,\n} from '@codex-app-sdk/core/surface-bridge';\nimport type {\n CodexSurfaceEvent,\n CodexSurfaceSnapshot,\n CodexSurfaceStatePatch,\n} from '@codex-app-sdk/core/surface';\n\nexport const codexWebSocketProtocolVersion = 1 as const;\n\nexport type CodexWebSocketRequest = {\n version: typeof codexWebSocketProtocolVersion;\n type: 'request';\n id: string;\n operation: CodexSurfaceBridgeOperation;\n args: unknown[];\n};\n\nexport type CodexWebSocketReady = {\n version: typeof codexWebSocketProtocolVersion;\n type: 'ready';\n snapshot: CodexSurfaceSnapshot;\n /**\n * Present when the server can stream state patches. A client that supports\n * them answers with `enableStatePatches`; others ignore it and keep\n * receiving `snapshot` messages.\n */\n stateVersion?: number;\n};\n\nexport type CodexWebSocketSuccess<Name extends CodexSurfaceBridgeOperation = CodexSurfaceBridgeOperation> = {\n version: typeof codexWebSocketProtocolVersion;\n type: 'response';\n id: string;\n ok: true;\n result: CodexSurfaceBridgeOperationResult<Name>;\n};\n\nexport type CodexWebSocketErrorPayload = {\n code: 'invalid_request' | 'operation_failed' | 'request_timeout' | 'transport_closed';\n message: string;\n};\n\nexport type CodexWebSocketFailure = {\n version: typeof codexWebSocketProtocolVersion;\n type: 'response';\n id: string;\n ok: false;\n error: CodexWebSocketErrorPayload;\n};\n\nexport type CodexWebSocketSnapshot = {\n version: typeof codexWebSocketProtocolVersion;\n type: 'snapshot';\n snapshot: CodexSurfaceSnapshot;\n /** Present on the base snapshot that starts a patch stream; patches continue from it. */\n stateVersion?: number;\n};\n\nexport type CodexWebSocketEvent = {\n version: typeof codexWebSocketProtocolVersion;\n type: 'event';\n event: CodexSurfaceEvent;\n};\n\n/** Client opt-in, sent only after a `ready` that carries `stateVersion`. */\nexport type CodexWebSocketEnableStatePatches = {\n version: typeof codexWebSocketProtocolVersion;\n type: 'enableStatePatches';\n};\n\n/** Sent instead of `snapshot` once a client has enabled state patches. */\nexport type CodexWebSocketStatePatch = {\n version: typeof codexWebSocketProtocolVersion;\n type: 'statePatch';\n patch: CodexSurfaceStatePatch;\n};\n\nexport type CodexWebSocketClientMessage = CodexWebSocketRequest;\nexport type CodexWebSocketServerMessage =\n | CodexWebSocketReady\n | CodexWebSocketSuccess\n | CodexWebSocketFailure\n | CodexWebSocketSnapshot\n | CodexWebSocketEvent;\n\nexport function encodeCodexWebSocketMessage(\n message:\n | CodexWebSocketClientMessage\n | CodexWebSocketServerMessage\n | CodexWebSocketEnableStatePatches\n | CodexWebSocketStatePatch,\n): string {\n return JSON.stringify(message);\n}\n"],"mappings":";AAUA,IAAa,IAAgC;AA8E7C,SAAgB,EACd,GAKQ;CACR,OAAO,KAAK,UAAU,CAAO;AAC/B"}
@@ -0,0 +1,56 @@
1
+ import { type CodexSurfaceBridgeAttachmentResolver, type CodexSurfaceBridgeTarget } from '@codex-app-sdk/core/surface-bridge';
2
+ import { type CodexSurfaceStatePatchSource } from '@codex-app-sdk/core/surface-bridge';
3
+ import { type CodexWebSocketClose, type CodexWebSocketPort } from './socket-port';
4
+ type Awaitable<Value> = Value | Promise<Value>;
5
+ export type CodexWebSocketSessionRelease = {
6
+ reason: 'authorization_failed' | 'server_closed' | 'socket_closed' | 'surface_failed';
7
+ close?: CodexWebSocketClose;
8
+ error?: unknown;
9
+ };
10
+ /** A host-authorized, connection-scoped lease. The host owns its lifecycle and isolation policy. */
11
+ export type CodexWebSocketSessionLease = {
12
+ /** A `CodexSurface` can stream state patches to clients that opt in; other targets send snapshots. */
13
+ surface: CodexSurfaceBridgeTarget & Partial<CodexSurfaceStatePatchSource>;
14
+ resolveAttachment?: CodexSurfaceBridgeAttachmentResolver;
15
+ release?(context: CodexWebSocketSessionRelease): Awaitable<void>;
16
+ };
17
+ export type BindCodexWebSocketOptions<Context> = {
18
+ socket: CodexWebSocketPort;
19
+ context: Context;
20
+ authorize(context: Context): Awaitable<CodexWebSocketSessionLease | null>;
21
+ maxMessageBytes?: number;
22
+ };
23
+ export type CodexWebSocketBinding = {
24
+ /** Resolves after authorization and the initial surface snapshot have been sent. */
25
+ ready: Promise<void>;
26
+ close(code?: number, reason?: string): Promise<void>;
27
+ };
28
+ /** The small EventEmitter-style subset implemented by the popular `ws` package. */
29
+ export type CodexNodeWebSocketLike = {
30
+ send(data: string): void;
31
+ close(code?: number, reason?: string): void;
32
+ on(event: 'message', listener: (data: unknown) => void): unknown;
33
+ on(event: 'close', listener: (code: number, reason: unknown) => void): unknown;
34
+ on(event: 'error', listener: (error: unknown) => void): unknown;
35
+ };
36
+ /** The header subset of a Node `IncomingMessage` (or equivalent) needed to check a WebSocket upgrade. */
37
+ export type CodexWebSocketUpgradeRequest = {
38
+ headers: Readonly<Record<string, string | readonly string[] | undefined>>;
39
+ };
40
+ /**
41
+ * Returns true only when a WebSocket upgrade carries exactly one `Origin`
42
+ * header matching one of `allowedOrigins`. Browsers do not apply the
43
+ * same-origin policy to WebSockets, so a host that skips this check lets any
44
+ * website the user visits drive its Codex surface. Requests without an
45
+ * `Origin` header are rejected.
46
+ */
47
+ export declare function isAllowedCodexWebSocketOrigin(request: CodexWebSocketUpgradeRequest, allowedOrigins: readonly string[]): boolean;
48
+ /**
49
+ * Binds an established socket to a required host authorization callback.
50
+ * HTTP upgrades, cookies, user lookup, runner pooling, and Express integration stay host-owned.
51
+ */
52
+ export declare function bindCodexWebSocket<Context>(options: BindCodexWebSocketOptions<Context>): CodexWebSocketBinding;
53
+ /** Adapts a `ws`-style socket without importing or depending on that library. */
54
+ export declare function createCodexNodeWebSocketPort(socket: CodexNodeWebSocketLike): CodexWebSocketPort;
55
+ export type { CodexWebSocketClose, CodexWebSocketPort, } from './socket-port';
56
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,oCAAoC,EACzC,KAAK,wBAAwB,EAC9B,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EAEL,KAAK,4BAA4B,EAClC,MAAM,oCAAoC,CAAC;AAS5C,OAAO,EAIL,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,EACxB,MAAM,eAAe,CAAC;AAEvB,KAAK,SAAS,CAAC,KAAK,IAAI,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;AAE/C,MAAM,MAAM,4BAA4B,GAAG;IACzC,MAAM,EAAE,sBAAsB,GAAG,eAAe,GAAG,eAAe,GAAG,gBAAgB,CAAC;IACtF,KAAK,CAAC,EAAE,mBAAmB,CAAC;IAC5B,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF,oGAAoG;AACpG,MAAM,MAAM,0BAA0B,GAAG;IACvC,sGAAsG;IACtG,OAAO,EAAE,wBAAwB,GAAG,OAAO,CAAC,4BAA4B,CAAC,CAAC;IAC1E,iBAAiB,CAAC,EAAE,oCAAoC,CAAC;IACzD,OAAO,CAAC,CAAC,OAAO,EAAE,4BAA4B,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;CAClE,CAAC;AAEF,MAAM,MAAM,yBAAyB,CAAC,OAAO,IAAI;IAC/C,MAAM,EAAE,kBAAkB,CAAC;IAC3B,OAAO,EAAE,OAAO,CAAC;IACjB,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,SAAS,CAAC,0BAA0B,GAAG,IAAI,CAAC,CAAC;IAC1E,eAA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AAiF;AACjF,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,sBAAsB,GAAG,kBAAkB,CAW/F;AAoTD,YAAY,EACV,mBAAmB,EACnB,kBAAkB,GACnB,MAAM,eAAe,CAAC"}
package/dist/server.js ADDED
@@ -0,0 +1,271 @@
1
+ import { encodeCodexWebSocketMessage as e } from "./protocol.js";
2
+ import { n as t, r as n, t as r } from "./chunks/socket-port-QOPQStPy.js";
3
+ import { invokeCodexSurfaceBridgeOperation as i, isCodexSurfaceBridgeOperation as a, isCodexSurfaceStatePatchSource as o } from "@codex-app-sdk/core/surface-bridge";
4
+ //#region src/server.ts
5
+ function s(e, t) {
6
+ let n = e.headers.origin;
7
+ if (typeof n != "string") return !1;
8
+ let r = v(n);
9
+ return r ? t.some((e) => {
10
+ let t = v(e);
11
+ if (!t) throw TypeError(`Invalid allowed Codex WebSocket origin: ${e}`);
12
+ return t === r;
13
+ }) : !1;
14
+ }
15
+ function c(e) {
16
+ return new u(e);
17
+ }
18
+ function l(e) {
19
+ return {
20
+ send: (t) => e.send(t),
21
+ close: (t, n) => e.close(t, n),
22
+ onMessage: (t) => _(e, "message", t),
23
+ onClose: (t) => _(e, "close", (e, n) => t({
24
+ code: typeof e == "number" ? e : void 0,
25
+ reason: y(n)
26
+ })),
27
+ onError: (t) => _(e, "error", t)
28
+ };
29
+ }
30
+ var u = class {
31
+ ready;
32
+ #e;
33
+ #t;
34
+ #n;
35
+ #r;
36
+ #i = [];
37
+ #a = null;
38
+ #o = Promise.resolve();
39
+ #s = !1;
40
+ #c = !1;
41
+ #l = null;
42
+ #u = null;
43
+ #d = null;
44
+ #f = "off";
45
+ #p = [];
46
+ constructor(e) {
47
+ this.#e = e.socket, this.#t = e.context, this.#n = e.authorize, this.#r = n(e.maxMessageBytes, t, "Codex WebSocket message byte limit"), this.#i.push(this.#e.onMessage((e) => this.#h(e)), this.#e.onClose((e) => {
48
+ this.#y({
49
+ reason: "socket_closed",
50
+ close: e
51
+ });
52
+ })), this.#e.onError && this.#i.push(this.#e.onError((e) => {
53
+ this.#y({
54
+ reason: "socket_closed",
55
+ error: e
56
+ });
57
+ })), this.ready = this.#m();
58
+ }
59
+ async close(e = 1e3, t = "Codex web session closed") {
60
+ this.#c || this.#e.close(e, t), await this.#y({
61
+ reason: "server_closed",
62
+ close: {
63
+ code: e,
64
+ reason: t,
65
+ wasClean: !0
66
+ }
67
+ });
68
+ }
69
+ async #m() {
70
+ try {
71
+ let e = await this.#n(this.#t);
72
+ if (!e) throw this.#e.close(4401, "Unauthorized"), await this.#y({ reason: "authorization_failed" }), Error("Codex WebSocket authorization was denied");
73
+ if (this.#c) {
74
+ await e.release?.({ reason: "socket_closed" });
75
+ return;
76
+ }
77
+ this.#a = e;
78
+ let t = o(e.surface) ? e.surface : null;
79
+ this.#i.push(e.surface.onStateChange((e) => {
80
+ this.#s && this.#f === "off" && this.#v({
81
+ version: 1,
82
+ type: "snapshot",
83
+ snapshot: e
84
+ });
85
+ }), e.surface.onEvent((e) => {
86
+ this.#s && this.#v({
87
+ version: 1,
88
+ type: "event",
89
+ event: e
90
+ });
91
+ })), t && this.#i.push(t.onStatePatch((e) => {
92
+ this.#f === "on" ? this.#v(d(e)) : this.#f === "starting" && this.#p.push(e);
93
+ }));
94
+ let n = await e.surface.connect(), r = t ? await t.getVersionedSnapshot() : null;
95
+ if (this.#c) return;
96
+ this.#u = r ? t : null, this.#d = r?.version ?? null, this.#v({
97
+ version: 1,
98
+ type: "ready",
99
+ ...r ? {
100
+ snapshot: r.snapshot,
101
+ stateVersion: r.version
102
+ } : { snapshot: n }
103
+ }), this.#s = !0;
104
+ } catch (e) {
105
+ throw this.#c || (this.#e.close(1011, "Codex web session initialization failed"), await this.#y({
106
+ reason: "surface_failed",
107
+ error: e
108
+ })), e;
109
+ }
110
+ }
111
+ #h(e) {
112
+ if (this.#c) return;
113
+ if (!this.#s) {
114
+ this.#e.close(4400, "Request received before the session was ready"), this.#y({
115
+ reason: "socket_closed",
116
+ close: { code: 4400 }
117
+ });
118
+ return;
119
+ }
120
+ let t;
121
+ try {
122
+ if (t = f(r(e, this.#r)), t === "enableStatePatches" && (!this.#u || this.#f !== "off")) throw TypeError("State patches cannot be enabled for this session");
123
+ } catch {
124
+ this.#e.close(4400, "Invalid Codex WebSocket request"), this.#y({
125
+ reason: "socket_closed",
126
+ close: { code: 4400 }
127
+ });
128
+ return;
129
+ }
130
+ if (t === "enableStatePatches") {
131
+ this.#g();
132
+ return;
133
+ }
134
+ this.#o = this.#o.then(() => this.#_(t));
135
+ }
136
+ async #g() {
137
+ let e = this.#u;
138
+ this.#f = "starting";
139
+ let t;
140
+ try {
141
+ t = await e.getVersionedSnapshot();
142
+ } catch {
143
+ t = null;
144
+ }
145
+ if (!this.#c) {
146
+ if (!t) {
147
+ this.#e.close(1011, "Codex state stream unavailable"), this.#y({ reason: "surface_failed" });
148
+ return;
149
+ }
150
+ t.version !== this.#d && this.#v({
151
+ version: 1,
152
+ type: "snapshot",
153
+ snapshot: t.snapshot,
154
+ stateVersion: t.version
155
+ }), this.#f = "on";
156
+ for (let e of this.#p.splice(0)) e.version > t.version && this.#v(d(e));
157
+ }
158
+ }
159
+ async #_(e) {
160
+ let t = this.#a;
161
+ if (!(!t || this.#c)) try {
162
+ let n = await i(t.surface, e.operation, e.args, t.resolveAttachment ? { resolveAttachment: t.resolveAttachment } : {});
163
+ this.#v({
164
+ version: 1,
165
+ type: "response",
166
+ id: e.id,
167
+ ok: !0,
168
+ result: n
169
+ });
170
+ } catch (t) {
171
+ this.#v(p(e.id, t instanceof TypeError || t instanceof RangeError ? "invalid_request" : "operation_failed", g(t)));
172
+ }
173
+ }
174
+ #v(t) {
175
+ if (!this.#c) try {
176
+ let n = e(t);
177
+ if (new TextEncoder().encode(n).byteLength > this.#r) throw RangeError("Codex WebSocket response exceeds the configured byte limit");
178
+ this.#e.send(n);
179
+ } catch (e) {
180
+ this.#e.close(1011, "Codex WebSocket response failed"), this.#y({
181
+ reason: "socket_closed",
182
+ error: e
183
+ });
184
+ }
185
+ }
186
+ #y(e) {
187
+ if (this.#l) return this.#l;
188
+ this.#c = !0, this.#s = !1;
189
+ for (let e of this.#i.splice(0)) e();
190
+ let t = this.#a;
191
+ return this.#a = null, this.#l = Promise.resolve(t?.release?.(e)).then(() => void 0), this.#l;
192
+ }
193
+ };
194
+ function d(e) {
195
+ return {
196
+ version: 1,
197
+ type: "statePatch",
198
+ patch: e
199
+ };
200
+ }
201
+ function f(e) {
202
+ let t = JSON.parse(e);
203
+ if (!m(t)) throw TypeError("Codex WebSocket request must be an object");
204
+ if (t.type === "enableStatePatches") {
205
+ if (h(t, ["version", "type"]), t.version !== 1) throw TypeError("Codex WebSocket version is invalid");
206
+ return "enableStatePatches";
207
+ }
208
+ if (h(t, [
209
+ "version",
210
+ "type",
211
+ "id",
212
+ "operation",
213
+ "args"
214
+ ]), t.version !== 1 || t.type !== "request") throw TypeError("Codex WebSocket request version or type is invalid");
215
+ if (typeof t.id != "string" || !t.id.trim() || t.id.length > 128) throw TypeError("Codex WebSocket request id is invalid");
216
+ if (!a(t.operation)) throw TypeError("Codex WebSocket operation is invalid");
217
+ if (!Array.isArray(t.args)) throw TypeError("Codex WebSocket request args must be an array");
218
+ return {
219
+ version: 1,
220
+ type: "request",
221
+ id: t.id,
222
+ operation: t.operation,
223
+ args: t.args
224
+ };
225
+ }
226
+ function p(e, t, n) {
227
+ return {
228
+ version: 1,
229
+ type: "response",
230
+ id: e,
231
+ ok: !1,
232
+ error: {
233
+ code: t,
234
+ message: n.slice(0, 2e3)
235
+ }
236
+ };
237
+ }
238
+ function m(e) {
239
+ if (!e || typeof e != "object" || Array.isArray(e)) return !1;
240
+ let t = Object.getPrototypeOf(e);
241
+ return t === Object.prototype || t === null;
242
+ }
243
+ function h(e, t) {
244
+ let n = new Set(t);
245
+ if (Reflect.ownKeys(e).some((e) => typeof e != "string" || !n.has(e))) throw TypeError("Codex WebSocket request contains unsupported properties");
246
+ }
247
+ function g(e) {
248
+ return e instanceof Error ? e.message : String(e);
249
+ }
250
+ function _(e, t, n) {
251
+ return t === "message" && e.on(t, n), t === "close" && e.on(t, n), t === "error" && e.on(t, n), () => {
252
+ let r = e;
253
+ r.off ? r.off(t, n) : r.removeListener?.(t, n);
254
+ };
255
+ }
256
+ function v(e) {
257
+ try {
258
+ let { origin: t } = new URL(e.trim());
259
+ return t === "null" ? null : t;
260
+ } catch {
261
+ return null;
262
+ }
263
+ }
264
+ function y(e) {
265
+ if (typeof e == "string") return e;
266
+ if (e instanceof ArrayBuffer || ArrayBuffer.isView(e)) return new TextDecoder().decode(e).trim() || void 0;
267
+ }
268
+ //#endregion
269
+ export { c as bindCodexWebSocket, l as createCodexNodeWebSocketPort, s as isAllowedCodexWebSocketOrigin };
270
+
271
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","names":["#socket","#context","#authorize","#maxMessageBytes","#unsubscribers","#pendingPatches","#receive","#finish","#initialize","#finished","#lease","#acceptingRequests","#patchMode","#send","#patchSource","#readyStateVersion","#enableStatePatches","#requestQueue","#handle","#releasePromise"],"sources":["../src/server.ts"],"sourcesContent":["import {\n invokeCodexSurfaceBridgeOperation,\n isCodexSurfaceBridgeOperation,\n type CodexSurfaceBridgeAttachmentResolver,\n type CodexSurfaceBridgeTarget,\n} from '@codex-app-sdk/core/surface-bridge';\nimport type { CodexSurfaceStatePatch } from '@codex-app-sdk/core/surface';\nimport {\n isCodexSurfaceStatePatchSource,\n type CodexSurfaceStatePatchSource,\n} from '@codex-app-sdk/core/surface-bridge';\nimport {\n codexWebSocketProtocolVersion,\n encodeCodexWebSocketMessage,\n type CodexWebSocketFailure,\n type CodexWebSocketRequest,\n type CodexWebSocketServerMessage,\n type CodexWebSocketStatePatch,\n} from './protocol';\nimport {\n codexWebSocketText,\n defaultCodexWebSocketMaximumMessageBytes,\n positiveWebSocketLimit,\n type CodexWebSocketClose,\n type CodexWebSocketPort,\n} from './socket-port';\n\ntype Awaitable<Value> = Value | Promise<Value>;\n\nexport type CodexWebSocketSessionRelease = {\n reason: 'authorization_failed' | 'server_closed' | 'socket_closed' | 'surface_failed';\n close?: CodexWebSocketClose;\n error?: unknown;\n};\n\n/** A host-authorized, connection-scoped lease. The host owns its lifecycle and isolation policy. */\nexport type CodexWebSocketSessionLease = {\n /** A `CodexSurface` can stream state patches to clients that opt in; other targets send snapshots. */\n surface: CodexSurfaceBridgeTarget & Partial<CodexSurfaceStatePatchSource>;\n resolveAttachment?: CodexSurfaceBridgeAttachmentResolver;\n release?(context: CodexWebSocketSessionRelease): Awaitable<void>;\n};\n\nexport type BindCodexWebSocketOptions<Context> = {\n socket: CodexWebSocketPort;\n context: Context;\n authorize(context: Context): Awaitable<CodexWebSocketSessionLease | null>;\n maxMessageBytes?: number;\n};\n\nexport type CodexWebSocketBinding = {\n /** Resolves after authorization and the initial surface snapshot have been sent. */\n ready: Promise<void>;\n close(code?: number, reason?: string): Promise<void>;\n};\n\n/** The small EventEmitter-style subset implemented by the popular `ws` package. */\nexport type CodexNodeWebSocketLike = {\n send(data: string): void;\n close(code?: number, reason?: string): void;\n on(event: 'message', listener: (data: unknown) => void): unknown;\n on(event: 'close', listener: (code: number, reason: unknown) => void): unknown;\n on(event: 'error', listener: (error: unknown) => void): unknown;\n};\n\n/** The header subset of a Node `IncomingMessage` (or equivalent) needed to check a WebSocket upgrade. */\nexport type CodexWebSocketUpgradeRequest = {\n headers: Readonly<Record<string, string | readonly string[] | undefined>>;\n};\n\n/**\n * Returns true only when a WebSocket upgrade carries exactly one `Origin`\n * header matching one of `allowedOrigins`. Browsers do not apply the\n * same-origin policy to WebSockets, so a host that skips this check lets any\n * website the user visits drive its Codex surface. Requests without an\n * `Origin` header are rejected.\n */\nexport function isAllowedCodexWebSocketOrigin(\n request: CodexWebSocketUpgradeRequest,\n allowedOrigins: readonly string[],\n): boolean {\n const origin = request.headers.origin;\n if (typeof origin !== 'string') return false;\n const requestOrigin = normalizedOrigin(origin);\n if (!requestOrigin) return false;\n return allowedOrigins.some((allowedOrigin) => {\n const allowed = normalizedOrigin(allowedOrigin);\n if (!allowed) throw new TypeError(`Invalid allowed Codex WebSocket origin: ${allowedOrigin}`);\n return allowed === requestOrigin;\n });\n}\n\n/**\n * Binds an established socket to a required host authorization callback.\n * HTTP upgrades, cookies, user lookup, runner pooling, and Express integration stay host-owned.\n */\nexport function bindCodexWebSocket<Context>(\n options: BindCodexWebSocketOptions<Context>,\n): CodexWebSocketBinding {\n return new ServerBinding(options);\n}\n\n/** Adapts a `ws`-style socket without importing or depending on that library. */\nexport function createCodexNodeWebSocketPort(socket: CodexNodeWebSocketLike): CodexWebSocketPort {\n return {\n send: (data) => socket.send(data),\n close: (code, reason) => socket.close(code, reason),\n onMessage: (listener) => nodeSocketListener(socket, 'message', listener),\n onClose: (listener) => nodeSocketListener(socket, 'close', (code: unknown, reason: unknown) => listener({\n code: typeof code === 'number' ? code : undefined,\n reason: socketReason(reason),\n })),\n onError: (listener) => nodeSocketListener(socket, 'error', listener),\n };\n}\n\nclass ServerBinding<Context> implements CodexWebSocketBinding {\n readonly ready: Promise<void>;\n readonly #socket: CodexWebSocketPort;\n readonly #context: Context;\n readonly #authorize: BindCodexWebSocketOptions<Context>['authorize'];\n readonly #maxMessageBytes: number;\n readonly #unsubscribers: Array<() => void> = [];\n #lease: CodexWebSocketSessionLease | null = null;\n #requestQueue = Promise.resolve();\n #acceptingRequests = false;\n #finished = false;\n #releasePromise: Promise<void> | null = null;\n // State stays on full snapshots unless the surface can stream patches and\n // the client opts in after a `ready` that advertised `stateVersion`.\n #patchSource: CodexSurfaceStatePatchSource | null = null;\n #readyStateVersion: number | null = null;\n #patchMode: 'off' | 'starting' | 'on' = 'off';\n readonly #pendingPatches: CodexSurfaceStatePatch[] = [];\n\n constructor(options: BindCodexWebSocketOptions<Context>) {\n this.#socket = options.socket;\n this.#context = options.context;\n this.#authorize = options.authorize;\n this.#maxMessageBytes = positiveWebSocketLimit(\n options.maxMessageBytes,\n defaultCodexWebSocketMaximumMessageBytes,\n 'Codex WebSocket message byte limit',\n );\n this.#unsubscribers.push(\n this.#socket.onMessage((data) => this.#receive(data)),\n this.#socket.onClose((close) => { void this.#finish({ reason: 'socket_closed', close }); }),\n );\n if (this.#socket.onError) {\n this.#unsubscribers.push(this.#socket.onError((error) => {\n void this.#finish({ reason: 'socket_closed', error });\n }));\n }\n this.ready = this.#initialize();\n }\n\n async close(code = 1000, reason = 'Codex web session closed'): Promise<void> {\n if (!this.#finished) this.#socket.close(code, reason);\n await this.#finish({ reason: 'server_closed', close: { code, reason, wasClean: true } });\n }\n\n async #initialize(): Promise<void> {\n try {\n const lease = await this.#authorize(this.#context);\n if (!lease) {\n this.#socket.close(4401, 'Unauthorized');\n await this.#finish({ reason: 'authorization_failed' });\n throw new Error('Codex WebSocket authorization was denied');\n }\n if (this.#finished) {\n await lease.release?.({ reason: 'socket_closed' });\n return;\n }\n this.#lease = lease;\n const patchSource = isCodexSurfaceStatePatchSource(lease.surface) ? lease.surface : null;\n this.#unsubscribers.push(\n lease.surface.onStateChange((snapshot) => {\n if (this.#acceptingRequests && this.#patchMode === 'off') this.#send({\n version: codexWebSocketProtocolVersion,\n type: 'snapshot',\n snapshot,\n });\n }),\n lease.surface.onEvent((event) => {\n if (this.#acceptingRequests) this.#send({\n version: codexWebSocketProtocolVersion,\n type: 'event',\n event,\n });\n }),\n );\n if (patchSource) {\n this.#unsubscribers.push(patchSource.onStatePatch((patch) => {\n if (this.#patchMode === 'on') this.#send(statePatchMessage(patch));\n else if (this.#patchMode === 'starting') this.#pendingPatches.push(patch);\n }));\n }\n const snapshot = await lease.surface.connect();\n const state = patchSource ? await patchSource.getVersionedSnapshot() : null;\n if (this.#finished) return;\n this.#patchSource = state ? patchSource : null;\n this.#readyStateVersion = state?.version ?? null;\n this.#send({\n version: codexWebSocketProtocolVersion,\n type: 'ready',\n ...(state ? { snapshot: state.snapshot, stateVersion: state.version } : { snapshot }),\n });\n this.#acceptingRequests = true;\n } catch (error) {\n if (!this.#finished) {\n this.#socket.close(1011, 'Codex web session initialization failed');\n await this.#finish({ reason: 'surface_failed', error });\n }\n throw error;\n }\n }\n\n #receive(data: unknown): void {\n if (this.#finished) return;\n if (!this.#acceptingRequests) {\n this.#socket.close(4400, 'Request received before the session was ready');\n void this.#finish({ reason: 'socket_closed', close: { code: 4400 } });\n return;\n }\n let request: CodexWebSocketRequest | 'enableStatePatches';\n try {\n request = parseClientMessage(codexWebSocketText(data, this.#maxMessageBytes));\n if (request === 'enableStatePatches' && (!this.#patchSource || this.#patchMode !== 'off')) {\n throw new TypeError('State patches cannot be enabled for this session');\n }\n } catch {\n this.#socket.close(4400, 'Invalid Codex WebSocket request');\n void this.#finish({ reason: 'socket_closed', close: { code: 4400 } });\n return;\n }\n if (request === 'enableStatePatches') {\n void this.#enableStatePatches();\n return;\n }\n this.#requestQueue = this.#requestQueue.then(() => this.#handle(request));\n }\n\n async #enableStatePatches(): Promise<void> {\n const patchSource = this.#patchSource!;\n this.#patchMode = 'starting';\n let state;\n try {\n state = await patchSource.getVersionedSnapshot();\n } catch {\n state = null;\n }\n if (this.#finished) return;\n if (!state) {\n // Without a base the client cannot apply patches; a reconnect starts over.\n this.#socket.close(1011, 'Codex state stream unavailable');\n void this.#finish({ reason: 'surface_failed' });\n return;\n }\n // Snapshots sent before the switch moved the client past `ready`; give it a new base.\n if (state.version !== this.#readyStateVersion) this.#send({\n version: codexWebSocketProtocolVersion,\n type: 'snapshot',\n snapshot: state.snapshot,\n stateVersion: state.version,\n });\n this.#patchMode = 'on';\n for (const patch of this.#pendingPatches.splice(0)) {\n if (patch.version > state.version) this.#send(statePatchMessage(patch));\n }\n }\n\n async #handle(request: CodexWebSocketRequest): Promise<void> {\n const lease = this.#lease;\n if (!lease || this.#finished) return;\n try {\n const result = await invokeCodexSurfaceBridgeOperation(\n lease.surface,\n request.operation,\n request.args,\n lease.resolveAttachment ? { resolveAttachment: lease.resolveAttachment } : {},\n );\n this.#send({\n version: codexWebSocketProtocolVersion,\n type: 'response',\n id: request.id,\n ok: true,\n result,\n });\n } catch (error) {\n this.#send(failure(\n request.id,\n error instanceof TypeError || error instanceof RangeError ? 'invalid_request' : 'operation_failed',\n errorMessage(error),\n ));\n }\n }\n\n #send(message: CodexWebSocketServerMessage | CodexWebSocketStatePatch): void {\n if (this.#finished) return;\n try {\n const encoded = encodeCodexWebSocketMessage(message);\n if (new TextEncoder().encode(encoded).byteLength > this.#maxMessageBytes) {\n throw new RangeError('Codex WebSocket response exceeds the configured byte limit');\n }\n this.#socket.send(encoded);\n } catch (error) {\n this.#socket.close(1011, 'Codex WebSocket response failed');\n void this.#finish({ reason: 'socket_closed', error });\n }\n }\n\n #finish(context: CodexWebSocketSessionRelease): Promise<void> {\n if (this.#releasePromise) return this.#releasePromise;\n this.#finished = true;\n this.#acceptingRequests = false;\n for (const unsubscribe of this.#unsubscribers.splice(0)) unsubscribe();\n const lease = this.#lease;\n this.#lease = null;\n this.#releasePromise = Promise.resolve(lease?.release?.(context)).then(() => undefined);\n return this.#releasePromise;\n }\n}\n\nfunction statePatchMessage(patch: CodexSurfaceStatePatch): CodexWebSocketStatePatch {\n return { version: codexWebSocketProtocolVersion, type: 'statePatch', patch };\n}\n\nfunction parseClientMessage(text: string): CodexWebSocketRequest | 'enableStatePatches' {\n const value = JSON.parse(text) as unknown;\n if (!isPlainObject(value)) throw new TypeError('Codex WebSocket request must be an object');\n if (value.type === 'enableStatePatches') {\n onlyKeys(value, ['version', 'type']);\n if (value.version !== codexWebSocketProtocolVersion) throw new TypeError('Codex WebSocket version is invalid');\n return 'enableStatePatches';\n }\n onlyKeys(value, ['version', 'type', 'id', 'operation', 'args']);\n if (value.version !== codexWebSocketProtocolVersion || value.type !== 'request') {\n throw new TypeError('Codex WebSocket request version or type is invalid');\n }\n if (typeof value.id !== 'string' || !value.id.trim() || value.id.length > 128) {\n throw new TypeError('Codex WebSocket request id is invalid');\n }\n if (!isCodexSurfaceBridgeOperation(value.operation)) {\n throw new TypeError('Codex WebSocket operation is invalid');\n }\n if (!Array.isArray(value.args)) throw new TypeError('Codex WebSocket request args must be an array');\n return {\n version: codexWebSocketProtocolVersion,\n type: 'request',\n id: value.id,\n operation: value.operation,\n args: value.args,\n };\n}\n\nfunction failure(\n id: string,\n code: CodexWebSocketFailure['error']['code'],\n message: string,\n): CodexWebSocketFailure {\n return {\n version: codexWebSocketProtocolVersion,\n type: 'response',\n id,\n ok: false,\n error: { code, message: message.slice(0, 2_000) },\n };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value) as object | null;\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction onlyKeys(record: Record<string, unknown>, allowedKeys: readonly string[]): void {\n const allowed = new Set(allowedKeys);\n if (Reflect.ownKeys(record).some((key) => typeof key !== 'string' || !allowed.has(key))) {\n throw new TypeError('Codex WebSocket request contains unsupported properties');\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction nodeSocketListener(\n socket: CodexNodeWebSocketLike,\n event: 'message' | 'close' | 'error',\n listener: (first: unknown, second?: unknown) => void,\n): () => void {\n if (event === 'message') socket.on(event, listener as (data: unknown) => void);\n if (event === 'close') socket.on(event, listener as (code: number, reason: unknown) => void);\n if (event === 'error') socket.on(event, listener as (error: unknown) => void);\n return () => {\n const removable = socket as CodexNodeWebSocketLike & {\n off?(name: string, callback: (first: unknown, second?: unknown) => void): unknown;\n removeListener?(name: string, callback: (first: unknown, second?: unknown) => void): unknown;\n };\n if (removable.off) removable.off(event, listener);\n else removable.removeListener?.(event, listener);\n };\n}\n\nfunction normalizedOrigin(value: string): string | null {\n try {\n const { origin } = new URL(value.trim());\n return origin === 'null' ? null : origin;\n } catch {\n return null;\n }\n}\n\nfunction socketReason(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n const reason = new TextDecoder().decode(value).trim();\n return reason || undefined;\n }\n return undefined;\n}\n\nexport type {\n CodexWebSocketClose,\n CodexWebSocketPort,\n} from './socket-port';\n"],"mappings":";;;;AA6EA,SAAgB,EACd,GACA,GACS;CACT,IAAM,IAAS,EAAQ,QAAQ;CAC/B,IAAI,OAAO,KAAW,UAAU,OAAO;CACvC,IAAM,IAAgB,EAAiB,CAAM;CAE7C,OADK,IACE,EAAe,MAAM,MAAkB;EAC5C,IAAM,IAAU,EAAiB,CAAa;EAC9C,IAAI,CAAC,GAAS,MAAU,UAAU,2CAA2C,GAAe;EAC5F,OAAO,MAAY;CACrB,CAAC,IAL0B;AAM7B;AAMA,SAAgB,EACd,GACuB;CACvB,OAAO,IAAI,EAAc,CAAO;AAClC;AAGA,SAAgB,EAA6B,GAAoD;CAC/F,OAAO;EACL,OAAO,MAAS,EAAO,KAAK,CAAI;EAChC,QAAQ,GAAM,MAAW,EAAO,MAAM,GAAM,CAAM;EAClD,YAAY,MAAa,EAAmB,GAAQ,WAAW,CAAQ;EACvE,UAAU,MAAa,EAAmB,GAAQ,UAAU,GAAe,MAAoB,EAAS;GACtG,MAAM,OAAO,KAAS,WAAW,IAAO,KAAA;GACxC,QAAQ,EAAa,CAAM;EAC7B,CAAC,CAAC;EACF,UAAU,MAAa,EAAmB,GAAQ,SAAS,CAAQ;CACrE;AACF;AAEA,IAAM,IAAN,MAA8D;CAC5D;CACA;CACA;CACA;CACA;CACA,KAA6C,CAAC;CAC9C,KAA4C;CAC5C,KAAgB,QAAQ,QAAQ;CAChC,KAAqB;CACrB,KAAY;CACZ,KAAwC;CAGxC,KAAoD;CACpD,KAAoC;CACpC,KAAwC;CACxC,KAAqD,CAAC;CAEtD,YAAY,GAA6C;EAkBvD,AAjBA,KAAKA,KAAU,EAAQ,QACvB,KAAKC,KAAW,EAAQ,SACxB,KAAKC,KAAa,EAAQ,WAC1B,KAAKC,KAAmB,EACtB,EAAQ,iBACR,GACA,oCACF,GACA,KAAKC,GAAe,KAClB,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,OAAO,KAAU,UAAU,OAAO;CACtC,IAAI,aAAiB,eAAe,YAAY,OAAO,CAAK,GAE1D,OADe,IAAI,YAAY,CAAC,CAAC,OAAO,CAAK,CAAC,CAAC,KACxC,KAAU,KAAA;AAGrB"}
@@ -0,0 +1,17 @@
1
+ export type CodexWebSocketClose = {
2
+ code?: number;
3
+ reason?: string;
4
+ wasClean?: boolean;
5
+ };
6
+ /** Minimal socket seam implemented by browser WebSocket, `ws`, or another host adapter. */
7
+ export type CodexWebSocketPort = {
8
+ send(data: string): void;
9
+ close(code?: number, reason?: string): void;
10
+ onMessage(listener: (data: unknown) => void): () => void;
11
+ onClose(listener: (event: CodexWebSocketClose) => void): () => void;
12
+ onError?(listener: (error: unknown) => void): () => void;
13
+ };
14
+ export declare const defaultCodexWebSocketMaximumMessageBytes: number;
15
+ export declare function codexWebSocketText(data: unknown, maximumBytes: number): string;
16
+ export declare function positiveWebSocketLimit(value: number | undefined, fallback: number, label: string): number;
17
+ //# sourceMappingURL=socket-port.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"socket-port.d.ts","sourceRoot":"","sources":["../src/socket-port.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,mBAAmB,GAAG;IAChC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,CAAC;AAEF,2FAA2F;AAC3F,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5C,SAAS,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IACzD,OAAO,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IACpE,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CAC1D,CAAC;AAEF,eAAO,MAAM,wCAAwC,QAAmB,CAAC;AAEzE,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAe9E;AAED,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,GACZ,MAAM,CAIR"}
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@codex-app-sdk/web",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.14.0",
4
+ "description": "Framework-neutral WebSocket bindings for browser-based Codex applications.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/codex-app-sdk/codex-app-sdk.git",
10
+ "directory": "packages/web"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public",
14
+ "registry": "https://registry.npmjs.org"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md"
19
+ ],
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js"
24
+ },
25
+ "./client": {
26
+ "types": "./dist/client.d.ts",
27
+ "import": "./dist/client.js"
28
+ },
29
+ "./server": {
30
+ "types": "./dist/server.d.ts",
31
+ "import": "./dist/server.js"
32
+ },
33
+ "./protocol": {
34
+ "types": "./dist/protocol.d.ts",
35
+ "import": "./dist/protocol.js"
36
+ }
37
+ },
38
+ "scripts": {
39
+ "build": "vite build && tsc -p tsconfig.build.json --declaration --emitDeclarationOnly",
40
+ "check": "npm run lint && npm run test:coverage && npm run build",
41
+ "lint": "tsc -p tsconfig.test.json --noEmit",
42
+ "test": "vitest run",
43
+ "test:coverage": "vitest run --coverage",
44
+ "test:mutation": "cd ../.. && stryker run packages/web/stryker.config.mjs",
45
+ "typecheck": "tsc -p tsconfig.json --noEmit"
46
+ },
47
+ "dependencies": {
48
+ "@codex-app-sdk/core": "0.14.0"
49
+ },
50
+ "engines": {
51
+ "node": ">=22"
52
+ }
53
+ }