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 CollectionHasSubscribersError CollectionReloadCrashedError CollectionReloadDuringSyncEntryError`,
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 DuplicateTransactionIdError TransactionNotPendingCommitError NoPendingSyncTransactionWriteError SyncTransactionAlreadyCommittedWriteError SyncRowReusedWithoutPreviousValueError NoPendingSyncTransactionCommitError SyncTransactionAlreadyCommittedError SyncQueueInvariantError`,
88 PacedTransactionManualCommitError: `PacedTransactionManualCommitError`,
89 QueueCapacityExceededError: `QueueCapacityExceededError`,
90 QueueDisposedError: `QueueDisposedError`,
91 ThrottleCallDroppedError: `ThrottleCallDroppedError`,
92 DebounceCallDroppedError: `DebounceCallDroppedError`,
93 OnMutateMustBeSynchronousError: `OnMutateMustBeSynchronousError`,
94 QueryBuilderError: `QueryBuilderError OnlyOneSourceAllowedError SubQueryMustHaveFromClauseError InvalidSourceError InvalidSourceTypeError JoinConditionMustBeEqualityError QueryMustHaveFromClauseError InvalidWhereExpressionError IncludeOperatorRequiredError`,
95 QueryCompilationError: `QueryCompilationError DistinctRequiresSelectError FnSelectWithGroupByError UnsupportedFnSelectResultError UnsupportedRootScalarSelectError HavingRequiresGroupByError LimitOffsetRequireOrderByError CollectionInputNotFoundError UnsupportedFromTypeError UnknownExpressionTypeError EmptyReferencePathError UnknownFunctionError JoinCollectionNotFoundError MissingAliasInputsError SetWindowRequiresOrderByError SetWindowFindOneLimitError GroupingOperatorRequiredError`,
96 UnsafeAliasPathError: `UnsafeAliasPathError`,
97 JoinError: `JoinError UnsupportedJoinTypeError InvalidJoinConditionSameSourceError InvalidJoinConditionSourceMismatchError InvalidJoinConditionLeftSourceError InvalidJoinConditionRightSourceError InvalidJoinCondition UnsupportedJoinSourceTypeError`,
98 GroupByError: `GroupByError NonAggregateExpressionNotInGroupByError UnsupportedAggregateFunctionError AggregateFunctionNotInSelectError UnknownHavingExpressionTypeError`,
99 StorageError: `StorageError SerializationError`,
100 LocalStorageCollectionError: `LocalStorageCollectionError StorageKeyRequiredError InvalidStorageDataFormatError InvalidStorageObjectFormatError`,
101 DatabaseRequiredError: `DatabaseRequiredError`,
102 GetKeyRequiredError: `GetKeyRequiredError`,
103 NameRequiredError: `NameRequiredError`,
104 ObjectStoreNotFoundError: `ObjectStoreNotFoundError`,
105 SyncCleanupError: `SyncCleanupError`,
106 AbortError: `SyncTransactionAbortedError CollectionPreloadAbortedError LoadSubsetOperationAbortedError`,
107 QueryOptimizerError: `QueryOptimizerError CannotCombineEmptyExpressionListError`,
108 SetWindowReentrancyError: `SetWindowReentrancyError`,
109 UnhashableQueryIRError: `UnhashableQueryIRError`,
110 SourceCollectionIdReuseError: `SourceCollectionIdReuseError`,
111 InvalidPoolOptionError: `InvalidPoolOptionError`,
112}
113
114function checkErrorNames(db) {
115 const expected = new Map(
116 Object.entries(errorGroups).flatMap(([name, exports]) =>
117 exports.split(' ').map((exportName) => [exportName, name]),
118 ),
119 )
120 const actual = Object.entries(db)
121 .filter(
122 ([, value]) =>
123 typeof value === 'function' && value.prototype instanceof Error,
124 )
125 .map(([name]) => name)
126 .sort()
127 assert.deepEqual(
128 actual,
129 [...expected.keys()].sort(),
130 'every exported error has a checked name',
131 )
132
133 for (const [exportName, name] of expected) {
134 const args =
135 exportName === 'MissingAliasInputsError' ? [[]] : ['insert', [], []]
136 const error = new db[exportName](...args)
137 assert.equal(error.name, name, `${exportName}.name`)
138 assert.ok(error instanceof Error, `${exportName} is an Error`)
139 }
140 return expected.size
141}
142
143async function checkCollectionsAndQueries(db) {
144 const initial = [
145 { id: 1, name: 'Ada', age: 28 },
146 { id: 2, name: 'Bea', age: 21 },
147 { id: 3, name: 'Cal', age: 35 },
148 ]
149 let sync
150 const source = db.createCollection({
151 id: 'minified-public-source',
152 getKey: (row) => row.id,
153 defaultIndexType: db.BasicIndex,
154 sync: {
155 sync(actions) {
156 sync = actions
157 actions.begin()
158 for (const value of initial) actions.write({ type: 'insert', value })
159 actions.commit()
160 actions.markReady()
161 },
162 },
163 })
164 let live
165 try {
166 const indexEvents = []
167 source.on('index:added', (event) => indexEvents.push(event))
168 const index = source.createIndex((row) => row.age, {
169 indexType: db.BasicIndex,
170 name: 'by-age',
171 })
172 assert.equal(
173 typeof source.getIndexMetadata,
174 'function',
175 'public index metadata method',
176 )
177 const metadata = source.getIndexMetadata()
178 assert.equal(metadata.length, 1)
179 assert.equal(metadata[0].indexId, index.id)
180 assert.equal(metadata[0].name, 'by-age')
181 assert.equal(metadata[0].resolver.kind, 'constructor')
182 assert.equal(metadata[0].resolver.name, 'BasicIndex')
183 assert.equal(indexEvents.length, 1)
184 assert.equal(indexEvents[0].index.signature, metadata[0].signature)
185 assert.equal(indexEvents[0].index.name, 'by-age')
186 assert.equal(indexEvents[0].index.resolver.name, 'BasicIndex')
187
188 await source.preload()
189 assert.deepEqual(
190 [...source.values()].map((row) => row.id).sort(),
191 [1, 2, 3],
192 )
193
194 // A small conformance and oracle slice: expected rows come from a plain
195 // array filter/sort/projection, independent of the query/index machinery.
196 const expected = (rows) =>
197 rows
198 .filter((row) => row.age > 25)
199 .sort((a, b) => a.age - b.age)
200 .map(({ id, name }) => ({ id, name }))
201 const query = (q) =>
202 q
203 .from({ user: source })
204 .where(({ user }) => db.gt(user.age, 25))
205 .orderBy(({ user }) => user.age, 'asc')
206 .select(({ user }) => ({ id: user.id, name: user.name }))
207 const selectedRows = (rows) =>
208 rows.map((row) => {
209 const selected = { ...row }
210 delete selected.$hasPendingWrites
211 delete selected.$origin
212 delete selected.$key
213 delete selected.$collectionId
214 return selected
215 })
216 const queryRows = [...(await db.queryOnce(query))]
217 if (mode === '--calibrate-output-shape') {
218 queryRows[0] = { ...queryRows[0], age: 28 }
219 }
220 assert.deepEqual(selectedRows(queryRows), expected(initial))
221
222 live = db.createLiveQueryCollection(query)
223 await live.preload()
224 assert.deepEqual(selectedRows([...live.values()]), expected(initial))
225
226 const changed = [
227 { id: 1, name: 'Ada', age: 28 },
228 { id: 2, name: 'Bea', age: 31 },
229 { id: 3, name: 'Cal', age: 35 },
230 ]
231 sync.begin()
232 sync.write({ type: 'update', value: changed[1] })
233 await sync.commit()
234 assert.deepEqual(selectedRows([...live.values()]), expected(changed))
235 assert.deepEqual(selectedRows(await db.queryOnce(query)), expected(changed))
236 } finally {
237 if (live) await live.cleanup()
238 await source.cleanup()
239 }
240}
241
242try {
243 const bundle = await build({
244 absWorkingDir: root,
245 entryPoints: [builtEntry],
246 outfile: bundlePath,
247 bundle: true,
248 minify: true,
249 format: 'esm',
250 target: 'es2020',
251 platform: 'node',
252 metafile: true,
253 external: ['@standard-schema/spec', '@tanstack/pacer-lite'],
254 plugins: [
255 aliasIvm,
256 ...(mode === '--calibrate-error-name' ? [errorNameMutant] : []),
257 ],
258 ...(mode === '--calibrate-public-member'
259 ? { mangleProps: /^getIndexMetadata$/ }
260 : {}),
261 logLevel: 'silent',
262 })
263 assert.ok(
264 Object.keys(bundle.metafile.inputs).some((input) =>
265 input.includes('packages/db-ivm/src/'),
266 ),
267 'db-ivm is inlined into the minified bundle',
268 )
269 const db = await import(pathToFileURL(bundlePath).href)
270 const errorCount = checkErrorNames(db)
271 await checkCollectionsAndQueries(db)
272 console.log(
273 `Minified public API: ${errorCount} error names, index metadata, query rows, live updates OK`,
274 )
275} finally {
276 await rm(bundleDirectory, { recursive: true, force: true })
277}