@rebasepro/server 0.29.0-canary.g0e3a0e7 → 0.29.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/{GCSStorageController-Ch3Ridyt.js → GCSStorageController-BrIYwK-M.js} +2 -2
- package/dist/{GCSStorageController-Ch3Ridyt.js.map → GCSStorageController-BrIYwK-M.js.map} +1 -1
- package/dist/{S3StorageController-CmNMg7Gu.js → S3StorageController-BD2Y9fAu.js} +2 -2
- package/dist/{S3StorageController-CmNMg7Gu.js.map → S3StorageController-BD2Y9fAu.js.map} +1 -1
- package/dist/{access-BZjeLhf5.js → access-9uIagW6R.js} +5 -5
- package/dist/{access-BZjeLhf5.js.map → access-9uIagW6R.js.map} +1 -1
- package/dist/api/rest/query-parser.d.ts +13 -14
- package/dist/{ast-schema-editor-Dg7BWKE3.js → ast-schema-editor-CNfBLvr-.js} +2 -2
- package/dist/{ast-schema-editor-Dg7BWKE3.js.map → ast-schema-editor-CNfBLvr-.js.map} +1 -1
- package/dist/{auth-CSWKaSgJ.js → auth-Crf0K_Ex.js} +13 -5
- package/dist/auth-Crf0K_Ex.js.map +1 -0
- package/dist/{backup-woinIDjt.js → backup-Cu1Xss09.js} +6 -6
- package/dist/{backup-woinIDjt.js.map → backup-Cu1Xss09.js.map} +1 -1
- package/dist/{branch-routes-F5VIJrZp.js → branch-routes-XdCv4JwV.js} +2 -2
- package/dist/{branch-routes-F5VIJrZp.js.map → branch-routes-XdCv4JwV.js.map} +1 -1
- package/dist/{contract-routes-D8Vsxjx8.js → contract-routes-Dw-7TPpm.js} +2 -2
- package/dist/{contract-routes-D8Vsxjx8.js.map → contract-routes-Dw-7TPpm.js.map} +1 -1
- package/dist/{cron-loader-n9Uh_E1a.js → cron-loader-DIvfKXNc.js} +2 -2
- package/dist/{cron-loader-n9Uh_E1a.js.map → cron-loader-DIvfKXNc.js.map} +1 -1
- package/dist/{cron-routes-mLexIC9F.js → cron-routes-DU3iiBvf.js} +3 -3
- package/dist/{cron-routes-mLexIC9F.js.map → cron-routes-DU3iiBvf.js.map} +1 -1
- package/dist/{cron-scheduler-DhxuCDuI.js → cron-scheduler-BpZ7mPoi.js} +2 -2
- package/dist/{cron-scheduler-DhxuCDuI.js.map → cron-scheduler-BpZ7mPoi.js.map} +1 -1
- package/dist/{cron-store-DzKz7jXF.js → cron-store-DzgxrJB8.js} +2 -2
- package/dist/{cron-store-DzKz7jXF.js.map → cron-store-DzgxrJB8.js.map} +1 -1
- package/dist/data_driver-D0mg1Y_x.js.map +1 -1
- package/dist/dist-CwBjjwfY.js +19359 -0
- package/dist/dist-CwBjjwfY.js.map +1 -0
- package/dist/{field-access-CzKjatID.js → field-access-wcJeaL5H.js} +2 -2
- package/dist/{field-access-CzKjatID.js.map → field-access-wcJeaL5H.js.map} +1 -1
- package/dist/{filter-dialect-C5wfpopB.js → filter-dialect-FFhZoNGh.js} +2 -2
- package/dist/filter-dialect-FFhZoNGh.js.map +1 -0
- package/dist/{history-recorder-wkBuX7Np.js → history-recorder-B1j5i1ZT.js} +2 -2
- package/dist/{history-recorder-wkBuX7Np.js.map → history-recorder-B1j5i1ZT.js.map} +1 -1
- package/dist/index.es.js +100 -73
- package/dist/index.es.js.map +1 -1
- package/dist/jobs/job-queue.d.ts +10 -0
- package/dist/{jobs-D61qYEGt.js → jobs-CzFPOfp1.js} +4 -3
- package/dist/jobs-CzFPOfp1.js.map +1 -0
- package/dist/{jwt-CBmQXYs-.js → jwt-GIOW5uNd.js} +2 -2
- package/dist/{jwt-CBmQXYs-.js.map → jwt-GIOW5uNd.js.map} +1 -1
- package/dist/{keys-Cd_4l48g.js → keys-eRFGbaeH.js} +2 -2
- package/dist/{keys-Cd_4l48g.js.map → keys-eRFGbaeH.js.map} +1 -1
- package/dist/{offline-BjJdcVBb-B_bOcnDC.js → offline-Cy6woFyt-CTjHURuZ.js} +14 -5
- package/dist/offline-Cy6woFyt-CTjHURuZ.js.map +1 -0
- package/dist/{offline-store-Cxhh99Q--DQ-M1M8d.js → offline-store-C2Sy3Kwl-DFw34Y50.js} +16 -6
- package/dist/offline-store-C2Sy3Kwl-DFw34Y50.js.map +1 -0
- package/dist/{openapi-generator-B3LsKCon.js → openapi-generator-CzvnvC53.js} +4 -4
- package/dist/{openapi-generator-B3LsKCon.js.map → openapi-generator-CzvnvC53.js.map} +1 -1
- package/dist/{query-parser-C90z8csB.js → query-parser-B0HJPjPt.js} +135 -29
- package/dist/query-parser-B0HJPjPt.js.map +1 -0
- package/dist/{rls-simulator-routes-igGu-giT.js → rls-simulator-routes-77UrbME2.js} +3 -3
- package/dist/{rls-simulator-routes-igGu-giT.js.map → rls-simulator-routes-77UrbME2.js.map} +1 -1
- package/dist/{schema-editor-routes-kF1ZKCB2.js → schema-editor-routes-MSrmYTCh.js} +3 -3
- package/dist/{schema-editor-routes-kF1ZKCB2.js.map → schema-editor-routes-MSrmYTCh.js.map} +1 -1
- package/dist/{sql-export-routes-DObpbf8x.js → sql-export-routes-DAeT_WVm.js} +2 -2
- package/dist/{sql-export-routes-DObpbf8x.js.map → sql-export-routes-DAeT_WVm.js.map} +1 -1
- package/dist/{src-BXDkXOtq.js → src-DwcwNTsc.js} +11 -3
- package/dist/src-DwcwNTsc.js.map +1 -0
- package/package.json +5 -5
- package/dist/auth-CSWKaSgJ.js.map +0 -1
- package/dist/dist-B4YtgTMh.js +0 -19359
- package/dist/dist-B4YtgTMh.js.map +0 -1
- package/dist/filter-dialect-C5wfpopB.js.map +0 -1
- package/dist/jobs-D61qYEGt.js.map +0 -1
- package/dist/offline-BjJdcVBb-B_bOcnDC.js.map +0 -1
- package/dist/offline-store-Cxhh99Q--DQ-M1M8d.js.map +0 -1
- package/dist/query-parser-C90z8csB.js.map +0 -1
- package/dist/src-BXDkXOtq.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"offline-store-Cxhh99Q--DQ-M1M8d.js","names":["RebaseApiError$1"],"sources":["../../utils/dist/unref.es.js","../../common/src/data/row-etag.ts","../../client/dist/offline-store-Cxhh99Q-.js"],"sourcesContent":["//#region src/unref.ts\n/**\n* Release a Node handle's hold on the event loop, where the runtime has one.\n*\n* `unref` is Node's, not the web platform's. Node ref-counts the handles that\n* can keep a process alive — timers, `BroadcastChannel`, sockets — and gives\n* each an `unref()` that says \"you are still live, but do not be the reason\n* this process refuses to exit\". The browser's equivalents have no such method:\n* `setTimeout` there returns a plain number, and nothing is holding a page open\n* in the first place.\n*\n* So the call is genuinely conditional at runtime, in every package that runs\n* in both places. Spelled out at the call site it came to\n* `(handle as unknown as { unref?: () => void }).unref?.()` — a double cast,\n* because where the DOM declaration of `setTimeout` wins the handle is a\n* `number`, and `number` does not overlap an object type, so a single `as` is\n* refused. The `unknown` in the middle was there to make the refusal go away,\n* and it also discarded the check on the member's name and signature. There\n* were seven copies, which is seven chances to get one of those wrong.\n*\n* Takes `unknown` on purpose: the argument's type is exactly what is not known\n* here, and narrowing it to a timer would be a claim this cannot make about a\n* `BroadcastChannel`. A no-op on a browser handle, on `null`/`undefined`, and\n* on a Node timer that has already fired.\n*/\nfunction unref(handle) {\n\tif (handle === null || typeof handle !== \"object\") return;\n\tconst fn = handle.unref;\n\tif (typeof fn === \"function\") fn.call(handle);\n}\n//#endregion\nexport { unref };\n\n//# sourceMappingURL=unref.es.js.map","/**\n * A row's version — the `ETag` the read that produced it reported — kept on\n * the row without being part of it.\n *\n * @module\n */\n\n/**\n * Where a fetched row's version is kept.\n *\n * Non-enumerable, so it does not appear in `Object.keys`, in `JSON.stringify`,\n * in a spread into an update body, or in the generated `Row` type — a row's\n * version is a fact about the *response*, not a column, and putting it in the\n * row proper would mean the server having to strip it back off every write.\n *\n * A string key rather than a symbol so it survives the structured clone an\n * offline store or a worker boundary does… which it does not, and that is the\n * honest position: an etag is per-read, and a row that has been through a cache\n * has not been read from the server. `etagOf` answers `undefined` there, and a\n * conditional write without a tag is an unconditional one.\n */\nexport const ETAG_KEY = \"__etag\";\n\n/**\n * The version of a row, when it came straight from a read that reported one.\n *\n * ```ts\n * const post = await client.data.posts.get(1);\n * await client.data.posts.update(1, { title: \"New\" }, { ifMatch: etagOf(post) });\n * ```\n *\n * Set on a row from `findById()`/`get()`, from `update()`, and on every row\n * `listenById()` delivers (the SDK asks the server to tag each frame).\n * `undefined` for a row from `find()` (a list response carries one ETag at\n * most, and it would not be this row's), from the offline cache, or from a\n * server that does not send them. Passing `undefined` as `ifMatch` sends no\n * precondition, so the call above degrades to an ordinary update rather than\n * failing — which is the right default, and the reason to read this at the call\n * site where the choice is visible.\n */\nexport function etagOf(row: unknown): string | undefined {\n if (!row || typeof row !== \"object\") return undefined;\n const value = (row as Record<string, unknown>)[ETAG_KEY];\n return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Attach a version to a row without making it part of the row: a\n * non-enumerable `__etag`, so it stays out of `Object.keys`, a spread and\n * `JSON.stringify`, and a row copied through any of them has no tag — which\n * is right, since the copy was not read from the server.\n */\nexport function withETag<T>(row: T, etag: string | undefined): T {\n if (!etag || !row || typeof row !== \"object\") return row;\n Object.defineProperty(row, ETAG_KEY, {\n value: etag,\n enumerable: false,\n configurable: true,\n writable: true\n });\n return row;\n}\n","import { EntityReference, EntityRelation, GeoPoint, IMPERSONATE_HEADER, RebaseApiError, RebaseApiError as RebaseApiError$1, RebaseClientError, RebaseClientError as RebaseClientError$1, SCHEMA_VERSION_HEADER, Vector, isUnsupported, sortKeyToString, unsupportedMethod } from \"@rebasepro/types\";\nimport { RESERVED_QUERY_KEYS, collectAllPages, etagOf, mergeIncludeSpecs, normalizeOrderBy, paginateFind, resolveFindWindow, serializeFilter, serializeInclude, serializeLogicalCondition, serializeOrderBy, withETag } from \"@rebasepro/common\";\n//#region src/reviver.ts\nfunction rebaseReviver(_key, value) {\n\tif (value && typeof value === \"object\" && \"__type\" in value) {\n\t\tconst record = value;\n\t\tswitch (record.__type) {\n\t\t\tcase \"date\":\n\t\t\tcase \"Date\": {\n\t\t\t\tif (typeof record.value !== \"string\") return value;\n\t\t\t\tconst date = new Date(record.value);\n\t\t\t\treturn isNaN(date.getTime()) ? null : date;\n\t\t\t}\n\t\t\tcase \"reference\":\n\t\t\tcase \"EntityReference\": return new EntityReference({\n\t\t\t\tid: String(record.id),\n\t\t\t\tpath: record.path,\n\t\t\t\tdriver: record.driver,\n\t\t\t\tdatabaseId: record.databaseId\n\t\t\t});\n\t\t\tcase \"relation\":\n\t\t\tcase \"EntityRelation\": return new EntityRelation(record.id, record.path, record.data);\n\t\t\tcase \"GeoPoint\": return new GeoPoint(record.latitude, record.longitude);\n\t\t\tcase \"Vector\": return new Vector(record.value);\n\t\t\tdefault: return value;\n\t\t}\n\t}\n\treturn value;\n}\n/**\n* Could `text` hold an object with a `__type` key — the only values\n* {@link rebaseReviver} changes?\n*\n* A key is spelled either literally or with `\\u` escapes, so a body with\n* neither cannot contain one. The check is two substring scans, which run at\n* memory speed; a false positive only costs the walk below.\n*/\nfunction mayHoldTypedValues(text) {\n\treturn text.includes(\"\\\"__type\\\"\") || text.includes(\"\\\\u\");\n}\n/**\n* Set a property the way `JSON.parse`'s reviver does: as an own data property.\n* A plain assignment to a key named `__proto__` would call the setter and swap\n* the object's prototype instead.\n*/\nfunction setRevived(target, key, value) {\n\tif (key === \"__proto__\") Object.defineProperty(target, key, {\n\t\tvalue,\n\t\twritable: true,\n\t\tenumerable: true,\n\t\tconfigurable: true\n\t});\n\telse target[key] = value;\n}\n/**\n* {@link rebaseReviver}, applied bottom-up to an already parsed value, in\n* place: every child is revived before its parent, so a relation's `data` holds\n* its own revived values by the time the relation is built from it — the order\n* `JSON.parse` calls a reviver in. Primitives are never visited; the reviver\n* hands every one of them back unchanged.\n*/\nfunction reviveTree(value) {\n\tif (value === null || typeof value !== \"object\") return value;\n\tif (Array.isArray(value)) {\n\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\tconst item = value[i];\n\t\t\tif (item !== null && typeof item === \"object\") {\n\t\t\t\tconst revived = reviveTree(item);\n\t\t\t\tif (revived !== item) value[i] = revived;\n\t\t\t}\n\t\t}\n\t\treturn value;\n\t}\n\tconst record = value;\n\tfor (const key of Object.keys(record)) {\n\t\tconst item = record[key];\n\t\tif (item !== null && typeof item === \"object\") {\n\t\t\tconst revived = reviveTree(item);\n\t\t\tif (revived !== item) setRevived(record, key, revived);\n\t\t}\n\t}\n\treturn rebaseReviver(\"\", record);\n}\n/**\n* `JSON.parse(text, rebaseReviver)`, without the reviver's cost where it has\n* nothing to do.\n*\n* Handing `JSON.parse` a reviver takes V8 off its fast path and calls back for\n* every key and every value, primitives included: about 7× a plain parse on a\n* 1,000-row page, 10 ms of main thread per 600 KB. The reviver only ever\n* changes objects carrying `__type`, and a REST page of flat rows has none. So\n* this parses plainly and walks the result only when the text can hold one —\n* and the walk visits objects, never primitives.\n*\n* Same result, instance for instance: the same values revived, bottom-up, as\n* own data properties, and nothing deleted (the reviver never answers\n* `undefined`).\n*\n* @throws SyntaxError exactly where `JSON.parse` does.\n*/\nfunction parseRebaseJson(text) {\n\tconst parsed = JSON.parse(text);\n\tif (!mayHoldTypedValues(text)) return parsed;\n\treturn reviveTree(parsed);\n}\n//#endregion\n//#region src/transport.ts\n/**\n* True when there is no browser to have signed a user in — a Node script, a\n* cron job, an edge worker.\n*\n* Anonymous is an ordinary, correct state in a browser: before sign-in, on a\n* marketing page, for public reads. Warning there would be noise that teaches\n* people to ignore warnings, so the guard is off entirely. This uses the same\n* `typeof window` test as {@link resolveBaseUrl}, and additionally treats a\n* defined `document` as a browser so an SSR shim or test harness that installs\n* only one of the two is still excluded.\n*/\nfunction isServerLikeEnvironment() {\n\treturn typeof window === \"undefined\" && typeof document === \"undefined\";\n}\n/**\n* Emitted once per client. Kept as a constant so the wording is testable and\n* greppable — this is the string a user will paste into a search.\n*/\nvar ANONYMOUS_SERVER_CLIENT_WARNING = \"[rebase] This client was created outside a browser with no credential — no `token`, no auth token getter, and no cookie auth flow — so every request runs as an anonymous caller. Row-level security will return only publicly readable rows, which is usually nothing and occasionally the wrong thing. Inside a cron or function handler, use the `rebase` you were handed instead of building a new one: its data plane is already admin-scoped. In a standalone script or job, pass the service key as `token`. If you really do want anonymous access, pass `anonymous: true` to silence this.\";\n/**\n* Refuse a filter whose *value* is missing.\n*\n* `where: { status: [\"==\", undefined] }` used to serialize to the literal\n* string, so `status=eq.undefined` went out on the wire and the server dutifully\n* looked for rows whose status is the four-letter word \"undefined\". The caller\n* saw an empty page, not an error — the classic shape of a variable that was\n* never set.\n*\n* Dropping the condition instead would be worse than sending it: the query\n* would come back *unfiltered*, which for an ownership or tenant filter means\n* returning rows the caller never asked to see. So this is a hard error, and\n* both correct spellings are named in the message: omit the key to skip the\n* filter, or use `[\"is-null\", null]` to match SQL NULL (which still\n* serializes — `null` is a value, `undefined` is the absence of one).\n*/\nfunction assertNoUndefinedFilterValues(where) {\n\tconst reject = (field, op) => {\n\t\tthrow new RebaseClientError(`Filter on \"${field}\" has an undefined value ([\"${String(op)}\", undefined]). Omit \"${field}\" from \\`where\\` to skip the filter, or use [\"is-null\", null] to match SQL NULL.`, {\n\t\t\tcode: \"INVALID_FILTER\",\n\t\t\tdetails: {\n\t\t\t\tfield,\n\t\t\t\toperator: String(op)\n\t\t\t}\n\t\t});\n\t};\n\tfor (const [field, condition] of Object.entries(where)) {\n\t\tif (condition === void 0) continue;\n\t\tif (!Array.isArray(condition)) continue;\n\t\tconst tuples = Array.isArray(condition[0]) ? condition : [condition];\n\t\tfor (const tuple of tuples) {\n\t\t\tif (!Array.isArray(tuple) || tuple.length !== 2) continue;\n\t\t\tconst [op, value] = tuple;\n\t\t\tif (value === void 0) reject(field, op);\n\t\t\tif (Array.isArray(value) && value.some((v) => v === void 0)) reject(field, op);\n\t\t}\n\t}\n}\n/**\n* A find's parameters as `[name, value]` pairs, in the order the URL carries\n* them, values not yet URL-encoded.\n*\n* One list for both spellings of a listing: {@link buildQueryString} encodes it\n* into the `GET`'s URL, and {@link buildQueryBody} gathers it into the body of\n* `POST …/query`, which the server turns back into exactly these parameters.\n* Two serializers would be two chances to send a query one way and not the\n* other.\n*/\nfunction findParamPairs(params, deleted) {\n\tconst pairs = [];\n\tif (deleted) pairs.push([\"deleted\", deleted]);\n\tif (!params) return pairs;\n\tresolveFindWindow(params);\n\tif (params.limit != null) pairs.push([\"limit\", String(params.limit)]);\n\tif (params.offset != null) pairs.push([\"offset\", String(params.offset)]);\n\tif (params.page != null) pairs.push([\"page\", String(params.page)]);\n\tif (params.after) pairs.push([\"after\", params.after]);\n\tif (params.count === \"none\") pairs.push([\"count\", \"none\"]);\n\tif (params.orderBy) {\n\t\tconst wire = serializeOrderBy(params.orderBy);\n\t\tif (wire) pairs.push([\"orderBy\", wire]);\n\t}\n\tif (params.searchString) {\n\t\tpairs.push([\"searchString\", params.searchString]);\n\t\tif (params.searchExplain) pairs.push([\"searchExplain\", \"true\"]);\n\t}\n\tif (params.vectorSearch) {\n\t\tconst vs = params.vectorSearch;\n\t\tpairs.push([\"vector_search\", vs.property]);\n\t\tpairs.push([\"vector\", JSON.stringify(vs.vector)]);\n\t\tif (vs.distance) pairs.push([\"vector_distance\", vs.distance]);\n\t\tif (vs.threshold !== void 0) pairs.push([\"vector_threshold\", String(vs.threshold)]);\n\t}\n\tconst include = serializeInclude(params.include);\n\tif (include) pairs.push([\"include\", include]);\n\tif (params.fields && params.fields.length > 0) pairs.push([\"fields\", params.fields.join(\",\")]);\n\tif (params.distinct) pairs.push([\"distinct\", \"true\"]);\n\tif (params.logical) {\n\t\tconst root = params.logical;\n\t\tconst serialized = (root.conditions ?? []).map(serializeLogicalCondition).join(\",\");\n\t\tpairs.push([root.type, `(${serialized})`]);\n\t}\n\tif (params.where) appendWhere(pairs, params.where);\n\treturn pairs;\n}\nvar encodePairs = (pairs) => pairs.length > 0 ? \"?\" + pairs.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`).join(\"&\") : \"\";\nfunction buildQueryString(params, deleted) {\n\treturn encodePairs(findParamPairs(params, deleted));\n}\n/**\n* The body of `POST /data/<collection>/query`: the parameters\n* {@link buildQueryString} puts in the URL, spelled as the URL spells them —\n* each value a string, and a parameter the URL repeats (a filter with two\n* conditions on one field) a list of them. The server reads it back into the\n* same parameters and runs the same listing.\n*/\nfunction buildQueryBody(params, deleted) {\n\tconst body = {};\n\tfor (const [name, value] of findParamPairs(params, deleted)) {\n\t\tconst held = body[name];\n\t\tbody[name] = held === void 0 ? value : [...Array.isArray(held) ? held : [held], value];\n\t}\n\treturn body;\n}\n/**\n* Append a `where` to a query string, one `?<field>=<op>.<value>` parameter per\n* condition.\n*\n* Except on a column whose name the server reads as a parameter of its own —\n* `page`, `select`, `hard`, `where` ({@link RESERVED_QUERY_KEYS}). A filter on\n* such a column sent as its own parameter is read as that parameter, and the\n* filter is never applied. Those conditions go inside `?where=` instead, in the\n* same dot-string spelling, which the server decodes through the same codec and\n* merges in. A collection with no such column sends exactly what it did before.\n*/\nfunction appendWhere(pairs, where) {\n\tassertNoUndefinedFilterValues(where);\n\tconst serialized = serializeFilter(where);\n\tconst reserved = {};\n\tfor (const [field, value] of Object.entries(serialized)) {\n\t\tif (RESERVED_QUERY_KEYS.has(field)) {\n\t\t\treserved[field] = value;\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const v of Array.isArray(value) ? value : [value]) pairs.push([field, v]);\n\t}\n\tif (Object.keys(reserved).length > 0) pairs.push([\"where\", JSON.stringify(reserved)]);\n}\n/**\n* The query string for `GET /<collection>/aggregate`.\n*\n* `?select=sum(total),count()` is SQL's spelling, because whoever writes an\n* aggregate is thinking in SQL and any other spelling has to be learned first —\n* and because it is what the route already parses. The filters are serialised\n* by exactly the same code a `find()` uses, so \"revenue by status, this month\"\n* narrows the same rows whichever call is asking.\n*\n* `include` and a cursor are deliberately not here: an aggregate has no\n* relations to load and no row to continue after. `limit`, `offset` and\n* `orderBy` are, and page and sort the *groups* — `orderBy` by a group column or\n* an aggregate's alias, in the spelling a `find()` sends.\n*/\nfunction buildAggregateQueryString(params) {\n\tconst pairs = [];\n\tconst select = params.select.map((entry) => `${entry.fn}(${entry.field ?? \"\"})`).join(\",\");\n\tpairs.push([\"select\", select]);\n\tif (params.groupBy && params.groupBy.length > 0) pairs.push([\"groupBy\", params.groupBy.join(\",\")]);\n\tif (params.limit != null) pairs.push([\"limit\", String(params.limit)]);\n\tif (params.offset != null) pairs.push([\"offset\", String(params.offset)]);\n\tif (params.orderBy) {\n\t\tconst wire = serializeOrderBy(params.orderBy);\n\t\tif (wire) pairs.push([\"orderBy\", wire]);\n\t}\n\tif (params.searchString) pairs.push([\"searchString\", params.searchString]);\n\tif (params.logical) {\n\t\tconst root = params.logical;\n\t\tconst serialized = (root.conditions ?? []).map(serializeLogicalCondition).join(\",\");\n\t\tpairs.push([root.type, `(${serialized})`]);\n\t}\n\tif (params.where) appendWhere(pairs, params.where);\n\treturn encodePairs(pairs);\n}\n/**\n* The 401 codes that mean \"the credential on this request is no good\", which a\n* refreshed token can fix.\n*\n* The rest of the 401s are answers about something the caller *sent*: a wrong\n* current password (`INVALID_CREDENTIALS`), a mistyped MFA code (`INVALID_CODE`,\n* `CHALLENGE_EXHAUSTED`), a sign-in that needs a second factor\n* (`MFA_REQUIRED`). Refreshing and resending one of those rotated the session\n* for nothing, sent the same wrong answer twice — and an MFA challenge claims\n* an attempt before it judges the code, so every typo cost two of its five.\n*\n* `SESSION_REVOKED` and `ACCOUNT_DISABLED` are refusals of the session behind\n* the token. The refresh is refused the same way, which is what signs the\n* client out at once rather than at its next scheduled refresh.\n*/\nvar TOKEN_REFUSAL_CODES = /* @__PURE__ */ new Set([\n\t\"UNAUTHORIZED\",\n\t\"INVALID_TOKEN\",\n\t\"TOKEN_EXPIRED\",\n\t\"SESSION_REVOKED\",\n\t\"ACCOUNT_DISABLED\"\n]);\n/**\n* Whether a 401's body says the token was the problem.\n*\n* A 401 with no code at all counts: it is what an older server, a proxy or\n* anything not speaking the envelope sends, and there the token is the\n* likeliest cause — refreshing is what this client always did with it.\n*/\nfunction isTokenRefusal(body) {\n\tconst error = body?.error;\n\tconst code = error && typeof error === \"object\" ? error.code : void 0;\n\treturn typeof code !== \"string\" || code === \"\" || TOKEN_REFUSAL_CODES.has(code);\n}\n/**\n* The base every request and every caller-built URL resolves against.\n*\n* `baseUrl` is optional because the common production shape is a Rebase\n* backend serving its own SPA, where the API is simply the page's origin.\n* Leaving it unset is therefore the *correct* configuration there — and the\n* one that keeps working when a second hostname (a custom domain) points at\n* the same app.\n*\n* When unset in a browser this resolves to the page origin rather than \"\".\n* Requests behave identically either way, but the empty string is a trap for\n* anything that builds a URL from `client.baseUrl`: `new URL(\"\" + path)`\n* throws, so apps \"fixed\" it by baking an absolute host into their bundle —\n* which is exactly what breaks the day a custom domain is added, and which no\n* amount of CORS configuration repairs, because a SameSite=Lax auth cookie is\n* not sent cross-site either.\n*/\n/**\n* The code an error carries when the response did not name one: a proxy's 413,\n* a load balancer's 502, a crash page's 500 — anything without the server's\n* envelope. Without it `e.code` was `undefined` and the documented\n* `switch (e.code)` fell through to `default` on exactly the failures that are\n* not Rebase's own. Only codes the backend itself answers with, so a switch\n* written against the error reference catches both.\n*\n* @internal\n*/\nfunction defaultCodeForStatus(status) {\n\tswitch (status) {\n\t\tcase 400: return \"BAD_REQUEST\";\n\t\tcase 401: return \"UNAUTHORIZED\";\n\t\tcase 403: return \"FORBIDDEN\";\n\t\tcase 404: return \"NOT_FOUND\";\n\t\tcase 409: return \"CONFLICT\";\n\t\tcase 412: return \"PRECONDITION_FAILED\";\n\t\tcase 413: return \"PAYLOAD_TOO_LARGE\";\n\t\tcase 415: return \"UNSUPPORTED_MEDIA_TYPE\";\n\t\tcase 429: return \"RATE_LIMITED\";\n\t\tcase 502:\n\t\tcase 503:\n\t\tcase 504: return \"SERVICE_UNAVAILABLE\";\n\t\tdefault: return status >= 500 && status < 600 ? \"INTERNAL_ERROR\" : void 0;\n\t}\n}\nfunction resolveBaseUrl(configured) {\n\tif (configured) return configured.replace(/\\/$/, \"\");\n\tif (typeof window !== \"undefined\" && window.location?.origin) return window.location.origin;\n\treturn \"\";\n}\nfunction createTransport(config, environment) {\n\tconst rawFetch = config.fetch || globalThis.fetch;\n\t/**\n\t* `fetch`, but its rejection is a `RebaseApiError` like everything else\n\t* this client throws.\n\t*\n\t* A transport failure — DNS, a refused connection, CORS, an aborted\n\t* request — rejects with whatever the runtime's `fetch` felt like: a\n\t* `TypeError` reading \"Failed to fetch\" in a browser, a `TypeError` with a\n\t* `cause` in undici, a `DOMException` on abort. So the one class the SDK\n\t* documents as \"a `catch` block only ever needs to check for this\" did not\n\t* cover the most common failure of all, and `e.status` / `e.code` were\n\t* undefined on the error every app hits first: the server being down.\n\t*\n\t* `status: 0` rather than a made-up 5xx. There was no response, and 0 is\n\t* how `XMLHttpRequest` has always spelled that; a fabricated 503 would be\n\t* indistinguishable from one the server actually sent. The original error\n\t* is on `cause`, so nothing is hidden.\n\t*\n\t* Wrapped once, at construction, because the request path reads `fetchFn`\n\t* twice — the first attempt and the post-refresh retry — and a wrapper\n\t* applied at one call site is a wrapper missing from the other.\n\t*/\n\tconst fetchFn = async (input, init) => {\n\t\ttry {\n\t\t\treturn await rawFetch(input, init);\n\t\t} catch (e) {\n\t\t\tif (e instanceof RebaseApiError) throw e;\n\t\t\tconst url = typeof input === \"string\" ? input : String(input.url ?? input);\n\t\t\tif (!/^[a-z][a-z0-9+.-]*:/i.test(url) && typeof window === \"undefined\") throw new RebaseClientError(`This client has no \\`baseUrl\\`, and outside a browser the relative URL ${url} cannot be fetched. Pass \\`baseUrl\\` (e.g. \"http://localhost:3001\") to createRebaseClient().`, {\n\t\t\t\tcode: \"BASE_URL_REQUIRED\",\n\t\t\t\tcause: e\n\t\t\t});\n\t\t\tthrow new RebaseApiError(`Could not reach the server at ${url}: ${e instanceof Error ? e.message : String(e)}`, {\n\t\t\t\tstatus: 0,\n\t\t\t\tcode: \"NETWORK_ERROR\",\n\t\t\t\tcause: e\n\t\t\t});\n\t\t}\n\t};\n\tconst apiPath = config.apiPath || \"/api\";\n\tfor (const field of [\"baseUrl\", \"storageUrlOrigin\"]) {\n\t\tconst value = config[field];\n\t\tif (!value || !apiPath) continue;\n\t\tconst trimmed = value.replace(/\\/+$/, \"\");\n\t\tif (!trimmed.endsWith(apiPath)) continue;\n\t\tconsole.warn(`[Rebase] ${field} ${JSON.stringify(value)} already ends with the API path ${JSON.stringify(apiPath)}, which is appended to it — requests will go to ${trimmed}${apiPath}/… and 404. Pass the origin only (${JSON.stringify(trimmed.slice(0, trimmed.length - apiPath.length) || \"/\")}), or set \\`apiPath\\` if the server really does mount the API one level deeper.`);\n\t}\n\t/**\n\t* The token `setToken` last set — the auth module sets it on every sign-in,\n\t* refresh and sign-out — or, until anything has, `config.token`.\n\t*\n\t* `config.token` is read each time a token is needed rather than copied\n\t* here once, so a config that declares `token` as a getter hands over what\n\t* its source holds at that moment: the Rebase console lends its own,\n\t* background-refreshed session to a tenant client that way. The realtime\n\t* socket resolves its token through this transport, so the two read it\n\t* alike.\n\t*/\n\tlet setTokenValue;\n\tconst heldToken = () => setTokenValue ? setTokenValue.token : config.token;\n\tlet tokenGetter;\n\tlet tokenRefresher;\n\tlet onUnauthorizedHandler = config.onUnauthorized;\n\t/** Once per client, never per request — log spam is its own bug. */\n\tlet anonymousWarningIssued = false;\n\t/**\n\t* Warn a server-side caller that it built a client that can only ever be\n\t* anonymous. Deliberately checked at the *first request* rather than at\n\t* construction: `setToken()` / `setAuthTokenGetter()` and a server-side\n\t* `auth.signIn…()` (which calls `transport.setToken`) all land after the\n\t* constructor, and warning at construction would fire on every one of them.\n\t*/\n\tfunction warnIfAnonymousServerClient(activeToken) {\n\t\tif (anonymousWarningIssued) return;\n\t\tif (activeToken) return;\n\t\tif (tokenGetter) return;\n\t\tif (config.anonymous) return;\n\t\tif (environment?.credentialOutOfBand) return;\n\t\tif (!isServerLikeEnvironment()) return;\n\t\tanonymousWarningIssued = true;\n\t\tconsole.warn(ANONYMOUS_SERVER_CLIENT_WARNING);\n\t}\n\tconst defaultHeaders = {\n\t\t...config.headers ?? {},\n\t\t...config.schemaVersion ? { [SCHEMA_VERSION_HEADER]: config.schemaVersion } : {},\n\t\t...config.impersonate !== void 0 ? { [IMPERSONATE_HEADER]: config.impersonate } : {}\n\t};\n\tfunction getHeaders(activeToken, init) {\n\t\tconst headers = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t...defaultHeaders,\n\t\t\t...activeToken ? { Authorization: `Bearer ${activeToken}` } : {},\n\t\t\t...init?.headers || {}\n\t\t};\n\t\tif (init?.body instanceof FormData) delete headers[\"Content-Type\"];\n\t\treturn headers;\n\t}\n\t/**\n\t* The refusal for a success status carrying a body this client cannot read.\n\t*\n\t* The first 120 characters go in the message because they identify the\n\t* sender at a glance: `<!doctype html>` says \"you are talking to a web\n\t* server, not to this API\" faster than any wording here could.\n\t*\n\t* One function for both the first attempt and the post-refresh retry — the\n\t* retry is a second copy of this whole response-reading path, and copies\n\t* are how one of them ends up fixed and the other not.\n\t*/\n\tfunction unreadableResponse(status, text, contentType) {\n\t\tconst type = contentType?.split(\";\")[0].trim().toLowerCase() || \"\";\n\t\treturn new RebaseApiError(`The server answered ${status} with a body that is not JSON, so there is nothing to return. ${type !== \"\" && type !== \"text/html\" && !type.includes(\"json\") ? `The body is ${type}. If this is a custom function that answers text or a file, ask for it with \\`functions.invoke(name, payload, { responseType: \"text\" | \"blob\" | \"response\" })\\`.` : \"This usually means the request reached something other than the Rebase API — a single-page-app fallback serving index.html, or a proxy error page — so check the API URL configuration (e.g. VITE_API_URL).\"} The body began: ${JSON.stringify(text.slice(0, 120))}`, {\n\t\t\tstatus,\n\t\t\tcode: \"INVALID_JSON_RESPONSE\",\n\t\t\t...type ? { details: { contentType: type } } : {}\n\t\t});\n\t}\n\t/**\n\t* The server always emits the canonical\n\t* `{ error: { message, code, details?, requestId? } }` envelope (formatted\n\t* by the central `errorHandler`), so a field is read strictly from\n\t* `body.error.*` and never from the top level.\n\t*/\n\tfunction getErrorField(obj, field) {\n\t\tconst err = obj?.error;\n\t\tif (err && typeof err === \"object\" && err !== null) return err[field];\n\t}\n\t/**\n\t* `Retry-After` as whole seconds, or `undefined`.\n\t*\n\t* The header is either a number of seconds or an HTTP date; both spellings\n\t* are legal and servers use both, so both are read. A date in the past —\n\t* which happens on a clock skew — is clamped to 0 rather than negative.\n\t*/\n\tfunction parseRetryAfter(header) {\n\t\tif (!header) return void 0;\n\t\tconst seconds = Number(header.trim());\n\t\tif (Number.isFinite(seconds)) return Math.max(0, Math.floor(seconds));\n\t\tconst at = Date.parse(header);\n\t\tif (Number.isNaN(at)) return void 0;\n\t\treturn Math.max(0, Math.round((at - Date.now()) / 1e3));\n\t}\n\t/**\n\t* Everything a failed response says about itself, in one place.\n\t*\n\t* The request path reads a response twice — the first attempt and the\n\t* post-refresh retry — and the two used to build their error separately.\n\t* Which is how they came to disagree: both dropped `requestId` and\n\t* `Retry-After`, and a fix applied to one would have missed the other.\n\t*/\n\tfunction errorFrom(res, body, fallbackMessage) {\n\t\tconst requestId = getErrorField(body, \"requestId\") ?? res.headers?.get(\"X-Request-ID\") ?? void 0;\n\t\treturn new RebaseApiError(String(getErrorField(body, \"message\") || fallbackMessage || `Request failed with status ${res.status}`), {\n\t\t\tstatus: res.status,\n\t\t\tcode: getErrorField(body, \"code\") || defaultCodeForStatus(res.status),\n\t\t\tdetails: getErrorField(body, \"details\"),\n\t\t\t...typeof requestId === \"string\" && requestId ? { requestId } : {},\n\t\t\t...(() => {\n\t\t\t\tconst retryAfter = parseRetryAfter(res.headers?.get(\"Retry-After\") ?? null);\n\t\t\t\treturn retryAfter === void 0 ? {} : { retryAfterSeconds: retryAfter };\n\t\t\t})()\n\t\t});\n\t}\n\t/**\n\t* The token a request should carry: the getter's when one is installed,\n\t* otherwise the one held — or, when the token refresher says the held one\n\t* is spent, the one it hands back once its refresh lands.\n\t*/\n\tasync function tokenForRequest() {\n\t\tif (tokenGetter) {\n\t\t\ttry {\n\t\t\t\tconst fetched = await tokenGetter();\n\t\t\t\tif (fetched !== null && fetched !== void 0) return fetched;\n\t\t\t} catch (e) {}\n\t\t\treturn heldToken();\n\t\t}\n\t\tconst pending = tokenRefresher?.();\n\t\tif (pending) try {\n\t\t\tconst fresh = await pending;\n\t\t\tif (fresh) return fresh;\n\t\t} catch (e) {}\n\t\treturn heldToken();\n\t}\n\t/** The body as JSON, `{}` for none, `undefined` when it is there and is not JSON. */\n\tfunction parseBody(text) {\n\t\tif (!text) return {};\n\t\ttry {\n\t\t\treturn parseRebaseJson(text);\n\t\t} catch (e) {\n\t\t\treturn;\n\t\t}\n\t}\n\t/**\n\t* Send a request and hand back the response that answers it: the token\n\t* attached, a token refusal answered by one refresh and resend, and an\n\t* error status thrown as a {@link RebaseApiError}. The body of a success is\n\t* left unread, for the caller to read in whatever form it expects.\n\t*\n\t* One path for the first attempt and the post-refresh retry: the two used\n\t* to be separate copies of this whole sequence, and copies are how one of\n\t* them ends up fixed and the other not.\n\t*/\n\tasync function requestRaw(path, init, meta) {\n\t\tconst url = resolveBaseUrl(config.baseUrl) + apiPath + path;\n\t\tconst activeToken = await tokenForRequest();\n\t\twarnIfAnonymousServerClient(activeToken);\n\t\tlet res = await fetchFn(url, {\n\t\t\t...init,\n\t\t\theaders: getHeaders(activeToken, init)\n\t\t});\n\t\tlet readText;\n\t\tif (res.status === 401 && onUnauthorizedHandler) {\n\t\t\treadText = await res.text().catch(() => \"\");\n\t\t\tif (isTokenRefusal(parseBody(readText) ?? {})) {\n\t\t\t\tif (await onUnauthorizedHandler()) {\n\t\t\t\t\tlet retryToken = heldToken();\n\t\t\t\t\tif (tokenGetter) try {\n\t\t\t\t\t\tconst fetched = await tokenGetter();\n\t\t\t\t\t\tif (fetched !== null && fetched !== void 0) retryToken = fetched;\n\t\t\t\t\t} catch (e) {}\n\t\t\t\t\tres = await fetchFn(url, {\n\t\t\t\t\t\t...init,\n\t\t\t\t\t\theaders: getHeaders(retryToken, init)\n\t\t\t\t\t});\n\t\t\t\t\treadText = void 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (meta) {\n\t\t\tmeta.status = res.status;\n\t\t\tmeta.etag = res.headers?.get?.(\"ETag\") ?? void 0;\n\t\t\tmeta.headers = res.headers;\n\t\t}\n\t\tif (!res.ok) {\n\t\t\tconst text = readText ?? await res.text().catch(() => \"\");\n\t\t\tlet fallbackMessage = res.statusText;\n\t\t\tif (res.status === 404 && !fallbackMessage) fallbackMessage = `Endpoint not found (${init?.method || \"GET\"} ${path}). This usually means the collection is not registered on the backend, or the frontend API URL configuration (e.g. VITE_API_URL) is missing or pointing to the wrong host.`;\n\t\t\tthrow errorFrom(res, parseBody(text) ?? {}, fallbackMessage);\n\t\t}\n\t\treturn res;\n\t}\n\tasync function request(path, init, meta) {\n\t\tconst res = await requestRaw(path, init, meta);\n\t\tif (res.status === 204) return void 0;\n\t\tconst text = await res.text().catch(() => \"\");\n\t\t/**\n\t\t* `undefined` when the body was there and could not be read as JSON.\n\t\t*\n\t\t* On a *success* status that is the whole answer, and `{}` was being\n\t\t* returned as though the server had sent it: `find()` answered `{}`\n\t\t* instead of an array, `getOne()` an empty object, with nothing thrown.\n\t\t*\n\t\t* The case that produces it is not exotic. Point `VITE_API_URL` at the\n\t\t* frontend's own host and `/api/data/posts` lands on the SPA fallback,\n\t\t* which answers `200` with `index.html` — so the misconfiguration the\n\t\t* 404 message spends four lines explaining reaches the caller, in its\n\t\t* most common form, as an empty success.\n\t\t*/\n\t\tconst body = parseBody(text);\n\t\tif (body === void 0) throw unreadableResponse(res.status, text, res.headers?.get?.(\"Content-Type\") ?? null);\n\t\treturn body;\n\t}\n\treturn {\n\t\trequest,\n\t\trequestRaw,\n\t\tsetToken(newToken) {\n\t\t\tsetTokenValue = { token: newToken || void 0 };\n\t\t},\n\t\tsetAuthTokenGetter(getter) {\n\t\t\ttokenGetter = getter;\n\t\t},\n\t\tsetOnUnauthorized(handler) {\n\t\t\tonUnauthorizedHandler = handler;\n\t\t},\n\t\tsetTokenRefresher(refresher) {\n\t\t\ttokenRefresher = refresher ?? void 0;\n\t\t},\n\t\tget baseUrl() {\n\t\t\treturn resolveBaseUrl(config.baseUrl);\n\t\t},\n\t\tget apiPath() {\n\t\t\treturn apiPath;\n\t\t},\n\t\tget storageUrlOrigin() {\n\t\t\treturn config.storageUrlOrigin?.replace(/\\/$/, \"\") || void 0;\n\t\t},\n\t\tget fetchFn() {\n\t\t\treturn fetchFn;\n\t\t},\n\t\tgetHeaders: (init) => getHeaders(heldToken(), init),\n\t\tresolveToken: async () => await tokenForRequest() || null\n\t};\n}\n//#endregion\n//#region src/sdk_query_builder.ts\n/**\n* SDK Query Builder — returns flat rows (`FindResult<M>`) instead of\n* Entity-wrapped results (`FindResponse<M>`).\n*\n* @example\n* const { data } = await rebase.data.posts\n* .where(\"status\", \"==\", \"published\")\n* .orderBy(\"created_at\", \"desc\")\n* .limit(10)\n* .find();\n*\n* console.log(data[0].title); // flat access\n*/\nvar SDKQueryBuilder = class {\n\tcollection;\n\tparams = { where: {} };\n\tconstructor(collection) {\n\t\tthis.collection = collection;\n\t}\n\twhere(columnOrCondition, operator, value) {\n\t\tif (typeof columnOrCondition === \"object\" && columnOrCondition !== null && \"type\" in columnOrCondition) {\n\t\t\tconst next = columnOrCondition;\n\t\t\tthis.params.logical = this.params.logical ? {\n\t\t\t\ttype: \"and\",\n\t\t\t\tconditions: [this.params.logical, next]\n\t\t\t} : next;\n\t\t\treturn this;\n\t\t}\n\t\tif (!this.params.where) this.params.where = {};\n\t\tconst column = columnOrCondition;\n\t\tconst condition = [operator, value];\n\t\tconst existing = this.params.where[column];\n\t\tif (existing === void 0) this.params.where[column] = condition;\n\t\telse if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) this.params.where[column].push(condition);\n\t\telse {\n\t\t\tlet firstCondition;\n\t\t\tif (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === \"string\") firstCondition = existing;\n\t\t\telse firstCondition = [\"==\", existing];\n\t\t\tthis.params.where[column] = [firstCondition, condition];\n\t\t}\n\t\treturn this;\n\t}\n\t/**\n\t* Order the results by a specific column.\n\t*\n\t* Call it again to add a tie-breaker rather than replace the sort: keys\n\t* apply in the order they were added, so\n\t* `.orderBy(\"roles\").orderBy(\"created_at\", \"desc\")` sorts by role and\n\t* shows the newest first within each one.\n\t*/\n\torderBy(column, direction = \"asc\", nulls) {\n\t\tconst existing = normalizeOrderBy(this.params.orderBy) ?? [];\n\t\tconst key = sortKeyToString(column);\n\t\tthis.params.orderBy = [...existing, nulls ? [\n\t\t\tkey,\n\t\t\tdirection,\n\t\t\tnulls\n\t\t] : [key, direction]];\n\t\treturn this;\n\t}\n\t/**\n\t* Limit the number of results returned.\n\t*/\n\tlimit(count) {\n\t\tthis.params.limit = count;\n\t\treturn this;\n\t}\n\t/**\n\t* Skip the first N results.\n\t*/\n\toffset(count) {\n\t\tthis.params.offset = count;\n\t\treturn this;\n\t}\n\t/**\n\t* Set a free-text search string if supported by the backend.\n\t*\n\t* By default this is a substring match across the collection's top-level\n\t* string properties. A Postgres collection that declares a `search` block\n\t* gets ranked full-text matching over the fields it named instead, and each\n\t* row comes back with a `_score` you can sort on:\n\t*\n\t* ```ts\n\t* client.data.talents.search(\"auditor iso 14001\").orderBy(\"_score\", \"desc\").find()\n\t* ```\n\t*\n\t* Pass `{ explain: true }` to have each row report which of the declared\n\t* fields matched, with a highlighted snippet, on `_matches`:\n\t*\n\t* ```ts\n\t* const { data } = await client.data.talents.search(\"iso 14001\", { explain: true }).find();\n\t* data[0]._matches\n\t* // [{ field: \"questionnaire.certifications\", snippet: \"<mark>ISO</mark> <mark>14001</mark> Lead Auditor\" }]\n\t* ```\n\t*/\n\tsearch(searchString, options) {\n\t\tthis.params.searchString = searchString;\n\t\tif (options?.explain !== void 0) this.params.searchExplain = options.explain;\n\t\treturn this;\n\t}\n\t/**\n\t* Order rows by nearest-neighbour distance to `vector`.\n\t*\n\t* The server has supported this from the REST layer since vectors landed;\n\t* this is the SDK reaching it. Results come back closest-first with a\n\t* `_distance` on each row, and any `where` / `orderBy` on the same query is\n\t* a filter applied before the ordering — distance decides the order.\n\t*\n\t* You supply the query vector. Rebase stores and searches embeddings; it\n\t* does not produce them, so this is where whatever model you already use\n\t* for the stored vectors gets called.\n\t*\n\t* @param property - Name of the `vector` property to compare against.\n\t* @param vector - The query embedding. Its length must match the property's\n\t* declared `dimensions`, or the server answers 400.\n\t* @example\n\t* client.data.docs.vectorSearch(\"embedding\", queryVector, { threshold: 0.35 }).limit(10).find()\n\t*/\n\tvectorSearch(property, vector, options) {\n\t\tthis.params.vectorSearch = {\n\t\t\tproperty,\n\t\t\tvector,\n\t\t\t...options?.distance !== void 0 && { distance: options.distance },\n\t\t\t...options?.threshold !== void 0 && { threshold: options.threshold }\n\t\t};\n\t\treturn this;\n\t}\n\t/**\n\t* Load related rows into the response, in place of their foreign keys.\n\t*\n\t* Three spellings, all the same request:\n\t*\n\t* ```ts\n\t* client.data.posts.include(\"tags\", \"author\") // names\n\t* client.data.posts.include(\"comments.author\") // a dotted path\n\t* client.data.posts.include({ // parametrised\n\t* comments: {\n\t* limit: 5,\n\t* where: { published: [\"==\", true] },\n\t* orderBy: [\"created_at\", \"desc\"],\n\t* include: { author: true }\n\t* }\n\t* })\n\t* ```\n\t*\n\t* Up to three hops deep, and `\"*\"` still loads every relation one hop\n\t* deep. A name that is not a relation of the collection is a 400\n\t* `UNKNOWN_RELATION` — it used to be ignored, which answers 200 with the\n\t* field missing and reads exactly like a row that has no related row.\n\t*\n\t* Repeated calls **merge**: `.include(\"author\").include(\"tags\")` asks for\n\t* both. Assigning here — which is what it used to do — meant the second\n\t* call silently discarded the first.\n\t*/\n\tinclude(...relations) {\n\t\tthis.params.include = mergeIncludeSpecs(this.params.include, relations);\n\t\treturn this;\n\t}\n\t/**\n\t* Return only these columns.\n\t*\n\t* A projection at the database, not a trim of the response: a query that\n\t* needs two fields of a wide row reads two columns. The primary key always\n\t* comes back regardless — a row that cannot be addressed cannot be\n\t* updated, deleted or paged past — and `excludeFromApi` columns stay\n\t* hidden whether or not they are named.\n\t*/\n\tfields(...columns) {\n\t\tthis.params.fields = [...this.params.fields ?? [], ...columns];\n\t\treturn this;\n\t}\n\t/**\n\t* Collapse rows that are identical over the columns being returned.\n\t*\n\t* Only meaningful alongside {@link fields}: the primary key is always in\n\t* the projection, so without narrowing it every row is already distinct.\n\t*\n\t* ```ts\n\t* client.data.posts.fields(\"status\").distinct().find() // the statuses in use\n\t* ```\n\t*/\n\tdistinct(enabled = true) {\n\t\tthis.params.distinct = enabled;\n\t\treturn this;\n\t}\n\t/**\n\t* Continue after a previous page's `meta.nextCursor` — keyset paging.\n\t*\n\t* Unlike `offset`, a row inserted or deleted before the cursor cannot\n\t* shift the window, so a walk neither repeats nor skips rows. Keep\n\t* `orderBy` identical across pages: a cursor only continues the listing it\n\t* came from, and one used against a different sort is refused rather than\n\t* seeked in an order nobody asked for.\n\t*/\n\tafter(cursor) {\n\t\tthis.params.after = cursor;\n\t\treturn this;\n\t}\n\t/**\n\t* Execute the find query and return the results as flat rows.\n\t*/\n\tasync find() {\n\t\treturn this.collection.find(this.params);\n\t}\n\t/**\n\t* Aggregate the rows this query matches instead of returning them.\n\t*\n\t* The builder's `where`/`logical`/`search` narrow which rows are\n\t* aggregated; its `orderBy`, `include` and window do not apply — an\n\t* aggregate has no rows to sort, no relations to load and no page to\n\t* continue.\n\t*\n\t* ```ts\n\t* await client.data.orders\n\t* .where(\"created_at\", \">=\", startOfMonth)\n\t* .aggregate({ select: [{ fn: \"sum\", field: \"total\" }], groupBy: [\"status\"] });\n\t* // [{ status: \"paid\", sum_total: 41822.5 }, …]\n\t* ```\n\t*/\n\tasync aggregate(params) {\n\t\treturn this.collection.aggregate({\n\t\t\t...params,\n\t\t\twhere: this.params.where,\n\t\t\tlogical: this.params.logical,\n\t\t\tsearchString: this.params.searchString\n\t\t});\n\t}\n\t/**\n\t* Page through everything this query matches, one row at a time.\n\t*\n\t* `.limit()` on the builder becomes the page size, so the ceiling on a\n\t* single `find()` is not a ceiling on what the query can read.\n\t*/\n\titerate(options) {\n\t\treturn this.collection.iterate({\n\t\t\t...this.params,\n\t\t\t...this.params.limit !== void 0 && { pageSize: this.params.limit },\n\t\t\t...options\n\t\t});\n\t}\n\t/** Collect everything this query matches into one array. */\n\tfindAll(options) {\n\t\treturn this.collection.findAll({\n\t\t\t...this.params,\n\t\t\t...this.params.limit !== void 0 && { pageSize: this.params.limit },\n\t\t\t...options\n\t\t});\n\t}\n\t/**\n\t* Count the records matching this query.\n\t*/\n\tasync count() {\n\t\treturn this.collection.count(this.params);\n\t}\n\t/**\n\t* Listen to realtime updates matching this query.\n\t*\n\t* The guard that used to stand here — `if (!this.collection.listen) throw`\n\t* — has moved onto the client itself, which is where the same failure had\n\t* to be diagnosed anyway: `client.data.posts.listen(…)`, one call short of\n\t* this builder, answered `undefined is not a function`. The message is now\n\t* the same either way.\n\t*/\n\tlisten(onUpdate, onError) {\n\t\treturn this.collection.listen(this.params, onUpdate, onError);\n\t}\n};\n//#endregion\n//#region src/collection.ts\n/**\n* What `listen`/`listenById` say on a client that has no socket.\n*\n* One sentence, in one place: it used to live in `SDKQueryBuilder.listen` only,\n* so the same failure reached callers of `client.data.posts.listen` as\n* `undefined is not a function`.\n*/\nvar NO_SOCKET = \"Listen is only available when RebaseClient is configured with a websocketUrl, and not when it was created with realtime: false.\";\n/**\n* Why a live query cannot be opened for these parameters, or `undefined` when\n* it can.\n*\n* A `listen()` is the same query as the `find()` beside it, so what `find()`\n* refuses it refuses too. The socket would not: a frame is JSON, where an\n* `undefined` filter value becomes `null`, so `[\"!=\", uid]` with `uid` unset\n* subscribed to every row whose column is NOT NULL — an ownership filter\n* widened instead of refused. And `after` names a place in one run of the\n* query, which a subscription re-runs on every write; the server keeps no\n* cursor for one, so it was dropped, and page one streamed to a caller who had\n* asked for page two.\n*/\nfunction listenRefusal(params) {\n\tif (params?.where) try {\n\t\tassertNoUndefinedFilterValues(params.where);\n\t} catch (error) {\n\t\tif (error instanceof RebaseClientError) return error;\n\t\tthrow error;\n\t}\n\tif (params?.after) return new RebaseClientError(\"listen() cannot continue from a cursor: a subscription re-runs its query on every write, and `after` names a place in one run of it. Use `offset` or `page` for a live window, or `find({ after })` to read the page once.\", { code: \"CURSOR_NOT_LIVE\" });\n}\n/**\n* Counts currently in flight, **per client**, keyed by the exact request they\n* issue. Entries live only for the duration of the request — see `count()` for\n* why they exist at all.\n*\n* The map used to be module-level, shared by every client in the process. A\n* request key is a path and a query string: it says nothing about *who* is\n* asking. So two clients holding different credentials — an admin panel beside\n* a signed-in user's client, a per-request server client in a Node process, a\n* test asserting one client's calls — counting the same collection would share\n* one request, and whichever arrived second was answered with the first one's\n* total. Row-level security makes those genuinely different numbers.\n*\n* Keyed on the transport instead, which is the object a credential lives on.\n* A `WeakMap`, so a closed client's entry goes with it.\n*/\nvar inflightCounts = /* @__PURE__ */ new WeakMap();\n/** The in-flight map for one transport, created on first use. */\nfunction inflightCountsFor(transport) {\n\tlet map = inflightCounts.get(transport);\n\tif (!map) {\n\t\tmap = /* @__PURE__ */ new Map();\n\t\tinflightCounts.set(transport, map);\n\t}\n\treturn map;\n}\n/**\n* Transports whose server reads `?count=none` as a filter on a column named\n* `count`.\n*\n* Every server released before the parameter existed does, and answers a 400\n* `UNKNOWN_FILTER_FIELD` naming `count`. Skipping the count only ever saves\n* the server work, so a read refused for it is sent again without it, and\n* later reads through the same transport (one per client, so one server) stop\n* sending it. Membership is never cleared: a server does not lose the\n* parameter, and one that gains it in an upgrade gets it again on the next\n* page load.\n*/\nvar serversWithoutCountParam = /* @__PURE__ */ new WeakSet();\n/**\n* The longest URL a `find()` sends as a `GET`. Past it the parameters go in\n* the body of `POST /data/<collection>/query` instead.\n*\n* Not the server's own ceiling but the one in front of it: nginx refuses a\n* request line over 8 KB by default (414), and a proxy or CDN is in front of\n* most deployments. 6 KB leaves the rest of the request line, and the headers\n* some proxies count against the same buffer, room.\n*/\nvar MAX_FIND_URL_LENGTH = 6 * 1024;\n/**\n* Transports whose server has no `POST …/query` — every server before 0.24.\n*\n* Such a server answers the POST 404 (or a proxy 405), and the read is sent\n* again as the `GET` it has always been, which may well be refused for its\n* length: that refusal is the old server's answer, and the caller sees it.\n* Membership is never cleared, as for {@link serversWithoutCountParam}.\n*/\nvar serversWithoutQueryRoute = /* @__PURE__ */ new WeakSet();\n/** {@link serversWithoutQueryRoute}, for `POST …/count`. */\nvar serversWithoutCountRoute = /* @__PURE__ */ new WeakSet();\n/**\n* Whether a read goes as its `POST` twin rather than `GET`: always for a\n* vector search, whose embedding is a JSON array in the URL (768 dimensions\n* are 17 KB of it, past Node's 16 KB and nginx's 8 KB), and for anything else\n* whose URL would not fit through a proxy.\n*/\nfunction sendsQueryBody(transport, path, queryString, params, serversWithoutRoute) {\n\tif (serversWithoutRoute.has(transport)) return false;\n\tif (params?.vectorSearch) return true;\n\treturn `${transport.baseUrl ?? \"\"}${transport.apiPath ?? \"\"}${path}${queryString}`.length > MAX_FIND_URL_LENGTH;\n}\n/**\n* A read whose parameters go in the URL of `GET <path>`, or — where\n* {@link sendsQueryBody} says so — in the JSON body of its `POST` twin:\n* `POST …/query` for a listing, `POST …/count` for a count.\n*\n* Against a server without the twin (404, or a proxy's 405) the `GET` is sent\n* instead, and the transport remembers — unless the `GET` 404s as well, which\n* is the collection's answer, not the route's.\n*/\n/**\n* A success whose body is not the shape the method reads: no body at all (a\n* `204`, or a `200` with nothing in it), or JSON without the page's `data`\n* list. Usually a proxy or a route that is not the Rebase API answering. It\n* used to resolve as an empty page, or the row `{}`, or throw a bare\n* `TypeError` — none of which `switch (e.code)` could tell from a real answer.\n*/\nfunction unexpectedResponse(slug, method, status, expected) {\n\treturn new RebaseApiError$1(`${method} on \"${slug}\" got ${status === 204 ? \"a 204 with no body\" : `a ${status} without ${expected}`} from the server. This usually means something other than the Rebase API answered — a proxy, or a route outside the API — so check the API URL configuration.`, {\n\t\tstatus,\n\t\tcode: \"UNEXPECTED_RESPONSE\"\n\t});\n}\n/**\n* A bulk call given something other than an array. A `RebaseClientError` with\n* the code the server uses for the same mistake in a request body, so one\n* `case \"INVALID_BULK_BODY\"` covers both.\n*/\nfunction invalidBulkBody(message) {\n\treturn new RebaseClientError(message, { code: \"INVALID_BULK_BODY\" });\n}\nasync function readWithParams(transport, path, postPath, params, serversWithoutRoute, deleted) {\n\tconst queryString = buildQueryString(params, deleted);\n\tconst get = () => transport.request(path + queryString, { method: \"GET\" });\n\tif (!sendsQueryBody(transport, path, queryString, params, serversWithoutRoute)) return get();\n\ttry {\n\t\treturn await transport.request(postPath, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify(buildQueryBody(params, deleted))\n\t\t});\n\t} catch (error) {\n\t\tif (!(error instanceof RebaseApiError$1) || error.status !== 404 && error.status !== 405) throw error;\n\t\ttry {\n\t\t\tconst answer = await get();\n\t\t\tserversWithoutRoute.add(transport);\n\t\t\treturn answer;\n\t\t} catch (getError) {\n\t\t\tif (!(getError instanceof RebaseApiError$1 && getError.status === 404)) serversWithoutRoute.add(transport);\n\t\t\tthrow getError;\n\t\t}\n\t}\n}\nfunction isCountReadAsFilter(error) {\n\tif (!(error instanceof RebaseApiError$1) || error.status !== 400 || error.code !== \"UNKNOWN_FILTER_FIELD\") return false;\n\tconst details = error.details;\n\treturn typeof details === \"object\" && details !== null && \"field\" in details && details.field === \"count\";\n}\n/**\n* The headers a write's options ask for.\n*\n* One function rather than a spread at each call site: the three headers are\n* easy to add to one method and forget on the next, which is exactly how single\n* `PATCH` and `DELETE` came to send an `Idempotency-Key` the server never read\n* and `delete()` came to have no options at all.\n*/\nfunction writeHeaders(options) {\n\tconst headers = {};\n\tif (options?.idempotencyKey) headers[\"Idempotency-Key\"] = options.idempotencyKey;\n\tif (options?.ifMatch) headers[\"If-Match\"] = options.ifMatch;\n\tif (options?.returning === false) headers[\"Prefer\"] = \"return=minimal\";\n\treturn Object.keys(headers).length > 0 ? { headers } : void 0;\n}\n/** What `softDelete: true` names the field a delete stamps. */\nvar DEFAULT_SOFT_DELETE_FIELD = \"deletedAt\";\n/**\n* The part of {@link ObserveByIdOptions} that is a read option: `include`, and\n* nothing else, so `realtime` never travels as a query parameter.\n*/\nfunction byIdRead(options) {\n\treturn options?.include !== void 0 ? { include: options.include } : void 0;\n}\n/**\n* The bulk route names the row a failure came from — \"Row 0 of 1 (id 7)\n* failed: …\" — which is what a caller needs from a 10,000-row import and noise\n* from `upsert()`, which the caller wrote as one row and which only travels as\n* a one-row batch. Drops that prefix and nothing else: the error keeps its\n* class, status, code, details and cause. `createMany` does not call this.\n*/\nvar ONE_ROW_BULK_PREFIX = /^Row 0 of 1 \\(.*?\\) failed: /;\nfunction withoutBulkRowPrefix(error) {\n\tif (error instanceof Error && ONE_ROW_BULK_PREFIX.test(error.message)) error.message = error.message.replace(ONE_ROW_BULK_PREFIX, \"\");\n\treturn error;\n}\n/** Whether a URL path segment is `.` or `..`, percent-encoded or not. */\nfunction isDotSegment(segment) {\n\treturn /^(?:\\.|%2e){1,2}$/i.test(segment);\n}\n/**\n* A collection path as the URL path under `/data/`, refused when one of its\n* segments is `.` or `..`.\n*\n* The path may hold slashes (a nested collection), so it is not encoded whole,\n* and `fetch` resolves a dot segment before the request leaves: `../admin/users`\n* would read another route, as whoever this client is. The URL parser also\n* reads `\\` as `/` and drops tabs and newlines, so the path is split as it\n* will.\n*/\nfunction collectionPathSegment(slug) {\n\tif (slug.replace(/[\\t\\n\\r]/g, \"\").split(/[/\\\\]/).some(isDotSegment)) throw new RebaseClientError(`Invalid collection path ${JSON.stringify(slug)}: a \\`.\\` or \\`..\\` segment would leave /data.`, {\n\t\tcode: \"INVALID_COLLECTION_PATH\",\n\t\tdetails: { path: slug }\n\t});\n\treturn slug;\n}\n/**\n* A row id as one URL path segment. Encoded, which keeps a `/` or `?` inside\n* it; and refused when it is `.` or `..`, which encoding leaves as they are and\n* `fetch` resolves, moving the request up a level.\n*/\nfunction rowIdSegment(id) {\n\tconst segment = encodeURIComponent(String(id));\n\tif (isDotSegment(segment)) throw new RebaseClientError(`Invalid row id ${JSON.stringify(String(id))}: it would address the collection, not a row.`, {\n\t\tcode: \"INVALID_ID\",\n\t\tdetails: { id }\n\t});\n\treturn segment;\n}\nfunction createCollectionClient(transport, slug, ws) {\n\tconst basePath = `/data/${collectionPathSegment(slug)}`;\n\t/**\n\t* A listing — the live rows, or with `deleted` the trash's. One reader for\n\t* both, so the trash takes every parameter, and every fallback for an\n\t* older server, that `find()` does.\n\t*/\n\tasync function findRows(params, deleted) {\n\t\tconst method = deleted ? \"trash.find()\" : \"find()\";\n\t\tconst read = async (p) => {\n\t\t\tconst page = await readWithParams(transport, basePath, `${basePath}/query`, p, serversWithoutQueryRoute, deleted);\n\t\t\tif (!page || !Array.isArray(page.data)) throw unexpectedResponse(slug, method, page ? 200 : 204, \"a page with a `data` list\");\n\t\t\treturn page;\n\t\t};\n\t\tconst counted = {\n\t\t\t...params,\n\t\t\tcount: void 0\n\t\t};\n\t\tlet raw;\n\t\tif (params?.count !== \"none\") raw = await read(params);\n\t\telse if (serversWithoutCountParam.has(transport)) raw = await read(counted);\n\t\telse try {\n\t\t\traw = await read(params);\n\t\t} catch (error) {\n\t\t\tif (!isCountReadAsFilter(error)) throw error;\n\t\t\tserversWithoutCountParam.add(transport);\n\t\t\traw = await read(counted);\n\t\t}\n\t\treturn {\n\t\t\tdata: raw.data,\n\t\t\tmeta: raw.meta\n\t\t};\n\t}\n\t/** A count — of the live rows, or with `deleted` of the trash's. */\n\tasync function countRows(params, deleted) {\n\t\tconst countParams = {\n\t\t\t...params,\n\t\t\tlimit: void 0,\n\t\t\toffset: void 0,\n\t\t\tinclude: void 0,\n\t\t\tcount: void 0\n\t\t};\n\t\tconst qs = buildQueryString(countParams, deleted);\n\t\tconst key = basePath + \"/count\" + qs;\n\t\tconst inflight = inflightCountsFor(transport);\n\t\tconst existing = inflight.get(key);\n\t\tif (existing) return existing;\n\t\tconst request = readWithParams(transport, `${basePath}/count`, `${basePath}/count`, countParams, serversWithoutCountRoute, deleted).then((raw) => raw.count ?? 0);\n\t\tinflight.set(key, request);\n\t\ttry {\n\t\t\treturn await request;\n\t\t} finally {\n\t\t\tinflight.delete(key);\n\t\t}\n\t}\n\tconst restoreField = (options) => options?.field ?? DEFAULT_SOFT_DELETE_FIELD;\n\tconst client = {\n\t\tfind(params) {\n\t\t\treturn findRows(params);\n\t\t},\n\t\ttrash: {\n\t\t\tfind: (params) => findRows(params, \"only\"),\n\t\t\tcount: (params) => countRows(params, \"only\"),\n\t\t\trestore: (id, options) => client.update(id, { [restoreField(options)]: null }, options),\n\t\t\trestoreMany: (ids, options) => {\n\t\t\t\tif (!Array.isArray(ids)) return Promise.reject(invalidBulkBody(\"trash.restoreMany expects an array of ids.\"));\n\t\t\t\tconst data = { [restoreField(options)]: null };\n\t\t\t\treturn client.updateMany(ids.map((id) => ({\n\t\t\t\t\tid,\n\t\t\t\t\tdata\n\t\t\t\t})), options);\n\t\t\t},\n\t\t\tasync purge(id, options) {\n\t\t\t\tawait transport.request(`${basePath}/${rowIdSegment(id)}?hard=true`, {\n\t\t\t\t\tmethod: \"DELETE\",\n\t\t\t\t\t...writeHeaders(options)\n\t\t\t\t});\n\t\t\t},\n\t\t\tasync purgeMany(ids, options) {\n\t\t\t\tif (!Array.isArray(ids)) throw invalidBulkBody(\"trash.purgeMany expects an array of ids.\");\n\t\t\t\tif (ids.length === 0) return;\n\t\t\t\tawait transport.request(`${basePath}/bulk/delete?hard=true`, {\n\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\tbody: JSON.stringify({ ids }),\n\t\t\t\t\t...writeHeaders(options)\n\t\t\t\t});\n\t\t\t}\n\t\t},\n\t\titerate(params) {\n\t\t\treturn paginateFind((p) => client.find(p), params, slug);\n\t\t},\n\t\tfindAll(params) {\n\t\t\treturn collectAllPages((p) => client.find(p), params, slug);\n\t\t},\n\t\tasync findById(id, options) {\n\t\t\ttry {\n\t\t\t\tconst meta = {};\n\t\t\t\tconst raw = await transport.request(`${basePath}/${rowIdSegment(id)}${buildQueryString({ include: options?.include })}`, { method: \"GET\" }, meta);\n\t\t\t\tif (!raw) return void 0;\n\t\t\t\tif (Object.keys(raw).length === 0) throw unexpectedResponse(slug, \"findById()\", meta.status ?? 200, \"a row\");\n\t\t\t\treturn withETag(raw, meta.etag);\n\t\t\t} catch (err) {\n\t\t\t\tif (err instanceof RebaseApiError$1 && err.status === 404) return;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t},\n\t\tasync get(id) {\n\t\t\tconst row = await client.findById(id);\n\t\t\tif (row === void 0) throw new RebaseApiError$1(`No record with id ${JSON.stringify(String(id))} in \"${slug}\".`, {\n\t\t\t\tstatus: 404,\n\t\t\t\tcode: \"NOT_FOUND\"\n\t\t\t});\n\t\t\treturn row;\n\t\t},\n\t\tasync create(data, id, options) {\n\t\t\tconst body = { ...data };\n\t\t\tif (id !== void 0) body.id = id;\n\t\t\treturn await transport.request(basePath, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t...writeHeaders(options)\n\t\t\t});\n\t\t},\n\t\t/**\n\t\t* Insert, or replace the row already occupying the conflict target.\n\t\t*\n\t\t* One statement server-side (`INSERT ... ON CONFLICT DO UPDATE`), so\n\t\t* unlike a `findById` followed by `create`-or-`update` it cannot lose\n\t\t* the race between the two.\n\t\t*\n\t\t* Sent as a one-row bulk write with `upsert: true`, which is what the\n\t\t* in-process accessor and the offline queue already send. It used to be\n\t\t* `POST /data/<slug>` with `?on_conflict=` only when a target was\n\t\t* named — and the route reads that POST without the parameter as the\n\t\t* plain insert a `create` is, so the documented default (\"on the\n\t\t* primary key\") never happened online: re-upserting an existing row\n\t\t* answered 409, while the same call succeeded offline and in a\n\t\t* function.\n\t\t*/\n\t\tasync upsert(data, options) {\n\t\t\tconst raw = await transport.request(`${basePath}/bulk`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\trows: [data],\n\t\t\t\t\tupsert: true,\n\t\t\t\t\t...options?.onConflict?.length ? { onConflict: options.onConflict } : {}\n\t\t\t\t}),\n\t\t\t\t...writeHeaders(options)\n\t\t\t}).catch((error) => {\n\t\t\t\tthrow withoutBulkRowPrefix(error);\n\t\t\t});\n\t\t\treturn options?.returning === false ? void 0 : raw?.data?.[0];\n\t\t},\n\t\tasync createMany(data, options) {\n\t\t\tif (!Array.isArray(data)) throw invalidBulkBody(\"createMany expects an array of records.\");\n\t\t\tif (data.length === 0) return [];\n\t\t\tconst raw = await transport.request(`${basePath}/bulk`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\trows: data,\n\t\t\t\t\t...options?.upsert ? { upsert: true } : {},\n\t\t\t\t\t...options?.onConflict?.length ? { onConflict: options.onConflict } : {}\n\t\t\t\t}),\n\t\t\t\t...writeHeaders(options)\n\t\t\t});\n\t\t\tif (options?.returning === false) return [];\n\t\t\treturn raw.data || [];\n\t\t},\n\t\t/**\n\t\t* `PATCH`, the verb for a merge — `update(id, data: Partial<M>)` sends\n\t\t* only the keys the caller named and the server merges the rest.\n\t\t*\n\t\t* `PATCH` is the verb the OpenAPI spec names, so a spec-validating\n\t\t* gateway in front of the API sees the operation this sends. The\n\t\t* server also answers `PUT` on the same route, as a deprecated alias\n\t\t* marked `Deprecation: true` and left out of the spec; this client\n\t\t* never sends it.\n\t\t*/\n\t\tasync update(id, data, options) {\n\t\t\tconst meta = {};\n\t\t\treturn withETag(await transport.request(`${basePath}/${rowIdSegment(id)}`, {\n\t\t\t\tmethod: \"PATCH\",\n\t\t\t\tbody: JSON.stringify(data),\n\t\t\t\t...writeHeaders(options)\n\t\t\t}, meta), meta.etag);\n\t\t},\n\t\tasync updateMany(updates, options) {\n\t\t\tif (!Array.isArray(updates)) throw invalidBulkBody(\"updateMany expects an array of { id, data } entries.\");\n\t\t\tif (updates.length === 0) return [];\n\t\t\tconst raw = await transport.request(`${basePath}/bulk`, {\n\t\t\t\tmethod: \"PATCH\",\n\t\t\t\tbody: JSON.stringify({ updates }),\n\t\t\t\t...writeHeaders(options)\n\t\t\t});\n\t\t\tif (options?.returning === false) return [];\n\t\t\treturn raw.data || [];\n\t\t},\n\t\tasync delete(id, options) {\n\t\t\tawait transport.request(`${basePath}/${rowIdSegment(id)}`, {\n\t\t\t\tmethod: \"DELETE\",\n\t\t\t\t...writeHeaders(options)\n\t\t\t});\n\t\t},\n\t\t/**\n\t\t* `POST .../bulk/delete`, not `DELETE .../bulk`.\n\t\t*\n\t\t* The honest verb would take the ids in a DELETE body, and that is the\n\t\t* one request shape the HTTP ecosystem handles unreliably: bodies on\n\t\t* DELETE are permitted but widely dropped by proxies and CDNs, and\n\t\t* several OpenAPI generators ignore `requestBody` on a DELETE\n\t\t* operation, so a generated client would send the request without its\n\t\t* ids. A backend deployed behind arbitrary ingress cannot take that\n\t\t* bet. Same reason `:batchDelete` exists in Google's API guidelines.\n\t\t*/\n\t\tasync deleteMany(ids, options) {\n\t\t\tif (!Array.isArray(ids)) throw invalidBulkBody(\"deleteMany expects an array of ids.\");\n\t\t\tif (ids.length === 0) return;\n\t\t\tawait transport.request(`${basePath}/bulk/delete`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\tbody: JSON.stringify({ ids }),\n\t\t\t\t...writeHeaders(options)\n\t\t\t});\n\t\t},\n\t\tcount(params) {\n\t\t\treturn countRows(params);\n\t\t},\n\t\tobserve(params, onResult, onError, options) {\n\t\t\tlet closed = false;\n\t\t\tlet liveDelivered = false;\n\t\t\tlet signature;\n\t\t\tconst deliver = (result, fromLive) => {\n\t\t\t\tif (closed) return;\n\t\t\t\tif (fromLive) liveDelivered = true;\n\t\t\t\telse if (liveDelivered) return;\n\t\t\t\tconst next = `${result.meta?.total ?? \"\"}|${JSON.stringify(result.data)}`;\n\t\t\t\tif (signature !== void 0 && next === signature) return;\n\t\t\t\tsignature = next;\n\t\t\t\tonResult({\n\t\t\t\t\t...result,\n\t\t\t\t\tfromCache: false,\n\t\t\t\t\thasPendingWrites: false,\n\t\t\t\t\tpartial: false\n\t\t\t\t});\n\t\t\t};\n\t\t\tconst wantsLive = options?.realtime !== false && !isUnsupported(client.listen);\n\t\t\tconst refusal = wantsLive ? listenRefusal(params) : void 0;\n\t\t\tif (refusal) {\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\tif (!closed) onError?.(refusal);\n\t\t\t\t});\n\t\t\t\treturn () => {\n\t\t\t\t\tclosed = true;\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst live = wantsLive ? client.listen(params, (result) => deliver(result, true), onError) : void 0;\n\t\t\tif (!liveDelivered) client.find(params).then((result) => deliver(result, false)).catch((error) => {\n\t\t\t\tif (!closed) onError?.(error);\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tclosed = true;\n\t\t\t\tlive?.();\n\t\t\t};\n\t\t},\n\t\tobserveById(id, onResult, onError, options) {\n\t\t\tlet closed = false;\n\t\t\tlet liveDelivered = false;\n\t\t\tlet signature;\n\t\t\tconst deliver = (row, fromLive) => {\n\t\t\t\tif (closed) return;\n\t\t\t\tif (fromLive) liveDelivered = true;\n\t\t\t\telse if (liveDelivered) return;\n\t\t\t\tconst next = row === void 0 ? \"\\0missing\" : JSON.stringify(row);\n\t\t\t\tif (signature !== void 0 && next === signature) return;\n\t\t\t\tsignature = next;\n\t\t\t\tonResult(row, {\n\t\t\t\t\tfromCache: false,\n\t\t\t\t\thasPendingWrites: false\n\t\t\t\t});\n\t\t\t};\n\t\t\tconst live = options?.realtime !== false && !isUnsupported(client.listenById) ? client.listenById(id, (row) => deliver(row, true), onError, byIdRead(options)) : void 0;\n\t\t\tif (!liveDelivered) client.findById(id, byIdRead(options)).then((row) => deliver(row, false)).catch((error) => {\n\t\t\t\tif (!closed) onError?.(error);\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tclosed = true;\n\t\t\t\tlive?.();\n\t\t\t};\n\t\t},\n\t\twhere(columnOrCondition, operator, value) {\n\t\t\tconst builder = new SDKQueryBuilder(client);\n\t\t\tif (typeof columnOrCondition === \"object\") return builder.where(columnOrCondition);\n\t\t\treturn builder.where(columnOrCondition, operator, value);\n\t\t},\n\t\torderBy(column, direction, nulls) {\n\t\t\treturn new SDKQueryBuilder(client).orderBy(column, direction, nulls);\n\t\t},\n\t\tlimit(count) {\n\t\t\treturn new SDKQueryBuilder(client).limit(count);\n\t\t},\n\t\toffset(count) {\n\t\t\treturn new SDKQueryBuilder(client).offset(count);\n\t\t},\n\t\tsearch(searchString, options) {\n\t\t\treturn new SDKQueryBuilder(client).search(searchString, options);\n\t\t},\n\t\tvectorSearch(property, vector, options) {\n\t\t\treturn new SDKQueryBuilder(client).vectorSearch(property, vector, options);\n\t\t},\n\t\tinclude(...relations) {\n\t\t\treturn new SDKQueryBuilder(client).include(...relations);\n\t\t},\n\t\tfields(...columns) {\n\t\t\treturn new SDKQueryBuilder(client).fields(...columns);\n\t\t},\n\t\tdistinct(enabled) {\n\t\t\treturn new SDKQueryBuilder(client).distinct(enabled);\n\t\t},\n\t\tafter(cursor) {\n\t\t\treturn new SDKQueryBuilder(client).after(cursor);\n\t\t},\n\t\t/**\n\t\t* `count`/`sum`/`avg`/`min`/`max` over the matching rows, optionally\n\t\t* grouped — `GET /<collection>/aggregate`.\n\t\t*\n\t\t* The REST route has served this since aggregates landed and the SDK\n\t\t* had no method for it, so the only way to reach it from a typed client\n\t\t* was to hand-build the URL. `findAll()` and a reduce is the thing this\n\t\t* exists to replace: wrong under a `limit`, unaffordable without one.\n\t\t*/\n\t\tasync aggregate(params) {\n\t\t\tconst qs = buildAggregateQueryString(params);\n\t\t\tconst raw = await transport.request(`${basePath}/aggregate${qs}`, { method: \"GET\" });\n\t\t\tconst rows = raw.data || [];\n\t\t\tif (raw.meta) Object.defineProperty(rows, \"meta\", {\n\t\t\t\tvalue: raw.meta,\n\t\t\t\tenumerable: false\n\t\t\t});\n\t\t\treturn rows;\n\t\t},\n\t\tlisten: unsupportedMethod(NO_SOCKET),\n\t\tlistenById: unsupportedMethod(NO_SOCKET),\n\t\tlistenCount: unsupportedMethod(NO_SOCKET)\n\t};\n\tif (ws) {\n\t\tclient.listen = (params, onUpdate, onError) => {\n\t\t\tlet active = true;\n\t\t\tconst refusal = listenRefusal(params);\n\t\t\tif (refusal) {\n\t\t\t\tqueueMicrotask(() => {\n\t\t\t\t\tif (active) onError?.(refusal);\n\t\t\t\t});\n\t\t\t\treturn () => {\n\t\t\t\t\tactive = false;\n\t\t\t\t};\n\t\t\t}\n\t\t\tlet lastUpdateId = 0;\n\t\t\tlet lastKnownTotal;\n\t\t\tconst window = resolveFindWindow(params);\n\t\t\tconst unsub = ws.listenCollection({\n\t\t\t\tpath: slug,\n\t\t\t\tfilter: params?.where,\n\t\t\t\tlogical: params?.logical,\n\t\t\t\tlimit: params?.limit,\n\t\t\t\toffset: window.driverOffset,\n\t\t\t\tpage: params?.page,\n\t\t\t\tinclude: params?.include,\n\t\t\t\tfields: params?.fields,\n\t\t\t\tdistinct: params?.distinct,\n\t\t\t\torderBy: normalizeOrderBy(params?.orderBy),\n\t\t\t\tsearchString: params?.searchString,\n\t\t\t\tsearchExplain: params?.searchExplain,\n\t\t\t\tvectorSearch: params?.vectorSearch\n\t\t\t}, (incomingRows, frameMeta) => {\n\t\t\t\tconst currentUpdateId = ++lastUpdateId;\n\t\t\t\tconst requestedLimit = window.limit;\n\t\t\t\tconst offset = window.offset;\n\t\t\t\tconst rows = incomingRows;\n\t\t\t\tconst emit = (total, hasMore, nextCursor) => {\n\t\t\t\t\tif (!active || currentUpdateId !== lastUpdateId) return;\n\t\t\t\t\tonUpdate({\n\t\t\t\t\t\tdata: rows,\n\t\t\t\t\t\tmeta: {\n\t\t\t\t\t\t\ttotal,\n\t\t\t\t\t\t\tlimit: frameMeta?.limit ?? requestedLimit,\n\t\t\t\t\t\t\toffset: frameMeta?.offset ?? offset,\n\t\t\t\t\t\t\thasMore,\n\t\t\t\t\t\t\t...nextCursor && { nextCursor }\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t\tif (frameMeta && frameMeta.total !== void 0) {\n\t\t\t\t\tlastKnownTotal = frameMeta.total;\n\t\t\t\t\temit(frameMeta.total, frameMeta.hasMore, frameMeta.nextCursor);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (lastKnownTotal !== void 0) {\n\t\t\t\t\temit(lastKnownTotal, offset + rows.length < lastKnownTotal, frameMeta?.nextCursor);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tclient.count(params).then((total) => {\n\t\t\t\t\tlastKnownTotal = total;\n\t\t\t\t\temit(total, offset + rows.length < total, frameMeta?.nextCursor);\n\t\t\t\t}).catch(() => {\n\t\t\t\t\temit(offset + rows.length, rows.length >= requestedLimit, frameMeta?.nextCursor);\n\t\t\t\t});\n\t\t\t}, onError);\n\t\t\treturn () => {\n\t\t\t\tactive = false;\n\t\t\t\tunsub();\n\t\t\t};\n\t\t};\n\t\t/**\n\t\t* The count as a subscription of its own: `countOnly` asks the server\n\t\t* to read no rows. One that predates it reads the single row\n\t\t* `limit: 1` asks for and counts as usual, and the frame's `meta`\n\t\t* answers either way. One that sends no `meta` at all is asked with\n\t\t* `count()` on each frame instead.\n\t\t*/\n\t\tclient.listenCount = (params, onCount, onError) => {\n\t\t\tlet active = true;\n\t\t\tlet last;\n\t\t\tconst emit = (total) => {\n\t\t\t\tif (!active || total === last) return;\n\t\t\t\tlast = total;\n\t\t\t\tonCount(total);\n\t\t\t};\n\t\t\tconst unsub = ws.listenCollection({\n\t\t\t\tpath: slug,\n\t\t\t\tfilter: params?.where,\n\t\t\t\tlogical: params?.logical,\n\t\t\t\tsearchString: params?.searchString,\n\t\t\t\tlimit: 1,\n\t\t\t\tcountOnly: true\n\t\t\t}, (_rows, meta) => {\n\t\t\t\tif (typeof meta?.total === \"number\") emit(meta.total);\n\t\t\t\telse if (!meta) client.count(params).then(emit).catch((error) => {\n\t\t\t\t\tif (active) onError?.(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t});\n\t\t\t}, onError);\n\t\t\treturn () => {\n\t\t\t\tactive = false;\n\t\t\t\tunsub();\n\t\t\t};\n\t\t};\n\t\tclient.listenById = (id, onUpdate, onError, options) => {\n\t\t\treturn ws.listenOne({\n\t\t\t\tpath: slug,\n\t\t\t\tid: String(id),\n\t\t\t\t...options?.include !== void 0 ? { include: options.include } : {}\n\t\t\t}, (row) => {\n\t\t\t\tif (row) onUpdate(row);\n\t\t\t\telse onUpdate(void 0);\n\t\t\t}, onError);\n\t\t};\n\t}\n\treturn client;\n}\n//#endregion\n//#region src/offline-errors.ts\n/**\n* True when a read failed because there was neither network nor local data.\n*\n* The code is `OFFLINE`. It was `\"offline\"`, the one lowercase code in a\n* surface whose every other code is `SCREAMING_SNAKE_CASE` — including the\n* `NETWORK_ERROR` it sits next to — so `e.code === \"OFFLINE\"`, which is what\n* anyone writes, never matched.\n*/\nfunction isOfflineError(error) {\n\treturn error instanceof RebaseApiError$1 && error.code === \"OFFLINE\";\n}\n//#endregion\n//#region src/offline-store.ts\n/**\n* Monotonic within a tab, unique across tabs, and sortable as a plain string:\n* `<ms base36, padded>-<counter>-<random>`. The padding is what keeps\n* lexicographic order equal to chronological order, and the random suffix is\n* what stops two tabs from writing the same queue key in the same millisecond\n* — which would silently drop one of the two writes.\n*/\nvar mutationCounter = 0;\nfunction createMutationId(now = Date.now()) {\n\treturn `${now.toString(36).padStart(10, \"0\")}-${(mutationCounter = (mutationCounter + 1) % 1679616).toString(36).padStart(4, \"0\")}-${Math.random().toString(36).slice(2, 10).padStart(8, \"0\")}`;\n}\n/**\n* In-memory store: the default outside the browser and the workhorse of the\n* test suite. Values are deep-copied on the way in and out so a caller\n* mutating a returned row cannot silently edit the \"persisted\" copy — the\n* IndexedDB implementation gets the same guarantee for free from structured\n* cloning, and the two must not differ in aliasing behaviour.\n*/\nvar MemoryOfflineStore = class {\n\tcache = /* @__PURE__ */ new Map();\n\tqueue = /* @__PURE__ */ new Map();\n\tasync getCache(key) {\n\t\tconst entry = this.cache.get(key);\n\t\treturn entry ? structuredClone(entry) : void 0;\n\t}\n\tasync setCache(key, entry) {\n\t\tthis.cache.set(key, structuredClone(entry));\n\t}\n\tasync setCacheMany(entries) {\n\t\tfor (const { key, entry } of entries) this.cache.set(key, structuredClone(entry));\n\t}\n\tasync deleteCache(keys) {\n\t\tfor (const key of keys) this.cache.delete(key);\n\t}\n\tasync listCache(prefix) {\n\t\tconst out = [];\n\t\tfor (const [key, entry] of this.cache) if (key.startsWith(prefix)) out.push({\n\t\t\tkey,\n\t\t\tcachedAt: entry.cachedAt\n\t\t});\n\t\treturn out;\n\t}\n\tasync listCacheEntries(prefix) {\n\t\tconst out = [];\n\t\tfor (const [key, entry] of this.cache) if (key.startsWith(prefix)) out.push({\n\t\t\tkey,\n\t\t\t...structuredClone(entry)\n\t\t});\n\t\tout.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);\n\t\treturn out;\n\t}\n\tasync enqueue(key, mutation) {\n\t\tthis.queue.set(key, structuredClone(mutation));\n\t}\n\tasync dequeue(key) {\n\t\tthis.queue.delete(key);\n\t}\n\tasync listQueue(prefix) {\n\t\treturn [...this.queue.entries()].filter(([key]) => key.startsWith(prefix)).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([, mutation]) => structuredClone(mutation));\n\t}\n\tasync clear(prefix) {\n\t\tfor (const key of [...this.cache.keys()]) if (key.startsWith(prefix)) this.cache.delete(key);\n\t\tfor (const key of [...this.queue.keys()]) if (key.startsWith(prefix)) this.queue.delete(key);\n\t}\n};\nvar IDB_NAME = \"rebase-offline\";\n/**\n* v2 introduced the normalized row cache and string mutation ids. A v1\n* database holds whole-response blobs under keys this version cannot read and\n* queue entries ordered by a numeric `seq` this version no longer writes, so\n* the upgrade drops both stores rather than trying to translate them. Offline\n* support had not shipped in a release when v2 landed, so nothing in the wild\n* loses a queued write to this.\n*/\nvar IDB_VERSION = 2;\nvar CACHE_STORE = \"cache\";\nvar QUEUE_STORE = \"queue\";\n/** The exclusive upper bound of an IDBKeyRange covering every key under `prefix`. */\nfunction prefixRange(prefix) {\n\treturn IDBKeyRange.bound(prefix, prefix + \"\", false, false);\n}\nfunction requestToPromise(request) {\n\treturn new Promise((resolve, reject) => {\n\t\trequest.onsuccess = () => resolve(request.result);\n\t\trequest.onerror = () => reject(request.error ?? /* @__PURE__ */ new Error(\"IndexedDB request failed\"));\n\t});\n}\n/** Resolve when the whole transaction commits, not just when the last request returns. */\nfunction transactionDone(tx) {\n\treturn new Promise((resolve, reject) => {\n\t\ttx.oncomplete = () => resolve();\n\t\ttx.onabort = tx.onerror = () => reject(tx.error ?? /* @__PURE__ */ new Error(\"IndexedDB transaction failed\"));\n\t});\n}\n/**\n* IndexedDB-backed store — the browser default, so cached rows and queued\n* writes survive a reload or a browser restart. Everything lives in one\n* database with two object stores; keys are the manager's full prefixed\n* strings, so multiple users (scopes) share the database without ever\n* sharing entries.\n*/\nvar IndexedDBOfflineStore = class {\n\tdbPromise;\n\t/**\n\t* Where everything goes once the database turns out to belong to a newer\n\t* version of the SDK — see {@link backend}.\n\t*/\n\tfallback;\n\t/**\n\t* The database, or the in-memory stand-in when it cannot be opened at\n\t* this version.\n\t*\n\t* A tab still running an older build (a stale tab, a rolled-back deploy)\n\t* that opens a database a newer build upgraded gets a `VersionError` —\n\t* and every read and every write after it failed with an opaque\n\t* IndexedDB rejection, so the app went down instead of degrading. It now\n\t* works in memory for the life of the page, says so once, and leaves the\n\t* newer build's data alone.\n\t*/\n\tasync backend() {\n\t\tif (this.fallback) return this.fallback;\n\t\ttry {\n\t\t\treturn await this.open();\n\t\t} catch (error) {\n\t\t\tif (error?.name !== \"VersionError\") throw error;\n\t\t\tif (!this.fallback) {\n\t\t\t\tconsole.warn(\"[rebase offline] The offline database on this device was written by a newer version of the SDK. This page keeps its offline data in memory only, and leaves that database untouched; reload to pick up the newer version.\");\n\t\t\t\tthis.fallback = new MemoryOfflineStore();\n\t\t\t}\n\t\t\treturn this.fallback;\n\t\t}\n\t}\n\topen() {\n\t\tif (!this.dbPromise) this.dbPromise = new Promise((resolve, reject) => {\n\t\t\tconst request = indexedDB.open(IDB_NAME, IDB_VERSION);\n\t\t\trequest.onupgradeneeded = (event) => {\n\t\t\t\tconst db = request.result;\n\t\t\t\tif (event.oldVersion > 0 && event.oldVersion < 2) {\n\t\t\t\t\tif (db.objectStoreNames.contains(CACHE_STORE)) db.deleteObjectStore(CACHE_STORE);\n\t\t\t\t\tif (db.objectStoreNames.contains(QUEUE_STORE)) db.deleteObjectStore(QUEUE_STORE);\n\t\t\t\t}\n\t\t\t\tif (!db.objectStoreNames.contains(CACHE_STORE)) db.createObjectStore(CACHE_STORE);\n\t\t\t\tif (!db.objectStoreNames.contains(QUEUE_STORE)) db.createObjectStore(QUEUE_STORE);\n\t\t\t};\n\t\t\trequest.onsuccess = () => {\n\t\t\t\tconst db = request.result;\n\t\t\t\tdb.onversionchange = () => {\n\t\t\t\t\tdb.close();\n\t\t\t\t\tthis.dbPromise = void 0;\n\t\t\t\t};\n\t\t\t\tresolve(db);\n\t\t\t};\n\t\t\trequest.onerror = () => {\n\t\t\t\tthis.dbPromise = void 0;\n\t\t\t\treject(request.error ?? /* @__PURE__ */ new Error(\"Failed to open IndexedDB\"));\n\t\t\t};\n\t\t\trequest.onblocked = () => {\n\t\t\t\tthis.dbPromise = void 0;\n\t\t\t\treject(/* @__PURE__ */ new Error(\"IndexedDB upgrade blocked by another tab\"));\n\t\t\t};\n\t\t});\n\t\treturn this.dbPromise;\n\t}\n\tasync store(db, name, mode) {\n\t\treturn db.transaction(name, mode).objectStore(name);\n\t}\n\tasync getCache(key) {\n\t\tconst db = await this.backend();\n\t\tif (db instanceof MemoryOfflineStore) return db.getCache(key);\n\t\treturn await requestToPromise((await this.store(db, CACHE_STORE, \"readonly\")).get(key));\n\t}\n\tasync setCache(key, entry) {\n\t\tconst db = await this.backend();\n\t\tif (db instanceof MemoryOfflineStore) return db.setCache(key, entry);\n\t\tawait requestToPromise((await this.store(db, CACHE_STORE, \"readwrite\")).put(entry, key));\n\t}\n\tasync setCacheMany(entries) {\n\t\tif (entries.length === 0) return;\n\t\tconst db = await this.backend();\n\t\tif (db instanceof MemoryOfflineStore) return db.setCacheMany(entries);\n\t\tconst store = await this.store(db, CACHE_STORE, \"readwrite\");\n\t\tfor (const { key, entry } of entries) store.put(entry, key);\n\t\tawait transactionDone(store.transaction);\n\t}\n\tasync deleteCache(keys) {\n\t\tif (keys.length === 0) return;\n\t\tconst db = await this.backend();\n\t\tif (db instanceof MemoryOfflineStore) return db.deleteCache(keys);\n\t\tconst store = await this.store(db, CACHE_STORE, \"readwrite\");\n\t\tfor (const key of keys) store.delete(key);\n\t\tawait transactionDone(store.transaction);\n\t}\n\tasync listCache(prefix) {\n\t\tconst db = await this.backend();\n\t\tif (db instanceof MemoryOfflineStore) return db.listCache(prefix);\n\t\tconst store = await this.store(db, CACHE_STORE, \"readonly\");\n\t\tconst [keys, entries] = await Promise.all([requestToPromise(store.getAllKeys(prefixRange(prefix))), requestToPromise(store.getAll(prefixRange(prefix)))]);\n\t\treturn keys.map((key, i) => ({\n\t\t\tkey: String(key),\n\t\t\tcachedAt: entries[i]?.cachedAt ?? 0\n\t\t}));\n\t}\n\tasync listCacheEntries(prefix) {\n\t\tconst db = await this.backend();\n\t\tif (db instanceof MemoryOfflineStore) return db.listCacheEntries(prefix);\n\t\tconst store = await this.store(db, CACHE_STORE, \"readonly\");\n\t\tconst [keys, entries] = await Promise.all([requestToPromise(store.getAllKeys(prefixRange(prefix))), requestToPromise(store.getAll(prefixRange(prefix)))]);\n\t\treturn keys.map((key, i) => {\n\t\t\tconst entry = entries[i];\n\t\t\treturn {\n\t\t\t\tkey: String(key),\n\t\t\t\tvalue: entry?.value,\n\t\t\t\tcachedAt: entry?.cachedAt ?? 0\n\t\t\t};\n\t\t});\n\t}\n\tasync enqueue(key, mutation) {\n\t\tconst db = await this.backend();\n\t\tif (db instanceof MemoryOfflineStore) return db.enqueue(key, mutation);\n\t\tawait requestToPromise((await this.store(db, QUEUE_STORE, \"readwrite\")).put(mutation, key));\n\t}\n\tasync dequeue(key) {\n\t\tconst db = await this.backend();\n\t\tif (db instanceof MemoryOfflineStore) return db.dequeue(key);\n\t\tawait requestToPromise((await this.store(db, QUEUE_STORE, \"readwrite\")).delete(key));\n\t}\n\tasync listQueue(prefix) {\n\t\tconst db = await this.backend();\n\t\tif (db instanceof MemoryOfflineStore) return db.listQueue(prefix);\n\t\treturn await requestToPromise((await this.store(db, QUEUE_STORE, \"readonly\")).getAll(prefixRange(prefix)));\n\t}\n\tasync clear(prefix) {\n\t\tconst db = await this.backend();\n\t\tif (db instanceof MemoryOfflineStore) return db.clear(prefix);\n\t\tawait requestToPromise((await this.store(db, CACHE_STORE, \"readwrite\")).delete(prefixRange(prefix)));\n\t\tawait requestToPromise((await this.store(db, QUEUE_STORE, \"readwrite\")).delete(prefixRange(prefix)));\n\t}\n};\n//#endregion\nexport { byIdRead as a, invalidBulkBody as c, RebaseApiError$1 as d, buildQueryString as f, rebaseReviver as g, parseRebaseJson as h, isOfflineError as i, SDKQueryBuilder as l, defaultCodeForStatus as m, MemoryOfflineStore as n, createCollectionClient as o, createTransport as p, createMutationId as r, etagOf as s, IndexedDBOfflineStore as t, RebaseClientError$1 as u };\n\n//# sourceMappingURL=offline-store-Cxhh99Q-.js.map"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAS,MAAM,QAAQ;CACtB,IAAI,WAAW,QAAQ,OAAO,WAAW,UAAU;CACnD,MAAM,KAAK,OAAO;CAClB,IAAI,OAAO,OAAO,YAAY,GAAG,KAAK,MAAM;AAC7C;;;;;;;;;;;;;;;;;;;;;;;ACRA,IAAa,WAAW;;;;;;;;;;;;;;;;;;AAmBxB,SAAgB,OAAO,KAAkC;CACrD,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO,KAAA;CAC5C,MAAM,QAAS,IAAgC;CAC/C,OAA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9B;EACD,CAAC;CACF;CACA,MAAM,QAAQ,KAAK,UAAU;EAC5B,MAAM,KAAK,MAAM,KAAK,QAAQ;EAC9B,IAAI,cAAc,oBAAoB,OAAO,GAAG,QAAQ,KAAK,QAAQ;EACrE,MAAM,kBAAkB,MAAM,KAAK,MAAM,IAAI,aAAa,WAAW,EAAA,CAAG,IAAI,UAAU,GAAG,CAAC;CAC3F;CACA,MAAM,QAAQ,KAAK;EAClB,MAAM,KAAK,MAAM,KAAK,QAAQ;EAC9B,IAAI,cAAc,oBAAoB,OAAO,GAAG,QAAQ,GAAG;EAC3D,MAAM,kBAAkB,MAAM,KAAK,MAAM,IAAI,aAAa,WAAW,EAAA,CAAG,OAAO,GAAG,CAAC;CACpF;CACA,MAAM,UAAU,QAAQ;EACvB,MAAM,KAAK,MAAM,KAAK,QAAQ;EAC9B,IAAI,cAAc,oBAAoB,OAAO,GAAG,UAAU,MAAM;EAChE,OAAO,MAAM,kBAAkB,MAAM,KAAK,MAAM,IAAI,aAAa,UAAU,EAAA,CAAG,OAAO,YAAY,MAAM,CAAC,CAAC;CAC1G;CACA,MAAM,MAAM,QAAQ;EACnB,MAAM,KAAK,MAAM,KAAK,QAAQ;EAC9B,IAAI,cAAc,oBAAoB,OAAO,GAAG,MAAM,MAAM;EAC5D,MAAM,kBAAkB,MAAM,KAAK,MAAM,IAAI,aAAa,WAAW,EAAA,CAAG,OAAO,YAAY,MAAM,CAAC,CAAC;EACnG,MAAM,kBAAkB,MAAM,KAAK,MAAM,IAAI,aAAa,WAAW,EAAA,CAAG,OAAO,YAAY,MAAM,CAAC,CAAC;CACpG;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"query-parser-C90z8csB.js","names":[],"sources":["../../common/src/collections/unknown-field.ts","../../common/src/data/cursor.ts","../src/api/rest/field-access-query.ts","../src/api/rest/query-parser.ts"],"sourcesContent":["import type { CollectionConfig, Property } from \"@rebasepro/types\";\nimport { fieldKeyForColumn, findRelation, resolveCollectionRelations } from \"../util/relations\";\nimport { apiHiddenFieldNames } from \"./field-access\";\n\n/**\n * The answers a query gets for naming a field that does not exist — written\n * once, here, because two layers give them.\n *\n * The driver gives them for a typo. The REST check gives the same ones for a\n * field marked `excludeFromApi`: OpenAPI, `list_collections` and the generated\n * SDK all leave such a field out, so anything but the typo's answer — \"not\n * readable\", a different message, a list that names it — confirms it exists.\n * Both build the answer from these functions, so the two cannot drift apart by\n * a byte. Each returns the parts of the 400 (`message`, `code`, `details`) and\n * the caller wraps them in its own error type.\n *\n * @module\n */\n\nexport interface UnknownFieldAnswer {\n message: string;\n code: string;\n details: Record<string, unknown>;\n}\n\n/**\n * The fields an unknown-field answer offers as valid, sorted: what a query on\n * this collection can name as a column. A relation contributes its foreign key\n * (`authorId`) when the key is on this table, and nothing otherwise. An\n * `excludeFromApi` field is never offered.\n *\n * Read off the collection rather than the table, so the REST check — which\n * holds no table — lists exactly what the driver lists.\n */\nexport function queryableFieldNames(collection: CollectionConfig): string[] {\n const hidden = apiHiddenFieldNames(collection);\n const names = new Set<string>();\n let relations: ReturnType<typeof resolveCollectionRelations> | undefined;\n for (const [key, property] of Object.entries(collection.properties ?? {})) {\n if ((property as Property | undefined)?.type === \"relation\") {\n relations ??= resolveCollectionRelations(collection);\n const relation = findRelation(relations, key);\n if (relation?.kind === \"belongsTo\") names.add(fieldKeyForColumn(collection, relation.localKey));\n continue;\n }\n names.add(key);\n }\n return [...names].filter(name => !hidden.has(name)).sort();\n}\n\nconst validList = (validFields: string[]): string =>\n validFields.length > 0 ? `. Valid fields: ${validFields.join(\", \")}` : \"\";\n\n/** A filter key that resolves to nothing on `collectionPath`. */\nexport function unknownFilterField(field: string, collectionPath: string, validFields: string[]): UnknownFieldAnswer {\n return {\n message: `Unknown filter field '${field}' on collection '${collectionPath}'${validList(validFields)}`,\n code: \"UNKNOWN_FILTER_FIELD\",\n details: { field, collection: collectionPath, ...(validFields.length > 0 && { validFields }) }\n };\n}\n\n/** `author.emial` — a relation path whose last segment names nothing on the relation's target. */\nexport function unknownRelationTargetField(\n path: { field: string; relationKey: string; fieldKey: string },\n target: { slug: string; validFields: string[] },\n collectionPath: string\n): UnknownFieldAnswer {\n return {\n message: `Unknown field '${path.fieldKey}' on '${target.slug}', the target of relation ` +\n `'${path.relationKey}' on collection '${collectionPath}'${validList(target.validFields)}`,\n code: \"UNKNOWN_FILTER_FIELD\",\n details: {\n field: path.field,\n collection: collectionPath,\n relation: path.relationKey,\n targetCollection: target.slug,\n ...(target.validFields.length > 0 && { validFields: target.validFields })\n }\n };\n}\n\n/** An `orderBy` key that resolves to nothing. `collectionName` is absent when the read carries no collection. */\nexport function unknownOrderByField(orderBy: string, collectionName: string | undefined, validFields: string[]): UnknownFieldAnswer {\n const onCollection = collectionName ? ` on collection '${collectionName}'` : \"\";\n return {\n message: `Unknown orderBy field '${orderBy}'${onCollection}${validList(validFields)}`,\n code: \"UNKNOWN_ORDER_BY_FIELD\",\n details: {\n field: orderBy,\n ...(collectionName && { collection: collectionName }),\n ...(validFields.length > 0 && { validFields })\n }\n };\n}\n\n/** A `fields` entry that names nothing. */\nexport function unknownProjectionField(name: string, collectionName: string, validFields: string[]): UnknownFieldAnswer {\n return {\n message: `Unknown field '${name}' in \\`fields\\` on collection '${collectionName}'. Valid fields: ${validFields.join(\", \")}`,\n code: \"UNKNOWN_FIELD\",\n details: { field: name, collection: collectionName }\n };\n}\n\n/**\n * An `include` naming no relation of the collection. `validRelations` is what\n * the collection declares, never an `excludeFromApi` relation.\n */\nexport function unknownIncludeRelation(key: string, collectionName: string, validRelations: string[]): UnknownFieldAnswer {\n return {\n message: `Unknown relation '${key}' on collection '${collectionName}'`\n + (validRelations.length > 0\n ? `. Its relations are: ${validRelations.join(\", \")}`\n : \". It declares no relations.\"),\n code: \"UNKNOWN_RELATION\",\n details: { relation: key, collection: collectionName, ...(validRelations.length > 0 && { validRelations }) }\n };\n}\n\n/** The relations an unknown-relation answer offers, sorted — never an `excludeFromApi` one. */\nexport function includableRelationNames(collection: CollectionConfig): string[] {\n const hidden = apiHiddenFieldNames(collection);\n return Object.keys(resolveCollectionRelations(collection)).filter(key => !hidden.has(key)).sort();\n}\n\n/**\n * An aggregate's `select` field or `groupBy` key that names no column.\n * `forWhat` is where it was named: `sum()`, `count()`, `groupBy`.\n * `validFields` is {@link queryableFieldNames}, never an `excludeFromApi` field.\n */\nexport function unknownAggregateField(field: string, forWhat: string, validFields: string[]): UnknownFieldAnswer {\n return {\n message: `Unknown field '${field}' in ${forWhat}${validList(validFields)}`,\n code: \"UNKNOWN_AGGREGATE_FIELD\",\n details: { field, ...(validFields.length > 0 && { validFields }) }\n };\n}\n\n/**\n * The properties a `vector_search` can name, sorted: those declared\n * `{ type: \"vector\" }`, never an `excludeFromApi` one.\n */\nexport function vectorPropertyNames(collection: CollectionConfig): string[] {\n const hidden = apiHiddenFieldNames(collection);\n return Object.entries(collection.properties ?? {})\n .filter(([key, property]) => (property as Property | undefined)?.type === \"vector\" && !hidden.has(key))\n .map(([key]) => key)\n .sort();\n}\n\n/** A `vector_search` naming no vector property. `vectorProperties` is {@link vectorPropertyNames}. */\nexport function unknownVectorProperty(property: string, vectorProperties: string[]): UnknownFieldAnswer {\n return {\n message: `Unknown vector property \"${property}\". ` +\n (vectorProperties.length > 0\n ? `This collection's vector properties are: ${vectorProperties.join(\", \")}.`\n : \"This collection declares no `vector` property to search.\"),\n code: \"UNKNOWN_VECTOR_PROPERTY\",\n details: { property, ...(vectorProperties.length > 0 && { vectorProperties }) }\n };\n}\n","import { parseRelationAggregateSort, type OrderByTuple } from \"@rebasepro/types\";\n\n/**\n * The keyset-cursor wire codec.\n *\n * ## Why this is one module\n *\n * Keyset pagination was implemented three times and reachable once. The driver\n * has a NULL-correct multi-key comparison (`FetchService.buildKeysetComparison`)\n * that only a WebSocket `startAfter` could reach; REST could not seek at all;\n * and the SDK's `iterate({cursor})` re-implemented a *single*-column keyset as a\n * `where` clause, which threw on any multi-key sort and silently dropped rows\n * whose sort value was NULL. Three implementations, three answers to \"what is\n * page two\".\n *\n * There is now one. The driver's comparison is the implementation; this module\n * is the only thing that says how a cursor is written down, and every transport\n * — the REST `?after=`, the WebSocket `startAfter`, the SDK's `iterate()` —\n * carries the string this produces and hands it back unread.\n *\n * ## What a cursor holds\n *\n * The sort keys the query was ordered by, the last served row's value for each\n * of them, and that row's id. The keys travel *with* the values because a\n * cursor that carried only values would be silently reinterpretable: paging a\n * `created_at DESC` listing and then asking for `title ASC` would seek on the\n * dates as though they were titles. Carrying the keys makes that a refusal\n * ({@link CursorMismatchError}) rather than a page of arbitrary rows.\n *\n * ## Opacity\n *\n * The encoding is base64url of JSON, and it is **not** API. It is opaque so it\n * can change — adding a key, changing how a value is tagged — without every\n * client that learned to read it breaking. Nothing outside this file parses it.\n *\n * @module\n */\n\n/** The decoded contents of a cursor. */\nexport interface DecodedCursor {\n /** The sort keys the cursor was produced under, in order of significance. */\n orderBy: OrderByTuple[];\n /** The last served row's value for each sort key, by field name. */\n values: Record<string, unknown>;\n /** The last served row's id, which breaks ties on the last key. */\n id: unknown;\n}\n\n/** A cursor that cannot be read at all — truncated, re-encoded, or invented. */\nexport class CursorError extends Error {\n readonly code = \"INVALID_CURSOR\";\n constructor(detail: string) {\n super(\n `Invalid \\`after\\` cursor: ${detail}. Pass back the \\`meta.nextCursor\\` ` +\n \"from the previous page unchanged — it is opaque and must not be built by hand.\"\n );\n this.name = \"CursorError\";\n Object.setPrototypeOf(this, CursorError.prototype);\n }\n}\n\n/**\n * A cursor that reads fine but describes a different query.\n *\n * Separate from {@link CursorError} because the fix is different: this one is\n * not a corrupt string, it is a correct cursor used against a sort it was not\n * produced under. Seeking anyway would return rows in an order nobody asked\n * for, and — worse — would look like it worked.\n */\nexport class CursorMismatchError extends Error {\n readonly code = \"CURSOR_ORDER_MISMATCH\";\n constructor(cursorKeys: string[], queryKeys: string[]) {\n super(\n `The \\`after\\` cursor was produced by a query ordered by ` +\n `${cursorKeys.map(k => `\"${k}\"`).join(\", \") || \"(nothing)\"}, but this query orders by ` +\n `${queryKeys.map(k => `\"${k}\"`).join(\", \") || \"(nothing)\"}. A cursor only continues the ` +\n \"listing it came from — keep `orderBy` identical across pages, or drop `after` to start over.\"\n );\n this.name = \"CursorMismatchError\";\n Object.setPrototypeOf(this, CursorMismatchError.prototype);\n }\n}\n\n/**\n * Tag for a value whose JSON round-trip would otherwise lose its type.\n *\n * A `timestamp` column comes back from the driver as a `Date`; JSON turns it\n * into a string, and the string would then be compared against the column by\n * whatever cast Postgres chose. Round-tripping it as a `Date` keeps the\n * comparison the one the ORDER BY made.\n */\nconst DATE_TAG = \"$date\";\n\nfunction encodeValue(value: unknown): unknown {\n if (value instanceof Date) return { [DATE_TAG]: value.toISOString() };\n return value;\n}\n\nfunction decodeValue(value: unknown): unknown {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n const tagged = (value as Record<string, unknown>)[DATE_TAG];\n if (typeof tagged === \"string\") {\n const date = new Date(tagged);\n return Number.isNaN(date.getTime()) ? tagged : date;\n }\n }\n return value;\n}\n\n/** base64url, without depending on Node's Buffer (this package runs in browsers). */\nfunction toBase64Url(text: string): string {\n const bytes = new TextEncoder().encode(text);\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction fromBase64Url(encoded: string): string {\n const padded = encoded.replace(/-/g, \"+\").replace(/_/g, \"/\")\n + \"=\".repeat((4 - (encoded.length % 4)) % 4);\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Encode \"everything strictly after this row, in this order\".\n *\n * @param orderBy the sort keys the listing ran under, in order of significance\n * @param row the last row served, which the next page picks up after\n * @param id that row's id — the tiebreaker every keyset comparison ends on\n * @returns the opaque cursor, or `undefined` when no cursor can describe the\n * page. That is not a failure: a listing sorted by relevance has no stored\n * value to compare a later page against (scores are computed per query and\n * are not on the same scale between two of them), so it pages by offset and\n * `meta.nextCursor` is simply absent.\n */\nexport function encodeCursor(\n orderBy: OrderByTuple[] | undefined,\n row: Record<string, unknown>,\n id: unknown\n): string | undefined {\n if (id === undefined || id === null) return undefined;\n const keys = orderBy ?? [];\n // A key whose value is not on the row cannot be seeked past. Rather than\n // emit a cursor that the next request would refuse, emit none — the caller\n // falls back to offset paging, which is what it did before cursors existed.\n //\n // An aggregate over a relation (`count(orders)`) is the exception: it is\n // never on the row, and it needs no value here, because the keyset\n // comparison recomputes the cursor row's value in SQL from the id.\n // Refusing it withheld the cursor from every such listing.\n const values: Record<string, unknown> = {};\n for (const [field] of keys) {\n if (field in row) {\n values[field] = encodeValue(row[field]);\n continue;\n }\n if (parseRelationAggregateSort(field)) continue;\n return undefined;\n }\n return toBase64Url(JSON.stringify({ k: keys, v: values, i: encodeValue(id) }));\n}\n\n/**\n * Read a cursor produced by {@link encodeCursor}.\n *\n * @throws {CursorError} when the string is not a cursor this codec wrote.\n */\nexport function decodeCursor(raw: string): DecodedCursor {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fromBase64Url(raw.trim()));\n } catch {\n throw new CursorError(\"it is not a cursor this API issued\");\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CursorError(\"it does not decode to a cursor\");\n }\n const body = parsed as { k?: unknown; v?: unknown; i?: unknown };\n if (!Array.isArray(body.k)) throw new CursorError(\"it carries no sort keys\");\n if (body.i === undefined) throw new CursorError(\"it carries no row id\");\n\n const orderBy: OrderByTuple[] = [];\n for (const entry of body.k) {\n if (!Array.isArray(entry) || typeof entry[0] !== \"string\") {\n throw new CursorError(\"one of its sort keys is malformed\");\n }\n const direction = entry[1] === \"desc\" ? \"desc\" : \"asc\";\n orderBy.push(entry[2] === \"first\" || entry[2] === \"last\"\n ? [entry[0], direction, entry[2]]\n : [entry[0], direction]);\n }\n\n const rawValues = (body.v && typeof body.v === \"object\" && !Array.isArray(body.v))\n ? body.v as Record<string, unknown>\n : {};\n const values: Record<string, unknown> = {};\n for (const [field, value] of Object.entries(rawValues)) values[field] = decodeValue(value);\n\n return { orderBy, values, id: decodeValue(body.i) };\n}\n\n/**\n * The `orderBy` a request should run under, given a cursor and whatever sort\n * the request itself named.\n *\n * A request that names no sort **adopts the cursor's** — that is what makes\n * `find({ after })` work without restating the `orderBy` from the previous\n * call, and it cannot be wrong, since the cursor is the only sort in play.\n * A request that names one must name the *same* one, key for key, direction for\n * direction, nulls for nulls; anything else is {@link CursorMismatchError}.\n *\n * @throws {CursorMismatchError}\n */\nexport function reconcileCursorOrder(\n cursor: DecodedCursor,\n requested: OrderByTuple[] | undefined\n): OrderByTuple[] {\n if (!requested || requested.length === 0) return cursor.orderBy;\n const spell = (keys: OrderByTuple[]) =>\n keys.map(([field, direction, nulls]) => `${field}:${direction}${nulls ? `:${nulls}` : \"\"}`);\n const cursorKeys = spell(cursor.orderBy);\n const queryKeys = spell(requested);\n if (cursorKeys.length !== queryKeys.length\n || cursorKeys.some((key, i) => key !== queryKeys[i])) {\n throw new CursorMismatchError(cursorKeys, queryKeys);\n }\n return requested;\n}\n\n/**\n * The `startAfter` shape the driver contract takes, built from a cursor.\n *\n * The driver has always accepted `{ id, values }`; this is the one place that\n * shape is produced, so the REST route and the WebSocket ingress cannot drift\n * into two spellings of the same seek.\n */\nexport function cursorToStartAfter(cursor: DecodedCursor): Record<string, unknown> {\n return { id: cursor.id, values: cursor.values };\n}\n","import type { CollectionConfig, IncludeSpec } from \"@rebasepro/types\";\nimport { type FilterCondition, type LogicalCondition, parseRelationAggregateSort } from \"@rebasepro/types\";\nimport {\n apiHiddenFieldNames,\n type FieldViewer,\n findRelation,\n includableRelationNames,\n type IncludeNode,\n normalizeInclude,\n queryableFieldNames,\n resolveCollectionRelations,\n restrictedFieldNames,\n type UnknownFieldAnswer,\n unknownAggregateField,\n unknownFilterField,\n unknownIncludeRelation,\n unknownOrderByField,\n unknownProjectionField,\n unknownRelationTargetField,\n unknownVectorProperty,\n vectorPropertyNames\n} from \"@rebasepro/common\";\nimport { ApiError } from \"../errors\";\n\n/**\n * A read may not name a field the caller cannot read.\n *\n * The strip in the row pipeline is what keeps the *value* off the wire. This is\n * the other half, and without it the value is still readable one bit at a time:\n * `?salary=gt.100000` returns the rows whose withheld salary is above 100k, and\n * `?orderBy=salary` returns them in order of it. A column no response can carry\n * has to be a column no query can interrogate, or the read rule is decoration.\n *\n * The refusal names a field restricted by role. That is deliberate and it is\n * not a leak: the published OpenAPI lists every property of every collection,\n * including the ones a given caller cannot read, because the document is one\n * document and is served off the app rather than off the authenticated data\n * router. Hiding the name here would protect nothing and would answer a\n * caller's genuine typo with \"unknown field\", sending them to look for a\n * spelling mistake that is not there. Those field *names* are public; their\n * *values* are not.\n *\n * An `excludeFromApi` field is the exception, because its name is *not*\n * public: OpenAPI, `list_collections` and the generated SDK all leave it out.\n * \"`email` is not readable on `authors`\" would confirm the one thing those hide,\n * so a filter, sort, projection, include, aggregate or vector search naming one\n * is answered as one naming a field that does not exist — built by the functions the driver answers a\n * typo with (`@rebasepro/common`'s `unknown-field`), so the two answers are the\n * same bytes. See {@link assertNoHiddenNames}.\n *\n * @module\n */\n\n/**\n * The roles behind a request, as a viewer a field rule can judge.\n *\n * Never `undefined`, and that is the point. `undefined` means the trusted server\n * plane in {@link FieldViewer}, which satisfies every non-empty role list — so\n * returning it for a request that merely has no `user` on the context would\n * hand an unauthenticated caller every field in the database. The auth\n * middleware scopes such a request's driver as `roles: [\"anon\"]` but sets no\n * `user`, so the fallback here has to be the same list the driver was scoped\n * with, not nothing.\n *\n * @param c anything carrying the Hono context's `get` — the batch route passes a\n * shim rather than the context itself, exactly as the API-key\n * permission check does.\n */\nexport function requestViewer(c: { get: (key: never) => unknown }): FieldViewer {\n const user = c.get(\"user\" as never) as { roles?: readonly string[] } | undefined;\n return { roles: user?.roles ?? ANON_ROLES };\n}\n\n/** What the auth middleware scopes an unauthenticated request's driver with. */\nconst ANON_ROLES: readonly string[] = Object.freeze([\"anon\"]);\n\n/** Which query parameter a refused field arrived in, for the message. */\ntype Where = \"filter\" | \"orderBy\" | \"fields\" | \"select\" | \"groupBy\" | \"vector_search\";\n\nconst WHERE_LABEL: Record<Where, string> = {\n filter: \"a filter\",\n orderBy: \"`orderBy`\",\n fields: \"`fields`\",\n select: \"`select`\",\n groupBy: \"`groupBy`\",\n vector_search: \"`vector_search`\"\n};\n\n/** Every column a logical group compares, however deeply nested. */\nfunction logicalColumns(logical: LogicalCondition | undefined, into: string[]): void {\n if (!logical?.conditions) return;\n for (const condition of logical.conditions) {\n if (\"conditions\" in condition) logicalColumns(condition as LogicalCondition, into);\n else if ((condition as FilterCondition).column) into.push((condition as FilterCondition).column);\n }\n}\n\n/**\n * The bare column an `orderBy` key names, or `undefined` for one that is not a\n * column at all.\n *\n * A sort key may be a relation aggregate (`comments.count()`) or one of the\n * computed keys a search adds (`_score`, `_distance`). Neither is a property of\n * this collection, so neither is a field this rule has anything to say about;\n * the field it *would* have named is checked by the same walk one level down\n * when the driver resolves the relation.\n */\nfunction orderByColumn(field: string): string | undefined {\n if (field.startsWith(\"_\")) return undefined;\n if (field.includes(\"(\") || field.includes(\".\")) return undefined;\n return field;\n}\n\n/**\n * Refuse the request when any of `names` is a field this caller cannot read.\n *\n * Exported so the aggregate route — whose `select` and `groupBy` are parsed\n * outside `parseQueryOptions` — applies the identical rule. `count(*)` over a\n * withheld column is the same disclosure as reading it, one predicate at a time.\n */\nexport function assertReadableFields(\n names: readonly (string | undefined)[],\n collection: CollectionConfig,\n viewer: FieldViewer | undefined,\n where: Where\n): void {\n if (names.length === 0) return;\n const { refused } = restrictedFieldNames(collection, viewer, \"read\");\n if (refused.size === 0) return;\n // An `excludeFromApi` name is answered as an unknown one, by\n // `assertNoHiddenNames` or `assertNoHiddenAggregateNames`, never here.\n const hidden = apiHiddenFieldNames(collection);\n\n const named = [...new Set(names.filter((n): n is string =>\n n !== undefined && refused.has(n) && !hidden.has(n)))];\n if (named.length === 0) return;\n\n throw ApiError.badRequest(\n `${named.map(f => `'${f}'`).join(\", \")} ${named.length > 1 ? \"are\" : \"is\"} not readable ` +\n `on '${collection.slug}' with your roles, so ${named.length > 1 ? \"they\" : \"it\"} cannot be used in ` +\n `${WHERE_LABEL[where]}.`,\n \"FIELD_NOT_READABLE\",\n {\n collection: collection.slug,\n fields: named,\n violations: named.map(field => ({\n field,\n code: \"access\",\n message: `'${field}' is not readable with your roles.`\n }))\n }\n );\n}\n\n/**\n * The whole of a parsed read request, checked in one pass.\n *\n * One call rather than five, because five call sites is five chances to add a\n * sixth query parameter and forget it — which is exactly how `?or=` came to be\n * parsed and then dropped by the list route.\n */\nexport function assertQueryFieldsReadable(\n options: {\n where?: Record<string, unknown>;\n logical?: LogicalCondition;\n orderBy?: { field: string }[];\n fields?: string[];\n include?: IncludeSpec;\n vectorSearch?: { property: string };\n },\n collection: CollectionConfig,\n viewer: FieldViewer | undefined\n): void {\n const filtered = assertRestrictedFieldsUnused(options, collection, viewer);\n\n // After every refusal, as the driver's unknown-field answers come after\n // them: a hidden name is a typo the driver has not reached yet.\n const include = options.include !== undefined ? normalizeInclude(options.include) : undefined;\n assertNoHiddenNames({ ...options, filtered, include: include?.tree }, collection);\n}\n\n/**\n * The aggregate route's `select` and `groupBy`, which it parses itself: an\n * `excludeFromApi` name there is answered exactly as the driver answers a\n * column that does not exist. Walked in the driver's order — each aggregate's\n * field, then each group key — and the first hidden *or* unknown name gets the\n * answer, so a typo before a hidden name is still the one named.\n */\nexport function assertNoHiddenAggregateNames(\n aggregates: readonly { fn: string; field?: string }[],\n groupBy: readonly string[],\n collection: CollectionConfig\n): void {\n const hidden = apiHiddenFieldNames(collection);\n if (hidden.size === 0) return;\n const asked = [\n ...aggregates.flatMap(({ fn, field }) => field === undefined ? [] : [{ name: field, forWhat: `${fn}()` }]),\n ...groupBy.map(name => ({ name, forWhat: \"groupBy\" }))\n ];\n if (!asked.some(({ name }) => hidden.has(name))) return;\n const valid = queryableFieldNames(collection);\n const known = (name: string) => !hidden.has(name) && (valid.includes(name) || name in (collection.properties ?? {}));\n for (const { name, forWhat } of asked) {\n if (known(name)) continue;\n const answer = unknownAggregateField(name, forWhat, valid);\n throw ApiError.badRequest(answer.message, answer.code, answer.details);\n }\n}\n\n/**\n * Refuse every field restricted by role that the read names, at every level of\n * its include tree. Returns the filter's column names, for the hidden pass.\n */\nfunction assertRestrictedFieldsUnused(\n options: Parameters<typeof assertQueryFieldsReadable>[0],\n collection: CollectionConfig,\n viewer: FieldViewer | undefined\n): string[] {\n const filtered: string[] = [];\n if (options.where) filtered.push(...Object.keys(options.where));\n logicalColumns(options.logical, filtered);\n assertReadableFields(filtered.map(filterHead), collection, viewer, \"filter\");\n assertRelationPathsReadable(filtered, collection, viewer);\n\n assertReadableFields(\n (options.orderBy ?? []).map(entry => orderByColumn(entry.field)),\n collection, viewer, \"orderBy\"\n );\n assertAggregateSortsReadable(options.orderBy ?? [], collection, viewer);\n\n assertReadableFields(options.fields ?? [], collection, viewer, \"fields\");\n\n // A similarity search reads the vector it ranks by: `_distance` from a\n // point the caller chose is a measurement of it, enough of them locate it,\n // and `vector_threshold` alone answers \"is it within r of here\".\n assertReadableFields(\n options.vectorSearch ? [options.vectorSearch.property] : [],\n collection, viewer, \"vector_search\"\n );\n\n const include = options.include !== undefined ? normalizeInclude(options.include) : undefined;\n if (include) assertIncludeFieldsReadable(include.tree, collection, viewer);\n return filtered;\n}\n\n/**\n * The field a filter key reads on *this* collection: the column before a JSON\n * path's first arrow (`metadata->theme` reads `metadata`), the relation before\n * a relation path's dot (`author.email` reads `author`), the key itself\n * otherwise. A key that is a property outright wins, as the driver resolves it.\n */\nfunction filterHead(name: string): string {\n const arrow = name.indexOf(\"->\");\n if (arrow > 0) return name.slice(0, arrow);\n const dot = name.indexOf(\".\");\n if (dot > 0) return name.slice(0, dot);\n return name;\n}\n\n/**\n * `orderBy=max(staff.salary)` ranks the parents by the target's `salary` — the\n * same reading `orderBy=salary` on `staff` is — so the aggregated field is\n * judged by the target's rule. Whether the relation itself may be read is the\n * driver's check (`assertRelationReadable`), which runs on every door.\n */\nfunction assertAggregateSortsReadable(\n orderBy: readonly { field: string }[],\n collection: CollectionConfig,\n viewer: FieldViewer | undefined\n): void {\n let relations: ReturnType<typeof resolveCollectionRelations> | undefined;\n for (const { field } of orderBy) {\n const spec = parseRelationAggregateSort(field);\n if (!spec?.field) continue;\n relations ??= resolveCollectionRelations(collection);\n const relation = findRelation(relations, spec.relation);\n if (!relation) continue;\n assertReadableFields([spec.field], relation.target(), viewer, \"orderBy\");\n }\n}\n\n/**\n * `?author.salary=gt.100000` reads the target's `salary`, a row at a time, as\n * `?salary=gt.100000` on `authors` would — so it is judged by the target's\n * rule. Only a path whose first segment is a relation here; anything else is\n * the driver's to refuse.\n */\nfunction assertRelationPathsReadable(\n filtered: readonly string[],\n collection: CollectionConfig,\n viewer: FieldViewer | undefined\n): void {\n let relations: ReturnType<typeof resolveCollectionRelations> | undefined;\n for (const name of filtered) {\n const dot = name.indexOf(\".\");\n if (dot <= 0 || name.indexOf(\"->\") >= 0) continue;\n relations ??= resolveCollectionRelations(collection);\n const relation = findRelation(relations, name.slice(0, dot));\n if (!relation) continue;\n assertReadableFields([name.slice(dot + 1)], relation.target(), viewer, \"filter\");\n }\n}\n\n/**\n * Answer a read naming an `excludeFromApi` field — or relation — exactly as the\n * driver answers a read naming a field that does not exist.\n *\n * The names are walked in the order the driver resolves them — the `fields`\n * projection, then the filter, then the sort, then each include, parent before\n * child — and the first that is hidden *or* unknown gets the answer. Answering\n * only the hidden one would still tell the two apart: with `?aaa=x&email=x` the\n * driver names `aaa` when `email` does not exist, so this has to as well.\n *\n * A request naming nothing hidden is left alone entirely, so the driver stays\n * the only one answering ordinary typos.\n */\nfunction assertNoHiddenNames(\n options: {\n filtered: string[];\n orderBy?: { field: string }[];\n fields?: string[];\n include?: Record<string, IncludeNode>;\n vectorSearch?: { property: string };\n },\n collection: CollectionConfig\n): void {\n const hidden = apiHiddenFieldNames(collection);\n if (hidden.size > 0) {\n const asked: { kind: \"fields\" | \"filter\" | \"orderBy\"; name: string }[] = [\n ...(options.fields ?? []).map(name => ({ kind: \"fields\" as const, name })),\n ...options.filtered.map(name => ({ kind: \"filter\" as const, name })),\n ...(options.orderBy ?? []).flatMap(entry => {\n const name = orderByColumn(entry.field);\n return name === undefined ? [] : [{ kind: \"orderBy\" as const, name }];\n })\n ];\n const shapes = asked.map(({ kind, name }) => ({ kind, name, shape: nameShape(name, collection, hidden) }));\n const vectorHidden = options.vectorSearch !== undefined && hidden.has(options.vectorSearch.property);\n if (vectorHidden || shapes.some(entry => entry.shape.hidden)) {\n for (const { kind, name, shape } of shapes) {\n if (shape.known && !shape.hidden) continue;\n const answer = unknownAnswer(kind, name, shape, collection);\n throw ApiError.badRequest(answer.message, answer.code, answer.details);\n }\n }\n if (vectorHidden && options.vectorSearch) {\n const answer = unknownVectorProperty(options.vectorSearch.property, vectorPropertyNames(collection));\n throw ApiError.badRequest(answer.message, answer.code, answer.details);\n }\n }\n\n const relations = resolveCollectionRelations(collection);\n for (const [key, node] of Object.entries(options.include ?? {})) {\n if (hidden.has(key)) {\n const answer = unknownIncludeRelation(key, collection.slug ?? collection.name, includableRelationNames(collection));\n throw ApiError.badRequest(answer.message, answer.code, answer.details);\n }\n const relation = relations[key];\n if (!relation) continue;\n const filtered: string[] = [];\n if (node.where) filtered.push(...Object.keys(node.where));\n logicalColumns(node.logical, filtered);\n assertNoHiddenNames({\n filtered,\n orderBy: node.orderBy?.map(([field]) => ({ field })),\n fields: node.fields,\n include: node.children\n }, relation.target());\n }\n}\n\n/**\n * What a name in a read resolves to, as far as a collection can say without its\n * table: `hidden` when it reaches an `excludeFromApi` field or relation, `known`\n * when it names something the driver will resolve. A relation path\n * (`author.email`) carries its relation, to be answered about the target.\n */\ntype NameShape = {\n hidden: boolean;\n known: boolean;\n path?: { relationKey: string; fieldKey: string; target: CollectionConfig };\n};\n\nfunction nameShape(name: string, collection: CollectionConfig, hidden: ReadonlySet<string>): NameShape {\n if (hidden.has(name)) return { hidden: true, known: false };\n const columns = new Set(queryableFieldNames(collection));\n const relations = resolveCollectionRelations(collection);\n if (columns.has(name) || name in (collection.properties ?? {})) return { hidden: false, known: true };\n\n // `metadata->theme`: the column before the first arrow is what it names.\n const arrow = name.indexOf(\"->\");\n if (arrow > 0) {\n const head = name.slice(0, arrow);\n return { hidden: hidden.has(head), known: columns.has(head) };\n }\n\n // `author.email`: a field of the relation's target.\n const dot = name.indexOf(\".\");\n if (dot > 0) {\n const relationKey = name.slice(0, dot);\n const fieldKey = name.slice(dot + 1);\n if (hidden.has(relationKey)) return { hidden: true, known: false };\n const relation = findRelation(relations, relationKey);\n if (!relation) return { hidden: false, known: false };\n const target = relation.target();\n const targetHidden = apiHiddenFieldNames(target);\n const path = { relationKey, fieldKey, target };\n if (targetHidden.has(fieldKey)) return { hidden: true, known: false, path };\n const known = queryableFieldNames(target).includes(fieldKey) || fieldKey in (target.properties ?? {});\n return { hidden: false, known, path };\n }\n return { hidden: false, known: false };\n}\n\nfunction unknownAnswer(\n kind: \"fields\" | \"filter\" | \"orderBy\",\n name: string,\n shape: NameShape,\n collection: CollectionConfig\n): UnknownFieldAnswer {\n const slug = collection.slug ?? collection.name;\n if (kind === \"fields\") return unknownProjectionField(name, slug, queryableFieldNames(collection));\n if (kind === \"orderBy\") return unknownOrderByField(name, slug, queryableFieldNames(collection));\n if (shape.path) {\n return unknownRelationTargetField(\n { field: name, relationKey: shape.path.relationKey, fieldKey: shape.path.fieldKey },\n { slug: shape.path.target.slug, validFields: queryableFieldNames(shape.path.target) },\n slug\n );\n }\n return unknownFilterField(name, slug, queryableFieldNames(collection));\n}\n\n/**\n * Every relation an `include` loads, judged like the read it is part of.\n *\n * An include's own `where`, `logical`, `orderBy` and `fields` read the columns\n * of the relation's *target*: `?include={\"staff\":{\"where\":{\"salary\":[\">\",100000]}}}`\n * answers which departments employ someone paid over 100k, and `orderBy` with a\n * `limit` of one names who — while `?salary=gt.100000` on `staff` itself is\n * refused. So each node is checked against its target's rules, level by level.\n *\n * A name that is not a relation of the collection is skipped rather than\n * refused here: the driver refuses it with a 400 naming the relations there\n * are, and loads nothing for it. Looked up by exact key, as the driver does, so\n * both judge the same relation.\n */\nfunction assertIncludeFieldsReadable(\n tree: Record<string, IncludeNode>,\n collection: CollectionConfig,\n viewer: FieldViewer | undefined\n): void {\n const relations = resolveCollectionRelations(collection);\n for (const [key, node] of Object.entries(tree)) {\n const relation = relations[key];\n if (!relation) continue;\n const target = relation.target();\n assertRestrictedFieldsUnused({\n where: node.where,\n logical: node.logical,\n orderBy: node.orderBy?.map(([field]) => ({ field })),\n fields: node.fields\n }, target, viewer);\n assertIncludeFieldsReadable(node.children, target, viewer);\n }\n}\n","import type { CollectionConfig, FilterValues, ListLimitBounds, LogicalCondition, NullsPlacement, OrderByTuple, VectorSearchParams } from \"@rebasepro/types\";\nimport { toCanonicalOp, resolveClientListLimit, ListLimitError, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT } from \"@rebasepro/types\";\nimport type { DecodedCursor } from \"@rebasepro/common\";\nimport {\n CursorError,\n CursorMismatchError,\n type FieldViewer,\n IncludeSpecError,\n OrderBySpecError,\n PAGE_WITH_OFFSET_MESSAGE,\n decodeCursor,\n deserializeFilter,\n deserializeInclude,\n deserializeLogicalCondition,\n normalizeInclude,\n reconcileCursorOrder,\n RESERVED_QUERY_KEYS,\n UnknownFilterOperatorError\n} from \"@rebasepro/common\";\nimport { QueryOptions } from \"../types\";\nimport { ApiError } from \"../errors\";\nimport { DELETED_QUERY_PARAM, parseWithDeleted } from \"./soft-delete-params\";\nimport { assertQueryFieldsReadable } from \"./field-access-query\";\n\nexport const mapOperator = (op: string) => toCanonicalOp(op) ?? null;\n\n/**\n * A malformed query parameter, refused with a 400.\n *\n * Every rejection in this file is one of these, and every one of them is\n * `expected` — the flag `errorHandler` reads to log a routine outcome at debug\n * instead of warn. A client that mistypes an operator, a sort direction or a\n * limit is not an incident: nothing on the server is wrong, the request never\n * reached the database, and the caller has already been told what to fix in the\n * response body. Left at warn, a single frontend holding a stale field name\n * writes a `⚠️` line per request forever, and the warn level stops meaning\n * anything — which is why \"routine 4xx logs at WARN\" is a standing finding\n * against this API.\n *\n * Not a factory on `ApiError`: the class's members are part of the tracked\n * runtime surface (`api-surface/server.api.txt`), and this needs no addition to\n * it. `ApiError.unauthenticated` is the same idea one status code up.\n */\nfunction invalidParam(message: string, code: string, details?: unknown): ApiError {\n return new ApiError(400, code, message, details, true);\n}\n\n/**\n * Decode a filter, turning the shared codec's operator rejection into a 400.\n *\n * `deserializeFilter` lives in `@rebasepro/common`, which cannot throw an\n * `ApiError` — it does not depend on this package, and the browser SDK decodes\n * through the same function and has nothing to render one with. So it throws\n * `UnknownFilterOperatorError`, and the HTTP boundary is where that becomes a\n * status code. Same seam `parseLogicalGroup` uses for the nesting bound.\n *\n * Without this the operator string became a *value*: `?where={\"title\":\n * [\"!!\",\"Hello\"]}` compiled to `title IN ('!!','Hello')` and answered 200 with\n * the row the caller was filtering out, and `{\"id\":[\">>\",0]}` reached Postgres\n * and came back a 500 quoting `invalid input syntax for type integer`. Both are\n * malformed requests and now say so.\n */\nfunction decodeFilter(query: Record<string, unknown>): FilterValues<string> {\n try {\n return deserializeFilter(query);\n } catch (e) {\n if (e instanceof UnknownFilterOperatorError) {\n throw invalidParam(e.message, e.code, e.details);\n }\n throw e;\n }\n}\n\nfunction getLastValue(val: unknown): unknown {\n if (Array.isArray(val)) {\n return val[val.length - 1];\n }\n return val;\n}\n\n/**\n * Parse an `or(...)` / `and(...)` logical group from its wire form.\n *\n * The wire carries the inner conditions wrapped in parens (e.g.\n * `(status.eq.active,age.gte.18)`); we re-attach the `or`/`and` prefix and\n * delegate to the canonical filter dialect (`@rebasepro/common`). Values are\n * preserved as strings — type coercion is the schema-aware driver's job, so\n * this path stays byte-for-byte consistent with the SDK/admin path (which\n * also parses via the shared dialect).\n */\nfunction parseLogicalGroup(type: \"or\" | \"and\" | \"not\", raw: unknown): LogicalCondition | undefined {\n let inner = String(raw).trim();\n if (inner.startsWith(\"(\") && inner.endsWith(\")\")) {\n inner = inner.slice(1, -1);\n }\n inner = inner.trim();\n if (!inner) return undefined;\n let parsed;\n try {\n parsed = deserializeLogicalCondition(`${type}(${inner})`);\n } catch (e) {\n // An operator the dialect does not have is the same refusal the JSON\n // `where` gives for it, by the same code.\n if (e instanceof UnknownFilterOperatorError) {\n throw invalidParam(e.message, e.code, e.details);\n }\n // The parser refuses a nesting depth no real filter reaches. That is a\n // request problem, and without this it surfaced as a 500 — the\n // unbounded version reached `RangeError: Maximum call stack size\n // exceeded`, which tells the caller nothing about their filter.\n throw invalidParam(\n `Invalid \\`${type}\\` parameter: ${e instanceof Error ? e.message : String(e)}`,\n \"INVALID_LOGICAL_GROUP\"\n );\n }\n return \"type\" in parsed ? parsed : undefined;\n}\n\n/**\n * Parse the `?where=` JSON filter object.\n *\n * This is the dialect the OpenAPI document publishes on every\n * `GET /api/data/{slug}` — `{\"status\":[\"==\",\"active\"]}`: field → canonical\n * `[WhereFilterOp, value]` tuple. It is normalized through the same\n * `deserializeFilter` as the `?field=op.value` params below, so a value that\n * arrives as a PostgREST dot-string (`{\"status\":\"eq.active\"}`) or as a bare\n * scalar (`{\"status\":\"active\"}`) compiles to the same condition. Unlike the\n * querystring dialect, JSON carries types — a number stays a number.\n *\n * A malformed value is a 400 rather than a silent drop: dropping the filter\n * would run the read unfiltered and return everything RLS happens to allow.\n */\nfunction parseWhereParam(raw: unknown): FilterValues<string> | undefined {\n const str = String(raw).trim();\n if (!str) return undefined;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(str);\n } catch {\n throw invalidParam(\n \"Invalid `where` parameter: expected a JSON object, e.g. {\\\"status\\\":[\\\"==\\\",\\\"active\\\"]}\",\n \"INVALID_WHERE\"\n );\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw invalidParam(\n \"Invalid `where` parameter: expected a JSON object mapping fields to conditions, \"\n + \"e.g. {\\\"status\\\":[\\\"==\\\",\\\"active\\\"]}\",\n \"INVALID_WHERE\"\n );\n }\n\n const filter = decodeFilter(parsed as Record<string, unknown>);\n return Object.keys(filter).length > 0 ? filter : undefined;\n}\n\ntype OrderByEntry = { field: string; direction: \"asc\" | \"desc\"; nulls?: NullsPlacement };\n\n/**\n * The parsed entries as the driver contract spells them: `[field, direction]`\n * tuples in order of significance.\n *\n * The REST layer used to hand the driver `orderBy[0].field` and drop the rest,\n * so `?orderBy=[{\"field\":\"roles\"},{\"field\":\"created_at\",\"direction\":\"desc\"}]`\n * — a shape this parser has always accepted and validated in full — sorted by\n * `roles` alone and returned the ties in whatever order Postgres pleased.\n */\nexport function orderByEntriesToTuples(entries?: OrderByEntry[]): OrderByTuple[] | undefined {\n if (!entries || entries.length === 0) return undefined;\n return entries.map(({ field, direction, nulls }) => (nulls\n ? [field, direction, nulls]\n : [field, direction]) as OrderByTuple);\n}\n\nfunction invalidOrderBy(detail: string): never {\n throw invalidParam(\n `Invalid \\`orderBy\\` parameter: ${detail}. Expected \\`field\\`, \\`field:desc\\`, `\n + \"`field:desc:last`, or a JSON array like \"\n + \"[{\\\"field\\\":\\\"created_at\\\",\\\"direction\\\":\\\"desc\\\",\\\"nulls\\\":\\\"last\\\"}]\",\n \"INVALID_ORDER_BY\"\n );\n}\n\n/**\n * The `nulls` slot: `first`/`last`, or a refusal naming the entry.\n *\n * Refused rather than defaulted, for the reason every other parameter here is:\n * a sort quietly ordered by a convention the caller did not ask for reads as\n * though it obeyed them. See {@link NullsPlacement} for what the default is\n * when the slot is simply absent.\n */\nfunction toNulls(raw: unknown, context: string): NullsPlacement | undefined {\n if (raw === undefined || raw === null || raw === \"\") return undefined;\n if (raw !== \"first\" && raw !== \"last\") {\n invalidOrderBy(`${context} has nulls '${String(raw)}'`);\n }\n return raw;\n}\n\n/** The aggregate functions `?select=` accepts. */\nconst AGGREGATE_FUNCTIONS = new Set([\"count\", \"sum\", \"avg\", \"min\", \"max\"]);\n\nexport interface ParsedAggregate {\n fn: \"count\" | \"sum\" | \"avg\" | \"min\" | \"max\";\n /** Absent only for `count()`, which counts rows rather than values. */\n field?: string;\n /** The key this appears under in the response. */\n alias: string;\n}\n\n/**\n * Parse `?select=count(),sum(total),avg(total)`.\n *\n * The spelling is SQL's, because whoever writes it is thinking in SQL and\n * because any other spelling has to be learned first. `count()` with no field\n * counts rows; every other function names a column.\n *\n * Aliases are derived rather than accepted: `sum(total)` returns as\n * `sum_total`, `count()` as `count`. Letting a caller choose would mean\n * checking their alias is not also a `groupBy` field — a rule nobody would\n * guess, and a silently overwritten value if it went unchecked.\n */\nexport function parseAggregateSelect(raw: unknown): ParsedAggregate[] | undefined {\n const value = getLastValue(raw);\n if (!value) return undefined;\n\n const entries = String(value).split(\",\").map(s => s.trim()).filter(Boolean);\n if (entries.length === 0) return undefined;\n\n return entries.map((entry) => {\n const match = /^([a-z]+)\\(\\s*([A-Za-z0-9_]*)\\s*\\)$/i.exec(entry);\n if (!match) {\n throw invalidParam(\n `Invalid \\`select\\` entry \"${entry}\". Expected \\`fn(field)\\`, e.g. \\`sum(total)\\` or \\`count()\\`.`,\n \"INVALID_AGGREGATE_SELECT\"\n );\n }\n\n const fn = match[1].toLowerCase();\n const field = match[2] || undefined;\n\n if (!AGGREGATE_FUNCTIONS.has(fn)) {\n throw invalidParam(\n `Unknown aggregate function \"${fn}\". Expected: ${[...AGGREGATE_FUNCTIONS].join(\", \")}.`,\n \"INVALID_AGGREGATE_FUNCTION\"\n );\n }\n if (fn !== \"count\" && !field) {\n // `sum()` has no sensible reading, and guessing one would be\n // inventing a column on the caller's behalf.\n throw invalidParam(\n `\\`${fn}()\\` needs a field, e.g. \\`${fn}(total)\\`. Only \\`count()\\` may be empty.`,\n \"INVALID_AGGREGATE_SELECT\"\n );\n }\n\n return {\n fn: fn as ParsedAggregate[\"fn\"],\n field,\n alias: field ? `${fn}_${field}` : fn\n };\n });\n}\n\n/** Parse `?groupBy=status,country`. */\nexport function parseGroupBy(raw: unknown): string[] | undefined {\n const value = getLastValue(raw);\n if (!value) return undefined;\n const fields = String(value).split(\",\").map(s => s.trim()).filter(Boolean);\n return fields.length > 0 ? fields : undefined;\n}\n\n/** `asc`/`desc`, in any case. Anything else is a request to sort in a way that does not exist. */\nfunction toDirection(raw: unknown, context: string): \"asc\" | \"desc\" {\n if (raw === undefined || raw === null) return \"asc\";\n if (typeof raw !== \"string\") invalidOrderBy(`${context} has a non-string \\`direction\\``);\n const lowered = raw.toLowerCase();\n if (lowered !== \"asc\" && lowered !== \"desc\") {\n invalidOrderBy(`${context} has direction '${raw}'`);\n }\n return lowered;\n}\n\n/** One entry: the canonical `{field, direction}`, or the `field:direction` shorthand as a string. */\nfunction toOrderByEntry(raw: unknown, index: number): OrderByEntry {\n const context = `entry ${index}`;\n if (typeof raw === \"string\") {\n // Split here rather than through `deserializeOrderBy`, which is the\n // *client* end of the codec and normalises anything that is not\n // literally \"desc\" to \"asc\". Routed through it, `?orderBy=x:DESC`\n // reached `toDirection` already collapsed to \"asc\" and answered 200\n // with the rows in the opposite order — a newest-first list showing\n // the oldest rows — and `x:sideways` did the same. The direction token\n // has to arrive here raw for `toDirection` to have anything to refuse.\n const idx = raw.indexOf(\":\");\n const field = (idx === -1 ? raw : raw.slice(0, idx)).trim();\n if (!field) invalidOrderBy(`${context} is an empty field name`);\n if (idx === -1) return { field, direction: \"asc\" };\n // `field:direction:nulls`. The third segment is optional, so every\n // `field:desc` written before it existed parses exactly as it did.\n const rest = raw.slice(idx + 1);\n const nullsIdx = rest.indexOf(\":\");\n const direction = toDirection(nullsIdx === -1 ? rest : rest.slice(0, nullsIdx), context);\n const nulls = nullsIdx === -1 ? undefined : toNulls(rest.slice(nullsIdx + 1), context);\n return nulls ? { field, direction, nulls } : { field, direction };\n }\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n invalidOrderBy(`${context} is not a field name or a {field, direction} object`);\n }\n const entry = raw as Record<string, unknown>;\n if (typeof entry.field !== \"string\" || entry.field.trim() === \"\") {\n invalidOrderBy(`${context} has no \\`field\\``);\n }\n const nulls = toNulls(entry.nulls, context);\n const direction = toDirection(entry.direction, context);\n return nulls ? { field: entry.field, direction, nulls } : { field: entry.field, direction };\n}\n\n/**\n * Parse the `orderBy` query parameter.\n *\n * The field *name* has been validated against the schema for a while — an\n * `?orderBy=titel` is a 400 rather than 200 with unsorted rows, on the grounds\n * that silently dropping the sort leaves the caller believing in an order that\n * is not there. The parameter's *shape* was never checked the same way, and it\n * failed in exactly the same silent manner one layer earlier: whatever\n * `JSON.parse` returned was assigned to an option declared as an array of\n * `{field, direction}`, and the REST layer reads only `orderBy[0].field`. So\n * `?orderBy={\"field\":\"name\"}` — an object rather than an array, and the most\n * natural thing for a client to try — read `undefined`, dropped the ORDER BY,\n * and answered 200. So did a number, a boolean, `null`, and `[\"name\"]`.\n *\n * This refuses those, the way `parseWhereParam` above already refuses a\n * malformed filter and for the same reason. What it keeps working is every\n * shape that worked before: the `field` and `field:desc` shorthands, and the\n * canonical JSON array.\n */\nfunction parseOrderByParam(raw: unknown): OrderByEntry[] | undefined {\n if (Array.isArray(raw)) {\n // A repeated query parameter arrives pre-split; treat it as the list.\n return raw.length === 0 ? undefined : raw.map(toOrderByEntry);\n }\n\n const str = String(raw).trim();\n if (!str) return undefined;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(str);\n } catch {\n // Not JSON at all, so it is the `field:direction` shorthand.\n return [toOrderByEntry(str, 0)];\n }\n\n // `JSON.parse` succeeding says nothing about the shape being usable.\n if (Array.isArray(parsed)) {\n if (parsed.length === 0) return undefined;\n return parsed.map(toOrderByEntry);\n }\n if (typeof parsed === \"string\") return [toOrderByEntry(parsed, 0)];\n if (typeof parsed === \"object\" && parsed !== null) {\n // A bare `{field, direction}` is a near miss rather than nonsense, but\n // accepting it would leave two spellings of one parameter. Name it.\n invalidOrderBy(\"a single object was given where a JSON array was expected\");\n }\n invalidOrderBy(`${typeof parsed} is not a field name or a list of them`);\n}\n\n// Re-exported for callers/tests that reference the REST list bounds. The\n// numbers and the rule live in `@rebasepro/types` so the REST parser and the\n// WebSocket ingress enforce ONE shared guarantee. See `resolveClientListLimit`.\nexport { DEFAULT_LIST_LIMIT, DEFAULT_VECTOR_LIST_LIMIT, MAX_LIST_LIMIT } from \"@rebasepro/types\";\n\n/**\n * Overridable list-pagination bounds for {@link parseQueryOptions}. Without\n * these, `GET /<collection>` with no `?limit` would buffer the ENTIRE table\n * into a JS array + JSON response (a trivial OOM/DoS), and `?limit=100000000`\n * would be honoured verbatim.\n */\nexport interface ListLimitOptions {\n /**\n * Page size used when the client sends no `?limit`. Applied to plain and\n * text-search reads — a vector search falls back to its own default (10).\n */\n defaultLimit?: number;\n /** Largest `?limit` a client may ask for. A larger one is a 400, not a clamp. */\n maxLimit?: number;\n}\n\n/**\n * {@link resolveClientListLimit} for an HTTP route: the same bounds, answered\n * with a 400 rather than a 500.\n *\n * The shared resolver throws a `ListLimitError`, which carries `status` — but\n * the Hono error handler discriminates on `statusCode`, so an unconverted one\n * reaches the client as `INTERNAL_ERROR` with its message stripped, telling the\n * caller nothing about the parameter it got wrong. Every REST list ingress\n * routes its `limit` through here so all of them name the ceiling the same way.\n */\nexport function resolveListLimitParam(\n rawLimit: number | string | null | undefined,\n opts: ListLimitBounds & { vectorSearch?: boolean } = {}\n): number {\n try {\n return resolveClientListLimit(rawLimit, opts);\n } catch (e) {\n if (e instanceof ListLimitError) {\n throw invalidParam(e.message, \"INVALID_LIMIT\");\n }\n throw e;\n }\n}\n\n/**\n * A whole number at or above `minimum`, or a 400 naming the parameter.\n *\n * `parseInt` was the whole of the validation, and it answers `NaN` for\n * `?offset=abc` and a negative for `?offset=-5`. Neither was checked:\n *\n * - `NaN` reached the driver, where `OFFSET NaN` is a 500 about a syntax error\n * in a query the caller never wrote;\n * - `?page=0` computed `offset = -limit`, a negative offset, which Postgres\n * also refuses — and `?page=-3` refused deeper;\n * - `?offset=1.5` truncated silently to `1`, so the caller paged a window they\n * had not asked for.\n *\n * Every one of those is the caller's parameter, so every one is a 400 named\n * after the parameter — the shape `INVALID_LIMIT` already had, and the reason a\n * limit is *rejected* rather than clamped: a window quietly different from the\n * one asked for cannot be told apart from having reached the end.\n *\n * `expected: true` on the error (via {@link invalidParam}): a mistyped query\n * parameter never reached the database and the response body already says what\n * to fix, so it logs at debug rather than putting a warning in production logs\n * on every request from a client holding a stale link.\n */\nfunction parseWindowParam(raw: unknown, name: string, minimum: number, code: string): number {\n const text = String(raw).trim();\n const value = Number(text);\n if (text === \"\" || !Number.isFinite(value) || !Number.isInteger(value) || value < minimum) {\n throw invalidParam(\n `Invalid \\`${name}\\` parameter: expected a whole number ${minimum === 0 ? \"of 0 or more\" : `of ${minimum} or more`}, got ${JSON.stringify(text)}.`,\n code\n );\n }\n return value;\n}\n\n/**\n * Parse query parameters into QueryOptions\n */\nexport function parseQueryOptions(\n query: Record<string, unknown>,\n limits: ListLimitOptions = {},\n /**\n * The collection being read and who is reading it. Optional so the parser\n * stays a pure parser for the callers that have neither (tests, the WS\n * ingress, anything parsing a query it is not about to run); when present,\n * a `where`, `orderBy` or `fields` naming a field the caller cannot read is\n * a 400 rather than a query the driver would happily answer. See\n * {@link assertQueryFieldsReadable}.\n */\n access?: { collection: CollectionConfig; viewer?: FieldViewer }\n): QueryOptions {\n const options: QueryOptions = {};\n const rawLimit = getLastValue(query.limit) as number | string | null | undefined;\n\n // `?deleted=include|only` — soft delete. See `soft-delete-params.ts`.\n const withDeleted = parseWithDeleted(getLastValue(query[DELETED_QUERY_PARAM]));\n if (withDeleted !== undefined) options.withDeleted = withDeleted;\n\n const offsetVal = getLastValue(query.offset);\n if (offsetVal) options.offset = parseWindowParam(offsetVal, \"offset\", 0, \"INVALID_OFFSET\");\n\n const pageVal = getLastValue(query.page);\n // Two names for one window. `page` used to win silently, so a caller who\n // sent `offset=10` read whatever page two was and was told nothing — the\n // same quiet override `after` + `offset` is refused for below.\n if (pageVal && offsetVal) {\n throw invalidParam(PAGE_WITH_OFFSET_MESSAGE, \"PAGE_WITH_OFFSET\");\n }\n if (pageVal) {\n const page = parseWindowParam(pageVal, \"page\", 1, \"INVALID_PAGE\");\n // Page stride uses the same bounded page size the read will use, so\n // pages neither overlap nor gap. (Vector search never paginates by\n // page, so the plain/text default is correct here.)\n const limit = resolveListLimitParam(rawLimit, {\n defaultLimit: limits.defaultLimit,\n maxLimit: limits.maxLimit\n });\n options.offset = (page - 1) * limit;\n }\n\n // ── Logical conditions (or / and / not) ────────────────────────────\n //\n // `?not=(status.eq.draft,views.gte.10)` negates the **conjunction** of its\n // conditions: `not(a)` is `NOT a`, `not(a,b)` is `NOT (a AND b)`. The rule\n // lives on `LogicalCondition` and is applied identically by this parser,\n // the shared wire codec and every driver compiler — one negation, one\n // meaning. A group nests, so `?not=(or(a,b))` is the De Morgan case.\n //\n // Three parameters and one slot, so exactly one applies. `or` wins over\n // `and`, and both over `not` — the precedence `or`/`and` already had, with\n // the third added at the end rather than in the middle, where it would have\n // silently changed which of two existing parameters was honoured.\n const orVal = getLastValue(query.or);\n const andVal = getLastValue(query.and);\n const notVal = getLastValue(query.not);\n if (orVal) {\n const logical = parseLogicalGroup(\"or\", orVal);\n if (logical) options.logical = logical;\n } else if (andVal) {\n const logical = parseLogicalGroup(\"and\", andVal);\n if (logical) options.logical = logical;\n } else if (notVal) {\n const logical = parseLogicalGroup(\"not\", notVal);\n if (logical) options.logical = logical;\n }\n\n // ── PostgREST-style field filters: ?field=op.value ─────────────────\n // Delegate to the canonical filter dialect (the single source of truth\n // for the wire grammar: operator codes, list/escape handling, implicit\n // eq). Values stay strings; the schema-aware driver coerces them to\n // column types. This keeps the REST path byte-for-byte consistent with\n // the SDK/admin path, which parses through the same `deserializeFilter`.\n //\n // `where` is reserved: it is the JSON filter dialect (see\n // `parseWhereParam`), not a column named \"where\". Leaving it out of this\n // list made the documented `?where={...}` compile as a filter on a\n // nonexistent field — which used to be dropped, widening the read to the\n // whole table, and is now a 400 `UNKNOWN_FILTER_FIELD`.\n //\n // `select` and `groupBy` are reserved for the same reason: on\n // `/aggregate` they are the request, and left out of this list\n // `?select=sum(total)` compiles into the filter as a comparison on a\n // column named \"select\" — a 400 on the one endpoint that requires it.\n // `not`, `after` and `distinct` join the list for the reason the comment\n // above gives: a reserved key left out of it compiles as a filter on a\n // column of that name, which is a 400 `UNKNOWN_FILTER_FIELD` on the one\n // request that needs the parameter. So do `?deleted=` and `?hard=`, which\n // ask about the soft-delete stamp rather than name a column.\n //\n // The list is shared with the SDK, which sends a filter on a column with\n // one of these names inside `?where=` rather than as its own parameter.\n const filterDict: Record<string, unknown> = {};\n for (const [key, rawValue] of Object.entries(query)) {\n if (RESERVED_QUERY_KEYS.has(key)) continue;\n filterDict[key] = rawValue;\n }\n // Both dialects may be sent together; an explicit `?field=op.value` wins\n // over the same field inside `where`, being the more specific request.\n const whereVal = getLastValue(query.where);\n const where = {\n ...(whereVal !== undefined && whereVal !== null ? parseWhereParam(whereVal) : undefined),\n ...decodeFilter(filterDict)\n };\n if (Object.keys(where).length > 0) {\n options.where = where;\n }\n\n // Sorting\n const orderByVal = getLastValue(query.orderBy);\n if (orderByVal) {\n options.orderBy = parseOrderByParam(orderByVal);\n }\n\n // ── Relation includes ──────────────────────────────────────────────\n //\n // Two spellings on one parameter, told apart by a leading `{`:\n //\n // ?include=author,comments.author — names and dotted paths\n // ?include={\"comments\":{\"limit\":5,\"include\":{\"author\":true}}}\n //\n // The flat form is what a human types and what every existing client\n // sends; the JSON form exists because the flat one has nowhere to put a\n // per-relation `limit`/`where`/`orderBy`/`fields`, and inventing a\n // punctuation for those (`comments(limit:5)`) would be a third grammar to\n // learn beside the two this API already has. Both compile to the same\n // request — `deserializeInclude` in `@rebasepro/common` is the codec, and\n // the SDK serialises through its inverse.\n const includeVal = getLastValue(query.include);\n if (includeVal !== undefined && includeVal !== null) {\n try {\n const include = deserializeInclude(String(includeVal));\n // Normalized for its *checks* — the depth bound and the shape of a\n // per-relation options object — and then discarded: what travels on\n // is the caller's own spelling, which the driver normalizes again\n // (idempotently) when it reads it. Validating here is what makes a\n // malformed include a 400 at the boundary rather than an\n // `IncludeSpecError` escaping from the driver as a 500, which is\n // what `?include=a.b.c.d` used to answer.\n normalizeInclude(include);\n options.include = include;\n } catch (e) {\n if (e instanceof IncludeSpecError) throw invalidParam(e.message, e.code);\n if (e instanceof OrderBySpecError) {\n throw invalidParam(`Invalid \\`include\\`: ${e.message}`, \"INVALID_INCLUDE\");\n }\n throw e;\n }\n }\n\n // Field selection. A projection at the driver, not a trim of the response:\n // the columns named here are the columns read.\n const fieldsVal = getLastValue(query.fields);\n if (fieldsVal) {\n const fieldsStr = String(fieldsVal).trim();\n options.fields = fieldsStr.split(\",\").map(s => s.trim()).filter(Boolean);\n }\n\n // `?distinct=true` — `SELECT DISTINCT` over the projection. Only `true`\n // and `1` mean yes; anything else is refused rather than read as \"no\",\n // because a `?distinct=1&` typo'd into `?distinct=ture` would otherwise\n // return duplicate rows while looking exactly like it had worked.\n const distinctVal = getLastValue(query.distinct);\n if (distinctVal !== undefined && distinctVal !== null && String(distinctVal) !== \"\") {\n const text = String(distinctVal).trim().toLowerCase();\n if (text !== \"true\" && text !== \"1\" && text !== \"false\" && text !== \"0\") {\n throw invalidParam(\n `Invalid \\`distinct\\` parameter: expected \\`true\\` or \\`false\\`, got ${JSON.stringify(String(distinctVal))}.`,\n \"INVALID_DISTINCT\"\n );\n }\n options.distinct = text === \"true\" || text === \"1\";\n }\n\n // `?count=exact|none` — whether a listing counts `meta.total`. Refused\n // rather than read as the default when it is neither: a `?count=nnone`\n // typo would otherwise pay for the count it was written to skip, and say\n // nothing.\n const countVal = getLastValue(query.count);\n if (countVal !== undefined && countVal !== null && String(countVal) !== \"\") {\n const text = String(countVal).trim().toLowerCase();\n if (text !== \"exact\" && text !== \"none\") {\n throw invalidParam(\n `Invalid \\`count\\` parameter: expected \\`exact\\` or \\`none\\`, got ${JSON.stringify(String(countVal))}.`,\n \"INVALID_COUNT\"\n );\n }\n options.count = text;\n }\n\n // ── Keyset cursor ──────────────────────────────────────────────────\n //\n // `?after=<meta.nextCursor>`. Decoded here so a malformed cursor is one\n // 400 in one place, and so the sort a cursor implies is settled before any\n // route reads `orderBy`: a request that names no sort adopts the cursor's,\n // and one that names a different sort is refused rather than seeked in an\n // order nobody asked for.\n const afterVal = getLastValue(query.after);\n if (afterVal !== undefined && afterVal !== null && String(afterVal).trim() !== \"\") {\n let cursor: DecodedCursor;\n try {\n cursor = decodeCursor(String(afterVal));\n } catch (e) {\n if (e instanceof CursorError) throw invalidParam(e.message, e.code);\n throw e;\n }\n try {\n const reconciled = reconcileCursorOrder(cursor, orderByEntriesToTuples(options.orderBy));\n options.orderBy = reconciled.map(([field, direction, nulls]) =>\n (nulls ? { field, direction, nulls } : { field, direction }));\n } catch (e) {\n if (e instanceof CursorMismatchError) throw invalidParam(e.message, e.code);\n throw e;\n }\n options.cursor = cursor;\n // A cursor and an offset describe the same window two incompatible\n // ways, and honouring both would start the page `offset` rows past\n // where the cursor pointed — a gap the caller cannot see.\n if (options.offset !== undefined) {\n throw invalidParam(\n \"`after` and `offset`/`page` cannot be combined: a cursor already says where the page \"\n + \"starts, and an offset on top of it skips rows. Use one or the other.\",\n \"CURSOR_WITH_OFFSET\"\n );\n }\n }\n\n // ── Vector similarity search ───────────────────────────────────────\n // Every rejection here is a malformed *request*, so it must carry a 400.\n // A bare `Error` reaches the handler with no `statusCode` and no known\n // `code`, which makes it a 500 — logged with a full stack as an incident,\n // and answered with \"An unexpected error occurred\", because the handler\n // only forwards a message to the client below 500. The caller was told\n // nothing about what it got wrong.\n const vectorSearchVal = getLastValue(query.vector_search);\n const vectorVal = getLastValue(query.vector);\n if (vectorSearchVal && vectorVal) {\n const vectorStr = String(vectorVal);\n let decoded: unknown;\n try {\n decoded = JSON.parse(vectorStr);\n } catch {\n decoded = undefined;\n }\n // Validated outside the `try` on purpose: inside it, the thrown\n // ApiError would be caught by its own `catch` and re-thrown as\n // something else.\n if (!Array.isArray(decoded) || !decoded.every(v => typeof v === \"number\")) {\n throw invalidParam(\n \"Invalid `vector` format. Expected a JSON array of numbers, e.g. [0.1,0.2,0.3]\",\n \"INVALID_VECTOR\"\n );\n }\n const queryVector = decoded as number[];\n\n const distanceParamVal = getLastValue(query.vector_distance);\n const distanceParam = distanceParamVal ? String(distanceParamVal) : \"cosine\";\n if (distanceParam !== \"cosine\" && distanceParam !== \"l2\" && distanceParam !== \"inner_product\") {\n throw invalidParam(\n `Invalid \\`vector_distance\\`: ${distanceParam}. Expected: cosine, l2, or inner_product`,\n \"INVALID_VECTOR_DISTANCE\"\n );\n }\n\n const vectorSearch: VectorSearchParams = {\n property: String(vectorSearchVal),\n vector: queryVector,\n distance: distanceParam\n };\n\n const thresholdVal = getLastValue(query.vector_threshold);\n if (thresholdVal) {\n const threshold = parseFloat(String(thresholdVal));\n if (isNaN(threshold)) {\n throw invalidParam(\n \"Invalid `vector_threshold`. Expected a number.\",\n \"INVALID_VECTOR_THRESHOLD\"\n );\n }\n vectorSearch.threshold = threshold;\n }\n\n options.vectorSearch = vectorSearch;\n }\n\n // Resolve the limit LAST — once we know whether this is a vector search —\n // so a client-supplied limit above the ceiling is refused with a 400 and an\n // absent one falls back to the correct mode default (plain/text =\n // defaultLimit, vector = 10). Without this a bare `GET /<collection>` would\n // return the whole table. Shared with the WebSocket ingress via\n // `resolveClientListLimit`.\n options.limit = resolveListLimitParam(rawLimit, {\n vectorSearch: !!options.vectorSearch,\n defaultLimit: limits.defaultLimit,\n maxLimit: limits.maxLimit\n });\n\n // Every field the request named, against what this caller may read. Last,\n // so a malformed parameter is still answered as malformed rather than as a\n // permission problem.\n if (access) assertQueryFieldsReadable(options, access.collection, access.viewer);\n\n return options;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,oBAAoB,YAAwC;CACxE,MAAM,SAAS,oBAAoB,UAAU;CAC7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