shapewall 0.0.0-stage → 0.2.2
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/CHANGELOG.md +139 -0
- package/Dockerfile.agent +45 -0
- package/LICENSE +202 -0
- package/NOTICE +12 -0
- package/README.md +651 -2
- package/THIRD_PARTY.md +165 -0
- package/bin/shapewall.js +29 -0
- package/dist/agent/package-lock.json +8384 -0
- package/dist/client/assets/BoardChat-D5SFd8HE.js +28 -0
- package/dist/client/assets/BuzzDialog-HWXBy52W.js +1 -0
- package/dist/client/assets/ChecksPanel-DTdImWoD.js +1 -0
- package/dist/client/assets/History-CEv6b-av.js +1 -0
- package/dist/client/assets/LocalSettings-C4vriEVQ.js +1 -0
- package/dist/client/assets/Management-DCfhcEUY.js +1 -0
- package/dist/client/assets/QuickConnect-DQGgUsl1.js +1 -0
- package/dist/client/assets/ShareDialog-C_plIto0.js +2 -0
- package/dist/client/assets/app-update-dialog-2hPz_N9G.js +1 -0
- package/dist/client/assets/circle-x-BZMPi8Zf.js +1 -0
- package/dist/client/assets/index-ByQRKVit.css +2 -0
- package/dist/client/assets/index-DweQ8Qtu.js +29 -0
- package/dist/client/assets/refresh-cw-CRow0Nbq.js +1 -0
- package/dist/client/assets/runtime-Bft6x_6E.js +4 -0
- package/dist/client/assets/square-A8EnIYLR.js +1 -0
- package/dist/client/assets/tts-dist-DYlBQmwG.js +18 -0
- package/dist/client/assets/tts-en-g2p-BPUtBFGG.js +1 -0
- package/dist/client/assets/tts-ort-wasm-simd-threaded-qh98TCA_.wasm +0 -0
- package/dist/client/assets/tts-ort.wasm.bundle.min-rEkcs_ow.js +12 -0
- package/dist/client/assets/tts-rolldown-runtime-D8NudN84.js +1 -0
- package/dist/client/assets/tts-spacy-en-tokenizer-6SNMl--A.json +1 -0
- package/dist/client/assets/tts-tts.worker-Bzm6aWbv.js +1 -0
- package/dist/client/assets/tts-us_gold-DcjeNMH1.json +92589 -0
- package/dist/client/assets/tts-us_silver-C964mEB5.json +93363 -0
- package/dist/client/assets/ui-CLbws0rx.js +41 -0
- package/dist/client/build-info.json +1 -0
- package/dist/client/favicon.svg +7 -0
- package/dist/client/icons/apple-touch-icon.png +0 -0
- package/dist/client/icons/icon-192.png +0 -0
- package/dist/client/icons/icon-512.png +0 -0
- package/dist/client/icons/maskable-512.png +0 -0
- package/dist/client/index.html +25 -0
- package/dist/client/manifest.webmanifest +15 -0
- package/dist/client/sw.js +53 -0
- package/dist/client/theme-boot.js +27 -0
- package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +1 -0
- package/dist/console/assets/LocalConsole-Bb2FUDs7.js +1 -0
- package/dist/console/assets/app-update-dialog-DIeYepLZ.js +1 -0
- package/dist/console/assets/console-C7uJLLOn.js +51 -0
- package/dist/console/assets/console-R8IBY3Am.css +2 -0
- package/dist/console/build-info.json +1 -0
- package/dist/console/console.html +21 -0
- package/dist/console/favicon.svg +7 -0
- package/dist/console/icons/apple-touch-icon.png +0 -0
- package/dist/console/icons/icon-192.png +0 -0
- package/dist/console/icons/icon-512.png +0 -0
- package/dist/console/icons/maskable-512.png +0 -0
- package/dist/console/manifest.webmanifest +15 -0
- package/dist/console/theme-boot.js +27 -0
- package/docs/agent-hardening.md +342 -0
- package/docs/agent-recipes.md +187 -0
- package/docs/agent-workflow.md +320 -0
- package/docs/agents.md +894 -0
- package/docs/architecture.md +242 -0
- package/docs/buzz.md +140 -0
- package/docs/capture-warnings.md +57 -0
- package/docs/config.md +489 -0
- package/docs/deployment.md +289 -0
- package/docs/design-system.md +162 -0
- package/docs/github.md +107 -0
- package/docs/hosted.md +764 -0
- package/docs/images/board-overview.png +0 -0
- package/docs/images/journeys.png +0 -0
- package/docs/images/live-comment.png +0 -0
- package/docs/images/phone-comment.png +0 -0
- package/docs/images/phone-overview.png +0 -0
- package/docs/images/variant.png +0 -0
- package/docs/interaction-audits.md +40 -0
- package/docs/journeys.md +137 -0
- package/docs/local-accounts.md +80 -0
- package/docs/notifications.md +237 -0
- package/docs/page-checks.md +69 -0
- package/docs/performance.md +174 -0
- package/docs/starter-agent.md +325 -0
- package/docs/updates.md +87 -0
- package/examples/audits/interaction.audit.json +17 -0
- package/package.json +132 -4
- package/src/accounts/avatar.js +121 -0
- package/src/accounts/local.js +464 -0
- package/src/agent/acp/command.js +204 -0
- package/src/agent/acp/detect.js +75 -0
- package/src/agent/acp/sandbox.js +160 -0
- package/src/agent/agent-health.js +75 -0
- package/src/agent/backends/acp.js +1297 -0
- package/src/agent/backends/index.js +61 -0
- package/src/agent/backends/openai.js +308 -0
- package/src/agent/composer.js +221 -0
- package/src/agent/config.js +338 -0
- package/src/agent/context.js +191 -0
- package/src/agent/control.js +122 -0
- package/src/agent/errors.js +17 -0
- package/src/agent/feedback-loop.js +137 -0
- package/src/agent/manage.js +94 -0
- package/src/agent/next-steps.js +51 -0
- package/src/agent/owner-mcp.js +38 -0
- package/src/agent/plain-text.js +52 -0
- package/src/agent/ratings-core.js +213 -0
- package/src/agent/ratings.js +100 -0
- package/src/agent/reply-text.js +67 -0
- package/src/agent/routes.js +1065 -0
- package/src/agent/run.js +326 -0
- package/src/agent/settings-routes.js +704 -0
- package/src/agent/showable.js +23 -0
- package/src/agent/starter/approvals.js +181 -0
- package/src/agent/starter/build-image.js +90 -0
- package/src/agent/starter/cli.js +163 -0
- package/src/agent/starter/disk.js +53 -0
- package/src/agent/starter/doctor.js +180 -0
- package/src/agent/starter/egress-proxy.js +351 -0
- package/src/agent/starter/gate.js +90 -0
- package/src/agent/starter/loop.js +114 -0
- package/src/agent/starter/model-relay.js +289 -0
- package/src/agent/starter/pause.js +14 -0
- package/src/agent/starter/probe.js +272 -0
- package/src/agent/starter/prompt.js +41 -0
- package/src/agent/starter/push-guard.js +146 -0
- package/src/agent/starter/rpc.js +164 -0
- package/src/agent/starter/runtime.js +287 -0
- package/src/agent/starter/sandbox-main.js +121 -0
- package/src/agent/starter/settings.js +290 -0
- package/src/agent/starter/source.js +69 -0
- package/src/agent/starter/supervisor.js +755 -0
- package/src/agent/starter/sweep.js +46 -0
- package/src/agent/starter/tools.js +524 -0
- package/src/agent/starter/watch.js +84 -0
- package/src/agent/starter/worktree.js +409 -0
- package/src/agent/text-diff.js +210 -0
- package/src/agent/thread-history.js +223 -0
- package/src/agent/threads.js +399 -0
- package/src/agent/tools.js +200 -0
- package/src/agent/turn-changes.js +424 -0
- package/src/agent/undo-state.js +26 -0
- package/src/agent/user-settings.js +308 -0
- package/src/auth/record.js +375 -0
- package/src/broken-links.js +164 -0
- package/src/buzz/client.js +75 -0
- package/src/buzz/config.js +151 -0
- package/src/buzz/environment.js +13 -0
- package/src/buzz/gateway.js +192 -0
- package/src/buzz/routes.js +61 -0
- package/src/buzz/signer-child.js +205 -0
- package/src/buzz/store.js +89 -0
- package/src/buzz/transport.js +60 -0
- package/src/buzz/verify.js +140 -0
- package/src/capture/actions.js +159 -0
- package/src/capture/capture.js +776 -0
- package/src/capture/dom-names.js +189 -0
- package/src/capture/element-map.js +509 -0
- package/src/capture/live.js +827 -0
- package/src/capture/media-scheme.js +317 -0
- package/src/capture/network-summary.js +86 -0
- package/src/capture/pacing.js +34 -0
- package/src/capture/requests.js +167 -0
- package/src/capture/sanitize.js +752 -0
- package/src/checks/accessibility.js +134 -0
- package/src/checks/budgets.js +58 -0
- package/src/checks/cli.js +55 -0
- package/src/checks/comparison.js +113 -0
- package/src/checks/environments.js +32 -0
- package/src/checks/flow-config.js +82 -0
- package/src/checks/flow-origin.js +53 -0
- package/src/checks/flows.js +398 -0
- package/src/checks/lighthouse-auth.js +145 -0
- package/src/checks/lighthouse-findings.js +130 -0
- package/src/checks/lighthouse.js +395 -0
- package/src/checks/robots.js +85 -0
- package/src/checks/routes.js +52 -0
- package/src/checks/run-control.js +259 -0
- package/src/checks/runner.js +724 -0
- package/src/checks/schema.js +133 -0
- package/src/checks/seo-analysis.js +443 -0
- package/src/checks/seo-probe.js +190 -0
- package/src/checks/seo-snapshot.js +99 -0
- package/src/checks/store.js +214 -0
- package/src/checks/transport.js +47 -0
- package/src/cli/args.js +319 -0
- package/src/cli/capture.js +79 -0
- package/src/cli/commands.js +92 -0
- package/src/cli/comments.js +84 -0
- package/src/cli/help.js +243 -0
- package/src/cli/init.js +214 -0
- package/src/cli/misc.js +64 -0
- package/src/cli/notify.js +87 -0
- package/src/cli/open.js +22 -0
- package/src/cli/serve.js +274 -0
- package/src/cli/variant.js +82 -0
- package/src/cli/watch.js +70 -0
- package/src/cli.js +130 -0
- package/src/comment-fields.js +76 -0
- package/src/comments-cli.js +208 -0
- package/src/config-reload.js +100 -0
- package/src/config.js +1061 -0
- package/src/devices-cli.js +21 -0
- package/src/diff.js +95 -0
- package/src/discover.js +284 -0
- package/src/doctor.js +295 -0
- package/src/event-log.js +268 -0
- package/src/events-cli.js +102 -0
- package/src/events.js +113 -0
- package/src/export.js +119 -0
- package/src/feedback.js +246 -0
- package/src/github.js +551 -0
- package/src/hosted/LICENSE.md +105 -0
- package/src/hosted/access-cli.js +78 -0
- package/src/hosted/admin.js +682 -0
- package/src/hosted/agent-approvals.js +163 -0
- package/src/hosted/agent-policy.js +189 -0
- package/src/hosted/app.js +510 -0
- package/src/hosted/auth-routes.js +540 -0
- package/src/hosted/auth.js +536 -0
- package/src/hosted/backup.js +483 -0
- package/src/hosted/board-context.js +35 -0
- package/src/hosted/board-routes.js +486 -0
- package/src/hosted/board-view.js +94 -0
- package/src/hosted/clean-worker.js +24 -0
- package/src/hosted/cleaner.js +89 -0
- package/src/hosted/comments.js +355 -0
- package/src/hosted/console-routes.js +401 -0
- package/src/hosted/cookies.js +18 -0
- package/src/hosted/crypto.js +80 -0
- package/src/hosted/db.js +496 -0
- package/src/hosted/device-routes.js +175 -0
- package/src/hosted/device.js +233 -0
- package/src/hosted/events.js +63 -0
- package/src/hosted/guards.js +172 -0
- package/src/hosted/guest-view.js +65 -0
- package/src/hosted/http.js +39 -0
- package/src/hosted/import.js +300 -0
- package/src/hosted/mail.js +73 -0
- package/src/hosted/mcp-http.js +71 -0
- package/src/hosted/membership.js +114 -0
- package/src/hosted/operator.js +478 -0
- package/src/hosted/ops-cli.js +345 -0
- package/src/hosted/pages.js +146 -0
- package/src/hosted/permissions.js +113 -0
- package/src/hosted/presence.js +372 -0
- package/src/hosted/projects.js +124 -0
- package/src/hosted/public.js +109 -0
- package/src/hosted/push.js +622 -0
- package/src/hosted/quotas.js +115 -0
- package/src/hosted/ratelimit.js +96 -0
- package/src/hosted/rebind.js +316 -0
- package/src/hosted/retention.js +128 -0
- package/src/hosted/server.js +260 -0
- package/src/hosted/setup-link.js +64 -0
- package/src/hosted/setup.js +323 -0
- package/src/hosted/shares.js +444 -0
- package/src/hosted/tailscale.js +204 -0
- package/src/hosted/tenancy.js +301 -0
- package/src/hosted/token-api.js +455 -0
- package/src/hosted/token-events.js +60 -0
- package/src/hosted/tokens.js +57 -0
- package/src/hosted/turnstile.js +49 -0
- package/src/hosted/usercontent.js +154 -0
- package/src/hosted/zip.js +155 -0
- package/src/invocation.js +58 -0
- package/src/journey-paths.js +282 -0
- package/src/journeys.js +189 -0
- package/src/links.js +106 -0
- package/src/local-projects.js +182 -0
- package/src/lock.js +193 -0
- package/src/mcp.js +417 -0
- package/src/mentions.js +151 -0
- package/src/net.js +15 -0
- package/src/notify/config.js +275 -0
- package/src/notify/index.js +301 -0
- package/src/notify/lease.js +73 -0
- package/src/notify/messages.js +212 -0
- package/src/notify/run.js +174 -0
- package/src/pixeldiff.js +49 -0
- package/src/png.js +143 -0
- package/src/reactions.js +111 -0
- package/src/remote/cli.js +133 -0
- package/src/remote/credentials.js +62 -0
- package/src/remote/ids.js +12 -0
- package/src/remote/login.js +155 -0
- package/src/remote/remote-mcp.js +237 -0
- package/src/remote/remote-watch.js +291 -0
- package/src/remote/remote.js +313 -0
- package/src/remote/share-state.js +78 -0
- package/src/remote/share.js +369 -0
- package/src/remote/terminal.js +13 -0
- package/src/serve-state.js +64 -0
- package/src/server/app.js +824 -0
- package/src/server/devices.js +186 -0
- package/src/server/local-console.js +28 -0
- package/src/server/local-user.js +59 -0
- package/src/server/pairing-routes.js +159 -0
- package/src/server/share-routes.js +89 -0
- package/src/server/tailscale.js +97 -0
- package/src/sitemap.js +431 -0
- package/src/store.js +983 -0
- package/src/tokens.js +11 -0
- package/src/update/routes.js +245 -0
- package/src/watch.js +403 -0
- package/src/which.js +58 -0
package/src/store.js
ADDED
|
@@ -0,0 +1,983 @@
|
|
|
1
|
+
// Everything Shapewall keeps lives under the output directory (default
|
|
2
|
+
// .shapewall/), as plain files:
|
|
3
|
+
//
|
|
4
|
+
// <out>/<board>/captures/<page>.<viewport>.png full frame
|
|
5
|
+
// <out>/<board>/captures/<page>.<viewport>.thumb.png thumbnail for zoomed-out views
|
|
6
|
+
// <out>/<board>/captures/<page>.<viewport>.html sanitized live HTML
|
|
7
|
+
// <out>/<board>/captures/manifest.json what was captured, when, errors
|
|
8
|
+
// <out>/<board>/variants/ + variants.json alternative versions of pages
|
|
9
|
+
// <out>/<board>/versions/<page>.<viewport>.<version>.* previous captures (newest N)
|
|
10
|
+
// <out>/<board>/envs/<env>/captures/ captures of other environments
|
|
11
|
+
// <out>/<board>/diffs/<a>_<b>/ cached pixel diffs between environments
|
|
12
|
+
// <out>/<board>/journeys.json journeys made on the board
|
|
13
|
+
// <out>/<board>/comments.json comments (written atomically)
|
|
14
|
+
// <out>/<board>/capture.lock | status.json | capture.log
|
|
15
|
+
// <out>/<board>/watch.lock | agent/ `shapewall watch` (one per board)
|
|
16
|
+
// <out>/events.jsonl (+ events.1.jsonl) comment events from every process (src/event-log.js)
|
|
17
|
+
// <out>/notifier.json which `shapewall serve` sends notifications
|
|
18
|
+
//
|
|
19
|
+
// JSON files are replaced atomically (write a temp file, fsync, rename), and
|
|
20
|
+
// read-modify-write runs under a short file lock, so the server and the CLI
|
|
21
|
+
// can both change comments safely.
|
|
22
|
+
|
|
23
|
+
import fs from 'node:fs'
|
|
24
|
+
import path from 'node:path'
|
|
25
|
+
import { randomBytes } from 'node:crypto'
|
|
26
|
+
import { cleanNetworkSummary } from './capture/network-summary.js'
|
|
27
|
+
import { ID_RE, VIEWPORT_NAMES, boardViewports } from './config.js'
|
|
28
|
+
import { isLockLive, readLock, withFileLock } from './lock.js'
|
|
29
|
+
import { commentMentions } from './mentions.js'
|
|
30
|
+
import { publicReactions, toggleReaction } from './reactions.js'
|
|
31
|
+
import { createdEvents, emitCommentEvents, replyEvents, updateEvents } from './events.js'
|
|
32
|
+
import { appendEvents } from './event-log.js'
|
|
33
|
+
import {
|
|
34
|
+
ANCHOR_SELECTOR_MAX,
|
|
35
|
+
ANCHOR_SELECTOR_RE,
|
|
36
|
+
ANCHOR_TEXT_MAX,
|
|
37
|
+
COMMENT_BODY_MAX,
|
|
38
|
+
CommentError,
|
|
39
|
+
FIX_REF_MAX,
|
|
40
|
+
cleanFixRef,
|
|
41
|
+
validateAnchor,
|
|
42
|
+
} from './comment-fields.js'
|
|
43
|
+
|
|
44
|
+
// A comment's pure field rules live in comment-fields.js (the demo's
|
|
45
|
+
// in-browser backend uses them too); re-exported for everyone else.
|
|
46
|
+
export {
|
|
47
|
+
ANCHOR_SELECTOR_MAX,
|
|
48
|
+
ANCHOR_SELECTOR_RE,
|
|
49
|
+
ANCHOR_TEXT_MAX,
|
|
50
|
+
COMMENT_BODY_MAX,
|
|
51
|
+
CommentError,
|
|
52
|
+
FIX_REF_MAX,
|
|
53
|
+
cleanFixRef,
|
|
54
|
+
validateAnchor,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const AUTHOR_MAX = 60
|
|
58
|
+
const COMMENTS_MAX = 5000
|
|
59
|
+
|
|
60
|
+
// The only capture file names ever served. Ids share ID_RE, so a name can
|
|
61
|
+
// never contain a slash, a dot segment or a NUL. .elements.json is the live
|
|
62
|
+
// HTML's element map (src/capture/element-map.js).
|
|
63
|
+
// Viewport names follow VIEWPORT_NAME_RE (no dots), so the parts never run together.
|
|
64
|
+
export const CAPTURE_FILE_RE = /^[a-z0-9][a-z0-9-]{0,63}\.([a-z][a-z0-9-]{0,31})(\.thumb\.png|\.png|\.html|\.elements\.json)$/
|
|
65
|
+
// A capture version: when the shot was taken, plus a short random suffix.
|
|
66
|
+
export const VERSION_RE = /^\d{8}T\d{9}Z(?:-[a-f0-9]{4})?$/
|
|
67
|
+
// Previous captures: <page>.<viewport>.<version>.png|.thumb.png|.html
|
|
68
|
+
export const VERSION_FILE_RE =
|
|
69
|
+
/^([a-z0-9][a-z0-9-]{0,63})\.([a-z][a-z0-9-]{0,31})\.(\d{8}T\d{9}Z(?:-[a-f0-9]{4})?)(\.thumb\.png|\.png|\.html)$/
|
|
70
|
+
// Pixel diffs between two environments: <page>.<viewport>.png
|
|
71
|
+
const DIFF_FILE_RE = /^[a-z0-9][a-z0-9-]{0,63}\.([a-z][a-z0-9-]{0,31})\.png$/
|
|
72
|
+
// An environment pair, "<a>_<b>" ('_' is never part of an id).
|
|
73
|
+
export const PAIR_RE = /^([a-z0-9][a-z0-9-]{0,63})_([a-z0-9][a-z0-9-]{0,63})$/
|
|
74
|
+
|
|
75
|
+
export function boardDir(config, boardId) {
|
|
76
|
+
if (!ID_RE.test(boardId)) throw new Error(`invalid board id ${boardId}`)
|
|
77
|
+
return path.join(config.outputDir, boardId)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function readJson(file) {
|
|
81
|
+
try {
|
|
82
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
83
|
+
} catch {
|
|
84
|
+
return null
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function writeFileAtomic(file, data) {
|
|
89
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
90
|
+
const temp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`
|
|
91
|
+
const fd = fs.openSync(temp, 'w', 0o644)
|
|
92
|
+
try {
|
|
93
|
+
try {
|
|
94
|
+
fs.writeSync(fd, data)
|
|
95
|
+
fs.fsyncSync(fd)
|
|
96
|
+
} finally {
|
|
97
|
+
fs.closeSync(fd)
|
|
98
|
+
}
|
|
99
|
+
fs.renameSync(temp, file)
|
|
100
|
+
} catch (error) {
|
|
101
|
+
// A full disk or a failed rename leaves no temporary file behind.
|
|
102
|
+
fs.rmSync(temp, { force: true })
|
|
103
|
+
throw error
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function writeJsonAtomic(file, value) {
|
|
108
|
+
writeFileAtomic(file, `${JSON.stringify(value, null, 2)}\n`)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ---- Captures -----------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
// The names in a directory, read once (empty when it is missing), so a
|
|
114
|
+
// board's file sets cost one readdir instead of a stat per file.
|
|
115
|
+
function dirNames(dir) {
|
|
116
|
+
try {
|
|
117
|
+
return new Set(fs.readdirSync(dir))
|
|
118
|
+
} catch {
|
|
119
|
+
return new Set()
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function fileSet(names, name, viewports) {
|
|
124
|
+
const files = {}
|
|
125
|
+
for (const viewport of viewports) {
|
|
126
|
+
const png = `${name}.${viewport}.png`
|
|
127
|
+
if (!names.has(png)) continue
|
|
128
|
+
const thumb = `${name}.${viewport}.thumb.png`
|
|
129
|
+
const live = `${name}.${viewport}.html`
|
|
130
|
+
files[viewport] = {
|
|
131
|
+
file: png,
|
|
132
|
+
thumb: names.has(thumb) ? thumb : null,
|
|
133
|
+
live: names.has(live) ? live : null,
|
|
134
|
+
}
|
|
135
|
+
// Only beside its live HTML; captures made before maps have none.
|
|
136
|
+
const elements = live.replace(/\.html$/, '.elements.json')
|
|
137
|
+
if (files[viewport].live && names.has(elements)) files[viewport].elements = elements
|
|
138
|
+
}
|
|
139
|
+
return files
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// The default environment's captures live in captures/ (as they always have);
|
|
143
|
+
// other environments in envs/<env>/captures/.
|
|
144
|
+
export function capturesDir(config, boardId, envId = null) {
|
|
145
|
+
const dir = boardDir(config, boardId)
|
|
146
|
+
if (!envId || isDefaultEnv(config, boardId, envId)) return path.join(dir, 'captures')
|
|
147
|
+
if (!ID_RE.test(envId)) throw new Error(`invalid environment id ${envId}`)
|
|
148
|
+
return path.join(dir, 'envs', envId, 'captures')
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function isDefaultEnv(config, boardId, envId) {
|
|
152
|
+
const board = config.boards.find((item) => item.id === boardId)
|
|
153
|
+
return !board?.environments?.length || board.environments[0].id === envId
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function readManifest(config, boardId, envId = null) {
|
|
157
|
+
const raw = readJson(path.join(capturesDir(config, boardId, envId), 'manifest.json'))
|
|
158
|
+
if (!raw || typeof raw !== 'object') return null
|
|
159
|
+
// Only bounded aggregate observations may leave the capture store.
|
|
160
|
+
for (const viewports of Object.values(raw.pages || {})) {
|
|
161
|
+
if (!viewports || typeof viewports !== 'object') continue
|
|
162
|
+
for (const entry of Object.values(viewports)) {
|
|
163
|
+
if (!entry || typeof entry !== 'object' || !Object.hasOwn(entry, 'networkSummary')) continue
|
|
164
|
+
const summary = cleanNetworkSummary(entry.networkSummary)
|
|
165
|
+
if (summary) entry.networkSummary = summary
|
|
166
|
+
else delete entry.networkSummary
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return raw
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Page -> viewport -> error ("HTTP 404") for the shots of the last capture
|
|
173
|
+
// of an environment that failed. Empty when nothing failed.
|
|
174
|
+
export function captureFailures(config, board, envId = null) {
|
|
175
|
+
const manifest = readManifest(config, board.id, envId)
|
|
176
|
+
const out = {}
|
|
177
|
+
for (const page of board.pages) {
|
|
178
|
+
const entry = manifest?.pages?.[page.id]
|
|
179
|
+
if (!entry || typeof entry !== 'object') continue
|
|
180
|
+
for (const [viewport, shot] of Object.entries(entry)) {
|
|
181
|
+
if (shot?.status !== 'failed') continue
|
|
182
|
+
out[page.id] = { ...out[page.id], [viewport]: String(shot.error || 'failed').slice(0, 300) }
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return out
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function captureFiles(config, board, envId = null) {
|
|
189
|
+
const dir = capturesDir(config, board.id, envId)
|
|
190
|
+
if (!fs.existsSync(dir)) return {}
|
|
191
|
+
const names = dirNames(dir)
|
|
192
|
+
return Object.fromEntries(board.pages.map((page) => [page.id, fileSet(names, page.id, page.viewports)]))
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Absolute path of a file Shapewall wrote, or null when the name is not one
|
|
196
|
+
// it writes or the file does not exist. Kinds: captures, variants, versions,
|
|
197
|
+
// env:<id> (another environment's captures), diff:<a>_<b> (pixel diffs).
|
|
198
|
+
export function resolveFile(config, boardId, kind, name) {
|
|
199
|
+
const value = String(name || '')
|
|
200
|
+
const board = config.boards.find((item) => item.id === boardId)
|
|
201
|
+
let dir
|
|
202
|
+
if (kind === 'captures' || kind === 'variants') {
|
|
203
|
+
if (!CAPTURE_FILE_RE.test(value)) return null
|
|
204
|
+
dir = path.join(boardDir(config, boardId), kind)
|
|
205
|
+
} else if (kind === 'versions') {
|
|
206
|
+
if (!VERSION_FILE_RE.test(value)) return null
|
|
207
|
+
dir = versionsDir(config, boardId)
|
|
208
|
+
} else if (typeof kind === 'string' && kind.startsWith('env:')) {
|
|
209
|
+
const envId = kind.slice(4)
|
|
210
|
+
if (!CAPTURE_FILE_RE.test(value) || !board?.environments.some((env) => env.id === envId)) return null
|
|
211
|
+
dir = capturesDir(config, boardId, envId)
|
|
212
|
+
} else if (typeof kind === 'string' && kind.startsWith('diff:')) {
|
|
213
|
+
const pair = PAIR_RE.exec(kind.slice(5))
|
|
214
|
+
const envIds = new Set(board?.environments.map((env) => env.id))
|
|
215
|
+
if (!DIFF_FILE_RE.test(value) || !pair || !envIds.has(pair[1]) || !envIds.has(pair[2])) return null
|
|
216
|
+
dir = diffsDir(config, boardId, pair[1], pair[2])
|
|
217
|
+
} else {
|
|
218
|
+
return null
|
|
219
|
+
}
|
|
220
|
+
const file = path.join(dir, value)
|
|
221
|
+
if (path.dirname(file) !== dir) return null
|
|
222
|
+
return fs.existsSync(file) ? file : null
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function diffsDir(config, boardId, a, b) {
|
|
226
|
+
if (!ID_RE.test(a) || !ID_RE.test(b)) throw new Error('invalid environment id')
|
|
227
|
+
return path.join(boardDir(config, boardId), 'diffs', `${a}_${b}`)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// ---- Capture versions -------------------------------------------------------------
|
|
231
|
+
// When a page is captured again, the previous shot (PNG, thumbnail, live
|
|
232
|
+
// HTML) moves to versions/, named by its version id. The newest
|
|
233
|
+
// `config.versions` per page and viewport are kept.
|
|
234
|
+
|
|
235
|
+
export function versionsDir(config, boardId) {
|
|
236
|
+
return path.join(boardDir(config, boardId), 'versions')
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// A sortable id for a shot taken at `date`.
|
|
240
|
+
export function versionId(date = new Date(), suffix = randomBytes(2).toString('hex')) {
|
|
241
|
+
const stamp = date
|
|
242
|
+
.toISOString()
|
|
243
|
+
.replace(/[-:]/g, '')
|
|
244
|
+
.replace(/\.(\d{3})Z$/, '$1Z')
|
|
245
|
+
return suffix ? `${stamp}-${suffix}` : stamp
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// The version of a manifest entry. Captures made before versions existed use
|
|
249
|
+
// the run's time.
|
|
250
|
+
export function entryVersion(entry, manifest) {
|
|
251
|
+
if (entry?.status !== 'ok') return null
|
|
252
|
+
if (typeof entry.version === 'string' && VERSION_RE.test(entry.version)) return entry.version
|
|
253
|
+
const time = Date.parse(manifest?.capturedAt || '')
|
|
254
|
+
return Number.isFinite(time) ? versionId(new Date(time), '') : null
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// The version currently shown for a page and viewport (default environment).
|
|
258
|
+
export function currentVersion(config, boardId, pageId, viewport) {
|
|
259
|
+
const manifest = readManifest(config, boardId)
|
|
260
|
+
return entryVersion(manifest?.pages?.[pageId]?.[viewport], manifest)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const VERSION_SUFFIXES = ['png', 'thumb.png', 'html']
|
|
264
|
+
|
|
265
|
+
// Copies the shot <page>.<viewport>.* in `fromDir` into versions/ as
|
|
266
|
+
// `version`. Returns the files written (to undo a failed recapture).
|
|
267
|
+
export function archiveVersion(config, boardId, { fromDir, pageId, viewport, version }) {
|
|
268
|
+
if (!VERSION_RE.test(String(version || '')) || !ID_RE.test(pageId)) return []
|
|
269
|
+
const png = path.join(fromDir, `${pageId}.${viewport}.png`)
|
|
270
|
+
if (!fs.existsSync(png)) return []
|
|
271
|
+
const dir = versionsDir(config, boardId)
|
|
272
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
273
|
+
const written = []
|
|
274
|
+
for (const suffix of VERSION_SUFFIXES) {
|
|
275
|
+
const source = path.join(fromDir, `${pageId}.${viewport}.${suffix}`)
|
|
276
|
+
if (!fs.existsSync(source)) continue
|
|
277
|
+
const target = path.join(dir, `${pageId}.${viewport}.${version}.${suffix}`)
|
|
278
|
+
fs.copyFileSync(source, target)
|
|
279
|
+
written.push(target)
|
|
280
|
+
}
|
|
281
|
+
return written
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Archived versions per page and viewport, newest first:
|
|
285
|
+
// { [pageId]: { [viewport]: [{ version, file, thumb, live }] } }
|
|
286
|
+
export function listVersions(config, boardId) {
|
|
287
|
+
const dir = versionsDir(config, boardId)
|
|
288
|
+
let names
|
|
289
|
+
try {
|
|
290
|
+
names = fs.readdirSync(dir)
|
|
291
|
+
} catch {
|
|
292
|
+
return {}
|
|
293
|
+
}
|
|
294
|
+
const found = {}
|
|
295
|
+
for (const name of names) {
|
|
296
|
+
const match = VERSION_FILE_RE.exec(name)
|
|
297
|
+
if (!match) continue
|
|
298
|
+
const [, pageId, viewport, version, suffix] = match
|
|
299
|
+
found[pageId] ||= {}
|
|
300
|
+
found[pageId][viewport] ||= {}
|
|
301
|
+
const item = (found[pageId][viewport][version] ||= { version, file: null, thumb: null, live: null })
|
|
302
|
+
if (suffix === '.png') item.file = name
|
|
303
|
+
else if (suffix === '.thumb.png') item.thumb = name
|
|
304
|
+
else item.live = name
|
|
305
|
+
}
|
|
306
|
+
const out = {}
|
|
307
|
+
for (const [pageId, viewports] of Object.entries(found)) {
|
|
308
|
+
out[pageId] = {}
|
|
309
|
+
for (const [viewport, byVersion] of Object.entries(viewports)) {
|
|
310
|
+
out[pageId][viewport] = Object.values(byVersion)
|
|
311
|
+
.filter((item) => item.file)
|
|
312
|
+
.sort((a, b) => (a.version < b.version ? 1 : -1))
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return out
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Keeps the newest `keep` versions of each page and viewport; removes the rest.
|
|
319
|
+
export function pruneVersions(config, boardId, keep = config.versions) {
|
|
320
|
+
const dir = versionsDir(config, boardId)
|
|
321
|
+
let removed = 0
|
|
322
|
+
for (const viewports of Object.values(listVersions(config, boardId))) {
|
|
323
|
+
for (const list of Object.values(viewports)) {
|
|
324
|
+
for (const item of list.slice(Math.max(0, keep))) {
|
|
325
|
+
for (const name of [item.file, item.thumb, item.live]) if (name) fs.rmSync(path.join(dir, name), { force: true })
|
|
326
|
+
removed += 1
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
return removed
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// ---- Capture state ------------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
export function readCaptureState(config, boardId) {
|
|
336
|
+
const dir = boardDir(config, boardId)
|
|
337
|
+
const running = isLockLive(readLock(path.join(dir, 'capture.lock')))
|
|
338
|
+
const status = readJson(path.join(dir, 'status.json')) || {}
|
|
339
|
+
let state = ['running', 'done', 'failed'].includes(status.state) ? status.state : 'idle'
|
|
340
|
+
if (state === 'running' && !running) state = 'failed'
|
|
341
|
+
return {
|
|
342
|
+
running,
|
|
343
|
+
state: running ? 'running' : state,
|
|
344
|
+
startedAt: typeof status.startedAt === 'string' ? status.startedAt : null,
|
|
345
|
+
finishedAt: typeof status.finishedAt === 'string' ? status.finishedAt : null,
|
|
346
|
+
done: Number.isFinite(status.done) ? status.done : null,
|
|
347
|
+
total: Number.isFinite(status.total) ? status.total : null,
|
|
348
|
+
failed: Number.isFinite(status.failed) ? status.failed : null,
|
|
349
|
+
error:
|
|
350
|
+
typeof status.error === 'string'
|
|
351
|
+
? status.error.slice(0, 300)
|
|
352
|
+
: state === 'failed' && status.state === 'running'
|
|
353
|
+
? 'The capture stopped before it finished.'
|
|
354
|
+
: null,
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// ---- Variants -------------------------------------------------------------------
|
|
359
|
+
|
|
360
|
+
function cleanVariant(entry) {
|
|
361
|
+
if (!entry || typeof entry !== 'object' || !ID_RE.test(String(entry.id || '')) || !ID_RE.test(String(entry.pageId || ''))) return null
|
|
362
|
+
const text = (value, max) => (typeof value === 'string' ? value.trim().slice(0, max) : '')
|
|
363
|
+
return {
|
|
364
|
+
id: entry.id,
|
|
365
|
+
pageId: entry.pageId,
|
|
366
|
+
title: text(entry.title, 120) || entry.id,
|
|
367
|
+
note: text(entry.note, 1000),
|
|
368
|
+
source: text(entry.source, 500),
|
|
369
|
+
createdAt: typeof entry.createdAt === 'string' ? entry.createdAt : null,
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export function variantsFile(config, boardId) {
|
|
374
|
+
return path.join(boardDir(config, boardId), 'variants.json')
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export function readVariants(config, boardId) {
|
|
378
|
+
const raw = readJsonStrict(variantsFile(config, boardId))
|
|
379
|
+
return (Array.isArray(raw?.variants) ? raw.variants : []).map(cleanVariant).filter(Boolean)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
export function variantsWithFiles(config, board) {
|
|
383
|
+
const dir = path.join(boardDir(config, board.id), 'variants')
|
|
384
|
+
const pages = new Map(board.pages.map((page) => [page.id, page]))
|
|
385
|
+
const variants = readVariants(config, board.id).filter((variant) => pages.has(variant.pageId))
|
|
386
|
+
const names = variants.length ? dirNames(dir) : new Set()
|
|
387
|
+
const viewports = [...new Set([...VIEWPORT_NAMES, ...Object.keys(boardViewports(config, board))])]
|
|
388
|
+
return variants.map((variant) => ({ ...variant, files: fileSet(names, variant.id, viewports) }))
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export async function saveVariant(config, boardId, variant) {
|
|
392
|
+
const file = variantsFile(config, boardId)
|
|
393
|
+
return withFileLock(file, () => {
|
|
394
|
+
const list = readVariants(config, boardId).filter((item) => item.id !== variant.id)
|
|
395
|
+
const clean = cleanVariant(variant)
|
|
396
|
+
if (!clean) throw new Error('invalid variant')
|
|
397
|
+
list.push(clean)
|
|
398
|
+
writeJsonAtomic(file, { variants: list })
|
|
399
|
+
return clean
|
|
400
|
+
})
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export async function removeVariant(config, boardId, variantId) {
|
|
404
|
+
const file = variantsFile(config, boardId)
|
|
405
|
+
return withFileLock(file, () => {
|
|
406
|
+
const list = readVariants(config, boardId)
|
|
407
|
+
const kept = list.filter((item) => item.id !== variantId)
|
|
408
|
+
if (kept.length === list.length) return false
|
|
409
|
+
writeJsonAtomic(file, { variants: kept })
|
|
410
|
+
const dir = path.join(boardDir(config, boardId), 'variants')
|
|
411
|
+
const board = config.boards?.find((item) => item.id === boardId)
|
|
412
|
+
for (const viewport of new Set([...VIEWPORT_NAMES, ...Object.keys(boardViewports(config, board) || {})])) {
|
|
413
|
+
for (const suffix of ['png', 'thumb.png', 'html']) fs.rmSync(path.join(dir, `${variantId}.${viewport}.${suffix}`), { force: true })
|
|
414
|
+
}
|
|
415
|
+
return true
|
|
416
|
+
})
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// ---- Comments -------------------------------------------------------------------
|
|
420
|
+
|
|
421
|
+
// The bridge freezes comments under their existing write lock. Captures and
|
|
422
|
+
// journeys stay writable. A host may explicitly keep the local copy independent.
|
|
423
|
+
export function readMigration(config, boardId) {
|
|
424
|
+
const marker = readJson(path.join(boardDir(config, boardId), 'migrated.json'))
|
|
425
|
+
if (!marker || typeof marker !== 'object' || Array.isArray(marker)) return null
|
|
426
|
+
let url = null
|
|
427
|
+
try {
|
|
428
|
+
const parsed = new URL(marker.url)
|
|
429
|
+
if (['https:', 'http:'].includes(parsed.protocol) && !parsed.username && !parsed.password) url = parsed.href
|
|
430
|
+
} catch {
|
|
431
|
+
/* A pending import has no destination yet. */
|
|
432
|
+
}
|
|
433
|
+
if (!url && marker.pending !== true) return null
|
|
434
|
+
return {
|
|
435
|
+
url,
|
|
436
|
+
readOnly: marker.readOnly === true,
|
|
437
|
+
pending: marker.pending === true,
|
|
438
|
+
previousReadOnly: marker.previousReadOnly === true,
|
|
439
|
+
...(typeof marker.migratedAt === 'string' ? { migratedAt: marker.migratedAt } : {}),
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
export async function writeMigration(config, boardId, marker, { beforeWrite = () => {} } = {}) {
|
|
443
|
+
await withFileLock(commentsFile(config, boardId), async () => {
|
|
444
|
+
beforeWrite()
|
|
445
|
+
writeJsonAtomic(path.join(boardDir(config, boardId), 'migrated.json'), marker)
|
|
446
|
+
})
|
|
447
|
+
}
|
|
448
|
+
function assertLocalComments(config, boardId) {
|
|
449
|
+
if (readMigration(config, boardId)?.readOnly)
|
|
450
|
+
throw new CommentError(
|
|
451
|
+
403,
|
|
452
|
+
'comments_moved',
|
|
453
|
+
'Comments for this board moved to the shared board. Choose Keep commenting here on the host to edit this independent local copy.',
|
|
454
|
+
)
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
export function commentsFile(config, boardId) {
|
|
458
|
+
return path.join(boardDir(config, boardId), 'comments.json')
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// Like readJson, but a file that exists and does not parse is an error, so a
|
|
462
|
+
// hand-edited comments.json with a typo is never overwritten with an empty list.
|
|
463
|
+
function readJsonStrict(file) {
|
|
464
|
+
let text
|
|
465
|
+
try {
|
|
466
|
+
text = fs.readFileSync(file, 'utf8')
|
|
467
|
+
} catch (error) {
|
|
468
|
+
if (error.code === 'ENOENT') return null
|
|
469
|
+
throw error
|
|
470
|
+
}
|
|
471
|
+
try {
|
|
472
|
+
return JSON.parse(text)
|
|
473
|
+
} catch (error) {
|
|
474
|
+
throw new CommentError(
|
|
475
|
+
500,
|
|
476
|
+
'corrupt_file',
|
|
477
|
+
`${path.basename(file)} is not valid JSON (${error.message}); fix or move it, nothing was written.`,
|
|
478
|
+
{ cause: error },
|
|
479
|
+
)
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function readCommentStore(config, boardId) {
|
|
484
|
+
const raw = readJsonStrict(commentsFile(config, boardId))
|
|
485
|
+
const comments = Array.isArray(raw?.comments) ? raw.comments.filter((item) => item && Number.isSafeInteger(item.id)) : []
|
|
486
|
+
const nextId = Math.max(Number(raw?.nextId) || 1, ...comments.map((item) => item.id + 1))
|
|
487
|
+
return { nextId, comments }
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// Comments written before replies and agent status existed read as having
|
|
491
|
+
// none, so every reader sees the same shape.
|
|
492
|
+
// The same goes for the reopen count; mentions are read from the text.
|
|
493
|
+
// Reactions read as { emoji, count, by } on the comment and each reply.
|
|
494
|
+
function withAgentFields(comment) {
|
|
495
|
+
const replies = (Array.isArray(comment.replies) ? comment.replies : []).map((reply) => ({
|
|
496
|
+
...reply,
|
|
497
|
+
reactions: publicReactions(reply.reactions),
|
|
498
|
+
}))
|
|
499
|
+
return {
|
|
500
|
+
...comment,
|
|
501
|
+
replies,
|
|
502
|
+
reactions: publicReactions(comment.reactions),
|
|
503
|
+
editedAt: typeof comment.editedAt === 'string' ? comment.editedAt : null,
|
|
504
|
+
agentStatus: AGENT_STATUSES.includes(comment.agentStatus) ? comment.agentStatus : null,
|
|
505
|
+
agentStatusAt: typeof comment.agentStatusAt === 'string' ? comment.agentStatusAt : null,
|
|
506
|
+
reopenCount: Number.isSafeInteger(comment.reopenCount) && comment.reopenCount > 0 ? comment.reopenCount : 0,
|
|
507
|
+
reopenedAt: typeof comment.reopenedAt === 'string' ? comment.reopenedAt : null,
|
|
508
|
+
mentions: commentMentions({ body: comment.body, replies }),
|
|
509
|
+
github: cleanGithub(comment.github),
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// `mention` keeps comments whose text or replies mention that handle.
|
|
514
|
+
export function listComments(config, boardId, { status = null, mention = null } = {}) {
|
|
515
|
+
const { comments } = readCommentStore(config, boardId)
|
|
516
|
+
const wanted = mention ? String(mention).replace(/^@/, '').toLowerCase() : null
|
|
517
|
+
return comments
|
|
518
|
+
.map(withAgentFields)
|
|
519
|
+
.filter((comment) => !status || comment.status === status)
|
|
520
|
+
.filter((comment) => !wanted || comment.mentions.includes(wanted))
|
|
521
|
+
.sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : b.id - a.id))
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
export function commentCounts(config, boardId) {
|
|
525
|
+
const counts = {}
|
|
526
|
+
for (const comment of readCommentStore(config, boardId).comments) {
|
|
527
|
+
counts[comment.pageId] = counts[comment.pageId] || { open: 0, resolved: 0 }
|
|
528
|
+
counts[comment.pageId][comment.status] = (counts[comment.pageId][comment.status] || 0) + 1
|
|
529
|
+
}
|
|
530
|
+
return counts
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function cleanBody(value) {
|
|
534
|
+
const body = typeof value === 'string' ? value.replace(/\r\n/g, '\n').trim() : ''
|
|
535
|
+
if (!body) throw new CommentError(400, 'empty_comment', 'Write something first.')
|
|
536
|
+
if (body.length > COMMENT_BODY_MAX)
|
|
537
|
+
throw new CommentError(400, 'comment_too_long', `Comments are limited to ${COMMENT_BODY_MAX} characters.`)
|
|
538
|
+
return body
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function cleanAuthor(value) {
|
|
542
|
+
const author = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, AUTHOR_MAX) : ''
|
|
543
|
+
return author || 'anonymous'
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// Validates a new comment against the board: the target is a page on it or
|
|
547
|
+
// one of its variants (`variant:<id>`), the viewport is one the target has,
|
|
548
|
+
// coordinates are percentages, and the body is plain text of bounded length.
|
|
549
|
+
export function validateCommentInput(config, board, input) {
|
|
550
|
+
const pageId = typeof input?.pageId === 'string' ? input.pageId.trim() : ''
|
|
551
|
+
const variantMatch = /^variant:([a-z0-9][a-z0-9-]{0,63})$/.exec(pageId)
|
|
552
|
+
const page = variantMatch ? null : board.pages.find((item) => item.id === pageId)
|
|
553
|
+
const variant = variantMatch ? readVariants(config, board.id).find((item) => item.id === variantMatch[1]) : null
|
|
554
|
+
if (!page && !variant) throw new CommentError(404, 'unknown_page', 'That page is not on this board.')
|
|
555
|
+
const viewport = input?.viewport
|
|
556
|
+
const allowed = page ? page.viewports : Object.keys(boardViewports(config, board))
|
|
557
|
+
if (!allowed.includes(viewport)) throw new CommentError(400, 'invalid_viewport', `Viewport must be one of ${allowed.join(', ')}.`)
|
|
558
|
+
const x = Number(input?.x)
|
|
559
|
+
const y = Number(input?.y)
|
|
560
|
+
if (
|
|
561
|
+
typeof input?.x !== 'number' ||
|
|
562
|
+
typeof input?.y !== 'number' ||
|
|
563
|
+
!Number.isFinite(x) ||
|
|
564
|
+
!Number.isFinite(y) ||
|
|
565
|
+
x < 0 ||
|
|
566
|
+
x > 100 ||
|
|
567
|
+
y < 0 ||
|
|
568
|
+
y > 100
|
|
569
|
+
) {
|
|
570
|
+
throw new CommentError(400, 'invalid_position', 'The pin must sit on the page (0 to 100 percent).')
|
|
571
|
+
}
|
|
572
|
+
return {
|
|
573
|
+
pageId,
|
|
574
|
+
viewport,
|
|
575
|
+
x: Math.round(x * 100) / 100,
|
|
576
|
+
y: Math.round(y * 100) / 100,
|
|
577
|
+
body: cleanBody(input?.body),
|
|
578
|
+
author: cleanAuthor(input?.author),
|
|
579
|
+
anchor: validateAnchor(input?.anchor),
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// Events go into the shared event log while the comments lock is still held
|
|
584
|
+
// (so the log has a board's changes in order); this process's listeners hear
|
|
585
|
+
// them once the lock is released.
|
|
586
|
+
async function logEvents(config, events) {
|
|
587
|
+
await appendEvents(config, events)
|
|
588
|
+
return events
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
export async function createComment(config, board, input, { now = new Date() } = {}) {
|
|
592
|
+
const clean = validateCommentInput(config, board, input)
|
|
593
|
+
const file = commentsFile(config, board.id)
|
|
594
|
+
let events = []
|
|
595
|
+
const saved = await withFileLock(file, async () => {
|
|
596
|
+
assertLocalComments(config, board.id)
|
|
597
|
+
const store = readCommentStore(config, board.id)
|
|
598
|
+
if (store.comments.length >= COMMENTS_MAX)
|
|
599
|
+
throw new CommentError(409, 'too_many_comments', `A board holds at most ${COMMENTS_MAX} comments.`)
|
|
600
|
+
const comment = {
|
|
601
|
+
id: store.nextId,
|
|
602
|
+
...clean,
|
|
603
|
+
// The capture the reviewer saw, for before/after once it is fixed.
|
|
604
|
+
captureVersion: clean.pageId.startsWith('variant:') ? null : currentVersion(config, board.id, clean.pageId, clean.viewport),
|
|
605
|
+
status: 'open',
|
|
606
|
+
createdAt: now.toISOString(),
|
|
607
|
+
updatedAt: now.toISOString(),
|
|
608
|
+
resolvedAt: null,
|
|
609
|
+
resolution: null,
|
|
610
|
+
replies: [],
|
|
611
|
+
agentStatus: null,
|
|
612
|
+
agentStatusAt: null,
|
|
613
|
+
}
|
|
614
|
+
if (!comment.anchor) delete comment.anchor
|
|
615
|
+
store.comments.push(comment)
|
|
616
|
+
writeJsonAtomic(file, { nextId: store.nextId + 1, comments: store.comments })
|
|
617
|
+
const result = withAgentFields(comment)
|
|
618
|
+
events = await logEvents(config, createdEvents(board.id, result, now))
|
|
619
|
+
return result
|
|
620
|
+
})
|
|
621
|
+
emitCommentEvents(events)
|
|
622
|
+
return saved
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// Changes a comment: { body } edits it, { status: 'open'|'resolved' } (with an
|
|
626
|
+
// optional resolution note) resolves or reopens it, { agentStatus } sets or
|
|
627
|
+
// (null) clears the agent status, { fixRef } records what fixed it (null
|
|
628
|
+
// clears it). Reopening clears the agent status too, so a reopened comment is
|
|
629
|
+
// new work for `shapewall watch`, and counts the reopen (reopenCount, reopenedAt).
|
|
630
|
+
// `actor` names who made the change in its events (null: nobody said).
|
|
631
|
+
export async function updateComment(config, boardId, commentId, changes, { now = new Date(), actor = null } = {}) {
|
|
632
|
+
const id = Number(commentId)
|
|
633
|
+
if (!Number.isSafeInteger(id) || id <= 0) throw new CommentError(404, 'unknown_comment', 'That comment does not exist.')
|
|
634
|
+
if (!changes || typeof changes !== 'object') throw new CommentError(400, 'invalid_change', 'Nothing to change.')
|
|
635
|
+
const body = changes.body !== undefined ? cleanBody(changes.body) : undefined
|
|
636
|
+
if (changes.status !== undefined && !['open', 'resolved'].includes(changes.status)) {
|
|
637
|
+
throw new CommentError(400, 'invalid_status', 'Status must be open or resolved.')
|
|
638
|
+
}
|
|
639
|
+
if (changes.resolution !== undefined && changes.resolution !== null && typeof changes.resolution !== 'string') {
|
|
640
|
+
throw new CommentError(400, 'invalid_resolution', 'The resolution note must be a string.')
|
|
641
|
+
}
|
|
642
|
+
const agentStatus = changes.agentStatus === undefined ? undefined : cleanAgentStatus(changes.agentStatus)
|
|
643
|
+
const fixRef = changes.fixRef === undefined ? undefined : cleanFixRef(changes.fixRef)
|
|
644
|
+
const file = commentsFile(config, boardId)
|
|
645
|
+
let events = []
|
|
646
|
+
const saved = await withFileLock(file, async () => {
|
|
647
|
+
assertLocalComments(config, boardId)
|
|
648
|
+
const store = readCommentStore(config, boardId)
|
|
649
|
+
const comment = store.comments.find((item) => item.id === id)
|
|
650
|
+
if (!comment) throw new CommentError(404, 'unknown_comment', 'That comment does not exist.')
|
|
651
|
+
const before = withAgentFields(structuredClone(comment))
|
|
652
|
+
if (body !== undefined && body !== comment.body) {
|
|
653
|
+
comment.body = body
|
|
654
|
+
// Shown as "edited" beside the time.
|
|
655
|
+
comment.editedAt = now.toISOString()
|
|
656
|
+
}
|
|
657
|
+
if (fixRef !== undefined) {
|
|
658
|
+
if (fixRef) comment.fixRef = fixRef
|
|
659
|
+
else delete comment.fixRef
|
|
660
|
+
}
|
|
661
|
+
if (changes.status !== undefined && changes.status !== comment.status) {
|
|
662
|
+
comment.status = changes.status
|
|
663
|
+
comment.resolvedAt = changes.status === 'resolved' ? now.toISOString() : null
|
|
664
|
+
if (changes.status === 'open') {
|
|
665
|
+
comment.resolution = null
|
|
666
|
+
// Reopened: kept, so the board can say so and people see it came back.
|
|
667
|
+
comment.reopenCount = (Number.isSafeInteger(comment.reopenCount) ? comment.reopenCount : 0) + 1
|
|
668
|
+
comment.reopenedAt = now.toISOString()
|
|
669
|
+
if (agentStatus === undefined) setAgent(comment, null, now)
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
if (agentStatus !== undefined) setAgent(comment, agentStatus, now)
|
|
673
|
+
if (typeof changes.resolution === 'string' && comment.status === 'resolved') {
|
|
674
|
+
comment.resolution = changes.resolution.trim().slice(0, COMMENT_BODY_MAX) || null
|
|
675
|
+
}
|
|
676
|
+
comment.updatedAt = now.toISOString()
|
|
677
|
+
writeJsonAtomic(file, { nextId: store.nextId, comments: store.comments })
|
|
678
|
+
const result = withAgentFields(comment)
|
|
679
|
+
events = await logEvents(config, updateEvents(boardId, before, result, now, cleanActor(actor)))
|
|
680
|
+
return result
|
|
681
|
+
})
|
|
682
|
+
emitCommentEvents(events)
|
|
683
|
+
return saved
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
export async function deleteComment(config, boardId, commentId) {
|
|
687
|
+
const id = Number(commentId)
|
|
688
|
+
const file = commentsFile(config, boardId)
|
|
689
|
+
return withFileLock(file, () => {
|
|
690
|
+
assertLocalComments(config, boardId)
|
|
691
|
+
const store = readCommentStore(config, boardId)
|
|
692
|
+
const kept = store.comments.filter((item) => item.id !== id)
|
|
693
|
+
if (kept.length === store.comments.length) throw new CommentError(404, 'unknown_comment', 'That comment does not exist.')
|
|
694
|
+
writeJsonAtomic(file, { nextId: store.nextId, comments: kept })
|
|
695
|
+
return true
|
|
696
|
+
})
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// ---- Replies and agent status ---------------------------------------------------
|
|
700
|
+
//
|
|
701
|
+
// A comment can carry a thread of replies ({ id, author, body, createdAt };
|
|
702
|
+
// an agent signs as "agent") and an agentStatus, the state of the work on
|
|
703
|
+
// it: queued (handed to an agent), working, done (the agent thinks it is
|
|
704
|
+
// fixed; a person still resolves) or needs-human (the agent stopped and
|
|
705
|
+
// asked). `shapewall watch` claims a comment by moving agentStatus from null
|
|
706
|
+
// to queued under the file lock, so two watchers never take the same one.
|
|
707
|
+
|
|
708
|
+
export const AGENT_STATUSES = ['queued', 'working', 'done', 'needs-human']
|
|
709
|
+
const REPLIES_MAX = 200
|
|
710
|
+
|
|
711
|
+
function cleanAgentStatus(value) {
|
|
712
|
+
if (value === null || AGENT_STATUSES.includes(value)) return value
|
|
713
|
+
throw new CommentError(400, 'invalid_agent_status', `Agent status must be one of ${AGENT_STATUSES.join(', ')} (or null to clear).`)
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function setAgent(comment, agentStatus, now) {
|
|
717
|
+
if ((comment.agentStatus ?? null) === agentStatus) return
|
|
718
|
+
comment.agentStatus = agentStatus
|
|
719
|
+
comment.agentStatusAt = agentStatus ? now.toISOString() : null
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
function parseCommentId(value) {
|
|
723
|
+
const id = typeof value === 'number' ? value : /^[1-9][0-9]{0,15}$/.test(String(value)) ? Number(value) : NaN
|
|
724
|
+
if (!Number.isSafeInteger(id) || id <= 0) throw new CommentError(404, 'unknown_comment', 'That comment does not exist.')
|
|
725
|
+
return id
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// Runs `change(comment)` on one comment under the file lock and saves it,
|
|
729
|
+
// unless `change` returns false (nothing to write). `eventsFor(comment,
|
|
730
|
+
// result)` lists the events of the change; they are logged under the lock and
|
|
731
|
+
// emitted after it.
|
|
732
|
+
async function changeComment(config, boardId, commentId, change, now, eventsFor = null) {
|
|
733
|
+
const id = parseCommentId(commentId)
|
|
734
|
+
const file = commentsFile(config, boardId)
|
|
735
|
+
let events = []
|
|
736
|
+
const outcome = await withFileLock(file, async () => {
|
|
737
|
+
assertLocalComments(config, boardId)
|
|
738
|
+
const store = readCommentStore(config, boardId)
|
|
739
|
+
const comment = store.comments.find((item) => item.id === id)
|
|
740
|
+
if (!comment) throw new CommentError(404, 'unknown_comment', 'That comment does not exist.')
|
|
741
|
+
const result = change(comment)
|
|
742
|
+
if (result === false) return { comment: withAgentFields(comment), changed: false, result }
|
|
743
|
+
comment.updatedAt = now.toISOString()
|
|
744
|
+
writeJsonAtomic(file, { nextId: store.nextId, comments: store.comments })
|
|
745
|
+
const saved = withAgentFields(comment)
|
|
746
|
+
if (eventsFor) events = await logEvents(config, eventsFor(saved, result))
|
|
747
|
+
return { comment: saved, changed: true, result }
|
|
748
|
+
})
|
|
749
|
+
emitCommentEvents(events)
|
|
750
|
+
return outcome
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
const cleanActor = (value) => (typeof value === 'string' && value.trim() ? cleanAuthor(value) : null)
|
|
754
|
+
|
|
755
|
+
export function getComment(config, boardId, commentId) {
|
|
756
|
+
const id = parseCommentId(commentId)
|
|
757
|
+
const comment = readCommentStore(config, boardId).comments.find((item) => item.id === id)
|
|
758
|
+
if (!comment) throw new CommentError(404, 'unknown_comment', 'That comment does not exist.')
|
|
759
|
+
return withAgentFields(comment)
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
// Adds a reply. Returns { comment, reply }.
|
|
763
|
+
export async function addReply(config, boardId, commentId, input, { now = new Date() } = {}) {
|
|
764
|
+
const body = cleanBody(input?.body)
|
|
765
|
+
const author = cleanAuthor(input?.author)
|
|
766
|
+
const { comment, result } = await changeComment(
|
|
767
|
+
config,
|
|
768
|
+
boardId,
|
|
769
|
+
commentId,
|
|
770
|
+
(target) => {
|
|
771
|
+
const replies = Array.isArray(target.replies) ? target.replies : []
|
|
772
|
+
if (replies.length >= REPLIES_MAX) throw new CommentError(409, 'too_many_replies', `A comment holds at most ${REPLIES_MAX} replies.`)
|
|
773
|
+
const reply = {
|
|
774
|
+
id: Math.max(0, ...replies.map((item) => Number(item.id) || 0)) + 1,
|
|
775
|
+
author,
|
|
776
|
+
body,
|
|
777
|
+
createdAt: now.toISOString(),
|
|
778
|
+
}
|
|
779
|
+
target.replies = [...replies, reply]
|
|
780
|
+
return reply
|
|
781
|
+
},
|
|
782
|
+
now,
|
|
783
|
+
(saved, reply) => replyEvents(boardId, saved, reply, now),
|
|
784
|
+
)
|
|
785
|
+
return { comment, reply: result }
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// Adds or takes away a person's emoji reaction on a comment (replyId null)
|
|
789
|
+
// or one of its replies. Returns { comment, added }. A reaction is not work
|
|
790
|
+
// on the comment: it keeps updatedAt and sends no events, so watchers,
|
|
791
|
+
// webhooks and notifications never see it.
|
|
792
|
+
export async function reactToComment(config, boardId, commentId, { emoji, replyId = null, author } = {}) {
|
|
793
|
+
const id = parseCommentId(commentId)
|
|
794
|
+
const file = commentsFile(config, boardId)
|
|
795
|
+
return withFileLock(file, () => {
|
|
796
|
+
assertLocalComments(config, boardId)
|
|
797
|
+
const store = readCommentStore(config, boardId)
|
|
798
|
+
const comment = store.comments.find((item) => item.id === id)
|
|
799
|
+
if (!comment) throw new CommentError(404, 'unknown_comment', 'That comment does not exist.')
|
|
800
|
+
let target = comment
|
|
801
|
+
if (replyId !== null && replyId !== undefined) {
|
|
802
|
+
const wanted = Number(replyId)
|
|
803
|
+
target = (Array.isArray(comment.replies) ? comment.replies : []).find((reply) => Number(reply.id) === wanted)
|
|
804
|
+
if (!target) throw new CommentError(404, 'unknown_reply', 'That reply does not exist.')
|
|
805
|
+
}
|
|
806
|
+
let result
|
|
807
|
+
try {
|
|
808
|
+
result = toggleReaction(target.reactions, emoji, { name: cleanAuthor(author) })
|
|
809
|
+
} catch (error) {
|
|
810
|
+
throw new CommentError(error.code === 'too_many_reactions' ? 409 : 400, error.code || 'invalid_reaction', error.message)
|
|
811
|
+
}
|
|
812
|
+
if (result.reactions.length) target.reactions = result.reactions
|
|
813
|
+
else delete target.reactions
|
|
814
|
+
writeJsonAtomic(file, { nextId: store.nextId, comments: store.comments })
|
|
815
|
+
return { comment: withAgentFields(comment), added: result.added }
|
|
816
|
+
})
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// Sets the agent status. With `onlyFrom` (a list of current values, null
|
|
820
|
+
// meaning unset) the change is a compare-and-set: it happens only when the
|
|
821
|
+
// comment is open and its status is one of them. Returns { comment, changed }.
|
|
822
|
+
// `actor` names who made the change in its event.
|
|
823
|
+
export async function setAgentStatus(config, boardId, commentId, agentStatus, { onlyFrom = null, now = new Date(), actor = null } = {}) {
|
|
824
|
+
const next = cleanAgentStatus(agentStatus)
|
|
825
|
+
let previous = null
|
|
826
|
+
const { comment, changed } = await changeComment(
|
|
827
|
+
config,
|
|
828
|
+
boardId,
|
|
829
|
+
commentId,
|
|
830
|
+
(target) => {
|
|
831
|
+
const current = AGENT_STATUSES.includes(target.agentStatus) ? target.agentStatus : null
|
|
832
|
+
if (onlyFrom && (target.status !== 'open' || !onlyFrom.includes(current))) return false
|
|
833
|
+
if (current === next) return false
|
|
834
|
+
previous = current
|
|
835
|
+
setAgent(target, next, now)
|
|
836
|
+
},
|
|
837
|
+
now,
|
|
838
|
+
(saved) => updateEvents(boardId, { ...saved, agentStatus: previous }, saved, now, cleanActor(actor)),
|
|
839
|
+
)
|
|
840
|
+
return { comment, changed }
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
// ---- GitHub links -----------------------------------------------------------------
|
|
844
|
+
//
|
|
845
|
+
// A comment can point at the GitHub issue made from it and at the pull
|
|
846
|
+
// requests that work on it: github: { issue: { number, url, title, createdAt },
|
|
847
|
+
// pulls: [{ number, url, title, state, mergedAt, via, linkedAt, notedAt }] }.
|
|
848
|
+
// `state` is open, closed or merged; `via` is how the link was made (manual,
|
|
849
|
+
// body: a "shapewall:<id>" marker in the PR, issue: the PR closes the issue);
|
|
850
|
+
// `notedAt` is when a merge resolved the comment, so that happens once.
|
|
851
|
+
|
|
852
|
+
export const PULL_STATES = ['open', 'closed', 'merged']
|
|
853
|
+
const PULL_VIA = ['manual', 'body', 'issue']
|
|
854
|
+
const PULLS_MAX = 20
|
|
855
|
+
const GITHUB_URL_RE = /^https?:\/\/[^\s"<>]{1,300}$/
|
|
856
|
+
|
|
857
|
+
function cleanGithubText(value, max) {
|
|
858
|
+
return typeof value === 'string'
|
|
859
|
+
? value
|
|
860
|
+
// eslint-disable-next-line no-control-regex
|
|
861
|
+
.replace(/[\u0000-\u001f\u007f]+/g, ' ')
|
|
862
|
+
.trim()
|
|
863
|
+
.slice(0, max)
|
|
864
|
+
: ''
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function cleanIssue(issue) {
|
|
868
|
+
if (!issue || typeof issue !== 'object' || !Number.isSafeInteger(issue.number) || issue.number <= 0) return null
|
|
869
|
+
if (!GITHUB_URL_RE.test(String(issue.url || ''))) return null
|
|
870
|
+
return {
|
|
871
|
+
number: issue.number,
|
|
872
|
+
url: issue.url,
|
|
873
|
+
title: cleanGithubText(issue.title, 256),
|
|
874
|
+
createdAt: typeof issue.createdAt === 'string' ? issue.createdAt : null,
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
function cleanPull(pull) {
|
|
879
|
+
if (!pull || typeof pull !== 'object' || !Number.isSafeInteger(pull.number) || pull.number <= 0) return null
|
|
880
|
+
if (!GITHUB_URL_RE.test(String(pull.url || ''))) return null
|
|
881
|
+
return {
|
|
882
|
+
number: pull.number,
|
|
883
|
+
url: pull.url,
|
|
884
|
+
title: cleanGithubText(pull.title, 256),
|
|
885
|
+
state: PULL_STATES.includes(pull.state) ? pull.state : 'open',
|
|
886
|
+
mergedAt: typeof pull.mergedAt === 'string' ? pull.mergedAt : null,
|
|
887
|
+
via: PULL_VIA.includes(pull.via) ? pull.via : 'manual',
|
|
888
|
+
linkedAt: typeof pull.linkedAt === 'string' ? pull.linkedAt : null,
|
|
889
|
+
notedAt: typeof pull.notedAt === 'string' ? pull.notedAt : null,
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
export function cleanGithub(value) {
|
|
894
|
+
const issue = cleanIssue(value?.issue)
|
|
895
|
+
const pulls = (Array.isArray(value?.pulls) ? value.pulls : []).map(cleanPull).filter(Boolean).slice(0, PULLS_MAX)
|
|
896
|
+
return { issue, pulls }
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// Records the issue made from a comment. Returns the comment.
|
|
900
|
+
export async function setGithubIssue(config, boardId, commentId, issue, { now = new Date() } = {}) {
|
|
901
|
+
const clean = cleanIssue({ createdAt: now.toISOString(), ...issue })
|
|
902
|
+
if (!clean) throw new CommentError(400, 'invalid_issue', 'That is not a GitHub issue.')
|
|
903
|
+
const { comment } = await changeComment(
|
|
904
|
+
config,
|
|
905
|
+
boardId,
|
|
906
|
+
commentId,
|
|
907
|
+
(target) => {
|
|
908
|
+
target.github = { ...cleanGithub(target.github), issue: clean }
|
|
909
|
+
},
|
|
910
|
+
now,
|
|
911
|
+
)
|
|
912
|
+
return comment
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
// Links a pull request to a comment, or updates the link (title, state).
|
|
916
|
+
// When the pull request has merged and that was not noted yet, an open
|
|
917
|
+
// comment is resolved (the PR becomes its fix reference, so before/after
|
|
918
|
+
// shows it) and a reply from "github" says so. Returns { comment, changed,
|
|
919
|
+
// merged }; merged is true when this call noted the merge.
|
|
920
|
+
export async function recordGithubPull(config, boardId, commentId, pull, { via = 'manual', now = new Date() } = {}) {
|
|
921
|
+
const incoming = cleanPull({ ...pull, via })
|
|
922
|
+
if (!incoming) throw new CommentError(400, 'invalid_pull', 'That is not a GitHub pull request.')
|
|
923
|
+
const { comment, changed, result } = await changeComment(
|
|
924
|
+
config,
|
|
925
|
+
boardId,
|
|
926
|
+
commentId,
|
|
927
|
+
(target) => {
|
|
928
|
+
const github = cleanGithub(target.github)
|
|
929
|
+
const index = github.pulls.findIndex((item) => item.number === incoming.number)
|
|
930
|
+
const previous = index >= 0 ? github.pulls[index] : null
|
|
931
|
+
if (!previous && github.pulls.length >= PULLS_MAX) {
|
|
932
|
+
throw new CommentError(409, 'too_many_pulls', `A comment links at most ${PULLS_MAX} pull requests.`)
|
|
933
|
+
}
|
|
934
|
+
const next = {
|
|
935
|
+
...incoming,
|
|
936
|
+
// A link keeps how it was first made.
|
|
937
|
+
via: previous ? previous.via : incoming.via,
|
|
938
|
+
linkedAt: previous?.linkedAt || now.toISOString(),
|
|
939
|
+
notedAt: previous?.notedAt || null,
|
|
940
|
+
}
|
|
941
|
+
const merging = next.state === 'merged' && !next.notedAt
|
|
942
|
+
if (merging) next.notedAt = now.toISOString()
|
|
943
|
+
if (previous && JSON.stringify(previous) === JSON.stringify(next)) return false
|
|
944
|
+
if (index >= 0) github.pulls[index] = next
|
|
945
|
+
else github.pulls.push(next)
|
|
946
|
+
target.github = github
|
|
947
|
+
if (!merging) return { merged: false }
|
|
948
|
+
const label = `pull request #${next.number}${next.title ? ` (${next.title})` : ''}`
|
|
949
|
+
const before = withAgentFields({ ...target })
|
|
950
|
+
let reply = null
|
|
951
|
+
if (target.status === 'open') {
|
|
952
|
+
target.status = 'resolved'
|
|
953
|
+
target.resolvedAt = now.toISOString()
|
|
954
|
+
target.resolution = `Merged in ${label}.`.slice(0, COMMENT_BODY_MAX)
|
|
955
|
+
target.fixRef = next.url
|
|
956
|
+
} else if (!target.fixRef) {
|
|
957
|
+
target.fixRef = next.url
|
|
958
|
+
}
|
|
959
|
+
const replies = Array.isArray(target.replies) ? target.replies : []
|
|
960
|
+
if (replies.length < REPLIES_MAX) {
|
|
961
|
+
reply = {
|
|
962
|
+
id: Math.max(0, ...replies.map((item) => Number(item.id) || 0)) + 1,
|
|
963
|
+
author: 'github',
|
|
964
|
+
body: `Merged ${label}: ${next.url}`.slice(0, COMMENT_BODY_MAX),
|
|
965
|
+
createdAt: now.toISOString(),
|
|
966
|
+
}
|
|
967
|
+
target.replies = [...replies, reply]
|
|
968
|
+
}
|
|
969
|
+
return { merged: true, before, reply }
|
|
970
|
+
},
|
|
971
|
+
now,
|
|
972
|
+
// A merge resolves and replies like a person would, so it tells listeners (notifications) the same way.
|
|
973
|
+
(saved, outcome) =>
|
|
974
|
+
outcome?.merged
|
|
975
|
+
? [
|
|
976
|
+
...updateEvents(boardId, outcome.before, saved, now, 'github'),
|
|
977
|
+
...(outcome.reply ? replyEvents(boardId, saved, outcome.reply, now) : []),
|
|
978
|
+
]
|
|
979
|
+
: [],
|
|
980
|
+
)
|
|
981
|
+
const merged = Boolean(changed && result?.merged)
|
|
982
|
+
return { comment, changed, merged }
|
|
983
|
+
}
|