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.
| 6 | ColineRecordQuery, |
| 7 | } from "../capabilities/types"; |
| 8 | import { |
| 9 | canAccessRecord, |
| 10 | canVisitorAccess, |
| 11 | DEFAULT_RECORD_ACCESS, |
| 12 | sameActor, |
| 13 | } from "../capabilities/record-access"; |
| 14 | import { |
| 15 | aggregateRecords, |
| 16 | compareRecords, |
| 17 | matchesRecordWhere, |
| 18 | normalizeRecordSort, |
| 19 | } from "../capabilities/record-query"; |
| 20 | import type { CollectionAccess } from "../manifest/collections"; |
| 21 | import type { TestWorkspaceState } from "./fake-capabilities"; |
| 22 |
| 23 | type Row = ColineRecordEnvelope<unknown> & { data: Record<string, unknown> }; |
| 24 |
| 25 | const MAX_PAGE = 1000; |
| 26 | const MAX_BATCH = 500; |
| 27 | const MAX_BULK = 5000; |
| 28 |
| 29 | const TEAM_ONLY: CollectionAccess = { read: "team", create: "team", update: "team", delete: "team" }; |
| 30 |
| 31 | export interface FakeCollectionOptions { |
| 32 | destructiveAllowed?: boolean; |
| 33 | /** Records created here belong to this actor (a site tool's visitor). */ |
| 34 | createdBy?: ColineActorRef; |
| 35 | /** The collection's declared visitor rules; used when `actor` is a visitor. */ |
| 36 | rules?: CollectionAccess; |
| 37 | /** The collection's zod schema; visitor writes must match it, as on Coline. */ |
| 38 | schema?: { safeParse(data: unknown): { success: boolean; error?: { message: string } } }; |
| 39 | } |
| 40 |
| 41 | /** |
| 42 | * The in-memory collection, with the same access semantics as the server: |
| 43 | * members and app logic use the per-record ACL, visitors use the |
| 44 | * collection's declared rules and only the operations a site page may call. |
| 45 | */ |
| 46 | export function createFakeCollection<T>( |
| 47 | state: TestWorkspaceState, |
| 48 | name: string, |
| 49 | actor: ColineActorRef, |
| 50 | installId: string, |
| 51 | options: FakeCollectionOptions = {}, |
| 52 | ): ColineCollection<T> { |
| 53 | if (!state.records.has(name)) state.records.set(name, new Map()); |
| 54 | const records = state.records.get(name)! as Map<string, Row>; |
| 55 | const visitor = actor.kind === "visitor" ? actor : null; |
| 56 | const rules = options.rules ?? TEAM_ONLY; |
| 57 | const creator = options.createdBy ?? actor; |
| 58 | const fail = (code: string, message: string): never => { |
| 59 | throw Object.assign(new Error(message), { code }); |
| 60 | }; |
| 61 | const visitorOnly = (operation: string): never => |
| 62 | fail("unavailable_to_visitors", `Site visitors cannot call "${operation}".`); |
| 63 | const assertShape = (data: unknown) => { |
| 64 | if (!visitor || !options.schema) return; |
| 65 | const result = options.schema.safeParse(data); |
| 66 | if (!result.success) fail("record_invalid", `This record doesn't match the collection's schema. ${result.error?.message ?? ""}`); |
| 67 | }; |
| 68 | const visible = (row: Row) => |
| 69 | visitor |
| 70 | ? canVisitorAccess(rules.read, visitor, rules.read === "owner" ? row.createdBy : null) && |
| 71 | (rules.read !== "owner" || sameActor(row.createdBy, visitor)) |
| 72 | : canAccessRecord(row.access, row.createdBy, actor, "read"); |
| 73 | const wrap = (row: Row) => structuredClone(row) as unknown as ColineRecordEnvelope<T>; |
| 74 | const changed = () => { |
| 75 | state.recordRevisions.set(name, (state.recordRevisions.get(name) ?? 0) + 1); |
| 76 | for (const listener of state.realtimeListeners.get("coline.records.changed") ?? []) |
| 77 | listener({ event: "coline.records.changed", data: null }); |
| 78 | }; |
| 79 | function writable(id: string, expectedVersion?: number, action: "update" | "delete" | "manage" = "update") { |
| 80 | const row = records.get(id); |
| 81 | if (!row || !visible(row)) return fail("record_not_found", "Record not found."); |
| 82 | const permitted = visitor |
| 83 | ? action !== "manage" && canVisitorAccess(rules[action], visitor, row.createdBy) |
| 84 | : canAccessRecord(row.access, row.createdBy, actor, action === "manage" ? "manage" : "write"); |
| 85 | if (!permitted) return fail("record_forbidden", "You cannot change this record."); |
| 86 | if (expectedVersion !== undefined && row.version !== expectedVersion) |
| 87 | return fail("record_conflict", "This record changed. Refresh before saving again."); |
| 88 | return row; |
| 89 | } |
| 90 | function matching(where: unknown) { |
| 91 | return [...records.values()].filter((row) => visible(row) && matchesRecordWhere(row.data, where)); |
| 92 | } |
| 93 | function query(input?: ColineRecordQuery<T>) { |
| 94 | const rows = matching(input?.where); |
| 95 | const sorts = normalizeRecordSort(input); |
| 96 | if (sorts.length > 3) return fail("invalid_query", "Sort by at most three fields."); |
| 97 | rows.sort((a, b) => compareRecords(a, b, sorts)); |
| 98 | const offset = Number(input?.cursor ?? 0), |
| 99 | limit = input?.limit ?? 50; |
| 100 | if (!Number.isSafeInteger(offset) || offset < 0) |
| 101 | return fail("invalid_cursor", "Invalid collection cursor."); |
| 102 | if (!Number.isInteger(limit) || limit < 1 || limit > MAX_PAGE) |
| 103 | return fail("invalid_query", `Record limit must be 1–${MAX_PAGE}.`); |
| 104 | return { |
| 105 | records: rows.slice(offset, offset + limit).map(wrap), |
| 106 | nextCursor: rows.length > offset + limit ? String(offset + limit) : null, |
| 107 | }; |
| 108 | } |
| 109 | function insertRow(data: unknown, insertOptions?: { id?: string | undefined; access?: Row["access"] | undefined }) { |
| 110 | if (visitor) { |
| 111 | if (!canVisitorAccess(rules.create, visitor, null)) |
| 112 | return fail("record_forbidden", "Visitors cannot add records here."); |
| 113 | if (insertOptions?.id || insertOptions?.access) |
| 114 | return fail("unavailable_to_visitors", "Visitors cannot choose record ids or access."); |
| 115 | assertShape(data); |
| 116 | } |
| 117 | const id = insertOptions?.id ?? state.nextRecordId(); |
| 118 | const existing = records.get(id); |
| 119 | if (existing) { |
| 120 | if ( |
| 121 | !sameActor(existing.createdBy, creator) || |
| 122 | JSON.stringify(existing.data) !== JSON.stringify(data) || |
| 123 | JSON.stringify(existing.access) !== |
| 124 | JSON.stringify(insertOptions?.access ?? DEFAULT_RECORD_ACCESS) |
| 125 | ) |
| 126 | return fail("record_identity_conflict", "Record identity already in use."); |
| 127 | return existing; |
| 128 | } |
| 129 | const now = new Date().toISOString(); |
| 130 | const row: Row = { |
| 131 | id, |
| 132 | appId: "app_test", |
| 133 | installId, |
| 134 | collection: name, |
| 135 | createdBy: structuredClone(creator), |
| 136 | createdAt: now, |
| 137 | updatedAt: now, |
| 138 | version: 1, |
| 139 | access: structuredClone(insertOptions?.access ?? DEFAULT_RECORD_ACCESS), |
| 140 | data: structuredClone(data) as Record<string, unknown>, |
| 141 | }; |
| 142 | records.set(id, row); |
| 143 | return row; |
| 144 | } |
| 145 | function patchRow(row: Row, patch: unknown) { |
| 146 | row.data = { ...row.data, ...(structuredClone(patch) as Record<string, unknown>) }; |
| 147 | row.version++; |
| 148 | row.updatedAt = new Date().toISOString(); |
| 149 | } |
| 150 | function atomically<R>(work: () => R): R { |
| 151 | const snapshot = new Map([...records].map(([id, row]) => [id, structuredClone(row)])); |
| 152 | try { |
| 153 | const result = work(); |
| 154 | changed(); |
| 155 | return result; |
| 156 | } catch (error) { |
| 157 | records.clear(); |
| 158 | for (const [id, row] of snapshot) records.set(id, row); |
| 159 | throw error; |
| 160 | } |
| 161 | } |
| 162 | function applyBatch(operations: Array<ColineRecordBatchOperation<T>>) { |
| 163 | if (operations.length > MAX_BATCH) return fail("batch_too_large", `Batches are limited to ${MAX_BATCH} operations.`); |
| 164 | if (operations.some((operation) => operation.op === "delete") && options.destructiveAllowed === false) |
| 165 | return fail("effect_ceiling_exceeded", "Batches with deletes need a destructive effect."); |
| 166 | return atomically(() => |
| 167 | operations.map((operation) => { |
| 168 | if (operation.op === "insert") return wrap(insertRow(operation.data, operation)); |
| 169 | if (operation.op === "update") { |
| 170 | const row = writable(operation.id, operation.expectedVersion); |
| 171 | patchRow(row, operation.data); |
| 172 | return wrap(row); |
| 173 | } |
| 174 | writable(operation.id, operation.expectedVersion, "delete"); |
| 175 | records.delete(operation.id); |
| 176 | return null; |
| 177 | }), |
| 178 | ); |
| 179 | } |
| 180 | return { |
| 181 | insert: async (data, insertOptions) => { |
| 182 | const row = insertRow(data, insertOptions); |
| 183 | changed(); |
| 184 | return wrap(row); |
| 185 | }, |
| 186 | get: async (id) => { |
| 187 | const row = records.get(id); |
| 188 | return row && visible(row) ? wrap(row) : null; |
| 189 | }, |
| 190 | update: async (id, patch, writeOptions) => { |
| 191 | const row = writable(id, writeOptions?.expectedVersion); |
| 192 | assertShape({ ...(row.data as Record<string, unknown>), ...(patch as Record<string, unknown>) }); |
| 193 | patchRow(row, patch); |
| 194 | changed(); |
| 195 | return wrap(row); |
| 196 | }, |
| 197 | delete: async (id, writeOptions) => { |
| 198 | writable(id, writeOptions?.expectedVersion, "delete"); |
| 199 | records.delete(id); |
| 200 | changed(); |
| 201 | }, |
| 202 | setAccess: async (id, access, writeOptions) => { |
| 203 | if (visitor) return visitorOnly("storage.records.setAccess"); |
| 204 | const row = writable(id, writeOptions?.expectedVersion, "manage"); |
| 205 | row.access = structuredClone(access); |
| 206 | row.version++; |
| 207 | row.updatedAt = new Date().toISOString(); |
| 208 | changed(); |
| 209 | return wrap(row); |
| 210 | }, |
| 211 | query: async (input) => query(input), |
| 212 | sync: async (input, revision) => { |
| 213 | const current = state.recordRevisions.get(name) ?? 0; |
| 214 | return { |
| 215 | revision: current, |
| 216 | ...(revision === current ? { records: null, nextCursor: null } : query(input)), |
| 217 | }; |
| 218 | }, |
| 219 | count: async (where) => ({ count: matching(where).length }), |
| 220 | aggregate: async (input) => { |
| 221 | if (visitor) return visitorOnly("storage.records.aggregate"); |
| 222 | if ((input.groupBy?.length ?? 0) > 3) return fail("invalid_query", "Group by at most three fields."); |
| 223 | if (Object.keys(input.metrics).length === 0) return fail("invalid_query", "Name at least one metric."); |
| 224 | return aggregateRecords(matching(input.where) as Array<{ data: T }>, input); |
| 225 | }, |
| 226 | batch: async (operations) => |
| 227 | visitor ? visitorOnly("storage.records.batch") : { results: applyBatch(operations) }, |
| 228 | insertMany: async (rows) => |
| 229 | visitor |
| 230 | ? visitorOnly("storage.records.insertMany") |
| 231 | : { |
| 232 | records: applyBatch(rows.map((row) => ({ op: "insert" as const, ...row }))) as Array< |
| 233 | ColineRecordEnvelope<T> |
| 234 | >, |
| 235 | }, |
| 236 | updateMany: async (input) => |
| 237 | visitor |
| 238 | ? visitorOnly("storage.records.updateMany") |
| 239 | : atomically(() => { |
| 240 | const rows = matching(input.where).filter((row) => |
| 241 | canAccessRecord(row.access, row.createdBy, actor, "write"), |
| 242 | ); |
| 243 | if (rows.length > MAX_BULK) return fail("bulk_too_large", `Bulk updates are limited to ${MAX_BULK} records.`); |
| 244 | for (const row of rows) patchRow(row, input.data); |
| 245 | return { count: rows.length }; |
| 246 | }), |
| 247 | deleteMany: async (input) => |
| 248 | visitor |
| 249 | ? visitorOnly("storage.records.deleteMany") |
| 250 | : atomically(() => { |
| 251 | const rows = matching(input.where).filter((row) => |
| 252 | canAccessRecord(row.access, row.createdBy, actor, "write"), |
| 253 | ); |
| 254 | if (rows.length > MAX_BULK) return fail("bulk_too_large", `Bulk deletes are limited to ${MAX_BULK} records.`); |
| 255 | for (const row of rows) records.delete(row.id); |
| 256 | return { count: rows.length }; |
| 257 | }), |
| 258 | }; |
| 259 | } |
| 260 |