@lunora/do 1.0.0-alpha.53 → 1.0.0-alpha.55
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/index.d.mts +83 -6
- package/dist/index.d.ts +83 -6
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-BedcYTGD.mjs +1 -0
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-BcW3nUKL.mjs → DEFAULT_MAX_RELATION_KEYS-VxD8RtL0.mjs} +1 -1
- package/dist/packem_shared/MAX_SQL_ROWS-C3-CO4jz.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-BwZ7vXA6.mjs +1 -0
- package/dist/packem_shared/ROOT_DO_SIZE_WARN_BYTES-B7J9OycY.mjs +130 -0
- package/dist/packem_shared/applyOnDelete-DCeU2Jh0.mjs +1 -0
- package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-DATbmCh8.mjs +5 -0
- package/dist/packem_shared/schema-history-YGeVjyvV.mjs +24 -0
- package/dist/packem_shared/{serveRelationFanout-CK8xbCFx.mjs → serveRelationFanout-DBA2hP-k.mjs} +1 -1
- package/dist/packem_shared/sql-console-Cln4Xfju.mjs +2 -0
- package/package.json +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-CjgwJp2Q.mjs +0 -1
- package/dist/packem_shared/MAX_SQL_ROWS-Bdu25ASB.mjs +0 -2
- package/dist/packem_shared/NotUniqueError-BDYkMtJP.mjs +0 -1
- package/dist/packem_shared/ROOT_DO_SIZE_WARN_BYTES-jp8WQaE9.mjs +0 -101
- package/dist/packem_shared/applyOnDelete-CafQWSqu.mjs +0 -1
- package/dist/packem_shared/ctx-db-idempotency-wiVoGnpQ.mjs +0 -19
- package/dist/packem_shared/runShardMigrations-CcSFXtXZ.mjs +0 -5
package/dist/index.d.mts
CHANGED
|
@@ -294,17 +294,18 @@ declare const applyOnDelete: (options: ApplyOnDeleteOptions) => Promise<void>;
|
|
|
294
294
|
* before the row hits SQL.
|
|
295
295
|
*
|
|
296
296
|
* Skips fields the validator doesn't declare a `parse` for (the structural
|
|
297
|
-
* fakes used in DO/D1 unit tests omit it)
|
|
298
|
-
*
|
|
299
|
-
*
|
|
300
|
-
*
|
|
297
|
+
* fakes used in DO/D1 unit tests omit it), fields absent from the document, and
|
|
298
|
+
* — only when `tolerateStoredNull` is set, i.e. on the patch path — a `null` on
|
|
299
|
+
* an optional field (see below). The shape is iterated, not the document, so
|
|
300
|
+
* unknown fields pass through untouched — they're part of the JSON-blob shape
|
|
301
|
+
* but not part of the schema's declared columns.
|
|
301
302
|
*
|
|
302
303
|
* Lives here (alongside `applyOnDelete`) rather than in each backend's
|
|
303
304
|
* `ctx-db.ts` so DO + D1 share one implementation instead of two drift-prone
|
|
304
305
|
* copies. The signature is intentionally `validator.parse?` so the unit-test
|
|
305
306
|
* fakes (which never carry a runtime parser) keep working.
|
|
306
307
|
*/
|
|
307
|
-
declare const runRowValidators: (definition: TableDefinitionLike, document: Record<string, unknown
|
|
308
|
+
declare const runRowValidators: (definition: TableDefinitionLike, document: Record<string, unknown>, tolerateStoredNull?: boolean) => void;
|
|
308
309
|
type SortDirection = "asc" | "desc";
|
|
309
310
|
/** A single `{ field: "asc" | "desc" }` entry; `orderBy` is an ordered list of these. */
|
|
310
311
|
type OrderByInput = Record<string, SortDirection>;
|
|
@@ -1286,6 +1287,10 @@ declare const applyCdcChanges: (writer: DatabaseWriterLike, changes: ReadonlyArr
|
|
|
1286
1287
|
*/
|
|
1287
1288
|
declare const runShardMigrations: (sql: SqlExec, schema: SchemaLike, options?: {
|
|
1288
1289
|
cdc?: boolean;
|
|
1290
|
+
schemaSnapshot?: {
|
|
1291
|
+
hash: string;
|
|
1292
|
+
json: string;
|
|
1293
|
+
};
|
|
1289
1294
|
}) => void;
|
|
1290
1295
|
/** One shape member: its `_id` key plus the decoded document (id + creationTime merged in). */
|
|
1291
1296
|
interface ShapeRow {
|
|
@@ -3212,7 +3217,12 @@ declare const FLAGS_FUNCTION_PREFIX = "__lunora_flags__:";
|
|
|
3212
3217
|
*/
|
|
3213
3218
|
declare const ADMIN_FUNCTIONS: {
|
|
3214
3219
|
readonly applyCdc: "__lunora_admin__:applyCdc";
|
|
3220
|
+
readonly aiAvailable: "__lunora_admin__:aiAvailable";
|
|
3221
|
+
readonly aiChartConfig: "__lunora_admin__:aiChartConfig";
|
|
3222
|
+
readonly aiGenerateSql: "__lunora_admin__:aiGenerateSql";
|
|
3223
|
+
readonly aiTableFilter: "__lunora_admin__:aiTableFilter";
|
|
3215
3224
|
readonly assignIssue: "__lunora_admin__:assignIssue";
|
|
3225
|
+
readonly backRelationCounts: "__lunora_admin__:backRelationCounts";
|
|
3216
3226
|
readonly cdcSync: "__lunora_admin__:cdcSync";
|
|
3217
3227
|
readonly clearCapturedMail: "__lunora_admin__:clearCapturedMail";
|
|
3218
3228
|
readonly clearQueueMessages: "__lunora_admin__:clearQueueMessages";
|
|
@@ -3238,6 +3248,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
3238
3248
|
readonly getLogs: "__lunora_admin__:getLogs";
|
|
3239
3249
|
readonly getMetrics: "__lunora_admin__:getMetrics";
|
|
3240
3250
|
readonly getPitrBookmark: "__lunora_admin__:getPitrBookmark";
|
|
3251
|
+
readonly getQueryInsights: "__lunora_admin__:getQueryInsights";
|
|
3241
3252
|
readonly getQueueMessages: "__lunora_admin__:getQueueMessages";
|
|
3242
3253
|
readonly getRequestLog: "__lunora_admin__:getRequestLog";
|
|
3243
3254
|
readonly getSecurityAudit: "__lunora_admin__:getSecurityAudit";
|
|
@@ -3248,6 +3259,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
3248
3259
|
readonly importShard: "__lunora_admin__:importShard";
|
|
3249
3260
|
readonly listFlags: "__lunora_admin__:listFlags";
|
|
3250
3261
|
readonly listQueues: "__lunora_admin__:listQueues";
|
|
3262
|
+
readonly lintSql: "__lunora_admin__:lintSql";
|
|
3251
3263
|
readonly listTables: "__lunora_admin__:listTables";
|
|
3252
3264
|
readonly listWorkflows: "__lunora_admin__:listWorkflows";
|
|
3253
3265
|
readonly maskPolicies: "__lunora_admin__:maskPolicies";
|
|
@@ -3263,6 +3275,8 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
3263
3275
|
readonly replayQueueMessage: "__lunora_admin__:replayQueueMessage";
|
|
3264
3276
|
readonly resolveIssue: "__lunora_admin__:resolveIssue";
|
|
3265
3277
|
readonly rlsPolicies: "__lunora_admin__:rlsPolicies";
|
|
3278
|
+
readonly schemaHistory: "__lunora_admin__:schemaHistory";
|
|
3279
|
+
readonly schemaVersion: "__lunora_admin__:schemaVersion";
|
|
3266
3280
|
readonly runAs: "__lunora_admin__:runAs";
|
|
3267
3281
|
readonly runMigration: "__lunora_admin__:runMigration";
|
|
3268
3282
|
readonly runSql: "__lunora_admin__:runSql";
|
|
@@ -3536,6 +3550,8 @@ interface StudioFeaturesResult {
|
|
|
3536
3550
|
kv: boolean;
|
|
3537
3551
|
/** `@lunora/mail` is imported by a `lunora/` source or a declared dependency. */
|
|
3538
3552
|
mail: boolean;
|
|
3553
|
+
/** `@lunora/notify` / `ctx.notify` is used (a `lunora/notify.ts` config counts), or it is a declared dependency. */
|
|
3554
|
+
notifications: boolean;
|
|
3539
3555
|
/**
|
|
3540
3556
|
* `@lunora/payment` is used (import or `ctx.payments`), or the app declares the store's
|
|
3541
3557
|
* `subscriptions`/`events` tables that the Payments panel reads. Unlike the other flags this
|
|
@@ -6867,7 +6883,11 @@ declare abstract class ShardDO {
|
|
|
6867
6883
|
* overwritten here for the duration of the dispatch and restored after, so
|
|
6868
6884
|
* the forge can't leak into a later request. The target path is validated to
|
|
6869
6885
|
* be a non-admin function, so it can't be used to re-enter the admin plane.
|
|
6870
|
-
*
|
|
6886
|
+
*
|
|
6887
|
+
* Callers: the studio surfaces it behind a loopback-dev gate (`runAsIdentity`),
|
|
6888
|
+
* and `lunora run --as` dispatches through it from the CLI. That gate was
|
|
6889
|
+
* always UI-only — the server-side authority is, and remains, the admin
|
|
6890
|
+
* bearer check above.
|
|
6871
6891
|
*/
|
|
6872
6892
|
private handleRunAs;
|
|
6873
6893
|
/**
|
|
@@ -6984,6 +7004,57 @@ declare abstract class ShardDO {
|
|
|
6984
7004
|
* no binding at all and so records nothing.
|
|
6985
7005
|
*/
|
|
6986
7006
|
private handleExplainIssue;
|
|
7007
|
+
/**
|
|
7008
|
+
* Serve `__lunora_admin__:aiGenerateSql` — the SQL editor's opt-in
|
|
7009
|
+
* natural-language draft / repair.
|
|
7010
|
+
*
|
|
7011
|
+
* Grounds the prompt in this shard's REAL tables and columns, so the model
|
|
7012
|
+
* names things that exist rather than plausible fiction. The engine validates
|
|
7013
|
+
* its own output against the same read-only gate `runSql` enforces, so what
|
|
7014
|
+
* comes back here is already safe to hand the editor — and is handed over
|
|
7015
|
+
* UNEXECUTED regardless.
|
|
7016
|
+
*
|
|
7017
|
+
* Audited like every other privileged admin action: an AI-drafted statement
|
|
7018
|
+
* is still an operator asking the database a question.
|
|
7019
|
+
*/
|
|
7020
|
+
private handleGenerateSql;
|
|
7021
|
+
/** The AI-assistant admin writes, keyed by function path. */
|
|
7022
|
+
private aiAdminHandlers;
|
|
7023
|
+
/**
|
|
7024
|
+
* Serve `__lunora_admin__:aiTableFilter` — a natural-language filter for the
|
|
7025
|
+
* data browser, grounded in the browsed table's real columns.
|
|
7026
|
+
*
|
|
7027
|
+
* Returns STRUCTURED clauses, never SQL, so the browser's existing filter
|
|
7028
|
+
* validation and parameter binding apply unchanged.
|
|
7029
|
+
*/
|
|
7030
|
+
private handleAiTableFilter;
|
|
7031
|
+
/**
|
|
7032
|
+
* Serve `__lunora_admin__:aiAvailable` — does this deployment have an `AI`
|
|
7033
|
+
* binding at all?
|
|
7034
|
+
*
|
|
7035
|
+
* The studio asks ONCE on mount so it can decide whether to paint the
|
|
7036
|
+
* assistant affordances. Without it the only way to find out was to issue a
|
|
7037
|
+
* real request and read `no-ai-binding` off the failure — which meant an app
|
|
7038
|
+
* with no binding rendered "Draft SQL" and "Suggest chart" buttons that did
|
|
7039
|
+
* nothing until the operator clicked one, and only then made them vanish.
|
|
7040
|
+
*
|
|
7041
|
+
* Deliberately NOT part of `studioFeatures()`: those flags are computed at
|
|
7042
|
+
* codegen time from imports and declared dependencies, while a binding is a
|
|
7043
|
+
* runtime property of `env`. Folding a runtime probe into that codegen-owned
|
|
7044
|
+
* contract would make its drift guard meaningless.
|
|
7045
|
+
*
|
|
7046
|
+
* No model call, no audit entry — it reads one property off `env`.
|
|
7047
|
+
*/
|
|
7048
|
+
private handleAiAvailable;
|
|
7049
|
+
/**
|
|
7050
|
+
* Serve `__lunora_admin__:aiChartConfig` — infer a chart for a result set.
|
|
7051
|
+
*
|
|
7052
|
+
* The caller sends the result's SHAPE (column names, inferred types, row
|
|
7053
|
+
* count), never its values: per plan 202's Phase 0, inference running on the
|
|
7054
|
+
* user's own account is not the same as the operator expecting a model to
|
|
7055
|
+
* read their rows, and the shape is enough to choose an axis.
|
|
7056
|
+
*/
|
|
7057
|
+
private handleAiChartConfig;
|
|
6987
7058
|
/**
|
|
6988
7059
|
* Serve `__lunora_admin__:replayQueueMessage` — the studio's one-click replay /
|
|
6989
7060
|
* DLQ redrive. Looks the captured row up by id, resolves the destination export
|
|
@@ -7890,6 +7961,12 @@ declare const MAX_SQL_ROWS = 1e3;
|
|
|
7890
7961
|
* LunoraError the studio surfaces inline. Enforces: non-empty, a single
|
|
7891
7962
|
* statement (no `;`-separated batch), a leading `SELECT`/`WITH`/`EXPLAIN`, and no
|
|
7892
7963
|
* mutating/DDL keyword anywhere.
|
|
7964
|
+
*
|
|
7965
|
+
* The rules themselves live in `shared/sql-readonly.ts` because the studio's SQL
|
|
7966
|
+
* editor lints with the SAME function — a second copy here would drift, and the
|
|
7967
|
+
* drift would show up as an editor that green-lights a statement this gate then
|
|
7968
|
+
* refuses. This wrapper only turns the returned rejection into the tagged error
|
|
7969
|
+
* the runtime serializes.
|
|
7893
7970
|
*/
|
|
7894
7971
|
declare const assertReadonly: (query: string) => void;
|
|
7895
7972
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -294,17 +294,18 @@ declare const applyOnDelete: (options: ApplyOnDeleteOptions) => Promise<void>;
|
|
|
294
294
|
* before the row hits SQL.
|
|
295
295
|
*
|
|
296
296
|
* Skips fields the validator doesn't declare a `parse` for (the structural
|
|
297
|
-
* fakes used in DO/D1 unit tests omit it)
|
|
298
|
-
*
|
|
299
|
-
*
|
|
300
|
-
*
|
|
297
|
+
* fakes used in DO/D1 unit tests omit it), fields absent from the document, and
|
|
298
|
+
* — only when `tolerateStoredNull` is set, i.e. on the patch path — a `null` on
|
|
299
|
+
* an optional field (see below). The shape is iterated, not the document, so
|
|
300
|
+
* unknown fields pass through untouched — they're part of the JSON-blob shape
|
|
301
|
+
* but not part of the schema's declared columns.
|
|
301
302
|
*
|
|
302
303
|
* Lives here (alongside `applyOnDelete`) rather than in each backend's
|
|
303
304
|
* `ctx-db.ts` so DO + D1 share one implementation instead of two drift-prone
|
|
304
305
|
* copies. The signature is intentionally `validator.parse?` so the unit-test
|
|
305
306
|
* fakes (which never carry a runtime parser) keep working.
|
|
306
307
|
*/
|
|
307
|
-
declare const runRowValidators: (definition: TableDefinitionLike, document: Record<string, unknown
|
|
308
|
+
declare const runRowValidators: (definition: TableDefinitionLike, document: Record<string, unknown>, tolerateStoredNull?: boolean) => void;
|
|
308
309
|
type SortDirection = "asc" | "desc";
|
|
309
310
|
/** A single `{ field: "asc" | "desc" }` entry; `orderBy` is an ordered list of these. */
|
|
310
311
|
type OrderByInput = Record<string, SortDirection>;
|
|
@@ -1286,6 +1287,10 @@ declare const applyCdcChanges: (writer: DatabaseWriterLike, changes: ReadonlyArr
|
|
|
1286
1287
|
*/
|
|
1287
1288
|
declare const runShardMigrations: (sql: SqlExec, schema: SchemaLike, options?: {
|
|
1288
1289
|
cdc?: boolean;
|
|
1290
|
+
schemaSnapshot?: {
|
|
1291
|
+
hash: string;
|
|
1292
|
+
json: string;
|
|
1293
|
+
};
|
|
1289
1294
|
}) => void;
|
|
1290
1295
|
/** One shape member: its `_id` key plus the decoded document (id + creationTime merged in). */
|
|
1291
1296
|
interface ShapeRow {
|
|
@@ -3212,7 +3217,12 @@ declare const FLAGS_FUNCTION_PREFIX = "__lunora_flags__:";
|
|
|
3212
3217
|
*/
|
|
3213
3218
|
declare const ADMIN_FUNCTIONS: {
|
|
3214
3219
|
readonly applyCdc: "__lunora_admin__:applyCdc";
|
|
3220
|
+
readonly aiAvailable: "__lunora_admin__:aiAvailable";
|
|
3221
|
+
readonly aiChartConfig: "__lunora_admin__:aiChartConfig";
|
|
3222
|
+
readonly aiGenerateSql: "__lunora_admin__:aiGenerateSql";
|
|
3223
|
+
readonly aiTableFilter: "__lunora_admin__:aiTableFilter";
|
|
3215
3224
|
readonly assignIssue: "__lunora_admin__:assignIssue";
|
|
3225
|
+
readonly backRelationCounts: "__lunora_admin__:backRelationCounts";
|
|
3216
3226
|
readonly cdcSync: "__lunora_admin__:cdcSync";
|
|
3217
3227
|
readonly clearCapturedMail: "__lunora_admin__:clearCapturedMail";
|
|
3218
3228
|
readonly clearQueueMessages: "__lunora_admin__:clearQueueMessages";
|
|
@@ -3238,6 +3248,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
3238
3248
|
readonly getLogs: "__lunora_admin__:getLogs";
|
|
3239
3249
|
readonly getMetrics: "__lunora_admin__:getMetrics";
|
|
3240
3250
|
readonly getPitrBookmark: "__lunora_admin__:getPitrBookmark";
|
|
3251
|
+
readonly getQueryInsights: "__lunora_admin__:getQueryInsights";
|
|
3241
3252
|
readonly getQueueMessages: "__lunora_admin__:getQueueMessages";
|
|
3242
3253
|
readonly getRequestLog: "__lunora_admin__:getRequestLog";
|
|
3243
3254
|
readonly getSecurityAudit: "__lunora_admin__:getSecurityAudit";
|
|
@@ -3248,6 +3259,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
3248
3259
|
readonly importShard: "__lunora_admin__:importShard";
|
|
3249
3260
|
readonly listFlags: "__lunora_admin__:listFlags";
|
|
3250
3261
|
readonly listQueues: "__lunora_admin__:listQueues";
|
|
3262
|
+
readonly lintSql: "__lunora_admin__:lintSql";
|
|
3251
3263
|
readonly listTables: "__lunora_admin__:listTables";
|
|
3252
3264
|
readonly listWorkflows: "__lunora_admin__:listWorkflows";
|
|
3253
3265
|
readonly maskPolicies: "__lunora_admin__:maskPolicies";
|
|
@@ -3263,6 +3275,8 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
3263
3275
|
readonly replayQueueMessage: "__lunora_admin__:replayQueueMessage";
|
|
3264
3276
|
readonly resolveIssue: "__lunora_admin__:resolveIssue";
|
|
3265
3277
|
readonly rlsPolicies: "__lunora_admin__:rlsPolicies";
|
|
3278
|
+
readonly schemaHistory: "__lunora_admin__:schemaHistory";
|
|
3279
|
+
readonly schemaVersion: "__lunora_admin__:schemaVersion";
|
|
3266
3280
|
readonly runAs: "__lunora_admin__:runAs";
|
|
3267
3281
|
readonly runMigration: "__lunora_admin__:runMigration";
|
|
3268
3282
|
readonly runSql: "__lunora_admin__:runSql";
|
|
@@ -3536,6 +3550,8 @@ interface StudioFeaturesResult {
|
|
|
3536
3550
|
kv: boolean;
|
|
3537
3551
|
/** `@lunora/mail` is imported by a `lunora/` source or a declared dependency. */
|
|
3538
3552
|
mail: boolean;
|
|
3553
|
+
/** `@lunora/notify` / `ctx.notify` is used (a `lunora/notify.ts` config counts), or it is a declared dependency. */
|
|
3554
|
+
notifications: boolean;
|
|
3539
3555
|
/**
|
|
3540
3556
|
* `@lunora/payment` is used (import or `ctx.payments`), or the app declares the store's
|
|
3541
3557
|
* `subscriptions`/`events` tables that the Payments panel reads. Unlike the other flags this
|
|
@@ -6867,7 +6883,11 @@ declare abstract class ShardDO {
|
|
|
6867
6883
|
* overwritten here for the duration of the dispatch and restored after, so
|
|
6868
6884
|
* the forge can't leak into a later request. The target path is validated to
|
|
6869
6885
|
* be a non-admin function, so it can't be used to re-enter the admin plane.
|
|
6870
|
-
*
|
|
6886
|
+
*
|
|
6887
|
+
* Callers: the studio surfaces it behind a loopback-dev gate (`runAsIdentity`),
|
|
6888
|
+
* and `lunora run --as` dispatches through it from the CLI. That gate was
|
|
6889
|
+
* always UI-only — the server-side authority is, and remains, the admin
|
|
6890
|
+
* bearer check above.
|
|
6871
6891
|
*/
|
|
6872
6892
|
private handleRunAs;
|
|
6873
6893
|
/**
|
|
@@ -6984,6 +7004,57 @@ declare abstract class ShardDO {
|
|
|
6984
7004
|
* no binding at all and so records nothing.
|
|
6985
7005
|
*/
|
|
6986
7006
|
private handleExplainIssue;
|
|
7007
|
+
/**
|
|
7008
|
+
* Serve `__lunora_admin__:aiGenerateSql` — the SQL editor's opt-in
|
|
7009
|
+
* natural-language draft / repair.
|
|
7010
|
+
*
|
|
7011
|
+
* Grounds the prompt in this shard's REAL tables and columns, so the model
|
|
7012
|
+
* names things that exist rather than plausible fiction. The engine validates
|
|
7013
|
+
* its own output against the same read-only gate `runSql` enforces, so what
|
|
7014
|
+
* comes back here is already safe to hand the editor — and is handed over
|
|
7015
|
+
* UNEXECUTED regardless.
|
|
7016
|
+
*
|
|
7017
|
+
* Audited like every other privileged admin action: an AI-drafted statement
|
|
7018
|
+
* is still an operator asking the database a question.
|
|
7019
|
+
*/
|
|
7020
|
+
private handleGenerateSql;
|
|
7021
|
+
/** The AI-assistant admin writes, keyed by function path. */
|
|
7022
|
+
private aiAdminHandlers;
|
|
7023
|
+
/**
|
|
7024
|
+
* Serve `__lunora_admin__:aiTableFilter` — a natural-language filter for the
|
|
7025
|
+
* data browser, grounded in the browsed table's real columns.
|
|
7026
|
+
*
|
|
7027
|
+
* Returns STRUCTURED clauses, never SQL, so the browser's existing filter
|
|
7028
|
+
* validation and parameter binding apply unchanged.
|
|
7029
|
+
*/
|
|
7030
|
+
private handleAiTableFilter;
|
|
7031
|
+
/**
|
|
7032
|
+
* Serve `__lunora_admin__:aiAvailable` — does this deployment have an `AI`
|
|
7033
|
+
* binding at all?
|
|
7034
|
+
*
|
|
7035
|
+
* The studio asks ONCE on mount so it can decide whether to paint the
|
|
7036
|
+
* assistant affordances. Without it the only way to find out was to issue a
|
|
7037
|
+
* real request and read `no-ai-binding` off the failure — which meant an app
|
|
7038
|
+
* with no binding rendered "Draft SQL" and "Suggest chart" buttons that did
|
|
7039
|
+
* nothing until the operator clicked one, and only then made them vanish.
|
|
7040
|
+
*
|
|
7041
|
+
* Deliberately NOT part of `studioFeatures()`: those flags are computed at
|
|
7042
|
+
* codegen time from imports and declared dependencies, while a binding is a
|
|
7043
|
+
* runtime property of `env`. Folding a runtime probe into that codegen-owned
|
|
7044
|
+
* contract would make its drift guard meaningless.
|
|
7045
|
+
*
|
|
7046
|
+
* No model call, no audit entry — it reads one property off `env`.
|
|
7047
|
+
*/
|
|
7048
|
+
private handleAiAvailable;
|
|
7049
|
+
/**
|
|
7050
|
+
* Serve `__lunora_admin__:aiChartConfig` — infer a chart for a result set.
|
|
7051
|
+
*
|
|
7052
|
+
* The caller sends the result's SHAPE (column names, inferred types, row
|
|
7053
|
+
* count), never its values: per plan 202's Phase 0, inference running on the
|
|
7054
|
+
* user's own account is not the same as the operator expecting a model to
|
|
7055
|
+
* read their rows, and the shape is enough to choose an axis.
|
|
7056
|
+
*/
|
|
7057
|
+
private handleAiChartConfig;
|
|
6987
7058
|
/**
|
|
6988
7059
|
* Serve `__lunora_admin__:replayQueueMessage` — the studio's one-click replay /
|
|
6989
7060
|
* DLQ redrive. Looks the captured row up by id, resolves the destination export
|
|
@@ -7890,6 +7961,12 @@ declare const MAX_SQL_ROWS = 1e3;
|
|
|
7890
7961
|
* LunoraError the studio surfaces inline. Enforces: non-empty, a single
|
|
7891
7962
|
* statement (no `;`-separated batch), a leading `SELECT`/`WITH`/`EXPLAIN`, and no
|
|
7892
7963
|
* mutating/DDL keyword anywhere.
|
|
7964
|
+
*
|
|
7965
|
+
* The rules themselves live in `shared/sql-readonly.ts` because the studio's SQL
|
|
7966
|
+
* editor lints with the SAME function — a second copy here would drift, and the
|
|
7967
|
+
* drift would show up as an editor that green-lights a statement this gate then
|
|
7968
|
+
* refuses. This wrapper only turns the returned rejection into the tagged error
|
|
7969
|
+
* the runtime serializes.
|
|
7893
7970
|
*/
|
|
7894
7971
|
declare const assertReadonly: (query: string) => void;
|
|
7895
7972
|
/**
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,exportShardTable as t,importShardRows as a,parseExportShardArgs as s,parseImportShardArgs as n,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as p,matchesStaticWhere as d,normalizeCountArgument as E,throwingScheduler as _}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as m,coerceAggregateNumber as u,encodeAggregateKey as x,foldAggregateTally as I,readAggregateValue as f}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as R,mergeWhere as N,planAggregateLookup as g,selectIndexForAggregate as C,selectIndexForCount as M,selectIndexForGroupBy as h}from"./packem_shared/CountRlsUnsupportedError-Cl8XpYDL.mjs";import{AUTH_METRICS_BUCKETS_TABLE as F,AUTH_METRICS_BUCKET_MS as L,AUTH_METRICS_BUCKET_RETENTION as U,AUTH_METRICS_TABLE as D,ensureAuthMetricsTables as B,readAuthMetrics as b,recordAuthEvent as y}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{c as K,a as P,d as G}from"./packem_shared/context-telemetry-BFO0N_e4.mjs";import{NotUniqueError as W,assertValidClientId as v,createShardCtxDb as X,normalizeIdStructurally as w}from"./packem_shared/NotUniqueError-
|
|
1
|
+
import{exportShardRows as o,exportShardTable as t,importShardRows as a,parseExportShardArgs as s,parseImportShardArgs as n,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as T,aggregateSqlFunction as p,matchesStaticWhere as d,normalizeCountArgument as E,throwingScheduler as _}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as m,coerceAggregateNumber as u,encodeAggregateKey as x,foldAggregateTally as I,readAggregateValue as f}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as R,mergeWhere as N,planAggregateLookup as g,selectIndexForAggregate as C,selectIndexForCount as M,selectIndexForGroupBy as h}from"./packem_shared/CountRlsUnsupportedError-Cl8XpYDL.mjs";import{AUTH_METRICS_BUCKETS_TABLE as F,AUTH_METRICS_BUCKET_MS as L,AUTH_METRICS_BUCKET_RETENTION as U,AUTH_METRICS_TABLE as D,ensureAuthMetricsTables as B,readAuthMetrics as b,recordAuthEvent as y}from"./packem_shared/AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs";import{c as K,a as P,d as G}from"./packem_shared/context-telemetry-BFO0N_e4.mjs";import{NotUniqueError as W,assertValidClientId as v,createShardCtxDb as X,normalizeIdStructurally as w}from"./packem_shared/NotUniqueError-BwZ7vXA6.mjs";import{DATA_MIGRATION_STATE_TABLE as z,readMigrationStatus as Y,runDataMigration as V}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as Z,createDependencyTracker as j,depKey as J}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{renderSql as ee}from"./packem_shared/renderSql-B5lF5Jd9.mjs";import{diffExternalSource as oe}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{materializeExternalRows as ae,materializeExternalRowsIncremental as se,readExternalSourceBaseline as ne,runExternalSourceTick as ie}from"./packem_shared/materializeExternalRows-BUmj_9WO.mjs";import{isSoftDeleted as ce,isSourceDue as Te,liftSourceId as pe,pullExternalSourceIncrementalTick as de,pullExternalSourceTick as Ee}from"./packem_shared/isSoftDeleted-juJOq515.mjs";import{FUNCTION_METRICS_BUCKETS_TABLE as Se,FUNCTION_METRICS_BUCKET_MS as me,FUNCTION_METRICS_BUCKET_RETENTION as ue,FUNCTION_METRICS_INDEX_TABLE as xe,FUNCTION_METRICS_TABLE as Ie,ensureFunctionMetricsTables as fe,readFunctionMetricBuckets as Ae,readFunctionMetricIndexHits as Re,readFunctionMetrics as Ne,readFunctionMetricsTotals as ge,recordFunctionMetric as Ce}from"./packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs";import{GEO_DEFAULT_PRECISION as he,boundingBoxGeohashes as Oe,coveringGeohashes as Fe,encodeGeohash as Le,haversineMeters as Ue,pointInBoundingBox as De}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as be,ADMIN_FUNCTION_PREFIX as ye,FLAGS_FUNCTION_PREFIX as ke,RELATION_FUNCTION_PREFIX as Ke,facetColumn as Pe,listTables as Ge,readTablePage as He,selectMatchingIds as We}from"./packem_shared/ADMIN_FUNCTIONS-BedcYTGD.mjs";import{DEFAULT_EXPLAIN_ISSUE_MODEL as Xe,explainIssue as we,parseExplainIssueArgs as qe}from"./packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-Dicm4iLF.mjs";import{LogBuffer as Ye}from"./packem_shared/LogBuffer-bIvCelI-.mjs";import{MAIL_RETENTION as Qe,MAIL_TABLE as Ze,clearCapturedMail as je,ensureMailTable as Je,readCapturedMail as $e,recordCapturedMail as er}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{default as or}from"./packem_shared/NotFoundError-J3tjf4Uo.mjs";import{armRestore as ar,readBookmark as sr}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as ir,buildSeekWhere as lr,decodeCursor as cr,encodeCursor as Tr,normalizeOrderKeys as pr,softDeleteScope as dr}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{RANK_TIEBREAK as _r,encodePartitionKey as Sr,matchesRankStaticWhere as mr,rankTableName as ur,resolveRankPartition as xr,sortColumnName as Ir}from"./packem_shared/RANK_TIEBREAK-DtX8zQyc.mjs";import{ReactiveCache as Ar,reactiveCacheKey as Rr}from"./packem_shared/ReactiveCache-1_9Rs7J_.mjs";import{serveRelationFanout as gr}from"./packem_shared/serveRelationFanout-DBA2hP-k.mjs";import{DEFAULT_MAX_RELATION_KEYS as Mr,assertFlatPredicate as hr,assertShapeShardable as Or,containsRelationPredicate as Fr,isRelationPredicate as Lr,resolveRelationPredicates as Ur}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-VxD8RtL0.mjs";import{applyOnDelete as Br,fanOutScalarCounts as br,resolveWith as yr,runRowValidators as kr}from"./packem_shared/applyOnDelete-DCeU2Jh0.mjs";import{RLS_UNWRAP_SYMBOL as Pr,RlsRequiredError as Gr,guardWriter as Hr}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{o as vr,c as Xr,_ as wr}from"./packem_shared/security-audit-BKUOgE0x.mjs";import{SESSION_DO_TTL_DEFAULT as zr,SessionDO as Yr}from"./packem_shared/SESSION_DO_TTL_DEFAULT-GvBy_DBz.mjs";import{ROOT_DO_SIZE_WARN_BYTES as Qr,ROOT_SHARD_NAME as Zr,ShardDO as jr}from"./packem_shared/ROOT_DO_SIZE_WARN_BYTES-B7J9OycY.mjs";import{SHARD_REGISTRY_DO_NAME as $r,ShardRegistryDO as eo}from"./packem_shared/SHARD_REGISTRY_DO_NAME-Caa0fR4N.mjs";import{a as oo,u as to,d as ao}from"./packem_shared/sql-console-Cln4Xfju.mjs";import{createSystemReader as no}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as lo}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{hasTrigger as To,runTriggers as po}from"./packem_shared/hasTrigger-_rexbWMO.mjs";import{selectExpiredIds as _o}from"./packem_shared/selectExpiredIds-BXJDiUtz.mjs";import{compileWhereSql as mo}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{CDC_LOG_TABLE as xo,applyCdcChanges as Io,readCdcChanges as fo,trimCdcChanges as Ao}from"./packem_shared/CDC_LOG_TABLE-E_J5LPoK.mjs";import{H as No,P as go,X as Co}from"./packem_shared/ctx-db-backfill-C4rAzsQo.mjs";import{runShardMigrations as ho}from"./packem_shared/runShardMigrations-DATbmCh8.mjs";import{stableStringify as Fo}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Uo}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";import{subscriptionListDeltas as Bo}from"./packem_shared/subscriptionListDeltas-Bs69JbA8.mjs";export{be as ADMIN_FUNCTIONS,ye as ADMIN_FUNCTION_PREFIX,T as AGGREGATE_SQL_FUNCTION,F as AUTH_METRICS_BUCKETS_TABLE,L as AUTH_METRICS_BUCKET_MS,U as AUTH_METRICS_BUCKET_RETENTION,D as AUTH_METRICS_TABLE,xo as CDC_LOG_TABLE,lo as ConflictError,R as CountRlsUnsupportedError,z as DATA_MIGRATION_STATE_TABLE,Xe as DEFAULT_EXPLAIN_ISSUE_MODEL,Mr as DEFAULT_MAX_RELATION_KEYS,ke as FLAGS_FUNCTION_PREFIX,Se as FUNCTION_METRICS_BUCKETS_TABLE,me as FUNCTION_METRICS_BUCKET_MS,ue as FUNCTION_METRICS_BUCKET_RETENTION,xe as FUNCTION_METRICS_INDEX_TABLE,Ie as FUNCTION_METRICS_TABLE,he as GEO_DEFAULT_PRECISION,Ye as LogBuffer,Qe as MAIL_RETENTION,Ze as MAIL_TABLE,oo as MAX_SQL_ROWS,vr as MIN_ADMIN_TOKEN_LENGTH,Xr as MIN_AUTH_SECRET_LENGTH,or as NotFoundError,W as NotUniqueError,_r as RANK_TIEBREAK,Ke as RELATION_FUNCTION_PREFIX,Pr as RLS_UNWRAP_SYMBOL,Qr as ROOT_DO_SIZE_WARN_BYTES,Zr as ROOT_SHARD_NAME,Ar as ReactiveCache,Gr as RlsRequiredError,Z as SCAN_DEP,zr as SESSION_DO_TTL_DEFAULT,$r as SHARD_REGISTRY_DO_NAME,Yr as SessionDO,jr as ShardDO,eo as ShardRegistryDO,p as aggregateSqlFunction,m as aggregateTableName,Io as applyCdcChanges,Br as applyOnDelete,ir as applySelect,ar as armRestore,hr as assertFlatPredicate,to as assertReadonly,Or as assertShapeShardable,v as assertValidClientId,No as backfillAggregateIndexes,go as backfillRankIndexes,Co as backfillSearchIndexes,Oe as boundingBoxGeohashes,wr as buildSecurityAudit,lr as buildSeekWhere,je as clearCapturedMail,u as coerceAggregateNumber,mo as compileWhereSql,Fr as containsRelationPredicate,Fe as coveringGeohashes,j as createDependencyTracker,K as createMetrics,X as createShardCtxDb,no as createSystemReader,P as createTracer,cr as decodeCursor,J as depKey,oe as diffExternalSource,G as dispatchRootSpan,x as encodeAggregateKey,Tr as encodeCursor,Le as encodeGeohash,Sr as encodePartitionKey,B as ensureAuthMetricsTables,fe as ensureFunctionMetricsTables,Je as ensureMailTable,we as explainIssue,o as exportShardRows,t as exportShardTable,Pe as facetColumn,br as fanOutScalarCounts,I as foldAggregateTally,Hr as guardWriter,To as hasTrigger,Ue as haversineMeters,a as importShardRows,Lr as isRelationPredicate,ce as isSoftDeleted,Te as isSourceDue,pe as liftSourceId,Ge as listTables,mr as matchesRankStaticWhere,d as matchesStaticWhere,ae as materializeExternalRows,se as materializeExternalRowsIncremental,N as mergeWhere,E as normalizeCountArgument,w as normalizeIdStructurally,pr as normalizeOrderKeys,qe as parseExplainIssueArgs,s as parseExportShardArgs,n as parseImportShardArgs,g as planAggregateLookup,De as pointInBoundingBox,de as pullExternalSourceIncrementalTick,Ee as pullExternalSourceTick,ur as rankTableName,Rr as reactiveCacheKey,f as readAggregateValue,b as readAuthMetrics,sr as readBookmark,$e as readCapturedMail,fo as readCdcChanges,ne as readExternalSourceBaseline,Ae as readFunctionMetricBuckets,Re as readFunctionMetricIndexHits,Ne as readFunctionMetrics,ge as readFunctionMetricsTotals,Y as readMigrationStatus,He as readTablePage,y as recordAuthEvent,er as recordCapturedMail,Ce as recordFunctionMetric,ee as renderSql,xr as resolveRankPartition,Ur as resolveRelationPredicates,yr as resolveWith,V as runDataMigration,ie as runExternalSourceTick,ao as runReadonlySql,kr as runRowValidators,ho as runShardMigrations,po as runTriggers,_o as selectExpiredIds,i as selectExportTables,C as selectIndexForAggregate,M as selectIndexForCount,h as selectIndexForGroupBy,We as selectMatchingIds,gr as serveRelationFanout,dr as softDeleteScope,Ir as sortColumnName,Fo as stableStringify,Uo as stableWireKey,Bo as subscriptionListDeltas,_ as throwingScheduler,Ao as trimCdcChanges,l as validateImportRow};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as M}from"@lunora/errors";import{q as d}from"./quote-identifier-CGiYFBvY.mjs";const K="__lunora_admin__:",X="__lunora_relation__:",Y="__lunora_flags__:",z={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},N=50,b=500,x=30,F=200,m="__doc__",w=e=>{try{const a=JSON.parse(e);return a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0}catch{return}},L=(e,a)=>{if(!e.includes(m))return{columns:e,rows:a};const r=[];for(const s of a){const _=s[m],i=typeof _=="string"?w(_):void 0;if(i===void 0)return{columns:e,rows:a};const u=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));r.push({...u,...i})}const t=e.filter(s=>s!==m),n=[],o=new Set(t);for(const s of r)for(const _ of Object.keys(s))o.has(_)||(o.add(_),n.push(_));return{columns:[...t,...n],rows:r}},O=e=>e.replaceAll(/[\\%_]/g,a=>`\\${a}`),S=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),I=(e,a,r)=>Math.min(Math.max(e,a),r),k=(e,a)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${a}`).one();return Number(r.c)},V=e=>{const a=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:t}of a)S(t)||r.push({name:t,rowCount:k(e,d(t))});return r},A=(e,a)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",a).toArray().length>0,P={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},U=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",T=(e,a)=>{const r=a.includes(e),t=a.includes(m);if(!(!r&&!t))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$."${e.replaceAll('"','""')}"`]}},W=(e,a)=>{const r=T(e.column,a);if(r===void 0)return;const{expression:t,params:n}=r;return e.operator==="contains"?{params:[...n,`%${O(U(e.value))}%`],sql:String.raw`CAST(${t} AS TEXT) LIKE ? ESCAPE '\'`}:{params:[...n,e.value],sql:`${t} ${P[e.operator]} ?`}},D=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,q=e=>{const a=D.exec(e.trim());if(a===null)return;const r=Number(a[1]),t=a[2]===void 0?void 0:Number(a[2]),n=a[3]===void 0?void 0:Number(a[3]);if(t!==void 0&&(t<1||t>12)||n!==void 0&&(n<1||n>31)||r<100)return;const o=Date.UTC(r,(t??1)-1,n??1);if(n!==void 0&&new Date(o).getUTCDate()!==n)return;let s;return n!==void 0?s=Date.UTC(r,t===void 0?0:t-1,n+1):t===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,t,1),{from:o,to:s}},v=(e,a,r)=>{const t=[],n=[];if(a!==""&&e.length>0){const o=`%${O(a)}%`,s=e.map(i=>String.raw`CAST(${d(i)} AS TEXT) LIKE ? ESCAPE '\'`);n.push(...e.map(()=>o));const _=q(a);if(_!==void 0)for(const i of e)s.push(`(${d(i)} >= ? AND ${d(i)} < ?)`),n.push(_.from,_.to);t.push(`(${s.join(" OR ")})`)}for(const o of r??[]){const s=W(o,e);s!==void 0&&(t.push(`(${s.sql})`),n.push(...s.params))}return t.length===0?void 0:{parameters:n,where:t.join(" AND ")}},Q=(e,a)=>{if(e===void 0)return;const r=T(e.column,a);if(r===void 0)return;const t=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${t}`}},J=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new M("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=I(Math.trunc(a.limit??N),1,b),n=Math.max(0,Math.trunc(a.offset??0)),o=d(r),s=e.exec(`PRAGMA table_info(${o})`).toArray().map(h=>h.name),_=a.search?.trim()??"",i=h=>{if(a.refs===void 0)return h;const C={};for(const $ of h.columns){const R=a.refs[$];R!==void 0&&(C[$]=R)}return Object.keys(C).length>0?{...h,refs:C}:h},u=v(s,_,a.filters),l=Q(a.orderBy,s),c=u===void 0?"":` WHERE ${u.where}`,f=l===void 0?"":` ORDER BY ${l.sql}`,g=u?.parameters??[],E=l?.params??[];let p;a.skipCount||(p=u===void 0?k(e,o):Number(e.exec(`SELECT COUNT(*) AS c FROM ${o}${c}`,...g).one().c));const y=e.exec(`SELECT * FROM ${o}${c}${f} LIMIT ? OFFSET ?`,...g,...E,t,n).toArray();return i({...L(s,y),total:p})},Z=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new M("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=I(Math.trunc(a.limit??b),1,b),n=d(r),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(c=>c.name),s=a.search?.trim()??"",_=v(o,s,a.filters),i=_===void 0?e.exec(`SELECT id FROM ${n} LIMIT ?`,t+1).toArray():e.exec(`SELECT id FROM ${n} WHERE ${_.where} LIMIT ?`,..._.parameters,t+1).toArray(),u=i.length>t,l=(u?i.slice(0,t):i).map(c=>c.id);return{hasMore:u,ids:l}},j=(e,a,r)=>{const t=new Set(r.filter(o=>o!==m));if(!r.includes(m))return t;const n=e.exec(`SELECT ${d(m)} AS doc FROM ${a} LIMIT ?`,b).toArray();for(const{doc:o}of n){const s=typeof o=="string"?w(o):void 0;if(s!==void 0)for(const _ of Object.keys(s))t.add(_)}return t},ee=(e,a)=>{const{column:r,table:t}=a;if(S(t)||!A(e,t))throw new M("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404});const n=d(t),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(p=>p.name);if(!j(e,n,o).has(r))throw new M("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=T(r,o);if(s===void 0)throw new M("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const _=I(Math.trunc(a.limit??x),1,F),i=a.search?.trim()??"",u=v(o,i,a.filters),l=u===void 0?"":` WHERE ${u.where}`,c=u?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${n}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray(),g=f.length>_,E=g?f.slice(0,_):f;return{truncated:g,values:E.map(p=>({count:Number(p.count),value:p.value}))}},ae=(e,a,r)=>{const t={},n=r.slice(0,b);for(const s of n)t[s]=[];if(n.length===0)return{references:t,storageColumns:a};const o=n.map(()=>"?").join(", ");for(const[s,_]of Object.entries(a)){if(S(s)||!A(e,s))continue;const i=d(s),u=e.exec(`PRAGMA table_info(${i})`).toArray().map(l=>l.name);for(const l of _){const c=T(l,u);if(c===void 0)continue;const f=e.exec(`SELECT id, ${c.expression} AS ref FROM ${i} WHERE ${c.expression} IN (${o})`,...c.params,...c.params,...n).toArray();for(const g of f)t[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:t,storageColumns:a}},te=e=>{const a=e.map((t,n)=>{const o=Object.values(t.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:t.admin===!0,id:n,subscriptions:o}}),r=a.reduce((t,n)=>t+n.subscriptions.length,0);return{connections:a,totalConnections:a.length,totalSubscriptions:r}},B=20,re=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),se=(e,a,r,t)=>({maxMs:Math.max(e.maxMs,t),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,a),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+a,totalMs:e.totalMs+t}),ne=(e,a=B)=>{const r=new Map,t=new Map;for(const o of e){for(const s of Object.values(o.shapes??{})){const _=s.name??"(unknown shape)";r.set(_,(r.get(_)??0)+1)}for(const s of o.whispers??[])t.set(s,(t.get(s)??0)+1)}const n=[...[...r].map(([o,s])=>({kind:"shape",subscribers:s,topic:o})),...[...t].map(([o,s])=>({kind:"whisper",subscribers:s,topic:o}))];return n.sort((o,s)=>s.subscribers-o.subscribers||o.topic.localeCompare(s.topic)),{peakSubscribers:n[0]?.subscribers??0,topics:n.slice(0,a),totalConnections:e.length}};export{z as ADMIN_FUNCTIONS,K as ADMIN_FUNCTION_PREFIX,B as DEFAULT_FANOUT_TOPIC_LIMIT,Y as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,X as RELATION_FUNCTION_PREFIX,re as createFanoutCounters,q as datePrefixRange,ee as facetColumn,ae as findStorageReferences,V as listTables,J as readTablePage,se as recordFanoutPass,Z as selectMatchingIds,ne as summarizeFanoutTopics,te as summarizeSubscriptions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{distinctValues as O}from"./applyOnDelete-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{distinctValues as O}from"./applyOnDelete-DCeU2Jh0.mjs";const k="__relationExists",f={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},R=new Set(Object.keys(f)),A=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},j=5e3,u=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],g=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>R.has(n))},d=(e,t,n)=>{const a=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const r=e[s];return s==="AND"||s==="OR"?b(r).some(o=>d(o,t,n)):s==="NOT"?d(r??{},t,n):!!a[s]&&p(r)})},I=(e,t,n,a)=>{if(e&&d(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${a}() — use them in findMany/findFirst or an RLS read policy`)},E=async(e,t,n,a,s)=>{const r=await c(t,e.table,a),{page:o}=await a.fetcher(e.table,{baseWhere:a.relationBaseWhere?.(e.table),relationBaseWhere:a.relationBaseWhere,where:r}),i=O(o,n);if(i.length>a.maxRelationKeys){if(s)return u;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(a.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},T=async(e,t,n,a,s)=>{const r=f[e];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);const{clause:o,project:i}=A(t),l=await E(t,r.negateChild?{NOT:n}:n,i,a,s);return l===u?u:r.negated?r.nullDisjunct?{OR:[{[o]:{notIn:l}},{[o]:{isNull:!0}}]}:{[o]:{notIn:l}}:{[o]:{in:l}}},m=async(e,t,n,a,s)=>{const r=f[e];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);const o=s.relationBaseWhere?.(t.table),i=r.negateChild?{NOT:n}:n,l={childWhere:await c(o?{AND:[o,i]}:i,t.table,s),negated:r.negated,parentTable:a,relation:t};return{[k]:l}},$=(e,t,n)=>{const a=f[e];if(a&&a.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${a.kind} relation, but "${t}" is to-${n.kind}`)},x=async(e,t,n,a,s)=>{const r=[];for(const o of Object.keys(n)){$(o,e,t);const i=n[o]??{},l=s.canPushExists?.(t)??!1;if(l&&s.existsPushMode==="always"){r.push(await m(o,t,i,a,s));continue}const w=await T(o,t,i,s,l);w===u?r.push(await m(o,t,i,a,s)):r.push(w)}return g(r)},S=async(e,t,n,a)=>{if(e==="AND"||e==="OR"){const r=[];for(const o of b(t))r.push(await c(o,n,a));return{[e]:r}}if(e==="NOT")return{NOT:await c(t??{},n,a)};const s=a.schema.tables[n]?.relationMap?.[e];return s&&p(t)?x(e,s,t,n,a):{[e]:t}},c=async(e,t,n)=>{const a=[];for(const s of Object.keys(e))a.push(await S(s,e[s],t,n));return g(a)},L=async(e,t)=>!e||!d(e,t.schema,t.tableName)?e:c(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??j,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),y=(e,t,n)=>{for(const a of e){const s=N(a,t,n);if(s)return s}},D=(e,t,n,a)=>{if(e==="AND"||e==="OR")return y(b(t),n,a);if(e==="NOT")return y([t??{}],n,a);const s=n.tables[a]?.relationMap?.[e];if(!(!s||!p(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:y(Object.values(t),n,s.table)},N=(e,t,n)=>{for(const a of Object.keys(e)){const s=D(a,e[a],t,n);if(s)return s}},M=(e,t,n)=>{if(!e)return;const a=N(e,t,n);if(a)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${a.target}" via relation "${a.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${a.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{j as DEFAULT_MAX_RELATION_KEYS,I as assertFlatPredicate,M as assertShapeShardable,d as containsRelationPredicate,p as isRelationPredicate,L as resolveRelationPredicates};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"@lunora/errors";import{a as s,u as e,y as n,d as r}from"./sql-console-Cln4Xfju.mjs";export{s as MAX_SQL_ROWS,e as assertReadonly,n as lintReadonlySql,r as runReadonlySql};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{searchTextUnchanged as Tt,ftsTableName as dt,FTS_ID_COLUMN as be,FTS_TEXT_COLUMN as Nt,analyzedSearchText as ct,createSearchBuilder as St,createSearchAnalyzer as Ve,planSearchPage as Rt,finishSearchPage as At,searchPageScan as It,resolveSearchScan as vt,assertSearchWithinCap as Ct,tokenizeSearch as ft,searchTermRange as kt,scoreDocument as Mt,MAX_SEARCH_SCAN as Lt}from"@lunora/search-core";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as Fe,aggregateSqlFunction as Ne,normalizeCountArgument as xt,throwingScheduler as Ot}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as de,foldAggregateTally as Dt,aggregateTableName as Se,coerceAggregateNumber as qe,readAggregateValue as Ue}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as re,CountRlsUnsupportedError as Pe,selectIndexForGroupBy as Wt,selectIndexForCount as Bt,selectIndexForAggregate as Ft}from"./CountRlsUnsupportedError-Cl8XpYDL.mjs";import{Y as qt}from"./ctx-db-backfill-C4rAzsQo.mjs";import{o as fi,H as ui,P as hi,X as $i}from"./ctx-db-backfill-C4rAzsQo.mjs";import{appendCdcChange as Ut}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{CDC_LOG_TABLE as mi,applyCdcChanges as wi,bumpCdcEpoch as gi,minCdcSeq as Ei,readCdcChanges as bi,readCdcCursor as yi,readCdcEpoch as _i,trimCdcChanges as Ti}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{r as M}from"./do-exec-BLe9lLrN.mjs";import{b as ut,s as Z,g as he,a as ce,_ as te,m as X,T as ht,E as Le,$ as ee,l as Pt,L as $t,N as pt,S as Xe}from"./do-sql-x0AjZhaN.mjs";import{param as Ye}from"./renderSql-B5lF5Jd9.mjs";import{encodeGeohash as Ht,GEO_DEFAULT_PRECISION as jt,coveringGeohashes as Gt,boundingBoxGeohashes as Jt,pointInBoundingBox as Vt,haversineMeters as Yt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{sortColumnName as Ae,matchesRankStaticWhere as mt,encodePartitionKey as De,rankTableName as Ie,resolveRankPartition as wt,RANK_TIEBREAK as me}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{t as fe}from"./serialize-sql-DiRzL7A4.mjs";import{SCAN_DEP as Q}from"./SCAN_DEP-D_yR9EeV.mjs";import{decodeCursor as Oe,normalizeOrderKeys as zt,buildSeekWhere as gt,applySelect as Ze,encodeCursor as Ge,softDeleteScope as Ee,buildSeekBeforeWhere as Kt}from"./applySelect-B0CF8T7y.mjs";import Qt from"./NotFoundError-J3tjf4Uo.mjs";import{assertFlatPredicate as He,resolveRelationPredicates as et}from"./DEFAULT_MAX_RELATION_KEYS-VxD8RtL0.mjs";import{runRowValidators as je,resolveWith as tt,applyOnDelete as Xt,fanOutScalarCounts as Zt}from"./applyOnDelete-DCeU2Jh0.mjs";import{guardWriter as en}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as tn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as nn}from"./hasTrigger-_rexbWMO.mjs";import{compileWhereSql as ue}from"./compileWhereSql-BLcfs4QW.mjs";import{e as Si,t as Ri,r as Ai,o as Ii,l as vi,p as Ci,_ as ki,a as Mi,b as Li,d as xi,m as Oi,c as Di,S as Wi,T as Bi}from"./schema-history-YGeVjyvV.mjs";import{runShardMigrations as qi}from"./runShardMigrations-DATbmCh8.mjs";import{a as Pi,s as Hi}from"./ctx-db-shapes-CHC2cS0g.mjs";const on=(o,r,n)=>[...o.partitionBy??[],...o.sortBy.map(l=>l.field),...o.where?Object.keys(o.where):[]].every(l=>r[l]===n[l]),rn=(o,r,n,l,s,c)=>{if(s&&c&&on(n,s,c))return;const E=Ie(r,n.name);if(s&&M(o,e`DELETE FROM ${e.identifier(E)} WHERE ${e.identifier("__id__")} = ${l}`),!c||n.where&&!mt(c,n.where))return;const m=n.sortBy.map((b,h)=>Ae(h)),_=e.join(["__id__","__partition__",...m].map(b=>e.identifier(b)),e`, `),v=De(n.partitionBy??[],c),L=n.sortBy.map(b=>fe(c[b.field]??null)),T=e.join([l,v,...L].map(b=>Ye(b)),e`, `);M(o,e`INSERT INTO ${e.identifier(E)} (${_}) VALUES (${T})`)},an=o=>{const{broadcast:r,invalidateCache:n,recordCdc:l,schema:s,sql:c}=o,E=new Set,m=new Set,_=(N,w)=>{const S=`${N}::${w.name}`;if(E.has(S))return;const F=Se(N,w.name),W=w.by??[],j=new Map,q=M(c,e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(N)}`).toArray();for(const U of q){const x=he(U);if(!x||w.where&&!Fe(x,w.where))continue;const G=de(W,x);Dt(j,G,w,x)}M(c,e`DELETE FROM ${e.identifier(F)}`);const J=32,B=[...j];for(let U=0;U<B.length;U+=J){const x=B.slice(U,U+J),G=e.join(x.map(([H,Y])=>e`(${H}, ${Y.value}, ${Y.count})`),e`, `);M(c,e`INSERT INTO ${e.identifier(F)} (${ce}, ${te}, ${X}) VALUES ${G}`)}E.add(S)},v=(N,w,S)=>{const F=w.by??[],W=Ne(w.op),j=w.field??"",q=[];for(const U of F){const x=fe(S[U]??null);x===null?q.push(e`${ee(U)} IS NULL`):q.push(e`${ee(U)} = ${x}`)}for(const[U,x]of Object.entries(w.where??{})){const G=x!==null&&typeof x=="object"&&!Array.isArray(x)?x.eq:x,H=fe(G);H===null?q.push(e`${ee(U)} IS NULL`):q.push(e`${ee(U)} = ${H}`)}const J=q.length>0?e` WHERE ${e.join(q,e` AND `)}`:e``,B=ee(j);return{value:M(c,e`SELECT ${e.raw(W)}(${B}) AS value FROM ${e.identifier(N)}${J}`).one().value??null}},L=(N,w,S,F)=>{const W=Se(N,w.name),{op:j}=w,q=w.field??"",J=x=>{M(c,e`DELETE FROM ${e.identifier(W)} WHERE ${ce} = ${x} AND ${X} <= 0`)},B=S&&(!w.where||Fe(S,w.where))?S:void 0,U=F&&(!w.where||Fe(F,w.where))?F:void 0;if(!(!B&&!U)){if(j==="count"){for(const[x,G]of[[B,-1],[U,1]]){if(!x)continue;const H=de(w.by??[],x);M(c,Le(W,H,G,G,e`${te} = ${te} + excluded.${te}, ${X} = ${X} + excluded.${X}`))}B&&J(de(w.by??[],B));return}if(j==="sum"||j==="avg"){for(const[x,G]of[[B,-1],[U,1]]){if(!x)continue;const H=qe(x[q]);if(H===void 0)continue;const Y=de(w.by??[],x);M(c,Le(W,Y,G*H,G,e`${te} = COALESCE(${te}, 0) + excluded.${te}, ${X} = ${X} + excluded.${X}`))}B&&J(de(w.by??[],B));return}if(B){const x=de(w.by??[],B),G=qe(B[q]),H=M(c,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(W)} WHERE ${ce} = ${x}`).toArray()[0],Y=(H?.count??0)-1;if(Y<=0)M(c,e`DELETE FROM ${e.identifier(W)} WHERE ${ce} = ${x}`);else if(H&&G!==void 0&&H.value!==null&&G===H.value){const ie=v(N,w,B);M(c,e`UPDATE ${e.identifier(W)} SET ${te} = ${ie.value}, ${X} = ${Y} WHERE ${ce} = ${x}`)}else M(c,e`UPDATE ${e.identifier(W)} SET ${X} = ${X} - 1 WHERE ${ce} = ${x}`)}if(U){const x=de(w.by??[],U),G=qe(U[q]);if(G===void 0)M(c,Le(W,x,null,1,e`${X} = ${X} + 1`));else{const H=j==="min"?"MIN":"MAX";M(c,Le(W,x,G,1,e`${te} = ${e.raw(H)}(COALESCE(${te}, excluded.${te}), excluded.${te}), ${X} = ${X} + 1`))}}}},T=N=>{const w=s.tables[N]?.aggregateIndexes;if(!(!w||w.length===0))for(const S of w)_(N,S)},b=(N,w,S)=>{const F=s.tables[N]?.aggregateIndexes;if(!(!F||F.length===0))for(const W of F)L(N,W,w,S)},h=(N,w)=>{const S=`${N}::rank::${w.name}`;if(m.has(S))return;const F=Ie(N,w.name),W=M(c,e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(N)}`).toArray();M(c,e`DELETE FROM ${e.identifier(F)}`);const j=w.sortBy.map((J,B)=>Ae(B)),q=e.join(["__id__","__partition__",...j].map(J=>e.identifier(J)),e`, `);for(const J of W){const B=he(J);if(!B||w.where&&!mt(B,w.where))continue;const U=De(w.partitionBy??[],B),x=w.sortBy.map(H=>fe(B[H.field]??null)),G=e.join([B._id,U,...x].map(H=>Ye(H)),e`, `);M(c,e`INSERT INTO ${e.identifier(F)} (${q}) VALUES (${G})`)}m.add(S)},k=N=>{const w=s.tables[N]?.rankIndexes;if(!(!w||w.length===0))for(const S of w)h(N,S)},C=(N,w,S,F)=>{const W=s.tables[N]?.rankIndexes;if(!(!W||W.length===0))for(const j of W)rn(c,N,j,w,S,F)},I=(N,w,S,F)=>{const W=s.tables[N]?.searchIndexes;if(!(!W||W.length===0||!ut(c)))for(const j of W){if(Tt(F,S,j))continue;const q=dt(N,j.name);M(c,e`DELETE FROM ${e.identifier(q)} WHERE ${e.identifier(be)} = ${w}`),S&&M(c,e`INSERT INTO ${e.identifier(q)} (${e.identifier(Nt)}, ${e.identifier(be)}) VALUES (${ct(S,j)}, ${w})`)}},P=(N,w,S)=>{const F=s.tables[N]?.geoIndexes;if(!(!F||F.length===0))for(const W of F){const j=ht(N,W.name);M(c,e`DELETE FROM ${e.identifier(j)} WHERE ${e.identifier("__id__")} = ${w}`);const q=S?.[W.field];if(q!==null&&typeof q=="object"&&typeof q.lat=="number"&&typeof q.lng=="number"){const{lat:J,lng:B}=q,U=Ht({lat:J,lng:B},W.precision??jt);M(c,e`INSERT INTO ${e.identifier(j)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${w}, ${U}, ${J}, ${B})`)}}};return{ensureBackfilledForTable:T,ensureBackfilledIndex:_,ensureRankBackfilled:h,ensureRankBackfilledForTable:k,syncAggregates:b,syncCompanionsForInsert:(N,w,S)=>{I(N,w,S),P(N,w,S),b(N,void 0,S),C(N,w,void 0,S),n(N,w),l(N,w,"insert",S),r({key:w,op:"insert",row:S,table:N})},syncGeo:P,syncRanks:C,syncSearch:I}},sn="__doc__",ln=o=>{const r=JSON.stringify(o),n=new TextEncoder().encode(r);let l="";for(const s of n)l+=String.fromCodePoint(s);return btoa(l)},dn=o=>o.after?[o.after.partitionKey,...o.after.sortValues,o.after.rowId]:o.cursor?Oe(o.cursor):void 0,cn=(o,r,n)=>{if(o?.length!==1+r.length+1)return;const l=[{column:"__partition__",direction:"asc"}];for(const[c,E]of r.entries())l.push({column:E,direction:n[c]?.direction??"asc"});l.push({column:me,direction:"asc"});const s=[];for(const[c,E]of l.entries()){const m=[];for(const[v,L]of l.slice(0,c).entries())m.push(e`${e.identifier(L.column)} IS ${o[v]}`);m.push(e`${e.identifier(E.column)} ${e.raw(E.direction==="desc"?"<":">")} ${o[c]}`);const[_]=m;s.push(m.length===1&&_!==void 0?_:e`(${e.join(m,e` AND `)})`)}return e`(${e.join(s,e` OR `)})`},Et=null,fn=(o,r)=>{if(o===void 0)return Et;const n=[o.__partition__,...r.map(l=>o[l]),o[me]];return ln(n)},un=(o,r,n)=>{const l=[];for(const s of o){const c=s[me];if(typeof c!="string")continue;const E=r.get(c);if(!E)continue;const m=typeof s.__partition__=="string"?s.__partition__:"",_=n.map(v=>s[v]??null);l.push({doc:E,key:{partitionKey:m,rowId:c,sortValues:_}})}return l},hn=(o,r,n)=>{const{rowToDocument:l}=o,s=new Map;if(n.length===0)return s;const c=e.join(n.map(m=>Ye(m)),e`, `),E=M(o.sql,e`SELECT id, _creationTime, ${e.identifier(sn)} FROM ${e.identifier(r)} WHERE id IN (${c})`).toArray();for(const m of E){const _=l(m),v=m.id;_&&typeof v=="string"&&s.set(v,_)}return s},nt=(o,r,n,l)=>{const{assertRankPartitionLocal:s,ensureRankBackfilled:c,onRead:E,schema:m}=o,_=m.tables[r];if(!_)throw new A("INTERNAL",`unknown table: ${r}`);const v=_.rankIndexes?.find(Y=>Y.name===n);if(!v)throw new A("INTERNAL",`unknown rankIndex "${n}" on table "${r}"`);s(r,_,v),E(r,Q),c(r,v);const L=Ie(r,v.name),T=v.sortBy.map((Y,ie)=>Ae(ie)),b=Math.max(1,Math.min(1e3,Math.floor(l.take??100))),h=re(l.baseWhere,l.where),k=wt(v,h),C=[e`${e.identifier("__partition__")} ASC`];for(const[Y,ie]of T.entries()){const se=v.sortBy[Y]?.direction;C.push(e`${e.identifier(ie)} ${e.raw(se==="desc"?"DESC":"ASC")}`)}C.push(e`${e.identifier(me)} ASC`);const I=[];typeof l.partitionKey=="string"?I.push(e`${e.identifier("__partition__")} = ${l.partitionKey}`):k&&I.push(e`${e.identifier("__partition__")} = ${De(v.partitionBy??[],k)}`);const P=dn(l),N=cn(P,T,v.sortBy);N&&I.push(N);const w=e.identifier(me),S=e.identifier("__partition__"),F=I.length>0?e` WHERE ${e.join(I,e` AND `)}`:e``,W=T.length>0?e`${w}, ${S}, ${e.join(T.map(Y=>e.identifier(Y)),e`, `)}`:e`${w}, ${S}`,j=e`SELECT ${W} FROM ${e.identifier(L)}${F} ORDER BY ${e.join(C,e`, `)} LIMIT ${e.raw(String(b+1))}`,q=M(o.sql,j).toArray(),J=q.length>b,B=J?q.slice(0,b):q,U=B.map(Y=>Y[me]),x=un(B,hn(o,r,U),T),G=J?fn(B.at(-1),T):Et,H=v.sortBy.map(Y=>Y.direction==="desc"?"desc":"asc");return{continueCursor:G,directions:H,hasMore:J,rows:x}},$n=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,pn=o=>{if(!$n.test(o))throw new A("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},it=50,bt=500,ge=(o,r,n)=>{const l=r??bt;if(o>l)throw new A("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(o)} exceeds the limit of ${String(l)} (raise options.limit or chunk the call)`,{status:400})},mn=o=>{const r={eq:(n,l)=>(o.sqlConditions.push({comparator:"=",field:n,value:l}),r),gt:(n,l)=>(o.sqlConditions.push({comparator:">",field:n,value:l}),r),gte:(n,l)=>(o.sqlConditions.push({comparator:">=",field:n,value:l}),r),lt:(n,l)=>(o.sqlConditions.push({comparator:"<",field:n,value:l}),r),lte:(n,l)=>(o.sqlConditions.push({comparator:"<=",field:n,value:l}),r)};return r},wn=o=>Math.max(o,Lt),gn=(o,r,n,l,s)=>{const c=ft(n.query,Ve(n.definition.language));if(c.length===0)return[];const E=dt(r,n.indexName),m=`${E}__vocab`,_=c.length-1,v=c.map((C,I)=>{const P=kt(C,I===_),N=P.exact?e`${e.identifier("term")} = ${P.lower}`:e`${e.identifier("term")} >= ${P.lower} AND ${e.identifier("term")} < ${P.upper}`;return e`SELECT ${e.identifier("doc")}, ${e.raw(String(I))} AS ${e.identifier("__term__")}, COUNT(*) AS ${e.identifier("__n__")} FROM ${e.identifier(m)} WHERE ${N} GROUP BY ${e.identifier("doc")}`}),L=c.map((C,I)=>e`SUM(CASE WHEN u.${e.identifier("__term__")} = ${e.raw(String(I))} THEN u.${e.identifier("__n__")} ELSE 0 END)`),T=e`SELECT f.${e.identifier(be)} AS ${e.identifier(be)}, ${e.join(L,e` + `)} AS ${e.identifier("__score__")} FROM (${e.join(v,e` UNION ALL `)}) u JOIN ${e.identifier(E)} f ON f.rowid = u.${e.identifier("doc")} GROUP BY f.${e.identifier(be)} HAVING ${e.join(L.map(C=>e`${C} > 0`),e` AND `)}`,b=[];for(const C of n.filters)b.push(e`${ee(C.field)} = ${fe(C.value)}`);s&&b.push(s);let h=e`SELECT m.id, m._creationTime, m.${e.identifier(Z)} FROM (${T}) s JOIN ${e.identifier(r)} m ON m.id = s.${e.identifier(be)}`;b.length>0&&(h=e`${h} WHERE ${e.join(b,e` AND `)}`),h=e`${h} ORDER BY s.${e.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${e.raw(String(l))}`;const k=[];for(const C of M(o,h)){const I=pt(C);I&&k.push(I)}return k},En=(o,r,n,l,s)=>{const c=Ve(n.definition.language),E=ft(n.query,c);if(E.length===0)return[];const m=[];for(const T of n.filters)m.push(e`${ee(T.field)} = ${fe(T.value)}`);s&&m.push(s);let _=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(r)}`;m.length>0&&(_=e`${_} WHERE ${e.join(m,e` AND `)}`),_=e`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${e.raw(String(wn(l)))}`;const v=M(o,_).toArray(),L=[];for(const T of v){const b=pt(T);if(!b)continue;const h=Mt(ct(b,n.definition),E,c);h>0&&L.push({creationTime:typeof b._creationTime=="number"?b._creationTime:0,doc:b,id:typeof b._id=="string"?b._id:"",score:h})}return L.sort((T,b)=>b.score-T.score||b.creationTime-T.creationTime||T.id.localeCompare(b.id)),L.slice(0,l).map(T=>T.doc)},bn=(o,r)=>{const n=o,l={near:(s,c)=>{if(n.within)throw new A("INTERNAL",`geo index "${n.indexName}" on table "${r}": call .near() or .within(), not both`);return n.near={point:{lat:s.lat,lng:s.lng},radiusMeters:c},l},within:s=>{if(n.near)throw new A("INTERNAL",`geo index "${n.indexName}" on table "${r}": call .near() or .within(), not both`);return n.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},l}};return l},yn=(o,r)=>{const n=o[r];if(n===null||typeof n!="object")return;const{lat:l,lng:s}=n;return typeof l=="number"&&typeof s=="number"?{lat:l,lng:s}:void 0},_n=(o,r)=>{const n=yn(o,r.definition.field);if(!n)return;const l=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const s=Yt(r.near.point,n);return s<=r.near.radiusMeters?{creationTime:l,distance:s}:void 0}return Vt(n,r.within)?{creationTime:l,distance:0}:void 0},Tn=(o,r,n,l,s)=>{if(!n.near&&!n.within)throw new A("INTERNAL",`geo index "${n.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=n.near?Gt(n.near.point,n.near.radiusMeters):Jt(n.within),E=ht(r,n.indexName),m=c.map(h=>e`(g.${e.identifier("__geohash__")} >= ${h} AND g.${e.identifier("__geohash__")} < ${`${h}{`})`),_=[e`(${e.join(m,e` OR `)})`];s&&_.push(s);const v=e`SELECT m.id, m._creationTime, m.${e.identifier(Z)} FROM ${e.identifier(E)} g JOIN ${e.identifier(r)} m ON m.id = g.${e.identifier("__id__")} WHERE ${e.join(_,e` AND `)}`,L=M(o,v).toArray(),T=[];for(const h of L){const k=he(h),C=k?_n(k,n):void 0;k&&C&&T.push({creationTime:C.creationTime,distance:C.distance,doc:k})}T.sort((h,k)=>h.distance-k.distance||k.creationTime-h.creationTime);const b=T.map(h=>h.doc);return typeof l=="number"?b.slice(0,Math.max(0,Math.floor(l))):b},Nn=(o,r,n,l,s)=>{const{geo:c}=n;if(!c)throw new A("INTERNAL","runGeoTerminal called without a staged geo query");const E=n.inMemoryFilters.length>0,m=Tn(o,r,c,E?void 0:s,l);if(!E)return m;const _=[];for(const v of m)if(n.inMemoryFilters.every(L=>L(v))&&(_.push(v),typeof s=="number"&&_.length>=s))break;return _},Sn=(o,r,n,l,s,c)=>{const E=[];for(const L of n.sqlConditions)E.push(e`${ee(L.field)} ${e.raw(L.comparator)} ${fe(L.value)}`);l&&E.push(l);let m=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(r)}`;E.length>0&&(m=e`${m} WHERE ${e.join(E,e` AND `)}`),m=e`${m} ORDER BY ${s}`,typeof c=="number"&&n.inMemoryFilters.length===0&&(m=e`${m} LIMIT ${e.raw(String(Math.max(0,Math.floor(c))))}`);const _=M(o,m).toArray(),v=[];for(const L of _){const T=he(L);if(T&&n.inMemoryFilters.every(b=>b(T))&&(v.push(T),typeof c=="number"&&v.length>=c))break}return v},pe={fieldRef:ee,serialize:fe},Rn=o=>{let r=0;const n=[],l={fieldRef:ee,relationExists:s=>{const{childWhere:c,negated:E,parentTable:m,relation:_}=s,v=`__rel_${String(r)}`,L=n.at(-1)??m;r+=1,o(_.table,Q);const T=_.kind==="one"?_.field:_.references,b=_.kind==="one"?_.references:_.field,h=e`${Xe(v,b)} = ${Xe(L,T)}`;n.push(v);const k=ue(c,l);n.pop();const C=k?e`${h} AND ${k}`:h,I=e`EXISTS (SELECT 1 FROM ${e.identifier(_.table)} AS ${e.identifier(v)} WHERE ${C})`;return E?e`NOT ${I}`:I},serialize:fe};return l},yt=o=>{const r=o.map(n=>e`${ee(n.field)} ${e.raw(n.direction==="desc"?"DESC":"ASC")}`);return o.some(n=>n.field==="_id"||n.field==="id")||r.push(e`${ee("id")} ASC`),e.join(r,e`, `)},An={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},In=o=>{const r=o.order;return o.indexFields.length>0?o.indexFields.map(n=>({direction:r,field:n})):[{direction:r,field:"_creationTime"}]},vn=(o,r,n,l)=>{const s=o.sqlConditions.map(c=>({[c.field]:{[An[c.comparator]??"eq"]:c.value}}));if(n&&s.push(gt(r,Oe(n))),l&&s.push(Kt(r,Oe(l))),s.length!==0)return s.length===1?s[0]:{AND:s}},Cn=(o,r,n)=>{const l=[];for(const s of o){const c=he(s);if(c&&r.every(E=>E(c))&&(l.push(c),n!==void 0&&l.length>n))break}return l},kn=(o,r,n,l,s)=>{const c=Math.max(0,Math.floor(l.numItems)),E=In(n),m=typeof l.endCursor=="string",_=ue(vn(n,E,l.cursor,l.endCursor),pe),v=s&&_?e`${_} AND ${s}`:s??_;let L=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(r)}`;v&&(L=e`${L} WHERE ${v}`),L=e`${L} ORDER BY ${yt(E)}`;const T=n.inMemoryFilters.length>0;!T&&!m&&(L=e`${L} LIMIT ${e.raw(String(c+1))}`);const b=M(o,L).toArray(),h=Cn(b,n.inMemoryFilters,T||m?void 0:c);if(m){const P=h.length>=2?h[Math.floor(h.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:h,splitCursor:P?Ge(P,E):null}}const k=h.length>c,C=k?h.slice(0,c):h,I=C.at(-1);return{continueCursor:k&&I?Ge(I,E):null,isDone:!k,page:C}};class Mn extends A{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ln=/\s/u,xn=String.fromCodePoint(0),ot=(o,r,n)=>{if(!o.tables[r])throw new A("INTERNAL",`unknown table: ${r}`);return typeof n!="string"||n.length===0||Ln.test(n)||n.includes(xn)?null:n},On=(o,r,n,l=()=>{})=>{const s=r.tables[n];if(!s)throw new A("INTERNAL",`unknown table: ${n}`);const c=Ee(s.softDeleteMode,void 0),E=c?ue(c,pe):void 0,m={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]},_=h=>{const{search:k}=m;if(!k)throw new A("INTERNAL","runSearchFetch called without a staged search");qt(o,n,s);const C=m.inMemoryFilters.length>0,I=vt(C?void 0:h),P=ut(o)?gn(o,n,k,I,E):En(o,n,k,I,E);if(!C)return h===void 0&&Ct(P),P;const N=[];for(const w of P)if(m.inMemoryFilters.every(S=>S(w))&&(N.push(w),typeof h=="number"&&N.length>=h))break;return N},v=h=>{const k=Rt(h);return At(_(It(k)),k)},L=()=>{const h=m.indexFields.length>0?m.indexFields:["_creationTime"],k=m.order==="desc"?"DESC":"ASC";return e.join(h.map(C=>e`${ee(C)} ${e.raw(k)}`),e`, `)},T=h=>m.search?_(h):m.geo?Nn(o,n,m,E,h):Sn(o,n,m,E,L(),h),b={async collect(){return T(void 0)},filter(h){return m.inMemoryFilters.push(h),b},async first(){return T(m.inMemoryFilters.length>0?void 0:1)[0]??null},order(h){return m.order=h==="desc"?"desc":"asc",b},async paginate(h){if(m.search)return v(h);if(m.geo)throw new A("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");return kn(o,n,m,h,E)},async take(h){return T(h)},async unique(){const h=T(m.inMemoryFilters.length>0?void 0:2);if(h.length>1)throw new Mn(`unique() on table "${n}" matched ${String(h.length)} documents; expected at most one`);return h[0]??null},withGeoIndex(h,k){const C=(s.geoIndexes??[]).find(P=>P.name===h);if(!C)throw new A("INTERNAL",`unknown geo index "${h}" on table "${n}"`);l(n,h,"geo");const I={definition:C,indexName:h};if(m.geo=I,k(bn(I,n)),!I.near&&!I.within)throw new A("INTERNAL",`geo index "${h}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return b},withIndex(h,k){const C=s.indexes.find(I=>I.name===h);if(!C)throw new A("INTERNAL",`unknown index "${h}" on table "${n}"`);return l(n,h,"index"),m.indexName=h,m.indexFields=C.fields,k&&k(mn(m)),b},withSearchIndex(h,k){const C=(s.searchIndexes??[]).find(P=>P.name===h);if(!C)throw new A("INTERNAL",`unknown search index "${h}" on table "${n}"`);l(n,h,"search");const I={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:h,query:""};if(m.search=I,k(St(I,n,Ve(C.language))),!I.hasQuery)throw new A("INTERNAL",`search index "${h}" on table "${n}" requires a .search(field, query) call`);return b}};return b},rt=(o,r,n)=>{const l={...r};for(const[s,c]of $t(o)){if(c.serverDefault){l[s]=c.serverDefault({auth:n});continue}l[s]===void 0&&(c.defaultFn?l[s]=c.defaultFn():"defaultValue"in c&&(l[s]=c.defaultValue))}return l},at=(o,r,n,l)=>{const s=n;for(const[c,E]of $t(o)){if(E.serverDefault){c in r&&(s[c]=E.serverDefault({auth:l}));continue}E.onUpdateFn&&!(c in r)&&(s[c]=E.onUpdateFn())}},st=(o,r)=>{for(const n of Object.keys(r))if(r[n]===void 0)throw new A("INTERNAL",`Cannot ${o} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Dn=/unique constraint failed/i,Wn=o=>o instanceof Error&&Dn.test(o.message),Je=(o,r,n)=>{try{M(o,n)}catch(l){throw Wn(l)?new Re(`unique constraint violation on "${r}"`,"unique"):l}},xe=(o,r,n)=>{if(Je(o,r,n),M(o,e`SELECT changes() AS changed`).one().changed===0)throw new Re(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},lt=(o,r,n,l,s,c,E)=>{const m=[];for(let T=0;T<n.length+1;T+=1){const b=[];for(let I=0;I<T;I+=1)b.push(e`${e.identifier(n[I])} IS ${c[I]}`);const h=n[T],k=l[T];if(h!==void 0&&k!==void 0){const I=k.direction==="desc"?">":"<";b.push(e`${e.identifier(h)} ${e.raw(I)} ${c[T]}`)}else b.push(e`${e.identifier(me)} < ${E}`);const[C]=b;m.push(b.length===1&&C!==void 0?C:e`(${e.join(b,e` AND `)})`)}const _=e.join(m,e` OR `),v=M(o,e`SELECT COUNT(*) AS c FROM ${e.identifier(r)} WHERE ${e.identifier("__partition__")} = ${s} AND (${_})`).one(),L=M(o,e`SELECT COUNT(*) AS c FROM ${e.identifier(r)} WHERE ${e.identifier("__partition__")} = ${s}`).one();return{before:v.c,total:L.c}},li=o=>{const{sql:r}=o,{schema:n}=o,l=o.broadcast??(()=>{}),s=o.onRead??(()=>{}),c=o.onIndexUse??(()=>{}),E=o.onWrite??(()=>{}),{cache:m}=o,_=o.clock??(()=>Date.now()),v=o.idGenerator??(()=>crypto.randomUUID()),L=o.scheduler??Ot,{globalDb:T}=o,b=o.auth??{identity:null,userId:null},h=o.cdc??!1,k=L,C=tn({scheduler:typeof k.list=="function"&&typeof k.get=="function"?k:void 0,storage:o.storage}),I=(t,i,a,p)=>{h&&Ut(r,_(),t,i,a,p)},P=t=>n.tables[t]?.shardMode?.kind==="global",N=(t,i)=>{if(P(t)){if(!T)throw new A("INTERNAL",`cross-backend ${i} for global table '${t}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return T}return z},w=t=>N(t,"cascade"),S=(t,i)=>{if(P(t)){if(!T)throw new A("INTERNAL",`${i} on global table '${t}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return T}},F=()=>T,W=(t,i)=>N(t,"relation load").findMany(t,i),j=(t,i)=>(P(t)&&s(t,Q),W(t,i)),q=t=>!P(t.table),J=o.relationExistsPushDown??"auto",B=J!=="never",{maxRelationKeys:U}=o,x=(t,i,a)=>et(t,{fetcher:j,maxRelationKeys:U,relationBaseWhere:a,schema:n,tableName:i}),G=async(t,i,a,p)=>{const $=S(t,"relation grouped count");if($)return s(t,Q),Zt((D,oe)=>$.count(D,oe),t,i,a,p);const f=n.tables[t];if(!f)throw new A("INTERNAL",`unknown table: ${t}`);s(t,Q);const d=Ee(f.softDeleteMode,void 0),u={[i]:{in:a}},g=re(re(u,p),d),R=await x(g,t,void 0),y=ue(R,pe),O=ee(i);let K=e`SELECT ${O} AS __fk__, COUNT(*) AS count FROM ${e.identifier(t)}`;y&&(K=e`${K} WHERE ${y}`),K=e`${K} GROUP BY ${O}`;const V=M(r,K).toArray();return new Map(V.map(D=>[D.__fk__,D.count]))};let H=0;const Y=new Set;for(const[t,i]of Object.entries(n.tables))for(const a of Object.values(i.triggerMap??{}))Y.add(`${t} ${a.timing} ${a.op}`);const ie=(t,i,a)=>Y.has(`${t} ${i} ${a}`),se=async(t,i,a)=>{if(H+=1,H>it)throw H-=1,new Re(`trigger recursion exceeded ${String(it)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await nn({ctx:_t,event:a,op:i,schema:n,tableName:a.table,timing:t})}finally{H-=1}},{ensureBackfilledForTable:ye,ensureBackfilledIndex:We,ensureRankBackfilled:Be,ensureRankBackfilledForTable:_e,syncAggregates:ve,syncCompanionsForInsert:ze,syncGeo:Ce,syncRanks:Te,syncSearch:ke}=an({broadcast:l,invalidateCache:(t,i)=>m?.invalidate(t,i),recordCdc:I,schema:n,sql:r}),Ke=(t,i,a)=>{const{shardMode:p}=i;if(p?.kind==="shardBy"&&!(p.field!==void 0&&(a.partitionBy??[]).includes(p.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${t}" partitions across shards (shard key "${p.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},$e=(t,i)=>{const a=Object.entries(n.tables).filter(([,R])=>R.shardMode?.kind!=="global").map(([R])=>R).filter(R=>i===void 0||R===i);if(a.length===0)return;const p=a.map(R=>e`SELECT ${e.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(R)} WHERE id = ${t}`),$=e`${e.join(p,e` UNION ALL `)} LIMIT 1`,[f]=M(r,$).toArray();if(!f)return;const d=f.__t__,u=he(f);if(typeof d!="string"||!u)return;const g=f[Z];return{docJson:typeof g=="string"?g:JSON.stringify(g??{}),row:u,tableName:d}},Qe={assertRankPartitionLocal:Ke,ensureRankBackfilled:Be,onRead:s,rowToDocument:he,schema:n,sql:r},z={system:C,async aggregate(t,i){const a=S(t,"aggregate");if(a)return s(t,Q),a.aggregate(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);if(Ne(i.op),i.op==="count")return z.count(t,{baseWhere:i.baseWhere,relationBaseWhere:i.relationBaseWhere,restrictsCounts:i.restrictsCounts,where:i.where});if(!i.field)throw new A("INTERNAL",`aggregate(${t}, { op: "${i.op}" }): "field" is required for non-count reducers`);s(t,Q);const $=Ee(p.softDeleteMode,void 0),f=re(re(i.baseWhere,i.where),$),d=await x(f,t,i.relationBaseWhere),u=d!==f;if(p.aggregateIndexes&&!i.baseWhere&&!u&&!$){const V=Ft(p.aggregateIndexes,i.op,i.field,i.where);if(V){We(t,V.index);const D=de(V.index.by??[],V.key),oe=Se(t,V.index.name),ae=M(r,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(oe)} WHERE ${ce} = ${D}`).toArray()[0];return Ue(i.op,ae)}}const g=ue(d,pe),R=Ne(i.op),y=ee(i.field);let O=e`SELECT ${e.raw(R)}(${y}) AS value FROM ${e.identifier(t)}`;return g&&(O=e`${O} WHERE ${g}`),M(r,O).toArray()[0]?.value??null},asId(t,i){const a=ot(n,t,i);if(a===null)throw new A("BAD_REQUEST",`asId("${t}", …): "${i}" is not a valid id for table "${t}"`,{status:400});return a},async count(t,i){const a=S(t,"count");if(a)return s(t,Q),a.count(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);const $=xt(i);if($.restrictsCounts)throw new Pe(t);s(t,Q);const f=Ee(p.softDeleteMode,void 0),d=re(re($.baseWhere,$.where),f),u=await x(d,t,$.relationBaseWhere),g=u!==d;if(p.aggregateIndexes&&!$.baseWhere&&!g&&!f){const O=Bt(p.aggregateIndexes,$.where);if(O){We(t,O.index);const K=de(O.index.by??[],O.key),V=Se(t,O.index.name),D=M(r,e`SELECT ${te} AS value FROM ${e.identifier(V)} WHERE ${ce} = ${K}`).toArray();return D[0]===void 0?0:D[0].value??0}}const R=ue(u,pe);let y=e`SELECT COUNT(*) AS count FROM ${e.identifier(t)}`;return R&&(y=e`${y} WHERE ${R}`),M(r,y).one().count},async delete(t,i,a){const p=$e(t,i);if(!p){const y=i===void 0?F():void 0;y&&await y.delete(t,void 0,a);return}const{docJson:$,row:f,tableName:d}=p,u=n.tables[d],g=a?.hard===!0,R=!g&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(R&&f[R]!==null&&f[R]!==void 0)){if(ie(d,"before","delete")&&await se("before","delete",{id:t,op:"delete",previous:f,table:d}),await Xt({deletedId:t,deletedReference:y=>f[y],findHolders:async(y,O,K)=>(await w(y).findMany(y,{includeDeleted:g,where:{[O]:K}})).page,onCascade:(y,O)=>w(y).delete(O,void 0,a),onRestrict:y=>{throw new Re(y,"restrict")},onSetNull:(y,O,K)=>w(y).patch(O,{[K]:null}),schema:n,tableName:d}),ye(d),_e(d),R){const y={...f,[R]:_(),_id:t};xe(r,d,e`UPDATE ${e.identifier(d)} SET ${e.identifier(Z)} = ${JSON.stringify(y)} WHERE id = ${t} AND ${e.identifier(Z)} = ${$}`),ke(d,t,y,f),Ce(d,t,void 0),ve(d,f,y),Te(d,t,f,void 0),m?.invalidate(d,t),I(d,t,"update",y),l({key:t,op:"update",row:y,table:d}),ie(d,"after","delete")&&await se("after","delete",{id:t,op:"delete",previous:f,table:d}),await E({id:t,op:"delete",table:d});return}xe(r,d,e`DELETE FROM ${e.identifier(d)} WHERE id = ${t} AND ${e.identifier(Z)} = ${$}`),ke(d,t,void 0),Ce(d,t,void 0),ve(d,f,void 0),Te(d,t,f,void 0),m?.invalidate(d,t),I(d,t,"delete"),l({key:t,op:"delete",table:d}),ie(d,"after","delete")&&await se("after","delete",{id:t,op:"delete",previous:f,table:d}),await E({id:t,op:"delete",table:d})}},async deleteAll(t,i){if(!n.tables[t])throw new A("INTERNAL",`unknown table: ${t}`);const a=Math.max(1,i?.chunkSize??bt),p=i?.hard===void 0?void 0:{hard:i.hard},$=P(t)?void 0:t;let f=0;for(;;){const d=(await z.findMany(t,{limit:a})).page.map(u=>String(u._id));if(d.length===0)break;for(const u of d)await z.delete(u,$,p),f+=1;if(d.length<a)break}return{deleted:f}},async deleteMany(t,i,a){ge(t.length,i?.limit,"deleteMany");for(const p of t)await z.delete(p,a);return{deleted:t.length}},async deleteWhere(t,i,a){const p=S(t,"deleteWhere");let $;if(p)$=(await p.findMany(t,{where:i})).page.map(f=>String(f._id));else{if(!n.tables[t])throw new A("INTERNAL",`unknown table: ${t}`);$=(await z.findMany(t,{where:i})).page.map(f=>String(f._id))}if(ge($.length,a?.limit,"deleteWhere"),z.deleteMany===void 0)throw new A("INTERNAL",`ctx.db.${t}.deleteMany is unavailable: this writer has no batch delete`);return z.deleteMany($,a)},async findFirst(t,i={}){return(await z.findMany(t,{...i,limit:1})).page[0]??null},async findFirstOrThrow(t,i={}){const a=await z.findFirst(t,i);if(a===null)throw new Qt(`findFirstOrThrow: no "${t}" document matched`);return a},async findMany(t,i={}){const a=S(t,"findMany");if(a)return s(t,Q),a.findMany(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);const $=!i.where&&!i.baseWhere;$?s(t,Q):s(t);const f=zt(i.orderBy),d=i.cursor?gt(f,Oe(i.cursor)):void 0;let u=re(i.baseWhere,i.where);u=re(u,Ee(p.softDeleteMode,i.includeDeleted)),u=await et(u,{canPushExists:B?q:void 0,existsPushMode:J==="always"?"always":"auto",fetcher:j,maxRelationKeys:U,relationBaseWhere:i.relationBaseWhere,schema:n,tableName:t}),d&&(u=u?{AND:[u,d]}:d);const g=B?Rn(s):pe,R=ue(u,g);let y=e`SELECT id, _creationTime, ${e.identifier(Z)} FROM ${e.identifier(t)}`;R&&(y=e`${y} WHERE ${R}`),y=e`${y} ORDER BY ${yt(f)}`;const O=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0;O!==void 0&&(y=e`${y} LIMIT ${e.raw(String(O+1))}`);const K=M(r,y).toArray(),V=[];for(const le of K){const ne=he(le);ne&&(V.push(ne),!$&&typeof ne._id=="string"&&s(t,ne._id))}if(O===void 0)return i.with&&await tt({groupedCounter:G,fetcher:W,parents:V,relationBaseWhere:i.relationBaseWhere,schema:n,tableName:t,with:i.with}),{continueCursor:null,isDone:!0,page:Ze(V,i.select,i.with)};const D=V.length>O,oe=D?V.slice(0,O):V,ae=oe.at(-1);return i.with&&await tt({fetcher:W,groupedCounter:G,parents:oe,relationBaseWhere:i.relationBaseWhere,schema:n,tableName:t,with:i.with}),{continueCursor:D&&ae?Ge(ae,f):null,isDone:!D,page:Ze(oe,i.select,i.with)}},async get(t,i){const a=$e(t,i);if(!a){const p=i===void 0?F():void 0;return p?p.get(t):null}return s(a.tableName,t),a.row},async lookupById(t,i){const a=$e(t,i);return a?(s(a.tableName,t),{row:a.row,tableName:a.tableName}):null},async groupBy(t,i){const a=S(t,"groupBy");if(a)return s(t,Q),a.groupBy(t,i);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);s(t,Q);const $=i.agg??{op:"count"};if(Ne($.op),$.op!=="count"&&!$.field)throw new A("INTERNAL",`groupBy(${t}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);const f=Ee(p.softDeleteMode,void 0),d=re(re(i.baseWhere,i.where),f),u=await x(d,t,i.relationBaseWhere),g=u!==d;if(p.aggregateIndexes&&!i.baseWhere&&!g&&!f){const D=Wt(p.aggregateIndexes,$.op,$.field,i.by,i.where);if(D){We(t,D.index);const oe=Se(t,D.index.name),ae=Object.keys(D.partial),le=[];if(ae.length===(D.index.by??[]).length&&ae.length>0){const we=de(D.index.by??[],D.partial),Me=M(r,e`SELECT ${te} AS value, ${X} AS count FROM ${e.identifier(oe)} WHERE ${ce} = ${we}`).toArray();return Me.length>0&&le.push({key:{...D.partial},value:Ue($.op,Me[0])}),le}const ne=M(r,e`SELECT ${ce} AS key, ${te} AS value, ${X} AS count FROM ${e.identifier(oe)}`).toArray();for(const we of ne){const Me=JSON.parse(we.key);le.push({key:Me,value:Ue($.op,we)})}return le}}const R=ue(u,pe),y=i.by.map(D=>e`${ee(D)} AS ${e.identifier(D)}`);if($.op==="count")y.push(e`COUNT(*) AS value`);else{const{field:D}=$;if(D===void 0)throw new A("INTERNAL",`groupBy(${t}, { agg: { op: "${$.op}" } }): "field" is required for non-count reducers`);y.push(e`${e.raw(Ne($.op))}(${ee(D)}) AS value`)}let O=e`SELECT ${e.join(y,e`, `)} FROM ${e.identifier(t)}`;R&&(O=e`${O} WHERE ${R}`),O=e`${O} GROUP BY ${e.join(i.by.map(D=>ee(D)),e`, `)}`;const K=M(r,O).toArray(),V=[];for(const D of K){const oe={};for(const le of i.by)oe[le]=D[le]??null;const{value:ae}=D;V.push({key:oe,value:ae==null?null:Number(ae)})}return V},async insert(t,i,a){const p=S(t,"insert");if(p){const R=await p.insert(t,i,a);return l({key:R,op:"insert",row:{...i,_id:R},table:t}),R}const $=n.tables[t];if(!$)throw new A("INTERNAL",`unknown table: ${t}`);const f=rt($,i,b);je($,f);let d;a?.clientId!==void 0?(pn(a.clientId),d=a.clientId):a?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=v();const u=a?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:_(),g={...f,_creationTime:u,_id:d};return ie(t,"before","insert")&&await se("before","insert",{doc:{...g},id:d,op:"insert",table:t}),ye(t),_e(t),Je(r,t,e`INSERT INTO ${e.identifier(t)} (id, _creationTime, ${e.identifier(Z)}) VALUES (${d}, ${u}, ${JSON.stringify(g)})`),ze(t,d,g),ie(t,"after","insert")&&await se("after","insert",{doc:g,id:d,op:"insert",table:t}),await E({doc:g,id:d,op:"insert",table:t}),d},async insertManyUnsafe(t,i,a){if(ge(i.length,a?.limit,"insertManyUnsafe"),i.length===0)return[];const p=S(t,"insert");if(p){const u=[];for(const g of i){const R=await p.insert(t,g,{allowExplicitId:a?.allowExplicitId});l({key:R,op:"insert",row:{...g,_id:R},table:t}),u.push(R)}return u}const $=n.tables[t];if(!$)throw new A("INTERNAL",`unknown table: ${t}`);ye(t),_e(t);const f=i.map(u=>{const g=rt($,u,b),R=a?.allowExplicitId===!0&&typeof g._id=="string"?g._id:v(),y=a?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:_();return{creationTime:y,document:{...g,_creationTime:y,_id:R},id:R}}),d=e.join(f.map(u=>e`(${u.id}, ${u.creationTime}, ${JSON.stringify(u.document)})`),e`, `);Je(r,t,e`INSERT INTO ${e.identifier(t)} (id, _creationTime, ${e.identifier(Z)}) VALUES ${d}`);for(const{document:u,id:g}of f)ze(t,g,u),await E({doc:u,id:g,op:"insert",table:t});return f.map(u=>u.id)},async insertMany(t,i,a){ge(i.length,a?.limit,"insertMany");const p=a?.skipDuplicates===!0,$=[];for(const f of i)try{$.push(await z.insert(t,f))}catch(d){if(p&&d instanceof Re&&d.kind==="unique")$.push(null);else throw d}return $},normalizeId(t,i){return ot(n,t,i)},async patch(t,i,a){const p=$e(t,a);if(!p){const R=a===void 0?F():void 0;if(R){await R.patch(t,i);return}throw new A("INTERNAL",`document not found: ${t}`)}const{docJson:$,row:f,tableName:d}=p,u=n.tables[d];if(!u)throw new A("INTERNAL",`unknown table: ${d}`);s(d,t),st("patch",i);const g={...f,...i,_id:t};at(u,i,g,b),je(u,g,!0),ie(d,"before","update")&&await se("before","update",{doc:{...g},id:t,op:"update",previous:f,table:d}),ye(d),_e(d),xe(r,d,e`UPDATE ${e.identifier(d)} SET ${e.identifier(Z)} = ${JSON.stringify(g)} WHERE id = ${t} AND ${e.identifier(Z)} = ${$}`),ke(d,t,g,f),Ce(d,t,g),ve(d,f,g),Te(d,t,f,g),m?.invalidate(d,t),I(d,t,"update",g),l({key:t,op:"update",row:g,table:d}),ie(d,"after","update")&&await se("after","update",{doc:g,id:t,op:"update",previous:f,table:d}),await E({doc:g,id:t,op:"update",table:d})},async patchMany(t,i,a){ge(t.length,i?.limit,"patchMany");for(const p of t)await z.patch(p.id,p.patch,a);return{patched:t.length}},async patchWhere(t,i,a){const p=S(t,"patchWhere");let $;if(p)$=(await p.findMany(t,{where:i.where})).page.map(f=>({id:String(f._id),patch:i.patch}));else{if(!n.tables[t])throw new A("INTERNAL",`unknown table: ${t}`);$=(await z.findMany(t,{where:i.where})).page.map(f=>({id:String(f._id),patch:i.patch}))}if(ge($.length,a?.limit,"patchWhere"),z.patchMany===void 0)throw new A("INTERNAL",`ctx.db.${t}.patchMany is unavailable: this writer has no batch patch`);return await z.patchMany($,a),{patched:$.length}},query(t){const i=S(t,"query");return i?(s(t,Q),i.query(t)):(s(t,Q),On(r,n,t,c))},async rank(t,i,a){const p=S(t,"rank");if(p)return s(t,Q),p.rank(t,i,a);c(t,i,"rank");const $=n.tables[t];if(!$)throw new A("INTERNAL",`unknown table: ${t}`);const f=$.rankIndexes?.find(ne=>ne.name===i);if(!f)throw new A("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(Ke(t,$,f),a.restrictsCounts)throw new Pe(t);s(t,Q),Be(t,f);const d=typeof a.row=="string"?a.row:a.row._id;if(!d)return null;const u=Ie(t,f.name),g=f.sortBy.map((ne,we)=>Ae(we)),R=g.map(ne=>Pt(ne)).join(", "),y=M(r,e`SELECT ${e.identifier("__partition__")}, ${e.raw(R)} FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${d}`).toArray(),[O]=y;if(O===void 0)return null;let K=O.__partition__;const V=re(a.baseWhere,a.where);He(V,n,t,"rank");const D=wt(f,V);if(D){const ne=De(f.partitionBy??[],D);if(ne!==K)return null;K=ne}const oe=g.map(ne=>O[ne]),{before:ae,total:le}=lt(r,u,g,f.sortBy,K,oe,d);return{position:ae+1,total:le}},async rankBefore(t,i,a){if(P(t))throw new A("INTERNAL",`rankBefore is not supported on the global (.global()) table '${t}' — cross-shard rank cursors apply only to sharded tables`);const p=n.tables[t];if(!p)throw new A("INTERNAL",`unknown table: ${t}`);const $=p.rankIndexes?.find(g=>g.name===i);if(!$)throw new A("INTERNAL",`unknown rankIndex "${i}" on table "${t}"`);if(a.restrictsCounts)throw new Pe(t);s(t,Q),Be(t,$);const f=Ie(t,$.name),d=$.sortBy.map((g,R)=>Ae(R)),u=$.sortBy.map((g,R)=>fe(a.sortValues[R]??null));return lt(r,f,d,$.sortBy,a.partitionKey,u,a.rowId)},async rankPage(t,i,a={}){He(re(a.baseWhere,a.where),n,t,"rankPage");const p=S(t,"rankPage");if(p)return s(t,Q),p.rankPage(t,i,a);c(t,i,"rank");const{continueCursor:$,hasMore:f,rows:d}=nt(Qe,t,i,a);return{continueCursor:$,isDone:!f,page:d.map(u=>u.doc)}},async rankPageRows(t,i,a={}){He(re(a.baseWhere,a.where),n,t,"rankPage"),c(t,i,"rank");const{directions:p,hasMore:$,rows:f}=nt(Qe,t,i,a);return{directions:p,hasMore:$,rows:f}},async restore(t,i){const a=$e(t,i);if(!a){const f=i===void 0?F():void 0;if(f?.restore){await f.restore(t);return}throw new A("INTERNAL",`document not found: ${t}`)}const p=n.tables[a.tableName]?.softDeleteMode?.field;if(!p)throw new A("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const $=a.row[p]!==null&&a.row[p]!==void 0;await z.patch(t,{[p]:null},i),$&&Te(a.tableName,t,void 0,a.row)},async replace(t,i,a,p){const $=$e(t,a);if(!$){const O=a===void 0?F():void 0;if(O){await O.replace(t,i,void 0,p);return}throw new A("INTERNAL",`document not found: ${t}`)}const{docJson:f,row:d,tableName:u}=$,g=n.tables[u];if(!g)throw new A("INTERNAL",`unknown table: ${u}`);st("replace",i);const R=p?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:_(),y={...i,_creationTime:R,_id:t};at(g,i,y,b),je(g,y),ie(u,"before","update")&&await se("before","update",{doc:{...y},id:t,op:"update",previous:d,table:u}),ye(u),_e(u),xe(r,u,e`UPDATE ${e.identifier(u)} SET _creationTime = ${R}, ${e.identifier(Z)} = ${JSON.stringify(y)} WHERE id = ${t} AND ${e.identifier(Z)} = ${f}`),ke(u,t,y,d),Ce(u,t,y),ve(u,d,y),Te(u,t,d,y),m?.invalidate(u,t),I(u,t,"update",y),l({key:t,op:"update",row:y,table:u}),ie(u,"after","update")&&await se("after","update",{doc:y,id:t,op:"update",previous:d,table:u}),await E({doc:y,id:t,op:"update",table:u})},async wipeShard(t){const i=new Set(t?.exclude),a=t?.tables,p=Object.entries(n.tables).filter(([u,g])=>i.has(u)||a!==void 0&&!a.includes(u)?!1:g.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!n.tables[u])throw new A("INTERNAL",`wipeShard: unknown table: ${u}`)}const $={};let f=0;const{deleteAll:d}=z;if(d===void 0)throw new A("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of p){const g=await d(u,{...t?.chunkSize===void 0?{}:{chunkSize:t.chunkSize},hard:!0});$[u]=g.deleted,f+=g.deleted}return{deleted:f,tables:$}}},_t={db:z,scheduler:L};return o.enforceRls===!0?en(z,n,(t,i)=>$e(t,i)?.tableName):z};export{mi as CDC_LOG_TABLE,Si as CLIENT_WATERMARK_TABLE,Ri as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ai as IDEMPOTENCY_TABLE,Mn as NotUniqueError,fi as SEARCH_STATE_TABLE,Ii as advanceClientWatermark,wi as applyCdcChanges,pn as assertValidClientId,ui as backfillAggregateIndexes,hi as backfillRankIndexes,$i as backfillSearchIndexes,gi as bumpCdcEpoch,li as createShardCtxDb,vi as deleteGlobalShapeSnapshot,Ci as deleteGlobalShapeSnapshotsForConnection,ki as migrateClientWatermark,Mi as migrateGlobalShapeSnapshot,Ei as minCdcSeq,ot as normalizeIdStructurally,bi as readCdcChanges,yi as readCdcCursor,_i as readCdcEpoch,Li as readClientWatermark,xi as readGlobalShapeSnapshot,Oi as readIdempotent,qi as runShardMigrations,Pi as selectShapeMemberIds,Hi as selectShapeRows,Ti as trimCdcChanges,Di as trimIdempotent,Wi as writeGlobalShapeSnapshot,Bi as writeIdempotent};
|