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