import { type EnvironmentSchema } from './environment.ts'; import { moduleHooks, type ModuleDefaultExport } from 'spacetime:sys@2.0'; import { CaseConversionPolicy, type MethodOrAny, type RawModuleDefV10, type RawProcedureDefV10, type RawReducerDefV10, type RawTableDefV10, type Typespace } from '../lib/autogen/types.ts'; import { type ParamsObj, type Reducer } from '../lib/reducers.ts'; import { ModuleContext, type TablesToSchema, type UntypedSchemaDef } from '../lib/schema.ts'; import type { UntypedTableSchema } from '../lib/table_schema.ts'; import { TypeBuilder } from '../lib/type_builders.ts'; import { Router, type HandlerFn, type HttpHandlerExport, type HttpHandlerOpts } from './http_handlers.ts'; import { type ProcedureExport, type ProcedureFn, type ProcedureOpts, type ProcedureOptsWithOptionalName, type Procedures } from './procedures.ts'; import { type ReducerExport, type ReducerOpts, type ReducerOptsWithOptionalName, type Reducers } from './reducers.ts'; import { type AnonViews, type AnonymousViewFn, type ViewExport, type ViewFn, type ViewOpts, type ViewReturnTypeBuilder, type ValidateViewPrimaryKey, type Views } from './views.ts'; import type { UntypedTableDef } from '../lib/table.ts'; /** * Internal erased form of a scheduled reducer/procedure export. * * Public reducer/procedure schedule options preserve row/return-type checks * before values enter `pendingSchedules`. Legacy table schedules still resolve * through export object identity. */ type UntypedScheduledFunctionExport = ReducerExport | ProcedureExport; export type SubmoduleDispatchInfo = { namespace: string; reducerFns: Reducers; reducerDefs: RawReducerDefV10[]; procedureFns: Procedures; procedureDefs: RawProcedureDefV10[]; anonViewFns: AnonViews; viewFns: Views; typespace: Typespace; tables: Array<{ accessorName: string; tableDef: RawTableDefV10; }>; /** The submodule's own schemaType tables, used to build namespace-scoped query builders. */ schemaTables: Record; subDispatches: SubmoduleDispatchInfo[]; }; export declare class SchemaInner extends ModuleContext { schemaType: S; exportsRegistered: boolean; schedulesResolved: boolean; existingFunctions: Set; existingHttpHandlers: Set; reducers: Reducers; procedures: Procedures; views: Views; anonViews: AnonViews; httpHandlers: HandlerFn[]; /** * Maps reducer/procedure export objects to their source names. * Used for resolving scheduled table targets. */ functionExports: Map; tableSourceNames: Map; httpHandlerExports: Map, string>; pendingSchedules: PendingSchedule[]; pendingOutboxCallbacks: { table: UntypedTableSchema; functionName: string; }[]; pendingHttpRoutes: PendingHttpRoute[]; submoduleDispatchInfos: SubmoduleDispatchInfo[]; constructor(getSchemaType: (ctx: SchemaInner) => S); defineFunction(name: string): void; defineHttpHandler(name: string): void; resolveSchedules(): void; resolveOutboxCallbacks(): void; resolveHttpRoutes(): void; } type PendingSchedule = { table: UntypedTableSchema; tableName?: string; scheduleAtCol?: number; reducer?: () => UntypedScheduledFunctionExport; functionName?: string; }; type PendingHttpRoute = { handler: HttpHandlerExport; method: MethodOrAny; path: string; }; /** * The Schema class represents the database schema for a SpacetimeDB application. * It encapsulates the table definitions and typespace, and provides methods to define * reducers and lifecycle hooks. * * Schema has a generic parameter S which represents the inferred schema type. This type * is automatically inferred when creating a schema using the `schema()` function and is * used to type the database view in reducer contexts. * * The methods on this class are used to register reducers and lifecycle hooks * with the SpacetimeDB runtime. Theey forward to free functions that handle the actual * registration logic, but having them as methods on the Schema class helps with type inference. * * @template S - The inferred schema type of the SpacetimeDB module. * * @example * ```typescript * const spacetimedb = schema({ * user: table({}, userType), * post: table({}, postType) * }); * spacetimedb.reducer( * 'create_user', * { username: t.string(), email: t.string() }, * (ctx, { username, email }) => { * ctx.db.user.insert({ username, email, created_at: ctx.timestamp }); * console.log(`User ${username} created by ${ctx.sender.identityId}`); * } * ); * ``` */ export declare class Schema implements ModuleDefaultExport { #private; constructor(ctx: SchemaInner); [moduleHooks](exports: object): import("spacetime:sys@2.0").ModuleHooks; get schemaType(): S; get moduleDef(): import("../lib/schema.ts").ModuleDef; get typespace(): { readonly types: ({ tag: "Ref"; value: number; } | { tag: "Sum"; value: import("../index.ts").SumTypeType; } | { tag: "Product"; value: import("../index.ts").ProductTypeType; } | { tag: "Array"; value: import("./index.ts").AlgebraicTypeType; } | { tag: "String"; } | { tag: "Bool"; } | { tag: "I8"; } | { tag: "U8"; } | { tag: "I16"; } | { tag: "U16"; } | { tag: "I32"; } | { tag: "U32"; } | { tag: "I64"; } | { tag: "U64"; } | { tag: "I128"; } | { tag: "U128"; } | { tag: "I256"; } | { tag: "U256"; } | { tag: "F32"; } | { tag: "F64"; })[]; }; get submoduleDispatchInfos(): SubmoduleDispatchInfo[]; /** Internal: register exports and materialize the RawModuleDefV10 for upload. */ buildRawModuleDefV10(exports: object, opts?: { ignoreNonModuleExports?: boolean; }): RawModuleDefV10; /** * @internal – called by schema() when processing a submodule namespace entry. * Registers the library's exports and returns both the serialized module def * and the runtime dispatch info needed by ModuleHooksImpl for __call_reducer__. */ buildSubmoduleDispatch(exports: object): { rawDef: RawModuleDefV10; dispatch: SubmoduleDispatchInfo; }; /** * Defines a SpacetimeDB reducer function. * * Reducers are the primary way to modify the state of your SpacetimeDB application. * They are atomic, meaning that either all operations within a reducer succeed, * or none of them do. * * @template S - The inferred schema type of the SpacetimeDB module. * @template Params - The type of the parameters object expected by the reducer. * * @param {Params} params - An object defining the parameters that the reducer accepts. * Each key-value pair represents a parameter name and its corresponding * {@link TypeBuilder} or {@link ColumnBuilder}. * @param {(ctx: ReducerCtx, payload: ParamsAsObject) => void} fn - The reducer function itself. * - `ctx`: The reducer context, providing access to `sender`, `timestamp`, `connection_id`, and `db`. * - `payload`: An object containing the arguments passed to the reducer, typed according to `params`. * * @example * ```typescript * // Define a reducer named 'create_user' that takes 'username' (string) and 'email' (string) * export const create_user = spacetime.reducer( * { * username: t.string(), * email: t.string(), * }, * (ctx, { username, email }) => { * // Access the 'user' table from the database view in the context * ctx.db.user.insert({ username, email, created_at: ctx.timestamp }); * console.log(`User ${username} created by ${ctx.sender.identityId}`); * } * ); * ``` */ reducer(params: Params, fn: Reducer): ReducerExport; reducer(fn: Reducer): ReducerExport; reducer(opts: ReducerOptsWithOptionalName, params: Params, fn: Reducer): ReducerExport; reducer(opts: ReducerOpts<{}>, fn: Reducer): ReducerExport; /** * Registers an initialization reducer that runs when the SpacetimeDB module is published * for the first time. * * This function is useful to set up any initial state of your database that is guaranteed * to run only once, and before any other reducers or client connections. * * @template S - The inferred schema type of the SpacetimeDB module. * @param {Reducer} fn - The initialization reducer function. * - `ctx`: The reducer context, providing access to `sender`, `timestamp`, `connection_id`, and `db`. * @example * ```typescript * export const init = spacetime.init((ctx) => { * ctx.db.user.insert({ username: 'admin', email: 'admin@example.com' }); * }); * ``` */ init(fn: Reducer): ReducerExport; init(opts: ReducerOpts<{}>, fn: Reducer): ReducerExport; /** * Registers a reducer to be called when a client connects to the SpacetimeDB module. * This function allows you to define custom logic that should execute * whenever a new client establishes a connection. * @template S - The inferred schema type of the SpacetimeDB module. * * @param fn - The reducer function to execute on client connection. * * @example * ```typescript * export const onConnect = spacetime.clientConnected( * (ctx) => { * console.log(`Client ${ctx.connectionId} connected`); * } * ); */ clientConnected(fn: Reducer): ReducerExport; clientConnected(opts: ReducerOpts<{}>, fn: Reducer): ReducerExport; /** * Registers a reducer to be called when a client disconnects from the SpacetimeDB module. * This function allows you to define custom logic that should execute * whenever a client disconnects. * @template S - The inferred schema type of the SpacetimeDB module. * * @param fn - The reducer function to execute on client disconnection. * * @example * ```typescript * export const onDisconnect = spacetime.clientDisconnected( * (ctx) => { * console.log(`Client ${ctx.connectionId} disconnected`); * } * ); * ``` */ clientDisconnected(fn: Reducer): ReducerExport; clientDisconnected(opts: ReducerOpts<{}>, fn: Reducer): ReducerExport; view>(opts: ViewOpts, ret: Ret, fn: F, ..._: ValidateViewPrimaryKey): ViewExport; view>(opts: ViewOpts, params: Params, ret: Ret, fn: F, ..._: ValidateViewPrimaryKey): ViewExport; anonymousView>(opts: ViewOpts, ret: Ret, fn: F, ..._: ValidateViewPrimaryKey): ViewExport; anonymousView>(opts: ViewOpts, params: Params, ret: Ret, fn: F, ..._: ValidateViewPrimaryKey): ViewExport; procedure>(params: Params, ret: Ret, fn: ProcedureFn): ProcedureExport; procedure>(ret: Ret, fn: ProcedureFn): ProcedureExport; procedure>(opts: ProcedureOptsWithOptionalName, params: Params, ret: Ret, fn: ProcedureFn): ProcedureExport; procedure>(opts: ProcedureOpts<{}, Ret>, ret: Ret, fn: ProcedureFn): ProcedureExport; httpHandler(fn: HandlerFn): HttpHandlerExport; httpHandler(opts: HttpHandlerOpts, fn: HandlerFn): HttpHandlerExport; httpRouter(router: Router): ModuleExport; /** * Bundle multiple reducers, procedures, etc into one value to export. * The name they will be exported with is their corresponding key in the `exports` argument. */ exportGroup(exports: Record): ModuleExport; clientVisibilityFilter: { sql: (filter: string) => ModuleExport; }; } export declare const registerExport: unique symbol; export declare const exportContext: unique symbol; export interface ModuleExport { [registerExport](ctx: SchemaInner, exportName: string): void; [exportContext]?: SchemaInner; } /** * Extracts the inferred schema type from a Schema instance */ export type InferSchema> = SchemaDef extends Schema ? S : never; /** * Creates a schema from table definitions * @param handles - Array of table handles created by table() function * @returns ColumnBuilder representing the complete database schema * @example * ```ts * const spacetimedb = schema({ * user: table({}, userType), * post: table({}, postType) * }); * ``` */ /** * Module-level settings that can be passed to `schema()`. */ export interface ModuleSettings { /** Declared strings installed only through publishing; omitted means empty. */ env?: E; /** * The case conversion policy for this module. * Defaults to `SnakeCase` if not specified. * * @example * ```ts * export default schema({ * player, * }, { CASE_CONVERSION_POLICY: CaseConversionPolicy.None }); * ``` */ CASE_CONVERSION_POLICY?: CaseConversionPolicy; } type SubmoduleNamespace = { default: Schema; [key: string]: unknown; }; /** * A submodule mount that picks the canonical namespace name explicitly. * * * @example * ```ts * import * as authLib from 'auth_lib'; * const spacetimedb = schema({ * myAuth: { name: 'myAuth', module: authLib }, // force canonical name to 'myAuth' instead of 'my_auth' * }); * ``` */ export type SubmoduleMount = { name?: string; module: M; }; type SchemaEntry = UntypedTableSchema | SubmoduleNamespace | SubmoduleMount; type ExtractTableEntries> = { [K in keyof H as H[K] extends UntypedTableSchema ? K : never]: Extract; }; /** The submodule namespace object behind a schema entry, or `never` for tables. */ type SubmoduleOfEntry = E extends { default: Schema; } ? E : E extends { module: infer M extends { default: Schema; }; } ? M : never; type ExtractSubmoduleSchemas> = { [K in keyof H as [SubmoduleOfEntry] extends [never] ? never : K]: SubmoduleOfEntry extends { default: Schema; } ? S : never; }; type SchemaDefForEntries> = TablesToSchema> & { namespaces: ExtractSubmoduleSchemas; }; export declare function schema, const E extends EnvironmentSchema = {}>(entries: H, moduleSettings?: ModuleSettings): Schema & { env: E; }>; export {}; //# sourceMappingURL=schema.d.ts.map