@friggframework/core 2.0.0--canary.690.08cd07e.0 → 2.0.0--canary.694.f66a64a.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 (267) 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 +2 -2
  15. package/database/encryption/encryption-schema-registry.js +12 -93
  16. package/database/prisma.js +2 -4
  17. package/errors/index.js +4 -0
  18. package/errors/mapping-already-exists-error.js +14 -0
  19. package/generated/prisma-mongodb/edge.js +38 -33
  20. package/generated/prisma-mongodb/index-browser.js +35 -30
  21. package/generated/prisma-mongodb/index.d.ts +1880 -3191
  22. package/generated/prisma-mongodb/index.js +38 -33
  23. package/generated/prisma-mongodb/package.json +1 -1
  24. package/generated/prisma-mongodb/schema.prisma +50 -86
  25. package/generated/prisma-mongodb/wasm.js +38 -33
  26. package/generated/prisma-postgresql/edge.js +38 -33
  27. package/generated/prisma-postgresql/index-browser.js +35 -30
  28. package/generated/prisma-postgresql/index.d.ts +2050 -3390
  29. package/generated/prisma-postgresql/index.js +38 -33
  30. package/generated/prisma-postgresql/package.json +1 -1
  31. package/generated/prisma-postgresql/schema.prisma +48 -81
  32. package/generated/prisma-postgresql/wasm.js +38 -33
  33. package/handlers/WEBHOOKS.md +29 -0
  34. package/handlers/app-definition-loader.js +19 -128
  35. package/handlers/app-handler-helpers.js +3 -25
  36. package/handlers/backend-utils.js +25 -31
  37. package/handlers/middleware/admin-auth.js +1 -14
  38. package/handlers/routers/auth.js +10 -46
  39. package/handlers/routers/health.js +4 -13
  40. package/handlers/routers/integration-defined-routers.js +92 -144
  41. package/handlers/routers/integration-webhook-routers.js +64 -102
  42. package/handlers/workers/integration-defined-workers.js +2 -5
  43. package/handlers/workers/integration-triggers.js +25 -0
  44. package/index.js +3 -65
  45. package/infrastructure/scheduler/index.js +6 -19
  46. package/infrastructure/scheduler/recurrence.js +204 -0
  47. package/infrastructure/scheduler/scheduler-service-factory.js +7 -55
  48. package/integrations/data-defined/README.md +185 -0
  49. package/integrations/data-defined/canonical.js +11 -0
  50. package/integrations/data-defined/capabilities/acmeerp.capabilities.json +608 -0
  51. package/integrations/data-defined/capabilities/asana.capabilities.json +265 -0
  52. package/integrations/data-defined/capabilities/calendly.capabilities.json +385 -0
  53. package/integrations/data-defined/capabilities/docusign.capabilities.json +314 -0
  54. package/integrations/data-defined/capabilities/fathom.capabilities.json +228 -0
  55. package/integrations/data-defined/capabilities/github.capabilities.json +563 -0
  56. package/integrations/data-defined/capabilities/hubspot.capabilities.json +715 -0
  57. package/integrations/data-defined/capabilities/jira.capabilities.json +376 -0
  58. package/integrations/data-defined/capabilities/klaviyo.capabilities.json +475 -0
  59. package/integrations/data-defined/capabilities/linear.capabilities.json +324 -0
  60. package/integrations/data-defined/capabilities/netsuite.capabilities.json +491 -0
  61. package/integrations/data-defined/capabilities/notion.capabilities.json +208 -0
  62. package/integrations/data-defined/capabilities/phone.capabilities.json +470 -0
  63. package/integrations/data-defined/capabilities/pipedrive.capabilities.json +388 -0
  64. package/integrations/data-defined/capabilities/quickbooks.capabilities.json +615 -0
  65. package/integrations/data-defined/capabilities/salesforce.capabilities.json +507 -0
  66. package/integrations/data-defined/capabilities/shopify.capabilities.json +1082 -0
  67. package/integrations/data-defined/capabilities/slack.capabilities.json +363 -0
  68. package/integrations/data-defined/capabilities/stripe.capabilities.json +580 -0
  69. package/integrations/data-defined/capabilities/webflow.capabilities.json +196 -0
  70. package/integrations/data-defined/capabilities/zendesk.capabilities.json +409 -0
  71. package/integrations/data-defined/compile.js +80 -0
  72. package/integrations/data-defined/config-form.js +137 -0
  73. package/integrations/data-defined/data-defined-integration.js +417 -0
  74. package/integrations/data-defined/examples/acme-erp-quickbooks.definition.json +467 -0
  75. package/integrations/data-defined/examples/asana-slack.definition.json +220 -0
  76. package/integrations/data-defined/examples/calendly-salesforce.definition.json +459 -0
  77. package/integrations/data-defined/examples/docusign-salesforce.definition.json +305 -0
  78. package/integrations/data-defined/examples/fathom-hubspot-notion.definition.json +575 -0
  79. package/integrations/data-defined/examples/github-linear.definition.json +316 -0
  80. package/integrations/data-defined/examples/hubspot-slack.definition.json +409 -0
  81. package/integrations/data-defined/examples/klaviyo-hubspot.definition.json +339 -0
  82. package/integrations/data-defined/examples/phone-hubspot.definition.json +637 -0
  83. package/integrations/data-defined/examples/pipedrive-hubspot.definition.json +136 -0
  84. package/integrations/data-defined/examples/pipedrive-phone.definition.json +340 -0
  85. package/integrations/data-defined/examples/records/phone-hubspot.definition-version.json +652 -0
  86. package/integrations/data-defined/examples/records/phone-hubspot.integration.json +86 -0
  87. package/integrations/data-defined/examples/records/phone-hubspot.mappings.json +39 -0
  88. package/integrations/data-defined/examples/records/phone-hubspot.workflow-run.json +62 -0
  89. package/integrations/data-defined/examples/shopify-klaviyo.definition.json +488 -0
  90. package/integrations/data-defined/examples/shopify-netsuite.definition.json +622 -0
  91. package/integrations/data-defined/examples/stripe-quickbooks.definition.json +476 -0
  92. package/integrations/data-defined/examples/webflow-hubspot-slack.definition.json +262 -0
  93. package/integrations/data-defined/examples/zendesk-jira.definition.json +604 -0
  94. package/integrations/data-defined/expressions.js +225 -0
  95. package/integrations/data-defined/index.js +39 -0
  96. package/integrations/data-defined/interpreter.js +89 -0
  97. package/integrations/data-defined/manifests.js +125 -0
  98. package/integrations/data-defined/repositories/definition-version-repository.js +67 -0
  99. package/integrations/data-defined/repositories/workflow-run-repository.js +59 -0
  100. package/integrations/data-defined/router.js +97 -0
  101. package/integrations/data-defined/runtime.js +208 -0
  102. package/integrations/data-defined/schema/capability-manifest.v0.1.schema.json +377 -0
  103. package/integrations/data-defined/schema/installation.v0.1.schema.json +130 -0
  104. package/integrations/data-defined/schema/integration-definition.v0.1.schema.json +902 -0
  105. package/integrations/data-defined/schema/records.md +98 -0
  106. package/integrations/data-defined/schema-check.js +58 -0
  107. package/integrations/data-defined/scripts/validate.js +66 -0
  108. package/integrations/data-defined/steps.js +89 -0
  109. package/integrations/data-defined/transforms.js +91 -0
  110. package/integrations/data-defined/use-cases/definition-use-cases.js +187 -0
  111. package/integrations/data-defined/validate.js +384 -0
  112. package/integrations/data-defined/versioning.js +176 -0
  113. package/integrations/data-defined/webhooks.js +119 -0
  114. package/integrations/index.js +0 -1
  115. package/integrations/integration-base.js +117 -0
  116. package/integrations/integration-router.js +101 -131
  117. package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
  118. package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
  119. package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
  120. package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
  121. package/integrations/repositories/integration-mapping-repository.js +29 -0
  122. package/integrations/repositories/integration-repository-documentdb.js +9 -37
  123. package/integrations/repositories/integration-repository-interface.js +4 -17
  124. package/integrations/repositories/integration-repository-mongo.js +96 -64
  125. package/integrations/repositories/integration-repository-postgres.js +81 -63
  126. package/integrations/repositories/process-repository-mongo.js +1 -1
  127. package/integrations/tests/doubles/test-integration-repository.js +1 -12
  128. package/integrations/triggers.js +244 -0
  129. package/integrations/use-cases/create-integration.js +20 -55
  130. package/integrations/use-cases/get-integrations-for-user.js +40 -80
  131. package/integrations/use-cases/index.js +1 -7
  132. package/integrations/use-cases/run-trigger-tick.js +132 -0
  133. package/integrations/use-cases/run-trigger.js +77 -0
  134. package/integrations/utils/map-integration-dto.js +14 -43
  135. package/modules/index.js +0 -14
  136. package/modules/module-factory.js +0 -12
  137. package/modules/module.js +2 -53
  138. package/modules/repositories/module-repository-documentdb.js +6 -51
  139. package/modules/repositories/module-repository-interface.js +2 -19
  140. package/modules/repositories/module-repository-mongo.js +74 -67
  141. package/modules/repositories/module-repository-postgres.js +74 -66
  142. package/modules/repositories/module-repository.js +1 -2
  143. package/modules/requester/requester.js +5 -35
  144. package/modules/use-cases/get-entities-for-user.js +13 -26
  145. package/modules/use-cases/get-entity-options-by-id.js +4 -10
  146. package/modules/use-cases/get-entity-options-by-type.js +1 -1
  147. package/modules/use-cases/get-module-instance-from-type.js +1 -1
  148. package/modules/use-cases/get-module.js +4 -10
  149. package/modules/use-cases/process-authorization-callback.js +19 -53
  150. package/modules/use-cases/refresh-entity-options.js +4 -10
  151. package/modules/use-cases/test-module-auth.js +4 -10
  152. package/package.json +6 -6
  153. package/prisma-mongodb/schema.prisma +50 -86
  154. package/prisma-postgresql/migrations/20261018000000_add_data_defined_integrations/migration.sql +66 -0
  155. package/prisma-postgresql/schema.prisma +48 -81
  156. package/queues/index.js +0 -25
  157. package/queues/queuer-util.js +9 -2
  158. package/types/index.d.ts +0 -2
  159. package/user/repositories/user-repository-documentdb.js +2 -27
  160. package/user/repositories/user-repository-interface.js +0 -18
  161. package/user/repositories/user-repository-mongo.js +0 -24
  162. package/user/repositories/user-repository-postgres.js +0 -18
  163. package/user/use-cases/authenticate-user.js +1 -7
  164. package/user/use-cases/get-user-from-adopter-jwt.js +124 -95
  165. package/user/use-cases/get-user-from-x-frigg-headers.js +80 -83
  166. package/user/user.js +1 -64
  167. package/credential/use-cases/credential-operations-for-user.js +0 -202
  168. package/credential/use-cases/reauthorize-credential-for-user.js +0 -73
  169. package/database/organization-where.js +0 -18
  170. package/database/unique-violation.js +0 -25
  171. package/extensions/bootstrap-runner.js +0 -43
  172. package/extensions/extension-loader.js +0 -187
  173. package/extensions/index.js +0 -41
  174. package/extensions/initialize-app.js +0 -123
  175. package/extensions/route-mounter.js +0 -103
  176. package/extensions/schema-composer.js +0 -188
  177. package/infrastructure/scheduler/netlify-scheduler-adapter.js +0 -216
  178. package/infrastructure/scheduler/scheduled-job-repository.js +0 -118
  179. package/integrations/repositories/integration-not-found.js +0 -14
  180. package/integrations/schedule-config.js +0 -80
  181. package/integrations/use-cases/dispatch-ongoing-syncs.js +0 -100
  182. package/integrations/use-cases/integration-operations-for-user.js +0 -256
  183. package/integrations/use-cases/resolve-integration-ownership.js +0 -177
  184. package/management-api/create-management-api-router.js +0 -49
  185. package/management-api/error-response.js +0 -116
  186. package/management-api/management-api-config.js +0 -151
  187. package/management-api/meta-router.js +0 -76
  188. package/management-api/openapi/build-openapi.js +0 -144
  189. package/management-api/openapi/components.js +0 -415
  190. package/management-api/openapi/v1-operations.js +0 -83
  191. package/management-api/openapi/v2-operations.js +0 -264
  192. package/management-api/route-registry.js +0 -411
  193. package/management-api/test-support/http-client.js +0 -39
  194. package/management-api/use-cases/get-management-api-meta.js +0 -57
  195. package/management-api/v1-deprecation.js +0 -120
  196. package/management-api/v2/create-v2-router.js +0 -85
  197. package/management-api/v2/dependencies.js +0 -281
  198. package/management-api/v2/dto.js +0 -143
  199. package/management-api/v2/handlers/authorization.js +0 -94
  200. package/management-api/v2/handlers/credentials.js +0 -33
  201. package/management-api/v2/handlers/entities.js +0 -77
  202. package/management-api/v2/handlers/integrations.js +0 -128
  203. package/management-api/v2/handlers/proxy.js +0 -34
  204. package/management-api/v2/request.js +0 -85
  205. package/management-api/v2/test-support/fake-dependencies.js +0 -103
  206. package/modules/domain/authorization-session.js +0 -144
  207. package/modules/entity-scope.js +0 -15
  208. package/modules/entity-type-registry.js +0 -311
  209. package/modules/proxy/proxy-bases.js +0 -169
  210. package/modules/proxy/proxy-errors.js +0 -31
  211. package/modules/proxy/proxy-path.js +0 -183
  212. package/modules/proxy/proxy-policy.js +0 -277
  213. package/modules/repositories/authorization-session-repository-documentdb.js +0 -112
  214. package/modules/repositories/authorization-session-repository-factory.js +0 -31
  215. package/modules/repositories/authorization-session-repository-interface.js +0 -47
  216. package/modules/repositories/authorization-session-repository-prisma.js +0 -87
  217. package/modules/repositories/entity-not-found.js +0 -18
  218. package/modules/requester/proxy-request.js +0 -245
  219. package/modules/scope-config.js +0 -192
  220. package/modules/scope-policy.js +0 -112
  221. package/modules/scope-resolution.js +0 -288
  222. package/modules/scope-visibility.js +0 -247
  223. package/modules/tests/doubles/in-memory-authorization-session-repository.js +0 -45
  224. package/modules/tests/doubles/ownership-matching.js +0 -18
  225. package/modules/use-cases/authorize-entity-for-user.js +0 -61
  226. package/modules/use-cases/create-entity-from-credential.js +0 -113
  227. package/modules/use-cases/entity-operations-for-user.js +0 -162
  228. package/modules/use-cases/entity-types.js +0 -139
  229. package/modules/use-cases/execute-entity-proxy-request.js +0 -331
  230. package/modules/use-cases/get-authorization-requirements.js +0 -100
  231. package/modules/use-cases/get-entity-module-for-user.js +0 -113
  232. package/modules/use-cases/manage-access.js +0 -21
  233. package/modules/use-cases/multi-step-authorization.js +0 -329
  234. package/prisma-postgresql/migrations/20261003000000_add_authorization_session/migration.sql +0 -28
  235. package/prisma-postgresql/migrations/20261015000000_add_organization_membership/migration.sql +0 -26
  236. package/prisma-postgresql/migrations/20261016000000_add_entity_integration_organization/migration.sql +0 -25
  237. package/prisma-postgresql/migrations/20261017000000_add_scheduled_job/migration.sql +0 -28
  238. package/providers/index.js +0 -23
  239. package/providers/resolve-provider.js +0 -93
  240. package/providers/runtime-detection.js +0 -124
  241. package/queues/providers/index.js +0 -11
  242. package/queues/providers/netlify-background-provider.js +0 -150
  243. package/queues/providers/qstash-queue-provider.js +0 -219
  244. package/queues/providers/sqs-queue-provider.js +0 -70
  245. package/queues/queue-client-interface.js +0 -55
  246. package/queues/queue-message-auth.js +0 -193
  247. package/queues/queue-provider-factory.js +0 -101
  248. package/queues/queue-provider.js +0 -65
  249. package/queues/sqs-queue-client.js +0 -81
  250. package/types/modules/index.d.ts +0 -214
  251. package/types/user/index.d.ts +0 -134
  252. package/user/adopter-jwt-config.js +0 -177
  253. package/user/adopter-jwt-errors.js +0 -59
  254. package/user/adopter-token-verifier.js +0 -122
  255. package/user/app-user-helpers.js +0 -97
  256. package/user/create-user-authentication.js +0 -64
  257. package/user/membership.js +0 -51
  258. package/user/repositories/organization-membership-record.js +0 -19
  259. package/user/repositories/organization-membership-repository-documentdb.js +0 -106
  260. package/user/repositories/organization-membership-repository-factory.js +0 -42
  261. package/user/repositories/organization-membership-repository-interface.js +0 -57
  262. package/user/repositories/organization-membership-repository-mongo.js +0 -13
  263. package/user/repositories/organization-membership-repository-postgres.js +0 -29
  264. package/user/repositories/organization-membership-repository-prisma.js +0 -81
  265. package/user/tests/doubles/adopter-jwt-fixtures.js +0 -220
  266. package/user/use-cases/ensure-organization-membership.js +0 -92
  267. package/user/use-cases/find-individual-users-by-organization.js +0 -54
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Recurrence: how often something repeats, in a form no host owns.
3
+ *
4
+ * { every: '15m' } every 15 minutes ('30s' is refused: ticks are whole minutes)
5
+ * { cron: '0 9 * * 1-5', timezone: 'America/New_York' } standard five-field cron (minute hour dom month dow)
6
+ *
7
+ * Recurring triggers (ADR-055, integrations/triggers.js) use it for the timing an installation may choose and for
8
+ * the floor a developer sets on that choice. Nothing here creates a host schedule: the tick asks `lastFiringIn`
9
+ * whether a cron fired since the previous tick, so a per-installation calendar needs no schedule of its own.
10
+ *
11
+ * Pure; no I/O.
12
+ */
13
+
14
+ const EVERY = /^(\d+)\s*(m|h|d)$/;
15
+ const UNIT_MINUTES = { m: 1, h: 60, d: 1440 };
16
+
17
+ /** '15m' -> 15, '2h' -> 120, '1d' -> 1440. Anything else -> null. */
18
+ function parseEvery(every) {
19
+ const m = EVERY.exec(String(every ?? '').trim());
20
+ if (!m) return null;
21
+ const n = Number(m[1]) * UNIT_MINUTES[m[2]];
22
+ return n > 0 ? n : null;
23
+ }
24
+
25
+ const MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
26
+ const DAYS = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
27
+ const FIELDS = [
28
+ { name: 'minute', min: 0, max: 59 },
29
+ { name: 'hour', min: 0, max: 23 },
30
+ { name: 'day of month', min: 1, max: 31 },
31
+ { name: 'month', min: 1, max: 12, names: MONTHS, base: 1 },
32
+ { name: 'day of week', min: 0, max: 7, names: DAYS, base: 0 }, // 0 and 7 are both Sunday
33
+ ];
34
+
35
+ function atom(token, field) {
36
+ const t = token.toUpperCase();
37
+ if (field.names) {
38
+ const i = field.names.indexOf(t);
39
+ if (i >= 0) return i + field.base;
40
+ }
41
+ if (!/^\d+$/.test(t)) return null;
42
+ const n = Number(t);
43
+ return n >= field.min && n <= field.max ? n : null;
44
+ }
45
+
46
+ /** One cron field -> the sorted set of values it matches, or an error string. */
47
+ function parseField(text, field) {
48
+ const out = new Set();
49
+ for (const part of text.split(',')) {
50
+ const [range, stepText] = part.split('/');
51
+ if (part.split('/').length > 2) return `${field.name}: "${part}" has more than one step`;
52
+ const step = stepText === undefined ? 1 : Number(stepText);
53
+ if (!Number.isInteger(step) || step < 1) return `${field.name}: step "${stepText}" is not a positive whole number`;
54
+ let lo, hi;
55
+ if (range === '*') { lo = field.min; hi = field.name === 'day of week' ? 6 : field.max; }
56
+ else if (range.includes('-')) {
57
+ const [a, b] = range.split('-');
58
+ lo = atom(a, field); hi = atom(b, field);
59
+ if (lo === null || hi === null) return `${field.name}: "${range}" is out of range`;
60
+ if (lo > hi) return `${field.name}: "${range}" runs backwards`;
61
+ } else {
62
+ lo = atom(range, field);
63
+ if (lo === null) return `${field.name}: "${range}" is out of range`;
64
+ hi = stepText === undefined ? lo : (field.name === 'day of week' ? 6 : field.max);
65
+ }
66
+ for (let v = lo; v <= hi; v += step) out.add(field.name === 'day of week' && v === 7 ? 0 : v);
67
+ }
68
+ return [...out].sort((a, b) => a - b);
69
+ }
70
+
71
+ /**
72
+ * Parse a five-field cron. Returns { fields: [Set x5], restricted: { dom, dow } } or { error }.
73
+ * `restricted` records whether day-of-month / day-of-week were given (not `*`), which decides how they combine.
74
+ */
75
+ function parseCron(cron) {
76
+ const parts = String(cron ?? '').trim().split(/\s+/);
77
+ if (parts.length !== 5 || parts[0] === '') return { error: 'A cron expression has five fields: minute hour day-of-month month day-of-week' };
78
+ const fields = [];
79
+ for (let i = 0; i < 5; i += 1) {
80
+ const v = parseField(parts[i], FIELDS[i]);
81
+ if (typeof v === 'string') return { error: v };
82
+ fields.push(new Set(v));
83
+ }
84
+ return { fields, parts, restricted: { dom: parts[2] !== '*', dow: parts[4] !== '*' } };
85
+ }
86
+
87
+ /** Does a parsed cron fire at this (UTC-free, wall-clock) minute? Standard cron: dom and dow OR when both are set. */
88
+ function matches(parsed, d) {
89
+ const [mi, h, dom, mon, dow] = parsed.fields;
90
+ if (!mi.has(d.getUTCMinutes()) || !h.has(d.getUTCHours()) || !mon.has(d.getUTCMonth() + 1)) return false;
91
+ const domHit = dom.has(d.getUTCDate()), dowHit = dow.has(d.getUTCDay());
92
+ if (parsed.restricted.dom && parsed.restricted.dow) return domHit || dowHit;
93
+ return domHit && dowHit;
94
+ }
95
+
96
+ /**
97
+ * The shortest gap, in minutes, between two firings. For `every` it is the interval; for cron it is measured over
98
+ * fifteen months of wall-clock minutes (long enough to see every month and weekday combination), so a floor such as
99
+ * "no more often than every 15 minutes" is checked against what the expression really does, not its spelling.
100
+ * Returns Infinity for an expression that fires at most once in that window, null when invalid.
101
+ */
102
+ function minGapMinutes(recurrence) {
103
+ if (recurrence?.every !== undefined) return parseEvery(recurrence.every);
104
+ const parsed = parseCron(recurrence?.cron);
105
+ return parsed.error ? null : scan(parsed).best;
106
+ }
107
+
108
+ /** Walk fifteen months of firings: how many there are and the shortest gap between two. */
109
+ function scan(parsed) {
110
+ const [mi, h] = parsed.fields;
111
+ const minutes = [...mi], hours = [...h];
112
+ let prev = null, best = Infinity, count = 0;
113
+ const start = Date.UTC(2027, 0, 1);
114
+ for (let day = 0; day < 457 && best > 1; day += 1) { // fifteen months: every month and weekday pairing
115
+ const midnight = start + day * 86400000;
116
+ if (!matches(parsed, new Date(midnight + hours[0] * 3600000 + minutes[0] * 60000))) continue;
117
+ for (const hr of hours) {
118
+ for (const mn of minutes) {
119
+ const t = day * 1440 + hr * 60 + mn;
120
+ if (prev !== null && t - prev < best) best = t - prev;
121
+ prev = t;
122
+ count += 1;
123
+ }
124
+ }
125
+ }
126
+ return { best, count };
127
+ }
128
+
129
+ /** Is `tz` an IANA time zone this runtime knows? */
130
+ function isTimeZone(tz) {
131
+ try { new Intl.DateTimeFormat('en-US', { timeZone: tz }); return true; } catch { return false; }
132
+ }
133
+
134
+ /**
135
+ * Validate a recurrence. `min` is an optional floor ('15m'): the expression must never fire more often.
136
+ * @returns {string[]} problems, empty when valid
137
+ */
138
+ function validateRecurrence(recurrence, { min } = {}) {
139
+ const problems = [];
140
+ if (!recurrence || typeof recurrence !== 'object') return ['Give a schedule as { every } or { cron, timezone? }'];
141
+ const hasEvery = recurrence.every !== undefined, hasCron = recurrence.cron !== undefined;
142
+ if (hasEvery === hasCron) return ['Give exactly one of every or cron'];
143
+ if (hasEvery && parseEvery(recurrence.every) === null) problems.push(`every "${recurrence.every}" is not a whole number of minutes, hours or days (15m, 2h, 1d)`);
144
+ if (hasCron) {
145
+ const parsed = parseCron(recurrence.cron);
146
+ if (parsed.error) problems.push(parsed.error);
147
+ // EventBridge (and Quartz) cannot express "this day of month OR this weekday"; refuse it everywhere, so a
148
+ // schedule that validates here runs on every host.
149
+ else if (parsed.restricted.dom && parsed.restricted.dow) problems.push('Restrict day of month or day of week, not both');
150
+ else if (scan(parsed).count === 0) problems.push(`"${recurrence.cron}" never fires`);
151
+ }
152
+ if (recurrence.timezone !== undefined && (hasEvery || !isTimeZone(recurrence.timezone))) {
153
+ problems.push(hasEvery ? 'timezone applies to cron schedules only' : `Unknown time zone "${recurrence.timezone}"`);
154
+ }
155
+ if (!problems.length && min !== undefined) {
156
+ const floor = parseEvery(min);
157
+ const gap = minGapMinutes(recurrence);
158
+ if (floor === null) problems.push(`minimum interval "${min}" is not a duration (15m, 2h, 1d)`);
159
+ else if (gap !== null && gap < floor) problems.push(`Runs every ${gap} minute${gap === 1 ? '' : 's'} at its most frequent; the minimum is ${min}`);
160
+ }
161
+ return problems;
162
+ }
163
+
164
+ /** The comparable identity of a recurrence (what decides whether a stored schedule must be updated). */
165
+ function recurrenceKey(r) {
166
+ if (!r) return '';
167
+ return r.every !== undefined ? `every:${parseEvery(r.every)}` : `cron:${String(r.cron).trim().split(/\s+/).join(' ')}@${r.timezone || 'UTC'}`;
168
+ }
169
+
170
+ const wallClockFormats = new Map();
171
+ /**
172
+ * The wall-clock time of an instant in a time zone, as a Date whose UTC fields hold that wall clock (what `matches`
173
+ * reads). Seconds are dropped.
174
+ */
175
+ function wallClock(ms, timezone = 'UTC') {
176
+ if (timezone === 'UTC') return new Date(Math.floor(ms / 60000) * 60000);
177
+ let format = wallClockFormats.get(timezone);
178
+ if (!format) {
179
+ format = new Intl.DateTimeFormat('en-US', { timeZone: timezone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' });
180
+ wallClockFormats.set(timezone, format);
181
+ }
182
+ const p = Object.fromEntries(format.formatToParts(new Date(ms)).map((x) => [x.type, x.value]));
183
+ return new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day), Number(p.hour) % 24, Number(p.minute)));
184
+ }
185
+
186
+ /**
187
+ * The latest whole minute in (fromMs, toMs] at which a cron recurrence fires in its time zone, as epoch ms, or null.
188
+ *
189
+ * This is how one shared tick serves a calendar each installation chose: the tick asks whether the cron fired since
190
+ * the previous tick. It is stateless, so a tick that runs twice for the same slot gives the same answer (and the same
191
+ * `scheduledFor`, which is what a run dedupes on). Real instants are walked, so a wall-clock time a DST change skips
192
+ * does not fire that day, and one it repeats fires twice.
193
+ */
194
+ function lastFiringIn(recurrence, fromMs, toMs) {
195
+ const parsed = parseCron(recurrence?.cron);
196
+ if (parsed.error) return null;
197
+ const tz = recurrence.timezone || 'UTC';
198
+ for (let t = Math.floor(toMs / 60000) * 60000; t > fromMs; t -= 60000) {
199
+ if (matches(parsed, wallClock(t, tz))) return t;
200
+ }
201
+ return null;
202
+ }
203
+
204
+ module.exports = { parseEvery, parseCron, minGapMinutes, validateRecurrence, recurrenceKey, isTimeZone, matches, wallClock, lastFiringIn };
@@ -7,22 +7,16 @@
7
7
  * Environment Detection:
8
8
  * - SCHEDULER_PROVIDER=eventbridge -> Use AWS EventBridge Scheduler
9
9
  * - SCHEDULER_PROVIDER=mock -> Use in-memory mock scheduler
10
- * - SCHEDULER_PROVIDER=netlify -> Netlify poll-and-dispatch scheduler
11
- * (friggframework/frigg#545; needs `repository`, usually `queueProvider`)
12
- * - Default on Netlify (NETLIFY=true, set by the Netlify runtime and build;
13
- * provider-netlify's generated functions also set SCHEDULER_PROVIDER) -> Netlify
14
10
  * - Default in dev/test/local stages -> Mock scheduler
15
11
  * - Default in other stages -> EventBridge scheduler
16
- * - Any other name -> require('@friggframework/provider-<name>').SchedulerAdapter
17
- *
18
- * Adapters are required inside their branch so building one never loads
19
- * another's SDK (@aws-sdk/client-scheduler is not a core dependency).
20
12
  */
21
13
 
14
+ const { EventBridgeSchedulerAdapter } = require('./eventbridge-scheduler-adapter');
15
+ const { MockSchedulerAdapter } = require('./mock-scheduler-adapter');
16
+
22
17
  const SCHEDULER_PROVIDERS = {
23
18
  EVENTBRIDGE: 'eventbridge',
24
19
  MOCK: 'mock',
25
- NETLIFY: 'netlify',
26
20
  };
27
21
 
28
22
  const LOCAL_STAGES = ['dev', 'test', 'local'];
@@ -38,12 +32,6 @@ function determineProvider() {
38
32
  return explicitProvider;
39
33
  }
40
34
 
41
- // Checked before the stage: a Netlify site with no STAGE (or STAGE=dev)
42
- // must still persist schedules where scheduled-sync reads them.
43
- if (process.env.NETLIFY === 'true') {
44
- return SCHEDULER_PROVIDERS.NETLIFY;
45
- }
46
-
47
35
  const stage = process.env.STAGE || 'dev';
48
36
  if (LOCAL_STAGES.includes(stage)) {
49
37
  return SCHEDULER_PROVIDERS.MOCK;
@@ -52,13 +40,6 @@ function determineProvider() {
52
40
  return SCHEDULER_PROVIDERS.EVENTBRIDGE;
53
41
  }
54
42
 
55
- function createDefaultScheduledJobRepository() {
56
- const { ScheduledJobRepository } = require('./scheduled-job-repository');
57
- // The prisma export is a lazy proxy: nothing connects until a query runs.
58
- const { prisma } = require('../../database/prisma');
59
- return new ScheduledJobRepository({ prismaClient: prisma });
60
- }
61
-
62
43
  /**
63
44
  * Create a scheduler service instance
64
45
  *
@@ -66,51 +47,22 @@ function createDefaultScheduledJobRepository() {
66
47
  * @param {string} options.provider - Scheduler provider ('eventbridge' or 'mock')
67
48
  * @param {string} options.region - AWS region (for EventBridge)
68
49
  * @param {boolean} options.verbose - Verbose logging (for Mock)
69
- * @param {Object} [options.repository] - Schedule repository (for Netlify: persists schedules)
70
- * @param {Object} [options.queueProvider] - Queue provider (for Netlify: dispatches due jobs)
71
50
  * @returns {SchedulerServiceInterface} Implementation of scheduler interface
72
51
  */
73
52
  function createSchedulerService(options = {}) {
74
53
  const provider = options.provider || determineProvider();
75
54
 
76
55
  switch (provider) {
77
- case SCHEDULER_PROVIDERS.EVENTBRIDGE: {
78
- const { EventBridgeSchedulerAdapter } = require('./eventbridge-scheduler-adapter');
56
+ case SCHEDULER_PROVIDERS.EVENTBRIDGE:
79
57
  return new EventBridgeSchedulerAdapter({
80
58
  region: options.region,
81
59
  });
82
- }
83
- case SCHEDULER_PROVIDERS.MOCK: {
84
- const { MockSchedulerAdapter } = require('./mock-scheduler-adapter');
60
+ case SCHEDULER_PROVIDERS.MOCK:
85
61
  return new MockSchedulerAdapter({
86
62
  verbose: options.verbose,
87
63
  });
88
- }
89
- case SCHEDULER_PROVIDERS.NETLIFY: {
90
- const { NetlifySchedulerAdapter } = require('./netlify-scheduler-adapter');
91
- return new NetlifySchedulerAdapter({
92
- // Default: the Prisma ScheduledJob rows that the Netlify
93
- // scheduled-sync function polls. Without it the adapter
94
- // falls back to memory, and a schedule made in one function
95
- // is never seen by the cron.
96
- repository: options.repository || createDefaultScheduledJobRepository(),
97
- queueProvider: options.queueProvider,
98
- });
99
- }
100
- default: {
101
- let plugin;
102
- try {
103
- plugin = require('../../providers/resolve-provider').resolveProvider(null, {
104
- provider,
105
- });
106
- } catch (error) {
107
- throw new Error(`Unknown scheduler provider: ${provider} (${error.message})`);
108
- }
109
- if (!plugin.SchedulerAdapter) {
110
- throw new Error(`Unknown scheduler provider: ${provider}`);
111
- }
112
- return new plugin.SchedulerAdapter(options);
113
- }
64
+ default:
65
+ throw new Error(`Unknown scheduler provider: ${provider}`);
114
66
  }
115
67
  }
116
68
 
@@ -0,0 +1,185 @@
1
+ # Data-defined integrations (v0.1)
2
+
3
+ ADR-063, implemented to the point where a definition can be validated, compiled into Frigg events, executed, rendered
4
+ and versioned. An integration becomes a **document** (what it connects, what it syncs, which workflows and UI it has)
5
+ run by **one** runtime class, instead of a hand-written class per integration.
6
+
7
+ ```
8
+ definition (JSON, immutable per version) ─┐
9
+ capability manifests (one per API module) ─┼─ validate ─ compile ─▶ this.events (same shape as hand-written)
10
+ installation (Integration.config) ─┘ │
11
+ event arrives ─▶ runWorkflow ─▶ steps ─▶ Api methods
12
+ ```
13
+
14
+ ## Layout
15
+
16
+ | Path | What |
17
+ |---|---|
18
+ | `schema/integration-definition.v0.1.schema.json` | The definition format (JSON Schema 2020-12) |
19
+ | `schema/capability-manifest.v0.1.schema.json` | What an API module declares it can do |
20
+ | `schema/installation.v0.1.schema.json` | `Integration.config` for a data-defined installation |
21
+ | `schema/records.md` | Database records: definition versions, installation, mappings, workflow runs |
22
+ | `capabilities/*.capabilities.json` | Mock manifests (HubSpot, Phone, and the apps the examples use) |
23
+ | `examples/*.definition.json` | Example definitions; `examples/records/` has Phone ↔ HubSpot database records |
24
+ | `expressions.js` | `$.ref`, `{{template \| filter}}` and conditions. No eval. |
25
+ | `steps.js`, `interpreter.js`, `transforms.js` | The step catalogue and the interpreter |
26
+ | `validate.js` | Structure + cross-references against the manifests (steps, templates, views, settings, `$.install`) |
27
+ | `manifests.js` | `validateManifest`: the manifests themselves (kinds, option lists, account fields) |
28
+ | `compile.js` | Definition + installation → events, webhook routes, recurring triggers, user actions |
29
+ | `runtime.js` | Ports (Api calls, link store), `runWorkflow`, `runQuery`, `renderSurface`, `runLifecycle`, `resolveOptions`, `installContext` |
30
+ | `versioning.js` | `diff`, `checkBump`, `planUpgrade` |
31
+ | `data-defined-integration.js` | `defineIntegrationClass`: the IntegrationBase subclass that runs it all |
32
+ | `use-cases/definition-use-cases.js` | Publish, deprecate, catalogue, history, upgrade plan; `createDefinitionCatalog()` (the store the runtime reads) |
33
+ | `repositories/` | `IntegrationDefinitionVersion` and `WorkflowRun` rows (MongoDB, PostgreSQL, DocumentDB) |
34
+ | `router.js` | The publish, catalogue, upgrade and run-history routes |
35
+
36
+ ## The pieces of a definition
37
+
38
+ - **modules** — module keys used everywhere else (`phone`, `hubspot`), each naming a capability manifest.
39
+ - **settings** — integration-level choices (`fromNumber`); workflows can declare their own. An option setting draws
40
+ its choices from a module's option list, and may pass it inputs read from earlier choices
41
+ (`{ "source": "asana.project", "with": { "workspaceGid": "$.settings.workspace" } }`); `resolveOptions` fills the
42
+ dropdown and returns nothing until those inputs are chosen.
43
+ - **syncs** — records kept as copies on both sides: identity keys, field mapping (with transforms and master rules),
44
+ backfill and ongoing mode. A sync maintains the link + identity index every workflow uses (`links.find`).
45
+ A definition can have no workflows at all (`pipedrive-hubspot` is sync only).
46
+ - **links** — link sets: records on two modules known to be the same thing, with no sync behind them (a Calendly
47
+ invitee and the Salesforce Lead it booked as). Same storage and identity index as a sync, addressed as
48
+ `links.find { link: "people", ... }`.
49
+ - **workflows** — trigger (`webhook`, `schedule`, `userAction`, `syncRecord`) + steps. Default on or off.
50
+ - **queries** — read-only steps that return data, used by UI surfaces.
51
+ - **ui** — a surface in a host app (`hubspot` `crm.record.sidebar`): a query for data and a view tree from a fixed
52
+ component set. A generic renderer deployed once per host draws it; changing the card is a publish, not a deploy.
53
+ - **templates** — message bodies. **lifecycle** — steps run on install / uninstall (webhook subscriptions). Each
54
+ `onInstall` step with an `id` keeps its result as `$.install.runtime.installed.<id>`, which is how `onUninstall`
55
+ deletes exactly what install created.
56
+
57
+ ## How it plugs into Frigg
58
+
59
+ - **Hydration**: Frigg's use cases call `initialize()` on every hydrated integration; the class loads its pinned
60
+ definition there.
61
+ - **Webhooks**: install steps register `$.install.webhookUrls.<key>` (the URL names the module). The manifest's
62
+ `webhook` block (`webhooks.js`) splits batches and reads each event's topic, id and account; `verify` must return
63
+ true; handshakes are answered at receipt. App-level webhooks (`webhook.scope: "app"`, one URL per provider app)
64
+ are fanned out to the installations connected to each account.
65
+ - **Routes**: Frigg's existing authenticated ones. `GET/POST /api/integrations/:id/config/options[/refresh]` is the
66
+ generated configure form (dependent dropdowns on refresh); `POST /api/integrations/:id/actions/:event` runs a
67
+ button workflow (`WF_*`), a backfill, or renders a UI surface (`UI_*`, body `{ record }`).
68
+
69
+ `$.install` is the same everywhere a definition runs: integration settings, `webhookUrl`, `integrationId`,
70
+ `runtime.installed`, and `accounts.<module key>.<field>` — values about the connected account that the module's
71
+ manifest declares under `account` (`$.install.accounts.quickbooks.realmId`). Nothing undeclared is exposed.
72
+
73
+ ## Publishing, installing, upgrading
74
+
75
+ Definitions live in the `IntegrationDefinitionVersion` table (Prisma models in both schemas, PostgreSQL migration
76
+ `20261018000000_add_data_defined_integrations`), and runs in `WorkflowRun`. Point the class at the store:
77
+
78
+ ```js
79
+ const { defineSharedIntegrationClass, createDefinitionCatalog } = require('@friggframework/core/integrations/data-defined');
80
+ // A database store is read asynchronously, so it goes with the shared class (one class, every definition).
81
+ const DataDefined = defineSharedIntegrationClass({ definitions: createDefinitionCatalog(), manifests, modules });
82
+ ```
83
+
84
+ | Route | Auth | |
85
+ |---|---|---|
86
+ | `POST /admin/integrations/definitions` `{ document, notes?, publish?, strict? }` | admin key | Validate (both layers) and publish, or save a draft with `publish: false` |
87
+ | `GET /admin/integrations/definitions/:id` | admin key | Version history |
88
+ | `POST /admin/integrations/definitions/:id/versions/:v/deprecate` | admin key | Stop new installs of a version |
89
+ | `GET /api/data-defined/definitions` | user | What can be installed |
90
+ | `POST /api/integrations` with `config: { type, definition: { id } }` | user | Install; pins the latest published version and its checksum |
91
+ | `GET` / `POST /api/integrations/:id/upgrade` `{ to? }` | user | Plan / apply an upgrade (409 with the plan while something is needed) |
92
+ | `GET /api/integrations/:id/runs` | user | Run history, newest first |
93
+
94
+ Published versions cannot change. Publishing a document that is identical to a published one returns that row. A
95
+ different document at the same version is refused. So is a version that is not newer than the latest, and so is a
96
+ semver bump smaller than the changes. Publishing goes through a conditional write, so two concurrent publishes of one
97
+ version cannot both win. With `memoryDefinitions()` (definitions bundled in the app) the admin routes answer 501.
98
+
99
+ ## Schedules
100
+
101
+ A schedule-triggered workflow or a polling sync is a recurring trigger (ADR-055), the same mechanism hand-written
102
+ integrations declare as `Definition.triggers` (ADR-063 §15a). Nothing is scheduled per installation: the class
103
+ declares `instanceTriggers: { tick: '5m' }`, so devtools provisions one tick function for it, and each tick compiles
104
+ every ENABLED installation's pinned definition with its config and queues the runs that are due. Mark one
105
+ `configurable` to let installations pick their own timing, optionally with a floor:
106
+
107
+ ```json
108
+ "trigger": { "type": "schedule", "cron": "0 16 * * 1-5", "timezone": "America/New_York", "configurable": { "min": "1h" } }
109
+ "ongoing": { "mode": "poll", "every": "15m", "configurable": true }
110
+ ```
111
+
112
+ The choice goes in `workflows.<id>.schedule` / `syncs.<id>.schedule` (the configure form offers the field). An
113
+ interval runs on whole multiples of the 5-minute tick; a cron runs on the first tick after it fires. Create, update,
114
+ upgrade and delete need no scheduler call: the next tick reads the new state. A run is deduped on
115
+ `tick:<event>:<scheduledFor>`, so a redelivered run happens once.
116
+
117
+ ## Steps (v0.1)
118
+
119
+ Built-ins: `links.find`, `links.upsert`, `map`, `merge`, `template`, `set`, `stop`, `foreach` (≤1000), `branch`, `code`.
120
+
121
+ - `map` rows read a `source` field or write a fixed `value` (`{ "target": "Line[0].DetailType", "value": "SalesItemLineDetail" }`).
122
+ - `merge` deep-merges objects (later wins, lists replaced).
123
+ - `foreach` takes `where` (skip items, checked before the cap) and `collect` (the step's result becomes one value per
124
+ item, which may read that iteration's steps); `do` is optional when `collect` is set. A digest is
125
+ `collect` + `{{steps.lines | join: '\n'}}`, not a string grown with `set`.
126
+ - Template filters include arithmetic as named, total functions: `plus`, `minus`, `times`, `divided_by`, `round`,
127
+ `abs`, `number`, `to_cents` / `from_cents`, `to_minor_units` / `from_minor_units` (currency-aware: JPY has no minor
128
+ unit, KWD three), `from_unix` / `to_unix`, and `join`, `size`, `first`. Bad input gives blank, never a throw. A
129
+ string that is exactly one tag keeps the value's type, so `"{{item.Amount | to_cents}}"` is the number 2000.
130
+ Everything else is `<moduleKey>.<object>.<verb>`, a capability the module's manifest declares and maps to one Api
131
+ method. There is no http, script or eval step. `code` calls a named, versioned function shipped in reviewed code
132
+ (`@scope/pkg#fn@1.2.0`) for logic that does not fit steps. Per step: `when` (skip), `onError`
133
+ (`fail` → the queue retries the run, `continue`, `stop`).
134
+
135
+ ## Versioning
136
+
137
+ Published versions are immutable and each installation pins one. `checkBump` refuses a release whose declared semver
138
+ bump is smaller than its changes (patch: steps/templates/view/mapping; minor: additive, including a new link set or
139
+ changed option-list inputs; major: removed workflow or link set, required setting, identity change, new module). `planUpgrade` lists what a person must supply first and what the
140
+ runtime does (enable/disable workflows, rebuild links, re-run install steps). Queued messages carry the version
141
+ they were routed under and finish on it.
142
+
143
+ ## Running the tests
144
+
145
+ ```bash
146
+ npx jest --config '{}' --rootDir packages/core/integrations/data-defined tests
147
+ ```
148
+
149
+ `tests/persistence.test.js` runs the repositories and the publish rules against real databases. Each leg runs only
150
+ when its URL is set. Point them at a migrated PostgreSQL database and a MongoDB replica set with the schema pushed:
151
+
152
+ ```bash
153
+ DATA_DEFINED_POSTGRES_URL=postgresql://… DATA_DEFINED_MONGO_URL=mongodb://… npx jest … tests
154
+ ```
155
+
156
+ ## Validating
157
+
158
+ Validation is two layers, and a document is valid only when both pass (`schema-check.js`):
159
+
160
+ 1. **JSON Schema** (`schema/*.schema.json`): the published shape.
161
+ 2. **References** (`validate.js`, `manifests.js`): what a schema cannot see — steps name declared capabilities,
162
+ `$.steps.x` is an earlier step, view paths exist, option inputs are declared, `$.install` paths resolve.
163
+
164
+ ```bash
165
+ npm run validate:definitions --workspace @friggframework/core # bundled manifests + examples
166
+ node packages/core/integrations/data-defined/scripts/validate.js my.definition.json --strict
167
+ node packages/core/integrations/data-defined/scripts/validate.js --manifests ./capabilities --json defs/
168
+ ```
169
+
170
+ Exit codes: `0` valid, `1` invalid (or a warning with `--strict`), `2` could not run (unreadable JSON, missing file,
171
+ unknown option, `ajv` not installed). Manifests are checked first and an invalid manifest fails the run, because a
172
+ definition is only as trustworthy as the manifests it is checked against.
173
+
174
+ `ajv` comes from the monorepo root (`@friggframework/schemas` depends on it); core's runtime stays dependency-free and
175
+ loads it only for validation. `tests/schemas.test.js` runs both layers over every example and manifest and drives the
176
+ CLI as a child process; it fails, rather than skips, if `ajv` is missing. Core's `npm test`, and so CI's
177
+ `npm run test:all`, runs it on every change.
178
+
179
+ ## Not in v0.1
180
+
181
+ - The sync engine (backfill pages, ongoing deltas, two-way master rules) — specified by the schema, to be executed by
182
+ the existing `SYNC_PAGE` pattern. `runSync` throws until then.
183
+ - `delay` / wait steps, approvals that pause a run, and per-tenant rate limits.
184
+ - The host renderers (the HubSpot app extension and Phone panel that draw `renderSurface` output).
185
+ - Rebuilding `link:` / `idx:` rows after an identity change; `planUpgrade` reports it as `relink` / `reindex`.
@@ -0,0 +1,11 @@
1
+ /** Canonical JSON (sorted keys, no whitespace) and its sha256: the checksum a published version is stored under. */
2
+ const crypto = require('crypto');
3
+ // Canonical order is by UTF-16 code unit (what a bare sort() does), never locale: the checksum must not depend on the host's locale.
4
+ const byCodeUnit = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
5
+ function canonical(v) {
6
+ if (Array.isArray(v)) return '[' + v.map(canonical).join(',') + ']';
7
+ if (v && typeof v === 'object') return '{' + Object.keys(v).sort(byCodeUnit).filter((k) => v[k] !== undefined).map((k) => JSON.stringify(k) + ':' + canonical(v[k])).join(',') + '}';
8
+ return JSON.stringify(v);
9
+ }
10
+ const checksum = (doc) => 'sha256:' + crypto.createHash('sha256').update(canonical(doc)).digest('hex');
11
+ module.exports = { canonical, checksum };