@lekman/devops-toolkit-tasks 1.4.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1273 @@
1
+ // @bun
2
+ // bin/register.ts
3
+ import { resolve as resolve3 } from "path";
4
+ import { parseArgs } from "util";
5
+
6
+ // src/register/checklist-report.ts
7
+ var MARK = {
8
+ done: "[x]",
9
+ missing: "[ ]",
10
+ unknown: "[?]"
11
+ };
12
+
13
+ class ChecklistReport {
14
+ static render(checklists, apply) {
15
+ if (checklists.length === 0) {
16
+ return `No publishable packages found. Looked for package.json without private, pyproject.toml with [build-system], a Gradle or Maven build that publishes, and a packable .csproj.
17
+ `;
18
+ }
19
+ const lines = [];
20
+ const count = {
21
+ done: 0,
22
+ missing: 0,
23
+ unknown: 0
24
+ };
25
+ for (const { pkg, items } of checklists) {
26
+ lines.push("", `${pkg.registry} ${pkg.name} (${pkg.path})`);
27
+ for (const item of items) {
28
+ count[item.status] += 1;
29
+ lines.push(` ${MARK[item.status]} ${item.title}: ${item.evidence}`);
30
+ if (item.status === "done")
31
+ continue;
32
+ if (item.action)
33
+ lines.push(` --apply: ${ChecklistReport.describe(item.action.kind)}`);
34
+ if (item.guide) {
35
+ lines.push(` by hand: ${item.guide.url}`);
36
+ for (const [label, value] of item.guide.values)
37
+ lines.push(` ${label}: ${value}`);
38
+ }
39
+ }
40
+ }
41
+ lines.push("", `${count.done} done, ${count.missing} missing, ${count.unknown} unknown.` + (apply || count.missing === 0 ? "" : " Run with --apply to make the changes marked --apply; it asks before each."));
42
+ return `${lines.join(`
43
+ `).trimStart()}
44
+ `;
45
+ }
46
+ static describe(kind) {
47
+ const text = {
48
+ "create-environment": "create the GitHub environment",
49
+ "dns-txt": "add the TXT record through the DNS provider's API, or print it",
50
+ "generate-signing-key": "generate a GPG signing key (passphrase typed, not shown)",
51
+ "npm-first-publish": "run npm publish in the package folder, in your terminal",
52
+ "npm-login": "run npm login, which opens the browser",
53
+ "npm-trust": "run npm trust github with the workflow, allowing npm publish",
54
+ "send-signing-key": "upload the public key",
55
+ "set-secret": "set the secret from a value typed at a hidden prompt",
56
+ "store-signing-key": "store SIGNING_KEY and SIGNING_PASSWORD from the GPG key"
57
+ };
58
+ return text[kind] ?? kind;
59
+ }
60
+ }
61
+
62
+ // src/register/dns-provider.ts
63
+ var PROVIDERS = [
64
+ [".ns.cloudflare.com", "cloudflare"],
65
+ [".azure-dns.com", "azure"],
66
+ [".azure-dns.net", "azure"],
67
+ [".azure-dns.org", "azure"],
68
+ [".azure-dns.info", "azure"]
69
+ ];
70
+
71
+ class DnsProvider {
72
+ static choose(nameservers, available) {
73
+ const serving = DnsProvider.serving(nameservers);
74
+ return serving && available.includes(serving) ? serving : undefined;
75
+ }
76
+ static serving(nameservers) {
77
+ for (const ns of nameservers ?? []) {
78
+ const host = ns.toLowerCase().replace(/\.$/, "");
79
+ const match = PROVIDERS.find(([suffix]) => host.endsWith(suffix));
80
+ if (match)
81
+ return match[1];
82
+ }
83
+ return;
84
+ }
85
+ }
86
+
87
+ // src/register/apply-actions.ts
88
+ class ApplyActions {
89
+ static async run(action, ports, repo) {
90
+ const { terminal } = ports;
91
+ const question = `${ChecklistReport.describe(action.kind)}${ApplyActions.target(action)}?`;
92
+ if (!await terminal.confirm(question))
93
+ return "skipped";
94
+ switch (action.kind) {
95
+ case "create-environment":
96
+ if (!repo)
97
+ return "no GitHub repository";
98
+ await ports.github.createEnvironment(repo, action.environment);
99
+ return `created environment ${action.environment}`;
100
+ case "set-secret": {
101
+ if (!repo)
102
+ return "no GitHub repository";
103
+ const value = await terminal.secret(`${action.secret} (${action.hint})`);
104
+ if (!value)
105
+ return "nothing typed, skipped";
106
+ await ports.github.setSecret(repo, action.environment, action.secret, value);
107
+ return `set ${action.secret} on ${action.environment}`;
108
+ }
109
+ case "generate-signing-key": {
110
+ const me = await ports.git.identity();
111
+ const name = await terminal.ask("Name on the key", me.name);
112
+ const email = await terminal.ask("Email on the key", me.email);
113
+ const passphrase = await ApplyActions.newPassphrase(ports);
114
+ if (!passphrase)
115
+ return "passphrases differ or are empty, skipped";
116
+ return `generated key ${await ports.gpg.generate(`${name} <${email}>`, passphrase)}`;
117
+ }
118
+ case "send-signing-key": {
119
+ const { email } = await ports.git.identity();
120
+ return ports.gpg.send(action.keyserver, action.fingerprint, email);
121
+ }
122
+ case "store-signing-key": {
123
+ if (!repo)
124
+ return "no GitHub repository";
125
+ const passphrase = await terminal.secret("The signing key's passphrase");
126
+ const armoured = await ports.gpg.exportSecret(action.fingerprint, passphrase);
127
+ await ports.github.setSecret(repo, action.environment, "SIGNING_KEY", armoured);
128
+ await ports.github.setSecret(repo, action.environment, "SIGNING_PASSWORD", passphrase);
129
+ return `stored SIGNING_KEY and SIGNING_PASSWORD on ${action.environment}`;
130
+ }
131
+ case "npm-login":
132
+ return ApplyActions.exit("npm login", await ports.npm.login());
133
+ case "npm-first-publish":
134
+ return ApplyActions.exit(`npm publish in ${action.path}`, await ports.npm.publish(action.path));
135
+ case "npm-trust":
136
+ return ApplyActions.exit("npm trust github", await ports.npm.trust(action.name, action.job, action.repo));
137
+ case "dns-txt":
138
+ return ApplyActions.dns(action.domain, ports);
139
+ }
140
+ }
141
+ static async dns(domain, ports) {
142
+ const value = await ports.terminal.ask(`The Verification Key shown for the namespace (TXT on ${domain})`);
143
+ if (!value)
144
+ return "nothing typed, skipped";
145
+ const provider = DnsProvider.choose(await ports.dns.nameservers(domain), await ports.dns.available());
146
+ if (!provider)
147
+ return `add this record at your DNS provider: ${domain} TXT "${value}"`;
148
+ await ports.dns.addTxt(provider, domain, value);
149
+ return `added ${domain} TXT "${value}" through ${provider}`;
150
+ }
151
+ static exit(what, code) {
152
+ return code === 0 ? `${what} finished` : `${what} exited with ${code}`;
153
+ }
154
+ static async newPassphrase(ports) {
155
+ const first = await ports.terminal.secret("Passphrase for the new key");
156
+ const second = await ports.terminal.secret("The passphrase again");
157
+ return first && first === second ? first : undefined;
158
+ }
159
+ static target(action) {
160
+ if ("environment" in action && "secret" in action)
161
+ return `: ${action.secret} on ${action.environment}`;
162
+ if ("environment" in action)
163
+ return `: ${action.environment}`;
164
+ if ("keyserver" in action)
165
+ return `: ${action.keyserver}`;
166
+ if ("name" in action)
167
+ return `: ${action.name}`;
168
+ if ("domain" in action)
169
+ return `: ${action.domain}`;
170
+ return "";
171
+ }
172
+ }
173
+ // src/register/github-items.ts
174
+ var SECRET_HINTS = {
175
+ MAVEN_CENTRAL_PASSWORD: "the password half of a Central Portal user token, from https://central.sonatype.com/usertoken",
176
+ MAVEN_CENTRAL_USERNAME: "the username half of a Central Portal user token, from https://central.sonatype.com/usertoken",
177
+ NUGET_USER: "your nuget.org user name: the profile name, not the email address"
178
+ };
179
+ var SIGNING_SECRETS = new Set(["SIGNING_KEY", "SIGNING_PASSWORD"]);
180
+
181
+ class GitHubItems {
182
+ static job(registry, facts) {
183
+ const job = facts.jobs.find((j) => j.registry === registry);
184
+ if (!job) {
185
+ return {
186
+ item: {
187
+ title: "A workflow job publishes it",
188
+ status: "missing",
189
+ evidence: "no job in .github/workflows/ publishes to this registry"
190
+ }
191
+ };
192
+ }
193
+ return {
194
+ job,
195
+ item: {
196
+ title: "A workflow job publishes it",
197
+ status: "done",
198
+ evidence: `${job.workflow}, job ${job.job}${job.environment ? `, environment ${job.environment}` : ""}`
199
+ }
200
+ };
201
+ }
202
+ static setup(job, facts) {
203
+ if (!job.environment || !facts.repo)
204
+ return [];
205
+ const env = job.environment;
206
+ const repo = `${facts.repo.owner}/${facts.repo.name}`;
207
+ const known = facts.environments;
208
+ const items = [
209
+ {
210
+ title: `GitHub environment ${env}`,
211
+ status: known === undefined ? "unknown" : known.includes(env) ? "done" : "missing",
212
+ evidence: known === undefined ? `gh api repos/${repo}/environments failed` : `gh api repos/${repo}/environments`,
213
+ action: { kind: "create-environment", environment: env }
214
+ }
215
+ ];
216
+ const names = facts.secrets[env];
217
+ for (const secret of job.secrets) {
218
+ const status = names === undefined ? known?.includes(env) === false ? "missing" : "unknown" : names.includes(secret) ? "done" : "missing";
219
+ items.push({
220
+ title: `Secret ${secret} on ${env}`,
221
+ status,
222
+ evidence: `gh api repos/${repo}/environments/${env}/secrets (names only)${SIGNING_SECRETS.has(secret) ? "; --apply sets it from the GPG signing key" : ""}`,
223
+ ...SIGNING_SECRETS.has(secret) ? {} : {
224
+ action: {
225
+ kind: "set-secret",
226
+ environment: env,
227
+ secret,
228
+ hint: SECRET_HINTS[secret] ?? "the value the workflow expects"
229
+ }
230
+ }
231
+ });
232
+ }
233
+ return items;
234
+ }
235
+ static published(name, where, facts) {
236
+ const found = facts.published[name];
237
+ return {
238
+ title: "Published on the registry",
239
+ status: found === undefined ? "unknown" : found ? "done" : "missing",
240
+ evidence: found === undefined ? `${where} did not answer` : `${where} ${found ? "has it" : "answered 404"}`
241
+ };
242
+ }
243
+ }
244
+
245
+ // src/register/registry-urls.ts
246
+ class RegistryUrls {
247
+ static lookup(pkg) {
248
+ switch (pkg.registry) {
249
+ case "npm":
250
+ return `https://registry.npmjs.org/${encodeURIComponent(pkg.name).replace(/^%40/, "@")}`;
251
+ case "pypi":
252
+ return `https://pypi.org/pypi/${encodeURIComponent(pkg.name)}/json`;
253
+ case "maven": {
254
+ const [group = "", artifact = ""] = pkg.name.split(":");
255
+ const path = group.split(".").map(encodeURIComponent).join("/");
256
+ return `https://repo1.maven.org/maven2/${path}/${encodeURIComponent(artifact)}/maven-metadata.xml`;
257
+ }
258
+ case "nuget":
259
+ return `https://api.nuget.org/v3-flatcontainer/${encodeURIComponent(pkg.name.toLowerCase())}/index.json`;
260
+ }
261
+ }
262
+ static namespaceDomain(group) {
263
+ const parts = group.split(".");
264
+ if (parts.length < 2 || ["io.github", "io.gitlab", "org.bitbucket"].includes(parts.slice(0, 2).join("."))) {
265
+ return;
266
+ }
267
+ return `${parts[1]}.${parts[0]}`;
268
+ }
269
+ }
270
+
271
+ // src/register/maven-checklist.ts
272
+ var KEYSERVERS = ["keyserver.ubuntu.com", "keys.openpgp.org"];
273
+
274
+ class MavenChecklist {
275
+ static items(pkg, facts) {
276
+ const { item, job } = GitHubItems.job("maven", facts);
277
+ const published = GitHubItems.published(pkg.name, RegistryUrls.lookup(pkg), facts);
278
+ const group = pkg.name.split(":")[0];
279
+ const domain = RegistryUrls.namespaceDomain(group);
280
+ const txt = domain ? facts.txt[domain] : undefined;
281
+ const items = [item, published];
282
+ items.push({
283
+ title: `Namespace ${group} verified`,
284
+ status: published.status === "done" ? "done" : "unknown",
285
+ evidence: published.status === "done" ? "an artifact is published under it" : `the Central Portal has no API for namespaces${domain ? `; ${domain} has ${txt?.length ?? "unknown"} TXT records` : ""}`,
286
+ ...domain && published.status !== "done" ? { action: { kind: "dns-txt", domain } } : {},
287
+ guide: {
288
+ url: "https://central.sonatype.com/publishing/namespaces",
289
+ values: [
290
+ ["Namespace", group],
291
+ ...domain ? [
292
+ [
293
+ "DNS TXT record on",
294
+ `${domain}, value: the namespace's Verification Key`
295
+ ]
296
+ ] : []
297
+ ]
298
+ }
299
+ });
300
+ if (!job)
301
+ return items;
302
+ items.push(...GitHubItems.setup(job, facts));
303
+ if (!job.secrets.includes("SIGNING_KEY"))
304
+ return items;
305
+ const key = facts.signingKeys[0];
306
+ items.push({
307
+ title: "GPG signing key",
308
+ status: key ? "done" : "missing",
309
+ evidence: key ? `gpg --list-secret-keys: ${key.fingerprint} ${key.uids[0] ?? ""}`.trim() : "gpg --list-secret-keys has no signing key",
310
+ action: { kind: "generate-signing-key" }
311
+ });
312
+ if (!key)
313
+ return items;
314
+ for (const server of KEYSERVERS) {
315
+ const found = facts.keyservers[`${server} ${key.fingerprint}`];
316
+ items.push({
317
+ title: `Public key on ${server}`,
318
+ status: found === undefined ? "unknown" : found ? "done" : "missing",
319
+ evidence: found === undefined ? `${server} did not answer` : `${server} lookup by fingerprint`,
320
+ action: {
321
+ kind: "send-signing-key",
322
+ fingerprint: key.fingerprint,
323
+ keyserver: server
324
+ }
325
+ });
326
+ }
327
+ const stored = items.filter((i) => /^Secret SIGNING_(KEY|PASSWORD) /.test(i.title));
328
+ if (job.environment && stored.some((i) => i.status === "missing")) {
329
+ items.push({
330
+ title: `Signing key stored on ${job.environment}`,
331
+ status: "missing",
332
+ evidence: stored.map((i) => `${i.title}: ${i.status}`).join(", "),
333
+ action: {
334
+ kind: "store-signing-key",
335
+ environment: job.environment,
336
+ fingerprint: key.fingerprint
337
+ }
338
+ });
339
+ }
340
+ return items;
341
+ }
342
+ }
343
+
344
+ // src/register/npm-checklist.ts
345
+ class NpmChecklist {
346
+ static items(pkg, facts) {
347
+ const { item, job } = GitHubItems.job("npm", facts);
348
+ const published = GitHubItems.published(pkg.name, RegistryUrls.lookup(pkg), facts);
349
+ const user = facts.npmUser;
350
+ const items = [item, published];
351
+ items.push({
352
+ title: "Signed in to npm",
353
+ status: user === undefined ? "unknown" : user ? "done" : "missing",
354
+ evidence: user ? `npm whoami: ${user}` : "npm whoami",
355
+ action: { kind: "npm-login" }
356
+ });
357
+ if (published.status === "missing") {
358
+ items.push({
359
+ title: "First version published by hand",
360
+ status: "missing",
361
+ evidence: "npm takes a trusted publisher only for a package that exists",
362
+ action: { kind: "npm-first-publish", path: pkg.path, name: pkg.name }
363
+ });
364
+ }
365
+ if (job && facts.repo) {
366
+ const trusted = facts.npmTrust[pkg.name];
367
+ items.push({
368
+ title: `Trusted publisher ${job.workflow}`,
369
+ status: trusted === undefined ? "unknown" : trusted.includes(job.workflow) ? "done" : "missing",
370
+ evidence: NpmChecklist.trustEvidence(trusted, user, published.status === "done", pkg.name),
371
+ action: { kind: "npm-trust", job, name: pkg.name, repo: facts.repo },
372
+ guide: {
373
+ url: `https://www.npmjs.com/package/${pkg.name}/access`,
374
+ values: [
375
+ ["Organization or user", facts.repo.owner],
376
+ ["Repository", facts.repo.name],
377
+ ["Workflow filename", job.workflow],
378
+ ["Environment", job.environment || "(none)"],
379
+ ["Allowed actions", "npm publish"]
380
+ ]
381
+ }
382
+ });
383
+ items.push(...GitHubItems.setup(job, facts));
384
+ }
385
+ return items;
386
+ }
387
+ static trustEvidence(trusted, user, published, name) {
388
+ if (trusted !== undefined)
389
+ return `npm trust list ${name}`;
390
+ if (!user || !published) {
391
+ return "npm trust list needs a signed-in npm and a published package";
392
+ }
393
+ return `npm trust list asks for a one-time password; run it to check: npm trust list ${name}`;
394
+ }
395
+ }
396
+
397
+ // src/register/nuget-checklist.ts
398
+ class NugetChecklist {
399
+ static items(pkg, facts) {
400
+ const { item, job } = GitHubItems.job("nuget", facts);
401
+ const items = [
402
+ item,
403
+ GitHubItems.published(pkg.name, RegistryUrls.lookup(pkg), facts)
404
+ ];
405
+ if (job && facts.repo) {
406
+ items.push({
407
+ title: "Trusted publishing policy",
408
+ status: "unknown",
409
+ evidence: "nuget.org has no API to read or add trusted publishing policies",
410
+ guide: {
411
+ url: "https://www.nuget.org/ (your user name, then Trusted Publishing)",
412
+ values: [
413
+ ["Repository Owner", facts.repo.owner],
414
+ ["Repository", facts.repo.name],
415
+ ["Workflow File", job.workflow],
416
+ ["Environment", job.environment || "(none)"]
417
+ ]
418
+ }
419
+ });
420
+ items.push(...GitHubItems.setup(job, facts));
421
+ }
422
+ const prefix = pkg.name.split(".")[0];
423
+ items.push({
424
+ title: `ID prefix ${prefix}. reserved (optional)`,
425
+ status: "unknown",
426
+ evidence: "reservation is by email; nuget.org has no API for it",
427
+ guide: {
428
+ url: "mailto:account@nuget.org",
429
+ values: [["Prefix", `${prefix}.*`]]
430
+ }
431
+ });
432
+ return items;
433
+ }
434
+ }
435
+
436
+ // src/register/pypi-checklist.ts
437
+ class PypiChecklist {
438
+ static items(pkg, facts) {
439
+ const { item, job } = GitHubItems.job("pypi", facts);
440
+ const published = GitHubItems.published(pkg.name, RegistryUrls.lookup(pkg), facts);
441
+ const items = [item, published];
442
+ if (job && facts.repo) {
443
+ const pending = published.status !== "done";
444
+ items.push({
445
+ title: pending ? "Pending trusted publisher" : "Trusted publisher",
446
+ status: "unknown",
447
+ evidence: "PyPI has no API to read or add trusted publishers",
448
+ guide: {
449
+ url: pending ? "https://pypi.org/manage/account/publishing/" : `https://pypi.org/manage/project/${pkg.name}/settings/publishing/`,
450
+ values: [
451
+ ...pending ? [["PyPI Project Name", pkg.name]] : [],
452
+ ["Owner", facts.repo.owner],
453
+ ["Repository name", facts.repo.name],
454
+ ["Workflow name", job.workflow],
455
+ ["Environment name", job.environment || "(none)"]
456
+ ]
457
+ }
458
+ });
459
+ items.push(...GitHubItems.setup(job, facts));
460
+ }
461
+ return items;
462
+ }
463
+ }
464
+
465
+ // src/register/checklists.ts
466
+ class Checklists {
467
+ static actions(checklists) {
468
+ const seen = new Map;
469
+ for (const list of checklists) {
470
+ for (const item of list.items) {
471
+ if (item.status !== "missing" || !item.action)
472
+ continue;
473
+ const key = JSON.stringify(item.action);
474
+ if (!seen.has(key))
475
+ seen.set(key, item.action);
476
+ }
477
+ }
478
+ return [...seen.values()];
479
+ }
480
+ static build(packages, facts) {
481
+ return packages.map((pkg) => {
482
+ switch (pkg.registry) {
483
+ case "maven":
484
+ return { pkg, items: MavenChecklist.items(pkg, facts) };
485
+ case "npm":
486
+ return { pkg, items: NpmChecklist.items(pkg, facts) };
487
+ case "nuget":
488
+ return { pkg, items: NugetChecklist.items(pkg, facts) };
489
+ case "pypi":
490
+ return { pkg, items: PypiChecklist.items(pkg, facts) };
491
+ }
492
+ });
493
+ }
494
+ }
495
+ // src/register/workflow-jobs.ts
496
+ var PUBLISHERS = [
497
+ ["npm", /\bnpm publish\b/],
498
+ ["pypi", /pypa\/gh-action-pypi-publish|\btwine upload\b|\buv publish\b/],
499
+ [
500
+ "maven",
501
+ /publishToMavenCentral|central-publishing-maven-plugin|\bmvn\b[^\n]*\bdeploy\b/
502
+ ],
503
+ ["nuget", /NuGet\/login|dotnet nuget push/]
504
+ ];
505
+
506
+ class WorkflowJobs {
507
+ static read(file, text) {
508
+ const body = text.split(/^jobs:\s*$/m)[1];
509
+ if (!body)
510
+ return [];
511
+ const jobs = body.split(/^(?= {2}[\w-]+:\s*$)/m).filter((part) => /^ {2}[\w-]+:/.test(part));
512
+ return jobs.flatMap((part) => {
513
+ const job = part.match(/^ {2}([\w-]+):/)?.[1] ?? "";
514
+ const code = part.replace(/^\s*#.*$/gm, "");
515
+ const environment = code.match(/^ {4}environment:\s*([\w.-]+)\s*$/m)?.[1] ?? code.match(/^ {4}environment:\s*\n\s+name:\s*([\w.-]+)/m)?.[1] ?? "";
516
+ const secrets = [
517
+ ...new Set([...code.matchAll(/secrets\.([A-Z0-9_]+)/g)].map((m) => m[1]))
518
+ ].filter((name) => name !== "GITHUB_TOKEN").sort();
519
+ return PUBLISHERS.filter(([, pattern]) => pattern.test(code)).map(([registry]) => ({
520
+ registry,
521
+ workflow: file,
522
+ job,
523
+ environment,
524
+ secrets
525
+ }));
526
+ });
527
+ }
528
+ static repo(url) {
529
+ const match = url.trim().match(/github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/);
530
+ return match ? { owner: match[1], name: match[2] } : undefined;
531
+ }
532
+ }
533
+
534
+ // src/register/fact-finder.ts
535
+ class FactFinder {
536
+ static async gather(ports, packages) {
537
+ const jobs = FactFinder.jobs(ports);
538
+ const repo = WorkflowJobs.repo(await ports.git.originUrl());
539
+ const environments = repo ? await ports.github.environments(repo) : undefined;
540
+ const secrets = {};
541
+ for (const env of new Set(jobs.map((j) => j.environment).filter(Boolean))) {
542
+ if (!repo || !environments?.includes(env))
543
+ continue;
544
+ const names = await ports.github.secretNames(repo, env);
545
+ if (names)
546
+ secrets[env] = names;
547
+ }
548
+ const published = {};
549
+ for (const pkg of packages)
550
+ published[pkg.name] = await ports.registries.exists(pkg);
551
+ const npm = packages.filter((p) => p.registry === "npm");
552
+ const npmUser = npm.length > 0 ? await ports.npm.whoami() : undefined;
553
+ const npmTrust = {};
554
+ for (const pkg of npm) {
555
+ npmTrust[pkg.name] = npmUser && published[pkg.name] ? await ports.npm.trustList(pkg.name) : undefined;
556
+ }
557
+ const signs = jobs.some((j) => j.registry === "maven" && j.secrets.includes("SIGNING_KEY"));
558
+ const signingKeys = signs ? await ports.gpg.signingKeys() : [];
559
+ const keyservers = {};
560
+ if (signingKeys[0]) {
561
+ for (const server of KEYSERVERS) {
562
+ const fpr = signingKeys[0].fingerprint;
563
+ keyservers[`${server} ${fpr}`] = await ports.gpg.onKeyserver(server, fpr);
564
+ }
565
+ }
566
+ const txt = {};
567
+ for (const pkg of packages.filter((p) => p.registry === "maven")) {
568
+ const domain = RegistryUrls.namespaceDomain(pkg.name.split(":")[0]);
569
+ if (domain && !(domain in txt))
570
+ txt[domain] = await ports.dns.txt(domain);
571
+ }
572
+ return {
573
+ environments,
574
+ jobs,
575
+ keyservers,
576
+ npmTrust,
577
+ npmUser,
578
+ published,
579
+ repo,
580
+ secrets,
581
+ signingKeys,
582
+ txt
583
+ };
584
+ }
585
+ static jobs(ports) {
586
+ return [
587
+ ...ports.files.glob(".github/workflows/*.yml"),
588
+ ...ports.files.glob(".github/workflows/*.yaml")
589
+ ].sort().flatMap((path) => WorkflowJobs.read(path.split("/").at(-1) ?? path, ports.files.read(path) ?? ""));
590
+ }
591
+ }
592
+ // src/register/jvm-dotnet-discovery.ts
593
+ var dirOf = (path) => path.split("/").slice(0, -1).join("/") || ".";
594
+ var join = (dir, file) => dir === "." ? file : `${dir}/${file}`;
595
+ var tag = (xml, name) => xml.match(new RegExp(`<${name}>\\s*([^<]+?)\\s*</${name}>`))?.[1];
596
+
597
+ class JvmDotnetDiscovery {
598
+ static maven(files) {
599
+ const gradle = [
600
+ ...files.glob("**/build.gradle.kts"),
601
+ ...files.glob("**/build.gradle")
602
+ ].flatMap((path) => {
603
+ const text = files.read(path) ?? "";
604
+ if (!/mavenPublishing|maven-publish/.test(text))
605
+ return [];
606
+ const coords = text.match(/coordinates\(\s*"([^"]+)"\s*,\s*"([^"]+)"/);
607
+ const dir = dirOf(path);
608
+ const settings = files.read(join(dir, "settings.gradle.kts")) ?? files.read(join(dir, "settings.gradle"));
609
+ const group = coords?.[1] ?? text.match(/^group\s*=\s*"([^"]+)"/m)?.[1];
610
+ const artifact = coords?.[2] ?? settings?.match(/rootProject\.name\s*=\s*"([^"]+)"/)?.[1] ?? dir.split("/").at(-1);
611
+ return group && artifact ? [
612
+ {
613
+ registry: "maven",
614
+ name: `${group}:${artifact}`,
615
+ path: dir
616
+ }
617
+ ] : [];
618
+ });
619
+ const poms = files.glob("**/pom.xml").flatMap((path) => {
620
+ const xml = (files.read(path) ?? "").replace(/<(parent|dependencies|build)>[\s\S]*?<\/\1>/g, "");
621
+ const full = files.read(path) ?? "";
622
+ if (!/central-publishing-maven-plugin|<distributionManagement[\s/>]/.test(full))
623
+ return [];
624
+ const group = tag(xml, "groupId");
625
+ const artifact = tag(xml, "artifactId");
626
+ return group && artifact ? [
627
+ {
628
+ registry: "maven",
629
+ name: `${group}:${artifact}`,
630
+ path: dirOf(path)
631
+ }
632
+ ] : [];
633
+ });
634
+ return [...gradle, ...poms];
635
+ }
636
+ static nuget(files) {
637
+ return files.glob("**/*.csproj").flatMap((path) => {
638
+ const xml = files.read(path) ?? "";
639
+ const packable = tag(xml, "IsPackable");
640
+ if (packable === "false")
641
+ return [];
642
+ if (packable !== "true" && tag(xml, "PackAsTool") !== "true" && !tag(xml, "PackageId"))
643
+ return [];
644
+ const id = tag(xml, "PackageId") ?? path.split("/").at(-1)?.replace(/\.csproj$/, "") ?? "";
645
+ return [{ registry: "nuget", name: id, path: dirOf(path) }];
646
+ });
647
+ }
648
+ }
649
+ // ../devops-toolkit/dist/toml-lite.js
650
+ var TABLE_HEADER = /^\[{1,2}\s*([^\]]+?)\s*\]{1,2}\s*$/;
651
+ var KEY_VALUE = /^([A-Za-z0-9_.-]+|"[^"]*"|'[^']*')\s*=\s*(.*)$/;
652
+ function parseToml(content) {
653
+ const tables = [];
654
+ const values = {};
655
+ let current = "";
656
+ for (const raw of content.split(`
657
+ `)) {
658
+ const line = stripComment(raw).trim();
659
+ if (line === "")
660
+ continue;
661
+ const header = line.match(TABLE_HEADER);
662
+ if (header) {
663
+ current = normaliseTablePath(header[1]);
664
+ if (!tables.includes(current))
665
+ tables.push(current);
666
+ continue;
667
+ }
668
+ const pair = line.match(KEY_VALUE);
669
+ if (!pair)
670
+ continue;
671
+ const value = readScalar(pair[2]);
672
+ if (value === null)
673
+ continue;
674
+ const key = unquote(pair[1]);
675
+ values[current ? `${current}.${key}` : key] = value;
676
+ }
677
+ return { tables, values };
678
+ }
679
+ function hasTable(doc, path) {
680
+ return doc.tables.some((t) => t === path || t.startsWith(`${path}.`));
681
+ }
682
+ function getString(doc, path) {
683
+ const raw = doc.values[path];
684
+ return raw === undefined ? undefined : unquote(raw);
685
+ }
686
+ function getBoolean(doc, path) {
687
+ const raw = doc.values[path];
688
+ if (raw === "true")
689
+ return true;
690
+ if (raw === "false")
691
+ return false;
692
+ return;
693
+ }
694
+ function stripComment(line) {
695
+ let quote = null;
696
+ for (let i = 0;i < line.length; i++) {
697
+ const ch = line[i];
698
+ if (quote) {
699
+ if (ch === quote)
700
+ quote = null;
701
+ continue;
702
+ }
703
+ if (ch === '"' || ch === "'") {
704
+ quote = ch;
705
+ continue;
706
+ }
707
+ if (ch === "#")
708
+ return line.slice(0, i);
709
+ }
710
+ return line;
711
+ }
712
+ function normaliseTablePath(path) {
713
+ return splitDotted(path).map((segment) => unquote(segment.trim())).join(".");
714
+ }
715
+ function splitDotted(path) {
716
+ const segments = [];
717
+ let current = "";
718
+ let quote = null;
719
+ for (const ch of path) {
720
+ if (quote) {
721
+ current += ch;
722
+ if (ch === quote)
723
+ quote = null;
724
+ continue;
725
+ }
726
+ if (ch === '"' || ch === "'") {
727
+ quote = ch;
728
+ current += ch;
729
+ continue;
730
+ }
731
+ if (ch === ".") {
732
+ segments.push(current);
733
+ current = "";
734
+ continue;
735
+ }
736
+ current += ch;
737
+ }
738
+ segments.push(current);
739
+ return segments;
740
+ }
741
+ function unquote(token) {
742
+ const first = token[0];
743
+ if ((first === '"' || first === "'") && token.endsWith(first)) {
744
+ return token.slice(1, -1);
745
+ }
746
+ return token;
747
+ }
748
+ function readScalar(raw) {
749
+ const value = raw.trim();
750
+ if (value === "")
751
+ return null;
752
+ if (value.startsWith("[") || value.startsWith("{"))
753
+ return null;
754
+ const first = value[0];
755
+ if (first === '"' || first === "'") {
756
+ const closing = value.indexOf(first, 1);
757
+ if (closing === -1)
758
+ return null;
759
+ return value.slice(0, closing + 1);
760
+ }
761
+ return value;
762
+ }
763
+
764
+ // src/register/package-discovery.ts
765
+ var dirOf2 = (path) => path.split("/").slice(0, -1).join("/") || ".";
766
+
767
+ class PackageDiscovery {
768
+ static find(files) {
769
+ return [
770
+ ...PackageDiscovery.npm(files),
771
+ ...PackageDiscovery.pypi(files),
772
+ ...JvmDotnetDiscovery.maven(files),
773
+ ...JvmDotnetDiscovery.nuget(files)
774
+ ];
775
+ }
776
+ static npm(files) {
777
+ return files.glob("**/package.json").flatMap((path) => {
778
+ try {
779
+ const manifest = JSON.parse(files.read(path) ?? "{}");
780
+ if (manifest.private === true || typeof manifest.name !== "string")
781
+ return [];
782
+ return [
783
+ { registry: "npm", name: manifest.name, path: dirOf2(path) }
784
+ ];
785
+ } catch {
786
+ return [];
787
+ }
788
+ });
789
+ }
790
+ static pypi(files) {
791
+ return files.glob("**/pyproject.toml").flatMap((path) => {
792
+ const doc = parseToml(files.read(path) ?? "");
793
+ if (!hasTable(doc, "build-system"))
794
+ return [];
795
+ if (getBoolean(doc, "tool.poetry.package-mode") === false)
796
+ return [];
797
+ const name = getString(doc, "project.name") ?? getString(doc, "tool.poetry.name");
798
+ return name ? [{ registry: "pypi", name, path: dirOf2(path) }] : [];
799
+ });
800
+ }
801
+ }
802
+ // src/register/register.ts
803
+ var ROUNDS = 3;
804
+
805
+ class Register {
806
+ static async run(ports, apply) {
807
+ const packages = PackageDiscovery.find(ports.files);
808
+ let facts = await FactFinder.gather(ports, packages);
809
+ let lists = Checklists.build(packages, facts);
810
+ ports.terminal.print(ChecklistReport.render(lists, apply));
811
+ if (apply) {
812
+ const offered = new Set;
813
+ for (let round = 0;round < ROUNDS; round += 1) {
814
+ const fresh = Checklists.actions(lists).filter((a) => !offered.has(JSON.stringify(a)));
815
+ if (fresh.length === 0)
816
+ break;
817
+ for (const action of fresh) {
818
+ offered.add(JSON.stringify(action));
819
+ ports.terminal.print(` ${await ApplyActions.run(action, ports, facts.repo)}`);
820
+ }
821
+ facts = await FactFinder.gather(ports, packages);
822
+ lists = Checklists.build(packages, facts);
823
+ }
824
+ ports.terminal.print(ChecklistReport.render(lists, true));
825
+ }
826
+ return 0;
827
+ }
828
+ }
829
+ // src/register/gpg-listing.ts
830
+ class GpgListing {
831
+ static signingKeys(text) {
832
+ const keys = [];
833
+ let current;
834
+ let awaitingFingerprint = false;
835
+ for (const line of text.split(`
836
+ `)) {
837
+ const fields = line.split(":");
838
+ if (fields[0] === "sec") {
839
+ const usable = !["r", "e", "d", "i"].includes(fields[1]) && /s/i.test(fields[11] ?? "");
840
+ current = usable ? { fingerprint: "", uids: [] } : undefined;
841
+ if (current)
842
+ keys.push(current);
843
+ awaitingFingerprint = true;
844
+ } else if (fields[0] === "fpr" && awaitingFingerprint) {
845
+ if (current)
846
+ current.fingerprint = (fields[9] ?? "").toUpperCase();
847
+ awaitingFingerprint = false;
848
+ } else if (fields[0] === "uid" && current && fields[1] !== "r") {
849
+ current.uids.push(fields[9] ?? "");
850
+ } else if (fields[0] === "ssb") {
851
+ awaitingFingerprint = false;
852
+ }
853
+ }
854
+ return keys.filter((k) => k.fingerprint);
855
+ }
856
+ }
857
+ // src/register/dns.system.ts
858
+ import { resolveNs, resolveTxt } from "dns/promises";
859
+
860
+ // src/register/process.system.ts
861
+ import { spawnSync } from "child_process";
862
+
863
+ class Processes {
864
+ static capture(program, args, input, cwd) {
865
+ const result = spawnSync(program, args, { cwd, encoding: "utf8", input });
866
+ return {
867
+ code: result.error ? 127 : result.status ?? 1,
868
+ stderr: result.stderr ?? "",
869
+ stdout: result.stdout ?? ""
870
+ };
871
+ }
872
+ static interactive(program, args, cwd) {
873
+ const result = spawnSync(program, args, { cwd, stdio: "inherit" });
874
+ return result.error ? 127 : result.status ?? 1;
875
+ }
876
+ }
877
+
878
+ // src/register/dns.system.ts
879
+ var CLOUDFLARE = "https://api.cloudflare.com/client/v4";
880
+
881
+ class DnsTools {
882
+ cloudflareToken;
883
+ constructor(cloudflareToken = "") {
884
+ this.cloudflareToken = cloudflareToken;
885
+ }
886
+ async addTxt(provider, domain, value) {
887
+ if (provider === "cloudflare")
888
+ return this.cloudflare(domain, value);
889
+ const group = Processes.capture("az", [
890
+ "network",
891
+ "dns",
892
+ "zone",
893
+ "list",
894
+ "--query",
895
+ `[?name=='${domain}'].resourceGroup | [0]`,
896
+ "-o",
897
+ "tsv"
898
+ ]).stdout.trim();
899
+ if (!group)
900
+ throw new Error(`az can see no DNS zone ${domain}`);
901
+ const args = [
902
+ "network",
903
+ "dns",
904
+ "record-set",
905
+ "txt",
906
+ "add-record",
907
+ "-g",
908
+ group,
909
+ "-z",
910
+ domain,
911
+ "-n",
912
+ "@",
913
+ "-v",
914
+ value
915
+ ];
916
+ const result = Processes.capture("az", args);
917
+ if (result.code !== 0)
918
+ throw new Error(`az could not add the record: ${result.stderr.trim()}`);
919
+ }
920
+ async available() {
921
+ const providers = [];
922
+ if (this.cloudflareToken)
923
+ providers.push("cloudflare");
924
+ if (Processes.capture("az", ["account", "show", "-o", "none"]).code === 0)
925
+ providers.push("azure");
926
+ return providers;
927
+ }
928
+ async nameservers(domain) {
929
+ return resolveNs(domain).catch(() => {
930
+ return;
931
+ });
932
+ }
933
+ async txt(domain) {
934
+ return resolveTxt(domain).then((records) => records.map((parts) => parts.join(""))).catch(() => {
935
+ return;
936
+ });
937
+ }
938
+ async cloudflare(domain, value) {
939
+ const headers = {
940
+ Authorization: `Bearer ${this.cloudflareToken}`,
941
+ "Content-Type": "application/json"
942
+ };
943
+ const zones = await (await fetch(`${CLOUDFLARE}/zones?name=${domain}`, { headers })).json();
944
+ const zone = zones.result?.[0]?.id;
945
+ if (!zone)
946
+ throw new Error(`the Cloudflare token can see no zone ${domain}`);
947
+ const body = JSON.stringify({
948
+ content: `"${value}"`,
949
+ name: domain,
950
+ ttl: 3600,
951
+ type: "TXT"
952
+ });
953
+ const response = await fetch(`${CLOUDFLARE}/zones/${zone}/dns_records`, {
954
+ body,
955
+ headers,
956
+ method: "POST"
957
+ });
958
+ if (!response.ok)
959
+ throw new Error(`Cloudflare refused the record: ${response.status}`);
960
+ }
961
+ }
962
+ // src/register/github.system.ts
963
+ var slug = (repo) => `${repo.owner}/${repo.name}`;
964
+
965
+ class GhCli {
966
+ async createEnvironment(repo, environment) {
967
+ const result = Processes.capture("gh", [
968
+ "api",
969
+ "-X",
970
+ "PUT",
971
+ `repos/${slug(repo)}/environments/${environment}`
972
+ ]);
973
+ if (result.code !== 0)
974
+ throw new Error(`gh could not create ${environment}: ${result.stderr.trim()}`);
975
+ }
976
+ async environments(repo) {
977
+ return this.names(`repos/${slug(repo)}/environments`, ".environments[].name");
978
+ }
979
+ async secretNames(repo, environment) {
980
+ return this.names(`repos/${slug(repo)}/environments/${environment}/secrets`, ".secrets[].name");
981
+ }
982
+ async setSecret(repo, environment, name, value) {
983
+ const result = Processes.capture("gh", ["secret", "set", name, "--env", environment, "--repo", slug(repo)], value);
984
+ if (result.code !== 0)
985
+ throw new Error(`gh could not set ${name}: ${result.stderr.trim()}`);
986
+ }
987
+ names(path, jq) {
988
+ const result = Processes.capture("gh", [
989
+ "api",
990
+ "--paginate",
991
+ path,
992
+ "--jq",
993
+ jq
994
+ ]);
995
+ if (result.code !== 0)
996
+ return;
997
+ return result.stdout.split(`
998
+ `).filter(Boolean);
999
+ }
1000
+ }
1001
+ // src/register/gpg.system.ts
1002
+ var WITH_PASSPHRASE = [
1003
+ "--batch",
1004
+ "--pinentry-mode",
1005
+ "loopback",
1006
+ "--passphrase-fd",
1007
+ "0"
1008
+ ];
1009
+ var LOOKUP = {
1010
+ "keys.openpgp.org": (fpr) => `https://keys.openpgp.org/vks/v1/by-fingerprint/${fpr.toUpperCase()}`,
1011
+ "keyserver.ubuntu.com": (fpr) => `https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x${fpr}`
1012
+ };
1013
+
1014
+ class GpgCli {
1015
+ async exportSecret(fingerprint, passphrase) {
1016
+ const result = Processes.capture("gpg", [...WITH_PASSPHRASE, "--armor", "--export-secret-keys", fingerprint], passphrase);
1017
+ if (result.code !== 0 || !result.stdout.includes("PRIVATE KEY"))
1018
+ throw new Error("gpg could not export the key");
1019
+ return result.stdout;
1020
+ }
1021
+ async generate(uid, passphrase) {
1022
+ const result = Processes.capture("gpg", [
1023
+ ...WITH_PASSPHRASE,
1024
+ "--quick-generate-key",
1025
+ uid,
1026
+ "rsa4096",
1027
+ "sign",
1028
+ "2y"
1029
+ ], passphrase);
1030
+ if (result.code !== 0)
1031
+ throw new Error(`gpg could not generate the key: ${result.stderr.trim()}`);
1032
+ const keys = GpgListing.signingKeys(Processes.capture("gpg", ["--list-secret-keys", "--with-colons", uid]).stdout);
1033
+ return keys.at(-1)?.fingerprint ?? "unknown";
1034
+ }
1035
+ async onKeyserver(keyserver, fingerprint) {
1036
+ const url = LOOKUP[keyserver]?.(fingerprint);
1037
+ if (!url)
1038
+ return;
1039
+ try {
1040
+ const response = await fetch(url, {
1041
+ signal: AbortSignal.timeout(1e4)
1042
+ });
1043
+ if (response.status === 200)
1044
+ return true;
1045
+ return response.status === 404 ? false : undefined;
1046
+ } catch {
1047
+ return;
1048
+ }
1049
+ }
1050
+ async send(keyserver, fingerprint, email) {
1051
+ if (keyserver !== "keys.openpgp.org") {
1052
+ const result = Processes.capture("gpg", [
1053
+ "--keyserver",
1054
+ `hkps://${keyserver}`,
1055
+ "--send-keys",
1056
+ fingerprint
1057
+ ]);
1058
+ return result.code === 0 ? `sent to ${keyserver}` : `gpg --send-keys failed: ${result.stderr.trim()}`;
1059
+ }
1060
+ const keytext = Processes.capture("gpg", [
1061
+ "--armor",
1062
+ "--export",
1063
+ fingerprint
1064
+ ]).stdout;
1065
+ const upload = await this.post("upload", { keytext });
1066
+ if (!upload?.token)
1067
+ return "keys.openpgp.org refused the upload";
1068
+ if (email)
1069
+ await this.post("request-verify", {
1070
+ addresses: [email],
1071
+ token: upload.token
1072
+ });
1073
+ return `sent to keys.openpgp.org; confirm the mail it sent to ${email || "the key's address"}`;
1074
+ }
1075
+ async signingKeys() {
1076
+ return GpgListing.signingKeys(Processes.capture("gpg", ["--list-secret-keys", "--with-colons"]).stdout);
1077
+ }
1078
+ async post(path, body) {
1079
+ const response = await fetch(`https://keys.openpgp.org/vks/v1/${path}`, {
1080
+ body: JSON.stringify(body),
1081
+ headers: { "Content-Type": "application/json" },
1082
+ method: "POST",
1083
+ signal: AbortSignal.timeout(15000)
1084
+ });
1085
+ return response.ok ? await response.json() : undefined;
1086
+ }
1087
+ }
1088
+ // src/register/npm.system.ts
1089
+ import { resolve } from "path";
1090
+ class NpmCli {
1091
+ root;
1092
+ constructor(root) {
1093
+ this.root = root;
1094
+ }
1095
+ async login() {
1096
+ return Processes.interactive("npm", ["login", "--auth-type=web"]);
1097
+ }
1098
+ async publish(path) {
1099
+ return Processes.interactive("npm", ["publish", "--access", "public"], resolve(this.root, path));
1100
+ }
1101
+ async trust(name, job, repo) {
1102
+ const env = job.environment ? ["--env", job.environment] : [];
1103
+ const args = [
1104
+ "trust",
1105
+ "github",
1106
+ name,
1107
+ "--file",
1108
+ job.workflow,
1109
+ "--repo",
1110
+ `${repo.owner}/${repo.name}`
1111
+ ];
1112
+ return Processes.interactive("npm", [
1113
+ ...args,
1114
+ ...env,
1115
+ "--allow-publish",
1116
+ "--yes"
1117
+ ]);
1118
+ }
1119
+ async trustList(name) {
1120
+ const result = Processes.capture("npm", ["trust", "list", name, "--json"]);
1121
+ if (result.code !== 0)
1122
+ return;
1123
+ return [...new Set(result.stdout.match(/[\w.-]+\.ya?ml\b/g) ?? [])];
1124
+ }
1125
+ async version() {
1126
+ return Processes.capture("npm", ["--version"]).stdout.trim();
1127
+ }
1128
+ async whoami() {
1129
+ const result = Processes.capture("npm", ["whoami"]);
1130
+ if (result.code === 0)
1131
+ return result.stdout.trim();
1132
+ return /E401|ENEEDAUTH/.test(result.stderr) ? "" : undefined;
1133
+ }
1134
+ }
1135
+ // src/register/registries.system.ts
1136
+ class HttpRegistryLookup {
1137
+ async exists(pkg) {
1138
+ try {
1139
+ const response = await fetch(RegistryUrls.lookup(pkg), {
1140
+ headers: { "User-Agent": "devops-toolkit.tasks" },
1141
+ signal: AbortSignal.timeout(1e4)
1142
+ });
1143
+ if (response.status === 200)
1144
+ return true;
1145
+ if (response.status === 404)
1146
+ return false;
1147
+ return;
1148
+ } catch {
1149
+ return;
1150
+ }
1151
+ }
1152
+ }
1153
+ // src/register/repo.system.ts
1154
+ import { existsSync, readFileSync } from "fs";
1155
+ import { resolve as resolve2 } from "path";
1156
+ var SKIPPED = new Set([
1157
+ ".git",
1158
+ ".gradle",
1159
+ ".venv",
1160
+ "bin",
1161
+ "build",
1162
+ "dist",
1163
+ "node_modules",
1164
+ "obj",
1165
+ "target"
1166
+ ]);
1167
+
1168
+ class DiskRepoFiles {
1169
+ root;
1170
+ constructor(root) {
1171
+ this.root = root;
1172
+ }
1173
+ exists(path) {
1174
+ return existsSync(resolve2(this.root, path));
1175
+ }
1176
+ glob(pattern) {
1177
+ const glob = new Bun.Glob(pattern);
1178
+ return [...glob.scanSync({ cwd: this.root, dot: true, onlyFiles: true })].filter((path) => !path.split("/").some((part) => SKIPPED.has(part))).sort();
1179
+ }
1180
+ read(path) {
1181
+ const file = resolve2(this.root, path);
1182
+ return existsSync(file) ? readFileSync(file, "utf8") : undefined;
1183
+ }
1184
+ }
1185
+
1186
+ class GitCli {
1187
+ root;
1188
+ constructor(root) {
1189
+ this.root = root;
1190
+ }
1191
+ async identity() {
1192
+ const get = (key) => Processes.capture("git", ["-C", this.root, "config", key]).stdout.trim();
1193
+ return { email: get("user.email"), name: get("user.name") };
1194
+ }
1195
+ async originUrl() {
1196
+ return Processes.capture("git", [
1197
+ "-C",
1198
+ this.root,
1199
+ "remote",
1200
+ "get-url",
1201
+ "origin"
1202
+ ]).stdout.trim();
1203
+ }
1204
+ }
1205
+ // src/register/terminal.system.ts
1206
+ import { createInterface } from "readline/promises";
1207
+
1208
+ class ConsoleTerminal {
1209
+ async ask(question, fallback = "") {
1210
+ if (!process.stdin.isTTY)
1211
+ return fallback;
1212
+ const rl = createInterface({
1213
+ input: process.stdin,
1214
+ output: process.stdout
1215
+ });
1216
+ const answer = await rl.question(fallback ? `${question} [${fallback}]: ` : `${question}: `);
1217
+ rl.close();
1218
+ return answer.trim() || fallback;
1219
+ }
1220
+ async confirm(question) {
1221
+ if (!process.stdin.isTTY)
1222
+ return false;
1223
+ return /^y(es)?$/i.test(await this.ask(`${question} [y/N]`));
1224
+ }
1225
+ print(line) {
1226
+ process.stdout.write(line.endsWith(`
1227
+ `) ? line : `${line}
1228
+ `);
1229
+ }
1230
+ async secret(question) {
1231
+ if (!process.stdin.isTTY)
1232
+ return "";
1233
+ process.stdout.write(`${question}: `);
1234
+ process.stdin.setRawMode(true);
1235
+ process.stdin.resume();
1236
+ let value = "";
1237
+ for await (const chunk of process.stdin) {
1238
+ const text = String(chunk);
1239
+ if (text === "\x03")
1240
+ process.exit(130);
1241
+ if (text.includes("\r") || text.includes(`
1242
+ `)) {
1243
+ value += text.split(/[\r\n]/)[0];
1244
+ break;
1245
+ }
1246
+ value = text === "\x7F" ? value.slice(0, -1) : value + text;
1247
+ }
1248
+ process.stdin.setRawMode(false);
1249
+ process.stdin.pause();
1250
+ process.stdout.write(`
1251
+ `);
1252
+ return value;
1253
+ }
1254
+ }
1255
+ // bin/register.ts
1256
+ var { values } = parseArgs({
1257
+ options: {
1258
+ apply: { type: "boolean", default: false },
1259
+ check: { type: "boolean", default: false },
1260
+ dir: { type: "string" }
1261
+ }
1262
+ });
1263
+ var root = resolve3(values.dir ?? process.cwd());
1264
+ process.exitCode = await Register.run({
1265
+ dns: new DnsTools(process.env.CLOUDFLARE_API_TOKEN ?? ""),
1266
+ files: new DiskRepoFiles(root),
1267
+ git: new GitCli(root),
1268
+ github: new GhCli,
1269
+ gpg: new GpgCli,
1270
+ npm: new NpmCli(root),
1271
+ registries: new HttpRegistryLookup,
1272
+ terminal: new ConsoleTerminal
1273
+ }, values.apply);