@n-dream/builders-sdk 0.2.2 → 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.
Files changed (3) hide show
  1. package/README.md +4 -2
  2. package/dist/index.js +186 -15
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -13,7 +13,7 @@ Apps import the package as `@builders/sdk`. Use an npm alias in
13
13
 
14
14
  ```json
15
15
  "dependencies": {
16
- "@builders/sdk": "npm:@n-dream/builders-sdk@^0.2.2"
16
+ "@builders/sdk": "npm:@n-dream/builders-sdk@^0.3.0"
17
17
  }
18
18
  ```
19
19
 
@@ -25,6 +25,7 @@ later.
25
25
  ```ts
26
26
  import { currentUser } from "@builders/sdk/next"; // server code only
27
27
  import { db, ai, storage, notify, secrets } from "@builders/sdk";
28
+ import { z } from "zod";
28
29
 
29
30
  const user = await currentUser(); // { email, name }
30
31
  const notes = db.collection<{ text: string; author: string }>("notes");
@@ -40,7 +41,8 @@ await secrets.get("HUBSPOT_API_KEY"); // set in the portal
40
41
  ```
41
42
 
42
43
  - `db` uses Firestore on the platform. In `next dev` and in tests, it uses
43
- a temporary database in memory.
44
+ a temporary database in memory. In the Builders dev preview, `ai` and
45
+ `notify` work through the platform (notifications go only to you).
44
46
  - `ai`, `storage` and `notify` are add-ons. If an add-on is off, the call
45
47
  throws `AddOnNotEnabledError`.
46
48
 
package/dist/index.js CHANGED
@@ -261,6 +261,32 @@ function secretNameError(name) {
261
261
  return null;
262
262
  }
263
263
 
264
+ // ../core/src/dev-data.ts
265
+ var DEV_ENV = {
266
+ url: "BUILDERS_DEV_URL",
267
+ tokenFile: "BUILDERS_TUNNEL_TOKEN_FILE"
268
+ };
269
+
270
+ // ../core/src/dev-files.ts
271
+ var DEV_FILES_PATH = "/_builders/dev-files/";
272
+ var DEV_DATA_DIR_ENV = "BUILDERS_DEV_DATA_DIR";
273
+ var DEV_FILES_SECRET_ENV = "BUILDERS_DEV_FILES_SECRET";
274
+ var DEV_PREVIEW_URL_ENV = "BUILDERS_DEV_PREVIEW_URL";
275
+ var enc = new TextEncoder();
276
+ async function sign(secret, g2) {
277
+ const key2 = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
278
+ const mac = await crypto.subtle.sign("HMAC", key2, enc.encode(`${g2.action}
279
+ ${g2.path}
280
+ ${g2.expires}
281
+ ${g2.contentType}`));
282
+ return [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, "0")).join("");
283
+ }
284
+ async function devFileLink(secret, g2) {
285
+ const q = new URLSearchParams({ a: g2.action, e: String(g2.expires), ...g2.contentType ? { ct: g2.contentType } : {} });
286
+ q.set("s", await sign(secret, g2));
287
+ return `${DEV_FILES_PATH}${g2.path.split("/").map(encodeURIComponent).join("/")}?${q}`;
288
+ }
289
+
264
290
  // src/db-limit.ts
265
291
  var MAX_QUERY_LIMIT = 500;
266
292
  function checkLimit(n) {
@@ -383,11 +409,51 @@ function toPlain(v, Timestamp) {
383
409
 
384
410
  // src/db-memory.ts
385
411
  import { randomBytes } from "node:crypto";
412
+ import { mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
413
+ import { join as join2 } from "node:path";
386
414
  var warnedCap = /* @__PURE__ */ new Set();
387
415
  var g = globalThis;
388
- var store = () => g.__buildersMemoryDb ??= /* @__PURE__ */ new Map();
416
+ var store = () => g.__buildersMemoryDb ??= load();
417
+ var SAVE_DELAY_MS = 100;
418
+ var dbFile = () => {
419
+ const dir = process.env[DEV_DATA_DIR_ENV];
420
+ return dir ? join2(dir, "db.json") : null;
421
+ };
422
+ function load() {
423
+ const file = dbFile();
424
+ const s = /* @__PURE__ */ new Map();
425
+ if (!file) return s;
426
+ let raw;
427
+ try {
428
+ raw = JSON.parse(
429
+ readFileSync2(file, "utf8"),
430
+ (_k, v) => v && typeof v === "object" && typeof v.$date === "string" && Object.keys(v).length === 1 ? new Date(v.$date) : v
431
+ );
432
+ } catch {
433
+ return s;
434
+ }
435
+ for (const [name, docs] of Object.entries(raw)) s.set(name, new Map(Object.entries(docs)));
436
+ return s;
437
+ }
438
+ function saveSoon() {
439
+ const file = dbFile();
440
+ if (!file || g.__buildersMemoryDbSave) return;
441
+ g.__buildersMemoryDbSave = setTimeout(() => {
442
+ g.__buildersMemoryDbSave = void 0;
443
+ const out = {};
444
+ for (const [name, docs] of store()) out[name] = Object.fromEntries(docs);
445
+ const text = JSON.stringify(out, function(k, v) {
446
+ const raw = this[k];
447
+ return raw instanceof Date ? { $date: raw.toISOString() } : v;
448
+ });
449
+ mkdirSync(join2(file, ".."), { recursive: true });
450
+ writeFileSync(`${file}.tmp`, text);
451
+ renameSync(`${file}.tmp`, file);
452
+ }, SAVE_DELAY_MS);
453
+ }
389
454
  function resetMemoryDb() {
390
455
  store().clear();
456
+ saveSoon();
391
457
  }
392
458
  function memoryCollection(name) {
393
459
  const docs = () => {
@@ -431,18 +497,22 @@ function memoryCollection(name) {
431
497
  async add(data) {
432
498
  const id = autoId();
433
499
  docs().set(id, clean(data));
500
+ saveSoon();
434
501
  return out(id, docs().get(id));
435
502
  },
436
503
  async set(id, data) {
437
504
  docs().set(id, clean(data));
505
+ saveSoon();
438
506
  },
439
507
  async update(id, patch) {
440
508
  const d = docs().get(id);
441
509
  if (!d) throw new NotFoundError(`No document "${id}" in "${name}".`);
442
510
  docs().set(id, { ...d, ...clean(patch) });
511
+ saveSoon();
443
512
  },
444
513
  async delete(id) {
445
514
  docs().delete(id);
515
+ saveSoon();
446
516
  }
447
517
  });
448
518
  return query({ where: [], orderBy: [] });
@@ -505,7 +575,9 @@ var db = {
505
575
  if (dbMode() === "firestore") return firestoreCollection(name);
506
576
  if (!warned && process.env.NODE_ENV !== "test") {
507
577
  warned = true;
508
- console.info("[builders] Using a temporary in-memory database. Data is lost when the dev server stops.");
578
+ console.info(
579
+ process.env[DEV_DATA_DIR_ENV] ? `[builders] Using the local test database in ${process.env[DEV_DATA_DIR_ENV]}.` : "[builders] Using a temporary in-memory database. Data is lost when the dev server stops."
580
+ );
509
581
  }
510
582
  return memoryCollection(name);
511
583
  },
@@ -517,6 +589,7 @@ var db = {
517
589
  import { z as z3 } from "zod";
518
590
 
519
591
  // src/platform.ts
592
+ import { readFileSync as readFileSync3, statSync as statSync2 } from "node:fs";
520
593
  var METADATA = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default";
521
594
  var idTokens = /* @__PURE__ */ new Map();
522
595
  var accessToken;
@@ -554,14 +627,47 @@ async function googleAccessToken() {
554
627
  accessToken = { token: j.access_token, exp: Date.now() + (j.expires_in ?? 300) * 1e3 };
555
628
  return accessToken.token;
556
629
  }
630
+ function devUrl(env = process.env) {
631
+ const url = env[DEV_ENV.url]?.trim();
632
+ if (!url || env.NODE_ENV === "production" || env.K_SERVICE) return null;
633
+ return url.replace(/\/+$/, "");
634
+ }
635
+ var devTokenCache;
636
+ var NO_DEV_TOKEN = "Start the dev preview again with the preview command from open_app (it gives a new token).";
637
+ function devToken(env = process.env) {
638
+ const path = env[DEV_ENV.tokenFile]?.trim();
639
+ if (!path) throw new BuildersError(`The dev preview has no Builders token (${DEV_ENV.tokenFile} is not set). ${NO_DEV_TOKEN}`, 401);
640
+ let st;
641
+ try {
642
+ st = statSync2(path);
643
+ } catch {
644
+ throw new BuildersError(`The dev preview's Builders token file is missing. ${NO_DEV_TOKEN}`, 401);
645
+ }
646
+ const c = devTokenCache;
647
+ if (c && c.path === path && c.mtimeMs === st.mtimeMs && c.size === st.size) return c.token;
648
+ let token;
649
+ try {
650
+ token = (readFileSync3(path, "utf8").split("\n")[0] ?? "").trim();
651
+ } catch {
652
+ throw new BuildersError(`The dev preview's Builders token file cannot be read. ${NO_DEV_TOKEN}`, 401);
653
+ }
654
+ if (!token) throw new BuildersError(`The dev preview's Builders token file is empty. ${NO_DEV_TOKEN}`, 401);
655
+ devTokenCache = { path, mtimeMs: st.mtimeMs, size: st.size, token };
656
+ return token;
657
+ }
557
658
  var NotOnBuildersError = class extends BuildersError {
558
659
  constructor(what) {
559
- super(`${what} works only in a saved version or the live app on Builders, not in the Studio preview or on this computer. Save a version and try it there.`, 503);
660
+ super(
661
+ `${what} works only on Builders: in the dev preview, a saved version and the live app. It does not work in pnpm dev without the Builders preview, or in tests. Start the dev preview with the commands from open_app, or show a short note here.`,
662
+ 503
663
+ );
560
664
  this.name = "NotOnBuildersError";
561
665
  }
562
666
  };
563
667
  var WHAT = { ai: "AI", notify: "Sending notifications" };
564
668
  function gateway(addOn) {
669
+ const dev = devUrl();
670
+ if (dev) return { url: dev, app: "", dev: true };
565
671
  const tenant = process.env[APP_ENV.tenant];
566
672
  const app = process.env[APP_ENV.app];
567
673
  if (!tenant || !app) throw new NotOnBuildersError(WHAT[addOn] ?? "This");
@@ -574,17 +680,18 @@ function errorOf(status, body, fallback) {
574
680
  return new BuildersError(msg, status === 429 && body?.error?.code === "budget" ? 402 : status);
575
681
  }
576
682
  async function gatewayFetch(t, path, body, o = {}) {
577
- const token = await idToken(t.url);
683
+ const headers = t.dev ? { "content-type": "application/json", authorization: `Bearer ${devToken()}` } : { "content-type": "application/json", authorization: `Bearer ${await idToken(t.url)}`, [APP_HEADER]: t.app };
684
+ const url = t.dev ? `${t.url}${path.replace(/^\/v1(?=\/)/, "")}` : `${t.url}${path}`;
578
685
  let res;
579
686
  try {
580
- res = await fetch(`${t.url}${path}`, {
687
+ res = await fetch(url, {
581
688
  method: "POST",
582
- headers: { "content-type": "application/json", authorization: `Bearer ${token}`, [APP_HEADER]: t.app },
689
+ headers,
583
690
  body: JSON.stringify(body),
584
691
  signal: o.signal ?? AbortSignal.timeout(o.timeoutMs ?? 12e4)
585
692
  });
586
693
  } catch (e) {
587
- throw new BuildersError(`Could not reach the platform's AI service: ${e.message}`, 502);
694
+ throw new BuildersError(`Could not reach the platform's ${t.dev ? "dev preview service" : "AI service"}: ${e.message}`, 502);
588
695
  }
589
696
  if (!res.ok) {
590
697
  const text = await res.text();
@@ -593,7 +700,7 @@ async function gatewayFetch(t, path, body, o = {}) {
593
700
  j = JSON.parse(text);
594
701
  } catch {
595
702
  }
596
- throw errorOf(res.status, j, `The platform's AI service answered ${res.status}.`);
703
+ throw errorOf(res.status, j, `The platform's ${t.dev ? "dev preview service" : "AI service"} answered ${res.status}.`);
597
704
  }
598
705
  return res;
599
706
  }
@@ -602,22 +709,73 @@ async function gatewayJson(addOn, path, body, o = {}) {
602
709
  return await res.json();
603
710
  }
604
711
 
605
- // src/http.ts
606
- function requireEnv(addOn, ...names) {
607
- const values = names.map((n) => process.env[n]);
608
- if (values.some((v) => !v)) throw new AddOnNotEnabledError(addOn);
609
- return values;
712
+ // src/storage-local.ts
713
+ import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
714
+ import { dirname, join as join3, relative, sep } from "node:path";
715
+ function localStorage(dir) {
716
+ const file = (path) => join3(dir, "files", path);
717
+ const meta = (path) => join3(dir, "files-meta", `${path}.json`);
718
+ return {
719
+ async upload(path, data, opts) {
720
+ await mkdir(dirname(file(path)), { recursive: true });
721
+ await mkdir(dirname(meta(path)), { recursive: true });
722
+ await writeFile(file(path), typeof data === "string" ? data : Buffer.from(data));
723
+ await writeFile(meta(path), JSON.stringify({ contentType: opts.contentType ?? "" }));
724
+ },
725
+ async download(path) {
726
+ try {
727
+ return await readFile(file(path));
728
+ } catch {
729
+ throw new NotFoundError(`No file "${path}".`);
730
+ }
731
+ },
732
+ async signedUrl(path, action, expires, contentType) {
733
+ const secret = process.env[DEV_FILES_SECRET_ENV];
734
+ if (!secret) throw new BuildersError("File links work in the dev preview. Start it with the preview command from open_app.");
735
+ const link = await devFileLink(secret, { path, action, expires, contentType: contentType ?? "" });
736
+ const origin = process.env[DEV_PREVIEW_URL_ENV];
737
+ return origin ? new URL(link, origin).toString() : link;
738
+ },
739
+ async list(prefix) {
740
+ const root = join3(dir, "files");
741
+ const out = [];
742
+ const walk = async (d) => {
743
+ let entries;
744
+ try {
745
+ entries = await readdir(d, { withFileTypes: true });
746
+ } catch {
747
+ return;
748
+ }
749
+ for (const e of entries) {
750
+ const p = join3(d, e.name);
751
+ if (e.isDirectory()) await walk(p);
752
+ else out.push(relative(root, p).split(sep).join("/"));
753
+ }
754
+ };
755
+ await walk(root);
756
+ return out.filter((p) => p.startsWith(prefix)).sort();
757
+ },
758
+ async delete(path) {
759
+ await rm(file(path), { force: true });
760
+ await rm(meta(path), { force: true });
761
+ }
762
+ };
610
763
  }
611
764
 
612
765
  // src/storage.ts
613
766
  var cached;
614
767
  async function bucket() {
615
- const [name] = requireEnv("storage", "STORAGE_BUCKET");
768
+ const name = process.env.STORAGE_BUCKET;
769
+ if (!name) throw new AddOnNotEnabledError("storage");
616
770
  if (cached?.name !== name) {
617
771
  cached = { name, bucket: import("@google-cloud/storage").then((m) => new m.Storage().bucket(name)) };
618
772
  }
619
773
  return cached.bucket;
620
774
  }
775
+ function local() {
776
+ const dir = process.env.STORAGE_BUCKET ? void 0 : process.env[DEV_DATA_DIR_ENV];
777
+ return dir ? localStorage(dir) : null;
778
+ }
621
779
  function checkPath(path) {
622
780
  if (!path || path.startsWith("/") || path.split("/").some((p) => p === ".." || p === "")) {
623
781
  throw new BuildersError(`"${path}" is not a valid file path. Use something like "photos/cat.jpg".`, 400);
@@ -626,6 +784,11 @@ function checkPath(path) {
626
784
  }
627
785
  var storage = {
628
786
  async upload(path, data, opts = {}) {
787
+ const l = local();
788
+ if (l) {
789
+ await l.upload(checkPath(path), data, opts);
790
+ return { path };
791
+ }
629
792
  await (await bucket()).file(checkPath(path)).save(typeof data === "string" ? data : Buffer.from(data), {
630
793
  contentType: opts.contentType,
631
794
  resumable: false
@@ -633,11 +796,15 @@ var storage = {
633
796
  return { path };
634
797
  },
635
798
  async download(path) {
799
+ const l = local();
800
+ if (l) return l.download(checkPath(path));
636
801
  const [buf] = await (await bucket()).file(checkPath(path)).download();
637
802
  return buf;
638
803
  },
639
804
  async signedUrl(path, opts = {}) {
640
805
  const minutes = Math.min(opts.expiresInMinutes ?? 15, 7 * 24 * 60);
806
+ const l = local();
807
+ if (l) return l.signedUrl(checkPath(path), opts.action ?? "read", Date.now() + minutes * 6e4, opts.contentType);
641
808
  const [url] = await (await bucket()).file(checkPath(path)).getSignedUrl({
642
809
  version: "v4",
643
810
  action: opts.action ?? "read",
@@ -647,10 +814,14 @@ var storage = {
647
814
  return url;
648
815
  },
649
816
  async list(prefix = "") {
817
+ const l = local();
818
+ if (l) return l.list(prefix);
650
819
  const [files] = await (await bucket()).getFiles({ prefix });
651
820
  return files.map((f) => f.name);
652
821
  },
653
822
  async delete(path) {
823
+ const l = local();
824
+ if (l) return l.delete(checkPath(path));
654
825
  await (await bucket()).file(checkPath(path)).delete({ ignoreNotFound: true });
655
826
  }
656
827
  };
@@ -807,7 +978,7 @@ var secrets = {
807
978
  const bad = secretNameError(name);
808
979
  if (bad) throw new BuildersError(`"${name}" is not a secret name. ${bad}`, 400);
809
980
  if (process.env[APP_ENV.revision] === "preview") {
810
- throw new BuildersError(`Secrets work only in the live app, not in a version preview. Publish the version to use ${name}; until then show a message instead.`, 503);
981
+ throw new BuildersError(`Secrets work only in the live app, not in a version preview. Make the version live to use ${name}; until then show a message instead.`, 503);
811
982
  }
812
983
  const project = process.env[APP_ENV.project];
813
984
  if (!project) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@n-dream/builders-sdk",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Builders platform helpers for app code: signed-in user, database, AI, file storage, notifications.",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://builders.n-dream.com",