diff --git a/crates/bindings-typescript/package.json b/crates/bindings-typescript/package.json index 7b83e8e1c4f..c50b875fa13 100644 --- a/crates/bindings-typescript/package.json +++ b/crates/bindings-typescript/package.json @@ -71,6 +71,12 @@ "import": "./dist/server/index.mjs", "require": "./dist/server/index.cjs", "default": "./dist/server/index.mjs" + }, + "./svelte": { + "types": "./dist/svelte/index.d.ts", + "import": "./dist/svelte/index.mjs", + "require": "./dist/svelte/index.cjs", + "default": "./dist/svelte/index.mjs" } }, "size-limit": [ @@ -161,18 +167,23 @@ }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0-0 || ^19.0.0", + "svelte": "^4.0.0 || ^5.0.0", "undici": "^6.19.2" }, "peerDependenciesMeta": { "react": { "optional": true }, + "svelte": { + "optional": true + }, "undici": { "optional": true } }, "devDependencies": { "@eslint/js": "^9.17.0", + "svelte": "^5.0.0", "@size-limit/file": "^11.2.0", "@types/fast-text-encoding": "^1.0.3", "@types/react": "^19.1.13", diff --git a/crates/bindings-typescript/src/svelte/SpacetimeDBProvider.ts b/crates/bindings-typescript/src/svelte/SpacetimeDBProvider.ts new file mode 100644 index 00000000000..d4e4bd1a82a --- /dev/null +++ b/crates/bindings-typescript/src/svelte/SpacetimeDBProvider.ts @@ -0,0 +1,101 @@ +import { setContext, onDestroy } from 'svelte'; +import { writable, type Writable } from 'svelte/store'; +import { + DbConnectionBuilder, + type DbConnectionImpl, + type ErrorContextInterface, + type RemoteModuleOf, +} from '../sdk/db_connection_impl'; +import { ConnectionId } from '../lib/connection_id'; +import { + SPACETIMEDB_CONTEXT_KEY, + type ConnectionState, +} from './connection_state'; + +let connRef: DbConnectionImpl | null = null; +let cleanupTimeoutId: ReturnType | null = null; + +export function createSpacetimeDBProvider< + DbConnection extends DbConnectionImpl, +>( + connectionBuilder: DbConnectionBuilder +): Writable { + const getConnection = () => connRef as DbConnection | null; + + const store = writable({ + isActive: false, + identity: undefined, + token: undefined, + connectionId: ConnectionId.random(), + connectionError: undefined, + getConnection: getConnection as ConnectionState['getConnection'], + }); + + if (cleanupTimeoutId) { + clearTimeout(cleanupTimeoutId); + cleanupTimeoutId = null; + } + + if (!connRef) { + connRef = connectionBuilder.build(); + } + + const onConnect = (conn: DbConnection) => { + store.update(s => ({ + ...s, + isActive: conn.isActive, + identity: conn.identity, + token: conn.token, + connectionId: conn.connectionId, + })); + }; + + const onDisconnect = ( + ctx: ErrorContextInterface> + ) => { + store.update(s => ({ + ...s, + isActive: ctx.isActive, + })); + }; + + const onConnectError = ( + ctx: ErrorContextInterface>, + err: Error + ) => { + store.update(s => ({ + ...s, + isActive: ctx.isActive, + connectionError: err, + })); + }; + + connectionBuilder.onConnect(onConnect); + connectionBuilder.onDisconnect(onDisconnect); + connectionBuilder.onConnectError(onConnectError); + + const conn = connRef; + store.update(s => ({ + ...s, + isActive: conn.isActive, + identity: conn.identity, + token: conn.token, + connectionId: conn.connectionId, + })); + + setContext(SPACETIMEDB_CONTEXT_KEY, store); + + onDestroy(() => { + connRef?.removeOnConnect(onConnect as any); + connRef?.removeOnDisconnect(onDisconnect as any); + connRef?.removeOnConnectError(onConnectError as any); + + cleanupTimeoutId = setTimeout(() => { + connRef?.disconnect(); + connRef = null; + cleanupTimeoutId = null; + }, 0); + }); + + return store; +} diff --git a/crates/bindings-typescript/src/svelte/connection_state.ts b/crates/bindings-typescript/src/svelte/connection_state.ts new file mode 100644 index 00000000000..bfd2098d929 --- /dev/null +++ b/crates/bindings-typescript/src/svelte/connection_state.ts @@ -0,0 +1,16 @@ +import type { ConnectionId } from '../lib/connection_id'; +import type { Identity } from '../lib/identity'; +import type { DbConnectionImpl } from '../sdk/db_connection_impl'; + +export type ConnectionState = { + isActive: boolean; + identity?: Identity; + token?: string; + connectionId: ConnectionId; + connectionError?: Error; + getConnection< + DbConnection extends DbConnectionImpl, + >(): DbConnection | null; +}; + +export const SPACETIMEDB_CONTEXT_KEY = Symbol('spacetimedb'); diff --git a/crates/bindings-typescript/src/svelte/index.ts b/crates/bindings-typescript/src/svelte/index.ts new file mode 100644 index 00000000000..6bcf01a6a28 --- /dev/null +++ b/crates/bindings-typescript/src/svelte/index.ts @@ -0,0 +1,4 @@ +export * from './SpacetimeDBProvider.ts'; +export { useSpacetimeDB } from './useSpacetimeDB.ts'; +export { useTable, where, eq } from './useTable.ts'; +export { useReducer } from './useReducer.ts'; diff --git a/crates/bindings-typescript/src/svelte/useReducer.ts b/crates/bindings-typescript/src/svelte/useReducer.ts new file mode 100644 index 00000000000..a25c576e123 --- /dev/null +++ b/crates/bindings-typescript/src/svelte/useReducer.ts @@ -0,0 +1,56 @@ +import { onDestroy } from 'svelte'; +import { get } from 'svelte/store'; +import type { InferTypeOfRow } from '../lib/type_builders'; +import type { UntypedReducerDef } from '../sdk/reducers'; +import { useSpacetimeDB } from './useSpacetimeDB'; +import type { Prettify } from '../lib/type_util'; + +type IsEmptyObject = [keyof T] extends [never] ? true : false; +type MaybeParams = IsEmptyObject extends true ? [] : [params: T]; + +type ParamsType = MaybeParams< + Prettify> +>; + +export function useReducer( + reducerDef: ReducerDef +): (...params: ParamsType) => void { + const connectionStore = useSpacetimeDB(); + const reducerName = reducerDef.accessorName; + + // Holds calls made before the connection exists + const queueRef: ParamsType[] = []; + + // Flush when we finally have a connection + const unsubscribe = connectionStore.subscribe(state => { + const conn = state.getConnection(); + if (!conn) return; + + const fn = (conn.reducers as any)[reducerName] as ( + ...p: ParamsType + ) => void; + if (queueRef.length) { + const pending = queueRef.splice(0); + for (const params of pending) { + fn(...params); + } + } + }); + + onDestroy(() => { + unsubscribe(); + }); + + return (...params: ParamsType) => { + const state = get(connectionStore); + const conn = state.getConnection(); + if (!conn) { + queueRef.push(params); + return; + } + const fn = (conn.reducers as any)[reducerName] as ( + ...p: ParamsType + ) => void; + return fn(...params); + }; +} diff --git a/crates/bindings-typescript/src/svelte/useSpacetimeDB.ts b/crates/bindings-typescript/src/svelte/useSpacetimeDB.ts new file mode 100644 index 00000000000..899c23c4f5f --- /dev/null +++ b/crates/bindings-typescript/src/svelte/useSpacetimeDB.ts @@ -0,0 +1,22 @@ +import { getContext } from 'svelte'; +import type { Writable } from 'svelte/store'; +import { + SPACETIMEDB_CONTEXT_KEY, + type ConnectionState, +} from './connection_state'; + +// Throws an error if used outside of a SpacetimeDBProvider +export function useSpacetimeDB(): Writable { + const context = getContext | undefined>( + SPACETIMEDB_CONTEXT_KEY + ); + + if (!context) { + throw new Error( + 'useSpacetimeDB must be used within a component that called createSpacetimeDBProvider. ' + + 'Did you forget to call `createSpacetimeDBProvider` in a parent component?' + ); + } + + return context; +} diff --git a/crates/bindings-typescript/src/svelte/useTable.ts b/crates/bindings-typescript/src/svelte/useTable.ts new file mode 100644 index 00000000000..fb21cc005ba --- /dev/null +++ b/crates/bindings-typescript/src/svelte/useTable.ts @@ -0,0 +1,375 @@ +import { onDestroy } from 'svelte'; +import { writable, get, type Readable } from 'svelte/store'; +import { useSpacetimeDB } from './useSpacetimeDB'; +import type { EventContextInterface } from '../sdk/db_connection_impl'; +import type { UntypedRemoteModule } from '../sdk/spacetime_module'; +import type { RowType, UntypedTableDef } from '../lib/table'; +import type { Prettify } from '../lib/type_util'; + +export interface UseTableCallbacks { + onInsert?: (row: RowType) => void; + onDelete?: (row: RowType) => void; + onUpdate?: (oldRow: RowType, newRow: RowType) => void; +} + +export type Value = string | number | boolean; + +export type Expr = + | { type: 'eq'; key: Column; value: Value } + | { type: 'and'; children: Expr[] } + | { type: 'or'; children: Expr[] }; + +export const eq = ( + key: Column, + value: Value +): Expr => ({ type: 'eq', key, value }); + +export const and = ( + ...children: Expr[] +): Expr => { + const flat: Expr[] = []; + for (const c of children) { + if (!c) continue; + if (c.type === 'and') flat.push(...c.children); + else flat.push(c); + } + const pruned = flat.filter(Boolean); + if (pruned.length === 0) return { type: 'and', children: [] }; + if (pruned.length === 1) return pruned[0]; + return { type: 'and', children: pruned }; +}; + +export const or = ( + ...children: Expr[] +): Expr => { + const flat: Expr[] = []; + for (const c of children) { + if (!c) continue; + if (c.type === 'or') flat.push(...c.children); + else flat.push(c); + } + const pruned = flat.filter(Boolean); + if (pruned.length === 0) return { type: 'or', children: [] }; + if (pruned.length === 1) return pruned[0]; + return { type: 'or', children: pruned }; +}; + +export const isEq = ( + e: Expr +): e is Extract, { type: 'eq' }> => e.type === 'eq'; +export const isAnd = ( + e: Expr +): e is Extract, { type: 'and' }> => e.type === 'and'; +export const isOr = ( + e: Expr +): e is Extract, { type: 'or' }> => e.type === 'or'; + +export function evaluate( + expr: Expr, + row: Record +): boolean { + switch (expr.type) { + case 'eq': { + const v = row[expr.key]; + if ( + typeof v === 'string' || + typeof v === 'number' || + typeof v === 'boolean' + ) { + return v === expr.value; + } + return false; + } + case 'and': + return ( + expr.children.length === 0 || expr.children.every(c => evaluate(c, row)) + ); + case 'or': + return ( + expr.children.length !== 0 && expr.children.some(c => evaluate(c, row)) + ); + } +} + +function formatValue(v: Value): string { + switch (typeof v) { + case 'string': + return `'${v.replace(/'/g, "''")}'`; + case 'number': + return Number.isFinite(v) ? String(v) : `'${String(v)}'`; + case 'boolean': + return v ? 'TRUE' : 'FALSE'; + } +} + +function escapeIdent(id: string): string { + if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(id)) return id; + return `"${id.replace(/"/g, '""')}"`; +} + +function parenthesize(s: string): string { + if (!s.includes(' AND ') && !s.includes(' OR ')) return s; + return `(${s})`; +} + +/** + * Extracts the column names from a RowType whose values are of type Value. + * Note that this will exclude columns that are of type object, array, etc. + */ +type ColumnsFromRow = { + [K in keyof R]-?: R[K] extends Value | undefined ? K : never; +}[keyof R] & + string; + +export function toString( + tableDef: TableDef, + expr: Expr>> +): string { + switch (expr.type) { + case 'eq': { + const key = tableDef.columns[expr.key].columnMetadata.name ?? expr.key; + return `${escapeIdent(key)} = ${formatValue(expr.value)}`; + } + case 'and': + return parenthesize( + expr.children.map(expr => toString(tableDef, expr)).join(' AND ') + ); + case 'or': + return parenthesize( + expr.children.map(expr => toString(tableDef, expr)).join(' OR ') + ); + } +} + +/** + * This is just the identity function to make things look like SQL. + * @param expr + * @returns + */ +export function where(expr: Expr): Expr { + return expr; +} + +type MembershipChange = 'enter' | 'leave' | 'stayIn' | 'stayOut'; + +function classifyMembership< + Col extends string, + R extends Record, +>(where: Expr | undefined, oldRow: R, newRow: R): MembershipChange { + // No filter: everything is in, so updates are always "stayIn". + if (!where) { + return 'stayIn'; + } + + const oldIn = evaluate(where, oldRow); + const newIn = evaluate(where, newRow); + + if (oldIn && !newIn) { + return 'leave'; + } + if (!oldIn && newIn) { + return 'enter'; + } + if (oldIn && newIn) { + return 'stayIn'; + } + return 'stayOut'; +} + +export function useTable( + tableDef: TableDef, + where: Expr>>, + callbacks?: UseTableCallbacks>> +): [Readable>[]>, Readable]; + +export function useTable( + tableDef: TableDef, + callbacks?: UseTableCallbacks>> +): [Readable>[]>, Readable]; + +export function useTable( + tableDef: TableDef, + whereClauseOrCallbacks?: + | Expr>> + | UseTableCallbacks>, + callbacks?: UseTableCallbacks> +): [Readable>[]>, Readable] { + type Row = RowType; + const tableName = tableDef.name; + const accessorName = tableDef.accessorName; + + let whereClause: Expr> | undefined; + if ( + whereClauseOrCallbacks && + typeof whereClauseOrCallbacks === 'object' && + 'type' in whereClauseOrCallbacks + ) { + whereClause = whereClauseOrCallbacks as Expr>; + } else { + callbacks = whereClauseOrCallbacks as UseTableCallbacks | undefined; + } + + let connectionStore; + try { + connectionStore = useSpacetimeDB(); + } catch { + throw new Error( + 'Could not find SpacetimeDB client! Did you forget to call ' + + '`createSpacetimeDBProvider`? `useTable` must be used in a Svelte component tree ' + + 'under a component that called `createSpacetimeDBProvider`.' + ); + } + + const rows = writable[]>([]); + const isReady = writable(false); + + const query = + `SELECT * FROM ${tableName}` + + (whereClause ? ` WHERE ${toString(tableDef, whereClause)}` : ''); + + let latestTransactionEvent: any = null; + let unsubscribeFromTable: (() => void) | null = null; + let subscriptionHandle: { unsubscribe: () => void } | null = null; + + const computeFilteredRows = (): readonly Prettify[] => { + const state = get(connectionStore); + const connection = state.getConnection(); + if (!connection) return []; + + const table = connection.db[accessorName]; + if (!table) return []; + + const allRows = Array.from(table.iter()) as Row[]; + if (whereClause) { + return allRows.filter(row => + evaluate(whereClause, row as Record) + ) as Prettify[]; + } + return allRows as Prettify[]; + }; + + const setupTableListeners = () => { + const state = get(connectionStore); + const connection = state.getConnection(); + if (!connection) return; + + const table = connection.db[accessorName]; + if (!table) return; + + const onInsert = ( + eventCtx: EventContextInterface, + row: any + ) => { + if (whereClause && !evaluate(whereClause, row)) return; + callbacks?.onInsert?.(row); + + if ( + eventCtx.event !== latestTransactionEvent || + !latestTransactionEvent + ) { + latestTransactionEvent = eventCtx.event; + rows.set(computeFilteredRows()); + } + }; + + const onDelete = ( + eventCtx: EventContextInterface, + row: any + ) => { + if (whereClause && !evaluate(whereClause, row)) return; + callbacks?.onDelete?.(row); + + if ( + eventCtx.event !== latestTransactionEvent || + !latestTransactionEvent + ) { + latestTransactionEvent = eventCtx.event; + rows.set(computeFilteredRows()); + } + }; + + const onUpdate = ( + eventCtx: EventContextInterface, + oldRow: any, + newRow: any + ) => { + const change = classifyMembership(whereClause, oldRow, newRow); + + switch (change) { + case 'leave': + callbacks?.onDelete?.(oldRow); + break; + case 'enter': + callbacks?.onInsert?.(newRow); + break; + case 'stayIn': + callbacks?.onUpdate?.(oldRow, newRow); + break; + case 'stayOut': + return; + } + + if ( + eventCtx.event !== latestTransactionEvent || + !latestTransactionEvent + ) { + latestTransactionEvent = eventCtx.event; + rows.set(computeFilteredRows()); + } + }; + + table.onInsert(onInsert); + table.onDelete(onDelete); + table.onUpdate?.(onUpdate); + + return () => { + table.removeOnInsert(onInsert); + table.removeOnDelete(onDelete); + table.removeOnUpdate?.(onUpdate); + }; + }; + + const setupSubscription = () => { + const state = get(connectionStore); + const connection = state.getConnection(); + if (!connection) return; + + subscriptionHandle = connection + .subscriptionBuilder() + .onApplied(() => { + isReady.set(true); + rows.set(computeFilteredRows()); + }) + .subscribe(query); + }; + + const unsubscribeConnection = connectionStore.subscribe(state => { + // clean up existing listeners and subscriptions first + if (unsubscribeFromTable) { + unsubscribeFromTable(); + unsubscribeFromTable = null; + } + if (subscriptionHandle) { + subscriptionHandle.unsubscribe(); + subscriptionHandle = null; + } + + if (state.isActive) { + unsubscribeFromTable = setupTableListeners() || null; + setupSubscription(); + rows.set(computeFilteredRows()); + } else { + isReady.set(false); + rows.set([]); + } + }); + + onDestroy(() => { + unsubscribeConnection(); + unsubscribeFromTable?.(); + subscriptionHandle?.unsubscribe(); + latestTransactionEvent = null; + }); + + return [{ subscribe: rows.subscribe }, { subscribe: isReady.subscribe }]; +} diff --git a/crates/bindings-typescript/tsup.config.ts b/crates/bindings-typescript/tsup.config.ts index f88f703b9ec..b629b02e9bc 100644 --- a/crates/bindings-typescript/tsup.config.ts +++ b/crates/bindings-typescript/tsup.config.ts @@ -76,6 +76,38 @@ export default defineConfig([ esbuildOptions: commonEsbuildTweaks(), }, + // Svelte subpath (SSR-friendly): dist/svelte/index.{mjs,cjs} + { + entry: { index: 'src/svelte/index.ts' }, + format: ['esm', 'cjs'], + target: 'es2022', + outDir: 'dist/svelte', + dts: false, + sourcemap: true, + clean: true, + platform: 'neutral', + treeshake: 'smallest', + external: ['svelte', 'svelte/store'], + outExtension, + esbuildOptions: commonEsbuildTweaks(), + }, + + // Svelte subpath (browser ESM): dist/browser/svelte/index.mjs + { + entry: { index: 'src/svelte/index.ts' }, + format: ['esm'], + target: 'es2022', + outDir: 'dist/browser/svelte', + dts: false, + sourcemap: true, + clean: true, + platform: 'browser', + treeshake: 'smallest', + external: ['svelte', 'svelte/store'], + outExtension, + esbuildOptions: commonEsbuildTweaks(), + }, + // SDK subpath (SSR-friendly): dist/sdk/index.{mjs,cjs} { entry: { index: 'src/sdk/index.ts' }, diff --git a/docs/docs/00100-intro/00200-quickstarts/00160-svelte.md b/docs/docs/00100-intro/00200-quickstarts/00160-svelte.md new file mode 100644 index 00000000000..bc56aa552ef --- /dev/null +++ b/docs/docs/00100-intro/00200-quickstarts/00160-svelte.md @@ -0,0 +1,127 @@ +--- +title: Svelte Quickstart +sidebar_label: Svelte +slug: /quickstarts/svelte +hide_table_of_contents: true +--- + +import { InstallCardLink } from "@site/src/components/InstallCardLink"; +import { StepByStep, Step, StepText, StepCode } from "@site/src/components/Steps"; + + +Get a SpacetimeDB Svelte app running in under 5 minutes. + +## Prerequisites + +- [Node.js](https://nodejs.org/) 18+ installed +- [SpacetimeDB CLI](https://spacetimedb.com/install) installed + + + +--- + + + + + Run the `spacetime dev` command to create a new project with a SpacetimeDB module and Svelte client. + + This will start the local SpacetimeDB server, publish your module, generate TypeScript bindings, and start the Svelte development server. + + +```bash +spacetime dev --template svelte-ts +``` + + + + + + Navigate to [http://localhost:5173](http://localhost:5173) to see your app running. + + The template includes a basic Svelte app connected to SpacetimeDB. + + + + + + Your project contains both server and client code. + + Edit `spacetimedb/src/index.ts` to add tables and reducers. Edit `src/App.svelte` to build your UI. + + +``` +my-spacetime-app/ +├── spacetimedb/ # Your SpacetimeDB module +│ └── src/ +│ └── index.ts # Server-side logic +├── src/ # Svelte frontend +│ ├── App.svelte +│ └── module_bindings/ # Auto-generated types +└── package.json +``` + + + + + + Open `spacetimedb/src/index.ts` to see the module code. The template includes a `person` table and two reducers: `add` to insert a person, and `say_hello` to greet everyone. + + Tables store your data. Reducers are functions that modify data — they're the only way to write to the database. + + +```typescript +import { schema, table, t } from 'spacetimedb/server'; + +export const spacetimedb = schema( + table( + { name: 'person', public: true }, + { + name: t.string(), + } + ) +); + +spacetimedb.reducer('add', { name: t.string() }, (ctx, { name }) => { + ctx.db.person.insert({ name }); +}); + +spacetimedb.reducer('say_hello', (ctx) => { + for (const person of ctx.db.person.iter()) { + console.info(`Hello, ${person.name}!`); + } + console.info('Hello, World!'); +}); +``` + + + + + + Use the SpacetimeDB CLI to call reducers and query your data directly. + + +```bash +# Call the add reducer to insert a person +spacetime call add Alice + +# Query the person table +spacetime sql "SELECT * FROM person" + name +--------- + "Alice" + +# Call say_hello to greet everyone +spacetime call say_hello + +# View the module logs +spacetime logs +2025-01-13T12:00:00.000000Z INFO: Hello, Alice! +2025-01-13T12:00:00.000000Z INFO: Hello, World! +``` + + + + +## Next steps + +- Read the [TypeScript SDK Reference](/sdks/typescript) for detailed API docs diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e9de64e1c10..15aa6c9d6e9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -108,6 +108,9 @@ importers: size-limit: specifier: ^11.2.0 version: 11.2.0 + svelte: + specifier: ^5.0.0 + version: 5.46.4 ts-node: specifier: ^10.9.2 version: 10.9.2(@types/node@24.3.0)(typescript@5.9.3) @@ -369,6 +372,28 @@ importers: specifier: workspace:^ version: link:../../../crates/bindings-typescript + templates/svelte-ts: + dependencies: + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@sveltejs/vite-plugin-svelte': + specifier: ^5.1.1 + version: 5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4)) + svelte: + specifier: ^5.0.0 + version: 5.46.4 + svelte-check: + specifier: ^4.0.0 + version: 4.3.5(picomatch@4.0.3)(svelte@5.46.4)(typescript@5.6.3) + typescript: + specifier: ~5.6.2 + version: 5.6.3 + vite: + specifier: ^6.4.1 + version: 6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4) + packages: '@adobe/css-tools@4.4.4': @@ -2012,6 +2037,9 @@ packages: '@jridgewell/gen-mapping@0.3.13': resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + '@jridgewell/resolve-uri@3.1.2': resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} engines: {node: '>=6.0.0'} @@ -3061,6 +3089,26 @@ packages: '@standard-schema/spec@1.0.0': resolution: {integrity: sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==} + '@sveltejs/acorn-typescript@1.0.8': + resolution: {integrity: sha512-esgN+54+q0NjB0Y/4BomT9samII7jGwNy/2a3wNZbT2A2RpmXsXwUt24LvLhx6jUq2gVk4cWEvcRO6MFQbOfNA==} + peerDependencies: + acorn: ^8.9.0 + + '@sveltejs/vite-plugin-svelte-inspector@4.0.1': + resolution: {integrity: sha512-J/Nmb2Q2y7mck2hyCX4ckVHcR5tu2J+MtBEQqpDrrgELZ2uvraQcK/ioCV61AqkdXFgriksOKIceDcQmqnGhVw==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22} + peerDependencies: + '@sveltejs/vite-plugin-svelte': ^5.0.0 + svelte: ^5.0.0 + vite: ^6.0.0 + + '@sveltejs/vite-plugin-svelte@5.1.1': + resolution: {integrity: sha512-Y1Cs7hhTc+a5E9Va/xwKlAJoariQyHY+5zBgCZg4PFWNYQ1nMN9sjK1zhw1gK69DuqVP++sht/1GZg1aRwmAXQ==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22} + peerDependencies: + svelte: ^5.0.0 + vite: ^6.0.0 + '@svgr/babel-plugin-add-jsx-attribute@8.0.0': resolution: {integrity: sha512-b9MIk7yhdS1pMCZM8VeNfUlSKVRhsHZNMl5O9SfaX0l0t5wjdgu4IDzGB8bpnGBBOjGST3rRFVsaaEtI4W6f7g==} engines: {node: '>=14'} @@ -4164,6 +4212,10 @@ packages: peerDependencies: postcss: ^8.1.0 + axobject-query@4.1.0: + resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==} + engines: {node: '>= 0.4'} + babel-loader@9.2.1: resolution: {integrity: sha512-fqe8naHt46e0yIdkjUZYqddSXfej3AHajX+CSO5X7oy0EmPc6o5Xh+RClNoHjnieWz9AW4kZxW9yyFMhVB1QLA==} engines: {node: '>= 14.15.0'} @@ -4810,6 +4862,9 @@ packages: engines: {node: '>= 4.0.0'} hasBin: true + devalue@5.6.2: + resolution: {integrity: sha512-nPRkjWzzDQlsejL1WVifk5rvcFi/y1onBRxjaFMjZeR9mFpqu2gmAZ9xUB9/IEanEP/vBtGeGganC/GO1fmufg==} + devlop@1.1.0: resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==} @@ -5026,6 +5081,9 @@ packages: jiti: optional: true + esm-env@1.2.2: + resolution: {integrity: sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==} + espree@10.4.0: resolution: {integrity: sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} @@ -5039,6 +5097,9 @@ packages: resolution: {integrity: sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==} engines: {node: '>=0.10'} + esrap@2.2.1: + resolution: {integrity: sha512-GiYWG34AN/4CUyaWAgunGt0Rxvr1PTMlGC0vvEov/uOQYWne2bpN03Um+k8jT+q3op33mKouP2zeJ6OlM+qeUg==} + esrecurse@4.3.0: resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} engines: {node: '>=4.0'} @@ -5818,6 +5879,9 @@ packages: is-potential-custom-element-name@1.0.1: resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} + is-reference@3.0.3: + resolution: {integrity: sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==} + is-regexp@1.0.0: resolution: {integrity: sha512-7zjFAPO4/gwyQAAgRRmqeEeyIICSdmCqa3tsVHMdBzaXXRiqopZL4Cyghg/XulGWrtABTpbnYYzzIRffLkP4oA==} engines: {node: '>=0.10.0'} @@ -6031,6 +6095,9 @@ packages: resolution: {integrity: sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==} engines: {node: '>=8.9.0'} + locate-character@3.0.0: + resolution: {integrity: sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==} + locate-path@5.0.0: resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==} engines: {node: '>=8'} @@ -6113,6 +6180,9 @@ packages: magic-string@0.30.19: resolution: {integrity: sha512-2N21sPY9Ws53PZvsEpVtNuSW+ScYbQdp4b9qUaL+9QkHUrGFKo56Lg9Emg5s9V/qrtNBmiR01sYhUOwu3H+VOw==} + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + magicast@0.3.5: resolution: {integrity: sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==} @@ -8078,6 +8148,18 @@ packages: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} + svelte-check@4.3.5: + resolution: {integrity: sha512-e4VWZETyXaKGhpkxOXP+B/d0Fp/zKViZoJmneZWe/05Y2aqSKj3YN2nLfYPJBQ87WEiY4BQCQ9hWGu9mPT1a1Q==} + engines: {node: '>= 18.0.0'} + hasBin: true + peerDependencies: + svelte: ^4.0.0 || ^5.0.0-next.0 + typescript: '>=5.0.0' + + svelte@5.46.4: + resolution: {integrity: sha512-VJwdXrmv9L8L7ZasJeWcCjoIuMRVbhuxbss0fpVnR8yorMmjNDwcjIH08vS6wmSzzzgAG5CADQ1JuXPS2nwt9w==} + engines: {node: '>=18'} + svg-parser@2.0.4: resolution: {integrity: sha512-e4hG1hRwoOdRb37cIMSgzNsxyzKfayW6VOflrwvR+/bzrkyxY/31WkbgnQpgtrNp1SdpJvpUAGTa/ZoiPNDuRQ==} @@ -8586,6 +8668,46 @@ packages: engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} hasBin: true + vite@6.4.1: + resolution: {integrity: sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + peerDependencies: + '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0 + jiti: '>=1.21.0' + less: '*' + lightningcss: ^1.21.0 + sass: '*' + sass-embedded: '*' + stylus: '*' + sugarss: '*' + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + jiti: + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + vite@7.1.5: resolution: {integrity: sha512-4cKBO9wR75r0BeIWWWId9XK9Lj6La5X846Zw9dFfzMRw38IlTk2iCcUt6hsyiDRcPidc55ZParFYDXi0nXOeLQ==} engines: {node: ^20.19.0 || >=22.12.0} @@ -8626,6 +8748,14 @@ packages: yaml: optional: true + vitefu@1.1.1: + resolution: {integrity: sha512-B/Fegf3i8zh0yFbpzZ21amWzHmuNlLlmJT6n7bu5e+pCHUKQIfXSYokrqOBGEMMe9UG2sostKQF9mml/vYaWJQ==} + peerDependencies: + vite: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0-beta.0 + peerDependenciesMeta: + vite: + optional: true + vitest@3.2.4: resolution: {integrity: sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==} engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} @@ -8867,6 +8997,9 @@ packages: zen-observable@0.8.15: resolution: {integrity: sha512-PQ2PC7R9rslx84ndNBZB/Dkv8V8fZEpk83RLgXtYd0fwUgEjseMn1Dgajh2x6S8QbZAFa9p2qVCEuYZNgve0dQ==} + zimmerframe@1.1.4: + resolution: {integrity: sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ==} + zod@4.1.12: resolution: {integrity: sha512-JInaHOamG8pt5+Ey8kGmdcAcg3OL9reK8ltczgHTAwNhMys/6ThXHityHxVV2p3fkw/c+MAvBHFVYHFZDmjMCQ==} @@ -11687,6 +11820,11 @@ snapshots: '@jridgewell/sourcemap-codec': 1.5.5 '@jridgewell/trace-mapping': 0.3.30 + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.30 + '@jridgewell/resolve-uri@3.1.2': {} '@jridgewell/source-map@0.3.11': @@ -12757,6 +12895,32 @@ snapshots: '@standard-schema/spec@1.0.0': {} + '@sveltejs/acorn-typescript@1.0.8(acorn@8.15.0)': + dependencies: + acorn: 8.15.0 + + '@sveltejs/vite-plugin-svelte-inspector@4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4)))(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4))': + dependencies: + '@sveltejs/vite-plugin-svelte': 5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4)) + debug: 4.4.3 + svelte: 5.46.4 + vite: 6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4) + transitivePeerDependencies: + - supports-color + + '@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4))': + dependencies: + '@sveltejs/vite-plugin-svelte-inspector': 4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4)))(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4)) + debug: 4.4.3 + deepmerge: 4.3.1 + kleur: 4.1.5 + magic-string: 0.30.21 + svelte: 5.46.4 + vite: 6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4) + vitefu: 1.1.1(vite@6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4)) + transitivePeerDependencies: + - supports-color + '@svgr/babel-plugin-add-jsx-attribute@8.0.0(@babel/core@7.28.3)': dependencies: '@babel/core': 7.28.3 @@ -14622,6 +14786,8 @@ snapshots: postcss: 8.5.6 postcss-value-parser: 4.2.0 + axobject-query@4.1.0: {} + babel-loader@9.2.1(@babel/core@7.28.3)(webpack@5.102.0): dependencies: '@babel/core': 7.28.3 @@ -15293,6 +15459,8 @@ snapshots: transitivePeerDependencies: - supports-color + devalue@5.6.2: {} + devlop@1.1.0: dependencies: dequal: 2.0.3 @@ -15548,6 +15716,8 @@ snapshots: transitivePeerDependencies: - supports-color + esm-env@1.2.2: {} + espree@10.4.0: dependencies: acorn: 8.15.0 @@ -15560,6 +15730,10 @@ snapshots: dependencies: estraverse: 5.3.0 + esrap@2.2.1: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + esrecurse@4.3.0: dependencies: estraverse: 5.3.0 @@ -16475,6 +16649,10 @@ snapshots: is-potential-custom-element-name@1.0.1: {} + is-reference@3.0.3: + dependencies: + '@types/estree': 1.0.8 + is-regexp@1.0.0: {} is-stream@2.0.1: {} @@ -16689,6 +16867,8 @@ snapshots: emojis-list: 3.0.0 json5: 2.2.3 + locate-character@3.0.0: {} + locate-path@5.0.0: dependencies: p-locate: 4.1.0 @@ -16753,6 +16933,10 @@ snapshots: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + magicast@0.3.5: dependencies: '@babel/parser': 7.28.3 @@ -19272,6 +19456,36 @@ snapshots: supports-preserve-symlinks-flag@1.0.0: {} + svelte-check@4.3.5(picomatch@4.0.3)(svelte@5.46.4)(typescript@5.6.3): + dependencies: + '@jridgewell/trace-mapping': 0.3.30 + chokidar: 4.0.3 + fdir: 6.5.0(picomatch@4.0.3) + picocolors: 1.1.1 + sade: 1.8.1 + svelte: 5.46.4 + typescript: 5.6.3 + transitivePeerDependencies: + - picomatch + + svelte@5.46.4: + dependencies: + '@jridgewell/remapping': 2.3.5 + '@jridgewell/sourcemap-codec': 1.5.5 + '@sveltejs/acorn-typescript': 1.0.8(acorn@8.15.0) + '@types/estree': 1.0.8 + acorn: 8.15.0 + aria-query: 5.3.2 + axobject-query: 4.1.0 + clsx: 2.1.1 + devalue: 5.6.2 + esm-env: 1.2.2 + esrap: 2.2.1 + is-reference: 3.0.3 + locate-character: 3.0.0 + magic-string: 0.30.19 + zimmerframe: 1.1.4 + svg-parser@2.0.4: {} svgo@3.3.2: @@ -19814,6 +20028,21 @@ snapshots: - tsx - yaml + vite@6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4): + dependencies: + esbuild: 0.25.9 + fdir: 6.5.0(picomatch@4.0.3) + picomatch: 4.0.3 + postcss: 8.5.6 + rollup: 4.50.2 + tinyglobby: 0.2.15 + optionalDependencies: + '@types/node': 24.3.0 + fsevents: 2.3.3 + jiti: 2.5.1 + terser: 5.43.1 + tsx: 4.20.4 + vite@7.1.5(@types/node@22.18.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4): dependencies: esbuild: 0.25.9 @@ -19844,6 +20073,10 @@ snapshots: terser: 5.43.1 tsx: 4.20.4 + vitefu@1.1.1(vite@6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4)): + optionalDependencies: + vite: 6.4.1(@types/node@24.3.0)(jiti@2.5.1)(terser@5.43.1)(tsx@4.20.4) + vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.5.1)(jsdom@26.1.0)(terser@5.43.1)(tsx@4.20.4): dependencies: '@types/chai': 5.2.2 @@ -20185,6 +20418,8 @@ snapshots: zen-observable@0.8.15: {} + zimmerframe@1.1.4: {} + zod@4.1.12: {} zwitch@2.0.4: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 0b6b411ea9e..e79a76ad249 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -2,6 +2,7 @@ packages: - 'crates/bindings-typescript' - 'crates/bindings-typescript/test-app' - 'templates/quickstart-chat-typescript' + - 'templates/svelte-ts' - 'templates/basic-react' - 'templates/basic-typescript' - 'modules/benchmarks-ts' diff --git a/templates/svelte-ts/.template.json b/templates/svelte-ts/.template.json new file mode 100644 index 00000000000..2f7d4081e89 --- /dev/null +++ b/templates/svelte-ts/.template.json @@ -0,0 +1,5 @@ +{ + "description": "Svelte web app with TypeScript server", + "client_lang": "typescript", + "server_lang": "typescript" +} diff --git a/templates/svelte-ts/LICENSE b/templates/svelte-ts/LICENSE new file mode 120000 index 00000000000..039e117dde2 --- /dev/null +++ b/templates/svelte-ts/LICENSE @@ -0,0 +1 @@ +../../licenses/apache2.txt \ No newline at end of file diff --git a/templates/svelte-ts/index.html b/templates/svelte-ts/index.html new file mode 100644 index 00000000000..3be04a1b6af --- /dev/null +++ b/templates/svelte-ts/index.html @@ -0,0 +1,12 @@ + + + + + + SpacetimeDB Svelte App + + +
+ + + diff --git a/templates/svelte-ts/package.json b/templates/svelte-ts/package.json new file mode 100644 index 00000000000..106ba63f522 --- /dev/null +++ b/templates/svelte-ts/package.json @@ -0,0 +1,25 @@ +{ + "name": "@clockworklabs/svelte-ts", + "private": true, + "version": "0.0.1", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview", + "generate": "pnpm --dir spacetimedb install --ignore-workspace && cargo run -p gen-bindings -- --out-dir src/module_bindings --project-path spacetimedb && prettier --write src/module_bindings", + "spacetime:generate": "spacetime generate --lang typescript --out-dir src/module_bindings --project-path spacetimedb", + "spacetime:publish:local": "spacetime publish --project-path spacetimedb --server local", + "spacetime:publish": "spacetime publish --project-path spacetimedb --server maincloud" + }, + "dependencies": { + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "^5.1.1", + "svelte": "^5.0.0", + "svelte-check": "^4.0.0", + "typescript": "~5.6.2", + "vite": "^6.4.1" + } +} diff --git a/templates/svelte-ts/spacetimedb/package.json b/templates/svelte-ts/spacetimedb/package.json new file mode 100644 index 00000000000..214ccc569bf --- /dev/null +++ b/templates/svelte-ts/spacetimedb/package.json @@ -0,0 +1,15 @@ +{ + "name": "spacetime-module", + "version": "1.0.0", + "description": "", + "scripts": { + "build": "spacetime build", + "publish": "spacetime publish" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "spacetimedb": "1.*" + } +} diff --git a/templates/svelte-ts/spacetimedb/src/index.ts b/templates/svelte-ts/spacetimedb/src/index.ts new file mode 100644 index 00000000000..900cb1bf2e9 --- /dev/null +++ b/templates/svelte-ts/spacetimedb/src/index.ts @@ -0,0 +1,33 @@ +import { schema, table, t } from 'spacetimedb/server'; + +export const spacetimedb = schema( + table( + { name: 'person', public: true }, + { + name: t.string(), + } + ) +); + +spacetimedb.init((_ctx) => { + // Called when the module is initially published +}); + +spacetimedb.clientConnected((_ctx) => { + // Called every time a new client connects +}); + +spacetimedb.clientDisconnected((_ctx) => { + // Called every time a client disconnects +}); + +spacetimedb.reducer('add', { name: t.string() }, (ctx, { name }) => { + ctx.db.person.insert({ name }); +}); + +spacetimedb.reducer('say_hello', (ctx) => { + for (const person of ctx.db.person.iter()) { + console.info(`Hello, ${person.name}!`); + } + console.info('Hello, World!'); +}); diff --git a/templates/svelte-ts/spacetimedb/tsconfig.json b/templates/svelte-ts/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..b6f79b99474 --- /dev/null +++ b/templates/svelte-ts/spacetimedb/tsconfig.json @@ -0,0 +1,23 @@ +/* + * This tsconfig is used for TypeScript projects created with `spacetimedb init + * --lang typescript`. You can modify it as needed for your project, although + * some options are required by SpacetimeDB. + */ +{ + "compilerOptions": { + "strict": true, + "skipLibCheck": true, + "moduleResolution": "bundler", + "jsx": "react-jsx", + + /* The following options are required by SpacetimeDB + * and should not be modified + */ + "target": "ESNext", + "lib": ["ES2021", "dom"], + "module": "ESNext", + "isolatedModules": true, + "noEmit": true + }, + "include": ["./**/*"] +} diff --git a/templates/svelte-ts/src/App.svelte b/templates/svelte-ts/src/App.svelte new file mode 100644 index 00000000000..9e3f0d37e2c --- /dev/null +++ b/templates/svelte-ts/src/App.svelte @@ -0,0 +1,63 @@ + + +
+

SpacetimeDB Svelte App

+ +
+ Status: + + {$conn.isActive ? 'Connected' : 'Disconnected'} + +
+ +
+ + +
+ +
+

People ({$people.length})

+ {#if $people.length === 0} +

No people yet. Add someone above!

+ {:else} +
    + {#each $people as person} +
  • {person.name}
  • + {/each} +
+ {/if} +
+
diff --git a/templates/svelte-ts/src/Root.svelte b/templates/svelte-ts/src/Root.svelte new file mode 100644 index 00000000000..b3341a11285 --- /dev/null +++ b/templates/svelte-ts/src/Root.svelte @@ -0,0 +1,37 @@ + + + diff --git a/templates/svelte-ts/src/main.ts b/templates/svelte-ts/src/main.ts new file mode 100644 index 00000000000..87d1f989c60 --- /dev/null +++ b/templates/svelte-ts/src/main.ts @@ -0,0 +1,6 @@ +import { mount } from 'svelte'; +import Root from './Root.svelte'; + +mount(Root, { + target: document.getElementById('app')!, +}); diff --git a/templates/svelte-ts/src/module_bindings/add_reducer.ts b/templates/svelte-ts/src/module_bindings/add_reducer.ts new file mode 100644 index 00000000000..85081559c7d --- /dev/null +++ b/templates/svelte-ts/src/module_bindings/add_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default { + name: __t.string(), +}; diff --git a/templates/svelte-ts/src/module_bindings/add_type.ts b/templates/svelte-ts/src/module_bindings/add_type.ts new file mode 100644 index 00000000000..638f62cea39 --- /dev/null +++ b/templates/svelte-ts/src/module_bindings/add_type.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('Add', { + name: __t.string(), +}); diff --git a/templates/svelte-ts/src/module_bindings/index.ts b/templates/svelte-ts/src/module_bindings/index.ts new file mode 100644 index 00000000000..d726335a186 --- /dev/null +++ b/templates/svelte-ts/src/module_bindings/index.ts @@ -0,0 +1,145 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +// This was generated using spacetimedb cli version 1.11.3 (commit 02449737ca3b29e7e39679fccbef541a50f32094). + +/* eslint-disable */ +/* tslint:disable */ +import { + DbConnectionBuilder as __DbConnectionBuilder, + DbConnectionImpl as __DbConnectionImpl, + SubscriptionBuilderImpl as __SubscriptionBuilderImpl, + TypeBuilder as __TypeBuilder, + Uuid as __Uuid, + convertToAccessorMap as __convertToAccessorMap, + procedureSchema as __procedureSchema, + procedures as __procedures, + reducerSchema as __reducerSchema, + reducers as __reducers, + schema as __schema, + t as __t, + table as __table, + type AlgebraicTypeType as __AlgebraicTypeType, + type DbConnectionConfig as __DbConnectionConfig, + type ErrorContextInterface as __ErrorContextInterface, + type Event as __Event, + type EventContextInterface as __EventContextInterface, + type Infer as __Infer, + type ReducerEventContextInterface as __ReducerEventContextInterface, + type RemoteModule as __RemoteModule, + type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, + type SubscriptionHandleImpl as __SubscriptionHandleImpl, +} from 'spacetimedb'; + +// Import and reexport all reducer arg types +import OnConnectReducer from './on_connect_reducer'; +export { OnConnectReducer }; +import OnDisconnectReducer from './on_disconnect_reducer'; +export { OnDisconnectReducer }; +import AddReducer from './add_reducer'; +export { AddReducer }; +import SayHelloReducer from './say_hello_reducer'; +export { SayHelloReducer }; + +// Import and reexport all procedure arg types + +// Import and reexport all table handle types +import PersonRow from './person_table'; +export { PersonRow }; + +// Import and reexport all types +import Add from './add_type'; +export { Add }; +import Init from './init_type'; +export { Init }; +import OnConnect from './on_connect_type'; +export { OnConnect }; +import OnDisconnect from './on_disconnect_type'; +export { OnDisconnect }; +import Person from './person_type'; +export { Person }; +import SayHello from './say_hello_type'; +export { SayHello }; + +/** The schema information for all tables in this module. This is defined the same was as the tables would have been defined in the server. */ +const tablesSchema = __schema( + __table( + { + name: 'person', + indexes: [], + constraints: [], + }, + PersonRow + ) +); + +/** The schema information for all reducers in this module. This is defined the same way as the reducers would have been defined in the server, except the body of the reducer is omitted in code generation. */ +const reducersSchema = __reducers( + __reducerSchema('add', AddReducer), + __reducerSchema('say_hello', SayHelloReducer) +); + +/** The schema information for all procedures in this module. This is defined the same way as the procedures would have been defined in the server. */ +const proceduresSchema = __procedures(); + +/** The remote SpacetimeDB module schema, both runtime and type information. */ +const REMOTE_MODULE = { + versionInfo: { + cliVersion: '1.11.3' as const, + }, + tables: tablesSchema.schemaType.tables, + reducers: reducersSchema.reducersType.reducers, + ...proceduresSchema, +} satisfies __RemoteModule< + typeof tablesSchema.schemaType, + typeof reducersSchema.reducersType, + typeof proceduresSchema +>; + +/** The tables available in this remote SpacetimeDB module. */ +export const tables = __convertToAccessorMap(tablesSchema.schemaType.tables); + +/** The reducers available in this remote SpacetimeDB module. */ +export const reducers = __convertToAccessorMap( + reducersSchema.reducersType.reducers +); + +/** The context type returned in callbacks for all possible events. */ +export type EventContext = __EventContextInterface; +/** The context type returned in callbacks for reducer events. */ +export type ReducerEventContext = __ReducerEventContextInterface< + typeof REMOTE_MODULE +>; +/** The context type returned in callbacks for subscription events. */ +export type SubscriptionEventContext = __SubscriptionEventContextInterface< + typeof REMOTE_MODULE +>; +/** The context type returned in callbacks for error events. */ +export type ErrorContext = __ErrorContextInterface; +/** The subscription handle type to manage active subscriptions created from a {@link SubscriptionBuilder}. */ +export type SubscriptionHandle = __SubscriptionHandleImpl; + +/** Builder class to configure a new subscription to the remote SpacetimeDB instance. */ +export class SubscriptionBuilder extends __SubscriptionBuilderImpl< + typeof REMOTE_MODULE +> {} + +/** Builder class to configure a new database connection to the remote SpacetimeDB instance. */ +export class DbConnectionBuilder extends __DbConnectionBuilder {} + +/** The typed database connection to manage connections to the remote SpacetimeDB instance. This class has type information specific to the generated module. */ +export class DbConnection extends __DbConnectionImpl { + /** Creates a new {@link DbConnectionBuilder} to configure and connect to the remote SpacetimeDB instance. */ + static builder = (): DbConnectionBuilder => { + return new DbConnectionBuilder( + REMOTE_MODULE, + (config: __DbConnectionConfig) => + new DbConnection(config) + ); + }; + + /** Creates a new {@link SubscriptionBuilder} to configure a subscription to the remote SpacetimeDB instance. */ + override subscriptionBuilder = (): SubscriptionBuilder => { + return new SubscriptionBuilder(this); + }; +} diff --git a/templates/svelte-ts/src/module_bindings/init_type.ts b/templates/svelte-ts/src/module_bindings/init_type.ts new file mode 100644 index 00000000000..52ed691ed94 --- /dev/null +++ b/templates/svelte-ts/src/module_bindings/init_type.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('Init', {}); diff --git a/templates/svelte-ts/src/module_bindings/on_connect_reducer.ts b/templates/svelte-ts/src/module_bindings/on_connect_reducer.ts new file mode 100644 index 00000000000..2ca99c88fea --- /dev/null +++ b/templates/svelte-ts/src/module_bindings/on_connect_reducer.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default {}; diff --git a/templates/svelte-ts/src/module_bindings/on_connect_type.ts b/templates/svelte-ts/src/module_bindings/on_connect_type.ts new file mode 100644 index 00000000000..d36362515de --- /dev/null +++ b/templates/svelte-ts/src/module_bindings/on_connect_type.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('OnConnect', {}); diff --git a/templates/svelte-ts/src/module_bindings/on_disconnect_reducer.ts b/templates/svelte-ts/src/module_bindings/on_disconnect_reducer.ts new file mode 100644 index 00000000000..2ca99c88fea --- /dev/null +++ b/templates/svelte-ts/src/module_bindings/on_disconnect_reducer.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default {}; diff --git a/templates/svelte-ts/src/module_bindings/on_disconnect_type.ts b/templates/svelte-ts/src/module_bindings/on_disconnect_type.ts new file mode 100644 index 00000000000..efda71ebcfd --- /dev/null +++ b/templates/svelte-ts/src/module_bindings/on_disconnect_type.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('OnDisconnect', {}); diff --git a/templates/svelte-ts/src/module_bindings/person_table.ts b/templates/svelte-ts/src/module_bindings/person_table.ts new file mode 100644 index 00000000000..0f70f74f617 --- /dev/null +++ b/templates/svelte-ts/src/module_bindings/person_table.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.row({ + name: __t.string(), +}); diff --git a/templates/svelte-ts/src/module_bindings/person_type.ts b/templates/svelte-ts/src/module_bindings/person_type.ts new file mode 100644 index 00000000000..1156775a3cf --- /dev/null +++ b/templates/svelte-ts/src/module_bindings/person_type.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('Person', { + name: __t.string(), +}); diff --git a/templates/svelte-ts/src/module_bindings/say_hello_reducer.ts b/templates/svelte-ts/src/module_bindings/say_hello_reducer.ts new file mode 100644 index 00000000000..2ca99c88fea --- /dev/null +++ b/templates/svelte-ts/src/module_bindings/say_hello_reducer.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default {}; diff --git a/templates/svelte-ts/src/module_bindings/say_hello_type.ts b/templates/svelte-ts/src/module_bindings/say_hello_type.ts new file mode 100644 index 00000000000..6293ca6bd09 --- /dev/null +++ b/templates/svelte-ts/src/module_bindings/say_hello_type.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from 'spacetimedb'; + +export default __t.object('SayHello', {}); diff --git a/templates/svelte-ts/svelte.config.js b/templates/svelte-ts/svelte.config.js new file mode 100644 index 00000000000..4c6b24b1073 --- /dev/null +++ b/templates/svelte-ts/svelte.config.js @@ -0,0 +1,5 @@ +import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; + +export default { + preprocess: vitePreprocess(), +}; diff --git a/templates/svelte-ts/tsconfig.json b/templates/svelte-ts/tsconfig.json new file mode 100644 index 00000000000..6406a7d1573 --- /dev/null +++ b/templates/svelte-ts/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "types": ["vite/client"], + "module": "ESNext", + "skipLibCheck": true, + + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "noUncheckedSideEffectImports": true + }, + "include": ["src", "vite.config.ts"] +} diff --git a/templates/svelte-ts/vite.config.ts b/templates/svelte-ts/vite.config.ts new file mode 100644 index 00000000000..5e6b0ec3055 --- /dev/null +++ b/templates/svelte-ts/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; + +// https://vite.dev/config/ +export default defineConfig({ + plugins: [svelte()], +}); diff --git a/templates/templates-list.json b/templates/templates-list.json index 05f8c035e5c..e83980a6f2f 100644 --- a/templates/templates-list.json +++ b/templates/templates-list.json @@ -1,6 +1,7 @@ { "highlights": [ - { "name": "React", "template_id": "basic-react" } + { "name": "React", "template_id": "basic-react" }, + { "name": "Svelte", "template_id": "svelte-ts" } ], "templates": [ { @@ -58,6 +59,14 @@ "client_source": "quickstart-chat-ts", "server_lang": "typescript", "client_lang": "typescript" + }, + { + "id": "svelte-ts", + "description": "Svelte web app with TypeScript server", + "server_source": "svelte-ts/spacetimedb", + "client_source": "svelte-ts", + "server_lang": "typescript", + "client_lang": "typescript" } ] }