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.
Files changed (304) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/Dockerfile.agent +45 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +12 -0
  5. package/README.md +651 -2
  6. package/THIRD_PARTY.md +165 -0
  7. package/bin/shapewall.js +29 -0
  8. package/dist/agent/package-lock.json +8384 -0
  9. package/dist/client/assets/BoardChat-D5SFd8HE.js +28 -0
  10. package/dist/client/assets/BuzzDialog-HWXBy52W.js +1 -0
  11. package/dist/client/assets/ChecksPanel-DTdImWoD.js +1 -0
  12. package/dist/client/assets/History-CEv6b-av.js +1 -0
  13. package/dist/client/assets/LocalSettings-C4vriEVQ.js +1 -0
  14. package/dist/client/assets/Management-DCfhcEUY.js +1 -0
  15. package/dist/client/assets/QuickConnect-DQGgUsl1.js +1 -0
  16. package/dist/client/assets/ShareDialog-C_plIto0.js +2 -0
  17. package/dist/client/assets/app-update-dialog-2hPz_N9G.js +1 -0
  18. package/dist/client/assets/circle-x-BZMPi8Zf.js +1 -0
  19. package/dist/client/assets/index-ByQRKVit.css +2 -0
  20. package/dist/client/assets/index-DweQ8Qtu.js +29 -0
  21. package/dist/client/assets/refresh-cw-CRow0Nbq.js +1 -0
  22. package/dist/client/assets/runtime-Bft6x_6E.js +4 -0
  23. package/dist/client/assets/square-A8EnIYLR.js +1 -0
  24. package/dist/client/assets/tts-dist-DYlBQmwG.js +18 -0
  25. package/dist/client/assets/tts-en-g2p-BPUtBFGG.js +1 -0
  26. package/dist/client/assets/tts-ort-wasm-simd-threaded-qh98TCA_.wasm +0 -0
  27. package/dist/client/assets/tts-ort.wasm.bundle.min-rEkcs_ow.js +12 -0
  28. package/dist/client/assets/tts-rolldown-runtime-D8NudN84.js +1 -0
  29. package/dist/client/assets/tts-spacy-en-tokenizer-6SNMl--A.json +1 -0
  30. package/dist/client/assets/tts-tts.worker-Bzm6aWbv.js +1 -0
  31. package/dist/client/assets/tts-us_gold-DcjeNMH1.json +92589 -0
  32. package/dist/client/assets/tts-us_silver-C964mEB5.json +93363 -0
  33. package/dist/client/assets/ui-CLbws0rx.js +41 -0
  34. package/dist/client/build-info.json +1 -0
  35. package/dist/client/favicon.svg +7 -0
  36. package/dist/client/icons/apple-touch-icon.png +0 -0
  37. package/dist/client/icons/icon-192.png +0 -0
  38. package/dist/client/icons/icon-512.png +0 -0
  39. package/dist/client/icons/maskable-512.png +0 -0
  40. package/dist/client/index.html +25 -0
  41. package/dist/client/manifest.webmanifest +15 -0
  42. package/dist/client/sw.js +53 -0
  43. package/dist/client/theme-boot.js +27 -0
  44. package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +1 -0
  45. package/dist/console/assets/LocalConsole-Bb2FUDs7.js +1 -0
  46. package/dist/console/assets/app-update-dialog-DIeYepLZ.js +1 -0
  47. package/dist/console/assets/console-C7uJLLOn.js +51 -0
  48. package/dist/console/assets/console-R8IBY3Am.css +2 -0
  49. package/dist/console/build-info.json +1 -0
  50. package/dist/console/console.html +21 -0
  51. package/dist/console/favicon.svg +7 -0
  52. package/dist/console/icons/apple-touch-icon.png +0 -0
  53. package/dist/console/icons/icon-192.png +0 -0
  54. package/dist/console/icons/icon-512.png +0 -0
  55. package/dist/console/icons/maskable-512.png +0 -0
  56. package/dist/console/manifest.webmanifest +15 -0
  57. package/dist/console/theme-boot.js +27 -0
  58. package/docs/agent-hardening.md +342 -0
  59. package/docs/agent-recipes.md +187 -0
  60. package/docs/agent-workflow.md +320 -0
  61. package/docs/agents.md +894 -0
  62. package/docs/architecture.md +242 -0
  63. package/docs/buzz.md +140 -0
  64. package/docs/capture-warnings.md +57 -0
  65. package/docs/config.md +489 -0
  66. package/docs/deployment.md +289 -0
  67. package/docs/design-system.md +162 -0
  68. package/docs/github.md +107 -0
  69. package/docs/hosted.md +764 -0
  70. package/docs/images/board-overview.png +0 -0
  71. package/docs/images/journeys.png +0 -0
  72. package/docs/images/live-comment.png +0 -0
  73. package/docs/images/phone-comment.png +0 -0
  74. package/docs/images/phone-overview.png +0 -0
  75. package/docs/images/variant.png +0 -0
  76. package/docs/interaction-audits.md +40 -0
  77. package/docs/journeys.md +137 -0
  78. package/docs/local-accounts.md +80 -0
  79. package/docs/notifications.md +237 -0
  80. package/docs/page-checks.md +69 -0
  81. package/docs/performance.md +174 -0
  82. package/docs/starter-agent.md +325 -0
  83. package/docs/updates.md +87 -0
  84. package/examples/audits/interaction.audit.json +17 -0
  85. package/package.json +132 -4
  86. package/src/accounts/avatar.js +121 -0
  87. package/src/accounts/local.js +464 -0
  88. package/src/agent/acp/command.js +204 -0
  89. package/src/agent/acp/detect.js +75 -0
  90. package/src/agent/acp/sandbox.js +160 -0
  91. package/src/agent/agent-health.js +75 -0
  92. package/src/agent/backends/acp.js +1297 -0
  93. package/src/agent/backends/index.js +61 -0
  94. package/src/agent/backends/openai.js +308 -0
  95. package/src/agent/composer.js +221 -0
  96. package/src/agent/config.js +338 -0
  97. package/src/agent/context.js +191 -0
  98. package/src/agent/control.js +122 -0
  99. package/src/agent/errors.js +17 -0
  100. package/src/agent/feedback-loop.js +137 -0
  101. package/src/agent/manage.js +94 -0
  102. package/src/agent/next-steps.js +51 -0
  103. package/src/agent/owner-mcp.js +38 -0
  104. package/src/agent/plain-text.js +52 -0
  105. package/src/agent/ratings-core.js +213 -0
  106. package/src/agent/ratings.js +100 -0
  107. package/src/agent/reply-text.js +67 -0
  108. package/src/agent/routes.js +1065 -0
  109. package/src/agent/run.js +326 -0
  110. package/src/agent/settings-routes.js +704 -0
  111. package/src/agent/showable.js +23 -0
  112. package/src/agent/starter/approvals.js +181 -0
  113. package/src/agent/starter/build-image.js +90 -0
  114. package/src/agent/starter/cli.js +163 -0
  115. package/src/agent/starter/disk.js +53 -0
  116. package/src/agent/starter/doctor.js +180 -0
  117. package/src/agent/starter/egress-proxy.js +351 -0
  118. package/src/agent/starter/gate.js +90 -0
  119. package/src/agent/starter/loop.js +114 -0
  120. package/src/agent/starter/model-relay.js +289 -0
  121. package/src/agent/starter/pause.js +14 -0
  122. package/src/agent/starter/probe.js +272 -0
  123. package/src/agent/starter/prompt.js +41 -0
  124. package/src/agent/starter/push-guard.js +146 -0
  125. package/src/agent/starter/rpc.js +164 -0
  126. package/src/agent/starter/runtime.js +287 -0
  127. package/src/agent/starter/sandbox-main.js +121 -0
  128. package/src/agent/starter/settings.js +290 -0
  129. package/src/agent/starter/source.js +69 -0
  130. package/src/agent/starter/supervisor.js +755 -0
  131. package/src/agent/starter/sweep.js +46 -0
  132. package/src/agent/starter/tools.js +524 -0
  133. package/src/agent/starter/watch.js +84 -0
  134. package/src/agent/starter/worktree.js +409 -0
  135. package/src/agent/text-diff.js +210 -0
  136. package/src/agent/thread-history.js +223 -0
  137. package/src/agent/threads.js +399 -0
  138. package/src/agent/tools.js +200 -0
  139. package/src/agent/turn-changes.js +424 -0
  140. package/src/agent/undo-state.js +26 -0
  141. package/src/agent/user-settings.js +308 -0
  142. package/src/auth/record.js +375 -0
  143. package/src/broken-links.js +164 -0
  144. package/src/buzz/client.js +75 -0
  145. package/src/buzz/config.js +151 -0
  146. package/src/buzz/environment.js +13 -0
  147. package/src/buzz/gateway.js +192 -0
  148. package/src/buzz/routes.js +61 -0
  149. package/src/buzz/signer-child.js +205 -0
  150. package/src/buzz/store.js +89 -0
  151. package/src/buzz/transport.js +60 -0
  152. package/src/buzz/verify.js +140 -0
  153. package/src/capture/actions.js +159 -0
  154. package/src/capture/capture.js +776 -0
  155. package/src/capture/dom-names.js +189 -0
  156. package/src/capture/element-map.js +509 -0
  157. package/src/capture/live.js +827 -0
  158. package/src/capture/media-scheme.js +317 -0
  159. package/src/capture/network-summary.js +86 -0
  160. package/src/capture/pacing.js +34 -0
  161. package/src/capture/requests.js +167 -0
  162. package/src/capture/sanitize.js +752 -0
  163. package/src/checks/accessibility.js +134 -0
  164. package/src/checks/budgets.js +58 -0
  165. package/src/checks/cli.js +55 -0
  166. package/src/checks/comparison.js +113 -0
  167. package/src/checks/environments.js +32 -0
  168. package/src/checks/flow-config.js +82 -0
  169. package/src/checks/flow-origin.js +53 -0
  170. package/src/checks/flows.js +398 -0
  171. package/src/checks/lighthouse-auth.js +145 -0
  172. package/src/checks/lighthouse-findings.js +130 -0
  173. package/src/checks/lighthouse.js +395 -0
  174. package/src/checks/robots.js +85 -0
  175. package/src/checks/routes.js +52 -0
  176. package/src/checks/run-control.js +259 -0
  177. package/src/checks/runner.js +724 -0
  178. package/src/checks/schema.js +133 -0
  179. package/src/checks/seo-analysis.js +443 -0
  180. package/src/checks/seo-probe.js +190 -0
  181. package/src/checks/seo-snapshot.js +99 -0
  182. package/src/checks/store.js +214 -0
  183. package/src/checks/transport.js +47 -0
  184. package/src/cli/args.js +319 -0
  185. package/src/cli/capture.js +79 -0
  186. package/src/cli/commands.js +92 -0
  187. package/src/cli/comments.js +84 -0
  188. package/src/cli/help.js +243 -0
  189. package/src/cli/init.js +214 -0
  190. package/src/cli/misc.js +64 -0
  191. package/src/cli/notify.js +87 -0
  192. package/src/cli/open.js +22 -0
  193. package/src/cli/serve.js +274 -0
  194. package/src/cli/variant.js +82 -0
  195. package/src/cli/watch.js +70 -0
  196. package/src/cli.js +130 -0
  197. package/src/comment-fields.js +76 -0
  198. package/src/comments-cli.js +208 -0
  199. package/src/config-reload.js +100 -0
  200. package/src/config.js +1061 -0
  201. package/src/devices-cli.js +21 -0
  202. package/src/diff.js +95 -0
  203. package/src/discover.js +284 -0
  204. package/src/doctor.js +295 -0
  205. package/src/event-log.js +268 -0
  206. package/src/events-cli.js +102 -0
  207. package/src/events.js +113 -0
  208. package/src/export.js +119 -0
  209. package/src/feedback.js +246 -0
  210. package/src/github.js +551 -0
  211. package/src/hosted/LICENSE.md +105 -0
  212. package/src/hosted/access-cli.js +78 -0
  213. package/src/hosted/admin.js +682 -0
  214. package/src/hosted/agent-approvals.js +163 -0
  215. package/src/hosted/agent-policy.js +189 -0
  216. package/src/hosted/app.js +510 -0
  217. package/src/hosted/auth-routes.js +540 -0
  218. package/src/hosted/auth.js +536 -0
  219. package/src/hosted/backup.js +483 -0
  220. package/src/hosted/board-context.js +35 -0
  221. package/src/hosted/board-routes.js +486 -0
  222. package/src/hosted/board-view.js +94 -0
  223. package/src/hosted/clean-worker.js +24 -0
  224. package/src/hosted/cleaner.js +89 -0
  225. package/src/hosted/comments.js +355 -0
  226. package/src/hosted/console-routes.js +401 -0
  227. package/src/hosted/cookies.js +18 -0
  228. package/src/hosted/crypto.js +80 -0
  229. package/src/hosted/db.js +496 -0
  230. package/src/hosted/device-routes.js +175 -0
  231. package/src/hosted/device.js +233 -0
  232. package/src/hosted/events.js +63 -0
  233. package/src/hosted/guards.js +172 -0
  234. package/src/hosted/guest-view.js +65 -0
  235. package/src/hosted/http.js +39 -0
  236. package/src/hosted/import.js +300 -0
  237. package/src/hosted/mail.js +73 -0
  238. package/src/hosted/mcp-http.js +71 -0
  239. package/src/hosted/membership.js +114 -0
  240. package/src/hosted/operator.js +478 -0
  241. package/src/hosted/ops-cli.js +345 -0
  242. package/src/hosted/pages.js +146 -0
  243. package/src/hosted/permissions.js +113 -0
  244. package/src/hosted/presence.js +372 -0
  245. package/src/hosted/projects.js +124 -0
  246. package/src/hosted/public.js +109 -0
  247. package/src/hosted/push.js +622 -0
  248. package/src/hosted/quotas.js +115 -0
  249. package/src/hosted/ratelimit.js +96 -0
  250. package/src/hosted/rebind.js +316 -0
  251. package/src/hosted/retention.js +128 -0
  252. package/src/hosted/server.js +260 -0
  253. package/src/hosted/setup-link.js +64 -0
  254. package/src/hosted/setup.js +323 -0
  255. package/src/hosted/shares.js +444 -0
  256. package/src/hosted/tailscale.js +204 -0
  257. package/src/hosted/tenancy.js +301 -0
  258. package/src/hosted/token-api.js +455 -0
  259. package/src/hosted/token-events.js +60 -0
  260. package/src/hosted/tokens.js +57 -0
  261. package/src/hosted/turnstile.js +49 -0
  262. package/src/hosted/usercontent.js +154 -0
  263. package/src/hosted/zip.js +155 -0
  264. package/src/invocation.js +58 -0
  265. package/src/journey-paths.js +282 -0
  266. package/src/journeys.js +189 -0
  267. package/src/links.js +106 -0
  268. package/src/local-projects.js +182 -0
  269. package/src/lock.js +193 -0
  270. package/src/mcp.js +417 -0
  271. package/src/mentions.js +151 -0
  272. package/src/net.js +15 -0
  273. package/src/notify/config.js +275 -0
  274. package/src/notify/index.js +301 -0
  275. package/src/notify/lease.js +73 -0
  276. package/src/notify/messages.js +212 -0
  277. package/src/notify/run.js +174 -0
  278. package/src/pixeldiff.js +49 -0
  279. package/src/png.js +143 -0
  280. package/src/reactions.js +111 -0
  281. package/src/remote/cli.js +133 -0
  282. package/src/remote/credentials.js +62 -0
  283. package/src/remote/ids.js +12 -0
  284. package/src/remote/login.js +155 -0
  285. package/src/remote/remote-mcp.js +237 -0
  286. package/src/remote/remote-watch.js +291 -0
  287. package/src/remote/remote.js +313 -0
  288. package/src/remote/share-state.js +78 -0
  289. package/src/remote/share.js +369 -0
  290. package/src/remote/terminal.js +13 -0
  291. package/src/serve-state.js +64 -0
  292. package/src/server/app.js +824 -0
  293. package/src/server/devices.js +186 -0
  294. package/src/server/local-console.js +28 -0
  295. package/src/server/local-user.js +59 -0
  296. package/src/server/pairing-routes.js +159 -0
  297. package/src/server/share-routes.js +89 -0
  298. package/src/server/tailscale.js +97 -0
  299. package/src/sitemap.js +431 -0
  300. package/src/store.js +983 -0
  301. package/src/tokens.js +11 -0
  302. package/src/update/routes.js +245 -0
  303. package/src/watch.js +403 -0
  304. package/src/which.js +58 -0
@@ -0,0 +1,274 @@
1
+ // `shapewall serve`: the local board server, and the checks that decide what it may share.
2
+
3
+ import fs from 'node:fs'
4
+ import { randomBytes } from 'node:crypto'
5
+ import { isLoopback } from '../net.js'
6
+ import https from 'node:https'
7
+ import { lanAccess, tailscaleAccess } from '../server/tailscale.js'
8
+ import { loadConfig } from '../config.js'
9
+ import { formatCommand } from '../agent/acp/command.js'
10
+ import { detectAgents } from '../agent/acp/detect.js'
11
+ import { agentSettings } from '../agent/config.js'
12
+ import { watchConfig } from '../config-reload.js'
13
+ import { cliCommand } from '../invocation.js'
14
+ import { DEFAULT_PORT, clearServeState, servedUrl, writeServeState } from '../serve-state.js'
15
+ import { registerProject } from '../local-projects.js'
16
+ import { openBrowser } from './open.js'
17
+ import { startNotifier } from './notify.js'
18
+
19
+ // The Host header values `serve` accepts, or null for any. On a loopback
20
+ // address the local names are always allowed; --allowed-host and
21
+ // SHAPEWALL_ALLOWED_HOSTS add names (and keep the check on for any address);
22
+ // "*" in either turns the check off on purpose.
23
+ export function allowedHostsFor(host, flagHosts = [], envHosts = '') {
24
+ const extra = [
25
+ ...(flagHosts || []),
26
+ ...String(envHosts || '')
27
+ .split(',')
28
+ .map((item) => item.trim())
29
+ .filter(Boolean),
30
+ ]
31
+ if (extra.includes('*') || (!isLoopback(host) && !extra.length)) return null
32
+ const name = host.toLowerCase()
33
+ return new Set(['127.0.0.1', 'localhost', '[::1]', '::1', name, `[${name}]`, ...extra.map((item) => item.toLowerCase())])
34
+ }
35
+
36
+ // The board chat spends the server owner's model key, so it is on by default
37
+ // only for a board on this machine: bound to loopback with no extra Host
38
+ // names. --chat turns it on anyway, --no-chat off.
39
+ export function chatEnabledFor(flags, host, envHosts = '') {
40
+ if (flags['no-chat']) return false
41
+ if (flags.chat) return true
42
+ const extra = (flags['allowed-host'] || []).length > 0 || String(envHosts || '').trim() !== ''
43
+ return isLoopback(host) && !extra
44
+ }
45
+
46
+ // --agent-acp "CMD": the agent command, or null. A bare --agent-acp (no
47
+ // command) is a mistake worth saying, not an empty command.
48
+ export function acpFlag(flags) {
49
+ const value = flags['agent-acp']
50
+ if (value === undefined) return null
51
+ if (typeof value !== 'string' || !value.trim()) throw new Error('--agent-acp needs the agent command, e.g. --agent-acp "codex-acp"')
52
+ return value
53
+ }
54
+
55
+ // An ACP agent on a board shared beyond this machine is remote command
56
+ // execution as you, for anyone who reaches the board. --chat alone does not
57
+ // allow that: it needs --allow-remote-agent as well.
58
+ export function remoteAgentProblem({ flags, host, chat, readOnly, config, acp, env = process.env }) {
59
+ if (!chat || readOnly || flags['allow-remote-agent']) return null
60
+ if (chatEnabledFor({ 'allowed-host': flags['allowed-host'] }, host, env.SHAPEWALL_ALLOWED_HOSTS)) return null
61
+ const settings = agentSettings(config, env, { acp })
62
+ if (settings.backend !== 'acp') return null
63
+ const where = settings.sources?.backend === 'settings' ? ' (the agent is saved in Settings > Agent, ' + settings.settingsFile + ')' : ''
64
+ return (
65
+ `Refusing to start: --chat with an ACP agent${where} on a board shared beyond this machine lets anyone who reaches it run commands as you. ` +
66
+ 'Drop --chat (or the agent), or add --allow-remote-agent if every person who can reach this board may do that.'
67
+ )
68
+ }
69
+
70
+ // One line on what Connect in the Agent panel will offer.
71
+ export function detectedAgentsLine(found) {
72
+ const ready = found.filter((item) => item.state === 'ready').map((item) => item.label)
73
+ const adapter = found.filter((item) => item.state === 'needs-adapter').map((item) => item.label)
74
+ const parts = []
75
+ if (ready.length) parts.push(`Agents found on this machine: ${ready.join(', ')}. Connect one in the Agent panel (open the link above).`)
76
+ if (adapter.length) parts.push(`Installed without their ACP adapter: ${adapter.join(', ')} (the Agent panel shows the install line).`)
77
+ const wrapped = found.filter((item) => item.state === 'needs-shell').map((item) => item.label)
78
+ if (wrapped.length) parts.push(`Installed only as .cmd wrappers, which need a shell: ${wrapped.join(', ')} (see the chat docs).`)
79
+ return parts.length ? parts.join(' ') : null
80
+ }
81
+
82
+ export async function serve(flags, out) {
83
+ const config = loadConfig(flags.config)
84
+ const acp = acpFlag(flags)
85
+ const { createApp, stopChildren } = await import('../server/app.js')
86
+ if (flags.lan && flags.tailscale) throw new Error('Choose --lan or --tailscale, not both.')
87
+ if ((flags.lan || flags.tailscale) && flags.host)
88
+ throw new Error('Use --lan=IP to select an interface; do not combine remote modes with --host.')
89
+ if ((flags['tls-cert'] || flags['tls-key']) && (!flags.lan || !flags['tls-cert'] || !flags['tls-key']))
90
+ throw new Error('TLS needs --lan, --tls-cert and --tls-key together.')
91
+ if (flags.tailscale && flags.tailscale !== true && flags.tailscale !== 'print') throw new Error('Use --tailscale or --tailscale=print.')
92
+ const lan = flags.lan ? lanAccess(flags.lan) : null
93
+ const host = lan?.host || flags.host || '127.0.0.1'
94
+ const port = flags.port === undefined ? DEFAULT_PORT : Number(flags.port)
95
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('--port must be a port number')
96
+ if (flags.tailscale && port === 0) throw new Error('--tailscale needs a fixed --port, not 0.')
97
+ const tail = flags.tailscale ? await tailscaleAccess({ port, noIdentity: Boolean(flags['no-identity']) }) : null
98
+ if (flags.tailscale === 'print') {
99
+ out(tail.command)
100
+ out(tail.url)
101
+ return
102
+ }
103
+ const remote =
104
+ lan || tail
105
+ ? { tailscale: tail, noRemoteChat: Boolean(flags['no-remote-chat']), approveOnHost: Boolean(flags['approve-on-host']) }
106
+ : null
107
+ const loopback = isLoopback(host)
108
+ const configuredHosts = allowedHostsFor(remote ? '127.0.0.1' : host, flags['allowed-host'], process.env.SHAPEWALL_ALLOWED_HOSTS)
109
+ if (remote && !configuredHosts) throw new Error('Remote owner mode does not allow wildcard Host names.')
110
+ const allowedHosts = remote ? new Set([...(configuredHosts || []), ...(lan?.hosts || []), ...(tail ? [tail.host] : [])]) : configuredHosts
111
+ const readOnly = Boolean(flags['read-only'])
112
+ const chat = remote ? !flags['no-chat'] : chatEnabledFor(flags, host, process.env.SHAPEWALL_ALLOWED_HOSTS)
113
+ const remoteAgent = remote ? null : remoteAgentProblem({ flags, host, chat, readOnly, config, acp, env: process.env })
114
+ if (remoteAgent) throw new Error(remoteAgent)
115
+ const shared = !remote && !chatEnabledFor({ 'allowed-host': flags['allowed-host'] }, host, process.env.SHAPEWALL_ALLOWED_HOSTS)
116
+ // Settings > Agent needs this per-process token (in the link printed below),
117
+ // so a visitor through a Host-rewriting proxy or tunnel cannot use it.
118
+ const settingsToken = !shared && (remote || !readOnly) ? randomBytes(24).toString('base64url') : null
119
+ const accountsEnabled = flags.accounts === undefined ? process.env.SHAPEWALL_ACCOUNTS === '1' : flags.accounts
120
+ let localAccounts = null
121
+ if (accountsEnabled) {
122
+ const { openLocalAccountDatabase } = await import('../accounts/local.js')
123
+ const origin =
124
+ flags['accounts-origin'] ||
125
+ process.env.SHAPEWALL_ACCOUNTS_ORIGIN ||
126
+ tail?.url ||
127
+ (loopback && port ? servedUrl('localhost', port) : null)
128
+ localAccounts = await openLocalAccountDatabase(config, origin)
129
+ } else if (flags['accounts-origin']) {
130
+ throw new Error('--accounts-origin needs --accounts.')
131
+ }
132
+ const app = createApp({
133
+ config,
134
+ readOnly,
135
+ allowCapture: !readOnly && !flags['no-capture'],
136
+ allowedHosts,
137
+ chat,
138
+ agentAcp: acp,
139
+ remote,
140
+ // Beyond this machine: no Settings > Agent, and no ACP agent without --allow-remote-agent.
141
+ shared,
142
+ settingsToken,
143
+ localAccounts,
144
+ buzzBridge: flags['buzz-bridge'] || null,
145
+ allowRemoteAgent: Boolean(flags['allow-remote-agent']),
146
+ // A managed installer opts in to restart only this serve process after
147
+ // its fixed helper switches an immutable release pointer. The existing
148
+ // service manager restarts exit 75; ordinary CLI installs never exit.
149
+ appUpdate: process.env.SHAPEWALL_UPDATE_RESTART === '1' ? { onRestart: () => process.exit(75) } : {},
150
+ log: (line) => out(line),
151
+ })
152
+ const tls = flags['tls-cert'] ? { cert: fs.readFileSync(flags['tls-cert']), key: fs.readFileSync(flags['tls-key']) } : null
153
+ const server = tls ? https.createServer(tls, app).listen(port, host) : app.listen(port, host)
154
+ watchConfig(config, { log: out, server })
155
+ await new Promise((resolve, reject) => {
156
+ server.once('listening', resolve)
157
+ server.once('error', reject)
158
+ })
159
+ let hostServer = null
160
+ if (lan && host !== '0.0.0.0') {
161
+ hostServer = tls
162
+ ? https.createServer(tls, app).listen(server.address().port, '127.0.0.1')
163
+ : app.listen(server.address().port, '127.0.0.1')
164
+ try {
165
+ await new Promise((resolve, reject) => {
166
+ hostServer.once('listening', resolve)
167
+ hostServer.once('error', reject)
168
+ })
169
+ } catch (error) {
170
+ server.close()
171
+ stopChildren(app)
172
+ throw error
173
+ }
174
+ }
175
+ try {
176
+ await tail?.start()
177
+ } catch (error) {
178
+ server.close()
179
+ hostServer?.close()
180
+ stopChildren(app)
181
+ throw error
182
+ }
183
+ const address = server.address()
184
+ const shown = host.includes(':') ? `[${host}]` : host
185
+ const accountUrl = localAccounts ? `${localAccounts.origin}/` : null
186
+ const remoteAccountOrigin = accountUrl && !['localhost', '127.0.0.1', '[::1]'].includes(new URL(accountUrl).hostname)
187
+ out(
188
+ `Shapewall is serving ${config.boards.length} board${config.boards.length === 1 ? '' : 's'} at ${accountUrl || `${tls ? 'https' : 'http'}://${shown}:${address.port}/`}`,
189
+ )
190
+ if (tail) out(`Private Tailscale board: ${tail.url}${tail.ownerLogin ? '' : ' (pairing required; node has no owner identity)'}`)
191
+ if (lan)
192
+ out(
193
+ 'LAN pairing is on. Plain HTTP on Wi-Fi exposes the device cookie to sniffing and replay; use --tailscale or --tls-cert/--tls-key. HTTP installs only as a bookmark.',
194
+ )
195
+ if (settingsToken && !remoteAccountOrigin) {
196
+ // Only to a terminal: a service's output goes to logs (journald), which
197
+ // keep the token. SHAPEWALL_PRINT_OWNER_LINK=1 prints it anyway.
198
+ if (process.stdout.isTTY || process.env.SHAPEWALL_PRINT_OWNER_LINK === '1') {
199
+ out(
200
+ `Private owner link (settings, sharing${remote ? ' and devices' : ''}; keep it to yourself): ${accountUrl || `${tls ? 'https' : 'http'}://127.0.0.1:${address.port}/`}#settings-token=${settingsToken}`,
201
+ )
202
+ } else if (!flags.open) {
203
+ out(
204
+ `Private owner link: not printed, because this output is not a terminal and logs would keep it. Run "${cliCommand('serve --open')}" to open it in your browser, "${cliCommand('settings')} --open" for agent settings, or set SHAPEWALL_PRINT_OWNER_LINK=1.`,
205
+ )
206
+ }
207
+ }
208
+ if (remoteAccountOrigin) {
209
+ out(`Host agent settings: ${cliCommand('settings')} --config ${formatCommand([config.file])} --open`)
210
+ out('Agent settings use a separate temporary window on this computer. The account board keeps its existing access gates.')
211
+ }
212
+ const agent = agentSettings(config, process.env, { acp })
213
+ if (settingsToken && chat && !readOnly && !agent.configured) {
214
+ const line = detectedAgentsLine(detectAgents(process.env))
215
+ if (line) out(line)
216
+ }
217
+ if (!loopback && !remote)
218
+ out('Warning: listening beyond this machine with no login. Put it behind an authenticating proxy (docs/deployment.md).')
219
+ if ((config.agent || agent.backend === 'acp') && !readOnly && !chat) {
220
+ out(
221
+ agent.backend === 'acp'
222
+ ? 'Chat is off for a shared board (anyone reaching it could drive your agent on this machine). Pass --chat to turn it on.'
223
+ : 'Chat is off for a shared board (it would spend your model key). Pass --chat to turn it on.',
224
+ )
225
+ } else if (agent.backend === 'acp' && !readOnly) {
226
+ out(
227
+ agent.configured
228
+ ? `Chat: ${agent.label} over ACP (${formatCommand(agent.acp.argv)}), started per thread in ${config.dir}`
229
+ : `Chat: the ACP agent is not ready: ${agent.problem}`,
230
+ )
231
+ if (agent.acp?.refusedEnv.length) out(`Not passed to the agent (Shapewall or other tools' secrets): ${agent.acp.refusedEnv.join(', ')}`)
232
+ if (
233
+ flags['allow-remote-agent'] &&
234
+ !chatEnabledFor({ 'allowed-host': flags['allowed-host'] }, host, process.env.SHAPEWALL_ALLOWED_HOSTS)
235
+ ) {
236
+ out('Warning: --allow-remote-agent: anyone who reaches this board can drive your agent on this machine, with your login.')
237
+ }
238
+ }
239
+ // Other commands (comments resolve, watch, mcp, github) link to this port.
240
+ const url = accountUrl || (remote ? `${tls ? 'https' : 'http'}://127.0.0.1:${address.port}/` : servedUrl(host, address.port))
241
+ writeServeState(config, url)
242
+ if (!shared) {
243
+ try {
244
+ registerProject(config)
245
+ } catch (error) {
246
+ out(`Local project switcher: ${error.message}`)
247
+ }
248
+ }
249
+ // serve: the notifier for changes from every process (src/notify/run.js).
250
+ const notifier = await startNotifier(config, out, { boardUrl: url, serve: true })
251
+ if (notifier) out(`Notifications: ${notifier.channels.map((channel) => channel.id).join(', ')}`)
252
+ server.on('close', () => {
253
+ localAccounts?.db.close()
254
+ hostServer?.close()
255
+ notifier?.stop()
256
+ tail?.stop().catch((error) => out(error.message))
257
+ clearServeState(config)
258
+ })
259
+ // With a token: a one-time link the server answers once with the settings
260
+ // link (src/server/app.js /open/<nonce>), so the token itself never goes on
261
+ // a command line. Without one: the plain address.
262
+ if (flags.open) openBrowser(!remoteAccountOrigin && app.locals.openLink ? `${url}${app.locals.openLink()}` : url, out)
263
+ const stop = () => {
264
+ clearServeState(config)
265
+ stopChildren(app)
266
+ // Hands the lease over after a last read of the log; messages still
267
+ // queued get a moment, inside the exit deadline below.
268
+ Promise.allSettled([notifier?.close(1500), tail?.stop()]).finally(() => server.close(() => process.exit(0)))
269
+ setTimeout(() => process.exit(0), tail ? 12000 : 2000).unref()
270
+ }
271
+ process.once('SIGINT', stop)
272
+ process.once('SIGTERM', stop)
273
+ return server
274
+ }
@@ -0,0 +1,82 @@
1
+ // `shapewall variant`: another version of a page, captured beside it.
2
+
3
+ import { randomBytes } from 'node:crypto'
4
+ import { ID_RE, boardViewports, getBoard, joinUrl, loadConfig } from '../config.js'
5
+ import { captureVariant } from '../capture/capture.js'
6
+ import { readVariants, removeVariant, saveVariant, variantsWithFiles } from '../store.js'
7
+ import { suggestFlag } from './args.js'
8
+
9
+ function slugify(textValue) {
10
+ return (
11
+ String(textValue || '')
12
+ .toLowerCase()
13
+ .replace(/[^a-z0-9]+/g, '-')
14
+ .replace(/^-+|-+$/g, '')
15
+ .slice(0, 40) || 'variant'
16
+ )
17
+ }
18
+
19
+ export async function variant(positional, flags, out) {
20
+ const config = loadConfig(flags.config)
21
+ const board = getBoard(config, flags.board)
22
+ const action = positional[0]
23
+ if (action === 'list') {
24
+ const list = variantsWithFiles(config, board)
25
+ if (flags.json) out(JSON.stringify({ variants: list }, null, 2))
26
+ else
27
+ out(
28
+ list.length
29
+ ? list
30
+ .map((item) => `${item.id} beside ${item.pageId} "${item.title}" ${Object.keys(item.files).join(', ') || 'no files'}`)
31
+ .join('\n')
32
+ : 'No variants.',
33
+ )
34
+ return
35
+ }
36
+ if (action === 'rm') {
37
+ const id = positional[1]
38
+ if (!id) throw new Error('usage: shapewall variant rm ID')
39
+ if (!(await removeVariant(config, board.id, id))) throw new Error(`No variant "${id}"`)
40
+ out(`Removed ${id}`)
41
+ return
42
+ }
43
+ if (action === 'add') {
44
+ const pageId = positional[1]
45
+ if (!pageId) throw new Error(`usage: shapewall variant add PAGE --url URL --title TEXT (PAGE is a page id on "${board.id}")`)
46
+ const page = board.pages.find((item) => item.id === pageId)
47
+ if (!page) {
48
+ const ids = board.pages.map((item) => item.id)
49
+ const close = suggestFlag(pageId, ids)
50
+ throw new Error(
51
+ `no page '${pageId.slice(0, 80)}' on board "${board.id}"${close ? ` (did you mean ${close}?)` : ''}; pages: ${ids.slice(0, 12).join(', ')}${ids.length > 12 ? ', ...' : ''}`,
52
+ )
53
+ }
54
+ const url = flags.url || (flags.path ? joinUrl(board.baseUrl, flags.path) : null)
55
+ if (!url || !/^https?:\/\//.test(url)) throw new Error('--url (http or https) or --path is required')
56
+ const title = typeof flags.title === 'string' && flags.title.trim() ? flags.title.trim() : 'Variant'
57
+ let id = flags.id || `${slugify(title)}-${randomBytes(2).toString('hex')}`
58
+ if (!ID_RE.test(id)) throw new Error('--id: lowercase letters, digits and dashes')
59
+ if (readVariants(config, board.id).some((item) => item.id === id) && !flags.id) id = `${id}-${randomBytes(2).toString('hex')}`
60
+ const viewports = flags.viewport
61
+ ? String(flags.viewport)
62
+ .split(',')
63
+ .map((item) => item.trim())
64
+ : page.viewports
65
+ for (const name of viewports)
66
+ if (!boardViewports(config, board)[name]) throw new Error(`--viewport: no viewport "${name}" on board "${board.id}"`)
67
+ out(`Capturing variant ${id} of ${page.id} from ${url}`)
68
+ const results = await captureVariant({ config, boardId: board.id, pageId: page.id, variantId: id, url, viewports, log: out })
69
+ if (!Object.values(results).some((entry) => entry.status === 'ok')) throw new Error('every shot failed; nothing was saved')
70
+ await saveVariant(config, board.id, {
71
+ id,
72
+ pageId: page.id,
73
+ title,
74
+ note: flags.note || '',
75
+ source: flags.source || url,
76
+ createdAt: new Date().toISOString(),
77
+ })
78
+ out(`Added variant ${id} beside ${page.id}`)
79
+ return
80
+ }
81
+ throw new Error('usage: shapewall variant add|rm|list')
82
+ }
@@ -0,0 +1,70 @@
1
+ // `shapewall watch`: hand each new open comment to an agent.
2
+
3
+ import { loadConfig } from '../config.js'
4
+ import { mentionFlag, startNotifier } from './notify.js'
5
+
6
+ export async function watch(flags, out, err) {
7
+ const config = flags.remote === undefined ? loadConfig(flags.config) : null
8
+ const { watchComments } = await import('../watch.js')
9
+ const number = (name, fallback) => {
10
+ if (flags[name] === undefined) return fallback
11
+ const value = Number(flags[name])
12
+ if (!Number.isFinite(value) || value <= 0) throw new Error(`--${name} must be a positive number`)
13
+ return value
14
+ }
15
+ const controller = new AbortController()
16
+ const stop = () => controller.abort()
17
+ process.once('SIGINT', stop)
18
+ process.once('SIGTERM', stop)
19
+ const notifier = config ? await startNotifier(config, err) : null
20
+ try {
21
+ if (flags.remote !== undefined) {
22
+ if (flags.recapture) throw new Error('--recapture works with local --exec only')
23
+ if (flags['no-claim']) throw new Error('--no-claim works on a local board only (not with --remote)')
24
+ const { createRemote, remoteSettings } = await import('../remote/remote.js')
25
+ const { remoteBoard } = await import('../remote/cli.js')
26
+ const { watchRemote } = await import('../remote/remote-watch.js')
27
+ const remote = createRemote(remoteSettings(flags))
28
+ const { project, boardId } = await remoteBoard(remote, flags.board)
29
+ await watchRemote({
30
+ remote,
31
+ boardId,
32
+ passToken: Boolean(flags['pass-token']),
33
+ includeGuests: Boolean(flags['include-guests']),
34
+ projectId: project.project.id,
35
+ exec: typeof flags.exec === 'string' ? flags.exec : null,
36
+ concurrency: number('concurrency', 1),
37
+ newOnly: Boolean(flags['new-only']),
38
+ once: Boolean(flags.once),
39
+ mention: mentionFlag(flags.mention),
40
+ timeoutMs: number('timeout', 60) * 60000,
41
+ signal: controller.signal,
42
+ out,
43
+ log: err,
44
+ })
45
+ return
46
+ }
47
+ await watchComments({
48
+ config,
49
+ boardId: flags.board,
50
+ exec: typeof flags.exec === 'string' ? flags.exec : null,
51
+ concurrency: number('concurrency', 1),
52
+ newOnly: Boolean(flags['new-only']),
53
+ once: Boolean(flags.once),
54
+ mention: mentionFlag(flags.mention),
55
+ claim: !flags['no-claim'],
56
+ recapture: Boolean(flags.recapture),
57
+ timeoutMs: number('timeout', 60) * 60000,
58
+ signal: controller.signal,
59
+ out,
60
+ log: err,
61
+ })
62
+ } finally {
63
+ process.removeListener('SIGINT', stop)
64
+ process.removeListener('SIGTERM', stop)
65
+ if (notifier) {
66
+ await notifier.flush(5000)
67
+ notifier.stop()
68
+ }
69
+ }
70
+ }
package/src/cli.js ADDED
@@ -0,0 +1,130 @@
1
+ // The `shapewall` command line.
2
+ // Each command lives in src/cli/; this file parses the command line and dispatches.
3
+
4
+ import { devicesCommand } from './devices-cli.js'
5
+ import { loadConfig } from './config.js'
6
+ import { HELP, SECTIONS, VERSION, commandHelp } from './cli/help.js'
7
+ import { parseArgs } from './cli/args.js'
8
+ import { init, sitemap } from './cli/init.js'
9
+ import { serve } from './cli/serve.js'
10
+ import { notify } from './cli/notify.js'
11
+ import { comments } from './cli/comments.js'
12
+ import { variant } from './cli/variant.js'
13
+ import { watch } from './cli/watch.js'
14
+ import { doctor, github } from './cli/misc.js'
15
+ import { capture, links } from './cli/capture.js'
16
+ import { buzzBridge, events, exportCommand, journeys, mcp, settings } from './cli/commands.js'
17
+
18
+ // Re-exported for the tests and older imports.
19
+ export { COMMAND_FLAGS, suggestFlag } from './cli/args.js'
20
+ export { initNextHint } from './cli/init.js'
21
+ export { openerFor } from './cli/open.js'
22
+ export { acpFlag, allowedHostsFor, chatEnabledFor, detectedAgentsLine, remoteAgentProblem } from './cli/serve.js'
23
+ export { commandHelp, parseArgs }
24
+
25
+ // Re-exported for the tests and older imports; it lives in net.js.
26
+ export { isLoopback } from './net.js'
27
+
28
+ // Each command: ({ positional, flags, out, err, fetch }) => its exit code
29
+ // (null: it keeps running, e.g. a server).
30
+ const COMMANDS = {
31
+ 'buzz-bridge': ({ flags, out }) => buzzBridge(flags, out),
32
+ auth: async ({ positional, flags, out }) => {
33
+ const { authCommand } = await import('./auth/record.js')
34
+ return authCommand(loadConfig(flags.config), positional, flags, out)
35
+ },
36
+ init: async ({ flags, out, fetch }) => {
37
+ await init(flags, out, { fetch })
38
+ return 0
39
+ },
40
+ sitemap: async ({ positional, flags, out, fetch }) => {
41
+ await sitemap(positional, flags, out, { fetch })
42
+ return 0
43
+ },
44
+ capture: ({ flags, out, err }) => capture(flags, out, err),
45
+ checks: async ({ positional, flags, out, err }) => {
46
+ const { checksCommand } = await import('./checks/cli.js')
47
+ return checksCommand(loadConfig(flags.config), positional, flags, out, err)
48
+ },
49
+ audit: async ({ positional, flags, out, err }) => {
50
+ const { auditCommand } = await import('./checks/lighthouse.js')
51
+ return auditCommand(loadConfig(flags.config), positional, flags, out, err)
52
+ },
53
+ links: ({ flags, out }) => links(flags, out),
54
+ serve: async ({ flags, out }) => {
55
+ await serve(flags, out)
56
+ return null
57
+ },
58
+ devices: ({ positional, flags, out }) => {
59
+ devicesCommand(loadConfig(flags.config), positional, flags, out)
60
+ return 0
61
+ },
62
+ settings: ({ flags, out, err }) => settings(flags, out, err),
63
+ comments: async ({ positional, flags, out, err }) => {
64
+ await comments(positional, flags, out, err)
65
+ return 0
66
+ },
67
+ notify: ({ positional, flags, out }) => notify(positional, flags, out),
68
+ variant: async ({ positional, flags, out }) => {
69
+ await variant(positional, flags, out)
70
+ return 0
71
+ },
72
+ journeys: ({ positional, flags, out }) => journeys(positional, flags, out),
73
+ watch: async ({ flags, out, err }) => {
74
+ await watch(flags, out, err)
75
+ return 0
76
+ },
77
+ events: ({ flags, out, err }) => events(flags, out, err),
78
+ github: async ({ positional, flags, out }) => {
79
+ await github(positional, flags, out)
80
+ return 0
81
+ },
82
+ agent: async ({ positional, flags, out, err }) => {
83
+ const { agentCommand } = await import('./agent/starter/cli.js')
84
+ return agentCommand(positional, flags, out, err)
85
+ },
86
+ mcp: ({ flags, err }) => mcp(flags, err),
87
+ doctor: ({ flags, out }) => doctor(flags, out),
88
+ export: ({ flags, out }) => exportCommand(flags, out),
89
+ login: async ({ flags, out }) => {
90
+ const { login } = await import('./remote/login.js')
91
+ await login(flags, out)
92
+ return 0
93
+ },
94
+ share: async ({ flags, out }) => {
95
+ const { share } = await import('./remote/share.js')
96
+ return (await share(flags, out)).code
97
+ },
98
+ push: async ({ flags, out }) => {
99
+ const { push } = await import('./remote/cli.js')
100
+ await push(flags, out)
101
+ return 0
102
+ },
103
+ hosted: async ({ positional, flags, out, err }) => {
104
+ const { hostedCommand } = await import('./hosted/ops-cli.js')
105
+ return hostedCommand(positional, flags, out, err)
106
+ },
107
+ }
108
+
109
+ export async function main(
110
+ argv = process.argv.slice(2),
111
+ { out = (line) => console.log(line), err = (line) => console.error(line), fetch = globalThis.fetch } = {},
112
+ ) {
113
+ // "shapewall capture --help" is that command's help, whatever else is on the line.
114
+ const wantsHelp = argv.includes('--help') || argv.includes('-h')
115
+ const { command, positional, flags } = wantsHelp ? parseArgs(argv) : parseArgs(argv, { strict: true })
116
+ if (flags.version && !wantsHelp) {
117
+ out(VERSION)
118
+ return 0
119
+ }
120
+ if (command === 'help') {
121
+ out(positional[0] ? commandHelp(positional[0]) : HELP)
122
+ return 0
123
+ }
124
+ if (flags.help || !command) {
125
+ out(command && SECTIONS[command] ? commandHelp(command) : HELP)
126
+ return command || flags.help ? 0 : 1
127
+ }
128
+ if (!Object.hasOwn(COMMANDS, command)) throw new Error(`unknown command "${command}" (try shapewall --help)`)
129
+ return COMMANDS[command]({ positional, flags, out, err, fetch })
130
+ }
@@ -0,0 +1,76 @@
1
+ // A comment's fields, checked the same way everywhere: the anchor a pin
2
+ // sits on, the fix reference, the body's limit, and the error they throw.
3
+ // Pure, with no imports, so the server (src/store.js re-exports all of it)
4
+ // and the demo's in-browser backend (client/src/demo) share one set of rules.
5
+
6
+ export const COMMENT_BODY_MAX = 2000
7
+ export const ANCHOR_SELECTOR_MAX = 600
8
+ export const ANCHOR_TEXT_MAX = 80
9
+
10
+ // The only selectors an anchor may hold: what the client's selectorFor()
11
+ // emits. Steps are `#id` (CSS-escaped), `tag[data-testid="..."]`,
12
+ // `tag[aria-label="..."]` or `tag:nth-of-type(n)`, joined by ` > `.
13
+ // Keep in sync with client/src/board/anchors.js.
14
+ const ANCHOR_STEP = String.raw`(?:#(?:[A-Za-z0-9_\u0080-￿-]|\\[0-9a-fA-F]{6} ?|\\[0-9a-fA-F]{1,5}(?![0-9a-fA-F]) ?|\\[^0-9a-fA-F\n\r\f])+|[a-z][a-z0-9-]{0,40}(?:\[(?:data-testid|aria-label)="(?:[^"\\\n]|\\.){0,200}"\]|:nth-of-type\([1-9][0-9]{0,4}\)))`
15
+ export const ANCHOR_SELECTOR_RE = new RegExp(`^${ANCHOR_STEP}(?: > ${ANCHOR_STEP}){0,79}$`)
16
+
17
+ export class CommentError extends Error {
18
+ constructor(statusCode, code, message, options) {
19
+ super(message, options)
20
+ this.statusCode = statusCode
21
+ this.code = code
22
+ }
23
+ }
24
+
25
+ export function validateAnchor(anchor) {
26
+ if (anchor === undefined || anchor === null) return null
27
+ const bad = (message) => new CommentError(400, 'invalid_anchor', message)
28
+ if (typeof anchor !== 'object' || Array.isArray(anchor)) throw bad('The anchor must be an object.')
29
+ const selector = typeof anchor.selector === 'string' ? anchor.selector.trim() : ''
30
+ // eslint-disable-next-line no-control-regex
31
+ if (!selector || selector.length > ANCHOR_SELECTOR_MAX || /[\u0000-\u001f\u007f]/.test(selector)) {
32
+ throw bad(`The anchor selector must be 1 to ${ANCHOR_SELECTOR_MAX} printable characters.`)
33
+ }
34
+ if (!ANCHOR_SELECTOR_RE.test(selector)) throw bad('The anchor selector is not one Shapewall writes.')
35
+ if (anchor.text !== undefined && typeof anchor.text !== 'string') throw bad('The anchor text must be a string.')
36
+ const text = typeof anchor.text === 'string' ? anchor.text.replace(/\s+/g, ' ').trim() : ''
37
+ if (text.length > ANCHOR_TEXT_MAX) throw bad(`The anchor text is limited to ${ANCHOR_TEXT_MAX} characters.`)
38
+ const { dx, dy } = anchor
39
+ if (
40
+ typeof dx !== 'number' ||
41
+ typeof dy !== 'number' ||
42
+ !Number.isFinite(dx) ||
43
+ !Number.isFinite(dy) ||
44
+ dx < 0 ||
45
+ dx > 1 ||
46
+ dy < 0 ||
47
+ dy > 1
48
+ ) {
49
+ throw bad('The anchor offset must be two numbers from 0 to 1.')
50
+ }
51
+ const round = (value) => Math.round(value * 10000) / 10000
52
+ const clean = { selector, text, dx: round(dx), dy: round(dy) }
53
+ // Optional: the element's size as a share of the page, so a pin can sit on
54
+ // the element's corner without the live HTML. Both or neither.
55
+ const share = (value) => typeof value === 'number' && Number.isFinite(value) && value > 0 && value <= 1
56
+ if (anchor.w !== undefined || anchor.h !== undefined) {
57
+ if (!share(anchor.w) || !share(anchor.h)) throw bad('The anchor size must be two numbers above 0, up to 1.')
58
+ clean.w = round(anchor.w)
59
+ clean.h = round(anchor.h)
60
+ }
61
+ return clean
62
+ }
63
+
64
+ // What fixed a comment: a pull request URL, a commit, a ticket. Plain text;
65
+ // the board links it only when it is an http(s) URL. null or '' clears it.
66
+ export const FIX_REF_MAX = 300
67
+ export function cleanFixRef(value) {
68
+ if (value === null || value === '') return null
69
+ // eslint-disable-next-line no-control-regex
70
+ if (typeof value !== 'string' || /[\u0000-\u001f\u007f]/.test(value)) {
71
+ throw new CommentError(400, 'invalid_fix_ref', 'The fix reference must be one line of text (a URL or a commit).')
72
+ }
73
+ const ref = value.trim()
74
+ if (ref.length > FIX_REF_MAX) throw new CommentError(400, 'invalid_fix_ref', `The fix reference is limited to ${FIX_REF_MAX} characters.`)
75
+ return ref || null
76
+ }