Skip to content

refactor(lib): migrate @pagespace/db barrel imports to subpath imports - #1106

Closed
2witstudios wants to merge 6 commits into
masterfrom
pu/barrel-lib-migration
Closed

2witstudios wants to merge 6 commits into
masterfrom
pu/barrel-lib-migration

Conversation

@2witstudios

@2witstudios 2witstudios commented Apr 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

Migrates all `@pagespace/db` barrel imports in `packages/lib/src/` to precise subpath imports:

  • `@pagespace/db/db` for the drizzle client
  • `@pagespace/db/operators` for SQL operators (eq, and, etc.)
  • `@pagespace/db/schema/` for each schema module

Files changed: 59 source files + 59 test files across all lib subsystems.

Key implementation details

Test mock forwarding (setup.ts): Unit tests mock the barrel via `vi.mock('@pagespace/db', factory)`. The source files now import from subpaths, so the setup file registers lazy factory mocks for every `@pagespace/db` subpath. Each factory spreads the real drizzle module first, then overlays the barrel mock on top — so test spies replace real functions wherever the barrel mock defines them, and everything else falls back to the real drizzle implementation. No individual test files needed modification.

Processor vitest setup: `apps/processor/src/services/tests/siem-pipeline.e2e.test.ts` directly imports `security-audit.ts` from `@pagespace/lib`, which now uses subpath imports. Added an identical forwarding mock setup at `apps/processor/src/test/setup.ts` so the processor's vitest context propagates barrel mocks to all `@pagespace/db` subpaths.

Integration test exclusion: `rate-limit-cache.integration.test.ts` requires a live PostgreSQL connection; added to the exclude list matching the existing pattern for other integration tests.

Prerequisites (already on master via PR #1107):

  • `packages/db/src/db.ts` — standalone drizzle client with SSL support
  • `packages/db/src/operators.ts` — re-exports from drizzle-orm
  • `packages/db/package.json` — 32+ subpath export entries

How to validate

  • `pnpm --filter @pagespace/lib typecheck` — clean (no TS errors)
  • `pnpm --filter @pagespace/lib test` — 153 test files, 3843 tests all pass
  • `pnpm --filter processor test` — 46 test files, 923 tests all pass
  • `grep -r "from '@pagespace/db'" packages/lib/src --include='*.ts' | grep -v test` — zero barrel imports in source files

🤖 Generated with Claude Code

Replaces all `from '@pagespace/db'` barrel imports in packages/lib/src/
with direct subpath imports (db, operators, schema/*). Covers 118 files
across auth, permissions, services, monitoring, compliance, and more.

Depends on: pu/barrel-db-setup (adds subpath exports to packages/db)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Database imports were reorganized across the codebase from the @pagespace/db barrel into targeted subpath imports (@pagespace/db/db, @pagespace/db/operators, @pagespace/db/schema/*). Tests were updated to align with the new module layout and test setup adds mocked factories for those subpaths.

Changes

Cohort / File(s) Summary
Test setup
packages/lib/src/test/setup.ts
Adds Vitest mock factories that proxy specific @pagespace/db subpaths to the existing barrel mock so tests importing subpaths receive the mocked exports.
Global test import updates
packages/lib/src/__tests__/*, packages/lib/src/**/__tests__/*, packages/lib/src/.../*/__tests__/*
Updated tests to import db, operators, and schemas from specific subpaths instead of the barrel; many db mocks/expectations realigned to the new import locations.
Core services & service tests
packages/lib/src/services/**, packages/lib/src/services/**/__tests__/*
Refactored imports to use @pagespace/db/db, @pagespace/db/operators, and @pagespace/db/schema/*; no runtime logic changes.
Auth, PKCE, Passkey, Magic link
packages/lib/src/auth/**, packages/lib/src/auth/**/__tests__/*
Split barrel imports into db, operators, and schema subpaths; test imports adjusted accordingly.
Permissions & File access
packages/lib/src/permissions/**, packages/lib/src/permissions/**/__tests__/*
Repointed db, operator helpers and schema tables to granular subpaths; implementation unchanged.
Repositories
packages/lib/src/repositories/**, packages/lib/src/repositories/**/__tests__/*
Database client, operators, and schema imports moved to dedicated subpaths; behavior unchanged.
Integrations & Config
packages/lib/src/integrations/repositories/*
Refactored repository imports to db/operators/schema/* subpaths.
Audit & Security
packages/lib/src/audit/**, packages/lib/src/security/**, packages/lib/src/audit/**/__tests__/*
Moved db, operator helpers, and audit/security schemas to specific subpaths; no functional changes.
Compliance & Retention
packages/lib/src/compliance/**, packages/lib/src/compliance/**/__tests__/*
Replaced barrel schema imports with @pagespace/db/schema/* and @pagespace/db/db.
Logging & Monitoring
packages/lib/src/logging/**, packages/lib/src/monitoring/**
Decoupled db, operators, and monitoring schemas to their subpaths; tests updated.
Content, Pages & File processing
packages/lib/src/content/**, packages/lib/src/pages/**, packages/lib/src/file-processing/**
Refactored import sources for db, operators, and core schemas; logic unchanged.
Notifications & Push
packages/lib/src/notifications/**
Operators, db, and notification schemas imported from explicit subpaths; implementation unchanged.
DB package minor formatting
packages/db/src/index.ts
Trailing comment/EOF formatting adjusted (newline/semi-colon fix).
Vitest config tweak
packages/lib/vitest.config.ts
Excludes one integration test from test run and coverage.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15 minutes

Possibly related PRs

Poem

🐰 I hopped through imports, neat and spry,
Split barrels into paths that fly,
db and schemas found their nests,
Operators tidy, tests at rest,
A modular burrow — tidy sky! 🥕✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: migration of @pagespace/db barrel imports to subpath imports across the lib package.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch pu/barrel-lib-migration

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e4a75899e7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2 to +3
import { db } from '@pagespace/db/db';
import { eq, and, isNull, lt, gt, sql, or } from '@pagespace/db/operators';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Avoid unresolved @pagespace/db subpath imports

This refactor switches many files to @pagespace/db/db and @pagespace/db/operators, but those entrypoints are not available on this branch (there is no matching packages/db/src/db.ts / operators.ts export path), so module resolution fails immediately. In the current base, pnpm --filter @pagespace/lib typecheck reports TS2307 errors for these imports across the migrated files, which blocks compilation unless the DB subpath setup is included in the same change.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved in 7e39b8c — cherry-picked the prerequisite DB package changes directly into this branch. packages/db/src/db.ts, packages/db/src/operators.ts, and all 32+ ./schema/* entries are now declared in packages/db/package.json's exports map. The build will now resolve all @pagespace/db/db and @pagespace/db/operators subpaths correctly.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (9)
packages/lib/src/pages/__tests__/circular-reference-guard.test.ts (1)

28-28: ⚠️ Potential issue | 🔴 Critical

Import updated but corresponding mock is still on the old path.

While this import correctly uses the new subpath @pagespace/db/db, the mock at lines 7-17 still mocks @pagespace/db. See the comment on lines 7-17 for the fix.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lib/src/pages/__tests__/circular-reference-guard.test.ts` at line
28, The test imports the database from the new subpath db (import { db } from
'@pagespace/db/db') but the jest mock still targets the old module path; update
the mock call that currently references '@pagespace/db' to the new subpath
'@pagespace/db/db' (and ensure the mocked exports match the actual exported
symbols from that module, e.g., the db object used in the test) so the mock and
import point to the same module.
packages/lib/src/services/__tests__/drive-member-service.test.ts (1)

10-54: ⚠️ Potential issue | 🔴 Critical

Same mock-path mismatch as notifications.test.ts — vi.mock('@pagespace/db') is no longer intercepting anything.

../drive-member-service now imports db, operators, and schema tables from @pagespace/db/db, @pagespace/db/operators, and @pagespace/db/schema/* (per the PR-wide refactor), and Line 54 of this test also pulls db from @pagespace/db/db. The barrel mock on Line 10 targets a path nobody imports anymore, so mockDb.select.mockReturnValue(…) is being applied to the real Drizzle client. Redirect each vi.mock call to the actual subpath(s) the production file uses, and move the table/operator fixtures to their respective subpath mocks — see the suggested diff on notifications.test.ts for the pattern.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lib/src/services/__tests__/drive-member-service.test.ts` around
lines 10 - 54, Test mock targets are wrong: the file uses subpath imports so
vi.mock('@pagespace/db') no longer intercepts them. Replace the barrel mock with
mocks for the actual subpaths the production module imports — e.g.,
vi.mock('@pagespace/db/db', ...) to mock
db.query/select/insert/update/delete/execute, vi.mock('@pagespace/db/operators',
...) to provide eq/and/sql, and vi.mock('@pagespace/db/schema/driveMembers'|
'drives' | 'users' | 'userProfiles' | 'driveRoles' | 'pagePermissions' |
'pages', ...) (one per schema module used) to export the table column fixtures;
move the table/operator fixtures currently inside the barrel mock into the
corresponding subpath mocks and keep the existing import of db from
'@pagespace/db/db' at Line 54 unchanged so mockDb.select.mockReturnValue will
correctly intercept calls from the tested module.
packages/lib/src/auth/__tests__/token-lookup.test.ts (1)

7-23: ⚠️ Potential issue | 🔴 Critical

Mock-path mismatch (same root cause).

vi.mock('@pagespace/db', …) targets the barrel, but production ../token-lookup and this test both import db from @pagespace/db/db. The mock is inert; db.query.mcpTokens.findFirst resolves to the real client and vi.mocked(db.query.mcpTokens.findFirst).mockResolvedValue(…) will fail. Split the mock into @pagespace/db/db, @pagespace/db/operators, and @pagespace/db/schema/<mcpTokens-module> to match the production module graph. See the suggested diff on notifications.test.ts.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lib/src/auth/__tests__/token-lookup.test.ts` around lines 7 - 23,
The test mock targets the barrel '@pagespace/db' but the code under test imports
db from '@pagespace/db/db', so the mocked functions are not applied; update the
mocks to mirror the actual import graph by mocking '@pagespace/db/db' (exporting
db with query.mcpTokens.findFirst as a vi.fn()), mock '@pagespace/db/operators'
(export eq/and/isNull as vi.fn()), and mock the schema module that exports
mcpTokens (so tokenHash/revokedAt shape matches production). Then update the
test to use vi.mocked(db.query.mcpTokens.findFirst).mockResolvedValue(...)
against the mocked db import and keep findMCPTokenByValue as the function under
test.
packages/lib/src/monitoring/__tests__/hash-chain-verifier.test.ts (1)

37-147: ⚠️ Potential issue | 🔴 Critical

Mock-path mismatch (same root cause as the other test files in this PR).

vi.mock('@pagespace/db', …) is no longer exercised because production ../hash-chain-verifier and ../activity-logger now import from @pagespace/db/db, @pagespace/db/operators, and @pagespace/db/schema/*. Line 147’s import { db } from '@pagespace/db/db' pulls the real client, so every vi.mocked(db.select).mockReturnValue(…) in this suite will throw. Re-point the mock to the actual subpaths — the stateful factory built around mockLogEntries can be moved verbatim into a vi.mock('@pagespace/db/db', …) (plus a separate vi.mock('@pagespace/db/schema/activity', …) — or wherever activityLogs actually lives) and the operator subpath. See the fix outlined on notifications.test.ts.

packages/lib/src/repositories/__tests__/agent-repository.test.ts (1)

7-30: ⚠️ Potential issue | 🔴 Critical

Same mock/import mismatch as the other migrated tests.

vi.mock('@pagespace/db', …) at line 7 defines db, pages, eq, and, but the test (line 30) and the migrated ../agent-repository SUT now resolve db from @pagespace/db/db, the pages schema from @pagespace/db/schema/pages (or similar), and operators from @pagespace/db/operators. vi.mocked(db.select) / vi.mocked(db.update) in setupSelectChain/setupUpdateChain will bind to the real module — not the stub chain — so the chained .from().where().limit() mocks never get wired in. Apply the multi-subpath mock pattern described on notification-email-service.test.ts.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lib/src/repositories/__tests__/agent-repository.test.ts` around
lines 7 - 30, The test's vi.mock('@pagespace/db', ...) stub doesn't match
imports used by the SUT (agentRepository) so db.select/db.update and chained
.from/.where/.limit mocks aren't wired; update the test to mock the actual
subpaths used by the SUT — mock '@pagespace/db/db' to provide the chained db
select/update spies, mock '@pagespace/db/schema/pages' to provide the pages
schema, and mock '@pagespace/db/operators' (or the operators module used) to
provide eq/and — follow the multi-subpath mock pattern used in
notification-email-service.test.ts and ensure setupSelectChain and
setupUpdateChain call vi.mocked on the exact db.select/db.update exports from
the '@pagespace/db/db' mock.
packages/lib/src/audit/__tests__/audit-query.test.ts (1)

26-37: ⚠️ Potential issue | 🔴 Critical

Critical: operator assertions will fail — eq/gte/lte spies from the barrel mock are never invoked.

The mock at line 26 defines eq, gte, lte, and, desc as vi.fn() spies on @pagespace/db, but line 37 imports eq, gte, lte from @pagespace/db/operators and the SUT (../audit-query) was migrated to the same subpath. Both consume the real drizzle-orm operators, so:

  • The expect(eq).toHaveBeenCalledWith(...) / expect(gte)… / expect(lte)… assertions at lines 65, 71, 78, 85, 101-102, 108 are checking spies that are never called.
  • and also needs mocking on @pagespace/db/operators if the SUT uses it.

Add a vi.mock('@pagespace/db/operators', …) factory that exposes the same spies (share them via vi.hoisted) — see the consolidated pattern on notification-email-service.test.ts.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lib/src/audit/__tests__/audit-query.test.ts` around lines 26 - 37,
The test's spies (eq, gte, lte, and, desc) are mocked on `@pagespace/db` but the
SUT and imports use `@pagespace/db/operators` so those spies are never invoked;
add a vi.mock('@pagespace/db/operators', ...) factory that returns the same
hoisted spies (eq, gte, lte, and, desc) used in the existing `@pagespace/db` mock
so the assertions (expect(eq).toHaveBeenCalledWith..., expect(gte)...,
expect(lte)..., and any expect(and)...) reference the actual mocked functions
invoked by queryAuditEvents; ensure you share the spies via vi.hoisted so both
module mocks point to the identical spy instances.
packages/lib/src/notifications/__tests__/push-notifications.test.ts (1)

7-60: ⚠️ Potential issue | 🔴 Critical

Same mock/import mismatch: barrel mocked, SUT + test import from @pagespace/db/db.

Root cause flagged on notification-email-service.test.ts. The factory at line 7 defines db, pushNotificationTokens, eq, and under @pagespace/db, but the test (line 60) and the migrated ../push-notifications SUT now resolve these from @pagespace/db/db, @pagespace/db/operators, and @pagespace/db/schema/*. Without corresponding vi.mock('@pagespace/db/db', …) (etc.) factories, mockDb.query.pushNotificationTokens.findFirst.mockResolvedValue(...) targets an unrelated object from the real module.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lib/src/notifications/__tests__/push-notifications.test.ts` around
lines 7 - 60, The test is mocking '@pagespace/db' but the SUT imports from
'@pagespace/db/db' (and related operators/schema modules), so the SUT receives
the real modules instead of your mock; update the test to mock the exact modules
the SUT imports: add vi.mock('@pagespace/db/db', () => ({ db: mockDb })) and
also mock '@pagespace/db/operators' (exporting eq/and) and any schema modules
under '@pagespace/db/schema/*' used by push-notifications, making sure to
re-export the same mockDb and the same named symbols
(mockDb.query.pushNotificationTokens.findFirst/findMany, db.insert, db.update,
eq, and) so calls in registerPushToken, unregisterPushToken,
unregisterAllPushTokens, sendPushNotification, and getUserPushTokens use your
mocked implementations.
packages/lib/src/services/__tests__/drive-service.test.ts (1)

13-36: ⚠️ Potential issue | 🔴 Critical

Same mock/import mismatch as the other test files in this PR.

vi.mock('@pagespace/db', …) at line 13 does not intercept import { db } from '@pagespace/db/db' at line 36 nor the subpath imports now present in ../drive-service. See the consolidated comment on notification-email-service.test.ts for the required fix; the same pattern applies here (and to every migrated test). Unless the subpath exports in the companion PR alias to the exact same file as the barrel, this test will no longer exercise the mocked db.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lib/src/services/__tests__/drive-service.test.ts` around lines 13 -
36, The test's vi.mock target doesn't match the actual import used by the code
under test: you mocked '@pagespace/db' but the test imports the DB via the
subpath import import { db } from '@pagespace/db/db' (and the implementation
under test also uses subpath exports). Fix by making the mock cover the exact
subpath(s) used—either change the vi.mock target to '@pagespace/db/db' (or add a
separate vi.mock for each subpath like '@pagespace/db/db' and any other subpath
used), or update the import in the test to the barrel you mocked; ensure the
mocked exports (db, drives, driveMembers, eq, and, not, inArray, etc.) are
provided under the same module name as the import so the mocked db in vi.mock is
actually injected into the code that references import { db } from
'@pagespace/db/db'.
packages/lib/src/monitoring/__tests__/activity-logger.test.ts (1)

42-79: ⚠️ Potential issue | 🔴 Critical

Same mock/import mismatch — db.transaction mock will not bind.

vi.mock('@pagespace/db', …) at line 42 provides a db with a vi.fn() transaction, but line 79 imports db from @pagespace/db/db and line 143 calls vi.mocked(db.transaction).mockImplementation(...). After migration, db is the real module's binding, so vi.mocked(...) will produce a non-spy and the call will likely throw (or contact a real database). Additionally, the SUT’s new subpath imports for activityLogs (schema), eq (operators), etc. need dedicated vi.mock('@pagespace/db/schema/*') / vi.mock('@pagespace/db/operators') factories.

See the consolidated fix pattern on notification-email-service.test.ts.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lib/src/monitoring/__tests__/activity-logger.test.ts` around lines
42 - 79, The test's module mocks don't match the actual imports used by the SUT
so vi.mocked(db.transaction) isn't a spy — update mocks to target the real
import paths used by the SUT: replace vi.mock('@pagespace/db', ...) with
vi.mock('@pagespace/db/db', ...) (so db.transaction is the mocked binding) and
add dedicated vi.mock factories for the schema/operator subpaths used (e.g.,
vi.mock('@pagespace/db/schema/activityLogs'),
vi.mock('@pagespace/db/schema/users'), vi.mock('@pagespace/db/operators') or
whatever actual subpaths export activityLogs, users, eq, sql) so activityLogs,
users, eq, sql are mocked consistently; keep the import of { db } from
'@pagespace/db/db' after the mocks and then you can safely call
vi.mocked(db.transaction).mockImplementation(...) and mock createId/init as you
already do for '@paralleldrive/cuid2'.
🧹 Nitpick comments (2)
packages/lib/src/auth/__tests__/session-service.test.ts (1)

2-7: Minor: operators still come from drizzle-orm directly.

Line 5 keeps import { eq, and, isNull } from 'drizzle-orm' while the rest of the file migrated to @pagespace/db/* subpaths. Not a correctness issue (drizzle-orm is a transitive dep), but inconsistent with the PR's goal of centralizing DB access through @pagespace/db. Consider swapping to @pagespace/db/operators for consistency with session-repository.ts.

♻️ Proposed tweak
 import { db } from '@pagespace/db/db';
 import { users } from '@pagespace/db/schema/auth';
 import { sessions } from '@pagespace/db/schema/sessions';
-import { eq, and, isNull } from 'drizzle-orm';
+import { eq, and, isNull } from '@pagespace/db/operators';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lib/src/auth/__tests__/session-service.test.ts` around lines 2 - 7,
The test imports operators directly from drizzle-orm (import { eq, and, isNull }
from 'drizzle-orm') which is inconsistent with the project's centralized DB API;
update the import to pull these operators from `@pagespace/db/operators` instead
so it matches session-repository.ts and other modules — replace the drizzle-orm
operator import in session-service.test.ts with an import from
`@pagespace/db/operators` for eq, and, and isNull.
packages/lib/src/compliance/retention/retention-engine.test.ts (1)

18-28: Remove the orphaned vi.mock('@pagespace/db', …) block.

Neither the SUT (./retention-engine) nor this test imports from the @pagespace/db barrel anymore — all schema symbols now resolve via @pagespace/db/schema/* (Lines 50–55). This factory never intercepts anything and is safe to delete; the real schema module exports the same table references the expect(deleteFn).toHaveBeenCalledWith(sessions) assertions rely on.

🧹 Suggested cleanup
-vi.mock('@pagespace/db', () => ({
-  sessions: { id: 'sessions.id', expiresAt: 'sessions.expiresAt' },
-  verificationTokens: { id: 'vt.id', expiresAt: 'vt.expiresAt' },
-  socketTokens: { id: 'st.id', expiresAt: 'st.expiresAt' },
-  emailUnsubscribeTokens: { id: 'eut.id', expiresAt: 'eut.expiresAt' },
-  pulseSummaries: { id: 'ps.id', expiresAt: 'ps.expiresAt' },
-  pageVersions: { id: 'pv.id', expiresAt: 'pv.expiresAt', isPinned: 'pv.isPinned' },
-  driveBackups: { id: 'db.id', expiresAt: 'db.expiresAt', isPinned: 'db.isPinned' },
-  pagePermissions: { id: 'pp.id', expiresAt: 'pp.expiresAt' },
-  aiUsageLogs: { id: 'aul.id', expiresAt: 'aul.expiresAt' },
-}));
-
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lib/src/compliance/retention/retention-engine.test.ts` around lines
18 - 28, Remove the unused mock block vi.mock('@pagespace/db', () => ({ ... }))
from the test file retention-engine.test.ts because the SUT (./retention-engine)
and this test now import schema symbols from `@pagespace/db/schema/`* and the mock
never intercepts anything; simply delete the entire vi.mock('@pagespace/db',
...) block so the test uses the real schema exports (e.g., sessions,
pageVersions, driveBackups) that the
expect(deleteFn).toHaveBeenCalledWith(sessions) assertions rely on.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/lib/src/__tests__/device-auth-utils.test.ts`:
- Around line 11-13: This test file still uses a barrel/dynamic import of
"@pagespace/db" in several places; replace those dynamic imports with the
explicit subpath imports already used at top (use the same modules: import db
from '@pagespace/db/db' or the named export db, import { eq } from
'@pagespace/db/operators', and import { deviceTokens } from
'@pagespace/db/schema/auth') so all references to db, eq, and deviceTokens come
from the specific subpath modules rather than the barrel; update any require()
or dynamic import(...) calls to use these subpath imports and adjust any
variable names to match the existing top-level imports so the tests no longer
import the barrel module.

In `@packages/lib/src/services/__tests__/app-shell-service.integration.test.ts`:
- Around line 11-16: Fix imports that use non-existent subpaths by replacing
subpath imports like "@pagespace/db/db" and "@pagespace/db/schema/..." with the
single barrel export from "@pagespace/db"; import db, users, channelMessages,
drives, pages, chatMessages, pagePermissions, driveMembers, and connections from
"@pagespace/db" instead of individual subpaths, and search/replace other
occurrences in packages/lib/src to ensure all modules import the re-exported
symbols (db, users, channelMessages, drives, pages, chatMessages,
pagePermissions, driveMembers, connections) from the barrel.

---

Outside diff comments:
In `@packages/lib/src/__tests__/page-version-service.test.ts`:
- Around line 6-15: The test is mocking the barrel module but the SUT imports
the subpaths directly, so replace the stale vi.mock('@pagespace/db', ...) with
mocks for the actual modules the code imports: mock '@pagespace/db/db' to export
a mocked db object (e.g., db.insert = vi.fn().mockReturnThis()) and mock
'@pagespace/db/schema/versioning' to export the pageVersions symbol used by
page-version-service; ensure these vi.mock calls run before importing the SUT so
the test uses the mocked db and pageVersions instead of the real Drizzle client.

In `@packages/lib/src/__tests__/token-lookup.test.ts`:
- Around line 12-30: The test and many files import from the non-existent
subpath '@pagespace/db/db' (and operators/schema subpaths) after refactor;
either restore subpath exports in the packages/db package or revert code to use
the barrel import. Fix by adding small re-export modules and package.json
exports: create packages/db/src/db.ts and packages/db/src/operators.ts that
re-export the existing barrel symbols (e.g., export * from './index' or from
their actual implementations), then add "./db" and "./operators" (and
"./schema/*") entries to packages/db/package.json exports so imports like
'@pagespace/db/db' and '@pagespace/db/operators' resolve; alternatively, change
the test and all files back to import from '@pagespace/db' instead of
'@pagespace/db/db' to match current package exports. Ensure the test mock stays
against the same import path used by the code (e.g., mock '@pagespace/db' if you
revert to barrel imports or mock '@pagespace/db/db' if you add the subpath
exports).

In `@packages/lib/src/__tests__/version-resolver.test.ts`:
- Around line 4-27: The test's barrel mock targets `@pagespace/db` but the SUT
imports subpaths, so replace the single vi.mock with separate mocks for the
exact modules the code imports: mock '@pagespace/db/db' to export db with select
as vi.fn(), mock '@pagespace/db/operators' to export eq, and, or, desc as
vi.fn(...) shapes, and mock '@pagespace/db/schema/versioning' to export
pageVersions with the expected fields; ensure the mocked symbols referenced by
resolveVersionContent, batchResolveVersionContent, and
resolveStackedVersionContent (db, eq, and, or, desc, pageVersions) match the
shapes used in the tests so calls like (db.select as ReturnType<typeof
vi.fn>).mockImplementation(...) work correctly.

In `@packages/lib/src/audit/__tests__/security-audit.test.ts`:
- Around line 33-79: The test currently mocks only the barrel '@pagespace/db'
causing the SUT to import unmocked subpaths; update the test to mock the exact
modules the SUT imports by adding vi.mock calls for '@pagespace/db/db',
'@pagespace/db/operators', and '@pagespace/db/schema/security-audit' (using the
same mock implementation used for the barrel) before importing
SecurityAuditService, computeSecurityEventHash, and securityAuditLog so the SUT
sees the mocked db, sql, and schema; ensure the mocked db has transaction,
insert, select, and the custom sql factory and then use
vi.mocked(db.transaction).mockImplementation(...) and other mocked assertions
against that same mocked db reference so SecurityAuditService.logEvent and
SecurityAuditService.queryEvents interact with the mocked implementations.

In `@packages/lib/src/auth/__tests__/account-lockout.test.ts`:
- Around line 4-40: The vi.mock target is stale: replace the current
vi.mock('@pagespace/db', ...) with separate mocks that match the actual imports
— mock '@pagespace/db/db' to provide the db object (including
db.query.users.findFirst and db.update(...).set(...).where(...).returning), mock
'@pagespace/db/schema/auth' to export the users schema (id, email,
failedLoginAttempts, lockedUntil), and mock '@pagespace/db/operators' to export
eq; ensure the mocked symbols (db, users schema, eq) match the shapes used by
the SUT and that all vi.mocked(db.query.users.findFirst) usages point to the
mocked db from '@pagespace/db/db'.

In `@packages/lib/src/auth/__tests__/device-auth-utils.test.ts`:
- Around line 8-97: Tests and SUT are importing from non-existent subpaths
(`@pagespace/db/db` and operators); change imports to the barrel export and mock
the barrel. Update the production SUT import lines to import { db, eq, and,
isNull, lt, gt, sql, or, deviceTokens, users } from '@pagespace/db'. In the
test, change the vi.mock target from '@pagespace/db' subpaths to
vi.mock('@pagespace/db', ...) and return an object containing db, deviceTokens,
users and the operator fns (eq, and, isNull, lt, gt, or, sql) as currently
shaped. Also update the test import at the bottom to import { db } from
'@pagespace/db' to match the barrel.

In `@packages/lib/src/auth/__tests__/magic-link-service.test.ts`:
- Around line 3-51: The test's Vitest module mocks are targeting the barrel
'@pagespace/db' but the code now imports db from the subpath '@pagespace/db/db'
(and uses operators/schema types from subpaths); update the vi.mock calls so
they target the actual import specifiers used by the code under test (replace
vi.mock('@pagespace/db', ...) with vi.mock('@pagespace/db/db', ...), and
add/adjust mocks for '@pagespace/db/operators' and '@pagespace/db/schema/auth'
as needed), keeping the same mock shapes for db.query, db.insert, users,
verificationTokens and exported helpers so createMagicLinkToken,
verifyMagicLinkToken and the tests pick up the mocks.

In `@packages/lib/src/auth/__tests__/oauth-utils-unit.test.ts`:
- Around line 23-53: The test's vi.mock('@pagespace/db', ...) is not
intercepting subpath imports used by createOrLinkOAuthUser; update the mocks to
target the actual subpaths imported by oauth-utils (e.g., mock
'@pagespace/db/db' to provide the db object with query.users.findFirst, insert,
update, select, etc., and mock '@pagespace/db/schema/auth' to export the users
symbols used in the code), and similarly mock any other subpath modules imported
by oauth-utils (for example '@pagespace/db/schema/core' or
'@pagespace/db/operators' if referenced) so that createOrLinkOAuthUser, db, and
users in the test resolve to the mocked implementations.

In `@packages/lib/src/auth/__tests__/passkey-service.test.ts`:
- Around line 13-59: The test mock targets the old barrel path '@pagespace/db'
but the code now imports db from '@pagespace/db/db' (and schema exports moved to
subpaths), so update the mocks: replace the single vi.mock('@pagespace/db', ...)
with a vi.mock('@pagespace/db/db', ...) that returns the mocked db object
(db.query.users/passkeys/verificationTokens, insert/update/delete/transaction)
and add a separate vi.mock for the schema subpath (e.g.,
'@pagespace/db/schema/auth' or whichever subpath exports
passkeys/users/verificationTokens) that returns the passkeys, users,
verificationTokens objects; keep or relocate the eq/and/isNull/lt/sql mocks to
whichever module exports them so ../passkey-service and the test import paths
resolve to these mocked symbols (db, passkeys, users, verificationTokens, eq,
and, isNull, lt, sql).

In `@packages/lib/src/auth/__tests__/session-repository-logging.test.ts`:
- Around line 3-24: The test currently mocks '@pagespace/db' which doesn't
intercept the actual imports used by sessionRepository; replace that single
vi.mock with explicit mocks for the exact subpaths imported by the module under
test: create vi.mock('@pagespace/db/db', ...) that returns a mocked db object
with update, query, insert, delete (each as vi.fn) and the sessions/users shapes
used in the tests, and add separate vi.mock calls for '@pagespace/db/operators'
(exporting mocked eq, and, or, isNull, gt, lt), '@pagespace/db/schema/auth' and
'@pagespace/db/schema/sessions' (exporting the required schema constants), so
that the imported symbols db.update, db.query, sessions, users, eq, and, or,
isNull, gt, lt are all vi.fn/mockable and
vi.mocked(db.update).mockReturnValue(...) will work against the mocked db.

In `@packages/lib/src/auth/__tests__/verification-utils.test.ts`:
- Around line 9-57: The current vi.mock for '@pagespace/db' must be split into
three specifier-scoped mocks: create a vi.mock('@pagespace/db/db', ...) that
exports the mocked db object (including db.query.verificationTokens.findFirst,
insert, delete, update, select), a vi.mock('@pagespace/db/schema/auth', ...)
that exports the verificationTokens and users schema shapes, and a
vi.mock('@pagespace/db/operators', ...) that exports eq, and, isNull; move the
operator stubs (eq/and/isNull) into the operators mock so where(and(eq(...),
eq(...))) calls in
createVerificationToken/verifyToken/markEmailVerified/isEmailVerified are
intercepted; keep the same shapes/return values you had previously and then
update any vi.mocked(...) calls in the test to target the mocked exports from
these three specifiers.

In `@packages/lib/src/compliance/retention/monitoring-retention.test.ts`:
- Around line 19-34: The test currently mocks '@pagespace/db' but the code under
test imports monitoring tables from '@pagespace/db/schema/monitoring', so the
mock never applies; update the vi.mock call to target the actual import path
('@pagespace/db/schema/monitoring') or add an additional mock for that path,
returning the same mocked objects (the db.delete stub that calls mockDeleteTable
and returns where().returning as mockReturning, plus
apiMetrics/systemLogs/errorLogs/userActivities exports) so the imports used by
the test resolve to the mocked schema instead of loading real definitions.

In `@packages/lib/src/content/__tests__/version-resolver.test.ts`:
- Around line 13-36: The tests and code currently import the DB subpaths that
don't exist yet (e.g., the import of db from '@pagespace/db/db' and any
operators subpath), so revert those subpath imports back to the barrel export
'@pagespace/db' until the pu/barrel-db-setup branch is merged; update the test's
vi.mock target to vi.mock('@pagespace/db', ...) and change any production
imports that use '@pagespace/db/db' or '@pagespace/db/operators' to import from
'@pagespace/db' instead, ensuring symbols like db, pageVersions, eq, and desc
are referenced from the barrel module used by resolveVersionContent,
batchResolveVersionContent, and resolveStackedVersionContent.

In `@packages/lib/src/logging/__tests__/ai-usage-purge.test.ts`:
- Around line 14-38: Change the broken subpath imports to use the barrel so the
test mock is applied and TypeScript resolves correctly: update the imports in
the module under test (the file that exports purgeAiUsageLogs and
deleteAiUsageLogsForUser) to import db, eq, lt, and aiUsageLogs from
'@pagespace/db' instead of subpaths like '@pagespace/db/db' or
'@pagespace/db/operators', and likewise update this test to import db from
'@pagespace/db' (so the vi.mock('@pagespace/db', ...) intercepts it); then
remove the duplicate lt/eq mocks from the vi.mock body because those symbols
will come from the barrel mock. Ensure you reference the existing symbols
purgeAiUsageLogs, deleteAiUsageLogsForUser, db, eq, lt, and aiUsageLogs when
making these changes.

In `@packages/lib/src/logging/__tests__/logger-database.test.ts`:
- Around line 20-55: The test's barrel mock vi.mock('@pagespace/db', ...)
doesn't match the SUT imports (the SUT imports from '@pagespace/db/db' and
'@pagespace/db/schema/monitoring'), so replace or add mocks for those exact
module IDs: mock '@pagespace/db/db' to export db with insert set to your
mockInsert and mock '@pagespace/db/schema/monitoring' to export the monitoring
table constants used by logger-database (systemLogs, apiMetrics, aiUsageLogs,
errorLogs, userActivities) so
writeLogsToDatabase/writeApiMetrics/writeAiUsage/writeUserActivity/writeError
exercise the mocked insert/values; drop the unused operator exports
(lt/eq/and/or/isNotNull) or move them into a separate
vi.mock('@pagespace/db/operators', ...) only if required by other modules.

In `@packages/lib/src/logging/__tests__/monitoring-purge.test.ts`:
- Around line 6-20: The test's vi.mock currently targets '@pagespace/db' but the
SUT imports db from '@pagespace/db/db', eq from '@pagespace/db/operators', and
the tables from '@pagespace/db/schema/monitoring', so the mock doesn't apply;
update the test to mock those exact modules (mock '@pagespace/db/db' to export a
db with delete mocked, mock '@pagespace/db/operators' to export eq as a vi.fn,
and mock '@pagespace/db/schema/monitoring' to export systemLogs, apiMetrics,
errorLogs, userActivities objects) so that the mocked db.delete, eq, and table
identifiers used by deleteMonitoringDataForUser are actually injected into the
SUT.

In `@packages/lib/src/monitoring/__tests__/activity-logger-compliance.test.ts`:
- Around line 47-84: The test currently mocks the barrel '@pagespace/db' but
activity-logger imports concrete subpaths, so replace or add vi.mock calls for
the exact module specifiers used by activity-logger: '@pagespace/db/db',
'@pagespace/db/operators', and '@pagespace/db/schema/monitoring'; export the
same mocked shapes as in your existing `@pagespace/db` mock (db with insert,
transaction, query.activityLogs.findFirst, activityLogs schema object, eq and
sql helpers) so that the db imported in the test (and used by logActivity)
points to the mocked transaction/insert and populates
testState.capturedInsertValues; ensure these vi.mock calls occur before
importing the module under test.

In `@packages/lib/src/notifications/__tests__/notifications.test.ts`:
- Around line 7-71: The tests mock the monolithic '@pagespace/db' but the
production code imports from subpaths (e.g., '@pagespace/db/db',
'@pagespace/db/operators', '@pagespace/db/schema/...'), so
vi.mocked(db.insert)/select/etc. are operating on the real client; update the
mocks to target each subpath used in the codebase: add vi.mock calls for
'@pagespace/db/db' that return the mocked db object (with
insert/select/update/delete/query), for '@pagespace/db/operators' to export
eq/and/desc/count/sql stubs, and for each schema import (e.g.,
'@pagespace/db/schema/notifications', '@pagespace/db/schema/users',
'@pagespace/db/schema/pages', '@pagespace/db/schema/drives') to export the table
shapes used in tests; then keep using vi.mocked(db.insert) and the
setupInsertChain/setupSelectChain helpers against the mocked '@pagespace/db/db'
export.

In `@packages/lib/src/pages/__tests__/circular-reference-guard.test.ts`:
- Line 39: The test's dynamic require still points to the old barrel export;
update the mocked import for eq by changing the require target from
'@pagespace/db' to the operators module so eqMock =
vi.mocked(require('@pagespace/db/operators').eq) (or switch to a static import
from '@pagespace/db/operators' for eq) to match the production export; ensure
the reference to eqMock and any usages of eq in the test remain unchanged.
- Around line 7-17: The test mock targets the old barrel '@pagespace/db' but the
code imports subpaths; update the mocks so they match the actual imports:
replace the single vi.mock('@pagespace/db', ...) with mocks for the subpaths
used in the production code—vi.mock('@pagespace/db/db', () => ({ db: { query: {
pages: { findFirst: vi.fn() } } } })), vi.mock('@pagespace/db/schema/core', ()
=> ({ pages: { id: 'id', parentId: 'parentId' } })), and
vi.mock('@pagespace/db/operators', () => ({ eq: vi.fn((_a, _b) => 'eq') }));
ensure the mocked symbols (db.query.pages.findFirst, pages, eq) match the names
used in the test and code.

In `@packages/lib/src/permissions/__tests__/batch-page-permissions.test.ts`:
- Around line 7-34: The test imports use non-existent subpaths
('@pagespace/db/db' and '@pagespace/db/operators') so the vi.mock targeting
'@pagespace/db' never applies; update the imports to import { db, isNotNull }
from '@pagespace/db' so the mocked db and isNotNull defined in the vi.mock block
are used by the tests (keep existing vi.mock('@pagespace/db', ...) and ensure
any references to db.select, isNotNull, eq, and other mocked symbols resolve to
the root package exports).

In `@packages/lib/src/permissions/__tests__/drive-permissions.test.ts`:
- Around line 7-32: The test imports are targeting non-existent subpaths; update
the imports that currently pull from '@pagespace/db/db' and
'@pagespace/db/operators' to import the exported symbols directly from the main
module so the mock works—replace those imports with a single import of { db,
isNotNull } from '@pagespace/db' (keeping the existing vi.mock('@pagespace/db',
...) in place), and ensure any usages of db and isNotNull in the test reference
those imported identifiers.

In `@packages/lib/src/permissions/__tests__/file-access.test.ts`:
- Around line 7-13: The current mock targets '@pagespace/db' but the test
imports db from '@pagespace/db/db', so the mock isn't applied; update the
vi.mock calls to match the actual import specifiers: replace the single mock of
'@pagespace/db' with separate mocks for '@pagespace/db/db' (exporting db.select
as a vi.fn()), '@pagespace/db/operators' (exporting eq as a vi.fn((_a,_b) =>
'eq')), and '@pagespace/db/schema/storage' (exporting filePages with fileId and
pageId); ensure the symbols db, eq, and filePages in the mocks match the names
used in the test imports and assertions.

In `@packages/lib/src/permissions/__tests__/permission-mutations-unit.test.ts`:
- Around line 8-24: Replace invalid subpath imports of the Drizzle client and
operators (e.g., any imports like "import { db } from '@pagespace/db/db'" or
"import { and, eq } from '@pagespace/db/operators'") with a single import from
the package root: "import { db, and, eq } from '@pagespace/db'"; update any test
mocks or usages that reference the old paths to use the root export symbols (db,
and, eq, etc.) so all references (e.g., in permission-mutations-unit.test.ts and
other files) import these symbols from '@pagespace/db' only.

In `@packages/lib/src/permissions/__tests__/permissions.test.ts`:
- Around line 7-28: The test's vi.mock targets the wrong module specifier: it
mocks '@pagespace/db' but the code under test imports { db } from
'@pagespace/db/db', so the mock doesn't intercept imports and
vi.mocked(db.select) assertions fail; fix by updating the mock call to
vi.mock('@pagespace/db/db', () => ({ ...same mock... })) so it matches the
import, or alternatively change the import that pulls db to use the barrel
export (import { db } from '@pagespace/db') so it matches the existing mock;
ensure references to db.select, vi.mocked, and other mocked helpers remain
unchanged.

In `@packages/lib/src/repositories/__tests__/account-repository.test.ts`:
- Around line 7-35: The test's vi.mock only stubs the barrel module so the SUT
(which imports db, eq, sql, users, drives, driveMembers from subpaths) still
gets the real Drizzle client; update the mocks to hoist and mock each consumed
subpath explicitly (vi.mock('@pagespace/db/db', ...),
vi.mock('@pagespace/db/operators', ...), vi.mock('@pagespace/db/schema/auth',
...), vi.mock('@pagespace/db/schema/core', ...),
vi.mock('@pagespace/db/schema/members', ...)) and share a vi.hoisted mock state
object so the same mock surface (mockDb with select/delete/transaction and the
schema objects users/drives/driveMembers and helpers eq/sql) is returned from
each mock; ensure references used in tests (db.select, db.delete,
db.transaction, eq, sql, users, drives, driveMembers) point to that shared
mocked instances so accountRepository uses the mocked client.

In `@packages/lib/src/repositories/__tests__/activity-log-repository.test.ts`:
- Around line 7-20: The current test mocks the barrel '@pagespace/db' but the
test imports subpaths (e.g., db from '@pagespace/db/db' and operators from
'@pagespace/db/operators'), so Vitest doesn't intercept them; replace the single
vi.mock('@pagespace/db', ...) with explicit mocks for each subpath used in this
test: vi.mock('@pagespace/db/db') to mock and export db.update (and any other db
methods like insert) and vi.mock('@pagespace/db/operators') to mock
eq/lt/and/or/isNotNull (and also mock each schema subpath used, e.g.,
vi.mock('@pagespace/db/schema/activityLogs') to export the schema constants
referenced by activityLogRepository); ensure the mocked symbols match the names
used in the file (db, eq, lt, activityLogs schema, etc.) so assertions like
vi.mocked(db.update) succeed.

In `@packages/lib/src/repositories/__tests__/drive-repository.test.ts`:
- Around line 7-25: The test's barrel mock is intercepting `@pagespace/db` but the
production code imports `@pagespace/db/db` (and operators/schema), so mocks are
missed; update the mocks to target the same subpath modules used at runtime by
calling vi.mock for '@pagespace/db/db' (and also '@pagespace/db/operators' and
'@pagespace/db/schema/core' if used), export the same mocked shape
(db.query.drives.findFirst, db.select, db.update, drives, eq, and) from those
mocks, and ensure the import of { db } from '@pagespace/db/db' occurs after
vi.mock so vi.mocked(db.query.drives.findFirst), db.select and db.update
reference the mocked module instance used by driveRepository and tests.

In `@packages/lib/src/repositories/__tests__/enforced-file-repository.test.ts`:
- Around line 22-67: The tests mock the barrel '@pagespace/db' but the
production module imports from subpaths, so those mocks never apply; update the
test to mock the exact subpath modules used by EnforcedFileRepository (mock
'@pagespace/db/db' to export db with query.files.findFirst,
query.filePages.findFirst and update; mock '@pagespace/db/operators' to export
eq/and; mock '@pagespace/db/schema/storage' to export files and filePages), and
ensure the mocked functions (e.g., db.query.files.findFirst,
db.query.filePages.findFirst, db.update, eq, and, files, filePages) are the ones
inspected by vi.mocked(...) in the test so the repository
(EnforcedFileRepository) calls are intercepted correctly.

In `@packages/lib/src/repositories/__tests__/page-repository.test.ts`:
- Around line 7-34: The barrel mock is bypassed because page-repository imports
subpaths; update the test to mock the actual modules used: replace
vi.mock('@pagespace/db', ...) with three mocks—vi.mock('@pagespace/db/db')
returning a fake db object with query.pages.findFirst, select, insert, update
fns, vi.mock('@pagespace/db/operators') exporting vi.fn() stubs for eq, and,
desc, isNull, inArray, isNotNull, lt, and vi.mock('@pagespace/db/schema/core')
exporting the pages symbol and PageTypeEnum; ensure the test uses
vi.mocked(db.query.pages.findFirst)/vi.mocked(db.select) against the mocked db
from '@pagespace/db/db' and import the mocked symbols to align with
pageRepository's actual imports.

In `@packages/lib/src/services/__tests__/drive-role-service.test.ts`:
- Around line 8-48: The tests fail because the code imports db and operators
from non-existent subpaths (`@pagespace/db/db` and `@pagespace/db/operators`);
either add those subpath modules or revert imports to the barrel. Fix options:
(A) Create packages/db/src/db.ts that exports the db instance and
packages/db/src/operators.ts that re-exports the drizzle-orm operators, then
update tests to mock those exact subpaths using vi.mock('@pagespace/db/db') and
vi.mock('@pagespace/db/operators') (use vi.hoisted() in the mocks to share
state), or (B) change the SUT and tests back to import from '@pagespace/db'
(barrel) and adjust the existing vi.mock(...) call accordingly so the test
intercepts the real import of db and operators. Ensure the mocked symbols (db,
driveRoles, driveMembers, eq, and, asc) match the exports you create or the
barrel so tests resolve.

In `@packages/lib/src/services/__tests__/notification-email-service.test.ts`:
- Around line 7-51: The test mocks the barrel '@pagespace/db' but the SUT
imports subpaths, so replace the single vi.mock('@pagespace/db') with explicit
mocks for the exact module specifiers the code under test imports (e.g.,
vi.mock('@pagespace/db/db') returning a mocked db with query.users.findFirst,
query.emailNotificationPreferences.findFirst, insert, etc., and
vi.mock('@pagespace/db/operators') returning eq and and, and
vi.mock('@pagespace/db/schema') or the specific schema subpath(s) returning
emailNotificationPreferences, emailNotificationLog, emailUnsubscribeTokens,
users); ensure the mocked exports include the same symbols used in the test (db,
eq, and, users, emailNotificationPreferences, emailNotificationLog,
emailUnsubscribeTokens) so calls like db.query.users.findFirst.mockResolvedValue
work, or alternatively change the SUT imports to the barrel '@pagespace/db' to
match the existing mock.

---

Duplicate comments:
In `@packages/lib/src/audit/__tests__/audit-query.test.ts`:
- Around line 26-37: The test's spies (eq, gte, lte, and, desc) are mocked on
`@pagespace/db` but the SUT and imports use `@pagespace/db/operators` so those spies
are never invoked; add a vi.mock('@pagespace/db/operators', ...) factory that
returns the same hoisted spies (eq, gte, lte, and, desc) used in the existing
`@pagespace/db` mock so the assertions (expect(eq).toHaveBeenCalledWith...,
expect(gte)..., expect(lte)..., and any expect(and)...) reference the actual
mocked functions invoked by queryAuditEvents; ensure you share the spies via
vi.hoisted so both module mocks point to the identical spy instances.

In `@packages/lib/src/auth/__tests__/token-lookup.test.ts`:
- Around line 7-23: The test mock targets the barrel '@pagespace/db' but the
code under test imports db from '@pagespace/db/db', so the mocked functions are
not applied; update the mocks to mirror the actual import graph by mocking
'@pagespace/db/db' (exporting db with query.mcpTokens.findFirst as a vi.fn()),
mock '@pagespace/db/operators' (export eq/and/isNull as vi.fn()), and mock the
schema module that exports mcpTokens (so tokenHash/revokedAt shape matches
production). Then update the test to use
vi.mocked(db.query.mcpTokens.findFirst).mockResolvedValue(...) against the
mocked db import and keep findMCPTokenByValue as the function under test.

In `@packages/lib/src/monitoring/__tests__/activity-logger.test.ts`:
- Around line 42-79: The test's module mocks don't match the actual imports used
by the SUT so vi.mocked(db.transaction) isn't a spy — update mocks to target the
real import paths used by the SUT: replace vi.mock('@pagespace/db', ...) with
vi.mock('@pagespace/db/db', ...) (so db.transaction is the mocked binding) and
add dedicated vi.mock factories for the schema/operator subpaths used (e.g.,
vi.mock('@pagespace/db/schema/activityLogs'),
vi.mock('@pagespace/db/schema/users'), vi.mock('@pagespace/db/operators') or
whatever actual subpaths export activityLogs, users, eq, sql) so activityLogs,
users, eq, sql are mocked consistently; keep the import of { db } from
'@pagespace/db/db' after the mocks and then you can safely call
vi.mocked(db.transaction).mockImplementation(...) and mock createId/init as you
already do for '@paralleldrive/cuid2'.

In `@packages/lib/src/notifications/__tests__/push-notifications.test.ts`:
- Around line 7-60: The test is mocking '@pagespace/db' but the SUT imports from
'@pagespace/db/db' (and related operators/schema modules), so the SUT receives
the real modules instead of your mock; update the test to mock the exact modules
the SUT imports: add vi.mock('@pagespace/db/db', () => ({ db: mockDb })) and
also mock '@pagespace/db/operators' (exporting eq/and) and any schema modules
under '@pagespace/db/schema/*' used by push-notifications, making sure to
re-export the same mockDb and the same named symbols
(mockDb.query.pushNotificationTokens.findFirst/findMany, db.insert, db.update,
eq, and) so calls in registerPushToken, unregisterPushToken,
unregisterAllPushTokens, sendPushNotification, and getUserPushTokens use your
mocked implementations.

In `@packages/lib/src/pages/__tests__/circular-reference-guard.test.ts`:
- Line 28: The test imports the database from the new subpath db (import { db }
from '@pagespace/db/db') but the jest mock still targets the old module path;
update the mock call that currently references '@pagespace/db' to the new
subpath '@pagespace/db/db' (and ensure the mocked exports match the actual
exported symbols from that module, e.g., the db object used in the test) so the
mock and import point to the same module.

In `@packages/lib/src/repositories/__tests__/agent-repository.test.ts`:
- Around line 7-30: The test's vi.mock('@pagespace/db', ...) stub doesn't match
imports used by the SUT (agentRepository) so db.select/db.update and chained
.from/.where/.limit mocks aren't wired; update the test to mock the actual
subpaths used by the SUT — mock '@pagespace/db/db' to provide the chained db
select/update spies, mock '@pagespace/db/schema/pages' to provide the pages
schema, and mock '@pagespace/db/operators' (or the operators module used) to
provide eq/and — follow the multi-subpath mock pattern used in
notification-email-service.test.ts and ensure setupSelectChain and
setupUpdateChain call vi.mocked on the exact db.select/db.update exports from
the '@pagespace/db/db' mock.

In `@packages/lib/src/services/__tests__/drive-member-service.test.ts`:
- Around line 10-54: Test mock targets are wrong: the file uses subpath imports
so vi.mock('@pagespace/db') no longer intercepts them. Replace the barrel mock
with mocks for the actual subpaths the production module imports — e.g.,
vi.mock('@pagespace/db/db', ...) to mock
db.query/select/insert/update/delete/execute, vi.mock('@pagespace/db/operators',
...) to provide eq/and/sql, and vi.mock('@pagespace/db/schema/driveMembers'|
'drives' | 'users' | 'userProfiles' | 'driveRoles' | 'pagePermissions' |
'pages', ...) (one per schema module used) to export the table column fixtures;
move the table/operator fixtures currently inside the barrel mock into the
corresponding subpath mocks and keep the existing import of db from
'@pagespace/db/db' at Line 54 unchanged so mockDb.select.mockReturnValue will
correctly intercept calls from the tested module.

In `@packages/lib/src/services/__tests__/drive-service.test.ts`:
- Around line 13-36: The test's vi.mock target doesn't match the actual import
used by the code under test: you mocked '@pagespace/db' but the test imports the
DB via the subpath import import { db } from '@pagespace/db/db' (and the
implementation under test also uses subpath exports). Fix by making the mock
cover the exact subpath(s) used—either change the vi.mock target to
'@pagespace/db/db' (or add a separate vi.mock for each subpath like
'@pagespace/db/db' and any other subpath used), or update the import in the test
to the barrel you mocked; ensure the mocked exports (db, drives, driveMembers,
eq, and, not, inArray, etc.) are provided under the same module name as the
import so the mocked db in vi.mock is actually injected into the code that
references import { db } from '@pagespace/db/db'.

---

Nitpick comments:
In `@packages/lib/src/auth/__tests__/session-service.test.ts`:
- Around line 2-7: The test imports operators directly from drizzle-orm (import
{ eq, and, isNull } from 'drizzle-orm') which is inconsistent with the project's
centralized DB API; update the import to pull these operators from
`@pagespace/db/operators` instead so it matches session-repository.ts and other
modules — replace the drizzle-orm operator import in session-service.test.ts
with an import from `@pagespace/db/operators` for eq, and, and isNull.

In `@packages/lib/src/compliance/retention/retention-engine.test.ts`:
- Around line 18-28: Remove the unused mock block vi.mock('@pagespace/db', () =>
({ ... })) from the test file retention-engine.test.ts because the SUT
(./retention-engine) and this test now import schema symbols from
`@pagespace/db/schema/`* and the mock never intercepts anything; simply delete the
entire vi.mock('@pagespace/db', ...) block so the test uses the real schema
exports (e.g., sessions, pageVersions, driveBackups) that the
expect(deleteFn).toHaveBeenCalledWith(sessions) assertions rely on.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4ad4ecb1-0f64-4664-b585-0f7ca6c0b202

📥 Commits

Reviewing files that changed from the base of the PR and between 1f74533 and e4a7589.

📒 Files selected for processing (118)
  • packages/lib/src/__tests__/cross-tenant-escalation.test.ts
  • packages/lib/src/__tests__/device-auth-utils.test.ts
  • packages/lib/src/__tests__/file-processor.test.ts
  • packages/lib/src/__tests__/notifications.test.ts
  • packages/lib/src/__tests__/page-version-service.test.ts
  • packages/lib/src/__tests__/permissions.test.ts
  • packages/lib/src/__tests__/token-lookup.test.ts
  • packages/lib/src/__tests__/version-resolver.test.ts
  • packages/lib/src/audit/__tests__/audit-query.test.ts
  • packages/lib/src/audit/__tests__/security-audit.test.ts
  • packages/lib/src/audit/audit-query.ts
  • packages/lib/src/audit/security-audit-chain-verifier.ts
  • packages/lib/src/audit/security-audit.ts
  • packages/lib/src/auth/__tests__/account-lockout.test.ts
  • packages/lib/src/auth/__tests__/device-auth-utils.test.ts
  • packages/lib/src/auth/__tests__/exchange-codes.integration.test.ts
  • packages/lib/src/auth/__tests__/magic-link-service.test.ts
  • packages/lib/src/auth/__tests__/oauth-utils-unit.test.ts
  • packages/lib/src/auth/__tests__/passkey-register-handoff.integration.test.ts
  • packages/lib/src/auth/__tests__/passkey-service.test.ts
  • packages/lib/src/auth/__tests__/pkce.integration.test.ts
  • packages/lib/src/auth/__tests__/session-repository-logging.test.ts
  • packages/lib/src/auth/__tests__/session-service.test.ts
  • packages/lib/src/auth/__tests__/token-lookup.test.ts
  • packages/lib/src/auth/__tests__/verification-utils.test.ts
  • packages/lib/src/auth/account-lockout.ts
  • packages/lib/src/auth/device-auth-utils.ts
  • packages/lib/src/auth/exchange-codes.ts
  • packages/lib/src/auth/magic-link-service.test.ts
  • packages/lib/src/auth/magic-link-service.ts
  • packages/lib/src/auth/oauth-utils.ts
  • packages/lib/src/auth/passkey-register-handoff.ts
  • packages/lib/src/auth/passkey-service.test.ts
  • packages/lib/src/auth/passkey-service.ts
  • packages/lib/src/auth/pkce.ts
  • packages/lib/src/auth/session-repository.ts
  • packages/lib/src/auth/token-lookup.ts
  • packages/lib/src/auth/verification-utils.ts
  • packages/lib/src/compliance/erasure/revoke-integration-tokens.ts
  • packages/lib/src/compliance/export/gdpr-export.ts
  • packages/lib/src/compliance/file-cleanup/orphan-detector.test.ts
  • packages/lib/src/compliance/file-cleanup/orphan-detector.ts
  • packages/lib/src/compliance/retention/monitoring-retention.test.ts
  • packages/lib/src/compliance/retention/monitoring-retention.ts
  • packages/lib/src/compliance/retention/retention-engine.test.ts
  • packages/lib/src/compliance/retention/retention-engine.ts
  • packages/lib/src/content/__tests__/version-resolver.test.ts
  • packages/lib/src/content/version-resolver.ts
  • packages/lib/src/file-processing/file-processor.ts
  • packages/lib/src/integrations/repositories/audit-repository.ts
  • packages/lib/src/integrations/repositories/config-repository.ts
  • packages/lib/src/integrations/repositories/connection-repository.ts
  • packages/lib/src/integrations/repositories/grant-repository.ts
  • packages/lib/src/integrations/repositories/provider-repository.ts
  • packages/lib/src/logging/__tests__/ai-usage-purge.test.ts
  • packages/lib/src/logging/__tests__/logger-database.test.ts
  • packages/lib/src/logging/__tests__/monitoring-purge.test.ts
  • packages/lib/src/logging/ai-usage-purge.ts
  • packages/lib/src/logging/logger-database.ts
  • packages/lib/src/logging/monitoring-purge.ts
  • packages/lib/src/monitoring/__tests__/activity-logger-compliance.test.ts
  • packages/lib/src/monitoring/__tests__/activity-logger.test.ts
  • packages/lib/src/monitoring/__tests__/hash-chain-verifier.test.ts
  • packages/lib/src/monitoring/activity-logger.ts
  • packages/lib/src/monitoring/ai-monitoring.ts
  • packages/lib/src/monitoring/hash-chain-verifier.ts
  • packages/lib/src/notifications/__tests__/notifications.test.ts
  • packages/lib/src/notifications/__tests__/push-notifications.test.ts
  • packages/lib/src/notifications/notifications.ts
  • packages/lib/src/notifications/push-notifications.ts
  • packages/lib/src/pages/__tests__/circular-reference-guard.test.ts
  • packages/lib/src/pages/circular-reference-guard.ts
  • packages/lib/src/permissions/__tests__/batch-page-permissions.test.ts
  • packages/lib/src/permissions/__tests__/drive-permissions.test.ts
  • packages/lib/src/permissions/__tests__/file-access.test.ts
  • packages/lib/src/permissions/__tests__/permission-mutations-unit.test.ts
  • packages/lib/src/permissions/__tests__/permission-mutations.test.ts
  • packages/lib/src/permissions/__tests__/permissions.test.ts
  • packages/lib/src/permissions/__tests__/zero-trust-boundaries.test.ts
  • packages/lib/src/permissions/accessible-page-ids.ts
  • packages/lib/src/permissions/file-access.ts
  • packages/lib/src/permissions/permission-mutations.ts
  • packages/lib/src/permissions/permissions.ts
  • packages/lib/src/repositories/__tests__/account-repository.test.ts
  • packages/lib/src/repositories/__tests__/activity-log-repository.test.ts
  • packages/lib/src/repositories/__tests__/agent-repository.test.ts
  • packages/lib/src/repositories/__tests__/drive-repository.test.ts
  • packages/lib/src/repositories/__tests__/enforced-file-repository.test.ts
  • packages/lib/src/repositories/__tests__/page-repository.test.ts
  • packages/lib/src/repositories/account-repository.ts
  • packages/lib/src/repositories/activity-log-repository.ts
  • packages/lib/src/repositories/agent-repository.ts
  • packages/lib/src/repositories/drive-repository.ts
  • packages/lib/src/repositories/enforced-file-repository.ts
  • packages/lib/src/repositories/page-repository.ts
  • packages/lib/src/security/__tests__/distributed-rate-limit.integration.test.ts
  • packages/lib/src/security/__tests__/jti-revocation.integration.test.ts
  • packages/lib/src/security/auth-handoff-sweep.ts
  • packages/lib/src/security/distributed-rate-limit.ts
  • packages/lib/src/security/jti-revocation.ts
  • packages/lib/src/services/__tests__/app-shell-service.integration.test.ts
  • packages/lib/src/services/__tests__/drive-member-service.test.ts
  • packages/lib/src/services/__tests__/drive-role-service.test.ts
  • packages/lib/src/services/__tests__/drive-service.test.ts
  • packages/lib/src/services/__tests__/notification-email-service.test.ts
  • packages/lib/src/services/__tests__/page-payload-service.integration.test.ts
  • packages/lib/src/services/__tests__/rate-limit-cache.integration.test.ts
  • packages/lib/src/services/app-shell-service.ts
  • packages/lib/src/services/drive-member-service.ts
  • packages/lib/src/services/drive-role-service.ts
  • packages/lib/src/services/drive-search-service.ts
  • packages/lib/src/services/drive-service.ts
  • packages/lib/src/services/notification-email-service.ts
  • packages/lib/src/services/page-payload-service.ts
  • packages/lib/src/services/page-version-service.ts
  • packages/lib/src/services/rate-limit-cache.ts
  • packages/lib/src/services/storage-repository.ts
  • packages/lib/src/services/validated-service-token.ts

Comment thread packages/lib/src/__tests__/device-auth-utils.test.ts Outdated
2witstudios and others added 4 commits April 24, 2026 09:50
Extracts @pagespace/db subpath modules (db, operators, schema/*) needed
by the lib barrel-import migration. db.ts and operators.ts re-export
from index.ts so that vi.mock('@pagespace/db', factory) in existing unit
tests continues to intercept all subpath imports without requiring 55
test files to be updated.

Also converts dynamic await import('@pagespace/db') calls in
device-auth-utils.test.ts to static imports from the appropriate
schema subpath.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Resolves merge conflicts from master (which landed pu/barrel-db-setup
independently). Restores the canonical standalone db.ts (with SSL flag
support) and operators.ts (re-exports from drizzle-orm) from master,
cleans index.ts barrel to use the same subpath pattern as master.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Source files import from precise subpaths (@pagespace/db/db, /operators,
/schema/*) but unit test files mock the barrel (@pagespace/db). This
disconnected the mock from what the code under test actually loaded,
causing 840 test failures.

The fix: register lazy factory mocks in the Vitest setup file for every
@pagespace/db subpath. Each factory spreads the real drizzle module first,
then overlays the barrel mock on top. Test files that vi.mock('@pagespace/db',
factory) have their mocked db/operators/schema automatically used by the
source files under test, without any changes to individual test files.

Also excludes rate-limit-cache.integration.test.ts from the unit run (it
requires a live PostgreSQL connection, matching the pattern of the other
excluded integration tests in this package).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/lib/src/test/setup.ts (1)

49-220: Mock-forwarding strategy looks correct; optional DRY opportunity.

The pattern — importOriginal for the real subpath, then overlaying await import('@pagespace/db') so the test's barrel mock wins — is sound:

  • When a test registers vi.mock('@pagespace/db', factory), the hoisted registration is in place before any of these factories fire, so await import('@pagespace/db') inside each factory correctly resolves to the mocked barrel.
  • When a test does not mock the barrel, ...barrel overlays real exports with themselves (no-op). Per context snippet 2, packages/db/src/schema.ts re-exports every subpath with export *, so there's no risk of a barrel re-export shadowing a differently-shaped subpath export.
  • The Record<string, unknown> cast keeps this compliant with the "no any" guideline.

The 32 near-identical blocks are verbose but largely unavoidable: vi.mock calls are statically hoisted and must use string-literal module IDs, so you can't iterate an array of subpath names. If you want to trim duplication, the factory body itself can be extracted via vi.hoisted:

♻️ Optional DRY refactor using vi.hoisted
+const { forwardToBarrel } = vi.hoisted(() => ({
+  forwardToBarrel: async (importOriginal: <T>() => Promise<T>) => {
+    const real = await importOriginal<Record<string, unknown>>();
+    const barrel = (await import('@pagespace/db')) as Record<string, unknown>;
+    return { ...real, ...barrel };
+  },
+}));
+
-vi.mock('@pagespace/db/db', async (importOriginal) => {
-  const real = await importOriginal<typeof import('@pagespace/db/db')>();
-  const barrel = await import('@pagespace/db') as Record<string, unknown>;
-  return { ...real, ...barrel };
-});
+vi.mock('@pagespace/db/db', forwardToBarrel);
+vi.mock('@pagespace/db/operators', forwardToBarrel);
+vi.mock('@pagespace/db/schema/ai', forwardToBarrel);
+// ...one line per subpath

Trade-off: you lose the per-subpath typeof import(...) annotation on real. Since the merged object is typed as the module shape regardless, that annotation is mostly documentary — but if you value it, the current explicit form is fine to keep.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/lib/src/test/setup.ts` around lines 49 - 220, The repeated vi.mock
factory bodies can be DRYed: extract the common factory function using
vi.hoisted and reuse it for each vi.mock call (keep the string-literal subpath
module IDs as-is) so you consolidate the repeated importOriginal/barrel merge
logic into a single hoisted factory; note this removes the per-subpath typeof
import(...) annotation on the local real variable but preserves behavior since
the returned object is the merged module (update vi.mock calls to reference the
hoisted factory and keep the Record<string, unknown> cast on the barrel).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/lib/src/test/setup.ts`:
- Around line 49-220: The repeated vi.mock factory bodies can be DRYed: extract
the common factory function using vi.hoisted and reuse it for each vi.mock call
(keep the string-literal subpath module IDs as-is) so you consolidate the
repeated importOriginal/barrel merge logic into a single hoisted factory; note
this removes the per-subpath typeof import(...) annotation on the local real
variable but preserves behavior since the returned object is the merged module
(update vi.mock calls to reference the hoisted factory and keep the
Record<string, unknown> cast on the barrel).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f647ead0-8124-4d7a-ba66-1f9325d5addb

📥 Commits

Reviewing files that changed from the base of the PR and between e4a7589 and 1676efd.

📒 Files selected for processing (4)
  • packages/db/src/index.ts
  • packages/lib/src/__tests__/device-auth-utils.test.ts
  • packages/lib/src/test/setup.ts
  • packages/lib/vitest.config.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/db/src/index.ts
  • packages/lib/vitest.config.ts
  • packages/lib/src/tests/device-auth-utils.test.ts

…setup

apps/processor/src/services/__tests__/siem-pipeline.e2e.test.ts directly
imports security-audit.ts from @pagespace/lib, which now uses subpath
imports (@pagespace/db/db, @pagespace/db/schema/security-audit). Without
forwarding mocks in the processor's vitest setup, those subpath imports
bypass vi.mock('@pagespace/db') and hit the real drizzle client.

Same pattern as packages/lib/src/test/setup.ts: each subpath mock factory
spreads the real module (importOriginal) then overlays the barrel mock so
test code that mocks @pagespace/db automatically intercepts all subpath
imports made by the code under test.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@2witstudios

Copy link
Copy Markdown
Owner Author

Thanks for the DRY suggestion on packages/lib/src/test/setup.ts (lines 49-220). You're right that the factory body could be extracted via vi.hoisted. Leaving it as-is for now for two reasons: (1) the verbose form keeps each mock explicitly typed at its call site, and (2) vi.mock hoisting semantics with a vi.hoisted-captured helper are subtler to reason about. The repetition is mechanical and will only need to change if new schema subpaths are added to packages/db. The processor setup (apps/processor/src/test/setup.ts) follows the same pattern — commit 41f231b — and now fixes the remaining siem-pipeline.e2e.test.ts CI failure.

@2witstudios

Copy link
Copy Markdown
Owner Author

Superseded by #1112 (consolidated all barrel import migrations into one PR)

@2witstudios
2witstudios deleted the pu/barrel-lib-migration branch April 24, 2026 17:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant