@moxxy/factorix-plugin-sdk 0.0.0-stage → 0.2.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/plugin.js ADDED
@@ -0,0 +1,288 @@
1
+ import { DELIVERY_HEADER, readPageToken, SIGNATURE_HEADER, sign, TIMESTAMP_HEADER, verify } from './signing.js';
2
+ import { PROTOCOL, } from './types.js';
3
+ export function definePlugin(definition) {
4
+ const pages = (definition.pages ?? []).map((page) => ({
5
+ key: page.key,
6
+ label: page.label,
7
+ path: page.path ?? `/pages/${page.key}`,
8
+ placement: page.placement ?? 'sidebar',
9
+ }));
10
+ for (const page of pages)
11
+ if (!page.path.startsWith('/') || page.path.startsWith('//'))
12
+ throw new Error(`Page ${page.key} needs a path that starts with one slash`);
13
+ const blocks = (definition.blocks ?? []).map((block) => ({
14
+ key: block.key,
15
+ title: block.title,
16
+ description: block.description,
17
+ fields: block.fields ?? [],
18
+ outputs: block.outputs ?? [{ id: 'next', label: 'Next' }],
19
+ provides: block.provides ?? [],
20
+ }));
21
+ for (const block of blocks) {
22
+ if (!/^[a-z][a-z0-9_]{0,39}$/.test(block.key))
23
+ throw new Error(`Block ${block.key} needs a key of lowercase letters, digits, and underscores`);
24
+ if (blocks.filter((other) => other.key === block.key).length > 1)
25
+ throw new Error(`Two blocks share the key ${block.key}`);
26
+ if (block.outputs.some((output) => output.id === 'failed'))
27
+ throw new Error(`Block ${block.key} cannot name an output failed, which every block has`);
28
+ }
29
+ const triggers = (definition.triggers ?? []).map((trigger) => ({
30
+ key: trigger.key,
31
+ title: trigger.title,
32
+ description: trigger.description,
33
+ fields: trigger.fields ?? [],
34
+ provides: trigger.provides ?? [],
35
+ }));
36
+ for (const trigger of triggers) {
37
+ if (!/^[a-z][a-z0-9_]{0,39}$/.test(trigger.key))
38
+ throw new Error(`Trigger ${trigger.key} needs a key of lowercase letters, digits, and underscores`);
39
+ if ([...blocks, ...triggers].filter((other) => other.key === trigger.key).length > 1)
40
+ throw new Error(`Two blocks or triggers share the key ${trigger.key}`);
41
+ if (trigger.fields.some((field) => field.kind !== 'text' && field.kind !== 'select'))
42
+ throw new Error(`The fields of trigger ${trigger.key} can only be text or select`);
43
+ }
44
+ if (!definition.tracker && pages.length === 0 && blocks.length === 0 && triggers.length === 0)
45
+ throw new Error('A plugin needs a tracker, a page, or a block');
46
+ const workflows = blocks.length + triggers.length > 0;
47
+ const permissions = [...(definition.permissions ?? []), ...(workflows ? ['workflows:blocks'] : [])];
48
+ return {
49
+ ...definition,
50
+ manifest: {
51
+ protocol: PROTOCOL,
52
+ name: definition.name,
53
+ version: definition.version,
54
+ ...(definition.description ? { description: definition.description } : {}),
55
+ provides: definition.tracker ? ['tracker'] : [],
56
+ permissions: [...new Set(permissions)],
57
+ connection: { fields: definition.connection?.fields ?? [] },
58
+ settings: { fields: definition.settings?.fields ?? [] },
59
+ pages,
60
+ blocks,
61
+ triggers,
62
+ },
63
+ };
64
+ }
65
+ const TRACKER_METHODS = new Set([
66
+ 'viewer',
67
+ 'listTeams',
68
+ 'listProjects',
69
+ 'listWorkflowStates',
70
+ 'listLabels',
71
+ 'listIssues',
72
+ 'getIssue',
73
+ 'listComments',
74
+ 'listResources',
75
+ 'createIssue',
76
+ 'updateIssueState',
77
+ 'updateIssueLabels',
78
+ 'createLabel',
79
+ 'comment',
80
+ 'updateComment',
81
+ 'registerWebhook',
82
+ ]);
83
+ /** What Factorix gets when a tracker leaves an optional method out. */
84
+ const DEFAULTS = { listProjects: [], listResources: [], updateComment: null, registerWebhook: { id: 'none' } };
85
+ const MAX_BODY_BYTES = 2 * 1024 * 1024;
86
+ const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
87
+ /**
88
+ * Serves a plugin from any runtime that speaks `Request` and `Response`. Calls from Factorix arrive as POST on `path`,
89
+ * signed, and pages as GET under it with a signed `factorix` parameter. Anything else gets a 404 or a 401.
90
+ */
91
+ export function createHandler(plugin, options) {
92
+ const base = (options.path ?? '/factorix').replace(/\/$/, '');
93
+ if (options.secret.length < 16)
94
+ throw new Error('The plugin secret must be at least 16 characters');
95
+ const rpc = async (request) => {
96
+ const raw = new Uint8Array(await request.arrayBuffer());
97
+ if (raw.byteLength > MAX_BODY_BYTES)
98
+ return json(413, { error: { message: 'Request too large' } });
99
+ if (!verify(options.secret, request.headers.get(TIMESTAMP_HEADER), request.headers.get(SIGNATURE_HEADER), raw)) {
100
+ return json(401, { error: { message: 'Signature check failed. The secret here must match the one typed into Factorix' } });
101
+ }
102
+ let call;
103
+ try {
104
+ call = JSON.parse(new TextDecoder().decode(raw));
105
+ }
106
+ catch {
107
+ return json(400, { error: { message: 'The body is not JSON' } });
108
+ }
109
+ if (call.protocol !== PROTOCOL)
110
+ return json(400, { error: { message: `This plugin speaks protocol ${PROTOCOL}` } });
111
+ if (call.method === 'manifest')
112
+ return json(200, { result: plugin.manifest });
113
+ if (call.method === 'workflow.block' || call.method === 'workflow.options')
114
+ return workflow(call.method, call.params?.[0]);
115
+ const [scope, method] = String(call.method).split('.');
116
+ if (scope !== 'tracker' || !method || !TRACKER_METHODS.has(method) || !plugin.tracker || !call.connection) {
117
+ return json(404, { error: { message: `Unknown method ${String(call.method)}` } });
118
+ }
119
+ try {
120
+ const tracker = plugin.tracker(call.connection);
121
+ const implemented = tracker[method];
122
+ if (!implemented)
123
+ return method in DEFAULTS ? json(200, { result: DEFAULTS[method] }) : json(404, { error: { message: `The tracker has no ${method}` } });
124
+ const result = await implemented.apply(tracker, Array.isArray(call.params) ? call.params : []);
125
+ return json(200, { result: result ?? null });
126
+ }
127
+ catch (error) {
128
+ return json(500, { error: { message: error instanceof Error ? error.message : 'The plugin failed' } });
129
+ }
130
+ };
131
+ const workflow = async (method, input) => {
132
+ const name = input?.block;
133
+ const block = plugin.blocks?.find((candidate) => candidate.key === name);
134
+ // A trigger's dynamic fields are asked for under the same method, by its key.
135
+ const trigger = method === 'workflow.options' ? plugin.triggers?.find((candidate) => candidate.key === name) : undefined;
136
+ if (trigger) {
137
+ if (!trigger.options)
138
+ return json(404, { error: { message: `Trigger ${trigger.key} lists no choices` } });
139
+ const { field, org } = input;
140
+ return json(200, { result: await trigger.options({ field, org }) });
141
+ }
142
+ if (!block)
143
+ return json(404, { error: { message: `This plugin has no block ${String(name)}` } });
144
+ try {
145
+ if (method === 'workflow.block')
146
+ return json(200, { result: await block.run(input) });
147
+ if (!block.options)
148
+ return json(404, { error: { message: `Block ${block.key} lists no choices` } });
149
+ const { field, org } = input;
150
+ return json(200, { result: await block.options({ field, org }) });
151
+ }
152
+ catch (error) {
153
+ return json(500, { error: { message: error instanceof Error ? error.message : 'The block failed' } });
154
+ }
155
+ };
156
+ return async (request) => {
157
+ const url = new URL(request.url);
158
+ if (request.method === 'POST' && url.pathname === (base || '/'))
159
+ return rpc(request);
160
+ const page = plugin.pages?.find((candidate) => base + (candidate.path ?? `/pages/${candidate.key}`) === url.pathname);
161
+ const handle = request.method === 'GET' ? page?.render : request.method === 'POST' ? page?.action : undefined;
162
+ if (!page || !handle)
163
+ return json(404, { error: { message: 'Not found' } });
164
+ const token = url.searchParams.get('factorix') ?? request.headers.get('x-factorix-page') ?? '';
165
+ const context = readPageToken(options.secret, token);
166
+ if (!context || context.page !== page.key) {
167
+ const where = (page.placement ?? 'sidebar') === 'settings' ? 'under Settings, Plugins' : 'in the sidebar';
168
+ return new Response(`This page opens from inside Factorix, and each opening lasts a few minutes. Open ${page.label} again ${where}.`, {
169
+ status: 401,
170
+ headers: { 'content-type': 'text/plain; charset=utf-8' },
171
+ });
172
+ }
173
+ const rendered = await handle.call(page, context, request, token);
174
+ if (rendered instanceof Response)
175
+ return rendered;
176
+ return new Response(rendered, {
177
+ headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' },
178
+ });
179
+ };
180
+ }
181
+ /** A call Factorix refused. `status` is 403 for a permission the organization did not allow, and 404 when it has not turned the plugin on. */
182
+ export class FactorixError extends Error {
183
+ status;
184
+ constructor(status, message) {
185
+ super(message);
186
+ this.status = status;
187
+ this.name = 'FactorixError';
188
+ }
189
+ }
190
+ /** The calls a plugin makes to Factorix, signed with the shared secret. Every call but `sendEvent` acts for one organization. */
191
+ export function factorix(options) {
192
+ const send = options.fetch ?? fetch;
193
+ const post = async (target, body, headers = {}) => {
194
+ const text = JSON.stringify(body);
195
+ const timestamp = String(Date.now());
196
+ const response = await send(target, {
197
+ method: 'POST',
198
+ headers: {
199
+ 'content-type': 'application/json',
200
+ [TIMESTAMP_HEADER]: timestamp,
201
+ [SIGNATURE_HEADER]: sign(options.secret, timestamp, text),
202
+ ...headers,
203
+ },
204
+ body: text,
205
+ });
206
+ const raw = await response.text();
207
+ let answer = null;
208
+ try {
209
+ answer = JSON.parse(raw);
210
+ }
211
+ catch { }
212
+ if (!response.ok) {
213
+ const message = typeof answer?.error === 'object' ? answer.error.message : (answer?.message ?? raw);
214
+ throw new FactorixError(response.status, `Factorix answered ${response.status}: ${String(message).slice(0, 300)}`);
215
+ }
216
+ return answer;
217
+ };
218
+ const origin = options.url.replace(/\/$/, '');
219
+ const call = (path, orgId, body = {}) => {
220
+ if (!options.pluginId)
221
+ throw new Error(`Calling Factorix for ${path} needs the pluginId, which pages get as context.plugin.id`);
222
+ return post(`${origin}/webhooks/plugins/${options.pluginId}/${path}`, { ...body, orgId });
223
+ };
224
+ return {
225
+ /**
226
+ * Tells Factorix something changed. `callbackUrl` is the address `registerWebhook` was given, or the connection's
227
+ * id. Give a `deliveryId` when the source has one, and a repeated delivery is dropped.
228
+ */
229
+ async sendEvent(callbackUrl, event, deliveryId) {
230
+ const target = callbackUrl.startsWith('http') ? callbackUrl : `${origin}/webhooks/plugin/${callbackUrl}`;
231
+ await post(target, { event }, deliveryId ? { [DELIVERY_HEADER]: deliveryId } : {});
232
+ },
233
+ /** What an organization set for this plugin, secret fields included. */
234
+ async settings(orgId) {
235
+ return (await call('settings', orgId));
236
+ },
237
+ /** What happened on the organization's tickets since `since`, at most 31 days back. Needs `activity:read`. */
238
+ async activity(orgId, since) {
239
+ return (await call('activity', orgId, { since: new Date(since).toISOString() })).activity;
240
+ },
241
+ /** The organization's agents. Needs `agents:run`. */
242
+ async agents(orgId) {
243
+ return (await call('agents', orgId)).agents;
244
+ },
245
+ /**
246
+ * Asks one of the organization's agents for work, in a run with no ticket and no repository. The run is queued and
247
+ * the answer comes later: read it with `getRun`. At most three of a plugin's runs are unfinished at once. Needs `agents:run`.
248
+ */
249
+ async startRun(orgId, request) {
250
+ return (await call('runs', orgId, { ...request })).run;
251
+ },
252
+ /** A run this plugin started, with the agent's answer once it succeeded. Needs `agents:run`. */
253
+ async getRun(orgId, runId) {
254
+ return (await call(`runs/${encodeURIComponent(runId)}`, orgId)).run;
255
+ },
256
+ /** The people and agents of the organization. Needs `members:read`. */
257
+ async members(orgId) {
258
+ return (await call('members', orgId)).members;
259
+ },
260
+ /** The projects a ticket can be created in. Needs `tickets:write`. */
261
+ async projects(orgId) {
262
+ return (await call('projects', orgId)).projects;
263
+ },
264
+ /** Creates a ticket in one of the organization's projects, in whatever tracker that project follows. Needs `tickets:write`. */
265
+ async createTicket(orgId, request) {
266
+ return (await call('tickets', orgId, { ...request })).ticket;
267
+ },
268
+ /** A ticket this plugin created, as it stands now. Needs `tickets:write`. */
269
+ async getTicket(orgId, ticketId) {
270
+ return (await call(`tickets/${encodeURIComponent(ticketId)}`, orgId)).ticket;
271
+ },
272
+ /**
273
+ * Ends a step one of your blocks held with `{ wait: true }`. `handle` and `output` work as in the block's answer, and
274
+ * `error` fails the step instead. Throws `FactorixError` 409 once the step has ended. Needs `workflows:blocks`.
275
+ */
276
+ async finishStep(orgId, step) {
277
+ await call('workflow-steps', orgId, { ...step });
278
+ },
279
+ /**
280
+ * Reports that one of your triggers happened, and starts the organization's workflows built on it. `data` holds the
281
+ * values its fields are compared with and what it provides, as texts; other keys are dropped. Sending the same
282
+ * `eventId` again starts nothing new, so a retry is safe. Answers how many workflows started. Needs `workflows:blocks`.
283
+ */
284
+ async fireTrigger(orgId, event) {
285
+ return Number((await call('workflow-triggers', orgId, { ...event })).started ?? 0);
286
+ },
287
+ };
288
+ }
package/signing.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { PageContext } from './types.js';
2
+ export declare const SIGNATURE_HEADER = "x-factorix-signature";
3
+ export declare const TIMESTAMP_HEADER = "x-factorix-timestamp";
4
+ export declare const DELIVERY_HEADER = "x-factorix-delivery";
5
+ export declare function sign(secret: string, timestamp: string, body: string | Uint8Array): string;
6
+ /** The timestamp is signed with the body, so a captured request stops working after a few minutes. */
7
+ export declare function verify(secret: string, timestamp: string | null | undefined, signature: string | null | undefined, body: string | Uint8Array, now?: number): boolean;
8
+ /** Reads the `factorix` parameter of a page address. Returns nothing for a forged or expired one. */
9
+ export declare function readPageToken(secret: string, token: string | null | undefined, now?: number): PageContext | null;
10
+ export declare function signPageToken(secret: string, context: PageContext): string;
package/signing.js ADDED
@@ -0,0 +1,38 @@
1
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
2
+ export const SIGNATURE_HEADER = 'x-factorix-signature';
3
+ export const TIMESTAMP_HEADER = 'x-factorix-timestamp';
4
+ export const DELIVERY_HEADER = 'x-factorix-delivery';
5
+ const TOLERANCE_MS = 5 * 60_000;
6
+ const digest = (value) => createHash('sha256').update(value).digest();
7
+ const same = (a, b) => timingSafeEqual(digest(a), digest(b));
8
+ export function sign(secret, timestamp, body) {
9
+ return `sha256=${createHmac('sha256', secret).update(`${timestamp}.`).update(body).digest('hex')}`;
10
+ }
11
+ /** The timestamp is signed with the body, so a captured request stops working after a few minutes. */
12
+ export function verify(secret, timestamp, signature, body, now = Date.now()) {
13
+ if (!secret || !timestamp || !signature)
14
+ return false;
15
+ const sent = Number(timestamp);
16
+ if (!Number.isFinite(sent) || Math.abs(now - sent) > TOLERANCE_MS)
17
+ return false;
18
+ return same(signature, sign(secret, timestamp, body));
19
+ }
20
+ /** Reads the `factorix` parameter of a page address. Returns nothing for a forged or expired one. */
21
+ export function readPageToken(secret, token, now = Date.now()) {
22
+ const [payload, signature] = (token ?? '').split('.');
23
+ if (!secret || !payload || !signature)
24
+ return null;
25
+ if (!same(signature, createHmac('sha256', secret).update(payload).digest('hex')))
26
+ return null;
27
+ try {
28
+ const context = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
29
+ return typeof context.exp === 'number' && context.exp > now ? context : null;
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ export function signPageToken(secret, context) {
36
+ const payload = Buffer.from(JSON.stringify(context)).toString('base64url');
37
+ return `${payload}.${createHmac('sha256', secret).update(payload).digest('hex')}`;
38
+ }
package/testing.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ import { type Plugin } from './plugin.js';
2
+ import { type BlockAnswer, type BlockCall, type Connection, type Manifest, type PageContext, type Tracker } from './types.js';
3
+ /** Calls a plugin the way Factorix does, without a network, for your tests. */
4
+ export declare function factorixClient(plugin: Plugin, options?: {
5
+ secret?: string;
6
+ path?: string;
7
+ }): {
8
+ handler: (request: Request) => Promise<Response>;
9
+ manifest: () => Promise<Manifest>;
10
+ tracker(connection?: Partial<Connection>): Required<Tracker>;
11
+ /** Runs a block as a workflow reaching it does. `config` holds its fields with templates already filled. */
12
+ runBlock(key: string, input?: Partial<Omit<BlockCall, "block">>): Promise<BlockAnswer>;
13
+ /** The choices a block lists for one of its `dynamic` fields. */
14
+ blockOptions(key: string, field: string, org?: {
15
+ id: string;
16
+ }): Promise<{
17
+ value: string;
18
+ label: string;
19
+ }[]>;
20
+ /**
21
+ * Opens a page as a signed-in person would, and returns what the plugin served. With `form`, posts it to the page
22
+ * the way a form on the page does, which reaches its `action`.
23
+ */
24
+ openPage(key: string, context?: Partial<PageContext>, options?: {
25
+ query?: Record<string, string>;
26
+ form?: Record<string, string>;
27
+ }): Promise<Response>;
28
+ };
29
+ type FakeCall = 'settings' | 'activity' | 'agents' | 'runs' | 'run' | 'members' | 'projects' | 'tickets' | 'ticket' | 'workflow-steps' | 'workflow-triggers';
30
+ /**
31
+ * Stands in for Factorix behind `factorix({ fetch })`, for your tests. Each handler gets the body the plugin sent
32
+ * (`runId` added for `run`, which is `getRun`, and `ticketId` for `ticket`, which is `getTicket`) and returns what
33
+ * Factorix would answer: settings, the activity, the agents, the run, the members, the projects, or the ticket.
34
+ * `workflow-steps` is `finishStep`, whose answer is not read, and `workflow-triggers` is `fireTrigger`, which answers how many
35
+ * workflows started. Throw a `FactorixError` to answer with its status. Signatures are checked like Factorix does.
36
+ */
37
+ export declare function fakeFactorix(handlers: Partial<Record<FakeCall, (body: Record<string, unknown>) => unknown>>, options?: {
38
+ secret?: string;
39
+ }): {
40
+ fetch: typeof fetch;
41
+ calls: {
42
+ call: FakeCall;
43
+ pluginId: string;
44
+ body: Record<string, unknown>;
45
+ }[];
46
+ };
47
+ /**
48
+ * Walks a tracker through what Factorix does with one: reads the teams and statuses, creates an issue, moves it, labels
49
+ * it, comments, and finds it again in a sync. Throws with a plain message at the first thing that is off. It writes to
50
+ * the tracker, so point it at a test account.
51
+ */
52
+ export declare function checkTracker(tracker: Tracker): Promise<void>;
53
+ export {};
package/testing.js ADDED
@@ -0,0 +1,189 @@
1
+ import { createHandler, FactorixError } from './plugin.js';
2
+ import { SIGNATURE_HEADER, sign, signPageToken, TIMESTAMP_HEADER, verify } from './signing.js';
3
+ import { PROTOCOL } from './types.js';
4
+ const DEFAULT_SECRET = 'test-secret-0123456789';
5
+ /** Calls a plugin the way Factorix does, without a network, for your tests. */
6
+ export function factorixClient(plugin, options = {}) {
7
+ const secret = options.secret ?? DEFAULT_SECRET;
8
+ const path = options.path ?? '/factorix';
9
+ const handler = createHandler(plugin, { secret, path });
10
+ const call = async (method, params, connection) => {
11
+ const body = JSON.stringify({ protocol: PROTOCOL, method, params, connection });
12
+ const timestamp = String(Date.now());
13
+ const response = await handler(new Request(`http://plugin.test${path}`, {
14
+ method: 'POST',
15
+ headers: { [TIMESTAMP_HEADER]: timestamp, [SIGNATURE_HEADER]: sign(secret, timestamp, body) },
16
+ body,
17
+ }));
18
+ const answer = (await response.json());
19
+ if (!response.ok || answer.error)
20
+ throw new Error(answer.error?.message ?? `The plugin answered ${response.status}`);
21
+ return answer.result;
22
+ };
23
+ return {
24
+ handler,
25
+ manifest: () => call('manifest', [], null),
26
+ tracker(connection = {}) {
27
+ const full = { id: 'connection-1', config: {}, secrets: {}, ...connection };
28
+ return new Proxy({}, {
29
+ get: (_target, method) => (...params) => call(`tracker.${String(method)}`, params, full),
30
+ });
31
+ },
32
+ /** Runs a block as a workflow reaching it does. `config` holds its fields with templates already filled. */
33
+ runBlock(key, input = {}) {
34
+ return call('workflow.block', [
35
+ {
36
+ plugin: { id: 'plugin-1' },
37
+ org: { id: 'org-1' },
38
+ run: { id: 'run-1', url: 'https://factorix.test/workflows/workflow-1/runs/run-1', workflowId: 'workflow-1', workflowName: 'Test' },
39
+ nodeId: `${key}-1`,
40
+ config: {},
41
+ issue: null,
42
+ ...input,
43
+ block: key,
44
+ },
45
+ ], null);
46
+ },
47
+ /** The choices a block lists for one of its `dynamic` fields. */
48
+ blockOptions(key, field, org = { id: 'org-1' }) {
49
+ return call('workflow.options', [{ block: key, field, org }], null);
50
+ },
51
+ /**
52
+ * Opens a page as a signed-in person would, and returns what the plugin served. With `form`, posts it to the page
53
+ * the way a form on the page does, which reaches its `action`.
54
+ */
55
+ async openPage(key, context = {}, options = {}) {
56
+ const page = plugin.manifest.pages.find((candidate) => candidate.key === key);
57
+ if (!page)
58
+ throw new Error(`The plugin has no page ${key}`);
59
+ const token = signPageToken(secret, {
60
+ exp: Date.now() + 60_000,
61
+ page: key,
62
+ plugin: { id: 'plugin-1' },
63
+ org: { id: 'org-1', name: 'Acme' },
64
+ account: { id: 'account-1', name: 'Sam', role: 'admin' },
65
+ settings: {},
66
+ ...context,
67
+ });
68
+ const query = new URLSearchParams({ factorix: token, ...options.query });
69
+ const address = `http://plugin.test${path}${page.path}?${query}`;
70
+ if (!options.form)
71
+ return handler(new Request(address));
72
+ return handler(new Request(address, {
73
+ method: 'POST',
74
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
75
+ body: new URLSearchParams(options.form),
76
+ }));
77
+ },
78
+ };
79
+ }
80
+ /**
81
+ * Stands in for Factorix behind `factorix({ fetch })`, for your tests. Each handler gets the body the plugin sent
82
+ * (`runId` added for `run`, which is `getRun`, and `ticketId` for `ticket`, which is `getTicket`) and returns what
83
+ * Factorix would answer: settings, the activity, the agents, the run, the members, the projects, or the ticket.
84
+ * `workflow-steps` is `finishStep`, whose answer is not read, and `workflow-triggers` is `fireTrigger`, which answers how many
85
+ * workflows started. Throw a `FactorixError` to answer with its status. Signatures are checked like Factorix does.
86
+ */
87
+ export function fakeFactorix(handlers, options = {}) {
88
+ const secret = options.secret ?? DEFAULT_SECRET;
89
+ const calls = [];
90
+ const answer = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
91
+ const wrap = {
92
+ settings: (value) => value,
93
+ activity: (activity) => ({ activity }),
94
+ agents: (agents) => ({ agents }),
95
+ runs: (run) => ({ run }),
96
+ run: (run) => ({ run }),
97
+ members: (members) => ({ members }),
98
+ projects: (projects) => ({ projects }),
99
+ tickets: (ticket) => ({ ticket }),
100
+ ticket: (ticket) => ({ ticket }),
101
+ 'workflow-steps': () => ({ ok: true }),
102
+ 'workflow-triggers': (started) => ({ started: Number(started ?? 0) }),
103
+ };
104
+ const fake = async (input, init) => {
105
+ const body = String(init?.body ?? '');
106
+ const headers = new Headers(init?.headers);
107
+ if (!verify(secret, headers.get(TIMESTAMP_HEADER), headers.get(SIGNATURE_HEADER), body))
108
+ return answer(401, { error: { message: 'Plugin signature check failed' } });
109
+ const match = /^\/webhooks\/plugins\/([^/]+)\/(settings|activity|agents|runs|members|projects|tickets|workflow-steps|workflow-triggers)(?:\/([^/]+))?$/.exec(new URL(String(input)).pathname);
110
+ if (!match?.[1] || !match[2])
111
+ return answer(404, { error: { message: 'Not found' } });
112
+ const one = match[2] === 'runs' ? 'run' : match[2] === 'tickets' ? 'ticket' : null;
113
+ if (match[3] && !one)
114
+ return answer(404, { error: { message: 'Not found' } });
115
+ const call = match[3] && one ? one : match[2];
116
+ const handle = handlers[call];
117
+ if (!handle)
118
+ return answer(404, { error: { message: `The fake has no ${call}` } });
119
+ const sent = { ...JSON.parse(body), ...(match[3] ? { [`${call}Id`]: decodeURIComponent(match[3]) } : {}) };
120
+ calls.push({ call, pluginId: match[1], body: sent });
121
+ try {
122
+ return answer(200, wrap[call](await handle(sent)));
123
+ }
124
+ catch (error) {
125
+ if (error instanceof FactorixError)
126
+ return answer(error.status, { error: { message: error.message } });
127
+ throw error;
128
+ }
129
+ };
130
+ return { fetch: fake, calls };
131
+ }
132
+ /**
133
+ * Walks a tracker through what Factorix does with one: reads the teams and statuses, creates an issue, moves it, labels
134
+ * it, comments, and finds it again in a sync. Throws with a plain message at the first thing that is off. It writes to
135
+ * the tracker, so point it at a test account.
136
+ */
137
+ export async function checkTracker(tracker) {
138
+ const fail = (message) => {
139
+ throw new Error(`Tracker check: ${message}`);
140
+ };
141
+ const viewer = await tracker.viewer();
142
+ if (!viewer.id || !viewer.name)
143
+ fail('viewer() must return an id and a name');
144
+ const team = (await tracker.listTeams())[0] ?? fail('listTeams() returned nothing to follow');
145
+ if (!/^[A-Z][A-Z0-9]*$/.test(team.key))
146
+ fail(`team key ${team.key} must be capital letters and digits, since issues are named ${team.key}-12`);
147
+ const states = await tracker.listWorkflowStates(team.id);
148
+ const open = states.find((state) => state.type === 'unstarted' || state.type === 'backlog') ?? fail('no status of type unstarted or backlog');
149
+ const started = states.find((state) => state.type === 'started') ?? fail('no status of type started, which is where an agent moves an issue it picks up');
150
+ if (!states.some((state) => state.type === 'completed'))
151
+ fail('no status of type completed');
152
+ const before = new Date(Date.now() - 1000).toISOString();
153
+ const issue = await tracker.createIssue({
154
+ teamId: team.id,
155
+ title: 'Factorix tracker check',
156
+ description: 'Made by **checkTracker**.',
157
+ stateId: open.id,
158
+ });
159
+ if (!issue.identifier.startsWith(`${team.key}-`))
160
+ fail(`identifier ${issue.identifier} must start with ${team.key}-`);
161
+ if (issue.stateId !== open.id || issue.teamId !== team.id)
162
+ fail('createIssue() must put the issue in the team and status it was given');
163
+ if (Number.isNaN(Date.parse(issue.updatedAt)))
164
+ fail('updatedAt must be an ISO date');
165
+ await tracker.updateIssueState(issue.id, started.id);
166
+ const moved = (await tracker.getIssue(issue.id)) ?? fail('getIssue() lost the issue it just created');
167
+ if (moved.stateId !== started.id || moved.stateType !== 'started')
168
+ fail('updateIssueState() did not move the issue');
169
+ const group = await tracker.createLabel({ teamId: team.id, name: 'Agent', isGroup: true });
170
+ const label = await tracker.createLabel({ teamId: team.id, name: 'check-agent', parentId: group.id });
171
+ if (label.parentId !== group.id)
172
+ fail('a label created under the Agent group must come back with that group as its parent');
173
+ await tracker.updateIssueLabels(issue.id, { add: [label.id] });
174
+ if (!(await tracker.getIssue(issue.id))?.labels.some((item) => item.id === label.id))
175
+ fail('updateIssueLabels() did not add the label');
176
+ await tracker.updateIssueLabels(issue.id, { remove: [label.id] });
177
+ if ((await tracker.getIssue(issue.id))?.labels.some((item) => item.id === label.id))
178
+ fail('updateIssueLabels() did not remove the label');
179
+ const comment = await tracker.comment(issue.id, '**[Factorix · check]** hello');
180
+ const comments = await tracker.listComments(issue.id);
181
+ const posted = comments.find((item) => item.id === comment.id) ?? fail('listComments() does not include the comment just posted');
182
+ if (!posted.body.startsWith('**[Factorix · check]**'))
183
+ fail('a comment must come back as the Markdown it was written in, since Factorix knows its own comments by how they start');
184
+ const page = await tracker.listIssues({ teamId: team.id, updatedAfter: before, limit: 50 });
185
+ if (!page.nodes.some((item) => item.id === issue.id))
186
+ fail('listIssues({ updatedAfter }) must include an issue changed after that moment');
187
+ if ((await tracker.getIssue('no-such-issue-id')) !== null)
188
+ fail('getIssue() must return null for an issue that does not exist');
189
+ }