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