@friggframework/core 2.0.0--canary.703.12b980b.0 → 2.0.0--canary.707.df80bfd.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 (308) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/CLAUDE.md +28 -0
  3. package/README.md +105 -0
  4. package/application/commands/integration-commands.js +20 -10
  5. package/application/commands/scheduler-commands.js +11 -7
  6. package/application/commands/user-commands.js +17 -5
  7. package/application/index.js +6 -2
  8. package/core/Worker.js +31 -7
  9. package/core/create-handler.js +9 -0
  10. package/credential/repositories/credential-repository-documentdb.js +34 -0
  11. package/credential/repositories/credential-repository-interface.js +15 -0
  12. package/credential/repositories/credential-repository-mongo.js +23 -0
  13. package/credential/repositories/credential-repository-postgres.js +28 -0
  14. package/credential/use-cases/credential-operations-for-user.js +202 -0
  15. package/credential/use-cases/reauthorize-credential-for-user.js +73 -0
  16. package/database/config.js +48 -24
  17. package/database/documentdb-encryption-service.js +9 -22
  18. package/database/documentdb-utils.js +2 -2
  19. package/database/encryption/README.md +78 -14
  20. package/database/encryption/documentdb-encryption-service.md +78 -1
  21. package/database/encryption/encryption-config.js +219 -0
  22. package/database/encryption/encryption-schema-registry.js +121 -24
  23. package/database/encryption/field-encryption-service.js +69 -5
  24. package/database/encryption/integration-mapping-encryption.js +1 -1
  25. package/database/encryption/test-support/fake-ciphertext.js +15 -0
  26. package/database/organization-where.js +18 -0
  27. package/database/prisma.js +15 -38
  28. package/database/unique-violation.js +25 -0
  29. package/database/use-cases/check-encryption-health-use-case.js +43 -52
  30. package/errors/index.js +0 -4
  31. package/extensions/bootstrap-runner.js +43 -0
  32. package/extensions/extension-loader.js +230 -0
  33. package/extensions/index.js +44 -0
  34. package/extensions/initialize-app.js +123 -0
  35. package/extensions/prisma-composer.js +270 -0
  36. package/extensions/route-mounter.js +103 -0
  37. package/extensions/schema-composer.js +188 -0
  38. package/generated/prisma-mongodb/edge.js +33 -42
  39. package/generated/prisma-mongodb/index-browser.js +30 -39
  40. package/generated/prisma-mongodb/index.d.ts +3187 -2005
  41. package/generated/prisma-mongodb/index.js +33 -42
  42. package/generated/prisma-mongodb/package.json +1 -1
  43. package/generated/prisma-mongodb/schema.prisma +86 -59
  44. package/generated/prisma-mongodb/wasm.js +33 -42
  45. package/generated/prisma-postgresql/edge.js +33 -42
  46. package/generated/prisma-postgresql/index-browser.js +30 -39
  47. package/generated/prisma-postgresql/index.d.ts +3380 -2177
  48. package/generated/prisma-postgresql/index.js +33 -42
  49. package/generated/prisma-postgresql/package.json +1 -1
  50. package/generated/prisma-postgresql/schema.prisma +81 -57
  51. package/generated/prisma-postgresql/wasm.js +33 -42
  52. package/handlers/WEBHOOKS.md +0 -29
  53. package/handlers/app-definition-loader.js +128 -19
  54. package/handlers/app-handler-helpers.js +27 -8
  55. package/handlers/backend-utils.js +31 -25
  56. package/handlers/integration-event-dispatcher.js +3 -7
  57. package/handlers/middleware/admin-auth.js +14 -1
  58. package/handlers/routers/auth.js +46 -10
  59. package/handlers/routers/health.js +13 -4
  60. package/handlers/routers/integration-defined-routers.js +144 -92
  61. package/handlers/routers/integration-webhook-routers.js +100 -50
  62. package/handlers/workers/integration-defined-workers.js +5 -2
  63. package/index.js +66 -16
  64. package/infrastructure/scheduler/index.js +19 -6
  65. package/infrastructure/scheduler/netlify-scheduler-adapter.js +216 -0
  66. package/infrastructure/scheduler/scheduled-job-repository.js +118 -0
  67. package/infrastructure/scheduler/scheduler-service-factory.js +55 -7
  68. package/integrations/index.js +1 -14
  69. package/integrations/integration-base.js +2 -163
  70. package/integrations/integration-router.js +132 -102
  71. package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
  72. package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
  73. package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
  74. package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
  75. package/integrations/repositories/integration-mapping-repository.js +0 -29
  76. package/integrations/repositories/integration-not-found.js +14 -0
  77. package/integrations/repositories/integration-repository-documentdb.js +37 -9
  78. package/integrations/repositories/integration-repository-interface.js +17 -4
  79. package/integrations/repositories/integration-repository-mongo.js +64 -96
  80. package/integrations/repositories/integration-repository-postgres.js +63 -81
  81. package/integrations/repositories/process-repository-mongo.js +1 -1
  82. package/integrations/schedule-config.js +80 -0
  83. package/integrations/tests/doubles/test-integration-repository.js +12 -1
  84. package/integrations/use-cases/create-integration.js +56 -31
  85. package/integrations/use-cases/delete-integration-for-user.js +4 -4
  86. package/integrations/use-cases/dispatch-ongoing-syncs.js +100 -0
  87. package/integrations/use-cases/get-integration-for-user.js +2 -4
  88. package/integrations/use-cases/get-integration-instance.js +4 -4
  89. package/integrations/use-cases/get-integrations-for-user.js +79 -39
  90. package/integrations/use-cases/get-possible-integrations.js +2 -7
  91. package/integrations/use-cases/index.js +7 -1
  92. package/integrations/use-cases/integration-operations-for-user.js +256 -0
  93. package/integrations/use-cases/resolve-integration-ownership.js +177 -0
  94. package/integrations/use-cases/update-integration.js +4 -4
  95. package/integrations/utils/map-integration-dto.js +43 -14
  96. package/management-api/create-management-api-router.js +49 -0
  97. package/management-api/error-response.js +116 -0
  98. package/management-api/management-api-config.js +151 -0
  99. package/management-api/meta-router.js +76 -0
  100. package/management-api/openapi/build-openapi.js +144 -0
  101. package/management-api/openapi/components.js +415 -0
  102. package/management-api/openapi/v1-operations.js +83 -0
  103. package/management-api/openapi/v2-operations.js +264 -0
  104. package/management-api/route-registry.js +411 -0
  105. package/management-api/test-support/http-client.js +39 -0
  106. package/management-api/use-cases/get-management-api-meta.js +57 -0
  107. package/management-api/v1-deprecation.js +120 -0
  108. package/management-api/v2/create-v2-router.js +85 -0
  109. package/management-api/v2/dependencies.js +281 -0
  110. package/management-api/v2/dto.js +143 -0
  111. package/management-api/v2/handlers/authorization.js +94 -0
  112. package/management-api/v2/handlers/credentials.js +33 -0
  113. package/management-api/v2/handlers/entities.js +77 -0
  114. package/management-api/v2/handlers/integrations.js +128 -0
  115. package/management-api/v2/handlers/proxy.js +34 -0
  116. package/management-api/v2/request.js +85 -0
  117. package/management-api/v2/test-support/fake-dependencies.js +103 -0
  118. package/modules/domain/authorization-session.js +144 -0
  119. package/modules/entity-scope.js +15 -0
  120. package/modules/entity-type-registry.js +311 -0
  121. package/modules/index.js +14 -0
  122. package/modules/module-factory.js +12 -0
  123. package/modules/module.js +53 -2
  124. package/modules/proxy/proxy-bases.js +169 -0
  125. package/modules/proxy/proxy-errors.js +31 -0
  126. package/modules/proxy/proxy-path.js +183 -0
  127. package/modules/proxy/proxy-policy.js +277 -0
  128. package/modules/repositories/authorization-session-repository-documentdb.js +112 -0
  129. package/modules/repositories/authorization-session-repository-factory.js +31 -0
  130. package/modules/repositories/authorization-session-repository-interface.js +47 -0
  131. package/modules/repositories/authorization-session-repository-prisma.js +87 -0
  132. package/modules/repositories/entity-not-found.js +18 -0
  133. package/modules/repositories/module-repository-documentdb.js +51 -6
  134. package/modules/repositories/module-repository-interface.js +19 -2
  135. package/modules/repositories/module-repository-mongo.js +67 -74
  136. package/modules/repositories/module-repository-postgres.js +66 -74
  137. package/modules/repositories/module-repository.js +2 -1
  138. package/modules/requester/proxy-request.js +245 -0
  139. package/modules/requester/requester.js +35 -5
  140. package/modules/scope-config.js +192 -0
  141. package/modules/scope-policy.js +112 -0
  142. package/modules/scope-resolution.js +288 -0
  143. package/modules/scope-visibility.js +247 -0
  144. package/modules/tests/doubles/in-memory-authorization-session-repository.js +45 -0
  145. package/modules/tests/doubles/ownership-matching.js +18 -0
  146. package/modules/use-cases/authorize-entity-for-user.js +61 -0
  147. package/modules/use-cases/create-entity-from-credential.js +113 -0
  148. package/modules/use-cases/entity-operations-for-user.js +162 -0
  149. package/modules/use-cases/entity-types.js +139 -0
  150. package/modules/use-cases/execute-entity-proxy-request.js +331 -0
  151. package/modules/use-cases/get-authorization-requirements.js +100 -0
  152. package/modules/use-cases/get-entities-for-user.js +26 -13
  153. package/modules/use-cases/get-entity-module-for-user.js +113 -0
  154. package/modules/use-cases/get-entity-options-by-id.js +10 -4
  155. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  156. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  157. package/modules/use-cases/get-module.js +10 -4
  158. package/modules/use-cases/manage-access.js +21 -0
  159. package/modules/use-cases/multi-step-authorization.js +329 -0
  160. package/modules/use-cases/process-authorization-callback.js +53 -19
  161. package/modules/use-cases/refresh-entity-options.js +10 -4
  162. package/modules/use-cases/test-module-auth.js +10 -4
  163. package/package.json +6 -7
  164. package/prisma-mongodb/schema.prisma +86 -59
  165. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +28 -0
  166. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +26 -0
  167. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +25 -0
  168. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +28 -0
  169. package/prisma-postgresql/schema.prisma +81 -57
  170. package/providers/index.js +23 -0
  171. package/providers/resolve-provider.js +93 -0
  172. package/providers/runtime-detection.js +124 -0
  173. package/queues/index.js +25 -0
  174. package/queues/providers/index.js +11 -0
  175. package/queues/providers/netlify-background-provider.js +150 -0
  176. package/queues/providers/qstash-queue-provider.js +219 -0
  177. package/queues/providers/sqs-queue-provider.js +70 -0
  178. package/queues/queue-client-interface.js +55 -0
  179. package/queues/queue-message-auth.js +193 -0
  180. package/queues/queue-provider-factory.js +101 -0
  181. package/queues/queue-provider.js +65 -0
  182. package/queues/queuer-util.js +2 -9
  183. package/queues/sqs-queue-client.js +81 -0
  184. package/types/index.d.ts +2 -0
  185. package/types/modules/index.d.ts +214 -0
  186. package/types/user/index.d.ts +134 -0
  187. package/user/adopter-jwt-config.js +177 -0
  188. package/user/adopter-jwt-errors.js +59 -0
  189. package/user/adopter-token-verifier.js +122 -0
  190. package/user/app-user-helpers.js +97 -0
  191. package/user/create-user-authentication.js +64 -0
  192. package/user/membership.js +51 -0
  193. package/user/repositories/organization-membership-record.js +19 -0
  194. package/user/repositories/organization-membership-repository-documentdb.js +106 -0
  195. package/user/repositories/organization-membership-repository-factory.js +42 -0
  196. package/user/repositories/organization-membership-repository-interface.js +57 -0
  197. package/user/repositories/organization-membership-repository-mongo.js +13 -0
  198. package/user/repositories/organization-membership-repository-postgres.js +29 -0
  199. package/user/repositories/organization-membership-repository-prisma.js +81 -0
  200. package/user/repositories/user-repository-documentdb.js +27 -2
  201. package/user/repositories/user-repository-interface.js +18 -0
  202. package/user/repositories/user-repository-mongo.js +24 -0
  203. package/user/repositories/user-repository-postgres.js +18 -0
  204. package/user/tests/doubles/adopter-jwt-fixtures.js +220 -0
  205. package/user/use-cases/authenticate-user.js +7 -1
  206. package/user/use-cases/ensure-organization-membership.js +92 -0
  207. package/user/use-cases/find-individual-users-by-organization.js +54 -0
  208. package/user/use-cases/get-user-from-adopter-jwt.js +95 -124
  209. package/user/use-cases/get-user-from-x-frigg-headers.js +83 -80
  210. package/user/user.js +64 -1
  211. package/errors/mapping-already-exists-error.js +0 -14
  212. package/handlers/workers/integration-triggers.js +0 -25
  213. package/infrastructure/scheduler/recurrence.js +0 -204
  214. package/integrations/define/DESIGN.md +0 -122
  215. package/integrations/define/config.js +0 -98
  216. package/integrations/define/define-app.js +0 -66
  217. package/integrations/define/define-extension.js +0 -154
  218. package/integrations/define/define-integration.js +0 -335
  219. package/integrations/define/examples/deal-alerts.js +0 -140
  220. package/integrations/define/extension-binding.js +0 -174
  221. package/integrations/define/index.js +0 -11
  222. package/integrations/define/json-schema-lite.js +0 -68
  223. package/integrations/define/subscriptions.js +0 -186
  224. package/integrations/define/tests/fixtures/hubspot.js +0 -109
  225. package/integrations/define/tests/fixtures/slack.js +0 -26
  226. package/integrations/define/use.js +0 -39
  227. package/integrations/definitions/README.md +0 -278
  228. package/integrations/definitions/canonical.js +0 -11
  229. package/integrations/definitions/capabilities/AUDIT.md +0 -480
  230. package/integrations/definitions/capabilities/acmeerp.capabilities.json +0 -633
  231. package/integrations/definitions/capabilities/asana.capabilities.json +0 -279
  232. package/integrations/definitions/capabilities/calendly.capabilities.json +0 -385
  233. package/integrations/definitions/capabilities/docusign.capabilities.json +0 -314
  234. package/integrations/definitions/capabilities/fathom.capabilities.json +0 -238
  235. package/integrations/definitions/capabilities/github.capabilities.json +0 -585
  236. package/integrations/definitions/capabilities/hubspot.capabilities.json +0 -822
  237. package/integrations/definitions/capabilities/jira.capabilities.json +0 -391
  238. package/integrations/definitions/capabilities/klaviyo.capabilities.json +0 -503
  239. package/integrations/definitions/capabilities/linear.capabilities.json +0 -378
  240. package/integrations/definitions/capabilities/netsuite.capabilities.json +0 -535
  241. package/integrations/definitions/capabilities/notion.capabilities.json +0 -208
  242. package/integrations/definitions/capabilities/phone.capabilities.json +0 -511
  243. package/integrations/definitions/capabilities/pipedrive.capabilities.json +0 -430
  244. package/integrations/definitions/capabilities/quickbooks.capabilities.json +0 -635
  245. package/integrations/definitions/capabilities/salesforce.capabilities.json +0 -568
  246. package/integrations/definitions/capabilities/shopify.capabilities.json +0 -1128
  247. package/integrations/definitions/capabilities/slack.capabilities.json +0 -373
  248. package/integrations/definitions/capabilities/stripe.capabilities.json +0 -630
  249. package/integrations/definitions/capabilities/webflow.capabilities.json +0 -196
  250. package/integrations/definitions/capabilities/zendesk.capabilities.json +0 -422
  251. package/integrations/definitions/compile.js +0 -80
  252. package/integrations/definitions/config-form.js +0 -137
  253. package/integrations/definitions/examples/acme-erp-quickbooks.definition.json +0 -467
  254. package/integrations/definitions/examples/asana-slack.definition.json +0 -219
  255. package/integrations/definitions/examples/calendly-salesforce.definition.json +0 -459
  256. package/integrations/definitions/examples/docusign-salesforce.definition.json +0 -305
  257. package/integrations/definitions/examples/fathom-hubspot-notion.definition.json +0 -575
  258. package/integrations/definitions/examples/github-linear.definition.json +0 -322
  259. package/integrations/definitions/examples/hubspot-slack.definition.json +0 -427
  260. package/integrations/definitions/examples/klaviyo-hubspot.definition.json +0 -336
  261. package/integrations/definitions/examples/phone-hubspot.definition.json +0 -633
  262. package/integrations/definitions/examples/pipedrive-hubspot.definition.json +0 -136
  263. package/integrations/definitions/examples/pipedrive-phone.definition.json +0 -340
  264. package/integrations/definitions/examples/records/phone-hubspot.definition-version.json +0 -652
  265. package/integrations/definitions/examples/records/phone-hubspot.integration.json +0 -86
  266. package/integrations/definitions/examples/records/phone-hubspot.mappings.json +0 -39
  267. package/integrations/definitions/examples/records/phone-hubspot.workflow-run.json +0 -62
  268. package/integrations/definitions/examples/shopify-klaviyo.definition.json +0 -488
  269. package/integrations/definitions/examples/shopify-netsuite.definition.json +0 -622
  270. package/integrations/definitions/examples/stripe-quickbooks.definition.json +0 -476
  271. package/integrations/definitions/examples/webflow-hubspot-slack.definition.json +0 -262
  272. package/integrations/definitions/examples/zendesk-jira.definition.json +0 -604
  273. package/integrations/definitions/expressions.js +0 -229
  274. package/integrations/definitions/index.js +0 -48
  275. package/integrations/definitions/integration-runtime.js +0 -779
  276. package/integrations/definitions/interpreter.js +0 -104
  277. package/integrations/definitions/manifests.js +0 -177
  278. package/integrations/definitions/renderers/common.js +0 -67
  279. package/integrations/definitions/renderers/html.js +0 -129
  280. package/integrations/definitions/renderers/hubspot.js +0 -59
  281. package/integrations/definitions/renderers/preview.js +0 -154
  282. package/integrations/definitions/renderers/slack.js +0 -146
  283. package/integrations/definitions/repositories/definition-version-repository.js +0 -67
  284. package/integrations/definitions/repositories/workflow-run-repository.js +0 -80
  285. package/integrations/definitions/router.js +0 -170
  286. package/integrations/definitions/runtime.js +0 -268
  287. package/integrations/definitions/schema/capability-manifest.v0.1.schema.json +0 -549
  288. package/integrations/definitions/schema/installation.v0.1.schema.json +0 -130
  289. package/integrations/definitions/schema/integration-definition.v0.1.schema.json +0 -909
  290. package/integrations/definitions/schema/records.md +0 -105
  291. package/integrations/definitions/schema-check.js +0 -58
  292. package/integrations/definitions/scripts/check-manifests.js +0 -220
  293. package/integrations/definitions/scripts/validate.js +0 -66
  294. package/integrations/definitions/steps.js +0 -123
  295. package/integrations/definitions/sync-engine.js +0 -297
  296. package/integrations/definitions/tests/helpers-fake-crm.js +0 -49
  297. package/integrations/definitions/transforms.js +0 -91
  298. package/integrations/definitions/use-cases/definition-use-cases.js +0 -245
  299. package/integrations/definitions/validate.js +0 -436
  300. package/integrations/definitions/versioning.js +0 -176
  301. package/integrations/definitions/webhooks.js +0 -119
  302. package/integrations/integration-types.js +0 -73
  303. package/integrations/triggers.js +0 -244
  304. package/integrations/use-cases/run-trigger-tick.js +0 -155
  305. package/integrations/use-cases/run-trigger.js +0 -77
  306. package/prisma-postgresql/migrations/20261018000000_add_data_defined_integrations/migration.sql +0 -66
  307. package/prisma-postgresql/migrations/20261019000000_workflow_run_waits/migration.sql +0 -7
  308. package/prisma-postgresql/migrations/20261019120000_definition_workspace/migration.sql +0 -5
@@ -0,0 +1,123 @@
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
+ };
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Prisma composer: puts core extensions' models into the Prisma client.
3
+ *
4
+ * Core ships one generated client per database (`generated/prisma-<db>`),
5
+ * built from `prisma-<db>/schema.prisma`. A core extension that declares a
6
+ * schema (`coreExtensions[].schema`) needs its models in that client, and on
7
+ * PostgreSQL its tables need migrations (`coreExtensions[].migrations`).
8
+ * Without this step the extension's models exist nowhere: every call to
9
+ * `prisma.<model>` is undefined, and the table is never created.
10
+ *
11
+ * At build time, for each database the app uses:
12
+ * 1. The pristine core schema is kept as `schema.base.prisma` (taken from
13
+ * `schema.prisma` the first time), so composing again never appends twice.
14
+ * 2. `schema.prisma` becomes base + the extensions' models. Everything that
15
+ * reads the schema (prisma generate, the migration runner, the Lambda
16
+ * layer, which copies the generated client's schema) sees the composed one.
17
+ * 3. PostgreSQL: each extension migration folder is copied into
18
+ * `prisma-postgresql/migrations`, so `prisma migrate deploy` applies it in
19
+ * timestamp order with the core migrations.
20
+ * 4. `prisma generate` rebuilds `generated/prisma-<db>` from the composed
21
+ * schema, only when the schema changed or the client is missing.
22
+ *
23
+ * Removing every extension restores the base schema and regenerates. Copied
24
+ * migrations are left in place: a migration that may already be applied must
25
+ * not disappear from the history.
26
+ */
27
+
28
+ const fs = require('fs');
29
+ const path = require('path');
30
+ const { execFileSync } = require('child_process');
31
+ const {
32
+ loadExtensions,
33
+ getExtensionSchemaPaths,
34
+ } = require('./extension-loader');
35
+ const { extractModelBlocks } = require('./schema-composer');
36
+
37
+ const DB_TYPES = ['postgresql', 'mongodb'];
38
+
39
+ /**
40
+ * The Prisma databases an app definition uses. DocumentDB uses the MongoDB client.
41
+ * @param {Object} appDefinition
42
+ * @returns {Array<'postgresql'|'mongodb'>}
43
+ */
44
+ function resolvePrismaDbTypes(appDefinition) {
45
+ const db = appDefinition?.database || {};
46
+ const types = [];
47
+ if (db.postgres?.enable) types.push('postgresql');
48
+ if (db.mongoDB?.enable || db.documentDB?.enable) types.push('mongodb');
49
+ return types;
50
+ }
51
+
52
+ function blockNames(schemaContent) {
53
+ const names = [];
54
+ const re = /^\s*(model|enum|type|view)\s+(\w+)\s*\{/gm;
55
+ let match;
56
+ while ((match = re.exec(schemaContent)) !== null) names.push(match[2]);
57
+ return names;
58
+ }
59
+
60
+ /**
61
+ * Base schema + the extensions' model blocks. Throws when an extension
62
+ * declares a model, enum or type the base (or another extension) already has.
63
+ */
64
+ function buildComposedSchema(baseContent, extensionSchemaPaths) {
65
+ const seen = new Map(
66
+ blockNames(baseContent).map((name) => [name, 'the core schema'])
67
+ );
68
+ const sections = [];
69
+
70
+ for (const extPath of extensionSchemaPaths) {
71
+ if (!fs.existsSync(extPath)) {
72
+ throw new Error(`Extension schema not found: ${extPath}`);
73
+ }
74
+ const blocks = extractModelBlocks(fs.readFileSync(extPath, 'utf-8'));
75
+ if (!blocks) continue;
76
+ for (const name of blockNames(blocks)) {
77
+ if (seen.has(name)) {
78
+ throw new Error(
79
+ `Extension schema ${extPath} declares "${name}", already declared by ${seen.get(
80
+ name
81
+ )}`
82
+ );
83
+ }
84
+ seen.set(name, extPath);
85
+ }
86
+ sections.push(`// --- Extension schema: ${extPath} ---`, blocks, '');
87
+ }
88
+
89
+ if (sections.length === 0) return baseContent;
90
+
91
+ return [
92
+ baseContent.trimEnd(),
93
+ '',
94
+ '// =========================================================================',
95
+ '// Extension models (composed by @friggframework/core at build; do not edit)',
96
+ '// =========================================================================',
97
+ '',
98
+ ...sections,
99
+ ].join('\n');
100
+ }
101
+
102
+ /**
103
+ * Copies each extension's migration folders into the core migrations
104
+ * directory. A folder already there with the same migration.sql is skipped;
105
+ * a different one under the same name is an error (it would silently be a
106
+ * different migration with an applied migration's name).
107
+ * @returns {string[]} names of the folders copied
108
+ */
109
+ function copyExtensionMigrations(extensions, migrationsDir) {
110
+ const copied = [];
111
+ for (const ext of extensions) {
112
+ if (!ext.migrations) continue;
113
+ if (
114
+ !fs.existsSync(ext.migrations) ||
115
+ !fs.statSync(ext.migrations).isDirectory()
116
+ ) {
117
+ throw new Error(
118
+ `Extension "${ext.name}" migrations directory not found: ${ext.migrations}`
119
+ );
120
+ }
121
+ const folders = fs
122
+ .readdirSync(ext.migrations, { withFileTypes: true })
123
+ .filter((entry) => entry.isDirectory())
124
+ .map((entry) => entry.name)
125
+ .sort();
126
+ for (const folder of folders) {
127
+ const source = path.join(ext.migrations, folder, 'migration.sql');
128
+ if (!fs.existsSync(source)) {
129
+ throw new Error(
130
+ `Extension "${ext.name}" migration ${folder} has no migration.sql`
131
+ );
132
+ }
133
+ const sql = fs.readFileSync(source, 'utf-8');
134
+ const destDir = path.join(migrationsDir, folder);
135
+ const dest = path.join(destDir, 'migration.sql');
136
+ if (fs.existsSync(dest)) {
137
+ if (fs.readFileSync(dest, 'utf-8') !== sql) {
138
+ throw new Error(
139
+ `Migration ${folder} from extension "${ext.name}" conflicts with an existing migration of the same name`
140
+ );
141
+ }
142
+ continue;
143
+ }
144
+ fs.mkdirSync(destDir, { recursive: true });
145
+ fs.writeFileSync(dest, sql, 'utf-8');
146
+ copied.push(folder);
147
+ }
148
+ }
149
+ return copied;
150
+ }
151
+
152
+ /**
153
+ * Runs `prisma generate` with the Prisma CLI installed beside core (the app's
154
+ * own `prisma`), falling back to npx.
155
+ */
156
+ function defaultGenerate({ schemaPath, corePath }) {
157
+ let cli;
158
+ try {
159
+ cli = require.resolve('prisma/build/index.js', {
160
+ paths: [corePath, process.cwd()],
161
+ });
162
+ } catch {
163
+ cli = null;
164
+ }
165
+ const [command, args] = cli
166
+ ? [process.execPath, [cli, 'generate', `--schema=${schemaPath}`]]
167
+ : ['npx', ['prisma', 'generate', `--schema=${schemaPath}`]];
168
+ execFileSync(command, args, { cwd: corePath, stdio: 'inherit' });
169
+ }
170
+
171
+ /**
172
+ * Composes the extensions' schemas and migrations into core's Prisma schema
173
+ * and regenerates the client when it changed.
174
+ *
175
+ * @param {Object} params
176
+ * @param {Object} params.appDefinition
177
+ * @param {string} params.corePath - Directory of the installed @friggframework/core
178
+ * @param {Array<'postgresql'|'mongodb'>} [params.dbTypes] - Defaults to the app definition's databases
179
+ * @param {Function} [params.generate] - ({ schemaPath, corePath, dbType }) => void
180
+ * @param {Function} [params.log]
181
+ * @returns {{ changed: boolean, results: Array<Object> }}
182
+ */
183
+ function composeExtensionPrisma({
184
+ appDefinition,
185
+ corePath,
186
+ dbTypes,
187
+ generate = defaultGenerate,
188
+ log = (message) => console.log(message),
189
+ }) {
190
+ if (!corePath) throw new Error('corePath is required');
191
+ const extensions = loadExtensions(appDefinition);
192
+ const types = (dbTypes || resolvePrismaDbTypes(appDefinition)).filter((t) =>
193
+ DB_TYPES.includes(t)
194
+ );
195
+ const results = [];
196
+
197
+ for (const dbType of types) {
198
+ const schemaDir = path.join(corePath, `prisma-${dbType}`);
199
+ const schemaPath = path.join(schemaDir, 'schema.prisma');
200
+ const basePath = path.join(schemaDir, 'schema.base.prisma');
201
+ if (!fs.existsSync(schemaPath)) {
202
+ throw new Error(`Core Prisma schema not found: ${schemaPath}`);
203
+ }
204
+
205
+ const extensionSchemas = getExtensionSchemaPaths(extensions, dbType);
206
+ // Migrations do not depend on a schema: an extension may ship only
207
+ // SQL (a table it reads with raw queries), and it must still be applied.
208
+ const migrations =
209
+ dbType === 'postgresql'
210
+ ? copyExtensionMigrations(
211
+ extensions,
212
+ path.join(schemaDir, 'migrations')
213
+ )
214
+ : [];
215
+ if (migrations.length > 0) {
216
+ log(`[Frigg] Added extension migrations: ${migrations.join(', ')}`);
217
+ }
218
+
219
+ // No schema to compose and none composed before: the schema and the
220
+ // client stay exactly as core shipped them.
221
+ if (extensionSchemas.length === 0 && !fs.existsSync(basePath)) {
222
+ results.push({
223
+ dbType,
224
+ changed: migrations.length > 0,
225
+ migrations,
226
+ });
227
+ continue;
228
+ }
229
+
230
+ if (!fs.existsSync(basePath)) fs.copyFileSync(schemaPath, basePath);
231
+ const target = buildComposedSchema(
232
+ fs.readFileSync(basePath, 'utf-8'),
233
+ extensionSchemas
234
+ );
235
+ const current = fs.readFileSync(schemaPath, 'utf-8');
236
+ const schemaChanged = current !== target;
237
+ if (schemaChanged) fs.writeFileSync(schemaPath, target, 'utf-8');
238
+
239
+ const clientPath = path.join(
240
+ corePath,
241
+ 'generated',
242
+ `prisma-${dbType}`,
243
+ 'schema.prisma'
244
+ );
245
+ const clientStale =
246
+ !fs.existsSync(clientPath) ||
247
+ fs.readFileSync(clientPath, 'utf-8') !== target;
248
+
249
+ if (schemaChanged || clientStale) {
250
+ log(
251
+ `[Frigg] Composing ${extensionSchemas.length} extension schema(s) into the ${dbType} Prisma client`
252
+ );
253
+ generate({ schemaPath, corePath, dbType });
254
+ }
255
+ results.push({
256
+ dbType,
257
+ changed: schemaChanged || clientStale || migrations.length > 0,
258
+ migrations,
259
+ });
260
+ }
261
+
262
+ return { changed: results.some((r) => r.changed), results };
263
+ }
264
+
265
+ module.exports = {
266
+ composeExtensionPrisma,
267
+ resolvePrismaDbTypes,
268
+ buildComposedSchema,
269
+ copyExtensionMigrations,
270
+ };
@@ -0,0 +1,103 @@
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;
@@ -0,0 +1,188 @@
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
+ };