The Coline App SDK: apps, tools, file types and surfaces that run inside Coline workspaces, and public websites with Coline Sites. TypeScript, with an in-memory test workspace. MIT.
| 4 | import type { ColineTask, ColineCalendarEvent, ColineMessage } from "../capabilities/workspace"; |
| 5 | import type { |
| 6 | ColineActorRef, |
| 7 | ColineCapabilities, |
| 8 | ColineConnectionStatus, |
| 9 | ColineFileSummaryV2, |
| 10 | ColineJobRun, |
| 11 | ColineJobStatus, |
| 12 | ColineMemberSummary, |
| 13 | ColineNetFetchInput, |
| 14 | ColineNetFetchResult, |
| 15 | ColineRecordEnvelope, |
| 16 | } from "../capabilities/types"; |
| 17 | import type { ColineAppManifestV2 } from "../manifest/manifest"; |
| 18 | import { EFFECT_CEILINGS, MUTATION_CLASS_RANK, type ToolEffect } from "../manifest/effect"; |
| 19 | import { uploadDataToBytes } from "../capabilities/upload"; |
| 20 |
| 21 | function toJobRun(run: TestJobRun): ColineJobRun { |
| 22 | return { |
| 23 | id: run.id, |
| 24 | name: run.name, |
| 25 | status: run.status, |
| 26 | attempt: run.attempt, |
| 27 | maxAttempts: run.maxAttempts, |
| 28 | progress: run.progress, |
| 29 | result: run.result ?? null, |
| 30 | error: run.error, |
| 31 | runAt: run.runAt, |
| 32 | createdAt: run.createdAt, |
| 33 | startedAt: run.startedAt, |
| 34 | finishedAt: run.finishedAt, |
| 35 | }; |
| 36 | } |
| 37 |
| 38 | /** |
| 39 | * The in-memory capability fake behind `createTestWorkspace` (plan §14.2). |
| 40 | * Implements the same `coline.*` contract apps run against in production, |
| 41 | * backed by maps — no network, no database, fully inspectable. |
| 42 | */ |
| 43 |
| 44 | export interface TestWorkspaceOptions { |
| 45 | grantedPermissions?: import("../manifest/permissions").AppPermissionV2[]; |
| 46 | workspaceId?: string; |
| 47 | workspaceSlug?: string; |
| 48 | workspaceName?: string; |
| 49 | appKey?: string; |
| 50 | installId?: string; |
| 51 | members?: Array<Partial<ColineMemberSummary> & { userId: string }>; |
| 52 | /** Handler for coline.net.fetch; defaults to rejecting. */ |
| 53 | onNetFetch?: (input: ColineNetFetchInput) => Promise<ColineNetFetchResult>; |
| 54 | /** Models enabled by the deterministic test provider. */ |
| 55 | aiModels?: import("../capabilities/ai").ColineAiModelInfo[]; |
| 56 | onAiJob?: Parameters<typeof fakeAi>[3]; |
| 57 | /** Handler for coline.ai.generate; defaults to echoing. */ |
| 58 | onAiGenerate?: (prompt: string) => Promise<string>; |
| 59 | /** Picker results; default null (dismissed) / false (confirm). */ |
| 60 | pickers?: { |
| 61 | file?: () => Promise<{ fileId: string } | null>; |
| 62 | member?: () => Promise<{ userId: string } | null>; |
| 63 | destination?: () => Promise<{ driveId: string; parentId: string | null } | null>; |
| 64 | confirm?: () => Promise<boolean>; |
| 65 | }; |
| 66 | /** Connections already made, by key. `connect()` marks a connection connected. */ |
| 67 | connections?: Record<string, { accountLabel?: string; scopes?: string[] }>; |
| 68 | } |
| 69 |
| 70 | export interface TestJobRun { |
| 71 | id: string; |
| 72 | name: string; |
| 73 | payload: Record<string, unknown>; |
| 74 | actor: ColineActorRef; |
| 75 | status: ColineJobStatus; |
| 76 | attempt: number; |
| 77 | maxAttempts: number; |
| 78 | runAt: string; |
| 79 | createdAt: string; |
| 80 | startedAt: string | null; |
| 81 | finishedAt: string | null; |
| 82 | checkpoint: unknown; |
| 83 | progress: { value: number; message: string | null } | null; |
| 84 | result: unknown; |
| 85 | error: { code: string; message: string } | null; |
| 86 | idempotencyKey: string | null; |
| 87 | } |
| 88 |
| 89 | export interface TestUpload { |
| 90 | file: TestFile; |
| 91 | mimeType: string; |
| 92 | bytes: Uint8Array; |
| 93 | } |
| 94 |
| 95 | export interface TestFile extends ColineFileSummaryV2 { |
| 96 | document: Record<string, unknown>; |
| 97 | trashed: boolean; |
| 98 | } |
| 99 |
| 100 | export interface TestNotification { |
| 101 | channelKey: string; |
| 102 | title: string; |
| 103 | body?: string | undefined; |
| 104 | href: string; |
| 105 | recipients: string[]; |
| 106 | } |
| 107 |
| 108 | export interface TestIndexDocument { |
| 109 | documentKey: string; |
| 110 | documentType: string; |
| 111 | title: string; |
| 112 | body: string; |
| 113 | fileId?: string | undefined; |
| 114 | } |
| 115 |
| 116 | export interface TestNavigationEvent { |
| 117 | intent: "openFile" | "openAppHome" | "navigate" | "openReference"; |
| 118 | payload: Record<string, unknown>; |
| 119 | } |
| 120 |
| 121 | export class TestWorkspaceState { |
| 122 | readonly tasks = new Map<string, ColineTask>(); |
| 123 | readonly calendar = new Map<string, ColineCalendarEvent>(); |
| 124 | readonly messages = new Map<string, ColineMessage[]>(); |
| 125 | readonly files = new Map<string, TestFile>(); |
| 126 | readonly kv = new Map<string, unknown>(); |
| 127 | readonly recordRevisions = new Map<string, number>(); |
| 128 | readonly realtimeListeners = new Map< |
| 129 | string, |
| 130 | Set<(message: { event: string; data: unknown }) => void> |
| 131 | >(); |
| 132 | readonly records = new Map<string, Map<string, ColineRecordEnvelope<Record<string, unknown>>>>(); |
| 133 | readonly notifications: TestNotification[] = []; |
| 134 | readonly indexDocuments = new Map<string, TestIndexDocument>(); |
| 135 | readonly navigations: TestNavigationEvent[] = []; |
| 136 | readonly events: { kind: string; payload?: Record<string, unknown> }[] = []; |
| 137 | readonly published: { event: string; data: unknown }[] = []; |
| 138 | readonly netRequests: ColineNetFetchInput[] = []; |
| 139 | readonly jobs = new Map<string, TestJobRun>(); |
| 140 | readonly uploads = new Map<string, TestUpload>(); |
| 141 | readonly connections = new Map<string, { accountLabel: string | null; scopes: string[]; connectedAt: string }>(); |
| 142 |
| 143 | private fileCounter = 0; |
| 144 | private recordCounter = 0; |
| 145 | private jobCounter = 0; |
| 146 |
| 147 | nextJobId(): string { |
| 148 | this.jobCounter += 1; |
| 149 | return `job_test_${this.jobCounter}`; |
| 150 | } |
| 151 |
| 152 | nextFileId(): string { |
| 153 | this.fileCounter += 1; |
| 154 | return `file_test_${this.fileCounter}`; |
| 155 | } |
| 156 |
| 157 | nextRecordId(): string { |
| 158 | this.recordCounter += 1; |
| 159 | return `rec_test_${this.recordCounter}`; |
| 160 | } |
| 161 |
| 162 | filesByType(typeKey: string): TestFile[] { |
| 163 | return [...this.files.values()].filter((file) => file.typeKey === typeKey && !file.trashed); |
| 164 | } |
| 165 | } |
| 166 |
| 167 | export function createFakeCapabilities( |
| 168 | state: TestWorkspaceState, |
| 169 | options: Required< |
| 170 | Pick< |
| 171 | TestWorkspaceOptions, |
| 172 | "workspaceId" | "workspaceSlug" | "workspaceName" | "appKey" | "installId" |
| 173 | > |
| 174 | > & { |
| 175 | members: ColineMemberSummary[]; |
| 176 | actor: ColineActorRef; |
| 177 | onNetFetch: TestWorkspaceOptions["onNetFetch"]; |
| 178 | onAiGenerate: TestWorkspaceOptions["onAiGenerate"]; |
| 179 | aiModels?: TestWorkspaceOptions["aiModels"]; |
| 180 | onAiJob?: TestWorkspaceOptions["onAiJob"]; |
| 181 | pickers: NonNullable<TestWorkspaceOptions["pickers"]>; |
| 182 | manifest: ColineAppManifestV2; |
| 183 | /** Ceiling of the executing unit; batches with deletes need destructive. */ |
| 184 | destructiveAllowed: boolean; |
| 185 | /** The executing unit's effect; a job it enqueues may not exceed it. */ |
| 186 | effect?: ToolEffect; |
| 187 | }, |
| 188 | ): ColineCapabilities { |
| 189 | const now = () => new Date().toISOString(); |
| 190 | const fail = (code: string, message: string): never => { |
| 191 | throw Object.assign(new Error(message), { code }); |
| 192 | }; |
| 193 | const connectionStatus = (key: string): ColineConnectionStatus => { |
| 194 | const declared = options.manifest.connections.find((connection) => connection.key === key); |
| 195 | if (!declared) return fail("connection_not_found", `This app does not declare connection "${key}".`); |
| 196 | const made = state.connections.get(key); |
| 197 | return { |
| 198 | key, |
| 199 | name: declared.name, |
| 200 | scope: declared.scope, |
| 201 | connected: Boolean(made), |
| 202 | account: made ? { label: made.accountLabel } : null, |
| 203 | scopes: made?.scopes ?? [], |
| 204 | connectedAt: made?.connectedAt ?? null, |
| 205 | }; |
| 206 | }; |
| 207 | const files = { |
| 208 | readUrl: async (fileId: string) => { |
| 209 | const upload = state.uploads.get(fileId); |
| 210 | if (!upload) return fail("file_not_binary", "This file has no binary content."); |
| 211 | return { url: `memory://uploads/${fileId}`, mimeType: upload.mimeType }; |
| 212 | }, |
| 213 | }; |
| 214 |
| 215 | return { |
| 216 | ...createFakeWorkspaceCapabilities( |
| 217 | state, |
| 218 | options.actor.kind === "user" ? options.actor.userId : null, |
| 219 | ), |
| 220 | tools: { |
| 221 | invoke: async () => { |
| 222 | throw new Error("Use createTestWorkspace to invoke tools."); |
| 223 | }, |
| 224 | }, |
| 225 | workspace: { |
| 226 | get: async () => ({ |
| 227 | workspaceId: options.workspaceId, |
| 228 | workspaceSlug: options.workspaceSlug, |
| 229 | workspaceName: options.workspaceName, |
| 230 | }), |
| 231 | }, |
| 232 | members: { |
| 233 | list: async () => ({ members: options.members }), |
| 234 | get: async (userId) => options.members.find((member) => member.userId === userId) ?? null, |
| 235 | }, |
| 236 | files: { |
| 237 | readUrl: files.readUrl, |
| 238 | upload: async (input) => { |
| 239 | const bytes = await uploadDataToBytes(input.data); |
| 240 | if (bytes.byteLength > 25 * 1024 * 1024) |
| 241 | return fail("upload_too_large", "files.upload accepts up to 25 MB."); |
| 242 | const mimeType = input.mimeType ?? "application/octet-stream"; |
| 243 | const file: TestFile = { |
| 244 | fileId: state.nextFileId(), |
| 245 | name: input.name, |
| 246 | typeKey: "file", |
| 247 | driveId: input.driveId ?? "drive_test_app", |
| 248 | parentId: input.parentId ?? null, |
| 249 | version: 1, |
| 250 | createdAt: now(), |
| 251 | updatedAt: now(), |
| 252 | document: {}, |
| 253 | trashed: false, |
| 254 | }; |
| 255 | state.files.set(file.fileId, file); |
| 256 | state.uploads.set(file.fileId, { file, mimeType, bytes }); |
| 257 | return { ...structuredClone(file), mimeType, size: bytes.byteLength }; |
| 258 | }, |
| 259 | createUpload: async (input) => ({ |
| 260 | uploadId: `upload_${input.name}`, |
| 261 | url: `memory://upload/${encodeURIComponent(input.name)}`, |
| 262 | headers: { "content-type": input.mimeType }, |
| 263 | expiresAt: new Date(Date.now() + 3_600_000).toISOString(), |
| 264 | }), |
| 265 | completeUpload: async () => |
| 266 | fail("upload_not_found", "Direct uploads are not simulated; use files.upload in tests."), |
| 267 | move: async (fileId, destination) => { |
| 268 | const file = state.files.get(fileId) ?? fail("file_not_found", "File not found."); |
| 269 | file.driveId = destination.driveId; |
| 270 | file.parentId = destination.parentId ?? null; |
| 271 | file.updatedAt = now(); |
| 272 | return structuredClone(file); |
| 273 | }, |
| 274 | saveAs: async (fileId) => { |
| 275 | const destination = options.pickers.destination ? await options.pickers.destination() : null; |
| 276 | if (!destination) return null; |
| 277 | const file = state.files.get(fileId) ?? fail("file_not_found", "File not found."); |
| 278 | file.driveId = destination.driveId; |
| 279 | file.parentId = destination.parentId; |
| 280 | file.updatedAt = now(); |
| 281 | return structuredClone(file); |
| 282 | }, |
| 283 | preview: async (fileId) => { |
| 284 | const file = state.files.get(fileId) ?? fail("file_not_found", "File not found."); |
| 285 | const upload = state.uploads.get(fileId); |
| 286 | return { |
| 287 | fileId, |
| 288 | name: file.name, |
| 289 | typeKey: file.typeKey, |
| 290 | tree: null, |
| 291 | media: upload ? { url: `memory://uploads/${fileId}`, mimeType: upload.mimeType } : null, |
| 292 | href: null, |
| 293 | }; |
| 294 | }, |
| 295 | list: async (input) => { |
| 296 | let files = [...state.files.values()].filter((file) => !file.trashed); |
| 297 | if (input?.typeKey) files = files.filter((file) => file.typeKey === input.typeKey); |
| 298 | if (input?.driveId) files = files.filter((file) => file.driveId === input.driveId); |
| 299 | const start = input?.cursor |
| 300 | ? files.findIndex((file) => file.fileId === input.cursor) + 1 |
| 301 | : 0; |
| 302 | const limit = input?.limit ?? 50; |
| 303 | const page = files.slice(start, start + limit); |
| 304 | return { |
| 305 | files: structuredClone(page), |
| 306 | nextCursor: files.length > start + limit ? page.at(-1)!.fileId : null, |
| 307 | }; |
| 308 | }, |
| 309 | get: async (fileId) => state.files.get(fileId) ?? null, |
| 310 | create: async (input) => { |
| 311 | const file: TestFile = { |
| 312 | fileId: state.nextFileId(), |
| 313 | name: input.name, |
| 314 | typeKey: input.typeKey, |
| 315 | driveId: input.driveId ?? "drive_test_app", |
| 316 | parentId: input.parentId ?? null, |
| 317 | version: 1, |
| 318 | createdAt: now(), |
| 319 | updatedAt: now(), |
| 320 | document: input.document ?? {}, |
| 321 | trashed: false, |
| 322 | }; |
| 323 | state.files.set(file.fileId, file); |
| 324 | return file; |
| 325 | }, |
| 326 | update: async (fileId, input) => { |
| 327 | const file = state.files.get(fileId); |
| 328 | if (!file) throw new Error(`Test file not found: ${fileId}`); |
| 329 | if (input.name) file.name = input.name; |
| 330 | file.updatedAt = now(); |
| 331 | return file; |
| 332 | }, |
| 333 | trash: async (fileId) => { |
| 334 | const file = state.files.get(fileId); |
| 335 | if (!file) throw new Error(`Test file not found: ${fileId}`); |
| 336 | file.trashed = true; |
| 337 | }, |
| 338 | getDocument: async (fileId) => { |
| 339 | const file = state.files.get(fileId); |
| 340 | if (!file) throw new Error(`Test file not found: ${fileId}`); |
| 341 | return file.document; |
| 342 | }, |
| 343 | updateDocument: async (fileId, document, options) => { |
| 344 | const file = state.files.get(fileId); |
| 345 | if (!file) throw new Error(`Test file not found: ${fileId}`); |
| 346 | if (options?.expectedVersion !== undefined && options.expectedVersion !== file.version) |
| 347 | throw Object.assign(new Error("The document changed. Reload before saving."), { |
| 348 | code: "document_conflict", |
| 349 | }); |
| 350 | file.document = structuredClone(document); |
| 351 | file.version += 1; |
| 352 | file.updatedAt = now(); |
| 353 | return { version: file.version, updatedAt: file.updatedAt }; |
| 354 | }, |
| 355 | }, |
| 356 | drives: { |
| 357 | getAppDrive: async () => ({ driveId: "drive_test_app" }), |
| 358 | }, |
| 359 | storage: { |
| 360 | kv: { |
| 361 | get: async (key) => state.kv.get(key) ?? null, |
| 362 | set: async (key, value) => { |
| 363 | state.kv.set(key, value ?? null); |
| 364 | }, |
| 365 | delete: async (key) => { |
| 366 | state.kv.delete(key); |
| 367 | }, |
| 368 | list: async (input) => ({ |
| 369 | keys: [...state.kv.keys()] |
| 370 | .filter((key) => !input?.prefix || key.startsWith(input.prefix)) |
| 371 | .sort() |
| 372 | .slice(0, input?.limit ?? 200), |
| 373 | }), |
| 374 | }, |
| 375 | collection: <TData>(name: string) => |
| 376 | createFakeCollection<TData>(state, name, options.actor, options.installId, { |
| 377 | destructiveAllowed: options.destructiveAllowed, |
| 378 | }), |
| 379 | batch: async (operations) => { |
| 380 | // Atomic across collections: snapshot every touched collection. |
| 381 | const names = [...new Set(operations.map((operation) => operation.collection))]; |
| 382 | const snapshots = new Map( |
| 383 | names.map((name) => [name, structuredClone([...(state.records.get(name) ?? new Map())])]), |
| 384 | ); |
| 385 | try { |
| 386 | const results = []; |
| 387 | for (const operation of operations) { |
| 388 | const { collection, ...rest } = operation; |
| 389 | const handle = createFakeCollection<Record<string, unknown>>( |
| 390 | state, |
| 391 | collection, |
| 392 | options.actor, |
| 393 | options.installId, |
| 394 | { destructiveAllowed: options.destructiveAllowed }, |
| 395 | ); |
| 396 | const { results: [result] } = await handle.batch([rest]); |
| 397 | results.push(result ?? null); |
| 398 | } |
| 399 | return { results }; |
| 400 | } catch (error) { |
| 401 | for (const [name, rows] of snapshots) state.records.set(name, new Map(rows)); |
| 402 | throw error; |
| 403 | } |
| 404 | }, |
| 405 | }, |
| 406 | jobs: { |
| 407 | enqueue: async (name, payload = {}, enqueueOptions = {}) => { |
| 408 | const declared = |
| 409 | options.manifest.jobs.find((job) => job.name === name) ?? |
| 410 | fail("job_not_found", `This app does not declare job "${name}".`); |
| 411 | // Same rule as production: a job may not exceed its enqueuer. |
| 412 | if ( |
| 413 | options.effect && |
| 414 | MUTATION_CLASS_RANK[EFFECT_CEILINGS[declared.effect].maxMutation] > |
| 415 | MUTATION_CLASS_RANK[EFFECT_CEILINGS[options.effect].maxMutation] |
| 416 | ) { |
| 417 | fail( |
| 418 | "effect_exceeds_caller", |
| 419 | `Job "${name}" is declared "${declared.effect}", which exceeds the "${options.effect}" effect of the code enqueueing it.`, |
| 420 | ); |
| 421 | } |
| 422 | // Like production, a key belongs to the principal that chose it: |
| 423 | // two members using "refresh" get their own runs. |
| 424 | const principal = options.actor.kind === "user" ? options.actor.userId : "app"; |
| 425 | const idempotencyKey = enqueueOptions.idempotencyKey ? `${principal}:${enqueueOptions.idempotencyKey}` : null; |
| 426 | if (idempotencyKey) { |
| 427 | const existing = [...state.jobs.values()].find((run) => run.idempotencyKey === idempotencyKey); |
| 428 | if (existing) return toJobRun(existing); |
| 429 | } |
| 430 | const runAt = enqueueOptions.runAt |
| 431 | ? new Date(enqueueOptions.runAt) |
| 432 | : new Date(Date.now() + (enqueueOptions.delaySeconds ?? 0) * 1000); |
| 433 | const run: TestJobRun = { |
| 434 | id: state.nextJobId(), |
| 435 | name, |
| 436 | payload: structuredClone(payload), |
| 437 | actor: options.actor, |
| 438 | status: "queued", |
| 439 | attempt: 0, |
| 440 | maxAttempts: declared.maxAttempts, |
| 441 | runAt: runAt.toISOString(), |
| 442 | createdAt: now(), |
| 443 | startedAt: null, |
| 444 | finishedAt: null, |
| 445 | checkpoint: null, |
| 446 | progress: null, |
| 447 | result: null, |
| 448 | error: null, |
| 449 | idempotencyKey, |
| 450 | }; |
| 451 | state.jobs.set(run.id, run); |
| 452 | return toJobRun(run); |
| 453 | }, |
| 454 | get: async (jobId) => { |
| 455 | const run = state.jobs.get(jobId); |
| 456 | return run ? toJobRun(run) : null; |
| 457 | }, |
| 458 | list: async (input) => { |
| 459 | const runs = [...state.jobs.values()] |
| 460 | .filter((run) => (!input?.name || run.name === input.name) && (!input?.status || run.status === input.status)) |
| 461 | .reverse(); |
| 462 | const offset = Number(input?.cursor ?? 0); |
| 463 | const limit = input?.limit ?? 50; |
| 464 | return { |
| 465 | runs: runs.slice(offset, offset + limit).map(toJobRun), |
| 466 | nextCursor: runs.length > offset + limit ? String(offset + limit) : null, |
| 467 | }; |
| 468 | }, |
| 469 | cancel: async (jobId) => { |
| 470 | const run = state.jobs.get(jobId) ?? fail("job_not_found", "Job run not found."); |
| 471 | if (run.status === "queued") { |
| 472 | run.status = "cancelled"; |
| 473 | run.finishedAt = now(); |
| 474 | } |
| 475 | return toJobRun(run); |
| 476 | }, |
| 477 | }, |
| 478 | connections: { |
| 479 | list: async () => ({ |
| 480 | connections: options.manifest.connections.map((connection) => connectionStatus(connection.key)), |
| 481 | }), |
| 482 | get: async (key) => connectionStatus(key), |
| 483 | connect: async (key) => { |
| 484 | connectionStatus(key); |
| 485 | if (!state.connections.has(key)) { |
| 486 | state.connections.set(key, { accountLabel: "test-account", scopes: [], connectedAt: now() }); |
| 487 | } |
| 488 | return connectionStatus(key); |
| 489 | }, |
| 490 | disconnect: async (key) => { |
| 491 | connectionStatus(key); |
| 492 | state.connections.delete(key); |
| 493 | }, |
| 494 | }, |
| 495 | endpoints: { |
| 496 | url: async (id) => { |
| 497 | if (!options.manifest.endpoints.some((endpoint) => endpoint.id === id)) |
| 498 | return fail("endpoint_not_found", `This app does not declare endpoint "${id}".`); |
| 499 | return { id, url: `https://coline.test/api/apps/endpoints/${options.installId}-${id}` }; |
| 500 | }, |
| 501 | list: async () => ({ |
| 502 | endpoints: options.manifest.endpoints.map((endpoint) => ({ |
| 503 | id: endpoint.id, |
| 504 | url: `https://coline.test/api/apps/endpoints/${options.installId}-${endpoint.id}`, |
| 505 | methods: endpoint.methods, |
| 506 | })), |
| 507 | }), |
| 508 | }, |
| 509 | search: { |
| 510 | query: async (input) => { |
| 511 | const query = input.query.toLowerCase(); |
| 512 | const matches = [...state.indexDocuments.values()].filter((doc) => |
| 513 | `${doc.title} ${doc.body}`.toLowerCase().includes(query), |
| 514 | ); |
| 515 | const offset = Number(input.cursor ?? 0), |
| 516 | limit = input.limit ?? 50; |
| 517 | return { |
| 518 | results: matches.slice(offset, offset + limit).map((doc) => ({ |
| 519 | documentKey: doc.documentKey, |
| 520 | documentType: doc.documentType, |
| 521 | title: doc.title, |
| 522 | snippet: doc.body, |
| 523 | url: null, |
| 524 | fileId: doc.fileId ?? null, |
| 525 | })), |
| 526 | nextCursor: matches.length > offset + limit ? String(offset + limit) : null, |
| 527 | }; |
| 528 | }, |
| 529 | index: { |
| 530 | upsert: async (input) => { |
| 531 | for (const document of input.documents) { |
| 532 | state.indexDocuments.set(document.documentKey, { |
| 533 | documentKey: document.documentKey, |
| 534 | documentType: document.documentType, |
| 535 | title: document.title, |
| 536 | body: document.body, |
| 537 | fileId: document.fileId, |
| 538 | }); |
| 539 | } |
| 540 | return { upserted: input.documents.length }; |
| 541 | }, |
| 542 | delete: async (input) => { |
| 543 | let deleted = 0; |
| 544 | for (const key of input.documentKeys) { |
| 545 | if (state.indexDocuments.delete(key)) deleted += 1; |
| 546 | } |
| 547 | return { deleted }; |
| 548 | }, |
| 549 | }, |
| 550 | }, |
| 551 | notifications: { |
| 552 | create: async (input) => { |
| 553 | state.notifications.push({ |
| 554 | channelKey: input.channelKey, |
| 555 | title: input.title, |
| 556 | body: input.body, |
| 557 | href: input.href, |
| 558 | recipients: input.recipients.map((recipient) => recipient.userId), |
| 559 | }); |
| 560 | }, |
| 561 | }, |
| 562 | ai: { |
| 563 | ...fakeAi(state, options.actor.kind === "user" ? options.actor.userId : null, options.aiModels ?? [], options.onAiJob), |
| 564 | generate: async (prompt) => ({ |
| 565 | text: options.onAiGenerate ? await options.onAiGenerate(prompt) : `echo: ${prompt}`, |
| 566 | }), |
| 567 | }, |
| 568 | net: { |
| 569 | fetch: async (input) => { |
| 570 | state.netRequests.push(input); |
| 571 | if (!options.onNetFetch) { |
| 572 | throw new Error("coline.net.fetch called in a test without an onNetFetch handler."); |
| 573 | } |
| 574 | return options.onNetFetch(input); |
| 575 | }, |
| 576 | }, |
| 577 | pickers: { |
| 578 | file: async () => (options.pickers.file ? options.pickers.file() : null), |
| 579 | member: async () => (options.pickers.member ? options.pickers.member() : null), |
| 580 | destination: async () => |
| 581 | options.pickers.destination ? options.pickers.destination() : null, |
| 582 | confirm: async () => (options.pickers.confirm ? options.pickers.confirm() : false), |
| 583 | }, |
| 584 | navigation: { |
| 585 | openFile: async (fileId) => { |
| 586 | state.navigations.push({ intent: "openFile", payload: { fileId } }); |
| 587 | }, |
| 588 | openAppHome: async () => { |
| 589 | state.navigations.push({ intent: "openAppHome", payload: {} }); |
| 590 | }, |
| 591 | navigate: async (href) => { |
| 592 | state.navigations.push({ intent: "navigate", payload: { href } }); |
| 593 | }, |
| 594 | openReference: async (reference) => { |
| 595 | state.navigations.push({ intent: "openReference", payload: { reference } }); |
| 596 | }, |
| 597 | }, |
| 598 | realtime: { |
| 599 | subscribe: async (event, handler) => { |
| 600 | const listeners = state.realtimeListeners.get(event) ?? new Set(); |
| 601 | listeners.add(handler); |
| 602 | state.realtimeListeners.set(event, listeners); |
| 603 | return { |
| 604 | unsubscribe: () => { |
| 605 | listeners.delete(handler); |
| 606 | }, |
| 607 | }; |
| 608 | }, |
| 609 | publish: async (event, data) => { |
| 610 | state.published.push({ event, data: data ?? null }); |
| 611 | for (const listener of state.realtimeListeners.get(event) ?? []) |
| 612 | listener({ event, data: data ?? null }); |
| 613 | return { delivered: true }; |
| 614 | }, |
| 615 | }, |
| 616 | events: { |
| 617 | emit: async (event, data) => { |
| 618 | state.events.push({ kind: event, ...(data ? { payload: data } : {}) }); |
| 619 | return { emitted: true }; |
| 620 | }, |
| 621 | }, |
| 622 | }; |
| 623 | } |
| 624 |