@longform/async 0.1.1 → 0.2.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.
@@ -0,0 +1,626 @@
1
+ /**
2
+ * The annotation method sets how data attributes can be set on
3
+ * elements outputted by the Longform parser. This is used by clients
4
+ * when searching the DOM for server rendered fragments, or in
5
+ * editing situations.
6
+ *
7
+ * `predictable` should only be used in situations where untrusted
8
+ * user data is not being added to the response. All data attributes
9
+ * would be prefixed with the `data-lf-` prefix, unless a `key` is
10
+ * passed in via the parser args.
11
+ *
12
+ * The predictable mode does not annotate fragments using data
13
+ * attributes if they have a Longform identifier as their HTML id.
14
+ *
15
+ * `obscure` creates a key that is hard to guess in advance when
16
+ * the document is created on the server. This should work in
17
+ * situations where HTTP caching is involved if the full document
18
+ * is created in one pass before being cached, as any untrusted
19
+ * data would also be baked into the response at the time of the
20
+ * obscure key's generation.
21
+ *
22
+ * This approach to obscuring potential data-attribute conflicts is
23
+ * not fool proof. Do not use it in situations where part of a
24
+ * Longform document would be parsed and cached before passing into
25
+ * another document which includes untrusted user data. The first
26
+ * pass might cache the obscure key and allow users to mimic the
27
+ * response and define blocks of HTML that are picked by the client's
28
+ * DOM processing logic.
29
+ *
30
+ * @see [Longform's security considerations](https://longform.occultist.dev/#security-considerations)
31
+ */
32
+ export declare type Annotation = 'none' | 'predictable' | 'obscure';
33
+
34
+ /**
35
+ * @internal
36
+ */
37
+ export declare type AppliedDirective = {
38
+ inlineArgs?: string;
39
+ blockArgs?: string;
40
+ element?: (ctx: ElementCtx) => void;
41
+ };
42
+
43
+ /**
44
+ * Context supplied to async directives.
45
+ */
46
+ export declare type AsyncRenderCtx = {
47
+ /**
48
+ * The directive's inline args.
49
+ */
50
+ inlineArgs?: string;
51
+ /**
52
+ * The directive's block args.
53
+ */
54
+ blockArgs?: string;
55
+ /**
56
+ * A doc object used to provide directives with meta information
57
+ * about the doc while it is being parsed.
58
+ */
59
+ doc: Readonly<Doc>;
60
+ };
61
+
62
+ /**
63
+ * Context supplied to attr directives
64
+ */
65
+ export declare type AttrCtx = {
66
+ /**
67
+ * The element's tag.
68
+ */
69
+ tag: string;
70
+ /**
71
+ * A doc object used to provide directives with meta information
72
+ * about the doc while it is being parsed.
73
+ */
74
+ doc: Readonly<Doc>;
75
+ };
76
+
77
+ /**
78
+ * Directive definition object. Directives can support multiple roles
79
+ * but some crate ambiguities and should not be used together. The
80
+ * parser will ignore the directive if it implements hooks for conflicting
81
+ * roles.
82
+ *
83
+ * A directive implementing `meta` cannot implement `element`.
84
+ * A directive implementing `element` cannot implement `render` or `asyncRender`.
85
+ * A directive implementing `render` cannot implement `asyncRender`.
86
+ */
87
+ export declare type Directive = {
88
+ /**
89
+ * The meta directive hook defines a meta value. Meta values can be accessed
90
+ * from the `doc.meta` object in other directive hooks and from
91
+ * the parsed result of a Longform document via the exported `parsed.meta`
92
+ * object.
93
+ *
94
+ * Meta directives should be used at the start of a longform document.
95
+ * They will be ignored by the longform parser if defined after the
96
+ * `@global` directive, directives implementing the element hook, or
97
+ * fragment definitions.
98
+ */
99
+ meta?: (args: MetaCtx) => unknown;
100
+ /**
101
+ * The global hook is not implemented.
102
+ *
103
+ * @internal
104
+ */
105
+ global?: (ctx: GlobalCtx) => void;
106
+ /**
107
+ * The attr directive hook can be used to set a element's attribute.
108
+ * It is triggered before element hooks defined for the same element
109
+ * or element chain.
110
+ */
111
+ attr?: (ctx: AttrCtx) => string | boolean | undefined | null;
112
+ /**
113
+ * The element hook can be used to set attribute and data values
114
+ * on an element with more context about the element's definition.
115
+ */
116
+ element?: (ctx: ElementCtx) => void;
117
+ /**
118
+ * The render hook can output custom HTML at the location it is
119
+ * called.
120
+ */
121
+ render?: (ctx: RenderCtx) => string | undefined;
122
+ /**
123
+ * The async render hook can output custom HTML after an asynchronous
124
+ * operation at the location it is called.
125
+ */
126
+ asyncRender?: (ctx: AsyncRenderCtx) => string | undefined | Promise<string | undefined>;
127
+ };
128
+
129
+ /**
130
+ * A doc object used to provide directives with meta information
131
+ * about the doc while it is being parsed.
132
+ */
133
+ export declare type Doc = {
134
+ /**
135
+ * The `@id` value of the document.
136
+ */
137
+ id?: string;
138
+ /**
139
+ * The `@type` value of the document.
140
+ */
141
+ type?: string;
142
+ /**
143
+ * The `@lang` value of the document.
144
+ */
145
+ lang?: string;
146
+ /**
147
+ * The `@dir` value of the document.
148
+ */
149
+ dir?: string;
150
+ /**
151
+ * An object containing all meta values defined for the document.
152
+ * Note that they will not have the directive's `@` character
153
+ * prefixing them. So the directive `@foo:bar` will have the
154
+ * key of `foo:bar` in the meta object.
155
+ */
156
+ meta: Readonly<Record<string, unknown>>;
157
+ };
158
+
159
+ /**
160
+ * An element's description. Directives with access to elements
161
+ * should only apply changes to its `attrs` object. The `id` can
162
+ * be set via the `attrs` object if it does not already have a
163
+ * value, and classes can be appended to the `class` value via
164
+ * the `attrs` object.
165
+ *
166
+ * The element's tag cannot be changed.
167
+ */
168
+ declare type Element_2 = {
169
+ /**
170
+ * The element's tag.
171
+ */
172
+ tag: string;
173
+ /**
174
+ * The element's id.
175
+ */
176
+ id?: string;
177
+ /**
178
+ * The element's class value.
179
+ */
180
+ class?: string;
181
+ /**
182
+ * An object containing the element's attributes.
183
+ */
184
+ attrs: Record<string, boolean | string>;
185
+ };
186
+ export { Element_2 as Element }
187
+
188
+ /**
189
+ * Context supplied to element directives.
190
+ */
191
+ export declare type ElementCtx = {
192
+ /**
193
+ * The directive's inline args.
194
+ */
195
+ inlineArgs?: string;
196
+ /**
197
+ * The directive's block args.
198
+ */
199
+ blockArgs?: string;
200
+ /**
201
+ * A doc object used to provide directives with meta information
202
+ * about the doc while it is being parsed.
203
+ */
204
+ doc: Readonly<Doc>;
205
+ /**
206
+ * The element which is the target of the directive.
207
+ */
208
+ el: Element_2;
209
+ /**
210
+ * The elements that are chained to the target element.
211
+ */
212
+ chain: Element_2[];
213
+ };
214
+
215
+ /**
216
+ * A fragment object.
217
+ */
218
+ export declare type Fragment = {
219
+ /**
220
+ * The Longform identifier for the element.
221
+ */
222
+ id: string;
223
+ /**
224
+ * A selector which can be used to extract the fragment from a pages DOM
225
+ * if the fragment had been server rendered.
226
+ */
227
+ selector: string;
228
+ /**
229
+ * The fragment type.
230
+ *
231
+ * `embed` indicates the fragment has a unique embedded HTML id.
232
+ * `bare` indicates the fragment has no embedded HTML id.
233
+ * `range` indicates the fragment is a range of elements, instead of having a single top level element.
234
+ * `text` indicates the fragment is text only can can be used in situations where HTML might be invalid.
235
+ */
236
+ type: FragmentType;
237
+ /**
238
+ * The fragment output as a string.
239
+ */
240
+ html: string;
241
+ };
242
+
243
+ /**
244
+ * @internal
245
+ */
246
+ export declare type FragmentRef = {
247
+ id: string;
248
+ start: number;
249
+ end: number;
250
+ };
251
+
252
+ /**
253
+ * The fragment type.
254
+ *
255
+ * `embed` indicates the fragment has a unique embedded HTML id.
256
+ * `bare` indicates the fragment has no embedded HTML id.
257
+ * `range` indicates the fragment is a range of elements, instead of having a single top level element.
258
+ * `text` indicates the fragment is text only can can be used in situations where HTML might be invalid.
259
+ */
260
+ export declare type FragmentType = 'embed' | 'bare' | 'range' | 'text';
261
+
262
+ /**
263
+ * Context supplied to directives declared in the global directive.
264
+ */
265
+ export declare type GlobalCtx = {
266
+ /**
267
+ * A doc object used to provide directives with meta information
268
+ * about the doc while it is being parsed.
269
+ */
270
+ doc: Doc;
271
+ };
272
+
273
+ /**
274
+ * Parses a longform document into a object containing the root and fragments
275
+ * in the output format.
276
+ *
277
+ * @param input - The Longform document to parse.
278
+ * @param args - Arguments for the Longform parser.
279
+ */
280
+ export declare function longform(input: string, args?: LongformArgs): Promise<ParsedLongform>;
281
+
282
+ /**
283
+ * The Longform parser is designed to serve multiple roles.
284
+ *
285
+ *
286
+ * In a situation where a document containing a HTML page's main content
287
+ * is split from a re-useable layout the `'doc'` output mode can be used
288
+ * on the main content and the result passed as arguments to the Longform
289
+ * parser when parsing the layout document. The id, type, lang and direction
290
+ * as well as any custom meta values and the parsed fragments from the
291
+ * main document will be available to the template's fragments.
292
+ *
293
+ *
294
+ * In a situation where a directive is being defined, the output mode
295
+ * `head` can be used to use the Longform parser as a DSL for custom
296
+ * directives. The `templates` output mode can be used to parse the
297
+ * block arguments of the directive as Longform templates, with the
298
+ * directive supplying arguments specified by the directive.
299
+ *
300
+ *
301
+ * The `mountable` output mode is used where Longform needs to be outputted
302
+ * so another libraries SSR rendered content can fill the gaps in mountable
303
+ * elements. Usually this would be used for a layout document which is
304
+ * used in a similar way to Astro's islands.
305
+ */
306
+ export declare type LongformArgs = {
307
+ /**
308
+ * The key used for creating data attributes.
309
+ * Defaults to a random string or 'lf' if predictable mode is enabled.
310
+ */
311
+ key?: string;
312
+ /**
313
+ * The id of the document. If set the `@id` is ignored.
314
+ * This can be used when creating partial re-usable documents.
315
+ */
316
+ id?: string;
317
+ /**
318
+ * The media type of the document. If set the `@type` directive within
319
+ * the input document is ignored.
320
+ */
321
+ type?: string;
322
+ /**
323
+ * The language tag of the document. If set the `@lang`
324
+ * directive is ignored.
325
+ * This can be used when creating partial re-usable documents.
326
+ */
327
+ lang?: string;
328
+ /**
329
+ * The text direction of the document. If set the `@dir`
330
+ * directive is ignored.
331
+ * This can be used when creating partial re-usable documents.
332
+ */
333
+ dir?: string;
334
+ /**
335
+ * Metadata set on the document.
336
+ */
337
+ meta?: Record<string, unknown>;
338
+ /**
339
+ * The media type of the target document. This is used to control
340
+ * the output of the serialized markup. If `'text/html'` is given
341
+ * void elements will be formatted in the HTML style and attributes
342
+ * will not use quotes unless used in the input markup.
343
+ *
344
+ * XML target types will always have attributes wrapped in double
345
+ * quotes.
346
+ */
347
+ targetType?: TargetType;
348
+ /**
349
+ * The output mode of the document.
350
+ */
351
+ outputMode?: OutputMode;
352
+ /**
353
+ * Style in which data attributes are added to output HTML markup.
354
+ *
355
+ * This is used in SSR situations where a client will need to use the
356
+ * data attributes that annotate Longform rendered fragments and elements
357
+ * to rebuild the Longform document from client produced DOM.
358
+ */
359
+ annotations?: Annotation;
360
+ /**
361
+ * Configures the sanitizer to allow all elements and attributes in the document.
362
+ */
363
+ /**
364
+ * Configures the sanitizer to allow the given set of attributes unless elements specify more.
365
+ */
366
+ /**
367
+ * Configures the sanitizer to allow the given set of elements and their attributes.
368
+ */
369
+ /**
370
+ * Object of custom directives.
371
+ */
372
+ directives?: Record<string, Directive>;
373
+ /**
374
+ * Object of fragments to make available to the parser when processing fragment refs.
375
+ */
376
+ fragments?: Record<string, Fragment>;
377
+ };
378
+
379
+ /**
380
+ * Context supplied to meta directives.
381
+ */
382
+ export declare type MetaCtx = {
383
+ /**
384
+ * The directive's inline args.
385
+ */
386
+ inlineArgs?: string;
387
+ /**
388
+ * The directive's block args.
389
+ */
390
+ blockArgs?: string;
391
+ };
392
+
393
+ /**
394
+ * If the parser's output mode is `mountable`, the Longform parser will
395
+ * break output of the root element up in locations where the `@mount:: mountPointId`
396
+ * directive is used.
397
+ */
398
+ export declare type MountPoint = {
399
+ /**
400
+ * The id of the mountpoint.
401
+ */
402
+ id: string;
403
+ /**
404
+ * The HTML output for this part.
405
+ */
406
+ part: string;
407
+ };
408
+
409
+ /**
410
+ * The Longform parser supports several output modes which are
411
+ * useful for different situations.
412
+ *
413
+ * `doc` Outputs all fragments normally.
414
+ *
415
+ * `head` Parses the `\@id`, `\@type`, `\@lang`, `\@dir` and any directives
416
+ * implementing the `meta` directive hook. It exits as soon as it hits
417
+ * another directive type or fragment declaration.
418
+ *
419
+ * `mountable` Supports use of the `\@mount` directive for turning elements
420
+ * into mountpoints. This output mode populates the `mountpoints` array
421
+ * in the parse result. This array can be looped over and data from another
422
+ * rendering tool can mount its output into the named mount points. Once all
423
+ * mountpoint entries have been populated the `tail` property in the parsed
424
+ * result should be appended to the final document.
425
+ *
426
+ * The mountable mode is currently very basic in implementation and only
427
+ * supports documents implementing a single root element.
428
+ *
429
+ * `templates` parses every fragment as though it was a template even
430
+ * if the `\@template` directive is not used. This is useful for creating
431
+ * directives which use the block args to define a Longform template.
432
+ */
433
+ export declare type OutputMode = 'doc' | 'head' | 'mountable' | 'templates';
434
+
435
+ /**
436
+ * An object containing the parsed Longform result.
437
+ */
438
+ export declare type ParsedLongform = {
439
+ /**
440
+ * The key used when annotating the markup with data attributes.
441
+ */
442
+ key?: string;
443
+ /**
444
+ * The id, or URL of the document.
445
+ */
446
+ id?: string;
447
+ /**
448
+ * The media type of the Longform document.
449
+ */
450
+ type?: string;
451
+ /**
452
+ * The language tag of the document.
453
+ */
454
+ lang?: string;
455
+ /**
456
+ * The text direction of the document.
457
+ */
458
+ dir?: string;
459
+ /**
460
+ * Meta values defined in the document's head.
461
+ */
462
+ meta: Record<string, unknown>;
463
+ /**
464
+ * The media type of the target document.
465
+ */
466
+ targetType?: TargetType;
467
+ /**
468
+ * The output mode used when parsing the document.
469
+ */
470
+ outputMode: OutputMode;
471
+ /**
472
+ * Style in which data attributes are added to output HTML markup.
473
+ */
474
+ annotations?: Annotation;
475
+ /**
476
+ * The root HTML output for the document.
477
+ */
478
+ root?: string;
479
+ /**
480
+ * The root block as a template.
481
+ * This is only produced if using the output mode of `'templates'`.
482
+ */
483
+ template?: string;
484
+ /**
485
+ * The root selector.
486
+ */
487
+ selector?: string;
488
+ /**
489
+ * The HTML fragments.
490
+ */
491
+ fragments: Record<string, Fragment>;
492
+ /**
493
+ * All parsed templates.
494
+ */
495
+ templates: Record<string, string>;
496
+ /**
497
+ * Document mount points.
498
+ */
499
+ mountpoints?: MountPoint[];
500
+ /**
501
+ * Final document part after mount points.
502
+ */
503
+ tail?: string;
504
+ };
505
+
506
+ /**
507
+ * Processes a client side Longform template to HTML fragment string.
508
+ *
509
+ * @param fragment - The fragment template.
510
+ * @param args - Args for the template.
511
+ * @param longformArgs - Args for the Longform parser.
512
+ * @param getFragment - A function which returns an already processed fragment's HTML string.
513
+ *
514
+ * @returns The processed template.
515
+ */
516
+ export declare function processTemplate(template: string, args: Record<string, string | number>, longformArgs?: LongformArgs, getFragment?: (fragment: string) => string | undefined): Promise<TemplateOutput | undefined>;
517
+
518
+ /**
519
+ * Context supplied to render directives.
520
+ */
521
+ export declare type RenderCtx = {
522
+ /**
523
+ * The directive's inline args.
524
+ */
525
+ inlineArgs?: string;
526
+ /**
527
+ * The directive's block args.
528
+ */
529
+ blockArgs?: string;
530
+ /**
531
+ * A doc object used to provide directives with meta information
532
+ * about the doc while it is being parsed.
533
+ */
534
+ doc: Readonly<Doc>;
535
+ };
536
+
537
+ /**
538
+ * @internal
539
+ */
540
+ export declare type SanitizerConfig = {
541
+ allowAll: boolean;
542
+ allowedAttributes: string[];
543
+ allowedElements: Record<string, SanitizerElement>;
544
+ };
545
+
546
+ /**
547
+ * @internal
548
+ */
549
+ export declare type SanitizerElement = {
550
+ tag: string;
551
+ attrs: string[];
552
+ };
553
+
554
+ /**
555
+ * The content type of the response can be passed into the Longform
556
+ * parser to change the shape of the output. The default value `text/html`
557
+ * will use HTML's method for closing void tags. The XML versions would
558
+ * use XML valid syntax.
559
+ *
560
+ * If `application/xml` is provided, no data attributes will be added to
561
+ * the outputted markup, even if an annotation mode or key is given.
562
+ */
563
+ export declare type TargetType = 'text/html' | 'application/xhtml+xml' | 'application/xml';
564
+
565
+ /**
566
+ * An object containing a parsed Longform template.
567
+ */
568
+ export declare type TemplateOutput = {
569
+ /**
570
+ * The Longform identifier for the element.
571
+ */
572
+ id?: string;
573
+ /**
574
+ * The fragment type.
575
+ *
576
+ * `root` indicates the template is a root fragments
577
+ * `embed` indicates the fragment has a unique embedded HTML id.
578
+ * `bare` indicates the fragment has no embedded HTML id.
579
+ * `range` indicates the fragment is a range of elements, instead of having a single top level element.
580
+ * `text` indicates the fragment is text only can can be used in situations where HTML might be invalid.
581
+ */
582
+ type: 'root' | FragmentType;
583
+ /**
584
+ * The fragment output as a string.
585
+ */
586
+ html: string;
587
+ };
588
+
589
+ /**
590
+ * @internal
591
+ */
592
+ export declare type WorkingElement = {
593
+ indent: number;
594
+ key?: string;
595
+ id?: string;
596
+ tag: string;
597
+ class?: string;
598
+ attrs: Record<string, string | true>;
599
+ text?: string;
600
+ html: string;
601
+ mount?: string;
602
+ sanitizerConfig?: SanitizerConfig;
603
+ chain: WorkingElement[];
604
+ beforeRender?: AppliedDirective[];
605
+ };
606
+
607
+ /**
608
+ * @internal
609
+ */
610
+ export declare type WorkingFragment = {
611
+ id: string;
612
+ template: boolean;
613
+ mountable: boolean;
614
+ type: WorkingFragmentType;
615
+ html: string;
616
+ refs: FragmentRef[];
617
+ els: WorkingElement[];
618
+ mountpoints?: MountPoint[];
619
+ };
620
+
621
+ /**
622
+ * @internal
623
+ */
624
+ export declare type WorkingFragmentType = 'root' | 'embed' | 'bare' | 'range' | 'text' | 'mount' | 'template';
625
+
626
+ export { }
package/dist/longform.cjs CHANGED
@@ -50,7 +50,7 @@ function makeFragment(type = 'bare') {
50
50
  mountable: false,
51
51
  els: [],
52
52
  refs: [],
53
- mountPoints: [],
53
+ mountpoints: [],
54
54
  };
55
55
  }
56
56
  const directiveValidator = /^[a-z][a-z\-]*\:[a-z][a-z\-]*$/i;
@@ -438,9 +438,9 @@ async function longform(input, args) {
438
438
  if (element.mount != null) {
439
439
  const id = element.mount;
440
440
  [element, fragment] = applyIndent(indent + 1, key, element, fragment, doc, parsed, output, args);
441
- if (fragment.mountPoints == null)
442
- fragment.mountPoints = [];
443
- fragment.mountPoints.push({
441
+ if (fragment.mountpoints == null)
442
+ fragment.mountpoints = [];
443
+ fragment.mountpoints.push({
444
444
  id,
445
445
  part: fragment.html,
446
446
  });
@@ -552,7 +552,7 @@ async function longform(input, args) {
552
552
  await Promise.all(promises);
553
553
  if (root?.mountable) {
554
554
  output.tail = root.html;
555
- output.mountpoints = root.mountPoints ?? [];
555
+ output.mountpoints = root.mountpoints ?? [];
556
556
  return output;
557
557
  }
558
558
  const arr = Array.from(parsed.values());
@@ -622,9 +622,9 @@ async function longform(input, args) {
622
622
  /**
623
623
  * Processes a client side Longform template to HTML fragment string.
624
624
  *
625
- * @param fragment The fragment template.
626
- * @param args Args for the template.
627
- * @param longformArgs Args for the Longform parser.
625
+ * @param fragment - The fragment template.
626
+ * @param args - Args for the template.
627
+ * @param longformArgs - Args for the Longform parser.
628
628
  * @param getFragment - A function which returns an already processed fragment's HTML string.
629
629
  *
630
630
  * @returns The processed template.
@@ -640,7 +640,9 @@ async function processTemplate(template, args, longformArgs, getFragment) {
640
640
  return args[param] != null ? escape(args[param].toString()) : '';
641
641
  });
642
642
  const res = await longform(processed, Object.assign({}, longformArgs, { outputMode: 'doc' }));
643
- return res.root ?? Object.values(res.fragments)[0]?.html;
643
+ if (res.root != null)
644
+ return { type: 'root', html: res.root };
645
+ return Object.values(res.fragments)[0];
644
646
  }
645
647
  function handleAttribute(name, value, element, doc, directives) {
646
648
  let m;