@friggframework/core 2.0.0--canary.686.3e27a92.0 → 2.0.0--canary.663.8de669c.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 (184) hide show
  1. package/CLAUDE.md +0 -28
  2. package/README.md +0 -105
  3. package/application/commands/integration-commands.js +10 -20
  4. package/application/commands/scheduler-commands.js +7 -11
  5. package/application/commands/user-commands.js +5 -17
  6. package/application/index.js +2 -6
  7. package/core/Worker.js +7 -31
  8. package/core/create-handler.js +0 -9
  9. package/credential/repositories/credential-repository-documentdb.js +0 -34
  10. package/credential/repositories/credential-repository-interface.js +0 -15
  11. package/credential/repositories/credential-repository-mongo.js +0 -23
  12. package/credential/repositories/credential-repository-postgres.js +0 -28
  13. package/database/config.js +24 -48
  14. package/database/documentdb-utils.js +1 -6
  15. package/database/encryption/encryption-config.js +31 -10
  16. package/database/encryption/encryption-schema-registry.js +12 -93
  17. package/database/prisma.js +2 -4
  18. package/generated/prisma-mongodb/edge.js +4 -43
  19. package/generated/prisma-mongodb/index-browser.js +1 -40
  20. package/generated/prisma-mongodb/index.d.ts +111 -4739
  21. package/generated/prisma-mongodb/index.js +4 -43
  22. package/generated/prisma-mongodb/package.json +1 -1
  23. package/generated/prisma-mongodb/schema.prisma +0 -92
  24. package/generated/prisma-mongodb/wasm.js +4 -43
  25. package/generated/prisma-postgresql/edge.js +4 -43
  26. package/generated/prisma-postgresql/index-browser.js +1 -40
  27. package/generated/prisma-postgresql/index.d.ts +33 -4966
  28. package/generated/prisma-postgresql/index.js +4 -43
  29. package/generated/prisma-postgresql/package.json +1 -1
  30. package/generated/prisma-postgresql/schema.prisma +0 -87
  31. package/generated/prisma-postgresql/wasm.js +4 -43
  32. package/handlers/app-definition-loader.js +19 -121
  33. package/handlers/app-handler-helpers.js +3 -25
  34. package/handlers/backend-utils.js +25 -31
  35. package/handlers/middleware/admin-auth.js +1 -14
  36. package/handlers/routers/auth.js +10 -46
  37. package/handlers/routers/health.js +4 -13
  38. package/handlers/routers/integration-defined-routers.js +92 -144
  39. package/handlers/routers/integration-webhook-routers.js +64 -102
  40. package/handlers/workers/integration-defined-workers.js +2 -5
  41. package/index.js +1 -65
  42. package/infrastructure/scheduler/index.js +6 -19
  43. package/infrastructure/scheduler/scheduler-service-factory.js +7 -55
  44. package/integrations/index.js +0 -1
  45. package/integrations/integration-router.js +96 -131
  46. package/integrations/repositories/integration-repository-documentdb.js +3 -35
  47. package/integrations/repositories/integration-repository-interface.js +1 -17
  48. package/integrations/repositories/integration-repository-mongo.js +76 -59
  49. package/integrations/repositories/integration-repository-postgres.js +76 -62
  50. package/integrations/tests/doubles/test-integration-repository.js +1 -12
  51. package/integrations/use-cases/create-integration.js +20 -55
  52. package/integrations/use-cases/get-integrations-for-user.js +40 -80
  53. package/integrations/use-cases/index.js +1 -7
  54. package/integrations/utils/map-integration-dto.js +14 -43
  55. package/modules/index.js +0 -14
  56. package/modules/module-factory.js +0 -12
  57. package/modules/module.js +2 -53
  58. package/modules/repositories/module-repository-documentdb.js +6 -51
  59. package/modules/repositories/module-repository-interface.js +2 -19
  60. package/modules/repositories/module-repository-mongo.js +74 -67
  61. package/modules/repositories/module-repository-postgres.js +74 -66
  62. package/modules/repositories/module-repository.js +1 -2
  63. package/modules/requester/requester.js +2 -27
  64. package/modules/use-cases/get-entities-for-user.js +13 -26
  65. package/modules/use-cases/get-entity-options-by-id.js +4 -10
  66. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  67. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  68. package/modules/use-cases/get-module.js +4 -10
  69. package/modules/use-cases/process-authorization-callback.js +19 -53
  70. package/modules/use-cases/refresh-entity-options.js +4 -10
  71. package/modules/use-cases/test-module-auth.js +4 -10
  72. package/package.json +5 -6
  73. package/prisma-mongodb/schema.prisma +0 -92
  74. package/prisma-postgresql/schema.prisma +0 -87
  75. package/queues/index.js +0 -25
  76. package/types/index.d.ts +0 -2
  77. package/user/repositories/user-repository-documentdb.js +2 -27
  78. package/user/repositories/user-repository-interface.js +0 -18
  79. package/user/repositories/user-repository-mongo.js +0 -24
  80. package/user/repositories/user-repository-postgres.js +0 -18
  81. package/user/use-cases/authenticate-user.js +1 -7
  82. package/user/use-cases/get-user-from-adopter-jwt.js +124 -95
  83. package/user/use-cases/get-user-from-x-frigg-headers.js +80 -83
  84. package/user/user.js +1 -64
  85. package/credential/use-cases/credential-operations-for-user.js +0 -202
  86. package/credential/use-cases/reauthorize-credential-for-user.js +0 -73
  87. package/database/organization-where.js +0 -18
  88. package/database/unique-violation.js +0 -25
  89. package/extensions/bootstrap-runner.js +0 -43
  90. package/extensions/extension-loader.js +0 -187
  91. package/extensions/index.js +0 -41
  92. package/extensions/initialize-app.js +0 -123
  93. package/extensions/route-mounter.js +0 -103
  94. package/extensions/schema-composer.js +0 -188
  95. package/infrastructure/scheduler/netlify-scheduler-adapter.js +0 -216
  96. package/infrastructure/scheduler/scheduled-job-repository.js +0 -118
  97. package/integrations/repositories/integration-not-found.js +0 -14
  98. package/integrations/schedule-config.js +0 -80
  99. package/integrations/use-cases/dispatch-ongoing-syncs.js +0 -100
  100. package/integrations/use-cases/integration-operations-for-user.js +0 -256
  101. package/integrations/use-cases/resolve-integration-ownership.js +0 -177
  102. package/management-api/create-management-api-router.js +0 -49
  103. package/management-api/error-response.js +0 -116
  104. package/management-api/management-api-config.js +0 -151
  105. package/management-api/meta-router.js +0 -76
  106. package/management-api/openapi/build-openapi.js +0 -144
  107. package/management-api/openapi/components.js +0 -408
  108. package/management-api/openapi/v1-operations.js +0 -83
  109. package/management-api/openapi/v2-operations.js +0 -264
  110. package/management-api/route-registry.js +0 -411
  111. package/management-api/test-support/http-client.js +0 -39
  112. package/management-api/use-cases/get-management-api-meta.js +0 -57
  113. package/management-api/v1-deprecation.js +0 -120
  114. package/management-api/v2/create-v2-router.js +0 -85
  115. package/management-api/v2/dependencies.js +0 -281
  116. package/management-api/v2/dto.js +0 -143
  117. package/management-api/v2/handlers/authorization.js +0 -94
  118. package/management-api/v2/handlers/credentials.js +0 -33
  119. package/management-api/v2/handlers/entities.js +0 -77
  120. package/management-api/v2/handlers/integrations.js +0 -128
  121. package/management-api/v2/handlers/proxy.js +0 -34
  122. package/management-api/v2/request.js +0 -85
  123. package/management-api/v2/test-support/fake-dependencies.js +0 -103
  124. package/modules/domain/authorization-session.js +0 -144
  125. package/modules/entity-scope.js +0 -15
  126. package/modules/entity-type-registry.js +0 -311
  127. package/modules/proxy/proxy-errors.js +0 -20
  128. package/modules/proxy/proxy-path.js +0 -179
  129. package/modules/proxy/proxy-policy.js +0 -248
  130. package/modules/repositories/authorization-session-repository-documentdb.js +0 -112
  131. package/modules/repositories/authorization-session-repository-factory.js +0 -31
  132. package/modules/repositories/authorization-session-repository-interface.js +0 -47
  133. package/modules/repositories/authorization-session-repository-prisma.js +0 -87
  134. package/modules/repositories/entity-not-found.js +0 -18
  135. package/modules/requester/proxy-request.js +0 -244
  136. package/modules/scope-config.js +0 -192
  137. package/modules/scope-policy.js +0 -112
  138. package/modules/scope-resolution.js +0 -288
  139. package/modules/scope-visibility.js +0 -247
  140. package/modules/tests/doubles/in-memory-authorization-session-repository.js +0 -45
  141. package/modules/tests/doubles/ownership-matching.js +0 -18
  142. package/modules/use-cases/authorize-entity-for-user.js +0 -61
  143. package/modules/use-cases/create-entity-from-credential.js +0 -113
  144. package/modules/use-cases/entity-operations-for-user.js +0 -162
  145. package/modules/use-cases/entity-types.js +0 -139
  146. package/modules/use-cases/execute-entity-proxy-request.js +0 -286
  147. package/modules/use-cases/get-authorization-requirements.js +0 -100
  148. package/modules/use-cases/get-entity-module-for-user.js +0 -113
  149. package/modules/use-cases/manage-access.js +0 -21
  150. package/modules/use-cases/multi-step-authorization.js +0 -329
  151. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +0 -28
  152. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +0 -26
  153. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +0 -25
  154. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +0 -28
  155. package/providers/index.js +0 -23
  156. package/providers/resolve-provider.js +0 -93
  157. package/providers/runtime-detection.js +0 -124
  158. package/queues/providers/index.js +0 -11
  159. package/queues/providers/netlify-background-provider.js +0 -150
  160. package/queues/providers/qstash-queue-provider.js +0 -219
  161. package/queues/providers/sqs-queue-provider.js +0 -70
  162. package/queues/queue-client-interface.js +0 -55
  163. package/queues/queue-message-auth.js +0 -193
  164. package/queues/queue-provider-factory.js +0 -101
  165. package/queues/queue-provider.js +0 -65
  166. package/queues/sqs-queue-client.js +0 -81
  167. package/types/modules/index.d.ts +0 -197
  168. package/types/user/index.d.ts +0 -134
  169. package/user/adopter-jwt-config.js +0 -177
  170. package/user/adopter-jwt-errors.js +0 -59
  171. package/user/adopter-token-verifier.js +0 -122
  172. package/user/app-user-helpers.js +0 -97
  173. package/user/create-user-authentication.js +0 -64
  174. package/user/membership.js +0 -51
  175. package/user/repositories/organization-membership-record.js +0 -19
  176. package/user/repositories/organization-membership-repository-documentdb.js +0 -106
  177. package/user/repositories/organization-membership-repository-factory.js +0 -42
  178. package/user/repositories/organization-membership-repository-interface.js +0 -57
  179. package/user/repositories/organization-membership-repository-mongo.js +0 -13
  180. package/user/repositories/organization-membership-repository-postgres.js +0 -29
  181. package/user/repositories/organization-membership-repository-prisma.js +0 -81
  182. package/user/tests/doubles/adopter-jwt-fixtures.js +0 -220
  183. package/user/use-cases/ensure-organization-membership.js +0 -92
  184. package/user/use-cases/find-individual-users-by-organization.js +0 -54
@@ -1,123 +0,0 @@
1
- /**
2
- * Application Initialization with Extension Lifecycle
3
- *
4
- * Provides an async initialization function that runs extension bootstraps
5
- * after database connection but before router creation. This is the integration
6
- * point for providers (Lambda, Netlify) to hook into the extension lifecycle.
7
- *
8
- * Call `initializeApp()` during the async startup phase of your handler/function.
9
- * It is safe to call multiple times — subsequent calls are no-ops.
10
- *
11
- * @example
12
- * const { initializeApp } = require('@friggframework/core/extensions/initialize-app');
13
- *
14
- * // In a Lambda handler or Netlify function:
15
- * await initializeApp();
16
- * // Now extensions are bootstrapped and router can be created
17
- */
18
-
19
- const { loadExtensions } = require('./extension-loader');
20
- const { runExtensionBootstraps } = require('./bootstrap-runner');
21
-
22
- let _initialized = false;
23
- let _initPromise = null;
24
-
25
- /**
26
- * Initializes extensions by running bootstrap hooks.
27
- *
28
- * This function:
29
- * 1. Loads the app definition
30
- * 2. Loads and validates extensions
31
- * 3. Runs extension bootstrap hooks in sequence
32
- *
33
- * Bootstrap hooks receive (prisma, appDefinition) and can:
34
- * - Load credentials from database into integration Definition.env
35
- * - Register services or middleware
36
- * - Perform any one-time async initialization
37
- *
38
- * @param {Object} [options]
39
- * @param {Object} [options.appDefinition] - Override app definition (skips loadAppDefinition)
40
- * @param {Object} [options.prisma] - Override Prisma client instance
41
- * @param {boolean} [options.force=false] - Force re-initialization
42
- * @returns {Promise<{extensions: Array}>} The loaded extensions
43
- */
44
- async function initializeApp(options = {}) {
45
- const { force = false } = options;
46
-
47
- // Return cached promise if already initializing (prevent race conditions)
48
- if (_initPromise && !force) {
49
- return _initPromise;
50
- }
51
-
52
- if (_initialized && !force) {
53
- return { extensions: [] };
54
- }
55
-
56
- _initPromise = _doInitialize(options);
57
-
58
- try {
59
- const result = await _initPromise;
60
- _initialized = true;
61
- return result;
62
- } catch (error) {
63
- _initPromise = null;
64
- throw error;
65
- }
66
- }
67
-
68
- async function _doInitialize(options = {}) {
69
- let { appDefinition, prisma } = options;
70
-
71
- // Load app definition if not provided
72
- if (!appDefinition) {
73
- try {
74
- const { loadAppDefinition } = require('../handlers/app-definition-loader');
75
- const loaded = loadAppDefinition();
76
- appDefinition = loaded.appDefinition;
77
- } catch {
78
- // No app definition available — skip extension bootstrap
79
- return { extensions: [] };
80
- }
81
- }
82
-
83
- if (!appDefinition) {
84
- return { extensions: [] };
85
- }
86
-
87
- // Load extensions
88
- const extensions = loadExtensions(appDefinition);
89
-
90
- if (extensions.length === 0) {
91
- return { extensions };
92
- }
93
-
94
- // Get Prisma client if not provided
95
- if (!prisma) {
96
- try {
97
- const db = require('../database/prisma');
98
- prisma = db.prisma;
99
- } catch {
100
- // Prisma not available — skip bootstrap
101
- console.warn('Prisma client not available, skipping extension bootstraps');
102
- return { extensions };
103
- }
104
- }
105
-
106
- // Run bootstrap hooks
107
- await runExtensionBootstraps(extensions, { prisma, appDefinition });
108
-
109
- return { extensions };
110
- }
111
-
112
- /**
113
- * Reset initialization state (for testing).
114
- */
115
- function resetInitialization() {
116
- _initialized = false;
117
- _initPromise = null;
118
- }
119
-
120
- module.exports = {
121
- initializeApp,
122
- resetInitialization,
123
- };
@@ -1,103 +0,0 @@
1
- /**
2
- * Route Mounter
3
- *
4
- * Mounts extension-defined Express routers onto the main app.
5
- * Each extension can declare routes with a base path and a handler factory.
6
- *
7
- * The handler factory receives (prisma, appDefinition) and returns an Express Router.
8
- * Routes are protected by the admin auth middleware by default.
9
- *
10
- * @example
11
- * mountExtensionRoutes(app, extensions, { prisma, appDefinition });
12
- */
13
-
14
- const { validateAdminApiKey } = require('../handlers/middleware/admin-auth');
15
-
16
- /**
17
- * Mounts all extension routes onto an Express app.
18
- *
19
- * @param {import('express').Express} app - Express app or router to mount on
20
- * @param {Array<Object>} extensions - Normalized extensions (from extension-loader)
21
- * @param {Object} context
22
- * @param {Object} context.prisma - Prisma client instance
23
- * @param {Object} context.appDefinition - Full app definition
24
- * @param {Function} [context.authMiddleware] - Override admin auth middleware
25
- */
26
- function mountExtensionRoutes(app, extensions, context = {}) {
27
- if (!extensions || extensions.length === 0) return;
28
-
29
- const { prisma, appDefinition, authMiddleware } = context;
30
- const adminAuth = authMiddleware || validateAdminApiKey;
31
-
32
- for (const ext of extensions) {
33
- if (!ext.routes) continue;
34
-
35
- const { path: basePath, handler } = ext.routes;
36
-
37
- let router;
38
- if (typeof handler === 'function') {
39
- // Handler factory: (prisma, appDefinition) => Router
40
- router = handler(prisma, appDefinition);
41
- } else if (handler && handler.router) {
42
- // Direct router object export pattern: { router }
43
- router = handler.router;
44
- } else if (handler && handler.default && typeof handler.default === 'function') {
45
- // ES module default export
46
- router = handler.default(prisma, appDefinition);
47
- } else {
48
- console.warn(
49
- `Extension "${ext.name}": routes.handler is not a function or router object, skipping`
50
- );
51
- continue;
52
- }
53
-
54
- // Mount with admin auth middleware
55
- app.use(basePath, adminAuth, router);
56
- }
57
- }
58
-
59
- module.exports = { mountExtensionRoutes };
60
-
61
- /**
62
- * Builds one router serving every app-level extension's routes
63
- * (`appDefinition.coreExtensions[].routes`), each behind the admin API key.
64
- *
65
- * Lazy by design: the extensions, their route factories and the Prisma
66
- * client are only touched on the first request, so requiring a handler
67
- * module never connects anything.
68
- *
69
- * @param {Object} [params]
70
- * @param {Object} [params.appDefinition] - raw app Definition; defaults to
71
- * loadAppDefinition().appDefinition on first request.
72
- * @param {Object} [params.prisma] - defaults to core's Prisma client.
73
- * @returns {import('express').Router}
74
- */
75
- function createExtensionRoutesRouter({ appDefinition, prisma } = {}) {
76
- const express = require('express');
77
- const outer = express.Router();
78
- let inner = null;
79
-
80
- outer.use((req, res, next) => {
81
- if (!inner) {
82
- const definition =
83
- appDefinition ||
84
- require('../handlers/app-definition-loader').loadAppDefinition()
85
- .appDefinition;
86
- const { loadExtensions } = require('./extension-loader');
87
- const extensions = loadExtensions(definition);
88
- const built = express.Router();
89
- if (extensions.some((ext) => ext.routes)) {
90
- mountExtensionRoutes(built, extensions, {
91
- prisma: prisma || require('../database/prisma').prisma,
92
- appDefinition: definition,
93
- });
94
- }
95
- inner = built;
96
- }
97
- return inner(req, res, next);
98
- });
99
-
100
- return outer;
101
- }
102
-
103
- module.exports.createExtensionRoutesRouter = createExtensionRoutesRouter;
@@ -1,188 +0,0 @@
1
- /**
2
- * Schema Composer
3
- *
4
- * Merges extension .prisma schema fragments with a base Prisma schema.
5
- * Extensions can add new models/enums that get composed into the final schema
6
- * used for `prisma generate` and migrations.
7
- *
8
- * Two approaches are supported:
9
- * 1. Build-time merge: Concatenate model definitions from extension files
10
- * into the base schema and write a merged output file.
11
- * 2. Multi-file schema (Prisma 5.15+): Return a list of schema paths for
12
- * Prisma's native `prismaSchemaFolder` feature.
13
- *
14
- * @example
15
- * const { composeSchemas } = require('@friggframework/core/extensions/schema-composer');
16
- *
17
- * // Build-time merge — writes a merged schema file
18
- * await composeSchemas({
19
- * baseSchemaPath: '/path/to/prisma-postgresql/schema.prisma',
20
- * extensionSchemaPaths: ['/path/to/extensions/db-credentials/schema.prisma'],
21
- * outputPath: '/path/to/prisma-postgresql/schema.composed.prisma',
22
- * });
23
- */
24
-
25
- const fs = require('fs');
26
- const path = require('path');
27
-
28
- /**
29
- * Extracts model/enum blocks from a .prisma file, stripping out
30
- * generator and datasource blocks (which should only appear in the base schema).
31
- *
32
- * @param {string} schemaContent - Raw .prisma file content
33
- * @returns {string} Only model/enum/type definitions
34
- */
35
- function extractModelBlocks(schemaContent) {
36
- const lines = schemaContent.split('\n');
37
- const result = [];
38
- let depth = 0;
39
- let inBlock = false;
40
- let blockType = null;
41
-
42
- for (const line of lines) {
43
- const trimmed = line.trim();
44
-
45
- // Detect block start
46
- if (depth === 0 && !inBlock) {
47
- const blockMatch = trimmed.match(
48
- /^(model|enum|type)\s+\w+\s*\{/
49
- );
50
- if (blockMatch) {
51
- inBlock = true;
52
- blockType = blockMatch[1];
53
- result.push(line);
54
- depth += (line.match(/\{/g) || []).length;
55
- depth -= (line.match(/\}/g) || []).length;
56
- continue;
57
- }
58
-
59
- // Skip generator/datasource blocks
60
- const skipMatch = trimmed.match(
61
- /^(generator|datasource)\s+\w+\s*\{/
62
- );
63
- if (skipMatch) {
64
- inBlock = true;
65
- blockType = 'skip';
66
- depth += (line.match(/\{/g) || []).length;
67
- depth -= (line.match(/\}/g) || []).length;
68
- continue;
69
- }
70
-
71
- // Keep standalone comments between blocks
72
- if (trimmed.startsWith('//') || trimmed === '') {
73
- // Only keep if we've already accumulated some model blocks
74
- if (result.length > 0) {
75
- result.push(line);
76
- }
77
- continue;
78
- }
79
- } else if (inBlock) {
80
- depth += (line.match(/\{/g) || []).length;
81
- depth -= (line.match(/\}/g) || []).length;
82
-
83
- if (blockType !== 'skip') {
84
- result.push(line);
85
- }
86
-
87
- if (depth <= 0) {
88
- inBlock = false;
89
- blockType = null;
90
- depth = 0;
91
- if (result.length > 0) {
92
- result.push(''); // blank line between blocks
93
- }
94
- }
95
- }
96
- }
97
-
98
- return result.join('\n').trim();
99
- }
100
-
101
- /**
102
- * Composes a merged Prisma schema from a base schema + extension fragments.
103
- *
104
- * @param {Object} options
105
- * @param {string} options.baseSchemaPath - Absolute path to the core .prisma file
106
- * @param {string[]} options.extensionSchemaPaths - Absolute paths to extension .prisma files
107
- * @param {string} [options.outputPath] - Where to write the merged schema.
108
- * Defaults to `<baseDir>/schema.composed.prisma`
109
- * @returns {string} The merged schema content
110
- */
111
- function composeSchemas({ baseSchemaPath, extensionSchemaPaths, outputPath }) {
112
- if (!baseSchemaPath) {
113
- throw new Error('baseSchemaPath is required');
114
- }
115
-
116
- if (
117
- !extensionSchemaPaths ||
118
- !Array.isArray(extensionSchemaPaths) ||
119
- extensionSchemaPaths.length === 0
120
- ) {
121
- // No extensions — just return base schema as-is
122
- const baseContent = fs.readFileSync(baseSchemaPath, 'utf-8');
123
- return baseContent;
124
- }
125
-
126
- const baseContent = fs.readFileSync(baseSchemaPath, 'utf-8');
127
-
128
- // Collect model blocks from each extension
129
- const extensionBlocks = [];
130
- for (const extPath of extensionSchemaPaths) {
131
- if (!fs.existsSync(extPath)) {
132
- throw new Error(
133
- `Extension schema not found: ${extPath}`
134
- );
135
- }
136
- const extContent = fs.readFileSync(extPath, 'utf-8');
137
- const models = extractModelBlocks(extContent);
138
- if (models) {
139
- extensionBlocks.push(
140
- `// --- Extension schema from: ${path.basename(path.dirname(extPath))}/${path.basename(extPath)} ---`,
141
- models
142
- );
143
- }
144
- }
145
-
146
- if (extensionBlocks.length === 0) {
147
- return baseContent;
148
- }
149
-
150
- // Append extension models to the base schema
151
- const merged = [
152
- baseContent.trimEnd(),
153
- '',
154
- '// =========================================================================',
155
- '// Extension Models (auto-composed — do not edit manually)',
156
- '// =========================================================================',
157
- '',
158
- ...extensionBlocks,
159
- '',
160
- ].join('\n');
161
-
162
- // Write the merged schema if outputPath is specified
163
- const resolvedOutput =
164
- outputPath ||
165
- path.join(path.dirname(baseSchemaPath), 'schema.composed.prisma');
166
-
167
- fs.writeFileSync(resolvedOutput, merged, 'utf-8');
168
-
169
- return merged;
170
- }
171
-
172
- /**
173
- * Returns schema paths suitable for Prisma's native multi-file schema support
174
- * (prismaSchemaFolder feature, Prisma 5.15+).
175
- *
176
- * @param {string} baseSchemaPath - Path to the core schema
177
- * @param {string[]} extensionSchemaPaths - Paths to extension schemas
178
- * @returns {string[]} All schema file paths
179
- */
180
- function getSchemaFilePaths(baseSchemaPath, extensionSchemaPaths) {
181
- return [baseSchemaPath, ...(extensionSchemaPaths || [])];
182
- }
183
-
184
- module.exports = {
185
- composeSchemas,
186
- extractModelBlocks,
187
- getSchemaFilePaths,
188
- };
@@ -1,216 +0,0 @@
1
- /**
2
- * Netlify Scheduler Adapter
3
- *
4
- * Implements SchedulerServiceInterface for Netlify deployments.
5
- *
6
- * Netlify Scheduled Functions use cron syntax but are defined statically in
7
- * netlify.toml or via the @netlify/functions schedule() helper. They cannot
8
- * be created dynamically at runtime like EventBridge Scheduler.
9
- *
10
- * Strategy for one-time scheduled jobs on Netlify:
11
- * 1. Store the schedule in the database (same as mock adapter pattern)
12
- * 2. A Netlify Scheduled Function runs on a cron interval (e.g., every 5 min)
13
- * 3. The cron function queries for due schedules and dispatches them
14
- * to a background function for execution
15
- *
16
- * This is a "poll-and-dispatch" pattern vs EventBridge's "push" pattern.
17
- * Trade-off: slightly less precise timing (up to cron interval delay),
18
- * but works on any platform without cloud-specific scheduling APIs.
19
- *
20
- * For integrations that need the queue provider to dispatch jobs:
21
- * - queueResourceId maps to the background function URL path
22
- * - Payload is stored and forwarded when the cron fires
23
- */
24
-
25
- const { SchedulerServiceInterface } = require('./scheduler-service-interface');
26
-
27
- // The one queue worker every Netlify deployment has (provider-netlify's
28
- // worker-background function); it dispatches by integrationName.
29
- const DEFAULT_WORKER_PATH = '/.netlify/functions/worker-background';
30
- const DEFAULT_LEASE_MS = 5 * 60 * 1000;
31
-
32
- class NetlifySchedulerAdapter extends SchedulerServiceInterface {
33
- /**
34
- * @param {Object} options
35
- * @param {Object} options.repository - Repository for persisting schedules
36
- * Must implement: save(schedule), delete(scheduleName),
37
- * findByName(scheduleName), findDue(now)
38
- * @param {Object} [options.queueProvider] - Queue provider for dispatching due jobs
39
- * @param {number} [options.leaseMs] - how long a claimed (PROCESSING) job
40
- * is held before another tick may take it again (default 5 minutes,
41
- * well past a Netlify scheduled function's 60-second limit)
42
- */
43
- constructor(options = {}) {
44
- super();
45
- this.repository = options.repository;
46
- this.queueProvider = options.queueProvider;
47
- this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;
48
-
49
- if (!this.repository) {
50
- console.warn(
51
- '[NetlifyScheduler] No repository provided. ' +
52
- 'Schedules will be stored in memory (lost on function restart). ' +
53
- 'Provide a database-backed repository for production use.'
54
- );
55
- this._inMemorySchedules = new Map();
56
- }
57
- }
58
-
59
- /**
60
- * Where a due job is sent. Netlify has no per-integration queues, so an
61
- * SQS-style queue URL (often unset here) maps to the worker function;
62
- * a function path is kept as given.
63
- *
64
- * @param {string} [queueUrl]
65
- * @returns {string} a path NetlifyBackgroundProvider.send() accepts
66
- */
67
- toQueueResourceId(queueUrl) {
68
- return typeof queueUrl === 'string' && queueUrl.startsWith('/')
69
- ? queueUrl
70
- : DEFAULT_WORKER_PATH;
71
- }
72
-
73
- async scheduleOneTime({
74
- scheduleName,
75
- scheduleAt,
76
- queueResourceId,
77
- payload,
78
- }) {
79
- if (!scheduleName) throw new Error('scheduleName is required');
80
- if (!scheduleAt || !(scheduleAt instanceof Date))
81
- throw new Error('scheduleAt must be a valid Date object');
82
- if (!queueResourceId) throw new Error('queueResourceId is required');
83
-
84
- const scheduleData = {
85
- scheduleName,
86
- scheduledAt: scheduleAt.toISOString(),
87
- queueResourceId,
88
- payload,
89
- createdAt: new Date().toISOString(),
90
- state: 'PENDING',
91
- };
92
-
93
- if (this.repository) {
94
- await this.repository.save(scheduleData);
95
- } else {
96
- this._inMemorySchedules.set(scheduleName, scheduleData);
97
- }
98
-
99
- console.log(
100
- `[NetlifyScheduler] Scheduled: ${scheduleName} for ${scheduleAt.toISOString()}`
101
- );
102
-
103
- return {
104
- scheduledJobId: `netlify-schedule-${scheduleName}`,
105
- scheduledAt: scheduleAt.toISOString(),
106
- };
107
- }
108
-
109
- async deleteSchedule(scheduleName) {
110
- if (!scheduleName) throw new Error('scheduleName is required');
111
-
112
- if (this.repository) {
113
- await this.repository.delete(scheduleName);
114
- } else {
115
- this._inMemorySchedules.delete(scheduleName);
116
- }
117
-
118
- console.log(`[NetlifyScheduler] Deleted schedule: ${scheduleName}`);
119
- }
120
-
121
- async getScheduleStatus(scheduleName) {
122
- if (!scheduleName) throw new Error('scheduleName is required');
123
-
124
- let schedule;
125
- if (this.repository) {
126
- schedule = await this.repository.findByName(scheduleName);
127
- } else {
128
- schedule = this._inMemorySchedules.get(scheduleName);
129
- }
130
-
131
- if (!schedule) {
132
- return { exists: false };
133
- }
134
-
135
- return {
136
- exists: true,
137
- scheduledAt: schedule.scheduledAt,
138
- state: schedule.state,
139
- };
140
- }
141
-
142
- /**
143
- * Process due schedules. Called by the Netlify cron function.
144
- *
145
- * Finds all schedules where scheduledAt <= now, dispatches them
146
- * to the queue provider, and marks them as completed.
147
- *
148
- * @returns {Promise<{ processed: number, errors: number }>}
149
- */
150
- async processDueSchedules() {
151
- if (!this.repository) {
152
- console.warn(
153
- '[NetlifyScheduler] Cannot process due schedules without a repository'
154
- );
155
- return { processed: 0, errors: 0, skipped: 0 };
156
- }
157
-
158
- const now = new Date();
159
- const lease = { leaseMs: this.leaseMs };
160
- const dueSchedules = await this.repository.findDue(now, lease);
161
-
162
- let processed = 0;
163
- let errors = 0;
164
- let skipped = 0;
165
-
166
- for (const schedule of dueSchedules) {
167
- try {
168
- // Claim before dispatch. Two overlapping ticks can both see
169
- // the row in findDue; only the one whose conditional update
170
- // wins sends it. A repository without claim() (a custom one)
171
- // keeps the old unconditional PROCESSING write.
172
- const claimed =
173
- typeof this.repository.claim === 'function'
174
- ? await this.repository.claim(schedule.scheduleName, now, lease)
175
- : (await this.repository.save({ ...schedule, state: 'PROCESSING' }), true);
176
- if (!claimed) {
177
- skipped++;
178
- continue;
179
- }
180
-
181
- if (this.queueProvider) {
182
- await this.queueProvider.send(
183
- schedule.payload,
184
- schedule.queueResourceId
185
- );
186
- } else {
187
- console.log(
188
- `[NetlifyScheduler] No queue provider — logging payload for: ${schedule.scheduleName}`,
189
- JSON.stringify(schedule.payload)
190
- );
191
- }
192
-
193
- await this.repository.delete(schedule.scheduleName);
194
- processed++;
195
- } catch (error) {
196
- console.error(
197
- `[NetlifyScheduler] Error processing schedule ${schedule.scheduleName}:`,
198
- error
199
- );
200
- // Mark as FAILED so it won't be re-dispatched automatically.
201
- // Operators can inspect FAILED schedules and retry manually.
202
- await this.repository
203
- .save({ ...schedule, state: 'FAILED' })
204
- .catch(() => {});
205
- errors++;
206
- }
207
- }
208
-
209
- console.log(
210
- `[NetlifyScheduler] Processed ${processed} due schedules, ${errors} errors, ${skipped} claimed elsewhere`
211
- );
212
- return { processed, errors, skipped };
213
- }
214
- }
215
-
216
- module.exports = { NetlifySchedulerAdapter, DEFAULT_WORKER_PATH, DEFAULT_LEASE_MS };