@hulla/db 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +263 -2
- package/THIRD_PARTY_NOTICES.md +850 -0
- package/dist/aggregate.d.ts +63 -0
- package/dist/aggregate.js +147 -0
- package/dist/auth.d.ts +10 -0
- package/dist/auth.js +22 -0
- package/dist/bindings.d.ts +56 -0
- package/dist/bindings.js +277 -0
- package/dist/browser.d.ts +12 -0
- package/dist/browser.js +24 -0
- package/dist/callable.d.ts +48 -0
- package/dist/callable.js +142 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +65 -0
- package/dist/codec.d.ts +32 -0
- package/dist/codec.js +129 -0
- package/dist/codegen.d.ts +19 -0
- package/dist/codegen.js +275 -0
- package/dist/config.d.ts +70 -0
- package/dist/config.js +100 -0
- package/dist/contracts.d.ts +109 -0
- package/dist/contracts.js +1 -0
- package/dist/database-builder.d.ts +19 -0
- package/dist/database-builder.js +183 -0
- package/dist/database.d.ts +69 -0
- package/dist/database.js +128 -0
- package/dist/declarations.d.ts +91 -0
- package/dist/declarations.js +141 -0
- package/dist/dev-worker.d.ts +1 -0
- package/dist/dev-worker.js +47 -0
- package/dist/dev.d.ts +5 -0
- package/dist/dev.js +148 -0
- package/dist/error.d.ts +20 -0
- package/dist/error.js +82 -0
- package/dist/fields.d.ts +36 -0
- package/dist/fields.js +63 -0
- package/dist/filters.d.ts +93 -0
- package/dist/filters.js +220 -0
- package/dist/function-shapes.d.ts +7 -0
- package/dist/function-shapes.js +150 -0
- package/dist/handles.d.ts +27 -0
- package/dist/handles.js +387 -0
- package/dist/http/protocol.d.ts +64 -0
- package/dist/http/protocol.js +77 -0
- package/dist/http/sse.d.ts +7 -0
- package/dist/http/sse.js +70 -0
- package/dist/http.d.ts +44 -0
- package/dist/http.js +911 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +1 -0
- package/dist/internal/client.d.ts +6 -0
- package/dist/internal/client.js +5 -0
- package/dist/json-value.d.ts +21 -0
- package/dist/json-value.js +79 -0
- package/dist/names.d.ts +2 -0
- package/dist/names.js +10 -0
- package/dist/native.d.ts +3 -0
- package/dist/native.js +42 -0
- package/dist/notifications.d.ts +8 -0
- package/dist/notifications.js +70 -0
- package/dist/optimistic.d.ts +46 -0
- package/dist/optimistic.js +140 -0
- package/dist/page.d.ts +11 -0
- package/dist/page.js +1 -0
- package/dist/pagination.d.ts +17 -0
- package/dist/pagination.js +262 -0
- package/dist/project-codegen.d.ts +2 -0
- package/dist/project-codegen.js +68 -0
- package/dist/projection.d.ts +19 -0
- package/dist/projection.js +31 -0
- package/dist/runtime-conditions.d.ts +2 -0
- package/dist/runtime-conditions.js +10 -0
- package/dist/runtime.d.ts +13 -0
- package/dist/runtime.js +47 -0
- package/dist/schema-codegen.d.ts +16 -0
- package/dist/schema-codegen.js +212 -0
- package/dist/schema-contract.d.ts +4 -0
- package/dist/schema-contract.js +42 -0
- package/dist/schema.d.ts +356 -0
- package/dist/schema.js +720 -0
- package/dist/server-database.d.ts +14 -0
- package/dist/server-database.js +386 -0
- package/dist/server.d.ts +7 -0
- package/dist/server.js +1 -0
- package/dist/service.d.ts +13 -0
- package/dist/service.js +206 -0
- package/dist/sql-check.d.ts +28 -0
- package/dist/sql-check.js +59 -0
- package/dist/validation.d.ts +43 -0
- package/dist/validation.js +21 -0
- package/dist/worker-codegen.d.ts +3 -0
- package/dist/worker-codegen.js +44 -0
- package/dist/worker.d.ts +9 -0
- package/dist/worker.js +92 -0
- package/dist/write-expression.d.ts +72 -0
- package/dist/write-expression.js +122 -0
- package/dist/zod.d.ts +28 -0
- package/dist/zod.js +102 -0
- package/licenses/allocator-api2-0.2.21/LICENSE-APACHE +176 -0
- package/licenses/allocator-api2-0.2.21/LICENSE-MIT +23 -0
- package/licenses/async-trait-0.1.92/LICENSE-APACHE +176 -0
- package/licenses/async-trait-0.1.92/LICENSE-MIT +23 -0
- package/licenses/atomic-waker-1.1.2/LICENSE-APACHE +201 -0
- package/licenses/atomic-waker-1.1.2/LICENSE-MIT +23 -0
- package/licenses/atomic-waker-1.1.2/LICENSE-THIRD-PARTY +45 -0
- package/licenses/axum-0.8.9/LICENSE +25 -0
- package/licenses/axum-core-0.5.6/LICENSE +27 -0
- package/licenses/base64-0.22.1/LICENSE-APACHE +201 -0
- package/licenses/base64-0.22.1/LICENSE-MIT +21 -0
- package/licenses/bitflags-2.13.2/LICENSE-APACHE +201 -0
- package/licenses/bitflags-2.13.2/LICENSE-MIT +25 -0
- package/licenses/block-buffer-0.12.1/LICENSE-APACHE +201 -0
- package/licenses/block-buffer-0.12.1/LICENSE-MIT +25 -0
- package/licenses/byteorder-1.5.0/COPYING +3 -0
- package/licenses/byteorder-1.5.0/LICENSE-MIT +21 -0
- package/licenses/bytes-1.12.1/LICENSE +25 -0
- package/licenses/cc-1.6.0/LICENSE-APACHE +201 -0
- package/licenses/cc-1.6.0/LICENSE-MIT +25 -0
- package/licenses/cfg-if-1.0.5/LICENSE-APACHE +201 -0
- package/licenses/cfg-if-1.0.5/LICENSE-MIT +25 -0
- package/licenses/chacha20-0.10.2/LICENSE-APACHE +201 -0
- package/licenses/chacha20-0.10.2/LICENSE-MIT +25 -0
- package/licenses/cmov-0.5.4/LICENSE-APACHE +202 -0
- package/licenses/cmov-0.5.4/LICENSE-MIT +25 -0
- package/licenses/const-oid-0.10.2/LICENSE-APACHE +201 -0
- package/licenses/const-oid-0.10.2/LICENSE-MIT +25 -0
- package/licenses/const-oid-0.9.6/LICENSE-APACHE +201 -0
- package/licenses/const-oid-0.9.6/LICENSE-MIT +25 -0
- package/licenses/cpufeatures-0.3.1/LICENSE-APACHE +201 -0
- package/licenses/cpufeatures-0.3.1/LICENSE-MIT +25 -0
- package/licenses/crypto-common-0.2.2/LICENSE-APACHE +201 -0
- package/licenses/crypto-common-0.2.2/LICENSE-MIT +25 -0
- package/licenses/ctutils-0.4.2/LICENSE-APACHE +202 -0
- package/licenses/ctutils-0.4.2/LICENSE-MIT +25 -0
- package/licenses/der-0.7.10/LICENSE-APACHE +201 -0
- package/licenses/der-0.7.10/LICENSE-MIT +25 -0
- package/licenses/der_derive-0.7.3/LICENSE-APACHE +201 -0
- package/licenses/der_derive-0.7.3/LICENSE-MIT +25 -0
- package/licenses/deranged-0.5.8/LICENSE-Apache +202 -0
- package/licenses/deranged-0.5.8/LICENSE-MIT +19 -0
- package/licenses/digest-0.11.3/LICENSE-APACHE +201 -0
- package/licenses/digest-0.11.3/LICENSE-MIT +26 -0
- package/licenses/equivalent-1.0.3/LICENSE-APACHE +201 -0
- package/licenses/equivalent-1.0.3/LICENSE-MIT +25 -0
- package/licenses/errno-0.3.14/LICENSE-APACHE +201 -0
- package/licenses/errno-0.3.14/LICENSE-MIT +25 -0
- package/licenses/fallible-iterator-0.2.0/LICENSE-APACHE +202 -0
- package/licenses/fallible-iterator-0.2.0/LICENSE-MIT +19 -0
- package/licenses/find-msvc-tools-0.1.14/LICENSE-APACHE +201 -0
- package/licenses/find-msvc-tools-0.1.14/LICENSE-MIT +25 -0
- package/licenses/flagset-0.4.7/LICENSE +202 -0
- package/licenses/foldhash-0.2.0/LICENSE +19 -0
- package/licenses/futures-channel-0.3.34/LICENSE-APACHE +202 -0
- package/licenses/futures-channel-0.3.34/LICENSE-MIT +26 -0
- package/licenses/futures-core-0.3.34/LICENSE-APACHE +202 -0
- package/licenses/futures-core-0.3.34/LICENSE-MIT +26 -0
- package/licenses/futures-sink-0.3.34/LICENSE-APACHE +202 -0
- package/licenses/futures-sink-0.3.34/LICENSE-MIT +26 -0
- package/licenses/futures-task-0.3.34/LICENSE-APACHE +202 -0
- package/licenses/futures-task-0.3.34/LICENSE-MIT +26 -0
- package/licenses/futures-util-0.3.34/LICENSE-APACHE +202 -0
- package/licenses/futures-util-0.3.34/LICENSE-MIT +26 -0
- package/licenses/getrandom-0.2.17/LICENSE-APACHE +201 -0
- package/licenses/getrandom-0.2.17/LICENSE-MIT +26 -0
- package/licenses/getrandom-0.4.3/LICENSE-APACHE +201 -0
- package/licenses/getrandom-0.4.3/LICENSE-MIT +26 -0
- package/licenses/hashbrown-0.17.1/LICENSE-APACHE +201 -0
- package/licenses/hashbrown-0.17.1/LICENSE-MIT +25 -0
- package/licenses/hmac-0.13.0/LICENSE-APACHE +201 -0
- package/licenses/hmac-0.13.0/LICENSE-MIT +25 -0
- package/licenses/http-1.5.0/LICENSE-APACHE +201 -0
- package/licenses/http-1.5.0/LICENSE-MIT +25 -0
- package/licenses/http-body-1.1.0/LICENSE +25 -0
- package/licenses/http-body-util-0.1.5/LICENSE +25 -0
- package/licenses/httparse-1.10.1/LICENSE-APACHE +201 -0
- package/licenses/httparse-1.10.1/LICENSE-MIT +20 -0
- package/licenses/httpdate-1.0.3/LICENSE-APACHE +201 -0
- package/licenses/httpdate-1.0.3/LICENSE-MIT +19 -0
- package/licenses/hybrid-array-0.4.15/LICENSE-APACHE +201 -0
- package/licenses/hybrid-array-0.4.15/LICENSE-MIT +25 -0
- package/licenses/hyper-1.11.1/LICENSE +19 -0
- package/licenses/hyper-util-0.1.21/LICENSE +19 -0
- package/licenses/itoa-1.0.18/LICENSE-APACHE +176 -0
- package/licenses/itoa-1.0.18/LICENSE-MIT +23 -0
- package/licenses/libc-0.2.189/LICENSE-APACHE +176 -0
- package/licenses/libc-0.2.189/LICENSE-MIT +25 -0
- package/licenses/lock_api-0.4.14/LICENSE-APACHE +201 -0
- package/licenses/lock_api-0.4.14/LICENSE-MIT +25 -0
- package/licenses/log-0.4.34/LICENSE-APACHE +201 -0
- package/licenses/log-0.4.34/LICENSE-MIT +25 -0
- package/licenses/matchit-0.8.4/LICENSE +21 -0
- package/licenses/matchit-0.8.4/LICENSE.httprouter +29 -0
- package/licenses/md-5-0.11.0/LICENSE-APACHE +201 -0
- package/licenses/md-5-0.11.0/LICENSE-MIT +28 -0
- package/licenses/memchr-2.8.3/COPYING +3 -0
- package/licenses/memchr-2.8.3/LICENSE-MIT +21 -0
- package/licenses/mime-0.3.17/LICENSE-APACHE +201 -0
- package/licenses/mime-0.3.17/LICENSE-MIT +20 -0
- package/licenses/mio-1.2.3/LICENSE +19 -0
- package/licenses/num-conv-0.2.2/LICENSE-Apache +177 -0
- package/licenses/num-conv-0.2.2/LICENSE-MIT +19 -0
- package/licenses/objc2-core-foundation-0.3.2/LICENSE.md +34 -0
- package/licenses/objc2-system-configuration-0.3.2/LICENSE.md +34 -0
- package/licenses/once_cell-1.21.4/LICENSE-APACHE +201 -0
- package/licenses/once_cell-1.21.4/LICENSE-MIT +23 -0
- package/licenses/parking_lot-0.12.5/LICENSE-APACHE +201 -0
- package/licenses/parking_lot-0.12.5/LICENSE-MIT +25 -0
- package/licenses/parking_lot_core-0.9.12/LICENSE-APACHE +201 -0
- package/licenses/parking_lot_core-0.9.12/LICENSE-MIT +25 -0
- package/licenses/percent-encoding-2.3.2/LICENSE-APACHE +201 -0
- package/licenses/percent-encoding-2.3.2/LICENSE-MIT +25 -0
- package/licenses/phf-0.13.1/LICENSE +20 -0
- package/licenses/phf_shared-0.13.1/LICENSE +20 -0
- package/licenses/pin-project-lite-0.2.17/LICENSE-APACHE +177 -0
- package/licenses/pin-project-lite-0.2.17/LICENSE-MIT +23 -0
- package/licenses/postgres-protocol-0.6.12/LICENSE-APACHE +201 -0
- package/licenses/postgres-protocol-0.6.12/LICENSE-MIT +22 -0
- package/licenses/postgres-types-0.2.14/LICENSE-APACHE +201 -0
- package/licenses/postgres-types-0.2.14/LICENSE-MIT +22 -0
- package/licenses/powerfmt-0.2.1/LICENSE-Apache +202 -0
- package/licenses/powerfmt-0.2.1/LICENSE-MIT +19 -0
- package/licenses/proc-macro2-1.0.107/LICENSE-APACHE +176 -0
- package/licenses/proc-macro2-1.0.107/LICENSE-MIT +23 -0
- package/licenses/quote-1.0.47/LICENSE-APACHE +176 -0
- package/licenses/quote-1.0.47/LICENSE-MIT +23 -0
- package/licenses/rand-0.10.3/COPYRIGHT +12 -0
- package/licenses/rand-0.10.3/LICENSE-APACHE +176 -0
- package/licenses/rand-0.10.3/LICENSE-MIT +26 -0
- package/licenses/rand_core-0.10.1/COPYRIGHT +9 -0
- package/licenses/rand_core-0.10.1/LICENSE-APACHE +187 -0
- package/licenses/rand_core-0.10.1/LICENSE-MIT +25 -0
- package/licenses/ring-0.17.14/LICENSE +9 -0
- package/licenses/ring-0.17.14/LICENSE-BoringSSL +272 -0
- package/licenses/ring-0.17.14/LICENSE-other-bits +13 -0
- package/licenses/ring-0.17.14/src/polyfill/once_cell/LICENSE-APACHE +201 -0
- package/licenses/ring-0.17.14/src/polyfill/once_cell/LICENSE-MIT +23 -0
- package/licenses/ring-0.17.14/third_party/fiat/LICENSE +15 -0
- package/licenses/rquickjs-0.14.0/LICENSE +22 -0
- package/licenses/rquickjs-core-0.14.0/LICENSE +22 -0
- package/licenses/rquickjs-sys-0.14.0/quickjs/LICENSE +24 -0
- package/licenses/rquickjs-sys-0.14.0/vendor/wasi-libc/NOTICE.md +26 -0
- package/licenses/rustls-0.23.46/LICENSE-APACHE +201 -0
- package/licenses/rustls-0.23.46/LICENSE-ISC +15 -0
- package/licenses/rustls-0.23.46/LICENSE-MIT +25 -0
- package/licenses/rustls-pki-types-1.15.1/LICENSE-APACHE +201 -0
- package/licenses/rustls-pki-types-1.15.1/LICENSE-MIT +25 -0
- package/licenses/rustls-webpki-0.103.15/LICENSE +19 -0
- package/licenses/scopeguard-1.2.0/LICENSE-APACHE +201 -0
- package/licenses/scopeguard-1.2.0/LICENSE-MIT +25 -0
- package/licenses/serde-1.0.229/LICENSE-APACHE +176 -0
- package/licenses/serde-1.0.229/LICENSE-MIT +23 -0
- package/licenses/serde_core-1.0.229/LICENSE-APACHE +176 -0
- package/licenses/serde_core-1.0.229/LICENSE-MIT +23 -0
- package/licenses/serde_derive-1.0.229/LICENSE-APACHE +176 -0
- package/licenses/serde_derive-1.0.229/LICENSE-MIT +23 -0
- package/licenses/serde_json-1.0.151/LICENSE-APACHE +176 -0
- package/licenses/serde_json-1.0.151/LICENSE-MIT +23 -0
- package/licenses/serde_path_to_error-0.1.20/LICENSE-APACHE +176 -0
- package/licenses/serde_path_to_error-0.1.20/LICENSE-MIT +23 -0
- package/licenses/sha2-0.11.0/LICENSE-APACHE +201 -0
- package/licenses/sha2-0.11.0/LICENSE-MIT +28 -0
- package/licenses/shlex-2.0.1/LICENSE-APACHE +13 -0
- package/licenses/shlex-2.0.1/LICENSE-MIT +21 -0
- package/licenses/signal-hook-registry-1.4.8/LICENSE-APACHE +201 -0
- package/licenses/signal-hook-registry-1.4.8/LICENSE-MIT +25 -0
- package/licenses/siphasher-1.0.4/COPYING +7 -0
- package/licenses/siphasher-1.0.4/LICENSE-APACHE +202 -0
- package/licenses/siphasher-1.0.4/LICENSE-MIT +17 -0
- package/licenses/slab-0.4.12/LICENSE +25 -0
- package/licenses/smallvec-1.16.2/LICENSE-APACHE +201 -0
- package/licenses/smallvec-1.16.2/LICENSE-MIT +25 -0
- package/licenses/socket2-0.6.5/LICENSE-APACHE +201 -0
- package/licenses/socket2-0.6.5/LICENSE-MIT +25 -0
- package/licenses/spki-0.7.3/LICENSE-APACHE +201 -0
- package/licenses/spki-0.7.3/LICENSE-MIT +25 -0
- package/licenses/stringprep-0.1.5/LICENSE-APACHE +202 -0
- package/licenses/stringprep-0.1.5/LICENSE-MIT +19 -0
- package/licenses/subtle-2.6.1/LICENSE +29 -0
- package/licenses/syn-2.0.119/LICENSE-APACHE +176 -0
- package/licenses/syn-2.0.119/LICENSE-MIT +23 -0
- package/licenses/syn-3.0.6/LICENSE-APACHE +176 -0
- package/licenses/syn-3.0.6/LICENSE-MIT +23 -0
- package/licenses/sync_wrapper-1.0.2/LICENSE +177 -0
- package/licenses/time-0.3.55/LICENSE-Apache +177 -0
- package/licenses/time-0.3.55/LICENSE-MIT +19 -0
- package/licenses/time-core-0.1.9/LICENSE-Apache +177 -0
- package/licenses/time-core-0.1.9/LICENSE-MIT +19 -0
- package/licenses/time-macros-0.2.32/LICENSE-Apache +177 -0
- package/licenses/time-macros-0.2.32/LICENSE-MIT +19 -0
- package/licenses/tinyvec-1.13.3/LICENSE-APACHE.md +202 -0
- package/licenses/tinyvec-1.13.3/LICENSE-MIT.md +5 -0
- package/licenses/tinyvec-1.13.3/LICENSE-ZLIB.md +11 -0
- package/licenses/tokio-1.53.1/LICENSE +21 -0
- package/licenses/tokio-macros-2.7.2/LICENSE +22 -0
- package/licenses/tokio-postgres-0.7.18/LICENSE-APACHE +201 -0
- package/licenses/tokio-postgres-0.7.18/LICENSE-MIT +22 -0
- package/licenses/tokio-postgres-rustls-0.14.0/LICENSE +21 -0
- package/licenses/tokio-rustls-0.26.6/LICENSE-APACHE +201 -0
- package/licenses/tokio-rustls-0.26.6/LICENSE-MIT +25 -0
- package/licenses/tokio-util-0.7.19/LICENSE +21 -0
- package/licenses/tower-0.5.3/LICENSE +25 -0
- package/licenses/tower-layer-0.3.3/LICENSE +25 -0
- package/licenses/tower-service-0.3.3/LICENSE +25 -0
- package/licenses/typenum-1.20.1/LICENSE +1 -0
- package/licenses/typenum-1.20.1/LICENSE-APACHE +201 -0
- package/licenses/typenum-1.20.1/LICENSE-MIT +21 -0
- package/licenses/unicode-bidi-0.3.18/COPYRIGHT +8 -0
- package/licenses/unicode-bidi-0.3.18/LICENSE-APACHE +201 -0
- package/licenses/unicode-bidi-0.3.18/LICENSE-MIT +25 -0
- package/licenses/unicode-ident-1.0.26/LICENSE-APACHE +176 -0
- package/licenses/unicode-ident-1.0.26/LICENSE-MIT +23 -0
- package/licenses/unicode-ident-1.0.26/LICENSE-UNICODE +39 -0
- package/licenses/unicode-normalization-0.1.25/COPYRIGHT +7 -0
- package/licenses/unicode-normalization-0.1.25/LICENSE-APACHE +201 -0
- package/licenses/unicode-normalization-0.1.25/LICENSE-MIT +25 -0
- package/licenses/unicode-properties-0.1.4/COPYRIGHT +7 -0
- package/licenses/unicode-properties-0.1.4/LICENSE-APACHE +201 -0
- package/licenses/unicode-properties-0.1.4/LICENSE-MIT +25 -0
- package/licenses/untrusted-0.9.0/LICENSE.txt +13 -0
- package/licenses/uuid-1.26.1/LICENSE-APACHE +201 -0
- package/licenses/uuid-1.26.1/LICENSE-MIT +26 -0
- package/licenses/webpki-roots-1.0.9/LICENSE +61 -0
- package/licenses/whoami-2.1.3/LICENSE_APACHE +176 -0
- package/licenses/whoami-2.1.3/LICENSE_BOOST +23 -0
- package/licenses/whoami-2.1.3/LICENSE_MIT +19 -0
- package/licenses/x509-cert-0.2.5/LICENSE-APACHE +201 -0
- package/licenses/x509-cert-0.2.5/LICENSE-MIT +25 -0
- package/licenses/zeroize-1.9.1/LICENSE-APACHE +202 -0
- package/licenses/zeroize-1.9.1/LICENSE-MIT +25 -0
- package/licenses/zmij-1.0.23/LICENSE-MIT +23 -0
- package/native/darwin-arm64/hulladb-bridge +0 -0
- package/native/darwin-arm64/hulladb-js +0 -0
- package/native/darwin-arm64/hulladb-service +0 -0
- package/native/linux-x64/hulladb-bridge +0 -0
- package/native/linux-x64/hulladb-js +0 -0
- package/native/linux-x64/hulladb-service +0 -0
- package/package.json +90 -4
package/dist/callable.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { canonical } from "./http/protocol.js";
|
|
2
|
+
import { PaginationOperation } from "./pagination.js";
|
|
3
|
+
import { stagedObserver } from "./notifications.js";
|
|
4
|
+
import { DatabaseError } from "./error.js";
|
|
5
|
+
import { MutationOperation, QueryOperation, queryListener, querySnapshot, subscriptionOptions } from "./handles.js";
|
|
6
|
+
const bindingMetadata = Symbol("hulla query binding");
|
|
7
|
+
/** Shared adapter boundary; never executes the callable or imports its handler. */
|
|
8
|
+
export function bindingInfo(reference) {
|
|
9
|
+
const metadata = reference?.[bindingMetadata];
|
|
10
|
+
if (!metadata)
|
|
11
|
+
throw new TypeError("A framework binding requires a generated Hulla function");
|
|
12
|
+
return metadata;
|
|
13
|
+
}
|
|
14
|
+
function options(value) {
|
|
15
|
+
if (value === undefined)
|
|
16
|
+
return {};
|
|
17
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
18
|
+
throw new TypeError("Call options must be an object");
|
|
19
|
+
if (Object.keys(value).some((key) => key !== "signal"))
|
|
20
|
+
throw new TypeError("Unknown call option");
|
|
21
|
+
const signal = value.signal;
|
|
22
|
+
if (signal !== undefined && !(signal instanceof AbortSignal))
|
|
23
|
+
throw new TypeError("signal must be an AbortSignal");
|
|
24
|
+
return signal === undefined ? {} : { signal };
|
|
25
|
+
}
|
|
26
|
+
function invocation(scope, name, kind, hasInput, args, codecs) {
|
|
27
|
+
if (args.length > (hasInput ? (kind === "query" ? 2 : 1) : (kind === "query" ? 1 : 0)))
|
|
28
|
+
throw new TypeError("Too many function arguments");
|
|
29
|
+
const configuration = kind === "query" ? options(args[hasInput ? 1 : 0]) : {};
|
|
30
|
+
configuration.signal?.throwIfAborted();
|
|
31
|
+
return {
|
|
32
|
+
runtime: scope.current(),
|
|
33
|
+
operation: { name, kind, input: hasInput ? args[0] : undefined, ...(codecs ? { codecs } : {}) },
|
|
34
|
+
configuration,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Used by generated modules; input/output types come from a type-only import. */
|
|
38
|
+
export function mutationBinding(scope, name, hasInput, codecs) {
|
|
39
|
+
const bind = (predictors) => {
|
|
40
|
+
const call = (...args) => {
|
|
41
|
+
let context;
|
|
42
|
+
let identityEpoch;
|
|
43
|
+
let identitySignal;
|
|
44
|
+
return new MutationOperation((onStatus) => {
|
|
45
|
+
context = invocation(scope, name, "mutation", hasInput, args, codecs);
|
|
46
|
+
const { runtime, operation, configuration } = context;
|
|
47
|
+
identityEpoch = runtime.identityEpoch;
|
|
48
|
+
identitySignal = runtime.identitySignal;
|
|
49
|
+
const optimistic = (input, context) => { for (const predictor of predictors)
|
|
50
|
+
predictor(input, context); };
|
|
51
|
+
return runtime.call(operation, predictors.length ? { ...configuration, optimistic } : configuration, onStatus);
|
|
52
|
+
}, codecs, () => {
|
|
53
|
+
if (context && context.runtime.identityEpoch !== identityEpoch)
|
|
54
|
+
throw new DatabaseError({ code: "context_changed", message: "Mutation authorization scope changed; the write may have committed" });
|
|
55
|
+
}, () => identitySignal);
|
|
56
|
+
};
|
|
57
|
+
const withOptimistic = (...targets) => {
|
|
58
|
+
if (!targets.length)
|
|
59
|
+
throw new TypeError("withOptimistic needs at least one query target");
|
|
60
|
+
const additions = targets.map(target => {
|
|
61
|
+
const metadata = target.query[bindingMetadata];
|
|
62
|
+
if (!metadata || metadata.scope !== scope || metadata.kind !== "query" || (target.input !== undefined && typeof target.input !== "function") || typeof target.update !== "function" || (target.match !== undefined && typeof target.match !== "function")) {
|
|
63
|
+
throw new TypeError("Optimistic targets need a generated query, updater and valid input/match callbacks");
|
|
64
|
+
}
|
|
65
|
+
const { input: mapInput, update, match } = target;
|
|
66
|
+
if (!mapInput && !match && metadata.hasInput) {
|
|
67
|
+
// A declaration can explicitly validate undefined. Its portable input
|
|
68
|
+
// contract then permits the same exact undefined target as a no-input query.
|
|
69
|
+
try {
|
|
70
|
+
if (!metadata.codecs)
|
|
71
|
+
throw new Error();
|
|
72
|
+
metadata.codecs.input.parse(undefined);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
throw new TypeError("Optimistic targets for queries with input need an input mapper or match callback");
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return (submitted, context) => {
|
|
79
|
+
const input = submitted;
|
|
80
|
+
const candidates = context.queries(metadata.name);
|
|
81
|
+
const selected = match ? undefined : mapInput?.(input);
|
|
82
|
+
const encode = (value) => canonical(metadata.codecs ? metadata.codecs.input.encode(value) : value);
|
|
83
|
+
const exact = match ? undefined : encode(selected);
|
|
84
|
+
const queries = candidates.filter(query => match ? match(query.input, input) : encode(query.input) === exact);
|
|
85
|
+
for (const query of queries) {
|
|
86
|
+
const value = context.get(query);
|
|
87
|
+
if (value === undefined)
|
|
88
|
+
continue;
|
|
89
|
+
const state = querySnapshot({ status: "success", data: value, isStale: false, isOptimistic: false }, metadata.codecs);
|
|
90
|
+
if (state.status === "error")
|
|
91
|
+
throw state.error;
|
|
92
|
+
if (state.status !== "success")
|
|
93
|
+
continue;
|
|
94
|
+
context.set(query, update(state.data, input, query.input));
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
});
|
|
98
|
+
return bind([...predictors, ...additions]);
|
|
99
|
+
};
|
|
100
|
+
return Object.assign(call, { withOptimistic, [bindingMetadata]: { name, scope, kind: "mutation", hasInput, ...(codecs ? { codecs } : {}) } });
|
|
101
|
+
};
|
|
102
|
+
return bind([]);
|
|
103
|
+
}
|
|
104
|
+
export function queryBinding(scope, name, hasInput, codecs, paginated = false) {
|
|
105
|
+
const call = (...args) => {
|
|
106
|
+
let context;
|
|
107
|
+
let identityEpoch;
|
|
108
|
+
let identitySignal;
|
|
109
|
+
return new QueryOperation(() => {
|
|
110
|
+
context = invocation(scope, name, "query", hasInput, args, codecs);
|
|
111
|
+
identityEpoch = context.runtime.identityEpoch;
|
|
112
|
+
identitySignal = context.runtime.identitySignal;
|
|
113
|
+
return context.runtime.call(context.operation, context.configuration);
|
|
114
|
+
}, (listener) => {
|
|
115
|
+
if (!context)
|
|
116
|
+
throw new Error("Cannot observe an invalid query invocation");
|
|
117
|
+
const { runtime, operation, configuration } = context;
|
|
118
|
+
if (!runtime.watch)
|
|
119
|
+
throw new Error("The configured runtime does not support query subscriptions");
|
|
120
|
+
return runtime.watch(operation, stagedObserver(state => listener(querySnapshot(state, codecs))), configuration);
|
|
121
|
+
}, codecs, () => {
|
|
122
|
+
if (context && context.runtime.identityEpoch !== identityEpoch)
|
|
123
|
+
throw new DatabaseError({ code: "context_changed", message: "Query authorization scope changed" });
|
|
124
|
+
}, () => context?.configuration.signal, () => identitySignal);
|
|
125
|
+
};
|
|
126
|
+
const subscribe = (...args) => {
|
|
127
|
+
if (args.length > (hasInput ? 3 : 2))
|
|
128
|
+
throw new TypeError("Too many subscription arguments");
|
|
129
|
+
const input = hasInput ? args[0] : undefined;
|
|
130
|
+
const listener = args[hasInput ? 1 : 0];
|
|
131
|
+
if (typeof listener !== "function")
|
|
132
|
+
throw new TypeError("A query subscription needs a listener");
|
|
133
|
+
const configuration = subscriptionOptions(args[hasInput ? 2 : 1]);
|
|
134
|
+
configuration.signal?.throwIfAborted();
|
|
135
|
+
const runtime = scope.current();
|
|
136
|
+
if (!runtime.watch)
|
|
137
|
+
throw new Error("The configured runtime does not support query subscriptions");
|
|
138
|
+
const deliver = queryListener(listener, configuration);
|
|
139
|
+
return runtime.watch({ name, kind: "query", input, ...(codecs ? { codecs } : {}) }, state => deliver(querySnapshot(state, codecs)), configuration.signal ? { signal: configuration.signal } : {});
|
|
140
|
+
};
|
|
141
|
+
return Object.assign(call, { subscribe, ...(paginated ? { paginate: (mapper) => new PaginationOperation(scope.current(), name, mapper, codecs) } : {}), [bindingMetadata]: { name, scope, kind: "query", hasInput, ...(codecs ? { codecs } : {}) } });
|
|
142
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
3
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
4
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
5
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
return path;
|
|
9
|
+
};
|
|
10
|
+
import { resolve, dirname } from "node:path";
|
|
11
|
+
import { pathToFileURL } from "node:url";
|
|
12
|
+
const [command, configArgument = "db.config.ts", ...extra] = process.argv.slice(2);
|
|
13
|
+
try {
|
|
14
|
+
if (extra.length || !["generate", "init", "serve", "dev"].includes(command ?? "")) {
|
|
15
|
+
throw new Error("Usage: hulla-db <generate|init|serve|dev> [db.config.ts]");
|
|
16
|
+
}
|
|
17
|
+
const configPath = resolve(configArgument);
|
|
18
|
+
if (command === "generate" || command === "dev") {
|
|
19
|
+
if (typeof Bun === "undefined")
|
|
20
|
+
throw new Error(`hulla-db ${command} requires Bun. Run bun --bun hulla-db ${command}.`);
|
|
21
|
+
try {
|
|
22
|
+
await import("typescript/unstable/async");
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
throw new Error("Code generation requires TypeScript 7.0.2. Install it with bun add --dev typescript@7.0.2.");
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (command === "generate") {
|
|
29
|
+
const { generateProject } = await import("./project-codegen.js");
|
|
30
|
+
await generateProject(configPath);
|
|
31
|
+
console.log("Generated database entrypoints.");
|
|
32
|
+
}
|
|
33
|
+
else if (command === "serve" || command === "dev") {
|
|
34
|
+
const service = command === "dev"
|
|
35
|
+
? await (await import("./dev.js")).startDevelopment(configPath)
|
|
36
|
+
: await (await import("./service.js")).startService(configPath);
|
|
37
|
+
const stop = () => { void service.close().catch(() => { }); };
|
|
38
|
+
process.on("SIGINT", stop);
|
|
39
|
+
process.on("SIGTERM", stop);
|
|
40
|
+
if ("url" in service)
|
|
41
|
+
console.log(`Database service listening at ${service.url}`);
|
|
42
|
+
try {
|
|
43
|
+
await service.closed;
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
process.off("SIGINT", stop);
|
|
47
|
+
process.off("SIGTERM", stop);
|
|
48
|
+
await service.close();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
const { defineConfig } = await import("./config.js");
|
|
53
|
+
const { initializeDatabase } = await import("./server-database.js");
|
|
54
|
+
const config = defineConfig((await import(__rewriteRelativeImportExtension(pathToFileURL(configPath).href))).default);
|
|
55
|
+
const schemaPath = resolve(dirname(configPath), config.schema ?? "db/schema.ts");
|
|
56
|
+
const schema = (await import(__rewriteRelativeImportExtension(pathToFileURL(schemaPath).href))).default;
|
|
57
|
+
await initializeDatabase(schema, config.database.server);
|
|
58
|
+
console.log("Database initialized and schema verified.");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
// Do not dump imported config contents, driver errors or connection URLs.
|
|
63
|
+
console.error(error instanceof Error ? error.message : "Database setup failed");
|
|
64
|
+
process.exitCode = 1;
|
|
65
|
+
}
|
package/dist/codec.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Portable value shapes compiled from function signatures. No handlers ship. */
|
|
2
|
+
export type ValueShape = {
|
|
3
|
+
readonly kind: "string" | "number" | "boolean" | "bigint" | "date" | "null" | "undefined" | "json";
|
|
4
|
+
} | {
|
|
5
|
+
readonly kind: "literal";
|
|
6
|
+
readonly value: string | number | boolean;
|
|
7
|
+
} | {
|
|
8
|
+
readonly kind: "array";
|
|
9
|
+
readonly item: ValueShape;
|
|
10
|
+
} | {
|
|
11
|
+
readonly kind: "tuple";
|
|
12
|
+
readonly items: readonly ValueShape[];
|
|
13
|
+
} | {
|
|
14
|
+
readonly kind: "union";
|
|
15
|
+
readonly choices: readonly ValueShape[];
|
|
16
|
+
} | {
|
|
17
|
+
readonly kind: "object";
|
|
18
|
+
readonly fields: Readonly<Record<string, {
|
|
19
|
+
readonly shape: ValueShape;
|
|
20
|
+
readonly optional: boolean;
|
|
21
|
+
}>>;
|
|
22
|
+
};
|
|
23
|
+
export interface ValueCodec {
|
|
24
|
+
parse(value: unknown): unknown;
|
|
25
|
+
encode(value: unknown): unknown;
|
|
26
|
+
decode(value: unknown): unknown;
|
|
27
|
+
}
|
|
28
|
+
export declare function valueCodec(shape: ValueShape): ValueCodec;
|
|
29
|
+
export interface FunctionCodecs {
|
|
30
|
+
readonly input: ValueCodec;
|
|
31
|
+
readonly result: ValueCodec;
|
|
32
|
+
}
|
package/dist/codec.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { validateJson } from "./json-value.js";
|
|
2
|
+
function plain(value) {
|
|
3
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
4
|
+
&& [null, Object.prototype].includes(Object.getPrototypeOf(value));
|
|
5
|
+
}
|
|
6
|
+
function same(a, b) {
|
|
7
|
+
if (Object.is(a, b))
|
|
8
|
+
return true;
|
|
9
|
+
if (a instanceof Date && b instanceof Date)
|
|
10
|
+
return Date.prototype.getTime.call(a) === Date.prototype.getTime.call(b);
|
|
11
|
+
if (Array.isArray(a) && Array.isArray(b))
|
|
12
|
+
return a.length === b.length && a.every((value, i) => same(value, b[i]));
|
|
13
|
+
if (plain(a) && plain(b))
|
|
14
|
+
return Object.keys(a).length === Object.keys(b).length && Object.keys(a).every(key => Object.hasOwn(b, key) && same(a[key], b[key]));
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
function dense(value) {
|
|
18
|
+
for (let i = 0; i < value.length; i++)
|
|
19
|
+
if (!Object.hasOwn(value, i))
|
|
20
|
+
return false;
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
function convert(shape, value, mode, path, depth = 0) {
|
|
24
|
+
const invalid = () => new TypeError(`Invalid ${shape.kind} at ${path}`);
|
|
25
|
+
if (depth > 128)
|
|
26
|
+
throw new TypeError("Value nesting exceeds budget");
|
|
27
|
+
switch (shape.kind) {
|
|
28
|
+
case "json": return validateJson(value, undefined, path);
|
|
29
|
+
case "string":
|
|
30
|
+
if (typeof value !== "string" || /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value))
|
|
31
|
+
throw invalid();
|
|
32
|
+
return value;
|
|
33
|
+
case "number":
|
|
34
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
35
|
+
throw invalid();
|
|
36
|
+
return value;
|
|
37
|
+
case "boolean":
|
|
38
|
+
if (typeof value !== "boolean")
|
|
39
|
+
throw invalid();
|
|
40
|
+
return value;
|
|
41
|
+
case "null":
|
|
42
|
+
if (value !== null)
|
|
43
|
+
throw invalid();
|
|
44
|
+
return null;
|
|
45
|
+
case "undefined":
|
|
46
|
+
if (value !== undefined && !(mode === "decode" && value === null))
|
|
47
|
+
throw invalid();
|
|
48
|
+
return mode === "encode" ? null : undefined;
|
|
49
|
+
case "bigint": {
|
|
50
|
+
if (mode === "decode") {
|
|
51
|
+
if (typeof value !== "string" || !/^(0|-?[1-9][0-9]*)$/.test(value))
|
|
52
|
+
throw invalid();
|
|
53
|
+
value = BigInt(value);
|
|
54
|
+
}
|
|
55
|
+
if (typeof value !== "bigint")
|
|
56
|
+
throw invalid();
|
|
57
|
+
return mode === "encode" ? value.toString() : value;
|
|
58
|
+
}
|
|
59
|
+
case "date": {
|
|
60
|
+
let milliseconds;
|
|
61
|
+
if (mode === "decode") {
|
|
62
|
+
if (!plain(value) || Reflect.ownKeys(value).length !== 1 || !Object.hasOwn(value, "$date"))
|
|
63
|
+
throw invalid();
|
|
64
|
+
milliseconds = value.$date;
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
if (!(value instanceof Date) || Object.getPrototypeOf(value) !== Date.prototype || Reflect.ownKeys(value).length)
|
|
68
|
+
throw invalid();
|
|
69
|
+
milliseconds = Date.prototype.getTime.call(value);
|
|
70
|
+
}
|
|
71
|
+
if (typeof milliseconds !== "number" || !Number.isSafeInteger(milliseconds) || Math.abs(milliseconds) > 8_640_000_000_000_000)
|
|
72
|
+
throw invalid();
|
|
73
|
+
return mode === "encode" ? { $date: milliseconds } : new Date(milliseconds);
|
|
74
|
+
}
|
|
75
|
+
case "literal":
|
|
76
|
+
if (value !== shape.value)
|
|
77
|
+
throw invalid();
|
|
78
|
+
return value;
|
|
79
|
+
case "union": {
|
|
80
|
+
const matches = [];
|
|
81
|
+
for (const choice of shape.choices) {
|
|
82
|
+
try {
|
|
83
|
+
matches.push(convert(choice, value, mode, path, depth + 1));
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
if (!(error instanceof TypeError))
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (!matches.length)
|
|
91
|
+
throw invalid();
|
|
92
|
+
if (mode === "decode" && matches.some(match => !same(match, matches[0])))
|
|
93
|
+
throw new TypeError(`Ambiguous union wire value at ${path}`);
|
|
94
|
+
if (mode === "encode")
|
|
95
|
+
convert(shape, matches[0], "decode", path, depth + 1);
|
|
96
|
+
return matches[0];
|
|
97
|
+
}
|
|
98
|
+
case "array":
|
|
99
|
+
if (!Array.isArray(value) || !dense(value))
|
|
100
|
+
throw invalid();
|
|
101
|
+
return value.map((item, i) => convert(shape.item, item, mode, `${path}[${i}]`, depth + 1));
|
|
102
|
+
case "tuple":
|
|
103
|
+
if (!Array.isArray(value) || value.length !== shape.items.length || !dense(value))
|
|
104
|
+
throw invalid();
|
|
105
|
+
const tuple = value;
|
|
106
|
+
return shape.items.map((item, i) => convert(item, tuple[i], mode, `${path}[${i}]`, depth + 1));
|
|
107
|
+
case "object": {
|
|
108
|
+
if (!plain(value) || Object.keys(value).some(key => !Object.hasOwn(shape.fields, key)))
|
|
109
|
+
throw invalid();
|
|
110
|
+
const result = Object.create(null);
|
|
111
|
+
for (const [key, field] of Object.entries(shape.fields)) {
|
|
112
|
+
if (!Object.hasOwn(value, key)) {
|
|
113
|
+
if (field.optional)
|
|
114
|
+
continue;
|
|
115
|
+
throw new TypeError(`Missing field ${path}.${key}`);
|
|
116
|
+
}
|
|
117
|
+
result[key] = convert(field.shape, value[key], mode, `${path}.${key}`, depth + 1);
|
|
118
|
+
}
|
|
119
|
+
return result;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
export function valueCodec(shape) {
|
|
124
|
+
return Object.freeze({
|
|
125
|
+
parse: (value) => convert(shape, value, "parse", "$"),
|
|
126
|
+
encode: (value) => convert(shape, value, "encode", "$"),
|
|
127
|
+
decode: (value) => convert(shape, value, "decode", "$"),
|
|
128
|
+
});
|
|
129
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type ClientConnection, type InvocationLimits } from "./config.ts";
|
|
2
|
+
export { generateProject } from "./project-codegen.ts";
|
|
3
|
+
export { generateSchema, generateRustSchema } from "./schema-codegen.ts";
|
|
4
|
+
export type { SchemaGenerationOptions } from "./schema-codegen.ts";
|
|
5
|
+
export interface GenerationOptions {
|
|
6
|
+
readonly client?: ClientConnection;
|
|
7
|
+
readonly limits?: InvocationLimits;
|
|
8
|
+
/** Low-level explicit source mapping. Normally omit this and use discovery. */
|
|
9
|
+
readonly modules?: Readonly<Record<string, string>>;
|
|
10
|
+
/** Defaults to ./db/schema.ts. Discovery starts beside this file. */
|
|
11
|
+
readonly schema?: string;
|
|
12
|
+
/** Optional discovery directory override. */
|
|
13
|
+
readonly functions?: string;
|
|
14
|
+
readonly outDir: string;
|
|
15
|
+
}
|
|
16
|
+
/** Find declarations without evaluating candidate modules or their dependencies. */
|
|
17
|
+
export declare function discoverFunctions(options: Pick<GenerationOptions, "schema" | "functions" | "outDir">): Promise<Readonly<Record<string, string>>>;
|
|
18
|
+
/** Discovery is static. Only selected declaration modules execute in the trusted build process. */
|
|
19
|
+
export declare function generateFunctions(options: GenerationOptions): Promise<void>;
|
package/dist/codegen.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import { resolveLimits, clientConnection } from "./config.js";
|
|
10
|
+
import { lstat, mkdir, readdir } from "node:fs/promises";
|
|
11
|
+
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
|
12
|
+
import { API, SymbolFlags } from "typescript/unstable/async";
|
|
13
|
+
import { isFunctionDefinition } from "./declarations.js";
|
|
14
|
+
import { assertModuleName, validExportName } from "./names.js";
|
|
15
|
+
import { checkGeneratedDirectory } from "./schema-codegen.js";
|
|
16
|
+
import { compileFunctionShapes } from "./function-shapes.js";
|
|
17
|
+
export { generateProject } from "./project-codegen.js";
|
|
18
|
+
export { generateSchema, generateRustSchema } from "./schema-codegen.js";
|
|
19
|
+
const header = "// Generated by @hulla/db. Do not edit.\n";
|
|
20
|
+
const schemaHeader = "// Generated schema by @hulla/db. Do not edit.\n";
|
|
21
|
+
function importPath(from, target) {
|
|
22
|
+
const path = relative(from, target).split(sep).join("/");
|
|
23
|
+
return path.startsWith(".") ? path : `./${path}`;
|
|
24
|
+
}
|
|
25
|
+
const excludedDirectories = new Set(["_generated", "node_modules", "tests", "test", "__tests__", "__mocks__"]);
|
|
26
|
+
/** Find declarations without evaluating candidate modules or their dependencies. */
|
|
27
|
+
export async function discoverFunctions(options) {
|
|
28
|
+
const schema = resolve(options.schema ?? "db/schema.ts");
|
|
29
|
+
const root = resolve(options.functions ?? dirname(schema));
|
|
30
|
+
const outDir = resolve(options.outDir);
|
|
31
|
+
const candidates = [];
|
|
32
|
+
async function scan(directory) {
|
|
33
|
+
for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
34
|
+
const path = resolve(directory, entry.name);
|
|
35
|
+
if (path === outDir || entry.name.startsWith("."))
|
|
36
|
+
continue;
|
|
37
|
+
if (entry.isDirectory()) {
|
|
38
|
+
if (!excludedDirectories.has(entry.name))
|
|
39
|
+
await scan(path);
|
|
40
|
+
}
|
|
41
|
+
else if (entry.isFile() && /\.[cm]?tsx?$/.test(entry.name)
|
|
42
|
+
&& !/\.(?:d|test|spec)\.[cm]?tsx?$/.test(entry.name)
|
|
43
|
+
&& !/\.config\.[cm]?tsx?$/.test(entry.name)
|
|
44
|
+
&& path !== schema)
|
|
45
|
+
candidates.push(path);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
await scan(root);
|
|
49
|
+
if (!candidates.length)
|
|
50
|
+
return {};
|
|
51
|
+
const api = new API();
|
|
52
|
+
try {
|
|
53
|
+
const snapshot = await api.updateSnapshot({ openFiles: candidates });
|
|
54
|
+
try {
|
|
55
|
+
const modules = Object.create(null);
|
|
56
|
+
for (const source of candidates) {
|
|
57
|
+
const project = await snapshot.getDefaultProjectForFile(source);
|
|
58
|
+
if (!project)
|
|
59
|
+
throw new TypeError(`No TypeScript project for ${source}`);
|
|
60
|
+
const syntax = await project.program.getSyntacticDiagnostics(source);
|
|
61
|
+
if (syntax.length)
|
|
62
|
+
throw new TypeError(`Invalid function source ${source}: ${syntax[0].text} (TS${syntax[0].code})`);
|
|
63
|
+
const file = await project.program.getSourceFile(source);
|
|
64
|
+
if (!file)
|
|
65
|
+
throw new TypeError(`Cannot read ${source}`);
|
|
66
|
+
const declarationFile = await project.program.getSourceFile(Bun.fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./declarations.ts" : "./declarations.d.ts", import.meta.url)));
|
|
67
|
+
if (!declarationFile)
|
|
68
|
+
continue;
|
|
69
|
+
const checker = project.checker;
|
|
70
|
+
const symbol = await checker.getSymbolAtLocation(file);
|
|
71
|
+
if (!symbol)
|
|
72
|
+
continue;
|
|
73
|
+
let found = false;
|
|
74
|
+
for (const exported of await checker.getExportsOfModule(symbol)) {
|
|
75
|
+
if (exported.flags & SymbolFlags.Alias) {
|
|
76
|
+
let typeOnly = false;
|
|
77
|
+
for (const declaration of exported.declarations) {
|
|
78
|
+
let node = await declaration.resolve(project);
|
|
79
|
+
while (node && node !== file) {
|
|
80
|
+
if ("isTypeOnly" in node && node.isTypeOnly)
|
|
81
|
+
typeOnly = true;
|
|
82
|
+
node = node.parent;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (typeOnly)
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const target = exported.flags & SymbolFlags.Alias ? await checker.getAliasedSymbol(exported) : exported;
|
|
89
|
+
if (!(target.flags & SymbolFlags.Value))
|
|
90
|
+
continue;
|
|
91
|
+
const type = await checker.getTypeOfSymbol(target);
|
|
92
|
+
if (!type)
|
|
93
|
+
continue;
|
|
94
|
+
// The private unique-symbol brand distinguishes actual declarations
|
|
95
|
+
// from helpers that happen to expose kind/$types metadata.
|
|
96
|
+
const branded = (await checker.getPropertiesOfType(type)).some(property => property.name.startsWith("__@definitionBrand@") && property.declarations.some(declaration => declaration.path === declarationFile.path));
|
|
97
|
+
if (branded) {
|
|
98
|
+
if (!validExportName(exported.name))
|
|
99
|
+
throw new Error(`Invalid function export name: ${exported.name}`);
|
|
100
|
+
found = true;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (!found)
|
|
104
|
+
continue;
|
|
105
|
+
const module = relative(root, source).split(sep).join("/").replace(/\.[cm]?tsx?$/, "");
|
|
106
|
+
assertModuleName(module);
|
|
107
|
+
if (modules[module])
|
|
108
|
+
throw new Error(`Duplicate discovered function module: ${module}`);
|
|
109
|
+
modules[module] = source;
|
|
110
|
+
}
|
|
111
|
+
return modules;
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
await snapshot.dispose();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
await api.close();
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
async function outputFiles(directory) {
|
|
122
|
+
const entries = await readdir(directory, { withFileTypes: true }).catch((error) => {
|
|
123
|
+
if (error.code === "ENOENT")
|
|
124
|
+
return [];
|
|
125
|
+
throw error;
|
|
126
|
+
});
|
|
127
|
+
const files = [];
|
|
128
|
+
for (const entry of entries) {
|
|
129
|
+
if (entry.isDirectory())
|
|
130
|
+
for (const name of await outputFiles(resolve(directory, entry.name)))
|
|
131
|
+
files.push(`${entry.name}/${name}`);
|
|
132
|
+
else
|
|
133
|
+
files.push(entry.name);
|
|
134
|
+
}
|
|
135
|
+
return files;
|
|
136
|
+
}
|
|
137
|
+
async function checkOutputPath(directory, name) {
|
|
138
|
+
await checkGeneratedDirectory(directory);
|
|
139
|
+
const parts = name.split("/");
|
|
140
|
+
for (let index = 0; index < parts.length; index++) {
|
|
141
|
+
const path = resolve(directory, ...parts.slice(0, index + 1));
|
|
142
|
+
const info = await lstat(path).catch((error) => {
|
|
143
|
+
if (error.code === "ENOENT")
|
|
144
|
+
return undefined;
|
|
145
|
+
throw error;
|
|
146
|
+
});
|
|
147
|
+
if (!info)
|
|
148
|
+
break;
|
|
149
|
+
if (info.isSymbolicLink() || (index < parts.length - 1 ? !info.isDirectory() : !info.isFile())) {
|
|
150
|
+
throw new Error(`Refusing to overwrite an authored path: ${parts.slice(0, index + 1).join("/")}`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/** Discovery is static. Only selected declaration modules execute in the trusted build process. */
|
|
155
|
+
export async function generateFunctions(options) {
|
|
156
|
+
const outDir = resolve(options.outDir);
|
|
157
|
+
if (options.modules && options.functions)
|
|
158
|
+
throw new Error("Use either explicit modules or a functions discovery directory");
|
|
159
|
+
await checkGeneratedDirectory(outDir);
|
|
160
|
+
const moduleSources = options.modules ?? await discoverFunctions(options);
|
|
161
|
+
const existing = await outputFiles(outDir);
|
|
162
|
+
// Reject collisions before evaluating selected server modules or writing output.
|
|
163
|
+
for (const module of Object.keys(moduleSources)) {
|
|
164
|
+
assertModuleName(module);
|
|
165
|
+
if (module === "types" || module === "functions" || module === "tables")
|
|
166
|
+
throw new Error(`Function module name conflicts with a generated schema output: ${module}.ts`);
|
|
167
|
+
}
|
|
168
|
+
for (const name of ["runtime.ts", "functions.json", ...Object.keys(moduleSources).map(module => `${module}.ts`)]) {
|
|
169
|
+
await checkOutputPath(outDir, name);
|
|
170
|
+
if (existing.includes(name) && !ownsOutput(name, await Bun.file(resolve(outDir, name)).text())) {
|
|
171
|
+
throw new Error(`Refusing to overwrite an authored file: ${name}`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const sources = Object.fromEntries(Object.entries(moduleSources).map(([name, path]) => [name, resolve(path)]));
|
|
175
|
+
const modules = new Map();
|
|
176
|
+
const declarations = Object.create(null);
|
|
177
|
+
for (const [module, source] of Object.entries(sources)) {
|
|
178
|
+
const fromOutput = relative(outDir, source);
|
|
179
|
+
if (!fromOutput.startsWith(`..${sep}`) && !isAbsolute(fromOutput))
|
|
180
|
+
throw new Error("Function definitions must be outside the generated output directory");
|
|
181
|
+
const definitions = await import(__rewriteRelativeImportExtension(Bun.pathToFileURL(source).href));
|
|
182
|
+
modules.set(module, definitions);
|
|
183
|
+
declarations[module] = Object.entries(definitions).filter(([, value]) => isFunctionDefinition(value)).map(([name]) => {
|
|
184
|
+
if (!validExportName(name))
|
|
185
|
+
throw new Error(`Invalid function export name: ${name}`);
|
|
186
|
+
return name;
|
|
187
|
+
});
|
|
188
|
+
if (!declarations[module].length)
|
|
189
|
+
throw new Error(`No query/mutation exports in ${source}`);
|
|
190
|
+
}
|
|
191
|
+
const shapes = await compileFunctionShapes(sources, declarations);
|
|
192
|
+
const files = new Map();
|
|
193
|
+
const contracts = [];
|
|
194
|
+
const manifest = Object.create(null);
|
|
195
|
+
const limits = resolveLimits(options.limits);
|
|
196
|
+
let maxOutputBytes = Math.max(16 * 1024 * 1024, limits.inputBytes, limits.outputBytes);
|
|
197
|
+
for (const [module, sourcePath] of Object.entries(moduleSources)) {
|
|
198
|
+
assertModuleName(module);
|
|
199
|
+
const source = resolve(sourcePath);
|
|
200
|
+
const definitions = modules.get(module);
|
|
201
|
+
const lines = [
|
|
202
|
+
header.trimEnd(),
|
|
203
|
+
`import type * as $definitions from ${JSON.stringify(importPath(dirname(resolve(outDir, `${module}.ts`)), source))}`,
|
|
204
|
+
`import { runtime as $runtime } from ${JSON.stringify(importPath(dirname(resolve(outDir, `${module}.ts`)), resolve(outDir, "runtime.ts")))}`,
|
|
205
|
+
"",
|
|
206
|
+
];
|
|
207
|
+
const bindings = new Set();
|
|
208
|
+
bindings.add("valueCodec");
|
|
209
|
+
let count = 0;
|
|
210
|
+
for (const [name, definition] of Object.entries(definitions).sort(([a], [b]) => a.localeCompare(b))) {
|
|
211
|
+
if (!isFunctionDefinition(definition))
|
|
212
|
+
continue;
|
|
213
|
+
if (!validExportName(name))
|
|
214
|
+
throw new Error(`Invalid function export name: ${name}`);
|
|
215
|
+
const binding = definition.kind === "query" ? "queryBinding" : "mutationBinding";
|
|
216
|
+
bindings.add(binding);
|
|
217
|
+
const shape = shapes.get(`${module}.${name}`);
|
|
218
|
+
if (!shape)
|
|
219
|
+
throw new TypeError(`No portable value contract for ${module}.${name}`);
|
|
220
|
+
if (shape.paginated && definition.kind !== "query")
|
|
221
|
+
throw new TypeError(`Paginated results require a query: ${module}.${name}`);
|
|
222
|
+
maxOutputBytes = Math.max(maxOutputBytes, definition.limits?.inputBytes ?? limits.inputBytes, definition.limits?.outputBytes ?? limits.outputBytes);
|
|
223
|
+
manifest[`${module}.${name}`] = { kind: definition.kind, ...shape, ...(definition.limits ? { limits: definition.limits } : {}) };
|
|
224
|
+
contracts.push(`${JSON.stringify(`${module}.${name}`)}: { kind: ${JSON.stringify(definition.kind)}, input: valueCodec(${JSON.stringify(shape.input)}), result: valueCodec(${JSON.stringify(shape.result)}) }`);
|
|
225
|
+
lines.push(`const $function${count} = $${binding}<typeof $definitions.${name}>($runtime, ${JSON.stringify(`${module}.${name}`)}, ${definition.hasInput}, { input: $valueCodec(${JSON.stringify(shape.input)}), result: $valueCodec(${JSON.stringify(shape.result)}) }${shape.paginated ? ", true" : ""})`);
|
|
226
|
+
lines.push(`export { $function${count} as ${name} }`);
|
|
227
|
+
count++;
|
|
228
|
+
}
|
|
229
|
+
if (count === 0)
|
|
230
|
+
throw new Error(`No query/mutation exports in ${source}`);
|
|
231
|
+
lines.splice(2, 0, `import { ${[...bindings]
|
|
232
|
+
.sort()
|
|
233
|
+
.map((binding) => `${binding} as $${binding}`)
|
|
234
|
+
.join(", ")} } from '@hulla/db/internal/client'`);
|
|
235
|
+
files.set(`${module}.ts`, `${lines.join("\n")}\n`);
|
|
236
|
+
}
|
|
237
|
+
const client = options.client === undefined ? undefined : clientConnection(options.client);
|
|
238
|
+
files.set("runtime.ts", `${header}import { ${client ? "createBrowserRuntime" : "createRuntimeScope"}, valueCodec } from '@hulla/db/internal/client'\n\nexport const contracts = {\n${contracts.join(",\n")}\n} as const\n${client
|
|
239
|
+
? `const browser = createBrowserRuntime(contracts, ${JSON.stringify(client)}, { maxResponseBytes: ${maxOutputBytes + 2 * 1024 * 1024} })\nexport const { runtime, setAuth, setHeaders, dispose } = browser`
|
|
240
|
+
: `export const runtime = createRuntimeScope()\nexport const setAuth = runtime.setAuth.bind(runtime)`}\n`);
|
|
241
|
+
files.set("functions.json", JSON.stringify({ generatedBy: "@hulla/db", limits: resolveLimits(options.limits), functions: manifest }, null, 2) + "\n");
|
|
242
|
+
// Validate ownership of every output before any write; never replace authored files.
|
|
243
|
+
await mkdir(outDir, { recursive: true });
|
|
244
|
+
for (const name of files.keys()) {
|
|
245
|
+
if (existing.includes(name) &&
|
|
246
|
+
!ownsOutput(name, await Bun.file(resolve(outDir, name)).text())) {
|
|
247
|
+
throw new Error(`Refusing to overwrite an authored file: ${name}`);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
for (const [name, contents] of files) {
|
|
251
|
+
await mkdir(dirname(resolve(outDir, name)), { recursive: true });
|
|
252
|
+
await Bun.write(resolve(outDir, name), contents);
|
|
253
|
+
}
|
|
254
|
+
// Retire only generator-owned modules, not other files in the directory.
|
|
255
|
+
for (const name of existing) {
|
|
256
|
+
if (name.endsWith(".ts") &&
|
|
257
|
+
!files.has(name) &&
|
|
258
|
+
!(await lstat(resolve(outDir, name))).isSymbolicLink() &&
|
|
259
|
+
(await Bun.file(resolve(outDir, name)).text()).startsWith(header)) {
|
|
260
|
+
await Bun.file(resolve(outDir, name)).delete();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
function ownsOutput(name, contents) {
|
|
265
|
+
if (contents.startsWith(schemaHeader))
|
|
266
|
+
throw new Error(`Function output conflicts with a generated schema file: ${name}`);
|
|
267
|
+
if (name !== "functions.json")
|
|
268
|
+
return contents.startsWith(header);
|
|
269
|
+
try {
|
|
270
|
+
return JSON.parse(contents).generatedBy === "@hulla/db";
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
}
|