### Install Evolu SDKs Source: https://evolu.dev/docs/local-first Install the necessary packages for your project environment. ```bash npm install @evolu/common @evolu/react @evolu/react-web ``` -------------------------------- ### Install Evolu Packages Source: https://evolu.dev/docs/local-first Commands to install the necessary Evolu packages for your project environment. ```bash npm install @evolu/common @evolu/web ``` -------------------------------- ### Usage examples for queryState Source: https://www.evolu.dev/llms-full.txt Examples demonstrating how to use queryState with static and derived queries in a Svelte environment. ```ts // Create your query const allTodos = evolu.createQuery((db) => ...); // Get all rows. const allTodosState = queryState(evolu, () => allTodos); ``` ```ts // some kind of state let someKindOfState = $state('someId'); // derive your query based other props const allTodos = $derived(evolu.createQuery((db) => use someKindOfState here )); // Get all rows, once someKindOfState changes, this allTodosState will be updated with the evolu query result const allTodosState = queryState(evolu, () => allTodos); // use allTodosState.rows in further calculations / UI ``` -------------------------------- ### Install Evolu for Vue Source: https://evolu.dev/docs/local-first Install the necessary packages to use Evolu within a Vue application. ```bash npm install @evolu/common @evolu/web @evolu/vue ``` -------------------------------- ### Usage Example Source: https://evolu.dev/docs/api-reference/common/local-first/functions/createOwnerWebSocketTransport Demonstrates how to initialize the transport with a relay URL. ```typescript // Create transport "wss://relay.evolu.dev?ownerId=..." const transport = createOwnerWebSocketTransport ``` -------------------------------- ### Install Evolu for Svelte Source: https://evolu.dev/docs/local-first Install the necessary packages to use Evolu within a Svelte application. ```bash npm install @evolu/common @evolu/web @evolu/svelte ``` -------------------------------- ### Install Evolu for Expo Source: https://evolu.dev/docs/local-first Install Evolu with Expo-compatible SQLite and crypto packages for Expo-managed projects. ```bash npm install @evolu/common @evolu/react @evolu/react-native \ expo-sqlite react-native-quick-crypto ``` -------------------------------- ### Basic Usage Source: https://evolu.dev/docs/api-reference/svelte/index.svelte/functions/queryState Example of creating a query and subscribing to its state. ```typescript // Create your query const allTodos = evolu.createQuery((db) => ...); // Get all rows. const allTodosState = queryState(evolu, () => allTodos); ``` -------------------------------- ### Usage of createUseEvolu Source: https://evolu.dev/docs/api-reference/react/index/functions/createUseEvolu Example showing how to initialize the hook and destructure methods like insert and update. ```typescript const useEvolu = createUseEvolu(evolu); const { insert, update } = useEvolu(); ``` -------------------------------- ### computeBalancedBuckets usage examples Source: https://evolu.dev/docs/api-reference/common/Number/functions/computeBalancedBuckets Examples showing successful bucket distribution and an error case when the minimum items per bucket cannot be satisfied. ```typescript computeBalancedBuckets(10, 3, 2); // Returns ok([4, 7, 10]) computeBalancedBuckets(5, 3, 2); // Returns err(6) ``` -------------------------------- ### Usage Examples for createIdAsUuidv7 Source: https://evolu.dev/docs/api-reference/common/Type/functions/createIdAsUuidv7 Examples showing how to generate a generic ID and a branded ID using createIdAsUuidv7. ```typescript const id = createIdAsUuidv7({ randomBytes, time }); const todoId = createIdAsUuidv7<"Todo">({ randomBytes, time }); ``` -------------------------------- ### Pipe Syntax Example Source: https://evolu.dev/docs/api-reference/common/Type/interfaces/BrandType Conceptual example showing how the definition would look using TC39 Hack pipes. ```ts // TrimmedString // |> minLength(8)(%) // |> maxLength(64)(%) // |> brand("SimplePassword", %) ``` -------------------------------- ### Install Evolu common package Source: https://evolu.dev/docs/library Use this command to add the core Evolu library to your project. ```bash npm install @evolu/common ``` -------------------------------- ### Initialize Evolu Source: https://evolu.dev/docs/local-first Setup the Evolu instance with React dependencies and wrap the application with the EvoluProvider. ```typescript import { createEvolu, SimpleName } from "@evolu/common"; import { createUseEvolu, EvoluProvider } from "@evolu/react"; import { evoluReactWebDeps } from "@evolu/react-web"; const evolu = createEvolu(evoluReactWebDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); // Wrap your app with {/* ... */} // Create a typed React Hook returning an instance of Evolu const useEvolu = createUseEvolu(evolu); // Use the Hook in your app const { insert, update } = useEvolu(); ``` -------------------------------- ### Using eqUndefined Source: https://evolu.dev/docs/api-reference/common/Eq/variables/eqUndefined An example showing the assignment of eqUndefined. ```typescript undefined = eqStrict; ``` -------------------------------- ### Install Evolu for React Native Source: https://evolu.dev/docs/local-first Install Evolu along with required native SQLite and crypto dependencies for React Native projects. ```bash npm install @evolu/common @evolu/react @evolu/react-native \ @op-engineering/op-sqlite react-native-quick-crypto ``` -------------------------------- ### Usage Example Source: https://evolu.dev/docs/api-reference/common/Number/functions/isBetween Demonstrates creating a range predicate and testing values against it. ```typescript const isBetween10And20 = isBetween(10, 20); console.log(isBetween10And20(15)); // true console.log(isBetween10And20(25)); // false ``` -------------------------------- ### get() Source: https://evolu.dev/docs/api-reference/common/Store/interfaces/Store Retrieves the current state of the store. ```APIDOC ## get() ### Description Returns the current state of the store. ### Signature `get(): T` ### Returns - **T** - The current state value. ``` -------------------------------- ### Importing modules Source: https://evolu.dev/docs/conventions Example of importing specific members from a module. ```ts import { bar, baz } from "Foo.ts"; ``` -------------------------------- ### Usage Example Source: https://evolu.dev/docs/api-reference/common/local-first/functions/parseOwnerIdFromOwnerWebSocketTransportUrl Demonstrates extracting an OwnerId from a sync URL. ```typescript parseOwnerIdFromOwnerWebSocketTransportUrl("/sync?ownerId=_12345678abcdefgh"); // Returns: OwnerId or null ``` -------------------------------- ### Usage examples for assert Source: https://evolu.dev/docs/api-reference/common/Assert/variables/assert Demonstrates basic usage and how to use assert to narrow types for TypeScript. ```typescript assert(true, "true is not true"); // no-op assert(false, "true is not true"); // throws Error const length = buffer.getLength(); // We know length is logically non-negative, but TypeScript doesn't assert(NonNegativeInt.is(length), "buffer length should be non-negative"); ``` -------------------------------- ### Configure Evolu Relay Transport Source: https://evolu.dev/docs/api-reference/common/local-first/interfaces/RelayConfig Example of setting up a WebSocket transport and initializing Evolu with the relay configuration. ```typescript // Client const transport = createOwnerWebSocketTransport({ url: "wss://relay.evolu.dev", ownerId: owner.id, }); const evolu = createEvolu(deps)(Schema, { transports: [transport], }); // Relay isOwnerAllowed: (ownerId) => Promise.resolve(ownerId === "6jy_2F4RT5qqeLgJ14_dnQ"), ``` -------------------------------- ### Initialize Evolu with Schema Source: https://evolu.dev/docs/api-reference/common/local-first/functions/createEvolu Example showing how to define a schema using Evolu types and initialize the Evolu instance. ```ts const TodoId = id("Todo"); type TodoId = InferType; const TodoCategoryId = id("TodoCategory"); type TodoCategoryId = InferType; const NonEmptyString50 = maxLength(50, NonEmptyString); type NonEmptyString50 = InferType; const Schema = { todo: { id: TodoId, title: NonEmptyString1000, isCompleted: nullOr(SqliteBoolean), categoryId: nullOr(TodoCategoryId), }, todoCategory: { id: TodoCategoryId, name: NonEmptyString50, }, }; const evolu = createEvolu(evoluReactDeps)(Schema); ``` -------------------------------- ### Usage Example Source: https://evolu.dev/docs/api-reference/common/Type/functions/createBaseTypeErrorFormatter Example of creating a specific error formatter for a StringError type. ```ts export const formatStringError = createBaseTypeErrorFormatter(); ``` -------------------------------- ### Configure Database Transports Source: https://evolu.dev/docs/api-reference/common/local-first/interfaces/DbConfig Examples showing single, multiple, local-only, and authenticated transport configurations. ```typescript // Single WebSocket relay transports: [{ type: "WebSocket", url: "wss://relay1.example.com" }]; // Multiple WebSocket relays for redundancy transports: [ { type: "WebSocket", url: "wss://relay1.example.com" }, { type: "WebSocket", url: "wss://relay2.example.com" }, { type: "WebSocket", url: "wss://relay3.example.com" }, ]; // Local-only instance (no sync) - useful for device settings or when relay // URL will be provided later (e.g., after authentication), allowing users // to work offline before the app connects transports: []; // Using createOwnerWebSocketTransport helper for relay authentication transports: [ createOwnerWebSocketTransport({ url: "ws://localhost:4000", ownerId, }), ]; ``` -------------------------------- ### Initialize Evolu Instance Source: https://evolu.dev/docs/api-reference/common/local-first/functions/createEvolu Example showing how to define a schema and initialize an Evolu instance using platform dependencies. ```typescript const TodoId = id("Todo"); type TodoId = InferType; const TodoCategoryId = id("TodoCategory"); type TodoCategoryId = InferType; const NonEmptyString50 = maxLength(50, NonEmptyString); type NonEmptyString50 = InferType; const Schema = { todo: { id: TodoId, title: NonEmptyString1000, isCompleted: nullOr(SqliteBoolean), categoryId: nullOr(TodoCategoryId), }, todoCategory: { id: TodoCategoryId, name: NonEmptyString50, }, }; const evolu = createEvolu(evoluReactDeps)(Schema); ``` -------------------------------- ### Registering a callback Source: https://evolu.dev/docs/api-reference/common/Callbacks/interfaces/Callbacks Example of creating a callback manager and registering a simple callback function. ```typescript // No-argument callbacks const callbacks = createCallbacks(deps); const id = callbacks.register(() => ``` -------------------------------- ### decodeFlags Usage Example Source: https://evolu.dev/docs/api-reference/common/local-first/Protocol/functions/decodeFlags Example showing how to decode a specific number of flags from a buffer. ```ts const flags = decodeFlags(buffer, 3); // Decode 3 flags ``` -------------------------------- ### Configure Evolu Instances Source: https://evolu.dev/docs/api-reference/common/local-first/interfaces/DbConfig Demonstrates creating both a local-only instance for device settings and a main synced instance for user data. ```typescript const ConfigId = id("Config"); type ConfigId = typeof ConfigId.Type; const DeviceSchema = { config: { id: ConfigId, key: NonEmptyString50, value: NonEmptyString50, }, }; // Local-only instance for device settings (no sync) const deviceEvolu = createEvolu(evoluReactWebDeps)(DeviceSchema, { name: SimpleName.orThrow("MyApp-Device"), transports: [], // No sync - stays local to device }); // Main synced instance for user data const evolu = createEvolu(evoluReactWebDeps)(MainSchema, { name: SimpleName.orThrow("MyApp"), // Default transports for sync }); ``` -------------------------------- ### Usage example for between Source: https://evolu.dev/docs/api-reference/common/Type/variables/between Demonstrates creating a branded type for a range and validating values against it. ```typescript const Between1And10 = between(1, 10)(PositiveNumber); const result = Between1And10.from(5); // ok(5) const errorResult = Between1And10.from(11); // err ``` -------------------------------- ### Implement BrandFactory Example Source: https://evolu.dev/docs/api-reference/common/Type/type-aliases/BrandFactory An example implementation of a BrandFactory that creates a 'Trimmed' branded type. ```typescript const trimmed: BrandFactory<"Trimmed", string, TrimmedError> = (parent) => brand("Trimmed", parent, (value) => value.trim().length === value.length ? ok(value) : err({ type: "Trimmed", value }), ); ``` -------------------------------- ### Example Usage of createResources Source: https://evolu.dev/docs/api-reference/common/Resources/functions/createResources Demonstrates how to initialize resources like WebSocket connections and manage consumer associations with reference counting. ```typescript // WebSocket connections interface WebSocketConfig { readonly url: WebSocketUrl; } type WebSocketUrl = string & Brand<"WebSocketUrl">; type UserId = string & Brand<"UserId">; const webSockets = createResources< WebSocket, WebSocketUrl, WebSocketConfig, User, UserId >({ createResource: (config) => new WebSocket(config.url), getResourceKey: (config) => config.url, getConsumerId: (user) => user.id, disposalDelay: 1000, }); // Add users to WebSocket connections webSockets.addConsumer(user1, [ { url: "ws://server1.com" as WebSocketUrl }, { url: "ws://server2.com" as WebSocketUrl }, ]); webSockets.addConsumer(user2, [{ url: "ws://server1.com" as WebSocketUrl }]); // Remove users - server1 stays alive (user2 still using it) webSockets.removeConsumer(user1, [ { url: "ws://server1.com" as WebSocketUrl }, { url: "ws://server2.com" as WebSocketUrl }, ]); // server2 gets disposed after delay, server1 stays alive ``` -------------------------------- ### Create and Configure Evolu Instance Source: https://evolu.dev/docs/local-first Initializes the Evolu instance with required dependencies and wraps the application with the EvoluProvider. ```typescript import { createEvolu, SimpleName } from "@evolu/common"; import { createUseEvolu, EvoluProvider } from "@evolu/react"; import { evoluReactWebDeps } from "@evolu/react-web"; const evolu = createEvolu(evoluReactWebDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); // Wrap your app with { /* ... ``` -------------------------------- ### NullablePartial Usage Example Source: https://evolu.dev/docs/api-reference/common/Types/type-aliases/NullablePartial An example demonstrating how NullablePartial affects properties that allow null values. ```typescript type Example = { required: string; optionalWithNull: string | null; }; ``` -------------------------------- ### Millis Maximum Value Example Source: https://evolu.dev/docs/api-reference/common/local-first/variables/Millis Demonstration of the maximum representable date using the Millis constraint. ```txt new Date(281474976710654).toString() = Tue Aug 02 10889 07:31:49 ``` -------------------------------- ### Development Script Configuration Source: https://evolu.dev/docs/api-reference/common/Console/interfaces/Console Example configuration for package.json scripts to filter console output using grep. ```json { "scripts": { "dev:relay": "node app.js | grep \"[relay]\"", "dev:db": "node app.js | grep -E \"[db]|[sql]\"" } } ``` -------------------------------- ### Task.timeout Usage Example Source: https://evolu.dev/docs/api-reference/common/Task/functions/timeout An example demonstrating the definition of a FetchError interface and the initialization of a task-based fetch function. ```typescript interface FetchError { readonly type: "FetchError"; readonly error: unknown; } // Task version of fetch with proper error handling and cancellation support. const fetch ``` -------------------------------- ### createConsole(config) Source: https://evolu.dev/docs/api-reference/common/Console/functions/createConsole Initializes a new Console instance. ```APIDOC ## createConsole(config) ### Description Creates and returns a `Console` instance based on the provided configuration. ### Signature `function createConsole(config): Console;` ### Parameters - **config** (any) - The configuration object required to initialize the console. ``` -------------------------------- ### createSqlite(name, options?) Source: https://evolu.dev/docs/api-reference/common/Sqlite/functions/createSqlite Initializes a SQLite database instance with the specified name and optional configuration. ```APIDOC ## createSqlite(name, options?) ### Description Initializes a SQLite database instance. Returns a promise that resolves to a Result containing the Sqlite instance or a SqliteError. ### Parameters - **name** (string & Brand<"UrlSafeString"> & Brand<"SimpleName">) - Required - The name of the SQLite database. - **options** (SqliteDriverOptions) - Optional - Configuration options for the SQLite driver. ### Returns - **Promise>** - A promise that resolves to a Result object containing the initialized Sqlite instance or an error. ``` -------------------------------- ### Usage example for length Source: https://evolu.dev/docs/api-reference/common/Type/variables/length Demonstrates creating a branded string type with an exact length constraint. ```typescript // string & Brand<"Length1"> const Length1String = length(1)(String); ``` -------------------------------- ### Usage Examples Source: https://evolu.dev/docs/api-reference/common/Time/functions/durationToNonNegativeInt Examples showing how to convert various duration strings and numeric millisecond values using durationToNonNegativeInt. ```typescript durationToNonNegativeInt("0ms"); // 0 ✅ durationToNonNegativeInt("500ms"); // 500 ✅ durationToNonNegativeInt("30s"); // 30000 ✅ durationToNonNegativeInt("5m"); // 300000 ✅ durationToNonNegativeInt("12h"); // 43200000 ✅ durationToNonNegativeInt("7d"); // 604800000 ✅ durationToNonNegativeInt("2h 45m"); // 9900000 ✅ durationToNonNegativeInt(5000); // 5000 ✅ (already milliseconds) ``` -------------------------------- ### EvoluConfig Configuration Options Source: https://evolu.dev/docs/api-reference/common/local-first/interfaces/EvoluConfig Documentation for the configuration properties available when initializing Evolu. ```APIDOC ## EvoluConfig ### Properties - **externalAppOwner** (AppOwner) - Optional - Used for managing AppOwner creation and persistence externally. If omitted, Evolu handles this automatically. - **indexes** (IndexesConfig) - Optional - Defines SQLite indexes for the database. Note that table and column names are not strictly typed. - **inMemory** (boolean) - Optional - If true, uses an in-memory SQLite database instead of persistent storage. Defaults to `false`. - **maxDrift** (number) - Optional - Maximum physical clock drift allowed in milliseconds. Defaults to 300,000 (5 minutes). - **name** (string) - Optional - The unique name of the Evolu instance, used as the SQLite filename. Defaults to `Evolu`. - **reloadUrl** (string) - Optional - The URL to reload browser tabs after a reset or restore operation. Defaults to `/`. - **transports** (OwnerWebSocketTransport[]) - Optional - Defines the synchronization transports for the instance. ``` -------------------------------- ### Usage example for maxLength Source: https://evolu.dev/docs/api-reference/common/Type/variables/maxLength Demonstrates how to create a branded string type with a maximum length of 100. ```typescript // string & Brand<"MaxLength100"> const String100 = maxLength(100)(String); ``` -------------------------------- ### Initialize Evolu in React Source: https://evolu.dev/docs/local-first Setup the Evolu client and provide it to the React component tree using EvoluProvider. ```tsx import { createEvolu, SimpleName } from "@evolu/common"; import { createUseEvolu, EvoluProvider } from "@evolu/react"; import { evoluReactWebDeps } from "@evolu/react-web"; const evolu = createEvolu(evoluReactWebDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); // Wrap your app with {/* ... */} // Create a typed React Hook returning an instance of Evolu const useEvolu = createUseEvolu(evolu); // Use the Hook in your app const { insert, update } = useEvolu(); ``` -------------------------------- ### BrandFactory Usage Example Source: https://evolu.dev/docs/api-reference/common/Type/type-aliases/BrandFactory An example demonstrating how to use BrandFactory to create a branded 'Trimmed' string type with custom validation logic. ```APIDOC ## BrandFactory ### Description Helper type for Type Factory that creates a branded Type. ### Usage Example ```ts const trimmed: BrandFactory<"Trimmed", string, TrimmedError> = (parent) => brand("Trimmed", parent, (value) => value.trim().length === value.length ? ok(value) : err(...) ); ``` ``` -------------------------------- ### Initialize Evolu Instance Source: https://www.evolu.dev/llms-full.txt Creates an Evolu instance for specific environments and configures the sync transport. ```tsx const evolu = createEvolu(evoluReactWebDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); // Wrap your app with {/* ... */} // Create a typed React Hook returning an instance of Evolu const useEvolu = createUseEvolu(evolu); // Use the Hook in your app const { insert, update } = useEvolu(); ``` ```tsx const evolu = createEvolu(evoluReactNativeDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); // Wrap your app with {/* ... */} // Create a typed React Hook returning an instance of Evolu const useEvolu = createUseEvolu(evolu); // Use the Hook in your app const { insert, update } = useEvolu(); ``` ```tsx const evolu = createEvolu(evoluReactNativeDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); // Wrap your app with {/* ... */} // Create a typed React Hook returning an instance of Evolu const useEvolu = createUseEvolu(evolu); // Use the Hook in your app const { insert, update } = useEvolu(); ``` ```ts const evolu = Evolu.createEvolu(evoluSvelteDeps)(Schema, { name: Evolu.SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); ``` ```ts const evolu = createEvolu(evoluWebDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); export default defineComponent({ setup() { provideEvolu(evolu); const { insert, update } = evolu; return { insert, update }; }, }); ``` ```ts const evolu = createEvolu(evoluWebDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); ``` -------------------------------- ### Using useQuery to fetch data Source: https://evolu.dev/docs/api-reference/react/index/functions/useQuery Examples of using useQuery to retrieve all rows or a specific row from the database. ```typescript // Get all rows. const rows = useQuery(allTodos); // Get rows for a specific todo (the first row can be null). const rows = useQuery( ``` -------------------------------- ### get() Source: https://www.evolu.dev/llms-full.txt Retrieves the current list of queries. ```APIDOC ## get() ### Description Returns an array of current queries. ### Signature `get(): readonly Query[]` ``` -------------------------------- ### createSqlite() Source: https://evolu.dev/docs/api-reference/common/Sqlite/functions/createSqlite Initializes a SQLite instance based on the provided dependencies. ```APIDOC ## createSqlite(deps) ### Description Initializes a SQLite instance. It takes dependencies as an argument and returns a function that accepts a database name and optional configuration to create the SQLite instance. ### Signature `function createSqlite(deps): (name, options?) => Promise>` ### Parameters - **deps** (object) - Required - The dependencies required to initialize the SQLite instance. ### Returns - **Promise>** - A promise that resolves to a Result object containing either the initialized Sqlite instance or a SqliteError. ``` -------------------------------- ### Configure NodeJsRelayConfig with WebSocket Transport Source: https://evolu.dev/docs/api-reference/nodejs/index/interfaces/NodeJsRelayConfig Example of initializing Evolu with a WebSocket transport and defining the isOwnerAllowed callback. ```typescript // Client const transport = createOwnerWebSocketTransport({ url: "wss://relay.evolu.dev", ownerId: owner.id, }); const evolu = createEvolu(deps)(Schema, { transports: [transport], }); // Relay isOwnerAllowed: (ownerId) => Promise.resolve(ownerId === "6jy_2F4RT5qqeLgJ14_dnQ"), ``` -------------------------------- ### Configure Evolu Client Source: https://evolu.dev/docs/local-first Standard initialization pattern for the Evolu client using web dependencies and custom sync transport configuration. ```ts import { createEvolu, SimpleName } from "@evolu/common"; import { evoluWebDeps } from "@evolu/web"; const evolu = createEvolu(evoluWebDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); ``` -------------------------------- ### useQuery Usage Examples Source: https://evolu.dev/docs/api-reference/react/index/functions/useQuery Demonstrates various ways to use the useQuery hook, including fetching all rows, specific rows, disabling subscriptions, and preloading. ```typescript // Get all rows. const rows = useQuery(allTodos); // Get rows for a specific todo (the first row can be null). const rows = useQuery(todoById(1)); // Get all rows, but without subscribing to changes. const rows = useQuery(allTodos, { once: true }); // Preload a query (rarely needed). const allTodosPromise = evolu.loadQuery(allTodos); const rows = useQuery(allTodos, { promise: allTodosPromise }); ``` -------------------------------- ### time(label?) Source: https://www.evolu.dev/llms-full.txt Starts a timer with an optional label. ```APIDOC ## time(label?) ### Description Starts a timer with an optional label. ### Parameters - **label** (string) - Optional - The label for the timer. ``` -------------------------------- ### Define and Create WebSocket Resources Source: https://evolu.dev/docs/api-reference/common/Resources/functions/createResources Example showing the configuration of WebSocket resources using createResources with specific types and branding. ```typescript // WebSocket connections interface WebSocketConfig { readonly url: WebSocketUrl; } type WebSocketUrl = string & Brand<"WebSocketUrl">; type UserId = string & Brand<"UserId">; const webSockets = createResources< WebSocket, WebSocketUrl, WebSocketConfig, User, UserId >({ ``` -------------------------------- ### Querying and Subscribing to Data in Vanilla JS Source: https://evolu.dev/docs/local-first Demonstrates how to perform a one-time load of query results and how to set up a subscription to react to data changes. ```ts // Query once const todos = await evolu.loadQuery(allTodos); const unsubscribe = evolu.subscribeQuery(allTodos)(() => { const rows = evolu.getQueryRows(allTodos); // do something with rows }); ``` -------------------------------- ### createSync() Source: https://www.evolu.dev/llms-full.txt Initializes the synchronization service for Evolu. It takes a set of required dependencies and returns a function that accepts a SyncConfig to produce a Result containing either the Sync instance or a SqliteError. ```APIDOC ## Function: createSync() ### Description Initializes the synchronization service. This function requires a set of dependencies (Clock, Console, WebSocket, DbSchema, RandomBytes, Random, Sqlite, SymmetricCrypto, Time, and TimestampConfig) and returns a factory function that accepts a `SyncConfig` to return a `Result`. ### Signature `createSync(deps): (config) => Result` ### Parameters - **deps** (Object) - Required - A collection of required dependencies including ClockDep, ConsoleDep, CreateWebSocketDep, DbSchemaDep, RandomBytesDep, RandomDep, SqliteDep, SymmetricCryptoDep, TimeDep, and TimestampConfigDep. ### Returns - **(config) => Result** - A function that takes a `SyncConfig` object and returns a `Result` containing the `Sync` instance or a `SqliteError`. ``` -------------------------------- ### get(key) Source: https://evolu.dev/docs/api-reference/common/Cache/interfaces/Cache Retrieves the value for a key, or undefined if not present. ```APIDOC ### get(key) Retrieves the value for a key, or undefined if not present. #### Signature `get(key: K) => V | undefined` ``` -------------------------------- ### Usage example for createLruCache Source: https://evolu.dev/docs/api-reference/common/Cache/functions/createLruCache Demonstrates initializing a cache with a capacity of 2 and observing eviction behavior when adding a third item. ```typescript const cache = createLruCache(2); cache.set("a", 1); cache.set("b", 2); cache.set("c", 3); // Evicts "a" cache.has("a"); // false ``` -------------------------------- ### Create Evolu instance Source: https://www.evolu.dev/llms-full.txt Initialize the Evolu instance for your specific environment and wrap the application with the provider. ```tsx const evolu = createEvolu(evoluReactWebDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); // Wrap your app with {/* ... */} // Create a typed React Hook returning an instance of Evolu const useEvolu = createUseEvolu(evolu); // Use the Hook in your app const { insert, update } = useEvolu(); ``` ```tsx const evolu = createEvolu(evoluReactNativeDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); // Wrap your app with {/* ... ``` -------------------------------- ### SimpleName usage Source: https://www.evolu.dev/llms-full.txt Example of validating a string using the SimpleName type. ```typescript SimpleName.from("data-report-123"); if (result.ok) { console.log("Valid SimpleName string:", result.value); } else { console.error("Invalid SimpleName string:", result.error); } ``` -------------------------------- ### Initialize and use an LRU cache Source: https://evolu.dev/docs/api-reference/common/Cache/functions/createLruCache Demonstrates creating a cache with a capacity of 2 and observing eviction behavior when adding a third item. ```ts const cache = createLruCache(2); cache.set("a", 1); cache.set("b", 2); cache.set("c", 3); // Evicts "a" cache.has("a"); // false ``` -------------------------------- ### Declare ReadonlyArray Source: https://evolu.dev/docs/conventions Example of defining a constant array with the ReadonlyArray type. ```ts // Use ReadonlyArray for immutable arrays. const values: ReadonlyArray = ["a", "b", "c"]; ``` -------------------------------- ### createEvolu(deps)(schema, config?) Source: https://evolu.dev/docs/api-reference/common/local-first/functions/createEvolu Initializes an Evolu instance with the provided schema and optional configuration. The function uses instance caching to manage database connections safely. ```APIDOC ## createEvolu ### Description Initializes an Evolu instance. It uses instance caching based on the configuration name to enable hot reloading and prevent database corruption from multiple connections. ### Parameters - **deps** (EvoluDeps) - Required - Dependencies required for initialization. - **schema** (S) - Required - The database schema definition. - **config** (EvoluConfig) - Optional - Configuration settings including instance name. ### Returns - **Evolu** - Returns an initialized Evolu instance. ### Example ```ts const Schema = { todo: { id: TodoId, title: NonEmptyString1000, isCompleted: nullOr(SqliteBoolean), categoryId: nullOr(TodoCategoryId), }, todoCategory: { id: TodoCategoryId, name: NonEmptyString50, }, }; const evolu = createEvolu(evoluReactDeps)(Schema); ``` ``` -------------------------------- ### Define SimplePassword Source: https://evolu.dev/docs/api-reference/common/Type/interfaces/RecursiveType Example definition of a custom type for password validation. ```ts export const SimplePassword = ``` -------------------------------- ### Ref Usage and Dependency Examples Source: https://www.evolu.dev/llms-full.txt Demonstrates basic state manipulation using Ref and how to define a dependency interface. ```ts const count = createRef(0); count.set(1); count.modify((n) => n + 1); console.log(count.get()); // 2 ``` ```ts interface CounterRefDep { readonly counterRef: Ref; } ``` -------------------------------- ### Example Usage of computeBalancedBuckets Source: https://evolu.dev/docs/api-reference/common/Number/functions/computeBalancedBuckets Demonstrates the function call with specific parameters. ```typescript computeBalancedBuckets(10, 3, 2); ``` -------------------------------- ### Using eqNull Source: https://evolu.dev/docs/api-reference/common/Eq/variables/eqNull An example of assigning the eqNull equality check to a variable. ```typescript null = eqStrict; ``` -------------------------------- ### Query Data with Evolu Source: https://evolu.dev/docs/local-first Shows how to create a query using the evolu.createQuery method with a Kysely-based builder. ```ts const allTodos = evolu.createQuery((db) => ``` -------------------------------- ### hexToBytes Usage Example Source: https://evolu.dev/docs/api-reference/common/Buffer/functions/hexToBytes Demonstrates converting a hex string into a Uint8Array. ```typescript hexToBytes("cafe0123"); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) ``` -------------------------------- ### createEvolu(deps) Source: https://evolu.dev/docs/api-reference/common/local-first/functions/createEvolu Initializes the Evolu instance using the provided dependencies. ```APIDOC ## createEvolu(deps) ### Description Initializes an Evolu instance. It takes dependencies as an argument and returns a function that accepts a schema and an optional configuration to create the Evolu instance. ### Signature `function createEvolu(deps): (schema, config?) => Evolu` ``` -------------------------------- ### Create and Manage WebSocket Resources Source: https://evolu.dev/docs/api-reference/common/Resources/functions/createResources Demonstrates initializing a resource manager for WebSockets and tracking consumer usage to handle automatic disposal. ```ts // WebSocket connections interface WebSocketConfig { readonly url: WebSocketUrl; } type WebSocketUrl = string & Brand<"WebSocketUrl">; type UserId = string & Brand<"UserId">; const webSockets = createResources< WebSocket, WebSocketUrl, WebSocketConfig, User, UserId >({ createResource: (config) => new WebSocket(config.url), getResourceKey: (config) => config.url, getConsumerId: (user) => user.id, disposalDelay: 1000, }); // Add users to WebSocket connections webSockets.addConsumer(user1, [ { url: "ws://server1.com" as WebSocketUrl }, { url: "ws://server2.com" as WebSocketUrl }, ]); webSockets.addConsumer(user2, [{ url: "ws://server1.com" as WebSocketUrl }]); // Remove users - server1 stays alive (user2 still using it) webSockets.removeConsumer(user1, [ { url: "ws://server1.com" as WebSocketUrl }, { url: "ws://server2.com" as WebSocketUrl }, ]); // server2 gets disposed after delay, server1 stays alive ``` -------------------------------- ### bytesToHex usage example Source: https://evolu.dev/docs/api-reference/common/Buffer/functions/bytesToHex Demonstrates converting a Uint8Array to a hex string. ```typescript bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123' ``` -------------------------------- ### Registering and Executing Callbacks Source: https://evolu.dev/docs/api-reference/common/Callbacks/interfaces/Callbacks Demonstrates basic callback registration and execution, including passing arguments to the callback function. ```typescript console.log("called")); callbacks.execute(id); // With argument callbacks const stringCallbacks = createCallbacks(deps); const id = stringCallbacks.register((value) => { console.log(value); }); stringCallbacks.execute(id, "hello"); // Promise.withResolvers pattern const promiseCallbacks = createCallbacks(deps); const { promise, resolve } = Promise.withResolvers(); const id = promiseCallbacks.register(resolve); promiseCallbacks.execute(id, ``` -------------------------------- ### Usage of firstInArray Source: https://evolu.dev/docs/api-reference/common/Array/functions/firstInArray Example demonstrating how to retrieve the first element from an array. ```typescript firstInArray(["a", "b", "c"]); // "a" ``` -------------------------------- ### getResource Source: https://evolu.dev/docs/api-reference/common/Resources/interfaces/Resources Gets the resource for the specified key, or null if it doesn't exist. ```APIDOC ## getResource(key) ### Description Gets the resource for the specified key, or null if it doesn't exist. ### Parameters - **key** (string) - Required - The resource key to retrieve. ``` -------------------------------- ### Implement database schema Source: https://evolu.dev/docs/api-reference/common/local-first/type-aliases/EvoluSchema Example showing how to define table structures using IDs, string constraints, and nullable types. ```typescript const TodoId = id("Todo"); type TodoId = typeof TodoId.Type; const TodoCategoryId = id("TodoCategory"); type TodoCategoryId = typeof TodoCategoryId.Type; const NonEmptyString50 = maxLength(50)(NonEmptyString); type NonEmptyString50 = typeof NonEmptyString50.Type; // Database schema. const Schema = { todo: { id: TodoId, title: NonEmptyString1000, isCompleted: nullable(SqliteBoolean), categoryId: nullable(TodoCategoryId), }, todoCategory: { id: TodoCategoryId, name: NonEmptyString50, json: nullable(SomeJson), }, }; ``` -------------------------------- ### getConsumer Source: https://evolu.dev/docs/api-reference/common/Resources/interfaces/Resources Gets the consumer for the specified consumer ID, or null if not found. ```APIDOC ## getConsumer ### Description Gets the consumer for the specified consumer ID, or null if not found or not using any. ### Signature `getConsumer(consumerId: TConsumerId) => TConsumer | null` ``` -------------------------------- ### Generated SQL for jsonObjectFrom Source: https://evolu.dev/docs/api-reference/common/local-first/Public/namespaces/kysely/functions/jsonObjectFrom The resulting SQLite query generated by the jsonObjectFrom example. ```sql select "id", ( select json_object( 'pet_id', "obj"."pet_id", 'name', "obj"."name" ) from ( select "pet"."id" as "pet_id", "pet"."name" from "pet" where "pet"."owner_id" = "person"."id" and "pet"."is_favorite" = ? ) as obj ) as "favorite_pet" from "person"; ``` -------------------------------- ### Creating and using a mutex Source: https://evolu.dev/docs/api-reference/common/Task/functions/createMutex This example demonstrates initializing a mutex and using it within a task to protect a shared resource. ```typescript const mutex = createMutex(); const updateTask = (id: number) => toTask((context) => tryAsync( () => updateSharedResource(id, context), (error): UpdateError => ({ type: "UpdateError" ``` -------------------------------- ### Usage Example for encodeFlags Source: https://evolu.dev/docs/api-reference/common/local-first/Protocol/functions/encodeFlags Demonstrates how to call encodeFlags with an array of boolean values. ```ts encodeFlags(buffer, [true, false, true]); // Encodes bits 0, 1, 2 ``` -------------------------------- ### createStore(initialState, eq?) Source: https://evolu.dev/docs/api-reference/common/Store/functions/createStore Creates a new store instance with an initial state and an optional equality function for change detection. ```APIDOC ## createStore(initialState, eq?) ### Description Creates a store with the given initial state. The store encapsulates its state, which can be read with `get` and updated with `set` or `modify`. All changes are broadcast to subscribers. By default, state changes are detected using `===` (shallow equality). You can provide a custom equality function as the second argument. ### Parameters - **initialState** (T) - Required - The initial state of the store. - **eq** ((a: T, b: T) => boolean) - Optional - A custom equality function used to detect state changes. ### Returns - **Store** - A store instance containing the state. ``` -------------------------------- ### Usage of encodeFlags Source: https://evolu.dev/docs/api-reference/common/local-first/Protocol/functions/encodeFlags Example showing how to encode an array of boolean values into a buffer. ```typescript encodeFlags(buffer, [true, false, true]); // Encodes bits 0, 1, 2 ``` -------------------------------- ### Initialize Evolu in Vue Source: https://evolu.dev/docs/local-first Use the Vue-specific dependencies and provideEvolu helper to integrate with Vue components. ```ts import { defineComponent } from "vue"; import { createEvolu, SimpleName } from "@evolu/common"; import { evoluWebDeps } from "@evolu/web"; import { provideEvolu } from "@evolu/vue"; const evolu = createEvolu(evoluWebDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); export default defineComponent ``` -------------------------------- ### Partitioning and Sharing Data with Owners Source: https://www.evolu.dev/llms-full.txt Demonstrates how to partition data by project using ShardOwner and how to handle collaborative data using SharedOwner. ```typescript // Partition your own data by project (derived from your AppOwner) const projectOwner = deriveShardOwner(appOwner, [ "project", projectId, ]); evolu.insert( "task", { title: "Task 1" }, { ownerId: projectOwner.id }, ); // Collaborative data (independent owner shared with others) const sharedOwner = createSharedOwner(sharedSecret); evolu.insert( "comment", { text: "Hello" }, { ownerId: sharedOwner.id }, ); ``` -------------------------------- ### Usage example for decodeFlags Source: https://evolu.dev/docs/api-reference/common/local-first/Protocol/functions/decodeFlags Demonstrates how to decode a specific number of flags from a buffer. ```typescript const flags = decodeFlags(buffer, 3); // Decode 3 flags ``` -------------------------------- ### Initialize Evolu in React Native Source: https://evolu.dev/docs/local-first Setup the Evolu instance with React Native dependencies and wrap the application with the EvoluProvider. ```typescript import { createEvolu } from "@evolu/common"; import { createUseEvolu, EvoluProvider } from "@evolu/react"; import { evoluReactNativeDeps } from "@evolu/react-native/bare-op-sqlite"; const evolu = createEvolu(evoluReactNativeDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); // Wrap your app with { /* ... ``` -------------------------------- ### Json Usage Example Source: https://evolu.dev/docs/api-reference/common/Type/variables/Json Demonstrates how to use Json.from to validate JSON strings. ```typescript const result = Json.from('{"key":"value"}'); // ok const error = Json.from("invalid json"); // err ``` -------------------------------- ### Initialize Evolu in React Native Source: https://evolu.dev/docs/local-first Setup the Evolu instance with React Native dependencies and wrap the application with the EvoluProvider. ```typescript import { createEvolu, SimpleName } from "@evolu/common"; import { createUseEvolu, EvoluProvider } from "@evolu/react"; import { evoluReactNativeDeps } from "@evolu/react-native/expo-sqlite"; const evolu = createEvolu(evoluReactNativeDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); // Wrap your app with {/* ... */} // Create a typed React Hook returning an instance of Evolu const useEvolu = createUseEvolu(evolu); // Use the Hook in your app const { insert, update } = useEvolu(); ``` -------------------------------- ### useQuery(query, options) Source: https://evolu.dev/docs/api-reference/vue/index/functions/useQuery Load and subscribe to a query, returning a reactive ref that stays in sync with Evolu changes. ```APIDOC ## function useQuery(query, options) ### Description Load and subscribe to the query, returning a ref that stays in sync with Evolu changes. ### Parameters - **query** (Query) - Required - The query to execute. - **options** (Partial<{ once: boolean; promise: Promise> }>) - Optional - Configuration options for the query execution. ### Returns - **Readonly>>** - A reactive, read-only reference containing the query results. ### Example ```typescript // Get all rows. const rows = useQuery(allTodos); // Get rows for a specific todo. const rows = useQuery(todoById(1)); // Get all rows, but without subscribing to changes. const rows = useQuery(allTodos, { once: true }); // Use prefetched rows. const rows = useQuery(allTodos, { promise: allTodosPromise }); ``` ``` -------------------------------- ### BrandFactory Usage Source: https://evolu.dev/docs/api-reference/common/Type/type-aliases/BrandFactory Example of how to use BrandFactory to create a branded type with validation. ```APIDOC ## BrandFactory ### Description BrandFactory is a type alias used to define a factory function that creates branded types. It allows you to wrap a base type with a unique brand name and apply validation logic to ensure the value conforms to specific requirements. ### Example ```ts const trimmed: BrandFactory<"Trimmed", string, TrimmedError> = (parent) => brand("Trimmed", parent, (value) => value.trim().length === value.length ? ok(value) : err({ type: "Trimmed", value }), ); ``` ``` -------------------------------- ### Point Validation Examples Source: https://evolu.dev/docs/api-reference/common/Type/interfaces/RecursiveType Demonstrates successful and failed validation for a Point type. ```ts Point.from({ x: 1, y: 2 }); // ok Point.from({ x: 1, y: "2" }); // err -> nested Number error ``` -------------------------------- ### Usage Example Source: https://evolu.dev/docs/api-reference/common/Sqlite/functions/booleanToSqliteBoolean Demonstrates converting a boolean variable into its SQLite integer representation. ```typescript const isActive = true; const sqlValue = booleanToSqliteBoolean(isActive); // Returns 1 ``` -------------------------------- ### Defining a FetchError Interface Source: https://evolu.dev/docs/api-reference/common/Result/functions/tryAsync An example interface definition for handling fetch errors. ```typescript interface FetchError { readonly type: "FetchError"; readonly message: string; } ``` -------------------------------- ### Initialize Evolu for Svelte, Vue, and Vanilla JS Source: https://www.evolu.dev/llms-full.txt Configure the Evolu instance with schema and transport settings for non-React environments. ```ts const evolu = Evolu.createEvolu(evoluSvelteDeps)(Schema, { name: Evolu.SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); ``` ```ts const evolu = createEvolu(evoluWebDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); export default defineComponent({ setup() { provideEvolu(evolu); const { insert, update } = evolu; return { insert, update }; }, }); ``` ```ts const evolu = createEvolu(evoluWebDeps)(Schema, { name: SimpleName.orThrow("your-app-name"), transports: [{ type: "WebSocket", url: "wss://your-sync-url" }], // optional, defaults to free.evoluhq.com }); ```