@n-dream/builders-sdk 1.0.0 → 1.4.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/dist/rules.js ADDED
@@ -0,0 +1,768 @@
1
+ // The rules of app data (docs/login-and-data.md 6, 8.3, 11.1). One module
2
+ // for the data service, the api, the CLI and the local mode of the SDK, so
3
+ // that they cannot differ (LD15, D135). It has no imports and no state.
4
+ const STATUS = {
5
+ "sign-in-required": 401,
6
+ "not-allowed": 403,
7
+ "not-declared": 400,
8
+ "not-supported": 400,
9
+ "too-large": 413,
10
+ quota: 403,
11
+ "rate-limit": 429,
12
+ conflict: 409,
13
+ preparing: 503,
14
+ invalid: 400,
15
+ "user-changed": 409,
16
+ };
17
+ export function ruleError(code, message, status = STATUS[code]) {
18
+ return { code, status, message };
19
+ }
20
+ export function isRuleError(v) {
21
+ return typeof v === "object" && v !== null && typeof v.code === "string" && typeof v.message === "string" && typeof v.status === "number";
22
+ }
23
+ const q = (s) => JSON.stringify(s);
24
+ // The messages of 8.3: one plain sentence, with what to do.
25
+ export const MESSAGES = {
26
+ notDeclared: (c) => `${q(c)} is not declared. Add it to builders.data.json with "mine" or "public".`,
27
+ noDeclaration: () => "This app has no builders.data.json, so it has no sign-in and no data. Add builders.data.json and push a preview.",
28
+ onlyPresets: () => 'Only "mine" and "public" are possible. Data that a group changes together is not possible now; offer send_feedback.',
29
+ mineSignIn: (c) => `${q(c)} needs sign-in (it is "mine"). Call builders.auth.signIn(), or keep the data in the browser with localStorage.`,
30
+ publicAddSignIn: (c) => `Adding to ${q(c)} needs sign-in. Call builders.auth.signIn().`,
31
+ publicChangeSignIn: (c) => `Changing items in ${q(c)} needs sign-in. Call builders.auth.signIn().`,
32
+ publicReadSignIn: (c) => `Reading ${q(c)} needs sign-in in this app (only some people can sign in). Call builders.auth.signIn().`,
33
+ notOwn: (c) => `You can only change your own items in ${q(c)}. To make your own item, use add() or set() with a short id.`,
34
+ dotInId: () => "An id cannot contain a dot. Use add(), or a short id of letters, digits, - and _.",
35
+ badId: () => "An id has 1 to 100 letters, digits, - and _. Use add() to get a new id.",
36
+ noItem: (c, id) => `There is no item ${q(id)} in ${q(c)}. Use set() to make it, or add() for a new one.`,
37
+ notFilter: (c, f, access) => `Cannot filter ${q(c)} by ${q(f)}. Declare it: ${q(c)}: { "access": ${q(access)}, "filter": [${q(f)}] } (at most 2 fields).`,
38
+ range: (f) => `Only "equal to" filters are possible. Sort by ${q(f)} instead (declare "sort": ${q(f)}) and stop reading when the value is too small.`,
39
+ notSort: (c, f, access) => `Cannot sort ${q(c)} by ${q(f)}. Sort by "createdAt" or "updatedAt", or declare it: ${q(c)}: { "access": ${q(access)}, "sort": ${q(f)} } (at most 1 field).`,
40
+ mineOnlyPublic: (c) => `list({ mine: true }) is only for "public" collections. In ${q(c)} (it is "mine") every item is already the user's own.`,
41
+ mineNoWhere: () => "list({ mine: true }) cannot use where. Read the user's items with mine: true, and test the fields in the app.",
42
+ mineSignIn2: (c) => `list({ mine: true }) of ${q(c)} needs sign-in. Call builders.auth.signIn().`,
43
+ queryKeys: (call, keys) => `${call} takes only ${keys}.`,
44
+ limit: (max) => `limit is a whole number from 1 to ${max}.`,
45
+ direction: () => 'direction is "asc" or "desc".',
46
+ badCursor: () => "after must be the next value of the last page. Read the list again from the start.",
47
+ filterValue: (f) => `A filter value of ${q(f)} is a string (at most about 1,000 characters), a number, true, false or null.`,
48
+ dataObject: () => 'The data of an item must be an object, for example { text: "Hi" }.',
49
+ notJson: () => "The data must be JSON: no functions, no cycles, no BigInt.",
50
+ tooDeep: (n) => `The data is nested too deeply (at most ${n} levels). Make it flatter.`,
51
+ tooLarge: (kb) => `This item is too large (max ${kb} KB). Split it into several items.`,
52
+ userFull: () => "Your space in this app is full. Delete some items.",
53
+ appFull: () => "This app is full. Its developers were told.",
54
+ appBusy: () => "This app is very busy. Sign in or try again later.",
55
+ rate: () => "Too many requests. Wait a moment.",
56
+ conflict: (c) => `The item in ${q(c)} changed in the meantime. Read it again, then try again.`,
57
+ ifRev: () => "ifRev is the rev of the item (a whole number from 0).",
58
+ preparing: () => "This list is being prepared. Try again in a minute.",
59
+ readOnly: () => "Saving is paused for a short time.",
60
+ userChanged: () => "The signed-in user changed (for example in another tab). Nothing was read or saved. The page has the new user now: read the data again.",
61
+ collectionName: () => "A collection name has 1 to 40 letters, digits, - and _.",
62
+ // Files (7).
63
+ fileSetNotDeclared: (s) => `${q(s)} is not declared as a file set. Add it to builders.data.json: "files": { ${q(s)}: "mine" }.`,
64
+ fileSignIn: (s) => `${q(s)} needs sign-in (files are "mine"). Call builders.auth.signIn().`,
65
+ fileSetName: () => "A file set name has 1 to 40 letters, digits, - and _.",
66
+ fileType: () => `This file type is not possible. Use ${FILE_TYPE_NAMES}.`,
67
+ fileContent: (type) => `The content of the file is not ${q(type)}. Upload the file as it is (a File or Blob with its own type), and only ${FILE_TYPE_NAMES}.`,
68
+ fileTooLarge: (mb) => `This file is too large (max ${mb} MB). Make photos smaller in the browser before the upload (at most 2,048 pixels, JPEG or WebP).`,
69
+ fileName: () => "A file name has 1 to 200 characters and no control characters.",
70
+ fileId: () => "This is not the id of a file. Use the id that upload() or list() gave.",
71
+ fileNone: () => "There is no such file.",
72
+ fileGone: () => "The test data was emptied during the upload. Upload the file again.",
73
+ fileUserFull: () => "Your space for files in this app is full. Delete some files.",
74
+ fileNotBlob: () => "upload() takes a File or a Blob, for example from <input type=\"file\">.",
75
+ fileLength: () => "The upload needs a Content-Length.",
76
+ fileDownloads: () => "This app used all its file downloads for this month. Its developers were told.",
77
+ userDownloads: () => "You opened too many files today. Try again tomorrow.",
78
+ userUploads: () => "You uploaded too many files today. Try again tomorrow.",
79
+ };
80
+ // Calls that Claude can guess but that do not exist (8.3). The stubs in the
81
+ // SDK throw these messages.
82
+ export const NOT_SUPPORTED = {
83
+ transaction: "There are no transactions. Keep the data that must change together in one item, or use set(id, data, { ifRev }) and try again on \"conflict\".",
84
+ batch: "There are no transactions. Keep the data that must change together in one item, or use set(id, data, { ifRev }) and try again on \"conflict\".",
85
+ join: "There are no joins. Keep the id of the other item in a field and read it with get(id).",
86
+ increment: 'There are no counters. Count items with count({ where }). For likes: a public collection "likes" with filter ["postId"]; the like of a user is set("like_" + postId.replace(".", "_"), { postId }) (one per user and post; get() of that id says if the user liked it, remove() takes it back), and count({ where: { postId } }) gives the number.',
87
+ serverCode: "Builders apps have no server code. Do the work in the app when a user opens it.",
88
+ publicFiles: 'Only "mine" files are possible. Other users cannot see files.',
89
+ later: 'This is not possible now. Use "mine" or "public" data.',
90
+ };
91
+ // --- The user guard (8.3) ---
92
+ // Every data and file request of the SDK names the user that the page
93
+ // believes is signed in: the header X-Builders-User with the user id, or
94
+ // "-" for nobody. The data service (and the local mode) compares it with
95
+ // the session and refuses another user with user-changed (409), before any
96
+ // read, write or count. Each answer names the session's user in the same
97
+ // header. A request without the header is not checked (older SDKs).
98
+ export const USER_HEADER = "x-builders-user";
99
+ export const NO_USER = "-";
100
+ export function userGuard(claimed, sessionUid) {
101
+ if (claimed === null || claimed === undefined)
102
+ return null;
103
+ return claimed === (sessionUid ?? NO_USER) ? null : ruleError("user-changed", MESSAGES.userChanged());
104
+ }
105
+ // --- Limits (11.1, LD13). ---
106
+ const KB = 1024;
107
+ const MB = 1024 * KB;
108
+ const GB = 1024 * MB;
109
+ export const DATA_LIMITS = {
110
+ itemBytes: 100 * KB,
111
+ depth: 20,
112
+ collections: 20,
113
+ filterFields: 2,
114
+ fileSets: 5,
115
+ mineItemsPerUser: 2_000,
116
+ mineBytesPerUser: 10 * MB,
117
+ publicItemsPerUser: 500,
118
+ publicBytesPerUser: 2 * MB,
119
+ mineBytesPerApp: 1 * GB,
120
+ publicItemsPerApp: 50_000,
121
+ publicBytesPerApp: 200 * MB,
122
+ pointsPerMinute: 1_000,
123
+ requestsPerAppPerSecond: 200,
124
+ readsPerAppPerMonth: 10_000_000,
125
+ writesPerAppPerMonth: 2_000_000,
126
+ waitsPerUser: 5,
127
+ waitsPerApp: 1_000,
128
+ fileBytes: 10 * MB,
129
+ filesPerUser: 1_000,
130
+ fileBytesPerUser: 200 * MB,
131
+ fileBytesPerApp: 10 * GB,
132
+ fileBytesPerOwner: 20 * GB,
133
+ // The bandwidth of an app per month (design 11).
134
+ downloadBytesPerAppPerMonth: 50 * GB,
135
+ downloadBytesPerUserPerDay: 2 * GB,
136
+ uploadBytesPerUserPerDay: 1 * GB,
137
+ };
138
+ // The per-app values that the test space gets one tenth of (11.1). The
139
+ // per-user values stay the same.
140
+ const PER_APP = ["mineBytesPerApp", "publicItemsPerApp", "publicBytesPerApp", "requestsPerAppPerSecond", "readsPerAppPerMonth", "writesPerAppPerMonth", "waitsPerApp", "fileBytesPerApp", "downloadBytesPerAppPerMonth"];
141
+ export function spaceLimits(space, base = DATA_LIMITS) {
142
+ const out = { ...base };
143
+ if (space === "test")
144
+ for (const k of PER_APP)
145
+ out[k] = Math.max(1, Math.floor(base[k] / 10));
146
+ return out;
147
+ }
148
+ // The limits that an operator can change for one app (11.1). The size and
149
+ // shape of an item and of the declaration stay the same for all apps (the
150
+ // CLI and the SDK check them too), and the owner's file bytes are for all
151
+ // apps of the owner.
152
+ export const DATA_LIMIT_OVERRIDES = [
153
+ "mineItemsPerUser",
154
+ "mineBytesPerUser",
155
+ "publicItemsPerUser",
156
+ "publicBytesPerUser",
157
+ "mineBytesPerApp",
158
+ "publicItemsPerApp",
159
+ "publicBytesPerApp",
160
+ "pointsPerMinute",
161
+ "requestsPerAppPerSecond",
162
+ "readsPerAppPerMonth",
163
+ "writesPerAppPerMonth",
164
+ "waitsPerUser",
165
+ "waitsPerApp",
166
+ "filesPerUser",
167
+ "fileBytesPerUser",
168
+ "fileBytesPerApp",
169
+ "downloadBytesPerAppPerMonth",
170
+ "downloadBytesPerUserPerDay",
171
+ "uploadBytesPerUserPerDay",
172
+ ];
173
+ // The app values with an operator's changes (only known keys, whole
174
+ // numbers of 0 or more). The test space then gets one tenth of the per-app
175
+ // values (spaceLimits).
176
+ export function appDataLimits(overrides, base = DATA_LIMITS) {
177
+ const out = { ...base };
178
+ for (const k of DATA_LIMIT_OVERRIDES) {
179
+ const v = overrides?.[k];
180
+ if (typeof v === "number" && Number.isSafeInteger(v) && v >= 0)
181
+ out[k] = v;
182
+ }
183
+ return out;
184
+ }
185
+ // Fixed sizes of the query surface (6.3, 9.3).
186
+ export const LIST_MAX = 100;
187
+ export const LIST_DEFAULT = 50;
188
+ export const COUNT_MAX = 10_000;
189
+ export const WATCH_LISTS_MAX = 10;
190
+ export const CHANGES_MAX = 200;
191
+ export const CURSOR_MAX_AGE_MS = 60 * 60_000;
192
+ // The most UTF-8 bytes of a slot ("<field>=<value>") and of a sort text:
193
+ // Firestore compares only the first 1,500 bytes of a value.
194
+ export const SLOT_BYTES_MAX = 1_400;
195
+ // --- The declaration builders.data.json (6.1). ---
196
+ export const DECLARATION_FILE = "builders.data.json";
197
+ export const DECLARATION_SCHEMA = "https://builders.n-dream.com/schema/data-v1.json";
198
+ export const PRESETS = ["mine", "public"];
199
+ export const NS_OF = { mine: "m", public: "p" };
200
+ const NAME = /^[A-Za-z0-9_-]{1,40}$/;
201
+ const FIELD = /^[A-Za-z_$][A-Za-z0-9_$]{0,39}$/;
202
+ const BUILT_IN_ORDERS = ["createdAt", "updatedAt"];
203
+ export function isCollectionName(v) {
204
+ return typeof v === "string" && NAME.test(v);
205
+ }
206
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
207
+ // Checks the parsed JSON of builders.data.json. Each problem is one plain
208
+ // sentence. The value has only own keys (no prototype tricks).
209
+ export function parseDeclaration(raw, limits = DATA_LIMITS) {
210
+ const problems = [];
211
+ if (!isObject(raw))
212
+ return { ok: false, problems: ['builders.data.json must be a JSON object with "schemaVersion": 1 and "collections".'] };
213
+ for (const k of Object.keys(raw)) {
214
+ if (!["$schema", "schemaVersion", "collections", "files"].includes(k))
215
+ problems.push(`Unknown field ${q(k)} in builders.data.json. Use only "$schema", "schemaVersion", "collections" and "files".`);
216
+ }
217
+ if (raw.schemaVersion !== 1)
218
+ problems.push('"schemaVersion" must be 1.');
219
+ if (raw.$schema !== undefined && typeof raw.$schema !== "string")
220
+ problems.push('"$schema" must be a text.');
221
+ const collections = Object.create(null);
222
+ const rawColls = raw.collections ?? {};
223
+ if (!isObject(rawColls))
224
+ problems.push('"collections" must be an object: { "<name>": "mine" or "public", ... }.');
225
+ else {
226
+ const names = Object.keys(rawColls);
227
+ if (names.length > limits.collections)
228
+ problems.push(`At most ${limits.collections} collections. This file has ${names.length}.`);
229
+ for (const name of names) {
230
+ const v = rawColls[name];
231
+ if (!NAME.test(name)) {
232
+ problems.push(`${q(name)}: ${MESSAGES.collectionName()}`);
233
+ continue;
234
+ }
235
+ const rule = collectionRule(name, v, limits, problems);
236
+ if (rule)
237
+ collections[name] = rule;
238
+ }
239
+ }
240
+ const files = Object.create(null);
241
+ const rawFiles = raw.files ?? {};
242
+ if (!isObject(rawFiles))
243
+ problems.push('"files" must be an object: { "<name>": "mine" }.');
244
+ else {
245
+ const names = Object.keys(rawFiles);
246
+ if (names.length > limits.fileSets)
247
+ problems.push(`At most ${limits.fileSets} file sets. This file has ${names.length}.`);
248
+ for (const name of names) {
249
+ if (!NAME.test(name))
250
+ problems.push(`files ${q(name)}: A file set name has 1 to 40 letters, digits, - and _.`);
251
+ else if (rawFiles[name] !== "mine")
252
+ problems.push(`files ${q(name)}: ${NOT_SUPPORTED.publicFiles}`);
253
+ else
254
+ files[name] = "mine";
255
+ }
256
+ }
257
+ if (problems.length)
258
+ return { ok: false, problems };
259
+ return { ok: true, value: { schemaVersion: 1, collections, files } };
260
+ }
261
+ function collectionRule(name, v, limits, problems) {
262
+ if (typeof v === "string") {
263
+ if (!PRESETS.includes(v))
264
+ return problems.push(`${q(name)}: ${MESSAGES.onlyPresets()}`), null;
265
+ return { access: v, filter: [], sort: null };
266
+ }
267
+ if (!isObject(v))
268
+ return problems.push(`${q(name)}: give "mine", "public", or { "access": "mine" or "public", "filter": [...], "sort": "..." }.`), null;
269
+ const before = problems.length;
270
+ for (const k of Object.keys(v))
271
+ if (!["access", "filter", "sort"].includes(k))
272
+ problems.push(`${q(name)}: unknown field ${q(k)}. Use only "access", "filter" and "sort".`);
273
+ if (!PRESETS.includes(v.access))
274
+ problems.push(`${q(name)}: ${MESSAGES.onlyPresets()}`);
275
+ const filter = v.filter ?? [];
276
+ if (!Array.isArray(filter) || filter.some((f) => typeof f !== "string" || !FIELD.test(f))) {
277
+ problems.push(`${q(name)}: "filter" is a list of top-level field names (letters, digits and _), for example ["folder"].`);
278
+ }
279
+ else if (filter.length > limits.filterFields) {
280
+ problems.push(`${q(name)}: at most ${limits.filterFields} filter fields.`);
281
+ }
282
+ else if (new Set(filter).size !== filter.length) {
283
+ problems.push(`${q(name)}: each filter field only once.`);
284
+ }
285
+ const sort = v.sort ?? null;
286
+ if (sort !== null && (typeof sort !== "string" || !FIELD.test(sort)))
287
+ problems.push(`${q(name)}: "sort" is one top-level field name, for example "points".`);
288
+ else if (typeof sort === "string" && BUILT_IN_ORDERS.includes(sort))
289
+ problems.push(`${q(name)}: "createdAt" and "updatedAt" are always there. Do not declare them as "sort".`);
290
+ if (problems.length > before)
291
+ return null;
292
+ return { access: v.access, filter: [...filter], sort: sort };
293
+ }
294
+ // The rule of a collection, or the not-declared error.
295
+ export function ruleOf(decl, coll) {
296
+ if (!decl)
297
+ return ruleError("not-declared", MESSAGES.noDeclaration());
298
+ if (!NAME.test(coll))
299
+ return ruleError("invalid", MESSAGES.collectionName());
300
+ if (!Object.prototype.hasOwnProperty.call(decl.collections, coll))
301
+ return ruleError("not-declared", MESSAGES.notDeclared(coll));
302
+ return decl.collections[coll];
303
+ }
304
+ // The presets in plain words (6.1): the CLI prints these lines at each
305
+ // preview and save, and get_app gives them.
306
+ export function declarationText(decl) {
307
+ if (!decl)
308
+ return ["This app keeps no data on Builders (no builders.data.json)."];
309
+ const lines = ["Data of this app:"];
310
+ for (const [name, r] of Object.entries(decl.collections)) {
311
+ lines.push(r.access === "mine"
312
+ ? `- ${name}: each user sees and changes only their own (sign-in needed).`
313
+ : `- ${name}: everyone can see them; signed-in users add their own and change only their own.`);
314
+ }
315
+ for (const name of Object.keys(decl.files))
316
+ lines.push(`- ${name} (files): each user sees only their own (sign-in needed).`);
317
+ if (lines.length === 1)
318
+ lines.push("- (no collections)");
319
+ return lines;
320
+ }
321
+ // What changes from one declaration to the next, for the warnings of the
322
+ // CLI (6.1) and the answer of make_live (6.4).
323
+ export function declarationChanges(before, after) {
324
+ const warnings = [];
325
+ const publicChanged = [];
326
+ const old = before?.collections ?? {};
327
+ const now = after?.collections ?? {};
328
+ for (const [name, r] of Object.entries(now)) {
329
+ const o = Object.prototype.hasOwnProperty.call(old, name) ? old[name] : undefined;
330
+ if (o && o.access !== r.access) {
331
+ warnings.push(`${q(name)} changes from ${q(o.access)} to ${q(r.access)}: it starts empty. The old items stay hidden and come back when it is ${q(o.access)} again.`);
332
+ }
333
+ if (r.access === "public" && (!o || o.access !== "public"))
334
+ publicChanged.push(name);
335
+ }
336
+ for (const name of Object.keys(old)) {
337
+ if (!Object.prototype.hasOwnProperty.call(now, name))
338
+ warnings.push(`${q(name)} is not declared any more: its items stay hidden and come back when it is declared again.`);
339
+ }
340
+ return { warnings, publicChanged };
341
+ }
342
+ // --- Ids (6.2). ---
343
+ export const ITEM_ID = /^[A-Za-z0-9_-]{1,100}$/;
344
+ export const USER_ID = /^[a-z0-9]{16}$/;
345
+ const DOC_ID = /^[mp]\.[A-Za-z0-9_-]{1,40}\.[a-z0-9]{16}\.[A-Za-z0-9_-]{1,100}$/;
346
+ // A short id (no dot) always means the caller's own item. A public item has
347
+ // the full id "<user id>.<id>". The server never takes a prefix off an id:
348
+ // any other form is invalid.
349
+ export function itemRef(access, raw, viewer) {
350
+ if (typeof raw !== "string")
351
+ return ruleError("invalid", MESSAGES.badId());
352
+ const dot = raw.indexOf(".");
353
+ if (dot < 0)
354
+ return ITEM_ID.test(raw) ? { owner: viewer, id: raw } : ruleError("invalid", MESSAGES.badId());
355
+ if (access === "mine")
356
+ return ruleError("invalid", MESSAGES.dotInId());
357
+ const owner = raw.slice(0, dot);
358
+ const id = raw.slice(dot + 1);
359
+ if (!USER_ID.test(owner) || !ITEM_ID.test(id))
360
+ return ruleError("invalid", MESSAGES.dotInId());
361
+ return { owner, id };
362
+ }
363
+ export function scopeOf(access, coll, owner) {
364
+ return access === "mine" ? `${coll}.${owner}` : coll;
365
+ }
366
+ export function docIdOf(access, coll, owner, id) {
367
+ return `${NS_OF[access]}.${coll}.${owner}.${id}`;
368
+ }
369
+ export function isDocId(v) {
370
+ return typeof v === "string" && DOC_ID.test(v);
371
+ }
372
+ // The id that the app sees (8.1): "<user id>.<id>" in public, "<id>" in mine.
373
+ export function publicIdOf(access, docId) {
374
+ const parts = docId.split(".");
375
+ return access === "public" ? `${parts[2]}.${parts[3]}` : parts[3];
376
+ }
377
+ // The checks of the table in 6.4. `owner` is the user id of the item (for
378
+ // change and remove). Only the data service decides; the SDK runs the same
379
+ // checks first.
380
+ export function accessError(coll, rule, op, viewer, loginMode, owner) {
381
+ if (rule.access === "mine") {
382
+ if (!viewer)
383
+ return ruleError("sign-in-required", MESSAGES.mineSignIn(coll));
384
+ if (owner && owner !== viewer.uid)
385
+ return ruleError("not-allowed", MESSAGES.notOwn(coll));
386
+ return null;
387
+ }
388
+ if (op === "read")
389
+ return !viewer && loginMode !== "anyone" ? ruleError("sign-in-required", MESSAGES.publicReadSignIn(coll)) : null;
390
+ if (!viewer)
391
+ return ruleError("sign-in-required", op === "add" ? MESSAGES.publicAddSignIn(coll) : MESSAGES.publicChangeSignIn(coll));
392
+ if (op === "add")
393
+ return owner && owner !== viewer.uid ? ruleError("not-allowed", MESSAGES.notOwn(coll)) : null;
394
+ if (owner && owner !== viewer.uid && !(op === "remove" && viewer.developer))
395
+ return ruleError("not-allowed", MESSAGES.notOwn(coll));
396
+ return null;
397
+ }
398
+ // --- Values (6.5). ---
399
+ function depthOf(v, max) {
400
+ let deepest = 0;
401
+ const stack = [[v, 1]];
402
+ while (stack.length) {
403
+ const [x, d] = stack.pop();
404
+ if (typeof x !== "object" || x === null)
405
+ continue;
406
+ if (d > deepest)
407
+ deepest = d;
408
+ if (deepest > max)
409
+ return deepest;
410
+ for (const c of Object.values(x))
411
+ stack.push([c, d + 1]);
412
+ }
413
+ return deepest;
414
+ }
415
+ const utf8 = (s) => new TextEncoder().encode(s).length;
416
+ // The data of an item as stored: JSON text (any JSON object fits, and no
417
+ // app field makes index entries). Dates become strings, as in JSON.
418
+ export function checkData(data, limits = DATA_LIMITS) {
419
+ if (!isObject(data))
420
+ return ruleError("invalid", MESSAGES.dataObject());
421
+ let text;
422
+ try {
423
+ text = JSON.stringify(data);
424
+ }
425
+ catch {
426
+ return ruleError("invalid", MESSAGES.notJson());
427
+ }
428
+ const size = utf8(text);
429
+ if (size > limits.itemBytes)
430
+ return ruleError("too-large", MESSAGES.tooLarge(Math.floor(limits.itemBytes / 1024)));
431
+ const value = JSON.parse(text);
432
+ if (depthOf(value, limits.depth) > limits.depth)
433
+ return ruleError("invalid", MESSAGES.tooDeep(limits.depth));
434
+ return { text, size, value };
435
+ }
436
+ // --- The index slots of an item (6.2). ---
437
+ function canonical(v) {
438
+ if (v === null || v === undefined)
439
+ return "null";
440
+ if (typeof v === "boolean")
441
+ return v ? "true" : "false";
442
+ if (typeof v === "number")
443
+ return Number.isFinite(v) ? (Object.is(v, -0) ? "0" : JSON.stringify(v)) : null;
444
+ if (typeof v === "string")
445
+ return JSON.stringify(v);
446
+ return null;
447
+ }
448
+ // "<field>=<canonical JSON>": an old slot never matches another field. A
449
+ // missing field counts as null.
450
+ export function slotOf(field, v) {
451
+ const c = canonical(v);
452
+ if (c === null)
453
+ return null;
454
+ const slot = `${field}=${c}`;
455
+ return utf8(slot) <= SLOT_BYTES_MAX ? slot : null;
456
+ }
457
+ // A text cut to at most `max` UTF-8 bytes, on a character boundary.
458
+ export function cutUtf8(s, max) {
459
+ if (utf8(s) <= max)
460
+ return s;
461
+ let out = "";
462
+ let n = 0;
463
+ for (const ch of s) {
464
+ const b = utf8(ch);
465
+ if (n + b > max)
466
+ break;
467
+ out += ch;
468
+ n += b;
469
+ }
470
+ return out;
471
+ }
472
+ export function slotsOf(rule, value) {
473
+ const out = {};
474
+ const own = (k) => (Object.prototype.hasOwnProperty.call(value, k) ? value[k] : undefined);
475
+ rule.filter.forEach((f, i) => {
476
+ const s = slotOf(f, own(f));
477
+ if (s !== null)
478
+ out[i === 0 ? "f1" : "f2"] = s;
479
+ });
480
+ if (rule.sort) {
481
+ const s = own(rule.sort);
482
+ if (typeof s === "number" && Number.isFinite(s))
483
+ out.s = Object.is(s, -0) ? 0 : s;
484
+ else if (typeof s === "string")
485
+ out.s = cutUtf8(s, SLOT_BYTES_MAX);
486
+ }
487
+ return out;
488
+ }
489
+ // The order of sort values as in Firestore: numbers before strings.
490
+ export function compareSort(a, b) {
491
+ const ta = typeof a === "number" ? 0 : 1;
492
+ const tb = typeof b === "number" ? 0 : 1;
493
+ if (ta !== tb)
494
+ return ta - tb;
495
+ if (a === b)
496
+ return 0;
497
+ return a < b ? -1 : 1;
498
+ }
499
+ const LIST_KEYS = ["where", "orderBy", "direction", "limit", "after", "mine"];
500
+ const COUNT_KEYS = ["where", "mine"];
501
+ export function encodeCursor(value, docId) {
502
+ const json = JSON.stringify([value, docId]);
503
+ const bytes = new TextEncoder().encode(json);
504
+ let bin = "";
505
+ for (const b of bytes)
506
+ bin += String.fromCharCode(b);
507
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
508
+ }
509
+ export function decodeCursor(raw) {
510
+ if (typeof raw !== "string" || raw.length > 2000 || !/^[A-Za-z0-9_-]+$/.test(raw))
511
+ return null;
512
+ try {
513
+ const bin = atob(raw.replace(/-/g, "+").replace(/_/g, "/"));
514
+ const v = JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0))));
515
+ if (!Array.isArray(v) || v.length !== 2 || !isDocId(v[1]))
516
+ return null;
517
+ if (!(typeof v[0] === "string" && utf8(v[0]) <= SLOT_BYTES_MAX) && !(typeof v[0] === "number" && Number.isFinite(v[0])))
518
+ return null;
519
+ return [v[0], v[1]];
520
+ }
521
+ catch {
522
+ return null;
523
+ }
524
+ }
525
+ // Checks a query of list, count or watch against the declaration.
526
+ export function planQuery(coll, rule, raw, call) {
527
+ const query = raw ?? {};
528
+ if (!isObject(query))
529
+ return ruleError("invalid", MESSAGES.queryKeys(`${call}()`, "an object"));
530
+ const allowed = call === "count" ? COUNT_KEYS : LIST_KEYS;
531
+ for (const k of Object.keys(query)) {
532
+ if (!allowed.includes(k))
533
+ return ruleError("invalid", MESSAGES.queryKeys(`${call}()`, allowed.join(", ")));
534
+ }
535
+ const out = { where: {}, order: "createdAt", direction: "desc", limit: LIST_DEFAULT, after: null, mine: false, usesSlots: false };
536
+ if (query.mine !== undefined && typeof query.mine !== "boolean")
537
+ return ruleError("invalid", "mine is true or false.");
538
+ out.mine = query.mine === true;
539
+ if (out.mine && rule.access !== "public")
540
+ return ruleError("invalid", MESSAGES.mineOnlyPublic(coll));
541
+ const where = query.where ?? {};
542
+ if (!isObject(where))
543
+ return ruleError("invalid", MESSAGES.queryKeys("where", 'an object of field and value, for example { folder: "work" }'));
544
+ const fields = Object.keys(where);
545
+ if (fields.length && out.mine)
546
+ return ruleError("invalid", MESSAGES.mineNoWhere());
547
+ for (const f of fields) {
548
+ const v = where[f];
549
+ const i = rule.filter.indexOf(f);
550
+ if (i < 0)
551
+ return ruleError("invalid", MESSAGES.notFilter(coll, f, rule.access));
552
+ if (typeof v === "object" && v !== null)
553
+ return ruleError("invalid", MESSAGES.range(rule.sort ?? f));
554
+ const slot = slotOf(f, v);
555
+ if (slot === null || v === undefined)
556
+ return ruleError("invalid", MESSAGES.filterValue(f));
557
+ out.where[i === 0 ? "f1" : "f2"] = slot;
558
+ out.usesSlots = true;
559
+ }
560
+ if (query.orderBy !== undefined) {
561
+ if (query.orderBy === "createdAt" || query.orderBy === "updatedAt")
562
+ out.order = query.orderBy;
563
+ else if (typeof query.orderBy === "string" && query.orderBy === rule.sort) {
564
+ out.order = "s";
565
+ out.usesSlots = true;
566
+ }
567
+ else
568
+ return ruleError("invalid", MESSAGES.notSort(coll, String(query.orderBy), rule.access));
569
+ }
570
+ if (query.direction !== undefined) {
571
+ if (query.direction !== "asc" && query.direction !== "desc")
572
+ return ruleError("invalid", MESSAGES.direction());
573
+ out.direction = query.direction;
574
+ }
575
+ if (query.limit !== undefined) {
576
+ if (typeof query.limit !== "number" || !Number.isInteger(query.limit) || query.limit < 1 || query.limit > LIST_MAX)
577
+ return ruleError("invalid", MESSAGES.limit(LIST_MAX));
578
+ out.limit = query.limit;
579
+ }
580
+ if (query.after !== undefined && query.after !== null) {
581
+ const c = decodeCursor(query.after);
582
+ // A time order needs a time (microseconds): never a text.
583
+ if (!c || (out.order !== "s" && !(typeof c[0] === "number" && Number.isSafeInteger(c[0]) && c[0] >= 0)))
584
+ return ruleError("invalid", MESSAGES.badCursor());
585
+ out.after = c;
586
+ }
587
+ return out;
588
+ }
589
+ // A time in microseconds as an ISO text (milliseconds).
590
+ export function isoOfUs(us) {
591
+ return new Date(Math.floor(us / 1000)).toISOString();
592
+ }
593
+ export const FILE_TYPES = {
594
+ "image/jpeg": { kind: "image", ext: "jpg", label: "JPEG" },
595
+ "image/png": { kind: "image", ext: "png", label: "PNG" },
596
+ "image/webp": { kind: "image", ext: "webp", label: "WebP" },
597
+ "image/gif": { kind: "image", ext: "gif", label: "GIF" },
598
+ "image/avif": { kind: "image", ext: "avif", label: "AVIF" },
599
+ "image/heic": { kind: "image", ext: "heic", label: "HEIC" },
600
+ "audio/mpeg": { kind: "audio", ext: "mp3", label: "MP3" },
601
+ "audio/mp4": { kind: "audio", ext: "m4a", label: "M4A" },
602
+ "audio/ogg": { kind: "audio", ext: "ogg", label: "OGG" },
603
+ "audio/wav": { kind: "audio", ext: "wav", label: "WAV" },
604
+ "audio/webm": { kind: "audio", ext: "webm", label: "WebM audio" },
605
+ "video/mp4": { kind: "video", ext: "mp4", label: "MP4" },
606
+ "video/webm": { kind: "video", ext: "webm", label: "WebM video" },
607
+ "application/pdf": { kind: "pdf", ext: "pdf", label: "PDF" },
608
+ };
609
+ const FILE_TYPE_NAMES = "JPEG, PNG, WebP, GIF, AVIF or HEIC pictures, MP3, M4A, OGG, WAV or WebM audio, MP4 or WebM video, or PDF";
610
+ // Other names that browsers give to the same types.
611
+ const TYPE_ALIASES = {
612
+ "image/jpg": "image/jpeg",
613
+ "image/pjpeg": "image/jpeg",
614
+ "image/heif": "image/heic",
615
+ "audio/mp3": "audio/mpeg",
616
+ "audio/mpeg3": "audio/mpeg",
617
+ "audio/x-mpeg": "audio/mpeg",
618
+ "audio/x-mp3": "audio/mpeg",
619
+ "audio/x-m4a": "audio/mp4",
620
+ "audio/m4a": "audio/mp4",
621
+ "audio/x-wav": "audio/wav",
622
+ "audio/wave": "audio/wav",
623
+ "audio/vnd.wave": "audio/wav",
624
+ "application/ogg": "audio/ogg",
625
+ "video/x-m4v": "video/mp4",
626
+ };
627
+ // The bytes that the type check reads.
628
+ export const FILE_HEAD_BYTES = 64;
629
+ // The declared type in its stored form. "": no type given (the type from
630
+ // the bytes is used). null: a type that is not possible.
631
+ export function fileTypeOf(raw) {
632
+ if (raw === undefined || raw === null || raw === "")
633
+ return "";
634
+ if (typeof raw !== "string" || raw.length > 200)
635
+ return null;
636
+ const t = raw.split(";")[0].trim().toLowerCase();
637
+ const canonical = TYPE_ALIASES[t] ?? t;
638
+ return Object.prototype.hasOwnProperty.call(FILE_TYPES, canonical) ? canonical : null;
639
+ }
640
+ const ascii = (b, at, text) => {
641
+ if (b.length < at + text.length)
642
+ return false;
643
+ for (let i = 0; i < text.length; i++)
644
+ if (b[at + i] !== text.charCodeAt(i))
645
+ return false;
646
+ return true;
647
+ };
648
+ function indexOfAscii(b, text, from) {
649
+ for (let i = from; i + text.length <= b.length; i++)
650
+ if (ascii(b, i, text))
651
+ return i;
652
+ return -1;
653
+ }
654
+ const AVIF_BRANDS = ["avif", "avis"];
655
+ const HEIC_BRANDS = ["heic", "heix", "heim", "heis", "hevc", "hevx", "mif1", "msf1"];
656
+ const M4A_BRANDS = ["M4A ", "M4B ", "M4P "];
657
+ const M4V_BRANDS = ["M4V ", "M4VH", "M4VP"];
658
+ const MP4_BRANDS = ["isom", "iso2", "iso3", "iso4", "iso5", "iso6", "mp41", "mp42", "avc1", "dash", "mmp4", "MSNV"];
659
+ function isoBrands(b) {
660
+ const size = ((b[0] << 24) >>> 0) + (b[1] << 16) + (b[2] << 8) + b[3];
661
+ const end = Math.min(b.length, Math.max(16, size));
662
+ const brands = [String.fromCharCode(...b.subarray(8, 12))];
663
+ for (let i = 16; i + 4 <= end; i += 4)
664
+ brands.push(String.fromCharCode(...b.subarray(i, i + 4)));
665
+ return brands;
666
+ }
667
+ // The types that the first bytes of a file can be (stored form), the most
668
+ // likely first. Empty: none of section 7 (for example SVG, HTML, XML or a
669
+ // script). The check reads only the start of the file.
670
+ export function sniffFileTypes(b) {
671
+ if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff)
672
+ return ["image/jpeg"];
673
+ if (b.length >= 8 && [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((x, i) => b[i] === x))
674
+ return ["image/png"];
675
+ if (ascii(b, 0, "GIF87a") || ascii(b, 0, "GIF89a"))
676
+ return ["image/gif"];
677
+ if (ascii(b, 0, "RIFF") && ascii(b, 8, "WEBP"))
678
+ return ["image/webp"];
679
+ if (ascii(b, 0, "RIFF") && ascii(b, 8, "WAVE"))
680
+ return ["audio/wav"];
681
+ if (ascii(b, 0, "%PDF-"))
682
+ return ["application/pdf"];
683
+ if (ascii(b, 0, "OggS"))
684
+ return ["audio/ogg"];
685
+ if (b.length >= 4 && b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3) {
686
+ // EBML: only the doc type "webm" (not Matroska).
687
+ return indexOfAscii(b, "webm", 4) > 0 ? ["video/webm", "audio/webm"] : [];
688
+ }
689
+ if (b.length >= 12 && ascii(b, 4, "ftyp")) {
690
+ const brands = isoBrands(b);
691
+ const major = brands[0];
692
+ if (AVIF_BRANDS.includes(major) || (HEIC_BRANDS.includes(major) && brands.some((x) => AVIF_BRANDS.includes(x))))
693
+ return ["image/avif"];
694
+ if (HEIC_BRANDS.includes(major))
695
+ return ["image/heic"];
696
+ if (M4A_BRANDS.includes(major))
697
+ return ["audio/mp4"];
698
+ if (M4V_BRANDS.includes(major))
699
+ return ["video/mp4"];
700
+ if (MP4_BRANDS.includes(major))
701
+ return ["video/mp4", "audio/mp4"];
702
+ return [];
703
+ }
704
+ if (ascii(b, 0, "ID3"))
705
+ return ["audio/mpeg"];
706
+ // An MP3 frame: the sync bits, MPEG version not reserved, layer III, a
707
+ // valid bit rate and sample rate.
708
+ if (b.length >= 3 && b[0] === 0xff && (b[1] & 0xe0) === 0xe0 && ((b[1] >> 3) & 3) !== 1 && ((b[1] >> 1) & 3) === 1 && b[2] >> 4 !== 15 && b[2] >> 4 !== 0 && ((b[2] >> 2) & 3) !== 3)
709
+ return ["audio/mpeg"];
710
+ return [];
711
+ }
712
+ // The stored type of an upload: the declared type when the bytes can be
713
+ // it; with no declared type, the type from the bytes.
714
+ export function checkFileType(declared, head) {
715
+ const can = sniffFileTypes(head.subarray(0, FILE_HEAD_BYTES));
716
+ if (!can.length)
717
+ return ruleError("invalid", declared ? MESSAGES.fileContent(declared) : MESSAGES.fileType());
718
+ if (!declared)
719
+ return can[0];
720
+ return can.includes(declared) ? declared : ruleError("invalid", MESSAGES.fileContent(declared));
721
+ }
722
+ // The file set of a name, or the error.
723
+ export function fileSetOf(decl, set) {
724
+ if (!decl)
725
+ return ruleError("not-declared", MESSAGES.noDeclaration());
726
+ if (!NAME.test(set))
727
+ return ruleError("invalid", MESSAGES.fileSetName());
728
+ if (!Object.prototype.hasOwnProperty.call(decl.files, set))
729
+ return ruleError("not-declared", MESSAGES.fileSetNotDeclared(set));
730
+ return null;
731
+ }
732
+ // A file id: 9 characters of time, newest first in the order of ids, then
733
+ // 11 random characters.
734
+ export const FILE_ID = /^[0-9a-z]{9}[A-Za-z0-9]{11}$/;
735
+ const TIME_MAX = 36 ** 9 - 1;
736
+ export function fileIdOf(nowMs, random) {
737
+ return (TIME_MAX - Math.min(TIME_MAX, Math.max(0, Math.floor(nowMs)))).toString(36).padStart(9, "0") + random.slice(0, 11);
738
+ }
739
+ // The id of the record of a file: the set and the owner are in it, so that
740
+ // no id reaches another user's file or another set.
741
+ export function fileDocIdOf(set, uid, id) {
742
+ return `${set}.${uid}.${id}`;
743
+ }
744
+ // The object of a file in the bucket (7).
745
+ export function fileObjectOf(appId, space, uid, id) {
746
+ return `apps/${appId}/${space}/${uid}/${id}`;
747
+ }
748
+ export function fileUrlOf(set, id) {
749
+ return `/_api/files/${set}/${id}`;
750
+ }
751
+ // Control characters, line breaks and the marks that turn text around.
752
+ // eslint-disable-next-line no-control-regex
753
+ const NAME_BAD = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/;
754
+ // The name of a file as the app gave it. No name: "file".
755
+ export function checkFileName(raw) {
756
+ if (raw === undefined || raw === null || raw === "")
757
+ return "file";
758
+ if (typeof raw !== "string" || raw.length > 200 || NAME_BAD.test(raw) || !raw.trim())
759
+ return ruleError("invalid", MESSAGES.fileName());
760
+ return raw;
761
+ }
762
+ // The name for Content-Disposition: the extension of the stored type, so
763
+ // that a saved file opens as that type.
764
+ export function downloadNameOf(name, type) {
765
+ const ext = FILE_TYPES[type]?.ext ?? "bin";
766
+ const stem = name.replace(/[\\/]/g, "_").replace(/\.[A-Za-z0-9]{1,5}$/, "") || "file";
767
+ return `${stem}.${ext}`;
768
+ }