dsh-remote 1.5.0 → 1.6.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,10 +1,50 @@
1
- // The routes in index.js are bounded JSON handlers, not arbitrary HTTP proxy
2
- // handlers. Keep their implementation shared with legacy Web hosts while using
3
- // Connection's authenticated, carrier-neutral channel on portless Desktop.
1
+ // Share plugin handlers with legacy Web hosts while using Connection's
2
+ // authenticated, carrier-neutral Fetch channel on Desktop.
4
3
  import { Readable } from 'node:stream'
5
4
 
6
5
  const MAX_BODY_BYTES = 1024 * 1024
7
6
 
7
+ function streamBody(chunks, signal) {
8
+ let onAbort
9
+ let stopped = false
10
+ const stop = () => {
11
+ stopped = true
12
+ signal.removeEventListener('abort', onAbort)
13
+ }
14
+ return new ReadableStream({
15
+ start(controller) {
16
+ onAbort = () => {
17
+ stop()
18
+ controller.error(signal.reason)
19
+ // SFTP range reads close their own handle. Finish the iterator as soon
20
+ // as any in-flight read settles, without delaying the client's abort.
21
+ void chunks.return().catch(() => {})
22
+ }
23
+ if (signal.aborted) onAbort()
24
+ else signal.addEventListener('abort', onAbort, { once: true })
25
+ },
26
+ async pull(controller) {
27
+ try {
28
+ const { done, value } = await chunks.next()
29
+ if (stopped) return
30
+ if (done) {
31
+ stop()
32
+ controller.close()
33
+ } else {
34
+ controller.enqueue(value)
35
+ }
36
+ } catch (error) {
37
+ stop()
38
+ controller.error(error)
39
+ }
40
+ },
41
+ cancel() {
42
+ stop()
43
+ return chunks.return()
44
+ },
45
+ }, { highWaterMark: 0 })
46
+ }
47
+
8
48
  export function connectionRoute(route) {
9
49
  // Only the prefix is a real invariant here. `kind`/`exact` belongs to
10
50
  // dsh-host-webserver's registry (WebRouteKind); Connection's
@@ -49,16 +89,21 @@ export function connectionRoute(route) {
49
89
  const req = Readable.from(size ? [Buffer.concat(chunks, size)] : [])
50
90
  req.method = request.method
51
91
  req.url = route.path + url.search
92
+ req.signal = request.signal
52
93
  const headers = new Headers()
53
94
  let response
54
95
  const res = {
55
96
  statusCode: 200,
56
97
  setHeader(key, value) { headers.set(key, value) },
57
98
  end(body) { response = new Response(body, { status: this.statusCode, headers }) },
99
+ stream(chunks) { this.end(streamBody(chunks, request.signal)) },
58
100
  }
59
101
  try {
60
102
  await route.handler(req, res)
61
- if (!response) throw new Error('JSON handler did not finish its response')
103
+ if (!response) {
104
+ request.signal.throwIfAborted()
105
+ throw new Error('JSON handler did not finish its response')
106
+ }
62
107
  return response
63
108
  } finally {
64
109
  req.destroy()
@@ -168,8 +213,30 @@ export function registerHttpTransports(ctx, routes) {
168
213
  // Apply DSH's own browser fence to every legacy route; the Connection
169
214
  // service is read per request so a late-arriving authenticator still counts.
170
215
  const guarded = routes.map((route) => guardRoute(route, () => ctx.get('connection')))
171
- const disposers = guarded.map((route) => inner.get('webServer').register(route))
216
+ // Issue #227: register routes ONE AT A TIME, so a duplicate on route k
217
+ // does not strand routes 1..k-1 on an unloaded plugin. webServer.register
218
+ // returns a bare disposer and THROWS on a duplicate; the old
219
+ // guarded.map(...) + a single trailing effect() never reached that
220
+ // effect() when route k threw, so the earlier registrations outlived the
221
+ // plugin (401 instead of 404) and re-enabling collided with them until
222
+ // the host restarted. Each disposer is collected as it is produced, and
223
+ // ONE effect hands the whole list to the child fiber — a throw from
224
+ // route k therefore still reaches the effect line below, which disposes
225
+ // every registration this callback actually made (the earlier ones), and
226
+ // only those.
227
+ const disposers = []
228
+ const failed = []
229
+ for (const route of guarded) {
230
+ try {
231
+ disposers.push(inner.get('webServer').register(route))
232
+ } catch (err) {
233
+ failed.push(route.path + ': ' + String((err && err.message) || err))
234
+ }
235
+ }
172
236
  inner.effect(() => () => disposers.forEach((dispose) => dispose()), 'dsh-remote.web-routes')
237
+ if (failed.length) {
238
+ console.warn('[dsh-remote] some webServer routes did not register:', failed.join('; '))
239
+ }
173
240
  })
174
241
  ctx.inject(['connection'], (inner) => {
175
242
  const connection = inner.get('connection')
package/lib/ignore.js CHANGED
@@ -4,7 +4,9 @@ import { readFileSync } from 'node:fs'
4
4
  // Deliberately a SUBSET of gitignore semantics (documented, no surprises):
5
5
  // - blank lines and `#` comments are skipped
6
6
  // - `!` negation is NOT supported (later rules never un-ignore)
7
- // - a trailing `/` matches directories only (and everything under them)
7
+ // - a trailing `/` matches directories only — the matcher honors the isDir
8
+ // argument its callers pass, so a plain FILE named `build` is not ignored —
9
+ // and everything under an ignored directory is ignored too
8
10
  // - a pattern containing `/` (or starting with `/`) is anchored to the
9
11
  // workspace root; otherwise it matches the basename at ANY depth
10
12
  // - `*` matches any run of chars except `/`; `**` matches any run incl. `/`;
@@ -32,44 +34,85 @@ function globToRe(glob) {
32
34
  return out
33
35
  }
34
36
 
37
+ /**
38
+ * Parse ONE ignore line into `{ pattern, dirOnly, anchored }`, or null for a
39
+ * blank / comment line.
40
+ *
41
+ * Shared with the POSIX search fast path (lib/search.js), which turns these into
42
+ * `rg`/`grep` exclude flags: one parser means the shell path cannot drift
43
+ * from the matcher the SFTP walk uses. `anchored` is true when the rule is
44
+ * relative to the search root — a leading `/`, or any `/` left after the
45
+ * markers are stripped.
46
+ */
47
+ export function parseIgnoreRule(raw) {
48
+ let line = String(raw || '').trim()
49
+ if (!line || line.startsWith('#')) return null
50
+ let dirOnly = false
51
+ if (line.endsWith('/')) { dirOnly = true; line = line.slice(0, -1) }
52
+ let anchored = line.startsWith('/')
53
+ if (anchored) line = line.slice(1)
54
+ if (!line) return null
55
+ return { pattern: line, dirOnly, anchored: anchored || line.includes('/') }
56
+ }
57
+
35
58
  /**
36
59
  * Compile a list of ignore patterns into a matcher.
37
60
  * @param {string[]|string} patterns lines or an array of lines
38
61
  * @returns {(relPath: string, isDir?: boolean) => boolean} true = ignored.
39
- * `relPath` is POSIX-style ('/' separated, no leading '/').
62
+ * `relPath` is POSIX-style ('/' separated, no leading '/'). `isDir` says
63
+ * whether the ENTRY itself is a directory: a trailing-slash rule ignores
64
+ * the entry only when isDir is true (false or unknown = not a directory),
65
+ * while a rule matching a proper ANCESTOR still ignores everything under
66
+ * an ignored directory — the case test/root-workspace.test.js pins for
67
+ * `/proc/` (issue #60, commit 29584ab).
40
68
  */
41
69
  export function compileIgnore(patterns) {
42
70
  const rules = []
43
71
  const lines = Array.isArray(patterns) ? patterns : String(patterns || '').split('\n')
44
- for (let raw of lines) {
45
- let line = String(raw || '').trim()
46
- if (!line || line.startsWith('#')) continue
47
- let dirOnly = false
48
- if (line.endsWith('/')) { dirOnly = true; line = line.slice(0, -1) }
49
- let anchored = line.startsWith('/')
50
- if (anchored) line = line.slice(1)
51
- if (!line) continue
52
- const hasSlash = line.includes('/')
53
- const isAnchored = anchored || hasSlash
72
+ for (const raw of lines) {
73
+ const rule = parseIgnoreRule(raw)
74
+ if (!rule) continue
75
+ const { pattern: line, dirOnly } = rule
54
76
  const segRe = globToRe(line)
77
+ // `re` matches the rule against the ENTRY itself. `underRe` (dir-only
78
+ // rules only) additionally matches when the rule names a proper ANCESTOR
79
+ // of the entry: such a component is a directory by definition, so
80
+ // everything under an ignored directory stays ignored whatever the entry
81
+ // itself is.
55
82
  let re
56
- if (isAnchored) {
83
+ let underRe = null
84
+ if (rule.anchored) {
57
85
  // Root-anchored: match the full path from the root.
58
- re = dirOnly
59
- ? new RegExp('^' + segRe + '(/.*)?$')
60
- : new RegExp('^' + segRe + '$')
86
+ re = new RegExp('^' + segRe + '$')
87
+ if (dirOnly) underRe = new RegExp('^' + segRe + '/')
61
88
  } else {
62
- // Basename at any depth; a dir pattern also covers everything under it.
63
- re = dirOnly
64
- ? new RegExp('(^|/)' + segRe + '(/|$)')
65
- : new RegExp('(^|/)' + segRe + '$')
89
+ // Basename at any depth.
90
+ re = new RegExp('(^|/)' + segRe + '$')
91
+ if (dirOnly) underRe = new RegExp('(^|/)' + segRe + '/')
66
92
  }
67
- rules.push({ re, dirOnly })
93
+ rules.push({ re, dirOnly, underRe })
68
94
  }
69
95
  return function isIgnored(relPath, isDir) {
70
96
  const rel = String(relPath || '').replace(/^\/+/, '').replace(/\\/g, '/')
71
97
  if (!rel) return false
72
98
  for (const r of rules) {
99
+ if (r.dirOnly) {
100
+ // A trailing-slash rule matches directories ONLY. The named component
101
+ // is either a proper ancestor of the entry (always ignored — callers
102
+ // that walk the tree also prune the directory itself first) or the
103
+ // entry itself, and then isDir decides: when isDir is false or unknown
104
+ // the entry is not known to be a directory, so the rule must not
105
+ // ignore it — a plain FILE named `build` syncs through. Callers that
106
+ // cannot know (pushOneFile writing one file) pass false for exactly
107
+ // this reason. This continues the caller/matcher contract line of
108
+ // issue #60 (commit 29584ab), which taught rw_search to pass
109
+ // root-relative paths here; the matcher now honors the isDir flag
110
+ // every caller already passes.
111
+ if (r.underRe.test(rel)) return true
112
+ if (isDir && r.re.test(rel)) return true
113
+ continue
114
+ }
115
+ // No trailing slash: matches files and directories alike, as before.
73
116
  if (r.re.test(rel)) return true
74
117
  }
75
118
  return false