@friggframework/core 2.0.0--canary.608.e6b65ff.0 → 2.0.0--canary.610.ca077d5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/application/commands/user-commands.js +29 -0
  2. package/generated/prisma-mongodb/edge.js +2 -2
  3. package/generated/prisma-mongodb/index.js +2 -2
  4. package/generated/prisma-mongodb/package.json +1 -1
  5. package/generated/prisma-mongodb/schema.prisma +1 -0
  6. package/generated/prisma-mongodb/wasm.js +2 -2
  7. package/generated/prisma-postgresql/edge.js +2 -2
  8. package/generated/prisma-postgresql/index.js +2 -2
  9. package/generated/prisma-postgresql/package.json +1 -1
  10. package/generated/prisma-postgresql/schema.prisma +1 -0
  11. package/generated/prisma-postgresql/wasm.js +2 -2
  12. package/index.js +0 -10
  13. package/integrations/integration-base.js +0 -20
  14. package/integrations/integration-router.js +1 -24
  15. package/integrations/use-cases/create-integration.js +2 -15
  16. package/integrations/use-cases/get-integration-instance.js +3 -10
  17. package/integrations/use-cases/update-integration.js +2 -16
  18. package/modules/requester/oauth-2.js +2 -2
  19. package/modules/requester/requester.js +12 -7
  20. package/package.json +5 -5
  21. package/prisma-mongodb/schema.prisma +1 -0
  22. package/prisma-postgresql/migrations/20260625000000_add_user_organization_id_index/migration.sql +2 -0
  23. package/prisma-postgresql/schema.prisma +1 -0
  24. package/queues/queuer-util.js +1 -7
  25. package/user/repositories/user-repository-documentdb.js +17 -0
  26. package/user/repositories/user-repository-interface.js +13 -0
  27. package/user/repositories/user-repository-mongo.js +15 -0
  28. package/user/repositories/user-repository-postgres.js +17 -0
  29. package/handlers/workers/user-action-worker.js +0 -146
  30. package/integrations/use-cases/dispatch-integration-event.js +0 -54
@@ -169,6 +169,35 @@ function createUserCommands() {
169
169
  }
170
170
  },
171
171
 
172
+ /**
173
+ * Find all individual users linked to an organization user
174
+ * @param {string} organizationUserId - Organization user ID to search for
175
+ * @returns {Promise<Object[]>} Array of individual user objects (empty if none)
176
+ */
177
+ async findIndividualUsersByOrganizationId(organizationUserId) {
178
+ try {
179
+ if (!organizationUserId) {
180
+ const error = new Error('organizationUserId is required');
181
+ error.code = 'INVALID_USER_DATA';
182
+ throw error;
183
+ }
184
+
185
+ const users =
186
+ await userRepository.findIndividualUsersByOrganizationId(
187
+ organizationUserId
188
+ );
189
+
190
+ return (users || []).map((user) => ({
191
+ id: user._id?.toString() || user.id,
192
+ username: user.username,
193
+ email: user.email,
194
+ appUserId: user.appUserId,
195
+ }));
196
+ } catch (error) {
197
+ return mapErrorToResponse(error);
198
+ }
199
+ },
200
+
172
201
  /**
173
202
  * Find an organization user by their ID
174
203
  * @param {string} userId - Organization user ID to search for
@@ -309,8 +309,8 @@ const config = {
309
309
  }
310
310
  }
311
311
  },
312
- "inlineSchema": "// Frigg Framework - Prisma Schema\n// MongoDB database schema for enterprise integration platform\n// Migration from Mongoose ODM to Prisma ORM\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-mongodb\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"mongodb\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId String? @db.ObjectId\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@map(\"User\")\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId String @db.ObjectId\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n @@map(\"Token\")\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n @@map(\"Credential\")\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n credentialId String? @db.ObjectId\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with scalar lists\n integrations Integration[] @relation(\"IntegrationEntities\", fields: [integrationIds], references: [id])\n integrationIds String[] @db.ObjectId\n\n syncs Sync[] @relation(\"SyncEntities\", fields: [syncIds], references: [id])\n syncIds String[] @db.ObjectId\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n @@map(\"Entity\")\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(ENABLED)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via explicit scalar list)\n entities Entity[] @relation(\"IntegrationEntities\", fields: [entityIds], references: [id])\n entityIds String[] @db.ObjectId\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n @@map(\"Integration\")\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n @@map(\"IntegrationMapping\")\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n // Core references\n userId String @db.ObjectId\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support\n childProcesses String[] @db.ObjectId\n parentProcessId String? @db.ObjectId\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@map(\"Process\")\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String? @db.ObjectId\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via explicit scalar list)\n entities Entity[] @relation(\"SyncEntities\", fields: [entityIds], references: [id])\n entityIds String[] @db.ObjectId\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n @@map(\"Sync\")\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n syncId String? @db.ObjectId\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId String @db.ObjectId\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n @@map(\"DataIdentifier\")\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n @@map(\"Association\")\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n associationId String @db.ObjectId\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId String @db.ObjectId\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n @@map(\"AssociationObject\")\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n state Json?\n\n @@map(\"State\")\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n connectionId String?\n\n @@index([connectionId])\n @@map(\"WebsocketConnection\")\n}\n",
313
- "inlineSchemaHash": "19d47c2df802693a622b31a2a012691eb073ad03d7cdb199b2098ae69f894a9c",
312
+ "inlineSchema": "// Frigg Framework - Prisma Schema\n// MongoDB database schema for enterprise integration platform\n// Migration from Mongoose ODM to Prisma ORM\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-mongodb\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"mongodb\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId String? @db.ObjectId\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@index([organizationId])\n @@map(\"User\")\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId String @db.ObjectId\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n @@map(\"Token\")\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n @@map(\"Credential\")\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n credentialId String? @db.ObjectId\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with scalar lists\n integrations Integration[] @relation(\"IntegrationEntities\", fields: [integrationIds], references: [id])\n integrationIds String[] @db.ObjectId\n\n syncs Sync[] @relation(\"SyncEntities\", fields: [syncIds], references: [id])\n syncIds String[] @db.ObjectId\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n @@map(\"Entity\")\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(ENABLED)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via explicit scalar list)\n entities Entity[] @relation(\"IntegrationEntities\", fields: [entityIds], references: [id])\n entityIds String[] @db.ObjectId\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n @@map(\"Integration\")\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n @@map(\"IntegrationMapping\")\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n // Core references\n userId String @db.ObjectId\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support\n childProcesses String[] @db.ObjectId\n parentProcessId String? @db.ObjectId\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@map(\"Process\")\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String? @db.ObjectId\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via explicit scalar list)\n entities Entity[] @relation(\"SyncEntities\", fields: [entityIds], references: [id])\n entityIds String[] @db.ObjectId\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n @@map(\"Sync\")\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n syncId String? @db.ObjectId\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId String @db.ObjectId\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n @@map(\"DataIdentifier\")\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n @@map(\"Association\")\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n associationId String @db.ObjectId\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId String @db.ObjectId\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n @@map(\"AssociationObject\")\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n state Json?\n\n @@map(\"State\")\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n connectionId String?\n\n @@index([connectionId])\n @@map(\"WebsocketConnection\")\n}\n",
313
+ "inlineSchemaHash": "ca2eeda0b55c6d306dd26cb0808456ec98bb3111bf37df570423ecf6829e5907",
314
314
  "copyEngine": true
315
315
  }
316
316
  config.dirname = '/'
@@ -310,8 +310,8 @@ const config = {
310
310
  }
311
311
  }
312
312
  },
313
- "inlineSchema": "// Frigg Framework - Prisma Schema\n// MongoDB database schema for enterprise integration platform\n// Migration from Mongoose ODM to Prisma ORM\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-mongodb\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"mongodb\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId String? @db.ObjectId\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@map(\"User\")\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId String @db.ObjectId\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n @@map(\"Token\")\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n @@map(\"Credential\")\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n credentialId String? @db.ObjectId\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with scalar lists\n integrations Integration[] @relation(\"IntegrationEntities\", fields: [integrationIds], references: [id])\n integrationIds String[] @db.ObjectId\n\n syncs Sync[] @relation(\"SyncEntities\", fields: [syncIds], references: [id])\n syncIds String[] @db.ObjectId\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n @@map(\"Entity\")\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(ENABLED)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via explicit scalar list)\n entities Entity[] @relation(\"IntegrationEntities\", fields: [entityIds], references: [id])\n entityIds String[] @db.ObjectId\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n @@map(\"Integration\")\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n @@map(\"IntegrationMapping\")\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n // Core references\n userId String @db.ObjectId\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support\n childProcesses String[] @db.ObjectId\n parentProcessId String? @db.ObjectId\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@map(\"Process\")\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String? @db.ObjectId\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via explicit scalar list)\n entities Entity[] @relation(\"SyncEntities\", fields: [entityIds], references: [id])\n entityIds String[] @db.ObjectId\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n @@map(\"Sync\")\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n syncId String? @db.ObjectId\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId String @db.ObjectId\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n @@map(\"DataIdentifier\")\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n @@map(\"Association\")\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n associationId String @db.ObjectId\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId String @db.ObjectId\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n @@map(\"AssociationObject\")\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n state Json?\n\n @@map(\"State\")\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n connectionId String?\n\n @@index([connectionId])\n @@map(\"WebsocketConnection\")\n}\n",
314
- "inlineSchemaHash": "19d47c2df802693a622b31a2a012691eb073ad03d7cdb199b2098ae69f894a9c",
313
+ "inlineSchema": "// Frigg Framework - Prisma Schema\n// MongoDB database schema for enterprise integration platform\n// Migration from Mongoose ODM to Prisma ORM\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-mongodb\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"mongodb\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId String? @db.ObjectId\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@index([organizationId])\n @@map(\"User\")\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId String @db.ObjectId\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n @@map(\"Token\")\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n @@map(\"Credential\")\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n credentialId String? @db.ObjectId\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with scalar lists\n integrations Integration[] @relation(\"IntegrationEntities\", fields: [integrationIds], references: [id])\n integrationIds String[] @db.ObjectId\n\n syncs Sync[] @relation(\"SyncEntities\", fields: [syncIds], references: [id])\n syncIds String[] @db.ObjectId\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n @@map(\"Entity\")\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(ENABLED)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via explicit scalar list)\n entities Entity[] @relation(\"IntegrationEntities\", fields: [entityIds], references: [id])\n entityIds String[] @db.ObjectId\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n @@map(\"Integration\")\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n @@map(\"IntegrationMapping\")\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n // Core references\n userId String @db.ObjectId\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support\n childProcesses String[] @db.ObjectId\n parentProcessId String? @db.ObjectId\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@map(\"Process\")\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String? @db.ObjectId\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via explicit scalar list)\n entities Entity[] @relation(\"SyncEntities\", fields: [entityIds], references: [id])\n entityIds String[] @db.ObjectId\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n @@map(\"Sync\")\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n syncId String? @db.ObjectId\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId String @db.ObjectId\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n @@map(\"DataIdentifier\")\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n @@map(\"Association\")\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n associationId String @db.ObjectId\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId String @db.ObjectId\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n @@map(\"AssociationObject\")\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n state Json?\n\n @@map(\"State\")\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n connectionId String?\n\n @@index([connectionId])\n @@map(\"WebsocketConnection\")\n}\n",
314
+ "inlineSchemaHash": "ca2eeda0b55c6d306dd26cb0808456ec98bb3111bf37df570423ecf6829e5907",
315
315
  "copyEngine": true
316
316
  }
317
317
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "name": "prisma-client-757bb4d524e2bac575468af19db9a259a34b200e05383b08c2371dfef12e4230",
2
+ "name": "prisma-client-172a5af2a8d70a83c3e97ba7fd5b0e6de205fad33b20407ee7fe14a85e9a8d03",
3
3
  "main": "index.js",
4
4
  "types": "index.d.ts",
5
5
  "browser": "default.js",
@@ -59,6 +59,7 @@ model User {
59
59
  @@unique([username, appUserId])
60
60
  @@index([type])
61
61
  @@index([appUserId])
62
+ @@index([organizationId])
62
63
  @@map("User")
63
64
  }
64
65
 
@@ -309,8 +309,8 @@ const config = {
309
309
  }
310
310
  }
311
311
  },
312
- "inlineSchema": "// Frigg Framework - Prisma Schema\n// MongoDB database schema for enterprise integration platform\n// Migration from Mongoose ODM to Prisma ORM\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-mongodb\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"mongodb\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId String? @db.ObjectId\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@map(\"User\")\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId String @db.ObjectId\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n @@map(\"Token\")\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n @@map(\"Credential\")\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n credentialId String? @db.ObjectId\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with scalar lists\n integrations Integration[] @relation(\"IntegrationEntities\", fields: [integrationIds], references: [id])\n integrationIds String[] @db.ObjectId\n\n syncs Sync[] @relation(\"SyncEntities\", fields: [syncIds], references: [id])\n syncIds String[] @db.ObjectId\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n @@map(\"Entity\")\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(ENABLED)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via explicit scalar list)\n entities Entity[] @relation(\"IntegrationEntities\", fields: [entityIds], references: [id])\n entityIds String[] @db.ObjectId\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n @@map(\"Integration\")\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n @@map(\"IntegrationMapping\")\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n // Core references\n userId String @db.ObjectId\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support\n childProcesses String[] @db.ObjectId\n parentProcessId String? @db.ObjectId\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@map(\"Process\")\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String? @db.ObjectId\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via explicit scalar list)\n entities Entity[] @relation(\"SyncEntities\", fields: [entityIds], references: [id])\n entityIds String[] @db.ObjectId\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n @@map(\"Sync\")\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n syncId String? @db.ObjectId\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId String @db.ObjectId\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n @@map(\"DataIdentifier\")\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n @@map(\"Association\")\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n associationId String @db.ObjectId\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId String @db.ObjectId\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n @@map(\"AssociationObject\")\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n state Json?\n\n @@map(\"State\")\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n connectionId String?\n\n @@index([connectionId])\n @@map(\"WebsocketConnection\")\n}\n",
313
- "inlineSchemaHash": "19d47c2df802693a622b31a2a012691eb073ad03d7cdb199b2098ae69f894a9c",
312
+ "inlineSchema": "// Frigg Framework - Prisma Schema\n// MongoDB database schema for enterprise integration platform\n// Migration from Mongoose ODM to Prisma ORM\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-mongodb\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"mongodb\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId String? @db.ObjectId\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@index([organizationId])\n @@map(\"User\")\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId String @db.ObjectId\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n @@map(\"Token\")\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n @@map(\"Credential\")\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n credentialId String? @db.ObjectId\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with scalar lists\n integrations Integration[] @relation(\"IntegrationEntities\", fields: [integrationIds], references: [id])\n integrationIds String[] @db.ObjectId\n\n syncs Sync[] @relation(\"SyncEntities\", fields: [syncIds], references: [id])\n syncIds String[] @db.ObjectId\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n @@map(\"Entity\")\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n userId String? @db.ObjectId\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(ENABLED)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via explicit scalar list)\n entities Entity[] @relation(\"IntegrationEntities\", fields: [entityIds], references: [id])\n entityIds String[] @db.ObjectId\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n @@map(\"Integration\")\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n @@map(\"IntegrationMapping\")\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n\n // Core references\n userId String @db.ObjectId\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support\n childProcesses String[] @db.ObjectId\n parentProcessId String? @db.ObjectId\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@map(\"Process\")\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String? @db.ObjectId\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via explicit scalar list)\n entities Entity[] @relation(\"SyncEntities\", fields: [entityIds], references: [id])\n entityIds String[] @db.ObjectId\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n @@map(\"Sync\")\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n syncId String? @db.ObjectId\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId String @db.ObjectId\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n @@map(\"DataIdentifier\")\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n integrationId String @db.ObjectId\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n @@map(\"Association\")\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n associationId String @db.ObjectId\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId String @db.ObjectId\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n @@map(\"AssociationObject\")\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n state Json?\n\n @@map(\"State\")\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n connectionId String?\n\n @@index([connectionId])\n @@map(\"WebsocketConnection\")\n}\n",
313
+ "inlineSchemaHash": "ca2eeda0b55c6d306dd26cb0808456ec98bb3111bf37df570423ecf6829e5907",
314
314
  "copyEngine": true
315
315
  }
316
316
  config.dirname = '/'
@@ -331,8 +331,8 @@ const config = {
331
331
  }
332
332
  }
333
333
  },
334
- "inlineSchema": "// Frigg Framework - Prisma Schema (PostgreSQL)\n// PostgreSQL database schema for enterprise integration platform\n// Converted from MongoDB schema for relational database support\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-postgresql\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id Int @id @default(autoincrement())\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId Int?\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id Int @id @default(autoincrement())\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id Int @id @default(autoincrement())\n credentialId Int?\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with implicit join tables\n integrations Integration[]\n syncs Sync[]\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(ENABLED)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id Int @id @default(autoincrement())\n integrationId Int?\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id Int @id @default(autoincrement())\n syncId Int?\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id Int @id @default(autoincrement())\n associationId Int\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id Int @id @default(autoincrement())\n\n // Core references\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support - self-referential relation\n parentProcessId Int?\n parentProcess Process? @relation(\"ProcessHierarchy\", fields: [parentProcessId], references: [id], onDelete: SetNull)\n childProcesses Process[] @relation(\"ProcessHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@index([parentProcessId])\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id Int @id @default(autoincrement())\n state Json?\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id Int @id @default(autoincrement())\n connectionId String?\n\n @@index([connectionId])\n}\n",
335
- "inlineSchemaHash": "f3edba5bb5e72088ff5a6505548bd90aa528e5e99e6433c2eed6eed57dcd25ab",
334
+ "inlineSchema": "// Frigg Framework - Prisma Schema (PostgreSQL)\n// PostgreSQL database schema for enterprise integration platform\n// Converted from MongoDB schema for relational database support\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-postgresql\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id Int @id @default(autoincrement())\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId Int?\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@index([organizationId])\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id Int @id @default(autoincrement())\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id Int @id @default(autoincrement())\n credentialId Int?\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with implicit join tables\n integrations Integration[]\n syncs Sync[]\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(ENABLED)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id Int @id @default(autoincrement())\n integrationId Int?\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id Int @id @default(autoincrement())\n syncId Int?\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id Int @id @default(autoincrement())\n associationId Int\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id Int @id @default(autoincrement())\n\n // Core references\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support - self-referential relation\n parentProcessId Int?\n parentProcess Process? @relation(\"ProcessHierarchy\", fields: [parentProcessId], references: [id], onDelete: SetNull)\n childProcesses Process[] @relation(\"ProcessHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@index([parentProcessId])\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id Int @id @default(autoincrement())\n state Json?\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id Int @id @default(autoincrement())\n connectionId String?\n\n @@index([connectionId])\n}\n",
335
+ "inlineSchemaHash": "eed4c64f28652dc5f954cdede8f210a503c0bb1624c2f42b92aea6cdcaaebaaf",
336
336
  "copyEngine": true
337
337
  }
338
338
  config.dirname = '/'
@@ -332,8 +332,8 @@ const config = {
332
332
  }
333
333
  }
334
334
  },
335
- "inlineSchema": "// Frigg Framework - Prisma Schema (PostgreSQL)\n// PostgreSQL database schema for enterprise integration platform\n// Converted from MongoDB schema for relational database support\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-postgresql\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id Int @id @default(autoincrement())\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId Int?\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id Int @id @default(autoincrement())\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id Int @id @default(autoincrement())\n credentialId Int?\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with implicit join tables\n integrations Integration[]\n syncs Sync[]\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(ENABLED)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id Int @id @default(autoincrement())\n integrationId Int?\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id Int @id @default(autoincrement())\n syncId Int?\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id Int @id @default(autoincrement())\n associationId Int\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id Int @id @default(autoincrement())\n\n // Core references\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support - self-referential relation\n parentProcessId Int?\n parentProcess Process? @relation(\"ProcessHierarchy\", fields: [parentProcessId], references: [id], onDelete: SetNull)\n childProcesses Process[] @relation(\"ProcessHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@index([parentProcessId])\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id Int @id @default(autoincrement())\n state Json?\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id Int @id @default(autoincrement())\n connectionId String?\n\n @@index([connectionId])\n}\n",
336
- "inlineSchemaHash": "f3edba5bb5e72088ff5a6505548bd90aa528e5e99e6433c2eed6eed57dcd25ab",
335
+ "inlineSchema": "// Frigg Framework - Prisma Schema (PostgreSQL)\n// PostgreSQL database schema for enterprise integration platform\n// Converted from MongoDB schema for relational database support\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-postgresql\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id Int @id @default(autoincrement())\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId Int?\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@index([organizationId])\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id Int @id @default(autoincrement())\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id Int @id @default(autoincrement())\n credentialId Int?\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with implicit join tables\n integrations Integration[]\n syncs Sync[]\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(ENABLED)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id Int @id @default(autoincrement())\n integrationId Int?\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id Int @id @default(autoincrement())\n syncId Int?\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id Int @id @default(autoincrement())\n associationId Int\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id Int @id @default(autoincrement())\n\n // Core references\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support - self-referential relation\n parentProcessId Int?\n parentProcess Process? @relation(\"ProcessHierarchy\", fields: [parentProcessId], references: [id], onDelete: SetNull)\n childProcesses Process[] @relation(\"ProcessHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@index([parentProcessId])\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id Int @id @default(autoincrement())\n state Json?\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id Int @id @default(autoincrement())\n connectionId String?\n\n @@index([connectionId])\n}\n",
336
+ "inlineSchemaHash": "eed4c64f28652dc5f954cdede8f210a503c0bb1624c2f42b92aea6cdcaaebaaf",
337
337
  "copyEngine": true
338
338
  }
339
339
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "name": "prisma-client-05b54a0b501019b5e1e05192fca86a8a38136acf22dc9acc33f22364d116cee4",
2
+ "name": "prisma-client-be108897cd5650bc94905604290862e58d5534c52ad58af310efe3e96826d709",
3
3
  "main": "index.js",
4
4
  "types": "index.d.ts",
5
5
  "browser": "default.js",
@@ -59,6 +59,7 @@ model User {
59
59
  @@unique([username, appUserId])
60
60
  @@index([type])
61
61
  @@index([appUserId])
62
+ @@index([organizationId])
62
63
  }
63
64
 
64
65
  enum UserType {
@@ -331,8 +331,8 @@ const config = {
331
331
  }
332
332
  }
333
333
  },
334
- "inlineSchema": "// Frigg Framework - Prisma Schema (PostgreSQL)\n// PostgreSQL database schema for enterprise integration platform\n// Converted from MongoDB schema for relational database support\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-postgresql\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id Int @id @default(autoincrement())\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId Int?\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id Int @id @default(autoincrement())\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id Int @id @default(autoincrement())\n credentialId Int?\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with implicit join tables\n integrations Integration[]\n syncs Sync[]\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(ENABLED)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id Int @id @default(autoincrement())\n integrationId Int?\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id Int @id @default(autoincrement())\n syncId Int?\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id Int @id @default(autoincrement())\n associationId Int\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id Int @id @default(autoincrement())\n\n // Core references\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support - self-referential relation\n parentProcessId Int?\n parentProcess Process? @relation(\"ProcessHierarchy\", fields: [parentProcessId], references: [id], onDelete: SetNull)\n childProcesses Process[] @relation(\"ProcessHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@index([parentProcessId])\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id Int @id @default(autoincrement())\n state Json?\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id Int @id @default(autoincrement())\n connectionId String?\n\n @@index([connectionId])\n}\n",
335
- "inlineSchemaHash": "f3edba5bb5e72088ff5a6505548bd90aa528e5e99e6433c2eed6eed57dcd25ab",
334
+ "inlineSchema": "// Frigg Framework - Prisma Schema (PostgreSQL)\n// PostgreSQL database schema for enterprise integration platform\n// Converted from MongoDB schema for relational database support\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma-postgresql\"\n binaryTargets = [\"native\", \"rhel-openssl-3.0.x\"] // native for local dev, rhel for Lambda deployment\n // Library engine (default since Prisma 3.x): Rust query engine loads as a\n // Node-API addon inside the same process. The binary engine forks a child\n // query-engine subprocess and communicates over a local HTTP/IPC pipe with\n // NO client-side timeout — a zombied child wedges the Node process until\n // Lambda's 900s cap. Switching to library eliminates that entire class of\n // silent hangs. See friggframework/frigg#580 for the investigation.\n engineType = \"library\"\n}\n\ndatasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n\n// ============================================================================\n// USER MODELS\n// ============================================================================\n\n/// User model with discriminator pattern support\n/// Replaces Mongoose discriminators (IndividualUser, OrganizationUser)\nmodel User {\n id Int @id @default(autoincrement())\n type UserType\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // IndividualUser fields (nullable for organizations)\n email String?\n username String?\n hashword String? // Bcrypt hashed password (handled in application layer)\n appUserId String?\n organizationId Int?\n\n // Self-referential relation for organization membership\n organization User? @relation(\"OrgMembers\", fields: [organizationId], references: [id], onDelete: NoAction, onUpdate: NoAction)\n members User[] @relation(\"OrgMembers\")\n\n // OrganizationUser fields (nullable for individuals)\n appOrgId String?\n name String?\n\n // Relations\n tokens Token[]\n credentials Credential[]\n entities Entity[]\n integrations Integration[]\n processes Process[]\n\n @@unique([username, appUserId])\n @@index([type])\n @@index([appUserId])\n @@index([organizationId])\n}\n\nenum UserType {\n INDIVIDUAL\n ORGANIZATION\n}\n\n// ============================================================================\n// AUTHENTICATION MODELS\n// ============================================================================\n\n/// Authentication tokens with expiration\n/// Bcrypt hashed tokens stored (handled in application layer)\nmodel Token {\n id Int @id @default(autoincrement())\n token String // Bcrypt hashed\n created DateTime @default(now())\n expires DateTime?\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([expires])\n}\n\n// ============================================================================\n// CREDENTIAL & ENTITY MODELS\n// ============================================================================\n\n/// OAuth credentials and API tokens\n/// All sensitive data encrypted with KMS at rest\nmodel Credential {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n authIsValid Boolean?\n externalId String?\n\n // Dynamic OAuth fields stored as JSON (encrypted via Prisma middleware)\n // Contains: access_token, refresh_token, domain, expires_in, token_type, etc.\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n entities Entity[]\n\n @@index([userId])\n @@index([externalId])\n}\n\n/// External service entities (API connections)\nmodel Entity {\n id Int @id @default(autoincrement())\n credentialId Int?\n credential Credential? @relation(fields: [credentialId], references: [id], onDelete: SetNull)\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n name String?\n moduleName String?\n externalId String?\n\n data Json @default(\"{}\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations - many-to-many with implicit join tables\n integrations Integration[]\n syncs Sync[]\n\n dataIdentifiers DataIdentifier[]\n associationObjects AssociationObject[]\n\n @@index([userId])\n @@index([externalId])\n @@index([moduleName])\n @@index([credentialId])\n}\n\n// ============================================================================\n// INTEGRATION MODELS\n// ============================================================================\n\n/// Main integration configuration and state\nmodel Integration {\n id Int @id @default(autoincrement())\n userId Int?\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n status IntegrationStatus @default(ENABLED)\n\n // Configuration and version\n config Json? // Integration configuration object\n version String?\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n // Message arrays (stored as JSON)\n errors Json @default(\"[]\")\n warnings Json @default(\"[]\")\n info Json @default(\"[]\")\n logs Json @default(\"[]\")\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n // Relations\n associations Association[]\n syncs Sync[]\n mappings IntegrationMapping[]\n processes Process[]\n\n @@index([userId])\n @@index([status])\n}\n\nenum IntegrationStatus {\n ENABLED\n NEEDS_CONFIG\n PROCESSING\n DISABLED\n ERROR\n}\n\n/// Integration-specific data mappings\n/// All mapping data encrypted with KMS\nmodel IntegrationMapping {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n sourceId String?\n\n // Encrypted mapping data (handled via Prisma middleware)\n mapping Json?\n\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([integrationId, sourceId])\n @@index([integrationId])\n @@index([sourceId])\n}\n\n// ============================================================================\n// SYNC MODELS\n// ============================================================================\n\n/// Bidirectional data synchronization tracking\nmodel Sync {\n id Int @id @default(autoincrement())\n integrationId Int?\n integration Integration? @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Entity references (many-to-many via implicit join table)\n entities Entity[]\n\n hash String\n name String\n\n // Data identifiers (extracted to separate model)\n dataIdentifiers DataIdentifier[]\n\n @@index([integrationId])\n @@index([hash])\n @@index([name])\n}\n\n/// Data identifier for sync operations\n/// Replaces nested array structure in Mongoose\nmodel DataIdentifier {\n id Int @id @default(autoincrement())\n syncId Int?\n sync Sync? @relation(fields: [syncId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n\n // Identifier data (can be any structure)\n idData Json\n\n hash String\n\n @@index([syncId])\n @@index([entityId])\n @@index([hash])\n}\n\n// ============================================================================\n// ASSOCIATION MODELS\n// ============================================================================\n\n/// Entity associations with cardinality tracking\nmodel Association {\n id Int @id @default(autoincrement())\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n name String\n type AssociationType\n primaryObject String\n\n // Associated objects (extracted to separate model)\n objects AssociationObject[]\n\n @@index([integrationId])\n @@index([name])\n}\n\n/// Association object entry\n/// Replaces nested array structure in Mongoose\nmodel AssociationObject {\n id Int @id @default(autoincrement())\n associationId Int\n association Association @relation(fields: [associationId], references: [id], onDelete: Cascade)\n entityId Int\n entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade)\n objectType String\n objId String\n metadata Json? // Optional metadata\n\n @@index([associationId])\n @@index([entityId])\n}\n\nenum AssociationType {\n ONE_TO_MANY\n ONE_TO_ONE\n MANY_TO_ONE\n}\n\n// ============================================================================\n// PROCESS MODELS\n// ============================================================================\n\n/// Generic Process Model - tracks any long-running operation\n/// Used for: CRM syncs, data migrations, bulk operations, etc.\nmodel Process {\n id Int @id @default(autoincrement())\n\n // Core references\n userId Int\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n integrationId Int\n integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)\n\n // Process identification\n name String // e.g., \"zoho-crm-contact-sync\", \"pipedrive-lead-sync\"\n type String // e.g., \"CRM_SYNC\", \"DATA_MIGRATION\", \"BULK_OPERATION\"\n\n // State machine\n state String // Current state (integration-defined states)\n\n // Flexible storage\n context Json @default(\"{}\") // Process-specific data (pagination, metadata, etc.)\n results Json @default(\"{}\") // Process results and metrics\n\n // Hierarchy support - self-referential relation\n parentProcessId Int?\n parentProcess Process? @relation(\"ProcessHierarchy\", fields: [parentProcessId], references: [id], onDelete: SetNull)\n childProcesses Process[] @relation(\"ProcessHierarchy\")\n\n // Timestamps\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@index([userId])\n @@index([integrationId])\n @@index([type])\n @@index([state])\n @@index([name])\n @@index([parentProcessId])\n}\n\n// ============================================================================\n// UTILITY MODELS\n// ============================================================================\n\n/// Generic state storage\nmodel State {\n id Int @id @default(autoincrement())\n state Json?\n}\n\n/// AWS API Gateway WebSocket connection tracking\nmodel WebsocketConnection {\n id Int @id @default(autoincrement())\n connectionId String?\n\n @@index([connectionId])\n}\n",
335
+ "inlineSchemaHash": "eed4c64f28652dc5f954cdede8f210a503c0bb1624c2f42b92aea6cdcaaebaaf",
336
336
  "copyEngine": true
337
337
  }
338
338
  config.dirname = '/'
package/index.js CHANGED
@@ -91,12 +91,6 @@ const application = require('./application');
91
91
  const utils = require('./utils');
92
92
 
93
93
  const { QueuerUtil } = require('./queues');
94
- const {
95
- dispatchIntegrationEvent,
96
- } = require('./integrations/use-cases/dispatch-integration-event');
97
- const {
98
- userActionQueueWorker,
99
- } = require('./handlers/workers/user-action-worker');
100
94
 
101
95
  module.exports = {
102
96
  // assertions
@@ -143,7 +137,6 @@ module.exports = {
143
137
  checkRequiredParams,
144
138
  createIntegrationRouter,
145
139
  getModulesDefinitionFromIntegrationClasses,
146
- dispatchIntegrationEvent,
147
140
  LoadIntegrationContextUseCase,
148
141
  CreateProcess,
149
142
  UpdateProcessState,
@@ -187,9 +180,6 @@ module.exports = {
187
180
  // queues
188
181
  QueuerUtil,
189
182
 
190
- // workers
191
- userActionQueueWorker,
192
-
193
183
  // utils
194
184
  ...utils,
195
185
  };
@@ -31,11 +31,6 @@ const constantsToBeMigrated = {
31
31
  LIFE_CYCLE_EVENT: 'LIFE_CYCLE_EVENT',
32
32
  USER_ACTION: 'USER_ACTION',
33
33
  },
34
- // 'sync' runs in-process (default); 'queue' routes through the FIFO queue.
35
- dispatch: {
36
- SYNC: 'sync',
37
- QUEUE: 'queue',
38
- },
39
34
  };
40
35
 
41
36
  class IntegrationBase {
@@ -526,18 +521,6 @@ class IntegrationBase {
526
521
  ...this.defaultEvents,
527
522
  ...this.events,
528
523
  };
529
-
530
- // Definition.eventDispatch marks default events; inline dispatch wins,
531
- // unknown names are ignored.
532
- const eventDispatch = this.constructor.Definition?.eventDispatch || {};
533
- for (const [eventName, mode] of Object.entries(eventDispatch)) {
534
- if (this.on[eventName] && this.on[eventName].dispatch === undefined) {
535
- this.on[eventName] = {
536
- ...this.on[eventName],
537
- dispatch: mode,
538
- };
539
- }
540
- }
541
524
  }
542
525
 
543
526
  /**
@@ -625,9 +608,6 @@ class IntegrationBase {
625
608
  this.events[eventName] = {
626
609
  type: eventDef.type,
627
610
  handler: fn.bind(this),
628
- ...(eventDef.dispatch !== undefined && {
629
- dispatch: eventDef.dispatch,
630
- }),
631
611
  };
632
612
  mergedByExtension.set(eventName, bindingName);
633
613
  }
@@ -30,9 +30,6 @@ const {
30
30
  GetIntegrationInstance,
31
31
  } = require('./use-cases/get-integration-instance');
32
32
  const { UpdateIntegration } = require('./use-cases/update-integration');
33
- const {
34
- dispatchIntegrationEvent,
35
- } = require('./use-cases/dispatch-integration-event');
36
33
  const {
37
34
  getModulesDefinitionFromIntegrationClasses,
38
35
  } = require('./utils/map-integration-dto');
@@ -296,9 +293,6 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
296
293
  params.config
297
294
  );
298
295
 
299
- if (integration?.queued) {
300
- return res.status(202).json(integration);
301
- }
302
296
  res.status(201).json(integration);
303
297
  })
304
298
  );
@@ -314,9 +308,6 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
314
308
  userId,
315
309
  params.config
316
310
  );
317
- if (integration?.queued) {
318
- return res.status(202).json(integration);
319
- }
320
311
  res.json(integration);
321
312
  })
322
313
  );
@@ -434,21 +425,7 @@ function setIntegrationRoutes(router, authenticateUser, useCases) {
434
425
  params.integrationId,
435
426
  user.getId()
436
427
  );
437
- const outcome = await dispatchIntegrationEvent({
438
- instance: integration,
439
- event: params.actionId,
440
- data: req.body,
441
- userId: user.getId(),
442
- });
443
- if (outcome.queued) {
444
- return res.status(202).json({
445
- queued: true,
446
- integrationId: integration.id,
447
- messageId: outcome.messageId,
448
- requestId: outcome.requestId,
449
- });
450
- }
451
- res.json(outcome.result);
428
+ res.json(await integration.send(params.actionId, req.body));
452
429
  })
453
430
  );
454
431
 
@@ -2,7 +2,6 @@
2
2
  const {
3
3
  mapIntegrationClassToIntegrationDTO,
4
4
  } = require('../utils/map-integration-dto');
5
- const { dispatchIntegrationEvent } = require('./dispatch-integration-event');
6
5
 
7
6
  /**
8
7
  * Use case for creating a new integration instance.
@@ -73,22 +72,10 @@ class CreateIntegration {
73
72
  });
74
73
 
75
74
  await integrationInstance.initialize();
76
- const outcome = await dispatchIntegrationEvent({
77
- instance: integrationInstance,
78
- event: 'ON_CREATE',
79
- data: { integrationId: integrationRecord.id },
80
- userId,
75
+ await integrationInstance.send('ON_CREATE', {
76
+ integrationId: integrationRecord.id,
81
77
  });
82
78
 
83
- if (outcome.queued) {
84
- return {
85
- queued: true,
86
- integrationId: integrationInstance.id,
87
- messageId: outcome.messageId,
88
- requestId: outcome.requestId,
89
- };
90
- }
91
-
92
79
  return mapIntegrationClassToIntegrationDTO(integrationInstance);
93
80
  }
94
81
  }
@@ -31,12 +31,9 @@ class GetIntegrationInstance {
31
31
  await this.integrationRepository.findIntegrationById(integrationId);
32
32
 
33
33
  if (!integrationRecord) {
34
- const error = new Error(
34
+ throw new Error(
35
35
  `No integration found by the ID of ${integrationId}`
36
36
  );
37
- // isTerminal → the queue worker discards these (no retry can succeed).
38
- error.isTerminal = true;
39
- throw error;
40
37
  }
41
38
 
42
39
  const integrationClass = this.integrationClasses.find(
@@ -46,19 +43,15 @@ class GetIntegrationInstance {
46
43
  );
47
44
 
48
45
  if (!integrationClass) {
49
- const error = new Error(
46
+ throw new Error(
50
47
  `No integration class found for type: ${integrationRecord.config.type}`
51
48
  );
52
- error.isTerminal = true;
53
- throw error;
54
49
  }
55
50
 
56
51
  if (integrationRecord.userId !== userId) {
57
- const error = new Error(
52
+ throw new Error(
58
53
  `Integration ${integrationId} does not belong to User ${userId}`
59
54
  );
60
- error.isTerminal = true;
61
- throw error;
62
55
  }
63
56
 
64
57
  const modules = [];
@@ -1,7 +1,6 @@
1
1
  const {
2
2
  mapIntegrationClassToIntegrationDTO,
3
3
  } = require('../utils/map-integration-dto');
4
- const { dispatchIntegrationEvent } = require('./dispatch-integration-event');
5
4
 
6
5
  /**
7
6
  * Use case for updating a single integration by ID and user.
@@ -82,22 +81,9 @@ class UpdateIntegration {
82
81
  modules,
83
82
  });
84
83
 
84
+ // 5. Complete async initialization and trigger update event
85
85
  await integrationInstance.initialize();
86
- const outcome = await dispatchIntegrationEvent({
87
- instance: integrationInstance,
88
- event: 'ON_UPDATE',
89
- data: { config },
90
- userId,
91
- });
92
-
93
- if (outcome.queued) {
94
- return {
95
- queued: true,
96
- integrationId: integrationInstance.id,
97
- messageId: outcome.messageId,
98
- requestId: outcome.requestId,
99
- };
100
- }
86
+ await integrationInstance.send('ON_UPDATE', { config });
101
87
 
102
88
  return mapIntegrationClassToIntegrationDTO(integrationInstance);
103
89
  }
@@ -315,13 +315,13 @@ class OAuth2Requester extends Requester {
315
315
  console.log('[Frigg] Token refresh succeeded');
316
316
  return true;
317
317
  } catch (error) {
318
- console.error('[Frigg] Token refresh failed', {
318
+ const moduleName = this.delegate?.name ?? 'unknown module';
319
+ console.error(`[Frigg] Token refresh failed for ${moduleName}`, {
319
320
  error_message: error?.message,
320
321
  error_name: error?.name,
321
322
  response_status: error?.response?.status,
322
323
  response_data: error?.response?.data,
323
324
  });
324
- await this.notify(this.DLGT_INVALID_AUTH);
325
325
  return false;
326
326
  }
327
327
  }
@@ -119,9 +119,7 @@ class Requester extends Delegate {
119
119
  if (e?.code === 'ECONNRESET' && i < this.backOff.length) {
120
120
  clearRequestTimer();
121
121
  const delay = this.backOff[i] * 1000;
122
- await new Promise((resolve) =>
123
- setTimeout(resolve, delay)
124
- );
122
+ await new Promise((resolve) => setTimeout(resolve, delay));
125
123
  return this._request(url, options, i + 1);
126
124
  }
127
125
  const fetchError = await FetchError.create({
@@ -150,16 +148,24 @@ class Requester extends Delegate {
150
148
  const delay = this.backOff[i] * 1000;
151
149
  await new Promise((resolve) => setTimeout(resolve, delay));
152
150
  return this._request(url, options, i + 1);
153
- } else if (status === 401) {
151
+ }
152
+
153
+ if (status === 401) {
154
154
  if (!this.isRefreshable) {
155
155
  await this.notify(this.DLGT_INVALID_AUTH);
156
- } else if (this.refreshCount === 0) {
156
+ return;
157
+ }
158
+
159
+ if (this.refreshCount === 0) {
157
160
  this.refreshCount++;
158
161
  const refreshSucceeded = await this.refreshAuth();
159
162
  if (refreshSucceeded) {
160
163
  clearRequestTimer();
161
164
  return this._request(url, options, i + 1);
162
165
  }
166
+
167
+ await this.notify(this.DLGT_INVALID_AUTH);
168
+ return;
163
169
  }
164
170
  }
165
171
 
@@ -201,8 +207,7 @@ class Requester extends Delegate {
201
207
  _maybeFlagTimeoutDuringBodyRead(err, timeoutMs) {
202
208
  if (!err || typeof err !== 'object') return err;
203
209
  if (err.isTimeout) return err;
204
- const isAbort =
205
- err.name === 'AbortError' || err.type === 'aborted';
210
+ const isAbort = err.name === 'AbortError' || err.type === 'aborted';
206
211
  if (!isAbort) return err;
207
212
  err.isTimeout = true;
208
213
  err.timeoutMs = timeoutMs;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@friggframework/core",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.608.e6b65ff.0",
4
+ "version": "2.0.0--canary.610.ca077d5.0",
5
5
  "dependencies": {
6
6
  "@aws-sdk/client-apigatewaymanagementapi": "^3.588.0",
7
7
  "@aws-sdk/client-kms": "^3.588.0",
@@ -38,9 +38,9 @@
38
38
  }
39
39
  },
40
40
  "devDependencies": {
41
- "@friggframework/eslint-config": "2.0.0--canary.608.e6b65ff.0",
42
- "@friggframework/prettier-config": "2.0.0--canary.608.e6b65ff.0",
43
- "@friggframework/test": "2.0.0--canary.608.e6b65ff.0",
41
+ "@friggframework/eslint-config": "2.0.0--canary.610.ca077d5.0",
42
+ "@friggframework/prettier-config": "2.0.0--canary.610.ca077d5.0",
43
+ "@friggframework/test": "2.0.0--canary.610.ca077d5.0",
44
44
  "@prisma/client": "^6.19.3",
45
45
  "@types/lodash": "4.17.15",
46
46
  "@typescript-eslint/eslint-plugin": "^8.0.0",
@@ -80,5 +80,5 @@
80
80
  "publishConfig": {
81
81
  "access": "public"
82
82
  },
83
- "gitHead": "e6b65ff3bf4a3b3e7777a1f2a6cf1cecd24bedd7"
83
+ "gitHead": "ca077d5f47ea8b69880c3adeebbdbd3a6ac5abb5"
84
84
  }
@@ -59,6 +59,7 @@ model User {
59
59
  @@unique([username, appUserId])
60
60
  @@index([type])
61
61
  @@index([appUserId])
62
+ @@index([organizationId])
62
63
  @@map("User")
63
64
  }
64
65
 
@@ -0,0 +1,2 @@
1
+ -- CreateIndex
2
+ CREATE INDEX "User_organizationId_idx" ON "User"("organizationId");
@@ -59,6 +59,7 @@ model User {
59
59
  @@unique([username, appUserId])
60
60
  @@index([type])
61
61
  @@index([appUserId])
62
+ @@index([organizationId])
62
63
  }
63
64
 
64
65
  enum UserType {
@@ -90,16 +90,10 @@ const inspectBatchResult = (result, queueUrl, buffer) => {
90
90
  };
91
91
 
92
92
  const QueuerUtil = {
93
- // FIFO-only: default a unique dedup id so identical bodies aren't dropped.
94
- // Standard sends pass no opts and stay unchanged.
95
- send: async (message, queueUrl, { messageGroupId, messageDeduplicationId } = {}) => {
93
+ send: async (message, queueUrl) => {
96
94
  const command = new SendMessageCommand({
97
95
  MessageBody: JSON.stringify(message),
98
96
  QueueUrl: queueUrl,
99
- ...(messageGroupId !== undefined && {
100
- MessageGroupId: messageGroupId,
101
- MessageDeduplicationId: messageDeduplicationId || uuid(),
102
- }),
103
97
  });
104
98
  const result = await sqs.send(command);
105
99
  console.log(
@@ -4,6 +4,7 @@ const {
4
4
  toObjectId,
5
5
  fromObjectId,
6
6
  findOne,
7
+ findMany,
7
8
  insertOne,
8
9
  updateOne,
9
10
  deleteOne,
@@ -67,6 +68,22 @@ class UserRepositoryDocumentDB extends UserRepositoryInterface {
67
68
  return this._mapUser(decrypted);
68
69
  }
69
70
 
71
+ async findIndividualUsersByOrganizationId(organizationUserId) {
72
+ const docs = await findMany(this.prisma, 'User', {
73
+ organizationId: toObjectId(organizationUserId),
74
+ type: 'INDIVIDUAL',
75
+ });
76
+ return Promise.all(
77
+ docs.map(async (doc) => {
78
+ const decrypted = await this.encryptionService.decryptFields(
79
+ 'User',
80
+ doc
81
+ );
82
+ return this._mapUser(decrypted);
83
+ })
84
+ );
85
+ }
86
+
70
87
  async createToken(userId, rawToken, minutes = 120) {
71
88
  const createdToken = await this.tokenRepository.createTokenWithExpire(
72
89
  fromObjectId(toObjectId(userId)),
@@ -53,6 +53,19 @@ class UserRepositoryInterface {
53
53
  );
54
54
  }
55
55
 
56
+ /**
57
+ * Find all individual users linked to an organization user
58
+ *
59
+ * @param {string|number} organizationUserId - Organization user ID
60
+ * @returns {Promise<Object[]>} Array of individual user objects (empty if none)
61
+ * @abstract
62
+ */
63
+ async findIndividualUsersByOrganizationId(organizationUserId) {
64
+ throw new Error(
65
+ 'Method findIndividualUsersByOrganizationId must be implemented by subclass'
66
+ );
67
+ }
68
+
56
69
  /**
57
70
  * Create token with expiration
58
71
  *
@@ -70,6 +70,21 @@ class UserRepositoryMongo extends UserRepositoryInterface {
70
70
  });
71
71
  }
72
72
 
73
+ /**
74
+ * Find all individual users linked to an organization user
75
+ *
76
+ * @param {string} organizationUserId - Organization user ID
77
+ * @returns {Promise<Object[]>} Array of individual user records (empty if none)
78
+ */
79
+ async findIndividualUsersByOrganizationId(organizationUserId) {
80
+ return await this.prisma.user.findMany({
81
+ where: {
82
+ organizationId: organizationUserId,
83
+ type: 'INDIVIDUAL',
84
+ },
85
+ });
86
+ }
87
+
73
88
  /**
74
89
  * Create token with expiration
75
90
  * Delegates to TokenRepository
@@ -105,6 +105,23 @@ class UserRepositoryPostgres extends UserRepositoryInterface {
105
105
  return this._convertUserIds(user);
106
106
  }
107
107
 
108
+ /**
109
+ * Find all individual users linked to an organization user
110
+ *
111
+ * @param {string} organizationUserId - Organization user ID (string from application layer)
112
+ * @returns {Promise<Object[]>} Array of individual user objects with string IDs (empty if none)
113
+ */
114
+ async findIndividualUsersByOrganizationId(organizationUserId) {
115
+ const intId = this._convertId(organizationUserId);
116
+ const users = await this.prisma.user.findMany({
117
+ where: {
118
+ organizationId: intId,
119
+ type: 'INDIVIDUAL',
120
+ },
121
+ });
122
+ return users.map((user) => this._convertUserIds(user));
123
+ }
124
+
108
125
  /**
109
126
  * Create token with expiration
110
127
  * Delegates to TokenRepository
@@ -1,146 +0,0 @@
1
- const { Worker } = require('../../core/Worker');
2
- // Direct path (not the package index) avoids a circular require.
3
- const { createHandler } = require('../../core/create-handler');
4
- const {
5
- GetIntegrationInstance,
6
- } = require('../../integrations/use-cases/get-integration-instance');
7
- const { ModuleFactory } = require('../../modules/module-factory');
8
- const {
9
- createIntegrationRepository,
10
- } = require('../../integrations/repositories/integration-repository-factory');
11
- const {
12
- createModuleRepository,
13
- } = require('../../modules/repositories/module-repository-factory');
14
- const {
15
- getModulesDefinitionFromIntegrationClasses,
16
- } = require('../../integrations/utils/map-integration-dto');
17
-
18
- /**
19
- * App-level worker for `dispatch: 'queue'` events. One Lambda serves every
20
- * integration; the FIFO queue serializes per integrationId. Re-hydrates by id +
21
- * owning user, then runs `instance.send(event, data)` (identical to the sync path).
22
- * Terminal failures discard; everything else retries → FIFO DLQ. DISABLED/ERROR
23
- * integrations are still processed (these are user-initiated mutations).
24
- */
25
- class UserActionWorker extends Worker {
26
- constructor({ getIntegrationInstance } = {}) {
27
- super();
28
- this._getIntegrationInstance = getIntegrationInstance || null;
29
- }
30
-
31
- _validateParams(params) {
32
- this._verifyParamExists(params, 'event');
33
- this._verifyParamExists(params, 'data');
34
- }
35
-
36
- _resolveGetIntegrationInstance() {
37
- if (this._getIntegrationInstance) return this._getIntegrationInstance;
38
-
39
- const { loadAppDefinition } = require('../app-definition-loader');
40
- const { integrations: integrationClasses } = loadAppDefinition();
41
- const integrationRepository = createIntegrationRepository();
42
- const moduleRepository = createModuleRepository();
43
- const moduleFactory = new ModuleFactory({
44
- moduleRepository,
45
- moduleDefinitions:
46
- getModulesDefinitionFromIntegrationClasses(integrationClasses),
47
- });
48
-
49
- this._getIntegrationInstance = new GetIntegrationInstance({
50
- integrationRepository,
51
- integrationClasses,
52
- moduleFactory,
53
- });
54
- return this._getIntegrationInstance;
55
- }
56
-
57
- async _run(params) {
58
- const { event, data = {}, integrationId, userId, requestId } = params;
59
- const logCtx = { event, integrationId, userId, requestId };
60
-
61
- if (!integrationId || !userId) {
62
- const err = new Error(
63
- '[UserActionWorker] message missing integrationId/userId'
64
- );
65
- err.isHaltError = true;
66
- console.error(err.message, logCtx);
67
- throw err;
68
- }
69
-
70
- const getIntegrationInstance = this._resolveGetIntegrationInstance();
71
-
72
- let instance;
73
- try {
74
- instance = await getIntegrationInstance.execute(
75
- integrationId,
76
- userId
77
- );
78
- } catch (error) {
79
- // Only terminal failures discard; transient ones (DB/Prisma/KMS
80
- // blips) retry → FIFO DLQ rather than being silently dropped.
81
- if (error.isTerminal) {
82
- error.isHaltError = true;
83
- console.warn(
84
- `[UserActionWorker] integration ${integrationId} gone/invalid — discarding`,
85
- { ...logCtx, reason: error.message }
86
- );
87
- } else {
88
- console.error(
89
- `[UserActionWorker] transient hydration failure for ${integrationId} — will retry`,
90
- { ...logCtx, reason: error.message }
91
- );
92
- }
93
- throw error;
94
- }
95
-
96
- if (String(instance.id) !== String(integrationId)) {
97
- const err = new Error(
98
- `[UserActionWorker] hydrated id ${instance.id} != message integrationId ${integrationId}`
99
- );
100
- err.isHaltError = true;
101
- console.error(err.message, logCtx);
102
- throw err;
103
- }
104
-
105
- try {
106
- console.log(`[UserActionWorker] dispatching ${event}`, logCtx);
107
- const result = await instance.send(event, data);
108
- console.log(`[UserActionWorker] ${event} ok`, logCtx);
109
- return result;
110
- } catch (error) {
111
- try {
112
- await instance.updateIntegrationStatus.execute(
113
- integrationId,
114
- 'ERROR'
115
- );
116
- await instance.updateIntegrationMessages.execute(
117
- integrationId,
118
- 'warnings',
119
- `Queued ${event} failed`,
120
- error.message,
121
- new Date().toISOString()
122
- );
123
- } catch (statusErr) {
124
- console.error(
125
- '[UserActionWorker] failed to record error status/messages',
126
- { ...logCtx, statusErr: statusErr.message }
127
- );
128
- }
129
- console.error(`[UserActionWorker] ${event} failed`, {
130
- ...logCtx,
131
- error: error.message,
132
- });
133
- throw error; // → SQS retry → FIFO DLQ
134
- }
135
- }
136
- }
137
-
138
- // createHandler gives the Lambda the standard worker setup (secretsToEnv,
139
- // connectPrisma, callbackWaitsForEmptyEventLoop) and passes the result through.
140
- const userActionQueueWorker = createHandler({
141
- eventName: 'UserActionQueueWorker',
142
- isUserFacingResponse: false,
143
- method: async (event, context) => new UserActionWorker().run(event, context),
144
- });
145
-
146
- module.exports = { UserActionWorker, userActionQueueWorker };
@@ -1,54 +0,0 @@
1
- const { v4: uuid } = require('uuid');
2
- const { QueuerUtil } = require('../../queues');
3
-
4
- const SCHEMA_VERSION = 1;
5
-
6
- // ON_DELETE is excluded: it dispatches directly and the record is gone before a
7
- // queued worker could re-hydrate it. Custom (non-default) events are mutating.
8
- const MUTATING_DEFAULT_EVENTS = new Set(['ON_CREATE', 'ON_UPDATE']);
9
-
10
- function isMutatingEvent(instance, event) {
11
- if (!instance.defaultEvents || !instance.defaultEvents[event]) {
12
- return true;
13
- }
14
- return MUTATING_DEFAULT_EVENTS.has(event);
15
- }
16
-
17
- // Enqueues the event (returning a { queued } ack) when it opts into
18
- // dispatch:'queue' and the queue is configured; otherwise runs it in-process
19
- // and returns the result. Missing queue URL degrades to in-process.
20
- async function dispatchIntegrationEvent({ instance, event, data, userId }) {
21
- const mode = instance.on?.[event]?.dispatch;
22
- const queueUrl = process.env.USER_ACTION_QUEUE_URL;
23
-
24
- const eligible = mode === 'queue' && isMutatingEvent(instance, event);
25
-
26
- if (eligible && !queueUrl) {
27
- console.warn(
28
- `[dispatchIntegrationEvent] event "${event}" requested dispatch:'queue' ` +
29
- `but USER_ACTION_QUEUE_URL is not set — running in-process (sync)`
30
- );
31
- }
32
-
33
- if (eligible && queueUrl) {
34
- const requestId = uuid();
35
- // Routing metadata at the top level keeps `data` identical to the sync path.
36
- const envelope = {
37
- schemaVersion: SCHEMA_VERSION,
38
- event,
39
- integrationId: instance.id,
40
- userId,
41
- requestId,
42
- data,
43
- };
44
- const result = await QueuerUtil.send(envelope, queueUrl, {
45
- messageGroupId: instance.id,
46
- messageDeduplicationId: requestId,
47
- });
48
- return { queued: true, messageId: result?.MessageId, requestId };
49
- }
50
-
51
- return { result: await instance.send(event, data) };
52
- }
53
-
54
- module.exports = { dispatchIntegrationEvent, SCHEMA_VERSION };