@dreamlake/dreamlake-cli 0.97.1 → 0.98.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.
Files changed (41) hide show
  1. package/dist/api/client.d.ts +1 -1
  2. package/dist/api/client.js +4 -4
  3. package/dist/api/http.d.ts +48 -1
  4. package/dist/api/http.js +111 -4
  5. package/dist/api/index.d.ts +17 -513
  6. package/dist/api/index.js +6 -2
  7. package/dist/api/note-edits.d.ts +40 -2
  8. package/dist/api/note-edits.js +197 -2
  9. package/dist/api/note-events.d.ts +40 -4
  10. package/dist/api/note-events.js +55 -2
  11. package/dist/api/note-facade.d.ts +268 -0
  12. package/dist/api/note-facade.js +376 -0
  13. package/dist/api/note-reading.d.ts +27 -0
  14. package/dist/api/note-reading.js +27 -0
  15. package/dist/api/note-write.d.ts +110 -0
  16. package/dist/api/note-write.js +217 -0
  17. package/dist/api/notes.d.ts +33 -44
  18. package/dist/api/notes.js +44 -34
  19. package/dist/api/sessions.d.ts +5 -5
  20. package/dist/cli/client.d.ts +2 -41
  21. package/dist/cli/client.js +13 -90
  22. package/dist/cli/help-examples.generated.js +1 -1
  23. package/dist/cli/notes/api-transport.js +6 -6
  24. package/dist/cli/notes/document.d.ts +32 -26
  25. package/dist/cli/notes/document.js +150 -95
  26. package/dist/cli/notes/edit-commands.d.ts +26 -5
  27. package/dist/cli/notes/edit-commands.js +163 -36
  28. package/dist/cli/notes/events.d.ts +3 -33
  29. package/dist/cli/notes/events.js +4 -51
  30. package/dist/cli/notes/html-read.d.ts +6 -0
  31. package/dist/cli/notes/html-read.js +12 -0
  32. package/dist/cli/notes/index.d.ts +10 -1
  33. package/dist/cli/notes/index.js +98 -27
  34. package/dist/cli/notes/move-command.d.ts +4 -0
  35. package/dist/cli/notes/move-command.js +7 -0
  36. package/dist/cli/sessions/runner/native.js +14 -4
  37. package/dist/cli/sessions/runner/serve.d.ts +1 -1
  38. package/dist/cli/vault/sshTransfer.d.ts +1 -1
  39. package/dist/cli/version.d.ts +1 -1
  40. package/dist/cli/version.js +1 -1
  41. package/package.json +9 -9
@@ -51,16 +51,24 @@ export declare function runNotesFind(query: string | undefined, opts: ConnOpts &
51
51
  flags?: string;
52
52
  json?: boolean;
53
53
  limit?: string;
54
+ at?: string;
55
+ caseSensitive?: boolean;
54
56
  }): Promise<number>;
55
57
  export declare function runNotesToc(opts: ConnOpts & {
56
58
  note?: string;
57
59
  json?: boolean;
58
60
  html?: boolean;
61
+ at?: string;
59
62
  }): Promise<number>;
60
63
  type MutateOpts = ConnOpts & {
61
64
  note?: string;
62
65
  selector?: string;
66
+ /** A mapped element address (`s1.p2`) from the reading view: its full original span. */
67
+ address?: string;
63
68
  text?: string;
69
+ /** Exact UTF-8 text from a file (`-` for stdin) instead of --text. */
70
+ file?: string;
71
+ lines?: string;
64
72
  regex?: string;
65
73
  flags?: string;
66
74
  line?: string;
@@ -74,20 +82,33 @@ type MutateOpts = ConnOpts & {
74
82
  legacy?: boolean;
75
83
  baseRevision?: string;
76
84
  exact?: boolean;
85
+ commandId?: string;
77
86
  };
87
+ /** `notes replace|delete NOTE_ID --lines a:b …`: with a span selector and no --note, a
88
+ * 24-hex positional is the note, not a query (Notes API: IDs are primary). */
89
+ export declare function positionalNote<T extends {
90
+ note?: string;
91
+ lines?: string;
92
+ line?: string;
93
+ address?: string;
94
+ ind?: string;
95
+ }>(query: string | undefined, opts: T): [string | undefined, T];
78
96
  export declare function runNotesReplace(query: string | undefined, opts: MutateOpts & {
79
97
  html?: string;
80
98
  }): Promise<number>;
99
+ /** `notes delete` and its contract alias `notes remove`: delete selected source, never the Note. */
81
100
  export declare function runNotesDelete(query: string | undefined, opts: MutateOpts): Promise<number>;
82
101
  /** Set an element's inner source verbatim. Markup, not escaped. */
83
102
  export declare function elementHtmlPlan(source: string, css: string, html: string): EditPlan;
84
103
  export declare function setElementHtml(source: string, css: string, html: string): string;
85
- export declare function runNotesInsert(opts: MutateOpts & {
104
+ type InsertOpts = MutateOpts & {
86
105
  position?: string;
87
- legacy?: boolean;
88
- baseRevision?: string;
89
- exact?: boolean;
90
- }): Promise<number>;
106
+ before?: string;
107
+ after?: string;
108
+ cursor?: string;
109
+ };
110
+ /** `notes insert [NOTE] --before|--after ADDRESS | --cursor N | --line N | --ind N | --selector CSS`; the note may be positional (IDs are primary). */
111
+ export declare function runNotesInsert(noteOrOpts: string | undefined | InsertOpts, maybeOpts?: InsertOpts): Promise<number>;
91
112
  /** `dreamlake notes select "#contact" --note NOTE` */
92
113
  export declare function runNotesSelect(css: string, opts: ConnOpts & {
93
114
  note?: string;
@@ -21,11 +21,14 @@
21
21
  * after step 2.
22
22
  */
23
23
  import { AmbiguousMatch, EditError, NoMatch, find, insert, insertPlacement, replacementPlan, removalPlan, applyEditPlan, remove, replace, } from "./editing.js";
24
- import { readDocumentSnapshot, documentInsertion, documentEdits, submitDocumentPatch, printPatchReceipt, documentWriteError } from "./document.js";
24
+ import { readDocumentSnapshot, documentInsertion, documentEdits, submitDocumentPatch, printPatchReceipt, documentWriteError, commandIdFlag, withCommandId, parseLines } from "./document.js";
25
+ import { notesApi } from "../../api/notes.js";
26
+ import { lineRange, InvalidLineRange } from "../../api/note-reading.js";
27
+ import { noteTransport } from "./api-transport.js";
25
28
  import { markdownToc, htmlToc } from "./toc.js";
26
29
  // The connection plumbing lives in the main notes module; importing it keeps
27
30
  // one definition of "how do I reach the server".
28
- import { ctx, report, resolveNote, seg } from "./index.js";
31
+ import { ctx, report, resolveNote, seg, bodyFrom } from "./index.js";
29
32
  import { AmbiguousElement, NoElement, SelectorError, parse, select, textPieces, } from "./html.js";
30
33
  import { emitJson, fail } from "../helpers.js";
31
34
  import { requestJson } from "../client.js";
@@ -168,6 +171,10 @@ function reportEdit(err) {
168
171
  fail(err.message);
169
172
  return EXIT_NO_MATCH;
170
173
  }
174
+ if (err instanceof InvalidLineRange) {
175
+ fail(err.message);
176
+ return EXIT_NO_MATCH;
177
+ }
171
178
  if (err instanceof EditError) {
172
179
  fail(err.message);
173
180
  return EXIT_NO_MATCH;
@@ -186,16 +193,17 @@ export async function runNotesFind(query, opts) {
186
193
  const id = await resolveNote(c, ref);
187
194
  if (!id)
188
195
  return 1;
189
- const body = await readBody(c, id);
190
- const matches = find(body.text, query, {
191
- regex: opts.regex,
192
- flags: opts.flags,
193
- limit: opts.limit ? Number(opts.limit) : undefined,
194
- });
196
+ // The v2 snapshot: matches carry the original RTC revision, not a legacy ETag, and --at pins one.
197
+ const source = await readDocumentSnapshot(c, id, opts.at);
198
+ const limit = opts.limit ? Number(opts.limit) : undefined;
199
+ // Literal queries are case-sensitive; --no-case-sensitive searches the escaped literal with the i flag.
200
+ const matches = query !== undefined && opts.caseSensitive === false
201
+ ? find(source.content, undefined, { regex: query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), flags: "i", limit })
202
+ : find(source.content, query, { regex: opts.regex, flags: opts.flags, limit });
195
203
  if (opts.json) {
196
204
  // The revision travels with the result: a caller that acts on a match
197
205
  // needs the revision those offsets were computed against.
198
- emitJson({ etag: body.etag, matches });
206
+ emitJson({ note: source.note, hash: source.hash, revision: source.revision, matches });
199
207
  return 0;
200
208
  }
201
209
  for (const m of matches) {
@@ -220,10 +228,10 @@ export async function runNotesToc(opts) {
220
228
  const id = await resolveNote(c, ref);
221
229
  if (!id)
222
230
  return 1;
223
- const body = await readBody(c, id);
224
- const entries = opts.html ? htmlToc(body.text) : markdownToc(body.text);
231
+ const source = await readDocumentSnapshot(c, id, opts.at);
232
+ const entries = opts.html ? htmlToc(source.content) : markdownToc(source.content);
225
233
  if (opts.json) {
226
- emitJson({ etag: body.etag, entries });
234
+ emitJson({ note: source.note, hash: source.hash, revision: source.revision, entries });
227
235
  return 0;
228
236
  }
229
237
  for (const e of entries) {
@@ -280,8 +288,63 @@ async function mutate(opts, apply) {
280
288
  return reportEdit(e);
281
289
  }
282
290
  }
291
+ /** `--text` or `--file` (exact UTF-8, `-` for stdin): one of them. null after a reported refusal, undefined when neither was given. */
292
+ async function editText(opts) {
293
+ if (opts.text !== undefined && opts.file !== undefined) {
294
+ fail("pass one of --text or --file, not both");
295
+ return null;
296
+ }
297
+ if (opts.file === undefined)
298
+ return opts.text;
299
+ try {
300
+ return await bodyFrom({ file: opts.file }, true);
301
+ }
302
+ catch (error) {
303
+ fail(error instanceof Error ? error.message : String(error));
304
+ return null;
305
+ }
306
+ }
307
+ /** A mapped address names the full original span of that element at the snapshot's revision. */
308
+ async function addressSpan(c, id, source, address) {
309
+ const range = await notesApi(noteTransport(c), c.ns).addressRange(id, address, source.revision);
310
+ return [range.start, range.end];
311
+ }
312
+ /** `notes replace|delete NOTE_ID --lines a:b …`: with a span selector and no --note, a
313
+ * 24-hex positional is the note, not a query (Notes API: IDs are primary). */
314
+ export function positionalNote(query, opts) {
315
+ const selector = opts.lines !== undefined || opts.line !== undefined || opts.address !== undefined || opts.ind !== undefined;
316
+ if (query !== undefined && opts.note === undefined && selector && /^[a-f0-9]{24}$/i.test(query))
317
+ return [undefined, { ...opts, note: query }];
318
+ return [query, opts];
319
+ }
320
+ /** `--address` and `--lines` each name the span by themselves. */
321
+ function spanAlone(query, opts) {
322
+ const spans = [opts.address !== undefined, opts.lines !== undefined].filter(Boolean).length;
323
+ if (spans === 0)
324
+ return true;
325
+ if (spans > 1 || query !== undefined || opts.regex !== undefined || opts.line !== undefined || opts.ind !== undefined || opts.selector !== undefined) {
326
+ fail("--address or --lines names the span by itself; it cannot combine with a query, --regex, --line, --ind, --selector or each other");
327
+ return false;
328
+ }
329
+ return true;
330
+ }
331
+ /** `--lines a:b`: the exact code-point span of those lines, terminators included, replaced literally.
332
+ * Nothing is added and nothing is clamped: the same lineRange the facade and `read --lines` use. */
333
+ function literalLineSpan(source, lines, text) {
334
+ let pair;
335
+ try {
336
+ pair = parseLines(lines);
337
+ }
338
+ catch (error) {
339
+ throw new EditError(error.message);
340
+ }
341
+ const { chars } = lineRange(source.content, pair);
342
+ return [[chars[0], chars[1], text]];
343
+ }
283
344
  /** Modern editors submit plans computed against one immutable source snapshot. */
284
345
  async function mutateDocument(opts, plan) {
346
+ if (!commandIdFlag(opts))
347
+ return 1;
285
348
  if (opts.baseRevision !== undefined && (!opts.baseRevision.trim() || opts.baseRevision === "*" || /[\r\n]/.test(opts.baseRevision))) {
286
349
  fail("--base-revision requires the original retained revision");
287
350
  return 1;
@@ -297,8 +360,8 @@ async function mutateDocument(opts, plan) {
297
360
  if (!id)
298
361
  return 1;
299
362
  const source = await readDocumentSnapshot(c, id, opts.baseRevision);
300
- const edits = plan(source.content);
301
- const payload = documentEdits(source, edits.map(([start, end, text]) => ({ start, end, text })), opts.exact);
363
+ const edits = await plan(source, { c, id });
364
+ const payload = withCommandId(documentEdits(source, edits.map(([start, end, text]) => ({ start, end, text })), opts.exact), opts);
302
365
  if (opts.dryRun) {
303
366
  const text = applyEditPlan(source.content, edits);
304
367
  if (opts.json)
@@ -318,7 +381,7 @@ async function mutateDocument(opts, plan) {
318
381
  return 0;
319
382
  }
320
383
  catch (error) {
321
- if (error instanceof EditError || error instanceof NoElement || error instanceof AmbiguousElement || error instanceof SelectorError)
384
+ if (error instanceof EditError || error instanceof InvalidLineRange || error instanceof NoElement || error instanceof AmbiguousElement || error instanceof SelectorError)
322
385
  return reportEdit(error);
323
386
  return documentWriteError(error);
324
387
  }
@@ -328,13 +391,28 @@ function modernFlagsCompatible(opts) {
328
391
  fail("--legacy/--force/--if-match cannot combine with --base-revision or --exact");
329
392
  return false;
330
393
  }
394
+ if ((opts.legacy || opts.force || opts.ifMatch !== undefined) && (opts.address !== undefined || opts.lines !== undefined)) {
395
+ fail("--address/--lines are v2 selectors; they cannot combine with --legacy, --force or --if-match");
396
+ return false;
397
+ }
398
+ if ((opts.legacy || opts.force || opts.ifMatch !== undefined) && opts.commandId !== undefined) {
399
+ fail("--command-id requires the v2 write; it cannot combine with --legacy, --force or --if-match");
400
+ return false;
401
+ }
331
402
  return true;
332
403
  }
333
404
  export async function runNotesReplace(query, opts) {
405
+ [query, opts] = positionalNote(query, opts);
334
406
  if (!modernFlagsCompatible(opts))
335
407
  return 1;
408
+ const text = await editText(opts);
409
+ if (text === null)
410
+ return 1;
411
+ opts = { ...opts, text, file: undefined };
336
412
  if (opts.legacy || opts.force || opts.ifMatch !== undefined)
337
413
  return runLegacyNotesReplace(query, opts);
414
+ if (!spanAlone(query, opts))
415
+ return 1;
338
416
  if (opts.text !== undefined && opts.html !== undefined) {
339
417
  fail("--text is escaped and --html is not; give one");
340
418
  return 1;
@@ -348,24 +426,42 @@ export async function runNotesReplace(query, opts) {
348
426
  fail("--html replaces the whole element's contents; it cannot be combined with a query");
349
427
  return 1;
350
428
  }
351
- return mutateDocument(opts, source => elementHtmlPlan(source, opts.selector, opts.html));
429
+ return mutateDocument(opts, source => elementHtmlPlan(source.content, opts.selector, opts.html));
352
430
  }
353
431
  if (opts.text === undefined) {
354
- fail("--text is the replacement; say what to put there");
432
+ fail("--text (or --file) is the replacement; say what to put there");
355
433
  return 1;
356
434
  }
435
+ if (opts.lines !== undefined)
436
+ return mutateDocument(opts, source => literalLineSpan(source, opts.lines, opts.text));
437
+ if (opts.address !== undefined)
438
+ return mutateDocument(opts, async (source, context) => {
439
+ const [start, end] = await addressSpan(context.c, context.id, source, opts.address);
440
+ return [[start, end, opts.text]];
441
+ });
357
442
  return mutateDocument(opts, source => opts.selector
358
- ? elementReplacementPlan(source, opts.selector, opts.text, whereFrom(query, opts))
359
- : replacementPlan(source, opts.text, whereFrom(query, opts)));
443
+ ? elementReplacementPlan(source.content, opts.selector, opts.text, whereFrom(query, opts))
444
+ : replacementPlan(source.content, opts.text, whereFrom(query, opts)));
360
445
  }
446
+ /** `notes delete` and its contract alias `notes remove`: delete selected source, never the Note. */
361
447
  export async function runNotesDelete(query, opts) {
448
+ [query, opts] = positionalNote(query, opts);
362
449
  if (!modernFlagsCompatible(opts))
363
450
  return 1;
364
451
  if (opts.legacy || opts.force || opts.ifMatch !== undefined)
365
452
  return runLegacyNotesDelete(query, opts);
453
+ if (!spanAlone(query, opts))
454
+ return 1;
455
+ if (opts.lines !== undefined)
456
+ return mutateDocument(opts, source => literalLineSpan(source, opts.lines, ""));
457
+ if (opts.address !== undefined)
458
+ return mutateDocument(opts, async (source, context) => {
459
+ const [start, end] = await addressSpan(context.c, context.id, source, opts.address);
460
+ return [[start, end, ""]];
461
+ });
366
462
  return mutateDocument(opts, source => opts.selector
367
- ? elementReplacementPlan(source, opts.selector, "", whereFrom(query, opts))
368
- : removalPlan(source, whereFrom(query, opts)));
463
+ ? elementReplacementPlan(source.content, opts.selector, "", whereFrom(query, opts))
464
+ : removalPlan(source.content, whereFrom(query, opts)));
369
465
  }
370
466
  async function runLegacyNotesReplace(query, opts) {
371
467
  if (opts.text !== undefined && opts.html !== undefined) {
@@ -401,25 +497,52 @@ export function elementHtmlPlan(source, css, html) {
401
497
  export function setElementHtml(source, css, html) {
402
498
  return applyEditPlan(source, elementHtmlPlan(source, css, html));
403
499
  }
404
- export async function runNotesInsert(opts) {
500
+ /** `notes insert [NOTE] --before|--after ADDRESS | --cursor N | --line N | --ind N | --selector CSS`; the note may be positional (IDs are primary). */
501
+ export async function runNotesInsert(noteOrOpts, maybeOpts) {
502
+ let opts = typeof noteOrOpts === "object" && noteOrOpts !== null ? noteOrOpts : (maybeOpts ?? {});
503
+ if (typeof noteOrOpts === "string") {
504
+ if (opts.note !== undefined && opts.note !== noteOrOpts) {
505
+ fail(`two notes given: '${noteOrOpts}' and --note '${opts.note}' — give one`);
506
+ return 1;
507
+ }
508
+ opts = { ...opts, note: noteOrOpts };
509
+ }
510
+ const text = await editText(opts);
511
+ if (text === null)
512
+ return 1;
513
+ opts = { ...opts, text, file: undefined };
514
+ if (opts.cursor !== undefined) {
515
+ if (opts.ind !== undefined) {
516
+ fail("--cursor and --ind are the same position; give one");
517
+ return 1;
518
+ }
519
+ opts = { ...opts, ind: opts.cursor, cursor: undefined };
520
+ }
405
521
  const compatibility = opts.legacy || opts.force || opts.ifMatch !== undefined;
406
522
  if (compatibility) {
407
523
  if (opts.baseRevision !== undefined || opts.exact) {
408
524
  fail("--legacy/--force/--if-match cannot combine with --base-revision or --exact");
409
525
  return 1;
410
526
  }
527
+ if (opts.commandId !== undefined) {
528
+ fail("--command-id requires the v2 write; it cannot combine with --legacy, --force or --if-match");
529
+ return 1;
530
+ }
531
+ if (opts.before !== undefined || opts.after !== undefined) {
532
+ fail("--before/--after are v2 placements; they cannot combine with --legacy, --force or --if-match");
533
+ return 1;
534
+ }
411
535
  return runLegacyNotesInsert(opts);
412
536
  }
413
- if (opts.text === undefined) {
414
- fail("--text is what to insert");
537
+ if (!commandIdFlag(opts))
415
538
  return 1;
416
- }
417
- if (opts.selector && (opts.line !== undefined || opts.ind !== undefined)) {
418
- fail("--selector and --line/--ind name different places; give one");
539
+ if (opts.text === undefined) {
540
+ fail("--text (or --file) is what to insert");
419
541
  return 1;
420
542
  }
421
- if (!opts.selector && (opts.line === undefined) === (opts.ind === undefined)) {
422
- fail("give exactly one of --line, --ind, or --selector");
543
+ const placements = [opts.selector !== undefined, opts.line !== undefined, opts.ind !== undefined, opts.before !== undefined, opts.after !== undefined].filter(Boolean).length;
544
+ if (placements !== 1) {
545
+ fail("give exactly one placement: --before ADDRESS, --after ADDRESS, --cursor N, --line N, --ind N or --selector CSS");
423
546
  return 1;
424
547
  }
425
548
  if (opts.baseRevision !== undefined && (!opts.baseRevision.trim() || opts.baseRevision === "*" || /[\r\n]/.test(opts.baseRevision))) {
@@ -437,13 +560,17 @@ export async function runNotesInsert(opts) {
437
560
  if (!id)
438
561
  return 1;
439
562
  const source = await readDocumentSnapshot(c, id, opts.baseRevision);
440
- const placement = opts.selector
441
- ? { at: elementInsertionPosition(source.content, opts.selector, opts.position ?? "append"), text: opts.text }
442
- : insertPlacement(source.content, opts.text, {
443
- line: opts.line === undefined ? undefined : singlePosition(opts.line, "--line"),
444
- ind: opts.ind === undefined ? undefined : singlePosition(opts.ind, "--ind"),
445
- });
446
- const payload = documentInsertion(source, placement.at, placement.text, opts.exact);
563
+ // `before` is the start of the element's full original span, `after` its end.
564
+ const address = opts.before ?? opts.after;
565
+ const placement = address !== undefined
566
+ ? await addressSpan(c, id, source, address).then(([start, end]) => ({ at: opts.before !== undefined ? start : end, text: opts.text }))
567
+ : opts.selector
568
+ ? { at: elementInsertionPosition(source.content, opts.selector, opts.position ?? "append"), text: opts.text }
569
+ : insertPlacement(source.content, opts.text, {
570
+ line: opts.line === undefined ? undefined : singlePosition(opts.line, "--line"),
571
+ ind: opts.ind === undefined ? undefined : singlePosition(opts.ind, "--ind"),
572
+ });
573
+ const payload = withCommandId(documentInsertion(source, placement.at, placement.text, opts.exact), opts);
447
574
  if (opts.dryRun) {
448
575
  const chars = Array.from(source.content);
449
576
  const text = chars.slice(0, placement.at).join("") + placement.text + chars.slice(placement.at).join("");
@@ -1,36 +1,6 @@
1
+ /** CLI adapter: the parser lives in `src/api/note-events.ts`; this supplies the CLI's request. */
1
2
  import { requestRaw } from '../client.js';
2
- export type Selection = null | {
3
- status: 'unresolved';
4
- } | {
5
- status: 'resolved';
6
- anchor: number;
7
- head: number;
8
- start: number;
9
- end: number;
10
- unit: 'unicode-code-point';
11
- text: string;
12
- truncated: boolean;
13
- };
14
- export interface Participant {
15
- client: string;
16
- user: {
17
- id: string;
18
- name: string;
19
- kind: 'human' | 'agent';
20
- owner?: {
21
- id: string;
22
- name: string;
23
- };
24
- };
25
- selection?: Selection;
26
- }
27
- export interface NoteEvent {
28
- type: 'observation';
29
- note: string;
30
- hash: string;
31
- observedAt: number;
32
- participants: Participant[];
33
- activityVersion: string;
34
- }
3
+ import { type NoteEvent } from '../../api/note-events.js';
4
+ export type { Selection, Participant, NoteEvent } from '../../api/note-events.js';
35
5
  /** Fetch SSE with auth headers, abort/idle bounds, and no automatic replay across gaps. */
36
6
  export declare function readNoteEvents(url: string, token: string, note: string, signal: AbortSignal, receive: (event: NoteEvent) => void, request?: typeof requestRaw): Promise<void>;
@@ -1,54 +1,7 @@
1
+ /** CLI adapter: the parser lives in `src/api/note-events.ts`; this supplies the CLI's request. */
1
2
  import { requestRaw } from '../client.js';
3
+ import { readNoteEvents as readEvents } from '../../api/note-events.js';
2
4
  /** Fetch SSE with auth headers, abort/idle bounds, and no automatic replay across gaps. */
3
- export async function readNoteEvents(url, token, note, signal, receive, request = requestRaw) {
4
- const idle = new AbortController();
5
- let timer;
6
- const touch = () => { clearTimeout(timer); timer = setTimeout(() => idle.abort(new Error('Notes event stream timed out')), 45000); };
7
- touch();
8
- let reader;
9
- try {
10
- const res = await request(url, { token, headers: { Accept: 'text/event-stream' },
11
- signal: AbortSignal.any([signal, idle.signal]), followRedirects: false });
12
- if (!/^text\/event-stream(?:;|$)/i.test(res.headers.get('content-type') ?? '') || !res.body)
13
- throw new Error('server does not support Notes events; upgrade the server');
14
- reader = res.body.getReader();
15
- const decoder = new TextDecoder('utf-8', { fatal: true });
16
- let buffer = '', data = [], frameSize = 0;
17
- while (!signal.aborted) {
18
- const { done, value } = await reader.read();
19
- if (done)
20
- throw new Error('Notes event stream disconnected; run --linger again for a fresh snapshot');
21
- touch();
22
- buffer += decoder.decode(value, { stream: true });
23
- if (buffer.length > 4_000_000)
24
- throw new Error('Notes event frame exceeds limit');
25
- let newline;
26
- while ((newline = buffer.indexOf('\n')) >= 0) {
27
- const line = buffer.slice(0, newline).replace(/\r$/, '');
28
- buffer = buffer.slice(newline + 1);
29
- if (line.startsWith('data:')) {
30
- const part = line.slice(5).replace(/^ /, '');
31
- frameSize += part.length;
32
- if (frameSize > 4_000_000)
33
- throw new Error('Notes event frame exceeds limit');
34
- data.push(part);
35
- }
36
- else if (!line && data.length) {
37
- const event = JSON.parse(data.join('\n'));
38
- data = [];
39
- frameSize = 0;
40
- if (event.type === 'error')
41
- throw new Error(`Notes event stream ended (${String(event.error)})`);
42
- if (event.type !== 'observation' || event.note !== note || !/^sha256:[a-f0-9]{64}$/.test(event.hash) ||
43
- !Array.isArray(event.participants) || typeof event.activityVersion !== 'string')
44
- throw new Error('invalid Notes event response');
45
- receive(event);
46
- }
47
- }
48
- }
49
- }
50
- finally {
51
- clearTimeout(timer);
52
- await reader?.cancel().catch(() => { });
53
- }
5
+ export function readNoteEvents(url, token, note, signal, receive, request = requestRaw) {
6
+ return readEvents(url, token, note, signal, receive, request);
54
7
  }
@@ -5,5 +5,11 @@ export declare function validateHtmlSnapshot(html: string, note: string, scope?:
5
5
  }): {
6
6
  revision: string;
7
7
  };
8
+ /** The absolute code-point range (`data-source-start`/`data-source-end`) of a scoped snapshot that
9
+ * validateHtmlSnapshot accepted; null for a whole-note read. */
10
+ export declare function scopedSourceRange(html: string): {
11
+ start: number;
12
+ end: number;
13
+ } | null;
8
14
  /** A reading view only: comments are generated hints, never canonical note source. */
9
15
  export declare function annotatedMarkdown(html: string): string;
@@ -61,6 +61,18 @@ export function validateHtmlSnapshot(html, note, scope = {}) {
61
61
  throw new Error("HTML canonical source does not match its returned hash");
62
62
  return { revision };
63
63
  }
64
+ /** The absolute code-point range (`data-source-start`/`data-source-end`) of a scoped snapshot that
65
+ * validateHtmlSnapshot accepted; null for a whole-note read. */
66
+ export function scopedSourceRange(html) {
67
+ const root = /^<!doctype html>\s*<html\b([^>]*)>/i.exec(html);
68
+ if (!root)
69
+ return null;
70
+ const attrs = new Map(Array.from(root[1].matchAll(/\s+([a-zA-Z][a-zA-Z0-9-]*)="([^"]*)"/g), m => [m[1].toLowerCase(), attributeValue(m[2])]));
71
+ const start = attrs.get("data-source-start"), end = attrs.get("data-source-end");
72
+ if (!/^\d+$/.test(start ?? "") || !/^\d+$/.test(end ?? ""))
73
+ return null;
74
+ return { start: Number(start), end: Number(end) };
75
+ }
64
76
  /** A reading view only: comments are generated hints, never canonical note source. */
65
77
  export function annotatedMarkdown(html) {
66
78
  const attrs = (raw) => new Map(Array.from(raw.matchAll(/\s+([a-zA-Z][a-zA-Z0-9-]*)="([^"]*)"/g), m => [m[1], attributeValue(m[2])]));
@@ -40,9 +40,16 @@ export declare function report(err: unknown): number;
40
40
  * happens to be titled similarly.
41
41
  */
42
42
  export declare function resolveNote(c: Ctx, ref: string): Promise<string | null>;
43
+ /** Body text from --file, --text, or stdin. Exactly one, so an empty write is
44
+ * always deliberate rather than the result of a forgotten flag. */
45
+ export declare function bodyFrom(opts: {
46
+ file?: string;
47
+ text?: string;
48
+ }, nativeSourceStdin?: boolean): Promise<string | null>;
43
49
  export declare function registerNotesCommand(program: Command): void;
44
50
  export declare function runNotesList(opts: ConnOpts & {
45
51
  limit?: string;
52
+ offset?: string;
46
53
  shared?: boolean;
47
54
  includeArchived?: boolean;
48
55
  json?: boolean;
@@ -66,6 +73,7 @@ export declare function runNotesWrite(ref: string, opts: ConnOpts & {
66
73
  exact?: boolean;
67
74
  json?: boolean;
68
75
  dryRun?: boolean;
76
+ commandId?: string;
69
77
  }): Promise<number>;
70
78
  export declare function runNotesAppend(ref: string, opts: ConnOpts & {
71
79
  file?: string;
@@ -76,8 +84,9 @@ export declare function runNotesAppend(ref: string, opts: ConnOpts & {
76
84
  exact?: boolean;
77
85
  json?: boolean;
78
86
  dryRun?: boolean;
87
+ commandId?: string;
79
88
  }): Promise<number>;
80
- export declare function runNotesCreate(name: string, opts: ConnOpts & {
89
+ export declare function runNotesCreate(name: string | undefined, opts: ConnOpts & {
81
90
  file?: string;
82
91
  text?: string;
83
92
  public?: boolean;