@lizard-build/sdk 0.1.21 → 0.1.23

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/dist/index.js CHANGED
@@ -22,6 +22,7 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  AuthenticationError: () => AuthenticationError,
24
24
  CodeSandbox: () => CodeSandbox,
25
+ DeployHandle: () => DeployHandle,
25
26
  Lizard: () => Lizard,
26
27
  LizardError: () => LizardError,
27
28
  NotFoundError: () => NotFoundError,
@@ -456,19 +457,437 @@ var Sandbox = class extends SandboxClient {
456
457
  Sandbox.defaultTemplate = "base";
457
458
  Sandbox.defaultTimeoutMs = DEFAULT_SANDBOX_TIMEOUT_MS;
458
459
 
460
+ // src/platform/client.ts
461
+ var PlatformClient = class {
462
+ constructor(opts) {
463
+ this.config = new ConnectionConfig(opts);
464
+ }
465
+ async get(path) {
466
+ const res = await fetch(`${this.config.apiUrl}${path}`, {
467
+ headers: this.config.headers
468
+ });
469
+ if (!res.ok) await handleApiError(res);
470
+ return res.json();
471
+ }
472
+ async post(path, body) {
473
+ const res = await fetch(`${this.config.apiUrl}${path}`, {
474
+ method: "POST",
475
+ headers: this.config.headers,
476
+ body: body !== void 0 ? JSON.stringify(body) : void 0
477
+ });
478
+ if (!res.ok) await handleApiError(res);
479
+ return res.json();
480
+ }
481
+ async patch(path, body) {
482
+ const res = await fetch(`${this.config.apiUrl}${path}`, {
483
+ method: "PATCH",
484
+ headers: this.config.headers,
485
+ body: JSON.stringify(body)
486
+ });
487
+ if (!res.ok) await handleApiError(res);
488
+ return res.json();
489
+ }
490
+ async delete(path, body) {
491
+ const res = await fetch(`${this.config.apiUrl}${path}`, {
492
+ method: "DELETE",
493
+ headers: this.config.headers,
494
+ body: body !== void 0 ? JSON.stringify(body) : void 0
495
+ });
496
+ if (!res.ok) await handleApiError(res);
497
+ if (res.status === 204 || res.headers.get("content-length") === "0") return void 0;
498
+ return res.json();
499
+ }
500
+ async postForm(path, form) {
501
+ const headers = { "X-API-Key": this.config.apiKey };
502
+ const res = await fetch(`${this.config.apiUrl}${path}`, {
503
+ method: "POST",
504
+ headers,
505
+ body: form
506
+ });
507
+ if (!res.ok) await handleApiError(res);
508
+ return res.json();
509
+ }
510
+ /** Stream SSE events from a path, calling handler for each data line. */
511
+ async *streamSse(path) {
512
+ const res = await fetch(`${this.config.apiUrl}${path}`, {
513
+ headers: this.config.headers
514
+ });
515
+ if (!res.ok) await handleApiError(res);
516
+ if (!res.body) return;
517
+ const reader = res.body.getReader();
518
+ const decoder = new TextDecoder();
519
+ let buf = "";
520
+ while (true) {
521
+ const { done, value } = await reader.read();
522
+ if (done) break;
523
+ buf += decoder.decode(value, { stream: true });
524
+ const events = buf.split("\n\n");
525
+ buf = events.pop();
526
+ for (const evt of events) {
527
+ const dataLine = evt.split("\n").find((l) => l.startsWith("data: "));
528
+ if (dataLine) yield dataLine.slice(6);
529
+ }
530
+ }
531
+ }
532
+ };
533
+
534
+ // src/platform/projects.ts
535
+ var ProjectsAPI = class {
536
+ constructor(client) {
537
+ this.client = client;
538
+ }
539
+ /** List all projects the API key can access. */
540
+ list(opts) {
541
+ const qs = opts?.workspaceId ? `?workspaceId=${opts.workspaceId}` : "";
542
+ return this.client.get(`/api/projects${qs}`);
543
+ }
544
+ /** Get a project by ID. */
545
+ get(id) {
546
+ return this.client.get(`/api/projects/${id}`);
547
+ }
548
+ /** Create a new project. */
549
+ create(opts) {
550
+ return this.client.post("/api/projects", opts);
551
+ }
552
+ /** Update a project's name. */
553
+ update(id, opts) {
554
+ return this.client.patch(`/api/projects/${id}`, opts);
555
+ }
556
+ /** Delete a project. */
557
+ delete(id) {
558
+ return this.client.delete(`/api/projects/${id}`);
559
+ }
560
+ };
561
+
562
+ // src/platform/services.ts
563
+ var DeployHandle = class {
564
+ constructor(client, serviceId, buildId) {
565
+ this._client = client;
566
+ this._serviceId = serviceId;
567
+ this._buildId = buildId;
568
+ }
569
+ get serviceId() {
570
+ return this._serviceId;
571
+ }
572
+ /** Stream build + runtime log lines until the deploy finishes. */
573
+ async *logs() {
574
+ const path = `/api/apps/${this._serviceId}/logs?limit=1000`;
575
+ const res = await fetch(`${this._client.config.apiUrl}${path}`, {
576
+ headers: this._client.config.headers
577
+ });
578
+ if (!res.ok) return;
579
+ const body = await res.json();
580
+ const lines = Array.isArray(body) ? body : body.logs ?? [];
581
+ for (const l of lines) yield typeof l === "string" ? l : JSON.stringify(l);
582
+ }
583
+ /**
584
+ * Poll until the deploy reaches a terminal state.
585
+ * @returns `{ url, status }` on success; throws `LizardError` on failure.
586
+ */
587
+ async wait(opts) {
588
+ const deadline = Date.now() + (opts?.timeoutMs ?? 10 * 6e4);
589
+ const pollMs = opts?.pollMs ?? 3e3;
590
+ while (Date.now() < deadline) {
591
+ const svc = await this._client.get(`/api/apps/${this._serviceId}`);
592
+ if (svc.deployStatus === "idle") {
593
+ if (svc.status === "running") return { url: svc.domain ? `https://${svc.domain}` : null, status: "running" };
594
+ if (svc.status === "crashed") throw new LizardError(`Service crashed after deploy`);
595
+ }
596
+ if (svc.deployStatus === "failed") throw new LizardError(`Deploy failed`);
597
+ await new Promise((r) => setTimeout(r, pollMs));
598
+ }
599
+ throw new TimeoutError(`Deploy did not complete within ${opts?.timeoutMs ?? 6e5}ms`);
600
+ }
601
+ };
602
+ var ServicesAPI = class {
603
+ constructor(client) {
604
+ this.client = client;
605
+ }
606
+ /** List all services in a project. */
607
+ list(opts) {
608
+ return this.client.get(`/api/projects/${opts.projectId}/apps`);
609
+ }
610
+ /** Get a service by ID. */
611
+ get(id) {
612
+ return this.client.get(`/api/apps/${id}`);
613
+ }
614
+ /**
615
+ * Create a service and start a deploy from a git repo.
616
+ * Returns a DeployHandle to track progress.
617
+ */
618
+ async deploy(opts) {
619
+ const body = {
620
+ name: opts.name,
621
+ sourceType: opts.sourceType ?? "github",
622
+ repoUrl: opts.repoUrl,
623
+ branch: opts.branch ?? "main",
624
+ startCommand: opts.startCommand,
625
+ buildCommand: opts.buildCommand,
626
+ containerPort: opts.port ?? opts.containerPort,
627
+ region: opts.region
628
+ };
629
+ const svc = await this.client.post(`/api/projects/${opts.projectId}/apps`, body);
630
+ return new DeployHandle(this.client, svc.id);
631
+ }
632
+ /**
633
+ * Upload a tarball and deploy it.
634
+ *
635
+ * @param opts.source - A `Buffer`, `Blob`, or `Uint8Array` of a `.tar.gz` file.
636
+ */
637
+ async upload(opts) {
638
+ const form = new FormData();
639
+ const blob = opts.source instanceof Blob ? opts.source : new Blob([opts.source], { type: "application/gzip" });
640
+ form.append("file", blob, "source.tar.gz");
641
+ form.append("name", opts.name);
642
+ if (opts.startCommand) form.append("startCommand", opts.startCommand);
643
+ if (opts.buildCommand) form.append("buildCommand", opts.buildCommand);
644
+ if (opts.port !== void 0) form.append("containerPort", String(opts.port));
645
+ if (opts.region) form.append("region", opts.region);
646
+ const result = await this.client.postForm(
647
+ `/api/projects/${opts.projectId}/apps/upload`,
648
+ form
649
+ );
650
+ return new DeployHandle(this.client, result.id, result.buildId);
651
+ }
652
+ /** Trigger a redeploy (rebuild from current source). */
653
+ async redeploy(id) {
654
+ await this.client.post(`/api/apps/${id}/redeploy`, {});
655
+ return new DeployHandle(this.client, id);
656
+ }
657
+ /** Restart a service without rebuilding. */
658
+ restart(id) {
659
+ return this.client.post(`/api/apps/${id}/restart`, {});
660
+ }
661
+ /** Scale a service. */
662
+ scale(id, opts) {
663
+ return this.client.post(`/api/apps/${id}/scale`, opts);
664
+ }
665
+ /**
666
+ * Get recent log lines. For a live tail, use the WebSocket API instead.
667
+ *
668
+ * @param opts.limit - Max lines to return (default 200, max 1000).
669
+ */
670
+ async logs(id, opts) {
671
+ const qs = new URLSearchParams();
672
+ if (opts?.limit) qs.set("limit", String(opts.limit));
673
+ if (opts?.since) qs.set("since", opts.since);
674
+ const result = await this.client.get(`/api/apps/${id}/logs?${qs}`);
675
+ return Array.isArray(result) ? result : result.logs ?? [];
676
+ }
677
+ /** Execute a command inside the running service VM. */
678
+ exec(id, cmd, opts) {
679
+ return this.client.post(`/api/apps/${id}/exec`, { cmd, timeoutMs: opts?.timeoutMs });
680
+ }
681
+ /** Update service configuration. */
682
+ update(id, opts) {
683
+ return this.client.patch(`/api/apps/${id}`, opts);
684
+ }
685
+ /** Delete a service. */
686
+ delete(id) {
687
+ return this.client.delete(`/api/apps/${id}`);
688
+ }
689
+ };
690
+
691
+ // src/platform/addons.ts
692
+ var AddonsAPI = class {
693
+ constructor(client) {
694
+ this.client = client;
695
+ }
696
+ /** List all addons in a project. */
697
+ list(opts) {
698
+ return this.client.get(`/api/projects/${opts.projectId}/addons`);
699
+ }
700
+ /** Get an addon by ID. */
701
+ get(projectId, addonId) {
702
+ return this.client.get(`/api/projects/${projectId}/addons/${addonId}`);
703
+ }
704
+ /**
705
+ * Create a new managed addon (database, cache, or object store).
706
+ *
707
+ * @example
708
+ * ```ts
709
+ * const pg = await lizard.addons.create({ projectId, type: 'postgres' })
710
+ * // Inject into a service:
711
+ * await lizard.secrets.set({ serviceId: svcId, key: 'DATABASE_URL', value: `${{${pg.name}.DATABASE_URL}}` })
712
+ * ```
713
+ */
714
+ create(opts) {
715
+ return this.client.post(`/api/projects/${opts.projectId}/addons`, {
716
+ type: opts.type,
717
+ name: opts.name,
718
+ version: opts.version,
719
+ vcpu: opts.vcpu,
720
+ memoryMb: opts.memoryMb,
721
+ storageGb: opts.storageGb
722
+ });
723
+ }
724
+ /** Delete an addon. */
725
+ delete(projectId, addonId) {
726
+ return this.client.delete(`/api/projects/${projectId}/addons/${addonId}`);
727
+ }
728
+ /** Resize an addon (CPU / memory / storage). */
729
+ resize(projectId, addonId, opts) {
730
+ return this.client.post(`/api/projects/${projectId}/addons/${addonId}/resize`, opts);
731
+ }
732
+ /** Restart an addon VM. */
733
+ redeploy(projectId, addonId) {
734
+ return this.client.post(`/api/projects/${projectId}/addons/${addonId}/redeploy`, {});
735
+ }
736
+ };
737
+
738
+ // src/platform/secrets.ts
739
+ var SecretsAPI = class {
740
+ constructor(client) {
741
+ this.client = client;
742
+ }
743
+ /**
744
+ * List secrets for a project or service.
745
+ *
746
+ * @param projectId - The project ID.
747
+ * @param opts.serviceId - If given, list service-scoped secrets instead of project secrets.
748
+ */
749
+ list(projectId, opts) {
750
+ if (opts?.serviceId) {
751
+ return this.client.get(`/api/apps/${opts.serviceId}/secrets`);
752
+ }
753
+ return this.client.get(`/api/projects/${projectId}/secrets`);
754
+ }
755
+ /**
756
+ * Set one or more secrets.
757
+ *
758
+ * ```ts
759
+ * // Service-scoped secret (default):
760
+ * await lizard.secrets.set(projectId, { key: 'DATABASE_URL', value: '${{postgres.DATABASE_URL}}', serviceId })
761
+ *
762
+ * // Project-scoped (shared across all services):
763
+ * await lizard.secrets.set(projectId, { key: 'LOG_LEVEL', value: 'info', global: true })
764
+ * ```
765
+ */
766
+ async set(projectId, secrets) {
767
+ const items = Array.isArray(secrets) ? secrets : [secrets];
768
+ const byService = /* @__PURE__ */ new Map();
769
+ const projectScoped = {};
770
+ for (const s of items) {
771
+ if (s.global || !s.serviceId) {
772
+ projectScoped[s.key] = s.value;
773
+ } else {
774
+ if (!byService.has(s.serviceId)) byService.set(s.serviceId, {});
775
+ byService.get(s.serviceId)[s.key] = s.value;
776
+ }
777
+ }
778
+ const tasks = [];
779
+ if (Object.keys(projectScoped).length > 0) {
780
+ tasks.push(this.client.post(`/api/projects/${projectId}/secrets`, projectScoped));
781
+ }
782
+ for (const [serviceId, kv] of byService) {
783
+ tasks.push(this.client.post(`/api/apps/${serviceId}/secrets`, kv));
784
+ }
785
+ await Promise.all(tasks);
786
+ }
787
+ /** Delete a secret by key. */
788
+ async delete(projectId, opts) {
789
+ if (opts.serviceId) {
790
+ await this.client.delete(`/api/apps/${opts.serviceId}/secrets`, { key: opts.key });
791
+ } else {
792
+ await this.client.delete(`/api/projects/${projectId}/secrets`, { key: opts.key });
793
+ }
794
+ }
795
+ };
796
+
797
+ // src/platform/domains.ts
798
+ var DomainsAPI = class {
799
+ constructor(client) {
800
+ this.client = client;
801
+ }
802
+ /**
803
+ * Show the current domain(s) for a service.
804
+ * The platform-assigned `.onlizard.com` subdomain is always present.
805
+ */
806
+ list(serviceId) {
807
+ return this.client.get(`/api/apps/${serviceId}/domains`);
808
+ }
809
+ /**
810
+ * Attach a custom domain to a service.
811
+ * Returns the DNS records to add before calling `verify()`.
812
+ *
813
+ * @example
814
+ * ```ts
815
+ * const info = await lizard.domains.add(serviceId, 'api.example.com')
816
+ * console.log('Add CNAME:', info.cnameTarget)
817
+ * ```
818
+ */
819
+ add(serviceId, domain) {
820
+ return this.client.post(`/api/apps/${serviceId}/domains`, { domain });
821
+ }
822
+ /**
823
+ * Verify that DNS records have propagated and activate the domain.
824
+ * Call after adding the CNAME or TXT record returned by `add()`.
825
+ */
826
+ verify(serviceId, domain) {
827
+ return this.client.post(`/api/apps/${serviceId}/domains/verify`, { domain });
828
+ }
829
+ };
830
+
831
+ // src/platform/metrics.ts
832
+ var MetricsAPI = class {
833
+ constructor(client) {
834
+ this.client = client;
835
+ }
836
+ /** Get CPU metrics for a service or addon. */
837
+ cpu(id, range = "1h") {
838
+ return this.client.get(`/api/apps/${id}/metrics/cpu?range=${range}`);
839
+ }
840
+ /** Get memory metrics for a service or addon. */
841
+ memory(id, range = "1h") {
842
+ return this.client.get(`/api/apps/${id}/metrics/memory?range=${range}`);
843
+ }
844
+ /** Get network I/O metrics for a service. */
845
+ network(id, range = "1h") {
846
+ return this.client.get(`/api/apps/${id}/metrics/network?range=${range}`);
847
+ }
848
+ /** Get disk I/O metrics for a service. */
849
+ disk(id, range = "1h") {
850
+ return this.client.get(`/api/apps/${id}/metrics/disk?range=${range}`);
851
+ }
852
+ /**
853
+ * Get cost breakdown for a project over the given range.
854
+ * Costs are in USD cents unless the `currency` field says otherwise.
855
+ */
856
+ cost(projectId, range = "30d") {
857
+ return this.client.get(`/api/projects/${projectId}/metrics/cost?range=${range}`);
858
+ }
859
+ /**
860
+ * Convenience: fetch all metric types for a service in one call.
861
+ */
862
+ async all(id, range = "1h") {
863
+ const [cpu, memory, network, disk] = await Promise.all([
864
+ this.cpu(id, range),
865
+ this.memory(id, range),
866
+ this.network(id, range),
867
+ this.disk(id, range)
868
+ ]);
869
+ return { cpu, memory, networkRx: network.rx, networkTx: network.tx, diskRead: disk.read, diskWrite: disk.write };
870
+ }
871
+ };
872
+
459
873
  // src/lizard.ts
460
874
  var Lizard = class {
461
875
  constructor(opts) {
462
- if (!opts?.project) {
463
- throw new LizardError(
464
- 'A project is required. Pass project (its ID, slug, or name): new Lizard({ project: "my-project" }).'
465
- );
466
- }
467
876
  this.config = new ConnectionConfig(opts);
468
877
  this.projectRef = opts.project;
878
+ const platform = new PlatformClient(opts);
879
+ this._platform = platform;
880
+ this.projects = new ProjectsAPI(platform);
881
+ this.services = new ServicesAPI(platform);
882
+ this.addons = new AddonsAPI(platform);
883
+ this.secrets = new SecretsAPI(platform);
884
+ this.domains = new DomainsAPI(platform);
885
+ this.metrics = new MetricsAPI(platform);
469
886
  }
887
+ // ── Sandbox convenience methods (backward-compatible) ──────────────────
470
888
  /** Resolve the client's project reference to a stable project ID (cached). */
471
889
  async projectId() {
890
+ if (!this.projectRef) throw new LizardError("No project set. Pass project in Lizard({ project }) to use sandbox APIs.");
472
891
  return resolveProjectId(this.projectRef, this.config);
473
892
  }
474
893
  async connectionOpts(extra) {
@@ -476,12 +895,7 @@ var Lizard = class {
476
895
  }
477
896
  /**
478
897
  * Create a new sandbox in this client's project.
479
- *
480
- * @example
481
- * ```ts
482
- * const sandbox = await lizard.create('base')
483
- * const sandbox = await lizard.create('code-interpreter-v1', { timeoutMs: 600_000 })
484
- * ```
898
+ * @requires `project` to be set in the constructor.
485
899
  */
486
900
  async create(template, opts) {
487
901
  const projectId = await this.projectId();
@@ -740,6 +1154,7 @@ var Volume = class _Volume {
740
1154
  0 && (module.exports = {
741
1155
  AuthenticationError,
742
1156
  CodeSandbox,
1157
+ DeployHandle,
743
1158
  Lizard,
744
1159
  LizardError,
745
1160
  NotFoundError,