@rebasepro/types 0.29.0-canary.g0e3a0e7 → 0.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,26 @@
1
+ import type { AggregateGroup, AggregateGroupTransform, AggregateSelect } from "./data.js";
2
+ import type { DriverAggregate, DriverAggregateGroup } from "./data_driver.js";
3
+ /** Every aggregate function, by its SDK name: what `?select=` accepts too. */
4
+ export declare const AGGREGATE_FUNCTIONS: readonly DriverAggregate["fn"][];
5
+ /** The functions that take no field. */
6
+ export declare const FIELDLESS_AGGREGATES: ReadonlySet<DriverAggregate["fn"]>;
7
+ /** Every `groupBy` transform. */
8
+ export declare const AGGREGATE_GROUP_TRANSFORMS: readonly AggregateGroupTransform[];
9
+ /**
10
+ * The key an aggregate comes back under.
11
+ *
12
+ * `sum(total)` → `sum_total`, `count()` → `count`, `countDistinct(sid)` →
13
+ * `count_distinct_sid`, `percentile(fame, 0.95)` → `p95_fame`. One function,
14
+ * because the SDK, the REST parser and the HTTP client all derive it and have
15
+ * to agree — a caller reading `row.sum_total` off an SDK result and off an HTTP
16
+ * response is reading the same key or the SDK is broken.
17
+ */
18
+ export declare function aggregateAlias(fn: string, field?: string, p?: number): string;
19
+ /** `percentile`'s `p`, refused unless it is a fraction a key can name (0–1, at most three decimals). */
20
+ export declare function isPercentileFraction(p: unknown): p is number;
21
+ /** An `AggregateSelect` as a driver is handed it. */
22
+ export declare function toDriverAggregate(select: AggregateSelect<Record<string, unknown>>): DriverAggregate;
23
+ /** The key a group comes back under: the column's name, or `<transform>_<field>`. */
24
+ export declare function aggregateGroupKey(group: string | AggregateGroup | DriverAggregateGroup): string;
25
+ /** A `groupBy` entry as a driver is handed it. */
26
+ export declare function toDriverAggregateGroup(group: string | AggregateGroup): string | DriverAggregateGroup;
@@ -42,8 +42,9 @@ export type WhereElementOf<T> = ElementOf<T> | IdOf<ElementOf<T>>;
42
42
  * The branches mirror `buildSingleFilterCondition` in `@rebasepro/server-postgres`:
43
43
  *
44
44
  * - `array-contains` → one element of the column (or a related row's id).
45
- * - `in` / `not-in` / `array-contains-any` → a list of elements; a bare element
46
- * is read as the one-element list, and `null` is a null check.
45
+ * - `in` / `not-in` / `array-contains-any` / `array-contains-all` /
46
+ * `array-contained-by` → a list of elements; a bare element is read as the
47
+ * one-element list, and `null` is a null check.
47
48
  * - `like` / `ilike` / `not-like` / `not-ilike` → a SQL pattern, always a
48
49
  * string. It matches a text column, or an enum by its label; on a number,
49
50
  * a date or any other column the Postgres driver refuses it with a 400
@@ -55,7 +56,7 @@ export type WhereElementOf<T> = ElementOf<T> | IdOf<ElementOf<T>>;
55
56
  * (a dynamic filter UI, say) gets the union of every branch and stays as
56
57
  * permissive as it was.
57
58
  */
58
- export type WhereValueFor<Op extends WhereFilterOp, T> = Op extends "array-contains" ? WhereElementOf<T> : Op extends "in" | "not-in" | "array-contains-any" ? readonly WhereElementOf<T>[] | WhereElementOf<T> | null : Op extends "like" | "ilike" | "not-like" | "not-ilike" ? string : Op extends "is-null" | "is-not-null" ? null | undefined : T | null;
59
+ export type WhereValueFor<Op extends WhereFilterOp, T> = Op extends "array-contains" ? WhereElementOf<T> : Op extends "in" | "not-in" | "array-contains-any" | "array-contains-all" | "array-contained-by" ? readonly WhereElementOf<T>[] | WhereElementOf<T> | null : Op extends "like" | "ilike" | "not-like" | "not-ilike" ? string : Op extends "is-null" | "is-not-null" ? null | undefined : T | null;
59
60
  /**
60
61
  * One `[operator, value]` condition on a column of type `T`, with the value
61
62
  * typed for the operator exactly as the fluent `where(column, op, value)` types
@@ -657,6 +658,8 @@ export interface CollectionAccessor<M extends Record<string, unknown> = Record<s
657
658
  * number nothing counted.
658
659
  */
659
660
  aggregate?(params: AggregateParams<M>): Promise<AggregateResult>;
661
+ /** {@link SDKCollectionClient.refresh}. Optional, as `aggregate` is. */
662
+ refresh?(options?: RefreshOptions): Promise<void>;
660
663
  where<K extends keyof M & string, Op extends WhereFilterOp>(column: K, operator: Op, value: WhereValueFor<Op, M[K]>): QueryBuilderInterface<M>;
661
664
  where(logicalCondition: LogicalConditionFor<M>): QueryBuilderInterface<M>;
662
665
  orderBy(column: (keyof M & string) | ComputedSortField, direction?: "asc" | "desc"): QueryBuilderInterface<M>;
@@ -774,10 +777,25 @@ export type QueryComputedFields = {
774
777
  * `count` alone counts rows; every other function names a column, and `count`
775
778
  * with a column counts its non-NULL values.
776
779
  *
780
+ * - `countDistinct` counts the distinct non-NULL values of a column.
781
+ * - `mode` is the most frequent value (ties go to the first in sort order).
782
+ * - `percentile` is the continuous percentile `p` (0–1) of a number column:
783
+ * `p: 0.5` is the median.
784
+ * - `distinct` is the column's distinct non-NULL values, sorted, as an array —
785
+ * for an array column, the distinct arrays; group by `unnest` for the
786
+ * distinct elements.
787
+ * - `fingerprint` is a short string that changes whenever a row it covers is
788
+ * inserted, updated or deleted: compare it with the last one you saw to
789
+ * know whether anything changed, without reading the rows. It may also
790
+ * change when nothing did (a write that set a column to its own value), never
791
+ * the other way round.
792
+ *
777
793
  * The result key is derived rather than chosen: `sum(total)` comes back as
778
- * `sum_total` and a bare `count()` as `count`. Letting a caller name it would
779
- * mean checking their name is not also a `groupBy` field — a rule nobody would
780
- * guess, and a silently overwritten value if it went unchecked.
794
+ * `sum_total`, a bare `count()` as `count`, `countDistinct(sid)` as
795
+ * `count_distinct_sid` and `percentile(fame, 0.95)` as `p95_fame` (see
796
+ * {@link AggregateAlias}). Letting a caller name it would mean checking their
797
+ * name is not also a `groupBy` field — a rule nobody would guess, and a
798
+ * silently overwritten value if it went unchecked.
781
799
  *
782
800
  * @group Data
783
801
  */
@@ -788,9 +806,33 @@ export type AggregateSelect<M extends Record<string, unknown> = Record<string, u
788
806
  fn: "sum" | "avg";
789
807
  field: NumericKeyOf<M>;
790
808
  } | {
791
- fn: "min" | "max";
809
+ fn: "min" | "max" | "countDistinct" | "mode" | "distinct";
792
810
  field: Extract<keyof M, string>;
811
+ } | {
812
+ fn: "percentile";
813
+ field: NumericKeyOf<M>;
814
+ p: number;
815
+ } | {
816
+ fn: "fingerprint";
817
+ };
818
+ /**
819
+ * A transformed column to group by, where a plain column will not do:
820
+ * `lower`/`upper` of a text column, the `year`/`month`/`day` of a date (in
821
+ * UTC, served as `"2026"`, `"2026-11"`, `"2026-11-08"`), or `unnest` — one
822
+ * group per element of an array column, so `count()` beside it counts the rows
823
+ * holding each element.
824
+ *
825
+ * Its key in each row is `<transform>_<field>` (`lower_artist`,
826
+ * `unnest_tags`), which is also how `orderBy` names it.
827
+ *
828
+ * @group Data
829
+ */
830
+ export type AggregateGroup<Field extends string = string> = {
831
+ field: Field;
832
+ transform: AggregateGroupTransform;
793
833
  };
834
+ /** What an {@link AggregateGroup} does to its column. @group Data */
835
+ export type AggregateGroupTransform = "lower" | "upper" | "unnest" | "year" | "month" | "day";
794
836
  /**
795
837
  * The columns of `M` that hold numbers — what `sum` and `avg` can add up. Any
796
838
  * column used to be accepted, and `sum` of a text column was a 400. An untyped
@@ -835,8 +877,12 @@ export type AggregateRow = Record<string, unknown>;
835
877
  export interface AggregateParams<M extends Record<string, unknown> = Record<string, unknown>> {
836
878
  /** The aggregates to compute. At least one. */
837
879
  select: AggregateSelect<M>[];
838
- /** Columns to group by. Omit for a single row over everything that matches. */
839
- groupBy?: Extract<keyof M, string>[];
880
+ /**
881
+ * Columns to group by — or a column transformed ({@link AggregateGroup}),
882
+ * e.g. `{ field: "artist", transform: "lower" }`. Omit for a single row
883
+ * over everything that matches.
884
+ */
885
+ groupBy?: (Extract<keyof M, string> | AggregateGroup<Extract<keyof M, string>>)[];
840
886
  /** Filter conditions, as {@link FindParams.where}. */
841
887
  where?: WhereFor<M>;
842
888
  /** An `and`/`or`/`not` group, AND-ed with `where`. */
@@ -866,20 +912,25 @@ export interface AggregateParams<M extends Record<string, unknown> = Record<stri
866
912
  */
867
913
  orderBy?: OrderByTuple<AggregateOrderKey<M>> | OrderByTuple<AggregateOrderKey<M>>[];
868
914
  }
915
+ /** What `refresh()` takes. @group Data */
916
+ export interface RefreshOptions {
917
+ /** Keep serving the old rows while the new ones are computed (`REFRESH … CONCURRENTLY`). */
918
+ concurrently?: boolean;
919
+ }
869
920
  /**
870
921
  * The key an {@link AggregateSelect} comes back under: `count` for `count()`,
871
922
  * `<fn>_<field>` otherwise (`sum_total`, `max_created_at`).
872
923
  *
873
924
  * @group Data
874
925
  */
875
- export type AggregateAlias<M extends Record<string, unknown> = Record<string, unknown>> = "count" | `${"count" | "min" | "max"}_${Extract<keyof M, string>}` | `${"sum" | "avg"}_${NumericKeyOf<M>}`;
926
+ export type AggregateAlias<M extends Record<string, unknown> = Record<string, unknown>> = "count" | "fingerprint" | `${"count" | "min" | "max" | "count_distinct" | "mode" | "distinct"}_${Extract<keyof M, string>}` | `${"sum" | "avg"}_${NumericKeyOf<M>}` | `p${number}_${NumericKeyOf<M>}`;
876
927
  /**
877
928
  * What {@link AggregateParams.orderBy} can sort the groups by: a column (to
878
929
  * group by) or an aggregate's alias.
879
930
  *
880
931
  * @group Data
881
932
  */
882
- export type AggregateOrderKey<M extends Record<string, unknown> = Record<string, unknown>> = Extract<keyof M, string> | AggregateAlias<M>;
933
+ export type AggregateOrderKey<M extends Record<string, unknown> = Record<string, unknown>> = Extract<keyof M, string> | `${AggregateGroupTransform}_${Extract<keyof M, string>}` | AggregateAlias<M>;
883
934
  /**
884
935
  * Where a grouped aggregate's page of groups sits: the `limit` it was cut at,
885
936
  * the `offset` it started from, and whether more groups follow.
@@ -1824,6 +1875,20 @@ Inc = IncludeSpec> {
1824
1875
  * as "nothing matched".
1825
1876
  */
1826
1877
  aggregate(params: AggregateParams<M>): Promise<AggregateResult>;
1878
+ /**
1879
+ * Recompute a materialized view's rows from its query (`view:
1880
+ * { materialized: true }`), as `REFRESH MATERIALIZED VIEW` does.
1881
+ *
1882
+ * For a caller holding one of the view's `roles` (`dataAsAdmin` does);
1883
+ * refused for anyone else and for a collection that is not a materialized
1884
+ * view. With `concurrently`, reads go on being served the old rows while
1885
+ * the new ones are computed — slower, and never a blocked read.
1886
+ *
1887
+ * ```ts
1888
+ * await rebase.dataAsAdmin.artist_stats.refresh({ concurrently: true });
1889
+ * ```
1890
+ */
1891
+ refresh(options?: RefreshOptions): Promise<void>;
1827
1892
  where<K extends keyof M & string, Op extends WhereFilterOp>(column: K, operator: Op, value: WhereValueFor<Op, M[K]>): SDKQueryBuilderInterface<M, Inc>;
1828
1893
  /** A relation path (`author.name`) or a JSON path (`metadata->>tier`). */
1829
1894
  where(column: NonColumnFieldPath, operator: WhereFilterOp, value: unknown): SDKQueryBuilderInterface<M, Inc>;
@@ -3,7 +3,7 @@ import type { EntityStatus, EntityValues } from "../types/entities.js";
3
3
  import type { CollectionConfig, FilterValues } from "../types/collections.js";
4
4
  import type { OrderByTuple } from "../types/filter-operators.js";
5
5
  import type { RebaseCallContext } from "../call_context.js";
6
- import type { IncludeSpec, LogicalCondition } from "./data.js";
6
+ import type { AggregateGroupTransform, IncludeSpec, LogicalCondition } from "./data.js";
7
7
  import type { CollectionUpdateMeta } from "../types/websockets.js";
8
8
  /**
9
9
  * @internal
@@ -401,6 +401,16 @@ export type FilterCombinationValidProps = {
401
401
  filterValues: FilterValues<string>;
402
402
  sortBy?: [string, "asc" | "desc"];
403
403
  };
404
+ /** Options of {@link DataDriver.sql}. */
405
+ export interface CallerSqlOptions {
406
+ /** The statement's values, referenced as `$1`, `$2`, … in the query text. */
407
+ params?: unknown[];
408
+ /**
409
+ * Run in a read-write transaction. Off by default: the statement runs
410
+ * read-only, and an `INSERT`, `UPDATE` or `DELETE` fails with `25006`.
411
+ */
412
+ write?: boolean;
413
+ }
404
414
  /**
405
415
  * The integration SPI for plugging a data backend into Rebase.
406
416
  *
@@ -500,6 +510,14 @@ export interface DataDriver {
500
510
  * a caller reaches for a batch to get.
501
511
  */
502
512
  updateMany?<M extends Record<string, unknown> = Record<string, unknown>>(props: UpdateManyProps<M>): Promise<Record<string, unknown>[]>;
513
+ /**
514
+ * Recompute the rows of a collection that serves a materialized view —
515
+ * see `SDKCollectionClient.refresh`. Optional: only a driver with views
516
+ * has one.
517
+ */
518
+ refreshView?(path: string, options?: {
519
+ concurrently?: boolean;
520
+ }): Promise<void>;
503
521
  /**
504
522
  * Delete the row `props.row` addresses.
505
523
  *
@@ -618,6 +636,26 @@ export interface DataDriver {
618
636
  * Optional: a driver without it is called directly, read by read.
619
637
  */
620
638
  readTogether?<T>(work: (driver: DataDriver) => Promise<T>): Promise<T>;
639
+ /**
640
+ * Run one SQL statement as this driver's identity: in the caller's own
641
+ * transaction, under the same row-level security as every read and write
642
+ * on this driver, so the tables' policies decide which rows it sees and
643
+ * changes. Read-only unless `write: true`.
644
+ *
645
+ * The query text must be the application's own. Every value — above all
646
+ * anything a user sent — goes in `params` as `$1`, `$2`, …: identity rides
647
+ * in session settings, and a statement able to change them is refused
648
+ * (`SQL_NOT_ALLOWED`), as is more than one statement.
649
+ *
650
+ * Policies are what it shares with the SDK, and all it shares. Per-field
651
+ * `access` rules, `afterRead`/`beforeQuery` hooks, validation, save hooks
652
+ * and history are application code the SDK runs and this does not.
653
+ *
654
+ * Optional: an engine without row-level security has none. On the
655
+ * server's own (unscoped) driver it is absent too — that one's raw SQL is
656
+ * `admin.executeSql`, which runs as the owner.
657
+ */
658
+ sql?(query: string, options?: CallerSqlOptions): Promise<Record<string, unknown>[]>;
621
659
  /**
622
660
  * Every row a collection stores, as stored, a page at a time: soft-deleted
623
661
  * rows included, and past every read hook — no `beforeQuery`, no
@@ -687,6 +725,25 @@ export interface DataDriver {
687
725
  */
688
726
  admin?: import("../types/backend.js").DatabaseAdmin;
689
727
  }
728
+ /**
729
+ * One aggregate as a driver is handed it: an `AggregateSelect` with its
730
+ * derived `alias` (the key it comes back under).
731
+ */
732
+ export interface DriverAggregate {
733
+ fn: "count" | "sum" | "avg" | "min" | "max" | "countDistinct" | "mode" | "percentile" | "distinct" | "fingerprint";
734
+ /** Absent for `count()` and `fingerprint()`. */
735
+ field?: string;
736
+ /** `percentile`'s fraction, 0–1. */
737
+ p?: number;
738
+ alias: string;
739
+ }
740
+ /** A transformed group (`AggregateGroup`) as a driver is handed it, with the key it comes back under. */
741
+ export interface DriverAggregateGroup {
742
+ field: string;
743
+ transform: AggregateGroupTransform;
744
+ /** `<transform>_<field>`. */
745
+ key: string;
746
+ }
690
747
  /**
691
748
  * REST-optimised fetch service exposed by drivers that support
692
749
  * eager-loading of relations via `include`.
@@ -750,8 +807,10 @@ export interface RestFetchService {
750
807
  */
751
808
  cursorFor?(collectionPath: string, row: Record<string, unknown>, orderBy?: OrderByTuple[]): string | undefined;
752
809
  /**
753
- * `count`/`sum`/`avg`/`min`/`max` over the rows a filter selects,
754
- * optionally grouped.
810
+ * The aggregates of `AggregateSelect` (`count`, `sum`, `avg`, `min`,
811
+ * `max`, `countDistinct`, `mode`, `percentile`, `distinct`, `fingerprint`)
812
+ * over the rows a filter selects, optionally grouped by columns or by
813
+ * transformed columns (`AggregateGroup`).
755
814
  *
756
815
  * Optional, and the REST route answers 501 where a driver does not
757
816
  * implement it — an aggregate is not a thing to approximate, and an empty
@@ -768,12 +827,8 @@ export interface RestFetchService {
768
827
  * `groupBy` is served; anything else is refused with a 400.
769
828
  */
770
829
  aggregate?(collectionPath: string, options: {
771
- aggregates: {
772
- fn: "count" | "sum" | "avg" | "min" | "max";
773
- field?: string;
774
- alias: string;
775
- }[];
776
- groupBy?: string[];
830
+ aggregates: DriverAggregate[];
831
+ groupBy?: (string | DriverAggregateGroup)[];
777
832
  filter?: FilterValues<string>;
778
833
  logical?: LogicalCondition;
779
834
  searchString?: string;
@@ -7,3 +7,4 @@ export * from "./storage.js";
7
7
  export * from "./storage-references.js";
8
8
  export * from "./email.js";
9
9
  export * from "./client.js";
10
+ export * from "./aggregates.js";
package/dist/index.es.js CHANGED
@@ -298,6 +298,8 @@ var CANONICAL_TO_REST = {
298
298
  "not-in": "nin",
299
299
  "array-contains": "cs",
300
300
  "array-contains-any": "csa",
301
+ "array-contains-all": "csall",
302
+ "array-contained-by": "cd",
301
303
  "like": "like",
302
304
  "ilike": "ilike",
303
305
  "not-like": "nlike",
@@ -317,6 +319,8 @@ var REST_TO_CANONICAL = {
317
319
  "nin": "not-in",
318
320
  "cs": "array-contains",
319
321
  "csa": "array-contains-any",
322
+ "csall": "array-contains-all",
323
+ "cd": "array-contained-by",
320
324
  "like": "like",
321
325
  "ilike": "ilike",
322
326
  "nlike": "not-like",
@@ -342,7 +346,9 @@ var NULL_OPS = /* @__PURE__ */ new Set(["is-null", "is-not-null"]);
342
346
  var LIST_OPS = /* @__PURE__ */ new Set([
343
347
  "in",
344
348
  "not-in",
345
- "array-contains-any"
349
+ "array-contains-any",
350
+ "array-contains-all",
351
+ "array-contained-by"
346
352
  ]);
347
353
  /**
348
354
  * Every canonical operator, in a stable order. Useful for engine capability
@@ -361,6 +367,8 @@ var ALL_WHERE_FILTER_OPS = [
361
367
  "not-in",
362
368
  "array-contains",
363
369
  "array-contains-any",
370
+ "array-contains-all",
371
+ "array-contained-by",
364
372
  "like",
365
373
  "ilike",
366
374
  "not-like",
@@ -651,7 +659,7 @@ var FIREBASE_CAPABILITIES = {
651
659
  supportsColumnTypes: false,
652
660
  supportsRealtime: true,
653
661
  supportsVectors: false,
654
- filterOperators: ALL_WHERE_FILTER_OPS.filter((op) => op !== "like" && op !== "ilike" && op !== "not-like" && op !== "not-ilike"),
662
+ filterOperators: ALL_WHERE_FILTER_OPS.filter((op) => op !== "like" && op !== "ilike" && op !== "not-like" && op !== "not-ilike" && op !== "array-contains-all" && op !== "array-contained-by"),
655
663
  filterableRelationKinds: [],
656
664
  supportsRelationFieldFilters: false,
657
665
  relationAggregateSorts: false,
@@ -1079,6 +1087,15 @@ var REBASE_SCHEMA = "rebase";
1079
1087
  * the trusted server plane and `IS NOT NULL` a tautology.
1080
1088
  */
1081
1089
  var RLS_UID_SQL = `${REBASE_SCHEMA}.uid()`;
1090
+ /**
1091
+ * Is the caller one of this database's request roles? What a permissive
1092
+ * policy is ANDed with under `rls.policyTarget: "requestRole"`, so another
1093
+ * application's role holding a grant on the table gets nothing from it.
1094
+ * `current_user` is passed in — inside the function, which reads the recorded
1095
+ * roles with its owner's rights, `current_user` would be the owner — and the
1096
+ * sub-select makes it one evaluation per statement, not one per row.
1097
+ */
1098
+ var RLS_IS_REQUEST_ROLE_SQL = `(SELECT ${REBASE_SCHEMA}.is_request_role(current_user::text))`;
1082
1099
  /** The request's roles as a comma-separated string, for `string_to_array`. */
1083
1100
  var RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;
1084
1101
  /**
@@ -1902,17 +1919,25 @@ registerResourceKind({
1902
1919
  ],
1903
1920
  implicitDefault: true
1904
1921
  });
1905
- amendResourceKind("database", { envBases: [
1906
- "DATABASE_URL",
1907
- "DATABASE_READ_URL",
1908
- "DATABASE_DIRECT_URL",
1909
- "DATABASE_POOLED",
1910
- "ADMIN_CONNECTION_STRING",
1911
- "REBASE_DRIVER",
1912
- "DB_POOL_MAX",
1913
- "DB_POOL_IDLE_TIMEOUT",
1914
- "DB_POOL_CONNECT_TIMEOUT"
1915
- ] });
1922
+ amendResourceKind("database", {
1923
+ optionKeys: [
1924
+ "databaseId",
1925
+ "migrations",
1926
+ "extensions",
1927
+ "rls"
1928
+ ],
1929
+ envBases: [
1930
+ "DATABASE_URL",
1931
+ "DATABASE_READ_URL",
1932
+ "DATABASE_DIRECT_URL",
1933
+ "DATABASE_POOLED",
1934
+ "ADMIN_CONNECTION_STRING",
1935
+ "REBASE_DRIVER",
1936
+ "DB_POOL_MAX",
1937
+ "DB_POOL_IDLE_TIMEOUT",
1938
+ "DB_POOL_CONNECT_TIMEOUT"
1939
+ ]
1940
+ });
1916
1941
  function database(keyOrOptions = DEFAULT_RESOURCE_KEY, options = {}) {
1917
1942
  return typeof keyOrOptions === "string" ? declareResource("database", keyOrOptions, options) : declareResource("database", DEFAULT_RESOURCE_KEY, keyOrOptions);
1918
1943
  }
@@ -1937,6 +1962,30 @@ function declaredDatabaseExtensions() {
1937
1962
  }
1938
1963
  return [...names].sort();
1939
1964
  }
1965
+ /** The `rls` options a database declaration gave, `{}` when it gave none or was never declared. */
1966
+ function declaredDatabaseRls(key = DEFAULT_DATA_SOURCE_KEY) {
1967
+ const rls = declaredResources("database").find((d) => d.key === key)?.options.rls;
1968
+ return rls && typeof rls === "object" ? rls : {};
1969
+ }
1970
+ /**
1971
+ * The policy settings every compile path must agree on — the boot's policy
1972
+ * ensure, `rebase db generate`, the drift check — read from the one place all
1973
+ * of them can see: the database declaration, with `REBASE_RLS_POLICY_TARGET` /
1974
+ * `REBASE_RLS_DEFAULT_POLICIES` over it. Defaults are what Rebase compiled
1975
+ * before these existed.
1976
+ *
1977
+ * Browser-safe: where there is no `process`, only the declaration counts.
1978
+ */
1979
+ function declaredRlsPolicyShape(dataSource = DEFAULT_DATA_SOURCE_KEY) {
1980
+ const declared = declaredDatabaseRls(dataSource);
1981
+ const env = typeof process !== "undefined" ? process.env : void 0;
1982
+ const envTarget = env?.REBASE_RLS_POLICY_TARGET?.trim();
1983
+ const envDefaults = env?.REBASE_RLS_DEFAULT_POLICIES?.trim().toLowerCase();
1984
+ return {
1985
+ policyTarget: envTarget === "requestRole" || envTarget === "public" ? envTarget : declared.policyTarget === "requestRole" ? "requestRole" : "public",
1986
+ defaultPolicies: envDefaults === "false" ? false : envDefaults === "true" ? true : declared.defaultPolicies !== false
1987
+ };
1988
+ }
1940
1989
  registerResourceKind({
1941
1990
  kind: "bucket",
1942
1991
  engines: [
@@ -3918,6 +3967,82 @@ function resolverFromSources(client) {
3918
3967
  };
3919
3968
  }
3920
3969
  //#endregion
3921
- export { ADMIN_COLLECTION_KEYS, ADMIN_PROPERTY_KEYS, ADMIN_ROLE, ADMIN_SCOPES, ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, AUTH_FLOW_HEADER, BATCH_REF_KEY, BUILT_IN_SCOPES, BUILT_IN_SCOPE_DESCRIPTIONS, BUNDLE_FORMAT_VERSION, CANONICAL_TO_REST, DATA_PLANE_SCOPES, DEFAULT_CAPABILITIES, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, DEFAULT_FILTERABLE_RELATION_KINDS, DEFAULT_FUZZY_THRESHOLD, DEFAULT_LIST_LIMIT, DEFAULT_RESOURCE_KEY, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, DEFAULT_STORAGE_SOURCE_KEY, DEFAULT_TENANT_BYPASS_ROLES, DEFAULT_VECTOR_LIST_LIMIT, EMPTY_ACCESS_MODEL, EntityReference, EntityRelation, FIELD_OPERATORS, FIREBASE_CAPABILITIES, GeoPoint, IMPERSONATE_HEADER, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, KEY_MANAGEMENT_SCOPES, LEGACY_RLS_JWT_SQL, LEGACY_RLS_ROLES_SQL, LEGACY_RLS_SCHEMA, LEGACY_RLS_UID_SQL, LIST_OPS, ListLimitError, MAX_INCLUDE_DEPTH, MAX_LIST_LIMIT, MCP_APP_MODULES, MONGODB_CAPABILITIES, NULL_OPS, POSTGRES_CAPABILITIES, PUBLIC_STORAGE_PREFIX, REBASE_SCHEMA, RELEVANCE_SORT_FIELD, RESERVED_BACKEND_PREFIXES, RESOURCE_GRAPH_VERSION, REST_TO_CANONICAL, RLS_IS_ANONYMOUS_SQL, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, RUNTIME_CONTRACT_VERSION, RUNTIME_ONLY_COLLECTION_KEYS, RebaseApiError, RebaseClientError, SCHEMA_VERSION_HEADER, SCOPE_TARGETS, SIMULATED_CONTEXT_HEADER, SIMULATE_API_KEY_ID_HEADER, SIMULATE_ROLE_HEADER, SIMULATE_USER_ID_HEADER, STORAGE_REFERENCE_SCHEME, Vector, amendResourceKind, applyCollectionPatch, bucket, buildResourceGraph, canonicalSchemaPayload, collectionPatchProblems, computeSchemaVersion, database, declareCron, declareFunction, declareResource, declaredDataSources, declaredDatabaseExtensions, declaredQueueConsumers, declaredResources, declaredStorageSources, declaredSubscriptions, describeScope, deserializeCollections, diffCollections, diffJsonValues, encodeRelationAggregateSort, envBasesForResource, findEnvSuffixCollision, findStorageSuffixCollision, formatSimulatedContext, getCollectionDataPath, getDataSourceCapabilities, getDeclaredSubcollections, hasAdminRole, hasFieldOperation, hasForeignKeyOnTarget, intersectScopes, isAdminScope, isAnonymousUid, isBranchAdmin, isBuiltInScope, isChannelBusInstance, isCollectionPatch, isContentHashedFileName, isDataPlaneScope, isDocumentAdmin, isFieldOperation, isFirebaseCollectionConfig, isLazyComponentRef, isManyToMany, isMongoDBCollectionConfig, isPostgresCollectionConfig, isPublicStorageKey, isPublicStoragePath, isRelationAggregateSort, isRelationalCollectionConfig, isResourceHandle, isSQLAdmin, isSchemaAdmin, isSchemaEditingAdmin, isSerializedCollectionRef, isStorageReference, isTenantClaimSource, isTenantMembershipSource, isToMany, isUnsupported, isValidAppHost, isValidEngine, joinConditions, knownScopes, nestAdminCollectionKeys, nestAdminKeysOf, nestAdminPropertyKeys, nestCollectionPatchPaths, parseAppAddress, parseEnvBoolean, parseRelationAggregateSort, parseScope, parseSimulatedContext, parseStorageReference, policy, queue, registerDataSourceCapabilities, registerResourceKind, reservedPrefixFor, resetDeclaredQueueConsumers, resetDeclaredResources, resetDeclaredSubscriptions, resolveClientListLimit, resolveResourceRefs, resolveStorageReferences, resourceEnvSuffix, resourceId, resourceKeyOf, resourceKind, resourceKinds, resourceToDataSource, resourceToStorageSource, rewriteLegacyRlsFunctions, roleNameProblem, runtimeOnlyKeyIn, scopeAcceptsTarget, scopeGrants, scopeGrantsAny, scopeTargets, scopesBeyond, scopesForRoles, serializeCollections, setQueueRuntime, setTopicRuntime, simulationHeaders, soleJoinCondition, sortKeyToString, storageEnvSuffix, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText, summarizeRoles, summarizeScopes, toCanonicalOp, toCollectionJson, topic, unsupportedMethod, usesLegacyRlsFunctions, validateScopes };
3970
+ //#region src/controllers/aggregates.ts
3971
+ /** Every aggregate function, by its SDK name: what `?select=` accepts too. */
3972
+ var AGGREGATE_FUNCTIONS = [
3973
+ "count",
3974
+ "sum",
3975
+ "avg",
3976
+ "min",
3977
+ "max",
3978
+ "countDistinct",
3979
+ "mode",
3980
+ "percentile",
3981
+ "distinct",
3982
+ "fingerprint"
3983
+ ];
3984
+ /** The functions that take no field. */
3985
+ var FIELDLESS_AGGREGATES = /* @__PURE__ */ new Set(["count", "fingerprint"]);
3986
+ /** Every `groupBy` transform. */
3987
+ var AGGREGATE_GROUP_TRANSFORMS = [
3988
+ "lower",
3989
+ "upper",
3990
+ "unnest",
3991
+ "year",
3992
+ "month",
3993
+ "day"
3994
+ ];
3995
+ /** A function's name in its result key: the SDK's camelCase in SQL's spelling. */
3996
+ var ALIAS_NAMES = { countDistinct: "count_distinct" };
3997
+ /**
3998
+ * `percentile`'s `p` as it reads in a key: `0.95` → `95`, `0.5` → `50`,
3999
+ * `0.995` → `99_5`.
4000
+ */
4001
+ function percentileLabel(p) {
4002
+ return String(Math.round(p * 1e3) / 10).replace(".", "_");
4003
+ }
4004
+ /**
4005
+ * The key an aggregate comes back under.
4006
+ *
4007
+ * `sum(total)` → `sum_total`, `count()` → `count`, `countDistinct(sid)` →
4008
+ * `count_distinct_sid`, `percentile(fame, 0.95)` → `p95_fame`. One function,
4009
+ * because the SDK, the REST parser and the HTTP client all derive it and have
4010
+ * to agree — a caller reading `row.sum_total` off an SDK result and off an HTTP
4011
+ * response is reading the same key or the SDK is broken.
4012
+ */
4013
+ function aggregateAlias(fn, field, p) {
4014
+ if (fn === "percentile") return `p${percentileLabel(p ?? 0)}_${field ?? ""}`;
4015
+ const name = ALIAS_NAMES[fn] ?? fn;
4016
+ return field ? `${name}_${field}` : name;
4017
+ }
4018
+ /** `percentile`'s `p`, refused unless it is a fraction a key can name (0–1, at most three decimals). */
4019
+ function isPercentileFraction(p) {
4020
+ return typeof p === "number" && Number.isFinite(p) && p >= 0 && p <= 1 && Math.abs(Math.round(p * 1e3) - p * 1e3) < 1e-9;
4021
+ }
4022
+ /** An `AggregateSelect` as a driver is handed it. */
4023
+ function toDriverAggregate(select) {
4024
+ const field = "field" in select ? select.field : void 0;
4025
+ const p = select.fn === "percentile" ? select.p : void 0;
4026
+ return {
4027
+ fn: select.fn,
4028
+ ...field !== void 0 ? { field } : {},
4029
+ ...p !== void 0 ? { p } : {},
4030
+ alias: aggregateAlias(select.fn, field, p)
4031
+ };
4032
+ }
4033
+ /** The key a group comes back under: the column's name, or `<transform>_<field>`. */
4034
+ function aggregateGroupKey(group) {
4035
+ return typeof group === "string" ? group : `${group.transform}_${group.field}`;
4036
+ }
4037
+ /** A `groupBy` entry as a driver is handed it. */
4038
+ function toDriverAggregateGroup(group) {
4039
+ return typeof group === "string" ? group : {
4040
+ field: group.field,
4041
+ transform: group.transform,
4042
+ key: aggregateGroupKey(group)
4043
+ };
4044
+ }
4045
+ //#endregion
4046
+ export { ADMIN_COLLECTION_KEYS, ADMIN_PROPERTY_KEYS, ADMIN_ROLE, ADMIN_SCOPES, AGGREGATE_FUNCTIONS, AGGREGATE_GROUP_TRANSFORMS, ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, AUTH_FLOW_HEADER, BATCH_REF_KEY, BUILT_IN_SCOPES, BUILT_IN_SCOPE_DESCRIPTIONS, BUNDLE_FORMAT_VERSION, CANONICAL_TO_REST, DATA_PLANE_SCOPES, DEFAULT_CAPABILITIES, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, DEFAULT_FILTERABLE_RELATION_KINDS, DEFAULT_FUZZY_THRESHOLD, DEFAULT_LIST_LIMIT, DEFAULT_RESOURCE_KEY, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, DEFAULT_STORAGE_SOURCE_KEY, DEFAULT_TENANT_BYPASS_ROLES, DEFAULT_VECTOR_LIST_LIMIT, EMPTY_ACCESS_MODEL, EntityReference, EntityRelation, FIELDLESS_AGGREGATES, FIELD_OPERATORS, FIREBASE_CAPABILITIES, GeoPoint, IMPERSONATE_HEADER, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, KEY_MANAGEMENT_SCOPES, LEGACY_RLS_JWT_SQL, LEGACY_RLS_ROLES_SQL, LEGACY_RLS_SCHEMA, LEGACY_RLS_UID_SQL, LIST_OPS, ListLimitError, MAX_INCLUDE_DEPTH, MAX_LIST_LIMIT, MCP_APP_MODULES, MONGODB_CAPABILITIES, NULL_OPS, POSTGRES_CAPABILITIES, PUBLIC_STORAGE_PREFIX, REBASE_SCHEMA, RELEVANCE_SORT_FIELD, RESERVED_BACKEND_PREFIXES, RESOURCE_GRAPH_VERSION, REST_TO_CANONICAL, RLS_IS_ANONYMOUS_SQL, RLS_IS_REQUEST_ROLE_SQL, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, RUNTIME_CONTRACT_VERSION, RUNTIME_ONLY_COLLECTION_KEYS, RebaseApiError, RebaseClientError, SCHEMA_VERSION_HEADER, SCOPE_TARGETS, SIMULATED_CONTEXT_HEADER, SIMULATE_API_KEY_ID_HEADER, SIMULATE_ROLE_HEADER, SIMULATE_USER_ID_HEADER, STORAGE_REFERENCE_SCHEME, Vector, aggregateAlias, aggregateGroupKey, amendResourceKind, applyCollectionPatch, bucket, buildResourceGraph, canonicalSchemaPayload, collectionPatchProblems, computeSchemaVersion, database, declareCron, declareFunction, declareResource, declaredDataSources, declaredDatabaseExtensions, declaredDatabaseRls, declaredQueueConsumers, declaredResources, declaredRlsPolicyShape, declaredStorageSources, declaredSubscriptions, describeScope, deserializeCollections, diffCollections, diffJsonValues, encodeRelationAggregateSort, envBasesForResource, findEnvSuffixCollision, findStorageSuffixCollision, formatSimulatedContext, getCollectionDataPath, getDataSourceCapabilities, getDeclaredSubcollections, hasAdminRole, hasFieldOperation, hasForeignKeyOnTarget, intersectScopes, isAdminScope, isAnonymousUid, isBranchAdmin, isBuiltInScope, isChannelBusInstance, isCollectionPatch, isContentHashedFileName, isDataPlaneScope, isDocumentAdmin, isFieldOperation, isFirebaseCollectionConfig, isLazyComponentRef, isManyToMany, isMongoDBCollectionConfig, isPercentileFraction, isPostgresCollectionConfig, isPublicStorageKey, isPublicStoragePath, isRelationAggregateSort, isRelationalCollectionConfig, isResourceHandle, isSQLAdmin, isSchemaAdmin, isSchemaEditingAdmin, isSerializedCollectionRef, isStorageReference, isTenantClaimSource, isTenantMembershipSource, isToMany, isUnsupported, isValidAppHost, isValidEngine, joinConditions, knownScopes, nestAdminCollectionKeys, nestAdminKeysOf, nestAdminPropertyKeys, nestCollectionPatchPaths, parseAppAddress, parseEnvBoolean, parseRelationAggregateSort, parseScope, parseSimulatedContext, parseStorageReference, policy, queue, registerDataSourceCapabilities, registerResourceKind, reservedPrefixFor, resetDeclaredQueueConsumers, resetDeclaredResources, resetDeclaredSubscriptions, resolveClientListLimit, resolveResourceRefs, resolveStorageReferences, resourceEnvSuffix, resourceId, resourceKeyOf, resourceKind, resourceKinds, resourceToDataSource, resourceToStorageSource, rewriteLegacyRlsFunctions, roleNameProblem, runtimeOnlyKeyIn, scopeAcceptsTarget, scopeGrants, scopeGrantsAny, scopeTargets, scopesBeyond, scopesForRoles, serializeCollections, setQueueRuntime, setTopicRuntime, simulationHeaders, soleJoinCondition, sortKeyToString, storageEnvSuffix, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText, summarizeRoles, summarizeScopes, toCanonicalOp, toCollectionJson, toDriverAggregate, toDriverAggregateGroup, topic, unsupportedMethod, usesLegacyRlsFunctions, validateScopes };
3922
4047
 
3923
4048
  //# sourceMappingURL=index.es.js.map