@friggframework/core 2.0.0--canary.700.80ec1cc.0 → 2.0.0--canary.702.047d3c4.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 (130) hide show
  1. package/database/documentdb-utils.js +1 -6
  2. package/errors/index.js +0 -4
  3. package/generated/prisma-mongodb/edge.js +4 -52
  4. package/generated/prisma-mongodb/index-browser.js +1 -49
  5. package/generated/prisma-mongodb/index.d.ts +60 -3506
  6. package/generated/prisma-mongodb/index.js +4 -52
  7. package/generated/prisma-mongodb/package.json +1 -1
  8. package/generated/prisma-mongodb/schema.prisma +0 -65
  9. package/generated/prisma-mongodb/wasm.js +4 -52
  10. package/generated/prisma-postgresql/edge.js +4 -52
  11. package/generated/prisma-postgresql/index-browser.js +1 -49
  12. package/generated/prisma-postgresql/index.d.ts +94 -3824
  13. package/generated/prisma-postgresql/index.js +4 -52
  14. package/generated/prisma-postgresql/package.json +1 -1
  15. package/generated/prisma-postgresql/schema.prisma +0 -63
  16. package/generated/prisma-postgresql/wasm.js +4 -52
  17. package/handlers/WEBHOOKS.md +0 -29
  18. package/handlers/app-definition-loader.js +9 -2
  19. package/handlers/app-handler-helpers.js +2 -5
  20. package/handlers/integration-event-dispatcher.js +3 -7
  21. package/handlers/routers/integration-webhook-routers.js +38 -26
  22. package/index.js +0 -2
  23. package/integrations/integration-base.js +1 -162
  24. package/integrations/integration-router.js +1 -6
  25. package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
  26. package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
  27. package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
  28. package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
  29. package/integrations/repositories/integration-mapping-repository.js +0 -29
  30. package/integrations/repositories/integration-repository-documentdb.js +2 -6
  31. package/integrations/repositories/integration-repository-interface.js +0 -3
  32. package/integrations/repositories/integration-repository-mongo.js +5 -20
  33. package/integrations/repositories/integration-repository-postgres.js +1 -5
  34. package/integrations/repositories/process-repository-mongo.js +1 -1
  35. package/integrations/use-cases/create-integration.js +4 -14
  36. package/integrations/use-cases/delete-integration-for-user.js +4 -4
  37. package/integrations/use-cases/get-integration-for-user.js +2 -4
  38. package/integrations/use-cases/get-integration-instance.js +4 -4
  39. package/integrations/use-cases/get-integrations-for-user.js +4 -4
  40. package/integrations/use-cases/get-possible-integrations.js +2 -7
  41. package/integrations/use-cases/update-integration.js +4 -4
  42. package/package.json +6 -6
  43. package/prisma-mongodb/schema.prisma +0 -65
  44. package/prisma-postgresql/schema.prisma +0 -63
  45. package/queues/queuer-util.js +2 -9
  46. package/errors/mapping-already-exists-error.js +0 -14
  47. package/handlers/workers/integration-triggers.js +0 -25
  48. package/infrastructure/scheduler/recurrence.js +0 -204
  49. package/integrations/definitions/README.md +0 -278
  50. package/integrations/definitions/canonical.js +0 -11
  51. package/integrations/definitions/capabilities/AUDIT.md +0 -480
  52. package/integrations/definitions/capabilities/acmeerp.capabilities.json +0 -633
  53. package/integrations/definitions/capabilities/asana.capabilities.json +0 -279
  54. package/integrations/definitions/capabilities/calendly.capabilities.json +0 -385
  55. package/integrations/definitions/capabilities/docusign.capabilities.json +0 -314
  56. package/integrations/definitions/capabilities/fathom.capabilities.json +0 -238
  57. package/integrations/definitions/capabilities/github.capabilities.json +0 -585
  58. package/integrations/definitions/capabilities/hubspot.capabilities.json +0 -822
  59. package/integrations/definitions/capabilities/jira.capabilities.json +0 -391
  60. package/integrations/definitions/capabilities/klaviyo.capabilities.json +0 -503
  61. package/integrations/definitions/capabilities/linear.capabilities.json +0 -378
  62. package/integrations/definitions/capabilities/netsuite.capabilities.json +0 -535
  63. package/integrations/definitions/capabilities/notion.capabilities.json +0 -208
  64. package/integrations/definitions/capabilities/phone.capabilities.json +0 -511
  65. package/integrations/definitions/capabilities/pipedrive.capabilities.json +0 -430
  66. package/integrations/definitions/capabilities/quickbooks.capabilities.json +0 -635
  67. package/integrations/definitions/capabilities/salesforce.capabilities.json +0 -568
  68. package/integrations/definitions/capabilities/shopify.capabilities.json +0 -1128
  69. package/integrations/definitions/capabilities/slack.capabilities.json +0 -373
  70. package/integrations/definitions/capabilities/stripe.capabilities.json +0 -630
  71. package/integrations/definitions/capabilities/webflow.capabilities.json +0 -196
  72. package/integrations/definitions/capabilities/zendesk.capabilities.json +0 -422
  73. package/integrations/definitions/compile.js +0 -80
  74. package/integrations/definitions/config-form.js +0 -137
  75. package/integrations/definitions/examples/acme-erp-quickbooks.definition.json +0 -467
  76. package/integrations/definitions/examples/asana-slack.definition.json +0 -219
  77. package/integrations/definitions/examples/calendly-salesforce.definition.json +0 -459
  78. package/integrations/definitions/examples/docusign-salesforce.definition.json +0 -305
  79. package/integrations/definitions/examples/fathom-hubspot-notion.definition.json +0 -575
  80. package/integrations/definitions/examples/github-linear.definition.json +0 -322
  81. package/integrations/definitions/examples/hubspot-slack.definition.json +0 -427
  82. package/integrations/definitions/examples/klaviyo-hubspot.definition.json +0 -336
  83. package/integrations/definitions/examples/phone-hubspot.definition.json +0 -633
  84. package/integrations/definitions/examples/pipedrive-hubspot.definition.json +0 -136
  85. package/integrations/definitions/examples/pipedrive-phone.definition.json +0 -340
  86. package/integrations/definitions/examples/records/phone-hubspot.definition-version.json +0 -652
  87. package/integrations/definitions/examples/records/phone-hubspot.integration.json +0 -86
  88. package/integrations/definitions/examples/records/phone-hubspot.mappings.json +0 -39
  89. package/integrations/definitions/examples/records/phone-hubspot.workflow-run.json +0 -62
  90. package/integrations/definitions/examples/shopify-klaviyo.definition.json +0 -488
  91. package/integrations/definitions/examples/shopify-netsuite.definition.json +0 -622
  92. package/integrations/definitions/examples/stripe-quickbooks.definition.json +0 -476
  93. package/integrations/definitions/examples/webflow-hubspot-slack.definition.json +0 -262
  94. package/integrations/definitions/examples/zendesk-jira.definition.json +0 -604
  95. package/integrations/definitions/expressions.js +0 -229
  96. package/integrations/definitions/index.js +0 -45
  97. package/integrations/definitions/integration-runtime.js +0 -763
  98. package/integrations/definitions/interpreter.js +0 -104
  99. package/integrations/definitions/manifests.js +0 -177
  100. package/integrations/definitions/renderers/common.js +0 -67
  101. package/integrations/definitions/renderers/html.js +0 -129
  102. package/integrations/definitions/renderers/hubspot.js +0 -59
  103. package/integrations/definitions/renderers/preview.js +0 -154
  104. package/integrations/definitions/renderers/slack.js +0 -146
  105. package/integrations/definitions/repositories/definition-version-repository.js +0 -67
  106. package/integrations/definitions/repositories/workflow-run-repository.js +0 -80
  107. package/integrations/definitions/router.js +0 -170
  108. package/integrations/definitions/runtime.js +0 -268
  109. package/integrations/definitions/schema/capability-manifest.v0.1.schema.json +0 -549
  110. package/integrations/definitions/schema/installation.v0.1.schema.json +0 -130
  111. package/integrations/definitions/schema/integration-definition.v0.1.schema.json +0 -909
  112. package/integrations/definitions/schema/records.md +0 -105
  113. package/integrations/definitions/schema-check.js +0 -58
  114. package/integrations/definitions/scripts/check-manifests.js +0 -220
  115. package/integrations/definitions/scripts/validate.js +0 -66
  116. package/integrations/definitions/steps.js +0 -123
  117. package/integrations/definitions/sync-engine.js +0 -297
  118. package/integrations/definitions/tests/helpers-fake-crm.js +0 -49
  119. package/integrations/definitions/transforms.js +0 -91
  120. package/integrations/definitions/use-cases/definition-use-cases.js +0 -245
  121. package/integrations/definitions/validate.js +0 -436
  122. package/integrations/definitions/versioning.js +0 -176
  123. package/integrations/definitions/webhooks.js +0 -119
  124. package/integrations/integration-types.js +0 -64
  125. package/integrations/triggers.js +0 -244
  126. package/integrations/use-cases/run-trigger-tick.js +0 -155
  127. package/integrations/use-cases/run-trigger.js +0 -77
  128. package/prisma-postgresql/migrations/20261018000000_add_data_defined_integrations/migration.sql +0 -66
  129. package/prisma-postgresql/migrations/20261019000000_workflow_run_waits/migration.sql +0 -7
  130. package/prisma-postgresql/migrations/20261019120000_definition_workspace/migration.sql +0 -5
@@ -1,4 +1,3 @@
1
- const { resolveIntegrationClass } = require('../integration-types');
2
1
  // Removed Integration wrapper - using IntegrationBase directly
3
2
 
4
3
  /**
@@ -37,9 +36,10 @@ class GetIntegrationInstance {
37
36
  );
38
37
  }
39
38
 
40
- const integrationClass = await resolveIntegrationClass(
41
- this.integrationClasses,
42
- integrationRecord.config.type
39
+ const integrationClass = this.integrationClasses.find(
40
+ (integrationClass) =>
41
+ integrationClass.Definition.name ===
42
+ integrationRecord.config.type
43
43
  );
44
44
 
45
45
  if (!integrationClass) {
@@ -1,4 +1,3 @@
1
- const { resolveIntegrationClass } = require('../integration-types');
2
1
  // Removed Integration wrapper - using IntegrationBase directly
3
2
  const {
4
3
  mapIntegrationClassToIntegrationDTO,
@@ -49,9 +48,10 @@ class GetIntegrationsForUser {
49
48
  integrationRecord.entitiesIds
50
49
  );
51
50
 
52
- const integrationClass = await resolveIntegrationClass(
53
- this.integrationClasses,
54
- integrationRecord.config.type
51
+ const integrationClass = this.integrationClasses.find(
52
+ (integrationClass) =>
53
+ integrationClass.Definition.name ===
54
+ integrationRecord.config.type
55
55
  );
56
56
 
57
57
  const modules = [];
@@ -1,5 +1,3 @@
1
- const { listIntegrationClasses } = require('../integration-types');
2
-
3
1
  /**
4
2
  * Use case for retrieving all possible integration types that can be created.
5
3
  * @class GetPossibleIntegrations
@@ -19,11 +17,8 @@ class GetPossibleIntegrations {
19
17
  * @async
20
18
  * @returns {Promise<Object[]>} Array of integration option details for all available integration types.
21
19
  */
22
- async execute({ userId } = {}) {
23
- // Registered classes and the types providers offer (published definitions, and the ones this user's workspace
24
- // built), one list.
25
- const classes = await listIntegrationClasses(this.integrationClasses, userId ? { workspaceId: String(userId) } : undefined);
26
- return classes.map((integrationClass) =>
20
+ async execute() {
21
+ return this.integrationClasses.map((integrationClass) =>
27
22
  integrationClass.getOptionDetails()
28
23
  );
29
24
  }
@@ -1,4 +1,3 @@
1
- const { resolveIntegrationClass } = require('../integration-types');
2
1
  const {
3
2
  mapIntegrationClassToIntegrationDTO,
4
3
  } = require('../utils/map-integration-dto');
@@ -42,9 +41,10 @@ class UpdateIntegration {
42
41
  }
43
42
 
44
43
  // 2. Get the correct Integration class by type
45
- const integrationClass = await resolveIntegrationClass(
46
- this.integrationClasses,
47
- integrationRecord.config.type
44
+ const integrationClass = this.integrationClasses.find(
45
+ (integrationClass) =>
46
+ integrationClass.Definition.name ===
47
+ integrationRecord.config.type
48
48
  );
49
49
 
50
50
  if (!integrationClass) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@friggframework/core",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.700.80ec1cc.0",
4
+ "version": "2.0.0--canary.702.047d3c4.0",
5
5
  "dependencies": {
6
6
  "@aws-sdk/client-apigatewaymanagementapi": "^3.588.0",
7
7
  "@aws-sdk/client-kms": "^3.588.0",
@@ -10,6 +10,7 @@
10
10
  "@aws-sdk/client-sqs": "^3.588.0",
11
11
  "@aws-sdk/client-ssm": "^3.588.0",
12
12
  "@aws-sdk/s3-request-presigner": "^3.588.0",
13
+ "@friggframework/schemas": "2.0.0--canary.702.047d3c4.0",
13
14
  "@hapi/boom": "^10.0.1",
14
15
  "@opentelemetry/api": "^1.9.1",
15
16
  "@opentelemetry/context-async-hooks": "^2.9.0",
@@ -47,9 +48,9 @@
47
48
  }
48
49
  },
49
50
  "devDependencies": {
50
- "@friggframework/eslint-config": "2.0.0--canary.700.80ec1cc.0",
51
- "@friggframework/prettier-config": "2.0.0--canary.700.80ec1cc.0",
52
- "@friggframework/test": "2.0.0--canary.700.80ec1cc.0",
51
+ "@friggframework/eslint-config": "2.0.0--canary.702.047d3c4.0",
52
+ "@friggframework/prettier-config": "2.0.0--canary.702.047d3c4.0",
53
+ "@friggframework/test": "2.0.0--canary.702.047d3c4.0",
53
54
  "@prisma/client": "^6.19.3",
54
55
  "@types/lodash": "4.17.15",
55
56
  "@typescript-eslint/eslint-plugin": "^8.0.0",
@@ -67,7 +68,6 @@
67
68
  "scripts": {
68
69
  "lint:fix": "prettier --write --loglevel error . && eslint . --fix",
69
70
  "test": "jest --passWithNoTests # TODO",
70
- "validate:definitions": "node integrations/definitions/scripts/validate.js",
71
71
  "prisma:generate:mongo": "npx prisma generate --schema ./prisma-mongodb/schema.prisma",
72
72
  "prisma:generate:postgres": "npx prisma generate --schema ./prisma-postgresql/schema.prisma",
73
73
  "prisma:generate": "npm run prisma:generate:mongo && npm run prisma:generate:postgres",
@@ -90,5 +90,5 @@
90
90
  "publishConfig": {
91
91
  "access": "public"
92
92
  },
93
- "gitHead": "80ec1cc658ebdfbe53482d0705c42129685eb47f"
93
+ "gitHead": "047d3c404aa8c9636d6c2c442d28ce5e5fcf6b39"
94
94
  }
@@ -181,7 +181,6 @@ model Integration {
181
181
  syncs Sync[]
182
182
  mappings IntegrationMapping[]
183
183
  processes Process[]
184
- workflowRuns WorkflowRun[]
185
184
 
186
185
  @@index([userId])
187
186
  @@index([status])
@@ -454,67 +453,3 @@ model UsageCounter {
454
453
  @@index([metric, integrationType, window])
455
454
  @@map("UsageCounter")
456
455
  }
457
-
458
- // Integrations published as definitions (ADR-063): one immutable row per published definition version.
459
- enum DefinitionStatus {
460
- DRAFT
461
- PUBLISHED
462
- DEPRECATED
463
- RETIRED
464
- }
465
-
466
- model IntegrationDefinitionVersion {
467
- id String @id @default(auto()) @map("_id") @db.ObjectId
468
- definitionId String
469
- version String
470
- schemaVersion String
471
- status DefinitionStatus @default(DRAFT)
472
- checksum String
473
- document Json
474
- changeLevel String?
475
- previousVersion String?
476
- notes String?
477
- createdBy String?
478
- // The workspace an integration a user built belongs to (null: the app's own catalogue, offered to everyone).
479
- workspaceId String?
480
- publishedAt DateTime?
481
- createdAt DateTime @default(now())
482
- updatedAt DateTime @updatedAt
483
-
484
- @@unique([definitionId, version])
485
- @@index([definitionId, status])
486
- @@index([workspaceId, status])
487
- @@map("IntegrationDefinitionVersion")
488
- }
489
-
490
- // One row per workflow run. trace holds step ids, statuses, timings and error messages, never request or
491
- // response bodies.
492
- model WorkflowRun {
493
- id String @id @default(auto()) @map("_id") @db.ObjectId
494
- integrationId String @db.ObjectId
495
- integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)
496
- definitionId String
497
- definitionVersion String
498
- workflowId String
499
- triggerType String
500
- eventId String?
501
- status String
502
- reason String?
503
- error String?
504
- retryable Boolean @default(false)
505
- trace Json @default("[]")
506
- /// The runtime's run id (run_...): how routes and resume jobs address a run
507
- runKey String?
508
- /// A paused run (status waiting): which step, and what it waits for. Never request or response bodies.
509
- waitingFor Json?
510
- resumeAt DateTime?
511
- startedAt DateTime
512
- endedAt DateTime?
513
- createdAt DateTime @default(now())
514
-
515
- @@index([integrationId, runKey])
516
- @@index([integrationId, startedAt])
517
- @@index([integrationId, workflowId, startedAt])
518
- @@index([integrationId, status])
519
- @@map("WorkflowRun")
520
- }
@@ -173,7 +173,6 @@ model Integration {
173
173
  syncs Sync[]
174
174
  mappings IntegrationMapping[]
175
175
  processes Process[]
176
- workflowRuns WorkflowRun[]
177
176
 
178
177
  @@index([userId])
179
178
  @@index([status])
@@ -435,65 +434,3 @@ model UsageCounter {
435
434
  // Covers series() (metric + integrationType + window range).
436
435
  @@index([metric, integrationType, window])
437
436
  }
438
-
439
- // Integrations published as definitions (ADR-063): one immutable row per published definition version.
440
- enum DefinitionStatus {
441
- DRAFT
442
- PUBLISHED
443
- DEPRECATED
444
- RETIRED
445
- }
446
-
447
- model IntegrationDefinitionVersion {
448
- id Int @id @default(autoincrement())
449
- definitionId String
450
- version String
451
- schemaVersion String
452
- status DefinitionStatus @default(DRAFT)
453
- checksum String
454
- document Json
455
- changeLevel String?
456
- previousVersion String?
457
- notes String?
458
- createdBy String?
459
- // The workspace an integration a user built belongs to (null: the app's own catalogue, offered to everyone).
460
- workspaceId String?
461
- publishedAt DateTime?
462
- createdAt DateTime @default(now())
463
- updatedAt DateTime @updatedAt
464
-
465
- @@unique([definitionId, version])
466
- @@index([definitionId, status])
467
- @@index([workspaceId, status])
468
- }
469
-
470
- // One row per workflow run. trace holds step ids, statuses, timings and error messages, never request or
471
- // response bodies.
472
- model WorkflowRun {
473
- id Int @id @default(autoincrement())
474
- integrationId Int
475
- integration Integration @relation(fields: [integrationId], references: [id], onDelete: Cascade)
476
- definitionId String
477
- definitionVersion String
478
- workflowId String
479
- triggerType String
480
- eventId String?
481
- status String
482
- reason String?
483
- error String?
484
- retryable Boolean @default(false)
485
- trace Json @default("[]")
486
- /// The runtime's run id (run_...): how routes and resume jobs address a run
487
- runKey String?
488
- /// A paused run (status waiting): which step, and what it waits for. Never request or response bodies.
489
- waitingFor Json?
490
- resumeAt DateTime?
491
- startedAt DateTime
492
- endedAt DateTime?
493
- createdAt DateTime @default(now())
494
-
495
- @@index([integrationId, runKey])
496
- @@index([integrationId, startedAt])
497
- @@index([integrationId, workflowId, startedAt])
498
- @@index([integrationId, status])
499
- }
@@ -88,21 +88,14 @@ const QueuerUtil = {
88
88
  return result;
89
89
  },
90
90
 
91
- /**
92
- * Send entries in batches of 10. `options.delaySeconds(entry, index)` may return a per-message SQS
93
- * DelaySeconds (0-900), e.g. to spread trigger runs across a tick.
94
- */
95
- batchSend: async (entries = [], queueUrl, options = {}) => {
91
+ batchSend: async (entries = [], queueUrl) => {
96
92
  const buffer = [];
97
93
  const batchSize = 10;
98
- const delayOf = typeof options.delaySeconds === 'function' ? options.delaySeconds : null;
99
94
 
100
- for (const [index, entry] of entries.entries()) {
101
- const delay = delayOf ? Math.max(0, Math.min(900, Math.floor(delayOf(entry, index) || 0))) : 0;
95
+ for (const entry of entries) {
102
96
  buffer.push({
103
97
  Id: uuid(),
104
98
  MessageBody: JSON.stringify(entry),
105
- ...(delay ? { DelaySeconds: delay } : {}),
106
99
  });
107
100
  // Sends 10, then purges the buffer
108
101
  if (buffer.length === batchSize) {
@@ -1,14 +0,0 @@
1
- const { BaseError } = require('./base-error');
2
-
3
- class MappingAlreadyExistsError extends BaseError {
4
- constructor(integrationId, sourceId, ...errorOptions) {
5
- super(
6
- `Mapping already exists for integration ${integrationId} and sourceId ${sourceId}`,
7
- ...errorOptions
8
- );
9
- this.integrationId = integrationId;
10
- this.sourceId = sourceId;
11
- }
12
- }
13
-
14
- module.exports = { MappingAlreadyExistsError };
@@ -1,25 +0,0 @@
1
- /**
2
- * The `{integration}Triggers` functions (ADR-055 §2-3): one per integration that declares triggers. Devtools gives
3
- * each one schedule per distinct tick (`{ tick: '5m', time }`) and one per `at` trigger (`{ at, time }`); this only
4
- * hands the event to the tick use case.
5
- */
6
- const { createHandler } = require('@friggframework/core');
7
- const { loadAppDefinition } = require('../app-definition-loader');
8
- const { hasTriggers } = require('../../integrations/triggers');
9
- const { runTriggerTick } = require('../../integrations/use-cases/run-trigger-tick');
10
-
11
- const handlers = {};
12
- const { integrations: integrationClasses } = loadAppDefinition();
13
-
14
- for (const IntegrationClass of integrationClasses) {
15
- if (!hasTriggers(IntegrationClass)) continue;
16
- handlers[IntegrationClass.Definition.name] = {
17
- tick: createHandler({
18
- eventName: `Trigger tick for ${IntegrationClass.Definition.name}`,
19
- isUserFacingResponse: false,
20
- method: async (event, context) => runTriggerTick(IntegrationClass, event || {}, context),
21
- }),
22
- };
23
- }
24
-
25
- module.exports = { handlers };
@@ -1,204 +0,0 @@
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 };