@rocicorp/zero 1.6.0-canary.12 → 1.6.0-canary.13
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/README.md +3 -28
- package/out/_virtual/{_@oxc-project_runtime@0.130.0 → _@oxc-project_runtime@0.122.0}/helpers/usingCtx.js +1 -1
- package/out/analyze-query/src/analyze-cli.js +3 -3
- package/out/analyze-query/src/analyze-cli.js.map +1 -1
- package/out/analyze-query/src/bin-analyze.js +1 -6
- package/out/analyze-query/src/bin-analyze.js.map +1 -1
- package/out/analyze-query/src/bin-transform.js.map +1 -1
- package/out/ast-to-zql/src/ast-to-zql.js.map +1 -1
- package/out/ast-to-zql/src/bin.js.map +1 -1
- package/out/ast-to-zql/src/format.js.map +1 -1
- package/out/datadog/src/datadog-log-sink.js.map +1 -1
- package/out/otel/src/enabled.js.map +1 -1
- package/out/otel/src/log-options.js.map +1 -1
- package/out/otel/src/maybe-time.js.map +1 -1
- package/out/otel/src/span.js.map +1 -1
- package/out/replicache/src/async-iterable-to-array.js.map +1 -1
- package/out/replicache/src/bg-interval.js.map +1 -1
- package/out/replicache/src/btree/diff.js.map +1 -1
- package/out/replicache/src/btree/node.js.map +1 -1
- package/out/replicache/src/btree/read.js.map +1 -1
- package/out/replicache/src/btree/splice.js.map +1 -1
- package/out/replicache/src/btree/write.js +3 -6
- package/out/replicache/src/btree/write.js.map +1 -1
- package/out/replicache/src/call-default-fetch.js.map +1 -1
- package/out/replicache/src/connection-loop-delegates.js.map +1 -1
- package/out/replicache/src/connection-loop.js.map +1 -1
- package/out/replicache/src/cookies.js.map +1 -1
- package/out/replicache/src/dag/chunk.js.map +1 -1
- package/out/replicache/src/dag/gc.js.map +1 -1
- package/out/replicache/src/dag/key.js.map +1 -1
- package/out/replicache/src/dag/lazy-store.js.map +1 -1
- package/out/replicache/src/dag/store-impl.js.map +1 -1
- package/out/replicache/src/dag/store.js.map +1 -1
- package/out/replicache/src/dag/visitor.js.map +1 -1
- package/out/replicache/src/db/commit.js.map +1 -1
- package/out/replicache/src/db/index.js.map +1 -1
- package/out/replicache/src/db/read.js.map +1 -1
- package/out/replicache/src/db/rebase.js.map +1 -1
- package/out/replicache/src/db/write.js.map +1 -1
- package/out/replicache/src/deleted-clients.js.map +1 -1
- package/out/replicache/src/error-responses.js.map +1 -1
- package/out/replicache/src/frozen-json.js.map +1 -1
- package/out/replicache/src/get-default-puller.js.map +1 -1
- package/out/replicache/src/get-default-pusher.js.map +1 -1
- package/out/replicache/src/get-kv-store-provider.js.map +1 -1
- package/out/replicache/src/hash.js.map +1 -1
- package/out/replicache/src/http-request-info.js.map +1 -1
- package/out/replicache/src/index-defs.js.map +1 -1
- package/out/replicache/src/kv/expo-sqlite/store.js.map +1 -1
- package/out/replicache/src/kv/idb-store-with-mem-fallback.js.map +1 -1
- package/out/replicache/src/kv/idb-store.js.map +1 -1
- package/out/replicache/src/kv/mem-store.js.map +1 -1
- package/out/replicache/src/kv/op-sqlite/store.js.map +1 -1
- package/out/replicache/src/kv/read-impl.js.map +1 -1
- package/out/replicache/src/kv/sqlite-store.d.ts.map +1 -1
- package/out/replicache/src/kv/sqlite-store.js +1 -4
- package/out/replicache/src/kv/sqlite-store.js.map +1 -1
- package/out/replicache/src/kv/throw-if-closed.js.map +1 -1
- package/out/replicache/src/kv/write-impl-base.js.map +1 -1
- package/out/replicache/src/kv/write-impl.js.map +1 -1
- package/out/replicache/src/lazy.js.map +1 -1
- package/out/replicache/src/log-options.js.map +1 -1
- package/out/replicache/src/make-idb-name.js.map +1 -1
- package/out/replicache/src/new-client-channel.js.map +1 -1
- package/out/replicache/src/on-persist-channel.js.map +1 -1
- package/out/replicache/src/patch-operation.js.map +1 -1
- package/out/replicache/src/pending-mutations.js.map +1 -1
- package/out/replicache/src/persist/client-gc.js.map +1 -1
- package/out/replicache/src/persist/client-group-gc.js.map +1 -1
- package/out/replicache/src/persist/client-groups.js +0 -40
- package/out/replicache/src/persist/client-groups.js.map +1 -1
- package/out/replicache/src/persist/clients.js +0 -28
- package/out/replicache/src/persist/clients.js.map +1 -1
- package/out/replicache/src/persist/collect-idb-databases.js.map +1 -1
- package/out/replicache/src/persist/gather-mem-only-visitor.js.map +1 -1
- package/out/replicache/src/persist/gather-not-cached-visitor.js.map +1 -1
- package/out/replicache/src/persist/heartbeat.js.map +1 -1
- package/out/replicache/src/persist/idb-databases-store-db-name.js.map +1 -1
- package/out/replicache/src/persist/idb-databases-store.js.map +1 -1
- package/out/replicache/src/persist/make-client-id.js.map +1 -1
- package/out/replicache/src/persist/persist.js.map +1 -1
- package/out/replicache/src/persist/refresh.js.map +1 -1
- package/out/replicache/src/process-scheduler.js.map +1 -1
- package/out/replicache/src/pusher.js.map +1 -1
- package/out/replicache/src/replicache-impl.js.map +1 -1
- package/out/replicache/src/report-error.js.map +1 -1
- package/out/replicache/src/request-idle.js.map +1 -1
- package/out/replicache/src/scan-iterator.js.map +1 -1
- package/out/replicache/src/scan-options.js.map +1 -1
- package/out/replicache/src/set-interval-with-signal.js.map +1 -1
- package/out/replicache/src/subscriptions.js.map +1 -1
- package/out/replicache/src/sync/diff.js.map +1 -1
- package/out/replicache/src/sync/ids.js.map +1 -1
- package/out/replicache/src/sync/patch.js.map +1 -1
- package/out/replicache/src/sync/pull-error.js.map +1 -1
- package/out/replicache/src/sync/pull.js.map +1 -1
- package/out/replicache/src/sync/push.js.map +1 -1
- package/out/replicache/src/sync/request-id.js.map +1 -1
- package/out/replicache/src/to-error.js.map +1 -1
- package/out/replicache/src/transaction-closed-error.js.map +1 -1
- package/out/replicache/src/transactions.js.map +1 -1
- package/out/replicache/src/with-transactions.js.map +1 -1
- package/out/shared/src/abort-error.js.map +1 -1
- package/out/shared/src/arrays.js.map +1 -1
- package/out/shared/src/asserts.js.map +1 -1
- package/out/shared/src/bigint-json.js.map +1 -1
- package/out/shared/src/binary-search.js.map +1 -1
- package/out/shared/src/broadcast-channel.js.map +1 -1
- package/out/shared/src/browser-env.js.map +1 -1
- package/out/shared/src/btree-set.js.map +1 -1
- package/out/shared/src/cache.js.map +1 -1
- package/out/shared/src/centroid.js.map +1 -1
- package/out/shared/src/custom-key-map.js.map +1 -1
- package/out/shared/src/custom-key-set.js.map +1 -1
- package/out/shared/src/deep-clone.js.map +1 -1
- package/out/shared/src/deep-merge.js.map +1 -1
- package/out/shared/src/document-visible.js.map +1 -1
- package/out/shared/src/dotenv.js.map +1 -1
- package/out/shared/src/error.js.map +1 -1
- package/out/shared/src/hash.js.map +1 -1
- package/out/shared/src/iterables.d.ts +0 -2
- package/out/shared/src/iterables.d.ts.map +1 -1
- package/out/shared/src/iterables.js +1 -9
- package/out/shared/src/iterables.js.map +1 -1
- package/out/shared/src/json-schema.js.map +1 -1
- package/out/shared/src/json.js.map +1 -1
- package/out/shared/src/logging-test-utils.js.map +1 -1
- package/out/shared/src/logging.js.map +1 -1
- package/out/shared/src/map.js.map +1 -1
- package/out/shared/src/must.js.map +1 -1
- package/out/shared/src/object-traversal.js.map +1 -1
- package/out/shared/src/objects.js.map +1 -1
- package/out/shared/src/options.js.map +1 -1
- package/out/shared/src/parse-big-int.js.map +1 -1
- package/out/shared/src/promise-race.js.map +1 -1
- package/out/shared/src/queue.d.ts.map +1 -1
- package/out/shared/src/queue.js +21 -15
- package/out/shared/src/queue.js.map +1 -1
- package/out/shared/src/rand.js.map +1 -1
- package/out/shared/src/random-uint64.js.map +1 -1
- package/out/shared/src/random-values.js.map +1 -1
- package/out/shared/src/record-proxy.js.map +1 -1
- package/out/shared/src/resolved-promises.js.map +1 -1
- package/out/shared/src/sentinels.js.map +1 -1
- package/out/shared/src/set-utils.js.map +1 -1
- package/out/shared/src/size-of-value.js.map +1 -1
- package/out/shared/src/sleep.js.map +1 -1
- package/out/shared/src/sorted-entries.js.map +1 -1
- package/out/shared/src/string-compare.js.map +1 -1
- package/out/shared/src/subscribable.js.map +1 -1
- package/out/shared/src/tdigest-schema.js.map +1 -1
- package/out/shared/src/tdigest.js.map +1 -1
- package/out/shared/src/valita.js.map +1 -1
- package/out/z2s/src/compiler.js.map +1 -1
- package/out/z2s/src/sql.js.map +1 -1
- package/out/zero/package.js +26 -34
- package/out/zero/package.js.map +1 -1
- package/out/zero/src/build-schema.js.map +1 -1
- package/out/zero/src/zero-cache-dev.js.map +1 -1
- package/out/zero/src/zero-out.js.map +1 -1
- package/out/zero-cache/src/auth/auth.js.map +1 -1
- package/out/zero-cache/src/auth/jwt.js.map +1 -1
- package/out/zero-cache/src/auth/load-permissions.js.map +1 -1
- package/out/zero-cache/src/auth/read-authorizer.js.map +1 -1
- package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
- package/out/zero-cache/src/config/network.js.map +1 -1
- package/out/zero-cache/src/config/normalize.js.map +1 -1
- package/out/zero-cache/src/config/server-context.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +0 -5
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/custom/fetch.js.map +1 -1
- package/out/zero-cache/src/custom-queries/transform-query.js.map +1 -1
- package/out/zero-cache/src/db/create.js.map +1 -1
- package/out/zero-cache/src/db/delete-lite-db.js.map +1 -1
- package/out/zero-cache/src/db/lite-tables.js.map +1 -1
- package/out/zero-cache/src/db/migration-lite.js +0 -19
- package/out/zero-cache/src/db/migration-lite.js.map +1 -1
- package/out/zero-cache/src/db/migration.js +0 -19
- package/out/zero-cache/src/db/migration.js.map +1 -1
- package/out/zero-cache/src/db/pg-copy-binary.js.map +1 -1
- package/out/zero-cache/src/db/pg-copy.js.map +1 -1
- package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
- package/out/zero-cache/src/db/pg-type-parser.js.map +1 -1
- package/out/zero-cache/src/db/run-transaction.js.map +1 -1
- package/out/zero-cache/src/db/specs.js.map +1 -1
- package/out/zero-cache/src/db/statements.js.map +1 -1
- package/out/zero-cache/src/db/transaction-pool.js.map +1 -1
- package/out/zero-cache/src/db/warmup.js.map +1 -1
- package/out/zero-cache/src/observability/events.js.map +1 -1
- package/out/zero-cache/src/observability/metrics.js.map +1 -1
- package/out/zero-cache/src/scripts/decommission.js.map +1 -1
- package/out/zero-cache/src/scripts/deploy-permissions.js.map +1 -1
- package/out/zero-cache/src/scripts/permissions.d.ts.map +1 -1
- package/out/zero-cache/src/scripts/permissions.js +2 -1
- package/out/zero-cache/src/scripts/permissions.js.map +1 -1
- package/out/zero-cache/src/server/anonymous-otel-start.js +7 -8
- package/out/zero-cache/src/server/anonymous-otel-start.js.map +1 -1
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/server/inspector-delegate.js.map +1 -1
- package/out/zero-cache/src/server/logging.js.map +1 -1
- package/out/zero-cache/src/server/main.js.map +1 -1
- package/out/zero-cache/src/server/mutator.js.map +1 -1
- package/out/zero-cache/src/server/otel-diag-logger.js.map +1 -1
- package/out/zero-cache/src/server/otel-log-sink.js.map +1 -1
- package/out/zero-cache/src/server/otel-start.js.map +1 -1
- package/out/zero-cache/src/server/priority-op.js.map +1 -1
- package/out/zero-cache/src/server/reaper.js.map +1 -1
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/server/runner/main.js.map +1 -1
- package/out/zero-cache/src/server/runner/run-worker.js.map +1 -1
- package/out/zero-cache/src/server/runner/runtime.js.map +1 -1
- package/out/zero-cache/src/server/runner/zero-dispatcher.js.map +1 -1
- package/out/zero-cache/src/server/shadow-syncer.js.map +1 -1
- package/out/zero-cache/src/server/syncer.js.map +1 -1
- package/out/zero-cache/src/server/worker-dispatcher.js.map +1 -1
- package/out/zero-cache/src/server/worker-urls.js.map +1 -1
- package/out/zero-cache/src/services/analyze.d.ts.map +1 -1
- package/out/zero-cache/src/services/analyze.js +2 -5
- package/out/zero-cache/src/services/analyze.js.map +1 -1
- package/out/zero-cache/src/services/change-source/common/backfill-manager.js.map +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-schema.js.map +1 -1
- package/out/zero-cache/src/services/change-source/custom/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/backfill-metadata.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.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/decommission.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/binary-reader.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/pgoutput-parser.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/lsn.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/control.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/data.js +0 -2
- package/out/zero-cache/src/services/change-source/protocol/current/data.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/downstream.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/json.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/status.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/current/upstream.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backup-monitor.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/broadcast.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/forwarder.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/replica-monitor.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/schema/init.js +25 -21
- package/out/zero-cache/src/services/change-streamer/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/schema/tables.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot.js +0 -15
- package/out/zero-cache/src/services/change-streamer/snapshot.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/subscriber.js.map +1 -1
- package/out/zero-cache/src/services/heapz.js.map +1 -1
- package/out/zero-cache/src/services/http-service.js.map +1 -1
- package/out/zero-cache/src/services/life-cycle.js.map +1 -1
- package/out/zero-cache/src/services/limiter/sliding-window-limiter.js.map +1 -1
- package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/error.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/pusher.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
- package/out/zero-cache/src/services/replicator/notifier.js.map +1 -1
- package/out/zero-cache/src/services/replicator/replication-status.js.map +1 -1
- package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/recorder.js.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/report-schema.js.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/change-log.js.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/column-metadata.js.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/replication-state.js.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/table-metadata.js.map +1 -1
- package/out/zero-cache/src/services/replicator/write-worker-client.js.map +1 -1
- package/out/zero-cache/src/services/replicator/write-worker.js.map +1 -1
- package/out/zero-cache/src/services/run-ast.d.ts.map +1 -1
- package/out/zero-cache/src/services/run-ast.js +0 -1
- package/out/zero-cache/src/services/run-ast.js.map +1 -1
- package/out/zero-cache/src/services/runner.js.map +1 -1
- package/out/zero-cache/src/services/running-state.js.map +1 -1
- package/out/zero-cache/src/services/shadow-sync/shadow-sync-service.js.map +1 -1
- package/out/zero-cache/src/services/statz.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/active-users-gauge.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/client-handler.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/client-schema.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/connection-context-manager.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-purger.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-purger.js +1 -2
- package/out/zero-cache/src/services/view-syncer/cvr-purger.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.js +1 -2
- package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/drain-coordinator.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts +14 -0
- package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/inspect-handler.js +25 -2
- package/out/zero-cache/src/services/view-syncer/inspect-handler.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/row-record-cache.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/row-set-signature.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/schema/cvr.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/schema/init.js +113 -97
- package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/schema/types.js +1 -103
- package/out/zero-cache/src/services/view-syncer/schema/types.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/tracer.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/ttl-clock.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +1 -4
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/types/configuration-error.js.map +1 -1
- package/out/zero-cache/src/types/error-with-level.js.map +1 -1
- package/out/zero-cache/src/types/http.js.map +1 -1
- package/out/zero-cache/src/types/lexi-version.js.map +1 -1
- package/out/zero-cache/src/types/lite.js.map +1 -1
- package/out/zero-cache/src/types/names.js.map +1 -1
- package/out/zero-cache/src/types/pg-data-type.js.map +1 -1
- package/out/zero-cache/src/types/pg.js.map +1 -1
- package/out/zero-cache/src/types/processes.js.map +1 -1
- package/out/zero-cache/src/types/profiler.js.map +1 -1
- package/out/zero-cache/src/types/row-key.js.map +1 -1
- package/out/zero-cache/src/types/shards.js.map +1 -1
- package/out/zero-cache/src/types/sql.js.map +1 -1
- package/out/zero-cache/src/types/state-version.js.map +1 -1
- package/out/zero-cache/src/types/streams.js.map +1 -1
- package/out/zero-cache/src/types/strings.js.map +1 -1
- package/out/zero-cache/src/types/subscription.js.map +1 -1
- package/out/zero-cache/src/types/timeout.js.map +1 -1
- package/out/zero-cache/src/types/url-params.js.map +1 -1
- package/out/zero-cache/src/types/websocket-handoff.js.map +1 -1
- package/out/zero-cache/src/types/ws.js.map +1 -1
- package/out/zero-cache/src/workers/connect-params.js.map +1 -1
- package/out/zero-cache/src/workers/connection.js.map +1 -1
- package/out/zero-cache/src/workers/mutator.js.map +1 -1
- package/out/zero-cache/src/workers/replicator.js.map +1 -1
- package/out/zero-cache/src/workers/syncer-ws-message-handler.js.map +1 -1
- package/out/zero-cache/src/workers/syncer.js.map +1 -1
- package/out/zero-client/src/client/active-clients-manager.js.map +1 -1
- package/out/zero-client/src/client/connection-manager.js +1 -2
- package/out/zero-client/src/client/connection-manager.js.map +1 -1
- package/out/zero-client/src/client/connection.js.map +1 -1
- package/out/zero-client/src/client/context.js.map +1 -1
- package/out/zero-client/src/client/crud-impl.js.map +1 -1
- package/out/zero-client/src/client/crud.js.map +1 -1
- package/out/zero-client/src/client/custom.js +1 -2
- package/out/zero-client/src/client/custom.js.map +1 -1
- package/out/zero-client/src/client/delete-clients-manager.js.map +1 -1
- package/out/zero-client/src/client/enable-analytics.js.map +1 -1
- package/out/zero-client/src/client/error.js.map +1 -1
- package/out/zero-client/src/client/http-string.js.map +1 -1
- package/out/zero-client/src/client/inspector/client-group.js.map +1 -1
- package/out/zero-client/src/client/inspector/client.js.map +1 -1
- package/out/zero-client/src/client/inspector/html-dialog-prompt.js.map +1 -1
- package/out/zero-client/src/client/inspector/inspector.js.map +1 -1
- package/out/zero-client/src/client/inspector/lazy-inspector.js.map +1 -1
- package/out/zero-client/src/client/inspector/query.js.map +1 -1
- package/out/zero-client/src/client/ivm-branch.js.map +1 -1
- package/out/zero-client/src/client/keys.js.map +1 -1
- package/out/zero-client/src/client/log-options.js.map +1 -1
- package/out/zero-client/src/client/make-mutate-property.js.map +1 -1
- package/out/zero-client/src/client/make-replicache-mutators.js.map +1 -1
- package/out/zero-client/src/client/metrics.js.map +1 -1
- package/out/zero-client/src/client/mutation-tracker.js.map +1 -1
- package/out/zero-client/src/client/mutator-proxy.js.map +1 -1
- package/out/zero-client/src/client/options.js.map +1 -1
- package/out/zero-client/src/client/query-manager.js.map +1 -1
- package/out/zero-client/src/client/reload-error-handler.js.map +1 -1
- package/out/zero-client/src/client/server-option.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero-poke-handler.js.map +1 -1
- package/out/zero-client/src/client/zero-rep.js.map +1 -1
- package/out/zero-client/src/client/zero.d.ts.map +1 -1
- package/out/zero-client/src/client/zero.js +32 -58
- package/out/zero-client/src/client/zero.js.map +1 -1
- package/out/zero-client/src/util/nanoid.js.map +1 -1
- package/out/zero-client/src/util/socket.d.ts +3 -0
- package/out/zero-client/src/util/socket.d.ts.map +1 -0
- package/out/zero-client/src/util/socket.js +8 -0
- package/out/zero-client/src/util/socket.js.map +1 -0
- package/out/zero-protocol/src/analyze-query-result.js +0 -3
- package/out/zero-protocol/src/analyze-query-result.js.map +1 -1
- package/out/zero-protocol/src/application-error.js.map +1 -1
- package/out/zero-protocol/src/ast.js.map +1 -1
- package/out/zero-protocol/src/change-desired-queries.js +0 -1
- package/out/zero-protocol/src/change-desired-queries.js.map +1 -1
- package/out/zero-protocol/src/client-schema.js.map +1 -1
- package/out/zero-protocol/src/close-connection.js.map +1 -1
- package/out/zero-protocol/src/connect.js +0 -7
- package/out/zero-protocol/src/connect.js.map +1 -1
- package/out/zero-protocol/src/custom-queries.js.map +1 -1
- package/out/zero-protocol/src/data.js.map +1 -1
- package/out/zero-protocol/src/delete-clients.js.map +1 -1
- package/out/zero-protocol/src/down.js.map +1 -1
- package/out/zero-protocol/src/error.js +0 -7
- package/out/zero-protocol/src/error.js.map +1 -1
- package/out/zero-protocol/src/inspect-down.js.map +1 -1
- package/out/zero-protocol/src/inspect-up.js +0 -1
- package/out/zero-protocol/src/inspect-up.js.map +1 -1
- package/out/zero-protocol/src/mutate-server.js.map +1 -1
- package/out/zero-protocol/src/mutation-id.js.map +1 -1
- package/out/zero-protocol/src/mutation.js.map +1 -1
- package/out/zero-protocol/src/mutations-patch.js.map +1 -1
- package/out/zero-protocol/src/ping.js.map +1 -1
- package/out/zero-protocol/src/poke.js +0 -4
- package/out/zero-protocol/src/poke.js.map +1 -1
- package/out/zero-protocol/src/pong.js.map +1 -1
- package/out/zero-protocol/src/primary-key.js.map +1 -1
- package/out/zero-protocol/src/protocol-version.js.map +1 -1
- package/out/zero-protocol/src/pull.js.map +1 -1
- package/out/zero-protocol/src/push.js +0 -16
- package/out/zero-protocol/src/push.js.map +1 -1
- package/out/zero-protocol/src/queries-patch.js.map +1 -1
- package/out/zero-protocol/src/query-hash.js.map +1 -1
- package/out/zero-protocol/src/query-server.js.map +1 -1
- package/out/zero-protocol/src/row-patch.js.map +1 -1
- package/out/zero-protocol/src/up.js.map +1 -1
- package/out/zero-protocol/src/update-auth.js.map +1 -1
- package/out/zero-protocol/src/version.js.map +1 -1
- package/out/zero-react/src/use-connection-state.js.map +1 -1
- package/out/zero-react/src/use-query.js.map +1 -1
- package/out/zero-react/src/use-zero-online.js.map +1 -1
- package/out/zero-react/src/zero-provider.js.map +1 -1
- package/out/zero-schema/src/builder/relationship-builder.js.map +1 -1
- package/out/zero-schema/src/builder/schema-builder.js.map +1 -1
- package/out/zero-schema/src/builder/table-builder.js.map +1 -1
- package/out/zero-schema/src/compiled-permissions.js.map +1 -1
- package/out/zero-schema/src/name-mapper.js.map +1 -1
- package/out/zero-schema/src/permissions.js.map +1 -1
- package/out/zero-schema/src/schema-config.js.map +1 -1
- package/out/zero-server/src/adapters/drizzle.js.map +1 -1
- package/out/zero-server/src/adapters/kysely.js.map +1 -1
- package/out/zero-server/src/adapters/pg.js.map +1 -1
- package/out/zero-server/src/adapters/postgresjs.js.map +1 -1
- package/out/zero-server/src/adapters/prisma.js.map +1 -1
- package/out/zero-server/src/custom.js +1 -2
- package/out/zero-server/src/custom.js.map +1 -1
- package/out/zero-server/src/logging.js.map +1 -1
- package/out/zero-server/src/pg-query-executor.js.map +1 -1
- package/out/zero-server/src/process-mutations.js.map +1 -1
- package/out/zero-server/src/push-processor.js.map +1 -1
- package/out/zero-server/src/queries/process-queries.js.map +1 -1
- package/out/zero-server/src/schema.js.map +1 -1
- package/out/zero-server/src/zql-database.js.map +1 -1
- package/out/zero-solid/src/solid-view.js.map +1 -1
- package/out/zero-solid/src/use-connection-state.js.map +1 -1
- package/out/zero-solid/src/use-query.js.map +1 -1
- package/out/zero-solid/src/use-zero-online.js.map +1 -1
- package/out/zero-solid/src/use-zero.js.map +1 -1
- package/out/zero-types/src/format.js.map +1 -1
- package/out/zero-types/src/name-mapper.js.map +1 -1
- package/out/zql/src/builder/builder.js.map +1 -1
- package/out/zql/src/builder/debug-delegate.d.ts +0 -5
- package/out/zql/src/builder/debug-delegate.d.ts.map +1 -1
- package/out/zql/src/builder/debug-delegate.js +1 -10
- package/out/zql/src/builder/debug-delegate.js.map +1 -1
- package/out/zql/src/builder/filter.js.map +1 -1
- package/out/zql/src/builder/like.js.map +1 -1
- package/out/zql/src/error.js.map +1 -1
- package/out/zql/src/ivm/array-view.js.map +1 -1
- package/out/zql/src/ivm/cap.js.map +1 -1
- package/out/zql/src/ivm/change.js.map +1 -1
- package/out/zql/src/ivm/constraint.js +1 -1
- package/out/zql/src/ivm/constraint.js.map +1 -1
- package/out/zql/src/ivm/data.js.map +1 -1
- package/out/zql/src/ivm/exists.js.map +1 -1
- package/out/zql/src/ivm/fan-in.js.map +1 -1
- package/out/zql/src/ivm/fan-out.js.map +1 -1
- package/out/zql/src/ivm/filter-operators.js.map +1 -1
- package/out/zql/src/ivm/filter-push.js.map +1 -1
- package/out/zql/src/ivm/filter.js.map +1 -1
- package/out/zql/src/ivm/flipped-join.d.ts +8 -4
- package/out/zql/src/ivm/flipped-join.d.ts.map +1 -1
- package/out/zql/src/ivm/flipped-join.js +63 -59
- package/out/zql/src/ivm/flipped-join.js.map +1 -1
- package/out/zql/src/ivm/join-utils.js.map +1 -1
- package/out/zql/src/ivm/join.js.map +1 -1
- package/out/zql/src/ivm/maybe-split-and-push-edit-change.js.map +1 -1
- package/out/zql/src/ivm/memory-source.js.map +1 -1
- package/out/zql/src/ivm/memory-storage.js.map +1 -1
- package/out/zql/src/ivm/operator.d.ts +1 -1
- package/out/zql/src/ivm/operator.js.map +1 -1
- package/out/zql/src/ivm/push-accumulated.js.map +1 -1
- package/out/zql/src/ivm/schema.d.ts +8 -0
- package/out/zql/src/ivm/schema.d.ts.map +1 -1
- package/out/zql/src/ivm/skip-yields.js.map +1 -1
- package/out/zql/src/ivm/skip.js.map +1 -1
- package/out/zql/src/ivm/source.js.map +1 -1
- package/out/zql/src/ivm/stream.js.map +1 -1
- package/out/zql/src/ivm/take.js.map +1 -1
- package/out/zql/src/ivm/union-fan-in.js.map +1 -1
- package/out/zql/src/ivm/union-fan-out.js.map +1 -1
- package/out/zql/src/ivm/view-apply-change.js.map +1 -1
- package/out/zql/src/mutate/crud.js.map +1 -1
- package/out/zql/src/mutate/custom.js.map +1 -1
- package/out/zql/src/mutate/mutator-registry.js.map +1 -1
- package/out/zql/src/mutate/mutator.js.map +1 -1
- package/out/zql/src/planner/planner-builder.js.map +1 -1
- package/out/zql/src/planner/planner-connection.js.map +1 -1
- package/out/zql/src/planner/planner-constraint.js.map +1 -1
- package/out/zql/src/planner/planner-debug.js.map +1 -1
- package/out/zql/src/planner/planner-fan-in.js.map +1 -1
- package/out/zql/src/planner/planner-fan-out.js.map +1 -1
- package/out/zql/src/planner/planner-graph.js.map +1 -1
- package/out/zql/src/planner/planner-join.d.ts.map +1 -1
- package/out/zql/src/planner/planner-join.js +1 -2
- package/out/zql/src/planner/planner-join.js.map +1 -1
- package/out/zql/src/planner/planner-node.js.map +1 -1
- package/out/zql/src/planner/planner-source.js.map +1 -1
- package/out/zql/src/planner/planner-terminus.js.map +1 -1
- package/out/zql/src/query/complete-ordering.js.map +1 -1
- package/out/zql/src/query/create-builder.js.map +1 -1
- package/out/zql/src/query/error.js.map +1 -1
- package/out/zql/src/query/escape-like.js.map +1 -1
- package/out/zql/src/query/expression.js.map +1 -1
- package/out/zql/src/query/measure-push-operator.js.map +1 -1
- package/out/zql/src/query/metrics-delegate.js.map +1 -1
- package/out/zql/src/query/named.js.map +1 -1
- package/out/zql/src/query/query-delegate-base.js.map +1 -1
- package/out/zql/src/query/query-impl.js +1 -1
- package/out/zql/src/query/query-impl.js.map +1 -1
- package/out/zql/src/query/query-internals.js.map +1 -1
- package/out/zql/src/query/query-registry.js.map +1 -1
- package/out/zql/src/query/runnable-query-impl.js.map +1 -1
- package/out/zql/src/query/static-query.js.map +1 -1
- package/out/zql/src/query/ttl.js.map +1 -1
- package/out/zql/src/query/validate-input.js.map +1 -1
- package/out/zqlite/src/database-storage.js.map +1 -1
- package/out/zqlite/src/db.js.map +1 -1
- package/out/zqlite/src/explain-queries.js.map +1 -1
- package/out/zqlite/src/internal/sql-inline.js.map +1 -1
- package/out/zqlite/src/internal/sql.js.map +1 -1
- package/out/zqlite/src/internal/statement-cache.js.map +1 -1
- package/out/zqlite/src/query-builder.js.map +1 -1
- package/out/zqlite/src/query-delegate.js.map +1 -1
- package/out/zqlite/src/resolve-scalar-subqueries.js.map +1 -1
- package/out/zqlite/src/sqlite-cost-model.js.map +1 -1
- package/out/zqlite/src/sqlite-stat-fanout.js.map +1 -1
- package/out/zqlite/src/table-source.d.ts.map +1 -1
- package/out/zqlite/src/table-source.js +6 -6
- package/out/zqlite/src/table-source.js.map +1 -1
- package/package.json +26 -42
- package/out/shared/src/ring-buffer.d.ts +0 -32
- package/out/shared/src/ring-buffer.d.ts.map +0 -1
- package/out/shared/src/ring-buffer.js +0 -109
- package/out/shared/src/ring-buffer.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"take.js","names":["#input","#storage","#limit","#partitionKey","#partitionKeyComparator","#output","#initialFetch","#rowHiddenFromFetch","#setTakeState","#pushEditChange","#getStateAndConstraint","#pushWithRowHiddenFromFetch"],"sources":["../../../../../zql/src/ivm/take.ts"],"sourcesContent":["import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport {hasOwn} from '../../../shared/src/has-own.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport {assertOrderingIncludesPK} from '../query/complete-ordering.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport {\n makeAddChange,\n makeRemoveChange,\n type Change,\n type EditChange,\n} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport {compareValues, type Comparator, type Node} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Operator,\n type Output,\n type Storage,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {type Stream} from './stream.ts';\n\nconst MAX_BOUND_KEY = 'maxBound';\n\ntype TakeState = {\n size: number;\n bound: Row | undefined;\n};\n\ninterface TakeStorage {\n get(key: typeof MAX_BOUND_KEY): Row | undefined;\n get(key: string): TakeState | undefined;\n set(key: typeof MAX_BOUND_KEY, value: Row): void;\n set(key: string, value: TakeState): void;\n del(key: string): void;\n}\n\nexport type PartitionKey = PrimaryKey;\n\n/**\n * The Take operator is for implementing limit queries. It takes the first n\n * nodes of its input as determined by the input’s comparator. It then keeps\n * a *bound* of the last item it has accepted so that it can evaluate whether\n * new incoming pushes should be accepted or rejected.\n *\n * Take can count rows globally or by unique value of some field.\n *\n * Maintains the invariant that its output size is always <= limit, even\n * mid processing of a push.\n */\nexport class Take implements Operator {\n readonly #input: Input;\n readonly #storage: TakeStorage;\n readonly #limit: number;\n readonly #partitionKey: PartitionKey | undefined;\n readonly #partitionKeyComparator: Comparator | undefined;\n // Fetch overlay needed for some split push cases.\n #rowHiddenFromFetch: Row | undefined;\n\n #output: Output = throwOutput;\n\n constructor(\n input: Input,\n storage: Storage,\n limit: number,\n partitionKey?: PartitionKey,\n ) {\n assert(limit >= 0, 'Limit must be non-negative');\n const {sort} = input.getSchema();\n assert(sort !== undefined, 'Take requires sorted input');\n assertOrderingIncludesPK(sort, input.getSchema().primaryKey);\n input.setOutput(this);\n this.#input = input;\n this.#storage = storage as TakeStorage;\n this.#limit = limit;\n this.#partitionKey = partitionKey;\n this.#partitionKeyComparator =\n partitionKey && makePartitionKeyComparator(partitionKey);\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *fetch(req: FetchRequest): Stream<Node | 'yield'> {\n if (\n !this.#partitionKey ||\n (req.constraint &&\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey))\n ) {\n const takeStateKey = getTakeStateKey(this.#partitionKey, req.constraint);\n const takeState = this.#storage.get(takeStateKey);\n if (!takeState) {\n yield* this.#initialFetch(req);\n return;\n }\n if (takeState.bound === undefined) {\n return;\n }\n for (const inputNode of this.#input.fetch(req)) {\n if (inputNode === 'yield') {\n yield inputNode;\n continue;\n }\n if (this.getSchema().compareRows(takeState.bound, inputNode.row) < 0) {\n return;\n }\n if (\n this.#rowHiddenFromFetch &&\n this.getSchema().compareRows(\n this.#rowHiddenFromFetch,\n inputNode.row,\n ) === 0\n ) {\n continue;\n }\n yield inputNode;\n }\n return;\n }\n // There is a partition key, but the fetch is not constrained or constrained\n // on a different key. Thus we don't have a single take state to bound by.\n // This currently only happens with nested sub-queries\n // e.g. issues include issuelabels include label. We could remove this\n // case if we added a translation layer (powered by some state) in join.\n // Specifically we need joinKeyValue => parent constraint key\n const maxBound = this.#storage.get(MAX_BOUND_KEY);\n if (maxBound === undefined) {\n return;\n }\n for (const inputNode of this.#input.fetch(req)) {\n if (inputNode === 'yield') {\n yield inputNode;\n continue;\n }\n if (this.getSchema().compareRows(inputNode.row, maxBound) > 0) {\n return;\n }\n const takeStateKey = getTakeStateKey(this.#partitionKey, inputNode.row);\n const takeState = this.#storage.get(takeStateKey);\n if (\n takeState?.bound !== undefined &&\n this.getSchema().compareRows(takeState.bound, inputNode.row) >= 0\n ) {\n yield inputNode;\n }\n }\n }\n\n *#initialFetch(req: FetchRequest): Stream<Node | 'yield'> {\n assert(req.start === undefined, 'Start should be undefined');\n assert(!req.reverse, 'Reverse should be false');\n\n if (this.#limit === 0) {\n return;\n }\n\n assert(\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey),\n 'Constraint should match partition key',\n );\n\n const takeStateKey = getTakeStateKey(this.#partitionKey, req.constraint);\n assert(\n this.#storage.get(takeStateKey) === undefined,\n 'Take state should be undefined',\n );\n\n let size = 0;\n let bound: Row | undefined;\n let downstreamEarlyReturn = true;\n let exceptionThrown = false;\n try {\n for (const inputNode of this.#input.fetch(req)) {\n if (inputNode === 'yield') {\n yield 'yield';\n continue;\n }\n yield inputNode;\n bound = inputNode.row;\n size++;\n if (size === this.#limit) {\n break;\n }\n }\n downstreamEarlyReturn = false;\n } catch (e) {\n exceptionThrown = true;\n throw e;\n } finally {\n if (!exceptionThrown) {\n this.#setTakeState(\n takeStateKey,\n size,\n bound,\n this.#storage.get(MAX_BOUND_KEY),\n );\n // If it becomes necessary to support downstream early return, this\n // assert should be removed, and replaced with code that consumes\n // the input stream until limit is reached or the input stream is\n // exhausted so that takeState is properly hydrated.\n assert(\n !downstreamEarlyReturn,\n 'Unexpected early return prevented full hydration',\n );\n }\n }\n }\n\n #getStateAndConstraint(row: Row) {\n const takeStateKey = getTakeStateKey(this.#partitionKey, row);\n const takeState = this.#storage.get(takeStateKey);\n let maxBound: Row | undefined;\n let constraint: Constraint | undefined;\n if (takeState) {\n maxBound = this.#storage.get(MAX_BOUND_KEY);\n constraint =\n this.#partitionKey &&\n Object.fromEntries(\n this.#partitionKey.map(key => [key, row[key]] as const),\n );\n }\n\n return {takeState, takeStateKey, maxBound, constraint} as\n | {\n takeState: undefined;\n takeStateKey: string;\n maxBound: undefined;\n constraint: undefined;\n }\n | {\n takeState: TakeState;\n takeStateKey: string;\n maxBound: Row | undefined;\n constraint: Constraint | undefined;\n };\n }\n\n *push(change: Change): Stream<'yield'> {\n if (change[ChangeIndex.TYPE] === ChangeType.EDIT) {\n yield* this.#pushEditChange(change);\n return;\n }\n\n const {takeState, takeStateKey, maxBound, constraint} =\n this.#getStateAndConstraint(change[ChangeIndex.NODE].row);\n if (!takeState) {\n return;\n }\n\n const {compareRows} = this.getSchema();\n\n if (change[ChangeIndex.TYPE] === ChangeType.ADD) {\n if (takeState.size < this.#limit) {\n this.#setTakeState(\n takeStateKey,\n takeState.size + 1,\n takeState.bound === undefined ||\n compareRows(takeState.bound, change[ChangeIndex.NODE].row) < 0\n ? change[ChangeIndex.NODE].row\n : takeState.bound,\n maxBound,\n );\n yield* this.#output.push(change, this);\n return;\n }\n // size === limit\n if (\n takeState.bound === undefined ||\n compareRows(change[ChangeIndex.NODE].row, takeState.bound) >= 0\n ) {\n return;\n }\n // added row < bound\n let beforeBoundNode: Node | undefined;\n let boundNode: Node | undefined;\n if (this.#limit === 1) {\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n boundNode = node;\n break;\n }\n } else {\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n reverse: true,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n } else if (boundNode === undefined) {\n boundNode = node;\n } else {\n beforeBoundNode = node;\n break;\n }\n }\n }\n assert(\n boundNode !== undefined,\n 'Take: boundNode must be found during fetch',\n );\n const removeChange = makeRemoveChange(boundNode);\n // Remove before add to maintain invariant that\n // output size <= limit.\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n beforeBoundNode === undefined ||\n compareRows(change[ChangeIndex.NODE].row, beforeBoundNode.row) > 0\n ? change[ChangeIndex.NODE].row\n : beforeBoundNode.row,\n maxBound,\n );\n yield* this.#pushWithRowHiddenFromFetch(\n change[ChangeIndex.NODE].row,\n removeChange,\n );\n yield* this.#output.push(change, this);\n } else if (change[ChangeIndex.TYPE] === ChangeType.REMOVE) {\n if (takeState.bound === undefined) {\n // change is after bound\n return;\n }\n const compToBound = compareRows(\n change[ChangeIndex.NODE].row,\n takeState.bound,\n );\n if (compToBound > 0) {\n // change is after bound\n return;\n }\n let beforeBoundNode: Node | undefined;\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'after',\n },\n constraint,\n reverse: true,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n beforeBoundNode = node;\n break;\n }\n\n let newBound: {node: Node; push: boolean} | undefined;\n if (beforeBoundNode) {\n const push = compareRows(beforeBoundNode.row, takeState.bound) > 0;\n newBound = {\n node: beforeBoundNode,\n push,\n };\n }\n if (!newBound?.push) {\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n const push = compareRows(node.row, takeState.bound) > 0;\n newBound = {\n node,\n push,\n };\n if (push) {\n break;\n }\n }\n }\n\n if (newBound?.push) {\n yield* this.#output.push(change, this);\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n newBound.node.row,\n maxBound,\n );\n yield* this.#output.push(makeAddChange(newBound.node), this);\n return;\n }\n this.#setTakeState(\n takeStateKey,\n takeState.size - 1,\n newBound?.node.row,\n maxBound,\n );\n yield* this.#output.push(change, this);\n } else if (change[ChangeIndex.TYPE] === ChangeType.CHILD) {\n // A 'child' change should be pushed to output if its row\n // is <= bound.\n if (\n takeState.bound &&\n compareRows(change[ChangeIndex.NODE].row, takeState.bound) <= 0\n ) {\n yield* this.#output.push(change, this);\n }\n }\n }\n\n *#pushEditChange(change: EditChange): Stream<'yield'> {\n assert(\n !this.#partitionKeyComparator ||\n this.#partitionKeyComparator(\n change[ChangeIndex.OLD_NODE].row,\n change[ChangeIndex.NODE].row,\n ) === 0,\n 'Unexpected change of partition key',\n );\n\n const {takeState, takeStateKey, maxBound, constraint} =\n this.#getStateAndConstraint(change[ChangeIndex.OLD_NODE].row);\n if (!takeState) {\n return;\n }\n\n assert(takeState.bound, 'Bound should be set');\n const {compareRows} = this.getSchema();\n const oldCmp = compareRows(\n change[ChangeIndex.OLD_NODE].row,\n takeState.bound,\n );\n const newCmp = compareRows(change[ChangeIndex.NODE].row, takeState.bound);\n\n const that = this;\n const replaceBoundAndForwardChange = function* () {\n that.#setTakeState(\n takeStateKey,\n takeState.size,\n change[ChangeIndex.NODE].row,\n maxBound,\n );\n yield* that.#output.push(change, that);\n };\n\n // The bounds row was changed.\n if (oldCmp === 0) {\n // The new row is the new bound.\n if (newCmp === 0) {\n // no need to update the state since we are keeping the bounds\n yield* this.#output.push(change, this);\n return;\n }\n\n if (newCmp < 0) {\n if (this.#limit === 1) {\n yield* replaceBoundAndForwardChange();\n return;\n }\n\n // New row will be in the result but it might not be the bounds any\n // more. We need to find the row before the bounds to determine the new\n // bounds.\n\n let beforeBoundNode: Node | undefined;\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'after',\n },\n constraint,\n reverse: true,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n beforeBoundNode = node;\n break;\n }\n assert(\n beforeBoundNode !== undefined,\n 'Take: beforeBoundNode must be found during fetch',\n );\n\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n beforeBoundNode.row,\n maxBound,\n );\n yield* this.#output.push(change, this);\n return;\n }\n\n assert(newCmp > 0, 'New comparison must be greater than 0');\n // Find the first item at the old bounds. This will be the new bounds.\n let newBoundNode: Node | undefined;\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n newBoundNode = node;\n break;\n }\n assert(\n newBoundNode !== undefined,\n 'Take: newBoundNode must be found during fetch',\n );\n\n // The next row is the new row. We can replace the bounds and keep the\n // edit change.\n if (compareRows(newBoundNode.row, change[ChangeIndex.NODE].row) === 0) {\n yield* replaceBoundAndForwardChange();\n return;\n }\n\n // The new row is now outside the bounds, so we need to remove the old\n // row and add the new bounds row.\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n newBoundNode.row,\n maxBound,\n );\n yield* this.#pushWithRowHiddenFromFetch(\n newBoundNode.row,\n makeRemoveChange(change[ChangeIndex.OLD_NODE]),\n );\n yield* this.#output.push(makeAddChange(newBoundNode), this);\n return;\n }\n\n if (oldCmp > 0) {\n assert(newCmp !== 0, 'Invalid state. Row has duplicate primary key');\n\n // Both old and new outside of bounds\n if (newCmp > 0) {\n return;\n }\n\n // old was outside, new is inside. Pushing out the old bounds\n assert(newCmp < 0, 'New comparison must be less than 0');\n\n let oldBoundNode: Node | undefined;\n let newBoundNode: Node | undefined;\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n reverse: true,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n } else if (oldBoundNode === undefined) {\n oldBoundNode = node;\n } else {\n newBoundNode = node;\n break;\n }\n }\n assert(\n oldBoundNode !== undefined,\n 'Take: oldBoundNode must be found during fetch',\n );\n assert(\n newBoundNode !== undefined,\n 'Take: newBoundNode must be found during fetch',\n );\n\n // Remove before add to maintain invariant that\n // output size <= limit.\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n newBoundNode.row,\n maxBound,\n );\n yield* this.#pushWithRowHiddenFromFetch(\n change[ChangeIndex.NODE].row,\n makeRemoveChange(oldBoundNode),\n );\n yield* this.#output.push(makeAddChange(change[ChangeIndex.NODE]), this);\n\n return;\n }\n\n if (oldCmp < 0) {\n assert(newCmp !== 0, 'Invalid state. Row has duplicate primary key');\n\n // Both old and new inside of bounds\n if (newCmp < 0) {\n yield* this.#output.push(change, this);\n return;\n }\n\n // old was inside, new is larger than old bound\n\n assert(newCmp > 0, 'New comparison must be greater than 0');\n\n // at this point we need to find the row after the bound and use that or\n // the newRow as the new bound.\n let afterBoundNode: Node | undefined;\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'after',\n },\n constraint,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n afterBoundNode = node;\n break;\n }\n assert(\n afterBoundNode !== undefined,\n 'Take: afterBoundNode must be found during fetch',\n );\n\n // The new row is the new bound. Use an edit change.\n if (compareRows(afterBoundNode.row, change[ChangeIndex.NODE].row) === 0) {\n yield* replaceBoundAndForwardChange();\n return;\n }\n\n yield* this.#output.push(\n makeRemoveChange(change[ChangeIndex.OLD_NODE]),\n this,\n );\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n afterBoundNode.row,\n maxBound,\n );\n yield* this.#output.push(makeAddChange(afterBoundNode), this);\n return;\n }\n\n unreachable();\n }\n\n *#pushWithRowHiddenFromFetch(row: Row, change: Change) {\n this.#rowHiddenFromFetch = row;\n try {\n yield* this.#output.push(change, this);\n } finally {\n this.#rowHiddenFromFetch = undefined;\n }\n }\n\n #setTakeState(\n takeStateKey: string,\n size: number,\n bound: Row | undefined,\n maxBound: Row | undefined,\n ) {\n this.#storage.set(takeStateKey, {\n size,\n bound,\n });\n if (\n bound !== undefined &&\n (maxBound === undefined ||\n this.getSchema().compareRows(bound, maxBound) > 0)\n ) {\n this.#storage.set(MAX_BOUND_KEY, bound);\n }\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n}\n\nfunction getTakeStateKey(\n partitionKey: PartitionKey | undefined,\n rowOrConstraint: Row | Constraint | undefined,\n): string {\n // The order must be consistent. We always use the order as defined by the\n // partition key.\n const partitionValues: Value[] = [];\n\n if (partitionKey && rowOrConstraint) {\n for (const key of partitionKey) {\n partitionValues.push(rowOrConstraint[key]);\n }\n }\n\n return JSON.stringify(['take', ...partitionValues]);\n}\n\nexport function constraintMatchesPartitionKey(\n constraint: Constraint | undefined,\n partitionKey: PartitionKey | undefined,\n): boolean {\n if (constraint === undefined || partitionKey === undefined) {\n return constraint === partitionKey;\n }\n if (partitionKey.length !== Object.keys(constraint).length) {\n return false;\n }\n for (const key of partitionKey) {\n if (!hasOwn(constraint, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function makePartitionKeyComparator(\n partitionKey: PartitionKey,\n): Comparator {\n return (a, b) => {\n for (const key of partitionKey) {\n const cmp = compareValues(a[key], b[key]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n return 0;\n };\n}\n"],"mappings":";;;;;;;AA0BA,IAAM,gBAAgB;;;;;;;;;;;;AA4BtB,IAAa,OAAb,MAAsC;CACpC;CACA;CACA;CACA;CACA;CAEA;CAEA,UAAkB;CAElB,YACE,OACA,SACA,OACA,cACA;EACA,OAAO,SAAS,GAAG,4BAA4B;EAC/C,MAAM,EAAC,SAAQ,MAAM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ACpD;AAEA,SAAgB,8BACd,YACA,cACS;CACT,IAAI,eAAe,KAAA,KAAa,iBAAiB,KAAA,GAC/C,OAAO,eAAe;CAExB,IAAI,aAAa,WAAW,OAAO,KAAK,UAAU,EAAE,QAClD,OAAO;CAET,KAAK,MAAM,OAAO,cAChB,IAAI,CAAC,OAAO,YAAY,GAAG,GACzB,OAAO;CAGX,OAAO;AACT;AAEA,SAAgB,2BACd,cACY;CACZ,QAAQ,GAAG,MAAM;EACf,KAAK,MAAM,OAAO,cAAc;GAC9B,MAAM,MAAM,cAAc,EAAE,MAAM,EAAE,IAAI;GACxC,IAAI,QAAQ,GACV,OAAO;EAEX;EACA,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"take.js","names":["#input","#storage","#limit","#partitionKey","#partitionKeyComparator","#output","#initialFetch","#rowHiddenFromFetch","#setTakeState","#pushEditChange","#getStateAndConstraint","#pushWithRowHiddenFromFetch"],"sources":["../../../../../zql/src/ivm/take.ts"],"sourcesContent":["import {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport {hasOwn} from '../../../shared/src/has-own.ts';\nimport type {Row, Value} from '../../../zero-protocol/src/data.ts';\nimport type {PrimaryKey} from '../../../zero-protocol/src/primary-key.ts';\nimport {assertOrderingIncludesPK} from '../query/complete-ordering.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport {\n makeAddChange,\n makeRemoveChange,\n type Change,\n type EditChange,\n} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport {compareValues, type Comparator, type Node} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type Operator,\n type Output,\n type Storage,\n} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {type Stream} from './stream.ts';\n\nconst MAX_BOUND_KEY = 'maxBound';\n\ntype TakeState = {\n size: number;\n bound: Row | undefined;\n};\n\ninterface TakeStorage {\n get(key: typeof MAX_BOUND_KEY): Row | undefined;\n get(key: string): TakeState | undefined;\n set(key: typeof MAX_BOUND_KEY, value: Row): void;\n set(key: string, value: TakeState): void;\n del(key: string): void;\n}\n\nexport type PartitionKey = PrimaryKey;\n\n/**\n * The Take operator is for implementing limit queries. It takes the first n\n * nodes of its input as determined by the input’s comparator. It then keeps\n * a *bound* of the last item it has accepted so that it can evaluate whether\n * new incoming pushes should be accepted or rejected.\n *\n * Take can count rows globally or by unique value of some field.\n *\n * Maintains the invariant that its output size is always <= limit, even\n * mid processing of a push.\n */\nexport class Take implements Operator {\n readonly #input: Input;\n readonly #storage: TakeStorage;\n readonly #limit: number;\n readonly #partitionKey: PartitionKey | undefined;\n readonly #partitionKeyComparator: Comparator | undefined;\n // Fetch overlay needed for some split push cases.\n #rowHiddenFromFetch: Row | undefined;\n\n #output: Output = throwOutput;\n\n constructor(\n input: Input,\n storage: Storage,\n limit: number,\n partitionKey?: PartitionKey,\n ) {\n assert(limit >= 0, 'Limit must be non-negative');\n const {sort} = input.getSchema();\n assert(sort !== undefined, 'Take requires sorted input');\n assertOrderingIncludesPK(sort, input.getSchema().primaryKey);\n input.setOutput(this);\n this.#input = input;\n this.#storage = storage as TakeStorage;\n this.#limit = limit;\n this.#partitionKey = partitionKey;\n this.#partitionKeyComparator =\n partitionKey && makePartitionKeyComparator(partitionKey);\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n *fetch(req: FetchRequest): Stream<Node | 'yield'> {\n if (\n !this.#partitionKey ||\n (req.constraint &&\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey))\n ) {\n const takeStateKey = getTakeStateKey(this.#partitionKey, req.constraint);\n const takeState = this.#storage.get(takeStateKey);\n if (!takeState) {\n yield* this.#initialFetch(req);\n return;\n }\n if (takeState.bound === undefined) {\n return;\n }\n for (const inputNode of this.#input.fetch(req)) {\n if (inputNode === 'yield') {\n yield inputNode;\n continue;\n }\n if (this.getSchema().compareRows(takeState.bound, inputNode.row) < 0) {\n return;\n }\n if (\n this.#rowHiddenFromFetch &&\n this.getSchema().compareRows(\n this.#rowHiddenFromFetch,\n inputNode.row,\n ) === 0\n ) {\n continue;\n }\n yield inputNode;\n }\n return;\n }\n // There is a partition key, but the fetch is not constrained or constrained\n // on a different key. Thus we don't have a single take state to bound by.\n // This currently only happens with nested sub-queries\n // e.g. issues include issuelabels include label. We could remove this\n // case if we added a translation layer (powered by some state) in join.\n // Specifically we need joinKeyValue => parent constraint key\n const maxBound = this.#storage.get(MAX_BOUND_KEY);\n if (maxBound === undefined) {\n return;\n }\n for (const inputNode of this.#input.fetch(req)) {\n if (inputNode === 'yield') {\n yield inputNode;\n continue;\n }\n if (this.getSchema().compareRows(inputNode.row, maxBound) > 0) {\n return;\n }\n const takeStateKey = getTakeStateKey(this.#partitionKey, inputNode.row);\n const takeState = this.#storage.get(takeStateKey);\n if (\n takeState?.bound !== undefined &&\n this.getSchema().compareRows(takeState.bound, inputNode.row) >= 0\n ) {\n yield inputNode;\n }\n }\n }\n\n *#initialFetch(req: FetchRequest): Stream<Node | 'yield'> {\n assert(req.start === undefined, 'Start should be undefined');\n assert(!req.reverse, 'Reverse should be false');\n\n if (this.#limit === 0) {\n return;\n }\n\n assert(\n constraintMatchesPartitionKey(req.constraint, this.#partitionKey),\n 'Constraint should match partition key',\n );\n\n const takeStateKey = getTakeStateKey(this.#partitionKey, req.constraint);\n assert(\n this.#storage.get(takeStateKey) === undefined,\n 'Take state should be undefined',\n );\n\n let size = 0;\n let bound: Row | undefined;\n let downstreamEarlyReturn = true;\n let exceptionThrown = false;\n try {\n for (const inputNode of this.#input.fetch(req)) {\n if (inputNode === 'yield') {\n yield 'yield';\n continue;\n }\n yield inputNode;\n bound = inputNode.row;\n size++;\n if (size === this.#limit) {\n break;\n }\n }\n downstreamEarlyReturn = false;\n } catch (e) {\n exceptionThrown = true;\n throw e;\n } finally {\n if (!exceptionThrown) {\n this.#setTakeState(\n takeStateKey,\n size,\n bound,\n this.#storage.get(MAX_BOUND_KEY),\n );\n // If it becomes necessary to support downstream early return, this\n // assert should be removed, and replaced with code that consumes\n // the input stream until limit is reached or the input stream is\n // exhausted so that takeState is properly hydrated.\n assert(\n !downstreamEarlyReturn,\n 'Unexpected early return prevented full hydration',\n );\n }\n }\n }\n\n #getStateAndConstraint(row: Row) {\n const takeStateKey = getTakeStateKey(this.#partitionKey, row);\n const takeState = this.#storage.get(takeStateKey);\n let maxBound: Row | undefined;\n let constraint: Constraint | undefined;\n if (takeState) {\n maxBound = this.#storage.get(MAX_BOUND_KEY);\n constraint =\n this.#partitionKey &&\n Object.fromEntries(\n this.#partitionKey.map(key => [key, row[key]] as const),\n );\n }\n\n return {takeState, takeStateKey, maxBound, constraint} as\n | {\n takeState: undefined;\n takeStateKey: string;\n maxBound: undefined;\n constraint: undefined;\n }\n | {\n takeState: TakeState;\n takeStateKey: string;\n maxBound: Row | undefined;\n constraint: Constraint | undefined;\n };\n }\n\n *push(change: Change): Stream<'yield'> {\n if (change[ChangeIndex.TYPE] === ChangeType.EDIT) {\n yield* this.#pushEditChange(change);\n return;\n }\n\n const {takeState, takeStateKey, maxBound, constraint} =\n this.#getStateAndConstraint(change[ChangeIndex.NODE].row);\n if (!takeState) {\n return;\n }\n\n const {compareRows} = this.getSchema();\n\n if (change[ChangeIndex.TYPE] === ChangeType.ADD) {\n if (takeState.size < this.#limit) {\n this.#setTakeState(\n takeStateKey,\n takeState.size + 1,\n takeState.bound === undefined ||\n compareRows(takeState.bound, change[ChangeIndex.NODE].row) < 0\n ? change[ChangeIndex.NODE].row\n : takeState.bound,\n maxBound,\n );\n yield* this.#output.push(change, this);\n return;\n }\n // size === limit\n if (\n takeState.bound === undefined ||\n compareRows(change[ChangeIndex.NODE].row, takeState.bound) >= 0\n ) {\n return;\n }\n // added row < bound\n let beforeBoundNode: Node | undefined;\n let boundNode: Node | undefined;\n if (this.#limit === 1) {\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n boundNode = node;\n break;\n }\n } else {\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n reverse: true,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n } else if (boundNode === undefined) {\n boundNode = node;\n } else {\n beforeBoundNode = node;\n break;\n }\n }\n }\n assert(\n boundNode !== undefined,\n 'Take: boundNode must be found during fetch',\n );\n const removeChange = makeRemoveChange(boundNode);\n // Remove before add to maintain invariant that\n // output size <= limit.\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n beforeBoundNode === undefined ||\n compareRows(change[ChangeIndex.NODE].row, beforeBoundNode.row) > 0\n ? change[ChangeIndex.NODE].row\n : beforeBoundNode.row,\n maxBound,\n );\n yield* this.#pushWithRowHiddenFromFetch(\n change[ChangeIndex.NODE].row,\n removeChange,\n );\n yield* this.#output.push(change, this);\n } else if (change[ChangeIndex.TYPE] === ChangeType.REMOVE) {\n if (takeState.bound === undefined) {\n // change is after bound\n return;\n }\n const compToBound = compareRows(\n change[ChangeIndex.NODE].row,\n takeState.bound,\n );\n if (compToBound > 0) {\n // change is after bound\n return;\n }\n let beforeBoundNode: Node | undefined;\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'after',\n },\n constraint,\n reverse: true,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n beforeBoundNode = node;\n break;\n }\n\n let newBound: {node: Node; push: boolean} | undefined;\n if (beforeBoundNode) {\n const push = compareRows(beforeBoundNode.row, takeState.bound) > 0;\n newBound = {\n node: beforeBoundNode,\n push,\n };\n }\n if (!newBound?.push) {\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n const push = compareRows(node.row, takeState.bound) > 0;\n newBound = {\n node,\n push,\n };\n if (push) {\n break;\n }\n }\n }\n\n if (newBound?.push) {\n yield* this.#output.push(change, this);\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n newBound.node.row,\n maxBound,\n );\n yield* this.#output.push(makeAddChange(newBound.node), this);\n return;\n }\n this.#setTakeState(\n takeStateKey,\n takeState.size - 1,\n newBound?.node.row,\n maxBound,\n );\n yield* this.#output.push(change, this);\n } else if (change[ChangeIndex.TYPE] === ChangeType.CHILD) {\n // A 'child' change should be pushed to output if its row\n // is <= bound.\n if (\n takeState.bound &&\n compareRows(change[ChangeIndex.NODE].row, takeState.bound) <= 0\n ) {\n yield* this.#output.push(change, this);\n }\n }\n }\n\n *#pushEditChange(change: EditChange): Stream<'yield'> {\n assert(\n !this.#partitionKeyComparator ||\n this.#partitionKeyComparator(\n change[ChangeIndex.OLD_NODE].row,\n change[ChangeIndex.NODE].row,\n ) === 0,\n 'Unexpected change of partition key',\n );\n\n const {takeState, takeStateKey, maxBound, constraint} =\n this.#getStateAndConstraint(change[ChangeIndex.OLD_NODE].row);\n if (!takeState) {\n return;\n }\n\n assert(takeState.bound, 'Bound should be set');\n const {compareRows} = this.getSchema();\n const oldCmp = compareRows(\n change[ChangeIndex.OLD_NODE].row,\n takeState.bound,\n );\n const newCmp = compareRows(change[ChangeIndex.NODE].row, takeState.bound);\n\n const that = this;\n const replaceBoundAndForwardChange = function* () {\n that.#setTakeState(\n takeStateKey,\n takeState.size,\n change[ChangeIndex.NODE].row,\n maxBound,\n );\n yield* that.#output.push(change, that);\n };\n\n // The bounds row was changed.\n if (oldCmp === 0) {\n // The new row is the new bound.\n if (newCmp === 0) {\n // no need to update the state since we are keeping the bounds\n yield* this.#output.push(change, this);\n return;\n }\n\n if (newCmp < 0) {\n if (this.#limit === 1) {\n yield* replaceBoundAndForwardChange();\n return;\n }\n\n // New row will be in the result but it might not be the bounds any\n // more. We need to find the row before the bounds to determine the new\n // bounds.\n\n let beforeBoundNode: Node | undefined;\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'after',\n },\n constraint,\n reverse: true,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n beforeBoundNode = node;\n break;\n }\n assert(\n beforeBoundNode !== undefined,\n 'Take: beforeBoundNode must be found during fetch',\n );\n\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n beforeBoundNode.row,\n maxBound,\n );\n yield* this.#output.push(change, this);\n return;\n }\n\n assert(newCmp > 0, 'New comparison must be greater than 0');\n // Find the first item at the old bounds. This will be the new bounds.\n let newBoundNode: Node | undefined;\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n newBoundNode = node;\n break;\n }\n assert(\n newBoundNode !== undefined,\n 'Take: newBoundNode must be found during fetch',\n );\n\n // The next row is the new row. We can replace the bounds and keep the\n // edit change.\n if (compareRows(newBoundNode.row, change[ChangeIndex.NODE].row) === 0) {\n yield* replaceBoundAndForwardChange();\n return;\n }\n\n // The new row is now outside the bounds, so we need to remove the old\n // row and add the new bounds row.\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n newBoundNode.row,\n maxBound,\n );\n yield* this.#pushWithRowHiddenFromFetch(\n newBoundNode.row,\n makeRemoveChange(change[ChangeIndex.OLD_NODE]),\n );\n yield* this.#output.push(makeAddChange(newBoundNode), this);\n return;\n }\n\n if (oldCmp > 0) {\n assert(newCmp !== 0, 'Invalid state. Row has duplicate primary key');\n\n // Both old and new outside of bounds\n if (newCmp > 0) {\n return;\n }\n\n // old was outside, new is inside. Pushing out the old bounds\n assert(newCmp < 0, 'New comparison must be less than 0');\n\n let oldBoundNode: Node | undefined;\n let newBoundNode: Node | undefined;\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'at',\n },\n constraint,\n reverse: true,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n } else if (oldBoundNode === undefined) {\n oldBoundNode = node;\n } else {\n newBoundNode = node;\n break;\n }\n }\n assert(\n oldBoundNode !== undefined,\n 'Take: oldBoundNode must be found during fetch',\n );\n assert(\n newBoundNode !== undefined,\n 'Take: newBoundNode must be found during fetch',\n );\n\n // Remove before add to maintain invariant that\n // output size <= limit.\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n newBoundNode.row,\n maxBound,\n );\n yield* this.#pushWithRowHiddenFromFetch(\n change[ChangeIndex.NODE].row,\n makeRemoveChange(oldBoundNode),\n );\n yield* this.#output.push(makeAddChange(change[ChangeIndex.NODE]), this);\n\n return;\n }\n\n if (oldCmp < 0) {\n assert(newCmp !== 0, 'Invalid state. Row has duplicate primary key');\n\n // Both old and new inside of bounds\n if (newCmp < 0) {\n yield* this.#output.push(change, this);\n return;\n }\n\n // old was inside, new is larger than old bound\n\n assert(newCmp > 0, 'New comparison must be greater than 0');\n\n // at this point we need to find the row after the bound and use that or\n // the newRow as the new bound.\n let afterBoundNode: Node | undefined;\n for (const node of this.#input.fetch({\n start: {\n row: takeState.bound,\n basis: 'after',\n },\n constraint,\n })) {\n if (node === 'yield') {\n yield node;\n continue;\n }\n afterBoundNode = node;\n break;\n }\n assert(\n afterBoundNode !== undefined,\n 'Take: afterBoundNode must be found during fetch',\n );\n\n // The new row is the new bound. Use an edit change.\n if (compareRows(afterBoundNode.row, change[ChangeIndex.NODE].row) === 0) {\n yield* replaceBoundAndForwardChange();\n return;\n }\n\n yield* this.#output.push(\n makeRemoveChange(change[ChangeIndex.OLD_NODE]),\n this,\n );\n this.#setTakeState(\n takeStateKey,\n takeState.size,\n afterBoundNode.row,\n maxBound,\n );\n yield* this.#output.push(makeAddChange(afterBoundNode), this);\n return;\n }\n\n unreachable();\n }\n\n *#pushWithRowHiddenFromFetch(row: Row, change: Change) {\n this.#rowHiddenFromFetch = row;\n try {\n yield* this.#output.push(change, this);\n } finally {\n this.#rowHiddenFromFetch = undefined;\n }\n }\n\n #setTakeState(\n takeStateKey: string,\n size: number,\n bound: Row | undefined,\n maxBound: Row | undefined,\n ) {\n this.#storage.set(takeStateKey, {\n size,\n bound,\n });\n if (\n bound !== undefined &&\n (maxBound === undefined ||\n this.getSchema().compareRows(bound, maxBound) > 0)\n ) {\n this.#storage.set(MAX_BOUND_KEY, bound);\n }\n }\n\n destroy(): void {\n this.#input.destroy();\n }\n}\n\nfunction getTakeStateKey(\n partitionKey: PartitionKey | undefined,\n rowOrConstraint: Row | Constraint | undefined,\n): string {\n // The order must be consistent. We always use the order as defined by the\n // partition key.\n const partitionValues: Value[] = [];\n\n if (partitionKey && rowOrConstraint) {\n for (const key of partitionKey) {\n partitionValues.push(rowOrConstraint[key]);\n }\n }\n\n return JSON.stringify(['take', ...partitionValues]);\n}\n\nexport function constraintMatchesPartitionKey(\n constraint: Constraint | undefined,\n partitionKey: PartitionKey | undefined,\n): boolean {\n if (constraint === undefined || partitionKey === undefined) {\n return constraint === partitionKey;\n }\n if (partitionKey.length !== Object.keys(constraint).length) {\n return false;\n }\n for (const key of partitionKey) {\n if (!hasOwn(constraint, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function makePartitionKeyComparator(\n partitionKey: PartitionKey,\n): Comparator {\n return (a, b) => {\n for (const key of partitionKey) {\n const cmp = compareValues(a[key], b[key]);\n if (cmp !== 0) {\n return cmp;\n }\n }\n return 0;\n };\n}\n"],"mappings":";;;;;;;AA0BA,IAAM,gBAAgB;;;;;;;;;;;;AA4BtB,IAAa,OAAb,MAAsC;CACpC;CACA;CACA;CACA;CACA;CAEA;CAEA,UAAkB;CAElB,YACE,OACA,SACA,OACA,cACA;AACA,SAAO,SAAS,GAAG,6BAA6B;EAChD,MAAM,EAAC,SAAQ,MAAM,WAAW;AAChC,SAAO,SAAS,KAAA,GAAW,6BAA6B;AACxD,2BAAyB,MAAM,MAAM,WAAW,CAAC,WAAW;AAC5D,QAAM,UAAU,KAAK;AACrB,QAAA,QAAc;AACd,QAAA,UAAgB;AAChB,QAAA,QAAc;AACd,QAAA,eAAqB;AACrB,QAAA,yBACE,gBAAgB,2BAA2B,aAAa;;CAG5D,UAAU,QAAsB;AAC9B,QAAA,SAAe;;CAGjB,YAA0B;AACxB,SA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,KAAU,QAAgB;AACrD,QAAA,qBAA2B;AAC3B,MAAI;AACF,UAAO,MAAA,OAAa,KAAK,QAAQ,KAAK;YAC9B;AACR,SAAA,qBAA2B,KAAA;;;CAI/B,cACE,cACA,MACA,OACA,UACA;AACA,QAAA,QAAc,IAAI,cAAc;GAC9B;GACA;GACD,CAAC;AACF,MACE,UAAU,KAAA,MACT,aAAa,KAAA,KACZ,KAAK,WAAW,CAAC,YAAY,OAAO,SAAS,GAAG,GAElD,OAAA,QAAc,IAAI,eAAe,MAAM;;CAI3C,UAAgB;AACd,QAAA,MAAY,SAAS;;;AAIzB,SAAS,gBACP,cACA,iBACQ;CAGR,MAAM,kBAA2B,EAAE;AAEnC,KAAI,gBAAgB,gBAClB,MAAK,MAAM,OAAO,aAChB,iBAAgB,KAAK,gBAAgB,KAAK;AAI9C,QAAO,KAAK,UAAU,CAAC,QAAQ,GAAG,gBAAgB,CAAC;;AAGrD,SAAgB,8BACd,YACA,cACS;AACT,KAAI,eAAe,KAAA,KAAa,iBAAiB,KAAA,EAC/C,QAAO,eAAe;AAExB,KAAI,aAAa,WAAW,OAAO,KAAK,WAAW,CAAC,OAClD,QAAO;AAET,MAAK,MAAM,OAAO,aAChB,KAAI,CAAC,OAAO,YAAY,IAAI,CAC1B,QAAO;AAGX,QAAO;;AAGT,SAAgB,2BACd,cACY;AACZ,SAAQ,GAAG,MAAM;AACf,OAAK,MAAM,OAAO,cAAc;GAC9B,MAAM,MAAM,cAAc,EAAE,MAAM,EAAE,KAAK;AACzC,OAAI,QAAQ,EACV,QAAO;;AAGX,SAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"union-fan-in.js","names":["#inputs","#schema","#fanOutPushStarted","#pushInternalChange","#accumulatedPushes","#output"],"sources":["../../../../../zql/src/ivm/union-fan-in.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {Writable} from '../../../shared/src/writable.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport type {Change} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport type {Node} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type InputBase,\n type Operator,\n type Output,\n} from './operator.ts';\nimport {\n makeAddEmptyRelationships,\n mergeRelationships,\n pushAccumulatedChanges,\n} from './push-accumulated.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {first, type Stream} from './stream.ts';\nimport type {UnionFanOut} from './union-fan-out.ts';\n\nexport class UnionFanIn implements Operator {\n readonly #inputs: readonly Input[];\n readonly #schema: SourceSchema;\n #fanOutPushStarted: boolean = false;\n #output: Output = throwOutput;\n #accumulatedPushes: Change[] = [];\n\n constructor(fanOut: UnionFanOut, inputs: Input[]) {\n this.#inputs = inputs;\n const fanOutSchema = fanOut.getSchema();\n fanOut.setFanIn(this);\n assert(fanOutSchema.sort !== undefined, 'UnionFanIn requires sorted input');\n\n const schema: Writable<SourceSchema> = {\n tableName: fanOutSchema.tableName,\n columns: fanOutSchema.columns,\n primaryKey: fanOutSchema.primaryKey,\n relationships: {\n ...fanOutSchema.relationships,\n },\n isHidden: fanOutSchema.isHidden,\n system: fanOutSchema.system,\n compareRows: fanOutSchema.compareRows,\n sort: fanOutSchema.sort,\n };\n\n // now go through inputs and merge relationships\n const relationshipsFromBranches: Set<string> = new Set();\n for (const input of inputs) {\n const inputSchema = input.getSchema();\n assert(\n schema.tableName === inputSchema.tableName,\n `Table name mismatch in union fan-in: ${schema.tableName} !== ${inputSchema.tableName}`,\n );\n assert(\n schema.primaryKey === inputSchema.primaryKey,\n `Primary key mismatch in union fan-in`,\n );\n assert(\n schema.system === inputSchema.system,\n `System mismatch in union fan-in: ${schema.system} !== ${inputSchema.system}`,\n );\n assert(\n schema.compareRows === inputSchema.compareRows,\n `compareRows mismatch in union fan-in`,\n );\n assert(schema.sort === inputSchema.sort, `Sort mismatch in union fan-in`);\n\n for (const [relName, relSchema] of Object.entries(\n inputSchema.relationships,\n )) {\n if (relName in fanOutSchema.relationships) {\n continue;\n }\n\n // All branches will have unique relationship names except for relationships\n // that come in from `fanOut`.\n assert(\n !relationshipsFromBranches.has(relName),\n `Relationship ${relName} exists in multiple upstream inputs to union fan-in`,\n );\n schema.relationships[relName] = relSchema;\n relationshipsFromBranches.add(relName);\n }\n\n input.setOutput(this);\n }\n\n this.#schema = schema;\n this.#inputs = inputs;\n }\n\n destroy(): void {\n for (const input of this.#inputs) {\n input.destroy();\n }\n }\n\n fetch(req: FetchRequest): Stream<Node | 'yield'> {\n const iterables = this.#inputs.map(input => input.fetch(req));\n const compareRows = this.#schema.compareRows;\n const compare = req.reverse\n ? (l: Node, r: Node) => compareRows(r.row, l.row)\n : (l: Node, r: Node) => compareRows(l.row, r.row);\n return mergeFetches(iterables, compare);\n }\n\n getSchema(): SourceSchema {\n return this.#schema;\n }\n\n *push(change: Change, pusher: InputBase): Stream<'yield'> {\n if (!this.#fanOutPushStarted) {\n yield* this.#pushInternalChange(change, pusher);\n } else {\n this.#accumulatedPushes.push(change);\n }\n }\n\n /**\n * An internal change means that a change was received inside the fan-out/fan-in sub-graph.\n *\n * These changes always come from children of a flip-join as no other push generating operators\n * currently exist between union-fan-in and union-fan-out. All other pushes\n * enter into union-fan-out before reaching union-fan-in.\n *\n * - normal joins for `exists` come before `union-fan-out`\n * - joins for `related` come after `union-fan-out`\n * - take comes after `union-fan-out`\n *\n * The algorithm for deciding whether or not to forward a push that came from inside the ufo/ufi sub-graph:\n * 1. If the change is a `child` change we can forward it. This is because all child branches in the ufo/ufi sub-graph are unique.\n * 2. If the change is `add` we can forward it iff no `fetches` for the row return any results.\n * If another branch has it, the add was already emitted in the past.\n * 3. If the change is `remove` we can forward it iff no `fetches` for the row return any results.\n * If no other branches have the change, the remove can be sent as the value is no longer present.\n * If other branches have it, the last branch the processes the remove will send the remove.\n * 4. Edits will always come through as child changes as flip join will flip them into children.\n * An edit that would result in a remove or add will have been split into an add/remove pair rather than being an edit.\n */\n *#pushInternalChange(change: Change, pusher: InputBase): Stream<'yield'> {\n if (change[ChangeIndex.TYPE] === ChangeType.CHILD) {\n yield* this.#output.push(change, this);\n return;\n }\n\n assert(\n change[ChangeIndex.TYPE] === ChangeType.ADD ||\n change[ChangeIndex.TYPE] === ChangeType.REMOVE,\n () =>\n `UnionFanIn: expected add or remove change type, got ${change[ChangeIndex.TYPE]}`,\n );\n\n let hadMatch = false;\n for (const input of this.#inputs) {\n if (input === pusher) {\n hadMatch = true;\n continue;\n }\n\n const constraint: Writable<Constraint> = {};\n for (const key of this.#schema.primaryKey) {\n constraint[key] = change[ChangeIndex.NODE].row[key];\n }\n const fetchResult = input.fetch({\n constraint,\n });\n\n if (first(fetchResult) !== undefined) {\n // Another branch has the row, so the add/remove is not needed.\n return;\n }\n }\n\n assert(hadMatch, 'Pusher was not one of the inputs to union-fan-in!');\n\n // No other branches have the row, so we can push the change.\n yield* this.#output.push(change, this);\n }\n\n fanOutStartedPushing() {\n assert(\n this.#fanOutPushStarted === false,\n 'UnionFanIn: fanOutStartedPushing called while already pushing',\n );\n this.#fanOutPushStarted = true;\n }\n\n *fanOutDonePushing(fanOutChangeType: ChangeType): Stream<'yield'> {\n assert(\n this.#fanOutPushStarted,\n 'UnionFanIn: fanOutDonePushing called without fanOutStartedPushing',\n );\n this.#fanOutPushStarted = false;\n if (this.#inputs.length === 0) {\n return;\n }\n\n if (this.#accumulatedPushes.length === 0) {\n // It is possible for no forks to pass along the push.\n // E.g., if no filters match in any fork.\n return;\n }\n\n yield* pushAccumulatedChanges(\n this.#accumulatedPushes,\n this.#output,\n this,\n fanOutChangeType,\n mergeRelationships,\n makeAddEmptyRelationships(this.#schema),\n );\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n}\n\nexport function* mergeFetches(\n fetches: Iterable<Node | 'yield'>[],\n comparator: (l: Node, r: Node) => number,\n): IterableIterator<Node | 'yield'> {\n const iterators = fetches.map(i => i[Symbol.iterator]());\n let threw = false;\n try {\n const current: (Node | null)[] = [];\n let lastNodeYielded: Node | undefined;\n for (let i = 0; i < iterators.length; i++) {\n const iter = iterators[i];\n let result = iter.next();\n // yield yields when initializing\n while (!result.done && result.value === 'yield') {\n yield result.value;\n result = iter.next();\n }\n current[i] = result.done ? null : (result.value as Node);\n }\n while (current.some(c => c !== null)) {\n const min = current.reduce(\n (acc: [Node, number] | undefined, c, i): [Node, number] | undefined => {\n if (c === null) {\n return acc;\n }\n if (acc === undefined || comparator(c, acc[0]) < 0) {\n return [c, i];\n }\n return acc;\n },\n undefined,\n );\n\n assert(min !== undefined, 'min is undefined');\n const [minNode, minIndex] = min;\n const iter = iterators[minIndex];\n let result = iter.next();\n while (!result.done && result.value === 'yield') {\n yield result.value;\n result = iter.next();\n }\n current[minIndex] = result.done ? null : (result.value as Node);\n if (\n lastNodeYielded !== undefined &&\n comparator(lastNodeYielded, minNode) === 0\n ) {\n continue;\n }\n lastNodeYielded = minNode;\n yield minNode;\n }\n } catch (e) {\n threw = true;\n for (const iter of iterators) {\n try {\n iter.throw?.(e);\n } catch (_cleanupError) {\n // error in the iter.throw cleanup,\n // catch so other iterators are cleaned up\n }\n }\n throw e;\n } finally {\n if (!threw) {\n for (const iter of iterators) {\n try {\n iter.return?.();\n } catch (_cleanupError) {\n // error in the iter.return cleanup,\n // catch so other iterators are cleaned up\n }\n }\n }\n }\n}\n"],"mappings":";;;;;AAwBA,IAAa,aAAb,MAA4C;CAC1C;CACA;CACA,qBAA8B;CAC9B,UAAkB;CAClB,qBAA+B,CAAC;CAEhC,YAAY,QAAqB,QAAiB;EAChD,KAAKA,UAAU;EACf,MAAM,eAAe,OAAO,UAAU;EACtC,OAAO,SAAS,IAAI;EACpB,OAAO,aAAa,SAAS,KAAA,GAAW,kCAAkC;EAE1E,MAAM,SAAiC;GACrC,WAAW,aAAa;GACxB,SAAS,aAAa;GACtB,YAAY,aAAa;GACzB,eAAe,EACb,GAAG,aAAa,cAClB;GACA,UAAU,aAAa;GACvB,QAAQ,aAAa;GACrB,aAAa,a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AAO,QAAQ,OAAO,UAAU,SAAS;IAC/C,MAAM,OAAO;IACb,SAAS,KAAK,KAAK;GACrB;GACA,QAAQ,KAAK,OAAO,OAAO,OAAQ,OAAO;EAC5C;EACA,OAAO,QAAQ,MAAK,MAAK,MAAM,IAAI,GAAG;GACpC,MAAM,MAAM,QAAQ,QACjB,KAAiC,GAAG,MAAkC;IACrE,IAAI,MAAM,MACR,OAAO;IAET,IAAI,QAAQ,KAAA,KAAa,WAAW,GAAG,IAAI,EAAE,IAAI,GAC/C,OAAO,CAAC,GAAG,CAAC;IAEd,OAAO;GACT,GACA,KAAA,CACF;GAEA,OAAO,QAAQ,KAAA,GAAW,kBAAkB;GAC5C,MAAM,CAAC,SAAS,YAAY;GAC5B,MAAM,OAAO,UAAU;GACvB,IAAI,SAAS,KAAK,KAAK;GACvB,OAAO,CAAC,OAAO,QAAQ,OAAO,UAAU,SAAS;IAC/C,MAAM,OAAO;IACb,SAAS,KAAK,KAAK;GACrB;GACA,QAAQ,YAAY,OAAO,OAAO,OAAQ,OAAO;GACjD,IACE,oBAAoB,KAAA,KACpB,WAAW,iBAAiB,OAAO,MAAM,GAEzC;GAEF,kBAAkB;GAClB,MAAM;EACR;CACF,SAAS,GAAG;EACV,QAAQ;EACR,KAAK,MAAM,QAAQ,WACjB,IAAI;GACF,KAAK,QAAQ,CAAC;EAChB,SAAS,eAAe,CAGxB;EAEF,MAAM;CACR,UAAU;EACR,IAAI,CAAC,OACH,KAAK,MAAM,QAAQ,WACjB,IAAI;GACF,KAAK,SAAS;EAChB,SAAS,eAAe,CAGxB;CAGN;AACF"}
|
|
1
|
+
{"version":3,"file":"union-fan-in.js","names":["#inputs","#schema","#fanOutPushStarted","#pushInternalChange","#accumulatedPushes","#output"],"sources":["../../../../../zql/src/ivm/union-fan-in.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {Writable} from '../../../shared/src/writable.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport {ChangeType} from './change-type.ts';\nimport type {Change} from './change.ts';\nimport type {Constraint} from './constraint.ts';\nimport type {Node} from './data.ts';\nimport {\n throwOutput,\n type FetchRequest,\n type Input,\n type InputBase,\n type Operator,\n type Output,\n} from './operator.ts';\nimport {\n makeAddEmptyRelationships,\n mergeRelationships,\n pushAccumulatedChanges,\n} from './push-accumulated.ts';\nimport type {SourceSchema} from './schema.ts';\nimport {first, type Stream} from './stream.ts';\nimport type {UnionFanOut} from './union-fan-out.ts';\n\nexport class UnionFanIn implements Operator {\n readonly #inputs: readonly Input[];\n readonly #schema: SourceSchema;\n #fanOutPushStarted: boolean = false;\n #output: Output = throwOutput;\n #accumulatedPushes: Change[] = [];\n\n constructor(fanOut: UnionFanOut, inputs: Input[]) {\n this.#inputs = inputs;\n const fanOutSchema = fanOut.getSchema();\n fanOut.setFanIn(this);\n assert(fanOutSchema.sort !== undefined, 'UnionFanIn requires sorted input');\n\n const schema: Writable<SourceSchema> = {\n tableName: fanOutSchema.tableName,\n columns: fanOutSchema.columns,\n primaryKey: fanOutSchema.primaryKey,\n relationships: {\n ...fanOutSchema.relationships,\n },\n isHidden: fanOutSchema.isHidden,\n system: fanOutSchema.system,\n compareRows: fanOutSchema.compareRows,\n sort: fanOutSchema.sort,\n };\n\n // now go through inputs and merge relationships\n const relationshipsFromBranches: Set<string> = new Set();\n for (const input of inputs) {\n const inputSchema = input.getSchema();\n assert(\n schema.tableName === inputSchema.tableName,\n `Table name mismatch in union fan-in: ${schema.tableName} !== ${inputSchema.tableName}`,\n );\n assert(\n schema.primaryKey === inputSchema.primaryKey,\n `Primary key mismatch in union fan-in`,\n );\n assert(\n schema.system === inputSchema.system,\n `System mismatch in union fan-in: ${schema.system} !== ${inputSchema.system}`,\n );\n assert(\n schema.compareRows === inputSchema.compareRows,\n `compareRows mismatch in union fan-in`,\n );\n assert(schema.sort === inputSchema.sort, `Sort mismatch in union fan-in`);\n\n for (const [relName, relSchema] of Object.entries(\n inputSchema.relationships,\n )) {\n if (relName in fanOutSchema.relationships) {\n continue;\n }\n\n // All branches will have unique relationship names except for relationships\n // that come in from `fanOut`.\n assert(\n !relationshipsFromBranches.has(relName),\n `Relationship ${relName} exists in multiple upstream inputs to union fan-in`,\n );\n schema.relationships[relName] = relSchema;\n relationshipsFromBranches.add(relName);\n }\n\n input.setOutput(this);\n }\n\n this.#schema = schema;\n this.#inputs = inputs;\n }\n\n destroy(): void {\n for (const input of this.#inputs) {\n input.destroy();\n }\n }\n\n fetch(req: FetchRequest): Stream<Node | 'yield'> {\n const iterables = this.#inputs.map(input => input.fetch(req));\n const compareRows = this.#schema.compareRows;\n const compare = req.reverse\n ? (l: Node, r: Node) => compareRows(r.row, l.row)\n : (l: Node, r: Node) => compareRows(l.row, r.row);\n return mergeFetches(iterables, compare);\n }\n\n getSchema(): SourceSchema {\n return this.#schema;\n }\n\n *push(change: Change, pusher: InputBase): Stream<'yield'> {\n if (!this.#fanOutPushStarted) {\n yield* this.#pushInternalChange(change, pusher);\n } else {\n this.#accumulatedPushes.push(change);\n }\n }\n\n /**\n * An internal change means that a change was received inside the fan-out/fan-in sub-graph.\n *\n * These changes always come from children of a flip-join as no other push generating operators\n * currently exist between union-fan-in and union-fan-out. All other pushes\n * enter into union-fan-out before reaching union-fan-in.\n *\n * - normal joins for `exists` come before `union-fan-out`\n * - joins for `related` come after `union-fan-out`\n * - take comes after `union-fan-out`\n *\n * The algorithm for deciding whether or not to forward a push that came from inside the ufo/ufi sub-graph:\n * 1. If the change is a `child` change we can forward it. This is because all child branches in the ufo/ufi sub-graph are unique.\n * 2. If the change is `add` we can forward it iff no `fetches` for the row return any results.\n * If another branch has it, the add was already emitted in the past.\n * 3. If the change is `remove` we can forward it iff no `fetches` for the row return any results.\n * If no other branches have the change, the remove can be sent as the value is no longer present.\n * If other branches have it, the last branch the processes the remove will send the remove.\n * 4. Edits will always come through as child changes as flip join will flip them into children.\n * An edit that would result in a remove or add will have been split into an add/remove pair rather than being an edit.\n */\n *#pushInternalChange(change: Change, pusher: InputBase): Stream<'yield'> {\n if (change[ChangeIndex.TYPE] === ChangeType.CHILD) {\n yield* this.#output.push(change, this);\n return;\n }\n\n assert(\n change[ChangeIndex.TYPE] === ChangeType.ADD ||\n change[ChangeIndex.TYPE] === ChangeType.REMOVE,\n () =>\n `UnionFanIn: expected add or remove change type, got ${change[ChangeIndex.TYPE]}`,\n );\n\n let hadMatch = false;\n for (const input of this.#inputs) {\n if (input === pusher) {\n hadMatch = true;\n continue;\n }\n\n const constraint: Writable<Constraint> = {};\n for (const key of this.#schema.primaryKey) {\n constraint[key] = change[ChangeIndex.NODE].row[key];\n }\n const fetchResult = input.fetch({\n constraint,\n });\n\n if (first(fetchResult) !== undefined) {\n // Another branch has the row, so the add/remove is not needed.\n return;\n }\n }\n\n assert(hadMatch, 'Pusher was not one of the inputs to union-fan-in!');\n\n // No other branches have the row, so we can push the change.\n yield* this.#output.push(change, this);\n }\n\n fanOutStartedPushing() {\n assert(\n this.#fanOutPushStarted === false,\n 'UnionFanIn: fanOutStartedPushing called while already pushing',\n );\n this.#fanOutPushStarted = true;\n }\n\n *fanOutDonePushing(fanOutChangeType: ChangeType): Stream<'yield'> {\n assert(\n this.#fanOutPushStarted,\n 'UnionFanIn: fanOutDonePushing called without fanOutStartedPushing',\n );\n this.#fanOutPushStarted = false;\n if (this.#inputs.length === 0) {\n return;\n }\n\n if (this.#accumulatedPushes.length === 0) {\n // It is possible for no forks to pass along the push.\n // E.g., if no filters match in any fork.\n return;\n }\n\n yield* pushAccumulatedChanges(\n this.#accumulatedPushes,\n this.#output,\n this,\n fanOutChangeType,\n mergeRelationships,\n makeAddEmptyRelationships(this.#schema),\n );\n }\n\n setOutput(output: Output): void {\n this.#output = output;\n }\n}\n\nexport function* mergeFetches(\n fetches: Iterable<Node | 'yield'>[],\n comparator: (l: Node, r: Node) => number,\n): IterableIterator<Node | 'yield'> {\n const iterators = fetches.map(i => i[Symbol.iterator]());\n let threw = false;\n try {\n const current: (Node | null)[] = [];\n let lastNodeYielded: Node | undefined;\n for (let i = 0; i < iterators.length; i++) {\n const iter = iterators[i];\n let result = iter.next();\n // yield yields when initializing\n while (!result.done && result.value === 'yield') {\n yield result.value;\n result = iter.next();\n }\n current[i] = result.done ? null : (result.value as Node);\n }\n while (current.some(c => c !== null)) {\n const min = current.reduce(\n (acc: [Node, number] | undefined, c, i): [Node, number] | undefined => {\n if (c === null) {\n return acc;\n }\n if (acc === undefined || comparator(c, acc[0]) < 0) {\n return [c, i];\n }\n return acc;\n },\n undefined,\n );\n\n assert(min !== undefined, 'min is undefined');\n const [minNode, minIndex] = min;\n const iter = iterators[minIndex];\n let result = iter.next();\n while (!result.done && result.value === 'yield') {\n yield result.value;\n result = iter.next();\n }\n current[minIndex] = result.done ? null : (result.value as Node);\n if (\n lastNodeYielded !== undefined &&\n comparator(lastNodeYielded, minNode) === 0\n ) {\n continue;\n }\n lastNodeYielded = minNode;\n yield minNode;\n }\n } catch (e) {\n threw = true;\n for (const iter of iterators) {\n try {\n iter.throw?.(e);\n } catch (_cleanupError) {\n // error in the iter.throw cleanup,\n // catch so other iterators are cleaned up\n }\n }\n throw e;\n } finally {\n if (!threw) {\n for (const iter of iterators) {\n try {\n iter.return?.();\n } catch (_cleanupError) {\n // error in the iter.return cleanup,\n // catch so other iterators are cleaned up\n }\n }\n }\n }\n}\n"],"mappings":";;;;;AAwBA,IAAa,aAAb,MAA4C;CAC1C;CACA;CACA,qBAA8B;CAC9B,UAAkB;CAClB,qBAA+B,EAAE;CAEjC,YAAY,QAAqB,QAAiB;AAChD,QAAA,SAAe;EACf,MAAM,eAAe,OAAO,WAAW;AACvC,SAAO,SAAS,KAAK;AACrB,SAAO,aAAa,SAAS,KAAA,GAAW,mCAAmC;EAE3E,MAAM,SAAiC;GACrC,WAAW,aAAa;GACxB,SAAS,aAAa;GACtB,YAAY,aAAa;GACzB,eAAe,EACb,GAAG,aAAa,eACjB;GACD,UAAU,aAAa;GACvB,QAAQ,aAAa;GACrB,aAAa,aAAa;GAC1B,MAA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,OAAO;;AAE5C,SAAO,QAAQ,MAAK,MAAK,MAAM,KAAK,EAAE;GACpC,MAAM,MAAM,QAAQ,QACjB,KAAiC,GAAG,MAAkC;AACrE,QAAI,MAAM,KACR,QAAO;AAET,QAAI,QAAQ,KAAA,KAAa,WAAW,GAAG,IAAI,GAAG,GAAG,EAC/C,QAAO,CAAC,GAAG,EAAE;AAEf,WAAO;MAET,KAAA,EACD;AAED,UAAO,QAAQ,KAAA,GAAW,mBAAmB;GAC7C,MAAM,CAAC,SAAS,YAAY;GAC5B,MAAM,OAAO,UAAU;GACvB,IAAI,SAAS,KAAK,MAAM;AACxB,UAAO,CAAC,OAAO,QAAQ,OAAO,UAAU,SAAS;AAC/C,UAAM,OAAO;AACb,aAAS,KAAK,MAAM;;AAEtB,WAAQ,YAAY,OAAO,OAAO,OAAQ,OAAO;AACjD,OACE,oBAAoB,KAAA,KACpB,WAAW,iBAAiB,QAAQ,KAAK,EAEzC;AAEF,qBAAkB;AAClB,SAAM;;UAED,GAAG;AACV,UAAQ;AACR,OAAK,MAAM,QAAQ,UACjB,KAAI;AACF,QAAK,QAAQ,EAAE;WACR,eAAe;AAK1B,QAAM;WACE;AACR,MAAI,CAAC,MACH,MAAK,MAAM,QAAQ,UACjB,KAAI;AACF,QAAK,UAAU;WACR,eAAe"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"union-fan-out.js","names":["#input","#outputs","#unionFanIn","#destroyCount"],"sources":["../../../../../zql/src/ivm/union-fan-out.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport type {Change} from './change.ts';\nimport type {Node} from './data.ts';\nimport type {FetchRequest, Input, Operator, Output} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Stream} from './stream.ts';\nimport type {UnionFanIn} from './union-fan-in.ts';\n\nexport class UnionFanOut implements Operator {\n #destroyCount: number = 0;\n #unionFanIn?: UnionFanIn;\n readonly #input: Input;\n readonly #outputs: Output[] = [];\n\n constructor(input: Input) {\n this.#input = input;\n input.setOutput(this);\n }\n\n setFanIn(fanIn: UnionFanIn) {\n assert(!this.#unionFanIn, 'FanIn already set for this FanOut');\n this.#unionFanIn = fanIn;\n }\n\n *push(change: Change): Stream<'yield'> {\n must(this.#unionFanIn).fanOutStartedPushing();\n for (const output of this.#outputs) {\n yield* output.push(change, this);\n }\n yield* must(this.#unionFanIn).fanOutDonePushing(change[ChangeIndex.TYPE]);\n }\n\n setOutput(output: Output): void {\n this.#outputs.push(output);\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n fetch(req: FetchRequest): Stream<Node | 'yield'> {\n return this.#input.fetch(req);\n }\n\n destroy(): void {\n if (this.#destroyCount < this.#outputs.length) {\n ++this.#destroyCount;\n if (this.#destroyCount === this.#outputs.length) {\n this.#input.destroy();\n }\n } else {\n throw new Error('FanOut already destroyed once for each output');\n }\n }\n}\n"],"mappings":";;;AAUA,IAAa,cAAb,MAA6C;CAC3C,gBAAwB;CACxB;CACA;CACA,WAA8B,
|
|
1
|
+
{"version":3,"file":"union-fan-out.js","names":["#input","#outputs","#unionFanIn","#destroyCount"],"sources":["../../../../../zql/src/ivm/union-fan-out.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {ChangeIndex} from './change-index.ts';\nimport type {Change} from './change.ts';\nimport type {Node} from './data.ts';\nimport type {FetchRequest, Input, Operator, Output} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Stream} from './stream.ts';\nimport type {UnionFanIn} from './union-fan-in.ts';\n\nexport class UnionFanOut implements Operator {\n #destroyCount: number = 0;\n #unionFanIn?: UnionFanIn;\n readonly #input: Input;\n readonly #outputs: Output[] = [];\n\n constructor(input: Input) {\n this.#input = input;\n input.setOutput(this);\n }\n\n setFanIn(fanIn: UnionFanIn) {\n assert(!this.#unionFanIn, 'FanIn already set for this FanOut');\n this.#unionFanIn = fanIn;\n }\n\n *push(change: Change): Stream<'yield'> {\n must(this.#unionFanIn).fanOutStartedPushing();\n for (const output of this.#outputs) {\n yield* output.push(change, this);\n }\n yield* must(this.#unionFanIn).fanOutDonePushing(change[ChangeIndex.TYPE]);\n }\n\n setOutput(output: Output): void {\n this.#outputs.push(output);\n }\n\n getSchema(): SourceSchema {\n return this.#input.getSchema();\n }\n\n fetch(req: FetchRequest): Stream<Node | 'yield'> {\n return this.#input.fetch(req);\n }\n\n destroy(): void {\n if (this.#destroyCount < this.#outputs.length) {\n ++this.#destroyCount;\n if (this.#destroyCount === this.#outputs.length) {\n this.#input.destroy();\n }\n } else {\n throw new Error('FanOut already destroyed once for each output');\n }\n }\n}\n"],"mappings":";;;AAUA,IAAa,cAAb,MAA6C;CAC3C,gBAAwB;CACxB;CACA;CACA,WAA8B,EAAE;CAEhC,YAAY,OAAc;AACxB,QAAA,QAAc;AACd,QAAM,UAAU,KAAK;;CAGvB,SAAS,OAAmB;AAC1B,SAAO,CAAC,MAAA,YAAkB,oCAAoC;AAC9D,QAAA,aAAmB;;CAGrB,CAAC,KAAK,QAAiC;AACrC,OAAK,MAAA,WAAiB,CAAC,sBAAsB;AAC7C,OAAK,MAAM,UAAU,MAAA,QACnB,QAAO,OAAO,KAAK,QAAQ,KAAK;AAElC,SAAO,KAAK,MAAA,WAAiB,CAAC,kBAAkB,OAAO,GAAkB;;CAG3E,UAAU,QAAsB;AAC9B,QAAA,QAAc,KAAK,OAAO;;CAG5B,YAA0B;AACxB,SAAO,MAAA,MAAY,WAAW;;CAGhC,MAAM,KAA2C;AAC/C,SAAO,MAAA,MAAY,MAAM,IAAI;;CAG/B,UAAgB;AACd,MAAI,MAAA,eAAqB,MAAA,QAAc,QAAQ;AAC7C,KAAE,MAAA;AACF,OAAI,MAAA,iBAAuB,MAAA,QAAc,OACvC,OAAA,MAAY,SAAS;QAGvB,OAAM,IAAI,MAAM,gDAAgD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"view-apply-change.js","names":[],"sources":["../../../../../zql/src/ivm/view-apply-change.ts"],"sourcesContent":["import {\n assert,\n assertArray,\n assertNumber,\n unreachable,\n} from '../../../shared/src/asserts.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {Writable} from '../../../shared/src/writable.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport {type Comparator, type Node} from './data.ts';\nimport {skipYields} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Entry, Format} from './view.ts';\n\nexport const refCountSymbol = Symbol('rc');\nexport const idSymbol = Symbol('id');\n\ntype MetaEntry = Writable<Entry> & {\n [refCountSymbol]: number;\n [idSymbol]?: string | undefined;\n};\ntype MetaEntryList = MetaEntry[];\n\n/**\n * `applyChange` does not consume the `relationships` of `ChildChange#node`,\n * `EditChange#node` and `EditChange#oldNode`. The `ViewChange` type\n * documents and enforces this via the type system.\n */\nexport type ViewChange =\n | AddViewChange\n | RemoveViewChange\n | ChildViewChange\n | EditViewChange;\n\nexport type RowOnlyNode = {row: Row};\n\nexport type AddViewChange = {\n type: 'add';\n node: Node;\n};\n\nexport type RemoveViewChange = {\n type: 'remove';\n node: Node;\n};\n\ntype ChildViewChange = {\n type: 'child';\n node: RowOnlyNode;\n child: {\n relationshipName: string;\n change: ViewChange;\n };\n};\n\ntype EditViewChange = {\n type: 'edit';\n node: RowOnlyNode;\n oldNode: RowOnlyNode;\n};\n\n/**\n * This is a subset of WeakMap but restricted to what we need.\n * @deprecated Not used anymore. This will be removed in the future.\n */\nexport interface RefCountMap {\n get(entry: Entry): number | undefined;\n set(entry: Entry, refCount: number): void;\n delete(entry: Entry): boolean;\n}\n\nexport function applyChange(\n parentEntry: Entry,\n change: ViewChange,\n schema: SourceSchema,\n relationship: string,\n format: Format,\n withIDs = false,\n): void {\n if (schema.isHidden) {\n switch (change.type) {\n case 'add':\n case 'remove':\n for (const [relationship, children] of Object.entries(\n change.node.relationships,\n )) {\n const childSchema = must(schema.relationships[relationship]);\n for (const node of skipYields(children())) {\n applyChange(\n parentEntry,\n {type: change.type, node},\n childSchema,\n relationship,\n format,\n withIDs,\n );\n }\n }\n return;\n case 'edit':\n // If hidden at this level it means that the hidden row was changed. If\n // the row was changed in such a way that it would change the\n // relationships then the edit would have been split into remove and\n // add.\n return;\n case 'child': {\n const childSchema = must(\n schema.relationships[change.child.relationshipName],\n );\n applyChange(\n parentEntry,\n change.child.change,\n childSchema,\n relationship,\n format,\n withIDs,\n );\n return;\n }\n default:\n unreachable(change);\n }\n }\n\n const {singular, relationships: childFormats} = format;\n switch (change.type) {\n case 'add': {\n let newEntry: MetaEntry | undefined;\n\n if (singular) {\n const oldEntry = parentEntry[relationship] as MetaEntry | undefined;\n if (oldEntry !== undefined) {\n assert(\n schema.compareRows(oldEntry, change.node.row) === 0,\n `Singular relationship '${relationship}' should not have multiple rows. You may need to declare this relationship with the \\`many\\` helper instead of the \\`one\\` helper in your schema.`,\n );\n // adding same again.\n oldEntry[refCountSymbol]++;\n } else {\n newEntry = makeNewMetaEntry(change.node.row, schema, withIDs, 1);\n\n (parentEntry as Writable<Entry>)[relationship] = newEntry;\n }\n } else {\n newEntry = addToView(\n change.node.row,\n getChildEntryList(parentEntry, relationship),\n schema,\n withIDs,\n );\n }\n\n if (newEntry) {\n for (const [relationship, children] of Object.entries(\n change.node.relationships,\n )) {\n // TODO: Is there a flag to make TypeScript complain that dictionary access might be undefined?\n const childSchema = must(schema.relationships[relationship]);\n const childFormat = childFormats[relationship];\n if (childFormat === undefined) {\n continue;\n }\n\n const newView = childFormat.singular\n ? undefined\n : ([] as MetaEntryList);\n newEntry[relationship] = newView;\n\n for (const node of skipYields(children())) {\n applyChange(\n newEntry,\n {type: 'add', node},\n childSchema,\n relationship,\n childFormat,\n withIDs,\n );\n }\n }\n }\n break;\n }\n case 'remove': {\n if (singular) {\n const oldEntry = parentEntry[relationship] as MetaEntry | undefined;\n assert(oldEntry !== undefined, 'node does not exist');\n const rc = oldEntry[refCountSymbol];\n if (rc === 1) {\n (parentEntry as Writable<Entry>)[relationship] = undefined;\n }\n oldEntry[refCountSymbol]--;\n } else {\n removeAndUpdateRefCount(\n getChildEntryList(parentEntry, relationship),\n change.node.row,\n schema.compareRows,\n );\n }\n break;\n }\n case 'child': {\n let existing: MetaEntry;\n if (singular) {\n existing = getSingularEntry(parentEntry, relationship);\n } else {\n const view = getChildEntryList(parentEntry, relationship);\n const bsResult = binarySearch(\n view,\n change.node.row,\n schema.compareRows,\n );\n assert(bsResult >= 0, 'node does not exist');\n existing = view[bsResult];\n }\n\n const childSchema = must(\n schema.relationships[change.child.relationshipName],\n );\n const childFormat = format.relationships[change.child.relationshipName];\n if (childFormat !== undefined) {\n applyChange(\n existing,\n change.child.change,\n childSchema,\n change.child.relationshipName,\n childFormat,\n withIDs,\n );\n }\n break;\n }\n case 'edit': {\n if (singular) {\n const existing = parentEntry[relationship];\n assertMetaEntry(existing);\n applyEdit(existing, change, schema, withIDs);\n } else {\n const view = getChildEntryList(parentEntry, relationship);\n // The position of the row in the list may have changed due to the edit.\n if (schema.compareRows(change.oldNode.row, change.node.row) !== 0) {\n const oldBsResult = binarySearch(\n view,\n change.oldNode.row,\n schema.compareRows,\n );\n assert(oldBsResult >= 0, 'old node does not exist');\n const oldPos = oldBsResult;\n const oldEntry = view[oldPos];\n const newBsResult = binarySearch(\n view,\n change.node.row,\n schema.compareRows,\n );\n const found = newBsResult >= 0;\n const pos = found ? newBsResult : ~newBsResult;\n // A special case:\n // when refCount is 1 (so the row is being moved\n // without leaving a placeholder behind), and the new pos is\n // the same as the old, or directly after the old (so after the remove\n // of the old it would be in the same pos):\n // the row does not need to be moved, it can just be edited in place.\n if (\n oldEntry[refCountSymbol] === 1 &&\n (pos === oldPos || pos - 1 === oldPos)\n ) {\n applyEdit(oldEntry, change, schema, withIDs);\n } else {\n // Move the row. If the row has > 1 ref count, an edit should\n // be received for each ref count. On the first edit, the original\n // row is moved, the edit is applied to it and its ref count is set\n // to 1. A shallow copy of the row is left at the old pos for\n // processing of the remaining edit, and the copy's ref count\n // is decremented. As each edit is received the ref count of the\n // copy is decrement, and the ref count of the row at the new\n // position is incremented. When the copy's ref count goes to 0,\n // it is removed.\n oldEntry[refCountSymbol]--;\n let adjustedPos = pos;\n if (oldEntry[refCountSymbol] === 0) {\n view.splice(oldPos, 1);\n adjustedPos = oldPos < pos ? pos - 1 : pos;\n }\n\n let entryToEdit;\n if (found) {\n entryToEdit = view[adjustedPos];\n } else {\n view.splice(adjustedPos, 0, oldEntry);\n entryToEdit = oldEntry;\n if (oldEntry[refCountSymbol] > 0) {\n const oldEntryCopy = {...oldEntry};\n view[oldPos] = oldEntryCopy;\n }\n }\n entryToEdit[refCountSymbol]++;\n applyEdit(entryToEdit, change, schema, withIDs);\n }\n } else {\n // Position could not have changed, so simply edit in place.\n const bsResult = binarySearch(\n view,\n change.oldNode.row,\n schema.compareRows,\n );\n assert(bsResult >= 0, 'node does not exist');\n applyEdit(view[bsResult], change, schema, withIDs);\n }\n }\n\n break;\n }\n default:\n unreachable(change);\n }\n}\n\nfunction applyEdit(\n existing: MetaEntry,\n change: EditViewChange,\n schema: SourceSchema,\n withIDs: boolean,\n) {\n Object.assign(existing, change.node.row);\n if (withIDs) {\n existing[idSymbol] = makeID(change.node.row, schema);\n }\n}\n\nfunction addToView(\n row: Row,\n view: MetaEntryList,\n schema: SourceSchema,\n withIDs: boolean,\n): MetaEntry | undefined {\n const bsResult = binarySearch(view, row, schema.compareRows);\n\n if (bsResult >= 0) {\n view[bsResult][refCountSymbol]++;\n return undefined;\n }\n const pos = ~bsResult;\n const newEntry = makeNewMetaEntry(row, schema, withIDs, 1);\n view.splice(pos, 0, newEntry);\n return newEntry;\n}\n\nfunction removeAndUpdateRefCount(\n view: MetaEntryList,\n row: Row,\n compareRows: Comparator,\n): MetaEntry {\n const bsResult = binarySearch(view, row, compareRows);\n assert(bsResult >= 0, 'node does not exist');\n const oldEntry = view[bsResult];\n const rc = oldEntry[refCountSymbol];\n if (rc === 1) {\n view.splice(bsResult, 1);\n }\n oldEntry[refCountSymbol]--;\n\n return oldEntry;\n}\n\n/**\n * Binary search a sorted view.\n *\n * Returns the index of `target` if found (a non-negative integer), or\n * `~insertionIndex` if not found (always negative, following Java's\n * `Arrays.binarySearch` convention). To get the insertion index when\n * not found use the bitwise NOT: `~result`.\n *\n * This avoids allocating a `{pos, found}` result object on every call.\n */\nfunction binarySearch(\n view: MetaEntryList,\n target: Row,\n comparator: Comparator,\n): number {\n let low = 0;\n let high = view.length - 1;\n while (low <= high) {\n const mid = (low + high) >>> 1;\n const comparison = comparator(view[mid] as Row, target as Row);\n if (comparison < 0) {\n low = mid + 1;\n } else if (comparison > 0) {\n high = mid - 1;\n } else {\n return mid; // found\n }\n }\n return ~low; // not found; use ~result to get insertion index\n}\n\nfunction getChildEntryList(\n parentEntry: Entry,\n relationship: string,\n): MetaEntryList {\n const view = parentEntry[relationship];\n assertArray(view);\n return view as MetaEntryList;\n}\n\nfunction assertMetaEntry(v: unknown): asserts v is MetaEntry {\n assertNumber((v as Partial<MetaEntry>)[refCountSymbol]);\n}\n\nfunction getSingularEntry(parentEntry: Entry, relationship: string): MetaEntry {\n const e = parentEntry[relationship];\n assertNumber((e as Partial<MetaEntry>)[refCountSymbol]);\n return e as MetaEntry;\n}\n\nfunction makeNewMetaEntry(\n row: Row,\n schema: SourceSchema,\n withIDs: boolean,\n rc: number,\n): MetaEntry {\n if (withIDs) {\n return {...row, [refCountSymbol]: rc, [idSymbol]: makeID(row, schema)};\n }\n return {...row, [refCountSymbol]: rc};\n}\nfunction makeID(row: Row, schema: SourceSchema) {\n // optimization for case of non-compound primary key\n if (schema.primaryKey.length === 1) {\n return JSON.stringify(row[schema.primaryKey[0]]);\n }\n return JSON.stringify(schema.primaryKey.map(k => row[k]));\n}\n"],"mappings":";;;;;AAcA,IAAa,iBAAiB,OAAO,IAAI;AACzC,IAAa,WAAW,OAAO,IAAI;AAwDnC,SAAg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ACT,KAAK,OAAO,UAAU,CAAC;CAEzB,SAAS;CAET,OAAO;AACT;;;;;;;;;;;AAYA,SAAS,aACP,MACA,QACA,YACQ;CACR,IAAI,MAAM;CACV,IAAI,OAAO,KAAK,SAAS;CACzB,OAAO,OAAO,MAAM;EAClB,MAAM,MAAO,MAAM,SAAU;EAC7B,MAAM,aAAa,WAAW,KAAK,MAAa,MAAa;EAC7D,IAAI,aAAa,GACf,MAAM,MAAM;OACP,IAAI,aAAa,GACtB,OAAO,MAAM;OAEb,OAAO;CAEX;CACA,OAAO,CAAC;AACV;AAEA,SAAS,kBACP,aACA,cACe;CACf,MAAM,OAAO,YAAY;CACzB,YAAY,IAAI;CAChB,OAAO;AACT;AAEA,SAAS,gBAAgB,GAAoC;CAC3D,aAAc,EAAyB,eAAe;AACxD;AAEA,SAAS,iBAAiB,aAAoB,cAAiC;CAC7E,MAAM,IAAI,YAAY;CACtB,aAAc,EAAyB,eAAe;CACtD,OAAO;AACT;AAEA,SAAS,iBACP,KACA,QACA,SACA,IACW;CACX,IAAI,SACF,OAAO;EAAC,GAAG;GAAM,iBAAiB;GAAK,WAAW,OAAO,KAAK,MAAM;CAAC;CAEvE,OAAO;EAAC,GAAG;GAAM,iBAAiB;CAAE;AACtC;AACA,SAAS,OAAO,KAAU,QAAsB;CAE9C,IAAI,OAAO,WAAW,WAAW,GAC/B,OAAO,KAAK,UAAU,IAAI,OAAO,WAAW,GAAG;CAEjD,OAAO,KAAK,UAAU,OAAO,WAAW,KAAI,MAAK,IAAI,EAAE,CAAC;AAC1D"}
|
|
1
|
+
{"version":3,"file":"view-apply-change.js","names":[],"sources":["../../../../../zql/src/ivm/view-apply-change.ts"],"sourcesContent":["import {\n assert,\n assertArray,\n assertNumber,\n unreachable,\n} from '../../../shared/src/asserts.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {Writable} from '../../../shared/src/writable.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport {type Comparator, type Node} from './data.ts';\nimport {skipYields} from './operator.ts';\nimport type {SourceSchema} from './schema.ts';\nimport type {Entry, Format} from './view.ts';\n\nexport const refCountSymbol = Symbol('rc');\nexport const idSymbol = Symbol('id');\n\ntype MetaEntry = Writable<Entry> & {\n [refCountSymbol]: number;\n [idSymbol]?: string | undefined;\n};\ntype MetaEntryList = MetaEntry[];\n\n/**\n * `applyChange` does not consume the `relationships` of `ChildChange#node`,\n * `EditChange#node` and `EditChange#oldNode`. The `ViewChange` type\n * documents and enforces this via the type system.\n */\nexport type ViewChange =\n | AddViewChange\n | RemoveViewChange\n | ChildViewChange\n | EditViewChange;\n\nexport type RowOnlyNode = {row: Row};\n\nexport type AddViewChange = {\n type: 'add';\n node: Node;\n};\n\nexport type RemoveViewChange = {\n type: 'remove';\n node: Node;\n};\n\ntype ChildViewChange = {\n type: 'child';\n node: RowOnlyNode;\n child: {\n relationshipName: string;\n change: ViewChange;\n };\n};\n\ntype EditViewChange = {\n type: 'edit';\n node: RowOnlyNode;\n oldNode: RowOnlyNode;\n};\n\n/**\n * This is a subset of WeakMap but restricted to what we need.\n * @deprecated Not used anymore. This will be removed in the future.\n */\nexport interface RefCountMap {\n get(entry: Entry): number | undefined;\n set(entry: Entry, refCount: number): void;\n delete(entry: Entry): boolean;\n}\n\nexport function applyChange(\n parentEntry: Entry,\n change: ViewChange,\n schema: SourceSchema,\n relationship: string,\n format: Format,\n withIDs = false,\n): void {\n if (schema.isHidden) {\n switch (change.type) {\n case 'add':\n case 'remove':\n for (const [relationship, children] of Object.entries(\n change.node.relationships,\n )) {\n const childSchema = must(schema.relationships[relationship]);\n for (const node of skipYields(children())) {\n applyChange(\n parentEntry,\n {type: change.type, node},\n childSchema,\n relationship,\n format,\n withIDs,\n );\n }\n }\n return;\n case 'edit':\n // If hidden at this level it means that the hidden row was changed. If\n // the row was changed in such a way that it would change the\n // relationships then the edit would have been split into remove and\n // add.\n return;\n case 'child': {\n const childSchema = must(\n schema.relationships[change.child.relationshipName],\n );\n applyChange(\n parentEntry,\n change.child.change,\n childSchema,\n relationship,\n format,\n withIDs,\n );\n return;\n }\n default:\n unreachable(change);\n }\n }\n\n const {singular, relationships: childFormats} = format;\n switch (change.type) {\n case 'add': {\n let newEntry: MetaEntry | undefined;\n\n if (singular) {\n const oldEntry = parentEntry[relationship] as MetaEntry | undefined;\n if (oldEntry !== undefined) {\n assert(\n schema.compareRows(oldEntry, change.node.row) === 0,\n `Singular relationship '${relationship}' should not have multiple rows. You may need to declare this relationship with the \\`many\\` helper instead of the \\`one\\` helper in your schema.`,\n );\n // adding same again.\n oldEntry[refCountSymbol]++;\n } else {\n newEntry = makeNewMetaEntry(change.node.row, schema, withIDs, 1);\n\n (parentEntry as Writable<Entry>)[relationship] = newEntry;\n }\n } else {\n newEntry = addToView(\n change.node.row,\n getChildEntryList(parentEntry, relationship),\n schema,\n withIDs,\n );\n }\n\n if (newEntry) {\n for (const [relationship, children] of Object.entries(\n change.node.relationships,\n )) {\n // TODO: Is there a flag to make TypeScript complain that dictionary access might be undefined?\n const childSchema = must(schema.relationships[relationship]);\n const childFormat = childFormats[relationship];\n if (childFormat === undefined) {\n continue;\n }\n\n const newView = childFormat.singular\n ? undefined\n : ([] as MetaEntryList);\n newEntry[relationship] = newView;\n\n for (const node of skipYields(children())) {\n applyChange(\n newEntry,\n {type: 'add', node},\n childSchema,\n relationship,\n childFormat,\n withIDs,\n );\n }\n }\n }\n break;\n }\n case 'remove': {\n if (singular) {\n const oldEntry = parentEntry[relationship] as MetaEntry | undefined;\n assert(oldEntry !== undefined, 'node does not exist');\n const rc = oldEntry[refCountSymbol];\n if (rc === 1) {\n (parentEntry as Writable<Entry>)[relationship] = undefined;\n }\n oldEntry[refCountSymbol]--;\n } else {\n removeAndUpdateRefCount(\n getChildEntryList(parentEntry, relationship),\n change.node.row,\n schema.compareRows,\n );\n }\n break;\n }\n case 'child': {\n let existing: MetaEntry;\n if (singular) {\n existing = getSingularEntry(parentEntry, relationship);\n } else {\n const view = getChildEntryList(parentEntry, relationship);\n const bsResult = binarySearch(\n view,\n change.node.row,\n schema.compareRows,\n );\n assert(bsResult >= 0, 'node does not exist');\n existing = view[bsResult];\n }\n\n const childSchema = must(\n schema.relationships[change.child.relationshipName],\n );\n const childFormat = format.relationships[change.child.relationshipName];\n if (childFormat !== undefined) {\n applyChange(\n existing,\n change.child.change,\n childSchema,\n change.child.relationshipName,\n childFormat,\n withIDs,\n );\n }\n break;\n }\n case 'edit': {\n if (singular) {\n const existing = parentEntry[relationship];\n assertMetaEntry(existing);\n applyEdit(existing, change, schema, withIDs);\n } else {\n const view = getChildEntryList(parentEntry, relationship);\n // The position of the row in the list may have changed due to the edit.\n if (schema.compareRows(change.oldNode.row, change.node.row) !== 0) {\n const oldBsResult = binarySearch(\n view,\n change.oldNode.row,\n schema.compareRows,\n );\n assert(oldBsResult >= 0, 'old node does not exist');\n const oldPos = oldBsResult;\n const oldEntry = view[oldPos];\n const newBsResult = binarySearch(\n view,\n change.node.row,\n schema.compareRows,\n );\n const found = newBsResult >= 0;\n const pos = found ? newBsResult : ~newBsResult;\n // A special case:\n // when refCount is 1 (so the row is being moved\n // without leaving a placeholder behind), and the new pos is\n // the same as the old, or directly after the old (so after the remove\n // of the old it would be in the same pos):\n // the row does not need to be moved, it can just be edited in place.\n if (\n oldEntry[refCountSymbol] === 1 &&\n (pos === oldPos || pos - 1 === oldPos)\n ) {\n applyEdit(oldEntry, change, schema, withIDs);\n } else {\n // Move the row. If the row has > 1 ref count, an edit should\n // be received for each ref count. On the first edit, the original\n // row is moved, the edit is applied to it and its ref count is set\n // to 1. A shallow copy of the row is left at the old pos for\n // processing of the remaining edit, and the copy's ref count\n // is decremented. As each edit is received the ref count of the\n // copy is decrement, and the ref count of the row at the new\n // position is incremented. When the copy's ref count goes to 0,\n // it is removed.\n oldEntry[refCountSymbol]--;\n let adjustedPos = pos;\n if (oldEntry[refCountSymbol] === 0) {\n view.splice(oldPos, 1);\n adjustedPos = oldPos < pos ? pos - 1 : pos;\n }\n\n let entryToEdit;\n if (found) {\n entryToEdit = view[adjustedPos];\n } else {\n view.splice(adjustedPos, 0, oldEntry);\n entryToEdit = oldEntry;\n if (oldEntry[refCountSymbol] > 0) {\n const oldEntryCopy = {...oldEntry};\n view[oldPos] = oldEntryCopy;\n }\n }\n entryToEdit[refCountSymbol]++;\n applyEdit(entryToEdit, change, schema, withIDs);\n }\n } else {\n // Position could not have changed, so simply edit in place.\n const bsResult = binarySearch(\n view,\n change.oldNode.row,\n schema.compareRows,\n );\n assert(bsResult >= 0, 'node does not exist');\n applyEdit(view[bsResult], change, schema, withIDs);\n }\n }\n\n break;\n }\n default:\n unreachable(change);\n }\n}\n\nfunction applyEdit(\n existing: MetaEntry,\n change: EditViewChange,\n schema: SourceSchema,\n withIDs: boolean,\n) {\n Object.assign(existing, change.node.row);\n if (withIDs) {\n existing[idSymbol] = makeID(change.node.row, schema);\n }\n}\n\nfunction addToView(\n row: Row,\n view: MetaEntryList,\n schema: SourceSchema,\n withIDs: boolean,\n): MetaEntry | undefined {\n const bsResult = binarySearch(view, row, schema.compareRows);\n\n if (bsResult >= 0) {\n view[bsResult][refCountSymbol]++;\n return undefined;\n }\n const pos = ~bsResult;\n const newEntry = makeNewMetaEntry(row, schema, withIDs, 1);\n view.splice(pos, 0, newEntry);\n return newEntry;\n}\n\nfunction removeAndUpdateRefCount(\n view: MetaEntryList,\n row: Row,\n compareRows: Comparator,\n): MetaEntry {\n const bsResult = binarySearch(view, row, compareRows);\n assert(bsResult >= 0, 'node does not exist');\n const oldEntry = view[bsResult];\n const rc = oldEntry[refCountSymbol];\n if (rc === 1) {\n view.splice(bsResult, 1);\n }\n oldEntry[refCountSymbol]--;\n\n return oldEntry;\n}\n\n/**\n * Binary search a sorted view.\n *\n * Returns the index of `target` if found (a non-negative integer), or\n * `~insertionIndex` if not found (always negative, following Java's\n * `Arrays.binarySearch` convention). To get the insertion index when\n * not found use the bitwise NOT: `~result`.\n *\n * This avoids allocating a `{pos, found}` result object on every call.\n */\nfunction binarySearch(\n view: MetaEntryList,\n target: Row,\n comparator: Comparator,\n): number {\n let low = 0;\n let high = view.length - 1;\n while (low <= high) {\n const mid = (low + high) >>> 1;\n const comparison = comparator(view[mid] as Row, target as Row);\n if (comparison < 0) {\n low = mid + 1;\n } else if (comparison > 0) {\n high = mid - 1;\n } else {\n return mid; // found\n }\n }\n return ~low; // not found; use ~result to get insertion index\n}\n\nfunction getChildEntryList(\n parentEntry: Entry,\n relationship: string,\n): MetaEntryList {\n const view = parentEntry[relationship];\n assertArray(view);\n return view as MetaEntryList;\n}\n\nfunction assertMetaEntry(v: unknown): asserts v is MetaEntry {\n assertNumber((v as Partial<MetaEntry>)[refCountSymbol]);\n}\n\nfunction getSingularEntry(parentEntry: Entry, relationship: string): MetaEntry {\n const e = parentEntry[relationship];\n assertNumber((e as Partial<MetaEntry>)[refCountSymbol]);\n return e as MetaEntry;\n}\n\nfunction makeNewMetaEntry(\n row: Row,\n schema: SourceSchema,\n withIDs: boolean,\n rc: number,\n): MetaEntry {\n if (withIDs) {\n return {...row, [refCountSymbol]: rc, [idSymbol]: makeID(row, schema)};\n }\n return {...row, [refCountSymbol]: rc};\n}\nfunction makeID(row: Row, schema: SourceSchema) {\n // optimization for case of non-compound primary key\n if (schema.primaryKey.length === 1) {\n return JSON.stringify(row[schema.primaryKey[0]]);\n }\n return JSON.stringify(schema.primaryKey.map(k => row[k]));\n}\n"],"mappings":";;;;;AAcA,IAAa,iBAAiB,OAAO,KAAK;AAC1C,IAAa,WAAW,OAAO,KAAK;AAwDpC,SAAgB,YACd,aACA,QACA,QACA,cACA,QACA,UAAU,OACJ;AACN,KAAI,OAAO,SACT,SAAQ,OAAO,MAAf;EACE,KAAK;EACL,KAAK;AACH,QAAK,MAAM,CAAC,cAAc,aAAa,OAAO,QAC5C,OAAO,KAAK,cACb,EAAE;IACD,MAAM,cAAc,KAAK,OAAO,cAAc,cAAc;AAC5D,SAAK,MAAM,QAAQ,WAAW,UAAU,CAAC,CACvC,aACE,aACA;K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cACe;CACf,MAAM,OAAO,YAAY;AACzB,aAAY,KAAK;AACjB,QAAO;;AAGT,SAAS,gBAAgB,GAAoC;AAC3D,cAAc,EAAyB,gBAAgB;;AAGzD,SAAS,iBAAiB,aAAoB,cAAiC;CAC7E,MAAM,IAAI,YAAY;AACtB,cAAc,EAAyB,gBAAgB;AACvD,QAAO;;AAGT,SAAS,iBACP,KACA,QACA,SACA,IACW;AACX,KAAI,QACF,QAAO;EAAC,GAAG;GAAM,iBAAiB;GAAK,WAAW,OAAO,KAAK,OAAO;EAAC;AAExE,QAAO;EAAC,GAAG;GAAM,iBAAiB;EAAG;;AAEvC,SAAS,OAAO,KAAU,QAAsB;AAE9C,KAAI,OAAO,WAAW,WAAW,EAC/B,QAAO,KAAK,UAAU,IAAI,OAAO,WAAW,IAAI;AAElD,QAAO,KAAK,UAAU,OAAO,WAAW,KAAI,MAAK,IAAI,GAAG,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crud.js","names":[],"sources":["../../../../../zql/src/mutate/crud.ts"],"sourcesContent":["import type {Expand} from '../../../shared/src/expand.ts';\nimport {recordProxy} from '../../../shared/src/record-proxy.ts';\nimport type {SchemaValueToTSType} from '../../../zero-types/src/schema-value.ts';\nimport type {Schema, TableSchema} from '../../../zero-types/src/schema.ts';\nimport type {MutateCRUD} from './custom.ts';\n\nexport type SchemaCRUD<S extends Schema> = {\n [Table in keyof S['tables']]: TableCRUD<S['tables'][Table]>;\n};\n\nexport type TransactionMutate<S extends Schema> = SchemaCRUD<S>;\n\nexport type TableCRUD<S extends TableSchema> = {\n /**\n * Writes a row if a row with the same primary key doesn't already exist.\n * Non-primary-key fields that are 'optional' can be omitted or set to\n * `undefined`. Such fields will be assigned the value `null` optimistically\n * and then the default value as defined by the server.\n */\n insert: (value: InsertValue<S>) => Promise<void>;\n\n /**\n * Writes a row unconditionally, overwriting any existing row with the same\n * primary key. Non-primary-key fields that are 'optional' can be omitted or\n * set to `undefined`. Such fields will be assigned the value `null`\n * optimistically and then the default value as defined by the server.\n */\n upsert: (value: UpsertValue<S>) => Promise<void>;\n\n /**\n * Updates a row with the same primary key. If no such row exists, this\n * function does nothing. All non-primary-key fields can be omitted or set to\n * `undefined`. Such fields will be left unchanged from previous value.\n */\n update: (value: UpdateValue<S>) => Promise<void>;\n\n /**\n * Deletes the row with the specified primary key. If no such row exists, this\n * function does nothing.\n */\n delete: (id: DeleteID<S>) => Promise<void>;\n};\n\nexport type CRUDKind = keyof TableCRUD<TableSchema>;\n\nexport const CRUD_KINDS = ['insert', 'upsert', 'update', 'delete'] as const;\n\nexport type DeleteID<S extends TableSchema> = Expand<PrimaryKeyFields<S>>;\n\ntype PrimaryKeyFields<S extends TableSchema> = {\n [K in Extract<\n S['primaryKey'][number],\n keyof S['columns']\n >]: SchemaValueToTSType<S['columns'][K]>;\n};\n\nexport type InsertValue<S extends TableSchema> = Expand<\n PrimaryKeyFields<S> & {\n [K in keyof S['columns'] as S['columns'][K] extends {optional: true}\n ? K\n : never]?: SchemaValueToTSType<S['columns'][K]> | undefined;\n } & {\n [K in keyof S['columns'] as S['columns'][K] extends {optional: true}\n ? never\n : K]: SchemaValueToTSType<S['columns'][K]>;\n }\n>;\n\nexport type UpsertValue<S extends TableSchema> = InsertValue<S>;\n\nexport type UpdateValue<S extends TableSchema> = Expand<\n PrimaryKeyFields<S> & {\n [K in keyof S['columns']]?:\n | SchemaValueToTSType<S['columns'][K]>\n | undefined;\n }\n>;\n\n/**\n * This is the type of the generated mutate.<name>.<verb> function.\n */\nexport type TableMutator<TS extends TableSchema> = {\n /**\n * Writes a row if a row with the same primary key doesn't already exist.\n * Non-primary-key fields that are 'optional' can be omitted or set to\n * `undefined`. Such fields will be assigned the value `null` optimistically\n * and then the default value as defined by the server.\n */\n insert: (value: InsertValue<TS>) => Promise<void>;\n\n /**\n * Writes a row unconditionally, overwriting any existing row with the same\n * primary key. Non-primary-key fields that are 'optional' can be omitted or\n * set to `undefined`. Such fields will be assigned the value `null`\n * optimistically and then the default value as defined by the server.\n */\n upsert: (value: UpsertValue<TS>) => Promise<void>;\n\n /**\n * Updates a row with the same primary key. If no such row exists, this\n * function does nothing. All non-primary-key fields can be omitted or set to\n * `undefined`. Such fields will be left unchanged from previous value.\n */\n update: (value: UpdateValue<TS>) => Promise<void>;\n\n /**\n * Deletes the row with the specified primary key. If no such row exists, this\n * function does nothing.\n */\n delete: (id: DeleteID<TS>) => Promise<void>;\n};\n\n/**\n * A function that executes a CRUD operation.\n * Client and server provide different implementations.\n */\nexport type CRUDExecutor = (\n table: string,\n kind: CRUDKind,\n args: unknown,\n) => Promise<void>;\n\n/**\n * Creates a MutateCRUD function from a schema and executor.\n * This is the shared implementation used by both client and server.\n *\n * @param schema - The Zero schema\n * @param executor - A function that executes CRUD operations\n * @returns A MutateCRUD function that can be called with CRUDMutateRequest objects\n */\nexport function makeCRUDMutate<\n TSchema extends Schema,\n TAddSchemaCRUD extends boolean,\n>(\n schema: TSchema,\n addSchemaCRUD: TAddSchemaCRUD,\n executor: CRUDExecutor,\n): MutateCRUD<TSchema, TAddSchemaCRUD> {\n // Create a callable function that accepts CRUDMutateRequest\n const mutate = (request: AnyCRUDMutateRequest) => {\n const {table, kind, args} = request;\n return executor(table, kind, args);\n };\n\n // Only add table properties when enableLegacyMutators is true\n if (addSchemaCRUD) {\n // Add table names as keys so the proxy can discover them\n for (const tableName of Object.keys(schema.tables)) {\n (mutate as unknown as Record<string, undefined>)[tableName] = undefined;\n }\n\n // Wrap in proxy that lazily creates and caches table CRUD objects\n return recordProxy(\n mutate as unknown as Record<string, undefined>,\n (_value, tableName) => makeTableCRUD(tableName, executor),\n ) as unknown as MutateCRUD<TSchema, TAddSchemaCRUD>;\n }\n\n return mutate as MutateCRUD<TSchema, TAddSchemaCRUD>;\n}\n\nexport function makeTransactionMutate<TSchema extends Schema>(\n schema: TSchema,\n executor: CRUDExecutor,\n): TransactionMutate<TSchema> {\n const target: Record<string, undefined> = {};\n for (const tableName of Object.keys(schema.tables)) {\n target[tableName] = undefined;\n }\n\n return recordProxy(target, (_value, tableName) =>\n makeTableCRUD(tableName, executor),\n ) as SchemaCRUD<TSchema>;\n}\n\n/**\n * Creates a TableCRUD object that delegates to the executor.\n */\nfunction makeTableCRUD(\n tableName: string,\n executor: CRUDExecutor,\n): TableCRUD<TableSchema> {\n return Object.fromEntries(\n CRUD_KINDS.map(kind => [\n kind,\n (value: unknown) => executor(tableName, kind, value),\n ]),\n ) as TableCRUD<TableSchema>;\n}\n\nexport type CRUDMutator<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n TKind extends keyof TableMutator<TSchema['tables'][TTable]>,\n TArgs extends Parameters<TableMutator<TSchema['tables'][TTable]>[TKind]>[0],\n> = {\n (args: TArgs): CRUDMutateRequest<TSchema, TTable, TKind, TArgs>;\n\n /**\n * Type-only phantom property to surface mutator types in a covariant position.\n */\n ['~']: Expand<CRUDMutatorTypes<TSchema, TTable, TKind, TArgs>>;\n};\n\nexport type CRUDMutatorTypes<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n TKind extends keyof TableMutator<TSchema['tables'][TTable]>,\n TArgs extends Parameters<TableMutator<TSchema['tables'][TTable]>[TKind]>[0],\n> = 'CRUDMutator' & CRUDMutateRequest<TSchema, TTable, TKind, TArgs>;\n\nexport type CRUDMutateRequest<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'],\n TKind extends keyof TableMutator<TSchema['tables'][TTable]>,\n TArgs extends Parameters<TableMutator<TSchema['tables'][TTable]>[TKind]>[0],\n> = {\n readonly schema: TSchema;\n readonly table: TTable;\n readonly kind: TKind;\n readonly args: TArgs;\n};\n\n// oxlint-disable-next-line no-explicit-any\nexport type AnyCRUDMutateRequest = CRUDMutateRequest<any, any, CRUDKind, any>;\n"],"mappings":";;AA6CA,IAAa,aAAa;CAAC;CAAU;CAAU;CAAU;
|
|
1
|
+
{"version":3,"file":"crud.js","names":[],"sources":["../../../../../zql/src/mutate/crud.ts"],"sourcesContent":["import type {Expand} from '../../../shared/src/expand.ts';\nimport {recordProxy} from '../../../shared/src/record-proxy.ts';\nimport type {SchemaValueToTSType} from '../../../zero-types/src/schema-value.ts';\nimport type {Schema, TableSchema} from '../../../zero-types/src/schema.ts';\nimport type {MutateCRUD} from './custom.ts';\n\nexport type SchemaCRUD<S extends Schema> = {\n [Table in keyof S['tables']]: TableCRUD<S['tables'][Table]>;\n};\n\nexport type TransactionMutate<S extends Schema> = SchemaCRUD<S>;\n\nexport type TableCRUD<S extends TableSchema> = {\n /**\n * Writes a row if a row with the same primary key doesn't already exist.\n * Non-primary-key fields that are 'optional' can be omitted or set to\n * `undefined`. Such fields will be assigned the value `null` optimistically\n * and then the default value as defined by the server.\n */\n insert: (value: InsertValue<S>) => Promise<void>;\n\n /**\n * Writes a row unconditionally, overwriting any existing row with the same\n * primary key. Non-primary-key fields that are 'optional' can be omitted or\n * set to `undefined`. Such fields will be assigned the value `null`\n * optimistically and then the default value as defined by the server.\n */\n upsert: (value: UpsertValue<S>) => Promise<void>;\n\n /**\n * Updates a row with the same primary key. If no such row exists, this\n * function does nothing. All non-primary-key fields can be omitted or set to\n * `undefined`. Such fields will be left unchanged from previous value.\n */\n update: (value: UpdateValue<S>) => Promise<void>;\n\n /**\n * Deletes the row with the specified primary key. If no such row exists, this\n * function does nothing.\n */\n delete: (id: DeleteID<S>) => Promise<void>;\n};\n\nexport type CRUDKind = keyof TableCRUD<TableSchema>;\n\nexport const CRUD_KINDS = ['insert', 'upsert', 'update', 'delete'] as const;\n\nexport type DeleteID<S extends TableSchema> = Expand<PrimaryKeyFields<S>>;\n\ntype PrimaryKeyFields<S extends TableSchema> = {\n [K in Extract<\n S['primaryKey'][number],\n keyof S['columns']\n >]: SchemaValueToTSType<S['columns'][K]>;\n};\n\nexport type InsertValue<S extends TableSchema> = Expand<\n PrimaryKeyFields<S> & {\n [K in keyof S['columns'] as S['columns'][K] extends {optional: true}\n ? K\n : never]?: SchemaValueToTSType<S['columns'][K]> | undefined;\n } & {\n [K in keyof S['columns'] as S['columns'][K] extends {optional: true}\n ? never\n : K]: SchemaValueToTSType<S['columns'][K]>;\n }\n>;\n\nexport type UpsertValue<S extends TableSchema> = InsertValue<S>;\n\nexport type UpdateValue<S extends TableSchema> = Expand<\n PrimaryKeyFields<S> & {\n [K in keyof S['columns']]?:\n | SchemaValueToTSType<S['columns'][K]>\n | undefined;\n }\n>;\n\n/**\n * This is the type of the generated mutate.<name>.<verb> function.\n */\nexport type TableMutator<TS extends TableSchema> = {\n /**\n * Writes a row if a row with the same primary key doesn't already exist.\n * Non-primary-key fields that are 'optional' can be omitted or set to\n * `undefined`. Such fields will be assigned the value `null` optimistically\n * and then the default value as defined by the server.\n */\n insert: (value: InsertValue<TS>) => Promise<void>;\n\n /**\n * Writes a row unconditionally, overwriting any existing row with the same\n * primary key. Non-primary-key fields that are 'optional' can be omitted or\n * set to `undefined`. Such fields will be assigned the value `null`\n * optimistically and then the default value as defined by the server.\n */\n upsert: (value: UpsertValue<TS>) => Promise<void>;\n\n /**\n * Updates a row with the same primary key. If no such row exists, this\n * function does nothing. All non-primary-key fields can be omitted or set to\n * `undefined`. Such fields will be left unchanged from previous value.\n */\n update: (value: UpdateValue<TS>) => Promise<void>;\n\n /**\n * Deletes the row with the specified primary key. If no such row exists, this\n * function does nothing.\n */\n delete: (id: DeleteID<TS>) => Promise<void>;\n};\n\n/**\n * A function that executes a CRUD operation.\n * Client and server provide different implementations.\n */\nexport type CRUDExecutor = (\n table: string,\n kind: CRUDKind,\n args: unknown,\n) => Promise<void>;\n\n/**\n * Creates a MutateCRUD function from a schema and executor.\n * This is the shared implementation used by both client and server.\n *\n * @param schema - The Zero schema\n * @param executor - A function that executes CRUD operations\n * @returns A MutateCRUD function that can be called with CRUDMutateRequest objects\n */\nexport function makeCRUDMutate<\n TSchema extends Schema,\n TAddSchemaCRUD extends boolean,\n>(\n schema: TSchema,\n addSchemaCRUD: TAddSchemaCRUD,\n executor: CRUDExecutor,\n): MutateCRUD<TSchema, TAddSchemaCRUD> {\n // Create a callable function that accepts CRUDMutateRequest\n const mutate = (request: AnyCRUDMutateRequest) => {\n const {table, kind, args} = request;\n return executor(table, kind, args);\n };\n\n // Only add table properties when enableLegacyMutators is true\n if (addSchemaCRUD) {\n // Add table names as keys so the proxy can discover them\n for (const tableName of Object.keys(schema.tables)) {\n (mutate as unknown as Record<string, undefined>)[tableName] = undefined;\n }\n\n // Wrap in proxy that lazily creates and caches table CRUD objects\n return recordProxy(\n mutate as unknown as Record<string, undefined>,\n (_value, tableName) => makeTableCRUD(tableName, executor),\n ) as unknown as MutateCRUD<TSchema, TAddSchemaCRUD>;\n }\n\n return mutate as MutateCRUD<TSchema, TAddSchemaCRUD>;\n}\n\nexport function makeTransactionMutate<TSchema extends Schema>(\n schema: TSchema,\n executor: CRUDExecutor,\n): TransactionMutate<TSchema> {\n const target: Record<string, undefined> = {};\n for (const tableName of Object.keys(schema.tables)) {\n target[tableName] = undefined;\n }\n\n return recordProxy(target, (_value, tableName) =>\n makeTableCRUD(tableName, executor),\n ) as SchemaCRUD<TSchema>;\n}\n\n/**\n * Creates a TableCRUD object that delegates to the executor.\n */\nfunction makeTableCRUD(\n tableName: string,\n executor: CRUDExecutor,\n): TableCRUD<TableSchema> {\n return Object.fromEntries(\n CRUD_KINDS.map(kind => [\n kind,\n (value: unknown) => executor(tableName, kind, value),\n ]),\n ) as TableCRUD<TableSchema>;\n}\n\nexport type CRUDMutator<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n TKind extends keyof TableMutator<TSchema['tables'][TTable]>,\n TArgs extends Parameters<TableMutator<TSchema['tables'][TTable]>[TKind]>[0],\n> = {\n (args: TArgs): CRUDMutateRequest<TSchema, TTable, TKind, TArgs>;\n\n /**\n * Type-only phantom property to surface mutator types in a covariant position.\n */\n ['~']: Expand<CRUDMutatorTypes<TSchema, TTable, TKind, TArgs>>;\n};\n\nexport type CRUDMutatorTypes<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'] & string,\n TKind extends keyof TableMutator<TSchema['tables'][TTable]>,\n TArgs extends Parameters<TableMutator<TSchema['tables'][TTable]>[TKind]>[0],\n> = 'CRUDMutator' & CRUDMutateRequest<TSchema, TTable, TKind, TArgs>;\n\nexport type CRUDMutateRequest<\n TSchema extends Schema,\n TTable extends keyof TSchema['tables'],\n TKind extends keyof TableMutator<TSchema['tables'][TTable]>,\n TArgs extends Parameters<TableMutator<TSchema['tables'][TTable]>[TKind]>[0],\n> = {\n readonly schema: TSchema;\n readonly table: TTable;\n readonly kind: TKind;\n readonly args: TArgs;\n};\n\n// oxlint-disable-next-line no-explicit-any\nexport type AnyCRUDMutateRequest = CRUDMutateRequest<any, any, CRUDKind, any>;\n"],"mappings":";;AA6CA,IAAa,aAAa;CAAC;CAAU;CAAU;CAAU;CAAS;;;;;;;;;AAqFlE,SAAgB,eAId,QACA,eACA,UACqC;CAErC,MAAM,UAAU,YAAkC;EAChD,MAAM,EAAC,OAAO,MAAM,SAAQ;AAC5B,SAAO,SAAS,OAAO,MAAM,KAAK;;AAIpC,KAAI,eAAe;AAEjB,OAAK,MAAM,aAAa,OAAO,KAAK,OAAO,OAAO,CAC/C,QAAgD,aAAa,KAAA;AAIhE,SAAO,YACL,SACC,QAAQ,cAAc,cAAc,WAAW,SAAS,CAC1D;;AAGH,QAAO;;AAGT,SAAgB,sBACd,QACA,UAC4B;CAC5B,MAAM,SAAoC,EAAE;AAC5C,MAAK,MAAM,aAAa,OAAO,KAAK,OAAO,OAAO,CAChD,QAAO,aAAa,KAAA;AAGtB,QAAO,YAAY,SAAS,QAAQ,cAClC,cAAc,WAAW,SAAS,CACnC;;;;;AAMH,SAAS,cACP,WACA,UACwB;AACxB,QAAO,OAAO,YACZ,WAAW,KAAI,SAAQ,CACrB,OACC,UAAmB,SAAS,WAAW,MAAM,MAAM,CACrD,CAAC,CACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"custom.js","names":[],"sources":["../../../../../zql/src/mutate/custom.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {AST} from '../../../zero-protocol/src/ast.ts';\nimport type {\n DefaultSchema,\n DefaultWrappedTransaction,\n} from '../../../zero-types/src/default-types.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {ServerSchema} from '../../../zero-types/src/server-schema.ts';\nimport type {Format} from '../ivm/view.ts';\nimport type {HumanReadable, Query, RunOptions} from '../query/query.ts';\nimport type {ConditionalSchemaQuery} from '../query/schema-query.ts';\nimport type {CRUDMutateRequest, SchemaCRUD, TransactionMutate} from './crud.ts';\n\ntype ClientID = string;\n\n/**\n * A base transaction interface that any Transaction<S, T> is assignable to.\n * Used in places where the schema type doesn't need to be preserved,\n * like the public signature of Mutator.fn.\n */\nexport interface AnyTransaction {\n readonly location: Location;\n readonly clientID: string;\n readonly mutationID: number;\n readonly reason: TransactionReason;\n}\n\nexport type Location = 'client' | 'server';\nexport type TransactionReason = 'optimistic' | 'rebase' | 'authoritative';\n\nexport interface TransactionBase<S extends Schema> {\n readonly location: Location;\n readonly clientID: ClientID;\n /**\n * The ID of the mutation that is being applied.\n */\n readonly mutationID: number;\n\n /**\n * The reason for the transaction.\n */\n readonly reason: TransactionReason;\n\n readonly mutate: TransactionMutate<S>;\n /**\n * @deprecated Use {@linkcode createBuilder} with `tx.run(zql.table.where(...))` instead.\n */\n readonly query: ConditionalSchemaQuery<S>;\n\n run<TTable extends keyof S['tables'] & string, TReturn>(\n query: Query<TTable, S, TReturn>,\n options?: RunOptions,\n ): Promise<HumanReadable<TReturn>>;\n}\n\nexport type Transaction<\n S extends Schema = DefaultSchema,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = ServerTransaction<S, TWrappedTransaction> | ClientTransaction<S>;\n\nexport interface ServerTransaction<\n S extends Schema = DefaultSchema,\n TWrappedTransaction = DefaultWrappedTransaction,\n> extends TransactionBase<S> {\n readonly location: 'server';\n readonly reason: 'authoritative';\n readonly dbTransaction: DBTransaction<TWrappedTransaction>;\n}\n\n/**\n * An instance of this is passed to custom mutator implementations and\n * allows reading and writing to the database and IVM at the head at which the\n * mutator is being applied.\n */\nexport interface ClientTransaction<\n S extends Schema = DefaultSchema,\n> extends TransactionBase<S> {\n readonly location: 'client';\n readonly reason: 'optimistic' | 'rebase';\n}\n\nexport interface Row {\n [column: string]: unknown;\n}\n\nexport interface DBConnection<TWrappedTransaction> {\n transaction: <T>(\n cb: (tx: DBTransaction<TWrappedTransaction>) => Promise<T>,\n ) => Promise<T>;\n}\n\nexport interface DBTransaction<T> extends Queryable {\n readonly wrappedTransaction: T;\n runQuery<TReturn>(\n ast: AST,\n format: Format,\n schema: Schema,\n serverSchema: ServerSchema,\n ): Promise<HumanReadable<TReturn>>;\n}\n\ninterface Queryable {\n query: (query: string, args: unknown[]) => Promise<Iterable<Row>>;\n}\n\n/**\n * A callable mutate shape with optional table helpers used by helper factories\n * like `makeMutateCRUD`. Transactions expose `SchemaCRUD` instead of this type.\n */\nexport type MutateCRUD<S extends Schema, AddSchemaCRUD extends boolean> = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n (request: CRUDMutateRequest<S, any, any, any>): Promise<void>;\n} & (AddSchemaCRUD extends true ? SchemaCRUD<S> : {});\n\nexport function customMutatorKey(sep: string, parts: string[]) {\n for (const part of parts) {\n assert(\n !part.includes(sep),\n `mutator names/namespaces must not include a ${sep}`,\n );\n }\n return parts.join(sep);\n}\n"],"mappings":";;AAkHA,SAAgB,iBAAiB,KAAa,OAAiB;
|
|
1
|
+
{"version":3,"file":"custom.js","names":[],"sources":["../../../../../zql/src/mutate/custom.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport type {AST} from '../../../zero-protocol/src/ast.ts';\nimport type {\n DefaultSchema,\n DefaultWrappedTransaction,\n} from '../../../zero-types/src/default-types.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {ServerSchema} from '../../../zero-types/src/server-schema.ts';\nimport type {Format} from '../ivm/view.ts';\nimport type {HumanReadable, Query, RunOptions} from '../query/query.ts';\nimport type {ConditionalSchemaQuery} from '../query/schema-query.ts';\nimport type {CRUDMutateRequest, SchemaCRUD, TransactionMutate} from './crud.ts';\n\ntype ClientID = string;\n\n/**\n * A base transaction interface that any Transaction<S, T> is assignable to.\n * Used in places where the schema type doesn't need to be preserved,\n * like the public signature of Mutator.fn.\n */\nexport interface AnyTransaction {\n readonly location: Location;\n readonly clientID: string;\n readonly mutationID: number;\n readonly reason: TransactionReason;\n}\n\nexport type Location = 'client' | 'server';\nexport type TransactionReason = 'optimistic' | 'rebase' | 'authoritative';\n\nexport interface TransactionBase<S extends Schema> {\n readonly location: Location;\n readonly clientID: ClientID;\n /**\n * The ID of the mutation that is being applied.\n */\n readonly mutationID: number;\n\n /**\n * The reason for the transaction.\n */\n readonly reason: TransactionReason;\n\n readonly mutate: TransactionMutate<S>;\n /**\n * @deprecated Use {@linkcode createBuilder} with `tx.run(zql.table.where(...))` instead.\n */\n readonly query: ConditionalSchemaQuery<S>;\n\n run<TTable extends keyof S['tables'] & string, TReturn>(\n query: Query<TTable, S, TReturn>,\n options?: RunOptions,\n ): Promise<HumanReadable<TReturn>>;\n}\n\nexport type Transaction<\n S extends Schema = DefaultSchema,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = ServerTransaction<S, TWrappedTransaction> | ClientTransaction<S>;\n\nexport interface ServerTransaction<\n S extends Schema = DefaultSchema,\n TWrappedTransaction = DefaultWrappedTransaction,\n> extends TransactionBase<S> {\n readonly location: 'server';\n readonly reason: 'authoritative';\n readonly dbTransaction: DBTransaction<TWrappedTransaction>;\n}\n\n/**\n * An instance of this is passed to custom mutator implementations and\n * allows reading and writing to the database and IVM at the head at which the\n * mutator is being applied.\n */\nexport interface ClientTransaction<\n S extends Schema = DefaultSchema,\n> extends TransactionBase<S> {\n readonly location: 'client';\n readonly reason: 'optimistic' | 'rebase';\n}\n\nexport interface Row {\n [column: string]: unknown;\n}\n\nexport interface DBConnection<TWrappedTransaction> {\n transaction: <T>(\n cb: (tx: DBTransaction<TWrappedTransaction>) => Promise<T>,\n ) => Promise<T>;\n}\n\nexport interface DBTransaction<T> extends Queryable {\n readonly wrappedTransaction: T;\n runQuery<TReturn>(\n ast: AST,\n format: Format,\n schema: Schema,\n serverSchema: ServerSchema,\n ): Promise<HumanReadable<TReturn>>;\n}\n\ninterface Queryable {\n query: (query: string, args: unknown[]) => Promise<Iterable<Row>>;\n}\n\n/**\n * A callable mutate shape with optional table helpers used by helper factories\n * like `makeMutateCRUD`. Transactions expose `SchemaCRUD` instead of this type.\n */\nexport type MutateCRUD<S extends Schema, AddSchemaCRUD extends boolean> = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n (request: CRUDMutateRequest<S, any, any, any>): Promise<void>;\n} & (AddSchemaCRUD extends true ? SchemaCRUD<S> : {});\n\nexport function customMutatorKey(sep: string, parts: string[]) {\n for (const part of parts) {\n assert(\n !part.includes(sep),\n `mutator names/namespaces must not include a ${sep}`,\n );\n }\n return parts.join(sep);\n}\n"],"mappings":";;AAkHA,SAAgB,iBAAiB,KAAa,OAAiB;AAC7D,MAAK,MAAM,QAAQ,MACjB,QACE,CAAC,KAAK,SAAS,IAAI,EACnB,+CAA+C,MAChD;AAEH,QAAO,MAAM,KAAK,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutator-registry.js","names":[],"sources":["../../../../../zql/src/mutate/mutator-registry.ts"],"sourcesContent":["import {\n deepMerge,\n isPlainObject,\n type DeepMerge,\n} from '../../../shared/src/deep-merge.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {\n getValueAtPath,\n iterateLeaves,\n} from '../../../shared/src/object-traversal.ts';\nimport type {\n BaseDefaultSchema,\n DefaultSchema,\n} from '../../../zero-types/src/default-types.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport {validateInput} from '../query/validate-input.ts';\nimport type {Transaction} from './custom.ts';\nimport {\n isMutator,\n isMutatorDefinition,\n type AnyMutator,\n type AnyMutatorDefinition,\n type MutateRequest,\n type MutateRequestTypes,\n type Mutator,\n type MutatorDefinition,\n type MutatorExecutionFunction,\n type MutatorTypes,\n} from './mutator.ts';\n\n/**\n * Creates a MutatorRegistry from a tree of MutatorDefinitions,\n * optionally extending a base MutatorRegistry.\n *\n * @example\n * ```ts\n * // Create a new registry\n * const mutators = defineMutators({\n * user: {\n * create: defineMutator(...),\n * delete: defineMutator(...),\n * },\n * post: {\n * publish: defineMutator(...),\n * },\n * });\n *\n * // Extend an existing registry (e.g., for server-side overrides)\n * const serverMutators = defineMutators(mutators, {\n * user: {\n * create: defineMutator(...), // overrides mutators.user.create\n * },\n * // post.publish is inherited from mutators\n * });\n *\n * // Access mutators by path\n * const mr = mutators.user.create({name: 'Alice'});\n *\n * // Execute on client\n * zero.mutate(mr);\n *\n * // Execute on server\n * mr.mutator.fn({tx, ctx, args: mr.args});\n *\n * // Lookup by name (for server-side dispatch)\n * const mutator = getMutator(mutators, 'user.create');\n * ```\n */\nexport function defineMutators<\n // let MD infer freely so defaults aren't erased by a MutatorDefinitions constraint\n const MD,\n S extends BaseDefaultSchema = DefaultSchema,\n>(\n // we assert types here for clear error messages\n definitions: MD & AssertMutatorDefinitions<MD>,\n): MutatorRegistry<EnsureMutatorDefinitions<MD>, S>;\n\nexport function defineMutators<\n // same as MD above, but for TBase and TOverrides\n const TBase,\n const TOverrides,\n S extends BaseDefaultSchema = DefaultSchema,\n>(\n base:\n | MutatorRegistry<EnsureMutatorDefinitions<TBase>, S>\n | (TBase & AssertMutatorDefinitions<TBase>),\n overrides: TOverrides & AssertMutatorDefinitions<TOverrides>,\n): MutatorRegistry<\n DeepMerge<\n EnsureMutatorDefinitions<TBase>,\n EnsureMutatorDefinitions<TOverrides>,\n AnyMutatorDefinition\n >,\n S\n>;\n\nexport function defineMutators(\n definitionsOrBase: MutatorDefinitions | AnyMutatorRegistry,\n maybeOverrides?: MutatorDefinitions,\n): AnyMutatorRegistry {\n function processDefinitions(\n definitions: MutatorDefinitions,\n path: string[],\n ): Record<string | symbol, unknown> {\n const result: Record<string | symbol, unknown> = {\n ['~']: 'MutatorRegistry',\n };\n\n for (const [key, value] of Object.entries(definitions)) {\n path.push(key);\n const name = path.join('.');\n\n if (isMutatorDefinition(value)) {\n result[key] = createMutator(name, value);\n } else {\n // Nested definitions\n result[key] = processDefinitions(value, path);\n }\n path.pop();\n }\n\n return result;\n }\n\n if (maybeOverrides !== undefined) {\n // Merge base and overrides\n let base: Record<string | symbol, unknown>;\n if (!isMutatorRegistry(definitionsOrBase)) {\n base = processDefinitions(definitionsOrBase, []);\n } else {\n base = definitionsOrBase;\n }\n\n const processed = processDefinitions(maybeOverrides, []);\n\n const merged = deepMerge(base, processed, isMutatorLeaf);\n merged['~'] = 'MutatorRegistry';\n return merged as AnyMutatorRegistry;\n }\n\n return processDefinitions(\n definitionsOrBase as MutatorDefinitions,\n [],\n ) as AnyMutatorRegistry;\n}\n\nconst isMutatorLeaf = (value: unknown): boolean =>\n !isPlainObject(value) || isMutator(value);\n\n/**\n * Creates a function that can be used to define mutators with a specific schema.\n */\nexport function defineMutatorsWithType<\n TSchema extends Schema,\n>(): TypedDefineMutators<TSchema> {\n return defineMutators;\n}\n\n/**\n * The return type of defineMutatorsWithType. A function matching the\n * defineMutators overloads but with Schema pre-bound.\n */\ntype TypedDefineMutators<S extends Schema> = {\n // Single definitions\n <MD>(\n definitions: MD & AssertMutatorDefinitions<MD>,\n ): MutatorRegistry<EnsureMutatorDefinitions<MD>, S>;\n\n // Base and overrides\n <TBase, TOverrides>(\n base:\n | MutatorRegistry<EnsureMutatorDefinitions<TBase>, S>\n | (TBase & AssertMutatorDefinitions<TBase>),\n overrides: TOverrides,\n ): MutatorRegistry<\n DeepMerge<\n EnsureMutatorDefinitions<TBase>,\n EnsureMutatorDefinitions<TOverrides>,\n AnyMutatorDefinition\n >,\n S\n >;\n};\n\nexport type AssertMutatorDefinitions<MD> = MD extends MutatorDefinitions\n ? unknown\n : never;\n\nexport type EnsureMutatorDefinitions<MD> = MD extends MutatorDefinitions\n ? MD\n : never;\n\n/**\n * Checks if a value is a MutatorRegistry.\n */\nexport function isMutatorRegistry(value: unknown): value is AnyMutatorRegistry {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>)['~'] === 'MutatorRegistry'\n );\n}\n\nexport type MutatorRegistryTypes<TSchema extends Schema> = 'MutatorRegistry' & {\n readonly $schema: TSchema;\n};\n\n/**\n * The result of defineMutators(). A tree of Mutators with a tag for detection.\n */\nexport type MutatorRegistry<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n> = ToMutatorTree<MD, TSchema> & {\n ['~']: MutatorRegistryTypes<TSchema>;\n};\n\n/**\n * A branded type for use in type constraints. Use this instead of\n * `MutatorRegistry<S, C, any>` to avoid TypeScript drilling into\n * the complex ToMutatorTree structure and hitting variance issues.\n */\nexport type AnyMutatorRegistry = {\n ['~']: MutatorRegistryTypes<Schema>;\n [key: string]: unknown;\n};\n\n/**\n * Transforms a MutatorDefinitions into a tree of Mutators.\n * Each MutatorDefinition becomes a Mutator at the same path.\n * Uses TInput for the callable args (TOutput is only used internally for validation).\n */\nexport type ToMutatorTree<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n> = {\n readonly [K in keyof MD]: MD[K] extends AnyMutatorDefinition\n ? // pull types from the phantom property\n Mutator<\n MD[K]['~']['$input'],\n TSchema,\n MD[K]['~']['$context'],\n MD[K]['~']['$wrappedTransaction']\n >\n : MD[K] extends MutatorDefinitions\n ? ToMutatorTree<MD[K], TSchema>\n : never;\n};\n\nexport type FromMutatorTree<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n> = {\n readonly [K in keyof MD]: MD[K] extends AnyMutatorDefinition\n ? // pull types from the phantom property\n Mutator<\n ReadonlyJSONValue | undefined, // intentionally left as generic to avoid variance issues\n TSchema,\n MD[K]['~']['$context'],\n MD[K]['~']['$wrappedTransaction']\n >\n : MD[K] extends MutatorDefinitions\n ? FromMutatorTree<MD[K], TSchema>\n : never;\n}[keyof MD];\n\n/**\n * A tree of MutatorDefinitions, possibly nested.\n */\nexport type MutatorDefinitions = {\n readonly [key: string]: AnyMutatorDefinition | MutatorDefinitions;\n};\n\nfunction createMutator<\n ArgsInput extends ReadonlyJSONValue | undefined,\n ArgsOutput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n C,\n TWrappedTransaction,\n>(\n name: string,\n definition: MutatorDefinition<ArgsInput, ArgsOutput, C, TWrappedTransaction>,\n): Mutator<ArgsInput, TSchema, C, TWrappedTransaction> {\n const {validator} = definition;\n\n // fn takes ReadonlyJSONValue args because it's called during rebase (from\n // stored JSON) and on the server (from wire format). Validation happens here.\n const fn: MutatorExecutionFunction<\n ArgsInput,\n C,\n Transaction<TSchema, TWrappedTransaction>\n > = async options => {\n const validatedArgs = validator\n ? validateInput(name, options.args, validator, 'mutator')\n : (options.args as unknown as ArgsOutput);\n await definition.fn({\n args: validatedArgs,\n ctx: options.ctx as C,\n tx: options.tx,\n });\n };\n\n const mutator = (\n args: ArgsInput,\n ): MutateRequest<ArgsInput, TSchema, C, TWrappedTransaction> => ({\n args,\n '~': 'MutateRequest' as MutateRequestTypes<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >,\n 'mutator': mutator as unknown as Mutator<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >,\n });\n\n mutator.mutatorName = name;\n mutator.fn = fn;\n mutator['~'] = 'Mutator' as unknown as MutatorTypes<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >;\n\n return mutator as unknown as Mutator<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >;\n}\n\nexport function* iterateMutators(\n registry: AnyMutatorRegistry,\n): Iterable<AnyMutator> {\n yield* iterateLeaves(registry, isMutator);\n}\n\n/**\n * Gets a Mutator by its dot-separated name from a MutatorRegistry.\n * Returns undefined if not found.\n */\nexport function getMutator<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n>(\n registry: MutatorRegistry<MD, TSchema>,\n name: string,\n): FromMutatorTree<MD, TSchema> | undefined {\n const m = getValueAtPath(registry, name, '.');\n return m as FromMutatorTree<MD, TSchema> | undefined;\n}\n\n/**\n * Gets a Mutator by its dot-separated name from a MutatorRegistry.\n * Throws if not found.\n */\nexport function mustGetMutator<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n>(\n registry: MutatorRegistry<MD, TSchema>,\n name: string,\n): FromMutatorTree<MD, TSchema> {\n const mutator = getMutator(registry, name);\n if (mutator === undefined) {\n throw new Error(`Mutator not found: ${name}`);\n }\n return mutator;\n}\n"],"mappings":";;;;;AAgGA,SAAgB,eACd,mBACA,gBACoB;CACpB,SAAS,mBACP,aACA,MACkC;EAClC,MAAM,SAA2C,GAC9C,MAAM,kBACT;EAEA,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,WAAW,GAAG;GACtD,KAAK,KAAK,GAAG;GACb,MAAM,OAAO,KAAK,KAAK,GAAG;GAE1B,IAAI,oBAAoB,KAAK,GAC3B,OAAO,OAAO,cAAc,MAAM,KAAK;QAGvC,OAAO,OAAO,mBAAmB,OAAO,IAAI;GAE9C,KAAK,IAAI;EACX;EAEA,OAAO;CACT;CAEA,IAAI,mBAAmB,KAAA,GAAW;EAEhC,IAAI;EACJ,IAAI,CAAC,kBAAkB,iBAAiB,GACtC,OAAO,mBAAmB,mBAAmB,CAAC,CAAC;OAE/C,OAAO;EAGT,MAAM,YAAY,mBAAmB,gBAAgB,CAAC,CAAC;EAEvD,MAAM,SAAS,UAAU,MAAM,WAAW,aAAa;EACvD,OAAO,OAAO;EACd,OAAO;CACT;CAEA,OAAO,mBACL,mBACA,CAAC,CACH;AACF;AAEA,IAAM,iBAAiB,UACrB,CAAC,cAAc,KAAK,KAAK,UAAU,KAAK;;;;AAK1C,SAAgB,yBAEkB;CAChC,OAAO;AACT;;;;AAuCA,SAAgB,kBAAkB,OAA6C;CAC7E,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,SAAS;AAEhD;AAwEA,SAAS,cAOP,MACA,YACqD;CACrD,MAAM,EAAC,cAAa;CAIpB,MAAM,KAIF,OAAM,YAAW;EACnB,MAAM,gBAAgB,YAClB,cAAc,MAAM,QAAQ,MAAM,WAAW,SAAS,IACrD,QAAQ;EACb,MAAM,WAAW,GAAG;GAClB,MAAM;GACN,KAAK,QAAQ;GACb,IAAI,QAAQ;EACd,CAAC;CACH;CAEA,MAAM,WACJ,UAC+D;EAC/D;EACA,KAAK;EAML,WAAW;CAMb;CAEA,QAAQ,cAAc;CACtB,QAAQ,KAAK;CACb,QAAQ,OAAO;CAOf,OAAO;AAMT;AAEA,UAAiB,gBACf,UACsB;CACtB,OAAO,cAAc,UAAU,SAAS;AAC1C;;;;;AAMA,SAAgB,WAId,UACA,MAC0C;CAE1C,OADU,eAAe,UAAU,MAAM,GAClC;AACT;;;;;AAMA,SAAgB,eAId,UACA,MAC8B;CAC9B,MAAM,UAAU,WAAW,UAAU,IAAI;CACzC,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,MAAM,sBAAsB,MAAM;CAE9C,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"mutator-registry.js","names":[],"sources":["../../../../../zql/src/mutate/mutator-registry.ts"],"sourcesContent":["import {\n deepMerge,\n isPlainObject,\n type DeepMerge,\n} from '../../../shared/src/deep-merge.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {\n getValueAtPath,\n iterateLeaves,\n} from '../../../shared/src/object-traversal.ts';\nimport type {\n BaseDefaultSchema,\n DefaultSchema,\n} from '../../../zero-types/src/default-types.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport {validateInput} from '../query/validate-input.ts';\nimport type {Transaction} from './custom.ts';\nimport {\n isMutator,\n isMutatorDefinition,\n type AnyMutator,\n type AnyMutatorDefinition,\n type MutateRequest,\n type MutateRequestTypes,\n type Mutator,\n type MutatorDefinition,\n type MutatorExecutionFunction,\n type MutatorTypes,\n} from './mutator.ts';\n\n/**\n * Creates a MutatorRegistry from a tree of MutatorDefinitions,\n * optionally extending a base MutatorRegistry.\n *\n * @example\n * ```ts\n * // Create a new registry\n * const mutators = defineMutators({\n * user: {\n * create: defineMutator(...),\n * delete: defineMutator(...),\n * },\n * post: {\n * publish: defineMutator(...),\n * },\n * });\n *\n * // Extend an existing registry (e.g., for server-side overrides)\n * const serverMutators = defineMutators(mutators, {\n * user: {\n * create: defineMutator(...), // overrides mutators.user.create\n * },\n * // post.publish is inherited from mutators\n * });\n *\n * // Access mutators by path\n * const mr = mutators.user.create({name: 'Alice'});\n *\n * // Execute on client\n * zero.mutate(mr);\n *\n * // Execute on server\n * mr.mutator.fn({tx, ctx, args: mr.args});\n *\n * // Lookup by name (for server-side dispatch)\n * const mutator = getMutator(mutators, 'user.create');\n * ```\n */\nexport function defineMutators<\n // let MD infer freely so defaults aren't erased by a MutatorDefinitions constraint\n const MD,\n S extends BaseDefaultSchema = DefaultSchema,\n>(\n // we assert types here for clear error messages\n definitions: MD & AssertMutatorDefinitions<MD>,\n): MutatorRegistry<EnsureMutatorDefinitions<MD>, S>;\n\nexport function defineMutators<\n // same as MD above, but for TBase and TOverrides\n const TBase,\n const TOverrides,\n S extends BaseDefaultSchema = DefaultSchema,\n>(\n base:\n | MutatorRegistry<EnsureMutatorDefinitions<TBase>, S>\n | (TBase & AssertMutatorDefinitions<TBase>),\n overrides: TOverrides & AssertMutatorDefinitions<TOverrides>,\n): MutatorRegistry<\n DeepMerge<\n EnsureMutatorDefinitions<TBase>,\n EnsureMutatorDefinitions<TOverrides>,\n AnyMutatorDefinition\n >,\n S\n>;\n\nexport function defineMutators(\n definitionsOrBase: MutatorDefinitions | AnyMutatorRegistry,\n maybeOverrides?: MutatorDefinitions,\n): AnyMutatorRegistry {\n function processDefinitions(\n definitions: MutatorDefinitions,\n path: string[],\n ): Record<string | symbol, unknown> {\n const result: Record<string | symbol, unknown> = {\n ['~']: 'MutatorRegistry',\n };\n\n for (const [key, value] of Object.entries(definitions)) {\n path.push(key);\n const name = path.join('.');\n\n if (isMutatorDefinition(value)) {\n result[key] = createMutator(name, value);\n } else {\n // Nested definitions\n result[key] = processDefinitions(value, path);\n }\n path.pop();\n }\n\n return result;\n }\n\n if (maybeOverrides !== undefined) {\n // Merge base and overrides\n let base: Record<string | symbol, unknown>;\n if (!isMutatorRegistry(definitionsOrBase)) {\n base = processDefinitions(definitionsOrBase, []);\n } else {\n base = definitionsOrBase;\n }\n\n const processed = processDefinitions(maybeOverrides, []);\n\n const merged = deepMerge(base, processed, isMutatorLeaf);\n merged['~'] = 'MutatorRegistry';\n return merged as AnyMutatorRegistry;\n }\n\n return processDefinitions(\n definitionsOrBase as MutatorDefinitions,\n [],\n ) as AnyMutatorRegistry;\n}\n\nconst isMutatorLeaf = (value: unknown): boolean =>\n !isPlainObject(value) || isMutator(value);\n\n/**\n * Creates a function that can be used to define mutators with a specific schema.\n */\nexport function defineMutatorsWithType<\n TSchema extends Schema,\n>(): TypedDefineMutators<TSchema> {\n return defineMutators;\n}\n\n/**\n * The return type of defineMutatorsWithType. A function matching the\n * defineMutators overloads but with Schema pre-bound.\n */\ntype TypedDefineMutators<S extends Schema> = {\n // Single definitions\n <MD>(\n definitions: MD & AssertMutatorDefinitions<MD>,\n ): MutatorRegistry<EnsureMutatorDefinitions<MD>, S>;\n\n // Base and overrides\n <TBase, TOverrides>(\n base:\n | MutatorRegistry<EnsureMutatorDefinitions<TBase>, S>\n | (TBase & AssertMutatorDefinitions<TBase>),\n overrides: TOverrides,\n ): MutatorRegistry<\n DeepMerge<\n EnsureMutatorDefinitions<TBase>,\n EnsureMutatorDefinitions<TOverrides>,\n AnyMutatorDefinition\n >,\n S\n >;\n};\n\nexport type AssertMutatorDefinitions<MD> = MD extends MutatorDefinitions\n ? unknown\n : never;\n\nexport type EnsureMutatorDefinitions<MD> = MD extends MutatorDefinitions\n ? MD\n : never;\n\n/**\n * Checks if a value is a MutatorRegistry.\n */\nexport function isMutatorRegistry(value: unknown): value is AnyMutatorRegistry {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>)['~'] === 'MutatorRegistry'\n );\n}\n\nexport type MutatorRegistryTypes<TSchema extends Schema> = 'MutatorRegistry' & {\n readonly $schema: TSchema;\n};\n\n/**\n * The result of defineMutators(). A tree of Mutators with a tag for detection.\n */\nexport type MutatorRegistry<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n> = ToMutatorTree<MD, TSchema> & {\n ['~']: MutatorRegistryTypes<TSchema>;\n};\n\n/**\n * A branded type for use in type constraints. Use this instead of\n * `MutatorRegistry<S, C, any>` to avoid TypeScript drilling into\n * the complex ToMutatorTree structure and hitting variance issues.\n */\nexport type AnyMutatorRegistry = {\n ['~']: MutatorRegistryTypes<Schema>;\n [key: string]: unknown;\n};\n\n/**\n * Transforms a MutatorDefinitions into a tree of Mutators.\n * Each MutatorDefinition becomes a Mutator at the same path.\n * Uses TInput for the callable args (TOutput is only used internally for validation).\n */\nexport type ToMutatorTree<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n> = {\n readonly [K in keyof MD]: MD[K] extends AnyMutatorDefinition\n ? // pull types from the phantom property\n Mutator<\n MD[K]['~']['$input'],\n TSchema,\n MD[K]['~']['$context'],\n MD[K]['~']['$wrappedTransaction']\n >\n : MD[K] extends MutatorDefinitions\n ? ToMutatorTree<MD[K], TSchema>\n : never;\n};\n\nexport type FromMutatorTree<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n> = {\n readonly [K in keyof MD]: MD[K] extends AnyMutatorDefinition\n ? // pull types from the phantom property\n Mutator<\n ReadonlyJSONValue | undefined, // intentionally left as generic to avoid variance issues\n TSchema,\n MD[K]['~']['$context'],\n MD[K]['~']['$wrappedTransaction']\n >\n : MD[K] extends MutatorDefinitions\n ? FromMutatorTree<MD[K], TSchema>\n : never;\n}[keyof MD];\n\n/**\n * A tree of MutatorDefinitions, possibly nested.\n */\nexport type MutatorDefinitions = {\n readonly [key: string]: AnyMutatorDefinition | MutatorDefinitions;\n};\n\nfunction createMutator<\n ArgsInput extends ReadonlyJSONValue | undefined,\n ArgsOutput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n C,\n TWrappedTransaction,\n>(\n name: string,\n definition: MutatorDefinition<ArgsInput, ArgsOutput, C, TWrappedTransaction>,\n): Mutator<ArgsInput, TSchema, C, TWrappedTransaction> {\n const {validator} = definition;\n\n // fn takes ReadonlyJSONValue args because it's called during rebase (from\n // stored JSON) and on the server (from wire format). Validation happens here.\n const fn: MutatorExecutionFunction<\n ArgsInput,\n C,\n Transaction<TSchema, TWrappedTransaction>\n > = async options => {\n const validatedArgs = validator\n ? validateInput(name, options.args, validator, 'mutator')\n : (options.args as unknown as ArgsOutput);\n await definition.fn({\n args: validatedArgs,\n ctx: options.ctx as C,\n tx: options.tx,\n });\n };\n\n const mutator = (\n args: ArgsInput,\n ): MutateRequest<ArgsInput, TSchema, C, TWrappedTransaction> => ({\n args,\n '~': 'MutateRequest' as MutateRequestTypes<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >,\n 'mutator': mutator as unknown as Mutator<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >,\n });\n\n mutator.mutatorName = name;\n mutator.fn = fn;\n mutator['~'] = 'Mutator' as unknown as MutatorTypes<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >;\n\n return mutator as unknown as Mutator<\n ArgsInput,\n TSchema,\n C,\n TWrappedTransaction\n >;\n}\n\nexport function* iterateMutators(\n registry: AnyMutatorRegistry,\n): Iterable<AnyMutator> {\n yield* iterateLeaves(registry, isMutator);\n}\n\n/**\n * Gets a Mutator by its dot-separated name from a MutatorRegistry.\n * Returns undefined if not found.\n */\nexport function getMutator<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n>(\n registry: MutatorRegistry<MD, TSchema>,\n name: string,\n): FromMutatorTree<MD, TSchema> | undefined {\n const m = getValueAtPath(registry, name, '.');\n return m as FromMutatorTree<MD, TSchema> | undefined;\n}\n\n/**\n * Gets a Mutator by its dot-separated name from a MutatorRegistry.\n * Throws if not found.\n */\nexport function mustGetMutator<\n MD extends MutatorDefinitions,\n TSchema extends Schema,\n>(\n registry: MutatorRegistry<MD, TSchema>,\n name: string,\n): FromMutatorTree<MD, TSchema> {\n const mutator = getMutator(registry, name);\n if (mutator === undefined) {\n throw new Error(`Mutator not found: ${name}`);\n }\n return mutator;\n}\n"],"mappings":";;;;;AAgGA,SAAgB,eACd,mBACA,gBACoB;CACpB,SAAS,mBACP,aACA,MACkC;EAClC,MAAM,SAA2C,GAC9C,MAAM,mBACR;AAED,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,YAAY,EAAE;AACtD,QAAK,KAAK,IAAI;GACd,MAAM,OAAO,KAAK,KAAK,IAAI;AAE3B,OAAI,oBAAoB,MAAM,CAC5B,QAAO,OAAO,cAAc,MAAM,MAAM;OAGxC,QAAO,OAAO,mBAAmB,OAAO,KAAK;AAE/C,QAAK,KAAK;;AAGZ,SAAO;;AAGT,KAAI,mBAAmB,KAAA,GAAW;EAEhC,IAAI;AACJ,MAAI,CAAC,kBAAkB,kBAAkB,CACvC,QAAO,mBAAmB,mBAAmB,EAAE,CAAC;MAEhD,QAAO;EAGT,MAAM,YAAY,mBAAmB,gBAAgB,EAAE,CAAC;EAExD,MAAM,SAAS,UAAU,MAAM,WAAW,cAAc;AACxD,SAAO,OAAO;AACd,SAAO;;AAGT,QAAO,mBACL,mBACA,EAAE,CACH;;AAGH,IAAM,iBAAiB,UACrB,CAAC,cAAc,MAAM,IAAI,UAAU,MAAM;;;;AAK3C,SAAgB,yBAEkB;AAChC,QAAO;;;;;AAwCT,SAAgB,kBAAkB,OAA6C;AAC7E,QACE,OAAO,UAAU,YACjB,UAAU,QACT,MAAkC,SAAS;;AA0EhD,SAAS,cAOP,MACA,YACqD;CACrD,MAAM,EAAC,cAAa;CAIpB,MAAM,KAIF,OAAM,YAAW;EACnB,MAAM,gBAAgB,YAClB,cAAc,MAAM,QAAQ,MAAM,WAAW,UAAU,GACtD,QAAQ;AACb,QAAM,WAAW,GAAG;GAClB,MAAM;GACN,KAAK,QAAQ;GACb,IAAI,QAAQ;GACb,CAAC;;CAGJ,MAAM,WACJ,UAC+D;EAC/D;EACA,KAAK;EAML,WAAW;EAMZ;AAED,SAAQ,cAAc;AACtB,SAAQ,KAAK;AACb,SAAQ,OAAO;AAOf,QAAO;;AAQT,UAAiB,gBACf,UACsB;AACtB,QAAO,cAAc,UAAU,UAAU;;;;;;AAO3C,SAAgB,WAId,UACA,MAC0C;AAE1C,QADU,eAAe,UAAU,MAAM,IAAI;;;;;;AAQ/C,SAAgB,eAId,UACA,MAC8B;CAC9B,MAAM,UAAU,WAAW,UAAU,KAAK;AAC1C,KAAI,YAAY,KAAA,EACd,OAAM,IAAI,MAAM,sBAAsB,OAAO;AAE/C,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutator.js","names":[],"sources":["../../../../../zql/src/mutate/mutator.ts"],"sourcesContent":["import type {StandardSchemaV1} from '@standard-schema/spec';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {\n DefaultContext,\n DefaultSchema,\n DefaultWrappedTransaction,\n IsUnknown,\n} from '../../../zero-types/src/default-types.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {AnyTransaction, Transaction} from './custom.ts';\n\n// ----------------------------------------------------------------------------\n// defineMutator\n// ----------------------------------------------------------------------------\n\nexport type MutatorDefinitionTypes<\n TInput extends ReadonlyJSONValue | undefined,\n TOutput,\n TContext,\n TWrappedTransaction,\n> = 'MutatorDefinition' & {\n readonly $input: TInput;\n readonly $output: TOutput;\n readonly $context: TContext;\n readonly $wrappedTransaction: TWrappedTransaction;\n};\n\nexport type MutatorDefinition<\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = {\n readonly 'fn': MutatorDefinitionFunction<TOutput, TContext, AnyTransaction>;\n readonly 'validator': StandardSchemaV1<TInput, TOutput> | undefined;\n readonly '~': MutatorDefinitionTypes<\n TInput,\n TOutput,\n TContext,\n TWrappedTransaction\n >;\n};\n\n// oxlint-disable-next-line no-explicit-any\nexport type AnyMutatorDefinition = MutatorDefinition<any, any, any, any>;\n\nexport function isMutatorDefinition(f: unknown): f is AnyMutatorDefinition {\n return (\n typeof f === 'object' &&\n f !== null &&\n (f as {['~']?: unknown})['~'] === 'MutatorDefinition'\n );\n}\n\n// Overload for no validator\nexport function defineMutator<\n TInput extends ReadonlyJSONValue | undefined = ReadonlyJSONValue | undefined,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n>(\n mutator: MutatorDefinitionFunction<\n TInput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n): MutatorDefinition<TInput, TInput, TContext, TWrappedTransaction>;\n\n// Overload for validator\nexport function defineMutator<\n TInput extends ReadonlyJSONValue | undefined = undefined,\n TOutput extends ReadonlyJSONValue | undefined = TInput,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n>(\n validator: StandardSchemaV1<TInput, TOutput>,\n mutator: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n): MutatorDefinition<TInput, TOutput, TContext, TWrappedTransaction>;\n\n// Implementation\nexport function defineMutator<\n TInput extends ReadonlyJSONValue | undefined = undefined,\n TOutput extends ReadonlyJSONValue | undefined = TInput,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n>(\n validatorOrMutator:\n | StandardSchemaV1<TInput, TOutput>\n | MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n mutator?: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n): MutatorDefinition<TInput, TOutput, TContext, TWrappedTransaction> {\n let validator: StandardSchemaV1<TInput, TOutput> | undefined;\n let actualMutator: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >;\n\n if ('~standard' in validatorOrMutator) {\n // defineMutator(validator, mutator)\n validator = validatorOrMutator;\n actualMutator = must(mutator);\n } else {\n // defineMutator(mutator) - no validator\n validator = undefined;\n actualMutator = validatorOrMutator;\n }\n\n const mutatorDefinition: MutatorDefinition<\n TInput,\n TOutput,\n TContext,\n TWrappedTransaction\n > = {\n 'fn': actualMutator as MutatorDefinitionFunction<\n TOutput,\n TContext,\n AnyTransaction\n >,\n 'validator': validator,\n '~': 'MutatorDefinition' as unknown as MutatorDefinitionTypes<\n TInput,\n TOutput,\n TContext,\n TWrappedTransaction\n >,\n };\n return mutatorDefinition;\n}\n\n// intentionally not using DefaultSchema, DefaultContext, or DefaultWrappedTransaction\nexport function defineMutatorWithType<\n TSchema extends Schema,\n TContext = unknown,\n TWrappedTransaction = unknown,\n>(): TypedDefineMutator<TSchema, TContext, TWrappedTransaction> {\n return defineMutator;\n}\n\n/**\n * The return type of defineMutatorWithType. A function matching the\n * defineMutator overloads but with Schema, Context, and WrappedTransaction\n * pre-bound.\n *\n * This is used as a workaround to using DefaultTypes (e.g. when using\n * multiple Zero instances).\n */\ntype TypedDefineMutator<\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = {\n // Without validator\n <TArgs extends ReadonlyJSONValue | undefined>(\n mutator: MutatorDefinitionFunction<\n TArgs,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n ): MutatorDefinition<TArgs, TArgs, TContext, TWrappedTransaction>;\n\n // With validator\n <\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n >(\n validator: StandardSchemaV1<TInput, TOutput>,\n mutator: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n ): MutatorDefinition<TInput, TOutput, TContext, TWrappedTransaction>;\n};\n\nexport type MutatorDefinitionFunction<\n TOutput extends ReadonlyJSONValue | undefined,\n TContext,\n TTransaction,\n> = (options: {\n args: TOutput;\n ctx: TContext;\n tx: TTransaction;\n}) => Promise<void>;\n\nexport type MutatorExecutionFunction<\n TOutput extends ReadonlyJSONValue | undefined,\n TContext,\n TTransaction,\n> = (\n options: MutatorExecutionOptions<TOutput, TContext, TTransaction>,\n) => Promise<void>;\n\ntype MutatorExecutionOptions<\n TOutput extends ReadonlyJSONValue | undefined,\n TContext,\n TTransaction,\n> = undefined extends TOutput\n ? IsUnknown<TContext> extends true\n ? {args?: TOutput | undefined; tx: TTransaction; ctx?: TContext | undefined}\n : {args?: TOutput | undefined; tx: TTransaction; ctx: TContext}\n : IsUnknown<TContext> extends true\n ? {args: TOutput; tx: TTransaction; ctx?: TContext | undefined}\n : {args: TOutput; tx: TTransaction; ctx: TContext};\n\n// ----------------------------------------------------------------------------\n// Mutator and MutateRequest types\n// ----------------------------------------------------------------------------\n\nexport type MutatorTypes<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = 'Mutator' & {\n readonly $input: TInput;\n readonly $schema: TSchema;\n readonly $context: TContext;\n readonly $wrappedTransaction: TWrappedTransaction;\n};\n\n/**\n * A callable wrapper around a MutatorDefinition, created by `defineMutators()`.\n *\n * Accessed like `mutators.foo.bar`, and called to create a MutateRequest:\n * `mutators.foo.bar(42)` returns a `MutateRequest`.\n *\n * The `fn` property is used for execution and takes raw JSON args (for rebase\n * and server wire format cases) that are validated internally.\n */\nexport type Mutator<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = {\n readonly 'mutatorName': string;\n /**\n * Execute the mutation. Args are ReadonlyJSONValue because this is called\n * during rebase (from stored JSON) and on the server (from wire format).\n * Validation happens internally before the recipe function runs.\n */\n readonly 'fn': MutatorExecutionFunction<\n TInput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >;\n readonly '~': MutatorTypes<TInput, TSchema, TContext, TWrappedTransaction>;\n} & MutatorCallable<TInput, TSchema, TContext, TWrappedTransaction>;\n\n// Helper type for the callable part of Mutator\n// When TInput is undefined, the function is callable with 0 args\n// When TInput includes undefined (optional), args is optional\n// Otherwise, args is required\ntype MutatorCallable<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = [TInput] extends [undefined]\n ? () => MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>\n : undefined extends TInput\n ? {\n (): MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>;\n (\n args?: TInput,\n ): MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>;\n }\n : {\n (\n args: TInput,\n ): MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>;\n };\n\n// oxlint-disable-next-line no-explicit-any\nexport type AnyMutator = Mutator<any, any, any, any>;\n\n/**\n * Checks if a value is a Mutator (the result of processing a MutatorDefinition\n * through defineMutators).\n */\nexport function isMutator<S extends Schema>(\n value: unknown,\n // oxlint-disable-next-line no-explicit-any\n): value is Mutator<any, S, any, any> {\n return (\n typeof value === 'function' &&\n typeof (value as {mutatorName?: unknown}).mutatorName === 'string' &&\n typeof (value as {fn?: unknown}).fn === 'function'\n );\n}\n\nexport type MutateRequestTypes<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = 'MutateRequest' & {\n readonly $input: TInput;\n readonly $schema: TSchema;\n readonly $context: TContext;\n readonly $wrappedTransaction: TWrappedTransaction;\n};\n\n/**\n * The result of calling a Mutator with arguments.\n *\n * Created by `mutators.foo.bar(42)`, executed by `zero.mutate(mr)` on the client\n * or `mr.mutator.fn({tx, ctx, args: mr.args})` on the server.\n */\nexport type MutateRequest<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = {\n readonly 'mutator': Mutator<TInput, TSchema, TContext, TWrappedTransaction>;\n readonly 'args': TInput;\n readonly '~': MutateRequestTypes<\n TInput,\n TSchema,\n TContext,\n TWrappedTransaction\n >;\n};\n"],"mappings":";;AA+CA,SAAgB,oBAAoB,GAAuC;CACzE,OACE,OAAO,MAAM,YACb,MAAM,QACL,EAAwB,SAAS;AAEtC;AAiCA,SAAgB,cAOd,oBAOA,SAKmE;CACnE,IAAI;CACJ,IAAI;CAMJ,IAAI,eAAe,oBAAoB;EAErC,YAAY;EACZ,gBAAgB,KAAK,OAAO;CAC9B,OAAO;EAEL,YAAY,KAAA;EACZ,gBAAgB;CAClB;CAqBA,OAAO;EAbL,MAAM;EAKN,aAAa;EACb,KAAK;CAOA;AACT;AAGA,SAAgB,wBAIgD;CAC9D,OAAO;AACT;;;;;AAgJA,SAAgB,UACd,OAEoC;CACpC,OACE,OAAO,UAAU,cACjB,OAAQ,MAAkC,gBAAgB,YAC1D,OAAQ,MAAyB,OAAO;AAE5C"}
|
|
1
|
+
{"version":3,"file":"mutator.js","names":[],"sources":["../../../../../zql/src/mutate/mutator.ts"],"sourcesContent":["import type {StandardSchemaV1} from '@standard-schema/spec';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport type {\n DefaultContext,\n DefaultSchema,\n DefaultWrappedTransaction,\n IsUnknown,\n} from '../../../zero-types/src/default-types.ts';\nimport type {Schema} from '../../../zero-types/src/schema.ts';\nimport type {AnyTransaction, Transaction} from './custom.ts';\n\n// ----------------------------------------------------------------------------\n// defineMutator\n// ----------------------------------------------------------------------------\n\nexport type MutatorDefinitionTypes<\n TInput extends ReadonlyJSONValue | undefined,\n TOutput,\n TContext,\n TWrappedTransaction,\n> = 'MutatorDefinition' & {\n readonly $input: TInput;\n readonly $output: TOutput;\n readonly $context: TContext;\n readonly $wrappedTransaction: TWrappedTransaction;\n};\n\nexport type MutatorDefinition<\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = {\n readonly 'fn': MutatorDefinitionFunction<TOutput, TContext, AnyTransaction>;\n readonly 'validator': StandardSchemaV1<TInput, TOutput> | undefined;\n readonly '~': MutatorDefinitionTypes<\n TInput,\n TOutput,\n TContext,\n TWrappedTransaction\n >;\n};\n\n// oxlint-disable-next-line no-explicit-any\nexport type AnyMutatorDefinition = MutatorDefinition<any, any, any, any>;\n\nexport function isMutatorDefinition(f: unknown): f is AnyMutatorDefinition {\n return (\n typeof f === 'object' &&\n f !== null &&\n (f as {['~']?: unknown})['~'] === 'MutatorDefinition'\n );\n}\n\n// Overload for no validator\nexport function defineMutator<\n TInput extends ReadonlyJSONValue | undefined = ReadonlyJSONValue | undefined,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n>(\n mutator: MutatorDefinitionFunction<\n TInput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n): MutatorDefinition<TInput, TInput, TContext, TWrappedTransaction>;\n\n// Overload for validator\nexport function defineMutator<\n TInput extends ReadonlyJSONValue | undefined = undefined,\n TOutput extends ReadonlyJSONValue | undefined = TInput,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n>(\n validator: StandardSchemaV1<TInput, TOutput>,\n mutator: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n): MutatorDefinition<TInput, TOutput, TContext, TWrappedTransaction>;\n\n// Implementation\nexport function defineMutator<\n TInput extends ReadonlyJSONValue | undefined = undefined,\n TOutput extends ReadonlyJSONValue | undefined = TInput,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n>(\n validatorOrMutator:\n | StandardSchemaV1<TInput, TOutput>\n | MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n mutator?: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n): MutatorDefinition<TInput, TOutput, TContext, TWrappedTransaction> {\n let validator: StandardSchemaV1<TInput, TOutput> | undefined;\n let actualMutator: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >;\n\n if ('~standard' in validatorOrMutator) {\n // defineMutator(validator, mutator)\n validator = validatorOrMutator;\n actualMutator = must(mutator);\n } else {\n // defineMutator(mutator) - no validator\n validator = undefined;\n actualMutator = validatorOrMutator;\n }\n\n const mutatorDefinition: MutatorDefinition<\n TInput,\n TOutput,\n TContext,\n TWrappedTransaction\n > = {\n 'fn': actualMutator as MutatorDefinitionFunction<\n TOutput,\n TContext,\n AnyTransaction\n >,\n 'validator': validator,\n '~': 'MutatorDefinition' as unknown as MutatorDefinitionTypes<\n TInput,\n TOutput,\n TContext,\n TWrappedTransaction\n >,\n };\n return mutatorDefinition;\n}\n\n// intentionally not using DefaultSchema, DefaultContext, or DefaultWrappedTransaction\nexport function defineMutatorWithType<\n TSchema extends Schema,\n TContext = unknown,\n TWrappedTransaction = unknown,\n>(): TypedDefineMutator<TSchema, TContext, TWrappedTransaction> {\n return defineMutator;\n}\n\n/**\n * The return type of defineMutatorWithType. A function matching the\n * defineMutator overloads but with Schema, Context, and WrappedTransaction\n * pre-bound.\n *\n * This is used as a workaround to using DefaultTypes (e.g. when using\n * multiple Zero instances).\n */\ntype TypedDefineMutator<\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = {\n // Without validator\n <TArgs extends ReadonlyJSONValue | undefined>(\n mutator: MutatorDefinitionFunction<\n TArgs,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n ): MutatorDefinition<TArgs, TArgs, TContext, TWrappedTransaction>;\n\n // With validator\n <\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n >(\n validator: StandardSchemaV1<TInput, TOutput>,\n mutator: MutatorDefinitionFunction<\n TOutput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >,\n ): MutatorDefinition<TInput, TOutput, TContext, TWrappedTransaction>;\n};\n\nexport type MutatorDefinitionFunction<\n TOutput extends ReadonlyJSONValue | undefined,\n TContext,\n TTransaction,\n> = (options: {\n args: TOutput;\n ctx: TContext;\n tx: TTransaction;\n}) => Promise<void>;\n\nexport type MutatorExecutionFunction<\n TOutput extends ReadonlyJSONValue | undefined,\n TContext,\n TTransaction,\n> = (\n options: MutatorExecutionOptions<TOutput, TContext, TTransaction>,\n) => Promise<void>;\n\ntype MutatorExecutionOptions<\n TOutput extends ReadonlyJSONValue | undefined,\n TContext,\n TTransaction,\n> = undefined extends TOutput\n ? IsUnknown<TContext> extends true\n ? {args?: TOutput | undefined; tx: TTransaction; ctx?: TContext | undefined}\n : {args?: TOutput | undefined; tx: TTransaction; ctx: TContext}\n : IsUnknown<TContext> extends true\n ? {args: TOutput; tx: TTransaction; ctx?: TContext | undefined}\n : {args: TOutput; tx: TTransaction; ctx: TContext};\n\n// ----------------------------------------------------------------------------\n// Mutator and MutateRequest types\n// ----------------------------------------------------------------------------\n\nexport type MutatorTypes<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = 'Mutator' & {\n readonly $input: TInput;\n readonly $schema: TSchema;\n readonly $context: TContext;\n readonly $wrappedTransaction: TWrappedTransaction;\n};\n\n/**\n * A callable wrapper around a MutatorDefinition, created by `defineMutators()`.\n *\n * Accessed like `mutators.foo.bar`, and called to create a MutateRequest:\n * `mutators.foo.bar(42)` returns a `MutateRequest`.\n *\n * The `fn` property is used for execution and takes raw JSON args (for rebase\n * and server wire format cases) that are validated internally.\n */\nexport type Mutator<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = {\n readonly 'mutatorName': string;\n /**\n * Execute the mutation. Args are ReadonlyJSONValue because this is called\n * during rebase (from stored JSON) and on the server (from wire format).\n * Validation happens internally before the recipe function runs.\n */\n readonly 'fn': MutatorExecutionFunction<\n TInput,\n TContext,\n Transaction<TSchema, TWrappedTransaction>\n >;\n readonly '~': MutatorTypes<TInput, TSchema, TContext, TWrappedTransaction>;\n} & MutatorCallable<TInput, TSchema, TContext, TWrappedTransaction>;\n\n// Helper type for the callable part of Mutator\n// When TInput is undefined, the function is callable with 0 args\n// When TInput includes undefined (optional), args is optional\n// Otherwise, args is required\ntype MutatorCallable<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = [TInput] extends [undefined]\n ? () => MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>\n : undefined extends TInput\n ? {\n (): MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>;\n (\n args?: TInput,\n ): MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>;\n }\n : {\n (\n args: TInput,\n ): MutateRequest<TInput, TSchema, TContext, TWrappedTransaction>;\n };\n\n// oxlint-disable-next-line no-explicit-any\nexport type AnyMutator = Mutator<any, any, any, any>;\n\n/**\n * Checks if a value is a Mutator (the result of processing a MutatorDefinition\n * through defineMutators).\n */\nexport function isMutator<S extends Schema>(\n value: unknown,\n // oxlint-disable-next-line no-explicit-any\n): value is Mutator<any, S, any, any> {\n return (\n typeof value === 'function' &&\n typeof (value as {mutatorName?: unknown}).mutatorName === 'string' &&\n typeof (value as {fn?: unknown}).fn === 'function'\n );\n}\n\nexport type MutateRequestTypes<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema,\n TContext,\n TWrappedTransaction,\n> = 'MutateRequest' & {\n readonly $input: TInput;\n readonly $schema: TSchema;\n readonly $context: TContext;\n readonly $wrappedTransaction: TWrappedTransaction;\n};\n\n/**\n * The result of calling a Mutator with arguments.\n *\n * Created by `mutators.foo.bar(42)`, executed by `zero.mutate(mr)` on the client\n * or `mr.mutator.fn({tx, ctx, args: mr.args})` on the server.\n */\nexport type MutateRequest<\n TInput extends ReadonlyJSONValue | undefined,\n TSchema extends Schema = DefaultSchema,\n TContext = DefaultContext,\n TWrappedTransaction = DefaultWrappedTransaction,\n> = {\n readonly 'mutator': Mutator<TInput, TSchema, TContext, TWrappedTransaction>;\n readonly 'args': TInput;\n readonly '~': MutateRequestTypes<\n TInput,\n TSchema,\n TContext,\n TWrappedTransaction\n >;\n};\n"],"mappings":";;AA+CA,SAAgB,oBAAoB,GAAuC;AACzE,QACE,OAAO,MAAM,YACb,MAAM,QACL,EAAwB,SAAS;;AAmCtC,SAAgB,cAOd,oBAOA,SAKmE;CACnE,IAAI;CACJ,IAAI;AAMJ,KAAI,eAAe,oBAAoB;AAErC,cAAY;AACZ,kBAAgB,KAAK,QAAQ;QACxB;AAEL,cAAY,KAAA;AACZ,kBAAgB;;AAsBlB,QAdI;EACF,MAAM;EAKN,aAAa;EACb,KAAK;EAMN;;AAKH,SAAgB,wBAIgD;AAC9D,QAAO;;;;;;AAiJT,SAAgB,UACd,OAEoC;AACpC,QACE,OAAO,UAAU,cACjB,OAAQ,MAAkC,gBAAgB,YAC1D,OAAQ,MAAyB,OAAO"}
|