@n-dream/builders-sdk 1.0.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +103 -5
- package/dist/auth.d.ts +25 -0
- package/dist/auth.js +159 -0
- package/dist/data.d.ts +3 -0
- package/dist/data.js +4 -0
- package/dist/db.d.ts +125 -0
- package/dist/db.js +581 -0
- package/dist/declared.d.ts +1 -0
- package/dist/declared.js +5 -0
- package/dist/engine.d.ts +236 -0
- package/dist/engine.js +981 -0
- package/dist/errors.d.ts +4 -1
- package/dist/errors.js +22 -2
- package/dist/index.d.ts +3 -1
- package/dist/index.js +5 -2
- package/dist/local-db.d.ts +15 -0
- package/dist/local-db.js +396 -0
- package/dist/local.d.ts +13 -0
- package/dist/local.js +70 -0
- package/dist/memory-storage.d.ts +55 -0
- package/dist/memory-storage.js +276 -0
- package/dist/rules.d.ts +220 -0
- package/dist/rules.js +824 -0
- package/dist/server.d.ts +3 -0
- package/dist/server.js +6 -0
- package/dist/session.d.ts +5 -0
- package/dist/session.js +18 -0
- package/dist/testing.d.ts +14 -0
- package/dist/testing.js +50 -0
- package/dist/vite.d.ts +21 -0
- package/dist/vite.js +46 -0
- package/package.json +21 -4
package/dist/errors.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
export type BuildersErrorCode = "sign-in-required" | "not-allowed" | "not-declared" | "not-supported" | "too-large" | "quota" | "rate-limit" | "conflict" | "offline" | "app-stopped" | "preparing" | "invalid" | "user-changed";
|
|
2
|
+
export declare function codeOfStatus(status: number): BuildersErrorCode;
|
|
1
3
|
export declare class BuildersError extends Error {
|
|
2
4
|
readonly status: number;
|
|
3
|
-
|
|
5
|
+
readonly code: BuildersErrorCode;
|
|
6
|
+
constructor(message: string, status?: number, code?: BuildersErrorCode);
|
|
4
7
|
}
|
package/dist/errors.js
CHANGED
|
@@ -1,12 +1,32 @@
|
|
|
1
|
-
// The SDK errors.
|
|
1
|
+
// The SDK errors (docs/login-and-data.md 8.1, 8.3).
|
|
2
2
|
// Each message is plain, so that Claude can give it to the person as it is.
|
|
3
|
+
// The code of an HTTP status when the platform gave no code.
|
|
4
|
+
export function codeOfStatus(status) {
|
|
5
|
+
if (status === 0)
|
|
6
|
+
return "offline";
|
|
7
|
+
if (status === 401)
|
|
8
|
+
return "sign-in-required";
|
|
9
|
+
if (status === 403)
|
|
10
|
+
return "not-allowed";
|
|
11
|
+
if (status === 409)
|
|
12
|
+
return "conflict";
|
|
13
|
+
if (status === 413)
|
|
14
|
+
return "too-large";
|
|
15
|
+
if (status === 429)
|
|
16
|
+
return "rate-limit";
|
|
17
|
+
if (status === 410 || status === 451 || status === 503)
|
|
18
|
+
return "app-stopped";
|
|
19
|
+
return "invalid";
|
|
20
|
+
}
|
|
3
21
|
export class BuildersError extends Error {
|
|
4
22
|
status;
|
|
23
|
+
code;
|
|
5
24
|
constructor(message,
|
|
6
25
|
// The HTTP status of the platform's answer, or 0 when no answer came.
|
|
7
|
-
status = 500) {
|
|
26
|
+
status = 500, code) {
|
|
8
27
|
super(message);
|
|
9
28
|
this.status = status;
|
|
10
29
|
this.name = "BuildersError";
|
|
30
|
+
this.code = code ?? codeOfStatus(status);
|
|
11
31
|
}
|
|
12
32
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
export { appInfo, APP_INFO_PATH, type AppInfo, type Environment } from "./app-info.js";
|
|
2
|
-
export {
|
|
2
|
+
export { auth, type Auth, type User } from "./auth.js";
|
|
3
|
+
export { db, type Collection, type Db, type FileSet, type Item, type Page, type Query, type StoredFile } from "./data.js";
|
|
4
|
+
export { BuildersError, type BuildersErrorCode } from "./errors.js";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
// @n-dream/builders-sdk (design 4.5, D13). Each
|
|
2
|
-
//
|
|
1
|
+
// @n-dream/builders-sdk (design 4.5, D13). Each platform service adds one
|
|
2
|
+
// named export here. The guidance uses `import * as builders from
|
|
3
|
+
// "@n-dream/builders-sdk"` (docs/login-and-data.md 8.1).
|
|
3
4
|
export { appInfo, APP_INFO_PATH } from "./app-info.js";
|
|
5
|
+
export { auth } from "./auth.js";
|
|
6
|
+
export { db } from "./data.js";
|
|
4
7
|
export { BuildersError } from "./errors.js";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type LocalUser } from "./local.js";
|
|
2
|
+
import { type DataLimits, type LoginMode } from "./rules.js";
|
|
3
|
+
import { type Transport } from "./db.js";
|
|
4
|
+
type Who = () => LocalUser | null;
|
|
5
|
+
export declare function localTransport(who?: Who, claim?: () => string | null | undefined): Transport;
|
|
6
|
+
export declare function setLocalLoginMode(mode: LoginMode, list?: string[]): void;
|
|
7
|
+
export declare function localLoginRefusal(name: string, developer: boolean): string | null;
|
|
8
|
+
export declare function seedLocal(collection: string, items: Array<{
|
|
9
|
+
id?: string;
|
|
10
|
+
data: Record<string, unknown>;
|
|
11
|
+
}>): Promise<void>;
|
|
12
|
+
export declare function resetLocal(): void;
|
|
13
|
+
export declare function useLocalDeclaration(raw: unknown): void;
|
|
14
|
+
export declare function setLocalLimits(l: Partial<DataLimits>): void;
|
|
15
|
+
export {};
|
package/dist/local-db.js
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
// The local mode of db (docs/login-and-data.md 8.4, LD15): on localhost the
|
|
2
|
+
// SDK runs the same engine as the data service, on a storage in memory,
|
|
3
|
+
// with builders.data.json from the build (the Vite plugin). The data is
|
|
4
|
+
// lost when the page closes. The tabs of one browser share it
|
|
5
|
+
// (BroadcastChannel). Only on localhost: db.ts loads this file there only.
|
|
6
|
+
import { declared } from "./declared.js";
|
|
7
|
+
import { BuildersError } from "./errors.js";
|
|
8
|
+
import { DataEngine, RuleFailure, randomItemId } from "./engine.js";
|
|
9
|
+
import { local } from "./local.js";
|
|
10
|
+
import { MemoryStorage } from "./memory-storage.js";
|
|
11
|
+
import { NO_USER, WATCH_LISTS_MAX, fileObjectOf, servedTypeOf, userGuard, parseDeclaration, spaceLimits } from "./rules.js";
|
|
12
|
+
import { userChanged } from "./db.js";
|
|
13
|
+
import { believed } from "./session.js";
|
|
14
|
+
const APP_ID = "local0000001";
|
|
15
|
+
const POLL_MS = 25_000;
|
|
16
|
+
const SIGNED_OUT_NEXT_S = 30;
|
|
17
|
+
const CHANNEL = "builders-sdk-local";
|
|
18
|
+
const HELLO_MS = 250;
|
|
19
|
+
let state = null;
|
|
20
|
+
function st() {
|
|
21
|
+
if (state)
|
|
22
|
+
return state;
|
|
23
|
+
const storage = new MemoryStorage();
|
|
24
|
+
const s = {
|
|
25
|
+
storage,
|
|
26
|
+
blobs: new Map(),
|
|
27
|
+
urls: new Map(),
|
|
28
|
+
engine: new DataEngine({ storage, now: Date.now, randomId: randomItemId, instance: "local" }),
|
|
29
|
+
loginMode: "anyone",
|
|
30
|
+
loginList: [],
|
|
31
|
+
limits: spaceLimits("live"),
|
|
32
|
+
declaration: undefined,
|
|
33
|
+
channel: typeof BroadcastChannel === "function" ? new BroadcastChannel(CHANNEL) : null,
|
|
34
|
+
ready: Promise.resolve(),
|
|
35
|
+
};
|
|
36
|
+
state = s;
|
|
37
|
+
if (s.channel) {
|
|
38
|
+
const ch = s.channel;
|
|
39
|
+
let answered = () => { };
|
|
40
|
+
s.ready = new Promise((resolve) => {
|
|
41
|
+
const t = setTimeout(resolve, HELLO_MS);
|
|
42
|
+
answered = () => {
|
|
43
|
+
clearTimeout(t);
|
|
44
|
+
resolve();
|
|
45
|
+
};
|
|
46
|
+
});
|
|
47
|
+
storage.onCommit = (writes) => ch.postMessage({ type: "writes", writes });
|
|
48
|
+
ch.onmessage = (ev) => {
|
|
49
|
+
const m = ev.data;
|
|
50
|
+
const b = ev.data;
|
|
51
|
+
if (m?.type === "hello") {
|
|
52
|
+
// Answer only when this tab has the data of the others itself (a
|
|
53
|
+
// tab that opened at the same time would give an empty answer).
|
|
54
|
+
// The file bytes first: a new tab that lists files after the
|
|
55
|
+
// writes has their bytes for the blob: URLs.
|
|
56
|
+
void s.ready.then(() => {
|
|
57
|
+
for (const [name, blob] of s.blobs)
|
|
58
|
+
ch.postMessage({ type: "blob", name, blob });
|
|
59
|
+
ch.postMessage({ type: "writes", writes: storage.dump(), hello: true });
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
else if (m?.type === "writes" && Array.isArray(m.writes)) {
|
|
63
|
+
storage.apply(m.writes);
|
|
64
|
+
// The answer of another tab to our hello: its data is here (also
|
|
65
|
+
// when it has none). The bytes of its files came before it.
|
|
66
|
+
if (m.hello)
|
|
67
|
+
answered();
|
|
68
|
+
}
|
|
69
|
+
else if (m?.type === "reset") {
|
|
70
|
+
storage.clear();
|
|
71
|
+
clearBlobs(s);
|
|
72
|
+
}
|
|
73
|
+
else if (b?.type === "blob" && typeof b.name === "string" && b.blob)
|
|
74
|
+
s.blobs.set(b.name, b.blob);
|
|
75
|
+
else if (b?.type === "blob-del" && typeof b.name === "string")
|
|
76
|
+
dropBlob(s, b.name);
|
|
77
|
+
};
|
|
78
|
+
ch.postMessage({ type: "hello" });
|
|
79
|
+
}
|
|
80
|
+
return s;
|
|
81
|
+
}
|
|
82
|
+
function dropBlob(s, name) {
|
|
83
|
+
s.blobs.delete(name);
|
|
84
|
+
const url = s.urls.get(name);
|
|
85
|
+
if (url)
|
|
86
|
+
URL.revokeObjectURL(url);
|
|
87
|
+
s.urls.delete(name);
|
|
88
|
+
}
|
|
89
|
+
function clearBlobs(s) {
|
|
90
|
+
for (const name of [...s.blobs.keys()])
|
|
91
|
+
dropBlob(s, name);
|
|
92
|
+
}
|
|
93
|
+
// The file bytes in memory, shared with the other tabs.
|
|
94
|
+
const blobStorage = {
|
|
95
|
+
async write(name, body, type) {
|
|
96
|
+
const parts = [];
|
|
97
|
+
for await (const c of body)
|
|
98
|
+
parts.push(c);
|
|
99
|
+
const s = st();
|
|
100
|
+
if (s.blobs.has(name))
|
|
101
|
+
return false;
|
|
102
|
+
const bytes = new Uint8Array(parts.reduce((n, c) => n + c.length, 0));
|
|
103
|
+
let at = 0;
|
|
104
|
+
for (const c of parts) {
|
|
105
|
+
bytes.set(c, at);
|
|
106
|
+
at += c.length;
|
|
107
|
+
}
|
|
108
|
+
s.blobs.set(name, { bytes, type });
|
|
109
|
+
s.channel?.postMessage({ type: "blob", name, blob: { bytes, type } });
|
|
110
|
+
return true;
|
|
111
|
+
},
|
|
112
|
+
async exists(name) {
|
|
113
|
+
return st().blobs.has(name);
|
|
114
|
+
},
|
|
115
|
+
async deletePrefix(prefix) {
|
|
116
|
+
for (const name of [...st().blobs.keys()])
|
|
117
|
+
if (name.startsWith(prefix))
|
|
118
|
+
await blobStorage.delete(name);
|
|
119
|
+
},
|
|
120
|
+
async delete(name) {
|
|
121
|
+
const s = st();
|
|
122
|
+
dropBlob(s, name);
|
|
123
|
+
s.channel?.postMessage({ type: "blob-del", name });
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
// The URL of a file in the local mode: a blob: URL of this tab (the app
|
|
127
|
+
// CSP allows blob: for pictures and media). There is no /_api/files on
|
|
128
|
+
// localhost.
|
|
129
|
+
function localUrl(f, uid) {
|
|
130
|
+
const s = st();
|
|
131
|
+
const name = fileObjectOf(APP_ID, "live", uid, f.id);
|
|
132
|
+
let url = s.urls.get(name);
|
|
133
|
+
const blob = s.blobs.get(name);
|
|
134
|
+
if (!url && blob && typeof URL.createObjectURL === "function") {
|
|
135
|
+
url = URL.createObjectURL(new Blob([blob.bytes], { type: servedTypeOf(blob.type) }));
|
|
136
|
+
s.urls.set(name, url);
|
|
137
|
+
}
|
|
138
|
+
return url ? { ...f, url } : f;
|
|
139
|
+
}
|
|
140
|
+
// The bytes of a file in slices, as a request body comes.
|
|
141
|
+
async function* slices(file) {
|
|
142
|
+
const step = 256 * 1024;
|
|
143
|
+
for (let at = 0; at < file.size; at += step)
|
|
144
|
+
yield new Uint8Array(await file.slice(at, at + step).arrayBuffer());
|
|
145
|
+
}
|
|
146
|
+
function declaration() {
|
|
147
|
+
const raw = st().declaration !== undefined ? st().declaration : declared;
|
|
148
|
+
if (raw === undefined) {
|
|
149
|
+
throw new BuildersError("The local mode does not know builders.data.json. Add builders() from @n-dream/builders-sdk/vite to the plugins in vite.config.ts.", 400, "not-declared");
|
|
150
|
+
}
|
|
151
|
+
if (raw === null)
|
|
152
|
+
return null;
|
|
153
|
+
const r = parseDeclaration(raw);
|
|
154
|
+
if (!r.ok)
|
|
155
|
+
throw new BuildersError(`builders.data.json is not valid: ${r.problems.join(" ")}`, 400, "invalid");
|
|
156
|
+
return r.value;
|
|
157
|
+
}
|
|
158
|
+
const pageUser = () => local.user;
|
|
159
|
+
// The counts of the app (6.5): exact here, from the usage docs.
|
|
160
|
+
async function appTotals() {
|
|
161
|
+
const t = { mBytes: 0, pItems: 0, pBytes: 0, fBytes: 0 };
|
|
162
|
+
for (const w of st().storage.dump()) {
|
|
163
|
+
if (!w.data)
|
|
164
|
+
continue;
|
|
165
|
+
if (/^spaces\/[^/]+\/usage\/f\.[a-z0-9]{16}$/.test(w.path))
|
|
166
|
+
t.fBytes += w.data.bytes ?? 0;
|
|
167
|
+
if (!/^spaces\/[^/]+\/usage\/[a-z0-9]{16}$/.test(w.path))
|
|
168
|
+
continue;
|
|
169
|
+
const u = w.data;
|
|
170
|
+
t.mBytes += u.m?.bytes ?? 0;
|
|
171
|
+
t.pItems += u.p?.items ?? 0;
|
|
172
|
+
t.pBytes += u.p?.bytes ?? 0;
|
|
173
|
+
}
|
|
174
|
+
return t;
|
|
175
|
+
}
|
|
176
|
+
function ctxOf(who) {
|
|
177
|
+
const s = st();
|
|
178
|
+
const u = who();
|
|
179
|
+
return {
|
|
180
|
+
appId: APP_ID,
|
|
181
|
+
space: "live",
|
|
182
|
+
decl: declaration(),
|
|
183
|
+
viewer: u ? { uid: u.id, developer: u.developer } : null,
|
|
184
|
+
loginMode: s.loginMode,
|
|
185
|
+
limits: s.limits,
|
|
186
|
+
appTotals,
|
|
187
|
+
// One app: the owner's files are the app's files.
|
|
188
|
+
ownerFileBytes: async () => (await appTotals()).fBytes,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
function toError(e) {
|
|
192
|
+
if (e instanceof RuleFailure)
|
|
193
|
+
return new BuildersError(e.rule.message, e.rule.status, e.rule.code);
|
|
194
|
+
return e;
|
|
195
|
+
}
|
|
196
|
+
async function run(f) {
|
|
197
|
+
await st().ready;
|
|
198
|
+
try {
|
|
199
|
+
return await f();
|
|
200
|
+
}
|
|
201
|
+
catch (e) {
|
|
202
|
+
throw toError(e);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
async function written(w) {
|
|
206
|
+
if (w.marker)
|
|
207
|
+
await st().storage.setMarker(w.marker.path, w.marker.removed);
|
|
208
|
+
return { item: w.item };
|
|
209
|
+
}
|
|
210
|
+
function watchList(who, lists, signal) {
|
|
211
|
+
return run(async () => {
|
|
212
|
+
// As the data service: at most WATCH_LISTS_MAX collections in one watch.
|
|
213
|
+
if (lists.length > WATCH_LISTS_MAX)
|
|
214
|
+
throw new BuildersError(`Watch 1 to ${WATCH_LISTS_MAX} lists in one request.`, 400, "invalid");
|
|
215
|
+
const s = st();
|
|
216
|
+
const c = ctxOf(who);
|
|
217
|
+
const targets = lists.map((l) => {
|
|
218
|
+
try {
|
|
219
|
+
return { ...l, path: s.engine.watchTarget(c, l.c).path, error: null };
|
|
220
|
+
}
|
|
221
|
+
catch (e) {
|
|
222
|
+
if (e instanceof RuleFailure)
|
|
223
|
+
return { ...l, path: null, error: e.rule };
|
|
224
|
+
throw e;
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
// The update time of the marker (microseconds), as a listener of the
|
|
228
|
+
// data service sees it.
|
|
229
|
+
const at = async (path) => s.storage.updateUs(path);
|
|
230
|
+
const newer = async () => (await Promise.all(targets.map(async (t) => (t.path ? (await at(t.path)) > Number(t.cursor) : false)))).some(Boolean);
|
|
231
|
+
// As the data service (9.3): a signed-out caller never waits.
|
|
232
|
+
// An abort (a new list joins the long poll) can come during the reads
|
|
233
|
+
// above: then do not wait.
|
|
234
|
+
if (c.viewer && !targets.some((t) => t.error) && !(await newer()) && !signal.aborted) {
|
|
235
|
+
await new Promise((resolve) => {
|
|
236
|
+
const stops = [];
|
|
237
|
+
const done = () => {
|
|
238
|
+
clearTimeout(timer);
|
|
239
|
+
stops.forEach((f) => f());
|
|
240
|
+
local.listeners.delete(done);
|
|
241
|
+
resolve();
|
|
242
|
+
};
|
|
243
|
+
const timer = setTimeout(done, POLL_MS);
|
|
244
|
+
signal.addEventListener("abort", done, { once: true });
|
|
245
|
+
local.listeners.add(done);
|
|
246
|
+
for (const t of targets) {
|
|
247
|
+
stops.push(s.storage.listen(t.path, (m) => void (m && m.atUs !== null && m.atUs > Number(t.cursor) && done()), () => { }));
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
// At the end of the wait: the user and the rights again.
|
|
252
|
+
const again = ctxOf(who);
|
|
253
|
+
const out = [];
|
|
254
|
+
for (const t of targets) {
|
|
255
|
+
let err = t.error;
|
|
256
|
+
let path = t.path;
|
|
257
|
+
if (!err) {
|
|
258
|
+
try {
|
|
259
|
+
path = s.engine.watchTarget(again, t.c).path;
|
|
260
|
+
}
|
|
261
|
+
catch (e) {
|
|
262
|
+
if (!(e instanceof RuleFailure))
|
|
263
|
+
throw e;
|
|
264
|
+
err = e.rule;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (err || !path) {
|
|
268
|
+
out.push({ c: t.c, error: err.code, message: err.message });
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
if ((await at(path)) <= Number(t.cursor)) {
|
|
272
|
+
out.push({ c: t.c, cursor: t.cursor, items: [], removed: [] });
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
try {
|
|
276
|
+
const ch = await s.engine.changes(again, t.c, Number(t.cursor));
|
|
277
|
+
out.push(ch.resync ? { c: t.c, resync: true } : { c: t.c, cursor: String(ch.cursor), items: ch.items, removed: ch.removed });
|
|
278
|
+
}
|
|
279
|
+
catch (e) {
|
|
280
|
+
if (!(e instanceof RuleFailure))
|
|
281
|
+
throw e;
|
|
282
|
+
out.push({ c: t.c, error: e.rule.code, message: e.rule.message });
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return { lists: out, next: again.viewer ? 0 : SIGNED_OUT_NEXT_S };
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
// `who`: the signed-in user of the page, or (tests of the SDK) a fixed one.
|
|
289
|
+
// claim: the user that the page believes is signed in (the user guard, as
|
|
290
|
+
// the data service); the page's auth for the tab's own transport.
|
|
291
|
+
export function localTransport(who = pageUser, claim = who === pageUser ? () => believed.uid : () => undefined) {
|
|
292
|
+
const e = () => st().engine;
|
|
293
|
+
const ctx = () => {
|
|
294
|
+
const c = claim();
|
|
295
|
+
if (userGuard(c === undefined ? undefined : (c ?? NO_USER), who()?.id ?? null))
|
|
296
|
+
throw userChanged();
|
|
297
|
+
return ctxOf(who);
|
|
298
|
+
};
|
|
299
|
+
// The arguments as the platform gets them: JSON (an undefined field goes
|
|
300
|
+
// away, a Date becomes a string).
|
|
301
|
+
const wire = (v) => (v === undefined ? v : JSON.parse(JSON.stringify(v)));
|
|
302
|
+
return {
|
|
303
|
+
get: (c, id) => run(() => e().get(ctx(), c, id)),
|
|
304
|
+
list: (c, q) => run(async () => {
|
|
305
|
+
const r = await e().list(ctx(), c, wire(q));
|
|
306
|
+
return { items: r.items, next: r.next, cursor: String(r.readUs) };
|
|
307
|
+
}),
|
|
308
|
+
count: (c, q) => run(() => e().count(ctx(), c, wire(q))),
|
|
309
|
+
add: (c, data) => run(async () => written(await e().add(ctx(), c, wire(data)))),
|
|
310
|
+
set: (c, id, data, ifRev) => run(async () => written(await e().set(ctx(), c, id, wire(data), ifRev))),
|
|
311
|
+
update: (c, id, patch, ifRev) => run(async () => written(await e().update(ctx(), c, id, wire(patch), ifRev))),
|
|
312
|
+
remove: (c, id) => run(async () => void (await written(await e().remove(ctx(), c, id)))),
|
|
313
|
+
usage: () => run(async () => {
|
|
314
|
+
const u = await e().usage(ctx());
|
|
315
|
+
return { bytes: u.bytes, bytesLimit: u.bytesLimit, fileBytes: u.fileBytes, fileBytesLimit: u.fileBytesLimit };
|
|
316
|
+
}),
|
|
317
|
+
upload: (set, file, name) => run(async () => {
|
|
318
|
+
const c = ctx();
|
|
319
|
+
const r = await e().upload(c, set, { name, type: file.type, size: file.size }, slices(file), blobStorage);
|
|
320
|
+
return { file: localUrl(r.file, c.viewer.uid) };
|
|
321
|
+
}),
|
|
322
|
+
listFiles: (set, q) => run(async () => {
|
|
323
|
+
const c = ctx();
|
|
324
|
+
const r = await e().listFiles(c, set, wire(q));
|
|
325
|
+
return { files: r.files.map((f) => localUrl(f, c.viewer.uid)), next: r.next };
|
|
326
|
+
}),
|
|
327
|
+
removeFile: (set, id) => run(async () => void (await e().removeFile(ctx(), set, id, blobStorage))),
|
|
328
|
+
watch: async (lists, signal) => {
|
|
329
|
+
ctx();
|
|
330
|
+
const r = await watchList(who, lists, signal);
|
|
331
|
+
// Another user at the end of the wait: no answer for the old one.
|
|
332
|
+
ctx();
|
|
333
|
+
return r;
|
|
334
|
+
},
|
|
335
|
+
// Only a change of the user id is a change of the user.
|
|
336
|
+
onUser: (cb) => {
|
|
337
|
+
let last = local.user?.id ?? null;
|
|
338
|
+
const l = () => {
|
|
339
|
+
const id = local.user?.id ?? null;
|
|
340
|
+
if (id === last)
|
|
341
|
+
return;
|
|
342
|
+
last = id;
|
|
343
|
+
cb();
|
|
344
|
+
};
|
|
345
|
+
local.listeners.add(l);
|
|
346
|
+
return () => local.listeners.delete(l);
|
|
347
|
+
},
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
// --- For @n-dream/builders-sdk/testing. ---
|
|
351
|
+
export function setLocalLoginMode(mode, list = []) {
|
|
352
|
+
if (!["anyone", "domains", "emails"].includes(mode))
|
|
353
|
+
throw new Error('The mode is "anyone", "domains" or "emails".');
|
|
354
|
+
const s = st();
|
|
355
|
+
s.loginMode = mode;
|
|
356
|
+
s.loginList = list.map((x) => String(x).trim().toLowerCase());
|
|
357
|
+
}
|
|
358
|
+
// May a test user of this name sign in in the login mode (4.4)? The name is
|
|
359
|
+
// the email in the modes "domains" and "emails". Developers always can.
|
|
360
|
+
export function localLoginRefusal(name, developer) {
|
|
361
|
+
const s = st();
|
|
362
|
+
if (developer || s.loginMode === "anyone")
|
|
363
|
+
return null;
|
|
364
|
+
const email = name.trim().toLowerCase();
|
|
365
|
+
if (s.loginMode === "emails" && s.loginList.includes(email))
|
|
366
|
+
return null;
|
|
367
|
+
if (s.loginMode === "domains" && s.loginList.includes(email.split("@")[1] ?? ""))
|
|
368
|
+
return null;
|
|
369
|
+
return `${name} cannot sign in: the login mode is "${s.loginMode}" and the name is not in its list.`;
|
|
370
|
+
}
|
|
371
|
+
export async function seedLocal(collection, items) {
|
|
372
|
+
for (const i of items) {
|
|
373
|
+
const t = localTransport();
|
|
374
|
+
if (i.id === undefined)
|
|
375
|
+
await t.add(collection, i.data);
|
|
376
|
+
else
|
|
377
|
+
await t.set(collection, i.id, i.data);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
export function resetLocal() {
|
|
381
|
+
const s = st();
|
|
382
|
+
s.storage.clear();
|
|
383
|
+
clearBlobs(s);
|
|
384
|
+
s.loginMode = "anyone";
|
|
385
|
+
s.loginList = [];
|
|
386
|
+
s.limits = spaceLimits("live");
|
|
387
|
+
s.declaration = undefined;
|
|
388
|
+
s.channel?.postMessage({ type: "reset" });
|
|
389
|
+
}
|
|
390
|
+
// Tests of the SDK: a declaration without the Vite plugin, and other limits.
|
|
391
|
+
export function useLocalDeclaration(raw) {
|
|
392
|
+
st().declaration = raw;
|
|
393
|
+
}
|
|
394
|
+
export function setLocalLimits(l) {
|
|
395
|
+
st().limits = { ...spaceLimits("live"), ...l };
|
|
396
|
+
}
|
package/dist/local.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface LocalUser {
|
|
2
|
+
id: string;
|
|
3
|
+
name: string;
|
|
4
|
+
developer: boolean;
|
|
5
|
+
}
|
|
6
|
+
export declare function isLocalHost(hostname: string | undefined): boolean;
|
|
7
|
+
export declare const LOCAL_USER_KEY = "builders-local-user";
|
|
8
|
+
export declare const local: {
|
|
9
|
+
user: LocalUser | null;
|
|
10
|
+
listeners: Set<() => void>;
|
|
11
|
+
};
|
|
12
|
+
export declare function localUserId(name: string): string;
|
|
13
|
+
export declare function setLocalUser(u: LocalUser | null): void;
|
package/dist/local.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// The local mode of the SDK (docs/login-and-data.md 8.4, LD15, D135): on
|
|
2
|
+
// localhost (vite dev and test:headless) the SDK keeps everything in
|
|
3
|
+
// memory. On every other host it never uses this mode. The data is lost
|
|
4
|
+
// when the last tab closes, so tests start clean.
|
|
5
|
+
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
|
|
6
|
+
export function isLocalHost(hostname) {
|
|
7
|
+
return hostname !== undefined && LOCAL_HOSTS.has(hostname);
|
|
8
|
+
}
|
|
9
|
+
// The key in sessionStorage that keeps the signed-in test user of a tab, so
|
|
10
|
+
// that a reload keeps the sign-in (as the session cookie does on the
|
|
11
|
+
// platform). A headless test sets it before the page loads to open a tab
|
|
12
|
+
// as a user: {"name":"Ann","developer":false}.
|
|
13
|
+
export const LOCAL_USER_KEY = "builders-local-user";
|
|
14
|
+
function session() {
|
|
15
|
+
try {
|
|
16
|
+
return isLocalHost(globalThis.location?.hostname) ? (globalThis.sessionStorage ?? null) : null;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
// The test user of this tab from sessionStorage (see LOCAL_USER_KEY).
|
|
23
|
+
function storedUser() {
|
|
24
|
+
try {
|
|
25
|
+
const raw = session()?.getItem(LOCAL_USER_KEY);
|
|
26
|
+
if (!raw)
|
|
27
|
+
return null;
|
|
28
|
+
const v = JSON.parse(raw);
|
|
29
|
+
if (typeof v.name !== "string" || !v.name)
|
|
30
|
+
return null;
|
|
31
|
+
return { id: localUserId(v.name), name: v.name, developer: v.developer === true };
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
// The local state of one page.
|
|
38
|
+
export const local = {
|
|
39
|
+
user: null,
|
|
40
|
+
listeners: new Set(),
|
|
41
|
+
};
|
|
42
|
+
// The id of a test user: the same name gives the same id in every tab (the
|
|
43
|
+
// tabs share the data). "local" and 11 lowercase letters and digits, as the
|
|
44
|
+
// 16 characters of a user id on the platform.
|
|
45
|
+
export function localUserId(name) {
|
|
46
|
+
let h1 = 0x811c9dc5;
|
|
47
|
+
let h2 = 0x9e3779b9;
|
|
48
|
+
for (let i = 0; i < name.length; i++) {
|
|
49
|
+
const c = name.charCodeAt(i);
|
|
50
|
+
h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0;
|
|
51
|
+
h2 = Math.imul(h2 ^ c, 0x5bd1e995) >>> 0;
|
|
52
|
+
}
|
|
53
|
+
return `local${(h1.toString(36) + h2.toString(36)).padStart(11, "0").slice(-11)}`;
|
|
54
|
+
}
|
|
55
|
+
export function setLocalUser(u) {
|
|
56
|
+
local.user = u;
|
|
57
|
+
try {
|
|
58
|
+
const s = session();
|
|
59
|
+
if (u)
|
|
60
|
+
s?.setItem(LOCAL_USER_KEY, JSON.stringify({ name: u.name, developer: u.developer }));
|
|
61
|
+
else
|
|
62
|
+
s?.removeItem(LOCAL_USER_KEY);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// Blocked storage: the sign-in stays for this page only.
|
|
66
|
+
}
|
|
67
|
+
for (const l of [...local.listeners])
|
|
68
|
+
l();
|
|
69
|
+
}
|
|
70
|
+
local.user = storedUser();
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { type DataStorage, type Row, type StorageQuery, type StorageTx, type Stored } from "./engine.js";
|
|
2
|
+
import type { Ns } from "./rules.js";
|
|
3
|
+
export interface MarkerValue {
|
|
4
|
+
atUs: number | null;
|
|
5
|
+
data: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
export type Write = {
|
|
8
|
+
path: string;
|
|
9
|
+
data: Stored | null;
|
|
10
|
+
};
|
|
11
|
+
export declare class MemoryStorage implements DataStorage {
|
|
12
|
+
private readonly clock;
|
|
13
|
+
private readonly spaces;
|
|
14
|
+
private readonly listeners;
|
|
15
|
+
private readonly updated;
|
|
16
|
+
private last;
|
|
17
|
+
private lock;
|
|
18
|
+
onCommit: ((writes: Write[]) => void) | null;
|
|
19
|
+
constructor(clock?: () => number);
|
|
20
|
+
private tick;
|
|
21
|
+
get readUs(): number;
|
|
22
|
+
private sub;
|
|
23
|
+
private read;
|
|
24
|
+
private commit;
|
|
25
|
+
apply(writes: Write[]): void;
|
|
26
|
+
dump(): Write[];
|
|
27
|
+
clear(): void;
|
|
28
|
+
private notify;
|
|
29
|
+
transaction<T>(fn: (tx: StorageTx) => Promise<T>): Promise<T>;
|
|
30
|
+
get(path: string): Promise<Stored | null>;
|
|
31
|
+
private docs;
|
|
32
|
+
query(space: string, q: StorageQuery): Promise<{
|
|
33
|
+
rows: Row[];
|
|
34
|
+
readUs: number;
|
|
35
|
+
}>;
|
|
36
|
+
count(space: string, q: Omit<StorageQuery, "limit" | "after" | "direction" | "order">, max: number): Promise<number>;
|
|
37
|
+
changes(space: string, ns: Ns, scope: string, sinceUs: number, limit: number): Promise<{
|
|
38
|
+
rows: Row[];
|
|
39
|
+
removed: Row[];
|
|
40
|
+
readUs: number;
|
|
41
|
+
}>;
|
|
42
|
+
setMarker(path: string, removed: boolean): Promise<number>;
|
|
43
|
+
docsByPrefix(space: string, prefix: string, after: string | null, limit: number, sub?: "docs" | "files" | "marks"): Promise<Row[]>;
|
|
44
|
+
countByPrefix(space: string, prefix: string, max: number, sub?: "docs" | "files"): Promise<number>;
|
|
45
|
+
docsOfUser(space: string, uid: string, after: string | null, limit: number, sub?: "docs" | "files"): Promise<Row[]>;
|
|
46
|
+
listSub(space: string, sub: "marks" | "usage" | "colls" | "jobs", after: string | null, limit: number): Promise<Row[]>;
|
|
47
|
+
private dropSubs;
|
|
48
|
+
resetSpace(space: string): Promise<void>;
|
|
49
|
+
purgeSpace(space: string): Promise<void>;
|
|
50
|
+
updateUs(path: string): number;
|
|
51
|
+
private markerOf;
|
|
52
|
+
listen(path: string, onValue: (m: MarkerValue | null) => void, _onError: (e: Error) => void): () => void;
|
|
53
|
+
writeMarker(path: string, data: Record<string, unknown>): Promise<number>;
|
|
54
|
+
removeDoc(path: string): Promise<void>;
|
|
55
|
+
}
|