### SpacetimeDB Client SDKs Source: https://spacetimedb.com/docs/getting-started Provides links to the quickstart guides for various client SDKs. These SDKs allow developers to interact with SpacetimeDB from different programming environments. ```Rust /docs/sdks/rust/quickstart ``` ```C# /docs/sdks/c-sharp/quickstart ``` ```C# (Unity) /docs/unity/part-1 ``` ```TypeScript /docs/sdks/typescript/quickstart ``` -------------------------------- ### SpacetimeDB Standalone Server Start Source: https://spacetimedb.com/docs/getting-started Instructions on how to start the SpacetimeDB standalone server locally. This involves installing the SpacetimeDB CLI and running the 'start' command. The server defaults to listening on port 3000. ```bash spacetime start ``` -------------------------------- ### Run SpacetimeDB using Docker Source: https://spacetimedb.com/install This Docker command starts a new instance of SpacetimeDB in a container. It pulls the latest image, removes the container when it exits, and maps port 3000 from the container to the host. ```docker docker run --rm --pull always -p 3000:3000 clockworklabs/spacetime start ``` -------------------------------- ### JavaScript: Initialize Remix Context and Manifest Source: https://spacetimedb.com/install This code snippet initializes the Remix framework's context and manifest for a web application. It configures various future flags for optimization and defines the application's routing structure, including entry points, modules, and CSS dependencies. This setup is crucial for the client-side rendering and routing logic of a Remix application. ```javascript window.__remixContext = { "basename": "/", "future": { "v3_fetcherPersist": true, "v3_relativeSplatPath": true, "v3_throwAbortReason": true, "v3_routeConfig": true, "v3_singleFetch": true, "v3_lazyRouteDiscovery": true, "unstable_optimizeDeps": true }, "isSpaMode": false }; window.__remixContext.stream = new ReadableStream({ start(controller) { window.__remixContext.streamController = controller; } }).pipeThrough(new TextEncoderStream());; import * as route0 from "/assets/root-BnKOThDk.js"; import * as route1 from "/assets/route-DGFzHQ-M.js"; import * as route2 from "/assets/route-D9oHoVAW.js"; window.__remixManifest = { "entry": { "module": "/assets/entry.client-BGtfi_QV.js", "imports": [ "/assets/jsx-runtime-B8m6gtXl.js", "/assets/index-Gwz8MVWd.js", "/assets/index-DQRDp3BA.js", "/assets/components-DZQBhqap.js" ], "css": [] }, "routes": { "root": { "id": "root", "path": "", "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": true, "module": "/assets/root-BnKOThDk.js", "imports": [ "/assets/jsx-runtime-B8m6gtXl.js", "/assets/index-Gwz8MVWd.js", "/assets/index-DQRDp3BA.js", "/assets/components-DZQBhqap.js", "/assets/index-BtvcE26l.js", "/assets/Layout-irBfUoRC.js", "/assets/preload-helper-D21cck6N.js", "/assets/client-only-wNC5TimA.js", "/assets/Container-DsvKPwib.js", "/assets/clsx-BeLtu-UY.js", "/assets/Icon-mnw7YCvf.js", "/assets/socials-pIkfUSDw.js", "/assets/index-ZcNkxdux.js", "/assets/Button-BsQzyESB.js" ], "css": [ "/assets/root-DgiNzMOf.css", "/assets/Layout-CTL7f1Hd.css", "/assets/Container-_6nMI5g_.css", "/assets/Button-C8_kLgtz.css" ] }, "routes/_marketing": { "id": "routes/_marketing", "parentId": "root", "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/route-DGFzHQ-M.js", "imports": [ "/assets/jsx-runtime-B8m6gtXl.js", "/assets/Layout-irBfUoRC.js", "/assets/components-DZQBhqap.js", "/assets/index-DQRDp3BA.js", "/assets/preload-helper-D21cck6N.js", "/assets/client-only-wNC5TimA.js", "/assets/Container-DsvKPwib.js", "/assets/clsx-BeLtu-UY.js", "/assets/Icon-mnw7YCvf.js", "/assets/socials-pIkfUSDw.js", "/assets/index-ZcNkxdux.js", "/assets/Button-BsQzyESB.js", "/assets/index-Gwz8MVWd.js" ], "css": [ "/assets/Layout-CTL7f1Hd.css", "/assets/Container-_6nMI5g_.css", "/assets/Button-C8_kLgtz.css" ] }, "routes/_marketing.install": { "id": "routes/_marketing.install", "parentId": "routes/_marketing", "path": "install", "hasAction": false, "hasLoader": false, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/route-D9oHoVAW.js", "imports": [ "/assets/jsx-runtime-B8m6gtXl.js", "/assets/clsx-BeLtu-UY.js", "/assets/index-BtvcE26l.js", "/assets/Hero-CrIvRlrd.js", "/assets/ScrollAnimation-B6l3GXNI.js", "/assets/index-ZcNkxdux.js" ], "css": [ "/assets/route-CY8vm6fK.css", "/assets/Hero-BQ6ieBxK.css", "/assets/ScrollAnimation-HNI5Nioi.css" ] }, "routes/_marketing._index": { "id": "routes/_marketing._index", "parentId": "routes/_marketing", "index": true, "hasAction": false, "hasLoader": true, "hasClientAction": false, "hasClientLoader": false, "hasErrorBoundary": false, "module": "/assets/route-Db0MPRTd.js", "imports": [ "/assets/route-DrgIsJ8p.js", "/assets/jsx-runtime-B8m6gtXl.js", "/assets/clsx-BeLtu-UY.js", "/assets/ScrollAnimation-B6l3GXNI.js", "/assets/index-ZcNkxdux.js", "/assets/Section-yNz5v-i9.js", "/assets/Button-BsQzyESB.js", "/assets/Icon-mnw7YCvf.js", "/assets/components-DZQBhqap.js", "/assets/index-Gwz8MVWd.js", "/assets/index-DQRDp3BA.js", "/assets/Modal-Drq6A6PB.js", "/assets/preload-helper-D21cck6N.js", "/assets/IllustrationSection-rAs5ohil.js", "/assets/Hero-CrIvRlrd.js" ], "css": [ "/assets/route-BD-0frUD.css", "/assets/ScrollAnimation-HNI5Nioi.css", "/assets/Section-BU2yo9B_.css", "/assets/Button-C8_kLgtz.css", "/assets/Modal-4Y8efbdF.css", "/assets/IllustrationSection-Ce9CQF80.css", "/assets/Hero-BQ6ieBxK.css" ] } }, "url": "/assets/manifest-2293bbea.js", "version": "2293bbea" }; window.__remixRouteModules = {"root":route0,"routes/":route1,"routes/":route2} ``` -------------------------------- ### Install .NET on Linux Instructions Source: https://dotnet.microsoft.com/download Instructions for installing .NET on Linux systems. This applies to both .NET 9.0 (Standard Term Support) and .NET 8.0 (Long Term Support). ```Bash https://learn.microsoft.com/dotnet/core/install/linux ``` -------------------------------- ### SpacetimeDB CLI Start Command Source: https://spacetimedb.com/docs/getting-started Starts the SpacetimeDB standalone server. The server listens on port 3000 by default, which can be customized using the --listen-addr flag. SSL is not supported in standalone mode. ```shell spacetime start ``` -------------------------------- ### Install SpacetimeDB on Windows Source: https://spacetimedb.com/install This PowerShell command downloads and executes the SpacetimeDB installer for Windows. It uses the 'Invoke-WebRequest' cmdlet to fetch the script and then executes it. ```powershell iwr https://windows.spacetimedb.com -useb | iex ``` -------------------------------- ### SpacetimeDB Client SDK: Project Setup (Bash) Source: https://context7_llms Demonstrates how to set up a C# client project for SpacetimeDB. Includes commands for creating a new .NET console application and adding the SpacetimeDB.ClientSDK NuGet package. ```bash dotnet new console -o my_csharp_client cd my_csharp_client dotnet add package SpacetimeDB.ClientSDK ``` -------------------------------- ### Install SpacetimeDB on macOS and Linux Source: https://spacetimedb.com/install This command downloads and executes the SpacetimeDB installation script. It is used for both macOS and Linux installations. After running, you can manage SpacetimeDB versions using the 'spacetime' command. ```bash curl -sSf https://install.spacetimedb.com | sh ``` -------------------------------- ### Rust Project Setup for SpacetimeDB Client Source: https://context7_llms Provides bash commands to set up a new Rust project for a SpacetimeDB client and add the necessary SDK dependency. This is the initial step for building native Rust clients. ```bash cargo new my_rust_client cd my_rust_client cargo add spacetimedb_sdk # Ensure version matches your SpacetimeDB installation ``` -------------------------------- ### Install SpacetimeDB CLI Source: https://context7_llms Commands to install the SpacetimeDB CLI tool on macOS, Linux, and Windows. The CLI is essential for managing SpacetimeDB modules, databases, and local instances. ```bash curl -sSf https://install.spacetimedb.com | sh ``` ```powershell iwr https://windows.spacetimedb.com -useb | iex ``` -------------------------------- ### Run SpacetimeDB Server with Docker Source: https://context7_llms Instructions for running a SpacetimeDB server instance using Docker. This command starts a server and maps the default port 3000. ```bash # This command starts a SpacetimeDB server instance in Docker docker run --rm --pull always -p 3000:3000 clockworklabs/spacetime start ``` -------------------------------- ### Build SpacetimeDB Module Source: https://context7_llms Builds a SpacetimeDB module from the specified project path. Requires the .NET SDK for C# modules. Ensure .NET 8 SDK is installed. ```bash spacetime build --project-path my_server_module ``` -------------------------------- ### Route Configuration and Analytics Setup Source: https://spacetimedb.com/install This snippet shows the JavaScript code for configuring application routes and initializing Google Analytics (gtag). It defines a mapping for marketing-related routes and sets up the gtag function to send events to a specific measurement ID. ```javascript const route1 = "_marketing"; const route2 = "routes/_marketing.install"; const routes = { "_marketing": route1, "routes/_marketing.install": route2 }; window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-PP0E4VHQKG'); ``` -------------------------------- ### Execute SpacetimeDB CLI Commands via Docker Source: https://context7_llms Examples of using the SpacetimeDB Docker image to execute CLI commands, such as building and publishing modules. This involves mounting the project directory into the container. ```bash # Example: Build a module located in the current directory (. # Mount current dir to /module inside container, set working dir to /module docker run --rm -v "$(pwd):/module" -w /module clockworklabs/spacetime build --project-path . # Example: Publish the module after building # Assumes a local server is running (or use --host for Maincloud/other) docker run --rm -v "$(pwd):/module" -w /module --network host clockworklabs/spacetime publish --project-path . my-database-name ``` -------------------------------- ### Install SpacetimeDB SDK for TypeScript Source: https://context7_llms Install the SpacetimeDB SDK package for building TypeScript/JavaScript client applications. This command uses either npm or yarn to add the SDK to your project dependencies. ```bash # Using npm npm install @clockworklabs/spacetimedb-sdk # Or using yarn yarn add @clockworklabs/spacetimedb-sdk ``` -------------------------------- ### Download .NET SDK for macOS (Intel) Source: https://dotnet.microsoft.com/download Provides direct download links for the .NET SDK for macOS, specifically for x64 (Intel) architecture. This is useful for developers using Intel-based Macs who need to install or update their .NET development environment. ```link /en-us/download/dotnet/thank-you/sdk-9.0.304-macos-x64-installer ``` ```link /en-us/download/dotnet/thank-you/sdk-8.0.413-macos-x64-installer ``` -------------------------------- ### SpacetimeDB Build Command Example Source: https://github.com/clockworklabs/SpacetimeDB/issues/2475 This demonstrates a command-line interaction related to building a SpacetimeDB module. The output indicates a successful build but a subsequent failure to locate the generated output file, highlighting the core issue. ```bash spacetime build ``` -------------------------------- ### SpacetimeDB Lifecycle Reducers (Rust) Source: https://context7_llms Demonstrates the implementation of SpacetimeDB's special lifecycle reducers: `init` for initial data setup, `client_connected` for handling new connections, and `client_disconnected` for managing disconnections. These reducers use `ReducerContext` to interact with the database and log events. ```rust use spacetimedb::{reducer, table, ReducerContext, Table, log}; #[table(name = settings)] #[derive(Clone, Debug)] pub struct Settings { #[primary_key] key: String, value: String, } // Example init reducer: Insert default settings if the table is empty #[reducer(init)] pub fn initialize_database(ctx: &ReducerContext) { log::info!( "Database Initializing! Module Identity: {}, Timestamp: {}", ctx.identity(), ctx.timestamp ); // Check if settings table is empty if ctx.db.settings().count() == 0 { log::info!("Settings table is empty, inserting default values..."); // Insert default settings ctx.db.settings().insert(Settings { key: "welcome_message".to_string(), value: "Hello from SpacetimeDB!".to_string(), }); ctx.db.settings().insert(Settings { key: "default_score".to_string(), value: "0".to_string(), }); } else { log::info!("Settings table already contains data."); } } // Example client_connected reducer #[reducer(client_connected)] pub fn handle_connect(ctx: &ReducerContext) { log::info!("Client connected: {}, Connection ID: {:?}", ctx.sender, ctx.connection_id); // ... setup initial state for ctx.sender ... } // Example client_disconnected reducer #[reducer(client_disconnected)] pub fn handle_disconnect(ctx: &ReducerContext) { log::info!("Client disconnected: {}, Connection ID: {:?}", ctx.sender, ctx.connection_id); // ... cleanup state for ctx.sender ... } ``` -------------------------------- ### SpacetimeDB Init Reducer Source: https://docs.rs/spacetimedb/latest/spacetimedb/attr.reducer.html The `init` reducer is executed when a SpacetimeDB module is first published or when the database is cleared. It's used for configuring static data tables or starting scheduled reducers. Errors during initialization prevent module publication. ```rust #[spacetimedb::reducer(init)] fn initialize_module(reducer_context: ReducerContext) { // Configuration logic here } ``` -------------------------------- ### Define and Schedule Reducers (C#) Source: https://context7_llms This C# code demonstrates how to define a table for scheduling reducer calls, create a static reducer that accepts schedule arguments, and schedule both one-off and periodic executions. It includes attribute usage for table definition and reducer invocation, along with example logic for scheduling within an initialization reducer. ```csharp using SpacetimeDB; using System; public static partial class Module { // 1. Define the table with scheduling information, linking to `SendMessage` reducer. // Specifies that the `ScheduledAt` field holds the schedule info. [Table(Name = "send_message_schedule", Scheduled = nameof(SendMessage), ScheduledAt = nameof(ScheduledAt))] public partial struct SendMessageSchedule { // Mandatory fields: [PrimaryKey] [AutoInc] public ulong Id; // Identifier for the scheduled call public ScheduleAt ScheduledAt; // Holds the schedule timing // Custom fields (arguments for the reducer): public string Message; } // 2. Define the scheduled reducer. // It takes the schedule table struct as its second argument. [Reducer] public static void SendMessage(ReducerContext ctx, SendMessageSchedule scheduleArgs) { // Security check is important! if (!ctx.Sender.Equals(ctx.Identity)) { throw new Exception("Reducer SendMessage may not be invoked by clients, only via scheduling."); } Log.Info($"Scheduled SendMessage: {scheduleArgs.Message}"); // ... perform action with scheduleArgs.Message ... } // 3. Example of scheduling reducers (e.g., in Init) [Reducer(ReducerKind.Init)] public static void Init(ReducerContext ctx) { // Avoid rescheduling if Init runs again if (ctx.Db.send_message_schedule.Count > 0) { return; } var tenSeconds = new TimeDuration { Microseconds = 10_000_000 }; var futureTimestamp = ctx.Timestamp + tenSeconds; // Schedule a one-off message ctx.Db.send_message_schedule.Insert(new SendMessageSchedule { Id = 0, // Let AutoInc assign ID // Use ScheduleAt.Time for one-off execution at a specific Timestamp ScheduledAt = new ScheduleAt.Time(futureTimestamp), Message = "I'm a bot sending a message one time!" }); Log.Info("Scheduled one-off message."); // Schedule a periodic message (every 10 seconds) ctx.Db.send_message_schedule.Insert(new SendMessageSchedule { Id = 0, // Let AutoInc assign ID // Use ScheduleAt.Interval for periodic execution with a TimeDuration ScheduledAt = new ScheduleAt.Interval(tenSeconds), Message = "I'm a bot sending a message every 10 seconds!" }); Log.Info("Scheduled periodic message."); } } ``` -------------------------------- ### Initialize SpacetimeDB Server Module Source: https://context7_llms Commands to initialize a new SpacetimeDB server module project using the CLI, supporting Rust and C# languages. ```bash # For Rust spacetime init --lang rust my_server_module # For C# spacetime init --lang csharp my_server_module ``` -------------------------------- ### Connect to SpacetimeDB with C# SDK Source: https://context7_llms Demonstrates how to initialize and build a database connection using the SpacetimeDB C# SDK. It includes setting the URI, module name, authentication token, and registering callbacks for connection events like successful connection, errors, and disconnections. ```C# using SpacetimeDB; using SpacetimeDB.Types; using System; public class ClientManager // Example class { const string HOST = "http://localhost:3000"; const string DB_NAME = "my_database"; // Or your specific DB name/identity private DbConnection connection; public void StartConnecting() { // Initialize token storage (e.g., in AppData) AuthToken.Init(".my_client_creds"); connection = DbConnection.Builder() .WithUri(HOST) .WithModuleName(DB_NAME) .WithToken(AuthToken.Token) // Load token if exists .OnConnect(HandleConnect) .OnConnectError(HandleConnectError) .OnDisconnect(HandleDisconnect) .Build(); // Need to call FrameTick regularly - see next section } private void HandleConnect(DbConnection conn, Identity identity, string authToken) { Console.WriteLine($"Connected. Identity: {identity}"); AuthToken.SaveToken(authToken); // Save token for future connections // Register other callbacks after connecting RegisterEventCallbacks(conn); // Subscribe to data SubscribeToTables(conn); } private void HandleConnectError(Exception e) { Console.WriteLine($"Connection Error: {e.Message}"); // Handle error, e.g., retry or exit } private void HandleDisconnect(DbConnection conn, Exception? e) { Console.WriteLine($"Disconnected. Reason: {(e == null ? "Requested" : e.Message)}"); // Handle disconnection } // Placeholder methods - implementations shown in later sections private void RegisterEventCallbacks(DbConnection conn) { /* ... */ } private void SubscribeToTables(DbConnection conn) { /* ... */ } } ``` -------------------------------- ### Download .NET SDK for Windows (x64) Source: https://dotnet.microsoft.com/download Download the .NET SDK for Windows 64-bit systems. This is the recommended version for .NET 9.0, which offers Standard Term Support. ```.NET /en-us/download/dotnet/thank-you/sdk-9.0.304-windows-x64-installer ``` -------------------------------- ### RLS Rules: Mutually Recursive Example (Invalid Rust) Source: https://context7_llms Illustrates an invalid RLS configuration in Rust where two rules are mutually recursive, causing a publication failure. This example highlights the dependency issues that can arise. ```rust use spacetimedb::{client_visibility_filter, Filter, table, Identity}; #[table(name = account)] struct Account { #[primary_key] id: u64, identity: Identity } #[table(name = player)] struct Player { #[primary_key] id: u64 } /// RLS: An account is visible only if a corresponding player exists. #[client_visibility_filter] const ACCOUNT_NEEDS_PLAYER: Filter = Filter::Sql( "SELECT a.* FROM account a JOIN player p ON a.id = p.id WHERE a.identity = :sender" ); /// RLS: A player is visible only if a corresponding account exists. #[client_visibility_filter] const PLAYER_NEEDS_ACCOUNT: Filter = Filter::Sql( // This rule requires access to 'account', which itself requires access to 'player' -> recursion! "SELECT p.* FROM account a JOIN player p ON a.id = p.id WHERE a.identity = :sender" ); ``` -------------------------------- ### Download .NET SDK for Windows (x86) Source: https://dotnet.microsoft.com/download Download the .NET SDK for Windows 32-bit systems. This is the recommended version for .NET 9.0, which offers Standard Term Support. ```.NET /en-us/download/dotnet/thank-you/sdk-9.0.304-windows-x86-installer ``` -------------------------------- ### Explore .NET Docker Images Source: https://dotnet.microsoft.com/download Directs users to the Microsoft Artifact Registry to find official Docker images for .NET and ASP.NET Core. This is essential for containerizing .NET applications for deployment in cloud or local environments. ```link https://mcr.microsoft.com/en-us/catalog?search=dotnet/&type=partial&cat=Application%20Frameworks ``` -------------------------------- ### Invoke Reducer in Rust Source: https://context7_llms Shows an example of how to invoke a reducer function, such as `send_message`, from a client-side handler, like a user input handler. This is typically a fire-and-forget style operation. ```rust // Example of calling a reducer (e.g., from user input handler) fn send_chat_message(conn: &DbConnection, message: String) { if !message.is_empty() { conn.reducers().send_message(message); // Fire-and-forget style } } ``` -------------------------------- ### Define a simple reducer Source: https://docs.rs/spacetimedb/latest/spacetimedb/attr.reducer.html Marks a function as a spacetimedb reducer. This example shows a basic reducer that logs a message. Reducers take a `ReducerContext` as their first argument. ```Rust use spacetimedb::{reducer, ReducerContext}; use log::info; #[reducer] pub fn hello_world(context: &ReducerContext) { info!("Hello, World!"); } ``` -------------------------------- ### Download .NET SDK for Windows (Arm64) Source: https://dotnet.microsoft.com/download Download the .NET SDK for Windows Arm64 systems. This is the recommended version for .NET 9.0, which offers Standard Term Support. ```.NET /en-us/download/dotnet/thank-you/sdk-9.0.304-windows-arm64-installer ``` -------------------------------- ### Client Processing Trigger Source: https://context7_llms Highlights the necessity for client SDKs to explicitly request processing time to receive and process messages from the server-to-client channel. Examples include `conn.FrameTick()` in C# and `conn.run_threaded()` in Rust. ```C# conn.FrameTick() ``` ```Rust conn.run_threaded() ``` -------------------------------- ### Delete Item by Primary Key Source: https://context7_llms Provides an example of deleting a specific `Item` record using its primary key (`item_key`). It shows how to access the primary key index handle and perform the deletion. ```rust use spacetimedb::{table, reducer, ReducerContext, Table, log}; #[table(name = points, index(name = idx_xy, btree(columns = [x, y])))] #[derive(Clone, Debug)] pub struct Point { #[primary_key] id: u64, x: i64, y: i64 } #[table(name = items, index(btree(columns = [name])))] #[derive(Clone, Debug)] // No SpacetimeType derive pub struct Item { #[primary_key] item_key: u32, name: String } #[reducer] fn index_operations(ctx: &ReducerContext) { // Example: Delete a single item by its primary key 'item_key' // Use the PK field name as the method to get the PK index handle, then call delete. // item_key is u32 (Copy), passing owned value is allowed. let item_id_to_delete = 101u32; ctx.db.items().item_key().delete(item_id_to_delete); } ``` -------------------------------- ### Define a reducer with arguments Source: https://docs.rs/spacetimedb/latest/spacetimedb/attr.reducer.html Defines a reducer that accepts arguments. Arguments must implement `SpacetimeType`, `Serialize`, and `Deserialize`, which can be derived using `#[derive(SpacetimeType)]`. This example adds a person with a name and age. ```Rust use spacetimedb::{reducer, ReducerContext}; #[reducer] pub fn add_person(context: &ReducerContext, name: String, age: u16) { // add a "person" to the database. } ``` -------------------------------- ### Application Insights SDK Initialization Source: https://dotnet.microsoft.com/download This JavaScript snippet initializes the Application Insights SDK for telemetry tracking. It dynamically loads the SDK script, configures connection strings and endpoints, and handles potential loading failures by sending telemetry events. ```JavaScript !function(T,l,y){var S=T.location,k="script",D="connectionString",C="ingestionendpoint",I="disableExceptionTracking",E="ai.device.",b="toLowerCase",w="crossOrigin",N="POST",e="appInsightsSDK",t=y.name||"appInsights";(y.name||T[e])&&(T[e]=t);var n=T[t]||function(d){var g=!1,f=!1,m={initialize:!0,queue:[],sv:"5",version:2,config:d};function v(e,t){var n={},a="Browser";return n[E+"id"]=a[b](),n[E+"type"]=a,n["ai.operation.name"]=S&&S.pathname||"_unknown_",n["ai.internal.sdkVersion"]="javascript:snippet_"+(m.sv||m.version),{time:function(){var e=new Date;function t(e){var t=""+e;return 1===t.length&&(t="0"+t),t}return e.getUTCFullYear()+"-"+t(1+e.getUTCMonth())+"-"+t(e.getUTCDate())+"T"+t(e.getUTCHours())+ மாதிரிகள்(e.getUTCMinutes())+ மாதிரிகள்(e.getUTCSeconds())+"."+((e.getUTCMilliseconds()/1e3).toFixed(3)+"").slice(2,5)+"Z"}(),name:"Microsoft.ApplicationInsights."+e.replace(/-/g,"")+"."+t,sampleRate:100,tags:n,data:{baseData:{ver:2}}}}var h=d.url||y.src;if(h){function a(e){var t,n,a,i,r,o,s,c,u,p,l;g=!0,m.queue=[],f||(f=!1,t=h,s=function(){var e={},t=d.connectionString;if(t)for(var n=t.split(";"),a=0;a {}", old.name.as_deref().unwrap_or("??"), new.name.as_deref().unwrap_or("??") ); } // ... handle other changes like online status ... } fn handle_message_insert(ctx: &EventContext, message: &Message) { if let Event::Reducer(_) = ctx.event { // Find sender name from cache let sender_name = ctx.db().player().identity().find(&message.sender) .map_or("Unknown".to_string(), |p| p.name.clone().unwrap_or("??".to_string())); println!("{}: {}", sender_name, message.text); } } ``` -------------------------------- ### Build SpacetimeDB Module Source: https://context7_llms Command to compile your SpacetimeDB module code into WebAssembly using the CLI. This command should be run from the directory containing your module folder. ```bash # Run from the directory containing your module folder ``` -------------------------------- ### Initialize SpacetimeDB C# Module Source: https://github.com/clockworklabs/SpacetimeDB/issues/2475 This bash command initializes a new SpacetimeDB module with C# as the programming language in the current directory. ```bash spacetime init --lang csharp . ``` -------------------------------- ### Define Row-Level Security Filter in Rust Source: https://context7_llms Illustrates how to define a Row-Level Security (RLS) filter in Rust for a public table. This example restricts access to only allow clients to see their own account records using a SQL query. ```rust use spacetimedb::{client_visibility_filter, Filter, table, Identity}; // Define a public table for RLS #[table(name = account, public)] // Now a public table struct Account { #[primary_key] identity: Identity, email: String, balance: u32, } /// RLS Rule: Allow a client to see *only* their own account record. #[client_visibility_filter] const ACCOUNT_VISIBILITY: Filter = Filter::Sql( // This query is evaluated per client request. // :sender is automatically bound to the requesting client's identity. // Only rows matching this filter are returned to the client from the public 'account' table, // overriding its default full visibility for matching clients. "SELECT * FROM account WHERE identity = :sender" ); ``` -------------------------------- ### Download Visual Studio Community Edition Source: https://dotnet.microsoft.com/download Provides a link to download the Visual Studio Community Edition, a free, full-featured Integrated Development Environment (IDE) for Windows. It's used for building all types of .NET applications, including web, mobile, desktop, and cloud services. ```link https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=Community&rel=17 ``` -------------------------------- ### Filter Points by Range using Reference on First Column Source: https://context7_llms Demonstrates filtering `Point` records using a range on the first column (`x`) of a multi-column index (`idx_xy`). This example shows the valid usage of references for range filtering. ```rust use spacetimedb::{table, reducer, ReducerContext, Table, log}; #[table(name = points, index(name = idx_xy, btree(columns = [x, y])))] #[derive(Clone, Debug)] pub struct Point { #[primary_key] id: u64, x: i64, y: i64 } #[table(name = items, index(btree(columns = [name])))] #[derive(Clone, Debug)] // No SpacetimeType derive pub struct Item { #[primary_key] item_key: u32, name: String } #[reducer] fn index_operations(ctx: &ReducerContext) { // Using references for a range filter on the first column - OK let min_x = 100i64; let max_x = 200i64; for point in ctx.db.points().idx_xy().filter(&min_x..=&max_x) { // ... } } ``` -------------------------------- ### Rust: Define Structs and Enums with SpacetimeType Source: https://context7_llms Demonstrates defining custom Rust structs and enums that derive `SpacetimeType` for use with SpacetimeDB. Includes examples of basic structs, enums with associated data, and enums with cross-language naming attributes. ```Rust use spacetimedb::{SpacetimeType, Identity, Timestamp}; // Example Struct #[derive(SpacetimeType, Clone, Debug, PartialEq)] pub struct Position { pub x: i32, pub y: i32, } // Example Enum #[derive(SpacetimeType, Clone, Debug, PartialEq)] pub enum PlayerStatus { Idle, Walking(Position), Fighting(Identity), // Store the identity of the opponent } // Example Enum with Cross-Language Naming Control // This enum will appear as `Game.ItemType` in C# bindings. #[derive(SpacetimeType, Clone, Debug, PartialEq)] #[sats(name = "Game.ItemType")] pub enum ItemType { Weapon, Armor, // This specific variant will be `ConsumableItem` in C# bindings. #[sats(name = "ConsumableItem")] Potion, } // Example Type Alias pub type PlayerScore = u32; // Advanced: For types with lifetimes or custom binary representations, // you can derive `spacetimedb::Deserialize` and use the `bsatn` crate // (provided by spacetimedb::spacetimedb_lib) for manual deserialization if needed. ``` -------------------------------- ### SpacetimeDB CLI Login Command Source: https://spacetimedb.com/docs/getting-started Logs the user into SpacetimeDB using GitHub authentication. This is required for publishing modules and other authenticated actions. If not run beforehand, commands requiring login will prompt for it. ```shell spacetime login ``` -------------------------------- ### SpacetimeDB RLS: Client and Admin Account Access Source: https://context7_llms Provides two RLS filter examples for the 'account' table in SpacetimeDB. 'ACCOUNT_FILTER' allows clients to see only their own account, while 'ACCOUNT_FILTER_FOR_ADMINS' allows administrators to view all accounts by joining with an 'admin' table. ```cs using SpacetimeDB; #pragma warning disable STDB_UNSTABLE public partial class Module { /// /// A client can only see their account. /// [SpacetimeDB.ClientVisibilityFilter] public static readonly Filter ACCOUNT_FILTER = new Filter.Sql( "SELECT * FROM account WHERE identity = :sender" ); /// /// An admin can see all accounts. /// [SpacetimeDB.ClientVisibilityFilter] public static readonly Filter ACCOUNT_FILTER_FOR_ADMINS = new Filter.Sql( "SELECT account.* FROM account JOIN admin WHERE admin.identity = :sender" ); } ``` -------------------------------- ### Download .NET SDK for macOS (Apple Silicon) Source: https://dotnet.microsoft.com/download Offers download links for the .NET SDK tailored for macOS on Apple Silicon (Arm64) architecture. This ensures optimal performance and compatibility for developers using M1, M2, or newer Macs. ```link /en-us/download/dotnet/thank-you/sdk-9.0.304-macos-arm64-installer ``` ```link /en-us/download/dotnet/thank-you/sdk-8.0.413-macos-arm64-installer ``` -------------------------------- ### Stream Controller Data Enqueue Source: https://spacetimedb.com/install This JavaScript code demonstrates the use of a stream controller to enqueue data, likely for real-time updates or logging within the application. It serializes a complex data structure, including route information and application state, before sending it. ```javascript window.__remixContext.streamController.enqueue("[{ \"_1\": 2, \"_12\": -5, \"_13\": -5 }, { \"loaderData\", { \"_3\": 4, \"_10\": -5, \"_11\": -5 } }, { \"root\", { \"_5\": 6, \"_7\": 8, \"_9\": -7 } }, { \"stargazersCount\", 17357 }, { \"isAnnouncementVisible\", true }, { \"sessionUserInfo\", \"routes/_marketing\" }, { \"routes/_marketing.install\" }, { \"actionData\" }, { \"errors\" }]"); window.__remixContext.streamController.close(); ``` -------------------------------- ### Subscribe to SpacetimeDB Tables Source: https://context7_llms Demonstrates subscribing to specific tables ('Player', 'Message') in SpacetimeDB using C#. It includes setting up callbacks for successful subscription application and error handling. ```csharp using SpacetimeDB.Types; // For SubscriptionEventContext, ErrorContext using System.Linq; // In ClientManager or similar class... private void SubscribeToTables(DbConnection conn) { Console.WriteLine("Subscribing to tables..."); conn.SubscriptionBuilder() .OnApplied(on_subscription_applied) .OnError((errCtx, err) => { Console.WriteLine($"Subscription failed: {err.Message}"); }) // Example: Subscribe to all rows from 'player' and 'message' tables .Subscribe(new string[] { "SELECT * FROM Player", "SELECT * FROM Message" }); } private void OnSubscriptionApplied(SubscriptionEventContext ctx) { Console.WriteLine("Subscription applied! Initial data received."); // Example: Print initial messages sorted by time var messages = ctx.Db.Message.Iter().ToList(); messages.Sort((a, b) => a.Sent.CompareTo(b.Sent)); foreach (var msg in messages) { // PrintMessage(ctx.Db, msg); // Assuming a PrintMessage helper } } ```