@leitwerk-dev/woodpecker 0.0.0-bootstrap.0 → 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.
@@ -0,0 +1,55 @@
1
+ import { LocalProviderStore } from "@leitwerk-dev/test-support/local-git";
2
+ import type { WoodpeckerClientLike } from "./capability.js";
3
+ import type { WoodpeckerPipeline, WoodpeckerRepository } from "./client.js";
4
+ export interface LocalWoodpeckerRepository {
5
+ repository: WoodpeckerRepository;
6
+ pipelines: Array<WoodpeckerPipeline & {
7
+ logs: string;
8
+ controlKey?: string;
9
+ }>;
10
+ }
11
+ export interface LocalWoodpeckerState {
12
+ version: 1;
13
+ sequence: number;
14
+ repositories: LocalWoodpeckerRepository[];
15
+ }
16
+ export interface LocalWoodpeckerOptions {
17
+ root: string;
18
+ baseUrl: string;
19
+ now?: () => number;
20
+ nextId?: () => number;
21
+ }
22
+ /** Local CI state is independent of the repository's Git host. */
23
+ export declare class LocalWoodpeckerAdapter extends LocalProviderStore<LocalWoodpeckerState, LocalWoodpeckerOptions> {
24
+ constructor(options: LocalWoodpeckerOptions);
25
+ seed(fullName: string, id?: number): LocalWoodpeckerRepository;
26
+ publish(repo: LocalWoodpeckerRepository, input: {
27
+ branch: string;
28
+ commit: string;
29
+ status: string;
30
+ logs: string;
31
+ event?: string;
32
+ controlKey?: string;
33
+ }): {
34
+ id: number;
35
+ number: number;
36
+ event: string;
37
+ created_at: number;
38
+ workflows: {
39
+ id: number;
40
+ name: string;
41
+ steps: {
42
+ id: number;
43
+ name: string;
44
+ state: string;
45
+ }[];
46
+ }[];
47
+ branch: string;
48
+ commit: string;
49
+ status: string;
50
+ logs: string;
51
+ controlKey?: string;
52
+ };
53
+ client(): WoodpeckerClientLike;
54
+ }
55
+ //# sourceMappingURL=testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA,OAAO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 +1,92 @@
1
+ import {
2
+ boundedLogTail
3
+ } from "./chunk-L6GKOYHO.js";
4
+
5
+ // src/testing.ts
6
+ import { LocalProviderStore } from "@leitwerk-dev/test-support/local-git";
7
+ var LocalWoodpeckerAdapter = class extends LocalProviderStore {
8
+ constructor(options) {
9
+ super(options, "woodpecker.json", {
10
+ version: 1,
11
+ sequence: 0,
12
+ repositories: []
13
+ });
14
+ }
15
+ seed(fullName, id) {
16
+ const existing = this.state.repositories.find((r) => r.repository.full_name === fullName);
17
+ if (existing) return existing;
18
+ const repo = { repository: { id: id ?? this.id(), full_name: fullName }, pipelines: [] };
19
+ this.state.sequence = Math.max(this.state.sequence, repo.repository.id);
20
+ this.state.repositories.push(repo);
21
+ this.save();
22
+ return repo;
23
+ }
24
+ publish(repo, input) {
25
+ if (![
26
+ "pending",
27
+ "running",
28
+ "success",
29
+ "failure",
30
+ "error",
31
+ "killed",
32
+ "canceled",
33
+ "cancelled",
34
+ "declined",
35
+ "blocked"
36
+ ].includes(input.status))
37
+ throw new Error("Invalid pipeline status");
38
+ const number = this.id();
39
+ const pipeline = {
40
+ ...input,
41
+ id: number,
42
+ number,
43
+ event: input.event ?? "push",
44
+ created_at: Math.floor((this.options.now?.() ?? Date.now()) / 1e3),
45
+ workflows: [
46
+ { id: 1, name: "local", steps: [{ id: 1, name: "validation", state: input.status }] }
47
+ ]
48
+ };
49
+ repo.pipelines.push(pipeline);
50
+ this.save();
51
+ return pipeline;
52
+ }
53
+ client() {
54
+ const repo = (id) => {
55
+ const value = this.state.repositories.find((r) => r.repository.id === id);
56
+ if (!value) throw new Error("Unknown local CI repository");
57
+ return value;
58
+ };
59
+ const pipeline = (id, number) => {
60
+ const value = repo(id).pipelines.find((p) => p.number === number);
61
+ if (!value) throw new Error("Unknown local pipeline");
62
+ return value;
63
+ };
64
+ return {
65
+ profile: { baseUrl: this.options.baseUrl, token: "" },
66
+ lookupRepository: async (name) => {
67
+ const value = this.state.repositories.find((r) => r.repository.full_name === name);
68
+ if (!value) throw new Error("Unknown local CI repository");
69
+ return structuredClone(value.repository);
70
+ },
71
+ listPipelines: async (id, _signal, { page = 1, perPage = 100 } = { page: 1 }) => structuredClone(
72
+ [...repo(id).pipelines].sort((a, b) => b.number - a.number).slice((page - 1) * perPage, page * perPage)
73
+ ),
74
+ getPipeline: async (id, number) => structuredClone(pipeline(id, number)),
75
+ getStepLogs: async (id, number, _step, tail = 400, bytes = 262144) => {
76
+ const original = pipeline(id, number).logs;
77
+ const logs = boundedLogTail(original.split("\n"), tail, bytes);
78
+ return { logs, truncated: logs !== original };
79
+ },
80
+ restartPipeline: async (id, number) => {
81
+ const value = pipeline(id, number);
82
+ value.status = "pending";
83
+ this.save();
84
+ return structuredClone(value);
85
+ }
86
+ };
87
+ }
88
+ };
89
+ export {
90
+ LocalWoodpeckerAdapter
91
+ };
92
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/testing.ts"],"sourcesContent":["import { LocalProviderStore } from \"@leitwerk-dev/test-support/local-git\";\nimport type { WoodpeckerClientLike } from \"./capability.js\";\nimport type { WoodpeckerPipeline, WoodpeckerRepository } from \"./client.js\";\nimport { boundedLogTail } from \"./logs.js\";\n\nexport interface LocalWoodpeckerRepository {\n\trepository: WoodpeckerRepository;\n\tpipelines: Array<WoodpeckerPipeline & { logs: string; controlKey?: string }>;\n}\nexport interface LocalWoodpeckerState {\n\tversion: 1;\n\tsequence: number;\n\trepositories: LocalWoodpeckerRepository[];\n}\nexport interface LocalWoodpeckerOptions {\n\troot: string;\n\tbaseUrl: string;\n\tnow?: () => number;\n\tnextId?: () => number;\n}\n\n/** Local CI state is independent of the repository's Git host. */\nexport class LocalWoodpeckerAdapter extends LocalProviderStore<\n\tLocalWoodpeckerState,\n\tLocalWoodpeckerOptions\n> {\n\tconstructor(options: LocalWoodpeckerOptions) {\n\t\tsuper(options, \"woodpecker.json\", {\n\t\t\tversion: 1,\n\t\t\tsequence: 0,\n\t\t\trepositories: [],\n\t\t});\n\t}\n\tseed(fullName: string, id?: number) {\n\t\tconst existing = this.state.repositories.find((r) => r.repository.full_name === fullName);\n\t\tif (existing) return existing;\n\t\tconst repo = { repository: { id: id ?? this.id(), full_name: fullName }, pipelines: [] };\n\t\tthis.state.sequence = Math.max(this.state.sequence, repo.repository.id);\n\t\tthis.state.repositories.push(repo);\n\t\tthis.save();\n\t\treturn repo;\n\t}\n\tpublish(\n\t\trepo: LocalWoodpeckerRepository,\n\t\tinput: {\n\t\t\tbranch: string;\n\t\t\tcommit: string;\n\t\t\tstatus: string;\n\t\t\tlogs: string;\n\t\t\tevent?: string;\n\t\t\tcontrolKey?: string;\n\t\t},\n\t) {\n\t\tif (\n\t\t\t![\n\t\t\t\t\"pending\",\n\t\t\t\t\"running\",\n\t\t\t\t\"success\",\n\t\t\t\t\"failure\",\n\t\t\t\t\"error\",\n\t\t\t\t\"killed\",\n\t\t\t\t\"canceled\",\n\t\t\t\t\"cancelled\",\n\t\t\t\t\"declined\",\n\t\t\t\t\"blocked\",\n\t\t\t].includes(input.status)\n\t\t)\n\t\t\tthrow new Error(\"Invalid pipeline status\");\n\t\tconst number = this.id();\n\t\tconst pipeline = {\n\t\t\t...input,\n\t\t\tid: number,\n\t\t\tnumber,\n\t\t\tevent: input.event ?? \"push\",\n\t\t\tcreated_at: Math.floor((this.options.now?.() ?? Date.now()) / 1000),\n\t\t\tworkflows: [\n\t\t\t\t{ id: 1, name: \"local\", steps: [{ id: 1, name: \"validation\", state: input.status }] },\n\t\t\t],\n\t\t};\n\t\trepo.pipelines.push(pipeline);\n\t\tthis.save();\n\t\treturn pipeline;\n\t}\n\tclient(): WoodpeckerClientLike {\n\t\tconst repo = (id: number) => {\n\t\t\tconst value = this.state.repositories.find((r) => r.repository.id === id);\n\t\t\tif (!value) throw new Error(\"Unknown local CI repository\");\n\t\t\treturn value;\n\t\t};\n\t\tconst pipeline = (id: number, number: number) => {\n\t\t\tconst value = repo(id).pipelines.find((p) => p.number === number);\n\t\t\tif (!value) throw new Error(\"Unknown local pipeline\");\n\t\t\treturn value;\n\t\t};\n\t\treturn {\n\t\t\tprofile: { baseUrl: this.options.baseUrl, token: \"\" },\n\t\t\tlookupRepository: async (name) => {\n\t\t\t\tconst value = this.state.repositories.find((r) => r.repository.full_name === name);\n\t\t\t\tif (!value) throw new Error(\"Unknown local CI repository\");\n\t\t\t\treturn structuredClone(value.repository);\n\t\t\t},\n\t\t\tlistPipelines: async (id, _signal, { page = 1, perPage = 100 } = { page: 1 }) =>\n\t\t\t\tstructuredClone(\n\t\t\t\t\t[...repo(id).pipelines]\n\t\t\t\t\t\t.sort((a, b) => b.number - a.number)\n\t\t\t\t\t\t.slice((page - 1) * perPage, page * perPage),\n\t\t\t\t),\n\t\t\tgetPipeline: async (id, number) => structuredClone(pipeline(id, number)),\n\t\t\tgetStepLogs: async (id, number, _step, tail = 400, bytes = 262144) => {\n\t\t\t\tconst original = pipeline(id, number).logs;\n\t\t\t\tconst logs = boundedLogTail(original.split(\"\\n\"), tail, bytes);\n\t\t\t\treturn { logs, truncated: logs !== original };\n\t\t\t},\n\t\t\trestartPipeline: async (id, number) => {\n\t\t\t\tconst value = pipeline(id, number);\n\t\t\t\tvalue.status = \"pending\";\n\t\t\t\tthis.save();\n\t\t\t\treturn structuredClone(value);\n\t\t\t},\n\t\t};\n\t}\n}\n"],"mappings":";;;;;AAAA,SAAS,0BAA0B;AAsB5B,IAAM,yBAAN,cAAqC,mBAG1C;AAAA,EACD,YAAY,SAAiC;AAC5C,UAAM,SAAS,mBAAmB;AAAA,MACjC,SAAS;AAAA,MACT,UAAU;AAAA,MACV,cAAc,CAAC;AAAA,IAChB,CAAC;AAAA,EACF;AAAA,EACA,KAAK,UAAkB,IAAa;AACnC,UAAM,WAAW,KAAK,MAAM,aAAa,KAAK,CAAC,MAAM,EAAE,WAAW,cAAc,QAAQ;AACxF,QAAI,SAAU,QAAO;AACrB,UAAM,OAAO,EAAE,YAAY,EAAE,IAAI,MAAM,KAAK,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IACR;AACA,WAAO;AAAA,MACN,SAAS,EAAE,SAAS,KAAK,QAAQ,SAAS,OAAO,GAAG;AAAA,MACpD,kBAAkB,OAAO,SAAS;AACjC,cAAM,QAAQ,KAAK,MAAM,aAAa,KAAK,CAAC,MAAM,EAAE,WAAW,cAAc,IAAI;AACjF,YAAI,CAAC,MAAO,OAAM,IAAI,MAAM,6BAA6B;AACzD,eAAO,gBAAgB,MAAM,UAAU;AAAA,MACxC;AAAA,MACA,eAAe,OAAO,IAAI,SAAS,EAAE,OAAO,GAAG,UAAU,IAAI,IAAI,EAAE,MAAM,EAAE,MAC1E;AAAA,QACC,CAAC,GAAG,KAAK,EAAE,EAAE,SAAS,EACpB,KAAK,CAAC,GAAG,MAAM,EAAE,SAAS,EAAE,MAAM,EAClC,OAAO,OAAO,KAAK,SAAS,OAAO,OAAO;AAAA,MAC7C;AAAA,MACD,aAAa,OAAO,IAAI,WAAW,gBAAgB,SAAS,IAAI,MAAM,CAAC;AAAA,MACvE,aAAa,OAAO,IAAI,QAAQ,OAAO,OAAO,KAAK,QAAQ,WAAW;AACrE,cAAM,WAAW,SAAS,IAAI,MAAM,EAAE;AACtC,cAAM,OAAO,eAAe,SAAS,MAAM,IAAI,GAAG,MAAM,KAAK;AAC7D,eAAO,EAAE,MAAM,WAAW,SAAS,SAAS;AAAA,MAC7C;AAAA,MACA,iBAAiB,OAAO,IAAI,WAAW;AACtC,cAAM,QAAQ,SAAS,IAAI,MAAM;AACjC,cAAM,SAAS;AACf,aAAK,KAAK;AACV,eAAO,gBAAgB,KAAK;AAAA,MAC7B;AAAA,IACD;AAAA,EACD;AACD;","names":[]}
@@ -0,0 +1,5 @@
1
+ import { type ExternalWriteLogRepoLike } from "@leitwerk-dev/external-writes";
2
+ import { type ServerExtensionAPI } from "@leitwerk-dev/process-sdk";
3
+ import type { WoodpeckerIntegration } from "./capability.js";
4
+ export declare function registerWoodpeckerTools(api: ServerExtensionAPI, integration: WoodpeckerIntegration, writes: ExternalWriteLogRepoLike): void;
5
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,KAAK,wBAAwB,EAE7B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAIN,KAAK,kBAAkB,EAEvB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAO7D,wBAAgB,uBAAuB,CACtC,GAAG,EAAE,kBAAkB,EACvB,WAAW,EAAE,qBAAqB,EAClC,MAAM,EAAE,wBAAwB,QA6FhC"}
package/package.json CHANGED
@@ -1,16 +1,56 @@
1
1
  {
2
- "name": "@leitwerk-dev/woodpecker",
3
- "version": "0.0.0-bootstrap.0",
4
- "description": "Registration placeholder only. Not a usable Leitwerk release.",
5
- "license": "Apache-2.0",
6
- "repository": {
7
- "type": "git",
8
- "url": "git+https://github.com/leitwerk-dev/leitwerk.git"
9
- },
10
- "publishConfig": {
11
- "access": "public",
12
- "registry": "https://registry.npmjs.org/",
13
- "tag": "bootstrap",
14
- "provenance": false
15
- }
2
+ "name": "@leitwerk-dev/woodpecker",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "leitwerk": {
6
+ "extension": {
7
+ "source": "./src/index.ts",
8
+ "import": "./dist/index.js"
9
+ },
10
+ "discover": false
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "source": "./src/index.ts",
15
+ "import": "./dist/index.js",
16
+ "types": "./dist/index.d.ts"
17
+ },
18
+ "./testing": {
19
+ "source": "./src/testing.ts",
20
+ "import": "./dist/testing.js",
21
+ "types": "./dist/testing.d.ts"
22
+ }
23
+ },
24
+ "scripts": {
25
+ "build": "tsup && tsc -p tsconfig.tsup.json --emitDeclarationOnly"
26
+ },
27
+ "dependencies": {
28
+ "@leitwerk-dev/domain": "0.2.0",
29
+ "@leitwerk-dev/external-writes": "0.2.0",
30
+ "@leitwerk-dev/process-sdk": "0.2.0",
31
+ "@leitwerk-dev/watcher-utils": "0.2.0",
32
+ "@leitwerk-dev/test-support": "0.2.0"
33
+ },
34
+ "devDependencies": {
35
+ "tsup": "^8.5.1",
36
+ "@types/node": "^26.2.0"
37
+ },
38
+ "license": "Apache-2.0",
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "engines": {
43
+ "node": ">=26 <27"
44
+ },
45
+ "files": [
46
+ "dist/**",
47
+ "src/**",
48
+ "!dist/**/*.test.*",
49
+ "!src/**/*.test.ts"
50
+ ],
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/leitwerk-dev/leitwerk.git",
54
+ "directory": "extensions/woodpecker"
55
+ }
16
56
  }
package/src/binding.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { resolveRepositoryProjectBinding } from "@leitwerk-dev/process-sdk";
2
+
3
+ export type { RepositoryProjectBinding as WoodpeckerProjectBinding } from "@leitwerk-dev/process-sdk";
4
+ export const resolveWoodpeckerProjectBinding = (
5
+ ctx: Parameters<typeof resolveRepositoryProjectBinding>[0],
6
+ ) => resolveRepositoryProjectBinding(ctx, "woodpecker", "forgejo");
@@ -0,0 +1,11 @@
1
+ import { createCapabilityToken } from "@leitwerk-dev/process-sdk";
2
+ import type { WoodpeckerClient } from "./client.js";
3
+ /** Public contract shared by HTTP and local adapters. */
4
+ export type WoodpeckerClientLike = Pick<WoodpeckerClient, keyof WoodpeckerClient>;
5
+
6
+ export interface WoodpeckerIntegration {
7
+ client(profile: string): WoodpeckerClientLike;
8
+ }
9
+ export const woodpeckerIntegration = createCapabilityToken<WoodpeckerIntegration>(
10
+ "@leitwerk-private/woodpecker.integration",
11
+ );
package/src/client.ts ADDED
@@ -0,0 +1,142 @@
1
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
2
+ import { IntegrationHttpClient } from "@leitwerk-dev/process-sdk";
3
+ import { boundedLogTail } from "./logs.js";
4
+
5
+ export interface WoodpeckerProfile {
6
+ baseUrl: string;
7
+ token: string;
8
+ }
9
+ export interface WoodpeckerRepository {
10
+ id: number;
11
+ full_name: string;
12
+ }
13
+ export interface WoodpeckerPipeline {
14
+ id: number;
15
+ number: number;
16
+ status: string;
17
+ event: string;
18
+ branch: string;
19
+ commit: string;
20
+ created_at?: number;
21
+ workflows?: unknown[];
22
+ }
23
+
24
+ interface WoodpeckerLogEntry {
25
+ data?: number[] | string;
26
+ }
27
+
28
+ function decodeLogData(data: WoodpeckerLogEntry["data"]): string {
29
+ if (Array.isArray(data)) {
30
+ return new TextDecoder("utf-8", { fatal: false }).decode(Uint8Array.from(data));
31
+ }
32
+ if (typeof data !== "string") return "";
33
+ if (/^[A-Za-z0-9+/]*={0,2}$/.test(data) && data.length % 4 === 0) {
34
+ try {
35
+ const binary = atob(data);
36
+ return new TextDecoder("utf-8", { fatal: false }).decode(
37
+ Uint8Array.from(binary, (character) => character.charCodeAt(0)),
38
+ );
39
+ } catch {
40
+ // Preserve an unexpected plain-text representation instead of hiding logs.
41
+ }
42
+ }
43
+ return data;
44
+ }
45
+
46
+ export function parseWoodpeckerProfiles(value: unknown): Map<string, WoodpeckerProfile> {
47
+ const profiles = new Map<string, WoodpeckerProfile>();
48
+ for (const [name, raw] of Object.entries(
49
+ asUnknownRecord(asUnknownRecord(value)?.profiles) ?? {},
50
+ )) {
51
+ const config = asUnknownRecord(raw) ?? {};
52
+ const baseUrl = typeof config.base_url === "string" ? config.base_url.replace(/\/+$/, "") : "";
53
+ const token = typeof config.token === "string" ? config.token.trim() : "";
54
+ if (!/^https:\/\//.test(baseUrl))
55
+ throw new Error(`Woodpecker profile '${name}' requires an HTTPS base_url`);
56
+ if (!token) throw new Error(`Woodpecker profile '${name}' requires a token`);
57
+ profiles.set(name, { baseUrl, token });
58
+ }
59
+ return profiles;
60
+ }
61
+
62
+ export class WoodpeckerClient extends IntegrationHttpClient {
63
+ constructor(readonly profile: WoodpeckerProfile) {
64
+ super("Woodpecker", `${profile.baseUrl}/api`, {
65
+ Authorization: `Bearer ${profile.token}`,
66
+ Accept: "application/json",
67
+ });
68
+ }
69
+
70
+ lookupRepository(fullName: string, signal?: AbortSignal): Promise<WoodpeckerRepository> {
71
+ return this.request(`/repos/lookup/${encodeURIComponent(fullName)}`, {
72
+ signal,
73
+ });
74
+ }
75
+
76
+ listPipelines(
77
+ repoId: number,
78
+ signal?: AbortSignal,
79
+ pagination: { page: number; perPage?: number } = { page: 1 },
80
+ ): Promise<WoodpeckerPipeline[]> {
81
+ const { page, perPage = 100 } = pagination;
82
+ if (
83
+ !Number.isSafeInteger(page) ||
84
+ page < 1 ||
85
+ !Number.isSafeInteger(perPage) ||
86
+ perPage < 1 ||
87
+ perPage > 100
88
+ )
89
+ throw new Error("Invalid Woodpecker pipeline pagination");
90
+ return this.request(`/repos/${repoId}/pipelines?page=${page}&perPage=${perPage}`, {
91
+ signal,
92
+ });
93
+ }
94
+
95
+ getPipeline(repoId: number, number: number, signal?: AbortSignal): Promise<WoodpeckerPipeline> {
96
+ return this.request(`/repos/${repoId}/pipelines/${number}`, { signal });
97
+ }
98
+
99
+ async getStepLogs(
100
+ repoId: number,
101
+ number: number,
102
+ stepId: number,
103
+ tailLines = 400,
104
+ maxBytes = 262_144,
105
+ signal?: AbortSignal,
106
+ ) {
107
+ const body = await (
108
+ await this.response(`/repos/${repoId}/logs/${number}/${stepId}`, {
109
+ signal,
110
+ })
111
+ ).text();
112
+ let text = body;
113
+ try {
114
+ const entries = JSON.parse(body) as unknown;
115
+ if (Array.isArray(entries)) {
116
+ text = entries
117
+ .map((entry) =>
118
+ decodeLogData(asUnknownRecord(entry)?.data as WoodpeckerLogEntry["data"]).replace(
119
+ /\r?\n$/,
120
+ "",
121
+ ),
122
+ )
123
+ .join("\n");
124
+ }
125
+ } catch {
126
+ // Older adapters may return text directly; retain it as-is.
127
+ }
128
+ const output = boundedLogTail(text.split(/\r?\n/), tailLines, maxBytes);
129
+ return { logs: output, truncated: output.length < text.length };
130
+ }
131
+
132
+ restartPipeline(
133
+ repoId: number,
134
+ number: number,
135
+ signal?: AbortSignal,
136
+ ): Promise<WoodpeckerPipeline> {
137
+ return this.request(`/repos/${repoId}/pipelines/${number}`, {
138
+ method: "POST",
139
+ signal,
140
+ });
141
+ }
142
+ }
@@ -0,0 +1,27 @@
1
+ import type { ExternalActionSource } from "@leitwerk-dev/process-sdk";
2
+ export const WOODPECKER_PIPELINE_KIND = "@leitwerk-private/woodpecker.pipeline";
3
+ export interface WoodpeckerPipelineSourceConfig {
4
+ profile: string;
5
+ owner: string;
6
+ repo: string;
7
+ branch: string;
8
+ headSha: string;
9
+ afterPipelineNumber?: number;
10
+ disabled?: boolean;
11
+ pollInterval?: string;
12
+ statuses?: string[];
13
+ }
14
+ export const woodpeckerExternal = {
15
+ pipeline<TParams, TState>(
16
+ resolve: (ctx: { params: TParams; state: TState }) => WoodpeckerPipelineSourceConfig,
17
+ ): ExternalActionSource<TParams, TState> {
18
+ return {
19
+ kind: WOODPECKER_PIPELINE_KIND,
20
+ label: "Woodpecker pipeline completion",
21
+ description: "Fires when a pipeline matching the current source head completes",
22
+ config: {},
23
+ inputMode: "none",
24
+ resolve,
25
+ };
26
+ },
27
+ };
package/src/index.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { ExternalWriteLogRepoLike } from "@leitwerk-dev/external-writes";
2
+ import { coreHostCapabilities, type LeitwerkExtensionModule } from "@leitwerk-dev/process-sdk";
3
+ import { type WoodpeckerIntegration, woodpeckerIntegration } from "./capability.js";
4
+ import { parseWoodpeckerProfiles, WoodpeckerClient } from "./client.js";
5
+ import { createWoodpeckerProvider } from "./provider.js";
6
+ import { registerWoodpeckerTools } from "./tools.js";
7
+ export const manifest = { id: "woodpecker", version: "0.1.9" } as const;
8
+ const extension: LeitwerkExtensionModule = {
9
+ manifest,
10
+ setupServer(api, config) {
11
+ const profiles = parseWoodpeckerProfiles(config);
12
+ const integration: WoodpeckerIntegration = {
13
+ client(profile) {
14
+ const value = profiles.get(profile);
15
+ if (!value) throw new Error(`Unknown Woodpecker profile '${profile}'`);
16
+ return new WoodpeckerClient(value);
17
+ },
18
+ };
19
+ setupWoodpeckerIntegration(api, integration);
20
+ },
21
+ };
22
+
23
+ export * from "./capability.js";
24
+ export * from "./client.js";
25
+ export * from "./external.js";
26
+ export default extension;
27
+
28
+ /** Register shared tools and polling with an explicit integration. */
29
+ export function setupWoodpeckerIntegration(
30
+ api: Parameters<NonNullable<LeitwerkExtensionModule["setupServer"]>>[0],
31
+ integration: WoodpeckerIntegration,
32
+ options: { now?: () => number } = {},
33
+ ) {
34
+ api.provide(woodpeckerIntegration, integration);
35
+ const deps = api.get(coreHostCapabilities.serverSetup);
36
+ if (!deps || Array.isArray(deps)) return;
37
+ registerWoodpeckerTools(api, integration, deps.externalWrites as ExternalWriteLogRepoLike);
38
+ return createWoodpeckerProvider(deps, integration, options);
39
+ }
40
+
41
+ export * from "./binding.js";
package/src/logs.ts ADDED
@@ -0,0 +1,8 @@
1
+ /** Keep a bounded tail without splitting a UTF-8 character. */
2
+ export function boundedLogTail(lines: string[], tailLines: number, maxBytes: number): string {
3
+ const encoded = Buffer.from(lines.slice(-Math.min(Math.max(tailLines, 1), 2_000)).join("\n"));
4
+ const cap = Math.min(Math.max(maxBytes, 1), 1_048_576);
5
+ let start = Math.max(0, encoded.length - cap);
6
+ while (start < encoded.length && (encoded[start] & 0xc0) === 0x80) start++;
7
+ return encoded.subarray(start).toString("utf8");
8
+ }
@@ -0,0 +1,121 @@
1
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
2
+ import {
3
+ type CoreServerSetupDeps,
4
+ createExternalSourcePollReporter,
5
+ } from "@leitwerk-dev/process-sdk";
6
+ import { createPollSchedule, emptyPollResult } from "@leitwerk-dev/watcher-utils";
7
+ import type { WoodpeckerClientLike, WoodpeckerIntegration } from "./capability.js";
8
+ import { WOODPECKER_PIPELINE_KIND, type WoodpeckerPipelineSourceConfig } from "./external.js";
9
+
10
+ function parse(value: unknown): WoodpeckerPipelineSourceConfig | null {
11
+ const config = asUnknownRecord(value) ?? {};
12
+ if (
13
+ ["profile", "owner", "repo", "branch", "headSha"].some(
14
+ (key) => typeof config[key] !== "string" || !(config[key] as string).trim(),
15
+ )
16
+ )
17
+ return null;
18
+ return {
19
+ profile: config.profile as string,
20
+ owner: config.owner as string,
21
+ repo: config.repo as string,
22
+ branch: config.branch as string,
23
+ headSha: config.headSha as string,
24
+ afterPipelineNumber:
25
+ typeof config.afterPipelineNumber === "number" ? config.afterPipelineNumber : 0,
26
+ disabled: config.disabled === true,
27
+ pollInterval: typeof config.pollInterval === "string" ? config.pollInterval : "30s",
28
+ statuses: Array.isArray(config.statuses)
29
+ ? config.statuses.filter((value): value is string => typeof value === "string")
30
+ : undefined,
31
+ };
32
+ }
33
+ const terminal = new Set([
34
+ "success",
35
+ "failure",
36
+ "error",
37
+ "killed",
38
+ "canceled",
39
+ "cancelled",
40
+ "declined",
41
+ "blocked",
42
+ ]);
43
+ const supportedEvents = new Set(["push", "pull_request", "pull_request_closed"]);
44
+
45
+ function matchesBranch(event: string, pipelineBranch: string, sourceBranch: string): boolean {
46
+ // Woodpecker reports the PR target branch in `branch`. The commit uniquely
47
+ // identifies the watched source head, so branch filtering only applies to pushes.
48
+ return event !== "push" || pipelineBranch === sourceBranch;
49
+ }
50
+
51
+ export function createWoodpeckerProvider(
52
+ deps: CoreServerSetupDeps,
53
+ integration: WoodpeckerIntegration,
54
+ options: { now?: () => number } = {},
55
+ ) {
56
+ const due = createPollSchedule(options.now);
57
+ return deps.polling.create({
58
+ id: "woodpecker",
59
+ pollInterval: () => "5s",
60
+ isEnabled: () => true,
61
+ defaultIntervalMs: 5_000,
62
+ async pollOnce() {
63
+ const result = emptyPollResult();
64
+ const report = createExternalSourcePollReporter(deps.externalSources, result);
65
+ await report.poll(WOODPECKER_PIPELINE_KIND, async (armed) => {
66
+ const config = parse(armed.resolved);
67
+ if (!config) {
68
+ result.errors.push(`${armed.id}:invalid_config`);
69
+ return;
70
+ }
71
+ if (config.disabled) return;
72
+ const key = `${armed.instanceId}:${armed.id}`;
73
+ if (!due(key, config.pollInterval)) return;
74
+ const client = integration.client(config.profile);
75
+ const repo = await client.lookupRepository(`${config.owner}/${config.repo}`);
76
+ const pipeline = await findLatestPipeline(client, repo.id, config);
77
+ if (
78
+ !pipeline ||
79
+ !terminal.has(pipeline.status) ||
80
+ (config.statuses && !config.statuses.includes(pipeline.status))
81
+ )
82
+ return;
83
+ await report.fire(
84
+ armed,
85
+ { repositoryId: repo.id, pipeline },
86
+ `${pipeline.number}:${pipeline.status}`,
87
+ );
88
+ });
89
+ return result;
90
+ },
91
+ });
92
+ }
93
+
94
+ /** The bounded lookup reports incomplete history instead of waiting silently. */
95
+ export async function findLatestPipeline(
96
+ client: WoodpeckerClientLike,
97
+ repoId: number,
98
+ config: WoodpeckerPipelineSourceConfig,
99
+ ) {
100
+ for (let page = 1; page <= 10; page++) {
101
+ const pipelines = (await client.listPipelines(repoId, undefined, { page, perPage: 100 })).sort(
102
+ (a, b) => b.number - a.number,
103
+ );
104
+ const match = pipelines.find(
105
+ (candidate) =>
106
+ candidate.number > (config.afterPipelineNumber ?? 0) &&
107
+ candidate.commit === config.headSha &&
108
+ supportedEvents.has(candidate.event) &&
109
+ matchesBranch(candidate.event, candidate.branch, config.branch),
110
+ );
111
+ if (match) return match;
112
+ if (
113
+ pipelines.length < 100 ||
114
+ pipelines.some((candidate) => candidate.number <= (config.afterPipelineNumber ?? 0))
115
+ )
116
+ return null;
117
+ }
118
+ throw new Error(
119
+ "Woodpecker pipeline lookup window exhausted (1000 pipelines); inspect the repository and update the watched pipeline floor before retrying",
120
+ );
121
+ }