dsh-publish-helper 0.21.2 → 0.21.4

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/index.js CHANGED
@@ -13,6 +13,7 @@ import { npmrcLine, publishArgs, recallArgs } from './lib/npm.mjs';
13
13
  import { DEFAULT_ORG, orgArgs } from './lib/org.mjs';
14
14
  import { preflightPackage } from './lib/preflight.mjs';
15
15
  import { listReviewQueue, readReviews, saveReview } from './lib/reviews.mjs';
16
+ import { releasePackage } from './lib/release.mjs';
16
17
  import { prepareManifest } from './lib/manifest.mjs';
17
18
  import { DEFAULT_SUBMISSIONS_REPO, reviewPullRequest, submitPackage } from './lib/submissions.mjs';
18
19
  import { DEFAULT_REGISTRY_REPO, forkAndOpenPr, generateEntry } from './lib/publish.mjs';
@@ -393,6 +394,33 @@ export function apply(ctx, rawConfig) {
393
394
  presentCall: present('Recall a published version'),
394
395
  });
395
396
 
397
+ ctx.tools.register({
398
+ name: 'publish_tag',
399
+ description: 'Bump the package version, upload the directory to its GitHub repository and create a vX.Y.Z tag to trigger the release workflow.',
400
+ parameters: objectSchema({
401
+ dir: { type: 'string', description: 'Absolute package directory.' },
402
+ repo: { type: 'string', description: 'Repository as owner/name; defaults to the package.json repository.' },
403
+ bump: { type: 'string', enum: ['patch', 'minor', 'major'], description: 'Version bump (default patch).' },
404
+ version: { type: 'string', description: 'Explicit version instead of a bump.' },
405
+ }, ['dir']),
406
+ output: textOutput,
407
+ async execute(args) {
408
+ const { token } = await resolveGithubToken(cfg);
409
+ if (!token) throw new Error('run gh auth login, or save a GitHub token first');
410
+ const result = await releasePackage({
411
+ dir: args.dir,
412
+ token,
413
+ repo: args.repo,
414
+ bump: args.bump ?? 'patch',
415
+ version: args.version,
416
+ });
417
+ return {
418
+ text: `released ${result.repo} ${result.tag}\ncommit: ${result.commit.slice(0, 7)}\nCI 已触发;staging 版本需要在 npm 页面 Approve`,
419
+ };
420
+ },
421
+ presentCall: present('Tag a release'),
422
+ });
423
+
396
424
  ctx.tools.register({
397
425
  name: 'publish_org',
398
426
  description: 'Manage npm org members: list, verify one user, invite (org set ... developer/admin) or remove. Needs an org-owner npm token.',
@@ -0,0 +1,147 @@
1
+ import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+
4
+ import { preflightPackage } from './preflight.mjs';
5
+ import { ensureRepo, getLogin, uploadFiles } from './repo.mjs';
6
+
7
+ const API = 'https://api.github.com';
8
+
9
+ async function api(url, { token, method = 'GET', body, fetchImpl = globalThis.fetch } = {}) {
10
+ const response = await fetchImpl(url, {
11
+ method,
12
+ headers: {
13
+ Authorization: `Bearer ${token}`,
14
+ Accept: 'application/vnd.github+json',
15
+ 'Content-Type': 'application/json',
16
+ },
17
+ body: body ? JSON.stringify(body) : undefined,
18
+ });
19
+ if (!response.ok) {
20
+ let detail = '';
21
+ try {
22
+ detail = JSON.stringify(await response.json());
23
+ } catch {
24
+ // status-only message
25
+ }
26
+ throw new Error(`GitHub ${response.status} ${url}${detail ? `: ${detail}` : ''}`);
27
+ }
28
+ return response.json();
29
+ }
30
+
31
+ export function nextVersion(current, bump = 'patch') {
32
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(String(current ?? ''));
33
+ if (!match) throw new Error(`invalid version: ${current}`);
34
+ let [major, minor, patch] = match.slice(1).map(Number);
35
+ if (bump === 'major') {
36
+ major += 1;
37
+ minor = 0;
38
+ patch = 0;
39
+ } else if (bump === 'minor') {
40
+ minor += 1;
41
+ patch = 0;
42
+ } else if (bump === 'patch') {
43
+ patch += 1;
44
+ } else {
45
+ throw new Error(`unknown bump: ${bump}`);
46
+ }
47
+ return `${major}.${minor}.${patch}`;
48
+ }
49
+
50
+ export function repoFromPackage(pkg) {
51
+ const value = typeof pkg.repository === 'string' ? pkg.repository : pkg.repository?.url;
52
+ const match = /github\.com[/:]([^/]+)\/([^/#]+?)(?:\.git)?$/.exec(String(value ?? '').trim());
53
+ return match ? `${match[1]}/${match[2]}` : null;
54
+ }
55
+
56
+ function walk(root, current = root, out = []) {
57
+ for (const entry of readdirSync(current)) {
58
+ if (entry === 'node_modules' || entry === '.git') continue;
59
+ const full = join(current, entry);
60
+ if (statSync(full).isDirectory()) walk(root, full, out);
61
+ else out.push(relative(root, full).replaceAll('\\', '/'));
62
+ }
63
+ return out;
64
+ }
65
+
66
+ function failedLines(preflight) {
67
+ return preflight.checks
68
+ .filter((check) => !check.ok)
69
+ .map((check) => `${check.id}: ${check.detail}`)
70
+ .join('\n');
71
+ }
72
+
73
+ /**
74
+ * Bump the version, upload the directory to its repository and create a vX.Y.Z tag
75
+ * so the release workflow publishes it.
76
+ */
77
+ export async function releasePackage({
78
+ dir,
79
+ token,
80
+ repo,
81
+ bump = 'patch',
82
+ version,
83
+ fetchImpl = globalThis.fetch,
84
+ } = {}) {
85
+ if (!token) throw new Error('publish_tag needs a GitHub token (run gh auth login or set GH_TOKEN)');
86
+ const directory = String(dir ?? '');
87
+ const manifest = join(directory, 'package.json');
88
+ if (!existsSync(manifest)) throw new Error(`no package.json in ${directory}`);
89
+ const pkg = JSON.parse(readFileSync(manifest, 'utf8'));
90
+ const target = version ?? nextVersion(pkg.version, bump);
91
+
92
+ pkg.version = target;
93
+ writeFileSync(manifest, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
94
+
95
+ const preflight = preflightPackage(directory);
96
+ if (!preflight.ok) throw new Error(`preflight failed:\n${failedLines(preflight)}`);
97
+
98
+ const login = await getLogin({ token, fetchImpl });
99
+ const repoSpec = repo ?? repoFromPackage(pkg) ?? `${login}/${pkg.name}`;
100
+ const [owner, name] = repoSpec.split('/');
101
+ if (!owner || !name) throw new Error(`invalid repository: ${repoSpec}`);
102
+ await ensureRepo({
103
+ token,
104
+ owner,
105
+ name,
106
+ description: typeof pkg.description === 'string' ? pkg.description : '',
107
+ fetchImpl,
108
+ });
109
+
110
+ const files = walk(directory).map((path) => ({
111
+ path,
112
+ content: readFileSync(join(directory, path)).toString('base64'),
113
+ }));
114
+ const workflowPath = '.github/workflows/release.yml';
115
+ if (!files.some((file) => file.path === workflowPath)) {
116
+ const template = readFileSync(new URL('../templates/release.yml', import.meta.url), 'utf8');
117
+ files.push({ path: workflowPath, content: Buffer.from(template, 'utf8').toString('base64') });
118
+ }
119
+ await uploadFiles({
120
+ token,
121
+ owner,
122
+ name,
123
+ files,
124
+ message: `release v${target}`,
125
+ fetchImpl,
126
+ });
127
+
128
+ const head = await api(`${API}/repos/${owner}/${name}/commits/main`, { token, fetchImpl });
129
+ const tag = `v${target}`;
130
+ let exists = false;
131
+ try {
132
+ await api(`${API}/repos/${owner}/${name}/git/ref/tags/${tag}`, { token, fetchImpl });
133
+ exists = true;
134
+ } catch (error) {
135
+ if (!String(error).includes(' 404 ')) throw error;
136
+ }
137
+ if (exists) throw new Error(`tag ${tag} already exists in ${owner}/${name}`);
138
+
139
+ await api(`${API}/repos/${owner}/${name}/git/refs`, {
140
+ token,
141
+ method: 'POST',
142
+ fetchImpl,
143
+ body: { ref: `refs/tags/${tag}`, sha: head.sha },
144
+ });
145
+
146
+ return { repo: `${owner}/${name}`, version: target, tag, commit: head.sha };
147
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-publish-helper",
3
- "version": "0.21.2",
3
+ "version": "0.21.4",
4
4
  "description": "DSH plugin publishing assistant: discover by topic, check listing readiness, generate the registry entry, open the pull request and show a settings page.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -1,13 +1,12 @@
1
1
  # Copy to .github/workflows/release.yml in the package repository.
2
2
  #
3
- # Trusted publishing (recommended): configure it once on npmjs.com
4
- # package page -> Settings -> Trusted publishing -> GitHub Actions
5
- # repository: <owner>/<repo> workflow filename: release.yml
6
- # Then a tag push (v1.2.3) publishes without any npm token or OTP.
3
+ # Token publishing (default here):
4
+ # add a repository secret NPM_TOKEN = granular npm token
5
+ # (Read and write, Bypass 2FA; never commit it) and push a tag.
7
6
  #
8
- # Without trusted publishing, replace the last step with the commented fallback
9
- # and store a granular npm token (Read and write, Bypass 2FA) in the NPM_TOKEN
10
- # repository secret. Never commit that token.
7
+ # Trusted publishing alternative (no token, needs account 2FA on npm):
8
+ # package page -> Settings -> Trusted publishing -> GitHub Actions
9
+ # then remove the NODE_AUTH_TOKEN env from the publish step.
11
10
  name: release
12
11
 
13
12
  on:
@@ -18,7 +17,7 @@ on:
18
17
 
19
18
  permissions:
20
19
  contents: read
21
- id-token: write # required for trusted publishing and provenance
20
+ id-token: write # provenance attestation
22
21
 
23
22
  jobs:
24
23
  publish:
@@ -31,8 +30,9 @@ jobs:
31
30
  - uses: actions/setup-node@v4
32
31
  with:
33
32
  node-version: 22
33
+ registry-url: 'https://registry.npmjs.org'
34
34
 
35
- - name: Use the npm CLI that supports trusted publishing
35
+ - name: Use the npm CLI that supports provenance
36
36
  run: npm install -g npm@latest
37
37
 
38
38
  - name: Verify the tag matches package.json
@@ -59,9 +59,5 @@ jobs:
59
59
 
60
60
  - name: Publish with provenance
61
61
  run: npm publish --provenance --access public
62
-
63
- # Fallback when trusted publishing is not configured:
64
- # - name: Publish with a token
65
- # run: npm publish --provenance --access public
66
- # env:
67
- # NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
62
+ env:
63
+ NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}