@rocicorp/zero 1.11.0-canary.41 → 1.11.0-canary.43
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/out/replicache/src/deleted-clients.d.ts +2 -2
- package/out/replicache/src/deleted-clients.js +2 -2
- package/out/replicache/src/deleted-clients.js.map +1 -1
- package/out/replicache/src/persist/client-group-gc.d.ts +1 -1
- package/out/replicache/src/persist/client-group-gc.js +1 -1
- package/out/replicache/src/persist/client-group-gc.js.map +1 -1
- package/out/replicache/src/replicache-options.d.ts +1 -1
- package/out/shared/src/browser-env.d.ts +1 -1
- package/out/shared/src/browser-env.js.map +1 -1
- package/out/shared/src/set-utils.d.ts +1 -1
- package/out/shared/src/set-utils.js +1 -1
- package/out/shared/src/set-utils.js.map +1 -1
- package/out/zero/package.js +1 -1
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
- package/out/zero-cache/src/server/change-streamer.js +2 -0
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +4 -2
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js +17 -6
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +3 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +4 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +3 -3
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/drain-tracker.d.ts +4 -4
- package/out/zero-cache/src/services/change-streamer/drain-tracker.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/drain-tracker.js +4 -8
- package/out/zero-cache/src/services/change-streamer/drain-tracker.js.map +1 -1
- package/out/zero-cache/src/services/http-service.d.ts +6 -0
- package/out/zero-cache/src/services/http-service.d.ts.map +1 -1
- package/out/zero-cache/src/services/http-service.js +11 -0
- package/out/zero-cache/src/services/http-service.js.map +1 -1
- package/out/zero-cache/src/services/life-cycle.d.ts +3 -2
- package/out/zero-cache/src/services/life-cycle.d.ts.map +1 -1
- package/out/zero-cache/src/services/life-cycle.js +17 -4
- package/out/zero-cache/src/services/life-cycle.js.map +1 -1
- package/out/zero-cache/src/services/replicator/drain-handler.d.ts +8 -0
- package/out/zero-cache/src/services/replicator/drain-handler.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/drain-handler.js +38 -4
- package/out/zero-cache/src/services/replicator/drain-handler.js.map +1 -1
- package/out/zero-cache/src/types/pg-patch.d.ts +21 -0
- package/out/zero-cache/src/types/pg-patch.d.ts.map +1 -0
- package/out/zero-cache/src/types/pg-patch.js +29 -0
- package/out/zero-cache/src/types/pg-patch.js.map +1 -0
- package/out/zero-client/src/client/connection-manager.js +1 -1
- package/out/zero-client/src/client/connection-manager.js.map +1 -1
- package/out/zero-client/src/client/custom.d.ts +1 -1
- package/out/zero-client/src/client/custom.js +1 -1
- package/out/zero-client/src/client/custom.js.map +1 -1
- package/out/zero-client/src/client/options.d.ts +6 -6
- package/out/zero-client/src/client/options.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero.d.ts +1 -1
- package/out/zero-client/src/client/zero.js +1 -1
- package/out/zero-client/src/client/zero.js.map +1 -1
- package/out/zero-protocol/src/inspect-up.d.ts +3 -3
- package/out/zero-protocol/src/inspect-up.d.ts.map +1 -1
- package/out/zero-protocol/src/inspect-up.js +2 -2
- package/out/zero-protocol/src/inspect-up.js.map +1 -1
- package/out/zero-react/src/use-zero-online.d.ts +1 -1
- package/out/zero-react/src/use-zero-online.js +1 -1
- package/out/zero-react/src/use-zero-online.js.map +1 -1
- package/out/zero-react/src/zero-provider.d.ts +1 -1
- package/out/zero-react/src/zero-provider.js +1 -1
- package/out/zero-react/src/zero-provider.js.map +1 -1
- package/out/zero-server/src/closable-db-transaction.d.ts +1 -1
- package/out/zero-server/src/closable-db-transaction.js +1 -1
- package/out/zero-server/src/closable-db-transaction.js.map +1 -1
- package/out/zero-server/src/custom.d.ts +1 -1
- package/out/zero-server/src/custom.js +1 -1
- package/out/zero-server/src/custom.js.map +1 -1
- package/out/zero-server/src/process-mutations.d.ts +3 -3
- package/out/zero-server/src/process-mutations.js +1 -1
- package/out/zero-server/src/process-mutations.js.map +1 -1
- package/out/zero-server/src/push-processor.d.ts +1 -1
- package/out/zero-server/src/push-processor.js +1 -1
- package/out/zero-server/src/push-processor.js.map +1 -1
- package/out/zero-server/src/queries/process-queries.d.ts +3 -3
- package/out/zero-server/src/queries/process-queries.js +2 -2
- package/out/zero-server/src/queries/process-queries.js.map +1 -1
- package/out/zero-server/src/schema.d.ts +1 -1
- package/out/zero-server/src/schema.js +1 -1
- package/out/zero-server/src/schema.js.map +1 -1
- package/out/zero-server/src/zql-database.d.ts +2 -2
- package/out/zero-server/src/zql-database.js +2 -2
- package/out/zero-server/src/zql-database.js.map +1 -1
- package/out/zero-solid/src/use-query.d.ts +2 -2
- package/out/zero-solid/src/use-query.js +1 -1
- package/out/zero-solid/src/use-query.js.map +1 -1
- package/out/zero-solid/src/use-zero-online.d.ts +1 -1
- package/out/zero-solid/src/use-zero-online.js +1 -1
- package/out/zero-solid/src/use-zero-online.js.map +1 -1
- package/out/zero-solid/src/use-zero.d.ts +2 -2
- package/out/zero-solid/src/use-zero.js +2 -2
- package/out/zero-solid/src/use-zero.js.map +1 -1
- package/out/zql/src/ivm/change.d.ts +3 -3
- package/out/zql/src/ivm/change.js.map +1 -1
- package/out/zql/src/ivm/data.d.ts +1 -1
- package/out/zql/src/ivm/data.js.map +1 -1
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.d.ts +1 -1
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.js +1 -1
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.js.map +1 -1
- package/out/zql/src/mutate/custom.d.ts +3 -3
- package/out/zql/src/mutate/custom.js.map +1 -1
- package/out/zql/src/query/create-builder.d.ts +1 -1
- package/out/zql/src/query/create-builder.d.ts.map +1 -1
- package/out/zql/src/query/create-builder.js +1 -1
- package/out/zql/src/query/create-builder.js.map +1 -1
- package/out/zql/src/query/named.d.ts +2 -2
- package/out/zql/src/query/named.js +2 -2
- package/out/zql/src/query/named.js.map +1 -1
- package/out/zql/src/query/query-impl.js +3 -3
- package/out/zql/src/query/query-impl.js.map +1 -1
- package/out/zql/src/query/query-internals.d.ts +5 -5
- package/out/zql/src/query/query-internals.js.map +1 -1
- package/out/zql/src/query/query-transitions.d.ts +5 -5
- package/out/zql/src/query/query-transitions.js +2 -2
- package/out/zql/src/query/query-transitions.js.map +1 -1
- package/out/zql/src/query/query.d.ts +8 -8
- package/package.json +1 -1
|
@@ -35,7 +35,7 @@ export declare const inspectAnalyzeQueryUpSchema: v.ObjectType<Omit<{
|
|
|
35
35
|
id: v.Type<string>;
|
|
36
36
|
}, "args" | "ast" | "name" | "op" | "options" | "value"> & {
|
|
37
37
|
op: v.Type<"analyze-query">;
|
|
38
|
-
/** @deprecated Use {@
|
|
38
|
+
/** @deprecated Use {@link ast} instead */
|
|
39
39
|
value: v.Optional<import("./ast.ts").AST>;
|
|
40
40
|
options: v.Optional<{
|
|
41
41
|
vendedRows?: boolean | undefined;
|
|
@@ -69,7 +69,7 @@ declare const inspectUpBodySchema: v.UnionType<[v.ObjectType<Omit<{
|
|
|
69
69
|
id: v.Type<string>;
|
|
70
70
|
}, "args" | "ast" | "name" | "op" | "options" | "value"> & {
|
|
71
71
|
op: v.Type<"analyze-query">;
|
|
72
|
-
/** @deprecated Use {@
|
|
72
|
+
/** @deprecated Use {@link ast} instead */
|
|
73
73
|
value: v.Optional<import("./ast.ts").AST>;
|
|
74
74
|
options: v.Optional<{
|
|
75
75
|
vendedRows?: boolean | undefined;
|
|
@@ -102,7 +102,7 @@ export declare const inspectUpMessageSchema: v.TupleType<[v.Type<"inspect">, v.U
|
|
|
102
102
|
id: v.Type<string>;
|
|
103
103
|
}, "args" | "ast" | "name" | "op" | "options" | "value"> & {
|
|
104
104
|
op: v.Type<"analyze-query">;
|
|
105
|
-
/** @deprecated Use {@
|
|
105
|
+
/** @deprecated Use {@link ast} instead */
|
|
106
106
|
value: v.Optional<import("./ast.ts").AST>;
|
|
107
107
|
options: v.Optional<{
|
|
108
108
|
vendedRows?: boolean | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inspect-up.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/inspect-up.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,CAAC,MAAM,4BAA4B,CAAC;AAOhD,QAAA,MAAM,0BAA0B;;;;;aAG9B,CAAC;AAEH,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,0BAA0B,CAAC,CAAC;AAE9E,QAAA,MAAM,sBAAsB;;;;aAE1B,CAAC;AAEH,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAE1E,QAAA,MAAM,sBAAsB;;;;aAE1B,CAAC;AAEH,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAE1E,eAAO,MAAM,2BAA2B;;;;;aAGtC,CAAC;AAEH,MAAM,MAAM,yBAAyB,GAAG,CAAC,CAAC,KAAK,CAC7C,OAAO,2BAA2B,CACnC,CAAC;AAEF,QAAA,MAAM,yBAAyB;;;;aAI7B,CAAC;AAEH,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAA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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAUvC,CAAC;AAEF,eAAO,MAAM,8BAA8B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAGzC,CAAC;AAEH,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAEtE,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEhE,MAAM,MAAM,wBAAwB,GAAG,CAAC,CAAC,KAAK,CAC5C,OAAO,8BAA8B,CACtC,CAAC;AAEF,sDAAsD;AACtD,MAAM,MAAM,qBAAqB,GAAG,OAAO,CACzC,CAAC,CAAC,KAAK,CAAC,OAAO,2BAA2B,CAAC,EAC3C,CAAC,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAC3B,CAAC"}
|
|
@@ -20,7 +20,7 @@ var analyzeQueryOptionsSchema = valita_exports.object({
|
|
|
20
20
|
});
|
|
21
21
|
var inspectAnalyzeQueryUpSchema = inspectUpBase.extend({
|
|
22
22
|
op: valita_exports.literal("analyze-query"),
|
|
23
|
-
/** @deprecated Use {@
|
|
23
|
+
/** @deprecated Use {@link ast} instead */
|
|
24
24
|
value: strictASTSchema.optional(),
|
|
25
25
|
options: analyzeQueryOptionsSchema.optional(),
|
|
26
26
|
ast: strictASTSchema.optional(),
|
|
@@ -29,7 +29,7 @@ var inspectAnalyzeQueryUpSchema = inspectUpBase.extend({
|
|
|
29
29
|
});
|
|
30
30
|
var unparsedInspectAnalyzeQueryUpSchema = inspectUpBase.extend({
|
|
31
31
|
op: valita_exports.literal("analyze-query"),
|
|
32
|
-
/** @deprecated Use {@
|
|
32
|
+
/** @deprecated Use {@link ast} instead */
|
|
33
33
|
value: valita_exports.unknown().optional(),
|
|
34
34
|
options: analyzeQueryOptionsSchema.optional(),
|
|
35
35
|
ast: valita_exports.unknown().optional(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inspect-up.js","names":[],"sources":["../../../../zero-protocol/src/inspect-up.ts"],"sourcesContent":["import {jsonSchema} from '../../shared/src/json-schema.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport {strictASTSchema} from './ast.ts';\n\nconst inspectUpBase = v.object({\n id: v.string(),\n});\n\nconst inspectQueriesUpBodySchema = inspectUpBase.extend({\n op: v.literal('queries'),\n clientID: v.string().optional(),\n});\n\nexport type InspectQueriesUpBody = v.Infer<typeof inspectQueriesUpBodySchema>;\n\nconst inspectMetricsUpSchema = inspectUpBase.extend({\n op: v.literal('metrics'),\n});\n\nexport type InspectMetricsUpBody = v.Infer<typeof inspectMetricsUpSchema>;\n\nconst inspectVersionUpSchema = inspectUpBase.extend({\n op: v.literal('version'),\n});\n\nexport type InspectVersionUpBody = v.Infer<typeof inspectVersionUpSchema>;\n\nexport const inspectAuthenticateUpSchema = inspectUpBase.extend({\n op: v.literal('authenticate'),\n value: v.string(),\n});\n\nexport type InspectAuthenticateUpBody = v.Infer<\n typeof inspectAuthenticateUpSchema\n>;\n\nconst analyzeQueryOptionsSchema = v.object({\n vendedRows: v.boolean().optional(),\n syncedRows: v.boolean().optional(),\n joinPlans: v.boolean().optional(),\n});\n\nexport type AnalyzeQueryOptions = v.Infer<typeof analyzeQueryOptionsSchema>;\n\nexport const inspectAnalyzeQueryUpSchema = inspectUpBase.extend({\n op: v.literal('analyze-query'),\n /** @deprecated Use {@
|
|
1
|
+
{"version":3,"file":"inspect-up.js","names":[],"sources":["../../../../zero-protocol/src/inspect-up.ts"],"sourcesContent":["import {jsonSchema} from '../../shared/src/json-schema.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport {strictASTSchema} from './ast.ts';\n\nconst inspectUpBase = v.object({\n id: v.string(),\n});\n\nconst inspectQueriesUpBodySchema = inspectUpBase.extend({\n op: v.literal('queries'),\n clientID: v.string().optional(),\n});\n\nexport type InspectQueriesUpBody = v.Infer<typeof inspectQueriesUpBodySchema>;\n\nconst inspectMetricsUpSchema = inspectUpBase.extend({\n op: v.literal('metrics'),\n});\n\nexport type InspectMetricsUpBody = v.Infer<typeof inspectMetricsUpSchema>;\n\nconst inspectVersionUpSchema = inspectUpBase.extend({\n op: v.literal('version'),\n});\n\nexport type InspectVersionUpBody = v.Infer<typeof inspectVersionUpSchema>;\n\nexport const inspectAuthenticateUpSchema = inspectUpBase.extend({\n op: v.literal('authenticate'),\n value: v.string(),\n});\n\nexport type InspectAuthenticateUpBody = v.Infer<\n typeof inspectAuthenticateUpSchema\n>;\n\nconst analyzeQueryOptionsSchema = v.object({\n vendedRows: v.boolean().optional(),\n syncedRows: v.boolean().optional(),\n joinPlans: v.boolean().optional(),\n});\n\nexport type AnalyzeQueryOptions = v.Infer<typeof analyzeQueryOptionsSchema>;\n\nexport const inspectAnalyzeQueryUpSchema = inspectUpBase.extend({\n op: v.literal('analyze-query'),\n /** @deprecated Use {@link ast} instead */\n value: strictASTSchema.optional(),\n options: analyzeQueryOptionsSchema.optional(),\n ast: strictASTSchema.optional(),\n name: v.string().optional(),\n args: v.readonlyArray(jsonSchema).optional(),\n});\n\nconst unparsedInspectAnalyzeQueryUpSchema = inspectUpBase.extend({\n op: v.literal('analyze-query'),\n /** @deprecated Use {@link ast} instead */\n value: v.unknown().optional(),\n options: analyzeQueryOptionsSchema.optional(),\n ast: v.unknown().optional(),\n name: v.string().optional(),\n args: v.readonlyArray(jsonSchema).optional(),\n});\n\nexport type InspectAnalyzeQueryUpBody = v.Infer<\n typeof inspectAnalyzeQueryUpSchema\n>;\n\nconst inspectUpBodySchema = v.union(\n inspectQueriesUpBodySchema,\n inspectMetricsUpSchema,\n inspectVersionUpSchema,\n inspectAuthenticateUpSchema,\n inspectAnalyzeQueryUpSchema,\n);\n\nexport const inspectUpMessageSchema = v.tuple([\n v.literal('inspect'),\n inspectUpBodySchema,\n]);\n\n// zero-cache answers an op from a newer client with an error for that request\n// instead of closing the connection.\nexport const unparsedInspectUpBodySchema = v.taggedObjectUnion(\n 'op',\n [\n inspectQueriesUpBodySchema,\n inspectMetricsUpSchema,\n inspectVersionUpSchema,\n inspectAuthenticateUpSchema,\n unparsedInspectAnalyzeQueryUpSchema,\n ],\n {open: true},\n);\n\nexport const unparsedInspectUpMessageSchema = v.tuple([\n v.literal('inspect'),\n unparsedInspectUpBodySchema,\n]);\n\nexport type InspectUpMessage = v.Infer<typeof inspectUpMessageSchema>;\n\nexport type InspectUpBody = v.Infer<typeof inspectUpBodySchema>;\n\nexport type UnparsedInspectUpMessage = v.Infer<\n typeof unparsedInspectUpMessageSchema\n>;\n\n/** An inspect request with an op this build knows. */\nexport type UnparsedInspectUpBody = Exclude<\n v.Infer<typeof unparsedInspectUpBodySchema>,\n v.UnrecognizedObject<'op'>\n>;\n"],"mappings":";;;;AAIA,IAAM,gBAAgB,eAAE,OAAO,EAC7B,IAAI,eAAE,OAAO,EACf,CAAC;AAED,IAAM,6BAA6B,cAAc,OAAO;CACtD,IAAI,eAAE,QAAQ,SAAS;CACvB,UAAU,eAAE,OAAO,EAAE,SAAS;AAChC,CAAC;AAID,IAAM,yBAAyB,cAAc,OAAO,EAClD,IAAI,eAAE,QAAQ,SAAS,EACzB,CAAC;AAID,IAAM,yBAAyB,cAAc,OAAO,EAClD,IAAI,eAAE,QAAQ,SAAS,EACzB,CAAC;AAID,IAAa,8BAA8B,cAAc,OAAO;CAC9D,IAAI,eAAE,QAAQ,cAAc;CAC5B,OAAO,eAAE,OAAO;AAClB,CAAC;AAMD,IAAM,4BAA4B,eAAE,OAAO;CACzC,YAAY,eAAE,QAAQ,EAAE,SAAS;CACjC,YAAY,eAAE,QAAQ,EAAE,SAAS;CACjC,WAAW,eAAE,QAAQ,EAAE,SAAS;AAClC,CAAC;AAID,IAAa,8BAA8B,cAAc,OAAO;CAC9D,IAAI,eAAE,QAAQ,eAAe;;CAE7B,OAAO,gBAAgB,SAAS;CAChC,SAAS,0BAA0B,SAAS;CAC5C,KAAK,gBAAgB,SAAS;CAC9B,MAAM,eAAE,OAAO,EAAE,SAAS;CAC1B,MAAM,cAAgB,UAAU,EAAE,SAAS;AAC7C,CAAC;AAED,IAAM,sCAAsC,cAAc,OAAO;CAC/D,IAAI,eAAE,QAAQ,eAAe;;CAE7B,OAAO,eAAE,QAAQ,EAAE,SAAS;CAC5B,SAAS,0BAA0B,SAAS;CAC5C,KAAK,eAAE,QAAQ,EAAE,SAAS;CAC1B,MAAM,eAAE,OAAO,EAAE,SAAS;CAC1B,MAAM,cAAgB,UAAU,EAAE,SAAS;AAC7C,CAAC;AAMD,IAAM,sBAAsB,eAAE,MAC5B,4BACA,wBACA,wBACA,6BACA,2BACF;AAEA,IAAa,yBAAyB,eAAE,MAAM,CAC5C,eAAE,QAAQ,SAAS,GACnB,mBACF,CAAC;AAID,IAAa,8BAA8B,kBACzC,MACA;CACE;CACA;CACA;CACA;CACA;AACF,GACA,EAAC,MAAM,KAAI,CACb;AAEA,IAAa,iCAAiC,eAAE,MAAM,CACpD,eAAE,QAAQ,SAAS,GACnB,2BACF,CAAC"}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
*
|
|
6
6
|
* @returns The online status of the Zero instance.
|
|
7
7
|
*
|
|
8
|
-
* @deprecated Use {@
|
|
8
|
+
* @deprecated Use {@link useConnectionState} instead, which provides more detailed connection state.
|
|
9
9
|
*/
|
|
10
10
|
export declare function useZeroOnline(): boolean;
|
|
11
11
|
//# sourceMappingURL=use-zero-online.d.ts.map
|
|
@@ -8,7 +8,7 @@ import { useSyncExternalStore } from "react";
|
|
|
8
8
|
*
|
|
9
9
|
* @returns The online status of the Zero instance.
|
|
10
10
|
*
|
|
11
|
-
* @deprecated Use {@
|
|
11
|
+
* @deprecated Use {@link useConnectionState} instead, which provides more detailed connection state.
|
|
12
12
|
*/
|
|
13
13
|
function useZeroOnline() {
|
|
14
14
|
const zero = useZero();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-zero-online.js","names":[],"sources":["../../../../zero-react/src/use-zero-online.tsx"],"sourcesContent":["import {useSyncExternalStore} from 'react';\nimport {useZero} from './zero-provider.tsx';\n\n/**\n * Hook to subscribe to the online status of the Zero instance.\n *\n * This is useful when you want to update state based on the online status.\n *\n * @returns The online status of the Zero instance.\n *\n * @deprecated Use {@
|
|
1
|
+
{"version":3,"file":"use-zero-online.js","names":[],"sources":["../../../../zero-react/src/use-zero-online.tsx"],"sourcesContent":["import {useSyncExternalStore} from 'react';\nimport {useZero} from './zero-provider.tsx';\n\n/**\n * Hook to subscribe to the online status of the Zero instance.\n *\n * This is useful when you want to update state based on the online status.\n *\n * @returns The online status of the Zero instance.\n *\n * @deprecated Use {@link useConnectionState} instead, which provides more detailed connection state.\n */\nexport function useZeroOnline(): boolean {\n const zero = useZero();\n return useSyncExternalStore(\n zero.onOnline,\n () => zero.online,\n () => zero.online,\n );\n}\n"],"mappings":";;;;;;;;;;;;AAYA,SAAgB,gBAAyB;CACvC,MAAM,OAAO,QAAQ;CACrB,OAAO,qBACL,KAAK,gBACC,KAAK,cACL,KAAK,MACb;AACF"}
|
|
@@ -3,7 +3,7 @@ import { Zero, type BaseDefaultContext, type BaseDefaultSchema, type CustomMutat
|
|
|
3
3
|
export declare const ZeroContext: import("react").Context<Zero<any, any, any> | undefined>;
|
|
4
4
|
export declare function useZero<S extends BaseDefaultSchema = DefaultSchema, MD extends CustomMutatorDefs | undefined = undefined, Context extends BaseDefaultContext = DefaultContext>(): Zero<S, MD, Context>;
|
|
5
5
|
/**
|
|
6
|
-
* @deprecated Use {@
|
|
6
|
+
* @deprecated Use {@link useZero} instead, alongside default types defined with:
|
|
7
7
|
*
|
|
8
8
|
* ```ts
|
|
9
9
|
* declare module '@rocicorp/zero' {
|
|
@@ -11,7 +11,7 @@ function useZero() {
|
|
|
11
11
|
return zero;
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
|
-
* @deprecated Use {@
|
|
14
|
+
* @deprecated Use {@link useZero} instead, alongside default types defined with:
|
|
15
15
|
*
|
|
16
16
|
* ```ts
|
|
17
17
|
* declare module '@rocicorp/zero' {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zero-provider.js","names":[],"sources":["../../../../zero-react/src/zero-provider.tsx"],"sourcesContent":["import {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport {stringCompare} from '../../shared/src/string-compare.ts';\nimport {\n Zero,\n type BaseDefaultContext,\n type BaseDefaultSchema,\n type CustomMutatorDefs,\n type DefaultContext,\n type DefaultSchema,\n type ZeroOptions,\n} from './zero.ts';\n\n// oxlint-disable-next-line no-explicit-any\nexport const ZeroContext = createContext<Zero<any, any, any> | undefined>(\n undefined,\n);\n\nexport function useZero<\n S extends BaseDefaultSchema = DefaultSchema,\n MD extends CustomMutatorDefs | undefined = undefined,\n Context extends BaseDefaultContext = DefaultContext,\n>(): Zero<S, MD, Context> {\n const zero = useContext(ZeroContext);\n if (zero === undefined) {\n throw new Error('useZero must be used within a ZeroProvider');\n }\n return zero as Zero<S, MD, Context>;\n}\n\n/**\n * @deprecated Use {@
|
|
1
|
+
{"version":3,"file":"zero-provider.js","names":[],"sources":["../../../../zero-react/src/zero-provider.tsx"],"sourcesContent":["import {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport {stringCompare} from '../../shared/src/string-compare.ts';\nimport {\n Zero,\n type BaseDefaultContext,\n type BaseDefaultSchema,\n type CustomMutatorDefs,\n type DefaultContext,\n type DefaultSchema,\n type ZeroOptions,\n} from './zero.ts';\n\n// oxlint-disable-next-line no-explicit-any\nexport const ZeroContext = createContext<Zero<any, any, any> | undefined>(\n undefined,\n);\n\nexport function useZero<\n S extends BaseDefaultSchema = DefaultSchema,\n MD extends CustomMutatorDefs | undefined = undefined,\n Context extends BaseDefaultContext = DefaultContext,\n>(): Zero<S, MD, Context> {\n const zero = useContext(ZeroContext);\n if (zero === undefined) {\n throw new Error('useZero must be used within a ZeroProvider');\n }\n return zero as Zero<S, MD, Context>;\n}\n\n/**\n * @deprecated Use {@link useZero} instead, alongside default types defined with:\n *\n * ```ts\n * declare module '@rocicorp/zero' {\n * interface DefaultTypes {\n * schema: typeof schema;\n * context: Context;\n * }\n * }\n */\nexport function createUseZero<\n S extends BaseDefaultSchema = DefaultSchema,\n MD extends CustomMutatorDefs | undefined = undefined,\n Context extends BaseDefaultContext = DefaultContext,\n>() {\n return () => useZero<S, MD, Context>();\n}\n\nexport type ZeroProviderProps<\n S extends BaseDefaultSchema = DefaultSchema,\n MD extends CustomMutatorDefs | undefined = undefined,\n Context extends BaseDefaultContext = DefaultContext,\n> = (ZeroOptions<S, MD, Context> | {zero: Zero<S, MD, Context>}) & {\n /**\n * Called after ZeroProvider constructs a new Zero instance.\n *\n * This runs only when the provider creates Zero from options, and is not\n * called when an existing instance is passed with `zero`.\n */\n init?: (zero: Zero<S, MD, Context>) => void;\n children: ReactNode;\n};\n\nexport function ZeroProvider<\n S extends BaseDefaultSchema = DefaultSchema,\n MD extends CustomMutatorDefs | undefined = undefined,\n Context extends BaseDefaultContext = DefaultContext,\n>({children, init, ...props}: ZeroProviderProps<S, MD, Context>) {\n const isExternalZero = 'zero' in props;\n\n const [zero, setZero] = useState<Zero<S, MD, Context> | undefined>(\n isExternalZero ? props.zero : undefined,\n );\n const [rotationGeneration, setRotationGeneration] = useState(0);\n\n const auth = 'auth' in props ? props.auth : undefined;\n const hasAuth = typeof auth === 'string';\n const prevAuthRef = useRef<typeof auth>(auth);\n const rotationPendingRef = useRef(false);\n\n const scheduleRotation = () => {\n if (rotationPendingRef.current) {\n return;\n }\n rotationPendingRef.current = true;\n setRotationGeneration(gen => gen + 1);\n };\n\n const keysWithoutAuth = useMemo(\n () =>\n Object.entries(props)\n .filter(([key]) => key !== 'auth')\n .sort(([a], [b]) => stringCompare(a, b))\n .map(([_, value]) => value),\n [props],\n );\n\n // If Zero is not passed in, we construct it, but only client-side.\n // Zero doesn't really work SSR today so this is usually the right thing.\n // When we support Zero SSR this will either become a breaking change or\n // more likely server support will be opt-in with a new prop on this\n // component.\n useEffect(() => {\n if (isExternalZero) {\n rotationPendingRef.current = false;\n setZero(props.zero);\n return;\n }\n\n const z = new Zero({\n ...props,\n onClientStateNotFound: () => {\n if (rotationPendingRef.current) {\n return;\n }\n\n if (props.onClientStateNotFound) {\n try {\n props.onClientStateNotFound();\n return;\n } catch {\n // rotate since zero client is now closed\n }\n }\n\n scheduleRotation();\n },\n });\n prevAuthRef.current = auth;\n init?.(z);\n setZero(z);\n rotationPendingRef.current = false;\n\n return () => {\n void z.close();\n setZero(undefined);\n };\n // we intentionally don't include auth in the dependency array\n // to avoid closing zero when auth changes\n }, [hasAuth, init, rotationGeneration, ...keysWithoutAuth]);\n\n useEffect(() => {\n if (!zero || isExternalZero) return;\n\n const prevAuth = prevAuthRef.current;\n const authChanged = auth !== prevAuth;\n\n if (authChanged) {\n prevAuthRef.current = auth;\n\n if (typeof prevAuth === 'string' && typeof auth === 'string') {\n void zero.connection.connect({auth});\n }\n }\n }, [auth, zero]);\n\n return (\n zero && <ZeroContext.Provider value={zero}>{children}</ZeroContext.Provider>\n );\n}\n"],"mappings":";;;;;;AAqBA,IAAa,cAAc,cACzB,KAAA,CACF;AAEA,SAAgB,UAIU;CACxB,MAAM,OAAO,WAAW,WAAW;CACnC,IAAI,SAAS,KAAA,GACX,MAAM,IAAI,MAAM,4CAA4C;CAE9D,OAAO;AACT;;;;;;;;;;;;AAaA,SAAgB,gBAIZ;CACF,aAAa,QAAwB;AACvC;AAiBA,SAAgB,aAId,EAAC,UAAU,MAAM,GAAG,SAA2C;CAC/D,MAAM,iBAAiB,UAAU;CAEjC,MAAM,CAAC,MAAM,WAAW,SACtB,iBAAiB,MAAM,OAAO,KAAA,CAChC;CACA,MAAM,CAAC,oBAAoB,yBAAyB,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A+B,CAAA;AAE/E"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { DBTransaction, Queryable } from '../../zql/src/mutate/custom.ts';
|
|
2
2
|
import type { HumanReadable } from '../../zql/src/query/query.ts';
|
|
3
3
|
/**
|
|
4
|
-
* A {@
|
|
4
|
+
* A {@link DBTransaction} that stops working once closed. The mutator's
|
|
5
5
|
* `tx` is built on it, so code that outlives the transaction cannot reach a
|
|
6
6
|
* connection that has been committed, rolled back or returned to the pool.
|
|
7
7
|
*/
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//#region ../zero-server/src/closable-db-transaction.ts
|
|
2
2
|
/**
|
|
3
|
-
* A {@
|
|
3
|
+
* A {@link DBTransaction} that stops working once closed. The mutator's
|
|
4
4
|
* `tx` is built on it, so code that outlives the transaction cannot reach a
|
|
5
5
|
* connection that has been committed, rolled back or returned to the pool.
|
|
6
6
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"closable-db-transaction.js","names":["#inner","#closed"],"sources":["../../../../zero-server/src/closable-db-transaction.ts"],"sourcesContent":["import type {DBTransaction, Queryable} from '../../zql/src/mutate/custom.ts';\nimport type {HumanReadable} from '../../zql/src/query/query.ts';\n\n/**\n * A {@
|
|
1
|
+
{"version":3,"file":"closable-db-transaction.js","names":["#inner","#closed"],"sources":["../../../../zero-server/src/closable-db-transaction.ts"],"sourcesContent":["import type {DBTransaction, Queryable} from '../../zql/src/mutate/custom.ts';\nimport type {HumanReadable} from '../../zql/src/query/query.ts';\n\n/**\n * A {@link DBTransaction} that stops working once closed. The mutator's\n * `tx` is built on it, so code that outlives the transaction cannot reach a\n * connection that has been committed, rolled back or returned to the pool.\n */\nexport class ClosableDBTransaction<T> implements DBTransaction<T> {\n readonly #inner: DBTransaction<T>;\n #closed = false;\n\n constructor(inner: DBTransaction<T>) {\n this.#inner = inner;\n }\n\n close(): void {\n this.#closed = true;\n }\n\n get wrappedTransaction(): T {\n if (this.#closed) {\n throw transactionEndedError();\n }\n return this.#inner.wrappedTransaction;\n }\n\n query: Queryable['query'] = (query, args) =>\n this.#closed\n ? Promise.reject(transactionEndedError())\n : this.#inner.query(query, args);\n\n runQuery<TReturn>(\n ...args: Parameters<DBTransaction<T>['runQuery']>\n ): Promise<HumanReadable<TReturn>> {\n return this.#closed\n ? Promise.reject(transactionEndedError())\n : this.#inner.runQuery<TReturn>(...args);\n }\n}\n\nfunction transactionEndedError(): Error {\n return new Error(\n 'This transaction has ended and can no longer be used. A tx.retryOn() predicate runs after its transaction is over.',\n );\n}\n"],"mappings":";;;;;;AAQA,IAAa,wBAAb,MAAkE;CAChE;CACA,UAAU;CAEV,YAAY,OAAyB;EACnC,KAAKA,SAAS;CAChB;CAEA,QAAc;EACZ,KAAKC,UAAU;CACjB;CAEA,IAAI,qBAAwB;EAC1B,IAAI,KAAKA,SACP,MAAM,sBAAsB;EAE9B,OAAO,KAAKD,OAAO;CACrB;CAEA,SAA6B,OAAO,SAClC,KAAKC,UACD,QAAQ,OAAO,sBAAsB,CAAC,IACtC,KAAKD,OAAO,MAAM,OAAO,IAAI;CAEnC,SACE,GAAG,MAC8B;EACjC,OAAO,KAAKC,UACR,QAAQ,OAAO,sBAAsB,CAAC,IACtC,KAAKD,OAAO,SAAkB,GAAG,IAAI;CAC3C;AACF;AAEA,SAAS,wBAA+B;CACtC,uBAAO,IAAI,MACT,oHACF;AACF"}
|
|
@@ -18,7 +18,7 @@ export declare class TransactionImpl<TSchema extends Schema, TWrappedTransaction
|
|
|
18
18
|
readonly mutationID: number;
|
|
19
19
|
readonly mutate: TransactionMutate<TSchema>;
|
|
20
20
|
/**
|
|
21
|
-
* @deprecated Use {@
|
|
21
|
+
* @deprecated Use {@link createBuilder} with `tx.run(zql.table.where(...))` instead.
|
|
22
22
|
*/
|
|
23
23
|
readonly query: ConditionalSchemaQuery<TSchema>;
|
|
24
24
|
constructor(dbTransaction: DBTransaction<TWrappedTransaction>, clientID: string, mutationID: number, mutate: TransactionMutate<TSchema>, schema: TSchema, serverSchema: ServerSchema, addRetryPredicate?: ((shouldRetry: RetryPredicate) => void) | undefined);
|
|
@@ -47,7 +47,7 @@ var TransactionImpl = class {
|
|
|
47
47
|
mutationID;
|
|
48
48
|
mutate;
|
|
49
49
|
/**
|
|
50
|
-
* @deprecated Use {@
|
|
50
|
+
* @deprecated Use {@link createBuilder} with `tx.run(zql.table.where(...))` instead.
|
|
51
51
|
*/
|
|
52
52
|
query;
|
|
53
53
|
#schema;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom.js","names":["#dbTransaction","#schema","#serverSchema","#addRetryPredicate","#tableCRUDs"],"sources":["../../../../zero-server/src/custom.ts"],"sourcesContent":["import {assert} from '../../shared/src/asserts.ts';\nimport type {ReadonlyJSONValue} from '../../shared/src/json.ts';\nimport {mapValues} from '../../shared/src/objects.ts';\nimport {recordProxy} from '../../shared/src/record-proxy.ts';\nimport {\n formatPgInternalConvert,\n sql,\n sqlConvertColumnArg,\n} from '../../z2s/src/sql.ts';\nimport type {TableSchema} from '../../zero-schema/src/table-schema.ts';\nimport type {Schema} from '../../zero-types/src/schema.ts';\nimport type {\n ServerColumnSchema,\n ServerSchema,\n ServerTableSchema,\n} from '../../zero-types/src/server-schema.ts';\nimport {\n type CRUDExecutor,\n type CRUDKind,\n makeCRUDMutate,\n makeTransactionMutate,\n type SchemaCRUD,\n type TableCRUD,\n type TransactionMutate,\n} from '../../zql/src/mutate/crud.ts';\nimport type {\n DBTransaction,\n MutateCRUD,\n Queryable,\n RetryPredicate,\n ServerTransaction,\n} from '../../zql/src/mutate/custom.ts';\nimport {createRunnableBuilder} from '../../zql/src/query/create-builder.ts';\nimport {QueryDelegateBase} from '../../zql/src/query/query-delegate-base.ts';\nimport {asQueryInternals} from '../../zql/src/query/query-internals.ts';\nimport type {\n HumanReadable,\n Query,\n RunOptions,\n} from '../../zql/src/query/query.ts';\nimport type {ConditionalSchemaQuery} from '../../zql/src/query/schema-query.ts';\nimport {getServerSchema} from './schema.ts';\n\nexport type CustomMutatorDefs<TDBTransaction> = {\n [namespaceOrKey: string]:\n | CustomMutatorImpl<TDBTransaction>\n | CustomMutatorDefs<TDBTransaction>;\n};\n\nexport type CustomMutatorImpl<\n TDBTransaction,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n TArgs = any,\n Context = unknown,\n> = (\n tx: TDBTransaction,\n args: TArgs,\n ctx: Context,\n) => Promise<ReadonlyJSONValue | void>;\n\n/**\n * QueryDelegate implementation for server-side transactions.\n * Extends QueryDelegateBase to satisfy the QueryDelegate interface,\n * but overrides run() to execute against Postgres and throws on\n * preload()/materialize() which don't make sense server-side.\n */\nclass ServerTransactionQueryDelegate extends QueryDelegateBase {\n readonly #dbTransaction: DBTransaction<unknown>;\n readonly #schema: Schema;\n readonly #serverSchema: ServerSchema;\n\n readonly defaultQueryComplete = true;\n\n constructor(\n dbTransaction: DBTransaction<unknown>,\n schema: Schema,\n serverSchema: ServerSchema,\n ) {\n super();\n this.#dbTransaction = dbTransaction;\n this.#schema = schema;\n this.#serverSchema = serverSchema;\n }\n\n getSource(): never {\n throw new Error('not implemented');\n }\n\n override run<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends Schema,\n TReturn,\n >(\n query: Query<TTable, TSchema, TReturn>,\n _options?: RunOptions,\n ): Promise<HumanReadable<TReturn>> {\n const queryInternals = asQueryInternals(query);\n return this.#dbTransaction.runQuery<TReturn>(\n queryInternals.ast,\n queryInternals.format,\n this.#schema,\n this.#serverSchema,\n );\n }\n\n override preload(): never {\n throw new Error('preload() is not supported in server transactions');\n }\n\n override materialize(): never {\n throw new Error('materialize() is not supported in server transactions');\n }\n}\n\nexport class TransactionImpl<\n TSchema extends Schema,\n TWrappedTransaction,\n> implements ServerTransaction<TSchema, TWrappedTransaction> {\n readonly location = 'server';\n readonly reason = 'authoritative';\n readonly dbTransaction: DBTransaction<TWrappedTransaction>;\n readonly clientID: string;\n readonly mutationID: number;\n readonly mutate: TransactionMutate<TSchema>;\n /**\n * @deprecated Use {@linkcode createBuilder} with `tx.run(zql.table.where(...))` instead.\n */\n readonly query: ConditionalSchemaQuery<TSchema>;\n\n readonly #schema: TSchema;\n readonly #serverSchema: ServerSchema;\n readonly #addRetryPredicate:\n | ((shouldRetry: RetryPredicate) => void)\n | undefined;\n\n constructor(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n mutate: TransactionMutate<TSchema>,\n schema: TSchema,\n serverSchema: ServerSchema,\n addRetryPredicate?: ((shouldRetry: RetryPredicate) => void) | undefined,\n ) {\n this.dbTransaction = dbTransaction;\n this.clientID = clientID;\n this.mutationID = mutationID;\n this.mutate = mutate;\n this.#schema = schema;\n this.#serverSchema = serverSchema;\n this.#addRetryPredicate = addRetryPredicate;\n\n const delegate = new ServerTransactionQueryDelegate(\n dbTransaction,\n schema,\n serverSchema,\n );\n this.query = createRunnableBuilder(delegate, schema);\n }\n\n retryOn(shouldRetry: RetryPredicate): void {\n if (this.#addRetryPredicate === undefined) {\n // Fail loudly: a predicate nothing will consult would silently turn\n // every retryable failure into a recorded error.\n throw new Error(\n 'tx.retryOn() is not supported on this transaction: nothing will re-run its mutator. A custom Database must pass TransactionProviderInput.addRetryPredicate on to createTransaction.',\n );\n }\n this.#addRetryPredicate(shouldRetry);\n }\n\n run<TTable extends keyof TSchema['tables'] & string, TReturn>(\n query: Query<TTable, TSchema, TReturn>,\n _options?: RunOptions,\n ): Promise<HumanReadable<TReturn>> {\n const queryInternals = asQueryInternals(query);\n\n // Execute the query using the database-specific executor\n return this.dbTransaction.runQuery<TReturn>(\n queryInternals.ast,\n queryInternals.format,\n this.#schema,\n this.#serverSchema,\n );\n }\n}\n\nconst dbTxSymbol = Symbol();\n\nconst serverSchemaSymbol = Symbol();\n\ntype WithHiddenTxAndSchema = {\n [dbTxSymbol]: DBTransaction<unknown>;\n [serverSchemaSymbol]: ServerSchema;\n};\n\n/**\n * Factory for creating MutateCRUD instances efficiently.\n *\n * Pre-creates the SQL-generating TableCRUD methods once from the schema,\n * caches the serverSchema after first fetch, and only binds the transaction\n * at transaction time.\n *\n * Use this when you need to create many transactions and want to avoid\n * the overhead of re-creating CRUD methods for each one.\n */\nexport class CRUDMutatorFactory<S extends Schema> {\n readonly #schema: S;\n readonly #tableCRUDs: Record<string, TableCRUD<TableSchema>>;\n // The in-flight or resolved fetch is cached (not just the result) so that\n // concurrent cold callers share a single catalog query.\n #serverSchema: Promise<ServerSchema> | undefined;\n\n constructor(schema: S) {\n this.#schema = schema;\n // Pre-create TableCRUD methods for each table once\n this.#tableCRUDs = {};\n for (const tableSchema of Object.values(schema.tables)) {\n this.#tableCRUDs[tableSchema.name] = makeServerTableCRUD(tableSchema);\n }\n }\n\n /**\n * Gets the cached serverSchema, or fetches and caches it on first call.\n */\n getOrFetchServerSchema(queryable: Queryable): Promise<ServerSchema> {\n if (!this.#serverSchema) {\n this.#serverSchema = getServerSchema(queryable, this.#schema).catch(e => {\n // Don't poison the cache with a transient failure.\n this.#serverSchema = undefined;\n throw e;\n });\n }\n return this.#serverSchema;\n }\n\n /**\n * Creates a CRUDExecutor bound to the given transaction and serverSchema.\n * Uses the pre-created TableCRUD methods from construction time.\n */\n createExecutor(\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n ): CRUDExecutor {\n const txHolder: WithHiddenTxAndSchema = {\n [dbTxSymbol]: dbTransaction,\n [serverSchemaSymbol]: serverSchema,\n };\n const boundCRUDs = recordProxy(this.#tableCRUDs, tableCRUD =>\n mapValues(tableCRUD, method => method.bind(txHolder)),\n ) as unknown as SchemaCRUD<S>;\n\n return (table: string, kind: CRUDKind, args: unknown) => {\n const tableCRUD = boundCRUDs[table as keyof S['tables']];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (tableCRUD as any)[kind](args);\n };\n }\n\n /**\n * Creates a full ServerTransaction.\n * Fetches/caches serverSchema automatically.\n */\n async createTransaction<TWrappedTransaction>(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n addRetryPredicate?: ((shouldRetry: RetryPredicate) => void) | undefined,\n ): Promise<TransactionImpl<S, TWrappedTransaction>> {\n const serverSchema = await this.getOrFetchServerSchema(dbTransaction);\n const executor = this.createExecutor(dbTransaction, serverSchema);\n const mutate = makeTransactionMutate(this.#schema, executor);\n return new TransactionImpl(\n dbTransaction,\n clientID,\n mutationID,\n mutate,\n this.#schema,\n serverSchema,\n addRetryPredicate,\n );\n }\n}\n\nexport async function makeServerTransaction<\n TSchema extends Schema,\n TWrappedTransaction,\n>(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n schema: TSchema,\n) {\n const serverSchema = await getServerSchema(dbTransaction, schema);\n // Use the internal executor and shared function directly,\n // bypassing the validation in makeMutateCRUD/makeSchemaCRUD\n const executor = makeServerCRUDExecutor(schema, dbTransaction, serverSchema);\n const mutate = makeTransactionMutate(schema, executor);\n return new TransactionImpl(\n dbTransaction,\n clientID,\n mutationID,\n mutate,\n schema,\n serverSchema,\n );\n}\n\n/**\n * @deprecated Use transactions instead.\n *\n * Returns a curried function for backwards compatibility.\n */\nexport function makeSchemaCRUD<S extends Schema>(\n schema: S,\n): (\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n) => MutateCRUD<S, true> {\n return (dbTransaction: DBTransaction<unknown>, serverSchema: ServerSchema) =>\n makeCRUDMutate(\n schema,\n true,\n makeServerCRUDExecutor(schema, dbTransaction, serverSchema),\n );\n}\n\nfunction removeUndefined<T extends Record<string, unknown>>(value: T): T {\n const valueWithoutUndefined: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n valueWithoutUndefined[key] = val;\n }\n }\n return valueWithoutUndefined as T;\n}\n\n/**\n * Creates a CRUDExecutor for server-side SQL execution.\n *\n * For users with very large schemas it is expensive to re-create\n * all the CRUD mutators for each transaction. Instead, we create\n * the SQL-generating methods once up-front and then bind them to\n * the transaction as requested.\n */\nfunction makeServerCRUDExecutor<S extends Schema>(\n schema: S,\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n): CRUDExecutor {\n // Pre-create TableCRUD methods for each table (optimization for large schemas)\n const tableCRUDs: Record<string, TableCRUD<TableSchema>> = {};\n for (const tableSchema of Object.values(schema.tables)) {\n tableCRUDs[tableSchema.name] = makeServerTableCRUD(tableSchema);\n }\n\n // Bind transaction context to the methods\n const txHolder: WithHiddenTxAndSchema = {\n [dbTxSymbol]: dbTransaction,\n [serverSchemaSymbol]: serverSchema,\n };\n const boundCRUDs = recordProxy(tableCRUDs, tableCRUD =>\n mapValues(tableCRUD, method => method.bind(txHolder)),\n ) as unknown as SchemaCRUD<S>;\n\n // Return executor that dispatches to bound methods\n return (table: string, kind: CRUDKind, args: unknown) => {\n const tableCRUD = boundCRUDs[table as keyof S['tables']];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (tableCRUD as any)[kind](args);\n };\n}\n\n/**\n * Creates SQL-generating TableCRUD methods for a table.\n * Methods use `this` context to access transaction and server schema.\n */\nfunction makeServerTableCRUD(schema: TableSchema): TableCRUD<TableSchema> {\n return {\n async insert(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const primaryKeyColumns = origAndServerNamesFor(\n schema.primaryKey,\n schema,\n );\n\n const stmt = formatPgInternalConvert(\n sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(\n targetedColumns.map(([, serverName]) => sql.ident(serverName)),\n ',',\n )}) VALUES (${sql.join(\n Object.entries(value).map(([col, v]) =>\n sqlInsertValue(v, serverTableSchema[serverNameFor(col, schema)]),\n ),\n ', ',\n )}) ON CONFLICT (${sql.join(\n primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)),\n ', ',\n )}) DO NOTHING`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async upsert(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const primaryKeyColumns = origAndServerNamesFor(\n schema.primaryKey,\n schema,\n );\n const updatedEntries = nonPrimaryKeyEntries(value, schema);\n const conflictAction =\n updatedEntries.length === 0\n ? sql`DO NOTHING`\n : sql`DO UPDATE SET ${sql.join(\n updatedEntries.map(\n ([col, val]) =>\n sql`${sql.ident(\n schema.columns[col].serverName ?? col,\n )} = ${sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)])}`,\n ),\n ', ',\n )}`;\n const stmt = formatPgInternalConvert(\n sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(\n targetedColumns.map(([, serverName]) => sql.ident(serverName)),\n ',',\n )}) VALUES (${sql.join(\n Object.entries(value).map(([col, val]) =>\n sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)]),\n ),\n ', ',\n )}) ON CONFLICT (${sql.join(\n primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)),\n ', ',\n )}) ${conflictAction}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async update(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const targetedColumns = origAndServerNamesFor(\n nonPrimaryKeyEntries(value, schema).map(([name]) => name),\n schema,\n );\n if (targetedColumns.length === 0) {\n return;\n }\n const stmt = formatPgInternalConvert(\n sql`UPDATE ${sql.ident(serverName(schema))} SET ${sql.join(\n targetedColumns.map(\n ([origName, serverName]) =>\n sql`${sql.ident(serverName)} = ${sqlInsertValue(value[origName], serverTableSchema[serverName])}`,\n ),\n ', ',\n )} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async delete(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const stmt = formatPgInternalConvert(\n sql`DELETE FROM ${sql.ident(\n serverName(schema),\n )} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n };\n}\n\nfunction nonPrimaryKeyEntries(\n value: Record<string, unknown>,\n schema: TableSchema,\n) {\n return Object.entries(value).filter(\n ([name]) => !schema.primaryKey.includes(name),\n );\n}\n\nfunction serverName(x: {name: string; serverName?: string | undefined}) {\n return x.serverName ?? x.name;\n}\n\nfunction primaryKeyClause(\n schema: TableSchema,\n serverTableSchema: ServerTableSchema,\n row: Record<string, unknown>,\n) {\n const primaryKey = origAndServerNamesFor(schema.primaryKey, schema);\n return sql`${sql.join(\n primaryKey.map(\n ([origName, serverName]) =>\n sql`${sql.ident(serverName)} = ${sqlValue(row[origName], serverTableSchema[serverName])}`,\n ),\n ' AND ',\n )}`;\n}\n\nfunction origAndServerNamesFor(\n originalNames: readonly string[],\n schema: TableSchema,\n): [origName: string, serverName: string][] {\n return originalNames.map(\n name => [name, serverNameFor(name, schema)] as const,\n );\n}\n\nfunction serverNameFor(originalName: string, schema: TableSchema): string {\n const col = schema.columns[originalName];\n assert(\n col,\n `Column ${originalName} was not found in the Zero schema for the table ${schema.name}`,\n );\n return col.serverName ?? originalName;\n}\n\nfunction sqlValue(value: unknown, serverColumnSchema: ServerColumnSchema) {\n return sqlConvertColumnArg(serverColumnSchema, value, false, true);\n}\n\nfunction sqlInsertValue(\n value: unknown,\n serverColumnSchema: ServerColumnSchema,\n) {\n return sqlConvertColumnArg(serverColumnSchema, value, false, false);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkEA,IAAM,iCAAN,cAA6C,kBAAkB;CAC7D;CACA;CACA;CAEA,uBAAgC;CAEhC,YACE,eACA,QACA,cACA;EACA,MAAM;EACN,KAAKA,iBAAiB;EACtB,KAAKC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AAE,SAAS,iBAAiB,QAAQ,mBAAmB,KAAK,GAC9D;GAEA,MADW,KAAK,YACP,MAAM,KAAK,MAAM,KAAK,MAAM;EACvC;CACF;AACF;AAEA,SAAS,qBACP,OACA,QACA;CACA,OAAO,OAAO,QAAQ,KAAK,EAAE,QAC1B,CAAC,UAAU,CAAC,OAAO,WAAW,SAAS,IAAI,CAC9C;AACF;AAEA,SAAS,WAAW,GAAoD;CACtE,OAAO,EAAE,cAAc,EAAE;AAC3B;AAEA,SAAS,iBACP,QACA,mBACA,KACA;CACA,MAAM,aAAa,sBAAsB,OAAO,YAAY,MAAM;CAClE,OAAO,GAAG,GAAG,IAAI,KACf,WAAW,KACR,CAAC,UAAU,gBACV,GAAG,GAAG,IAAI,MAAM,UAAU,EAAE,KAAK,SAAS,IAAI,WAAW,kBAAkB,WAAW,GAC1F,GACA,OACF;AACF;AAEA,SAAS,sBACP,eACA,QAC0C;CAC1C,OAAO,cAAc,KACnB,SAAQ,CAAC,MAAM,cAAc,MAAM,MAAM,CAAC,CAC5C;AACF;AAEA,SAAS,cAAc,cAAsB,QAA6B;CACxE,MAAM,MAAM,OAAO,QAAQ;CAC3B,OACE,KACA,UAAU,aAAa,kDAAkD,OAAO,MAClF;CACA,OAAO,IAAI,cAAc;AAC3B;AAEA,SAAS,SAAS,OAAgB,oBAAwC;CACxE,OAAO,oBAAoB,oBAAoB,OAAO,OAAO,IAAI;AACnE;AAEA,SAAS,eACP,OACA,oBACA;CACA,OAAO,oBAAoB,oBAAoB,OAAO,OAAO,KAAK;AACpE"}
|
|
1
|
+
{"version":3,"file":"custom.js","names":["#dbTransaction","#schema","#serverSchema","#addRetryPredicate","#tableCRUDs"],"sources":["../../../../zero-server/src/custom.ts"],"sourcesContent":["import {assert} from '../../shared/src/asserts.ts';\nimport type {ReadonlyJSONValue} from '../../shared/src/json.ts';\nimport {mapValues} from '../../shared/src/objects.ts';\nimport {recordProxy} from '../../shared/src/record-proxy.ts';\nimport {\n formatPgInternalConvert,\n sql,\n sqlConvertColumnArg,\n} from '../../z2s/src/sql.ts';\nimport type {TableSchema} from '../../zero-schema/src/table-schema.ts';\nimport type {Schema} from '../../zero-types/src/schema.ts';\nimport type {\n ServerColumnSchema,\n ServerSchema,\n ServerTableSchema,\n} from '../../zero-types/src/server-schema.ts';\nimport {\n type CRUDExecutor,\n type CRUDKind,\n makeCRUDMutate,\n makeTransactionMutate,\n type SchemaCRUD,\n type TableCRUD,\n type TransactionMutate,\n} from '../../zql/src/mutate/crud.ts';\nimport type {\n DBTransaction,\n MutateCRUD,\n Queryable,\n RetryPredicate,\n ServerTransaction,\n} from '../../zql/src/mutate/custom.ts';\nimport {createRunnableBuilder} from '../../zql/src/query/create-builder.ts';\nimport {QueryDelegateBase} from '../../zql/src/query/query-delegate-base.ts';\nimport {asQueryInternals} from '../../zql/src/query/query-internals.ts';\nimport type {\n HumanReadable,\n Query,\n RunOptions,\n} from '../../zql/src/query/query.ts';\nimport type {ConditionalSchemaQuery} from '../../zql/src/query/schema-query.ts';\nimport {getServerSchema} from './schema.ts';\n\nexport type CustomMutatorDefs<TDBTransaction> = {\n [namespaceOrKey: string]:\n | CustomMutatorImpl<TDBTransaction>\n | CustomMutatorDefs<TDBTransaction>;\n};\n\nexport type CustomMutatorImpl<\n TDBTransaction,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n TArgs = any,\n Context = unknown,\n> = (\n tx: TDBTransaction,\n args: TArgs,\n ctx: Context,\n) => Promise<ReadonlyJSONValue | void>;\n\n/**\n * QueryDelegate implementation for server-side transactions.\n * Extends QueryDelegateBase to satisfy the QueryDelegate interface,\n * but overrides run() to execute against Postgres and throws on\n * preload()/materialize() which don't make sense server-side.\n */\nclass ServerTransactionQueryDelegate extends QueryDelegateBase {\n readonly #dbTransaction: DBTransaction<unknown>;\n readonly #schema: Schema;\n readonly #serverSchema: ServerSchema;\n\n readonly defaultQueryComplete = true;\n\n constructor(\n dbTransaction: DBTransaction<unknown>,\n schema: Schema,\n serverSchema: ServerSchema,\n ) {\n super();\n this.#dbTransaction = dbTransaction;\n this.#schema = schema;\n this.#serverSchema = serverSchema;\n }\n\n getSource(): never {\n throw new Error('not implemented');\n }\n\n override run<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends Schema,\n TReturn,\n >(\n query: Query<TTable, TSchema, TReturn>,\n _options?: RunOptions,\n ): Promise<HumanReadable<TReturn>> {\n const queryInternals = asQueryInternals(query);\n return this.#dbTransaction.runQuery<TReturn>(\n queryInternals.ast,\n queryInternals.format,\n this.#schema,\n this.#serverSchema,\n );\n }\n\n override preload(): never {\n throw new Error('preload() is not supported in server transactions');\n }\n\n override materialize(): never {\n throw new Error('materialize() is not supported in server transactions');\n }\n}\n\nexport class TransactionImpl<\n TSchema extends Schema,\n TWrappedTransaction,\n> implements ServerTransaction<TSchema, TWrappedTransaction> {\n readonly location = 'server';\n readonly reason = 'authoritative';\n readonly dbTransaction: DBTransaction<TWrappedTransaction>;\n readonly clientID: string;\n readonly mutationID: number;\n readonly mutate: TransactionMutate<TSchema>;\n /**\n * @deprecated Use {@link createBuilder} with `tx.run(zql.table.where(...))` instead.\n */\n readonly query: ConditionalSchemaQuery<TSchema>;\n\n readonly #schema: TSchema;\n readonly #serverSchema: ServerSchema;\n readonly #addRetryPredicate:\n | ((shouldRetry: RetryPredicate) => void)\n | undefined;\n\n constructor(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n mutate: TransactionMutate<TSchema>,\n schema: TSchema,\n serverSchema: ServerSchema,\n addRetryPredicate?: ((shouldRetry: RetryPredicate) => void) | undefined,\n ) {\n this.dbTransaction = dbTransaction;\n this.clientID = clientID;\n this.mutationID = mutationID;\n this.mutate = mutate;\n this.#schema = schema;\n this.#serverSchema = serverSchema;\n this.#addRetryPredicate = addRetryPredicate;\n\n const delegate = new ServerTransactionQueryDelegate(\n dbTransaction,\n schema,\n serverSchema,\n );\n this.query = createRunnableBuilder(delegate, schema);\n }\n\n retryOn(shouldRetry: RetryPredicate): void {\n if (this.#addRetryPredicate === undefined) {\n // Fail loudly: a predicate nothing will consult would silently turn\n // every retryable failure into a recorded error.\n throw new Error(\n 'tx.retryOn() is not supported on this transaction: nothing will re-run its mutator. A custom Database must pass TransactionProviderInput.addRetryPredicate on to createTransaction.',\n );\n }\n this.#addRetryPredicate(shouldRetry);\n }\n\n run<TTable extends keyof TSchema['tables'] & string, TReturn>(\n query: Query<TTable, TSchema, TReturn>,\n _options?: RunOptions,\n ): Promise<HumanReadable<TReturn>> {\n const queryInternals = asQueryInternals(query);\n\n // Execute the query using the database-specific executor\n return this.dbTransaction.runQuery<TReturn>(\n queryInternals.ast,\n queryInternals.format,\n this.#schema,\n this.#serverSchema,\n );\n }\n}\n\nconst dbTxSymbol = Symbol();\n\nconst serverSchemaSymbol = Symbol();\n\ntype WithHiddenTxAndSchema = {\n [dbTxSymbol]: DBTransaction<unknown>;\n [serverSchemaSymbol]: ServerSchema;\n};\n\n/**\n * Factory for creating MutateCRUD instances efficiently.\n *\n * Pre-creates the SQL-generating TableCRUD methods once from the schema,\n * caches the serverSchema after first fetch, and only binds the transaction\n * at transaction time.\n *\n * Use this when you need to create many transactions and want to avoid\n * the overhead of re-creating CRUD methods for each one.\n */\nexport class CRUDMutatorFactory<S extends Schema> {\n readonly #schema: S;\n readonly #tableCRUDs: Record<string, TableCRUD<TableSchema>>;\n // The in-flight or resolved fetch is cached (not just the result) so that\n // concurrent cold callers share a single catalog query.\n #serverSchema: Promise<ServerSchema> | undefined;\n\n constructor(schema: S) {\n this.#schema = schema;\n // Pre-create TableCRUD methods for each table once\n this.#tableCRUDs = {};\n for (const tableSchema of Object.values(schema.tables)) {\n this.#tableCRUDs[tableSchema.name] = makeServerTableCRUD(tableSchema);\n }\n }\n\n /**\n * Gets the cached serverSchema, or fetches and caches it on first call.\n */\n getOrFetchServerSchema(queryable: Queryable): Promise<ServerSchema> {\n if (!this.#serverSchema) {\n this.#serverSchema = getServerSchema(queryable, this.#schema).catch(e => {\n // Don't poison the cache with a transient failure.\n this.#serverSchema = undefined;\n throw e;\n });\n }\n return this.#serverSchema;\n }\n\n /**\n * Creates a CRUDExecutor bound to the given transaction and serverSchema.\n * Uses the pre-created TableCRUD methods from construction time.\n */\n createExecutor(\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n ): CRUDExecutor {\n const txHolder: WithHiddenTxAndSchema = {\n [dbTxSymbol]: dbTransaction,\n [serverSchemaSymbol]: serverSchema,\n };\n const boundCRUDs = recordProxy(this.#tableCRUDs, tableCRUD =>\n mapValues(tableCRUD, method => method.bind(txHolder)),\n ) as unknown as SchemaCRUD<S>;\n\n return (table: string, kind: CRUDKind, args: unknown) => {\n const tableCRUD = boundCRUDs[table as keyof S['tables']];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (tableCRUD as any)[kind](args);\n };\n }\n\n /**\n * Creates a full ServerTransaction.\n * Fetches/caches serverSchema automatically.\n */\n async createTransaction<TWrappedTransaction>(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n addRetryPredicate?: ((shouldRetry: RetryPredicate) => void) | undefined,\n ): Promise<TransactionImpl<S, TWrappedTransaction>> {\n const serverSchema = await this.getOrFetchServerSchema(dbTransaction);\n const executor = this.createExecutor(dbTransaction, serverSchema);\n const mutate = makeTransactionMutate(this.#schema, executor);\n return new TransactionImpl(\n dbTransaction,\n clientID,\n mutationID,\n mutate,\n this.#schema,\n serverSchema,\n addRetryPredicate,\n );\n }\n}\n\nexport async function makeServerTransaction<\n TSchema extends Schema,\n TWrappedTransaction,\n>(\n dbTransaction: DBTransaction<TWrappedTransaction>,\n clientID: string,\n mutationID: number,\n schema: TSchema,\n) {\n const serverSchema = await getServerSchema(dbTransaction, schema);\n // Use the internal executor and shared function directly,\n // bypassing the validation in makeMutateCRUD/makeSchemaCRUD\n const executor = makeServerCRUDExecutor(schema, dbTransaction, serverSchema);\n const mutate = makeTransactionMutate(schema, executor);\n return new TransactionImpl(\n dbTransaction,\n clientID,\n mutationID,\n mutate,\n schema,\n serverSchema,\n );\n}\n\n/**\n * @deprecated Use transactions instead.\n *\n * Returns a curried function for backwards compatibility.\n */\nexport function makeSchemaCRUD<S extends Schema>(\n schema: S,\n): (\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n) => MutateCRUD<S, true> {\n return (dbTransaction: DBTransaction<unknown>, serverSchema: ServerSchema) =>\n makeCRUDMutate(\n schema,\n true,\n makeServerCRUDExecutor(schema, dbTransaction, serverSchema),\n );\n}\n\nfunction removeUndefined<T extends Record<string, unknown>>(value: T): T {\n const valueWithoutUndefined: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n valueWithoutUndefined[key] = val;\n }\n }\n return valueWithoutUndefined as T;\n}\n\n/**\n * Creates a CRUDExecutor for server-side SQL execution.\n *\n * For users with very large schemas it is expensive to re-create\n * all the CRUD mutators for each transaction. Instead, we create\n * the SQL-generating methods once up-front and then bind them to\n * the transaction as requested.\n */\nfunction makeServerCRUDExecutor<S extends Schema>(\n schema: S,\n dbTransaction: DBTransaction<unknown>,\n serverSchema: ServerSchema,\n): CRUDExecutor {\n // Pre-create TableCRUD methods for each table (optimization for large schemas)\n const tableCRUDs: Record<string, TableCRUD<TableSchema>> = {};\n for (const tableSchema of Object.values(schema.tables)) {\n tableCRUDs[tableSchema.name] = makeServerTableCRUD(tableSchema);\n }\n\n // Bind transaction context to the methods\n const txHolder: WithHiddenTxAndSchema = {\n [dbTxSymbol]: dbTransaction,\n [serverSchemaSymbol]: serverSchema,\n };\n const boundCRUDs = recordProxy(tableCRUDs, tableCRUD =>\n mapValues(tableCRUD, method => method.bind(txHolder)),\n ) as unknown as SchemaCRUD<S>;\n\n // Return executor that dispatches to bound methods\n return (table: string, kind: CRUDKind, args: unknown) => {\n const tableCRUD = boundCRUDs[table as keyof S['tables']];\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n return (tableCRUD as any)[kind](args);\n };\n}\n\n/**\n * Creates SQL-generating TableCRUD methods for a table.\n * Methods use `this` context to access transaction and server schema.\n */\nfunction makeServerTableCRUD(schema: TableSchema): TableCRUD<TableSchema> {\n return {\n async insert(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const primaryKeyColumns = origAndServerNamesFor(\n schema.primaryKey,\n schema,\n );\n\n const stmt = formatPgInternalConvert(\n sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(\n targetedColumns.map(([, serverName]) => sql.ident(serverName)),\n ',',\n )}) VALUES (${sql.join(\n Object.entries(value).map(([col, v]) =>\n sqlInsertValue(v, serverTableSchema[serverNameFor(col, schema)]),\n ),\n ', ',\n )}) ON CONFLICT (${sql.join(\n primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)),\n ', ',\n )}) DO NOTHING`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async upsert(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const targetedColumns = origAndServerNamesFor(Object.keys(value), schema);\n const primaryKeyColumns = origAndServerNamesFor(\n schema.primaryKey,\n schema,\n );\n const updatedEntries = nonPrimaryKeyEntries(value, schema);\n const conflictAction =\n updatedEntries.length === 0\n ? sql`DO NOTHING`\n : sql`DO UPDATE SET ${sql.join(\n updatedEntries.map(\n ([col, val]) =>\n sql`${sql.ident(\n schema.columns[col].serverName ?? col,\n )} = ${sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)])}`,\n ),\n ', ',\n )}`;\n const stmt = formatPgInternalConvert(\n sql`INSERT INTO ${sql.ident(serverName(schema))} (${sql.join(\n targetedColumns.map(([, serverName]) => sql.ident(serverName)),\n ',',\n )}) VALUES (${sql.join(\n Object.entries(value).map(([col, val]) =>\n sqlInsertValue(val, serverTableSchema[serverNameFor(col, schema)]),\n ),\n ', ',\n )}) ON CONFLICT (${sql.join(\n primaryKeyColumns.map(([, serverName]) => sql.ident(serverName)),\n ', ',\n )}) ${conflictAction}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async update(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const targetedColumns = origAndServerNamesFor(\n nonPrimaryKeyEntries(value, schema).map(([name]) => name),\n schema,\n );\n if (targetedColumns.length === 0) {\n return;\n }\n const stmt = formatPgInternalConvert(\n sql`UPDATE ${sql.ident(serverName(schema))} SET ${sql.join(\n targetedColumns.map(\n ([origName, serverName]) =>\n sql`${sql.ident(serverName)} = ${sqlInsertValue(value[origName], serverTableSchema[serverName])}`,\n ),\n ', ',\n )} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n async delete(this: WithHiddenTxAndSchema, value) {\n value = removeUndefined(value);\n const serverTableSchema = this[serverSchemaSymbol][serverName(schema)];\n const stmt = formatPgInternalConvert(\n sql`DELETE FROM ${sql.ident(\n serverName(schema),\n )} WHERE ${primaryKeyClause(schema, serverTableSchema, value)}`,\n );\n const tx = this[dbTxSymbol];\n await tx.query(stmt.text, stmt.values);\n },\n };\n}\n\nfunction nonPrimaryKeyEntries(\n value: Record<string, unknown>,\n schema: TableSchema,\n) {\n return Object.entries(value).filter(\n ([name]) => !schema.primaryKey.includes(name),\n );\n}\n\nfunction serverName(x: {name: string; serverName?: string | undefined}) {\n return x.serverName ?? x.name;\n}\n\nfunction primaryKeyClause(\n schema: TableSchema,\n serverTableSchema: ServerTableSchema,\n row: Record<string, unknown>,\n) {\n const primaryKey = origAndServerNamesFor(schema.primaryKey, schema);\n return sql`${sql.join(\n primaryKey.map(\n ([origName, serverName]) =>\n sql`${sql.ident(serverName)} = ${sqlValue(row[origName], serverTableSchema[serverName])}`,\n ),\n ' AND ',\n )}`;\n}\n\nfunction origAndServerNamesFor(\n originalNames: readonly string[],\n schema: TableSchema,\n): [origName: string, serverName: string][] {\n return originalNames.map(\n name => [name, serverNameFor(name, schema)] as const,\n );\n}\n\nfunction serverNameFor(originalName: string, schema: TableSchema): string {\n const col = schema.columns[originalName];\n assert(\n col,\n `Column ${originalName} was not found in the Zero schema for the table ${schema.name}`,\n );\n return col.serverName ?? originalName;\n}\n\nfunction sqlValue(value: unknown, serverColumnSchema: ServerColumnSchema) {\n return sqlConvertColumnArg(serverColumnSchema, value, false, true);\n}\n\nfunction sqlInsertValue(\n value: unknown,\n serverColumnSchema: ServerColumnSchema,\n) {\n return sqlConvertColumnArg(serverColumnSchema, value, false, false);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkEA,IAAM,iCAAN,cAA6C,kBAAkB;CAC7D;CACA;CACA;CAEA,uBAAgC;CAEhC,YACE,eACA,QACA,cACA;EACA,MAAM;EACN,KAAKA,iBAAiB;EACtB,KAAKC,UAAU;EACf,KAAKC,gBAAgB;CACvB;CAEA,YAAmB;EACjB,MAAM,IAAI,MAAM,iBAAiB;CACnC;CAEA,IAKE,OACA,UACiC;EACjC,MAAM,iBAAiB,iBAAiB,KAAK;EAC7C,OAAO,KAAKF,eAAe,SACzB,eAAe,KACf,eAAe,QACf,KAAKC,SACL,KAAKC,aACP;CACF;CAEA,UAA0B;EACxB,MAAM,IAAI,MAAM,mDAAmD;CACrE;CAEA,cAA8B;EAC5B,MAAM,IAAI,MAAM,uDAAuD;CACzE;AACF;AAEA,IAAa,kBAAb,MAG6D;CAC3D,WAAoB;CACpB,SAAkB;CAClB;CACA;CACA;CACA;;;;CAIA;CAEA;CACA;CACA;CAIA,YACE,eACA,UACA,YACA,QACA,QACA,cACA,mBACA;EACA,KAAK,gBAAgB;EACrB,KAAK,WAAW;EAChB,KAAK,aAAa;EAClB,KAAK,SAAS;EACd,KAAKD,UAAU;EACf,KAAKC,gBAAgB;EAC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SAAQ,CAAC,MAAM,cAAc,MAAM,MAAM,CAAC,CAC5C;AACF;AAEA,SAAS,cAAc,cAAsB,QAA6B;CACxE,MAAM,MAAM,OAAO,QAAQ;CAC3B,OACE,KACA,UAAU,aAAa,kDAAkD,OAAO,MAClF;CACA,OAAO,IAAI,cAAc;AAC3B;AAEA,SAAS,SAAS,OAAgB,oBAAwC;CACxE,OAAO,oBAAoB,oBAAoB,OAAO,OAAO,IAAI;AACnE;AAEA,SAAS,eACP,OACA,oBACA;CACA,OAAO,oBAAoB,oBAAoB,OAAO,OAAO,KAAK;AACpE"}
|
|
@@ -42,11 +42,11 @@ export type Parsed<D extends Database<ExtractTransactionType<D>>> = {
|
|
|
42
42
|
mutations: CustomMutation[];
|
|
43
43
|
};
|
|
44
44
|
/**
|
|
45
|
-
* @deprecated Use {@
|
|
45
|
+
* @deprecated Use {@link handleMutateRequest} instead.
|
|
46
46
|
*/
|
|
47
47
|
export declare const handleMutationRequest: typeof handleMutateRequest;
|
|
48
48
|
/**
|
|
49
|
-
* Parsed query params accepted by {@
|
|
49
|
+
* Parsed query params accepted by {@link handleMutateRequest} when the
|
|
50
50
|
* incoming request URL has already been handled by your framework.
|
|
51
51
|
*/
|
|
52
52
|
export type MutateSearchParams = URLSearchParams | Record<string, string>;
|
|
@@ -72,7 +72,7 @@ export type HandleMutateRequestArgs<D extends Database<ExtractTransactionType<D>
|
|
|
72
72
|
* Destination for this request's log output. When omitted, logs are written
|
|
73
73
|
* with `console.log`/`info`/`warn`/`error` etc.
|
|
74
74
|
*
|
|
75
|
-
* Provide a custom {@
|
|
75
|
+
* Provide a custom {@link LogSink} to redirect logs — for example into an
|
|
76
76
|
* application's own structured logging pipeline, so that records emitted while
|
|
77
77
|
* processing a push carry the same fields as the rest of the server's logs.
|
|
78
78
|
*/
|
|
@@ -24,7 +24,7 @@ var applicationErrorWrapper = async (fn) => {
|
|
|
24
24
|
}
|
|
25
25
|
};
|
|
26
26
|
/**
|
|
27
|
-
* @deprecated Use {@
|
|
27
|
+
* @deprecated Use {@link handleMutateRequest} instead.
|
|
28
28
|
*/
|
|
29
29
|
var handleMutationRequest = handleMutateRequest;
|
|
30
30
|
async function handleMutateRequest(inputOrDbProvider, maybeHandler, requestOrQuery, bodyOrLogLevel, logLevelOrLogSink, maybeLogSink) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"process-mutations.js","names":["#dbProvider","#req","#params","#lc","#transactImpl","#shouldRetry","#checkAndIncrementLastMutationID","#getTransactionInput"],"sources":["../../../../zero-server/src/process-mutations.ts"],"sourcesContent":["import {\n consoleLogSink,\n type LogContext,\n type LogLevel,\n type LogSink,\n} from '@rocicorp/logger';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {getErrorDetails, getErrorMessage} from '../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../shared/src/json.ts';\nimport {promiseVoid} from '../../shared/src/resolved-promises.ts';\nimport type {MaybePromise} from '../../shared/src/types.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport {MutationAlreadyProcessedError} from '../../zero-cache/src/services/mutagen/error.ts';\nimport type {ApplicationError} from '../../zero-protocol/src/application-error.ts';\nimport {\n isApplicationError,\n wrapWithApplicationError,\n} from '../../zero-protocol/src/application-error.ts';\nimport {ErrorKind} from '../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../zero-protocol/src/error-reason.ts';\nimport type {PushFailedBody} from '../../zero-protocol/src/error.ts';\nimport {\n mutateParamsSchema,\n type MutateResponse,\n} from '../../zero-protocol/src/mutate-server.ts';\nimport type {MutationID} from '../../zero-protocol/src/mutation-id.ts';\nimport {\n CLEANUP_RESULTS_MUTATION_NAME,\n cleanupResultsArgSchema,\n type CleanupResultsArg,\n type CustomMutation,\n type Mutation,\n} from '../../zero-protocol/src/mutation.ts';\nimport {\n pushBodySchema,\n type MutationResponse,\n type PushBody,\n} from '../../zero-protocol/src/push.ts';\nimport type {RetryPredicate} from '../../zql/src/mutate/custom.ts';\nimport type {AnyMutatorRegistry} from '../../zql/src/mutate/mutator-registry.ts';\nimport {isMutator} from '../../zql/src/mutate/mutator.ts';\nimport type {CustomMutatorDefs, CustomMutatorImpl} from './custom.ts';\nimport {createLogContext} from './logging.ts';\nimport {separatorRe} from './push-processor.ts';\n\nexport interface TransactionProviderHooks {\n updateClientMutationID: () => Promise<{lastMutationID: number | bigint}>;\n writeMutationResult: (result: MutationResponse) => Promise<void>;\n deleteMutationResults: (args: CleanupResultsArg) => Promise<void>;\n}\n\nexport interface TransactionProviderInput {\n upstreamSchema: string;\n clientGroupID: string;\n clientID: string;\n mutationID: number;\n /**\n * Receives each predicate the mutator registers with `tx.retryOn()`. A\n * `Database` passes it on to the server transaction it creates.\n */\n addRetryPredicate?: ((shouldRetry: RetryPredicate) => void) | undefined;\n}\n\n/**\n * Defines the abstract interface for a database that PushProcessor can execute\n * transactions against.\n */\nexport interface Database<T> {\n transaction: <R>(\n callback: (\n tx: T,\n transactionHooks: TransactionProviderHooks,\n ) => MaybePromise<R>,\n transactionInput?: TransactionProviderInput,\n ) => Promise<R>;\n}\n\nexport type ExtractTransactionType<D> = D extends Database<infer T> ? T : never;\nexport type Params = v.Infer<typeof mutateParamsSchema>;\n\nexport type TransactFn<D extends Database<ExtractTransactionType<D>>> = (\n cb: TransactFnCallback<D>,\n) => Promise<MutationResponse>;\n\nexport type TransactFnCallback<D extends Database<ExtractTransactionType<D>>> =\n (\n tx: ExtractTransactionType<D>,\n mutatorName: string,\n mutatorArgs: ReadonlyJSONValue | undefined,\n ) => Promise<ReadonlyJSONValue | void>;\n\nexport type Parsed<D extends Database<ExtractTransactionType<D>>> = {\n transact: TransactFn<D>;\n mutations: CustomMutation[];\n};\n\ntype MutationPhase = 'preTransaction' | 'transactionPending' | 'postCommit';\n\nconst applicationErrorWrapper = async <T>(fn: () => Promise<T>): Promise<T> => {\n try {\n return await fn();\n } catch (error) {\n if (\n error instanceof DatabaseTransactionError ||\n error instanceof OutOfOrderMutation ||\n error instanceof MutationAlreadyProcessedError ||\n isApplicationError(error)\n ) {\n throw error;\n }\n\n throw wrapWithApplicationError(error);\n }\n};\n\n/**\n * @deprecated Use {@linkcode handleMutateRequest} instead.\n */\nexport const handleMutationRequest = handleMutateRequest;\n\n/**\n * Parsed query params accepted by {@linkcode handleMutateRequest} when the\n * incoming request URL has already been handled by your framework.\n */\nexport type MutateSearchParams = URLSearchParams | Record<string, string>;\n\n/**\n * Runs once per custom mutation in a `/mutate` request.\n *\n * Call `transact` to execute database work for the mutation. Throwing before\n * `transact` persists an application error; throwing after `transact` resolves\n * only affects server-side logging because the mutation is already committed.\n */\nexport type MutateRequestHandler<\n D extends Database<ExtractTransactionType<D>>,\n> = (\n transact: TransactFn<D>,\n mutation: CustomMutation,\n) => Promise<MutationResponse>;\n\nexport type HandleMutateRequestArgs<\n D extends Database<ExtractTransactionType<D>>,\n> = {\n /** Database used to run transactions and store mutation results. */\n dbProvider: D;\n handler: MutateRequestHandler<D>;\n /**\n * Authenticated user ID. Null or undefined means the user is logged out.\n */\n userID: string | null | undefined;\n /** Optional log level for request parsing and execution. */\n logLevel?: LogLevel | undefined;\n /**\n * Destination for this request's log output. When omitted, logs are written\n * with `console.log`/`info`/`warn`/`error` etc.\n *\n * Provide a custom {@linkcode LogSink} to redirect logs — for example into an\n * application's own structured logging pipeline, so that records emitted while\n * processing a push carry the same fields as the rest of the server's logs.\n */\n logSink?: LogSink | undefined;\n} & (\n | {\n /** Fetch request containing both query params and the JSON body. */\n request: Request;\n }\n | {\n /** Parsed query params from the `/mutate` request URL. */\n query: MutateSearchParams;\n /** Parsed JSON body from the `/mutate` request. */\n body: ReadonlyJSONValue;\n }\n);\n\ntype NormalizedMutateRequestArgs<\n D extends Database<ExtractTransactionType<D>>,\n> = {\n readonly dbProvider: D;\n readonly handler: MutateRequestHandler<D>;\n // Note: semantics of undefined differ from HandleMutateRequestArgs.userID.\n // Here, undefined means the app didn't provide a user ID - we do not know if\n // the user is logged in or not. This is legacy behavior needed to support\n // deprecated signatures of handleMutateRequest which did not receive userID\n // from app.\n readonly userID: string | null | undefined;\n readonly logLevel: LogLevel;\n readonly logSink: LogSink;\n} & (\n | {\n readonly type: 'request';\n readonly request: Request;\n }\n | {\n readonly type: 'body';\n readonly queryParams: Record<string, string>;\n readonly jsonBody: ReadonlyJSONValue;\n }\n);\n\n/**\n * Process a `/mutate` request from a Fetch `Request`.\n */\nexport function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(input: HandleMutateRequestArgs<D>): Promise<MutateResponse>;\n\n/**\n * @deprecated Pass a single object instead:\n * `handleMutateRequest({dbProvider, handler, query, body, userID, logLevel})`.\n */\nexport function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n handler: MutateRequestHandler<D>,\n query: MutateSearchParams,\n body: ReadonlyJSONValue,\n logLevel?: LogLevel,\n logSink?: LogSink,\n): Promise<MutateResponse>;\n\n/**\n * @deprecated Pass a single object instead:\n * `handleMutateRequest({dbProvider, handler, request, userID, logLevel})`.\n */\nexport function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n handler: MutateRequestHandler<D>,\n request: Request,\n logLevel?: LogLevel,\n logSink?: LogSink,\n): Promise<MutateResponse>;\n\nexport async function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(\n inputOrDbProvider: HandleMutateRequestArgs<D> | D,\n maybeHandler?: MutateRequestHandler<D> | undefined,\n requestOrQuery?: Request | MutateSearchParams | undefined,\n bodyOrLogLevel?: ReadonlyJSONValue | LogLevel | undefined,\n logLevelOrLogSink?: LogLevel | LogSink | undefined,\n maybeLogSink?: LogSink | undefined,\n): Promise<MutateResponse> {\n const normalized =\n typeof inputOrDbProvider === 'object' && 'handler' in inputOrDbProvider\n ? normalizeMutateRequestInput(inputOrDbProvider)\n : normalizeLegacyMutateRequestArgs(\n inputOrDbProvider,\n maybeHandler,\n requestOrQuery,\n bodyOrLogLevel,\n logLevelOrLogSink,\n maybeLogSink,\n );\n\n const lc = createLogContext(\n normalized.logLevel,\n normalized.logSink,\n ).withContext('PushProcessor');\n let jsonBody: unknown;\n\n if (normalized.type === 'request') {\n try {\n jsonBody = await normalized.request.json();\n } catch (error) {\n lc.error?.('Failed to parse push body', error);\n const message = `Failed to parse push body: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n mutationIDs: [],\n ...(details ? {details} : {}),\n } as const satisfies PushFailedBody;\n }\n } else {\n jsonBody = normalized.jsonBody;\n }\n\n let mutationIDs: MutationID[] = [];\n\n let pushBody: PushBody;\n try {\n pushBody = v.parse(jsonBody, pushBodySchema, 'passthrough');\n mutationIDs = pushBody.mutations.map(m => ({\n id: m.id,\n clientID: m.clientID,\n }));\n } catch (error) {\n lc.error?.('Failed to parse push body', error);\n const message = `Failed to parse push body: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n mutationIDs,\n ...(details ? {details} : {}),\n } as const satisfies PushFailedBody;\n }\n\n let parsedQueryParams: Params;\n try {\n parsedQueryParams = v.parse(\n normalized.type === 'request'\n ? Object.fromEntries(new URL(normalized.request.url).searchParams)\n : normalized.queryParams,\n mutateParamsSchema,\n 'passthrough',\n );\n } catch (error) {\n lc.error?.('Failed to parse push query parameters', error);\n const message = `Failed to parse push query parameters: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n mutationIDs,\n ...(details ? {details} : {}),\n } as const satisfies PushFailedBody;\n }\n\n if (pushBody.pushVersion !== 1) {\n const response = {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.UnsupportedPushVersion,\n mutationIDs,\n message: `Unsupported push version: ${pushBody.pushVersion}`,\n } as const satisfies PushFailedBody;\n return response;\n }\n\n const responses: MutationResponse[] = [];\n let processedCount = 0;\n\n try {\n const transactor = new Transactor(\n normalized.dbProvider,\n pushBody,\n parsedQueryParams,\n lc,\n );\n\n // Each mutation goes through three phases:\n // 1. Pre-transaction: user logic that runs before `transact` is called. If\n // this throws we still advance LMID and persist the failure result.\n // 2. Transaction: the callback passed to `transact`, which can be retried\n // if it fails with an ApplicationError.\n // 3. Post-commit: any logic that runs after `transact` resolves. Failures\n // here are logged but the mutation remains committed.\n for (const m of pushBody.mutations) {\n // Handle internal mutations (like cleanup) directly without user dispatch\n if (m.type === 'custom' && m.name === CLEANUP_RESULTS_MUTATION_NAME) {\n lc.debug?.(\n `Processing internal mutation '${m.name}' (clientID=${m.clientID})`,\n );\n try {\n await processCleanupResultsMutation(\n normalized.dbProvider,\n m,\n parsedQueryParams,\n lc,\n );\n // No response added - this is fire-and-forget\n processedCount++;\n } catch (error) {\n lc.warn?.(\n `Failed to process cleanup mutation for client ${m.clientID}`,\n error,\n );\n // Don't fail the whole push for cleanup errors\n processedCount++;\n }\n continue;\n }\n\n assert(m.type === 'custom', 'Expected custom mutation');\n lc.debug?.(\n `Processing mutation '${m.name}' (id=${m.id}, clientID=${m.clientID})`,\n );\n\n let mutationPhase: MutationPhase = 'preTransaction';\n\n const transactProxy: TransactFn<D> = async innerCb => {\n mutationPhase = 'transactionPending';\n const result = await transactor.transact(m, innerCb);\n mutationPhase = 'postCommit';\n return result;\n };\n\n try {\n const res = await applicationErrorWrapper(() =>\n normalized.handler(transactProxy, m),\n );\n responses.push(res);\n lc.debug?.(`Mutation '${m.name}' (id=${m.id}) completed successfully`);\n\n processedCount++;\n } catch (error) {\n if (!isApplicationError(error)) {\n throw error;\n }\n\n if (mutationPhase === 'preTransaction') {\n // Pre-transaction\n await transactor.persistPreTransactionFailure(m, error);\n } else if (mutationPhase === 'postCommit') {\n // Post-commit\n lc.error?.(\n `Post-commit mutation handler failed for mutation ${m.id} for client ${m.clientID}`,\n error,\n );\n }\n\n lc.warn?.(\n `Application error processing mutation ${m.id} for client ${m.clientID}`,\n error,\n );\n responses.push(makeAppErrorResponse(m, error));\n\n processedCount++;\n }\n }\n\n return {\n kind: 'MutateResponse',\n mutations: responses,\n ...(typeof normalized.userID !== 'undefined'\n ? {userID: normalized.userID}\n : {}),\n } as const satisfies MutateResponse;\n } catch (error) {\n lc.error?.('Failed to process push request', error);\n // only include mutationIDs for mutations that were not processed\n const unprocessedMutationIDs = mutationIDs.slice(processedCount);\n\n const message = getErrorMessage(error);\n const details = getErrorDetails(error);\n\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason:\n error instanceof OutOfOrderMutation\n ? ErrorReason.OutOfOrderMutation\n : error instanceof DatabaseTransactionError\n ? ErrorReason.Database\n : ErrorReason.Internal,\n message,\n mutationIDs: unprocessedMutationIDs,\n ...(details ? {details} : {}),\n };\n }\n}\n\nfunction normalizeMutateRequestInput<\n D extends Database<ExtractTransactionType<D>>,\n>(input: HandleMutateRequestArgs<D>): NormalizedMutateRequestArgs<D> {\n if ('request' in input) {\n return {\n type: 'request',\n dbProvider: input.dbProvider,\n handler: input.handler,\n request: input.request,\n userID: input.userID ?? null,\n logLevel: input.logLevel ?? 'info',\n logSink: input.logSink ?? consoleLogSink,\n };\n }\n\n return {\n type: 'body',\n dbProvider: input.dbProvider,\n handler: input.handler,\n jsonBody: input.body,\n userID: input.userID ?? null,\n queryParams:\n input.query instanceof URLSearchParams\n ? Object.fromEntries(input.query)\n : input.query,\n logLevel: input.logLevel ?? 'info',\n logSink: input.logSink ?? consoleLogSink,\n };\n}\n\nfunction normalizeLegacyMutateRequestArgs<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n handler: MutateRequestHandler<D> | undefined,\n requestOrQuery: Request | MutateSearchParams | undefined,\n bodyOrLogLevel: ReadonlyJSONValue | LogLevel | undefined,\n logLevelOrLogSink: LogLevel | LogSink | undefined,\n maybeLogSink: LogSink | undefined,\n): NormalizedMutateRequestArgs<D> {\n assert(typeof handler === 'function', 'Handler function is required');\n assert(\n typeof requestOrQuery !== 'undefined',\n 'Request or query parameters are required',\n );\n\n if (requestOrQuery instanceof Request) {\n return {\n type: 'request',\n dbProvider,\n handler,\n request: requestOrQuery,\n userID: undefined,\n logLevel: (bodyOrLogLevel as LogLevel | undefined) ?? 'info',\n // The `request` overload has no `body` slot, so the sink arrives one\n // position earlier than it does in the `query`/`body` overload.\n logSink: (logLevelOrLogSink as LogSink | undefined) ?? consoleLogSink,\n };\n }\n\n assert(\n typeof bodyOrLogLevel !== 'undefined',\n 'JSON body cannot be undefined',\n );\n\n return {\n type: 'body',\n dbProvider,\n handler,\n jsonBody: bodyOrLogLevel,\n userID: undefined,\n queryParams:\n requestOrQuery instanceof URLSearchParams\n ? Object.fromEntries(requestOrQuery)\n : requestOrQuery,\n logLevel: (logLevelOrLogSink as LogLevel | undefined) ?? 'info',\n logSink: maybeLogSink ?? consoleLogSink,\n };\n}\n\n/**\n * The most times a mutator runs for one mutation within one push when its\n * `tx.retryOn()` predicate keeps answering yes: the first run and four\n * re-runs.\n */\nexport const MAX_MUTATOR_RUNS = 5;\n\nclass Transactor<D extends Database<ExtractTransactionType<D>>> {\n readonly #dbProvider: D;\n readonly #req: PushBody;\n readonly #params: Params;\n readonly #lc: LogContext;\n\n constructor(dbProvider: D, req: PushBody, params: Params, lc: LogContext) {\n this.#dbProvider = dbProvider;\n this.#req = req;\n this.#params = params;\n this.#lc = lc;\n }\n\n /**\n * Asks all of the run's `tx.retryOn()` predicates at once whether to run\n * the mutator again. The first to answer yes decides it and the other\n * answers are ignored; it is no once every predicate has answered no. A\n * predicate that throws or rejects answers no: escaping here would skip\n * recording the mutation's result, and the client would send it again.\n */\n #shouldRetry(\n predicates: readonly RetryPredicate[],\n error: unknown,\n attempt: number,\n ): Promise<boolean> {\n if (predicates.length === 0) {\n return Promise.resolve(false);\n }\n const ask = async (shouldRetry: RetryPredicate): Promise<boolean> => {\n try {\n return (await shouldRetry(error, attempt)) === true;\n } catch (retryError) {\n this.#lc.warn?.(\n 'retryOn predicate threw; treating it as no',\n retryError,\n );\n return false;\n }\n };\n return new Promise(resolve => {\n let pending = predicates.length;\n for (const shouldRetry of predicates) {\n void ask(shouldRetry).then(yes => {\n if (yes) {\n resolve(true);\n } else if (--pending === 0) {\n resolve(false);\n }\n });\n }\n });\n }\n\n transact = async (\n mutation: CustomMutation,\n cb: TransactFnCallback<D>,\n ): Promise<MutationResponse> => {\n let appError: ApplicationError | undefined = undefined;\n // Which run of the mutator this is: 1, then 2 for the first re-run, and so\n // on. When a run fails, it is also the number of the re-run being decided.\n let attempt = 1;\n for (;;) {\n // What this run registers with `tx.retryOn()`. Each run starts empty.\n const predicates: RetryPredicate[] = [];\n try {\n const ret = await this.#transactImpl(\n mutation,\n cb,\n appError,\n shouldRetry => {\n predicates.push(shouldRetry);\n },\n );\n if (appError !== undefined) {\n this.#lc.warn?.(\n // log-leak-ignore -- mutation and client ids, not row data\n `Mutation ${mutation.id} for client ${mutation.clientID} was retried after an error`,\n appError,\n );\n return makeAppErrorResponse(mutation, appError);\n }\n\n return ret;\n } catch (error) {\n if (error instanceof OutOfOrderMutation) {\n this.#lc.error?.(error);\n throw error;\n }\n\n if (error instanceof MutationAlreadyProcessedError) {\n this.#lc.warn?.(error);\n return {\n id: {\n clientID: mutation.clientID,\n id: mutation.id,\n },\n result: {\n error: 'alreadyProcessed',\n details: error.message,\n },\n };\n }\n\n if (appError !== undefined) {\n // Retry also failed → internal error, cannot skip mutation\n this.#lc.error?.(\n // log-leak-ignore -- mutation and client ids, not row data\n `Retry also failed for mutation ${mutation.id} for client ${mutation.clientID}`,\n error,\n );\n throw error;\n }\n\n // What the mutator or the database threw, without the wrapper. This\n // includes errors raised at COMMIT, which the mutator cannot catch.\n const originalError =\n error instanceof DatabaseTransactionError\n ? (error.cause ?? error)\n : error;\n\n // One of the run's `tx.retryOn()` predicates says to run it again → do\n // so, in a fresh transaction.\n //\n // `continue` WITHOUT setting `appError` is the whole mechanism: it is\n // `appError` being set that makes the next `#transactImpl` skip\n // `cb(...)`. `#transactImpl` opens a new transaction each pass, so the\n // re-run gets a new snapshot. `#checkAndIncrementLastMutationID` re-runs\n // safely because the failed run rolled its increment back.\n if (\n attempt < MAX_MUTATOR_RUNS &&\n (await this.#shouldRetry(predicates, originalError, attempt))\n ) {\n this.#lc.warn?.(\n // log-leak-ignore -- mutation and client ids, not row data\n `Mutation ${mutation.id} for client ${mutation.clientID} failed, re-running mutator (retry ${attempt})`,\n originalError,\n );\n attempt++;\n continue;\n }\n\n // Not re-run → store error and retry without mutator\n appError = wrapWithApplicationError(originalError);\n this.#lc.warn?.(\n // log-leak-ignore -- mutation and client ids, not row data\n `Error processing mutation ${mutation.id} for client ${mutation.clientID}, retrying without mutator`,\n appError,\n );\n continue;\n }\n }\n };\n\n async persistPreTransactionFailure(\n mutation: CustomMutation,\n appError: ApplicationError<ReadonlyJSONValue | undefined>,\n ): Promise<MutationResponse> {\n // User-land code threw before calling `transact`. We still need to bump the\n // LMID for this mutation and persist the error so that the client knows it failed.\n const ret = await this.#transactImpl(\n mutation,\n // noop callback since there's no transaction to execute\n () => promiseVoid,\n appError,\n undefined,\n );\n return ret;\n }\n\n async #transactImpl(\n mutation: CustomMutation,\n cb: TransactFnCallback<D>,\n appError: ApplicationError | undefined,\n addRetryPredicate: ((shouldRetry: RetryPredicate) => void) | undefined,\n ): Promise<MutationResponse> {\n let transactionPhase: DatabaseTransactionPhase = 'open';\n\n try {\n const ret = await this.#dbProvider.transaction(\n async (dbTx, transactionHooks) => {\n // update the transaction phase to 'execute' after the transaction is opened\n transactionPhase = 'execute';\n\n await this.#checkAndIncrementLastMutationID(\n transactionHooks,\n mutation.clientID,\n mutation.id,\n );\n\n if (appError === undefined) {\n this.#lc.debug?.(\n // log-leak-ignore -- mutator name and mutation id, not row data\n `Executing mutator '${mutation.name}' (id=${mutation.id})`,\n );\n const data = (await cb(dbTx, mutation.name, mutation.args[0])) as\n | ReadonlyJSONValue\n | undefined;\n const id = {clientID: mutation.clientID, id: mutation.id};\n if (data === undefined) {\n return {id, result: {}};\n }\n // Persisted so the data still reaches the client if the push\n // response is lost. A mutator that returns nothing writes no row.\n const successResult: MutationResponse = {id, result: {data}};\n await transactionHooks.writeMutationResult(successResult);\n return successResult;\n } else {\n const mutationResult = makeAppErrorResponse(mutation, appError);\n await transactionHooks.writeMutationResult(mutationResult);\n return mutationResult;\n }\n },\n this.#getTransactionInput(mutation, addRetryPredicate),\n );\n\n return ret;\n } catch (error) {\n if (\n isApplicationError(error) ||\n error instanceof OutOfOrderMutation ||\n error instanceof MutationAlreadyProcessedError\n ) {\n throw error;\n }\n\n throw new DatabaseTransactionError(transactionPhase, {cause: error});\n }\n }\n\n #getTransactionInput(\n mutation: CustomMutation,\n addRetryPredicate: ((shouldRetry: RetryPredicate) => void) | undefined,\n ): TransactionProviderInput {\n return {\n upstreamSchema: this.#params.schema,\n clientGroupID: this.#req.clientGroupID,\n clientID: mutation.clientID,\n mutationID: mutation.id,\n addRetryPredicate,\n };\n }\n\n async #checkAndIncrementLastMutationID(\n transactionHooks: TransactionProviderHooks,\n clientID: string,\n receivedMutationID: number,\n ) {\n const {lastMutationID} = await transactionHooks.updateClientMutationID();\n\n if (receivedMutationID < lastMutationID) {\n throw new MutationAlreadyProcessedError(\n clientID,\n receivedMutationID,\n lastMutationID,\n );\n } else if (receivedMutationID > lastMutationID) {\n throw new OutOfOrderMutation(\n clientID,\n receivedMutationID,\n lastMutationID,\n );\n }\n }\n}\n\nexport class OutOfOrderMutation extends Error {\n constructor(\n clientID: string,\n receivedMutationID: number,\n lastMutationID: number | bigint,\n ) {\n super(\n `Client ${clientID} sent mutation ID ${receivedMutationID} but expected ${lastMutationID}`,\n );\n }\n}\n\nfunction makeAppErrorResponse(\n m: Mutation,\n error: ApplicationError<ReadonlyJSONValue | undefined>,\n): MutationResponse {\n return {\n id: {\n clientID: m.clientID,\n id: m.id,\n },\n result: {\n error: 'app',\n message: error.message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n}\n\n/** @deprecated Use getMutator instead */\nexport function getMutation(\n // oxlint-disable-next-line no-explicit-any\n mutators: AnyMutatorRegistry | CustomMutatorDefs<any>,\n name: string,\n // oxlint-disable-next-line no-explicit-any\n): CustomMutatorImpl<any> {\n const path = name.split(separatorRe);\n const mutator = getObjectAtPath(mutators, path);\n assert(typeof mutator === 'function', `could not find mutator ${name}`);\n\n if (isMutator(mutator)) {\n // mutator needs to be called with {tx, args, ctx}\n // CustomMutatorImpl is called with (tx, args, ctx)\n return (tx, args, ctx) => mutator.fn({args, ctx, tx});\n }\n\n // oxlint-disable-next-line no-explicit-any\n return mutator as CustomMutatorImpl<any>;\n}\n\nfunction getObjectAtPath(\n obj: Record<string, unknown>,\n path: string[],\n): unknown {\n let current: unknown = obj;\n for (const part of path) {\n if (typeof current !== 'object' || current === null || !(part in current)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/**\n * Processes internal cleanup mutation that deletes acknowledged mutation results\n * from the upstream database. This runs without LMID tracking since it's an\n * internal operation.\n */\nasync function processCleanupResultsMutation<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n mutation: CustomMutation,\n queryParams: Params,\n lc: LogContext,\n): Promise<void> {\n const parseResult = v.test(mutation.args[0], cleanupResultsArgSchema);\n if (!parseResult.ok) {\n // log-leak-ignore -- valita reports the failing type, not the value\n lc.warn?.('Cleanup mutation has invalid args', parseResult.error);\n return;\n }\n const args: CleanupResultsArg = parseResult.value;\n\n // Determine clientID for transaction input based on cleanup type\n // Note: legacy format without type field is treated as single\n const clientID =\n 'type' in args && args.type === 'bulk' ? args.clientIDs[0] : args.clientID;\n\n // Run in a transaction, using the hook for DB-specific operation.\n // Note: only upstreamSchema is used by deleteMutationResults; the other\n // fields are required by the interface but ignored for this operation.\n await dbProvider.transaction(\n async (_, hooks) => {\n await hooks.deleteMutationResults(args);\n },\n {\n upstreamSchema: queryParams.schema,\n clientGroupID: args.clientGroupID,\n clientID,\n mutationID: 0,\n },\n );\n}\n\ntype DatabaseTransactionPhase = 'open' | 'execute';\nclass DatabaseTransactionError extends Error {\n constructor(phase: DatabaseTransactionPhase, options?: ErrorOptions) {\n super(\n phase === 'open'\n ? `Failed to open database transaction: ${getErrorMessage(options?.cause)}`\n : `Database transaction failed after opening: ${getErrorMessage(options?.cause)}`,\n options,\n );\n this.name = 'DatabaseTransactionError';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmGA,IAAM,0BAA0B,OAAU,OAAqC;CAC7E,IAAI;EACF,OAAO,MAAM,GAAG;CAClB,SAAS,OAAO;EACd,IACE,iBAAiB,4BACjB,iBAAiB,sBACjB,iBAAiB,iCACjB,mBAAmB,KAAK,GAExB,MAAM;EAGR,MAAM,yBAAyB,KAAK;CACtC;AACF;;;;AAKA,IAAa,wBAAwB;AAqHrC,eAAsB,oBAGpB,mBACA,cACA,gBACA,gBACA,mBACA,cACyB;CACzB,MAAM,aACJ,OAAO,sBAAsB,YAAY,aAAa,oBAClD,4BAA4B,iBAAiB,IAC7C,iCACE,mBACA,cACA,gBACA,gBACA,mBACA,YACF;CAEN,MAAM,KAAK,iBACT,WAAW,UACX,WAAW,OACb,EAAE,YAAY,eAAe;CAC7B,IAAI;CAEJ,IAAI,WAAW,SAAS,WACtB,IAAI;EACF,WAAW,MAAM,WAAW,QAAQ,KAAK;CAC3C,SAAS,OAAO;EACd,GAAG,QAAQ,6BAA6B,KAAK;EAC7C,MAAM,UAAU,8BAA8B,gBAAgB,KAAK;EACnE,MAAM,UAAU,gBAAgB,KAAK;EACrC,OAAO;GACL,MAAM;GACN,QAAQ;GACR,QAAQ;GACR;GACA,aAAa,CAAC;GACd,GAAI,UAAU,EAAC,QAAO,IAAI,CAAC;EAC7B;CACF;MAEA,WAAW,WAAW;CAGxB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,qCAAqC,YAAY,KAAK;EAChE;CACF;CACA,MAAM,OAA0B,YAAY;CAI5C,MAAM,WACJ,UAAU,QAAQ,KAAK,SAAS,SAAS,KAAK,UAAU,KAAK,KAAK;CAKpE,MAAM,WAAW,YACf,OAAO,GAAG,UAAU;EAClB,MAAM,MAAM,sBAAsB,IAAI;CACxC,GACA;EACE,gBAAgB,YAAY;EAC5B,eAAe,KAAK;EACpB;EACA,YAAY;CACd,CACF;AACF;AAGA,IAAM,2BAAN,cAAuC,MAAM;CAC3C,YAAY,OAAiC,SAAwB;EACnE,MACE,UAAU,SACN,wCAAwC,gBAAgB,SAAS,KAAK,MACtE,8CAA8C,gBAAgB,SAAS,KAAK,KAChF,OACF;EACA,KAAK,OAAO;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"process-mutations.js","names":["#dbProvider","#req","#params","#lc","#transactImpl","#shouldRetry","#checkAndIncrementLastMutationID","#getTransactionInput"],"sources":["../../../../zero-server/src/process-mutations.ts"],"sourcesContent":["import {\n consoleLogSink,\n type LogContext,\n type LogLevel,\n type LogSink,\n} from '@rocicorp/logger';\nimport {assert} from '../../shared/src/asserts.ts';\nimport {getErrorDetails, getErrorMessage} from '../../shared/src/error.ts';\nimport type {ReadonlyJSONValue} from '../../shared/src/json.ts';\nimport {promiseVoid} from '../../shared/src/resolved-promises.ts';\nimport type {MaybePromise} from '../../shared/src/types.ts';\nimport * as v from '../../shared/src/valita.ts';\nimport {MutationAlreadyProcessedError} from '../../zero-cache/src/services/mutagen/error.ts';\nimport type {ApplicationError} from '../../zero-protocol/src/application-error.ts';\nimport {\n isApplicationError,\n wrapWithApplicationError,\n} from '../../zero-protocol/src/application-error.ts';\nimport {ErrorKind} from '../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../zero-protocol/src/error-reason.ts';\nimport type {PushFailedBody} from '../../zero-protocol/src/error.ts';\nimport {\n mutateParamsSchema,\n type MutateResponse,\n} from '../../zero-protocol/src/mutate-server.ts';\nimport type {MutationID} from '../../zero-protocol/src/mutation-id.ts';\nimport {\n CLEANUP_RESULTS_MUTATION_NAME,\n cleanupResultsArgSchema,\n type CleanupResultsArg,\n type CustomMutation,\n type Mutation,\n} from '../../zero-protocol/src/mutation.ts';\nimport {\n pushBodySchema,\n type MutationResponse,\n type PushBody,\n} from '../../zero-protocol/src/push.ts';\nimport type {RetryPredicate} from '../../zql/src/mutate/custom.ts';\nimport type {AnyMutatorRegistry} from '../../zql/src/mutate/mutator-registry.ts';\nimport {isMutator} from '../../zql/src/mutate/mutator.ts';\nimport type {CustomMutatorDefs, CustomMutatorImpl} from './custom.ts';\nimport {createLogContext} from './logging.ts';\nimport {separatorRe} from './push-processor.ts';\n\nexport interface TransactionProviderHooks {\n updateClientMutationID: () => Promise<{lastMutationID: number | bigint}>;\n writeMutationResult: (result: MutationResponse) => Promise<void>;\n deleteMutationResults: (args: CleanupResultsArg) => Promise<void>;\n}\n\nexport interface TransactionProviderInput {\n upstreamSchema: string;\n clientGroupID: string;\n clientID: string;\n mutationID: number;\n /**\n * Receives each predicate the mutator registers with `tx.retryOn()`. A\n * `Database` passes it on to the server transaction it creates.\n */\n addRetryPredicate?: ((shouldRetry: RetryPredicate) => void) | undefined;\n}\n\n/**\n * Defines the abstract interface for a database that PushProcessor can execute\n * transactions against.\n */\nexport interface Database<T> {\n transaction: <R>(\n callback: (\n tx: T,\n transactionHooks: TransactionProviderHooks,\n ) => MaybePromise<R>,\n transactionInput?: TransactionProviderInput,\n ) => Promise<R>;\n}\n\nexport type ExtractTransactionType<D> = D extends Database<infer T> ? T : never;\nexport type Params = v.Infer<typeof mutateParamsSchema>;\n\nexport type TransactFn<D extends Database<ExtractTransactionType<D>>> = (\n cb: TransactFnCallback<D>,\n) => Promise<MutationResponse>;\n\nexport type TransactFnCallback<D extends Database<ExtractTransactionType<D>>> =\n (\n tx: ExtractTransactionType<D>,\n mutatorName: string,\n mutatorArgs: ReadonlyJSONValue | undefined,\n ) => Promise<ReadonlyJSONValue | void>;\n\nexport type Parsed<D extends Database<ExtractTransactionType<D>>> = {\n transact: TransactFn<D>;\n mutations: CustomMutation[];\n};\n\ntype MutationPhase = 'preTransaction' | 'transactionPending' | 'postCommit';\n\nconst applicationErrorWrapper = async <T>(fn: () => Promise<T>): Promise<T> => {\n try {\n return await fn();\n } catch (error) {\n if (\n error instanceof DatabaseTransactionError ||\n error instanceof OutOfOrderMutation ||\n error instanceof MutationAlreadyProcessedError ||\n isApplicationError(error)\n ) {\n throw error;\n }\n\n throw wrapWithApplicationError(error);\n }\n};\n\n/**\n * @deprecated Use {@link handleMutateRequest} instead.\n */\nexport const handleMutationRequest = handleMutateRequest;\n\n/**\n * Parsed query params accepted by {@link handleMutateRequest} when the\n * incoming request URL has already been handled by your framework.\n */\nexport type MutateSearchParams = URLSearchParams | Record<string, string>;\n\n/**\n * Runs once per custom mutation in a `/mutate` request.\n *\n * Call `transact` to execute database work for the mutation. Throwing before\n * `transact` persists an application error; throwing after `transact` resolves\n * only affects server-side logging because the mutation is already committed.\n */\nexport type MutateRequestHandler<\n D extends Database<ExtractTransactionType<D>>,\n> = (\n transact: TransactFn<D>,\n mutation: CustomMutation,\n) => Promise<MutationResponse>;\n\nexport type HandleMutateRequestArgs<\n D extends Database<ExtractTransactionType<D>>,\n> = {\n /** Database used to run transactions and store mutation results. */\n dbProvider: D;\n handler: MutateRequestHandler<D>;\n /**\n * Authenticated user ID. Null or undefined means the user is logged out.\n */\n userID: string | null | undefined;\n /** Optional log level for request parsing and execution. */\n logLevel?: LogLevel | undefined;\n /**\n * Destination for this request's log output. When omitted, logs are written\n * with `console.log`/`info`/`warn`/`error` etc.\n *\n * Provide a custom {@link LogSink} to redirect logs — for example into an\n * application's own structured logging pipeline, so that records emitted while\n * processing a push carry the same fields as the rest of the server's logs.\n */\n logSink?: LogSink | undefined;\n} & (\n | {\n /** Fetch request containing both query params and the JSON body. */\n request: Request;\n }\n | {\n /** Parsed query params from the `/mutate` request URL. */\n query: MutateSearchParams;\n /** Parsed JSON body from the `/mutate` request. */\n body: ReadonlyJSONValue;\n }\n);\n\ntype NormalizedMutateRequestArgs<\n D extends Database<ExtractTransactionType<D>>,\n> = {\n readonly dbProvider: D;\n readonly handler: MutateRequestHandler<D>;\n // Note: semantics of undefined differ from HandleMutateRequestArgs.userID.\n // Here, undefined means the app didn't provide a user ID - we do not know if\n // the user is logged in or not. This is legacy behavior needed to support\n // deprecated signatures of handleMutateRequest which did not receive userID\n // from app.\n readonly userID: string | null | undefined;\n readonly logLevel: LogLevel;\n readonly logSink: LogSink;\n} & (\n | {\n readonly type: 'request';\n readonly request: Request;\n }\n | {\n readonly type: 'body';\n readonly queryParams: Record<string, string>;\n readonly jsonBody: ReadonlyJSONValue;\n }\n);\n\n/**\n * Process a `/mutate` request from a Fetch `Request`.\n */\nexport function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(input: HandleMutateRequestArgs<D>): Promise<MutateResponse>;\n\n/**\n * @deprecated Pass a single object instead:\n * `handleMutateRequest({dbProvider, handler, query, body, userID, logLevel})`.\n */\nexport function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n handler: MutateRequestHandler<D>,\n query: MutateSearchParams,\n body: ReadonlyJSONValue,\n logLevel?: LogLevel,\n logSink?: LogSink,\n): Promise<MutateResponse>;\n\n/**\n * @deprecated Pass a single object instead:\n * `handleMutateRequest({dbProvider, handler, request, userID, logLevel})`.\n */\nexport function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n handler: MutateRequestHandler<D>,\n request: Request,\n logLevel?: LogLevel,\n logSink?: LogSink,\n): Promise<MutateResponse>;\n\nexport async function handleMutateRequest<\n D extends Database<ExtractTransactionType<D>>,\n>(\n inputOrDbProvider: HandleMutateRequestArgs<D> | D,\n maybeHandler?: MutateRequestHandler<D> | undefined,\n requestOrQuery?: Request | MutateSearchParams | undefined,\n bodyOrLogLevel?: ReadonlyJSONValue | LogLevel | undefined,\n logLevelOrLogSink?: LogLevel | LogSink | undefined,\n maybeLogSink?: LogSink | undefined,\n): Promise<MutateResponse> {\n const normalized =\n typeof inputOrDbProvider === 'object' && 'handler' in inputOrDbProvider\n ? normalizeMutateRequestInput(inputOrDbProvider)\n : normalizeLegacyMutateRequestArgs(\n inputOrDbProvider,\n maybeHandler,\n requestOrQuery,\n bodyOrLogLevel,\n logLevelOrLogSink,\n maybeLogSink,\n );\n\n const lc = createLogContext(\n normalized.logLevel,\n normalized.logSink,\n ).withContext('PushProcessor');\n let jsonBody: unknown;\n\n if (normalized.type === 'request') {\n try {\n jsonBody = await normalized.request.json();\n } catch (error) {\n lc.error?.('Failed to parse push body', error);\n const message = `Failed to parse push body: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n mutationIDs: [],\n ...(details ? {details} : {}),\n } as const satisfies PushFailedBody;\n }\n } else {\n jsonBody = normalized.jsonBody;\n }\n\n let mutationIDs: MutationID[] = [];\n\n let pushBody: PushBody;\n try {\n pushBody = v.parse(jsonBody, pushBodySchema, 'passthrough');\n mutationIDs = pushBody.mutations.map(m => ({\n id: m.id,\n clientID: m.clientID,\n }));\n } catch (error) {\n lc.error?.('Failed to parse push body', error);\n const message = `Failed to parse push body: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n mutationIDs,\n ...(details ? {details} : {}),\n } as const satisfies PushFailedBody;\n }\n\n let parsedQueryParams: Params;\n try {\n parsedQueryParams = v.parse(\n normalized.type === 'request'\n ? Object.fromEntries(new URL(normalized.request.url).searchParams)\n : normalized.queryParams,\n mutateParamsSchema,\n 'passthrough',\n );\n } catch (error) {\n lc.error?.('Failed to parse push query parameters', error);\n const message = `Failed to parse push query parameters: ${getErrorMessage(error)}`;\n const details = getErrorDetails(error);\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.Parse,\n message,\n mutationIDs,\n ...(details ? {details} : {}),\n } as const satisfies PushFailedBody;\n }\n\n if (pushBody.pushVersion !== 1) {\n const response = {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason: ErrorReason.UnsupportedPushVersion,\n mutationIDs,\n message: `Unsupported push version: ${pushBody.pushVersion}`,\n } as const satisfies PushFailedBody;\n return response;\n }\n\n const responses: MutationResponse[] = [];\n let processedCount = 0;\n\n try {\n const transactor = new Transactor(\n normalized.dbProvider,\n pushBody,\n parsedQueryParams,\n lc,\n );\n\n // Each mutation goes through three phases:\n // 1. Pre-transaction: user logic that runs before `transact` is called. If\n // this throws we still advance LMID and persist the failure result.\n // 2. Transaction: the callback passed to `transact`, which can be retried\n // if it fails with an ApplicationError.\n // 3. Post-commit: any logic that runs after `transact` resolves. Failures\n // here are logged but the mutation remains committed.\n for (const m of pushBody.mutations) {\n // Handle internal mutations (like cleanup) directly without user dispatch\n if (m.type === 'custom' && m.name === CLEANUP_RESULTS_MUTATION_NAME) {\n lc.debug?.(\n `Processing internal mutation '${m.name}' (clientID=${m.clientID})`,\n );\n try {\n await processCleanupResultsMutation(\n normalized.dbProvider,\n m,\n parsedQueryParams,\n lc,\n );\n // No response added - this is fire-and-forget\n processedCount++;\n } catch (error) {\n lc.warn?.(\n `Failed to process cleanup mutation for client ${m.clientID}`,\n error,\n );\n // Don't fail the whole push for cleanup errors\n processedCount++;\n }\n continue;\n }\n\n assert(m.type === 'custom', 'Expected custom mutation');\n lc.debug?.(\n `Processing mutation '${m.name}' (id=${m.id}, clientID=${m.clientID})`,\n );\n\n let mutationPhase: MutationPhase = 'preTransaction';\n\n const transactProxy: TransactFn<D> = async innerCb => {\n mutationPhase = 'transactionPending';\n const result = await transactor.transact(m, innerCb);\n mutationPhase = 'postCommit';\n return result;\n };\n\n try {\n const res = await applicationErrorWrapper(() =>\n normalized.handler(transactProxy, m),\n );\n responses.push(res);\n lc.debug?.(`Mutation '${m.name}' (id=${m.id}) completed successfully`);\n\n processedCount++;\n } catch (error) {\n if (!isApplicationError(error)) {\n throw error;\n }\n\n if (mutationPhase === 'preTransaction') {\n // Pre-transaction\n await transactor.persistPreTransactionFailure(m, error);\n } else if (mutationPhase === 'postCommit') {\n // Post-commit\n lc.error?.(\n `Post-commit mutation handler failed for mutation ${m.id} for client ${m.clientID}`,\n error,\n );\n }\n\n lc.warn?.(\n `Application error processing mutation ${m.id} for client ${m.clientID}`,\n error,\n );\n responses.push(makeAppErrorResponse(m, error));\n\n processedCount++;\n }\n }\n\n return {\n kind: 'MutateResponse',\n mutations: responses,\n ...(typeof normalized.userID !== 'undefined'\n ? {userID: normalized.userID}\n : {}),\n } as const satisfies MutateResponse;\n } catch (error) {\n lc.error?.('Failed to process push request', error);\n // only include mutationIDs for mutations that were not processed\n const unprocessedMutationIDs = mutationIDs.slice(processedCount);\n\n const message = getErrorMessage(error);\n const details = getErrorDetails(error);\n\n return {\n kind: ErrorKind.PushFailed,\n origin: ErrorOrigin.Server,\n reason:\n error instanceof OutOfOrderMutation\n ? ErrorReason.OutOfOrderMutation\n : error instanceof DatabaseTransactionError\n ? ErrorReason.Database\n : ErrorReason.Internal,\n message,\n mutationIDs: unprocessedMutationIDs,\n ...(details ? {details} : {}),\n };\n }\n}\n\nfunction normalizeMutateRequestInput<\n D extends Database<ExtractTransactionType<D>>,\n>(input: HandleMutateRequestArgs<D>): NormalizedMutateRequestArgs<D> {\n if ('request' in input) {\n return {\n type: 'request',\n dbProvider: input.dbProvider,\n handler: input.handler,\n request: input.request,\n userID: input.userID ?? null,\n logLevel: input.logLevel ?? 'info',\n logSink: input.logSink ?? consoleLogSink,\n };\n }\n\n return {\n type: 'body',\n dbProvider: input.dbProvider,\n handler: input.handler,\n jsonBody: input.body,\n userID: input.userID ?? null,\n queryParams:\n input.query instanceof URLSearchParams\n ? Object.fromEntries(input.query)\n : input.query,\n logLevel: input.logLevel ?? 'info',\n logSink: input.logSink ?? consoleLogSink,\n };\n}\n\nfunction normalizeLegacyMutateRequestArgs<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n handler: MutateRequestHandler<D> | undefined,\n requestOrQuery: Request | MutateSearchParams | undefined,\n bodyOrLogLevel: ReadonlyJSONValue | LogLevel | undefined,\n logLevelOrLogSink: LogLevel | LogSink | undefined,\n maybeLogSink: LogSink | undefined,\n): NormalizedMutateRequestArgs<D> {\n assert(typeof handler === 'function', 'Handler function is required');\n assert(\n typeof requestOrQuery !== 'undefined',\n 'Request or query parameters are required',\n );\n\n if (requestOrQuery instanceof Request) {\n return {\n type: 'request',\n dbProvider,\n handler,\n request: requestOrQuery,\n userID: undefined,\n logLevel: (bodyOrLogLevel as LogLevel | undefined) ?? 'info',\n // The `request` overload has no `body` slot, so the sink arrives one\n // position earlier than it does in the `query`/`body` overload.\n logSink: (logLevelOrLogSink as LogSink | undefined) ?? consoleLogSink,\n };\n }\n\n assert(\n typeof bodyOrLogLevel !== 'undefined',\n 'JSON body cannot be undefined',\n );\n\n return {\n type: 'body',\n dbProvider,\n handler,\n jsonBody: bodyOrLogLevel,\n userID: undefined,\n queryParams:\n requestOrQuery instanceof URLSearchParams\n ? Object.fromEntries(requestOrQuery)\n : requestOrQuery,\n logLevel: (logLevelOrLogSink as LogLevel | undefined) ?? 'info',\n logSink: maybeLogSink ?? consoleLogSink,\n };\n}\n\n/**\n * The most times a mutator runs for one mutation within one push when its\n * `tx.retryOn()` predicate keeps answering yes: the first run and four\n * re-runs.\n */\nexport const MAX_MUTATOR_RUNS = 5;\n\nclass Transactor<D extends Database<ExtractTransactionType<D>>> {\n readonly #dbProvider: D;\n readonly #req: PushBody;\n readonly #params: Params;\n readonly #lc: LogContext;\n\n constructor(dbProvider: D, req: PushBody, params: Params, lc: LogContext) {\n this.#dbProvider = dbProvider;\n this.#req = req;\n this.#params = params;\n this.#lc = lc;\n }\n\n /**\n * Asks all of the run's `tx.retryOn()` predicates at once whether to run\n * the mutator again. The first to answer yes decides it and the other\n * answers are ignored; it is no once every predicate has answered no. A\n * predicate that throws or rejects answers no: escaping here would skip\n * recording the mutation's result, and the client would send it again.\n */\n #shouldRetry(\n predicates: readonly RetryPredicate[],\n error: unknown,\n attempt: number,\n ): Promise<boolean> {\n if (predicates.length === 0) {\n return Promise.resolve(false);\n }\n const ask = async (shouldRetry: RetryPredicate): Promise<boolean> => {\n try {\n return (await shouldRetry(error, attempt)) === true;\n } catch (retryError) {\n this.#lc.warn?.(\n 'retryOn predicate threw; treating it as no',\n retryError,\n );\n return false;\n }\n };\n return new Promise(resolve => {\n let pending = predicates.length;\n for (const shouldRetry of predicates) {\n void ask(shouldRetry).then(yes => {\n if (yes) {\n resolve(true);\n } else if (--pending === 0) {\n resolve(false);\n }\n });\n }\n });\n }\n\n transact = async (\n mutation: CustomMutation,\n cb: TransactFnCallback<D>,\n ): Promise<MutationResponse> => {\n let appError: ApplicationError | undefined = undefined;\n // Which run of the mutator this is: 1, then 2 for the first re-run, and so\n // on. When a run fails, it is also the number of the re-run being decided.\n let attempt = 1;\n for (;;) {\n // What this run registers with `tx.retryOn()`. Each run starts empty.\n const predicates: RetryPredicate[] = [];\n try {\n const ret = await this.#transactImpl(\n mutation,\n cb,\n appError,\n shouldRetry => {\n predicates.push(shouldRetry);\n },\n );\n if (appError !== undefined) {\n this.#lc.warn?.(\n // log-leak-ignore -- mutation and client ids, not row data\n `Mutation ${mutation.id} for client ${mutation.clientID} was retried after an error`,\n appError,\n );\n return makeAppErrorResponse(mutation, appError);\n }\n\n return ret;\n } catch (error) {\n if (error instanceof OutOfOrderMutation) {\n this.#lc.error?.(error);\n throw error;\n }\n\n if (error instanceof MutationAlreadyProcessedError) {\n this.#lc.warn?.(error);\n return {\n id: {\n clientID: mutation.clientID,\n id: mutation.id,\n },\n result: {\n error: 'alreadyProcessed',\n details: error.message,\n },\n };\n }\n\n if (appError !== undefined) {\n // Retry also failed → internal error, cannot skip mutation\n this.#lc.error?.(\n // log-leak-ignore -- mutation and client ids, not row data\n `Retry also failed for mutation ${mutation.id} for client ${mutation.clientID}`,\n error,\n );\n throw error;\n }\n\n // What the mutator or the database threw, without the wrapper. This\n // includes errors raised at COMMIT, which the mutator cannot catch.\n const originalError =\n error instanceof DatabaseTransactionError\n ? (error.cause ?? error)\n : error;\n\n // One of the run's `tx.retryOn()` predicates says to run it again → do\n // so, in a fresh transaction.\n //\n // `continue` WITHOUT setting `appError` is the whole mechanism: it is\n // `appError` being set that makes the next `#transactImpl` skip\n // `cb(...)`. `#transactImpl` opens a new transaction each pass, so the\n // re-run gets a new snapshot. `#checkAndIncrementLastMutationID` re-runs\n // safely because the failed run rolled its increment back.\n if (\n attempt < MAX_MUTATOR_RUNS &&\n (await this.#shouldRetry(predicates, originalError, attempt))\n ) {\n this.#lc.warn?.(\n // log-leak-ignore -- mutation and client ids, not row data\n `Mutation ${mutation.id} for client ${mutation.clientID} failed, re-running mutator (retry ${attempt})`,\n originalError,\n );\n attempt++;\n continue;\n }\n\n // Not re-run → store error and retry without mutator\n appError = wrapWithApplicationError(originalError);\n this.#lc.warn?.(\n // log-leak-ignore -- mutation and client ids, not row data\n `Error processing mutation ${mutation.id} for client ${mutation.clientID}, retrying without mutator`,\n appError,\n );\n continue;\n }\n }\n };\n\n async persistPreTransactionFailure(\n mutation: CustomMutation,\n appError: ApplicationError<ReadonlyJSONValue | undefined>,\n ): Promise<MutationResponse> {\n // User-land code threw before calling `transact`. We still need to bump the\n // LMID for this mutation and persist the error so that the client knows it failed.\n const ret = await this.#transactImpl(\n mutation,\n // noop callback since there's no transaction to execute\n () => promiseVoid,\n appError,\n undefined,\n );\n return ret;\n }\n\n async #transactImpl(\n mutation: CustomMutation,\n cb: TransactFnCallback<D>,\n appError: ApplicationError | undefined,\n addRetryPredicate: ((shouldRetry: RetryPredicate) => void) | undefined,\n ): Promise<MutationResponse> {\n let transactionPhase: DatabaseTransactionPhase = 'open';\n\n try {\n const ret = await this.#dbProvider.transaction(\n async (dbTx, transactionHooks) => {\n // update the transaction phase to 'execute' after the transaction is opened\n transactionPhase = 'execute';\n\n await this.#checkAndIncrementLastMutationID(\n transactionHooks,\n mutation.clientID,\n mutation.id,\n );\n\n if (appError === undefined) {\n this.#lc.debug?.(\n // log-leak-ignore -- mutator name and mutation id, not row data\n `Executing mutator '${mutation.name}' (id=${mutation.id})`,\n );\n const data = (await cb(dbTx, mutation.name, mutation.args[0])) as\n | ReadonlyJSONValue\n | undefined;\n const id = {clientID: mutation.clientID, id: mutation.id};\n if (data === undefined) {\n return {id, result: {}};\n }\n // Persisted so the data still reaches the client if the push\n // response is lost. A mutator that returns nothing writes no row.\n const successResult: MutationResponse = {id, result: {data}};\n await transactionHooks.writeMutationResult(successResult);\n return successResult;\n } else {\n const mutationResult = makeAppErrorResponse(mutation, appError);\n await transactionHooks.writeMutationResult(mutationResult);\n return mutationResult;\n }\n },\n this.#getTransactionInput(mutation, addRetryPredicate),\n );\n\n return ret;\n } catch (error) {\n if (\n isApplicationError(error) ||\n error instanceof OutOfOrderMutation ||\n error instanceof MutationAlreadyProcessedError\n ) {\n throw error;\n }\n\n throw new DatabaseTransactionError(transactionPhase, {cause: error});\n }\n }\n\n #getTransactionInput(\n mutation: CustomMutation,\n addRetryPredicate: ((shouldRetry: RetryPredicate) => void) | undefined,\n ): TransactionProviderInput {\n return {\n upstreamSchema: this.#params.schema,\n clientGroupID: this.#req.clientGroupID,\n clientID: mutation.clientID,\n mutationID: mutation.id,\n addRetryPredicate,\n };\n }\n\n async #checkAndIncrementLastMutationID(\n transactionHooks: TransactionProviderHooks,\n clientID: string,\n receivedMutationID: number,\n ) {\n const {lastMutationID} = await transactionHooks.updateClientMutationID();\n\n if (receivedMutationID < lastMutationID) {\n throw new MutationAlreadyProcessedError(\n clientID,\n receivedMutationID,\n lastMutationID,\n );\n } else if (receivedMutationID > lastMutationID) {\n throw new OutOfOrderMutation(\n clientID,\n receivedMutationID,\n lastMutationID,\n );\n }\n }\n}\n\nexport class OutOfOrderMutation extends Error {\n constructor(\n clientID: string,\n receivedMutationID: number,\n lastMutationID: number | bigint,\n ) {\n super(\n `Client ${clientID} sent mutation ID ${receivedMutationID} but expected ${lastMutationID}`,\n );\n }\n}\n\nfunction makeAppErrorResponse(\n m: Mutation,\n error: ApplicationError<ReadonlyJSONValue | undefined>,\n): MutationResponse {\n return {\n id: {\n clientID: m.clientID,\n id: m.id,\n },\n result: {\n error: 'app',\n message: error.message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n}\n\n/** @deprecated Use getMutator instead */\nexport function getMutation(\n // oxlint-disable-next-line no-explicit-any\n mutators: AnyMutatorRegistry | CustomMutatorDefs<any>,\n name: string,\n // oxlint-disable-next-line no-explicit-any\n): CustomMutatorImpl<any> {\n const path = name.split(separatorRe);\n const mutator = getObjectAtPath(mutators, path);\n assert(typeof mutator === 'function', `could not find mutator ${name}`);\n\n if (isMutator(mutator)) {\n // mutator needs to be called with {tx, args, ctx}\n // CustomMutatorImpl is called with (tx, args, ctx)\n return (tx, args, ctx) => mutator.fn({args, ctx, tx});\n }\n\n // oxlint-disable-next-line no-explicit-any\n return mutator as CustomMutatorImpl<any>;\n}\n\nfunction getObjectAtPath(\n obj: Record<string, unknown>,\n path: string[],\n): unknown {\n let current: unknown = obj;\n for (const part of path) {\n if (typeof current !== 'object' || current === null || !(part in current)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/**\n * Processes internal cleanup mutation that deletes acknowledged mutation results\n * from the upstream database. This runs without LMID tracking since it's an\n * internal operation.\n */\nasync function processCleanupResultsMutation<\n D extends Database<ExtractTransactionType<D>>,\n>(\n dbProvider: D,\n mutation: CustomMutation,\n queryParams: Params,\n lc: LogContext,\n): Promise<void> {\n const parseResult = v.test(mutation.args[0], cleanupResultsArgSchema);\n if (!parseResult.ok) {\n // log-leak-ignore -- valita reports the failing type, not the value\n lc.warn?.('Cleanup mutation has invalid args', parseResult.error);\n return;\n }\n const args: CleanupResultsArg = parseResult.value;\n\n // Determine clientID for transaction input based on cleanup type\n // Note: legacy format without type field is treated as single\n const clientID =\n 'type' in args && args.type === 'bulk' ? args.clientIDs[0] : args.clientID;\n\n // Run in a transaction, using the hook for DB-specific operation.\n // Note: only upstreamSchema is used by deleteMutationResults; the other\n // fields are required by the interface but ignored for this operation.\n await dbProvider.transaction(\n async (_, hooks) => {\n await hooks.deleteMutationResults(args);\n },\n {\n upstreamSchema: queryParams.schema,\n clientGroupID: args.clientGroupID,\n clientID,\n mutationID: 0,\n },\n );\n}\n\ntype DatabaseTransactionPhase = 'open' | 'execute';\nclass DatabaseTransactionError extends Error {\n constructor(phase: DatabaseTransactionPhase, options?: ErrorOptions) {\n super(\n phase === 'open'\n ? `Failed to open database transaction: ${getErrorMessage(options?.cause)}`\n : `Database transaction failed after opening: ${getErrorMessage(options?.cause)}`,\n options,\n );\n this.name = 'DatabaseTransactionError';\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmGA,IAAM,0BAA0B,OAAU,OAAqC;CAC7E,IAAI;EACF,OAAO,MAAM,GAAG;CAClB,SAAS,OAAO;EACd,IACE,iBAAiB,4BACjB,iBAAiB,sBACjB,iBAAiB,iCACjB,mBAAmB,KAAK,GAExB,MAAM;EAGR,MAAM,yBAAyB,KAAK;CACtC;AACF;;;;AAKA,IAAa,wBAAwB;AAqHrC,eAAsB,oBAGpB,mBACA,cACA,gBACA,gBACA,mBACA,cACyB;CACzB,MAAM,aACJ,OAAO,sBAAsB,YAAY,aAAa,oBAClD,4BAA4B,iBAAiB,IAC7C,iCACE,mBACA,cACA,gBACA,gBACA,mBACA,YACF;CAEN,MAAM,KAAK,iBACT,WAAW,UACX,WAAW,OACb,EAAE,YAAY,eAAe;CAC7B,IAAI;CAEJ,IAAI,WAAW,SAAS,WACtB,IAAI;EACF,WAAW,MAAM,WAAW,QAAQ,KAAK;CAC3C,SAAS,OAAO;EACd,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;EACvB,IAAI,OAAO,YAAY,YAAY,YAAY,QAAQ,EAAE,QAAQ,UAC/D;EAEF,UAAW,QAAoC;CACjD;CACA,OAAO;AACT;;;;;;AAOA,eAAe,8BAGb,YACA,UACA,aACA,IACe;CACf,MAAM,cAAc,KAAO,SAAS,KAAK,IAAI,uBAAuB;CACpE,IAAI,CAAC,YAAY,IAAI;EAEnB,GAAG,OAAO,qCAAqC,YAAY,KAAK;EAChE;CACF;CACA,MAAM,OAA0B,YAAY;CAI5C,MAAM,WACJ,UAAU,QAAQ,KAAK,SAAS,SAAS,KAAK,UAAU,KAAK,KAAK;CAKpE,MAAM,WAAW,YACf,OAAO,GAAG,UAAU;EAClB,MAAM,MAAM,sBAAsB,IAAI;CACxC,GACA;EACE,gBAAgB,YAAY;EAC5B,eAAe,KAAK;EACpB;EACA,YAAY;CACd,CACF;AACF;AAGA,IAAM,2BAAN,cAAuC,MAAM;CAC3C,YAAY,OAAiC,SAAwB;EACnE,MACE,UAAU,SACN,wCAAwC,gBAAgB,SAAS,KAAK,MACtE,8CAA8C,gBAAgB,SAAS,KAAK,KAChF,OACF;EACA,KAAK,OAAO;CACd;AACF"}
|
|
@@ -11,7 +11,7 @@ export declare class PushProcessor<_S extends Schema, D extends Database<Extract
|
|
|
11
11
|
/**
|
|
12
12
|
* @param logSink Destination for this processor's log output. When omitted,
|
|
13
13
|
* logs are written with `console.log`/`info`/`warn`/`error` etc. Provide a
|
|
14
|
-
* custom {@
|
|
14
|
+
* custom {@link LogSink} to redirect them into the application's own
|
|
15
15
|
* logging pipeline.
|
|
16
16
|
*/
|
|
17
17
|
constructor(dbProvider: D, context?: C, logLevel?: LogLevel, logSink?: LogSink);
|
|
@@ -15,7 +15,7 @@ var PushProcessor = class {
|
|
|
15
15
|
/**
|
|
16
16
|
* @param logSink Destination for this processor's log output. When omitted,
|
|
17
17
|
* logs are written with `console.log`/`info`/`warn`/`error` etc. Provide a
|
|
18
|
-
* custom {@
|
|
18
|
+
* custom {@link LogSink} to redirect them into the application's own
|
|
19
19
|
* logging pipeline.
|
|
20
20
|
*/
|
|
21
21
|
constructor(dbProvider, context, logLevel = "info", logSink = consoleLogSink) {
|