@ever-works/jira-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 +81 -0
- package/dist/index.cjs +518 -0
- package/dist/index.d.cts +224 -0
- package/dist/index.d.ts +224 -0
- package/dist/index.js +502 -0
- package/package.json +125 -0
package/README.md
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# @ever-works/jira-connector-plugin
|
|
2
|
+
|
|
3
|
+
First-party **JIRA connector** for the Ever Works platform (Wave 8), built on
|
|
4
|
+
[`jira.js`](https://www.npmjs.com/package/jira.js).
|
|
5
|
+
|
|
6
|
+
Capabilities: `connector`, `event-source`.
|
|
7
|
+
|
|
8
|
+
## Why `jira.js`
|
|
9
|
+
|
|
10
|
+
Atlassian publishes no maintained first-party Node client for the Jira Cloud
|
|
11
|
+
REST API: the Atlassian Labs `@atlassian/jira` package stopped at `0.1.0` with
|
|
12
|
+
no release since 2018, and `@forge/api` only runs inside a Forge app runtime.
|
|
13
|
+
`jira.js` is the actively maintained (weekly releases), TypeScript-native Jira
|
|
14
|
+
Cloud client, and is what this connector builds on.
|
|
15
|
+
|
|
16
|
+
## What it does
|
|
17
|
+
|
|
18
|
+
- **Outbound** — `send()` posts a comment on a JIRA issue
|
|
19
|
+
(`targetConfig.issueKey` / `defaultIssueKey`), idempotent on `messageRef`.
|
|
20
|
+
Plain text is rendered into Atlassian Document Format by the SDK.
|
|
21
|
+
- **Event source** — `pullEvents()` sweeps issues updated since the platform
|
|
22
|
+
watermark with one bounded JQL query per page, normalized into
|
|
23
|
+
`IngestedEventEnvelope`s (`jira.issue` / `jira.comment`). Each envelope
|
|
24
|
+
carries the issue's browse URL as `sourceUrl` so Memory/Activity rows link
|
|
25
|
+
back to the origin.
|
|
26
|
+
- **Work routing** — every envelope carries a `tracker-team` `workHint` keyed
|
|
27
|
+
on the project key, so a Work claiming that project gets the event on its
|
|
28
|
+
feed.
|
|
29
|
+
- **Opt-in historical backfill** — `backfillDays` (default `0` = off, max 90)
|
|
30
|
+
widens the FIRST pull's window only, bounded to `JIRA_BACKFILL_MAX_PAGES`
|
|
31
|
+
pages.
|
|
32
|
+
|
|
33
|
+
### Comments ride with the issue
|
|
34
|
+
|
|
35
|
+
JIRA has no "all comments" endpoint — comments only exist under an issue. The
|
|
36
|
+
sweep therefore requests the `comment` field alongside each issue and emits a
|
|
37
|
+
`jira.comment` envelope for every comment that itself changed inside the
|
|
38
|
+
window. That keeps a page at ONE API call instead of one per issue, and an
|
|
39
|
+
issue whose only change is a new comment is already in the result set because
|
|
40
|
+
commenting bumps `updated`.
|
|
41
|
+
|
|
42
|
+
### JQL and the site timezone
|
|
43
|
+
|
|
44
|
+
JQL evaluates bare date literals in the SITE's timezone while the platform
|
|
45
|
+
watermark is UTC, so the rendered window can be off by the site's UTC offset.
|
|
46
|
+
That is safe in both directions: dedupe is `(source, sourceEventId)`, so an
|
|
47
|
+
over-wide window costs one extra page and drops nothing, and each comment
|
|
48
|
+
re-checks `since` before its envelope is emitted.
|
|
49
|
+
|
|
50
|
+
- **Historical backfill (`backfill()` capability method)** — the optional
|
|
51
|
+
`backfill()` method on the `event-source` capability runs the same sweep
|
|
52
|
+
out-of-band over an EXPLICIT window, so history can be imported at any time
|
|
53
|
+
instead of only as a side effect of the first pull's `backfillDays`. One call
|
|
54
|
+
fetches one page and hands back a cursor, so the per-phase page bound still
|
|
55
|
+
applies. Re-delivery is free — the ingest pipeline dedupes on
|
|
56
|
+
`(source, sourceEventId)`.
|
|
57
|
+
|
|
58
|
+
## Settings
|
|
59
|
+
|
|
60
|
+
| Key | Notes |
|
|
61
|
+
| ----------------- | ------------------------------------------------------------------ |
|
|
62
|
+
| `baseUrl` | JIRA site URL, `https://…` only — env `JIRA_BASE_URL`. |
|
|
63
|
+
| `email` | Atlassian account email (API-token basic auth) — env `JIRA_EMAIL`. |
|
|
64
|
+
| `apiToken` | Atlassian API token — secret, env `JIRA_API_TOKEN`. |
|
|
65
|
+
| `projectKeys` | Optional comma-separated project-key filter for the pull. |
|
|
66
|
+
| `backfillDays` | Opt-in first-pull history window (0 = off, max 90). |
|
|
67
|
+
| `defaultIssueKey` | Default issue for outbound comments. |
|
|
68
|
+
|
|
69
|
+
### SSRF posture
|
|
70
|
+
|
|
71
|
+
Unlike every sibling connector, this one takes its host from user settings (a
|
|
72
|
+
JIRA site is per-customer), so `baseUrl` is an SSRF surface. It is validated
|
|
73
|
+
before any request: `https:` only, no embedded credentials, and loopback /
|
|
74
|
+
link-local / RFC-1918 / `.local` / `.internal` hosts are rejected. Project keys
|
|
75
|
+
are whitelisted against JIRA's own key alphabet rather than escaped, because
|
|
76
|
+
they are interpolated into JQL.
|
|
77
|
+
|
|
78
|
+
## Testing
|
|
79
|
+
|
|
80
|
+
Hermetic Vitest suite (`pnpm test`) — the SDK client is stubbed through the
|
|
81
|
+
`createClient` seam; no network calls.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var crypto = require('crypto');
|
|
6
|
+
var jira_js = require('jira.js');
|
|
7
|
+
require('@ever-works/contracts');
|
|
8
|
+
|
|
9
|
+
// src/jira-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
|
+
// Event-ingest spine (Wave 6) — plugins that pull/push normalized
|
|
30
|
+
// external events into the platform ingest pipeline. See
|
|
31
|
+
// capabilities/event-source.interface.ts.
|
|
32
|
+
EVENT_SOURCE: "event-source"};
|
|
33
|
+
|
|
34
|
+
// src/jira-connector-plugin.ts
|
|
35
|
+
var JIRA_EVENT_TEXT_MAX_CHARS = 4e3;
|
|
36
|
+
var JIRA_PULL_PAGE_SIZE = 50;
|
|
37
|
+
var JIRA_BACKFILL_MAX_PAGES = 10;
|
|
38
|
+
var JIRA_ISSUE_FIELDS = [
|
|
39
|
+
"summary",
|
|
40
|
+
"description",
|
|
41
|
+
"created",
|
|
42
|
+
"updated",
|
|
43
|
+
"project",
|
|
44
|
+
"status",
|
|
45
|
+
"issuetype",
|
|
46
|
+
"comment"
|
|
47
|
+
];
|
|
48
|
+
function clampBackfillDays(value) {
|
|
49
|
+
return clampEventSourceBackfillDays(value);
|
|
50
|
+
}
|
|
51
|
+
function truncateText(text) {
|
|
52
|
+
return text.length > JIRA_EVENT_TEXT_MAX_CHARS ? text.slice(0, JIRA_EVENT_TEXT_MAX_CHARS) : text;
|
|
53
|
+
}
|
|
54
|
+
var PRIVATE_HOST_PATTERNS = [
|
|
55
|
+
/^localhost$/i,
|
|
56
|
+
/^127(?:\.\d{1,3}){3}$/,
|
|
57
|
+
/^0\.0\.0\.0$/,
|
|
58
|
+
/^10(?:\.\d{1,3}){3}$/,
|
|
59
|
+
/^192\.168(?:\.\d{1,3}){2}$/,
|
|
60
|
+
/^172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}$/,
|
|
61
|
+
/^169\.254(?:\.\d{1,3}){2}$/,
|
|
62
|
+
/^\[?::1\]?$/,
|
|
63
|
+
/\.local$/i,
|
|
64
|
+
/\.internal$/i
|
|
65
|
+
];
|
|
66
|
+
function normalizeBaseUrl(value) {
|
|
67
|
+
if (typeof value !== "string" || value.trim().length === 0) return void 0;
|
|
68
|
+
let url;
|
|
69
|
+
try {
|
|
70
|
+
url = new URL(value.trim());
|
|
71
|
+
} catch {
|
|
72
|
+
return void 0;
|
|
73
|
+
}
|
|
74
|
+
if (url.protocol !== "https:") return void 0;
|
|
75
|
+
if (url.username.length > 0 || url.password.length > 0) return void 0;
|
|
76
|
+
const host = url.hostname;
|
|
77
|
+
if (host.length === 0) return void 0;
|
|
78
|
+
if (PRIVATE_HOST_PATTERNS.some((pattern) => pattern.test(host))) return void 0;
|
|
79
|
+
return url.origin;
|
|
80
|
+
}
|
|
81
|
+
function resolveProjectKeys(settings) {
|
|
82
|
+
const raw = settings?.projectKeys;
|
|
83
|
+
if (typeof raw !== "string" || raw.trim().length === 0) return [];
|
|
84
|
+
return raw.split(",").map((key) => key.trim().toUpperCase()).filter((key) => /^[A-Z][A-Z0-9_]{0,63}$/.test(key));
|
|
85
|
+
}
|
|
86
|
+
function jiraErrorMessage(err) {
|
|
87
|
+
const e = err;
|
|
88
|
+
const apiMessage = e.response?.data?.errorMessages?.[0];
|
|
89
|
+
return apiMessage ?? e.message ?? "unknown error";
|
|
90
|
+
}
|
|
91
|
+
function toIso(value) {
|
|
92
|
+
if (value instanceof Date) return value.toISOString();
|
|
93
|
+
if (typeof value === "string") {
|
|
94
|
+
const ms = Date.parse(value);
|
|
95
|
+
if (Number.isFinite(ms)) return new Date(ms).toISOString();
|
|
96
|
+
}
|
|
97
|
+
return (/* @__PURE__ */ new Date(0)).toISOString();
|
|
98
|
+
}
|
|
99
|
+
function toJqlDateTime(iso) {
|
|
100
|
+
const ms = Date.parse(iso);
|
|
101
|
+
const date = new Date(Number.isFinite(ms) ? ms : 0);
|
|
102
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
103
|
+
return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())} ${pad(
|
|
104
|
+
date.getUTCHours()
|
|
105
|
+
)}:${pad(date.getUTCMinutes())}`;
|
|
106
|
+
}
|
|
107
|
+
function buildJql(since, projectKeys) {
|
|
108
|
+
const clauses = [`updated >= "${toJqlDateTime(since)}"`];
|
|
109
|
+
if (projectKeys.length > 0) {
|
|
110
|
+
clauses.push(`project in (${projectKeys.join(", ")})`);
|
|
111
|
+
}
|
|
112
|
+
return `${clauses.join(" AND ")} ORDER BY updated ASC`;
|
|
113
|
+
}
|
|
114
|
+
function adfToText(value) {
|
|
115
|
+
if (typeof value === "string") return value;
|
|
116
|
+
if (!value || typeof value !== "object") return "";
|
|
117
|
+
const walk = (node) => {
|
|
118
|
+
if (typeof node.text === "string") return node.text;
|
|
119
|
+
const children = Array.isArray(node.content) ? node.content.map(walk) : [];
|
|
120
|
+
const isBlock = node.type === "paragraph" || node.type === "heading" || node.type === "listItem";
|
|
121
|
+
return isBlock ? `${children.join("")}
|
|
122
|
+
` : children.join("");
|
|
123
|
+
};
|
|
124
|
+
return walk(value).replace(/\n{3,}/g, "\n\n").trim();
|
|
125
|
+
}
|
|
126
|
+
function parsePullCursor(cursor) {
|
|
127
|
+
if (!cursor) return void 0;
|
|
128
|
+
try {
|
|
129
|
+
const parsed = JSON.parse(cursor);
|
|
130
|
+
if (parsed && typeof parsed.s === "string") return parsed;
|
|
131
|
+
} catch {
|
|
132
|
+
}
|
|
133
|
+
return void 0;
|
|
134
|
+
}
|
|
135
|
+
function resolveCredentials(config, settings) {
|
|
136
|
+
const baseUrl = normalizeBaseUrl(config?.baseUrl) ?? normalizeBaseUrl(settings?.baseUrl);
|
|
137
|
+
const emailRaw = config?.email ?? settings?.email;
|
|
138
|
+
const tokenRaw = config?.apiToken ?? settings?.apiToken;
|
|
139
|
+
if (baseUrl && typeof emailRaw === "string" && emailRaw.length > 0 && typeof tokenRaw === "string" && tokenRaw.length > 0) {
|
|
140
|
+
return { baseUrl, email: emailRaw, apiToken: tokenRaw };
|
|
141
|
+
}
|
|
142
|
+
return void 0;
|
|
143
|
+
}
|
|
144
|
+
function resolveIssueKey(config, options) {
|
|
145
|
+
const candidates = [
|
|
146
|
+
config.issueKey,
|
|
147
|
+
config.issueIdOrKey,
|
|
148
|
+
config.defaultIssueKey,
|
|
149
|
+
options.settings?.defaultIssueKey
|
|
150
|
+
];
|
|
151
|
+
for (const c of candidates) {
|
|
152
|
+
if (typeof c === "string" && c.length > 0) return c;
|
|
153
|
+
}
|
|
154
|
+
throw new Error("jira-connector: an issue key is required (targetConfig.issueKey or defaultIssueKey)");
|
|
155
|
+
}
|
|
156
|
+
var JiraConnectorPlugin = class {
|
|
157
|
+
constructor() {
|
|
158
|
+
this.id = "jira-connector";
|
|
159
|
+
this.name = "JIRA Connector";
|
|
160
|
+
this.version = "1.0.0";
|
|
161
|
+
this.category = "connector";
|
|
162
|
+
this.capabilities = [PLUGIN_CAPABILITIES.CONNECTOR, PLUGIN_CAPABILITIES.EVENT_SOURCE];
|
|
163
|
+
this.providerName = "jira";
|
|
164
|
+
this.connector = {
|
|
165
|
+
direction: "outbound",
|
|
166
|
+
transport: "poll",
|
|
167
|
+
flags: {
|
|
168
|
+
outboundMessage: true,
|
|
169
|
+
outboundRecord: false,
|
|
170
|
+
inbound: false,
|
|
171
|
+
reply: false,
|
|
172
|
+
pairing: false,
|
|
173
|
+
richOutbound: false
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
this.settingsSchema = {
|
|
177
|
+
type: "object",
|
|
178
|
+
required: ["baseUrl", "email", "apiToken"],
|
|
179
|
+
properties: {
|
|
180
|
+
baseUrl: {
|
|
181
|
+
type: "string",
|
|
182
|
+
title: "JIRA site base URL (https://your-site.atlassian.net)",
|
|
183
|
+
"x-envVar": "JIRA_BASE_URL"
|
|
184
|
+
},
|
|
185
|
+
email: {
|
|
186
|
+
type: "string",
|
|
187
|
+
title: "Atlassian account email (API-token basic auth)",
|
|
188
|
+
"x-envVar": "JIRA_EMAIL"
|
|
189
|
+
},
|
|
190
|
+
apiToken: {
|
|
191
|
+
type: "string",
|
|
192
|
+
title: "Atlassian API token",
|
|
193
|
+
"x-secret": true,
|
|
194
|
+
"x-envVar": "JIRA_API_TOKEN"
|
|
195
|
+
},
|
|
196
|
+
projectKeys: {
|
|
197
|
+
type: "string",
|
|
198
|
+
title: "Project keys to ingest events from (comma-separated; all projects when empty)"
|
|
199
|
+
},
|
|
200
|
+
backfillDays: {
|
|
201
|
+
type: "number",
|
|
202
|
+
title: "Historical backfill window in days on first pull (0 = off, max 90)",
|
|
203
|
+
default: 0,
|
|
204
|
+
minimum: 0,
|
|
205
|
+
maximum: 90
|
|
206
|
+
},
|
|
207
|
+
defaultIssueKey: {
|
|
208
|
+
type: "string",
|
|
209
|
+
title: "Default issue key for outbound comments (e.g. ENG-42)"
|
|
210
|
+
},
|
|
211
|
+
webhookSecret: {
|
|
212
|
+
type: "string",
|
|
213
|
+
title: "Webhook secret",
|
|
214
|
+
description: "Secret set on the Jira Cloud webhook that points at the platform ingest receiver (POST /api/ingest/jira/events). Jira signs every delivery with it (X-Hub-Signature, HMAC SHA-256); deliveries with a missing or mismatched signature are rejected, so a webhook created without a secret never files anything. Leave blank to keep the inbound receiver disabled for your account.",
|
|
215
|
+
"x-secret": true,
|
|
216
|
+
"x-scope": "user",
|
|
217
|
+
"x-widget": "password"
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
this.idempotencyCache = /* @__PURE__ */ new Map();
|
|
222
|
+
}
|
|
223
|
+
async onLoad() {
|
|
224
|
+
}
|
|
225
|
+
async onUnload() {
|
|
226
|
+
this.idempotencyCache.clear();
|
|
227
|
+
}
|
|
228
|
+
/** Testable seam — specs stub this; production uses the real SDK. */
|
|
229
|
+
createClient(credentials) {
|
|
230
|
+
const client = new jira_js.Version3Client({
|
|
231
|
+
host: credentials.baseUrl,
|
|
232
|
+
authentication: { basic: { email: credentials.email, apiToken: credentials.apiToken } }
|
|
233
|
+
});
|
|
234
|
+
return {
|
|
235
|
+
getCurrentUser: () => client.myself.getCurrentUser(),
|
|
236
|
+
searchIssues: async (params) => await client.issueSearch.searchForIssuesUsingJqlEnhancedSearch({
|
|
237
|
+
jql: params.jql,
|
|
238
|
+
maxResults: params.maxResults,
|
|
239
|
+
fields: params.fields,
|
|
240
|
+
...params.nextPageToken ? { nextPageToken: params.nextPageToken } : {}
|
|
241
|
+
}),
|
|
242
|
+
addComment: (params) => client.issueComments.addComment({ issueIdOrKey: params.issueIdOrKey, comment: params.comment })
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
async verifyConnection(config, options) {
|
|
246
|
+
const credentials = resolveCredentials(config, options.settings);
|
|
247
|
+
if (!credentials) {
|
|
248
|
+
return {
|
|
249
|
+
valid: false,
|
|
250
|
+
message: "baseUrl (https site URL), email and apiToken are required"
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
try {
|
|
254
|
+
const user = await this.createClient(credentials).getCurrentUser();
|
|
255
|
+
return {
|
|
256
|
+
valid: true,
|
|
257
|
+
details: {
|
|
258
|
+
site: credentials.baseUrl,
|
|
259
|
+
accountId: user?.accountId,
|
|
260
|
+
displayName: user?.displayName
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
} catch (err) {
|
|
264
|
+
return { valid: false, message: `JIRA current-user lookup failed: ${jiraErrorMessage(err)}` };
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
/** Outbound leg — create a comment on a JIRA issue. */
|
|
268
|
+
async send(payload, options) {
|
|
269
|
+
const config = payload.target ?? options.target ?? {};
|
|
270
|
+
const credentials = resolveCredentials(config, options.settings);
|
|
271
|
+
if (!credentials) {
|
|
272
|
+
throw new Error(
|
|
273
|
+
"jira-connector: baseUrl (https site URL), email and apiToken are required to post a comment"
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
const issueKey = resolveIssueKey(config, options);
|
|
277
|
+
const cacheKey = `${options.connectorId ?? ""}\0${issueKey}\0${payload.messageRef}`;
|
|
278
|
+
const cached = this.idempotencyCache.get(cacheKey);
|
|
279
|
+
if (cached) return cached;
|
|
280
|
+
let commentId;
|
|
281
|
+
try {
|
|
282
|
+
const res = await this.createClient(credentials).addComment({
|
|
283
|
+
issueIdOrKey: issueKey,
|
|
284
|
+
comment: payload.text
|
|
285
|
+
});
|
|
286
|
+
commentId = typeof res?.id === "string" ? res.id : void 0;
|
|
287
|
+
} catch (err) {
|
|
288
|
+
throw new Error(`JIRA addComment failed: ${jiraErrorMessage(err)}`);
|
|
289
|
+
}
|
|
290
|
+
const result = {
|
|
291
|
+
provider: this.id,
|
|
292
|
+
providerMessageId: commentId ?? `jira-${payload.messageRef}`,
|
|
293
|
+
deliveredAt: /* @__PURE__ */ new Date()
|
|
294
|
+
};
|
|
295
|
+
this.idempotencyCache.set(cacheKey, result);
|
|
296
|
+
if (this.idempotencyCache.size > 500) {
|
|
297
|
+
const firstKey = this.idempotencyCache.keys().next().value;
|
|
298
|
+
if (firstKey) this.idempotencyCache.delete(firstKey);
|
|
299
|
+
}
|
|
300
|
+
return result;
|
|
301
|
+
}
|
|
302
|
+
// ── Event source (pull) ─────────────────────────────────────────────
|
|
303
|
+
/**
|
|
304
|
+
* Pull one JQL page of issues updated since the effective watermark,
|
|
305
|
+
* normalized to `jira.issue` envelopes plus a `jira.comment` envelope
|
|
306
|
+
* per comment that changed inside the same window. The returned
|
|
307
|
+
* cursor resumes the sweep (API page token); no cursor means the
|
|
308
|
+
* sweep is done.
|
|
309
|
+
*
|
|
310
|
+
* First pull (epoch/absent watermark, no cursor): the window is
|
|
311
|
+
* `now - backfillDays` when the opt-in backfill is on, otherwise
|
|
312
|
+
* `now` — history stays untouched unless the user asked for it.
|
|
313
|
+
*/
|
|
314
|
+
async pullEvents(input) {
|
|
315
|
+
const credentials = resolveCredentials(void 0, input.settings);
|
|
316
|
+
if (!credentials) {
|
|
317
|
+
throw new EventSourceNotConfiguredError(
|
|
318
|
+
"jira-connector: settings.baseUrl (https site URL), settings.email and settings.apiToken are required to pull events"
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
const cursor = parsePullCursor(input.cursor);
|
|
322
|
+
let pageToken;
|
|
323
|
+
let since;
|
|
324
|
+
let backfill;
|
|
325
|
+
let pagesUsed;
|
|
326
|
+
if (cursor) {
|
|
327
|
+
pageToken = cursor.n;
|
|
328
|
+
since = cursor.s;
|
|
329
|
+
backfill = cursor.f === 1;
|
|
330
|
+
pagesUsed = cursor.b ?? 0;
|
|
331
|
+
} else {
|
|
332
|
+
const sinceMs = Date.parse(input.since);
|
|
333
|
+
const firstPull = !Number.isFinite(sinceMs) || sinceMs <= 0;
|
|
334
|
+
const backfillDays = clampBackfillDays(input.settings?.backfillDays);
|
|
335
|
+
if (firstPull) {
|
|
336
|
+
const start = backfillDays > 0 ? Date.now() - backfillDays * 864e5 : Date.now();
|
|
337
|
+
since = new Date(start).toISOString();
|
|
338
|
+
backfill = backfillDays > 0;
|
|
339
|
+
} else {
|
|
340
|
+
since = new Date(sinceMs).toISOString();
|
|
341
|
+
backfill = false;
|
|
342
|
+
}
|
|
343
|
+
pageToken = void 0;
|
|
344
|
+
pagesUsed = 0;
|
|
345
|
+
}
|
|
346
|
+
const client = this.createClient(credentials);
|
|
347
|
+
const projectKeys = resolveProjectKeys(input.settings);
|
|
348
|
+
const page = await client.searchIssues({
|
|
349
|
+
jql: buildJql(since, projectKeys),
|
|
350
|
+
maxResults: JIRA_PULL_PAGE_SIZE,
|
|
351
|
+
fields: [...JIRA_ISSUE_FIELDS],
|
|
352
|
+
...pageToken ? { nextPageToken: pageToken } : {}
|
|
353
|
+
});
|
|
354
|
+
const events = [];
|
|
355
|
+
for (const issue of page.issues ?? []) {
|
|
356
|
+
const issueEnvelope = this.normalizeIssue(issue, since, credentials.baseUrl);
|
|
357
|
+
if (issueEnvelope) events.push(issueEnvelope);
|
|
358
|
+
for (const comment of issue.fields?.comment?.comments ?? []) {
|
|
359
|
+
const commentEnvelope = this.normalizeComment(issue, comment, since, credentials.baseUrl);
|
|
360
|
+
if (commentEnvelope) events.push(commentEnvelope);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
pagesUsed += 1;
|
|
364
|
+
const pageBudgetExhausted = backfill && pagesUsed >= JIRA_BACKFILL_MAX_PAGES;
|
|
365
|
+
const nextPageToken = typeof page.nextPageToken === "string" && page.nextPageToken.length > 0 ? page.nextPageToken : void 0;
|
|
366
|
+
const next = nextPageToken && !pageBudgetExhausted ? { n: nextPageToken, s: since, ...backfill ? { f: 1 } : {}, b: pagesUsed } : void 0;
|
|
367
|
+
return next ? { events, nextCursor: JSON.stringify(next) } : { events };
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Bounded HISTORICAL sweep from an explicit `since` — the
|
|
371
|
+
* capability's opt-in `backfill()` method.
|
|
372
|
+
*
|
|
373
|
+
* Before this method existed, history was reachable only as a side
|
|
374
|
+
* effect of the FIRST pull (`settings.backfillDays` widening the
|
|
375
|
+
* initial window), so a user who activated the connector without the
|
|
376
|
+
* setting could never go back and fetch it. `backfill()` runs the
|
|
377
|
+
* same JQL sweep out-of-band on a caller-chosen window, as many times
|
|
378
|
+
* as wanted — re-delivery is free because the ingest pipeline dedupes
|
|
379
|
+
* on `(source, sourceEventId)`.
|
|
380
|
+
*
|
|
381
|
+
* `until` is accepted for contract symmetry but NOT applied: the
|
|
382
|
+
* sweep's JQL bounds only the near end (`updated >= since`). An
|
|
383
|
+
* over-wide window costs duplicate deliveries, which the pipeline
|
|
384
|
+
* drops — never wrong data.
|
|
385
|
+
*
|
|
386
|
+
* The page bound (`JIRA_BACKFILL_MAX_PAGES`) applies here too: one
|
|
387
|
+
* call fetches ONE page and hands back a cursor, so a large project
|
|
388
|
+
* can never turn a backfill into an unbounded crawl.
|
|
389
|
+
*/
|
|
390
|
+
async backfill(input) {
|
|
391
|
+
const sinceMs = Date.parse(input.since);
|
|
392
|
+
if (!Number.isFinite(sinceMs)) {
|
|
393
|
+
throw new EventSourceNotConfiguredError(
|
|
394
|
+
`jira-connector: backfill requires a valid ISO 8601 "since" (received ${JSON.stringify(input.since)})`
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
const cursor = input.cursor ?? JSON.stringify({
|
|
398
|
+
s: new Date(sinceMs).toISOString(),
|
|
399
|
+
f: 1,
|
|
400
|
+
b: 0
|
|
401
|
+
});
|
|
402
|
+
const page = await this.pullEvents({
|
|
403
|
+
since: input.since,
|
|
404
|
+
cursor,
|
|
405
|
+
...input.settings ? { settings: input.settings } : {}
|
|
406
|
+
});
|
|
407
|
+
return page.nextCursor ? { events: page.events, nextCursor: page.nextCursor } : { events: page.events, complete: true };
|
|
408
|
+
}
|
|
409
|
+
normalizeIssue(issue, since, baseUrl) {
|
|
410
|
+
if (!issue.id) return null;
|
|
411
|
+
const fields = issue.fields ?? {};
|
|
412
|
+
const updatedAt = toIso(fields.updated ?? fields.created);
|
|
413
|
+
const createdAt = toIso(fields.created);
|
|
414
|
+
const changeType = Date.parse(createdAt) >= Date.parse(since) ? "created" : "updated";
|
|
415
|
+
const projectKey = fields.project?.key;
|
|
416
|
+
const description = adfToText(fields.description);
|
|
417
|
+
return {
|
|
418
|
+
id: crypto.randomUUID(),
|
|
419
|
+
source: this.id,
|
|
420
|
+
sourceEventId: `${issue.id}:${updatedAt}`,
|
|
421
|
+
kind: "jira.issue",
|
|
422
|
+
occurredAt: updatedAt,
|
|
423
|
+
subject: {
|
|
424
|
+
type: "issue",
|
|
425
|
+
externalId: issue.id,
|
|
426
|
+
...fields.summary ? { title: fields.summary } : {}
|
|
427
|
+
},
|
|
428
|
+
// Work routing: the project is the container an Ever Works Work
|
|
429
|
+
// maps onto. Issues without a project stay user-scoped.
|
|
430
|
+
...projectKey ? {
|
|
431
|
+
workHint: {
|
|
432
|
+
kind: "tracker-team",
|
|
433
|
+
externalId: projectKey,
|
|
434
|
+
...fields.project?.name ? { label: fields.project.name } : {}
|
|
435
|
+
}
|
|
436
|
+
} : {},
|
|
437
|
+
...issue.key ? { sourceUrl: `${baseUrl}/browse/${issue.key}` } : {},
|
|
438
|
+
payload: {
|
|
439
|
+
issueId: issue.id,
|
|
440
|
+
...issue.key ? { issueKey: issue.key } : {},
|
|
441
|
+
...projectKey ? { projectKey } : {},
|
|
442
|
+
...fields.summary ? { summary: truncateText(fields.summary) } : {},
|
|
443
|
+
...description ? { description: truncateText(description) } : {},
|
|
444
|
+
...fields.status?.name ? { status: fields.status.name } : {},
|
|
445
|
+
...fields.issuetype?.name ? { issueType: fields.issuetype.name } : {},
|
|
446
|
+
changeType,
|
|
447
|
+
createdAt,
|
|
448
|
+
updatedAt
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Normalize one comment → envelope, or null when the comment did NOT
|
|
454
|
+
* change inside the sweep window. Commenting bumps the parent issue's
|
|
455
|
+
* `updated`, so an issue can arrive with a long comment history of
|
|
456
|
+
* which only the newest entry is actually news.
|
|
457
|
+
*/
|
|
458
|
+
normalizeComment(issue, comment, since, baseUrl) {
|
|
459
|
+
if (!comment.id) return null;
|
|
460
|
+
const updatedAt = toIso(comment.updated ?? comment.created);
|
|
461
|
+
if (Date.parse(updatedAt) < Date.parse(since)) return null;
|
|
462
|
+
const fields = issue.fields ?? {};
|
|
463
|
+
const projectKey = fields.project?.key;
|
|
464
|
+
const body = adfToText(comment.body);
|
|
465
|
+
const sourceUrl = issue.key ? `${baseUrl}/browse/${issue.key}?focusedCommentId=${encodeURIComponent(comment.id)}` : void 0;
|
|
466
|
+
return {
|
|
467
|
+
id: crypto.randomUUID(),
|
|
468
|
+
source: this.id,
|
|
469
|
+
sourceEventId: `${comment.id}:${updatedAt}`,
|
|
470
|
+
kind: "jira.comment",
|
|
471
|
+
occurredAt: updatedAt,
|
|
472
|
+
...comment.author?.displayName ? {
|
|
473
|
+
actor: {
|
|
474
|
+
name: comment.author.displayName,
|
|
475
|
+
...comment.author.accountId ? { externalId: comment.author.accountId } : {}
|
|
476
|
+
}
|
|
477
|
+
} : {},
|
|
478
|
+
subject: {
|
|
479
|
+
type: "issue",
|
|
480
|
+
externalId: issue.id ?? "unknown",
|
|
481
|
+
...fields.summary ? { title: fields.summary } : {}
|
|
482
|
+
},
|
|
483
|
+
// Same project-as-container routing as issues.
|
|
484
|
+
...projectKey ? {
|
|
485
|
+
workHint: {
|
|
486
|
+
kind: "tracker-team",
|
|
487
|
+
externalId: projectKey,
|
|
488
|
+
...fields.project?.name ? { label: fields.project.name } : {}
|
|
489
|
+
}
|
|
490
|
+
} : {},
|
|
491
|
+
...sourceUrl ? { sourceUrl } : {},
|
|
492
|
+
payload: {
|
|
493
|
+
commentId: comment.id,
|
|
494
|
+
...issue.id ? { issueId: issue.id } : {},
|
|
495
|
+
...issue.key ? { issueKey: issue.key } : {},
|
|
496
|
+
...projectKey ? { projectKey } : {},
|
|
497
|
+
...body ? { body: truncateText(body) } : {},
|
|
498
|
+
createdAt: toIso(comment.created),
|
|
499
|
+
updatedAt
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
var jiraConnectorPlugin = new JiraConnectorPlugin();
|
|
505
|
+
|
|
506
|
+
exports.JIRA_BACKFILL_MAX_PAGES = JIRA_BACKFILL_MAX_PAGES;
|
|
507
|
+
exports.JIRA_EVENT_TEXT_MAX_CHARS = JIRA_EVENT_TEXT_MAX_CHARS;
|
|
508
|
+
exports.JIRA_ISSUE_FIELDS = JIRA_ISSUE_FIELDS;
|
|
509
|
+
exports.JIRA_PULL_PAGE_SIZE = JIRA_PULL_PAGE_SIZE;
|
|
510
|
+
exports.JiraConnectorPlugin = JiraConnectorPlugin;
|
|
511
|
+
exports.adfToText = adfToText;
|
|
512
|
+
exports.buildJql = buildJql;
|
|
513
|
+
exports.clampBackfillDays = clampBackfillDays;
|
|
514
|
+
exports.default = JiraConnectorPlugin;
|
|
515
|
+
exports.jiraConnectorPlugin = jiraConnectorPlugin;
|
|
516
|
+
exports.normalizeBaseUrl = normalizeBaseUrl;
|
|
517
|
+
exports.resolveProjectKeys = resolveProjectKeys;
|
|
518
|
+
exports.toJqlDateTime = toJqlDateTime;
|