@rebasepro/common 0.8.0 → 0.9.1-canary.09aaf62
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 +5 -5
- package/dist/collections/CollectionRegistry.d.ts +16 -16
- package/dist/collections/default-collections.d.ts +5 -1
- package/dist/data/buildRebaseData.d.ts +44 -3
- package/dist/data/buildRoutedRebaseData.d.ts +14 -9
- package/dist/data/filter-dialect.d.ts +18 -4
- package/dist/data/query_builder.d.ts +1 -1
- package/dist/data/resolveDataSource.d.ts +1 -1
- package/dist/data/sort-dialect.d.ts +41 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.es.js +1236 -179
- package/dist/index.es.js.map +1 -1
- package/dist/util/auth-default-policies.d.ts +22 -0
- package/dist/util/builders.d.ts +19 -56
- package/dist/util/callbacks.d.ts +3 -3
- package/dist/util/collections.d.ts +4 -4
- package/dist/util/entities.d.ts +2 -2
- package/dist/util/filter-operator-resolution.d.ts +32 -0
- package/dist/util/identity.d.ts +83 -0
- package/dist/util/index.d.ts +4 -0
- package/dist/util/junction-policies.d.ts +108 -0
- package/dist/util/navigation_from_path.d.ts +4 -4
- package/dist/util/navigation_utils.d.ts +3 -3
- package/dist/util/parent_references_from_path.d.ts +2 -2
- package/dist/util/permissions.d.ts +6 -6
- package/dist/util/policy/evaluatePolicy.d.ts +8 -1
- package/dist/util/policy/index.d.ts +1 -0
- package/dist/util/policy/policyToPostgres.d.ts +14 -2
- package/dist/util/policy/sqlToPolicy.d.ts +24 -14
- package/dist/util/references.d.ts +2 -2
- package/dist/util/relations.d.ts +5 -5
- package/dist/util/resolutions.d.ts +2 -2
- package/package.json +7 -8
- package/src/collections/CollectionRegistry.ts +36 -36
- package/src/collections/default-collections.ts +2 -0
- package/src/data/buildRebaseData.ts +430 -60
- package/src/data/buildRoutedRebaseData.ts +22 -16
- package/src/data/filter-dialect.ts +151 -60
- package/src/data/query_builder.ts +11 -2
- package/src/data/resolveDataSource.ts +1 -1
- package/src/data/sort-dialect.ts +56 -0
- package/src/index.ts +1 -0
- package/src/util/auth-default-policies.ts +152 -0
- package/src/util/builders.ts +25 -99
- package/src/util/callbacks.ts +8 -8
- package/src/util/collections.ts +4 -4
- package/src/util/entities.ts +4 -4
- package/src/util/filter-operator-resolution.ts +81 -0
- package/src/util/identity.ts +166 -0
- package/src/util/index.ts +4 -0
- package/src/util/junction-policies.ts +353 -0
- package/src/util/navigation_from_path.ts +4 -4
- package/src/util/navigation_utils.ts +8 -8
- package/src/util/parent_references_from_path.ts +3 -3
- package/src/util/permissions.test.ts +2 -2
- package/src/util/permissions.ts +7 -7
- package/src/util/policy/evaluatePolicy.ts +26 -4
- package/src/util/policy/index.ts +1 -0
- package/src/util/policy/policyToPostgres.ts +123 -17
- package/src/util/policy/sqlToPolicy.ts +190 -13
- package/src/util/references.ts +2 -2
- package/src/util/relations.ts +12 -12
- package/src/util/resolutions.ts +5 -5
- package/dist/index.umd.js +0 -2901
- package/dist/index.umd.js.map +0 -1
package/dist/index.es.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { CANONICAL_TO_REST, DEFAULT_DATA_SOURCE_KEY, EntityReference, EntityRelation, REST_TO_CANONICAL, getDataSourceCapabilities, getDeclaredSubcollections, policy, toCanonicalOp } from "@rebasepro/types";
|
|
2
|
-
import { deepClone, generateForeignKeyName, getIn, isDefaultFieldConfigId, mergeDeep, randomString, removeFunctions, toSnakeCase } from "@rebasepro/utils";
|
|
1
|
+
import { ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, CANONICAL_TO_REST, DEFAULT_DATA_SOURCE_KEY, EntityReference, EntityRelation, NULL_OPS, REST_TO_CANONICAL, getDataSourceCapabilities, getDeclaredSubcollections, isPostgresCollectionConfig, policy, toCanonicalOp } from "@rebasepro/types";
|
|
2
|
+
import { deepClone, generateForeignKeyName, getIn, getPolicyOperations, isDefaultFieldConfigId, mergeDeep, randomString, removeFunctions, toSnakeCase } from "@rebasepro/utils";
|
|
3
3
|
import jsonLogic from "json-logic-js";
|
|
4
4
|
import { deepEqual } from "fast-equals";
|
|
5
5
|
//#region src/util/common.ts
|
|
@@ -54,7 +54,7 @@ function getDefaultValueFortype(type) {
|
|
|
54
54
|
else return null;
|
|
55
55
|
}
|
|
56
56
|
/**
|
|
57
|
-
* Update the automatic values in
|
|
57
|
+
* Update the automatic values in a entity before save
|
|
58
58
|
* @group Driver
|
|
59
59
|
*/
|
|
60
60
|
function updateDateAutoValues({ inputValues, properties, status, timestampNowValue }) {
|
|
@@ -66,7 +66,7 @@ function updateDateAutoValues({ inputValues, properties, status, timestampNowVal
|
|
|
66
66
|
}) ?? {};
|
|
67
67
|
}
|
|
68
68
|
/**
|
|
69
|
-
* Add missing required fields, expected in the collection, to the values of
|
|
69
|
+
* Add missing required fields, expected in the collection, to the values of a entity
|
|
70
70
|
* @param values
|
|
71
71
|
* @param properties
|
|
72
72
|
* @group Driver
|
|
@@ -236,7 +236,7 @@ function getLocalChangesBackup(collection) {
|
|
|
236
236
|
return collection.localChangesBackup;
|
|
237
237
|
}
|
|
238
238
|
/**
|
|
239
|
-
* Returns the primary keys for
|
|
239
|
+
* Returns the primary keys for a entity collection by inspecting the properties
|
|
240
240
|
* and finding any properties with `isId`.
|
|
241
241
|
* Fallbacks to `["id"]` if no properties are marked as `isId: true`.
|
|
242
242
|
* @param collection
|
|
@@ -249,6 +249,113 @@ function getPrimaryKeys(collection) {
|
|
|
249
249
|
return ["id"];
|
|
250
250
|
}
|
|
251
251
|
//#endregion
|
|
252
|
+
//#region src/util/identity.ts
|
|
253
|
+
/** Separator between the parts of a composite address. */
|
|
254
|
+
var COMPOSITE_ID_SEPARATOR = ":::";
|
|
255
|
+
/**
|
|
256
|
+
* Derive a row's address from its key columns.
|
|
257
|
+
*
|
|
258
|
+
* Single key → the value as a string. Composite → each part joined by
|
|
259
|
+
* {@link COMPOSITE_ID_SEPARATOR}, in primary-key order, which is what
|
|
260
|
+
* {@link parseIdValues} expects to invert.
|
|
261
|
+
*/
|
|
262
|
+
function buildCompositeId(values, primaryKeys) {
|
|
263
|
+
if (primaryKeys.length === 0) return "";
|
|
264
|
+
if (primaryKeys.length === 1) return String(values[primaryKeys[0].fieldName] ?? "");
|
|
265
|
+
return primaryKeys.map((pk) => String(values[pk.fieldName] ?? "")).join(":::");
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Invert {@link buildCompositeId}: turn an address back into key columns, each
|
|
269
|
+
* coerced to the type its column actually round-trips as.
|
|
270
|
+
*
|
|
271
|
+
* This is the boundary where a URL segment becomes a query parameter, so a
|
|
272
|
+
* malformed address must throw rather than silently produce a query that
|
|
273
|
+
* matches the wrong row (or none).
|
|
274
|
+
*/
|
|
275
|
+
function parseIdValues(idValue, primaryKeys) {
|
|
276
|
+
const result = {};
|
|
277
|
+
if (primaryKeys.length === 0) return result;
|
|
278
|
+
if (primaryKeys.length === 1) {
|
|
279
|
+
const pk = primaryKeys[0];
|
|
280
|
+
if (pk.type === "number" && !pk.isUUID) {
|
|
281
|
+
const parsed = typeof idValue === "number" ? idValue : parseInt(String(idValue), 10);
|
|
282
|
+
if (isNaN(parsed)) throw new Error(`Invalid numeric ID: ${idValue}`);
|
|
283
|
+
result[pk.fieldName] = parsed;
|
|
284
|
+
} else result[pk.fieldName] = String(idValue);
|
|
285
|
+
return result;
|
|
286
|
+
}
|
|
287
|
+
const parts = String(idValue).split(":::");
|
|
288
|
+
if (parts.length !== primaryKeys.length) throw new Error(`Composite ID parts mismatch. Expected ${primaryKeys.length}, got ${parts.length} for ID: ${idValue}`);
|
|
289
|
+
for (let i = 0; i < primaryKeys.length; i++) {
|
|
290
|
+
const pk = primaryKeys[i];
|
|
291
|
+
const val = parts[i];
|
|
292
|
+
if (pk.type === "number" && !pk.isUUID) {
|
|
293
|
+
const parsed = parseInt(val, 10);
|
|
294
|
+
if (isNaN(parsed)) throw new Error(`Invalid numeric ID component: ${val}`);
|
|
295
|
+
result[pk.fieldName] = parsed;
|
|
296
|
+
} else result[pk.fieldName] = val;
|
|
297
|
+
}
|
|
298
|
+
return result;
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* The primary keys of a collection, as declared by its properties.
|
|
302
|
+
*
|
|
303
|
+
* This is the only tier both sides can read, because it is the only one written
|
|
304
|
+
* in the config: the postgres driver can also infer keys from the Drizzle
|
|
305
|
+
* schema, which the browser never sees and is never sent — the admin compiles
|
|
306
|
+
* the collection files into its own bundle rather than being served them. A key
|
|
307
|
+
* that lives only in the Drizzle schema is therefore invisible here, and the
|
|
308
|
+
* server says so at boot (`warnOnKeysTheAdminCannotResolve`) naming the `isId`
|
|
309
|
+
* to add.
|
|
310
|
+
*
|
|
311
|
+
* Returns an empty array when a collection declares none, which callers must
|
|
312
|
+
* treat as "not addressable" rather than defaulting to `id`: guessing a key
|
|
313
|
+
* that is not the real one produces confidently wrong addresses.
|
|
314
|
+
*/
|
|
315
|
+
function getDeclaredPrimaryKeys(collection) {
|
|
316
|
+
const properties = collection.properties;
|
|
317
|
+
if (!properties) return [];
|
|
318
|
+
const keys = [];
|
|
319
|
+
for (const [fieldName, propRaw] of Object.entries(properties)) {
|
|
320
|
+
const prop = propRaw;
|
|
321
|
+
if (!prop || typeof prop !== "object") continue;
|
|
322
|
+
if (!("isId" in prop) || !prop.isId) continue;
|
|
323
|
+
keys.push({
|
|
324
|
+
fieldName,
|
|
325
|
+
type: prop.type === "number" ? "number" : "string",
|
|
326
|
+
isUUID: prop.isId === "uuid"
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
return keys;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* The keys to address a collection's rows with, resolved the way the driver
|
|
333
|
+
* resolves them — minus the tier the browser cannot reach.
|
|
334
|
+
*
|
|
335
|
+
* The postgres driver tries, in order: properties marked `isId`; the primary
|
|
336
|
+
* keys of the Drizzle schema; and finally a column literally named `id`. Only
|
|
337
|
+
* the first and last are visible in a `CollectionConfig`, which is what both
|
|
338
|
+
* sides share.
|
|
339
|
+
*
|
|
340
|
+
* So the two agree except on a collection that declares no `isId` and whose key
|
|
341
|
+
* is known only to Drizzle. There, the driver reads the real key, and this
|
|
342
|
+
* either resolves nothing (reported to the console by the caller) or — if the
|
|
343
|
+
* table happens to have an unrelated `id` property — resolves `id`, which is
|
|
344
|
+
* the wrong key and cannot be detected from here: the addresses look right and
|
|
345
|
+
* route wrong. Only the config can settle it, so the server names both cases
|
|
346
|
+
* at boot (`warnOnKeysTheAdminCannotResolve`) with the `isId` to add.
|
|
347
|
+
*/
|
|
348
|
+
function resolvePrimaryKeys(collection) {
|
|
349
|
+
const declared = getDeclaredPrimaryKeys(collection);
|
|
350
|
+
if (declared.length > 0) return declared;
|
|
351
|
+
const idProp = collection.properties?.id;
|
|
352
|
+
if (idProp && typeof idProp === "object") return [{
|
|
353
|
+
fieldName: "id",
|
|
354
|
+
type: idProp.type === "number" ? "number" : "string"
|
|
355
|
+
}];
|
|
356
|
+
return [];
|
|
357
|
+
}
|
|
358
|
+
//#endregion
|
|
252
359
|
//#region src/util/enums.ts
|
|
253
360
|
function enumToObjectEntries(enumValues) {
|
|
254
361
|
if (Array.isArray(enumValues)) return enumValues;
|
|
@@ -682,15 +789,109 @@ function getSubcollections(collection) {
|
|
|
682
789
|
* - `field = 'literal'`
|
|
683
790
|
* - `field != 'literal'`
|
|
684
791
|
* - `field = current_setting('app.user_id')`
|
|
685
|
-
* - `A AND B`
|
|
792
|
+
* - `A AND B`, `A OR B` — only where the keyword is at the top level
|
|
686
793
|
* - `true`
|
|
687
794
|
* - `IN (...)` (as optimistic true)
|
|
688
795
|
*
|
|
689
796
|
* For anything it doesn't understand, it returns a `raw` expression, which
|
|
690
797
|
* the evaluator treats as "unknown" (and usually optimistic true).
|
|
798
|
+
*
|
|
799
|
+
* **This output also round-trips back into DDL** via `policyToPostgres` (the
|
|
800
|
+
* schema/policy generators), so decomposing a clause the parser only partly
|
|
801
|
+
* understands is not a cosmetic mistake — it emits invalid SQL. When in doubt,
|
|
802
|
+
* prefer `raw`: it is reproduced verbatim.
|
|
803
|
+
*/
|
|
804
|
+
/** True when `keyword` starts at `i` as a standalone word. */
|
|
805
|
+
function isKeywordAt(upper, i, keyword) {
|
|
806
|
+
if (!upper.startsWith(keyword, i)) return false;
|
|
807
|
+
const before = i === 0 ? " " : upper[i - 1];
|
|
808
|
+
const after = upper[i + keyword.length] ?? " ";
|
|
809
|
+
return /[\s()]/.test(before) && /[\s()]/.test(after);
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Split `sql` on a boolean keyword, but only where it sits at paren depth 0 and
|
|
813
|
+
* outside a string literal. Returns null when it never does, so the caller
|
|
814
|
+
* leaves the clause alone.
|
|
815
|
+
*
|
|
816
|
+
* This used to be `sql.split(/ AND /i)`, which tore subqueries in half: the
|
|
817
|
+
* `AND` inside
|
|
818
|
+
* `EXISTS (SELECT 1 FROM organization_members m WHERE m.org = t.org AND m.user_id = auth.uid())`
|
|
819
|
+
* split the expression, and re-emitting the halves produced
|
|
820
|
+
* `(EXISTS (...) AND m.user_id = auth.uid())`
|
|
821
|
+
* where `m` is no longer in scope — SQL that Postgres rejects outright with
|
|
822
|
+
* "missing FROM-clause entry for table". Returning null instead keeps such a
|
|
823
|
+
* clause as a `raw` expression, which round-trips verbatim.
|
|
691
824
|
*/
|
|
825
|
+
function splitTopLevel(sql, keyword) {
|
|
826
|
+
const upper = sql.toUpperCase();
|
|
827
|
+
const parts = [];
|
|
828
|
+
let depth = 0;
|
|
829
|
+
let inString = false;
|
|
830
|
+
let start = 0;
|
|
831
|
+
for (let i = 0; i < sql.length; i++) {
|
|
832
|
+
const ch = sql[i];
|
|
833
|
+
if (inString) {
|
|
834
|
+
if (ch === "'") if (sql[i + 1] === "'") i++;
|
|
835
|
+
else inString = false;
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
if (ch === "'") {
|
|
839
|
+
inString = true;
|
|
840
|
+
continue;
|
|
841
|
+
}
|
|
842
|
+
if (ch === "(") {
|
|
843
|
+
depth++;
|
|
844
|
+
continue;
|
|
845
|
+
}
|
|
846
|
+
if (ch === ")") {
|
|
847
|
+
depth--;
|
|
848
|
+
continue;
|
|
849
|
+
}
|
|
850
|
+
if (depth === 0 && isKeywordAt(upper, i, keyword)) {
|
|
851
|
+
parts.push(sql.slice(start, i));
|
|
852
|
+
i += keyword.length - 1;
|
|
853
|
+
start = i + 1;
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
if (parts.length === 0) return null;
|
|
857
|
+
parts.push(sql.slice(start));
|
|
858
|
+
const trimmedParts = parts.map((p) => p.trim()).filter((p) => p.length > 0);
|
|
859
|
+
return trimmedParts.length > 1 ? trimmedParts : null;
|
|
860
|
+
}
|
|
861
|
+
/** Drop redundant wrapping parens (`(a AND b)` → `a AND b`), never `(a) AND (b)`. */
|
|
862
|
+
function stripOuterParens(sql) {
|
|
863
|
+
let s = sql.trim();
|
|
864
|
+
for (;;) {
|
|
865
|
+
if (!s.startsWith("(") || !s.endsWith(")")) return s;
|
|
866
|
+
let depth = 0;
|
|
867
|
+
let inString = false;
|
|
868
|
+
let wraps = true;
|
|
869
|
+
for (let i = 0; i < s.length; i++) {
|
|
870
|
+
const ch = s[i];
|
|
871
|
+
if (inString) {
|
|
872
|
+
if (ch === "'") if (s[i + 1] === "'") i++;
|
|
873
|
+
else inString = false;
|
|
874
|
+
continue;
|
|
875
|
+
}
|
|
876
|
+
if (ch === "'") {
|
|
877
|
+
inString = true;
|
|
878
|
+
continue;
|
|
879
|
+
}
|
|
880
|
+
if (ch === "(") depth++;
|
|
881
|
+
else if (ch === ")") {
|
|
882
|
+
depth--;
|
|
883
|
+
if (depth === 0 && i < s.length - 1) {
|
|
884
|
+
wraps = false;
|
|
885
|
+
break;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
if (!wraps) return s;
|
|
890
|
+
s = s.slice(1, -1).trim();
|
|
891
|
+
}
|
|
892
|
+
}
|
|
692
893
|
function sqlToPolicy(sql) {
|
|
693
|
-
const trimmed = sql.trim();
|
|
894
|
+
const trimmed = stripOuterParens(sql.trim());
|
|
694
895
|
if (trimmed.toLowerCase() === "true") return policy.true();
|
|
695
896
|
if (trimmed.toLowerCase() === "false") return policy.false();
|
|
696
897
|
const overlapMatch = trimmed.match(/^string_to_array\s*\(\s*auth\.roles\(\)\s*,\s*','\s*\)\s*&&\s*ARRAY\s*\[(.+)\]$/i);
|
|
@@ -703,14 +904,10 @@ function sqlToPolicy(sql) {
|
|
|
703
904
|
const roles = containMatch[1].split(",").map((s) => s.trim().replace(/^'|'$/g, ""));
|
|
704
905
|
return policy.rolesContain(roles);
|
|
705
906
|
}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
if (trimmed.toUpperCase().includes(" AND ")) {
|
|
711
|
-
const parts = trimmed.split(/ AND /i);
|
|
712
|
-
return policy.and(...parts.map(sqlToPolicy));
|
|
713
|
-
}
|
|
907
|
+
const orParts = splitTopLevel(trimmed, "OR");
|
|
908
|
+
if (orParts) return policy.or(...orParts.map(sqlToPolicy));
|
|
909
|
+
const andParts = splitTopLevel(trimmed, "AND");
|
|
910
|
+
if (andParts) return policy.and(...andParts.map(sqlToPolicy));
|
|
714
911
|
const match = trimmed.match(/^(.+?)\s*(!?=)\s*(.+)$/);
|
|
715
912
|
if (match) {
|
|
716
913
|
const [, leftStr, op, rightStr] = match;
|
|
@@ -720,6 +917,77 @@ function sqlToPolicy(sql) {
|
|
|
720
917
|
}
|
|
721
918
|
return policy.raw(sql);
|
|
722
919
|
}
|
|
920
|
+
/**
|
|
921
|
+
* Literals from other BaaS platforms that people compare `auth.uid()` against
|
|
922
|
+
* out of habit. Mirrors the driver's `FOREIGN_CONVENTION_ROLES` guard on
|
|
923
|
+
* `pgRoles`, one surface over: the same muscle memory inside a `using:` string
|
|
924
|
+
* is the more dangerous spelling, because it inverts a rule instead of
|
|
925
|
+
* emptying a table.
|
|
926
|
+
*/
|
|
927
|
+
var FOREIGN_CONVENTION_UIDS = {
|
|
928
|
+
anon: "Supabase",
|
|
929
|
+
authenticated: "Supabase",
|
|
930
|
+
service_role: "Supabase"
|
|
931
|
+
};
|
|
932
|
+
/** `auth.uid() IS NOT NULL` in raw SQL, the clause that is always true. */
|
|
933
|
+
var UID_NOT_NULL = /auth\.uid\(\)\s+IS\s+NOT\s+NULL/i;
|
|
934
|
+
/**
|
|
935
|
+
* Find clauses that read as "signed-in users only" but admit anonymous callers.
|
|
936
|
+
*
|
|
937
|
+
* Both spellings come from the same place — Supabase, where `auth.uid()` really
|
|
938
|
+
* is NULL for an anonymous request. Rebase substitutes
|
|
939
|
+
* {@link ANONYMOUS_USER_ID} instead (a blank id would read back as NULL, which
|
|
940
|
+
* is how the trusted *server* context is recognised), so:
|
|
941
|
+
*
|
|
942
|
+
* - `auth.uid() IS NOT NULL` is a tautology on the user path, and
|
|
943
|
+
* - `auth.uid() != 'anon'` compares against a string no caller ever has.
|
|
944
|
+
*
|
|
945
|
+
* Either one turns a lockdown into a full grant, and neither looks wrong. No
|
|
946
|
+
* real user id is ever one of these literals, and a user-context request is
|
|
947
|
+
* never NULL, so a match is always a mistake rather than a deliberate check.
|
|
948
|
+
*
|
|
949
|
+
* Structured expressions are checked too, not just parsed SQL: `policy.compare`
|
|
950
|
+
* can spell the same mistake.
|
|
951
|
+
*/
|
|
952
|
+
function findAnonymousGrants(expr) {
|
|
953
|
+
const found = [];
|
|
954
|
+
const visit = (e) => {
|
|
955
|
+
switch (e.kind) {
|
|
956
|
+
case "and":
|
|
957
|
+
case "or":
|
|
958
|
+
e.operands.forEach(visit);
|
|
959
|
+
return;
|
|
960
|
+
case "not":
|
|
961
|
+
visit(e.operand);
|
|
962
|
+
return;
|
|
963
|
+
case "existsIn":
|
|
964
|
+
visit(e.where);
|
|
965
|
+
return;
|
|
966
|
+
case "raw":
|
|
967
|
+
if (UID_NOT_NULL.test(e.sql)) found.push({
|
|
968
|
+
pattern: "uid-not-null",
|
|
969
|
+
detail: e.sql,
|
|
970
|
+
explanation: `\`auth.uid() IS NOT NULL\` is true for every request that came from a client, including anonymous ones — they carry '${ANONYMOUS_USER_ID}', not NULL. Use \`condition: policy.authenticated()\` to mean "signed in".`
|
|
971
|
+
});
|
|
972
|
+
return;
|
|
973
|
+
case "compare": {
|
|
974
|
+
const literal = [e.left, e.right].find((o) => o.kind === "literal");
|
|
975
|
+
if (!(e.left.kind === "authUid" || e.right.kind === "authUid") || typeof literal?.value !== "string") return;
|
|
976
|
+
const platform = FOREIGN_CONVENTION_UIDS[literal.value];
|
|
977
|
+
if (!platform) return;
|
|
978
|
+
found.push({
|
|
979
|
+
pattern: "foreign-uid-literal",
|
|
980
|
+
detail: literal.value,
|
|
981
|
+
explanation: `'${literal.value}' is a ${platform} convention. Rebase reports an anonymous request as '${ANONYMOUS_USER_ID}', so comparing against '${literal.value}' passes for every caller. Use \`condition: policy.authenticated()\` to mean "signed in".`
|
|
982
|
+
});
|
|
983
|
+
return;
|
|
984
|
+
}
|
|
985
|
+
default: return;
|
|
986
|
+
}
|
|
987
|
+
};
|
|
988
|
+
visit(expr);
|
|
989
|
+
return found;
|
|
990
|
+
}
|
|
723
991
|
function parseOperand(str) {
|
|
724
992
|
if (/current_setting\s*\(\s*'app\.user_id'\s*\)/i.test(str) || /auth\.uid\(\)/i.test(str)) return policy.authUid();
|
|
725
993
|
const stringMatch = str.match(/^'(.+)'$/);
|
|
@@ -780,22 +1048,58 @@ function withRoles(base, rule) {
|
|
|
780
1048
|
* {@link evaluatePolicy}); the Postgres schema generators call it so that DDL
|
|
781
1049
|
* and the admin UI derive from the exact same expression.
|
|
782
1050
|
*/
|
|
783
|
-
function policyToPostgres(expr, collection) {
|
|
1051
|
+
function policyToPostgres(expr, collection, options) {
|
|
1052
|
+
return compile(expr, {
|
|
1053
|
+
fieldCollection: collection,
|
|
1054
|
+
fieldPrefix: "",
|
|
1055
|
+
outerCollection: collection,
|
|
1056
|
+
outerPrefix: "",
|
|
1057
|
+
resolveCollection: options?.resolveCollection,
|
|
1058
|
+
alias: { n: 0 }
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
function compile(expr, scope) {
|
|
784
1062
|
switch (expr.kind) {
|
|
785
1063
|
case "true": return "true";
|
|
786
1064
|
case "false": return "false";
|
|
787
|
-
case "and": return expr.operands.length === 0 ? "true" : expr.operands.map((o) => `(${
|
|
788
|
-
case "or": return expr.operands.length === 0 ? "false" : expr.operands.map((o) => `(${
|
|
789
|
-
case "not":
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
1065
|
+
case "and": return expr.operands.length === 0 ? "true" : expr.operands.map((o) => `(${compile(o, scope)})`).join(" AND ");
|
|
1066
|
+
case "or": return expr.operands.length === 0 ? "false" : expr.operands.map((o) => `(${compile(o, scope)})`).join(" OR ");
|
|
1067
|
+
case "not": return `NOT (${compile(expr.operand, scope)})`;
|
|
1068
|
+
case "compare": {
|
|
1069
|
+
const castForAuthUid = (operand, sqlText, other) => other.kind === "authUid" && (operand.kind === "field" || operand.kind === "outerField") ? `(${sqlText})::text` : sqlText;
|
|
1070
|
+
const leftSql = castForAuthUid(expr.left, operandToSql(expr.left, scope), expr.right);
|
|
1071
|
+
const rightSql = castForAuthUid(expr.right, operandToSql(expr.right, scope), expr.left);
|
|
1072
|
+
return `${leftSql} ${COMPARE_SQL[expr.op]} ${rightSql}`;
|
|
1073
|
+
}
|
|
793
1074
|
case "rolesOverlap": return `string_to_array(auth.roles(), ',') && ${rolesArraySql(expr.roles)}`;
|
|
794
1075
|
case "rolesContain": return `string_to_array(auth.roles(), ',') @> ${rolesArraySql(expr.roles)}`;
|
|
795
|
-
case "authenticated": return
|
|
796
|
-
case "
|
|
1076
|
+
case "authenticated": return `auth.uid() IS NOT NULL AND auth.uid() <> ${quoteLiteral(ANONYMOUS_USER_ID)}`;
|
|
1077
|
+
case "serverContext": return "auth.uid() IS NULL";
|
|
1078
|
+
case "existsIn": return compileExistsIn(expr, scope);
|
|
1079
|
+
case "raw": return expr.sql.replace(/\{(\w+)\}/g, (_, col) => `${outerQualifier(scope)}${resolveColumnName(col, scope.outerCollection)}`);
|
|
797
1080
|
}
|
|
798
1081
|
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Compiles `existsIn` to a correlated `EXISTS (SELECT 1 FROM <join> WHERE ...)`.
|
|
1084
|
+
* Inside the subquery, `field` operands bind to the aliased join table and
|
|
1085
|
+
* `outerField` operands bind to the (table-qualified) outer RLS row.
|
|
1086
|
+
*/
|
|
1087
|
+
function compileExistsIn(expr, scope) {
|
|
1088
|
+
const join = scope.resolveCollection?.(expr.collection);
|
|
1089
|
+
const joinTable = join ? getTableName(join) : toSnakeCase(expr.collection);
|
|
1090
|
+
const joinSchema = schemaOf(join) ?? schemaOf(scope.outerCollection) ?? "public";
|
|
1091
|
+
const alias = `_ex${scope.alias.n++}`;
|
|
1092
|
+
const outerPrefix = outerQualifier(scope);
|
|
1093
|
+
const innerScope = {
|
|
1094
|
+
fieldCollection: join,
|
|
1095
|
+
fieldPrefix: `"${alias}".`,
|
|
1096
|
+
outerCollection: scope.outerCollection,
|
|
1097
|
+
outerPrefix,
|
|
1098
|
+
resolveCollection: scope.resolveCollection,
|
|
1099
|
+
alias: scope.alias
|
|
1100
|
+
};
|
|
1101
|
+
return `EXISTS (SELECT 1 FROM "${joinSchema}"."${joinTable}" "${alias}" WHERE ${compile(expr.where, innerScope)})`;
|
|
1102
|
+
}
|
|
799
1103
|
var COMPARE_SQL = {
|
|
800
1104
|
eq: "=",
|
|
801
1105
|
neq: "!=",
|
|
@@ -804,14 +1108,27 @@ var COMPARE_SQL = {
|
|
|
804
1108
|
gt: ">",
|
|
805
1109
|
gte: ">="
|
|
806
1110
|
};
|
|
807
|
-
function operandToSql(operand,
|
|
1111
|
+
function operandToSql(operand, scope) {
|
|
808
1112
|
switch (operand.kind) {
|
|
809
|
-
case "field": return resolveColumnName(operand.name,
|
|
1113
|
+
case "field": return `${scope.fieldPrefix}${resolveColumnName(operand.name, scope.fieldCollection)}`;
|
|
1114
|
+
case "outerField": return `${scope.outerPrefix}${resolveColumnName(operand.name, scope.outerCollection)}`;
|
|
810
1115
|
case "literal": return quoteLiteral(operand.value);
|
|
811
1116
|
case "authUid": return "auth.uid()";
|
|
812
1117
|
case "authRoles": return "string_to_array(auth.roles(), ',')";
|
|
813
1118
|
}
|
|
814
1119
|
}
|
|
1120
|
+
/**
|
|
1121
|
+
* SQL prefix that qualifies a column of the outer RLS row (`"schema"."table".`),
|
|
1122
|
+
* or `""` when the collection is unknown.
|
|
1123
|
+
*/
|
|
1124
|
+
function outerQualifier(scope) {
|
|
1125
|
+
const table = scope.outerCollection ? getTableName(scope.outerCollection) : void 0;
|
|
1126
|
+
if (!table) return "";
|
|
1127
|
+
return `"${schemaOf(scope.outerCollection) ?? "public"}"."${table}".`;
|
|
1128
|
+
}
|
|
1129
|
+
function schemaOf(collection) {
|
|
1130
|
+
return collection?.schema || void 0;
|
|
1131
|
+
}
|
|
815
1132
|
function resolveColumnName(propName, collection) {
|
|
816
1133
|
const prop = collection?.properties?.[propName];
|
|
817
1134
|
if (prop && "columnName" in prop && typeof prop.columnName === "string") return prop.columnName;
|
|
@@ -853,7 +1170,9 @@ function evaluatePolicy(expr, ctx) {
|
|
|
853
1170
|
const userRoles = ctx.roles ?? [];
|
|
854
1171
|
return expr.roles.every((r) => r === "public" || userRoles.includes(r));
|
|
855
1172
|
}
|
|
856
|
-
case "authenticated": return ctx.uid != null;
|
|
1173
|
+
case "authenticated": return ctx.uid != null && ctx.uid !== ANONYMOUS_USER_ID;
|
|
1174
|
+
case "serverContext": return false;
|
|
1175
|
+
case "existsIn": return "unknown";
|
|
857
1176
|
case "raw": return "unknown";
|
|
858
1177
|
}
|
|
859
1178
|
}
|
|
@@ -879,7 +1198,7 @@ function resolveOperand(operand, ctx) {
|
|
|
879
1198
|
};
|
|
880
1199
|
case "authUid": return {
|
|
881
1200
|
known: true,
|
|
882
|
-
value: ctx.uid ??
|
|
1201
|
+
value: ctx.uid ?? ANONYMOUS_USER_ID
|
|
883
1202
|
};
|
|
884
1203
|
case "authRoles": return {
|
|
885
1204
|
known: true,
|
|
@@ -891,6 +1210,7 @@ function resolveOperand(operand, ctx) {
|
|
|
891
1210
|
known: true,
|
|
892
1211
|
value: ctx.entity.values[operand.name]
|
|
893
1212
|
};
|
|
1213
|
+
case "outerField": return { known: false };
|
|
894
1214
|
}
|
|
895
1215
|
}
|
|
896
1216
|
function evaluateCompare(op, left, right, ctx) {
|
|
@@ -1102,7 +1422,7 @@ function resolveCollectionPathIds(path, allCollections) {
|
|
|
1102
1422
|
} else {
|
|
1103
1423
|
entityId = remainingPath;
|
|
1104
1424
|
remainingPath = "";
|
|
1105
|
-
console.warn(`resolveCollectionPathIds: Path seems to end with
|
|
1425
|
+
console.warn(`resolveCollectionPathIds: Path seems to end with a entity ID "${entityId}" instead of a collection segment in original path "${path}". This might indicate an invalid input path.`);
|
|
1106
1426
|
}
|
|
1107
1427
|
resolvedPathParts.push(entityId);
|
|
1108
1428
|
currentCollections = getSubcollections(foundCollection);
|
|
@@ -1258,9 +1578,12 @@ function getParentReferencesFromPath(props) {
|
|
|
1258
1578
|
//#endregion
|
|
1259
1579
|
//#region src/util/builders.ts
|
|
1260
1580
|
/**
|
|
1261
|
-
*
|
|
1262
|
-
*
|
|
1263
|
-
*
|
|
1581
|
+
* @deprecated Use {@link defineCollection} instead — it infers property
|
|
1582
|
+
* types automatically (autocomplete on `titleProperty`, `sort`,
|
|
1583
|
+
* `propertiesOrder`, callbacks) without manual generics.
|
|
1584
|
+
* `buildCollection` is kept for FireCMS migration compatibility and will
|
|
1585
|
+
* be removed before 1.0.
|
|
1586
|
+
*
|
|
1264
1587
|
* @group Builder
|
|
1265
1588
|
*/
|
|
1266
1589
|
function buildCollection(collection) {
|
|
@@ -1274,68 +1597,16 @@ function defineCollection(collection) {
|
|
|
1274
1597
|
return collection;
|
|
1275
1598
|
}
|
|
1276
1599
|
/**
|
|
1277
|
-
*
|
|
1278
|
-
*
|
|
1279
|
-
*
|
|
1600
|
+
* @deprecated Use plain typed property objects with {@link defineCollection}
|
|
1601
|
+
* instead — `defineCollection` infers property types automatically, making
|
|
1602
|
+
* this wrapper unnecessary. `buildProperty` is kept for FireCMS migration
|
|
1603
|
+
* compatibility and will be removed before 1.0.
|
|
1604
|
+
*
|
|
1280
1605
|
* @group Builder
|
|
1281
1606
|
*/
|
|
1282
1607
|
function buildProperty(property) {
|
|
1283
1608
|
return property;
|
|
1284
1609
|
}
|
|
1285
|
-
/**
|
|
1286
|
-
* Identity function we use to defeat the type system of Typescript and preserve
|
|
1287
|
-
* the properties keys.
|
|
1288
|
-
* @param properties
|
|
1289
|
-
* @group Builder
|
|
1290
|
-
*/
|
|
1291
|
-
function buildProperties(properties) {
|
|
1292
|
-
return properties;
|
|
1293
|
-
}
|
|
1294
|
-
/**
|
|
1295
|
-
* Identity function we use to defeat the type system of Typescript and preserve
|
|
1296
|
-
* the properties keys.
|
|
1297
|
-
* @param propertiesOrBuilder
|
|
1298
|
-
* @group Builder
|
|
1299
|
-
*/
|
|
1300
|
-
function buildPropertiesOrBuilder(propertiesOrBuilder) {
|
|
1301
|
-
return propertiesOrBuilder;
|
|
1302
|
-
}
|
|
1303
|
-
/**
|
|
1304
|
-
* Identity function we use to defeat the type system of Typescript and preserve
|
|
1305
|
-
* the properties keys.
|
|
1306
|
-
* @param enumValues
|
|
1307
|
-
* @group Builder
|
|
1308
|
-
*/
|
|
1309
|
-
function buildEnum(enumValues) {
|
|
1310
|
-
return enumValues;
|
|
1311
|
-
}
|
|
1312
|
-
/**
|
|
1313
|
-
* Identity function we use to defeat the type system of Typescript and preserve
|
|
1314
|
-
* the properties keys.
|
|
1315
|
-
* @param enumValueConfig
|
|
1316
|
-
* @group Builder
|
|
1317
|
-
*/
|
|
1318
|
-
function buildEnumValueConfig(enumValueConfig) {
|
|
1319
|
-
return enumValueConfig;
|
|
1320
|
-
}
|
|
1321
|
-
/**
|
|
1322
|
-
* Identity function we use to defeat the type system of Typescript and preserve
|
|
1323
|
-
* the properties keys.
|
|
1324
|
-
* @param callbacks
|
|
1325
|
-
* @group Builder
|
|
1326
|
-
*/
|
|
1327
|
-
function buildEntityCallbacks(callbacks) {
|
|
1328
|
-
return callbacks;
|
|
1329
|
-
}
|
|
1330
|
-
/**
|
|
1331
|
-
* Identity function we use to defeat the type system of Typescript and build
|
|
1332
|
-
* additional field delegates views with all its properties
|
|
1333
|
-
* @param additionalFieldDelegate
|
|
1334
|
-
* @group Builder
|
|
1335
|
-
*/
|
|
1336
|
-
function buildAdditionalFieldDelegate(additionalFieldDelegate) {
|
|
1337
|
-
return additionalFieldDelegate;
|
|
1338
|
-
}
|
|
1339
1610
|
//#endregion
|
|
1340
1611
|
//#region src/util/storage.ts
|
|
1341
1612
|
/**
|
|
@@ -1471,16 +1742,17 @@ async function processProperties(properties, values, previousValues, propsContex
|
|
|
1471
1742
|
}
|
|
1472
1743
|
/**
|
|
1473
1744
|
* Helper function to extract field-level PropertyCallbacks from a properties schema
|
|
1474
|
-
* and wrap them into an
|
|
1745
|
+
* and wrap them into an CollectionCallbacks object recursively.
|
|
1475
1746
|
*/
|
|
1476
1747
|
var buildPropertyCallbacks = (properties) => {
|
|
1477
1748
|
if (!properties) return void 0;
|
|
1478
1749
|
const propertyCallbacks = {};
|
|
1479
1750
|
if (hasPropertyCallbacks(properties, "afterRead")) propertyCallbacks.afterRead = async (props) => {
|
|
1480
|
-
const
|
|
1751
|
+
const row = props.row;
|
|
1752
|
+
const processedValues = await processProperties(properties, row, row, props, "afterRead");
|
|
1481
1753
|
return {
|
|
1482
|
-
...props.
|
|
1483
|
-
|
|
1754
|
+
...props.row,
|
|
1755
|
+
...processedValues
|
|
1484
1756
|
};
|
|
1485
1757
|
};
|
|
1486
1758
|
if (hasPropertyCallbacks(properties, "beforeSave")) propertyCallbacks.beforeSave = async (props) => {
|
|
@@ -1489,6 +1761,323 @@ var buildPropertyCallbacks = (properties) => {
|
|
|
1489
1761
|
return Object.keys(propertyCallbacks).length > 0 ? propertyCallbacks : void 0;
|
|
1490
1762
|
};
|
|
1491
1763
|
//#endregion
|
|
1764
|
+
//#region src/util/auth-default-policies.ts
|
|
1765
|
+
/**
|
|
1766
|
+
* Default RLS policies injected by the schema generator.
|
|
1767
|
+
*
|
|
1768
|
+
* Rebase's enforcement model is unified: authenticated (user-context) requests
|
|
1769
|
+
* run under the restricted `rebase_user` role, so Postgres RLS binds *every*
|
|
1770
|
+
* statement — reads and writes. A collection's `securityRules` are the whole
|
|
1771
|
+
* authorization model. The server context (auth flows, migrations,
|
|
1772
|
+
* `dataAsAdmin`) runs as the owner and bypasses RLS.
|
|
1773
|
+
*
|
|
1774
|
+
* Because RLS default-denies, every collection is **locked by default**: with
|
|
1775
|
+
* no rules, only the server context and admins can touch it. The generator
|
|
1776
|
+
* injects that safe baseline:
|
|
1777
|
+
*
|
|
1778
|
+
* **For every collection**
|
|
1779
|
+
* 1. A permissive **server-or-admin SELECT** grant.
|
|
1780
|
+
* 2. A permissive **server-or-admin write** grant (insert/update/delete).
|
|
1781
|
+
*
|
|
1782
|
+
* Author `securityRules` are permissive and OR together, so explicit rules only
|
|
1783
|
+
* *broaden* access from this locked baseline (e.g. "users read/write their own
|
|
1784
|
+
* rows").
|
|
1785
|
+
*
|
|
1786
|
+
* **For auth collections additionally**
|
|
1787
|
+
* 3. A permissive **self SELECT** grant (`id = auth.uid()`), so users can read
|
|
1788
|
+
* their own row (profile, session bootstrap) without every app re-declaring
|
|
1789
|
+
* it.
|
|
1790
|
+
* 4. A **restrictive** admin write gate. Restrictive policies are AND'd with
|
|
1791
|
+
* every other policy, so a write is rejected unless the caller is an admin
|
|
1792
|
+
* (or the server context) — even if the author also wrote a permissive rule
|
|
1793
|
+
* such as "a user may edit their own row". Without this, a permissive owner
|
|
1794
|
+
* rule would let a user change their own `roles`.
|
|
1795
|
+
*
|
|
1796
|
+
* The server context is recognised as `auth.uid() IS NULL` (`policy.serverContext()`)
|
|
1797
|
+
* — the built-in flows that run without a user (signup, migrations) set no user
|
|
1798
|
+
* GUC — which also lets the owner connection satisfy these policies even under
|
|
1799
|
+
* FORCE RLS. A *user* request never reaches that state: an anonymous one carries
|
|
1800
|
+
* `ANONYMOUS_USER_ID`, precisely so it cannot pass for the server here.
|
|
1801
|
+
*
|
|
1802
|
+
* Opt out with `disableDefaultPolicies: true` to take full responsibility for
|
|
1803
|
+
* the collection's RLS.
|
|
1804
|
+
*/
|
|
1805
|
+
var SERVER_OR_ADMIN_EXPR$1 = policy.or(policy.serverContext(), policy.rolesOverlap(["admin"]));
|
|
1806
|
+
/** Write operations that must be admin-gated by default on auth collections. */
|
|
1807
|
+
var DEFAULT_GUARDED_OPS = [
|
|
1808
|
+
"insert",
|
|
1809
|
+
"update",
|
|
1810
|
+
"delete"
|
|
1811
|
+
];
|
|
1812
|
+
/** Whether a collection is flagged as an authentication collection. */
|
|
1813
|
+
function isAuthCollection(collection) {
|
|
1814
|
+
const auth = collection.auth;
|
|
1815
|
+
return auth === true || typeof auth === "object" && auth?.enabled === true;
|
|
1816
|
+
}
|
|
1817
|
+
/** The property marked as the row id (falls back to `id`). */
|
|
1818
|
+
function getIdPropertyName$1(collection) {
|
|
1819
|
+
for (const [name, prop] of Object.entries(collection.properties ?? {})) if (prop && typeof prop === "object" && "isId" in prop && prop.isId) return name;
|
|
1820
|
+
return "id";
|
|
1821
|
+
}
|
|
1822
|
+
/**
|
|
1823
|
+
* Returns the security rules that should be applied to a collection: the
|
|
1824
|
+
* author's explicit `securityRules` plus the framework defaults described in
|
|
1825
|
+
* the module doc (baseline server/admin read for all collections; self-read
|
|
1826
|
+
* and the admin write gate for auth collections).
|
|
1827
|
+
*
|
|
1828
|
+
* Collections that opt out via `disableDefaultPolicies` are returned unchanged.
|
|
1829
|
+
*/
|
|
1830
|
+
function getEffectiveSecurityRules(collection) {
|
|
1831
|
+
const explicit = [...(isPostgresCollectionConfig(collection) ? collection.securityRules : void 0) ?? []];
|
|
1832
|
+
if (collection.disableDefaultPolicies) return explicit;
|
|
1833
|
+
const tableName = getTableName(collection);
|
|
1834
|
+
const injected = [];
|
|
1835
|
+
injected.push({
|
|
1836
|
+
name: `${tableName}_default_admin_read`,
|
|
1837
|
+
operations: ["select"],
|
|
1838
|
+
condition: SERVER_OR_ADMIN_EXPR$1
|
|
1839
|
+
});
|
|
1840
|
+
injected.push({
|
|
1841
|
+
name: `${tableName}_default_admin_write`,
|
|
1842
|
+
operations: [...DEFAULT_GUARDED_OPS],
|
|
1843
|
+
condition: SERVER_OR_ADMIN_EXPR$1,
|
|
1844
|
+
check: SERVER_OR_ADMIN_EXPR$1
|
|
1845
|
+
});
|
|
1846
|
+
if (isAuthCollection(collection)) {
|
|
1847
|
+
injected.push({
|
|
1848
|
+
name: `${tableName}_default_self_read`,
|
|
1849
|
+
operations: ["select"],
|
|
1850
|
+
condition: policy.compare(policy.field(getIdPropertyName$1(collection)), "eq", policy.authUid())
|
|
1851
|
+
});
|
|
1852
|
+
injected.push({
|
|
1853
|
+
name: `${tableName}_require_admin_write`,
|
|
1854
|
+
mode: "restrictive",
|
|
1855
|
+
operations: [...DEFAULT_GUARDED_OPS],
|
|
1856
|
+
condition: SERVER_OR_ADMIN_EXPR$1,
|
|
1857
|
+
check: SERVER_OR_ADMIN_EXPR$1
|
|
1858
|
+
});
|
|
1859
|
+
}
|
|
1860
|
+
return [...explicit, ...injected];
|
|
1861
|
+
}
|
|
1862
|
+
/**
|
|
1863
|
+
* The framework defaults that {@link getEffectiveSecurityRules} would add to a
|
|
1864
|
+
* collection, without the author's own rules.
|
|
1865
|
+
*
|
|
1866
|
+
* These policies appear in the database under names the author never wrote, and
|
|
1867
|
+
* a permissive policy ORs with every other permissive policy — so someone
|
|
1868
|
+
* reading their `securityRules` and then the real ACL sees more access than they
|
|
1869
|
+
* declared. Dropping them by hand does nothing either: `db push` is declarative,
|
|
1870
|
+
* so the next push asserts them again. Callers use this to say, in the generated
|
|
1871
|
+
* DDL, which policies are injected and how to take them off.
|
|
1872
|
+
*/
|
|
1873
|
+
function getInjectedSecurityRules(collection) {
|
|
1874
|
+
if (collection.disableDefaultPolicies) return [];
|
|
1875
|
+
const explicitCount = ((isPostgresCollectionConfig(collection) ? collection.securityRules : void 0) ?? []).length;
|
|
1876
|
+
return getEffectiveSecurityRules(collection).slice(explicitCount);
|
|
1877
|
+
}
|
|
1878
|
+
//#endregion
|
|
1879
|
+
//#region src/util/junction-policies.ts
|
|
1880
|
+
var SERVER_OR_ADMIN_EXPR = policy.or(policy.serverContext(), policy.rolesOverlap(["admin"]));
|
|
1881
|
+
/**
|
|
1882
|
+
* Walk every collection's resolved relations and aggregate the junction tables
|
|
1883
|
+
* they declare. Two collections may declare the same junction from opposite
|
|
1884
|
+
* sides (posts→tags and tags→posts through `posts_tags`); both become
|
|
1885
|
+
* `declaringSides` of one spec, so derived write grants consider both.
|
|
1886
|
+
*/
|
|
1887
|
+
function resolveJunctionSpecs(collections) {
|
|
1888
|
+
const specs = /* @__PURE__ */ new Map();
|
|
1889
|
+
for (const collection of collections) {
|
|
1890
|
+
const resolved = resolveCollectionRelations(collection);
|
|
1891
|
+
for (const relation of Object.values(resolved)) {
|
|
1892
|
+
if (!relation.through) continue;
|
|
1893
|
+
const targetCollection = typeof relation.target === "function" ? relation.target() : void 0;
|
|
1894
|
+
if (!targetCollection) continue;
|
|
1895
|
+
const rawName = relation.through.table;
|
|
1896
|
+
const table = rawName.includes(".") ? rawName.split(".").pop() : rawName;
|
|
1897
|
+
const schema = "public";
|
|
1898
|
+
const source = {
|
|
1899
|
+
collection,
|
|
1900
|
+
junctionColumn: relation.through.sourceColumn,
|
|
1901
|
+
relation
|
|
1902
|
+
};
|
|
1903
|
+
const target = {
|
|
1904
|
+
collection: targetCollection,
|
|
1905
|
+
junctionColumn: relation.through.targetColumn
|
|
1906
|
+
};
|
|
1907
|
+
const existing = specs.get(table);
|
|
1908
|
+
if (!existing) specs.set(table, {
|
|
1909
|
+
table,
|
|
1910
|
+
schema,
|
|
1911
|
+
endpoints: [source, target],
|
|
1912
|
+
declaringSides: [source]
|
|
1913
|
+
});
|
|
1914
|
+
else if (!existing.declaringSides.some((s) => s.collection === collection)) existing.declaringSides.push(source);
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
return specs;
|
|
1918
|
+
}
|
|
1919
|
+
/**
|
|
1920
|
+
* A synthetic CollectionConfig standing in for the junction during policy
|
|
1921
|
+
* compilation and naming. Its two FK columns carry explicit `columnName`s so
|
|
1922
|
+
* `outerField` operands resolve to the exact columns the CREATE TABLE emitted,
|
|
1923
|
+
* whatever their casing.
|
|
1924
|
+
*/
|
|
1925
|
+
function getJunctionCollectionConfig(spec) {
|
|
1926
|
+
const properties = {};
|
|
1927
|
+
for (const endpoint of spec.endpoints) properties[endpoint.junctionColumn] = {
|
|
1928
|
+
type: "string",
|
|
1929
|
+
columnName: endpoint.junctionColumn
|
|
1930
|
+
};
|
|
1931
|
+
return {
|
|
1932
|
+
slug: spec.table,
|
|
1933
|
+
name: spec.table,
|
|
1934
|
+
table: spec.table,
|
|
1935
|
+
schema: spec.schema,
|
|
1936
|
+
properties
|
|
1937
|
+
};
|
|
1938
|
+
}
|
|
1939
|
+
/** The property marked as the row id (falls back to `id`). */
|
|
1940
|
+
function getIdPropertyName(collection) {
|
|
1941
|
+
for (const [name, prop] of Object.entries(collection.properties ?? {})) if (prop && typeof prop === "object" && "isId" in prop && prop.isId) return name;
|
|
1942
|
+
return "id";
|
|
1943
|
+
}
|
|
1944
|
+
/** `EXISTS (SELECT 1 FROM endpoint WHERE endpoint.pk = junction.fk [AND extra])`. */
|
|
1945
|
+
function existsEndpoint(endpoint, extra) {
|
|
1946
|
+
const correlation = policy.compare(policy.field(getIdPropertyName(endpoint.collection)), "eq", policy.outerField(endpoint.junctionColumn));
|
|
1947
|
+
return policy.existsIn({
|
|
1948
|
+
collection: endpoint.collection.slug,
|
|
1949
|
+
where: extra ? policy.and(correlation, extra) : correlation
|
|
1950
|
+
});
|
|
1951
|
+
}
|
|
1952
|
+
/**
|
|
1953
|
+
* Whether a parent-rule expression keeps its meaning when moved inside the
|
|
1954
|
+
* junction's `EXISTS` subquery — and the re-scoped copy if it does.
|
|
1955
|
+
*
|
|
1956
|
+
* Returns `null` when the rule cannot be embedded faithfully: `raw` SQL
|
|
1957
|
+
* anywhere (its `{column}` placeholders would bind to the junction), or an
|
|
1958
|
+
* `outerField` inside a nested `existsIn` (it would bind to the junction while
|
|
1959
|
+
* the author meant the parent, and no operand can express "the middle scope").
|
|
1960
|
+
* Top-level `outerField`s are rewritten to `field`, which is what they meant.
|
|
1961
|
+
*/
|
|
1962
|
+
function embedParentExpression(expr, depth = 0) {
|
|
1963
|
+
switch (expr.kind) {
|
|
1964
|
+
case "raw": return null;
|
|
1965
|
+
case "and":
|
|
1966
|
+
case "or": {
|
|
1967
|
+
const parts = [];
|
|
1968
|
+
for (const child of expr.operands) {
|
|
1969
|
+
const embedded = embedParentExpression(child, depth);
|
|
1970
|
+
if (!embedded) return null;
|
|
1971
|
+
parts.push(embedded);
|
|
1972
|
+
}
|
|
1973
|
+
return expr.kind === "and" ? policy.and(...parts) : policy.or(...parts);
|
|
1974
|
+
}
|
|
1975
|
+
case "not": {
|
|
1976
|
+
const embedded = embedParentExpression(expr.operand, depth);
|
|
1977
|
+
return embedded ? policy.not(embedded) : null;
|
|
1978
|
+
}
|
|
1979
|
+
case "existsIn": {
|
|
1980
|
+
const where = embedParentExpression(expr.where, depth + 1);
|
|
1981
|
+
return where ? policy.existsIn({
|
|
1982
|
+
collection: expr.collection,
|
|
1983
|
+
where
|
|
1984
|
+
}) : null;
|
|
1985
|
+
}
|
|
1986
|
+
case "compare": {
|
|
1987
|
+
const left = embedOperand(expr.left, depth);
|
|
1988
|
+
const right = embedOperand(expr.right, depth);
|
|
1989
|
+
if (!left || !right) return null;
|
|
1990
|
+
return {
|
|
1991
|
+
...expr,
|
|
1992
|
+
left,
|
|
1993
|
+
right
|
|
1994
|
+
};
|
|
1995
|
+
}
|
|
1996
|
+
default: return expr;
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
/** Re-scope an operand, or return `null` if its binding cannot be preserved. */
|
|
2000
|
+
function embedOperand(operand, depth) {
|
|
2001
|
+
if (operand.kind === "outerField") {
|
|
2002
|
+
if (depth === 0) return policy.field(operand.name);
|
|
2003
|
+
return null;
|
|
2004
|
+
}
|
|
2005
|
+
return operand;
|
|
2006
|
+
}
|
|
2007
|
+
/** Does the rule cover the `update` operation? */
|
|
2008
|
+
function coversUpdate(rule) {
|
|
2009
|
+
return getPolicyOperations(rule).some((op) => op === "update" || op === "all");
|
|
2010
|
+
}
|
|
2011
|
+
/**
|
|
2012
|
+
* The full derived policy set for a junction table: the locked server/admin
|
|
2013
|
+
* baseline, the endpoint-visibility read grant, inherited write grants, and
|
|
2014
|
+
* inherited restrictive gates. Returns `[]` when every declaring collection set
|
|
2015
|
+
* `disableDefaultPolicies` — the junction is then the author's to police, and
|
|
2016
|
+
* stays locked (RLS is still enabled) until they write policies for it.
|
|
2017
|
+
*/
|
|
2018
|
+
function getJunctionSecurityRules(spec) {
|
|
2019
|
+
if (spec.declaringSides.every((side) => side.collection.disableDefaultPolicies)) return [];
|
|
2020
|
+
const rules = [];
|
|
2021
|
+
rules.push({
|
|
2022
|
+
name: `${spec.table}_default_admin_read`,
|
|
2023
|
+
operations: ["select"],
|
|
2024
|
+
condition: SERVER_OR_ADMIN_EXPR
|
|
2025
|
+
});
|
|
2026
|
+
rules.push({
|
|
2027
|
+
name: `${spec.table}_default_admin_write`,
|
|
2028
|
+
operations: [
|
|
2029
|
+
"insert",
|
|
2030
|
+
"update",
|
|
2031
|
+
"delete"
|
|
2032
|
+
],
|
|
2033
|
+
condition: SERVER_OR_ADMIN_EXPR,
|
|
2034
|
+
check: SERVER_OR_ADMIN_EXPR
|
|
2035
|
+
});
|
|
2036
|
+
rules.push({
|
|
2037
|
+
name: `${spec.table}_default_edge_read`,
|
|
2038
|
+
operations: ["select"],
|
|
2039
|
+
condition: policy.and(existsEndpoint(spec.endpoints[0]), existsEndpoint(spec.endpoints[1]))
|
|
2040
|
+
});
|
|
2041
|
+
const writeGrants = [];
|
|
2042
|
+
for (const side of spec.declaringSides) {
|
|
2043
|
+
const updateRules = ((isPostgresCollectionConfig(side.collection) ? side.collection.securityRules : void 0) ?? []).filter(coversUpdate);
|
|
2044
|
+
const permissive = updateRules.filter((r) => r.mode !== "restrictive");
|
|
2045
|
+
const restrictive = updateRules.filter((r) => r.mode === "restrictive");
|
|
2046
|
+
const embeddedGates = [];
|
|
2047
|
+
let gatesEmbeddable = true;
|
|
2048
|
+
for (const gate of restrictive) {
|
|
2049
|
+
const using = securityRuleToConditions(gate).usingExpr;
|
|
2050
|
+
const embedded = using ? embedParentExpression(using) : null;
|
|
2051
|
+
if (!embedded) {
|
|
2052
|
+
gatesEmbeddable = false;
|
|
2053
|
+
break;
|
|
2054
|
+
}
|
|
2055
|
+
embeddedGates.push(embedded);
|
|
2056
|
+
}
|
|
2057
|
+
if (!gatesEmbeddable) continue;
|
|
2058
|
+
const grants = [];
|
|
2059
|
+
for (const rule of permissive) {
|
|
2060
|
+
const using = securityRuleToConditions(rule).usingExpr;
|
|
2061
|
+
const embedded = using ? embedParentExpression(using) : null;
|
|
2062
|
+
if (embedded) grants.push(embedded);
|
|
2063
|
+
}
|
|
2064
|
+
if (grants.length === 0) continue;
|
|
2065
|
+
const condition = embeddedGates.length > 0 ? policy.and(policy.or(...grants), ...embeddedGates) : policy.or(...grants);
|
|
2066
|
+
writeGrants.push(existsEndpoint(side, condition));
|
|
2067
|
+
}
|
|
2068
|
+
if (writeGrants.length > 0) rules.push({
|
|
2069
|
+
name: `${spec.table}_default_edge_write`,
|
|
2070
|
+
operations: [
|
|
2071
|
+
"insert",
|
|
2072
|
+
"update",
|
|
2073
|
+
"delete"
|
|
2074
|
+
],
|
|
2075
|
+
condition: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants),
|
|
2076
|
+
check: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants)
|
|
2077
|
+
});
|
|
2078
|
+
return rules;
|
|
2079
|
+
}
|
|
2080
|
+
//#endregion
|
|
1492
2081
|
//#region src/util/conditions.ts
|
|
1493
2082
|
/**
|
|
1494
2083
|
* Access a nested property from an object via dot notation.
|
|
@@ -1667,6 +2256,84 @@ function applyEnumConditions(enumValues, conditions, context) {
|
|
|
1667
2256
|
return result;
|
|
1668
2257
|
}
|
|
1669
2258
|
//#endregion
|
|
2259
|
+
//#region src/util/filter-operator-resolution.ts
|
|
2260
|
+
/**
|
|
2261
|
+
* Default operators offered per property type, before engine capabilities and
|
|
2262
|
+
* per-property narrowing are applied. These mirror what the built-in filter
|
|
2263
|
+
* fields can render.
|
|
2264
|
+
*/
|
|
2265
|
+
var COMPARISON_OPS = [
|
|
2266
|
+
"==",
|
|
2267
|
+
"!=",
|
|
2268
|
+
">",
|
|
2269
|
+
">=",
|
|
2270
|
+
"<",
|
|
2271
|
+
"<="
|
|
2272
|
+
];
|
|
2273
|
+
var NULL_CHECK_OPS = ["is-null", "is-not-null"];
|
|
2274
|
+
var MEMBERSHIP_OPS = ["in", "not-in"];
|
|
2275
|
+
var PATTERN_OPS = [
|
|
2276
|
+
"like",
|
|
2277
|
+
"ilike",
|
|
2278
|
+
"not-like",
|
|
2279
|
+
"not-ilike"
|
|
2280
|
+
];
|
|
2281
|
+
var DEFAULT_OPS_BY_TYPE = {
|
|
2282
|
+
string: [
|
|
2283
|
+
...COMPARISON_OPS,
|
|
2284
|
+
...MEMBERSHIP_OPS,
|
|
2285
|
+
...PATTERN_OPS,
|
|
2286
|
+
...NULL_CHECK_OPS
|
|
2287
|
+
],
|
|
2288
|
+
number: [
|
|
2289
|
+
...COMPARISON_OPS,
|
|
2290
|
+
...MEMBERSHIP_OPS,
|
|
2291
|
+
...NULL_CHECK_OPS
|
|
2292
|
+
],
|
|
2293
|
+
date: [...COMPARISON_OPS, ...NULL_CHECK_OPS],
|
|
2294
|
+
boolean: [
|
|
2295
|
+
"==",
|
|
2296
|
+
"!=",
|
|
2297
|
+
...NULL_CHECK_OPS
|
|
2298
|
+
],
|
|
2299
|
+
reference: [
|
|
2300
|
+
"==",
|
|
2301
|
+
"!=",
|
|
2302
|
+
...MEMBERSHIP_OPS,
|
|
2303
|
+
...NULL_CHECK_OPS
|
|
2304
|
+
],
|
|
2305
|
+
relation: [
|
|
2306
|
+
"==",
|
|
2307
|
+
"!=",
|
|
2308
|
+
...MEMBERSHIP_OPS,
|
|
2309
|
+
...NULL_CHECK_OPS
|
|
2310
|
+
]
|
|
2311
|
+
};
|
|
2312
|
+
/** Operators offered when the property is an *array of* a filterable type. */
|
|
2313
|
+
var ARRAY_OPS = ["array-contains", "array-contains-any"];
|
|
2314
|
+
/**
|
|
2315
|
+
* Resolve which filter operators the UI should offer for a property.
|
|
2316
|
+
*
|
|
2317
|
+
* The result is the **intersection** of three sets:
|
|
2318
|
+
* 1. what the engine can execute — {@link DataSourceCapabilities.filterOperators}
|
|
2319
|
+
* (e.g. Firestore cannot run the LIKE family);
|
|
2320
|
+
* 2. what makes sense for the property type (e.g. no `>` on booleans);
|
|
2321
|
+
* 3. the developer's optional narrowing — `property.ui.filterOperators`.
|
|
2322
|
+
*
|
|
2323
|
+
* Returns an empty array when the property is not filterable (either by
|
|
2324
|
+
* type, or because the developer disabled it with `filterOperators: []`).
|
|
2325
|
+
*
|
|
2326
|
+
* @group Models
|
|
2327
|
+
*/
|
|
2328
|
+
function resolveFilterOperators({ property, isArray, engine }) {
|
|
2329
|
+
const typeDefaults = isArray ? ARRAY_OPS : DEFAULT_OPS_BY_TYPE[property.type] ?? [];
|
|
2330
|
+
if (typeDefaults.length === 0) return [];
|
|
2331
|
+
const engineOps = new Set(getDataSourceCapabilities(engine).filterOperators ?? ALL_WHERE_FILTER_OPS);
|
|
2332
|
+
const narrowing = property.ui?.filterOperators;
|
|
2333
|
+
const narrowingSet = narrowing !== void 0 ? new Set(narrowing) : void 0;
|
|
2334
|
+
return typeDefaults.filter((op) => engineOps.has(op) && (narrowingSet === void 0 || narrowingSet.has(op)));
|
|
2335
|
+
}
|
|
2336
|
+
//#endregion
|
|
1670
2337
|
//#region src/data/resolveDataSource.ts
|
|
1671
2338
|
/**
|
|
1672
2339
|
* Build a keyed registry from a list of {@link DataSourceDefinition}s.
|
|
@@ -1745,7 +2412,7 @@ var CollectionRegistry = class {
|
|
|
1745
2412
|
rawCollectionsBySlug = /* @__PURE__ */ new Map();
|
|
1746
2413
|
rawRootCollections = [];
|
|
1747
2414
|
cachedRawCollectionsList = null;
|
|
1748
|
-
|
|
2415
|
+
lastRawInputEntity = null;
|
|
1749
2416
|
constructor(collections, dataSources) {
|
|
1750
2417
|
if (dataSources) this.dataSources = dataSources;
|
|
1751
2418
|
if (collections) this.registerMultiple(collections);
|
|
@@ -1775,12 +2442,12 @@ var CollectionRegistry = class {
|
|
|
1775
2442
|
* Returns true if the collections have changed, false otherwise.
|
|
1776
2443
|
*
|
|
1777
2444
|
* Idempotent: compares the raw input (before normalization) against a stored
|
|
1778
|
-
*
|
|
2445
|
+
* entity. Only re-normalizes and re-registers when the raw input actually changed.
|
|
1779
2446
|
* @param collections
|
|
1780
2447
|
*/
|
|
1781
2448
|
registerMultiple(collections) {
|
|
1782
|
-
const
|
|
1783
|
-
if (this.
|
|
2449
|
+
const rawEntity = collections.map((c) => removeFunctions(c));
|
|
2450
|
+
if (this.lastRawInputEntity && deepEqual(this.lastRawInputEntity, rawEntity)) return false;
|
|
1784
2451
|
this.reset();
|
|
1785
2452
|
collections.forEach((c) => {
|
|
1786
2453
|
if (c.slug) this.collectionsBySlug.set(c.slug, c);
|
|
@@ -1804,7 +2471,7 @@ var CollectionRegistry = class {
|
|
|
1804
2471
|
this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));
|
|
1805
2472
|
});
|
|
1806
2473
|
});
|
|
1807
|
-
this.
|
|
2474
|
+
this.lastRawInputEntity = rawEntity;
|
|
1808
2475
|
return true;
|
|
1809
2476
|
}
|
|
1810
2477
|
register(collection, rawCollection) {
|
|
@@ -2096,6 +2763,7 @@ var defaultUsersCollection = defineCollection({
|
|
|
2096
2763
|
name: "Password Hash",
|
|
2097
2764
|
type: "string",
|
|
2098
2765
|
columnName: "password_hash",
|
|
2766
|
+
excludeFromApi: true,
|
|
2099
2767
|
ui: {
|
|
2100
2768
|
hideFromCollection: true,
|
|
2101
2769
|
disabled: { hidden: true }
|
|
@@ -2115,6 +2783,7 @@ var defaultUsersCollection = defineCollection({
|
|
|
2115
2783
|
name: "Email Verification Token",
|
|
2116
2784
|
type: "string",
|
|
2117
2785
|
columnName: "email_verification_token",
|
|
2786
|
+
excludeFromApi: true,
|
|
2118
2787
|
ui: {
|
|
2119
2788
|
hideFromCollection: true,
|
|
2120
2789
|
disabled: { hidden: true }
|
|
@@ -2224,7 +2893,7 @@ var QueryBuilder = class {
|
|
|
2224
2893
|
* client.collection('users').orderBy('createdAt', 'desc').find()
|
|
2225
2894
|
*/
|
|
2226
2895
|
orderBy(column, direction = "asc") {
|
|
2227
|
-
this.params.orderBy =
|
|
2896
|
+
this.params.orderBy = [column, direction];
|
|
2228
2897
|
return this;
|
|
2229
2898
|
}
|
|
2230
2899
|
/**
|
|
@@ -2287,32 +2956,74 @@ var QueryBuilder = class {
|
|
|
2287
2956
|
* PostgREST-style dot-syntax strings (`eq.active`, `gt.18`, `in.(a,b)`).
|
|
2288
2957
|
* Everything else speaks `FilterValues` exclusively.
|
|
2289
2958
|
*
|
|
2959
|
+
* Wire-format values are always strings — the wire format carries no type
|
|
2960
|
+
* metadata, so type coercion is the responsibility of the server-side data
|
|
2961
|
+
* driver which has access to the collection schema.
|
|
2962
|
+
*
|
|
2963
|
+
* Commas inside list values are backslash-escaped (`\,`), and literal
|
|
2964
|
+
* backslashes are escaped as `\\`.
|
|
2965
|
+
*
|
|
2290
2966
|
* @module
|
|
2291
2967
|
*/
|
|
2292
2968
|
/**
|
|
2293
|
-
* Coerce a raw querystring value to its natural JS type.
|
|
2294
|
-
* - `"true"` / `"false"` → boolean
|
|
2295
|
-
* - `"null"` → null
|
|
2296
|
-
* - Numeric strings → number
|
|
2297
|
-
* - Everything else → string (unchanged)
|
|
2298
|
-
*/
|
|
2299
|
-
function coerceValue(raw) {
|
|
2300
|
-
if (raw === "true") return true;
|
|
2301
|
-
if (raw === "false") return false;
|
|
2302
|
-
if (raw === "null") return null;
|
|
2303
|
-
if (raw !== "" && !isNaN(Number(raw))) return Number(raw);
|
|
2304
|
-
return raw;
|
|
2305
|
-
}
|
|
2306
|
-
/**
|
|
2307
2969
|
* Serialize a JS value to its querystring representation.
|
|
2970
|
+
* `null` is serialized as the literal string `"null"`.
|
|
2971
|
+
* Relation values (`EntityRelation` instances or `{ __type: "relation", id, path }`
|
|
2972
|
+
* objects) are serialized as their raw id — the wire format only carries the
|
|
2973
|
+
* value to compare against the FK column.
|
|
2308
2974
|
*/
|
|
2309
2975
|
function stringifyValue(value) {
|
|
2310
2976
|
if (value === null) return "null";
|
|
2311
|
-
|
|
2977
|
+
const relation = normalizeToEntityRelation(value);
|
|
2978
|
+
if (relation) return String(relation.id);
|
|
2312
2979
|
return String(value);
|
|
2313
2980
|
}
|
|
2314
2981
|
/**
|
|
2315
|
-
*
|
|
2982
|
+
* Escape a single list item for the wire format.
|
|
2983
|
+
* `\` → `\\`, `,` → `\,`
|
|
2984
|
+
*/
|
|
2985
|
+
function escapeListItem(value) {
|
|
2986
|
+
return value.replace(/\\/g, "\\\\").replace(/,/g, "\\,");
|
|
2987
|
+
}
|
|
2988
|
+
/**
|
|
2989
|
+
* Unescape a single list item from the wire format.
|
|
2990
|
+
* `\\` → `\`, `\,` → `,`
|
|
2991
|
+
*/
|
|
2992
|
+
function unescapeListItem(value) {
|
|
2993
|
+
let result = "";
|
|
2994
|
+
for (let i = 0; i < value.length; i++) if (value[i] === "\\" && i + 1 < value.length) {
|
|
2995
|
+
result += value[i + 1];
|
|
2996
|
+
i++;
|
|
2997
|
+
} else result += value[i];
|
|
2998
|
+
return result;
|
|
2999
|
+
}
|
|
3000
|
+
/**
|
|
3001
|
+
* Split a parenthesized list string on unescaped commas.
|
|
3002
|
+
* Input is the content between `(` and `)`.
|
|
3003
|
+
*
|
|
3004
|
+
* @example
|
|
3005
|
+
* splitListItems("admin,editor") // ["admin", "editor"]
|
|
3006
|
+
* splitListItems("hello\\, world,foo") // ["hello, world", "foo"]
|
|
3007
|
+
*/
|
|
3008
|
+
function splitListItems(inner) {
|
|
3009
|
+
const items = [];
|
|
3010
|
+
let current = "";
|
|
3011
|
+
for (let i = 0; i < inner.length; i++) if (inner[i] === "\\" && i + 1 < inner.length) {
|
|
3012
|
+
current += inner[i] + inner[i + 1];
|
|
3013
|
+
i++;
|
|
3014
|
+
} else if (inner[i] === ",") {
|
|
3015
|
+
items.push(unescapeListItem(current));
|
|
3016
|
+
current = "";
|
|
3017
|
+
} else current += inner[i];
|
|
3018
|
+
items.push(unescapeListItem(current));
|
|
3019
|
+
return items;
|
|
3020
|
+
}
|
|
3021
|
+
var REST_OP_LOOKUP = REST_TO_CANONICAL;
|
|
3022
|
+
var CANONICAL_OP_LOOKUP = CANONICAL_TO_REST;
|
|
3023
|
+
/**
|
|
3024
|
+
* Serialize a single canonical condition tuple to a PostgREST dot-string.
|
|
3025
|
+
*
|
|
3026
|
+
* Throws `TypeError` if the input is not a valid `[WhereFilterOp, unknown]` tuple.
|
|
2316
3027
|
*
|
|
2317
3028
|
* @example
|
|
2318
3029
|
* serializeTuple(["==", "active"]) // "eq.active"
|
|
@@ -2320,22 +3031,20 @@ function stringifyValue(value) {
|
|
|
2320
3031
|
* serializeTuple([">=", 18]) // "gte.18"
|
|
2321
3032
|
*/
|
|
2322
3033
|
function serializeTuple(tuple) {
|
|
2323
|
-
if (
|
|
2324
|
-
if (tuple.includes(".")) {
|
|
2325
|
-
const dotIndex = tuple.indexOf(".");
|
|
2326
|
-
if (REST_TO_CANONICAL[tuple.substring(0, dotIndex)]) return tuple;
|
|
2327
|
-
}
|
|
2328
|
-
return tuple;
|
|
2329
|
-
}
|
|
2330
|
-
if (!Array.isArray(tuple) || tuple.length !== 2 || typeof tuple[0] !== "string" || !CANONICAL_TO_REST[tuple[0]]) return `eq.${stringifyValue(tuple)}`;
|
|
3034
|
+
if (!Array.isArray(tuple) || tuple.length !== 2) throw new TypeError(`serializeTuple: expected a [WhereFilterOp, value] tuple, got ${JSON.stringify(tuple)}`);
|
|
2331
3035
|
const [op, value] = tuple;
|
|
2332
|
-
|
|
2333
|
-
|
|
3036
|
+
if (typeof op !== "string") throw new TypeError(`serializeTuple: operator must be a string, got ${typeof op}`);
|
|
3037
|
+
const restOp = CANONICAL_OP_LOOKUP[op];
|
|
3038
|
+
if (!restOp) throw new TypeError(`serializeTuple: unknown operator "${op}". Valid operators: ${Object.keys(CANONICAL_TO_REST).join(", ")}`);
|
|
3039
|
+
if (Array.isArray(value)) return `${restOp}.(${value.map((v) => escapeListItem(stringifyValue(v))).join(",")})`;
|
|
2334
3040
|
return `${restOp}.${stringifyValue(value)}`;
|
|
2335
3041
|
}
|
|
2336
3042
|
/**
|
|
2337
|
-
* Convert `FilterValues` to a PostgREST-style
|
|
3043
|
+
* Convert `FilterValues` (or `WireFilterValues`) to a PostgREST-style
|
|
3044
|
+
* querystring record.
|
|
2338
3045
|
*
|
|
3046
|
+
* - Canonical `[WhereFilterOp, value]` tuples are serialized strictly.
|
|
3047
|
+
* - Pre-serialized PostgREST strings (e.g. `"eq.published"`) are passed through.
|
|
2339
3048
|
* - Single conditions produce a string value.
|
|
2340
3049
|
* - Multiple conditions on the same field produce a string array (repeated params).
|
|
2341
3050
|
*
|
|
@@ -2345,11 +3054,19 @@ function serializeTuple(tuple) {
|
|
|
2345
3054
|
*
|
|
2346
3055
|
* serializeFilter({ age: [[">=", 18], ["<", 65]] })
|
|
2347
3056
|
* // → { age: ["gte.18", "lt.65"] }
|
|
3057
|
+
*
|
|
3058
|
+
* // Pre-serialized strings pass through unchanged:
|
|
3059
|
+
* serializeFilter({ status: "eq.published" })
|
|
3060
|
+
* // → { status: "eq.published" }
|
|
2348
3061
|
*/
|
|
2349
3062
|
function serializeFilter(filter) {
|
|
2350
3063
|
const result = {};
|
|
2351
3064
|
for (const [field, condition] of Object.entries(filter)) {
|
|
2352
3065
|
if (condition === void 0) continue;
|
|
3066
|
+
if (typeof condition === "string") {
|
|
3067
|
+
result[field] = condition;
|
|
3068
|
+
continue;
|
|
3069
|
+
}
|
|
2353
3070
|
if (Array.isArray(condition) && condition.length > 0 && Array.isArray(condition[0])) result[field] = condition.map(serializeTuple);
|
|
2354
3071
|
else result[field] = serializeTuple(condition);
|
|
2355
3072
|
}
|
|
@@ -2358,18 +3075,24 @@ function serializeFilter(filter) {
|
|
|
2358
3075
|
/**
|
|
2359
3076
|
* Parse a single PostgREST dot-string into a `[WhereFilterOp, unknown]` tuple.
|
|
2360
3077
|
*
|
|
2361
|
-
*
|
|
3078
|
+
* All values are returned as strings — the wire format carries no type
|
|
3079
|
+
* metadata, so coercion is the data driver's responsibility.
|
|
3080
|
+
*
|
|
3081
|
+
* If the string doesn't match a known operator prefix, it falls back to
|
|
2362
3082
|
* `["==", originalString]` (treating the whole string as an equality value).
|
|
3083
|
+
* This intentional defense handles values like `"user@host.com"` or
|
|
3084
|
+
* `"1.2.3"` that happen to contain dots.
|
|
2363
3085
|
*/
|
|
2364
3086
|
function deserializeSingle(raw) {
|
|
2365
3087
|
const dotIndex = raw.indexOf(".");
|
|
2366
|
-
if (dotIndex === -1) return ["==",
|
|
3088
|
+
if (dotIndex === -1) return ["==", raw];
|
|
2367
3089
|
const prefix = raw.substring(0, dotIndex);
|
|
2368
3090
|
const rest = raw.substring(dotIndex + 1);
|
|
2369
|
-
const canonicalOp =
|
|
3091
|
+
const canonicalOp = REST_OP_LOOKUP[prefix];
|
|
2370
3092
|
if (!canonicalOp) return ["==", raw];
|
|
2371
|
-
if (
|
|
2372
|
-
return [canonicalOp,
|
|
3093
|
+
if (NULL_OPS.has(canonicalOp)) return [canonicalOp, null];
|
|
3094
|
+
if (rest.startsWith("(") && rest.endsWith(")")) return [canonicalOp, splitListItems(rest.slice(1, -1))];
|
|
3095
|
+
return [canonicalOp, rest];
|
|
2373
3096
|
}
|
|
2374
3097
|
/**
|
|
2375
3098
|
* Convert a PostgREST-style querystring record to `FilterValues`.
|
|
@@ -2382,7 +3105,7 @@ function deserializeSingle(raw) {
|
|
|
2382
3105
|
* // → { status: ["==", "active"] }
|
|
2383
3106
|
*
|
|
2384
3107
|
* deserializeFilter({ age: ["gte.18", "lt.65"] })
|
|
2385
|
-
* // → { age: [[">=", 18], ["<", 65]] }
|
|
3108
|
+
* // → { age: [[">=", "18"], ["<", "65"]] }
|
|
2386
3109
|
*/
|
|
2387
3110
|
function deserializeFilter(query) {
|
|
2388
3111
|
const result = {};
|
|
@@ -2421,9 +3144,9 @@ function serializeLogicalCondition(cond) {
|
|
|
2421
3144
|
const inner = (cond.conditions ?? []).map(serializeLogicalCondition).join(",");
|
|
2422
3145
|
return `${cond.type}(${inner})`;
|
|
2423
3146
|
}
|
|
2424
|
-
const restOp =
|
|
3147
|
+
const restOp = CANONICAL_OP_LOOKUP[cond.operator] ?? "eq";
|
|
2425
3148
|
if (Array.isArray(cond.value)) {
|
|
2426
|
-
const items = cond.value.map(stringifyValue).join(",");
|
|
3149
|
+
const items = cond.value.map((v) => escapeListItem(stringifyValue(v))).join(",");
|
|
2427
3150
|
return `${cond.column}.${restOp}.(${items})`;
|
|
2428
3151
|
}
|
|
2429
3152
|
return `${cond.column}.${restOp}.${stringifyValue(cond.value)}`;
|
|
@@ -2471,99 +3194,149 @@ function deserializeLogicalCondition(str) {
|
|
|
2471
3194
|
if (secondDot === -1) return {
|
|
2472
3195
|
column,
|
|
2473
3196
|
operator: "==",
|
|
2474
|
-
value:
|
|
3197
|
+
value: rest
|
|
2475
3198
|
};
|
|
2476
3199
|
const opStr = rest.substring(0, secondDot);
|
|
2477
|
-
|
|
3200
|
+
const valueStr = rest.substring(secondDot + 1);
|
|
2478
3201
|
const operator = toCanonicalOp(opStr) ?? "==";
|
|
2479
3202
|
if (valueStr.startsWith("(") && valueStr.endsWith(")")) return {
|
|
2480
3203
|
column,
|
|
2481
3204
|
operator,
|
|
2482
|
-
value: valueStr.slice(1, -1)
|
|
3205
|
+
value: splitListItems(valueStr.slice(1, -1))
|
|
2483
3206
|
};
|
|
2484
3207
|
return {
|
|
2485
3208
|
column,
|
|
2486
3209
|
operator,
|
|
2487
|
-
value:
|
|
3210
|
+
value: valueStr
|
|
2488
3211
|
};
|
|
2489
3212
|
}
|
|
2490
3213
|
//#endregion
|
|
2491
3214
|
//#region src/data/buildRebaseData.ts
|
|
3215
|
+
function createPrimaryKeyResolver(options) {
|
|
3216
|
+
const cache = /* @__PURE__ */ new Map();
|
|
3217
|
+
const warned = /* @__PURE__ */ new Set();
|
|
3218
|
+
return function primaryKeysFor(slug) {
|
|
3219
|
+
const cached = cache.get(slug);
|
|
3220
|
+
if (cached) return cached;
|
|
3221
|
+
const collection = options?.resolveCollection?.(slug);
|
|
3222
|
+
if (!collection) return [];
|
|
3223
|
+
const keys = resolvePrimaryKeys(collection);
|
|
3224
|
+
if (keys.length > 0) {
|
|
3225
|
+
cache.set(slug, keys);
|
|
3226
|
+
return keys;
|
|
3227
|
+
}
|
|
3228
|
+
if (!warned.has(slug)) {
|
|
3229
|
+
warned.add(slug);
|
|
3230
|
+
console.warn(`[rebase] Collection '${slug}' declares no primary key, so its rows have no address: detail links, caching and relations will not work for it. Mark the key property with \`isId\` in its collection config — the server logs which column to mark at boot, if its schema knows the key.`);
|
|
3231
|
+
}
|
|
3232
|
+
return keys;
|
|
3233
|
+
};
|
|
3234
|
+
}
|
|
2492
3235
|
/**
|
|
2493
|
-
*
|
|
3236
|
+
* Give a flat row the Entity view-model the admin renders.
|
|
3237
|
+
*
|
|
3238
|
+
* The address is *derived here* — it is not a column, and the row it came from
|
|
3239
|
+
* does not contain one. Rows carry exactly what the table has, with the types
|
|
3240
|
+
* Postgres returned; the id is this layer's invention, and this is the only
|
|
3241
|
+
* place it is minted.
|
|
3242
|
+
*
|
|
3243
|
+
* `primaryKeys` empty falls back to a literal `id` on the row: drivers other
|
|
3244
|
+
* than postgres still serve rows with one, and this keeps them working.
|
|
2494
3245
|
*/
|
|
2495
|
-
function
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
3246
|
+
function rowToEntity(row, slug, primaryKeys = []) {
|
|
3247
|
+
return {
|
|
3248
|
+
id: primaryKeys.length > 0 ? buildCompositeId(row, primaryKeys) : row.id,
|
|
3249
|
+
path: slug,
|
|
3250
|
+
values: row
|
|
3251
|
+
};
|
|
2499
3252
|
}
|
|
2500
|
-
function createDriverAccessor(driver, slug) {
|
|
3253
|
+
function createDriverAccessor(driver, slug, getPks = () => []) {
|
|
2501
3254
|
const accessor = {
|
|
2502
3255
|
async find(params) {
|
|
2503
|
-
const orderParsed = parseOrderBy(params?.orderBy);
|
|
2504
3256
|
const filter = params?.where ? deserializeFilter(params.where) : void 0;
|
|
2505
|
-
const
|
|
3257
|
+
const limit = params?.limit ?? 20;
|
|
3258
|
+
const offset = params?.offset ?? 0;
|
|
3259
|
+
const fetchService = driver.restFetchService;
|
|
3260
|
+
const rows = fetchService && params?.include && params.include.length > 0 ? await fetchService.fetchCollectionForRest(slug, {
|
|
3261
|
+
filter,
|
|
3262
|
+
limit: params?.limit,
|
|
3263
|
+
offset: params?.offset,
|
|
3264
|
+
orderBy: params?.orderBy?.[0],
|
|
3265
|
+
order: params?.orderBy?.[1],
|
|
3266
|
+
searchString: params?.searchString
|
|
3267
|
+
}, params.include) : await driver.fetchCollection({
|
|
2506
3268
|
path: slug,
|
|
2507
3269
|
limit: params?.limit,
|
|
2508
3270
|
offset: params?.offset,
|
|
2509
3271
|
filter,
|
|
2510
|
-
orderBy:
|
|
2511
|
-
order:
|
|
3272
|
+
orderBy: params?.orderBy?.[0],
|
|
3273
|
+
order: params?.orderBy?.[1],
|
|
2512
3274
|
searchString: params?.searchString
|
|
2513
3275
|
});
|
|
2514
|
-
|
|
2515
|
-
|
|
3276
|
+
let total = rows.length + offset;
|
|
3277
|
+
let hasMore = rows.length >= limit;
|
|
3278
|
+
if (driver.count) {
|
|
3279
|
+
total = await driver.count({
|
|
3280
|
+
path: slug,
|
|
3281
|
+
filter
|
|
3282
|
+
});
|
|
3283
|
+
hasMore = offset + rows.length < total;
|
|
3284
|
+
}
|
|
2516
3285
|
return {
|
|
2517
|
-
data:
|
|
3286
|
+
data: rows.map((row) => rowToEntity(row, slug, getPks())),
|
|
2518
3287
|
meta: {
|
|
2519
|
-
total
|
|
3288
|
+
total,
|
|
2520
3289
|
limit,
|
|
2521
3290
|
offset,
|
|
2522
|
-
hasMore
|
|
3291
|
+
hasMore
|
|
2523
3292
|
}
|
|
2524
3293
|
};
|
|
2525
3294
|
},
|
|
2526
3295
|
async findById(id) {
|
|
2527
|
-
|
|
3296
|
+
const row = await driver.fetchOne({
|
|
2528
3297
|
path: slug,
|
|
2529
|
-
|
|
3298
|
+
id
|
|
2530
3299
|
});
|
|
3300
|
+
return row ? rowToEntity(row, slug, getPks()) : void 0;
|
|
2531
3301
|
},
|
|
2532
3302
|
async create(data, id) {
|
|
2533
|
-
return driver.
|
|
3303
|
+
return rowToEntity(await driver.save({
|
|
2534
3304
|
path: slug,
|
|
2535
3305
|
values: data,
|
|
2536
|
-
|
|
3306
|
+
id,
|
|
2537
3307
|
status: "new"
|
|
2538
|
-
});
|
|
3308
|
+
}), slug, getPks());
|
|
2539
3309
|
},
|
|
3310
|
+
createMany: driver.saveMany ? async (data, options) => {
|
|
3311
|
+
return (await driver.saveMany({
|
|
3312
|
+
path: slug,
|
|
3313
|
+
rows: data,
|
|
3314
|
+
upsert: options?.upsert
|
|
3315
|
+
})).map((row) => rowToEntity(row, slug, getPks()));
|
|
3316
|
+
} : void 0,
|
|
2540
3317
|
async update(id, data) {
|
|
2541
|
-
return driver.
|
|
3318
|
+
return rowToEntity(await driver.save({
|
|
2542
3319
|
path: slug,
|
|
2543
3320
|
values: data,
|
|
2544
|
-
|
|
3321
|
+
id,
|
|
2545
3322
|
status: "existing"
|
|
2546
|
-
});
|
|
3323
|
+
}), slug, getPks());
|
|
2547
3324
|
},
|
|
2548
3325
|
async delete(id) {
|
|
2549
|
-
return driver.
|
|
3326
|
+
return driver.delete({ row: {
|
|
2550
3327
|
id,
|
|
2551
3328
|
path: slug,
|
|
2552
3329
|
values: {}
|
|
2553
3330
|
} });
|
|
2554
3331
|
},
|
|
2555
|
-
|
|
2556
|
-
return driver.deleteAll(slug);
|
|
2557
|
-
} : void 0,
|
|
2558
|
-
count: driver.countEntities ? async (params) => {
|
|
3332
|
+
count: driver.count ? async (params) => {
|
|
2559
3333
|
const filter = params?.where ? deserializeFilter(params.where) : void 0;
|
|
2560
|
-
return driver.
|
|
3334
|
+
return driver.count({
|
|
2561
3335
|
path: slug,
|
|
2562
3336
|
filter
|
|
2563
3337
|
});
|
|
2564
3338
|
} : void 0,
|
|
2565
3339
|
listen: driver.listenCollection ? (params, onUpdate, onError) => {
|
|
2566
|
-
const orderParsed = parseOrderBy(params?.orderBy);
|
|
2567
3340
|
const limit = params?.limit ?? 20;
|
|
2568
3341
|
const offset = params?.offset ?? 0;
|
|
2569
3342
|
return driver.listenCollection({
|
|
@@ -2571,12 +3344,12 @@ function createDriverAccessor(driver, slug) {
|
|
|
2571
3344
|
limit: params?.limit,
|
|
2572
3345
|
offset: params?.offset,
|
|
2573
3346
|
filter: params?.where,
|
|
2574
|
-
orderBy:
|
|
2575
|
-
order:
|
|
3347
|
+
orderBy: params?.orderBy?.[0],
|
|
3348
|
+
order: params?.orderBy?.[1],
|
|
2576
3349
|
searchString: params?.searchString,
|
|
2577
3350
|
onUpdate: (entities) => {
|
|
2578
3351
|
onUpdate({
|
|
2579
|
-
data: entities,
|
|
3352
|
+
data: entities.map((row) => rowToEntity(row, slug, getPks())),
|
|
2580
3353
|
meta: {
|
|
2581
3354
|
total: entities.length,
|
|
2582
3355
|
limit,
|
|
@@ -2588,11 +3361,11 @@ function createDriverAccessor(driver, slug) {
|
|
|
2588
3361
|
onError
|
|
2589
3362
|
});
|
|
2590
3363
|
} : void 0,
|
|
2591
|
-
listenById: driver.
|
|
2592
|
-
return driver.
|
|
3364
|
+
listenById: driver.listenOne ? (id, onUpdate, onError) => {
|
|
3365
|
+
return driver.listenOne({
|
|
2593
3366
|
path: slug,
|
|
2594
|
-
|
|
2595
|
-
onUpdate: (entity) => onUpdate(entity
|
|
3367
|
+
id,
|
|
3368
|
+
onUpdate: (entity) => onUpdate(entity ? rowToEntity(entity, slug, getPks()) : void 0),
|
|
2596
3369
|
onError
|
|
2597
3370
|
});
|
|
2598
3371
|
} : void 0,
|
|
@@ -2629,14 +3402,15 @@ function createDriverAccessor(driver, slug) {
|
|
|
2629
3402
|
* @example
|
|
2630
3403
|
* const data = buildRebaseData(driver);
|
|
2631
3404
|
* await data.products.create({ name: "Camera", price: 299 });
|
|
2632
|
-
* const { data: items } = await data.products.find({ where: { status: "
|
|
3405
|
+
* const { data: items } = await data.products.find({ where: { status: ["==", "published"] } });
|
|
2633
3406
|
*/
|
|
2634
|
-
function buildRebaseData(driver) {
|
|
3407
|
+
function buildRebaseData(driver, options) {
|
|
2635
3408
|
const cache = /* @__PURE__ */ new Map();
|
|
3409
|
+
const primaryKeysFor = createPrimaryKeyResolver(options);
|
|
2636
3410
|
function getAccessor(slug) {
|
|
2637
3411
|
let accessor = cache.get(slug);
|
|
2638
3412
|
if (!accessor) {
|
|
2639
|
-
accessor = createDriverAccessor(driver, slug);
|
|
3413
|
+
accessor = createDriverAccessor(driver, slug, () => primaryKeysFor(slug));
|
|
2640
3414
|
cache.set(slug, accessor);
|
|
2641
3415
|
}
|
|
2642
3416
|
return accessor;
|
|
@@ -2648,6 +3422,238 @@ function buildRebaseData(driver) {
|
|
|
2648
3422
|
return getAccessor(toSnakeCase(prop));
|
|
2649
3423
|
} });
|
|
2650
3424
|
}
|
|
3425
|
+
/**
|
|
3426
|
+
* Unwrap a Entity back into the flat row it was built from. `rowToEntity` keeps
|
|
3427
|
+
* the row untouched under `.values` and derives `.id` alongside it, so dropping
|
|
3428
|
+
* the wrapper is the whole operation — the address was never part of the row.
|
|
3429
|
+
*/
|
|
3430
|
+
function entityToRow(entity) {
|
|
3431
|
+
return entity.values;
|
|
3432
|
+
}
|
|
3433
|
+
/**
|
|
3434
|
+
* Fluent query builder for the flat SDK data layer. Mirrors {@link QueryBuilder}
|
|
3435
|
+
* but resolves to `FindResult<M>` (flat rows) instead of Entity-wrapped
|
|
3436
|
+
* `FindResponse<M>`.
|
|
3437
|
+
*/
|
|
3438
|
+
var SdkQueryBuilder = class {
|
|
3439
|
+
client;
|
|
3440
|
+
params = { where: {} };
|
|
3441
|
+
constructor(client) {
|
|
3442
|
+
this.client = client;
|
|
3443
|
+
}
|
|
3444
|
+
where(columnOrCondition, operator, value) {
|
|
3445
|
+
if (typeof columnOrCondition === "object" && columnOrCondition !== null && "type" in columnOrCondition) {
|
|
3446
|
+
this.params.logical = columnOrCondition;
|
|
3447
|
+
return this;
|
|
3448
|
+
}
|
|
3449
|
+
if (!this.params.where) this.params.where = {};
|
|
3450
|
+
const column = columnOrCondition;
|
|
3451
|
+
const condition = [operator, value];
|
|
3452
|
+
const existing = this.params.where[column];
|
|
3453
|
+
if (existing === void 0) this.params.where[column] = condition;
|
|
3454
|
+
else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) this.params.where[column].push(condition);
|
|
3455
|
+
else {
|
|
3456
|
+
let firstCondition;
|
|
3457
|
+
if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === "string") firstCondition = existing;
|
|
3458
|
+
else firstCondition = ["==", existing];
|
|
3459
|
+
this.params.where[column] = [firstCondition, condition];
|
|
3460
|
+
}
|
|
3461
|
+
return this;
|
|
3462
|
+
}
|
|
3463
|
+
orderBy(column, direction = "asc") {
|
|
3464
|
+
this.params.orderBy = [column, direction];
|
|
3465
|
+
return this;
|
|
3466
|
+
}
|
|
3467
|
+
limit(count) {
|
|
3468
|
+
this.params.limit = count;
|
|
3469
|
+
return this;
|
|
3470
|
+
}
|
|
3471
|
+
offset(count) {
|
|
3472
|
+
this.params.offset = count;
|
|
3473
|
+
return this;
|
|
3474
|
+
}
|
|
3475
|
+
search(searchString) {
|
|
3476
|
+
this.params.searchString = searchString;
|
|
3477
|
+
return this;
|
|
3478
|
+
}
|
|
3479
|
+
include(...relations) {
|
|
3480
|
+
this.params.include = relations;
|
|
3481
|
+
return this;
|
|
3482
|
+
}
|
|
3483
|
+
async find() {
|
|
3484
|
+
return this.client.find(this.params);
|
|
3485
|
+
}
|
|
3486
|
+
async count() {
|
|
3487
|
+
return this.client.count ? this.client.count(this.params) : 0;
|
|
3488
|
+
}
|
|
3489
|
+
listen(onUpdate, onError) {
|
|
3490
|
+
if (!this.client.listen) throw new Error("Listen is only available when the driver supports realtime.");
|
|
3491
|
+
return this.client.listen(this.params, onUpdate, onError);
|
|
3492
|
+
}
|
|
3493
|
+
};
|
|
3494
|
+
/**
|
|
3495
|
+
* Wrap a Entity-shaped {@link CollectionAccessor} into a flat
|
|
3496
|
+
* {@link SDKCollectionClient}. Every returned record is unwrapped to a flat row
|
|
3497
|
+
* so the backend SDK is byte-for-byte the same shape as the frontend client.
|
|
3498
|
+
*/
|
|
3499
|
+
function toSdkCollectionClient(snap) {
|
|
3500
|
+
const client = {
|
|
3501
|
+
async find(params) {
|
|
3502
|
+
const res = await snap.find(params);
|
|
3503
|
+
return {
|
|
3504
|
+
data: res.data.map(entityToRow),
|
|
3505
|
+
meta: res.meta
|
|
3506
|
+
};
|
|
3507
|
+
},
|
|
3508
|
+
async findById(id) {
|
|
3509
|
+
const s = await snap.findById(id);
|
|
3510
|
+
return s ? entityToRow(s) : void 0;
|
|
3511
|
+
},
|
|
3512
|
+
async create(data, id) {
|
|
3513
|
+
return entityToRow(await snap.create(data, id));
|
|
3514
|
+
},
|
|
3515
|
+
async createMany(data, options) {
|
|
3516
|
+
if (!Array.isArray(data)) throw new TypeError("createMany expects an array of records.");
|
|
3517
|
+
if (data.length === 0) return [];
|
|
3518
|
+
if (!snap.createMany) throw new Error("Bulk writes are not supported by this collection's data source. Fall back to create() per record.");
|
|
3519
|
+
return (await snap.createMany(data, options)).map(entityToRow);
|
|
3520
|
+
},
|
|
3521
|
+
async update(id, data) {
|
|
3522
|
+
return entityToRow(await snap.update(id, data));
|
|
3523
|
+
},
|
|
3524
|
+
delete(id) {
|
|
3525
|
+
return snap.delete(id);
|
|
3526
|
+
},
|
|
3527
|
+
count: snap.count ? (params) => snap.count(params) : void 0,
|
|
3528
|
+
listen: snap.listen ? (params, onUpdate, onError) => snap.listen(params, (res) => onUpdate({
|
|
3529
|
+
data: res.data.map(entityToRow),
|
|
3530
|
+
meta: res.meta
|
|
3531
|
+
}), onError) : void 0,
|
|
3532
|
+
listenById: snap.listenById ? (id, onUpdate, onError) => snap.listenById(id, (s) => onUpdate(s ? entityToRow(s) : void 0), onError) : void 0,
|
|
3533
|
+
where(columnOrCondition, operator, value) {
|
|
3534
|
+
const builder = new SdkQueryBuilder(client);
|
|
3535
|
+
if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
|
|
3536
|
+
return builder.where(columnOrCondition, operator, value);
|
|
3537
|
+
},
|
|
3538
|
+
orderBy: (column, direction) => new SdkQueryBuilder(client).orderBy(column, direction),
|
|
3539
|
+
limit: (count) => new SdkQueryBuilder(client).limit(count),
|
|
3540
|
+
offset: (count) => new SdkQueryBuilder(client).offset(count),
|
|
3541
|
+
search: (searchString) => new SdkQueryBuilder(client).search(searchString),
|
|
3542
|
+
include: (...relations) => new SdkQueryBuilder(client).include(...relations)
|
|
3543
|
+
};
|
|
3544
|
+
return client;
|
|
3545
|
+
}
|
|
3546
|
+
/**
|
|
3547
|
+
* Wrap a flat {@link SDKCollectionClient} into a Entity-shaped
|
|
3548
|
+
* {@link CollectionAccessor}. Every returned row is re-wrapped into the
|
|
3549
|
+
* `{ id, path, values }` view-model the admin CMS renders.
|
|
3550
|
+
*/
|
|
3551
|
+
function toEntityAccessor(sdk, slug, getPks = () => []) {
|
|
3552
|
+
const accessor = {
|
|
3553
|
+
async find(params) {
|
|
3554
|
+
const res = await sdk.find(params);
|
|
3555
|
+
return {
|
|
3556
|
+
data: res.data.map((row) => rowToEntity(row, slug, getPks())),
|
|
3557
|
+
meta: res.meta
|
|
3558
|
+
};
|
|
3559
|
+
},
|
|
3560
|
+
async findById(id) {
|
|
3561
|
+
const row = await sdk.findById(id);
|
|
3562
|
+
return row ? rowToEntity(row, slug, getPks()) : void 0;
|
|
3563
|
+
},
|
|
3564
|
+
async create(data, id) {
|
|
3565
|
+
return rowToEntity(await sdk.create(data, id), slug, getPks());
|
|
3566
|
+
},
|
|
3567
|
+
async update(id, data) {
|
|
3568
|
+
const row = await sdk.update(id, data);
|
|
3569
|
+
if (!row) throw new Error(`Update returned no data for id ${id}`);
|
|
3570
|
+
return rowToEntity(row, slug, getPks());
|
|
3571
|
+
},
|
|
3572
|
+
delete(id) {
|
|
3573
|
+
return sdk.delete(id);
|
|
3574
|
+
},
|
|
3575
|
+
count: sdk.count ? (params) => sdk.count(params) : void 0,
|
|
3576
|
+
listen: sdk.listen ? (params, onUpdate, onError) => sdk.listen(params, (res) => onUpdate({
|
|
3577
|
+
data: res.data.map((row) => rowToEntity(row, slug, getPks())),
|
|
3578
|
+
meta: res.meta
|
|
3579
|
+
}), onError) : void 0,
|
|
3580
|
+
listenById: sdk.listenById ? (id, onUpdate, onError) => sdk.listenById(id, (row) => onUpdate(row ? rowToEntity(row, slug, getPks()) : void 0), onError) : void 0,
|
|
3581
|
+
where(columnOrCondition, operator, value) {
|
|
3582
|
+
const builder = new QueryBuilder(accessor);
|
|
3583
|
+
if (typeof columnOrCondition === "object") return builder.where(columnOrCondition);
|
|
3584
|
+
return builder.where(columnOrCondition, operator, value);
|
|
3585
|
+
},
|
|
3586
|
+
orderBy: (column, direction) => new QueryBuilder(accessor).orderBy(column, direction),
|
|
3587
|
+
limit: (count) => new QueryBuilder(accessor).limit(count),
|
|
3588
|
+
offset: (count) => new QueryBuilder(accessor).offset(count),
|
|
3589
|
+
search: (searchString) => new QueryBuilder(accessor).search(searchString),
|
|
3590
|
+
include: (...relations) => new QueryBuilder(accessor).include(...relations)
|
|
3591
|
+
};
|
|
3592
|
+
return accessor;
|
|
3593
|
+
}
|
|
3594
|
+
/**
|
|
3595
|
+
* Wrap a flat {@link RebaseSdkData} into a Entity-shaped {@link RebaseData}.
|
|
3596
|
+
*
|
|
3597
|
+
* This is the **CMS boundary**: the SDK client (`client.data`) returns flat
|
|
3598
|
+
* rows, but the admin renders the `Entity` view-model (`entity.values.*`).
|
|
3599
|
+
* `core/Rebase.tsx` wraps `client.data` through this before handing it to the
|
|
3600
|
+
* CMS `RebaseDataContext` — without it the admin renders rows with only their
|
|
3601
|
+
* `id`.
|
|
3602
|
+
*/
|
|
3603
|
+
function wrapAsEntityData(sdkData, options) {
|
|
3604
|
+
const cache = /* @__PURE__ */ new Map();
|
|
3605
|
+
const primaryKeysFor = createPrimaryKeyResolver(options);
|
|
3606
|
+
function getAccessor(slug) {
|
|
3607
|
+
let accessor = cache.get(slug);
|
|
3608
|
+
if (!accessor) {
|
|
3609
|
+
accessor = toEntityAccessor(sdkData.collection(slug), slug, () => primaryKeysFor(slug));
|
|
3610
|
+
cache.set(slug, accessor);
|
|
3611
|
+
}
|
|
3612
|
+
return accessor;
|
|
3613
|
+
}
|
|
3614
|
+
return new Proxy({ collection: getAccessor }, { get(_target, prop) {
|
|
3615
|
+
if (prop === "collection") return getAccessor;
|
|
3616
|
+
if (typeof prop === "symbol") return void 0;
|
|
3617
|
+
if (prop === "then" || prop === "toJSON" || prop === "$$typeof") return void 0;
|
|
3618
|
+
return getAccessor(toSnakeCase(prop));
|
|
3619
|
+
} });
|
|
3620
|
+
}
|
|
3621
|
+
/**
|
|
3622
|
+
* Wrap a Entity-shaped {@link RebaseData} into a flat {@link RebaseSdkData}.
|
|
3623
|
+
*
|
|
3624
|
+
* Every collection accessor is adapted to return flat rows. Use this to derive
|
|
3625
|
+
* the flat SDK data layer (`context.data`) from an existing Entity data layer
|
|
3626
|
+
* — e.g. the admin routes its Entity data via `useData()` and exposes the
|
|
3627
|
+
* same routing as flat `context.data` for callbacks by wrapping it here.
|
|
3628
|
+
*/
|
|
3629
|
+
function wrapAsSdkData(entityData) {
|
|
3630
|
+
const cache = /* @__PURE__ */ new Map();
|
|
3631
|
+
function getAccessor(slug) {
|
|
3632
|
+
let accessor = cache.get(slug);
|
|
3633
|
+
if (!accessor) {
|
|
3634
|
+
accessor = toSdkCollectionClient(entityData.collection(slug));
|
|
3635
|
+
cache.set(slug, accessor);
|
|
3636
|
+
}
|
|
3637
|
+
return accessor;
|
|
3638
|
+
}
|
|
3639
|
+
return new Proxy({ collection: getAccessor }, { get(_target, prop) {
|
|
3640
|
+
if (prop === "collection") return getAccessor;
|
|
3641
|
+
if (typeof prop === "symbol") return void 0;
|
|
3642
|
+
if (prop === "then" || prop === "toJSON" || prop === "$$typeof") return void 0;
|
|
3643
|
+
return getAccessor(toSnakeCase(prop));
|
|
3644
|
+
} });
|
|
3645
|
+
}
|
|
3646
|
+
/**
|
|
3647
|
+
* Build a flat {@link RebaseSdkData} from a `DataDriver`.
|
|
3648
|
+
*
|
|
3649
|
+
* This is the developer-facing SDK data layer used by backend framework
|
|
3650
|
+
* callbacks & scripts (`context.data` / `rebase.data`). It returns flat rows —
|
|
3651
|
+
* identical in shape to the frontend SDK client — so the API is symmetric
|
|
3652
|
+
* across front and back. The admin CMS uses {@link buildRebaseData} (Entity).
|
|
3653
|
+
*/
|
|
3654
|
+
function buildSdkData(driver) {
|
|
3655
|
+
return wrapAsSdkData(buildRebaseData(driver));
|
|
3656
|
+
}
|
|
2651
3657
|
//#endregion
|
|
2652
3658
|
//#region src/data/buildRoutedRebaseData.ts
|
|
2653
3659
|
/**
|
|
@@ -2692,6 +3698,57 @@ function buildRoutedRebaseData({ defaultData, sources, resolveKey }) {
|
|
|
2692
3698
|
} });
|
|
2693
3699
|
}
|
|
2694
3700
|
//#endregion
|
|
3701
|
+
//#region src/data/sort-dialect.ts
|
|
3702
|
+
/**
|
|
3703
|
+
* Sort-order wire codec.
|
|
3704
|
+
*
|
|
3705
|
+
* This is the ONLY module that knows about the colon-delimited wire format
|
|
3706
|
+
* (`"field:direction"`) used in HTTP query parameters.
|
|
3707
|
+
* Everything else speaks {@link OrderByTuple} exclusively.
|
|
3708
|
+
*
|
|
3709
|
+
* Mirrors the filter architecture in `filter-dialect.ts`.
|
|
3710
|
+
*
|
|
3711
|
+
* @module
|
|
3712
|
+
*/
|
|
3713
|
+
/**
|
|
3714
|
+
* Serialize an {@link OrderByTuple} to the wire format `"field:direction"`.
|
|
3715
|
+
*
|
|
3716
|
+
* **Runtime tolerance:** if the input is already a well-formed wire string
|
|
3717
|
+
* (from an untyped JS caller), it is returned unchanged.
|
|
3718
|
+
* This is undocumented tolerance, not public API — don't rely on it.
|
|
3719
|
+
*
|
|
3720
|
+
* @param orderBy - A canonical `[field, direction]` tuple, or at runtime
|
|
3721
|
+
* possibly a pre-serialized string (undocumented tolerance).
|
|
3722
|
+
* @returns The wire-format string, or `undefined` if the input is falsy.
|
|
3723
|
+
*
|
|
3724
|
+
* @remarks
|
|
3725
|
+
* Field names containing `:` are representable in the tuple form but
|
|
3726
|
+
* **not** on the wire — this is an inherent limitation of the colon-delimited
|
|
3727
|
+
* encoding and is not resolved here.
|
|
3728
|
+
*/
|
|
3729
|
+
function serializeOrderBy(orderBy) {
|
|
3730
|
+
if (!orderBy) return void 0;
|
|
3731
|
+
if (typeof orderBy === "string") return orderBy;
|
|
3732
|
+
return `${orderBy[0]}:${orderBy[1]}`;
|
|
3733
|
+
}
|
|
3734
|
+
/**
|
|
3735
|
+
* Deserialize a wire-format `"field:direction"` string into an {@link OrderByTuple}.
|
|
3736
|
+
*
|
|
3737
|
+
* Lenient parsing (matches existing server behaviour):
|
|
3738
|
+
* - Bare field name (no colon): `"name"` → `["name", "asc"]`
|
|
3739
|
+
* - Unknown direction: `"name:foo"` → `["name", "asc"]`
|
|
3740
|
+
* - Empty / falsy input: → `undefined`
|
|
3741
|
+
*
|
|
3742
|
+
* @param raw - The wire-format string from an HTTP query parameter.
|
|
3743
|
+
* @returns The canonical tuple, or `undefined` if the input is empty/falsy.
|
|
3744
|
+
*/
|
|
3745
|
+
function deserializeOrderBy(raw) {
|
|
3746
|
+
if (!raw) return void 0;
|
|
3747
|
+
const idx = raw.indexOf(":");
|
|
3748
|
+
if (idx === -1) return [raw, "asc"];
|
|
3749
|
+
return [raw.slice(0, idx), raw.slice(idx + 1) === "desc" ? "desc" : "asc"];
|
|
3750
|
+
}
|
|
3751
|
+
//#endregion
|
|
2695
3752
|
//#region src/table-classification.ts
|
|
2696
3753
|
/** Schemas that are always considered Rebase-internal. */
|
|
2697
3754
|
var REBASE_INTERNAL_SCHEMAS = ["rebase", "auth"];
|
|
@@ -2768,6 +3825,6 @@ async function detectJunctionTables(executeSql) {
|
|
|
2768
3825
|
return junctionTables;
|
|
2769
3826
|
}
|
|
2770
3827
|
//#endregion
|
|
2771
|
-
export { COLLECTION_PATH_SEPARATOR, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, JUNCTION_TABLES_SQL, QueryBuilder, REBASE_INTERNAL_PREFIXES, REBASE_INTERNAL_SCHEMAS, addInitialSlash, and, applyPropertyConditions,
|
|
3828
|
+
export { COLLECTION_PATH_SEPARATOR, COMPOSITE_ID_SEPARATOR, CollectionRegistry, DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE, JUNCTION_TABLES_SQL, QueryBuilder, REBASE_INTERNAL_PREFIXES, REBASE_INTERNAL_SCHEMAS, addInitialSlash, and, applyPropertyConditions, buildCollection, buildCompositeId, buildConditionContext, buildProperty, buildPropertyCallbacks, buildRebaseData, buildRoutedRebaseData, buildSdkData, canCreateEntity, canDeleteEntity, canEditEntity, canReadCollection, checkOperation, classifyTable, cond, createDataSourceRegistry, createRelationRef, createRelationRefWithData, defaultUsersCollection, defineCollection, deserializeFilter, deserializeLogicalCondition, deserializeOrderBy, detectJunctionTables, embedParentExpression, enumToObjectEntries, evaluateCondition, evaluatePolicy, findAnonymousGrants, findRelation, fullPathToCollectionSegments, getArrayResolvedProperties, getCollectionBySlugWithin, getCollectionPathsCombinations, getColumnName, getDeclaredPrimaryKeys, getDefaultValueFor, getDefaultValueFortype, getDefaultValuesFor, getEffectiveSecurityRules, getEntityImagePreviewPropertyKey, getEnumVarName, getInjectedSecurityRules, getJunctionCollectionConfig, getJunctionSecurityRules, getLabelOrConfigFrom, getLastSegment, getLocalChangesBackup, getNavigationEntriesFromPath, getParentReferencesFromPath, getPrimaryKeys, getReferenceFrom, getRelationFrom, getSubcollections, getTableName, getTableVarName, isHidden, isPropertyBuilder, isReadOnly, isRebaseInternalTable, normalizeToEntityRelation, or, parseIdValues, policyToPostgres, registerConditionOperations, removeInitialAndTrailingSlashes, removeInitialSlash, removeTrailingSlash, resolveArrayProperties, resolveCollectionPathIds, resolveCollectionRelations, resolveDataSource, resolveDefaultSelectedView, resolveEnumValues, resolveFilterOperators, resolveJunctionSpecs, resolvePrimaryKeys, resolveProperties, resolveProperty, resolvePropertyEnum, resolvePropertyRelation, resolveRelationProperty, resolveStorageFilenameString, resolveStoragePathString, resolveStorageSource, sanitizeData, sanitizeRelation, securityRuleToConditions, segmentsToStrippedPath, serializeFilter, serializeLogicalCondition, serializeOrderBy, sortProperties, sqlToPolicy, stripCollectionPath, traverseValueProperty, traverseValuesProperties, updateDateAutoValues, wrapAsEntityData, wrapAsSdkData };
|
|
2772
3829
|
|
|
2773
3830
|
//# sourceMappingURL=index.es.js.map
|