@supacloud/cli 0.38.0 → 0.40.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 (2) hide show
  1. package/dist/index.js +1225 -15
  2. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -238452,20 +238452,20 @@ async function runCli(cliTools, args, options = {}) {
238452
238452
  const shape = getSchemaShape(tool2.schema);
238453
238453
  const actionField = shape.action;
238454
238454
  const actionOptions = getEnumOptions(actionField);
238455
+ const actionless = toolName2 === "deploy";
238455
238456
  const otherFields = Object.entries(shape).filter(([name]) => name !== "action");
238456
238457
  const actionLines = actionOptions.length ? `Available actions:
238457
238458
  ${actionOptions.join(`
238458
- `)}` : "This command does not declare action metadata.";
238459
+ `)}` : actionless ? "" : "This command does not declare action metadata.";
238459
238460
  const argLines = otherFields.length ? otherFields.map(([name, field]) => {
238460
238461
  const description = getDescription(field) || "(no description)";
238461
238462
  return ` --${name} ${description}`;
238462
238463
  }).join(`
238463
238464
  `) : " (no additional flags)";
238464
238465
  return [
238465
- `Usage: ${commandName} ${toolName2} <action> [--flags]`,
238466
- "",
238467
- actionLines,
238466
+ `Usage: ${commandName} ${toolName2}${actionless ? "" : " <action>"} [--flags]`,
238468
238467
  "",
238468
+ ...actionLines ? [actionLines, ""] : [],
238469
238469
  "Flags:",
238470
238470
  argLines
238471
238471
  ].join(`
@@ -238764,6 +238764,7 @@ function resolveSupaCloudContext(env = process.env, cwd = process.cwd(), selecti
238764
238764
 
238765
238765
  // src/shared/execution-policy.ts
238766
238766
  var ACTION_POLICY = {
238767
+ deploy: { write: ["deploy"] },
238767
238768
  project: {
238768
238769
  read: ["get", "endpoints", "health", "logs", "api_keys", "settings", "tasks", "task_detail", "task_stats", "dlq", "background_settings"],
238769
238770
  write: ["pause", "restore", "task_cancel", "task_retry", "update_background_settings"],
@@ -238850,6 +238851,8 @@ function declaredMode(moduleName, action) {
238850
238851
  return;
238851
238852
  }
238852
238853
  function executionMode(moduleName, action, args) {
238854
+ if (moduleName === "deploy" && args.dry_run === true)
238855
+ return "read";
238853
238856
  if (moduleName === "database" && ["push_migrations", "baseline_migrations"].includes(action) && args.dry_run === true)
238854
238857
  return "read";
238855
238858
  if (moduleName === "supabase" && action === "push" && args.dry_run === true)
@@ -238857,7 +238860,7 @@ function executionMode(moduleName, action, args) {
238857
238860
  return declaredMode(moduleName, action);
238858
238861
  }
238859
238862
  function authorizeExecution(moduleName, args, authorization) {
238860
- const action = typeof args.action === "string" ? args.action : "";
238863
+ const action = typeof args.action === "string" ? args.action : moduleName === "deploy" ? "deploy" : "";
238861
238864
  if (!action)
238862
238865
  return;
238863
238866
  const mode = executionMode(moduleName, action, args);
@@ -248354,10 +248357,35 @@ async function runExplain2(args, root) {
248354
248357
  const text = explainObject(manifest, target);
248355
248358
  return textResult2(text, text.startsWith("未找到对象"));
248356
248359
  }
248357
- async function runModuleCheckAction(args, root, environment) {
248360
+ var defaultLiteSpawn = async (command, cwd) => {
248361
+ const proc = Bun.spawn({ cmd: command, cwd, stdout: "pipe", stderr: "pipe" });
248362
+ const [exitCode, stdout, stderr] = await Promise.all([
248363
+ proc.exited,
248364
+ new Response(proc.stdout).text(),
248365
+ new Response(proc.stderr).text()
248366
+ ]);
248367
+ return { exitCode, stdout, stderr };
248368
+ };
248369
+ async function runModuleCheckLite(args, root, spawn3, liteBinary) {
248370
+ const projectDir = resolve8(args.project_dir?.trim() || root);
248371
+ const binary = liteBinary === undefined ? Bun.which("supacloud-lite") : liteBinary;
248372
+ if (!binary) {
248373
+ throw new Error("db module_check --lite 需要本机可用的 supacloud-lite(npm i -g @supacloud/lite,或加入 PATH)");
248374
+ }
248375
+ const command = [binary, "db", "check", "--project-dir", projectDir];
248376
+ if (args.module_file?.trim())
248377
+ command.push("--module-file", resolve8(root, args.module_file.trim()));
248378
+ const result = await spawn3(command, projectDir);
248379
+ const output = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join(`
248380
+ `);
248381
+ return textResult2(output || "lite db check 无输出", result.exitCode !== 0);
248382
+ }
248383
+ async function runModuleCheckAction(args, root, environment, spawn3, liteBinary) {
248384
+ if (args.lite)
248385
+ return runModuleCheckLite(args, root, spawn3, liteBinary);
248358
248386
  const databaseUrl = args.database_url?.trim() || environment.DATABASE_URL?.trim();
248359
248387
  if (!databaseUrl) {
248360
- throw new Error("db module_check requires --database_url 或环境变量 DATABASE_URL");
248388
+ throw new Error("db module_check requires --database_url、环境变量 DATABASE_URL 或 --lite");
248361
248389
  }
248362
248390
  const modules = await loadDatabaseModules(root, args.module_file);
248363
248391
  const schemas = parseSchemas(args.schema);
@@ -248385,14 +248413,17 @@ async function runModuleCheckAction(args, root, environment) {
248385
248413
  function registerDbGovernanceTools(server2, options = {}) {
248386
248414
  const environment = options.environment || process.env;
248387
248415
  const fallbackRoot = options.currentWorkingDirectory || process.cwd();
248388
- server2.tool("db", "Local database governance (@supacloud/db): lint declared modules, explain objects, reconcile against a live catalog. Actions: lint, explain, module_check", {
248416
+ const liteSpawn = options.liteSpawn || defaultLiteSpawn;
248417
+ server2.tool("db", "Local database governance (@supacloud/db): lint declared modules, explain objects, reconcile against a live catalog or a local SupaCloud Lite project. Actions: lint, explain, module_check", {
248389
248418
  action: withDescription(stringEnum(["lint", "explain", "module_check"]), "Database governance action"),
248390
248419
  module: optional(Type.String(), "[lint] Only lint this manifest module (default: all)"),
248391
248420
  root: optional(Type.String(), "[*] Project root (default: current directory)"),
248392
248421
  module_file: optional(Type.String(), "[*] File exporting defineDatabaseModule(...) (default: <root>/db/modules.ts)"),
248393
248422
  target: optional(Type.String(), "[explain] Policy / function / table name to explain"),
248394
248423
  database_url: optional(Type.String(), "[module_check] Postgres connection URL (default: DATABASE_URL)"),
248395
- schema: optional(Type.String(), "[module_check] Comma-separated schemas to inspect (default: public)")
248424
+ schema: optional(Type.String(), "[module_check] Comma-separated schemas to inspect (default: public)"),
248425
+ lite: optional(Type.Boolean(), "[module_check] Reconcile against a local SupaCloud Lite project (runs supacloud-lite db check)"),
248426
+ project_dir: optional(Type.String(), "[module_check] Lite project directory (with --lite; default: --root)")
248396
248427
  }, async (request) => {
248397
248428
  const root = resolve8(request.root || fallbackRoot);
248398
248429
  switch (request.action) {
@@ -248401,7 +248432,7 @@ function registerDbGovernanceTools(server2, options = {}) {
248401
248432
  case "explain":
248402
248433
  return runExplain2(request, root);
248403
248434
  case "module_check":
248404
- return runModuleCheckAction(request, root, environment);
248435
+ return runModuleCheckAction(request, root, environment, liteSpawn, options.liteBinary);
248405
248436
  default:
248406
248437
  return textResult2(`Unknown db action: ${String(request.action)}`, true);
248407
248438
  }
@@ -249451,10 +249482,1166 @@ function registerReleaseTools(server2, http, options = {}) {
249451
249482
  });
249452
249483
  });
249453
249484
  }
249485
+
249486
+ // src/shared/tools/deploy-tools.ts
249487
+ import { access, lstat, mkdtemp, opendir, readFile as readFile2, rm, writeFile as writeFile3 } from "node:fs/promises";
249488
+ import { createHash as createHash4 } from "node:crypto";
249489
+ import { tmpdir as tmpdir2 } from "node:os";
249490
+ import { basename as basename4, dirname as dirname4, join as join9, relative as relative4, resolve as resolve10, sep as sep4 } from "node:path";
249491
+ import { spawn as spawn3 } from "node:child_process";
249492
+
249493
+ // node_modules/fflate/esm/index.mjs
249494
+ import { createRequire as createRequire2 } from "module";
249495
+ var require2 = createRequire2("/");
249496
+ var _a;
249497
+ var Worker;
249498
+ var isMarkedAsUntransferable;
249499
+ try {
249500
+ _a = require2("worker_threads"), Worker = _a.Worker, isMarkedAsUntransferable = _a.isMarkedAsUntransferable;
249501
+ } catch (e) {}
249502
+ var u8 = Uint8Array;
249503
+ var u16 = Uint16Array;
249504
+ var i32 = Int32Array;
249505
+ var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0]);
249506
+ var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0]);
249507
+ var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
249508
+ var freb = function(eb, start) {
249509
+ var b = new u16(31);
249510
+ for (var i = 0;i < 31; ++i) {
249511
+ b[i] = start += 1 << eb[i - 1];
249512
+ }
249513
+ var r = new i32(b[30]);
249514
+ for (var i = 1;i < 30; ++i) {
249515
+ for (var j = b[i];j < b[i + 1]; ++j) {
249516
+ r[j] = j - b[i] << 5 | i;
249517
+ }
249518
+ }
249519
+ return { b, r };
249520
+ };
249521
+ var _a = freb(fleb, 2);
249522
+ var fl = _a.b;
249523
+ var revfl = _a.r;
249524
+ fl[28] = 258, revfl[258] = 28;
249525
+ var _b = freb(fdeb, 0);
249526
+ var fd = _b.b;
249527
+ var revfd = _b.r;
249528
+ var rev = new u16(32768);
249529
+ for (i = 0;i < 32768; ++i) {
249530
+ x = (i & 43690) >> 1 | (i & 21845) << 1;
249531
+ x = (x & 52428) >> 2 | (x & 13107) << 2;
249532
+ x = (x & 61680) >> 4 | (x & 3855) << 4;
249533
+ rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
249534
+ }
249535
+ var x;
249536
+ var i;
249537
+ var hMap = function(cd, mb, r) {
249538
+ var s = cd.length;
249539
+ var i2 = 0;
249540
+ var l = new u16(mb);
249541
+ for (;i2 < s; ++i2) {
249542
+ if (cd[i2])
249543
+ ++l[cd[i2] - 1];
249544
+ }
249545
+ var le = new u16(mb);
249546
+ for (i2 = 1;i2 < mb; ++i2) {
249547
+ le[i2] = le[i2 - 1] + l[i2 - 1] << 1;
249548
+ }
249549
+ var co;
249550
+ if (r) {
249551
+ co = new u16(1 << mb);
249552
+ var rvb = 15 - mb;
249553
+ for (i2 = 0;i2 < s; ++i2) {
249554
+ if (cd[i2]) {
249555
+ var sv = i2 << 4 | cd[i2];
249556
+ var r_1 = mb - cd[i2];
249557
+ var v = le[cd[i2] - 1]++ << r_1;
249558
+ for (var m = v | (1 << r_1) - 1;v <= m; ++v) {
249559
+ co[rev[v] >> rvb] = sv;
249560
+ }
249561
+ }
249562
+ }
249563
+ } else {
249564
+ co = new u16(s);
249565
+ for (i2 = 0;i2 < s; ++i2) {
249566
+ if (cd[i2]) {
249567
+ co[i2] = rev[le[cd[i2] - 1]++] >> 15 - cd[i2];
249568
+ }
249569
+ }
249570
+ }
249571
+ return co;
249572
+ };
249573
+ var flt = new u8(288);
249574
+ for (i = 0;i < 144; ++i)
249575
+ flt[i] = 8;
249576
+ var i;
249577
+ for (i = 144;i < 256; ++i)
249578
+ flt[i] = 9;
249579
+ var i;
249580
+ for (i = 256;i < 280; ++i)
249581
+ flt[i] = 7;
249582
+ var i;
249583
+ for (i = 280;i < 288; ++i)
249584
+ flt[i] = 8;
249585
+ var i;
249586
+ var fdt = new u8(32);
249587
+ for (i = 0;i < 32; ++i)
249588
+ fdt[i] = 5;
249589
+ var i;
249590
+ var flm = /* @__PURE__ */ hMap(flt, 9, 0);
249591
+ var fdm = /* @__PURE__ */ hMap(fdt, 5, 0);
249592
+ var shft = function(p) {
249593
+ return (p + 7) / 8 | 0;
249594
+ };
249595
+ var slc = function(v, s, e) {
249596
+ if (s == null || s < 0)
249597
+ s = 0;
249598
+ if (e == null || e > v.length)
249599
+ e = v.length;
249600
+ return new u8(v.subarray(s, e));
249601
+ };
249602
+ var ec = [
249603
+ "unexpected EOF",
249604
+ "invalid block type",
249605
+ "invalid length/literal",
249606
+ "invalid distance",
249607
+ "stream finished",
249608
+ "no stream handler",
249609
+ ,
249610
+ "no callback",
249611
+ "invalid UTF-8 data",
249612
+ "extra field too long",
249613
+ "date not in range 1980-2099",
249614
+ "filename too long",
249615
+ "stream finishing",
249616
+ "invalid zip data"
249617
+ ];
249618
+ var err = function(ind, msg, nt) {
249619
+ var e = new Error(msg || ec[ind]);
249620
+ e.code = ind;
249621
+ if (Error.captureStackTrace)
249622
+ Error.captureStackTrace(e, err);
249623
+ if (!nt)
249624
+ throw e;
249625
+ return e;
249626
+ };
249627
+ var wbits = function(d, p, v) {
249628
+ v <<= p & 7;
249629
+ var o = p / 8 | 0;
249630
+ d[o] |= v;
249631
+ d[o + 1] |= v >> 8;
249632
+ };
249633
+ var wbits16 = function(d, p, v) {
249634
+ v <<= p & 7;
249635
+ var o = p / 8 | 0;
249636
+ d[o] |= v;
249637
+ d[o + 1] |= v >> 8;
249638
+ d[o + 2] |= v >> 16;
249639
+ };
249640
+ var hTree = function(d, mb) {
249641
+ var t = [];
249642
+ for (var i2 = 0;i2 < d.length; ++i2) {
249643
+ if (d[i2])
249644
+ t.push({ s: i2, f: d[i2] });
249645
+ }
249646
+ var s = t.length;
249647
+ var t2 = t.slice();
249648
+ if (!s)
249649
+ return { t: et, l: 0 };
249650
+ if (s == 1) {
249651
+ var v = new u8(t[0].s + 1);
249652
+ v[t[0].s] = 1;
249653
+ return { t: v, l: 1 };
249654
+ }
249655
+ t.sort(function(a, b) {
249656
+ return a.f - b.f;
249657
+ });
249658
+ t.push({ s: -1, f: 25001 });
249659
+ var l = t[0], r = t[1], i0 = 0, i1 = 1, i22 = 2;
249660
+ t[0] = { s: -1, f: l.f + r.f, l, r };
249661
+ while (i1 != s - 1) {
249662
+ l = t[t[i0].f < t[i22].f ? i0++ : i22++];
249663
+ r = t[i0 != i1 && t[i0].f < t[i22].f ? i0++ : i22++];
249664
+ t[i1++] = { s: -1, f: l.f + r.f, l, r };
249665
+ }
249666
+ var maxSym = t2[0].s;
249667
+ for (var i2 = 1;i2 < s; ++i2) {
249668
+ if (t2[i2].s > maxSym)
249669
+ maxSym = t2[i2].s;
249670
+ }
249671
+ var tr = new u16(maxSym + 1);
249672
+ var mbt = ln(t[i1 - 1], tr, 0);
249673
+ if (mbt > mb) {
249674
+ var i2 = 0, dt = 0;
249675
+ var lft = mbt - mb, cst = 1 << lft;
249676
+ t2.sort(function(a, b) {
249677
+ return tr[b.s] - tr[a.s] || a.f - b.f;
249678
+ });
249679
+ for (;i2 < s; ++i2) {
249680
+ var i2_1 = t2[i2].s;
249681
+ if (tr[i2_1] > mb) {
249682
+ dt += cst - (1 << mbt - tr[i2_1]);
249683
+ tr[i2_1] = mb;
249684
+ } else
249685
+ break;
249686
+ }
249687
+ dt >>= lft;
249688
+ while (dt > 0) {
249689
+ var i2_2 = t2[i2].s;
249690
+ if (tr[i2_2] < mb)
249691
+ dt -= 1 << mb - tr[i2_2]++ - 1;
249692
+ else
249693
+ ++i2;
249694
+ }
249695
+ for (;i2 >= 0 && dt; --i2) {
249696
+ var i2_3 = t2[i2].s;
249697
+ if (tr[i2_3] == mb) {
249698
+ --tr[i2_3];
249699
+ ++dt;
249700
+ }
249701
+ }
249702
+ mbt = mb;
249703
+ }
249704
+ return { t: new u8(tr), l: mbt };
249705
+ };
249706
+ var ln = function(n, l, d) {
249707
+ return n.s == -1 ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) : l[n.s] = d;
249708
+ };
249709
+ var lc = function(c) {
249710
+ var s = c.length;
249711
+ while (s && !c[--s])
249712
+ ;
249713
+ var cl = new u16(++s);
249714
+ var cli = 0, cln = c[0], cls = 1;
249715
+ var w = function(v) {
249716
+ cl[cli++] = v;
249717
+ };
249718
+ for (var i2 = 1;i2 <= s; ++i2) {
249719
+ if (c[i2] == cln && i2 != s)
249720
+ ++cls;
249721
+ else {
249722
+ if (!cln && cls > 2) {
249723
+ for (;cls > 138; cls -= 138)
249724
+ w(32754);
249725
+ if (cls > 2) {
249726
+ w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305);
249727
+ cls = 0;
249728
+ }
249729
+ } else if (cls > 3) {
249730
+ w(cln), --cls;
249731
+ for (;cls > 6; cls -= 6)
249732
+ w(8304);
249733
+ if (cls > 2)
249734
+ w(cls - 3 << 5 | 8208), cls = 0;
249735
+ }
249736
+ while (cls--)
249737
+ w(cln);
249738
+ cls = 1;
249739
+ cln = c[i2];
249740
+ }
249741
+ }
249742
+ return { c: cl.subarray(0, cli), n: s };
249743
+ };
249744
+ var clen = function(cf, cl) {
249745
+ var l = 0;
249746
+ for (var i2 = 0;i2 < cl.length; ++i2)
249747
+ l += cf[i2] * cl[i2];
249748
+ return l;
249749
+ };
249750
+ var wfblk = function(out, pos, dat) {
249751
+ var s = dat.length;
249752
+ var o = shft(pos + 2);
249753
+ out[o] = s & 255;
249754
+ out[o + 1] = s >> 8;
249755
+ out[o + 2] = out[o] ^ 255;
249756
+ out[o + 3] = out[o + 1] ^ 255;
249757
+ for (var i2 = 0;i2 < s; ++i2)
249758
+ out[o + i2 + 4] = dat[i2];
249759
+ return (o + 4 + s) * 8;
249760
+ };
249761
+ var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p) {
249762
+ wbits(out, p++, final);
249763
+ ++lf[256];
249764
+ var _a2 = hTree(lf, 15), dlt = _a2.t, mlb = _a2.l;
249765
+ var _b2 = hTree(df, 15), ddt = _b2.t, mdb = _b2.l;
249766
+ var _c = lc(dlt), lclt = _c.c, nlc = _c.n;
249767
+ var _d = lc(ddt), lcdt = _d.c, ndc = _d.n;
249768
+ var lcfreq = new u16(19);
249769
+ for (var i2 = 0;i2 < lclt.length; ++i2)
249770
+ ++lcfreq[lclt[i2] & 31];
249771
+ for (var i2 = 0;i2 < lcdt.length; ++i2)
249772
+ ++lcfreq[lcdt[i2] & 31];
249773
+ var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l;
249774
+ var nlcc = 19;
249775
+ for (;nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc)
249776
+ ;
249777
+ var flen = bl + 5 << 3;
249778
+ var ftlen = clen(lf, flt) + clen(df, fdt) + eb;
249779
+ var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18];
249780
+ if (bs >= 0 && flen <= ftlen && flen <= dtlen)
249781
+ return wfblk(out, p, dat.subarray(bs, bs + bl));
249782
+ var lm, ll, dm, dl;
249783
+ wbits(out, p, 1 + (dtlen < ftlen)), p += 2;
249784
+ if (dtlen < ftlen) {
249785
+ lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt;
249786
+ var llm = hMap(lct, mlcb, 0);
249787
+ wbits(out, p, nlc - 257);
249788
+ wbits(out, p + 5, ndc - 1);
249789
+ wbits(out, p + 10, nlcc - 4);
249790
+ p += 14;
249791
+ for (var i2 = 0;i2 < nlcc; ++i2)
249792
+ wbits(out, p + 3 * i2, lct[clim[i2]]);
249793
+ p += 3 * nlcc;
249794
+ var lcts = [lclt, lcdt];
249795
+ for (var it = 0;it < 2; ++it) {
249796
+ var clct = lcts[it];
249797
+ for (var i2 = 0;i2 < clct.length; ++i2) {
249798
+ var len = clct[i2] & 31;
249799
+ wbits(out, p, llm[len]), p += lct[len];
249800
+ if (len > 15)
249801
+ wbits(out, p, clct[i2] >> 5 & 127), p += clct[i2] >> 12;
249802
+ }
249803
+ }
249804
+ } else {
249805
+ lm = flm, ll = flt, dm = fdm, dl = fdt;
249806
+ }
249807
+ for (var i2 = 0;i2 < li; ++i2) {
249808
+ var sym = syms[i2];
249809
+ if (sym > 255) {
249810
+ var len = sym >> 18 & 31;
249811
+ wbits16(out, p, lm[len + 257]), p += ll[len + 257];
249812
+ if (len > 7)
249813
+ wbits(out, p, sym >> 23 & 31), p += fleb[len];
249814
+ var dst = sym & 31;
249815
+ wbits16(out, p, dm[dst]), p += dl[dst];
249816
+ if (dst > 3)
249817
+ wbits16(out, p, sym >> 5 & 8191), p += fdeb[dst];
249818
+ } else {
249819
+ wbits16(out, p, lm[sym]), p += ll[sym];
249820
+ }
249821
+ }
249822
+ wbits16(out, p, lm[256]);
249823
+ return p + ll[256];
249824
+ };
249825
+ var deo = /* @__PURE__ */ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]);
249826
+ var et = /* @__PURE__ */ new u8(0);
249827
+ var dflt = function(dat, lvl, plvl, pre, post, st) {
249828
+ var s = st.z || dat.length;
249829
+ var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post);
249830
+ var w = o.subarray(pre, o.length - post);
249831
+ var lst = st.l;
249832
+ var pos = (st.r || 0) & 7;
249833
+ if (lvl) {
249834
+ if (pos)
249835
+ w[0] = st.r >> 3;
249836
+ var opt = deo[lvl - 1];
249837
+ var n = opt >> 13, c = opt & 8191;
249838
+ var msk_1 = (1 << plvl) - 1;
249839
+ var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1);
249840
+ var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1;
249841
+ var hsh = function(i3) {
249842
+ return (dat[i3] ^ dat[i3 + 1] << bs1_1 ^ dat[i3 + 2] << bs2_1) & msk_1;
249843
+ };
249844
+ var syms = new i32(25000);
249845
+ var lf = new u16(288), df = new u16(32);
249846
+ var lc_1 = 0, eb = 0, i2 = st.i || 0, li = 0, wi = st.w || 0, bs = 0;
249847
+ for (;i2 + 2 < s; ++i2) {
249848
+ var hv = hsh(i2);
249849
+ var imod = i2 & 32767, pimod = head[hv];
249850
+ prev[imod] = pimod;
249851
+ head[hv] = imod;
249852
+ if (wi <= i2) {
249853
+ var rem = s - i2;
249854
+ if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) {
249855
+ pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i2 - bs, pos);
249856
+ li = lc_1 = eb = 0, bs = i2;
249857
+ for (var j = 0;j < 286; ++j)
249858
+ lf[j] = 0;
249859
+ for (var j = 0;j < 30; ++j)
249860
+ df[j] = 0;
249861
+ }
249862
+ var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767;
249863
+ if (rem > 2 && hv == hsh(i2 - dif)) {
249864
+ var maxn = Math.min(n, rem) - 1;
249865
+ var maxd = Math.min(32767, i2);
249866
+ var ml = Math.min(258, rem);
249867
+ while (dif <= maxd && --ch_1 && imod != pimod) {
249868
+ if (dat[i2 + l] == dat[i2 + l - dif]) {
249869
+ var nl = 0;
249870
+ for (;nl < ml && dat[i2 + nl] == dat[i2 + nl - dif]; ++nl)
249871
+ ;
249872
+ if (nl > l) {
249873
+ l = nl, d = dif;
249874
+ if (nl > maxn)
249875
+ break;
249876
+ var mmd = Math.min(dif, nl - 2);
249877
+ var md = 0;
249878
+ for (var j = 0;j < mmd; ++j) {
249879
+ var ti = i2 - dif + j & 32767;
249880
+ var pti = prev[ti];
249881
+ var cd = ti - pti & 32767;
249882
+ if (cd > md)
249883
+ md = cd, pimod = ti;
249884
+ }
249885
+ }
249886
+ }
249887
+ imod = pimod, pimod = prev[imod];
249888
+ dif += imod - pimod & 32767;
249889
+ }
249890
+ }
249891
+ if (d) {
249892
+ syms[li++] = 268435456 | revfl[l] << 18 | revfd[d];
249893
+ var lin = revfl[l] & 31, din = revfd[d] & 31;
249894
+ eb += fleb[lin] + fdeb[din];
249895
+ ++lf[257 + lin];
249896
+ ++df[din];
249897
+ wi = i2 + l;
249898
+ ++lc_1;
249899
+ } else {
249900
+ syms[li++] = dat[i2];
249901
+ ++lf[dat[i2]];
249902
+ }
249903
+ }
249904
+ }
249905
+ for (i2 = Math.max(i2, wi);i2 < s; ++i2) {
249906
+ syms[li++] = dat[i2];
249907
+ ++lf[dat[i2]];
249908
+ }
249909
+ pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i2 - bs, pos);
249910
+ if (!lst) {
249911
+ st.r = pos & 7 | w[pos / 8 | 0] << 3;
249912
+ pos -= 7;
249913
+ st.h = head, st.p = prev, st.i = i2, st.w = wi;
249914
+ }
249915
+ } else {
249916
+ for (var i2 = st.w || 0;i2 < s + lst; i2 += 65535) {
249917
+ var e = i2 + 65535;
249918
+ if (e >= s) {
249919
+ w[pos / 8 | 0] = lst;
249920
+ e = s;
249921
+ }
249922
+ pos = wfblk(w, pos + 1, dat.subarray(i2, e));
249923
+ }
249924
+ st.i = s;
249925
+ }
249926
+ return slc(o, 0, pre + shft(pos) + post);
249927
+ };
249928
+ var crct = /* @__PURE__ */ function() {
249929
+ var t = new Int32Array(256);
249930
+ for (var i2 = 0;i2 < 256; ++i2) {
249931
+ var c = i2, k = 9;
249932
+ while (--k)
249933
+ c = (c & 1 && -306674912) ^ c >>> 1;
249934
+ t[i2] = c;
249935
+ }
249936
+ return t;
249937
+ }();
249938
+ var crc = function() {
249939
+ var c = -1;
249940
+ return {
249941
+ p: function(d) {
249942
+ var cr = c;
249943
+ for (var i2 = 0;i2 < d.length; ++i2)
249944
+ cr = crct[cr & 255 ^ d[i2]] ^ cr >>> 8;
249945
+ c = cr;
249946
+ },
249947
+ d: function() {
249948
+ return ~c;
249949
+ }
249950
+ };
249951
+ };
249952
+ var dopt = function(dat, opt, pre, post, st) {
249953
+ if (!st) {
249954
+ st = { l: 1 };
249955
+ if (opt.dictionary) {
249956
+ var dict = opt.dictionary.subarray(-32768);
249957
+ var newDat = new u8(dict.length + dat.length);
249958
+ newDat.set(dict);
249959
+ newDat.set(dat, dict.length);
249960
+ dat = newDat;
249961
+ st.w = dict.length;
249962
+ }
249963
+ }
249964
+ return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20 : 12 + opt.mem, pre, post, st);
249965
+ };
249966
+ var mrg = function(a, b) {
249967
+ var o = {};
249968
+ for (var k in a)
249969
+ o[k] = a[k];
249970
+ for (var k in b)
249971
+ o[k] = b[k];
249972
+ return o;
249973
+ };
249974
+ var wbytes = function(d, b, v) {
249975
+ for (;v; ++b)
249976
+ d[b] = v, v >>>= 8;
249977
+ };
249978
+ function deflateSync(data, opts) {
249979
+ return dopt(data, opts || {}, 0, 0);
249980
+ }
249981
+ var fltn = function(d, p, t, o) {
249982
+ for (var k in d) {
249983
+ var val = d[k], n = p + k, op = o;
249984
+ if (Array.isArray(val))
249985
+ op = mrg(o, val[1]), val = val[0];
249986
+ if (ArrayBuffer.isView(val))
249987
+ t[n] = [val, op];
249988
+ else {
249989
+ t[n += "/"] = [new u8(0), op];
249990
+ fltn(val, n, t, o);
249991
+ }
249992
+ }
249993
+ };
249994
+ var te = typeof TextEncoder != "undefined" && /* @__PURE__ */ new TextEncoder;
249995
+ var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder;
249996
+ var tds = 0;
249997
+ try {
249998
+ td.decode(et, { stream: true });
249999
+ tds = 1;
250000
+ } catch (e) {}
250001
+ function strToU8(str, latin1) {
250002
+ if (latin1) {
250003
+ var ar_1 = new u8(str.length);
250004
+ for (var i2 = 0;i2 < str.length; ++i2)
250005
+ ar_1[i2] = str.charCodeAt(i2);
250006
+ return ar_1;
250007
+ }
250008
+ if (te)
250009
+ return te.encode(str);
250010
+ var l = str.length;
250011
+ var ar = new u8(str.length + (str.length >> 1));
250012
+ var ai = 0;
250013
+ var w = function(v) {
250014
+ ar[ai++] = v;
250015
+ };
250016
+ for (var i2 = 0;i2 < l; ++i2) {
250017
+ if (ai + 5 > ar.length) {
250018
+ var n = new u8(ai + 8 + (l - i2 << 1));
250019
+ n.set(ar);
250020
+ ar = n;
250021
+ }
250022
+ var c = str.charCodeAt(i2);
250023
+ if (c < 128 || latin1)
250024
+ w(c);
250025
+ else if (c < 2048)
250026
+ w(192 | c >> 6), w(128 | c & 63);
250027
+ else if (c > 55295 && c < 57344)
250028
+ c = 65536 + (c & 1023 << 10) | str.charCodeAt(++i2) & 1023, w(240 | c >> 18), w(128 | c >> 12 & 63), w(128 | c >> 6 & 63), w(128 | c & 63);
250029
+ else
250030
+ w(224 | c >> 12), w(128 | c >> 6 & 63), w(128 | c & 63);
250031
+ }
250032
+ return slc(ar, 0, ai);
250033
+ }
250034
+ var exfl = function(ex) {
250035
+ var le = 0;
250036
+ if (ex) {
250037
+ for (var k in ex) {
250038
+ var l = ex[k].length;
250039
+ if (l > 65535)
250040
+ err(9);
250041
+ le += l + 4;
250042
+ }
250043
+ }
250044
+ return le;
250045
+ };
250046
+ var wzh = function(d, b, f, fn, u, c, ce, co) {
250047
+ var fl2 = fn.length, ex = f.extra, col = co && co.length;
250048
+ var exl = exfl(ex);
250049
+ wbytes(d, b, ce != null ? 33639248 : 67324752), b += 4;
250050
+ if (ce != null)
250051
+ d[b++] = 20, d[b++] = f.os;
250052
+ d[b] = 20, b += 2;
250053
+ d[b++] = f.flag << 1 | (c < 0 && 8), d[b++] = u && 8;
250054
+ d[b++] = f.compression & 255, d[b++] = f.compression >> 8;
250055
+ var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980;
250056
+ if (y < 0 || y > 119)
250057
+ err(10);
250058
+ wbytes(d, b, y << 25 | dt.getMonth() + 1 << 21 | dt.getDate() << 16 | dt.getHours() << 11 | dt.getMinutes() << 5 | dt.getSeconds() >> 1), b += 4;
250059
+ if (c != -1) {
250060
+ wbytes(d, b, f.crc);
250061
+ wbytes(d, b + 4, c < 0 ? -c - 2 : c);
250062
+ wbytes(d, b + 8, f.size);
250063
+ }
250064
+ wbytes(d, b + 12, fl2);
250065
+ wbytes(d, b + 14, exl), b += 16;
250066
+ if (ce != null) {
250067
+ wbytes(d, b, col);
250068
+ wbytes(d, b + 6, f.attrs);
250069
+ wbytes(d, b + 10, ce), b += 14;
250070
+ }
250071
+ d.set(fn, b);
250072
+ b += fl2;
250073
+ if (exl) {
250074
+ for (var k in ex) {
250075
+ var exf = ex[k], l = exf.length;
250076
+ wbytes(d, b, +k);
250077
+ wbytes(d, b + 2, l);
250078
+ d.set(exf, b + 4), b += 4 + l;
250079
+ }
250080
+ }
250081
+ if (col)
250082
+ d.set(co, b), b += col;
250083
+ return b;
250084
+ };
250085
+ var wzf = function(o, b, c, d, e) {
250086
+ wbytes(o, b, 101010256);
250087
+ wbytes(o, b + 8, c);
250088
+ wbytes(o, b + 10, c);
250089
+ wbytes(o, b + 12, d);
250090
+ wbytes(o, b + 16, e);
250091
+ };
250092
+ function zipSync(data, opts) {
250093
+ if (!opts)
250094
+ opts = {};
250095
+ var r = {};
250096
+ var files = [];
250097
+ fltn(data, "", r, opts);
250098
+ var o = 0;
250099
+ var tot = 0;
250100
+ for (var fn in r) {
250101
+ var _a2 = r[fn], file = _a2[0], p = _a2[1];
250102
+ var compression = p.level == 0 ? 0 : 8;
250103
+ var f = strToU8(fn), s = f.length;
250104
+ var com = p.comment, m = com && strToU8(com), ms = m && m.length;
250105
+ var exl = exfl(p.extra);
250106
+ if (s > 65535)
250107
+ err(11);
250108
+ var d = compression ? deflateSync(file, p) : file, l = d.length;
250109
+ var c = crc();
250110
+ c.p(file);
250111
+ files.push(mrg(p, {
250112
+ size: file.length,
250113
+ crc: c.d(),
250114
+ c: d,
250115
+ f,
250116
+ m,
250117
+ u: s != fn.length || m && com.length != ms,
250118
+ o,
250119
+ compression
250120
+ }));
250121
+ o += 30 + s + exl + l;
250122
+ tot += 76 + 2 * (s + exl) + (ms || 0) + l;
250123
+ }
250124
+ var out = new u8(tot + 22), oe = o, cdl = tot - o;
250125
+ for (var i2 = 0;i2 < files.length; ++i2) {
250126
+ var f = files[i2];
250127
+ wzh(out, f.o, f, f.f, f.u, f.c.length);
250128
+ var badd = 30 + f.f.length + exfl(f.extra);
250129
+ out.set(f.c, f.o + badd);
250130
+ wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0);
250131
+ }
250132
+ wzf(out, o, files.length, cdl, oe);
250133
+ return out;
250134
+ }
250135
+
250136
+ // src/shared/tools/deploy-tools.ts
250137
+ var FIXED_ZIP_MTIME = new Date("1980-01-01T00:00:00.000Z");
250138
+ var MAX_SOURCE_BYTES = 256 * 1024 * 1024;
250139
+ var deployToolSchema = {
250140
+ ref: optional(Type.String(), "Project ref (defaults to the linked project)"),
250141
+ target: optional(Type.String(), "Named deploy target from supacloud.json"),
250142
+ id: optional(Type.String(), "Frontend deployment ID (auto-selected when unambiguous)"),
250143
+ cwd: optional(Type.String(), "Project directory (default: current directory)"),
250144
+ build_command: optional(Type.String(), "Build command override"),
250145
+ output_dir: optional(Type.String(), "Build output directory override"),
250146
+ skip_build: optional(Type.Boolean(), "Use an existing output directory without building"),
250147
+ dry_run: optional(Type.Boolean(), "Resolve and validate the deployment without building or publishing"),
250148
+ json: optional(Type.Boolean(), "Print only the final JSON result")
250149
+ };
250150
+ function record(candidate) {
250151
+ return candidate && typeof candidate === "object" && !Array.isArray(candidate) ? candidate : null;
250152
+ }
250153
+ function requiredString(candidate, field) {
250154
+ if (typeof candidate !== "string" || !candidate.trim()) {
250155
+ throw new Error(`Invalid frontend deployment response: missing ${field}`);
250156
+ }
250157
+ return candidate.trim();
250158
+ }
250159
+ function frontendDeployment(candidate) {
250160
+ const value = record(candidate);
250161
+ if (!value)
250162
+ throw new Error("Invalid frontend deployment response");
250163
+ return {
250164
+ id: requiredString(value.id, "id"),
250165
+ name: typeof value.name === "string" && value.name.trim() ? value.name.trim() : requiredString(value.id, "id"),
250166
+ framework: typeof value.framework === "string" ? value.framework.trim() : "static",
250167
+ buildCommand: typeof value.build_command === "string" ? value.build_command.trim() : "",
250168
+ outputDirectory: typeof value.output_dir === "string" ? value.output_dir.trim() : "",
250169
+ deploymentUrl: typeof value.deployment_url === "string" && value.deployment_url.trim() ? value.deployment_url.trim() : null
250170
+ };
250171
+ }
250172
+ async function readJson(path) {
250173
+ try {
250174
+ return JSON.parse(await readFile2(path, "utf8"));
250175
+ } catch (error) {
250176
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
250177
+ return null;
250178
+ throw new Error(`Invalid JSON file ${path}: ${error instanceof Error ? error.message : String(error)}`);
250179
+ }
250180
+ }
250181
+ async function findDeployConfigRoot(startDirectory) {
250182
+ let directory = resolve10(startDirectory);
250183
+ while (true) {
250184
+ if (await pathExists(join9(directory, "supacloud.json")))
250185
+ return directory;
250186
+ const parent = dirname4(directory);
250187
+ if (parent === directory)
250188
+ return resolve10(startDirectory);
250189
+ directory = parent;
250190
+ }
250191
+ }
250192
+ function optionalText(value, field) {
250193
+ if (value === undefined)
250194
+ return;
250195
+ if (typeof value !== "string" || !value.trim()) {
250196
+ throw new Error(`supacloud.json ${field} must be a non-empty string`);
250197
+ }
250198
+ return value.trim();
250199
+ }
250200
+ function optionalBoolean(value, field) {
250201
+ if (value === undefined)
250202
+ return;
250203
+ if (typeof value !== "boolean")
250204
+ throw new Error(`supacloud.json ${field} must be a boolean`);
250205
+ return value;
250206
+ }
250207
+ function deployTargetConfig(candidate, name) {
250208
+ const value = record(candidate);
250209
+ if (!value || value.type !== "frontend" && value.type !== "edge_function") {
250210
+ throw new Error(`supacloud.json targets.${name}.type must be 'frontend' or 'edge_function'`);
250211
+ }
250212
+ const framework = optionalText(value.framework, `targets.${name}.framework`);
250213
+ if (framework && !["fetch", "elysia", "hono", "sveltekit-function"].includes(framework)) {
250214
+ throw new Error(`supacloud.json targets.${name}.framework is invalid`);
250215
+ }
250216
+ return {
250217
+ type: value.type,
250218
+ root: optionalText(value.root, `targets.${name}.root`),
250219
+ id: optionalText(value.id, `targets.${name}.id`),
250220
+ slug: optionalText(value.slug, `targets.${name}.slug`),
250221
+ buildCommand: optionalText(value.buildCommand, `targets.${name}.buildCommand`),
250222
+ outputDirectory: optionalText(value.outputDirectory, `targets.${name}.outputDirectory`),
250223
+ bundleDirectory: optionalText(value.bundleDirectory, `targets.${name}.bundleDirectory`),
250224
+ entrypoint: optionalText(value.entrypoint, `targets.${name}.entrypoint`),
250225
+ verifyJwt: optionalBoolean(value.verifyJwt, `targets.${name}.verifyJwt`),
250226
+ minify: optionalBoolean(value.minify, `targets.${name}.minify`),
250227
+ framework
250228
+ };
250229
+ }
250230
+ async function readDeployConfig(configRoot) {
250231
+ const configPath = join9(configRoot, "supacloud.json");
250232
+ const candidate = await readJson(configPath);
250233
+ if (candidate === null)
250234
+ return {};
250235
+ const config = record(candidate);
250236
+ const frontend = record(config?.frontend);
250237
+ const targetValues = record(config?.targets);
250238
+ if (!config || config.frontend !== undefined && !frontend || config.targets !== undefined && !targetValues) {
250239
+ throw new Error("supacloud.json must contain object-valued 'frontend' or 'targets' configuration");
250240
+ }
250241
+ return {
250242
+ defaultTarget: optionalText(config.defaultTarget, "defaultTarget"),
250243
+ targets: targetValues ? Object.fromEntries(Object.entries(targetValues).map(([name, value]) => [name, deployTargetConfig(value, name)])) : undefined,
250244
+ frontend: frontend ? {
250245
+ id: optionalText(frontend.id, "frontend.id"),
250246
+ root: optionalText(frontend.root, "frontend.root"),
250247
+ buildCommand: optionalText(frontend.buildCommand, "frontend.buildCommand"),
250248
+ outputDirectory: optionalText(frontend.outputDirectory, "frontend.outputDirectory")
250249
+ } : undefined
250250
+ };
250251
+ }
250252
+ async function packageName(projectDirectory) {
250253
+ const candidate = record(await readJson(join9(projectDirectory, "package.json")));
250254
+ return typeof candidate?.name === "string" && candidate.name.trim() ? candidate.name.trim() : null;
250255
+ }
250256
+ async function pathExists(path) {
250257
+ return access(path).then(() => true, () => false);
250258
+ }
250259
+ async function defaultBuildCommand(projectDirectory, configRoot) {
250260
+ const packageJson = record(await readJson(join9(projectDirectory, "package.json")));
250261
+ const scripts = record(packageJson?.scripts);
250262
+ if (typeof scripts?.build !== "string" || !scripts.build.trim()) {
250263
+ throw new Error("No build command was configured and package.json has no build script");
250264
+ }
250265
+ let directory = projectDirectory;
250266
+ while (true) {
250267
+ if (await pathExists(join9(directory, "bun.lock")) || await pathExists(join9(directory, "bun.lockb")))
250268
+ return "bun run build";
250269
+ if (await pathExists(join9(directory, "pnpm-lock.yaml")))
250270
+ return "pnpm run build";
250271
+ if (await pathExists(join9(directory, "yarn.lock")))
250272
+ return "yarn build";
250273
+ if (directory === configRoot)
250274
+ break;
250275
+ const parent = dirname4(directory);
250276
+ if (parent === directory || !directory.startsWith(`${configRoot}${sep4}`))
250277
+ break;
250278
+ directory = parent;
250279
+ }
250280
+ return "npm run build";
250281
+ }
250282
+ function deploymentList(candidate) {
250283
+ const values = Array.isArray(candidate) ? candidate : Array.isArray(record(candidate)?.deployments) ? record(candidate)?.deployments : null;
250284
+ if (!values)
250285
+ throw new Error("Invalid frontend deployment list response");
250286
+ return values.map(frontendDeployment);
250287
+ }
250288
+ function selectDeployment(deployments, requestedId, projectName) {
250289
+ if (requestedId) {
250290
+ const selected = deployments.find((deployment) => deployment.id === requestedId);
250291
+ if (!selected)
250292
+ throw new Error(`Frontend deployment '${requestedId}' was not found`);
250293
+ return selected;
250294
+ }
250295
+ if (deployments.length === 1)
250296
+ return deployments[0];
250297
+ if (projectName) {
250298
+ const matches = deployments.filter((deployment) => deployment.id === projectName || deployment.name === projectName);
250299
+ if (matches.length === 1)
250300
+ return matches[0];
250301
+ }
250302
+ const ids = deployments.map((deployment) => deployment.id).sort().join(", ");
250303
+ throw new Error(deployments.length === 0 ? "No frontend deployments exist for this project" : `Multiple frontend deployments found (${ids}). Set frontend.id in supacloud.json or pass --id`);
250304
+ }
250305
+ function targetRoot(configRoot, target, name) {
250306
+ const root = resolve10(configRoot, target.root || (name === "frontend" ? "." : name));
250307
+ const prefix = `${resolve10(configRoot)}${sep4}`;
250308
+ if (root !== resolve10(configRoot) && !root.startsWith(prefix)) {
250309
+ throw new Error(`Deploy target '${name}' root must stay inside the repository root`);
250310
+ }
250311
+ return root;
250312
+ }
250313
+ function selectTarget(configRoot, invocationDirectory, config, requestedName) {
250314
+ const targets = config.targets ? Object.entries(config.targets) : [["frontend", {
250315
+ type: "frontend",
250316
+ root: config.frontend?.root,
250317
+ id: config.frontend?.id,
250318
+ buildCommand: config.frontend?.buildCommand,
250319
+ outputDirectory: config.frontend?.outputDirectory
250320
+ }]];
250321
+ if (targets.length === 0)
250322
+ throw new Error("supacloud.json defines no deploy targets");
250323
+ if (requestedName) {
250324
+ const selected = targets.find(([name]) => name === requestedName);
250325
+ if (!selected)
250326
+ throw new Error(`Deploy target '${requestedName}' was not found in supacloud.json`);
250327
+ return { name: selected[0], config: selected[1], root: targetRoot(configRoot, selected[1], selected[0]) };
250328
+ }
250329
+ const containing = targets.map(([name, target]) => ({ name, target, root: targetRoot(configRoot, target, name) })).filter((candidate) => invocationDirectory === candidate.root || invocationDirectory.startsWith(`${candidate.root}${sep4}`)).sort((left, right) => right.root.length - left.root.length);
250330
+ if (containing.length === 1 || containing.length > 1 && containing[0].root !== containing[1].root) {
250331
+ const selected = containing[0];
250332
+ return { name: selected.name, config: selected.target, root: selected.root };
250333
+ }
250334
+ if (config.defaultTarget) {
250335
+ const selected = targets.find(([name]) => name === config.defaultTarget);
250336
+ if (!selected)
250337
+ throw new Error(`supacloud.json defaultTarget '${config.defaultTarget}' was not found`);
250338
+ return { name: selected[0], config: selected[1], root: targetRoot(configRoot, selected[1], selected[0]) };
250339
+ }
250340
+ if (targets.length === 1) {
250341
+ const selected = targets[0];
250342
+ return { name: selected[0], config: selected[1], root: targetRoot(configRoot, selected[1], selected[0]) };
250343
+ }
250344
+ throw new Error(`Multiple deploy targets found (${targets.map(([name]) => name).sort().join(", ")}). Pass --target`);
250345
+ }
250346
+ function defaultOutputDirectory(framework) {
250347
+ switch (framework) {
250348
+ case "sveltekit-static":
250349
+ return "build";
250350
+ case "nextjs":
250351
+ return "out";
250352
+ case "static":
250353
+ return "dist";
250354
+ default:
250355
+ return "dist";
250356
+ }
250357
+ }
250358
+ function resolveInsideProject(projectDirectory, candidate, allowRoot = false) {
250359
+ const resolved = resolve10(projectDirectory, candidate);
250360
+ const projectRoot = resolve10(projectDirectory);
250361
+ const projectPrefix = `${projectRoot}${sep4}`;
250362
+ if (!allowRoot && resolved === projectRoot || resolved !== projectRoot && !resolved.startsWith(projectPrefix)) {
250363
+ throw new Error("Frontend output directory must stay inside the project directory");
250364
+ }
250365
+ return resolved;
250366
+ }
250367
+ async function runBuild(command, cwd) {
250368
+ await new Promise((resolvePromise, reject) => {
250369
+ const child = spawn3(command, { cwd, env: process.env, shell: true, stdio: "inherit" });
250370
+ child.once("error", reject);
250371
+ child.once("exit", (code, signal) => {
250372
+ if (code === 0)
250373
+ resolvePromise();
250374
+ else
250375
+ reject(new Error(`Build command failed (${signal ? `signal ${signal}` : `exit ${code ?? "unknown"}`}): ${command}`));
250376
+ });
250377
+ });
250378
+ }
250379
+ async function collectArchiveFiles(root) {
250380
+ const rootStat = await lstat(root).catch(() => null);
250381
+ if (!rootStat?.isDirectory() || rootStat.isSymbolicLink()) {
250382
+ throw new Error(`Frontend output directory does not exist or is not a regular directory: ${root}`);
250383
+ }
250384
+ const paths = [];
250385
+ const visit = async (directory) => {
250386
+ const entries = [];
250387
+ for await (const entry of await opendir(directory))
250388
+ entries.push(entry);
250389
+ entries.sort((left, right) => left.name.localeCompare(right.name, "en"));
250390
+ for (const entry of entries) {
250391
+ const path = join9(directory, entry.name);
250392
+ const stats = await lstat(path);
250393
+ if (stats.isSymbolicLink())
250394
+ throw new Error(`Frontend output cannot contain symbolic links: ${path}`);
250395
+ if (stats.isDirectory())
250396
+ await visit(path);
250397
+ else if (stats.isFile())
250398
+ paths.push(path);
250399
+ else
250400
+ throw new Error(`Frontend output contains an unsupported file type: ${path}`);
250401
+ }
250402
+ };
250403
+ await visit(root);
250404
+ if (paths.length === 0)
250405
+ throw new Error(`Frontend output directory is empty: ${root}`);
250406
+ let bytes = 0;
250407
+ const files = {};
250408
+ for (const path of paths) {
250409
+ const data = new Uint8Array(await readFile2(path));
250410
+ bytes += data.byteLength;
250411
+ if (bytes > MAX_SOURCE_BYTES)
250412
+ throw new Error(`Frontend output exceeds ${MAX_SOURCE_BYTES} bytes`);
250413
+ const archivePath = relative4(root, path).split(sep4).join("/");
250414
+ files[archivePath] = [data, { mtime: FIXED_ZIP_MTIME }];
250415
+ }
250416
+ return { files, bytes, count: paths.length };
250417
+ }
250418
+ async function createFrontendArchive(outputDirectory) {
250419
+ const collected = await collectArchiveFiles(outputDirectory);
250420
+ const temporaryDirectory = await mkdtemp(join9(tmpdir2(), "supacloud-deploy-"));
250421
+ const archivePath = join9(temporaryDirectory, `${basename4(outputDirectory)}.zip`);
250422
+ try {
250423
+ const archiveBytes = zipSync(collected.files, { level: 6, mtime: FIXED_ZIP_MTIME });
250424
+ await writeFile3(archivePath, archiveBytes);
250425
+ const sha256 = createHash4("sha256").update(archiveBytes).digest("hex");
250426
+ return {
250427
+ archivePath,
250428
+ sha256,
250429
+ sourceBytes: collected.bytes,
250430
+ fileCount: collected.count,
250431
+ cleanup: () => rm(temporaryDirectory, { recursive: true, force: true })
250432
+ };
250433
+ } catch (error) {
250434
+ await rm(temporaryDirectory, { recursive: true, force: true });
250435
+ throw error;
250436
+ }
250437
+ }
250438
+ function payload(response) {
250439
+ if (response.isError)
250440
+ throw new Error(response.content[0]?.text || "Deployment operation failed");
250441
+ const text = response.content.find((chunk) => chunk.type === "text")?.text;
250442
+ const parsed = text ? record(JSON.parse(text)) : null;
250443
+ if (!parsed)
250444
+ throw new Error("Deployment operation returned an invalid response");
250445
+ return parsed;
250446
+ }
250447
+ function phaseReporter(json) {
250448
+ const started = performance.now();
250449
+ return (phase, detail) => {
250450
+ if (!json)
250451
+ console.error(` ${phase.padEnd(10)} ${detail}`);
250452
+ return Math.round(performance.now() - started);
250453
+ };
250454
+ }
250455
+ function deployResponse(result, json) {
250456
+ if (json)
250457
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
250458
+ const lines = [
250459
+ result.unchanged === true ? "Already up to date." : `Deployed ${String(result.target || result.deployment_id || result.slug)}.`,
250460
+ result.url ? `URL: ${String(result.url)}` : null,
250461
+ result.release_id ? `Release: ${String(result.release_id)}` : null,
250462
+ result.active_version ? `Active version: ${String(result.active_version)}` : null,
250463
+ result.file_count ? `Files: ${String(result.file_count)}` : null,
250464
+ `Duration: ${(Number(result.duration_ms) / 1000).toFixed(1)}s`
250465
+ ].filter((line) => Boolean(line));
250466
+ return { content: [{ type: "text", text: lines.join(`
250467
+ `) }] };
250468
+ }
250469
+ function registerDeployTools(server2, http, options = {}) {
250470
+ server2.tool("deploy", "Build and publish the linked frontend with one command", deployToolSchema, async (args) => {
250471
+ const invocationDirectory = resolve10(String(args.cwd || options.cwd || process.cwd()));
250472
+ const projectRef2 = String(args.ref || options.projectRef || "").trim();
250473
+ if (!projectRef2)
250474
+ throw new Error("A linked project ref is required. Set SUPACLOUD_PROJECT_REF or pass --ref");
250475
+ const configRoot = await findDeployConfigRoot(invocationDirectory);
250476
+ const config = await readDeployConfig(configRoot);
250477
+ const target = selectTarget(configRoot, invocationDirectory, config, String(args.target || "").trim() || undefined);
250478
+ const projectDirectory = target.root;
250479
+ const targetState = await lstat(projectDirectory).catch(() => null);
250480
+ if (!targetState?.isDirectory() || targetState.isSymbolicLink()) {
250481
+ throw new Error(`Deploy target '${target.name}' root is not a regular directory: ${projectDirectory}`);
250482
+ }
250483
+ const requestedId = String(args.id || target.config.id || "").trim() || undefined;
250484
+ const report = phaseReporter(args.json === true);
250485
+ report("inspect", `${target.name} (${projectRef2})`);
250486
+ if (target.config.type === "edge_function") {
250487
+ if (!options.edgeFunctionDeploy)
250488
+ throw new Error("Edge Function deploy support is unavailable in this CLI context");
250489
+ const slug = target.config.slug || requestedId || target.name;
250490
+ const functionListResponse2 = await options.edgeFunctionDeploy({
250491
+ action: "list",
250492
+ ref: projectRef2
250493
+ });
250494
+ if (functionListResponse2.isError) {
250495
+ throw new Error(`Unable to read the current identity for Edge Function '${slug}'`);
250496
+ }
250497
+ const functionListText = functionListResponse2.content.find((chunk) => chunk.type === "text")?.text;
250498
+ if (!functionListText)
250499
+ throw new Error(`Unable to read the current identity for Edge Function '${slug}'`);
250500
+ const functions = projectedFunctionList(JSON.parse(functionListText));
250501
+ if (!functions)
250502
+ throw new Error(`Invalid current identity for Edge Function '${slug}'`);
250503
+ const current = functions?.find((candidate) => candidate.slug === slug);
250504
+ const activeVersion = current && typeof current.version === "number" ? String(current.version) : "absent";
250505
+ const activationId = current && typeof current.activation_id === "string" ? current.activation_id : "legacy";
250506
+ if (!activeVersion || !activationId)
250507
+ throw new Error(`Edge Function '${slug}' has an invalid active identity`);
250508
+ const buildCommand2 = String(args.build_command || target.config.buildCommand || "").trim() || (args.skip_build === true ? "" : await defaultBuildCommand(projectDirectory, configRoot));
250509
+ const bundleDirectory = resolveInsideProject(projectDirectory, String(args.output_dir || target.config.bundleDirectory || target.config.outputDirectory || "dist"), true);
250510
+ if (args.dry_run === true) {
250511
+ return { content: [{ type: "text", text: JSON.stringify({
250512
+ ok: true,
250513
+ dry_run: true,
250514
+ type: target.config.type,
250515
+ target: target.name,
250516
+ project_ref: projectRef2,
250517
+ slug,
250518
+ build_command: args.skip_build === true ? null : buildCommand2,
250519
+ bundle_directory: bundleDirectory,
250520
+ expected_active_version: activeVersion,
250521
+ expected_activation_id: activationId
250522
+ }, null, 2) }] };
250523
+ }
250524
+ if (args.skip_build !== true) {
250525
+ report("build", buildCommand2);
250526
+ await runBuild(buildCommand2, projectDirectory);
250527
+ } else {
250528
+ report("build", "skipped");
250529
+ }
250530
+ report("deploy", `edge function ${slug}`);
250531
+ const deployed = await options.edgeFunctionDeploy({
250532
+ action: "deploy_bundle",
250533
+ ref: projectRef2,
250534
+ slug,
250535
+ "bundle-dir": bundleDirectory,
250536
+ entrypoint: target.config.entrypoint || "index.ts",
250537
+ minify: target.config.minify,
250538
+ verify_jwt: target.config.verifyJwt,
250539
+ framework: target.config.framework,
250540
+ "expected-active-version": activeVersion,
250541
+ "expected-activation-id": activationId
250542
+ });
250543
+ if (deployed.isError)
250544
+ return deployed;
250545
+ const deployedText = deployed.content.find((chunk) => chunk.type === "text")?.text;
250546
+ const deployedPayload = deployedText ? record(JSON.parse(deployedText)) : null;
250547
+ const durationMs = report("done", slug);
250548
+ return deployResponse({
250549
+ ok: true,
250550
+ unchanged: false,
250551
+ type: target.config.type,
250552
+ target: target.name,
250553
+ project_ref: projectRef2,
250554
+ slug,
250555
+ active_version: deployedPayload?.active_version,
250556
+ activation_id: deployedPayload?.activation_id,
250557
+ duration_ms: durationMs
250558
+ }, args.json === true);
250559
+ }
250560
+ const listResponse2 = await http.get(`/v1/projects/${encodeURIComponent(projectRef2)}/frontend/deployments`);
250561
+ if (!listResponse2.ok)
250562
+ throw new Error(`Failed to list frontend deployments (HTTP ${listResponse2.status})`);
250563
+ const selected = selectDeployment(deploymentList(listResponse2.data), requestedId, await packageName(projectDirectory));
250564
+ const configuredBuildCommand = String(args.build_command || target.config.buildCommand || selected.buildCommand || "").trim();
250565
+ const buildCommand = configuredBuildCommand || (args.skip_build === true ? "" : await defaultBuildCommand(projectDirectory, configRoot));
250566
+ const configuredOutput = String(args.output_dir || target.config.outputDirectory || "").trim();
250567
+ const remoteOutput = selected.outputDirectory && selected.outputDirectory !== "." ? selected.outputDirectory : "";
250568
+ const outputDirectory = resolveInsideProject(projectDirectory, configuredOutput || remoteOutput || defaultOutputDirectory(selected.framework));
250569
+ if (args.dry_run === true) {
250570
+ return { content: [{ type: "text", text: JSON.stringify({
250571
+ ok: true,
250572
+ dry_run: true,
250573
+ project_ref: projectRef2,
250574
+ deployment_id: selected.id,
250575
+ build_command: args.skip_build === true ? null : buildCommand,
250576
+ output_directory: outputDirectory
250577
+ }, null, 2) }] };
250578
+ }
250579
+ if (args.skip_build !== true) {
250580
+ report("build", buildCommand);
250581
+ await runBuild(buildCommand, projectDirectory);
250582
+ } else {
250583
+ report("build", "skipped");
250584
+ }
250585
+ report("package", relative4(projectDirectory, outputDirectory) || ".");
250586
+ const archive = await createFrontendArchive(outputDirectory);
250587
+ try {
250588
+ const inventory = payload(await listFrontendReleases(http, projectRef2, selected.id, undefined, 100));
250589
+ const activeReleaseId = typeof inventory.active_release_id === "string" ? inventory.active_release_id : null;
250590
+ const activeActivationId = typeof inventory.active_activation_id === "string" ? inventory.active_activation_id : null;
250591
+ if (archive.sha256 === activeReleaseId) {
250592
+ const durationMs2 = report("done", "already current");
250593
+ return deployResponse({
250594
+ ok: true,
250595
+ unchanged: true,
250596
+ project_ref: projectRef2,
250597
+ deployment_id: selected.id,
250598
+ release_id: archive.sha256,
250599
+ url: selected.deploymentUrl,
250600
+ file_count: archive.fileCount,
250601
+ source_bytes: archive.sourceBytes,
250602
+ duration_ms: durationMs2
250603
+ }, args.json === true);
250604
+ }
250605
+ report("upload", `${archive.fileCount} files`);
250606
+ const uploaded = payload(await uploadFrontendRelease(http, projectRef2, selected.id, archive.archivePath));
250607
+ const release = record(uploaded.release);
250608
+ const releaseId = requiredString(release?.release_id, "release.release_id");
250609
+ if (releaseId !== archive.sha256)
250610
+ throw new Error("Uploaded release identity does not match the local archive");
250611
+ report("activate", releaseId.slice(0, 12));
250612
+ const mutationId = crypto.randomUUID();
250613
+ const activated = payload(await activateFrontendRelease(http, {
250614
+ projectRef: projectRef2,
250615
+ deploymentId: selected.id,
250616
+ releaseId,
250617
+ expectedActiveReleaseId: activeReleaseId || "absent",
250618
+ expectedActivationId: activeActivationId || "absent",
250619
+ mutationId
250620
+ }));
250621
+ const finalResponse = await http.get(`/v1/projects/${encodeURIComponent(projectRef2)}/frontend/deployments/${encodeURIComponent(selected.id)}`);
250622
+ const finalDeployment = finalResponse.ok ? frontendDeployment(finalResponse.data) : selected;
250623
+ const durationMs = report("done", finalDeployment.deploymentUrl || selected.id);
250624
+ return deployResponse({
250625
+ ok: true,
250626
+ unchanged: false,
250627
+ project_ref: projectRef2,
250628
+ deployment_id: selected.id,
250629
+ release_id: activated.active_release_id,
250630
+ activation_id: activated.activation_id,
250631
+ url: finalDeployment.deploymentUrl,
250632
+ file_count: archive.fileCount,
250633
+ source_bytes: archive.sourceBytes,
250634
+ duration_ms: durationMs
250635
+ }, args.json === true);
250636
+ } finally {
250637
+ await archive.cleanup();
250638
+ }
250639
+ });
250640
+ }
249454
250641
  // package.json
249455
250642
  var package_default = {
249456
250643
  name: "@supacloud/cli",
249457
- version: "0.38.0",
250644
+ version: "0.40.0",
249458
250645
  description: "Project-scoped CLI for SupaCloud users",
249459
250646
  type: "module",
249460
250647
  main: "./dist/index.js",
@@ -249487,7 +250674,8 @@ var package_default = {
249487
250674
  dependencies: {
249488
250675
  "@sinclair/typebox": "^0.34.52",
249489
250676
  "@supacloud/compiler": "^0.1.0",
249490
- "@supacloud/db": "^0.1.0"
250677
+ "@supacloud/db": "^0.1.0",
250678
+ fflate: "^0.8.3"
249491
250679
  },
249492
250680
  devDependencies: {
249493
250681
  "@types/bun": "^1.4.0",
@@ -249666,6 +250854,7 @@ function printHelp(context) {
249666
250854
 
249667
250855
  USAGE
249668
250856
 
250857
+ ${preferredCommand} [global flags] deploy [--flags]
249669
250858
  ${preferredCommand} [global flags] <module> <action> [--flags]
249670
250859
  ${preferredCommand} [global flags] status
249671
250860
  ${preferredCommand} --help
@@ -249700,6 +250889,9 @@ DEFAULT CONTEXT
249700
250889
  EXAMPLES
249701
250890
 
249702
250891
  ${preferredCommand} status
250892
+ ${preferredCommand} deploy
250893
+ ${preferredCommand} deploy --target web
250894
+ ${preferredCommand} deploy --target api
249703
250895
  ${preferredCommand} project get
249704
250896
  ${preferredCommand} project logs --log_type database
249705
250897
  ${preferredCommand} project task_stats
@@ -249738,6 +250930,7 @@ EXAMPLES
249738
250930
  ${preferredCommand} db lint --root . --module_file db/modules.ts
249739
250931
  ${preferredCommand} db explain --target public.cases --module_file db/modules.ts
249740
250932
  ${preferredCommand} db module_check --module_file db/modules.ts --database_url "postgresql://..."
250933
+ ${preferredCommand} db module_check --lite --project_dir .
249741
250934
  ${preferredCommand} edge_functions get_config --ref abc123 --slug hello
249742
250935
  ${preferredCommand} edge_functions deploy --ref abc123 --slug hello --path ./supabase/functions/hello --expected-active-version absent --expected-activation-id legacy
249743
250936
  ${preferredCommand} edge_functions deploy --ref abc123 --slug hello --prebundled-path ./dist/hello.js --expected-sha256 <sha256> --expected-active-version 4 --expected-activation-id <uuid>
@@ -249852,6 +251045,16 @@ function createCliTools(context, confirmProduction) {
249852
251045
  };
249853
251046
  if (context.credentialScope !== "management" || !context.apiUrl || !context.apiToken) {
249854
251047
  registerContextAwareHelp();
251048
+ tools.deploy = {
251049
+ schema: deployToolSchema,
251050
+ callback: async () => ({
251051
+ isError: true,
251052
+ content: [{
251053
+ type: "text",
251054
+ text: `⚠️ Deploy requires Management API context. Run \`${preferredCommand} status\` to inspect current detection.`
251055
+ }]
251056
+ })
251057
+ };
249855
251058
  Object.assign(tools, captureTools((server2) => registerDatabaseTools(server2, undefined, {
249856
251059
  localOnly: true
249857
251060
  })));
@@ -249910,9 +251113,10 @@ function createCliTools(context, confirmProduction) {
249910
251113
  assign(captureTools((server2) => registerAuthTools(server2, http)));
249911
251114
  assign(captureTools((server2) => registerOAuthClientTools(server2, http)));
249912
251115
  assign(captureTools((server2) => registerStorageTools(server2, http)));
249913
- assign(captureTools((server2) => registerAdvancedTools(server2, http, process.env, {
251116
+ const advancedTools = captureTools((server2) => registerAdvancedTools(server2, http, process.env, {
249914
251117
  readOnly: context.readOnly
249915
- })));
251118
+ }));
251119
+ assign(advancedTools);
249916
251120
  assign(captureTools((server2) => registerScheduledFunctionTools(server2, http, process.env, {
249917
251121
  readOnly: context.readOnly
249918
251122
  })));
@@ -249923,6 +251127,11 @@ function createCliTools(context, confirmProduction) {
249923
251127
  applicationOrigin: context.inferredSupabaseUrl || undefined
249924
251128
  })));
249925
251129
  assign(captureTools((server2) => registerFrontendTools(server2, http)));
251130
+ assign(captureTools((server2) => registerDeployTools(server2, http, {
251131
+ projectRef: context.projectRef || undefined,
251132
+ cwd: process.cwd(),
251133
+ edgeFunctionDeploy: advancedTools.edge_functions?.callback
251134
+ })));
249926
251135
  assign(captureTools((server2) => registerGatewayTools(server2, http, {
249927
251136
  projectRef: context.projectRef || undefined
249928
251137
  })));
@@ -249944,7 +251153,8 @@ async function main() {
249944
251153
  }
249945
251154
  const globalOptions = parseGlobalOptions(rawArgs);
249946
251155
  const args = globalOptions.args;
249947
- const context = resolveSupaCloudContext(process.env, process.cwd(), {
251156
+ const contextDirectory = args[0] === "deploy" ? await findDeployConfigRoot(process.cwd()) : process.cwd();
251157
+ const context = resolveSupaCloudContext(process.env, contextDirectory, {
249948
251158
  environmentName: globalOptions.environmentName,
249949
251159
  envFile: globalOptions.envFile
249950
251160
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/cli",
3
- "version": "0.38.0",
3
+ "version": "0.40.0",
4
4
  "description": "Project-scoped CLI for SupaCloud users",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -33,7 +33,8 @@
33
33
  "dependencies": {
34
34
  "@sinclair/typebox": "^0.34.52",
35
35
  "@supacloud/compiler": "^0.1.0",
36
- "@supacloud/db": "^0.1.0"
36
+ "@supacloud/db": "^0.1.0",
37
+ "fflate": "^0.8.3"
37
38
  },
38
39
  "devDependencies": {
39
40
  "@types/bun": "^1.4.0",