@docs-sdk-dev/reader 0.0.0-stage → 0.4.0-next.0

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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +97 -2
  3. package/dist/annotation-projection.d.ts +35 -0
  4. package/dist/annotation-projection.js +78 -0
  5. package/dist/annotation-projection.js.map +1 -0
  6. package/dist/artifacts.d.ts +19 -0
  7. package/dist/artifacts.js +33 -0
  8. package/dist/artifacts.js.map +1 -0
  9. package/dist/ask.d.ts +41 -0
  10. package/dist/ask.js +89 -0
  11. package/dist/ask.js.map +1 -0
  12. package/dist/collection-view.d.ts +190 -0
  13. package/dist/collection-view.js +170 -0
  14. package/dist/collection-view.js.map +1 -0
  15. package/dist/composition.d.ts +199 -0
  16. package/dist/composition.js +473 -0
  17. package/dist/composition.js.map +1 -0
  18. package/dist/condition.d.ts +17 -0
  19. package/dist/condition.js +61 -0
  20. package/dist/condition.js.map +1 -0
  21. package/dist/content-schema.d.ts +182 -0
  22. package/dist/content-schema.js +288 -0
  23. package/dist/content-schema.js.map +1 -0
  24. package/dist/context-search.d.ts +168 -0
  25. package/dist/context-search.js +73 -0
  26. package/dist/context-search.js.map +1 -0
  27. package/dist/context-store.d.ts +93 -0
  28. package/dist/context-store.js +438 -0
  29. package/dist/context-store.js.map +1 -0
  30. package/dist/dimension-runtime.d.ts +203 -0
  31. package/dist/dimension-runtime.js +737 -0
  32. package/dist/dimension-runtime.js.map +1 -0
  33. package/dist/dimensions.d.ts +84 -0
  34. package/dist/dimensions.js +136 -0
  35. package/dist/dimensions.js.map +1 -0
  36. package/dist/directory-navigation.d.ts +60 -0
  37. package/dist/directory-navigation.js +41 -0
  38. package/dist/directory-navigation.js.map +1 -0
  39. package/dist/directory-sections.d.ts +9 -0
  40. package/dist/directory-sections.js +76 -0
  41. package/dist/directory-sections.js.map +1 -0
  42. package/dist/document-reader.d.ts +1017 -0
  43. package/dist/document-reader.js +396 -0
  44. package/dist/document-reader.js.map +1 -0
  45. package/dist/document-selection.d.ts +412 -0
  46. package/dist/document-selection.js +45 -0
  47. package/dist/document-selection.js.map +1 -0
  48. package/dist/evidence.d.ts +102 -0
  49. package/dist/evidence.js +104 -0
  50. package/dist/evidence.js.map +1 -0
  51. package/dist/index.d.ts +19 -0
  52. package/dist/index.js +23 -0
  53. package/dist/model.d.ts +89 -0
  54. package/dist/model.js +31 -0
  55. package/dist/model.js.map +1 -0
  56. package/dist/module.d.ts +657 -0
  57. package/dist/module.js +199 -0
  58. package/dist/module.js.map +1 -0
  59. package/dist/navigation-view.d.ts +33 -0
  60. package/dist/navigation-view.js +68 -0
  61. package/dist/navigation-view.js.map +1 -0
  62. package/dist/node.d.ts +2004 -0
  63. package/dist/node.js +210 -0
  64. package/dist/node.js.map +1 -0
  65. package/dist/open-docs.d.ts +1396 -0
  66. package/dist/open-docs.js +198 -0
  67. package/dist/open-docs.js.map +1 -0
  68. package/dist/outline.d.ts +97 -0
  69. package/dist/outline.js +171 -0
  70. package/dist/outline.js.map +1 -0
  71. package/dist/persistence.d.ts +82 -0
  72. package/dist/persistence.js +377 -0
  73. package/dist/persistence.js.map +1 -0
  74. package/dist/projection-catalog.d.ts +23 -0
  75. package/dist/projection-catalog.js +45 -0
  76. package/dist/projection-catalog.js.map +1 -0
  77. package/dist/publication.d.ts +59 -0
  78. package/dist/publication.js +11 -0
  79. package/dist/publication.js.map +1 -0
  80. package/dist/reader.d.ts +236 -0
  81. package/dist/reader.js +400 -0
  82. package/dist/reader.js.map +1 -0
  83. package/dist/references.d.ts +54 -0
  84. package/dist/references.js +70 -0
  85. package/dist/references.js.map +1 -0
  86. package/dist/retrieval.d.ts +82 -0
  87. package/dist/retrieval.js +135 -0
  88. package/dist/retrieval.js.map +1 -0
  89. package/dist/search-view.d.ts +11 -0
  90. package/dist/search-view.js +30 -0
  91. package/dist/search-view.js.map +1 -0
  92. package/dist/search.d.ts +95 -0
  93. package/dist/search.js +234 -0
  94. package/dist/search.js.map +1 -0
  95. package/dist/semantic.d.ts +177 -0
  96. package/dist/semantic.js +104 -0
  97. package/dist/semantic.js.map +1 -0
  98. package/dist/skills.d.ts +21 -0
  99. package/dist/skills.js +42 -0
  100. package/dist/skills.js.map +1 -0
  101. package/docs/index.md +10 -0
  102. package/docs/sdk/composition.md +72 -0
  103. package/docs/sdk/reader-storage.md +70 -0
  104. package/docs/sdk/reader.md +99 -0
  105. package/docs/zh-CN/sdk/composition.md +72 -0
  106. package/docs/zh-CN/sdk/reader-storage.md +70 -0
  107. package/docs/zh-CN/sdk/reader.md +99 -0
  108. package/package.json +69 -4
@@ -0,0 +1,737 @@
1
+ import { conditionReferences, matchesCondition } from "./condition.js";
2
+ import { createContextStore } from "./context-store.js";
3
+ import { createPersistenceRuntime } from "./persistence.js";
4
+ import { contextRestrictions, defineDimensions, dimensionValueIds, validatePublishedDimensions } from "./dimensions.js";
5
+ import { DocsError } from "./model.js";
6
+ import { canonicalJson, resolveContext } from "./semantic.js";
7
+
8
+ // src/dimension-runtime.ts
9
+ function ownerId(owner) {
10
+ if (owner.kind === "project") return "project";
11
+ return owner.kind === "scope" ? "scope:" + encodeURIComponent(owner.scope) : docKey(owner);
12
+ }
13
+ function docKey(identity) {
14
+ return "document:" + encodeURIComponent(identity.scope) + "/" + encodeURIComponent(identity.id);
15
+ }
16
+ function invalid(field, message) {
17
+ throw new DocsError("DOCS_DIMENSION_CONFLICT", message, { field });
18
+ }
19
+ function scopeKeys(scope) {
20
+ const keys = [];
21
+ do {
22
+ keys.push("scope:" + encodeURIComponent(scope));
23
+ scope = scope.substring(0, scope.lastIndexOf("/"));
24
+ } while (scope);
25
+ return keys;
26
+ }
27
+ function owners(identity) {
28
+ return [
29
+ "project",
30
+ ...scopeKeys(identity.scope),
31
+ docKey(identity)
32
+ ];
33
+ }
34
+ /** Select the most specific compatible published selector. Incomparable matches stay ambiguous. */
35
+ function resolveDocumentContext(editions, requested) {
36
+ const result = resolveContext(editions.map((document) => ({
37
+ context: document.identity.dimensions,
38
+ document
39
+ })), requested);
40
+ return result.status === "exact" ? {
41
+ status: "exact",
42
+ value: result.value.document
43
+ } : result;
44
+ }
45
+ function buildDimensionRegistry(documents, declarations, policy, validate) {
46
+ const byOwner = /* @__PURE__ */ new Map();
47
+ const declared = /* @__PURE__ */ new Map();
48
+ const discovered = /* @__PURE__ */ new Map();
49
+ let localeKey = "locale";
50
+ function add(owner, name, axis, source) {
51
+ const ownerKey = ownerId(owner);
52
+ if (ownerKey === "project" && axis.role === "locale") localeKey = name;
53
+ let map = byOwner.get(ownerKey);
54
+ if (!map) byOwner.set(ownerKey, map = /* @__PURE__ */ new Map());
55
+ const id = ownerKey + ":" + name;
56
+ const normalized = {
57
+ ...axis,
58
+ kind: axis.kind ?? "edition"
59
+ };
60
+ const signature = canonicalJson(normalized);
61
+ const previous = map.get(name);
62
+ if (previous) {
63
+ if (declared.get(id) !== signature) invalid(id, "Conflicting dimension declarations in " + [...previous.sources, source].sort().join(", "));
64
+ if (!previous.sources.includes(source)) previous.sources = [...previous.sources, source].sort();
65
+ return previous;
66
+ }
67
+ const definition = {
68
+ ...normalized,
69
+ owner,
70
+ id,
71
+ name,
72
+ values: dimensionValueIds(axis.values ?? []),
73
+ ...axis.values?.some((value) => typeof value !== "string" && value.when !== void 0) && { valueConditions: Object.fromEntries(axis.values.flatMap((value) => typeof value !== "string" && value.when !== void 0 ? [[value.id, value.when]] : [])) },
74
+ sources: [source]
75
+ };
76
+ declared.set(id, signature);
77
+ if (!axis.values) discovered.set(id, new Set([
78
+ axis.default,
79
+ axis.fallback,
80
+ ...(axis.defaults ?? []).map((rule) => rule.value)
81
+ ].filter((v) => v !== void 0)));
82
+ map.set(name, definition);
83
+ return definition;
84
+ }
85
+ for (const { owner, definitions, source } of declarations) {
86
+ validate?.(definitions);
87
+ for (const [name, axis] of Object.entries(definitions)) add(owner, name, axis, source);
88
+ }
89
+ const project = byOwner.get("project");
90
+ for (const [name, axis] of Object.entries(policy?.axes ?? {})) {
91
+ const existing = project?.get(name);
92
+ if (!existing) add({ kind: "project" }, name, axis, "editions.axes");
93
+ else if (declared.get(existing.id) !== canonicalJson({
94
+ ...axis,
95
+ kind: axis.kind ?? "edition"
96
+ })) invalid(existing.id, "Edition policy conflicts with project dimensions.");
97
+ }
98
+ for (const [name, def, values, fallback] of [[
99
+ localeKey,
100
+ policy?.defaultLocale,
101
+ policy?.locales,
102
+ policy?.fallbackToDefaultLocale ? policy.defaultLocale : void 0
103
+ ], ["version", policy?.defaultVersion]]) {
104
+ const axis = byOwner.get("project")?.get(name);
105
+ if (axis?.kind === "edition" && def !== void 0 && axis.default === void 0) {
106
+ const values = discovered.get(axis.id);
107
+ if (values) values.add(def);
108
+ else if (!axis.values.includes(def)) throw new DocsError("DOCS_PROJECT_INVALID", "Default edition is not offered.", { field: axis.id });
109
+ axis.default = def;
110
+ }
111
+ if ((def || values) && !axis) add({ kind: "project" }, name, {
112
+ default: def,
113
+ values,
114
+ fallback
115
+ }, "editions");
116
+ }
117
+ for (const map of byOwner.values()) for (const axis of map.values()) {
118
+ const parent = axis.owner.kind !== "project" && byOwner.get("project")?.get(axis.name) || axis.owner.kind === "document" && byOwner.get(ownerId({
119
+ kind: "scope",
120
+ scope: axis.owner.scope
121
+ }))?.get(axis.name);
122
+ if (parent) invalid(axis.id, "Dimension shadows inherited " + parent.id);
123
+ }
124
+ for (const { identity } of documents) {
125
+ const lineage = owners(identity).map((owner) => byOwner.get(owner));
126
+ for (const [name, value] of Object.entries(identity.dimensions)) {
127
+ const axis = lineage.find((map) => map?.has(name))?.get(name) ?? add({
128
+ kind: "document",
129
+ scope: identity.scope,
130
+ id: identity.id
131
+ }, name, {}, "edition identity");
132
+ if (axis.kind === "preference") invalid(axis.id, "A preference cannot be assigned in an edition identity.");
133
+ const values = discovered.get(axis.id);
134
+ if (values) values.add(value);
135
+ else if (!axis.values.includes(value)) throw new DocsError("DOCS_PROJECT_INVALID", "Edition assigns an undeclared value: " + value, { field: axis.id });
136
+ }
137
+ }
138
+ for (const map of byOwner.values()) for (const axis of map.values()) {
139
+ const values = discovered.get(axis.id);
140
+ if (values) axis.values = [...values].sort();
141
+ }
142
+ const axes = [...byOwner.values()].flatMap((map) => [...map.values()]);
143
+ const dependencies = /* @__PURE__ */ new Map();
144
+ const byName = new Set(axes.map((axis) => axis.name));
145
+ for (const axis of axes) {
146
+ const conditions = [
147
+ axis.when,
148
+ ...Object.values(axis.valueConditions ?? {}),
149
+ ...(axis.defaults ?? []).map((rule) => rule.when)
150
+ ];
151
+ if (conditions.every((condition) => condition === void 0)) continue;
152
+ const fail = (message) => {
153
+ throw new DocsError("DOCS_DIMENSION_CONDITION_INVALID", message, {
154
+ field: axis.id,
155
+ source: axis.sources.join(", ")
156
+ });
157
+ };
158
+ const accessible = axis.owner.kind === "project" ? ["project"] : axis.owner.kind === "scope" ? ["project", ...scopeKeys(axis.owner.scope)] : owners(axis.owner);
159
+ const refs = /* @__PURE__ */ new Set();
160
+ for (const condition of conditions) conditionReferences(condition, fail, (name, values) => {
161
+ const dependency = accessible.map((owner) => byOwner.get(owner)?.get(name)).find(Boolean);
162
+ if (!dependency) return fail(byName.has(name) ? "Dimension " + name + " is outside this scope." : "Unknown dimension " + name + ".");
163
+ if (dependency === axis) return fail("A dimension cannot depend on itself.");
164
+ for (const value of values) if (!dependency.values.includes(value)) return fail("Unknown value " + value + " for dimension " + name + ".");
165
+ refs.add(dependency);
166
+ });
167
+ axis.dependencies = [...refs].map(({ id }) => id);
168
+ dependencies.set(axis, [...refs]);
169
+ }
170
+ const ordered = [];
171
+ const complete = /* @__PURE__ */ new Set();
172
+ const visiting = /* @__PURE__ */ new Set();
173
+ function visit(axis) {
174
+ if (complete.has(axis)) return;
175
+ if (visiting.has(axis)) invalid(axis.id, "Dimension dependency cycle: " + [...visiting, axis].map(({ id }) => id).join(" → "));
176
+ visiting.add(axis);
177
+ for (const dependency of dependencies.get(axis) ?? []) visit(dependency);
178
+ visiting.delete(axis);
179
+ complete.add(axis);
180
+ ordered.push(axis);
181
+ }
182
+ for (const axis of axes) visit(axis);
183
+ const registry = dimensionView(documents, ordered, policy, memoizeAxisResolution(dependencies));
184
+ const policies = /* @__PURE__ */ new WeakMap();
185
+ function policyFor(identity) {
186
+ const axes = registry.definitions(identity);
187
+ let visiblePolicy = policies.get(axes);
188
+ if (!visiblePolicy) {
189
+ visiblePolicy = {
190
+ profiles: policy?.profiles,
191
+ compatibility: policy?.compatibility,
192
+ dimensions: Object.fromEntries(axes.map((axis) => [axis.name, axis]))
193
+ };
194
+ policies.set(axes, visiblePolicy);
195
+ }
196
+ return visiblePolicy;
197
+ }
198
+ const all = [...axes].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
199
+ return {
200
+ ...registry,
201
+ policyFor,
202
+ dependencies,
203
+ all,
204
+ graph: ordered
205
+ };
206
+ }
207
+ function evaluateAxis(axis, effective, desired, saved) {
208
+ if (!matchesCondition(axis.when, effective)) return;
209
+ const conditions = axis.valueConditions;
210
+ const choices = conditions ? axis.values.filter((value) => !Object.hasOwn(conditions, value) || matchesCondition(conditions[value], effective)) : axis.values;
211
+ const valid = (value) => value !== void 0 && (choices.includes(value) || !axis.values.length && !conditions);
212
+ const preferred = axis.defaults?.find(({ value, when }) => choices.includes(value) && matchesCondition(when, effective))?.value ?? axis.default;
213
+ return {
214
+ choices,
215
+ selected: valid(desired) ? desired : valid(saved) ? saved : valid(preferred) ? preferred : axis.kind === "preference" || axis.dependencies ? choices[0] : void 0
216
+ };
217
+ }
218
+ function memoizeAxisResolution(graph) {
219
+ const evaluations = /* @__PURE__ */ new WeakMap();
220
+ return (axis, context, desired, saved) => {
221
+ const dependencies = graph.get(axis);
222
+ if (!dependencies) return evaluateAxis(axis, context, desired, saved);
223
+ const inputs = [
224
+ desired,
225
+ saved,
226
+ ...dependencies.map(({ name }) => Object.hasOwn(context, name) ? context[name] : void 0)
227
+ ];
228
+ const cached = evaluations.get(axis);
229
+ if (cached && inputs.every((value, index) => value === cached.inputs[index])) return cached.result;
230
+ const result = evaluateAxis(axis, context, desired, saved);
231
+ evaluations.set(axis, {
232
+ inputs,
233
+ result
234
+ });
235
+ return result;
236
+ };
237
+ }
238
+ function dimensionView(documents, axes, policy, evaluate = evaluateAxis) {
239
+ const byOwner = /* @__PURE__ */ new Map();
240
+ for (const axis of axes) {
241
+ const key = ownerId(axis.owner);
242
+ let map = byOwner.get(key);
243
+ if (!map) byOwner.set(key, map = /* @__PURE__ */ new Map());
244
+ map.set(axis.name, axis);
245
+ }
246
+ const localeKey = axes.find(({ owner, role }) => owner.kind === "project" && role === "locale")?.name ?? "locale";
247
+ const groups = /* @__PURE__ */ new Map();
248
+ for (const page of documents) {
249
+ const key = docKey(page.identity);
250
+ const group = groups.get(key);
251
+ if (group) group.push(page);
252
+ else groups.set(key, [page]);
253
+ }
254
+ const visible = /* @__PURE__ */ new Map();
255
+ const ranks = new Map(policy?.order.map((name, index) => [name, index]));
256
+ const rank = (name) => ranks.get(name) ?? ranks.size;
257
+ function registryDefinitions(identity) {
258
+ const key = docKey(identity);
259
+ let axes = visible.get(key);
260
+ if (!axes) {
261
+ axes = owners(identity).flatMap((owner) => [...byOwner.get(owner)?.values() ?? []]).sort((a, b) => rank(a.name) - rank(b.name) || a.name.localeCompare(b.name, "en"));
262
+ if (groups.has(key) || byOwner.has(key) || key === "document:/") visible.set(key, axes);
263
+ }
264
+ return axes;
265
+ }
266
+ const rankInGraph = new Map(axes.map((axis, index) => [axis, index]));
267
+ const sequences = /* @__PURE__ */ new WeakMap();
268
+ function resolve(identity, requested, persisted = {}, fixed = {}, omitted) {
269
+ const definitions = registryDefinitions(identity);
270
+ if (!definitions.length) return {
271
+ effective: fixed,
272
+ available: {},
273
+ reasons: []
274
+ };
275
+ let sequence = sequences.get(definitions);
276
+ if (!sequence) {
277
+ sequence = [...definitions].sort((a, b) => rankInGraph.get(a) - rankInGraph.get(b));
278
+ sequences.set(definitions, sequence);
279
+ }
280
+ const effective = {};
281
+ const available = {};
282
+ Object.setPrototypeOf(available, null);
283
+ const reasons = [];
284
+ for (const axis of sequence) {
285
+ const { name } = axis;
286
+ if (omitted?.has(name)) continue;
287
+ const desired = Object.hasOwn(fixed, name) ? fixed[name] : Object.hasOwn(requested, name) ? requested[name] : void 0;
288
+ const result = evaluate(axis, effective, desired, Object.hasOwn(persisted, name) ? persisted[name] : void 0);
289
+ if (!result) continue;
290
+ available[name] = result.choices;
291
+ if (result.selected !== void 0) effective[name] = result.selected;
292
+ if (desired !== void 0 && !result.choices.includes(desired) && (axis.values.length || axis.valueConditions)) reasons.push({
293
+ key: name,
294
+ reason: axis.dependencies ? "conditional-value" : "value",
295
+ requested: desired,
296
+ resolved: result.selected
297
+ });
298
+ }
299
+ return {
300
+ effective,
301
+ available,
302
+ reasons
303
+ };
304
+ }
305
+ return {
306
+ localeKey,
307
+ definitions: registryDefinitions,
308
+ resolve,
309
+ editions: (identity) => groups.get(docKey(identity)) ?? []
310
+ };
311
+ }
312
+ /** Authoring ownership checks used before sealing a publication. */
313
+ function validateDimensionOwnership(registry) {
314
+ const { localeKey, all } = registry;
315
+ const declared = new Set(all.map((axis) => axis.id));
316
+ for (const axis of all) {
317
+ if (axis.owner.kind !== "project") for (const parent of scopeKeys(axis.owner.scope).slice(1)) {
318
+ const inherited = parent + ":" + axis.name;
319
+ if (declared.has(inherited)) invalid(axis.id, "Dimension shadows inherited " + inherited);
320
+ }
321
+ if (axis.kind === "preference") continue;
322
+ if (axis.role === "locale" && axis.name !== "locale" && axis.owner.kind !== "project") invalid(axis.id, "A renamed locale dimension must be declared at project level.");
323
+ if (localeKey !== "locale" && (axis.name === "locale" || axis.role === "locale" && axis.name !== localeKey)) invalid(axis.id, "Locale role conflicts with project:" + localeKey + ".");
324
+ }
325
+ }
326
+ function createDimensionRegistry(documents, declarations = [], policy) {
327
+ const registry = buildDimensionRegistry(documents, declarations, policy, defineDimensions);
328
+ validateDimensionOwnership(registry);
329
+ for (const page of documents) {
330
+ if (!page.availability) continue;
331
+ const definitions = registry.definitions(page.identity);
332
+ for (const [name, value] of Object.entries(page.availability)) {
333
+ const axis = definitions.find((axis) => axis.name === name);
334
+ if (axis?.kind !== "preference" || !axis.values.includes(value)) throw new DocsError("DOCS_PAGE_AVAILABILITY_INVALID", "Expected a declared preference Dimension value.", {
335
+ source: page.route,
336
+ field: "availability." + name
337
+ });
338
+ }
339
+ }
340
+ function projections(identity, keys, fixed, limit = 64) {
341
+ const closure = /* @__PURE__ */ new Set();
342
+ function include(axis) {
343
+ if (closure.has(axis)) return;
344
+ closure.add(axis);
345
+ for (const dependency of registry.dependencies.get(axis) ?? []) include(dependency);
346
+ }
347
+ for (const axis of registry.definitions(identity)) if (keys.has(axis.name)) include(axis);
348
+ const required = registry.graph.filter((axis) => closure.has(axis));
349
+ const contexts = /* @__PURE__ */ new Map();
350
+ const pick = (effective) => Object.fromEntries(Object.entries(effective).filter(([name]) => keys.has(name)));
351
+ const current = pick(registry.resolve(identity, {}, {}, fixed).effective);
352
+ function visit(index, requested) {
353
+ const state = registry.resolve(identity, requested, {}, fixed);
354
+ const axis = required[index];
355
+ if (!axis) {
356
+ const context = pick(state.effective);
357
+ const key = canonicalJson(context);
358
+ if (!contexts.has(key)) {
359
+ if (contexts.size >= limit) throw new DocsError("DOCS_CONTEXT_CONTENT_INVALID", "A page can publish up to " + limit + " reading contexts.", { document: identity.scope + "/" + identity.id });
360
+ contexts.set(key, requested);
361
+ }
362
+ return;
363
+ }
364
+ const values = !Object.hasOwn(fixed, axis.name) ? state.available[axis.name] : void 0;
365
+ if (!values?.length) visit(index + 1, requested);
366
+ else for (const value of values) visit(index + 1, {
367
+ ...requested,
368
+ [axis.name]: value
369
+ });
370
+ }
371
+ visit(0, {});
372
+ return {
373
+ current,
374
+ variants: [...contexts.values()].flatMap((requested) => {
375
+ const context = pick(registry.resolve(identity, requested, {}, fixed).effective);
376
+ return canonicalJson(context) === canonicalJson(current) ? [] : [{
377
+ context,
378
+ requested
379
+ }];
380
+ })
381
+ };
382
+ }
383
+ return {
384
+ ...registry,
385
+ projections
386
+ };
387
+ }
388
+ function buildDimensionInspector(publication, registry) {
389
+ const policy = publication.dimensionPolicy;
390
+ const rules = policy ?? {};
391
+ function inspect(identity, input = {}) {
392
+ const definitions = registry.definitions(identity);
393
+ const pages = registry.editions(identity);
394
+ const conditional = definitions.some((axis) => axis.when || axis.valueConditions || axis.defaults);
395
+ const requested = input.requested ?? {};
396
+ const edition = input.edition && Object.entries(input.locked ?? {}).every(([name, value]) => !Object.hasOwn(input.edition, name) || input.edition[name] === value) ? input.edition : void 0;
397
+ const pinned = edition === void 0 ? void 0 : pages.find(({ identity }) => identity.dimensions === edition || Object.keys(identity.dimensions).length === Object.keys(edition).length && matchesCondition(identity.dimensions, edition));
398
+ const placement = (document) => document && Object.hasOwn(publication.dimensionPlacements ?? {}, document.route) ? publication.dimensionPlacements?.[document.route] : void 0;
399
+ const evaluate = (page, assumed = page?.identity.dimensions) => registry.resolve(identity, requested, input.persisted, {
400
+ ...placement(page),
401
+ ...assumed,
402
+ ...input.locked
403
+ });
404
+ const fixed = {
405
+ ...placement(pinned),
406
+ ...edition,
407
+ ...input.locked
408
+ };
409
+ const resolvedRequest = evaluate(pinned, edition);
410
+ let { effective, available } = resolvedRequest;
411
+ const { reasons } = resolvedRequest;
412
+ const active = definitions.filter((axis) => Object.hasOwn(available, axis.name));
413
+ if (rules.compatibility?.length || rules.profiles) {
414
+ const compatibilityInput = {
415
+ ...effective,
416
+ ...Object.fromEntries(reasons.flatMap(({ key, reason, requested }) => reason === "value" && requested !== void 0 ? [[key, requested]] : []))
417
+ };
418
+ reasons.push(...contextRestrictions(rules, compatibilityInput).map(({ key, reason, value }) => ({
419
+ key,
420
+ reason,
421
+ requested: value
422
+ })));
423
+ }
424
+ const base = {
425
+ requested,
426
+ ...input.persisted && { persisted: input.persisted },
427
+ effective,
428
+ definitions,
429
+ active,
430
+ available,
431
+ resolved: {},
432
+ availability: pages.map((page) => ({
433
+ route: page.route,
434
+ dimensions: page.identity.dimensions,
435
+ ...page.availability && { requires: page.availability }
436
+ })),
437
+ reasons
438
+ };
439
+ if (!pages.length) return {
440
+ ...base,
441
+ status: "not-found"
442
+ };
443
+ const assigned = (document, status) => {
444
+ const selected = edition !== void 0 ? {
445
+ effective,
446
+ available
447
+ } : evaluate(document);
448
+ const resolved = {};
449
+ const active = [];
450
+ for (const axis of definitions) {
451
+ if (Object.hasOwn(selected.available, axis.name)) active.push(axis);
452
+ if ((axis.kind === "preference" || Object.hasOwn(document.identity.dimensions, axis.name)) && Object.hasOwn(selected.effective, axis.name)) resolved[axis.name] = selected.effective[axis.name];
453
+ }
454
+ return {
455
+ ...base,
456
+ effective: status === "fallback" && !conditional ? effective : selected.effective,
457
+ available: selected.available,
458
+ active,
459
+ status,
460
+ document,
461
+ resolved
462
+ };
463
+ };
464
+ function unavailable(choices) {
465
+ const alternate = choices[0]?.availability;
466
+ for (const [key, value] of Object.entries(alternate ?? {})) if (effective[key] !== value) reasons.push({
467
+ key,
468
+ reason: "availability",
469
+ requested: effective[key],
470
+ resolved: value
471
+ });
472
+ return {
473
+ ...base,
474
+ status: "unavailable"
475
+ };
476
+ }
477
+ if (edition !== void 0) {
478
+ const selected = pinned;
479
+ if (!selected || Object.entries(edition).some(([name, value]) => effective[name] !== value)) return {
480
+ ...base,
481
+ status: "unavailable"
482
+ };
483
+ const rejected = new Set(reasons.flatMap(({ key, reason }) => (reason === "compatibility" || reason === "profile") && definitions.find((axis) => axis.name === key)?.kind === "preference" ? [key] : []));
484
+ if (rejected.size) {
485
+ const safe = registry.resolve(identity, requested, input.persisted, fixed, rejected);
486
+ const defaults = {};
487
+ for (const axis of definitions) {
488
+ if (!rejected.has(axis.name)) continue;
489
+ const candidate = axis.default;
490
+ if (candidate !== void 0 && contextRestrictions(rules, {
491
+ ...safe.effective,
492
+ ...defaults,
493
+ [axis.name]: candidate
494
+ }).length === 0) {
495
+ rejected.delete(axis.name);
496
+ defaults[axis.name] = candidate;
497
+ }
498
+ }
499
+ const corrected = registry.resolve(identity, requested, input.persisted, {
500
+ ...defaults,
501
+ ...fixed
502
+ }, rejected);
503
+ effective = corrected.effective;
504
+ available = corrected.available;
505
+ for (const reason of reasons) if (Object.hasOwn(effective, reason.key)) reason.resolved = effective[reason.key];
506
+ Object.assign(base, {
507
+ effective,
508
+ available,
509
+ active: definitions.filter((axis) => Object.hasOwn(available, axis.name))
510
+ });
511
+ }
512
+ for (const [key, value] of Object.entries(edition)) if (Object.hasOwn(requested, key) && requested[key] !== value) reasons.push({
513
+ key,
514
+ requested: requested[key],
515
+ resolved: value,
516
+ reason: "explicit-edition"
517
+ });
518
+ return matchesCondition(selected.availability, effective) ? assigned(selected, "exact") : unavailable([selected]);
519
+ }
520
+ if (reasons.some(({ key, reason }) => reason !== "conditional-value" && (reason !== "value" || definitions.find((axis) => axis.name === key)?.kind !== "preference"))) return {
521
+ ...base,
522
+ status: "unavailable"
523
+ };
524
+ const eligible = pages.filter((page) => {
525
+ if (!placement(page) && !conditional) return matchesCondition(page.availability, effective);
526
+ const candidate = evaluate(page).effective;
527
+ return matchesCondition(page.identity.dimensions, candidate) && matchesCondition(page.availability, candidate);
528
+ });
529
+ const strict = resolveDocumentContext(eligible, effective);
530
+ if (strict.status === "ambiguous") return {
531
+ ...base,
532
+ status: "ambiguous",
533
+ candidates: strict.candidates
534
+ };
535
+ if (strict.status === "exact") {
536
+ const shared = definitions.some((axis) => axis.kind === "edition" && Object.hasOwn(effective, axis.name) && !Object.hasOwn(strict.value.identity.dimensions, axis.name));
537
+ return assigned(strict.value, shared ? "compatible" : "exact");
538
+ }
539
+ let best = 1e400;
540
+ let matches = [];
541
+ candidate: for (const page of eligible) {
542
+ let cost = 0;
543
+ for (const [name, value] of Object.entries(page.identity.dimensions)) {
544
+ if (!Object.hasOwn(effective, name) || effective[name] === value) continue;
545
+ if (value !== (definitions.find((axis) => axis.name === name)?.fallback ?? (name === registry.localeKey && policy?.fallbackToDefaultLocale ? policy.defaultLocale : void 0))) continue candidate;
546
+ cost++;
547
+ }
548
+ if (cost > best) continue;
549
+ const candidate = evaluate(page).effective;
550
+ if (Object.entries(page.identity.dimensions).some(([key, value]) => candidate[key] !== value) || !matchesCondition(page.availability, candidate) || contextRestrictions(rules, candidate).length > 0) continue;
551
+ if (cost < best) {
552
+ matches = [];
553
+ best = cost;
554
+ }
555
+ matches.push(page);
556
+ }
557
+ if (matches.length > 1) {
558
+ const corrections = matches.map((page) => Object.fromEntries(Object.entries(page.identity.dimensions).filter(([key, value]) => effective[key] !== value)));
559
+ const common = canonicalJson(corrections[0]);
560
+ if (corrections.every((change) => canonicalJson(change) === common)) {
561
+ const best = resolveDocumentContext(matches, {
562
+ ...effective,
563
+ ...corrections[0]
564
+ });
565
+ if (best.status === "exact") matches = [best.value];
566
+ else if (best.status === "ambiguous") return {
567
+ ...base,
568
+ status: "ambiguous",
569
+ candidates: best.candidates
570
+ };
571
+ }
572
+ if (matches.length > 1) return {
573
+ ...base,
574
+ status: "ambiguous",
575
+ candidates: matches.map((page) => page.identity.dimensions)
576
+ };
577
+ }
578
+ const document = matches[0];
579
+ if (!document) return unavailable(eligible.length ? [] : pages);
580
+ for (const [key, value] of Object.entries(document.identity.dimensions)) if (Object.hasOwn(effective, key) && effective[key] !== value) reasons.push({
581
+ key,
582
+ reason: "fallback",
583
+ requested: effective[key],
584
+ resolved: value
585
+ });
586
+ return assigned(document, best ? "fallback" : "compatible");
587
+ }
588
+ return {
589
+ registry,
590
+ inspect,
591
+ includesEdition(page, requested) {
592
+ const { identity } = page;
593
+ return !registry.definitions(identity).some((axis) => Object.hasOwn(identity.dimensions, axis.name) && (axis.when || axis.valueConditions)) || !!inspect(identity, {
594
+ edition: identity.dimensions,
595
+ requested
596
+ }).document;
597
+ }
598
+ };
599
+ }
600
+ /** Read-only context inspection also serves pinned hosts that do not own any mutable selection state. */
601
+ function createDimensionInspector(publication) {
602
+ return buildDimensionInspector(publication, buildDimensionRegistry(publication.documents, publication.dimensionDeclarations ?? [], publication.dimensionPolicy, validatePublishedDimensions));
603
+ }
604
+ /** A pinned manifest carries the definitions resolved by its verified producer. */
605
+ function inspectPinnedDimensions(publication) {
606
+ const { documents, dimensionGraph, dimensionPolicy } = publication;
607
+ return buildDimensionInspector(publication, dimensionView(documents, dimensionGraph ?? [], dimensionPolicy));
608
+ }
609
+ /** Address a Context key explicitly bound to this Dimension's semantic selection. */
610
+ function dimensionPersistenceBinding(axis) {
611
+ const { owner } = axis;
612
+ return {
613
+ id: axis.id,
614
+ scope: owner.kind,
615
+ policy: axis.persistence,
616
+ identity: owner.kind === "project" ? void 0 : {
617
+ scope: owner.scope,
618
+ ...owner.kind === "document" && { document: {
619
+ scope: owner.scope,
620
+ id: owner.id
621
+ } }
622
+ }
623
+ };
624
+ }
625
+ function createDimensionRuntime(publication, options = {}) {
626
+ const reader = buildDimensionInspector(publication, buildDimensionRegistry(publication.documents, publication.dimensionDeclarations ?? [], publication.dimensionPolicy, defineDimensions));
627
+ const { registry } = reader;
628
+ validateDimensionOwnership(registry);
629
+ const selectable = registry.all.filter((axis) => axis.values.length);
630
+ const axes = new Map(selectable.map((axis) => [axis.id, axis]));
631
+ const persistence = options.persistence ?? createPersistenceRuntime({ projectId: "dimensions" });
632
+ const bindings = Object.fromEntries(selectable.map((axis) => [axis.id, dimensionPersistenceBinding(axis)]));
633
+ const selections = createContextStore(selectable.map((axis) => ({
634
+ id: axis.id,
635
+ default: axis.default ?? axis.values[0],
636
+ values: axis.values,
637
+ persistence: axis.persistence
638
+ })), {
639
+ bindings,
640
+ persistence
641
+ });
642
+ const listeners = /* @__PURE__ */ new Set();
643
+ let revision = 0;
644
+ selections.subscribeResolution(selectable.map((axis) => axis.id), () => {
645
+ revision++;
646
+ for (const listener of [...listeners]) listener();
647
+ });
648
+ function inspect(identity, input = {}) {
649
+ const definitions = registry.definitions(identity);
650
+ const requested = {
651
+ ...Object.fromEntries(definitions.flatMap((axis) => {
652
+ const value = axes.has(axis.id) ? selections.resolution(axis.id).requested : void 0;
653
+ return typeof value === "string" ? [[axis.name, value]] : [];
654
+ })),
655
+ ...input.requested
656
+ };
657
+ const persisted = Object.fromEntries(definitions.flatMap((axis) => {
658
+ const value = axes.has(axis.id) ? selections.resolution(axis.id).persisted : void 0;
659
+ return typeof value === "string" ? [[axis.name, value]] : [];
660
+ }));
661
+ return {
662
+ ...reader.inspect(identity, {
663
+ ...input,
664
+ requested,
665
+ persisted
666
+ }),
667
+ persisted
668
+ };
669
+ }
670
+ function validateSelection(identity, name, value, input = {}) {
671
+ const axis = registry.definitions(identity).find((axis) => axis.name === name);
672
+ if (input.locked && Object.hasOwn(input.locked, name)) throw new DocsError("DOCS_CONTEXT_READ_ONLY", "Dimension is locked.", { field: name });
673
+ if (!axis || value !== void 0 && !axis.values.includes(value)) throw new DocsError("DOCS_CONTEXT_UNAVAILABLE", "Unknown dimension or value for this document.", { field: name });
674
+ if (value !== void 0) {
675
+ const next = inspect(identity, {
676
+ ...input,
677
+ ...axis.kind === "edition" && { edition: void 0 },
678
+ requested: {
679
+ ...input.requested,
680
+ [name]: value
681
+ }
682
+ });
683
+ if (!next.available[name]?.includes(value) || next.reasons.some(({ key, reason }) => key === name && (reason === "value" || reason === "compatibility" || reason === "profile"))) throw new DocsError("DOCS_CONTEXT_UNAVAILABLE", "Incompatible dimension selection.", { field: name });
684
+ }
685
+ return axis;
686
+ }
687
+ return {
688
+ registry,
689
+ inspect,
690
+ includesEdition: reader.includesEdition,
691
+ revision: () => revision,
692
+ dispose() {
693
+ selections.dispose();
694
+ if (!options.persistence) persistence.dispose();
695
+ listeners.clear();
696
+ },
697
+ subscribe(listener) {
698
+ listeners.add(listener);
699
+ return () => {
700
+ listeners.delete(listener);
701
+ };
702
+ },
703
+ validateSelection,
704
+ select(identity, name, value, input = {}) {
705
+ const axis = validateSelection(identity, name, value, input);
706
+ if (!axes.has(axis.id)) return;
707
+ if (value === void 0) selections.reset(axis.id);
708
+ else selections.set(axis.id, value);
709
+ },
710
+ choices(identity, name, input = {}) {
711
+ const state = inspect(identity, input);
712
+ const axis = state.definitions.find((axis) => axis.name === name);
713
+ return (state.available[name] ?? []).map((value) => {
714
+ const next = inspect(identity, {
715
+ ...input,
716
+ ...axis?.kind === "edition" && { edition: void 0 },
717
+ requested: {
718
+ ...input.requested,
719
+ [name]: value
720
+ }
721
+ });
722
+ const available = (!input.locked || !Object.hasOwn(input.locked, name) || input.locked[name] === value) && (axis?.kind === "preference" ? next.effective[name] === value && (!!next.document || next.reasons.some(({ reason }) => reason === "availability")) : !!next.document && next.resolved[name] === value);
723
+ return {
724
+ value,
725
+ current: (state.resolved[name] ?? state.effective[name]) === value,
726
+ requested: state.requested[name] === value,
727
+ available,
728
+ route: next.document?.route,
729
+ reasons: next.reasons
730
+ };
731
+ });
732
+ }
733
+ };
734
+ }
735
+
736
+ export { createDimensionInspector, createDimensionRegistry, createDimensionRuntime, dimensionPersistenceBinding, inspectPinnedDimensions, resolveDocumentContext };
737
+ //# sourceMappingURL=dimension-runtime.js.map