@rebasepro/types 0.35.0 → 0.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/controllers/client.d.ts +6 -3
- package/dist/index.es.js +57 -2494
- package/dist/index.es.js.map +1 -1
- package/dist/types/backend.d.ts +31 -0
- package/dist/users/import.d.ts +42 -3
- package/package.json +6 -3
package/dist/index.es.js
CHANGED
|
@@ -1,38 +1,9 @@
|
|
|
1
1
|
//#region src/errors.ts
|
|
2
|
-
/**
|
|
3
|
-
* The single error type thrown across the entire Rebase client surface —
|
|
4
|
-
* HTTP data/control-plane calls, realtime/WebSocket operations, and
|
|
5
|
-
* client-side logic errors (e.g. an unknown collection accessor). A `catch`
|
|
6
|
-
* block only ever needs to check for this one class:
|
|
7
|
-
*
|
|
8
|
-
* ```ts
|
|
9
|
-
* import { RebaseApiError } from "@rebasepro/client"; // re-exported
|
|
10
|
-
*
|
|
11
|
-
* try {
|
|
12
|
-
* await client.data.products.update(id, { price: 9 });
|
|
13
|
-
* } catch (e) {
|
|
14
|
-
* if (e instanceof RebaseApiError) {
|
|
15
|
-
* if (e.status === 404) { ... } // HTTP failures carry a status
|
|
16
|
-
* console.error(e.code, e.details);
|
|
17
|
-
* }
|
|
18
|
-
* }
|
|
19
|
-
* ```
|
|
20
|
-
*
|
|
21
|
-
* `status` is present for HTTP failures and `undefined` otherwise, so its
|
|
22
|
-
* presence distinguishes transport-level errors from realtime/logic errors.
|
|
23
|
-
*
|
|
24
|
-
* @group Errors
|
|
25
|
-
*/
|
|
26
2
|
var RebaseApiError = class extends Error {
|
|
27
|
-
/** HTTP status code, or `undefined` for non-HTTP errors. */
|
|
28
3
|
status;
|
|
29
|
-
/** Stable machine-readable error code, when the server supplied one. See {@link RebaseErrorCode}. */
|
|
30
4
|
code;
|
|
31
|
-
/** Structured error payload from the server, when present. */
|
|
32
5
|
details;
|
|
33
|
-
/** See {@link RebaseErrorInit.requestId}. Quote it in a bug report. */
|
|
34
6
|
requestId;
|
|
35
|
-
/** See {@link RebaseErrorInit.retryAfterSeconds}. */
|
|
36
7
|
retryAfterSeconds;
|
|
37
8
|
constructor(message, init = {}) {
|
|
38
9
|
super(message);
|
|
@@ -45,41 +16,12 @@ var RebaseApiError = class extends Error {
|
|
|
45
16
|
if (init.cause !== void 0) this.cause = init.cause;
|
|
46
17
|
}
|
|
47
18
|
};
|
|
48
|
-
/**
|
|
49
|
-
* Client-side logic error — raised before any request is made (e.g. accessing
|
|
50
|
-
* an unknown collection accessor when a typed dictionary is configured).
|
|
51
|
-
*
|
|
52
|
-
* A subclass of {@link RebaseApiError} (with no `status`), so a single
|
|
53
|
-
* `catch (e) { if (e instanceof RebaseApiError) ... }` handles it too.
|
|
54
|
-
*
|
|
55
|
-
* @group Errors
|
|
56
|
-
*/
|
|
57
19
|
var RebaseClientError = class extends RebaseApiError {
|
|
58
|
-
/**
|
|
59
|
-
* `init` is the same one {@link RebaseApiError} takes, and it is what makes
|
|
60
|
-
* `code` reachable at all.
|
|
61
|
-
*
|
|
62
|
-
* The constructor used to accept a message and nothing else, so every
|
|
63
|
-
* client-side failure — an undefined filter value, an unknown accessor,
|
|
64
|
-
* `listen()` on a client built with `realtime: false`, a function name with
|
|
65
|
-
* a `/` in it, `refreshSession()` while signed out — arrived with `code ===
|
|
66
|
-
* undefined`. The documented `switch (e.code)` in this file's own example
|
|
67
|
-
* fell to `default: throw e` for all of them, and the only client-side error
|
|
68
|
-
* that *did* carry a code was `OFFLINE`, because that one path minted a
|
|
69
|
-
* `RebaseApiError` instead.
|
|
70
|
-
*/
|
|
71
20
|
constructor(message, init = {}) {
|
|
72
21
|
super(message, init);
|
|
73
22
|
this.name = "RebaseClientError";
|
|
74
23
|
}
|
|
75
24
|
};
|
|
76
|
-
/**
|
|
77
|
-
* Brand for a contract method a particular client cannot serve.
|
|
78
|
-
*
|
|
79
|
-
* `Symbol.for` rather than a fresh symbol: two copies of `@rebasepro/types` in
|
|
80
|
-
* one tree — which happens, see `docs/dependency-duplication-traps.md` — must
|
|
81
|
-
* agree about it, and a module-local symbol would not.
|
|
82
|
-
*/
|
|
83
25
|
var UNSUPPORTED_METHOD = Symbol.for("rebase.unsupportedMethod");
|
|
84
26
|
function unsupportedMethod(message) {
|
|
85
27
|
const stub = () => {
|
|
@@ -88,61 +30,16 @@ function unsupportedMethod(message) {
|
|
|
88
30
|
stub[UNSUPPORTED_METHOD] = true;
|
|
89
31
|
return stub;
|
|
90
32
|
}
|
|
91
|
-
/**
|
|
92
|
-
* Can this method actually do anything?
|
|
93
|
-
*
|
|
94
|
-
* `true` for a stub from {@link unsupportedMethod} **and** for a method that is
|
|
95
|
-
* simply not there — a partial client, a hand-built test double, an
|
|
96
|
-
* implementation written against an older shape of the interface. Both mean the
|
|
97
|
-
* same thing to a caller, so both answer the same way, and an adapter that
|
|
98
|
-
* checks this cannot be caught out by either.
|
|
99
|
-
*
|
|
100
|
-
* Ordinary code does not need it: calling the method and letting it throw is
|
|
101
|
-
* the normal path. Adapters do — the admin panel chooses between subscribing
|
|
102
|
-
* and a one-shot `find()` by asking whether the client can listen, and a UI
|
|
103
|
-
* that subscribes into a throw is worse than one that polls. This is the
|
|
104
|
-
* question `if (accessor.listen)` used to be asking, made explicit now that the
|
|
105
|
-
* method is always there to call.
|
|
106
|
-
*
|
|
107
|
-
* @group Errors
|
|
108
|
-
*/
|
|
109
33
|
function isUnsupported(method) {
|
|
110
34
|
if (typeof method !== "function") return true;
|
|
111
35
|
return method[UNSUPPORTED_METHOD] === true;
|
|
112
36
|
}
|
|
113
37
|
//#endregion
|
|
114
38
|
//#region src/types/filter-operators.ts
|
|
115
|
-
/** The wire spelling of a {@link RelationAggregateSort}: `min(applications.created_at)`. */
|
|
116
39
|
var RELATION_AGGREGATE_SORT_PATTERN = /^(min|max|count|sum|avg)\(([^().]+)(?:\.([^()]+))?\)$/;
|
|
117
|
-
/**
|
|
118
|
-
* A {@link RelationAggregateSort} as a single string — `min(applications.created_at)`,
|
|
119
|
-
* `count(applications)`.
|
|
120
|
-
*
|
|
121
|
-
* The wire form is a string because every layer below the call site already is
|
|
122
|
-
* one: `OrderByTuple` is `[string, direction]`, the REST parameter is
|
|
123
|
-
* `?orderBy=key:direction`, the driver contract takes `orderBy?: string |
|
|
124
|
-
* OrderByTuple[]`, and a cursor names its keys by string. `_score` established
|
|
125
|
-
* the same pattern — a sort key that is not a column, spelled as one — and this
|
|
126
|
-
* reuses it rather than widening five signatures to carry an object that would
|
|
127
|
-
* be flattened at the end anyway.
|
|
128
|
-
*
|
|
129
|
-
* SQL's own spelling, so the key reads as what it compiles to. Neither `:` nor
|
|
130
|
-
* `,` appears in it, which is what keeps it safe in the colon-delimited wire
|
|
131
|
-
* shorthand.
|
|
132
|
-
*
|
|
133
|
-
* @group Models
|
|
134
|
-
*/
|
|
135
40
|
function encodeRelationAggregateSort(sort) {
|
|
136
41
|
return `${sort.agg}(${sort.relation}${sort.field ? `.${sort.field}` : ""})`;
|
|
137
42
|
}
|
|
138
|
-
/**
|
|
139
|
-
* Read the string spelling back, or `undefined` if it is not one.
|
|
140
|
-
*
|
|
141
|
-
* `undefined` rather than a throw: this is asked of *every* sort key to find
|
|
142
|
-
* out which kind it is, and an ordinary column name is not an error.
|
|
143
|
-
*
|
|
144
|
-
* @group Models
|
|
145
|
-
*/
|
|
146
43
|
function parseRelationAggregateSort(key) {
|
|
147
44
|
const match = RELATION_AGGREGATE_SORT_PATTERN.exec(key);
|
|
148
45
|
if (!match) return void 0;
|
|
@@ -154,20 +51,12 @@ function parseRelationAggregateSort(key) {
|
|
|
154
51
|
...field && { field }
|
|
155
52
|
};
|
|
156
53
|
}
|
|
157
|
-
/** Is this sort key the object form rather than a field name? */
|
|
158
54
|
function isRelationAggregateSort(key) {
|
|
159
55
|
return typeof key === "object" && key !== null && typeof key.relation === "string" && typeof key.agg === "string";
|
|
160
56
|
}
|
|
161
|
-
/** A sort key in the single-string form every layer below the call site speaks. */
|
|
162
57
|
function sortKeyToString(key) {
|
|
163
58
|
return isRelationAggregateSort(key) ? encodeRelationAggregateSort(key) : key;
|
|
164
59
|
}
|
|
165
|
-
/**
|
|
166
|
-
* Read a {@link CaseFoldedFieldPath}: the function and the field it folds, or
|
|
167
|
-
* `undefined` for any other key.
|
|
168
|
-
*
|
|
169
|
-
* @group Models
|
|
170
|
-
*/
|
|
171
60
|
function parseCaseFoldedFieldPath(key) {
|
|
172
61
|
const match = /^(lower|upper)\(\s*([^()\s]+)\s*\)$/.exec(key);
|
|
173
62
|
return match ? {
|
|
@@ -175,7 +64,6 @@ function parseCaseFoldedFieldPath(key) {
|
|
|
175
64
|
field: match[2]
|
|
176
65
|
} : void 0;
|
|
177
66
|
}
|
|
178
|
-
/** Maps canonical operators to their REST short-code equivalents. */
|
|
179
67
|
var CANONICAL_TO_REST = {
|
|
180
68
|
"==": "eq",
|
|
181
69
|
"!=": "neq",
|
|
@@ -196,7 +84,6 @@ var CANONICAL_TO_REST = {
|
|
|
196
84
|
"is-null": "isnull",
|
|
197
85
|
"is-not-null": "notnull"
|
|
198
86
|
};
|
|
199
|
-
/** Maps REST short-code operators to their canonical equivalents. */
|
|
200
87
|
var REST_TO_CANONICAL = {
|
|
201
88
|
"eq": "==",
|
|
202
89
|
"neq": "!=",
|
|
@@ -217,21 +104,7 @@ var REST_TO_CANONICAL = {
|
|
|
217
104
|
"isnull": "is-null",
|
|
218
105
|
"notnull": "is-not-null"
|
|
219
106
|
};
|
|
220
|
-
/**
|
|
221
|
-
* Operators that test for null/not-null and therefore ignore their value.
|
|
222
|
-
* Codecs normalize the value of these conditions to `null`.
|
|
223
|
-
*/
|
|
224
107
|
var NULL_OPS = /* @__PURE__ */ new Set(["is-null", "is-not-null"]);
|
|
225
|
-
/**
|
|
226
|
-
* Operators whose operand is a **list** of values rather than one value.
|
|
227
|
-
*
|
|
228
|
-
* On the wire that list is always parenthesised — `in.(draft,review)` — which
|
|
229
|
-
* is what lets the REST codec tell `?status=in.(a,b)` (the operator) from
|
|
230
|
-
* `?status=in.progress` (a value that happens to start with an operator's
|
|
231
|
-
* name). See `deserializeSingle` in `@rebasepro/common`.
|
|
232
|
-
*
|
|
233
|
-
* @group Models
|
|
234
|
-
*/
|
|
235
108
|
var LIST_OPS = /* @__PURE__ */ new Set([
|
|
236
109
|
"in",
|
|
237
110
|
"not-in",
|
|
@@ -239,12 +112,6 @@ var LIST_OPS = /* @__PURE__ */ new Set([
|
|
|
239
112
|
"array-contains-all",
|
|
240
113
|
"array-contained-by"
|
|
241
114
|
]);
|
|
242
|
-
/**
|
|
243
|
-
* Every canonical operator, in a stable order. Useful for engine capability
|
|
244
|
-
* declarations ({@link DataSourceCapabilities.filterOperators}) and for
|
|
245
|
-
* building operator subsets.
|
|
246
|
-
* @group Models
|
|
247
|
-
*/
|
|
248
115
|
var ALL_WHERE_FILTER_OPS = [
|
|
249
116
|
"<",
|
|
250
117
|
"<=",
|
|
@@ -265,105 +132,27 @@ var ALL_WHERE_FILTER_OPS = [
|
|
|
265
132
|
"is-null",
|
|
266
133
|
"is-not-null"
|
|
267
134
|
];
|
|
268
|
-
/** All canonical operator strings for runtime validation. */
|
|
269
135
|
var CANONICAL_OPS = new Set(ALL_WHERE_FILTER_OPS);
|
|
270
|
-
/**
|
|
271
|
-
* The REST table as a `Map`, because the key `toCanonicalOp` is handed comes
|
|
272
|
-
* off the wire.
|
|
273
|
-
*
|
|
274
|
-
* Indexed as a plain object, every `Object.prototype` member answered:
|
|
275
|
-
* `toCanonicalOp("valueOf")` returned the inherited *function* as though it
|
|
276
|
-
* were a `WhereFilterOp`, and every caller here treats a defined result as
|
|
277
|
-
* "known operator". Same defect the REST codec's own lookup tables were
|
|
278
|
-
* converted away from in `filter-dialect.ts`; this is the copy that survived
|
|
279
|
-
* one package over, and it now sits under the operator validation the REST
|
|
280
|
-
* parser does, which would otherwise have admitted `["constructor", x]`.
|
|
281
|
-
*/
|
|
282
136
|
var REST_OP_LOOKUP = new Map(Object.entries(REST_TO_CANONICAL));
|
|
283
|
-
/**
|
|
284
|
-
* Resolve any operator string (canonical or REST short-code) to its
|
|
285
|
-
* canonical `WhereFilterOp` form. Returns `undefined` for unknown operators.
|
|
286
|
-
*
|
|
287
|
-
* @example
|
|
288
|
-
* toCanonicalOp("==") // "=="
|
|
289
|
-
* toCanonicalOp("eq") // "=="
|
|
290
|
-
* toCanonicalOp("cs") // "array-contains"
|
|
291
|
-
* toCanonicalOp("xyz") // undefined
|
|
292
|
-
*/
|
|
293
137
|
function toCanonicalOp(op) {
|
|
294
138
|
if (CANONICAL_OPS.has(op)) return op;
|
|
295
139
|
return REST_OP_LOOKUP.get(op);
|
|
296
140
|
}
|
|
297
141
|
//#endregion
|
|
298
142
|
//#region src/types/search.ts
|
|
299
|
-
/** The column name used when {@link SearchConfig.column} is not given. */
|
|
300
143
|
var DEFAULT_SEARCH_COLUMN = "search_vector";
|
|
301
|
-
/** The matching strategy used when {@link SearchConfig.mode} is not given. */
|
|
302
144
|
var DEFAULT_SEARCH_MODE = "fts";
|
|
303
|
-
/** The text search configuration used when {@link SearchConfig.language} is not given. */
|
|
304
145
|
var DEFAULT_SEARCH_LANGUAGE = "simple";
|
|
305
|
-
/** The weight a field carries when it does not name one. */
|
|
306
146
|
var DEFAULT_SEARCH_WEIGHT = "B";
|
|
307
|
-
/** The similarity floor used when {@link SearchConfig.fuzzyThreshold} is not given. */
|
|
308
147
|
var DEFAULT_FUZZY_THRESHOLD = .3;
|
|
309
|
-
/**
|
|
310
|
-
* The relevance sort key. Valid only on a collection that declares a
|
|
311
|
-
* {@link SearchConfig} *and* on a query that carries a search string; anywhere
|
|
312
|
-
* else it is an unknown field and the request is refused.
|
|
313
|
-
*/
|
|
314
148
|
var RELEVANCE_SORT_FIELD = "_score";
|
|
315
149
|
//#endregion
|
|
316
150
|
//#region src/types/relations.ts
|
|
317
|
-
/**
|
|
318
|
-
* The key a junction row's own columns are carried under, in both directions.
|
|
319
|
-
*
|
|
320
|
-
* A read that includes a `manyToMany` relation serves each related row with its
|
|
321
|
-
* link's columns nested here — `{ id: 5, name: "ts", _pivot: { role: "owner" } }`
|
|
322
|
-
* — and a membership write may name the same key on an element to state what
|
|
323
|
-
* the link should hold. One constant because the two have to be the same word:
|
|
324
|
-
* a wire name that differs between the read and the write it round-trips
|
|
325
|
-
* through is a shape no client can echo back.
|
|
326
|
-
*
|
|
327
|
-
* Leading underscore, like `_matches`: it reads as metadata about the row
|
|
328
|
-
* rather than as one of its columns. A payload property may not be named
|
|
329
|
-
* `_pivot` either — `checkJunctionPayload` refuses it — so the key means one
|
|
330
|
-
* thing wherever it appears.
|
|
331
|
-
*
|
|
332
|
-
* @group Models
|
|
333
|
-
*/
|
|
334
151
|
var JUNCTION_PIVOT_KEY = "_pivot";
|
|
335
|
-
/**
|
|
336
|
-
* The key a row carries the totals of its counted relations under.
|
|
337
|
-
*
|
|
338
|
-
* An include that asks for a count — `include: { tags: { limit: 4, count: true } }`
|
|
339
|
-
* — serves, beside the (capped) `tags`, how many related rows there are in all:
|
|
340
|
-
* `{ id: 1, tags: [ …4 rows ], _count: { tags: 37 } }`. One object per row,
|
|
341
|
-
* keyed by relation name, so counting a second relation adds a key rather than
|
|
342
|
-
* a second top-level name.
|
|
343
|
-
*
|
|
344
|
-
* Leading underscore, like {@link JUNCTION_PIVOT_KEY} and `_matches`: it
|
|
345
|
-
* describes the read, not the record, and no column or form writes it. A
|
|
346
|
-
* collection with a property of this name cannot ask for a count — the read
|
|
347
|
-
* answers 400 rather than writing over the column.
|
|
348
|
-
*
|
|
349
|
-
* @group Models
|
|
350
|
-
*/
|
|
351
152
|
var INCLUDE_COUNT_KEY = "_count";
|
|
352
|
-
/**
|
|
353
|
-
* The conditions of a join step, as a list: one entry for a plain step, one
|
|
354
|
-
* per alternative for a step that joins on any of several.
|
|
355
|
-
* @group Models
|
|
356
|
-
*/
|
|
357
153
|
function joinConditions(step) {
|
|
358
154
|
return Array.isArray(step.on) ? step.on : [step.on];
|
|
359
155
|
}
|
|
360
|
-
/**
|
|
361
|
-
* The one condition of a step that has no alternatives — for the write paths,
|
|
362
|
-
* which only run on a writable chain and a chain with alternatives never is.
|
|
363
|
-
* Throws rather than pick one of several: writing a link into the wrong column
|
|
364
|
-
* is the mistake read-only exists to prevent.
|
|
365
|
-
* @group Models
|
|
366
|
-
*/
|
|
367
156
|
function soleJoinCondition(step) {
|
|
368
157
|
if (Array.isArray(step.on)) {
|
|
369
158
|
if (step.on.length === 1) return step.on[0];
|
|
@@ -374,62 +163,11 @@ function soleJoinCondition(step) {
|
|
|
374
163
|
}
|
|
375
164
|
//#endregion
|
|
376
165
|
//#region src/types/policy.ts
|
|
377
|
-
/**
|
|
378
|
-
* The id a request without a logged-in user reports as `rebase.uid()`.
|
|
379
|
-
*
|
|
380
|
-
* A user-context request always sets `app.uid`: blank would read back as
|
|
381
|
-
* `NULL`, and `NULL` is how the trusted server context is recognised, so an
|
|
382
|
-
* anonymous visitor would be promoted to server privileges. The driver
|
|
383
|
-
* therefore substitutes this sentinel at the single chokepoint where the GUC
|
|
384
|
-
* is set.
|
|
385
|
-
*
|
|
386
|
-
* The consequence for policy authors is that **`rebase.uid() IS NOT NULL` is a
|
|
387
|
-
* tautology on the user path** — it is true for anonymous visitors too. Use
|
|
388
|
-
* {@link policy.authenticated} to mean "signed in", and
|
|
389
|
-
* {@link policy.serverContext} to mean "the trusted server context". Do not
|
|
390
|
-
* hand-write the comparison: see {@link ANONYMOUS_USER_IDS} for why one
|
|
391
|
-
* literal is not enough.
|
|
392
|
-
*
|
|
393
|
-
* @group Models
|
|
394
|
-
*/
|
|
395
166
|
var ANONYMOUS_USER_ID = "anonymous";
|
|
396
|
-
/**
|
|
397
|
-
* Every uid that has ever meant "nobody is signed in" — newest first.
|
|
398
|
-
*
|
|
399
|
-
* There are two because there were two. The types, the policy compiler, the
|
|
400
|
-
* JavaScript evaluator and the linter were all built on
|
|
401
|
-
* {@link ANONYMOUS_USER_ID}, while the request path scoped unauthenticated
|
|
402
|
-
* callers as `'anon'` — so `policy.authenticated()`, which compiled to
|
|
403
|
-
* `rebase.uid() <> 'anonymous'`, was *true* for an anonymous visitor. The
|
|
404
|
-
* sanctioned way to write "signed in" granted to everyone, and the linter
|
|
405
|
-
* flagged the spelling that actually worked as a foreign convention.
|
|
406
|
-
*
|
|
407
|
-
* The request path now reports {@link ANONYMOUS_USER_ID}. `'anon'` stays here
|
|
408
|
-
* because policies outlive the server that generated them: a database still
|
|
409
|
-
* holding policies from before the fix, or a project whose server has not been
|
|
410
|
-
* upgraded yet, must not become a grant in either direction. Compile against
|
|
411
|
-
* this list, not against a single literal.
|
|
412
|
-
*
|
|
413
|
-
* No real user id is ever one of these, so a match is always "not signed in".
|
|
414
|
-
*
|
|
415
|
-
* @group Models
|
|
416
|
-
*/
|
|
417
167
|
var ANONYMOUS_USER_IDS = [ANONYMOUS_USER_ID, "anon"];
|
|
418
|
-
/**
|
|
419
|
-
* Whether a uid stands for "no one is signed in", in any spelling rebase has
|
|
420
|
-
* used. `null`/`undefined` is the trusted server context, not an anonymous
|
|
421
|
-
* caller, and is therefore **not** anonymous — see {@link ANONYMOUS_USER_ID}.
|
|
422
|
-
*
|
|
423
|
-
* @group Models
|
|
424
|
-
*/
|
|
425
168
|
function isAnonymousUid(uid) {
|
|
426
169
|
return typeof uid === "string" && ANONYMOUS_USER_IDS.includes(uid);
|
|
427
170
|
}
|
|
428
|
-
/**
|
|
429
|
-
* Every `kind` a {@link PolicyExpression} node can have — the discriminator
|
|
430
|
-
* {@link isPolicyShorthand} and {@link isPolicyExpressionKind} read.
|
|
431
|
-
* @group Models
|
|
432
|
-
*/
|
|
433
171
|
var POLICY_EXPRESSION_KINDS = [
|
|
434
172
|
"true",
|
|
435
173
|
"false",
|
|
@@ -445,28 +183,10 @@ var POLICY_EXPRESSION_KINDS = [
|
|
|
445
183
|
"existsIn",
|
|
446
184
|
"raw"
|
|
447
185
|
];
|
|
448
|
-
/**
|
|
449
|
-
* Whether `kind` names a {@link PolicyExpression} node.
|
|
450
|
-
* @group Models
|
|
451
|
-
*/
|
|
452
186
|
function isPolicyExpressionKind(kind) {
|
|
453
187
|
return typeof kind === "string" && POLICY_EXPRESSION_KINDS.includes(kind);
|
|
454
188
|
}
|
|
455
189
|
var isShorthandValue = (value) => value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
456
|
-
/**
|
|
457
|
-
* Whether a rule's `condition` / `check` is a {@link PolicyShorthand} rather
|
|
458
|
-
* than a {@link PolicyExpression}.
|
|
459
|
-
*
|
|
460
|
-
* True only for a plain object with at least one key, none of them `kind`,
|
|
461
|
-
* whose every value is a string, a finite number, a boolean or `null`. Every
|
|
462
|
-
* expression node carries `kind`, so no expression is ever taken for a
|
|
463
|
-
* shorthand — and an object that has a `kind` key is never taken for a
|
|
464
|
-
* shorthand either, whatever its value: such an object is ambiguous (a column
|
|
465
|
-
* called `kind`, or a misspelt node) and the compiler refuses it rather than
|
|
466
|
-
* guessing.
|
|
467
|
-
*
|
|
468
|
-
* @group Models
|
|
469
|
-
*/
|
|
470
190
|
function isPolicyShorthand(value) {
|
|
471
191
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
472
192
|
const proto = Object.getPrototypeOf(value);
|
|
@@ -475,7 +195,6 @@ function isPolicyShorthand(value) {
|
|
|
475
195
|
const entries = Object.entries(value);
|
|
476
196
|
return entries.length > 0 && entries.every(([, v]) => isShorthandValue(v));
|
|
477
197
|
}
|
|
478
|
-
/** @group Models */
|
|
479
198
|
var policy = {
|
|
480
199
|
true: () => ({ kind: "true" }),
|
|
481
200
|
false: () => ({ kind: "false" }),
|
|
@@ -538,291 +257,70 @@ var policy = {
|
|
|
538
257
|
};
|
|
539
258
|
//#endregion
|
|
540
259
|
//#region src/types/rls-functions.ts
|
|
541
|
-
/**
|
|
542
|
-
* The SQL helper functions RLS policies call, and the schema they live in.
|
|
543
|
-
*
|
|
544
|
-
* ## One schema, and it is ours
|
|
545
|
-
*
|
|
546
|
-
* Rebase creates exactly one schema in a project's database: `rebase`. These
|
|
547
|
-
* three functions live in it alongside the framework's own tables, and that is
|
|
548
|
-
* the whole contract — a reader can look at a database and know precisely which
|
|
549
|
-
* namespace belongs to the framework and that nothing else was touched.
|
|
550
|
-
*
|
|
551
|
-
* It used to be two. `uid()`, `jwt()` and `roles()` sat in a schema called
|
|
552
|
-
* `auth`, which is Supabase's name, chosen so that a developer who had written
|
|
553
|
-
* Supabase RLS would recognise `auth.uid()`. The familiarity was real but the
|
|
554
|
-
* name was not Rebase's to take, and taking it had a concrete cost: pointing
|
|
555
|
-
* Rebase at a database that already had a Supabase `auth` schema meant
|
|
556
|
-
* `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` against Supabase's
|
|
557
|
-
* `RETURNS uuid`, which Postgres rejects outright —
|
|
558
|
-
*
|
|
559
|
-
* ERROR: cannot change return type of existing function
|
|
560
|
-
* HINT: Use DROP FUNCTION auth.uid() first.
|
|
561
|
-
*
|
|
562
|
-
* — and the failure landed inside a catch-all that logged a warning and carried
|
|
563
|
-
* on, leaving a database with auth tables, no helper functions, and policies
|
|
564
|
-
* calling functions that did not exist. Under `rebase db migrate` the same
|
|
565
|
-
* statements aborted the migration instead.
|
|
566
|
-
*
|
|
567
|
-
* `rebase.uid()` collides with nobody. A Supabase database keeps its `auth`
|
|
568
|
-
* schema untouched and gains a `rebase` one, which is what a gradual migration
|
|
569
|
-
* needs.
|
|
570
|
-
*
|
|
571
|
-
* ## Why functions at all, rather than inlining `current_setting`
|
|
572
|
-
*
|
|
573
|
-
* Because the indirection has already been spent once. `uid()` resolves
|
|
574
|
-
* `app.uid` and falls back to the pre-rename `app.user_id`, so that during a
|
|
575
|
-
* rolling deploy — old and new pods serving one database — both eras resolve
|
|
576
|
-
* the principal. That was a single `CREATE OR REPLACE`. Inlined into policy
|
|
577
|
-
* bodies it would have been a rewrite of every policy on every table.
|
|
578
|
-
*
|
|
579
|
-
* ## Why the name is not configurable
|
|
580
|
-
*
|
|
581
|
-
* A policy body is stored SQL: Postgres parses `USING (…)` once and keeps it, so
|
|
582
|
-
* these strings are written into every policy in every database Rebase has
|
|
583
|
-
* provisioned. Everything that reads policies back — the SQL-to-policy parser
|
|
584
|
-
* behind the admin UI, the drift checker, `rls-check` — would have to know the
|
|
585
|
-
* configured value to recognise its own output. One frozen name is the feature.
|
|
586
|
-
*/
|
|
587
|
-
/** The schema Rebase owns. The only schema Rebase creates. */
|
|
588
260
|
var REBASE_SCHEMA = "rebase";
|
|
589
|
-
/**
|
|
590
|
-
* The principal of the current request, as text, or NULL in the server context.
|
|
591
|
-
*
|
|
592
|
-
* Never NULL for a user request — an anonymous one carries
|
|
593
|
-
* {@link ANONYMOUS_USER_ID} — which is what makes `IS NULL` a reliable test for
|
|
594
|
-
* the trusted server plane and `IS NOT NULL` a tautology.
|
|
595
|
-
*/
|
|
596
261
|
var RLS_UID_SQL = `${REBASE_SCHEMA}.uid()`;
|
|
597
|
-
/**
|
|
598
|
-
* Is the caller one of this database's request roles? What a permissive
|
|
599
|
-
* policy is ANDed with under `rls.policyTarget: "requestRole"`, so another
|
|
600
|
-
* application's role holding a grant on the table gets nothing from it.
|
|
601
|
-
* `current_user` is passed in — inside the function, which reads the recorded
|
|
602
|
-
* roles with its owner's rights, `current_user` would be the owner — and the
|
|
603
|
-
* sub-select makes it one evaluation per statement, not one per row.
|
|
604
|
-
*/
|
|
605
262
|
var RLS_IS_REQUEST_ROLE_SQL = `(SELECT ${REBASE_SCHEMA}.is_request_role(current_user::text))`;
|
|
606
|
-
/** The request's roles as a comma-separated string, for `string_to_array`. */
|
|
607
263
|
var RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;
|
|
608
|
-
/**
|
|
609
|
-
* The Postgres role that policies granting only the server context or admins
|
|
610
|
-
* are written `TO`: the injected `<table>_default_admin_*` baseline, and any
|
|
611
|
-
* permissive rule whose every clause requires one of the two (`roles: ["admin"]`).
|
|
612
|
-
*
|
|
613
|
-
* Postgres ORs the permissive policies that apply to the current role. Written
|
|
614
|
-
* `TO public`, the baseline applied to every signed-in user too, as
|
|
615
|
-
* `(InitPlan) OR owner_id = (InitPlan)` — and an OR with a per-statement
|
|
616
|
-
* constant arm cannot use the owner index, so a user's owner-scoped list or
|
|
617
|
-
* count scanned the whole table (78 ms against 2.8 ms at 1M rows). Written `TO`
|
|
618
|
-
* this role, the policy is not in a user's plan at all.
|
|
619
|
-
*
|
|
620
|
-
* It holds no privilege and cannot log in: being in it only decides which
|
|
621
|
-
* policies apply, and those still test `rebase.uid() IS NULL` or the `admin`
|
|
622
|
-
* role. Admin requests switch to a request role that inherits it
|
|
623
|
-
* ({@link adminRequestRoleFor}); a connection that is itself subject to RLS
|
|
624
|
-
* inherits it for the server context. One fixed name, so the policy text is the
|
|
625
|
-
* same in every deployment and every generated migration. FROZEN.
|
|
626
|
-
*/
|
|
627
264
|
var REBASE_ADMIN_ROLE = "rebase_admin";
|
|
628
|
-
/**
|
|
629
|
-
* The role the admin request roles ({@link adminRequestRoleFor}) inherit and
|
|
630
|
-
* nothing else does, so an admin-only grant can apply to admin REQUESTS alone.
|
|
631
|
-
*
|
|
632
|
-
* {@link REBASE_ADMIN_ROLE} cannot do that job: the connection inherits it for
|
|
633
|
-
* the server context, and so would any process on it that does not switch
|
|
634
|
-
* roles. Its policies therefore keep their test (`rebase.uid() IS NULL` or the
|
|
635
|
-
* `admin` role) — and any policy expression that is not a constant is a
|
|
636
|
-
* security barrier, behind which Postgres will not evaluate a non-leakproof
|
|
637
|
-
* operator as an index condition. An admin's `tags && $1`, `name ~ $1` or
|
|
638
|
-
* jsonb filter scanned the whole table where the owner's used the index.
|
|
639
|
-
*
|
|
640
|
-
* Each admin-only grant gets a companion `TO` this role `USING (true)`.
|
|
641
|
-
* Postgres folds the OR of the permissive policies to `true` for a member, the
|
|
642
|
-
* barrier goes, and an admin request plans as the owner's does; restrictive
|
|
643
|
-
* policies still apply. Membership is the boundary: only the admin request
|
|
644
|
-
* roles hold it, granted `WITH INHERIT TRUE, SET FALSE`, and only from
|
|
645
|
-
* PostgreSQL 16, whose per-grant INHERIT keeps the connection (which holds
|
|
646
|
-
* those roles `WITH INHERIT FALSE`) out. A boot that finds the connection with
|
|
647
|
-
* its privileges revokes every membership, and the companions admit nobody.
|
|
648
|
-
* One fixed name, as {@link REBASE_ADMIN_ROLE}. FROZEN.
|
|
649
|
-
*/
|
|
650
265
|
var REBASE_ADMIN_REQUEST_ROLE = "rebase_admin_request";
|
|
651
|
-
/**
|
|
652
|
-
* The role an admin request runs as, for a signed-in request role: it inherits
|
|
653
|
-
* that role (its grants and every policy written for it) and
|
|
654
|
-
* {@link REBASE_ADMIN_ROLE}. One per request role rather than the shared
|
|
655
|
-
* `rebase_admin` itself, because roles belong to the cluster: a project with a
|
|
656
|
-
* request role of its own (`rls.requestRole`) would otherwise share its admin
|
|
657
|
-
* access with every other project on the cluster. FROZEN derivation.
|
|
658
|
-
*/
|
|
659
266
|
function adminRequestRoleFor(requestRole) {
|
|
660
267
|
return `${requestRole}_admin`;
|
|
661
268
|
}
|
|
662
|
-
/**
|
|
663
|
-
* Whether a request with these roles passes `rolesOverlap(["admin"])` — the
|
|
664
|
-
* test `string_to_array(rebase.roles(), ',') && ARRAY['admin']` makes of the
|
|
665
|
-
* comma-joined `app.user_roles`, so a role name with a comma in it is split
|
|
666
|
-
* exactly as Postgres splits it.
|
|
667
|
-
*/
|
|
668
269
|
function holdsAdminRole(roles) {
|
|
669
270
|
return roles.join(",").split(",").includes("admin");
|
|
670
271
|
}
|
|
671
|
-
/**
|
|
672
|
-
* Whether the caller is a GUEST — signed in through anonymous sign-in rather
|
|
673
|
-
* than with an account.
|
|
674
|
-
*
|
|
675
|
-
* A different question from {@link ANONYMOUS_USER_ID}, and the two are easy to
|
|
676
|
-
* confuse: that sentinel means "no session at all", while this means "a session
|
|
677
|
-
* with nobody behind it". Anonymous sign-in mints a real user row with a real
|
|
678
|
-
* uid, so before this reached the database the two kinds of caller were one
|
|
679
|
-
* principal inside every policy.
|
|
680
|
-
*/
|
|
681
272
|
var RLS_IS_ANONYMOUS_SQL = `${REBASE_SCHEMA}.is_anonymous()`;
|
|
682
|
-
/** The request's JWT claims as `jsonb`, or `{}`. */
|
|
683
273
|
var RLS_JWT_SQL = `${REBASE_SCHEMA}.jwt()`;
|
|
684
|
-
/**
|
|
685
|
-
* The pre-1.0 spellings, for recognising policies and hand-written SQL that
|
|
686
|
-
* predate the move.
|
|
687
|
-
*
|
|
688
|
-
* Kept because policies outlive the server that wrote them: a database migrated
|
|
689
|
-
* by an older release still holds `auth.uid()` in its policy bodies until the
|
|
690
|
-
* next push or boot recompiles them, and anything that reads policies back has
|
|
691
|
-
* to recognise both eras or report the framework's own output as foreign drift.
|
|
692
|
-
* Also used to give a project whose `securityRules` contain raw `auth.uid()` a
|
|
693
|
-
* message naming the replacement, instead of a parse failure.
|
|
694
|
-
*/
|
|
695
274
|
var LEGACY_RLS_SCHEMA = "auth";
|
|
696
275
|
var LEGACY_RLS_UID_SQL = `${LEGACY_RLS_SCHEMA}.uid()`;
|
|
697
276
|
var LEGACY_RLS_ROLES_SQL = `${LEGACY_RLS_SCHEMA}.roles()`;
|
|
698
277
|
var LEGACY_RLS_JWT_SQL = `${LEGACY_RLS_SCHEMA}.jwt()`;
|
|
699
|
-
/**
|
|
700
|
-
* Rewrites the pre-1.0 function calls in a fragment of policy SQL.
|
|
701
|
-
*
|
|
702
|
-
* Deliberately anchored on a word boundary and the schema qualifier, so a column
|
|
703
|
-
* called `auth_uid` or a table named `auth` is left alone.
|
|
704
|
-
*/
|
|
705
278
|
function rewriteLegacyRlsFunctions(sql) {
|
|
706
279
|
return sql.replace(/\bauth\.(uid|jwt|roles)\s*\(\s*\)/gi, (_match, fn) => `${REBASE_SCHEMA}.${fn.toLowerCase()}()`);
|
|
707
280
|
}
|
|
708
|
-
/** Whether a fragment of SQL still calls the pre-1.0 functions. */
|
|
709
281
|
function usesLegacyRlsFunctions(sql) {
|
|
710
282
|
return /\bauth\.(uid|jwt|roles)\s*\(\s*\)/i.test(sql);
|
|
711
283
|
}
|
|
712
284
|
//#endregion
|
|
713
285
|
//#region src/types/security_rules.ts
|
|
714
|
-
/**
|
|
715
|
-
* Whether a rule is the {@link RedactedSecurityRule} marker the server sends
|
|
716
|
-
* in place of a rule whose SQL it withheld.
|
|
717
|
-
*
|
|
718
|
-
* @group Models
|
|
719
|
-
*/
|
|
720
286
|
function isRedactedSecurityRule(rule) {
|
|
721
287
|
return "redacted" in rule && rule.redacted === true;
|
|
722
288
|
}
|
|
723
289
|
//#endregion
|
|
724
290
|
//#region src/types/tenancy.ts
|
|
725
|
-
/** Narrow a {@link TenantSource} to its claim form. @group Models */
|
|
726
291
|
function isTenantClaimSource(source) {
|
|
727
292
|
return typeof source.claim === "string";
|
|
728
293
|
}
|
|
729
|
-
/** Narrow a {@link TenantSource} to its membership form. @group Models */
|
|
730
294
|
function isTenantMembershipSource(source) {
|
|
731
295
|
return typeof source.membership === "object" && source.membership !== null;
|
|
732
296
|
}
|
|
733
|
-
/**
|
|
734
|
-
* The roles tenancy does not apply to, when the collection names none.
|
|
735
|
-
*
|
|
736
|
-
* `admin`, mirroring the security baseline every collection already carries
|
|
737
|
-
* (`<table>_default_admin_read` / `_write`): the Studio, `dataAsAdmin` and a
|
|
738
|
-
* support operator all run with it, and a tenancy rule that locked them out
|
|
739
|
-
* would make the admin panel show an empty table on a collection full of rows.
|
|
740
|
-
*
|
|
741
|
-
* @group Models
|
|
742
|
-
*/
|
|
743
297
|
var DEFAULT_TENANT_BYPASS_ROLES = ["admin"];
|
|
744
298
|
//#endregion
|
|
745
299
|
//#region src/types/backend.ts
|
|
746
|
-
/**
|
|
747
|
-
* Type guard: can this admin plan a live schema change?
|
|
748
|
-
*
|
|
749
|
-
* Planning is engine-specific — it renders DDL, a Drizzle schema and the
|
|
750
|
-
* declarative SQL artifacts — so the implementation lives in the driver
|
|
751
|
-
* package. The server detects the capability structurally, exactly as it does
|
|
752
|
-
* for SQL, rather than importing an engine it is supposed to know nothing
|
|
753
|
-
* about.
|
|
754
|
-
*
|
|
755
|
-
* @group Admin
|
|
756
|
-
*/
|
|
757
300
|
function isSchemaEditingAdmin(admin) {
|
|
758
301
|
return !!admin && typeof admin.planSchemaChange === "function";
|
|
759
302
|
}
|
|
760
|
-
/**
|
|
761
|
-
* Type guard: does this admin support SQL operations?
|
|
762
|
-
* @group Admin
|
|
763
|
-
*/
|
|
764
303
|
function isSQLAdmin(admin) {
|
|
765
304
|
return !!admin && typeof admin.executeSql === "function";
|
|
766
305
|
}
|
|
767
|
-
/**
|
|
768
|
-
* Type guard: does this admin support schema management?
|
|
769
|
-
* @group Admin
|
|
770
|
-
*/
|
|
771
306
|
function isSchemaAdmin(admin) {
|
|
772
307
|
return !!admin && (typeof admin.fetchUnmappedTables === "function" || typeof admin.fetchTableMetadata === "function");
|
|
773
308
|
}
|
|
774
|
-
/**
|
|
775
|
-
* Type guard: does this admin support database branching?
|
|
776
|
-
* @group Admin
|
|
777
|
-
*/
|
|
778
309
|
function isBranchAdmin(admin) {
|
|
779
310
|
return !!admin && typeof admin.createBranch === "function";
|
|
780
311
|
}
|
|
781
312
|
//#endregion
|
|
782
313
|
//#region src/types/schema_editing.ts
|
|
783
|
-
/**
|
|
784
|
-
* The SQL `db push` and `db generate` render — `schema.sql`, `policies.sql` and
|
|
785
|
-
* the rest — is not here, and must not come back. Both commands regenerate it
|
|
786
|
-
* from the collections before reading it, so nothing ever read a committed
|
|
787
|
-
* copy; it lives in the gitignored `.rebase/sql/`. When the commit carried it,
|
|
788
|
-
* it carried a second copy besides: these paths are from the project root,
|
|
789
|
-
* while the CLI writes beside the backend, so a live edit left `drizzle/` and
|
|
790
|
-
* `backend/drizzle/` disagreeing about the schema.
|
|
791
|
-
*/
|
|
792
314
|
var DEFAULT_COMMIT_PATHS = { schemaFile: "backend/src/schema.generated.ts" };
|
|
793
315
|
//#endregion
|
|
794
316
|
//#region src/types/channel_bus.ts
|
|
795
|
-
/**
|
|
796
|
-
* Whether `setting` is an already-constructed transport rather than a request
|
|
797
|
-
* for a built-in one.
|
|
798
|
-
*
|
|
799
|
-
* Structural rather than nominal so that an instance from a *different copy* of
|
|
800
|
-
* `@rebasepro/types` — an entirely normal outcome of a separately versioned
|
|
801
|
-
* transport package — is still recognised.
|
|
802
|
-
*/
|
|
803
317
|
function isChannelBusInstance(setting) {
|
|
804
318
|
return typeof setting?.publish === "function";
|
|
805
319
|
}
|
|
806
320
|
//#endregion
|
|
807
321
|
//#region src/types/data_source.ts
|
|
808
|
-
/**
|
|
809
|
-
* The default data-source key, used when a collection does not name a
|
|
810
|
-
* `dataSource`. Shared by the frontend router and the backend driver
|
|
811
|
-
* registry so both agree on "the default database".
|
|
812
|
-
* @group Models
|
|
813
|
-
*/
|
|
814
322
|
var DEFAULT_DATA_SOURCE_KEY = "(default)";
|
|
815
|
-
/**
|
|
816
|
-
* Relation kinds assumed filterable when a driver does not say.
|
|
817
|
-
*
|
|
818
|
-
* `belongsTo` alone: its filter is a comparison on a column of the row being
|
|
819
|
-
* filtered, the one shape that needs no query construction a driver might not
|
|
820
|
-
* have. Everything else is a correlated subquery over another table.
|
|
821
|
-
*
|
|
822
|
-
* @group Models
|
|
823
|
-
*/
|
|
824
323
|
var DEFAULT_FILTERABLE_RELATION_KINDS = ["belongsTo"];
|
|
825
|
-
/** @group Models */
|
|
826
324
|
var POSTGRES_CAPABILITIES = {
|
|
827
325
|
key: "postgres",
|
|
828
326
|
label: "PostgreSQL",
|
|
@@ -845,7 +343,6 @@ var POSTGRES_CAPABILITIES = {
|
|
|
845
343
|
supportsSQLAdmin: true,
|
|
846
344
|
supportsSchemaAdmin: true
|
|
847
345
|
};
|
|
848
|
-
/** @group Models */
|
|
849
346
|
var FIREBASE_CAPABILITIES = {
|
|
850
347
|
key: "firestore",
|
|
851
348
|
label: "Firebase / Firestore",
|
|
@@ -863,11 +360,6 @@ var FIREBASE_CAPABILITIES = {
|
|
|
863
360
|
supportsSQLAdmin: false,
|
|
864
361
|
supportsSchemaAdmin: false
|
|
865
362
|
};
|
|
866
|
-
/**
|
|
867
|
-
* Fallback capabilities when the driver is unknown.
|
|
868
|
-
* Enables everything so nothing is hidden unexpectedly.
|
|
869
|
-
* @group Models
|
|
870
|
-
*/
|
|
871
363
|
var DEFAULT_CAPABILITIES = {
|
|
872
364
|
key: "(default)",
|
|
873
365
|
label: "Default",
|
|
@@ -890,13 +382,6 @@ var BUILT_IN_CAPABILITIES = /* @__PURE__ */ new Map([
|
|
|
890
382
|
["firestore", FIREBASE_CAPABILITIES],
|
|
891
383
|
["(default)", DEFAULT_CAPABILITIES]
|
|
892
384
|
]);
|
|
893
|
-
/**
|
|
894
|
-
* Capabilities registered at runtime, on `globalThis` rather than in a module
|
|
895
|
-
* local: a third-party driver inlines its own copy of this package and
|
|
896
|
-
* registers through it, while the app and the server read through theirs. A
|
|
897
|
-
* module local made the registration land in a copy nobody else reads.
|
|
898
|
-
* See `module-state-across-copies.test.ts`.
|
|
899
|
-
*/
|
|
900
385
|
var REGISTERED_CAPABILITIES_KEY = Symbol.for("@rebasepro/types.dataSourceCapabilities.v1");
|
|
901
386
|
function registeredCapabilities() {
|
|
902
387
|
const g = globalThis;
|
|
@@ -907,45 +392,23 @@ function registeredCapabilities() {
|
|
|
907
392
|
}
|
|
908
393
|
return registered;
|
|
909
394
|
}
|
|
910
|
-
/**
|
|
911
|
-
* Look up capabilities for a given engine key.
|
|
912
|
-
* If `engine` is undefined or not found, returns `DEFAULT_CAPABILITIES`.
|
|
913
|
-
* @group Models
|
|
914
|
-
*/
|
|
915
395
|
function getDataSourceCapabilities(engine) {
|
|
916
396
|
if (!engine) return POSTGRES_CAPABILITIES;
|
|
917
397
|
return registeredCapabilities().get(engine) ?? BUILT_IN_CAPABILITIES.get(engine) ?? DEFAULT_CAPABILITIES;
|
|
918
398
|
}
|
|
919
|
-
/**
|
|
920
|
-
* Register custom capabilities for a third-party driver.
|
|
921
|
-
* @group Models
|
|
922
|
-
*/
|
|
923
399
|
function registerDataSourceCapabilities(capabilities) {
|
|
924
400
|
registeredCapabilities().set(capabilities.key, capabilities);
|
|
925
401
|
}
|
|
926
402
|
//#endregion
|
|
927
403
|
//#region src/types/resources.ts
|
|
928
|
-
/** The key a resource takes when a project declares only one of its kind. */
|
|
929
404
|
var DEFAULT_RESOURCE_KEY = "(default)";
|
|
930
405
|
var BRAND = Symbol.for("@rebasepro/types.resource");
|
|
931
|
-
/** Whether a value is a resource handle rather than a plain string key. */
|
|
932
406
|
function isResourceHandle(value) {
|
|
933
407
|
return typeof value === "object" && value !== null && BRAND in value;
|
|
934
408
|
}
|
|
935
|
-
/** The key a resource reference names, whether it is a handle or already a key. */
|
|
936
409
|
function resourceKeyOf(ref) {
|
|
937
410
|
return isResourceHandle(ref) ? ref.key : ref;
|
|
938
411
|
}
|
|
939
|
-
/**
|
|
940
|
-
* Replace every resource handle inside a value with its key, deeply.
|
|
941
|
-
*
|
|
942
|
-
* Applied where authored config becomes data: `defineCollection`, the
|
|
943
|
-
* collection loaders, the derive step. Past that point a collection is plain
|
|
944
|
-
* data that serialises, compares with `===` and reaches the admin UI over the
|
|
945
|
-
* wire, so a handle must not survive into it. Plain objects and arrays are
|
|
946
|
-
* walked; anything else — a function, a Date, a class instance — is a leaf and
|
|
947
|
-
* is returned as it is, which is what keeps callbacks and validators intact.
|
|
948
|
-
*/
|
|
949
412
|
function resolveResourceRefs(value) {
|
|
950
413
|
if (isResourceHandle(value)) return value.key;
|
|
951
414
|
if (Array.isArray(value)) {
|
|
@@ -973,31 +436,6 @@ function resolveResourceRefs(value) {
|
|
|
973
436
|
return value;
|
|
974
437
|
}
|
|
975
438
|
var GLOBAL_KEY = Symbol.for("@rebasepro/types.resourceRegistry");
|
|
976
|
-
/**
|
|
977
|
-
* Where kinds live, versioned — and why the version is in the symbol.
|
|
978
|
-
*
|
|
979
|
-
* Sharing one kinds map across copies means the copy that registers SECOND is
|
|
980
|
-
* the one that runs the comparison. That copy is whatever the bundle happens to
|
|
981
|
-
* carry, which for a driver is a build of this package frozen at its release —
|
|
982
|
-
* so the rule enforced is the rule that shipped THEN, not the one written here.
|
|
983
|
-
*
|
|
984
|
-
* `revision` (390bb03cd, applied to `database` in 346df48e2) was supposed to
|
|
985
|
-
* settle a disagreement between two copies, and it settles it only when the
|
|
986
|
-
* copy doing the arithmetic knows what `revision` is. 0.17.0–0.17.3 do not:
|
|
987
|
-
* they deep-equal the spec and throw. The runtime registers at import and a
|
|
988
|
-
* driver is imported after it, so the old copy is always second, always the
|
|
989
|
-
* judge, and always throws — verified by the bundle corpus on 2026-09-07,
|
|
990
|
-
* which reported v0.17.3's message verbatim ("Two packages cannot define the
|
|
991
|
-
* same kind.", no revision clause) while the runtime it ran on was 0.18.
|
|
992
|
-
*
|
|
993
|
-
* So copies that understand `revision` keep their kinds here, under a symbol
|
|
994
|
-
* no released copy looks at, and the legacy map is left to whoever still wants
|
|
995
|
-
* it. An old copy then registers into a map nobody contests, finds no existing
|
|
996
|
-
* entry, and cannot throw — in any load order, which is what the previous fix
|
|
997
|
-
* only claimed. Bumping this suffix again is how a future change to the
|
|
998
|
-
* REGISTRATION PROTOCOL is made; a change to a kind's own definition is still
|
|
999
|
-
* `revision`, among peers that share this map.
|
|
1000
|
-
*/
|
|
1001
439
|
var KINDS_KEY = Symbol.for("@rebasepro/types.resourceKinds.v2");
|
|
1002
440
|
function registry() {
|
|
1003
441
|
const g = globalThis;
|
|
@@ -1020,16 +458,6 @@ function registry() {
|
|
|
1020
458
|
declarations: shared.declarations
|
|
1021
459
|
};
|
|
1022
460
|
}
|
|
1023
|
-
/**
|
|
1024
|
-
* Every kind visible to this copy: the versioned map, plus anything only a
|
|
1025
|
-
* legacy copy registered.
|
|
1026
|
-
*
|
|
1027
|
-
* The fallback is not for Rebase's own kinds — this copy defines all of those —
|
|
1028
|
-
* but for a third-party driver built against an older `@rebasepro/types` that
|
|
1029
|
-
* registers a kind of its own. Dropping it would make that kind invisible and
|
|
1030
|
-
* turn `declareResource` into "unknown resource kind" for something genuinely
|
|
1031
|
-
* registered.
|
|
1032
|
-
*/
|
|
1033
461
|
function visibleKinds() {
|
|
1034
462
|
const { kinds, legacyKinds } = registry();
|
|
1035
463
|
if (legacyKinds.size === 0) return kinds;
|
|
@@ -1038,19 +466,12 @@ function visibleKinds() {
|
|
|
1038
466
|
return merged;
|
|
1039
467
|
}
|
|
1040
468
|
var amendments = /* @__PURE__ */ new Map();
|
|
1041
|
-
/**
|
|
1042
|
-
* Correct a registered kind without touching its registered literal.
|
|
1043
|
-
*
|
|
1044
|
-
* Use this, never an edit to the literal, for a kind that has shipped in a
|
|
1045
|
-
* published package. The amendment applies to reads through this copy only.
|
|
1046
|
-
*/
|
|
1047
469
|
function amendResourceKind(kind, amendment) {
|
|
1048
470
|
amendments.set(kind, {
|
|
1049
471
|
...amendments.get(kind),
|
|
1050
472
|
...amendment
|
|
1051
473
|
});
|
|
1052
474
|
}
|
|
1053
|
-
/** A registered kind as this copy sees it: the shared literal plus this copy's amendments. */
|
|
1054
475
|
function effectiveKind(spec) {
|
|
1055
476
|
const amendment = amendments.get(spec.kind);
|
|
1056
477
|
return amendment ? {
|
|
@@ -1058,25 +479,9 @@ function effectiveKind(spec) {
|
|
|
1058
479
|
...amendment
|
|
1059
480
|
} : spec;
|
|
1060
481
|
}
|
|
1061
|
-
/** `kind:key`, the graph's primary key. */
|
|
1062
482
|
function declarationId(kind, key) {
|
|
1063
483
|
return `${kind}:${key}`;
|
|
1064
484
|
}
|
|
1065
|
-
/**
|
|
1066
|
-
* Register a resource kind.
|
|
1067
|
-
*
|
|
1068
|
-
* Idempotent for an identical spec. When a spec for the same kind is already
|
|
1069
|
-
* registered and differs, the `revision` decides: the higher one is kept and
|
|
1070
|
-
* the other copy is warned about, in either load order. Two different specs at
|
|
1071
|
-
* the SAME revision are a genuine conflict — two packages defining one kind, or
|
|
1072
|
-
* a change that forgot to bump — and still throw.
|
|
1073
|
-
*
|
|
1074
|
-
* Both copies in that comparison are peers on `KINDS_KEY`, which is what makes
|
|
1075
|
-
* the rule enforceable: a copy old enough not to know `revision` writes to the
|
|
1076
|
-
* legacy map instead and never reaches this function's arithmetic. Registering
|
|
1077
|
-
* a kind an older copy already put in the legacy map is therefore not a
|
|
1078
|
-
* conflict — it is the ordinary case, and `visibleKinds` prefers this one.
|
|
1079
|
-
*/
|
|
1080
485
|
function registerResourceKind(spec) {
|
|
1081
486
|
const kinds = registry().kinds;
|
|
1082
487
|
const existing = kinds.get(spec.kind);
|
|
@@ -1090,13 +495,11 @@ function registerResourceKind(spec) {
|
|
|
1090
495
|
if (have === incoming) throw new Error(`Resource kind "${spec.kind}" is already registered with a different definition at revision ${have}. Two packages cannot define the same kind; a newer definition of the same kind must carry a higher \`revision\`.`);
|
|
1091
496
|
const [kept, dropped] = incoming > have ? [spec, existing] : [existing, spec];
|
|
1092
497
|
if (kept === spec) kinds.set(spec.kind, spec);
|
|
1093
|
-
console.warn(`[resources] Resource kind "${spec.kind}" is registered twice, at revisions ${dropped.revision ?? 0} and ${kept.revision ?? 0}; keeping revision ${kept.revision ?? 0}. The older copy is usually @rebasepro/types inlined in a driver built before the kind changed
|
|
498
|
+
console.warn(`[resources] Resource kind "${spec.kind}" is registered twice, at revisions ${dropped.revision ?? 0} and ${kept.revision ?? 0}; keeping revision ${kept.revision ?? 0}. The older copy is usually @rebasepro/types inlined in a driver built before the kind changed \u2014 rebuild the project with a current driver to remove it.`);
|
|
1094
499
|
}
|
|
1095
|
-
/** Every registered kind, for validators and for `rebase doctor`. */
|
|
1096
500
|
function resourceKinds() {
|
|
1097
501
|
return [...visibleKinds().values()].map(effectiveKind);
|
|
1098
502
|
}
|
|
1099
|
-
/** One registered kind, or undefined. */
|
|
1100
503
|
function resourceKind(kind) {
|
|
1101
504
|
const spec = visibleKinds().get(kind);
|
|
1102
505
|
return spec && effectiveKind(spec);
|
|
@@ -1106,19 +509,9 @@ var COMMON_OPTION_KEYS = [
|
|
|
1106
509
|
"transport",
|
|
1107
510
|
"label"
|
|
1108
511
|
];
|
|
1109
|
-
/** Whether an engine is one the kind knows, or an explicit `custom:` opt-out. */
|
|
1110
512
|
function isValidEngine(spec, engine) {
|
|
1111
513
|
return engine.startsWith("custom:") || spec.engines.includes(engine);
|
|
1112
514
|
}
|
|
1113
|
-
/**
|
|
1114
|
-
* Declare a resource. The primitive every kind's constructor is built from.
|
|
1115
|
-
*
|
|
1116
|
-
* Redeclaring the same `kind:key` with a *different* shape throws rather than
|
|
1117
|
-
* merging. Merging is what the old storage path did, and it silently discarded
|
|
1118
|
-
* one of the two engines — a declaration accepted and then ignored, which is
|
|
1119
|
-
* the failure this whole model exists to remove. Redeclaring it identically is
|
|
1120
|
-
* fine: a config module evaluated twice must not be an error.
|
|
1121
|
-
*/
|
|
1122
515
|
function declareResource(kind, key = DEFAULT_RESOURCE_KEY, options = {}) {
|
|
1123
516
|
const spec = resourceKind(kind);
|
|
1124
517
|
if (!spec) {
|
|
@@ -1144,7 +537,7 @@ function declareResource(kind, key = DEFAULT_RESOURCE_KEY, options = {}) {
|
|
|
1144
537
|
const id = declarationId(kind, key);
|
|
1145
538
|
const previous = registry().declarations.get(id);
|
|
1146
539
|
if (previous) {
|
|
1147
|
-
if (JSON.stringify(previous) !== JSON.stringify(declaration)) throw new Error(`${kind} "${key}" is declared twice with different configuration. Declare it once and export it
|
|
540
|
+
if (JSON.stringify(previous) !== JSON.stringify(declaration)) throw new Error(`${kind} "${key}" is declared twice with different configuration. Declare it once and export it \u2014 two declarations of one resource is the ambiguity this model exists to remove, so it is refused rather than merged.`);
|
|
1148
541
|
} else registry().declarations.set(id, declaration);
|
|
1149
542
|
return {
|
|
1150
543
|
...declaration,
|
|
@@ -1154,40 +547,17 @@ function declareResource(kind, key = DEFAULT_RESOURCE_KEY, options = {}) {
|
|
|
1154
547
|
[BRAND]: true
|
|
1155
548
|
};
|
|
1156
549
|
}
|
|
1157
|
-
/** Every declared resource, in declaration order, optionally filtered by kind. */
|
|
1158
550
|
function declaredResources(kind) {
|
|
1159
551
|
const all = [...registry().declarations.values()];
|
|
1160
552
|
return kind ? all.filter((r) => r.kind === kind) : all;
|
|
1161
553
|
}
|
|
1162
|
-
/**
|
|
1163
|
-
* Forget every declaration, keeping registered kinds.
|
|
1164
|
-
*
|
|
1165
|
-
* For tests and for a CLI that evaluates more than one project in a process.
|
|
1166
|
-
* Kinds survive because they are registered by module import, which will not
|
|
1167
|
-
* happen a second time.
|
|
1168
|
-
*/
|
|
1169
554
|
function resetDeclaredResources() {
|
|
1170
555
|
registry().declarations.clear();
|
|
1171
556
|
}
|
|
1172
|
-
/**
|
|
1173
|
-
* The env-var suffix a resource's bindings use: `__ANALYTICS` for `analytics`,
|
|
1174
|
-
* and nothing at all for the default-keyed one.
|
|
1175
|
-
*
|
|
1176
|
-
* The default takes no suffix so that a project with one database configured
|
|
1177
|
-
* through plain `DATABASE_URL` keeps working having declared nothing — the
|
|
1178
|
-
* overwhelmingly common project must not have to say so.
|
|
1179
|
-
*/
|
|
1180
557
|
function resourceEnvSuffix(key) {
|
|
1181
558
|
if (key === "(default)") return "";
|
|
1182
559
|
return `__${key.toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, "")}`;
|
|
1183
560
|
}
|
|
1184
|
-
/**
|
|
1185
|
-
* Two resources of a kind whose keys differ but whose env suffixes do not.
|
|
1186
|
-
*
|
|
1187
|
-
* `media-files` and `media_files` both become `__MEDIA_FILES`, so one would
|
|
1188
|
-
* silently read the other's configuration. Returned rather than thrown so the
|
|
1189
|
-
* caller can report it with the rest of a validation pass.
|
|
1190
|
-
*/
|
|
1191
561
|
function findEnvSuffixCollision(keys) {
|
|
1192
562
|
const seen = /* @__PURE__ */ new Map();
|
|
1193
563
|
for (const key of keys) {
|
|
@@ -1202,15 +572,7 @@ function findEnvSuffixCollision(keys) {
|
|
|
1202
572
|
}
|
|
1203
573
|
return null;
|
|
1204
574
|
}
|
|
1205
|
-
/** The current graph format version. */
|
|
1206
575
|
var RESOURCE_GRAPH_VERSION = 1;
|
|
1207
|
-
/**
|
|
1208
|
-
* Build a graph from the current declarations, sorted for a stable diff.
|
|
1209
|
-
*
|
|
1210
|
-
* `usedBy` maps a `kind:key` id to the things that reach it. The derive step
|
|
1211
|
-
* supplies it after evaluating collections; a runtime building the graph at
|
|
1212
|
-
* boot passes nothing and gets declarations alone, which is all it binds from.
|
|
1213
|
-
*/
|
|
1214
576
|
function buildResourceGraph(usedBy) {
|
|
1215
577
|
return {
|
|
1216
578
|
version: 1,
|
|
@@ -1223,17 +585,9 @@ function buildResourceGraph(usedBy) {
|
|
|
1223
585
|
})
|
|
1224
586
|
};
|
|
1225
587
|
}
|
|
1226
|
-
/** `kind:key`, the id `usedBy` maps are keyed by. Exported for the derive step. */
|
|
1227
588
|
function resourceId(kind, key) {
|
|
1228
589
|
return declarationId(kind, key);
|
|
1229
590
|
}
|
|
1230
|
-
/**
|
|
1231
|
-
* The environment variables worth writing for a resource, given its engine.
|
|
1232
|
-
*
|
|
1233
|
-
* Falls back to every base the kind reads when the engine is unknown — a
|
|
1234
|
-
* `custom:` engine gets the full list rather than an empty one, because
|
|
1235
|
-
* guessing narrow would silently omit the variable it actually needs.
|
|
1236
|
-
*/
|
|
1237
591
|
function envBasesForResource(declaration) {
|
|
1238
592
|
const spec = resourceKind(declaration.kind);
|
|
1239
593
|
if (!spec) return [];
|
|
@@ -1241,62 +595,13 @@ function envBasesForResource(declaration) {
|
|
|
1241
595
|
}
|
|
1242
596
|
//#endregion
|
|
1243
597
|
//#region src/types/storage_source.ts
|
|
1244
|
-
/**
|
|
1245
|
-
* Describes a named storage backend — a place files live.
|
|
1246
|
-
*
|
|
1247
|
-
* Declared once and shared front + back: the frontend uses it to decide
|
|
1248
|
-
* transport (HTTP proxy vs direct SDK), the backend uses the same `key`
|
|
1249
|
-
* to resolve a StorageController, and collection properties reference
|
|
1250
|
-
* a definition by its `key` via `StorageConfig.storageSource`.
|
|
1251
|
-
*
|
|
1252
|
-
* This mirrors the {@link DataSourceDefinition} pattern used for databases.
|
|
1253
|
-
*
|
|
1254
|
-
* @group Models
|
|
1255
|
-
*/
|
|
1256
|
-
/**
|
|
1257
|
-
* The default storage source key, used when a property does not specify
|
|
1258
|
-
* a `storageSource`. Shared by the frontend and backend registries so
|
|
1259
|
-
* both agree on "the default storage backend".
|
|
1260
|
-
* @group Models
|
|
1261
|
-
*/
|
|
1262
598
|
var DEFAULT_STORAGE_SOURCE_KEY = "(default)";
|
|
1263
|
-
/**
|
|
1264
|
-
* The environment-variable suffix for a storage or data source key.
|
|
1265
|
-
*
|
|
1266
|
-
* `""` for the default source — so a single-bucket project keeps configuring
|
|
1267
|
-
* plain `S3_BUCKET` — and `__<KEY>` for every named one, uppercased with
|
|
1268
|
-
* non-alphanumerics collapsed to underscores: `media-cdn` → `S3_BUCKET__MEDIA_CDN`.
|
|
1269
|
-
*
|
|
1270
|
-
* The rule derives the variable name from the declared key rather than
|
|
1271
|
-
* discovering keys by scanning the environment. Scanning would have to guess how
|
|
1272
|
-
* `S3_BUCKET__MEDIA_CDN` splits into a key; deriving cannot be ambiguous, and a
|
|
1273
|
-
* typo surfaces as a missing source at boot instead of a silently ignored
|
|
1274
|
-
* variable.
|
|
1275
|
-
*
|
|
1276
|
-
* It lives in this package, with no dependencies, because four things must agree
|
|
1277
|
-
* on it exactly: the CLI (validating a build), the runtime (reading its own
|
|
1278
|
-
* environment), the control plane (writing a tenant's Secret), and the docs. A
|
|
1279
|
-
* second implementation of a naming convention is a second chance to disagree.
|
|
1280
|
-
*
|
|
1281
|
-
* @group Models
|
|
1282
|
-
*/
|
|
1283
599
|
function storageEnvSuffix(key, defaultKey = DEFAULT_STORAGE_SOURCE_KEY) {
|
|
1284
600
|
if (!key || key === defaultKey) return "";
|
|
1285
601
|
const normalized = key.replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").toUpperCase();
|
|
1286
602
|
if (!normalized) throw new Error(`Source key "${key}" cannot be turned into an environment variable name. Use a key containing at least one letter or digit.`);
|
|
1287
603
|
return `__${normalized}`;
|
|
1288
604
|
}
|
|
1289
|
-
/**
|
|
1290
|
-
* Two distinct keys that collapse onto the same variable name, or `null`.
|
|
1291
|
-
*
|
|
1292
|
-
* `media-cdn` and `media_cdn` are different source keys but the same suffix, so
|
|
1293
|
-
* without this one of them silently reads the other's configuration. Returns the
|
|
1294
|
-
* offending pair rather than throwing, so each caller can raise it in its own
|
|
1295
|
-
* idiom — a `BundleError` at boot, a build failure in the CLI, a rejected deploy
|
|
1296
|
-
* in a control plane.
|
|
1297
|
-
*
|
|
1298
|
-
* @group Models
|
|
1299
|
-
*/
|
|
1300
605
|
function findStorageSuffixCollision(keys, defaultKey = DEFAULT_STORAGE_SOURCE_KEY) {
|
|
1301
606
|
const seen = /* @__PURE__ */ new Map();
|
|
1302
607
|
for (const key of keys) {
|
|
@@ -1313,19 +618,6 @@ function findStorageSuffixCollision(keys, defaultKey = DEFAULT_STORAGE_SOURCE_KE
|
|
|
1313
618
|
}
|
|
1314
619
|
//#endregion
|
|
1315
620
|
//#region src/types/resource_kinds.ts
|
|
1316
|
-
/**
|
|
1317
|
-
* The kinds Rebase ships, and the constructors a project declares them with.
|
|
1318
|
-
*
|
|
1319
|
-
* Each kind is registered rather than hardcoded, so a fourth one arrives
|
|
1320
|
-
* without editing a manifest schema, a validator and a switch statement. That
|
|
1321
|
-
* cost is precisely why databases and buckets ended up declared in different
|
|
1322
|
-
* files with different rules — the cheapest thing to do was always to bolt the
|
|
1323
|
-
* new kind onto whichever home was nearest.
|
|
1324
|
-
*
|
|
1325
|
-
* A kind owns its engine list. `custom:<id>` is always accepted, so a build
|
|
1326
|
-
* that ships an engine this package has never heard of says so at the call site
|
|
1327
|
-
* instead of looking like a typo of one that exists.
|
|
1328
|
-
*/
|
|
1329
621
|
registerResourceKind({
|
|
1330
622
|
revision: 1,
|
|
1331
623
|
kind: "database",
|
|
@@ -1370,18 +662,6 @@ amendResourceKind("database", {
|
|
|
1370
662
|
function database(keyOrOptions = DEFAULT_RESOURCE_KEY, options = {}) {
|
|
1371
663
|
return typeof keyOrOptions === "string" ? declareResource("database", keyOrOptions, options) : declareResource("database", DEFAULT_RESOURCE_KEY, keyOrOptions);
|
|
1372
664
|
}
|
|
1373
|
-
/**
|
|
1374
|
-
* The extensions the project's databases gave Rebase leave to install.
|
|
1375
|
-
*
|
|
1376
|
-
* A flat union rather than a per-database answer, because the surfaces that ask
|
|
1377
|
-
* — `rebase db push` and the boot schema-ensure — drive one connection and
|
|
1378
|
-
* generate one `schema.sql` for every collection regardless of `dataSource`.
|
|
1379
|
-
* Splitting the permission by data source would be a distinction the rest of
|
|
1380
|
-
* that pipeline does not make, and a false precision is worse than none.
|
|
1381
|
-
*
|
|
1382
|
-
* Empty for a project that declared nothing, which is every project that has
|
|
1383
|
-
* not opted in — so this reads as a refusal by default, on purpose.
|
|
1384
|
-
*/
|
|
1385
665
|
function declaredDatabaseExtensions() {
|
|
1386
666
|
const names = /* @__PURE__ */ new Set();
|
|
1387
667
|
for (const declaration of declaredResources("database")) {
|
|
@@ -1391,21 +671,10 @@ function declaredDatabaseExtensions() {
|
|
|
1391
671
|
}
|
|
1392
672
|
return [...names].sort();
|
|
1393
673
|
}
|
|
1394
|
-
/** The `rls` options a database declaration gave, `{}` when it gave none or was never declared. */
|
|
1395
674
|
function declaredDatabaseRls(key = DEFAULT_DATA_SOURCE_KEY) {
|
|
1396
675
|
const rls = declaredResources("database").find((d) => d.key === key)?.options.rls;
|
|
1397
676
|
return rls && typeof rls === "object" ? rls : {};
|
|
1398
677
|
}
|
|
1399
|
-
/**
|
|
1400
|
-
* The policy settings every compile path must agree on — the boot's policy
|
|
1401
|
-
* ensure, `rebase db generate`, the drift check — read from the one place all
|
|
1402
|
-
* of them can see: the database declaration, with `REBASE_RLS_POLICY_TARGET` /
|
|
1403
|
-
* `REBASE_RLS_ADMIN_POLICIES` / `REBASE_RLS_DEFAULT_POLICIES` over it. Defaults
|
|
1404
|
-
* are what Rebase compiled before these existed, except `adminPolicies`, whose
|
|
1405
|
-
* default (`"adminRole"`) changed what the server-or-admin policies are `TO`.
|
|
1406
|
-
*
|
|
1407
|
-
* Browser-safe: where there is no `process`, only the declaration counts.
|
|
1408
|
-
*/
|
|
1409
678
|
function declaredRlsPolicyShape(dataSource = DEFAULT_DATA_SOURCE_KEY) {
|
|
1410
679
|
const declared = declaredDatabaseRls(dataSource);
|
|
1411
680
|
const env = typeof process !== "undefined" ? process.env : void 0;
|
|
@@ -1514,26 +783,6 @@ registerResourceKind({
|
|
|
1514
783
|
implicitDefault: false
|
|
1515
784
|
});
|
|
1516
785
|
amendResourceKind("topic", { envBases: [] });
|
|
1517
|
-
/**
|
|
1518
|
-
* Declared handlers and installed runtimes, for topics and queues — on
|
|
1519
|
-
* `globalThis` under a shared symbol, never in module locals.
|
|
1520
|
-
*
|
|
1521
|
-
* A module local is one per COPY of this package, and two copies in one
|
|
1522
|
-
* process is the normal layout rather than an accident: `@rebasepro/server`
|
|
1523
|
-
* inlines this package into its own dist, while `config/resources.ts` imports
|
|
1524
|
-
* it from `node_modules`. With locals, a project's `.handler()` and
|
|
1525
|
-
* `.subscription()` went into the project's copy and the worker read the
|
|
1526
|
-
* server's empty one (`Job queue started {"tasks":0}`), and the runtime the
|
|
1527
|
-
* server installed was invisible to the project's `enqueue`/`publish` — so
|
|
1528
|
-
* every queue and topic threw "no runtime is installed" inside a running
|
|
1529
|
-
* backend. The CLI deriving the graph had the same split. Same mechanism and
|
|
1530
|
-
* reasoning as `registry()` in resources.ts; `module-state-across-copies.test.ts`
|
|
1531
|
-
* loads two copies to hold it, and scans for any other module-level state that
|
|
1532
|
-
* would split the same way.
|
|
1533
|
-
*
|
|
1534
|
-
* The version is in the symbol: a change to this object's SHAPE takes a new
|
|
1535
|
-
* suffix, so no copy ever reads a shape it does not know.
|
|
1536
|
-
*/
|
|
1537
786
|
var WORK_KEY = Symbol.for("@rebasepro/types.workRegistry.v1");
|
|
1538
787
|
function work() {
|
|
1539
788
|
const g = globalThis;
|
|
@@ -1549,48 +798,21 @@ function work() {
|
|
|
1549
798
|
}
|
|
1550
799
|
return shared;
|
|
1551
800
|
}
|
|
1552
|
-
/**
|
|
1553
|
-
* Where `@rebasepro/server` publishes its client once it has booted (its
|
|
1554
|
-
* `singleton.ts`). Read only to tell the two causes of a missing runtime apart.
|
|
1555
|
-
*/
|
|
1556
801
|
var SERVER_INSTANCE_SLOT = Symbol.for("@rebasepro/server:singleton-instance");
|
|
1557
|
-
/**
|
|
1558
|
-
* Why there is no runtime to send through, as far as this process can tell.
|
|
1559
|
-
*
|
|
1560
|
-
* Outside a backend — the CLI evaluating config, a script, a unit test — the
|
|
1561
|
-
* answer is that there is nothing to deliver to. Inside one it is not: the
|
|
1562
|
-
* backend installs a runtime at boot for what `config/resources.ts` declared,
|
|
1563
|
-
* so a missing one there means boot never saw the declaration, or the backend
|
|
1564
|
-
* carries a copy of this package too old to share the slot it installs into.
|
|
1565
|
-
* Saying "outside a backend" to somebody whose backend is running sends them
|
|
1566
|
-
* looking for the wrong thing.
|
|
1567
|
-
*/
|
|
1568
802
|
function missingRuntimeCause(kind) {
|
|
1569
803
|
if (!(globalThis[SERVER_INSTANCE_SLOT] != null)) return "This works inside a running Rebase backend; this looks like code running outside one (a build, a script, or a test without a harness).";
|
|
1570
|
-
return `A Rebase backend is running in this process but installed no ${kind} runtime. It installs one at boot when config/resources.ts declares a ${kind}, so either this ${kind} is declared somewhere boot does not read, or the backend's copy of @rebasepro/types predates the shared runtime slot this copy reads
|
|
804
|
+
return `A Rebase backend is running in this process but installed no ${kind} runtime. It installs one at boot when config/resources.ts declares a ${kind}, so either this ${kind} is declared somewhere boot does not read, or the backend's copy of @rebasepro/types predates the shared runtime slot this copy reads \u2014 keep @rebasepro/server and @rebasepro/types on the same version.`;
|
|
1571
805
|
}
|
|
1572
|
-
/** Install the transport topics publish through. Called by the server at boot. */
|
|
1573
806
|
function setTopicRuntime(runtime) {
|
|
1574
807
|
work().topicRuntime = runtime;
|
|
1575
808
|
}
|
|
1576
|
-
/** Every declared subscription, for the worker to wire and the graph to record. */
|
|
1577
809
|
function declaredSubscriptions(topic) {
|
|
1578
810
|
const { subscriptions } = work();
|
|
1579
811
|
return topic ? subscriptions.filter((s) => s.topic === topic) : subscriptions.slice();
|
|
1580
812
|
}
|
|
1581
|
-
/** Forget declared subscriptions. For tests, alongside `resetDeclaredResources`. */
|
|
1582
813
|
function resetDeclaredSubscriptions() {
|
|
1583
814
|
work().subscriptions.length = 0;
|
|
1584
815
|
}
|
|
1585
|
-
/**
|
|
1586
|
-
* Declare a topic.
|
|
1587
|
-
*
|
|
1588
|
-
* ```ts
|
|
1589
|
-
* export const signups = topic<{ userId: string }>("signups");
|
|
1590
|
-
* signups.subscription("send-welcome", async (event) => { … });
|
|
1591
|
-
* await signups.publish({ userId });
|
|
1592
|
-
* ```
|
|
1593
|
-
*/
|
|
1594
816
|
function topic(key, options = {}) {
|
|
1595
817
|
if (options.delivery === "at-most-once") throw new Error(`Topic "${key}" asks for at-most-once delivery, which no shipped transport implements. The durable queue behind topics retries, so it is at-least-once and a handler must tolerate seeing an event twice. Refused rather than quietly given the other guarantee.`);
|
|
1596
818
|
return {
|
|
@@ -1631,17 +853,8 @@ registerResourceKind({
|
|
|
1631
853
|
],
|
|
1632
854
|
implicitDefault: false
|
|
1633
855
|
});
|
|
1634
|
-
/**
|
|
1635
|
-
* Declare a cron, as the scheduler's `defineCron` does on its way through.
|
|
1636
|
-
*
|
|
1637
|
-
* Projects do not call this: `defineCron` in `@rebasepro/server` does, so a
|
|
1638
|
-
* cron file is both the handler and the declaration — one file, one name, and
|
|
1639
|
-
* the graph derived from it says what a host needs to know without evaluating
|
|
1640
|
-
* the handler. Exported so the derive step and the scheduler spell the
|
|
1641
|
-
* declaration identically.
|
|
1642
|
-
*/
|
|
1643
856
|
function declareCron(name, options) {
|
|
1644
|
-
if (typeof options.schedule !== "string" || options.schedule.trim() === "") throw new Error(`Cron "${name}" needs a schedule
|
|
857
|
+
if (typeof options.schedule !== "string" || options.schedule.trim() === "") throw new Error(`Cron "${name}" needs a schedule \u2014 a five-field cron expression such as "0 3 * * *".`);
|
|
1645
858
|
return declareResource("cron", name, options);
|
|
1646
859
|
}
|
|
1647
860
|
registerResourceKind({
|
|
@@ -1656,7 +869,6 @@ registerResourceKind({
|
|
|
1656
869
|
],
|
|
1657
870
|
implicitDefault: false
|
|
1658
871
|
});
|
|
1659
|
-
/** Declare a function. Called by the derive step, not by projects. */
|
|
1660
872
|
function declareFunction(name, options = {}) {
|
|
1661
873
|
return declareResource("function", name, options);
|
|
1662
874
|
}
|
|
@@ -1668,31 +880,15 @@ registerResourceKind({
|
|
|
1668
880
|
optionKeys: ["maxAttempts"],
|
|
1669
881
|
implicitDefault: false
|
|
1670
882
|
});
|
|
1671
|
-
/** Install the transport queues enqueue through. Called by the server at boot. */
|
|
1672
883
|
function setQueueRuntime(runtime) {
|
|
1673
884
|
work().queueRuntime = runtime;
|
|
1674
885
|
}
|
|
1675
|
-
/** Every declared queue handler, for the worker to wire. */
|
|
1676
886
|
function declaredQueueConsumers() {
|
|
1677
887
|
return [...work().queueConsumers.values()];
|
|
1678
888
|
}
|
|
1679
|
-
/** Forget declared queue handlers. For tests, alongside `resetDeclaredResources`. */
|
|
1680
889
|
function resetDeclaredQueueConsumers() {
|
|
1681
890
|
work().queueConsumers.clear();
|
|
1682
891
|
}
|
|
1683
|
-
/**
|
|
1684
|
-
* Declare a queue.
|
|
1685
|
-
*
|
|
1686
|
-
* ```ts
|
|
1687
|
-
* export const thumbnails = queue<{ key: string }>("thumbnails");
|
|
1688
|
-
* thumbnails.handler(async ({ key }) => { … });
|
|
1689
|
-
* await thumbnails.enqueue({ key }, { runAt: new Date(Date.now() + 60_000) });
|
|
1690
|
-
* ```
|
|
1691
|
-
*
|
|
1692
|
-
* The difference from a topic is the number of consumers: a queue has one, a
|
|
1693
|
-
* topic fans out to every subscription. Both ride on the durable job queue, so
|
|
1694
|
-
* declaring either turns it on.
|
|
1695
|
-
*/
|
|
1696
892
|
function queue(key, options = {}) {
|
|
1697
893
|
return {
|
|
1698
894
|
...declareResource("queue", key, options),
|
|
@@ -1714,21 +910,6 @@ function queue(key, options = {}) {
|
|
|
1714
910
|
}
|
|
1715
911
|
};
|
|
1716
912
|
}
|
|
1717
|
-
/**
|
|
1718
|
-
* One declaration, as the data layer's definition.
|
|
1719
|
-
*
|
|
1720
|
-
* There is exactly one of these per kind, and everything that needs a
|
|
1721
|
-
* definition goes through it — the frontend, the managed runtime's boot path,
|
|
1722
|
-
* and an ejected project's own entrypoint. That is not tidiness: the mapping
|
|
1723
|
-
* used to exist twice, once here and once in `@rebasepro/server`'s
|
|
1724
|
-
* `graphToStorageSources`, and the two disagreed. The server's copy carried a
|
|
1725
|
-
* bucket's `account`; this one dropped it, so a bucket declared with shared
|
|
1726
|
-
* credentials resolved them on the managed runtime and resolved *nothing* in an
|
|
1727
|
-
* ejected backend — the source was skipped and every upload to it answered 501.
|
|
1728
|
-
*
|
|
1729
|
-
* A field-by-field map is one line away from that failure at all times, so
|
|
1730
|
-
* there is now one line to keep right instead of two to keep equal.
|
|
1731
|
-
*/
|
|
1732
913
|
function resourceToDataSource(declaration) {
|
|
1733
914
|
return {
|
|
1734
915
|
key: declaration.key === "(default)" ? DEFAULT_DATA_SOURCE_KEY : declaration.key,
|
|
@@ -1738,7 +919,6 @@ function resourceToDataSource(declaration) {
|
|
|
1738
919
|
...declaration.label !== void 0 ? { label: declaration.label } : {}
|
|
1739
920
|
};
|
|
1740
921
|
}
|
|
1741
|
-
/** One declaration, as the storage layer's definition. See {@link resourceToDataSource}. */
|
|
1742
922
|
function resourceToStorageSource(declaration) {
|
|
1743
923
|
return {
|
|
1744
924
|
key: declaration.key === "(default)" ? DEFAULT_STORAGE_SOURCE_KEY : declaration.key,
|
|
@@ -1750,12 +930,6 @@ function resourceToStorageSource(declaration) {
|
|
|
1750
930
|
...declaration.label !== void 0 ? { label: declaration.label } : {}
|
|
1751
931
|
};
|
|
1752
932
|
}
|
|
1753
|
-
/**
|
|
1754
|
-
* A bucket's `orphanSweep` option as a definition carries it: `true` is the
|
|
1755
|
-
* defaults, an object keeps only the fields of the right type. The runtime
|
|
1756
|
-
* checks the values (the grace-period floor, the schedule) and refuses a bad
|
|
1757
|
-
* one loudly; this only refuses to invent one.
|
|
1758
|
-
*/
|
|
1759
933
|
function orphanSweepOf(option) {
|
|
1760
934
|
if (option === true) return { orphanSweep: {} };
|
|
1761
935
|
if (!option || typeof option !== "object") return {};
|
|
@@ -1765,31 +939,9 @@ function orphanSweepOf(option) {
|
|
|
1765
939
|
...typeof schedule === "string" ? { schedule } : {}
|
|
1766
940
|
} };
|
|
1767
941
|
}
|
|
1768
|
-
/**
|
|
1769
|
-
* The declared databases, as definitions.
|
|
1770
|
-
*
|
|
1771
|
-
* Both the frontend and a project's own backend entrypoint read this. The
|
|
1772
|
-
* frontend needs to know which sources exist and how they are reached — a
|
|
1773
|
-
* `direct`-transport source is one the browser talks to itself — and it imports
|
|
1774
|
-
* the same config package the backend does. Without these it would mean writing
|
|
1775
|
-
* the list a second time, by hand, next to the declarations, which is precisely
|
|
1776
|
-
* the two-homes problem this model removed everywhere else.
|
|
1777
|
-
*
|
|
1778
|
-
* ```tsx
|
|
1779
|
-
* import "../config/resources"; // registers them
|
|
1780
|
-
* import { declaredDataSources, declaredStorageSources } from "@rebasepro/types";
|
|
1781
|
-
*
|
|
1782
|
-
* <Rebase dataSources={declaredDataSources()} storageSources={declaredStorageSources()} />
|
|
1783
|
-
* ```
|
|
1784
|
-
*
|
|
1785
|
-
* The import is what registers them, so a bundler that drops an unused module
|
|
1786
|
-
* would leave this empty — hence the side-effect import above rather than a
|
|
1787
|
-
* bare re-export.
|
|
1788
|
-
*/
|
|
1789
942
|
function declaredDataSources() {
|
|
1790
943
|
return declaredResources("database").map(resourceToDataSource);
|
|
1791
944
|
}
|
|
1792
|
-
/** The declared buckets, as definitions. */
|
|
1793
945
|
function declaredStorageSources() {
|
|
1794
946
|
return declaredResources("bucket").map(resourceToStorageSource);
|
|
1795
947
|
}
|
|
@@ -1807,40 +959,6 @@ var NO = /* @__PURE__ */ new Set([
|
|
|
1807
959
|
"no",
|
|
1808
960
|
"off"
|
|
1809
961
|
]);
|
|
1810
|
-
/**
|
|
1811
|
-
* Read a boolean environment variable — one spelling rule for every reader.
|
|
1812
|
-
*
|
|
1813
|
-
* `true`, `1`, `yes` and `on` are true; `false`, `0`, `no` and `off` are
|
|
1814
|
-
* false. Case and surrounding whitespace are ignored. Anything else — unset,
|
|
1815
|
-
* blank, or a value that spells neither — is `undefined`, so the caller's
|
|
1816
|
-
* default decides and a typo lands on the side the caller chose:
|
|
1817
|
-
*
|
|
1818
|
-
* ```ts
|
|
1819
|
-
* parseEnvBoolean(env.FORCE_LOCAL_STORAGE) === true // off unless said
|
|
1820
|
-
* parseEnvBoolean(env.REBASE_MCP_OPEN_REGISTRATION) !== false // on unless said
|
|
1821
|
-
* ```
|
|
1822
|
-
*
|
|
1823
|
-
* It exists because every reader used to spell this itself, and they
|
|
1824
|
-
* disagreed. The reader that mattered tested the raw string for truthiness —
|
|
1825
|
-
* `!process.env.FORCE_LOCAL_STORAGE` — and every non-empty string is truthy,
|
|
1826
|
-
* so `FORCE_LOCAL_STORAGE=false`, written to say "there is no durable volume
|
|
1827
|
-
* here", switched the production storage guard off and sent uploads to a
|
|
1828
|
-
* container filesystem the next redeploy erased. Beside it, `=== "true"` made
|
|
1829
|
-
* `DISABLE_DB_ROLE_SWITCHING=1` do nothing and `!== "false"` made
|
|
1830
|
-
* `REBASE_MCP_OPEN_REGISTRATION=0` leave registration open.
|
|
1831
|
-
*
|
|
1832
|
-
* The boot schemas in `@rebasepro/server` (`loadEnv`, `loadBootEnv`) accept a
|
|
1833
|
-
* strict subset — `true`, `false` and blank — and refuse any other value
|
|
1834
|
-
* before the server starts. On that subset they read exactly what this reads,
|
|
1835
|
-
* so a variable a schema declares and something else reads lazily cannot mean
|
|
1836
|
-
* two different things.
|
|
1837
|
-
*
|
|
1838
|
-
* It lives in this package, with no dependencies, for the reason
|
|
1839
|
-
* {@link storageEnvSuffix} does: the runtime, its drivers and the CLI all read
|
|
1840
|
-
* these variables, and a second parser is a second chance to disagree.
|
|
1841
|
-
*
|
|
1842
|
-
* @group Models
|
|
1843
|
-
*/
|
|
1844
962
|
function parseEnvBoolean(value) {
|
|
1845
963
|
if (value === void 0) return void 0;
|
|
1846
964
|
const spelled = value.trim().toLowerCase();
|
|
@@ -1849,81 +967,12 @@ function parseEnvBoolean(value) {
|
|
|
1849
967
|
}
|
|
1850
968
|
//#endregion
|
|
1851
969
|
//#region src/types/auth_adapter.ts
|
|
1852
|
-
/**
|
|
1853
|
-
* The request header that asks for a data-plane request to run as another
|
|
1854
|
-
* user, named by uid.
|
|
1855
|
-
*
|
|
1856
|
-
* The server honours it only on a signed-in administrator's own session —
|
|
1857
|
-
* never on an API key or the service key — and only through an adapter that
|
|
1858
|
-
* implements {@link AuthAdapter.resolveUser}. Everywhere else a request that
|
|
1859
|
-
* carries it is refused, never run as its caller.
|
|
1860
|
-
*
|
|
1861
|
-
* @group Auth
|
|
1862
|
-
*/
|
|
1863
970
|
var IMPERSONATE_HEADER = "x-rebase-impersonate";
|
|
1864
|
-
/**
|
|
1865
|
-
* The request header a client sends to the auth routes to say where it keeps
|
|
1866
|
-
* its refresh token. `json` asks for the token in the response body, and has
|
|
1867
|
-
* the token it presents read from the request body.
|
|
1868
|
-
*
|
|
1869
|
-
* It matters only on a server with `cookieAuth`, which otherwise puts the
|
|
1870
|
-
* token in an HttpOnly cookie and answers the body's with `""`, so a client
|
|
1871
|
-
* with no cookie jar (Node, React Native), or one that keeps its own sign-in
|
|
1872
|
-
* apart from the page's cookie session, held nothing to renew with. A request
|
|
1873
|
-
* that sends it is answered as a server without `cookieAuth` answers: the
|
|
1874
|
-
* cookie is neither read nor set. So it can never turn a cookie the page's
|
|
1875
|
-
* script cannot read into a token it can.
|
|
1876
|
-
*
|
|
1877
|
-
* `@rebasepro/client` sends it on every auth request in `authFlowMode: "json"`.
|
|
1878
|
-
*
|
|
1879
|
-
* @group Auth
|
|
1880
|
-
*/
|
|
1881
971
|
var AUTH_FLOW_HEADER = "x-rebase-auth-flow";
|
|
1882
|
-
/**
|
|
1883
|
-
* The request header that asks for a data-plane request to run as a role —
|
|
1884
|
-
* the RLS simulator's "view as". Alone it runs as a signed-in holder of that
|
|
1885
|
-
* role who owns no rows; with {@link SIMULATE_USER_ID_HEADER} it runs as that
|
|
1886
|
-
* uid holding that role, whether or not such an account exists.
|
|
1887
|
-
*
|
|
1888
|
-
* `anon` (or `anonymous`) runs as a caller with no session at all.
|
|
1889
|
-
*
|
|
1890
|
-
* Like {@link IMPERSONATE_HEADER}, only a signed-in administrator's own session
|
|
1891
|
-
* may send it; anyone else is refused with 403, never answered as themselves.
|
|
1892
|
-
*
|
|
1893
|
-
* @group Auth
|
|
1894
|
-
*/
|
|
1895
972
|
var SIMULATE_ROLE_HEADER = "x-rebase-simulate-role";
|
|
1896
|
-
/**
|
|
1897
|
-
* The uid a simulated request runs as. With {@link SIMULATE_ROLE_HEADER} it is
|
|
1898
|
-
* a hypothetical — "u_1 holding customer" — and need not name an account;
|
|
1899
|
-
* without it, the uid must be an active user and runs with their roles now.
|
|
1900
|
-
*
|
|
1901
|
-
* @group Auth
|
|
1902
|
-
*/
|
|
1903
973
|
var SIMULATE_USER_ID_HEADER = "x-rebase-simulate-user-id";
|
|
1904
|
-
/**
|
|
1905
|
-
* The id of a service API key a simulated request runs as: the key's identity,
|
|
1906
|
-
* its RLS roles and its scopes, exactly as a request presenting the key would.
|
|
1907
|
-
* Excludes the other two simulation headers.
|
|
1908
|
-
*
|
|
1909
|
-
* @group Auth
|
|
1910
|
-
*/
|
|
1911
974
|
var SIMULATE_API_KEY_ID_HEADER = "x-rebase-simulate-api-key-id";
|
|
1912
|
-
/**
|
|
1913
|
-
* The response header naming what a simulated request ran as:
|
|
1914
|
-
* `role=<role>;sub=<uid>;masked_columns=<a,b>`, plus `api_key=<id>` and
|
|
1915
|
-
* `collection=<slug>` when they apply. Every value is URI-encoded. Read it
|
|
1916
|
-
* with {@link parseSimulatedContext}.
|
|
1917
|
-
*
|
|
1918
|
-
* @group Auth
|
|
1919
|
-
*/
|
|
1920
975
|
var SIMULATED_CONTEXT_HEADER = "x-rebase-simulated-context";
|
|
1921
|
-
/**
|
|
1922
|
-
* The request headers for an {@link AccessSimulation}. Empty when it asks for
|
|
1923
|
-
* nothing, so spreading it into a header set is always safe.
|
|
1924
|
-
*
|
|
1925
|
-
* @group Auth
|
|
1926
|
-
*/
|
|
1927
976
|
function simulationHeaders(simulation) {
|
|
1928
977
|
if (!simulation) return {};
|
|
1929
978
|
const headers = {};
|
|
@@ -1932,11 +981,6 @@ function simulationHeaders(simulation) {
|
|
|
1932
981
|
if (simulation.apiKeyId) headers[SIMULATE_API_KEY_ID_HEADER] = simulation.apiKeyId;
|
|
1933
982
|
return headers;
|
|
1934
983
|
}
|
|
1935
|
-
/**
|
|
1936
|
-
* Write a {@link SimulatedContext} as the header value.
|
|
1937
|
-
*
|
|
1938
|
-
* @group Auth
|
|
1939
|
-
*/
|
|
1940
984
|
function formatSimulatedContext(context) {
|
|
1941
985
|
const parts = [
|
|
1942
986
|
`role=${encodeURIComponent(context.role)}`,
|
|
@@ -1947,12 +991,6 @@ function formatSimulatedContext(context) {
|
|
|
1947
991
|
if (context.collection) parts.push(`collection=${encodeURIComponent(context.collection)}`);
|
|
1948
992
|
return parts.join(";");
|
|
1949
993
|
}
|
|
1950
|
-
/**
|
|
1951
|
-
* Read {@link SIMULATED_CONTEXT_HEADER}. `undefined` for an absent header or one
|
|
1952
|
-
* missing `role` or `sub`.
|
|
1953
|
-
*
|
|
1954
|
-
* @group Auth
|
|
1955
|
-
*/
|
|
1956
994
|
function parseSimulatedContext(value) {
|
|
1957
995
|
if (!value) return void 0;
|
|
1958
996
|
const fields = /* @__PURE__ */ new Map();
|
|
@@ -1983,37 +1021,6 @@ function parseSimulatedContext(value) {
|
|
|
1983
1021
|
}
|
|
1984
1022
|
//#endregion
|
|
1985
1023
|
//#region src/types/scopes.ts
|
|
1986
|
-
/**
|
|
1987
|
-
* Scopes — what a credential may do, named `resource:action`.
|
|
1988
|
-
*
|
|
1989
|
-
* One vocabulary for every way of reaching a Rebase backend: a person's
|
|
1990
|
-
* session, a service key, a personal key and an OAuth token for `/mcp` all
|
|
1991
|
-
* answer "may this caller do X?" with the same strings, so a grant reads the
|
|
1992
|
-
* same on a key, on a role and on a consent screen.
|
|
1993
|
-
*
|
|
1994
|
-
* A scope may carry a target — `data:read:posts` is `data:read` on the `posts`
|
|
1995
|
-
* collection only. The unqualified scope covers every target. Only the data
|
|
1996
|
-
* plane and app scopes take targets; see {@link SCOPE_TARGETS}.
|
|
1997
|
-
*
|
|
1998
|
-
* Two planes, held differently:
|
|
1999
|
-
*
|
|
2000
|
-
* - **The data plane** (`data:*`, `storage:*`, `functions:invoke`). Every
|
|
2001
|
-
* signed-in person holds all of it, because what a person may do with data
|
|
2002
|
-
* is decided row by row by the collection's `securityRules` and by storage
|
|
2003
|
-
* policies, never by a scope. On a key or a token these scopes narrow: a key
|
|
2004
|
-
* holding `data:read:posts` reaches nothing else, whatever RLS would allow.
|
|
2005
|
-
* - **The admin plane** (everything else). Nobody holds it implicitly. The
|
|
2006
|
-
* `admin` role holds all of it; any other role holds what the app declares
|
|
2007
|
-
* for it under `auth.roles` on the users collection.
|
|
2008
|
-
*
|
|
2009
|
-
* Apps declare their own scopes too (`auth.scopes`), named the same way —
|
|
2010
|
-
* `project:deploy`. Every signed-in person holds every app scope: like the data
|
|
2011
|
-
* plane, the function behind it decides whether the person may act, and the
|
|
2012
|
-
* scope exists so a key can be narrowed to that one action.
|
|
2013
|
-
*
|
|
2014
|
-
* @module
|
|
2015
|
-
*/
|
|
2016
|
-
/** @group Auth */
|
|
2017
1024
|
var DATA_PLANE_SCOPES = [
|
|
2018
1025
|
"data:read",
|
|
2019
1026
|
"data:write",
|
|
@@ -2023,7 +1030,6 @@ var DATA_PLANE_SCOPES = [
|
|
|
2023
1030
|
"storage:delete",
|
|
2024
1031
|
"functions:invoke"
|
|
2025
1032
|
];
|
|
2026
|
-
/** @group Auth */
|
|
2027
1033
|
var ADMIN_SCOPES = [
|
|
2028
1034
|
"users:read",
|
|
2029
1035
|
"users:write",
|
|
@@ -2038,29 +1044,9 @@ var ADMIN_SCOPES = [
|
|
|
2038
1044
|
"keys:read",
|
|
2039
1045
|
"keys:write"
|
|
2040
1046
|
];
|
|
2041
|
-
/** Every scope Rebase itself defines, in display order. @group Auth */
|
|
2042
1047
|
var BUILT_IN_SCOPES = [...DATA_PLANE_SCOPES, ...ADMIN_SCOPES];
|
|
2043
|
-
/**
|
|
2044
|
-
* Scopes no key may hold.
|
|
2045
|
-
*
|
|
2046
|
-
* A key that could manage keys could mint its own successor, widen itself, or
|
|
2047
|
-
* revoke the keys other integrations run on — and revoking it would undo none
|
|
2048
|
-
* of that. Managing keys is for a person (or the service key).
|
|
2049
|
-
*
|
|
2050
|
-
* @group Auth
|
|
2051
|
-
*/
|
|
2052
1048
|
var KEY_MANAGEMENT_SCOPES = ["keys:read", "keys:write"];
|
|
2053
|
-
/** The one built-in role. It holds every scope and is the RLS `admin` role. @group Auth */
|
|
2054
1049
|
var ADMIN_ROLE = "admin";
|
|
2055
|
-
/**
|
|
2056
|
-
* The built-in scopes that accept a target, and what the target names.
|
|
2057
|
-
*
|
|
2058
|
-
* - `data:*` — a collection slug
|
|
2059
|
-
* - `storage:*` — a storage source id (`(default)` for the default source)
|
|
2060
|
-
* - `functions:invoke` — a custom function's name
|
|
2061
|
-
*
|
|
2062
|
-
* @group Auth
|
|
2063
|
-
*/
|
|
2064
1050
|
var SCOPE_TARGETS = {
|
|
2065
1051
|
"data:read": "collection",
|
|
2066
1052
|
"data:write": "collection",
|
|
@@ -2070,7 +1056,6 @@ var SCOPE_TARGETS = {
|
|
|
2070
1056
|
"storage:delete": "bucket",
|
|
2071
1057
|
"functions:invoke": "function"
|
|
2072
1058
|
};
|
|
2073
|
-
/** @group Auth */
|
|
2074
1059
|
var BUILT_IN_SCOPE_DESCRIPTIONS = {
|
|
2075
1060
|
"data:read": {
|
|
2076
1061
|
label: "Read data",
|
|
@@ -2126,7 +1111,7 @@ var BUILT_IN_SCOPE_DESCRIPTIONS = {
|
|
|
2126
1111
|
},
|
|
2127
1112
|
"backups:read": {
|
|
2128
1113
|
label: "Download backups",
|
|
2129
|
-
description: "List and download database backups
|
|
1114
|
+
description: "List and download database backups \u2014 every row, outside row-level security."
|
|
2130
1115
|
},
|
|
2131
1116
|
"cron:read": {
|
|
2132
1117
|
label: "See cron jobs",
|
|
@@ -2149,20 +1134,11 @@ var BUILT_IN_SCOPE_DESCRIPTIONS = {
|
|
|
2149
1134
|
description: "Create, change and revoke the project's service keys. Never grantable to a key."
|
|
2150
1135
|
}
|
|
2151
1136
|
};
|
|
2152
|
-
/** The access model of an app that declares nothing: built-ins only. @group Auth */
|
|
2153
1137
|
var EMPTY_ACCESS_MODEL = {
|
|
2154
1138
|
roles: {},
|
|
2155
1139
|
scopes: {}
|
|
2156
1140
|
};
|
|
2157
1141
|
var SCOPE_PART = /^[a-z][a-z0-9-]*$/;
|
|
2158
|
-
/**
|
|
2159
|
-
* Split `resource:action[:target]`. Returns null for anything else.
|
|
2160
|
-
*
|
|
2161
|
-
* The target is everything after the second colon, so a target may itself
|
|
2162
|
-
* contain colons. Resource and action are lower-case words.
|
|
2163
|
-
*
|
|
2164
|
-
* @group Auth
|
|
2165
|
-
*/
|
|
2166
1142
|
function parseScope(value) {
|
|
2167
1143
|
if (typeof value !== "string") return null;
|
|
2168
1144
|
const first = value.indexOf(":");
|
|
@@ -2179,50 +1155,24 @@ function parseScope(value) {
|
|
|
2179
1155
|
target
|
|
2180
1156
|
};
|
|
2181
1157
|
}
|
|
2182
|
-
/** @group Auth */
|
|
2183
1158
|
function isBuiltInScope(scope) {
|
|
2184
1159
|
return BUILT_IN_SCOPES.includes(scope);
|
|
2185
1160
|
}
|
|
2186
|
-
/** @group Auth */
|
|
2187
1161
|
function isDataPlaneScope(scope) {
|
|
2188
1162
|
return DATA_PLANE_SCOPES.includes(scope);
|
|
2189
1163
|
}
|
|
2190
|
-
/** @group Auth */
|
|
2191
1164
|
function isAdminScope(scope) {
|
|
2192
1165
|
return ADMIN_SCOPES.includes(scope);
|
|
2193
1166
|
}
|
|
2194
|
-
/** Does this list of roles include the built-in `admin` role? @group Auth */
|
|
2195
1167
|
function hasAdminRole(roles) {
|
|
2196
1168
|
return !!roles?.includes(ADMIN_ROLE);
|
|
2197
1169
|
}
|
|
2198
|
-
/**
|
|
2199
|
-
* Why `name` cannot be written as a role, or `undefined` when it can.
|
|
2200
|
-
*
|
|
2201
|
-
* No naming pattern is imposed — an app may call its roles anything. What is
|
|
2202
|
-
* refused is a name that would be read back as *other* roles: a role travels as
|
|
2203
|
-
* one element of a Postgres `text[]` and as one entry of the comma-joined
|
|
2204
|
-
* `app.user_roles` setting that RLS policies split with
|
|
2205
|
-
* `string_to_array(…, ',')`. Written as `"support,admin"`, a role comes back as
|
|
2206
|
-
* `admin`; braces, quotes and backslashes are array-literal syntax, so they are
|
|
2207
|
-
* refused too, as are empty names and control characters.
|
|
2208
|
-
*
|
|
2209
|
-
* @group Auth
|
|
2210
|
-
*/
|
|
2211
1170
|
function roleNameProblem(name) {
|
|
2212
1171
|
if (typeof name !== "string") return "is not a string";
|
|
2213
1172
|
if (name.trim() === "") return "is empty";
|
|
2214
1173
|
if (/[,{}"\\]/.test(name)) return "contains , { } \" or \\";
|
|
2215
1174
|
if (/[\u0000-\u001f\u007f]/.test(name)) return "contains a control character";
|
|
2216
1175
|
}
|
|
2217
|
-
/**
|
|
2218
|
-
* Does a set of held scopes grant `scope`, optionally on one `target`?
|
|
2219
|
-
*
|
|
2220
|
-
* The unqualified grant covers every target. A qualified grant covers its own
|
|
2221
|
-
* target only, and never answers an unqualified question: a key holding
|
|
2222
|
-
* `data:read:posts` is not asked "may you read data?" and told yes.
|
|
2223
|
-
*
|
|
2224
|
-
* @group Auth
|
|
2225
|
-
*/
|
|
2226
1176
|
function scopeGrants(held, scope, target) {
|
|
2227
1177
|
for (const entry of held) {
|
|
2228
1178
|
if (entry === scope) return true;
|
|
@@ -2230,24 +1180,10 @@ function scopeGrants(held, scope, target) {
|
|
|
2230
1180
|
}
|
|
2231
1181
|
return false;
|
|
2232
1182
|
}
|
|
2233
|
-
/**
|
|
2234
|
-
* Does a set of held scopes grant `scope` on at least one target?
|
|
2235
|
-
*
|
|
2236
|
-
* For a surface that lists what is reachable — the collections an MCP client
|
|
2237
|
-
* may query — and filters per item afterwards.
|
|
2238
|
-
*
|
|
2239
|
-
* @group Auth
|
|
2240
|
-
*/
|
|
2241
1183
|
function scopeGrantsAny(held, scope) {
|
|
2242
1184
|
const prefix = `${scope}:`;
|
|
2243
1185
|
return held.some((entry) => entry === scope || entry.startsWith(prefix));
|
|
2244
1186
|
}
|
|
2245
|
-
/**
|
|
2246
|
-
* The targets a held set narrows `scope` to: `"all"` when it holds the
|
|
2247
|
-
* unqualified scope, otherwise the listed targets (possibly none).
|
|
2248
|
-
*
|
|
2249
|
-
* @group Auth
|
|
2250
|
-
*/
|
|
2251
1187
|
function scopeTargets(held, scope) {
|
|
2252
1188
|
const prefix = `${scope}:`;
|
|
2253
1189
|
const targets = [];
|
|
@@ -2257,15 +1193,6 @@ function scopeTargets(held, scope) {
|
|
|
2257
1193
|
}
|
|
2258
1194
|
return targets;
|
|
2259
1195
|
}
|
|
2260
|
-
/**
|
|
2261
|
-
* Every scope a person holding `roles` has.
|
|
2262
|
-
*
|
|
2263
|
-
* The data plane and every app scope always; the whole admin plane with the
|
|
2264
|
-
* `admin` role; otherwise each declared role's scopes. A role nobody declared
|
|
2265
|
-
* adds nothing — it may still mean something to an RLS policy.
|
|
2266
|
-
*
|
|
2267
|
-
* @group Auth
|
|
2268
|
-
*/
|
|
2269
1196
|
function scopesForRoles(roles, model = EMPTY_ACCESS_MODEL) {
|
|
2270
1197
|
const held = /* @__PURE__ */ new Set([...DATA_PLANE_SCOPES, ...Object.keys(model.scopes)]);
|
|
2271
1198
|
if (hasAdminRole(roles)) {
|
|
@@ -2278,26 +1205,13 @@ function scopesForRoles(roles, model = EMPTY_ACCESS_MODEL) {
|
|
|
2278
1205
|
}
|
|
2279
1206
|
return [...held];
|
|
2280
1207
|
}
|
|
2281
|
-
/**
|
|
2282
|
-
* Every scope this access model knows, unqualified: the built-ins, then the
|
|
2283
|
-
* app's own.
|
|
2284
|
-
*
|
|
2285
|
-
* @group Auth
|
|
2286
|
-
*/
|
|
2287
1208
|
function knownScopes(model = EMPTY_ACCESS_MODEL) {
|
|
2288
1209
|
return [...BUILT_IN_SCOPES, ...Object.keys(model.scopes)];
|
|
2289
1210
|
}
|
|
2290
|
-
/** Does this scope accept a target? @group Auth */
|
|
2291
1211
|
function scopeAcceptsTarget(scope, model = EMPTY_ACCESS_MODEL) {
|
|
2292
1212
|
if (isBuiltInScope(scope)) return SCOPE_TARGETS[scope] !== void 0;
|
|
2293
1213
|
return (Object.prototype.hasOwnProperty.call(model.scopes, scope) ? model.scopes[scope] : void 0)?.target !== void 0;
|
|
2294
1214
|
}
|
|
2295
|
-
/**
|
|
2296
|
-
* Check a list of scope strings against an access model. Returns the
|
|
2297
|
-
* problems, empty when every entry is a known scope with an acceptable target.
|
|
2298
|
-
*
|
|
2299
|
-
* @group Auth
|
|
2300
|
-
*/
|
|
2301
1215
|
function validateScopes(values, model = EMPTY_ACCESS_MODEL) {
|
|
2302
1216
|
const known = new Set(knownScopes(model));
|
|
2303
1217
|
const problems = [];
|
|
@@ -2319,15 +1233,6 @@ function validateScopes(values, model = EMPTY_ACCESS_MODEL) {
|
|
|
2319
1233
|
}
|
|
2320
1234
|
return problems;
|
|
2321
1235
|
}
|
|
2322
|
-
/**
|
|
2323
|
-
* The entries of `requested` that `held` does not cover — what a credential
|
|
2324
|
-
* would hold beyond its minter. Empty means the request is within reach.
|
|
2325
|
-
*
|
|
2326
|
-
* `data:read:posts` is covered by `data:read`; `data:read` is not covered by
|
|
2327
|
-
* `data:read:posts`.
|
|
2328
|
-
*
|
|
2329
|
-
* @group Auth
|
|
2330
|
-
*/
|
|
2331
1236
|
function scopesBeyond(requested, held) {
|
|
2332
1237
|
return requested.filter((entry) => {
|
|
2333
1238
|
const parsed = parseScope(entry);
|
|
@@ -2335,23 +1240,10 @@ function scopesBeyond(requested, held) {
|
|
|
2335
1240
|
return !scopeGrants(held, parsed.scope, parsed.target);
|
|
2336
1241
|
});
|
|
2337
1242
|
}
|
|
2338
|
-
/**
|
|
2339
|
-
* Narrow `requested` to what `held` covers, entry by entry. What a personal
|
|
2340
|
-
* key holds today when its owner has lost a role since it was minted.
|
|
2341
|
-
*
|
|
2342
|
-
* @group Auth
|
|
2343
|
-
*/
|
|
2344
1243
|
function intersectScopes(requested, held) {
|
|
2345
1244
|
const beyond = new Set(scopesBeyond(requested, held));
|
|
2346
1245
|
return requested.filter((entry) => !beyond.has(entry));
|
|
2347
1246
|
}
|
|
2348
|
-
/**
|
|
2349
|
-
* How a scope is worded for a person: the built-in description, the app's
|
|
2350
|
-
* declared label, or the raw string when nothing describes it. A target is
|
|
2351
|
-
* named after the label.
|
|
2352
|
-
*
|
|
2353
|
-
* @group Auth
|
|
2354
|
-
*/
|
|
2355
1247
|
function describeScope(value, model = EMPTY_ACCESS_MODEL) {
|
|
2356
1248
|
const parsed = parseScope(value);
|
|
2357
1249
|
if (!parsed) return {
|
|
@@ -2373,7 +1265,6 @@ function describeScope(value, model = EMPTY_ACCESS_MODEL) {
|
|
|
2373
1265
|
description: base?.description ?? ""
|
|
2374
1266
|
};
|
|
2375
1267
|
}
|
|
2376
|
-
/** The roles of an access model, `admin` first. @group Auth */
|
|
2377
1268
|
function summarizeRoles(model = EMPTY_ACCESS_MODEL) {
|
|
2378
1269
|
return [{
|
|
2379
1270
|
id: ADMIN_ROLE,
|
|
@@ -2389,7 +1280,6 @@ function summarizeRoles(model = EMPTY_ACCESS_MODEL) {
|
|
|
2389
1280
|
builtIn: false
|
|
2390
1281
|
}))];
|
|
2391
1282
|
}
|
|
2392
|
-
/** Every scope of an access model, described, in display order. @group Auth */
|
|
2393
1283
|
function summarizeScopes(model = EMPTY_ACCESS_MODEL) {
|
|
2394
1284
|
const builtIn = BUILT_IN_SCOPES.map((scope) => ({
|
|
2395
1285
|
scope,
|
|
@@ -2408,34 +1298,16 @@ function summarizeScopes(model = EMPTY_ACCESS_MODEL) {
|
|
|
2408
1298
|
}
|
|
2409
1299
|
//#endregion
|
|
2410
1300
|
//#region src/types/project_manifest.ts
|
|
2411
|
-
/** The statuses a static app's redirect may answer with. */
|
|
2412
1301
|
var STATIC_REDIRECT_STATUSES = [
|
|
2413
1302
|
301,
|
|
2414
1303
|
302,
|
|
2415
1304
|
307,
|
|
2416
1305
|
308
|
|
2417
1306
|
];
|
|
2418
|
-
/** The status a redirect answers with when it names none: permanent, method kept. */
|
|
2419
1307
|
var DEFAULT_STATIC_REDIRECT_STATUS = 308;
|
|
2420
|
-
/** Whether `value` is one of {@link STATIC_REDIRECT_STATUSES}. */
|
|
2421
1308
|
function isStaticRedirectStatus(value) {
|
|
2422
1309
|
return STATIC_REDIRECT_STATUSES.some((status) => status === value);
|
|
2423
1310
|
}
|
|
2424
|
-
/**
|
|
2425
|
-
* Path prefixes the backend owns, which no static app may claim.
|
|
2426
|
-
*
|
|
2427
|
-
* One process — and, on the platform, one hostname — serves both the API and
|
|
2428
|
-
* however many static apps a project has. Mounting is longest-path-first, so an
|
|
2429
|
-
* app declaring `/api` would win against the API itself and every request to it
|
|
2430
|
-
* would be answered with that app's `index.html`: a 200 carrying HTML where the
|
|
2431
|
-
* caller expected JSON, from a project that looks deployed and healthy.
|
|
2432
|
-
*
|
|
2433
|
-
* Declared here rather than in either enforcer because both must agree. The CLI
|
|
2434
|
-
* checks it so a developer finds out while editing `rebase.json`; the control
|
|
2435
|
-
* plane checks it again at deploy intake, because the front door's correctness
|
|
2436
|
-
* cannot rest on a check that ran in somebody else's CLI — and a repository can
|
|
2437
|
-
* be deployed by a CLI older than this rule.
|
|
2438
|
-
*/
|
|
2439
1311
|
var RESERVED_BACKEND_PREFIXES = [
|
|
2440
1312
|
"/api",
|
|
2441
1313
|
"/health",
|
|
@@ -2444,36 +1316,15 @@ var RESERVED_BACKEND_PREFIXES = [
|
|
|
2444
1316
|
"/readyz",
|
|
2445
1317
|
"/metrics"
|
|
2446
1318
|
];
|
|
2447
|
-
/**
|
|
2448
|
-
* Whether `path` collides with a prefix the backend owns.
|
|
2449
|
-
*
|
|
2450
|
-
* Compares at segment boundaries, so `/api` and `/api/v2` collide while
|
|
2451
|
-
* `/apidocs` does not — the same rule the router matches with, because a check
|
|
2452
|
-
* that is stricter than the router rejects paths that would have worked, and one
|
|
2453
|
-
* that is looser admits paths that will not.
|
|
2454
|
-
*/
|
|
2455
1319
|
function reservedPrefixFor(path) {
|
|
2456
1320
|
const normalized = path.endsWith("/") && path !== "/" ? path.slice(0, -1) : path;
|
|
2457
1321
|
return RESERVED_BACKEND_PREFIXES.find((reserved) => normalized === reserved || normalized.startsWith(`${reserved}/`));
|
|
2458
1322
|
}
|
|
2459
|
-
/**
|
|
2460
|
-
* Split a static app's declared `path` into the hostname it claims and the path
|
|
2461
|
-
* under it.
|
|
2462
|
-
*
|
|
2463
|
-
* `"/admin"` is `{ path: "/admin" }`, returned as written: the path rules
|
|
2464
|
-
* (leading slash, no `..`, reserved prefixes) belong to the caller, which
|
|
2465
|
-
* applies them to the path part of either form. `"https://admin.example.com/cms"`
|
|
2466
|
-
* is `{ host: "admin.example.com", path: "/cms" }`.
|
|
2467
|
-
*
|
|
2468
|
-
* Shared because three parties must read the same value the same way: the CLI
|
|
2469
|
-
* while `rebase.json` is edited, the control plane at deploy intake (a bundle can
|
|
2470
|
-
* come from any CLI, or none), and the runtime choosing which app answers.
|
|
2471
|
-
*/
|
|
2472
1323
|
function parseAppAddress(value) {
|
|
2473
1324
|
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
|
|
2474
1325
|
if (!value.startsWith("/") && isValidAppHost(value.toLowerCase().replace(/\/.*$/, ""))) return {
|
|
2475
1326
|
ok: false,
|
|
2476
|
-
reason: `looks like a hostname
|
|
1327
|
+
reason: `looks like a hostname \u2014 write it as a URL: "https://${value}"`
|
|
2477
1328
|
};
|
|
2478
1329
|
return {
|
|
2479
1330
|
ok: true,
|
|
@@ -2487,7 +1338,7 @@ function parseAppAddress(value) {
|
|
|
2487
1338
|
const authority = value.slice(value.indexOf("//") + 2).split(/[/?#]/)[0];
|
|
2488
1339
|
if (/:[^@]*$/.test(authority) && !authority.startsWith("[")) return {
|
|
2489
1340
|
ok: false,
|
|
2490
|
-
reason: "must not name a port
|
|
1341
|
+
reason: "must not name a port \u2014 a hostname is served on 443"
|
|
2491
1342
|
};
|
|
2492
1343
|
let url;
|
|
2493
1344
|
try {
|
|
@@ -2500,7 +1351,7 @@ function parseAppAddress(value) {
|
|
|
2500
1351
|
}
|
|
2501
1352
|
if (url.protocol !== "https:") return {
|
|
2502
1353
|
ok: false,
|
|
2503
|
-
reason: `must use https
|
|
1354
|
+
reason: `must use https \u2014 the platform serves every hostname over TLS: "https://${url.host}${url.pathname === "/" ? "" : url.pathname}"`
|
|
2504
1355
|
};
|
|
2505
1356
|
if (url.username || url.password) return {
|
|
2506
1357
|
ok: false,
|
|
@@ -2508,7 +1359,7 @@ function parseAppAddress(value) {
|
|
|
2508
1359
|
};
|
|
2509
1360
|
if (url.port) return {
|
|
2510
1361
|
ok: false,
|
|
2511
|
-
reason: "must not name a port
|
|
1362
|
+
reason: "must not name a port \u2014 a hostname is served on 443"
|
|
2512
1363
|
};
|
|
2513
1364
|
if (url.search || url.hash || /[?#]/.test(value)) return {
|
|
2514
1365
|
ok: false,
|
|
@@ -2528,11 +1379,6 @@ function parseAppAddress(value) {
|
|
|
2528
1379
|
}
|
|
2529
1380
|
};
|
|
2530
1381
|
}
|
|
2531
|
-
/**
|
|
2532
|
-
* Whether `host` is a public DNS name an app can be given: lowercase labels of
|
|
2533
|
-
* letters, digits and hyphens, at least two of them, not an IP address and not
|
|
2534
|
-
* `localhost`. Internationalised names arrive here already in punycode.
|
|
2535
|
-
*/
|
|
2536
1382
|
function isValidAppHost(host) {
|
|
2537
1383
|
if (host.length === 0 || host.length > 253 || host !== host.toLowerCase()) return false;
|
|
2538
1384
|
const labels = host.split(".");
|
|
@@ -2541,39 +1387,12 @@ function isValidAppHost(host) {
|
|
|
2541
1387
|
if (!labels.every((part) => label.test(part))) return false;
|
|
2542
1388
|
return !/^[0-9]+$/.test(labels[labels.length - 1]);
|
|
2543
1389
|
}
|
|
2544
|
-
/** Whether `path` is `parent`, or a path beneath it, at segment boundaries. */
|
|
2545
1390
|
function isPathUnder(path, parent) {
|
|
2546
1391
|
if (parent === "/") return true;
|
|
2547
1392
|
return path === parent || path.startsWith(`${parent}/`);
|
|
2548
1393
|
}
|
|
2549
|
-
/**
|
|
2550
|
-
* The characters a route's path may hold: unreserved and sub-delimiters, `:`,
|
|
2551
|
-
* `@` and `/`. A request path arrives percent-encoded and is matched as it
|
|
2552
|
-
* arrives, so a route written with a space, a `%` or a non-ASCII letter could
|
|
2553
|
-
* never match anything.
|
|
2554
|
-
*/
|
|
2555
1394
|
var ROUTE_PATH_CHARACTERS = /^\/[A-Za-z0-9\-._~!$&'()+,;=:@/]*$/;
|
|
2556
|
-
/** A function's name as it appears in `/api/functions/<name>`: one path segment. */
|
|
2557
1395
|
var FUNCTION_NAME = /^[A-Za-z0-9_-][A-Za-z0-9_.-]*$/;
|
|
2558
|
-
/**
|
|
2559
|
-
* Validate one of a static app's routes against the app's own path (the path
|
|
2560
|
-
* part of its address).
|
|
2561
|
-
*
|
|
2562
|
-
* Shared for the reason {@link parseAppAddress} is: the CLI checks a route
|
|
2563
|
-
* while `rebase.json` is edited, and the runtime checks it again when it loads
|
|
2564
|
-
* a bundle, which any program could have written. The rules:
|
|
2565
|
-
*
|
|
2566
|
-
* - `path` is absolute, with no `..`, empty segment or trailing slash, and
|
|
2567
|
-
* ends in `/*` or holds no `*` at all.
|
|
2568
|
-
* - No segment starts with a dot: `/.well-known` is the backend's, and a
|
|
2569
|
-
* static app serves no dot-file.
|
|
2570
|
-
* - It is not under a prefix the backend owns ({@link RESERVED_BACKEND_PREFIXES}),
|
|
2571
|
-
* because the API answers there on every hostname.
|
|
2572
|
-
* - It is inside the app's path, since the app is what answers there, and a
|
|
2573
|
-
* wildcard does not cover the whole app, which would leave nothing of the
|
|
2574
|
-
* build to serve.
|
|
2575
|
-
* - `function` is one path segment, as a function's file name is.
|
|
2576
|
-
*/
|
|
2577
1396
|
function validateStaticRoute(value, appPath) {
|
|
2578
1397
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return {
|
|
2579
1398
|
ok: false,
|
|
@@ -2595,7 +1414,7 @@ function validateStaticRoute(value, appPath) {
|
|
|
2595
1414
|
if (!ROUTE_PATH_CHARACTERS.test(prefix)) return {
|
|
2596
1415
|
ok: false,
|
|
2597
1416
|
field: "path",
|
|
2598
|
-
reason: "may hold letters, digits, \"/\" and - . _ ~ ! $ & ' ( ) + , ; = : @ only
|
|
1417
|
+
reason: "may hold letters, digits, \"/\" and - . _ ~ ! $ & ' ( ) + , ; = : @ only \u2014 no spaces, \"?\", \"#\" or \"%\""
|
|
2599
1418
|
};
|
|
2600
1419
|
if (prefix.includes("//") || prefix !== "/" && prefix.endsWith("/")) return {
|
|
2601
1420
|
ok: false,
|
|
@@ -2605,18 +1424,18 @@ function validateStaticRoute(value, appPath) {
|
|
|
2605
1424
|
if (prefix.split("/").some((segment) => segment.startsWith("."))) return {
|
|
2606
1425
|
ok: false,
|
|
2607
1426
|
field: "path",
|
|
2608
|
-
reason: "must have no segment starting with \".\"
|
|
1427
|
+
reason: "must have no segment starting with \".\" \u2014 an app serves no dot-file; for /.well-known, put the file in the .well-known/ folder of the build and the app at \"/\" serves it"
|
|
2609
1428
|
};
|
|
2610
1429
|
const reserved = reservedPrefixFor(prefix);
|
|
2611
1430
|
if (reserved) return {
|
|
2612
1431
|
ok: false,
|
|
2613
1432
|
field: "path",
|
|
2614
|
-
reason: `cannot be "${reserved}" or nest under it
|
|
1433
|
+
reason: `cannot be "${reserved}" or nest under it \u2014 the backend serves that path on every hostname`
|
|
2615
1434
|
};
|
|
2616
1435
|
if (!isPathUnder(prefix, appPath)) return {
|
|
2617
1436
|
ok: false,
|
|
2618
1437
|
field: "path",
|
|
2619
|
-
reason: `must be inside this app's path, "${appPath}"
|
|
1438
|
+
reason: `must be inside this app's path, "${appPath}" \u2014 the app is what answers there`
|
|
2620
1439
|
};
|
|
2621
1440
|
if (wildcard && prefix === appPath) return {
|
|
2622
1441
|
ok: false,
|
|
@@ -2636,14 +1455,6 @@ function validateStaticRoute(value, appPath) {
|
|
|
2636
1455
|
}
|
|
2637
1456
|
};
|
|
2638
1457
|
}
|
|
2639
|
-
/**
|
|
2640
|
-
* Whether `route` answers `requestPath`, and with what path under its
|
|
2641
|
-
* function: `""` for the route's own path, `/rest` beneath a wildcard.
|
|
2642
|
-
* `undefined` when it does not match.
|
|
2643
|
-
*
|
|
2644
|
-
* Compared as the path arrives, percent-encoding and all, and at segment
|
|
2645
|
-
* boundaries: `/blog/*` matches `/blog` and `/blog/x`, not `/blogroll`.
|
|
2646
|
-
*/
|
|
2647
1458
|
function matchStaticRoute(route, requestPath) {
|
|
2648
1459
|
if (!route.path.endsWith("/*")) return requestPath === route.path ? "" : void 0;
|
|
2649
1460
|
const prefix = route.path.slice(0, -2);
|
|
@@ -2651,31 +1462,17 @@ function matchStaticRoute(route, requestPath) {
|
|
|
2651
1462
|
if (requestPath === prefix) return "";
|
|
2652
1463
|
return requestPath.startsWith(`${prefix}/`) ? requestPath.slice(prefix.length) : void 0;
|
|
2653
1464
|
}
|
|
2654
|
-
/**
|
|
2655
|
-
* Order routes so the first match is the most specific: exact paths first,
|
|
2656
|
-
* then wildcards by the length of their prefix, longest first. Declaration
|
|
2657
|
-
* order breaks ties, which only equal wildcards can have.
|
|
2658
|
-
*/
|
|
2659
1465
|
function compareStaticRoutes(a, b) {
|
|
2660
1466
|
const aWild = a.path.endsWith("/*");
|
|
2661
1467
|
if (aWild !== b.path.endsWith("/*")) return aWild ? 1 : -1;
|
|
2662
1468
|
return aWild ? b.path.length - a.path.length : 0;
|
|
2663
1469
|
}
|
|
2664
|
-
/** `:name` or `:name*`, a whole segment. */
|
|
2665
1470
|
var REDIRECT_PARAM_SEGMENT = /^:([A-Za-z_][A-Za-z0-9_]*)(\*)?$/;
|
|
2666
|
-
/** A parameter written in `to`: `:name` or `:name*`, with the slash before it. */
|
|
2667
1471
|
var REDIRECT_PARAM_IN_TO = /(\/)?:([A-Za-z_][A-Za-z0-9_]*)(\*)?/g;
|
|
2668
|
-
/** What a literal segment may not hold. A `:` starts a parameter, which is a whole segment. */
|
|
2669
1472
|
var REDIRECT_LITERAL_FORBIDDEN = /[?#\\*:\s\u0000-\u001f\u007f]/;
|
|
2670
|
-
/**
|
|
2671
|
-
* A literal segment as a browser sends it: percent-encoded where the URL
|
|
2672
|
-
* standard encodes a path, so `café` in `from` matches the request
|
|
2673
|
-
* `/caf%C3%A9`, and an escape already written is kept.
|
|
2674
|
-
*/
|
|
2675
1473
|
function encodePathSegment(segment) {
|
|
2676
1474
|
return new URL(`http://h/${segment}`).pathname.slice(1);
|
|
2677
1475
|
}
|
|
2678
|
-
/** Split `from` into segments, or say why it cannot be. */
|
|
2679
1476
|
function parseRedirectFrom(from) {
|
|
2680
1477
|
if (from === "/") return {
|
|
2681
1478
|
ok: true,
|
|
@@ -2683,12 +1480,12 @@ function parseRedirectFrom(from) {
|
|
|
2683
1480
|
};
|
|
2684
1481
|
if (from.startsWith("//")) return {
|
|
2685
1482
|
ok: false,
|
|
2686
|
-
reason: "must be a path, not a URL without its scheme
|
|
1483
|
+
reason: "must be a path, not a URL without its scheme \u2014 match a hostname with \"host\""
|
|
2687
1484
|
};
|
|
2688
1485
|
const parts = from.slice(1).split("/");
|
|
2689
1486
|
if (parts.some((part) => part === "")) return {
|
|
2690
1487
|
ok: false,
|
|
2691
|
-
reason: "must have no empty segment and no trailing slash
|
|
1488
|
+
reason: "must have no empty segment and no trailing slash \u2014 a request's trailing slash is ignored anyway"
|
|
2692
1489
|
};
|
|
2693
1490
|
const segments = [];
|
|
2694
1491
|
const names = /* @__PURE__ */ new Set();
|
|
@@ -2702,7 +1499,7 @@ function parseRedirectFrom(from) {
|
|
|
2702
1499
|
const [, name, star] = param;
|
|
2703
1500
|
if (star && index !== parts.length - 1) return {
|
|
2704
1501
|
ok: false,
|
|
2705
|
-
reason: `has ":${name}*" before its last segment
|
|
1502
|
+
reason: `has ":${name}*" before its last segment \u2014 a parameter matching the rest of the path comes last`
|
|
2706
1503
|
};
|
|
2707
1504
|
if (names.has(name)) return {
|
|
2708
1505
|
ok: false,
|
|
@@ -2718,16 +1515,16 @@ function parseRedirectFrom(from) {
|
|
|
2718
1515
|
}
|
|
2719
1516
|
if (part.startsWith(".")) return {
|
|
2720
1517
|
ok: false,
|
|
2721
|
-
reason: "must have no segment starting with \".\"
|
|
1518
|
+
reason: "must have no segment starting with \".\" \u2014 an app serves no dot-file; for /.well-known, put the file in the .well-known/ folder of the build and the app at \"/\" serves it"
|
|
2722
1519
|
};
|
|
2723
1520
|
if (REDIRECT_LITERAL_FORBIDDEN.test(part)) return {
|
|
2724
1521
|
ok: false,
|
|
2725
|
-
reason: `has "${part}", which holds a space, "?", "#", "\\", "*" or ":"
|
|
1522
|
+
reason: `has "${part}", which holds a space, "?", "#", "\\", "*" or ":" \u2014 a ":" starts a parameter, which is a whole segment, and a query is matched with "query"`
|
|
2726
1523
|
};
|
|
2727
1524
|
const encoded = encodePathSegment(part);
|
|
2728
1525
|
if (encoded === "") return {
|
|
2729
1526
|
ok: false,
|
|
2730
|
-
reason: `has "${part}", which is "." or ".." written with escapes
|
|
1527
|
+
reason: `has "${part}", which is "." or ".." written with escapes \u2014 a request never arrives with one`
|
|
2731
1528
|
};
|
|
2732
1529
|
segments.push({
|
|
2733
1530
|
kind: "literal",
|
|
@@ -2739,7 +1536,6 @@ function parseRedirectFrom(from) {
|
|
|
2739
1536
|
segments
|
|
2740
1537
|
};
|
|
2741
1538
|
}
|
|
2742
|
-
/** The leading literal segments of `from`, as a path: what every match is under. */
|
|
2743
1539
|
function literalPrefixOf(segments) {
|
|
2744
1540
|
const literals = [];
|
|
2745
1541
|
for (const segment of segments) {
|
|
@@ -2748,11 +1544,6 @@ function literalPrefixOf(segments) {
|
|
|
2748
1544
|
}
|
|
2749
1545
|
return `/${literals.join("/")}`;
|
|
2750
1546
|
}
|
|
2751
|
-
/**
|
|
2752
|
-
* Compile one redirect into the function that answers a request with it, or
|
|
2753
|
-
* `undefined` when it does not match. The redirect must have passed
|
|
2754
|
-
* {@link validateStaticRedirect}; one that would not throws.
|
|
2755
|
-
*/
|
|
2756
1547
|
function compileStaticRedirect(redirect) {
|
|
2757
1548
|
const parsed = parseRedirectFrom(redirect.from);
|
|
2758
1549
|
if (!parsed.ok) throw new Error(`Redirect from ${JSON.stringify(redirect.from)} ${parsed.reason}.`);
|
|
@@ -2794,15 +1585,6 @@ function compileStaticRedirect(redirect) {
|
|
|
2794
1585
|
};
|
|
2795
1586
|
};
|
|
2796
1587
|
}
|
|
2797
|
-
/**
|
|
2798
|
-
* Compile a static app's redirects into the one function that answers a
|
|
2799
|
-
* request with the first that matches, in declaration order — `undefined`
|
|
2800
|
-
* when none does. Each must have passed {@link validateStaticRedirect}.
|
|
2801
|
-
*
|
|
2802
|
-
* Shared so every server of a static app answers the same request the same
|
|
2803
|
-
* way: `rebase dev`, `rebase start` and `rebase-server` through `serveSPA`,
|
|
2804
|
-
* and any other host that serves a built app.
|
|
2805
|
-
*/
|
|
2806
1588
|
function compileStaticRedirects(redirects) {
|
|
2807
1589
|
const compiled = redirects.map(compileStaticRedirect);
|
|
2808
1590
|
return (request) => {
|
|
@@ -2812,32 +1594,6 @@ function compileStaticRedirects(redirects) {
|
|
|
2812
1594
|
}
|
|
2813
1595
|
};
|
|
2814
1596
|
}
|
|
2815
|
-
/**
|
|
2816
|
-
* Validate one of a static app's redirects against the app's address (its
|
|
2817
|
-
* hostname, when its `path` names one, and the path part).
|
|
2818
|
-
*
|
|
2819
|
-
* Shared for the reason {@link validateStaticRoute} is: the CLI checks a
|
|
2820
|
-
* redirect while `rebase.json` is edited, and the runtime checks it again
|
|
2821
|
-
* when it loads a bundle. The rules:
|
|
2822
|
-
*
|
|
2823
|
-
* - `from` is an absolute path with no empty segment, no trailing slash and
|
|
2824
|
-
* no segment starting with a dot. A segment is literal text or a parameter
|
|
2825
|
-
* — `:name`, or `:name*` as the last segment — and a literal holds no
|
|
2826
|
-
* space, `?`, `#`, `\`, `*` or `:`. Its leading literal segments are inside
|
|
2827
|
-
* the app's path and not under a prefix the backend owns, since the app is
|
|
2828
|
-
* what answers there.
|
|
2829
|
-
* - `to` is a path (`/…`, never `//…`) or an absolute `http://` or `https://`
|
|
2830
|
-
* URL, with no space or backslash. It names only parameters `from`
|
|
2831
|
-
* declares, and none in an absolute URL's scheme, host or port.
|
|
2832
|
-
* - `status` is 301, 302, 307 or 308.
|
|
2833
|
-
* - `host` is a public hostname, lowercase, and is the app's own when the
|
|
2834
|
-
* app has one — on any other the redirect could never match.
|
|
2835
|
-
* - `notHost` is a public hostname, lowercase, never with `host`, and never
|
|
2836
|
-
* the app's own hostname, on which the redirect could never match.
|
|
2837
|
-
* - `query` maps parameter names to the exact string each must hold.
|
|
2838
|
-
* - A redirect to a path on the same address that its own `from` matches
|
|
2839
|
-
* again is refused: every request it answers would be sent round forever.
|
|
2840
|
-
*/
|
|
2841
1597
|
function validateStaticRedirect(value, app) {
|
|
2842
1598
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return {
|
|
2843
1599
|
ok: false,
|
|
@@ -2847,12 +1603,12 @@ function validateStaticRedirect(value, app) {
|
|
|
2847
1603
|
if (from === void 0 && source !== void 0) return {
|
|
2848
1604
|
ok: false,
|
|
2849
1605
|
field: "from",
|
|
2850
|
-
reason: "is missing
|
|
1606
|
+
reason: "is missing \u2014 Vercel's \"source\" is \"from\" here"
|
|
2851
1607
|
};
|
|
2852
1608
|
if (to === void 0 && destination !== void 0) return {
|
|
2853
1609
|
ok: false,
|
|
2854
1610
|
field: "to",
|
|
2855
|
-
reason: "is missing
|
|
1611
|
+
reason: "is missing \u2014 Vercel's \"destination\" is \"to\" here"
|
|
2856
1612
|
};
|
|
2857
1613
|
if (typeof from !== "string" || !from.startsWith("/")) return {
|
|
2858
1614
|
ok: false,
|
|
@@ -2870,17 +1626,17 @@ function validateStaticRedirect(value, app) {
|
|
|
2870
1626
|
if (reserved) return {
|
|
2871
1627
|
ok: false,
|
|
2872
1628
|
field: "from",
|
|
2873
|
-
reason: `cannot be "${reserved}" or under it
|
|
1629
|
+
reason: `cannot be "${reserved}" or under it \u2014 the backend answers that path on every hostname`
|
|
2874
1630
|
};
|
|
2875
1631
|
if (!isPathUnder(prefix, app.path) && !isPathUnder(app.path, prefix)) return {
|
|
2876
1632
|
ok: false,
|
|
2877
1633
|
field: "from",
|
|
2878
|
-
reason: `must be inside this app's path, "${app.path}"
|
|
1634
|
+
reason: `must be inside this app's path, "${app.path}" \u2014 the app is what answers there`
|
|
2879
1635
|
};
|
|
2880
1636
|
if (!isPathUnder(prefix, app.path)) return {
|
|
2881
1637
|
ok: false,
|
|
2882
1638
|
field: "from",
|
|
2883
|
-
reason: `must start with this app's path, "${app.path}"
|
|
1639
|
+
reason: `must start with this app's path, "${app.path}" \u2014 write "${app.path}${from === "/" ? "" : from}" if that is what you mean`
|
|
2884
1640
|
};
|
|
2885
1641
|
if (typeof to !== "string" || to === "") return {
|
|
2886
1642
|
ok: false,
|
|
@@ -2902,7 +1658,7 @@ function validateStaticRedirect(value, app) {
|
|
|
2902
1658
|
if (to.startsWith("//")) return {
|
|
2903
1659
|
ok: false,
|
|
2904
1660
|
field: "to",
|
|
2905
|
-
reason: `must be a path, not a URL without its scheme
|
|
1661
|
+
reason: `must be a path, not a URL without its scheme \u2014 write "https:${to}"`
|
|
2906
1662
|
};
|
|
2907
1663
|
} else {
|
|
2908
1664
|
const authority = to.slice(to.indexOf("//") + 2).split(/[/?#]/)[0];
|
|
@@ -2930,18 +1686,18 @@ function validateStaticRedirect(value, app) {
|
|
|
2930
1686
|
for (const [, , name] of to.matchAll(REDIRECT_PARAM_IN_TO)) if (!declared.has(name)) return {
|
|
2931
1687
|
ok: false,
|
|
2932
1688
|
field: "to",
|
|
2933
|
-
reason: `names ":${name}", which "from" does not declare` + (declared.size > 0 ? `
|
|
1689
|
+
reason: `names ":${name}", which "from" does not declare` + (declared.size > 0 ? ` \u2014 it declares ${[...declared].map((n) => `":${n}"`).join(", ")}` : "")
|
|
2934
1690
|
};
|
|
2935
1691
|
if (status !== void 0 && !isStaticRedirectStatus(status)) return {
|
|
2936
1692
|
ok: false,
|
|
2937
1693
|
field: "status",
|
|
2938
|
-
reason: "must be 301, 302, 307 or 308
|
|
1694
|
+
reason: "must be 301, 302, 307 or 308 \u2014 308 when left out"
|
|
2939
1695
|
};
|
|
2940
1696
|
if (host !== void 0) {
|
|
2941
1697
|
if (typeof host !== "string" || !isValidAppHost(host)) return {
|
|
2942
1698
|
ok: false,
|
|
2943
1699
|
field: "host",
|
|
2944
|
-
reason: "must be a lowercase public hostname like \"example.com\"
|
|
1700
|
+
reason: "must be a lowercase public hostname like \"example.com\" \u2014 no scheme, port or path"
|
|
2945
1701
|
};
|
|
2946
1702
|
if (app.host !== void 0 && host !== app.host) return {
|
|
2947
1703
|
ok: false,
|
|
@@ -2953,7 +1709,7 @@ function validateStaticRedirect(value, app) {
|
|
|
2953
1709
|
if (typeof notHost !== "string" || !isValidAppHost(notHost)) return {
|
|
2954
1710
|
ok: false,
|
|
2955
1711
|
field: "notHost",
|
|
2956
|
-
reason: "must be a lowercase public hostname like \"example.com\"
|
|
1712
|
+
reason: "must be a lowercase public hostname like \"example.com\" \u2014 no scheme, port or path"
|
|
2957
1713
|
};
|
|
2958
1714
|
if (host !== void 0) return {
|
|
2959
1715
|
ok: false,
|
|
@@ -3010,7 +1766,7 @@ function validateStaticRedirect(value, app) {
|
|
|
3010
1766
|
})) return {
|
|
3011
1767
|
ok: false,
|
|
3012
1768
|
field: "to",
|
|
3013
|
-
reason: `sends "${samplePath}${sampleSearch}" to "${first.location}", which "from" matches again
|
|
1769
|
+
reason: `sends "${samplePath}${sampleSearch}" to "${first.location}", which "from" matches again \u2014 every request it answers would be redirected forever. Narrow "from", or send it somewhere "from" does not match`
|
|
3014
1770
|
};
|
|
3015
1771
|
}
|
|
3016
1772
|
}
|
|
@@ -3019,14 +1775,6 @@ function validateStaticRedirect(value, app) {
|
|
|
3019
1775
|
redirect
|
|
3020
1776
|
};
|
|
3021
1777
|
}
|
|
3022
|
-
/**
|
|
3023
|
-
* Where a `cleanUrls` app sends a request for an HTML file by name: `/x.html`
|
|
3024
|
-
* to `/x`, and an `index.html` to its directory, `/docs/index.html` to
|
|
3025
|
-
* `/docs/`. `undefined` for a path that names no `.html` file.
|
|
3026
|
-
*
|
|
3027
|
-
* The path is compared as it arrives, percent-encoded; the caller keeps the
|
|
3028
|
-
* query string and redirects only when the file exists.
|
|
3029
|
-
*/
|
|
3030
1778
|
function cleanUrlFor(requestPath) {
|
|
3031
1779
|
if (!requestPath.endsWith(".html")) return void 0;
|
|
3032
1780
|
const slash = requestPath.lastIndexOf("/");
|
|
@@ -3035,26 +1783,11 @@ function cleanUrlFor(requestPath) {
|
|
|
3035
1783
|
if (name === "index.html") return requestPath.slice(0, slash + 1);
|
|
3036
1784
|
return requestPath.slice(0, -5);
|
|
3037
1785
|
}
|
|
3038
|
-
/** Hosts plain `http://` is accepted for: a CMS running on the developer's own machine. */
|
|
3039
1786
|
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
|
|
3040
1787
|
"localhost",
|
|
3041
1788
|
"127.0.0.1",
|
|
3042
1789
|
"[::1]"
|
|
3043
1790
|
]);
|
|
3044
|
-
/**
|
|
3045
|
-
* Validate one entry of a static app's `frameAncestors`: a single origin that
|
|
3046
|
-
* may frame the app.
|
|
3047
|
-
*
|
|
3048
|
-
* The value ends up inside a `Content-Security-Policy` header, so it is held
|
|
3049
|
-
* to the exact serialisation of an origin — `new URL(value).origin` has to
|
|
3050
|
-
* give it back unchanged. That leaves nothing that could close the directive
|
|
3051
|
-
* or open another one, and turns every near miss (a trailing slash, a
|
|
3052
|
-
* capital, a default port, a path) into a refusal that names the fix.
|
|
3053
|
-
*
|
|
3054
|
-
* `https://` with a public hostname, or `localhost`; plain `http://` only for
|
|
3055
|
-
* a loopback host. Never a wildcard or a keyword: this is a list of the
|
|
3056
|
-
* origins an operator chose, and `'self'` is always on it.
|
|
3057
|
-
*/
|
|
3058
1791
|
function parseFrameAncestor(value) {
|
|
3059
1792
|
const example = "must be an origin like \"https://admin.example.com\"";
|
|
3060
1793
|
if (typeof value !== "string" || value === "") return {
|
|
@@ -3063,11 +1796,11 @@ function parseFrameAncestor(value) {
|
|
|
3063
1796
|
};
|
|
3064
1797
|
if (value.includes("*")) return {
|
|
3065
1798
|
ok: false,
|
|
3066
|
-
reason: "must name one origin
|
|
1799
|
+
reason: "must name one origin \u2014 wildcards are not accepted, so list each origin that may frame this app"
|
|
3067
1800
|
};
|
|
3068
1801
|
if (value.startsWith("'")) return {
|
|
3069
1802
|
ok: false,
|
|
3070
|
-
reason: `${example}
|
|
1803
|
+
reason: `${example} \u2014 keywords are not accepted, and 'self' is always allowed`
|
|
3071
1804
|
};
|
|
3072
1805
|
let url;
|
|
3073
1806
|
try {
|
|
@@ -3085,7 +1818,7 @@ function parseFrameAncestor(value) {
|
|
|
3085
1818
|
const loopback = LOOPBACK_HOSTS.has(url.hostname);
|
|
3086
1819
|
if (url.protocol === "http:" && !loopback) return {
|
|
3087
1820
|
ok: false,
|
|
3088
|
-
reason: `must use https
|
|
1821
|
+
reason: `must use https \u2014 plain http is accepted for localhost only: "https://${url.host}"`
|
|
3089
1822
|
};
|
|
3090
1823
|
if (!loopback && !isValidAppHost(url.hostname)) return {
|
|
3091
1824
|
ok: false,
|
|
@@ -3093,122 +1826,19 @@ function parseFrameAncestor(value) {
|
|
|
3093
1826
|
};
|
|
3094
1827
|
if (url.origin !== value) return {
|
|
3095
1828
|
ok: false,
|
|
3096
|
-
reason: `must be the origin alone
|
|
1829
|
+
reason: `must be the origin alone \u2014 scheme, hostname and an optional port, lowercase, with nothing after it: "${url.origin}"`
|
|
3097
1830
|
};
|
|
3098
1831
|
return {
|
|
3099
1832
|
ok: true,
|
|
3100
1833
|
origin: value
|
|
3101
1834
|
};
|
|
3102
1835
|
}
|
|
3103
|
-
/**
|
|
3104
|
-
* Version of the bundle *format* itself.
|
|
3105
|
-
*
|
|
3106
|
-
* Bumped only when the on-disk layout changes in a way an older runtime could
|
|
3107
|
-
* not read. A runtime accepts any bundle whose `bundleFormat` is less than or
|
|
3108
|
-
* equal to its own — old bundles keep booting on new runtimes, which is the
|
|
3109
|
-
* whole point of separating the artifact from the engine.
|
|
3110
|
-
*
|
|
3111
|
-
* - **1** — `mode: "cms" | "baas" | "static"`, `entry.static` a single directory
|
|
3112
|
-
* string, `entry.admin` for a bundled admin panel.
|
|
3113
|
-
* - **2** — `kind: "backend" | "static"`, `entry.static` a list of
|
|
3114
|
-
* {@link RebaseBundleStatic}, `entry.admin` removed. A format-1 runtime reading
|
|
3115
|
-
* one of these would find no `mode` and an array where it expects a string, so
|
|
3116
|
-
* the bump is what turns that into a refusal to boot instead of a bundle that
|
|
3117
|
-
* starts and serves nothing.
|
|
3118
|
-
* - **3** — the schema is `entry.tables` (the compiled `backend/schema`
|
|
3119
|
-
* directory, whose `index` exports the tables), beside `entry.resources`,
|
|
3120
|
-
* `entry.storage` and `entry.hooks`. There is no config package any more:
|
|
3121
|
-
* `entry.config`, `entry.collections` and `entry.usersCollection` are not
|
|
3122
|
-
* written. A format-2 runtime would find none of the keys it boots from and
|
|
3123
|
-
* introspect the database instead of serving the declared tables — so the
|
|
3124
|
-
* bump turns that into a refusal.
|
|
3125
|
-
*
|
|
3126
|
-
* **Format 2 bundles are refused, not upgraded.** Unlike 1 → 2, which was a
|
|
3127
|
-
* renaming, a format-2 bundle carries `config/collections` — `defineCollection`
|
|
3128
|
-
* objects — and a runtime that reads only `backend/schema` has nothing to read
|
|
3129
|
-
* them with. It refuses them at boot with {@link LEGACY_LAYOUT_REMEDY} in the
|
|
3130
|
-
* error: run the codemod on the project's source, then rebuild.
|
|
3131
|
-
*/
|
|
3132
1836
|
var BUNDLE_FORMAT_VERSION = 3;
|
|
3133
|
-
/**
|
|
3134
|
-
* What to do about a project on the `config/collections` layout — the words
|
|
3135
|
-
* every refusal of that layout ends with.
|
|
3136
|
-
*
|
|
3137
|
-
* Shared because two parties refuse it and must say the same thing: the CLI,
|
|
3138
|
-
* for a `rebase.json` that still names `config` or `usersCollection`, and the
|
|
3139
|
-
* runtime, for a format-2 / contract-1 bundle built from `config/collections`.
|
|
3140
|
-
*/
|
|
3141
1837
|
var LEGACY_LAYOUT_REMEDY = "run `rebase migrate collections-to-tables` (in the Rebase repository: tooling/scripts/migrate-collections-to-tables.mts), which rewrites config/collections as backend/schema (and the admin presentation as frontend/src/cms), carries the collection callbacks into the tables as hooks, moves resources.ts and storage.ts to backend/, and proves the generated SQL unchanged; then rebuild";
|
|
3142
|
-
/**
|
|
3143
|
-
* The runtime contract major.
|
|
3144
|
-
*
|
|
3145
|
-
* Distinct from the `@rebasepro/server` package version: the package may release
|
|
3146
|
-
* any number of minors and patches while this stays put. It changes only when
|
|
3147
|
-
* the bundle/runtime contract breaks compatibility, and a project's
|
|
3148
|
-
* `manifest.runtime` range is matched against *this*.
|
|
3149
|
-
*
|
|
3150
|
-
* ## v2 — tables, not collections
|
|
3151
|
-
*
|
|
3152
|
-
* The runtime reads the project's schema from `backend/schema` (bundle format
|
|
3153
|
-
* 3, `entry.tables`): `defineTable` / `defineAuthTable` / `defineView` exports
|
|
3154
|
-
* and `defaultRls`. It no longer loads `config/collections`, and it no longer
|
|
3155
|
-
* reads a config package's `collections` / `callbacks` exports or a
|
|
3156
|
-
* `usersCollection` module; global table hooks come from `backend/hooks.ts`,
|
|
3157
|
-
* `storageAuthorize` from `backend/storage.ts`, declared resources from
|
|
3158
|
-
* `backend/resources.ts`.
|
|
3159
|
-
*
|
|
3160
|
-
* So, plainly: **a format-2 / contract-1 bundle — one built from
|
|
3161
|
-
* `config/collections` — is refused by a contract-2 runtime**, at boot, with
|
|
3162
|
-
* {@link LEGACY_LAYOUT_REMEDY} in the message. There is no in-runtime adapter
|
|
3163
|
-
* from collections to tables; the project's source is migrated once with the
|
|
3164
|
-
* codemod and rebuilt. On the managed tier that means the platform keeps such a
|
|
3165
|
-
* tenant on a contract-1 image until it is rebuilt — the release order below
|
|
3166
|
-
* applies unchanged.
|
|
3167
|
-
*
|
|
3168
|
-
* This has to be a major, and the reason is the managed tier: it moves projects
|
|
3169
|
-
* onto new images WITHOUT rebuilding them. Without the bump, one image rollout
|
|
3170
|
-
* would crash-loop every tenant whose bundle predates the change, in a wave,
|
|
3171
|
-
* with the cause in a container log nobody is watching. With it, an older
|
|
3172
|
-
* bundle on a newer runtime is refused by `readBundleManifest` with the remedy
|
|
3173
|
-
* in the message, and the platform keeps it on an image of its own major until
|
|
3174
|
-
* it is rebuilt. That is the whole purpose of this number.
|
|
3175
|
-
*
|
|
3176
|
-
* (Declared resources — `database()` / `bucket()` replacing
|
|
3177
|
-
* `RebaseBackendConfig.dataSources` / `.storageSources` — once took this number
|
|
3178
|
-
* to 2 and were taken back to 1 before launch, when there was no fleet for the
|
|
3179
|
-
* major to protect. They are part of v1.)
|
|
3180
|
-
*
|
|
3181
|
-
* **Release order matters and is not optional.** The control plane is the side
|
|
3182
|
-
* that rejects, so it ships FIRST: raise `SUPPORTED_RUNTIME_CONTRACT` in the
|
|
3183
|
-
* saas repo (it rejects only `contract >` its own, so it then accepts both),
|
|
3184
|
-
* deploy that, and only then release a runtime implementing v2. Shipping the
|
|
3185
|
-
* runtime first turns every deploy into a rejected intake blaming the tenant's
|
|
3186
|
-
* bundle.
|
|
3187
|
-
*/
|
|
3188
1838
|
var RUNTIME_CONTRACT_VERSION = 2;
|
|
3189
|
-
/** Header carrying the schema version an SDK was generated from. */
|
|
3190
1839
|
var SCHEMA_VERSION_HEADER = "x-rebase-schema";
|
|
3191
1840
|
//#endregion
|
|
3192
1841
|
//#region src/types/content_hash.ts
|
|
3193
|
-
/**
|
|
3194
|
-
* Whether a static build's file name carries a content hash: the files the
|
|
3195
|
-
* runtime serves `immutable` for a year, and the ones `rebase build` writes
|
|
3196
|
-
* `.br` and `.gz` beside. One rule for both, so a file is never precompressed
|
|
3197
|
-
* and revalidated, or cached for a year and compressed on every request.
|
|
3198
|
-
*
|
|
3199
|
-
* Two shapes count:
|
|
3200
|
-
*
|
|
3201
|
-
* - **Vite's own**, `[name]-[hash]`: the last eight characters of the name,
|
|
3202
|
-
* after a `-`. They are base64url, an alphabet with `-` and `_` in it, so
|
|
3203
|
-
* about one hash in eight holds a `-` (`index-C-WpENHZ.js`,
|
|
3204
|
-
* `page10-D6Dq--fD.js`), and the last `-` is not where it starts.
|
|
3205
|
-
* - **A longer one** with no `-` in it, eight characters or more after the last
|
|
3206
|
-
* `-` (`[hash:12]`, another bundler's names).
|
|
3207
|
-
*
|
|
3208
|
-
* Either must hold a digit or a capital. That is the evidence of a hash: a
|
|
3209
|
-
* hand-written `vendor-analytics.js` is not taken for one, and gets revalidated
|
|
3210
|
-
* rather than pinned in every visitor's cache with no way to recall it.
|
|
3211
|
-
*/
|
|
3212
1842
|
function isContentHashedFileName(fileName) {
|
|
3213
1843
|
const dot = fileName.lastIndexOf(".");
|
|
3214
1844
|
if (dot <= 0) return false;
|
|
@@ -3219,73 +1849,20 @@ function isContentHashedFileName(fileName) {
|
|
|
3219
1849
|
const suffix = stem.slice(dash + 1);
|
|
3220
1850
|
return suffix.length >= 8 && looksLikeHash(suffix);
|
|
3221
1851
|
}
|
|
3222
|
-
/** Base64url throughout, with a digit or a capital somewhere in it. */
|
|
3223
1852
|
function looksLikeHash(text) {
|
|
3224
1853
|
return /^[A-Za-z0-9_-]+$/.test(text) && /[0-9A-Z]/.test(text);
|
|
3225
1854
|
}
|
|
3226
1855
|
//#endregion
|
|
3227
1856
|
//#region src/types/schema_version.ts
|
|
3228
|
-
/**
|
|
3229
|
-
* The schema version stamp.
|
|
3230
|
-
*
|
|
3231
|
-
* One function, used in three places that must agree or the whole drift-detection
|
|
3232
|
-
* story is noise: `rebase build` writes it into a bundle manifest, the runtime
|
|
3233
|
-
* serves it from the contract endpoint and stamps it into the database it
|
|
3234
|
-
* provisions, and a generated SDK records the value it was built from. If any
|
|
3235
|
-
* two of those computed it differently, every client would look permanently out
|
|
3236
|
-
* of date.
|
|
3237
|
-
*
|
|
3238
|
-
* It covers **tables only** — their compiled descriptors — so editing a hook's
|
|
3239
|
-
* code or a server function never invalidates every SDK in every repository.
|
|
3240
|
-
* That is a deliberate narrowing, not an oversight.
|
|
3241
|
-
*
|
|
3242
|
-
* Versions are prefixed `v2:` (descriptors, since 0.31); `v1:` versions were
|
|
3243
|
-
* computed from collections — see {@link LEGACY_SCHEMA_VERSION_PREFIX}.
|
|
3244
|
-
*/
|
|
3245
|
-
/** Stable stringify: object keys sorted at every level, so key order cannot alter the hash. */
|
|
3246
1857
|
function canonicalize(value) {
|
|
3247
1858
|
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
3248
1859
|
if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`;
|
|
3249
1860
|
return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalize(v)}`).join(",")}}`;
|
|
3250
1861
|
}
|
|
3251
|
-
/**
|
|
3252
|
-
* The prefix of a version computed before 0.31, from collections.
|
|
3253
|
-
*
|
|
3254
|
-
* A database stamped with one was provisioned under the collection model. Its
|
|
3255
|
-
* version can never equal a descriptor version, so the first boot of a 0.31
|
|
3256
|
-
* runtime against it reports a mismatch once — and says why, and how to
|
|
3257
|
-
* restamp.
|
|
3258
|
-
*/
|
|
3259
1862
|
var LEGACY_SCHEMA_VERSION_PREFIX = "v1:";
|
|
3260
|
-
/**
|
|
3261
|
-
* Compute the canonical string a schema version hashes: the tables'
|
|
3262
|
-
* descriptors, ordered by slug, every object's keys sorted.
|
|
3263
|
-
*
|
|
3264
|
-
* A descriptor is the compiled table — every default applied, every name
|
|
3265
|
-
* derived, `rls` resolved against `defaultRls` — so the same source compiles to
|
|
3266
|
-
* the same descriptor before or after anything loads it, and a build-time
|
|
3267
|
-
* stamp can match the server that serves it. It is plain JSON by
|
|
3268
|
-
* construction: hooks appear only as presence flags (`hooks.afterRead: true`),
|
|
3269
|
-
* so editing what a hook does never moves the version, while adding or
|
|
3270
|
-
* removing one does.
|
|
3271
|
-
*
|
|
3272
|
-
* Ordered by slug, so the order the tables were exported in cannot alter it.
|
|
3273
|
-
*
|
|
3274
|
-
* Exposed separately so the hashing itself can differ by environment: Node has
|
|
3275
|
-
* `crypto`, and callers without it can still compare canonical forms directly.
|
|
3276
|
-
*/
|
|
3277
1863
|
function canonicalSchemaPayload(tables) {
|
|
3278
1864
|
return canonicalize([...tables].sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));
|
|
3279
1865
|
}
|
|
3280
|
-
/**
|
|
3281
|
-
* A short, non-cryptographic digest of the canonical payload.
|
|
3282
|
-
*
|
|
3283
|
-
* FNV-1a style, 64 bits, as two 32-bit halves. This is an identity, not a
|
|
3284
|
-
* security boundary: nothing trusts a schema version to prove anything, it only
|
|
3285
|
-
* answers "is this the same schema as before". A hand-rolled hash keeps this
|
|
3286
|
-
* module free of `node:crypto`, so the identical function runs in the browser,
|
|
3287
|
-
* in the CLI, and in the runtime — which is the property that actually matters.
|
|
3288
|
-
*/
|
|
3289
1866
|
function computeSchemaVersion(tables) {
|
|
3290
1867
|
const payload = canonicalSchemaPayload(tables);
|
|
3291
1868
|
let h1 = 2166136261;
|
|
@@ -3302,15 +1879,6 @@ function computeSchemaVersion(tables) {
|
|
|
3302
1879
|
}
|
|
3303
1880
|
//#endregion
|
|
3304
1881
|
//#region src/types/storage_authorize.ts
|
|
3305
|
-
/**
|
|
3306
|
-
* Where a project with no storage rules of its own starts — what Rebase
|
|
3307
|
-
* Cloud gives a new project and what its console offers as "recommended":
|
|
3308
|
-
* a `public/` folder anyone may read, a `users/<uid>/` folder only its user
|
|
3309
|
-
* may touch, and every key to admins. Rules are deny-by-default, so this is
|
|
3310
|
-
* also everything a caller may do.
|
|
3311
|
-
*
|
|
3312
|
-
* @group Storage
|
|
3313
|
-
*/
|
|
3314
1882
|
var RECOMMENDED_STORAGE_RULES = Object.freeze([
|
|
3315
1883
|
{
|
|
3316
1884
|
path: "public/**",
|
|
@@ -3328,23 +1896,6 @@ var RECOMMENDED_STORAGE_RULES = Object.freeze([
|
|
|
3328
1896
|
]);
|
|
3329
1897
|
//#endregion
|
|
3330
1898
|
//#region src/types/mcp_app_modules.ts
|
|
3331
|
-
/**
|
|
3332
|
-
* The modules an app Claude writes for show_app may import, and from each the
|
|
3333
|
-
* names the MCP view serves.
|
|
3334
|
-
*
|
|
3335
|
-
* An app imports the real package names, so the code reads — and pastes into
|
|
3336
|
-
* a project — like every other piece of Rebase code. Inside the view each
|
|
3337
|
-
* name is the package's own part: `"*"` serves the whole module, a list
|
|
3338
|
-
* serves exactly those exports. The one list three readers share, so none
|
|
3339
|
-
* can drift from the others:
|
|
3340
|
-
*
|
|
3341
|
-
* - the view's module registry (`@rebasepro/cms/mcp-view`), which hands an
|
|
3342
|
-
* app these exports and no others;
|
|
3343
|
-
* - the server's compiler for show_app, which refuses any other import
|
|
3344
|
-
* before the app opens, naming it;
|
|
3345
|
-
* - show_app's guide (`SHOW_APP_CODE_GUIDE` in `@rebasepro/server`), which a
|
|
3346
|
-
* test holds to this list.
|
|
3347
|
-
*/
|
|
3348
1899
|
var MCP_APP_MODULES = {
|
|
3349
1900
|
"react": "*",
|
|
3350
1901
|
"react/jsx-runtime": "*",
|
|
@@ -3372,12 +1923,6 @@ var MCP_APP_MODULES = {
|
|
|
3372
1923
|
};
|
|
3373
1924
|
//#endregion
|
|
3374
1925
|
//#region src/types/ui_preferences.ts
|
|
3375
|
-
/**
|
|
3376
|
-
* Every key a {@link UiTablePreferences} may hold, as data: what the server
|
|
3377
|
-
* validates a stored preference by.
|
|
3378
|
-
*
|
|
3379
|
-
* @group UI preferences
|
|
3380
|
-
*/
|
|
3381
1926
|
var UI_PREFERENCE_TABLE_KEYS = [
|
|
3382
1927
|
"alwaysApplyDefaultValues",
|
|
3383
1928
|
"customViews",
|
|
@@ -3415,11 +1960,6 @@ var UI_PREFERENCE_TABLE_KEYS = [
|
|
|
3415
1960
|
"singularName",
|
|
3416
1961
|
"sort"
|
|
3417
1962
|
];
|
|
3418
|
-
/**
|
|
3419
|
-
* Every key a {@link UiFieldPreferences} may hold, as data.
|
|
3420
|
-
*
|
|
3421
|
-
* @group UI preferences
|
|
3422
|
-
*/
|
|
3423
1963
|
var UI_PREFERENCE_FIELD_KEYS = [
|
|
3424
1964
|
"canAddElements",
|
|
3425
1965
|
"clearable",
|
|
@@ -3500,11 +2040,6 @@ var fieldMap = (value, path, out) => {
|
|
|
3500
2040
|
}
|
|
3501
2041
|
for (const [key, field] of Object.entries(value)) fieldProblems(field, `${path}.${key}`, out);
|
|
3502
2042
|
};
|
|
3503
|
-
/**
|
|
3504
|
-
* The checks, built on first use: module-level calls would keep this file in
|
|
3505
|
-
* every bundle that imports `@rebasepro/types`, whether it validates a
|
|
3506
|
-
* preference or not.
|
|
3507
|
-
*/
|
|
3508
2043
|
var builtChecks;
|
|
3509
2044
|
function checks() {
|
|
3510
2045
|
builtChecks ??= {
|
|
@@ -3634,13 +2169,6 @@ function fieldProblems(value, path, out) {
|
|
|
3634
2169
|
checks().field[key](entry, `${path}.${key}`, out);
|
|
3635
2170
|
}
|
|
3636
2171
|
}
|
|
3637
|
-
/**
|
|
3638
|
-
* Every problem with a table's preference delta as it arrived: a key that is
|
|
3639
|
-
* not a preference (a schema fact, a component, a misspelling) or a value of
|
|
3640
|
-
* the wrong shape. Empty when it may be stored.
|
|
3641
|
-
*
|
|
3642
|
-
* @group UI preferences
|
|
3643
|
-
*/
|
|
3644
2172
|
function uiTablePreferencesProblems(value) {
|
|
3645
2173
|
const out = [];
|
|
3646
2174
|
if (!isRecord$1(value)) return [{
|
|
@@ -3660,20 +2188,9 @@ function uiTablePreferencesProblems(value) {
|
|
|
3660
2188
|
}
|
|
3661
2189
|
return out;
|
|
3662
2190
|
}
|
|
3663
|
-
/**
|
|
3664
|
-
* Whether a value is a well-formed {@link UiTablePreferences} delta.
|
|
3665
|
-
*
|
|
3666
|
-
* @group UI preferences
|
|
3667
|
-
*/
|
|
3668
2191
|
function isUiTablePreferences(value) {
|
|
3669
2192
|
return uiTablePreferencesProblems(value).length === 0;
|
|
3670
2193
|
}
|
|
3671
|
-
/**
|
|
3672
|
-
* One delta over another: what `over` names replaces what `base` says, key by
|
|
3673
|
-
* key, and `fields` (and a field's nested `fields` / `of`) field by field.
|
|
3674
|
-
*
|
|
3675
|
-
* @group UI preferences
|
|
3676
|
-
*/
|
|
3677
2194
|
function mergeUiTablePreferences(base, over) {
|
|
3678
2195
|
const out = {
|
|
3679
2196
|
...base,
|
|
@@ -3702,98 +2219,14 @@ function mergeField(base, over) {
|
|
|
3702
2219
|
}
|
|
3703
2220
|
//#endregion
|
|
3704
2221
|
//#region src/controllers/data.ts
|
|
3705
|
-
/**
|
|
3706
|
-
* Hops an {@link IncludeSpec} may nest. `comments.author` is two.
|
|
3707
|
-
*
|
|
3708
|
-
* @group Data
|
|
3709
|
-
*/
|
|
3710
2222
|
var MAX_INCLUDE_DEPTH = 3;
|
|
3711
|
-
/**
|
|
3712
|
-
* SDK table client — returns flat rows, no Entity wrapper.
|
|
3713
|
-
*
|
|
3714
|
-
* This is the public API surface for app developers using
|
|
3715
|
-
* `createRebaseClient()`.
|
|
3716
|
-
*
|
|
3717
|
-
* Type parameters:
|
|
3718
|
-
* - `M` — the **Row** shape returned by reads (`find`, `findById`, `listen`).
|
|
3719
|
-
* - `I` — the **Insert** shape accepted by {@link create}. Defaults to
|
|
3720
|
-
* `Partial<M>`; the generated SDK supplies a dedicated `Insert` type where
|
|
3721
|
-
* required columns are required and auto-generated / read-only columns are
|
|
3722
|
-
* omitted, so `create({})` on a table with required fields is a compile error.
|
|
3723
|
-
* - `U` — the **Update** shape accepted by {@link update}. Defaults to
|
|
3724
|
-
* `Partial<M>`; the generated SDK supplies a dedicated `Update` type.
|
|
3725
|
-
*
|
|
3726
|
-
* @example
|
|
3727
|
-
* const { data: posts } = await rebase.data.posts.find();
|
|
3728
|
-
* console.log(posts[0].title); // flat access
|
|
3729
|
-
* console.log(posts[0].id); // id at top level
|
|
3730
|
-
*
|
|
3731
|
-
* const post = await rebase.data.posts.findById(1);
|
|
3732
|
-
* console.log(post?.title); // no .values needed
|
|
3733
|
-
*
|
|
3734
|
-
* @group Data
|
|
3735
|
-
*/
|
|
3736
|
-
/**
|
|
3737
|
-
* A change expressed as an operation on the column's current value, rather than
|
|
3738
|
-
* as the value to store.
|
|
3739
|
-
*
|
|
3740
|
-
* `{ views: 5 }` says what the number becomes; `{ views: { $inc: 1 } }` says
|
|
3741
|
-
* what happens to it. The difference is the read the caller no longer has to
|
|
3742
|
-
* make — and the race that read opens. Two requests that each read `4`, add one
|
|
3743
|
-
* and write `5` lose an increment between them; `SET views = views + 1` cannot,
|
|
3744
|
-
* because the arithmetic happens inside the statement holding the row lock.
|
|
3745
|
-
*
|
|
3746
|
-
* Exactly one operator per field. `{ views: { $inc: 1, $push: "x" } }` is
|
|
3747
|
-
* refused rather than applied in an order the caller cannot see.
|
|
3748
|
-
*
|
|
3749
|
-
* @group Data
|
|
3750
|
-
*/
|
|
3751
|
-
/**
|
|
3752
|
-
* The operator names, as a value.
|
|
3753
|
-
*
|
|
3754
|
-
* A runtime list beside the type because three layers have to *recognise* an
|
|
3755
|
-
* operation, not just accept one: the REST validator, the driver that compiles
|
|
3756
|
-
* it, and the offline queue that must refuse to apply one locally. Three copies
|
|
3757
|
-
* of four strings is three chances for one of them to miss an operator added to
|
|
3758
|
-
* the other two, and the failure is silent in the worst direction — an
|
|
3759
|
-
* unrecognised marker is written to the column as a JSON document.
|
|
3760
|
-
*
|
|
3761
|
-
* @group Data
|
|
3762
|
-
*/
|
|
3763
2223
|
var FIELD_OPERATORS = [
|
|
3764
2224
|
"$inc",
|
|
3765
2225
|
"$push",
|
|
3766
2226
|
"$pull",
|
|
3767
2227
|
"$merge"
|
|
3768
2228
|
];
|
|
3769
|
-
/**
|
|
3770
|
-
* The key of a {@link BatchRef}. Declared here, beside the field operators,
|
|
3771
|
-
* because the two share one namespace: a `$`-prefixed key in a write payload is
|
|
3772
|
-
* a marker, and every reader of that namespace has to know all of it.
|
|
3773
|
-
*
|
|
3774
|
-
* @group Data
|
|
3775
|
-
*/
|
|
3776
2229
|
var BATCH_REF_KEY = "$ref";
|
|
3777
|
-
/**
|
|
3778
|
-
* Whether a value is *trying* to be a field operation — including a misspelled
|
|
3779
|
-
* one, which is the case worth catching.
|
|
3780
|
-
*
|
|
3781
|
-
* Any `$`-prefixed key counts, because `{ $increment: 1 }` written to a number
|
|
3782
|
-
* column as a JSON document is the failure this exists to prevent.
|
|
3783
|
-
*
|
|
3784
|
-
* Except on a `map` (pass `propertyType`): a map's value is a JSON document,
|
|
3785
|
-
* and one may legitimately carry `$` keys — a JSON Schema's `$schema`, a
|
|
3786
|
-
* document exported from another database. There, only a single-key object whose key is one of
|
|
3787
|
-
* {@link FIELD_OPERATORS} is an operation, and anything else is data. A caller
|
|
3788
|
-
* that does not know the property type gets the strict reading.
|
|
3789
|
-
*
|
|
3790
|
-
* The one exception is `{ $ref: … }`, the batch's backward reference. It stands
|
|
3791
|
-
* where a *value* goes and is resolved to one before the row is written, so it
|
|
3792
|
-
* is not an operation on a column — reading it as a misspelled operator refused
|
|
3793
|
-
* every `$ref` in a batch with "unknown field operator '$ref'".
|
|
3794
|
-
*
|
|
3795
|
-
* @group Data
|
|
3796
|
-
*/
|
|
3797
2230
|
function isFieldOperation(value, propertyType) {
|
|
3798
2231
|
if (typeof value !== "object" || value === null || Array.isArray(value) || value instanceof Date) return false;
|
|
3799
2232
|
const keys = Object.keys(value);
|
|
@@ -3801,27 +2234,15 @@ function isFieldOperation(value, propertyType) {
|
|
|
3801
2234
|
if (propertyType === "map") return keys.length === 1 && FIELD_OPERATORS.includes(keys[0]);
|
|
3802
2235
|
return keys.some((key) => key.startsWith("$"));
|
|
3803
2236
|
}
|
|
3804
|
-
/** True when any value in a write payload is (or is attempting to be) one. @group Data */
|
|
3805
2237
|
function hasFieldOperation(values) {
|
|
3806
2238
|
return !!values && Object.values(values).some((value) => isFieldOperation(value));
|
|
3807
2239
|
}
|
|
3808
2240
|
//#endregion
|
|
3809
2241
|
//#region src/controllers/data_driver.ts
|
|
3810
|
-
/** Rows returned for a plain / text-search list read when the client sends no `limit`. */
|
|
3811
2242
|
var DEFAULT_LIST_LIMIT = 50;
|
|
3812
|
-
/** Rows returned for a vector-search list read when the client sends no `limit`. */
|
|
3813
2243
|
var DEFAULT_VECTOR_LIST_LIMIT = 10;
|
|
3814
|
-
/** Largest `limit` a client may ask for on any surface. Above it, the read is refused. */
|
|
3815
2244
|
var MAX_LIST_LIMIT = 1e3;
|
|
3816
|
-
/**
|
|
3817
|
-
* Thrown by {@link resolveClientListLimit} for a `limit` the platform will not
|
|
3818
|
-
* serve. Carries an HTTP status so an ingress that speaks HTTP can forward it
|
|
3819
|
-
* verbatim, and `maxLimit` so one can be built without re-deriving the ceiling.
|
|
3820
|
-
*
|
|
3821
|
-
* @group Errors
|
|
3822
|
-
*/
|
|
3823
2245
|
var ListLimitError = class ListLimitError extends RebaseApiError {
|
|
3824
|
-
/** The ceiling that was exceeded — what the caller should page by instead. */
|
|
3825
2246
|
maxLimit;
|
|
3826
2247
|
constructor(message, maxLimit) {
|
|
3827
2248
|
super(message, {
|
|
@@ -3833,74 +2254,23 @@ var ListLimitError = class ListLimitError extends RebaseApiError {
|
|
|
3833
2254
|
Object.setPrototypeOf(this, ListLimitError.prototype);
|
|
3834
2255
|
}
|
|
3835
2256
|
};
|
|
3836
|
-
/**
|
|
3837
|
-
* Resolve a client-supplied list `limit` into a safe, always-defined value.
|
|
3838
|
-
*
|
|
3839
|
-
* - An absent / blank limit falls back to the mode default:
|
|
3840
|
-
* `vectorDefaultLimit` for a vector search, otherwise `defaultLimit`.
|
|
3841
|
-
* - A limit that is present must be an integer in `[1, maxLimit]`. Anything
|
|
3842
|
-
* else — `0`, a negative, `1.5`, `abc`, `100000000` — throws
|
|
3843
|
-
* {@link ListLimitError} rather than being coerced into range, because every
|
|
3844
|
-
* coercion answers a question the caller did not ask with a page it cannot
|
|
3845
|
-
* tell apart from the whole collection.
|
|
3846
|
-
*
|
|
3847
|
-
* The return is never `undefined` — no ingress that routes its client limit
|
|
3848
|
-
* through this can produce an unbounded read.
|
|
3849
|
-
*
|
|
3850
|
-
* @throws {ListLimitError} when a present `limit` is not an integer in range.
|
|
3851
|
-
*/
|
|
3852
2257
|
function resolveClientListLimit(rawLimit, opts = {}) {
|
|
3853
2258
|
const maxLimit = opts.maxLimit ?? 1e3;
|
|
3854
2259
|
if (rawLimit != null && String(rawLimit).trim() !== "") {
|
|
3855
2260
|
const parsed = typeof rawLimit === "number" ? rawLimit : Number(String(rawLimit).trim());
|
|
3856
2261
|
if (!Number.isInteger(parsed) || parsed < 1) throw new ListLimitError(`Invalid \`limit\`: ${String(rawLimit)}. Expected a whole number between 1 and ${maxLimit}.`, maxLimit);
|
|
3857
|
-
if (parsed > maxLimit) throw new ListLimitError(`\`limit\` ${parsed} is above the maximum of ${maxLimit}. Ask for at most ${maxLimit} rows per read and page through the rest with \`offset\`
|
|
2262
|
+
if (parsed > maxLimit) throw new ListLimitError(`\`limit\` ${parsed} is above the maximum of ${maxLimit}. Ask for at most ${maxLimit} rows per read and page through the rest with \`offset\` \u2014 answering with a smaller page would be indistinguishable from there being no more rows.`, maxLimit);
|
|
3858
2263
|
return parsed;
|
|
3859
2264
|
}
|
|
3860
2265
|
return opts.vectorSearch ? opts.vectorDefaultLimit ?? 10 : opts.defaultLimit ?? 50;
|
|
3861
2266
|
}
|
|
3862
2267
|
//#endregion
|
|
3863
2268
|
//#region src/controllers/storage.ts
|
|
3864
|
-
/**
|
|
3865
|
-
* Path prefix that marks an object as **public**. Files stored under this
|
|
3866
|
-
* prefix are served without any auth token via a stable, permanent,
|
|
3867
|
-
* CDN-cacheable URL (see {@link StorageSource.getSignedUrl}). Shared by the
|
|
3868
|
-
* client SDK and the backend so both agree on which objects are public.
|
|
3869
|
-
*
|
|
3870
|
-
* @group Models
|
|
3871
|
-
*/
|
|
3872
2269
|
var PUBLIC_STORAGE_PREFIX = "public/";
|
|
3873
|
-
/**
|
|
3874
|
-
* True when a storage **key** is public: it lies under
|
|
3875
|
-
* {@link PUBLIC_STORAGE_PREFIX}.
|
|
3876
|
-
*
|
|
3877
|
-
* The key is read exactly as it is — the canonical key within its bucket, the
|
|
3878
|
-
* one the server stores, serves, and hands a `storageAuthorize` hook as
|
|
3879
|
-
* `key` — and nothing is parsed out of it. That is the difference from
|
|
3880
|
-
* {@link isPublicStoragePath}, which reads a client-side *path* and so strips
|
|
3881
|
-
* a `scheme://` and a leading `default/` bucket segment first. On a key both are
|
|
3882
|
-
* wrong: `default/public/x` is a key in a folder called `default`, and a
|
|
3883
|
-
* request path `notes://public/x` names the key `notes:/public/x`. Neither is
|
|
3884
|
-
* public, and the server decides on this function so that it never says they
|
|
3885
|
-
* are.
|
|
3886
|
-
*
|
|
3887
|
-
* @group Models
|
|
3888
|
-
*/
|
|
3889
2270
|
function isPublicStorageKey(key) {
|
|
3890
2271
|
if (!key || !key.startsWith("public/")) return false;
|
|
3891
2272
|
return !key.split(/[\\/]/).includes("..");
|
|
3892
2273
|
}
|
|
3893
|
-
/**
|
|
3894
|
-
* True when a storage key or client-side path points at a public object
|
|
3895
|
-
* (lives under {@link PUBLIC_STORAGE_PREFIX}).
|
|
3896
|
-
*
|
|
3897
|
-
* For a path as a client holds it: a `scheme://` prefix and a single leading
|
|
3898
|
-
* `default/` bucket segment are stripped first. The server and a
|
|
3899
|
-
* `storageAuthorize` hook, which hold the canonical key, use
|
|
3900
|
-
* {@link isPublicStorageKey}.
|
|
3901
|
-
*
|
|
3902
|
-
* @group Models
|
|
3903
|
-
*/
|
|
3904
2274
|
function isPublicStoragePath(path) {
|
|
3905
2275
|
if (!path) return false;
|
|
3906
2276
|
let p = path;
|
|
@@ -3910,29 +2280,6 @@ function isPublicStoragePath(path) {
|
|
|
3910
2280
|
if (p.split("/").some((seg) => seg === "..")) return false;
|
|
3911
2281
|
return p.startsWith("public/") || p.startsWith(`default/public/`);
|
|
3912
2282
|
}
|
|
3913
|
-
/**
|
|
3914
|
-
* The path the storage routes address an object by, from a key or from the
|
|
3915
|
-
* `storageUrl` an upload returned (`<scheme>://<bucket>/<key>`, which is what a
|
|
3916
|
-
* property with `includeBucketUrl: true` keeps in its column).
|
|
3917
|
-
*
|
|
3918
|
-
* The routes address a source's objects by key. On S3 and GCS the bucket in a
|
|
3919
|
-
* `storageUrl` is always the source's own — the server refuses any other — so
|
|
3920
|
-
* it is dropped: sent along, `s3://acme-media/products/a.png` reached the
|
|
3921
|
-
* server as the key `acme-media/products/a.png`, the preview found nothing and
|
|
3922
|
-
* a delete reported success while the object stayed. It worked on local disk
|
|
3923
|
-
* only, because `local://default/<key>` happens to carry the one bucket
|
|
3924
|
-
* segment the routes recognise — which is kept, as is any other local bucket.
|
|
3925
|
-
*
|
|
3926
|
-
* A bare key whose first folder is `default` is sent behind that bucket
|
|
3927
|
-
* segment. The routes read one leading `default/` (in any case) as the bucket,
|
|
3928
|
-
* so the key `default/photo.png` sent as it is names the root `photo.png`:
|
|
3929
|
-
* {@link defaultBucketPath} is the spelling that names the key itself.
|
|
3930
|
-
*
|
|
3931
|
-
* Shared by every storage source that talks to those routes, so they address
|
|
3932
|
-
* an object alike.
|
|
3933
|
-
*
|
|
3934
|
-
* @group Models
|
|
3935
|
-
*/
|
|
3936
2283
|
function storageObjectPath(keyOrUrl, bucket) {
|
|
3937
2284
|
let filePath = keyOrUrl;
|
|
3938
2285
|
let bucketQualified = false;
|
|
@@ -3950,71 +2297,21 @@ function storageObjectPath(keyOrUrl, bucket) {
|
|
|
3950
2297
|
}
|
|
3951
2298
|
return bucketQualified ? filePath : defaultBucketPath(filePath);
|
|
3952
2299
|
}
|
|
3953
|
-
/**
|
|
3954
|
-
* The request path of a key in the default bucket: the key itself, unless the
|
|
3955
|
-
* routes would read its first folder as the bucket — a first folder named
|
|
3956
|
-
* `default`, matched as the routes match it (case-insensitively, and only when
|
|
3957
|
-
* something follows it). Then the bucket segment goes in front, so exactly the
|
|
3958
|
-
* one segment the routes strip is the one added.
|
|
3959
|
-
*/
|
|
3960
2300
|
function defaultBucketPath(key) {
|
|
3961
2301
|
const segments = key.split("/");
|
|
3962
2302
|
return segments.length > 1 && segments[0].toLowerCase() === "default" ? `default/${key}` : key;
|
|
3963
2303
|
}
|
|
3964
2304
|
//#endregion
|
|
3965
2305
|
//#region src/controllers/storage-references.ts
|
|
3966
|
-
/**
|
|
3967
|
-
* The scheme of a **storage reference**: a stored object named inside text.
|
|
3968
|
-
*
|
|
3969
|
-
* Text that embeds a file — a markdown body above all — cannot hold a private
|
|
3970
|
-
* object's URL: that URL carries a download token which expires in minutes,
|
|
3971
|
-
* after which every reader of the text gets a 401 for an image that is still in
|
|
3972
|
-
* the bucket. It holds a reference instead,
|
|
3973
|
-
* `rebase-storage:posts/cover.png` (`?storageId=media` for a named source),
|
|
3974
|
-
* and whoever renders the text exchanges each reference for a fresh URL with
|
|
3975
|
-
* {@link resolveStorageReferences} — `resolveStorageReferences(text, client)`
|
|
3976
|
-
* from `@rebasepro/client` on a site.
|
|
3977
|
-
*
|
|
3978
|
-
* @group Models
|
|
3979
|
-
*/
|
|
3980
2306
|
var STORAGE_REFERENCE_SCHEME = "rebase-storage:";
|
|
3981
|
-
/**
|
|
3982
|
-
* `encodeURIComponent`, plus the five characters it leaves alone that end or
|
|
3983
|
-
* break a markdown link destination: `(`, `)`, `'`, `!` and `*`.
|
|
3984
|
-
*/
|
|
3985
2307
|
var encodeReferencePart = (part) => encodeURIComponent(part).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
3986
|
-
/**
|
|
3987
|
-
* A reference as it appears in text: the scheme, then the characters
|
|
3988
|
-
* {@link storageReference} writes. Kept beside {@link STORAGE_REFERENCE_SCHEME};
|
|
3989
|
-
* the test round-trips names chosen to break it.
|
|
3990
|
-
*/
|
|
3991
2308
|
var STORAGE_REFERENCE_PATTERN = /rebase-storage:[A-Za-z0-9\-._~%/?=&]+/g;
|
|
3992
|
-
/**
|
|
3993
|
-
* The reference for an object — what text stores in place of its URL.
|
|
3994
|
-
*
|
|
3995
|
-
* Every part is percent-encoded, so the reference contains no space,
|
|
3996
|
-
* parenthesis or quote and survives as one markdown link destination whatever
|
|
3997
|
-
* the file was called.
|
|
3998
|
-
*
|
|
3999
|
-
* @group Models
|
|
4000
|
-
*/
|
|
4001
2309
|
function storageReference(key, storageId) {
|
|
4002
2310
|
return `${STORAGE_REFERENCE_SCHEME}${key.replace(/^\/+/, "").split("/").map(encodeReferencePart).join("/")}${storageId && storageId !== "(default)" ? `?storageId=${encodeReferencePart(storageId)}` : ""}`;
|
|
4003
2311
|
}
|
|
4004
|
-
/**
|
|
4005
|
-
* Whether a string — an image's `src`, a link's `href` — is a storage reference.
|
|
4006
|
-
*
|
|
4007
|
-
* @group Models
|
|
4008
|
-
*/
|
|
4009
2312
|
function isStorageReference(value) {
|
|
4010
2313
|
return typeof value === "string" && value.startsWith("rebase-storage:");
|
|
4011
2314
|
}
|
|
4012
|
-
/**
|
|
4013
|
-
* The object a storage reference names, or `null` for anything else — a URL, a
|
|
4014
|
-
* bare key, or a reference whose key would climb out of its prefix.
|
|
4015
|
-
*
|
|
4016
|
-
* @group Models
|
|
4017
|
-
*/
|
|
4018
2315
|
function parseStorageReference(value) {
|
|
4019
2316
|
if (!isStorageReference(value)) return null;
|
|
4020
2317
|
const rest = value.slice(15);
|
|
@@ -4038,7 +2335,6 @@ function parseStorageReference(value) {
|
|
|
4038
2335
|
storageId
|
|
4039
2336
|
} : { key };
|
|
4040
2337
|
}
|
|
4041
|
-
/** The JSON in a JWT's payload segment, or `undefined` for anything else. */
|
|
4042
2338
|
function jwtPayload(token) {
|
|
4043
2339
|
const segments = token.split(".");
|
|
4044
2340
|
if (segments.length !== 3) return void 0;
|
|
@@ -4052,20 +2348,6 @@ function jwtPayload(token) {
|
|
|
4052
2348
|
return;
|
|
4053
2349
|
}
|
|
4054
2350
|
}
|
|
4055
|
-
/**
|
|
4056
|
-
* The object a private file's download URL was minted for, or `null` for any
|
|
4057
|
-
* other URL.
|
|
4058
|
-
*
|
|
4059
|
-
* Text written before storage references stored such URLs —
|
|
4060
|
-
* `…/storage/file/posts/cover.png?token=…` — and their tokens expired minutes
|
|
4061
|
-
* later. The token still names the object it was minted for, so the URL can be
|
|
4062
|
-
* traded for a fresh one, or for a reference. Read without verifying the
|
|
4063
|
-
* token: it grants nothing here, it only says which object is meant, and the
|
|
4064
|
-
* key in the URL must agree with it. Host-agnostic, since a URL written
|
|
4065
|
-
* through one origin may be read through another.
|
|
4066
|
-
*
|
|
4067
|
-
* @group Models
|
|
4068
|
-
*/
|
|
4069
2351
|
function storageTargetOfDownloadUrl(url) {
|
|
4070
2352
|
let parsed;
|
|
4071
2353
|
try {
|
|
@@ -4093,13 +2375,7 @@ function storageTargetOfDownloadUrl(url) {
|
|
|
4093
2375
|
storageId: named
|
|
4094
2376
|
} : { key };
|
|
4095
2377
|
}
|
|
4096
|
-
/**
|
|
4097
|
-
* A private file's download URL as it may appear in text. Parentheses are
|
|
4098
|
-
* allowed in the path, where an unencoded file name puts them; the query, a
|
|
4099
|
-
* token, has none, so the match ends where a markdown destination does.
|
|
4100
|
-
*/
|
|
4101
2378
|
var DOWNLOAD_URL_PATTERN = /(?:https?:\/\/[^\s()<>"'\]]+)?\/storage\/file\/[^\s<>"'?#\]]+\?[^\s()<>"'#\]]*/g;
|
|
4102
|
-
/** Each download URL in `text` that names an object, with its reference. */
|
|
4103
2379
|
function downloadUrlsIn(text) {
|
|
4104
2380
|
const found = /* @__PURE__ */ new Map();
|
|
4105
2381
|
if (!text.includes("/storage/file/")) return found;
|
|
@@ -4109,49 +2385,14 @@ function downloadUrlsIn(text) {
|
|
|
4109
2385
|
}
|
|
4110
2386
|
return found;
|
|
4111
2387
|
}
|
|
4112
|
-
/**
|
|
4113
|
-
* Every object `text` names: its storage references, and the private files'
|
|
4114
|
-
* download URLs saved in it before references existed. An object named more
|
|
4115
|
-
* than once may be listed more than once.
|
|
4116
|
-
*
|
|
4117
|
-
* @group Models
|
|
4118
|
-
*/
|
|
4119
2388
|
function storageTargetsInText(text) {
|
|
4120
2389
|
return [...text.includes("rebase-storage:") ? text.match(STORAGE_REFERENCE_PATTERN) ?? [] : [], ...downloadUrlsIn(text).values()].map((reference) => parseStorageReference(reference)).filter((target) => target !== null);
|
|
4121
2390
|
}
|
|
4122
|
-
/**
|
|
4123
|
-
* `text` with every private file's download URL replaced by the storage
|
|
4124
|
-
* reference for its object — for rewriting text saved before references, so
|
|
4125
|
-
* it stores what new text stores. Any other URL is left as it is.
|
|
4126
|
-
*
|
|
4127
|
-
* @group Models
|
|
4128
|
-
*/
|
|
4129
2391
|
function storageReferencesForDownloadUrls(text) {
|
|
4130
2392
|
const urls = downloadUrlsIn(text);
|
|
4131
2393
|
if (urls.size === 0) return text;
|
|
4132
2394
|
return text.replace(DOWNLOAD_URL_PATTERN, (url) => urls.get(url) ?? url);
|
|
4133
2395
|
}
|
|
4134
|
-
/**
|
|
4135
|
-
* Exchange every storage reference in `text` for a URL, at the moment the text
|
|
4136
|
-
* is rendered.
|
|
4137
|
-
*
|
|
4138
|
-
* ```ts
|
|
4139
|
-
* const html = markdown.render(await resolveStorageReferences(post.body, client));
|
|
4140
|
-
* ```
|
|
4141
|
-
*
|
|
4142
|
-
* Each distinct object is asked for once — `getSignedUrl(key)` on its source —
|
|
4143
|
-
* so a private object gets a freshly minted download URL every time the text is
|
|
4144
|
-
* rendered. A reference that cannot be resolved (no such object, an unknown
|
|
4145
|
-
* source) is left as it was, so a missing object reads as a missing image
|
|
4146
|
-
* rather than as a failed render.
|
|
4147
|
-
*
|
|
4148
|
-
* A private file's download URL saved in the text before references existed
|
|
4149
|
-
* is renewed the same way: its expired token still names the object (see
|
|
4150
|
-
* {@link storageTargetOfDownloadUrl}). One that cannot be resolved is left as
|
|
4151
|
-
* it was.
|
|
4152
|
-
*
|
|
4153
|
-
* @group Models
|
|
4154
|
-
*/
|
|
4155
2396
|
async function resolveStorageReferences(text, from) {
|
|
4156
2397
|
if (!text) return text;
|
|
4157
2398
|
const downloadUrls = downloadUrlsIn(text);
|
|
@@ -4177,14 +2418,7 @@ async function resolveStorageReferences(text, from) {
|
|
|
4177
2418
|
return url === void 0 ? reference : asLinkDestination(url);
|
|
4178
2419
|
});
|
|
4179
2420
|
}
|
|
4180
|
-
/**
|
|
4181
|
-
* A URL as one markdown link destination: whitespace, parentheses, angle
|
|
4182
|
-
* brackets and quotes percent-encoded, since any of them ends the destination
|
|
4183
|
-
* and turns the image into literal text. The URL means the same thing either
|
|
4184
|
-
* way.
|
|
4185
|
-
*/
|
|
4186
2421
|
var asLinkDestination = (url) => url.replace(/[\s()<>"']/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
|
|
4187
|
-
/** A resolver over a client's storage sources, one source per named key. */
|
|
4188
2422
|
function resolverFromSources(client) {
|
|
4189
2423
|
const named = /* @__PURE__ */ new Map();
|
|
4190
2424
|
return async ({ key, storageId }) => {
|
|
@@ -4200,7 +2434,6 @@ function resolverFromSources(client) {
|
|
|
4200
2434
|
}
|
|
4201
2435
|
//#endregion
|
|
4202
2436
|
//#region src/controllers/aggregates.ts
|
|
4203
|
-
/** Every aggregate function, by its SDK name: what `?select=` accepts too. */
|
|
4204
2437
|
var AGGREGATE_FUNCTIONS = [
|
|
4205
2438
|
"count",
|
|
4206
2439
|
"sum",
|
|
@@ -4213,9 +2446,7 @@ var AGGREGATE_FUNCTIONS = [
|
|
|
4213
2446
|
"distinct",
|
|
4214
2447
|
"fingerprint"
|
|
4215
2448
|
];
|
|
4216
|
-
/** The functions that take no field. */
|
|
4217
2449
|
var FIELDLESS_AGGREGATES = /* @__PURE__ */ new Set(["count", "fingerprint"]);
|
|
4218
|
-
/** Every `groupBy` transform. */
|
|
4219
2450
|
var AGGREGATE_GROUP_TRANSFORMS = [
|
|
4220
2451
|
"lower",
|
|
4221
2452
|
"upper",
|
|
@@ -4224,38 +2455,18 @@ var AGGREGATE_GROUP_TRANSFORMS = [
|
|
|
4224
2455
|
"month",
|
|
4225
2456
|
"day"
|
|
4226
2457
|
];
|
|
4227
|
-
/** A function's name in its result key: the SDK's camelCase in SQL's spelling. */
|
|
4228
2458
|
var ALIAS_NAMES = { countDistinct: "count_distinct" };
|
|
4229
|
-
/**
|
|
4230
|
-
* `percentile`'s `p` as it reads in a key: `0.95` → `95`, `0.5` → `50`,
|
|
4231
|
-
* `0.995` → `99_5`.
|
|
4232
|
-
*/
|
|
4233
2459
|
function percentileLabel(p) {
|
|
4234
2460
|
return String(Math.round(p * 1e3) / 10).replace(".", "_");
|
|
4235
2461
|
}
|
|
4236
|
-
/**
|
|
4237
|
-
* The key an aggregate comes back under.
|
|
4238
|
-
*
|
|
4239
|
-
* `sum(total)` → `sum_total`, `count()` → `count`, `countDistinct(sid)` →
|
|
4240
|
-
* `count_distinct_sid`, `percentile(fame, 0.95)` → `p95_fame`. One function,
|
|
4241
|
-
* because the SDK, the REST parser and the HTTP client all derive it and have
|
|
4242
|
-
* to agree — a caller reading `row.sum_total` off an SDK result and off an HTTP
|
|
4243
|
-
* response is reading the same key or the SDK is broken.
|
|
4244
|
-
*/
|
|
4245
2462
|
function aggregateAlias(fn, field, p) {
|
|
4246
2463
|
if (fn === "percentile") return `p${percentileLabel(p ?? 0)}_${field ?? ""}`;
|
|
4247
2464
|
const name = ALIAS_NAMES[fn] ?? fn;
|
|
4248
2465
|
return field ? `${name}_${field}` : name;
|
|
4249
2466
|
}
|
|
4250
|
-
/** `percentile`'s `p`, refused unless it is a fraction a key can name (0–1, at most three decimals). */
|
|
4251
2467
|
function isPercentileFraction(p) {
|
|
4252
2468
|
return typeof p === "number" && Number.isFinite(p) && p >= 0 && p <= 1 && Math.abs(Math.round(p * 1e3) - p * 1e3) < 1e-9;
|
|
4253
2469
|
}
|
|
4254
|
-
/**
|
|
4255
|
-
* An `AggregateSelect` as a driver is handed it — but for its `where`, which
|
|
4256
|
-
* the caller decodes into the driver's `filter` (this package has no filter
|
|
4257
|
-
* codec).
|
|
4258
|
-
*/
|
|
4259
2470
|
function toDriverAggregate(select) {
|
|
4260
2471
|
const field = "field" in select ? select.field : void 0;
|
|
4261
2472
|
const p = select.fn === "percentile" ? select.p : void 0;
|
|
@@ -4266,7 +2477,6 @@ function toDriverAggregate(select) {
|
|
|
4266
2477
|
alias: select.as ?? aggregateAlias(select.fn, field, p)
|
|
4267
2478
|
};
|
|
4268
2479
|
}
|
|
4269
|
-
/** Whether `timeZone` names a time zone this runtime knows: an IANA name such as `Europe/Madrid`, or `UTC`. */
|
|
4270
2480
|
function isTimeZoneName(timeZone) {
|
|
4271
2481
|
if (typeof timeZone !== "string" || !/^[A-Za-z][A-Za-z0-9_+\-/]*$/.test(timeZone)) return false;
|
|
4272
2482
|
try {
|
|
@@ -4276,11 +2486,9 @@ function isTimeZoneName(timeZone) {
|
|
|
4276
2486
|
return false;
|
|
4277
2487
|
}
|
|
4278
2488
|
}
|
|
4279
|
-
/** The key a group comes back under: the column's name, or `<transform>_<field>`. */
|
|
4280
2489
|
function aggregateGroupKey(group) {
|
|
4281
2490
|
return typeof group === "string" ? group : `${group.transform}_${group.field}`;
|
|
4282
2491
|
}
|
|
4283
|
-
/** A `groupBy` entry as a driver is handed it. */
|
|
4284
2492
|
function toDriverAggregateGroup(group) {
|
|
4285
2493
|
return typeof group === "string" ? group : {
|
|
4286
2494
|
field: group.field,
|
|
@@ -4291,56 +2499,14 @@ function toDriverAggregateGroup(group) {
|
|
|
4291
2499
|
}
|
|
4292
2500
|
//#endregion
|
|
4293
2501
|
//#region src/users/import.ts
|
|
4294
|
-
/**
|
|
4295
|
-
* Importing accounts from another system: `POST /admin/users/import`,
|
|
4296
|
-
* `client.admin.importUsers()` and `rebase users import`.
|
|
4297
|
-
*
|
|
4298
|
-
* An import keeps the ids the accounts had, so every row that points at a user
|
|
4299
|
-
* still points at the same one. It carries no password and sends no email: an
|
|
4300
|
-
* imported account signs in by magic link, an email code, a provider, or a
|
|
4301
|
-
* password reset.
|
|
4302
|
-
*/
|
|
4303
|
-
/**
|
|
4304
|
-
* The most accounts one `POST /admin/users/import` takes. The CLI sends a
|
|
4305
|
-
* longer file in requests of this size.
|
|
4306
|
-
*
|
|
4307
|
-
* @group Admin
|
|
4308
|
-
*/
|
|
4309
2502
|
var MAX_USERS_PER_IMPORT = 100;
|
|
4310
|
-
/**
|
|
4311
|
-
* The longest id an imported account may keep.
|
|
4312
|
-
*
|
|
4313
|
-
* @group Admin
|
|
4314
|
-
*/
|
|
4315
2503
|
var MAX_IMPORTED_USER_ID_LENGTH = 128;
|
|
4316
|
-
/**
|
|
4317
|
-
* Ids that already mean someone other than an account: the anonymous caller,
|
|
4318
|
-
* the service key, and the identity a custom validator's `true` stands for.
|
|
4319
|
-
*/
|
|
4320
2504
|
var RESERVED_USER_IDS = /* @__PURE__ */ new Set([
|
|
4321
2505
|
"anonymous",
|
|
4322
2506
|
"anon",
|
|
4323
2507
|
"service",
|
|
4324
2508
|
"default"
|
|
4325
2509
|
]);
|
|
4326
|
-
/**
|
|
4327
|
-
* Why `id` cannot be kept as an imported account's id, or `undefined` when it
|
|
4328
|
-
* can.
|
|
4329
|
-
*
|
|
4330
|
-
* A uuid is the common case (Supabase, Cognito). Other systems' ids fit too:
|
|
4331
|
-
* letters, digits and `_ - . : |`, starting with a letter or a digit, at most
|
|
4332
|
-
* {@link MAX_IMPORTED_USER_ID_LENGTH} characters (Firebase's 28-character
|
|
4333
|
-
* uids, Auth0's `auth0|5f7c…`, Clerk's `user_2abc…`). Refused: what would read
|
|
4334
|
-
* as something else on the way through a URL, a storage path or a CLI argument
|
|
4335
|
-
* (`/`, `?`, `%`, whitespace, `@`, which the CLI reads as an email), and the
|
|
4336
|
-
* ids that already name a caller who is not an account (`service`,
|
|
4337
|
-
* `anonymous`).
|
|
4338
|
-
*
|
|
4339
|
-
* The users table's id column has the last word: a uuid column refuses an id
|
|
4340
|
-
* that is not a uuid.
|
|
4341
|
-
*
|
|
4342
|
-
* @group Admin
|
|
4343
|
-
*/
|
|
4344
2510
|
function importedUserIdProblem(id) {
|
|
4345
2511
|
if (typeof id !== "string") return "is not a string";
|
|
4346
2512
|
if (id === "") return "is empty";
|
|
@@ -4348,6 +2514,16 @@ function importedUserIdProblem(id) {
|
|
|
4348
2514
|
if (!/^[A-Za-z0-9][A-Za-z0-9_.:|-]*$/.test(id)) return "may hold only letters, digits and _ - . : |, starting with a letter or a digit";
|
|
4349
2515
|
if (RESERVED_USER_IDS.has(id.toLowerCase())) return "is reserved: it names a caller who is not an account";
|
|
4350
2516
|
}
|
|
2517
|
+
var IMPORTED_PASSWORD_HASH_ALGORITHMS = ["bcrypt"];
|
|
2518
|
+
function importedPasswordHashProblem(hash, algorithm) {
|
|
2519
|
+
if (typeof hash !== "string") return "is not a string";
|
|
2520
|
+
if (algorithm === "bcrypt") {
|
|
2521
|
+
const match = /^\$2[aby]\$(\d{2})\$[./A-Za-z0-9]{53}$/.exec(hash);
|
|
2522
|
+
if (!match) return "is not a bcrypt hash: one starts with $2a$, $2b$ or $2y$, then a two-digit cost and 53 characters";
|
|
2523
|
+
const cost = Number(match[1]);
|
|
2524
|
+
if (cost < 4 || cost > 31) return `has a bcrypt cost of ${cost}, outside 4 to 31`;
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
4351
2527
|
//#endregion
|
|
4352
2528
|
//#region src/schema/column_type.ts
|
|
4353
2529
|
var TEXT_KINDS = [
|
|
@@ -4371,46 +2547,18 @@ var TEMPORAL_KINDS = [
|
|
|
4371
2547
|
"date",
|
|
4372
2548
|
"time"
|
|
4373
2549
|
];
|
|
4374
|
-
/**
|
|
4375
|
-
* Whether a column type is stored as text (`text`, `varchar`, `char`).
|
|
4376
|
-
*
|
|
4377
|
-
* @group Schema
|
|
4378
|
-
*/
|
|
4379
2550
|
function isTextColumnType(type) {
|
|
4380
2551
|
return TEXT_KINDS.includes(type.kind);
|
|
4381
2552
|
}
|
|
4382
|
-
/**
|
|
4383
|
-
* Whether a column type is read and written as a JavaScript `number`.
|
|
4384
|
-
*
|
|
4385
|
-
* @group Schema
|
|
4386
|
-
*/
|
|
4387
2553
|
function isNumericColumnType(type) {
|
|
4388
2554
|
return NUMERIC_KINDS.includes(type.kind);
|
|
4389
2555
|
}
|
|
4390
|
-
/**
|
|
4391
|
-
* Whether a column type holds an instant, a day or a time of day.
|
|
4392
|
-
*
|
|
4393
|
-
* @group Schema
|
|
4394
|
-
*/
|
|
4395
2556
|
function isTemporalColumnType(type) {
|
|
4396
2557
|
return TEMPORAL_KINDS.includes(type.kind);
|
|
4397
2558
|
}
|
|
4398
|
-
/**
|
|
4399
|
-
* Whether a column type is a JSON document (`json`, `jsonb`).
|
|
4400
|
-
*
|
|
4401
|
-
* @group Schema
|
|
4402
|
-
*/
|
|
4403
2559
|
function isJsonColumnType(type) {
|
|
4404
2560
|
return type.kind === "json" || type.kind === "jsonb";
|
|
4405
2561
|
}
|
|
4406
|
-
/**
|
|
4407
|
-
* The SQL spelling of a column type, for messages and generated comments.
|
|
4408
|
-
*
|
|
4409
|
-
* Not the DDL renderer: an enum prints as `enum(a, b)` because its type name
|
|
4410
|
-
* belongs to the table it is planned in.
|
|
4411
|
-
*
|
|
4412
|
-
* @group Schema
|
|
4413
|
-
*/
|
|
4414
2562
|
function columnTypeLabel(type) {
|
|
4415
2563
|
switch (type.kind) {
|
|
4416
2564
|
case "varchar": return `varchar(${type.length})`;
|
|
@@ -4428,20 +2576,8 @@ function columnTypeLabel(type) {
|
|
|
4428
2576
|
}
|
|
4429
2577
|
//#endregion
|
|
4430
2578
|
//#region src/schema/column_options.ts
|
|
4431
|
-
/**
|
|
4432
|
-
* Per-role access in its stored form, checked: `read` and `write` must each be
|
|
4433
|
-
* a list of non-empty role names, and nothing else may be given.
|
|
4434
|
-
*
|
|
4435
|
-
* Checked at runtime because a JavaScript caller writing
|
|
4436
|
-
* `.access({ read: "admin" })` would otherwise have the string spread into
|
|
4437
|
-
* one role per character, silently.
|
|
4438
|
-
*
|
|
4439
|
-
* @param where What is being configured, for the error: `column "title"`.
|
|
4440
|
-
*
|
|
4441
|
-
* @group Schema
|
|
4442
|
-
*/
|
|
4443
2579
|
function normalizeColumnAccess(access, where) {
|
|
4444
|
-
const expected = "Write `{ read?: [\"role\",
|
|
2580
|
+
const expected = "Write `{ read?: [\"role\", \u2026], write?: [\"role\", \u2026] }`.";
|
|
4445
2581
|
if (typeof access !== "object" || access === null || Array.isArray(access)) throw new Error(`The access of ${where} must be an object of role lists, got ${JSON.stringify(access)}. ${expected}`);
|
|
4446
2582
|
const stored = {};
|
|
4447
2583
|
for (const [key, value] of Object.entries(access)) {
|
|
@@ -4453,13 +2589,6 @@ function normalizeColumnAccess(access, where) {
|
|
|
4453
2589
|
return stored;
|
|
4454
2590
|
}
|
|
4455
2591
|
var isoOf = (value) => value instanceof Date ? value.toISOString() : value;
|
|
4456
|
-
/**
|
|
4457
|
-
* Validation rules in their stored form: a `RegExp` becomes its source and
|
|
4458
|
-
* flags, a `Date` bound becomes an ISO string. What a builder keeps is then
|
|
4459
|
-
* exactly what the wire carries.
|
|
4460
|
-
*
|
|
4461
|
-
* @group Schema
|
|
4462
|
-
*/
|
|
4463
2592
|
function normalizeValidation(rules) {
|
|
4464
2593
|
const out = {};
|
|
4465
2594
|
for (const [key, value] of Object.entries(rules)) {
|
|
@@ -4484,15 +2613,6 @@ var BYTE_UNITS = {
|
|
|
4484
2613
|
gb: 1024 ** 3,
|
|
4485
2614
|
tb: 1024 ** 4
|
|
4486
2615
|
};
|
|
4487
|
-
/**
|
|
4488
|
-
* A size in bytes, from a number or from `"10MB"` / `"512 kb"` / `"1.5GB"`.
|
|
4489
|
-
*
|
|
4490
|
-
* Binary multiples (1 MB = 1,048,576 bytes), the unit a storage limit is
|
|
4491
|
-
* enforced in. Throws on anything else: a limit that silently parsed to `NaN`
|
|
4492
|
-
* is a limit that is never applied.
|
|
4493
|
-
*
|
|
4494
|
-
* @group Schema
|
|
4495
|
-
*/
|
|
4496
2616
|
function parseByteSize(size) {
|
|
4497
2617
|
if (typeof size === "number") {
|
|
4498
2618
|
if (!Number.isFinite(size) || size < 0) throw new Error(`A byte size must be a non-negative number, got ${size}.`);
|
|
@@ -4503,11 +2623,6 @@ function parseByteSize(size) {
|
|
|
4503
2623
|
const unit = (match[2] ?? "b").toLowerCase();
|
|
4504
2624
|
return Math.round(Number(match[1]) * BYTE_UNITS[unit]);
|
|
4505
2625
|
}
|
|
4506
|
-
/**
|
|
4507
|
-
* Storage options in their stored form.
|
|
4508
|
-
*
|
|
4509
|
-
* @group Schema
|
|
4510
|
-
*/
|
|
4511
2626
|
function normalizeStorage(options) {
|
|
4512
2627
|
if (typeof options.path !== "string" || options.path.length === 0) throw new Error("A storage column needs a `path`: where its files go, e.g. `col.storage({ path: \"posts/heroes/\" })`.");
|
|
4513
2628
|
const out = { path: options.path };
|
|
@@ -4524,15 +2639,7 @@ function normalizeStorage(options) {
|
|
|
4524
2639
|
}
|
|
4525
2640
|
//#endregion
|
|
4526
2641
|
//#region src/schema/json.ts
|
|
4527
|
-
/** The brand every JSON field builder carries, so one built by another copy of this package is still recognised. */
|
|
4528
2642
|
var JSON_FIELD_BRAND = "rebase.json-field";
|
|
4529
|
-
/**
|
|
4530
|
-
* One field of a JSON document: `json.string()`, `json.object({...})`, ….
|
|
4531
|
-
*
|
|
4532
|
-
* Immutable: every modifier returns a new field.
|
|
4533
|
-
*
|
|
4534
|
-
* @group Schema
|
|
4535
|
-
*/
|
|
4536
2643
|
var JsonField = class JsonField {
|
|
4537
2644
|
shape;
|
|
4538
2645
|
brand = JSON_FIELD_BRAND;
|
|
@@ -4542,48 +2649,34 @@ var JsonField = class JsonField {
|
|
|
4542
2649
|
with(patch) {
|
|
4543
2650
|
return new JsonField(Object.assign({}, this.shape, patch));
|
|
4544
2651
|
}
|
|
4545
|
-
/** The key must be present in the document. */
|
|
4546
2652
|
required() {
|
|
4547
2653
|
return this.with({ required: true });
|
|
4548
2654
|
}
|
|
4549
|
-
/** The value written when the key is absent on create. */
|
|
4550
2655
|
default(value) {
|
|
4551
2656
|
return this.with({ default: value });
|
|
4552
2657
|
}
|
|
4553
|
-
/** What the value is, for OpenAPI and MCP. */
|
|
4554
2658
|
describe(description) {
|
|
4555
2659
|
return this.with({ description });
|
|
4556
2660
|
}
|
|
4557
|
-
/** Rules the API checks before a write. */
|
|
4558
2661
|
validate(rules) {
|
|
4559
2662
|
const input = rules;
|
|
4560
2663
|
return this.with({ validate: normalizeValidation(input) });
|
|
4561
2664
|
}
|
|
4562
|
-
/** A closed set of accepted values. */
|
|
4563
2665
|
oneOf(values) {
|
|
4564
2666
|
return this.with({ oneOf: [...values] });
|
|
4565
2667
|
}
|
|
4566
|
-
/** The server writes the current time into the field when the row is created. */
|
|
4567
2668
|
onCreateNow() {
|
|
4568
2669
|
return this.with({ stamp: "create" });
|
|
4569
2670
|
}
|
|
4570
|
-
/** The server writes the current time into the field on every write. */
|
|
4571
2671
|
onUpdateNow() {
|
|
4572
2672
|
return this.with({ stamp: "update" });
|
|
4573
2673
|
}
|
|
4574
|
-
/** The server writes the caller's user id into the field when the row is created. */
|
|
4575
2674
|
onCreateUser() {
|
|
4576
2675
|
return this.with({ stamp: "createUser" });
|
|
4577
2676
|
}
|
|
4578
|
-
/** The server writes the caller's user id into the field on every write. */
|
|
4579
2677
|
onUpdateUser() {
|
|
4580
2678
|
return this.with({ stamp: "updateUser" });
|
|
4581
2679
|
}
|
|
4582
|
-
/**
|
|
4583
|
-
* The field holds the id of a user. The panel offers a user picker for it,
|
|
4584
|
-
* and callers who may write the table may look users up to fill it.
|
|
4585
|
-
* Only on `json.string()`; anything else throws.
|
|
4586
|
-
*/
|
|
4587
2680
|
userId() {
|
|
4588
2681
|
if (this.shape.kind !== "string" || this.shape.storage !== void 0) {
|
|
4589
2682
|
const what = this.shape.kind === "string" ? "`json.storage()`" : `a \`json.${this.shape.kind}()\` field`;
|
|
@@ -4591,14 +2684,6 @@ var JsonField = class JsonField {
|
|
|
4591
2684
|
}
|
|
4592
2685
|
return this.with({ semantic: "user" });
|
|
4593
2686
|
}
|
|
4594
|
-
/**
|
|
4595
|
-
* Field-level hooks. They run on the server only.
|
|
4596
|
-
*
|
|
4597
|
-
* The value is `TData | undefined` on a field not (yet) marked
|
|
4598
|
-
* `.required()` — the key can be absent from the document — and `TData` on
|
|
4599
|
-
* one that is; see {@link JsonTransformValue}. Chain `.required()` before
|
|
4600
|
-
* `.transform()` to get the narrower type.
|
|
4601
|
-
*/
|
|
4602
2687
|
transform(transform) {
|
|
4603
2688
|
const erased = transform;
|
|
4604
2689
|
return this.with({ transform: erased });
|
|
@@ -4609,54 +2694,28 @@ var shapesOf = (fields) => {
|
|
|
4609
2694
|
for (const [key, field] of Object.entries(fields)) out[key] = field.shape;
|
|
4610
2695
|
return out;
|
|
4611
2696
|
};
|
|
4612
|
-
/**
|
|
4613
|
-
* Builders for the shape of a `json`/`jsonb` document.
|
|
4614
|
-
*
|
|
4615
|
-
* ```ts
|
|
4616
|
-
* metadata: col.jsonb(json.object({
|
|
4617
|
-
* seoTitle: json.string().validate({ max: 60 }),
|
|
4618
|
-
* canonicalUrl: json.string().validate({ url: true }),
|
|
4619
|
-
* })),
|
|
4620
|
-
* content: col.jsonb(json.array(json.oneOf({
|
|
4621
|
-
* text: json.string(),
|
|
4622
|
-
* image: json.storage({ path: "posts/content/" }),
|
|
4623
|
-
* }))),
|
|
4624
|
-
* ```
|
|
4625
|
-
*
|
|
4626
|
-
* `col.jsonb().$type<T>()` on its own types the document statically; a shape also
|
|
4627
|
-
* tells the server what is inside it.
|
|
4628
|
-
*
|
|
4629
|
-
* @group Schema
|
|
4630
|
-
*/
|
|
4631
2697
|
var json = {
|
|
4632
|
-
/** A string. */
|
|
4633
2698
|
string() {
|
|
4634
2699
|
return new JsonField({ kind: "string" });
|
|
4635
2700
|
},
|
|
4636
|
-
/** A number. */
|
|
4637
2701
|
number() {
|
|
4638
2702
|
return new JsonField({ kind: "number" });
|
|
4639
2703
|
},
|
|
4640
|
-
/** A boolean. */
|
|
4641
2704
|
boolean() {
|
|
4642
2705
|
return new JsonField({ kind: "boolean" });
|
|
4643
2706
|
},
|
|
4644
|
-
/** An instant, stored as an ISO string. */
|
|
4645
2707
|
date() {
|
|
4646
2708
|
return new JsonField({ kind: "date" });
|
|
4647
2709
|
},
|
|
4648
|
-
/** A point on Earth: `{ latitude, longitude }`. */
|
|
4649
2710
|
geopoint() {
|
|
4650
2711
|
return new JsonField({ kind: "geopoint" });
|
|
4651
2712
|
},
|
|
4652
|
-
/** The path of a stored file. Counted by the orphan sweep like a `col.storage()` column. */
|
|
4653
2713
|
storage(options) {
|
|
4654
2714
|
return new JsonField({
|
|
4655
2715
|
kind: "string",
|
|
4656
2716
|
storage: normalizeStorage(options)
|
|
4657
2717
|
});
|
|
4658
2718
|
},
|
|
4659
|
-
/** An object with known keys. `additional: true` also accepts keys it does not name. */
|
|
4660
2719
|
object(fields, options = {}) {
|
|
4661
2720
|
const shape = {
|
|
4662
2721
|
kind: "object",
|
|
@@ -4665,17 +2724,12 @@ var json = {
|
|
|
4665
2724
|
if (options.additional) shape.additional = true;
|
|
4666
2725
|
return new JsonField(shape);
|
|
4667
2726
|
},
|
|
4668
|
-
/** An array of one shape. */
|
|
4669
2727
|
array(of) {
|
|
4670
2728
|
return new JsonField({
|
|
4671
2729
|
kind: "array",
|
|
4672
2730
|
of: of.shape
|
|
4673
2731
|
});
|
|
4674
2732
|
},
|
|
4675
|
-
/**
|
|
4676
|
-
* A typed block: `{ type: "<variant>", value: <its shape> }`. The keys are
|
|
4677
|
-
* `type` and `value` unless `typeField` / `valueField` say otherwise.
|
|
4678
|
-
*/
|
|
4679
2733
|
oneOf(variants, options = {}) {
|
|
4680
2734
|
return new JsonField({
|
|
4681
2735
|
kind: "oneOf",
|
|
@@ -4684,25 +2738,13 @@ var json = {
|
|
|
4684
2738
|
variants: shapesOf(variants)
|
|
4685
2739
|
});
|
|
4686
2740
|
},
|
|
4687
|
-
/** Anything. */
|
|
4688
2741
|
unknown() {
|
|
4689
2742
|
return new JsonField({ kind: "unknown" });
|
|
4690
2743
|
}
|
|
4691
2744
|
};
|
|
4692
|
-
/**
|
|
4693
|
-
* Whether a value is a JSON field builder, from this copy of the package or
|
|
4694
|
-
* another.
|
|
4695
|
-
*
|
|
4696
|
-
* @group Schema
|
|
4697
|
-
*/
|
|
4698
2745
|
function isJsonField(value) {
|
|
4699
2746
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.json-field";
|
|
4700
2747
|
}
|
|
4701
|
-
/**
|
|
4702
|
-
* A JSON shape without its hooks: what the wire carries.
|
|
4703
|
-
*
|
|
4704
|
-
* @group Schema
|
|
4705
|
-
*/
|
|
4706
2748
|
function describeJsonShape(shape) {
|
|
4707
2749
|
const { transform: _transform, ...rest } = shape;
|
|
4708
2750
|
switch (rest.kind) {
|
|
@@ -4731,87 +2773,39 @@ function describeJsonShape(shape) {
|
|
|
4731
2773
|
}
|
|
4732
2774
|
//#endregion
|
|
4733
2775
|
//#region src/schema/columns.ts
|
|
4734
|
-
/**
|
|
4735
|
-
* Every Drizzle spelling Rebase refuses, with the instruction it shows.
|
|
4736
|
-
*
|
|
4737
|
-
* Each text is used twice: as a string-literal *type* placed where the
|
|
4738
|
-
* developer wrote the refused thing (a `this` parameter, a config key, an
|
|
4739
|
-
* argument), so TypeScript prints the instruction verbatim; and as the message
|
|
4740
|
-
* thrown at run time, for a JavaScript caller the types do not reach. See
|
|
4741
|
-
* `drizzle-alignment.md` for the table of Drizzle spellings.
|
|
4742
|
-
*
|
|
4743
|
-
* @group Schema
|
|
4744
|
-
*/
|
|
4745
2776
|
var DRIZZLE_REFUSALS = {
|
|
4746
|
-
/** `col.timestamp()` without `withTimezone: true`: Drizzle's timestamp WITHOUT time zone. */
|
|
4747
2777
|
timestamp: "Rebase stores instants as timestamptz: write `col.timestamp({ withTimezone: true })`. For a timestamp without time zone write `col.custom({ dataType: \"timestamp\" })`.",
|
|
4748
|
-
/** `col.timestamp({ mode: "date" })`: Drizzle's Date-typed mode. */
|
|
4749
2778
|
timestampMode: "Rebase serves a timestamp as an ISO string: leave `mode` out or write `mode: \"string\"`.",
|
|
4750
|
-
/** `col.timestamp({ precision })`. */
|
|
4751
2779
|
timestampPrecision: "Rebase does not state a timestamp's precision: leave `precision` out, or write `col.custom({ dataType: \"timestamp(3) with time zone\" })`.",
|
|
4752
|
-
/** `col.date({ mode: "date" })`: Drizzle's Date-typed mode. */
|
|
4753
2780
|
dateMode: "Rebase serves a date as a `YYYY-MM-DD` string: leave `mode` out or write `mode: \"string\"`.",
|
|
4754
|
-
/** `col.time({ withTimezone: true })`: a `timetz`. */
|
|
4755
2781
|
timeZone: "`col.time()` is a time without time zone: leave `withTimezone` out, or write `col.custom({ dataType: \"timetz\" })`.",
|
|
4756
|
-
/** `col.time({ precision })`. */
|
|
4757
2782
|
timePrecision: "Rebase does not state a time's precision: leave `precision` out, or write `col.custom({ dataType: \"time(3)\" })`.",
|
|
4758
|
-
/** `col.numeric({ mode: "string" | "bigint" })`: our value is a JSON number. */
|
|
4759
2783
|
numericMode: "Rebase reads and writes numeric as a JSON number: leave `mode` out or write `mode: \"number\"`. For exact decimals kept as text write `col.text()`.",
|
|
4760
|
-
/** `col.bigint({ mode: "bigint" })`: our value is a JSON number. */
|
|
4761
2784
|
bigintMode: "Rebase serves bigint as a JSON number: write `{ mode: \"number\" }`. For exact 64-bit values write `col.numeric()` or `col.text()`.",
|
|
4762
|
-
/** `col.varchar("name")` / `col.varchar({ enum })` without a length. */
|
|
4763
2785
|
varcharLength: "`col.varchar()` needs a length (a bare varchar is unbounded in Postgres and Drizzle): write `col.varchar({ length: 255 })`, or `col.text()` for text of any length.",
|
|
4764
|
-
/** `col.char("name")` / `col.char({ enum })` without a length. */
|
|
4765
2786
|
charLength: "`col.char()` needs a length (a bare char is char(1) in Postgres and Drizzle): write `col.char({ length: 2 })`.",
|
|
4766
|
-
/** `.generatedAlwaysAsIdentity()`: the planner creates BY DEFAULT identities only. */
|
|
4767
2787
|
identityAlways: "Rebase creates identity columns GENERATED BY DEFAULT: write `.generatedByDefaultAsIdentity()`.",
|
|
4768
|
-
/** `.generatedByDefaultAsIdentity({ … })`: sequence options. */
|
|
4769
2788
|
identityOptions: "Rebase does not take sequence options: write `.generatedByDefaultAsIdentity()` with no argument.",
|
|
4770
|
-
/** `.references(() => …)`: a foreign key is a `rel.belongsTo`. */
|
|
4771
2789
|
references: "A foreign key is a relation in Rebase: write `relations: { author: rel.belongsTo(() => users, { localKey: \"author_id\", onDelete: \"cascade\" }) }`. The relation's key is what `include` names.",
|
|
4772
|
-
|
|
4773
|
-
defaultFn: "Rebase's schema is data, not code: a default is `.default(value)` or `.default(sql`…`)`; the time is `.defaultNow()` or `.onCreateNow()`, the caller `.onCreateUser()`; anything else belongs in `hooks.beforeSave`, with `.serverDefault()` on the column it fills.",
|
|
4774
|
-
/** `.$onUpdate()` / `.$onUpdateFn()`: a run-time update function. */
|
|
2790
|
+
defaultFn: "Rebase's schema is data, not code: a default is `.default(value)` or `.default(sql`\u2026`)`; the time is `.defaultNow()` or `.onCreateNow()`, the caller `.onCreateUser()`; anything else belongs in `hooks.beforeSave`, with `.serverDefault()` on the column it fills.",
|
|
4775
2791
|
onUpdateFn: "Rebase's schema is data, not code: write `.onUpdateNow()` for the time, `.onUpdateUser()` for the caller; anything else belongs in `hooks.beforeSave`.",
|
|
4776
|
-
/** `.unique(name, { nulls })`: a named or NULLS NOT DISTINCT constraint. */
|
|
4777
2792
|
uniqueName: "Rebase derives constraint names and keeps NULLs distinct: write `.unique()`, or a unique index under `indexes`.",
|
|
4778
|
-
|
|
4779
|
-
generatedValue: "`.generatedAlwaysAs()` takes a SQL expression: write `.generatedAlwaysAs(sql`…`)`.",
|
|
4780
|
-
/** `.array(size)`. */
|
|
2793
|
+
generatedValue: "`.generatedAlwaysAs()` takes a SQL expression: write `.generatedAlwaysAs(sql`\u2026`)`.",
|
|
4781
2794
|
arraySize: "Postgres ignores array sizes: write `.array()`.",
|
|
4782
|
-
/** `.notNull()` & co. before `.array()`. */
|
|
4783
2795
|
arrayOrder: "`.notNull()`, a default, `.primaryKey()`, `.readOnly()` and `.private()` before `.array()` would describe each item: write them after it, as in `col.text().array().notNull()`.",
|
|
4784
|
-
/** `.array().array()`. */
|
|
4785
2796
|
arrayOfArray: "An array of arrays is not supported: use `col.jsonb()` for nested lists.",
|
|
4786
|
-
|
|
4787
|
-
sqlInterpolation: "`sql` writes its text into the DDL verbatim: write the expression inline, without `${…}`.",
|
|
4788
|
-
/** `col.bigint()` / `col.bigserial()` without `{ mode }`. */
|
|
2797
|
+
sqlInterpolation: "`sql` writes its text into the DDL verbatim: write the expression inline, without `${\u2026}`.",
|
|
4789
2798
|
bigintModeMissing: "`col.bigint()` and `col.bigserial()` take Drizzle's `{ mode: \"number\" }`: write `col.bigint({ mode: \"number\" })`.",
|
|
4790
|
-
/** `col.numeric(10, 2)`: positional precision and scale. */
|
|
4791
2799
|
numericPositional: "`col.numeric()` takes a config object: write `col.numeric({ precision: 10, scale: 2 })`.",
|
|
4792
|
-
/** `col.vector(1536)`: positional dimensions. */
|
|
4793
2800
|
vectorPositional: "`col.vector()` takes a config object: write `col.vector({ dimensions: 1536 })`.",
|
|
4794
|
-
/** `col.enum(values, { name })`: a named enum type. */
|
|
4795
2801
|
enumName: "A named Postgres enum type is declared once with `pgEnum`: write `const postStatus = pgEnum(\"post_status\", [...])`, then `postStatus()` in the column.",
|
|
4796
|
-
/** `col.custom("inet")`: a lone string is the SQL column name. */
|
|
4797
2802
|
customDataType: "`col.custom()` names its Postgres type in a config object: write `col.custom({ dataType: \"inet\" })`, or `col.custom(\"ip\", { dataType: \"inet\" })` with a SQL column name.",
|
|
4798
|
-
/** `pgEnum(name, { A: "a" })`: Drizzle's object form. */
|
|
4799
2803
|
pgEnumObject: "`pgEnum(name, values)` takes the list of labels: write `pgEnum(\"post_status\", [\"draft\", \"published\"])`."
|
|
4800
2804
|
};
|
|
4801
2805
|
function unsupportedMessage(type) {
|
|
4802
2806
|
return `Rebase has no \`col.${type}()\`: write \`col.custom({ dataType: "${type}" })\`. The value passes through as the driver returns it (a string).`;
|
|
4803
2807
|
}
|
|
4804
|
-
/** The brand of a {@link sql} expression. */
|
|
4805
2808
|
var SQL_BRAND = "rebase.sql";
|
|
4806
|
-
/**
|
|
4807
|
-
* A SQL expression for a default or a generated column, as Drizzle writes it:
|
|
4808
|
-
* `.default(sql\`gen_short_id()\`)`, `.generatedAlwaysAs(sql\`lower(email)\`)`.
|
|
4809
|
-
*
|
|
4810
|
-
* The text goes into the DDL verbatim, so it takes no interpolation: write the
|
|
4811
|
-
* expression inline.
|
|
4812
|
-
*
|
|
4813
|
-
* @group Schema
|
|
4814
|
-
*/
|
|
4815
2809
|
function sql(strings, ...values) {
|
|
4816
2810
|
if (values.length > 0 || strings.length !== 1) throw new Error(DRIZZLE_REFUSALS.sqlInterpolation);
|
|
4817
2811
|
const text = strings[0] ?? strings.raw[0];
|
|
@@ -4821,11 +2815,6 @@ function sql(strings, ...values) {
|
|
|
4821
2815
|
text
|
|
4822
2816
|
};
|
|
4823
2817
|
}
|
|
4824
|
-
/**
|
|
4825
|
-
* Whether a value is a {@link sql} expression, from this copy of the package or another.
|
|
4826
|
-
*
|
|
4827
|
-
* @group Schema
|
|
4828
|
-
*/
|
|
4829
2818
|
function isSqlTemplate(value) {
|
|
4830
2819
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.sql" && "text" in value && typeof value.text === "string";
|
|
4831
2820
|
}
|
|
@@ -4835,7 +2824,6 @@ var STAMP_METHODS = {
|
|
|
4835
2824
|
"create:user": ".onCreateUser",
|
|
4836
2825
|
"update:user": ".onUpdateUser"
|
|
4837
2826
|
};
|
|
4838
|
-
/** The brand every column builder carries, so one built by another copy of this package is still recognised. */
|
|
4839
2827
|
var COLUMN_BRAND = "rebase.column";
|
|
4840
2828
|
var baseDef = (type) => ({
|
|
4841
2829
|
type,
|
|
@@ -4845,19 +2833,6 @@ var baseDef = (type) => ({
|
|
|
4845
2833
|
readOnly: false,
|
|
4846
2834
|
private: false
|
|
4847
2835
|
});
|
|
4848
|
-
/**
|
|
4849
|
-
* One column of a table: `col.text()`, `col.uuid().primaryKey()`, ….
|
|
4850
|
-
*
|
|
4851
|
-
* Immutable — every modifier returns a new builder — so a column can be shared
|
|
4852
|
-
* between tables. Columns are nullable until `.notNull()` or `.primaryKey()`
|
|
4853
|
-
* says otherwise, as in SQL.
|
|
4854
|
-
*
|
|
4855
|
-
* @typeParam TData The TypeScript type of a value on the wire.
|
|
4856
|
-
* @typeParam TKind Which builder made it; decides which modifiers apply.
|
|
4857
|
-
* @typeParam F What has been said about it so far.
|
|
4858
|
-
*
|
|
4859
|
-
* @group Schema
|
|
4860
|
-
*/
|
|
4861
2836
|
var ColumnBuilder = class ColumnBuilder {
|
|
4862
2837
|
def;
|
|
4863
2838
|
brand = COLUMN_BRAND;
|
|
@@ -4870,52 +2845,27 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
4870
2845
|
...patch
|
|
4871
2846
|
});
|
|
4872
2847
|
}
|
|
4873
|
-
/**
|
|
4874
|
-
* The patch that sets a stamp, refusing a second, different one: a column
|
|
4875
|
-
* holds one stamp, so `.onCreateNow().onUpdateNow()` would otherwise keep
|
|
4876
|
-
* whichever came last without a word.
|
|
4877
|
-
*/
|
|
4878
2848
|
stamped(stamp, method) {
|
|
4879
2849
|
const current = this.def.stamp;
|
|
4880
2850
|
if (current && (current.on !== stamp.on || current.value !== stamp.value)) throw new Error(`\`.${method}()\` on a column that already has \`${STAMP_METHODS[`${current.on}:${current.value}`]}()\`: a column holds one stamp. \`.onUpdateNow()\` alone also stamps the row when it is created.`);
|
|
4881
2851
|
return { stamp };
|
|
4882
2852
|
}
|
|
4883
|
-
/**
|
|
4884
|
-
* Types the value without changing the column, as Drizzle's `$type`:
|
|
4885
|
-
* `col.jsonb().$type<{ seoTitle?: string }>()`, `col.integer().$type<UserId>()`.
|
|
4886
|
-
* Nothing is checked at run time; use `col.jsonb(json.object({...}))` for
|
|
4887
|
-
* a shape the server enforces.
|
|
4888
|
-
*/
|
|
4889
2853
|
$type() {
|
|
4890
2854
|
return this.with({});
|
|
4891
2855
|
}
|
|
4892
|
-
/** `NOT NULL`. The API requires the column on create unless it has a default. */
|
|
4893
2856
|
notNull() {
|
|
4894
2857
|
return this.with({ notNull: true });
|
|
4895
2858
|
}
|
|
4896
|
-
/**
|
|
4897
|
-
* Part of the primary key. Several columns marked this way form a composite
|
|
4898
|
-
* key, in declaration order.
|
|
4899
|
-
*/
|
|
4900
2859
|
primaryKey() {
|
|
4901
2860
|
return this.with({
|
|
4902
2861
|
primaryKey: true,
|
|
4903
2862
|
notNull: true
|
|
4904
2863
|
});
|
|
4905
2864
|
}
|
|
4906
|
-
/**
|
|
4907
|
-
* A single-column `UNIQUE` constraint. Its name is derived; Drizzle's
|
|
4908
|
-
* `.unique(name, { nulls })` arguments are refused.
|
|
4909
|
-
*/
|
|
4910
2865
|
unique(name, config) {
|
|
4911
2866
|
if (name !== void 0 || config !== void 0) throw new Error(DRIZZLE_REFUSALS.uniqueName);
|
|
4912
2867
|
return this.with({ unique: true });
|
|
4913
2868
|
}
|
|
4914
|
-
/**
|
|
4915
|
-
* A default: a value, written as the column's DDL default and applied by
|
|
4916
|
-
* the driver on create, so a row comes out the same whoever inserts it — or
|
|
4917
|
-
* an expression Postgres evaluates, `.default(sql\`gen_short_id()\`)`.
|
|
4918
|
-
*/
|
|
4919
2869
|
default(value) {
|
|
4920
2870
|
if (isSqlTemplate(value)) return this.with({ default: {
|
|
4921
2871
|
kind: "sql",
|
|
@@ -4927,54 +2877,27 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
4927
2877
|
value: stored
|
|
4928
2878
|
} });
|
|
4929
2879
|
}
|
|
4930
|
-
/** Refused: Drizzle's run-time default function. See {@link DRIZZLE_REFUSALS}. */
|
|
4931
2880
|
$defaultFn(..._args) {
|
|
4932
2881
|
throw new Error(DRIZZLE_REFUSALS.defaultFn);
|
|
4933
2882
|
}
|
|
4934
|
-
/** Refused: Drizzle's alias of `$defaultFn`. See {@link DRIZZLE_REFUSALS}. */
|
|
4935
2883
|
$default(..._args) {
|
|
4936
2884
|
throw new Error(DRIZZLE_REFUSALS.defaultFn);
|
|
4937
2885
|
}
|
|
4938
|
-
/** Refused: Drizzle's run-time update function. See {@link DRIZZLE_REFUSALS}. */
|
|
4939
2886
|
$onUpdate(..._args) {
|
|
4940
2887
|
throw new Error(DRIZZLE_REFUSALS.onUpdateFn);
|
|
4941
2888
|
}
|
|
4942
|
-
/** Refused: Drizzle's run-time update function. See {@link DRIZZLE_REFUSALS}. */
|
|
4943
2889
|
$onUpdateFn(..._args) {
|
|
4944
2890
|
throw new Error(DRIZZLE_REFUSALS.onUpdateFn);
|
|
4945
2891
|
}
|
|
4946
|
-
/**
|
|
4947
|
-
* Refused: a foreign key is a relation, `rel.belongsTo(() => users, {...})`
|
|
4948
|
-
* under `relations`, whose key is what `include` names.
|
|
4949
|
-
*/
|
|
4950
2892
|
references(..._args) {
|
|
4951
2893
|
throw new Error(DRIZZLE_REFUSALS.references);
|
|
4952
2894
|
}
|
|
4953
|
-
/**
|
|
4954
|
-
* The database already holds a default for this column that Rebase does not
|
|
4955
|
-
* state. A create may omit the column, and a schema push leaves the default
|
|
4956
|
-
* alone.
|
|
4957
|
-
*/
|
|
4958
2895
|
dbDefault() {
|
|
4959
2896
|
return this.with({ default: { kind: "database" } });
|
|
4960
2897
|
}
|
|
4961
|
-
/**
|
|
4962
|
-
* The table's own server code fills this column when a create leaves it
|
|
4963
|
-
* out: a `hooks.beforeSave` that derives it (a slug from the title), or
|
|
4964
|
-
* the column's `.transform()`. A hook is code and cannot be read, so this
|
|
4965
|
-
* says what it does: a create may omit the column (the SDK's insert type
|
|
4966
|
-
* makes it optional), the panel's form lets a record be created without
|
|
4967
|
-
* it, and the descriptor carries `default: { kind: "server" }`. No DDL
|
|
4968
|
-
* default is written. A `NOT NULL` column the hook does not fill still
|
|
4969
|
-
* fails on the database.
|
|
4970
|
-
*/
|
|
4971
2898
|
serverDefault() {
|
|
4972
2899
|
return this.with({ default: { kind: "server" } });
|
|
4973
2900
|
}
|
|
4974
|
-
/**
|
|
4975
|
-
* `GENERATED ALWAYS AS (<expression>) STORED`, as Drizzle writes it:
|
|
4976
|
-
* `.generatedAlwaysAs(sql\`lower(email)\`)`. Nobody writes the column.
|
|
4977
|
-
*/
|
|
4978
2901
|
generatedAlwaysAs(as) {
|
|
4979
2902
|
const expression = typeof as === "function" ? as() : as;
|
|
4980
2903
|
if (!isSqlTemplate(expression)) throw new Error(DRIZZLE_REFUSALS.generatedValue);
|
|
@@ -4983,34 +2906,18 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
4983
2906
|
readOnly: true
|
|
4984
2907
|
});
|
|
4985
2908
|
}
|
|
4986
|
-
/**
|
|
4987
|
-
* Client writes are refused on create and update. The database (a default,
|
|
4988
|
-
* a trigger) and the server's own code still fill it.
|
|
4989
|
-
*/
|
|
4990
2909
|
readOnly() {
|
|
4991
2910
|
return this.with({ readOnly: true });
|
|
4992
2911
|
}
|
|
4993
|
-
/**
|
|
4994
|
-
* Never leaves the server: absent from every row on the wire, from the SDK
|
|
4995
|
-
* and from OpenAPI, and refused in filters and sorts. Hooks and server code
|
|
4996
|
-
* still see it.
|
|
4997
|
-
*/
|
|
4998
2912
|
private() {
|
|
4999
2913
|
return this.with({ private: true });
|
|
5000
2914
|
}
|
|
5001
|
-
/**
|
|
5002
|
-
* Who may read and who may write the column, by role. Enforced on every
|
|
5003
|
-
* door into the table, not only in the panel. `read` and `write` are lists
|
|
5004
|
-
* of role names; anything else throws.
|
|
5005
|
-
*/
|
|
5006
2915
|
access(access) {
|
|
5007
2916
|
return this.with({ access: normalizeColumnAccess(access, "a column (`.access()`)") });
|
|
5008
2917
|
}
|
|
5009
|
-
/** What the column holds, for OpenAPI and MCP tool descriptions. */
|
|
5010
2918
|
describe(description) {
|
|
5011
2919
|
return this.with({ description });
|
|
5012
2920
|
}
|
|
5013
|
-
/** Rules the API checks before a write. */
|
|
5014
2921
|
validate(rules) {
|
|
5015
2922
|
const input = rules;
|
|
5016
2923
|
return this.with({ validate: {
|
|
@@ -5018,27 +2925,10 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
5018
2925
|
...normalizeValidation(input)
|
|
5019
2926
|
} });
|
|
5020
2927
|
}
|
|
5021
|
-
/**
|
|
5022
|
-
* Field-level hooks: `beforeSave` returns the value to store, `afterRead`
|
|
5023
|
-
* the value to serve. They run on the server, for every caller.
|
|
5024
|
-
*
|
|
5025
|
-
* The value is `TData | null` on a column not (yet) marked `.notNull()` /
|
|
5026
|
-
* `.primaryKey()` — a nullable column hands the hook `null` — and `TData`
|
|
5027
|
-
* on one that is; see {@link ColumnTransformValue}. Chain `.notNull()`
|
|
5028
|
-
* before `.transform()` to get the narrower type.
|
|
5029
|
-
*/
|
|
5030
2928
|
transform(transform) {
|
|
5031
2929
|
const erased = transform;
|
|
5032
2930
|
return this.with({ transform: erased });
|
|
5033
2931
|
}
|
|
5034
|
-
/**
|
|
5035
|
-
* A closed set of accepted values that is *not* a Postgres enum type: the
|
|
5036
|
-
* API refuses anything else and the SDK types the column as their union.
|
|
5037
|
-
* Use `col.enum()` when the database should enforce it too.
|
|
5038
|
-
*
|
|
5039
|
-
* On a number column. On a text column write Drizzle's spelling,
|
|
5040
|
-
* `col.text({ enum: [...] })`.
|
|
5041
|
-
*/
|
|
5042
2932
|
oneOf(values) {
|
|
5043
2933
|
const stored = [];
|
|
5044
2934
|
for (const value of values) {
|
|
@@ -5047,27 +2937,16 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
5047
2937
|
}
|
|
5048
2938
|
return this.with({ oneOf: stored });
|
|
5049
2939
|
}
|
|
5050
|
-
/** `DEFAULT gen_random_uuid()`. */
|
|
5051
2940
|
defaultRandom() {
|
|
5052
2941
|
return this.with({ default: { kind: "random-uuid" } });
|
|
5053
2942
|
}
|
|
5054
|
-
/** `GENERATED BY DEFAULT AS IDENTITY`. Sequence options are refused. */
|
|
5055
2943
|
generatedByDefaultAsIdentity(sequence) {
|
|
5056
2944
|
if (sequence !== void 0) throw new Error(DRIZZLE_REFUSALS.identityOptions);
|
|
5057
2945
|
return this.with({ default: { kind: "identity" } });
|
|
5058
2946
|
}
|
|
5059
|
-
/** Refused: Rebase creates identity columns `GENERATED BY DEFAULT`. See {@link DRIZZLE_REFUSALS}. */
|
|
5060
2947
|
generatedAlwaysAsIdentity(..._args) {
|
|
5061
2948
|
throw new Error(DRIZZLE_REFUSALS.identityAlways);
|
|
5062
2949
|
}
|
|
5063
|
-
/**
|
|
5064
|
-
* A Postgres array of this column's type, as Drizzle writes it:
|
|
5065
|
-
* `col.text().array()` is `TEXT[]`. What is chained before `.array()`
|
|
5066
|
-
* describes each item (`col.text({ enum: [...] }).array()`,
|
|
5067
|
-
* `col.integer().validate({ min: 0 }).array()`); column modifiers come
|
|
5068
|
-
* after it (`.array().notNull().default([])`). A leading SQL name
|
|
5069
|
-
* (`col.text("tag_list").array()`) names the array column.
|
|
5070
|
-
*/
|
|
5071
2950
|
array(size) {
|
|
5072
2951
|
if (size !== void 0) throw new Error(DRIZZLE_REFUSALS.arraySize);
|
|
5073
2952
|
if (!isColumnBuilder(this)) throw new Error("`.array()` is called on a column builder.");
|
|
@@ -5077,57 +2956,36 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
5077
2956
|
if (column !== void 0) def.column = column;
|
|
5078
2957
|
return new ColumnBuilder(def);
|
|
5079
2958
|
}
|
|
5080
|
-
/**
|
|
5081
|
-
* `DEFAULT now()`, as Drizzle's `defaultNow()`: a DDL default a client may
|
|
5082
|
-
* still override. `.onCreateNow()` is the server stamp the client cannot.
|
|
5083
|
-
*/
|
|
5084
2959
|
defaultNow() {
|
|
5085
2960
|
return this.with({ default: {
|
|
5086
2961
|
kind: "sql",
|
|
5087
2962
|
expression: "now()"
|
|
5088
2963
|
} });
|
|
5089
2964
|
}
|
|
5090
|
-
/** The server stamps the current time when the row is created (`DEFAULT now()`). */
|
|
5091
2965
|
onCreateNow() {
|
|
5092
2966
|
return this.with(this.stamped({
|
|
5093
2967
|
on: "create",
|
|
5094
2968
|
value: "now"
|
|
5095
2969
|
}, "onCreateNow"));
|
|
5096
2970
|
}
|
|
5097
|
-
/**
|
|
5098
|
-
* The server stamps the current time on every write: `DEFAULT now()`, a
|
|
5099
|
-
* `BEFORE UPDATE` trigger, and the driver's own stamp.
|
|
5100
|
-
*/
|
|
5101
2971
|
onUpdateNow() {
|
|
5102
2972
|
return this.with(this.stamped({
|
|
5103
2973
|
on: "update",
|
|
5104
2974
|
value: "now"
|
|
5105
2975
|
}, "onUpdateNow"));
|
|
5106
2976
|
}
|
|
5107
|
-
/** The server writes the caller's id when the row is created. */
|
|
5108
2977
|
onCreateUser() {
|
|
5109
2978
|
return this.with(this.stamped({
|
|
5110
2979
|
on: "create",
|
|
5111
2980
|
value: "user"
|
|
5112
2981
|
}, "onCreateUser"));
|
|
5113
2982
|
}
|
|
5114
|
-
/** The server writes the caller's id on every write. */
|
|
5115
2983
|
onUpdateUser() {
|
|
5116
2984
|
return this.with(this.stamped({
|
|
5117
2985
|
on: "update",
|
|
5118
2986
|
value: "user"
|
|
5119
2987
|
}, "onUpdateUser"));
|
|
5120
2988
|
}
|
|
5121
|
-
/**
|
|
5122
|
-
* The column holds the id of a user. The panel offers a user picker for it,
|
|
5123
|
-
* and callers who may write the table may look users up to fill it (the
|
|
5124
|
-
* user picker's read answers them even though row-level security hides
|
|
5125
|
-
* other users' rows).
|
|
5126
|
-
*
|
|
5127
|
-
* Only on `col.text()`, `col.varchar()`, `col.char()` and `col.uuid()`;
|
|
5128
|
-
* anything else throws. It declares no foreign key: use
|
|
5129
|
-
* `rel.belongsTo(() => users)` when the database should enforce one.
|
|
5130
|
-
*/
|
|
5131
2989
|
userId() {
|
|
5132
2990
|
const kind = this.def.type.kind;
|
|
5133
2991
|
if (kind !== "text" && kind !== "varchar" && kind !== "char" && kind !== "uuid" || this.def.storage !== void 0) {
|
|
@@ -5136,7 +2994,6 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
5136
2994
|
}
|
|
5137
2995
|
return this.with({ semantic: "user" });
|
|
5138
2996
|
}
|
|
5139
|
-
/** The column holds several files: `TEXT[]` of paths. */
|
|
5140
2997
|
multiple() {
|
|
5141
2998
|
const { storage, validate, ...rest } = this.def;
|
|
5142
2999
|
return new ColumnBuilder({
|
|
@@ -5154,30 +3011,25 @@ var ColumnBuilder = class ColumnBuilder {
|
|
|
5154
3011
|
});
|
|
5155
3012
|
}
|
|
5156
3013
|
};
|
|
5157
|
-
/** The SQL column name a builder's leading argument gives, checked. */
|
|
5158
3014
|
function sqlName(name, builder) {
|
|
5159
3015
|
if (name === void 0) return void 0;
|
|
5160
|
-
if (typeof name !== "string" || name.length === 0) throw new Error(`\`col.${builder}(name,
|
|
3016
|
+
if (typeof name !== "string" || name.length === 0) throw new Error(`\`col.${builder}(name, \u2026)\`: the leading argument is the SQL column name, a non-empty string.`);
|
|
5161
3017
|
return name;
|
|
5162
3018
|
}
|
|
5163
|
-
/** A fresh definition, named by the builder's leading argument when it has one. */
|
|
5164
3019
|
function namedDef(type, name, builder) {
|
|
5165
3020
|
const def = baseDef(type);
|
|
5166
3021
|
const column = sqlName(name, builder);
|
|
5167
3022
|
if (column !== void 0) def.column = column;
|
|
5168
3023
|
return def;
|
|
5169
3024
|
}
|
|
5170
|
-
/** Drizzle's `(name?, config?)` arguments, either of which may be left out. */
|
|
5171
3025
|
function nameAndConfig(first, second) {
|
|
5172
3026
|
return typeof first === "string" ? [first, second] : [void 0, first];
|
|
5173
3027
|
}
|
|
5174
|
-
/** A config object, checked at run time: JavaScript callers bypass the types. */
|
|
5175
3028
|
function configOf(value, builder) {
|
|
5176
3029
|
if (value === void 0) return {};
|
|
5177
3030
|
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`\`col.${builder}()\` takes an optional SQL column name and a config object, got ${JSON.stringify(value)}.`);
|
|
5178
3031
|
return { ...value };
|
|
5179
3032
|
}
|
|
5180
|
-
/** The definition of an array of `item`: what `col.text().array()` builds. */
|
|
5181
3033
|
function arrayDef(item) {
|
|
5182
3034
|
if (item.type.kind === "array") throw new Error(DRIZZLE_REFUSALS.arrayOfArray);
|
|
5183
3035
|
const def = baseDef({
|
|
@@ -5188,7 +3040,6 @@ function arrayDef(item) {
|
|
|
5188
3040
|
if (item.storage) def.storage = item.storage;
|
|
5189
3041
|
return def;
|
|
5190
3042
|
}
|
|
5191
|
-
/** A list of string labels: an enum's values, Drizzle's `{ enum: [...] }`. */
|
|
5192
3043
|
function labelsOf(values, where) {
|
|
5193
3044
|
if (!Array.isArray(values) || values.length === 0 || values.some((value) => typeof value !== "string")) throw new Error(`${where} takes a non-empty list of strings, got ${JSON.stringify(values)}.`);
|
|
5194
3045
|
return values.filter((value) => typeof value === "string");
|
|
@@ -5219,7 +3070,6 @@ function text(first, second) {
|
|
|
5219
3070
|
if (config.enum !== void 0) def.oneOf = labelsOf(config.enum, "`col.text({ enum })`");
|
|
5220
3071
|
return new ColumnBuilder(def);
|
|
5221
3072
|
}
|
|
5222
|
-
/** `varchar` / `char`: Drizzle's `(name?, { length, enum? })`. A length is required. */
|
|
5223
3073
|
function stringColumn(kind, first, second) {
|
|
5224
3074
|
const name = typeof first === "string" ? first : void 0;
|
|
5225
3075
|
const raw = typeof first === "string" ? second : first;
|
|
@@ -5255,7 +3105,6 @@ function enumColumn(first, second) {
|
|
|
5255
3105
|
values: [...first]
|
|
5256
3106
|
}));
|
|
5257
3107
|
}
|
|
5258
|
-
/** `numeric`, Drizzle's `(name?, { precision, scale, mode })`. */
|
|
5259
3108
|
function numericColumn(builder, first, second) {
|
|
5260
3109
|
if (typeof first === "number" || typeof second === "number") throw new Error(DRIZZLE_REFUSALS.numericPositional);
|
|
5261
3110
|
const name = typeof first === "string" ? first : void 0;
|
|
@@ -5280,7 +3129,6 @@ function numeric(first, second) {
|
|
|
5280
3129
|
function decimal(first, second) {
|
|
5281
3130
|
return numericColumn("decimal", first, second);
|
|
5282
3131
|
}
|
|
5283
|
-
/** `bigint` / `bigserial`, Drizzle's `(name?, { mode })`. */
|
|
5284
3132
|
function bigColumn(kind, first, second) {
|
|
5285
3133
|
const name = typeof first === "string" ? first : void 0;
|
|
5286
3134
|
const raw = typeof first === "string" ? second : first;
|
|
@@ -5347,143 +3195,58 @@ function custom(first, second) {
|
|
|
5347
3195
|
sqlType: customSqlType(config.dataType)
|
|
5348
3196
|
}, name, "custom"));
|
|
5349
3197
|
}
|
|
5350
|
-
/** A builder for a Drizzle column type Rebase serves only through `col.custom()`: refused with the spelling. */
|
|
5351
3198
|
function unsupported(type) {
|
|
5352
3199
|
return () => {
|
|
5353
3200
|
throw new Error(unsupportedMessage(type));
|
|
5354
3201
|
};
|
|
5355
3202
|
}
|
|
5356
|
-
/** A builder that takes only the optional SQL column name. */
|
|
5357
3203
|
function simple(kind, type) {
|
|
5358
3204
|
return (name) => new ColumnBuilder(namedDef(type, name, kind));
|
|
5359
3205
|
}
|
|
5360
|
-
/**
|
|
5361
|
-
* The column builders, spelled as Drizzle's `pg-core` spells them: the
|
|
5362
|
-
* optional SQL column name first, then Drizzle's config object, then the
|
|
5363
|
-
* chain.
|
|
5364
|
-
*
|
|
5365
|
-
* ```ts
|
|
5366
|
-
* columns: {
|
|
5367
|
-
* id: col.uuid().primaryKey().defaultRandom(),
|
|
5368
|
-
* title: col.text().notNull().validate({ min: 3, max: 200 }),
|
|
5369
|
-
* slug: col.varchar({ length: 160 }).notNull().unique(),
|
|
5370
|
-
* status: postStatus().notNull().default("draft"), // const postStatus = pgEnum("post_status", [...])
|
|
5371
|
-
* tags: col.text().array().notNull().default([]),
|
|
5372
|
-
* heroImage: col.storage({ path: "posts/heroes/", accept: ["image/*"], maxBytes: "10MB" }),
|
|
5373
|
-
* createdAt: col.timestamp({ withTimezone: true }).notNull().defaultNow(),
|
|
5374
|
-
* }
|
|
5375
|
-
* ```
|
|
5376
|
-
*
|
|
5377
|
-
* @group Schema
|
|
5378
|
-
*/
|
|
5379
3206
|
var col = {
|
|
5380
|
-
/** `UUID`. */
|
|
5381
3207
|
uuid: simple("uuid", { kind: "uuid" }),
|
|
5382
|
-
/** `TEXT`. `col.text({ enum: [...] })` accepts only those values. */
|
|
5383
3208
|
text,
|
|
5384
|
-
/** `VARCHAR(n)`: `col.varchar({ length: n })`. */
|
|
5385
3209
|
varchar,
|
|
5386
|
-
/** `CHAR(n)`: `col.char({ length: n })`. */
|
|
5387
3210
|
char,
|
|
5388
|
-
/**
|
|
5389
|
-
* A Postgres enum type of its own, created as `<table>_<column>`. A type
|
|
5390
|
-
* with a stated name, shared by several columns, is `pgEnum(name, values)`.
|
|
5391
|
-
*/
|
|
5392
3211
|
enum: enumColumn,
|
|
5393
|
-
/** `SMALLINT`. */
|
|
5394
3212
|
smallint: simple("smallint", { kind: "smallint" }),
|
|
5395
|
-
/** `INTEGER`. */
|
|
5396
3213
|
integer: simple("integer", { kind: "integer" }),
|
|
5397
|
-
/** `BIGINT`, read and written as a JavaScript number: `col.bigint({ mode: "number" })`. */
|
|
5398
3214
|
bigint,
|
|
5399
|
-
/** `SMALLSERIAL`. Prefer `col.smallint().generatedByDefaultAsIdentity()` in a new schema. */
|
|
5400
3215
|
smallserial(name) {
|
|
5401
3216
|
return new ColumnBuilder(namedDef({ kind: "smallserial" }, name, "smallserial"));
|
|
5402
3217
|
},
|
|
5403
|
-
/** `SERIAL`. Prefer `col.integer().generatedByDefaultAsIdentity()` in a new schema. */
|
|
5404
3218
|
serial(name) {
|
|
5405
3219
|
return new ColumnBuilder(namedDef({ kind: "serial" }, name, "serial"));
|
|
5406
3220
|
},
|
|
5407
|
-
/** `BIGSERIAL`: `col.bigserial({ mode: "number" })`. Prefer an identity column in a new schema. */
|
|
5408
3221
|
bigserial,
|
|
5409
|
-
/** `REAL`. */
|
|
5410
3222
|
real: simple("real", { kind: "real" }),
|
|
5411
|
-
/** `DOUBLE PRECISION`. */
|
|
5412
3223
|
doublePrecision: simple("doublePrecision", { kind: "doublePrecision" }),
|
|
5413
|
-
/** `NUMERIC`, `NUMERIC(p)` or `NUMERIC(p, s)`: `col.numeric({ precision, scale })`. A JSON number. */
|
|
5414
3224
|
numeric,
|
|
5415
|
-
/** Drizzle's alias of `col.numeric()`. */
|
|
5416
3225
|
decimal,
|
|
5417
|
-
/** `BOOLEAN`. */
|
|
5418
3226
|
boolean: simple("boolean", { kind: "boolean" }),
|
|
5419
|
-
/** `TIMESTAMPTZ`: `col.timestamp({ withTimezone: true })`. An ISO string on the wire. */
|
|
5420
3227
|
timestamp,
|
|
5421
|
-
/** `DATE`. `YYYY-MM-DD` on the wire. */
|
|
5422
3228
|
date,
|
|
5423
|
-
/** `TIME`. `HH:MM:SS` on the wire. */
|
|
5424
3229
|
time,
|
|
5425
|
-
/**
|
|
5426
|
-
* `JSONB`. `col.jsonb().$type<T>()` types the document;
|
|
5427
|
-
* `col.jsonb(json.object({...}))` also tells the server its shape, so
|
|
5428
|
-
* nested fields are validated, stamped and searchable.
|
|
5429
|
-
*/
|
|
5430
3230
|
jsonb,
|
|
5431
|
-
/** `JSON`. As `col.jsonb`, for a column that must keep the text it was given. */
|
|
5432
3231
|
json: json$1,
|
|
5433
|
-
/**
|
|
5434
|
-
* `vector(dimensions)` (pgvector): `col.vector({ dimensions: 1536 })`. An
|
|
5435
|
-
* HNSW cosine index is created unless `index` says otherwise; `index: false`
|
|
5436
|
-
* creates none.
|
|
5437
|
-
*/
|
|
5438
3232
|
vector,
|
|
5439
|
-
/** `BYTEA`. Base64 on the wire. */
|
|
5440
3233
|
bytea: simple("bytea", { kind: "bytea" }),
|
|
5441
|
-
/** A point on Earth, stored as `JSONB` `{ latitude, longitude }`. */
|
|
5442
3234
|
geopoint(name) {
|
|
5443
3235
|
const def = namedDef({ kind: "jsonb" }, name, "geopoint");
|
|
5444
3236
|
def.semantic = "geopoint";
|
|
5445
3237
|
return new ColumnBuilder(def);
|
|
5446
3238
|
},
|
|
5447
|
-
/**
|
|
5448
|
-
* The path of a stored file, as `TEXT` — or several with `.multiple()`. The
|
|
5449
|
-
* upload route enforces `accept` and `maxBytes`, and the orphan sweep counts
|
|
5450
|
-
* the file as referenced.
|
|
5451
|
-
*/
|
|
5452
3239
|
storage,
|
|
5453
|
-
/**
|
|
5454
|
-
* A column of a Postgres type no other builder names —
|
|
5455
|
-
* `col.custom({ dataType: "inet" })`, `col.custom({ dataType: "citext" })`,
|
|
5456
|
-
* `col.custom({ dataType: "geometry(Point, 4326)" })`. What
|
|
5457
|
-
* `rebase schema introspect` writes for a column of such a type, so a
|
|
5458
|
-
* project generated from an existing database keeps it.
|
|
5459
|
-
*
|
|
5460
|
-
* Rebase names the type in DDL, verbatim, and does nothing else with it: it
|
|
5461
|
-
* does not create, alter or drop the type's definition (an extension or a
|
|
5462
|
-
* `CREATE TYPE` the database already holds provides it), it does not
|
|
5463
|
-
* validate values, and it passes every value through exactly as the
|
|
5464
|
-
* driver returns it — a string for most types. `.$type<T>()` types it for
|
|
5465
|
-
* the SDK when the driver returns something else.
|
|
5466
|
-
*/
|
|
5467
3240
|
custom,
|
|
5468
|
-
/** Refused: write `col.custom({ dataType: "interval" })`. */
|
|
5469
3241
|
interval: unsupported("interval"),
|
|
5470
|
-
/** Refused: write `col.custom({ dataType: "inet" })`. */
|
|
5471
3242
|
inet: unsupported("inet"),
|
|
5472
|
-
/** Refused: write `col.custom({ dataType: "cidr" })`. */
|
|
5473
3243
|
cidr: unsupported("cidr"),
|
|
5474
|
-
/** Refused: write `col.custom({ dataType: "macaddr" })`. */
|
|
5475
3244
|
macaddr: unsupported("macaddr"),
|
|
5476
|
-
/** Refused: write `col.custom({ dataType: "macaddr8" })`. */
|
|
5477
3245
|
macaddr8: unsupported("macaddr8"),
|
|
5478
|
-
/** Refused: write `col.custom({ dataType: "point" })`. */
|
|
5479
3246
|
point: unsupported("point"),
|
|
5480
|
-
/** Refused: write `col.custom({ dataType: "line" })`. */
|
|
5481
3247
|
line: unsupported("line"),
|
|
5482
|
-
/** Refused: write `col.custom({ dataType: "halfvec" })`. */
|
|
5483
3248
|
halfvec: unsupported("halfvec"),
|
|
5484
|
-
/** Refused: write `col.custom({ dataType: "sparsevec" })`. */
|
|
5485
3249
|
sparsevec: unsupported("sparsevec"),
|
|
5486
|
-
/** Refused: write `col.custom({ dataType: "bit" })`. */
|
|
5487
3250
|
bit: unsupported("bit")
|
|
5488
3251
|
};
|
|
5489
3252
|
function pgEnum(enumName, values) {
|
|
@@ -5503,35 +3266,23 @@ function pgEnum(enumName, values) {
|
|
|
5503
3266
|
function isLabelTuple(values) {
|
|
5504
3267
|
return Array.isArray(values) && values.length > 0 && values.every((value) => typeof value === "string");
|
|
5505
3268
|
}
|
|
5506
|
-
/**
|
|
5507
|
-
* The type name `col.custom()` puts into DDL: trimmed, and refused when it is
|
|
5508
|
-
* empty or could end the statement it is written into.
|
|
5509
|
-
*/
|
|
5510
3269
|
function customSqlType(sqlType) {
|
|
5511
3270
|
const trimmed = typeof sqlType === "string" ? sqlType.trim() : "";
|
|
5512
3271
|
if (trimmed.length === 0) throw new Error("`col.custom()` takes the Postgres type, e.g. `col.custom({ dataType: \"inet\" })`.");
|
|
5513
3272
|
if (/;|--|\/\*/.test(trimmed)) throw new Error(`\`col.custom({ dataType: ${JSON.stringify(sqlType)} })\`: a type name holds no \`;\` and no comment.`);
|
|
5514
3273
|
return trimmed;
|
|
5515
3274
|
}
|
|
5516
|
-
/**
|
|
5517
|
-
* Whether a value is a column builder, from this copy of the package or
|
|
5518
|
-
* another.
|
|
5519
|
-
*
|
|
5520
|
-
* @group Schema
|
|
5521
|
-
*/
|
|
5522
3275
|
function isColumnBuilder(value) {
|
|
5523
3276
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.column";
|
|
5524
3277
|
}
|
|
5525
3278
|
//#endregion
|
|
5526
3279
|
//#region src/schema/relations.ts
|
|
5527
|
-
/** The brand every relation builder result carries. */
|
|
5528
3280
|
var RELATION_BRAND = "rebase.relation";
|
|
5529
|
-
/** The options with `access` checked and copied: a role list, never a string spread into characters. */
|
|
5530
3281
|
function withCheckedAccess(kind, options) {
|
|
5531
3282
|
if (options.access === void 0) return options;
|
|
5532
3283
|
return {
|
|
5533
3284
|
...options,
|
|
5534
|
-
access: normalizeColumnAccess(options.access, `a relation (\`rel.${kind}(
|
|
3285
|
+
access: normalizeColumnAccess(options.access, `a relation (\`rel.${kind}(\u2026, { access })\`)`)
|
|
5535
3286
|
};
|
|
5536
3287
|
}
|
|
5537
3288
|
function belongsTo(target, options = {}) {
|
|
@@ -5542,27 +3293,8 @@ function belongsTo(target, options = {}) {
|
|
|
5542
3293
|
target
|
|
5543
3294
|
};
|
|
5544
3295
|
}
|
|
5545
|
-
/**
|
|
5546
|
-
* The relation builders. All five kinds; the target is a thunk, so two tables
|
|
5547
|
-
* can point at each other whatever order their modules load in — and, being a
|
|
5548
|
-
* {@link TableThunk}, without a type annotation on either side.
|
|
5549
|
-
*
|
|
5550
|
-
* ```ts
|
|
5551
|
-
* relations: {
|
|
5552
|
-
* author: rel.belongsTo(() => users, { localKey: "author_id", notNull: true, onDelete: "restrict" }),
|
|
5553
|
-
* tags: rel.manyToMany(() => tags, { through: "posts_tags", pivot: { sortOrder: col.integer().default(0) } }),
|
|
5554
|
-
* }
|
|
5555
|
-
* ```
|
|
5556
|
-
*
|
|
5557
|
-
* @group Schema
|
|
5558
|
-
*/
|
|
5559
3296
|
var rel = {
|
|
5560
|
-
/**
|
|
5561
|
-
* This table holds the foreign key. Binds to the column in `columns` whose
|
|
5562
|
-
* SQL name is `localKey`, or derives that column and indexes it.
|
|
5563
|
-
*/
|
|
5564
3297
|
belongsTo,
|
|
5565
|
-
/** The target holds a unique foreign key pointing here. */
|
|
5566
3298
|
hasOne(target, options = {}) {
|
|
5567
3299
|
return {
|
|
5568
3300
|
...withCheckedAccess("hasOne", options),
|
|
@@ -5571,7 +3303,6 @@ var rel = {
|
|
|
5571
3303
|
target
|
|
5572
3304
|
};
|
|
5573
3305
|
},
|
|
5574
|
-
/** The target holds a foreign key pointing here. */
|
|
5575
3306
|
hasMany(target, options = {}) {
|
|
5576
3307
|
return {
|
|
5577
3308
|
...withCheckedAccess("hasMany", options),
|
|
@@ -5580,10 +3311,6 @@ var rel = {
|
|
|
5580
3311
|
target
|
|
5581
3312
|
};
|
|
5582
3313
|
},
|
|
5583
|
-
/**
|
|
5584
|
-
* Linked through a junction table, which is created with its own row-level
|
|
5585
|
-
* security. `pivot` columns are read and written as `_pivot`.
|
|
5586
|
-
*/
|
|
5587
3314
|
manyToMany(target, options = {}) {
|
|
5588
3315
|
return {
|
|
5589
3316
|
...withCheckedAccess("manyToMany", options),
|
|
@@ -5592,7 +3319,6 @@ var rel = {
|
|
|
5592
3319
|
target
|
|
5593
3320
|
};
|
|
5594
3321
|
},
|
|
5595
|
-
/** A read-only traversal across several joins. */
|
|
5596
3322
|
via(target, options) {
|
|
5597
3323
|
if (!options.steps || options.steps.length === 0) throw new Error("`rel.via(target, { steps })` needs at least one join step.");
|
|
5598
3324
|
return {
|
|
@@ -5603,26 +3329,19 @@ var rel = {
|
|
|
5603
3329
|
};
|
|
5604
3330
|
}
|
|
5605
3331
|
};
|
|
5606
|
-
/**
|
|
5607
|
-
* Whether a value is the result of a `rel.*` call.
|
|
5608
|
-
*
|
|
5609
|
-
* @group Schema
|
|
5610
|
-
*/
|
|
5611
3332
|
function isRelationDef(value) {
|
|
5612
3333
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.relation";
|
|
5613
3334
|
}
|
|
5614
3335
|
//#endregion
|
|
5615
3336
|
//#region src/schema/table.ts
|
|
5616
|
-
/** The brand of a `defineTable` / `defineAuthTable` result. */
|
|
5617
3337
|
var TABLE_BRAND = "rebase.table";
|
|
5618
|
-
/** The brand of a `defineView` result. */
|
|
5619
3338
|
var VIEW_BRAND = "rebase.view";
|
|
5620
3339
|
var IDENTIFIER$1 = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
5621
3340
|
function assertTableShape(builder, name, config) {
|
|
5622
3341
|
if (typeof name !== "string" || name.length === 0) throw new Error(`\`${builder}(name, config)\` needs the table's name as its first argument.`);
|
|
5623
3342
|
if (typeof config !== "object" || config === null) throw new Error(`\`${builder}("${name}", config)\` needs a config object.`);
|
|
5624
3343
|
const columns = "columns" in config ? config.columns : void 0;
|
|
5625
|
-
if (typeof columns !== "object" || columns === null || Object.keys(columns).length === 0) throw new Error(`Table "${name}" declares no columns. Add \`columns: { id: col.uuid().primaryKey().defaultRandom(),
|
|
3344
|
+
if (typeof columns !== "object" || columns === null || Object.keys(columns).length === 0) throw new Error(`Table "${name}" declares no columns. Add \`columns: { id: col.uuid().primaryKey().defaultRandom(), \u2026 }\`.`);
|
|
5626
3345
|
for (const [key, column] of Object.entries(columns)) if (!isColumnBuilder(column)) throw new Error(`Column "${key}" of table "${name}" is not a \`col.*\` builder.`);
|
|
5627
3346
|
const relations = "relations" in config ? config.relations : void 0;
|
|
5628
3347
|
if (relations !== void 0) {
|
|
@@ -5640,31 +3359,8 @@ function assertTableShape(builder, name, config) {
|
|
|
5640
3359
|
function assertRlsDeclared(builder, name, config) {
|
|
5641
3360
|
const rls = "rls" in config ? config.rls : void 0;
|
|
5642
3361
|
if (rls === "admin-only" || rls === "inherit" || Array.isArray(rls) && rls.length > 0) return;
|
|
5643
|
-
throw new Error(`\`${builder}("${name}",
|
|
5644
|
-
}
|
|
5645
|
-
/**
|
|
5646
|
-
* Define a Postgres table.
|
|
5647
|
-
*
|
|
5648
|
-
* The name is the SQL table and the API slug; `rls` is mandatory. The result
|
|
5649
|
-
* is what the backend reads from `backend/schema/index.ts` — it generates the
|
|
5650
|
-
* DDL and the policies, serves the REST, realtime and MCP surfaces, and types
|
|
5651
|
-
* the SDK.
|
|
5652
|
-
*
|
|
5653
|
-
* ```ts
|
|
5654
|
-
* export const posts = defineTable("posts", {
|
|
5655
|
-
* columns: {
|
|
5656
|
-
* id: col.uuid().primaryKey().defaultRandom(),
|
|
5657
|
-
* title: col.text().notNull(),
|
|
5658
|
-
* },
|
|
5659
|
-
* rls: [
|
|
5660
|
-
* { operation: "select", access: "public" },
|
|
5661
|
-
* { operations: ["insert", "update", "delete"], roles: ["editor"] },
|
|
5662
|
-
* ],
|
|
5663
|
-
* });
|
|
5664
|
-
* ```
|
|
5665
|
-
*
|
|
5666
|
-
* @group Schema
|
|
5667
|
-
*/
|
|
3362
|
+
throw new Error(`\`${builder}("${name}", \u2026)\` has no usable \`rls\`. ${Array.isArray(rls) ? "`rls: []` grants nothing and says nothing. Write `rls: \"admin-only\"` to lock the table to admins." : "Every table needs an explicit row-level security posture."} Accepted: \`"admin-only"\`, \`"inherit"\` (the \`defaultRls\` exported from backend/schema/index.ts), or a non-empty list of rules.`);
|
|
3363
|
+
}
|
|
5668
3364
|
function defineTable(name, config) {
|
|
5669
3365
|
assertTableShape("defineTable", name, config);
|
|
5670
3366
|
assertRlsDeclared("defineTable", name, config);
|
|
@@ -5674,16 +3370,6 @@ function defineTable(name, config) {
|
|
|
5674
3370
|
config
|
|
5675
3371
|
};
|
|
5676
3372
|
}
|
|
5677
|
-
/**
|
|
5678
|
-
* Define the table users are stored in.
|
|
5679
|
-
*
|
|
5680
|
-
* A `defineTable` that auth reads and writes: the columns auth needs are added
|
|
5681
|
-
* when the table does not declare them, a signed-in user can read their own
|
|
5682
|
-
* row, and the privilege columns (`roles`) can only be written by an admin —
|
|
5683
|
-
* whatever `rls` says. A project has at most one.
|
|
5684
|
-
*
|
|
5685
|
-
* @group Schema
|
|
5686
|
-
*/
|
|
5687
3373
|
function defineAuthTable(name, config) {
|
|
5688
3374
|
assertTableShape("defineAuthTable", name, config);
|
|
5689
3375
|
assertRlsDeclared("defineAuthTable", name, config);
|
|
@@ -5695,15 +3381,6 @@ function defineAuthTable(name, config) {
|
|
|
5695
3381
|
auth: auth ?? {}
|
|
5696
3382
|
};
|
|
5697
3383
|
}
|
|
5698
|
-
/**
|
|
5699
|
-
* Define a SQL view, served read-only.
|
|
5700
|
-
*
|
|
5701
|
-
* A plain view is created `WITH (security_invoker = true)`: the row-level
|
|
5702
|
-
* security of the tables it reads decides what each caller sees. A
|
|
5703
|
-
* materialized view stores its rows, so it is gated by `roles` instead.
|
|
5704
|
-
*
|
|
5705
|
-
* @group Schema
|
|
5706
|
-
*/
|
|
5707
3384
|
function defineView(name, config) {
|
|
5708
3385
|
assertTableShape("defineView", name, config);
|
|
5709
3386
|
if (typeof config.query !== "string" || config.query.trim().length === 0) throw new Error(`View "${name}" needs a \`query\`: the SELECT that defines it.`);
|
|
@@ -5714,55 +3391,29 @@ function defineView(name, config) {
|
|
|
5714
3391
|
config
|
|
5715
3392
|
};
|
|
5716
3393
|
}
|
|
5717
|
-
/**
|
|
5718
|
-
* Whether a value is the result of `defineTable` or `defineAuthTable`, from
|
|
5719
|
-
* this copy of the package or another.
|
|
5720
|
-
*
|
|
5721
|
-
* @group Schema
|
|
5722
|
-
*/
|
|
5723
3394
|
function isTableDef(value) {
|
|
5724
3395
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.table";
|
|
5725
3396
|
}
|
|
5726
|
-
/**
|
|
5727
|
-
* Whether a value is the result of `defineAuthTable`.
|
|
5728
|
-
*
|
|
5729
|
-
* @group Schema
|
|
5730
|
-
*/
|
|
5731
3397
|
function isAuthTableDef(value) {
|
|
5732
3398
|
return isTableDef(value) && value.auth !== void 0;
|
|
5733
3399
|
}
|
|
5734
|
-
/**
|
|
5735
|
-
* Whether a value is the result of `defineView`.
|
|
5736
|
-
*
|
|
5737
|
-
* @group Schema
|
|
5738
|
-
*/
|
|
5739
3400
|
function isViewDef(value) {
|
|
5740
3401
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.view";
|
|
5741
3402
|
}
|
|
5742
3403
|
//#endregion
|
|
5743
3404
|
//#region src/schema/rpc.ts
|
|
5744
|
-
/** The brand of a `defineRpc` result. */
|
|
5745
3405
|
var RPC_BRAND = "rebase.rpc";
|
|
5746
|
-
/**
|
|
5747
|
-
* The limit a `public` RPC is held to when it declares none: 120 calls a
|
|
5748
|
-
* minute per caller.
|
|
5749
|
-
*
|
|
5750
|
-
* @group Schema
|
|
5751
|
-
*/
|
|
5752
3406
|
var DEFAULT_PUBLIC_RPC_RATE_LIMIT = {
|
|
5753
3407
|
limit: 120,
|
|
5754
3408
|
windowMs: 6e4
|
|
5755
3409
|
};
|
|
5756
|
-
/** A SQL identifier as Rebase writes one: letters, digits, `_`, not starting with a digit. */
|
|
5757
3410
|
var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
5758
|
-
/** Schemas whose functions are the database's or the server's own, never an RPC. */
|
|
5759
3411
|
var RESERVED_SCHEMAS = /* @__PURE__ */ new Set([
|
|
5760
3412
|
"rebase",
|
|
5761
3413
|
"pg_catalog",
|
|
5762
3414
|
"information_schema",
|
|
5763
3415
|
"pg_toast"
|
|
5764
3416
|
]);
|
|
5765
|
-
/** A modifier on a JSON field that means something on a write and nothing on a call. */
|
|
5766
3417
|
function writeOnlyModifier(shape) {
|
|
5767
3418
|
if (shape.transform !== void 0) return "`.transform()`";
|
|
5768
3419
|
if ((shape.kind === "string" || shape.kind === "date") && shape.stamp !== void 0) return shape.stamp === "createUser" || shape.stamp === "updateUser" ? "`.onCreateUser()` / `.onUpdateUser()`" : "`.onCreateNow()` / `.onUpdateNow()`";
|
|
@@ -5784,31 +3435,6 @@ function assertRateLimit(name, rateLimit) {
|
|
|
5784
3435
|
if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1) throw new Error(`RPC "${name}": \`rateLimit.limit\` must be a positive integer.`);
|
|
5785
3436
|
if (typeof windowMs !== "number" || !Number.isFinite(windowMs) || windowMs <= 0) throw new Error(`RPC "${name}": \`rateLimit.windowMs\` must be a positive number of milliseconds.`);
|
|
5786
3437
|
}
|
|
5787
|
-
/**
|
|
5788
|
-
* Expose a SQL function as `POST /api/rpc/<name>`, with a JSON body of named
|
|
5789
|
-
* arguments.
|
|
5790
|
-
*
|
|
5791
|
-
* Only declared functions are callable. Each call runs as the caller, like
|
|
5792
|
-
* `getSql(c)`: an anonymous caller as the anonymous identity, a signed-in one
|
|
5793
|
-
* as themselves under the tables' row-level security. A `SECURITY DEFINER`
|
|
5794
|
-
* function runs as its owner, as it does anywhere. The answer is the
|
|
5795
|
-
* function's result: an array of rows (or values) for a set-returning
|
|
5796
|
-
* function, the row or the value for any other.
|
|
5797
|
-
*
|
|
5798
|
-
* Export the result from `backend/schema/index.ts`, beside the tables.
|
|
5799
|
-
*
|
|
5800
|
-
* ```ts
|
|
5801
|
-
* // backend/schema/rpc.ts
|
|
5802
|
-
* import { defineRpc, json } from "@rebasepro/server/schema";
|
|
5803
|
-
*
|
|
5804
|
-
* export const getPublicProposal = defineRpc("get_public_proposal", {
|
|
5805
|
-
* access: "public",
|
|
5806
|
-
* args: { token: json.string().required() }
|
|
5807
|
-
* });
|
|
5808
|
-
* ```
|
|
5809
|
-
*
|
|
5810
|
-
* @group Schema
|
|
5811
|
-
*/
|
|
5812
3438
|
function defineRpc(name, config) {
|
|
5813
3439
|
if (typeof name !== "string" || !IDENTIFIER.test(name)) throw new Error(`defineRpc: ${JSON.stringify(name)} is not a function name an RPC can have. Use the SQL function's name as Postgres stores it: letters, digits and _, not starting with a digit (an unquoted \`CREATE FUNCTION getProposal\` is stored as \`getproposal\`).`);
|
|
5814
3440
|
if (typeof config !== "object" || config === null) throw new Error(`RPC "${name}" needs a config: \`defineRpc("${name}", { access: "public" | "authenticated" })\`.`);
|
|
@@ -5834,18 +3460,11 @@ function defineRpc(name, config) {
|
|
|
5834
3460
|
config
|
|
5835
3461
|
};
|
|
5836
3462
|
}
|
|
5837
|
-
/**
|
|
5838
|
-
* Whether a value is the result of `defineRpc`, from this copy of the package
|
|
5839
|
-
* or another.
|
|
5840
|
-
*
|
|
5841
|
-
* @group Schema
|
|
5842
|
-
*/
|
|
5843
3463
|
function isRpcDef(value) {
|
|
5844
3464
|
return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.rpc";
|
|
5845
3465
|
}
|
|
5846
3466
|
//#endregion
|
|
5847
3467
|
//#region src/schema/table_patch.ts
|
|
5848
|
-
/** The keys of {@link TableOptionValues}, in the order a table prints them. */
|
|
5849
3468
|
var TABLE_OPTION_KEYS = [
|
|
5850
3469
|
"description",
|
|
5851
3470
|
"defaultPolicies",
|
|
@@ -5858,11 +3477,6 @@ var TABLE_OPTION_KEYS = [
|
|
|
5858
3477
|
"strictWrites",
|
|
5859
3478
|
"metadata"
|
|
5860
3479
|
];
|
|
5861
|
-
/**
|
|
5862
|
-
* A list of table edits that cannot be applied, with every problem found.
|
|
5863
|
-
*
|
|
5864
|
-
* @group Schema
|
|
5865
|
-
*/
|
|
5866
3480
|
var TablePatchError = class TablePatchError extends Error {
|
|
5867
3481
|
problems;
|
|
5868
3482
|
code = "TABLE_PATCH_INVALID";
|
|
@@ -5880,13 +3494,7 @@ var TablePatchError = class TablePatchError extends Error {
|
|
|
5880
3494
|
return `The schema edit cannot be applied (${problems.length === 1 ? "1 problem" : `${problems.length} problems`}):\n${lines.join("\n")}`;
|
|
5881
3495
|
}
|
|
5882
3496
|
};
|
|
5883
|
-
/**
|
|
5884
|
-
* A name that reaches SQL as an identifier, or becomes a file name: letters,
|
|
5885
|
-
* digits, underscores and dollar signs, not starting with a digit. The same
|
|
5886
|
-
* alphabet the DDL builders accept, so a name accepted here is one they take.
|
|
5887
|
-
*/
|
|
5888
3497
|
var SQL_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;
|
|
5889
|
-
/** A key on the JSON row: any non-empty string without control characters. */
|
|
5890
3498
|
var isRowKey = (key) => key.length > 0 && [...key].every((char) => char.charCodeAt(0) >= 32);
|
|
5891
3499
|
var COLUMN_KINDS = /* @__PURE__ */ new Set([
|
|
5892
3500
|
"text",
|
|
@@ -5955,7 +3563,6 @@ var RELATION_OPTION_KEYS = {
|
|
|
5955
3563
|
"private"
|
|
5956
3564
|
]
|
|
5957
3565
|
};
|
|
5958
|
-
/** The relation options that name a SQL column or table. */
|
|
5959
3566
|
var RELATION_IDENTIFIER_KEYS = [
|
|
5960
3567
|
"localKey",
|
|
5961
3568
|
"foreignKey",
|
|
@@ -5971,12 +3578,11 @@ var MIGRATION_KEYS = {
|
|
|
5971
3578
|
name: "The table's name is its file and its default SQL name; renaming it moves data, which is a migration, not an edit. Write the rename in code together with a migration.",
|
|
5972
3579
|
database: "Moving the table to another database moves its rows, which is a migration, not an edit."
|
|
5973
3580
|
};
|
|
5974
|
-
/** Problems with a column definition sent on the wire. */
|
|
5975
3581
|
function columnProblems(value, where) {
|
|
5976
3582
|
if (!isRecord(value)) return [`${where} must be a column definition object.`];
|
|
5977
3583
|
const problems = [];
|
|
5978
3584
|
const type = value.type;
|
|
5979
|
-
if (!isRecord(type) || typeof type.kind !== "string" || !COLUMN_KINDS.has(type.kind)) problems.push(`${where}.type must be a column type, \`{ kind: "text" }\`, \`{ kind: "varchar", length: 160 }\`
|
|
3585
|
+
if (!isRecord(type) || typeof type.kind !== "string" || !COLUMN_KINDS.has(type.kind)) problems.push(`${where}.type must be a column type, \`{ kind: "text" }\`, \`{ kind: "varchar", length: 160 }\` \u2026`);
|
|
5980
3586
|
else if (type.kind === "array") {
|
|
5981
3587
|
if (!isRecord(type.of)) problems.push(`${where}.type.of must be the type of each item.`);
|
|
5982
3588
|
} else if ((type.kind === "varchar" || type.kind === "char") && typeof type.length !== "number") problems.push(`${where}.type.length must be a number.`);
|
|
@@ -5996,7 +3602,6 @@ function columnProblems(value, where) {
|
|
|
5996
3602
|
if (value.json !== void 0 && !isRecord(value.json)) problems.push(`${where}.json must be a JSON shape.`);
|
|
5997
3603
|
return problems;
|
|
5998
3604
|
}
|
|
5999
|
-
/** Problems with a table description sent to be adopted. */
|
|
6000
3605
|
function adoptedTableProblems(spec) {
|
|
6001
3606
|
const out = [];
|
|
6002
3607
|
for (const key of [
|
|
@@ -6054,7 +3659,6 @@ function adoptedTableProblems(spec) {
|
|
|
6054
3659
|
if (spec.auth !== void 0 || spec.view !== void 0) out.push({ message: "an auth table or a view is not adopted here: declare it in code." });
|
|
6055
3660
|
return out;
|
|
6056
3661
|
}
|
|
6057
|
-
/** Problems with a relation sent on the wire. */
|
|
6058
3662
|
function relationProblems(value, where) {
|
|
6059
3663
|
if (!isRecord(value)) return [`${where} must be a relation object.`];
|
|
6060
3664
|
const kind = value.kind;
|
|
@@ -6075,14 +3679,12 @@ function relationProblems(value, where) {
|
|
|
6075
3679
|
else for (const [key, column] of Object.entries(value.pivot)) problems.push(...columnProblems(column, `${where}.pivot.${key}`));
|
|
6076
3680
|
return problems;
|
|
6077
3681
|
}
|
|
6078
|
-
/** Problems with an `rls` value sent on the wire. */
|
|
6079
3682
|
function rlsProblems(value, where) {
|
|
6080
3683
|
if (value === "admin-only" || value === "inherit") return [];
|
|
6081
3684
|
if (!Array.isArray(value)) return [`${where} must be "admin-only", "inherit" or a list of rules.`];
|
|
6082
3685
|
if (value.length === 0) return [`${where} is an empty list of rules, which leaves nobody a policy. Send "admin-only" instead.`];
|
|
6083
3686
|
return value.flatMap((rule, index) => isRecord(rule) ? [] : [`${where}[${index}] must be a rule object.`]);
|
|
6084
3687
|
}
|
|
6085
|
-
/** Problems with a table-level option's value. */
|
|
6086
3688
|
function optionProblems(option, value, where) {
|
|
6087
3689
|
if (value === null) return [];
|
|
6088
3690
|
switch (option) {
|
|
@@ -6100,7 +3702,6 @@ function optionProblems(option, value, where) {
|
|
|
6100
3702
|
}
|
|
6101
3703
|
var isOptionKey = (value) => typeof value === "string" && TABLE_OPTION_KEYS.includes(value);
|
|
6102
3704
|
var isIndex = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
|
|
6103
|
-
/** The problems of one operation. */
|
|
6104
3705
|
function operationProblems(value, index) {
|
|
6105
3706
|
if (!isRecord(value)) return [{
|
|
6106
3707
|
index,
|
|
@@ -6171,7 +3772,7 @@ function operationProblems(value, index) {
|
|
|
6171
3772
|
if (!isRecord(spec)) return [{
|
|
6172
3773
|
index,
|
|
6173
3774
|
table: "",
|
|
6174
|
-
message: "`table` must be the description of the table to adopt, as `GET
|
|
3775
|
+
message: "`table` must be the description of the table to adopt, as `GET \u2026/unmapped-tables/:schema/:table` serves it."
|
|
6175
3776
|
}];
|
|
6176
3777
|
const name = typeof spec.slug === "string" ? spec.slug : "";
|
|
6177
3778
|
return adoptedTableProblems(spec).map((found) => ({
|
|
@@ -6226,13 +3827,6 @@ function operationProblems(value, index) {
|
|
|
6226
3827
|
default: return [problem(`\`op\` ${JSON.stringify(op)} is not a schema edit. Send one of createTable, adoptTable, deleteTable, addColumn, changeColumn, renameColumn, removeColumn, moveColumn, addRelation, changeRelation, removeRelation, setRls, addRule, replaceRule, removeRule, setOption.`)];
|
|
6227
3828
|
}
|
|
6228
3829
|
}
|
|
6229
|
-
/**
|
|
6230
|
-
* Every problem with a list of table edits as it arrived, in operation order.
|
|
6231
|
-
* Empty when the list is well formed — which says nothing about whether the
|
|
6232
|
-
* result compiles: the server compiles it before writing anything.
|
|
6233
|
-
*
|
|
6234
|
-
* @group Schema
|
|
6235
|
-
*/
|
|
6236
3830
|
function tablePatchProblems(value) {
|
|
6237
3831
|
if (!Array.isArray(value)) return [{
|
|
6238
3832
|
index: 0,
|
|
@@ -6246,30 +3840,13 @@ function tablePatchProblems(value) {
|
|
|
6246
3840
|
}];
|
|
6247
3841
|
return value.flatMap((operation, index) => operationProblems(operation, index));
|
|
6248
3842
|
}
|
|
6249
|
-
/**
|
|
6250
|
-
* Whether a value is a well-formed list of {@link TablePatch} operations.
|
|
6251
|
-
*
|
|
6252
|
-
* @group Schema
|
|
6253
|
-
*/
|
|
6254
3843
|
function isTablePatchList(value) {
|
|
6255
3844
|
return tablePatchProblems(value).length === 0;
|
|
6256
3845
|
}
|
|
6257
|
-
/**
|
|
6258
|
-
* A list of edits as it arrived, checked: the list, or a
|
|
6259
|
-
* {@link TablePatchError} naming every problem.
|
|
6260
|
-
*
|
|
6261
|
-
* @group Schema
|
|
6262
|
-
*/
|
|
6263
3846
|
function parseTablePatches(value) {
|
|
6264
3847
|
if (isTablePatchList(value)) return value;
|
|
6265
3848
|
throw new TablePatchError(tablePatchProblems(value));
|
|
6266
3849
|
}
|
|
6267
|
-
/**
|
|
6268
|
-
* The column definition a {@link WireColumnDef} stands for, the flags it left
|
|
6269
|
-
* out `false`.
|
|
6270
|
-
*
|
|
6271
|
-
* @group Schema
|
|
6272
|
-
*/
|
|
6273
3850
|
function columnDefFromWire(column) {
|
|
6274
3851
|
const { element, json, notNull, primaryKey, unique, readOnly, private: isPrivate, ...rest } = column;
|
|
6275
3852
|
const def = {
|
|
@@ -6284,7 +3861,6 @@ function columnDefFromWire(column) {
|
|
|
6284
3861
|
if (json !== void 0) def.json = json;
|
|
6285
3862
|
return def;
|
|
6286
3863
|
}
|
|
6287
|
-
/** Deep equality of JSON-like values: what a rule read from the wire is compared by. */
|
|
6288
3864
|
function sameValue(a, b) {
|
|
6289
3865
|
if (a === b) return true;
|
|
6290
3866
|
if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
|
|
@@ -6293,19 +3869,6 @@ function sameValue(a, b) {
|
|
|
6293
3869
|
const otherKeys = Object.keys(b).filter((key) => b[key] !== void 0);
|
|
6294
3870
|
return keys.length === otherKeys.length && keys.every((key) => sameValue(a[key], b[key]));
|
|
6295
3871
|
}
|
|
6296
|
-
/**
|
|
6297
|
-
* The rule operations that turn one list of rules into another, touching only
|
|
6298
|
-
* the rules that changed.
|
|
6299
|
-
*
|
|
6300
|
-
* A policy's name is a hash of its rule as written, so an editor that sends
|
|
6301
|
-
* the whole list back (one `setRls`) would rewrite every rule's text and risk
|
|
6302
|
-
* renaming policies it never changed. This pairs the lists by position: an
|
|
6303
|
-
* equal rule is left alone, a different one is replaced, a longer list adds
|
|
6304
|
-
* rules and a shorter one removes from the end. Positions are those of the
|
|
6305
|
-
* list as it is when each operation runs.
|
|
6306
|
-
*
|
|
6307
|
-
* @group Schema
|
|
6308
|
-
*/
|
|
6309
3872
|
function rulePatches(table, before, after) {
|
|
6310
3873
|
const out = [];
|
|
6311
3874
|
const shared = Math.min(before.length, after.length);
|
|
@@ -6329,6 +3892,6 @@ function rulePatches(table, before, after) {
|
|
|
6329
3892
|
return out;
|
|
6330
3893
|
}
|
|
6331
3894
|
//#endregion
|
|
6332
|
-
export { 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, COLUMN_BRAND, ColumnBuilder, DATA_PLANE_SCOPES, DEFAULT_CAPABILITIES, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, DEFAULT_FILTERABLE_RELATION_KINDS, DEFAULT_FUZZY_THRESHOLD, DEFAULT_LIST_LIMIT, DEFAULT_PUBLIC_RPC_RATE_LIMIT, DEFAULT_RESOURCE_KEY, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, DEFAULT_STATIC_REDIRECT_STATUS, DEFAULT_STORAGE_SOURCE_KEY, DEFAULT_TENANT_BYPASS_ROLES, DEFAULT_VECTOR_LIST_LIMIT, EMPTY_ACCESS_MODEL, FIELDLESS_AGGREGATES, FIELD_OPERATORS, FIREBASE_CAPABILITIES, IMPERSONATE_HEADER, INCLUDE_COUNT_KEY, JSON_FIELD_BRAND, JUNCTION_PIVOT_KEY, JsonField, KEY_MANAGEMENT_SCOPES, LEGACY_LAYOUT_REMEDY, LEGACY_RLS_JWT_SQL, LEGACY_RLS_ROLES_SQL, LEGACY_RLS_SCHEMA, LEGACY_RLS_UID_SQL, LEGACY_SCHEMA_VERSION_PREFIX, LIST_OPS, ListLimitError, MAX_IMPORTED_USER_ID_LENGTH, MAX_INCLUDE_DEPTH, MAX_LIST_LIMIT, MAX_USERS_PER_IMPORT, MCP_APP_MODULES, NULL_OPS, POLICY_EXPRESSION_KINDS, POSTGRES_CAPABILITIES, PUBLIC_STORAGE_PREFIX, REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE, REBASE_SCHEMA, RECOMMENDED_STORAGE_RULES, RELATION_BRAND, 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, RPC_BRAND, RUNTIME_CONTRACT_VERSION, RebaseApiError, RebaseClientError, SCHEMA_VERSION_HEADER, SCOPE_TARGETS, SIMULATED_CONTEXT_HEADER, SIMULATE_API_KEY_ID_HEADER, SIMULATE_ROLE_HEADER, SIMULATE_USER_ID_HEADER, STATIC_REDIRECT_STATUSES, STORAGE_REFERENCE_SCHEME, TABLE_BRAND, TABLE_OPTION_KEYS, TablePatchError, UI_PREFERENCE_FIELD_KEYS, UI_PREFERENCE_TABLE_KEYS, VIEW_BRAND, adminRequestRoleFor, aggregateAlias, aggregateGroupKey, amendResourceKind, bucket, buildResourceGraph, canonicalSchemaPayload, cleanUrlFor, col, columnDefFromWire, columnTypeLabel, compareStaticRoutes, compileStaticRedirects, computeSchemaVersion, database, declareCron, declareFunction, declareResource, declaredDataSources, declaredDatabaseExtensions, declaredDatabaseRls, declaredQueueConsumers, declaredResources, declaredRlsPolicyShape, declaredStorageSources, declaredSubscriptions, defineAuthTable, defineRpc, defineTable, defineView, describeJsonShape, describeScope, encodeRelationAggregateSort, envBasesForResource, findEnvSuffixCollision, findStorageSuffixCollision, formatSimulatedContext, getDataSourceCapabilities, hasAdminRole, hasFieldOperation, holdsAdminRole, importedUserIdProblem, intersectScopes, isAdminScope, isAnonymousUid, isAuthTableDef, isBranchAdmin, isBuiltInScope, isChannelBusInstance, isColumnBuilder, isContentHashedFileName, isDataPlaneScope, isFieldOperation, isJsonColumnType, isJsonField, isNumericColumnType, isPercentileFraction, isPolicyExpressionKind, isPolicyShorthand, isPublicStorageKey, isPublicStoragePath, isRedactedSecurityRule, isRelationAggregateSort, isRelationDef, isResourceHandle, isRpcDef, isSQLAdmin, isSchemaAdmin, isSchemaEditingAdmin, isSqlTemplate, isStaticRedirectStatus, isStorageReference, isTableDef, isTablePatchList, isTemporalColumnType, isTenantClaimSource, isTenantMembershipSource, isTextColumnType, isTimeZoneName, isUiTablePreferences, isUnsupported, isValidAppHost, isValidEngine, isViewDef, joinConditions, json, knownScopes, matchStaticRoute, mergeUiTablePreferences, normalizeColumnAccess, normalizeStorage, normalizeValidation, parseAppAddress, parseByteSize, parseCaseFoldedFieldPath, parseEnvBoolean, parseFrameAncestor, parseRelationAggregateSort, parseScope, parseSimulatedContext, parseStorageReference, parseTablePatches, pgEnum, policy, queue, registerDataSourceCapabilities, registerResourceKind, rel, reservedPrefixFor, resetDeclaredQueueConsumers, resetDeclaredResources, resetDeclaredSubscriptions, resolveClientListLimit, resolveResourceRefs, resolveStorageReferences, resourceEnvSuffix, resourceId, resourceKeyOf, resourceKind, resourceKinds, resourceToDataSource, resourceToStorageSource, rewriteLegacyRlsFunctions, roleNameProblem, rulePatches, scopeAcceptsTarget, scopeGrants, scopeGrantsAny, scopeTargets, scopesBeyond, scopesForRoles, setQueueRuntime, setTopicRuntime, simulationHeaders, soleJoinCondition, sortKeyToString, sql, storageEnvSuffix, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText, summarizeRoles, summarizeScopes, tablePatchProblems, toCanonicalOp, toDriverAggregate, toDriverAggregateGroup, topic, uiTablePreferencesProblems, unsupportedMethod, usesLegacyRlsFunctions, validateScopes, validateStaticRedirect, validateStaticRoute };
|
|
3895
|
+
export { 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, COLUMN_BRAND, ColumnBuilder, DATA_PLANE_SCOPES, DEFAULT_CAPABILITIES, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, DEFAULT_FILTERABLE_RELATION_KINDS, DEFAULT_FUZZY_THRESHOLD, DEFAULT_LIST_LIMIT, DEFAULT_PUBLIC_RPC_RATE_LIMIT, DEFAULT_RESOURCE_KEY, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, DEFAULT_STATIC_REDIRECT_STATUS, DEFAULT_STORAGE_SOURCE_KEY, DEFAULT_TENANT_BYPASS_ROLES, DEFAULT_VECTOR_LIST_LIMIT, EMPTY_ACCESS_MODEL, FIELDLESS_AGGREGATES, FIELD_OPERATORS, FIREBASE_CAPABILITIES, IMPERSONATE_HEADER, IMPORTED_PASSWORD_HASH_ALGORITHMS, INCLUDE_COUNT_KEY, JSON_FIELD_BRAND, JUNCTION_PIVOT_KEY, JsonField, KEY_MANAGEMENT_SCOPES, LEGACY_LAYOUT_REMEDY, LEGACY_RLS_JWT_SQL, LEGACY_RLS_ROLES_SQL, LEGACY_RLS_SCHEMA, LEGACY_RLS_UID_SQL, LEGACY_SCHEMA_VERSION_PREFIX, LIST_OPS, ListLimitError, MAX_IMPORTED_USER_ID_LENGTH, MAX_INCLUDE_DEPTH, MAX_LIST_LIMIT, MAX_USERS_PER_IMPORT, MCP_APP_MODULES, NULL_OPS, POLICY_EXPRESSION_KINDS, POSTGRES_CAPABILITIES, PUBLIC_STORAGE_PREFIX, REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE, REBASE_SCHEMA, RECOMMENDED_STORAGE_RULES, RELATION_BRAND, 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, RPC_BRAND, RUNTIME_CONTRACT_VERSION, RebaseApiError, RebaseClientError, SCHEMA_VERSION_HEADER, SCOPE_TARGETS, SIMULATED_CONTEXT_HEADER, SIMULATE_API_KEY_ID_HEADER, SIMULATE_ROLE_HEADER, SIMULATE_USER_ID_HEADER, STATIC_REDIRECT_STATUSES, STORAGE_REFERENCE_SCHEME, TABLE_BRAND, TABLE_OPTION_KEYS, TablePatchError, UI_PREFERENCE_FIELD_KEYS, UI_PREFERENCE_TABLE_KEYS, VIEW_BRAND, adminRequestRoleFor, aggregateAlias, aggregateGroupKey, amendResourceKind, bucket, buildResourceGraph, canonicalSchemaPayload, cleanUrlFor, col, columnDefFromWire, columnTypeLabel, compareStaticRoutes, compileStaticRedirects, computeSchemaVersion, database, declareCron, declareFunction, declareResource, declaredDataSources, declaredDatabaseExtensions, declaredDatabaseRls, declaredQueueConsumers, declaredResources, declaredRlsPolicyShape, declaredStorageSources, declaredSubscriptions, defineAuthTable, defineRpc, defineTable, defineView, describeJsonShape, describeScope, encodeRelationAggregateSort, envBasesForResource, findEnvSuffixCollision, findStorageSuffixCollision, formatSimulatedContext, getDataSourceCapabilities, hasAdminRole, hasFieldOperation, holdsAdminRole, importedPasswordHashProblem, importedUserIdProblem, intersectScopes, isAdminScope, isAnonymousUid, isAuthTableDef, isBranchAdmin, isBuiltInScope, isChannelBusInstance, isColumnBuilder, isContentHashedFileName, isDataPlaneScope, isFieldOperation, isJsonColumnType, isJsonField, isNumericColumnType, isPercentileFraction, isPolicyExpressionKind, isPolicyShorthand, isPublicStorageKey, isPublicStoragePath, isRedactedSecurityRule, isRelationAggregateSort, isRelationDef, isResourceHandle, isRpcDef, isSQLAdmin, isSchemaAdmin, isSchemaEditingAdmin, isSqlTemplate, isStaticRedirectStatus, isStorageReference, isTableDef, isTablePatchList, isTemporalColumnType, isTenantClaimSource, isTenantMembershipSource, isTextColumnType, isTimeZoneName, isUiTablePreferences, isUnsupported, isValidAppHost, isValidEngine, isViewDef, joinConditions, json, knownScopes, matchStaticRoute, mergeUiTablePreferences, normalizeColumnAccess, normalizeStorage, normalizeValidation, parseAppAddress, parseByteSize, parseCaseFoldedFieldPath, parseEnvBoolean, parseFrameAncestor, parseRelationAggregateSort, parseScope, parseSimulatedContext, parseStorageReference, parseTablePatches, pgEnum, policy, queue, registerDataSourceCapabilities, registerResourceKind, rel, reservedPrefixFor, resetDeclaredQueueConsumers, resetDeclaredResources, resetDeclaredSubscriptions, resolveClientListLimit, resolveResourceRefs, resolveStorageReferences, resourceEnvSuffix, resourceId, resourceKeyOf, resourceKind, resourceKinds, resourceToDataSource, resourceToStorageSource, rewriteLegacyRlsFunctions, roleNameProblem, rulePatches, scopeAcceptsTarget, scopeGrants, scopeGrantsAny, scopeTargets, scopesBeyond, scopesForRoles, setQueueRuntime, setTopicRuntime, simulationHeaders, soleJoinCondition, sortKeyToString, sql, storageEnvSuffix, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText, summarizeRoles, summarizeScopes, tablePatchProblems, toCanonicalOp, toDriverAggregate, toDriverAggregateGroup, topic, uiTablePreferencesProblems, unsupportedMethod, usesLegacyRlsFunctions, validateScopes, validateStaticRedirect, validateStaticRoute };
|
|
6333
3896
|
|
|
6334
3897
|
//# sourceMappingURL=index.es.js.map
|