@podlite/schema 0.0.80 → 0.0.82

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 (68) hide show
  1. package/CHANGELOG.podlite +44 -0
  2. package/esm/ast-helpers.d.ts +8 -1
  3. package/esm/ast-helpers.js +172 -47
  4. package/esm/ast-helpers.js.map +1 -1
  5. package/esm/exportAny.d.ts +1 -0
  6. package/esm/exportAny.js +11 -0
  7. package/esm/exportAny.js.map +1 -1
  8. package/esm/exportHtml.js +58 -1
  9. package/esm/exportHtml.js.map +1 -1
  10. package/esm/exportMarkdown.js +604 -137
  11. package/esm/exportMarkdown.js.map +1 -1
  12. package/esm/helpers/code-config.d.ts +1 -0
  13. package/esm/helpers/code-config.js +4 -0
  14. package/esm/helpers/code-config.js.map +1 -0
  15. package/esm/helpers/corePlugins.js +4 -0
  16. package/esm/helpers/corePlugins.js.map +1 -1
  17. package/esm/helpers/handlers.js +8 -4
  18. package/esm/helpers/handlers.js.map +1 -1
  19. package/esm/index.d.ts +2 -0
  20. package/esm/index.js +1 -0
  21. package/esm/index.js.map +1 -1
  22. package/esm/markdown-heading-text.d.ts +3 -0
  23. package/esm/markdown-heading-text.js +36 -0
  24. package/esm/markdown-heading-text.js.map +1 -0
  25. package/esm/plugin-formatting-codes.js +1 -3
  26. package/esm/plugin-formatting-codes.js.map +1 -1
  27. package/esm/plugin-tables.d.ts +4 -1
  28. package/esm/plugin-tables.js +99 -26
  29. package/esm/plugin-tables.js.map +1 -1
  30. package/esm/test-display.js +8 -1
  31. package/esm/test-display.js.map +1 -1
  32. package/esm/title.d.ts +13 -0
  33. package/esm/title.js +22 -0
  34. package/esm/title.js.map +1 -0
  35. package/esm/types.d.ts +9 -4
  36. package/esm/version.d.ts +1 -1
  37. package/esm/version.js +1 -1
  38. package/esm/writerMarkdown.d.ts +9 -0
  39. package/esm/writerMarkdown.js +103 -1
  40. package/esm/writerMarkdown.js.map +1 -1
  41. package/lib/ast-helpers.d.ts +8 -1
  42. package/lib/ast-helpers.js +176 -48
  43. package/lib/exportAny.d.ts +1 -0
  44. package/lib/exportAny.js +11 -0
  45. package/lib/exportHtml.js +58 -1
  46. package/lib/exportMarkdown.js +607 -140
  47. package/lib/helpers/code-config.d.ts +1 -0
  48. package/lib/helpers/code-config.js +8 -0
  49. package/lib/helpers/corePlugins.js +4 -0
  50. package/lib/helpers/handlers.js +8 -4
  51. package/lib/index.d.ts +2 -0
  52. package/lib/index.js +5 -2
  53. package/lib/markdown-heading-text.d.ts +3 -0
  54. package/lib/markdown-heading-text.js +40 -0
  55. package/lib/plugin-formatting-codes.js +2 -4
  56. package/lib/plugin-tables.d.ts +4 -1
  57. package/lib/plugin-tables.js +99 -26
  58. package/lib/test-display.js +8 -1
  59. package/lib/title.d.ts +13 -0
  60. package/lib/title.js +27 -0
  61. package/lib/types.d.ts +9 -4
  62. package/lib/version.d.ts +1 -1
  63. package/lib/version.js +1 -1
  64. package/lib/writerMarkdown.d.ts +9 -0
  65. package/lib/writerMarkdown.js +103 -1
  66. package/package.json +3 -2
  67. package/schema/AstTree.json +246 -0
  68. package/schema/PodliteDocument.json +246 -0
@@ -0,0 +1 @@
1
+ export declare const codeConfigOwner: (name: unknown) => string | null;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.codeConfigOwner = void 0;
4
+ // `=config C<> :allow<I>` names a markup code, not a block: the trailing angles
5
+ // are the marker, and what it declares belongs to the code they name
6
+ const codeConfigOwner = (name) => typeof name === 'string' && /^[A-Z]<>$/.test(name) ? name[0] : null;
7
+ exports.codeConfigOwner = codeConfigOwner;
8
+ //# sourceMappingURL=code-config.js.map
@@ -19,6 +19,10 @@ exports.core = {
19
19
  if (alt !== undefined) {
20
20
  writer.writeRaw(` alt="${(0, html_attr_1.quoteAttribute)((0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(alt) : alt)}"`);
21
21
  }
22
+ // the hint a reader shows over the picture, hidden as its text is
23
+ if (typeof node.title === 'string') {
24
+ writer.writeRaw(` title="${(0, html_attr_1.quoteAttribute)((0, guard_1.isCovered)(node, ctx) ? (0, handlers_1.maskText)(node.title) : node.title)}"`);
25
+ }
22
26
  writer.writeRaw(`/>`);
23
27
  }
24
28
  },
@@ -135,10 +135,14 @@ const handleNested = (defaultHandler, implicitLevel) => {
135
135
  if (nesting !== undefined) {
136
136
  writer.addLevel(nesting);
137
137
  }
138
- defaultHandlerInited(node, ctx, interator);
139
- // remove nesting level
140
- if (nesting !== undefined) {
141
- writer.removeLevel(nesting);
138
+ try {
139
+ defaultHandlerInited(node, ctx, interator);
140
+ }
141
+ finally {
142
+ // remove nesting level
143
+ if (nesting !== undefined) {
144
+ writer.removeLevel(nesting);
145
+ }
142
146
  }
143
147
  };
144
148
  };
package/lib/index.d.ts CHANGED
@@ -4,6 +4,8 @@ export { PodliteDocument } from './types';
4
4
  export { AstTree } from './types';
5
5
  export * from './types';
6
6
  export * from './block-names';
7
+ export { titleParts, isTitleBlock } from './title';
8
+ export type { TitleEntry } from './title';
7
9
  export * from './attribute-names';
8
10
  export * from './blocks-helpers';
9
11
  export * from './query-helpers';
package/lib/index.js CHANGED
@@ -39,8 +39,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
39
39
  return (mod && mod.__esModule) ? mod : { "default": mod };
40
40
  };
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.renderCodeText = exports.getMaskedTextContent = exports.guardedTextLeaves = exports.isCovered = exports.markGuarded = exports.isSetTarget = exports.isSetTransparent = exports.mergeSet = exports.applySetToFirst = exports.SelectorError = exports.getDocIDs = exports.filePathMatches = exports.outermost = exports.runSelector = exports.readSelector = exports.parseSelector = exports.Writer = exports.toMarkdown = exports.toHtml = exports.parseFormattingCodes = exports.parse = exports.isWrapper = exports.isDirectiveNode = exports.holderInside = exports.blockNameOf = exports.walkConfigScopes = exports.propagateConfigDefaults = exports.mergeConfigSettings = exports.headingId = exports.frozenIds = exports.cleanIds = exports.podlitePluggable = exports.toAnyRules = exports.pluginCleanLocation = exports.quoteAttribute = exports.fingerprint = exports.assignHeadingKeys = exports.readLinkConfig = exports.parseAttributes = exports.codeConfigWithDefaults = exports.makeAttrs = exports.toAny = exports.isSemanticBlock = exports.isNamedBlock = exports.makeTransformer = exports.makeInterator = exports.MARKUP_CODE_DEPTH_LIMIT = exports.ALIAS_EXPANSION_BUDGET = exports.ALIAS_EXPANSION_DEPTH = exports.expandAlias = void 0;
43
- exports.version = exports.applyImageBase = exports.tocTitleText = exports.mayHoldTests = exports.canOwnTest = exports.testFoldedByAuthor = exports.testCaption = exports.applyFoldedSections = void 0;
42
+ exports.guardedTextLeaves = exports.isCovered = exports.markGuarded = exports.isSetTarget = exports.isSetTransparent = exports.mergeSet = exports.applySetToFirst = exports.SelectorError = exports.getDocIDs = exports.filePathMatches = exports.outermost = exports.runSelector = exports.readSelector = exports.parseSelector = exports.Writer = exports.toMarkdown = exports.toHtml = exports.parseFormattingCodes = exports.parse = exports.isWrapper = exports.isDirectiveNode = exports.holderInside = exports.blockNameOf = exports.walkConfigScopes = exports.propagateConfigDefaults = exports.mergeConfigSettings = exports.headingId = exports.frozenIds = exports.cleanIds = exports.podlitePluggable = exports.toAnyRules = exports.pluginCleanLocation = exports.quoteAttribute = exports.fingerprint = exports.assignHeadingKeys = exports.readLinkConfig = exports.parseAttributes = exports.codeConfigWithDefaults = exports.makeAttrs = exports.toAny = exports.isSemanticBlock = exports.isNamedBlock = exports.makeTransformer = exports.makeInterator = exports.MARKUP_CODE_DEPTH_LIMIT = exports.ALIAS_EXPANSION_BUDGET = exports.ALIAS_EXPANSION_DEPTH = exports.expandAlias = exports.isTitleBlock = exports.titleParts = void 0;
43
+ exports.version = exports.applyImageBase = exports.tocTitleText = exports.mayHoldTests = exports.canOwnTest = exports.testFoldedByAuthor = exports.testCaption = exports.applyFoldedSections = exports.renderCodeText = exports.getMaskedTextContent = void 0;
44
44
  exports.toAst = toAst;
45
45
  exports.getTextContentFromNode = getTextContentFromNode;
46
46
  exports.getPodContentFromNode = getPodContentFromNode;
@@ -56,6 +56,9 @@ const jsonShemes = __importStar(require("../schema"));
56
56
  const ast_inerator_1 = require("./ast-inerator");
57
57
  __exportStar(require("./types"), exports);
58
58
  __exportStar(require("./block-names"), exports);
59
+ var title_1 = require("./title");
60
+ Object.defineProperty(exports, "titleParts", { enumerable: true, get: function () { return title_1.titleParts; } });
61
+ Object.defineProperty(exports, "isTitleBlock", { enumerable: true, get: function () { return title_1.isTitleBlock; } });
59
62
  __exportStar(require("./attribute-names"), exports);
60
63
  __exportStar(require("./blocks-helpers"), exports);
61
64
  __exportStar(require("./query-helpers"), exports);
@@ -0,0 +1,3 @@
1
+ import { type Token } from 'marked';
2
+ export declare const headingTextOf: (line: string) => string;
3
+ export declare const textOfTokens: (tokens: Token[] | undefined) => string;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.textOfTokens = exports.headingTextOf = void 0;
4
+ const marked_1 = require("marked");
5
+ const entities_1 = require("entities");
6
+ // The text a reader of Markdown shows for a heading, which its address is built from.
7
+ // The line is read by marked, held at one version, so its address changes only when
8
+ // the version does; a kind of piece this reading does not know fails out loud.
9
+ const textOf = (tokens) => (tokens || [])
10
+ .map((token) => {
11
+ switch (token.type) {
12
+ case 'image':
13
+ case 'html':
14
+ case 'br':
15
+ return '';
16
+ case 'codespan':
17
+ // marked holds the text of code as it stands
18
+ return token.text;
19
+ case 'escape':
20
+ return token.text;
21
+ case 'text':
22
+ return token.tokens ? textOf(token.tokens) : (0, entities_1.decodeHTMLStrict)(token.text);
23
+ case 'link':
24
+ case 'strong':
25
+ case 'em':
26
+ case 'del':
27
+ return textOf(token.tokens);
28
+ default:
29
+ throw new Error(`[podlite] the text of a markdown heading has a piece it cannot read: ${token.type}`);
30
+ }
31
+ })
32
+ .join('');
33
+ const headingTextOf = (line) => {
34
+ const heading = marked_1.marked.lexer(`# ${line}`).find(token => token.type === 'heading');
35
+ return heading ? textOf(heading.tokens) : '';
36
+ };
37
+ exports.headingTextOf = headingTextOf;
38
+ // for a test of the pieces that are not known
39
+ exports.textOfTokens = textOf;
40
+ //# sourceMappingURL=markdown-heading-text.js.map
@@ -11,15 +11,13 @@ const config_1 = __importDefault(require("./helpers/config"));
11
11
  const parseAttributes_1 = require("./helpers/parseAttributes");
12
12
  const blockName_1 = require("./helpers/blockName");
13
13
  const blocks_helpers_1 = require("./blocks-helpers");
14
- // `=config C<> :allow<I>` names a markup code, not a block: the trailing angles
15
- // are the marker, and what it declares belongs to the code they name
16
- const codeConfigOwner = (name) => typeof name === 'string' && /^[A-Z]<>$/.test(name) ? name[0] : null;
14
+ const code_config_1 = require("./helpers/code-config");
17
15
  // a declaration acts from where it is written, and one without :allow leaves
18
16
  // the codes an earlier declaration allowed
19
17
  const declareAllowedIn = (node, scope) => {
20
18
  if (!node || typeof node !== 'object')
21
19
  return;
22
- const owner = codeConfigOwner('name' in node ? node.name : undefined);
20
+ const owner = (0, code_config_1.codeConfigOwner)('name' in node ? node.name : undefined);
23
21
  if (!owner)
24
22
  return;
25
23
  const conf = (0, config_1.default)(node, {});
@@ -1,3 +1,4 @@
1
+ import { ConfigScope } from './helpers/configPropagation';
1
2
  export declare function parseCsv(text: any): any[];
2
3
  export declare function parseTsv(text: any): any;
3
4
  export declare function parseMimeType(raw: any): {
@@ -10,5 +11,7 @@ export declare function csvToTableContent(csvRows: any, hasHeader?: boolean, all
10
11
  export type TableReport = (code: string, message: string, node: any) => void;
11
12
  export declare function makeTableReport(opt: any): TableReport;
12
13
  export declare function normalizeCellCounts(tableNode: any, source?: string, report?: TableReport): any;
13
- declare const _default: (opt?: {}) => (tree: any) => any;
14
+ declare const _default: (opt?: {
15
+ config?: ConfigScope;
16
+ }) => (tree: any) => any;
14
17
  export default _default;
@@ -18,6 +18,9 @@ exports.normalizeCellCounts = normalizeCellCounts;
18
18
  */
19
19
  const makeTransformer_1 = __importDefault(require("./helpers/makeTransformer"));
20
20
  const config_1 = __importDefault(require("./helpers/config"));
21
+ const scan_1 = require("./codes/scan");
22
+ const configPropagation_1 = require("./helpers/configPropagation");
23
+ const code_config_1 = require("./helpers/code-config");
21
24
  function flattenDeep(arr) {
22
25
  return arr.reduce((acc, val) => (Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val)), []);
23
26
  }
@@ -324,6 +327,58 @@ function buildCodeFromDataBlock(tableNode, dataBlock) {
324
327
  config: Array.isArray(tableNode.config) ? tableNode.config : [],
325
328
  };
326
329
  }
330
+ // ─── Markup codes closed on their line (spec §Tables) ──────────────────────
331
+ // The codes a cell of this table reads, by the scope at the table: the :allow of
332
+ // a cell, else of a row, else of the table, else every code; the codes read
333
+ // inside C<> and V<> come from =config C<> and =config V<>. Null when no code acts.
334
+ const codeScopeOf = (table, scope) => {
335
+ const allowOf = items => {
336
+ const attrs = (0, config_1.default)({ config: items || [] }, {});
337
+ return attrs.exists('allow') ? attrs.getAllValues('allow') : undefined;
338
+ };
339
+ const own = (0, config_1.default)(table, {});
340
+ const allowed = allowOf(scope.cell) ??
341
+ allowOf(scope.row) ??
342
+ (own.exists('allow') ? own.getAllValues('allow') : allowOf(scope.table));
343
+ if (allowed && allowed.length === 0)
344
+ return null;
345
+ const allowedIn = {};
346
+ for (const key of Object.keys(scope)) {
347
+ const owner = (0, code_config_1.codeConfigOwner)(key);
348
+ const inside = owner && allowOf(scope[key]);
349
+ if (owner && inside)
350
+ allowedIn[owner] = inside;
351
+ }
352
+ return { allowed, allowedIn };
353
+ };
354
+ // A line with every character of a markup code closed on that line replaced, so
355
+ // no separator is found inside it. The length stays the same, unit by unit, and a
356
+ // cell is cut out of the line itself at the places found in the mask.
357
+ const protectCodes = (line, scope) => {
358
+ if (!scope || !/[<«]/.test(line))
359
+ return line;
360
+ const spans = [];
361
+ const visit = (codes) => codes.forEach(code => (code.ending === 'own' ? spans.push([code.start, code.end]) : visit(code.children)));
362
+ visit((0, scan_1.scanCodes)(line, scope).codes);
363
+ if (spans.length === 0)
364
+ return line;
365
+ const units = line.split('');
366
+ for (const [start, end] of spans)
367
+ for (let i = start; i < end; i++)
368
+ units[i] = 'x';
369
+ return units.join('');
370
+ };
371
+ // The pieces of a line between the separators found in its mask.
372
+ const cutAt = (line, mask, separator) => {
373
+ const pieces = [];
374
+ let from = 0;
375
+ for (const match of mask.matchAll(separator)) {
376
+ pieces.push(line.slice(from, match.index));
377
+ from = (match.index || 0) + match[0].length;
378
+ }
379
+ pieces.push(line.slice(from));
380
+ return pieces;
381
+ };
327
382
  /**
328
383
  * Helpers section
329
384
  */
@@ -343,10 +398,13 @@ const strbin = (str1, str2, cb) => {
343
398
  // string where `0` runs mark column ranges and `1` runs mark gaps.
344
399
  const makeMask = (lines, separators) => {
345
400
  const tmplLength = Math.max(...[...lines, ...separators].map(s => s.length));
401
+ // a table held apart by spaces alone splits on two of them, as a row on one line
402
+ // does; a table with bars keeps its own gaps
403
+ const spacedOnly = lines.every(line => detectLineSeparator(line) === 'whitespace');
346
404
  const masks = lines.map(str => {
347
405
  const tstr = str + ' '.repeat(tmplLength - str.length);
348
406
  const mask = [];
349
- const re = /\s+[+|\s]\s/g;
407
+ const re = spacedOnly ? /\s{2,}/g : /\s+[+|\s]\s/g;
350
408
  let match;
351
409
  while ((match = re.exec(tstr)) != null) {
352
410
  const tmpMask = '1'.repeat(match.index) + '0'.repeat(match[0].length);
@@ -402,38 +460,38 @@ const trimEdgeEmpty = (cells) => {
402
460
  return cells.slice(start, end);
403
461
  };
404
462
  // A separator has to stand apart from the content, so a bare `|` inside markup
405
- // such as L<text|url> is content, not a column break.
406
- const splitLineByPipe = (line) => trimEdgeEmpty(line.split(/(?<=^|\s)\|(?=\s|$)/).map(c => c.trim()));
407
- const splitLineByPlus = (line) => trimEdgeEmpty(line.split(/(?<=^|\s)\+(?=\s|$)/).map(c => c.trim()));
408
- const splitLineByWhitespace = (line) => line
409
- .trim()
410
- .split(/\s{2,}/)
463
+ // such as L<text|url> is content, not a column break. Separators are looked for in
464
+ // the mask, where a markup code closed on the line hides its own.
465
+ const splitLineByPipe = (line, mask = line) => trimEdgeEmpty(cutAt(line, mask, /(?<=^|\s)\|(?=\s|$)/g).map(c => c.trim()));
466
+ const splitLineByPlus = (line, mask = line) => trimEdgeEmpty(cutAt(line, mask, /(?<=^|\s)\+(?=\s|$)/g).map(c => c.trim()));
467
+ const splitLineByWhitespace = (line, mask = line) => cutAt(line, mask, /\s{2,}/g)
468
+ .map(c => c.trim())
411
469
  .filter(c => c !== '');
412
- const splitLineCells = (line) => {
470
+ const splitLineCells = (line, mask = line) => {
413
471
  const trimmed = line.trim();
414
472
  if (trimmed === '')
415
473
  return [];
416
- const kind = detectLineSeparator(line);
474
+ const kind = detectLineSeparator(mask);
417
475
  if (kind === 'pipe')
418
- return splitLineByPipe(line);
476
+ return splitLineByPipe(line, mask);
419
477
  if (kind === 'plus')
420
- return splitLineByPlus(line);
421
- return splitLineByWhitespace(line);
478
+ return splitLineByPlus(line, mask);
479
+ return splitLineByWhitespace(line, mask);
422
480
  };
423
481
  // Convert a row's raw text (which may span multiple lines) to cell values.
424
482
  // Multi-line rows: take the separator kind from the first non-blank line and
425
483
  // apply it to every line of the row, then aggregate column-wise so that a
426
484
  // continuation line (e.g. wrapped cell content) appends to the cell from the
427
485
  // previous line in the same column.
428
- const rowToCells = (rowValue) => {
486
+ const rowToCells = (rowValue, protect = line => line) => {
429
487
  const lines = rowValue.split(/\r?\n/).filter(l => l.trim() !== '');
430
488
  if (lines.length === 0)
431
489
  return [];
432
490
  if (lines.length === 1)
433
- return splitLineCells(lines[0]);
434
- const kind = detectLineSeparator(lines[0]);
491
+ return splitLineCells(lines[0], protect(lines[0]));
492
+ const kind = detectLineSeparator(protect(lines[0]));
435
493
  const splitFn = kind === 'pipe' ? splitLineByPipe : kind === 'plus' ? splitLineByPlus : splitLineByWhitespace;
436
- const lineCells = lines.map(splitFn);
494
+ const lineCells = lines.map(line => splitFn(line, protect(line)));
437
495
  const maxCols = Math.max(...lineCells.map(c => c.length));
438
496
  const merged = [];
439
497
  for (let i = 0; i < maxCols; i++) {
@@ -495,6 +553,12 @@ const isStructured = tableNode => Array.isArray(tableNode.content) &&
495
553
  tableNode.content.some(c => c && c.type === 'block' && (c.name === 'row' || c.name === 'cell'));
496
554
  exports.default = (opt = {}) => tree => {
497
555
  const report = makeTableReport(opt);
556
+ // the settings in force where each table stands, as a cell of it will read them
557
+ const scopes = new Map();
558
+ (0, configPropagation_1.walkConfigScopes)(tree, opt.config || {}, (block, scope) => {
559
+ if (block.name === 'table')
560
+ scopes.set(block, { ...scope });
561
+ });
498
562
  const transformer = (0, makeTransformer_1.default)({
499
563
  table: (node, ctx, visiter) => {
500
564
  // CSV/data source reference (spec §1672):
@@ -573,8 +637,11 @@ exports.default = (opt = {}) => tree => {
573
637
  // split each row into lines
574
638
  const lines = flattenDeep(rows.map(splitToLines));
575
639
  const separators = flattenDeep(seps.map(splitToLines));
640
+ const codeScope = codeScopeOf(node, scopes.get(node) || {});
641
+ const protect = (line) => protectCodes(line, codeScope);
642
+ const masks = lines.map(protect);
576
643
  // Rule 3: warn on mixed separator types within a single table
577
- detectMixedSeparators(lines, report, node);
644
+ detectMixedSeparators(masks, report, node);
578
645
  // collect text rows
579
646
  let textRows = [];
580
647
  (0, makeTransformer_1.default)({
@@ -589,25 +656,31 @@ exports.default = (opt = {}) => tree => {
589
656
  const makeHeaderRow = cells => makeBlock('row', cells, { config: [{ name: 'header', value: true, type: 'boolean' }] });
590
657
  const makeCell = text => makeBlock('cell', { type: 'text', value: text });
591
658
  // Routing: a whitespace-separated row on one line splits by its own
592
- // gaps — two spaces are enough there, while the positional mask needs
593
- // three. Rows with a visible separator keep the mask: an edge `|`
594
- // carries a real empty cell that per-line splitting would drop.
595
- const columnTemplate = makeMask(lines, separators);
596
- const seenSeparatorKinds = new Set(lines.map(detectLineSeparator));
659
+ // gaps. In a table held apart by spaces alone a row on several lines
660
+ // takes its columns from its own lines, so a line of another row does
661
+ // not close its gaps. Rows with a visible separator keep the shared
662
+ // mask: an edge `|` carries a real empty cell that per-line splitting
663
+ // would drop.
664
+ const columnTemplate = makeMask(masks, separators);
665
+ const seenSeparatorKinds = new Set(masks.map(detectLineSeparator));
666
+ const spacedOnly = seenSeparatorKinds.size === 1 && seenSeparatorKinds.has('whitespace');
597
667
  const useMixedSplitting = (seenSeparatorKinds.has('pipe') || seenSeparatorKinds.has('plus')) && seenSeparatorKinds.has('whitespace');
598
- const splitsItself = (line) => useMixedSplitting || detectLineSeparator(line) === 'whitespace';
668
+ const splitsItself = (line) => useMixedSplitting || detectLineSeparator(protect(line)) === 'whitespace';
599
669
  const splitToCells = (rowValue) => {
600
670
  const rowLines = rowValue.split(/\r?\n/).filter(l => l.trim() !== '');
601
671
  if (rowLines.length <= 1 && splitsItself(rowValue))
602
- return rowToCells(rowValue);
603
- return extractColumnsByTemplate(rowValue, columnTemplate);
672
+ return rowToCells(rowValue, protect);
673
+ const template = spacedOnly ? makeMask(rowLines.map(protect), separators) : columnTemplate;
674
+ return extractColumnsByTemplate(rowValue, template);
604
675
  };
605
676
  const res = (0, makeTransformer_1.default)({
606
677
  'row:text': row => {
607
678
  if (textRows.length == 1) {
608
679
  // No separator blocks: each line of the only text row becomes its own row
609
680
  const textRowsLines = flattenDeep([row.value].map(splitToLines));
610
- return textRowsLines.map(line => makeRow((splitsItself(line) ? splitLineCells(line) : extractColumnsByTemplate(line, columnTemplate)).map(makeCell)));
681
+ return textRowsLines.map(line => makeRow((splitsItself(line)
682
+ ? splitLineCells(line, protect(line))
683
+ : extractColumnsByTemplate(line, columnTemplate)).map(makeCell)));
611
684
  }
612
685
  return makeRow(splitToCells(row.value).map(makeCell));
613
686
  },
@@ -62,7 +62,14 @@ const testFoldedByAuthor = (node, ctx) => {
62
62
  };
63
63
  exports.testFoldedByAuthor = testFoldedByAuthor;
64
64
  // A fence has to be longer than any run of backticks inside what it encloses.
65
- const longestBacktickRun = (text) => Math.max(0, ...(text.match(/`+/g) || []).map(run => run.length));
65
+ const longestBacktickRun = (text) => {
66
+ // a loop: a long body holds more runs than Math.max takes arguments
67
+ let longest = 0;
68
+ for (const run of text.match(/`+/g) || [])
69
+ if (run.length > longest)
70
+ longest = run.length;
71
+ return longest;
72
+ };
66
73
  exports.longestBacktickRun = longestBacktickRun;
67
74
  // a heading, a directive, a comment or data says nothing a test could check, and a
68
75
  // directive wrapped into a group would lose the reach it has over what follows
package/lib/title.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { Node } from './types';
2
+ export type TitleEntry = {
3
+ kind: 'part';
4
+ content: Node[];
5
+ owners: Node[];
6
+ } | {
7
+ kind: 'rest';
8
+ node: Node;
9
+ };
10
+ export declare const titleParts: (node: {
11
+ content?: unknown;
12
+ }) => TitleEntry[];
13
+ export declare const isTitleBlock: (node: any) => boolean;
package/lib/title.js ADDED
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isTitleBlock = exports.titleParts = void 0;
4
+ const titleParts = (node) => {
5
+ const entries = [];
6
+ const walk = (children, owners) => {
7
+ const list = Array.isArray(children) ? children : children ? [children] : [];
8
+ list.forEach((child) => {
9
+ if (child && typeof child === 'object' && child.type === 'para') {
10
+ entries.push({ kind: 'part', content: child.content || [], owners: [...owners, child] });
11
+ }
12
+ else if (child && typeof child === 'object' && child.type === 'block' && child.name === 'para') {
13
+ walk(child.content, [...owners, child]);
14
+ }
15
+ else {
16
+ entries.push({ kind: 'rest', node: child });
17
+ }
18
+ });
19
+ };
20
+ walk(node.content, []);
21
+ return entries;
22
+ };
23
+ exports.titleParts = titleParts;
24
+ // a TITLE written in the singular or the plural, as the specification lets a semantic block be
25
+ const isTitleBlock = (node) => Boolean(node) && node.type === 'block' && (node.name === 'TITLE' || node.name === 'TITLES');
26
+ exports.isTitleBlock = isTitleBlock;
27
+ //# sourceMappingURL=title.js.map
package/lib/types.d.ts CHANGED
@@ -99,6 +99,7 @@ export interface Image {
99
99
  src: string;
100
100
  alt?: string;
101
101
  link?: string;
102
+ title?: string;
102
103
  }
103
104
  export interface ParaBuilt {
104
105
  type: 'para';
@@ -353,8 +354,12 @@ export interface Separator {
353
354
  type: 'separator';
354
355
  text: string;
355
356
  }
356
- export interface Block {
357
+ export interface SourceFormatMark {
358
+ sourceFormat?: 'markdown';
359
+ }
360
+ export interface Block extends SourceFormatMark {
357
361
  type: 'block';
362
+ markdownHtml?: 'block' | 'inline';
358
363
  location: Location;
359
364
  content: Array<Node>;
360
365
  margin: string;
@@ -417,17 +422,17 @@ export interface BlockTable extends Omit<Block, 'content'> {
417
422
  align?: ('left' | 'center' | 'right' | null)[];
418
423
  text?: string;
419
424
  }
420
- export interface TableCell {
425
+ export interface TableCell extends SourceFormatMark {
421
426
  name: 'cell';
422
427
  type: 'block';
423
428
  content: Array<PodNode>;
424
429
  }
425
- export interface TableRow {
430
+ export interface TableRow extends SourceFormatMark {
426
431
  name: 'row';
427
432
  type: 'block';
428
433
  content: Array<TableCell>;
429
434
  }
430
- export interface TableHead {
435
+ export interface TableHead extends SourceFormatMark {
431
436
  name: 'row';
432
437
  type: 'block';
433
438
  content: Array<TableCell>;
package/lib/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const version = "0.0.80";
1
+ export declare const version = "0.0.82";
package/lib/version.js CHANGED
@@ -2,5 +2,5 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.version = void 0;
4
4
  // generated by scripts/inject-version.mjs — do not edit by hand
5
- exports.version = '0.0.80';
5
+ exports.version = '0.0.82';
6
6
  //# sourceMappingURL=version.js.map
@@ -3,8 +3,17 @@
3
3
  */
4
4
  import Writer from './writer';
5
5
  declare class WriterMarkdown extends Writer {
6
+ codeDepth: number;
7
+ htmlDepth: number;
8
+ cellDepth: number;
9
+ paraStart: boolean;
10
+ lineText: string;
11
+ trailingBreaks: number | null;
12
+ pendingBreak: boolean;
6
13
  constructor(output?: any);
7
14
  escape(string: any): string;
15
+ writeRaw(str: any): void;
16
+ writeSource(text: string): void;
8
17
  _add_nesting(n: any): void;
9
18
  _remove_nesting(n: any): void;
10
19
  }
@@ -7,13 +7,115 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
7
7
  };
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  const writer_1 = __importDefault(require("./writer"));
10
+ // An ampersand opens a character reference only before a name or a number and a semicolon; one at the
11
+ // end of a piece is escaped, since the piece after it is not seen here. Left alone elsewhere, it keeps
12
+ // the query of an address a reader links by itself, as a tilde inside such an address is kept.
13
+ // a reader links a scheme in any case and www. only in small letters
14
+ const bareAddress = /(?:[hH][tT][tT][pP][sS]?:\/\/|www\.)[^\s<]*/g;
15
+ const escapeText = (text) => {
16
+ let out = '';
17
+ let from = 0;
18
+ for (const match of text.matchAll(bareAddress)) {
19
+ const at = match.index ?? 0;
20
+ out += escapeSigns(text.slice(from, at), true) + escapeSigns(match[0], false);
21
+ from = at + match[0].length;
22
+ }
23
+ return (out + escapeSigns(text.slice(from), true)).replace(/&(?=#?[A-Za-z0-9]+;|$)/g, '\\&');
24
+ };
25
+ const escapeSigns = (text, tilde) => text.replace(tilde ? /([\\`*_\[\]#|<~])/g : /([\\`*_\[\]#|<])/g, '\\$1');
26
+ // the prefixes of a quote and of an item come before the content of a line
27
+ const linePrefixes = /^(?:[ \t]*(?:>[ \t]?|(?:[-+*]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?))*[ \t]*/;
28
+ // Places in the text where a line starts with a sign a reader would take for a block: an item, a quote,
29
+ // the line under a heading or a rule, the line that aligns a table, a number that starts a list.
30
+ const lineStartMarks = (text, lineText) => {
31
+ const marks = [];
32
+ const before = lineText.replace(linePrefixes, '');
33
+ let start = 0;
34
+ text.split('\n').forEach((line, index) => {
35
+ const atStart = index > 0 || before === '';
36
+ const lead = line.length - line.replace(/^[ \t]+/, '').length;
37
+ const content = line.slice(lead);
38
+ const at = start + lead;
39
+ if (atStart) {
40
+ if (/^[-+](?:[ \t]|$)/.test(content) || /^>/.test(content))
41
+ marks.push(at);
42
+ else if (/^[-=][-= \t]*$/.test(content) || /^:?-+:?[ \t]*$/.test(content) || /^:-*[ \t]*$/.test(content))
43
+ marks.push(at);
44
+ else {
45
+ const number = content.match(/^\d{1,9}(?=[.)](?:[ \t]|$))/);
46
+ if (number)
47
+ marks.push(at + number[0].length);
48
+ }
49
+ }
50
+ else if (index === 0 && /^\d{1,9}$/.test(before) && /^[.)](?:[ \t]|$)/.test(line)) {
51
+ marks.push(start);
52
+ }
53
+ start += line.length + 1;
54
+ });
55
+ return marks;
56
+ };
10
57
  class WriterMarkdown extends writer_1.default {
58
+ // inside code a reader takes < and & as written
59
+ codeDepth = 0;
60
+ // inside a frame of HTML around Markdown: raw text there could close the frame
61
+ htmlDepth = 0;
62
+ // a table cell folded onto one line: a fence does not hold there
63
+ cellDepth = 0;
64
+ // a paragraph has begun and shown nothing yet: an indent here would make it code
65
+ paraStart = false;
66
+ // what was written after the last line break
67
+ lineText = '';
68
+ // the line breaks at the end of what was written; null before anything of the
69
+ // current content, where a block needs no blank line before it
70
+ trailingBreaks = null;
71
+ // a block of HTML of Markdown wants a blank line before what comes after it in
72
+ // the same content; it is written when that comes, so a tight list stays tight
73
+ pendingBreak = false;
11
74
  constructor(output) {
12
75
  super(output);
13
76
  }
14
77
  escape(string) {
15
- return (string + '').replace(/([\\`*_\[\]#|])/g, '\\$1');
78
+ const text = string + '';
79
+ // inside code a reader shows a backslash as written, so nothing is escaped there; a bar
80
+ // of code in a cell of a pipe table is kept by the code as a whole (exportMarkdown)
81
+ if (this.codeDepth > 0)
82
+ return text;
83
+ // a sign a reader takes for a block only at the start of a line gets a backslash there
84
+ const marks = lineStartMarks(text, this.lineText);
85
+ let out = '';
86
+ let from = 0;
87
+ for (const at of marks) {
88
+ out += escapeText(text.slice(from, at)) + '\\';
89
+ from = at;
90
+ }
91
+ return out + escapeText(text.slice(from));
92
+ }
93
+ writeRaw(str) {
94
+ if (this.pendingBreak && typeof str === 'string' && /[^\n]/.test(str)) {
95
+ this.pendingBreak = false;
96
+ // the line breaks the piece starts with count, so the blank line is the same however
97
+ // the writing is split into pieces
98
+ const leading = str.length - str.replace(/^\n+/, '').length;
99
+ const missing = 2 - (this.trailingBreaks ?? 2) - leading;
100
+ if (missing > 0)
101
+ this.writeRaw('\n'.repeat(missing));
102
+ }
103
+ super.writeRaw(str);
104
+ if (typeof str === 'string' && str !== '') {
105
+ const end = str.lastIndexOf('\n');
106
+ this.lineText = end === -1 ? this.lineText + str : str.slice(end + 1);
107
+ const breaks = str.length - str.replace(/\n+$/, '').length;
108
+ this.trailingBreaks = breaks === str.length ? (this.trailingBreaks ?? 0) + breaks : breaks;
109
+ }
110
+ if (this.paraStart && /[^ \t\n]/.test(str))
111
+ this.paraStart = false;
112
+ }
113
+ // text of the document written as it stands, such as the body of a code block
114
+ writeSource(text) {
115
+ this.writeRaw(text);
16
116
  }
117
+ // the signs of a quote for a writer that writes as it goes; with a function for its
118
+ // output, the export writes a quote aside and puts the signs on every line of it
17
119
  _add_nesting(n) {
18
120
  this.writeRaw('> '.repeat(n));
19
121
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@podlite/schema",
3
- "version": "0.0.80",
3
+ "version": "0.0.82",
4
4
  "description": "Parser and AST schema for Podlite: typed blocks with positions, selectors, validate, traverse, and transform.",
5
5
  "main": "./lib/index.js",
6
6
  "sideEffects": false,
@@ -36,7 +36,7 @@
36
36
  "CHANGELOG.md"
37
37
  ],
38
38
  "engines": {
39
- "node": ">=20.19"
39
+ "node": "^20.19.0 || >=22.12.0"
40
40
  },
41
41
  "engineStrict": true,
42
42
  "publishConfig": {
@@ -73,6 +73,7 @@
73
73
  "entities": "^4.5.0",
74
74
  "events": "^3.1.0",
75
75
  "json-pointer": "^0.6.1",
76
+ "marked": "16.4.2",
76
77
  "nanoid": "3.1.30",
77
78
  "slugify": "^1.6.6"
78
79
  },