Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

test-minified-db.mjs

265 lines11.0 KB

1// Consumer-build contract: public Collection/query behavior, error names, and
2// index metadata have the same observations after identifier minification.
3// Authority: the corresponding source-facing tests in packages/db/tests for
4// queryOnce, live queries, collection events/indexes, and errors. The model is
5// a plain array filter/sort/projection over one initial and one updated source
6// snapshot; the driver invokes only the bundled public entry. This fixed slice
7// does not replace the generated oracles or framework adapter conformance.
8// The --calibrate modes are hostile controls for this check, not CI jobs.
9import assert from 'node:assert/strict'
10import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'
11import path from 'node:path'
12import { fileURLToPath, pathToFileURL } from 'node:url'
13import { build } from 'esbuild'
14​
15const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
16const mode = process.argv[2]
17assert.ok(
18 mode === undefined ||
19 mode === '--calibrate-error-name' ||
20 mode === '--calibrate-public-member' ||
21 mode === '--calibrate-output-shape',
22 `Unknown mode: ${mode}`,
24​
25const dbNodeModules = path.join(root, 'packages/db/node_modules')
26const dbNodeModulesInfo = await stat(dbNodeModules).catch((error) => {
27 if (error.code !== 'ENOENT') throw error
28 return null
29})
30assert.ok(
31 dbNodeModulesInfo?.isDirectory(),
32 'Install workspace dependencies before running test:minified-db',
34const bundleDirectory = await mkdtemp(path.join(dbNodeModules, '.minified-db-'))
35const bundlePath = path.join(bundleDirectory, 'index.mjs')
36​
37const aliasIvm = {
38 name: 'inline-db-ivm',
39 setup(builder) {
40 builder.onResolve({ filter: /^@tanstack\/db-ivm$/ }, () => ({
41 path: path.join(root, 'packages/db-ivm/src/index.ts'),
42 }))
43 },
45​
46const errorNameMutant = {
47 name: 'error-name-mutant',
48 setup(builder) {
49 builder.onLoad(
50 { filter: /packages\/db\/src\/errors\.ts$/ },
51 async ({ path: file }) => {
52 const source = await readFile(file, 'utf8')
53 const original = 'this.name = `CollectionConfigurationError`'
54 assert.equal(
55 source.split(original).length,
56 2,
57 'mutant target exists once',
58 )
59 return {
60 contents: source.replace(original, 'this.name = new.target.name'),
61 loader: 'ts',
62 }
63 },
64 )
65 },
67​
68// These are the public names currently assigned by the exported error classes.
69// Subclasses often deliberately inherit their family's name. Abort errors
70// intentionally use the platform AbortError name. Keep the export inventory
71// check below so a newly exported class must receive an explicit expectation.
72const errorGroups = {
73 TanStackDBError: `TanStackDBError`,
74 NonRetriableError: `NonRetriableError`,
75 SchemaValidationError: `SchemaValidationError`,
76 DuplicateDbInstanceError: `DuplicateDbInstanceError`,
77 CollectionConfigurationError: `CollectionConfigurationError CollectionRequiresConfigError CollectionRequiresSyncConfigError InvalidSchemaError SchemaMustBeSynchronousError`,
78 InvalidSyncPersistenceCapabilityError: `InvalidSyncPersistenceCapabilityError`,
79 CollectionStateError: `CollectionStateError CollectionInErrorStateError InvalidCollectionStatusTransitionError CollectionIsInErrorStateError NegativeActiveSubscribersError LiveQueryObserverDisposedError LiveQueryWindowControllerDisposedError`,
80 CollectionOperationError: `CollectionOperationError UndefinedKeyError InvalidKeyError DuplicateKeyError DuplicateKeySyncError MissingUpdateArgumentError NoKeysPassedToUpdateError UpdateKeyNotFoundError KeyUpdateNotAllowedError NoKeysPassedToDeleteError DeleteKeyNotFoundError`,
81 MissingHandlerError: `MissingHandlerError MissingInsertHandlerError MissingUpdateHandlerError MissingDeleteHandlerError`,
82 TransactionError: `TransactionError MissingMutationFunctionError TransactionNotPendingMutateError TransactionAlreadyCompletedRollbackError TransactionNotPendingCommitError NoPendingSyncTransactionWriteError SyncTransactionAlreadyCommittedWriteError NoPendingSyncTransactionCommitError SyncTransactionAlreadyCommittedError`,
83 QueueCapacityExceededError: `QueueCapacityExceededError`,
84 QueueDisposedError: `QueueDisposedError`,
85 ThrottleCallDroppedError: `ThrottleCallDroppedError`,
86 DebounceCallDroppedError: `DebounceCallDroppedError`,
87 OnMutateMustBeSynchronousError: `OnMutateMustBeSynchronousError`,
88 QueryBuilderError: `QueryBuilderError OnlyOneSourceAllowedError SubQueryMustHaveFromClauseError InvalidSourceError InvalidSourceTypeError JoinConditionMustBeEqualityError QueryMustHaveFromClauseError InvalidWhereExpressionError`,
89 QueryCompilationError: `QueryCompilationError DistinctRequiresSelectError FnSelectWithGroupByError UnsupportedFnSelectResultError UnsupportedRootScalarSelectError HavingRequiresGroupByError LimitOffsetRequireOrderByError CollectionInputNotFoundError DuplicateAliasInSubqueryError UnsupportedFromTypeError UnknownExpressionTypeError EmptyReferencePathError UnknownFunctionError JoinCollectionNotFoundError MissingAliasInputsError SetWindowRequiresOrderByError`,
90 UnsafeAliasPathError: `UnsafeAliasPathError`,
91 JoinError: `JoinError UnsupportedJoinTypeError InvalidJoinConditionSameSourceError InvalidJoinConditionSourceMismatchError InvalidJoinConditionLeftSourceError InvalidJoinConditionRightSourceError InvalidJoinCondition UnsupportedJoinSourceTypeError`,
92 GroupByError: `GroupByError NonAggregateExpressionNotInGroupByError UnsupportedAggregateFunctionError AggregateFunctionNotInSelectError UnknownHavingExpressionTypeError`,
93 StorageError: `StorageError SerializationError`,
94 LocalStorageCollectionError: `LocalStorageCollectionError StorageKeyRequiredError InvalidStorageDataFormatError InvalidStorageObjectFormatError`,
95 SyncCleanupError: `SyncCleanupError`,
96 AbortError: `SyncTransactionAbortedError CollectionPreloadAbortedError LoadSubsetOperationAbortedError`,
97 QueryOptimizerError: `QueryOptimizerError CannotCombineEmptyExpressionListError`,
98 SetWindowReentrancyError: `SetWindowReentrancyError`,
99 UnhashableQueryIRError: `UnhashableQueryIRError`,
101​
102function checkErrorNames(db) {
103 const expected = new Map(
104 Object.entries(errorGroups).flatMap(([name, exports]) =>
105 exports.split(' ').map((exportName) => [exportName, name]),
106 ),
107 )
108 const actual = Object.entries(db)
109 .filter(
110 ([, value]) =>
111 typeof value === 'function' && value.prototype instanceof Error,
112 )
113 .map(([name]) => name)
114 .sort()
115 assert.deepEqual(
116 actual,
117 [...expected.keys()].sort(),
118 'every exported error has a checked name',
119 )
120​
121 for (const [exportName, name] of expected) {
122 const args =
123 exportName === 'MissingAliasInputsError' ? [[]] : ['insert', [], []]
124 const error = new db[exportName](...args)
125 assert.equal(error.name, name, `${exportName}.name`)
126 assert.ok(error instanceof Error, `${exportName} is an Error`)
127 }
128 return expected.size
130​
131async function checkCollectionsAndQueries(db) {
132 const initial = [
133 { id: 1, name: 'Ada', age: 28 },
134 { id: 2, name: 'Bea', age: 21 },
135 { id: 3, name: 'Cal', age: 35 },
136 ]
137 let sync
138 const source = db.createCollection({
139 id: 'minified-public-source',
140 getKey: (row) => row.id,
141 defaultIndexType: db.BasicIndex,
142 sync: {
143 sync(actions) {
144 sync = actions
145 actions.begin()
146 for (const value of initial) actions.write({ type: 'insert', value })
147 actions.commit()
148 actions.markReady()
149 },
150 },
151 })
152 let live
153 try {
154 const indexEvents = []
155 source.on('index:added', (event) => indexEvents.push(event))
156 const index = source.createIndex((row) => row.age, {
157 indexType: db.BasicIndex,
158 name: 'by-age',
159 })
160 assert.equal(
161 typeof source.getIndexMetadata,
162 'function',
163 'public index metadata method',
164 )
165 const metadata = source.getIndexMetadata()
166 assert.equal(metadata.length, 1)
167 assert.equal(metadata[0].indexId, index.id)
168 assert.equal(metadata[0].name, 'by-age')
169 assert.equal(metadata[0].resolver.kind, 'constructor')
170 assert.equal(metadata[0].resolver.name, 'BasicIndex')
171 assert.equal(indexEvents.length, 1)
172 assert.equal(indexEvents[0].index.signature, metadata[0].signature)
173 assert.equal(indexEvents[0].index.name, 'by-age')
174 assert.equal(indexEvents[0].index.resolver.name, 'BasicIndex')
175​
176 await source.preload()
177 assert.deepEqual(
178 [...source.values()].map((row) => row.id).sort(),
179 [1, 2, 3],
180 )
181​
182 // A small conformance and oracle slice: expected rows come from a plain
183 // array filter/sort/projection, independent of the query/index machinery.
184 const expected = (rows) =>
185 rows
186 .filter((row) => row.age > 25)
187 .sort((a, b) => a.age - b.age)
188 .map(({ id, name }) => ({ id, name }))
189 const query = (q) =>
190 q
191 .from({ user: source })
192 .where(({ user }) => db.gt(user.age, 25))
193 .orderBy(({ user }) => user.age, 'asc')
194 .select(({ user }) => ({ id: user.id, name: user.name }))
195 const selectedRows = (rows) =>
196 rows.map((row) => {
197 const selected = { ...row }
198 delete selected.$synced
199 delete selected.$origin
200 delete selected.$key
201 delete selected.$collectionId
202 return selected
203 })
204 const queryRows = [...(await db.queryOnce(query))]
205 if (mode === '--calibrate-output-shape') {
206 queryRows[0] = { ...queryRows[0], age: 28 }
207 }
208 assert.deepEqual(selectedRows(queryRows), expected(initial))
209​
210 live = db.createLiveQueryCollection(query)
211 await live.preload()
212 assert.deepEqual(selectedRows([...live.values()]), expected(initial))
213​
214 const changed = [
215 { id: 1, name: 'Ada', age: 28 },
216 { id: 2, name: 'Bea', age: 31 },
217 { id: 3, name: 'Cal', age: 35 },
218 ]
219 sync.begin()
220 sync.write({ type: 'update', value: changed[1] })
221 await sync.commit()
222 assert.deepEqual(selectedRows([...live.values()]), expected(changed))
223 assert.deepEqual(selectedRows(await db.queryOnce(query)), expected(changed))
224 } finally {
225 if (live) await live.cleanup()
226 await source.cleanup()
227 }
229​
230try {
231 const bundle = await build({
232 absWorkingDir: root,
233 entryPoints: [path.join(root, 'packages/db/src/index.ts')],
234 outfile: bundlePath,
235 bundle: true,
236 minify: true,
237 format: 'esm',
238 target: 'es2020',
239 platform: 'node',
240 metafile: true,
241 external: ['@standard-schema/spec', '@tanstack/pacer-lite'],
242 plugins: [
243 aliasIvm,
244 ...(mode === '--calibrate-error-name' ? [errorNameMutant] : []),
245 ],
246 ...(mode === '--calibrate-public-member'
247 ? { mangleProps: /^getIndexMetadata$/ }
248 : {}),
249 logLevel: 'silent',
250 })
251 assert.ok(
252 Object.keys(bundle.metafile.inputs).some((input) =>
253 input.includes('packages/db-ivm/src/'),
254 ),
255 'db-ivm is inlined into the minified bundle',
256 )
257 const db = await import(pathToFileURL(bundlePath).href)
258 const errorCount = checkErrorNames(db)
259 await checkCollectionsAndQueries(db)
260 console.log(
261 `Minified public API: ${errorCount} error names, index metadata, query rows, live updates OK`,
262 )
263} finally {
264 await rm(bundleDirectory, { recursive: true, force: true })