@mastra/factory 0.30.0 → 0.31.0-alpha.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.
- package/README.md +32 -10
- package/dist/factory.d.ts +12 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +72 -31
- package/dist/factory.js.map +1 -1
- package/dist/integrations/gitlab/api.d.ts +3 -2
- package/dist/integrations/gitlab/api.d.ts.map +1 -1
- package/dist/integrations/gitlab/api.js +12 -9
- package/dist/integrations/gitlab/api.js.map +1 -1
- package/dist/integrations/issue-reconcile-worker.d.ts +5 -0
- package/dist/integrations/issue-reconcile-worker.d.ts.map +1 -1
- package/dist/integrations/issue-reconcile-worker.js +17 -1
- package/dist/integrations/issue-reconcile-worker.js.map +1 -1
- package/dist/integrations/platform/connect/routes.d.ts +22 -13
- package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
- package/dist/integrations/platform/connect/routes.js +63 -64
- package/dist/integrations/platform/connect/routes.js.map +1 -1
- package/dist/integrations/platform/foundation/connect-binding.d.ts +125 -0
- package/dist/integrations/platform/foundation/connect-binding.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/connect-binding.js +252 -0
- package/dist/integrations/platform/foundation/connect-binding.js.map +1 -0
- package/dist/integrations/platform/foundation/connect-event-poller.d.ts +49 -0
- package/dist/integrations/platform/foundation/connect-event-poller.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/connect-event-poller.js +304 -0
- package/dist/integrations/platform/foundation/connect-event-poller.js.map +1 -0
- package/dist/integrations/platform/foundation/connect-events.d.ts +31 -0
- package/dist/integrations/platform/foundation/connect-events.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/connect-events.js +7 -0
- package/dist/integrations/platform/foundation/connect-events.js.map +1 -0
- package/dist/integrations/platform/foundation/index.d.ts +10 -0
- package/dist/integrations/platform/foundation/index.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/index.js +6 -0
- package/dist/integrations/platform/foundation/intake.d.ts +39 -0
- package/dist/integrations/platform/foundation/intake.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/intake.js +45 -0
- package/dist/integrations/platform/foundation/intake.js.map +1 -0
- package/dist/integrations/platform/foundation/integration.d.ts +84 -0
- package/dist/integrations/platform/foundation/integration.d.ts.map +1 -0
- package/dist/integrations/platform/foundation/integration.js +107 -0
- package/dist/integrations/platform/foundation/integration.js.map +1 -0
- package/dist/integrations/platform/github/event-worker.d.ts +2 -2
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +4 -8
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +3 -0
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +131 -70
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/gitlab/connect-events.d.ts +22 -0
- package/dist/integrations/platform/gitlab/connect-events.d.ts.map +1 -0
- package/dist/integrations/platform/gitlab/connect-events.js +49 -0
- package/dist/integrations/platform/gitlab/connect-events.js.map +1 -0
- package/dist/integrations/platform/gitlab/integration.d.ts +24 -15
- package/dist/integrations/platform/gitlab/integration.d.ts.map +1 -1
- package/dist/integrations/platform/gitlab/integration.js +61 -26
- package/dist/integrations/platform/gitlab/integration.js.map +1 -1
- package/dist/integrations/platform/incidentio/intake.d.ts +33 -0
- package/dist/integrations/platform/incidentio/intake.d.ts.map +1 -0
- package/dist/integrations/platform/incidentio/intake.js +271 -0
- package/dist/integrations/platform/incidentio/intake.js.map +1 -0
- package/dist/integrations/platform/incidentio/integration.d.ts +11 -23
- package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
- package/dist/integrations/platform/incidentio/integration.js +27 -297
- package/dist/integrations/platform/incidentio/integration.js.map +1 -1
- package/dist/integrations/platform/jira/intake.d.ts +60 -0
- package/dist/integrations/platform/jira/intake.d.ts.map +1 -0
- package/dist/integrations/platform/jira/intake.js +445 -0
- package/dist/integrations/platform/jira/intake.js.map +1 -0
- package/dist/integrations/platform/jira/integration.d.ts +13 -37
- package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
- package/dist/integrations/platform/jira/integration.js +29 -468
- package/dist/integrations/platform/jira/integration.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts +2 -2
- package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/linear/event-worker.js +5 -9
- package/dist/integrations/platform/linear/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/integration.d.ts +3 -1
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +9 -9
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/integrations/platform/logging.d.ts +6 -0
- package/dist/integrations/platform/logging.d.ts.map +1 -0
- package/dist/integrations/platform/logging.js +25 -0
- package/dist/integrations/platform/logging.js.map +1 -0
- package/dist/integrations/platform/platform-connect.d.ts +38 -0
- package/dist/integrations/platform/platform-connect.d.ts.map +1 -0
- package/dist/integrations/platform/platform-connect.js +109 -0
- package/dist/integrations/platform/platform-connect.js.map +1 -0
- package/dist/integrations/platform/vanta/integration.d.ts +12 -18
- package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
- package/dist/integrations/platform/vanta/integration.js +38 -38
- package/dist/integrations/platform/vanta/integration.js.map +1 -1
- package/dist/memory-embedder.d.ts +11 -0
- package/dist/memory-embedder.d.ts.map +1 -0
- package/dist/memory-embedder.js +19 -0
- package/dist/memory-embedder.js.map +1 -0
- package/dist/metrics/config.d.ts +1 -1
- package/dist/metrics/config.d.ts.map +1 -1
- package/dist/metrics/config.js +1 -0
- package/dist/metrics/config.js.map +1 -1
- package/dist/metrics/index.js +2 -2
- package/dist/metrics/index.js.map +1 -1
- package/dist/metrics/sandbox.d.ts +3 -3
- package/dist/metrics/sandbox.js +13 -13
- package/dist/metrics/sandbox.js.map +1 -1
- package/dist/metrics/session.d.ts +28 -0
- package/dist/metrics/session.d.ts.map +1 -0
- package/dist/metrics/session.js +76 -0
- package/dist/metrics/session.js.map +1 -0
- package/dist/routes/source-control-sessions.d.ts +5 -0
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +65 -7
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/surface.d.ts +5 -0
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +1 -0
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts +29 -1
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +156 -23
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/public-failure-reason.js +1 -1
- package/dist/rules/public-failure-reason.js.map +1 -1
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +33 -9
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +2 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +4 -2
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/work-item-branch.d.ts +7 -1
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +9 -1
- package/dist/work-item-branch.js.map +1 -1
- package/dist/work-items/card-facts.d.ts.map +1 -1
- package/dist/work-items/card-facts.js +2 -2
- package/dist/work-items/card-facts.js.map +1 -1
- package/package.json +8 -8
- package/dist/integrations/platform/api-client.d.ts +0 -34
- package/dist/integrations/platform/api-client.d.ts.map +0 -1
- package/dist/integrations/platform/api-client.js +0 -186
- package/dist/integrations/platform/api-client.js.map +0 -1
- package/dist/integrations/platform/gitlab/event-worker.d.ts +0 -64
- package/dist/integrations/platform/gitlab/event-worker.d.ts.map +0 -1
- package/dist/integrations/platform/gitlab/event-worker.js +0 -304
- package/dist/integrations/platform/gitlab/event-worker.js.map +0 -1
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { platformErrorStatus, platformRetryDelayMs } from "../platform-connect.js";
|
|
2
|
+
import { NoopLeaseProvider, isLeaseProvider } from "@mastra/core/events";
|
|
3
|
+
import { MastraWorker } from "@mastra/core/worker";
|
|
4
|
+
// src/integrations/platform/foundation/connect-event-poller.ts
|
|
5
|
+
/** Integration-storage id the deployment's Connect event poller keeps its cursors under. */
|
|
6
|
+
const PLATFORM_CONNECT_EVENT_POLLER_STORAGE_ID = "platform-connect-event-poller";
|
|
7
|
+
const DEFAULT_POLL_INTERVAL_MS = 2e4;
|
|
8
|
+
const EVENT_PAGE_SIZE = 500;
|
|
9
|
+
/**
|
|
10
|
+
* Pages drained per connection per cycle. A connection that never runs dry
|
|
11
|
+
* hands over to the next after this many pages and resumes next cycle.
|
|
12
|
+
*/
|
|
13
|
+
const MAX_PAGES_PER_CONNECTION_PER_CYCLE = 10;
|
|
14
|
+
const MIN_LEASE_TTL_MS = 3e4;
|
|
15
|
+
const DEFAULT_RETRY_DELAY_MS = 1e3;
|
|
16
|
+
const HANDLER_ATTEMPTS = 3;
|
|
17
|
+
const CURSOR_ORG_ID = "__platform_connect_event_poller__";
|
|
18
|
+
const CURSOR_USER_ID = "worker";
|
|
19
|
+
/**
|
|
20
|
+
* Reads each routed integration's active connections' platform event logs,
|
|
21
|
+
* through the integration's own Connect client, and
|
|
22
|
+
* hands every event to the integration's route. It is how Platform
|
|
23
|
+
* integrations receive provider webhooks until they read the events service.
|
|
24
|
+
*
|
|
25
|
+
* One replica polls at a time (lease). Each connection keeps its own cursor,
|
|
26
|
+
* saved after each handled event, so delivery is at-least-once: handlers
|
|
27
|
+
* dedupe on `dedupeKey`. A connection read for the first time starts at the
|
|
28
|
+
* present and asks its integration to reconcile once, since events from
|
|
29
|
+
* before then are not read.
|
|
30
|
+
*
|
|
31
|
+
* The event log carries no verification flag, so events reach handlers with
|
|
32
|
+
* `unverified: false`. That doesn't prove the platform checked the signature.
|
|
33
|
+
*/
|
|
34
|
+
var PlatformConnectEventPoller = class extends MastraWorker {
|
|
35
|
+
name = "platform-connect-event-poller";
|
|
36
|
+
#storage;
|
|
37
|
+
#routes;
|
|
38
|
+
#intervalMs;
|
|
39
|
+
#retryDelayMs;
|
|
40
|
+
#now;
|
|
41
|
+
#leaseTtlMs;
|
|
42
|
+
#leaseOwner = globalThis.crypto.randomUUID();
|
|
43
|
+
#running = false;
|
|
44
|
+
#timer;
|
|
45
|
+
#leaseRenewalTimer;
|
|
46
|
+
#inFlight;
|
|
47
|
+
#leaseProvider = NoopLeaseProvider;
|
|
48
|
+
#hasLease = false;
|
|
49
|
+
#settings = {
|
|
50
|
+
version: 1,
|
|
51
|
+
connections: {}
|
|
52
|
+
};
|
|
53
|
+
#handlerFailures = 0;
|
|
54
|
+
constructor(config) {
|
|
55
|
+
super();
|
|
56
|
+
this.#storage = config.storage;
|
|
57
|
+
this.#routes = config.routes;
|
|
58
|
+
const asked = config.routes.flatMap((route) => route.pollIntervalMs === void 0 ? [] : [route.pollIntervalMs]);
|
|
59
|
+
this.#intervalMs = config.intervalMs ?? (asked.length > 0 ? Math.min(...asked) : DEFAULT_POLL_INTERVAL_MS);
|
|
60
|
+
if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) throw new Error("Platform Connect event polling interval must be a positive number.");
|
|
61
|
+
this.#retryDelayMs = config.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
|
|
62
|
+
this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);
|
|
63
|
+
this.#now = config.now ?? Date.now;
|
|
64
|
+
}
|
|
65
|
+
async init(deps) {
|
|
66
|
+
await super.init(deps);
|
|
67
|
+
this.#leaseProvider = getLeaseProvider(deps.pubsub);
|
|
68
|
+
}
|
|
69
|
+
async start() {
|
|
70
|
+
if (this.#running) return;
|
|
71
|
+
if (!this.deps) throw new Error("PlatformConnectEventPoller: call init() before start()");
|
|
72
|
+
this.#running = true;
|
|
73
|
+
this.deps.logger.debug("Platform Connect event polling started", {
|
|
74
|
+
intervalMs: this.#intervalMs,
|
|
75
|
+
integrations: this.#routes.map((route) => route.binding.integrationId)
|
|
76
|
+
});
|
|
77
|
+
this.#schedule(0);
|
|
78
|
+
}
|
|
79
|
+
async stop() {
|
|
80
|
+
if (!this.#running) return;
|
|
81
|
+
this.#running = false;
|
|
82
|
+
if (this.#timer) clearTimeout(this.#timer);
|
|
83
|
+
this.#timer = void 0;
|
|
84
|
+
this.#stopLeaseRenewal();
|
|
85
|
+
await this.#inFlight;
|
|
86
|
+
if (this.#hasLease) {
|
|
87
|
+
await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => void 0);
|
|
88
|
+
this.#hasLease = false;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
get isRunning() {
|
|
92
|
+
return this.#running;
|
|
93
|
+
}
|
|
94
|
+
diagnostics() {
|
|
95
|
+
return {
|
|
96
|
+
polling: this.#running,
|
|
97
|
+
hasLease: this.#hasLease,
|
|
98
|
+
connections: Object.keys(this.#settings.connections).length,
|
|
99
|
+
handlerFailures: this.#handlerFailures
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
#schedule(delayMs) {
|
|
103
|
+
if (!this.#running) return;
|
|
104
|
+
this.#timer = setTimeout(() => {
|
|
105
|
+
this.#timer = void 0;
|
|
106
|
+
const run = this.#tick();
|
|
107
|
+
this.#inFlight = run;
|
|
108
|
+
run.finally(() => {
|
|
109
|
+
if (this.#inFlight === run) this.#inFlight = void 0;
|
|
110
|
+
});
|
|
111
|
+
}, delayMs);
|
|
112
|
+
this.#timer.unref?.();
|
|
113
|
+
}
|
|
114
|
+
async #tick() {
|
|
115
|
+
let nextDelay = this.#intervalMs;
|
|
116
|
+
try {
|
|
117
|
+
if (!await this.#ensureLease()) return;
|
|
118
|
+
nextDelay = await this.#poll();
|
|
119
|
+
} catch (error) {
|
|
120
|
+
nextDelay = platformRetryDelayMs(error, this.#intervalMs);
|
|
121
|
+
this.deps?.logger.error("Platform Connect event polling cycle failed", {
|
|
122
|
+
error: error instanceof Error ? error.message : String(error),
|
|
123
|
+
retryInMs: nextDelay
|
|
124
|
+
});
|
|
125
|
+
} finally {
|
|
126
|
+
this.#schedule(nextDelay);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async #ensureLease() {
|
|
130
|
+
if (this.#hasLease) return true;
|
|
131
|
+
if (!(await this.#leaseProvider.acquireLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs)).acquired) return false;
|
|
132
|
+
this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));
|
|
133
|
+
this.#hasLease = true;
|
|
134
|
+
this.#startLeaseRenewal();
|
|
135
|
+
return true;
|
|
136
|
+
}
|
|
137
|
+
#startLeaseRenewal() {
|
|
138
|
+
if (this.#leaseRenewalTimer) return;
|
|
139
|
+
this.#leaseRenewalTimer = setInterval(() => {
|
|
140
|
+
this.#leaseProvider.renewLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs).then((renewed) => {
|
|
141
|
+
if (!renewed) this.#loseLease();
|
|
142
|
+
}).catch((error) => {
|
|
143
|
+
this.#loseLease();
|
|
144
|
+
this.deps?.logger.warn("Platform Connect event polling lease renewal failed", { error: error instanceof Error ? error.message : String(error) });
|
|
145
|
+
});
|
|
146
|
+
}, Math.floor(this.#leaseTtlMs / 3));
|
|
147
|
+
this.#leaseRenewalTimer.unref?.();
|
|
148
|
+
}
|
|
149
|
+
#loseLease() {
|
|
150
|
+
this.#hasLease = false;
|
|
151
|
+
this.#stopLeaseRenewal();
|
|
152
|
+
}
|
|
153
|
+
#stopLeaseRenewal() {
|
|
154
|
+
if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);
|
|
155
|
+
this.#leaseRenewalTimer = void 0;
|
|
156
|
+
}
|
|
157
|
+
async #poll() {
|
|
158
|
+
let retryInMs = this.#intervalMs;
|
|
159
|
+
const seen = /* @__PURE__ */ new Set();
|
|
160
|
+
for (const route of this.#routes) {
|
|
161
|
+
let connections;
|
|
162
|
+
try {
|
|
163
|
+
connections = await route.binding.activeConnections();
|
|
164
|
+
} catch (error) {
|
|
165
|
+
this.deps?.logger.warn("Platform Connect event polling could not list connections", {
|
|
166
|
+
integration: route.binding.integrationId,
|
|
167
|
+
error: error instanceof Error ? error.message : String(error)
|
|
168
|
+
});
|
|
169
|
+
retryInMs = Math.max(retryInMs, platformRetryDelayMs(error, this.#intervalMs));
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
for (const connection of connections) {
|
|
173
|
+
if (!this.#running || !this.#hasLease) return retryInMs;
|
|
174
|
+
if (connection.resourceId) continue;
|
|
175
|
+
if (route.eventProviderKeys && !route.eventProviderKeys.includes(connection.integrationId)) continue;
|
|
176
|
+
if (seen.has(connection.id)) continue;
|
|
177
|
+
seen.add(connection.id);
|
|
178
|
+
try {
|
|
179
|
+
await this.#pollConnection(route, connection.id);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
const status = platformErrorStatus(error);
|
|
182
|
+
if (status === 401 || status === 404) {
|
|
183
|
+
this.deps?.logger.warn("Platform Connect connection is unavailable; skipped this cycle", {
|
|
184
|
+
integration: route.binding.integrationId,
|
|
185
|
+
connectionId: connection.id,
|
|
186
|
+
status
|
|
187
|
+
});
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
const delay = platformRetryDelayMs(error, this.#intervalMs);
|
|
191
|
+
retryInMs = Math.max(retryInMs, delay);
|
|
192
|
+
this.deps?.logger.error("Platform Connect connection event polling failed", {
|
|
193
|
+
integration: route.binding.integrationId,
|
|
194
|
+
connectionId: connection.id,
|
|
195
|
+
error: error instanceof Error ? error.message : String(error),
|
|
196
|
+
retryInMs: delay
|
|
197
|
+
});
|
|
198
|
+
if (status === 429) return retryInMs;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return retryInMs;
|
|
203
|
+
}
|
|
204
|
+
async #pollConnection(route, connectionId) {
|
|
205
|
+
if (!this.#settings.connections[connectionId]) {
|
|
206
|
+
await this.#saveCursor(connectionId, `${this.#now()}-0`);
|
|
207
|
+
route.reconcile();
|
|
208
|
+
}
|
|
209
|
+
for (let page = 0; page < MAX_PAGES_PER_CONNECTION_PER_CYCLE; page += 1) {
|
|
210
|
+
if (!this.#running || !this.#hasLease) return;
|
|
211
|
+
const after = this.#settings.connections[connectionId].afterEventId;
|
|
212
|
+
const query = new URLSearchParams({
|
|
213
|
+
afterEventId: after,
|
|
214
|
+
limit: String(EVENT_PAGE_SIZE)
|
|
215
|
+
});
|
|
216
|
+
const result = await route.binding.connect.request("GET", `/v2/connections/${encodeURIComponent(connectionId)}/events?${query}`);
|
|
217
|
+
for (const entry of result.events) {
|
|
218
|
+
if (!this.#running || !this.#hasLease) return;
|
|
219
|
+
await this.#deliver(route, connectionId, entry);
|
|
220
|
+
if (!this.#running || !this.#hasLease) return;
|
|
221
|
+
await this.#saveCursor(connectionId, entry.id);
|
|
222
|
+
}
|
|
223
|
+
if (result.events.length < EVENT_PAGE_SIZE) return;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Runs the handler, retrying with backoff. An event that still fails is
|
|
228
|
+
* logged and skipped, and its integration reconciles now.
|
|
229
|
+
*/
|
|
230
|
+
async #deliver(route, connectionId, entry) {
|
|
231
|
+
const sourceEventId = entry.sourceEventId || null;
|
|
232
|
+
const delivery = {
|
|
233
|
+
id: entry.id,
|
|
234
|
+
timestamp: entry.timestamp,
|
|
235
|
+
connectionId,
|
|
236
|
+
integrationId: entry.integrationId,
|
|
237
|
+
eventType: entry.eventType,
|
|
238
|
+
sourceEventId,
|
|
239
|
+
payload: entry.payload,
|
|
240
|
+
unverified: entry.unverified === true,
|
|
241
|
+
dedupeKey: sourceEventId ?? entry.id
|
|
242
|
+
};
|
|
243
|
+
for (let attempt = 1;; attempt += 1) try {
|
|
244
|
+
await route.handle(delivery);
|
|
245
|
+
return;
|
|
246
|
+
} catch (error) {
|
|
247
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
248
|
+
if (attempt >= HANDLER_ATTEMPTS) {
|
|
249
|
+
this.#handlerFailures += 1;
|
|
250
|
+
this.deps?.logger.error("Platform Connect events: giving up on an event; reconciling to repair it", {
|
|
251
|
+
integration: route.binding.integrationId,
|
|
252
|
+
connectionId,
|
|
253
|
+
eventId: entry.id,
|
|
254
|
+
attempts: attempt,
|
|
255
|
+
error: message
|
|
256
|
+
});
|
|
257
|
+
route.reconcile();
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
this.deps?.logger.warn("Platform Connect events: event handler failed; retrying", {
|
|
261
|
+
integration: route.binding.integrationId,
|
|
262
|
+
connectionId,
|
|
263
|
+
eventId: entry.id,
|
|
264
|
+
attempt,
|
|
265
|
+
error: message
|
|
266
|
+
});
|
|
267
|
+
await new Promise((resolve) => setTimeout(resolve, this.#retryDelayMs * 2 ** (attempt - 1)));
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
async #saveCursor(connectionId, afterEventId) {
|
|
271
|
+
const next = {
|
|
272
|
+
...this.#settings,
|
|
273
|
+
connections: {
|
|
274
|
+
...this.#settings.connections,
|
|
275
|
+
[connectionId]: { afterEventId }
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, next);
|
|
279
|
+
this.#settings = next;
|
|
280
|
+
}
|
|
281
|
+
#leaseKey() {
|
|
282
|
+
return `${this.name}:${this.#storage.integrationId}`;
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
function getLeaseProvider(pubsub) {
|
|
286
|
+
const getProvider = pubsub.getLeaseProvider;
|
|
287
|
+
if (typeof getProvider === "function") return getProvider.call(pubsub) ?? NoopLeaseProvider;
|
|
288
|
+
return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;
|
|
289
|
+
}
|
|
290
|
+
function normalizeSettings(value) {
|
|
291
|
+
if (!value || value.version !== 1 || !value.connections || typeof value.connections !== "object") return {
|
|
292
|
+
version: 1,
|
|
293
|
+
connections: {}
|
|
294
|
+
};
|
|
295
|
+
const connections = {};
|
|
296
|
+
for (const [connectionId, cursor] of Object.entries(value.connections)) if (typeof cursor?.afterEventId === "string" && cursor.afterEventId.length > 0) connections[connectionId] = { afterEventId: cursor.afterEventId };
|
|
297
|
+
return {
|
|
298
|
+
version: 1,
|
|
299
|
+
connections
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
export { PLATFORM_CONNECT_EVENT_POLLER_STORAGE_ID, PlatformConnectEventPoller };
|
|
303
|
+
|
|
304
|
+
//# sourceMappingURL=connect-event-poller.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-event-poller.js","names":[],"sources":["../../../../src/integrations/platform/foundation/connect-event-poller.ts"],"sourcesContent":["import { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport { platformErrorStatus, platformRetryDelayMs } from '../platform-connect.js';\nimport type { PlatformConnectEventRoute } from './connect-events.js';\n\n/** Integration-storage id the deployment's Connect event poller keeps its cursors under. */\nexport const PLATFORM_CONNECT_EVENT_POLLER_STORAGE_ID = 'platform-connect-event-poller';\n\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\nconst EVENT_PAGE_SIZE = 500;\n/**\n * Pages drained per connection per cycle. A connection that never runs dry\n * hands over to the next after this many pages and resumes next cycle.\n */\nconst MAX_PAGES_PER_CONNECTION_PER_CYCLE = 10;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst DEFAULT_RETRY_DELAY_MS = 1_000;\nconst HANDLER_ATTEMPTS = 3;\nconst CURSOR_ORG_ID = '__platform_connect_event_poller__';\nconst CURSOR_USER_ID = 'worker';\n\ntype PollerSettings = { version: 1; connections: Record<string, { afterEventId: string }> };\n\nexport type PlatformConnectEventPollerStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PollerSettings,\n Record<string, unknown>\n>;\n\n/** One row of a connection's platform event log (`GET /v2/connections/:id/events`). */\ninterface ConnectionEventEntry {\n id: string;\n timestamp: number;\n integrationId: string;\n eventType: string;\n sourceEventId: string | null;\n payload: unknown;\n /** Set when the forwarder skipped the provider's signature check. Not every platform version logs it. */\n unverified?: boolean;\n}\n\nexport interface PlatformConnectEventPollerConfig {\n storage: PlatformConnectEventPollerStorage;\n routes: readonly PlatformConnectEventRoute[];\n /** Defaults to the shortest `pollIntervalMs` the routes ask for, else 20 s. */\n intervalMs?: number;\n /** First delay between handler attempts; doubles per attempt. */\n retryDelayMs?: number;\n now?: () => number;\n}\n\n/**\n * Reads each routed integration's active connections' platform event logs,\n * through the integration's own Connect client, and\n * hands every event to the integration's route. It is how Platform\n * integrations receive provider webhooks until they read the events service.\n *\n * One replica polls at a time (lease). Each connection keeps its own cursor,\n * saved after each handled event, so delivery is at-least-once: handlers\n * dedupe on `dedupeKey`. A connection read for the first time starts at the\n * present and asks its integration to reconcile once, since events from\n * before then are not read.\n *\n * The event log carries no verification flag, so events reach handlers with\n * `unverified: false`. That doesn't prove the platform checked the signature.\n */\nexport class PlatformConnectEventPoller extends MastraWorker {\n readonly name = 'platform-connect-event-poller';\n\n readonly #storage: PlatformConnectEventPollerStorage;\n readonly #routes: readonly PlatformConnectEventRoute[];\n readonly #intervalMs: number;\n readonly #retryDelayMs: number;\n readonly #now: () => number;\n readonly #leaseTtlMs: number;\n readonly #leaseOwner = globalThis.crypto.randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #hasLease = false;\n #settings: PollerSettings = { version: 1, connections: {} };\n #handlerFailures = 0;\n\n constructor(config: PlatformConnectEventPollerConfig) {\n super();\n this.#storage = config.storage;\n this.#routes = config.routes;\n const asked = config.routes.flatMap(route => (route.pollIntervalMs === undefined ? [] : [route.pollIntervalMs]));\n this.#intervalMs = config.intervalMs ?? (asked.length > 0 ? Math.min(...asked) : DEFAULT_POLL_INTERVAL_MS);\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform Connect event polling interval must be a positive number.');\n }\n this.#retryDelayMs = config.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, this.#intervalMs * 3);\n this.#now = config.now ?? Date.now;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformConnectEventPoller: call init() before start()');\n this.#running = true;\n this.deps.logger.debug('Platform Connect event polling started', {\n intervalMs: this.#intervalMs,\n integrations: this.#routes.map(route => route.binding.integrationId),\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n diagnostics(): Record<string, unknown> {\n return {\n polling: this.#running,\n hasLease: this.#hasLease,\n connections: Object.keys(this.#settings.connections).length,\n handlerFailures: this.#handlerFailures,\n };\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = platformRetryDelayMs(error, this.#intervalMs);\n this.deps?.logger.error('Platform Connect event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs);\n if (!result.acquired) return false;\n // Another replica may have advanced the cursors while this one waited.\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#hasLease = true;\n this.#startLeaseRenewal();\n return true;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) this.#loseLease();\n })\n .catch(error => {\n this.#loseLease();\n this.deps?.logger.warn('Platform Connect event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #loseLease(): void {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n let retryInMs = this.#intervalMs;\n const seen = new Set<string>();\n for (const route of this.#routes) {\n let connections;\n try {\n connections = await route.binding.activeConnections();\n } catch (error) {\n this.deps?.logger.warn('Platform Connect event polling could not list connections', {\n integration: route.binding.integrationId,\n error: error instanceof Error ? error.message : String(error),\n });\n retryInMs = Math.max(retryInMs, platformRetryDelayMs(error, this.#intervalMs));\n continue;\n }\n for (const connection of connections) {\n if (!this.#running || !this.#hasLease) return retryInMs;\n // End-user connections carry tokens, not the integration's webhooks.\n if (connection.resourceId) continue;\n if (route.eventProviderKeys && !route.eventProviderKeys.includes(connection.integrationId)) continue;\n if (seen.has(connection.id)) continue;\n seen.add(connection.id);\n try {\n await this.#pollConnection(route, connection.id);\n } catch (error) {\n const status = platformErrorStatus(error);\n if (status === 401 || status === 404) {\n // The platform no longer serves this connection; its listing will\n // say so. The other connections keep flowing.\n this.deps?.logger.warn('Platform Connect connection is unavailable; skipped this cycle', {\n integration: route.binding.integrationId,\n connectionId: connection.id,\n status,\n });\n continue;\n }\n const delay = platformRetryDelayMs(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform Connect connection event polling failed', {\n integration: route.binding.integrationId,\n connectionId: connection.id,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (status === 429) return retryInMs;\n }\n }\n }\n return retryInMs;\n }\n\n async #pollConnection(route: PlatformConnectEventRoute, connectionId: string): Promise<void> {\n if (!this.#settings.connections[connectionId]) {\n // Log ids are Redis stream ids (`<unix ms>-<sequence>`), so this starts\n // at the present. What came before is covered by a reconcile.\n await this.#saveCursor(connectionId, `${this.#now()}-0`);\n route.reconcile();\n }\n for (let page = 0; page < MAX_PAGES_PER_CONNECTION_PER_CYCLE; page += 1) {\n if (!this.#running || !this.#hasLease) return;\n const after = this.#settings.connections[connectionId]!.afterEventId;\n const query = new URLSearchParams({ afterEventId: after, limit: String(EVENT_PAGE_SIZE) });\n const result = await route.binding.connect.request<{ events: ConnectionEventEntry[]; nextCursor: string | null }>(\n 'GET',\n `/v2/connections/${encodeURIComponent(connectionId)}/events?${query}`,\n );\n for (const entry of result.events) {\n // A replica that lost its lease must not move a cursor the new holder owns.\n if (!this.#running || !this.#hasLease) return;\n await this.#deliver(route, connectionId, entry);\n // The lease can lapse while a handler runs; the event is then the new holder's to deliver again.\n if (!this.#running || !this.#hasLease) return;\n await this.#saveCursor(connectionId, entry.id);\n }\n if (result.events.length < EVENT_PAGE_SIZE) return;\n }\n }\n\n /**\n * Runs the handler, retrying with backoff. An event that still fails is\n * logged and skipped, and its integration reconciles now.\n */\n async #deliver(route: PlatformConnectEventRoute, connectionId: string, entry: ConnectionEventEntry): Promise<void> {\n const sourceEventId = entry.sourceEventId || null;\n const delivery = {\n id: entry.id,\n timestamp: entry.timestamp,\n connectionId,\n integrationId: entry.integrationId,\n eventType: entry.eventType,\n sourceEventId,\n payload: entry.payload,\n unverified: entry.unverified === true,\n dedupeKey: sourceEventId ?? entry.id,\n };\n for (let attempt = 1; ; attempt += 1) {\n try {\n await route.handle(delivery);\n return;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (attempt >= HANDLER_ATTEMPTS) {\n this.#handlerFailures += 1;\n this.deps?.logger.error('Platform Connect events: giving up on an event; reconciling to repair it', {\n integration: route.binding.integrationId,\n connectionId,\n eventId: entry.id,\n attempts: attempt,\n error: message,\n });\n route.reconcile();\n return;\n }\n this.deps?.logger.warn('Platform Connect events: event handler failed; retrying', {\n integration: route.binding.integrationId,\n connectionId,\n eventId: entry.id,\n attempt,\n error: message,\n });\n await new Promise(resolve => setTimeout(resolve, this.#retryDelayMs * 2 ** (attempt - 1)));\n }\n }\n }\n\n async #saveCursor(connectionId: string, afterEventId: string): Promise<void> {\n const next = {\n ...this.#settings,\n connections: { ...this.#settings.connections, [connectionId]: { afterEventId } },\n };\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, next);\n // Only a saved cursor moves: if the save fails, the next cycle delivers the event again.\n this.#settings = next;\n }\n\n #leaseKey(): string {\n return `${this.name}:${this.#storage.integrationId}`;\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PollerSettings | null): PollerSettings {\n if (!value || value.version !== 1 || !value.connections || typeof value.connections !== 'object') {\n return { version: 1, connections: {} };\n }\n const connections: PollerSettings['connections'] = {};\n for (const [connectionId, cursor] of Object.entries(value.connections)) {\n if (typeof cursor?.afterEventId === 'string' && cursor.afterEventId.length > 0) {\n connections[connectionId] = { afterEventId: cursor.afterEventId };\n }\n }\n return { version: 1, connections };\n}\n"],"mappings":";;;;;AAUA,MAAa,2CAA2C;AAExD,MAAM,2BAA2B;AACjC,MAAM,kBAAkB;;;;;AAKxB,MAAM,qCAAqC;AAC3C,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAC/B,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;;;;;;;;;;;;;;;;AA+CvB,IAAa,6BAAb,cAAgD,aAAa;CAC3D,OAAgB;CAEhB;CACA;CACA;CACA;CACA;CACA;CACA,cAAuB,WAAW,OAAO,WAAW;CAEpD,WAAW;CACX;CACA;CACA;CACA,iBAAgC;CAChC,YAAY;CACZ,YAA4B;EAAE,SAAS;EAAG,aAAa,CAAC;CAAE;CAC1D,mBAAmB;CAEnB,YAAY,QAA0C;EACpD,MAAM;EACN,KAAK,WAAW,OAAO;EACvB,KAAK,UAAU,OAAO;EACtB,MAAM,QAAQ,OAAO,OAAO,SAAQ,UAAU,MAAM,mBAAmB,KAAA,IAAY,CAAC,IAAI,CAAC,MAAM,cAAc,CAAE;EAC/G,KAAK,cAAc,OAAO,eAAe,MAAM,SAAS,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI;EACjF,IAAI,CAAC,OAAO,SAAS,KAAK,WAAW,KAAK,KAAK,eAAe,GAC5D,MAAM,IAAI,MAAM,oEAAoE;EAEtF,KAAK,gBAAgB,OAAO,gBAAgB;EAC5C,K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} from '@mastra/connect';
|
|
2
|
+
import type { IntegrationContext } from '../../base.js';
|
|
3
|
+
import type { PlatformConnectBinding } from './connect-binding.js';
|
|
4
|
+
/** A provider event for one of an integration's connections. */
|
|
5
|
+
export interface PlatformConnectEventDelivery extends ConnectEvent {
|
|
6
|
+
/** `sourceEventId ?? id`: the provider's delivery id when known, else the event id. Prefix it per integration. */
|
|
7
|
+
dedupeKey: string;
|
|
8
|
+
}
|
|
9
|
+
/** How one integration receives its connections' provider events. */
|
|
10
|
+
export interface PlatformConnectEventRoute {
|
|
11
|
+
/** The integration's binding: its connections are the ones whose events it receives. */
|
|
12
|
+
binding: PlatformConnectBinding;
|
|
13
|
+
/** Handles one event. Must be idempotent: delivery is at-least-once. */
|
|
14
|
+
handle(event: PlatformConnectEventDelivery): Promise<void>;
|
|
15
|
+
/** Asks the integration to reconcile once, to cover events that may have been missed. */
|
|
16
|
+
reconcile(): void;
|
|
17
|
+
/**
|
|
18
|
+
* The provider keys whose connections send events the integration handles.
|
|
19
|
+
* Defaults to every provider key of the binding.
|
|
20
|
+
*/
|
|
21
|
+
eventProviderKeys?: readonly string[];
|
|
22
|
+
/** How often the integration wants its connections' events read. The poller reads at the shortest asked for. */
|
|
23
|
+
pollIntervalMs?: number;
|
|
24
|
+
}
|
|
25
|
+
/** An integration that may receive its connections' provider events. */
|
|
26
|
+
export interface PlatformConnectEventSource {
|
|
27
|
+
/** The integration's route, or null when it takes no events in this context. */
|
|
28
|
+
connectEventRoute(ctx: IntegrationContext): PlatformConnectEventRoute | null;
|
|
29
|
+
}
|
|
30
|
+
export declare function isPlatformConnectEventSource(value: unknown): value is PlatformConnectEventSource;
|
|
31
|
+
//# sourceMappingURL=connect-events.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-events.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/foundation/connect-events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEpD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAEnE,gEAAgE;AAChE,MAAM,WAAW,4BAA6B,SAAQ,YAAY;IAChE,kHAAkH;IAClH,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,qEAAqE;AACrE,MAAM,WAAW,yBAAyB;IACxC,wFAAwF;IACxF,OAAO,EAAE,sBAAsB,CAAC;IAChC,wEAAwE;IACxE,MAAM,CAAC,KAAK,EAAE,4BAA4B,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3D,yFAAyF;IACzF,SAAS,IAAI,IAAI,CAAC;IAClB;;;OAGG;IACH,iBAAiB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,gHAAgH;IAChH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,wEAAwE;AACxE,MAAM,WAAW,0BAA0B;IACzC,gFAAgF;IAChF,iBAAiB,CAAC,GAAG,EAAE,kBAAkB,GAAG,yBAAyB,GAAG,IAAI,CAAC;CAC9E;AAED,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,0BAA0B,CAMhG"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// src/integrations/platform/foundation/connect-events.ts
|
|
2
|
+
function isPlatformConnectEventSource(value) {
|
|
3
|
+
return typeof value === "object" && value !== null && typeof value.connectEventRoute === "function";
|
|
4
|
+
}
|
|
5
|
+
export { isPlatformConnectEventSource };
|
|
6
|
+
|
|
7
|
+
//# sourceMappingURL=connect-events.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-events.js","names":[],"sources":["../../../../src/integrations/platform/foundation/connect-events.ts"],"sourcesContent":["import type { ConnectEvent } from '@mastra/connect';\n\nimport type { IntegrationContext } from '../../base.js';\nimport type { PlatformConnectBinding } from './connect-binding.js';\n\n/** A provider event for one of an integration's connections. */\nexport interface PlatformConnectEventDelivery extends ConnectEvent {\n /** `sourceEventId ?? id`: the provider's delivery id when known, else the event id. Prefix it per integration. */\n dedupeKey: string;\n}\n\n/** How one integration receives its connections' provider events. */\nexport interface PlatformConnectEventRoute {\n /** The integration's binding: its connections are the ones whose events it receives. */\n binding: PlatformConnectBinding;\n /** Handles one event. Must be idempotent: delivery is at-least-once. */\n handle(event: PlatformConnectEventDelivery): Promise<void>;\n /** Asks the integration to reconcile once, to cover events that may have been missed. */\n reconcile(): void;\n /**\n * The provider keys whose connections send events the integration handles.\n * Defaults to every provider key of the binding.\n */\n eventProviderKeys?: readonly string[];\n /** How often the integration wants its connections' events read. The poller reads at the shortest asked for. */\n pollIntervalMs?: number;\n}\n\n/** An integration that may receive its connections' provider events. */\nexport interface PlatformConnectEventSource {\n /** The integration's route, or null when it takes no events in this context. */\n connectEventRoute(ctx: IntegrationContext): PlatformConnectEventRoute | null;\n}\n\nexport function isPlatformConnectEventSource(value: unknown): value is PlatformConnectEventSource {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { connectEventRoute?: unknown }).connectEventRoute === 'function'\n );\n}\n"],"mappings":";AAkCA,SAAgB,6BAA6B,OAAqD;CAChG,OACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAA0C,sBAAsB;AAE5E"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { DEFAULT_CONNECTION_CACHE_TTL_MS, PlatformConnectBinding, PlatformConnectionNotConnectedError, isPlatformNeedsReauth, } from './connect-binding.js';
|
|
2
|
+
export type { LinkOrgConnectionsResult, NeedsLinkingEntry, PlatformConnectBindingOptions, PlatformConnection, } from './connect-binding.js';
|
|
3
|
+
export { DEFAULT_PLATFORM_RECONCILE_INTERVAL_MS, PlatformConnectIntegration } from './integration.js';
|
|
4
|
+
export type { PlatformConnectIntegrationOptions, PlatformConnectProvider } from './integration.js';
|
|
5
|
+
export { PlatformIntakeCapability } from './intake.js';
|
|
6
|
+
export { PLATFORM_CONNECT_EVENT_POLLER_STORAGE_ID, PlatformConnectEventPoller } from './connect-event-poller.js';
|
|
7
|
+
export type { PlatformConnectEventPollerConfig, PlatformConnectEventPollerStorage } from './connect-event-poller.js';
|
|
8
|
+
export { isPlatformConnectEventSource } from './connect-events.js';
|
|
9
|
+
export type { PlatformConnectEventDelivery, PlatformConnectEventRoute, PlatformConnectEventSource, } from './connect-events.js';
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/foundation/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAC/B,sBAAsB,EACtB,mCAAmC,EACnC,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EACV,wBAAwB,EACxB,iBAAiB,EACjB,6BAA6B,EAC7B,kBAAkB,GACnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,sCAAsC,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AACtG,YAAY,EAAE,iCAAiC,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AACnG,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EAAE,wCAAwC,EAAE,0BAA0B,EAAE,MAAM,2BAA2B,CAAC;AACjH,YAAY,EAAE,gCAAgC,EAAE,iCAAiC,EAAE,MAAM,2BAA2B,CAAC;AACrH,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AACnE,YAAY,EACV,4BAA4B,EAC5B,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,qBAAqB,CAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { DEFAULT_CONNECTION_CACHE_TTL_MS, PlatformConnectBinding, PlatformConnectionNotConnectedError, isPlatformNeedsReauth } from "./connect-binding.js";
|
|
2
|
+
import { DEFAULT_PLATFORM_RECONCILE_INTERVAL_MS, PlatformConnectIntegration } from "./integration.js";
|
|
3
|
+
import { PlatformIntakeCapability } from "./intake.js";
|
|
4
|
+
import { PLATFORM_CONNECT_EVENT_POLLER_STORAGE_ID, PlatformConnectEventPoller } from "./connect-event-poller.js";
|
|
5
|
+
import { isPlatformConnectEventSource } from "./connect-events.js";
|
|
6
|
+
export { DEFAULT_CONNECTION_CACHE_TTL_MS, DEFAULT_PLATFORM_RECONCILE_INTERVAL_MS, PLATFORM_CONNECT_EVENT_POLLER_STORAGE_ID, PlatformConnectBinding, PlatformConnectEventPoller, PlatformConnectIntegration, PlatformConnectionNotConnectedError, PlatformIntakeCapability, isPlatformConnectEventSource, isPlatformNeedsReauth };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { IntegrationConnection } from '../../../capabilities/connection.js';
|
|
2
|
+
import type { CreateIntakeCommentInput, CreatedIntakeComment, GetIntakeIssueInput, Intake, IntakeIssue, IntakeIssueDetail, IntakeIssuePage, IntakeItemPage, IntakeSource, ListIntakeIssuesInput, ListIntakeItemsInput, ListIntakeSourcesInput, ResolveIntakeDispatchInput, ResolvedIntakeDispatch, UpdateIntakeIssueInput } from '../../../capabilities/intake.js';
|
|
3
|
+
import type { PlatformConnection } from './connect-binding.js';
|
|
4
|
+
import type { PlatformConnectIntegration } from './integration.js';
|
|
5
|
+
/**
|
|
6
|
+
* Base class for the intake of a {@link PlatformConnectIntegration}. It owns
|
|
7
|
+
* what every Platform intake shares: the connection token that carries a
|
|
8
|
+
* Platform connection id through intake storage, and resolving that id to an
|
|
9
|
+
* active connection. Source ids, paging, dispatch resolution and issue
|
|
10
|
+
* mapping are provider-specific and stay in the subclass.
|
|
11
|
+
*
|
|
12
|
+
* The constructor only stores its arguments, so a subclass can be created in
|
|
13
|
+
* a field initializer of its integration before the integration's
|
|
14
|
+
* constructor body has run.
|
|
15
|
+
*/
|
|
16
|
+
export declare abstract class PlatformIntakeCapability implements Intake {
|
|
17
|
+
#private;
|
|
18
|
+
constructor(integration: PlatformConnectIntegration, connectionTokenPrefix: string);
|
|
19
|
+
/** The intake connection that names a Platform connection. */
|
|
20
|
+
connectionCredential(connectionId: string): IntegrationConnection;
|
|
21
|
+
/** The Platform connection id an intake connection names, if it names one. */
|
|
22
|
+
connectionIdOf(connection: IntegrationConnection): string | null;
|
|
23
|
+
/**
|
|
24
|
+
* The active connection with this id. A caller-supplied id is only a claim,
|
|
25
|
+
* so anything that isn't an active connection of the integration throws
|
|
26
|
+
* {@link notConnectedError} before a proxy request is made with it.
|
|
27
|
+
*/
|
|
28
|
+
protected activeConnectionById(connectionId: string): Promise<PlatformConnection>;
|
|
29
|
+
/** The provider's error for a connection that is missing or needs reauthentication. */
|
|
30
|
+
protected abstract notConnectedError(connectionId: string): Error;
|
|
31
|
+
abstract resolveIntakeDispatch(input: ResolveIntakeDispatchInput): Promise<ResolvedIntakeDispatch | null>;
|
|
32
|
+
abstract listSources(input: ListIntakeSourcesInput): Promise<IntakeSource[]>;
|
|
33
|
+
abstract listItems(input: ListIntakeItemsInput): Promise<IntakeItemPage>;
|
|
34
|
+
abstract listIssues(input: ListIntakeIssuesInput): Promise<IntakeIssuePage>;
|
|
35
|
+
abstract getIssue(input: GetIntakeIssueInput): Promise<IntakeIssueDetail | null>;
|
|
36
|
+
abstract createComment(input: CreateIntakeCommentInput): Promise<CreatedIntakeComment | null>;
|
|
37
|
+
abstract updateIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null>;
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=intake.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intake.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/foundation/intake.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qCAAqC,CAAC;AACjF,OAAO,KAAK,EACV,wBAAwB,EACxB,oBAAoB,EACpB,mBAAmB,EACnB,MAAM,EACN,WA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CAAC,CAAC;IACjF,QAAQ,CAAC,aAAa,CAAC,KAAK,EAAE,wBAAwB,GAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAAC;IAC9F,QAAQ,CAAC,WAAW,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;CAClF"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// src/integrations/platform/foundation/intake.ts
|
|
2
|
+
/**
|
|
3
|
+
* Base class for the intake of a {@link PlatformConnectIntegration}. It owns
|
|
4
|
+
* what every Platform intake shares: the connection token that carries a
|
|
5
|
+
* Platform connection id through intake storage, and resolving that id to an
|
|
6
|
+
* active connection. Source ids, paging, dispatch resolution and issue
|
|
7
|
+
* mapping are provider-specific and stay in the subclass.
|
|
8
|
+
*
|
|
9
|
+
* The constructor only stores its arguments, so a subclass can be created in
|
|
10
|
+
* a field initializer of its integration before the integration's
|
|
11
|
+
* constructor body has run.
|
|
12
|
+
*/
|
|
13
|
+
var PlatformIntakeCapability = class {
|
|
14
|
+
#integration;
|
|
15
|
+
#connectionTokenPrefix;
|
|
16
|
+
constructor(integration, connectionTokenPrefix) {
|
|
17
|
+
this.#integration = integration;
|
|
18
|
+
this.#connectionTokenPrefix = connectionTokenPrefix;
|
|
19
|
+
}
|
|
20
|
+
/** The intake connection that names a Platform connection. */
|
|
21
|
+
connectionCredential(connectionId) {
|
|
22
|
+
return {
|
|
23
|
+
type: "oauth",
|
|
24
|
+
accessToken: `${this.#connectionTokenPrefix}${connectionId}`
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** The Platform connection id an intake connection names, if it names one. */
|
|
28
|
+
connectionIdOf(connection) {
|
|
29
|
+
if (connection.type !== "oauth" || !connection.accessToken.startsWith(this.#connectionTokenPrefix)) return null;
|
|
30
|
+
return connection.accessToken.slice(this.#connectionTokenPrefix.length) || null;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The active connection with this id. A caller-supplied id is only a claim,
|
|
34
|
+
* so anything that isn't an active connection of the integration throws
|
|
35
|
+
* {@link notConnectedError} before a proxy request is made with it.
|
|
36
|
+
*/
|
|
37
|
+
async activeConnectionById(connectionId) {
|
|
38
|
+
const connection = (await this.#integration.listConnections()).find((candidate) => candidate.id === connectionId && candidate.status === "active");
|
|
39
|
+
if (!connection) throw this.notConnectedError(connectionId);
|
|
40
|
+
return connection;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
export { PlatformIntakeCapability };
|
|
44
|
+
|
|
45
|
+
//# sourceMappingURL=intake.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intake.js","names":[],"sources":["../../../../src/integrations/platform/foundation/intake.ts"],"sourcesContent":["import type { IntegrationConnection } from '../../../capabilities/connection.js';\nimport type {\n CreateIntakeCommentInput,\n CreatedIntakeComment,\n GetIntakeIssueInput,\n Intake,\n IntakeIssue,\n IntakeIssueDetail,\n IntakeIssuePage,\n IntakeItemPage,\n IntakeSource,\n ListIntakeIssuesInput,\n ListIntakeItemsInput,\n ListIntakeSourcesInput,\n ResolveIntakeDispatchInput,\n ResolvedIntakeDispatch,\n UpdateIntakeIssueInput,\n} from '../../../capabilities/intake.js';\nimport type { PlatformConnection } from './connect-binding.js';\nimport type { PlatformConnectIntegration } from './integration.js';\n\n/**\n * Base class for the intake of a {@link PlatformConnectIntegration}. It owns\n * what every Platform intake shares: the connection token that carries a\n * Platform connection id through intake storage, and resolving that id to an\n * active connection. Source ids, paging, dispatch resolution and issue\n * mapping are provider-specific and stay in the subclass.\n *\n * The constructor only stores its arguments, so a subclass can be created in\n * a field initializer of its integration before the integration's\n * constructor body has run.\n */\nexport abstract class PlatformIntakeCapability implements Intake {\n readonly #integration: PlatformConnectIntegration;\n readonly #connectionTokenPrefix: string;\n\n constructor(integration: PlatformConnectIntegration, connectionTokenPrefix: string) {\n this.#integration = integration;\n this.#connectionTokenPrefix = connectionTokenPrefix;\n }\n\n /** The intake connection that names a Platform connection. */\n connectionCredential(connectionId: string): IntegrationConnection {\n return { type: 'oauth', accessToken: `${this.#connectionTokenPrefix}${connectionId}` };\n }\n\n /** The Platform connection id an intake connection names, if it names one. */\n connectionIdOf(connection: IntegrationConnection): string | null {\n if (connection.type !== 'oauth' || !connection.accessToken.startsWith(this.#connectionTokenPrefix)) return null;\n return connection.accessToken.slice(this.#connectionTokenPrefix.length) || null;\n }\n\n /**\n * The active connection with this id. A caller-supplied id is only a claim,\n * so anything that isn't an active connection of the integration throws\n * {@link notConnectedError} before a proxy request is made with it.\n */\n protected async activeConnectionById(connectionId: string): Promise<PlatformConnection> {\n const connection = (await this.#integration.listConnections()).find(\n candidate => candidate.id === connectionId && candidate.status === 'active',\n );\n if (!connection) throw this.notConnectedError(connectionId);\n return connection;\n }\n\n /** The provider's error for a connection that is missing or needs reauthentication. */\n protected abstract notConnectedError(connectionId: string): Error;\n\n abstract resolveIntakeDispatch(input: ResolveIntakeDispatchInput): Promise<ResolvedIntakeDispatch | null>;\n abstract listSources(input: ListIntakeSourcesInput): Promise<IntakeSource[]>;\n abstract listItems(input: ListIntakeItemsInput): Promise<IntakeItemPage>;\n abstract listIssues(input: ListIntakeIssuesInput): Promise<IntakeIssuePage>;\n abstract getIssue(input: GetIntakeIssueInput): Promise<IntakeIssueDetail | null>;\n abstract createComment(input: CreateIntakeCommentInput): Promise<CreatedIntakeComment | null>;\n abstract updateIssue(input: UpdateIntakeIssueInput): Promise<IntakeIssue | null>;\n}\n"],"mappings":";;;;;;;;;;;;AAgCA,IAAsB,2BAAtB,MAAiE;CAC/D;CACA;CAEA,YAAY,aAAyC,uBAA+B;EAClF,KAAK,eAAe;EACpB,KAAK,yBAAyB;CAChC;;CAGA,qBAAqB,cAA6C;EAChE,OAAO;GAAE,MAAM;GAAS,aAAa,GAAG,KAAK,yBAAyB;EAAe;CACvF;;CAGA,eAAe,YAAkD;EAC/D,IAAI,WAAW,SAAS,WAAW,CAAC,WAAW,YAAY,WAAW,KAAK,sBAAsB,GAAG,OAAO;EAC3G,OAAO,WAAW,YAAY,MAAM,KAAK,uBAAuB,MAAM,KAAK;CAC7E;;;;;;CAOA,MAAgB,qBAAqB,cAAmD;EACtF,MAAM,cAAc,MAAM,KAAK,aAAa,gBAAgB,EAAA,CAAG,MAC7D,cAAa,UAAU,OAAO,gBAAgB,UAAU,WAAW,QACrE;EACA,IAAI,CAAC,YAAY,MAAM,KAAK,kBAAkB,YAAY;EAC1D,OAAO;CACT;AAYF"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { ConnectClient, ProxyRequestOptions } from '@mastra/connect';
|
|
2
|
+
import type { ApiRoute } from '@mastra/core/server';
|
|
3
|
+
import type { MastraWorker } from '@mastra/core/worker';
|
|
4
|
+
import type { FactoryIntegration, IntegrationContext } from '../../base.js';
|
|
5
|
+
import type { IssueReconciler } from '../../issue-reconciler.js';
|
|
6
|
+
import type { PlatformConnectProviderRegistration, PlatformConnectProviderSource } from '../connect/routes.js';
|
|
7
|
+
import type { PlatformConnectOption } from '../platform-connect.js';
|
|
8
|
+
import { PlatformConnectBinding } from './connect-binding.js';
|
|
9
|
+
import type { LinkOrgConnectionsResult, NeedsLinkingEntry, PlatformConnection } from './connect-binding.js';
|
|
10
|
+
/** Reconciles run hourly unless an integration says otherwise. */
|
|
11
|
+
export declare const DEFAULT_PLATFORM_RECONCILE_INTERVAL_MS: number;
|
|
12
|
+
/** A provider the integration registers with the platform connect routes. */
|
|
13
|
+
export interface PlatformConnectProvider {
|
|
14
|
+
/** SPA-facing provider slug, the `:provider` path segment. */
|
|
15
|
+
provider: string;
|
|
16
|
+
/** Platform integration id used to mint connect sessions. */
|
|
17
|
+
integrationId: string;
|
|
18
|
+
/** Connection `integrationId` variants that belong to this provider. Defaults to `[integrationId]`. */
|
|
19
|
+
connectionIntegrationIds?: readonly string[];
|
|
20
|
+
}
|
|
21
|
+
export interface PlatformConnectIntegrationOptions {
|
|
22
|
+
/** The integration's id, also its reconcile worker's name prefix. */
|
|
23
|
+
id: string;
|
|
24
|
+
/** Connect integration ids (provider keys) the integration owns. */
|
|
25
|
+
providerKeys: readonly string[];
|
|
26
|
+
connect?: PlatformConnectOption;
|
|
27
|
+
/** Link the org's global connections for `providerKeys` to the Factory project at boot. */
|
|
28
|
+
linkOrgConnectionsAtBoot?: boolean;
|
|
29
|
+
/** Providers the integration exposes through the platform connect routes. */
|
|
30
|
+
connectProviders?: readonly PlatformConnectProvider[];
|
|
31
|
+
/** Narrows the provider's connections further, e.g. to one configured connection id. */
|
|
32
|
+
connectionFilter?: (connection: PlatformConnection) => boolean;
|
|
33
|
+
/**
|
|
34
|
+
* The reconcile interval from the integration's constructor option or
|
|
35
|
+
* environment variable. Takes precedence over `reconcileDefaultIntervalMs`.
|
|
36
|
+
*/
|
|
37
|
+
reconcileIntervalMs?: number;
|
|
38
|
+
/** The integration's own default reconcile interval, in place of hourly. */
|
|
39
|
+
reconcileDefaultIntervalMs?: number;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Base class for a Factory integration whose provider is reached through
|
|
43
|
+
* Mastra Connect. It owns the Connect client, project-scoped connection
|
|
44
|
+
* listing, the connection proxy, linking existing org connections to the
|
|
45
|
+
* Factory project, the provider's connect routes and the reconcile worker.
|
|
46
|
+
* Capabilities (`intake`, `versionControl`) are composed in by subclasses.
|
|
47
|
+
*/
|
|
48
|
+
export declare abstract class PlatformConnectIntegration implements FactoryIntegration, PlatformConnectProviderSource {
|
|
49
|
+
#private;
|
|
50
|
+
readonly id: string;
|
|
51
|
+
readonly binding: PlatformConnectBinding;
|
|
52
|
+
constructor(options: PlatformConnectIntegrationOptions);
|
|
53
|
+
get connect(): ConnectClient;
|
|
54
|
+
get providerKeys(): readonly string[];
|
|
55
|
+
/** How often the reconcile worker runs. */
|
|
56
|
+
get reconcileIntervalMs(): number;
|
|
57
|
+
/** The project's `active` and `needs_reauth` connections for the integration's provider keys. */
|
|
58
|
+
listConnections(options?: {
|
|
59
|
+
fresh?: boolean;
|
|
60
|
+
}): Promise<PlatformConnection[]>;
|
|
61
|
+
/** Active connections, sorted by id. */
|
|
62
|
+
activeConnections(): Promise<PlatformConnection[]>;
|
|
63
|
+
connectionFor(providerKey: string, predicate?: (connection: PlatformConnection) => boolean): Promise<PlatformConnection | null>;
|
|
64
|
+
invalidateConnections(): void;
|
|
65
|
+
proxy(connectionId: string, request: ProxyRequestOptions): Promise<unknown>;
|
|
66
|
+
linkOrgConnections(): Promise<LinkOrgConnectionsResult>;
|
|
67
|
+
get needsLinking(): NeedsLinkingEntry[];
|
|
68
|
+
platformConnectProviders(): PlatformConnectProviderRegistration[];
|
|
69
|
+
/**
|
|
70
|
+
* The reconciler the reconcile worker runs, or null when the integration
|
|
71
|
+
* has nothing to reconcile in this context. Integrations without a
|
|
72
|
+
* reconcile return null.
|
|
73
|
+
*/
|
|
74
|
+
protected reconcile(_ctx: IntegrationContext): IssueReconciler | null;
|
|
75
|
+
/**
|
|
76
|
+
* Starts boot linking (non-blocking) and returns the reconcile worker, when
|
|
77
|
+
* the integration reconciles. Linking that adds a connection triggers one
|
|
78
|
+
* extra reconcile.
|
|
79
|
+
*/
|
|
80
|
+
workers(ctx: IntegrationContext): MastraWorker[];
|
|
81
|
+
abstract routes(ctx: IntegrationContext): ApiRoute[];
|
|
82
|
+
diagnostics(): Record<string, unknown>;
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=integration.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/foundation/integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,KAAK,EAAE,kBAAkB,EA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