@hatchet-dev/sandbox 0.1.1 → 0.1.3
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/CHANGELOG.md +25 -1
- package/README.md +57 -40
- package/dist/index.cjs +405 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +198 -0
- package/dist/index.d.ts +198 -2
- package/dist/index.js +381 -8
- package/dist/index.js.map +1 -0
- package/package.json +47 -22
- package/dist/files.d.ts +0 -94
- package/dist/files.js +0 -179
- package/dist/otel.d.ts +0 -1
- package/dist/otel.js +0 -20
- package/dist/sandbox.d.ts +0 -91
- package/dist/sandbox.js +0 -112
package/dist/index.js
CHANGED
|
@@ -1,8 +1,381 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import { HatchetClient } from '@hatchet-dev/typescript-sdk/v1';
|
|
2
|
+
import * as fs from 'fs/promises';
|
|
3
|
+
|
|
4
|
+
// src/sandbox.ts
|
|
5
|
+
var FilesystemError = class extends Error {
|
|
6
|
+
constructor(code, message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.name = "FilesystemError";
|
|
10
|
+
}
|
|
11
|
+
code;
|
|
12
|
+
};
|
|
13
|
+
var toEntry = (e) => ({
|
|
14
|
+
...e,
|
|
15
|
+
modifiedTime: e.modifiedTime ? new Date(e.modifiedTime) : void 0
|
|
16
|
+
});
|
|
17
|
+
var STAGE_OVER_BYTES = 2 << 20;
|
|
18
|
+
async function toBytes(data) {
|
|
19
|
+
if (typeof data === "string") return Buffer.from(data, "utf8");
|
|
20
|
+
if (data instanceof Blob) return Buffer.from(await data.arrayBuffer());
|
|
21
|
+
if (data instanceof Uint8Array) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
22
|
+
return Buffer.from(data);
|
|
23
|
+
}
|
|
24
|
+
async function putStaged(url, bytes) {
|
|
25
|
+
if (url.startsWith("file://")) {
|
|
26
|
+
await fs.writeFile(decodeURIComponent(url.slice("file://".length)), bytes);
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const res = await fetch(url, {
|
|
30
|
+
method: "PUT",
|
|
31
|
+
body: new Uint8Array(bytes),
|
|
32
|
+
headers: { "Content-Type": "application/octet-stream" }
|
|
33
|
+
});
|
|
34
|
+
if (!res.ok)
|
|
35
|
+
throw new FilesystemError("staging_failed", `stage upload failed: HTTP ${res.status}`);
|
|
36
|
+
}
|
|
37
|
+
async function getStaged(url) {
|
|
38
|
+
if (url.startsWith("file://")) {
|
|
39
|
+
return fs.readFile(decodeURIComponent(url.slice("file://".length)));
|
|
40
|
+
}
|
|
41
|
+
const res = await fetch(url);
|
|
42
|
+
if (!res.ok)
|
|
43
|
+
throw new FilesystemError("staging_failed", `stage download failed: HTTP ${res.status}`);
|
|
44
|
+
return Buffer.from(await res.arrayBuffer());
|
|
45
|
+
}
|
|
46
|
+
var Files = class {
|
|
47
|
+
/** @internal */
|
|
48
|
+
constructor(turn) {
|
|
49
|
+
this.turn = turn;
|
|
50
|
+
}
|
|
51
|
+
turn;
|
|
52
|
+
async call(fn, input, fresh = false) {
|
|
53
|
+
const out = await this.turn(`$fs.${fn}`, input, fresh);
|
|
54
|
+
if (out.error) throw new FilesystemError(out.error.code, out.error.message);
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
async read(path, opts = {}) {
|
|
58
|
+
const out = await this.call("read", { path });
|
|
59
|
+
const bytes = out.url ? await this.readStaged(out.url, out.stagedKey) : Buffer.from(out.content ?? "", "base64");
|
|
60
|
+
if (opts.format === "bytes") return new Uint8Array(bytes);
|
|
61
|
+
if (opts.format === "blob") return new Blob([new Uint8Array(bytes)]);
|
|
62
|
+
return bytes.toString("utf8");
|
|
63
|
+
}
|
|
64
|
+
/** A replayed durable read may hold a URL that has expired; the provider signs the same staged file again. The renewal is a plain run, not a durable child, so the replayed child sequence stays aligned. */
|
|
65
|
+
async readStaged(url, stagedKey) {
|
|
66
|
+
try {
|
|
67
|
+
return await getStaged(url);
|
|
68
|
+
} catch (e) {
|
|
69
|
+
if (url.startsWith("file://") || !(e instanceof FilesystemError)) throw e;
|
|
70
|
+
const { getUrl } = await this.call("presign", { stagedKey }, true);
|
|
71
|
+
return getStaged(getUrl);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
async write(pathOrFiles, data) {
|
|
75
|
+
if (typeof pathOrFiles !== "string") return this.writeFiles(pathOrFiles);
|
|
76
|
+
const [entry] = await this.writeFiles([{ path: pathOrFiles, data: data ?? "" }]);
|
|
77
|
+
return entry;
|
|
78
|
+
}
|
|
79
|
+
/** Writes several files in one task. */
|
|
80
|
+
async writeFiles(files) {
|
|
81
|
+
const bytes = await Promise.all(files.map((f) => toBytes(f.data)));
|
|
82
|
+
const encoded = [];
|
|
83
|
+
for (const [i, f] of files.entries()) {
|
|
84
|
+
const b = bytes[i];
|
|
85
|
+
if (b.length <= STAGE_OVER_BYTES) {
|
|
86
|
+
encoded.push({ path: f.path, content: b.toString("base64") });
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
const { stagedKey, putUrl } = await this.call("presign", {});
|
|
90
|
+
try {
|
|
91
|
+
await putStaged(putUrl, b);
|
|
92
|
+
encoded.push({ path: f.path, stagedKey });
|
|
93
|
+
} catch {
|
|
94
|
+
const again = await this.call("presign", {}, true);
|
|
95
|
+
await putStaged(again.putUrl, b);
|
|
96
|
+
encoded.push({ path: f.path, stagedKey: again.stagedKey });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const { entries = [] } = await this.call("write", { files: encoded });
|
|
100
|
+
return entries.map(toEntry);
|
|
101
|
+
}
|
|
102
|
+
/** Lists a directory. `depth` 1 (default) is the directory itself; higher values recurse. No snapshot is made. */
|
|
103
|
+
async list(path = ".", opts = {}) {
|
|
104
|
+
const { entries = [] } = await this.call("list", { path, depth: opts.depth ?? 1 });
|
|
105
|
+
return entries.map(toEntry);
|
|
106
|
+
}
|
|
107
|
+
/** True if the path exists. No snapshot is made. */
|
|
108
|
+
async exists(path) {
|
|
109
|
+
const { entry } = await this.call("stat", { path });
|
|
110
|
+
return entry != null;
|
|
111
|
+
}
|
|
112
|
+
/** Metadata of a file or directory. Throws `FilesystemError` with code `not_found` if absent. */
|
|
113
|
+
async getInfo(path) {
|
|
114
|
+
const { entry } = await this.call("stat", { path });
|
|
115
|
+
if (!entry) throw new FilesystemError("not_found", `${path} does not exist`);
|
|
116
|
+
return toEntry(entry);
|
|
117
|
+
}
|
|
118
|
+
/** Creates a directory and its parents. Returns false if it already existed. */
|
|
119
|
+
async makeDir(path) {
|
|
120
|
+
const { created } = await this.call("mkdir", { path });
|
|
121
|
+
return created === true;
|
|
122
|
+
}
|
|
123
|
+
/** Renames or moves a file or directory. */
|
|
124
|
+
async rename(oldPath, newPath) {
|
|
125
|
+
const { entry } = await this.call("rename", { path: oldPath, newPath });
|
|
126
|
+
return toEntry(entry);
|
|
127
|
+
}
|
|
128
|
+
/** Copies a file or directory tree. */
|
|
129
|
+
async copy(srcPath, dstPath) {
|
|
130
|
+
const { entry } = await this.call("copy", { path: srcPath, newPath: dstPath });
|
|
131
|
+
return toEntry(entry);
|
|
132
|
+
}
|
|
133
|
+
/** Deletes a file or directory tree. */
|
|
134
|
+
async remove(path) {
|
|
135
|
+
await this.call("remove", { path });
|
|
136
|
+
}
|
|
137
|
+
/** The provider fetches an https URL into the workspace. The sandbox needs no network. Private and loopback addresses are refused. */
|
|
138
|
+
async download(url, path, opts = {}) {
|
|
139
|
+
const { entry } = await this.call("download", {
|
|
140
|
+
url,
|
|
141
|
+
path,
|
|
142
|
+
...opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}
|
|
143
|
+
});
|
|
144
|
+
return toEntry(entry);
|
|
145
|
+
}
|
|
146
|
+
/** The provider sends a workspace file to an https URL with HTTP PUT, for example a presigned URL. */
|
|
147
|
+
async upload(path, url, opts = {}) {
|
|
148
|
+
await this.call("upload", {
|
|
149
|
+
path,
|
|
150
|
+
url,
|
|
151
|
+
...opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// src/otel.ts
|
|
157
|
+
var telemetryStarted = false;
|
|
158
|
+
async function setupTelemetry() {
|
|
159
|
+
if (telemetryStarted || process.env.HATCHET_SANDBOX_OTEL === "false" || process.env.BRICKIE_OTEL === "false") {
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
telemetryStarted = true;
|
|
163
|
+
try {
|
|
164
|
+
const [{ registerInstrumentations }, { HatchetInstrumentor }] = await Promise.all([
|
|
165
|
+
import('@opentelemetry/instrumentation'),
|
|
166
|
+
import('@hatchet-dev/typescript-sdk/opentelemetry/index.js')
|
|
167
|
+
]);
|
|
168
|
+
registerInstrumentations({ instrumentations: [new HatchetInstrumentor()] });
|
|
169
|
+
} catch (err) {
|
|
170
|
+
console.error(`sandbox: opentelemetry disabled: ${err.message}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// src/sandbox.ts
|
|
175
|
+
var TASK_NAMES = ["hatchet-sandbox", "brickie-sandbox"];
|
|
176
|
+
var taskNames = /* @__PURE__ */ new WeakMap();
|
|
177
|
+
async function registered(client, name) {
|
|
178
|
+
const namespace = client.config.namespace ?? "";
|
|
179
|
+
const full = name.startsWith(namespace) ? name : `${namespace}${name}`;
|
|
180
|
+
for (let offset = 0; ; ) {
|
|
181
|
+
const { rows = [] } = await client.workflows.list({ name: full, limit: 100, offset });
|
|
182
|
+
if (rows.some((w) => w.name === full)) return true;
|
|
183
|
+
if (rows.length === 0) return false;
|
|
184
|
+
offset += rows.length;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
async function probe(client) {
|
|
188
|
+
for (const name of TASK_NAMES) {
|
|
189
|
+
if (await registered(client, name)) return name;
|
|
190
|
+
}
|
|
191
|
+
return void 0;
|
|
192
|
+
}
|
|
193
|
+
function resolveTaskName(client) {
|
|
194
|
+
let pending = taskNames.get(client);
|
|
195
|
+
if (!pending) {
|
|
196
|
+
pending = probe(client).then(
|
|
197
|
+
(name) => {
|
|
198
|
+
if (!name) taskNames.delete(client);
|
|
199
|
+
return name ?? TASK_NAMES[TASK_NAMES.length - 1];
|
|
200
|
+
},
|
|
201
|
+
(err) => {
|
|
202
|
+
taskNames.delete(client);
|
|
203
|
+
throw err;
|
|
204
|
+
}
|
|
205
|
+
);
|
|
206
|
+
taskNames.set(client, pending);
|
|
207
|
+
}
|
|
208
|
+
return pending;
|
|
209
|
+
}
|
|
210
|
+
var UNITS = {
|
|
211
|
+
K: 1e3,
|
|
212
|
+
M: 1e6,
|
|
213
|
+
G: 1e9,
|
|
214
|
+
T: 1e12,
|
|
215
|
+
Ki: 2 ** 10,
|
|
216
|
+
Mi: 2 ** 20,
|
|
217
|
+
Gi: 2 ** 30,
|
|
218
|
+
Ti: 2 ** 40
|
|
219
|
+
};
|
|
220
|
+
function toMib(value, field) {
|
|
221
|
+
if (typeof value === "number") {
|
|
222
|
+
if (!Number.isInteger(value) || value <= 0)
|
|
223
|
+
throw new Error(`resources.${field}: expected a positive whole number of MiB`);
|
|
224
|
+
return value;
|
|
225
|
+
}
|
|
226
|
+
const m = /^(\d+(?:\.\d+)?)\s*([KMGT]i?)?B?$/.exec(value.trim());
|
|
227
|
+
if (!m)
|
|
228
|
+
throw new Error(
|
|
229
|
+
`resources.${field}: expected a quantity like '512Mi', '4Gi' or '8G', got ${JSON.stringify(value)}`
|
|
230
|
+
);
|
|
231
|
+
const bytes = Number(m[1]) * (m[2] ? UNITS[m[2]] : UNITS.Mi);
|
|
232
|
+
const mib = Math.ceil(bytes / UNITS.Mi);
|
|
233
|
+
if (mib <= 0) throw new Error(`resources.${field}: must be at least 1Mi`);
|
|
234
|
+
return mib;
|
|
235
|
+
}
|
|
236
|
+
function wireResources(r) {
|
|
237
|
+
const out = {};
|
|
238
|
+
if (r.vcpu !== void 0) {
|
|
239
|
+
if (!Number.isInteger(r.vcpu) || r.vcpu <= 0)
|
|
240
|
+
throw new Error("resources.vcpu: expected a positive whole number of cores");
|
|
241
|
+
out.vcpu = r.vcpu;
|
|
242
|
+
}
|
|
243
|
+
if (r.memory !== void 0) out.memoryMib = toMib(r.memory, "memory");
|
|
244
|
+
if (r.disk !== void 0) out.diskMib = toMib(r.disk, "disk");
|
|
245
|
+
if (Object.keys(out).length === 0)
|
|
246
|
+
throw new Error("resources: set at least one of vcpu, memory, disk");
|
|
247
|
+
return out;
|
|
248
|
+
}
|
|
249
|
+
function turnRunner(client) {
|
|
250
|
+
const resolved = resolveTaskName(client);
|
|
251
|
+
return async (input, opts) => {
|
|
252
|
+
const name = await resolved;
|
|
253
|
+
const additionalMetadata = {
|
|
254
|
+
"hatchet.sandbox.fn": input.fn,
|
|
255
|
+
...input.sandboxId ? { "hatchet.sandbox.id": input.sandboxId } : {},
|
|
256
|
+
...input.image ? { "hatchet.sandbox.image": input.image } : {},
|
|
257
|
+
...input.snapshotId ? { "hatchet.sandbox.from": input.snapshotId } : {}
|
|
258
|
+
};
|
|
259
|
+
const result = opts?.fresh ? await (await client.admin.runWorkflow(name, input, {
|
|
260
|
+
additionalMetadata
|
|
261
|
+
})).result() : await client.workflow({ name }).run(input, { additionalMetadata });
|
|
262
|
+
return result[name] ?? result;
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
var Sandbox = class _Sandbox {
|
|
266
|
+
constructor(run, sandboxId, template) {
|
|
267
|
+
this.run = run;
|
|
268
|
+
this.sandboxId = sandboxId;
|
|
269
|
+
this.template = template;
|
|
270
|
+
this.files = new Files((fn, input, fresh) => this.turn(fn, input, fresh));
|
|
271
|
+
}
|
|
272
|
+
run;
|
|
273
|
+
sandboxId;
|
|
274
|
+
template;
|
|
275
|
+
/** File operations on the workspace. */
|
|
276
|
+
files;
|
|
277
|
+
/** Starts a new sandbox. Prefer `hatchet.sandbox.create`. */
|
|
278
|
+
static async create(client, opts = {}) {
|
|
279
|
+
await setupTelemetry();
|
|
280
|
+
const run = turnRunner(client);
|
|
281
|
+
const metadata = opts.provider ? { ...opts.metadata, provider: opts.provider } : opts.metadata;
|
|
282
|
+
const created = await run({
|
|
283
|
+
fn: "$create",
|
|
284
|
+
input: {},
|
|
285
|
+
...opts.id ? { sandboxId: opts.id } : {},
|
|
286
|
+
...opts.template ? { image: opts.template } : {},
|
|
287
|
+
...opts.from ? { snapshotId: opts.from } : {},
|
|
288
|
+
...metadata ? { metadata } : {},
|
|
289
|
+
...opts.idleTimeoutMs ? { idleTtlMs: opts.idleTimeoutMs } : {},
|
|
290
|
+
...opts.inheritParentMetadata ? { inheritMetadata: true } : {},
|
|
291
|
+
...opts.resources ? { resources: wireResources(opts.resources) } : {}
|
|
292
|
+
});
|
|
293
|
+
return new _Sandbox(run, created.sandboxId, opts.template);
|
|
294
|
+
}
|
|
295
|
+
/** Attaches to a sandbox by ID. Prefer `hatchet.sandbox.connect`. */
|
|
296
|
+
static async connect(client, sandboxId, opts = {}) {
|
|
297
|
+
await setupTelemetry();
|
|
298
|
+
const run = turnRunner(client);
|
|
299
|
+
await run({
|
|
300
|
+
fn: "$connect",
|
|
301
|
+
input: {},
|
|
302
|
+
sandboxId,
|
|
303
|
+
...opts.template ? { image: opts.template } : {}
|
|
304
|
+
});
|
|
305
|
+
return new _Sandbox(run, sandboxId, opts.template);
|
|
306
|
+
}
|
|
307
|
+
/** Lists sandboxes on the provider. Prefer `hatchet.sandbox.list`. */
|
|
308
|
+
static async list(client, opts = {}) {
|
|
309
|
+
const result = await turnRunner(client)({
|
|
310
|
+
fn: "$list",
|
|
311
|
+
input: {
|
|
312
|
+
...opts.sandboxId ? { sandboxId: opts.sandboxId } : {},
|
|
313
|
+
...opts.metadata ? { metadata: opts.metadata } : {}
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
const raw = result.output.sandboxes ?? [];
|
|
317
|
+
return raw.map((s) => ({
|
|
318
|
+
...s,
|
|
319
|
+
createdAt: new Date(s.createdAt),
|
|
320
|
+
lastUsed: s.lastUsed ? new Date(s.lastUsed) : void 0
|
|
321
|
+
}));
|
|
322
|
+
}
|
|
323
|
+
/** Deletes every sandbox matching the filter, with all their snapshots and files. Prefer `hatchet.sandbox.delete`. */
|
|
324
|
+
static async delete(client, opts) {
|
|
325
|
+
if (!opts.sandboxId && Object.keys(opts.metadata ?? {}).length === 0)
|
|
326
|
+
throw new Error("delete needs a sandboxId or a metadata filter");
|
|
327
|
+
const run = turnRunner(client);
|
|
328
|
+
const ids = [];
|
|
329
|
+
for (const { sandboxId } of await _Sandbox.list(client, opts)) {
|
|
330
|
+
await run({ fn: "$delete", input: {}, sandboxId });
|
|
331
|
+
ids.push(sandboxId);
|
|
332
|
+
}
|
|
333
|
+
return ids;
|
|
334
|
+
}
|
|
335
|
+
/** Runs a shell command with `sh -c` in the workspace and makes a snapshot. A timeout gives `exitCode` 124, not an error. */
|
|
336
|
+
async exec(cmd, opts = {}) {
|
|
337
|
+
return this.turn("$command", {
|
|
338
|
+
cmd,
|
|
339
|
+
...opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
/** Removes the sandbox. Its snapshots stay; `connect` can bring it back. */
|
|
343
|
+
async kill() {
|
|
344
|
+
await this.turn("$destroy", {});
|
|
345
|
+
}
|
|
346
|
+
/** Removes the sandbox and deletes every snapshot and file the provider stored for it. `connect` fails afterwards. */
|
|
347
|
+
async delete() {
|
|
348
|
+
await this.turn("$delete", {});
|
|
349
|
+
}
|
|
350
|
+
async turn(fn, input, fresh = false) {
|
|
351
|
+
const result = await this.run(
|
|
352
|
+
{
|
|
353
|
+
sandboxId: this.sandboxId,
|
|
354
|
+
...this.template ? { image: this.template } : {},
|
|
355
|
+
fn,
|
|
356
|
+
input
|
|
357
|
+
},
|
|
358
|
+
{ fresh }
|
|
359
|
+
);
|
|
360
|
+
return {
|
|
361
|
+
...result.output,
|
|
362
|
+
snapshotId: result.snapshotId,
|
|
363
|
+
timings: result.timings
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
Object.defineProperty(HatchetClient.prototype, "sandbox", {
|
|
368
|
+
configurable: true,
|
|
369
|
+
get() {
|
|
370
|
+
return {
|
|
371
|
+
create: (opts) => Sandbox.create(this, opts),
|
|
372
|
+
connect: (sandboxId, opts) => Sandbox.connect(this, sandboxId, opts),
|
|
373
|
+
list: (opts) => Sandbox.list(this, opts),
|
|
374
|
+
delete: (opts) => Sandbox.delete(this, opts)
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
export { Files, FilesystemError, Sandbox };
|
|
380
|
+
//# sourceMappingURL=index.js.map
|
|
381
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/files.ts","../src/otel.ts","../src/sandbox.ts"],"names":[],"mappings":";;;;AAgDO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACzC,WAAA,CACW,MACT,OAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHJ,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAIT,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AAAA,EACd;AAAA,EALW,IAAA;AAMb;AAmBA,IAAM,OAAA,GAAU,CAAC,CAAA,MAA4B;AAAA,EAC3C,GAAG,CAAA;AAAA,EACH,cAAc,CAAA,CAAE,YAAA,GAAe,IAAI,IAAA,CAAK,CAAA,CAAE,YAAY,CAAA,GAAI;AAC5D,CAAA,CAAA;AAEA,IAAM,mBAAmB,CAAA,IAAK,EAAA;AAE9B,eAAe,QAAQ,IAAA,EAAiC;AACtD,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,SAAiB,MAAA,CAAO,IAAA,CAAK,MAAM,M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AAAA,EACF;AACF;AAoBA,MAAA,CAAO,cAAA,CAAe,aAAA,CAAc,SAAA,EAAW,SAAA,EAAW;AAAA,EACxD,YAAA,EAAc,IAAA;AAAA,EACd,GAAA,GAA2C;AACzC,IAAA,OAAO;AAAA,MACL,QAAQ,CAAC,IAAA,KAAS,OAAA,CAAQ,MAAA,CAAO,MAAM,IAAI,CAAA;AAAA,MAC3C,OAAA,EAAS,CAAC,SAAA,EAAW,IAAA,KAAS,QAAQ,OAAA,CAAQ,IAAA,EAAM,WAAW,IAAI,CAAA;AAAA,MACnE,MAAM,CAAC,IAAA,KAAS,OAAA,CAAQ,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,MACvC,QAAQ,CAAC,IAAA,KAAS,OAAA,CAAQ,MAAA,CAAO,MAAM,IAAI;AAAA,KAC7C;AAAA,EACF;AACF,CAAC,CAAA","file":"index.js","sourcesContent":["import * as fs from 'node:fs/promises';\nimport type { JsonObject } from '@hatchet-dev/typescript-sdk/v1';\n\nexport type FileType = 'file' | 'dir';\n\nexport interface EntryInfo {\n name: string;\n path: string;\n type: FileType;\n size: number;\n mode: number;\n permissions: string;\n modifiedTime?: Date;\n}\n\nexport type FileData = string | ArrayBuffer | Uint8Array | Blob;\n\nexport interface WriteEntry {\n path: string;\n data: FileData;\n}\n\nexport interface ReadOpts {\n format?: 'text' | 'bytes' | 'blob';\n}\n\nexport interface TransferOpts {\n /** Give up after this long. */\n timeoutMs?: number;\n}\n\nexport interface ListOpts {\n depth?: number;\n}\n\nexport type FilesystemErrorCode =\n | 'staging_failed'\n | 'not_found'\n | 'invalid_path'\n | 'invalid_url'\n | 'invalid_content'\n | 'invalid'\n | 'is_a_directory'\n | 'not_a_directory'\n | 'too_large'\n | 'transfer_failed';\n\n/** Thrown for caller mistakes such as a missing file or a path outside the workspace. */\nexport class FilesystemError extends Error {\n constructor(\n readonly code: FilesystemErrorCode,\n message: string\n ) {\n super(message);\n this.name = 'FilesystemError';\n }\n}\n\ntype RawEntry = Omit<EntryInfo, 'modifiedTime'> & { modifiedTime?: string };\n\ninterface FsOutput extends JsonObject {\n content?: string;\n stagedKey?: string;\n url?: string;\n putUrl?: string;\n getUrl?: string;\n entry?: RawEntry | null;\n entries?: RawEntry[];\n created?: boolean;\n error?: { code: FilesystemErrorCode; message: string };\n}\n\n/** @internal */\nexport type FsTurn = (fn: string, input: JsonObject, fresh?: boolean) => Promise<FsOutput>;\n\nconst toEntry = (e: RawEntry): EntryInfo => ({\n ...e,\n modifiedTime: e.modifiedTime ? new Date(e.modifiedTime) : undefined,\n});\n\nconst STAGE_OVER_BYTES = 2 << 20;\n\nasync function toBytes(data: FileData): Promise<Buffer> {\n if (typeof data === 'string') return Buffer.from(data, 'utf8');\n if (data instanceof Blob) return Buffer.from(await data.arrayBuffer());\n if (data instanceof Uint8Array) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);\n return Buffer.from(data);\n}\n\nasync function putStaged(url: string, bytes: Buffer): Promise<void> {\n if (url.startsWith('file://')) {\n await fs.writeFile(decodeURIComponent(url.slice('file://'.length)), bytes);\n return;\n }\n const res = await fetch(url, {\n method: 'PUT',\n body: new Uint8Array(bytes),\n headers: { 'Content-Type': 'application/octet-stream' },\n });\n if (!res.ok)\n throw new FilesystemError('staging_failed', `stage upload failed: HTTP ${res.status}`);\n}\n\nasync function getStaged(url: string): Promise<Buffer> {\n if (url.startsWith('file://')) {\n return fs.readFile(decodeURIComponent(url.slice('file://'.length)));\n }\n const res = await fetch(url);\n if (!res.ok)\n throw new FilesystemError('staging_failed', `stage download failed: HTTP ${res.status}`);\n return Buffer.from(await res.arrayBuffer());\n}\n/** File operations on a sandbox workspace. Paths are relative to the workspace. Each call is one Hatchet task. */\nexport class Files {\n /** @internal */\n constructor(private readonly turn: FsTurn) {}\n\n private async call(fn: string, input: JsonObject, fresh = false): Promise<FsOutput> {\n const out = await this.turn(`$fs.${fn}`, input, fresh);\n if (out.error) throw new FilesystemError(out.error.code, out.error.message);\n return out;\n }\n\n /** Reads a file as text (default), bytes, or a Blob. Files over the provider's `--max-file-bytes` (2 MiB) come through the provider's `--store` instead of Hatchet. */\n read(path: string, opts?: ReadOpts & { format?: 'text' }): Promise<string>;\n read(path: string, opts: ReadOpts & { format: 'bytes' }): Promise<Uint8Array>;\n read(path: string, opts: ReadOpts & { format: 'blob' }): Promise<Blob>;\n async read(path: string, opts: ReadOpts = {}): Promise<string | Uint8Array | Blob> {\n const out = await this.call('read', { path });\n const bytes = out.url\n ? await this.readStaged(out.url, out.stagedKey!)\n : Buffer.from(out.content ?? '', 'base64');\n if (opts.format === 'bytes') return new Uint8Array(bytes);\n if (opts.format === 'blob') return new Blob([new Uint8Array(bytes)]);\n return bytes.toString('utf8');\n }\n\n /** A replayed durable read may hold a URL that has expired; the provider signs the same staged file again. The renewal is a plain run, not a durable child, so the replayed child sequence stays aligned. */\n private async readStaged(url: string, stagedKey: string): Promise<Buffer> {\n try {\n return await getStaged(url);\n } catch (e) {\n if (url.startsWith('file://') || !(e instanceof FilesystemError)) throw e;\n const { getUrl } = await this.call('presign', { stagedKey }, true);\n return getStaged(getUrl!);\n }\n }\n\n /** Writes one file or several. Parent directories are created. Bytes are stored exactly. Files over 2 MiB go through the provider's `--store` instead of Hatchet. */\n write(path: string, data: FileData): Promise<EntryInfo>;\n write(files: WriteEntry[]): Promise<EntryInfo[]>;\n async write(\n pathOrFiles: string | WriteEntry[],\n data?: FileData\n ): Promise<EntryInfo | EntryInfo[]> {\n if (typeof pathOrFiles !== 'string') return this.writeFiles(pathOrFiles);\n const [entry] = await this.writeFiles([{ path: pathOrFiles, data: data ?? '' }]);\n return entry;\n }\n\n /** Writes several files in one task. */\n async writeFiles(files: WriteEntry[]): Promise<EntryInfo[]> {\n const bytes = await Promise.all(files.map((f) => toBytes(f.data)));\n const encoded: Array<{ path: string; content?: string; stagedKey?: string }> = [];\n for (const [i, f] of files.entries()) {\n const b = bytes[i];\n if (b.length <= STAGE_OVER_BYTES) {\n encoded.push({ path: f.path, content: b.toString('base64') });\n continue;\n }\n const { stagedKey, putUrl } = await this.call('presign', {});\n try {\n await putStaged(putUrl!, b);\n encoded.push({ path: f.path, stagedKey: stagedKey! });\n } catch {\n const again = await this.call('presign', {}, true);\n await putStaged(again.putUrl!, b);\n encoded.push({ path: f.path, stagedKey: again.stagedKey! });\n }\n }\n const { entries = [] } = await this.call('write', { files: encoded });\n return entries.map(toEntry);\n }\n\n /** Lists a directory. `depth` 1 (default) is the directory itself; higher values recurse. No snapshot is made. */\n async list(path = '.', opts: ListOpts = {}): Promise<EntryInfo[]> {\n const { entries = [] } = await this.call('list', { path, depth: opts.depth ?? 1 });\n return entries.map(toEntry);\n }\n\n /** True if the path exists. No snapshot is made. */\n async exists(path: string): Promise<boolean> {\n const { entry } = await this.call('stat', { path });\n return entry != null;\n }\n\n /** Metadata of a file or directory. Throws `FilesystemError` with code `not_found` if absent. */\n async getInfo(path: string): Promise<EntryInfo> {\n const { entry } = await this.call('stat', { path });\n if (!entry) throw new FilesystemError('not_found', `${path} does not exist`);\n return toEntry(entry);\n }\n\n /** Creates a directory and its parents. Returns false if it already existed. */\n async makeDir(path: string): Promise<boolean> {\n const { created } = await this.call('mkdir', { path });\n return created === true;\n }\n\n /** Renames or moves a file or directory. */\n async rename(oldPath: string, newPath: string): Promise<EntryInfo> {\n const { entry } = await this.call('rename', { path: oldPath, newPath });\n return toEntry(entry!);\n }\n\n /** Copies a file or directory tree. */\n async copy(srcPath: string, dstPath: string): Promise<EntryInfo> {\n const { entry } = await this.call('copy', { path: srcPath, newPath: dstPath });\n return toEntry(entry!);\n }\n\n /** Deletes a file or directory tree. */\n async remove(path: string): Promise<void> {\n await this.call('remove', { path });\n }\n /** The provider fetches an https URL into the workspace. The sandbox needs no network. Private and loopback addresses are refused. */\n async download(url: string, path: string, opts: TransferOpts = {}): Promise<EntryInfo> {\n const { entry } = await this.call('download', {\n url,\n path,\n ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}),\n });\n return toEntry(entry!);\n }\n /** The provider sends a workspace file to an https URL with HTTP PUT, for example a presigned URL. */\n async upload(path: string, url: string, opts: TransferOpts = {}): Promise<void> {\n await this.call('upload', {\n path,\n url,\n ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}),\n });\n }\n}\n","let telemetryStarted = false;\n\nexport async function setupTelemetry(): Promise<void> {\n if (\n telemetryStarted ||\n process.env.HATCHET_SANDBOX_OTEL === 'false' ||\n process.env.BRICKIE_OTEL === 'false'\n ) {\n return;\n }\n telemetryStarted = true;\n try {\n const [{ registerInstrumentations }, { HatchetInstrumentor }] = await Promise.all([\n import('@opentelemetry/instrumentation'),\n import('@hatchet-dev/typescript-sdk/opentelemetry/index.js'),\n ]);\n registerInstrumentations({ instrumentations: [new HatchetInstrumentor()] });\n } catch (err) {\n console.error(`sandbox: opentelemetry disabled: ${(err as Error).message}`);\n }\n}\n","import { HatchetClient, JsonObject } from '@hatchet-dev/typescript-sdk/v1';\nimport { Files } from './files.js';\nimport { setupTelemetry } from './otel.js';\n\nconst TASK_NAMES = ['hatchet-sandbox', 'brickie-sandbox'];\nconst taskNames = new WeakMap<HatchetClient, Promise<string>>();\n\nasync function registered(client: HatchetClient, name: string): Promise<boolean> {\n const namespace = client.config.namespace ?? '';\n const full = name.startsWith(namespace) ? name : `${namespace}${name}`;\n for (let offset = 0; ;) {\n const { rows = [] } = await client.workflows.list({ name: full, limit: 100, offset });\n if (rows.some((w) => w.name === full)) return true;\n if (rows.length === 0) return false;\n offset += rows.length;\n }\n}\n\nasync function probe(client: HatchetClient): Promise<string | undefined> {\n for (const name of TASK_NAMES) {\n if (await registered(client, name)) return name;\n }\n return undefined;\n}\n\nfunction resolveTaskName(client: HatchetClient): Promise<string> {\n let pending = taskNames.get(client);\n if (!pending) {\n pending = probe(client).then(\n (name) => {\n if (!name) taskNames.delete(client);\n return name ?? TASK_NAMES[TASK_NAMES.length - 1];\n },\n (err) => {\n taskNames.delete(client);\n throw err;\n }\n );\n taskNames.set(client, pending);\n }\n return pending;\n}\n\ninterface TurnInput extends JsonObject {\n sandboxId?: string;\n image?: string;\n fn: string;\n input: JsonObject;\n snapshotId?: string;\n metadata?: Record<string, string>;\n idleTtlMs?: number;\n inheritMetadata?: boolean;\n}\n\ninterface TurnResult extends JsonObject {\n output: JsonObject;\n sandboxId: string;\n snapshotId?: string;\n timings?: Record<string, number>;\n}\n\nexport interface Timings {\n /** Snapshot made after this turn. Absent for turns that do not change the workspace. */\n snapshotId?: string;\n /** Milliseconds per phase: `claim`, `restore`, `exec`, `checkpoint`. */\n timings?: Record<string, number>;\n}\n\nexport interface CommandResult extends Timings {\n stdout: string;\n stderr: string;\n /** A non-zero code is a normal result, not an error. */\n exitCode: number;\n}\n\nexport interface SandboxOpts {\n /** Sandbox ID to use instead of a generated one. Lowercase letters, digits, and hyphens; must be new on the provider. */\n id?: string;\n /** Container image. Defaults to the provider's image. */\n template?: string;\n /** Snapshot to start from. Two sandboxes with the same `from` are a fork. */\n from?: string;\n /** Key-value tags, used to find the sandbox again with {@link SandboxNamespace.list}. */\n metadata?: Record<string, string>;\n /** Milliseconds without a turn before the provider removes the sandbox. Capped by the provider. */\n idleTimeoutMs?: number;\n /** With `from`, start from the metadata of the sandbox that made that snapshot. Pairs given in `metadata` take precedence over inherited ones. */\n inheritParentMetadata?: boolean;\n /** Name of the sandbox provider to create on. Required when the tenant has more than one; with `from`, it must be the provider that holds the snapshot. */\n provider?: string;\n /** Machine size. Providers that cannot honour a field fail the create with their own message. Providers that do not know the option ignore it. */\n resources?: Resources;\n}\n\nexport interface Resources {\n /** Whole cores. */\n vcpu?: number;\n /** A number is MiB. A string takes a Kubernetes quantity such as `'512Mi'`, `'4Gi'` or `'8G'`. */\n memory?: number | string;\n /** Same format as `memory`. */\n disk?: number | string;\n}\n\nconst UNITS: Record<string, number> = {\n K: 1e3,\n M: 1e6,\n G: 1e9,\n T: 1e12,\n Ki: 2 ** 10,\n Mi: 2 ** 20,\n Gi: 2 ** 30,\n Ti: 2 ** 40,\n};\n\nfunction toMib(value: number | string, field: string): number {\n if (typeof value === 'number') {\n if (!Number.isInteger(value) || value <= 0)\n throw new Error(`resources.${field}: expected a positive whole number of MiB`);\n return value;\n }\n const m = /^(\\d+(?:\\.\\d+)?)\\s*([KMGT]i?)?B?$/.exec(value.trim());\n if (!m)\n throw new Error(\n `resources.${field}: expected a quantity like '512Mi', '4Gi' or '8G', got ${JSON.stringify(value)}`\n );\n const bytes = Number(m[1]) * (m[2] ? UNITS[m[2]] : UNITS.Mi);\n const mib = Math.ceil(bytes / UNITS.Mi);\n if (mib <= 0) throw new Error(`resources.${field}: must be at least 1Mi`);\n return mib;\n}\n\nfunction wireResources(r: Resources): JsonObject {\n const out: JsonObject = {};\n if (r.vcpu !== undefined) {\n if (!Number.isInteger(r.vcpu) || r.vcpu <= 0)\n throw new Error('resources.vcpu: expected a positive whole number of cores');\n out.vcpu = r.vcpu;\n }\n if (r.memory !== undefined) out.memoryMib = toMib(r.memory, 'memory');\n if (r.disk !== undefined) out.diskMib = toMib(r.disk, 'disk');\n if (Object.keys(out).length === 0)\n throw new Error('resources: set at least one of vcpu, memory, disk');\n return out;\n}\n\nexport interface ExecOpts {\n /** Kill the command after this long. The result then has `exitCode` 124. */\n timeoutMs?: number;\n}\n\nexport interface ConnectOpts {\n /** Image to use if the sandbox has to be started again. Defaults to the provider's image. */\n template?: string;\n}\n\nexport interface SandboxListOpts {\n /** Only the sandbox with this ID. */\n sandboxId?: string;\n /** Only sandboxes whose metadata contains every one of these pairs. */\n metadata?: Record<string, string>;\n}\n\nexport interface SandboxInfo {\n sandboxId: string;\n metadata?: Record<string, string>;\n /** True while the sandbox is running. A sandbox that is not live is started again by `connect`. */\n live: boolean;\n latestSnapshot?: string;\n createdAt: Date;\n lastUsed?: Date;\n}\n\ntype RunTurn = (input: TurnInput, opts?: { fresh?: boolean }) => Promise<TurnResult>;\n\nfunction turnRunner(client: HatchetClient): RunTurn {\n const resolved = resolveTaskName(client);\n return async (input, opts) => {\n const name = await resolved;\n const additionalMetadata = {\n 'hatchet.sandbox.fn': input.fn,\n ...(input.sandboxId ? { 'hatchet.sandbox.id': input.sandboxId } : {}),\n ...(input.image ? { 'hatchet.sandbox.image': input.image } : {}),\n ...(input.snapshotId ? { 'hatchet.sandbox.from': input.snapshotId } : {}),\n };\n const result = opts?.fresh\n ? await (\n await client.admin.runWorkflow<TurnInput, Record<string, TurnResult>>(name, input, {\n additionalMetadata,\n })\n ).result()\n : await client\n .workflow<TurnInput, Record<string, TurnResult>>({ name })\n .run(input, { additionalMetadata });\n return result[name] ?? (result as unknown as TurnResult);\n };\n}\n\n/** One sandbox. Every method is one Hatchet task on the tenant's sandbox provider. */\nexport class Sandbox {\n /** File operations on the workspace. */\n readonly files: Files;\n\n private constructor(\n private readonly run: RunTurn,\n readonly sandboxId: string,\n private readonly template?: string\n ) {\n this.files = new Files((fn, input, fresh) => this.turn(fn, input, fresh));\n }\n\n /** Starts a new sandbox. Prefer `hatchet.sandbox.create`. */\n static async create(client: HatchetClient, opts: SandboxOpts = {}): Promise<Sandbox> {\n await setupTelemetry();\n const run = turnRunner(client);\n const metadata = opts.provider ? { ...opts.metadata, provider: opts.provider } : opts.metadata;\n const created = await run({\n fn: '$create',\n input: {},\n ...(opts.id ? { sandboxId: opts.id } : {}),\n ...(opts.template ? { image: opts.template } : {}),\n ...(opts.from ? { snapshotId: opts.from } : {}),\n ...(metadata ? { metadata } : {}),\n ...(opts.idleTimeoutMs ? { idleTtlMs: opts.idleTimeoutMs } : {}),\n ...(opts.inheritParentMetadata ? { inheritMetadata: true } : {}),\n ...(opts.resources ? { resources: wireResources(opts.resources) } : {}),\n });\n return new Sandbox(run, created.sandboxId, opts.template);\n }\n\n /** Attaches to a sandbox by ID. Prefer `hatchet.sandbox.connect`. */\n static async connect(\n client: HatchetClient,\n sandboxId: string,\n opts: ConnectOpts = {}\n ): Promise<Sandbox> {\n await setupTelemetry();\n const run = turnRunner(client);\n await run({\n fn: '$connect',\n input: {},\n sandboxId,\n ...(opts.template ? { image: opts.template } : {}),\n });\n return new Sandbox(run, sandboxId, opts.template);\n }\n\n /** Lists sandboxes on the provider. Prefer `hatchet.sandbox.list`. */\n static async list(client: HatchetClient, opts: SandboxListOpts = {}): Promise<SandboxInfo[]> {\n const result = await turnRunner(client)({\n fn: '$list',\n input: {\n ...(opts.sandboxId ? { sandboxId: opts.sandboxId } : {}),\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n },\n });\n const raw = (result.output.sandboxes ?? []) as Array<\n Omit<SandboxInfo, 'createdAt' | 'lastUsed'> & { createdAt: string; lastUsed?: string }\n >;\n return raw.map((s) => ({\n ...s,\n createdAt: new Date(s.createdAt),\n lastUsed: s.lastUsed ? new Date(s.lastUsed) : undefined,\n }));\n }\n\n /** Deletes every sandbox matching the filter, with all their snapshots and files. Prefer `hatchet.sandbox.delete`. */\n static async delete(client: HatchetClient, opts: SandboxListOpts): Promise<string[]> {\n if (!opts.sandboxId && Object.keys(opts.metadata ?? {}).length === 0)\n throw new Error('delete needs a sandboxId or a metadata filter');\n const run = turnRunner(client);\n const ids: string[] = [];\n for (const { sandboxId } of await Sandbox.list(client, opts)) {\n await run({ fn: '$delete', input: {}, sandboxId });\n ids.push(sandboxId);\n }\n return ids;\n }\n\n /** Runs a shell command with `sh -c` in the workspace and makes a snapshot. A timeout gives `exitCode` 124, not an error. */\n async exec(cmd: string, opts: ExecOpts = {}): Promise<CommandResult> {\n return this.turn<CommandResult>('$command', {\n cmd,\n ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}),\n });\n }\n\n /** Removes the sandbox. Its snapshots stay; `connect` can bring it back. */\n async kill(): Promise<void> {\n await this.turn('$destroy', {});\n }\n\n /** Removes the sandbox and deletes every snapshot and file the provider stored for it. `connect` fails afterwards. */\n async delete(): Promise<void> {\n await this.turn('$delete', {});\n }\n\n private async turn<T = JsonObject>(fn: string, input: JsonObject, fresh = false): Promise<T> {\n const result = await this.run(\n {\n sandboxId: this.sandboxId,\n ...(this.template ? { image: this.template } : {}),\n fn,\n input,\n },\n { fresh }\n );\n return {\n ...result.output,\n snapshotId: result.snapshotId,\n timings: result.timings,\n } as unknown as T;\n }\n}\n\n/** `hatchet.sandbox`, added to `HatchetClient` by importing `@hatchet-dev/sandbox`. */\nexport interface SandboxNamespace {\n /** Starts a new sandbox. Inside a durable task this is a durable step. */\n create(opts?: SandboxOpts): Promise<Sandbox>;\n /** Attaches to a sandbox by ID. If it is not running, the provider starts it from its latest snapshot. */\n connect(sandboxId: string, opts?: ConnectOpts): Promise<Sandbox>;\n /** Lists sandboxes the provider knows, filtered by ID or metadata. */\n list(opts?: SandboxListOpts): Promise<SandboxInfo[]>;\n /** Deletes the sandboxes matching the filter, with every snapshot and file stored for them. Returns their IDs. */\n delete(opts: SandboxListOpts): Promise<string[]>;\n}\n\ndeclare module '@hatchet-dev/typescript-sdk/v1' {\n interface HatchetClient {\n readonly sandbox: SandboxNamespace;\n }\n}\n\nObject.defineProperty(HatchetClient.prototype, 'sandbox', {\n configurable: true,\n get(this: HatchetClient): SandboxNamespace {\n return {\n create: (opts) => Sandbox.create(this, opts),\n connect: (sandboxId, opts) => Sandbox.connect(this, sandboxId, opts),\n list: (opts) => Sandbox.list(this, opts),\n delete: (opts) => Sandbox.delete(this, opts),\n };\n },\n});\n"]}
|
package/package.json
CHANGED
|
@@ -1,25 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hatchet-dev/sandbox",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
|
+
"private": false,
|
|
4
5
|
"description": "Hatchet Sandbox TypeScript SDK",
|
|
5
6
|
"license": "MIT",
|
|
6
7
|
"repository": {
|
|
7
8
|
"type": "git",
|
|
8
|
-
"url": "
|
|
9
|
-
"directory": "sdks/typescript"
|
|
9
|
+
"url": "https://github.com/hatchet-dev/hatchet.git",
|
|
10
|
+
"directory": "sdks/typescript-sandbox"
|
|
10
11
|
},
|
|
12
|
+
"type": "module",
|
|
13
|
+
"sideEffects": true,
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md",
|
|
17
|
+
"CHANGELOG.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"main": "./dist/index.cjs",
|
|
21
|
+
"module": "./dist/index.js",
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
11
23
|
"exports": {
|
|
12
24
|
".": {
|
|
13
25
|
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js",
|
|
27
|
+
"require": "./dist/index.cjs",
|
|
14
28
|
"default": "./dist/index.js"
|
|
15
|
-
}
|
|
29
|
+
},
|
|
30
|
+
"./package.json": "./package.json"
|
|
16
31
|
},
|
|
17
|
-
"
|
|
18
|
-
"
|
|
19
|
-
"CHANGELOG.md"
|
|
20
|
-
],
|
|
21
|
-
"publishConfig": {
|
|
22
|
-
"access": "public"
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@hatchet-dev/typescript-sdk": ">=1.33.1"
|
|
23
34
|
},
|
|
24
35
|
"dependencies": {
|
|
25
36
|
"@opentelemetry/api": "^1.9.0",
|
|
@@ -28,20 +39,34 @@
|
|
|
28
39
|
"@opentelemetry/instrumentation": "^0.221.0",
|
|
29
40
|
"@opentelemetry/sdk-trace-base": "^2.0.0"
|
|
30
41
|
},
|
|
31
|
-
"peerDependencies": {
|
|
32
|
-
"@hatchet-dev/typescript-sdk": ">=1.33.1"
|
|
33
|
-
},
|
|
34
42
|
"devDependencies": {
|
|
35
|
-
"@
|
|
36
|
-
"@
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"
|
|
43
|
+
"@eslint/js": "^10.0.1",
|
|
44
|
+
"@hatchet-dev/typescript-sdk": "file:../typescript/dist",
|
|
45
|
+
"@types/node": "^26.6.3",
|
|
46
|
+
"eslint": "^10.0.3",
|
|
47
|
+
"eslint-config-prettier": "^10.1.8",
|
|
48
|
+
"eslint-plugin-prettier": "^5.5.5",
|
|
49
|
+
"eslint-plugin-unused-imports": "^4.4.1",
|
|
50
|
+
"prettier": "^3.8.1",
|
|
51
|
+
"tsup": "^8.5.1",
|
|
52
|
+
"typescript": "^5.9.3",
|
|
53
|
+
"typescript-eslint": "^8.56.1"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public"
|
|
40
57
|
},
|
|
41
58
|
"scripts": {
|
|
42
|
-
"build": "
|
|
43
|
-
"
|
|
44
|
-
"
|
|
45
|
-
"
|
|
59
|
+
"build:sdk": "cd ../typescript && pnpm install --frozen-lockfile --config.strict-dep-builds=false && pnpm tsc:build && pnpm prepublish",
|
|
60
|
+
"build": "tsup",
|
|
61
|
+
"typecheck": "tsc --noEmit",
|
|
62
|
+
"lint": "pnpm run eslint:check && pnpm run prettier:check",
|
|
63
|
+
"lint:fix": "pnpm run eslint:fix && pnpm run prettier:fix",
|
|
64
|
+
"eslint:check": "eslint \"src/**/*.ts\"",
|
|
65
|
+
"eslint:fix": "eslint \"src/**/*.ts\" --fix",
|
|
66
|
+
"prettier:check": "prettier \"src/**/*.ts\" \"*.md\" --list-different",
|
|
67
|
+
"prettier:fix": "prettier \"src/**/*.ts\" \"*.md\" --write",
|
|
68
|
+
"publish:ci": "pnpm run build && pnpm publish --access public --no-git-checks",
|
|
69
|
+
"publish:ci:alpha": "pnpm run build && pnpm publish --access public --no-git-checks --tag alpha",
|
|
70
|
+
"release:local": "pnpm run build:sdk && pnpm install && pnpm run lint && pnpm run build && pnpm publish --access public --no-git-checks"
|
|
46
71
|
}
|
|
47
72
|
}
|
package/dist/files.d.ts
DELETED
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
import type { JsonObject } from '@hatchet-dev/typescript-sdk/v1';
|
|
2
|
-
export type FileType = 'file' | 'dir';
|
|
3
|
-
export interface EntryInfo {
|
|
4
|
-
name: string;
|
|
5
|
-
path: string;
|
|
6
|
-
type: FileType;
|
|
7
|
-
size: number;
|
|
8
|
-
mode: number;
|
|
9
|
-
permissions: string;
|
|
10
|
-
modifiedTime?: Date;
|
|
11
|
-
}
|
|
12
|
-
export type FileData = string | ArrayBuffer | Uint8Array | Blob;
|
|
13
|
-
export interface WriteEntry {
|
|
14
|
-
path: string;
|
|
15
|
-
data: FileData;
|
|
16
|
-
}
|
|
17
|
-
export interface ReadOpts {
|
|
18
|
-
format?: 'text' | 'bytes' | 'blob';
|
|
19
|
-
}
|
|
20
|
-
export interface TransferOpts {
|
|
21
|
-
/** Give up after this long. */
|
|
22
|
-
timeoutMs?: number;
|
|
23
|
-
}
|
|
24
|
-
export interface ListOpts {
|
|
25
|
-
depth?: number;
|
|
26
|
-
}
|
|
27
|
-
export type FilesystemErrorCode = 'staging_failed' | 'not_found' | 'invalid_path' | 'invalid_url' | 'invalid_content' | 'invalid' | 'is_a_directory' | 'not_a_directory' | 'too_large' | 'transfer_failed';
|
|
28
|
-
/** Thrown for caller mistakes such as a missing file or a path outside the workspace. */
|
|
29
|
-
export declare class FilesystemError extends Error {
|
|
30
|
-
readonly code: FilesystemErrorCode;
|
|
31
|
-
constructor(code: FilesystemErrorCode, message: string);
|
|
32
|
-
}
|
|
33
|
-
type RawEntry = Omit<EntryInfo, 'modifiedTime'> & {
|
|
34
|
-
modifiedTime?: string;
|
|
35
|
-
};
|
|
36
|
-
interface FsOutput extends JsonObject {
|
|
37
|
-
content?: string;
|
|
38
|
-
stagedKey?: string;
|
|
39
|
-
url?: string;
|
|
40
|
-
putUrl?: string;
|
|
41
|
-
getUrl?: string;
|
|
42
|
-
entry?: RawEntry | null;
|
|
43
|
-
entries?: RawEntry[];
|
|
44
|
-
created?: boolean;
|
|
45
|
-
error?: {
|
|
46
|
-
code: FilesystemErrorCode;
|
|
47
|
-
message: string;
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
/** @internal */
|
|
51
|
-
export type FsTurn = (fn: string, input: JsonObject) => Promise<FsOutput>;
|
|
52
|
-
/** File operations on a sandbox workspace. Paths are relative to the workspace. Each call is one Hatchet task. */
|
|
53
|
-
export declare class Files {
|
|
54
|
-
private readonly turn;
|
|
55
|
-
/** @internal */
|
|
56
|
-
constructor(turn: FsTurn);
|
|
57
|
-
private call;
|
|
58
|
-
/** Reads a file as text (default), bytes, or a Blob. Files over the provider's `--max-file-bytes` (2 MiB) come through the provider's `--store` instead of Hatchet. */
|
|
59
|
-
read(path: string, opts?: ReadOpts & {
|
|
60
|
-
format?: 'text';
|
|
61
|
-
}): Promise<string>;
|
|
62
|
-
read(path: string, opts: ReadOpts & {
|
|
63
|
-
format: 'bytes';
|
|
64
|
-
}): Promise<Uint8Array>;
|
|
65
|
-
read(path: string, opts: ReadOpts & {
|
|
66
|
-
format: 'blob';
|
|
67
|
-
}): Promise<Blob>;
|
|
68
|
-
/** A replayed durable read may hold a URL that has expired; the provider signs the same staged file again. */
|
|
69
|
-
private readStaged;
|
|
70
|
-
/** Writes one file or several. Parent directories are created. Bytes are stored exactly. Files over 2 MiB go through the provider's `--store` instead of Hatchet. */
|
|
71
|
-
write(path: string, data: FileData): Promise<EntryInfo>;
|
|
72
|
-
write(files: WriteEntry[]): Promise<EntryInfo[]>;
|
|
73
|
-
/** Writes several files in one task. */
|
|
74
|
-
writeFiles(files: WriteEntry[]): Promise<EntryInfo[]>;
|
|
75
|
-
/** Lists a directory. `depth` 1 (default) is the directory itself; higher values recurse. No snapshot is made. */
|
|
76
|
-
list(path?: string, opts?: ListOpts): Promise<EntryInfo[]>;
|
|
77
|
-
/** True if the path exists. No snapshot is made. */
|
|
78
|
-
exists(path: string): Promise<boolean>;
|
|
79
|
-
/** Metadata of a file or directory. Throws `FilesystemError` with code `not_found` if absent. */
|
|
80
|
-
getInfo(path: string): Promise<EntryInfo>;
|
|
81
|
-
/** Creates a directory and its parents. Returns false if it already existed. */
|
|
82
|
-
makeDir(path: string): Promise<boolean>;
|
|
83
|
-
/** Renames or moves a file or directory. */
|
|
84
|
-
rename(oldPath: string, newPath: string): Promise<EntryInfo>;
|
|
85
|
-
/** Copies a file or directory tree. */
|
|
86
|
-
copy(srcPath: string, dstPath: string): Promise<EntryInfo>;
|
|
87
|
-
/** Deletes a file or directory tree. */
|
|
88
|
-
remove(path: string): Promise<void>;
|
|
89
|
-
/** The provider fetches an https URL into the workspace. The sandbox needs no network. Private and loopback addresses are refused. */
|
|
90
|
-
download(url: string, path: string, opts?: TransferOpts): Promise<EntryInfo>;
|
|
91
|
-
/** The provider sends a workspace file to an https URL with HTTP PUT, for example a presigned URL. */
|
|
92
|
-
upload(path: string, url: string, opts?: TransferOpts): Promise<void>;
|
|
93
|
-
}
|
|
94
|
-
export {};
|