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