@ever-works/linear-connector-plugin 1.0.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 ADDED
@@ -0,0 +1,41 @@
1
+ # @ever-works/linear-connector-plugin
2
+
3
+ First-party **Linear connector** for the Ever Works platform (Wave 8), built on
4
+ the official [`@linear/sdk`](https://www.npmjs.com/package/@linear/sdk).
5
+
6
+ Capabilities: `connector`, `connector-linear`, `event-source`.
7
+
8
+ ## What it does
9
+
10
+ - **Outbound** — `send()` posts a comment on a Linear issue
11
+ (`targetConfig.issueId` / `defaultIssueId`), idempotent on `messageRef`.
12
+ - **Event source** — `pullEvents()` sweeps issues (created/updated) and then
13
+ comments since the platform watermark, normalized into
14
+ `IngestedEventEnvelope`s (`linear.issue` / `linear.comment`) for the
15
+ event-ingest spine. Each envelope carries the issue URL as `sourceUrl` so
16
+ Memory/Activity rows link back to the origin.
17
+ - **Opt-in historical backfill** — `backfillDays` (default `0` = off, max 90)
18
+ widens the FIRST pull's window only, bounded to
19
+ `LINEAR_BACKFILL_MAX_PAGES` pages per phase.
20
+
21
+ - **Historical backfill (`backfill()` capability method)** — the optional
22
+ `backfill()` method on the `event-source` capability runs the same sweep
23
+ out-of-band over an EXPLICIT window, so history can be imported at any time
24
+ instead of only as a side effect of the first pull's `backfillDays`. One call
25
+ fetches one page and hands back a cursor, so the per-phase page bound still
26
+ applies. Re-delivery is free — the ingest pipeline dedupes on
27
+ `(source, sourceEventId)`.
28
+
29
+ ## Settings
30
+
31
+ | Key | Notes |
32
+ | ---------------- | ------------------------------------------------------------ |
33
+ | `apiKey` | Linear API key (`lin_api_…`) — secret, env `LINEAR_API_KEY`. |
34
+ | `teamIds` | Optional comma-separated team-id filter for the pull. |
35
+ | `backfillDays` | Opt-in first-pull history window (0 = off, max 90). |
36
+ | `defaultIssueId` | Default issue for outbound comments. |
37
+
38
+ ## Testing
39
+
40
+ Hermetic Vitest suite (`pnpm test`) — the SDK client is stubbed through the
41
+ `createClient` seam; no network calls.
package/dist/index.cjs ADDED
@@ -0,0 +1,417 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var crypto = require('crypto');
6
+ var sdk = require('@linear/sdk');
7
+ require('@ever-works/contracts');
8
+
9
+ // src/linear-connector-plugin.ts
10
+ var EVENT_SOURCE_BACKFILL_MAX_DAYS = 90;
11
+ function clampEventSourceBackfillDays(value, max = EVENT_SOURCE_BACKFILL_MAX_DAYS) {
12
+ const num = typeof value === "number" ? value : Number(value);
13
+ if (!Number.isFinite(num) || num <= 0) return 0;
14
+ return Math.min(Math.floor(num), max);
15
+ }
16
+ var EventSourceNotConfiguredError = class extends Error {
17
+ constructor(message) {
18
+ super(message ?? "Event-source plugin is not configured in this runtime.");
19
+ this.name = "EventSourceNotConfiguredError";
20
+ }
21
+ };
22
+ var PLUGIN_CAPABILITIES = {
23
+ // Connectors ("Connector fabric") — first-party BIDIRECTIONAL
24
+ // communication-channel plugins. Each connector declares `CONNECTOR`
25
+ // (umbrella, for discovery/grouping) plus its `CONNECTOR_<provider>`
26
+ // constant. Superset of the outbound-only notification channels; see
27
+ // `capabilities/connector.interface.ts`.
28
+ CONNECTOR: "connector",
29
+ CONNECTOR_LINEAR: "connector-linear",
30
+ // Event-ingest spine (Wave 6) — plugins that pull/push normalized
31
+ // external events into the platform ingest pipeline. See
32
+ // capabilities/event-source.interface.ts.
33
+ EVENT_SOURCE: "event-source"};
34
+
35
+ // src/linear-connector-plugin.ts
36
+ var LINEAR_EVENT_TEXT_MAX_CHARS = 4e3;
37
+ var LINEAR_PULL_PAGE_SIZE = 50;
38
+ var LINEAR_BACKFILL_MAX_PAGES = 10;
39
+ function clampBackfillDays(value) {
40
+ return clampEventSourceBackfillDays(value);
41
+ }
42
+ function truncateText(text) {
43
+ return text.length > LINEAR_EVENT_TEXT_MAX_CHARS ? text.slice(0, LINEAR_EVENT_TEXT_MAX_CHARS) : text;
44
+ }
45
+ function teamKeyFromIdentifier(identifier) {
46
+ if (!identifier) return void 0;
47
+ const match = /^([A-Za-z0-9]+)-\d+$/.exec(identifier.trim());
48
+ return match ? match[1] : void 0;
49
+ }
50
+ function resolveTeamIds(settings) {
51
+ const raw = settings?.teamIds;
52
+ if (typeof raw === "string" && raw.trim().length > 0) {
53
+ return raw.split(/[\s,]+/).map((t) => t.trim()).filter((t) => t.length > 0);
54
+ }
55
+ return [];
56
+ }
57
+ function linearErrorMessage(err) {
58
+ const e = err;
59
+ return e.message ?? e.type ?? "unknown error";
60
+ }
61
+ function toIso(value) {
62
+ if (value instanceof Date) return value.toISOString();
63
+ if (typeof value === "string") {
64
+ const ms = Date.parse(value);
65
+ if (Number.isFinite(ms)) return new Date(ms).toISOString();
66
+ }
67
+ return (/* @__PURE__ */ new Date(0)).toISOString();
68
+ }
69
+ function parsePullCursor(cursor) {
70
+ if (!cursor) return void 0;
71
+ try {
72
+ const parsed = JSON.parse(cursor);
73
+ if (parsed && (parsed.p === "issues" || parsed.p === "comments") && typeof parsed.s === "string") {
74
+ return parsed;
75
+ }
76
+ } catch {
77
+ }
78
+ return void 0;
79
+ }
80
+ function resolveApiKey(config, options) {
81
+ const candidates = [config.apiKey, options.settings?.apiKey];
82
+ for (const c of candidates) {
83
+ if (typeof c === "string" && c.length > 0) return c;
84
+ }
85
+ return void 0;
86
+ }
87
+ function resolveIssueId(config, options) {
88
+ const candidates = [config.issueId, config.defaultIssueId, options.settings?.defaultIssueId];
89
+ for (const c of candidates) {
90
+ if (typeof c === "string" && c.length > 0) return c;
91
+ }
92
+ throw new Error("linear-connector: an issue id is required (targetConfig.issueId or defaultIssueId)");
93
+ }
94
+ var LinearConnectorPlugin = class {
95
+ constructor() {
96
+ this.id = "linear-connector";
97
+ this.name = "Linear Connector";
98
+ this.version = "1.0.0";
99
+ this.category = "connector";
100
+ this.capabilities = [
101
+ PLUGIN_CAPABILITIES.CONNECTOR,
102
+ PLUGIN_CAPABILITIES.CONNECTOR_LINEAR,
103
+ PLUGIN_CAPABILITIES.EVENT_SOURCE
104
+ ];
105
+ this.providerName = "linear";
106
+ this.connector = {
107
+ direction: "outbound",
108
+ transport: "poll",
109
+ flags: {
110
+ outboundMessage: true,
111
+ outboundRecord: false,
112
+ inbound: false,
113
+ reply: false,
114
+ pairing: false,
115
+ richOutbound: false
116
+ }
117
+ };
118
+ this.settingsSchema = {
119
+ type: "object",
120
+ required: ["apiKey"],
121
+ properties: {
122
+ apiKey: {
123
+ type: "string",
124
+ title: "Linear API key (lin_api_\u2026)",
125
+ "x-secret": true,
126
+ "x-envVar": "LINEAR_API_KEY"
127
+ },
128
+ teamIds: {
129
+ type: "string",
130
+ title: "Team ids to ingest events from (comma-separated; all teams when empty)"
131
+ },
132
+ backfillDays: {
133
+ type: "number",
134
+ title: "Historical backfill window in days on first pull (0 = off, max 90)",
135
+ default: 0,
136
+ minimum: 0,
137
+ maximum: 90
138
+ },
139
+ defaultIssueId: {
140
+ type: "string",
141
+ title: "Default issue id for outbound comments"
142
+ }
143
+ }
144
+ };
145
+ this.idempotencyCache = /* @__PURE__ */ new Map();
146
+ }
147
+ async onLoad() {
148
+ }
149
+ async onUnload() {
150
+ this.idempotencyCache.clear();
151
+ }
152
+ /** Testable seam — specs stub this; production uses the real SDK. */
153
+ createClient(apiKey) {
154
+ return new sdk.LinearClient({ apiKey });
155
+ }
156
+ async verifyConnection(config, options) {
157
+ const apiKey = resolveApiKey(config, options);
158
+ if (!apiKey) {
159
+ return { valid: false, message: "apiKey is required" };
160
+ }
161
+ try {
162
+ const viewer = await this.createClient(apiKey).viewer;
163
+ return {
164
+ valid: true,
165
+ details: {
166
+ viewerId: viewer?.id,
167
+ viewerName: viewer?.name,
168
+ ...viewer?.email ? { email: viewer.email } : {}
169
+ }
170
+ };
171
+ } catch (err) {
172
+ return { valid: false, message: `Linear viewer lookup failed: ${linearErrorMessage(err)}` };
173
+ }
174
+ }
175
+ /** Outbound leg — create a comment on a Linear issue. */
176
+ async send(payload, options) {
177
+ const config = payload.target ?? options.target ?? {};
178
+ const apiKey = resolveApiKey(config, options);
179
+ if (!apiKey) {
180
+ throw new Error("linear-connector: an API key is required (targetConfig.apiKey or settings.apiKey)");
181
+ }
182
+ const issueId = resolveIssueId(config, options);
183
+ const cacheKey = `${options.connectorId ?? ""}\0${issueId}\0${payload.messageRef}`;
184
+ const cached = this.idempotencyCache.get(cacheKey);
185
+ if (cached) return cached;
186
+ let commentId;
187
+ try {
188
+ const res = await this.createClient(apiKey).createComment({ issueId, body: payload.text });
189
+ const comment = res.comment ? await res.comment : void 0;
190
+ commentId = typeof comment?.id === "string" ? comment.id : void 0;
191
+ } catch (err) {
192
+ throw new Error(`Linear createComment failed: ${linearErrorMessage(err)}`);
193
+ }
194
+ const result = {
195
+ provider: this.id,
196
+ providerMessageId: commentId ?? `linear-${payload.messageRef}`,
197
+ deliveredAt: /* @__PURE__ */ new Date()
198
+ };
199
+ this.idempotencyCache.set(cacheKey, result);
200
+ if (this.idempotencyCache.size > 500) {
201
+ const firstKey = this.idempotencyCache.keys().next().value;
202
+ if (firstKey) this.idempotencyCache.delete(firstKey);
203
+ }
204
+ return result;
205
+ }
206
+ // ── Event source (pull) ─────────────────────────────────────────────
207
+ /**
208
+ * Pull one page of the current sweep phase (issues → comments)
209
+ * since the effective watermark, normalized to envelopes. The
210
+ * returned cursor resumes the same phase (SDK page cursor) or
211
+ * advances to the next; no cursor means the sweep is done.
212
+ *
213
+ * First pull (epoch/absent watermark, no cursor): the window is
214
+ * `now - backfillDays` when the opt-in backfill is on, otherwise
215
+ * `now` — history stays untouched unless the user asked for it.
216
+ */
217
+ async pullEvents(input) {
218
+ const apiKey = input.settings?.apiKey;
219
+ if (typeof apiKey !== "string" || apiKey.length === 0) {
220
+ throw new EventSourceNotConfiguredError("linear-connector: settings.apiKey is required to pull events");
221
+ }
222
+ const cursor = parsePullCursor(input.cursor);
223
+ let phase;
224
+ let after;
225
+ let since;
226
+ let backfill;
227
+ let pagesUsed;
228
+ if (cursor) {
229
+ phase = cursor.p;
230
+ after = cursor.n;
231
+ since = cursor.s;
232
+ backfill = cursor.f === 1;
233
+ pagesUsed = cursor.b ?? 0;
234
+ } else {
235
+ const sinceMs = Date.parse(input.since);
236
+ const firstPull = !Number.isFinite(sinceMs) || sinceMs <= 0;
237
+ const backfillDays = clampBackfillDays(input.settings?.backfillDays);
238
+ if (firstPull) {
239
+ const start = backfillDays > 0 ? Date.now() - backfillDays * 864e5 : Date.now();
240
+ since = new Date(start).toISOString();
241
+ backfill = backfillDays > 0;
242
+ } else {
243
+ since = new Date(sinceMs).toISOString();
244
+ backfill = false;
245
+ }
246
+ phase = "issues";
247
+ after = void 0;
248
+ pagesUsed = 0;
249
+ }
250
+ const client = this.createClient(apiKey);
251
+ const teamIds = resolveTeamIds(input.settings);
252
+ const events = [];
253
+ let hasNextPage = false;
254
+ let endCursor;
255
+ if (phase === "issues") {
256
+ const page = await client.issues({
257
+ first: LINEAR_PULL_PAGE_SIZE,
258
+ ...after ? { after } : {},
259
+ filter: {
260
+ updatedAt: { gte: new Date(since) },
261
+ ...teamIds.length > 0 ? { team: { id: { in: teamIds } } } : {}
262
+ }
263
+ });
264
+ for (const issue of page.nodes ?? []) {
265
+ const envelope = this.normalizeIssue(issue, since);
266
+ if (envelope) events.push(envelope);
267
+ }
268
+ hasNextPage = page.pageInfo?.hasNextPage === true;
269
+ endCursor = page.pageInfo?.endCursor;
270
+ } else {
271
+ const page = await client.comments({
272
+ first: LINEAR_PULL_PAGE_SIZE,
273
+ ...after ? { after } : {},
274
+ filter: { updatedAt: { gte: new Date(since) } }
275
+ });
276
+ for (const comment of page.nodes ?? []) {
277
+ const envelope = await this.normalizeComment(comment);
278
+ if (envelope) events.push(envelope);
279
+ }
280
+ hasNextPage = page.pageInfo?.hasNextPage === true;
281
+ endCursor = page.pageInfo?.endCursor;
282
+ }
283
+ pagesUsed += 1;
284
+ const pageBudgetExhausted = backfill && pagesUsed >= LINEAR_BACKFILL_MAX_PAGES;
285
+ let next;
286
+ if (hasNextPage && endCursor && !pageBudgetExhausted) {
287
+ next = { p: phase, n: endCursor, s: since, ...backfill ? { f: 1 } : {}, b: pagesUsed };
288
+ } else if (phase === "issues") {
289
+ next = { p: "comments", s: since, ...backfill ? { f: 1 } : {}, b: 0 };
290
+ }
291
+ return next ? { events, nextCursor: JSON.stringify(next) } : { events };
292
+ }
293
+ /**
294
+ * Bounded HISTORICAL sweep from an explicit `since` — the
295
+ * capability's opt-in `backfill()` method.
296
+ *
297
+ * Before this method existed, history was reachable only as a side
298
+ * effect of the FIRST pull (`settings.backfillDays` widening the
299
+ * initial window), so a user who activated the connector without the
300
+ * setting could never go back and fetch it. `backfill()` runs the
301
+ * same two-phase sweep (issues → comments) out-of-band on a
302
+ * caller-chosen window, as many times as wanted — re-delivery is free
303
+ * because the ingest pipeline dedupes on `(source, sourceEventId)`.
304
+ *
305
+ * `until` is accepted for contract symmetry but NOT applied: the SDK
306
+ * filter bounds only the near end (`updatedAt >= since`). An
307
+ * over-wide window costs duplicate deliveries, which the pipeline
308
+ * drops — never wrong data.
309
+ *
310
+ * The per-phase page bound (`LINEAR_BACKFILL_MAX_PAGES`) applies here
311
+ * too: one call fetches ONE page and hands back a cursor, so a large
312
+ * workspace can never turn a backfill into an unbounded crawl.
313
+ */
314
+ async backfill(input) {
315
+ const sinceMs = Date.parse(input.since);
316
+ if (!Number.isFinite(sinceMs)) {
317
+ throw new EventSourceNotConfiguredError(
318
+ `linear-connector: backfill requires a valid ISO 8601 "since" (received ${JSON.stringify(input.since)})`
319
+ );
320
+ }
321
+ const cursor = input.cursor ?? JSON.stringify({
322
+ p: "issues",
323
+ s: new Date(sinceMs).toISOString(),
324
+ f: 1,
325
+ b: 0
326
+ });
327
+ const page = await this.pullEvents({
328
+ since: input.since,
329
+ cursor,
330
+ ...input.settings ? { settings: input.settings } : {}
331
+ });
332
+ return page.nextCursor ? { events: page.events, nextCursor: page.nextCursor } : { events: page.events, complete: true };
333
+ }
334
+ normalizeIssue(issue, since) {
335
+ if (!issue.id) return null;
336
+ const updatedAt = toIso(issue.updatedAt ?? issue.createdAt);
337
+ const createdAt = toIso(issue.createdAt);
338
+ const changeType = Date.parse(createdAt) >= Date.parse(since) ? "created" : "updated";
339
+ const teamKey = teamKeyFromIdentifier(issue.identifier);
340
+ return {
341
+ id: crypto.randomUUID(),
342
+ source: this.id,
343
+ sourceEventId: `${issue.id}:${updatedAt}`,
344
+ kind: "linear.issue",
345
+ occurredAt: updatedAt,
346
+ subject: {
347
+ type: "issue",
348
+ externalId: issue.id,
349
+ ...issue.title ? { title: issue.title } : {}
350
+ },
351
+ // Work routing: the team is the container an Ever Works Work
352
+ // maps onto. Issues with an unparseable identifier carry no
353
+ // hint and stay user-scoped.
354
+ ...teamKey ? { workHint: { kind: "tracker-team", externalId: teamKey } } : {},
355
+ ...issue.url ? { sourceUrl: issue.url } : {},
356
+ payload: {
357
+ issueId: issue.id,
358
+ ...issue.identifier ? { identifier: issue.identifier } : {},
359
+ ...issue.title ? { title: truncateText(issue.title) } : {},
360
+ ...issue.description ? { description: truncateText(issue.description) } : {},
361
+ changeType,
362
+ createdAt,
363
+ updatedAt
364
+ }
365
+ };
366
+ }
367
+ /**
368
+ * Normalize one comment → envelope. The parent issue is a lazy SDK
369
+ * fetch — awaited best-effort for the subject/sourceUrl; a failure
370
+ * degrades to the comment's own permalink.
371
+ */
372
+ async normalizeComment(comment) {
373
+ if (!comment.id) return null;
374
+ const updatedAt = toIso(comment.updatedAt ?? comment.createdAt);
375
+ let issue;
376
+ try {
377
+ issue = comment.issue ? await comment.issue : void 0;
378
+ } catch {
379
+ issue = void 0;
380
+ }
381
+ const sourceUrl = comment.url ?? issue?.url;
382
+ const teamKey = teamKeyFromIdentifier(issue?.identifier);
383
+ return {
384
+ id: crypto.randomUUID(),
385
+ source: this.id,
386
+ sourceEventId: `${comment.id}:${updatedAt}`,
387
+ kind: "linear.comment",
388
+ occurredAt: updatedAt,
389
+ subject: {
390
+ type: "issue",
391
+ externalId: issue?.id ?? "unknown",
392
+ ...issue?.title ? { title: issue.title } : {}
393
+ },
394
+ // Same team-as-container routing as issues; the parent-issue
395
+ // fetch is best-effort, so a failed one simply means no hint.
396
+ ...teamKey ? { workHint: { kind: "tracker-team", externalId: teamKey } } : {},
397
+ ...sourceUrl ? { sourceUrl } : {},
398
+ payload: {
399
+ commentId: comment.id,
400
+ ...issue?.id ? { issueId: issue.id } : {},
401
+ ...issue?.identifier ? { issueIdentifier: issue.identifier } : {},
402
+ ...comment.body ? { body: truncateText(comment.body) } : {},
403
+ createdAt: toIso(comment.createdAt),
404
+ updatedAt
405
+ }
406
+ };
407
+ }
408
+ };
409
+ var linearConnectorPlugin = new LinearConnectorPlugin();
410
+
411
+ exports.LINEAR_BACKFILL_MAX_PAGES = LINEAR_BACKFILL_MAX_PAGES;
412
+ exports.LINEAR_EVENT_TEXT_MAX_CHARS = LINEAR_EVENT_TEXT_MAX_CHARS;
413
+ exports.LINEAR_PULL_PAGE_SIZE = LINEAR_PULL_PAGE_SIZE;
414
+ exports.LinearConnectorPlugin = LinearConnectorPlugin;
415
+ exports.clampBackfillDays = clampBackfillDays;
416
+ exports.default = LinearConnectorPlugin;
417
+ exports.linearConnectorPlugin = linearConnectorPlugin;
@@ -0,0 +1,151 @@
1
+ import { IConnectorPlugin, IEventSourcePlugin, PluginCategory, ConnectorMetadata, JsonSchema, ChannelTargetConfig, ConnectorCallOptions, ChannelVerification, ChannelSendInput, ChannelSendResult, EventSourcePullInput, EventSourcePullResult, EventSourceBackfillInput, EventSourceBackfillResult } from '@ever-works/plugin';
2
+
3
+ /**
4
+ * Payload text cap for ingested envelopes. Envelope payloads are
5
+ * size-capped platform-side (32 KB serialized); issue descriptions and
6
+ * comment bodies never need more than this to be useful in
7
+ * Memory/Activities.
8
+ */
9
+ declare const LINEAR_EVENT_TEXT_MAX_CHARS = 4000;
10
+ /** Items requested per Linear page (issues and comments alike). */
11
+ declare const LINEAR_PULL_PAGE_SIZE = 50;
12
+ /**
13
+ * Historical backfill bound: at most this many pages per phase
14
+ * (issues, then comments) during the opt-in first-pull backfill, so a
15
+ * large workspace can never turn activation into an unbounded crawl.
16
+ */
17
+ declare const LINEAR_BACKFILL_MAX_PAGES = 10;
18
+ /**
19
+ * Clamp the opt-in backfill window to the supported 0–90 day range.
20
+ *
21
+ * Delegates to the shared capability helper so the bound is stated once
22
+ * for the whole connector fabric; the local export stays because it is
23
+ * part of this plugin's published surface.
24
+ */
25
+ declare function clampBackfillDays(value: unknown): number;
26
+ /** Minimal scalar shape of an issue node we consume. */
27
+ interface LinearIssueNode {
28
+ id?: string;
29
+ identifier?: string;
30
+ title?: string;
31
+ description?: string;
32
+ url?: string;
33
+ createdAt?: Date | string;
34
+ updatedAt?: Date | string;
35
+ }
36
+ /** Minimal scalar shape of a comment node we consume. */
37
+ interface LinearCommentNode {
38
+ id?: string;
39
+ body?: string;
40
+ url?: string;
41
+ createdAt?: Date | string;
42
+ updatedAt?: Date | string;
43
+ /** Lazy parent-issue fetch (awaited per node, best-effort). */
44
+ issue?: Promise<LinearIssueNode | undefined> | LinearIssueNode;
45
+ }
46
+ interface LinearConnectionPage<T> {
47
+ nodes?: T[];
48
+ pageInfo?: {
49
+ hasNextPage?: boolean;
50
+ endCursor?: string;
51
+ };
52
+ }
53
+ /** The subset of the `LinearClient` surface this plugin calls. */
54
+ interface LinearClientLike {
55
+ viewer: Promise<{
56
+ id?: string;
57
+ name?: string;
58
+ email?: string;
59
+ }>;
60
+ issues(args: Record<string, unknown>): Promise<LinearConnectionPage<LinearIssueNode>>;
61
+ comments(args: Record<string, unknown>): Promise<LinearConnectionPage<LinearCommentNode>>;
62
+ createComment(input: {
63
+ issueId: string;
64
+ body: string;
65
+ }): Promise<{
66
+ success?: boolean;
67
+ comment?: Promise<{
68
+ id?: string;
69
+ } | undefined> | {
70
+ id?: string;
71
+ };
72
+ }>;
73
+ }
74
+ /**
75
+ * Linear connector (Wave 8) — first-party native connector.
76
+ *
77
+ * Outbound: posts comments on Linear issues via `createComment` on the
78
+ * official `@linear/sdk` (API-key auth; the SDK pins the GraphQL host,
79
+ * so there is no SSRF surface).
80
+ *
81
+ * Event source: `pullEvents` sweeps issues (created/updated) then
82
+ * comments since the watermark, normalized into
83
+ * `IngestedEventEnvelope`s (`linear.issue` / `linear.comment`, issue
84
+ * url as `sourceUrl`) for the platform's event-ingest spine. The
85
+ * opt-in historical backfill (`backfillDays`, default 0 = off, max 90)
86
+ * widens the FIRST pull's window only, with a per-phase page bound so
87
+ * activation never becomes an unbounded crawl. Re-delivery across
88
+ * overlapping windows is fine — the ingest pipeline dedupes on
89
+ * `(source, sourceEventId)`.
90
+ */
91
+ declare class LinearConnectorPlugin implements IConnectorPlugin, IEventSourcePlugin {
92
+ readonly id = "linear-connector";
93
+ readonly name = "Linear Connector";
94
+ readonly version = "1.0.0";
95
+ readonly category: PluginCategory;
96
+ readonly capabilities: readonly ["connector", "connector-linear", "event-source"];
97
+ readonly providerName = "linear";
98
+ readonly connector: ConnectorMetadata;
99
+ readonly settingsSchema: JsonSchema;
100
+ private readonly idempotencyCache;
101
+ onLoad(): Promise<void>;
102
+ onUnload(): Promise<void>;
103
+ /** Testable seam — specs stub this; production uses the real SDK. */
104
+ protected createClient(apiKey: string): LinearClientLike;
105
+ verifyConnection(config: ChannelTargetConfig, options: ConnectorCallOptions): Promise<ChannelVerification>;
106
+ /** Outbound leg — create a comment on a Linear issue. */
107
+ send(payload: ChannelSendInput, options: ConnectorCallOptions): Promise<ChannelSendResult>;
108
+ /**
109
+ * Pull one page of the current sweep phase (issues → comments)
110
+ * since the effective watermark, normalized to envelopes. The
111
+ * returned cursor resumes the same phase (SDK page cursor) or
112
+ * advances to the next; no cursor means the sweep is done.
113
+ *
114
+ * First pull (epoch/absent watermark, no cursor): the window is
115
+ * `now - backfillDays` when the opt-in backfill is on, otherwise
116
+ * `now` — history stays untouched unless the user asked for it.
117
+ */
118
+ pullEvents(input: EventSourcePullInput): Promise<EventSourcePullResult>;
119
+ /**
120
+ * Bounded HISTORICAL sweep from an explicit `since` — the
121
+ * capability's opt-in `backfill()` method.
122
+ *
123
+ * Before this method existed, history was reachable only as a side
124
+ * effect of the FIRST pull (`settings.backfillDays` widening the
125
+ * initial window), so a user who activated the connector without the
126
+ * setting could never go back and fetch it. `backfill()` runs the
127
+ * same two-phase sweep (issues → comments) out-of-band on a
128
+ * caller-chosen window, as many times as wanted — re-delivery is free
129
+ * because the ingest pipeline dedupes on `(source, sourceEventId)`.
130
+ *
131
+ * `until` is accepted for contract symmetry but NOT applied: the SDK
132
+ * filter bounds only the near end (`updatedAt >= since`). An
133
+ * over-wide window costs duplicate deliveries, which the pipeline
134
+ * drops — never wrong data.
135
+ *
136
+ * The per-phase page bound (`LINEAR_BACKFILL_MAX_PAGES`) applies here
137
+ * too: one call fetches ONE page and hands back a cursor, so a large
138
+ * workspace can never turn a backfill into an unbounded crawl.
139
+ */
140
+ backfill(input: EventSourceBackfillInput): Promise<EventSourceBackfillResult>;
141
+ private normalizeIssue;
142
+ /**
143
+ * Normalize one comment → envelope. The parent issue is a lazy SDK
144
+ * fetch — awaited best-effort for the subject/sourceUrl; a failure
145
+ * degrades to the comment's own permalink.
146
+ */
147
+ private normalizeComment;
148
+ }
149
+ declare const linearConnectorPlugin: LinearConnectorPlugin;
150
+
151
+ export { LINEAR_BACKFILL_MAX_PAGES, LINEAR_EVENT_TEXT_MAX_CHARS, LINEAR_PULL_PAGE_SIZE, LinearConnectorPlugin, clampBackfillDays, LinearConnectorPlugin as default, linearConnectorPlugin };
@@ -0,0 +1,151 @@
1
+ import { IConnectorPlugin, IEventSourcePlugin, PluginCategory, ConnectorMetadata, JsonSchema, ChannelTargetConfig, ConnectorCallOptions, ChannelVerification, ChannelSendInput, ChannelSendResult, EventSourcePullInput, EventSourcePullResult, EventSourceBackfillInput, EventSourceBackfillResult } from '@ever-works/plugin';
2
+
3
+ /**
4
+ * Payload text cap for ingested envelopes. Envelope payloads are
5
+ * size-capped platform-side (32 KB serialized); issue descriptions and
6
+ * comment bodies never need more than this to be useful in
7
+ * Memory/Activities.
8
+ */
9
+ declare const LINEAR_EVENT_TEXT_MAX_CHARS = 4000;
10
+ /** Items requested per Linear page (issues and comments alike). */
11
+ declare const LINEAR_PULL_PAGE_SIZE = 50;
12
+ /**
13
+ * Historical backfill bound: at most this many pages per phase
14
+ * (issues, then comments) during the opt-in first-pull backfill, so a
15
+ * large workspace can never turn activation into an unbounded crawl.
16
+ */
17
+ declare const LINEAR_BACKFILL_MAX_PAGES = 10;
18
+ /**
19
+ * Clamp the opt-in backfill window to the supported 0–90 day range.
20
+ *
21
+ * Delegates to the shared capability helper so the bound is stated once
22
+ * for the whole connector fabric; the local export stays because it is
23
+ * part of this plugin's published surface.
24
+ */
25
+ declare function clampBackfillDays(value: unknown): number;
26
+ /** Minimal scalar shape of an issue node we consume. */
27
+ interface LinearIssueNode {
28
+ id?: string;
29
+ identifier?: string;
30
+ title?: string;
31
+ description?: string;
32
+ url?: string;
33
+ createdAt?: Date | string;
34
+ updatedAt?: Date | string;
35
+ }
36
+ /** Minimal scalar shape of a comment node we consume. */
37
+ interface LinearCommentNode {
38
+ id?: string;
39
+ body?: string;
40
+ url?: string;
41
+ createdAt?: Date | string;
42
+ updatedAt?: Date | string;
43
+ /** Lazy parent-issue fetch (awaited per node, best-effort). */
44
+ issue?: Promise<LinearIssueNode | undefined> | LinearIssueNode;
45
+ }
46
+ interface LinearConnectionPage<T> {
47
+ nodes?: T[];
48
+ pageInfo?: {
49
+ hasNextPage?: boolean;
50
+ endCursor?: string;
51
+ };
52
+ }
53
+ /** The subset of the `LinearClient` surface this plugin calls. */
54
+ interface LinearClientLike {
55
+ viewer: Promise<{
56
+ id?: string;
57
+ name?: string;
58
+ email?: string;
59
+ }>;
60
+ issues(args: Record<string, unknown>): Promise<LinearConnectionPage<LinearIssueNode>>;
61
+ comments(args: Record<string, unknown>): Promise<LinearConnectionPage<LinearCommentNode>>;
62
+ createComment(input: {
63
+ issueId: string;
64
+ body: string;
65
+ }): Promise<{
66
+ success?: boolean;
67
+ comment?: Promise<{
68
+ id?: string;
69
+ } | undefined> | {
70
+ id?: string;
71
+ };
72
+ }>;
73
+ }
74
+ /**
75
+ * Linear connector (Wave 8) — first-party native connector.
76
+ *
77
+ * Outbound: posts comments on Linear issues via `createComment` on the
78
+ * official `@linear/sdk` (API-key auth; the SDK pins the GraphQL host,
79
+ * so there is no SSRF surface).
80
+ *
81
+ * Event source: `pullEvents` sweeps issues (created/updated) then
82
+ * comments since the watermark, normalized into
83
+ * `IngestedEventEnvelope`s (`linear.issue` / `linear.comment`, issue
84
+ * url as `sourceUrl`) for the platform's event-ingest spine. The
85
+ * opt-in historical backfill (`backfillDays`, default 0 = off, max 90)
86
+ * widens the FIRST pull's window only, with a per-phase page bound so
87
+ * activation never becomes an unbounded crawl. Re-delivery across
88
+ * overlapping windows is fine — the ingest pipeline dedupes on
89
+ * `(source, sourceEventId)`.
90
+ */
91
+ declare class LinearConnectorPlugin implements IConnectorPlugin, IEventSourcePlugin {
92
+ readonly id = "linear-connector";
93
+ readonly name = "Linear Connector";
94
+ readonly version = "1.0.0";
95
+ readonly category: PluginCategory;
96
+ readonly capabilities: readonly ["connector", "connector-linear", "event-source"];
97
+ readonly providerName = "linear";
98
+ readonly connector: ConnectorMetadata;
99
+ readonly settingsSchema: JsonSchema;
100
+ private readonly idempotencyCache;
101
+ onLoad(): Promise<void>;
102
+ onUnload(): Promise<void>;
103
+ /** Testable seam — specs stub this; production uses the real SDK. */
104
+ protected createClient(apiKey: string): LinearClientLike;
105
+ verifyConnection(config: ChannelTargetConfig, options: ConnectorCallOptions): Promise<ChannelVerification>;
106
+ /** Outbound leg — create a comment on a Linear issue. */
107
+ send(payload: ChannelSendInput, options: ConnectorCallOptions): Promise<ChannelSendResult>;
108
+ /**
109
+ * Pull one page of the current sweep phase (issues → comments)
110
+ * since the effective watermark, normalized to envelopes. The
111
+ * returned cursor resumes the same phase (SDK page cursor) or
112
+ * advances to the next; no cursor means the sweep is done.
113
+ *
114
+ * First pull (epoch/absent watermark, no cursor): the window is
115
+ * `now - backfillDays` when the opt-in backfill is on, otherwise
116
+ * `now` — history stays untouched unless the user asked for it.
117
+ */
118
+ pullEvents(input: EventSourcePullInput): Promise<EventSourcePullResult>;
119
+ /**
120
+ * Bounded HISTORICAL sweep from an explicit `since` — the
121
+ * capability's opt-in `backfill()` method.
122
+ *
123
+ * Before this method existed, history was reachable only as a side
124
+ * effect of the FIRST pull (`settings.backfillDays` widening the
125
+ * initial window), so a user who activated the connector without the
126
+ * setting could never go back and fetch it. `backfill()` runs the
127
+ * same two-phase sweep (issues → comments) out-of-band on a
128
+ * caller-chosen window, as many times as wanted — re-delivery is free
129
+ * because the ingest pipeline dedupes on `(source, sourceEventId)`.
130
+ *
131
+ * `until` is accepted for contract symmetry but NOT applied: the SDK
132
+ * filter bounds only the near end (`updatedAt >= since`). An
133
+ * over-wide window costs duplicate deliveries, which the pipeline
134
+ * drops — never wrong data.
135
+ *
136
+ * The per-phase page bound (`LINEAR_BACKFILL_MAX_PAGES`) applies here
137
+ * too: one call fetches ONE page and hands back a cursor, so a large
138
+ * workspace can never turn a backfill into an unbounded crawl.
139
+ */
140
+ backfill(input: EventSourceBackfillInput): Promise<EventSourceBackfillResult>;
141
+ private normalizeIssue;
142
+ /**
143
+ * Normalize one comment → envelope. The parent issue is a lazy SDK
144
+ * fetch — awaited best-effort for the subject/sourceUrl; a failure
145
+ * degrades to the comment's own permalink.
146
+ */
147
+ private normalizeComment;
148
+ }
149
+ declare const linearConnectorPlugin: LinearConnectorPlugin;
150
+
151
+ export { LINEAR_BACKFILL_MAX_PAGES, LINEAR_EVENT_TEXT_MAX_CHARS, LINEAR_PULL_PAGE_SIZE, LinearConnectorPlugin, clampBackfillDays, LinearConnectorPlugin as default, linearConnectorPlugin };
package/dist/index.js ADDED
@@ -0,0 +1,407 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { LinearClient } from '@linear/sdk';
3
+ import '@ever-works/contracts';
4
+
5
+ // src/linear-connector-plugin.ts
6
+ var EVENT_SOURCE_BACKFILL_MAX_DAYS = 90;
7
+ function clampEventSourceBackfillDays(value, max = EVENT_SOURCE_BACKFILL_MAX_DAYS) {
8
+ const num = typeof value === "number" ? value : Number(value);
9
+ if (!Number.isFinite(num) || num <= 0) return 0;
10
+ return Math.min(Math.floor(num), max);
11
+ }
12
+ var EventSourceNotConfiguredError = class extends Error {
13
+ constructor(message) {
14
+ super(message ?? "Event-source plugin is not configured in this runtime.");
15
+ this.name = "EventSourceNotConfiguredError";
16
+ }
17
+ };
18
+ var PLUGIN_CAPABILITIES = {
19
+ // Connectors ("Connector fabric") — first-party BIDIRECTIONAL
20
+ // communication-channel plugins. Each connector declares `CONNECTOR`
21
+ // (umbrella, for discovery/grouping) plus its `CONNECTOR_<provider>`
22
+ // constant. Superset of the outbound-only notification channels; see
23
+ // `capabilities/connector.interface.ts`.
24
+ CONNECTOR: "connector",
25
+ CONNECTOR_LINEAR: "connector-linear",
26
+ // Event-ingest spine (Wave 6) — plugins that pull/push normalized
27
+ // external events into the platform ingest pipeline. See
28
+ // capabilities/event-source.interface.ts.
29
+ EVENT_SOURCE: "event-source"};
30
+
31
+ // src/linear-connector-plugin.ts
32
+ var LINEAR_EVENT_TEXT_MAX_CHARS = 4e3;
33
+ var LINEAR_PULL_PAGE_SIZE = 50;
34
+ var LINEAR_BACKFILL_MAX_PAGES = 10;
35
+ function clampBackfillDays(value) {
36
+ return clampEventSourceBackfillDays(value);
37
+ }
38
+ function truncateText(text) {
39
+ return text.length > LINEAR_EVENT_TEXT_MAX_CHARS ? text.slice(0, LINEAR_EVENT_TEXT_MAX_CHARS) : text;
40
+ }
41
+ function teamKeyFromIdentifier(identifier) {
42
+ if (!identifier) return void 0;
43
+ const match = /^([A-Za-z0-9]+)-\d+$/.exec(identifier.trim());
44
+ return match ? match[1] : void 0;
45
+ }
46
+ function resolveTeamIds(settings) {
47
+ const raw = settings?.teamIds;
48
+ if (typeof raw === "string" && raw.trim().length > 0) {
49
+ return raw.split(/[\s,]+/).map((t) => t.trim()).filter((t) => t.length > 0);
50
+ }
51
+ return [];
52
+ }
53
+ function linearErrorMessage(err) {
54
+ const e = err;
55
+ return e.message ?? e.type ?? "unknown error";
56
+ }
57
+ function toIso(value) {
58
+ if (value instanceof Date) return value.toISOString();
59
+ if (typeof value === "string") {
60
+ const ms = Date.parse(value);
61
+ if (Number.isFinite(ms)) return new Date(ms).toISOString();
62
+ }
63
+ return (/* @__PURE__ */ new Date(0)).toISOString();
64
+ }
65
+ function parsePullCursor(cursor) {
66
+ if (!cursor) return void 0;
67
+ try {
68
+ const parsed = JSON.parse(cursor);
69
+ if (parsed && (parsed.p === "issues" || parsed.p === "comments") && typeof parsed.s === "string") {
70
+ return parsed;
71
+ }
72
+ } catch {
73
+ }
74
+ return void 0;
75
+ }
76
+ function resolveApiKey(config, options) {
77
+ const candidates = [config.apiKey, options.settings?.apiKey];
78
+ for (const c of candidates) {
79
+ if (typeof c === "string" && c.length > 0) return c;
80
+ }
81
+ return void 0;
82
+ }
83
+ function resolveIssueId(config, options) {
84
+ const candidates = [config.issueId, config.defaultIssueId, options.settings?.defaultIssueId];
85
+ for (const c of candidates) {
86
+ if (typeof c === "string" && c.length > 0) return c;
87
+ }
88
+ throw new Error("linear-connector: an issue id is required (targetConfig.issueId or defaultIssueId)");
89
+ }
90
+ var LinearConnectorPlugin = class {
91
+ constructor() {
92
+ this.id = "linear-connector";
93
+ this.name = "Linear Connector";
94
+ this.version = "1.0.0";
95
+ this.category = "connector";
96
+ this.capabilities = [
97
+ PLUGIN_CAPABILITIES.CONNECTOR,
98
+ PLUGIN_CAPABILITIES.CONNECTOR_LINEAR,
99
+ PLUGIN_CAPABILITIES.EVENT_SOURCE
100
+ ];
101
+ this.providerName = "linear";
102
+ this.connector = {
103
+ direction: "outbound",
104
+ transport: "poll",
105
+ flags: {
106
+ outboundMessage: true,
107
+ outboundRecord: false,
108
+ inbound: false,
109
+ reply: false,
110
+ pairing: false,
111
+ richOutbound: false
112
+ }
113
+ };
114
+ this.settingsSchema = {
115
+ type: "object",
116
+ required: ["apiKey"],
117
+ properties: {
118
+ apiKey: {
119
+ type: "string",
120
+ title: "Linear API key (lin_api_\u2026)",
121
+ "x-secret": true,
122
+ "x-envVar": "LINEAR_API_KEY"
123
+ },
124
+ teamIds: {
125
+ type: "string",
126
+ title: "Team ids to ingest events from (comma-separated; all teams when empty)"
127
+ },
128
+ backfillDays: {
129
+ type: "number",
130
+ title: "Historical backfill window in days on first pull (0 = off, max 90)",
131
+ default: 0,
132
+ minimum: 0,
133
+ maximum: 90
134
+ },
135
+ defaultIssueId: {
136
+ type: "string",
137
+ title: "Default issue id for outbound comments"
138
+ }
139
+ }
140
+ };
141
+ this.idempotencyCache = /* @__PURE__ */ new Map();
142
+ }
143
+ async onLoad() {
144
+ }
145
+ async onUnload() {
146
+ this.idempotencyCache.clear();
147
+ }
148
+ /** Testable seam — specs stub this; production uses the real SDK. */
149
+ createClient(apiKey) {
150
+ return new LinearClient({ apiKey });
151
+ }
152
+ async verifyConnection(config, options) {
153
+ const apiKey = resolveApiKey(config, options);
154
+ if (!apiKey) {
155
+ return { valid: false, message: "apiKey is required" };
156
+ }
157
+ try {
158
+ const viewer = await this.createClient(apiKey).viewer;
159
+ return {
160
+ valid: true,
161
+ details: {
162
+ viewerId: viewer?.id,
163
+ viewerName: viewer?.name,
164
+ ...viewer?.email ? { email: viewer.email } : {}
165
+ }
166
+ };
167
+ } catch (err) {
168
+ return { valid: false, message: `Linear viewer lookup failed: ${linearErrorMessage(err)}` };
169
+ }
170
+ }
171
+ /** Outbound leg — create a comment on a Linear issue. */
172
+ async send(payload, options) {
173
+ const config = payload.target ?? options.target ?? {};
174
+ const apiKey = resolveApiKey(config, options);
175
+ if (!apiKey) {
176
+ throw new Error("linear-connector: an API key is required (targetConfig.apiKey or settings.apiKey)");
177
+ }
178
+ const issueId = resolveIssueId(config, options);
179
+ const cacheKey = `${options.connectorId ?? ""}\0${issueId}\0${payload.messageRef}`;
180
+ const cached = this.idempotencyCache.get(cacheKey);
181
+ if (cached) return cached;
182
+ let commentId;
183
+ try {
184
+ const res = await this.createClient(apiKey).createComment({ issueId, body: payload.text });
185
+ const comment = res.comment ? await res.comment : void 0;
186
+ commentId = typeof comment?.id === "string" ? comment.id : void 0;
187
+ } catch (err) {
188
+ throw new Error(`Linear createComment failed: ${linearErrorMessage(err)}`);
189
+ }
190
+ const result = {
191
+ provider: this.id,
192
+ providerMessageId: commentId ?? `linear-${payload.messageRef}`,
193
+ deliveredAt: /* @__PURE__ */ new Date()
194
+ };
195
+ this.idempotencyCache.set(cacheKey, result);
196
+ if (this.idempotencyCache.size > 500) {
197
+ const firstKey = this.idempotencyCache.keys().next().value;
198
+ if (firstKey) this.idempotencyCache.delete(firstKey);
199
+ }
200
+ return result;
201
+ }
202
+ // ── Event source (pull) ─────────────────────────────────────────────
203
+ /**
204
+ * Pull one page of the current sweep phase (issues → comments)
205
+ * since the effective watermark, normalized to envelopes. The
206
+ * returned cursor resumes the same phase (SDK page cursor) or
207
+ * advances to the next; no cursor means the sweep is done.
208
+ *
209
+ * First pull (epoch/absent watermark, no cursor): the window is
210
+ * `now - backfillDays` when the opt-in backfill is on, otherwise
211
+ * `now` — history stays untouched unless the user asked for it.
212
+ */
213
+ async pullEvents(input) {
214
+ const apiKey = input.settings?.apiKey;
215
+ if (typeof apiKey !== "string" || apiKey.length === 0) {
216
+ throw new EventSourceNotConfiguredError("linear-connector: settings.apiKey is required to pull events");
217
+ }
218
+ const cursor = parsePullCursor(input.cursor);
219
+ let phase;
220
+ let after;
221
+ let since;
222
+ let backfill;
223
+ let pagesUsed;
224
+ if (cursor) {
225
+ phase = cursor.p;
226
+ after = cursor.n;
227
+ since = cursor.s;
228
+ backfill = cursor.f === 1;
229
+ pagesUsed = cursor.b ?? 0;
230
+ } else {
231
+ const sinceMs = Date.parse(input.since);
232
+ const firstPull = !Number.isFinite(sinceMs) || sinceMs <= 0;
233
+ const backfillDays = clampBackfillDays(input.settings?.backfillDays);
234
+ if (firstPull) {
235
+ const start = backfillDays > 0 ? Date.now() - backfillDays * 864e5 : Date.now();
236
+ since = new Date(start).toISOString();
237
+ backfill = backfillDays > 0;
238
+ } else {
239
+ since = new Date(sinceMs).toISOString();
240
+ backfill = false;
241
+ }
242
+ phase = "issues";
243
+ after = void 0;
244
+ pagesUsed = 0;
245
+ }
246
+ const client = this.createClient(apiKey);
247
+ const teamIds = resolveTeamIds(input.settings);
248
+ const events = [];
249
+ let hasNextPage = false;
250
+ let endCursor;
251
+ if (phase === "issues") {
252
+ const page = await client.issues({
253
+ first: LINEAR_PULL_PAGE_SIZE,
254
+ ...after ? { after } : {},
255
+ filter: {
256
+ updatedAt: { gte: new Date(since) },
257
+ ...teamIds.length > 0 ? { team: { id: { in: teamIds } } } : {}
258
+ }
259
+ });
260
+ for (const issue of page.nodes ?? []) {
261
+ const envelope = this.normalizeIssue(issue, since);
262
+ if (envelope) events.push(envelope);
263
+ }
264
+ hasNextPage = page.pageInfo?.hasNextPage === true;
265
+ endCursor = page.pageInfo?.endCursor;
266
+ } else {
267
+ const page = await client.comments({
268
+ first: LINEAR_PULL_PAGE_SIZE,
269
+ ...after ? { after } : {},
270
+ filter: { updatedAt: { gte: new Date(since) } }
271
+ });
272
+ for (const comment of page.nodes ?? []) {
273
+ const envelope = await this.normalizeComment(comment);
274
+ if (envelope) events.push(envelope);
275
+ }
276
+ hasNextPage = page.pageInfo?.hasNextPage === true;
277
+ endCursor = page.pageInfo?.endCursor;
278
+ }
279
+ pagesUsed += 1;
280
+ const pageBudgetExhausted = backfill && pagesUsed >= LINEAR_BACKFILL_MAX_PAGES;
281
+ let next;
282
+ if (hasNextPage && endCursor && !pageBudgetExhausted) {
283
+ next = { p: phase, n: endCursor, s: since, ...backfill ? { f: 1 } : {}, b: pagesUsed };
284
+ } else if (phase === "issues") {
285
+ next = { p: "comments", s: since, ...backfill ? { f: 1 } : {}, b: 0 };
286
+ }
287
+ return next ? { events, nextCursor: JSON.stringify(next) } : { events };
288
+ }
289
+ /**
290
+ * Bounded HISTORICAL sweep from an explicit `since` — the
291
+ * capability's opt-in `backfill()` method.
292
+ *
293
+ * Before this method existed, history was reachable only as a side
294
+ * effect of the FIRST pull (`settings.backfillDays` widening the
295
+ * initial window), so a user who activated the connector without the
296
+ * setting could never go back and fetch it. `backfill()` runs the
297
+ * same two-phase sweep (issues → comments) out-of-band on a
298
+ * caller-chosen window, as many times as wanted — re-delivery is free
299
+ * because the ingest pipeline dedupes on `(source, sourceEventId)`.
300
+ *
301
+ * `until` is accepted for contract symmetry but NOT applied: the SDK
302
+ * filter bounds only the near end (`updatedAt >= since`). An
303
+ * over-wide window costs duplicate deliveries, which the pipeline
304
+ * drops — never wrong data.
305
+ *
306
+ * The per-phase page bound (`LINEAR_BACKFILL_MAX_PAGES`) applies here
307
+ * too: one call fetches ONE page and hands back a cursor, so a large
308
+ * workspace can never turn a backfill into an unbounded crawl.
309
+ */
310
+ async backfill(input) {
311
+ const sinceMs = Date.parse(input.since);
312
+ if (!Number.isFinite(sinceMs)) {
313
+ throw new EventSourceNotConfiguredError(
314
+ `linear-connector: backfill requires a valid ISO 8601 "since" (received ${JSON.stringify(input.since)})`
315
+ );
316
+ }
317
+ const cursor = input.cursor ?? JSON.stringify({
318
+ p: "issues",
319
+ s: new Date(sinceMs).toISOString(),
320
+ f: 1,
321
+ b: 0
322
+ });
323
+ const page = await this.pullEvents({
324
+ since: input.since,
325
+ cursor,
326
+ ...input.settings ? { settings: input.settings } : {}
327
+ });
328
+ return page.nextCursor ? { events: page.events, nextCursor: page.nextCursor } : { events: page.events, complete: true };
329
+ }
330
+ normalizeIssue(issue, since) {
331
+ if (!issue.id) return null;
332
+ const updatedAt = toIso(issue.updatedAt ?? issue.createdAt);
333
+ const createdAt = toIso(issue.createdAt);
334
+ const changeType = Date.parse(createdAt) >= Date.parse(since) ? "created" : "updated";
335
+ const teamKey = teamKeyFromIdentifier(issue.identifier);
336
+ return {
337
+ id: randomUUID(),
338
+ source: this.id,
339
+ sourceEventId: `${issue.id}:${updatedAt}`,
340
+ kind: "linear.issue",
341
+ occurredAt: updatedAt,
342
+ subject: {
343
+ type: "issue",
344
+ externalId: issue.id,
345
+ ...issue.title ? { title: issue.title } : {}
346
+ },
347
+ // Work routing: the team is the container an Ever Works Work
348
+ // maps onto. Issues with an unparseable identifier carry no
349
+ // hint and stay user-scoped.
350
+ ...teamKey ? { workHint: { kind: "tracker-team", externalId: teamKey } } : {},
351
+ ...issue.url ? { sourceUrl: issue.url } : {},
352
+ payload: {
353
+ issueId: issue.id,
354
+ ...issue.identifier ? { identifier: issue.identifier } : {},
355
+ ...issue.title ? { title: truncateText(issue.title) } : {},
356
+ ...issue.description ? { description: truncateText(issue.description) } : {},
357
+ changeType,
358
+ createdAt,
359
+ updatedAt
360
+ }
361
+ };
362
+ }
363
+ /**
364
+ * Normalize one comment → envelope. The parent issue is a lazy SDK
365
+ * fetch — awaited best-effort for the subject/sourceUrl; a failure
366
+ * degrades to the comment's own permalink.
367
+ */
368
+ async normalizeComment(comment) {
369
+ if (!comment.id) return null;
370
+ const updatedAt = toIso(comment.updatedAt ?? comment.createdAt);
371
+ let issue;
372
+ try {
373
+ issue = comment.issue ? await comment.issue : void 0;
374
+ } catch {
375
+ issue = void 0;
376
+ }
377
+ const sourceUrl = comment.url ?? issue?.url;
378
+ const teamKey = teamKeyFromIdentifier(issue?.identifier);
379
+ return {
380
+ id: randomUUID(),
381
+ source: this.id,
382
+ sourceEventId: `${comment.id}:${updatedAt}`,
383
+ kind: "linear.comment",
384
+ occurredAt: updatedAt,
385
+ subject: {
386
+ type: "issue",
387
+ externalId: issue?.id ?? "unknown",
388
+ ...issue?.title ? { title: issue.title } : {}
389
+ },
390
+ // Same team-as-container routing as issues; the parent-issue
391
+ // fetch is best-effort, so a failed one simply means no hint.
392
+ ...teamKey ? { workHint: { kind: "tracker-team", externalId: teamKey } } : {},
393
+ ...sourceUrl ? { sourceUrl } : {},
394
+ payload: {
395
+ commentId: comment.id,
396
+ ...issue?.id ? { issueId: issue.id } : {},
397
+ ...issue?.identifier ? { issueIdentifier: issue.identifier } : {},
398
+ ...comment.body ? { body: truncateText(comment.body) } : {},
399
+ createdAt: toIso(comment.createdAt),
400
+ updatedAt
401
+ }
402
+ };
403
+ }
404
+ };
405
+ var linearConnectorPlugin = new LinearConnectorPlugin();
406
+
407
+ export { LINEAR_BACKFILL_MAX_PAGES, LINEAR_EVENT_TEXT_MAX_CHARS, LINEAR_PULL_PAGE_SIZE, LinearConnectorPlugin, clampBackfillDays, LinearConnectorPlugin as default, linearConnectorPlugin };
package/package.json ADDED
@@ -0,0 +1,106 @@
1
+ {
2
+ "name": "@ever-works/linear-connector-plugin",
3
+ "version": "1.0.0",
4
+ "description": "Linear connector plugin for Ever Works platform (outbound issue comments via @linear/sdk and event-source pull of issues/comments into the event-ingest pipeline, with opt-in historical backfill)",
5
+ "author": {
6
+ "name": "Ever Co. LTD",
7
+ "email": "ever@ever.co",
8
+ "url": "https://ever.co"
9
+ },
10
+ "license": "AGPL-3.0",
11
+ "private": false,
12
+ "type": "module",
13
+ "main": "./dist/index.cjs",
14
+ "module": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "require": "./dist/index.cjs"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsc --noEmit && tsup",
28
+ "dev": "tsup --watch",
29
+ "clean": "rm -rf dist",
30
+ "type-check": "tsc --noEmit",
31
+ "test": "vitest run",
32
+ "test:watch": "vitest"
33
+ },
34
+ "dependencies": {
35
+ "@ever-works/contracts": "^1.0.0",
36
+ "@ever-works/plugin": "^1.2.0",
37
+ "@linear/sdk": "^88.0.0"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "^22.0.0",
41
+ "tsup": "^8.0.0",
42
+ "typescript": "^5.9.3",
43
+ "vitest": "^4.1.0"
44
+ },
45
+ "everworks": {
46
+ "plugin": {
47
+ "id": "linear-connector",
48
+ "name": "Linear Connector",
49
+ "version": "1.0.0",
50
+ "category": "connector",
51
+ "capabilities": [
52
+ "connector",
53
+ "connector-linear",
54
+ "event-source"
55
+ ],
56
+ "description": "Linear connector. Outbound posts comments on Linear issues via the official @linear/sdk. Event-source pull ingests issues (created/updated) and comments since the last watermark into the platform event-ingest pipeline, with opt-in historical backfill (backfillDays, max 90).",
57
+ "systemPlugin": false,
58
+ "builtIn": true,
59
+ "isDefault": false,
60
+ "autoEnable": false,
61
+ "settings": {
62
+ "type": "object",
63
+ "required": [
64
+ "apiKey"
65
+ ],
66
+ "properties": {
67
+ "apiKey": {
68
+ "type": "string",
69
+ "title": "Linear API key (lin_api_…)",
70
+ "x-secret": true,
71
+ "x-envVar": "LINEAR_API_KEY"
72
+ },
73
+ "teamIds": {
74
+ "type": "string",
75
+ "title": "Team ids to ingest events from (comma-separated; all teams when empty)"
76
+ },
77
+ "backfillDays": {
78
+ "type": "number",
79
+ "title": "Historical backfill window in days on first pull (0 = off, max 90)",
80
+ "default": 0,
81
+ "minimum": 0,
82
+ "maximum": 90
83
+ },
84
+ "defaultIssueId": {
85
+ "type": "string",
86
+ "title": "Default issue id for outbound comments"
87
+ }
88
+ }
89
+ }
90
+ }
91
+ },
92
+ "repository": {
93
+ "type": "git",
94
+ "url": "git+https://github.com/ever-works/ever-works.git",
95
+ "directory": "packages/plugins/linear-connector"
96
+ },
97
+ "homepage": "https://github.com/ever-works/ever-works/tree/main/packages/plugins/linear-connector#readme",
98
+ "bugs": {
99
+ "url": "https://github.com/ever-works/ever-works/issues"
100
+ },
101
+ "everworksRelease": {
102
+ "contentHash": "sha256:52552656e6b34573bbf1ae42578dc9c538567c6e783b92e1ae35b4fd4b5bfe2a",
103
+ "commit": "6628882fbf102716a412f7d9a66d8387bd6a784c",
104
+ "source": "https://github.com/ever-works/ever-works/tree/6628882fbf102716a412f7d9a66d8387bd6a784c/packages/plugins/linear-connector"
105
+ }
106
+ }