@self-review/serve 2.0.4 → 2.1.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 (76) hide show
  1. package/README.md +297 -3
  2. package/dist/chunk-CDBNWCCT.js +71 -0
  3. package/dist/chunk-CDBNWCCT.js.map +1 -0
  4. package/dist/chunk-THN5XTYQ.js +151 -0
  5. package/dist/chunk-THN5XTYQ.js.map +1 -0
  6. package/dist/cli.js +2140 -489
  7. package/dist/cli.js.map +1 -1
  8. package/dist/client/assets/{abnfDiagram-VCTEODGH-CRvWpEsk.js → abnfDiagram-VCTEODGH-Dxm_OGm7.js} +1 -1
  9. package/dist/client/assets/{arc-PsXBAWZS.js → arc-BkF-Cs_1.js} +1 -1
  10. package/dist/client/assets/{architectureDiagram-5GKGNRK7-C3DgmaC3.js → architectureDiagram-5GKGNRK7-zB4eyVpl.js} +1 -1
  11. package/dist/client/assets/{blockDiagram-I7D4REHJ-BUrTsHao.js → blockDiagram-I7D4REHJ-cinsJzJ1.js} +1 -1
  12. package/dist/client/assets/{c4Diagram-7LVT6UL2-CpZNs6lz.js → c4Diagram-7LVT6UL2-D4TGkD91.js} +1 -1
  13. package/dist/client/assets/channel-BsuWTbtj.js +1 -0
  14. package/dist/client/assets/{chunk-2Q5K7J3B-BcKcR0LE.js → chunk-2Q5K7J3B-C8HjvUMv.js} +1 -1
  15. package/dist/client/assets/{chunk-5VM5RSS4-C7oHjssV.js → chunk-5VM5RSS4-45fUpmT8.js} +1 -1
  16. package/dist/client/assets/{chunk-F27PBJKO-BlPczT9-.js → chunk-F27PBJKO-DObAqHRK.js} +1 -1
  17. package/dist/client/assets/{chunk-IMKFNOWR-JWhBhxWO.js → chunk-IMKFNOWR-DPvCBgjP.js} +1 -1
  18. package/dist/client/assets/{chunk-JWPE2WC7-BHqPUvha.js → chunk-JWPE2WC7-D3HxOmIl.js} +1 -1
  19. package/dist/client/assets/{chunk-POPQ4Y6H-F7oDRNF5.js → chunk-POPQ4Y6H-CeetmS6D.js} +1 -1
  20. package/dist/client/assets/{chunk-SVP7TREG-BXZpN96Q.js → chunk-SVP7TREG-BltjJmw4.js} +1 -1
  21. package/dist/client/assets/{chunk-TICWLB2K-DNvFXi10.js → chunk-TICWLB2K-CRp0Zdpy.js} +1 -1
  22. package/dist/client/assets/{chunk-XXDRQBXY-DOvXkBHK.js → chunk-XXDRQBXY-BhqJXAOb.js} +1 -1
  23. package/dist/client/assets/classDiagram-ZZMXUADV-CJ7wz9Pi.js +1 -0
  24. package/dist/client/assets/classDiagram-v2-VYDZK3BY-CJ7wz9Pi.js +1 -0
  25. package/dist/client/assets/{cose-bilkent-JH36ORCC-DPJK_EQL.js → cose-bilkent-JH36ORCC-D29IHBME.js} +1 -1
  26. package/dist/client/assets/{cynefin-OW5HDTMX-JBAmnTQp.js → cynefin-OW5HDTMX-DbO7Hdnr.js} +1 -1
  27. package/dist/client/assets/{cynefinDiagram-5FMLGOSQ-CsYygsrr.js → cynefinDiagram-5FMLGOSQ-AmW3TeXb.js} +1 -1
  28. package/dist/client/assets/{dagre-GXQ25YYZ-Dbz4M33p.js → dagre-GXQ25YYZ-BIyWjaCd.js} +1 -1
  29. package/dist/client/assets/{diagram-S7CK7UJ4-Biv-Q_jb.js → diagram-S7CK7UJ4-CBHWhWpQ.js} +1 -1
  30. package/dist/client/assets/{diagram-UQ7AKVKN-JRvoicym.js → diagram-UQ7AKVKN-DRTCWqRa.js} +1 -1
  31. package/dist/client/assets/{diagram-VSXAHHWV-VAXOLPk0.js → diagram-VSXAHHWV-GE0ZO13U.js} +1 -1
  32. package/dist/client/assets/{diagram-VX7I27RA-DRmE-ol9.js → diagram-VX7I27RA-BBp26skq.js} +1 -1
  33. package/dist/client/assets/{diagram-Z3DM3KII-CavqQl_8.js → diagram-Z3DM3KII-CSUSeDRk.js} +1 -1
  34. package/dist/client/assets/{ebnfDiagram-PWID7BFC-70cdWXxf.js → ebnfDiagram-PWID7BFC-2RgBVavT.js} +1 -1
  35. package/dist/client/assets/{erDiagram-RLTQ6QDP-Ha04LW0x.js → erDiagram-RLTQ6QDP-DoEVHzNL.js} +1 -1
  36. package/dist/client/assets/{flowDiagram-HODETNUW-BRLi1S7q.js → flowDiagram-HODETNUW-BLeHpICc.js} +1 -1
  37. package/dist/client/assets/{ganttDiagram-EL5Y4UJY-BfBVCQ3A.js → ganttDiagram-EL5Y4UJY-BE4gCIyJ.js} +1 -1
  38. package/dist/client/assets/{gitGraphDiagram-WWUBYQGX-D-GiQOxC.js → gitGraphDiagram-WWUBYQGX-BuuJ4_PE.js} +1 -1
  39. package/dist/client/assets/index-D1YcCF2h.css +1 -0
  40. package/dist/client/assets/{index-vUb9LsiF.js → index-P5EmeykP.js} +247 -220
  41. package/dist/client/assets/{infoDiagram-27XIBGKW-KEMBoX9p.js → infoDiagram-27XIBGKW-Dj6SJlyc.js} +1 -1
  42. package/dist/client/assets/{ishikawaDiagram-5VMMS53U-CBS0T3w-.js → ishikawaDiagram-5VMMS53U-BVxSH4Dd.js} +1 -1
  43. package/dist/client/assets/{journeyDiagram-3NMN7TZE-AN4puIAJ.js → journeyDiagram-3NMN7TZE-BQIb4zis.js} +1 -1
  44. package/dist/client/assets/{kanban-definition-UXKFOSKX-BWQivApD.js → kanban-definition-UXKFOSKX-zswZjsPL.js} +1 -1
  45. package/dist/client/assets/{layout-B7etliRi.js → layout-i9tH82X4.js} +1 -1
  46. package/dist/client/assets/{linear-DYVJ9r-o.js → linear-CGCu0_8r.js} +1 -1
  47. package/dist/client/assets/{mermaid.core-B9m3791z.js → mermaid.core-DGOIMnVG.js} +5 -5
  48. package/dist/client/assets/{mindmap-definition-YA3MSWOX-BwhaRhOg.js → mindmap-definition-YA3MSWOX-DXzfof8m.js} +1 -1
  49. package/dist/client/assets/{pegDiagram-XKGWAZYB-B6zVpKjE.js → pegDiagram-XKGWAZYB-CmhgC38j.js} +1 -1
  50. package/dist/client/assets/{pieDiagram-E7YTZNPT-DGmD4H1L.js → pieDiagram-E7YTZNPT-iiATrVql.js} +1 -1
  51. package/dist/client/assets/{quadrantDiagram-AXDQQJYC-CrKpGbBm.js → quadrantDiagram-AXDQQJYC-eENXXuDO.js} +1 -1
  52. package/dist/client/assets/{railroadDiagram-O6MQD6OU-DLcnTQsv.js → railroadDiagram-O6MQD6OU-Ve9DVyyu.js} +1 -1
  53. package/dist/client/assets/{requirementDiagram-BXWQKSXE-bqG-UOfq.js → requirementDiagram-BXWQKSXE-Ds3SiU76.js} +1 -1
  54. package/dist/client/assets/{sankeyDiagram-P5KCCOFB-DGRQqw-s.js → sankeyDiagram-P5KCCOFB-Ca_9nHzQ.js} +1 -1
  55. package/dist/client/assets/{sequenceDiagram-WJ2MYXX4-CW-ivDp5.js → sequenceDiagram-WJ2MYXX4-YB9gvQgl.js} +1 -1
  56. package/dist/client/assets/{sizeCapture-INFHLROL-BbHjPnUF.js → sizeCapture-INFHLROL-CNrWHUe0.js} +1 -1
  57. package/dist/client/assets/{stateDiagram-D77RDMKH-BproWKBe.js → stateDiagram-D77RDMKH-MSnDTD49.js} +1 -1
  58. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-BqISu6Sp.js +1 -0
  59. package/dist/client/assets/{swimlanes-42K2YHIH-OG2jZQn8.js → swimlanes-42K2YHIH-DA1GpdIB.js} +1 -1
  60. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-DSERx6Gl.js +8 -0
  61. package/dist/client/assets/{timeline-definition-24CTP7MA-DQeIsWHU.js → timeline-definition-24CTP7MA-CKkqwVz6.js} +1 -1
  62. package/dist/client/assets/{vennDiagram-4TSXK5OY-CzLpoCxP.js → vennDiagram-4TSXK5OY-Bu9SbqJ4.js} +1 -1
  63. package/dist/client/assets/{wardleyDiagram-VM6X3IG4-Bga8iF2e.js → wardleyDiagram-VM6X3IG4-DCUikUwQ.js} +1 -1
  64. package/dist/client/assets/{xychartDiagram-S5SC5T6Z-BMPq9UWm.js → xychartDiagram-S5SC5T6Z-DS3iQdcW.js} +1 -1
  65. package/dist/client/index.html +2 -2
  66. package/dist/json-body-worker.js +16 -0
  67. package/dist/json-body-worker.js.map +1 -0
  68. package/dist/resume-parser-worker.js +30 -0
  69. package/dist/resume-parser-worker.js.map +1 -0
  70. package/package.json +4 -3
  71. package/dist/client/assets/channel-mzvzhynH.js +0 -1
  72. package/dist/client/assets/classDiagram-ZZMXUADV-BAE1ijM-.js +0 -1
  73. package/dist/client/assets/classDiagram-v2-VYDZK3BY-BAE1ijM-.js +0 -1
  74. package/dist/client/assets/index-hcoT-WH0.css +0 -1
  75. package/dist/client/assets/stateDiagram-v2-MP3YSRHH-Ck8yo6ic.js +0 -1
  76. package/dist/client/assets/swimlanesDiagram-VR7AAH4N-CgYw65ZN.js +0 -8
package/README.md CHANGED
@@ -7,6 +7,18 @@ It is the same review engine (`@self-review/core`) and the same UI (`@self-revie
7
7
  desktop application. Only the transport differs: HTTP and a browser tab in place of IPC and a
8
8
  window.
9
9
 
10
+ ## Client read cancellation
11
+
12
+ The browser adapter supplies the optional `ReviewAdapter.reads` capability for lazy hunks, context
13
+ expansion, reviewed images and comment attachments. Caller cancellation composes with the page
14
+ lifetime and the read deadline, including response-body consumption. A pre-aborted read sends no
15
+ HTTP request. Disposal, success, failure and cancellation release listeners and deadline timers. The
16
+ capability remains in memory and authorization headers are preserved.
17
+
18
+ The original adapter methods and the requester's three- and four-argument call forms remain
19
+ supported. Read failures require an explicit retry. Publication and source Apply retain their
20
+ mutation semantics, including unknown outcomes and no automatic replay.
21
+
10
22
  ## Run it
11
23
 
12
24
  ```bash
@@ -104,8 +116,193 @@ A review over 32 MB on the wire is refused before it is sent, with its size in t
104
116
  attachments are the usual cause — they travel base64-encoded, which adds a third — so remove or
105
117
  shrink some and finish again. A server-side `413` for the same reason is reported the same way.
106
118
 
107
- Closing the tab warns you first, once you have entered something. Your comments live only in that
108
- page until you finish, so closing without finishing loses them.
119
+ While Finish Review is pending, the review controls and keyboard shortcuts are blocked so the
120
+ submitted snapshot stays unchanged. A refusal restores editing with the review intact. Read requests
121
+ have a 30-second deadline, and Apply and Finish Review have a 60-second deadline, including reading
122
+ the response body. Failed initial diff loads can be retried; the retry also loads the walkthrough
123
+ guide.
124
+
125
+ An Apply acknowledgement must carry the existing applied/refused discriminator, the requested file
126
+ path and all fields of that outcome. An applied result also needs a nonnegative integer
127
+ `replacedLines`; a refusal needs string `reason` and `detail` fields. An empty or malformed 2xx
128
+ reply keeps Apply locked behind the inspection step, including after collapsing the file.
129
+
130
+ A timeout, lost connection, malformed acknowledgement, or unexpected server error after sending a
131
+ mutation can leave its outcome unknown. The page says so instead of claiming that nothing was
132
+ written. After an uncertain Finish Review, the submitted snapshot stays locked and the close warning
133
+ stays, and Finish Review is unavailable to prevent a blind duplicate submission. Check the terminal
134
+ and the output file, stop the original process, and restart with `--resume-from` if the review was
135
+ saved. An uncertain Apply likewise requires checking the destination before continuing. Mutations
136
+ are never retried automatically. A publisher's explicit refusal remains safely retryable.
137
+
138
+ Closing the tab warns you after comments or viewed flags change, including deleting the last resumed
139
+ comment or clearing a viewed flag. The warning stays until the server acknowledges the save. Your
140
+ work lives only in that page until you finish, so closing without finishing loses it.
141
+
142
+ Only one submission can publish at a time. An overlapping authenticated `POST /api/review` receives
143
+ `409` with `{"error":"review submission already in progress or complete"}`. A failed attempt permits
144
+ retry. Successful acknowledgement still means the XML is on disk. After flushing that response, the
145
+ listener stops accepting connections and drains admitted operations and their responses for up to
146
+ five seconds before closing remaining connections. Exit 0 follows once admitted work and cleanup
147
+ settle; a pending native operation may delay final exit beyond that grace period. SIGINT and SIGTERM
148
+ use the same shutdown owner, including during startup and listener creation, and exit with 130 and
149
+ 143 respectively. An observed signal takes precedence over completion success. Startup has a
150
+ 45-second deadline, and its git commands have a 30-second timeout. With the current core,
151
+ cancellation reaches git, snapshot reads, directory and file loading, attachment preparation, and
152
+ asynchronous asset staging. Publication accepts at most 1,000 attachment occurrences, 10 MiB per
153
+ image and 64 MiB of newly staged assets, including resumed references that need copying. These
154
+ disk-derived limits are independent of the HTTP body limit. Cancellation does not roll back a
155
+ committed file. Synchronous/native work can still delay event-loop callbacks; the grace period is
156
+ not hard preemption of arbitrary code.
157
+
158
+ The listener accepts at most 64 TCP connections, including idle keepalive connections and peers that
159
+ have not finished sending HTTP headers. Excess connections close before parsing a request or logging
160
+ its bytes. Programmatic `createReviewServer` callers may supply a positive integer `maxConnections`;
161
+ the CLI uses 64. Normal keepalive, the 15-second header deadline and the 60-second request deadline
162
+ remain in effect.
163
+
164
+ Static bundle files stream from one opened regular-file descriptor per request in chunks of at most
165
+ 64 KiB, waiting for response backpressure before reading more. Each asset is limited to 32 MiB; a
166
+ larger file receives `413` with `{"error":"static asset exceeds 32 MiB limit"}` before successful
167
+ headers. This limit accommodates the bundled scripts, styles, fonts and diagrams. The original file
168
+ size fixes both Content-Length and the read range, so file growth cannot extend the response. A
169
+ failed or shortened read after headers closes the response as incomplete. Missing files, directories
170
+ and unsafe paths retain the quiet `404` response. Unexpected I/O failures receive a generic `500`
171
+ and go to the injected diagnostic reporter. Containment inspection uses asynchronous metadata calls
172
+ before opening and during the inode recheck, with cancellation checkpoints between calls.
173
+ Missing-path inspection removes one requested path component per lookup and never enumerates a
174
+ directory. Descriptor opens use no-follow and nonblocking flags, reject non-regular files, and
175
+ recheck containment and inode identity. Disconnect, request expiry and shutdown cancel reads and
176
+ backpressure waits. Admission retains the operation until the descriptor closes and the response
177
+ settles. Already issued filesystem calls and kernel socket buffers may finish after cancellation;
178
+ cancellation does not preempt native I/O.
179
+
180
+ The server admits at most 32 operations and responses in total, with at most eight concurrent
181
+ expensive DTO, image or attachment reads. Excess requests receive `503` with
182
+ `{"error":"review server busy; retry after pending requests finish"}` before engine work starts.
183
+ This refusal is safely retryable. Apply, context expansion and publication are mutually exclusive. A
184
+ competing publication retains the existing `409` response above; a competing Apply or expansion gets
185
+ `409` with `{"error":"review source mutation or publication already in progress"}`. Wait for the
186
+ active operation before retrying. Publication cannot overtake an admitted source mutation.
187
+
188
+ Diff, file, config, resume, image and context-expansion JSON responses use bounded data-only DTO
189
+ encoding. Each response is limited to 64 MiB of encoded UTF-8, 2,000,000 visited values or object
190
+ properties, and 128 nesting levels. Limits include escaping and repeated references. A measuring
191
+ pass checks these bounds before successful headers; an over-limit DTO receives `413` without
192
+ omitting hunks. Encoding checks cancellation and yields after 2,048 tokens or 256 KiB of encoded
193
+ work. A second pass streams chunks to the socket and waits for backpressure. It applies the same
194
+ bounds again, so concurrent growth cannot extend delivery indefinitely. An encoding failure after
195
+ headers destroys the incomplete response. Admission stays owned until encoding and response cleanup
196
+ settle. Small Apply/publication acknowledgements and errors use the separate small-response writer,
197
+ which serializes before sending headers.
198
+
199
+ These limits bound transport encoding, not the engine's existing loaded representation. Native
200
+ string operations, object-key enumeration, small-body JSON parsing and garbage collection cannot be
201
+ preempted by a JavaScript deadline. Large request decoding and parsing use the owned worker below.
202
+ The supported older engine also retains the synchronous limitations below.
203
+
204
+ Each admitted request has a 60-second server deadline. Expiry cancels supported work and answers
205
+ `503` with `{"error":"request deadline exceeded; operation outcome may be unknown"}` if headers have
206
+ not been sent, or closes a response already in progress. Disconnecting cancels the request's owned
207
+ work too. An operation keeps its admission slot until both work and response settle, including when
208
+ a filesystem operation ignores cancellation. Shutdown stops accepting and cancels admitted
209
+ operations, then closes remaining connections after five seconds. Owned operations and cleanup
210
+ remain joined until they settle before process exit. Each expiry reports one bounded diagnostic with
211
+ the operation kind and elapsed milliseconds. It includes no request path, query, body or session
212
+ key. Disconnect and shutdown cancellation do not produce deadline diagnostics. Static responses
213
+ close on expiry rather than returning JSON, including before headers.
214
+
215
+ Suggestion Apply requests have a separate 32 MiB JSON UTF-8 budget for original and proposed code,
216
+ matching the review upload budget. The browser refuses larger suggestions before sending them with
217
+ code `suggestion-too-large`; the server enforces the same bound. Desktop and library callers keep
218
+ their existing capabilities. When the installed core exports `applySuggestionForSessionAsync`, serve
219
+ awaits that writer with the request's `signal`. Its default destination input and output limits are
220
+ each 5,242,880 bytes, independent of the HTTP budget; exceeding either resolves as a typed engine
221
+ refusal. With core 2.0.4, serve uses the existing synchronous writer, which blocks and cannot
222
+ interrupt an in-progress write. The compatibility shim can be removed once the published minimum
223
+ core dependency provides the async operation. Context expansion requests retain their 64 KiB bound.
224
+
225
+ Programmatic `createReviewServer` callers may supply a per-instance `reportDiagnostic(message)`
226
+ callback for submission success, known publication refusals, transport failures and deadlines.
227
+ `createPublicationOperations` also forwards its supplied reporter to Core publication diagnostics.
228
+ An installed older Core may still send its own diagnostics to stderr if it ignores that option.
229
+ `ReviewSubmission` also accepts it as an optional second constructor argument.
230
+ `createServeLifecycle` and `completeReviewOnSubmit` accept `reportDiagnostic` for completion and
231
+ shutdown-deadline messages; the CLI binds the same host reporter to its lifecycle. Defaults retain
232
+ the existing stderr messages and argument shapes. Reporter throws, rejected promises and pending
233
+ thenables are observational: they cannot change a committed success or interrupt exit code, delay
234
+ connection closing or owned cleanup, reopen completed admission or retry a write. Synchronous
235
+ reporter code must return control to the host; it cannot be preempted.
236
+
237
+ Core 2.0.4 remains a supported installed peer. On that peer, startup prints diagnostics for the
238
+ synchronous startup probe and Apply, local loading without signal support, and publication without
239
+ an aggregate disk-asset budget or cooperative staging cancellation. The old startup probe and Apply
240
+ block the event loop. A deadline or signal cannot interrupt them or enforce the shutdown grace while
241
+ they run. Serve checks cancellation before invoking legacy Apply and returns its actual outcome
242
+ afterward, including a committed success, without replay. If the response is lost, inspect the
243
+ destination before continuing. A synchronous wrapper cannot add interruption to that writer.
244
+
245
+ Serve bundles the canonical pure DTO validator and request decoder from the focused
246
+ `@self-review/core/validation` build entry. Only that entry is inlined; the root engine stays an
247
+ installed runtime dependency, so core 2.0.4 needs no new export. Current installed validators and
248
+ decoders are selected when present. Bundled validation failures are translated to the installed
249
+ root's `ReviewXmlError` class so existing error handling keeps its class identity.
250
+
251
+ This validator enforces the current attachment count and in-memory byte limits before session
252
+ storage on both peers. It cannot bound old core's disk-derived publication reads or add cancellation
253
+ inside the old writer. The runtime compatibility selectors must stay until a published minimum core
254
+ provides asynchronous startup/loading, asynchronous Apply and bounded cooperative publication. Then
255
+ raise that minimum and remove the corresponding fallbacks together. No unpublished minimum is
256
+ required today.
257
+
258
+ Apply's transport validation checks containers, primitive types and anchor side. A null anchor,
259
+ zero/fractional line number or inverted numeric range reaches core and resolves as its typed refusal
260
+ with HTTP 200, matching the desktop adapter. Reviewed-path authorization and the exact original-code
261
+ check still apply. Context expansion retains its 99,999-line limit.
262
+
263
+ A submitted source must match the loaded source kind and its required path, or its repository and
264
+ git diff arguments. Property order and supported source extension metadata do not affect ownership.
265
+ A mismatch receives a recoverable `422` validation refusal before cached state, XML or assets
266
+ change. Remote provenance and resumed attachment origins always come from the owned session.
267
+
268
+ Only missing attachment files receive `404` and become null in the browser. Unauthorized references,
269
+ unsafe links and non-regular files receive `400`, oversized files receive `413`, and operational I/O
270
+ failures receive `500`, preserving the useful read error.
271
+
272
+ Request JSON is decoded as strict UTF-8 after the complete bounded body arrives. Invalid byte
273
+ sequences receive the existing generic `400` `{"error":"body must be valid JSON"}` before review
274
+ publication, Apply or other operation execution. Valid multibyte characters may span request chunks;
275
+ encoded U+FFFD remains valid text. A leading UTF-8 BOM still receives the same refusal. Media type,
276
+ byte caps and cancellation handling are unchanged.
277
+
278
+ Bodies through 128 KiB decode and parse inline. Larger bodies use a one-shot Node worker for
279
+ concatenation, fatal UTF-8 decoding and JSON parsing. Collection copies bytes incrementally into 64
280
+ KiB transferable blocks, limiting transfer-list size even with tiny incoming chunks. A decoder
281
+ admits at most two large bodies and 64 MiB of reserved input, including collection and termination,
282
+ with no waiting queue. Saturation receives the existing busy error text and HTTP 503. The server's
283
+ exclusive mutation/publication admission usually allows only one such body at a time. The 32 MiB
284
+ per-request cap is unchanged. Disconnect, request expiry and shutdown cancel parsing and join worker
285
+ termination before releasing admission. If termination fails, the worker remains owned until exit;
286
+ shutdown does not claim a hard time bound.
287
+
288
+ The existing tsup build emits `dist/json-body-worker.js` beside `cli.js`; the default factory
289
+ resolves it relative to that module. Build it with `npm run build --workspace @self-review/serve`. A
290
+ source host can supply `jsonBodyProcessing: new JsonBodyProcessing(createWorker)` with a factory for
291
+ its built worker entry. Each server owns that processor through shutdown, so independently retiring
292
+ servers must use separate processors. The four-argument `readJsonBody` form accepts an explicit
293
+ processor; its original three-argument form remains available. Only byte decoding and JSON parsing
294
+ cross the worker boundary. Returning the parsed object still requires host structured cloning;
295
+ attachment decoding, injected validators and engine functions remain on the host and can block it.
296
+ Cancellation cannot preempt those host functions. Deeply nested JSON uses a flat internal transfer
297
+ form to avoid native message-clone recursion limits. It reconstructs the same containers and own
298
+ properties and imposes no additional JSON depth limit; reconstruction also runs on the host.
299
+
300
+ Nested review JSON is validated after attachment decoding and before it enters the session.
301
+ Malformed containers, source kinds, anchors and optional metadata receive a recoverable `400`
302
+ `{"error":"Invalid review state: ..."}`; publication still performs XML validation. Each comment's
303
+ `filePath` must exactly match its containing file's `path`, including the empty review-level path.
304
+ This check also runs through the bundled pure validator when the installed peer is Core 2.0.4; its
305
+ failures retain that peer's error class.
109
306
 
110
307
  The desktop application asks the same question with better options, offering to save on the way out.
111
308
  A browser will not let a page do that: `beforeunload` is a yes or no prompt whose wording belongs to
@@ -122,7 +319,12 @@ starts and the file tree opens in guided mode. Generate one with the `self-revie
122
319
  before starting the server.
123
320
 
124
321
  The guide is read once at startup. Writing a sidecar while the server is already running has no
125
- effect until you restart it.
322
+ effect until you restart it. Programmatic startup may supply a launch directory, diagnostic reporter
323
+ and the six startup effect operations as the optional third `resolveSession` argument; existing one-
324
+ and two-argument calls still use process cwd and stderr. The CLI supplies these explicitly.
325
+ Configured guide paths resolve against that launch directory, including with core 2.0.4, whose
326
+ loader ignores the optional fourth argument. That peer still sends its own guide diagnostics to
327
+ stderr rather than the injected reporter.
126
328
 
127
329
  ## Access control
128
330
 
@@ -193,3 +395,95 @@ forward into the namespace, not a published port.
193
395
  Anyone who can reach the forwarded port _and has the URL_ has the same access you do. The key is a
194
396
  session secret, not a login: treat the printed URL like a password, and securing the tunnel is still
195
397
  yours to do.
398
+
399
+ ## Engine and transport contracts
400
+
401
+ Current Core image-read diagnostics use the host's supplied reporter as well. Published Core 2.0.4
402
+ ignores that optional reporter and retains stderr output for image refusals.
403
+
404
+ Recognized API routes return `405` for an unsupported method with an `Allow` header listing only the
405
+ methods registered for that path. Host, origin and session-key checks still run first. This does not
406
+ add HEAD or OPTIONS handlers.
407
+
408
+ The CLI resolves installed Core capabilities once into a normalized engine contract. Core 2.0.4
409
+ remains supported without disabling Apply, resume or publication. Its synchronous source probe,
410
+ local loading and Apply can delay cancellation; its publication lacks the newer aggregate asset
411
+ budget and cooperative staging cancellation. The CLI reports those limitations at startup. Pure
412
+ request validation stays bundled, and fallback errors retain the installed Core error class.
413
+
414
+ `resolveServeEngine` accepts the capabilities its selectors use. Its `.core` retains the supplied
415
+ object and all inferred members, and the original `ServeEngine` and resolver return types retain the
416
+ complete root namespace. `createPublicationOperations` takes only its read, Apply, validation and
417
+ publication roles. It binds `requestValidation` and the publication error constructor from that same
418
+ engine. Route construction uses those validators for review, Apply and context requests. Original
419
+ operation sets may omit the added roles and retain the installed-engine defaults. The exported
420
+ `parseReviewStateBody`, `parseSuggestionApplyBody` and `parseExpandContextBody` remain default
421
+ compatibility entry points with the same strict field policy and error text.
422
+
423
+ Startup forwards its host reporter through `loadConfigWithProvenance` options. Reporter throws and
424
+ rejections cannot change loaded configuration or provenance. Core 2.0.4 ignores this option and
425
+ keeps its own configuration diagnostics on stderr, as it does for guide and image diagnostics.
426
+
427
+ First-party transport construction uses `createValidatedReviewServer` with bound read operations and
428
+ an explicit publication role from `createValidatedPublicationOperations`. These complete internal
429
+ roles require the selected engine's request validation. Replacement operations and validator objects
430
+ remain observable after route construction. There is no installed-engine fallback in that path.
431
+ `createBoundReviewServer`, `createPublicationOperations` and their original reflected contracts
432
+ remain available with optional validation and the existing compatibility default. Publication owns
433
+ its supplied state and does not first mutate the session's handoff cache. The existing
434
+ `createReviewServer` overloads, `createReviewOperations`, `SubmissionOperations` and
435
+ `ReviewSubmission` constructor retain the original submit-then-publish sequence, including custom
436
+ handoff side effects. The transport and publication reporter contains both synchronous throws and
437
+ asynchronous rejections; default route failure details still go to stderr.
438
+
439
+ Startup's original required synchronous `loadResumeDocument` operation keeps its type and behavior
440
+ for injected operation sets. The optional `loadResumeDocumentAsync` takes the startup signal and
441
+ deadline. When replacing operations from a first-party host, clear that optional member to select
442
+ the original synchronous path. `createStartupHost` selects it for the CLI. It reads and parses XML
443
+ in a worker emitted as `dist/resume-parser-worker.js` beside `cli.js`, resolved relative to that
444
+ module, before loading the guide or opening the listener. Every success, error, deadline and
445
+ cancellation reaps that worker before adopting a result. Replacing an owner must abort its signal;
446
+ an optional `isCurrent` guard also refuses stale replies. Termination may wait for a native syscall.
447
+ After worker release, the first-party loader resolves the document directory asynchronously and
448
+ checks cancellation and ownership again before adopting comments, viewed files and attachment
449
+ origins together. Its optional `paths.realpath(directory)` capability owns that lookup, retains its
450
+ receiver and never retries a failure through the native filesystem. It controls directory lookup;
451
+ XML reading remains in the owned worker. The native default preserves the original canonicalization
452
+ policy, including a lexical fallback if native resolution fails.
453
+
454
+ First-party adoption bundles Core's pure attachment-origin planner, so actual Core 2.0.4 also uses
455
+ the supplied directory without a second runtime engine. The original
456
+ `createResumeLoader(adopt, createWorker)` factory retains its three-argument adopter and its
457
+ original native compatibility behavior, including a supplied adopter's side effects.
458
+
459
+ Browser reads validate diff, guide, config, resume, lazy hunks, context and image DTOs before
460
+ delivery. A malformed read rejects with `malformed-read-response`, preserving existing data and
461
+ subscriptions for explicit repair. Valid null responses, optional fields, extension metadata,
462
+ duplicate paths and the full Core line budgets remain supported. Generic JSON helper call forms
463
+ remain available. Admission busy responses preserve their original error text and add
464
+ `code: "server-busy"`. Modern clients classify that code only on HTTP 503. The exact old uncoded
465
+ busy response remains supported by an isolated legacy policy; other failures keep mutation outcomes
466
+ uncertain and are never replayed.
467
+
468
+ The one-shot owner and resume reply policy are bundled from the build's
469
+ `@self-review/core/resume-worker` subpath. The installed Core root stays external, including with
470
+ Core 2.0.4; workers and hosts reconstruct detailed XML failures with that peer's constructors.
471
+ Timeouts omitted or set to zero use 30 seconds. Positive fractions round up to milliseconds and
472
+ large values clamp at 2,147,483,647 ms; negative and nonfinite values reject. The desktop host now
473
+ accepts these same forms. Cancellation never settles before termination. If termination itself
474
+ rejects, release is unconfirmed and the owner reports a termination failure retaining the original
475
+ failure/cancellation as its cause. Native syscalls can delay worker termination.
476
+
477
+ `createBoundApiRoutes` requires bound operations and complete request validation. It does not select
478
+ an engine or construct validators. Server composition supplies the operations' selected validation;
479
+ the original `createApiRoutes` facade and operation sets without `requestValidation` use the
480
+ compatibility composition factory. An explicit fourth validator still takes precedence. All original
481
+ server overloads remain available. Operations replaced after route construction remain observable.
482
+
483
+ The HTTP body cap applies to bytes received from the client. A resumed attachment reference can name
484
+ up to 10 MiB of disk content without sending those bytes in the request. Published Core 2.0.4 owns
485
+ those reads internally and has no aggregate publication budget or cooperative staging cancellation.
486
+ Pure request validation cannot derive authoritative disk sizes from references, and an extra host
487
+ filesystem probe would neither cover virtual effects nor prevent a later file change. Serve keeps
488
+ that peer's publication support and startup warning. Current Core enforces its aggregate budget
489
+ inside the authoritative reader and writer, preserving the prior document on refusal.
@@ -0,0 +1,71 @@
1
+ // src/json-body-codec.ts
2
+ import { TextDecoder } from "util";
3
+ function decodeJsonBody(chunks) {
4
+ try {
5
+ const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
6
+ Buffer.concat(chunks)
7
+ );
8
+ return { ok: true, value: JSON.parse(text) };
9
+ } catch {
10
+ return { ok: false, status: 400, error: "body must be valid JSON" };
11
+ }
12
+ }
13
+
14
+ // src/json-body-transfer.ts
15
+ function encodeJsonWorkerReply(result) {
16
+ if (!result.ok || !needsFlatTransfer(result.value)) return result;
17
+ const objects = [result.value];
18
+ const nodes = [];
19
+ for (let index = 0; index < objects.length; index++) {
20
+ const value = objects[index];
21
+ const entries = [];
22
+ for (const key of Object.keys(value)) {
23
+ const child = value[key];
24
+ if (child !== null && typeof child === "object") {
25
+ entries.push([key, { ref: objects.length }]);
26
+ objects.push(child);
27
+ } else entries.push([key, child]);
28
+ }
29
+ nodes.push({ array: Array.isArray(value), entries });
30
+ }
31
+ return { ok: true, flat: nodes };
32
+ }
33
+ function needsFlatTransfer(value) {
34
+ const pending = [{ value, depth: 0 }];
35
+ while (pending.length) {
36
+ const { value: value2, depth } = pending.pop();
37
+ if (value2 === null || typeof value2 !== "object") continue;
38
+ if (depth >= 128) return true;
39
+ for (const key of Object.keys(value2)) {
40
+ const child = value2[key];
41
+ if (child !== null && typeof child === "object")
42
+ pending.push({ value: child, depth: depth + 1 });
43
+ }
44
+ }
45
+ return false;
46
+ }
47
+ function decodeJsonWorkerReply(reply) {
48
+ if (!reply.ok || !("flat" in reply)) return reply;
49
+ const values = reply.flat.map((node) => node.array ? [] : {});
50
+ reply.flat.forEach((node, index) => {
51
+ for (const [key, entry] of node.entries) {
52
+ const value = entry !== null && typeof entry === "object" ? values[entry.ref] : entry;
53
+ if (key === "__proto__")
54
+ Object.defineProperty(values[index], key, {
55
+ value,
56
+ enumerable: true,
57
+ writable: true,
58
+ configurable: true
59
+ });
60
+ else values[index][key] = value;
61
+ }
62
+ });
63
+ return { ok: true, value: values[0] };
64
+ }
65
+
66
+ export {
67
+ decodeJsonBody,
68
+ encodeJsonWorkerReply,
69
+ decodeJsonWorkerReply
70
+ };
71
+ //# sourceMappingURL=chunk-CDBNWCCT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/json-body-codec.ts","../src/json-body-transfer.ts"],"sourcesContent":["import { TextDecoder } from 'node:util';\n\nexport type JsonBodyResult =\n | { ok: true; value: unknown }\n | { ok: false; status: number; error: string };\n\n/** The inline and worker paths share strict UTF-8 and the historical BOM refusal. */\nexport function decodeJsonBody(chunks: readonly Uint8Array[]): JsonBodyResult {\n try {\n const text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(\n Buffer.concat(chunks)\n );\n return { ok: true, value: JSON.parse(text) as unknown };\n } catch {\n return { ok: false, status: 400, error: 'body must be valid JSON' };\n }\n}\n","import type { JsonBodyResult } from './json-body-codec';\n\ntype Scalar = string | number | boolean | null;\ntype Entry = [string, Scalar | { ref: number }];\ninterface FlatNode {\n array: boolean;\n entries: Entry[];\n}\nexport type JsonWorkerReply = JsonBodyResult | { ok: true; flat: FlatNode[] };\n\n/** Native message cloning has a recursion limit that JSON.parse does not share. */\nexport function encodeJsonWorkerReply(result: JsonBodyResult): JsonWorkerReply {\n if (!result.ok || !needsFlatTransfer(result.value)) return result;\n const objects: object[] = [result.value as object];\n const nodes: FlatNode[] = [];\n for (let index = 0; index < objects.length; index++) {\n const value = objects[index] as Record<string, unknown>;\n const entries: Entry[] = [];\n for (const key of Object.keys(value)) {\n const child = value[key];\n if (child !== null && typeof child === 'object') {\n entries.push([key, { ref: objects.length }]);\n objects.push(child);\n } else entries.push([key, child as Scalar]);\n }\n nodes.push({ array: Array.isArray(value), entries });\n }\n return { ok: true, flat: nodes };\n}\n\nfunction needsFlatTransfer(value: unknown): boolean {\n const pending = [{ value, depth: 0 }];\n while (pending.length) {\n const { value, depth } = pending.pop()!;\n if (value === null || typeof value !== 'object') continue;\n if (depth >= 128) return true;\n for (const key of Object.keys(value)) {\n const child = (value as Record<string, unknown>)[key];\n if (child !== null && typeof child === 'object')\n pending.push({ value: child, depth: depth + 1 });\n }\n }\n return false;\n}\n\n/** Rebuild JSON containers iteratively, keeping own __proto__ properties inert. */\nexport function decodeJsonWorkerReply(reply: JsonWorkerReply): JsonBodyResult {\n if (!reply.ok || !('flat' in reply)) return reply;\n const values = reply.flat.map(node => (node.array ? [] : {})) as Record<string, unknown>[];\n reply.flat.forEach((node, index) => {\n for (const [key, entry] of node.entries) {\n const value = entry !== null && typeof entry === 'object' ? values[entry.ref] : entry;\n if (key === '__proto__')\n Object.defineProperty(values[index], key, {\n value,\n enumerable: true,\n writable: true,\n config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AAI,QAAQ,IAAI;AACrC,QAAIA,WAAU,QAAQ,OAAOA,WAAU,SAAU;AACjD,QAAI,SAAS,IAAK,QAAO;AACzB,eAAW,OAAO,OAAO,KAAKA,MAAK,GAAG;AACpC,YAAM,QAASA,OAAkC,GAAG;AACpD,UAAI,UAAU,QAAQ,OAAO,UAAU;AACrC,gBAAQ,KAAK,EAAE,OAAO,OAAO,OAAO,QAAQ,EAAE,CAAC;AAAA,IACnD;AAAA,EACF;AACA,SAAO;AACT;AAGO,SAAS,sBAAsB,OAAwC;AAC5E,MAAI,CAAC,MAAM,MAAM,EAAE,UAAU,OAAQ,QAAO;AAC5C,QAAM,SAAS,MAAM,KAAK,IAAI,UAAS,KAAK,QAAQ,CAAC,IAAI,CAAC,CAAE;AAC5D,QAAM,KAAK,QAAQ,CAAC,MAAM,UAAU;AAClC,eAAW,CAAC,KAAK,KAAK,KAAK,KAAK,SAAS;AACvC,YAAM,QAAQ,UAAU,QAAQ,OAAO,UAAU,WAAW,OAAO,MAAM,GAAG,IAAI;AAChF,UAAI,QAAQ;AACV,eAAO,eAAe,OAAO,KAAK,GAAG,KAAK;AAAA,UACxC;AAAA,UACA,YAAY;AAAA,UACZ,UAAU;AAAA,UACV,cAAc;AAAA,QAChB,CAAC;AAAA,UACE,QAAO,KAAK,EAAE,GAAG,IAAI;AAAA,IAC5B;AAAA,EACF,CAAC;AACD,SAAO,EAAE,IAAI,MAAM,OAAO,OAAO,CAAC,EAAE;AACtC;","names":["value"]}
@@ -0,0 +1,151 @@
1
+ // ../core/src/resume-worker-protocol.ts
2
+ function readResumeReply(reply, id, restoreFailure) {
3
+ if (!isRecord(reply) || reply.id !== id) {
4
+ throw new Error("Resume parser returned an unowned reply");
5
+ }
6
+ if (reply.kind === "failed" && isFailure(reply.error)) throw restoreFailure(reply.error);
7
+ if (reply.kind === "parsed" && isRecord(reply.parsed) && Array.isArray(reply.parsed.comments) && Array.isArray(reply.parsed.viewedFiles) && Array.isArray(reply.parsed.importDiagnostics)) {
8
+ return reply.parsed;
9
+ }
10
+ throw new Error("Resume parser returned an invalid reply");
11
+ }
12
+ function isRecord(value) {
13
+ return value !== null && typeof value === "object";
14
+ }
15
+ function isFailure(value) {
16
+ return isRecord(value) && typeof value.message === "string" && ["name", "stack", "code"].every(
17
+ (key) => value[key] === void 0 || typeof value[key] === "string"
18
+ ) && (value.details === void 0 || Array.isArray(value.details) && value.details.every((detail) => typeof detail === "string"));
19
+ }
20
+ function describeResumeFailure(error, xmlDetails) {
21
+ if (!(error instanceof Error)) return { name: "Error", message: String(error) };
22
+ return {
23
+ name: error.name,
24
+ message: error.message,
25
+ stack: error.stack,
26
+ ...xmlDetails(error),
27
+ cause: describeCause(error.cause)
28
+ };
29
+ }
30
+ function restoreResumeFailure(failure, createXmlError) {
31
+ const cause = restoreCause(failure.cause);
32
+ const error = failure.code ? createXmlError(failure.code, failure.message, { details: failure.details, cause }) : Object.assign(new Error(failure.message), cause === void 0 ? {} : { cause });
33
+ if (failure.name !== void 0) error.name = failure.name;
34
+ if (failure.stack) error.stack = failure.stack;
35
+ return error;
36
+ }
37
+ function describeCause(cause) {
38
+ if (!(cause instanceof Error)) return cause;
39
+ const native = cause;
40
+ return {
41
+ name: native.name,
42
+ message: native.message,
43
+ stack: native.stack,
44
+ code: native.code,
45
+ errno: native.errno,
46
+ path: native.path,
47
+ syscall: native.syscall
48
+ };
49
+ }
50
+ function restoreCause(cause) {
51
+ if (!isRecord(cause) || typeof cause.message !== "string") return cause;
52
+ return Object.assign(new Error(cause.message), cause);
53
+ }
54
+
55
+ // ../core/src/resume-worker.ts
56
+ function checkResumeOwnership(options) {
57
+ options.signal?.throwIfAborted();
58
+ if (options.isCurrent && !options.isCurrent()) {
59
+ throw new DOMException("Resume operation is no longer current", "AbortError");
60
+ }
61
+ }
62
+ var ResumeWorkerTerminationError = class extends Error {
63
+ constructor(terminationError, cause) {
64
+ super("Resume parser termination failed; worker release is unconfirmed");
65
+ this.name = "ResumeWorkerTerminationError";
66
+ this.cause = cause;
67
+ this.terminationError = terminationError;
68
+ }
69
+ };
70
+ async function runResumeWorker(worker, request, options, restoreFailure) {
71
+ let cancellation;
72
+ let timer;
73
+ let onMessage;
74
+ let onError;
75
+ let onExit;
76
+ let onAbort;
77
+ const outcome = await new Promise((resolve, reject) => {
78
+ const cancel = (reason) => {
79
+ cancellation ?? (cancellation = { reason });
80
+ reject(cancellation.reason);
81
+ };
82
+ onAbort = () => cancel(options.signal.reason);
83
+ onMessage = (reply) => {
84
+ try {
85
+ resolve(readResumeReply(reply, request.id, restoreFailure));
86
+ } catch (error) {
87
+ reject(error);
88
+ }
89
+ };
90
+ onError = reject;
91
+ onExit = (code) => reject(new Error(`Resume parser exited before replying (code ${code})`));
92
+ worker.on("message", onMessage);
93
+ worker.on("error", onError);
94
+ worker.on("exit", onExit);
95
+ options.signal?.addEventListener("abort", onAbort, { once: true });
96
+ try {
97
+ const requested = options.timeoutMs ?? 3e4;
98
+ if (!Number.isFinite(requested) || requested < 0) {
99
+ throw new RangeError("Resume timeout must be a nonnegative finite number");
100
+ }
101
+ const timeoutMs = requested === 0 ? 3e4 : Math.min(Math.ceil(requested), 2147483647);
102
+ timer = setTimeout(
103
+ () => cancel(new DOMException("Resume parsing timed out", "TimeoutError")),
104
+ timeoutMs
105
+ );
106
+ checkResumeOwnership(options);
107
+ if (!request || typeof request.id !== "string" || typeof request.path !== "string") {
108
+ throw new Error("Invalid resume parser request");
109
+ }
110
+ worker.postMessage(request);
111
+ } catch (error) {
112
+ reject(error);
113
+ }
114
+ }).then(
115
+ (parsed) => ({ ok: true, parsed }),
116
+ (error) => ({ ok: false, error })
117
+ );
118
+ let termination;
119
+ try {
120
+ await worker.terminate();
121
+ } catch (error) {
122
+ termination = { error };
123
+ } finally {
124
+ clearTimeout(timer);
125
+ worker.off("message", onMessage);
126
+ worker.off("error", onError);
127
+ worker.off("exit", onExit);
128
+ options.signal?.removeEventListener("abort", onAbort);
129
+ }
130
+ let failure = cancellation ?? (outcome.ok ? void 0 : { reason: outcome.error });
131
+ try {
132
+ checkResumeOwnership(options);
133
+ } catch (reason) {
134
+ failure = { reason };
135
+ }
136
+ if (termination) {
137
+ if (failure) throw new ResumeWorkerTerminationError(termination.error, failure.reason);
138
+ throw termination.error;
139
+ }
140
+ if (failure) throw failure.reason;
141
+ if (outcome.ok) return outcome.parsed;
142
+ throw outcome.error;
143
+ }
144
+
145
+ export {
146
+ describeResumeFailure,
147
+ restoreResumeFailure,
148
+ checkResumeOwnership,
149
+ runResumeWorker
150
+ };
151
+ //# sourceMappingURL=chunk-THN5XTYQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../core/src/resume-worker-protocol.ts","../../core/src/resume-worker.ts"],"sourcesContent":["import type { ParsedReview } from './xml-parser';\n\nexport interface ResumeParseRequest {\n id: string;\n path: string;\n}\n\n/** Name/stack/cause are additive; legacy serve failures only carried message/code/details. */\nexport interface ResumeParseFailure {\n name?: string;\n message: string;\n stack?: string;\n code?: string;\n details?: readonly string[];\n cause?: unknown;\n}\n\nexport type ResumeParseReply =\n | { id: string; kind: 'parsed'; parsed: ParsedReview }\n | { id: string; kind: 'failed'; error: ResumeParseFailure };\n\n/** Validates the reply envelope without changing the parser's result or optional metadata. */\nexport function readResumeReply(\n reply: unknown,\n id: string,\n restoreFailure: (failure: ResumeParseFailure) => Error\n): ParsedReview {\n if (!isRecord(reply) || reply.id !== id) {\n throw new Error('Resume parser returned an unowned reply');\n }\n if (reply.kind === 'failed' && isFailure(reply.error)) throw restoreFailure(reply.error);\n if (\n reply.kind === 'parsed' &&\n isRecord(reply.parsed) &&\n Array.isArray(reply.parsed.comments) &&\n Array.isArray(reply.parsed.viewedFiles) &&\n Array.isArray(reply.parsed.importDiagnostics)\n ) {\n return reply.parsed as unknown as ParsedReview;\n }\n throw new Error('Resume parser returned an invalid reply');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object';\n}\n\nfunction isFailure(value: unknown): value is ResumeParseFailure {\n return (\n isRecord(value) &&\n typeof value.message === 'string' &&\n ['name', 'stack', 'code'].every(\n key => value[key] === undefined || typeof value[key] === 'string'\n ) &&\n (value.details === undefined ||\n (Array.isArray(value.details) && value.details.every(detail => typeof detail === 'string')))\n );\n}\n\nexport function describeResumeFailure(\n error: unknown,\n xmlDetails: (error: Error) => Pick<ResumeParseFailure, 'code' | 'details'> | undefined\n): ResumeParseFailure {\n if (!(error instanceof Error)) return { name: 'Error', message: String(error) };\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n ...xmlDetails(error),\n cause: describeCause((error as Error & { cause?: unknown }).cause),\n };\n}\n\nexport function restoreResumeFailure(\n failure: ResumeParseFailure,\n createXmlError: (\n code: string,\n message: string,\n options: { details?: readonly string[]; cause?: unknown }\n ) => Error\n): Error {\n const cause = restoreCause(failure.cause);\n const error = failure.code\n ? createXmlError(failure.code, failure.message, { details: failure.details, cause })\n : Object.assign(new Error(failure.message), cause === undefined ? {} : { cause });\n if (failure.name !== undefined) error.name = failure.name;\n if (failure.stack) error.stack = failure.stack;\n return error;\n}\n\n// Native Error structured cloning drops errno/code/path. Preserve read diagnostics explicitly.\nfunction describeCause(cause: unknown): unknown {\n if (!(cause instanceof Error)) return cause;\n const native = cause as NodeJS.ErrnoException;\n return {\n name: native.name,\n message: native.message,\n stack: native.stack,\n code: native.code,\n errno: native.errno,\n path: native.path,\n syscall: native.syscall,\n };\n}\n\nfunction restoreCause(cause: unknown): unknown {\n if (!isRecord(cause) || typeof cause.message !== 'string') return cause;\n return Object.assign(new Error(cause.message), cause);\n}\n","// Host-owned one-shot resume work. No parser, filesystem or runtime Core class imports.\nimport type { Worker } from 'node:worker_threads';\nimport type { ParsedReview } from './xml-parser';\nimport { readResumeReply } from './resume-worker-protocol';\nimport type { ResumeParseFailure, ResumeParseRequest } from './resume-worker-protocol';\nexport * from './resume-worker-protocol';\n\nexport interface ResumeWorkerOptions {\n signal?: AbortSignal;\n /** Omitted/zero: 30s; positive fractions round up; capped at 2^31-1 ms. */\n timeoutMs?: number;\n /** The host must revoke ownership when replacing the operation. */\n isCurrent?: () => boolean;\n}\n\nexport function checkResumeOwnership(options: ResumeWorkerOptions): void {\n options.signal?.throwIfAborted();\n if (options.isCurrent && !options.isCurrent()) {\n throw new DOMException('Resume operation is no longer current', 'AbortError');\n }\n}\n\n/** A rejected terminate cannot establish that cancellation released the worker. */\nexport class ResumeWorkerTerminationError extends Error {\n readonly cause: unknown;\n readonly terminationError: unknown;\n\n constructor(terminationError: unknown, cause: unknown) {\n super('Resume parser termination failed; worker release is unconfirmed');\n this.name = 'ResumeWorkerTerminationError';\n this.cause = cause;\n this.terminationError = terminationError;\n }\n}\n\n/**\n * Owns the supplied worker immediately, even on admission/delivery failure. Never\n * adopts a reply before termination. Abort/deadline remain active until reaped.\n * The host reconstructs failures with its installed peer's error constructors.\n */\nexport async function runResumeWorker(\n worker: Pick<Worker, 'on' | 'off' | 'postMessage' | 'terminate'>,\n request: ResumeParseRequest,\n options: ResumeWorkerOptions,\n restoreFailure: (failure: ResumeParseFailure) => Error\n): Promise<ParsedReview> {\n let cancellation: { reason: unknown } | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let onMessage!: (reply: unknown) => void;\n let onError!: (error: Error) => void;\n let onExit!: (code: number) => void;\n let onAbort!: () => void;\n const outcome = await new Promise<ParsedReview>((resolve, reject) => {\n const cancel = (reason: unknown) => {\n // Retain even falsy abort reasons, and the first deadline/abort identity.\n cancellation ??= { reason };\n reject(cancellation.reason);\n };\n onAbort = () => cancel(options.signal!.reason);\n onMessage = reply => {\n try {\n resolve(readResumeReply(reply, request.id, restoreFailure));\n } catch (error) {\n reject(error);\n }\n };\n onError = reject;\n onExit = code => reject(new Error(`Resume parser exited before replying (code ${code})`));\n worker.on('message', onMessage);\n worker.on('error', onError);\n worker.on('exit', onExit);\n options.signal?.addEventListener('abort', onAbort, { once: true });\n try {\n const requested = options.timeoutMs ?? 30_000;\n if (!Number.isFinite(requested) || requested < 0) {\n throw new RangeError('Resume timeout must be a nonnegative finite number');\n }\n const timeoutMs = requested === 0 ? 30_000 : Math.min(Math.ceil(requested), 2_147_483_647);\n timer = setTimeout(\n () => cancel(new DOMException('Resume parsing timed out', 'TimeoutError')),\n timeoutMs\n );\n checkResumeOwnership(options);\n if (!request || typeof request.id !== 'string' || typeof request.path !== 'string') {\n throw new Error('Invalid resume parser request');\n }\n worker.postMessage(request);\n } catch (error) {\n reject(error);\n }\n }).then(\n parsed => ({ ok: true as const, parsed }),\n (error: unknown) => ({ ok: false as const, error })\n );\n let termination: { error: unknown } | undefined;\n try {\n await worker.terminate();\n } catch (error) {\n termination = { error };\n } finally {\n clearTimeout(timer);\n worker.off('message', onMessage);\n worker.off('error', onError);\n worker.off('exit', onExit);\n options.signal?.removeEventListener('abort', onAbort);\n }\n let failure = cancellation ?? (outcome.ok ? undefined : { reason: outcome.error });\n try {\n checkResumeOwnership(options);\n } catch (reason) {\n failure = { reason };\n }\n if (termination) {\n if (failure) throw new ResumeWorkerTerminationError(termination.error, failure.reason);\n throw termination.error;\n }\n if (failure) throw failure.reason;\n if (outcome.ok) return outcome.parsed;\n throw outcome.error;\n}\n"],"mappings":";AAsBO,SAAS,gBACd,OACA,IACA,gBACc;AACd,MAAI,CAAC,SAAS,KAAK,KAAK,MAAM,OAAO,IAAI;AACvC,UAAM,IAAI,MAAM,yCAAyC;AAAA,EAC3D;AACA,MAAI,MAAM,SAAS,YAAY,UAAU,MAAM,KAAK,EAAG,OAAM,eAAe,MAAM,KAAK;AACvF,MACE,MAAM,SAAS,YACf,SAAS,MAAM,MAAM,KACrB,MAAM,QAAQ,MAAM,OAAO,QAAQ,KACnC,MAAM,QAAQ,MAAM,OAAO,WAAW,KACtC,MAAM,QAAQ,MAAM,OAAO,iBAAiB,GAC5C;AACA,WAAO,MAAM;AAAA,EACf;AACA,QAAM,IAAI,MAAM,yCAAyC;AAC3D;AAEA,SAAS,SAAS,OAAkD;AAClE,SAAO,UAAU,QAAQ,O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