@n-dream/builders-sdk 0.2.3 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/index.js +206 -15
- 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.
|
|
16
|
+
"@builders/sdk": "npm:@n-dream/builders-sdk@^0.3.0"
|
|
17
17
|
}
|
|
18
18
|
```
|
|
19
19
|
|
|
@@ -41,7 +41,8 @@ await secrets.get("HUBSPOT_API_KEY"); // set in the portal
|
|
|
41
41
|
```
|
|
42
42
|
|
|
43
43
|
- `db` uses Firestore on the platform. In `next dev` and in tests, it uses
|
|
44
|
-
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).
|
|
45
46
|
- `ai`, `storage` and `notify` are add-ons. If an add-on is off, the call
|
|
46
47
|
throws `AddOnNotEnabledError`.
|
|
47
48
|
|
package/dist/index.js
CHANGED
|
@@ -261,6 +261,35 @@ 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
|
+
function validDevFilePath(path) {
|
|
290
|
+
return !!path && !path.startsWith("/") && !/[\\\u0000-\u001f\u007f]/.test(path) && path.split("/").every((p) => p !== "" && p !== "." && p !== "..");
|
|
291
|
+
}
|
|
292
|
+
|
|
264
293
|
// src/db-limit.ts
|
|
265
294
|
var MAX_QUERY_LIMIT = 500;
|
|
266
295
|
function checkLimit(n) {
|
|
@@ -383,11 +412,65 @@ function toPlain(v, Timestamp) {
|
|
|
383
412
|
|
|
384
413
|
// src/db-memory.ts
|
|
385
414
|
import { randomBytes } from "node:crypto";
|
|
415
|
+
import { mkdirSync, readFileSync as readFileSync2, renameSync, writeFileSync } from "node:fs";
|
|
416
|
+
import { join as join2 } from "node:path";
|
|
386
417
|
var warnedCap = /* @__PURE__ */ new Set();
|
|
387
418
|
var g = globalThis;
|
|
388
|
-
var store = () => g.__buildersMemoryDb ??=
|
|
419
|
+
var store = () => g.__buildersMemoryDb ??= load();
|
|
420
|
+
var SAVE_DELAY_MS = 100;
|
|
421
|
+
var dbFile = () => {
|
|
422
|
+
const dir = process.env[DEV_DATA_DIR_ENV];
|
|
423
|
+
return dir ? join2(dir, "db.json") : null;
|
|
424
|
+
};
|
|
425
|
+
var TAG = "__builders";
|
|
426
|
+
function revive(_k, v) {
|
|
427
|
+
if (!v || typeof v !== "object" || Array.isArray(v)) return v;
|
|
428
|
+
const t = v;
|
|
429
|
+
if (Object.keys(t).length !== 2 || typeof t.value !== "string") return v;
|
|
430
|
+
if (t[TAG] === "date") return new Date(t.value);
|
|
431
|
+
if (t[TAG] === "bytes") return new Uint8Array(Buffer.from(t.value, "base64"));
|
|
432
|
+
return v;
|
|
433
|
+
}
|
|
434
|
+
function load() {
|
|
435
|
+
const file = dbFile();
|
|
436
|
+
const s = /* @__PURE__ */ new Map();
|
|
437
|
+
if (!file) return s;
|
|
438
|
+
let raw;
|
|
439
|
+
try {
|
|
440
|
+
raw = JSON.parse(readFileSync2(file, "utf8"), revive);
|
|
441
|
+
} catch {
|
|
442
|
+
return s;
|
|
443
|
+
}
|
|
444
|
+
for (const [name, docs] of Object.entries(raw)) s.set(name, new Map(Object.entries(docs)));
|
|
445
|
+
return s;
|
|
446
|
+
}
|
|
447
|
+
var warnedSave = false;
|
|
448
|
+
function saveSoon() {
|
|
449
|
+
const file = dbFile();
|
|
450
|
+
if (!file || g.__buildersMemoryDbSave) return;
|
|
451
|
+
g.__buildersMemoryDbSave = setTimeout(() => {
|
|
452
|
+
g.__buildersMemoryDbSave = void 0;
|
|
453
|
+
try {
|
|
454
|
+
const out = {};
|
|
455
|
+
for (const [name, docs] of store()) out[name] = Object.fromEntries(docs);
|
|
456
|
+
const text = JSON.stringify(out, function(k, v) {
|
|
457
|
+
const raw = this[k];
|
|
458
|
+
if (raw instanceof Date) return { [TAG]: "date", value: Number.isNaN(raw.getTime()) ? "" : raw.toISOString() };
|
|
459
|
+
if (raw instanceof Uint8Array) return { [TAG]: "bytes", value: Buffer.from(raw).toString("base64") };
|
|
460
|
+
return typeof v === "bigint" ? v.toString() : v;
|
|
461
|
+
});
|
|
462
|
+
mkdirSync(join2(file, ".."), { recursive: true });
|
|
463
|
+
writeFileSync(`${file}.tmp`, text);
|
|
464
|
+
renameSync(`${file}.tmp`, file);
|
|
465
|
+
} catch (e) {
|
|
466
|
+
if (!warnedSave) console.warn(`[builders] The test database could not be saved to ${file}: ${e instanceof Error ? e.message : String(e)}`);
|
|
467
|
+
warnedSave = true;
|
|
468
|
+
}
|
|
469
|
+
}, SAVE_DELAY_MS);
|
|
470
|
+
}
|
|
389
471
|
function resetMemoryDb() {
|
|
390
472
|
store().clear();
|
|
473
|
+
saveSoon();
|
|
391
474
|
}
|
|
392
475
|
function memoryCollection(name) {
|
|
393
476
|
const docs = () => {
|
|
@@ -431,18 +514,22 @@ function memoryCollection(name) {
|
|
|
431
514
|
async add(data) {
|
|
432
515
|
const id = autoId();
|
|
433
516
|
docs().set(id, clean(data));
|
|
517
|
+
saveSoon();
|
|
434
518
|
return out(id, docs().get(id));
|
|
435
519
|
},
|
|
436
520
|
async set(id, data) {
|
|
437
521
|
docs().set(id, clean(data));
|
|
522
|
+
saveSoon();
|
|
438
523
|
},
|
|
439
524
|
async update(id, patch) {
|
|
440
525
|
const d = docs().get(id);
|
|
441
526
|
if (!d) throw new NotFoundError(`No document "${id}" in "${name}".`);
|
|
442
527
|
docs().set(id, { ...d, ...clean(patch) });
|
|
528
|
+
saveSoon();
|
|
443
529
|
},
|
|
444
530
|
async delete(id) {
|
|
445
531
|
docs().delete(id);
|
|
532
|
+
saveSoon();
|
|
446
533
|
}
|
|
447
534
|
});
|
|
448
535
|
return query({ where: [], orderBy: [] });
|
|
@@ -505,7 +592,9 @@ var db = {
|
|
|
505
592
|
if (dbMode() === "firestore") return firestoreCollection(name);
|
|
506
593
|
if (!warned && process.env.NODE_ENV !== "test") {
|
|
507
594
|
warned = true;
|
|
508
|
-
console.info(
|
|
595
|
+
console.info(
|
|
596
|
+
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."
|
|
597
|
+
);
|
|
509
598
|
}
|
|
510
599
|
return memoryCollection(name);
|
|
511
600
|
},
|
|
@@ -517,6 +606,7 @@ var db = {
|
|
|
517
606
|
import { z as z3 } from "zod";
|
|
518
607
|
|
|
519
608
|
// src/platform.ts
|
|
609
|
+
import { readFileSync as readFileSync3, statSync as statSync2 } from "node:fs";
|
|
520
610
|
var METADATA = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default";
|
|
521
611
|
var idTokens = /* @__PURE__ */ new Map();
|
|
522
612
|
var accessToken;
|
|
@@ -554,14 +644,47 @@ async function googleAccessToken() {
|
|
|
554
644
|
accessToken = { token: j.access_token, exp: Date.now() + (j.expires_in ?? 300) * 1e3 };
|
|
555
645
|
return accessToken.token;
|
|
556
646
|
}
|
|
647
|
+
function devUrl(env = process.env) {
|
|
648
|
+
const url = env[DEV_ENV.url]?.trim();
|
|
649
|
+
if (!url || env.NODE_ENV === "production" || env.K_SERVICE) return null;
|
|
650
|
+
return url.replace(/\/+$/, "");
|
|
651
|
+
}
|
|
652
|
+
var devTokenCache;
|
|
653
|
+
var NO_DEV_TOKEN = "Start the dev preview again with the preview command from open_app (it gives a new token).";
|
|
654
|
+
function devToken(env = process.env) {
|
|
655
|
+
const path = env[DEV_ENV.tokenFile]?.trim();
|
|
656
|
+
if (!path) throw new BuildersError(`The dev preview has no Builders token (${DEV_ENV.tokenFile} is not set). ${NO_DEV_TOKEN}`, 401);
|
|
657
|
+
let st;
|
|
658
|
+
try {
|
|
659
|
+
st = statSync2(path);
|
|
660
|
+
} catch {
|
|
661
|
+
throw new BuildersError(`The dev preview's Builders token file is missing. ${NO_DEV_TOKEN}`, 401);
|
|
662
|
+
}
|
|
663
|
+
const c = devTokenCache;
|
|
664
|
+
if (c && c.path === path && c.mtimeMs === st.mtimeMs && c.size === st.size) return c.token;
|
|
665
|
+
let token;
|
|
666
|
+
try {
|
|
667
|
+
token = (readFileSync3(path, "utf8").split("\n")[0] ?? "").trim();
|
|
668
|
+
} catch {
|
|
669
|
+
throw new BuildersError(`The dev preview's Builders token file cannot be read. ${NO_DEV_TOKEN}`, 401);
|
|
670
|
+
}
|
|
671
|
+
if (!token) throw new BuildersError(`The dev preview's Builders token file is empty. ${NO_DEV_TOKEN}`, 401);
|
|
672
|
+
devTokenCache = { path, mtimeMs: st.mtimeMs, size: st.size, token };
|
|
673
|
+
return token;
|
|
674
|
+
}
|
|
557
675
|
var NotOnBuildersError = class extends BuildersError {
|
|
558
676
|
constructor(what) {
|
|
559
|
-
super(
|
|
677
|
+
super(
|
|
678
|
+
`${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.`,
|
|
679
|
+
503
|
|
680
|
+
);
|
|
560
681
|
this.name = "NotOnBuildersError";
|
|
561
682
|
}
|
|
562
683
|
};
|
|
563
684
|
var WHAT = { ai: "AI", notify: "Sending notifications" };
|
|
564
685
|
function gateway(addOn) {
|
|
686
|
+
const dev = devUrl();
|
|
687
|
+
if (dev) return { url: dev, app: "", dev: true };
|
|
565
688
|
const tenant = process.env[APP_ENV.tenant];
|
|
566
689
|
const app = process.env[APP_ENV.app];
|
|
567
690
|
if (!tenant || !app) throw new NotOnBuildersError(WHAT[addOn] ?? "This");
|
|
@@ -574,17 +697,18 @@ function errorOf(status, body, fallback) {
|
|
|
574
697
|
return new BuildersError(msg, status === 429 && body?.error?.code === "budget" ? 402 : status);
|
|
575
698
|
}
|
|
576
699
|
async function gatewayFetch(t, path, body, o = {}) {
|
|
577
|
-
const
|
|
700
|
+
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 };
|
|
701
|
+
const url = t.dev ? `${t.url}${path.replace(/^\/v1(?=\/)/, "")}` : `${t.url}${path}`;
|
|
578
702
|
let res;
|
|
579
703
|
try {
|
|
580
|
-
res = await fetch(
|
|
704
|
+
res = await fetch(url, {
|
|
581
705
|
method: "POST",
|
|
582
|
-
headers
|
|
706
|
+
headers,
|
|
583
707
|
body: JSON.stringify(body),
|
|
584
708
|
signal: o.signal ?? AbortSignal.timeout(o.timeoutMs ?? 12e4)
|
|
585
709
|
});
|
|
586
710
|
} catch (e) {
|
|
587
|
-
throw new BuildersError(`Could not reach the platform's AI service: ${e.message}`, 502);
|
|
711
|
+
throw new BuildersError(`Could not reach the platform's ${t.dev ? "dev preview service" : "AI service"}: ${e.message}`, 502);
|
|
588
712
|
}
|
|
589
713
|
if (!res.ok) {
|
|
590
714
|
const text = await res.text();
|
|
@@ -593,7 +717,7 @@ async function gatewayFetch(t, path, body, o = {}) {
|
|
|
593
717
|
j = JSON.parse(text);
|
|
594
718
|
} catch {
|
|
595
719
|
}
|
|
596
|
-
throw errorOf(res.status, j, `The platform's AI service answered ${res.status}.`);
|
|
720
|
+
throw errorOf(res.status, j, `The platform's ${t.dev ? "dev preview service" : "AI service"} answered ${res.status}.`);
|
|
597
721
|
}
|
|
598
722
|
return res;
|
|
599
723
|
}
|
|
@@ -602,30 +726,89 @@ async function gatewayJson(addOn, path, body, o = {}) {
|
|
|
602
726
|
return await res.json();
|
|
603
727
|
}
|
|
604
728
|
|
|
605
|
-
// src/
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
729
|
+
// src/storage-local.ts
|
|
730
|
+
import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
731
|
+
import { dirname, join as join3, relative, sep } from "node:path";
|
|
732
|
+
function localStorage(dir) {
|
|
733
|
+
const file = (path) => join3(dir, "files", path);
|
|
734
|
+
const meta = (path) => join3(dir, "files-meta", `${path}.json`);
|
|
735
|
+
return {
|
|
736
|
+
async upload(path, data, opts) {
|
|
737
|
+
await mkdir(dirname(file(path)), { recursive: true });
|
|
738
|
+
await mkdir(dirname(meta(path)), { recursive: true });
|
|
739
|
+
await writeFile(file(path), typeof data === "string" ? data : Buffer.from(data));
|
|
740
|
+
await writeFile(meta(path), JSON.stringify({ contentType: opts.contentType ?? "" }));
|
|
741
|
+
},
|
|
742
|
+
async download(path) {
|
|
743
|
+
try {
|
|
744
|
+
return await readFile(file(path));
|
|
745
|
+
} catch {
|
|
746
|
+
throw new NotFoundError(`No file "${path}".`);
|
|
747
|
+
}
|
|
748
|
+
},
|
|
749
|
+
async signedUrl(path, action, expires, contentType) {
|
|
750
|
+
const secret = process.env[DEV_FILES_SECRET_ENV];
|
|
751
|
+
if (!secret) throw new BuildersError("File links work in the dev preview. Start it with the preview command from open_app.");
|
|
752
|
+
const link = await devFileLink(secret, { path, action, expires, contentType: contentType ?? "" });
|
|
753
|
+
const origin = process.env[DEV_PREVIEW_URL_ENV];
|
|
754
|
+
return origin ? new URL(link, origin).toString() : link;
|
|
755
|
+
},
|
|
756
|
+
async list(prefix) {
|
|
757
|
+
const root = join3(dir, "files");
|
|
758
|
+
const out = [];
|
|
759
|
+
const walk = async (d) => {
|
|
760
|
+
let entries;
|
|
761
|
+
try {
|
|
762
|
+
entries = await readdir(d, { withFileTypes: true });
|
|
763
|
+
} catch {
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
for (const e of entries) {
|
|
767
|
+
const p = join3(d, e.name);
|
|
768
|
+
if (e.isDirectory()) await walk(p);
|
|
769
|
+
else out.push(relative(root, p).split(sep).join("/"));
|
|
770
|
+
}
|
|
771
|
+
};
|
|
772
|
+
await walk(root);
|
|
773
|
+
return out.filter((p) => p.startsWith(prefix)).sort();
|
|
774
|
+
},
|
|
775
|
+
async delete(path) {
|
|
776
|
+
await rm(file(path), { force: true });
|
|
777
|
+
await rm(meta(path), { force: true });
|
|
778
|
+
}
|
|
779
|
+
};
|
|
610
780
|
}
|
|
611
781
|
|
|
612
782
|
// src/storage.ts
|
|
613
783
|
var cached;
|
|
614
784
|
async function bucket() {
|
|
615
|
-
const
|
|
785
|
+
const name = process.env.STORAGE_BUCKET;
|
|
786
|
+
if (!name) throw new AddOnNotEnabledError("storage");
|
|
616
787
|
if (cached?.name !== name) {
|
|
617
788
|
cached = { name, bucket: import("@google-cloud/storage").then((m) => new m.Storage().bucket(name)) };
|
|
618
789
|
}
|
|
619
790
|
return cached.bucket;
|
|
620
791
|
}
|
|
792
|
+
function local() {
|
|
793
|
+
const dir = process.env.STORAGE_BUCKET ? void 0 : process.env[DEV_DATA_DIR_ENV];
|
|
794
|
+
if (!dir) return null;
|
|
795
|
+
const addOns = process.env.BUILDERS_DEV_ADDONS;
|
|
796
|
+
if (addOns !== void 0 && !addOns.split(",").includes("storage")) throw new AddOnNotEnabledError("storage");
|
|
797
|
+
return localStorage(dir);
|
|
798
|
+
}
|
|
621
799
|
function checkPath(path) {
|
|
622
|
-
if (!
|
|
800
|
+
if (!validDevFilePath(path)) {
|
|
623
801
|
throw new BuildersError(`"${path}" is not a valid file path. Use something like "photos/cat.jpg".`, 400);
|
|
624
802
|
}
|
|
625
803
|
return path;
|
|
626
804
|
}
|
|
627
805
|
var storage = {
|
|
628
806
|
async upload(path, data, opts = {}) {
|
|
807
|
+
const l = local();
|
|
808
|
+
if (l) {
|
|
809
|
+
await l.upload(checkPath(path), data, opts);
|
|
810
|
+
return { path };
|
|
811
|
+
}
|
|
629
812
|
await (await bucket()).file(checkPath(path)).save(typeof data === "string" ? data : Buffer.from(data), {
|
|
630
813
|
contentType: opts.contentType,
|
|
631
814
|
resumable: false
|
|
@@ -633,11 +816,15 @@ var storage = {
|
|
|
633
816
|
return { path };
|
|
634
817
|
},
|
|
635
818
|
async download(path) {
|
|
819
|
+
const l = local();
|
|
820
|
+
if (l) return l.download(checkPath(path));
|
|
636
821
|
const [buf] = await (await bucket()).file(checkPath(path)).download();
|
|
637
822
|
return buf;
|
|
638
823
|
},
|
|
639
824
|
async signedUrl(path, opts = {}) {
|
|
640
825
|
const minutes = Math.min(opts.expiresInMinutes ?? 15, 7 * 24 * 60);
|
|
826
|
+
const l = local();
|
|
827
|
+
if (l) return l.signedUrl(checkPath(path), opts.action ?? "read", Date.now() + minutes * 6e4, opts.contentType);
|
|
641
828
|
const [url] = await (await bucket()).file(checkPath(path)).getSignedUrl({
|
|
642
829
|
version: "v4",
|
|
643
830
|
action: opts.action ?? "read",
|
|
@@ -647,10 +834,14 @@ var storage = {
|
|
|
647
834
|
return url;
|
|
648
835
|
},
|
|
649
836
|
async list(prefix = "") {
|
|
837
|
+
const l = local();
|
|
838
|
+
if (l) return l.list(prefix);
|
|
650
839
|
const [files] = await (await bucket()).getFiles({ prefix });
|
|
651
840
|
return files.map((f) => f.name);
|
|
652
841
|
},
|
|
653
842
|
async delete(path) {
|
|
843
|
+
const l = local();
|
|
844
|
+
if (l) return l.delete(checkPath(path));
|
|
654
845
|
await (await bucket()).file(checkPath(path)).delete({ ignoreNotFound: true });
|
|
655
846
|
}
|
|
656
847
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@n-dream/builders-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
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",
|