@leitwerk-dev/forgejo-repo-change 0.3.0 → 0.4.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/dist/index.js CHANGED
@@ -3,502 +3,40 @@ import { forgejoIntegration } from "@leitwerk-dev/forgejo";
3
3
  import { gitSshIntegration } from "@leitwerk-dev/git-ssh";
4
4
  import { woodpeckerIntegration } from "@leitwerk-dev/woodpecker";
5
5
 
6
- // src/launcher.ts
7
- import { buildAutoWorkBranchFromSeed } from "@leitwerk-dev/coding/auto-work-branch";
8
-
9
- // ../../node_modules/valibot/dist/index.mjs
10
- var store$4;
11
- // @__NO_SIDE_EFFECTS__
12
- function getGlobalConfig(config$1) {
13
- return {
14
- lang: config$1?.lang ?? store$4?.lang,
15
- message: config$1?.message,
16
- abortEarly: config$1?.abortEarly ?? store$4?.abortEarly,
17
- abortPipeEarly: config$1?.abortPipeEarly ?? store$4?.abortPipeEarly
18
- };
19
- }
20
- var store$3;
21
- // @__NO_SIDE_EFFECTS__
22
- function getGlobalMessage(lang) {
23
- return store$3?.get(lang);
24
- }
25
- var store$2;
26
- // @__NO_SIDE_EFFECTS__
27
- function getSchemaMessage(lang) {
28
- return store$2?.get(lang);
29
- }
30
- var store$1;
31
- // @__NO_SIDE_EFFECTS__
32
- function getSpecificMessage(reference, lang) {
33
- return store$1?.get(reference)?.get(lang);
34
- }
35
- // @__NO_SIDE_EFFECTS__
36
- function _stringify(input) {
37
- const type = typeof input;
38
- if (type === "string") return `"${input}"`;
39
- if (type === "number" || type === "bigint" || type === "boolean") return `${input}`;
40
- if (type === "object" || type === "function") return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
41
- return type;
42
- }
43
- function _addIssue(context, label, dataset, config$1, other) {
44
- const input = other && "input" in other ? other.input : dataset.value;
45
- const expected = other?.expected ?? context.expects ?? null;
46
- const received = other?.received ?? /* @__PURE__ */ _stringify(input);
47
- const issue = {
48
- kind: context.kind,
49
- type: context.type,
50
- input,
51
- expected,
52
- received,
53
- message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
54
- requirement: context.requirement,
55
- path: other?.path,
56
- issues: other?.issues,
57
- lang: config$1.lang,
58
- abortEarly: config$1.abortEarly,
59
- abortPipeEarly: config$1.abortPipeEarly
60
- };
61
- const isSchema = context.kind === "schema";
62
- const message$1 = other?.message ?? context.message ?? /* @__PURE__ */ getSpecificMessage(context.reference, issue.lang) ?? (isSchema ? /* @__PURE__ */ getSchemaMessage(issue.lang) : null) ?? config$1.message ?? /* @__PURE__ */ getGlobalMessage(issue.lang);
63
- if (message$1 !== void 0) issue.message = typeof message$1 === "function" ? message$1(issue) : message$1;
64
- if (isSchema) dataset.typed = false;
65
- if (dataset.issues) dataset.issues.push(issue);
66
- else dataset.issues = [issue];
67
- }
68
- // @__NO_SIDE_EFFECTS__
69
- function _getStandardProps(context) {
70
- return {
71
- version: 1,
72
- vendor: "valibot",
73
- validate(value$1) {
74
- return context["~run"]({ value: value$1 }, /* @__PURE__ */ getGlobalConfig());
75
- }
76
- };
77
- }
78
- // @__NO_SIDE_EFFECTS__
79
- function _isValidObjectKey(object$1, key) {
80
- return Object.hasOwn(object$1, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor";
81
- }
82
- // @__NO_SIDE_EFFECTS__
83
- function check(requirement, message$1) {
84
- return {
85
- kind: "validation",
86
- type: "check",
87
- reference: check,
88
- async: false,
89
- expects: null,
90
- requirement,
91
- message: message$1,
92
- "~run"(dataset, config$1) {
93
- if (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, "input", dataset, config$1);
94
- return dataset;
95
- }
96
- };
97
- }
98
- // @__NO_SIDE_EFFECTS__
99
- function parseJson(config$1, message$1) {
100
- return {
101
- kind: "transformation",
102
- type: "parse_json",
103
- reference: parseJson,
104
- config: config$1,
105
- message: message$1,
106
- async: false,
107
- "~run"(dataset, config$2) {
108
- try {
109
- dataset.value = JSON.parse(dataset.value, this.config?.reviver);
110
- } catch (error) {
111
- if (error instanceof Error) {
112
- _addIssue(this, "JSON", dataset, config$2, { received: `"${error.message}"` });
113
- dataset.typed = false;
114
- } else throw error;
115
- }
116
- return dataset;
117
- }
118
- };
119
- }
120
- // @__NO_SIDE_EFFECTS__
121
- function getFallback(schema, dataset, config$1) {
122
- return typeof schema.fallback === "function" ? schema.fallback(dataset, config$1) : schema.fallback;
123
- }
124
- // @__NO_SIDE_EFFECTS__
125
- function getDefault(schema, dataset, config$1) {
126
- return typeof schema.default === "function" ? schema.default(dataset, config$1) : schema.default;
127
- }
128
- // @__NO_SIDE_EFFECTS__
129
- function custom(check$1, message$1) {
130
- return {
131
- kind: "schema",
132
- type: "custom",
133
- reference: custom,
134
- expects: "unknown",
135
- async: false,
136
- check: check$1,
137
- message: message$1,
138
- get "~standard"() {
139
- return /* @__PURE__ */ _getStandardProps(this);
140
- },
141
- "~run"(dataset, config$1) {
142
- if (this.check(dataset.value)) dataset.typed = true;
143
- else _addIssue(this, "type", dataset, config$1);
144
- return dataset;
145
- }
146
- };
147
- }
148
- // @__NO_SIDE_EFFECTS__
149
- function object(entries$1, message$1) {
150
- return {
151
- kind: "schema",
152
- type: "object",
153
- reference: object,
154
- expects: "Object",
155
- async: false,
156
- entries: entries$1,
157
- message: message$1,
158
- get "~standard"() {
159
- return /* @__PURE__ */ _getStandardProps(this);
160
- },
161
- "~run"(dataset, config$1) {
162
- const input = dataset.value;
163
- if (input && typeof input === "object") {
164
- dataset.typed = true;
165
- dataset.value = {};
166
- for (const key in this.entries) {
167
- const valueSchema = this.entries[key];
168
- if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
169
- const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
170
- const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
171
- if (valueDataset.issues) {
172
- const pathItem = {
173
- type: "object",
174
- origin: "value",
175
- input,
176
- key,
177
- value: value$1
178
- };
179
- for (const issue of valueDataset.issues) {
180
- if (issue.path) issue.path.unshift(pathItem);
181
- else issue.path = [pathItem];
182
- dataset.issues?.push(issue);
183
- }
184
- if (!dataset.issues) dataset.issues = valueDataset.issues;
185
- if (config$1.abortEarly) {
186
- dataset.typed = false;
187
- break;
188
- }
189
- }
190
- if (!valueDataset.typed) dataset.typed = false;
191
- dataset.value[key] = valueDataset.value;
192
- } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
193
- else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
194
- _addIssue(this, "key", dataset, config$1, {
195
- input: void 0,
196
- expected: `"${key}"`,
197
- path: [{
198
- type: "object",
199
- origin: "key",
200
- input,
201
- key,
202
- value: input[key]
203
- }]
204
- });
205
- if (config$1.abortEarly) break;
206
- }
207
- }
208
- } else _addIssue(this, "type", dataset, config$1);
209
- return dataset;
210
- }
211
- };
212
- }
213
- // @__NO_SIDE_EFFECTS__
214
- function optional(wrapped, default_) {
215
- return {
216
- kind: "schema",
217
- type: "optional",
218
- reference: optional,
219
- expects: `(${wrapped.expects} | undefined)`,
220
- async: false,
221
- wrapped,
222
- default: default_,
223
- get "~standard"() {
224
- return /* @__PURE__ */ _getStandardProps(this);
225
- },
226
- "~run"(dataset, config$1) {
227
- if (dataset.value === void 0) {
228
- if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
229
- if (dataset.value === void 0) {
230
- dataset.typed = true;
231
- return dataset;
232
- }
233
- }
234
- return this.wrapped["~run"](dataset, config$1);
235
- }
236
- };
237
- }
238
- // @__NO_SIDE_EFFECTS__
239
- function record(key, value$1, message$1) {
240
- return {
241
- kind: "schema",
242
- type: "record",
243
- reference: record,
244
- expects: "Object",
245
- async: false,
246
- key,
247
- value: value$1,
248
- message: message$1,
249
- get "~standard"() {
250
- return /* @__PURE__ */ _getStandardProps(this);
251
- },
252
- "~run"(dataset, config$1) {
253
- const input = dataset.value;
254
- if (input && typeof input === "object") {
255
- dataset.typed = true;
256
- dataset.value = {};
257
- for (const entryKey in input) if (/* @__PURE__ */ _isValidObjectKey(input, entryKey)) {
258
- const entryValue = input[entryKey];
259
- const keyDataset = this.key["~run"]({ value: entryKey }, config$1);
260
- if (keyDataset.issues) {
261
- const pathItem = {
262
- type: "object",
263
- origin: "key",
264
- input,
265
- key: entryKey,
266
- value: entryValue
267
- };
268
- for (const issue of keyDataset.issues) {
269
- issue.path = [pathItem];
270
- dataset.issues?.push(issue);
271
- }
272
- if (!dataset.issues) dataset.issues = keyDataset.issues;
273
- if (config$1.abortEarly) {
274
- dataset.typed = false;
275
- break;
276
- }
277
- }
278
- const valueDataset = this.value["~run"]({ value: entryValue }, config$1);
279
- if (valueDataset.issues) {
280
- const pathItem = {
281
- type: "object",
282
- origin: "value",
283
- input,
284
- key: entryKey,
285
- value: entryValue
286
- };
287
- for (const issue of valueDataset.issues) {
288
- if (issue.path) issue.path.unshift(pathItem);
289
- else issue.path = [pathItem];
290
- dataset.issues?.push(issue);
291
- }
292
- if (!dataset.issues) dataset.issues = valueDataset.issues;
293
- if (config$1.abortEarly) {
294
- dataset.typed = false;
295
- break;
296
- }
297
- }
298
- if (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;
299
- if (keyDataset.typed) dataset.value[keyDataset.value] = valueDataset.value;
300
- }
301
- } else _addIssue(this, "type", dataset, config$1);
302
- return dataset;
303
- }
304
- };
305
- }
306
- // @__NO_SIDE_EFFECTS__
307
- function string(message$1) {
308
- return {
309
- kind: "schema",
310
- type: "string",
311
- reference: string,
312
- expects: "string",
313
- async: false,
314
- message: message$1,
315
- get "~standard"() {
316
- return /* @__PURE__ */ _getStandardProps(this);
317
- },
318
- "~run"(dataset, config$1) {
319
- if (typeof dataset.value === "string") dataset.typed = true;
320
- else _addIssue(this, "type", dataset, config$1);
321
- return dataset;
322
- }
323
- };
324
- }
325
- // @__NO_SIDE_EFFECTS__
326
- function unknown() {
327
- return {
328
- kind: "schema",
329
- type: "unknown",
330
- reference: unknown,
331
- expects: "unknown",
332
- async: false,
333
- get "~standard"() {
334
- return /* @__PURE__ */ _getStandardProps(this);
335
- },
336
- "~run"(dataset) {
337
- dataset.typed = true;
338
- return dataset;
339
- }
340
- };
341
- }
342
- // @__NO_SIDE_EFFECTS__
343
- function pipe(...pipe$1) {
344
- return {
345
- ...pipe$1[0],
346
- pipe: pipe$1,
347
- get "~standard"() {
348
- return /* @__PURE__ */ _getStandardProps(this);
349
- },
350
- "~run"(dataset, config$1) {
351
- for (const item of pipe$1) if (item.kind !== "metadata") {
352
- if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
353
- dataset.typed = false;
354
- break;
355
- }
356
- if (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly) dataset = item["~run"](dataset, config$1);
357
- }
358
- return dataset;
359
- }
360
- };
361
- }
362
-
363
- // ../../packages/domain/dist/index.js
364
- function trimString(value) {
365
- return typeof value === "string" ? value.trim() : "";
366
- }
367
- var SYSTEM_ACTOR = { id: "system", kind: "system", provider: null };
368
- function serializeActor(actor) {
369
- return JSON.stringify({
370
- id: actor.id,
371
- kind: actor.kind,
372
- provider: actor.provider,
373
- ...actor.displayName !== void 0 ? { displayName: actor.displayName } : {}
374
- });
375
- }
376
- var SERIALIZED_SYSTEM_ACTOR = serializeActor(SYSTEM_ACTOR);
377
- var jsonObjectSchema = custom(
378
- (value) => typeof value === "object" && value !== null && !Array.isArray(value),
379
- "Expected object"
380
- );
381
- var instanceTurnConfigSchema = pipe(
382
- jsonObjectSchema,
383
- object({
384
- modelProfileId: optional(unknown())
385
- })
386
- );
387
- var strictInstanceTurnConfigsJsonSchema = pipe(
388
- string(),
389
- parseJson(),
390
- jsonObjectSchema,
391
- record(string(), instanceTurnConfigSchema)
392
- );
393
- var copiedUnknownRecordSchema = pipe(
394
- unknown(),
395
- check(isUnknownRecord, "Expected object"),
396
- record(string(), unknown())
397
- );
398
- function isUnknownRecord(value) {
399
- return typeof value === "object" && value !== null && !Array.isArray(value);
400
- }
401
-
402
6
  // src/launcher.ts
403
7
  import {
404
- SafeLaunchPreparationError
405
- } from "@leitwerk-dev/process-sdk";
8
+ createRepositoryChangeLauncher,
9
+ repositoryIssueChangeLaunchConfig
10
+ } from "@leitwerk-dev/coding/repository-change-launch";
11
+ import { createGitSshPreparationCheck } from "@leitwerk-dev/git-ssh";
406
12
 
407
13
  // src/params.ts
408
14
  import {
409
15
  createRepositoryChangeParamsCodec,
410
- normalizeRepositoryChangeParamsInput,
411
- repositoryChangeParamsRecord
16
+ normalizeRepositoryIssueChangeParams
412
17
  } from "@leitwerk-dev/coding/repository-change-launch";
413
18
  function isIssueOrigin(params) {
414
19
  return params.origin === "issue";
415
20
  }
416
21
  var forgejoRepoChangeParamsCodec = createRepositoryChangeParamsCodec({
417
22
  normalize(value) {
418
- const shared = normalizeRepositoryChangeParamsInput(value, "Forgejo Repo Change");
419
- const record3 = repositoryChangeParamsRecord(value, "Forgejo Repo Change");
420
- const text = (name) => {
421
- const value2 = trimString(record3[name]);
422
- if (!value2) throw new Error(`Forgejo Repo Change requires ${name}`);
423
- return value2;
424
- };
425
- const common = {
426
- ...shared,
427
- forgejoProfile: text("forgejoProfile"),
428
- woodpeckerProfile: text("woodpeckerProfile"),
429
- sshCredentialRef: text("sshCredentialRef"),
430
- owner: text("owner"),
431
- repo: text("repo")
432
- };
433
- const origin = trimString(record3.origin);
434
- if (origin === "ui") {
435
- return {
436
- ...common,
437
- origin: "ui",
438
- issueNumber: null,
439
- issueUrl: null,
440
- triggerLabel: null,
441
- doneLabel: null
442
- };
443
- }
444
- if (origin && origin !== "issue") {
445
- throw new Error("Forgejo Repo Change requires a valid origin");
446
- }
447
- if (typeof record3.issueNumber !== "number" || !Number.isInteger(record3.issueNumber) || record3.issueNumber <= 0)
448
- throw new Error("Forgejo Repo Change requires issueNumber");
449
- return {
450
- ...common,
451
- origin: "issue",
452
- issueNumber: record3.issueNumber,
453
- issueUrl: text("issueUrl"),
454
- triggerLabel: text("triggerLabel"),
455
- doneLabel: text("doneLabel")
456
- };
23
+ return normalizeRepositoryIssueChangeParams(value, "Forgejo Repo Change", [
24
+ "forgejoProfile",
25
+ "woodpeckerProfile",
26
+ "sshCredentialRef",
27
+ "owner",
28
+ "repo"
29
+ ]);
457
30
  }
458
31
  });
459
32
 
460
33
  // src/profile-bindings.ts
461
- function record2(value, label) {
462
- if (!value || typeof value !== "object" || Array.isArray(value))
463
- throw new Error(`${label} must be an object`);
464
- return value;
465
- }
466
- function field(value, fallback, label) {
467
- if (value === void 0) return fallback;
468
- if (typeof value !== "string" || !value.trim())
469
- throw new Error(`${label} must be a non-empty string`);
470
- return value.trim();
471
- }
34
+ import { parseRepositoryProfileBindings } from "@leitwerk-dev/coding/repository-change-launch";
472
35
  function parseProfileBindings(raw) {
473
- const config = raw === void 0 ? {} : record2(raw, "forgejo-repo-change configuration");
474
- if (config.profile_bindings === void 0) return Object.freeze({});
475
- const mappings = record2(config.profile_bindings, "profile_bindings");
476
- const entries = Object.entries(mappings).map(([profile, value]) => {
477
- if (!profile.trim() || profile.trim() !== profile)
478
- throw new Error(
479
- "profile_bindings keys must be non-empty profile names without surrounding whitespace"
480
- );
481
- const mapping = record2(value, `profile_bindings.${profile}`);
482
- for (const key of Object.keys(mapping))
483
- if (key !== "woodpecker_profile" && key !== "ssh_credential_ref")
484
- throw new Error(`Unknown profile_bindings.${profile}.${key}`);
485
- return [
486
- profile,
487
- Object.freeze({
488
- woodpeckerProfile: field(
489
- mapping.woodpecker_profile,
490
- profile,
491
- `profile_bindings.${profile}.woodpecker_profile`
492
- ),
493
- sshCredentialRef: field(
494
- mapping.ssh_credential_ref,
495
- profile,
496
- `profile_bindings.${profile}.ssh_credential_ref`
497
- )
498
- })
499
- ];
36
+ return parseRepositoryProfileBindings(raw, "forgejo-repo-change", {
37
+ woodpeckerProfile: "woodpecker_profile",
38
+ sshCredentialRef: "ssh_credential_ref"
500
39
  });
501
- return Object.freeze(Object.fromEntries(entries));
502
40
  }
503
41
  function resolveProfileBinding(bindings, profile) {
504
42
  return Object.hasOwn(bindings, profile) ? { ...bindings[profile] } : { woodpeckerProfile: profile, sshCredentialRef: profile };
@@ -524,299 +62,80 @@ function forgejoRepoChangeParams(repository, input) {
524
62
  doneLabel: null
525
63
  };
526
64
  }
527
- function forgejoRepoChangeLaunchConfig(params, title, gitIdentity) {
65
+ function forgejoRepoChangeLaunchConfig(params, title, gitIdentity, repository) {
528
66
  const { owner, repo, forgejoProfile: profile, woodpeckerProfile } = params;
529
67
  const issue = isIssueOrigin(params);
530
- return {
531
- processId: "forgejo_repo_change_process",
68
+ return repositoryIssueChangeLaunchConfig(
69
+ "forgejo",
532
70
  params,
533
71
  title,
534
- startTurnId: "generate_plan",
535
- ...issue ? {
536
- externalId: `forgejo:${owner}/${repo}#${params.issueNumber}`,
537
- externalUrl: params.issueUrl
538
- } : {},
539
- projects: [
540
- {
541
- key: "repo",
542
- repoLocator: params.repoLocator,
543
- baseBranch: params.baseBranch,
544
- workBranch: params.workBranch,
545
- ...issue ? { externalId: String(params.issueNumber), externalUrl: params.issueUrl } : {},
546
- metadata: {
547
- forgejo: { owner, repo, profile, ...issue ? { issueNumber: params.issueNumber } : {} },
548
- woodpecker: { owner, repo, profile: woodpeckerProfile },
549
- "leitwerk.gitIdentity": gitIdentity
550
- }
551
- }
552
- ]
553
- };
72
+ `${owner}/${repo}`,
73
+ {
74
+ forgejo: { owner, repo, profile, ...issue ? { issueNumber: params.issueNumber } : {} },
75
+ woodpecker: { owner, repo, profile: woodpeckerProfile },
76
+ "leitwerk.gitIdentity": gitIdentity
77
+ },
78
+ repository
79
+ );
554
80
  }
555
81
  function createForgejoRepoChangeLauncher() {
556
- let dependencies = null;
557
- function configureForgejoRepoChangeLauncher(value) {
558
- dependencies = value;
559
- }
560
- function requireDependencies() {
561
- if (!dependencies) throw new Error("Forgejo repository launcher is not configured");
562
- return dependencies;
563
- }
564
- function sshPreparationCheck(access, params) {
565
- return {
566
- id: `ssh_${access}`,
567
- label: `Verify SSH ${access} access`,
568
- async run({ signal, logger }) {
569
- signal.throwIfAborted();
570
- const result = await requireDependencies().gitSsh.preflight({
571
- credentialRef: params.sshCredentialRef,
572
- repoLocator: params.repoLocator,
573
- baseBranch: params.baseBranch,
574
- requireWrite: access === "write"
575
- });
576
- signal.throwIfAborted();
577
- if (!result.ok) {
578
- logger.warn(`Git SSH ${result.access} preflight failed: ${result.detail}`);
579
- throw new SafeLaunchPreparationError(
580
- `SSH ${result.access} access failed: ${result.detail}`,
581
- `Authorize Git SSH profile '${params.sshCredentialRef}' for '${params.owner}/${params.repo}' with read/write access, then try again.`
582
- );
583
- }
584
- }
585
- };
586
- }
587
- function forgejoRepositoryPreparationChecks(_input, { params }) {
588
- return [
589
- {
590
- id: "repository_visibility",
591
- label: "Check repository visibility",
592
- async run({ signal }) {
593
- signal.throwIfAborted();
594
- const repositoryName = `${params.owner}/${params.repo}`;
595
- const visible = (await repositories(params.forgejoProfile)).some(
596
- (candidate) => candidate.full_name === repositoryName
597
- );
598
- signal.throwIfAborted();
599
- if (!visible) {
600
- throw new SafeLaunchPreparationError(
601
- "Repository is not visible",
602
- "Grant the selected Forgejo profile access to the repository, then try again."
603
- );
604
- }
605
- }
606
- },
607
- sshPreparationCheck("read", params),
608
- sshPreparationCheck("write", params)
609
- ];
610
- }
611
- function validationError(fieldId, message, code = "required") {
612
- return { code, fieldId, message };
613
- }
614
- function resolveProfiles(profile) {
615
- const { forgejo, woodpecker, gitSsh, profileBindings = {} } = requireDependencies();
616
- if (!forgejo.profiles().includes(profile)) throw new Error("Forgejo profile is not available");
617
- const binding = resolveProfileBinding(profileBindings, profile);
618
- try {
619
- woodpecker.client(binding.woodpeckerProfile);
620
- } catch {
621
- throw new Error(`Woodpecker profile '${binding.woodpeckerProfile}' is not available`);
622
- }
623
- if (!gitSsh.profiles().includes(binding.sshCredentialRef))
624
- throw new Error(`Git SSH profile '${binding.sshCredentialRef}' is not available`);
625
- return binding;
626
- }
627
- async function resolveForgejoGitIdentity(profile) {
628
- if (!profile) throw new Error("A Forgejo profile is required to resolve Git identity");
629
- return requireDependencies().forgejo.client(profile).resolveGitIdentity(profile);
630
- }
631
- async function repositories(profile) {
632
- if (!profile) return [];
633
- const { forgejo } = requireDependencies();
634
- if (!forgejo.profiles().includes(profile)) return [];
635
- return forgejo.client(profile).listRepositories();
636
- }
637
- const forgejoRepoChangeUiLauncher = {
82
+ return createRepositoryChangeLauncher({
638
83
  id: forgejoRepoChangeUiLauncherId,
639
- label: "Forgejo Repo Change",
640
- description: "Plan, implement, review, and publish a Forgejo change without a source issue",
641
- visibility: "ui",
642
- ui: {
643
- card: {
644
- title: "Forgejo Repo Change",
645
- description: "Start a repository change and publish it as a Forgejo pull request."
646
- },
647
- launchConfigSchema: {
648
- id: "forgejo_repo_change_form",
649
- title: "Forgejo Repo Change",
650
- fields: [
651
- {
652
- id: "forgejoProfile",
653
- label: "Forgejo profile",
654
- kind: "select",
655
- required: true,
656
- description: "Forgejo profile with server-configured CI and Git SSH access."
657
- },
658
- {
659
- id: "repository",
660
- label: "Repository",
661
- kind: "select",
662
- required: true,
663
- description: "Repository visible to the selected Forgejo profile."
664
- },
665
- {
666
- id: "prompt",
667
- label: "Requested change",
668
- kind: "textarea",
669
- required: true,
670
- placeholder: "Describe the change to plan, implement, review, and publish."
671
- }
672
- ],
673
- submitLabel: "Start change"
674
- },
675
- resolveDefaults() {
676
- return {
677
- forgejoProfile: requireDependencies().forgejo.profiles()[0] ?? "",
678
- repository: "",
679
- prompt: ""
680
- };
681
- },
682
- async resolveOptions(input) {
683
- const { forgejo } = requireDependencies();
684
- const profile = trimString(input.forgejoProfile);
685
- return {
686
- forgejoProfile: forgejo.profiles().map((value) => ({ value, label: value })),
687
- repository: (await repositories(profile)).map((repository) => ({
688
- value: repository.full_name,
689
- label: repository.full_name,
690
- description: repository.html_url
691
- }))
692
- };
693
- },
694
- preparationChecks: forgejoRepositoryPreparationChecks,
695
- resolveRelaunchInput(previousInput) {
696
- return {
697
- forgejoProfile: trimString(previousInput.forgejoProfile),
698
- repository: trimString(previousInput.repository),
699
- prompt: trimString(previousInput.prompt)
700
- };
701
- },
702
- async resolveLaunchConfig(input) {
703
- const profile = trimString(input.forgejoProfile);
704
- const repositoryName = trimString(input.repository);
705
- const prompt = trimString(input.prompt);
706
- const errors = [];
707
- const invalid = (fieldId, message) => ({
708
- ok: false,
709
- errors: [validationError(fieldId, message, "custom_rule")]
710
- });
711
- const { forgejo } = requireDependencies();
712
- if (!profile) errors.push(validationError("forgejoProfile", "Forgejo profile is required"));
713
- else if (!forgejo.profiles().includes(profile))
714
- errors.push(
715
- validationError("forgejoProfile", "Forgejo profile is not available", "custom_rule")
716
- );
717
- if (!repositoryName) errors.push(validationError("repository", "Repository is required"));
718
- if (!prompt) errors.push(validationError("prompt", "Requested change is required"));
719
- if (errors.length > 0) return { ok: false, errors };
720
- const repository = (await repositories(profile)).find(
721
- (candidate) => candidate.full_name === repositoryName
722
- );
723
- if (!repository)
724
- return invalid(
725
- "repository",
726
- "Repository is not available to the selected Forgejo profile"
727
- );
728
- let binding;
729
- try {
730
- binding = resolveProfiles(profile);
731
- } catch (error) {
732
- return invalid("forgejoProfile", error.message);
733
- }
734
- const gitIdentity = await resolveForgejoGitIdentity(profile);
735
- const workBranch = buildAutoWorkBranchFromSeed(
736
- prompt,
737
- `${repository.ssh_url}:${repository.default_branch}`
738
- );
739
- const params = forgejoRepoChangeParams(repository, {
740
- ...binding,
741
- profile,
742
- prompt,
743
- workBranch
744
- });
745
- return {
746
- ok: true,
747
- launchConfig: forgejoRepoChangeLaunchConfig(params, prompt, gitIdentity)
748
- };
84
+ provider: "Forgejo",
85
+ providerId: "forgejo",
86
+ integration: (deps) => deps.forgejo,
87
+ profile: (params) => params.forgejoProfile,
88
+ params: forgejoRepoChangeParams,
89
+ launchConfig: forgejoRepoChangeLaunchConfig,
90
+ resolveProfiles(profile, { woodpecker, gitSsh, profileBindings = {} }) {
91
+ const binding = resolveProfileBinding(profileBindings, profile);
92
+ try {
93
+ woodpecker.client(binding.woodpeckerProfile);
94
+ } catch {
95
+ throw new Error(`Woodpecker profile '${binding.woodpeckerProfile}' is not available`);
749
96
  }
750
- }
751
- };
752
- return {
753
- /** @internal */
754
- configure: configureForgejoRepoChangeLauncher,
755
- /** @internal */
756
- preparationChecks: forgejoRepositoryPreparationChecks,
757
- /** @internal */
758
- resolveProfiles,
759
- /** @internal */
760
- resolveGitIdentity: resolveForgejoGitIdentity,
761
- /** @internal */
762
- launcher: forgejoRepoChangeUiLauncher
763
- };
97
+ if (!gitSsh.profiles().includes(binding.sshCredentialRef))
98
+ throw new Error(`Git SSH profile '${binding.sshCredentialRef}' is not available`);
99
+ return binding;
100
+ },
101
+ preparationChecks: (params, dependencies) => [
102
+ createGitSshPreparationCheck("write", params, () => dependencies().gitSsh)
103
+ ]
104
+ });
764
105
  }
765
106
 
766
107
  // src/process.ts
767
- import { createRepositoryChangeProcess } from "@leitwerk-dev/coding";
768
108
  import {
769
- createRepositoryChangePublication,
770
- publicationObject as object2,
109
+ createPullRequestChangeProcess,
110
+ publicationObject as object,
111
+ pullRequestPublicationDefaults,
771
112
  readPublicationState
772
113
  } from "@leitwerk-dev/coding/repository-change-publication";
773
- import {
774
- forgejoExternal,
775
- forgejoIssueWatcherSource
776
- } from "@leitwerk-dev/forgejo";
114
+ import { forgejoExternal, forgejoIssueWatcherSource } from "@leitwerk-dev/forgejo";
777
115
  import { woodpeckerExternal } from "@leitwerk-dev/woodpecker";
778
- var processId = "forgejo_repo_change_process";
779
- var ids = {
780
- deliver: "deliver_change",
781
- feedback: "revise_from_pull_request_feedback",
782
- ciRepair: "repair_woodpecker_pipeline",
783
- operator: "ci_operator_action"
784
- };
785
116
  var remote = (state) => readPublicationState(state, "forgejoRepoChange");
786
- function requirePr(state) {
787
- const value = remote(state);
788
- if (!value.headSha || !value.prNumber || !value.prUrl)
789
- throw new Error("Pull request delivery state is incomplete");
790
- return { ...value, headSha: value.headSha, prNumber: value.prNumber, prUrl: value.prUrl };
791
- }
792
- var feedbackKey = (value) => `${value.kind}:${value.id}`;
793
- var callFor = (ctx) => (name, args) => ctx.callIntegrationTool(name, { projectKey: "repo", ...args });
794
- function requireIssueOrigin(params) {
795
- if (!isIssueOrigin(params)) throw new Error("Forgejo source issue metadata is unavailable");
796
- return params;
797
- }
798
- function pinnedGitIdentity(ctx) {
799
- const project = ctx.projects.find((candidate2) => candidate2.key === "repo");
800
- const candidate = object2(project?.metadata)?.["leitwerk.gitIdentity"];
801
- const identity = object2(candidate);
802
- if (identity.provider !== "forgejo" || identity.profile !== ctx.params.forgejoProfile || typeof identity.login !== "string" || !identity.login.trim() || typeof identity.name !== "string" || !identity.name.trim() || typeof identity.email !== "string" || !identity.email.trim()) {
803
- return null;
804
- }
805
- return identity;
806
- }
807
- var deliveryTools = [
808
- "forgejo_get_pull_request",
809
- "forgejo_add_pull_request_comment",
810
- "forgejo_resolve_git_identity",
811
- "forgejo_ensure_pull_request",
812
- "forgejo_add_issue_comment",
813
- "forgejo_add_pull_request_feedback_reaction",
814
- "forgejo_reply_to_pull_request_feedback",
815
- "forgejo_get_issue",
816
- "forgejo_ensure_label",
817
- "forgejo_update_issue"
818
- ];
819
117
  function createForgejoRepoChangeProcess(launcher, docker) {
118
+ const sharedSources = pullRequestPublicationDefaults(
119
+ "forgejo",
120
+ "Forgejo",
121
+ forgejoExternal,
122
+ (params) => params.forgejoProfile,
123
+ (params) => isIssueOrigin(params) ? params : void 0,
124
+ "id",
125
+ {
126
+ id: "repair_woodpecker_pipeline",
127
+ label: "Woodpecker pipeline",
128
+ tools: [
129
+ "woodpecker_lookup_repository",
130
+ "woodpecker_list_pipelines",
131
+ "woodpecker_get_pipeline",
132
+ "woodpecker_get_step_logs",
133
+ "woodpecker_restart_pipeline"
134
+ ],
135
+ prompt: (current) => `Diagnose Woodpecker pipeline #${current.pipeline?.number ?? "unknown"} (${current.pipeline?.status ?? "unknown"}) for the current checkout. Use Woodpecker tools to inspect pipeline metadata and bounded failed-step logs before changing anything. Fix repository causes. Call changes_ready for repository changes, no_changes only after an explicit provider restart or a justified diagnosis that no repository change is needed, or cannot_repair when operator action is required.`
136
+ }
137
+ );
138
+ const { requirePr } = sharedSources;
820
139
  const failedPipeline = woodpeckerExternal.pipeline(({ params, state }) => {
821
140
  const current = requirePr(state);
822
141
  return {
@@ -831,11 +150,8 @@ function createForgejoRepoChangeProcess(launcher, docker) {
831
150
  };
832
151
  });
833
152
  const sources = [
834
- {
835
- id: "forgejo_merge_conflict",
836
- kind: "conflict",
837
- label: "Rebase conflicting pull request",
838
- source: forgejoExternal.pullRequestConflict(({ params, state }) => ({
153
+ sharedSources.conflict(
154
+ forgejoExternal.pullRequestConflict(({ params, state }) => ({
839
155
  profile: params.forgejoProfile,
840
156
  owner: params.owner,
841
157
  repo: params.repo,
@@ -843,40 +159,9 @@ function createForgejoRepoChangeProcess(launcher, docker) {
843
159
  headSha: requirePr(state).headSha,
844
160
  lastConflictKey: remote(state).lastConflictKey,
845
161
  pollInterval: "30s"
846
- })),
847
- read: ({ event }) => ({
848
- kind: "conflict",
849
- conflict: object2(event).conflict
850
- })
851
- },
852
- {
853
- id: "forgejo_feedback",
854
- kind: "feedback",
855
- label: "Forgejo pull request feedback",
856
- source: forgejoExternal.pullRequestFeedback(({ params, state }) => ({
857
- profile: params.forgejoProfile,
858
- owner: params.owner,
859
- repo: params.repo,
860
- prNumber: requirePr(state).prNumber,
861
- conversationCursor: remote(state).conversationCursor,
862
- reviewCursor: remote(state).reviewCursor,
863
- inlineCursor: remote(state).inlineCursor,
864
- quietPeriodMs: 12e4,
865
- pollInterval: "30s"
866
- })),
867
- read: ({ state, event }) => {
868
- const value = object2(event);
869
- const cursors = object2(value.cursors);
870
- const current = remote(state);
871
- return {
872
- kind: "feedback",
873
- conversationCursor: Number(cursors.conversationCursor ?? current.conversationCursor),
874
- reviewCursor: Number(cursors.reviewCursor ?? current.reviewCursor),
875
- inlineCursor: Number(cursors.inlineCursor ?? current.inlineCursor),
876
- feedbackIds: value.feedbackIds ?? []
877
- };
878
- }
879
- },
162
+ }))
163
+ ),
164
+ sharedSources.feedback,
880
165
  {
881
166
  id: "woodpecker_failure_repair",
882
167
  operatorId: "woodpecker_failure_operator",
@@ -885,212 +170,23 @@ function createForgejoRepoChangeProcess(launcher, docker) {
885
170
  source: failedPipeline,
886
171
  read: ({ event }) => ({
887
172
  kind: "failure",
888
- pipeline: object2(event).pipeline
173
+ pipeline: object(event).pipeline
889
174
  })
890
175
  },
891
- ...["merged", "closed"].map((terminalOutcome) => ({
892
- id: `forgejo_pr_${terminalOutcome}`,
893
- kind: "terminal",
894
- label: `Forgejo pull request ${terminalOutcome}`,
895
- source: forgejoExternal.pullRequestTerminal(
896
- ({ params, state }) => ({
897
- profile: params.forgejoProfile,
898
- owner: params.owner,
899
- repo: params.repo,
900
- prNumber: requirePr(state).prNumber,
901
- terminalOutcome,
902
- pollInterval: "30s"
903
- })
904
- ),
905
- read: ({ event }) => ({
906
- kind: "terminal",
907
- request: object2(event).pullRequest
908
- })
909
- })),
910
- {
911
- id: "source_cancelled",
912
- kind: "cancelled",
913
- label: "Source issue cancelled",
914
- enabled: isIssueOrigin,
915
- source: forgejoExternal.issueCancelled(({ params }) => {
916
- const issue = requireIssueOrigin(params);
917
- return {
918
- profile: issue.forgejoProfile,
919
- owner: issue.owner,
920
- repo: issue.repo,
921
- issueNumber: issue.issueNumber,
922
- triggerLabel: issue.triggerLabel,
923
- pollInterval: "30s"
924
- };
925
- }),
926
- read: () => ({ kind: "cancelled" })
927
- }
176
+ ...sharedSources.terminal,
177
+ sharedSources.cancelled
928
178
  ];
929
- const publicationConfig = createRepositoryChangePublication({
930
- namespace: "forgejoRepoChange",
931
- label: "Forgejo PR",
932
- ids,
933
- sources,
934
- tools: {
935
- delivery: deliveryTools,
936
- feedback: ["forgejo_get_pull_request", "forgejo_list_pull_request_feedback"],
937
- ci: [
938
- "woodpecker_lookup_repository",
939
- "woodpecker_list_pipelines",
940
- "woodpecker_get_pipeline",
941
- "woodpecker_get_step_logs",
942
- "woodpecker_restart_pipeline"
943
- ]
944
- },
945
- async identity(ctx) {
946
- return pinnedGitIdentity(ctx) ?? await callFor(ctx)("forgejo_resolve_git_identity", {});
947
- },
948
- async reconcileTerminal(ctx, _current, pr) {
949
- const call = callFor(ctx);
950
- if (isIssueOrigin(ctx.params)) {
951
- const issue = await call("forgejo_get_issue", {
952
- issueNumber: ctx.params.issueNumber
953
- });
954
- let labels = issue.labels.filter((label) => label.name !== ctx.params.triggerLabel).map((label) => label.id);
955
- if (pr.merged) {
956
- const done = await call("forgejo_ensure_label", {
957
- name: ctx.params.doneLabel
958
- });
959
- labels = [.../* @__PURE__ */ new Set([...labels, done.id])];
960
- }
961
- await call("forgejo_update_issue", {
962
- issueNumber: ctx.params.issueNumber,
963
- patch: { labels, ...pr.merged ? { state: "closed" } : {} },
964
- writeKey: `forgejo:${ctx.process.id}:${pr.merged ? "complete-source-issue" : "remove-source-trigger"}`
965
- });
966
- await call("forgejo_add_issue_comment", {
967
- issueNumber: ctx.params.issueNumber,
968
- body: pr.merged ? `Merged ${pr.html_url}${pr.merge_commit_sha ? ` at ${pr.merge_commit_sha}` : ""}.` : `Leitwerk stopped because ${pr.html_url} was closed without merge.`,
969
- writeKey: `forgejo:${ctx.process.id}:${pr.merged ? "merged" : "closed"}-pr-comment`
970
- });
971
- }
972
- },
973
- async ensureRequest(ctx) {
974
- const call = callFor(ctx);
975
- const project = ctx.repo.get("repo");
976
- const issueOrigin = isIssueOrigin(ctx.params);
977
- const pr = await call("forgejo_ensure_pull_request", {
978
- title: ctx.process.title ?? (issueOrigin ? `Issue #${ctx.params.issueNumber}` : "Leitwerk change"),
979
- body: issueOrigin ? `Implements ${ctx.params.issueUrl}
980
-
981
- Leitwerk process: ${ctx.process.id}` : `Leitwerk process: ${ctx.process.id}`,
982
- head: project.workBranch,
983
- base: project.baseBranch
984
- });
985
- if (!pr) throw new Error("Forgejo pull request could not be created or found");
986
- return pr;
987
- },
988
- async linkIssue(ctx, current) {
989
- const call = callFor(ctx);
990
- if (isIssueOrigin(ctx.params)) {
991
- await call("forgejo_add_issue_comment", {
992
- issueNumber: ctx.params.issueNumber,
993
- body: `Leitwerk opened pull request ${current.prUrl}.`,
994
- writeKey: `forgejo:${ctx.process.id}:source-pr-link:${current.prNumber}`
995
- });
996
- }
997
- },
998
- async reply(ctx, current) {
999
- const call = callFor(ctx);
1000
- for (const feedback of current.feedbackIds) {
1001
- await call("forgejo_reply_to_pull_request_feedback", {
1002
- pullRequestNumber: current.prNumber,
1003
- feedbackKind: feedback.kind,
1004
- feedbackId: feedback.id,
1005
- body: `Addressed in ${current.headSha?.slice(0, 8) ?? "the current revision"}.`,
1006
- writeKey: `forgejo:${ctx.process.id}:feedback-reply:${feedbackKey(feedback)}:${current.headSha}`
1007
- });
1008
- }
1009
- },
1010
- async acknowledge(ctx, current) {
1011
- const call = callFor(ctx);
1012
- for (const feedback of current.feedbackIds) {
1013
- if (feedback.kind === "review") continue;
1014
- await call("forgejo_add_pull_request_feedback_reaction", {
1015
- pullRequestNumber: current.prNumber,
1016
- feedbackKind: feedback.kind,
1017
- feedbackId: feedback.id,
1018
- writeKey: `forgejo:${ctx.process.id}:feedback-eyes:${feedbackKey(feedback)}`
1019
- });
1020
- }
1021
- },
1022
- async head(ctx, current) {
1023
- return (await callFor(ctx)("forgejo_get_pull_request", {
1024
- pullRequestNumber: current.prNumber
1025
- })).head.sha;
1026
- },
1027
- async afterRebase(ctx, current) {
1028
- await callFor(ctx)("forgejo_add_pull_request_comment", {
1029
- pullRequestNumber: current.prNumber,
1030
- body: `Merge conflict repair completed at ${current.headSha}; base ${current.conflict?.baseSha}.`,
1031
- writeKey: `rebase:${ctx.process.id}:${current.lastConflictKey}:${current.headSha}`
1032
- });
1033
- },
1034
- commitMessage: (kind) => kind === "feedback" ? "fix: address Forgejo review feedback" : "fix: repair Woodpecker pipeline",
1035
- prompt(kind, current) {
1036
- return kind === "feedback" ? `Address the unseen Forgejo pull-request feedback batch for PR #${current.prNumber}. Feedback identifiers: ${JSON.stringify(current.feedbackIds)}. Inspect the current checkout and use Forgejo tools to read the full feedback. Do not rely on an earlier plan or conversation. Make only justified repository changes. Call changes_ready if files need publishing, no_changes after an explicit diagnosis that no repository change is needed, or cannot_repair when operator action is required.` : `Diagnose Woodpecker pipeline #${current.pipeline?.number ?? "unknown"} (${current.pipeline?.status ?? "unknown"}) for the current checkout. Use Woodpecker tools to inspect pipeline metadata and bounded failed-step logs before changing anything. Fix repository causes. Call changes_ready for repository changes, no_changes only after an explicit provider restart or a justified diagnosis that no repository change is needed, or cannot_repair when operator action is required.`;
1037
- }
1038
- });
1039
- const publication = publicationConfig.fragment;
1040
- publication.watcher({
1041
- id: "use_leitwerk",
1042
- label: "Forgejo use-leitwerk issues",
1043
- description: "Launch a remote repository change for Forgejo issues carrying the trigger label",
1044
- source: forgejoIssueWatcherSource,
1045
- preparationChecks: launcher.preparationChecks,
1046
- async resolveLaunchConfig({ profile, repository, issue, labels }) {
1047
- const issueNumber = issue.number;
1048
- const title = issue.title.trim();
1049
- const body = issue.body?.trim() ?? "";
1050
- const issueUrl = issue.html_url;
1051
- const binding = launcher.resolveProfiles(profile);
1052
- const gitIdentity = await launcher.resolveGitIdentity(profile);
1053
- const params = {
1054
- ...forgejoRepoChangeParams(repository, {
1055
- ...binding,
1056
- profile,
1057
- workBranch: `leitwerk/issue-${issueNumber}`,
1058
- prompt: `${title}${body ? `
1059
-
1060
- ${body}` : ""}`
1061
- }),
1062
- origin: "issue",
1063
- issueNumber,
1064
- issueUrl,
1065
- triggerLabel: labels.trigger,
1066
- doneLabel: labels.done
1067
- };
1068
- return forgejoRepoChangeLaunchConfig(params, title, gitIdentity);
1069
- }
1070
- });
1071
- const definition = createRepositoryChangeProcess({
1072
- processId,
1073
- displayName: "Forgejo Repo Change",
179
+ return createPullRequestChangeProcess("forgejo", "Forgejo", docker, {
1074
180
  paramsCodec: forgejoRepoChangeParamsCodec,
1075
181
  launcher: launcher.launcher,
1076
- finalizeLabel: "Publish pull request",
1077
- finalizeForm: {
1078
- id: "forgejo_publish",
1079
- title: "Publish pull request",
1080
- fields: [],
1081
- submitLabel: "Publish"
1082
- },
1083
- repositoryCredentials: ({ params }) => [
1084
- {
1085
- projectKey: "repo",
1086
- kind: "git_ssh",
1087
- credentialRef: params.sshCredentialRef
1088
- }
1089
- ],
1090
- publication: publicationConfig
182
+ workflow: launcher.workflow,
183
+ publication: { ...sharedSources.adapter, sources },
184
+ watcher: {
185
+ source: forgejoIssueWatcherSource,
186
+ preparationChecks: launcher.preparationChecks,
187
+ resolveLaunchConfig: launcher.launcher.resolveIssueLaunchConfig
188
+ }
1091
189
  });
1092
- definition.process.runtime = { ...definition.process.runtime, docker };
1093
- return definition.process;
1094
190
  }
1095
191
 
1096
192
  // src/index.ts