deepspace 0.8.2 → 0.9.1

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.
@@ -0,0 +1,115 @@
1
+ import * as _playwright_test from '@playwright/test';
2
+ import { BrowserContext, Page, Browser } from '@playwright/test';
3
+ export { expect } from '@playwright/test';
4
+
5
+ interface MultiplayerUser {
6
+ context: BrowserContext;
7
+ page: Page;
8
+ email: string;
9
+ name: string;
10
+ /** Test account user ID, if known from the accounts registry. */
11
+ userId?: string;
12
+ }
13
+ /**
14
+ * Fixture function signature. Pass either a count (`users(2)`) or an
15
+ * array of account names (`users(['Alice', 'Bob'])`). Returns one entry
16
+ * per requested user.
17
+ */
18
+ type UsersFixture = (selector: number | string[], options?: {
19
+ label?: string;
20
+ }) => Promise<MultiplayerUser[]>;
21
+ interface MultiplayerFixtures {
22
+ users: UsersFixture;
23
+ }
24
+ declare const test: _playwright_test.TestType<_playwright_test.PlaywrightTestArgs & _playwright_test.PlaywrightTestOptions & MultiplayerFixtures, _playwright_test.PlaywrightWorkerArgs & _playwright_test.PlaywrightWorkerOptions>;
25
+
26
+ /**
27
+ * Account-credential plumbing for the testing module.
28
+ *
29
+ * Reads test accounts from `~/.deepspace/test-accounts.json` (the same
30
+ * file `deepspace test accounts create` writes). Each account has at
31
+ * minimum `{email, password}`; `name` and `label` are optional.
32
+ *
33
+ * Used by the multi-user Playwright fixture in `./fixtures.ts` and is
34
+ * also exported standalone in case suites want to do their own
35
+ * orchestration.
36
+ */
37
+ interface TestAccount {
38
+ email: string;
39
+ password: string;
40
+ name?: string;
41
+ label?: string | null;
42
+ id?: string;
43
+ userId?: string;
44
+ createdAt?: number;
45
+ }
46
+ /**
47
+ * Load all test accounts the developer has created. Returns an empty
48
+ * array if the file doesn't exist yet.
49
+ */
50
+ declare function loadAllTestAccounts(): TestAccount[];
51
+ /**
52
+ * Pick `count` test accounts from the local registry, optionally
53
+ * filtered by `label`. Order-stable: sorted by `createdAt` ascending so
54
+ * the first test account you created is always the first one returned.
55
+ *
56
+ * Throws with a helpful message if not enough accounts exist.
57
+ */
58
+ declare function pickTestAccounts(count: number, options?: {
59
+ label?: string;
60
+ }): TestAccount[];
61
+ /**
62
+ * Find a single account by name. Used by `users(['Alice', 'Bob'])`.
63
+ * Throws if not found.
64
+ */
65
+ declare function findTestAccountByName(name: string): TestAccount;
66
+
67
+ /**
68
+ * Per-account `storageState` cache for Playwright.
69
+ *
70
+ * Better Auth applies a per-IP rate limit on `/api/auth/sign-in/email`
71
+ * (~5 sign-ins / 60s / endpoint). A multiplayer suite that spins up
72
+ * 5+ users per spec would hit the limit and start failing in non-obvious
73
+ * ways. This module signs each account in *once*, persists the
74
+ * resulting browser cookies + storage to disk, and reuses the file on
75
+ * subsequent runs.
76
+ *
77
+ * Cache layout:
78
+ * ~/.deepspace/playwright-states/<sha256(email)>.json
79
+ *
80
+ * Validity: a cached file is reused if Playwright successfully loads it
81
+ * AND the resulting context produces a non-anonymous session on the
82
+ * target app. If validation fails, we fall back to a fresh sign-in and
83
+ * overwrite the cache.
84
+ */
85
+
86
+ interface EnsureStorageStateOptions {
87
+ /** Max age of a cached state file before we re-sign-in. Default 7 days. */
88
+ maxAgeMs?: number;
89
+ /** Force a fresh sign-in even if the cache is fresh. */
90
+ force?: boolean;
91
+ }
92
+ /**
93
+ * Ensure a Playwright `storageState` file exists for `account` and
94
+ * return its path. Signs in once if the cache is missing, stale, or
95
+ * `force: true`.
96
+ */
97
+ declare function ensureStorageState(browser: Browser, account: {
98
+ email: string;
99
+ password: string;
100
+ }, baseURL: string, options?: EnsureStorageStateOptions): Promise<string>;
101
+ /**
102
+ * Convenience: open a fresh `BrowserContext` for `account` using the
103
+ * cached storage state (signing in if needed). The caller is responsible
104
+ * for closing the context.
105
+ */
106
+ declare function newSignedInContext(browser: Browser, account: {
107
+ email: string;
108
+ password: string;
109
+ }, baseURL: string, options?: EnsureStorageStateOptions): Promise<BrowserContext>;
110
+ /** Read a cached storageState file (mostly for debugging). */
111
+ declare function readCachedState(email: string): unknown | null;
112
+ /** Where the cache for `email` lives. Useful for diagnostics. */
113
+ declare function getStatePathForEmail(email: string): string;
114
+
115
+ export { type EnsureStorageStateOptions, type MultiplayerUser, type TestAccount, type UsersFixture, ensureStorageState, findTestAccountByName, getStatePathForEmail, loadAllTestAccounts, newSignedInContext, pickTestAccounts, readCachedState, test };
package/dist/worker.d.ts CHANGED
@@ -2603,10 +2603,11 @@ declare function parseQuotaLimit(raw: string | undefined, fallback: number): num
2603
2603
  */
2604
2604
  /** The singleton registry instance — one DO holds every app/route/collaborator. */
2605
2605
  declare const REGISTRY_INSTANCE = "v1:global";
2606
- /** App id shape: a ULID-minted `app_…` id, or a legacy name-as-id. */
2606
+ /** Public app ids have one canonical ULID-minted shape. */
2607
2607
  declare const APP_ID_RE: RegExp;
2608
- /** ONLY a ULID-minted id — surfaces that must not accept a legacy name. */
2609
2608
  declare const STRICT_APP_ID_RE: RegExp;
2609
+ /** Internal physical locators survive identity migration and are not public ids. */
2610
+ declare const RESOURCE_ID_RE: RegExp;
2610
2611
  declare class RegistryClientError extends Error {
2611
2612
  readonly code: string;
2612
2613
  readonly status: number;
@@ -3364,6 +3365,7 @@ declare function appendMessage(stub: DurableObjectStub, msg: {
3364
3365
  interface MeteringEnv {
3365
3366
  USAGE_EVENTS?: AnalyticsEngineDataset;
3366
3367
  OWNER_USER_ID?: string;
3368
+ DEEPSPACE_RESOURCE_ID?: string;
3367
3369
  APP_NAME?: string;
3368
3370
  }
3369
3371
  /**
@@ -4880,4 +4882,4 @@ interface AppLogsResponse {
4880
4882
  declare const APP_LOG_EVENT_KEYS: readonly ["id", "timestamp", "level", "eventType", "message", "source", "outcome", "request", "exception"];
4881
4883
  type AppLogEventKey = (typeof APP_LOG_EVENT_KEYS)[number];
4882
4884
 
4883
- export { AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, APP_ID_RE, APP_LOG_EVENT_KEYS, APP_NAME_RULES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type ApiWorkerEnv, type AppLogEvent, type AppLogEventKey, type AppLogsResponse, 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, CLIENT_LOG_MARKER, CONVERSATION_SCHEMAS, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientErrorKind, type ClientErrorReport, type ClientMessage, type CollectionPermissionSummary, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ComposioToolsOptions, 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_QUERY_LIMIT, DEPLOYED_APPS_DEFAULTS, 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 Job, type JobContext, JobRoom, type JobRoomConfig, type JobStatus, type JwtClaims, type JwtVerifierConfig, LOG_LEVELS, type LogLevel, 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, REGISTRY_INSTANCE, RESERVED_BINDING_NAMES, RESERVED_COLLECTION_NAMES, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, RegistryClientError, type ResolvedColumn, type ResolvedPermission, type RolePermissions, type RunMigrationsResult, STRICT_APP_ID_RE, SYSTEM_COLLECTIONS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ScreenshotEnv, type ScreenshotResult, type ServerMessage, type SharedConnection, type StoredRecord, type Summarizer, type SyncResult, TEST_ACCOUNT_EMAIL_SUFFIX, type TokenDebugInfo, type ToolResult, type ToolSchema, USERS_COLUMNS, type User, type UserAttachment, VOTING_SCHEMAS, type ValidationError, type VerifiedAuth, type VerifyOutcome, type VerifyResult, type Viewport, WORKSPACE_SCHEMAS, YjsRoom, analyzePermissions, apiWorkerFetch, appendMessage, applyAiToolDefaults, applySlidingWindow, authWorkerFetch, bindingManifestFromOutputConfig, buildCronContext, buildTableSelect, buildUiParts, callRegistry, canCreate, canDelete, canRead, canUpdate, capToolResultSize, captureScreenshot, checkFieldPermissions, clientBuild, coerceValue, collectionTableName, columnId, composioTools, computeDoMigration, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, dataToColumnValues, decodeJwtPayload, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, enqueueJob, getChat, getGlobalDOSchemas, getGlobalDOType, getMessageType, getRolePermissions, handleAwarenessMessage, handleClientErrorReport, handleSyncMessage, hasContent, isAutoProvision, isOwner, isTestAccountClaims, isTestAccountEmail, isTestAccountTier, lintSchema, loadMessages, makeDefaultSummarizer, matchOrigin, meterAi, meterUsage, meterVectorize, noopPermissionContext, parseQuotaLimit, platformCorsPatterns, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, readVarUint, readVarUint8Array, registerClientErrorRoute, registryErrorJson, registryStub, resolveAppName, resolveColumn, rowToData, runMigrations, serverBuild, timingSafeEqualHex, timingSafeEqualStrings, toUint8Array, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppName, validateBindingManifest, validateDoManifest, verifyJwt, workspaceAccountsSchema, workspaceContentSharesSchema, workspaceEmailHandlesSchema, workspaceFormResponsesSchema, workspacePeopleSchema, workspaceProjectsSchema, workspaceTagsSchema, workspaceTasksSchema, workspaceTeamMembersSchema, workspaceTeamsSchema, workspaceTransactionsSchema, writeVarUint, writeVarUint8Array };
4885
+ export { AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, APP_ID_RE, APP_LOG_EVENT_KEYS, APP_NAME_RULES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type ApiWorkerEnv, type AppLogEvent, type AppLogEventKey, type AppLogsResponse, 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, CLIENT_LOG_MARKER, CONVERSATION_SCHEMAS, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientErrorKind, type ClientErrorReport, type ClientMessage, type CollectionPermissionSummary, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ComposioToolsOptions, 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_QUERY_LIMIT, DEPLOYED_APPS_DEFAULTS, 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 Job, type JobContext, JobRoom, type JobRoomConfig, type JobStatus, type JwtClaims, type JwtVerifierConfig, LOG_LEVELS, type LogLevel, 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, REGISTRY_INSTANCE, RESERVED_BINDING_NAMES, RESERVED_COLLECTION_NAMES, RESOURCE_ID_RE, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, RegistryClientError, type ResolvedColumn, type ResolvedPermission, type RolePermissions, type RunMigrationsResult, STRICT_APP_ID_RE, SYSTEM_COLLECTIONS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ScreenshotEnv, type ScreenshotResult, type ServerMessage, type SharedConnection, type StoredRecord, type Summarizer, type SyncResult, TEST_ACCOUNT_EMAIL_SUFFIX, type TokenDebugInfo, type ToolResult, type ToolSchema, USERS_COLUMNS, type User, type UserAttachment, VOTING_SCHEMAS, type ValidationError, type VerifiedAuth, type VerifyOutcome, type VerifyResult, type Viewport, WORKSPACE_SCHEMAS, YjsRoom, analyzePermissions, apiWorkerFetch, appendMessage, applyAiToolDefaults, applySlidingWindow, authWorkerFetch, bindingManifestFromOutputConfig, buildCronContext, buildTableSelect, buildUiParts, callRegistry, canCreate, canDelete, canRead, canUpdate, capToolResultSize, captureScreenshot, checkFieldPermissions, clientBuild, coerceValue, collectionTableName, columnId, composioTools, computeDoMigration, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, dataToColumnValues, decodeJwtPayload, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, enqueueJob, getChat, getGlobalDOSchemas, getGlobalDOType, getMessageType, getRolePermissions, handleAwarenessMessage, handleClientErrorReport, handleSyncMessage, hasContent, isAutoProvision, isOwner, isTestAccountClaims, isTestAccountEmail, isTestAccountTier, lintSchema, loadMessages, makeDefaultSummarizer, matchOrigin, meterAi, meterUsage, meterVectorize, noopPermissionContext, parseQuotaLimit, platformCorsPatterns, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, readVarUint, readVarUint8Array, registerClientErrorRoute, registryErrorJson, registryStub, resolveAppName, resolveColumn, rowToData, runMigrations, serverBuild, timingSafeEqualHex, timingSafeEqualStrings, toUint8Array, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppName, validateBindingManifest, validateDoManifest, verifyJwt, workspaceAccountsSchema, workspaceContentSharesSchema, workspaceEmailHandlesSchema, workspaceFormResponsesSchema, workspacePeopleSchema, workspaceProjectsSchema, workspaceTagsSchema, workspaceTasksSchema, workspaceTeamMembersSchema, workspaceTeamsSchema, workspaceTransactionsSchema, writeVarUint, writeVarUint8Array };
package/dist/worker.js CHANGED
@@ -5108,6 +5108,8 @@ var RESERVED_BINDING_NAMES = /* @__PURE__ */ new Set([
5108
5108
  "ASSETS",
5109
5109
  "PLATFORM_WORKER",
5110
5110
  "API_WORKER",
5111
+ "DEEPSPACE_APP_ID",
5112
+ "DEEPSPACE_RESOURCE_ID",
5111
5113
  "APP_NAME",
5112
5114
  "OWNER_USER_ID",
5113
5115
  "AUTH_JWT_PUBLIC_KEY",
@@ -5125,7 +5127,9 @@ function validateBindingManifest(manifest) {
5125
5127
  const seenNames = /* @__PURE__ */ new Set();
5126
5128
  for (const entry of manifest) {
5127
5129
  if (!entry || typeof entry !== "object") {
5128
- errors.push({ reason: `Entry must be an object (got ${entry === null ? "null" : typeof entry})` });
5130
+ errors.push({
5131
+ reason: `Entry must be an object (got ${entry === null ? "null" : typeof entry})`
5132
+ });
5129
5133
  continue;
5130
5134
  }
5131
5135
  const e = entry;
@@ -5174,7 +5178,8 @@ function requiredFieldError(b) {
5174
5178
  case "r2_bucket":
5175
5179
  return b.bucket_name ? null : `r2_bucket binding "${b.name}" missing bucket_name (or "auto")`;
5176
5180
  case "kv_namespace": {
5177
- if (!b.namespace_id) return `kv_namespace binding "${b.name}" missing namespace_id (or "auto")`;
5181
+ if (!b.namespace_id)
5182
+ return `kv_namespace binding "${b.name}" missing namespace_id (or "auto")`;
5178
5183
  if (b.namespace_id === AUTO_PROVISION_SENTINEL && !b.title) {
5179
5184
  return `kv_namespace binding "${b.name}" with namespace_id="auto" requires "title"`;
5180
5185
  }
@@ -5979,8 +5984,9 @@ function parseQuotaLimit(raw, fallback) {
5979
5984
 
5980
5985
  // src/server/utils/registry-client.ts
5981
5986
  var REGISTRY_INSTANCE = "v1:global";
5982
- var APP_ID_RE = /^(app_[0-9A-HJKMNP-TV-Z]{26}|[a-z0-9][a-z0-9_-]{0,63})$/;
5983
- var STRICT_APP_ID_RE = /^app_[0-9A-HJKMNP-TV-Z]{26}$/;
5987
+ var APP_ID_RE = /^app_[0-9A-HJKMNP-TV-Z]{26}$/;
5988
+ var STRICT_APP_ID_RE = APP_ID_RE;
5989
+ var RESOURCE_ID_RE = /^(app_[0-9A-HJKMNP-TV-Z]{26}|[a-z0-9][a-z0-9_-]{0,63})$/;
5984
5990
  var RegistryClientError = class extends Error {
5985
5991
  constructor(message, code, status) {
5986
5992
  super(message);
@@ -7034,7 +7040,12 @@ function meterUsage(env, kind, fields = {}) {
7034
7040
  try {
7035
7041
  ds.writeDataPoint({
7036
7042
  indexes: [env.OWNER_USER_ID ?? "unknown"],
7037
- blobs: [env.APP_NAME ?? "unknown", kind, fields.id ?? "", fields.op ?? ""],
7043
+ blobs: [
7044
+ env.DEEPSPACE_RESOURCE_ID ?? env.APP_NAME ?? "unknown",
7045
+ kind,
7046
+ fields.id ?? "",
7047
+ fields.op ?? ""
7048
+ ],
7038
7049
  doubles: [fields.units ?? 0, fields.count ?? 0]
7039
7050
  });
7040
7051
  return true;
@@ -7591,6 +7602,7 @@ export {
7591
7602
  REGISTRY_INSTANCE,
7592
7603
  RESERVED_BINDING_NAMES,
7593
7604
  RESERVED_COLLECTION_NAMES,
7605
+ RESOURCE_ID_RE,
7594
7606
  ROLE_ADMIN,
7595
7607
  ROLE_ANONYMOUS,
7596
7608
  ROLE_DEFAULT,