requirementbot 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +197 -2
- package/bin/requirementbot.js +21 -0
- package/package.json +53 -4
- package/prompts/README.md +18 -0
- package/prompts/check.md +15 -0
- package/prompts/fix.md +4 -0
- package/prompts/from-code.md +12 -0
- package/prompts/from-docs.md +11 -0
- package/prompts/from-issues.md +14 -0
- package/prompts/mdq.md +8 -0
- package/prompts/partials/non-interactive.md +1 -0
- package/prompts/partials/subagents.md +1 -0
- package/prompts/report.md +8 -0
- package/prompts/system.md +9 -0
- package/skills/SOURCE.md +14 -0
- package/skills/catalog-features/SKILL.md +168 -0
- package/skills/catalog-features/references/layout.md +87 -0
- package/skills/detect-product-mismatches/SKILL.md +147 -0
- package/skills/detect-product-mismatches/references/features.md +84 -0
- package/skills/detect-product-mismatches/references/layout.md +99 -0
- package/skills/pull-request-diff-analyzer/SKILL.md +141 -0
- package/skills/qa-explain-behavior/SKILL.md +112 -0
- package/skills/qa-explain-behavior/references/answer-shapes.md +116 -0
- package/skills/qa-explain-behavior/references/examples.md +157 -0
- package/skills/qa-pr-requirements-analyzer/SKILL.md +149 -0
- package/skills/qa-pr-requirements-analyzer/references/summary-example.md +54 -0
- package/skills/qa-requirement-reviewer/SKILL.md +126 -0
- package/skills/qa-requirement-reviewer/references/requirements_reviewer_examples.md +128 -0
- package/skills/qa-thinking/SKILL.md +46 -0
- package/skills/requirements-from-code/SKILL.md +114 -0
- package/skills/requirements-from-code/references/behaviors.md +42 -0
- package/skills/requirements-from-code/references/layout.md +100 -0
- package/skills/requirements-from-expected/SKILL.md +116 -0
- package/skills/requirements-from-expected/references/behaviors.md +49 -0
- package/skills/requirements-from-expected/references/layout.md +74 -0
- package/skills/requirements-from-expected/references/merge.md +34 -0
- package/skills/write-user-story/SKILL.md +42 -0
- package/src/agent/agent.js +278 -0
- package/src/agent/auth.js +209 -0
- package/src/agent/prompt.js +36 -0
- package/src/branding.js +27 -0
- package/src/cli.js +26 -0
- package/src/commands/agent-command.js +61 -0
- package/src/commands/check.js +26 -0
- package/src/commands/command.js +40 -0
- package/src/commands/connect.js +33 -0
- package/src/commands/disconnect.js +18 -0
- package/src/commands/generate-from-code.js +20 -0
- package/src/commands/generate-from-docs.js +38 -0
- package/src/commands/generate-from-issues.js +41 -0
- package/src/commands/index.js +40 -0
- package/src/commands/login.js +44 -0
- package/src/commands/logout.js +17 -0
- package/src/commands/models.js +11 -0
- package/src/commands/pull.js +15 -0
- package/src/commands/push.js +29 -0
- package/src/commands/query.js +31 -0
- package/src/commands/report.js +23 -0
- package/src/commands/skills.js +20 -0
- package/src/commands/sources.js +16 -0
- package/src/commands/update-from-code.js +7 -0
- package/src/commands/update-from-docs.js +7 -0
- package/src/commands/update-from-issues.js +7 -0
- package/src/config.js +90 -0
- package/src/files.js +25 -0
- package/src/github.js +50 -0
- package/src/http.js +19 -0
- package/src/requirements.js +139 -0
- package/src/sources/adf.js +48 -0
- package/src/sources/github.js +81 -0
- package/src/sources/index.js +41 -0
- package/src/sources/jira.js +135 -0
- package/src/sources/pages.js +67 -0
- package/src/sources/source.js +60 -0
- package/src/transports/confluence.js +114 -0
- package/src/transports/git.js +90 -0
- package/src/transports/github.js +42 -0
- package/src/transports/index.js +36 -0
- package/src/transports/notion.js +108 -0
- package/src/transports/page-tree.js +119 -0
- package/src/transports/transport.js +41 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { GitHubSource } from './github.js';
|
|
2
|
+
import { JiraSource } from './jira.js';
|
|
3
|
+
import { ConfluenceSource, NotionSource } from './pages.js';
|
|
4
|
+
|
|
5
|
+
/** All sources by kind. */
|
|
6
|
+
export class Sources {
|
|
7
|
+
static all = [GitHubSource, JiraSource, ConfluenceSource, NotionSource];
|
|
8
|
+
|
|
9
|
+
static get usage() {
|
|
10
|
+
return Sources.all.map((s) => s.usage).join(' · ');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Create a source from `<kind>:<target>`. */
|
|
14
|
+
static parse(value, scope) {
|
|
15
|
+
const colon = value.indexOf(':');
|
|
16
|
+
const Type = Sources.all.find((s) => s.kind === value.slice(0, colon).toLowerCase());
|
|
17
|
+
if (colon < 0 || !Type || !value.slice(colon + 1)) throw new Error(`Use one of: ${Sources.usage}`);
|
|
18
|
+
return new Type(value.slice(colon + 1), scope);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Create a source from a saved config entry. */
|
|
22
|
+
static fromConfig({ kind, target, scope }) {
|
|
23
|
+
return Sources.parse(`${kind}:${target}`, scope);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Connected sources of one type, as `[name, entry, source]`.
|
|
28
|
+
* @param {import('../config.js').Config} config
|
|
29
|
+
* @param {'issues'|'docs'} type
|
|
30
|
+
*/
|
|
31
|
+
static connected(config, type, only) {
|
|
32
|
+
const entries = Object.entries(config.sources)
|
|
33
|
+
.map(([name, entry]) => [name, entry, Sources.fromConfig(entry)])
|
|
34
|
+
.filter(([name, , source]) => source.type === type && (!only || name === only));
|
|
35
|
+
if (!entries.length) {
|
|
36
|
+
const kinds = Sources.all.filter((s) => s.type === type).map((s) => `connect ${s.usage}`).join(' or ');
|
|
37
|
+
throw new Error(`No ${type} sources${only ? ` named "${only}"` : ''} connected. Run: requirementbot ${kinds}`);
|
|
38
|
+
}
|
|
39
|
+
return entries;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { slugify, writeMarkdown } from '../files.js';
|
|
3
|
+
import { request } from '../http.js';
|
|
4
|
+
import { Adf } from './adf.js';
|
|
5
|
+
import { Source } from './source.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* `jira:<site>/<PROJECT>` — resolved issues matching a JQL query (default: the project's issues).
|
|
9
|
+
* Unresolved issues are never fetched: every query is narrowed to `statusCategory = Done`.
|
|
10
|
+
* Jira Cloud: JIRA_EMAIL + JIRA_TOKEN. Server/Data Center: JIRA_TOKEN as a personal access token.
|
|
11
|
+
*/
|
|
12
|
+
export class JiraSource extends Source {
|
|
13
|
+
static kind = 'jira';
|
|
14
|
+
static type = 'issues';
|
|
15
|
+
static usage = 'jira:<site>/<PROJECT>';
|
|
16
|
+
static defaultScope = { jql: '', limit: 500, comments: true };
|
|
17
|
+
static FIELDS = ['summary', 'description', 'status', 'issuetype', 'priority', 'labels', 'parent', 'created', 'updated', 'resolutiondate', 'resolution', 'comment', 'issuelinks', 'subtasks'];
|
|
18
|
+
|
|
19
|
+
constructor(target, scope) {
|
|
20
|
+
super(target, scope);
|
|
21
|
+
const url = new URL(target.startsWith('http') ? target : `https://${target}`);
|
|
22
|
+
const project = url.pathname.match(/projects\/([A-Z][A-Z0-9_]+)/) || url.pathname.match(/^\/([A-Z][A-Z0-9_]+)\/?$/) || url.pathname.match(/browse\/([A-Z][A-Z0-9_]+)/);
|
|
23
|
+
if (!project) throw new Error(`Cannot find a Jira project key in "${target}". Use ${JiraSource.usage}`);
|
|
24
|
+
this.baseUrl = url.origin;
|
|
25
|
+
this.project = project[1];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
get defaultName() {
|
|
29
|
+
return slugify(`jira-${this.project}`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
get cloud() {
|
|
33
|
+
return Boolean(process.env.JIRA_EMAIL);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async validate() {
|
|
37
|
+
const info = await this.api(`/project/${this.project}`);
|
|
38
|
+
return `${info.key} — ${info.name}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async fetch(dir, { since } = {}) {
|
|
42
|
+
const query = this.scope.jql || `project = ${this.project} ORDER BY created ASC`;
|
|
43
|
+
const jql = JiraSource.withSince(JiraSource.and(query, 'statusCategory = Done'), since);
|
|
44
|
+
const limit = Number(this.scope.limit) || 500;
|
|
45
|
+
let written = 0;
|
|
46
|
+
let nextPageToken;
|
|
47
|
+
let startAt = 0;
|
|
48
|
+
while (written < limit) {
|
|
49
|
+
const page = this.cloud
|
|
50
|
+
? await this.api('/search/jql', { method: 'POST', json: { jql, fields: JiraSource.FIELDS, maxResults: 100, nextPageToken } })
|
|
51
|
+
: await this.api('/search', { method: 'POST', json: { jql, fields: JiraSource.FIELDS, maxResults: 100, startAt } });
|
|
52
|
+
for (const issue of page.issues || []) {
|
|
53
|
+
if (written >= limit) break;
|
|
54
|
+
await this.write(dir, issue);
|
|
55
|
+
written++;
|
|
56
|
+
}
|
|
57
|
+
startAt += page.issues?.length || 0;
|
|
58
|
+
nextPageToken = page.nextPageToken;
|
|
59
|
+
const done = this.cloud ? !nextPageToken || page.isLast : startAt >= page.total;
|
|
60
|
+
if (done || !page.issues?.length) break;
|
|
61
|
+
}
|
|
62
|
+
return written;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async write(dir, issue) {
|
|
66
|
+
const f = issue.fields;
|
|
67
|
+
const body = [`# ${issue.key} ${f.summary}`, '', Adf.toMarkdown(f.description) || '_No description._'];
|
|
68
|
+
if (this.scope.comments !== false) {
|
|
69
|
+
for (const c of await this.comments(issue)) body.push('', `## Comment by ${c.author?.displayName} on ${c.created?.slice(0, 10)}`, '', Adf.toMarkdown(c.body));
|
|
70
|
+
}
|
|
71
|
+
writeMarkdown(join(dir, `${issue.key}-${slugify(f.summary)}.md`), {
|
|
72
|
+
key: issue.key,
|
|
73
|
+
title: f.summary,
|
|
74
|
+
type: f.issuetype?.name,
|
|
75
|
+
status: f.status?.name,
|
|
76
|
+
resolution: f.resolution?.name,
|
|
77
|
+
priority: f.priority?.name,
|
|
78
|
+
labels: f.labels,
|
|
79
|
+
parent: f.parent?.key,
|
|
80
|
+
links: JiraSource.links(f.issuelinks),
|
|
81
|
+
subtasks: (f.subtasks || []).map((t) => JiraSource.compact({ key: t.key, title: t.fields?.summary, status: t.fields?.status?.name })),
|
|
82
|
+
created: f.created,
|
|
83
|
+
updated: f.updated,
|
|
84
|
+
resolved: f.resolutiondate,
|
|
85
|
+
url: `${this.baseUrl}/browse/${issue.key}`,
|
|
86
|
+
}, body.join('\n'));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Every comment of the issue: search results may hold only the first ones. */
|
|
90
|
+
async comments(issue) {
|
|
91
|
+
const first = issue.fields.comment || {};
|
|
92
|
+
const comments = [...(first.comments || [])];
|
|
93
|
+
while (first.total > comments.length) {
|
|
94
|
+
const page = await this.api(`/issue/${issue.key}/comment?startAt=${comments.length}&maxResults=100`);
|
|
95
|
+
if (!page.comments?.length) break;
|
|
96
|
+
comments.push(...page.comments);
|
|
97
|
+
}
|
|
98
|
+
return comments;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Issue links as `{ relation, key, title, status }`, the relation read from this issue's side. */
|
|
102
|
+
static links(issuelinks = []) {
|
|
103
|
+
return issuelinks.map((link) => {
|
|
104
|
+
const other = link.outwardIssue || link.inwardIssue;
|
|
105
|
+
return JiraSource.compact({
|
|
106
|
+
relation: link.outwardIssue ? link.type?.outward : link.type?.inward,
|
|
107
|
+
key: other?.key,
|
|
108
|
+
title: other?.fields?.summary,
|
|
109
|
+
status: other?.fields?.status?.name,
|
|
110
|
+
});
|
|
111
|
+
}).filter((link) => link.key);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
static compact(object) {
|
|
115
|
+
return Object.fromEntries(Object.entries(object).filter(([, v]) => v !== undefined && v !== null));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
api(path, options = {}) {
|
|
119
|
+
const token = process.env.JIRA_TOKEN || process.env.JIRA_API_TOKEN;
|
|
120
|
+
if (!token) throw new Error('Set JIRA_TOKEN (and JIRA_EMAIL for Jira Cloud)');
|
|
121
|
+
const auth = this.cloud ? `Basic ${Buffer.from(`${process.env.JIRA_EMAIL}:${token}`).toString('base64')}` : `Bearer ${token}`;
|
|
122
|
+
return request(`${this.baseUrl}/rest/api/${this.cloud ? 3 : 2}${path}`, { ...options, headers: { Authorization: auth } });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Add `updated >= since` to a JQL query, keeping its ORDER BY. */
|
|
126
|
+
static withSince(jql, since) {
|
|
127
|
+
return since ? JiraSource.and(jql, `updated >= "${since.slice(0, 10)}"`) : jql;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Add a condition to a JQL query, keeping its ORDER BY. */
|
|
131
|
+
static and(jql, condition) {
|
|
132
|
+
const [, filter, order = ''] = jql.match(/^(.*?)(\s+ORDER BY\s+.*)?$/is);
|
|
133
|
+
return filter.trim() ? `(${filter.trim()}) AND ${condition}${order}` : `${condition}${order}`;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { ConfluenceTransport } from '../transports/confluence.js';
|
|
2
|
+
import { NotionTransport } from '../transports/notion.js';
|
|
3
|
+
import { Source } from './source.js';
|
|
4
|
+
|
|
5
|
+
/** A docs space read through its transport's `pull`. */
|
|
6
|
+
class PagesSource extends Source {
|
|
7
|
+
static type = 'docs';
|
|
8
|
+
/** @type {typeof import('../transports/transport.js').Transport} */
|
|
9
|
+
static Transport;
|
|
10
|
+
|
|
11
|
+
constructor(target, scope) {
|
|
12
|
+
super(target, scope);
|
|
13
|
+
this.transport = new this.constructor.Transport(target);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async fetch(dir) {
|
|
17
|
+
await this.transport.pull(dir, {});
|
|
18
|
+
return 'pages';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** `confluence:<SPACE>[/<pageId>]` — a Confluence page tree. */
|
|
23
|
+
export class ConfluenceSource extends PagesSource {
|
|
24
|
+
static kind = 'confluence';
|
|
25
|
+
static usage = ConfluenceTransport.usage;
|
|
26
|
+
static Transport = ConfluenceTransport;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Check the credentials and the space or page with one request before the source is saved;
|
|
30
|
+
* returns `SPACE / Page title`.
|
|
31
|
+
*/
|
|
32
|
+
async validate() {
|
|
33
|
+
if (!this.transport.parentId) {
|
|
34
|
+
const space = await this.transport.api(`/space/${encodeURIComponent(this.transport.space)}?expand=homepage`).catch((err) => {
|
|
35
|
+
throw /→ 404\b/.test(err.message) ? new Error(`Space ${this.transport.space} not found in Confluence`) : err;
|
|
36
|
+
});
|
|
37
|
+
return `${this.transport.space} / ${space.homepage?.title || space.name}`;
|
|
38
|
+
}
|
|
39
|
+
const id = this.transport.parentId;
|
|
40
|
+
const page = await this.transport.api(`/content/${id}?expand=space`).catch((err) => {
|
|
41
|
+
throw /→ 404\b/.test(err.message) ? new Error(`Page ${id} not found in Confluence (draft pages cannot be read: publish it first)`) : err;
|
|
42
|
+
});
|
|
43
|
+
const key = page.space?.key;
|
|
44
|
+
if (key && key.toLowerCase() !== this.transport.space.toLowerCase()) throw new Error(`Page ${id} is in space ${key}, not ${this.transport.space}`);
|
|
45
|
+
return `${this.transport.space} / ${page.title}`;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** `notion:<page id or URL>` — a Notion page and its subpages. */
|
|
50
|
+
export class NotionSource extends PagesSource {
|
|
51
|
+
static kind = 'notion';
|
|
52
|
+
static usage = NotionTransport.usage;
|
|
53
|
+
static Transport = NotionTransport;
|
|
54
|
+
|
|
55
|
+
/** Check the token and the page with one request before the source is saved; returns the page title. */
|
|
56
|
+
async validate() {
|
|
57
|
+
const id = this.transport.pageId;
|
|
58
|
+
const page = await this.transport.client.pages.retrieve({ page_id: id }).catch((err) => {
|
|
59
|
+
throw err.code === 'object_not_found'
|
|
60
|
+
? new Error(`Notion page ${id} not found: check the id and share the page with the integration (••• → Connections)`)
|
|
61
|
+
: err;
|
|
62
|
+
});
|
|
63
|
+
if (page.archived || page.in_trash) throw new Error(`Notion page ${id} is archived or in trash: restore it first`);
|
|
64
|
+
const title = Object.values(page.properties || {}).find((p) => p.type === 'title')?.title?.map((t) => t.plain_text).join('');
|
|
65
|
+
return title || id;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { slugify } from '../files.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Where requirements come from: an issue tracker or a docs space. Subclasses set `kind`, `type`
|
|
5
|
+
* and `defaultScope`, and implement `validate` and `fetch`, which dumps the source as markdown
|
|
6
|
+
* files the agent reads.
|
|
7
|
+
*/
|
|
8
|
+
export class Source {
|
|
9
|
+
/** @type {string} */
|
|
10
|
+
static kind;
|
|
11
|
+
/** @type {'issues'|'docs'} */
|
|
12
|
+
static type;
|
|
13
|
+
static usage = '';
|
|
14
|
+
/** Options stored at `connect` time so later runs never ask. */
|
|
15
|
+
static defaultScope = {};
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {string} target everything after `<kind>:`
|
|
19
|
+
* @param {Record<string, any>} [scope]
|
|
20
|
+
*/
|
|
21
|
+
constructor(target, scope = {}) {
|
|
22
|
+
this.target = target;
|
|
23
|
+
this.scope = { ...this.constructor.defaultScope, ...scope };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
get kind() {
|
|
27
|
+
return this.constructor.kind;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
get type() {
|
|
31
|
+
return this.constructor.type;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Name used in config and as the output folder, e.g. `github-testomatio-check-tests`. */
|
|
35
|
+
get defaultName() {
|
|
36
|
+
return slugify(`${this.kind}-${this.target}`, 40);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
toString() {
|
|
40
|
+
return `${this.kind}:${this.target}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Check the target and credentials.
|
|
45
|
+
* @returns {Promise<string>} a short description of what was found
|
|
46
|
+
*/
|
|
47
|
+
async validate() {
|
|
48
|
+
return String(this);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Write the source as markdown files into `dir`.
|
|
53
|
+
* @param {string} dir
|
|
54
|
+
* @param {{ since?: string }} [options] only items changed since this ISO date
|
|
55
|
+
* @returns {Promise<number|string>} what was written, for the log
|
|
56
|
+
*/
|
|
57
|
+
async fetch(dir, options) {
|
|
58
|
+
throw new Error(`${this.kind} cannot be fetched`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { marked } from 'marked';
|
|
2
|
+
import TurndownService from 'turndown';
|
|
3
|
+
import { log, muted } from '../branding.js';
|
|
4
|
+
import { requireEnv } from '../config.js';
|
|
5
|
+
import { request } from '../http.js';
|
|
6
|
+
import { PageIds, PageTree } from './page-tree.js';
|
|
7
|
+
import { Transport } from './transport.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `confluence:<SPACE>[/<parentPageId>]` — mirrors the folder as a page tree under the parent page
|
|
11
|
+
* (the space home page by default). Needs CONFLUENCE_URL, CONFLUENCE_EMAIL, CONFLUENCE_TOKEN.
|
|
12
|
+
*/
|
|
13
|
+
export class ConfluenceTransport extends Transport {
|
|
14
|
+
static kind = 'confluence';
|
|
15
|
+
static usage = 'confluence:<SPACE>[/<parentPageId>]';
|
|
16
|
+
|
|
17
|
+
constructor(target) {
|
|
18
|
+
super(target);
|
|
19
|
+
const [space, parentId] = String(target).split('/');
|
|
20
|
+
if (!space) throw new Error(`Use ${ConfluenceTransport.usage}`);
|
|
21
|
+
this.space = space;
|
|
22
|
+
this.parentId = parentId;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** @param {{ dryRun?: boolean, titlePrefix?: string }} options */
|
|
26
|
+
async push(dir, { dryRun, titlePrefix = '' }) {
|
|
27
|
+
const tree = PageTree.read(dir).uniqueTitles(titlePrefix);
|
|
28
|
+
const pages = tree.pages();
|
|
29
|
+
const ids = new PageIds('confluence', `${this.space}/${this.parentId || 'home'}`);
|
|
30
|
+
if (dryRun) {
|
|
31
|
+
for (const p of pages) process.stderr.write(` ${ids.get(p.path) ? 'update' : 'create'} ${muted(p.title)} ← ${p.path}\n`);
|
|
32
|
+
return log(`Dry run: ${pages.length} page(s) under ${this}`);
|
|
33
|
+
}
|
|
34
|
+
const titles = new Map(pages.map((p) => [p.path, p.title]));
|
|
35
|
+
try {
|
|
36
|
+
await this.upsert(tree, await this.rootPageId(), ids, titles);
|
|
37
|
+
} finally {
|
|
38
|
+
ids.save();
|
|
39
|
+
}
|
|
40
|
+
const rootId = ids.get(tree.path);
|
|
41
|
+
log(`Pushed ${pages.length} page(s) to ${this.baseUrl}/pages/viewpage.action?pageId=${rootId}`);
|
|
42
|
+
log(`Requirements page id: ${rootId}`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async upsert(node, parentId, ids, titles) {
|
|
46
|
+
const body = { storage: { value: ConfluenceTransport.toStorage(node.body, node.path, titles), representation: 'storage' } };
|
|
47
|
+
let id = ids.get(node.path);
|
|
48
|
+
const existing = id ? await this.api(`/content/${id}?expand=version`).catch(() => undefined) : undefined;
|
|
49
|
+
if (existing) {
|
|
50
|
+
await this.api(`/content/${id}`, { method: 'PUT', json: { type: 'page', title: node.title, version: { number: existing.version.number + 1 }, ancestors: [{ id: parentId }], body } });
|
|
51
|
+
process.stderr.write(` updated ${muted(node.title)}\n`);
|
|
52
|
+
} else {
|
|
53
|
+
id = (await this.api('/content', { method: 'POST', json: { type: 'page', title: node.title, space: { key: this.space }, ancestors: [{ id: parentId }], body } })).id;
|
|
54
|
+
ids.set(node.path, id);
|
|
55
|
+
process.stderr.write(` created ${muted(node.title)}\n`);
|
|
56
|
+
}
|
|
57
|
+
for (const child of node.children) await this.upsert(child, id, ids, titles);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async pull(dir, { dryRun }) {
|
|
61
|
+
const tree = await this.download(await this.rootPageId());
|
|
62
|
+
const count = tree.pages().length;
|
|
63
|
+
if (dryRun) return log(`Dry run: would write ${count} page(s) into ${dir}`);
|
|
64
|
+
tree.write(dir);
|
|
65
|
+
log(`Pulled ${count} page(s) into ${dir}`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async download(id) {
|
|
69
|
+
const page = await this.api(`/content/${id}?expand=body.storage`);
|
|
70
|
+
const node = new PageTree({ path: '', title: page.title, body: ConfluenceTransport.fromStorage(page.body?.storage?.value) });
|
|
71
|
+
for (let start = 0; ; start += 100) {
|
|
72
|
+
const kids = await this.api(`/content/${id}/child/page?limit=100&start=${start}`);
|
|
73
|
+
for (const kid of kids.results) node.children.push(await this.download(kid.id));
|
|
74
|
+
if (kids.size < 100) break;
|
|
75
|
+
}
|
|
76
|
+
return node;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async rootPageId() {
|
|
80
|
+
if (this.parentId) return this.parentId;
|
|
81
|
+
return (await this.api(`/space/${encodeURIComponent(this.space)}?expand=homepage`)).homepage.id;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
get baseUrl() {
|
|
85
|
+
const [base] = requireEnv('CONFLUENCE_URL');
|
|
86
|
+
const url = base.replace(/\/+$/, '');
|
|
87
|
+
return /atlassian\.net$/.test(new URL(url).host) && !url.endsWith('/wiki') ? `${url}/wiki` : url;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
api(path, options = {}) {
|
|
91
|
+
const [, email, token] = requireEnv('CONFLUENCE_URL', 'CONFLUENCE_EMAIL', 'CONFLUENCE_TOKEN');
|
|
92
|
+
return request(`${this.baseUrl}/rest/api${path}`, { ...options, headers: { Authorization: `Basic ${Buffer.from(`${email}:${token}`).toString('base64')}` } });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Markdown to Confluence storage format; links to other pages in the tree become page links. */
|
|
96
|
+
static toStorage(markdown, fromPath, titles) {
|
|
97
|
+
const html = marked.parse(markdown, { async: false, gfm: true });
|
|
98
|
+
return html
|
|
99
|
+
.replace(/<(br|hr|img)([^>]*?)\s*\/?>/g, '<$1$2 />')
|
|
100
|
+
.replace(/<input([^>]*?)\s*\/?>/g, '<input$1 />')
|
|
101
|
+
.replace(/<a href="([^"#:]+\.md(?:#[^"]*)?|[^"#:]+\/)">([\s\S]*?)<\/a>/g, (match, href, text) => {
|
|
102
|
+
const title = titles.get(PageTree.resolveLink(fromPath, href));
|
|
103
|
+
if (!title) return match;
|
|
104
|
+
const escaped = title.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<');
|
|
105
|
+
return `<ac:link><ri:page ri:content-title="${escaped}" /><ac:plain-text-link-body><![CDATA[${text.replace(/<[^>]+>/g, '')}]]></ac:plain-text-link-body></ac:link>`;
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
static fromStorage(html) {
|
|
110
|
+
const turndown = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced', bulletListMarker: '-' });
|
|
111
|
+
turndown.addRule('confluenceLink', { filter: (node) => node.nodeName === 'AC:LINK', replacement: (content) => content });
|
|
112
|
+
return turndown.turndown(html || '').replace(/^(\s*)(-|\d+\.)\s{2,}/gm, '$1$2 ');
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { cpSync, existsSync, mkdtempSync, rmSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { log, muted } from '../branding.js';
|
|
6
|
+
import { Transport } from './transport.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* `git:<url>[#branch]` — clone, replace the requirements folder inside the repo, commit, push.
|
|
10
|
+
*/
|
|
11
|
+
export class GitTransport extends Transport {
|
|
12
|
+
static kind = 'git';
|
|
13
|
+
static usage = 'git:<url>[#branch]';
|
|
14
|
+
|
|
15
|
+
constructor(target) {
|
|
16
|
+
super(target);
|
|
17
|
+
const hash = target.lastIndexOf('#');
|
|
18
|
+
this.url = hash < 0 ? target : target.slice(0, hash);
|
|
19
|
+
this.branch = hash < 0 ? undefined : target.slice(hash + 1) || undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
get cloneUrl() {
|
|
23
|
+
return this.url;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param {{ path: string, message: string, dryRun?: boolean }} options */
|
|
27
|
+
async push(dir, { path, message, dryRun }) {
|
|
28
|
+
await this.withClone(async (repo) => {
|
|
29
|
+
const changes = this.mirror(dir, repo, path);
|
|
30
|
+
if (!changes.length) return log('Nothing to push: destination is up to date');
|
|
31
|
+
this.printChanges(changes);
|
|
32
|
+
if (dryRun) return log(`Dry run: ${changes.length} change(s) not pushed`);
|
|
33
|
+
await this.publish(repo, changes, message);
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Commit and push the staged changes in `repo`. */
|
|
38
|
+
async publish(repo, changes, message) {
|
|
39
|
+
const branch = this.branch || this.git(['rev-parse', '--abbrev-ref', 'HEAD'], repo);
|
|
40
|
+
this.git(['commit', '-m', message], repo);
|
|
41
|
+
this.git(['push', 'origin', `HEAD:${branch}`], repo, { quiet: false });
|
|
42
|
+
log(`Pushed ${changes.length} change(s) to ${this.url} ${muted(branch)}`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param {{ path: string, dryRun?: boolean }} options */
|
|
46
|
+
async pull(dir, { path, dryRun }) {
|
|
47
|
+
await this.withClone(async (repo) => {
|
|
48
|
+
const source = join(repo, path);
|
|
49
|
+
if (!existsSync(source)) throw new Error(`No "${path}" folder in ${this.url}`);
|
|
50
|
+
if (dryRun) return log(`Dry run: would replace ${dir} with ${path}/ from ${this.url}`);
|
|
51
|
+
rmSync(dir, { recursive: true, force: true });
|
|
52
|
+
cpSync(source, dir, { recursive: true });
|
|
53
|
+
log(`Pulled ${path}/ from ${this.url} into ${dir}`);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Shallow-clone into a temp dir at `branch` (created from the default branch when missing). */
|
|
58
|
+
async withClone(fn) {
|
|
59
|
+
const repo = mkdtempSync(join(tmpdir(), 'requirementbot-'));
|
|
60
|
+
try {
|
|
61
|
+
try {
|
|
62
|
+
this.git(['clone', '--depth', '1', ...(this.branch ? ['--branch', this.branch] : []), this.cloneUrl, repo]);
|
|
63
|
+
} catch (err) {
|
|
64
|
+
if (!this.branch || !/Remote branch .* not found/.test(String(err.stderr))) throw err;
|
|
65
|
+
this.git(['clone', '--depth', '1', this.cloneUrl, repo]);
|
|
66
|
+
this.git(['checkout', '-B', this.branch], repo);
|
|
67
|
+
}
|
|
68
|
+
return await fn(repo);
|
|
69
|
+
} finally {
|
|
70
|
+
rmSync(repo, { recursive: true, force: true });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Replace `repo/subdir` with `source` and stage it; returns `git status --porcelain` lines. */
|
|
75
|
+
mirror(source, repo, subdir) {
|
|
76
|
+
const target = join(repo, subdir);
|
|
77
|
+
rmSync(target, { recursive: true, force: true });
|
|
78
|
+
cpSync(source, target, { recursive: true });
|
|
79
|
+
this.git(['add', '-A', '--', subdir], repo);
|
|
80
|
+
return this.git(['status', '--porcelain', '--', subdir], repo).split('\n').filter(Boolean);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
printChanges(changes) {
|
|
84
|
+
for (const line of changes) process.stderr.write(` ${muted(line)}\n`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
git(args, cwd, { quiet = true } = {}) {
|
|
88
|
+
return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', quiet ? 'pipe' : 'inherit'] }).trim();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { log } from '../branding.js';
|
|
2
|
+
import { GitHub } from '../github.js';
|
|
3
|
+
import { GitTransport } from './git.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* `github:<url or owner/repo>[#base]` — like git, but pushes a `requirementbot/<time>` branch and opens a pull request.
|
|
7
|
+
*/
|
|
8
|
+
export class GitHubTransport extends GitTransport {
|
|
9
|
+
static kind = 'github';
|
|
10
|
+
static usage = 'github:<url or owner/repo>[#base]';
|
|
11
|
+
|
|
12
|
+
constructor(target) {
|
|
13
|
+
super(target);
|
|
14
|
+
this.github = new GitHub(this.url);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
get cloneUrl() {
|
|
18
|
+
return /^(git@|https?:\/\/|ssh:\/\/)/.test(this.url) ? this.url : `https://github.com/${this.github.fullName}.git`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async push(dir, { path, message, dryRun }) {
|
|
22
|
+
await this.withClone(async (repo) => {
|
|
23
|
+
const base = this.branch || this.git(['rev-parse', '--abbrev-ref', 'HEAD'], repo);
|
|
24
|
+
const changes = this.mirror(dir, repo, path);
|
|
25
|
+
if (!changes.length) return log('Nothing to push: destination is up to date');
|
|
26
|
+
this.printChanges(changes);
|
|
27
|
+
const head = `requirementbot/${new Date().toISOString().replace(/[-:]/g, '').replace(/\..*/, '').replace('T', '-')}`;
|
|
28
|
+
if (dryRun) return log(`Dry run: would push ${changes.length} change(s) to branch ${head} and open a PR into ${base}`);
|
|
29
|
+
this.git(['checkout', '-b', head], repo);
|
|
30
|
+
this.git(['commit', '-m', message], repo);
|
|
31
|
+
this.git(['push', 'origin', head], repo, { quiet: false });
|
|
32
|
+
const pr = await this.github.openPullRequest({ head, base, title: message, body: this.pullRequestBody(changes) });
|
|
33
|
+
log(`Opened pull request ${pr}`);
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
pullRequestBody(changes) {
|
|
38
|
+
const list = changes.slice(0, 50).map((c) => `- \`${c.slice(3)}\` (${c.slice(0, 2).trim()})`).join('\n');
|
|
39
|
+
const more = changes.length > 50 ? `\n- …and ${changes.length - 50} more` : '';
|
|
40
|
+
return `Requirements updated by [requirementbot](https://github.com/testomatio/requirementbot).\n\n${list}${more}\n`;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { ConfluenceTransport } from './confluence.js';
|
|
2
|
+
import { GitTransport } from './git.js';
|
|
3
|
+
import { GitHubTransport } from './github.js';
|
|
4
|
+
import { NotionTransport } from './notion.js';
|
|
5
|
+
|
|
6
|
+
/** All destinations by kind; `Transports.create('notion:<id>')` returns a ready transport. */
|
|
7
|
+
export class Transports {
|
|
8
|
+
static all = [GitTransport, GitHubTransport, ConfluenceTransport, NotionTransport];
|
|
9
|
+
|
|
10
|
+
static get usage() {
|
|
11
|
+
return Transports.all.map((t) => t.usage).join(' · ');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
static find(kind) {
|
|
15
|
+
const Type = Transports.all.find((t) => t.kind === kind.toLowerCase());
|
|
16
|
+
if (!Type) throw new Error(`Unknown destination "${kind}". Use one of: ${Transports.all.map((t) => t.kind).join(', ')}`);
|
|
17
|
+
return Type;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Create a transport from `<kind>:<target>`. A bare kind (`notion:` or `notion`) or no value at all
|
|
22
|
+
* reuses the last destination of that kind saved in config.
|
|
23
|
+
* @param {string|undefined} value
|
|
24
|
+
* @param {import('../config.js').Config} [config]
|
|
25
|
+
*/
|
|
26
|
+
static create(value, config) {
|
|
27
|
+
const text = String(value || config?.lastDestination || '').trim();
|
|
28
|
+
if (!text) throw new Error(`No destination. Use ${Transports.usage}`);
|
|
29
|
+
const colon = text.indexOf(':');
|
|
30
|
+
const kind = colon < 0 ? text : text.slice(0, colon);
|
|
31
|
+
const Type = Transports.find(kind);
|
|
32
|
+
const target = (colon < 0 ? '' : text.slice(colon + 1).trim()) || config?.destinationFor(Type.kind);
|
|
33
|
+
if (!target) throw new Error(`No ${Type.kind} destination yet: pass ${Type.usage} once and it will be remembered`);
|
|
34
|
+
return new Type(target);
|
|
35
|
+
}
|
|
36
|
+
}
|