Repository navigation
[Refactor] Backend Re-architecture - #598
Conversation
WalkthroughReorganizes backend module paths (core → services/infra), introduces provider interfaces (OAuth, Email, Storage), renames AI services, adds S3/Local storage providers and EmailService, removes OpenAPI/agent-doc generators and routes, consolidates database routes, updates many import paths, and bumps version to 1.2.2. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Areas to focus review on:
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
update readme and assets
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
backend/src/services/logs/audit.service.ts (1)
169-224: Fix incorrect use of.get()result ingetStats
this.db.prepare(...).get(...)is treated elsewhere as returning a single row object, but here it’s array-destructured. That will break at runtime and make/logs/audits/statsunusable.Consider updating
getStatslike this:- const [totalLogs] = await this.db - .prepare('SELECT COUNT(*) as count FROM _audit_logs WHERE created_at >= $1') - .get(startDate.toISOString()); - - const [uniqueActors] = await this.db - .prepare('SELECT COUNT(DISTINCT actor) as count FROM _audit_logs WHERE created_at >= $1') - .get(startDate.toISOString()); - - const [uniqueModules] = await this.db - .prepare('SELECT COUNT(DISTINCT module) as count FROM _audit_logs WHERE created_at >= $1') - .get(startDate.toISOString()); + const totalLogsRow = await this.db + .prepare('SELECT COUNT(*) as count FROM _audit_logs WHERE created_at >= $1') + .get(startDate.toISOString()); + + const uniqueActorsRow = await this.db + .prepare('SELECT COUNT(DISTINCT actor) as count FROM _audit_logs WHERE created_at >= $1') + .get(startDate.toISOString()); + + const uniqueModulesRow = await this.db + .prepare('SELECT COUNT(DISTINCT module) as count FROM _audit_logs WHERE created_at >= $1') + .get(startDate.toISOString()); @@ - return { - totalLogs: parseInt(totalLogs?.count || 0), - uniqueActors: parseInt(uniqueActors?.count || 0), - uniqueModules: parseInt(uniqueModules?.count || 0), + return { + totalLogs: parseInt(totalLogsRow?.count ?? 0, 10), + uniqueActors: parseInt(uniqueActorsRow?.count ?? 0, 10), + uniqueModules: parseInt(uniqueModulesRow?.count ?? 0, 10),This matches how
.get()is used elsewhere and avoids the runtime error.backend/src/services/secrets/secret.service.ts (1)
163-199: Guard against empty updates inupdateSecretIf
UpdateSecretInputhas no fields set,updatesstays empty and the generated SQL becomesUPDATE _secrets SET WHERE id = $1, which is invalid.A simple guard avoids this edge-case failure:
async updateSecret(id: string, input: UpdateSecretInput): Promise<boolean> { @@ if (input.expiresAt !== undefined) { updates.push(`expires_at = $${paramCount++}`); values.push(input.expiresAt); } - values.push(id); - - const result = await client.query( - `UPDATE _secrets - SET ${updates.join(', ')} - WHERE id = $${paramCount}`, - values - ); + if (updates.length === 0) { + // Nothing to update; treat as no-op + logger.warn('updateSecret called with no updatable fields', { id }); + return false; + } + + values.push(id); + + const result = await client.query( + `UPDATE _secrets + SET ${updates.join(', ')} + WHERE id = $${paramCount}`, + values + );This keeps the API safe if callers accidentally pass an empty payload.
backend/src/api/routes/metadata/index.routes.ts (1)
110-110: Fix variable name typo.The variable name
sercretServiceis misspelled. It should besecretService.Apply this diff:
- const sercretService = new SecretService(); + const secretService = new SecretService();Also update line 111:
- const apiKey = await sercretService.getSecretByKey('API_KEY'); + const apiKey = await secretService.getSecretByKey('API_KEY');backend/src/providers/oauth/x.provider.ts (1)
28-47: Clarify thestateparameter contract forgenerateOAuthUrlThe method signature and interface treat
stateas optional (state?: string), but the implementation throws ifstateis falsy. This creates a gap between the type-level contract and runtime behavior: callers are allowed by TypeScript to omitstate, but will hit a runtime error.Consider either:
- Making
staterequired in both the interface and this implementation, or- Allowing
stateto be omitted and handling that case gracefully here (e.g., by generating or defaulting a value, if that fits your overall OAuth design).This will prevent surprising runtime failures and better align the types with actual behavior.
🧹 Nitpick comments (8)
backend/src/providers/email/base.provider.ts (1)
1-41: EmailProvider interface is well-structured for extensible providersThe interface cleanly separates template-based sending, optional raw sending, and capability discovery via
supportsTemplates(), and it aligns with theEmailTemplateunion.If you expect providers to pass non-string data into templates (e.g., numbers or booleans), you might consider widening
variablesto something likeRecord<string, string | number>orRecord<string, unknown>, but the current stricter typing is perfectly acceptable if templates always work with strings.backend/src/services/email/email.service.ts (1)
13-27: Consider initializing providers and using domain-specific errors forsendRawThe service correctly delegates to the underlying
EmailProvider, but there are two improvements worth considering:
Provider initialization
SinceEmailProviderexposes an optionalinitialize()hook, you may want to invoke it in the constructor (or lazily on first use) when present, e.g.:if (this.provider.initialize) { void this.provider.initialize(); }This keeps provider setup consistently encapsulated in the service.
Error type for unsupported
sendRaw
sendRawcurrently throws a plainErrorwhen the provider does not support raw sending. To keep error handling consistent with the rest of the backend (which appears to rely on structured errors likeAppError), consider throwing a domain-specific error instead, so HTTP status codes and error codes can be handled uniformly.These are not blockers but would make the service more robust and consistent.
Also applies to: 62-67
backend/src/providers/email/cloud.provider.ts (1)
47-52: EmailProvider implementation looks solid; consider centralizing template list
CloudEmailProvidercleanly implementsEmailProvider(includingsupportsTemplates) and has good validation and error mapping for the cloud API. The only maintainability concern is the hard‑codedvalidTemplateslist: it must stay in sync with theEmailTemplateunion and any backend‑side templates. Consider moving the allowed template list into a shared module (or exporting it alongsideEmailTemplate) so both the provider and any future callers derive from a single source of truth.Also applies to: 62-186
backend/src/services/storage/storage.service.ts (1)
388-412: Upload strategy + confirm flow is clean, but consider orphaned-object handlingThe provider-based
getUploadStrategy/confirmUploadflow is nicely structured and keepsStorageServiceindependent from specific backends. One behavioral edge case to be aware of: if two clients concurrently request an upload strategy for the same filename, both can receive different keys, upload successfully, but the secondconfirmUploadwill fail because the DB record already exists, leaving the second object orphaned in S3/local storage.If this matters for your use case, consider:
- Including a client-generated upload ID or nonce in the key, or
- Having
confirmUploadoptionally adopt/rename the second object instead of hard‑failing, or- Adding a periodic cleanup routine that removes objects not present in
_storage.Otherwise, the refactor and delegation to
StorageProviderlook good.Also applies to: 424-487
backend/src/providers/storage/local.provider.ts (1)
50-56: Usefs.rminstead of deprecatedfs.rmdirfor recursive deletes
deleteBucketcorrectly treats missing directories as non-fatal, butfs.rmdir(path, { recursive: true })is deprecated in recent Node versions. To avoid deprecation warnings and future breakage, consider switching to:await fs.rm(path.join(this.baseDir, bucket), { recursive: true, force: true });This preserves the current “ignore if missing” behavior via
force: true.backend/src/providers/storage/s3.provider.ts (1)
82-102: ClarifygetObjecterror semantics (missing vs. other S3 errors)
getObjectcurrently returnsnullfor any error (including permission or transient S3 issues), which is fine if callers treatnullstrictly as “not available” and don’t need to differentiate missing vs. other failures. If you ever need finer-grained behavior (or better user messaging), consider logging and rethrowing non‑404/NoSuchKeyerrors while only mapping genuine “not found” cases tonull.backend/src/services/auth/auth.service.ts (2)
65-71: Align naming with provider-based OAuth layer (optional)You’ve correctly switched the types/initialization to
*OAuthProvider.getInstance(), but the fields and comment still refer to “OAuth service”:
private googleOAuthService: GoogleOAuthProvider;etc.- Comment:
// OAuth service instances (cached singletons)To reduce confusion as more services/providers accumulate, consider renaming these to
*OAuthProviderand updating the comment, e.g.:- // OAuth service instances (cached singletons) - private googleOAuthService: GoogleOAuthProvider; + // OAuth provider instances (cached singletons) + private googleOAuthProvider: GoogleOAuthProvider;(and adjust call sites accordingly).
Also applies to: 102-108
900-918: Contract mismatch confirmed; however, current call site always provides stateVerification confirms the X provider enforces state (throws if missing), but oauth.routes.ts always generates and passes a JWT-based state token. The inconsistency exists—X requires state while the method signature suggests it's optional—but the current code path avoids the runtime error.
Since the oauth.routes.ts caller always supplies state and no other call sites were found, this is a design clarity issue rather than an active defect. Refactoring to align the contract (either enforce state for all providers or handle X specially) would prevent future surprises.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (3)
assets/mcpInstallv2.pngis excluded by!**/*.pngassets/sampleResponse.pngis excluded by!**/*.pngpackage-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (64)
CHANGELOG.md(1 hunks)README.md(3 hunks)backend/package.json(1 hunks)backend/src/api/middlewares/auth.ts(1 hunks)backend/src/api/routes/agent.ts(0 hunks)backend/src/api/routes/ai/index.routes.ts(3 hunks)backend/src/api/routes/auth/index.routes.ts(2 hunks)backend/src/api/routes/auth/oauth.routes.ts(1 hunks)backend/src/api/routes/database/advance.routes.ts(1 hunks)backend/src/api/routes/database/index.routes.ts(1 hunks)backend/src/api/routes/database/records.routes.ts(1 hunks)backend/src/api/routes/database/tables.routes.ts(1 hunks)backend/src/api/routes/functions/index.routes.ts(1 hunks)backend/src/api/routes/logs/index.routes.ts(1 hunks)backend/src/api/routes/metadata/index.routes.ts(1 hunks)backend/src/api/routes/openapi.ts(0 hunks)backend/src/api/routes/secrets/index.routes.ts(1 hunks)backend/src/api/routes/storage/index.routes.ts(1 hunks)backend/src/api/routes/usage/index.routes.ts(1 hunks)backend/src/core/documentation/agent.ts(0 hunks)backend/src/core/documentation/openapi.ts(0 hunks)backend/src/core/email/index.ts(0 hunks)backend/src/infra/socket/socket.ts(2 hunks)backend/src/providers/ai/openrouter.provider.ts(1 hunks)backend/src/providers/email/base.provider.ts(1 hunks)backend/src/providers/email/cloud.provider.ts(3 hunks)backend/src/providers/logs/cloudwatch.provider.ts(1 hunks)backend/src/providers/oauth/base.provider.ts(1 hunks)backend/src/providers/oauth/discord.provider.ts(1 hunks)backend/src/providers/oauth/facebook.provider.ts(1 hunks)backend/src/providers/oauth/github.provider.ts(1 hunks)backend/src/providers/oauth/google.provider.ts(2 hunks)backend/src/providers/oauth/index.ts(1 hunks)backend/src/providers/oauth/linkedin.provider.ts(2 hunks)backend/src/providers/oauth/microsoft.provider.ts(1 hunks)backend/src/providers/oauth/x.provider.ts(1 hunks)backend/src/providers/storage/base.provider.ts(1 hunks)backend/src/providers/storage/local.provider.ts(1 hunks)backend/src/providers/storage/s3.provider.ts(1 hunks)backend/src/server.ts(2 hunks)backend/src/services/ai/ai-config.service.ts(1 hunks)backend/src/services/ai/ai-model.service.ts(1 hunks)backend/src/services/ai/ai-usage.service.ts(1 hunks)backend/src/services/ai/chat-completion.service.ts(2 hunks)backend/src/services/ai/image-generation.service.ts(5 hunks)backend/src/services/ai/index.ts(1 hunks)backend/src/services/auth/auth-config.service.ts(1 hunks)backend/src/services/auth/auth-otp.service.ts(1 hunks)backend/src/services/auth/auth.service.ts(6 hunks)backend/src/services/auth/index.ts(1 hunks)backend/src/services/auth/oauth-config.service.ts(1 hunks)backend/src/services/database/database-advance.service.ts(1 hunks)backend/src/services/database/database-table.service.ts(1 hunks)backend/src/services/email/email.service.ts(1 hunks)backend/src/services/functions/function.service.ts(2 hunks)backend/src/services/logs/audit.service.ts(1 hunks)backend/src/services/logs/log.service.ts(1 hunks)backend/src/services/secrets/secret.service.ts(1 hunks)backend/src/services/storage/storage.service.ts(3 hunks)backend/src/types/email.ts(1 hunks)backend/src/utils/cloud-token.ts(1 hunks)backend/src/utils/seed.ts(1 hunks)backend/src/utils/validations.ts(1 hunks)package.json(1 hunks)
💤 Files with no reviewable changes (5)
- backend/src/core/email/index.ts
- backend/src/core/documentation/openapi.ts
- backend/src/api/routes/openapi.ts
- backend/src/core/documentation/agent.ts
- backend/src/api/routes/agent.ts
🧰 Additional context used
🧠 Learnings (5)
📚 Learning: 2025-11-14T18:47:06.676Z
Learnt from: Fermionic-Lyu
Repo: InsForge/InsForge PR: 585
File: frontend/src/features/database/page/FunctionsPage.tsx:57-83
Timestamp: 2025-11-14T18:47:06.676Z
Learning: In the InsForge codebase, there are two distinct types of functions: (1) database functions (SQL stored procedures/functions in PostgreSQL) which are part of the database schema and emit DATA_UPDATE events with resource type DATABASE, handled in frontend/src/features/database/page/FunctionsPage.tsx; (2) edge/serverless functions which emit DATA_UPDATE events with resource type FUNCTIONS, handled in frontend/src/features/functions/page/FunctionsPage.tsx. These are separate concepts with different resource types.
Applied to files:
backend/src/services/functions/function.service.ts
📚 Learning: 2025-10-16T01:09:15.904Z
Learnt from: Leo-rq-yu
Repo: InsForge/InsForge PR: 439
File: frontend/src/features/ai/helpers.ts:169-195
Timestamp: 2025-10-16T01:09:15.904Z
Learning: In frontend/src/features/ai/helpers.ts, the convertOpenRouterModelToOption function uses `model.name.split(':')[1]` to extract modelName. This is safe because OpenRouter predefines the name format to always include a colon, so the split operation will always return a valid value at index 1.
Applied to files:
backend/src/services/ai/ai-model.service.ts
📚 Learning: 2025-10-16T01:08:53.805Z
Learnt from: Leo-rq-yu
Repo: InsForge/InsForge PR: 439
File: frontend/src/features/ai/helpers.ts:163-166
Timestamp: 2025-10-16T01:08:53.805Z
Learning: In frontend/src/features/ai/helpers.ts, the sortModalitiesByOrder function uses a simple indexOf-based sort. The user prefers this implementation because ModalitySchema currently only includes 'text' and 'image', both of which are in the order array, so the -1 case won't occur in practice.
Applied to files:
backend/src/services/ai/index.ts
📚 Learning: 2025-11-04T05:18:26.126Z
Learnt from: Fermionic-Lyu
Repo: InsForge/InsForge PR: 553
File: docs/changelog.mdx:6-35
Timestamp: 2025-11-04T05:18:26.126Z
Learning: The InsForge JavaScript SDK repository is named "insforge-sdk-js" and is located at https://github.com/insforge/insforge-sdk-js
Applied to files:
package.json
📚 Learning: 2025-10-25T13:38:54.723Z
Learnt from: Kathuria
Repo: InsForge/InsForge PR: 525
File: i18n/README.de.md:81-83
Timestamp: 2025-10-25T13:38:54.723Z
Learning: In README files for InsForge, code blocks containing natural language prompts/messages to be sent to AI agents (e.g., instructions like "Senden Sie in Ihrem Agenten:" or "Send in your agent:") should not have a language identifier like `bash`, as they are user prompts, not code commands.
Applied to files:
README.md
🧬 Code graph analysis (20)
backend/src/services/ai/chat-completion.service.ts (1)
backend/src/services/ai/index.ts (1)
ChatCompletionService(4-4)
backend/src/providers/oauth/google.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
OAuthProvider(7-29)
backend/src/api/routes/database/index.routes.ts (1)
backend/src/api/routes/database/records.routes.ts (1)
router(260-260)
backend/src/providers/email/base.provider.ts (1)
backend/src/types/email.ts (1)
EmailTemplate(4-8)
backend/src/providers/oauth/github.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
OAuthProvider(7-29)
backend/src/providers/oauth/base.provider.ts (1)
backend/src/types/auth.ts (1)
OAuthUserData(139-154)
backend/src/providers/oauth/microsoft.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
OAuthProvider(7-29)
backend/src/api/routes/ai/index.routes.ts (2)
backend/src/services/ai/chat-completion.service.ts (1)
ChatCompletionService(13-210)backend/src/services/ai/image-generation.service.ts (1)
ImageGenerationService(14-154)
backend/src/services/email/email.service.ts (4)
backend/src/providers/email/base.provider.ts (1)
EmailProvider(7-41)backend/src/providers/email/cloud.provider.ts (1)
CloudEmailProvider(13-187)backend/src/utils/logger.ts (1)
logger(6-29)backend/src/types/email.ts (1)
EmailTemplate(4-8)
backend/src/providers/oauth/discord.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
OAuthProvider(7-29)
backend/src/providers/oauth/facebook.provider.ts (2)
backend/src/providers/oauth/index.ts (1)
FacebookOAuthProvider(5-5)backend/src/providers/oauth/base.provider.ts (1)
OAuthProvider(7-29)
backend/src/providers/storage/base.provider.ts (1)
shared-schemas/src/storage-api.schema.ts (2)
UploadStrategyResponse(62-62)DownloadStrategyResponse(64-64)
backend/src/providers/storage/local.provider.ts (3)
backend/src/providers/storage/base.provider.ts (1)
StorageProvider(7-29)shared-schemas/src/storage-api.schema.ts (2)
UploadStrategyResponse(62-62)DownloadStrategyResponse(64-64)backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)
backend/src/providers/email/cloud.provider.ts (1)
backend/src/providers/email/base.provider.ts (1)
EmailProvider(7-41)
backend/src/providers/oauth/linkedin.provider.ts (2)
backend/src/providers/oauth/index.ts (1)
LinkedInOAuthProvider(4-4)backend/src/providers/oauth/base.provider.ts (1)
OAuthProvider(7-29)
backend/src/providers/oauth/x.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
OAuthProvider(7-29)
backend/src/services/ai/image-generation.service.ts (1)
backend/src/services/ai/index.ts (1)
ImageGenerationService(5-5)
backend/src/providers/storage/s3.provider.ts (3)
backend/src/providers/storage/base.provider.ts (1)
StorageProvider(7-29)backend/src/utils/logger.ts (1)
logger(6-29)shared-schemas/src/storage-api.schema.ts (2)
UploadStrategyResponse(62-62)DownloadStrategyResponse(64-64)
backend/src/services/auth/auth.service.ts (7)
backend/src/providers/oauth/google.provider.ts (1)
GoogleOAuthProvider(13-249)backend/src/providers/oauth/github.provider.ts (1)
GitHubOAuthProvider(12-208)backend/src/providers/oauth/discord.provider.ts (1)
DiscordOAuthProvider(12-195)backend/src/providers/oauth/linkedin.provider.ts (1)
LinkedInOAuthProvider(12-240)backend/src/providers/oauth/facebook.provider.ts (1)
FacebookOAuthProvider(12-194)backend/src/providers/oauth/microsoft.provider.ts (1)
MicrosoftOAuthProvider(12-169)backend/src/providers/oauth/x.provider.ts (1)
XOAuthProvider(9-202)
backend/src/services/storage/storage.service.ts (3)
backend/src/providers/storage/base.provider.ts (1)
StorageProvider(7-29)backend/src/providers/storage/s3.provider.ts (1)
S3StorageProvider(24-313)backend/src/providers/storage/local.provider.ts (1)
LocalStorageProvider(10-103)
🔇 Additional comments (57)
package.json (1)
3-3: LGTM! Version bump aligns with the refactor.The version bump to 1.2.2 is consistent with the changelog entry and appropriate for this architecture refactor.
CHANGELOG.md (1)
3-4: LGTM! Changelog entry added for version 1.2.2.The changelog entry is appropriate for this WIP refactor. Consider adding detailed changelog items before merging.
backend/src/providers/logs/cloudwatch.provider.ts (1)
12-12: LGTM! Import path updated correctly.The import path has been correctly updated from
@/api/middleware/error.jsto@/api/middlewares/error.js, maintaining the.jsextension consistently.backend/src/api/middlewares/auth.ts (2)
2-2: LGTM! AuthService import path updated correctly.The import path has been correctly updated from
@/core/auth/auth.service.jsto@/services/auth/auth.service.js, aligning with the new services-based architecture.
6-6: LGTM! SecretService import path updated correctly.The import path has been correctly updated from
@/core/secrets/secret.service.jsto@/services/secrets/secret.service.js, aligning with the new services-based architecture.backend/src/utils/validations.ts (1)
1-1: LGTM! Import path updated correctly.The import path has been correctly updated from
@/api/middleware/errorto@/api/middlewares/error.backend/src/providers/ai/openrouter.provider.ts (1)
4-4: LGTM! Import path updated correctly.The import path has been correctly updated from
@/api/middleware/errorto@/api/middlewares/error.backend/src/services/functions/function.service.ts (2)
1-1: LGTM! DatabaseManager import path updated correctly.The import path has been correctly updated from
@/core/database/manager.jsto@/infra/database/manager.js, aligning with the new infrastructure-based architecture.
10-10: LGTM! AppError import path updated correctly across the codebase.Verification confirms the import path has been correctly updated from
@/api/middleware/error.jsto@/api/middlewares/error.jsin function.service.ts, and no remaining old import paths exist in the backend codebase.backend/src/services/auth/auth-config.service.ts (1)
2-3: LGTM! Clean import path updates.The import paths have been correctly updated to reflect the new architecture (infra for infrastructure, middlewares for middleware). The service logic remains unchanged.
backend/src/services/auth/oauth-config.service.ts (1)
2-4: LGTM! Import paths aligned with new architecture.The import path updates are consistent with the project's migration to services/infra organization. All service functionality is preserved.
backend/src/api/routes/database/records.routes.ts (1)
5-16: LGTM! Comprehensive import path migration.All import paths have been correctly updated to reflect the new organizational structure:
- Middlewares:
@/api/middlewares/*- Infrastructure:
@/infra/database/*,@/infra/socket/*- Services:
@/services/auth/*,@/services/secrets/*- Types:
@/types/socketThe route logic remains unchanged and functional.
backend/src/services/ai/image-generation.service.ts (2)
3-5: LGTM! Import paths updated for service layer.The import paths correctly reference the new service and provider locations.
14-14: Excellent rename for clarity.The rename from
ImageServicetoImageGenerationServiceis more descriptive and aligns with theChatCompletionServicenaming pattern. All internal references (lines 25, 40, 136) have been consistently updated.backend/src/utils/seed.ts (1)
1-9: LGTM! All seed imports updated correctly.The import paths have been comprehensively updated to reflect the new architecture:
- Infrastructure:
@/infra/database/*- Services:
@/services/ai/*,@/services/auth/*,@/services/secrets/*The seed logic remains intact and functional.
README.md (3)
28-28: Great addition! AI Integration feature documented.The new AI Integration feature is now properly documented in the Core Features list, making it clear that InsForge supports chat completions and image generation with OpenAI-compatible APIs.
81-83: Improved quickstart prompt.The updated prompt is clearer and more instructive, directing users to fetch the InsForge instruction doc to learn more. This aligns with the MCP integration workflow.
Based on learnings, the code block format without a language identifier is appropriate here since this is a user prompt to be sent to an AI agent, not a code command.
95-141: Excellent architecture visualization.The new Mermaid diagram effectively illustrates:
- How multiple agents (Claude, Cursor, Windsurf, etc.) connect via MCP
- The fetch-docs pattern for InsForge instructions
- Core service offerings (Storage, Auth, Database, Edge Function, AI Integration)
The accompanying Reddit-like app specification provides a concrete, relatable example for users. The styling makes the diagram visually appealing and professional.
backend/package.json (1)
19-24: LGTM! Migration scripts updated for new directory structure.Verification confirms the migrations directory exists at
backend/src/infra/database/migrations/and contains 17 SQL migration files. All migration scripts correctly specify--migrations-dir src/infra/database/migrations, ensuring node-pg-migrate operates on the new infra directory structure as intended.backend/src/providers/oauth/base.provider.ts (1)
1-29: LGTM! Clean provider interface definition.All 7 OAuth providers (Google, GitHub, Discord, LinkedIn, Facebook, Microsoft, X) correctly implement the
OAuthProviderinterface with full compliance:
- Required methods present in all providers:
generateOAuthUrl()andhandleCallback()- Optional method
handleSharedCallback()implemented in 6 providers (Microsoft intentionally omits it, which is valid since the method is optional)- All method signatures match the interface contract exactly
- Well-documented with consistent JSDoc comments
- Standardized return type ensures consistency across implementations
The interface promotes clean, predictable OAuth provider implementations across the codebase.
backend/src/services/database/database-advance.service.ts (1)
1-2: Import paths aligned with new infra/middlewares layoutDatabaseManager and AppError imports now match the refactored locations; no behavioral change in this service.
backend/src/services/database/database-table.service.ts (1)
1-2: Consistent DatabaseManager/AppError import refactorUpdated imports match the new infra and middlewares structure and keep the service behavior intact.
backend/src/services/ai/ai-usage.service.ts (1)
1-2: DatabaseManager import moved to infra moduleUsing
@/infra/database/manager.jskeeps the pooling logic the same while aligning with the new infra layout.backend/src/services/logs/audit.service.ts (1)
1-3: Audit service imports now point to infra/middlewaresImports for DatabaseManager and AppError are consistent with the new architecture; behavior is unchanged.
backend/src/services/secrets/secret.service.ts (1)
3-5: Secrets service imports updated to infra modulesDatabaseManager and EncryptionUtils now come from the shared infra layer, centralizing DB and crypto concerns without changing this service’s behavior.
backend/src/api/routes/logs/index.routes.ts (1)
2-4: Logs router now wired to services/middlewares pathsUsing
@/services/logs/*and the new@/api/middlewares/auth.jsis consistent with the backend re-architecture; route behavior is preserved.backend/src/services/ai/ai-config.service.ts (1)
1-2: AIConfigService now depends on infra DatabaseManagerSwitching to
@/infra/database/manager.jskeeps the pooling pattern identical while aligning with the new infra layer.backend/src/services/ai/ai-model.service.ts (1)
2-5: AI model service now uses provider-based client and shared helpersImporting
AIClientServicefrom@/providers/ai/openrouter.providerand helpers from./helpersfits the new provider pattern;getModels’ logic and API remain the same.backend/src/services/logs/log.service.ts (1)
2-4: Log provider import refactor looks consistentThe switch to
@/providers/logs/*imports with.jsextensions is consistent with the new provider-based logging structure and should be transparent to callers ofLogService. No behavioral issues apparent in howCloudWatchProvider/LocalFileProviderare selected or used.backend/src/api/routes/database/index.routes.ts (1)
1-13: Central database router composition is clean and correctThe new index router cleanly mounts the three sub-routers under
/tables,/records, and/advancewith explicit.jsextensions, which fits the refactored routing architecture. No issues from an express standpoint.backend/src/services/auth/auth-otp.service.ts (1)
4-5: Auth OTP imports now aligned with infra/middlewares layoutUpdating
DatabaseManagerto@/infra/database/manager.jsandAppErrorto@/api/middlewares/error.jsmatches the new layering and keeps the existing OTP transaction logic intact. No further changes required here.backend/src/api/routes/usage/index.routes.ts (1)
2-5: Usage route imports correctly follow new infra/types structureThe updated imports for
DatabaseManager, auth middlewares,SocketService, andServerEventsare consistent with the broader move toinfraandmiddlewaresdirectories and maintain the existing route behavior.backend/src/infra/socket/socket.ts (1)
4-15: SocketService import updates match refactored module layoutThe AuthService, socket type, and AppError imports have been correctly redirected to
@/services/auth/auth.service.js,@/types/socket.js, and@/api/middlewares/error.js, respectively. The surrounding SocketService logic remains intact, so this should be a no-op behaviorally.backend/src/types/email.ts (1)
1-8: EmailTemplate union is a clear, type-safe centralization of template IDsDefining
EmailTemplateas a string-literal union with inline documentation gives providers and services a single, type-safe source of truth for email templates. This is a good fit for the refactored email provider architecture.backend/src/api/routes/secrets/index.routes.ts (1)
2-5: LGTM!Import path updates are consistent and correctly reflect the new project structure.
backend/src/api/routes/auth/index.routes.ts (1)
2-40: LGTM!Import path updates correctly reflect the new project structure with consistent
.jsextensions throughout.backend/src/api/routes/auth/oauth.routes.ts (1)
2-8: LGTM!Import paths properly updated to reflect the new service and middleware organization.
backend/src/services/auth/index.ts (1)
1-4: LGTM!Clean barrel export pattern with consistent
.jsextensions for all auth service modules.backend/src/providers/oauth/linkedin.provider.ts (1)
12-28: Class rename and interface implementation look good.The rename from
LinkedInOAuthServicetoLinkedInOAuthProviderwithOAuthProviderinterface implementation aligns well with the provider-based architecture refactor.backend/src/services/ai/chat-completion.service.ts (1)
13-13: Class rename verified as complete and correct.The verification confirms:
- New class name
ChatCompletionServiceis properly declared at backend/src/services/ai/chat-completion.service.ts:13- Consumers have been updated (e.g., backend/src/api/routes/ai/index.routes.ts imports the new name)
- No orphaned references to the old
ChatServicename remain anywhere in the codebasebackend/src/providers/oauth/x.provider.ts (1)
9-26: XOAuthProvider implementation aligns with OAuthProvider contractThe singleton pattern and the concrete implementations of
generateOAuthUrl,handleCallback, andhandleSharedCallbackare consistent with theOAuthProviderinterface and provide a clear, self-contained X/Twitter OAuth flow (including PKCE and shared-key mode). No functional issues spotted in these sections.Also applies to: 82-201
backend/src/providers/oauth/index.ts (1)
1-7: Centralized OAuth provider barrel looks goodThe consolidated exports for all OAuth providers are clean and make the public surface of the OAuth module obvious. Paths and names look consistent.
backend/src/services/ai/index.ts (1)
1-13: AI services and helper barrel export is consistent and usefulThe centralized exports for AI services and helper functions give callers a single, coherent entry point to the AI module. Re-exporting modality helpers (
sortModalities,filterAndSortModalities, etc.) aligns well with the existing pattern of using simple helper-based sorting logic elsewhere in the project. Based on learnings.backend/src/api/routes/storage/index.routes.ts (1)
3-17: LGTM! Import paths updated for architectural refactor.All import path updates are consistent with the migration from
core/toservices//infra/andmiddleware/tomiddlewares/. No behavioral changes detected.backend/src/api/routes/ai/index.routes.ts (3)
2-12: LGTM! Service imports updated correctly.Import paths updated to reflect the new architecture with services in
@/services/and providers in@/providers/. The service renames (ChatService → ChatCompletionService, ImageService → ImageGenerationService) are consistent with the PR's architectural improvements.
23-23: LGTM! Service instantiation updated correctly.The instantiation of
ChatCompletionServicealigns with the new service architecture and matches the instance method usage pattern throughout the route handlers.
136-136: LGTM! Static method call updated correctly.The call to
ImageGenerationService.generate()correctly uses the static method pattern as shown in the service implementation.backend/src/providers/oauth/facebook.provider.ts (1)
4-24: LGTM! OAuth provider refactor completed correctly.The class rename from
FacebookOAuthServicetoFacebookOAuthProviderand the implementation of theOAuthProviderinterface are correctly applied. The singleton pattern is properly updated, and all required interface methods are present.backend/src/providers/oauth/github.provider.ts (1)
4-24: LGTM! GitHub provider refactor matches the new architecture.The refactoring from
GitHubOAuthServicetoGitHubOAuthProvideris consistent with the Facebook provider and correctly implements theOAuthProviderinterface with all required methods.backend/src/providers/oauth/google.provider.ts (1)
5-29: LGTM! Google provider refactor applied consistently.The migration from
GoogleOAuthServicetoGoogleOAuthProviderfollows the same pattern as other OAuth providers and correctly implements theOAuthProviderinterface.backend/src/providers/oauth/microsoft.provider.ts (1)
4-24: LGTM! Microsoft provider refactor completed correctly.The refactoring from
MicrosoftOAuthServicetoMicrosoftOAuthProvideris consistent with other providers. Note thathandleSharedCallbackis not implemented, which is acceptable as it's optional in theOAuthProviderinterface.backend/src/server.ts (2)
8-27: LGTM! Server imports updated for new architecture.All route imports updated to use consolidated
index.routes.jsfiles, and service/middleware imports reflect the newservices//infra//middlewares/structure. ThepackageJsonimport enables version reporting in the health endpoint.
164-174: LGTM! Route mounting consolidated successfully.The database routes are now mounted under a single
/api/databaseendpoint using the consolidateddatabaseRouter, which simplifies the routing structure. This aligns with the PR's goal of improving maintainability.backend/src/providers/oauth/discord.provider.ts (1)
4-24: LGTM! Discord provider refactor completes the OAuth provider migration.The refactoring from
DiscordOAuthServicetoDiscordOAuthProvideris consistent with all other OAuth providers and correctly implements theOAuthProviderinterface with all required methods.backend/src/providers/storage/base.provider.ts (1)
1-29: Well‑factored storage abstraction
StorageProvidercleanly captures the storage contract (CRUD, bucket ops, presigned strategies, existence checks) and aligns with bothLocalStorageProviderandS3StorageProvider. This should make future backends straightforward to plug in without touchingStorageService.backend/src/services/auth/auth.service.ts (2)
9-30: Import refactor looks consistent with new architecture layoutThe moved imports (DatabaseManager →
@/infra, OAuth config/services, providers,AppError,EmailService,XOAuthProvider) align with the newinfra/+providers/+services/structure and preserve the previous public APIs from this file’s perspective. No issues from this file’s usage standpoint.Also applies to: 46-49
924-954: Review comment is incorrect—Facebook OAuth implementation is working as designedThe actual
FacebookOAuthProviderimplementation correctly handles the OAuth flow:
exchangeCodeToTokencalls the correct Facebook token endpoint (https://graph.facebook.com/v21.0/oauth/access_token) with the required parameters (client_id,client_secret,code,redirect_uri)- It properly retrieves and returns the access token from the response
handleCallbackcorrectly chains the flow: it callsexchangeCodeToToken(payload.code)to obtain the token, then passes that token togetUserInfo(accessToken)getUserInfothen calls the user info endpoint (/me) with the retrieved access token—this is the expected behaviorThe
accessTokenvariable is not undefined; it is explicitly assigned from theexchangeCodeToTokenreturn value. There are no bugs preventing Facebook OAuth login from functioning.Likely an incorrect or invalid review comment.
| import { AuthRequest, verifyAdmin } from '@/api/middlewares/auth.js'; | ||
| import { FunctionService } from '@/services/functions/function.service.js'; | ||
| import { AuditService } from '@/services/logs/audit.service.js'; | ||
| import { AppError } from '@/api/middlewares/error.js'; | ||
| import logger from '@/utils/logger.js'; | ||
| import { functionUploadRequestSchema, functionUpdateRequestSchema } from '@insforge/shared-schemas'; | ||
| import { SocketService } from '@/core/socket/socket'; | ||
| import { DataUpdateResourceType, ServerEvents } from '@/core/socket/types'; | ||
| import { SocketService } from '@/infra/socket/socket'; | ||
| import { DataUpdateResourceType, ServerEvents } from '@/types/socket'; |
There was a problem hiding this comment.
Fix missing .js extensions for consistency.
Lines 8 and 9 are missing .js file extensions, which is inconsistent with the other imports in this file (lines 2-7). This could cause module resolution issues depending on your configuration.
Apply this diff:
-import { SocketService } from '@/infra/socket/socket';
-import { DataUpdateResourceType, ServerEvents } from '@/types/socket';
+import { SocketService } from '@/infra/socket/socket.js';
+import { DataUpdateResourceType, ServerEvents } from '@/types/socket.js';📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import { AuthRequest, verifyAdmin } from '@/api/middlewares/auth.js'; | |
| import { FunctionService } from '@/services/functions/function.service.js'; | |
| import { AuditService } from '@/services/logs/audit.service.js'; | |
| import { AppError } from '@/api/middlewares/error.js'; | |
| import logger from '@/utils/logger.js'; | |
| import { functionUploadRequestSchema, functionUpdateRequestSchema } from '@insforge/shared-schemas'; | |
| import { SocketService } from '@/core/socket/socket'; | |
| import { DataUpdateResourceType, ServerEvents } from '@/core/socket/types'; | |
| import { SocketService } from '@/infra/socket/socket'; | |
| import { DataUpdateResourceType, ServerEvents } from '@/types/socket'; | |
| import { AuthRequest, verifyAdmin } from '@/api/middlewares/auth.js'; | |
| import { FunctionService } from '@/services/functions/function.service.js'; | |
| import { AuditService } from '@/services/logs/audit.service.js'; | |
| import { AppError } from '@/api/middlewares/error.js'; | |
| import logger from '@/utils/logger.js'; | |
| import { functionUploadRequestSchema, functionUpdateRequestSchema } from '@insforge/shared-schemas'; | |
| import { SocketService } from '@/infra/socket/socket.js'; | |
| import { DataUpdateResourceType, ServerEvents } from '@/types/socket.js'; |
🤖 Prompt for AI Agents
In backend/src/api/routes/functions/index.routes.ts around lines 2 to 9, imports
on lines 8 and 9 are missing the .js extensions; update the import specifiers to
include the .js extension (e.g., change "@insforge/shared-schemas" to
"@insforge/shared-schemas.js" and "@/infra/socket/socket" to
"@/infra/socket/socket.js") so they match the other imports in this file and
ensure consistent module resolution.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
backend/src/providers/email/cloud.provider.ts (2)
82-94: Consider centralizing template validation to reduce maintenance burden.The
validTemplatesarray duplicates theEmailTemplatetype definition imported from@/types/email.js. If the type changes, this validation logic must be manually updated, creating a maintenance risk and potential for runtime errors.Consider one of these approaches:
Option 1: Define the valid templates as a const array in
@/types/email.jsand import it:// In @/types/email.js export const VALID_EMAIL_TEMPLATES = [ 'email-verification-code', 'email-verification-link', 'reset-password-code', 'reset-password-link', ] as const; export type EmailTemplate = typeof VALID_EMAIL_TEMPLATES[number];Then use it here:
- const validTemplates: EmailTemplate[] = [ - 'email-verification-code', - 'email-verification-link', - 'reset-password-code', - 'reset-password-link', - ]; - if (!validTemplates.includes(template)) { + if (!VALID_EMAIL_TEMPLATES.includes(template)) { throw new AppError( - `Invalid template type: ${template}. Must be one of: ${validTemplates.join(', ')}`, + `Invalid template type: ${template}. Must be one of: ${VALID_EMAIL_TEMPLATES.join(', ')}`, 400, ERROR_CODES.INVALID_INPUT ); }Option 2: If runtime validation isn't critical (TypeScript already enforces the type), you can remove this check entirely and rely on the type system.
110-110: Consider making the timeout configurable.The 10-second timeout is hardcoded. Consider adding this to the config for better flexibility, especially if different environments require different timeout values.
- timeout: 10000, // 10 second timeout + timeout: config.cloud.emailTimeout || 10000,backend/src/api/routes/metadata/index.routes.ts (1)
110-111: Consider using a singleton pattern for SecretService.A new
SecretServiceinstance is created on every request. While this works (the underlying database pool is shared via theDatabaseManagersingleton), adopting a singleton pattern like other services would reduce object allocations.Apply this pattern if you'd like to optimize:
+const secretService = new SecretService(); + router.use(verifyAdmin); // Get full metadata (default endpoint)Then replace line 110:
- const secretService = new SecretService(); - const apiKey = await secretService.getSecretByKey('API_KEY'); + const apiKey = await secretService.getSecretByKey('API_KEY');backend/src/providers/storage/local.provider.ts (1)
50-56: Consider usingfs.rminstead of deprecatedfs.rmdir.The
fs.rmdirmethod withrecursiveoption is deprecated in Node.js 14+ in favor offs.rm.Apply this diff:
async deleteBucket(bucket: string): Promise<void> { try { - await fs.rmdir(path.join(this.baseDir, bucket), { recursive: true }); + await fs.rm(path.join(this.baseDir, bucket), { recursive: true }); } catch { // Directory might not exist } }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (33)
backend/src/api/middlewares/error.ts(1 hunks)backend/src/api/middlewares/rate-limiters.ts(1 hunks)backend/src/api/routes/ai/index.routes.ts(3 hunks)backend/src/api/routes/database/advance.routes.ts(1 hunks)backend/src/api/routes/database/records.routes.ts(1 hunks)backend/src/api/routes/database/tables.routes.ts(1 hunks)backend/src/api/routes/functions/index.routes.ts(1 hunks)backend/src/api/routes/metadata/index.routes.ts(2 hunks)backend/src/api/routes/storage/index.routes.ts(1 hunks)backend/src/providers/ai/openrouter.provider.ts(1 hunks)backend/src/providers/email/cloud.provider.ts(3 hunks)backend/src/providers/oauth/base.provider.ts(1 hunks)backend/src/providers/oauth/discord.provider.ts(1 hunks)backend/src/providers/oauth/facebook.provider.ts(1 hunks)backend/src/providers/oauth/github.provider.ts(1 hunks)backend/src/providers/oauth/google.provider.ts(2 hunks)backend/src/providers/oauth/linkedin.provider.ts(2 hunks)backend/src/providers/oauth/microsoft.provider.ts(1 hunks)backend/src/providers/oauth/x.provider.ts(1 hunks)backend/src/providers/storage/local.provider.ts(1 hunks)backend/src/server.ts(2 hunks)backend/src/services/ai/ai-model.service.ts(1 hunks)backend/src/services/ai/chat-completion.service.ts(1 hunks)backend/src/services/ai/helpers.ts(1 hunks)backend/src/services/ai/image-generation.service.ts(4 hunks)backend/src/services/auth/auth.service.ts(6 hunks)backend/src/services/database/database-advance.service.ts(2 hunks)backend/src/services/database/database-table.service.ts(2 hunks)backend/src/services/storage/storage.service.ts(3 hunks)backend/src/utils/cloud-token.ts(1 hunks)backend/src/utils/seed.ts(1 hunks)backend/src/utils/sql-parser.ts(1 hunks)backend/src/utils/validations.ts(1 hunks)
✅ Files skipped from review due to trivial changes (3)
- backend/src/api/middlewares/error.ts
- backend/src/api/middlewares/rate-limiters.ts
- backend/src/services/database/database-advance.service.ts
🚧 Files skipped from review as they are similar to previous changes (12)
- backend/src/services/database/database-table.service.ts
- backend/src/utils/validations.ts
- backend/src/api/routes/database/records.routes.ts
- backend/src/api/routes/database/advance.routes.ts
- backend/src/api/routes/ai/index.routes.ts
- backend/src/providers/ai/openrouter.provider.ts
- backend/src/api/routes/functions/index.routes.ts
- backend/src/services/ai/image-generation.service.ts
- backend/src/providers/oauth/linkedin.provider.ts
- backend/src/utils/seed.ts
- backend/src/providers/oauth/microsoft.provider.ts
- backend/src/providers/oauth/base.provider.ts
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-10-16T01:09:15.904Z
Learnt from: Leo-rq-yu
Repo: InsForge/InsForge PR: 439
File: frontend/src/features/ai/helpers.ts:169-195
Timestamp: 2025-10-16T01:09:15.904Z
Learning: In frontend/src/features/ai/helpers.ts, the convertOpenRouterModelToOption function uses `model.name.split(':')[1]` to extract modelName. This is safe because OpenRouter predefines the name format to always include a colon, so the split operation will always return a valid value at index 1.
Applied to files:
backend/src/services/ai/helpers.tsbackend/src/services/ai/ai-model.service.ts
📚 Learning: 2025-10-16T01:08:53.805Z
Learnt from: Leo-rq-yu
Repo: InsForge/InsForge PR: 439
File: frontend/src/features/ai/helpers.ts:163-166
Timestamp: 2025-10-16T01:08:53.805Z
Learning: In frontend/src/features/ai/helpers.ts, the sortModalitiesByOrder function uses a simple indexOf-based sort. The user prefers this implementation because ModalitySchema currently only includes 'text' and 'image', both of which are in the order array, so the -1 case won't occur in practice.
Applied to files:
backend/src/services/ai/helpers.ts
🧬 Code graph analysis (11)
backend/src/providers/oauth/x.provider.ts (2)
backend/src/providers/oauth/index.ts (1)
XOAuthProvider(7-7)backend/src/providers/oauth/base.provider.ts (1)
OAuthProvider(7-29)
backend/src/services/ai/chat-completion.service.ts (1)
backend/src/services/ai/index.ts (1)
ChatCompletionService(4-4)
backend/src/providers/oauth/discord.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
OAuthProvider(7-29)
backend/src/providers/oauth/facebook.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
OAuthProvider(7-29)
backend/src/services/storage/storage.service.ts (3)
backend/src/providers/storage/base.provider.ts (1)
StorageProvider(7-29)backend/src/providers/storage/s3.provider.ts (1)
S3StorageProvider(24-313)backend/src/providers/storage/local.provider.ts (1)
LocalStorageProvider(10-103)
backend/src/providers/email/cloud.provider.ts (1)
backend/src/providers/email/base.provider.ts (1)
EmailProvider(7-41)
backend/src/api/routes/metadata/index.routes.ts (1)
backend/src/services/secrets/secret.service.ts (1)
SecretService(32-410)
backend/src/services/auth/auth.service.ts (7)
backend/src/providers/oauth/google.provider.ts (1)
GoogleOAuthProvider(13-249)backend/src/providers/oauth/github.provider.ts (1)
GitHubOAuthProvider(12-208)backend/src/providers/oauth/discord.provider.ts (1)
DiscordOAuthProvider(12-195)backend/src/providers/oauth/linkedin.provider.ts (1)
LinkedInOAuthProvider(12-240)backend/src/providers/oauth/facebook.provider.ts (1)
FacebookOAuthProvider(12-194)backend/src/providers/oauth/microsoft.provider.ts (1)
MicrosoftOAuthProvider(12-169)backend/src/providers/oauth/x.provider.ts (1)
XOAuthProvider(9-202)
backend/src/providers/oauth/github.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
OAuthProvider(7-29)
backend/src/providers/oauth/google.provider.ts (1)
backend/src/providers/oauth/base.provider.ts (1)
OAuthProvider(7-29)
backend/src/providers/storage/local.provider.ts (3)
backend/src/providers/storage/base.provider.ts (1)
StorageProvider(7-29)shared-schemas/src/storage-api.schema.ts (2)
UploadStrategyResponse(62-62)DownloadStrategyResponse(64-64)backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: E2E Tests
- GitHub Check: CI Pre-merge Check
🔇 Additional comments (31)
backend/src/utils/cloud-token.ts (1)
2-3: Import paths updated correctly with.jsextensions.The import paths have been successfully updated to reflect the new backend structure:
@/api/middleware/error→@/api/middlewares/error.js@/types/error-constants→@/types/error-constants.jsBoth imports now include the
.jsextension, addressing the consistency concern raised in the previous review. The changes correctly align with the new directory layout and ESM module resolution requirements.backend/src/services/ai/helpers.ts (1)
1-1: LGTM!The explicit
.jsextension aligns with ES module best practices and the broader refactoring goal of normalizing import paths.backend/src/services/ai/chat-completion.service.ts (1)
2-4: LGTM!The updated import paths and class rename to
ChatCompletionServicealign well with the refactoring objectives, improving clarity and maintainability.Also applies to: 13-13
backend/src/providers/email/cloud.provider.ts (2)
1-13: LGTM! Clean implementation of the provider interface.The import paths have been correctly updated to the new module structure, and the class properly implements the
EmailProviderinterface frombase.provider.ts.
47-52: LGTM! Correctly implements interface requirement.The
supportsTemplates()method properly implements the required interface method and accurately returnstruefor this cloud-based provider.backend/src/services/ai/ai-model.service.ts (1)
1-5: Import verification passed—all paths resolve correctly.All four imports in the file have been verified:
isCloudEnvironmentcorrectly exported from@/utils/environment.jsAIClientServicecorrectly exported from@/providers/ai/openrouter.provider.jsRawOpenRouterModelcorrectly exported from@/types/ai.jscalculatePriceLevel,filterAndSortModalities,getProviderOrdercorrectly exported from./helpers.jsThe import path updates are sound, the refactor structure is consistent, and the code is ready.
backend/src/utils/sql-parser.ts (1)
3-3: ESM import path updated correctly and verified consistent across codebase.The
.jsextension on line 3 is correct for ESM and TypeScript. Verification confirms all local module imports inbackend/src/consistently use.jsextensions, confirming the refactoring is complete and uniform.backend/src/api/routes/database/tables.routes.ts (1)
2-8: LGTM! Import paths successfully updated.All imports now correctly reference the new module structure with explicit
.jsextensions. The previous concern about the missing.jsextension on the AuditService import has been resolved.backend/src/api/routes/metadata/index.routes.ts (1)
2-13: LGTM! Import consistency restored.All imports now include explicit
.jsextensions, resolving the previous review concerns about lines 12-13. The module paths correctly reflect the new architecture.backend/src/providers/oauth/x.provider.ts (1)
9-28: LGTM! Provider refactor correctly implemented.The class has been successfully renamed to
XOAuthProviderand now implements theOAuthProviderinterface. The singleton pattern and method signature (generateOAuthUrl) align with the new provider-based architecture.backend/src/providers/oauth/facebook.provider.ts (1)
12-29: LGTM! Consistent provider pattern applied.The refactor from
FacebookOAuthServicetoFacebookOAuthProviderimplementing theOAuthProviderinterface is consistent with the broader OAuth provider architecture changes across the codebase.backend/src/providers/oauth/discord.provider.ts (1)
12-29: LGTM! Provider architecture consistently applied.The renaming and interface implementation align with the standardized OAuth provider pattern being applied across all providers in this refactor.
backend/src/api/routes/storage/index.routes.ts (1)
3-17: LGTM! Import paths successfully migrated.All import paths have been correctly updated to reflect the new architecture (
services/,infra/,middlewares/) with explicit.jsextensions throughout.backend/src/server.ts (2)
8-26: LGTM! Router imports successfully consolidated.All route imports now use the
index.routes.jspattern and reference the correct paths. Infrastructure imports (DatabaseManager,LogService,StorageService,SocketService) correctly point to their new locations ininfra/andservices/.
164-174: LGTM! Database routes successfully consolidated.The consolidation of database routes under
/api/database(line 166) aligns with the PR's objective to normalize and organize the backend structure. The removal of deprecated OpenAPI and agent documentation routes is also consistent with the stated goals.backend/src/providers/oauth/github.provider.ts (1)
12-29: LGTM! Provider pattern consistently implemented.The refactor to
GitHubOAuthProviderimplementingOAuthProvideris consistent with the standardized provider architecture applied across all OAuth integrations in this PR.backend/src/providers/oauth/google.provider.ts (5)
1-29: LGTM! Clean refactoring to provider-based architecture.The class correctly implements the
OAuthProviderinterface and the singleton pattern has been properly updated with the new class name.
34-81: LGTM!The OAuth URL generation logic correctly handles both shared key and standard OAuth flows.
86-202: LGTM!The token exchange and verification methods correctly handle caching, deduplication, and error cases.
207-229: LGTM!The callback handler correctly implements the
OAuthProviderinterface and properly transforms provider-specific data to the generic format.
234-248: LGTM!The shared callback handler correctly transforms the payload data with defensive type coercion.
backend/src/services/storage/storage.service.ts (4)
1-45: LGTM! Provider-based architecture properly implemented.The service correctly instantiates either S3StorageProvider or LocalStorageProvider based on the environment configuration.
389-412: LGTM!The method correctly generates the next available key using the (1), (2), (3) pattern before delegating to the storage provider.
414-422: LGTM!The method correctly determines bucket visibility internally and passes it to the storage provider.
119-563: LGTM! Comprehensive provider delegation.All storage operations correctly delegate to the provider while maintaining business logic (validation, metadata management, access control) at the service layer.
backend/src/providers/storage/local.provider.ts (3)
58-61: LGTM!Correctly indicates that local storage does not support presigned URLs.
63-90: LGTM!The upload and download strategies correctly return direct URLs with proper encoding for local storage operations.
92-102: LGTM!The file existence verification correctly uses
fs.accesswith appropriate error handling.backend/src/services/auth/auth.service.ts (3)
1-71: LGTM! Consistent provider-based refactoring.All imports and field declarations have been correctly updated to use the new provider-based architecture.
73-111: LGTM!All OAuth providers are correctly initialized using their singleton
getInstance()methods.
900-1008: LGTM! OAuth provider integration complete.All three OAuth methods correctly delegate to the appropriate provider implementations with proper error handling for unsupported providers.
| } from '@insforge/shared-schemas'; | ||
| import logger from '@/utils/logger.js'; | ||
| import { ChatCompletionOptions } from '@/types/ai'; | ||
| import { ChatCompletionOptions } from '@/types/ai.js'; |
There was a problem hiding this comment.
Use type-only import for ChatCompletionOptions.
Since ChatCompletionOptions is only used as a type annotation (lines 81, 144), it should be imported as a type-only import to prevent unnecessary runtime bundling.
Apply this diff:
-import { ChatCompletionOptions } from '@/types/ai.js';
+import type { ChatCompletionOptions } from '@/types/ai.js';📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import { ChatCompletionOptions } from '@/types/ai.js'; | |
| import type { ChatCompletionOptions } from '@/types/ai.js'; |
🤖 Prompt for AI Agents
In backend/src/services/ai/chat-completion.service.ts around line 11, the import
"import { ChatCompletionOptions } from '@/types/ai.js';" brings in
ChatCompletionOptions at runtime even though it's used only for type annotations
(lines ~81 and ~144); change it to a type-only import (e.g., "import type {
ChatCompletionOptions } from '@/types/ai.js';") so the type is erased at emit
and not included in the runtime bundle.
Summary
This PR refactors the backend service into a more maintainable, open-source friendly architecture that follows the best industrial practices.
The backend directory now follows this structure:
with routes/services file names normalized to keep consistency. Providers are for external services and it is now very extendable.
Also removed deprecated openapi and agent doc files.
How did you test this change?
Tested locally
Summary by CodeRabbit
New Features
Refactor
Chores
Bug Fixes