superbee 0.4.4-pre.9 → 0.4.5-pre.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -63,8 +63,8 @@ var require_common = __commonJS({
63
63
  return target;
64
64
  }
65
65
  function repeat(string3, count) {
66
- var result = "", cycle;
67
- for (cycle = 0; cycle < count; cycle += 1) {
66
+ var result = "", cycle2;
67
+ for (cycle2 = 0; cycle2 < count; cycle2 += 1) {
68
68
  result += string3;
69
69
  }
70
70
  return result;
@@ -30835,6 +30835,14 @@ var InvalidInputError = class extends Error {
30835
30835
  this.name = "InvalidInputError";
30836
30836
  }
30837
30837
  };
30838
+ var FrontmatterRefusedError = class extends InvalidInputError {
30839
+ code;
30840
+ constructor(code2, detail) {
30841
+ super(`frontmatter cannot be stored: ${detail}`);
30842
+ this.name = "FrontmatterRefusedError";
30843
+ this.code = code2;
30844
+ }
30845
+ };
30838
30846
  var FilesystemIdentityAliasError = class extends InvalidInputError {
30839
30847
  rel;
30840
30848
  segment;
@@ -30859,12 +30867,21 @@ var ConcurrentReplacementError = class extends Error {
30859
30867
  }
30860
30868
  };
30861
30869
 
30862
- // ../core/src/portable-frontmatter.ts
30870
+ // ../core/src/bounded-yaml.ts
30863
30871
  var import_js_yaml = __toESM(require_js_yaml2(), 1);
30864
30872
 
30865
30873
  // ../core/src/frontmatter-contract.ts
30874
+ var FrontmatterLimitError = class extends Error {
30875
+ name = "FrontmatterLimitError";
30876
+ code;
30877
+ constructor(code2, message) {
30878
+ super(message);
30879
+ this.code = code2;
30880
+ }
30881
+ };
30866
30882
  var MalformedDocumentError = class extends Error {
30867
30883
  name = "MalformedDocumentError";
30884
+ code;
30868
30885
  context;
30869
30886
  detail;
30870
30887
  constructor(context, cause) {
@@ -30872,12 +30889,165 @@ var MalformedDocumentError = class extends Error {
30872
30889
  super(
30873
30890
  `malformed frontmatter${context ? ` in '${context}'` : ""}: ${detail} \u2014 fix the YAML or remove the file`
30874
30891
  );
30892
+ this.code = cause instanceof FrontmatterLimitError ? cause.code : "FRONTMATTER_MALFORMED";
30875
30893
  if (context !== void 0) this.context = context;
30876
30894
  this.detail = detail;
30877
30895
  if (cause !== void 0) this.cause = cause;
30878
30896
  }
30879
30897
  };
30880
30898
 
30899
+ // ../core/src/bounded-yaml.ts
30900
+ var FRONTMATTER_LIMITS = Object.freeze({
30901
+ sourceChars: 256 * 1024,
30902
+ depth: 32,
30903
+ aliases: 1e3,
30904
+ expandedNodes: 1e5,
30905
+ expandedChars: 1024 * 1024
30906
+ });
30907
+ var PARSE_NESTING_GUARD = FRONTMATTER_LIMITS.depth * 4;
30908
+ function tooDeep() {
30909
+ return new FrontmatterLimitError("FRONTMATTER_TOO_DEEP", `YAML nesting is deeper than ${FRONTMATTER_LIMITS.depth} levels`);
30910
+ }
30911
+ function tooLarge() {
30912
+ return new FrontmatterLimitError(
30913
+ "FRONTMATTER_ALIAS_LIMIT",
30914
+ `YAML aliases expand to more than ${FRONTMATTER_LIMITS.expandedNodes} nodes or ${FRONTMATTER_LIMITS.expandedChars} characters`
30915
+ );
30916
+ }
30917
+ function cycle() {
30918
+ return new FrontmatterLimitError("FRONTMATTER_CYCLE", "YAML aliases form a cycle");
30919
+ }
30920
+ function scalarExtent(value) {
30921
+ const chars = typeof value === "string" ? value.length : ArrayBuffer.isView(value) ? value.byteLength : 0;
30922
+ return { nodes: 1, chars, depth: 0 };
30923
+ }
30924
+ function isCollection(value) {
30925
+ if (Array.isArray(value)) return true;
30926
+ if (value === null || typeof value !== "object") return false;
30927
+ const prototype = Object.getPrototypeOf(value);
30928
+ return prototype === Object.prototype || prototype === null;
30929
+ }
30930
+ var ExtentMeter = class {
30931
+ known = /* @__PURE__ */ new Map();
30932
+ path = /* @__PURE__ */ new Set();
30933
+ unfinished;
30934
+ constructor(unfinished = /* @__PURE__ */ new Set()) {
30935
+ this.unfinished = unfinished;
30936
+ }
30937
+ measure(value) {
30938
+ if (!isCollection(value)) return scalarExtent(value);
30939
+ const known = this.known.get(value);
30940
+ if (known !== void 0) return known;
30941
+ if (this.path.has(value) || this.unfinished.has(value)) throw cycle();
30942
+ return this.walk(value);
30943
+ }
30944
+ walk(value) {
30945
+ if (this.path.size >= FRONTMATTER_LIMITS.depth) throw tooDeep();
30946
+ this.path.add(value);
30947
+ const keyed = !Array.isArray(value);
30948
+ const extent = { nodes: 1, chars: 0, depth: 1 };
30949
+ for (const [key, child] of Object.entries(value)) {
30950
+ const inner = this.measure(child);
30951
+ extent.nodes += inner.nodes;
30952
+ extent.chars += inner.chars + (keyed ? key.length : 0);
30953
+ extent.depth = Math.max(extent.depth, inner.depth + 1);
30954
+ if (extent.nodes > FRONTMATTER_LIMITS.expandedNodes || extent.chars > FRONTMATTER_LIMITS.expandedChars) throw tooLarge();
30955
+ if (extent.depth > FRONTMATTER_LIMITS.depth) throw tooDeep();
30956
+ }
30957
+ this.path.delete(value);
30958
+ this.known.set(value, extent);
30959
+ return extent;
30960
+ }
30961
+ };
30962
+ var AliasBudget = class {
30963
+ unfinished = /* @__PURE__ */ new Set();
30964
+ finished = /* @__PURE__ */ new Set();
30965
+ meter = new ExtentMeter(this.unfinished);
30966
+ aliases = 0;
30967
+ nodes = 0;
30968
+ chars = 0;
30969
+ /** Wrap the parser's anchor table; the parser reads it only to resolve an alias. */
30970
+ watch(state) {
30971
+ state.anchorMap = new Proxy(state.anchorMap, {
30972
+ get: (target, name, receiver) => {
30973
+ const value = Reflect.get(target, name, receiver);
30974
+ if (typeof name === "string") this.charge(name, value);
30975
+ return value;
30976
+ },
30977
+ set: (target, name, value, receiver) => {
30978
+ if (typeof name === "string") {
30979
+ this.finished.delete(name);
30980
+ if (isCollection(value)) this.unfinished.add(value);
30981
+ }
30982
+ return Reflect.set(target, name, value, receiver);
30983
+ }
30984
+ });
30985
+ }
30986
+ /** Called when an anchored node closes: its anchor now names a complete value. */
30987
+ close(anchor, value) {
30988
+ this.finished.add(anchor);
30989
+ if (isCollection(value)) this.unfinished.delete(value);
30990
+ }
30991
+ charge(name, value) {
30992
+ this.aliases += 1;
30993
+ if (this.aliases > FRONTMATTER_LIMITS.aliases) {
30994
+ throw new FrontmatterLimitError(
30995
+ "FRONTMATTER_ALIAS_LIMIT",
30996
+ `YAML aliases are used more than ${FRONTMATTER_LIMITS.aliases} times`
30997
+ );
30998
+ }
30999
+ if (!this.finished.has(name) && isCollection(value)) throw cycle();
31000
+ const extent = this.meter.measure(value);
31001
+ this.nodes += extent.nodes;
31002
+ this.chars += extent.chars;
31003
+ if (this.nodes > FRONTMATTER_LIMITS.expandedNodes || this.chars > FRONTMATTER_LIMITS.expandedChars) throw tooLarge();
31004
+ }
31005
+ };
31006
+ var MERGE_KEY_LIMIT_REASON = "merge keys exceeded maxTotalMergeKeys";
31007
+ function loadBoundedYaml(source, options = {}) {
31008
+ if (source.length > FRONTMATTER_LIMITS.sourceChars) {
31009
+ throw new FrontmatterLimitError(
31010
+ "FRONTMATTER_TOO_LARGE",
31011
+ `YAML source is longer than ${FRONTMATTER_LIMITS.sourceChars} characters`
31012
+ );
31013
+ }
31014
+ const schema = options.schema === "json" ? import_js_yaml.default.JSON_SCHEMA : options.schema;
31015
+ const budget = new AliasBudget();
31016
+ let watched;
31017
+ let nesting = 0;
31018
+ let value;
31019
+ try {
31020
+ value = import_js_yaml.default.safeLoad(source, {
31021
+ ...schema ? { schema } : {},
31022
+ listener(event, rawState) {
31023
+ const state = rawState;
31024
+ if (state.anchorMap !== watched) {
31025
+ budget.watch(state);
31026
+ watched = state.anchorMap;
31027
+ }
31028
+ if (event === "open") {
31029
+ nesting += 1;
31030
+ if (nesting > PARSE_NESTING_GUARD) throw tooDeep();
31031
+ } else {
31032
+ nesting -= 1;
31033
+ if (state.anchor !== null) budget.close(state.anchor, state.result);
31034
+ }
31035
+ }
31036
+ });
31037
+ } catch (error) {
31038
+ const reason = error.reason;
31039
+ if (typeof reason === "string" && reason.startsWith(MERGE_KEY_LIMIT_REASON)) {
31040
+ throw new FrontmatterLimitError("FRONTMATTER_ALIAS_LIMIT", reason);
31041
+ }
31042
+ throw error;
31043
+ }
31044
+ new ExtentMeter().measure(value);
31045
+ return value;
31046
+ }
31047
+
31048
+ // ../core/src/frontmatter.ts
31049
+ var import_js_yaml2 = __toESM(require_js_yaml2(), 1);
31050
+
30881
31051
  // ../core/src/frontmatter-splitter.ts
30882
31052
  function delimiterLineEnd(input, offset) {
30883
31053
  if (!input.startsWith("---", offset)) return null;
@@ -30907,12 +31077,106 @@ function splitLeadingFrontmatter(raw, context) {
30907
31077
  throw new MalformedDocumentError(context, new Error("unterminated YAML frontmatter delimiter"));
30908
31078
  }
30909
31079
 
31080
+ // ../core/src/frontmatter.ts
31081
+ var YAML_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp";
31082
+ function requireYamlTimestampType() {
31083
+ const type = import_js_yaml2.default.DEFAULT_SAFE_SCHEMA.implicit.find(
31084
+ (candidate) => candidate.tag === YAML_TIMESTAMP_TAG
31085
+ );
31086
+ if (!type) throw new Error("js-yaml safe schema is missing its timestamp type");
31087
+ return type;
31088
+ }
31089
+ var yamlTimestampType = requireYamlTimestampType();
31090
+ var stringTimestampType = new import_js_yaml2.default.Type(YAML_TIMESTAMP_TAG, {
31091
+ kind: "scalar",
31092
+ resolve: (value) => yamlTimestampType.resolve(value),
31093
+ construct: (value) => value
31094
+ });
31095
+ var losslessDateSchema = new import_js_yaml2.default.Schema({
31096
+ include: [import_js_yaml2.default.DEFAULT_SAFE_SCHEMA],
31097
+ implicit: [stringTimestampType]
31098
+ });
31099
+ var yamlEngine = {
31100
+ parse(input) {
31101
+ return loadBoundedYaml(input, { schema: losslessDateSchema }) ?? {};
31102
+ }
31103
+ };
31104
+ function normalizeFrontmatter(data, options) {
31105
+ const out = { ...data };
31106
+ if (options.preserveTimestamp || options.okfVersion === "0.2") return out;
31107
+ const value = out.timestamp;
31108
+ if (value instanceof Date) {
31109
+ out.timestamp = value.toISOString();
31110
+ } else if (typeof value === "number" && Number.isFinite(value)) {
31111
+ out.timestamp = new Date(value).toISOString();
31112
+ } else if (typeof value === "string" && yamlTimestampType.resolve(value)) {
31113
+ const parsed = yamlTimestampType.construct(value);
31114
+ if (parsed instanceof Date) out.timestamp = parsed.toISOString();
31115
+ }
31116
+ return out;
31117
+ }
31118
+ function parseMarkdown(raw, context, options = {}) {
31119
+ const split = splitLeadingFrontmatter(raw, context);
31120
+ if (!("yamlSource" in split)) return { frontmatter: {}, body: split.body };
31121
+ return { frontmatter: parseFrontmatter(split.yamlSource, context, options), body: split.body };
31122
+ }
31123
+ function parseFrontmatter(source, context, options = {}) {
31124
+ let parsed;
31125
+ try {
31126
+ parsed = yamlEngine.parse(source);
31127
+ } catch (err) {
31128
+ throw new MalformedDocumentError(context, err);
31129
+ }
31130
+ return normalizeFrontmatter(parsed, options);
31131
+ }
31132
+ function isStackExhaustion(error) {
31133
+ if (error instanceof RangeError) return /call stack/i.test(error.message);
31134
+ return error?.name === "InternalError" && /recursion/i.test(error.message);
31135
+ }
31136
+ function stringifyFrontmatter(data) {
31137
+ let dumped;
31138
+ try {
31139
+ dumped = import_js_yaml2.default.safeDump(data).trim();
31140
+ } catch (error) {
31141
+ if (isStackExhaustion(error)) throw new FrontmatterRefusedError("FRONTMATTER_TOO_DEEP", `YAML nesting is deeper than ${FRONTMATTER_LIMITS.depth} levels`);
31142
+ throw error;
31143
+ }
31144
+ try {
31145
+ yamlEngine.parse(`${dumped}
31146
+ `);
31147
+ } catch (error) {
31148
+ if (error instanceof FrontmatterLimitError) throw new FrontmatterRefusedError(error.code, error.message);
31149
+ const detail = (error instanceof Error ? error.message : String(error)).split("\n")[0] ?? "";
31150
+ throw new FrontmatterRefusedError("FRONTMATTER_MALFORMED", detail);
31151
+ }
31152
+ return dumped;
31153
+ }
31154
+ function normalizeDocumentBodyForStorage(body) {
31155
+ return body.endsWith("\n") ? body : `${body}
31156
+ `;
31157
+ }
31158
+ function stringifyWithData(data, body) {
31159
+ return stringifyWithSerializedFrontmatter(stringifyFrontmatter(data), body);
31160
+ }
31161
+ function stringifyWithSerializedFrontmatter(dumped, body) {
31162
+ const content3 = body ?? "";
31163
+ const newline = (value) => value.endsWith("\n") ? value : `${value}
31164
+ `;
31165
+ if (dumped === "{}") return normalizeDocumentBodyForStorage(content3);
31166
+ return `---
31167
+ ${newline(dumped)}---
31168
+ ${normalizeDocumentBodyForStorage(content3)}`;
31169
+ }
31170
+ function stringifyDoc(frontmatter2, body) {
31171
+ return stringifyWithData(frontmatter2, body);
31172
+ }
31173
+
30910
31174
  // ../core/src/portable-frontmatter.ts
30911
31175
  function parseLeadingFrontmatter(raw, context) {
30912
31176
  const split = splitLeadingFrontmatter(raw, context);
30913
31177
  if (!("yamlSource" in split)) return {};
30914
31178
  try {
30915
- const parsed = import_js_yaml.default.safeLoad(split.yamlSource);
31179
+ const parsed = loadBoundedYaml(split.yamlSource);
30916
31180
  if (parsed === void 0 || parsed === null) return {};
30917
31181
  if (typeof parsed !== "object" || Array.isArray(parsed)) {
30918
31182
  throw new TypeError("YAML frontmatter must be a mapping");
@@ -30923,6 +31187,18 @@ function parseLeadingFrontmatter(raw, context) {
30923
31187
  throw new MalformedDocumentError(context, error);
30924
31188
  }
30925
31189
  }
31190
+ function assertStorableFrontmatter(raw) {
31191
+ try {
31192
+ parseLeadingFrontmatter(raw);
31193
+ const split = splitLeadingFrontmatter(raw);
31194
+ if ("yamlSource" in split) parseFrontmatter(split.yamlSource);
31195
+ } catch (error) {
31196
+ if (error instanceof MalformedDocumentError && error.code !== "FRONTMATTER_MALFORMED") {
31197
+ throw new FrontmatterRefusedError(error.code, error.detail);
31198
+ }
31199
+ if (!(error instanceof MalformedDocumentError)) throw error;
31200
+ }
31201
+ }
30926
31202
 
30927
31203
  // ../core/src/paths.ts
30928
31204
  var RESERVED_FILENAMES = ["index.md", "log.md"];
@@ -30956,6 +31232,17 @@ function isReservedFile(relPath) {
30956
31232
  const base = toPosix(relPath).split("/").pop() ?? "";
30957
31233
  return RESERVED_FILENAMES.includes(base);
30958
31234
  }
31235
+ function isHiddenWalkEntry(name) {
31236
+ return name.startsWith(".");
31237
+ }
31238
+ function hasMarkdownExtension(name) {
31239
+ return name.toLowerCase().endsWith(".md");
31240
+ }
31241
+ function classifyWalkPath(relPath) {
31242
+ const segments = toPosix(relPath).split("/").filter((segment) => segment !== "");
31243
+ if (segments.some(isHiddenWalkEntry)) return "hidden";
31244
+ return hasMarkdownExtension(segments.at(-1) ?? "") ? "markdown" : "other";
31245
+ }
30959
31246
  function conceptIdFromPath(relPath) {
30960
31247
  const norm = toPosix(relPath).replace(/^\.?\//, "").split("/").filter((segment) => segment !== ".").join("/");
30961
31248
  return norm.endsWith(".md") ? norm.slice(0, -3) : norm;
@@ -31282,82 +31569,6 @@ function inventoryDigest(inventory) {
31282
31569
  return `sha256:${sha256HexOfUtf8(JSON.stringify(inventory.map((row) => [row.id, row.version])))}`;
31283
31570
  }
31284
31571
 
31285
- // ../core/src/frontmatter.ts
31286
- var import_js_yaml2 = __toESM(require_js_yaml2(), 1);
31287
- var YAML_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp";
31288
- function requireYamlTimestampType() {
31289
- const type = import_js_yaml2.default.DEFAULT_SAFE_SCHEMA.implicit.find(
31290
- (candidate) => candidate.tag === YAML_TIMESTAMP_TAG
31291
- );
31292
- if (!type) throw new Error("js-yaml safe schema is missing its timestamp type");
31293
- return type;
31294
- }
31295
- var yamlTimestampType = requireYamlTimestampType();
31296
- var stringTimestampType = new import_js_yaml2.default.Type(YAML_TIMESTAMP_TAG, {
31297
- kind: "scalar",
31298
- resolve: (value) => yamlTimestampType.resolve(value),
31299
- construct: (value) => value
31300
- });
31301
- var losslessDateSchema = new import_js_yaml2.default.Schema({
31302
- include: [import_js_yaml2.default.DEFAULT_SAFE_SCHEMA],
31303
- implicit: [stringTimestampType]
31304
- });
31305
- var yamlEngine = {
31306
- parse(input) {
31307
- return import_js_yaml2.default.safeLoad(input, { schema: losslessDateSchema }) ?? {};
31308
- }
31309
- };
31310
- function normalizeFrontmatter(data, options) {
31311
- const out = { ...data };
31312
- if (options.preserveTimestamp || options.okfVersion === "0.2") return out;
31313
- const value = out.timestamp;
31314
- if (value instanceof Date) {
31315
- out.timestamp = value.toISOString();
31316
- } else if (typeof value === "number" && Number.isFinite(value)) {
31317
- out.timestamp = new Date(value).toISOString();
31318
- } else if (typeof value === "string" && yamlTimestampType.resolve(value)) {
31319
- const parsed = yamlTimestampType.construct(value);
31320
- if (parsed instanceof Date) out.timestamp = parsed.toISOString();
31321
- }
31322
- return out;
31323
- }
31324
- function parseMarkdown(raw, context, options = {}) {
31325
- const split = splitLeadingFrontmatter(raw, context);
31326
- if (!("yamlSource" in split)) return { frontmatter: {}, body: split.body };
31327
- return { frontmatter: parseFrontmatter(split.yamlSource, context, options), body: split.body };
31328
- }
31329
- function parseFrontmatter(source, context, options = {}) {
31330
- let parsed;
31331
- try {
31332
- parsed = yamlEngine.parse(source);
31333
- } catch (err) {
31334
- throw new MalformedDocumentError(context, err);
31335
- }
31336
- return normalizeFrontmatter(parsed, options);
31337
- }
31338
- function stringifyFrontmatter(data) {
31339
- return import_js_yaml2.default.safeDump(data).trim();
31340
- }
31341
- function normalizeDocumentBodyForStorage(body) {
31342
- return body.endsWith("\n") ? body : `${body}
31343
- `;
31344
- }
31345
- function stringifyWithData(data, body) {
31346
- return stringifyWithSerializedFrontmatter(stringifyFrontmatter(data), body);
31347
- }
31348
- function stringifyWithSerializedFrontmatter(dumped, body) {
31349
- const content3 = body ?? "";
31350
- const newline = (value) => value.endsWith("\n") ? value : `${value}
31351
- `;
31352
- if (dumped === "{}") return normalizeDocumentBodyForStorage(content3);
31353
- return `---
31354
- ${newline(dumped)}---
31355
- ${normalizeDocumentBodyForStorage(content3)}`;
31356
- }
31357
- function stringifyDoc(frontmatter2, body) {
31358
- return stringifyWithData(frontmatter2, body);
31359
- }
31360
-
31361
31572
  // ../core/src/code-unit-order.ts
31362
31573
  function compareCodeUnits(a, b) {
31363
31574
  return a < b ? -1 : a > b ? 1 : 0;
@@ -31769,24 +31980,7 @@ function hasSourceIdentity(sources, identity) {
31769
31980
  return Array.isArray(sources) && sources.some((entry) => matchesSourceIdentity(entry, identity));
31770
31981
  }
31771
31982
 
31772
- // ../core/src/engine.ts
31773
- async function readBundleOkfVersion(backend) {
31774
- const index2 = await backend.readReserved("", "index.md");
31775
- if (!index2) return void 0;
31776
- const value = parseLeadingFrontmatter(index2.content, "index.md").okf_version;
31777
- return typeof value === "string" && value.trim() !== "" ? value : void 0;
31778
- }
31779
- function assertReadableConceptId(id) {
31780
- assertSafeConceptId(id);
31781
- const rel = pathFromConceptId(id);
31782
- if (isReservedFile(rel)) {
31783
- throw new InvalidInputError(`'${id}' is a reserved file (index.md / log.md), not a concept document.`);
31784
- }
31785
- }
31786
- async function readDocVersioned(backend, id) {
31787
- assertReadableConceptId(id);
31788
- return backend.read(id);
31789
- }
31983
+ // ../core/src/document-scan.ts
31790
31984
  function isEnoent(err) {
31791
31985
  return typeof err === "object" && err !== null && err.code === "ENOENT";
31792
31986
  }
@@ -31817,6 +32011,25 @@ async function readManyExisting(backend, ids, onMalformed, onAliased) {
31817
32011
  return out;
31818
32012
  }
31819
32013
  }
32014
+
32015
+ // ../core/src/engine.ts
32016
+ async function readBundleOkfVersion(backend) {
32017
+ const index2 = await backend.readReserved("", "index.md");
32018
+ if (!index2) return void 0;
32019
+ const value = parseLeadingFrontmatter(index2.content, "index.md").okf_version;
32020
+ return typeof value === "string" && value.trim() !== "" ? value : void 0;
32021
+ }
32022
+ function assertReadableConceptId(id) {
32023
+ assertSafeConceptId(id);
32024
+ const rel = pathFromConceptId(id);
32025
+ if (isReservedFile(rel)) {
32026
+ throw new InvalidInputError(`'${id}' is a reserved file (index.md / log.md), not a concept document.`);
32027
+ }
32028
+ }
32029
+ async function readDocVersioned(backend, id) {
32030
+ assertReadableConceptId(id);
32031
+ return backend.read(id);
32032
+ }
31820
32033
  async function scanMatching(backend, filter, onSkip) {
31821
32034
  const ids = await backend.list(filter.prefix);
31822
32035
  const results = [];
@@ -31935,6 +32148,13 @@ function resolveContentType(key, override) {
31935
32148
  return inferContentTypeFromDocKey(key) ?? DEFAULT_BLOB_CONTENT_TYPE;
31936
32149
  }
31937
32150
 
32151
+ // ../core/src/reserved-write.ts
32152
+ function assertStorableReservedWrite(dir, name, content3) {
32153
+ assertSafeReservedDir(dir);
32154
+ assertSafeReservedFilename(name);
32155
+ if (name.endsWith(".md")) assertStorableFrontmatter(content3);
32156
+ }
32157
+
31938
32158
  // ../core/src/filesystem-identity.ts
31939
32159
  import { promises as fs2 } from "node:fs";
31940
32160
  import path2 from "node:path";
@@ -33085,7 +33305,7 @@ async function walkFiles(port, root, keep, sub = "") {
33085
33305
  const entries = await port.entries(path3.join(root, sub)) ?? [];
33086
33306
  const out = [];
33087
33307
  for (const entry of entries) {
33088
- if (entry.name.startsWith(".")) continue;
33308
+ if (isHiddenWalkEntry(entry.name)) continue;
33089
33309
  const rel = sub === "" ? entry.name : `${sub}/${entry.name}`;
33090
33310
  if (entry.kind === "directory") {
33091
33311
  out.push(...await walkFiles(port, root, keep, rel));
@@ -33289,8 +33509,7 @@ var FilesystemBackend = class _FilesystemBackend {
33289
33509
  return { content: content3, version: versionOfBytes(content3) };
33290
33510
  }
33291
33511
  async writeReserved(dir, name, content3, options = {}) {
33292
- assertSafeReservedDir(dir);
33293
- assertSafeReservedFilename(name);
33512
+ assertStorableReservedWrite(dir, name, content3);
33294
33513
  const rel = reservedPath(dir, name);
33295
33514
  return this.#mutateExact(rel, async (target) => {
33296
33515
  if (options.expectedVersion !== void 0) {
@@ -33345,12 +33564,15 @@ var FilesystemBackend = class _FilesystemBackend {
33345
33564
  return observed.state === "exact" && observed.value.kind === "file";
33346
33565
  }
33347
33566
  async listBlobs(prefix) {
33348
- const files = await walkFiles(this.#port, this.#root, (name) => !name.toLowerCase().endsWith(".md"));
33567
+ const files = await walkFiles(this.#port, this.#root, (name) => !hasMarkdownExtension(name));
33349
33568
  const keys2 = files.map(toPosix);
33350
33569
  const filtered = prefix ? keys2.filter((k) => k.startsWith(prefix)) : keys2;
33351
33570
  filtered.sort(compareStorageKeys);
33352
33571
  return filtered;
33353
33572
  }
33573
+ classifyChangedPath(relPath) {
33574
+ return classifyWalkPath(relPath);
33575
+ }
33354
33576
  capabilities() {
33355
33577
  return {
33356
33578
  history: false,
@@ -43216,6 +43438,72 @@ function gfmFromMarkdown() {
43216
43438
  ];
43217
43439
  }
43218
43440
 
43441
+ // ../markdown-renderer/src/parse.ts
43442
+ var MAX_BLOCK_SCORE = 44e7;
43443
+ var MAX_BLOCK_EMPHASIS = 4e3;
43444
+ var MAX_EMPHASIS_SCORE = 1e8;
43445
+ var MAX_PIPES = 25e3;
43446
+ var MAX_LINE_MARKERS = 14e3;
43447
+ var MAX_TABLES = 2500;
43448
+ var MAX_LINE_NESTING = 64;
43449
+ var MAX_LINE_PREFIX = 512;
43450
+ var CONTAINER_MARKER = />|[-+*](?=[ \t]|$)|\d{1,9}[.)](?=[ \t]|$)|\[\^[^[\]\s]+\]:/my;
43451
+ function withinParseLimits(source) {
43452
+ let emphasisSum = 0, score = 0, block = 0, emphasis = 0, pipes = 0, markers = 0, tables = 0;
43453
+ let lineStart = 0, linePipes = 0, lineDashes = 0, blank = true, delimiterRow = true;
43454
+ for (let i = 0; i <= source.length; i++) {
43455
+ const code2 = i < source.length ? source.charCodeAt(i) : 10;
43456
+ if (code2 === 13 && source.charCodeAt(i + 1) === 10) continue;
43457
+ if (code2 === 10 || code2 === 13) {
43458
+ let nesting = 0, prefix = 0, position2 = lineStart;
43459
+ for (; ; ) {
43460
+ while (source.charCodeAt(position2) === 32 || source.charCodeAt(position2) === 9) position2++;
43461
+ CONTAINER_MARKER.lastIndex = position2;
43462
+ if (!CONTAINER_MARKER.test(source)) break;
43463
+ position2 = CONTAINER_MARKER.lastIndex;
43464
+ prefix = position2 - lineStart;
43465
+ nesting++;
43466
+ }
43467
+ if (nesting > MAX_LINE_NESTING || prefix > MAX_LINE_PREFIX) return false;
43468
+ markers += nesting;
43469
+ if (delimiterRow && linePipes > 0 && lineDashes > 0) tables++;
43470
+ if (blank) {
43471
+ score += block * block;
43472
+ emphasisSum += emphasis * emphasis;
43473
+ block = 0;
43474
+ emphasis = 0;
43475
+ } else {
43476
+ block += 2;
43477
+ }
43478
+ lineStart = i + 1;
43479
+ linePipes = lineDashes = 0;
43480
+ blank = delimiterRow = true;
43481
+ continue;
43482
+ }
43483
+ if (code2 === 32 || code2 === 9) continue;
43484
+ blank = false;
43485
+ if (code2 === 124) linePipes++, pipes++;
43486
+ else if (code2 === 45) lineDashes++;
43487
+ else if (code2 !== 58 && code2 !== 62) delimiterRow = false;
43488
+ const alphanumeric = code2 >= 48 && code2 <= 57 || code2 >= 65 && code2 <= 90 || code2 >= 97 && code2 <= 122 || code2 >= 128;
43489
+ if (!alphanumeric) block += code2 === 93 ? 2 : 1;
43490
+ if ((code2 === 42 || code2 === 95 || code2 === 126) && ++emphasis > MAX_BLOCK_EMPHASIS) return false;
43491
+ }
43492
+ return (emphasisSum + emphasis * emphasis) / MAX_EMPHASIS_SCORE + (score + block * block) / MAX_BLOCK_SCORE + (markers / MAX_LINE_MARKERS) ** 2 + (tables / MAX_TABLES) ** 2 + (pipes / MAX_PIPES) ** 2 <= 1;
43493
+ }
43494
+ function isCallStackExhausted(error) {
43495
+ return error instanceof Error && (error.name === "RangeError" || error.name === "InternalError") && /call stack|recursion/i.test(error.message);
43496
+ }
43497
+ function parseWithinLimits(source) {
43498
+ if (!withinParseLimits(source)) return null;
43499
+ try {
43500
+ return fromMarkdown(source, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] });
43501
+ } catch (error) {
43502
+ if (isCallStackExhausted(error)) return null;
43503
+ throw error;
43504
+ }
43505
+ }
43506
+
43219
43507
  // ../markdown-renderer/src/index.tsx
43220
43508
  var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
43221
43509
  function renderableConceptId(fromId, raw) {
@@ -43229,13 +43517,36 @@ function resolveBound(requested, max) {
43229
43517
  if (requested === void 0 || !Number.isFinite(requested) || requested < 1) return max;
43230
43518
  return Math.min(Math.floor(requested), max);
43231
43519
  }
43232
- function textOf(node2) {
43233
- if (node2.type === "text" || node2.type === "inlineCode" || node2.type === "html") {
43234
- return node2.value ?? "";
43520
+ var MAX_STATIC_IMAGE_ASSETS = 4096;
43521
+ var STATIC_IMAGE_PATH = /^\/assets\/(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)*[A-Za-z0-9][A-Za-z0-9._-]*\.(?:png|jpe?g|gif|webp|avif|svg)$/;
43522
+ function staticImageLookup(options) {
43523
+ const lookup = /* @__PURE__ */ new Map();
43524
+ if (options.profile !== "inert" || options.imageAssets === void 0) return lookup;
43525
+ if (!Array.isArray(options.imageAssets) || options.imageAssets.length > MAX_STATIC_IMAGE_ASSETS) {
43526
+ throw new TypeError("static image asset inventory must be a bounded array");
43527
+ }
43528
+ for (const path6 of options.imageAssets) {
43529
+ if (typeof path6 !== "string" || path6.length > 2048 || path6.trim() !== path6 || !STATIC_IMAGE_PATH.test(path6)) {
43530
+ throw new TypeError("static image asset paths must be canonical local image paths");
43531
+ }
43532
+ lookup.set(path6, path6);
43533
+ }
43534
+ return lookup;
43535
+ }
43536
+ function textOf(root) {
43537
+ const parts = [];
43538
+ const pending = [root];
43539
+ while (pending.length > 0) {
43540
+ const node2 = pending.pop();
43541
+ if (node2.type === "text" || node2.type === "inlineCode" || node2.type === "html") {
43542
+ parts.push(node2.value ?? "");
43543
+ continue;
43544
+ }
43545
+ const children = node2.children;
43546
+ if (!Array.isArray(children)) continue;
43547
+ for (let i = children.length - 1; i >= 0; i--) pending.push(children[i]);
43235
43548
  }
43236
- const children = node2.children;
43237
- if (!Array.isArray(children)) return "";
43238
- return children.map((child) => textOf(child)).join("");
43549
+ return parts.join("");
43239
43550
  }
43240
43551
  function renderTextFallback(node2, index2) {
43241
43552
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "doc-markdown-fallback", children: textOf(node2) }, index2);
@@ -43288,16 +43599,19 @@ function admitFragment(raw) {
43288
43599
  }
43289
43600
  return fragment.length <= MAX_FRAGMENT_LENGTH && SAFE_FRAGMENT.test(fragment) ? fragment : null;
43290
43601
  }
43291
- function admitExternalLink(raw, hosts) {
43292
- if (!Array.isArray(hosts) || hosts.length === 0) return null;
43602
+ function admitExternalLink(raw, policy) {
43603
+ const anyHost = policy === "https";
43604
+ const hosts = typeof policy === "object" && policy !== null ? policy.hosts : void 0;
43605
+ if (!anyHost && (!Array.isArray(hosts) || hosts.length === 0)) return null;
43293
43606
  let url;
43294
43607
  try {
43295
43608
  url = new URL(raw);
43296
43609
  } catch {
43297
43610
  return null;
43298
43611
  }
43299
- if (url.protocol !== "https:" || url.username !== "" || url.password !== "" || url.port !== "") return null;
43300
- if (isIpLiteralHost(url.hostname)) return null;
43612
+ if (url.protocol !== "https:" || url.username !== "" || url.password !== "") return null;
43613
+ if (anyHost) return url.href;
43614
+ if (url.port !== "") return null;
43301
43615
  for (const entry of hosts) {
43302
43616
  if (normalizeAllowedHost(entry) === url.hostname) return url.href;
43303
43617
  }
@@ -43379,10 +43693,14 @@ function renderNode(node2, state, depth, index2) {
43379
43693
  case "link": {
43380
43694
  const raw = node2.url ?? "";
43381
43695
  const resolved = renderableConceptId(state.options.fromId, raw);
43696
+ const insideLink = state.insideLink;
43697
+ state.insideLink = true;
43382
43698
  const children = renderChildren(node2, state, depth);
43699
+ state.insideLink = insideLink;
43383
43700
  if (resolved === null) {
43384
- const external = admitExternalLink(raw, state.options.externalLinkHosts);
43385
- if (external !== null) {
43701
+ const hasContent = /\S/.test(textOf(node2)) || node2.children.some((child) => child.type === "image");
43702
+ const external = admitExternalLink(raw, state.options.externalLinks);
43703
+ if (external !== null && !insideLink && hasContent) {
43386
43704
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("a", { href: external, rel: "noopener noreferrer", target: "_blank", className: "doc-link-external", children }, index2);
43387
43705
  }
43388
43706
  const fragment = admitFragment(raw);
@@ -43410,7 +43728,21 @@ function renderNode(node2, state, depth, index2) {
43410
43728
  index2
43411
43729
  );
43412
43730
  }
43413
- case "image":
43731
+ case "image": {
43732
+ const source = state.imageAssets.get(node2.url ?? "");
43733
+ if (source !== void 0) {
43734
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
43735
+ "img",
43736
+ {
43737
+ src: source,
43738
+ alt: node2.alt ?? "",
43739
+ loading: "lazy",
43740
+ decoding: "async",
43741
+ referrerPolicy: "no-referrer"
43742
+ },
43743
+ index2
43744
+ );
43745
+ }
43414
43746
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
43415
43747
  "span",
43416
43748
  {
@@ -43424,6 +43756,7 @@ function renderNode(node2, state, depth, index2) {
43424
43756
  },
43425
43757
  index2
43426
43758
  );
43759
+ }
43427
43760
  case "table": {
43428
43761
  const align = node2.align ?? [];
43429
43762
  const rows = node2.children;
@@ -43489,11 +43822,15 @@ function renderMarkdown(body, options) {
43489
43822
  source = source.slice(0, maxBodyChars);
43490
43823
  bounded = true;
43491
43824
  }
43492
- const tree = fromMarkdown(source, {
43493
- extensions: [gfm()],
43494
- mdastExtensions: [gfmFromMarkdown()]
43495
- });
43496
- const state = { count: 0, bounded: false, options, maxNodes };
43825
+ const tree = parseWithinLimits(source);
43826
+ if (tree === null) {
43827
+ return {
43828
+ element: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("pre", { className: "doc-code doc-markdown-fallback", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("code", { children: source }) }),
43829
+ bounded: true,
43830
+ limits: { maxBodyChars, maxNodes }
43831
+ };
43832
+ }
43833
+ const state = { count: 0, bounded: false, insideLink: false, options, maxNodes, imageAssets: staticImageLookup(options) };
43497
43834
  const children = tree.children;
43498
43835
  const nodes = [];
43499
43836
  let i = 0;
@@ -43530,11 +43867,8 @@ function renderMarkdownToStaticHtml(body, options) {
43530
43867
  );
43531
43868
  return { html, bounded: rendered.bounded, limits: rendered.limits };
43532
43869
  }
43533
- function renderDocumentToStaticHtml(document3, options = {}) {
43534
- const rendered = renderMarkdownToStaticHtml(document3.body, {
43535
- fromId: document3.id,
43536
- externalLinkHosts: options.externalLinkHosts
43537
- });
43870
+ function renderDocumentToStaticHtml(document3) {
43871
+ const rendered = renderMarkdownToStaticHtml(document3.body, { fromId: document3.id });
43538
43872
  return { html: rendered.html, bounded: rendered.bounded };
43539
43873
  }
43540
43874
 
@@ -44432,6 +44766,17 @@ async function readInventory(backend, limits) {
44432
44766
  }
44433
44767
  return { documents, reserved, blobs };
44434
44768
  }
44769
+ function parseDocumentSource(bytes, id, okfEdition) {
44770
+ try {
44771
+ const raw = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
44772
+ return parseMarkdown(raw, `${id}.md`, { okfVersion: okfEdition });
44773
+ } catch (error) {
44774
+ throw new PublicationError("MALFORMED_DOCUMENT", "a publication document is malformed", {
44775
+ subject: id,
44776
+ cause: error
44777
+ });
44778
+ }
44779
+ }
44435
44780
  var SnapshotHandle = class {
44436
44781
  constructor(manifest, objects) {
44437
44782
  this.objects = objects;
@@ -44465,6 +44810,21 @@ var SnapshotHandle = class {
44465
44810
  }
44466
44811
  return bytes.slice();
44467
44812
  }
44813
+ async renderDocument(id, options = {}) {
44814
+ if (this.closed) throw new PublicationError("HANDLE_CLOSED", "the publication snapshot handle is closed");
44815
+ const row = this.manifest.documents.find((document3) => document3.id === id);
44816
+ if (!row) throw new PublicationError("OBJECT_MISSING", "the document is not part of this snapshot", { subject: id });
44817
+ const parsed = parseDocumentSource(await this.readObject(row.source), id, this.manifest.source.okfEdition);
44818
+ try {
44819
+ const rendered = renderMarkdownToStaticHtml(parsed.body, { fromId: id, externalLinks: options.externalLinks });
44820
+ return { html: rendered.html, bounded: rendered.bounded };
44821
+ } catch (error) {
44822
+ throw new PublicationError("RENDER_FAILED", "a publication document could not be rendered", {
44823
+ subject: id,
44824
+ cause: error
44825
+ });
44826
+ }
44827
+ }
44468
44828
  serializeManifest() {
44469
44829
  if (this.closed) throw new PublicationError("HANDLE_CLOSED", "the publication snapshot handle is closed");
44470
44830
  return this.serializedManifest.slice();
@@ -44528,16 +44888,7 @@ function buildSnapshot(first) {
44528
44888
  }
44529
44889
  }
44530
44890
  for (const row of first.documents) {
44531
- let parsed;
44532
- try {
44533
- const raw = new TextDecoder("utf-8", { fatal: true }).decode(row.bytes);
44534
- parsed = parseMarkdown(raw, `${row.id}.md`, { okfVersion: okfEdition });
44535
- } catch (error) {
44536
- throw new PublicationError("MALFORMED_DOCUMENT", "a publication document is malformed", {
44537
- subject: row.id,
44538
- cause: error
44539
- });
44540
- }
44891
+ const parsed = parseDocumentSource(row.bytes, row.id, okfEdition);
44541
44892
  if (typeof parsed.frontmatter.type !== "string" || !parsed.frontmatter.type.trim()) {
44542
44893
  throw new PublicationError("MALFORMED_DOCUMENT", "a publication document requires a non-empty type", {
44543
44894
  subject: row.id