@gadgetinc/substrate 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/dist/assets/kernel.wasm +0 -0
  2. package/dist/assets/manifest.json +32 -0
  3. package/dist/assets/network-driver.js +2 -0
  4. package/dist/assets/network-driver.js.map +1 -0
  5. package/dist/assets/runtime.js +264 -0
  6. package/dist/assets/runtime.js.map +1 -0
  7. package/dist/binaries.d.ts +58 -0
  8. package/dist/binaries.d.ts.map +1 -0
  9. package/dist/boot/index.d.ts +318 -0
  10. package/dist/boot/index.d.ts.map +1 -0
  11. package/dist/index.d.ts +8 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +4589 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/kernel/bridge.d.ts +64 -0
  16. package/dist/kernel/bridge.d.ts.map +1 -0
  17. package/dist/kernel/types.d.ts +518 -0
  18. package/dist/kernel/types.d.ts.map +1 -0
  19. package/dist/kernel/wasm.d.ts +20 -0
  20. package/dist/kernel/wasm.d.ts.map +1 -0
  21. package/dist/node/assert.d.ts +99 -0
  22. package/dist/node/assert.d.ts.map +1 -0
  23. package/dist/node/async_hooks.d.ts +88 -0
  24. package/dist/node/async_hooks.d.ts.map +1 -0
  25. package/dist/node/buffer.d.ts +62 -0
  26. package/dist/node/buffer.d.ts.map +1 -0
  27. package/dist/node/child_process.d.ts +300 -0
  28. package/dist/node/child_process.d.ts.map +1 -0
  29. package/dist/node/cluster.d.ts +37 -0
  30. package/dist/node/cluster.d.ts.map +1 -0
  31. package/dist/node/constants.d.ts +306 -0
  32. package/dist/node/constants.d.ts.map +1 -0
  33. package/dist/node/crypto.d.ts +176 -0
  34. package/dist/node/crypto.d.ts.map +1 -0
  35. package/dist/node/dgram.d.ts +44 -0
  36. package/dist/node/dgram.d.ts.map +1 -0
  37. package/dist/node/diagnostics_channel.d.ts +57 -0
  38. package/dist/node/diagnostics_channel.d.ts.map +1 -0
  39. package/dist/node/dns.d.ts +278 -0
  40. package/dist/node/dns.d.ts.map +1 -0
  41. package/dist/node/domain.d.ts +21 -0
  42. package/dist/node/domain.d.ts.map +1 -0
  43. package/dist/node/events.d.ts +54 -0
  44. package/dist/node/events.d.ts.map +1 -0
  45. package/dist/node/fs/promises.d.ts +116 -0
  46. package/dist/node/fs/promises.d.ts.map +1 -0
  47. package/dist/node/fs.d.ts +536 -0
  48. package/dist/node/fs.d.ts.map +1 -0
  49. package/dist/node/http.d.ts +471 -0
  50. package/dist/node/http.d.ts.map +1 -0
  51. package/dist/node/http2.d.ts +508 -0
  52. package/dist/node/http2.d.ts.map +1 -0
  53. package/dist/node/https.d.ts +42 -0
  54. package/dist/node/https.d.ts.map +1 -0
  55. package/dist/node/inspector.d.ts +25 -0
  56. package/dist/node/inspector.d.ts.map +1 -0
  57. package/dist/node/net.d.ts +231 -0
  58. package/dist/node/net.d.ts.map +1 -0
  59. package/dist/node/os.d.ts +318 -0
  60. package/dist/node/os.d.ts.map +1 -0
  61. package/dist/node/path.d.ts +144 -0
  62. package/dist/node/path.d.ts.map +1 -0
  63. package/dist/node/process.d.ts +105 -0
  64. package/dist/node/process.d.ts.map +1 -0
  65. package/dist/node/punycode.d.ts +34 -0
  66. package/dist/node/punycode.d.ts.map +1 -0
  67. package/dist/node/querystring.d.ts +49 -0
  68. package/dist/node/querystring.d.ts.map +1 -0
  69. package/dist/node/readline.d.ts +99 -0
  70. package/dist/node/readline.d.ts.map +1 -0
  71. package/dist/node/stream.d.ts +409 -0
  72. package/dist/node/stream.d.ts.map +1 -0
  73. package/dist/node/string_decoder.d.ts +46 -0
  74. package/dist/node/string_decoder.d.ts.map +1 -0
  75. package/dist/node/timers.d.ts +79 -0
  76. package/dist/node/timers.d.ts.map +1 -0
  77. package/dist/node/tls.d.ts +159 -0
  78. package/dist/node/tls.d.ts.map +1 -0
  79. package/dist/node/trace_events.d.ts +18 -0
  80. package/dist/node/trace_events.d.ts.map +1 -0
  81. package/dist/node/tty.d.ts +67 -0
  82. package/dist/node/tty.d.ts.map +1 -0
  83. package/dist/node/url.d.ts +85 -0
  84. package/dist/node/url.d.ts.map +1 -0
  85. package/dist/node/util.d.ts +252 -0
  86. package/dist/node/util.d.ts.map +1 -0
  87. package/dist/node/v8.d.ts +134 -0
  88. package/dist/node/v8.d.ts.map +1 -0
  89. package/dist/node/vm.d.ts +89 -0
  90. package/dist/node/vm.d.ts.map +1 -0
  91. package/dist/node/wasi.d.ts +25 -0
  92. package/dist/node/wasi.d.ts.map +1 -0
  93. package/dist/node/worker_threads.d.ts +206 -0
  94. package/dist/node/worker_threads.d.ts.map +1 -0
  95. package/dist/node/ws.d.ts +110 -0
  96. package/dist/node/ws.d.ts.map +1 -0
  97. package/dist/node/zlib.d.ts +328 -0
  98. package/dist/node/zlib.d.ts.map +1 -0
  99. package/dist/persistence/opfs-store.d.ts +93 -0
  100. package/dist/persistence/opfs-store.d.ts.map +1 -0
  101. package/dist/runtime/async-function-shim.d.ts +27 -0
  102. package/dist/runtime/async-function-shim.d.ts.map +1 -0
  103. package/dist/runtime/fs-interface.d.ts +60 -0
  104. package/dist/runtime/fs-interface.d.ts.map +1 -0
  105. package/dist/runtime/index.d.ts +113 -0
  106. package/dist/runtime/index.d.ts.map +1 -0
  107. package/dist/runtime/loader.d.ts +50 -0
  108. package/dist/runtime/loader.d.ts.map +1 -0
  109. package/dist/runtime/loaders/async-transform.d.ts +40 -0
  110. package/dist/runtime/loaders/async-transform.d.ts.map +1 -0
  111. package/dist/runtime/loaders/cjs.d.ts +37 -0
  112. package/dist/runtime/loaders/cjs.d.ts.map +1 -0
  113. package/dist/runtime/loaders/detect-module-type.d.ts +21 -0
  114. package/dist/runtime/loaders/detect-module-type.d.ts.map +1 -0
  115. package/dist/runtime/loaders/esm.d.ts +140 -0
  116. package/dist/runtime/loaders/esm.d.ts.map +1 -0
  117. package/dist/runtime/loaders/source-map-registry.d.ts +43 -0
  118. package/dist/runtime/loaders/source-map-registry.d.ts.map +1 -0
  119. package/dist/runtime/loaders/source-map.d.ts +50 -0
  120. package/dist/runtime/loaders/source-map.d.ts.map +1 -0
  121. package/dist/runtime/loaders/utils.d.ts +6 -0
  122. package/dist/runtime/loaders/utils.d.ts.map +1 -0
  123. package/dist/runtime/native-globals.d.ts +24 -0
  124. package/dist/runtime/native-globals.d.ts.map +1 -0
  125. package/dist/runtime/network-driver.d.ts +78 -0
  126. package/dist/runtime/network-driver.d.ts.map +1 -0
  127. package/dist/runtime/process-context.d.ts +96 -0
  128. package/dist/runtime/process-context.d.ts.map +1 -0
  129. package/dist/runtime/process-event-loop.d.ts +356 -0
  130. package/dist/runtime/process-event-loop.d.ts.map +1 -0
  131. package/dist/runtime/process-handler.d.ts +71 -0
  132. package/dist/runtime/process-handler.d.ts.map +1 -0
  133. package/dist/runtime/process-handlers/node.d.ts +22 -0
  134. package/dist/runtime/process-handlers/node.d.ts.map +1 -0
  135. package/dist/runtime/process-handlers/npm.d.ts +20 -0
  136. package/dist/runtime/process-handlers/npm.d.ts.map +1 -0
  137. package/dist/runtime/process-handlers/npx.d.ts +11 -0
  138. package/dist/runtime/process-handlers/npx.d.ts.map +1 -0
  139. package/dist/runtime/process-handlers/pnpm.d.ts +12 -0
  140. package/dist/runtime/process-handlers/pnpm.d.ts.map +1 -0
  141. package/dist/runtime/process-handlers/shell.d.ts +24 -0
  142. package/dist/runtime/process-handlers/shell.d.ts.map +1 -0
  143. package/dist/runtime/process-handlers/yarn.d.ts +12 -0
  144. package/dist/runtime/process-handlers/yarn.d.ts.map +1 -0
  145. package/dist/runtime/process-helpers.d.ts +17 -0
  146. package/dist/runtime/process-helpers.d.ts.map +1 -0
  147. package/dist/runtime/process-manager.d.ts +87 -0
  148. package/dist/runtime/process-manager.d.ts.map +1 -0
  149. package/dist/runtime/process-scheduler.d.ts +123 -0
  150. package/dist/runtime/process-scheduler.d.ts.map +1 -0
  151. package/dist/runtime/process-waker.d.ts +24 -0
  152. package/dist/runtime/process-waker.d.ts.map +1 -0
  153. package/dist/runtime/promise.d.ts +44 -0
  154. package/dist/runtime/promise.d.ts.map +1 -0
  155. package/dist/runtime/stack-trace.d.ts +52 -0
  156. package/dist/runtime/stack-trace.d.ts.map +1 -0
  157. package/dist/runtime/wasm-package-interceptor.d.ts +141 -0
  158. package/dist/runtime/wasm-package-interceptor.d.ts.map +1 -0
  159. package/dist/runtime/web-streams.d.ts +57 -0
  160. package/dist/runtime/web-streams.d.ts.map +1 -0
  161. package/dist/runtime/websocket.d.ts +102 -0
  162. package/dist/runtime/websocket.d.ts.map +1 -0
  163. package/dist/shim/websocket-shim-inline.d.ts +9 -0
  164. package/dist/shim/websocket-shim-inline.d.ts.map +1 -0
  165. package/dist/shim/websocket-shim.d.ts +15 -0
  166. package/dist/shim/websocket-shim.d.ts.map +1 -0
  167. package/dist/sw/index.d.ts +53 -0
  168. package/dist/sw/index.d.ts.map +1 -0
  169. package/dist/utils/debug.d.ts +75 -0
  170. package/dist/utils/debug.d.ts.map +1 -0
  171. package/dist/utils/path.d.ts +20 -0
  172. package/dist/utils/path.d.ts.map +1 -0
  173. package/dist/utils/tarball.d.ts +37 -0
  174. package/dist/utils/tarball.d.ts.map +1 -0
  175. package/dist/utils/websocket-protocol.d.ts +102 -0
  176. package/dist/utils/websocket-protocol.d.ts.map +1 -0
  177. package/dist/worker/host.d.ts +14 -0
  178. package/dist/worker/host.d.ts.map +1 -0
  179. package/dist/worker/types.d.ts +209 -0
  180. package/dist/worker/types.d.ts.map +1 -0
  181. package/package.json +53 -0
package/dist/index.js ADDED
@@ -0,0 +1,4589 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
3
+
4
+ //#endregion
5
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/is.js
6
+ var require_is = /* @__PURE__ */ __commonJSMin(((exports) => {
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.stringArray = exports.array = exports.func = exports.error = exports.number = exports.string = exports.boolean = void 0;
9
+ function boolean(value) {
10
+ return value === true || value === false;
11
+ }
12
+ exports.boolean = boolean;
13
+ function string(value) {
14
+ return typeof value === "string" || value instanceof String;
15
+ }
16
+ exports.string = string;
17
+ function number(value) {
18
+ return typeof value === "number" || value instanceof Number;
19
+ }
20
+ exports.number = number;
21
+ function error(value) {
22
+ return value instanceof Error;
23
+ }
24
+ exports.error = error;
25
+ function func(value) {
26
+ return typeof value === "function";
27
+ }
28
+ exports.func = func;
29
+ function array(value) {
30
+ return Array.isArray(value);
31
+ }
32
+ exports.array = array;
33
+ function stringArray(value) {
34
+ return array(value) && value.every((elem) => string(elem));
35
+ }
36
+ exports.stringArray = stringArray;
37
+ }));
38
+
39
+ //#endregion
40
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/messages.js
41
+ var require_messages = /* @__PURE__ */ __commonJSMin(((exports) => {
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.Message = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType = exports.RequestType0 = exports.AbstractMessageSignature = exports.ParameterStructures = exports.ResponseError = exports.ErrorCodes = void 0;
44
+ const is = require_is();
45
+ /**
46
+ * Predefined error codes.
47
+ */
48
+ var ErrorCodes;
49
+ (function(ErrorCodes) {
50
+ ErrorCodes.ParseError = -32700;
51
+ ErrorCodes.InvalidRequest = -32600;
52
+ ErrorCodes.MethodNotFound = -32601;
53
+ ErrorCodes.InvalidParams = -32602;
54
+ ErrorCodes.InternalError = -32603;
55
+ /**
56
+ * This is the start range of JSON RPC reserved error codes.
57
+ * It doesn't denote a real error code. No application error codes should
58
+ * be defined between the start and end range. For backwards
59
+ * compatibility the `ServerNotInitialized` and the `UnknownErrorCode`
60
+ * are left in the range.
61
+ *
62
+ * @since 3.16.0
63
+ */
64
+ ErrorCodes.jsonrpcReservedErrorRangeStart = -32099;
65
+ /** @deprecated use jsonrpcReservedErrorRangeStart */
66
+ ErrorCodes.serverErrorStart = -32099;
67
+ /**
68
+ * An error occurred when write a message to the transport layer.
69
+ */
70
+ ErrorCodes.MessageWriteError = -32099;
71
+ /**
72
+ * An error occurred when reading a message from the transport layer.
73
+ */
74
+ ErrorCodes.MessageReadError = -32098;
75
+ /**
76
+ * The connection got disposed or lost and all pending responses got
77
+ * rejected.
78
+ */
79
+ ErrorCodes.PendingResponseRejected = -32097;
80
+ /**
81
+ * The connection is inactive and a use of it failed.
82
+ */
83
+ ErrorCodes.ConnectionInactive = -32096;
84
+ /**
85
+ * Error code indicating that a server received a notification or
86
+ * request before the server has received the `initialize` request.
87
+ */
88
+ ErrorCodes.ServerNotInitialized = -32002;
89
+ ErrorCodes.UnknownErrorCode = -32001;
90
+ /**
91
+ * This is the end range of JSON RPC reserved error codes.
92
+ * It doesn't denote a real error code.
93
+ *
94
+ * @since 3.16.0
95
+ */
96
+ ErrorCodes.jsonrpcReservedErrorRangeEnd = -32e3;
97
+ /** @deprecated use jsonrpcReservedErrorRangeEnd */
98
+ ErrorCodes.serverErrorEnd = -32e3;
99
+ })(ErrorCodes || (exports.ErrorCodes = ErrorCodes = {}));
100
+ /**
101
+ * An error object return in a response in case a request
102
+ * has failed.
103
+ */
104
+ var ResponseError = class ResponseError extends Error {
105
+ constructor(code, message, data) {
106
+ super(message);
107
+ this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
108
+ this.data = data;
109
+ Object.setPrototypeOf(this, ResponseError.prototype);
110
+ }
111
+ toJson() {
112
+ const result = {
113
+ code: this.code,
114
+ message: this.message
115
+ };
116
+ if (this.data !== void 0) result.data = this.data;
117
+ return result;
118
+ }
119
+ };
120
+ exports.ResponseError = ResponseError;
121
+ var ParameterStructures = class ParameterStructures {
122
+ constructor(kind) {
123
+ this.kind = kind;
124
+ }
125
+ static is(value) {
126
+ return value === ParameterStructures.auto || value === ParameterStructures.byName || value === ParameterStructures.byPosition;
127
+ }
128
+ toString() {
129
+ return this.kind;
130
+ }
131
+ };
132
+ exports.ParameterStructures = ParameterStructures;
133
+ /**
134
+ * The parameter structure is automatically inferred on the number of parameters
135
+ * and the parameter type in case of a single param.
136
+ */
137
+ ParameterStructures.auto = new ParameterStructures("auto");
138
+ /**
139
+ * Forces `byPosition` parameter structure. This is useful if you have a single
140
+ * parameter which has a literal type.
141
+ */
142
+ ParameterStructures.byPosition = new ParameterStructures("byPosition");
143
+ /**
144
+ * Forces `byName` parameter structure. This is only useful when having a single
145
+ * parameter. The library will report errors if used with a different number of
146
+ * parameters.
147
+ */
148
+ ParameterStructures.byName = new ParameterStructures("byName");
149
+ /**
150
+ * An abstract implementation of a MessageType.
151
+ */
152
+ var AbstractMessageSignature = class {
153
+ constructor(method, numberOfParams) {
154
+ this.method = method;
155
+ this.numberOfParams = numberOfParams;
156
+ }
157
+ get parameterStructures() {
158
+ return ParameterStructures.auto;
159
+ }
160
+ };
161
+ exports.AbstractMessageSignature = AbstractMessageSignature;
162
+ /**
163
+ * Classes to type request response pairs
164
+ */
165
+ var RequestType0 = class extends AbstractMessageSignature {
166
+ constructor(method) {
167
+ super(method, 0);
168
+ }
169
+ };
170
+ exports.RequestType0 = RequestType0;
171
+ var RequestType = class extends AbstractMessageSignature {
172
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
173
+ super(method, 1);
174
+ this._parameterStructures = _parameterStructures;
175
+ }
176
+ get parameterStructures() {
177
+ return this._parameterStructures;
178
+ }
179
+ };
180
+ exports.RequestType = RequestType;
181
+ var RequestType1 = class extends AbstractMessageSignature {
182
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
183
+ super(method, 1);
184
+ this._parameterStructures = _parameterStructures;
185
+ }
186
+ get parameterStructures() {
187
+ return this._parameterStructures;
188
+ }
189
+ };
190
+ exports.RequestType1 = RequestType1;
191
+ var RequestType2 = class extends AbstractMessageSignature {
192
+ constructor(method) {
193
+ super(method, 2);
194
+ }
195
+ };
196
+ exports.RequestType2 = RequestType2;
197
+ var RequestType3 = class extends AbstractMessageSignature {
198
+ constructor(method) {
199
+ super(method, 3);
200
+ }
201
+ };
202
+ exports.RequestType3 = RequestType3;
203
+ var RequestType4 = class extends AbstractMessageSignature {
204
+ constructor(method) {
205
+ super(method, 4);
206
+ }
207
+ };
208
+ exports.RequestType4 = RequestType4;
209
+ var RequestType5 = class extends AbstractMessageSignature {
210
+ constructor(method) {
211
+ super(method, 5);
212
+ }
213
+ };
214
+ exports.RequestType5 = RequestType5;
215
+ var RequestType6 = class extends AbstractMessageSignature {
216
+ constructor(method) {
217
+ super(method, 6);
218
+ }
219
+ };
220
+ exports.RequestType6 = RequestType6;
221
+ var RequestType7 = class extends AbstractMessageSignature {
222
+ constructor(method) {
223
+ super(method, 7);
224
+ }
225
+ };
226
+ exports.RequestType7 = RequestType7;
227
+ var RequestType8 = class extends AbstractMessageSignature {
228
+ constructor(method) {
229
+ super(method, 8);
230
+ }
231
+ };
232
+ exports.RequestType8 = RequestType8;
233
+ var RequestType9 = class extends AbstractMessageSignature {
234
+ constructor(method) {
235
+ super(method, 9);
236
+ }
237
+ };
238
+ exports.RequestType9 = RequestType9;
239
+ var NotificationType = class extends AbstractMessageSignature {
240
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
241
+ super(method, 1);
242
+ this._parameterStructures = _parameterStructures;
243
+ }
244
+ get parameterStructures() {
245
+ return this._parameterStructures;
246
+ }
247
+ };
248
+ exports.NotificationType = NotificationType;
249
+ var NotificationType0 = class extends AbstractMessageSignature {
250
+ constructor(method) {
251
+ super(method, 0);
252
+ }
253
+ };
254
+ exports.NotificationType0 = NotificationType0;
255
+ var NotificationType1 = class extends AbstractMessageSignature {
256
+ constructor(method, _parameterStructures = ParameterStructures.auto) {
257
+ super(method, 1);
258
+ this._parameterStructures = _parameterStructures;
259
+ }
260
+ get parameterStructures() {
261
+ return this._parameterStructures;
262
+ }
263
+ };
264
+ exports.NotificationType1 = NotificationType1;
265
+ var NotificationType2 = class extends AbstractMessageSignature {
266
+ constructor(method) {
267
+ super(method, 2);
268
+ }
269
+ };
270
+ exports.NotificationType2 = NotificationType2;
271
+ var NotificationType3 = class extends AbstractMessageSignature {
272
+ constructor(method) {
273
+ super(method, 3);
274
+ }
275
+ };
276
+ exports.NotificationType3 = NotificationType3;
277
+ var NotificationType4 = class extends AbstractMessageSignature {
278
+ constructor(method) {
279
+ super(method, 4);
280
+ }
281
+ };
282
+ exports.NotificationType4 = NotificationType4;
283
+ var NotificationType5 = class extends AbstractMessageSignature {
284
+ constructor(method) {
285
+ super(method, 5);
286
+ }
287
+ };
288
+ exports.NotificationType5 = NotificationType5;
289
+ var NotificationType6 = class extends AbstractMessageSignature {
290
+ constructor(method) {
291
+ super(method, 6);
292
+ }
293
+ };
294
+ exports.NotificationType6 = NotificationType6;
295
+ var NotificationType7 = class extends AbstractMessageSignature {
296
+ constructor(method) {
297
+ super(method, 7);
298
+ }
299
+ };
300
+ exports.NotificationType7 = NotificationType7;
301
+ var NotificationType8 = class extends AbstractMessageSignature {
302
+ constructor(method) {
303
+ super(method, 8);
304
+ }
305
+ };
306
+ exports.NotificationType8 = NotificationType8;
307
+ var NotificationType9 = class extends AbstractMessageSignature {
308
+ constructor(method) {
309
+ super(method, 9);
310
+ }
311
+ };
312
+ exports.NotificationType9 = NotificationType9;
313
+ var Message;
314
+ (function(Message) {
315
+ /**
316
+ * Tests if the given message is a request message
317
+ */
318
+ function isRequest(message) {
319
+ const candidate = message;
320
+ return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
321
+ }
322
+ Message.isRequest = isRequest;
323
+ /**
324
+ * Tests if the given message is a notification message
325
+ */
326
+ function isNotification(message) {
327
+ const candidate = message;
328
+ return candidate && is.string(candidate.method) && message.id === void 0;
329
+ }
330
+ Message.isNotification = isNotification;
331
+ /**
332
+ * Tests if the given message is a response message
333
+ */
334
+ function isResponse(message) {
335
+ const candidate = message;
336
+ return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
337
+ }
338
+ Message.isResponse = isResponse;
339
+ })(Message || (exports.Message = Message = {}));
340
+ }));
341
+
342
+ //#endregion
343
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/linkedMap.js
344
+ var require_linkedMap = /* @__PURE__ */ __commonJSMin(((exports) => {
345
+ var _a;
346
+ Object.defineProperty(exports, "__esModule", { value: true });
347
+ exports.LRUCache = exports.LinkedMap = exports.Touch = void 0;
348
+ var Touch;
349
+ (function(Touch) {
350
+ Touch.None = 0;
351
+ Touch.First = 1;
352
+ Touch.AsOld = Touch.First;
353
+ Touch.Last = 2;
354
+ Touch.AsNew = Touch.Last;
355
+ })(Touch || (exports.Touch = Touch = {}));
356
+ var LinkedMap = class {
357
+ constructor() {
358
+ this[_a] = "LinkedMap";
359
+ this._map = /* @__PURE__ */ new Map();
360
+ this._head = void 0;
361
+ this._tail = void 0;
362
+ this._size = 0;
363
+ this._state = 0;
364
+ }
365
+ clear() {
366
+ this._map.clear();
367
+ this._head = void 0;
368
+ this._tail = void 0;
369
+ this._size = 0;
370
+ this._state++;
371
+ }
372
+ isEmpty() {
373
+ return !this._head && !this._tail;
374
+ }
375
+ get size() {
376
+ return this._size;
377
+ }
378
+ get first() {
379
+ return this._head?.value;
380
+ }
381
+ get last() {
382
+ return this._tail?.value;
383
+ }
384
+ has(key) {
385
+ return this._map.has(key);
386
+ }
387
+ get(key, touch = Touch.None) {
388
+ const item = this._map.get(key);
389
+ if (!item) return;
390
+ if (touch !== Touch.None) this.touch(item, touch);
391
+ return item.value;
392
+ }
393
+ set(key, value, touch = Touch.None) {
394
+ let item = this._map.get(key);
395
+ if (item) {
396
+ item.value = value;
397
+ if (touch !== Touch.None) this.touch(item, touch);
398
+ } else {
399
+ item = {
400
+ key,
401
+ value,
402
+ next: void 0,
403
+ previous: void 0
404
+ };
405
+ switch (touch) {
406
+ case Touch.None:
407
+ this.addItemLast(item);
408
+ break;
409
+ case Touch.First:
410
+ this.addItemFirst(item);
411
+ break;
412
+ case Touch.Last:
413
+ this.addItemLast(item);
414
+ break;
415
+ default:
416
+ this.addItemLast(item);
417
+ break;
418
+ }
419
+ this._map.set(key, item);
420
+ this._size++;
421
+ }
422
+ return this;
423
+ }
424
+ delete(key) {
425
+ return !!this.remove(key);
426
+ }
427
+ remove(key) {
428
+ const item = this._map.get(key);
429
+ if (!item) return;
430
+ this._map.delete(key);
431
+ this.removeItem(item);
432
+ this._size--;
433
+ return item.value;
434
+ }
435
+ shift() {
436
+ if (!this._head && !this._tail) return;
437
+ if (!this._head || !this._tail) throw new Error("Invalid list");
438
+ const item = this._head;
439
+ this._map.delete(item.key);
440
+ this.removeItem(item);
441
+ this._size--;
442
+ return item.value;
443
+ }
444
+ forEach(callbackfn, thisArg) {
445
+ const state = this._state;
446
+ let current = this._head;
447
+ while (current) {
448
+ if (thisArg) callbackfn.bind(thisArg)(current.value, current.key, this);
449
+ else callbackfn(current.value, current.key, this);
450
+ if (this._state !== state) throw new Error(`LinkedMap got modified during iteration.`);
451
+ current = current.next;
452
+ }
453
+ }
454
+ keys() {
455
+ const state = this._state;
456
+ let current = this._head;
457
+ const iterator = {
458
+ [Symbol.iterator]: () => {
459
+ return iterator;
460
+ },
461
+ next: () => {
462
+ if (this._state !== state) throw new Error(`LinkedMap got modified during iteration.`);
463
+ if (current) {
464
+ const result = {
465
+ value: current.key,
466
+ done: false
467
+ };
468
+ current = current.next;
469
+ return result;
470
+ } else return {
471
+ value: void 0,
472
+ done: true
473
+ };
474
+ }
475
+ };
476
+ return iterator;
477
+ }
478
+ values() {
479
+ const state = this._state;
480
+ let current = this._head;
481
+ const iterator = {
482
+ [Symbol.iterator]: () => {
483
+ return iterator;
484
+ },
485
+ next: () => {
486
+ if (this._state !== state) throw new Error(`LinkedMap got modified during iteration.`);
487
+ if (current) {
488
+ const result = {
489
+ value: current.value,
490
+ done: false
491
+ };
492
+ current = current.next;
493
+ return result;
494
+ } else return {
495
+ value: void 0,
496
+ done: true
497
+ };
498
+ }
499
+ };
500
+ return iterator;
501
+ }
502
+ entries() {
503
+ const state = this._state;
504
+ let current = this._head;
505
+ const iterator = {
506
+ [Symbol.iterator]: () => {
507
+ return iterator;
508
+ },
509
+ next: () => {
510
+ if (this._state !== state) throw new Error(`LinkedMap got modified during iteration.`);
511
+ if (current) {
512
+ const result = {
513
+ value: [current.key, current.value],
514
+ done: false
515
+ };
516
+ current = current.next;
517
+ return result;
518
+ } else return {
519
+ value: void 0,
520
+ done: true
521
+ };
522
+ }
523
+ };
524
+ return iterator;
525
+ }
526
+ [(_a = Symbol.toStringTag, Symbol.iterator)]() {
527
+ return this.entries();
528
+ }
529
+ trimOld(newSize) {
530
+ if (newSize >= this.size) return;
531
+ if (newSize === 0) {
532
+ this.clear();
533
+ return;
534
+ }
535
+ let current = this._head;
536
+ let currentSize = this.size;
537
+ while (current && currentSize > newSize) {
538
+ this._map.delete(current.key);
539
+ current = current.next;
540
+ currentSize--;
541
+ }
542
+ this._head = current;
543
+ this._size = currentSize;
544
+ if (current) current.previous = void 0;
545
+ this._state++;
546
+ }
547
+ addItemFirst(item) {
548
+ if (!this._head && !this._tail) this._tail = item;
549
+ else if (!this._head) throw new Error("Invalid list");
550
+ else {
551
+ item.next = this._head;
552
+ this._head.previous = item;
553
+ }
554
+ this._head = item;
555
+ this._state++;
556
+ }
557
+ addItemLast(item) {
558
+ if (!this._head && !this._tail) this._head = item;
559
+ else if (!this._tail) throw new Error("Invalid list");
560
+ else {
561
+ item.previous = this._tail;
562
+ this._tail.next = item;
563
+ }
564
+ this._tail = item;
565
+ this._state++;
566
+ }
567
+ removeItem(item) {
568
+ if (item === this._head && item === this._tail) {
569
+ this._head = void 0;
570
+ this._tail = void 0;
571
+ } else if (item === this._head) {
572
+ if (!item.next) throw new Error("Invalid list");
573
+ item.next.previous = void 0;
574
+ this._head = item.next;
575
+ } else if (item === this._tail) {
576
+ if (!item.previous) throw new Error("Invalid list");
577
+ item.previous.next = void 0;
578
+ this._tail = item.previous;
579
+ } else {
580
+ const next = item.next;
581
+ const previous = item.previous;
582
+ if (!next || !previous) throw new Error("Invalid list");
583
+ next.previous = previous;
584
+ previous.next = next;
585
+ }
586
+ item.next = void 0;
587
+ item.previous = void 0;
588
+ this._state++;
589
+ }
590
+ touch(item, touch) {
591
+ if (!this._head || !this._tail) throw new Error("Invalid list");
592
+ if (touch !== Touch.First && touch !== Touch.Last) return;
593
+ if (touch === Touch.First) {
594
+ if (item === this._head) return;
595
+ const next = item.next;
596
+ const previous = item.previous;
597
+ if (item === this._tail) {
598
+ previous.next = void 0;
599
+ this._tail = previous;
600
+ } else {
601
+ next.previous = previous;
602
+ previous.next = next;
603
+ }
604
+ item.previous = void 0;
605
+ item.next = this._head;
606
+ this._head.previous = item;
607
+ this._head = item;
608
+ this._state++;
609
+ } else if (touch === Touch.Last) {
610
+ if (item === this._tail) return;
611
+ const next = item.next;
612
+ const previous = item.previous;
613
+ if (item === this._head) {
614
+ next.previous = void 0;
615
+ this._head = next;
616
+ } else {
617
+ next.previous = previous;
618
+ previous.next = next;
619
+ }
620
+ item.next = void 0;
621
+ item.previous = this._tail;
622
+ this._tail.next = item;
623
+ this._tail = item;
624
+ this._state++;
625
+ }
626
+ }
627
+ toJSON() {
628
+ const data = [];
629
+ this.forEach((value, key) => {
630
+ data.push([key, value]);
631
+ });
632
+ return data;
633
+ }
634
+ fromJSON(data) {
635
+ this.clear();
636
+ for (const [key, value] of data) this.set(key, value);
637
+ }
638
+ };
639
+ exports.LinkedMap = LinkedMap;
640
+ var LRUCache = class extends LinkedMap {
641
+ constructor(limit, ratio = 1) {
642
+ super();
643
+ this._limit = limit;
644
+ this._ratio = Math.min(Math.max(0, ratio), 1);
645
+ }
646
+ get limit() {
647
+ return this._limit;
648
+ }
649
+ set limit(limit) {
650
+ this._limit = limit;
651
+ this.checkTrim();
652
+ }
653
+ get ratio() {
654
+ return this._ratio;
655
+ }
656
+ set ratio(ratio) {
657
+ this._ratio = Math.min(Math.max(0, ratio), 1);
658
+ this.checkTrim();
659
+ }
660
+ get(key, touch = Touch.AsNew) {
661
+ return super.get(key, touch);
662
+ }
663
+ peek(key) {
664
+ return super.get(key, Touch.None);
665
+ }
666
+ set(key, value) {
667
+ super.set(key, value, Touch.Last);
668
+ this.checkTrim();
669
+ return this;
670
+ }
671
+ checkTrim() {
672
+ if (this.size > this._limit) this.trimOld(Math.round(this._limit * this._ratio));
673
+ }
674
+ };
675
+ exports.LRUCache = LRUCache;
676
+ }));
677
+
678
+ //#endregion
679
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/disposable.js
680
+ var require_disposable = /* @__PURE__ */ __commonJSMin(((exports) => {
681
+ Object.defineProperty(exports, "__esModule", { value: true });
682
+ exports.Disposable = void 0;
683
+ var Disposable;
684
+ (function(Disposable) {
685
+ function create(func) {
686
+ return { dispose: func };
687
+ }
688
+ Disposable.create = create;
689
+ })(Disposable || (exports.Disposable = Disposable = {}));
690
+ }));
691
+
692
+ //#endregion
693
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/ral.js
694
+ var require_ral = /* @__PURE__ */ __commonJSMin(((exports) => {
695
+ Object.defineProperty(exports, "__esModule", { value: true });
696
+ let _ral;
697
+ function RAL() {
698
+ if (_ral === void 0) throw new Error(`No runtime abstraction layer installed`);
699
+ return _ral;
700
+ }
701
+ (function(RAL) {
702
+ function install(ral) {
703
+ if (ral === void 0) throw new Error(`No runtime abstraction layer provided`);
704
+ _ral = ral;
705
+ }
706
+ RAL.install = install;
707
+ })(RAL || (RAL = {}));
708
+ exports.default = RAL;
709
+ }));
710
+
711
+ //#endregion
712
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/events.js
713
+ var require_events = /* @__PURE__ */ __commonJSMin(((exports) => {
714
+ Object.defineProperty(exports, "__esModule", { value: true });
715
+ exports.Emitter = exports.Event = void 0;
716
+ const ral_1 = require_ral();
717
+ var Event;
718
+ (function(Event) {
719
+ const _disposable = { dispose() {} };
720
+ Event.None = function() {
721
+ return _disposable;
722
+ };
723
+ })(Event || (exports.Event = Event = {}));
724
+ var CallbackList = class {
725
+ add(callback, context = null, bucket) {
726
+ if (!this._callbacks) {
727
+ this._callbacks = [];
728
+ this._contexts = [];
729
+ }
730
+ this._callbacks.push(callback);
731
+ this._contexts.push(context);
732
+ if (Array.isArray(bucket)) bucket.push({ dispose: () => this.remove(callback, context) });
733
+ }
734
+ remove(callback, context = null) {
735
+ if (!this._callbacks) return;
736
+ let foundCallbackWithDifferentContext = false;
737
+ for (let i = 0, len = this._callbacks.length; i < len; i++) if (this._callbacks[i] === callback) if (this._contexts[i] === context) {
738
+ this._callbacks.splice(i, 1);
739
+ this._contexts.splice(i, 1);
740
+ return;
741
+ } else foundCallbackWithDifferentContext = true;
742
+ if (foundCallbackWithDifferentContext) throw new Error("When adding a listener with a context, you should remove it with the same context");
743
+ }
744
+ invoke(...args) {
745
+ if (!this._callbacks) return [];
746
+ const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
747
+ for (let i = 0, len = callbacks.length; i < len; i++) try {
748
+ ret.push(callbacks[i].apply(contexts[i], args));
749
+ } catch (e) {
750
+ (0, ral_1.default)().console.error(e);
751
+ }
752
+ return ret;
753
+ }
754
+ isEmpty() {
755
+ return !this._callbacks || this._callbacks.length === 0;
756
+ }
757
+ dispose() {
758
+ this._callbacks = void 0;
759
+ this._contexts = void 0;
760
+ }
761
+ };
762
+ var Emitter = class Emitter {
763
+ constructor(_options) {
764
+ this._options = _options;
765
+ }
766
+ /**
767
+ * For the public to allow to subscribe
768
+ * to events from this Emitter
769
+ */
770
+ get event() {
771
+ if (!this._event) this._event = (listener, thisArgs, disposables) => {
772
+ if (!this._callbacks) this._callbacks = new CallbackList();
773
+ if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) this._options.onFirstListenerAdd(this);
774
+ this._callbacks.add(listener, thisArgs);
775
+ const result = { dispose: () => {
776
+ if (!this._callbacks) return;
777
+ this._callbacks.remove(listener, thisArgs);
778
+ result.dispose = Emitter._noop;
779
+ if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) this._options.onLastListenerRemove(this);
780
+ } };
781
+ if (Array.isArray(disposables)) disposables.push(result);
782
+ return result;
783
+ };
784
+ return this._event;
785
+ }
786
+ /**
787
+ * To be kept private to fire an event to
788
+ * subscribers
789
+ */
790
+ fire(event) {
791
+ if (this._callbacks) this._callbacks.invoke.call(this._callbacks, event);
792
+ }
793
+ dispose() {
794
+ if (this._callbacks) {
795
+ this._callbacks.dispose();
796
+ this._callbacks = void 0;
797
+ }
798
+ }
799
+ };
800
+ exports.Emitter = Emitter;
801
+ Emitter._noop = function() {};
802
+ }));
803
+
804
+ //#endregion
805
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/cancellation.js
806
+ var require_cancellation = /* @__PURE__ */ __commonJSMin(((exports) => {
807
+ Object.defineProperty(exports, "__esModule", { value: true });
808
+ exports.CancellationTokenSource = exports.CancellationToken = void 0;
809
+ const ral_1 = require_ral();
810
+ const Is = require_is();
811
+ const events_1 = require_events();
812
+ var CancellationToken;
813
+ (function(CancellationToken) {
814
+ CancellationToken.None = Object.freeze({
815
+ isCancellationRequested: false,
816
+ onCancellationRequested: events_1.Event.None
817
+ });
818
+ CancellationToken.Cancelled = Object.freeze({
819
+ isCancellationRequested: true,
820
+ onCancellationRequested: events_1.Event.None
821
+ });
822
+ function is(value) {
823
+ const candidate = value;
824
+ return candidate && (candidate === CancellationToken.None || candidate === CancellationToken.Cancelled || Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested);
825
+ }
826
+ CancellationToken.is = is;
827
+ })(CancellationToken || (exports.CancellationToken = CancellationToken = {}));
828
+ const shortcutEvent = Object.freeze(function(callback, context) {
829
+ const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);
830
+ return { dispose() {
831
+ handle.dispose();
832
+ } };
833
+ });
834
+ var MutableToken = class {
835
+ constructor() {
836
+ this._isCancelled = false;
837
+ }
838
+ cancel() {
839
+ if (!this._isCancelled) {
840
+ this._isCancelled = true;
841
+ if (this._emitter) {
842
+ this._emitter.fire(void 0);
843
+ this.dispose();
844
+ }
845
+ }
846
+ }
847
+ get isCancellationRequested() {
848
+ return this._isCancelled;
849
+ }
850
+ get onCancellationRequested() {
851
+ if (this._isCancelled) return shortcutEvent;
852
+ if (!this._emitter) this._emitter = new events_1.Emitter();
853
+ return this._emitter.event;
854
+ }
855
+ dispose() {
856
+ if (this._emitter) {
857
+ this._emitter.dispose();
858
+ this._emitter = void 0;
859
+ }
860
+ }
861
+ };
862
+ var CancellationTokenSource = class {
863
+ get token() {
864
+ if (!this._token) this._token = new MutableToken();
865
+ return this._token;
866
+ }
867
+ cancel() {
868
+ if (!this._token) this._token = CancellationToken.Cancelled;
869
+ else this._token.cancel();
870
+ }
871
+ dispose() {
872
+ if (!this._token) this._token = CancellationToken.None;
873
+ else if (this._token instanceof MutableToken) this._token.dispose();
874
+ }
875
+ };
876
+ exports.CancellationTokenSource = CancellationTokenSource;
877
+ }));
878
+
879
+ //#endregion
880
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js
881
+ var require_sharedArrayCancellation = /* @__PURE__ */ __commonJSMin(((exports) => {
882
+ Object.defineProperty(exports, "__esModule", { value: true });
883
+ exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = void 0;
884
+ const cancellation_1 = require_cancellation();
885
+ var CancellationState;
886
+ (function(CancellationState) {
887
+ CancellationState.Continue = 0;
888
+ CancellationState.Cancelled = 1;
889
+ })(CancellationState || (CancellationState = {}));
890
+ var SharedArraySenderStrategy = class {
891
+ constructor() {
892
+ this.buffers = /* @__PURE__ */ new Map();
893
+ }
894
+ enableCancellation(request) {
895
+ if (request.id === null) return;
896
+ const buffer = new SharedArrayBuffer(4);
897
+ const data = new Int32Array(buffer, 0, 1);
898
+ data[0] = CancellationState.Continue;
899
+ this.buffers.set(request.id, buffer);
900
+ request.$cancellationData = buffer;
901
+ }
902
+ async sendCancellation(_conn, id) {
903
+ const buffer = this.buffers.get(id);
904
+ if (buffer === void 0) return;
905
+ const data = new Int32Array(buffer, 0, 1);
906
+ Atomics.store(data, 0, CancellationState.Cancelled);
907
+ }
908
+ cleanup(id) {
909
+ this.buffers.delete(id);
910
+ }
911
+ dispose() {
912
+ this.buffers.clear();
913
+ }
914
+ };
915
+ exports.SharedArraySenderStrategy = SharedArraySenderStrategy;
916
+ var SharedArrayBufferCancellationToken = class {
917
+ constructor(buffer) {
918
+ this.data = new Int32Array(buffer, 0, 1);
919
+ }
920
+ get isCancellationRequested() {
921
+ return Atomics.load(this.data, 0) === CancellationState.Cancelled;
922
+ }
923
+ get onCancellationRequested() {
924
+ throw new Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`);
925
+ }
926
+ };
927
+ var SharedArrayBufferCancellationTokenSource = class {
928
+ constructor(buffer) {
929
+ this.token = new SharedArrayBufferCancellationToken(buffer);
930
+ }
931
+ cancel() {}
932
+ dispose() {}
933
+ };
934
+ var SharedArrayReceiverStrategy = class {
935
+ constructor() {
936
+ this.kind = "request";
937
+ }
938
+ createCancellationTokenSource(request) {
939
+ const buffer = request.$cancellationData;
940
+ if (buffer === void 0) return new cancellation_1.CancellationTokenSource();
941
+ return new SharedArrayBufferCancellationTokenSource(buffer);
942
+ }
943
+ };
944
+ exports.SharedArrayReceiverStrategy = SharedArrayReceiverStrategy;
945
+ }));
946
+
947
+ //#endregion
948
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/semaphore.js
949
+ var require_semaphore = /* @__PURE__ */ __commonJSMin(((exports) => {
950
+ Object.defineProperty(exports, "__esModule", { value: true });
951
+ exports.Semaphore = void 0;
952
+ const ral_1 = require_ral();
953
+ var Semaphore = class {
954
+ constructor(capacity = 1) {
955
+ if (capacity <= 0) throw new Error("Capacity must be greater than 0");
956
+ this._capacity = capacity;
957
+ this._active = 0;
958
+ this._waiting = [];
959
+ }
960
+ lock(thunk) {
961
+ return new Promise((resolve, reject) => {
962
+ this._waiting.push({
963
+ thunk,
964
+ resolve,
965
+ reject
966
+ });
967
+ this.runNext();
968
+ });
969
+ }
970
+ get active() {
971
+ return this._active;
972
+ }
973
+ runNext() {
974
+ if (this._waiting.length === 0 || this._active === this._capacity) return;
975
+ (0, ral_1.default)().timer.setImmediate(() => this.doRunNext());
976
+ }
977
+ doRunNext() {
978
+ if (this._waiting.length === 0 || this._active === this._capacity) return;
979
+ const next = this._waiting.shift();
980
+ this._active++;
981
+ if (this._active > this._capacity) throw new Error(`To many thunks active`);
982
+ try {
983
+ const result = next.thunk();
984
+ if (result instanceof Promise) result.then((value) => {
985
+ this._active--;
986
+ next.resolve(value);
987
+ this.runNext();
988
+ }, (err) => {
989
+ this._active--;
990
+ next.reject(err);
991
+ this.runNext();
992
+ });
993
+ else {
994
+ this._active--;
995
+ next.resolve(result);
996
+ this.runNext();
997
+ }
998
+ } catch (err) {
999
+ this._active--;
1000
+ next.reject(err);
1001
+ this.runNext();
1002
+ }
1003
+ }
1004
+ };
1005
+ exports.Semaphore = Semaphore;
1006
+ }));
1007
+
1008
+ //#endregion
1009
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/messageReader.js
1010
+ var require_messageReader = /* @__PURE__ */ __commonJSMin(((exports) => {
1011
+ Object.defineProperty(exports, "__esModule", { value: true });
1012
+ exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = void 0;
1013
+ const ral_1 = require_ral();
1014
+ const Is = require_is();
1015
+ const events_1 = require_events();
1016
+ const semaphore_1 = require_semaphore();
1017
+ var MessageReader;
1018
+ (function(MessageReader) {
1019
+ function is(value) {
1020
+ let candidate = value;
1021
+ return candidate && Is.func(candidate.listen) && Is.func(candidate.dispose) && Is.func(candidate.onError) && Is.func(candidate.onClose) && Is.func(candidate.onPartialMessage);
1022
+ }
1023
+ MessageReader.is = is;
1024
+ })(MessageReader || (exports.MessageReader = MessageReader = {}));
1025
+ var AbstractMessageReader = class {
1026
+ constructor() {
1027
+ this.errorEmitter = new events_1.Emitter();
1028
+ this.closeEmitter = new events_1.Emitter();
1029
+ this.partialMessageEmitter = new events_1.Emitter();
1030
+ }
1031
+ dispose() {
1032
+ this.errorEmitter.dispose();
1033
+ this.closeEmitter.dispose();
1034
+ }
1035
+ get onError() {
1036
+ return this.errorEmitter.event;
1037
+ }
1038
+ fireError(error) {
1039
+ this.errorEmitter.fire(this.asError(error));
1040
+ }
1041
+ get onClose() {
1042
+ return this.closeEmitter.event;
1043
+ }
1044
+ fireClose() {
1045
+ this.closeEmitter.fire(void 0);
1046
+ }
1047
+ get onPartialMessage() {
1048
+ return this.partialMessageEmitter.event;
1049
+ }
1050
+ firePartialMessage(info) {
1051
+ this.partialMessageEmitter.fire(info);
1052
+ }
1053
+ asError(error) {
1054
+ if (error instanceof Error) return error;
1055
+ else return /* @__PURE__ */ new Error(`Reader received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
1056
+ }
1057
+ };
1058
+ exports.AbstractMessageReader = AbstractMessageReader;
1059
+ var ResolvedMessageReaderOptions;
1060
+ (function(ResolvedMessageReaderOptions) {
1061
+ function fromOptions(options) {
1062
+ let charset;
1063
+ let contentDecoder;
1064
+ const contentDecoders = /* @__PURE__ */ new Map();
1065
+ let contentTypeDecoder;
1066
+ const contentTypeDecoders = /* @__PURE__ */ new Map();
1067
+ if (options === void 0 || typeof options === "string") charset = options ?? "utf-8";
1068
+ else {
1069
+ charset = options.charset ?? "utf-8";
1070
+ if (options.contentDecoder !== void 0) {
1071
+ contentDecoder = options.contentDecoder;
1072
+ contentDecoders.set(contentDecoder.name, contentDecoder);
1073
+ }
1074
+ if (options.contentDecoders !== void 0) for (const decoder of options.contentDecoders) contentDecoders.set(decoder.name, decoder);
1075
+ if (options.contentTypeDecoder !== void 0) {
1076
+ contentTypeDecoder = options.contentTypeDecoder;
1077
+ contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
1078
+ }
1079
+ if (options.contentTypeDecoders !== void 0) for (const decoder of options.contentTypeDecoders) contentTypeDecoders.set(decoder.name, decoder);
1080
+ }
1081
+ if (contentTypeDecoder === void 0) {
1082
+ contentTypeDecoder = (0, ral_1.default)().applicationJson.decoder;
1083
+ contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
1084
+ }
1085
+ return {
1086
+ charset,
1087
+ contentDecoder,
1088
+ contentDecoders,
1089
+ contentTypeDecoder,
1090
+ contentTypeDecoders
1091
+ };
1092
+ }
1093
+ ResolvedMessageReaderOptions.fromOptions = fromOptions;
1094
+ })(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));
1095
+ var ReadableStreamMessageReader = class extends AbstractMessageReader {
1096
+ constructor(readable, options) {
1097
+ super();
1098
+ this.readable = readable;
1099
+ this.options = ResolvedMessageReaderOptions.fromOptions(options);
1100
+ this.buffer = (0, ral_1.default)().messageBuffer.create(this.options.charset);
1101
+ this._partialMessageTimeout = 1e4;
1102
+ this.nextMessageLength = -1;
1103
+ this.messageToken = 0;
1104
+ this.readSemaphore = new semaphore_1.Semaphore(1);
1105
+ }
1106
+ set partialMessageTimeout(timeout) {
1107
+ this._partialMessageTimeout = timeout;
1108
+ }
1109
+ get partialMessageTimeout() {
1110
+ return this._partialMessageTimeout;
1111
+ }
1112
+ listen(callback) {
1113
+ this.nextMessageLength = -1;
1114
+ this.messageToken = 0;
1115
+ this.partialMessageTimer = void 0;
1116
+ this.callback = callback;
1117
+ const result = this.readable.onData((data) => {
1118
+ this.onData(data);
1119
+ });
1120
+ this.readable.onError((error) => this.fireError(error));
1121
+ this.readable.onClose(() => this.fireClose());
1122
+ return result;
1123
+ }
1124
+ onData(data) {
1125
+ try {
1126
+ this.buffer.append(data);
1127
+ while (true) {
1128
+ if (this.nextMessageLength === -1) {
1129
+ const headers = this.buffer.tryReadHeaders(true);
1130
+ if (!headers) return;
1131
+ const contentLength = headers.get("content-length");
1132
+ if (!contentLength) {
1133
+ this.fireError(/* @__PURE__ */ new Error(`Header must provide a Content-Length property.\n${JSON.stringify(Object.fromEntries(headers))}`));
1134
+ return;
1135
+ }
1136
+ const length = parseInt(contentLength);
1137
+ if (isNaN(length)) {
1138
+ this.fireError(/* @__PURE__ */ new Error(`Content-Length value must be a number. Got ${contentLength}`));
1139
+ return;
1140
+ }
1141
+ this.nextMessageLength = length;
1142
+ }
1143
+ const body = this.buffer.tryReadBody(this.nextMessageLength);
1144
+ if (body === void 0) {
1145
+ /** We haven't received the full message yet. */
1146
+ this.setPartialMessageTimer();
1147
+ return;
1148
+ }
1149
+ this.clearPartialMessageTimer();
1150
+ this.nextMessageLength = -1;
1151
+ this.readSemaphore.lock(async () => {
1152
+ const bytes = this.options.contentDecoder !== void 0 ? await this.options.contentDecoder.decode(body) : body;
1153
+ const message = await this.options.contentTypeDecoder.decode(bytes, this.options);
1154
+ this.callback(message);
1155
+ }).catch((error) => {
1156
+ this.fireError(error);
1157
+ });
1158
+ }
1159
+ } catch (error) {
1160
+ this.fireError(error);
1161
+ }
1162
+ }
1163
+ clearPartialMessageTimer() {
1164
+ if (this.partialMessageTimer) {
1165
+ this.partialMessageTimer.dispose();
1166
+ this.partialMessageTimer = void 0;
1167
+ }
1168
+ }
1169
+ setPartialMessageTimer() {
1170
+ this.clearPartialMessageTimer();
1171
+ if (this._partialMessageTimeout <= 0) return;
1172
+ this.partialMessageTimer = (0, ral_1.default)().timer.setTimeout((token, timeout) => {
1173
+ this.partialMessageTimer = void 0;
1174
+ if (token === this.messageToken) {
1175
+ this.firePartialMessage({
1176
+ messageToken: token,
1177
+ waitingTime: timeout
1178
+ });
1179
+ this.setPartialMessageTimer();
1180
+ }
1181
+ }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
1182
+ }
1183
+ };
1184
+ exports.ReadableStreamMessageReader = ReadableStreamMessageReader;
1185
+ }));
1186
+
1187
+ //#endregion
1188
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/messageWriter.js
1189
+ var require_messageWriter = /* @__PURE__ */ __commonJSMin(((exports) => {
1190
+ Object.defineProperty(exports, "__esModule", { value: true });
1191
+ exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = void 0;
1192
+ const ral_1 = require_ral();
1193
+ const Is = require_is();
1194
+ const semaphore_1 = require_semaphore();
1195
+ const events_1 = require_events();
1196
+ const ContentLength = "Content-Length: ";
1197
+ const CRLF = "\r\n";
1198
+ var MessageWriter;
1199
+ (function(MessageWriter) {
1200
+ function is(value) {
1201
+ let candidate = value;
1202
+ return candidate && Is.func(candidate.dispose) && Is.func(candidate.onClose) && Is.func(candidate.onError) && Is.func(candidate.write);
1203
+ }
1204
+ MessageWriter.is = is;
1205
+ })(MessageWriter || (exports.MessageWriter = MessageWriter = {}));
1206
+ var AbstractMessageWriter = class {
1207
+ constructor() {
1208
+ this.errorEmitter = new events_1.Emitter();
1209
+ this.closeEmitter = new events_1.Emitter();
1210
+ }
1211
+ dispose() {
1212
+ this.errorEmitter.dispose();
1213
+ this.closeEmitter.dispose();
1214
+ }
1215
+ get onError() {
1216
+ return this.errorEmitter.event;
1217
+ }
1218
+ fireError(error, message, count) {
1219
+ this.errorEmitter.fire([
1220
+ this.asError(error),
1221
+ message,
1222
+ count
1223
+ ]);
1224
+ }
1225
+ get onClose() {
1226
+ return this.closeEmitter.event;
1227
+ }
1228
+ fireClose() {
1229
+ this.closeEmitter.fire(void 0);
1230
+ }
1231
+ asError(error) {
1232
+ if (error instanceof Error) return error;
1233
+ else return /* @__PURE__ */ new Error(`Writer received error. Reason: ${Is.string(error.message) ? error.message : "unknown"}`);
1234
+ }
1235
+ };
1236
+ exports.AbstractMessageWriter = AbstractMessageWriter;
1237
+ var ResolvedMessageWriterOptions;
1238
+ (function(ResolvedMessageWriterOptions) {
1239
+ function fromOptions(options) {
1240
+ if (options === void 0 || typeof options === "string") return {
1241
+ charset: options ?? "utf-8",
1242
+ contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder
1243
+ };
1244
+ else return {
1245
+ charset: options.charset ?? "utf-8",
1246
+ contentEncoder: options.contentEncoder,
1247
+ contentTypeEncoder: options.contentTypeEncoder ?? (0, ral_1.default)().applicationJson.encoder
1248
+ };
1249
+ }
1250
+ ResolvedMessageWriterOptions.fromOptions = fromOptions;
1251
+ })(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
1252
+ var WriteableStreamMessageWriter = class extends AbstractMessageWriter {
1253
+ constructor(writable, options) {
1254
+ super();
1255
+ this.writable = writable;
1256
+ this.options = ResolvedMessageWriterOptions.fromOptions(options);
1257
+ this.errorCount = 0;
1258
+ this.writeSemaphore = new semaphore_1.Semaphore(1);
1259
+ this.writable.onError((error) => this.fireError(error));
1260
+ this.writable.onClose(() => this.fireClose());
1261
+ }
1262
+ async write(msg) {
1263
+ return this.writeSemaphore.lock(async () => {
1264
+ return this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
1265
+ if (this.options.contentEncoder !== void 0) return this.options.contentEncoder.encode(buffer);
1266
+ else return buffer;
1267
+ }).then((buffer) => {
1268
+ const headers = [];
1269
+ headers.push(ContentLength, buffer.byteLength.toString(), CRLF);
1270
+ headers.push(CRLF);
1271
+ return this.doWrite(msg, headers, buffer);
1272
+ }, (error) => {
1273
+ this.fireError(error);
1274
+ throw error;
1275
+ });
1276
+ });
1277
+ }
1278
+ async doWrite(msg, headers, data) {
1279
+ try {
1280
+ await this.writable.write(headers.join(""), "ascii");
1281
+ return this.writable.write(data);
1282
+ } catch (error) {
1283
+ this.handleError(error, msg);
1284
+ return Promise.reject(error);
1285
+ }
1286
+ }
1287
+ handleError(error, msg) {
1288
+ this.errorCount++;
1289
+ this.fireError(error, msg, this.errorCount);
1290
+ }
1291
+ end() {
1292
+ this.writable.end();
1293
+ }
1294
+ };
1295
+ exports.WriteableStreamMessageWriter = WriteableStreamMessageWriter;
1296
+ }));
1297
+
1298
+ //#endregion
1299
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/messageBuffer.js
1300
+ var require_messageBuffer = /* @__PURE__ */ __commonJSMin(((exports) => {
1301
+ Object.defineProperty(exports, "__esModule", { value: true });
1302
+ exports.AbstractMessageBuffer = void 0;
1303
+ const CR = 13;
1304
+ const LF = 10;
1305
+ const CRLF = "\r\n";
1306
+ var AbstractMessageBuffer = class {
1307
+ constructor(encoding = "utf-8") {
1308
+ this._encoding = encoding;
1309
+ this._chunks = [];
1310
+ this._totalLength = 0;
1311
+ }
1312
+ get encoding() {
1313
+ return this._encoding;
1314
+ }
1315
+ append(chunk) {
1316
+ const toAppend = typeof chunk === "string" ? this.fromString(chunk, this._encoding) : chunk;
1317
+ this._chunks.push(toAppend);
1318
+ this._totalLength += toAppend.byteLength;
1319
+ }
1320
+ tryReadHeaders(lowerCaseKeys = false) {
1321
+ if (this._chunks.length === 0) return;
1322
+ let state = 0;
1323
+ let chunkIndex = 0;
1324
+ let offset = 0;
1325
+ let chunkBytesRead = 0;
1326
+ row: while (chunkIndex < this._chunks.length) {
1327
+ const chunk = this._chunks[chunkIndex];
1328
+ offset = 0;
1329
+ column: while (offset < chunk.length) {
1330
+ switch (chunk[offset]) {
1331
+ case CR:
1332
+ switch (state) {
1333
+ case 0:
1334
+ state = 1;
1335
+ break;
1336
+ case 2:
1337
+ state = 3;
1338
+ break;
1339
+ default: state = 0;
1340
+ }
1341
+ break;
1342
+ case LF:
1343
+ switch (state) {
1344
+ case 1:
1345
+ state = 2;
1346
+ break;
1347
+ case 3:
1348
+ state = 4;
1349
+ offset++;
1350
+ break row;
1351
+ default: state = 0;
1352
+ }
1353
+ break;
1354
+ default: state = 0;
1355
+ }
1356
+ offset++;
1357
+ }
1358
+ chunkBytesRead += chunk.byteLength;
1359
+ chunkIndex++;
1360
+ }
1361
+ if (state !== 4) return;
1362
+ const buffer = this._read(chunkBytesRead + offset);
1363
+ const result = /* @__PURE__ */ new Map();
1364
+ const headers = this.toString(buffer, "ascii").split(CRLF);
1365
+ if (headers.length < 2) return result;
1366
+ for (let i = 0; i < headers.length - 2; i++) {
1367
+ const header = headers[i];
1368
+ const index = header.indexOf(":");
1369
+ if (index === -1) throw new Error(`Message header must separate key and value using ':'\n${header}`);
1370
+ const key = header.substr(0, index);
1371
+ const value = header.substr(index + 1).trim();
1372
+ result.set(lowerCaseKeys ? key.toLowerCase() : key, value);
1373
+ }
1374
+ return result;
1375
+ }
1376
+ tryReadBody(length) {
1377
+ if (this._totalLength < length) return;
1378
+ return this._read(length);
1379
+ }
1380
+ get numberOfBytes() {
1381
+ return this._totalLength;
1382
+ }
1383
+ _read(byteCount) {
1384
+ if (byteCount === 0) return this.emptyBuffer();
1385
+ if (byteCount > this._totalLength) throw new Error(`Cannot read so many bytes!`);
1386
+ if (this._chunks[0].byteLength === byteCount) {
1387
+ const chunk = this._chunks[0];
1388
+ this._chunks.shift();
1389
+ this._totalLength -= byteCount;
1390
+ return this.asNative(chunk);
1391
+ }
1392
+ if (this._chunks[0].byteLength > byteCount) {
1393
+ const chunk = this._chunks[0];
1394
+ const result = this.asNative(chunk, byteCount);
1395
+ this._chunks[0] = chunk.slice(byteCount);
1396
+ this._totalLength -= byteCount;
1397
+ return result;
1398
+ }
1399
+ const result = this.allocNative(byteCount);
1400
+ let resultOffset = 0;
1401
+ let chunkIndex = 0;
1402
+ while (byteCount > 0) {
1403
+ const chunk = this._chunks[chunkIndex];
1404
+ if (chunk.byteLength > byteCount) {
1405
+ const chunkPart = chunk.slice(0, byteCount);
1406
+ result.set(chunkPart, resultOffset);
1407
+ resultOffset += byteCount;
1408
+ this._chunks[chunkIndex] = chunk.slice(byteCount);
1409
+ this._totalLength -= byteCount;
1410
+ byteCount -= byteCount;
1411
+ } else {
1412
+ result.set(chunk, resultOffset);
1413
+ resultOffset += chunk.byteLength;
1414
+ this._chunks.shift();
1415
+ this._totalLength -= chunk.byteLength;
1416
+ byteCount -= chunk.byteLength;
1417
+ }
1418
+ }
1419
+ return result;
1420
+ }
1421
+ };
1422
+ exports.AbstractMessageBuffer = AbstractMessageBuffer;
1423
+ }));
1424
+
1425
+ //#endregion
1426
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/connection.js
1427
+ var require_connection = /* @__PURE__ */ __commonJSMin(((exports) => {
1428
+ Object.defineProperty(exports, "__esModule", { value: true });
1429
+ exports.createMessageConnection = exports.ConnectionOptions = exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.RequestCancellationReceiverStrategy = exports.IdCancellationReceiverStrategy = exports.ConnectionStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = exports.NullLogger = exports.ProgressType = exports.ProgressToken = void 0;
1430
+ const ral_1 = require_ral();
1431
+ const Is = require_is();
1432
+ const messages_1 = require_messages();
1433
+ const linkedMap_1 = require_linkedMap();
1434
+ const events_1 = require_events();
1435
+ const cancellation_1 = require_cancellation();
1436
+ var CancelNotification;
1437
+ (function(CancelNotification) {
1438
+ CancelNotification.type = new messages_1.NotificationType("$/cancelRequest");
1439
+ })(CancelNotification || (CancelNotification = {}));
1440
+ var ProgressToken;
1441
+ (function(ProgressToken) {
1442
+ function is(value) {
1443
+ return typeof value === "string" || typeof value === "number";
1444
+ }
1445
+ ProgressToken.is = is;
1446
+ })(ProgressToken || (exports.ProgressToken = ProgressToken = {}));
1447
+ var ProgressNotification;
1448
+ (function(ProgressNotification) {
1449
+ ProgressNotification.type = new messages_1.NotificationType("$/progress");
1450
+ })(ProgressNotification || (ProgressNotification = {}));
1451
+ var ProgressType = class {
1452
+ constructor() {}
1453
+ };
1454
+ exports.ProgressType = ProgressType;
1455
+ var StarRequestHandler;
1456
+ (function(StarRequestHandler) {
1457
+ function is(value) {
1458
+ return Is.func(value);
1459
+ }
1460
+ StarRequestHandler.is = is;
1461
+ })(StarRequestHandler || (StarRequestHandler = {}));
1462
+ exports.NullLogger = Object.freeze({
1463
+ error: () => {},
1464
+ warn: () => {},
1465
+ info: () => {},
1466
+ log: () => {}
1467
+ });
1468
+ var Trace;
1469
+ (function(Trace) {
1470
+ Trace[Trace["Off"] = 0] = "Off";
1471
+ Trace[Trace["Messages"] = 1] = "Messages";
1472
+ Trace[Trace["Compact"] = 2] = "Compact";
1473
+ Trace[Trace["Verbose"] = 3] = "Verbose";
1474
+ })(Trace || (exports.Trace = Trace = {}));
1475
+ var TraceValues;
1476
+ (function(TraceValues) {
1477
+ /**
1478
+ * Turn tracing off.
1479
+ */
1480
+ TraceValues.Off = "off";
1481
+ /**
1482
+ * Trace messages only.
1483
+ */
1484
+ TraceValues.Messages = "messages";
1485
+ /**
1486
+ * Compact message tracing.
1487
+ */
1488
+ TraceValues.Compact = "compact";
1489
+ /**
1490
+ * Verbose message tracing.
1491
+ */
1492
+ TraceValues.Verbose = "verbose";
1493
+ })(TraceValues || (exports.TraceValues = TraceValues = {}));
1494
+ (function(Trace) {
1495
+ function fromString(value) {
1496
+ if (!Is.string(value)) return Trace.Off;
1497
+ value = value.toLowerCase();
1498
+ switch (value) {
1499
+ case "off": return Trace.Off;
1500
+ case "messages": return Trace.Messages;
1501
+ case "compact": return Trace.Compact;
1502
+ case "verbose": return Trace.Verbose;
1503
+ default: return Trace.Off;
1504
+ }
1505
+ }
1506
+ Trace.fromString = fromString;
1507
+ function toString(value) {
1508
+ switch (value) {
1509
+ case Trace.Off: return "off";
1510
+ case Trace.Messages: return "messages";
1511
+ case Trace.Compact: return "compact";
1512
+ case Trace.Verbose: return "verbose";
1513
+ default: return "off";
1514
+ }
1515
+ }
1516
+ Trace.toString = toString;
1517
+ })(Trace || (exports.Trace = Trace = {}));
1518
+ var TraceFormat;
1519
+ (function(TraceFormat) {
1520
+ TraceFormat["Text"] = "text";
1521
+ TraceFormat["JSON"] = "json";
1522
+ })(TraceFormat || (exports.TraceFormat = TraceFormat = {}));
1523
+ (function(TraceFormat) {
1524
+ function fromString(value) {
1525
+ if (!Is.string(value)) return TraceFormat.Text;
1526
+ value = value.toLowerCase();
1527
+ if (value === "json") return TraceFormat.JSON;
1528
+ else return TraceFormat.Text;
1529
+ }
1530
+ TraceFormat.fromString = fromString;
1531
+ })(TraceFormat || (exports.TraceFormat = TraceFormat = {}));
1532
+ var SetTraceNotification;
1533
+ (function(SetTraceNotification) {
1534
+ SetTraceNotification.type = new messages_1.NotificationType("$/setTrace");
1535
+ })(SetTraceNotification || (exports.SetTraceNotification = SetTraceNotification = {}));
1536
+ var LogTraceNotification;
1537
+ (function(LogTraceNotification) {
1538
+ LogTraceNotification.type = new messages_1.NotificationType("$/logTrace");
1539
+ })(LogTraceNotification || (exports.LogTraceNotification = LogTraceNotification = {}));
1540
+ var ConnectionErrors;
1541
+ (function(ConnectionErrors) {
1542
+ /**
1543
+ * The connection is closed.
1544
+ */
1545
+ ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed";
1546
+ /**
1547
+ * The connection got disposed.
1548
+ */
1549
+ ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed";
1550
+ /**
1551
+ * The connection is already in listening mode.
1552
+ */
1553
+ ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";
1554
+ })(ConnectionErrors || (exports.ConnectionErrors = ConnectionErrors = {}));
1555
+ var ConnectionError = class ConnectionError extends Error {
1556
+ constructor(code, message) {
1557
+ super(message);
1558
+ this.code = code;
1559
+ Object.setPrototypeOf(this, ConnectionError.prototype);
1560
+ }
1561
+ };
1562
+ exports.ConnectionError = ConnectionError;
1563
+ var ConnectionStrategy;
1564
+ (function(ConnectionStrategy) {
1565
+ function is(value) {
1566
+ const candidate = value;
1567
+ return candidate && Is.func(candidate.cancelUndispatched);
1568
+ }
1569
+ ConnectionStrategy.is = is;
1570
+ })(ConnectionStrategy || (exports.ConnectionStrategy = ConnectionStrategy = {}));
1571
+ var IdCancellationReceiverStrategy;
1572
+ (function(IdCancellationReceiverStrategy) {
1573
+ function is(value) {
1574
+ const candidate = value;
1575
+ return candidate && (candidate.kind === void 0 || candidate.kind === "id") && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === void 0 || Is.func(candidate.dispose));
1576
+ }
1577
+ IdCancellationReceiverStrategy.is = is;
1578
+ })(IdCancellationReceiverStrategy || (exports.IdCancellationReceiverStrategy = IdCancellationReceiverStrategy = {}));
1579
+ var RequestCancellationReceiverStrategy;
1580
+ (function(RequestCancellationReceiverStrategy) {
1581
+ function is(value) {
1582
+ const candidate = value;
1583
+ return candidate && candidate.kind === "request" && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === void 0 || Is.func(candidate.dispose));
1584
+ }
1585
+ RequestCancellationReceiverStrategy.is = is;
1586
+ })(RequestCancellationReceiverStrategy || (exports.RequestCancellationReceiverStrategy = RequestCancellationReceiverStrategy = {}));
1587
+ var CancellationReceiverStrategy;
1588
+ (function(CancellationReceiverStrategy) {
1589
+ CancellationReceiverStrategy.Message = Object.freeze({ createCancellationTokenSource(_) {
1590
+ return new cancellation_1.CancellationTokenSource();
1591
+ } });
1592
+ function is(value) {
1593
+ return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value);
1594
+ }
1595
+ CancellationReceiverStrategy.is = is;
1596
+ })(CancellationReceiverStrategy || (exports.CancellationReceiverStrategy = CancellationReceiverStrategy = {}));
1597
+ var CancellationSenderStrategy;
1598
+ (function(CancellationSenderStrategy) {
1599
+ CancellationSenderStrategy.Message = Object.freeze({
1600
+ sendCancellation(conn, id) {
1601
+ return conn.sendNotification(CancelNotification.type, { id });
1602
+ },
1603
+ cleanup(_) {}
1604
+ });
1605
+ function is(value) {
1606
+ const candidate = value;
1607
+ return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup);
1608
+ }
1609
+ CancellationSenderStrategy.is = is;
1610
+ })(CancellationSenderStrategy || (exports.CancellationSenderStrategy = CancellationSenderStrategy = {}));
1611
+ var CancellationStrategy;
1612
+ (function(CancellationStrategy) {
1613
+ CancellationStrategy.Message = Object.freeze({
1614
+ receiver: CancellationReceiverStrategy.Message,
1615
+ sender: CancellationSenderStrategy.Message
1616
+ });
1617
+ function is(value) {
1618
+ const candidate = value;
1619
+ return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);
1620
+ }
1621
+ CancellationStrategy.is = is;
1622
+ })(CancellationStrategy || (exports.CancellationStrategy = CancellationStrategy = {}));
1623
+ var MessageStrategy;
1624
+ (function(MessageStrategy) {
1625
+ function is(value) {
1626
+ const candidate = value;
1627
+ return candidate && Is.func(candidate.handleMessage);
1628
+ }
1629
+ MessageStrategy.is = is;
1630
+ })(MessageStrategy || (exports.MessageStrategy = MessageStrategy = {}));
1631
+ var ConnectionOptions;
1632
+ (function(ConnectionOptions) {
1633
+ function is(value) {
1634
+ const candidate = value;
1635
+ return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy));
1636
+ }
1637
+ ConnectionOptions.is = is;
1638
+ })(ConnectionOptions || (exports.ConnectionOptions = ConnectionOptions = {}));
1639
+ var ConnectionState;
1640
+ (function(ConnectionState) {
1641
+ ConnectionState[ConnectionState["New"] = 1] = "New";
1642
+ ConnectionState[ConnectionState["Listening"] = 2] = "Listening";
1643
+ ConnectionState[ConnectionState["Closed"] = 3] = "Closed";
1644
+ ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";
1645
+ })(ConnectionState || (ConnectionState = {}));
1646
+ function createMessageConnection(messageReader, messageWriter, _logger, options) {
1647
+ const logger = _logger !== void 0 ? _logger : exports.NullLogger;
1648
+ let sequenceNumber = 0;
1649
+ let notificationSequenceNumber = 0;
1650
+ let unknownResponseSequenceNumber = 0;
1651
+ const version = "2.0";
1652
+ let starRequestHandler = void 0;
1653
+ const requestHandlers = /* @__PURE__ */ new Map();
1654
+ let starNotificationHandler = void 0;
1655
+ const notificationHandlers = /* @__PURE__ */ new Map();
1656
+ const progressHandlers = /* @__PURE__ */ new Map();
1657
+ let timer;
1658
+ let messageQueue = new linkedMap_1.LinkedMap();
1659
+ let responsePromises = /* @__PURE__ */ new Map();
1660
+ let knownCanceledRequests = /* @__PURE__ */ new Set();
1661
+ let requestTokens = /* @__PURE__ */ new Map();
1662
+ let trace = Trace.Off;
1663
+ let traceFormat = TraceFormat.Text;
1664
+ let tracer;
1665
+ let state = ConnectionState.New;
1666
+ const errorEmitter = new events_1.Emitter();
1667
+ const closeEmitter = new events_1.Emitter();
1668
+ const unhandledNotificationEmitter = new events_1.Emitter();
1669
+ const unhandledProgressEmitter = new events_1.Emitter();
1670
+ const disposeEmitter = new events_1.Emitter();
1671
+ const cancellationStrategy = options && options.cancellationStrategy ? options.cancellationStrategy : CancellationStrategy.Message;
1672
+ function createRequestQueueKey(id) {
1673
+ if (id === null) throw new Error(`Can't send requests with id null since the response can't be correlated.`);
1674
+ return "req-" + id.toString();
1675
+ }
1676
+ function createResponseQueueKey(id) {
1677
+ if (id === null) return "res-unknown-" + (++unknownResponseSequenceNumber).toString();
1678
+ else return "res-" + id.toString();
1679
+ }
1680
+ function createNotificationQueueKey() {
1681
+ return "not-" + (++notificationSequenceNumber).toString();
1682
+ }
1683
+ function addMessageToQueue(queue, message) {
1684
+ if (messages_1.Message.isRequest(message)) queue.set(createRequestQueueKey(message.id), message);
1685
+ else if (messages_1.Message.isResponse(message)) queue.set(createResponseQueueKey(message.id), message);
1686
+ else queue.set(createNotificationQueueKey(), message);
1687
+ }
1688
+ function cancelUndispatched(_message) {}
1689
+ function isListening() {
1690
+ return state === ConnectionState.Listening;
1691
+ }
1692
+ function isClosed() {
1693
+ return state === ConnectionState.Closed;
1694
+ }
1695
+ function isDisposed() {
1696
+ return state === ConnectionState.Disposed;
1697
+ }
1698
+ function closeHandler() {
1699
+ if (state === ConnectionState.New || state === ConnectionState.Listening) {
1700
+ state = ConnectionState.Closed;
1701
+ closeEmitter.fire(void 0);
1702
+ }
1703
+ }
1704
+ function readErrorHandler(error) {
1705
+ errorEmitter.fire([
1706
+ error,
1707
+ void 0,
1708
+ void 0
1709
+ ]);
1710
+ }
1711
+ function writeErrorHandler(data) {
1712
+ errorEmitter.fire(data);
1713
+ }
1714
+ messageReader.onClose(closeHandler);
1715
+ messageReader.onError(readErrorHandler);
1716
+ messageWriter.onClose(closeHandler);
1717
+ messageWriter.onError(writeErrorHandler);
1718
+ function triggerMessageQueue() {
1719
+ if (timer || messageQueue.size === 0) return;
1720
+ timer = (0, ral_1.default)().timer.setImmediate(() => {
1721
+ timer = void 0;
1722
+ processMessageQueue();
1723
+ });
1724
+ }
1725
+ function handleMessage(message) {
1726
+ if (messages_1.Message.isRequest(message)) handleRequest(message);
1727
+ else if (messages_1.Message.isNotification(message)) handleNotification(message);
1728
+ else if (messages_1.Message.isResponse(message)) handleResponse(message);
1729
+ else handleInvalidMessage(message);
1730
+ }
1731
+ function processMessageQueue() {
1732
+ if (messageQueue.size === 0) return;
1733
+ const message = messageQueue.shift();
1734
+ try {
1735
+ const messageStrategy = options?.messageStrategy;
1736
+ if (MessageStrategy.is(messageStrategy)) messageStrategy.handleMessage(message, handleMessage);
1737
+ else handleMessage(message);
1738
+ } finally {
1739
+ triggerMessageQueue();
1740
+ }
1741
+ }
1742
+ const callback = (message) => {
1743
+ try {
1744
+ if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) {
1745
+ const cancelId = message.params.id;
1746
+ const key = createRequestQueueKey(cancelId);
1747
+ const toCancel = messageQueue.get(key);
1748
+ if (messages_1.Message.isRequest(toCancel)) {
1749
+ const strategy = options?.connectionStrategy;
1750
+ const response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
1751
+ if (response && (response.error !== void 0 || response.result !== void 0)) {
1752
+ messageQueue.delete(key);
1753
+ requestTokens.delete(cancelId);
1754
+ response.id = toCancel.id;
1755
+ traceSendingResponse(response, message.method, Date.now());
1756
+ messageWriter.write(response).catch(() => logger.error(`Sending response for canceled message failed.`));
1757
+ return;
1758
+ }
1759
+ }
1760
+ const cancellationToken = requestTokens.get(cancelId);
1761
+ if (cancellationToken !== void 0) {
1762
+ cancellationToken.cancel();
1763
+ traceReceivedNotification(message);
1764
+ return;
1765
+ } else knownCanceledRequests.add(cancelId);
1766
+ }
1767
+ addMessageToQueue(messageQueue, message);
1768
+ } finally {
1769
+ triggerMessageQueue();
1770
+ }
1771
+ };
1772
+ function handleRequest(requestMessage) {
1773
+ if (isDisposed()) return;
1774
+ function reply(resultOrError, method, startTime) {
1775
+ const message = {
1776
+ jsonrpc: version,
1777
+ id: requestMessage.id
1778
+ };
1779
+ if (resultOrError instanceof messages_1.ResponseError) message.error = resultOrError.toJson();
1780
+ else message.result = resultOrError === void 0 ? null : resultOrError;
1781
+ traceSendingResponse(message, method, startTime);
1782
+ messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
1783
+ }
1784
+ function replyError(error, method, startTime) {
1785
+ const message = {
1786
+ jsonrpc: version,
1787
+ id: requestMessage.id,
1788
+ error: error.toJson()
1789
+ };
1790
+ traceSendingResponse(message, method, startTime);
1791
+ messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
1792
+ }
1793
+ function replySuccess(result, method, startTime) {
1794
+ if (result === void 0) result = null;
1795
+ const message = {
1796
+ jsonrpc: version,
1797
+ id: requestMessage.id,
1798
+ result
1799
+ };
1800
+ traceSendingResponse(message, method, startTime);
1801
+ messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
1802
+ }
1803
+ traceReceivedRequest(requestMessage);
1804
+ const element = requestHandlers.get(requestMessage.method);
1805
+ let type;
1806
+ let requestHandler;
1807
+ if (element) {
1808
+ type = element.type;
1809
+ requestHandler = element.handler;
1810
+ }
1811
+ const startTime = Date.now();
1812
+ if (requestHandler || starRequestHandler) {
1813
+ const tokenKey = requestMessage.id ?? String(Date.now());
1814
+ const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver) ? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey) : cancellationStrategy.receiver.createCancellationTokenSource(requestMessage);
1815
+ if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) cancellationSource.cancel();
1816
+ if (requestMessage.id !== null) requestTokens.set(tokenKey, cancellationSource);
1817
+ try {
1818
+ let handlerResult;
1819
+ if (requestHandler) if (requestMessage.params === void 0) {
1820
+ if (type !== void 0 && type.numberOfParams !== 0) {
1821
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime);
1822
+ return;
1823
+ }
1824
+ handlerResult = requestHandler(cancellationSource.token);
1825
+ } else if (Array.isArray(requestMessage.params)) {
1826
+ if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byName) {
1827
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime);
1828
+ return;
1829
+ }
1830
+ handlerResult = requestHandler(...requestMessage.params, cancellationSource.token);
1831
+ } else {
1832
+ if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
1833
+ replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime);
1834
+ return;
1835
+ }
1836
+ handlerResult = requestHandler(requestMessage.params, cancellationSource.token);
1837
+ }
1838
+ else if (starRequestHandler) handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
1839
+ const promise = handlerResult;
1840
+ if (!handlerResult) {
1841
+ requestTokens.delete(tokenKey);
1842
+ replySuccess(handlerResult, requestMessage.method, startTime);
1843
+ } else if (promise.then) promise.then((resultOrError) => {
1844
+ requestTokens.delete(tokenKey);
1845
+ reply(resultOrError, requestMessage.method, startTime);
1846
+ }, (error) => {
1847
+ requestTokens.delete(tokenKey);
1848
+ if (error instanceof messages_1.ResponseError) replyError(error, requestMessage.method, startTime);
1849
+ else if (error && Is.string(error.message)) replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
1850
+ else replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
1851
+ });
1852
+ else {
1853
+ requestTokens.delete(tokenKey);
1854
+ reply(handlerResult, requestMessage.method, startTime);
1855
+ }
1856
+ } catch (error) {
1857
+ requestTokens.delete(tokenKey);
1858
+ if (error instanceof messages_1.ResponseError) reply(error, requestMessage.method, startTime);
1859
+ else if (error && Is.string(error.message)) replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
1860
+ else replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
1861
+ }
1862
+ } else replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
1863
+ }
1864
+ function handleResponse(responseMessage) {
1865
+ if (isDisposed()) return;
1866
+ if (responseMessage.id === null) if (responseMessage.error) logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, void 0, 4)}`);
1867
+ else logger.error(`Received response message without id. No further error information provided.`);
1868
+ else {
1869
+ const key = responseMessage.id;
1870
+ const responsePromise = responsePromises.get(key);
1871
+ traceReceivedResponse(responseMessage, responsePromise);
1872
+ if (responsePromise !== void 0) {
1873
+ responsePromises.delete(key);
1874
+ try {
1875
+ if (responseMessage.error) {
1876
+ const error = responseMessage.error;
1877
+ responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
1878
+ } else if (responseMessage.result !== void 0) responsePromise.resolve(responseMessage.result);
1879
+ else throw new Error("Should never happen.");
1880
+ } catch (error) {
1881
+ if (error.message) logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
1882
+ else logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
1883
+ }
1884
+ }
1885
+ }
1886
+ }
1887
+ function handleNotification(message) {
1888
+ if (isDisposed()) return;
1889
+ let type = void 0;
1890
+ let notificationHandler;
1891
+ if (message.method === CancelNotification.type.method) {
1892
+ const cancelId = message.params.id;
1893
+ knownCanceledRequests.delete(cancelId);
1894
+ traceReceivedNotification(message);
1895
+ return;
1896
+ } else {
1897
+ const element = notificationHandlers.get(message.method);
1898
+ if (element) {
1899
+ notificationHandler = element.handler;
1900
+ type = element.type;
1901
+ }
1902
+ }
1903
+ if (notificationHandler || starNotificationHandler) try {
1904
+ traceReceivedNotification(message);
1905
+ if (notificationHandler) if (message.params === void 0) {
1906
+ if (type !== void 0) {
1907
+ if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`);
1908
+ }
1909
+ notificationHandler();
1910
+ } else if (Array.isArray(message.params)) {
1911
+ const params = message.params;
1912
+ if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) notificationHandler({
1913
+ token: params[0],
1914
+ value: params[1]
1915
+ });
1916
+ else {
1917
+ if (type !== void 0) {
1918
+ if (type.parameterStructures === messages_1.ParameterStructures.byName) logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`);
1919
+ if (type.numberOfParams !== message.params.length) logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`);
1920
+ }
1921
+ notificationHandler(...params);
1922
+ }
1923
+ } else {
1924
+ if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`);
1925
+ notificationHandler(message.params);
1926
+ }
1927
+ else if (starNotificationHandler) starNotificationHandler(message.method, message.params);
1928
+ } catch (error) {
1929
+ if (error.message) logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
1930
+ else logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
1931
+ }
1932
+ else unhandledNotificationEmitter.fire(message);
1933
+ }
1934
+ function handleInvalidMessage(message) {
1935
+ if (!message) {
1936
+ logger.error("Received empty message.");
1937
+ return;
1938
+ }
1939
+ logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`);
1940
+ const responseMessage = message;
1941
+ if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) {
1942
+ const key = responseMessage.id;
1943
+ const responseHandler = responsePromises.get(key);
1944
+ if (responseHandler) responseHandler.reject(/* @__PURE__ */ new Error("The received response has neither a result nor an error property."));
1945
+ }
1946
+ }
1947
+ function stringifyTrace(params) {
1948
+ if (params === void 0 || params === null) return;
1949
+ switch (trace) {
1950
+ case Trace.Verbose: return JSON.stringify(params, null, 4);
1951
+ case Trace.Compact: return JSON.stringify(params);
1952
+ default: return;
1953
+ }
1954
+ }
1955
+ function traceSendingRequest(message) {
1956
+ if (trace === Trace.Off || !tracer) return;
1957
+ if (traceFormat === TraceFormat.Text) {
1958
+ let data = void 0;
1959
+ if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) data = `Params: ${stringifyTrace(message.params)}\n\n`;
1960
+ tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
1961
+ } else logLSPMessage("send-request", message);
1962
+ }
1963
+ function traceSendingNotification(message) {
1964
+ if (trace === Trace.Off || !tracer) return;
1965
+ if (traceFormat === TraceFormat.Text) {
1966
+ let data = void 0;
1967
+ if (trace === Trace.Verbose || trace === Trace.Compact) if (message.params) data = `Params: ${stringifyTrace(message.params)}\n\n`;
1968
+ else data = "No parameters provided.\n\n";
1969
+ tracer.log(`Sending notification '${message.method}'.`, data);
1970
+ } else logLSPMessage("send-notification", message);
1971
+ }
1972
+ function traceSendingResponse(message, method, startTime) {
1973
+ if (trace === Trace.Off || !tracer) return;
1974
+ if (traceFormat === TraceFormat.Text) {
1975
+ let data = void 0;
1976
+ if (trace === Trace.Verbose || trace === Trace.Compact) {
1977
+ if (message.error && message.error.data) data = `Error data: ${stringifyTrace(message.error.data)}\n\n`;
1978
+ else if (message.result) data = `Result: ${stringifyTrace(message.result)}\n\n`;
1979
+ else if (message.error === void 0) data = "No result returned.\n\n";
1980
+ }
1981
+ tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
1982
+ } else logLSPMessage("send-response", message);
1983
+ }
1984
+ function traceReceivedRequest(message) {
1985
+ if (trace === Trace.Off || !tracer) return;
1986
+ if (traceFormat === TraceFormat.Text) {
1987
+ let data = void 0;
1988
+ if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) data = `Params: ${stringifyTrace(message.params)}\n\n`;
1989
+ tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
1990
+ } else logLSPMessage("receive-request", message);
1991
+ }
1992
+ function traceReceivedNotification(message) {
1993
+ if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) return;
1994
+ if (traceFormat === TraceFormat.Text) {
1995
+ let data = void 0;
1996
+ if (trace === Trace.Verbose || trace === Trace.Compact) if (message.params) data = `Params: ${stringifyTrace(message.params)}\n\n`;
1997
+ else data = "No parameters provided.\n\n";
1998
+ tracer.log(`Received notification '${message.method}'.`, data);
1999
+ } else logLSPMessage("receive-notification", message);
2000
+ }
2001
+ function traceReceivedResponse(message, responsePromise) {
2002
+ if (trace === Trace.Off || !tracer) return;
2003
+ if (traceFormat === TraceFormat.Text) {
2004
+ let data = void 0;
2005
+ if (trace === Trace.Verbose || trace === Trace.Compact) {
2006
+ if (message.error && message.error.data) data = `Error data: ${stringifyTrace(message.error.data)}\n\n`;
2007
+ else if (message.result) data = `Result: ${stringifyTrace(message.result)}\n\n`;
2008
+ else if (message.error === void 0) data = "No result returned.\n\n";
2009
+ }
2010
+ if (responsePromise) {
2011
+ const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : "";
2012
+ tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
2013
+ } else tracer.log(`Received response ${message.id} without active response promise.`, data);
2014
+ } else logLSPMessage("receive-response", message);
2015
+ }
2016
+ function logLSPMessage(type, message) {
2017
+ if (!tracer || trace === Trace.Off) return;
2018
+ const lspMessage = {
2019
+ isLSPMessage: true,
2020
+ type,
2021
+ message,
2022
+ timestamp: Date.now()
2023
+ };
2024
+ tracer.log(lspMessage);
2025
+ }
2026
+ function throwIfClosedOrDisposed() {
2027
+ if (isClosed()) throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed.");
2028
+ if (isDisposed()) throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed.");
2029
+ }
2030
+ function throwIfListening() {
2031
+ if (isListening()) throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening");
2032
+ }
2033
+ function throwIfNotListening() {
2034
+ if (!isListening()) throw new Error("Call listen() first.");
2035
+ }
2036
+ function undefinedToNull(param) {
2037
+ if (param === void 0) return null;
2038
+ else return param;
2039
+ }
2040
+ function nullToUndefined(param) {
2041
+ if (param === null) return;
2042
+ else return param;
2043
+ }
2044
+ function isNamedParam(param) {
2045
+ return param !== void 0 && param !== null && !Array.isArray(param) && typeof param === "object";
2046
+ }
2047
+ function computeSingleParam(parameterStructures, param) {
2048
+ switch (parameterStructures) {
2049
+ case messages_1.ParameterStructures.auto: if (isNamedParam(param)) return nullToUndefined(param);
2050
+ else return [undefinedToNull(param)];
2051
+ case messages_1.ParameterStructures.byName:
2052
+ if (!isNamedParam(param)) throw new Error(`Received parameters by name but param is not an object literal.`);
2053
+ return nullToUndefined(param);
2054
+ case messages_1.ParameterStructures.byPosition: return [undefinedToNull(param)];
2055
+ default: throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`);
2056
+ }
2057
+ }
2058
+ function computeMessageParams(type, params) {
2059
+ let result;
2060
+ const numberOfParams = type.numberOfParams;
2061
+ switch (numberOfParams) {
2062
+ case 0:
2063
+ result = void 0;
2064
+ break;
2065
+ case 1:
2066
+ result = computeSingleParam(type.parameterStructures, params[0]);
2067
+ break;
2068
+ default:
2069
+ result = [];
2070
+ for (let i = 0; i < params.length && i < numberOfParams; i++) result.push(undefinedToNull(params[i]));
2071
+ if (params.length < numberOfParams) for (let i = params.length; i < numberOfParams; i++) result.push(null);
2072
+ break;
2073
+ }
2074
+ return result;
2075
+ }
2076
+ const connection = {
2077
+ sendNotification: (type, ...args) => {
2078
+ throwIfClosedOrDisposed();
2079
+ let method;
2080
+ let messageParams;
2081
+ if (Is.string(type)) {
2082
+ method = type;
2083
+ const first = args[0];
2084
+ let paramStart = 0;
2085
+ let parameterStructures = messages_1.ParameterStructures.auto;
2086
+ if (messages_1.ParameterStructures.is(first)) {
2087
+ paramStart = 1;
2088
+ parameterStructures = first;
2089
+ }
2090
+ let paramEnd = args.length;
2091
+ const numberOfParams = paramEnd - paramStart;
2092
+ switch (numberOfParams) {
2093
+ case 0:
2094
+ messageParams = void 0;
2095
+ break;
2096
+ case 1:
2097
+ messageParams = computeSingleParam(parameterStructures, args[paramStart]);
2098
+ break;
2099
+ default:
2100
+ if (parameterStructures === messages_1.ParameterStructures.byName) throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`);
2101
+ messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
2102
+ break;
2103
+ }
2104
+ } else {
2105
+ const params = args;
2106
+ method = type.method;
2107
+ messageParams = computeMessageParams(type, params);
2108
+ }
2109
+ const notificationMessage = {
2110
+ jsonrpc: version,
2111
+ method,
2112
+ params: messageParams
2113
+ };
2114
+ traceSendingNotification(notificationMessage);
2115
+ return messageWriter.write(notificationMessage).catch((error) => {
2116
+ logger.error(`Sending notification failed.`);
2117
+ throw error;
2118
+ });
2119
+ },
2120
+ onNotification: (type, handler) => {
2121
+ throwIfClosedOrDisposed();
2122
+ let method;
2123
+ if (Is.func(type)) starNotificationHandler = type;
2124
+ else if (handler) if (Is.string(type)) {
2125
+ method = type;
2126
+ notificationHandlers.set(type, {
2127
+ type: void 0,
2128
+ handler
2129
+ });
2130
+ } else {
2131
+ method = type.method;
2132
+ notificationHandlers.set(type.method, {
2133
+ type,
2134
+ handler
2135
+ });
2136
+ }
2137
+ return { dispose: () => {
2138
+ if (method !== void 0) notificationHandlers.delete(method);
2139
+ else starNotificationHandler = void 0;
2140
+ } };
2141
+ },
2142
+ onProgress: (_type, token, handler) => {
2143
+ if (progressHandlers.has(token)) throw new Error(`Progress handler for token ${token} already registered`);
2144
+ progressHandlers.set(token, handler);
2145
+ return { dispose: () => {
2146
+ progressHandlers.delete(token);
2147
+ } };
2148
+ },
2149
+ sendProgress: (_type, token, value) => {
2150
+ return connection.sendNotification(ProgressNotification.type, {
2151
+ token,
2152
+ value
2153
+ });
2154
+ },
2155
+ onUnhandledProgress: unhandledProgressEmitter.event,
2156
+ sendRequest: (type, ...args) => {
2157
+ throwIfClosedOrDisposed();
2158
+ throwIfNotListening();
2159
+ let method;
2160
+ let messageParams;
2161
+ let token = void 0;
2162
+ if (Is.string(type)) {
2163
+ method = type;
2164
+ const first = args[0];
2165
+ const last = args[args.length - 1];
2166
+ let paramStart = 0;
2167
+ let parameterStructures = messages_1.ParameterStructures.auto;
2168
+ if (messages_1.ParameterStructures.is(first)) {
2169
+ paramStart = 1;
2170
+ parameterStructures = first;
2171
+ }
2172
+ let paramEnd = args.length;
2173
+ if (cancellation_1.CancellationToken.is(last)) {
2174
+ paramEnd = paramEnd - 1;
2175
+ token = last;
2176
+ }
2177
+ const numberOfParams = paramEnd - paramStart;
2178
+ switch (numberOfParams) {
2179
+ case 0:
2180
+ messageParams = void 0;
2181
+ break;
2182
+ case 1:
2183
+ messageParams = computeSingleParam(parameterStructures, args[paramStart]);
2184
+ break;
2185
+ default:
2186
+ if (parameterStructures === messages_1.ParameterStructures.byName) throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`);
2187
+ messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
2188
+ break;
2189
+ }
2190
+ } else {
2191
+ const params = args;
2192
+ method = type.method;
2193
+ messageParams = computeMessageParams(type, params);
2194
+ const numberOfParams = type.numberOfParams;
2195
+ token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : void 0;
2196
+ }
2197
+ const id = sequenceNumber++;
2198
+ let disposable;
2199
+ if (token) disposable = token.onCancellationRequested(() => {
2200
+ const p = cancellationStrategy.sender.sendCancellation(connection, id);
2201
+ if (p === void 0) {
2202
+ logger.log(`Received no promise from cancellation strategy when cancelling id ${id}`);
2203
+ return Promise.resolve();
2204
+ } else return p.catch(() => {
2205
+ logger.log(`Sending cancellation messages for id ${id} failed`);
2206
+ });
2207
+ });
2208
+ const requestMessage = {
2209
+ jsonrpc: version,
2210
+ id,
2211
+ method,
2212
+ params: messageParams
2213
+ };
2214
+ traceSendingRequest(requestMessage);
2215
+ if (typeof cancellationStrategy.sender.enableCancellation === "function") cancellationStrategy.sender.enableCancellation(requestMessage);
2216
+ return new Promise(async (resolve, reject) => {
2217
+ const resolveWithCleanup = (r) => {
2218
+ resolve(r);
2219
+ cancellationStrategy.sender.cleanup(id);
2220
+ disposable?.dispose();
2221
+ };
2222
+ const rejectWithCleanup = (r) => {
2223
+ reject(r);
2224
+ cancellationStrategy.sender.cleanup(id);
2225
+ disposable?.dispose();
2226
+ };
2227
+ const responsePromise = {
2228
+ method,
2229
+ timerStart: Date.now(),
2230
+ resolve: resolveWithCleanup,
2231
+ reject: rejectWithCleanup
2232
+ };
2233
+ try {
2234
+ responsePromises.set(id, responsePromise);
2235
+ await messageWriter.write(requestMessage);
2236
+ } catch (error) {
2237
+ responsePromises.delete(id);
2238
+ responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : "Unknown reason"));
2239
+ logger.error(`Sending request failed.`);
2240
+ throw error;
2241
+ }
2242
+ });
2243
+ },
2244
+ onRequest: (type, handler) => {
2245
+ throwIfClosedOrDisposed();
2246
+ let method = null;
2247
+ if (StarRequestHandler.is(type)) {
2248
+ method = void 0;
2249
+ starRequestHandler = type;
2250
+ } else if (Is.string(type)) {
2251
+ method = null;
2252
+ if (handler !== void 0) {
2253
+ method = type;
2254
+ requestHandlers.set(type, {
2255
+ handler,
2256
+ type: void 0
2257
+ });
2258
+ }
2259
+ } else if (handler !== void 0) {
2260
+ method = type.method;
2261
+ requestHandlers.set(type.method, {
2262
+ type,
2263
+ handler
2264
+ });
2265
+ }
2266
+ return { dispose: () => {
2267
+ if (method === null) return;
2268
+ if (method !== void 0) requestHandlers.delete(method);
2269
+ else starRequestHandler = void 0;
2270
+ } };
2271
+ },
2272
+ hasPendingResponse: () => {
2273
+ return responsePromises.size > 0;
2274
+ },
2275
+ trace: async (_value, _tracer, sendNotificationOrTraceOptions) => {
2276
+ let _sendNotification = false;
2277
+ let _traceFormat = TraceFormat.Text;
2278
+ if (sendNotificationOrTraceOptions !== void 0) if (Is.boolean(sendNotificationOrTraceOptions)) _sendNotification = sendNotificationOrTraceOptions;
2279
+ else {
2280
+ _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
2281
+ _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
2282
+ }
2283
+ trace = _value;
2284
+ traceFormat = _traceFormat;
2285
+ if (trace === Trace.Off) tracer = void 0;
2286
+ else tracer = _tracer;
2287
+ if (_sendNotification && !isClosed() && !isDisposed()) await connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
2288
+ },
2289
+ onError: errorEmitter.event,
2290
+ onClose: closeEmitter.event,
2291
+ onUnhandledNotification: unhandledNotificationEmitter.event,
2292
+ onDispose: disposeEmitter.event,
2293
+ end: () => {
2294
+ messageWriter.end();
2295
+ },
2296
+ dispose: () => {
2297
+ if (isDisposed()) return;
2298
+ state = ConnectionState.Disposed;
2299
+ disposeEmitter.fire(void 0);
2300
+ const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, "Pending response rejected since connection got disposed");
2301
+ for (const promise of responsePromises.values()) promise.reject(error);
2302
+ responsePromises = /* @__PURE__ */ new Map();
2303
+ requestTokens = /* @__PURE__ */ new Map();
2304
+ knownCanceledRequests = /* @__PURE__ */ new Set();
2305
+ messageQueue = new linkedMap_1.LinkedMap();
2306
+ if (Is.func(messageWriter.dispose)) messageWriter.dispose();
2307
+ if (Is.func(messageReader.dispose)) messageReader.dispose();
2308
+ },
2309
+ listen: () => {
2310
+ throwIfClosedOrDisposed();
2311
+ throwIfListening();
2312
+ state = ConnectionState.Listening;
2313
+ messageReader.listen(callback);
2314
+ },
2315
+ inspect: () => {
2316
+ (0, ral_1.default)().console.log("inspect");
2317
+ }
2318
+ };
2319
+ connection.onNotification(LogTraceNotification.type, (params) => {
2320
+ if (trace === Trace.Off || !tracer) return;
2321
+ const verbose = trace === Trace.Verbose || trace === Trace.Compact;
2322
+ tracer.log(params.message, verbose ? params.verbose : void 0);
2323
+ });
2324
+ connection.onNotification(ProgressNotification.type, (params) => {
2325
+ const handler = progressHandlers.get(params.token);
2326
+ if (handler) handler(params.value);
2327
+ else unhandledProgressEmitter.fire(params);
2328
+ });
2329
+ return connection;
2330
+ }
2331
+ exports.createMessageConnection = createMessageConnection;
2332
+ }));
2333
+
2334
+ //#endregion
2335
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/common/api.js
2336
+ var require_api = /* @__PURE__ */ __commonJSMin(((exports) => {
2337
+ Object.defineProperty(exports, "__esModule", { value: true });
2338
+ exports.ProgressType = exports.ProgressToken = exports.createMessageConnection = exports.NullLogger = exports.ConnectionOptions = exports.ConnectionStrategy = exports.AbstractMessageBuffer = exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = exports.CancellationToken = exports.CancellationTokenSource = exports.Emitter = exports.Event = exports.Disposable = exports.LRUCache = exports.Touch = exports.LinkedMap = exports.ParameterStructures = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.ErrorCodes = exports.ResponseError = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType0 = exports.RequestType = exports.Message = exports.RAL = void 0;
2339
+ exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.Trace = void 0;
2340
+ const messages_1 = require_messages();
2341
+ Object.defineProperty(exports, "Message", {
2342
+ enumerable: true,
2343
+ get: function() {
2344
+ return messages_1.Message;
2345
+ }
2346
+ });
2347
+ Object.defineProperty(exports, "RequestType", {
2348
+ enumerable: true,
2349
+ get: function() {
2350
+ return messages_1.RequestType;
2351
+ }
2352
+ });
2353
+ Object.defineProperty(exports, "RequestType0", {
2354
+ enumerable: true,
2355
+ get: function() {
2356
+ return messages_1.RequestType0;
2357
+ }
2358
+ });
2359
+ Object.defineProperty(exports, "RequestType1", {
2360
+ enumerable: true,
2361
+ get: function() {
2362
+ return messages_1.RequestType1;
2363
+ }
2364
+ });
2365
+ Object.defineProperty(exports, "RequestType2", {
2366
+ enumerable: true,
2367
+ get: function() {
2368
+ return messages_1.RequestType2;
2369
+ }
2370
+ });
2371
+ Object.defineProperty(exports, "RequestType3", {
2372
+ enumerable: true,
2373
+ get: function() {
2374
+ return messages_1.RequestType3;
2375
+ }
2376
+ });
2377
+ Object.defineProperty(exports, "RequestType4", {
2378
+ enumerable: true,
2379
+ get: function() {
2380
+ return messages_1.RequestType4;
2381
+ }
2382
+ });
2383
+ Object.defineProperty(exports, "RequestType5", {
2384
+ enumerable: true,
2385
+ get: function() {
2386
+ return messages_1.RequestType5;
2387
+ }
2388
+ });
2389
+ Object.defineProperty(exports, "RequestType6", {
2390
+ enumerable: true,
2391
+ get: function() {
2392
+ return messages_1.RequestType6;
2393
+ }
2394
+ });
2395
+ Object.defineProperty(exports, "RequestType7", {
2396
+ enumerable: true,
2397
+ get: function() {
2398
+ return messages_1.RequestType7;
2399
+ }
2400
+ });
2401
+ Object.defineProperty(exports, "RequestType8", {
2402
+ enumerable: true,
2403
+ get: function() {
2404
+ return messages_1.RequestType8;
2405
+ }
2406
+ });
2407
+ Object.defineProperty(exports, "RequestType9", {
2408
+ enumerable: true,
2409
+ get: function() {
2410
+ return messages_1.RequestType9;
2411
+ }
2412
+ });
2413
+ Object.defineProperty(exports, "ResponseError", {
2414
+ enumerable: true,
2415
+ get: function() {
2416
+ return messages_1.ResponseError;
2417
+ }
2418
+ });
2419
+ Object.defineProperty(exports, "ErrorCodes", {
2420
+ enumerable: true,
2421
+ get: function() {
2422
+ return messages_1.ErrorCodes;
2423
+ }
2424
+ });
2425
+ Object.defineProperty(exports, "NotificationType", {
2426
+ enumerable: true,
2427
+ get: function() {
2428
+ return messages_1.NotificationType;
2429
+ }
2430
+ });
2431
+ Object.defineProperty(exports, "NotificationType0", {
2432
+ enumerable: true,
2433
+ get: function() {
2434
+ return messages_1.NotificationType0;
2435
+ }
2436
+ });
2437
+ Object.defineProperty(exports, "NotificationType1", {
2438
+ enumerable: true,
2439
+ get: function() {
2440
+ return messages_1.NotificationType1;
2441
+ }
2442
+ });
2443
+ Object.defineProperty(exports, "NotificationType2", {
2444
+ enumerable: true,
2445
+ get: function() {
2446
+ return messages_1.NotificationType2;
2447
+ }
2448
+ });
2449
+ Object.defineProperty(exports, "NotificationType3", {
2450
+ enumerable: true,
2451
+ get: function() {
2452
+ return messages_1.NotificationType3;
2453
+ }
2454
+ });
2455
+ Object.defineProperty(exports, "NotificationType4", {
2456
+ enumerable: true,
2457
+ get: function() {
2458
+ return messages_1.NotificationType4;
2459
+ }
2460
+ });
2461
+ Object.defineProperty(exports, "NotificationType5", {
2462
+ enumerable: true,
2463
+ get: function() {
2464
+ return messages_1.NotificationType5;
2465
+ }
2466
+ });
2467
+ Object.defineProperty(exports, "NotificationType6", {
2468
+ enumerable: true,
2469
+ get: function() {
2470
+ return messages_1.NotificationType6;
2471
+ }
2472
+ });
2473
+ Object.defineProperty(exports, "NotificationType7", {
2474
+ enumerable: true,
2475
+ get: function() {
2476
+ return messages_1.NotificationType7;
2477
+ }
2478
+ });
2479
+ Object.defineProperty(exports, "NotificationType8", {
2480
+ enumerable: true,
2481
+ get: function() {
2482
+ return messages_1.NotificationType8;
2483
+ }
2484
+ });
2485
+ Object.defineProperty(exports, "NotificationType9", {
2486
+ enumerable: true,
2487
+ get: function() {
2488
+ return messages_1.NotificationType9;
2489
+ }
2490
+ });
2491
+ Object.defineProperty(exports, "ParameterStructures", {
2492
+ enumerable: true,
2493
+ get: function() {
2494
+ return messages_1.ParameterStructures;
2495
+ }
2496
+ });
2497
+ const linkedMap_1 = require_linkedMap();
2498
+ Object.defineProperty(exports, "LinkedMap", {
2499
+ enumerable: true,
2500
+ get: function() {
2501
+ return linkedMap_1.LinkedMap;
2502
+ }
2503
+ });
2504
+ Object.defineProperty(exports, "LRUCache", {
2505
+ enumerable: true,
2506
+ get: function() {
2507
+ return linkedMap_1.LRUCache;
2508
+ }
2509
+ });
2510
+ Object.defineProperty(exports, "Touch", {
2511
+ enumerable: true,
2512
+ get: function() {
2513
+ return linkedMap_1.Touch;
2514
+ }
2515
+ });
2516
+ const disposable_1 = require_disposable();
2517
+ Object.defineProperty(exports, "Disposable", {
2518
+ enumerable: true,
2519
+ get: function() {
2520
+ return disposable_1.Disposable;
2521
+ }
2522
+ });
2523
+ const events_1 = require_events();
2524
+ Object.defineProperty(exports, "Event", {
2525
+ enumerable: true,
2526
+ get: function() {
2527
+ return events_1.Event;
2528
+ }
2529
+ });
2530
+ Object.defineProperty(exports, "Emitter", {
2531
+ enumerable: true,
2532
+ get: function() {
2533
+ return events_1.Emitter;
2534
+ }
2535
+ });
2536
+ const cancellation_1 = require_cancellation();
2537
+ Object.defineProperty(exports, "CancellationTokenSource", {
2538
+ enumerable: true,
2539
+ get: function() {
2540
+ return cancellation_1.CancellationTokenSource;
2541
+ }
2542
+ });
2543
+ Object.defineProperty(exports, "CancellationToken", {
2544
+ enumerable: true,
2545
+ get: function() {
2546
+ return cancellation_1.CancellationToken;
2547
+ }
2548
+ });
2549
+ const sharedArrayCancellation_1 = require_sharedArrayCancellation();
2550
+ Object.defineProperty(exports, "SharedArraySenderStrategy", {
2551
+ enumerable: true,
2552
+ get: function() {
2553
+ return sharedArrayCancellation_1.SharedArraySenderStrategy;
2554
+ }
2555
+ });
2556
+ Object.defineProperty(exports, "SharedArrayReceiverStrategy", {
2557
+ enumerable: true,
2558
+ get: function() {
2559
+ return sharedArrayCancellation_1.SharedArrayReceiverStrategy;
2560
+ }
2561
+ });
2562
+ const messageReader_1 = require_messageReader();
2563
+ Object.defineProperty(exports, "MessageReader", {
2564
+ enumerable: true,
2565
+ get: function() {
2566
+ return messageReader_1.MessageReader;
2567
+ }
2568
+ });
2569
+ Object.defineProperty(exports, "AbstractMessageReader", {
2570
+ enumerable: true,
2571
+ get: function() {
2572
+ return messageReader_1.AbstractMessageReader;
2573
+ }
2574
+ });
2575
+ Object.defineProperty(exports, "ReadableStreamMessageReader", {
2576
+ enumerable: true,
2577
+ get: function() {
2578
+ return messageReader_1.ReadableStreamMessageReader;
2579
+ }
2580
+ });
2581
+ const messageWriter_1 = require_messageWriter();
2582
+ Object.defineProperty(exports, "MessageWriter", {
2583
+ enumerable: true,
2584
+ get: function() {
2585
+ return messageWriter_1.MessageWriter;
2586
+ }
2587
+ });
2588
+ Object.defineProperty(exports, "AbstractMessageWriter", {
2589
+ enumerable: true,
2590
+ get: function() {
2591
+ return messageWriter_1.AbstractMessageWriter;
2592
+ }
2593
+ });
2594
+ Object.defineProperty(exports, "WriteableStreamMessageWriter", {
2595
+ enumerable: true,
2596
+ get: function() {
2597
+ return messageWriter_1.WriteableStreamMessageWriter;
2598
+ }
2599
+ });
2600
+ const messageBuffer_1 = require_messageBuffer();
2601
+ Object.defineProperty(exports, "AbstractMessageBuffer", {
2602
+ enumerable: true,
2603
+ get: function() {
2604
+ return messageBuffer_1.AbstractMessageBuffer;
2605
+ }
2606
+ });
2607
+ const connection_1 = require_connection();
2608
+ Object.defineProperty(exports, "ConnectionStrategy", {
2609
+ enumerable: true,
2610
+ get: function() {
2611
+ return connection_1.ConnectionStrategy;
2612
+ }
2613
+ });
2614
+ Object.defineProperty(exports, "ConnectionOptions", {
2615
+ enumerable: true,
2616
+ get: function() {
2617
+ return connection_1.ConnectionOptions;
2618
+ }
2619
+ });
2620
+ Object.defineProperty(exports, "NullLogger", {
2621
+ enumerable: true,
2622
+ get: function() {
2623
+ return connection_1.NullLogger;
2624
+ }
2625
+ });
2626
+ Object.defineProperty(exports, "createMessageConnection", {
2627
+ enumerable: true,
2628
+ get: function() {
2629
+ return connection_1.createMessageConnection;
2630
+ }
2631
+ });
2632
+ Object.defineProperty(exports, "ProgressToken", {
2633
+ enumerable: true,
2634
+ get: function() {
2635
+ return connection_1.ProgressToken;
2636
+ }
2637
+ });
2638
+ Object.defineProperty(exports, "ProgressType", {
2639
+ enumerable: true,
2640
+ get: function() {
2641
+ return connection_1.ProgressType;
2642
+ }
2643
+ });
2644
+ Object.defineProperty(exports, "Trace", {
2645
+ enumerable: true,
2646
+ get: function() {
2647
+ return connection_1.Trace;
2648
+ }
2649
+ });
2650
+ Object.defineProperty(exports, "TraceValues", {
2651
+ enumerable: true,
2652
+ get: function() {
2653
+ return connection_1.TraceValues;
2654
+ }
2655
+ });
2656
+ Object.defineProperty(exports, "TraceFormat", {
2657
+ enumerable: true,
2658
+ get: function() {
2659
+ return connection_1.TraceFormat;
2660
+ }
2661
+ });
2662
+ Object.defineProperty(exports, "SetTraceNotification", {
2663
+ enumerable: true,
2664
+ get: function() {
2665
+ return connection_1.SetTraceNotification;
2666
+ }
2667
+ });
2668
+ Object.defineProperty(exports, "LogTraceNotification", {
2669
+ enumerable: true,
2670
+ get: function() {
2671
+ return connection_1.LogTraceNotification;
2672
+ }
2673
+ });
2674
+ Object.defineProperty(exports, "ConnectionErrors", {
2675
+ enumerable: true,
2676
+ get: function() {
2677
+ return connection_1.ConnectionErrors;
2678
+ }
2679
+ });
2680
+ Object.defineProperty(exports, "ConnectionError", {
2681
+ enumerable: true,
2682
+ get: function() {
2683
+ return connection_1.ConnectionError;
2684
+ }
2685
+ });
2686
+ Object.defineProperty(exports, "CancellationReceiverStrategy", {
2687
+ enumerable: true,
2688
+ get: function() {
2689
+ return connection_1.CancellationReceiverStrategy;
2690
+ }
2691
+ });
2692
+ Object.defineProperty(exports, "CancellationSenderStrategy", {
2693
+ enumerable: true,
2694
+ get: function() {
2695
+ return connection_1.CancellationSenderStrategy;
2696
+ }
2697
+ });
2698
+ Object.defineProperty(exports, "CancellationStrategy", {
2699
+ enumerable: true,
2700
+ get: function() {
2701
+ return connection_1.CancellationStrategy;
2702
+ }
2703
+ });
2704
+ Object.defineProperty(exports, "MessageStrategy", {
2705
+ enumerable: true,
2706
+ get: function() {
2707
+ return connection_1.MessageStrategy;
2708
+ }
2709
+ });
2710
+ const ral_1 = require_ral();
2711
+ exports.RAL = ral_1.default;
2712
+ }));
2713
+
2714
+ //#endregion
2715
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/browser/ril.js
2716
+ var require_ril = /* @__PURE__ */ __commonJSMin(((exports) => {
2717
+ Object.defineProperty(exports, "__esModule", { value: true });
2718
+ const api_1 = require_api();
2719
+ var MessageBuffer = class MessageBuffer extends api_1.AbstractMessageBuffer {
2720
+ constructor(encoding = "utf-8") {
2721
+ super(encoding);
2722
+ this.asciiDecoder = new TextDecoder("ascii");
2723
+ }
2724
+ emptyBuffer() {
2725
+ return MessageBuffer.emptyBuffer;
2726
+ }
2727
+ fromString(value, _encoding) {
2728
+ return new TextEncoder().encode(value);
2729
+ }
2730
+ toString(value, encoding) {
2731
+ if (encoding === "ascii") return this.asciiDecoder.decode(value);
2732
+ else return new TextDecoder(encoding).decode(value);
2733
+ }
2734
+ asNative(buffer, length) {
2735
+ if (length === void 0) return buffer;
2736
+ else return buffer.slice(0, length);
2737
+ }
2738
+ allocNative(length) {
2739
+ return new Uint8Array(length);
2740
+ }
2741
+ };
2742
+ MessageBuffer.emptyBuffer = new Uint8Array(0);
2743
+ var ReadableStreamWrapper = class {
2744
+ constructor(socket) {
2745
+ this.socket = socket;
2746
+ this._onData = new api_1.Emitter();
2747
+ this._messageListener = (event) => {
2748
+ event.data.arrayBuffer().then((buffer) => {
2749
+ this._onData.fire(new Uint8Array(buffer));
2750
+ }, () => {
2751
+ (0, api_1.RAL)().console.error(`Converting blob to array buffer failed.`);
2752
+ });
2753
+ };
2754
+ this.socket.addEventListener("message", this._messageListener);
2755
+ }
2756
+ onClose(listener) {
2757
+ this.socket.addEventListener("close", listener);
2758
+ return api_1.Disposable.create(() => this.socket.removeEventListener("close", listener));
2759
+ }
2760
+ onError(listener) {
2761
+ this.socket.addEventListener("error", listener);
2762
+ return api_1.Disposable.create(() => this.socket.removeEventListener("error", listener));
2763
+ }
2764
+ onEnd(listener) {
2765
+ this.socket.addEventListener("end", listener);
2766
+ return api_1.Disposable.create(() => this.socket.removeEventListener("end", listener));
2767
+ }
2768
+ onData(listener) {
2769
+ return this._onData.event(listener);
2770
+ }
2771
+ };
2772
+ var WritableStreamWrapper = class {
2773
+ constructor(socket) {
2774
+ this.socket = socket;
2775
+ }
2776
+ onClose(listener) {
2777
+ this.socket.addEventListener("close", listener);
2778
+ return api_1.Disposable.create(() => this.socket.removeEventListener("close", listener));
2779
+ }
2780
+ onError(listener) {
2781
+ this.socket.addEventListener("error", listener);
2782
+ return api_1.Disposable.create(() => this.socket.removeEventListener("error", listener));
2783
+ }
2784
+ onEnd(listener) {
2785
+ this.socket.addEventListener("end", listener);
2786
+ return api_1.Disposable.create(() => this.socket.removeEventListener("end", listener));
2787
+ }
2788
+ write(data, encoding) {
2789
+ if (typeof data === "string") {
2790
+ if (encoding !== void 0 && encoding !== "utf-8") throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${encoding}`);
2791
+ this.socket.send(data);
2792
+ } else this.socket.send(data);
2793
+ return Promise.resolve();
2794
+ }
2795
+ end() {
2796
+ this.socket.close();
2797
+ }
2798
+ };
2799
+ const _textEncoder = new TextEncoder();
2800
+ const _ril = Object.freeze({
2801
+ messageBuffer: Object.freeze({ create: (encoding) => new MessageBuffer(encoding) }),
2802
+ applicationJson: Object.freeze({
2803
+ encoder: Object.freeze({
2804
+ name: "application/json",
2805
+ encode: (msg, options) => {
2806
+ if (options.charset !== "utf-8") throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${options.charset}`);
2807
+ return Promise.resolve(_textEncoder.encode(JSON.stringify(msg, void 0, 0)));
2808
+ }
2809
+ }),
2810
+ decoder: Object.freeze({
2811
+ name: "application/json",
2812
+ decode: (buffer, options) => {
2813
+ if (!(buffer instanceof Uint8Array)) throw new Error(`In a Browser environments only Uint8Arrays are supported.`);
2814
+ return Promise.resolve(JSON.parse(new TextDecoder(options.charset).decode(buffer)));
2815
+ }
2816
+ })
2817
+ }),
2818
+ stream: Object.freeze({
2819
+ asReadableStream: (socket) => new ReadableStreamWrapper(socket),
2820
+ asWritableStream: (socket) => new WritableStreamWrapper(socket)
2821
+ }),
2822
+ console,
2823
+ timer: Object.freeze({
2824
+ setTimeout(callback, ms, ...args) {
2825
+ const handle = setTimeout(callback, ms, ...args);
2826
+ return { dispose: () => clearTimeout(handle) };
2827
+ },
2828
+ setImmediate(callback, ...args) {
2829
+ const handle = setTimeout(callback, 0, ...args);
2830
+ return { dispose: () => clearTimeout(handle) };
2831
+ },
2832
+ setInterval(callback, ms, ...args) {
2833
+ const handle = setInterval(callback, ms, ...args);
2834
+ return { dispose: () => clearInterval(handle) };
2835
+ }
2836
+ })
2837
+ });
2838
+ function RIL() {
2839
+ return _ril;
2840
+ }
2841
+ (function(RIL) {
2842
+ function install() {
2843
+ api_1.RAL.install(_ril);
2844
+ }
2845
+ RIL.install = install;
2846
+ })(RIL || (RIL = {}));
2847
+ exports.default = RIL;
2848
+ }));
2849
+
2850
+ //#endregion
2851
+ //#region node_modules/.pnpm/vscode-jsonrpc@8.2.1/node_modules/vscode-jsonrpc/lib/browser/main.js
2852
+ var require_main = /* @__PURE__ */ __commonJSMin(((exports) => {
2853
+ var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {
2854
+ if (k2 === void 0) k2 = k;
2855
+ var desc = Object.getOwnPropertyDescriptor(m, k);
2856
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
2857
+ enumerable: true,
2858
+ get: function() {
2859
+ return m[k];
2860
+ }
2861
+ };
2862
+ Object.defineProperty(o, k2, desc);
2863
+ }) : (function(o, m, k, k2) {
2864
+ if (k2 === void 0) k2 = k;
2865
+ o[k2] = m[k];
2866
+ }));
2867
+ var __exportStar = exports && exports.__exportStar || function(m, exports$1) {
2868
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);
2869
+ };
2870
+ Object.defineProperty(exports, "__esModule", { value: true });
2871
+ exports.createMessageConnection = exports.BrowserMessageWriter = exports.BrowserMessageReader = void 0;
2872
+ require_ril().default.install();
2873
+ const api_1 = require_api();
2874
+ __exportStar(require_api(), exports);
2875
+ var BrowserMessageReader = class extends api_1.AbstractMessageReader {
2876
+ constructor(port) {
2877
+ super();
2878
+ this._onData = new api_1.Emitter();
2879
+ this._messageListener = (event) => {
2880
+ this._onData.fire(event.data);
2881
+ };
2882
+ port.addEventListener("error", (event) => this.fireError(event));
2883
+ port.onmessage = this._messageListener;
2884
+ }
2885
+ listen(callback) {
2886
+ return this._onData.event(callback);
2887
+ }
2888
+ };
2889
+ exports.BrowserMessageReader = BrowserMessageReader;
2890
+ var BrowserMessageWriter = class extends api_1.AbstractMessageWriter {
2891
+ constructor(port) {
2892
+ super();
2893
+ this.port = port;
2894
+ this.errorCount = 0;
2895
+ port.addEventListener("error", (event) => this.fireError(event));
2896
+ }
2897
+ write(msg) {
2898
+ try {
2899
+ this.port.postMessage(msg);
2900
+ return Promise.resolve();
2901
+ } catch (error) {
2902
+ this.handleError(error, msg);
2903
+ return Promise.reject(error);
2904
+ }
2905
+ }
2906
+ handleError(error, msg) {
2907
+ this.errorCount++;
2908
+ this.fireError(error, msg, this.errorCount);
2909
+ }
2910
+ end() {}
2911
+ };
2912
+ exports.BrowserMessageWriter = BrowserMessageWriter;
2913
+ function createMessageConnection(reader, writer, logger, options) {
2914
+ if (logger === void 0) logger = api_1.NullLogger;
2915
+ if (api_1.ConnectionStrategy.is(options)) options = { connectionStrategy: options };
2916
+ return (0, api_1.createMessageConnection)(reader, writer, logger, options);
2917
+ }
2918
+ exports.createMessageConnection = createMessageConnection;
2919
+ }));
2920
+
2921
+ //#endregion
2922
+ //#region node_modules/.pnpm/thumbdrive@0.3.0_tslib@2.8.1/node_modules/thumbdrive/dist/MultiTabWorkerBroker.js
2923
+ var import_main = require_main();
2924
+ function generateBrokerId() {
2925
+ return `broker-${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
2926
+ }
2927
+ var MultiTabWorkerBrokerError = class extends Error {
2928
+ details;
2929
+ constructor(message, details) {
2930
+ super(message);
2931
+ this.details = details;
2932
+ this.name = "MultiTabWorkerBrokerError";
2933
+ }
2934
+ };
2935
+ /**
2936
+ * A worker broker that allows multiple tabs open on the same origin to all talk to one active tab's worker
2937
+ * Supports tabs coming and going and re-electing the active tab as leader
2938
+ */
2939
+ var MultiTabWorkerBroker = class {
2940
+ lockName;
2941
+ makeWorker;
2942
+ isLeader = false;
2943
+ started = false;
2944
+ brokerId;
2945
+ broadcastChannel = null;
2946
+ worker = null;
2947
+ lockAbortController = new AbortController();
2948
+ pendingRequests = /* @__PURE__ */ new Map();
2949
+ nextRequestId = 0;
2950
+ timeout;
2951
+ onStateChange;
2952
+ leaderRequestQueue = [];
2953
+ workerReadyPromise = null;
2954
+ workerReadyResolver = null;
2955
+ rewrittenIdMap = /* @__PURE__ */ new Map();
2956
+ connections = /* @__PURE__ */ new Map();
2957
+ nextConnectionId = 0;
2958
+ shouldDebug = false;
2959
+ activeLockPromise = null;
2960
+ stopPromise = null;
2961
+ constructor(lockName, makeWorker, options) {
2962
+ this.lockName = lockName;
2963
+ this.makeWorker = makeWorker;
2964
+ this.brokerId = generateBrokerId();
2965
+ this.timeout = options?.timeout ?? 2e4;
2966
+ this.onStateChange = options?.onStateChange;
2967
+ this.shouldDebug = options?.debug ?? false;
2968
+ }
2969
+ /** Central debug logging function */
2970
+ debug(message, ...args) {
2971
+ if (this.shouldDebug) {
2972
+ const role = this.isLeader ? "LEADER" : "FOLLOWER";
2973
+ const prefix = `[MTB:${this.brokerId.slice(0, 20)}:${role}]`;
2974
+ console.debug(prefix, message, ...args);
2975
+ }
2976
+ }
2977
+ /** Central error logging function */
2978
+ error(message, ...args) {
2979
+ const role = this.isLeader ? "LEADER" : "FOLLOWER";
2980
+ const prefix = `[MTB:${this.brokerId.slice(0, 20)}:${role}]`;
2981
+ console.error(prefix, message, ...args);
2982
+ }
2983
+ /** Create a new connection with independent reader and writer */
2984
+ createConnection() {
2985
+ const connectionId = String(this.nextConnectionId++);
2986
+ const reader = new MultiTabMessageReader();
2987
+ const writer = new MultiTabMessageWriter();
2988
+ writer._setWriteHandler(async (message) => {
2989
+ await this.sendMessage(message);
2990
+ });
2991
+ this.connections.set(connectionId, {
2992
+ reader,
2993
+ writer
2994
+ });
2995
+ this.debug(`createConnection: Created connection ${connectionId}`);
2996
+ const dispose = () => {
2997
+ this.debug(`Connection ${connectionId} disposed`);
2998
+ const conn = this.connections.get(connectionId);
2999
+ if (conn) {
3000
+ conn.reader.dispose();
3001
+ conn.writer.dispose();
3002
+ this.connections.delete(connectionId);
3003
+ }
3004
+ };
3005
+ return {
3006
+ reader,
3007
+ writer,
3008
+ dispose
3009
+ };
3010
+ }
3011
+ /** Start the broker and attempt to acquire leadership */
3012
+ async start() {
3013
+ if (this.stopPromise) await this.stopPromise;
3014
+ if (this.started) return;
3015
+ this.started = true;
3016
+ this.lockAbortController = new AbortController();
3017
+ this.broadcastChannel = new BroadcastChannel(this.lockName);
3018
+ this.broadcastChannel.addEventListener("message", this.handleBroadcastMessage);
3019
+ await this.tryAcquireLock();
3020
+ this.debug(`Broker started, isLeader=${this.isLeader}`);
3021
+ }
3022
+ async tryAcquireLock() {
3023
+ let outcomeKnown;
3024
+ let outcomeKnownError;
3025
+ const outcome = new Promise((resolve, reject) => {
3026
+ outcomeKnown = resolve;
3027
+ outcomeKnownError = reject;
3028
+ });
3029
+ this.activeLockPromise = navigator.locks.request(this.lockName, { ifAvailable: true }, async (lock) => {
3030
+ if (lock === null) {
3031
+ outcomeKnown(false);
3032
+ return false;
3033
+ }
3034
+ await this.becomeLeader();
3035
+ outcomeKnown(true);
3036
+ return new Promise((resolve) => {
3037
+ this.lockAbortController.signal.addEventListener("abort", () => {
3038
+ resolve();
3039
+ });
3040
+ });
3041
+ }).catch(outcomeKnownError);
3042
+ if (!await outcome) {
3043
+ this.isLeader = false;
3044
+ this.lockAbortController = new AbortController();
3045
+ this.waitForLockAndBecomeLeader();
3046
+ this.onStateChange?.({ isLeader: this.isLeader });
3047
+ }
3048
+ }
3049
+ waitForLockAndBecomeLeader() {
3050
+ this.activeLockPromise = navigator.locks.request(this.lockName, { signal: this.lockAbortController.signal }, async () => {
3051
+ await this.becomeLeader();
3052
+ return new Promise((resolve) => {
3053
+ this.lockAbortController.signal.addEventListener("abort", () => {
3054
+ resolve();
3055
+ });
3056
+ });
3057
+ }).catch((error) => {
3058
+ if (error.name !== "AbortError") {
3059
+ this.error(`Lock acquisition failed:`, error);
3060
+ this.emitErrorToAllConnections(error instanceof Error ? error : new Error(String(error)));
3061
+ }
3062
+ });
3063
+ }
3064
+ async becomeLeader() {
3065
+ this.debug(`Becoming leader...`);
3066
+ this.isLeader = true;
3067
+ this.workerReadyPromise = new Promise((resolve) => {
3068
+ this.workerReadyResolver = resolve;
3069
+ });
3070
+ this.worker = await this.makeWorker();
3071
+ const messageHandler = (event) => {
3072
+ this.handleWorkerMessage(event);
3073
+ };
3074
+ const errorHandler = (event) => {
3075
+ this.handleWorkerError(event);
3076
+ };
3077
+ this.worker.addEventListener("message", messageHandler);
3078
+ this.worker.addEventListener("error", errorHandler);
3079
+ this.debug(`Leader ready with worker`);
3080
+ this.onStateChange?.({ isLeader: this.isLeader });
3081
+ if (this.leaderRequestQueue.length > 0 && this.worker && this.broadcastChannel) {
3082
+ const queued = this.leaderRequestQueue.splice(0, this.leaderRequestQueue.length);
3083
+ for (const { id, message } of queued) {
3084
+ this.worker.postMessage(message);
3085
+ const response = {
3086
+ type: "worker-response",
3087
+ id,
3088
+ message
3089
+ };
3090
+ this.broadcastChannel.postMessage(response);
3091
+ }
3092
+ }
3093
+ if (this.workerReadyResolver) {
3094
+ this.workerReadyResolver();
3095
+ this.workerReadyResolver = null;
3096
+ }
3097
+ }
3098
+ /** Rewrite a JSONRPC ID to make it globally unique */
3099
+ rewriteId(originalId) {
3100
+ const rewrittenId = `${this.brokerId}:${originalId}`;
3101
+ this.rewrittenIdMap.set(rewrittenId, originalId);
3102
+ return rewrittenId;
3103
+ }
3104
+ unrewriteId(rewrittenId) {
3105
+ if (typeof rewrittenId === "string" && rewrittenId.startsWith(`${this.brokerId}:`)) {
3106
+ const originalId = this.rewrittenIdMap.get(rewrittenId);
3107
+ if (originalId !== void 0) {
3108
+ this.rewrittenIdMap.delete(rewrittenId);
3109
+ return {
3110
+ originalId,
3111
+ isOurs: true
3112
+ };
3113
+ }
3114
+ }
3115
+ return {
3116
+ originalId: rewrittenId,
3117
+ isOurs: false
3118
+ };
3119
+ }
3120
+ rewriteMessage(message) {
3121
+ if (message && typeof message === "object" && "method" in message && message.method && "id" in message && message.id !== void 0) return {
3122
+ ...message,
3123
+ id: this.rewriteId(message.id)
3124
+ };
3125
+ return message;
3126
+ }
3127
+ unrewriteMessage(message) {
3128
+ if (message && typeof message === "object" && "id" in message && message.id !== void 0) {
3129
+ const { originalId, isOurs } = this.unrewriteId(message.id);
3130
+ return {
3131
+ message: {
3132
+ ...message,
3133
+ id: originalId
3134
+ },
3135
+ isOurs
3136
+ };
3137
+ }
3138
+ return {
3139
+ message,
3140
+ isOurs: true
3141
+ };
3142
+ }
3143
+ handleWorkerMessage(event) {
3144
+ const message = event.data;
3145
+ if (message && typeof message === "object" && "method" in message && message.method) {
3146
+ const isNotification = message.id === void 0;
3147
+ this.emitToAllConnections(message);
3148
+ if (isNotification && this.broadcastChannel && this.isLeader) {
3149
+ const brokerMessage = {
3150
+ type: "worker-message",
3151
+ message
3152
+ };
3153
+ this.broadcastChannel.postMessage(brokerMessage);
3154
+ }
3155
+ return;
3156
+ }
3157
+ const { message: unrewrittenMessage, isOurs } = this.unrewriteMessage(message);
3158
+ if (isOurs) this.emitToAllConnections(unrewrittenMessage);
3159
+ else {
3160
+ const rawId = message?.id;
3161
+ if (!(typeof rawId === "string" && rawId.startsWith("broker-"))) this.emitToAllConnections(message);
3162
+ }
3163
+ if (this.broadcastChannel && this.isLeader) {
3164
+ const brokerMessage = {
3165
+ type: "worker-message",
3166
+ message
3167
+ };
3168
+ this.broadcastChannel.postMessage(brokerMessage);
3169
+ }
3170
+ }
3171
+ emitToAllConnections(message) {
3172
+ for (const { reader } of this.connections.values()) reader._emitMessage(message);
3173
+ }
3174
+ emitErrorToAllConnections(error) {
3175
+ for (const { reader, writer } of this.connections.values()) {
3176
+ reader._emitError(error);
3177
+ writer._emitError(error);
3178
+ }
3179
+ }
3180
+ emitCloseToAllConnections() {
3181
+ for (const { reader, writer } of this.connections.values()) {
3182
+ reader._emitClose();
3183
+ writer._emitClose();
3184
+ }
3185
+ }
3186
+ handleWorkerError(event) {
3187
+ const error = new Error(event.message || "Worker error");
3188
+ this.error(`Worker error:`, error, event);
3189
+ this.emitErrorToAllConnections(error);
3190
+ }
3191
+ handleBroadcastMessage = (event) => {
3192
+ if (!this.started) return;
3193
+ const brokerMessage = event.data;
3194
+ if (brokerMessage.type === "worker-message") {
3195
+ if (!this.isLeader) {
3196
+ const { message: unrewrittenMessage, isOurs } = this.unrewriteMessage(brokerMessage.message);
3197
+ if (isOurs) this.emitToAllConnections(unrewrittenMessage);
3198
+ }
3199
+ } else if (brokerMessage.type === "worker-request") {
3200
+ if (this.isLeader) if (this.worker) {
3201
+ this.worker.postMessage(brokerMessage.message);
3202
+ const response = {
3203
+ type: "worker-response",
3204
+ id: brokerMessage.id,
3205
+ message: brokerMessage.message
3206
+ };
3207
+ this.broadcastChannel.postMessage(response);
3208
+ } else this.leaderRequestQueue.push({
3209
+ id: brokerMessage.id,
3210
+ message: brokerMessage.message
3211
+ });
3212
+ } else if (brokerMessage.type === "worker-response") {
3213
+ const pending = this.pendingRequests.get(brokerMessage.id);
3214
+ if (pending) {
3215
+ pending.resolve(brokerMessage.message);
3216
+ this.pendingRequests.delete(brokerMessage.id);
3217
+ }
3218
+ }
3219
+ };
3220
+ async sendMessage(message) {
3221
+ const originalId = message?.id;
3222
+ this.debug(`sendMessage: originalId=${originalId}`, message);
3223
+ const rewrittenMessage = this.rewriteMessage(message);
3224
+ const rewrittenId = rewrittenMessage?.id;
3225
+ if (this.isLeader) {
3226
+ if (!this.worker) {
3227
+ this.debug(`Leader not ready; waiting for worker to initialize`);
3228
+ if (this.workerReadyPromise) await this.workerReadyPromise;
3229
+ }
3230
+ if (this.worker) {
3231
+ this.debug(`Sending to worker with rewrittenId=${rewrittenId}`, message);
3232
+ this.worker.postMessage(rewrittenMessage);
3233
+ return;
3234
+ }
3235
+ this.debug(`Worker still not available after wait; falling back to broadcast`);
3236
+ } else {
3237
+ if (!this.broadcastChannel) throw new Error("Broker not started");
3238
+ const requestId = String(this.nextRequestId++);
3239
+ this.debug(`Sending worker-request: brokerRequestId=${requestId}, rewrittenId=${rewrittenId}`, message);
3240
+ const request = {
3241
+ type: "worker-request",
3242
+ id: requestId,
3243
+ message: rewrittenMessage
3244
+ };
3245
+ await new Promise((resolve, reject) => {
3246
+ const timeout = setTimeout(() => {
3247
+ this.pendingRequests.delete(requestId);
3248
+ reject(new MultiTabWorkerBrokerError(`MultiTabWorkerBroker request timeout - no leader responded within ${this.timeout}ms`, { rpcMessage: message }));
3249
+ }, this.timeout);
3250
+ this.pendingRequests.set(requestId, {
3251
+ resolve: () => {
3252
+ clearTimeout(timeout);
3253
+ resolve();
3254
+ },
3255
+ reject: (error) => {
3256
+ clearTimeout(timeout);
3257
+ reject(error);
3258
+ }
3259
+ });
3260
+ this.broadcastChannel.postMessage(request);
3261
+ });
3262
+ }
3263
+ }
3264
+ /** Stop the broker and release all resources */
3265
+ async stop() {
3266
+ if (this.stopPromise) {
3267
+ await this.stopPromise;
3268
+ return;
3269
+ }
3270
+ if (!this.started) return;
3271
+ this.started = false;
3272
+ const performStop = async () => {
3273
+ if (this.lockAbortController) this.lockAbortController.abort();
3274
+ const lockPromiseToAwait = this.activeLockPromise;
3275
+ if (lockPromiseToAwait) {
3276
+ try {
3277
+ await lockPromiseToAwait;
3278
+ } catch (error) {
3279
+ if (error && error.name !== "AbortError") this.error("Error while waiting for lock release:", error);
3280
+ }
3281
+ this.activeLockPromise = null;
3282
+ }
3283
+ if (this.worker) {
3284
+ this.worker.terminate();
3285
+ this.worker = null;
3286
+ }
3287
+ const channel = this.broadcastChannel;
3288
+ if (channel) {
3289
+ channel.removeEventListener("message", this.handleBroadcastMessage);
3290
+ channel.close();
3291
+ this.broadcastChannel = null;
3292
+ }
3293
+ for (const [id, pending] of this.pendingRequests.entries()) pending.reject(/* @__PURE__ */ new Error("Broker stopped"));
3294
+ this.pendingRequests.clear();
3295
+ this.emitCloseToAllConnections();
3296
+ for (const { reader, writer } of this.connections.values()) {
3297
+ reader.dispose();
3298
+ writer.dispose();
3299
+ }
3300
+ this.connections.clear();
3301
+ this.workerReadyPromise = null;
3302
+ this.workerReadyResolver = null;
3303
+ this.leaderRequestQueue = [];
3304
+ this.rewrittenIdMap.clear();
3305
+ const wasLeader = this.isLeader;
3306
+ this.isLeader = false;
3307
+ if (wasLeader) this.onStateChange?.({ isLeader: false });
3308
+ };
3309
+ this.stopPromise = (async () => {
3310
+ try {
3311
+ await performStop();
3312
+ } finally {
3313
+ this.stopPromise = null;
3314
+ }
3315
+ })();
3316
+ await this.stopPromise;
3317
+ }
3318
+ };
3319
+ var MultiTabMessageReader = class MultiTabMessageReader {
3320
+ errorEmitter = new import_main.Emitter();
3321
+ closeEmitter = new import_main.Emitter();
3322
+ partialMessageEmitter = new import_main.Emitter();
3323
+ messageEmitter = new import_main.Emitter();
3324
+ disposed = false;
3325
+ hasListener = false;
3326
+ queuedMessages = [];
3327
+ static MAX_QUEUE = 1e3;
3328
+ onError = this.errorEmitter.event;
3329
+ onClose = this.closeEmitter.event;
3330
+ onPartialMessage = this.partialMessageEmitter.event;
3331
+ listen(callback) {
3332
+ const disposable = this.messageEmitter.event((message) => {
3333
+ callback(message);
3334
+ });
3335
+ if (!this.hasListener) {
3336
+ this.hasListener = true;
3337
+ if (this.queuedMessages.length > 0) {
3338
+ const toFlush = this.queuedMessages.splice(0, this.queuedMessages.length);
3339
+ for (const msg of toFlush) this.messageEmitter.fire(msg);
3340
+ }
3341
+ }
3342
+ return disposable;
3343
+ }
3344
+ _emitMessage(message) {
3345
+ if (!this.disposed) if (this.hasListener) this.messageEmitter.fire(message);
3346
+ else {
3347
+ if (this.queuedMessages.length >= MultiTabMessageReader.MAX_QUEUE) this.queuedMessages.shift();
3348
+ this.queuedMessages.push(message);
3349
+ }
3350
+ }
3351
+ _emitError(error) {
3352
+ if (!this.disposed) this.errorEmitter.fire(error);
3353
+ }
3354
+ _emitClose() {
3355
+ if (!this.disposed) this.closeEmitter.fire();
3356
+ }
3357
+ dispose() {
3358
+ if (!this.disposed) {
3359
+ this.disposed = true;
3360
+ this.errorEmitter.dispose();
3361
+ this.closeEmitter.dispose();
3362
+ this.partialMessageEmitter.dispose();
3363
+ this.messageEmitter.dispose();
3364
+ this.queuedMessages = [];
3365
+ }
3366
+ }
3367
+ };
3368
+ var MultiTabMessageWriter = class {
3369
+ errorEmitter = new import_main.Emitter();
3370
+ closeEmitter = new import_main.Emitter();
3371
+ disposed = false;
3372
+ writeHandler = null;
3373
+ onError = this.errorEmitter.event;
3374
+ onClose = this.closeEmitter.event;
3375
+ async write(message) {
3376
+ if (this.disposed) throw new Error("Writer is disposed");
3377
+ if (!this.writeHandler) throw new Error("Writer not initialized");
3378
+ try {
3379
+ await this.writeHandler(message);
3380
+ } catch (error) {
3381
+ const err = error instanceof Error ? error : new Error(String(error));
3382
+ this.errorEmitter.fire([
3383
+ err,
3384
+ message,
3385
+ void 0
3386
+ ]);
3387
+ throw err;
3388
+ }
3389
+ }
3390
+ end() {}
3391
+ _setWriteHandler(handler) {
3392
+ this.writeHandler = handler;
3393
+ }
3394
+ _emitError(error) {
3395
+ if (!this.disposed) this.errorEmitter.fire([
3396
+ error,
3397
+ void 0,
3398
+ void 0
3399
+ ]);
3400
+ }
3401
+ _emitClose() {
3402
+ if (!this.disposed) this.closeEmitter.fire();
3403
+ }
3404
+ dispose() {
3405
+ if (!this.disposed) {
3406
+ this.disposed = true;
3407
+ this.writeHandler = null;
3408
+ this.errorEmitter.dispose();
3409
+ this.closeEmitter.dispose();
3410
+ }
3411
+ }
3412
+ };
3413
+
3414
+ //#endregion
3415
+ //#region packages/substrate/src/utils/debug.ts
3416
+ /**
3417
+ * Substrate Logging Utility
3418
+ *
3419
+ * A unified logging system with configurable levels and component filtering.
3420
+ *
3421
+ * Configuration via globals:
3422
+ * - __SUBSTRATE_LOG_LEVEL: "off" | "error" | "warn" | "info" | "debug" | "trace"
3423
+ * - __SUBSTRATE_LOG_COMPONENTS: string[] - filter to specific components (empty = all)
3424
+ *
3425
+ * Or via API:
3426
+ * - setLogLevel("debug")
3427
+ * - setLogComponents(["vfs", "proc"])
3428
+ */
3429
+ /**
3430
+ * Capture the original browser console at module load time.
3431
+ *
3432
+ * CRITICAL: runWithGlobals() replaces globalThis.console with a child process
3433
+ * console that routes output to process stdout/stderr. If our internal logging
3434
+ * used globalThis.console, it would cause infinite recursion:
3435
+ *
3436
+ * 1. User code: console.log("hello")
3437
+ * 2. Custom console → processContext.writeStdout()
3438
+ * 3. writeStdout() → procLog.trace() → console.debug() (OOPS! globalThis.console is replaced)
3439
+ * 4. Custom console → processContext.writeStdout()
3440
+ * 5. → infinite recursion → stack overflow
3441
+ *
3442
+ * By capturing the original console here, our internal logging always goes
3443
+ * to the real browser console, never to a child process's stdout.
3444
+ */
3445
+ const _console = console;
3446
+ /** Log level ordering (higher = more verbose) */
3447
+ const LOG_LEVEL_ORDER = {
3448
+ off: 0,
3449
+ error: 1,
3450
+ warn: 2,
3451
+ info: 3,
3452
+ debug: 4,
3453
+ trace: 5
3454
+ };
3455
+ /** Get current log level from global config */
3456
+ function getLogLevel() {
3457
+ const level = globalThis.__SUBSTRATE_LOG_LEVEL;
3458
+ if (typeof level === "string" && level in LOG_LEVEL_ORDER) return level;
3459
+ return "info";
3460
+ }
3461
+ /** Set log level at runtime */
3462
+ function setLogLevel(level) {
3463
+ globalThis.__SUBSTRATE_LOG_LEVEL = level;
3464
+ }
3465
+ /** Get component filter */
3466
+ function getLogComponents() {
3467
+ const components = globalThis.__SUBSTRATE_LOG_COMPONENTS;
3468
+ if (Array.isArray(components)) return components;
3469
+ return [];
3470
+ }
3471
+ /** Set component filter at runtime */
3472
+ function setLogComponents(components) {
3473
+ globalThis.__SUBSTRATE_LOG_COMPONENTS = components;
3474
+ }
3475
+ /** Check if a log should be emitted based on current config */
3476
+ function shouldLog(level, component) {
3477
+ const configLevel = getLogLevel();
3478
+ const configComponents = getLogComponents();
3479
+ if (LOG_LEVEL_ORDER[level] > LOG_LEVEL_ORDER[configLevel]) return false;
3480
+ if (configComponents.length > 0) {
3481
+ if (!configComponents.some((pattern) => {
3482
+ if (pattern.endsWith("*")) return component.startsWith(pattern.slice(0, -1));
3483
+ return component === pattern;
3484
+ })) return false;
3485
+ }
3486
+ return true;
3487
+ }
3488
+ /** Color codes for different log levels (for browser/terminal) */
3489
+ const LEVEL_COLORS = {
3490
+ off: "",
3491
+ error: "color: #ff5555; font-weight: bold",
3492
+ warn: "color: #ffaa00; font-weight: bold",
3493
+ info: "color: #55aaff",
3494
+ debug: "color: #888888",
3495
+ trace: "color: #666666"
3496
+ };
3497
+ /** Create a logger for a specific component */
3498
+ function createLogger(component) {
3499
+ const emit = (level, ...args) => {
3500
+ if (level === "off") return;
3501
+ if (!shouldLog(level, component)) return;
3502
+ const prefix = `[${component}]`;
3503
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().split("T")[1]?.slice(0, -1) ?? "";
3504
+ switch (level) {
3505
+ case "error":
3506
+ _console.error(`%c${timestamp} ${level.toUpperCase()} ${prefix}`, LEVEL_COLORS[level], ...args);
3507
+ break;
3508
+ case "warn":
3509
+ _console.warn(`%c${timestamp} ${level.toUpperCase()} ${prefix}`, LEVEL_COLORS[level], ...args);
3510
+ break;
3511
+ case "info":
3512
+ _console.info(`%c${timestamp} ${level.toUpperCase()} ${prefix}`, LEVEL_COLORS[level], ...args);
3513
+ break;
3514
+ case "debug":
3515
+ _console.debug(`%c${timestamp} ${level.toUpperCase()} ${prefix}`, LEVEL_COLORS[level], ...args);
3516
+ break;
3517
+ case "trace":
3518
+ _console.debug(`%c${timestamp} ${level.toUpperCase()} ${prefix}`, LEVEL_COLORS[level], ...args);
3519
+ break;
3520
+ }
3521
+ };
3522
+ return {
3523
+ error: (...args) => emit("error", ...args),
3524
+ warn: (...args) => emit("warn", ...args),
3525
+ info: (...args) => emit("info", ...args),
3526
+ debug: (...args) => emit("debug", ...args),
3527
+ trace: (...args) => emit("trace", ...args),
3528
+ log: emit
3529
+ };
3530
+ }
3531
+ /** Kernel logger */
3532
+ const kernelLog = createLogger("kernel");
3533
+ /** VFS logger */
3534
+ const vfsLog = createLogger("vfs");
3535
+ /** Process logger */
3536
+ const procLog = createLogger("proc");
3537
+ /** Network logger */
3538
+ const netLog = createLogger("net");
3539
+ /** Event loop logger */
3540
+ const eventLog = createLogger("events");
3541
+ /** Module loader logger */
3542
+ const moduleLog = createLogger("module");
3543
+ /** ESM loader logger */
3544
+ const esmLog = createLogger("esm");
3545
+ /** HTTP logger */
3546
+ const httpLog = createLogger("http");
3547
+ /** WebSocket logger */
3548
+ const wsLog = createLogger("ws");
3549
+ /** Child process logger */
3550
+ const childLog = createLogger("child_process");
3551
+ /** Buffer logger */
3552
+ const bufferLog = createLogger("buffer");
3553
+ /** Stream logger */
3554
+ const streamLog = createLogger("stream");
3555
+ /** FS logger */
3556
+ const fsLog = createLogger("fs");
3557
+ /** Worker logger (for worker/client communication) */
3558
+ const workerLog = createLogger("worker");
3559
+ /** Runtime logger */
3560
+ const runtimeLog = createLogger("runtime");
3561
+
3562
+ //#endregion
3563
+ //#region packages/substrate/src/kernel/wasm.ts
3564
+ /**
3565
+ * Substrate CDN asset URLs.
3566
+ *
3567
+ * Assets (kernel WASM, runtime worker, network driver) are distributed via
3568
+ * the Gadget CDN at versioned paths. They also ship inside the npm package
3569
+ * under dist/assets/ for consumers who want to self-host.
3570
+ */
3571
+ /** CDN base URL for all Substrate assets. */
3572
+ const SUBSTRATE_CDN_BASE = "https://assets.gadget.dev/substrate";
3573
+ /** Package version — kept in sync by scripts/release.mjs. */
3574
+ const SUBSTRATE_VERSION = "0.1.0-rc.1";
3575
+ /** Get the CDN URL for the kernel WASM binary. */
3576
+ function getKernelUrl(version = SUBSTRATE_VERSION) {
3577
+ return `${SUBSTRATE_CDN_BASE}/v${version}/kernel.wasm`;
3578
+ }
3579
+ /** Get the CDN URL for the Substrate runtime bundle. */
3580
+ function getRuntimeUrl(version = SUBSTRATE_VERSION) {
3581
+ return `${SUBSTRATE_CDN_BASE}/v${version}/runtime.js`;
3582
+ }
3583
+ /** Get the CDN URL for the Substrate network driver bundle. */
3584
+ function getNetworkDriverUrl(version = SUBSTRATE_VERSION) {
3585
+ return `${SUBSTRATE_CDN_BASE}/v${version}/network-driver.js`;
3586
+ }
3587
+ /** Get the CDN URL for a binary tarball (e.g., npm, yarn, pnpm). */
3588
+ function getBinaryTarballUrl(binary, binaryVersion, version = SUBSTRATE_VERSION) {
3589
+ return `${SUBSTRATE_CDN_BASE}/v${version}/${binary}-${binaryVersion}-bundle.tgz`;
3590
+ }
3591
+
3592
+ //#endregion
3593
+ //#region packages/substrate/src/utils/path.ts
3594
+ /**
3595
+ * Normalize a path, resolving '..' and '.' segments
3596
+ */
3597
+ function normalize(path) {
3598
+ if (path.length === 0) return ".";
3599
+ const isAbsolute = path.charCodeAt(0) === 47;
3600
+ const trailingSlash = path.charCodeAt(path.length - 1) === 47;
3601
+ const segments = path.split("/");
3602
+ const result = [];
3603
+ for (const segment of segments) {
3604
+ if (segment === "" || segment === ".") continue;
3605
+ if (segment === "..") {
3606
+ if (result.length > 0 && result[result.length - 1] !== "..") result.pop();
3607
+ else if (!isAbsolute) result.push("..");
3608
+ } else result.push(segment);
3609
+ }
3610
+ let normalized = result.join("/");
3611
+ if (isAbsolute) normalized = "/" + normalized;
3612
+ if (trailingSlash && normalized.length > 1) normalized += "/";
3613
+ return normalized || (isAbsolute ? "/" : ".");
3614
+ }
3615
+ /**
3616
+ * Join path segments
3617
+ */
3618
+ function join(...paths) {
3619
+ if (paths.length === 0) return ".";
3620
+ let joined = "";
3621
+ for (const path of paths) if (path.length > 0) if (joined.length === 0) joined = path;
3622
+ else joined += "/" + path;
3623
+ return normalize(joined);
3624
+ }
3625
+
3626
+ //#endregion
3627
+ //#region packages/substrate/src/binaries.ts
3628
+ /**
3629
+ * Binary Configuration
3630
+ *
3631
+ * Central configuration for all binaries that Substrate can install and run.
3632
+ * This module is the source of truth for:
3633
+ * - Binary versions
3634
+ * - Binary handlers
3635
+ * - Tarball URL generation
3636
+ * - Binary specs for initialization
3637
+ */
3638
+ /**
3639
+ * Default versions for each binary.
3640
+ * Update these when upgrading binary versions.
3641
+ */
3642
+ const BINARY_VERSIONS = {
3643
+ npm: "11.8.0",
3644
+ pnpm: "10.6.4",
3645
+ yarn: "1.22.22"
3646
+ };
3647
+ /**
3648
+ * Get the default tarball URL for a binary.
3649
+ *
3650
+ * When no baseUrl is provided, returns the CDN URL for the binary tarball.
3651
+ * When a baseUrl is provided, returns a relative path under that base.
3652
+ *
3653
+ * @param binary - The binary name
3654
+ * @param baseUrl - Base URL prefix. If omitted, uses the Gadget CDN.
3655
+ * @returns The full tarball URL
3656
+ */
3657
+ function getDefaultTarballUrl(binary, baseUrl) {
3658
+ const version = BINARY_VERSIONS[binary];
3659
+ if (baseUrl !== void 0) return join(baseUrl, `${binary}-${version}-bundle.tgz`);
3660
+ return getBinaryTarballUrl(binary, version);
3661
+ }
3662
+ /**
3663
+ * Get all binary names
3664
+ */
3665
+ function getBinaryNames() {
3666
+ return Object.keys(BINARY_VERSIONS);
3667
+ }
3668
+
3669
+ //#endregion
3670
+ //#region packages/substrate/src/boot/index.ts
3671
+ /**
3672
+ * Substrate Bootloader
3673
+ *
3674
+ * Consolidates all Substrate initialization:
3675
+ * - Service Worker registration and activation
3676
+ * - Multi-tab coordination (via thumbdrive's MultiTabWorkerBroker)
3677
+ * - Kernel WASM loading
3678
+ * - OPFS filesystem initialization (future)
3679
+ *
3680
+ * @example
3681
+ * ```ts
3682
+ * import { bootSubstrate } from '@gadgetinc/substrate/boot';
3683
+ *
3684
+ * const substrate = await bootSubstrate({
3685
+ * name: 'my-project',
3686
+ * });
3687
+ *
3688
+ * // fetch() and WebSocket just work - SW intercepts transparently
3689
+ * const response = await fetch('/api/hello');
3690
+ * ```
3691
+ */
3692
+ const bootLog = createLogger("boot");
3693
+ /** WebSocket ready states */
3694
+ const WS_CONNECTING = 0;
3695
+ const WS_OPEN = 1;
3696
+ const WS_CLOSING = 2;
3697
+ const WS_CLOSED = 3;
3698
+ /**
3699
+ * Internal class that implements the WebSocket API and proxies through the worker.
3700
+ *
3701
+ * This is NOT exported directly - users access it via `substrate.WebSocket`.
3702
+ */
3703
+ var ProxyWebSocket = class extends EventTarget {
3704
+ static CONNECTING = WS_CONNECTING;
3705
+ static OPEN = WS_OPEN;
3706
+ static CLOSING = WS_CLOSING;
3707
+ static CLOSED = WS_CLOSED;
3708
+ url;
3709
+ _readyState = WS_CONNECTING;
3710
+ _protocol = "";
3711
+ _extensions = "";
3712
+ _bufferedAmount = 0;
3713
+ binaryType = "blob";
3714
+ onopen = null;
3715
+ onmessage = null;
3716
+ onerror = null;
3717
+ onclose = null;
3718
+ _wsId;
3719
+ _send;
3720
+ _getNextId;
3721
+ constructor(url, protocols, wsId, send, getNextId) {
3722
+ super();
3723
+ this.url = typeof url === "string" ? url : url.toString();
3724
+ this._wsId = wsId;
3725
+ this._send = send;
3726
+ this._getNextId = getNextId;
3727
+ const protocolArray = Array.isArray(protocols) ? protocols : protocols ? [protocols] : [];
3728
+ queueMicrotask(() => {
3729
+ this._send({
3730
+ type: "ws_connect",
3731
+ id: this._getNextId(),
3732
+ wsId: this._wsId,
3733
+ url: this.url,
3734
+ protocols: protocolArray
3735
+ }).catch((err) => {
3736
+ this._handleError(err instanceof Error ? err.message : String(err));
3737
+ });
3738
+ });
3739
+ }
3740
+ get readyState() {
3741
+ return this._readyState;
3742
+ }
3743
+ get protocol() {
3744
+ return this._protocol;
3745
+ }
3746
+ get extensions() {
3747
+ return this._extensions;
3748
+ }
3749
+ get bufferedAmount() {
3750
+ return this._bufferedAmount;
3751
+ }
3752
+ send(data) {
3753
+ if (this._readyState !== WS_OPEN) throw new DOMException("Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.", "InvalidStateError");
3754
+ let payload;
3755
+ if (typeof data === "string") payload = data;
3756
+ else if (data instanceof ArrayBuffer) payload = new Uint8Array(data);
3757
+ else if (ArrayBuffer.isView(data)) payload = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
3758
+ else if (data instanceof Blob) {
3759
+ data.arrayBuffer().then((buffer) => {
3760
+ if (this._readyState === WS_OPEN) this._send({
3761
+ type: "ws_send",
3762
+ id: this._getNextId(),
3763
+ wsId: this._wsId,
3764
+ data: new Uint8Array(buffer)
3765
+ }).catch((err) => {
3766
+ bootLog.error(`Failed to send WebSocket data: ${err instanceof Error ? err.message : String(err)}`);
3767
+ });
3768
+ }).catch((err) => {
3769
+ bootLog.error(`Failed to send WebSocket data: ${err instanceof Error ? err.message : String(err)}`);
3770
+ });
3771
+ return;
3772
+ } else throw new TypeError("Invalid data type");
3773
+ this._send({
3774
+ type: "ws_send",
3775
+ id: this._getNextId(),
3776
+ wsId: this._wsId,
3777
+ data: payload
3778
+ }).catch(() => {});
3779
+ }
3780
+ close(code, reason) {
3781
+ if (this._readyState === WS_CLOSING || this._readyState === WS_CLOSED) return;
3782
+ this._readyState = WS_CLOSING;
3783
+ this._send({
3784
+ type: "ws_close",
3785
+ id: this._getNextId(),
3786
+ wsId: this._wsId,
3787
+ code,
3788
+ reason
3789
+ }).catch(() => {});
3790
+ }
3791
+ _handleOpen(protocol) {
3792
+ if (this._readyState !== WS_CONNECTING) return;
3793
+ this._readyState = WS_OPEN;
3794
+ this._protocol = protocol;
3795
+ const event = new Event("open");
3796
+ this.onopen?.call(this, event);
3797
+ this.dispatchEvent(event);
3798
+ }
3799
+ _handleMessage(data) {
3800
+ if (this._readyState !== WS_OPEN) return;
3801
+ let messageData;
3802
+ if (typeof data === "string") messageData = data;
3803
+ else messageData = data.buffer;
3804
+ const event = new MessageEvent("message", { data: messageData });
3805
+ this.onmessage?.call(this, event);
3806
+ this.dispatchEvent(event);
3807
+ }
3808
+ _handleClose(code, reason, wasClean) {
3809
+ if (this._readyState === WS_CLOSED) return;
3810
+ this._readyState = WS_CLOSED;
3811
+ const event = new CloseEvent("close", {
3812
+ code,
3813
+ reason,
3814
+ wasClean
3815
+ });
3816
+ this.onclose?.call(this, event);
3817
+ this.dispatchEvent(event);
3818
+ }
3819
+ _handleError(message) {
3820
+ const event = new Event("error");
3821
+ event.message = message;
3822
+ this.onerror?.call(this, event);
3823
+ this.dispatchEvent(event);
3824
+ if (this._readyState !== WS_CLOSED) {
3825
+ this._readyState = WS_CLOSED;
3826
+ const closeEvent = new CloseEvent("close", {
3827
+ code: 1006,
3828
+ reason: message,
3829
+ wasClean: false
3830
+ });
3831
+ this.onclose?.call(this, closeEvent);
3832
+ this.dispatchEvent(closeEvent);
3833
+ }
3834
+ }
3835
+ };
3836
+ /**
3837
+ * Register the Service Worker and wait for it to control this page.
3838
+ */
3839
+ async function registerServiceWorker(swUrl) {
3840
+ if (!("serviceWorker" in navigator)) throw new Error("Service Workers not supported in this browser");
3841
+ bootLog.debug("Registering Service Worker:", swUrl);
3842
+ const registration = await navigator.serviceWorker.register(swUrl, {
3843
+ scope: "/",
3844
+ type: "module"
3845
+ });
3846
+ if (registration.waiting) registration.waiting.postMessage({ type: "skipWaiting" });
3847
+ if (registration.installing) await new Promise((resolve) => {
3848
+ const worker = registration.installing;
3849
+ worker.addEventListener("statechange", () => {
3850
+ if (worker.state === "activated") resolve();
3851
+ });
3852
+ });
3853
+ registration.addEventListener("updatefound", () => {
3854
+ const newWorker = registration.installing;
3855
+ if (newWorker) {
3856
+ bootLog.debug("SW update found, telling new worker to skip waiting");
3857
+ newWorker.postMessage({ type: "skipWaiting" });
3858
+ }
3859
+ });
3860
+ return registration;
3861
+ }
3862
+ /**
3863
+ * Wait for the Service Worker to control this page.
3864
+ */
3865
+ async function waitForServiceWorkerControl() {
3866
+ if (navigator.serviceWorker.controller) {
3867
+ bootLog.debug("Already controlled by Service Worker");
3868
+ return;
3869
+ }
3870
+ bootLog.debug("Waiting for Service Worker control...");
3871
+ return new Promise((resolve) => {
3872
+ navigator.serviceWorker.addEventListener("controllerchange", () => {
3873
+ bootLog.debug("Service Worker now controlling page");
3874
+ resolve();
3875
+ }, { once: true });
3876
+ navigator.serviceWorker.ready.then((registration) => {
3877
+ registration.active?.postMessage({ type: "claim" });
3878
+ });
3879
+ });
3880
+ }
3881
+ /**
3882
+ * Send routing configuration to the Service Worker.
3883
+ *
3884
+ * Also watches for controller changes (e.g., when a new SW activates via
3885
+ * skipWaiting during development) and re-sends the config so the new SW
3886
+ * has the basePath and other routing state.
3887
+ */
3888
+ function configureServiceWorker(registration, config) {
3889
+ const sendConfig = () => {
3890
+ const worker = registration.active ?? navigator.serviceWorker.controller;
3891
+ if (worker) {
3892
+ bootLog.debug("Sending routing config to SW");
3893
+ worker.postMessage({
3894
+ type: "config",
3895
+ config
3896
+ });
3897
+ }
3898
+ };
3899
+ sendConfig();
3900
+ navigator.serviceWorker.addEventListener("controllerchange", () => {
3901
+ bootLog.debug("SW controller changed, re-sending config");
3902
+ sendConfig();
3903
+ });
3904
+ }
3905
+ /**
3906
+ * Get the URL to the Substrate runtime entrypoint.
3907
+ * Returns the CDN URL by default.
3908
+ */
3909
+ function getRuntimeURL() {
3910
+ return new URL(getRuntimeUrl());
3911
+ }
3912
+ /**
3913
+ * Boot Substrate with Service Worker network interception and multi-tab coordination.
3914
+ *
3915
+ * This must be called early in your application, before any requests that should
3916
+ * be intercepted by the Service Worker.
3917
+ *
3918
+ * @example
3919
+ * ```ts
3920
+ * const substrate = await bootSubstrate({
3921
+ * name: 'my-project',
3922
+ * });
3923
+ *
3924
+ * await substrate.mount({
3925
+ * 'server.js': { file: { contents: '...' } }
3926
+ * });
3927
+ *
3928
+ * substrate.spawn('node', ['server.js']);
3929
+ *
3930
+ * // fetch() just works - SW intercepts automatically
3931
+ * await substrate.waitForPort(3000);
3932
+ * const res = await fetch('http://localhost:3000/');
3933
+ * ```
3934
+ */
3935
+ async function bootSubstrate(config = {}) {
3936
+ const networkDriverUrl = config.networkDriverUrl ?? getNetworkDriverUrl();
3937
+ const basePath = config.basePath ?? null;
3938
+ const basePathPort = config.basePathPort ?? null;
3939
+ const registration = await registerServiceWorker(networkDriverUrl);
3940
+ await waitForServiceWorkerControl();
3941
+ const routingConfig = {
3942
+ basePath,
3943
+ basePathPort,
3944
+ listeningPorts: [],
3945
+ proxyUrl: config.proxyUrl,
3946
+ neverProxy: config.neverProxy ?? [],
3947
+ logging: config.logging
3948
+ };
3949
+ const client = await createSubstrateClient(config, routingConfig, registration);
3950
+ patchGlobalWebSocket(client, routingConfig);
3951
+ if (config.persistence?.storeName) window.addEventListener("beforeunload", () => {
3952
+ client.persist().catch(() => {});
3953
+ });
3954
+ return client;
3955
+ }
3956
+ /**
3957
+ * Patch globalThis.WebSocket to route localhost connections through Substrate.
3958
+ *
3959
+ * This allows code in the boot tab to use `new WebSocket('ws://localhost:PORT')`
3960
+ * and have it automatically connect to virtual servers running in Substrate.
3961
+ */
3962
+ function patchGlobalWebSocket(client, routingConfig) {
3963
+ const NativeWebSocket = globalThis.WebSocket;
3964
+ const PatchedWebSocket = function(url, protocols) {
3965
+ const urlString = typeof url === "string" ? url : url.toString();
3966
+ const parsedUrl = new URL(urlString, globalThis.location?.href);
3967
+ if (parsedUrl.hostname === "localhost" || parsedUrl.hostname === "127.0.0.1") {
3968
+ const port = parseInt(parsedUrl.port) || (parsedUrl.protocol === "wss:" ? 443 : 80);
3969
+ if (routingConfig.listeningPorts.includes(port)) {
3970
+ bootLog.debug(`Routing WebSocket to Substrate: ${urlString}`);
3971
+ return new client.WebSocket(url, protocols);
3972
+ }
3973
+ }
3974
+ return new NativeWebSocket(url, protocols);
3975
+ };
3976
+ Object.defineProperties(PatchedWebSocket, {
3977
+ CONNECTING: {
3978
+ value: NativeWebSocket.CONNECTING,
3979
+ writable: false
3980
+ },
3981
+ OPEN: {
3982
+ value: NativeWebSocket.OPEN,
3983
+ writable: false
3984
+ },
3985
+ CLOSING: {
3986
+ value: NativeWebSocket.CLOSING,
3987
+ writable: false
3988
+ },
3989
+ CLOSED: {
3990
+ value: NativeWebSocket.CLOSED,
3991
+ writable: false
3992
+ }
3993
+ });
3994
+ Object.setPrototypeOf(PatchedWebSocket.prototype, NativeWebSocket.prototype);
3995
+ globalThis.WebSocket = PatchedWebSocket;
3996
+ bootLog.debug("Patched globalThis.WebSocket for Substrate routing");
3997
+ }
3998
+ /**
3999
+ * Create a Substrate client that communicates with the worker.
4000
+ *
4001
+ * Uses MultiTabWorkerBroker for leader election - only one tab runs the kernel,
4002
+ * other tabs communicate through BroadcastChannel.
4003
+ */
4004
+ async function createSubstrateClient(config, routingConfig, registration) {
4005
+ const runtimeUrl = config.runtimeUrl ? new URL(config.runtimeUrl.toString(), location.href) : getRuntimeURL();
4006
+ const lockName = `substrate:${config.name ?? "default"}`;
4007
+ const networkChannel = new BroadcastChannel("substrate:network");
4008
+ let nextId = 1;
4009
+ const pending = /* @__PURE__ */ new Map();
4010
+ const listeningPorts = /* @__PURE__ */ new Set();
4011
+ const portListeners = /* @__PURE__ */ new Map();
4012
+ const processExitResolvers = /* @__PURE__ */ new Map();
4013
+ const pendingExits = /* @__PURE__ */ new Map();
4014
+ const processOutputControllers = /* @__PURE__ */ new Map();
4015
+ const pendingOutput = /* @__PURE__ */ new Map();
4016
+ const leadershipListeners = [];
4017
+ let nextWsId = 1;
4018
+ const activeWebSockets = /* @__PURE__ */ new Map();
4019
+ const servedPageWsClients = /* @__PURE__ */ new Map();
4020
+ let currentIsLeader = false;
4021
+ const { promise: leadershipKnown, resolve: resolveLeadership } = Promise.withResolvers();
4022
+ const broker = new MultiTabWorkerBroker(lockName, () => {
4023
+ bootLog.debug("Creating worker (this tab is becoming leader)");
4024
+ currentIsLeader = true;
4025
+ resolveLeadership(true);
4026
+ return new Worker(runtimeUrl, { type: "module" });
4027
+ });
4028
+ await broker.start();
4029
+ setTimeout(() => resolveLeadership(false), 100);
4030
+ currentIsLeader = await leadershipKnown;
4031
+ bootLog.debug(`Broker started, isLeader=${currentIsLeader}`);
4032
+ const connection = broker.createConnection();
4033
+ let readyResolve = null;
4034
+ const readyPromise = new Promise((resolve, reject) => {
4035
+ readyResolve = resolve;
4036
+ setTimeout(() => reject(/* @__PURE__ */ new Error("Worker timeout")), 1e4);
4037
+ });
4038
+ connection.reader.listen((raw) => {
4039
+ const msg = raw;
4040
+ switch (msg.type) {
4041
+ case "success": {
4042
+ if (msg.id === void 0) break;
4043
+ const p = pending.get(msg.id);
4044
+ if (p) {
4045
+ pending.delete(msg.id);
4046
+ p.resolve(msg.result);
4047
+ }
4048
+ break;
4049
+ }
4050
+ case "error": {
4051
+ if (msg.id === void 0) break;
4052
+ const p = pending.get(msg.id);
4053
+ if (p) {
4054
+ pending.delete(msg.id);
4055
+ const err = new Error(msg.error.message);
4056
+ if (msg.error.code) err.code = msg.error.code;
4057
+ if (msg.error.stack) err.stack = msg.error.stack;
4058
+ p.reject(err);
4059
+ }
4060
+ break;
4061
+ }
4062
+ case "log":
4063
+ config.onConsole?.(msg.level, msg.args);
4064
+ break;
4065
+ case "port_listen": {
4066
+ const port = msg.port;
4067
+ listeningPorts.add(port);
4068
+ if (!routingConfig.listeningPorts.includes(port)) routingConfig.listeningPorts.push(port);
4069
+ registration.active?.postMessage({
4070
+ type: "port_listen",
4071
+ port
4072
+ });
4073
+ networkChannel.postMessage({
4074
+ type: "port_listen",
4075
+ port
4076
+ });
4077
+ config.onPortListen?.(port);
4078
+ const listeners = portListeners.get(port);
4079
+ if (listeners) {
4080
+ for (const resolve of listeners) resolve();
4081
+ portListeners.delete(port);
4082
+ }
4083
+ break;
4084
+ }
4085
+ case "port_close": {
4086
+ const port = msg.port;
4087
+ listeningPorts.delete(port);
4088
+ const idx = routingConfig.listeningPorts.indexOf(port);
4089
+ if (idx !== -1) routingConfig.listeningPorts.splice(idx, 1);
4090
+ registration.active?.postMessage({
4091
+ type: "port_close",
4092
+ port
4093
+ });
4094
+ networkChannel.postMessage({
4095
+ type: "port_close",
4096
+ port
4097
+ });
4098
+ config.onPortClose?.(port);
4099
+ break;
4100
+ }
4101
+ case "proc_exit": {
4102
+ const resolver = processExitResolvers.get(msg.pid);
4103
+ processOutputControllers.delete(msg.pid);
4104
+ pendingOutput.delete(msg.pid);
4105
+ if (resolver) {
4106
+ processExitResolvers.delete(msg.pid);
4107
+ resolver(msg.exitCode);
4108
+ } else pendingExits.set(msg.pid, msg.exitCode);
4109
+ break;
4110
+ }
4111
+ case "proc_stdout": {
4112
+ const controllers = processOutputControllers.get(msg.pid);
4113
+ if (controllers?.stdout) controllers.stdout.enqueue(msg.data);
4114
+ else {
4115
+ let p = pendingOutput.get(msg.pid);
4116
+ if (!p) {
4117
+ p = {
4118
+ stdout: [],
4119
+ stderr: []
4120
+ };
4121
+ pendingOutput.set(msg.pid, p);
4122
+ }
4123
+ p.stdout.push(msg.data);
4124
+ }
4125
+ break;
4126
+ }
4127
+ case "proc_stderr": {
4128
+ const controllers = processOutputControllers.get(msg.pid);
4129
+ if (controllers?.stderr) controllers.stderr.enqueue(msg.data);
4130
+ else {
4131
+ let p = pendingOutput.get(msg.pid);
4132
+ if (!p) {
4133
+ p = {
4134
+ stdout: [],
4135
+ stderr: []
4136
+ };
4137
+ pendingOutput.set(msg.pid, p);
4138
+ }
4139
+ p.stderr.push(msg.data);
4140
+ }
4141
+ break;
4142
+ }
4143
+ case "ws_open": {
4144
+ const openWs = activeWebSockets.get(msg.wsId);
4145
+ if (openWs) openWs._handleOpen(msg.protocol ?? "");
4146
+ if (servedPageWsClients.get(msg.wsId)) networkChannel.postMessage({
4147
+ type: "sw_ws_open",
4148
+ wsId: msg.wsId,
4149
+ protocol: msg.protocol
4150
+ });
4151
+ break;
4152
+ }
4153
+ case "ws_message": {
4154
+ const msgWs = activeWebSockets.get(msg.wsId);
4155
+ if (msgWs) msgWs._handleMessage(msg.data);
4156
+ if (servedPageWsClients.get(msg.wsId)) networkChannel.postMessage({
4157
+ type: "sw_ws_message",
4158
+ wsId: msg.wsId,
4159
+ data: msg.data
4160
+ });
4161
+ break;
4162
+ }
4163
+ case "ws_close": {
4164
+ const closeWs = activeWebSockets.get(msg.wsId);
4165
+ if (closeWs) {
4166
+ closeWs._handleClose(msg.code ?? 1e3, msg.reason ?? "", msg.wasClean ?? true);
4167
+ activeWebSockets.delete(msg.wsId);
4168
+ }
4169
+ if (servedPageWsClients.get(msg.wsId)) {
4170
+ networkChannel.postMessage({
4171
+ type: "sw_ws_close",
4172
+ wsId: msg.wsId,
4173
+ code: msg.code,
4174
+ reason: msg.reason,
4175
+ wasClean: msg.wasClean
4176
+ });
4177
+ servedPageWsClients.delete(msg.wsId);
4178
+ }
4179
+ break;
4180
+ }
4181
+ case "ws_error": {
4182
+ const errorWs = activeWebSockets.get(msg.wsId);
4183
+ if (errorWs) {
4184
+ errorWs._handleError(msg.message ?? "WebSocket error");
4185
+ activeWebSockets.delete(msg.wsId);
4186
+ }
4187
+ if (servedPageWsClients.get(msg.wsId)) {
4188
+ networkChannel.postMessage({
4189
+ type: "sw_ws_error",
4190
+ wsId: msg.wsId,
4191
+ message: msg.message
4192
+ });
4193
+ servedPageWsClients.delete(msg.wsId);
4194
+ }
4195
+ break;
4196
+ }
4197
+ case "ready":
4198
+ if (readyResolve) {
4199
+ readyResolve();
4200
+ readyResolve = null;
4201
+ }
4202
+ break;
4203
+ }
4204
+ });
4205
+ networkChannel.onmessage = async (event) => {
4206
+ const msg = event.data;
4207
+ if (!currentIsLeader) return;
4208
+ if (msg.type === "fetch") {
4209
+ try {
4210
+ const fetchUrl = new URL(msg.url);
4211
+ const fetchPort = parseInt(fetchUrl.port) || (fetchUrl.protocol === "https:" ? 443 : 80);
4212
+ if ((fetchUrl.hostname === "localhost" || fetchUrl.hostname === "127.0.0.1") && !listeningPorts.has(fetchPort)) {
4213
+ networkChannel.postMessage({
4214
+ type: "fetch_response",
4215
+ requestId: msg.requestId,
4216
+ status: 0,
4217
+ statusText: "",
4218
+ headers: [],
4219
+ body: null,
4220
+ error: `connect ECONNREFUSED 127.0.0.1:${fetchPort}`
4221
+ });
4222
+ return;
4223
+ }
4224
+ } catch {}
4225
+ try {
4226
+ const response = await handleFetchFromSWViaBroker(msg, connection.writer, pending, nextId++);
4227
+ networkChannel.postMessage(response);
4228
+ } catch (err) {
4229
+ networkChannel.postMessage({
4230
+ type: "fetch_response",
4231
+ requestId: msg.requestId,
4232
+ status: 500,
4233
+ statusText: "Internal Server Error",
4234
+ headers: [],
4235
+ body: new TextEncoder().encode(String(err))
4236
+ });
4237
+ }
4238
+ } else if (msg.type === "sw_ws_connect") {
4239
+ bootLog.debug("sw_ws_connect:", msg.wsId, msg.url);
4240
+ servedPageWsClients.set(msg.wsId, msg.clientId);
4241
+ send({
4242
+ type: "ws_connect",
4243
+ id: nextId++,
4244
+ wsId: msg.wsId,
4245
+ url: msg.url,
4246
+ protocols: msg.protocols
4247
+ }).catch((err) => {
4248
+ bootLog.error("Error connecting WebSocket:", err);
4249
+ networkChannel.postMessage({
4250
+ type: "sw_ws_error",
4251
+ wsId: msg.wsId,
4252
+ message: err instanceof Error ? err.message : String(err)
4253
+ });
4254
+ servedPageWsClients.delete(msg.wsId);
4255
+ });
4256
+ } else if (msg.type === "sw_ws_send") {
4257
+ bootLog.trace("sw_ws_send:", msg.wsId);
4258
+ send({
4259
+ type: "ws_send",
4260
+ id: nextId++,
4261
+ wsId: msg.wsId,
4262
+ data: msg.data
4263
+ }).catch((err) => {
4264
+ bootLog.error("Error sending WebSocket data:", err);
4265
+ });
4266
+ } else if (msg.type === "sw_ws_close") {
4267
+ bootLog.debug("sw_ws_close:", msg.wsId);
4268
+ send({
4269
+ type: "ws_close",
4270
+ id: nextId++,
4271
+ wsId: msg.wsId,
4272
+ code: msg.code,
4273
+ reason: msg.reason
4274
+ }).catch((err) => {
4275
+ bootLog.error("Error closing WebSocket:", err);
4276
+ });
4277
+ }
4278
+ };
4279
+ const send = (req) => {
4280
+ return new Promise((resolve, reject) => {
4281
+ pending.set(req.id, {
4282
+ resolve,
4283
+ reject
4284
+ });
4285
+ connection.writer.write({
4286
+ ...req,
4287
+ method: req.type
4288
+ }).catch(reject);
4289
+ });
4290
+ };
4291
+ if (currentIsLeader) {
4292
+ configureServiceWorker(registration, routingConfig);
4293
+ await readyPromise;
4294
+ const binaries = {};
4295
+ for (const binaryName of getBinaryNames()) {
4296
+ const spec = config.binaries?.[binaryName];
4297
+ if (spec === true || spec === void 0) binaries[binaryName] = { tarUrl: getDefaultTarballUrl(binaryName, config.binaryTarballBaseUrl) };
4298
+ else if (spec) binaries[binaryName] = spec;
4299
+ }
4300
+ await send({
4301
+ type: "init",
4302
+ id: nextId++,
4303
+ kernel: config.kernelUrl ?? getKernelUrl(),
4304
+ cwd: config.cwd ?? "/",
4305
+ env: config.env ?? { NODE_ENV: "development" },
4306
+ config: {
4307
+ features: {
4308
+ net_listen: true,
4309
+ fs_watch: true,
4310
+ timers: true,
4311
+ proc_spawn: true
4312
+ },
4313
+ storeName: config.persistence?.storeName
4314
+ },
4315
+ logging: config.logging,
4316
+ debug: config.debug,
4317
+ binaries,
4318
+ wasmPackages: config.wasmPackages
4319
+ });
4320
+ } else {
4321
+ readyPromise.catch(() => {});
4322
+ readyResolve = null;
4323
+ bootLog.debug("Follower tab connected to existing runtime");
4324
+ try {
4325
+ const result = await send({
4326
+ type: "http_listen",
4327
+ id: nextId++
4328
+ });
4329
+ if (result?.ports) {
4330
+ for (const port of result.ports) {
4331
+ listeningPorts.add(port);
4332
+ if (!routingConfig.listeningPorts.includes(port)) routingConfig.listeningPorts.push(port);
4333
+ }
4334
+ bootLog.debug("Synced listening ports from leader:", result.ports);
4335
+ }
4336
+ } catch {
4337
+ bootLog.debug("Could not sync listening ports from leader");
4338
+ }
4339
+ }
4340
+ const serializeTree = (tree) => {
4341
+ const result = {};
4342
+ for (const [name, node] of Object.entries(tree)) if ("file" in node) {
4343
+ const contents = node.file.contents;
4344
+ result[name] = { file: { contents: typeof contents === "string" ? contents : Array.from(contents) } };
4345
+ } else if ("directory" in node) result[name] = { directory: serializeTree(node.directory) };
4346
+ return result;
4347
+ };
4348
+ return {
4349
+ get isLeader() {
4350
+ return broker.isLeader;
4351
+ },
4352
+ async mount(tree, mountPoint = "/") {
4353
+ await send({
4354
+ type: "syscall",
4355
+ id: nextId++,
4356
+ op: "mount",
4357
+ args: {
4358
+ tree: serializeTree(tree),
4359
+ mountPoint
4360
+ }
4361
+ });
4362
+ },
4363
+ async readFile(path) {
4364
+ return (await send({
4365
+ type: "syscall",
4366
+ id: nextId++,
4367
+ op: "fs_read_file",
4368
+ args: { path }
4369
+ })).content;
4370
+ },
4371
+ async writeFile(path, content) {
4372
+ await send({
4373
+ type: "syscall",
4374
+ id: nextId++,
4375
+ op: "fs_write_file",
4376
+ args: {
4377
+ path,
4378
+ content
4379
+ }
4380
+ });
4381
+ },
4382
+ spawn(command, args = [], options = {}) {
4383
+ let stdoutController;
4384
+ let stderrController;
4385
+ let stdoutClosed = false;
4386
+ let stderrClosed = false;
4387
+ const stdoutStream = new ReadableStream({ start(controller) {
4388
+ stdoutController = controller;
4389
+ } });
4390
+ const stderrStream = new ReadableStream({ start(controller) {
4391
+ stderrController = controller;
4392
+ } });
4393
+ const closeStdout = () => {
4394
+ if (!stdoutClosed) {
4395
+ stdoutClosed = true;
4396
+ try {
4397
+ stdoutController.close();
4398
+ } catch {}
4399
+ }
4400
+ };
4401
+ const closeStderr = () => {
4402
+ if (!stderrClosed) {
4403
+ stderrClosed = true;
4404
+ try {
4405
+ stderrController.close();
4406
+ } catch {}
4407
+ }
4408
+ };
4409
+ const { promise: exit, resolve: resolveExit } = Promise.withResolvers();
4410
+ const { promise: pidPromise, resolve: resolvePid } = Promise.withResolvers();
4411
+ let exitResolved = false;
4412
+ let pid;
4413
+ send({
4414
+ type: "syscall",
4415
+ id: nextId++,
4416
+ op: "spawn",
4417
+ args: {
4418
+ command,
4419
+ args,
4420
+ options: {
4421
+ cwd: options.cwd,
4422
+ env: options.env
4423
+ }
4424
+ }
4425
+ }).then((result) => {
4426
+ pid = result.pid;
4427
+ resolvePid(pid);
4428
+ processOutputControllers.set(pid, {
4429
+ stdout: stdoutController,
4430
+ stderr: stderrController
4431
+ });
4432
+ const p = pendingOutput.get(pid);
4433
+ if (p) {
4434
+ for (const d of p.stdout) stdoutController.enqueue(d);
4435
+ for (const d of p.stderr) stderrController.enqueue(d);
4436
+ pendingOutput.delete(pid);
4437
+ }
4438
+ const pendingExit = pendingExits.get(pid);
4439
+ if (pendingExit !== void 0) {
4440
+ pendingExits.delete(pid);
4441
+ closeStdout();
4442
+ closeStderr();
4443
+ if (!exitResolved) {
4444
+ exitResolved = true;
4445
+ resolveExit(pendingExit);
4446
+ }
4447
+ } else processExitResolvers.set(pid, (code) => {
4448
+ closeStdout();
4449
+ closeStderr();
4450
+ if (!exitResolved) {
4451
+ exitResolved = true;
4452
+ resolveExit(code);
4453
+ }
4454
+ });
4455
+ }).catch((err) => {
4456
+ closeStdout();
4457
+ closeStderr();
4458
+ if (!exitResolved) {
4459
+ exitResolved = true;
4460
+ resolveExit(1);
4461
+ }
4462
+ resolvePid(-1);
4463
+ bootLog.error("Spawn failed:", err);
4464
+ });
4465
+ return {
4466
+ pid: pidPromise,
4467
+ stdout: stdoutStream,
4468
+ stderr: stderrStream,
4469
+ exit,
4470
+ kill: () => {
4471
+ if (pid !== void 0) send({
4472
+ type: "syscall",
4473
+ id: nextId++,
4474
+ op: "proc_kill",
4475
+ args: {
4476
+ pid,
4477
+ signal: "SIGTERM"
4478
+ }
4479
+ });
4480
+ }
4481
+ };
4482
+ },
4483
+ waitForPort(port, timeout = 3e4) {
4484
+ if (listeningPorts.has(port)) return Promise.resolve();
4485
+ return new Promise((resolve, reject) => {
4486
+ const timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Timeout waiting for port ${port}`)), timeout);
4487
+ if (!portListeners.has(port)) portListeners.set(port, []);
4488
+ portListeners.get(port).push(() => {
4489
+ clearTimeout(timer);
4490
+ resolve();
4491
+ });
4492
+ });
4493
+ },
4494
+ isListening(port) {
4495
+ return listeningPorts.has(port);
4496
+ },
4497
+ getListeningPorts() {
4498
+ return Array.from(listeningPorts);
4499
+ },
4500
+ async persist() {
4501
+ await send({
4502
+ type: "flush",
4503
+ id: nextId++
4504
+ });
4505
+ },
4506
+ async mountStore(storeName) {
4507
+ await send({
4508
+ type: "mount_store",
4509
+ id: nextId++,
4510
+ storeName
4511
+ });
4512
+ },
4513
+ async listStores() {
4514
+ return (await send({
4515
+ type: "list_stores",
4516
+ id: nextId++
4517
+ })).stores;
4518
+ },
4519
+ async deleteStore(storeName) {
4520
+ await send({
4521
+ type: "delete_store",
4522
+ id: nextId++,
4523
+ storeName
4524
+ });
4525
+ },
4526
+ async terminate() {
4527
+ networkChannel.close();
4528
+ await send({
4529
+ type: "shutdown",
4530
+ id: nextId++
4531
+ }).catch(() => {});
4532
+ broker.stop();
4533
+ },
4534
+ async listProcesses(options) {
4535
+ return (await send({
4536
+ type: "syscall",
4537
+ id: nextId++,
4538
+ op: "proc_list",
4539
+ args: { include_exited: options?.includeExited ?? false }
4540
+ })).processes;
4541
+ },
4542
+ on(event, callback) {
4543
+ if (event === "leadership") leadershipListeners.push(callback);
4544
+ },
4545
+ WebSocket: Object.assign(function(url, protocols) {
4546
+ const wsId = nextWsId++;
4547
+ const ws = new ProxyWebSocket(url, protocols, wsId, send, () => nextId++);
4548
+ activeWebSockets.set(wsId, ws);
4549
+ return ws;
4550
+ }, {
4551
+ CONNECTING: WS_CONNECTING,
4552
+ OPEN: WS_OPEN,
4553
+ CLOSING: WS_CLOSING,
4554
+ CLOSED: WS_CLOSED
4555
+ })
4556
+ };
4557
+ }
4558
+ /**
4559
+ * Handle a fetch request forwarded from the Service Worker.
4560
+ * Uses the broker to send the request to the worker (via leader tab if not leader).
4561
+ */
4562
+ async function handleFetchFromSWViaBroker(msg, writer, pending, id) {
4563
+ const result = await new Promise((resolve, reject) => {
4564
+ pending.set(id, {
4565
+ resolve,
4566
+ reject
4567
+ });
4568
+ writer.write({
4569
+ type: "http_fetch",
4570
+ id,
4571
+ url: msg.url,
4572
+ method: msg.method,
4573
+ headers: msg.headers,
4574
+ body: msg.body
4575
+ }).catch(reject);
4576
+ });
4577
+ return {
4578
+ type: "fetch_response",
4579
+ requestId: msg.requestId,
4580
+ status: result.status,
4581
+ statusText: result.status === 200 ? "OK" : "Error",
4582
+ headers: result.headers,
4583
+ body: result.body
4584
+ };
4585
+ }
4586
+
4587
+ //#endregion
4588
+ export { bootSubstrate, setLogComponents, setLogLevel };
4589
+ //# sourceMappingURL=index.js.map