deepspace 0.3.6 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/worker.d.ts CHANGED
@@ -815,11 +815,9 @@ interface UserAttachment {
815
815
  /** Subclass-specific data serialized alongside user info */
816
816
  [key: string]: unknown;
817
817
  }
818
- declare abstract class BaseRoom {
818
+ declare abstract class BaseRoom<E = Record<string, unknown>> {
819
819
  protected state: DurableObjectState;
820
- protected env: {
821
- [key: string]: unknown;
822
- };
820
+ protected env: E;
823
821
  protected sql: SqlStorage;
824
822
  constructor(state: DurableObjectState, env: unknown);
825
823
  fetch(request: Request): Promise<Response>;
@@ -915,6 +913,13 @@ interface YjsSubscription {
915
913
  recordId: string;
916
914
  fieldName: string;
917
915
  }
916
+ interface RecordResult {
917
+ recordId: string;
918
+ data: Record<string, unknown>;
919
+ createdBy: string;
920
+ createdAt: string;
921
+ updatedAt: string;
922
+ }
918
923
  interface DirectoryConversationData {
919
924
  Name: string;
920
925
  Description: string;
@@ -1270,7 +1275,7 @@ interface RecordRoomConfig {
1270
1275
  /**
1271
1276
  * RecordRoom Durable Object
1272
1277
  */
1273
- declare class RecordRoom extends BaseRoom {
1278
+ declare class RecordRoom<E = Record<string, unknown>> extends BaseRoom<E> {
1274
1279
  private schemaRegistry;
1275
1280
  private initPromise;
1276
1281
  /** Yjs docs loaded in memory (key: collection:recordId:fieldName) */
@@ -1333,7 +1338,7 @@ interface YjsAttachment extends UserAttachment {
1333
1338
  canWrite: boolean;
1334
1339
  awarenessClientId: number | null;
1335
1340
  }
1336
- declare class YjsRoom extends BaseRoom {
1341
+ declare class YjsRoom<E = Record<string, unknown>> extends BaseRoom<E> {
1337
1342
  private doc;
1338
1343
  private initialized;
1339
1344
  constructor(state: DurableObjectState, env: unknown);
@@ -1391,7 +1396,7 @@ interface GameInput {
1391
1396
  interface GameAttachment extends UserAttachment {
1392
1397
  joinedAt: string;
1393
1398
  }
1394
- declare abstract class GameRoom extends BaseRoom {
1399
+ declare abstract class GameRoom<E = Record<string, unknown>> extends BaseRoom<E> {
1395
1400
  private config;
1396
1401
  private players;
1397
1402
  private inputBuffer;
@@ -1488,7 +1493,7 @@ interface Viewport {
1488
1493
  interface CanvasAttachment extends UserAttachment {
1489
1494
  viewport: Viewport | null;
1490
1495
  }
1491
- declare class CanvasRoom extends BaseRoom {
1496
+ declare class CanvasRoom<E = Record<string, unknown>> extends BaseRoom<E> {
1492
1497
  private doc;
1493
1498
  private initialized;
1494
1499
  private viewports;
@@ -1541,7 +1546,7 @@ interface PresencePeer {
1541
1546
  interface PresenceAttachment extends UserAttachment {
1542
1547
  joinedAt: string;
1543
1548
  }
1544
- declare class PresenceRoom extends BaseRoom {
1549
+ declare class PresenceRoom<E = Record<string, unknown>> extends BaseRoom<E> {
1545
1550
  private peers;
1546
1551
  private peerSockets;
1547
1552
  constructor(state: DurableObjectState, env: unknown);
@@ -1593,7 +1598,7 @@ interface CronExecution {
1593
1598
  durationMs: number;
1594
1599
  error?: string;
1595
1600
  }
1596
- declare abstract class CronRoom extends BaseRoom {
1601
+ declare abstract class CronRoom<E = Record<string, unknown>> extends BaseRoom<E> {
1597
1602
  private tasks;
1598
1603
  private initialized;
1599
1604
  constructor(state: DurableObjectState, env: unknown, config: CronRoomConfig);
@@ -2285,24 +2290,62 @@ declare function createScopedR2Handler(config: ScopedR2Config): ScopedR2Handler;
2285
2290
  * Actions bypass user RBAC via the X-App-Action header — the app's
2286
2291
  * server-side code IS the trust boundary.
2287
2292
  */
2288
- interface ActionResult {
2289
- success: boolean;
2290
- data?: unknown;
2291
- error?: string;
2293
+
2294
+ /**
2295
+ * Discriminated result wrapper. Narrowing on `.success` lets TS know
2296
+ * `.data` is present in the success branch and `.error` in the failure
2297
+ * branch, so callers can't read the wrong field by accident.
2298
+ *
2299
+ * `TData` is the per-operation data shape — `tools.query` returns
2300
+ * `{ records, count }`, `tools.get` returns `{ record }`, etc. Apps
2301
+ * that compose their own server actions can specialize further.
2302
+ */
2303
+ type ActionResult<TData = unknown> = {
2304
+ success: true;
2305
+ data: TData;
2306
+ error?: never;
2307
+ } | {
2308
+ success: false;
2309
+ data?: never;
2310
+ error: string;
2311
+ };
2312
+ /** Shape of the data field for `tools.query`. */
2313
+ interface QueryActionData<T = Record<string, unknown>> {
2314
+ records: Array<RecordResult & {
2315
+ data: T;
2316
+ }>;
2317
+ count: number;
2318
+ }
2319
+ /** Shape of the data field for `tools.get`. */
2320
+ interface GetActionData<T = Record<string, unknown>> {
2321
+ record: RecordResult & {
2322
+ data: T;
2323
+ };
2324
+ }
2325
+ /** Shape of the data field for `tools.create`/`update`/`remove`. */
2326
+ interface MutateActionData {
2327
+ recordId: string;
2328
+ }
2329
+ /** Shape of the data field for `tools.integration`. */
2330
+ interface IntegrationActionData<T = unknown> {
2331
+ /** The integration endpoint's response body, parsed as JSON when possible. */
2332
+ response: T;
2333
+ /** HTTP status the api-worker forwarded back. */
2334
+ status?: number;
2292
2335
  }
2293
2336
  interface ActionTools {
2294
- create(collection: string, data: Record<string, unknown>): Promise<ActionResult>;
2295
- update(collection: string, recordId: string, data: Record<string, unknown>): Promise<ActionResult>;
2296
- remove(collection: string, recordId: string): Promise<ActionResult>;
2297
- get(collection: string, recordId: string): Promise<ActionResult>;
2298
- query(collection: string, options?: {
2337
+ create<T extends Record<string, unknown> = Record<string, unknown>>(collection: string, data: T): Promise<ActionResult<MutateActionData>>;
2338
+ update<T extends Record<string, unknown> = Record<string, unknown>>(collection: string, recordId: string, data: Partial<T>): Promise<ActionResult<MutateActionData>>;
2339
+ remove(collection: string, recordId: string): Promise<ActionResult<MutateActionData>>;
2340
+ get<T extends Record<string, unknown> = Record<string, unknown>>(collection: string, recordId: string): Promise<ActionResult<GetActionData<T>>>;
2341
+ query<T extends Record<string, unknown> = Record<string, unknown>>(collection: string, options?: {
2299
2342
  where?: Record<string, unknown>;
2300
2343
  orderBy?: string;
2301
2344
  orderDir?: 'asc' | 'desc';
2302
2345
  limit?: number;
2303
- }): Promise<ActionResult>;
2346
+ }): Promise<ActionResult<QueryActionData<T>>>;
2304
2347
  /** Call an integration endpoint (e.g. 'openai/completions') via the API worker */
2305
- integration(endpoint: string, data?: unknown): Promise<ActionResult>;
2348
+ integration<T = unknown>(endpoint: string, data?: unknown): Promise<ActionResult<IntegrationActionData<T>>>;
2306
2349
  }
2307
2350
  /**
2308
2351
  * `TEnv` lets apps type the worker-scoped env object passed to the
@@ -3847,4 +3890,4 @@ type DeepSpaceAuth = ReturnType<typeof createDeepSpaceAuth>;
3847
3890
  /** Collections that bypass schema checks (permissive access) */
3848
3891
  declare const SYSTEM_COLLECTIONS: Set<string>;
3849
3892
 
3850
- export { AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, APP_NAME_RULES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type ApiWorkerEnv, type AppNameResolution, type AppNameValidation, type AuthWorkerEnv, Awareness, type AwarenessState, type AwarenessStates, BASE_USERS_SCHEMA, BUILT_IN_TOOLS, type BaseMessage, BaseRoom, CHANNELS_SCHEMA, CHANNEL_INVITATIONS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, CONVERSATION_SCHEMAS, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientMessage, type CollectionPermissionSummary, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ConnectionAttachment, type ConvMemberData, type ConvMessageData, type ConvReactionData, type ConvReadCursorData, type ConvVoteData, type ConversationStateData, type CronContext, type CronExecution, CronRoom, type CronRoomConfig, type CronTask, type CustomBinding, type CustomBindingManifest, DEFAULT_CONTEXT_CONFIG, DEFAULT_DO_MANIFEST, DEFAULT_MAX_SKEW_MS, DIRECTORY_SCHEMAS, type DOBindings, type DOManifest, type DOManifestEntry, type DeepSpaceAIEnv, type DeepSpaceAIOptions, type DeepSpaceAuth, type DeepSpaceAuthConfig, type DirectoryCommunityData, type DirectoryConversationData, type DirectoryMembershipData, type DirectoryPostData, type DoMigrationDirective, type DoMigrationPlan, type ExistingDOBinding, GLOBAL_DO_TYPES, GLOBAL_DO_TYPE_NAMES, type GameInput, GameRoom, type GameRoomConfig, type GlobalDOType, type HandlerContext, type InternalSignature, type JwtClaims, type JwtVerifierConfig, MESSAGES_SCHEMA, MSG, MSG_AWARENESS, MSG_SYNC, MSG_SYNC_STEP1, MSG_SYNC_STEP2, MSG_SYNC_UPDATE, MSG_YJS_AWARENESS, MSG_YJS_SYNC, type MessageHandlers, type MsgType, type PermissionAnalysis, type PermissionContext, type PermissionLevel, type PermissionSource, type PlatformWorkerEnv, type Player, type PrefixResult, type PresencePeer, PresenceRoom, type ProtocolMessage, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, RESERVED_BINDING_NAMES, RESERVED_COLLECTION_NAMES, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, type ResolvedColumn, type ResolvedPermission, type RolePermissions, type RunMigrationsResult, SYSTEM_COLLECTIONS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ServerMessage, type SharedConnection, type SignInternalPayloadInput, type StoredRecord, type Summarizer, type SyncResult, type TokenDebugInfo, type ToolResult, type ToolSchema, USERS_COLUMNS, type User, type UserAttachment, VOTING_SCHEMAS, type ValidationError, type VerifiedAuth, type VerifyInternalSignatureInput, type VerifyOutcome, type VerifyResult, type Viewport, WORKSPACE_SCHEMAS, YjsRoom, analyzePermissions, apiWorkerFetch, appendMessage, applySlidingWindow, authWorkerFetch, bindingManifestFromOutputConfig, buildCronContext, buildInternalPayload, buildTableSelect, buildUiParts, canCreate, canDelete, canRead, canUpdate, capToolResultSize, checkFieldPermissions, clientBuild, coerceValue, collectionTableName, columnId, computeDoMigration, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, dataToColumnValues, decodeJwtPayload, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, getChat, getGlobalDOSchemas, getGlobalDOType, getMessageType, getRolePermissions, handleAwarenessMessage, handleSyncMessage, hasContent, isAutoProvision, isOwner, loadMessages, makeDefaultSummarizer, meterAi, meterUsage, meterVectorize, noopPermissionContext, platformWorkerFetch, prepareMessagesWithCompaction, readVarUint, readVarUint8Array, resolveAppName, resolveColumn, rowToData, runMigrations, serverBuild, signInternalPayload, timingSafeEqualHex, toUint8Array, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppName, validateBindingManifest, validateDoManifest, verifyInternalSignature, verifyJwt, workspaceAccountsSchema, workspaceContentSharesSchema, workspaceEmailHandlesSchema, workspaceFormResponsesSchema, workspacePeopleSchema, workspaceProjectsSchema, workspaceTagsSchema, workspaceTasksSchema, workspaceTeamMembersSchema, workspaceTeamsSchema, workspaceTransactionsSchema, writeVarUint, writeVarUint8Array };
3893
+ export { AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, APP_NAME_RULES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type ApiWorkerEnv, type AppNameResolution, type AppNameValidation, type AuthWorkerEnv, Awareness, type AwarenessState, type AwarenessStates, BASE_USERS_SCHEMA, BUILT_IN_TOOLS, type BaseMessage, BaseRoom, CHANNELS_SCHEMA, CHANNEL_INVITATIONS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, CONVERSATION_SCHEMAS, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientMessage, type CollectionPermissionSummary, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ConnectionAttachment, type ConvMemberData, type ConvMessageData, type ConvReactionData, type ConvReadCursorData, type ConvVoteData, type ConversationStateData, type CronContext, type CronExecution, CronRoom, type CronRoomConfig, type CronTask, type CustomBinding, type CustomBindingManifest, DEFAULT_CONTEXT_CONFIG, DEFAULT_DO_MANIFEST, DEFAULT_MAX_SKEW_MS, DIRECTORY_SCHEMAS, type DOBindings, type DOManifest, type DOManifestEntry, type DeepSpaceAIEnv, type DeepSpaceAIOptions, type DeepSpaceAuth, type DeepSpaceAuthConfig, type DirectoryCommunityData, type DirectoryConversationData, type DirectoryMembershipData, type DirectoryPostData, type DoMigrationDirective, type DoMigrationPlan, type ExistingDOBinding, GLOBAL_DO_TYPES, GLOBAL_DO_TYPE_NAMES, type GameInput, GameRoom, type GameRoomConfig, type GetActionData, type GlobalDOType, type HandlerContext, type IntegrationActionData, type InternalSignature, type JwtClaims, type JwtVerifierConfig, MESSAGES_SCHEMA, MSG, MSG_AWARENESS, MSG_SYNC, MSG_SYNC_STEP1, MSG_SYNC_STEP2, MSG_SYNC_UPDATE, MSG_YJS_AWARENESS, MSG_YJS_SYNC, type MessageHandlers, type MsgType, type MutateActionData, type PermissionAnalysis, type PermissionContext, type PermissionLevel, type PermissionSource, type PlatformWorkerEnv, type Player, type PrefixResult, type PresencePeer, PresenceRoom, type ProtocolMessage, type QueryActionData, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, RESERVED_BINDING_NAMES, RESERVED_COLLECTION_NAMES, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, type ResolvedColumn, type ResolvedPermission, type RolePermissions, type RunMigrationsResult, SYSTEM_COLLECTIONS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ServerMessage, type SharedConnection, type SignInternalPayloadInput, type StoredRecord, type Summarizer, type SyncResult, type TokenDebugInfo, type ToolResult, type ToolSchema, USERS_COLUMNS, type User, type UserAttachment, VOTING_SCHEMAS, type ValidationError, type VerifiedAuth, type VerifyInternalSignatureInput, type VerifyOutcome, type VerifyResult, type Viewport, WORKSPACE_SCHEMAS, YjsRoom, analyzePermissions, apiWorkerFetch, appendMessage, applySlidingWindow, authWorkerFetch, bindingManifestFromOutputConfig, buildCronContext, buildInternalPayload, buildTableSelect, buildUiParts, canCreate, canDelete, canRead, canUpdate, capToolResultSize, checkFieldPermissions, clientBuild, coerceValue, collectionTableName, columnId, computeDoMigration, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, dataToColumnValues, decodeJwtPayload, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, getChat, getGlobalDOSchemas, getGlobalDOType, getMessageType, getRolePermissions, handleAwarenessMessage, handleSyncMessage, hasContent, isAutoProvision, isOwner, loadMessages, makeDefaultSummarizer, meterAi, meterUsage, meterVectorize, noopPermissionContext, platformWorkerFetch, prepareMessagesWithCompaction, readVarUint, readVarUint8Array, resolveAppName, resolveColumn, rowToData, runMigrations, serverBuild, signInternalPayload, timingSafeEqualHex, toUint8Array, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppName, validateBindingManifest, validateDoManifest, verifyInternalSignature, verifyJwt, workspaceAccountsSchema, workspaceContentSharesSchema, workspaceEmailHandlesSchema, workspaceFormResponsesSchema, workspacePeopleSchema, workspaceProjectsSchema, workspaceTagsSchema, workspaceTasksSchema, workspaceTeamMembersSchema, workspaceTeamsSchema, workspaceTransactionsSchema, writeVarUint, writeVarUint8Array };
package/dist/worker.js CHANGED
@@ -1507,7 +1507,7 @@ function handleSubscribe(ctx, ws, attachment, payload) {
1507
1507
  }
1508
1508
  function handleUnsubscribe(_ctx, _ws, _attachment, _payload) {
1509
1509
  }
1510
- function executeQuery(ctx, query, userId, userRole) {
1510
+ function executeQuery(ctx, query, userId, userRole, skipUserRbac = false) {
1511
1511
  const isSystem = SYSTEM_COLLECTIONS.has(query.collection);
1512
1512
  const schema = ctx.schemaRegistry.get(query.collection);
1513
1513
  if (!schema && !isSystem) {
@@ -1516,7 +1516,7 @@ function executeQuery(ctx, query, userId, userRole) {
1516
1516
  if (!schema) {
1517
1517
  return executeSystemQuery(ctx, query);
1518
1518
  }
1519
- return executeTableQuery(ctx, query, schema, userId, userRole, isSystem);
1519
+ return executeTableQuery(ctx, query, schema, userId, userRole, isSystem, skipUserRbac);
1520
1520
  }
1521
1521
  function executeSystemQuery(ctx, query) {
1522
1522
  const tbl = collectionTableName(query.collection);
@@ -1552,14 +1552,14 @@ function preloadUserTeamIds(ctx, userId) {
1552
1552
  );
1553
1553
  return cursor.toArray().map((r) => r.col_teamid);
1554
1554
  }
1555
- function executeTableQuery(ctx, query, schema, userId, userRole, isSystem) {
1555
+ function executeTableQuery(ctx, query, schema, userId, userRole, isSystem, skipUserRbac = false) {
1556
1556
  const columns = (schema.columns ?? []).map(resolveColumn);
1557
1557
  const perms = getRolePermissions(schema, userRole);
1558
1558
  let sql = buildTableSelect(query.collection, columns);
1559
1559
  const params = [];
1560
1560
  const whereClauses = [];
1561
- let skipPerRecordCheck = false;
1562
- if (schema.teamField && perms.read === "team") {
1561
+ let skipPerRecordCheck = skipUserRbac;
1562
+ if (!skipUserRbac && schema.teamField && perms.read === "team") {
1563
1563
  const filterCol = schema.teamField === "_rowId" ? "_row_id" : columns.find((c) => c.name === schema.teamField)?.id ?? columnId(schema.teamField);
1564
1564
  const teamIds = preloadUserTeamIds(ctx, userId);
1565
1565
  if (teamIds && teamIds.length > 0) {
@@ -2128,7 +2128,7 @@ function executeTool(ctx, toolName, params, userId, userRole, skipUserRbac) {
2128
2128
  orderDir: params.orderDir,
2129
2129
  limit: params.limit
2130
2130
  };
2131
- const records = executeQuery(ctx, query, userId, userRole);
2131
+ const records = executeQuery(ctx, query, userId, userRole, skipUserRbac);
2132
2132
  return { success: true, data: { records, count: records.length } };
2133
2133
  }
2134
2134
  case "records.get": {