@cloudflare/sandbox 0.13.0-next.681.1 → 0.13.0-next.709.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.
- package/Dockerfile +6 -6
- package/README.md +49 -3
- package/dist/bridge/index.d.ts.map +1 -1
- package/dist/bridge/index.js +1364 -1072
- package/dist/bridge/index.js.map +1 -1
- package/dist/{contexts-DY1LHU1v.d.ts → contexts-1EsLHByO.d.ts} +156 -20
- package/dist/contexts-1EsLHByO.d.ts.map +1 -0
- package/dist/{dist-BStBkGIC.js → dist-Duor5GbS.js} +7 -56
- package/dist/dist-Duor5GbS.js.map +1 -0
- package/dist/errors/index.d.ts +4 -4
- package/dist/errors/index.js +3 -3
- package/dist/{errors-k3B8orjH.js → errors-CXR0xBpw.js} +42 -10
- package/dist/errors-CXR0xBpw.js.map +1 -0
- package/dist/{errors-ewgSNicb.js → errors-QYlSkVGz.js} +402 -250
- package/dist/errors-QYlSkVGz.js.map +1 -0
- package/dist/extensions/index.d.ts +4 -2
- package/dist/extensions/index.js +5 -3
- package/dist/extensions-CFB2xHqY.js +1023 -0
- package/dist/extensions-CFB2xHqY.js.map +1 -0
- package/dist/filesystem-BWAZCZER.d.ts +732 -0
- package/dist/filesystem-BWAZCZER.d.ts.map +1 -0
- package/dist/git/index.d.ts +8 -19
- package/dist/git/index.d.ts.map +1 -1
- package/dist/git/index.js +16 -23
- package/dist/git/index.js.map +1 -1
- package/dist/index-Bs4bqXDR.d.ts +438 -0
- package/dist/index-Bs4bqXDR.d.ts.map +1 -0
- package/dist/{index-Dy6u9r60.d.ts → index-HNYBk-az.d.ts} +233 -179
- package/dist/index-HNYBk-az.d.ts.map +1 -0
- package/dist/index.d.ts +480 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -6
- package/dist/interpreter/index.d.ts +3 -1
- package/dist/interpreter/index.d.ts.map +1 -1
- package/dist/interpreter/index.js +46 -18
- package/dist/interpreter/index.js.map +1 -1
- package/dist/openai/index.d.ts +5 -5
- package/dist/openai/index.d.ts.map +1 -1
- package/dist/openai/index.js +11 -6
- package/dist/openai/index.js.map +1 -1
- package/dist/opencode/index.d.ts +7 -11
- package/dist/opencode/index.d.ts.map +1 -1
- package/dist/opencode/index.js +56 -85
- package/dist/opencode/index.js.map +1 -1
- package/dist/process-types-GStiZ8f8.d.ts +73 -0
- package/dist/process-types-GStiZ8f8.d.ts.map +1 -0
- package/dist/{sandbox-boKWPIcd.js → sandbox-Auuwfnur.js} +4152 -3359
- package/dist/sandbox-Auuwfnur.js.map +1 -0
- package/dist/sandbox-BbAabq93.d.ts +42 -0
- package/dist/sandbox-BbAabq93.d.ts.map +1 -0
- package/dist/xterm/index.d.ts +5 -1
- package/dist/xterm/index.d.ts.map +1 -1
- package/dist/xterm/index.js +55 -12
- package/dist/xterm/index.js.map +1 -1
- package/package.json +3 -2
- package/dist/codes-y-U76vnQ.d.ts +0 -79
- package/dist/codes-y-U76vnQ.d.ts.map +0 -1
- package/dist/contexts-DY1LHU1v.d.ts.map +0 -1
- package/dist/dist-BStBkGIC.js.map +0 -1
- package/dist/errors-ewgSNicb.js.map +0 -1
- package/dist/errors-k3B8orjH.js.map +0 -1
- package/dist/extensions-CepYdzro.js +0 -191
- package/dist/extensions-CepYdzro.js.map +0 -1
- package/dist/index-B7QgIs0N.d.ts +0 -1841
- package/dist/index-B7QgIs0N.d.ts.map +0 -1
- package/dist/index-Dy6u9r60.d.ts.map +0 -1
- package/dist/sandbox-DHNO89IF.d.ts +0 -828
- package/dist/sandbox-DHNO89IF.d.ts.map +0 -1
- package/dist/sandbox-boKWPIcd.js.map +0 -1
|
@@ -0,0 +1,1023 @@
|
|
|
1
|
+
import { i as ErrorCode, n as getSuggestion, r as getHttpStatus } from "./errors-CXR0xBpw.js";
|
|
2
|
+
import { d as ProcessExitedBeforeLogError, f as ProcessExitedBeforeReadyError, g as ProcessWaitTimeoutError, l as ProcessAbortedError, m as ProcessReadyTimeoutError, t as createErrorFromResponse, tt as SandboxError, u as ProcessError } from "./errors-QYlSkVGz.js";
|
|
3
|
+
import { n as EXTENSION_TARBALL_REQUIRED } from "./dist-Duor5GbS.js";
|
|
4
|
+
import { RpcTarget } from "cloudflare:workers";
|
|
5
|
+
|
|
6
|
+
//#region src/container-control/rpc-error.ts
|
|
7
|
+
/** Error translation for container control RPC calls. */
|
|
8
|
+
function isLocalSandboxError(error) {
|
|
9
|
+
if (!("errorResponse" in error)) return false;
|
|
10
|
+
const response = error.errorResponse;
|
|
11
|
+
return typeof response?.code === "string" && Object.hasOwn(ErrorCode, response.code) && typeof response.message === "string" && typeof response.httpStatus === "number" && typeof response.timestamp === "string" && typeof response.context === "object" && response.context !== null;
|
|
12
|
+
}
|
|
13
|
+
function translateRPCError(error, context = {}) {
|
|
14
|
+
if (error instanceof SandboxError) throw error;
|
|
15
|
+
if (error instanceof Error) {
|
|
16
|
+
if (isLocalSandboxError(error)) throw error;
|
|
17
|
+
const propagated = error;
|
|
18
|
+
if (typeof propagated.code === "string" && Object.hasOwn(ErrorCode, propagated.code)) {
|
|
19
|
+
const code = propagated.code;
|
|
20
|
+
const context$1 = propagated.details && typeof propagated.details === "object" ? propagated.details : {};
|
|
21
|
+
throw createErrorFromResponse({
|
|
22
|
+
code,
|
|
23
|
+
message: error.message,
|
|
24
|
+
context: context$1,
|
|
25
|
+
httpStatus: getHttpStatus(code),
|
|
26
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
let payload;
|
|
30
|
+
try {
|
|
31
|
+
payload = JSON.parse(error.message);
|
|
32
|
+
} catch {}
|
|
33
|
+
if (payload && typeof payload.code === "string" && typeof payload.message === "string") throw createErrorFromResponse({
|
|
34
|
+
code: payload.code,
|
|
35
|
+
message: payload.message,
|
|
36
|
+
context: payload.context ?? {},
|
|
37
|
+
httpStatus: getHttpStatus(payload.code),
|
|
38
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
39
|
+
});
|
|
40
|
+
const transportResponse = buildTransportErrorResponse(error);
|
|
41
|
+
throw createErrorFromResponse((context.translateTransportErrorsAsInterruptions === false ? null : buildInterruptedOperationResponse(transportResponse, context)) ?? transportResponse, { cause: error });
|
|
42
|
+
}
|
|
43
|
+
throw createErrorFromResponse(buildTransportErrorResponse(new Error(String(error))), { cause: error });
|
|
44
|
+
}
|
|
45
|
+
function buildTransportErrorResponse(error) {
|
|
46
|
+
const message = error.message;
|
|
47
|
+
const errorName = error.name;
|
|
48
|
+
let kind = "unknown";
|
|
49
|
+
let closeCode;
|
|
50
|
+
let closeReason;
|
|
51
|
+
if (errorName === "TypeError") kind = "invalid_frame";
|
|
52
|
+
else if (errorName === "SyntaxError") kind = "protocol_error";
|
|
53
|
+
else {
|
|
54
|
+
const peerCloseMatch = message.match(/^Peer closed WebSocket: (\d+) ?(.*)$/);
|
|
55
|
+
if (peerCloseMatch) {
|
|
56
|
+
kind = "peer_closed";
|
|
57
|
+
closeCode = Number(peerCloseMatch[1]);
|
|
58
|
+
closeReason = peerCloseMatch[2] || void 0;
|
|
59
|
+
} else if (message === "WebSocket connection failed.") kind = "connection_failed";
|
|
60
|
+
else if (message.startsWith("WebSocket upgrade failed")) kind = "upgrade_failed";
|
|
61
|
+
else if (message === "No WebSocket in upgrade response") kind = "upgrade_failed";
|
|
62
|
+
else if (message === "RPC session was shut down by disposing the main stub" || message === "RPC was canceled because the RpcPromise was disposed.") kind = "session_disposed";
|
|
63
|
+
}
|
|
64
|
+
const context = {
|
|
65
|
+
kind,
|
|
66
|
+
originalMessage: message,
|
|
67
|
+
errorName,
|
|
68
|
+
...closeCode !== void 0 ? { closeCode } : {},
|
|
69
|
+
...closeReason !== void 0 ? { closeReason } : {}
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
code: ErrorCode.RPC_TRANSPORT_ERROR,
|
|
73
|
+
message,
|
|
74
|
+
context,
|
|
75
|
+
httpStatus: getHttpStatus(ErrorCode.RPC_TRANSPORT_ERROR),
|
|
76
|
+
suggestion: getSuggestion(ErrorCode.RPC_TRANSPORT_ERROR, context),
|
|
77
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
function buildInterruptedOperationResponse(transportResponse, context) {
|
|
81
|
+
if (!context.operation) return null;
|
|
82
|
+
const { kind } = transportResponse.context;
|
|
83
|
+
if (kind !== "session_disposed" && kind !== "peer_closed" && kind !== "connection_failed") return null;
|
|
84
|
+
const interruptedContext = {
|
|
85
|
+
reason: kind === "session_disposed" ? "transport_disposed" : "runtime_replaced",
|
|
86
|
+
operation: context.operation,
|
|
87
|
+
admitted: "unknown",
|
|
88
|
+
retryable: false
|
|
89
|
+
};
|
|
90
|
+
const action = kind === "session_disposed" ? "was closing" : "closed unexpectedly";
|
|
91
|
+
return {
|
|
92
|
+
code: ErrorCode.OPERATION_INTERRUPTED,
|
|
93
|
+
message: `Sandbox operation ${context.operation} was interrupted while the runtime connection ${action}`,
|
|
94
|
+
context: interruptedContext,
|
|
95
|
+
httpStatus: getHttpStatus(ErrorCode.OPERATION_INTERRUPTED),
|
|
96
|
+
suggestion: getSuggestion(ErrorCode.OPERATION_INTERRUPTED, interruptedContext),
|
|
97
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
//#endregion
|
|
102
|
+
//#region src/processes/remote-subscription.ts
|
|
103
|
+
/** Keeps a stream local to its Durable Object and exposes pull RPC methods. */
|
|
104
|
+
var PullSubscriptionTarget = class extends RpcTarget {
|
|
105
|
+
#reader;
|
|
106
|
+
#onRelease;
|
|
107
|
+
#released = false;
|
|
108
|
+
constructor(stream, onRelease) {
|
|
109
|
+
super();
|
|
110
|
+
this.#reader = stream.getReader();
|
|
111
|
+
this.#onRelease = onRelease;
|
|
112
|
+
}
|
|
113
|
+
async next() {
|
|
114
|
+
if (this.#released) return {
|
|
115
|
+
done: true,
|
|
116
|
+
value: void 0
|
|
117
|
+
};
|
|
118
|
+
try {
|
|
119
|
+
const result = await this.#reader.read();
|
|
120
|
+
if (result.done) this.#release();
|
|
121
|
+
return result;
|
|
122
|
+
} catch (error) {
|
|
123
|
+
this.#release();
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async cancel() {
|
|
128
|
+
if (this.#released) return;
|
|
129
|
+
try {
|
|
130
|
+
await this.#reader.cancel();
|
|
131
|
+
} finally {
|
|
132
|
+
this.#release();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
[Symbol.dispose]() {
|
|
136
|
+
if (this.#released) return;
|
|
137
|
+
this.#reader.cancel().catch(() => void 0);
|
|
138
|
+
this.#release();
|
|
139
|
+
}
|
|
140
|
+
#release() {
|
|
141
|
+
if (this.#released) return;
|
|
142
|
+
this.#released = true;
|
|
143
|
+
this.#onRelease?.();
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
/** Exposes a remote Workers RPC subscription as a caller-owned local stream. */
|
|
147
|
+
async function openRemoteSubscription(subscriptionPromise, options) {
|
|
148
|
+
let subscription;
|
|
149
|
+
let releaseRequested = false;
|
|
150
|
+
let cleanupStarted = false;
|
|
151
|
+
const release = () => {
|
|
152
|
+
releaseRequested = true;
|
|
153
|
+
if (cleanupStarted || subscription === void 0) return;
|
|
154
|
+
cleanupStarted = true;
|
|
155
|
+
try {
|
|
156
|
+
subscription.cancel().catch(() => void 0);
|
|
157
|
+
} catch {}
|
|
158
|
+
try {
|
|
159
|
+
subscription[Symbol.dispose]();
|
|
160
|
+
} catch {}
|
|
161
|
+
};
|
|
162
|
+
const signal = options.signal;
|
|
163
|
+
const aborted = () => options.abortError?.() ?? (signal?.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("Operation aborted"));
|
|
164
|
+
const raceSetup = async (setup) => {
|
|
165
|
+
if (signal === void 0) return setup;
|
|
166
|
+
if (signal.aborted) {
|
|
167
|
+
release();
|
|
168
|
+
throw aborted();
|
|
169
|
+
}
|
|
170
|
+
let onAbort$1;
|
|
171
|
+
const abort = new Promise((_, reject) => {
|
|
172
|
+
onAbort$1 = () => {
|
|
173
|
+
release();
|
|
174
|
+
reject(aborted());
|
|
175
|
+
};
|
|
176
|
+
signal.addEventListener("abort", onAbort$1, { once: true });
|
|
177
|
+
});
|
|
178
|
+
try {
|
|
179
|
+
return await Promise.race([setup, abort]);
|
|
180
|
+
} finally {
|
|
181
|
+
if (onAbort$1 !== void 0) signal.removeEventListener("abort", onAbort$1);
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
try {
|
|
185
|
+
subscription = await raceSetup(subscriptionPromise.then((value) => {
|
|
186
|
+
subscription = value;
|
|
187
|
+
if (releaseRequested) release();
|
|
188
|
+
return value;
|
|
189
|
+
}));
|
|
190
|
+
} catch (error) {
|
|
191
|
+
if (signal?.aborted) throw error;
|
|
192
|
+
translateRPCError(error, { operation: options.operation ?? "open process subscription" });
|
|
193
|
+
}
|
|
194
|
+
if (subscription === void 0) throw new Error("Process subscription acquisition did not complete");
|
|
195
|
+
let read;
|
|
196
|
+
let cancelReader;
|
|
197
|
+
if (options.protocol === "pull") {
|
|
198
|
+
const pullSubscription = subscription;
|
|
199
|
+
read = () => pullSubscription.next();
|
|
200
|
+
cancelReader = () => void 0;
|
|
201
|
+
} else {
|
|
202
|
+
const streamSubscription = subscription;
|
|
203
|
+
let source;
|
|
204
|
+
try {
|
|
205
|
+
source = await raceSetup(streamSubscription.stream());
|
|
206
|
+
} catch (error) {
|
|
207
|
+
release();
|
|
208
|
+
if (signal?.aborted) throw error;
|
|
209
|
+
translateRPCError(error, { operation: options.operation ?? "open process subscription" });
|
|
210
|
+
}
|
|
211
|
+
let reader;
|
|
212
|
+
try {
|
|
213
|
+
reader = source.getReader();
|
|
214
|
+
} catch (error) {
|
|
215
|
+
release();
|
|
216
|
+
translateRPCError(error, { operation: options.operation ?? "read process subscription" });
|
|
217
|
+
}
|
|
218
|
+
read = () => reader.read();
|
|
219
|
+
cancelReader = () => {
|
|
220
|
+
try {
|
|
221
|
+
reader.cancel().catch(() => void 0);
|
|
222
|
+
} catch {}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
let stopped = false;
|
|
226
|
+
let controller;
|
|
227
|
+
const stop = (error) => {
|
|
228
|
+
if (stopped) return;
|
|
229
|
+
stopped = true;
|
|
230
|
+
signal?.removeEventListener("abort", onAbort);
|
|
231
|
+
cancelReader();
|
|
232
|
+
release();
|
|
233
|
+
if (error !== void 0) controller?.error(error);
|
|
234
|
+
};
|
|
235
|
+
const onAbort = () => stop(aborted());
|
|
236
|
+
return new ReadableStream({
|
|
237
|
+
start(localController) {
|
|
238
|
+
controller = localController;
|
|
239
|
+
if (signal?.aborted) onAbort();
|
|
240
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
241
|
+
},
|
|
242
|
+
async pull(localController) {
|
|
243
|
+
if (stopped) return;
|
|
244
|
+
try {
|
|
245
|
+
const result = await read();
|
|
246
|
+
if (stopped) return;
|
|
247
|
+
if (result.done) {
|
|
248
|
+
stopped = true;
|
|
249
|
+
signal?.removeEventListener("abort", onAbort);
|
|
250
|
+
release();
|
|
251
|
+
localController.close();
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
localController.enqueue(result.value);
|
|
255
|
+
} catch (error) {
|
|
256
|
+
stop();
|
|
257
|
+
translateRPCError(error, { operation: options.operation ?? "consume process subscription" });
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
cancel() {
|
|
261
|
+
stop();
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
//#endregion
|
|
267
|
+
//#region src/processes/process-waits.ts
|
|
268
|
+
async function withLocalWait(work, options) {
|
|
269
|
+
const { signal, timeout } = options;
|
|
270
|
+
const settlement = new AbortController();
|
|
271
|
+
let timer;
|
|
272
|
+
let abortListener;
|
|
273
|
+
const competitors = [work(settlement.signal)];
|
|
274
|
+
if (timeout !== void 0) competitors.push(new Promise((_, reject) => {
|
|
275
|
+
timer = setTimeout(() => reject(timeoutError(options, timeout)), timeout);
|
|
276
|
+
}));
|
|
277
|
+
if (signal !== void 0) competitors.push(new Promise((_, reject) => {
|
|
278
|
+
const abort = () => reject(abortError(options.processId, options.operation, signal));
|
|
279
|
+
if (signal.aborted) abort();
|
|
280
|
+
else {
|
|
281
|
+
abortListener = abort;
|
|
282
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
283
|
+
}
|
|
284
|
+
}));
|
|
285
|
+
try {
|
|
286
|
+
return await Promise.race(competitors);
|
|
287
|
+
} finally {
|
|
288
|
+
settlement.abort();
|
|
289
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
290
|
+
if (abortListener !== void 0) signal?.removeEventListener("abort", abortListener);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
function processFailure(processId, pid, failure) {
|
|
294
|
+
return new ProcessError({
|
|
295
|
+
code: ErrorCode.PROCESS_ERROR,
|
|
296
|
+
message: failure.message,
|
|
297
|
+
context: {
|
|
298
|
+
processId,
|
|
299
|
+
pid
|
|
300
|
+
},
|
|
301
|
+
httpStatus: 500,
|
|
302
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
function streamClosed(message) {
|
|
306
|
+
translateRPCError(new Error(message), {
|
|
307
|
+
operation: "consume process subscription",
|
|
308
|
+
translateTransportErrorsAsInterruptions: false
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
function timeoutError(options, timeout) {
|
|
312
|
+
if (options.operation === "waitForPort") {
|
|
313
|
+
const condition = `port ${options.port ?? "unknown"}`;
|
|
314
|
+
return new ProcessReadyTimeoutError({
|
|
315
|
+
code: ErrorCode.PROCESS_READY_TIMEOUT,
|
|
316
|
+
message: `Process did not become ready within ${timeout}ms. Waiting for: ${condition}`,
|
|
317
|
+
context: {
|
|
318
|
+
processId: options.processId,
|
|
319
|
+
command: options.processId,
|
|
320
|
+
condition,
|
|
321
|
+
timeout
|
|
322
|
+
},
|
|
323
|
+
httpStatus: 408,
|
|
324
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
const operation = options.operation === "logs" ? "waitForLog" : options.operation;
|
|
328
|
+
return new ProcessWaitTimeoutError({
|
|
329
|
+
code: ErrorCode.PROCESS_WAIT_TIMEOUT,
|
|
330
|
+
message: `Process ${operation} did not complete within ${timeout}ms`,
|
|
331
|
+
context: {
|
|
332
|
+
processId: options.processId,
|
|
333
|
+
operation,
|
|
334
|
+
timeout
|
|
335
|
+
},
|
|
336
|
+
httpStatus: 408,
|
|
337
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
function abortError(processId, operation, signal) {
|
|
341
|
+
if (signal.reason instanceof Error && signal.reason.name !== "AbortError") return signal.reason;
|
|
342
|
+
return new ProcessAbortedError({
|
|
343
|
+
code: ErrorCode.PROCESS_ABORTED,
|
|
344
|
+
message: `Process ${operation} was aborted`,
|
|
345
|
+
context: {
|
|
346
|
+
processId,
|
|
347
|
+
operation
|
|
348
|
+
},
|
|
349
|
+
httpStatus: 499,
|
|
350
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
//#endregion
|
|
355
|
+
//#region src/processes/process-output.ts
|
|
356
|
+
async function readProcessOutput(reader, options) {
|
|
357
|
+
const maxBytes = validateMaxBytes(options.maxBytes);
|
|
358
|
+
const stdout = [];
|
|
359
|
+
const stderr = [];
|
|
360
|
+
let stdoutBytes = 0;
|
|
361
|
+
let stderrBytes = 0;
|
|
362
|
+
let retainedBytes = 0;
|
|
363
|
+
let truncated = false;
|
|
364
|
+
for (;;) {
|
|
365
|
+
const result = await reader.read();
|
|
366
|
+
if (result.done) streamClosed("Process log stream ended before exit");
|
|
367
|
+
const event = result.value;
|
|
368
|
+
if ("type" in event && event.type === "truncated") {
|
|
369
|
+
truncated = true;
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
if ("state" in event) {
|
|
373
|
+
if (event.state === "error") throw processFailure(options.processId, options.pid, event.error);
|
|
374
|
+
return {
|
|
375
|
+
stdout: concat(stdout, stdoutBytes),
|
|
376
|
+
stderr: concat(stderr, stderrBytes),
|
|
377
|
+
exitCode: event.exit.code,
|
|
378
|
+
signal: event.exit.signal,
|
|
379
|
+
timedOut: event.exit.timedOut,
|
|
380
|
+
truncated
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
const remaining = maxBytes === void 0 ? event.data.byteLength : Math.max(0, maxBytes - retainedBytes);
|
|
384
|
+
const retainedLength = Math.min(remaining, event.data.byteLength);
|
|
385
|
+
if (retainedLength < event.data.byteLength) truncated = true;
|
|
386
|
+
if (retainedLength === 0) continue;
|
|
387
|
+
const chunk = retainedLength === event.data.byteLength ? event.data : event.data.slice(0, retainedLength);
|
|
388
|
+
if (event.type === "stdout") {
|
|
389
|
+
stdout.push(chunk);
|
|
390
|
+
stdoutBytes += chunk.byteLength;
|
|
391
|
+
} else {
|
|
392
|
+
stderr.push(chunk);
|
|
393
|
+
stderrBytes += chunk.byteLength;
|
|
394
|
+
}
|
|
395
|
+
retainedBytes += chunk.byteLength;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
function validateMaxBytes(maxBytes) {
|
|
399
|
+
if (maxBytes === void 0) return void 0;
|
|
400
|
+
if (!Number.isFinite(maxBytes) || maxBytes < 0) throw new Error("maxBytes must be a non-negative finite number");
|
|
401
|
+
return maxBytes;
|
|
402
|
+
}
|
|
403
|
+
function concat(chunks, length) {
|
|
404
|
+
const out = new Uint8Array(length);
|
|
405
|
+
let offset = 0;
|
|
406
|
+
for (const chunk of chunks) {
|
|
407
|
+
out.set(chunk, offset);
|
|
408
|
+
offset += chunk.byteLength;
|
|
409
|
+
}
|
|
410
|
+
return out;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
//#endregion
|
|
414
|
+
//#region src/processes/process-readiness.ts
|
|
415
|
+
async function waitForReadiness(portReader, logReader, context) {
|
|
416
|
+
await Promise.race([consumePort(portReader), consumeTerminal(logReader, context)]);
|
|
417
|
+
}
|
|
418
|
+
async function consumePort(reader) {
|
|
419
|
+
for (;;) {
|
|
420
|
+
const result = await reader.read();
|
|
421
|
+
if (result.done) streamClosed("Port watch stream ended unexpectedly");
|
|
422
|
+
if (result.value.type === "ready") return;
|
|
423
|
+
if (result.value.type === "error") throw new Error(result.value.error || "Port watch failed");
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
async function consumeTerminal(reader, context) {
|
|
427
|
+
for (;;) {
|
|
428
|
+
const result = await reader.read();
|
|
429
|
+
if (result.done) streamClosed("Process log stream ended before exit");
|
|
430
|
+
const event = result.value;
|
|
431
|
+
if (!("state" in event)) continue;
|
|
432
|
+
if (event.state === "error") throw processFailure(context.processId, context.pid, event.error);
|
|
433
|
+
throw exitedBeforeReady(context.processId, context.port, event.exit.code);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
function exitedBeforeReady(processId, port, exitCode) {
|
|
437
|
+
return new ProcessExitedBeforeReadyError({
|
|
438
|
+
code: ErrorCode.PROCESS_EXITED_BEFORE_READY,
|
|
439
|
+
message: `Process exited with code ${exitCode} before becoming ready. Waiting for: port ${port}`,
|
|
440
|
+
context: {
|
|
441
|
+
processId,
|
|
442
|
+
command: processId,
|
|
443
|
+
condition: `port ${port}`,
|
|
444
|
+
exitCode
|
|
445
|
+
},
|
|
446
|
+
httpStatus: 500,
|
|
447
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
//#endregion
|
|
452
|
+
//#region src/processes/wait-for-log.ts
|
|
453
|
+
const MATCH_WINDOW = 64 * 1024;
|
|
454
|
+
async function readUntilLogMatch(reader, pattern, wanted, processId, pid) {
|
|
455
|
+
const decoders = {
|
|
456
|
+
stdout: new TextDecoder(),
|
|
457
|
+
stderr: new TextDecoder()
|
|
458
|
+
};
|
|
459
|
+
const windows = {
|
|
460
|
+
stdout: "",
|
|
461
|
+
stderr: ""
|
|
462
|
+
};
|
|
463
|
+
const cursors = {
|
|
464
|
+
stdout: "",
|
|
465
|
+
stderr: ""
|
|
466
|
+
};
|
|
467
|
+
const append = (stream, decoded, cursor) => {
|
|
468
|
+
const text = bounded(windows[stream] + decoded);
|
|
469
|
+
windows[stream] = text;
|
|
470
|
+
cursors[stream] = cursor;
|
|
471
|
+
const match = findMatch(text, pattern);
|
|
472
|
+
return match === void 0 ? void 0 : {
|
|
473
|
+
stream,
|
|
474
|
+
text,
|
|
475
|
+
match,
|
|
476
|
+
cursor
|
|
477
|
+
};
|
|
478
|
+
};
|
|
479
|
+
const flush = (cursor) => {
|
|
480
|
+
for (const stream of ["stdout", "stderr"]) {
|
|
481
|
+
if (wanted !== "both" && wanted !== stream) continue;
|
|
482
|
+
const result = append(stream, decoders[stream].decode(), cursors[stream] || cursor);
|
|
483
|
+
if (result !== void 0) return result;
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
for (;;) {
|
|
487
|
+
const result = await reader.read();
|
|
488
|
+
if (result.done) {
|
|
489
|
+
const match$1 = flush("");
|
|
490
|
+
if (match$1 !== void 0) return match$1;
|
|
491
|
+
streamClosed("Process log stream ended before a match was found");
|
|
492
|
+
}
|
|
493
|
+
const event = result.value;
|
|
494
|
+
if ("state" in event) {
|
|
495
|
+
const match$1 = flush(event.cursor);
|
|
496
|
+
if (match$1 !== void 0) return match$1;
|
|
497
|
+
if (event.state === "error") throw processFailure(processId, pid, event.error);
|
|
498
|
+
throw new ProcessExitedBeforeLogError({
|
|
499
|
+
code: ErrorCode.PROCESS_EXITED_BEFORE_LOG,
|
|
500
|
+
message: "Process exited before a log match was found",
|
|
501
|
+
context: {
|
|
502
|
+
processId,
|
|
503
|
+
pid,
|
|
504
|
+
exit: { ...event.exit }
|
|
505
|
+
},
|
|
506
|
+
httpStatus: 409,
|
|
507
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
if (event.type !== "stdout" && event.type !== "stderr") continue;
|
|
511
|
+
if (wanted !== "both" && wanted !== event.type) continue;
|
|
512
|
+
const match = append(event.type, decoders[event.type].decode(event.data, { stream: true }), event.cursor);
|
|
513
|
+
if (match !== void 0) return match;
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
function bounded(text) {
|
|
517
|
+
return text.length <= MATCH_WINDOW ? text : text.slice(-MATCH_WINDOW);
|
|
518
|
+
}
|
|
519
|
+
function findMatch(text, pattern) {
|
|
520
|
+
if (typeof pattern === "string") return text.includes(pattern) ? pattern : void 0;
|
|
521
|
+
pattern.lastIndex = 0;
|
|
522
|
+
const match = pattern.exec(text)?.[0];
|
|
523
|
+
pattern.lastIndex = 0;
|
|
524
|
+
return match;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
//#endregion
|
|
528
|
+
//#region src/processes/sandbox-process.ts
|
|
529
|
+
var SandboxProcessImpl = class {
|
|
530
|
+
#exitCodePromise;
|
|
531
|
+
constructor(id, pid, capability) {
|
|
532
|
+
this.id = id;
|
|
533
|
+
this.pid = pid;
|
|
534
|
+
this.capability = capability;
|
|
535
|
+
}
|
|
536
|
+
get exitCode() {
|
|
537
|
+
this.#exitCodePromise ??= this.waitForExit().then((exit) => exit.code);
|
|
538
|
+
return this.#exitCodePromise;
|
|
539
|
+
}
|
|
540
|
+
status() {
|
|
541
|
+
return this.capability.status();
|
|
542
|
+
}
|
|
543
|
+
async logs(options = {}) {
|
|
544
|
+
const { signal, ...rpcOptions } = options;
|
|
545
|
+
return openRemoteSubscription(this.capability.openLogs(rpcOptions), {
|
|
546
|
+
protocol: "pull",
|
|
547
|
+
signal,
|
|
548
|
+
operation: "read process logs",
|
|
549
|
+
abortError: signal === void 0 ? void 0 : () => abortError(this.id, "logs", signal)
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
async output(options = {}) {
|
|
553
|
+
const maxBytes = validateMaxBytes(options.maxBytes);
|
|
554
|
+
const bytes = await withLocalWait((settlementSignal) => this.consumeLogs(settlementSignal, (reader) => readProcessOutput(reader, {
|
|
555
|
+
maxBytes,
|
|
556
|
+
processId: this.id,
|
|
557
|
+
pid: this.pid
|
|
558
|
+
})), {
|
|
559
|
+
processId: this.id,
|
|
560
|
+
operation: "output",
|
|
561
|
+
timeout: options.timeout,
|
|
562
|
+
signal: options.signal
|
|
563
|
+
});
|
|
564
|
+
if ("encoding" in options && options.encoding === "utf8") return {
|
|
565
|
+
...bytes,
|
|
566
|
+
stdout: new TextDecoder().decode(bytes.stdout),
|
|
567
|
+
stderr: new TextDecoder().decode(bytes.stderr)
|
|
568
|
+
};
|
|
569
|
+
return bytes;
|
|
570
|
+
}
|
|
571
|
+
async waitForExit(options = {}) {
|
|
572
|
+
return withLocalWait((settlementSignal) => this.consumeLogs(settlementSignal, (reader) => readTerminal(reader, this.id, this.pid)), {
|
|
573
|
+
processId: this.id,
|
|
574
|
+
operation: "waitForExit",
|
|
575
|
+
timeout: options.timeout,
|
|
576
|
+
signal: options.signal
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
async waitForLog(pattern, options = {}) {
|
|
580
|
+
return withLocalWait((settlementSignal) => this.consumeLogs(settlementSignal, (reader) => readUntilLogMatch(reader, pattern, options.stream ?? "both", this.id, this.pid)), {
|
|
581
|
+
processId: this.id,
|
|
582
|
+
operation: "waitForLog",
|
|
583
|
+
timeout: options.timeout,
|
|
584
|
+
signal: options.signal
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
async waitForPort(port, options = {}) {
|
|
588
|
+
const { timeout, signal, ...rpcOptions } = options;
|
|
589
|
+
return withLocalWait((settlementSignal) => this.waitForPortSubscriptions(port, rpcOptions, settlementSignal), {
|
|
590
|
+
processId: this.id,
|
|
591
|
+
operation: "waitForPort",
|
|
592
|
+
timeout,
|
|
593
|
+
signal,
|
|
594
|
+
port
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
async waitForPortSubscriptions(port, options, settlementSignal) {
|
|
598
|
+
const portStream = await openRemoteSubscription(this.capability.openPortWatch(port, options), {
|
|
599
|
+
operation: `watch port ${port}`,
|
|
600
|
+
protocol: "pull",
|
|
601
|
+
signal: settlementSignal
|
|
602
|
+
});
|
|
603
|
+
let logStream;
|
|
604
|
+
let portReader;
|
|
605
|
+
let logReader;
|
|
606
|
+
try {
|
|
607
|
+
portReader = portStream.getReader();
|
|
608
|
+
logStream = await openRemoteSubscription(this.capability.openLogs({
|
|
609
|
+
replay: true,
|
|
610
|
+
follow: true
|
|
611
|
+
}), {
|
|
612
|
+
operation: "read process logs",
|
|
613
|
+
protocol: "pull",
|
|
614
|
+
signal: settlementSignal
|
|
615
|
+
});
|
|
616
|
+
logReader = logStream.getReader();
|
|
617
|
+
await waitForReadiness(portReader, logReader, {
|
|
618
|
+
processId: this.id,
|
|
619
|
+
pid: this.pid,
|
|
620
|
+
port
|
|
621
|
+
});
|
|
622
|
+
} finally {
|
|
623
|
+
await cancelOwned(portReader, portStream);
|
|
624
|
+
if (logStream !== void 0) await cancelOwned(logReader, logStream);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
kill(signal = 15) {
|
|
628
|
+
return this.capability.kill(signal);
|
|
629
|
+
}
|
|
630
|
+
async consumeLogs(signal, consume) {
|
|
631
|
+
const stream = await openRemoteSubscription(this.capability.openLogs({
|
|
632
|
+
replay: true,
|
|
633
|
+
follow: true
|
|
634
|
+
}), {
|
|
635
|
+
signal,
|
|
636
|
+
operation: "read process logs",
|
|
637
|
+
protocol: "pull"
|
|
638
|
+
});
|
|
639
|
+
return this.consume(stream, consume);
|
|
640
|
+
}
|
|
641
|
+
async consume(stream, consume) {
|
|
642
|
+
let reader;
|
|
643
|
+
try {
|
|
644
|
+
reader = stream.getReader();
|
|
645
|
+
return await consume(reader);
|
|
646
|
+
} finally {
|
|
647
|
+
await cancelOwned(reader, stream);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
function createSandboxProcess(descriptor) {
|
|
652
|
+
return new SandboxProcessImpl(descriptor.id, descriptor.pid, descriptor.capability);
|
|
653
|
+
}
|
|
654
|
+
async function readTerminal(reader, processId, pid) {
|
|
655
|
+
for (;;) {
|
|
656
|
+
const result = await reader.read();
|
|
657
|
+
if (result.done) streamClosed("Process log stream ended before exit");
|
|
658
|
+
if ("state" in result.value) {
|
|
659
|
+
if (result.value.state === "exited") return result.value.exit;
|
|
660
|
+
throw processFailure(processId, pid, result.value.error);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
async function cancelOwned(reader, stream) {
|
|
665
|
+
try {
|
|
666
|
+
if (reader !== void 0) await reader.cancel();
|
|
667
|
+
else await stream.cancel();
|
|
668
|
+
} catch {}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
//#endregion
|
|
672
|
+
//#region src/extensions/index.ts
|
|
673
|
+
/**
|
|
674
|
+
* Unified extension surface for the Cloudflare Sandbox SDK.
|
|
675
|
+
*
|
|
676
|
+
* Every extension \u2014 whether it just drives existing control sub-APIs or
|
|
677
|
+
* ships its own container sidecar \u2014 shares one shape: a class extending
|
|
678
|
+
* {@link SandboxExtension}, captured lazily via a `withX(this)` factory.
|
|
679
|
+
*
|
|
680
|
+
* - No sidecar? Extend {@link SandboxExtension} and use `this.exec()` or
|
|
681
|
+
* `this.withRuntime()` for scoped control APIs. Don't pass a package.
|
|
682
|
+
* - Need a container sidecar? Pass an {@link ExtensionPackage} to `super()`.
|
|
683
|
+
* Then use {@link SandboxExtension.withSidecar} with the sidecar's typed
|
|
684
|
+
* capnweb remote main. Calls on that stub stream through capnweb \u2014 callback
|
|
685
|
+
* parameters round-trip across both the DO\u2192container and container\u2192sidecar
|
|
686
|
+
* hops.
|
|
687
|
+
*
|
|
688
|
+
* `ExtensionPackage` carries tarball bytes produced by an extension build.
|
|
689
|
+
* The SDK sends those bytes only when the container has not provisioned the
|
|
690
|
+
* package hash yet.
|
|
691
|
+
*/
|
|
692
|
+
const sandboxRuntimeCall = Symbol("sandboxRuntimeCall");
|
|
693
|
+
function isProcessRPCDescriptor(process) {
|
|
694
|
+
return "capability" in process;
|
|
695
|
+
}
|
|
696
|
+
/** Normalize local RPC descriptors and caller-side handles for extensions. */
|
|
697
|
+
function createExtensionProcessSandbox(sandbox) {
|
|
698
|
+
return {
|
|
699
|
+
async exec(command, options) {
|
|
700
|
+
if (!sandbox.exec) throw new Error("Sandbox extension requires the exec surface from the owning Sandbox");
|
|
701
|
+
const process = await sandbox.exec.call(sandbox, command, options);
|
|
702
|
+
return isProcessRPCDescriptor(process) ? createSandboxProcess(process) : process;
|
|
703
|
+
},
|
|
704
|
+
async getProcess(processId) {
|
|
705
|
+
if (!sandbox.getProcess) throw new Error("Sandbox extension requires the getProcess surface from the owning Sandbox");
|
|
706
|
+
const process = await sandbox.getProcess.call(sandbox, processId);
|
|
707
|
+
if (!process) return null;
|
|
708
|
+
return isProcessRPCDescriptor(process) ? createSandboxProcess(process) : process;
|
|
709
|
+
},
|
|
710
|
+
listProcesses() {
|
|
711
|
+
if (!sandbox.listProcesses) throw new Error("Sandbox extension requires the listProcesses surface from the owning Sandbox");
|
|
712
|
+
return sandbox.listProcesses.call(sandbox);
|
|
713
|
+
}
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* The one base class for *every* extension.
|
|
718
|
+
*
|
|
719
|
+
* - SDK-only: just drives existing sub-APIs.
|
|
720
|
+
* - Sidecar: pass an {@link ExtensionPackage} to `super(sandbox, pkg)` and
|
|
721
|
+
* call `this.withSidecar<T>(operation, callback)` to use the typed capnweb stub inside one runtime callback.
|
|
722
|
+
*
|
|
723
|
+
* The sidecar helper throws a clear error if no package was supplied, so an
|
|
724
|
+
* extension only "becomes" a sidecar extension when it opts in.
|
|
725
|
+
*
|
|
726
|
+
* ```ts
|
|
727
|
+
* // SDK-only
|
|
728
|
+
* class GitStatus extends SandboxExtension {
|
|
729
|
+
* constructor(s: SandboxLike) { super(s); }
|
|
730
|
+
* async status() {
|
|
731
|
+
* const process = await this.exec(['git', 'status']);
|
|
732
|
+
* return process.output({ encoding: 'utf8' });
|
|
733
|
+
* }
|
|
734
|
+
* }
|
|
735
|
+
*
|
|
736
|
+
* // Sidecar
|
|
737
|
+
* import sidecarTarballBytes from './sidecar-package.tgz';
|
|
738
|
+
* import type { MyAPI } from './shared';
|
|
739
|
+
*
|
|
740
|
+
* class MyExt extends SandboxExtension {
|
|
741
|
+
* constructor(s: SandboxLike) { super(s, { tarball: new Uint8Array(sidecarTarballBytes) }); }
|
|
742
|
+
* async run(input: string): Promise<string> {
|
|
743
|
+
* return this.withSidecar<MyAPI, string>('my-ext.run', (api) =>
|
|
744
|
+
* api.run(input)
|
|
745
|
+
* );
|
|
746
|
+
* }
|
|
747
|
+
* }
|
|
748
|
+
* ```
|
|
749
|
+
*
|
|
750
|
+
* RPC-safety: the sandbox lives in `#sandbox` and runtime control is reached
|
|
751
|
+
* only through a symbol-keyed capability, so it is not exposed as a named RPC
|
|
752
|
+
* method. Only the public methods you add form the extension's RPC surface.
|
|
753
|
+
*/
|
|
754
|
+
var SandboxExtension = class extends RpcTarget {
|
|
755
|
+
#sandbox;
|
|
756
|
+
#pkg;
|
|
757
|
+
#hashPromise;
|
|
758
|
+
constructor(sandbox, pkg) {
|
|
759
|
+
super();
|
|
760
|
+
this.#sandbox = sandbox;
|
|
761
|
+
this.#pkg = pkg;
|
|
762
|
+
}
|
|
763
|
+
withRuntime(operation, call) {
|
|
764
|
+
const guardedCall = async (runtimeControl) => {
|
|
765
|
+
const { control, revoke } = scopedRuntimeControl(runtimeControl);
|
|
766
|
+
try {
|
|
767
|
+
const result = await call(control);
|
|
768
|
+
assertRuntimeControlDidNotEscape(result, control);
|
|
769
|
+
return result;
|
|
770
|
+
} finally {
|
|
771
|
+
revoke();
|
|
772
|
+
}
|
|
773
|
+
};
|
|
774
|
+
return this.#sandbox[sandboxRuntimeCall](operation, guardedCall);
|
|
775
|
+
}
|
|
776
|
+
/** Launch an argv process through the owning Sandbox. */
|
|
777
|
+
exec(command, options) {
|
|
778
|
+
return createExtensionProcessSandbox(this.#sandbox).exec(command, options);
|
|
779
|
+
}
|
|
780
|
+
/** Sandbox-level environment applied to extension-launched processes. */
|
|
781
|
+
get envVars() {
|
|
782
|
+
return this.#sandbox.envVars ?? {};
|
|
783
|
+
}
|
|
784
|
+
get httpAuthInterceptor() {
|
|
785
|
+
const register = this.#sandbox.registerGitAuthInterceptor;
|
|
786
|
+
return register ? (params) => register.call(this.#sandbox, params) : void 0;
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* Provision/connect to the sidecar and use its typed capnweb remote inside
|
|
790
|
+
* one runtime callback. The remote is invalid after `call` resolves or
|
|
791
|
+
* rejects, so extension code cannot silently reconnect or keep using an old
|
|
792
|
+
* runtime's sidecar.
|
|
793
|
+
*/
|
|
794
|
+
async withSidecar(operation, call) {
|
|
795
|
+
const pkg = this.#requirePackage();
|
|
796
|
+
const packageHash = await this.#hashOnce();
|
|
797
|
+
const scopedCall = async (control) => {
|
|
798
|
+
const { proxy, revoke } = scopedSidecarRemote(await this.#connect(control.extensions, pkg, packageHash));
|
|
799
|
+
try {
|
|
800
|
+
const result = await call(proxy);
|
|
801
|
+
assertSidecarRemoteDidNotEscape(result);
|
|
802
|
+
return detachPlainData(result);
|
|
803
|
+
} finally {
|
|
804
|
+
revoke();
|
|
805
|
+
}
|
|
806
|
+
};
|
|
807
|
+
return await this.withRuntime(operation, scopedCall);
|
|
808
|
+
}
|
|
809
|
+
/** Health snapshot for this extension's sidecar. */
|
|
810
|
+
async sidecarHealth() {
|
|
811
|
+
const hash = await this.#hashOnce();
|
|
812
|
+
return await this.withRuntime("extension.health", (control) => control.extensions.health(hash));
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* Stop this extension's sidecar. The next `withSidecar()` call will respawn
|
|
816
|
+
* it on demand.
|
|
817
|
+
*/
|
|
818
|
+
async stopSidecar() {
|
|
819
|
+
const hash = await this.#hashOnce();
|
|
820
|
+
await this.withRuntime("extension.stop", (control) => control.extensions.stop(hash));
|
|
821
|
+
}
|
|
822
|
+
async #connect(api, pkg, packageHash) {
|
|
823
|
+
try {
|
|
824
|
+
return await api.connect({
|
|
825
|
+
packageHash,
|
|
826
|
+
bin: pkg.bin,
|
|
827
|
+
readinessTimeoutMs: pkg.readinessTimeoutMs,
|
|
828
|
+
allowInstallScripts: pkg.allowInstallScripts
|
|
829
|
+
});
|
|
830
|
+
} catch (error) {
|
|
831
|
+
if (!isTarballRequiredError(error)) throw error;
|
|
832
|
+
try {
|
|
833
|
+
return await api.connect({
|
|
834
|
+
packageHash,
|
|
835
|
+
tarball: pkg.tarball,
|
|
836
|
+
bin: pkg.bin,
|
|
837
|
+
readinessTimeoutMs: pkg.readinessTimeoutMs,
|
|
838
|
+
allowInstallScripts: pkg.allowInstallScripts
|
|
839
|
+
});
|
|
840
|
+
} catch (retryError) {
|
|
841
|
+
throw createSidecarProvisioningError(packageHash, retryError);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
#hashOnce() {
|
|
846
|
+
const pkg = this.#requirePackage();
|
|
847
|
+
this.#hashPromise ??= sha256Hex(pkg.tarball);
|
|
848
|
+
return this.#hashPromise;
|
|
849
|
+
}
|
|
850
|
+
#requirePackage() {
|
|
851
|
+
if (!this.#pkg) throw new Error("This extension has no sidecar package. Pass one to `super(sandbox, pkg)` to use sidecar/sidecarHealth/stopSidecar.");
|
|
852
|
+
return this.#pkg;
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
/**
|
|
856
|
+
* Recognise the host's `ExtensionTarballRequired` error across the capnweb
|
|
857
|
+
* boundary. There are two cases:
|
|
858
|
+
*
|
|
859
|
+
* 1. capnweb preserves `Error.name`, so the primary wire-safe contract is the
|
|
860
|
+
* string constant `EXTENSION_TARBALL_REQUIRED`.
|
|
861
|
+
* 2. capnweb sometimes re-wraps the error as an `RPCTransportError`, discarding
|
|
862
|
+
* `name` but preserving the message text. We fall back to matching the
|
|
863
|
+
* message so the tarball retry still fires in that case.
|
|
864
|
+
*/
|
|
865
|
+
function assertRuntimeControlDidNotEscape(result, control) {
|
|
866
|
+
if (![
|
|
867
|
+
control,
|
|
868
|
+
control.files,
|
|
869
|
+
control.ports,
|
|
870
|
+
control.backup,
|
|
871
|
+
control.watch,
|
|
872
|
+
control.tunnels,
|
|
873
|
+
control.terminals,
|
|
874
|
+
control.extensions,
|
|
875
|
+
control.utils
|
|
876
|
+
].filter((handle) => handle !== void 0).includes(result)) return;
|
|
877
|
+
throw new Error("Sandbox extension runtime callbacks must not return runtime control handles");
|
|
878
|
+
}
|
|
879
|
+
function scopedRuntimeControl(target) {
|
|
880
|
+
let active = true;
|
|
881
|
+
const inactiveError = () => /* @__PURE__ */ new Error("Sandbox extension runtime control is no longer valid outside its runtime callback");
|
|
882
|
+
const wrappedDomains = /* @__PURE__ */ new WeakMap();
|
|
883
|
+
const scopeDomain = (domain) => {
|
|
884
|
+
const existing = wrappedDomains.get(domain);
|
|
885
|
+
if (existing) return existing;
|
|
886
|
+
const proxy = new Proxy(domain, { get(domainTarget, property, receiver) {
|
|
887
|
+
if (!active) return () => Promise.reject(inactiveError());
|
|
888
|
+
const value = Reflect.get(domainTarget, property, receiver);
|
|
889
|
+
if (typeof value === "function") return (...args) => {
|
|
890
|
+
if (!active) return Promise.reject(inactiveError());
|
|
891
|
+
return scopeRuntimeResult(Reflect.apply(value, domainTarget, args));
|
|
892
|
+
};
|
|
893
|
+
if (typeof value === "object" && value !== null) {
|
|
894
|
+
if (objectHasCallableMember(value)) return scopeDomain(value);
|
|
895
|
+
return detachPlainData(value);
|
|
896
|
+
}
|
|
897
|
+
return value;
|
|
898
|
+
} });
|
|
899
|
+
wrappedDomains.set(domain, proxy);
|
|
900
|
+
return proxy;
|
|
901
|
+
};
|
|
902
|
+
const scopeRuntimeResult = (result) => {
|
|
903
|
+
if (result instanceof Promise) return result.then(scopeRuntimeResult);
|
|
904
|
+
if (typeof result === "object" && result !== null) {
|
|
905
|
+
if (objectHasCallableMember(result)) return scopeDomain(result);
|
|
906
|
+
return detachPlainData(result);
|
|
907
|
+
}
|
|
908
|
+
return result;
|
|
909
|
+
};
|
|
910
|
+
return {
|
|
911
|
+
control: {
|
|
912
|
+
files: scopeDomain(target.files),
|
|
913
|
+
ports: scopeDomain(target.ports),
|
|
914
|
+
backup: scopeDomain(target.backup),
|
|
915
|
+
watch: scopeDomain(target.watch),
|
|
916
|
+
tunnels: scopeDomain(target.tunnels),
|
|
917
|
+
terminals: scopeDomain(target.terminals),
|
|
918
|
+
extensions: scopeDomain(target.extensions),
|
|
919
|
+
utils: scopeDomain(target.utils)
|
|
920
|
+
},
|
|
921
|
+
revoke: () => {
|
|
922
|
+
active = false;
|
|
923
|
+
}
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
const sidecarRemoteProxies = /* @__PURE__ */ new WeakSet();
|
|
927
|
+
function scopedSidecarRemote(target) {
|
|
928
|
+
let active = true;
|
|
929
|
+
const wrappedTargets = /* @__PURE__ */ new WeakMap();
|
|
930
|
+
const createProxy = (currentTarget) => {
|
|
931
|
+
const existing = wrappedTargets.get(currentTarget);
|
|
932
|
+
if (existing) return existing;
|
|
933
|
+
const proxy = new Proxy(currentTarget, { get(targetObject, property, receiver) {
|
|
934
|
+
if (!active) return () => Promise.reject(/* @__PURE__ */ new Error("Sandbox extension sidecar remote is no longer valid outside its runtime callback"));
|
|
935
|
+
const value = Reflect.get(targetObject, property, receiver);
|
|
936
|
+
if (typeof value === "function") return (...args) => {
|
|
937
|
+
if (!active) return Promise.reject(/* @__PURE__ */ new Error("Sandbox extension sidecar remote is no longer valid outside its runtime callback"));
|
|
938
|
+
return wrapSidecarResult(Reflect.apply(value, targetObject, args), createProxy);
|
|
939
|
+
};
|
|
940
|
+
if (typeof value === "object" && value !== null) {
|
|
941
|
+
if (objectHasCallableMember(value)) return createProxy(value);
|
|
942
|
+
return detachPlainData(value);
|
|
943
|
+
}
|
|
944
|
+
return value;
|
|
945
|
+
} });
|
|
946
|
+
wrappedTargets.set(currentTarget, proxy);
|
|
947
|
+
sidecarRemoteProxies.add(proxy);
|
|
948
|
+
return proxy;
|
|
949
|
+
};
|
|
950
|
+
return {
|
|
951
|
+
proxy: createProxy(target),
|
|
952
|
+
revoke: () => {
|
|
953
|
+
active = false;
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
}
|
|
957
|
+
function wrapSidecarResult(result, wrapObject) {
|
|
958
|
+
if (result instanceof Promise) return result.then((value) => wrapSidecarResult(value, wrapObject));
|
|
959
|
+
if (typeof result === "object" && result !== null) {
|
|
960
|
+
if (objectHasCallableMember(result)) return wrapObject(result);
|
|
961
|
+
return detachPlainData(result);
|
|
962
|
+
}
|
|
963
|
+
return result;
|
|
964
|
+
}
|
|
965
|
+
function objectHasCallableMember(value) {
|
|
966
|
+
if (Array.isArray(value)) return value.some((entry) => typeof entry === "function");
|
|
967
|
+
let current = value;
|
|
968
|
+
while (current && current !== Object.prototype) {
|
|
969
|
+
for (const property of Reflect.ownKeys(current)) {
|
|
970
|
+
if (property === "constructor") continue;
|
|
971
|
+
const descriptor = Reflect.getOwnPropertyDescriptor(current, property);
|
|
972
|
+
if (!descriptor) continue;
|
|
973
|
+
if (typeof descriptor.value === "function") return true;
|
|
974
|
+
if (typeof descriptor.get === "function") return true;
|
|
975
|
+
}
|
|
976
|
+
current = Reflect.getPrototypeOf(current);
|
|
977
|
+
}
|
|
978
|
+
return false;
|
|
979
|
+
}
|
|
980
|
+
function assertSidecarRemoteDidNotEscape(result) {
|
|
981
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
982
|
+
const visit = (value) => {
|
|
983
|
+
if (typeof value !== "object" || value === null) return false;
|
|
984
|
+
if (seen.has(value)) return false;
|
|
985
|
+
seen.add(value);
|
|
986
|
+
if (sidecarRemoteProxies.has(value)) return true;
|
|
987
|
+
if (Array.isArray(value)) return value.some(visit);
|
|
988
|
+
return Object.values(value).some(visit);
|
|
989
|
+
};
|
|
990
|
+
if (!visit(result)) return;
|
|
991
|
+
throw new Error("Sandbox extension sidecar callbacks must not return sidecar remotes");
|
|
992
|
+
}
|
|
993
|
+
function detachPlainData(value) {
|
|
994
|
+
if (typeof value !== "object" || value === null) return value;
|
|
995
|
+
return structuredClone(value);
|
|
996
|
+
}
|
|
997
|
+
function isTarballRequiredError(error) {
|
|
998
|
+
if (typeof error !== "object" || error === null) return false;
|
|
999
|
+
const candidate = error;
|
|
1000
|
+
if (candidate.name === EXTENSION_TARBALL_REQUIRED) return true;
|
|
1001
|
+
if (typeof candidate.message !== "string") return false;
|
|
1002
|
+
return candidate.message.includes(EXTENSION_TARBALL_REQUIRED) || /Extension package '[0-9a-f]{64}' is not provisioned/.test(candidate.message);
|
|
1003
|
+
}
|
|
1004
|
+
function createSidecarProvisioningError(packageHash, cause) {
|
|
1005
|
+
const causeMessage = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : String(cause);
|
|
1006
|
+
return new Error(`Failed to provision sandbox sidecar package '${packageHash}'. The sidecar tarball was sent to the container, but the container could not install or start it. Check that the extension build generated a valid npm-style .tgz, that the .tgz is included in the Worker bundle, and that the sidecar package declares a valid package.json bin/sandboxExtension entry. Cause: ${causeMessage}`, { cause });
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* Hex sha256 of a tarball via Web Crypto, which is available in workerd and
|
|
1010
|
+
* every modern runtime. Avoids a Node-only path so this module stays
|
|
1011
|
+
* Worker-bundle-safe.
|
|
1012
|
+
*/
|
|
1013
|
+
async function sha256Hex(bytes) {
|
|
1014
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
1015
|
+
const view = new Uint8Array(digest);
|
|
1016
|
+
let hex = "";
|
|
1017
|
+
for (const byte of view) hex += byte.toString(16).padStart(2, "0");
|
|
1018
|
+
return hex;
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
//#endregion
|
|
1022
|
+
export { PullSubscriptionTarget as a, createSandboxProcess as i, createExtensionProcessSandbox as n, openRemoteSubscription as o, sandboxRuntimeCall as r, translateRPCError as s, SandboxExtension as t };
|
|
1023
|
+
//# sourceMappingURL=extensions-CFB2xHqY.js.map
|