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