@agentshouse/mdmodel 0.1.0-c375119e5613a → 0.1.0-c3c0e116a89f8

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 (143) hide show
  1. package/API.md +131 -109
  2. package/README.md +8 -6
  3. package/dist/definition.d.ts +2 -1
  4. package/dist/definition.d.ts.map +1 -1
  5. package/dist/definition.js +107 -26
  6. package/dist/divide.d.ts.map +1 -1
  7. package/dist/divide.js +5 -4
  8. package/dist/document.d.ts +5 -5
  9. package/dist/document.d.ts.map +1 -1
  10. package/dist/document.js +114 -79
  11. package/dist/event.d.ts +78 -0
  12. package/dist/event.d.ts.map +1 -0
  13. package/dist/event.js +201 -0
  14. package/dist/facts.d.ts +15 -0
  15. package/dist/facts.d.ts.map +1 -0
  16. package/dist/facts.js +41 -0
  17. package/dist/index.d.ts +23 -10
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +14 -7
  20. package/dist/kinds.d.ts +18 -0
  21. package/dist/kinds.d.ts.map +1 -0
  22. package/dist/kinds.js +150 -0
  23. package/dist/markdown.d.ts +51 -0
  24. package/dist/markdown.d.ts.map +1 -0
  25. package/dist/markdown.js +271 -0
  26. package/dist/paths.d.ts.map +1 -1
  27. package/dist/paths.js +9 -2
  28. package/dist/pattern.d.ts +10 -0
  29. package/dist/pattern.d.ts.map +1 -0
  30. package/dist/pattern.js +356 -0
  31. package/dist/project.d.ts.map +1 -1
  32. package/dist/project.js +16 -21
  33. package/dist/query/language.d.ts +254 -0
  34. package/dist/query/language.d.ts.map +1 -0
  35. package/dist/query/language.js +620 -0
  36. package/dist/query/match.d.ts +14 -0
  37. package/dist/query/match.d.ts.map +1 -0
  38. package/dist/query/match.js +150 -0
  39. package/dist/query/rows.d.ts +32 -0
  40. package/dist/query/rows.d.ts.map +1 -0
  41. package/dist/query/rows.js +161 -0
  42. package/dist/query/sql.d.ts +39 -0
  43. package/dist/query/sql.d.ts.map +1 -0
  44. package/dist/query/sql.js +285 -0
  45. package/dist/reserved.d.ts +6 -0
  46. package/dist/reserved.d.ts.map +1 -0
  47. package/dist/reserved.js +21 -0
  48. package/dist/schema.d.ts +1 -0
  49. package/dist/schema.d.ts.map +1 -1
  50. package/dist/schema.js +55 -4
  51. package/dist/types.d.ts +12 -3
  52. package/dist/types.d.ts.map +1 -1
  53. package/dist/validate.d.ts +28 -5
  54. package/dist/validate.d.ts.map +1 -1
  55. package/dist/validate.js +325 -160
  56. package/dist/yaml.d.ts.map +1 -1
  57. package/dist/yaml.js +40 -14
  58. package/fixtures/README.md +25 -3
  59. package/fixtures/cases/conditional-section/context.json +1 -0
  60. package/fixtures/cases/conditional-section/expected.json +6 -0
  61. package/fixtures/cases/conditional-section/library/questions/hosting.md +9 -0
  62. package/fixtures/cases/conditional-section/library/questions/payments.md +12 -0
  63. package/fixtures/cases/conditional-section/schema.yaml +14 -0
  64. package/fixtures/cases/lazy-list-item/context.json +1 -0
  65. package/fixtures/cases/lazy-list-item/expected.json +3 -0
  66. package/fixtures/cases/lazy-list-item/library/item.md +8 -0
  67. package/fixtures/cases/lazy-list-item/schema.yaml +3 -0
  68. package/fixtures/cases/link-into-a-reserved-name/context.json +1 -0
  69. package/fixtures/cases/link-into-a-reserved-name/expected.json +5 -0
  70. package/fixtures/cases/link-into-a-reserved-name/library/notes/a.md +6 -0
  71. package/fixtures/cases/link-into-a-reserved-name/schema.yaml +3 -0
  72. package/fixtures/cases/link-into-a-reserved-name-from-an-untyped-document/context.json +1 -0
  73. package/fixtures/cases/link-into-a-reserved-name-from-an-untyped-document/expected.json +5 -0
  74. package/fixtures/cases/link-into-a-reserved-name-from-an-untyped-document/library/notes/b.md +5 -0
  75. package/fixtures/cases/member-on-an-untyped-document/context.json +1 -0
  76. package/fixtures/cases/member-on-an-untyped-document/expected.json +6 -0
  77. package/fixtures/cases/member-on-an-untyped-document/library/note.md +4 -0
  78. package/fixtures/cases/member-on-another-type/context.json +1 -0
  79. package/fixtures/cases/member-on-another-type/expected.json +6 -0
  80. package/fixtures/cases/member-on-another-type/library/note.md +4 -0
  81. package/fixtures/cases/member-on-another-type/schema.yaml +7 -0
  82. package/fixtures/cases/reference-into-a-reserved-name/context.json +1 -0
  83. package/fixtures/cases/reference-into-a-reserved-name/expected.json +6 -0
  84. package/fixtures/cases/reference-into-a-reserved-name/library/notes/a.md +4 -0
  85. package/fixtures/cases/reference-into-a-reserved-name/library/settings/brief.md +1 -0
  86. package/fixtures/cases/reference-into-a-reserved-name/schema.yaml +3 -0
  87. package/fixtures/cases/room-md-declares-a-type/context.json +1 -0
  88. package/fixtures/cases/room-md-declares-a-type/expected.json +6 -0
  89. package/fixtures/cases/room-md-declares-a-type/library/ROOM.md +5 -0
  90. package/fixtures/cases/thematic-break-in-a-list-section/context.json +1 -0
  91. package/fixtures/cases/thematic-break-in-a-list-section/expected.json +6 -0
  92. package/fixtures/cases/thematic-break-in-a-list-section/library/item.md +7 -0
  93. package/fixtures/cases/thematic-break-in-a-list-section/schema.yaml +3 -0
  94. package/fixtures/cases/typed-path-names-another-type/context.json +11 -0
  95. package/fixtures/cases/typed-path-names-another-type/expected.json +6 -0
  96. package/fixtures/cases/typed-path-names-another-type/library/settings/prefs/one.md +3 -0
  97. package/fixtures/cases/typed-path-names-another-type/schema.yaml +6 -0
  98. package/fixtures/cases/typed-path-names-its-type/context.json +11 -0
  99. package/fixtures/cases/typed-path-names-its-type/expected.json +3 -0
  100. package/fixtures/cases/typed-path-names-its-type/library/settings/prefs/deeper/two.md +1 -0
  101. package/fixtures/cases/typed-path-names-its-type/library/settings/prefs/one.md +4 -0
  102. package/fixtures/cases/typed-path-names-its-type/schema.yaml +6 -0
  103. package/fixtures/cases/typed-path-names-no-type/context.json +11 -0
  104. package/fixtures/cases/typed-path-names-no-type/expected.json +6 -0
  105. package/fixtures/cases/typed-path-names-no-type/library/settings/prefs/one.md +1 -0
  106. package/fixtures/cases/typed-path-names-no-type/schema.yaml +6 -0
  107. package/fixtures/cases/unnamed-typed-path-checks-its-fields/context.json +11 -0
  108. package/fixtures/cases/unnamed-typed-path-checks-its-fields/expected.json +6 -0
  109. package/fixtures/cases/unnamed-typed-path-checks-its-fields/library/rooms/team/tasks/plan.md +4 -0
  110. package/fixtures/cases/unnamed-typed-path-checks-its-fields/schema.yaml +5 -0
  111. package/fixtures/cases/unnamed-typed-path-names-a-type/context.json +11 -0
  112. package/fixtures/cases/unnamed-typed-path-names-a-type/expected.json +6 -0
  113. package/fixtures/cases/unnamed-typed-path-names-a-type/library/rooms/team/tasks/plan.md +6 -0
  114. package/fixtures/cases/unnamed-typed-path-names-a-type/schema.yaml +5 -0
  115. package/fixtures/cases/unnamed-typed-path-reads-its-type/context.json +11 -0
  116. package/fixtures/cases/unnamed-typed-path-reads-its-type/expected.json +3 -0
  117. package/fixtures/cases/unnamed-typed-path-reads-its-type/library/rooms/team/plan.md +1 -0
  118. package/fixtures/cases/unnamed-typed-path-reads-its-type/library/rooms/team/tasks/plan.md +5 -0
  119. package/fixtures/cases/unnamed-typed-path-reads-its-type/schema.yaml +5 -0
  120. package/fixtures/cases/unnamed-typed-path-without-a-body/context.json +11 -0
  121. package/fixtures/cases/unnamed-typed-path-without-a-body/expected.json +5 -0
  122. package/fixtures/cases/unnamed-typed-path-without-a-body/library/rooms/team/tasks/plan.md +5 -0
  123. package/fixtures/cases/unnamed-typed-path-without-a-body/schema.yaml +5 -0
  124. package/fixtures/division.json +47 -2
  125. package/fixtures/preamble.json +24 -3
  126. package/fixtures/projection.json +105 -2
  127. package/fixtures/queries.json +964 -0
  128. package/package.json +16 -2
  129. package/dist/blocks.d.ts +0 -11
  130. package/dist/blocks.d.ts.map +0 -1
  131. package/dist/blocks.js +0 -69
  132. package/dist/condition.d.ts +0 -162
  133. package/dist/condition.d.ts.map +0 -1
  134. package/dist/condition.js +0 -616
  135. package/dist/links.d.ts +0 -29
  136. package/dist/links.d.ts.map +0 -1
  137. package/dist/links.js +0 -788
  138. package/dist/profile.d.ts +0 -6
  139. package/dist/profile.d.ts.map +0 -1
  140. package/dist/profile.js +0 -5
  141. package/dist/sections.d.ts +0 -11
  142. package/dist/sections.d.ts.map +0 -1
  143. package/dist/sections.js +0 -57
@@ -1,4 +1,5 @@
1
1
  import { MEMBER_FIELD, RECEIVED_FIELD, SITE_FIELD, TYPE_FIELD } from './fields.js';
2
+ import { linearPattern } from './pattern.js';
2
3
  import { equalValue, isRecord, jsValue, parseYamlMapping, YamlError } from './yaml.js';
3
4
  export const JSON_TYPES = [
4
5
  'string',
@@ -24,16 +25,20 @@ const ANNOTATIONS = new Set([
24
25
  'writeOnly',
25
26
  ]);
26
27
  const FIELD_RULES = ['change_roles', 'initial_roles', 'transitions'];
28
+ const PROVIDED_KEYWORDS = ['create_roles', 'delete_roles'];
29
+ const NO_TYPES = Object.freeze({ types: Object.freeze({}) });
27
30
  const DEFS_REFERENCE = '#/$defs/';
31
+ const UNBOUNDED_FORMAT = 'url';
28
32
  const UNRESOLVED = /[\u0000-\u001f\u007f%[\]\\^{|}]|\s$/u;
29
33
  export const ARRAY_INDEX = /^(?:0|[1-9][0-9]*)$/u;
34
+ export const JSON_POINTER = /^(?:\/(?:[^~/]|~[01])*)*$/u;
30
35
  const HOUSE_KEYS = {
31
36
  [TYPE_FIELD]: { prose: false },
32
37
  [SITE_FIELD]: { prose: false },
33
38
  [RECEIVED_FIELD]: { prose: false },
34
39
  };
35
40
  function refuse(rule, location) {
36
- return location === undefined ? { rule } : { rule, location };
41
+ return { rule, location };
37
42
  }
38
43
  export function escapePointer(key) {
39
44
  return key.replaceAll('~', '~0').replaceAll('/', '~1');
@@ -45,12 +50,12 @@ export function pointerSegments(pointer) {
45
50
  return pointer.split('/').slice(1).map(unescapePointer);
46
51
  }
47
52
  export function refTarget(reference, defs) {
48
- if (!reference.startsWith(DEFS_REFERENCE) || UNRESOLVED.test(reference))
49
- return undefined;
50
- const segments = reference.slice(DEFS_REFERENCE.length).split('/');
51
- const [name = '', ...rest] = segments.map(unescapePointer);
52
- if (segments.some((segment) => escapePointer(unescapePointer(segment)) !== segment))
53
+ const pointer = reference.slice('#'.length);
54
+ if (!reference.startsWith(DEFS_REFERENCE) ||
55
+ UNRESOLVED.test(reference) ||
56
+ !JSON_POINTER.test(pointer))
53
57
  return undefined;
58
+ const [, name = '', ...rest] = pointerSegments(pointer);
54
59
  if (!Object.hasOwn(defs, name))
55
60
  return undefined;
56
61
  let node = defs[name];
@@ -81,15 +86,7 @@ export function refTarget(reference, defs) {
81
86
  return { name, node };
82
87
  }
83
88
  function compiles(pattern) {
84
- if (typeof pattern !== 'string')
85
- return false;
86
- try {
87
- new RegExp(pattern, 'u');
88
- return true;
89
- }
90
- catch {
91
- return false;
92
- }
89
+ return typeof pattern === 'string' && linearPattern(pattern) !== null;
93
90
  }
94
91
  function finite(value) {
95
92
  return typeof value === 'number' && Number.isFinite(value);
@@ -103,7 +100,7 @@ function strings(value) {
103
100
  new Set(value).size === value.length);
104
101
  }
105
102
  function schemaFailure(value, at, context) {
106
- if (typeof value === 'boolean')
103
+ if (!context.checked || typeof value === 'boolean')
107
104
  return undefined;
108
105
  if (!isRecord(value))
109
106
  return refuse('schema', at);
@@ -199,7 +196,7 @@ const KEYWORDS = {
199
196
  uniqueItems: FLAG,
200
197
  required: strings,
201
198
  dependentRequired: (value) => isRecord(value) && Object.values(value).every(strings),
202
- format: TEXT,
199
+ format: (value) => typeof value === 'string' && value !== UNBOUNDED_FORMAT,
203
200
  contentEncoding: TEXT,
204
201
  contentMediaType: TEXT,
205
202
  title: TEXT,
@@ -447,7 +444,7 @@ export function itemFacts(facts, index) {
447
444
  export function memberFacts(facts, key) {
448
445
  if (facts.properties !== undefined && Object.hasOwn(facts.properties, key))
449
446
  return facts.properties[key];
450
- const pattern = facts.patterns?.find((one) => new RegExp(one.pattern, 'u').test(key));
447
+ const pattern = facts.patterns?.find((one) => linearPattern(one.pattern).test(key));
451
448
  return pattern === undefined ? facts.additional : pattern.facts;
452
449
  }
453
450
  export function crossedFacts(facts) {
@@ -550,6 +547,56 @@ function readSections(value, at, context) {
550
547
  }
551
548
  return { sections };
552
549
  }
550
+ function branchSectionsFailure(sections, declared, where) {
551
+ if (!isRecord(sections))
552
+ return refuse('sections', where);
553
+ for (const [name, spec] of Object.entries(sections)) {
554
+ const place = `${where}/${escapePointer(name)}`;
555
+ const own = isRecord(declared) && Object.hasOwn(declared, name) ? declared[name] : undefined;
556
+ if (!isRecord(spec) || !isRecord(own))
557
+ return refuse('sections', place);
558
+ const { required, ...kind } = spec;
559
+ const { required: _required, ...ownKind } = own;
560
+ if (required !== undefined && typeof required !== 'boolean')
561
+ return refuse('sections', `${place}/required`);
562
+ if (!equalValue(kind, ownKind))
563
+ return refuse('sections', place);
564
+ }
565
+ return undefined;
566
+ }
567
+ function withoutBranchSections(schema, declared, at) {
568
+ const kept = { ...schema };
569
+ if (Array.isArray(schema.allOf)) {
570
+ const entries = [];
571
+ for (const [index, entry] of schema.allOf.entries()) {
572
+ const read = isRecord(entry)
573
+ ? withoutBranchSections(entry, declared, `${at}/allOf/${index}`)
574
+ : { schema: entry };
575
+ if ('failure' in read)
576
+ return read;
577
+ entries.push(read.schema);
578
+ }
579
+ kept.allOf = entries;
580
+ }
581
+ if (schema.if === undefined)
582
+ return { schema: kept };
583
+ for (const branch of ['then', 'else']) {
584
+ const held = schema[branch];
585
+ if (!isRecord(held))
586
+ continue;
587
+ const { sections, ...rest } = held;
588
+ const failure = sections === undefined
589
+ ? undefined
590
+ : branchSectionsFailure(sections, declared, `${at}/${branch}/sections`);
591
+ if (failure !== undefined)
592
+ return { failure };
593
+ const read = withoutBranchSections(rest, declared, `${at}/${branch}`);
594
+ if ('failure' in read)
595
+ return read;
596
+ kept[branch] = read.schema;
597
+ }
598
+ return { schema: kept };
599
+ }
553
600
  function deepFreeze(value) {
554
601
  if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
555
602
  Object.freeze(value);
@@ -587,8 +634,9 @@ function composites(node, defs, seen) {
587
634
  const target = typeof node.$ref === 'string' ? refTarget(node.$ref, defs)?.node : undefined;
588
635
  const conditioned = () => {
589
636
  const met = composites(node.then ?? true, defs, seen);
590
- return COMPOSITES.filter((kind) => (composites(node.if, defs, seen).includes(kind) && met.includes(kind)) ||
591
- composites(node.else ?? true, defs, seen).includes(kind));
637
+ const condition = composites(node.if, defs, seen);
638
+ const otherwise = composites(node.else ?? true, defs, seen);
639
+ return COMPOSITES.filter((kind) => (condition.includes(kind) && met.includes(kind)) || otherwise.includes(kind));
592
640
  };
593
641
  const bounds = [
594
642
  typed(node.type),
@@ -657,6 +705,26 @@ function unruled(schema) {
657
705
  }
658
706
  return { schema: written.size === 0 ? schema : { ...schema, properties }, written };
659
707
  }
708
+ function providedType(name, value, provided, checked) {
709
+ const at = `/${escapePointer(name)}`;
710
+ if (checked && provided.nameable?.includes(name) !== true)
711
+ return refuse('provided-type', at);
712
+ if (!isRecord(value))
713
+ return refuse('schema', at);
714
+ const declared = Object.keys(value).find((key) => !PROVIDED_KEYWORDS.includes(key));
715
+ if (checked && declared !== undefined)
716
+ return refuse('provided-type', `${at}/${escapePointer(declared)}`);
717
+ const { create_roles: createRoles, delete_roles: deleteRoles } = value;
718
+ if (createRoles !== undefined && !roleNames(createRoles))
719
+ return refuse('create_roles', `${at}/create_roles`);
720
+ if (deleteRoles !== undefined && !roleNames(deleteRoles))
721
+ return refuse('delete_roles', `${at}/delete_roles`);
722
+ return {
723
+ ...provided.types[name],
724
+ ...(createRoles === undefined ? {} : { createRoles }),
725
+ ...(deleteRoles === undefined ? {} : { deleteRoles }),
726
+ };
727
+ }
660
728
  function readType(name, value, context) {
661
729
  const at = `/${escapePointer(name)}`;
662
730
  if (!isRecord(value))
@@ -673,7 +741,10 @@ function readType(name, value, context) {
673
741
  : readSections(declared, `${at}/sections`, context);
674
742
  if ('failure' in read)
675
743
  return read.failure;
676
- const { schema, written } = unruled(ruled);
744
+ const unbranched = withoutBranchSections(ruled, declared, at);
745
+ if ('failure' in unbranched)
746
+ return unbranched.failure;
747
+ const { schema, written } = unruled(unbranched.schema);
677
748
  const failure = schemaFailure(schema, at, context);
678
749
  if (failure !== undefined)
679
750
  return failure;
@@ -712,7 +783,7 @@ function readType(name, value, context) {
712
783
  function lineAt(text, offset) {
713
784
  return text.slice(0, offset).split(/\r\n|\r|\n/).length;
714
785
  }
715
- export function readSchema(text) {
786
+ export function readSchema(text, provided = NO_TYPES, checked = true) {
716
787
  let root;
717
788
  try {
718
789
  root = jsValue(parseYamlMapping(text, 0, text.length));
@@ -726,11 +797,15 @@ export function readSchema(text) {
726
797
  if (!isRecord(defs))
727
798
  return refuse('$defs', '/$defs');
728
799
  const names = Object.keys(root).filter((key) => key !== '$defs');
729
- for (const name of names) {
800
+ for (const name of checked ? names : []) {
730
801
  if (name === '' || name.startsWith('$') || name === BUILT_IN_TYPE || name === ATTACHMENT)
731
802
  return refuse('schema-type-name', `/${escapePointer(name)}`);
732
803
  }
733
- const context = { defs, types: new Set(names) };
804
+ const context = {
805
+ defs,
806
+ types: new Set([...names, ...Object.keys(provided.types)]),
807
+ checked,
808
+ };
734
809
  for (const [name, def] of Object.entries(defs)) {
735
810
  const failure = schemaFailure(def, `/$defs/${escapePointer(name)}`, context);
736
811
  if (failure !== undefined)
@@ -739,15 +814,21 @@ export function readSchema(text) {
739
814
  const types = Object.create(null);
740
815
  let marked = false;
741
816
  for (const name of names) {
742
- const definition = readType(name, root[name], context);
817
+ const definition = Object.hasOwn(provided.types, name)
818
+ ? providedType(name, root[name], provided, checked)
819
+ : readType(name, root[name], context);
743
820
  if ('rule' in definition)
744
821
  return definition;
745
- if (definition.memberDocument) {
822
+ if (checked && definition.memberDocument) {
746
823
  if (marked)
747
824
  return refuse('member_document', `/${escapePointer(name)}/member_document`);
748
825
  marked = true;
749
826
  }
750
827
  types[name] = deepFreeze(definition);
751
828
  }
829
+ for (const [name, definition] of Object.entries(provided.types)) {
830
+ if (!Object.hasOwn(types, name))
831
+ types[name] = definition;
832
+ }
752
833
  return Object.freeze({ types: Object.freeze(types) });
753
834
  }
@@ -1 +1 @@
1
- {"version":3,"file":"divide.d.ts","sourceRoot":"","sources":["../src/divide.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,QAAQ,EAAE,eAAe,EAAE,QAAQ,EAAgB,MAAM,YAAY,CAAC;AAwXpF,wBAAgB,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,QAAQ,CAc3F"}
1
+ {"version":3,"file":"divide.d.ts","sourceRoot":"","sources":["../src/divide.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,QAAQ,EAAE,eAAe,EAAE,QAAQ,EAAgB,MAAM,YAAY,CAAC;AAwXpF,wBAAgB,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,GAAG,QAAQ,CAe3F"}
package/dist/divide.js CHANGED
@@ -1,4 +1,5 @@
1
- import { blockRanges, headingLines } from './blocks.js';
1
+ import { readingOf } from './document.js';
2
+ import { blockRanges, headingsIn } from './markdown.js';
2
3
  import { firstEditFrom, projectionInput, rangeText, } from './project.js';
3
4
  import { refusal } from './refuse.js';
4
5
  const SMALLEST_BOUND = 2;
@@ -12,8 +13,7 @@ function node(draft) {
12
13
  };
13
14
  }
14
15
  function forest(state, range) {
15
- const content = state.content;
16
- const headings = headingLines(content, range.start, range.end);
16
+ const headings = headingsIn(state.reading, range.start, range.end);
17
17
  const roots = [];
18
18
  const open = [];
19
19
  const first = headings[0]?.start ?? range.end;
@@ -282,7 +282,7 @@ function ownBlocks(subject, end, blocks) {
282
282
  }
283
283
  function divideNode(state, subject) {
284
284
  const end = subject.children[0]?.start ?? subject.end;
285
- const blocks = blockRanges(state.content, subject.bodyStart, end);
285
+ const blocks = blockRanges(state.reading, subject.bodyStart, end);
286
286
  const children = { heading: '', emitted: 0 };
287
287
  if (blocks.length === 0 && subject.children.length > 0) {
288
288
  const [first, ...rest] = subject.children;
@@ -311,6 +311,7 @@ export function divide(document, file, context) {
311
311
  return { ok: false, refusal: result.refusal };
312
312
  const state = {
313
313
  content: document.content,
314
+ reading: readingOf(document),
314
315
  edits: result.input.edits,
315
316
  bound: context.bound,
316
317
  spans: [],
@@ -1,18 +1,18 @@
1
1
  import { type Definition } from './definition.js';
2
- import { type LinkInventory } from './links.js';
3
- import type { ApplyResult, BodyResult, FrontmatterResult, Change, Document, Link, LinkOccurrence, ParseResult } from './types.js';
2
+ import { type HrefOccurrence, type Reading } from './markdown.js';
3
+ import type { ApplyResult, BodyResult, FrontmatterResult, Change, Document, Link, ParseResult, UnlinkedBody } from './types.js';
4
4
  import { type YamlMap } from './yaml.js';
5
- export declare function inventoryOf(document: Document): LinkInventory;
5
+ export declare function readingOf(document: Document): Reading;
6
+ export declare function linkDestinations(document: Document): readonly HrefOccurrence[];
6
7
  export declare function parseFrontmatter(content: string, file?: string): FrontmatterResult;
7
8
  export declare function parse(content: string, file?: string): ParseResult;
8
9
  export declare function relativize(document: Document, file: string, handle: string, definition?: Definition, kept?: ReadonlySet<string>): ApplyResult;
9
10
  export declare function relativizeBody(body: string, file: string, handle: string): BodyResult;
10
11
  export declare function relinkBody(body: string, file: string, moves: ReadonlyMap<string, string>): BodyResult;
12
+ export declare function unlinkBody(body: string, hrefs: ReadonlySet<string>): UnlinkedBody;
11
13
  export declare function links(document: Document, file: string): readonly Link[];
12
- export declare function linkOccurrences(document: Document, file: string): readonly LinkOccurrence[];
13
14
  export declare function bodyLinks(body: string, file: string): readonly Link[];
14
15
  export declare function apply(document: Document, changes: readonly Change[]): ApplyResult;
15
16
  export declare function serialize(document: Document): string;
16
- export declare function fieldStart(document: Document, pointer: string): number | undefined;
17
17
  export declare function frontmatter(document: Document): YamlMap | null;
18
18
  //# sourceMappingURL=document.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"document.d.ts","sourceRoot":"","sources":["../src/document.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgC,KAAK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CAAa,GACpC,WAAW,CAuBb;AAED,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,UAAU,CAUrF;AAED,wBAAgB,UAAU,CACxB,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GACjC,UAAU,CAkBZ;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,YAAY,CAqBjF;AAeD,wBAAgB,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAEvE;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAErE;AAsMD,wBAAgB,KAAK,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,WAAW,CA+CjF;AAED,wBAAgB,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,CAEpD;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,GAAG,IAAI,CAE9D"}
package/dist/document.js CHANGED
@@ -1,38 +1,53 @@
1
1
  import { ARRAY_INDEX, pointerSegments } from './definition.js';
2
- import { destinations, hrefOccurrences, linkInventory, } from './links.js';
2
+ import { destinations, hrefOccurrences, read, sectionSpans, sectionsRecord, } from './markdown.js';
3
3
  import { destinationPath, relative, retarget, roomPath, roomTarget, SHELL_ROOMS, shellTarget, target, } from './paths.js';
4
4
  import { references } from './references.js';
5
- import { headingSpans, sectionsRecord } from './sections.js';
6
5
  import { refusal } from './refuse.js';
7
6
  import { bodyStartAfterYaml, bodyStartOf, equalValue, extractFrontmatter, frontmatterValue, jsValue, lineEnding, mapEntry, parseYamlMapping, serializeJs, serializeKey, YamlError, } from './yaml.js';
8
- const internals = new WeakMap();
9
- const inventories = new WeakMap();
10
- export function inventoryOf(document) {
11
- const held = inventories.get(document);
12
- if (held !== undefined)
13
- return held;
14
- const inventory = linkInventory(document.content.slice(bodyStartOf(document.content)));
15
- inventories.set(document, inventory);
16
- return inventory;
7
+ const HELD = Symbol('held');
8
+ function heldOf(document) {
9
+ return document[HELD];
10
+ }
11
+ function bodyReading(content, bodyStart) {
12
+ return read(content.slice(bodyStart), bodyStart);
13
+ }
14
+ function heldReading(content, held) {
15
+ held.reading ??= bodyReading(content, held.internal.bodyStart);
16
+ return held.reading;
17
+ }
18
+ export function readingOf(document) {
19
+ const held = heldOf(document);
20
+ return held === undefined
21
+ ? bodyReading(document.content, bodyStartOf(document.content))
22
+ : heldReading(document.content, held);
23
+ }
24
+ export function linkDestinations(document) {
25
+ const bodyStart = heldOf(document)?.internal.bodyStart ?? bodyStartOf(document.content);
26
+ return document.content.includes('[', bodyStart) ? destinations(readingOf(document)) : [];
27
+ }
28
+ function heldParts(content, held) {
29
+ if (held.parts !== undefined)
30
+ return held.parts;
31
+ const spans = sectionSpans(heldReading(content, held), content.length);
32
+ held.parts = {
33
+ preamble: content.slice(held.internal.bodyStart, spans[0]?.headingStart),
34
+ sections: Object.freeze(sectionsRecord(spans, content)),
35
+ };
36
+ return held.parts;
17
37
  }
18
38
  function refuse(file, rule, location) {
19
39
  return location === undefined ? refusal(file, rule) : refusal(file, rule, { location });
20
40
  }
21
- function freezeDocument(content, type, fields, preamble, sections, internal) {
22
- const document = Object.freeze({
23
- content,
24
- type,
25
- fields: Object.freeze(fields),
26
- preamble,
27
- sections: Object.freeze(sections),
28
- });
29
- internals.set(document, internal);
30
- return document;
41
+ function freezeDocument(content, type, fields, internal) {
42
+ const held = { internal };
43
+ return Object.freeze(Object.defineProperties({ content, type, fields: Object.freeze(fields) }, {
44
+ preamble: { enumerable: true, get: () => heldParts(content, held).preamble },
45
+ sections: { enumerable: true, get: () => heldParts(content, held).sections },
46
+ [HELD]: { value: held },
47
+ }));
31
48
  }
32
49
  function declaredType(fields) {
33
50
  const value = fields.type;
34
- if (value === undefined || value === null)
35
- return undefined;
36
51
  if (typeof value !== 'string' || value === '')
37
52
  return undefined;
38
53
  return value;
@@ -46,9 +61,6 @@ function opened(content, file) {
46
61
  try {
47
62
  const root = parseYamlMapping(content, fence.yamlStart, fence.yamlEnd);
48
63
  const fields = jsValue(root);
49
- if (fields === null || typeof fields !== 'object' || Array.isArray(fields)) {
50
- return { ok: false, refusal: refuse(file, 'frontmatter-fence') };
51
- }
52
64
  return { ok: true, root, fields: fields, yamlEnd: fence.yamlEnd };
53
65
  }
54
66
  catch (error) {
@@ -58,27 +70,30 @@ function opened(content, file) {
58
70
  }
59
71
  }
60
72
  export function parseFrontmatter(content, file = '') {
61
- const read = opened(content, file);
62
- if (!read.ok)
63
- return read;
73
+ const opening = opened(content, file);
74
+ if (!opening.ok)
75
+ return opening;
64
76
  return {
65
77
  ok: true,
66
78
  frontmatter: Object.freeze({
67
79
  content,
68
- type: declaredType(read.fields),
69
- fields: Object.freeze(read.fields),
80
+ type: declaredType(opening.fields),
81
+ fields: Object.freeze(opening.fields),
70
82
  }),
71
83
  };
72
84
  }
73
85
  export function parse(content, file = '') {
74
- const read = opened(content, file);
75
- if (!read.ok)
76
- return read;
77
- const bodyStart = read.root === null ? 0 : bodyStartAfterYaml(content, read.yamlEnd);
78
- const spans = headingSpans(content, bodyStart);
86
+ const opening = opened(content, file);
87
+ if (!opening.ok)
88
+ return opening;
89
+ const bodyStart = opening.root === null ? 0 : bodyStartAfterYaml(content, opening.yamlEnd);
79
90
  return {
80
91
  ok: true,
81
- document: freezeDocument(content, declaredType(read.fields), read.fields, content.slice(bodyStart, spans[0]?.headingStart), sectionsRecord(spans, content), { root: read.root, yamlEnd: read.yamlEnd, bodyStart }),
92
+ document: freezeDocument(content, declaredType(opening.fields), opening.fields, {
93
+ root: opening.root,
94
+ yamlEnd: opening.yamlEnd,
95
+ bodyStart,
96
+ }),
82
97
  };
83
98
  }
84
99
  function fitsBare(to) {
@@ -168,7 +183,7 @@ export function relativize(document, file, handle, definition, kept = new Set())
168
183
  prior: value,
169
184
  });
170
185
  }
171
- for (const href of new Set(destinations(inventoryOf(document)).map(({ href }) => href))) {
186
+ for (const href of new Set(linkDestinations(document).map(({ href }) => href))) {
172
187
  const path = relativized(href);
173
188
  if (path !== null)
174
189
  changes.push({ kind: 'link', href, to: relative(file, path) });
@@ -201,46 +216,61 @@ export function relinkBody(body, file, moves) {
201
216
  }
202
217
  return { outcome: 'applied', body: rewritten + body.slice(cursor) };
203
218
  }
204
- function occurrencesIn(occurrences, file, offset) {
205
- const found = [];
206
- for (const occurrence of occurrences) {
207
- const resolved = target(file, occurrence.href);
208
- if (resolved !== null)
209
- found.push({ href: occurrence.href, target: resolved, start: offset + occurrence.start });
219
+ export function unlinkBody(body, hrefs) {
220
+ const { uses, definitions } = read(body);
221
+ const links = new Map();
222
+ for (const use of uses) {
223
+ const { href, bracketed } = use.destination;
224
+ if (!hrefs.has(href) || links.has(href))
225
+ continue;
226
+ const label = body.slice(use.labelStart, use.labelEnd);
227
+ const image = body[use.start] === '!' ? '!' : '';
228
+ links.set(href, `${image}[${label}](${destinationText(href, bracketed) ?? href})`);
210
229
  }
211
- return found;
230
+ const cut = [...uses, ...definitions]
231
+ .filter((span) => hrefs.has(span.destination.href))
232
+ .sort((left, right) => left.start - right.start);
233
+ let kept = '';
234
+ let cursor = 0;
235
+ for (const span of cut) {
236
+ if (span.start < cursor)
237
+ continue;
238
+ kept += body.slice(cursor, span.start);
239
+ cursor = span.end;
240
+ }
241
+ return { body: kept + body.slice(cursor), links };
212
242
  }
213
243
  function linksIn(occurrences, file) {
214
244
  const found = [];
215
245
  const seen = new Set();
216
- for (const occurrence of occurrencesIn(occurrences, file, 0)) {
246
+ for (const occurrence of occurrences) {
217
247
  if (seen.has(occurrence.href))
218
248
  continue;
249
+ const resolved = target(file, occurrence.href);
250
+ if (resolved === null)
251
+ continue;
219
252
  seen.add(occurrence.href);
220
- found.push({ href: occurrence.href, target: occurrence.target });
253
+ found.push({ href: occurrence.href, target: resolved });
221
254
  }
222
255
  return found;
223
256
  }
224
257
  export function links(document, file) {
225
- return linksIn(destinations(inventoryOf(document)), file);
226
- }
227
- export function linkOccurrences(document, file) {
228
- return occurrencesIn(destinations(inventoryOf(document)), file, bodyStartOf(document.content));
258
+ return linksIn(linkDestinations(document), file);
229
259
  }
230
260
  export function bodyLinks(body, file) {
231
261
  return linksIn(hrefOccurrences(body), file);
232
262
  }
233
263
  function internalOf(document) {
234
- const held = internals.get(document);
264
+ const held = heldOf(document);
235
265
  if (held !== undefined)
236
- return held;
237
- const read = opened(document.content, '');
238
- if (!read.ok)
239
- return read.refusal;
266
+ return held.internal;
267
+ const opening = opened(document.content, '');
268
+ if (!opening.ok)
269
+ return opening.refusal;
240
270
  return {
241
- root: read.root,
242
- yamlEnd: read.yamlEnd,
243
- bodyStart: read.root === null ? 0 : bodyStartAfterYaml(document.content, read.yamlEnd),
271
+ root: opening.root,
272
+ yamlEnd: opening.yamlEnd,
273
+ bodyStart: opening.root === null ? 0 : bodyStartAfterYaml(document.content, opening.yamlEnd),
244
274
  };
245
275
  }
246
276
  function partOf(change) {
@@ -300,7 +330,7 @@ function planner(document, internal) {
300
330
  const section = (name, value, prior, at) => {
301
331
  if (spans === undefined) {
302
332
  spans = new Map();
303
- for (const span of headingSpans(content, internal.bodyStart))
333
+ for (const span of sectionSpans(readingOf(document), content.length))
304
334
  if (!spans.has(span.name))
305
335
  spans.set(span.name, span);
306
336
  }
@@ -314,7 +344,7 @@ function planner(document, internal) {
314
344
  const link = (href, to, at) => {
315
345
  if (occurrences === undefined) {
316
346
  occurrences = new Map();
317
- for (const occurrence of destinations(inventoryOf(document))) {
347
+ for (const occurrence of linkDestinations(document)) {
318
348
  const same = occurrences.get(occurrence.href);
319
349
  if (same === undefined)
320
350
  occurrences.set(occurrence.href, [occurrence]);
@@ -329,8 +359,8 @@ function planner(document, internal) {
329
359
  if (destinationText(written, false) === null)
330
360
  return refuse('', 'unwritable-link', written);
331
361
  return found.map((occurrence) => ({
332
- start: internal.bodyStart + occurrence.start,
333
- end: internal.bodyStart + occurrence.end,
362
+ start: occurrence.start,
363
+ end: occurrence.end,
334
364
  text: destinationText(written, occurrence.bracketed),
335
365
  at,
336
366
  }));
@@ -370,19 +400,19 @@ function overlapping(edits, stale) {
370
400
  }
371
401
  }
372
402
  }
373
- function firstHeadings(content, bodyStart) {
403
+ function firstHeadings(reading) {
374
404
  const first = new Map();
375
- for (const span of headingSpans(content, bodyStart)) {
405
+ for (const span of sectionSpans(reading, 0)) {
376
406
  if (!first.has(span.name))
377
407
  first.set(span.name, span.headingStart);
378
408
  }
379
409
  return first;
380
410
  }
381
- function hidden(before, bodyStart, after, shifts) {
382
- const placed = firstHeadings(after, bodyStartOf(after));
411
+ function hidden(before, after, shifts) {
412
+ const placed = firstHeadings(after);
383
413
  let shift = 0;
384
414
  let index = 0;
385
- for (const [name, at] of firstHeadings(before, bodyStart)) {
415
+ for (const [name, at] of firstHeadings(before)) {
386
416
  while (index < shifts.length && shifts[index][0] <= at) {
387
417
  shift += shifts[index][1];
388
418
  index += 1;
@@ -418,6 +448,13 @@ function spliced(source, edits) {
418
448
  pieces.push(source.slice(cursor));
419
449
  return { content: pieces.join(''), shifts };
420
450
  }
451
+ function checkedReading(source, replaced) {
452
+ const checked = spliced(source, replaced);
453
+ return {
454
+ reading: bodyReading(checked.content, bodyStartOf(checked.content)),
455
+ shifts: checked.shifts,
456
+ };
457
+ }
421
458
  export function apply(document, changes) {
422
459
  const internal = internalOf(document);
423
460
  if (!('bodyStart' in internal))
@@ -448,31 +485,29 @@ export function apply(document, changes) {
448
485
  if (stale.size > 0)
449
486
  return { outcome: 'stale', document, stale: [...stale].sort((left, right) => left - right) };
450
487
  const source = document.content;
451
- const { content } = spliced(source, edits);
488
+ const { content, shifts } = spliced(source, edits);
452
489
  if (content === source)
453
490
  return { outcome: 'applied', document };
491
+ const parsed = parse(content);
492
+ if (!parsed.ok)
493
+ return { outcome: 'refuse', refusal: parsed.refusal };
454
494
  const replaced = edits.filter((edit) => {
455
495
  const kind = changes[edit.at].kind;
456
496
  return kind === 'section' || kind === 'preamble';
457
497
  });
458
498
  if (replaced.length > 0) {
459
- const checked = spliced(source, replaced);
460
- const name = hidden(source, internal.bodyStart, checked.content, checked.shifts);
499
+ const checked = replaced.length === edits.length
500
+ ? { reading: readingOf(parsed.document), shifts }
501
+ : checkedReading(source, replaced);
502
+ const name = hidden(readingOf(document), checked.reading, checked.shifts);
461
503
  if (name !== undefined)
462
504
  return { outcome: 'refuse', refusal: refuse('', 'overlapping-section', name) };
463
505
  }
464
- const parsed = parse(content);
465
- if (!parsed.ok)
466
- return { outcome: 'refuse', refusal: parsed.refusal };
467
506
  return { outcome: 'applied', document: parsed.document };
468
507
  }
469
508
  export function serialize(document) {
470
509
  return document.content;
471
510
  }
472
- export function fieldStart(document, pointer) {
473
- const root = internals.get(document)?.root;
474
- return root === null || root === undefined ? undefined : nodeAt(root, pointer)?.start;
475
- }
476
511
  export function frontmatter(document) {
477
- return internals.get(document)?.root ?? null;
512
+ return heldOf(document)?.internal.root ?? null;
478
513
  }