flypod 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,8 @@ npx flypod ./dist
10
10
  ## How it works
11
11
 
12
12
  - **No auth to deploy** — POST a zip, receive a URL + one-time tokens
13
- - **Ephemeral by default** — anonymous deploys expire in 14 days; there are no accounts in v0.1. User accounts and site claiming (to keep a site alive past expiry) are on the roadmap, not yet shipped
13
+ - **Ephemeral by default** — anonymous deploys expire in 14 days
14
+ - **Optional accounts** — sign in once at [`flypod.dev/account`](https://flypod.dev/account) and every site you've deployed from that browser becomes permanently yours. CLI keys (`fk_...`) drop anonymous expiry too. See [`docs/identity.md`](https://github.com/sdserranog/flypod/blob/main/docs/identity.md)
14
15
  - **Rollback built-in** — every deploy is versioned; roll back with a single call
15
16
  - **Render loop** — optional headless screenshot + console capture on every deploy
16
17
 
@@ -39,12 +40,16 @@ What you see:
39
40
  https://ab12cd34.flypod.dev
40
41
  ────────────────────────────────────────────────────────
41
42
 
42
- manage token <token>
43
- save it — needed to redeploy or roll back
44
-
45
43
  expires in 14 days · ephemeral by default
44
+
45
+ ship a change flypod update (new version of this site)
46
+ roll back flypod rollback
47
+ history flypod versions
46
48
  ```
47
49
 
50
+ `flypod` always creates a **new site**. To ship changes to the *same* site as a
51
+ new version, use `flypod update` (see below) — not `flypod` again.
52
+
48
53
  ### Agent-friendly modes
49
54
 
50
55
  The CLI detects whether stderr is a TTY. When piped (or under an agent), the
@@ -108,6 +113,47 @@ flypod
108
113
 
109
114
  ---
110
115
 
116
+ ## Versions and rollback
117
+
118
+ Every deploy is a **version**, identified by the content hash of its files.
119
+ `flypod` creates a brand-new site; `flypod update` adds a version to a site you
120
+ already made and points the live URL at it. Old versions are kept, so rollback
121
+ is instant. Re-deploying identical content is a no-op (same hash → same
122
+ version).
123
+
124
+ ```sh
125
+ flypod ./dist # deploy v1 → new site, prints the URL
126
+ flypod update # ship changes to that same site → v2 (now live)
127
+ flypod versions # list every version, newest first (live one marked)
128
+ flypod rollback # make the previous version live again
129
+ flypod rollback <id> # roll back to a specific version (full id or a prefix)
130
+ ```
131
+
132
+ **How `update`/`versions`/`rollback` find the site.** On the first deploy,
133
+ flypod records which site a folder maps to under your config dir
134
+ (`projects.json`, next to the session — **never written into your repo**). From
135
+ that folder the commands need no flags. The registry is self-cleaning: entries
136
+ for expired sites are pruned automatically and it is capped at 64 projects.
137
+
138
+ To act on a site from anywhere — or in a stateless agent that kept the
139
+ `site_id` from the deploy output — pass `--site`:
140
+
141
+ ```sh
142
+ flypod update --site <id> ./dist
143
+ flypod versions --site <id>
144
+ flypod rollback --site <id> <version>
145
+ flypod forget [--site <id>] # drop the folder→site memory
146
+ ```
147
+
148
+ **Auth.** Owned sites (after `flypod login`) authorize by your account key.
149
+ Anonymous sites use a per-site manage token, which flypod stashes in the
150
+ registry for you — pass `--token <manage_token>` to use one from a machine that
151
+ doesn't remember it.
152
+
153
+ `--json` is supported on all three for stable, scriptable output.
154
+
155
+ ---
156
+
111
157
  ## Library
112
158
 
113
159
  ```ts
@@ -141,11 +187,12 @@ Returns a `DeployResult`:
141
187
  interface DeployResult {
142
188
  site_id: string;
143
189
  slug: string;
144
- url: string; // live URL
190
+ url: string; // live URL
145
191
  version_id: string;
146
- expires_at: number; // unix ms; anonymous sites expire 14 days out
147
- claim_token: string; // reserved for forward-compat; claiming not live in v0.1
148
- manage_token: string; // one-time; redeploy, rollback, delete
192
+ expires_at: number | null; // unix ms when anonymous, null when owned (authenticated)
193
+ claim_token?: string; // per-site claim token when anonymous; omitted when owned
194
+ manage_token: string; // one-time; redeploy, rollback, delete
195
+ owner_account_id?: string; // present on authenticated deploys (cookie or API key)
149
196
  next_actions: unknown[];
150
197
  }
151
198
  ```
@@ -156,9 +203,12 @@ Reads a local directory into a `Record<string, Uint8Array>` map for `deploySite`
156
203
 
157
204
  ---
158
205
 
159
- ## Managing a site
206
+ ## Managing a site (HTTP)
160
207
 
161
- All management calls use the `manage_token` returned on first deploy.
208
+ The CLI commands above (`update`, `versions`, `rollback`) wrap these endpoints —
209
+ reach for raw HTTP only when scripting against the API directly. All management
210
+ calls authorize with the `manage_token` returned on first deploy (or an account
211
+ API key for owned sites).
162
212
 
163
213
  ```sh
164
214
  # redeploy a new version
@@ -180,6 +230,37 @@ curl -X POST https://flypod.dev/sites/<id>/rollback \
180
230
 
181
231
  ---
182
232
 
233
+ ## Accounts and bulk claim (v0.2)
234
+
235
+ The `manage_token` keeps working exactly as v0.1 — accounts are an
236
+ upgrade path, not a replacement.
237
+
238
+ ```sh
239
+ flypod login --key fk_... # save an API key minted at flypod.dev/account
240
+ flypod list # your sites
241
+ flypod claim <id> <token> # attach an anonymous deploy by its per-site token
242
+ flypod keys create # mint a new API key (for agents / CI)
243
+ flypod logout # forget the local key
244
+ ```
245
+
246
+ After running `flypod login` once, every subsequent `flypod` deploy is
247
+ attributed to your account: no expiry, no claim_token, listed under
248
+ `flypod list`. The same applies in the browser: sign in at
249
+ `flypod.dev/account` and every site you've deployed from that browser
250
+ gets absorbed in one bulk-UPDATE.
251
+
252
+ For agents and CI, set `FLYPOD_API_KEY=fk_…` and the CLI sends it as
253
+ `Authorization: Bearer fk_…` on every request. Same key works in curl, in
254
+ GitHub Actions, in your own code.
255
+
256
+ Login on the web uses **magic link** or **email + password** — pick the one you
257
+ prefer; both land you in the same account. The full design (Better Auth
258
+ `anonymous` + `magicLink` + `apiKey` plugins plus core email/password on
259
+ Cloudflare Workers + Turso, with `onLinkAccount` powering bulk claim) is
260
+ documented at [docs/identity.md](https://github.com/sdserranog/flypod/blob/main/docs/identity.md).
261
+
262
+ ---
263
+
183
264
  ## Self-hosting
184
265
 
185
266
  ```ts
@@ -203,6 +284,9 @@ Environment variables / secrets:
203
284
  | `LIBSQL_URL` | — | Turso/libSQL connection URL |
204
285
  | `LIBSQL_AUTH_TOKEN` | — | Turso auth token |
205
286
  | `SAFE_BROWSING_KEY` | — | Enables Google Safe Browsing link scan |
287
+ | `BETTER_AUTH_SECRET` | — | _v0.2:_ Better Auth signing secret (32+ random bytes) |
288
+ | `RESEND_API_KEY` | — | _v0.2:_ Resend API key for magic-link email delivery |
289
+ | `RESEND_FROM` | `notifications@flypod.dev` | _v0.2:_ verified sender address for magic links |
206
290
 
207
291
  ---
208
292
 
@@ -2,14 +2,461 @@
2
2
  import {
3
3
  collectDist,
4
4
  deploySite,
5
- resolveDeployDir
6
- } from "../cli-ezsrcc6t.js";
5
+ resolveDeployDir,
6
+ zipSync
7
+ } from "../cli-ynzcc4xy.js";
7
8
 
8
9
  // bin/deploy.ts
9
- import { readFile } from "node:fs/promises";
10
+ import { readFile as readFile3 } from "node:fs/promises";
10
11
  import { relative } from "node:path";
11
12
  import { fileURLToPath } from "node:url";
12
13
 
14
+ // src/cli/projects.ts
15
+ import { readFile } from "node:fs/promises";
16
+
17
+ // src/cli/paths.ts
18
+ import { mkdir, rename, writeFile } from "node:fs/promises";
19
+ import { homedir, platform } from "node:os";
20
+ import { dirname, join } from "node:path";
21
+ function configDir(env = process.env) {
22
+ if (env.FLYPOD_CONFIG_DIR)
23
+ return env.FLYPOD_CONFIG_DIR;
24
+ const os = platform();
25
+ if (os === "darwin") {
26
+ return join(homedir(), "Library", "Application Support", "flypod");
27
+ }
28
+ if (os === "win32") {
29
+ const appData = env.APPDATA ?? join(homedir(), "AppData", "Roaming");
30
+ return join(appData, "flypod");
31
+ }
32
+ const xdg = env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
33
+ return join(xdg, "flypod");
34
+ }
35
+ function sessionFilePath(env = process.env) {
36
+ return join(configDir(env), "session.json");
37
+ }
38
+ function projectsFilePath(env = process.env) {
39
+ return join(configDir(env), "projects.json");
40
+ }
41
+ async function atomicWriteFile(path, content) {
42
+ await mkdir(dirname(path), { recursive: true });
43
+ const tmp = `${path}.tmp`;
44
+ await writeFile(tmp, content, { mode: 384 });
45
+ await rename(tmp, path);
46
+ }
47
+
48
+ // src/cli/projects.ts
49
+ var MAX_PROJECTS = 64;
50
+ function prune(projects, now) {
51
+ const out = {};
52
+ for (const [dir, rec] of Object.entries(projects)) {
53
+ if (rec.expires_at !== null && rec.expires_at <= now)
54
+ continue;
55
+ out[dir] = rec;
56
+ }
57
+ return out;
58
+ }
59
+ function cap(projects) {
60
+ const entries = Object.entries(projects);
61
+ if (entries.length <= MAX_PROJECTS)
62
+ return projects;
63
+ entries.sort(([, a], [, b]) => b.last_used - a.last_used);
64
+ return Object.fromEntries(entries.slice(0, MAX_PROJECTS));
65
+ }
66
+ async function loadProjects(env) {
67
+ try {
68
+ const text = await readFile(projectsFilePath(env), "utf8");
69
+ const parsed = JSON.parse(text);
70
+ if (!parsed || typeof parsed !== "object" || typeof parsed.projects !== "object")
71
+ return {};
72
+ return prune(parsed.projects, Date.now());
73
+ } catch {
74
+ return {};
75
+ }
76
+ }
77
+ async function saveProjects(projects, env) {
78
+ const cleaned = cap(prune(projects, Date.now()));
79
+ const file = { v: 1, projects: cleaned };
80
+ const path = projectsFilePath(env);
81
+ await atomicWriteFile(path, `${JSON.stringify(file, null, 2)}
82
+ `);
83
+ return path;
84
+ }
85
+ async function linkProject(dir, rec, env) {
86
+ const projects = await loadProjects(env);
87
+ projects[dir] = rec;
88
+ await saveProjects(projects, env);
89
+ }
90
+ async function projectForDir(dir, env) {
91
+ const projects = await loadProjects(env);
92
+ return projects[dir] ?? null;
93
+ }
94
+ async function forgetDir(dir, env) {
95
+ const projects = await loadProjects(env);
96
+ if (!(dir in projects))
97
+ return false;
98
+ delete projects[dir];
99
+ await saveProjects(projects, env);
100
+ return true;
101
+ }
102
+ async function forgetSite(site_id, env) {
103
+ const projects = await loadProjects(env);
104
+ let removed = 0;
105
+ for (const [dir, rec] of Object.entries(projects)) {
106
+ if (rec.site_id === site_id) {
107
+ delete projects[dir];
108
+ removed++;
109
+ }
110
+ }
111
+ if (removed)
112
+ await saveProjects(projects, env);
113
+ return removed;
114
+ }
115
+
116
+ // src/cli/session.ts
117
+ import { readFile as readFile2, unlink } from "node:fs/promises";
118
+ async function loadSession(env) {
119
+ try {
120
+ const path = sessionFilePath(env);
121
+ const text = await readFile2(path, "utf8");
122
+ const parsed = JSON.parse(text);
123
+ if (typeof parsed?.api_key === "string" && typeof parsed?.base_url === "string" && typeof parsed?.created_at === "number") {
124
+ return parsed;
125
+ }
126
+ return null;
127
+ } catch {
128
+ return null;
129
+ }
130
+ }
131
+ async function saveSession(session, env) {
132
+ const path = sessionFilePath(env);
133
+ await atomicWriteFile(path, `${JSON.stringify(session, null, 2)}
134
+ `);
135
+ return path;
136
+ }
137
+ async function clearSession(env) {
138
+ try {
139
+ await unlink(sessionFilePath(env));
140
+ return true;
141
+ } catch {
142
+ return false;
143
+ }
144
+ }
145
+
146
+ // src/cli/commands.ts
147
+ function baseUrlFrom(env = process.env) {
148
+ return env.DEPLOY_URL ?? "https://flypod.dev";
149
+ }
150
+ function looksLikeApiKey(key) {
151
+ return /^fk_[A-Za-z0-9_-]{16,}$/.test(key);
152
+ }
153
+ async function login(args, io) {
154
+ const env = io.env ?? process.env;
155
+ if (!args.key) {
156
+ io.err("flypod login: --key fk_... is required.");
157
+ io.err("");
158
+ io.err("Mint a key at https://flypod.dev/account (or wherever your");
159
+ io.err("flypod server lives) and run:");
160
+ io.err(" flypod login --key fk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
161
+ return 2;
162
+ }
163
+ if (!looksLikeApiKey(args.key)) {
164
+ io.err("flypod login: that doesn't look like a flypod key (expected fk_...).");
165
+ return 2;
166
+ }
167
+ const baseUrl = baseUrlFrom(env);
168
+ const path = await saveSession({ api_key: args.key, base_url: baseUrl, created_at: Date.now() }, env);
169
+ io.err(`Saved your key to ${path}`);
170
+ io.err(`Now using ${baseUrl} for every flypod command.`);
171
+ return 0;
172
+ }
173
+ async function logout(_args, io) {
174
+ const env = io.env ?? process.env;
175
+ const ok = await clearSession(env);
176
+ if (ok)
177
+ io.err("Signed out. Local session forgotten.");
178
+ else
179
+ io.err("Already signed out.");
180
+ return 0;
181
+ }
182
+ async function list(_args, io) {
183
+ const env = io.env ?? process.env;
184
+ const session = await loadSession(env);
185
+ if (!session) {
186
+ io.err("Not signed in. Run `flypod login --key fk_...` first.");
187
+ return 1;
188
+ }
189
+ const fetchImpl = io.fetch ?? fetch;
190
+ const res = await fetchImpl(`${session.base_url}/account/sites`, {
191
+ headers: { authorization: `Bearer ${session.api_key}` }
192
+ });
193
+ if (!res.ok) {
194
+ io.err(`flypod list: server returned ${res.status}.`);
195
+ return 1;
196
+ }
197
+ const body = await res.json();
198
+ const sites = body.sites ?? [];
199
+ if (sites.length === 0) {
200
+ io.err("No sites yet. Run `flypod` in a folder to deploy one.");
201
+ return 0;
202
+ }
203
+ for (const site of sites)
204
+ io.out(`${site.site_id} ${site.url}`);
205
+ return 0;
206
+ }
207
+ async function claim(args, io) {
208
+ const env = io.env ?? process.env;
209
+ const session = await loadSession(env);
210
+ if (!session) {
211
+ io.err("Not signed in. Run `flypod login --key fk_...` first.");
212
+ return 1;
213
+ }
214
+ if (!args.site_id || !args.token) {
215
+ io.err("Usage: flypod claim <site_id> <claim_token>");
216
+ return 2;
217
+ }
218
+ const fetchImpl = io.fetch ?? fetch;
219
+ const res = await fetchImpl(`${session.base_url}/sites/${args.site_id}/claim`, {
220
+ method: "POST",
221
+ headers: {
222
+ "content-type": "application/json",
223
+ authorization: `Bearer ${session.api_key}`
224
+ },
225
+ body: JSON.stringify({ claim_token: args.token })
226
+ });
227
+ if (!res.ok) {
228
+ io.err(`flypod claim: server returned ${res.status}.`);
229
+ return 1;
230
+ }
231
+ const body = await res.json();
232
+ io.out(body.site_id);
233
+ io.err(`Claimed. Owned by ${body.owner_account_id}.`);
234
+ return 0;
235
+ }
236
+ async function keysCreate(_args, io) {
237
+ const env = io.env ?? process.env;
238
+ const session = await loadSession(env);
239
+ if (!session) {
240
+ io.err("Not signed in. Run `flypod login --key fk_...` first.");
241
+ return 1;
242
+ }
243
+ const fetchImpl = io.fetch ?? fetch;
244
+ const res = await fetchImpl(`${session.base_url}/account/api-keys`, {
245
+ method: "POST",
246
+ headers: { authorization: `Bearer ${session.api_key}` }
247
+ });
248
+ if (!res.ok) {
249
+ io.err(`flypod keys create: server returned ${res.status}.`);
250
+ return 1;
251
+ }
252
+ const body = await res.json();
253
+ io.out(body.api_key);
254
+ io.err("Save this now. You will not see it again.");
255
+ return 0;
256
+ }
257
+ var NO_SITE = "No flypod site is linked to this folder. Run 'flypod' here to create one, or pass --site <id>.";
258
+ async function resolveTarget(args, io) {
259
+ const env = io.env ?? process.env;
260
+ if (args.site)
261
+ return { site_id: args.site, rec: null, dir: null };
262
+ const cwd = io.cwd ?? process.cwd();
263
+ const rec = await projectForDir(cwd, env);
264
+ return rec ? { site_id: rec.site_id, rec, dir: cwd } : null;
265
+ }
266
+ async function requestContext(target, args, env) {
267
+ const session = await loadSession(env);
268
+ const baseUrl = target.rec?.base_url ?? session?.base_url ?? baseUrlFrom(env);
269
+ const auth = args.token ?? target.rec?.manage_token ?? session?.api_key;
270
+ return { baseUrl, auth };
271
+ }
272
+ function authHeaders(auth, extra = {}) {
273
+ return auth ? { ...extra, authorization: `Bearer ${auth}` } : { ...extra };
274
+ }
275
+ async function healGone(target, io, env) {
276
+ if (target.dir)
277
+ await forgetDir(target.dir, env);
278
+ io.err(`Site ${target.site_id} is gone (expired or deleted). Run 'flypod' to create a new one.`);
279
+ }
280
+ function unauthorized(target, io) {
281
+ io.err(`Unauthorized for ${target.site_id}. Run 'flypod login' or pass --token <manage_token>.`);
282
+ }
283
+ async function fetchSite(target, args, io, env) {
284
+ const { baseUrl, auth } = await requestContext(target, args, env);
285
+ const fetchImpl = io.fetch ?? fetch;
286
+ const res = await fetchImpl(`${baseUrl}/sites/${target.site_id}`, { headers: authHeaders(auth) });
287
+ if (res.status === 401 || res.status === 403) {
288
+ unauthorized(target, io);
289
+ return { error: 1 };
290
+ }
291
+ if (res.status === 404) {
292
+ await healGone(target, io, env);
293
+ return { error: 1 };
294
+ }
295
+ if (!res.ok) {
296
+ io.err(`flypod: server returned ${res.status}.`);
297
+ return { error: 1 };
298
+ }
299
+ return { data: await res.json() };
300
+ }
301
+ async function touchLink(target, version_id, env) {
302
+ if (target.dir && target.rec) {
303
+ await linkProject(target.dir, { ...target.rec, version_id, last_used: Date.now() }, env);
304
+ }
305
+ }
306
+ async function update(args, io) {
307
+ const env = io.env ?? process.env;
308
+ const cwd = io.cwd ?? process.cwd();
309
+ const target = await resolveTarget(args, io);
310
+ if (!target) {
311
+ io.err(NO_SITE);
312
+ return 1;
313
+ }
314
+ let dir;
315
+ try {
316
+ dir = await resolveDeployDir({ cwd, explicit: args.path });
317
+ } catch (e) {
318
+ io.err(e.message);
319
+ return 1;
320
+ }
321
+ let files;
322
+ try {
323
+ files = await collectDist(dir);
324
+ } catch (e) {
325
+ io.err(`Could not read ${dir}: ${e.message}`);
326
+ return 1;
327
+ }
328
+ const { baseUrl, auth } = await requestContext(target, args, env);
329
+ const fetchImpl = io.fetch ?? fetch;
330
+ const res = await fetchImpl(`${baseUrl}/sites/${target.site_id}/deploys`, {
331
+ method: "POST",
332
+ headers: authHeaders(auth, { "content-type": "application/zip" }),
333
+ body: zipSync(files)
334
+ });
335
+ if (res.status === 401 || res.status === 403) {
336
+ unauthorized(target, io);
337
+ return 1;
338
+ }
339
+ if (res.status === 404) {
340
+ await healGone(target, io, env);
341
+ return 1;
342
+ }
343
+ if (!res.ok) {
344
+ io.err(`flypod update: server returned ${res.status}.`);
345
+ return 1;
346
+ }
347
+ const body = await res.json();
348
+ const noop = target.rec?.version_id !== undefined && body.version_id === target.rec.version_id;
349
+ await touchLink(target, body.version_id, env);
350
+ if (args.json) {
351
+ io.out(JSON.stringify({
352
+ ok: true,
353
+ site_id: target.site_id,
354
+ version_id: body.version_id,
355
+ url: body.url
356
+ }));
357
+ return 0;
358
+ }
359
+ io.err(noop ? `No changes — already live as ${body.version_id}.` : `→ version ${body.version_id} is now live`);
360
+ io.out(body.url);
361
+ return 0;
362
+ }
363
+ async function versions(args, io) {
364
+ const env = io.env ?? process.env;
365
+ const target = await resolveTarget(args, io);
366
+ if (!target) {
367
+ io.err(NO_SITE);
368
+ return 1;
369
+ }
370
+ const site = await fetchSite(target, args, io, env);
371
+ if ("error" in site)
372
+ return site.error;
373
+ const { live_version_id, versions: vers } = site.data;
374
+ if (args.json) {
375
+ io.out(JSON.stringify({ ok: true, site_id: target.site_id, live_version_id, versions: vers }));
376
+ return 0;
377
+ }
378
+ for (const v of [...vers].reverse()) {
379
+ io.out(`${v.version_id} ${v.created_at} ${v.version_id === live_version_id ? "live" : ""}`);
380
+ }
381
+ return 0;
382
+ }
383
+ async function rollback(args, io) {
384
+ const env = io.env ?? process.env;
385
+ const target = await resolveTarget(args, io);
386
+ if (!target) {
387
+ io.err(NO_SITE);
388
+ return 1;
389
+ }
390
+ const site = await fetchSite(target, args, io, env);
391
+ if ("error" in site)
392
+ return site.error;
393
+ const { live_version_id, versions: vers } = site.data;
394
+ let chosen;
395
+ if (args.version) {
396
+ const exact = vers.find((v) => v.version_id === args.version);
397
+ const prefixed = vers.filter((v) => v.version_id.startsWith(args.version));
398
+ if (exact)
399
+ chosen = exact.version_id;
400
+ else if (prefixed.length === 1)
401
+ chosen = prefixed[0]?.version_id;
402
+ else if (prefixed.length === 0) {
403
+ io.err(`No version matches '${args.version}'.`);
404
+ return 1;
405
+ } else {
406
+ io.err(`'${args.version}' is ambiguous — it matches ${prefixed.length} versions.`);
407
+ return 1;
408
+ }
409
+ } else {
410
+ if (vers.length < 2) {
411
+ io.err("Only one version exists — nothing to roll back to.");
412
+ return 1;
413
+ }
414
+ const liveIdx = vers.findIndex((v) => v.version_id === live_version_id);
415
+ if (liveIdx <= 0) {
416
+ io.err("Already at the oldest version.");
417
+ return 1;
418
+ }
419
+ chosen = vers[liveIdx - 1]?.version_id;
420
+ }
421
+ const { baseUrl, auth } = await requestContext(target, args, env);
422
+ const fetchImpl = io.fetch ?? fetch;
423
+ const res = await fetchImpl(`${baseUrl}/sites/${target.site_id}/rollback`, {
424
+ method: "POST",
425
+ headers: authHeaders(auth, { "content-type": "application/json" }),
426
+ body: JSON.stringify({ version_id: chosen })
427
+ });
428
+ if (res.status === 404) {
429
+ await healGone(target, io, env);
430
+ return 1;
431
+ }
432
+ if (!res.ok) {
433
+ io.err(`flypod rollback: server returned ${res.status}.`);
434
+ return 1;
435
+ }
436
+ const body = await res.json();
437
+ await touchLink(target, body.live_version_id, env);
438
+ if (args.json) {
439
+ io.out(JSON.stringify({ ok: true, site_id: target.site_id, live_version_id: body.live_version_id }));
440
+ return 0;
441
+ }
442
+ io.err(`→ rolled back to ${body.live_version_id}`);
443
+ io.out(body.live_version_id);
444
+ return 0;
445
+ }
446
+ async function forget(args, io) {
447
+ const env = io.env ?? process.env;
448
+ if (args.site) {
449
+ const n = await forgetSite(args.site, env);
450
+ io.err(n ? `Forgot ${n} link${n === 1 ? "" : "s"} to ${args.site}.` : `No links to ${args.site}.`);
451
+ return 0;
452
+ }
453
+ const cwd = io.cwd ?? process.cwd();
454
+ const rec = await projectForDir(cwd, env);
455
+ const removed = await forgetDir(cwd, env);
456
+ io.err(removed && rec ? `Forgot ${rec.site_id} for this folder.` : "Nothing linked to this folder.");
457
+ return 0;
458
+ }
459
+
13
460
  // src/ui.ts
14
461
  var ESC = "\x1B[";
15
462
  function envBool(name) {
@@ -114,6 +561,18 @@ function fmtCount(n, singular) {
114
561
  }
115
562
 
116
563
  // bin/deploy.ts
564
+ var SUBCOMMANDS = new Set([
565
+ "deploy",
566
+ "update",
567
+ "versions",
568
+ "rollback",
569
+ "forget",
570
+ "login",
571
+ "logout",
572
+ "list",
573
+ "claim",
574
+ "keys"
575
+ ]);
117
576
  function parseArgs(argv) {
118
577
  const out = { json: false, quiet: false, help: false, version: false };
119
578
  for (const a of argv) {
@@ -135,12 +594,95 @@ Run \`flypod --help\` for usage.
135
594
  }
136
595
  return out;
137
596
  }
597
+ function flag(argv, name) {
598
+ const long = `--${name}`;
599
+ const equals = `${long}=`;
600
+ for (let i = 0;i < argv.length; i++) {
601
+ const a = argv[i];
602
+ if (a === long)
603
+ return argv[i + 1];
604
+ if (a.startsWith(equals))
605
+ return a.slice(equals.length);
606
+ }
607
+ return;
608
+ }
609
+ function parseSub(argv) {
610
+ const positionals = [];
611
+ let site;
612
+ let token;
613
+ let json = false;
614
+ let quiet = false;
615
+ for (let i = 0;i < argv.length; i++) {
616
+ const a = argv[i];
617
+ if (a === "--site")
618
+ site = argv[++i];
619
+ else if (a.startsWith("--site="))
620
+ site = a.slice("--site=".length);
621
+ else if (a === "--token")
622
+ token = argv[++i];
623
+ else if (a.startsWith("--token="))
624
+ token = a.slice("--token=".length);
625
+ else if (a === "--json")
626
+ json = true;
627
+ else if (a === "-q" || a === "--quiet")
628
+ quiet = true;
629
+ else if (!a.startsWith("-"))
630
+ positionals.push(a);
631
+ }
632
+ return { positionals, site, token, json, quiet };
633
+ }
634
+ async function runSubcommand(name, argv) {
635
+ const io = {
636
+ out: (line) => process.stdout.write(`${line}
637
+ `),
638
+ err: (line) => process.stderr.write(`${line}
639
+ `)
640
+ };
641
+ switch (name) {
642
+ case "update": {
643
+ const { positionals, site, token, json, quiet } = parseSub(argv);
644
+ return update({ path: positionals[0], site, token, json, quiet }, io);
645
+ }
646
+ case "versions": {
647
+ const { site, token, json } = parseSub(argv);
648
+ return versions({ site, token, json }, io);
649
+ }
650
+ case "rollback": {
651
+ const { positionals, site, token, json } = parseSub(argv);
652
+ return rollback({ version: positionals[0], site, token, json }, io);
653
+ }
654
+ case "forget": {
655
+ const { site } = parseSub(argv);
656
+ return forget({ site }, io);
657
+ }
658
+ case "login":
659
+ return login({ key: flag(argv, "key") }, io);
660
+ case "logout":
661
+ return logout({}, io);
662
+ case "list":
663
+ return list({}, io);
664
+ case "claim": {
665
+ const positional = argv.filter((a) => !a.startsWith("-"));
666
+ return claim({ site_id: positional[0], token: positional[1] }, io);
667
+ }
668
+ case "keys": {
669
+ const sub = argv.find((a) => !a.startsWith("-"));
670
+ if (sub === "create")
671
+ return keysCreate({}, io);
672
+ io.err("Usage: flypod keys create");
673
+ return 2;
674
+ }
675
+ default:
676
+ io.err(`flypod: unknown subcommand "${name}"`);
677
+ return 2;
678
+ }
679
+ }
138
680
  async function readVersion() {
139
681
  const here = fileURLToPath(import.meta.url);
140
682
  for (const rel of ["../../package.json", "../package.json"]) {
141
683
  try {
142
684
  const url = new URL(rel, `file://${here}`);
143
- const text = await readFile(url, "utf8");
685
+ const text = await readFile3(url, "utf8");
144
686
  const version = JSON.parse(text).version;
145
687
  if (version)
146
688
  return version;
@@ -150,19 +692,55 @@ async function readVersion() {
150
692
  }
151
693
  function showHelp(version) {
152
694
  const usage = `flypod v${version}
153
- Drop files, get a live URL.
695
+ Drop files, get a live URL. Every deploy is versioned, so you can roll back.
696
+
697
+ THE LOOP (this is all most agents need):
698
+ flypod [path] Deploy NEW content -> creates a new site, prints a URL.
699
+ flypod update Ship CHANGES to that same site -> adds a new VERSION.
700
+ flypod versions List every version, newest first (the live one is marked).
701
+ flypod rollback Make the previous version live again.
702
+
703
+ A "version" is one deploy of a set of files. 'flypod' makes a brand-new site;
704
+ 'flypod update' adds a version to the site you already made. flypod remembers
705
+ which site a folder belongs to (stored under your home config, never in your
706
+ repo), so 'update'/'versions'/'rollback' just work from that folder. To target
707
+ a site from anywhere, pass --site <id> (the id is printed on first deploy).
708
+
709
+ Examples:
710
+ flypod ./dist Deploy a built site (folder).
711
+ flypod index.html Deploy a single file. (For several files, put
712
+ them in a folder and deploy the folder.)
713
+ flypod Deploy the auto-detected build folder.
714
+ flypod update Re-deploy this folder as a new version.
715
+ flypod update ./dist Same, with an explicit path.
716
+ flypod versions Show this folder's version history.
717
+ flypod rollback Roll back to the previous version.
718
+ flypod rollback <version> Roll back to a specific version (id or prefix).
719
+ flypod update --site <id> Update any site by id (no folder memory needed).
720
+
721
+ Targeting (update / versions / rollback):
722
+ --site <id> The site to act on. Omit to use the folder's remembered site.
723
+ --token <tok> A site's manage token, for acting on an anonymous site from a
724
+ machine that doesn't remember it. Owned sites use your login.
154
725
 
155
- Usage:
156
- flypod [path] Deploy a folder (default: auto-detected)
157
- flypod [path] --json Emit a JSON result instead of pretty output
158
- flypod [path] -q, --quiet Print only the URL
159
- flypod -h, --help Show this help
160
- flypod -v, --version Show the flypod version
726
+ Account (optional — lets deploys live forever and be listed/owned):
727
+ flypod login --key fk_... Save an API key; deploys are then yours forever.
728
+ flypod logout Forget the saved API key.
729
+ flypod list List sites you own.
730
+ flypod claim <id> <token> Attach an earlier anonymous deploy to your account.
731
+ flypod keys create Mint a new API key (for agents / CI).
732
+ flypod forget [--site <id>] Drop this folder's remembered site link.
733
+
734
+ Output:
735
+ --json Emit a stable JSON result on stdout (for agents/scripts).
736
+ -q, --quiet Print only the URL.
737
+ -h, --help Show this help. -v, --version Show the flypod version.
161
738
 
162
739
  Environment:
163
- DEPLOY_URL Override the deploy server (default: https://flypod.dev)
164
- NO_COLOR Disable ANSI colors
165
- FORCE_COLOR Force ANSI colors even when stderr is not a TTY
740
+ DEPLOY_URL Override the deploy server (default: https://flypod.dev)
741
+ FLYPOD_CONFIG_DIR Override where the CLI keeps its session + folder memory
742
+ NO_COLOR Disable ANSI colors
743
+ FORCE_COLOR Force ANSI colors even when stderr is not a TTY
166
744
 
167
745
  When no path is given, flypod looks for a build folder in the current directory:
168
746
  dist, build, out, .output/public, .vercel/output/static, public, _site
@@ -178,8 +756,15 @@ function shortDir(dir) {
178
756
  return rel === "" || rel.startsWith("..") ? dir : rel || ".";
179
757
  }
180
758
  async function main() {
181
- const args = parseArgs(process.argv.slice(2));
759
+ const rawArgv = process.argv.slice(2);
182
760
  const version = await readVersion();
761
+ const firstPositional = rawArgv.find((a) => !a.startsWith("-"));
762
+ if (firstPositional && SUBCOMMANDS.has(firstPositional) && firstPositional !== "deploy") {
763
+ const rest = rawArgv.filter((a) => a !== firstPositional);
764
+ const code = await runSubcommand(firstPositional, rest);
765
+ process.exit(code);
766
+ }
767
+ const args = parseArgs(firstPositional === "deploy" ? rawArgv.filter((a) => a !== "deploy") : rawArgv);
183
768
  if (args.help) {
184
769
  showHelp(version);
185
770
  return;
@@ -189,7 +774,8 @@ async function main() {
189
774
  `);
190
775
  return;
191
776
  }
192
- const baseUrl = process.env.DEPLOY_URL ?? "https://flypod.dev";
777
+ const session = await loadSession();
778
+ const baseUrl = session?.base_url ?? process.env.DEPLOY_URL ?? "https://flypod.dev";
193
779
  const useUI = !args.json && !args.quiet;
194
780
  const style = makeStyle(colorsEnabled(process.stderr) && useUI);
195
781
  if (useUI) {
@@ -251,7 +837,7 @@ async function main() {
251
837
  const started = Date.now();
252
838
  let result;
253
839
  try {
254
- result = await deploySite({ baseUrl, files });
840
+ result = await deploySite({ baseUrl, files, apiKey: session?.api_key });
255
841
  } catch (error) {
256
842
  spinner.fail("Deploy failed.");
257
843
  const msg = error.message;
@@ -267,6 +853,18 @@ async function main() {
267
853
  }
268
854
  const elapsed = Date.now() - started;
269
855
  spinner.success(`Deployed in ${fmtSeconds(elapsed)}`);
856
+ const owned = typeof result.owner_account_id === "string";
857
+ try {
858
+ await linkProject(process.cwd(), {
859
+ site_id: result.site_id,
860
+ url: result.url,
861
+ base_url: baseUrl,
862
+ ...owned ? {} : { manage_token: result.manage_token },
863
+ expires_at: result.expires_at,
864
+ last_used: Date.now(),
865
+ version_id: result.version_id
866
+ });
867
+ } catch {}
270
868
  if (args.json) {
271
869
  process.stdout.write(`${JSON.stringify({
272
870
  ok: true,
@@ -275,6 +873,8 @@ async function main() {
275
873
  version_id: result.version_id,
276
874
  expires_at: result.expires_at,
277
875
  manage_token: result.manage_token,
876
+ claim_token: result.claim_token,
877
+ owner_account_id: result.owner_account_id,
278
878
  source: shortDir(dir),
279
879
  files: fileNames.length,
280
880
  bytes: totalBytes,
@@ -301,12 +901,16 @@ async function main() {
301
901
  process.stderr.write(` ${rule}
302
902
 
303
903
  `);
304
- process.stderr.write(` ${style.muted("manage token")} ${style.bold(result.manage_token)}
305
- ` + ` ${style.muted(" ")} ${style.dim("save it — needed to redeploy or roll back")}
904
+ const expiry = typeof result.expires_at === "number" ? `in ${Math.max(0, Math.round((result.expires_at - Date.now()) / 86400000))} days . ephemeral by default` : result.owner_account_id ? `never . owned by you (${result.owner_account_id})` : "never (claimed)";
905
+ process.stderr.write(` ${style.muted("expires")} ${style.dim(expiry)}
906
+
907
+ `);
908
+ process.stderr.write(` ${style.muted("ship a change")} ${style.bold("flypod update")} ${style.dim("(new version of this site)")}
909
+ ` + ` ${style.muted("roll back")} ${style.bold("flypod rollback")}
910
+ ` + ` ${style.muted("history")} ${style.bold("flypod versions")}
306
911
 
307
912
  `);
308
- const expiry = typeof result.expires_at === "number" ? `in ${Math.max(0, Math.round((result.expires_at - Date.now()) / 86400000))} days · ephemeral by default` : "never (claimed)";
309
- process.stderr.write(` ${style.muted("expires ")} ${style.dim(expiry)}
913
+ process.stderr.write(` ${style.dim(`manage token ${result.manage_token} — remembered for this folder; needed only with --site elsewhere`)}
310
914
 
311
915
  `);
312
916
  process.stdout.write(`${result.url}
@@ -670,7 +670,12 @@ async function resolveDeployDir(opts = {}) {
670
670
  }
671
671
  throw new Error(`No build output folder found. Looked for ${BUILD_DIR_CANDIDATES.join(", ")} ` + `(each must contain an index.html). Pass the folder explicitly, e.g. \`npx flypod ./dist\`.`);
672
672
  }
673
- async function collectDist(dir) {
673
+ async function collectDist(path) {
674
+ const info = await stat(path);
675
+ if (info.isFile()) {
676
+ const name = path.split("/").pop() ?? "index.html";
677
+ return { [name]: await readFile(path) };
678
+ }
674
679
  const files = {};
675
680
  async function walk(current) {
676
681
  for (const entry of await readdir(current, { withFileTypes: true })) {
@@ -678,19 +683,22 @@ async function collectDist(dir) {
678
683
  if (entry.isDirectory())
679
684
  await walk(full);
680
685
  else
681
- files[relative(dir, full).split("\\").join("/")] = await readFile(full);
686
+ files[relative(path, full).split("\\").join("/")] = await readFile(full);
682
687
  }
683
688
  }
684
- await walk(dir);
689
+ await walk(path);
685
690
  return files;
686
691
  }
687
692
  async function deploySite(opts) {
688
693
  const handle = opts.handle ?? ((request) => fetch(request));
689
694
  const baseUrl = opts.baseUrl ?? "https://flypod.dev";
690
695
  const zip = zipSync(opts.files);
696
+ const headers = { "content-type": "application/zip" };
697
+ if (opts.apiKey)
698
+ headers.authorization = `Bearer ${opts.apiKey}`;
691
699
  const res = await handle(new Request(`${baseUrl}/sites`, {
692
700
  method: "POST",
693
- headers: { "content-type": "application/zip" },
701
+ headers,
694
702
  body: zip
695
703
  }));
696
704
  if (!res.ok)
@@ -698,4 +706,4 @@ async function deploySite(opts) {
698
706
  return await res.json();
699
707
  }
700
708
 
701
- export { BUILD_DIR_CANDIDATES, resolveDeployDir, collectDist, deploySite };
709
+ export { zipSync, BUILD_DIR_CANDIDATES, resolveDeployDir, collectDist, deploySite };
package/dist/src/cli.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  collectDist,
4
4
  deploySite,
5
5
  resolveDeployDir
6
- } from "../cli-ezsrcc6t.js";
6
+ } from "../cli-ynzcc4xy.js";
7
7
  export {
8
8
  resolveDeployDir,
9
9
  deploySite,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "flypod",
3
- "version": "0.1.0",
4
- "description": "Zero-auth, agent-native deploy primitive — drop files, get a URL back",
3
+ "version": "0.3.0",
4
+ "description": "Zero-auth deploy primitive. Turns any folder into a live URL in one command. For AI agents and humans.",
5
5
  "module": "src/cli.ts",
6
6
  "type": "module",
7
7
  "license": "MIT",
@@ -33,20 +33,22 @@
33
33
  ],
34
34
  "scripts": {
35
35
  "build": "rm -rf dist && bun build src/cli.ts bin/deploy.ts --outdir dist --target node --splitting",
36
+ "prepublishOnly": "bun run build",
36
37
  "test": "bun test",
37
38
  "typecheck": "tsc --noEmit",
38
39
  "deploy": "wrangler deploy",
39
40
  "dev": "bun --hot index.ts"
40
41
  },
41
42
  "dependencies": {
42
- "fflate": "^0.8.3",
43
- "hono": "^4.12.25",
44
- "marked": "^18.0.5"
43
+ "fflate": "^0.8.3"
45
44
  },
46
45
  "devDependencies": {
47
46
  "@libsql/client": "^0.17.3",
48
47
  "@types/bun": "latest",
49
- "better-auth": "^1.6.14",
48
+ "better-auth": "1.6.14",
49
+ "drizzle-orm": "^0.45.2",
50
+ "hono": "^4.12.25",
51
+ "marked": "^18.0.5",
50
52
  "playwright": "^1.60.0",
51
53
  "typescript": "^6.0.3",
52
54
  "wrangler": "^4.0.0"