rapier-markdown-kit 1.2.42 → 1.2.43

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.
@@ -110,11 +110,15 @@ function keyedRow(row, depth) {
110
110
  }
111
111
  return json;
112
112
  }
113
+ const plainRowArrays = new WeakSet();
113
114
  export function* canonicalRowsParts(rows, depth = 0) {
114
- const {array, keys} = fields(rows, depth, new Set());
115
- if (!array) { yield* canonicalParts(rows, depth); return; }
115
+ if (!(depth <= 64 && plainRowArrays.has(rows))) {
116
+ const {array} = fields(rows, depth, new Set());
117
+ if (!array) { yield* canonicalParts(rows, depth); return; }
118
+ if (Object.isFrozen(rows) && depth <= 64) plainRowArrays.add(rows);
119
+ }
116
120
  yield '[';
117
- for (let i = 0; i < keys.length; i++) { if (i) yield ','; yield canonicalRow(rows[keys[i]], depth + 1); }
121
+ for (let i = 0; i < rows.length; i++) { if (i) yield ','; yield canonicalRow(rows[i], depth + 1); }
118
122
  yield ']';
119
123
  }
120
124
  export function exactKeys(value, keys) {
@@ -10,10 +10,10 @@ import {minimalHistorySplice} from './inverse-source.mjs';
10
10
  import {evaluateWill} from '../../agent/will.mjs';
11
11
  export {textRoot, rootAfter};
12
12
  const rootShape = value => typeof value === 'string' && /^\d+:[a-z0-9]+:[a-z0-9]+$/.test(value);
13
- function* checkedRecords(ledger, prepared) {
13
+ function* checkedRecords(ledger, prepared, from = null) {
14
14
  if (!prepared.ok || ledger.records.length !== prepared.records.length) throw fault('record chain differs');
15
- let root = ledger.start.root, revision = ledger.start.revision;
16
- for (let index = 0; index < prepared.records.length; index++) {
15
+ let root = from ? from.root : ledger.start.root, revision = from ? from.revision : ledger.start.revision;
16
+ for (let index = from ? from.index : 0; index < prepared.records.length; index++) {
17
17
  const record = ledger.records[index];
18
18
  if (!Array.isArray(record.splices) || !prepared.validRecord(index,
19
19
  ledger.documentAuthority, 64 * 1024 * 1024, utf8Length, !ledger.complete) ||
@@ -170,6 +170,7 @@ const expandedRows = new WeakMap();
170
170
  const sameSplices = (a, b) => a === b || a.length === b.length &&
171
171
  a.every((row, i) => row.pos === b[i].pos && row.removed === b[i].removed && row.inserted === b[i].inserted);
172
172
  const sameEffect = (a, b) => a === b || !!a && !!b && canonicalJSON(a) === canonicalJSON(b);
173
+ let recentLedgers = [];
173
174
  function* produceLedger({text, metadata, records, documentAuthority, revision, root, complete = false, earlier = records} = {}, native = false) {
174
175
  if (!_rapierValidMetadata(metadata)) throw fault('document metadata required');
175
176
  metadata = {...metadata};
@@ -191,16 +192,30 @@ function* produceLedger({text, metadata, records, documentAuthority, revision, r
191
192
  yield;
192
193
  }
193
194
  const headBytes = bytes;
195
+ let base = recentLedgers.find(row => row.rows.length <= expanded.length && row.rows.every((value, at) => value === expanded[at]));
194
196
  let startSource = new HistorySource(text), startMetadata = {...metadata};
195
- for (let i = expanded.length - 1; i >= 0; i--) {
197
+ for (let i = expanded.length - 1; i >= (base ? base.rows.length : 0); i--) {
196
198
  startSource = startSource.apply(expanded[i].splices, true);
197
- startMetadata = _rapierTransformMetadata(startMetadata, expanded[i].metadata, true);
199
+ if (expanded[i].metadata) startMetadata = _rapierTransformMetadata(startMetadata, expanded[i].metadata, true);
198
200
  if (startSource === null || !startMetadata) throw fault('history does not reverse from this document');
199
201
  for (const row of expanded[i].splices) bytes += utf8Length(row.removed) - utf8Length(row.inserted);
200
202
  if (bytes > 64 * 1024 * 1024) throw fault('document exceeds the editor text limit');
201
203
  yield;
202
204
  }
203
- const startText = startSource.slice();
205
+ if (base && (bytes !== base.headBytes || startSource.length !== base.headText.length || !startSource.matches(0, base.headText) ||
206
+ canonicalJSON(startMetadata) !== base.headMetadata)) {
207
+ base = null; bytes = headBytes; startSource = new HistorySource(text); startMetadata = {...metadata};
208
+ for (let i = expanded.length - 1; i >= 0; i--) {
209
+ startSource = startSource.apply(expanded[i].splices, true);
210
+ if (expanded[i].metadata) startMetadata = _rapierTransformMetadata(startMetadata, expanded[i].metadata, true);
211
+ if (startSource === null || !startMetadata) throw fault('history does not reverse from this document');
212
+ for (const row of expanded[i].splices) bytes += utf8Length(row.removed) - utf8Length(row.inserted);
213
+ if (bytes > 64 * 1024 * 1024) throw fault('document exceeds the editor text limit');
214
+ yield;
215
+ }
216
+ }
217
+ if (base) { startMetadata = {...base.startMetadata}; bytes = base.startBytes; }
218
+ const startText = base ? base.startText : startSource.slice();
204
219
  const unchangedText = expanded.every(row => !row.splices.length);
205
220
  const contentRoot = headFacts.contentRoot;
206
221
  revision ??= expanded.at(-1)?.transaction.revision ?? 0;
@@ -209,19 +224,24 @@ function* produceLedger({text, metadata, records, documentAuthority, revision, r
209
224
  const startRevision = expanded[0]?.transaction.baseRevision ?? revision, startRoot = expanded[0]?.beforeHash ?? root;
210
225
  if (typeof documentAuthority !== 'string' || !documentAuthority || documentAuthority.length > 256) throw fault('unsupported or invalid envelope');
211
226
  if (!nonnegative(startRevision) || !rootShape(startRoot)) throw fault('invalid start');
212
- const startFacts = unchangedText ? headFacts : yield* sourceFacts(startText, native);
227
+ const startFacts = unchangedText ? headFacts : base ? base.startFacts : yield* sourceFacts(startText, native);
213
228
  if (startRevision === 0 && startRoot !== startFacts.contentRoot) throw fault('invalid start');
214
229
  const headSHA = headFacts.sha256, startSHA = startFacts.sha256;
215
230
  const payload = {format: 'rapier-ledger/2', documentAuthority,
216
231
  start: {text: startText, revision: startRevision, root: startRoot, sha256: startSHA, metadata: startMetadata},
217
232
  records: expanded, head: {revision, root, sha256: headSHA, metadata: {...metadata}}, complete: complete === true && startRevision === 0 && expanded.every((row, i) => !i || row.transaction.baseRevision === expanded[i - 1].transaction.revision)};
218
- for (const _record of checkedRecords(payload, prepared)) yield;
233
+ const from = base && base.documentAuthority === documentAuthority && base.complete === payload.complete &&
234
+ base.startRoot === startRoot && base.startRevision === startRevision ? {index: base.rows.length, root: base.chainRoot, revision: base.chainRevision} : null;
235
+ for (const _record of checkedRecords(payload, prepared, from)) yield;
219
236
  if (expanded.some(row => Object.hasOwn(row, 'authored'))) {
220
237
  try { authoredHistory(startText, expanded); } catch (_) { throw fault('authored origin differs'); }
221
238
  }
222
239
  const replayedMetadata = prepared.replayMetadata(startMetadata);
223
240
  if (!replayedMetadata || canonicalJSON(replayedMetadata) !== canonicalJSON(metadata)) throw fault('metadata does not describe this document');
224
241
  const ledger = {...payload, sha256: yield* checksum(envelopeParts(payload), native)};
242
+ recentLedgers = [{rows: expanded, headText: text, headMetadata: canonicalJSON(metadata), headBytes, startText, startMetadata: {...startMetadata},
243
+ startFacts, startBytes: bytes, documentAuthority, complete: payload.complete, startRoot, startRevision, chainRoot: payload.head.root,
244
+ chainRevision: payload.head.revision}, ...recentLedgers.filter(row => row.rows[0] !== expanded[0] && row.documentAuthority === documentAuthority)].slice(0, 4);
225
245
  ownLedger(ledger);
226
246
  proofs.set(ledger, {shell: Array.from(envelopeParts({...ledger, start: {...ledger.start, text: ''}})).join(''), startText,
227
247
  text, metadata: {...metadata}, root, revision, prepared: _rapierPrepareHistoryRecords(ledger.records),
@@ -273,7 +293,7 @@ function historyNavigation(ledger, text, metadata, prepared, source) {
273
293
  let traversed = source, traversedMetadata = {...metadata};
274
294
  for (let i = cursor - 1; i >= 0; i--) {
275
295
  traversed = step(traversed, branch[i], false);
276
- traversedMetadata = _rapierTransformMetadata(traversedMetadata, byId.get(branch[i]).metadata, true);
296
+ if (byId.get(branch[i]).metadata) traversedMetadata = _rapierTransformMetadata(traversedMetadata, byId.get(branch[i]).metadata, true);
277
297
  if (traversed === null || !traversedMetadata) throw fault('undo branch does not reverse');
278
298
  }
279
299
  if (ledger.complete) {
@@ -284,7 +304,7 @@ function historyNavigation(ledger, text, metadata, prepared, source) {
284
304
  traversed = source; traversedMetadata = {...metadata};
285
305
  for (let i = cursor; i < branch.length; i++) {
286
306
  traversed = step(traversed, branch[i], true);
287
- traversedMetadata = _rapierTransformMetadata(traversedMetadata, byId.get(branch[i]).metadata);
307
+ if (byId.get(branch[i]).metadata) traversedMetadata = _rapierTransformMetadata(traversedMetadata, byId.get(branch[i]).metadata);
288
308
  if (traversed === null || !traversedMetadata) throw fault('redo branch does not replay');
289
309
  }
290
310
  if (ledger.complete && pictures.size) {
@@ -110,7 +110,8 @@ function _rapierRecordIndex(records, shared = false) {
110
110
  }
111
111
  return value;
112
112
  };
113
- return {byId, splices: record => resolve(record, false), metadata: record => resolve(record, true)};
113
+ const extend = more => { for (const record of more) { const id = record?.transaction?.id; if (!byId.has(id)) byId.set(id, []); byId.get(id).push(record); } };
114
+ return {byId, extend, splices: record => resolve(record, false), metadata: record => resolve(record, true)};
114
115
  }
115
116
 
116
117
  const _rapierLedgerIndexes = new WeakMap();
@@ -233,87 +234,89 @@ function _rapierPictureFinish(record, original, earlier, lookup) {
233
234
  });
234
235
  }
235
236
 
236
- function _rapierWalkHistoryEffects(records, lookup, visit = null, observe = null) {
237
- try {
238
- if (!Array.isArray(records)) return {ok: false};
239
- const nodes = new Map(), references = new Map(), pictures = new Map(), byId = new Map(), finished = new Set(), earlier = [];
240
- const update = (target, delta) => {
241
- const pending = [[target, delta]];
242
- while (pending.length) {
243
- const [id, change] = pending.pop(), node = nodes.get(id), was = node.active;
244
- node.blockers += change;
245
- if (node.blockers < 0) throw Error('effect');
246
- node.active = node.blockers === 0;
247
- if (was !== node.active) for (const ref of node.references) pending.push([ref, node.active ? 1 : -1]);
248
- }
249
- };
250
- const activity = new Map();
251
- const active = id => {
252
- if (visit) return nodes.get(id).active;
253
- const pending = [[id, 0]];
254
- while (pending.length) {
255
- const frame = pending.at(-1), target = frame[0];
256
- if (activity.has(target)) { pending.pop(); continue; }
257
- const dependents = nodes.get(target).dependents;
258
- if (frame[1] === dependents.length) { activity.set(target, true); pending.pop(); continue; }
259
- const next = dependents[frame[1]];
260
- if (!activity.has(next)) pending.push([next, 0]);
261
- else if (activity.get(next)) { activity.set(target, false); pending.pop(); }
262
- else frame[1]++;
263
- }
264
- return activity.get(id);
265
- };
266
- const lastUndo = new Map(), contexts = new Map(), order = [];
267
- const contextOf = origin => {
268
- if (!origin) return null;
269
- if (!_rapierValidAuthored(origin)) throw Error('origin');
270
- const known = new Set(), pending = origin.basis.slice();
271
- while (pending.length) {
272
- const id = pending.pop(), context = contexts.get(id);
273
- if (!context) throw Error('origin');
274
- if (known.has(id)) continue;
275
- known.add(id);
276
- if (context.basis) pending.push(...context.basis);
277
- else for (let index = 0; index < context.index; index++) known.add(order[index]);
278
- }
279
- const inactive = new Set();
280
- for (let index = order.length - 1; index >= 0; index--) {
281
- const id = order[index];
282
- if (!known.has(id) || inactive.has(id)) continue;
283
- for (const ref of references.get(id)) {
284
- if (!known.has(ref)) throw Error('origin');
285
- inactive.add(ref);
286
- }
237
+ function _rapierHistoryWalker(records, lookup, visit = null, observe = null) {
238
+ let nodes = new Map(), references = new Map(), pictures = new Map();
239
+ const byId = new Map(), finished = new Set(), earlier = [];
240
+ const update = (target, delta) => {
241
+ const pending = [[target, delta]];
242
+ while (pending.length) {
243
+ const [id, change] = pending.pop(), node = nodes.get(id), was = node.active;
244
+ node.blockers += change;
245
+ if (node.blockers < 0) throw Error('effect');
246
+ node.active = node.blockers === 0;
247
+ if (was !== node.active) for (const ref of node.references) pending.push([ref, node.active ? 1 : -1]);
248
+ }
249
+ };
250
+ const activity = new Map();
251
+ const active = id => {
252
+ if (visit) return nodes.get(id).active;
253
+ const pending = [[id, 0]];
254
+ while (pending.length) {
255
+ const frame = pending.at(-1), target = frame[0];
256
+ if (activity.has(target)) { pending.pop(); continue; }
257
+ const dependents = nodes.get(target).dependents;
258
+ if (frame[1] === dependents.length) { activity.set(target, true); pending.pop(); continue; }
259
+ const next = dependents[frame[1]];
260
+ if (!activity.has(next)) pending.push([next, 0]);
261
+ else if (activity.get(next)) { activity.set(target, false); pending.pop(); }
262
+ else frame[1]++;
263
+ }
264
+ return activity.get(id);
265
+ };
266
+ const lastUndo = new Map(), contexts = new Map(), order = [];
267
+ const contextOf = origin => {
268
+ if (!origin) return null;
269
+ if (!_rapierValidAuthored(origin)) throw Error('origin');
270
+ const known = new Set(), pending = origin.basis.slice();
271
+ while (pending.length) {
272
+ const id = pending.pop(), context = contexts.get(id);
273
+ if (!context) throw Error('origin');
274
+ if (known.has(id)) continue;
275
+ known.add(id);
276
+ if (context.basis) pending.push(...context.basis);
277
+ else for (let index = 0; index < context.index; index++) known.add(order[index]);
278
+ }
279
+ const inactive = new Set();
280
+ for (let index = order.length - 1; index >= 0; index--) {
281
+ const id = order[index];
282
+ if (!known.has(id) || inactive.has(id)) continue;
283
+ for (const ref of references.get(id)) {
284
+ if (!known.has(ref)) throw Error('origin');
285
+ inactive.add(ref);
287
286
  }
288
- return {known, inactive};
289
- };
290
- for (const record of records) {
287
+ }
288
+ return {known, inactive};
289
+ };
290
+ const walker = {observe, failed: false};
291
+ walker.add = record => {
292
+ if (walker.failed) return false;
293
+ try {
291
294
  const tx = record?.transaction;
292
- if (!tx || typeof tx.id !== 'string' || !tx.id || nodes.has(tx.id) || (tx.reverts && tx.reapplies)) return {ok: false};
295
+ if (!tx || typeof tx.id !== 'string' || !tx.id || nodes.has(tx.id) || (tx.reverts && tx.reapplies)) { walker.failed = true; return false; }
293
296
  const supplied = tx.sourceTransactionIds || (tx.sourceTransactionId ? [tx.sourceTransactionId] : []);
294
297
  if (!Array.isArray(supplied) || new Set(supplied).size !== supplied.length ||
295
- (tx.sourceTransactionIds && tx.sourceTransactionId && (supplied.length !== 1 || supplied[0] !== tx.sourceTransactionId))) return {ok: false};
298
+ (tx.sourceTransactionIds && tx.sourceTransactionId && (supplied.length !== 1 || supplied[0] !== tx.sourceTransactionId))) { walker.failed = true; return false; }
296
299
  let refs = supplied;
297
300
  if (tx.operation === 'document.finish-picture' && tx.sourceTransactionId) {
298
301
  const owner = tx.sourceTransactionId;
299
302
  if (!nodes.has(owner) || !active(owner) || finished.has(owner) ||
300
- !_rapierPictureFinish(record, byId.get(owner), earlier, lookup ||= _rapierRecordIndex(records))) return {ok: false};
303
+ !_rapierPictureFinish(record, byId.get(owner), earlier, lookup ||= _rapierRecordIndex(records))) { walker.failed = true; return false; }
301
304
  pictures.set(tx.id, owner); finished.add(owner); refs = [];
302
305
  }
303
306
  if (tx.reverts || tx.reapplies) {
304
307
  const target = tx.reverts || tx.reapplies;
305
- if (!nodes.has(target) || (supplied.length && (supplied.length !== 1 || supplied[0] !== target))) return {ok: false};
308
+ if (!nodes.has(target) || (supplied.length && (supplied.length !== 1 || supplied[0] !== target))) { walker.failed = true; return false; }
306
309
  if (tx.reverts) refs = [target];
307
310
  else {
308
311
  const context = contextOf(record.authored || tx.authored);
309
312
  const undo = (lastUndo.get(target) || []).findLast(id => context
310
313
  ? context.known.has(id) && !context.inactive.has(id) : active(id));
311
- if (!undo) return {ok: false};
314
+ if (!undo) { walker.failed = true; return false; }
312
315
  refs = [undo];
313
316
  }
314
317
  }
315
- if (refs.some(id => typeof id !== 'string' || !nodes.has(id) || pictures.has(id))) return {ok: false};
316
- if (tx.actor?.kind === 'agent' && refs.some(id => byId.get(id).transaction.actor?.kind !== 'agent')) return {ok: false};
318
+ if (refs.some(id => typeof id !== 'string' || !nodes.has(id) || pictures.has(id))) { walker.failed = true; return false; }
319
+ if (tx.actor?.kind === 'agent' && refs.some(id => byId.get(id).transaction.actor?.kind !== 'agent')) { walker.failed = true; return false; }
317
320
  nodes.set(tx.id, {active: true, blockers: 0, references: refs, dependents: []}); references.set(tx.id, refs.slice());
318
321
  byId.set(tx.id, record); earlier.push(record);
319
322
  for (const ref of refs) {
@@ -328,23 +331,45 @@ function _rapierWalkHistoryEffects(records, lookup, visit = null, observe = null
328
331
  lastUndo.get(tx.reverts).push(tx.id);
329
332
  }
330
333
  if (visit) visit(record, nodes, refs);
331
- if (observe) observe(record, refs, active);
332
- }
333
- if (!visit) for (let i = order.length - 1; i >= 0; i--) {
334
- const node = nodes.get(order[i]); node.active = node.blockers === 0;
335
- if (node.active) for (const ref of node.references) nodes.get(ref).blockers++;
334
+ if (walker.observe) walker.observe(record, refs, active);
335
+ return true;
336
+ } catch (_) { walker.failed = true; return false; }
337
+ };
338
+ walker.finish = () => {
339
+ if (walker.failed) return {ok: false};
340
+ const blockers = new Map(), effectiveActIds = [];
341
+ for (let i = order.length - 1; i >= 0; i--) {
342
+ const id = order[i], node = nodes.get(id), on = visit ? node.active : !(blockers.get(id) > 0);
343
+ if (!visit && on) for (const ref of node.references) blockers.set(ref, (blockers.get(ref) || 0) + 1);
344
+ if (on && !pictures.has(id)) effectiveActIds.push(id);
336
345
  }
337
- const effectiveActIds = [...nodes].filter(([id, node]) => node.active && !pictures.has(id)).map(([id]) => id);
338
- return {ok: true, effectiveActIds, active: new Set(effectiveActIds), references, pictures};
339
- } catch (_) { return {ok: false}; }
346
+ effectiveActIds.reverse();
347
+ const result = {ok: true, effectiveActIds, active: new Set(effectiveActIds), references, pictures};
348
+ walker.shared = true;
349
+ return result;
350
+ };
351
+ const add = walker.add;
352
+ walker.add = record => {
353
+ if (walker.shared) { references = new Map(references); pictures = new Map(pictures); walker.shared = false; }
354
+ return add(record);
355
+ };
356
+ return walker;
357
+ }
358
+
359
+ function _rapierWalkHistoryEffects(records, lookup, visit = null, observe = null) {
360
+ if (!Array.isArray(records)) return {ok: false};
361
+ const walker = _rapierHistoryWalker(records, lookup, visit, observe);
362
+ for (const record of records) if (!walker.add(record)) return {ok: false};
363
+ return walker.finish();
340
364
  }
341
365
 
342
366
  function _rapierHistoryEffects(records, visit = null) {
343
367
  return _rapierWalkHistoryEffects(records, null, visit);
344
368
  }
345
369
 
346
- function _rapierMetadataProof(lookup) {
347
- const values = {}, required = {}, assignments = {filename: [], docKind: []};
370
+ function _rapierMetadataProof(lookup, from = null) {
371
+ const values = {...from?.values}, required = {...from?.required},
372
+ assignments = {filename: [...(from?.assignments.filename || [])], docKind: [...(from?.assignments.docKind || [])]};
348
373
  const requireInitial = (key, value) => {
349
374
  if (Object.hasOwn(required, key) && required[key] !== value) throw Error('metadata_effect');
350
375
  required[key] = value;
@@ -371,7 +396,7 @@ function _rapierMetadataProof(lookup) {
371
396
  if (!_rapierValidMetadata(initial) || Object.keys(required).some(key => initial[key] !== required[key])) return null;
372
397
  return {...initial, ...values};
373
398
  };
374
- return {observe, replay};
399
+ return {observe, replay, fork: other => _rapierMetadataProof(other || lookup, {values, required, assignments})};
375
400
  }
376
401
 
377
402
  function _rapierMetadataState(initial, records, effects = _rapierHistoryEffects(records)) {
@@ -478,16 +503,79 @@ const _rapierPrepareHistoryRecords = (() => {
478
503
  frame.descriptors = descriptors; frame.fields = fields;
479
504
  frame.leaving = true; active.add(value); pending.push(frame);
480
505
  for (let at = fields.length - 1; at >= 0; at--) {
481
- const key = fields[at]; pending.push({value: descriptors[key].value, parent: frame, key, depth: frame.depth + 1});
506
+ const key = fields[at], child = descriptors[key].value;
507
+ const prior = array && child && typeof child === 'object' ? copies.get(child) : undefined;
508
+ if (prior?.immutable && !active.has(child) && frame.depth + 1 + prior.height <= 64) {
509
+ finish({parent: frame, key}, prior.copy, true, prior.height); continue;
510
+ }
511
+ pending.push({value: child, parent: frame, key, depth: frame.depth + 1});
482
512
  }
483
513
  }
484
514
  return result.value;
485
515
  };
516
+ let resumable = [];
517
+ const rowOf = (lookup, record) => {
518
+ const splices = lookup.splices(record), metadata = lookup.metadata(record);
519
+ if (splices && !Object.isFrozen(splices)) {
520
+ for (const row of splices) Object.freeze(row);
521
+ Object.freeze(splices);
522
+ }
523
+ if (metadata && !Object.isFrozen(metadata)) {
524
+ for (const pair of Object.values(metadata)) Object.freeze(pair);
525
+ Object.freeze(metadata);
526
+ }
527
+ return Object.freeze({record, splices, metadata});
528
+ };
529
+ const observe = (records, basis, byId, rows, effects, proof) => {
530
+ for (const refs of effects.references.values()) Object.freeze(refs);
531
+ const effectView = Object.freeze({ok: true, effectiveActIds: Object.freeze(effects.effectiveActIds),
532
+ active: view(effects.active), references: view(effects.references), pictures: view(effects.pictures)});
533
+ const observation = Object.freeze({ok: effects.ok, records, rows: Object.freeze(rows), effects: effectView, byId: view(byId),
534
+ replayMetadata: initial => effects.ok ? proof.replay(initial) : null,
535
+ validRecord: (index, documentAuthority, maxDocumentBytes, utf8Length, allowGap = false) => {
536
+ if (!effects.ok || !Number.isSafeInteger(index) || index < 0 || index >= records.length) return false;
537
+ const row = rows[index], tx = row.record.transaction;
538
+ return _rapierCheckLedgerRecord(row.record, records[index - 1] || null, documentAuthority, maxDocumentBytes, utf8Length, allowGap,
539
+ {...row, duplicate: false, semantic: !!(tx.reverts || tx.reapplies || tx.sourceTransactionId || tx.sourceTransactionIds?.length)});
540
+ }});
541
+ prepared = new WeakMap([[records, {basis, observation}]]);
542
+ return observation;
543
+ };
544
+ const authorityOf = state => state.records[0]?.transaction?.documentAuthority;
545
+ const keep = state => { resumable = [state, ...resumable.filter(row => row !== state && row.records[0] !== state.records[0] &&
546
+ authorityOf(row) === authorityOf(state))].slice(0, 4); };
547
+ const extend = records => {
548
+ const base = resumable.find(row => row.records.length < records.length && row.records[0] === records[0] &&
549
+ row.records.every((record, at) => record === records[at]));
550
+ if (!base) return null;
551
+ resumable = resumable.filter(row => row !== base);
552
+ const more = records.slice(base.records.length), byId = new Map(base.byId);
553
+ for (const record of more) {
554
+ const id = record?.transaction?.id;
555
+ if (typeof id !== 'string' || !id || byId.has(id)) return null;
556
+ byId.set(id, record);
557
+ }
558
+ const {lookup, walker} = base;
559
+ lookup.extend(more);
560
+ const rows = base.rows.concat(more.map(record => rowOf(lookup, record)));
561
+ const proof = base.proof.fork(lookup);
562
+ walker.observe = proof.observe;
563
+ for (const record of more) if (!walker.add(record)) return null;
564
+ const effects = walker.finish();
565
+ if (!effects.ok) return null;
566
+ if (rows.every(row => row.splices && row.metadata !== undefined)) keep({records, lookup, walker, proof, byId, rows});
567
+ return observe(records, records, byId, rows, effects, proof);
568
+ };
486
569
  return (input, earlier = input) => {
487
570
  try {
488
571
  if (!Array.isArray(input) || !Array.isArray(earlier)) return {ok: false};
489
572
  const records = capture(input), basis = input === earlier ? records : capture(earlier), previous = prepared.get(records);
490
573
  if (previous?.basis === basis) return previous.observation;
574
+ if (basis === records) {
575
+ let grown = null;
576
+ try { grown = extend(records); } catch (_) { grown = null; }
577
+ if (grown) return grown;
578
+ }
491
579
  const byId = new Map();
492
580
  for (const record of records) {
493
581
  const id = record?.transaction?.id;
@@ -495,32 +583,14 @@ const _rapierPrepareHistoryRecords = (() => {
495
583
  byId.set(id, record);
496
584
  }
497
585
  const lookup = _rapierRecordIndex(basis), proof = _rapierMetadataProof(lookup);
498
- const rows = records.map(record => {
499
- const splices = lookup.splices(record), metadata = lookup.metadata(record);
500
- if (splices && !Object.isFrozen(splices)) {
501
- for (const row of splices) Object.freeze(row);
502
- Object.freeze(splices);
503
- }
504
- if (metadata && !Object.isFrozen(metadata)) {
505
- for (const pair of Object.values(metadata)) Object.freeze(pair);
506
- Object.freeze(metadata);
507
- }
508
- return Object.freeze({record, splices, metadata});
509
- });
510
- const effects = _rapierWalkHistoryEffects(records, lookup, null, proof.observe);
586
+ const rows = records.map(record => rowOf(lookup, record));
587
+ const walker = _rapierHistoryWalker(records, lookup, null, proof.observe);
588
+ for (const record of records) if (!walker.add(record)) return {ok: false};
589
+ const effects = walker.finish();
511
590
  if (!effects.ok) return {ok: false};
512
- for (const refs of effects.references.values()) Object.freeze(refs);
513
- const effectView = Object.freeze({ok: true, effectiveActIds: Object.freeze(effects.effectiveActIds),
514
- active: view(effects.active), references: view(effects.references), pictures: view(effects.pictures)});
515
- const observation = Object.freeze({ok: effects.ok, records, rows: Object.freeze(rows), effects: effectView, byId: view(byId),
516
- replayMetadata: initial => effects.ok ? proof.replay(initial) : null,
517
- validRecord: (index, documentAuthority, maxDocumentBytes, utf8Length, allowGap = false) => {
518
- if (!effects.ok || !Number.isSafeInteger(index) || index < 0 || index >= records.length) return false;
519
- const row = rows[index], tx = row.record.transaction;
520
- return _rapierCheckLedgerRecord(row.record, records[index - 1] || null, documentAuthority, maxDocumentBytes, utf8Length, allowGap,
521
- {...row, duplicate: false, semantic: !!(tx.reverts || tx.reapplies || tx.sourceTransactionId || tx.sourceTransactionIds?.length)});
522
- }});
523
- prepared = new WeakMap([[records, {basis, observation}]]); return observation;
591
+ if (basis === records && rows.every(row => row.splices && row.metadata !== undefined))
592
+ keep({records, lookup, walker, proof, byId, rows});
593
+ return observe(records, basis, byId, rows, effects, proof);
524
594
  } catch (_) { return {ok: false}; }
525
595
  };
526
596
  })();
@@ -55,18 +55,23 @@ function createMarkdownRenderer(runtime) {
55
55
  window?.addEventListener?.('rapier:original-file-ready', scheduleWikiEmbeds);
56
56
  const wikiMode = options => options.wikiEmbedding ? 'links' : options.wikiLinks !== undefined ? options.wikiLinks
57
57
  : globalThis.RapierOriginalFolderCore?.currentOriginal?.() ? 'label' : false;
58
+ let codeLeft = Infinity;
58
59
  function initMarkdownIt() {
59
60
  if (typeof window.markdownit !== 'function') throw new Error('markdownit');
60
61
  if (typeof _rapierMarkdownPreview === 'function') globalThis.rapierRenderPreview = _rapierMarkdownPreview;
61
62
 
62
63
  md = window.markdownit({
63
64
  ...RAPIER_MARKDOWN_SPEC.options,
64
- highlight: (code, lang) => lang && _rapierHighlightAdmitted(code) ? _rapierCodeHtml(code, lang) : '',
65
+ highlight: (code, lang) => lang && _rapierHighlightAdmitted(code) && (codeLeft -= code.length) >= 0 ? _rapierCodeHtml(code, lang) : '',
65
66
  });
66
67
 
67
68
  _rapierApplyMarkdownSpec(md, window);
68
69
  globalThis.RapierImageAssets.installMarkdownImages(md);
69
70
  _rapierInstallSemanticProbe(md);
71
+ md.core.ruler.after('block', 'rapier_part_decorations', state => {
72
+ if (state.env.rapierPartDecorations && !/[<$\\]/.test(state.src) && !state.src.includes('^['))
73
+ state.tokens = _rapierPartDecorationGroups(state.tokens).flat();
74
+ });
70
75
  _rapierInstallMarkdownMath(md, RAPIER_MARKDOWN_SPEC.rules.mathBlock);
71
76
 
72
77
  const markOpenDefault = md.renderer.rules.mark_open ||
@@ -138,7 +143,7 @@ function initMarkdownIt() {
138
143
  '" data-rapier-image-source="' + esc(encodeURIComponent(token.content)) + '">' + esc(label) + '</span>';
139
144
  }
140
145
  const note = embed && !env.rapierWikiEmbedding;
141
- if (note) scheduleWikiEmbeds();
146
+ if (note && !env.rapierPassive) scheduleWikiEmbeds();
142
147
  return '<span class="rapier-source-token rapier-source-token--wiki' + (note ? '-embed' : '') +
143
148
  '" data-rapier-source="' + esc(encodeURIComponent(token.content)) + '" data-rapier-visible="' + esc(encodeURIComponent(label)) +
144
149
  '"><a href="' + esc(href) + '">' + esc(label) + '</a></span>';
@@ -371,12 +376,12 @@ function initMarkdownIt() {
371
376
  const mathProvider = env.rapierProviders === false ? null : _rapierProviders.math;
372
377
  const mathNeeded = provider?.requiresMath?.(src) === true;
373
378
  const mathReady = !mathNeeded || mathProvider?.status === 'ready';
374
- if (!mathReady && !mathProvider?.request?.() && env.rapierProviders !== false && !_mathPromptedOnce) {
379
+ if (!mathReady && !env.rapierPassive && !mathProvider?.request?.() && env.rapierProviders !== false && !_mathPromptedOnce) {
375
380
  _mathPromptedOnce = true;
376
381
  try { _rapierUiMath.request(); } catch (_) {}
377
382
  }
378
383
  const ready = diagramReady && mathReady;
379
- if (!diagramReady && !provider?.request?.() && env.rapierProviders !== false && !_diagramPromptedOnce) {
384
+ if (!diagramReady && !env.rapierPassive && !provider?.request?.() && env.rapierProviders !== false && !_diagramPromptedOnce) {
380
385
  _diagramPromptedOnce = true;
381
386
  try { _rapierUiDiagram.request(); } catch (_) {}
382
387
  }
@@ -420,7 +425,7 @@ function initMarkdownIt() {
420
425
  if (env.rapierPage) return sourceHtml;
421
426
  const mathProvider = env.rapierProviders === false ? null : _rapierProviders.math;
422
427
  if (!mathProvider || mathProvider.status !== 'ready' || typeof mathProvider.renderToString !== 'function') {
423
- if (!mathProvider?.request?.() && env.rapierProviders !== false && !_mathPromptedOnce) {
428
+ if (!env.rapierPassive && !mathProvider?.request?.() && env.rapierProviders !== false && !_mathPromptedOnce) {
424
429
  _mathPromptedOnce = true;
425
430
  try { _rapierUiMath.request(); } catch (_) {}
426
431
  }
@@ -476,13 +481,15 @@ function _rapierRenderSemanticRoot(canonical, metadata, options = {}) {
476
481
  }
477
482
 
478
483
  const markdown = _rapierSplitOpeningFrontmatter(canonical).body;
479
- const env = {rapierImagePresentation: options.imagePresentation === true, ...(options.page ? {rapierPage: true} : {}), ...(options.providers === false ? {rapierProviders: false} : {})};
484
+ const env = {rapierImagePresentation: options.imagePresentation === true, rapierPassive: options.passive === true, ...(options.page ? {rapierPage: true} : {}), ...(options.providers === false ? {rapierProviders: false} : {})};
480
485
  if (options.wikiEmbedding) env.rapierWikiEmbedding = true;
481
486
  const wikiLinks = wikiMode(options);
482
487
  if (wikiLinks) env.rapierWikiLinks = wikiLinks;
483
488
  if (options.mathEquations) env.rapierMathEquations = options.mathEquations;
484
489
  const nesting = md && options.maxNesting > 0 ? options.maxNesting : 0;
485
490
  let cutAt = -1, rendered;
491
+ codeLeft = options.codeBudget >= 0 ? options.codeBudget : Infinity;
492
+ try {
486
493
  if (nesting || md && options.closeDetails) {
487
494
  const saved = md.options.maxNesting;
488
495
  if (nesting) md.options.maxNesting = nesting;
@@ -494,6 +501,7 @@ function _rapierRenderSemanticRoot(canonical, metadata, options = {}) {
494
501
  } else rendered = md
495
502
  ? md.render(markdown, env)
496
503
  : '<pre><code>' + escapeRapierHtmlText(markdown) + '</code></pre>';
504
+ } finally { codeLeft = Infinity; }
497
505
  if (md && env.footnotes && Array.isArray(env.footnotes.list) && env.footnotes.list.length) {
498
506
  const labels = env.footnotes.list.map((item, index) =>
499
507
  String(item && item.label || ('inline-' + (index + 1))));
@@ -503,14 +511,14 @@ function _rapierRenderSemanticRoot(canonical, metadata, options = {}) {
503
511
  if (cutAt >= 0) _rapierAppendNestingCut(root, markdown, cutAt);
504
512
  _rapierApplyBlockDirection(root);
505
513
 
506
- _rapierAssignHeadingSlugs(root, RAPIER_RENDERED_HEADING_SELECTOR, false);
514
+ _rapierAssignHeadingSlugs(root, RAPIER_RENDERED_HEADING_SELECTOR, false, options.carry?.slugs, options.carry?.headingIds);
507
515
  _rapierDisambiguateRenderedAnchors(root);
508
516
 
509
517
  root.querySelectorAll('pre > code').forEach(_rapierNormalizeCodeElement);
510
- _rapierMarkTableCaptions(root);
518
+ _rapierMarkTableCaptions(root, options.carry);
511
519
  _rapierMarkFigureCaptions(root);
512
520
  _rapierMarkListContinuations(_rapierChildElements(root));
513
- _rapierDecorateJumpLists(root);
521
+ _rapierDecorateJumpLists(root, options.carry);
514
522
  return root;
515
523
  }
516
524
 
@@ -543,12 +551,13 @@ async function _rapierRenderSemanticRootAsync(canonical, metadata, options = {})
543
551
  let {tokens, env} = parsed, labels = env.footnotes?.list?.map((item, index) => String(item?.label || ('inline-' + (index + 1))));
544
552
  const cutAt = nesting ? _rapierNestingCutAt(tokens, nesting) : -1;
545
553
  tokens = _rapierCloseOpenDetails(tokens);
546
- env = {...env, rapierImagePresentation: options.imagePresentation === true};
554
+ env = {...env, rapierImagePresentation: options.imagePresentation === true, rapierPassive: options.passive === true};
547
555
  await pause(work, .3);
548
556
  const inert = document.createElement('template').content.ownerDocument;
549
557
  const root = inert.createElement('div'), part = inert.createElement('div'), boundary = htmlBoundary();
550
558
  root.setAttribute('data-rapier-semantic-root', 'true');
551
559
  let html = '', began = performance.now(), complete = false;
560
+ codeLeft = options.codeBudget >= 0 ? options.codeBudget : Infinity;
552
561
  const append = () => {
553
562
  if (md.renderer.rapierTransformHtml) html = md.renderer.rapierTransformHtml(html);
554
563
  if (labels?.length) html = _relabelFootnoteHtml(html, labels);
@@ -571,22 +580,70 @@ async function _rapierRenderSemanticRootAsync(canonical, metadata, options = {})
571
580
  if (html) append();
572
581
  if (cutAt >= 0) _rapierAppendNestingCut(root, markdown, cutAt);
573
582
  parsed = tokens = env = labels = null;
574
- await finishAsync(_rapierSemanticDecorations(root), work);
583
+ await finishAsync(_rapierSemanticDecorations(root, options.carry), work);
575
584
  await pause(work, .6);
576
585
  complete = true;
577
586
  return root;
578
- } finally { if (!complete) { root.replaceChildren(); part.replaceChildren(); } }
587
+ } finally { codeLeft = Infinity; if (!complete) { root.replaceChildren(); part.replaceChildren(); } }
588
+ }
589
+
590
+ function _rapierPartDecorationGroups(tokens) {
591
+ const groups = [];
592
+ for (let at = 0; at < tokens.length; at++) {
593
+ const first = tokens[at];
594
+ if (first.type !== 'heading_open' && first.type !== 'table_open') continue;
595
+ const close = first.type === 'heading_open' ? 'heading_close' : 'table_close';
596
+ let end = at + 1;
597
+ while (end < tokens.length && !(tokens[end].type === close && tokens[end].level === first.level)) end++;
598
+ end++;
599
+ if (first.type === 'table_open' && tokens[end]?.type === 'paragraph_open' && tokens[end].level === first.level) {
600
+ while (end < tokens.length && !(tokens[end].type === 'paragraph_close' && tokens[end].level === first.level)) end++;
601
+ end++;
602
+ }
603
+ groups.push(tokens.slice(at, end));
604
+ at = end - 1;
605
+ }
606
+ return groups;
607
+ }
608
+
609
+ function _rapierReadPartDecorations(canonical, metadata, options = {}) {
610
+ const carry = options.carry || {slugs: Object.create(null), captions: 0, continued: true}, captionStart = carry.captions || 0;
611
+ const markdown = _rapierSplitOpeningFrontmatter(canonical).body, env = {rapierImagePresentation: options.imagePresentation === true, rapierPassive: true, rapierPartDecorations: true,
612
+ ...(options.page ? {rapierPage: true} : {}), ...(options.providers === false ? {rapierProviders: false} : {})};
613
+ if (options.wikiEmbedding) env.rapierWikiEmbedding = true;
614
+ const wikiLinks = wikiMode(options);
615
+ if (wikiLinks) env.rapierWikiLinks = wikiLinks;
616
+ if (options.mathEquations) env.rapierMathEquations = options.mathEquations;
617
+ const saved = md.options.maxNesting;
618
+ let tokens;
619
+ try {
620
+ if (options.maxNesting > 0) md.options.maxNesting = options.maxNesting;
621
+ tokens = md.parse(markdown, env);
622
+ } finally { md.options.maxNesting = saved; }
623
+ if (tokens.some(token => token.type === 'html_block' || token.type === 'math_block' || token.type.startsWith('footnote_') ||
624
+ token.type === 'inline' && token.children?.some(child => child.type === 'html_inline' || child.type === 'math_inline' || child.type.startsWith('footnote_')))) {
625
+ const root = _rapierRenderSemanticRoot(canonical, metadata, {...options, carry, codeBudget: 0, passive: true});
626
+ return Object.freeze({headingIds: Object.freeze([...root.querySelectorAll(RAPIER_RENDERED_HEADING_SELECTOR)].map(heading => heading.id)), captionStart});
627
+ }
628
+ const html = [];
629
+ for (const group of _rapierPartDecorationGroups(tokens)) html.push('<div>', md.renderer.render(group, md.options, env), '</div>');
630
+ const root = document.createElement('template').content.ownerDocument.createElement('div');
631
+ root.innerHTML = sanitizeRapierHtml(html.join(''), 'export');
632
+ _rapierAssignHeadingSlugs(root, RAPIER_RENDERED_HEADING_SELECTOR, false, carry.slugs);
633
+ const headingIds = Object.freeze([...root.querySelectorAll(RAPIER_RENDERED_HEADING_SELECTOR)].map(heading => heading.id));
634
+ _rapierMarkTableCaptions(root, carry);
635
+ return Object.freeze({headingIds, captionStart});
579
636
  }
580
637
 
581
- function* _rapierSemanticDecorations(root) {
638
+ function* _rapierSemanticDecorations(root, carry = null) {
582
639
  yield* _rapierApplyBlockDirectionSteps(root); yield;
583
- yield* _rapierAssignHeadingSlugsSteps(root, RAPIER_RENDERED_HEADING_SELECTOR, false); yield;
640
+ yield* _rapierAssignHeadingSlugsSteps(root, RAPIER_RENDERED_HEADING_SELECTOR, false, carry?.slugs, carry?.headingIds); yield;
584
641
  yield* _rapierDisambiguateRenderedAnchorsSteps(root); yield;
585
642
  for (const code of root.querySelectorAll('pre > code')) { _rapierNormalizeCodeElement(code); yield; }
586
- yield* _rapierMarkTableCaptionsSteps(root); yield;
643
+ yield* _rapierMarkTableCaptionsSteps(root, carry); yield;
587
644
  yield* _rapierMarkFigureCaptionsSteps(root); yield;
588
645
  yield* _rapierMarkListContinuationsSteps(_rapierChildElements(root)); yield;
589
- yield* _rapierDecorateJumpListsSteps(root); yield;
646
+ yield* _rapierDecorateJumpListsSteps(root, carry); yield;
590
647
  }
591
648
 
592
649
  function _rapierInstallSemanticProbe(instance) {
@@ -931,17 +988,23 @@ function _rapierFirstStrongDir(text) {
931
988
 
932
989
  const _RAPIER_DIR_BLOCKS = 'p,h1,h2,h3,h4,h5,h6,li,blockquote,ul,ol,dt,dd,td,th';
933
990
 
934
- function _rapierAssignHeadingSlugs(root, selector, reserveExisting) { return finish(_rapierAssignHeadingSlugsSteps(root, selector, reserveExisting)); }
991
+ function _rapierAssignHeadingSlugs(root, selector, reserveExisting, taken, assigned) { return finish(_rapierAssignHeadingSlugsSteps(root, selector, reserveExisting, taken, assigned)); }
935
992
 
936
- function* _rapierAssignHeadingSlugsSteps(root, selector = RAPIER_RENDERED_HEADING_SELECTOR, reserveExisting = true) {
993
+ function* _rapierAssignHeadingSlugsSteps(root, selector = RAPIER_RENDERED_HEADING_SELECTOR, reserveExisting = true, taken = null, assigned = null) {
937
994
  if (!root || !root.querySelectorAll) return;
938
- const used = Object.create(null);
995
+ const used = taken || Object.create(null);
939
996
  const headings = _rapierDormantHeadings(root, selector, true);
997
+ if (assigned && assigned.length !== headings.length) {
998
+ try { console.warn('[rapier-reader] Part heading facts do not match its rendered headings; assigning ordinary heading IDs.'); } catch (_) {}
999
+ assigned = null;
1000
+ }
940
1001
  const headingSet = new Set(headings);
941
1002
  if (reserveExisting) for (const element of _rapierDormantHeadings(root.isConnected ? document : root, '[id]', true)) { yield;
942
1003
  if (!headingSet.has(element) && element.id) used[element.id] = 0;
943
1004
  }
1005
+ let index = 0;
944
1006
  for (const heading of headings) { yield;
1007
+ if (assigned) { heading.id = assigned[index++]; continue; }
945
1008
  const base = _rapierHeadingSlugBase(heading.textContent);
946
1009
  const owned = typeof _rapierChromeOwnsId === 'function' && _rapierChromeOwnsId(base);
947
1010
  heading.id = _rapierNextHeadingSlug(owned ? 'heading-' + base : base, used);
@@ -1042,9 +1105,9 @@ function _rapierDecodeHash(hash) {
1042
1105
  catch (_) { return raw; }
1043
1106
  }
1044
1107
 
1045
- function _rapierDecorateJumpLists(root) { return finish(_rapierDecorateJumpListsSteps(root)); }
1108
+ function _rapierDecorateJumpLists(root, carry) { return finish(_rapierDecorateJumpListsSteps(root, carry)); }
1046
1109
 
1047
- function* _rapierDecorateJumpListsSteps(root) {
1110
+ function* _rapierDecorateJumpListsSteps(root, carry = null) {
1048
1111
  for (const list of root.querySelectorAll('ul')) { yield;
1049
1112
  if (list.closest('li')) continue;
1050
1113
  const items = Array.from(list.children).filter(item => item.tagName === 'LI');
@@ -1067,7 +1130,7 @@ function* _rapierDecorateJumpListsSteps(root) {
1067
1130
  }
1068
1131
  }
1069
1132
 
1070
- const first = root.firstElementChild, only = first && !first.nextElementSibling ? first : null;
1133
+ const first = root.firstElementChild, only = !carry && first && !first.nextElementSibling ? first : null;
1071
1134
  if (only && only.tagName === 'P' && /^(?:jump\s+to|contents|table\s+of\s+contents):?$/i.test(String(only.textContent || '').trim())) {
1072
1135
  only.classList.add('rapier-jump-label-candidate');
1073
1136
  }
@@ -1109,11 +1172,11 @@ function* _rapierMarkListContinuationsSteps(blocks, mark = (element, name) => el
1109
1172
  }
1110
1173
  }
1111
1174
 
1112
- function _rapierMarkTableCaptions(root) { return finish(_rapierMarkTableCaptionsSteps(root)); }
1175
+ function _rapierMarkTableCaptions(root, carry) { return finish(_rapierMarkTableCaptionsSteps(root, carry)); }
1113
1176
 
1114
- function* _rapierMarkTableCaptionsSteps(root) {
1177
+ function* _rapierMarkTableCaptionsSteps(root, carry = null) {
1115
1178
  const used = new Set(Array.from(root.querySelectorAll('[id]'), element => element.id));
1116
- let ordinal = 0;
1179
+ let ordinal = carry?.captions || 0;
1117
1180
  for (const table of root.querySelectorAll('table')) { yield;
1118
1181
  const sibling = table.nextElementSibling;
1119
1182
  if (!sibling || sibling.tagName !== 'P') continue;
@@ -1126,6 +1189,7 @@ function* _rapierMarkTableCaptionsSteps(root) {
1126
1189
  const existing = (table.getAttribute('aria-describedby') || '').trim();
1127
1190
  table.setAttribute('aria-describedby', existing ? existing + ' ' + id : id);
1128
1191
  }
1192
+ if (carry) carry.captions = ordinal;
1129
1193
  }
1130
1194
 
1131
1195
 
@@ -1829,7 +1893,7 @@ function renderWithMathML(source, metadata = {}) {
1829
1893
  return {html, equations};
1830
1894
  }
1831
1895
 
1832
- return {renderWithMathML, _rapierClipboardPayloadAsync, _rapierPlainTextFileAsync, _rapierCloneRootAsync, _rapierPortablePlainTextAsync, _rapierHeldPicturesAsWordsAsync, _rapierRenderSemanticRootAsync, _rapierProjectPortableRootAsync, _rapierPortableHtmlAsync, _rapierCalloutInfo, _rapierRemoveCalloutMarker, _rapierMathSource, _rapierFlattenPortableDetails, _rapierProjectPortableRoot, _rapierPortableHtml, _rapierNormalizeInlineText, _rapierPortableInlineText, _rapierPortableListText, _rapierPortableTableText, _rapierPortablePlainText, _rapierPlainTextFile, _rapierHeldPicturesAsWords, _rapierSourceTokenValue, _rapierResolveSoftBreakTokens, _rapierInertParse, _rapierUnwrapElement, _rapierBidiStrong, render: (source, metadata = {}) => { if (!md) initMarkdownIt(); return _rapierRenderSemanticRoot(source, metadata).innerHTML; }, initMarkdownIt, _rapierRenderSemanticRoot, _rapierInstallSemanticProbe, _rapierApplyImageGeometry, _rapierImageAltSize, _rapierImageAltSourceParts, _rapierImageAltText, _rapierImageSizeAttributes, _rapierRawHtmlFragment, _rapierApplyBlockDirection, _rapierFirstStrongDir, _rapierAssignHeadingSlugs, _rapierDisambiguateRenderedAnchors, _rapierDecodeHash, _rapierDecorateJumpLists, _rapierMarkFigureCaptions, _rapierMarkListContinuations, _rapierMarkTableCaptions, _rapierNormalizeCodeElement, _rapierLanguageClass, _relabelFootnoteHtml, _footnoteIdFromLabel, wrapDisplayMath, parser: () => md};
1896
+ return {_rapierReadPartDecorations, renderWithMathML, _rapierClipboardPayloadAsync, _rapierPlainTextFileAsync, _rapierCloneRootAsync, _rapierPortablePlainTextAsync, _rapierHeldPicturesAsWordsAsync, _rapierRenderSemanticRootAsync, _rapierProjectPortableRootAsync, _rapierPortableHtmlAsync, _rapierCalloutInfo, _rapierRemoveCalloutMarker, _rapierMathSource, _rapierFlattenPortableDetails, _rapierProjectPortableRoot, _rapierPortableHtml, _rapierNormalizeInlineText, _rapierPortableInlineText, _rapierPortableListText, _rapierPortableTableText, _rapierPortablePlainText, _rapierPlainTextFile, _rapierHeldPicturesAsWords, _rapierSourceTokenValue, _rapierResolveSoftBreakTokens, _rapierInertParse, _rapierUnwrapElement, _rapierBidiStrong, render: (source, metadata = {}) => { if (!md) initMarkdownIt(); return _rapierRenderSemanticRoot(source, metadata).innerHTML; }, initMarkdownIt, _rapierRenderSemanticRoot, _rapierInstallSemanticProbe, _rapierApplyImageGeometry, _rapierImageAltSize, _rapierImageAltSourceParts, _rapierImageAltText, _rapierImageSizeAttributes, _rapierRawHtmlFragment, _rapierApplyBlockDirection, _rapierFirstStrongDir, _rapierAssignHeadingSlugs, _rapierDisambiguateRenderedAnchors, _rapierDecodeHash, _rapierDecorateJumpLists, _rapierMarkFigureCaptions, _rapierMarkListContinuations, _rapierMarkTableCaptions, _rapierNormalizeCodeElement, _rapierLanguageClass, _relabelFootnoteHtml, _footnoteIdFromLabel, wrapDisplayMath, parser: () => md};
1833
1897
  }
1834
1898
  export {RAPIER_TABLE_CAPTION_PREFIX_RE as tableCaptionPrefix, RAPIER_PORTABLE_HIGHLIGHT_HEX as portableHighlightHex, _RAPIER_RTL_SCRIPT as rtlScripts, createMarkdownRenderer};
1835
1899
 
@@ -289,15 +289,21 @@ function* _rapierProjectStyledRootSteps(semanticRoot, options) {
289
289
  if (code) {
290
290
  const lang = _rapierLanguageClass(code) || String(metadata.codeLang || '');
291
291
  code.classList.add('artifact-code');
292
- if (metadata.docKind === 'code') _rapierPaintCode(code, _rapierArtifactHighlight(code.textContent || '', lang));
292
+ if (metadata.docKind === 'code') {
293
+ const colored = _rapierArtifactHighlight(code.textContent || '', lang);
294
+ _rapierPaintCode(code, opts.sanitized ? sanitizeRapierHtml(colored, 'export') : colored);
295
+ }
293
296
  if (lang) code.classList.add('language-' + String(lang).replace(/[^a-z0-9_-]/gi, ''));
294
297
  }
295
298
  } else {
299
+ let codeLeft = opts.codeBudget >= 0 ? opts.codeBudget : Infinity;
296
300
  for (const code of root.querySelectorAll('pre > code')) { yield;
297
301
  if (code.parentElement?.classList.contains('diagram-source') &&
298
302
  code.closest('.diagram-block')?.getAttribute('data-diagram-state') === 'ready') continue;
299
303
  const lang = _rapierLanguageClass(code) || 'text';
300
- _rapierPaintCode(code, _rapierArtifactHighlight(code.textContent || '', lang));
304
+ if ((codeLeft -= code.textContent.length) < 0) { code.replaceChildren(document.createTextNode(code.textContent)); continue; }
305
+ const colored = _rapierArtifactHighlight(code.textContent || '', lang);
306
+ _rapierPaintCode(code, opts.sanitized ? sanitizeRapierHtml(colored, 'export') : colored);
301
307
  }
302
308
 
303
309
  for (const table of root.querySelectorAll('table')) { yield;
@@ -336,6 +342,13 @@ function* _rapierProjectStyledRootSteps(semanticRoot, options) {
336
342
 
337
343
  yield* _rapierPrefixPortableAnchorsSteps(root, opts.baseName || metadata.filename || 'document');
338
344
 
345
+ if (opts.sanitized) {
346
+ for (const cache of root.querySelectorAll('.diagram-cache')) {
347
+ yield;
348
+ cache.innerHTML = sanitizeRapierHtml(cache.innerHTML, 'export');
349
+ }
350
+ return root;
351
+ }
339
352
  return yield* cleanTree(root, sanitizeRapierHtml, 'export');
340
353
  }
341
354
 
@@ -100,7 +100,7 @@ export function* blockWindows(source, bodyOffset, parser, env, keepNul = false)
100
100
  return end < body.length ? sourceOffset(end + 1) : undefined;
101
101
  }});
102
102
  let lines = 0;
103
- for (let at = 0; at < body.length; at++) if (body.charCodeAt(at) === 10) lines++;
103
+ for (let at = body.indexOf('\n'); at !== -1; at = body.indexOf('\n', at + 1)) lines++;
104
104
  if (lines <= BLOCK_WINDOW) {
105
105
  state = new parser.block.State(body, parser, env, tokens);
106
106
  state.rapierSourceSlice = (from, to) => source.slice(sourceOffset(from), sourceOffset(to));
@@ -179,8 +179,7 @@ export function* blockWindows(source, bodyOffset, parser, env, keepNul = false)
179
179
  }
180
180
  }
181
181
 
182
- const PERCENT_PAYLOAD = Array.from({length: 128}, (_, code) => code >= 48 && code <= 57 || code >= 65 && code <= 90 ||
183
- code >= 97 && code <= 122 || '-._~:/?@+$,;='.includes(String.fromCharCode(code)));
182
+ const INVALID_PERCENT_PAYLOAD = /[^A-Za-z0-9._~:\/?@+$,;=%-]/;
184
183
  const isHexUnit = code => code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102;
185
184
  let lastScan = null;
186
185
  export function dataImage(url) {
@@ -197,13 +196,11 @@ function scanDataImage(url) {
197
196
  ...(prepared.encoding ? {encoding: prepared.encoding} : {})};
198
197
  if (/^data:image\/svg\+xml,/i.test(url)) {
199
198
  const payloadStart = 19;
200
- let byteLength = 0;
201
- for (let at = payloadStart; at < url.length; at++, byteLength++) {
202
- const code = url.charCodeAt(at);
203
- if (code === 37) {
204
- if (!isHexUnit(url.charCodeAt(at + 1)) || !isHexUnit(url.charCodeAt(at + 2))) return null;
205
- at += 2;
206
- } else if (!(code < 128 && PERCENT_PAYLOAD[code])) return null;
199
+ if (INVALID_PERCENT_PAYLOAD.test(url)) return null;
200
+ let byteLength = url.length - payloadStart;
201
+ for (let at = url.indexOf('%', payloadStart); at !== -1; at = url.indexOf('%', at + 3)) {
202
+ if (!isHexUnit(url.charCodeAt(at + 1)) || !isHexUnit(url.charCodeAt(at + 2))) return null;
203
+ byteLength -= 2;
207
204
  }
208
205
  return byteLength && byteLength <= IMAGE_LIMITS.bytes
209
206
  ? {codec: 'image/svg+xml', byteLength, payloadStart, encoding: 'percent'} : null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rapier-markdown-kit",
3
- "version": "1.2.42",
3
+ "version": "1.2.43",
4
4
  "description": "Read, render and write Self-contained Markdown: one .md file that carries its pictures, drawings and layout, and that any Markdown app can read. HTML renderer, stylesheet, text layout, Will/1 agent permissions, and an edit history with authorship and offline merge. MIT, no dependencies.",
5
5
  "keywords": [
6
6
  "markdown",