@rocicorp/zero 1.11.0-canary.21 → 1.11.0-canary.22
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/zero/package.js +1 -1
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
- package/out/zero-cache/src/config/normalize.js +1 -2
- package/out/zero-cache/src/config/normalize.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +0 -22
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +38 -42
- package/out/zero-cache/src/config/zero-config.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 +9 -6
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.js +1 -1
- package/out/zero-cache/src/services/change-source/common/change-stream-multiplexer.js.map +1 -1
- package/out/zero-cache/src/services/change-source/common/replica-restore.d.ts +31 -1
- package/out/zero-cache/src/services/change-source/common/replica-restore.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/common/replica-restore.js.map +1 -1
- package/out/zero-cache/src/services/change-source/custom/change-source.d.ts +1 -1
- package/out/zero-cache/src/services/change-source/custom/change-source.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/custom/change-source.js +5 -2
- package/out/zero-cache/src/services/change-source/custom/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source-init.d.ts +4 -5
- package/out/zero-cache/src/services/change-source/pg/change-source-init.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source-init.js +46 -17
- package/out/zero-cache/src/services/change-source/pg/change-source-init.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts +31 -0
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +100 -2
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backfill-state-tracker.d.ts +6 -0
- package/out/zero-cache/src/services/change-streamer/backfill-state-tracker.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backfill-state-tracker.js +8 -0
- package/out/zero-cache/src/services/change-streamer/backfill-state-tracker.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js +3 -16
- package/out/zero-cache/src/services/change-streamer/backup-cleanup-monitor-factory.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.d.ts +17 -0
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +44 -1
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +7 -0
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +27 -8
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts +57 -0
- package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/schema/tables.js +103 -23
- package/out/zero-cache/src/services/change-streamer/schema/tables.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/storer.d.ts +86 -1
- package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/storer.js +272 -77
- package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/upstream-acker.d.ts +7 -5
- package/out/zero-cache/src/services/change-streamer/upstream-acker.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-streamer/upstream-acker.js +9 -5
- package/out/zero-cache/src/services/change-streamer/upstream-acker.js.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.d.ts +0 -13
- package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.js +2 -17
- package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
- package/out/zero-cache/src/services/litestream/config-v5.yml +0 -7
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +0 -2
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +45 -107
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero.d.ts.map +1 -1
- package/out/zero-client/src/client/zero.js +2 -1
- package/out/zero-client/src/client/zero.js.map +1 -1
- package/out/zero-protocol/src/down.d.ts +27 -27
- package/out/zero-react/src/use-query.js +12 -3
- package/out/zero-react/src/use-query.js.map +1 -1
- package/out/zql/src/ivm/array-view.d.ts.map +1 -1
- package/out/zql/src/ivm/array-view.js +21 -12
- package/out/zql/src/ivm/array-view.js.map +1 -1
- package/package.json +1 -1
- package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.d.ts +0 -34
- package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.d.ts.map +0 -1
- package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js +0 -184
- package/out/zero-cache/src/services/change-streamer/vfs-watermark-poller.js.map +0 -1
|
@@ -191,33 +191,6 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
|
|
|
191
191
|
type: "attempt-start";
|
|
192
192
|
attemptNumber: number;
|
|
193
193
|
totalAttempts: number;
|
|
194
|
-
} | {
|
|
195
|
-
type: "connection-selected";
|
|
196
|
-
attemptNumber: number;
|
|
197
|
-
connection: string;
|
|
198
|
-
cost: number;
|
|
199
|
-
isRoot: boolean;
|
|
200
|
-
} | {
|
|
201
|
-
type: "plan-failed";
|
|
202
|
-
attemptNumber: number;
|
|
203
|
-
reason: string;
|
|
204
|
-
} | {
|
|
205
|
-
type: "best-plan-selected";
|
|
206
|
-
bestAttemptNumber: number;
|
|
207
|
-
totalCost: number;
|
|
208
|
-
flipPattern: number;
|
|
209
|
-
joinStates: {
|
|
210
|
-
join: string;
|
|
211
|
-
type: "flipped" | "semi" | "unflippable";
|
|
212
|
-
}[];
|
|
213
|
-
} | {
|
|
214
|
-
type: "node-constraint";
|
|
215
|
-
attemptNumber?: number | undefined;
|
|
216
|
-
nodeType: "connection" | "fan-in" | "fan-out" | "filter" | "join" | "terminus";
|
|
217
|
-
node: string;
|
|
218
|
-
branchPattern: number[];
|
|
219
|
-
constraint?: Record<string, unknown> | null | undefined;
|
|
220
|
-
from: string;
|
|
221
194
|
} | {
|
|
222
195
|
type: "connection-costs";
|
|
223
196
|
attemptNumber: number;
|
|
@@ -243,6 +216,12 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
|
|
|
243
216
|
limit?: number | undefined;
|
|
244
217
|
}>;
|
|
245
218
|
}[];
|
|
219
|
+
} | {
|
|
220
|
+
type: "connection-selected";
|
|
221
|
+
attemptNumber: number;
|
|
222
|
+
connection: string;
|
|
223
|
+
cost: number;
|
|
224
|
+
isRoot: boolean;
|
|
246
225
|
} | {
|
|
247
226
|
type: "constraints-propagated";
|
|
248
227
|
attemptNumber: number;
|
|
@@ -267,6 +246,19 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
|
|
|
267
246
|
join: string;
|
|
268
247
|
type: "flipped" | "semi" | "unflippable";
|
|
269
248
|
}[];
|
|
249
|
+
} | {
|
|
250
|
+
type: "plan-failed";
|
|
251
|
+
attemptNumber: number;
|
|
252
|
+
reason: string;
|
|
253
|
+
} | {
|
|
254
|
+
type: "best-plan-selected";
|
|
255
|
+
bestAttemptNumber: number;
|
|
256
|
+
totalCost: number;
|
|
257
|
+
flipPattern: number;
|
|
258
|
+
joinStates: {
|
|
259
|
+
join: string;
|
|
260
|
+
type: "flipped" | "semi" | "unflippable";
|
|
261
|
+
}[];
|
|
270
262
|
} | {
|
|
271
263
|
type: "node-cost";
|
|
272
264
|
attemptNumber?: number | undefined;
|
|
@@ -285,6 +277,14 @@ export declare const downstreamSchema: v.UnionType<[v.TupleType<[v.Type<"connect
|
|
|
285
277
|
filters?: import("./ast.ts").Condition | undefined;
|
|
286
278
|
ordering?: readonly (readonly [string, "asc" | "desc"])[] | undefined;
|
|
287
279
|
joinType?: "flipped" | "semi" | "unflippable" | undefined;
|
|
280
|
+
} | {
|
|
281
|
+
type: "node-constraint";
|
|
282
|
+
attemptNumber?: number | undefined;
|
|
283
|
+
nodeType: "connection" | "fan-in" | "fan-out" | "filter" | "join" | "terminus";
|
|
284
|
+
node: string;
|
|
285
|
+
branchPattern: number[];
|
|
286
|
+
constraint?: Record<string, unknown> | null | undefined;
|
|
287
|
+
from: string;
|
|
288
288
|
})[]>;
|
|
289
289
|
}, undefined>;
|
|
290
290
|
}, undefined>, v.ObjectType<Omit<{
|
|
@@ -283,6 +283,9 @@ var ViewWrapper = class {
|
|
|
283
283
|
#zero;
|
|
284
284
|
#singular;
|
|
285
285
|
#destroyTimer;
|
|
286
|
+
#lastData;
|
|
287
|
+
#lastResultType;
|
|
288
|
+
#lastError;
|
|
286
289
|
constructor(query, zero, ttl, onDematerialized) {
|
|
287
290
|
this.#query = query;
|
|
288
291
|
this.#zero = zero;
|
|
@@ -294,9 +297,15 @@ var ViewWrapper = class {
|
|
|
294
297
|
this.#materializeIfNeeded();
|
|
295
298
|
}
|
|
296
299
|
#onData = (snap, resultType, error) => {
|
|
297
|
-
const data = snap;
|
|
298
300
|
const wasCached = this.#snapshot[1].type === "cached";
|
|
299
|
-
this.#
|
|
301
|
+
const changed = this.#lastResultType === void 0 || this.#lastData !== snap || this.#lastResultType !== resultType || this.#lastError !== error;
|
|
302
|
+
this.#lastData = snap;
|
|
303
|
+
this.#lastResultType = resultType;
|
|
304
|
+
this.#lastError = error;
|
|
305
|
+
if (changed) {
|
|
306
|
+
const data = snap;
|
|
307
|
+
this.#snapshot = getSnapshot(this.#singular, data, resultType, this.#retry, error);
|
|
308
|
+
}
|
|
300
309
|
if (resultType === "complete" || resultType === "error") {
|
|
301
310
|
this.#complete = true;
|
|
302
311
|
this.#completeResolver.resolve();
|
|
@@ -311,7 +320,7 @@ var ViewWrapper = class {
|
|
|
311
320
|
this.#nonEmpty = false;
|
|
312
321
|
this.#nonEmptyResolver = resolver();
|
|
313
322
|
}
|
|
314
|
-
for (const internals of this.#reactInternals) internals();
|
|
323
|
+
if (changed) for (const internals of this.#reactInternals) internals();
|
|
315
324
|
};
|
|
316
325
|
/**
|
|
317
326
|
* Called by the user to force a retry of the query
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-query.js","names":["#views","#onDematerialized","#query","#reactInternals","#zero","#singular","#ttl","#snapshot","#materializeIfNeeded","#retry","#complete","#completeResolver","#nonEmpty","#nonEmptyResolver","#view","#onData","#destroyTimer"],"sources":["../../../../zero-react/src/use-query.tsx"],"sourcesContent":["import {resolver} from '@rocicorp/resolver';\nimport React, {useRef, useSyncExternalStore} from 'react';\nimport {deepEqual} from '../../shared/src/json.ts';\nimport {TESTING} from '../../shared/src/testing.ts';\nimport {\n type Immutable,\n addContextToQuery,\n asQueryInternals,\n DEFAULT_TTL_MS,\n} from './bindings.ts';\nimport {useZero} from './zero-provider.tsx';\nimport type {\n AnyMutatorRegistry,\n BaseDefaultContext,\n BaseDefaultSchema,\n CustomMutatorDefs,\n DefaultContext,\n DefaultSchema,\n ErroredQuery,\n Falsy,\n HumanReadable,\n PullRow,\n Query,\n QueryErrorDetails,\n QueryOrQueryRequest,\n QueryResultDetails,\n ReadonlyJSONValue,\n ResultType,\n TTL,\n TypedView,\n Zero,\n} from './zero.ts';\n\ntype StableQueryCache = {\n zero: unknown;\n context: unknown;\n /** The last input, so an unchanged one is an identity compare and nothing else. */\n rawQuery: object;\n /** The `CustomQuery` a query request names; undefined for a plain query. */\n customQuery: unknown;\n args: ReadonlyJSONValue | undefined;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n q: Query<any, any, any>;\n};\n\n/**\n * Resolves a query request against the Zero context, reusing the previous\n * result while the request means the same thing.\n *\n * Interning already makes an unchanged *plain* query come back as the same\n * object, so this is aimed at the query-request form -- `queries.issue({id})`\n * -- where every render allocates a fresh request and `addContextToQuery`\n * re-runs the definition. That costs argument validation (a zod parse of\n * byte-identical args) plus a walk of the builder chain, neither of which\n * interning removes: it makes rebuilding the chain cheap and gives the same\n * object back, but only after the work has been done again.\n *\n * A request resolves to the previous query when it names the same\n * `CustomQuery`, the same context, and deep-equal args. Those are exactly the\n * inputs the definition is allowed to depend on: a named query is re-derived\n * on the server from its name and args, so it has to be a pure function of\n * them, or client and server would build different queries.\n *\n * The ref is written during render. That is safe here because it is a pure\n * cache: an entry is derived only from the inputs, so a StrictMode double\n * render or a discarded concurrent render leaves it valid either way.\n */\nfunction useStableQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema,\n TReturn,\n TContext extends BaseDefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n zero: Zero<TSchema, undefined, TContext>,\n): Query<TTable, TSchema, TReturn> | undefined {\n const cacheRef = useRef<StableQueryCache | undefined>(undefined);\n\n // Deliberately kept rather than cleared: a query toggled off and back on\n // reuses what it had.\n if (!query) {\n return undefined;\n }\n\n const cache = cacheRef.current;\n if (cache && cache.zero === zero) {\n if (cache.rawQuery === query) {\n return cache.q as Query<TTable, TSchema, TReturn>;\n }\n if (\n 'query' in query &&\n cache.customQuery === query.query &&\n cache.context === zero.context &&\n deepEqual(cache.args, query.args)\n ) {\n // Same meaning, new wrapper object: remember it so the next render is\n // the identity compare above.\n cache.rawQuery = query;\n return cache.q as Query<TTable, TSchema, TReturn>;\n }\n }\n\n const q = addContextToQuery(query, zero.context);\n const isRequest = 'query' in query;\n cacheRef.current = {\n zero: zero,\n context: zero.context,\n rawQuery: query,\n customQuery: isRequest ? query.query : undefined,\n args: isRequest ? query.args : undefined,\n q,\n };\n return q;\n}\n\nexport type QueryResult<TReturn> = readonly [\n HumanReadable<TReturn>,\n QueryResultDetails & {},\n];\n\n/**\n * Result type for \"maybe queries\" - queries that may be falsy.\n * The data value can be undefined when the query is falsy/disabled.\n */\nexport type MaybeQueryResult<TReturn> = readonly [\n HumanReadable<TReturn> | undefined,\n QueryResultDetails & {},\n];\n\nexport type UseQueryOptions = {\n enabled?: boolean | undefined;\n /**\n * Time to live (TTL) in seconds. Controls how long query results are cached\n * after the query is removed. During this time, Zero continues to sync the query.\n * Default is 'never'.\n */\n ttl?: TTL | undefined;\n};\n\nexport type UseSuspenseQueryOptions = UseQueryOptions & {\n /**\n * Whether to suspend until:\n * - 'partial': the query has partial results (partial array or defined\n * value for singular results) which may be of result type 'unknown',\n * or the query result type is 'complete' or 'cached' (in which case\n * results may be empty: a server-confirmed empty answer, from this\n * connection or a previous one, is something to render). This is useful\n * for suspending until there are partial optimistic local results, or\n * the query has completed loading from the server.\n * - 'complete': the query result type is 'complete'.\n *\n * Default is 'partial'.\n */\n suspendUntil?: 'complete' | 'partial';\n};\n\nconst reactUse = (React as {use?: (p: Promise<unknown>) => void}).use;\nconst suspend: (p: Promise<unknown>) => void = reactUse\n ? reactUse\n : p => {\n throw p;\n };\n\n// Overload 1: Query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({enabled = true, ttl = DEFAULT_TTL_MS} = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = useStableQuery(query, zero);\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n return useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n}\n\n// Overload 1: Query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n let suspendUntil: 'complete' | 'partial' = 'partial';\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({\n enabled = true,\n ttl = DEFAULT_TTL_MS,\n suspendUntil = 'complete',\n } = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = useStableQuery(query, zero);\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n const snapshot = useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n\n if (view && enabled) {\n if (suspendUntil === 'complete' && !view.complete) {\n suspend(view.waitForComplete());\n }\n\n if (suspendUntil === 'partial' && !view.nonEmpty) {\n suspend(view.waitForNonEmpty());\n }\n }\n\n return snapshot;\n}\n\nconst emptyArray: unknown[] = [];\nconst disabledSubscriber = () => () => {};\n\nconst resultTypeUnknown = {type: 'unknown'} as const;\nconst resultTypeCached = {type: 'cached'} as const;\nconst resultTypeComplete = {type: 'complete'} as const;\nconst resultTypeError = {type: 'error'} as const;\n\nconst disabledQuerySnapshot = [undefined, resultTypeUnknown] as const;\nconst getDisabledSnapshot = () => disabledQuerySnapshot;\n\nconst emptySnapshotSingularUnknown = [undefined, resultTypeUnknown] as const;\nconst emptySnapshotSingularCached = [undefined, resultTypeCached] as const;\nconst emptySnapshotSingularComplete = [undefined, resultTypeComplete] as const;\nconst emptySnapshotSingularErrorUnknown = [undefined, resultTypeError] as const;\nconst emptySnapshotPluralUnknown = [emptyArray, resultTypeUnknown] as const;\nconst emptySnapshotPluralCached = [emptyArray, resultTypeCached] as const;\nconst emptySnapshotPluralComplete = [emptyArray, resultTypeComplete] as const;\nconst emptySnapshotErrorUnknown = [emptyArray, resultTypeError] as const;\n\nfunction getDefaultSnapshot<TReturn>(singular: boolean): QueryResult<TReturn> {\n return (\n singular ? emptySnapshotSingularUnknown : emptySnapshotPluralUnknown\n ) as QueryResult<TReturn>;\n}\n\n/**\n * Returns a new snapshot or one of the empty predefined ones. Returning the\n * predefined ones is important to prevent unnecessary re-renders in React.\n */\nfunction getSnapshot<TReturn>(\n singular: boolean,\n data: HumanReadable<TReturn>,\n resultType: ResultType,\n retryFn: () => void,\n error?: ErroredQuery,\n): QueryResult<TReturn> {\n if (singular && data === undefined) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n undefined,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotSingularErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotSingularComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotSingularUnknown as unknown as QueryResult<TReturn>;\n case 'cached':\n return emptySnapshotSingularCached as unknown as QueryResult<TReturn>;\n }\n }\n\n if (!singular && (data as unknown[]).length === 0) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n emptyArray,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotPluralComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotPluralUnknown as unknown as QueryResult<TReturn>;\n case 'cached':\n return emptySnapshotPluralCached as unknown as QueryResult<TReturn>;\n }\n }\n\n switch (resultType) {\n case 'error':\n if (error) {\n return [data, makeError(retryFn, error)];\n }\n return [\n data,\n makeError(retryFn, {\n error: 'app',\n id: 'unknown',\n name: 'unknown',\n message: 'An unknown error occurred',\n }),\n ];\n case 'complete':\n return [data, resultTypeComplete];\n case 'unknown':\n return [data, resultTypeUnknown];\n case 'cached':\n return [data, resultTypeCached];\n }\n}\n\nfunction makeError(retry: () => void, error: ErroredQuery): QueryErrorDetails {\n const message = error.message ?? 'An unknown error occurred';\n return {\n type: 'error',\n retry,\n refetch: retry,\n error: {\n type: error.error,\n message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyViewWrapper = ViewWrapper<any, any, any, any, any>;\n\nconst allViews = new WeakMap<\n ViewStore,\n Map<string, Map<string, AnyViewWrapper>>\n>();\n\nexport function getAllViewsSizeForTesting(store: ViewStore): number {\n if (TESTING) {\n let size = 0;\n for (const byHash of allViews.get(store)?.values() ?? []) {\n size += byHash.size;\n }\n return size;\n }\n return 0;\n}\n\n/**\n * A global store of all active views.\n *\n * React subscribes and unsubscribes to these views\n * via `useSyncExternalStore`.\n *\n * Managing views through `useEffect` or `useLayoutEffect` causes\n * inconsistencies because effects run after render.\n *\n * For example, if useQuery used use*Effect in the component below:\n * ```ts\n * function Foo({issueID}) {\n * const issue = useQuery(z.query.issue.where('id', issueID).one());\n * if (issue?.id !== undefined && issue.id !== issueID) {\n * console.log('MISMATCH!', issue.id, issueID);\n * }\n * }\n * ```\n *\n * `MISMATCH` will be printed whenever the `issueID` prop changes.\n *\n * This is because the component will render once with\n * the old state returned from `useQuery`. Then the effect inside\n * `useQuery` will run. The component will render again with the new\n * state. This inconsistent transition can cause unexpected results.\n *\n * Emulating `useEffect` via `useState` and `if` causes resource leaks.\n * That is:\n *\n * ```ts\n * function useQuery(q) {\n * const [oldHash, setOldHash] = useState();\n * if (hash(q) !== oldHash) {\n * // make new view\n * }\n *\n * useEffect(() => {\n * return () => view.destroy();\n * }, []);\n * }\n * ```\n *\n * I'm not sure why but in strict mode the cleanup function\n * fails to be called for the first instance of the view and only\n * cleans up later instances.\n *\n * Swapping `useState` to `useRef` has similar problems.\n */\nexport class ViewStore {\n /**\n * Client id, then query hash.\n *\n * Nested rather than keyed by the two joined together, because this is\n * looked up on every render of every `useQuery`. Joining them builds a\n * string that V8 has to hash from scratch, where both halves on their own\n * are strings it has already hashed and cached -- `hash()` is memoized on an\n * interned query, so the same string comes back each render. Measured over a\n * rebuild-and-look-up of one chain, that is the difference between 202ns and\n * 123ns; the join cost more than rebuilding and hashing the whole query.\n */\n #views = new Map<string, Map<string, AnyViewWrapper>>();\n\n constructor() {\n if (TESTING) {\n allViews.set(this, this.#views);\n }\n }\n\n getView<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n >(\n zero: Zero<TSchema, MD, TContext>,\n q: Query<TTable, TSchema, TReturn>,\n enabled: boolean,\n ttl: TTL,\n ): {\n getSnapshot: () => QueryResult<TReturn>;\n subscribeReactInternals: (internals: () => void) => () => void;\n updateTTL: (ttl: TTL) => void;\n waitForComplete: () => Promise<void>;\n waitForNonEmpty: () => Promise<void>;\n complete: boolean;\n nonEmpty: boolean;\n } {\n const qi = asQueryInternals(q);\n\n if (!enabled) {\n return {\n getSnapshot: () => getDefaultSnapshot(qi.format.singular),\n subscribeReactInternals: disabledSubscriber,\n updateTTL: () => {},\n waitForComplete: () => Promise.resolve(),\n waitForNonEmpty: () => Promise.resolve(),\n complete: false,\n nonEmpty: false,\n };\n }\n\n const {clientID} = zero;\n const hash = qi.hash();\n let byHash = this.#views.get(clientID);\n let existing = byHash?.get(hash);\n if (!existing) {\n existing = new ViewWrapper(q, zero, ttl, view => {\n const views = this.#views.get(clientID);\n const currentView = views?.get(hash);\n if (currentView && currentView !== view) {\n // we replaced the view with a new one already.\n return;\n }\n views?.delete(hash);\n if (views?.size === 0) {\n // Nothing is left for this client, so drop its map rather than\n // keeping one per client id the page has ever seen.\n this.#views.delete(clientID);\n }\n });\n if (!byHash) {\n byHash = new Map();\n this.#views.set(clientID, byHash);\n }\n byHash.set(hash, existing);\n } else {\n existing.updateTTL(ttl);\n }\n return existing as ViewWrapper<TTable, TSchema, TReturn, MD, TContext>;\n }\n}\n\nconst viewStore = new ViewStore();\n\n/**\n * This wraps and ref counts a view.\n *\n * The only signal we have from React as to whether or not it is\n * done with a view is when it calls `unsubscribe`.\n *\n * In non-strict-mode we can clean up the view as soon\n * as the listener count goes to 0.\n *\n * In strict-mode, the listener count will go to 0 then a\n * new listener for the same view is immediately added back.\n *\n * This is why the `onMaterialized` and `onDematerialized` callbacks exist --\n * they allow a view which React is still referencing to be added\n * back into the store when React re-subscribes to it.\n *\n * This wrapper also exists to deal with the various\n * `useSyncExternalStore` caveats that cause excessive\n * re-renders and materializations.\n *\n * See: https://react.dev/reference/react/useSyncExternalStore#caveats\n * Especially:\n * 1. The store snapshot returned by getSnapshot must be immutable. If the underlying store has mutable data, return a new immutable snapshot if the data has changed. Otherwise, return a cached last snapshot.\n * 2. If a different subscribe function is passed during a re-render, React will re-subscribe to the store using the newly passed subscribe function. You can prevent this by declaring subscribe outside the component.\n */\nclass ViewWrapper<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends AnyMutatorRegistry | CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n> {\n #view: TypedView<HumanReadable<TReturn>> | undefined;\n readonly #onDematerialized;\n readonly #query: Query<TTable, TSchema, TReturn>;\n #snapshot: QueryResult<TReturn>;\n readonly #reactInternals: Set<() => void> = new Set();\n #ttl: TTL;\n #complete = false;\n #completeResolver = resolver<void>();\n #nonEmpty = false;\n #nonEmptyResolver = resolver<void>();\n readonly #zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>;\n readonly #singular: boolean;\n #destroyTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n query: Query<TTable, TSchema, TReturn>,\n zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>,\n ttl: TTL,\n onDematerialized: (\n view: ViewWrapper<TTable, TSchema, TReturn, MD, TContext>,\n ) => void,\n ) {\n this.#query = query;\n this.#zero = zero;\n this.#ttl = ttl;\n this.#onDematerialized = onDematerialized;\n const {singular} = asQueryInternals(query).format;\n this.#singular = singular;\n this.#snapshot = getDefaultSnapshot(singular);\n this.#materializeIfNeeded();\n }\n\n #onData = (\n snap: Immutable<HumanReadable<TReturn>>,\n resultType: ResultType,\n error?: ErroredQuery,\n ) => {\n // applyChange now returns immutable data structures, so no deep clone needed.\n // Unchanged rows preserve their object identity for React.memo optimization.\n const data = snap as HumanReadable<TReturn>;\n const wasCached = this.#snapshot[1].type === 'cached';\n this.#snapshot = getSnapshot(\n this.#singular,\n data,\n resultType,\n this.#retry,\n error,\n );\n if (resultType === 'complete' || resultType === 'error') {\n this.#complete = true;\n this.#completeResolver.resolve();\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n const hasData = this.#singular\n ? this.#snapshot[0] !== undefined\n : (this.#snapshot[0] as unknown[]).length !== 0;\n // A 'cached' result is the server-confirmed answer from a previous\n // session, so even an empty one is something to render. It never\n // satisfies `complete`; only a confirmation on this connection does.\n if (resultType === 'cached' || hasData) {\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n } else if (wasCached && resultType === 'unknown') {\n // The cached claim was revoked (the got key was evicted before this\n // connection confirmed the query) and the view is empty: there is\n // nothing to render again until rows or a confirmation arrive.\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n }\n\n for (const internals of this.#reactInternals) {\n internals();\n }\n };\n\n /**\n * Called by the user to force a retry of the query\n * in the case the query errored.\n */\n #retry = () => {\n this.#view?.destroy();\n this.#view = undefined;\n this.#materializeIfNeeded();\n };\n\n #materializeIfNeeded = () => {\n if (this.#view) {\n return;\n }\n this.#view = this.#zero.materialize(this.#query, {\n ttl: this.#ttl,\n });\n this.#view.addListener(this.#onData);\n };\n\n getSnapshot = () => this.#snapshot;\n\n subscribeReactInternals = (internals: () => void): (() => void) => {\n this.#reactInternals.add(internals);\n // Cancel any pending destroy timer from a previous unsubscribe.\n // Without this, rapid unsub/resub cycles accumulate stale timers\n // that can fire during a gap between unsubscribe and resubscribe,\n // destroying the view even though it was actively used.\n if (this.#destroyTimer !== undefined) {\n clearTimeout(this.#destroyTimer);\n this.#destroyTimer = undefined;\n }\n this.#materializeIfNeeded();\n return () => {\n this.#reactInternals.delete(internals);\n\n // only schedule a cleanup task if we have no listeners left\n if (this.#reactInternals.size === 0) {\n this.#destroyTimer = setTimeout(() => {\n this.#destroyTimer = undefined;\n\n // We already destroyed the view\n if (this.#view === undefined) {\n return;\n }\n\n // Someone re-registered a listener on this view before the timeout elapsed.\n // This happens often in strict-mode which forces a component\n // to mount, unmount, remount.\n if (this.#reactInternals.size > 0) {\n return;\n }\n\n this.#view.destroy();\n this.#view = undefined;\n this.#complete = false;\n this.#completeResolver = resolver();\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n this.#onDematerialized(this);\n }, 10);\n }\n };\n };\n\n updateTTL(ttl: TTL): void {\n // `getView` calls this on every render, and forwarding an unchanged TTL\n // reaches the query manager, which re-derives the query's id from its AST\n // to find the entry. Nothing downstream distinguishes a repeat, so skip\n // it. A change in how the same duration is spelled ('60s' vs 60000) is\n // still a change here and still propagates, as it did before.\n if (this.#ttl === ttl) {\n return;\n }\n this.#ttl = ttl;\n this.#view?.updateTTL(ttl);\n }\n\n get complete() {\n return this.#complete;\n }\n\n waitForComplete(): Promise<void> {\n return this.#completeResolver.promise;\n }\n\n get nonEmpty() {\n return this.#nonEmpty;\n }\n\n waitForNonEmpty(): Promise<void> {\n return this.#nonEmptyResolver.promise;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,SAAS,eAQP,OAGA,MAC6C;CAC7C,MAAM,WAAW,OAAqC,KAAA,CAAS;CAI/D,IAAI,CAAC,OACH;CAGF,MAAM,QAAQ,SAAS;CACvB,IAAI,SAAS,MAAM,SAAS,MAAM;EAChC,IAAI,MAAM,aAAa,OACrB,OAAO,MAAM;EAEf,IACE,WAAW,SACX,MAAM,gBAAgB,MAAM,SAC5B,MAAM,YAAY,KAAK,WACvB,UAAU,MAAM,MAAM,MAAM,IAAI,GAChC;GAGA,MAAM,WAAW;GACjB,OAAO,MAAM;EACf;CACF;CAEA,MAAM,IAAI,kBAAkB,OAAO,KAAK,OAAO;CAC/C,MAAM,YAAY,WAAW;CAC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ized","#query","#reactInternals","#zero","#singular","#ttl","#snapshot","#materializeIfNeeded","#lastResultType","#lastData","#lastError","#retry","#complete","#completeResolver","#nonEmpty","#nonEmptyResolver","#view","#onData","#destroyTimer"],"sources":["../../../../zero-react/src/use-query.tsx"],"sourcesContent":["import {resolver} from '@rocicorp/resolver';\nimport React, {useRef, useSyncExternalStore} from 'react';\nimport {deepEqual} from '../../shared/src/json.ts';\nimport {TESTING} from '../../shared/src/testing.ts';\nimport {\n type Immutable,\n addContextToQuery,\n asQueryInternals,\n DEFAULT_TTL_MS,\n} from './bindings.ts';\nimport {useZero} from './zero-provider.tsx';\nimport type {\n AnyMutatorRegistry,\n BaseDefaultContext,\n BaseDefaultSchema,\n CustomMutatorDefs,\n DefaultContext,\n DefaultSchema,\n ErroredQuery,\n Falsy,\n HumanReadable,\n PullRow,\n Query,\n QueryErrorDetails,\n QueryOrQueryRequest,\n QueryResultDetails,\n ReadonlyJSONValue,\n ResultType,\n TTL,\n TypedView,\n Zero,\n} from './zero.ts';\n\ntype StableQueryCache = {\n zero: unknown;\n context: unknown;\n /** The last input, so an unchanged one is an identity compare and nothing else. */\n rawQuery: object;\n /** The `CustomQuery` a query request names; undefined for a plain query. */\n customQuery: unknown;\n args: ReadonlyJSONValue | undefined;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n q: Query<any, any, any>;\n};\n\n/**\n * Resolves a query request against the Zero context, reusing the previous\n * result while the request means the same thing.\n *\n * Interning already makes an unchanged *plain* query come back as the same\n * object, so this is aimed at the query-request form -- `queries.issue({id})`\n * -- where every render allocates a fresh request and `addContextToQuery`\n * re-runs the definition. That costs argument validation (a zod parse of\n * byte-identical args) plus a walk of the builder chain, neither of which\n * interning removes: it makes rebuilding the chain cheap and gives the same\n * object back, but only after the work has been done again.\n *\n * A request resolves to the previous query when it names the same\n * `CustomQuery`, the same context, and deep-equal args. Those are exactly the\n * inputs the definition is allowed to depend on: a named query is re-derived\n * on the server from its name and args, so it has to be a pure function of\n * them, or client and server would build different queries.\n *\n * The ref is written during render. That is safe here because it is a pure\n * cache: an entry is derived only from the inputs, so a StrictMode double\n * render or a discarded concurrent render leaves it valid either way.\n */\nfunction useStableQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema,\n TReturn,\n TContext extends BaseDefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n zero: Zero<TSchema, undefined, TContext>,\n): Query<TTable, TSchema, TReturn> | undefined {\n const cacheRef = useRef<StableQueryCache | undefined>(undefined);\n\n // Deliberately kept rather than cleared: a query toggled off and back on\n // reuses what it had.\n if (!query) {\n return undefined;\n }\n\n const cache = cacheRef.current;\n if (cache && cache.zero === zero) {\n if (cache.rawQuery === query) {\n return cache.q as Query<TTable, TSchema, TReturn>;\n }\n if (\n 'query' in query &&\n cache.customQuery === query.query &&\n cache.context === zero.context &&\n deepEqual(cache.args, query.args)\n ) {\n // Same meaning, new wrapper object: remember it so the next render is\n // the identity compare above.\n cache.rawQuery = query;\n return cache.q as Query<TTable, TSchema, TReturn>;\n }\n }\n\n const q = addContextToQuery(query, zero.context);\n const isRequest = 'query' in query;\n cacheRef.current = {\n zero: zero,\n context: zero.context,\n rawQuery: query,\n customQuery: isRequest ? query.query : undefined,\n args: isRequest ? query.args : undefined,\n q,\n };\n return q;\n}\n\nexport type QueryResult<TReturn> = readonly [\n HumanReadable<TReturn>,\n QueryResultDetails & {},\n];\n\n/**\n * Result type for \"maybe queries\" - queries that may be falsy.\n * The data value can be undefined when the query is falsy/disabled.\n */\nexport type MaybeQueryResult<TReturn> = readonly [\n HumanReadable<TReturn> | undefined,\n QueryResultDetails & {},\n];\n\nexport type UseQueryOptions = {\n enabled?: boolean | undefined;\n /**\n * Time to live (TTL) in seconds. Controls how long query results are cached\n * after the query is removed. During this time, Zero continues to sync the query.\n * Default is 'never'.\n */\n ttl?: TTL | undefined;\n};\n\nexport type UseSuspenseQueryOptions = UseQueryOptions & {\n /**\n * Whether to suspend until:\n * - 'partial': the query has partial results (partial array or defined\n * value for singular results) which may be of result type 'unknown',\n * or the query result type is 'complete' or 'cached' (in which case\n * results may be empty: a server-confirmed empty answer, from this\n * connection or a previous one, is something to render). This is useful\n * for suspending until there are partial optimistic local results, or\n * the query has completed loading from the server.\n * - 'complete': the query result type is 'complete'.\n *\n * Default is 'partial'.\n */\n suspendUntil?: 'complete' | 'partial';\n};\n\nconst reactUse = (React as {use?: (p: Promise<unknown>) => void}).use;\nconst suspend: (p: Promise<unknown>) => void = reactUse\n ? reactUse\n : p => {\n throw p;\n };\n\n// Overload 1: Query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({enabled = true, ttl = DEFAULT_TTL_MS} = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = useStableQuery(query, zero);\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n return useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n}\n\n// Overload 1: Query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n let suspendUntil: 'complete' | 'partial' = 'partial';\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({\n enabled = true,\n ttl = DEFAULT_TTL_MS,\n suspendUntil = 'complete',\n } = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = useStableQuery(query, zero);\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n const snapshot = useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n\n if (view && enabled) {\n if (suspendUntil === 'complete' && !view.complete) {\n suspend(view.waitForComplete());\n }\n\n if (suspendUntil === 'partial' && !view.nonEmpty) {\n suspend(view.waitForNonEmpty());\n }\n }\n\n return snapshot;\n}\n\nconst emptyArray: unknown[] = [];\nconst disabledSubscriber = () => () => {};\n\nconst resultTypeUnknown = {type: 'unknown'} as const;\nconst resultTypeCached = {type: 'cached'} as const;\nconst resultTypeComplete = {type: 'complete'} as const;\nconst resultTypeError = {type: 'error'} as const;\n\nconst disabledQuerySnapshot = [undefined, resultTypeUnknown] as const;\nconst getDisabledSnapshot = () => disabledQuerySnapshot;\n\nconst emptySnapshotSingularUnknown = [undefined, resultTypeUnknown] as const;\nconst emptySnapshotSingularCached = [undefined, resultTypeCached] as const;\nconst emptySnapshotSingularComplete = [undefined, resultTypeComplete] as const;\nconst emptySnapshotSingularErrorUnknown = [undefined, resultTypeError] as const;\nconst emptySnapshotPluralUnknown = [emptyArray, resultTypeUnknown] as const;\nconst emptySnapshotPluralCached = [emptyArray, resultTypeCached] as const;\nconst emptySnapshotPluralComplete = [emptyArray, resultTypeComplete] as const;\nconst emptySnapshotErrorUnknown = [emptyArray, resultTypeError] as const;\n\nfunction getDefaultSnapshot<TReturn>(singular: boolean): QueryResult<TReturn> {\n return (\n singular ? emptySnapshotSingularUnknown : emptySnapshotPluralUnknown\n ) as QueryResult<TReturn>;\n}\n\n/**\n * Returns a new snapshot or one of the empty predefined ones. Returning the\n * predefined ones is important to prevent unnecessary re-renders in React.\n */\nfunction getSnapshot<TReturn>(\n singular: boolean,\n data: HumanReadable<TReturn>,\n resultType: ResultType,\n retryFn: () => void,\n error?: ErroredQuery,\n): QueryResult<TReturn> {\n if (singular && data === undefined) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n undefined,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotSingularErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotSingularComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotSingularUnknown as unknown as QueryResult<TReturn>;\n case 'cached':\n return emptySnapshotSingularCached as unknown as QueryResult<TReturn>;\n }\n }\n\n if (!singular && (data as unknown[]).length === 0) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n emptyArray,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotPluralComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotPluralUnknown as unknown as QueryResult<TReturn>;\n case 'cached':\n return emptySnapshotPluralCached as unknown as QueryResult<TReturn>;\n }\n }\n\n switch (resultType) {\n case 'error':\n if (error) {\n return [data, makeError(retryFn, error)];\n }\n return [\n data,\n makeError(retryFn, {\n error: 'app',\n id: 'unknown',\n name: 'unknown',\n message: 'An unknown error occurred',\n }),\n ];\n case 'complete':\n return [data, resultTypeComplete];\n case 'unknown':\n return [data, resultTypeUnknown];\n case 'cached':\n return [data, resultTypeCached];\n }\n}\n\nfunction makeError(retry: () => void, error: ErroredQuery): QueryErrorDetails {\n const message = error.message ?? 'An unknown error occurred';\n return {\n type: 'error',\n retry,\n refetch: retry,\n error: {\n type: error.error,\n message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyViewWrapper = ViewWrapper<any, any, any, any, any>;\n\nconst allViews = new WeakMap<\n ViewStore,\n Map<string, Map<string, AnyViewWrapper>>\n>();\n\nexport function getAllViewsSizeForTesting(store: ViewStore): number {\n if (TESTING) {\n let size = 0;\n for (const byHash of allViews.get(store)?.values() ?? []) {\n size += byHash.size;\n }\n return size;\n }\n return 0;\n}\n\n/**\n * A global store of all active views.\n *\n * React subscribes and unsubscribes to these views\n * via `useSyncExternalStore`.\n *\n * Managing views through `useEffect` or `useLayoutEffect` causes\n * inconsistencies because effects run after render.\n *\n * For example, if useQuery used use*Effect in the component below:\n * ```ts\n * function Foo({issueID}) {\n * const issue = useQuery(z.query.issue.where('id', issueID).one());\n * if (issue?.id !== undefined && issue.id !== issueID) {\n * console.log('MISMATCH!', issue.id, issueID);\n * }\n * }\n * ```\n *\n * `MISMATCH` will be printed whenever the `issueID` prop changes.\n *\n * This is because the component will render once with\n * the old state returned from `useQuery`. Then the effect inside\n * `useQuery` will run. The component will render again with the new\n * state. This inconsistent transition can cause unexpected results.\n *\n * Emulating `useEffect` via `useState` and `if` causes resource leaks.\n * That is:\n *\n * ```ts\n * function useQuery(q) {\n * const [oldHash, setOldHash] = useState();\n * if (hash(q) !== oldHash) {\n * // make new view\n * }\n *\n * useEffect(() => {\n * return () => view.destroy();\n * }, []);\n * }\n * ```\n *\n * I'm not sure why but in strict mode the cleanup function\n * fails to be called for the first instance of the view and only\n * cleans up later instances.\n *\n * Swapping `useState` to `useRef` has similar problems.\n */\nexport class ViewStore {\n /**\n * Client id, then query hash.\n *\n * Nested rather than keyed by the two joined together, because this is\n * looked up on every render of every `useQuery`. Joining them builds a\n * string that V8 has to hash from scratch, where both halves on their own\n * are strings it has already hashed and cached -- `hash()` is memoized on an\n * interned query, so the same string comes back each render. Measured over a\n * rebuild-and-look-up of one chain, that is the difference between 202ns and\n * 123ns; the join cost more than rebuilding and hashing the whole query.\n */\n #views = new Map<string, Map<string, AnyViewWrapper>>();\n\n constructor() {\n if (TESTING) {\n allViews.set(this, this.#views);\n }\n }\n\n getView<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n >(\n zero: Zero<TSchema, MD, TContext>,\n q: Query<TTable, TSchema, TReturn>,\n enabled: boolean,\n ttl: TTL,\n ): {\n getSnapshot: () => QueryResult<TReturn>;\n subscribeReactInternals: (internals: () => void) => () => void;\n updateTTL: (ttl: TTL) => void;\n waitForComplete: () => Promise<void>;\n waitForNonEmpty: () => Promise<void>;\n complete: boolean;\n nonEmpty: boolean;\n } {\n const qi = asQueryInternals(q);\n\n if (!enabled) {\n return {\n getSnapshot: () => getDefaultSnapshot(qi.format.singular),\n subscribeReactInternals: disabledSubscriber,\n updateTTL: () => {},\n waitForComplete: () => Promise.resolve(),\n waitForNonEmpty: () => Promise.resolve(),\n complete: false,\n nonEmpty: false,\n };\n }\n\n const {clientID} = zero;\n const hash = qi.hash();\n let byHash = this.#views.get(clientID);\n let existing = byHash?.get(hash);\n if (!existing) {\n existing = new ViewWrapper(q, zero, ttl, view => {\n const views = this.#views.get(clientID);\n const currentView = views?.get(hash);\n if (currentView && currentView !== view) {\n // we replaced the view with a new one already.\n return;\n }\n views?.delete(hash);\n if (views?.size === 0) {\n // Nothing is left for this client, so drop its map rather than\n // keeping one per client id the page has ever seen.\n this.#views.delete(clientID);\n }\n });\n if (!byHash) {\n byHash = new Map();\n this.#views.set(clientID, byHash);\n }\n byHash.set(hash, existing);\n } else {\n existing.updateTTL(ttl);\n }\n return existing as ViewWrapper<TTable, TSchema, TReturn, MD, TContext>;\n }\n}\n\nconst viewStore = new ViewStore();\n\n/**\n * This wraps and ref counts a view.\n *\n * The only signal we have from React as to whether or not it is\n * done with a view is when it calls `unsubscribe`.\n *\n * In non-strict-mode we can clean up the view as soon\n * as the listener count goes to 0.\n *\n * In strict-mode, the listener count will go to 0 then a\n * new listener for the same view is immediately added back.\n *\n * This is why the `onMaterialized` and `onDematerialized` callbacks exist --\n * they allow a view which React is still referencing to be added\n * back into the store when React re-subscribes to it.\n *\n * This wrapper also exists to deal with the various\n * `useSyncExternalStore` caveats that cause excessive\n * re-renders and materializations.\n *\n * See: https://react.dev/reference/react/useSyncExternalStore#caveats\n * Especially:\n * 1. The store snapshot returned by getSnapshot must be immutable. If the underlying store has mutable data, return a new immutable snapshot if the data has changed. Otherwise, return a cached last snapshot.\n * 2. If a different subscribe function is passed during a re-render, React will re-subscribe to the store using the newly passed subscribe function. You can prevent this by declaring subscribe outside the component.\n */\nclass ViewWrapper<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends AnyMutatorRegistry | CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n> {\n #view: TypedView<HumanReadable<TReturn>> | undefined;\n readonly #onDematerialized;\n readonly #query: Query<TTable, TSchema, TReturn>;\n #snapshot: QueryResult<TReturn>;\n readonly #reactInternals: Set<() => void> = new Set();\n #ttl: TTL;\n #complete = false;\n #completeResolver = resolver<void>();\n #nonEmpty = false;\n #nonEmptyResolver = resolver<void>();\n readonly #zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>;\n readonly #singular: boolean;\n #destroyTimer: ReturnType<typeof setTimeout> | undefined;\n\n // Inputs of the previous #onData call. When a view flush delivers\n // reference-identical data with the same resultType and error, the previous\n // snapshot tuple is kept and React is not notified — building a fresh tuple\n // would defeat useSyncExternalStore's Object.is bailout and re-render every\n // subscriber with identical data. #lastResultType doubles as the \"has fired\n // before\" sentinel (data and error may both legitimately be undefined).\n #lastData: Immutable<HumanReadable<TReturn>> | undefined;\n #lastResultType: ResultType | undefined;\n #lastError: ErroredQuery | undefined;\n\n constructor(\n query: Query<TTable, TSchema, TReturn>,\n zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>,\n ttl: TTL,\n onDematerialized: (\n view: ViewWrapper<TTable, TSchema, TReturn, MD, TContext>,\n ) => void,\n ) {\n this.#query = query;\n this.#zero = zero;\n this.#ttl = ttl;\n this.#onDematerialized = onDematerialized;\n const {singular} = asQueryInternals(query).format;\n this.#singular = singular;\n this.#snapshot = getDefaultSnapshot(singular);\n this.#materializeIfNeeded();\n }\n\n #onData = (\n snap: Immutable<HumanReadable<TReturn>>,\n resultType: ResultType,\n error?: ErroredQuery,\n ) => {\n const wasCached = this.#snapshot[1].type === 'cached';\n const changed =\n this.#lastResultType === undefined ||\n this.#lastData !== snap ||\n this.#lastResultType !== resultType ||\n this.#lastError !== error;\n this.#lastData = snap;\n this.#lastResultType = resultType;\n this.#lastError = error;\n\n if (changed) {\n // applyChange now returns immutable data structures, so no deep clone needed.\n // Unchanged rows preserve their object identity for React.memo optimization.\n const data = snap as HumanReadable<TReturn>;\n this.#snapshot = getSnapshot(\n this.#singular,\n data,\n resultType,\n this.#retry,\n error,\n );\n }\n\n // The resolver bookkeeping runs even when unchanged: after a\n // destroy/re-materialize cycle the resolvers are fresh but the new view\n // may deliver the same data/resultType as before the destroy.\n if (resultType === 'complete' || resultType === 'error') {\n this.#complete = true;\n this.#completeResolver.resolve();\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n const hasData = this.#singular\n ? this.#snapshot[0] !== undefined\n : (this.#snapshot[0] as unknown[]).length !== 0;\n // A 'cached' result is the server-confirmed answer from a previous\n // session, so even an empty one is something to render. It never\n // satisfies `complete`; only a confirmation on this connection does.\n if (resultType === 'cached' || hasData) {\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n } else if (wasCached && resultType === 'unknown') {\n // The cached claim was revoked (the got key was evicted before this\n // connection confirmed the query) and the view is empty: there is\n // nothing to render again until rows or a confirmation arrive.\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n }\n\n if (changed) {\n for (const internals of this.#reactInternals) {\n internals();\n }\n }\n };\n\n /**\n * Called by the user to force a retry of the query\n * in the case the query errored.\n */\n #retry = () => {\n this.#view?.destroy();\n this.#view = undefined;\n this.#materializeIfNeeded();\n };\n\n #materializeIfNeeded = () => {\n if (this.#view) {\n return;\n }\n this.#view = this.#zero.materialize(this.#query, {\n ttl: this.#ttl,\n });\n this.#view.addListener(this.#onData);\n };\n\n getSnapshot = () => this.#snapshot;\n\n subscribeReactInternals = (internals: () => void): (() => void) => {\n this.#reactInternals.add(internals);\n // Cancel any pending destroy timer from a previous unsubscribe.\n // Without this, rapid unsub/resub cycles accumulate stale timers\n // that can fire during a gap between unsubscribe and resubscribe,\n // destroying the view even though it was actively used.\n if (this.#destroyTimer !== undefined) {\n clearTimeout(this.#destroyTimer);\n this.#destroyTimer = undefined;\n }\n this.#materializeIfNeeded();\n return () => {\n this.#reactInternals.delete(internals);\n\n // only schedule a cleanup task if we have no listeners left\n if (this.#reactInternals.size === 0) {\n this.#destroyTimer = setTimeout(() => {\n this.#destroyTimer = undefined;\n\n // We already destroyed the view\n if (this.#view === undefined) {\n return;\n }\n\n // Someone re-registered a listener on this view before the timeout elapsed.\n // This happens often in strict-mode which forces a component\n // to mount, unmount, remount.\n if (this.#reactInternals.size > 0) {\n return;\n }\n\n this.#view.destroy();\n this.#view = undefined;\n this.#complete = false;\n this.#completeResolver = resolver();\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n this.#onDematerialized(this);\n }, 10);\n }\n };\n };\n\n updateTTL(ttl: TTL): void {\n // `getView` calls this on every render, and forwarding an unchanged TTL\n // reaches the query manager, which re-derives the query's id from its AST\n // to find the entry. Nothing downstream distinguishes a repeat, so skip\n // it. A change in how the same duration is spelled ('60s' vs 60000) is\n // still a change here and still propagates, as it did before.\n if (this.#ttl === ttl) {\n return;\n }\n this.#ttl = ttl;\n this.#view?.updateTTL(ttl);\n }\n\n get complete() {\n return this.#complete;\n }\n\n waitForComplete(): Promise<void> {\n return this.#completeResolver.promise;\n }\n\n get nonEmpty() {\n return this.#nonEmpty;\n }\n\n waitForNonEmpty(): Promise<void> {\n return this.#nonEmptyResolver.promise;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,SAAS,eAQP,OAGA,MAC6C;CAC7C,MAAM,WAAW,OAAqC,KAAA,CAAS;CAI/D,IAAI,CAAC,OACH;CAGF,MAAM,QAAQ,SAAS;CACvB,IAAI,SAAS,MAAM,SAAS,MAAM;EAChC,IAAI,MAAM,aAAa,OACrB,OAAO,MAAM;EAEf,IACE,WAAW,SACX,MAAM,gBAAgB,MAAM,SAC5B,MAAM,YAAY,KAAK,WACvB,UAAU,MAAM,MAAM,MAAM,IAAI,GAChC;GAGA,MAAM,WAAW;GACjB,OAAO,MAAM;EACf;CACF;CAEA,MAAM,IAAI,kBAAkB,OAAO,KAAK,OAAO;CAC/C,MAAM,YAAY,WAAW;CAC7B,SAAS,UAAU;EACX;EACN,SAAS,KAAK;EACd,UAAU;EACV,aAAa,YAAY,MAAM,QAAQ,KAAA;EACvC,MAAM,YAAY,MAAM,OAAO,KAAA;EAC/B;CACF;CACA,OAAO;AACT;AA2CA,IAAM,WAAY,MAAgD;AAClE,IAAM,UAAyC,WAC3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
{"version":3,"file":"array-view.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/array-view.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,8CAA8C,CAAC;AAC/E,OAAO,KAAK,EAAC,GAAG,EAAC,MAAM,iBAAiB,CAAC;AACzC,OAAO,KAAK,EAAC,QAAQ,EAAc,SAAS,EAAC,MAAM,wBAAwB,CAAC;AAG5E,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AACxC,OAAO,EAAa,KAAK,KAAK,EAAE,KAAK,MAAM,EAAC,MAAM,eAAe,CAAC;AAGlE,OAAO,KAAK,EAAQ,MAAM,EAAE,IAAI,EAAC,MAAM,WAAW,CAAC;AA0BnD;;;;;;;;;;GAUG;AACH,qBAAa,SAAS,CAAC,CAAC,SAAS,IAAI,CAAE,YAAW,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;;IAgBpE,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC;IAyBpC,YACE,KAAK,EAAE,KAAK,EACZ,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,IAAI,GAAG,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,EAClD,SAAS,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,EAmB9B;IAED,IAAI,IAAI,IAC4C,CAAC,CACpD;IAMD,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,cAShC;
|
|
1
|
+
{"version":3,"file":"array-view.d.ts","sourceRoot":"","sources":["../../../../../zql/src/ivm/array-view.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,8CAA8C,CAAC;AAC/E,OAAO,KAAK,EAAC,GAAG,EAAC,MAAM,iBAAiB,CAAC;AACzC,OAAO,KAAK,EAAC,QAAQ,EAAc,SAAS,EAAC,MAAM,wBAAwB,CAAC;AAG5E,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,aAAa,CAAC;AACxC,OAAO,EAAa,KAAK,KAAK,EAAE,KAAK,MAAM,EAAC,MAAM,eAAe,CAAC;AAGlE,OAAO,KAAK,EAAQ,MAAM,EAAE,IAAI,EAAC,MAAM,WAAW,CAAC;AA0BnD;;;;;;;;;;GAUG;AACH,qBAAa,SAAS,CAAC,CAAC,SAAS,IAAI,CAAE,YAAW,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;;IAgBpE,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC;IAyBpC,YACE,KAAK,EAAE,KAAK,EACZ,MAAM,EAAE,MAAM,EACd,aAAa,EAAE,IAAI,GAAG,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,EAClD,SAAS,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,EAmB9B;IAED,IAAI,IAAI,IAC4C,CAAC,CACpD;IAMD,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,cAShC;IAoBD,OAAO,SAEN;IAqBD,IAAI,CAAC,MAAM,EAAE,MAAM,oBAuBlB;IAED;;;;;;;;;;OAUG;IACH,QAAQ,IAAI,IAAI,CAKf;IAED;;;;;OAKG;IACH,WAAW,IAAI,IAAI,CAElB;IAED,KAAK,SAkBJ;IAED,SAAS,CAAC,GAAG,EAAE,GAAG,QAEjB;IAED;;;;;;OAMG;IACH,UAAU,IAAI,IAAI,CAIjB;IAED,wEAAwE;IACxE,YAAY,IAAI,IAAI,CAInB;CAkBF"}
|
|
@@ -77,20 +77,26 @@ var ArrayView = class {
|
|
|
77
77
|
addListener(listener) {
|
|
78
78
|
assert(!this.#listeners.has(listener), "Listener already registered");
|
|
79
79
|
this.#listeners.add(listener);
|
|
80
|
-
this.#
|
|
80
|
+
listener(...this.#listenerArgs());
|
|
81
81
|
return () => {
|
|
82
82
|
this.#listeners.delete(listener);
|
|
83
83
|
};
|
|
84
84
|
}
|
|
85
85
|
#fireListeners() {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
86
|
+
const args = this.#listenerArgs();
|
|
87
|
+
for (const listener of this.#listeners) listener(...args);
|
|
88
|
+
}
|
|
89
|
+
#listenerArgs() {
|
|
90
|
+
if (this.#committedRoot !== void 0) return [
|
|
91
|
+
this.data,
|
|
92
|
+
this.#heldResultType,
|
|
93
|
+
this.#heldError
|
|
94
|
+
];
|
|
95
|
+
return [
|
|
96
|
+
this.data,
|
|
97
|
+
this.#resultType,
|
|
98
|
+
this.#error
|
|
99
|
+
];
|
|
94
100
|
}
|
|
95
101
|
destroy() {
|
|
96
102
|
this.onDestroy?.();
|
|
@@ -104,8 +110,11 @@ var ArrayView = class {
|
|
|
104
110
|
this.flush();
|
|
105
111
|
}
|
|
106
112
|
push(change) {
|
|
107
|
-
this.#
|
|
108
|
-
|
|
113
|
+
const newRoot = applyChange(this.#root, changeToViewChange(change), this.#getSchema(), "", this.#format, false, this.#txnDirty);
|
|
114
|
+
if (newRoot !== this.#root) {
|
|
115
|
+
this.#root = newRoot;
|
|
116
|
+
this.#dirty = true;
|
|
117
|
+
}
|
|
109
118
|
return emptyArray;
|
|
110
119
|
}
|
|
111
120
|
/**
|
|
@@ -139,8 +148,8 @@ var ArrayView = class {
|
|
|
139
148
|
this.#held = false;
|
|
140
149
|
if (!this.#dirty) return;
|
|
141
150
|
this.#dirty = false;
|
|
142
|
-
this.#fireListeners();
|
|
143
151
|
this.#txnDirty = /* @__PURE__ */ new WeakSet();
|
|
152
|
+
this.#fireListeners();
|
|
144
153
|
}
|
|
145
154
|
updateTTL(ttl) {
|
|
146
155
|
this.#updateTTL(ttl);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"array-view.js","names":["#input","#listeners","#format","#updateTTL","#root","#resultType","#error","#setResultType","#hydrate","#committedRoot","#schema","#fireListener","#heldResultType","#heldError","#dirty","#getSchema","#txnDirty","#held","#fireListeners"],"sources":["../../../../../zql/src/ivm/array-view.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {Immutable} from '../../../shared/src/immutable.ts';\nimport {emptyArray} from '../../../shared/src/sentinels.ts';\nimport type {ErroredQuery} from '../../../zero-protocol/src/custom-queries.ts';\nimport type {TTL} from '../query/ttl.ts';\nimport type {Listener, ResultType, TypedView} from '../query/typed-view.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport type {Change} from './change.ts';\nimport {skipYields, type Input, type Output} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {applyChange, type ViewChange} from './view-apply-change.ts';\nimport type {Entry, Format, View} from './view.ts';\n\nfunction changeToViewChange(change: Change): ViewChange {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n return {type: 'add', node: change[ChangeIndex.NODE]};\n case ChangeType.REMOVE:\n return {type: 'remove', node: change[ChangeIndex.NODE]};\n case ChangeType.CHILD:\n return {\n type: 'child',\n node: change[ChangeIndex.NODE],\n child: {\n relationshipName: change[ChangeIndex.CHILD_DATA].relationshipName,\n change: changeToViewChange(change[ChangeIndex.CHILD_DATA].change),\n },\n };\n case ChangeType.EDIT:\n return {\n type: 'edit',\n node: change[ChangeIndex.NODE],\n oldNode: change[ChangeIndex.OLD_NODE],\n };\n }\n}\n\n/**\n * Implements a materialized view of the output of an operator.\n *\n * It might seem more efficient to use an immutable b-tree for the\n * materialization, but it's not so clear. Inserts in the middle are\n * asymptotically slower in an array, but can often be done with zero\n * allocations, where changes to the b-tree will often require several allocs.\n *\n * Also the plain array view is more convenient for consumers since you can dump\n * it into console to see what it is, rather than having to iterate it.\n */\nexport class ArrayView<V extends View> implements Output, TypedView<V> {\n readonly #input: Input;\n readonly #listeners = new Set<Listener<V>>();\n // Read lazily: a DeferredInput has no schema until its pipeline is attached,\n // and the schema is only needed once there is a change to apply.\n #schema: SourceSchema | undefined;\n readonly #format: Format;\n\n // Synthetic \"root\" entry that has a single \"\" relationship, so that we can\n // treat all changes, including the root change, generically.\n //\n // applyChange is immutable: it returns a new root, preserving the references\n // of unchanged subtrees so consumers (React.memo / Solid) can skip them. We\n // therefore reassign #root on every change rather than mutating in place.\n #root: Entry;\n\n onDestroy: (() => void) | undefined;\n\n #dirty = false;\n // Set by holdData(): the root that `data` and newly added listeners keep\n // seeing until releaseData() or the next flush, while pushes build up #root\n // behind it.\n #committedRoot: Entry | undefined;\n // From holdData() until the next flush. Outlasts #committedRoot, which\n // releaseData() drops first.\n #held = false;\n // The result type and error as of holdData(): what a listener added while\n // held is called with, so it never sees old rows paired with a new type.\n #heldResultType: ResultType = 'unknown';\n #heldError: ErroredQuery | undefined;\n #resultType: ResultType = 'unknown';\n #error: ErroredQuery | undefined;\n readonly #updateTTL: (ttl: TTL) => void;\n\n // Objects/arrays created or cloned during the current (un-flushed)\n // transaction. applyChange may mutate these in place rather than copying\n // again, since they are not yet observed by any listener. Replaced at\n // flush(), after which the committed snapshot must be copied-on-write again.\n // A WeakSet (not a Set) so it never extends the lifetime of transient clones.\n #txnDirty: WeakSet<object> = new WeakSet();\n\n constructor(\n input: Input,\n format: Format,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n ) {\n this.#input = input;\n this.#format = format;\n this.#updateTTL = updateTTL;\n this.#root = {'': format.singular ? undefined : []};\n input.setOutput(this);\n\n if (queryComplete === true) {\n this.#resultType = 'complete';\n } else if ('error' in queryComplete) {\n this.#resultType = 'error';\n this.#error = queryComplete;\n } else {\n void queryComplete\n .then(() => this.#setResultType('complete'))\n .catch(e => this.#setResultType('error', e));\n }\n this.#hydrate();\n }\n\n get data() {\n return (this.#committedRoot ?? this.#root)[''] as V;\n }\n\n #getSchema(): SourceSchema {\n return (this.#schema ??= this.#input.getSchema());\n }\n\n addListener(listener: Listener<V>) {\n assert(!this.#listeners.has(listener), 'Listener already registered');\n this.#listeners.add(listener);\n\n this.#fireListener(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #fireListeners() {\n for (const listener of this.#listeners) {\n this.#fireListener(listener);\n }\n }\n\n #fireListener(listener: Listener<V>) {\n if (this.#committedRoot !== undefined) {\n // Held rows go with the held type; after releaseData() both are current.\n listener(\n this.data as Immutable<V>,\n this.#heldResultType,\n this.#heldError,\n );\n return;\n }\n listener(this.data as Immutable<V>, this.#resultType, this.#error);\n }\n\n destroy() {\n this.onDestroy?.();\n }\n\n #hydrate() {\n this.#dirty = true;\n for (const node of skipYields(this.#input.fetch({}))) {\n this.#root = applyChange(\n this.#root,\n {type: 'add', node},\n this.#getSchema(),\n '',\n this.#format,\n false /* withIDs */,\n true /* mutate: #root is freshly created and not yet observed by any\n consumer, so build it in place to avoid O(N^2) array copies.\n Every later push() is immutable, preserving reference\n stability for unchanged subtrees. */,\n );\n }\n this.flush();\n }\n\n push(change: Change) {\n this.#dirty = true;\n this.#root = applyChange(\n this.#root,\n changeToViewChange(change),\n this.#getSchema(),\n '',\n this.#format,\n false /* withIDs */,\n this.#txnDirty /* mutate: copy-on-write within this transaction */,\n );\n return emptyArray;\n }\n\n /**\n * Keep exposing the current snapshot, whatever is pushed in the meantime,\n * until {@link releaseData} or the next {@link flush}. Result type\n * notifications are held back until that flush.\n *\n * A transaction is normally one synchronous task, so nobody can look at a\n * view between its pushes and its flush. Deferred pipelines are different:\n * they are hydrated over several tasks and flushed together (see\n * `QueryDelegate.onPipelinesReady`), and a view that already has its rows\n * must not show them early.\n */\n holdData(): void {\n this.#committedRoot = this.#root;\n this.#held = true;\n this.#heldResultType = this.#resultType;\n this.#heldError = this.#error;\n }\n\n /**\n * Make `data` current again without notifying anyone yet; listeners are\n * still only called by the next {@link flush}. Views released together get\n * this called on all of them before any is flushed, so a listener of one\n * that reads another sees its rows too.\n */\n releaseData(): void {\n this.#committedRoot = undefined;\n }\n\n flush() {\n this.#committedRoot = undefined;\n this.#held = false;\n if (!this.#dirty) {\n return;\n }\n this.#dirty = false;\n this.#fireListeners();\n // The snapshot just handed to listeners is now observed; the next\n // transaction must copy-on-write rather than mutate these objects. A fresh\n // WeakSet drops all \"owned\" marks (WeakSet has no clear()).\n this.#txnDirty = new WeakSet();\n }\n\n updateTTL(ttl: TTL) {\n this.#updateTTL(ttl);\n }\n\n /**\n * The store holds the server-confirmed complete result of this query from a\n * previous sync (the persisted got-queries key exists, pre-authoritative).\n * Never downgrades 'complete'/'error', and never resolves anything that\n * waits on 'complete' — freshness stays a promise only the connection can\n * keep.\n */\n markCached(): void {\n if (this.#resultType === 'unknown') {\n this.#setResultType('cached');\n }\n }\n\n /** The got key was deleted (eviction) while still pre-authoritative. */\n unmarkCached(): void {\n if (this.#resultType === 'cached') {\n this.#setResultType('unknown');\n }\n }\n\n #setResultType(resultType: ResultType, error?: ErroredQuery) {\n this.#resultType = resultType;\n this.#error = error;\n // A dirty view is mid-transaction: rows were pushed and not yet flushed,\n // and the objects in #txnDirty are still mutable. Firing now would hand\n // those to listeners and then fire again at flush() with the same data, so\n // let the pending flush deliver the new result type instead.\n // A held view is waiting to be exposed together with others at the next\n // flush; that goes for its result type as much as for its rows.\n if (this.#held) {\n // Dirty so that the flush notifies even when no rows were pushed.\n this.#dirty = true;\n } else if (!this.#dirty) {\n this.#fireListeners();\n }\n }\n}\n"],"mappings":";;;;;AAcA,SAAS,mBAAmB,QAA4B;CACtD,QAAQ,OAAO,IAAf;EACE,KAAK,GACH,OAAO;GAAC,MAAM;GAAO,MAAM,OAAO;EAAiB;EACrD,KAAK,GACH,OAAO;GAAC,MAAM;GAAU,MAAM,OAAO;EAAiB;EACxD,KAAK,GACH,OAAO;GACL,MAAM;GACN,MAAM,OAAO;GACb,OAAO;IACL,kBAAkB,OAAO,GAAwB;IACjD,QAAQ,mBAAmB,OAAO,GAAwB,MAAM;GAClE;EACF;EACF,KAAK,GACH,OAAO;GACL,MAAM;GACN,MAAM,OAAO;GACb,SAAS,OAAO;EAClB;CACJ;AACF;;;;;;;;;;;;AAaA,IAAa,YAAb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,QAAQ,WAAW,KAAKd,OAAO,MAAM,CAAC,CAAC,CAAC,GACjD,KAAKI,QAAQ,YACX,KAAKA,OACL;GAAC,MAAM;GAAO;EAAI,GAClB,KAAKW,WAAW,GAChB,IACA,KAAKb,SACL,OACA,IAIF;EAEF,KAAK,MAAM;CACb;CAEA,KAAK,QAAgB;EACnB,KAAKY,SAAS;EACd,KAAKV,QAAQ,YACX,KAAKA,OACL,mBAAmB,MAAM,GACzB,KAAKW,WAAW,GAChB,IACA,KAAKb,SACL,OACA,KAAKc,SACP;EACA,OAAO;CACT;;;;;;;;;;;;CAaA,WAAiB;EACf,KAAKP,iBAAiB,KAAKL;EAC3B,KAAKa,QAAQ;EACb,KAAKL,kBAAkB,KAAKP;EAC5B,KAAKQ,aAAa,KAAKP;CACzB;;;;;;;CAQA,cAAoB;EAClB,KAAKG,iBAAiB,KAAA;CACxB;CAEA,QAAQ;EACN,KAAKA,iBAAiB,KAAA;EACtB,KAAKQ,QAAQ;EACb,IAAI,CAAC,KAAKH,QACR;EAEF,KAAKA,SAAS;EACd,KAAKI,eAAe;EAIpB,KAAKF,4BAAY,IAAI,QAAQ;CAC/B;CAEA,UAAU,KAAU;EAClB,KAAKb,WAAW,GAAG;CACrB;;;;;;;;CASA,aAAmB;EACjB,IAAI,KAAKE,gBAAgB,WACvB,KAAKE,eAAe,QAAQ;CAEhC;;CAGA,eAAqB;EACnB,IAAI,KAAKF,gBAAgB,UACvB,KAAKE,eAAe,SAAS;CAEjC;CAEA,eAAe,YAAwB,OAAsB;EAC3D,KAAKF,cAAc;EACnB,KAAKC,SAAS;EAOd,IAAI,KAAKW,OAEP,KAAKH,SAAS;OACT,IAAI,CAAC,KAAKA,QACf,KAAKI,eAAe;CAExB;AACF"}
|
|
1
|
+
{"version":3,"file":"array-view.js","names":["#input","#listeners","#format","#updateTTL","#root","#resultType","#error","#setResultType","#hydrate","#committedRoot","#schema","#listenerArgs","#heldResultType","#heldError","#dirty","#getSchema","#txnDirty","#held","#fireListeners"],"sources":["../../../../../zql/src/ivm/array-view.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {Immutable} from '../../../shared/src/immutable.ts';\nimport {emptyArray} from '../../../shared/src/sentinels.ts';\nimport type {ErroredQuery} from '../../../zero-protocol/src/custom-queries.ts';\nimport type {TTL} from '../query/ttl.ts';\nimport type {Listener, ResultType, TypedView} from '../query/typed-view.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport type {Change} from './change.ts';\nimport {skipYields, type Input, type Output} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {applyChange, type ViewChange} from './view-apply-change.ts';\nimport type {Entry, Format, View} from './view.ts';\n\nfunction changeToViewChange(change: Change): ViewChange {\n switch (change[ChangeIndex.TYPE]) {\n case ChangeType.ADD:\n return {type: 'add', node: change[ChangeIndex.NODE]};\n case ChangeType.REMOVE:\n return {type: 'remove', node: change[ChangeIndex.NODE]};\n case ChangeType.CHILD:\n return {\n type: 'child',\n node: change[ChangeIndex.NODE],\n child: {\n relationshipName: change[ChangeIndex.CHILD_DATA].relationshipName,\n change: changeToViewChange(change[ChangeIndex.CHILD_DATA].change),\n },\n };\n case ChangeType.EDIT:\n return {\n type: 'edit',\n node: change[ChangeIndex.NODE],\n oldNode: change[ChangeIndex.OLD_NODE],\n };\n }\n}\n\n/**\n * Implements a materialized view of the output of an operator.\n *\n * It might seem more efficient to use an immutable b-tree for the\n * materialization, but it's not so clear. Inserts in the middle are\n * asymptotically slower in an array, but can often be done with zero\n * allocations, where changes to the b-tree will often require several allocs.\n *\n * Also the plain array view is more convenient for consumers since you can dump\n * it into console to see what it is, rather than having to iterate it.\n */\nexport class ArrayView<V extends View> implements Output, TypedView<V> {\n readonly #input: Input;\n readonly #listeners = new Set<Listener<V>>();\n // Read lazily: a DeferredInput has no schema until its pipeline is attached,\n // and the schema is only needed once there is a change to apply.\n #schema: SourceSchema | undefined;\n readonly #format: Format;\n\n // Synthetic \"root\" entry that has a single \"\" relationship, so that we can\n // treat all changes, including the root change, generically.\n //\n // applyChange is immutable: it returns a new root, preserving the references\n // of unchanged subtrees so consumers (React.memo / Solid) can skip them. We\n // therefore reassign #root on every change rather than mutating in place.\n #root: Entry;\n\n onDestroy: (() => void) | undefined;\n\n #dirty = false;\n // Set by holdData(): the root that `data` and newly added listeners keep\n // seeing until releaseData() or the next flush, while pushes build up #root\n // behind it.\n #committedRoot: Entry | undefined;\n // From holdData() until the next flush. Outlasts #committedRoot, which\n // releaseData() drops first.\n #held = false;\n // The result type and error as of holdData(): what a listener added while\n // held is called with, so it never sees old rows paired with a new type.\n #heldResultType: ResultType = 'unknown';\n #heldError: ErroredQuery | undefined;\n #resultType: ResultType = 'unknown';\n #error: ErroredQuery | undefined;\n readonly #updateTTL: (ttl: TTL) => void;\n\n // Objects/arrays created or cloned during the current (un-flushed)\n // transaction. applyChange may mutate these in place rather than copying\n // again, since they are not yet observed by any listener. Replaced at\n // flush(), after which the committed snapshot must be copied-on-write again.\n // A WeakSet (not a Set) so it never extends the lifetime of transient clones.\n #txnDirty: WeakSet<object> = new WeakSet();\n\n constructor(\n input: Input,\n format: Format,\n queryComplete: true | ErroredQuery | Promise<true>,\n updateTTL: (ttl: TTL) => void,\n ) {\n this.#input = input;\n this.#format = format;\n this.#updateTTL = updateTTL;\n this.#root = {'': format.singular ? undefined : []};\n input.setOutput(this);\n\n if (queryComplete === true) {\n this.#resultType = 'complete';\n } else if ('error' in queryComplete) {\n this.#resultType = 'error';\n this.#error = queryComplete;\n } else {\n void queryComplete\n .then(() => this.#setResultType('complete'))\n .catch(e => this.#setResultType('error', e));\n }\n this.#hydrate();\n }\n\n get data() {\n return (this.#committedRoot ?? this.#root)[''] as V;\n }\n\n #getSchema(): SourceSchema {\n return (this.#schema ??= this.#input.getSchema());\n }\n\n addListener(listener: Listener<V>) {\n assert(!this.#listeners.has(listener), 'Listener already registered');\n this.#listeners.add(listener);\n\n listener(...this.#listenerArgs());\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #fireListeners() {\n // Read the snapshot once: a listener may push() synchronously, and the\n // listeners after it must not be handed the root that push is building,\n // which the rest of the transaction would then mutate in place.\n const args = this.#listenerArgs();\n for (const listener of this.#listeners) {\n listener(...args);\n }\n }\n\n #listenerArgs(): Parameters<Listener<V>> {\n if (this.#committedRoot !== undefined) {\n // Held rows go with the held type; after releaseData() both are current.\n return [this.data as Immutable<V>, this.#heldResultType, this.#heldError];\n }\n return [this.data as Immutable<V>, this.#resultType, this.#error];\n }\n\n destroy() {\n this.onDestroy?.();\n }\n\n #hydrate() {\n this.#dirty = true;\n for (const node of skipYields(this.#input.fetch({}))) {\n this.#root = applyChange(\n this.#root,\n {type: 'add', node},\n this.#getSchema(),\n '',\n this.#format,\n false /* withIDs */,\n true /* mutate: #root is freshly created and not yet observed by any\n consumer, so build it in place to avoid O(N^2) array copies.\n Every later push() is immutable, preserving reference\n stability for unchanged subtrees. */,\n );\n }\n this.flush();\n }\n\n push(change: Change) {\n const newRoot = applyChange(\n this.#root,\n changeToViewChange(change),\n this.#getSchema(),\n '',\n this.#format,\n false /* withIDs */,\n this.#txnDirty /* mutate: copy-on-write within this transaction */,\n );\n // applyChange returns the same root when the change did not affect the\n // view — e.g. a child change for a relationship that is not in the format,\n // such as a whereExists subquery (zsubq_*). Only mark dirty when the root\n // actually changed so flush() does not notify listeners with identical\n // data. Within a transaction the root keeps its reference across a *real*\n // change only if an earlier change in the same transaction already cloned\n // it (copy-on-write) — and that earlier change set #dirty, so an unchanged\n // reference here never hides a real change.\n if (newRoot !== this.#root) {\n this.#root = newRoot;\n this.#dirty = true;\n }\n return emptyArray;\n }\n\n /**\n * Keep exposing the current snapshot, whatever is pushed in the meantime,\n * until {@link releaseData} or the next {@link flush}. Result type\n * notifications are held back until that flush.\n *\n * A transaction is normally one synchronous task, so nobody can look at a\n * view between its pushes and its flush. Deferred pipelines are different:\n * they are hydrated over several tasks and flushed together (see\n * `QueryDelegate.onPipelinesReady`), and a view that already has its rows\n * must not show them early.\n */\n holdData(): void {\n this.#committedRoot = this.#root;\n this.#held = true;\n this.#heldResultType = this.#resultType;\n this.#heldError = this.#error;\n }\n\n /**\n * Make `data` current again without notifying anyone yet; listeners are\n * still only called by the next {@link flush}. Views released together get\n * this called on all of them before any is flushed, so a listener of one\n * that reads another sees its rows too.\n */\n releaseData(): void {\n this.#committedRoot = undefined;\n }\n\n flush() {\n this.#committedRoot = undefined;\n this.#held = false;\n if (!this.#dirty) {\n return;\n }\n this.#dirty = false;\n // The snapshot about to be handed to listeners becomes observed; the next\n // transaction must copy-on-write rather than mutate these objects. A fresh\n // WeakSet drops all \"owned\" marks (WeakSet has no clear()).\n //\n // Reset BEFORE notifying: a listener may throw (swallowed by\n // ZeroContext#endTransaction) or re-enter push(). If the committed root\n // kept its \"owned\" marks, a later transaction would mutate it in place and\n // return an identical reference — which push() would read as \"no change\",\n // permanently silencing the view.\n this.#txnDirty = new WeakSet();\n this.#fireListeners();\n }\n\n updateTTL(ttl: TTL) {\n this.#updateTTL(ttl);\n }\n\n /**\n * The store holds the server-confirmed complete result of this query from a\n * previous sync (the persisted got-queries key exists, pre-authoritative).\n * Never downgrades 'complete'/'error', and never resolves anything that\n * waits on 'complete' — freshness stays a promise only the connection can\n * keep.\n */\n markCached(): void {\n if (this.#resultType === 'unknown') {\n this.#setResultType('cached');\n }\n }\n\n /** The got key was deleted (eviction) while still pre-authoritative. */\n unmarkCached(): void {\n if (this.#resultType === 'cached') {\n this.#setResultType('unknown');\n }\n }\n\n #setResultType(resultType: ResultType, error?: ErroredQuery) {\n this.#resultType = resultType;\n this.#error = error;\n // A dirty view is mid-transaction: rows were pushed and not yet flushed,\n // and the objects in #txnDirty are still mutable. Firing now would hand\n // those to listeners and then fire again at flush() with the same data, so\n // let the pending flush deliver the new result type instead.\n // A held view is waiting to be exposed together with others at the next\n // flush; that goes for its result type as much as for its rows.\n if (this.#held) {\n // Dirty so that the flush notifies even when no rows were pushed.\n this.#dirty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KA,SAAS;EAUd,KAAKE,4BAAY,IAAI,QAAQ;EAC7B,KAAKE,eAAe;CACtB;CAEA,UAAU,KAAU;EAClB,KAAKf,WAAW,GAAG;CACrB;;;;;;;;CASA,aAAmB;EACjB,IAAI,KAAKE,gBAAgB,WACvB,KAAKE,eAAe,QAAQ;CAEhC;;CAGA,eAAqB;EACnB,IAAI,KAAKF,gBAAgB,UACvB,KAAKE,eAAe,SAAS;CAEjC;CAEA,eAAe,YAAwB,OAAsB;EAC3D,KAAKF,cAAc;EACnB,KAAKC,SAAS;EAOd,IAAI,KAAKW,OAEP,KAAKH,SAAS;OACT,IAAI,CAAC,KAAKA,QACf,KAAKI,eAAe;CAExB;AACF"}
|
package/package.json
CHANGED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import type { LogContext } from '@rocicorp/logger';
|
|
2
|
-
import type { Source } from '../../types/streams.ts';
|
|
3
|
-
import type { BackedUpWatermark } from './backup-monitor.ts';
|
|
4
|
-
export type VfsPollerConfig = {
|
|
5
|
-
executable: string;
|
|
6
|
-
remotePollIntervalMs: number;
|
|
7
|
-
remoteQueryTimeoutMs?: number;
|
|
8
|
-
backupURL: string;
|
|
9
|
-
region?: string | undefined;
|
|
10
|
-
endpoint?: string | undefined;
|
|
11
|
-
logLevel?: string;
|
|
12
|
-
logFormat?: string;
|
|
13
|
-
};
|
|
14
|
-
/**
|
|
15
|
-
* Returns the GOMEMLIMIT for a vfs-query process watching a replica of
|
|
16
|
-
* `pageCount` pages.
|
|
17
|
-
*/
|
|
18
|
-
export declare function vfsQueryMemoryLimitBytes(pageCount: number): number;
|
|
19
|
-
export declare class VfsWatermarkPoller {
|
|
20
|
-
#private;
|
|
21
|
-
constructor(lc: LogContext, replicaFile: string, pollerConfig: VfsPollerConfig);
|
|
22
|
-
/**
|
|
23
|
-
* Starts polling for watermarks and pushes new ones to returned stream.
|
|
24
|
-
* Must only be called once.
|
|
25
|
-
*/
|
|
26
|
-
start(): Source<BackedUpWatermark>;
|
|
27
|
-
readonly checkLocalWatermark: () => void;
|
|
28
|
-
}
|
|
29
|
-
export declare function buildLitestreamVfsReplicaURL({ backupURL, endpoint, region, }: {
|
|
30
|
-
readonly backupURL: string;
|
|
31
|
-
readonly endpoint?: string | undefined;
|
|
32
|
-
readonly region?: string | undefined;
|
|
33
|
-
}): string;
|
|
34
|
-
//# sourceMappingURL=vfs-watermark-poller.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"vfs-watermark-poller.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/change-streamer/vfs-watermark-poller.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAIjD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,wBAAwB,CAAC;AAGnD,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,qBAAqB,CAAC;AAe3D,MAAM,MAAM,eAAe,GAAG;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AAqCF;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAKlE;AAED,qBAAa,kBAAkB;;IAmB7B,YACE,EAAE,EAAE,UAAU,EACd,WAAW,EAAE,MAAM,EACnB,YAAY,EAAE,eAAe,EAwB9B;IAED;;;OAGG;IACH,KAAK,IAAI,MAAM,CAAC,iBAAiB,CAAC,CASjC;IAGD,QAAQ,CAAC,mBAAmB,aAiB1B;CAwIH;AAED,wBAAgB,4BAA4B,CAAC,EAC3C,SAAS,EACT,QAAQ,EACR,MAAM,GACP,EAAE;IACD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACvC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACtC,GAAG,MAAM,CAiBT"}
|