@nera-static/mcp 1.2.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod'
2
2
  import { freePort } from '../processes.js'
3
3
  import { ok, tool, ToolError } from '../results.js'
4
+ import { neraVersion } from '../runner.js'
4
5
  import { failureText } from './cli.js'
5
6
  import { resolveSite, siteInput } from './sites.js'
6
7
 
@@ -12,6 +13,8 @@ export const PUBLISH_WAIT_MS = 30 * 1000
12
13
  const PUBLISH_TARGETS = ['github-pages', 'netlify']
13
14
  /** How much of the CLI's last progress line a status carries. */
14
15
  const PROGRESS_MAX = 300
16
+ /** The first `@nera-static/nera` whose `publish --json` writes the event lines `pendingAction` reads. */
17
+ const PUBLISH_CLI_FLOOR = '1.27.0'
15
18
 
16
19
  /** Terminal colour codes (ESC [ … m), in case a child ignores NO_COLOR. Built from a string so the source holds no control character. */
17
20
  const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`, 'g')
@@ -19,33 +22,19 @@ const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`, 'g')
19
22
  const LOCAL_URL = /Local:\s+(https?:\/\/[^\s]+)/
20
23
 
21
24
  /**
22
- * The lines of `nera publish` that ask the user to do something in the
23
- * browser, and the lines that say it is done. Only these fixed shapes are
24
- * read: the GitHub user code and verification page (the code is what the
25
- * user types; it is not a credential — the device code and the tokens never
26
- * appear in the CLI's output), the GitHub App installation page, and the
27
- * Netlify authorization page.
25
+ * The browser steps `nera publish --json` (@nera-static/nera ≥ 1.27.0)
26
+ * announces as event lines on stderr, `{"event":"action_required","action":
27
+ * {kind,code?,url}}` and `{"event":"action_done","kind"}`, and the host each
28
+ * one's page must be on. An event counts only in this shape: a known kind, an
29
+ * `https://` page on its host and, for the GitHub sign-in, a user code of the
30
+ * user-code shape (what the user types; it is not a credential — the device
31
+ * code and the tokens never appear in the CLI's output).
28
32
  */
29
- const ACTIONS = [
30
- {
31
- kind: 'github_sign_in',
32
- match: /To sign in to GitHub, enter the code ([A-Z0-9]{4,8}-[A-Z0-9]{4,8}) at (https:\/\/github\.com\/\S+)/,
33
- action: ([, code, url]) => ({ kind: 'github_sign_in', code, url }),
34
- done: /^Signed in as /,
35
- },
36
- {
37
- kind: 'github_app_install',
38
- match: /Install it at (https:\/\/github\.com\/apps\/\S+)/,
39
- action: ([, url]) => ({ kind: 'github_app_install', url }),
40
- done: /^Nera Static is installed on /,
41
- },
42
- {
43
- kind: 'netlify_sign_in',
44
- match: /To sign in to Netlify, open (https:\/\/app\.netlify\.com\/\S+) and choose "Authorize"/,
45
- action: ([, url]) => ({ kind: 'netlify_sign_in', url }),
46
- done: /^Signed in to Netlify/,
47
- },
48
- ]
33
+ const ACTIONS = {
34
+ github_sign_in: { host: 'github.com', code: /^[A-Z0-9]{4,8}-[A-Z0-9]{4,8}$/ },
35
+ github_app_install: { host: 'github.com' },
36
+ netlify_sign_in: { host: 'app.netlify.com' },
37
+ }
49
38
 
50
39
  const INSTRUCTIONS = {
51
40
  github_sign_in: ({ code, url }) => `Ask the user to open ${url} and enter the code ${code}, then call publish again.`,
@@ -58,8 +47,49 @@ function lines(text) {
58
47
  }
59
48
 
60
49
  /**
61
- * What a running `nera publish` waits for: the last browser step it asked
62
- * for that it has not reported done since, or null.
50
+ * The event a line of `nera publish --json` carries, or null for a log line
51
+ * (and for a line that starts with `{` but is no JSON object with a string
52
+ * `event`). Never throws: it runs inside `waitFor`'s predicate.
53
+ *
54
+ * @param {string} line
55
+ * @returns {{ event: string, [key: string]: unknown }|null}
56
+ */
57
+ function eventOf(line) {
58
+ if (!line.startsWith('{')) return null
59
+ try {
60
+ const parsed = JSON.parse(line)
61
+ return typeof parsed?.event === 'string' ? parsed : null
62
+ } catch {
63
+ return null
64
+ }
65
+ }
66
+
67
+ /** Whether `url` is one `https://` address, without whitespace, on exactly `host`. */
68
+ function onHost(url, host) {
69
+ if (typeof url !== 'string' || /\s/.test(url)) return false
70
+ try {
71
+ const parsed = new URL(url)
72
+ return parsed.protocol === 'https:' && parsed.hostname === host
73
+ } catch {
74
+ return false
75
+ }
76
+ }
77
+
78
+ /** The action of an `action_required` event, reduced to `kind`, `code?` and `url`, or null when it is not of a known shape. */
79
+ function knownAction(action) {
80
+ const kind = action?.kind
81
+ if (typeof kind !== 'string' || !Object.hasOwn(ACTIONS, kind)) return null
82
+ const known = ACTIONS[kind]
83
+ if (!onHost(action.url, known.host)) return null
84
+ if (!known.code) return { kind, url: action.url }
85
+ if (typeof action.code !== 'string' || !known.code.test(action.code)) return null
86
+ return { kind, code: action.code, url: action.url }
87
+ }
88
+
89
+ /**
90
+ * What a running `nera publish` waits for: the last browser step an
91
+ * `action_required` event asked for with no later `action_done` of the same
92
+ * kind, or null. Log lines never count, whatever they say.
63
93
  *
64
94
  * @param {string} stderr the CLI's log (`--json` mode logs to stderr)
65
95
  * @returns {{ kind: string, code?: string, url: string }|null}
@@ -67,20 +97,44 @@ function lines(text) {
67
97
  export function pendingAction(stderr) {
68
98
  let pending = null
69
99
  for (const line of lines(stderr)) {
70
- for (const known of ACTIONS) {
71
- const found = line.match(known.match)
72
- if (found) pending = known.action(found)
73
- else if (pending?.kind === known.kind && known.done.test(line)) pending = null
74
- }
100
+ const event = eventOf(line)
101
+ if (event?.event === 'action_required') pending = knownAction(event.action) ?? pending
102
+ else if (event?.event === 'action_done' && pending?.kind === event.kind) pending = null
75
103
  }
76
104
  return pending
77
105
  }
78
106
 
107
+ /** The CLI's last log line, the event lines skipped, cut to PROGRESS_MAX. */
79
108
  function lastProgress(stderr) {
80
- const last = lines(stderr).at(-1) ?? ''
109
+ const last = lines(stderr).findLast((line) => eventOf(line) === null) ?? ''
81
110
  return last.length > PROGRESS_MAX ? `${last.slice(0, PROGRESS_MAX)}…` : last
82
111
  }
83
112
 
113
+ /** `x.y.z` with an optional `-prerelease` (and `+build`, ignored), or null. */
114
+ function parseVersion(version) {
115
+ const match = typeof version === 'string' && version.match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/)
116
+ return match ? { numbers: match.slice(1, 4).map(Number), prerelease: match[4] !== undefined } : null
117
+ }
118
+
119
+ /**
120
+ * Whether `version` is `floor` or later, by semver precedence: major, minor
121
+ * and patch compared as numbers, and a prerelease of a version (`1.27.0-beta.1`)
122
+ * below that version. Anything that is no `x.y.z` version is not.
123
+ *
124
+ * @param {string|null} version
125
+ * @param {string} floor an `x.y.z` version without a prerelease
126
+ * @returns {boolean}
127
+ */
128
+ export function meetsFloor(version, floor) {
129
+ const have = parseVersion(version)
130
+ if (!have) return false
131
+ const need = parseVersion(floor).numbers
132
+ for (let i = 0; i < 3; i++) {
133
+ if (have.numbers[i] !== need[i]) return have.numbers[i] > need[i]
134
+ }
135
+ return !have.prerelease
136
+ }
137
+
84
138
  /**
85
139
  * The local address `nera dev` serves on, once Vite has printed it.
86
140
  *
@@ -150,7 +204,7 @@ export function registerLongRunningTools(server, ctx) {
150
204
 
151
205
  server.registerTool('preview', {
152
206
  title: 'Preview a Nera site',
153
- description: 'Builds a Nera site and serves it on this computer (`nera dev`), rebuilding whenever a page, template or setting changes, and returns the local address (e.g. http://localhost:3000/) for the user to open in a browser. Calling it again for the same site returns the running server\'s address; edits show up there by themselves. Pass `stop: true` to stop it. The server stops when this MCP server closes. If it fails, call validate to find the cause.',
207
+ description: 'Builds a Nera site and serves it on this computer (`nera dev`), rebuilding whenever a page, template or setting changes, and returns the local address (e.g. http://localhost:3000/) for the user to open in a browser. Calling it again for the same site returns the running server\'s address. After a change the user may need to reload the page in the browser to see it. Pass `stop: true` to stop it. The server stops when this MCP server closes. If it fails, call validate to find the cause.',
154
208
  inputSchema: {
155
209
  site: siteInput,
156
210
  stop: z.boolean().optional().describe('Stop the site\'s running preview instead of starting one. Default false.'),
@@ -190,7 +244,7 @@ export function registerLongRunningTools(server, ctx) {
190
244
  }
191
245
  return ok(
192
246
  { site: resolved.site, url, reused },
193
- `${reused ? 'The preview is running' : 'Started the preview'} at ${url}. Give the user this address; it updates by itself when files change.`,
247
+ `${reused ? 'The preview is running' : 'Started the preview'} at ${url}. Give the user this address. The site rebuilds after every change; the user may need to reload the page to see it.`,
194
248
  )
195
249
  }))
196
250
 
@@ -209,6 +263,12 @@ export function registerLongRunningTools(server, ctx) {
209
263
  const key = `publish:${resolved.dir}`
210
264
  let run = ctx.processes.get(key)
211
265
  if (!run) {
266
+ // an older CLI announces no browser step as an event, so the user would never see the sign-in code
267
+ const version = neraVersion(resolved.dir)
268
+ if (!meetsFloor(version, PUBLISH_CLI_FLOOR)) {
269
+ const runs = version ? `@nera-static/nera ${version}` : 'a @nera-static/nera whose version cannot be read'
270
+ throw new ToolError(`Publishing "${resolved.site}" runs ${runs}; publish needs ${PUBLISH_CLI_FLOOR} or later. Run \`npm update\` in the site, then call publish again.`)
271
+ }
212
272
  run = ctx.processes.start(key, 'nera', publishArgs(options), { cwd: resolved.dir })
213
273
  }
214
274
  const before = pendingAction(run.stderr)
@@ -30,12 +30,38 @@ async function readPackage(dir) {
30
30
  }
31
31
  }
32
32
 
33
+ /**
34
+ * @param {object|null} pkg a parsed package.json
35
+ * @returns {Record<string, string>} its dependencies and devDependencies
36
+ */
33
37
  function allDependencies(pkg) {
34
38
  return { ...pkg?.devDependencies, ...pkg?.dependencies }
35
39
  }
36
40
 
37
- function isNeraSite(pkg) {
38
- return Boolean(allDependencies(pkg)[CLI_PACKAGE])
41
+ /**
42
+ * @param {object|null} pkg a parsed package.json
43
+ * @returns {boolean} whether it is a Nera site's: it depends on `@nera-static/nera`
44
+ */
45
+ export function isNeraSite(pkg) {
46
+ return Boolean(neraRange(pkg))
47
+ }
48
+
49
+ /**
50
+ * @param {object|null} pkg a parsed package.json
51
+ * @returns {string|undefined} the `@nera-static/nera` range it depends on
52
+ */
53
+ export function neraRange(pkg) {
54
+ return allDependencies(pkg)[CLI_PACKAGE]
55
+ }
56
+
57
+ /**
58
+ * @param {object|null} pkg a parsed package.json
59
+ * @returns {string[]} the Nera plugins it depends on, sorted
60
+ */
61
+ export function sitePlugins(pkg) {
62
+ return Object.keys(allDependencies(pkg))
63
+ .filter((name) => name.startsWith(PLUGIN_PREFIX) && !NOT_PLUGINS.has(name))
64
+ .sort()
39
65
  }
40
66
 
41
67
  /**
@@ -110,7 +136,7 @@ export async function findSites(root) {
110
136
  found.push({
111
137
  site: relativeTo(root, dir),
112
138
  name: pkg.name ?? null,
113
- nera: allDependencies(pkg)[CLI_PACKAGE],
139
+ nera: neraRange(pkg),
114
140
  })
115
141
  return
116
142
  }
@@ -158,14 +184,12 @@ export function registerSiteTools(server, ctx) {
158
184
  }, tool(async ({ site }) => {
159
185
  const resolved = await resolveSite(ctx, site)
160
186
  const { model, pagesDir } = await siteFolders(resolved.dir)
161
- const plugins = Object.keys(allDependencies(resolved.pkg))
162
- .filter((name) => name.startsWith(PLUGIN_PREFIX) && !NOT_PLUGINS.has(name))
163
- .sort()
187
+ const plugins = sitePlugins(resolved.pkg)
164
188
  const pages = await listPages(resolved.dir, pagesDir)
165
189
  const structured = {
166
190
  site: resolved.site,
167
191
  name: resolved.pkg.name ?? null,
168
- nera: allDependencies(resolved.pkg)[CLI_PACKAGE],
192
+ nera: neraRange(resolved.pkg),
169
193
  app: model.appConfig,
170
194
  appConfigError: model.appConfigError,
171
195
  folders: model.folders,