@icebreakers/monorepo-templates 1.3.2 → 1.3.3

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,90 @@
1
+ import { Buffer } from 'node:buffer'
2
+
3
+ function repositoryParts(repository) {
4
+ const [owner, name] = repository.split('/')
5
+ if (!owner || !name) {
6
+ throw new Error(`Invalid GitHub repository: ${repository}`)
7
+ }
8
+ return { owner, name }
9
+ }
10
+
11
+ function encodePath(path) {
12
+ return path.split('/').map(segment => encodeURIComponent(segment)).join('/')
13
+ }
14
+
15
+ export function createGitHubClient({ token, repository, fetchImpl = fetch }) {
16
+ const { owner, name } = repositoryParts(repository)
17
+ const apiBase = `https://api.github.com/repos/${owner}/${name}`
18
+ async function request(path, options = {}) {
19
+ const response = await fetchImpl(`${apiBase}${path}`, {
20
+ ...options,
21
+ headers: {
22
+ 'accept': 'application/vnd.github+json',
23
+ 'authorization': `Bearer ${token}`,
24
+ 'content-type': 'application/json',
25
+ 'x-github-api-version': '2022-11-28',
26
+ ...(options.headers ?? {}),
27
+ },
28
+ })
29
+ const text = await response.text()
30
+ let body
31
+ try {
32
+ body = text ? JSON.parse(text) : undefined
33
+ }
34
+ catch {
35
+ body = text
36
+ }
37
+ if (!response.ok) {
38
+ throw new Error(`GitHub API ${response.status} ${options.method ?? 'GET'} ${path}: ${typeof body === 'string' ? body : body?.message ?? 'request failed'}`)
39
+ }
40
+ return body
41
+ }
42
+ return {
43
+ repository,
44
+ getPullRequest: number => request(`/pulls/${number}`),
45
+ getPullRequestFiles: async (number) => {
46
+ const files = []
47
+ for (let page = 1; ; page++) {
48
+ const pageFiles = await request(`/pulls/${number}/files?per_page=100&page=${page}`)
49
+ files.push(...pageFiles)
50
+ if (pageFiles.length < 100) {
51
+ return files
52
+ }
53
+ }
54
+ },
55
+ getContent: async (path, ref) => {
56
+ try {
57
+ const content = await request(`/contents/${encodePath(path)}?ref=${encodeURIComponent(ref)}`)
58
+ if (Array.isArray(content) || content.encoding !== 'base64') {
59
+ return undefined
60
+ }
61
+ return Buffer.from(content.content.replace(/\n/g, ''), 'base64').toString('utf8')
62
+ }
63
+ catch (error) {
64
+ if (String(error.message).startsWith('GitHub API 404')) {
65
+ return undefined
66
+ }
67
+ throw error
68
+ }
69
+ },
70
+ getRef: ref => request(`/git/ref/${encodePath(ref)}`),
71
+ getCommit: sha => request(`/git/commits/${sha}`),
72
+ createBlob: content => request('/git/blobs', { method: 'POST', body: JSON.stringify({ content, encoding: 'utf-8' }) }),
73
+ createTree: (baseTree, tree) => request('/git/trees', { method: 'POST', body: JSON.stringify({ base_tree: baseTree, tree }) }),
74
+ createCommit: (message, tree, parents) => request('/git/commits', { method: 'POST', body: JSON.stringify({ message, tree, parents }) }),
75
+ updateRef: (ref, sha) => request(`/git/refs/heads/${encodePath(ref)}`, { method: 'PATCH', body: JSON.stringify({ sha, force: false }) }),
76
+ createComment: (number, body) => request(`/issues/${number}/comments`, { method: 'POST', body: JSON.stringify({ body }) }),
77
+ listComments: async (number) => {
78
+ const comments = []
79
+ for (let page = 1; ; page++) {
80
+ const pageComments = await request(`/issues/${number}/comments?per_page=100&page=${page}`)
81
+ comments.push(...pageComments)
82
+ if (pageComments.length < 100) {
83
+ return comments
84
+ }
85
+ }
86
+ },
87
+ createBranch: async (branch, sha) => request('/git/refs', { method: 'POST', body: JSON.stringify({ ref: `refs/heads/${branch}`, sha }) }),
88
+ createPullRequest: input => request('/pulls', { method: 'POST', body: JSON.stringify(input) }),
89
+ }
90
+ }
@@ -0,0 +1,218 @@
1
+ import fs from 'node:fs/promises'
2
+ import process from 'node:process'
3
+ import { createGitHubClient } from './github.mjs'
4
+
5
+ const CHANGESET_MARKER = '<!-- repoctl-auto-changeset -->'
6
+ const PACKAGE_PATH = /^packages\/([^/]+)\//
7
+ const CHANGESET_PATH = /^\.changeset\/[^/]+\.md$/
8
+ const RELEASE_BRANCH = /^(?:pnpm-release\/|release\/pnpm-version)/
9
+
10
+ export function packageDirectories(files) {
11
+ return [...new Set(files
12
+ .map(file => file.filename ?? file)
13
+ .filter(filename => !/^packages\/[^/]+\/dist(?:\/|$)/.test(filename))
14
+ .map(filename => filename.match(PACKAGE_PATH)?.[1])
15
+ .filter(Boolean))]
16
+ }
17
+
18
+ export function releaseLevel(labels = []) {
19
+ const names = labels.map(label => typeof label === 'string' ? label : label.name)
20
+ if (names.includes('release:major')) {
21
+ return 'major'
22
+ }
23
+ if (names.includes('release:minor')) {
24
+ return 'minor'
25
+ }
26
+ return 'patch'
27
+ }
28
+
29
+ export function renderChangeset({ packages, level = 'patch', number, title }) {
30
+ const frontmatter = packages
31
+ .slice()
32
+ .sort((a, b) => a.localeCompare(b))
33
+ .map(name => `${/^[\w.-]+$/.test(name) ? name : JSON.stringify(name)}: ${level}`)
34
+ .join('\n')
35
+ const summary = title.replace(/\r?\n/g, ' ').replace(/\s+/g, ' ').trim()
36
+ return `---\n${frontmatter}\n---\n\n${summary} (#${number})\n`
37
+ }
38
+
39
+ export function changesetPath(number) {
40
+ return `.changeset/auto-pr-${number}.md`
41
+ }
42
+
43
+ export function isReleaseBranch(ref) {
44
+ return RELEASE_BRANCH.test(ref)
45
+ }
46
+
47
+ export function hasChangeset(files) {
48
+ return files.some(file => CHANGESET_PATH.test(file.filename ?? file))
49
+ }
50
+
51
+ function hasManualChangeset(files, generatedPath) {
52
+ return files.some((file) => {
53
+ const filename = file.filename ?? file
54
+ return CHANGESET_PATH.test(filename) && filename !== generatedPath
55
+ })
56
+ }
57
+
58
+ export function isPublishableManifest(manifest) {
59
+ return Boolean(manifest && typeof manifest.name === 'string' && manifest.private !== true)
60
+ }
61
+
62
+ async function manifestsForFiles(client, files, ref) {
63
+ const names = []
64
+ for (const directory of packageDirectories(files)) {
65
+ const content = await client.getContent(`packages/${directory}/package.json`, ref)
66
+ if (!content) {
67
+ continue
68
+ }
69
+ try {
70
+ const manifest = JSON.parse(content)
71
+ if (isPublishableManifest(manifest)) {
72
+ names.push(manifest.name)
73
+ }
74
+ }
75
+ catch {
76
+ // Ignore a malformed manifest; the normal CI checks will report it.
77
+ }
78
+ }
79
+ return [...new Set(names)]
80
+ }
81
+
82
+ async function commitChangesets(client, branch, baseSha, entries) {
83
+ const commit = await client.getCommit(baseSha)
84
+ const tree = []
85
+ for (const entry of entries) {
86
+ const blob = await client.createBlob(entry.content)
87
+ tree.push({ path: entry.path, mode: '100644', type: 'blob', sha: blob.sha })
88
+ }
89
+ const nextTree = await client.createTree(commit.tree.sha, tree)
90
+ const nextCommit = await client.createCommit('chore(release): add automated changesets', nextTree.sha, [baseSha])
91
+ await client.updateRef(branch, nextCommit.sha)
92
+ return nextCommit.sha
93
+ }
94
+
95
+ async function commentFork(client, number) {
96
+ const comments = await client.listComments(number)
97
+ if (comments.some(comment => comment.body?.includes(CHANGESET_MARKER))) {
98
+ return false
99
+ }
100
+ await client.createComment(number, `${CHANGESET_MARKER}\nThis PR changes a publishable package. Please add a .changeset/*.md release intent before merging. You can run pnpm change locally.`)
101
+ return true
102
+ }
103
+
104
+ async function prepareEntry(client, pullRequest, files) {
105
+ const path = changesetPath(pullRequest.number)
106
+ if (pullRequest.draft || isReleaseBranch(pullRequest.head.ref) || hasManualChangeset(files, path)) {
107
+ return undefined
108
+ }
109
+ const packages = await manifestsForFiles(client, files, pullRequest.head.sha)
110
+ if (!packages.length) {
111
+ return undefined
112
+ }
113
+ const level = releaseLevel(pullRequest.labels)
114
+ const content = renderChangeset({ packages, level, number: pullRequest.number, title: pullRequest.title })
115
+ const existing = await client.getContent(path, pullRequest.head.sha)
116
+ if (existing && !['patch', 'minor', 'major'].some(candidate => existing === renderChangeset({ packages, level: candidate, number: pullRequest.number, title: pullRequest.title }))) {
117
+ return undefined
118
+ }
119
+ if (existing === content) {
120
+ return undefined
121
+ }
122
+ return {
123
+ path,
124
+ content,
125
+ }
126
+ }
127
+
128
+ export async function processPullRequest(client, number) {
129
+ const pullRequest = await client.getPullRequest(number)
130
+ const files = await client.getPullRequestFiles(number)
131
+ const entry = await prepareEntry(client, pullRequest, files)
132
+ if (!entry) {
133
+ return { action: 'skipped', number }
134
+ }
135
+ const repository = pullRequest.base.repo.full_name
136
+ if (pullRequest.head.repo.full_name !== repository) {
137
+ await commentFork(client, number)
138
+ return { action: 'commented', number }
139
+ }
140
+ const ref = await client.getRef(`heads/${pullRequest.head.ref}`)
141
+ await commitChangesets(client, pullRequest.head.ref, ref.object.sha, [entry])
142
+ return { action: 'committed', number, path: entry.path }
143
+ }
144
+
145
+ export async function backfillPullRequests(client, numbers, { runId = `${Date.now()}` } = {}) {
146
+ const baseRef = await client.getRef('heads/main')
147
+ const entries = []
148
+ const seen = new Set()
149
+ const results = []
150
+ for (const number of numbers) {
151
+ const pullRequest = await client.getPullRequest(number)
152
+ if (!pullRequest.merged_at || pullRequest.base.ref !== 'main') {
153
+ results.push({ action: 'skipped', number })
154
+ continue
155
+ }
156
+ const files = await client.getPullRequestFiles(number)
157
+ const path = changesetPath(number)
158
+ if (hasChangeset(files) || seen.has(path) || await client.getContent(path, baseRef.object.sha)) {
159
+ results.push({ action: 'skipped', number })
160
+ continue
161
+ }
162
+ const packages = await manifestsForFiles(client, files, pullRequest.merge_commit_sha)
163
+ if (!packages.length) {
164
+ results.push({ action: 'skipped', number })
165
+ continue
166
+ }
167
+ seen.add(path)
168
+ entries.push({
169
+ path,
170
+ content: renderChangeset({ packages, level: releaseLevel(pullRequest.labels), number, title: pullRequest.title }),
171
+ })
172
+ results.push({ action: 'planned', number, path })
173
+ }
174
+ if (!entries.length) {
175
+ return { results, pullRequest: undefined }
176
+ }
177
+ const branch = `automation/changeset-backfill-${runId}`
178
+ await client.createBranch(branch, baseRef.object.sha)
179
+ await commitChangesets(client, branch, baseRef.object.sha, entries)
180
+ const created = await client.createPullRequest({
181
+ base: 'main',
182
+ head: branch,
183
+ title: `chore(release): backfill changesets (${numbers.map(number => `#${number}`).join(', ')})`,
184
+ body: `This PR backfills automated release intents for merged PRs.\n\n${entries.map(entry => `- ${entry.path}`).join('\n')}`,
185
+ })
186
+ return { results, pullRequest: created }
187
+ }
188
+
189
+ async function main() {
190
+ const eventPath = process.env.GITHUB_EVENT_PATH
191
+ const event = eventPath ? JSON.parse(await fs.readFile(eventPath, 'utf8')) : undefined
192
+ const repository = process.env.GITHUB_REPOSITORY ?? event?.repository?.full_name
193
+ const token = process.env.GITHUB_TOKEN
194
+ if (!repository || !token) {
195
+ throw new Error('GITHUB_REPOSITORY and GITHUB_TOKEN are required')
196
+ }
197
+ const client = createGitHubClient({ token, repository })
198
+ if (process.env.GITHUB_EVENT_NAME === 'workflow_dispatch') {
199
+ const numbers = (process.env.PR_NUMBERS ?? '').split(',').map(value => Number(value.trim())).filter(value => Number.isInteger(value) && value > 0)
200
+ if (!numbers.length) {
201
+ throw new Error('PR_NUMBERS must contain at least one PR number')
202
+ }
203
+ console.log(JSON.stringify(await backfillPullRequests(client, numbers, { runId: process.env.GITHUB_RUN_ID })))
204
+ return
205
+ }
206
+ const number = event?.pull_request?.number
207
+ if (!number) {
208
+ throw new Error('pull_request event payload is required')
209
+ }
210
+ console.log(JSON.stringify(await processPullRequest(client, number)))
211
+ }
212
+
213
+ if (import.meta.url === `file://${process.argv[1]}`) {
214
+ main().catch((error) => {
215
+ console.error(error.stack ?? error)
216
+ process.exitCode = 1
217
+ })
218
+ }
@@ -0,0 +1,40 @@
1
+ name: Automatic Release Intent
2
+
3
+ on:
4
+ pull_request_target:
5
+ types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled]
6
+ workflow_dispatch:
7
+ inputs:
8
+ pr_numbers:
9
+ description: Comma-separated merged PR numbers to backfill
10
+ required: true
11
+ type: string
12
+
13
+ permissions:
14
+ contents: write
15
+ pull-requests: write
16
+
17
+ concurrency:
18
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
19
+ cancel-in-progress: false
20
+
21
+ jobs:
22
+ generate:
23
+ name: Generate release intent
24
+ runs-on: ubuntu-latest
25
+ steps:
26
+ - name: Check out workflow source
27
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
28
+ with:
29
+ fetch-depth: 1
30
+
31
+ - name: Setup Node.js environment
32
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
33
+ with:
34
+ node-version: 24
35
+
36
+ - name: Generate or backfill changesets
37
+ env:
38
+ GITHUB_TOKEN: ${{ github.token }}
39
+ PR_NUMBERS: ${{ inputs.pr_numbers }}
40
+ run: node .github/auto-changeset/index.mjs
@@ -23,6 +23,10 @@ pnpm test
23
23
 
24
24
  Changes to publishable packages require a pnpm change intent created with `pnpm change`. Commits must use Conventional Commit syntax.
25
25
 
26
+ Pull requests that change a publishable package receive an automatic `.changeset/auto-pr-<number>.md` intent when they come from a branch in this repository. The default bump is `patch`; add the `release:minor` or `release:major` label to override it. Fork pull requests cannot be written to by the workflow, so add the intent manually. Existing hand-written intents are always preserved.
27
+
28
+ To backfill merged pull requests that predate this automation, run the `Automatic Release Intent` workflow manually with a comma-separated list of PR numbers. The workflow opens one backfill pull request, and the next `repo release ci` run consumes its changesets normally.
29
+
26
30
  The repository includes repoctl's CLI and monorepo engine, template assets, shared lint/config packages, and the `apps/mock` fixture demo. Keep package APIs and independent version lines intact when working across these areas.
27
31
 
28
32
  When changing templates or managed root assets, update their source first and refresh packaged copies with `pnpm --filter @icebreakers/monorepo-templates sync:assets`.
@@ -90,7 +90,7 @@
90
90
  "@types/set-value": "^4.0.3",
91
91
  "@typescript-eslint/types": "^8.69.0",
92
92
  "@unocss/eslint-plugin": "66.9.2",
93
- "@vitest/coverage-v8": "~4.1.11",
93
+ "@vitest/coverage-v8": "~5.0.0",
94
94
  "astro-eslint-parser": "^3.1.0",
95
95
  "ci-info": "^4.4.0",
96
96
  "cross-env": "^10.1.0",
@@ -112,7 +112,7 @@
112
112
  "micromatch": "^4.0.8",
113
113
  "only-allow": "^1.2.2",
114
114
  "pathe": "^2.0.3",
115
- "pkg-types": "^2.3.1",
115
+ "pkg-types": "^2.3.2",
116
116
  "prettier": "^3.9.6",
117
117
  "prettier-plugin-astro": "^0.14.1",
118
118
  "repoctl": "workspace:*",
@@ -131,7 +131,7 @@
131
131
  "tsup": "^8.5.1",
132
132
  "typescript": "^6.0.3",
133
133
  "unbuild": "^3.6.1",
134
- "vitest": "~4.1.11",
134
+ "vitest": "~5.0.0",
135
135
  "yaml": "^2.9.0"
136
136
  },
137
137
  "publishConfig": {
@@ -18,8 +18,8 @@ overrides:
18
18
  prettier: 3.9.6
19
19
  typescript: 6.0.3
20
20
  vite: 8.2.2
21
- postcss: 8.5.26
22
- postcss-selector-parser: 7.1.5
21
+ postcss: 8.5.28
22
+ postcss-selector-parser: 7.1.6
23
23
  js-yaml: 5.4.1
24
24
  nanoid: 6.0.1
25
25
  brace-expansion: 5.0.9
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@icebreakers/monorepo-templates",
3
3
  "type": "module",
4
- "version": "1.3.2",
4
+ "version": "1.3.3",
5
5
  "description": "Built-in project templates and managed workspace assets for repoctl",
6
6
  "author": "ice breaker <hi@sonofmagic.top>",
7
7
  "license": "MIT",
@@ -45,9 +45,9 @@
45
45
  "node": ">=18.0.0"
46
46
  },
47
47
  "dependencies": {
48
- "@inquirer/checkbox": "^5.2.3",
49
- "@inquirer/input": "^5.1.4",
50
- "@inquirer/select": "^5.2.3",
48
+ "@inquirer/checkbox": "^5.2.4",
49
+ "@inquirer/input": "^5.1.5",
50
+ "@inquirer/select": "^5.2.4",
51
51
  "commander": "^15.0.0",
52
52
  "nanoexec": "^1.1.0",
53
53
  "yaml": "^2.9.0"
@@ -43,7 +43,7 @@
43
43
  "tailwind-variants": "^3.3.1",
44
44
  "vue": "^3.5.42",
45
45
  "vue-i18n": "^11.4.10",
46
- "vue-router": "^5.3.0"
46
+ "vue-router": "^5.3.1"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@cloudflare/vite-plugin": "^1.54.3",