@lovelaces-io/storyteller 0.2.0 → 0.3.1

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.
package/dist/index.d.cts CHANGED
@@ -1,15 +1,158 @@
1
+ /**
2
+ * Which default audience a storyteller registers.
3
+ *
4
+ * - `text` — colorized console output for a person watching
5
+ * - `ndjson` — one JSON object per line for a program reading
6
+ */
7
+ type OutputFormat = "text" | "ndjson";
8
+ /**
9
+ * A level written any of the ways people and agents actually write it.
10
+ * `report("...", { level: "warn" })` should not be a type error.
11
+ */
12
+ type LevelInput = StoryLevel | "info" | "information" | "warn" | "warning" | "oops" | "error";
13
+ /**
14
+ * Resolve any accepted level spelling to a stored level label.
15
+ *
16
+ * @param input - A level in any accepted spelling
17
+ * @returns The canonical StoryLevel, defaulting to Information
18
+ */
19
+ declare function toStoryLevel(input?: LevelInput): StoryLevel;
20
+ /**
21
+ * Read an environment variable, tolerating runtimes that have no environment at all.
22
+ *
23
+ * @param name - Variable name
24
+ * @returns The trimmed value, or undefined when unset or unavailable
25
+ */
26
+ declare function readEnvironmentValue(name: string): string | undefined;
27
+ /**
28
+ * Resolve the minimum level to deliver, from an explicit option then `STORYTELLER_LEVEL`.
29
+ *
30
+ * @param requested - Explicit level, if the caller set one
31
+ * @returns The threshold level, defaulting to Information (deliver everything)
32
+ */
33
+ declare function resolveMinimumLevel(requested?: StoryLevel | string): StoryLevel;
34
+ /**
35
+ * Check whether a level clears the configured minimum.
36
+ *
37
+ * @param level - The emission's level
38
+ * @param minimum - The configured threshold
39
+ */
40
+ declare function meetsLevel(level: StoryLevel, minimum: StoryLevel): boolean;
41
+ /**
42
+ * Resolve which default audience to register, from an explicit option then
43
+ * `STORYTELLER_FORMAT`.
44
+ *
45
+ * Deliberately not inferred from whether stdout is a TTY: output that silently
46
+ * changes shape when a process is piped is a debugging afternoon nobody asked for.
47
+ *
48
+ * @param requested - Explicit format, if the caller set one
49
+ * @returns The format, defaulting to text
50
+ */
51
+ declare function resolveOutputFormat(requested?: OutputFormat): OutputFormat;
52
+ /**
53
+ * Resolve whether to colorize, from an explicit option then `STORYTELLER_COLOR`.
54
+ *
55
+ * @param requested - Explicit choice, if the caller set one
56
+ * @returns Whether colors should be used, defaulting to true
57
+ */
58
+ declare function resolveColors(requested?: boolean): boolean;
59
+
60
+ /** A value that survives JSON.stringify with no loss and no throwing */
61
+ type JsonValue = string | number | boolean | null | JsonValue[] | {
62
+ [key: string]: JsonValue;
63
+ };
64
+ type NormalizeOptions = {
65
+ /** How many levels deep to descend before replacing the value with a truncation marker */
66
+ maxDepth?: number;
67
+ /** How many array entries to keep before truncating */
68
+ maxArrayLength?: number;
69
+ /** How many object properties to keep before truncating */
70
+ maxProperties?: number;
71
+ /** How many characters of a string to keep before truncating */
72
+ maxStringLength?: number;
73
+ /** Property names whose values are replaced with the redaction marker */
74
+ redactKeys?: string[];
75
+ /** Set false to keep secret-shaped values as-is */
76
+ redact?: boolean;
77
+ };
78
+ /** Marker written in place of a value that matched a redacted key name */
79
+ declare const REDACTED = "[redacted]";
80
+ /**
81
+ * Property names whose values are replaced with {@link REDACTED}.
82
+ * Matching ignores case and separators, so `apiKey`, `api_key` and `API-KEY` all match.
83
+ */
84
+ declare const DEFAULT_REDACT_KEYS: string[];
85
+ /**
86
+ * Convert any value into a JSON-safe structure suitable for a story record.
87
+ *
88
+ * Handles the shapes real code actually holds — errors, dates, maps, sets, class
89
+ * instances, binary buffers, circular references, throwing getters — and never throws,
90
+ * so a hostile object logged by a caller cannot break the delivery pipeline.
91
+ *
92
+ * Data dropped for size is replaced with an explicit `@truncated` marker rather than
93
+ * disappearing silently, so a consumer can tell the difference between "this was empty"
94
+ * and "this was too big".
95
+ *
96
+ * @param input - Any value
97
+ * @param options - Depth, size and redaction limits
98
+ * @returns A value that JSON.stringify can always serialize
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * normalizeValue({ user: new Map([["id", 1]]), apiKey: "sk-live-abc" });
103
+ * // { user: { "@type": "Map", entries: { id: 1 } }, apiKey: "[redacted]" }
104
+ * ```
105
+ */
106
+ declare function normalizeValue(input: unknown, options?: NormalizeOptions): JsonValue;
107
+ /**
108
+ * Convert an unknown thrown value into a serializable StoryError,
109
+ * following the `cause` chain and collecting AggregateError members.
110
+ *
111
+ * @param rawError - Any thrown or rejected value
112
+ * @param options - Depth, size and redaction limits applied to attached data
113
+ * @returns A StoryError safe to store and serialize
114
+ */
115
+ declare function normalizeError(rawError: unknown, options?: NormalizeOptions): StoryError;
116
+
1
117
  /** Human-readable level labels stored in story records */
2
118
  type StoryLevel = "Information" | "Warning" | "Error";
3
- type StoryContextValue = Record<string, unknown> | string;
119
+ /**
120
+ * A stored context value. Always JSON-safe — whatever the caller passed in has
121
+ * already been through the normalizer by the time it reaches a record.
122
+ */
123
+ type StoryContextValue = JsonValue;
124
+ /** Context accepted from callers. Anything goes; the normalizer makes it storable. */
125
+ type StoryContextInput = unknown;
4
126
  type StoryError = {
5
127
  name?: string;
6
128
  message?: string;
7
129
  stack?: string;
8
- cause?: unknown;
130
+ cause?: JsonValue;
131
+ /** Members of an AggregateError */
132
+ errors?: StoryError[];
133
+ };
134
+ /** Origin as stored on a record */
135
+ type StoryOrigin = {
136
+ who?: StoryContextValue;
137
+ what?: StoryContextValue;
138
+ where?: StoryContextValue;
139
+ };
140
+ /** Origin as accepted from callers */
141
+ type StoryOriginInput = {
142
+ who?: StoryContextInput;
143
+ what?: StoryContextInput;
144
+ where?: StoryContextInput;
9
145
  };
10
146
  type StoryNote = {
11
147
  timestamp: string;
148
+ /**
149
+ * Position within the story, assigned when the note is taken. Gap-free from 0.
150
+ * Optional so records written before sequencing existed still typecheck.
151
+ */
152
+ sequence?: number;
12
153
  note: string;
154
+ /** Omitted when the note carries the story's default Information level */
155
+ level?: StoryLevel;
13
156
  who?: StoryContextValue;
14
157
  what?: StoryContextValue;
15
158
  where?: StoryContextValue;
@@ -19,13 +162,25 @@ type StoryEventBase = {
19
162
  timestamp: string;
20
163
  level: StoryLevel;
21
164
  title: string;
22
- origin?: {
23
- who?: StoryContextValue;
24
- what?: StoryContextValue;
25
- where?: StoryContextValue;
26
- };
165
+ /**
166
+ * Correlates every note emission with the story it belongs to. Always set on
167
+ * events this library builds; optional so older stored records still typecheck.
168
+ */
169
+ storyId?: string;
170
+ /**
171
+ * The story this one is a chapter of. Absent on a top-level story.
172
+ * Following this field reconstructs the tree of a nested run.
173
+ */
174
+ parentStoryId?: string;
175
+ origin?: StoryOrigin;
27
176
  notes: StoryNote[];
28
177
  durationMs?: number;
178
+ /**
179
+ * How many emissions were dropped for back-pressure while this story was being
180
+ * collected. Present only when something was actually lost, so the loss shows up
181
+ * in the record instead of vanishing.
182
+ */
183
+ droppedEmissions?: number;
29
184
  error?: StoryError;
30
185
  };
31
186
  type ReportOptions = {
@@ -76,88 +231,288 @@ type FormattedReport = {
76
231
  /** @deprecated Use FormattedReport instead */
77
232
  type StorySummary = FormattedReport;
78
233
  type StoryEvent = StoryEventBase & {
234
+ kind: "story";
79
235
  summarize: (options?: ReportOptions) => FormattedReport;
80
236
  };
81
- type AudienceMember = {
237
+ /** @deprecated Use StoryEvent — the story-shaped emission */
238
+ type StoryEmission = StoryEvent;
239
+ /** The two things an audience can hear */
240
+ type EmissionKind = "note" | "story";
241
+ /**
242
+ * A single beat, delivered the moment it happens when narration is live.
243
+ *
244
+ * `storyId` and `sequence` are what make streaming lossless: a consumer holding
245
+ * the beats of a story can order and group them back into the record that
246
+ * collected narration would have produced.
247
+ */
248
+ type NoteEmission = StoryNote & {
249
+ kind: "note";
250
+ storyId: string;
251
+ parentStoryId?: string;
252
+ sequence: number;
253
+ level: StoryLevel;
254
+ origin?: StoryOrigin;
255
+ };
256
+ type Emission = NoteEmission | StoryEvent;
257
+ /** The emission type an audience receives, given the kinds it hears */
258
+ type EmissionOf<Kind extends EmissionKind> = Kind extends "note" ? NoteEmission : StoryEvent;
259
+ /**
260
+ * An audience, typed by what it hears.
261
+ *
262
+ * With no `hears`, it hears stories only and `accepts`/`hear` receive a
263
+ * `StoryEvent` — so an audience written before live narration existed compiles
264
+ * unchanged, including one that hands the event to a helper typed for
265
+ * `StoryEvent`. `hears: ["note"]` gives `NoteEmission`; `["note", "story"]`
266
+ * gives the union, and the code narrows on `kind`.
267
+ */
268
+ type AudienceMember<Kind extends EmissionKind = "story"> = {
82
269
  name: string;
83
- accepts?: (event: StoryEvent) => boolean;
84
- hear: (event: StoryEvent) => void | Promise<void>;
270
+ /** Which emission kinds this audience wants. Defaults to `["story"]`. */
271
+ hears?: Kind[];
272
+ accepts?(emission: EmissionOf<Kind>): boolean;
273
+ hear(emission: EmissionOf<Kind>): void | Promise<void>;
85
274
  };
275
+ /** Any audience, whatever it hears — the shape the registry stores */
276
+ type AnyAudienceMember = AudienceMember<EmissionKind>;
277
+ /**
278
+ * How a storyteller narrates.
279
+ *
280
+ * - `collected` — beats are buffered and leave as one story record (the default)
281
+ * - `live` — each beat is emitted as it happens, and the story still lands at the end
282
+ *
283
+ * Live narration adds emissions, it never removes them: a consumer that only wants
284
+ * beats says so with `hears: ["note"]` rather than by silencing the record.
285
+ */
286
+ type Narration = "collected" | "live";
287
+ /** @deprecated `both` is now the behavior of `live` — beats stream and the story still lands */
288
+ type NarrationInput = Narration | "both";
86
289
  type NoteData = {
87
- who?: StoryContextValue;
88
- what?: StoryContextValue;
89
- where?: StoryContextValue;
290
+ who?: StoryContextInput;
291
+ what?: StoryContextInput;
292
+ where?: StoryContextInput;
90
293
  error?: unknown;
294
+ /** Level for this beat alone. Defaults to Information. */
295
+ level?: LevelInput;
296
+ /** Emit this beat immediately even when narration is collected */
297
+ live?: boolean;
298
+ /** Deliver this beat only to the named audiences */
299
+ to?: string[];
91
300
  };
301
+ type FinishOptions = {
302
+ /** Defaults to Information */
303
+ level?: LevelInput;
304
+ /** The error that ended the story, normalized onto the record */
305
+ error?: unknown;
306
+ };
307
+ type ChapterOptions = {
308
+ /** Merged over the parent's origin */
309
+ origin?: StoryOriginInput;
310
+ /** Defaults to the parent's setting */
311
+ narration?: NarrationInput;
312
+ /** Defaults to the parent's setting */
313
+ level?: LevelInput;
314
+ /** Defaults to the parent's handler */
315
+ onAudienceError?: AudienceErrorHandler;
316
+ /** Defaults to the parent's bound */
317
+ maxInFlight?: number;
318
+ };
319
+ type StorytellerOptions = {
320
+ origin?: StoryOriginInput;
321
+ audiences?: AnyAudienceMember[];
322
+ /** Defaults to `STORYTELLER_NARRATION`, then `collected` */
323
+ narration?: NarrationInput;
324
+ /**
325
+ * Which default audience to register: colorized text for a person, NDJSON for a
326
+ * program. Defaults to `STORYTELLER_FORMAT`, then `text`.
327
+ */
328
+ format?: OutputFormat;
329
+ /**
330
+ * Share another storyteller's audience registry instead of creating one.
331
+ * Audiences added to it later reach this storyteller too. When given, no
332
+ * default audience is registered — the registry already has whatever it has.
333
+ */
334
+ audience?: AudienceRegistry;
335
+ /** The story this one is a chapter of. Set by `chapter()`. */
336
+ parentStoryId?: string;
337
+ /**
338
+ * Drop emissions below this level before they reach any audience.
339
+ * Defaults to `STORYTELLER_LEVEL`, then Information (deliver everything).
340
+ */
341
+ level?: LevelInput;
342
+ /**
343
+ * Called when an audience throws or rejects. Without one, a single throttled
344
+ * warning per audience goes to the console — a logging library that loses
345
+ * records in silence is worse than one that complains.
346
+ */
347
+ onAudienceError?: AudienceErrorHandler;
348
+ /**
349
+ * Cap on deliveries in flight to a single audience at once. Live narration is
350
+ * fire-and-forget, so a slow audience would otherwise grow an unbounded queue.
351
+ * Past the cap, emissions are dropped and counted on the closing story.
352
+ */
353
+ maxInFlight?: number;
354
+ };
355
+ /** Called when an audience member throws or rejects while hearing an emission */
356
+ type AudienceErrorHandler = (error: unknown, member: AnyAudienceMember, emission: Emission) => void;
92
357
  /** Manages the set of audience members that receive story events */
93
358
  declare class AudienceRegistry {
94
359
  private members;
95
360
  /** Register an audience member, replacing any existing member with the same name */
96
- add(member: AudienceMember): this;
361
+ add<Kind extends EmissionKind = "story">(member: AudienceMember<Kind>): this;
97
362
  /** Remove an audience member by name */
98
363
  remove(name: string): this;
99
364
  /** Return all registered audience members */
100
- getAll(): AudienceMember[];
365
+ getAll(): AnyAudienceMember[];
101
366
  /** Return only the audience members matching the given names */
102
- getOnly(names: string[]): AudienceMember[];
367
+ getOnly(names: string[]): AnyAudienceMember[];
103
368
  /** Check if an audience member is registered by name */
104
369
  has(name: string): boolean;
105
370
  /** List the names of all registered audience members */
106
371
  names(): string[];
107
372
  }
108
373
  /**
109
- * Collects timestamped notes and emits them as a single structured story event.
374
+ * Collects timestamped notes and emits them as one structured story — and, when
375
+ * narration is live, emits each note the moment it is taken.
110
376
  *
111
377
  * @example
112
378
  * ```ts
113
- * const story = new Storyteller({ origin: { who: "api-server" } });
114
- * story.note("Request received", { what: { path: "/checkout" } });
115
- * story.note("Validated cart");
116
- * story.tell("Checkout started");
379
+ * const story = new Storyteller({ origin: { who: "api-server" }, narration: "live" });
380
+ * story.report("Request received", { what: { path: "/checkout" } });
381
+ * story.report("Validated cart");
382
+ * story.finish("Checkout started");
117
383
  * ```
118
384
  */
119
385
  declare class Storyteller {
120
386
  readonly audience: AudienceRegistry;
121
387
  private readonly origin?;
388
+ private readonly parentStoryId?;
122
389
  private notes;
123
- constructor(options?: {
124
- origin?: StoryEventBase["origin"];
125
- audiences?: AudienceMember[];
126
- });
390
+ private narration;
391
+ private readonly minimumLevel;
392
+ private readonly onAudienceError;
393
+ private readonly maxInFlight;
394
+ /** Deliveries currently awaiting each audience, keyed by audience name */
395
+ private readonly inFlight;
396
+ /** Emissions dropped for back-pressure since the current story began */
397
+ private droppedEmissions;
398
+ /** Identifies the story currently being collected; regenerated after each telling */
399
+ private storyId;
400
+ /** Position of the next note within the current story */
401
+ private nextSequence;
402
+ constructor(options?: StorytellerOptions);
403
+ /**
404
+ * Switch between collected and live narration at runtime.
405
+ * Takes effect on the next note; already-buffered notes are not replayed.
406
+ *
407
+ * @param narration - `collected` to buffer, `live` to emit each note as it happens
408
+ * @returns `this` for chaining
409
+ */
410
+ narrate(narration: NarrationInput): this;
411
+ /** The id of the story currently being collected */
412
+ get currentStoryId(): string;
127
413
  /**
128
- * Add a timestamped note to the current story.
129
- * @param text - What happened
414
+ * Start a chapter: a child storyteller whose stories are linked back to this
415
+ * one by `parentStoryId`.
416
+ *
417
+ * Real work nests — an agent spawns subtasks, a batch runs per-item operations.
418
+ * A chapter keeps each of those a complete story in its own right while leaving
419
+ * the run reconstructable as a tree.
420
+ *
421
+ * The child shares this storyteller's audience registry, so audiences added
422
+ * later reach it too, and inherits narration, level and delivery settings.
423
+ * Its stories are separate records — a chapter is not folded into the parent's
424
+ * notes.
425
+ *
426
+ * @param options - Origin to merge over the parent's, and any setting to override
427
+ * @returns A child Storyteller
428
+ *
429
+ * @example
430
+ * ```ts
431
+ * for (const account of accounts) {
432
+ * const chapter = story.chapter({ origin: { what: account.id } });
433
+ * chapter.report("Fetching invoices");
434
+ * chapter.finish(`Synced ${account.id}`);
435
+ * }
436
+ * ```
437
+ */
438
+ chapter(options?: ChapterOptions): Storyteller;
439
+ /**
440
+ * Report a beat of the current story.
441
+ *
442
+ * In collected narration the beat is buffered and leaves with the story. In live
443
+ * narration it is emitted the moment you call this, so whoever is tuned in sees
444
+ * the work as it happens.
445
+ *
446
+ * Accepts anything, not just a string — pass an error, an API response, a Map, a
447
+ * class instance — and the value is normalized into a storable shape with the note
448
+ * text derived from it.
449
+ *
450
+ * @param input - What happened: a message, or any value to describe
130
451
  * @param data - Optional context: who did it, what was involved, where it happened, any error
131
452
  * @returns `this` for chaining
132
453
  *
133
454
  * @example
134
455
  * ```ts
135
- * story.note("Card charged", { what: { amount: "$42" }, where: "stripe" });
456
+ * story.report("Card charged", { what: { amount: "$42" }, where: "stripe" });
457
+ * story.report(await response.json());
136
458
  * ```
137
459
  */
138
- note(text: string, data?: NoteData): this;
139
- /** Clear all accumulated notes without emitting a story */
460
+ report(input: unknown, data?: NoteData): this;
461
+ /** Clear all accumulated notes without emitting a story, and start a new story id */
140
462
  reset(): this;
141
463
  /** Preview the current notes as a formatted report without emitting or clearing them */
142
464
  summarize(options?: PreviewOptions): FormattedReport;
143
- /** Tell a success story — everything went well */
465
+ /**
466
+ * Finish the story: emit everything collected so far as one record, and start fresh.
467
+ *
468
+ * @param title - What the story was about
469
+ * @param options - Level, and the error that ended it
470
+ * @returns A one-shot handle whose `.to()` overrides the audience list — call it
471
+ * synchronously, delivery happens on the next microtask
472
+ *
473
+ * @example
474
+ * ```ts
475
+ * story.finish("Sync complete");
476
+ * story.finish("Sync failed", { level: "oops", error }).to("db");
477
+ * ```
478
+ */
479
+ finish(title: string, options?: FinishOptions): {
480
+ to: (...names: string[]) => void;
481
+ };
482
+ /** @deprecated Use `finish(title)`. Removed at 1.0. */
144
483
  tell(title: string): {
145
484
  to: (...names: string[]) => void;
146
485
  };
147
- /** Tell a cautionary story — something was off but it's handled */
486
+ /** @deprecated Use `finish(title, { level: "warn" })`. Removed at 1.0. */
148
487
  warn(title: string): {
149
488
  to: (...names: string[]) => void;
150
489
  };
151
- /** Tell an error story — something broke. Pass the error for automatic normalization. */
490
+ /** @deprecated Use `finish(title, { level: "oops", error })`. Removed at 1.0. */
152
491
  oops(title: string, error?: unknown): {
153
492
  to: (...names: string[]) => void;
154
493
  };
494
+ /** @deprecated Use `report()`. Removed at 1.0. */
495
+ note(input: unknown, data?: NoteData): this;
496
+ /** Emit a single note to the audiences listening for notes */
497
+ private emitNote;
155
498
  /** Build a story event and schedule delivery, returning a handle to override the audience list */
156
499
  private createDelivery;
157
- /** Assemble the story event from current notes and clear notes for the next story */
500
+ /** Assemble the story event from current notes and start a fresh story */
158
501
  private buildEvent;
159
- /** Deliver a story event to matching audience members */
502
+ /** Begin a new story: fresh id, sequence back to zero */
503
+ private startNewStory;
504
+ /** Deliver an emission to the audience members listening for its kind */
160
505
  private deliver;
506
+ /** Run an audience's accepts() without letting a throw from it lose the emission */
507
+ private acceptsSafely;
508
+ /**
509
+ * Hand an emission to one audience, keeping its failures and its slowness
510
+ * contained: a throw is reported rather than swallowed, and a backlog is dropped
511
+ * rather than grown without limit.
512
+ */
513
+ private hearSafely;
514
+ /** Report an audience failure without ever letting it reach caller code */
515
+ private handleAudienceError;
161
516
  }
162
517
 
163
518
  /**
@@ -180,7 +535,8 @@ declare function formatDuration(milliseconds: number): string;
180
535
  declare const summarizeStory: typeof formatStory;
181
536
 
182
537
  type StorytellerSharedOptions = {
183
- origin?: StoryEventBase["origin"];
538
+ origin?: StoryOriginInput;
539
+ narration?: NarrationInput;
184
540
  reset?: boolean;
185
541
  };
186
542
  /**
@@ -198,9 +554,19 @@ type StorytellerSharedOptions = {
198
554
  */
199
555
  declare function useStoryteller(options?: StorytellerSharedOptions): Storyteller;
200
556
 
557
+ type ConsoleAudienceOptions = {
558
+ /** Set false to strip ANSI colors from live note lines. Defaults to `STORYTELLER_COLOR`. */
559
+ colors?: boolean;
560
+ };
201
561
  /**
202
- * Create an audience that prints stories to the console with color-coded grouped output.
203
- * Registered by default on every Storyteller instance.
562
+ * Create an audience that prints to the console: one compact line per note when
563
+ * narration is live, and a color-coded grouped record when a story is told.
564
+ *
565
+ * Registered by default on every Storyteller instance. It listens for notes as well
566
+ * as stories, so switching a storyteller to live narration shows something immediately
567
+ * without registering anything extra.
568
+ *
569
+ * @param options - Rendering options for live note lines
204
570
  *
205
571
  * @example
206
572
  * ```ts
@@ -208,12 +574,15 @@ declare function useStoryteller(options?: StorytellerSharedOptions): Storyteller
208
574
  * story.audience.add(consoleAudience());
209
575
  * ```
210
576
  */
211
- declare function consoleAudience(): AudienceMember;
577
+ declare function consoleAudience(options?: ConsoleAudienceOptions): AudienceMember<EmissionKind>;
212
578
 
213
579
  /**
214
580
  * Create an audience that stores warn and oops stories via your insert function.
215
581
  * Tell-level events are filtered out to reduce noise — only warnings and errors are persisted.
216
582
  *
583
+ * Hears stories only. Live notes are not persisted: the story record already contains
584
+ * every note, so storing both would double-write the same content.
585
+ *
217
586
  * Note: if the insert function throws, the error is silently caught by the delivery
218
587
  * pipeline (Promise.allSettled). Wrap your insert with try/catch to handle failures.
219
588
  *
@@ -230,6 +599,36 @@ declare function consoleAudience(): AudienceMember;
230
599
  */
231
600
  declare function dbAudience(insert: (event: StoryEvent) => Promise<void> | void): AudienceMember;
232
601
 
602
+ /** Anything that can take a line of text — a Node stream, or your own sink */
603
+ type LineWriter = {
604
+ write: (chunk: string) => unknown;
605
+ };
606
+ type NdjsonAudienceOptions = {
607
+ /** Where lines go. Defaults to stdout in Node, console.log elsewhere. */
608
+ stream?: LineWriter;
609
+ /** Register under a different name, e.g. to run two streams at once */
610
+ name?: string;
611
+ /** Minimum level to write. Defaults to `STORYTELLER_LEVEL`, then everything. */
612
+ level?: StoryLevel;
613
+ };
614
+ /**
615
+ * Create an audience that writes one JSON object per line — every note and every
616
+ * story, nothing else on the channel.
617
+ *
618
+ * This is the format to give a program: a log shipper, `jq`, or an agent reading
619
+ * another process's output. Each line parses on its own, and `storyId` plus
620
+ * `sequence` let a reader group streamed notes back into their story.
621
+ *
622
+ * @param options - Stream, name and level threshold
623
+ *
624
+ * @example
625
+ * ```ts
626
+ * story.audience.remove("console");
627
+ * story.audience.add(ndjsonAudience({ stream: process.stderr }));
628
+ * ```
629
+ */
630
+ declare function ndjsonAudience(options?: NdjsonAudienceOptions): AudienceMember<EmissionKind>;
631
+
233
632
  type StoryReportOptions = {
234
633
  timezone?: string;
235
634
  locale?: string;
@@ -253,6 +652,20 @@ declare const ANSI: {
253
652
  /** Map a story level to its corresponding ANSI terminal color */
254
653
  declare function getLevelColor(level: StoryLevel): string;
255
654
  /** Format an origin context into a human-readable path like "app / page / component" */
256
- declare function formatOrigin(origin?: StoryEventBase["origin"]): string | undefined;
655
+ declare function formatOrigin(origin?: StoryOrigin): string | undefined;
656
+ /**
657
+ * Condense a note's context into a short inline summary for one-line output.
658
+ * The full values are always available on the story record and the NDJSON stream,
659
+ * so this can afford to be lossy in favor of staying readable.
660
+ *
661
+ * @param note - The note's context fields
662
+ * @returns A brace-wrapped summary, or undefined when there is no context
663
+ */
664
+ declare function summarizeContext(note: {
665
+ note?: string;
666
+ what?: JsonValue;
667
+ where?: JsonValue;
668
+ error?: StoryError;
669
+ }): string | undefined;
257
670
 
258
- export { ANSI, type AudienceMember, type FormattedReport, type PreviewOptions, type ReportNote, type ReportOptions, type StoryContextValue, type StoryError, type StoryEvent, type StoryEventBase, type StoryLevel, type StoryNote, type StoryPreviewOptions, type StoryReport, type StoryReportOptions, type StorySummary, type StorySummaryData, type StorySummaryNote, type StorySummaryOptions, Storyteller, consoleAudience, dbAudience, formatDuration, formatOrigin, formatStory, getLevelColor, summarizeStory, useStoryteller, writeStoryReport };
671
+ export { ANSI, type AnyAudienceMember, type AudienceErrorHandler, type AudienceMember, AudienceRegistry, type ChapterOptions, type ConsoleAudienceOptions, DEFAULT_REDACT_KEYS, type Emission, type EmissionKind, type EmissionOf, type FinishOptions, type FormattedReport, type JsonValue, type LevelInput, type LineWriter, type Narration, type NarrationInput, type NdjsonAudienceOptions, type NormalizeOptions, type NoteData, type NoteEmission, type OutputFormat, type PreviewOptions, REDACTED, type ReportNote, type ReportOptions, type StoryContextInput, type StoryContextValue, type StoryEmission, type StoryError, type StoryEvent, type StoryEventBase, type StoryLevel, type StoryNote, type StoryOrigin, type StoryOriginInput, type StoryPreviewOptions, type StoryReport, type StoryReportOptions, type StorySummary, type StorySummaryData, type StorySummaryNote, type StorySummaryOptions, Storyteller, type StorytellerOptions, consoleAudience, dbAudience, formatDuration, formatOrigin, formatStory, getLevelColor, meetsLevel, ndjsonAudience, normalizeError, normalizeValue, readEnvironmentValue, resolveColors, resolveMinimumLevel, resolveOutputFormat, summarizeContext, summarizeStory, toStoryLevel, useStoryteller, writeStoryReport };