runwork 0.9.4 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/agents/__tests__/intro-skill.test.js +6 -2
  2. package/dist/agents/codex.js +9 -3
  3. package/dist/api/__tests__/client.test.js +10 -2
  4. package/dist/api/client.js +5 -4
  5. package/dist/auth/__tests__/login-flow.test.js +57 -81
  6. package/dist/auth/__tests__/store.test.js +35 -6
  7. package/dist/commands/__tests__/upgrade.test.js +25 -42
  8. package/dist/commands/clone.d.ts +2 -2
  9. package/dist/commands/clone.js +39 -7
  10. package/dist/commands/dev.js +9 -1
  11. package/dist/commands/endpoints.js +2 -1
  12. package/dist/commands/files.js +3 -2
  13. package/dist/commands/init.d.ts +2 -2
  14. package/dist/commands/init.js +34 -5
  15. package/dist/commands/upgrade.js +4 -3
  16. package/dist/commands/welcome.js +2 -2
  17. package/dist/devtools/registry-data.d.ts +7 -0
  18. package/dist/devtools/registry-data.js +1 -0
  19. package/dist/generated/version.d.ts +1 -1
  20. package/dist/generated/version.js +1 -1
  21. package/dist/git/__tests__/credentials.test.js +4 -4
  22. package/dist/git/__tests__/identity.test.d.ts +1 -0
  23. package/dist/git/__tests__/identity.test.js +146 -0
  24. package/dist/git/__tests__/preflight.test.d.ts +1 -0
  25. package/dist/git/__tests__/preflight.test.js +36 -0
  26. package/dist/git/auto-commit.js +8 -2
  27. package/dist/git/credentials.js +1 -1
  28. package/dist/git/identity.d.ts +44 -0
  29. package/dist/git/identity.js +133 -0
  30. package/dist/git/preflight.d.ts +28 -0
  31. package/dist/git/preflight.js +50 -0
  32. package/dist/git/sync.js +3 -1
  33. package/dist/health/__tests__/cli-distribution-checks.test.js +25 -28
  34. package/dist/health/checks.js +3 -2
  35. package/dist/index.js +32 -1
  36. package/dist/utils/__tests__/format-error.test.d.ts +1 -0
  37. package/dist/utils/__tests__/format-error.test.js +43 -0
  38. package/dist/utils/__tests__/http.test.d.ts +1 -0
  39. package/dist/utils/__tests__/http.test.js +381 -0
  40. package/dist/utils/agent-guidance.js +10 -3
  41. package/dist/utils/format-error.d.ts +10 -0
  42. package/dist/utils/format-error.js +38 -0
  43. package/dist/utils/http.d.ts +46 -0
  44. package/dist/utils/http.js +421 -0
  45. package/package.json +3 -2
@@ -20,13 +20,19 @@ export const APP_STRUCTURE = {
20
20
  };
21
21
  const COMMON_TIPS = [
22
22
  'Read CLAUDE.md in the app directory first -- it has complete framework documentation with code examples.',
23
- 'You do NOT need git commands. runwork dev handles file syncing automatically.',
23
+ 'You do NOT need to run git commands manually. runwork dev handles file syncing automatically. (git itself must be installed on the system -- see dependencies.)',
24
24
  'Do NOT install external AI SDKs (openai, @anthropic-ai/sdk). Use @runworkai/framework/ai instead.',
25
25
  'Every workflow MUST have a trigger (API endpoint, scheduled job, or UI button). Workflows without triggers are dead code.',
26
26
  'Every conversational agent MUST have a frontend page to access it.',
27
27
  'After adding entities, workflows, or agents, update blueprint.json with the new metadata.',
28
28
  'Never guess integration IDs. Run: runwork integrations search <query>',
29
29
  ];
30
+ /**
31
+ * Required system dependencies for the Runwork CLI to function. The AI agent
32
+ * reading these guides should verify each is installed and install missing
33
+ * ones for the user using whatever method is appropriate for their platform.
34
+ */
35
+ const SYSTEM_DEPENDENCIES_NOTE = 'System dependency: git must be installed on this machine. The CLI uses git internally to sync files between local and the workspace remote. Verify with: git --version. If missing, the AI agent reading this guide should install git for the user without prompting -- pick the method that fits the platform: macOS uses "brew install git" (or "xcode-select --install" if Homebrew is unavailable); Debian/Ubuntu uses "sudo apt-get update && sudo apt-get install -y git"; Fedora/RHEL uses "sudo dnf install -y git"; Arch uses "sudo pacman -S --noconfirm git"; Windows uses "winget install --id Git.Git -e" or "choco install git -y". After installing, re-verify with git --version before continuing.';
30
36
  export function buildInitGuide(appName, dir) {
31
37
  return {
32
38
  context: 'Created a Runwork app -- a full-stack Cloudflare Workers application with built-in support for persistent data (entities), background jobs (schedules), multi-step durable processes (workflows), AI agents, public APIs, and third-party integrations. The app runs in a sandbox during development and deploys to Cloudflare Workers for production.',
@@ -52,7 +58,7 @@ export function buildCloneGuide(appName, dir) {
52
58
  'Edit files for your needs',
53
59
  'runwork deploy # deploy to production when ready',
54
60
  ],
55
- tips: COMMON_TIPS,
61
+ tips: [SYSTEM_DEPENDENCIES_NOTE, ...COMMON_TIPS],
56
62
  learnMore: 'Read CLAUDE.md in the app directory for complete framework documentation.',
57
63
  };
58
64
  }
@@ -65,7 +71,8 @@ export function buildDevSessionGuide() {
65
71
  'Run runwork deploy in another terminal when ready for production',
66
72
  ],
67
73
  tips: [
68
- 'You do NOT need git commands. The dev server handles all file syncing.',
74
+ SYSTEM_DEPENDENCIES_NOTE,
75
+ 'You in normal cases do NOT need to run git commands manually. The dev server handles all file syncing (it shells out to the system git binary, which must be installed).',
69
76
  'If the preview seems stuck, try runwork dev again to restart the session.',
70
77
  ],
71
78
  };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Render an unknown thrown value as a single human-readable line. Tailored
3
+ * for `execFileSync` failures (which carry stderr/stdout buffers, an `errno`
4
+ * code, and a `message` like "Command failed: git ...") so the most useful
5
+ * piece of information surfaces first.
6
+ *
7
+ * Used by command entry points that have a `stdio: 'pipe'` git invocation
8
+ * to keep the diagnostic from being silently dropped.
9
+ */
10
+ export declare function formatError(err: unknown): string;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Render an unknown thrown value as a single human-readable line. Tailored
3
+ * for `execFileSync` failures (which carry stderr/stdout buffers, an `errno`
4
+ * code, and a `message` like "Command failed: git ...") so the most useful
5
+ * piece of information surfaces first.
6
+ *
7
+ * Used by command entry points that have a `stdio: 'pipe'` git invocation
8
+ * to keep the diagnostic from being silently dropped.
9
+ */
10
+ export function formatError(err) {
11
+ if (!err)
12
+ return 'unknown error';
13
+ if (err instanceof Error) {
14
+ const obj = err;
15
+ const stderr = bufToStr(obj.stderr);
16
+ const stdout = bufToStr(obj.stdout);
17
+ const detail = stderr || stdout;
18
+ if (detail) {
19
+ // Common case for ENOENT: errno -> "git ENOENT: no such file or directory"
20
+ if (obj.code)
21
+ return `${obj.code}: ${detail}`;
22
+ return detail;
23
+ }
24
+ if (obj.code)
25
+ return `${obj.code}: ${obj.message}`;
26
+ return obj.message || String(err);
27
+ }
28
+ return String(err);
29
+ }
30
+ function bufToStr(value) {
31
+ if (!value)
32
+ return '';
33
+ if (typeof value === 'string')
34
+ return value.trim();
35
+ if (Buffer.isBuffer(value))
36
+ return value.toString('utf-8').trim();
37
+ return '';
38
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Minimal `fetch`-like HTTP client built on `node:http` / `node:https`.
3
+ *
4
+ * Why this exists rather than calling `fetch` directly:
5
+ * 1) Single seam for diagnostics, retries, transport swaps, etc., without
6
+ * touching every call site.
7
+ * 2) Opt-in `curl` transport (set `RUNWORK_HTTP_TRANSPORT=curl`) as a
8
+ * break-glass: it shells out to the system `curl` binary so HTTP runs
9
+ * in a subprocess, immune to any runtime regression in the Bun-compiled
10
+ * binary. We've kept it after needing it once on an older Bun version.
11
+ *
12
+ * Default transport is `node:https` on every platform. Surface mirrors
13
+ * enough of the standard `Response` API for call sites to swap from
14
+ * `fetch(...)` to `httpFetch(...)` with no other change. Out of scope:
15
+ * streaming bodies, AbortController, ReadableStream request bodies, the
16
+ * `cache` option. This is a workaround layer, not a fetch polyfill.
17
+ */
18
+ export interface HttpRequestInit {
19
+ method?: string;
20
+ headers?: Record<string, string | undefined> | Headers;
21
+ body?: string | Uint8Array | ArrayBuffer | Buffer | null;
22
+ /** Accepted for compatibility with `fetch(..., { cache: 'no-store' })`; ignored. */
23
+ cache?: string;
24
+ /** Accepted for compatibility; ignored (no AbortController support yet). */
25
+ signal?: AbortSignal;
26
+ }
27
+ export interface HttpResponse {
28
+ readonly ok: boolean;
29
+ readonly status: number;
30
+ readonly statusText: string;
31
+ readonly headers: Headers;
32
+ readonly url: string;
33
+ text(): Promise<string>;
34
+ json<T = unknown>(): Promise<T>;
35
+ arrayBuffer(): Promise<ArrayBuffer>;
36
+ }
37
+ /**
38
+ * Available HTTP transports. `node` is the default everywhere. `curl` is an
39
+ * opt-in escape hatch (set the `RUNWORK_HTTP_TRANSPORT=curl` env var) that
40
+ * shells out to `curl.exe` / `curl` for each request, sidestepping the
41
+ * runtime's native HTTP stack entirely. We keep it around as break-glass
42
+ * for any future Bun runtime regression on Windows; see file header.
43
+ */
44
+ export type HttpTransport = 'auto' | 'node' | 'curl';
45
+ export declare function __setTransportForTests(t: HttpTransport): void;
46
+ export declare function httpFetch(url: string, init?: HttpRequestInit): Promise<HttpResponse>;
@@ -0,0 +1,421 @@
1
+ /**
2
+ * Minimal `fetch`-like HTTP client built on `node:http` / `node:https`.
3
+ *
4
+ * Why this exists rather than calling `fetch` directly:
5
+ * 1) Single seam for diagnostics, retries, transport swaps, etc., without
6
+ * touching every call site.
7
+ * 2) Opt-in `curl` transport (set `RUNWORK_HTTP_TRANSPORT=curl`) as a
8
+ * break-glass: it shells out to the system `curl` binary so HTTP runs
9
+ * in a subprocess, immune to any runtime regression in the Bun-compiled
10
+ * binary. We've kept it after needing it once on an older Bun version.
11
+ *
12
+ * Default transport is `node:https` on every platform. Surface mirrors
13
+ * enough of the standard `Response` API for call sites to swap from
14
+ * `fetch(...)` to `httpFetch(...)` with no other change. Out of scope:
15
+ * streaming bodies, AbortController, ReadableStream request bodies, the
16
+ * `cache` option. This is a workaround layer, not a fetch polyfill.
17
+ */
18
+ import { request as httpRequest } from 'node:http';
19
+ import { request as httpsRequest } from 'node:https';
20
+ import { URL } from 'node:url';
21
+ import { spawn } from 'node:child_process';
22
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
23
+ import { tmpdir } from 'node:os';
24
+ import { join } from 'node:path';
25
+ import { createBrotliDecompress, createGunzip, createInflate, createInflateRaw, } from 'node:zlib';
26
+ const MAX_REDIRECTS = 10;
27
+ let transportOverride = 'auto';
28
+ export function __setTransportForTests(t) { transportOverride = t; }
29
+ function pickTransport() {
30
+ if (transportOverride === 'curl')
31
+ return 'curl';
32
+ if (transportOverride === 'node')
33
+ return 'node';
34
+ const env = (process.env.RUNWORK_HTTP_TRANSPORT || '').toLowerCase().trim();
35
+ if (env === 'curl')
36
+ return 'curl';
37
+ return 'node';
38
+ }
39
+ export async function httpFetch(url, init = {}) {
40
+ const transport = pickTransport();
41
+ if (transport === 'curl')
42
+ return curlFetch(url, init);
43
+ return doRequest(url, init, 0);
44
+ }
45
+ async function doRequest(url, init, redirectCount) {
46
+ const parsed = new URL(url);
47
+ const isHttps = parsed.protocol === 'https:';
48
+ const isHttp = parsed.protocol === 'http:';
49
+ if (!isHttps && !isHttp) {
50
+ throw new Error(`Unsupported protocol "${parsed.protocol}" -- only http: and https: are supported.`);
51
+ }
52
+ const requestFn = isHttps ? httpsRequest : httpRequest;
53
+ const headers = normalizeHeaders(init.headers);
54
+ const method = (init.method || 'GET').toUpperCase();
55
+ const isBodylessMethod = method === 'GET' || method === 'HEAD';
56
+ const bodyBuffer = isBodylessMethod ? null : bodyToBuffer(init.body);
57
+ if (bodyBuffer && headers['content-length'] === undefined) {
58
+ headers['content-length'] = String(bodyBuffer.byteLength);
59
+ }
60
+ // Match `fetch`'s default of advertising compression support. We
61
+ // transparently decompress gzip/deflate/br responses below.
62
+ if (headers['accept-encoding'] === undefined) {
63
+ headers['accept-encoding'] = 'gzip, deflate, br';
64
+ }
65
+ const requestOptions = {
66
+ method,
67
+ headers,
68
+ };
69
+ return new Promise((resolve, reject) => {
70
+ const req = requestFn(url, requestOptions, (res) => {
71
+ const status = res.statusCode ?? 0;
72
+ // Follow redirects manually so behavior matches `fetch`. We wait for
73
+ // the previous response to fully drain before starting the recursive
74
+ // request: guarantees socket cleanup ordering and avoids leaking
75
+ // the previous request when the new one fails.
76
+ const location = res.headers.location;
77
+ if (status >= 300 && status < 400 && location && redirectCount < MAX_REDIRECTS) {
78
+ res.resume();
79
+ res.once('end', () => {
80
+ let nextUrl;
81
+ try {
82
+ nextUrl = new URL(location, url).toString();
83
+ }
84
+ catch (err) {
85
+ reject(err);
86
+ return;
87
+ }
88
+ const shouldDowngradeToGet = status === 303 ||
89
+ ((status === 301 || status === 302) && method !== 'GET' && method !== 'HEAD');
90
+ const nextInit = shouldDowngradeToGet
91
+ ? { ...init, method: 'GET', body: undefined }
92
+ : init;
93
+ doRequest(nextUrl, nextInit, redirectCount + 1).then(resolve, reject);
94
+ });
95
+ res.once('error', reject);
96
+ return;
97
+ }
98
+ // Decompress gzip / deflate / br transparently to match fetch.
99
+ const decoded = decompressedStream(res);
100
+ const chunks = [];
101
+ decoded.on('data', (chunk) => {
102
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
103
+ });
104
+ decoded.on('end', () => {
105
+ const buffer = Buffer.concat(chunks);
106
+ // For HEAD responses there is no body; preserve the empty buffer.
107
+ resolve(buildResponse(url, res, status, buffer));
108
+ });
109
+ decoded.on('error', reject);
110
+ // Surface upstream socket errors too when we are reading through a
111
+ // decompressor (the transformed stream wouldn't otherwise see them).
112
+ if (decoded !== res) {
113
+ res.on('error', reject);
114
+ }
115
+ });
116
+ req.on('error', reject);
117
+ if (bodyBuffer)
118
+ req.write(bodyBuffer);
119
+ req.end();
120
+ });
121
+ }
122
+ function normalizeHeaders(input) {
123
+ const out = {};
124
+ if (!input)
125
+ return out;
126
+ if (input instanceof Headers) {
127
+ input.forEach((value, key) => {
128
+ out[key.toLowerCase()] = value;
129
+ });
130
+ return out;
131
+ }
132
+ for (const [key, value] of Object.entries(input)) {
133
+ if (value === undefined || value === null)
134
+ continue;
135
+ out[key.toLowerCase()] = String(value);
136
+ }
137
+ return out;
138
+ }
139
+ function bodyToBuffer(body) {
140
+ if (body === undefined || body === null)
141
+ return null;
142
+ if (typeof body === 'string')
143
+ return Buffer.from(body, 'utf-8');
144
+ if (Buffer.isBuffer(body))
145
+ return body;
146
+ if (body instanceof Uint8Array)
147
+ return Buffer.from(body.buffer, body.byteOffset, body.byteLength);
148
+ if (body instanceof ArrayBuffer)
149
+ return Buffer.from(new Uint8Array(body));
150
+ throw new TypeError('Unsupported request body type');
151
+ }
152
+ function decompressedStream(res) {
153
+ // Per RFC 7230, Content-Encoding may be a comma-separated list of
154
+ // transformations applied in order. Unwrap them in reverse, but in
155
+ // practice servers send a single encoding so the simple cases dominate.
156
+ const raw = (res.headers['content-encoding'] || '').toString().toLowerCase().trim();
157
+ if (!raw || raw === 'identity')
158
+ return res;
159
+ const encodings = raw.split(',').map((s) => s.trim()).filter(Boolean).reverse();
160
+ let stream = res;
161
+ for (const enc of encodings) {
162
+ let decoder = null;
163
+ if (enc === 'gzip' || enc === 'x-gzip')
164
+ decoder = createGunzip();
165
+ else if (enc === 'br')
166
+ decoder = createBrotliDecompress();
167
+ else if (enc === 'deflate')
168
+ decoder = createInflate();
169
+ else if (enc === 'deflate-raw')
170
+ decoder = createInflateRaw();
171
+ else
172
+ continue; // unknown encoding -- pass bytes through
173
+ stream.pipe(decoder);
174
+ stream = decoder;
175
+ }
176
+ return stream;
177
+ }
178
+ function buildResponse(url, res, status, buffer) {
179
+ const headers = new Headers();
180
+ for (const [name, value] of Object.entries(res.headers)) {
181
+ if (value === undefined)
182
+ continue;
183
+ if (Array.isArray(value)) {
184
+ for (const v of value)
185
+ headers.append(name, v);
186
+ }
187
+ else {
188
+ headers.set(name, value);
189
+ }
190
+ }
191
+ return {
192
+ ok: status >= 200 && status < 300,
193
+ status,
194
+ statusText: res.statusMessage ?? '',
195
+ headers,
196
+ url,
197
+ async text() {
198
+ return buffer.toString('utf-8');
199
+ },
200
+ async json() {
201
+ const text = buffer.toString('utf-8');
202
+ return JSON.parse(text);
203
+ },
204
+ async arrayBuffer() {
205
+ // Slice the underlying buffer so the returned ArrayBuffer matches the
206
+ // exact byte range and is independent of Node's internal pool.
207
+ const copy = new Uint8Array(buffer.byteLength);
208
+ copy.set(buffer);
209
+ return copy.buffer;
210
+ },
211
+ };
212
+ }
213
+ // ────────────────────────────────────────────────────────────────────────
214
+ // curl-based transport (Windows workaround)
215
+ //
216
+ // On Windows we spawn `curl.exe` for every HTTP call so we never touch
217
+ // Bun's broken HTTP runtime in the standalone binary. The subprocess
218
+ // approach trades a few tens of milliseconds of process-spawn overhead per
219
+ // request for rock-solid reliability. Curl ships at
220
+ // C:\Windows\System32\curl.exe on Windows 10+ since 2018.
221
+ //
222
+ // Layout:
223
+ // - body → written by curl to a temp file (--output)
224
+ // - response hdrs → written by curl to a temp file (--dump-header)
225
+ // - status/url → printed by curl to stdout via --write-out
226
+ //
227
+ // We never let body bytes share a stream with metadata, so binary
228
+ // downloads (zip skeletons, presigned URL fetches) round-trip cleanly.
229
+ // ────────────────────────────────────────────────────────────────────────
230
+ async function curlFetch(url, init) {
231
+ return curlFetchOnce(url, init, 0);
232
+ }
233
+ async function curlFetchOnce(url, init, redirectCount) {
234
+ // Quick URL sanity check so we throw the same way the node:https path
235
+ // does for unsupported protocols, before paying the spawn cost.
236
+ const parsed = new URL(url);
237
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
238
+ throw new Error(`Unsupported protocol "${parsed.protocol}" -- only http: and https: are supported.`);
239
+ }
240
+ const headers = normalizeHeaders(init.headers);
241
+ const method = (init.method || 'GET').toUpperCase();
242
+ const isBodyless = method === 'GET' || method === 'HEAD';
243
+ const bodyBuffer = isBodyless ? null : bodyToBuffer(init.body);
244
+ if (headers['accept-encoding'] === undefined) {
245
+ headers['accept-encoding'] = 'identity';
246
+ }
247
+ // Per-call temp directory keeps cleanup simple and concurrent calls from
248
+ // racing on shared filenames.
249
+ const tmp = mkdtempSync(join(tmpdir(), 'runwork-curl-'));
250
+ const bodyOutPath = join(tmp, 'body.bin');
251
+ const headerOutPath = join(tmp, 'headers.txt');
252
+ const args = [
253
+ '--silent',
254
+ '--show-error',
255
+ // We deliberately do NOT pass --location. curl's redirect-method
256
+ // semantics differ subtly from fetch's (notably curl can preserve
257
+ // POST across 303 in some versions despite the spec). We follow
258
+ // redirects ourselves below so behavior matches the node:https
259
+ // transport exactly.
260
+ '--output', bodyOutPath, // body to file (binary safe)
261
+ '--dump-header', headerOutPath, // response headers to file
262
+ '--write-out', '%{http_code}\n%{url_effective}\n',
263
+ ];
264
+ if (method === 'HEAD') {
265
+ // --head sends HEAD AND tells curl not to expect a body, otherwise
266
+ // curl hangs waiting for body bytes. The downside is that --head also
267
+ // writes the response headers into the --output body file -- we work
268
+ // around that below by ignoring the body buffer when method is HEAD.
269
+ args.push('--head');
270
+ }
271
+ else if (method !== 'GET') {
272
+ args.push('--request', method);
273
+ }
274
+ // Curl's default already follows fetch semantics on 301/302/303 (downgrade
275
+ // POST to GET). We do NOT pass --post30x because those flags violate that
276
+ // default and force POST to be preserved across redirects.
277
+ for (const [name, value] of Object.entries(headers)) {
278
+ args.push('--header', `${name}: ${value}`);
279
+ }
280
+ if (bodyBuffer) {
281
+ // Read request body from stdin so we don't have to write it to disk.
282
+ args.push('--data-binary', '@-');
283
+ }
284
+ args.push(url);
285
+ // Async spawn: spawnSync would block the event loop, which deadlocks
286
+ // unit tests (the test server lives in the same Node worker, can't
287
+ // service curl's connection while we're blocked). The async path is
288
+ // also strictly nicer for any future caller that wants to overlap
289
+ // requests.
290
+ const result = await new Promise((resolve) => {
291
+ const child = spawn('curl', args, { windowsHide: true });
292
+ const stdoutChunks = [];
293
+ const stderrChunks = [];
294
+ child.stdout.on('data', (c) => stdoutChunks.push(c));
295
+ child.stderr.on('data', (c) => stderrChunks.push(c));
296
+ child.on('error', (err) => resolve({
297
+ status: -1,
298
+ stdout: Buffer.concat(stdoutChunks).toString('utf-8'),
299
+ stderr: Buffer.concat(stderrChunks).toString('utf-8'),
300
+ error: err,
301
+ }));
302
+ child.on('close', (code) => resolve({
303
+ status: code ?? -1,
304
+ stdout: Buffer.concat(stdoutChunks).toString('utf-8'),
305
+ stderr: Buffer.concat(stderrChunks).toString('utf-8'),
306
+ }));
307
+ if (bodyBuffer) {
308
+ child.stdin.write(bodyBuffer);
309
+ }
310
+ child.stdin.end();
311
+ });
312
+ if (result.error) {
313
+ safeRm(tmp);
314
+ throw result.error;
315
+ }
316
+ const stdoutLines = result.stdout.trim().split(/\r?\n/);
317
+ const statusLine = stdoutLines[0] || '0';
318
+ const finalUrl = stdoutLines[1] || url;
319
+ const status = Number.parseInt(statusLine, 10) || 0;
320
+ if (status === 0) {
321
+ // curl never received a response, or exited before writing the status.
322
+ const stderr = result.stderr.trim();
323
+ safeRm(tmp);
324
+ throw new Error(`curl failed (exit ${result.status}): ${stderr || 'no error output'}`);
325
+ }
326
+ let bodyBuf;
327
+ try {
328
+ bodyBuf = readFileSync(bodyOutPath);
329
+ }
330
+ catch {
331
+ bodyBuf = Buffer.alloc(0);
332
+ }
333
+ // For HEAD, --head causes curl to write the response status line + headers
334
+ // into the body output file (since there is no real body to write). Strip
335
+ // it so callers see an empty body, matching fetch's HEAD behavior.
336
+ if (method === 'HEAD') {
337
+ bodyBuf = Buffer.alloc(0);
338
+ }
339
+ let headerText = '';
340
+ try {
341
+ headerText = readFileSync(headerOutPath, 'utf-8');
342
+ }
343
+ catch {
344
+ // best-effort
345
+ }
346
+ safeRm(tmp);
347
+ // After redirects curl writes one header block per hop; the LAST block is
348
+ // the response we actually want to expose to the caller.
349
+ const blocks = headerText.split(/\r?\n\r?\n/).map((b) => b.trim()).filter(Boolean);
350
+ const finalBlock = blocks[blocks.length - 1] || '';
351
+ const finalLines = finalBlock.split(/\r?\n/);
352
+ // Pull statusText off the HTTP/x.y NNN <reason> status line if present.
353
+ let statusText = '';
354
+ if (finalLines.length > 0 && finalLines[0].startsWith('HTTP/')) {
355
+ const match = finalLines[0].match(/^HTTP\/\S+\s+\d+\s*(.*)$/);
356
+ if (match)
357
+ statusText = match[1].trim();
358
+ }
359
+ const responseHeaders = new Headers();
360
+ for (const line of finalLines) {
361
+ if (line.startsWith('HTTP/'))
362
+ continue;
363
+ const colon = line.indexOf(':');
364
+ if (colon < 0)
365
+ continue;
366
+ const name = line.slice(0, colon).trim();
367
+ const value = line.slice(colon + 1).trim();
368
+ if (!name)
369
+ continue;
370
+ responseHeaders.append(name, value);
371
+ }
372
+ // Manual redirect handling so curl and node:https behave identically.
373
+ // 303 always downgrades to GET; 301/302 downgrade non-GET/HEAD to GET;
374
+ // 307/308 preserve method and body.
375
+ const location = responseHeaders.get('location');
376
+ if (status >= 300 && status < 400 && location && redirectCount < MAX_REDIRECTS) {
377
+ let nextUrl;
378
+ try {
379
+ nextUrl = new URL(location, url).toString();
380
+ }
381
+ catch (err) {
382
+ throw err;
383
+ }
384
+ const shouldDowngradeToGet = status === 303 ||
385
+ ((status === 301 || status === 302) && method !== 'GET' && method !== 'HEAD');
386
+ const nextInit = shouldDowngradeToGet
387
+ ? { ...init, method: 'GET', body: undefined }
388
+ : init;
389
+ return curlFetchOnce(nextUrl, nextInit, redirectCount + 1);
390
+ }
391
+ // Mirror the node-path warning on unexpected encoding so the diagnostics
392
+ // are consistent across platforms.
393
+ const enc = (responseHeaders.get('content-encoding') || '').toLowerCase().trim();
394
+ if (enc && enc !== 'identity') {
395
+ try {
396
+ process.stderr.write(`[http] warning: server returned Content-Encoding: ${enc} despite Accept-Encoding: identity; ` +
397
+ `body returned as raw bytes (${url}).\n`);
398
+ }
399
+ catch { /* ignore */ }
400
+ }
401
+ return {
402
+ ok: status >= 200 && status < 300,
403
+ status,
404
+ statusText,
405
+ headers: responseHeaders,
406
+ url: finalUrl,
407
+ async text() { return bodyBuf.toString('utf-8'); },
408
+ async json() { return JSON.parse(bodyBuf.toString('utf-8')); },
409
+ async arrayBuffer() {
410
+ const copy = new Uint8Array(bodyBuf.byteLength);
411
+ copy.set(bodyBuf);
412
+ return copy.buffer;
413
+ },
414
+ };
415
+ }
416
+ function safeRm(path) {
417
+ try {
418
+ rmSync(path, { recursive: true, force: true });
419
+ }
420
+ catch { /* best-effort */ }
421
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "runwork",
3
- "version": "0.9.4",
3
+ "version": "0.10.0",
4
4
  "description": "CLI for Runwork: develop, preview, and deploy Runwork apps from your local machine.",
5
5
  "license": "UNLICENSED",
6
6
  "author": "Runwork <info@runwork.ai> (https://www.runwork.ai)",
@@ -56,7 +56,8 @@
56
56
  "vitest": "^3.2.0"
57
57
  },
58
58
  "engines": {
59
- "node": ">=22.5.0"
59
+ "node": ">=22.5.0",
60
+ "bun": ">=1.3.13"
60
61
  },
61
62
  "files": [
62
63
  "dist/**/*.js",