|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { describe, it, expect, vi } from 'vitest'; |
| 4 | +import { SeedLoaderService } from './seed-loader'; |
| 5 | +import type { IDataEngine, IMetadataService } from '@objectstack/spec/contracts'; |
| 6 | + |
| 7 | +/** |
| 8 | + * #3433 — a curated seed is a snapshot of ESTABLISHED facts (a project already |
| 9 | + * `completed`, an opportunity `closed_won`), not a record walking its lifecycle. |
| 10 | + * When an object declares `state_machine.initialStates` (#3165), the write path |
| 11 | + * enforces that INSERTS are born in an initial state — which silently rejects |
| 12 | + * every mid-lifecycle seed row and cascades its master-detail children ("installed |
| 13 | + * but no data"). So SeedLoaderService marks its writes `seedReplay`, and the engine |
| 14 | + * skips the state_machine rule for them. |
| 15 | + * |
| 16 | + * The engine that actually enforces this lives in @objectstack/objectql, which |
| 17 | + * DEPENDS ON this package — importing it back would cycle. So this mock engine |
| 18 | + * reproduces the exact insert-time guard (reject a state ∉ initialStates UNLESS the |
| 19 | + * write carries `context.seedReplay`) to regression-test the loader's end of the |
| 20 | + * contract in isolation. Revert the `seedReplay` flag in `SEED_OPTIONS` and both |
| 21 | + * cases below go red — 4 of 5 rows rejected, the flag absent from the writes. |
| 22 | + */ |
| 23 | + |
| 24 | +function createLogger() { |
| 25 | + return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; |
| 26 | +} |
| 27 | + |
| 28 | +const PROJECT = { |
| 29 | + name: 'showcase_project', |
| 30 | + fields: { |
| 31 | + name: { type: 'text' }, |
| 32 | + status: { type: 'select' }, |
| 33 | + }, |
| 34 | + validations: [ |
| 35 | + { |
| 36 | + type: 'state_machine', |
| 37 | + name: 'project_status_flow', |
| 38 | + field: 'status', |
| 39 | + initialStates: ['planned'], |
| 40 | + transitions: { |
| 41 | + planned: ['active', 'cancelled'], |
| 42 | + active: ['on_hold', 'completed', 'cancelled'], |
| 43 | + }, |
| 44 | + message: 'Invalid project status transition.', |
| 45 | + }, |
| 46 | + ], |
| 47 | +}; |
| 48 | + |
| 49 | +/** Reproduces the objectql insert-time initialStates guard, honoring the #3433 exemption. */ |
| 50 | +function enforceInitialStates(data: Record<string, unknown>, opts: any): void { |
| 51 | + if (opts?.context?.seedReplay === true) return; // #3433 exemption |
| 52 | + const sm = PROJECT.validations[0]; |
| 53 | + const value = data[sm.field]; |
| 54 | + if (value == null || value === '') return; |
| 55 | + if (!sm.initialStates.includes(String(value))) { |
| 56 | + const err: any = new Error( |
| 57 | + `invalid_initial_state: ${sm.field} '${String(value)}' not in [${sm.initialStates.join(', ')}]`, |
| 58 | + ); |
| 59 | + err.code = 'VALIDATION_FAILED'; |
| 60 | + throw err; |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +function createEnforcingEngine(): { engine: IDataEngine; store: Record<string, any[]> } { |
| 65 | + const store: Record<string, any[]> = {}; |
| 66 | + let idCounter = 0; |
| 67 | + const engine = { |
| 68 | + find: vi.fn(async (objectName: string, query?: any) => { |
| 69 | + let rows = store[objectName] || []; |
| 70 | + if (query?.where) { |
| 71 | + rows = rows.filter((r) => Object.entries(query.where).every(([k, v]) => r[k] === v)); |
| 72 | + } |
| 73 | + if (typeof query?.limit === 'number') rows = rows.slice(0, query.limit); |
| 74 | + return rows; |
| 75 | + }), |
| 76 | + findOne: vi.fn(async () => null), |
| 77 | + // Per-row partial-success path the seed loader prefers (framework#3172): |
| 78 | + // one verdict per row, so a rejected row is culled, not thrown as a batch. |
| 79 | + insertMany: vi.fn(async (objectName: string, rows: any[], opts: any) => |
| 80 | + rows.map((r) => { |
| 81 | + try { |
| 82 | + enforceInitialStates(r, opts); |
| 83 | + const record = { id: `gen-${++idCounter}`, ...r }; |
| 84 | + (store[objectName] ||= []).push(record); |
| 85 | + return { ok: true, record }; |
| 86 | + } catch (error) { |
| 87 | + return { ok: false, error }; |
| 88 | + } |
| 89 | + }), |
| 90 | + ), |
| 91 | + insert: vi.fn(async (objectName: string, data: any, opts: any) => { |
| 92 | + const rows = Array.isArray(data) ? data : [data]; |
| 93 | + const written = rows.map((r) => { |
| 94 | + enforceInitialStates(r, opts); // throws on violation (whole-array semantics) |
| 95 | + const record = { id: `gen-${++idCounter}`, ...r }; |
| 96 | + (store[objectName] ||= []).push(record); |
| 97 | + return record; |
| 98 | + }); |
| 99 | + return Array.isArray(data) ? written : written[0]; |
| 100 | + }), |
| 101 | + update: vi.fn(async (objectName: string, data: any) => { |
| 102 | + const rows = store[objectName] || []; |
| 103 | + const idx = rows.findIndex((r) => r.id === data.id); |
| 104 | + if (idx >= 0) { |
| 105 | + rows[idx] = { ...rows[idx], ...data }; |
| 106 | + return rows[idx]; |
| 107 | + } |
| 108 | + return data; |
| 109 | + }), |
| 110 | + delete: vi.fn(async () => ({ deleted: 1 })), |
| 111 | + count: vi.fn(async (o: string) => (store[o] || []).length), |
| 112 | + aggregate: vi.fn(async () => []), |
| 113 | + } as unknown as IDataEngine; |
| 114 | + return { engine, store }; |
| 115 | +} |
| 116 | + |
| 117 | +function createMetadata(): IMetadataService { |
| 118 | + return { |
| 119 | + getObject: vi.fn(async (name: string) => (name === PROJECT.name ? PROJECT : undefined)), |
| 120 | + listObjects: vi.fn(async () => [PROJECT]), |
| 121 | + register: vi.fn(async () => {}), |
| 122 | + get: vi.fn(async (_t: string, name: string) => (name === PROJECT.name ? PROJECT : undefined)), |
| 123 | + list: vi.fn(async () => []), |
| 124 | + unregister: vi.fn(async () => {}), |
| 125 | + exists: vi.fn(async () => false), |
| 126 | + listNames: vi.fn(async () => []), |
| 127 | + } as unknown as IMetadataService; |
| 128 | +} |
| 129 | + |
| 130 | +// Mirrors the AppPlugin inline-seed config (defaultMode upsert, multiPass on). |
| 131 | +const CONFIG = { |
| 132 | + dryRun: false, |
| 133 | + haltOnError: false, |
| 134 | + multiPass: true, |
| 135 | + defaultMode: 'upsert', |
| 136 | + batchSize: 1000, |
| 137 | + transaction: false, |
| 138 | +} as any; |
| 139 | + |
| 140 | +// A seed that deliberately spans the lifecycle: 1 born-initial + 4 mid-lifecycle, |
| 141 | +// exactly like the showcase project board (one card per Kanban column). |
| 142 | +const SEED = [ |
| 143 | + { |
| 144 | + object: 'showcase_project', |
| 145 | + externalId: 'name', |
| 146 | + mode: 'upsert', |
| 147 | + env: ['prod', 'dev', 'test'], |
| 148 | + records: [ |
| 149 | + { name: 'Mobile App', status: 'planned' }, |
| 150 | + { name: 'Website Relaunch', status: 'active' }, |
| 151 | + { name: 'Data Platform', status: 'active' }, |
| 152 | + { name: 'Compliance Audit', status: 'on_hold' }, |
| 153 | + { name: 'Legacy Sunset', status: 'completed' }, |
| 154 | + ], |
| 155 | + }, |
| 156 | +] as any[]; |
| 157 | + |
| 158 | +describe('seed loader — state_machine initialStates exemption (#3433)', () => { |
| 159 | + it('inserts every mid-lifecycle row on a fresh DB (no initialStates rejection)', async () => { |
| 160 | + const { engine, store } = createEnforcingEngine(); |
| 161 | + const result = await new SeedLoaderService(engine, createMetadata(), createLogger()).load({ |
| 162 | + seeds: SEED, |
| 163 | + config: CONFIG, |
| 164 | + }); |
| 165 | + |
| 166 | + expect(result.success).toBe(true); |
| 167 | + expect(result.summary.totalErrored).toBe(0); |
| 168 | + expect(result.summary.totalInserted).toBe(5); |
| 169 | + expect(store.showcase_project).toHaveLength(5); |
| 170 | + // The exact spread the showcase board needs — proof no state was dropped. |
| 171 | + expect(store.showcase_project.map((r) => r.status).sort()).toEqual([ |
| 172 | + 'active', |
| 173 | + 'active', |
| 174 | + 'completed', |
| 175 | + 'on_hold', |
| 176 | + 'planned', |
| 177 | + ]); |
| 178 | + }); |
| 179 | + |
| 180 | + it('threads seedReplay into every project write (the flag the engine keys off)', async () => { |
| 181 | + const { engine } = createEnforcingEngine(); |
| 182 | + await new SeedLoaderService(engine, createMetadata(), createLogger()).load({ |
| 183 | + seeds: SEED, |
| 184 | + config: CONFIG, |
| 185 | + }); |
| 186 | + |
| 187 | + // Whichever write path the loader took (insertMany batch or a per-row |
| 188 | + // fallback), its options must carry the exemption flag — that is what the |
| 189 | + // engine reads to skip the state_machine rule. |
| 190 | + const writeCalls = [ |
| 191 | + ...(engine.insertMany as any).mock.calls, |
| 192 | + ...(engine.insert as any).mock.calls, |
| 193 | + ].filter(([obj]) => obj === 'showcase_project'); |
| 194 | + expect(writeCalls.length).toBeGreaterThan(0); |
| 195 | + for (const call of writeCalls) { |
| 196 | + expect(call[2]?.context?.seedReplay).toBe(true); |
| 197 | + } |
| 198 | + }); |
| 199 | +}); |
0 commit comments