@tokenoftrust/storefront-runner 6.15.3 → 6.15.4

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.15.3",
3
+ "version": "6.15.4",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",
@@ -11,6 +11,7 @@
11
11
  ".": "./src/index.ts",
12
12
  "./v1": "./src/v1/index.ts",
13
13
  "./tour": "./src/tour/index.ts",
14
+ "./tour/resolve": "./src/tour/resolve/index.ts",
14
15
  "./primitives": "./src/primitives/index.ts"
15
16
  },
16
17
  "files": [
@@ -0,0 +1,267 @@
1
+ import type { FeedbackTarget, PathSegment, Rect } from "../../v1/types.js";
2
+ import type { ViewportBand } from "../schema.js";
3
+
4
+ /** CSS px thresholds: narrow < 600, medium 600-1023, wide >= 1024. */
5
+ export function bandOf(width: number): ViewportBand {
6
+ if (width < 600) return "narrow";
7
+ if (width < 1024) return "medium";
8
+ return "wide";
9
+ }
10
+
11
+ export const DRIFT_EVALUATION_LIMIT = 64;
12
+ export const SETTLE_WINDOW_MS = 1500;
13
+ export const GEOMETRY_AGREEMENT_FLOOR = 0.1;
14
+ const MAX_TOTAL_OFFSET = 3;
15
+
16
+ export type MatchKind = "exact" | "drifted" | "host" | "region" | "page";
17
+
18
+ export type TargetResolution =
19
+ | { state: "resolved"; match: MatchKind; rect: Rect; fallback?: true }
20
+ | { state: "ambiguous"; reason: "drift-tie" | "geometry-disagrees"; candidates: number }
21
+ | { state: "absent"; reason: "path-miss" | "hidden" | "viewport-band" | "host-mismatch" | "timeout" };
22
+
23
+ /** What the resolver may ask of a document. Nothing here can change the document. */
24
+ export interface TreeAccess<N> {
25
+ root(): N;
26
+ /** The element child at `index`, or null. */
27
+ child(node: N, index: number): N | null;
28
+ tag(node: N): string;
29
+ isHost(node: N): boolean;
30
+ /** Zero area, display:none, visibility:hidden, or an inert / aria-hidden ancestor. */
31
+ hidden(node: N): boolean;
32
+ /** Page coordinates. */
33
+ rect(node: N): Rect;
34
+ }
35
+
36
+ export interface ViewportInfo {
37
+ width: number;
38
+ height: number;
39
+ }
40
+
41
+ export interface AuthoredViewport extends ViewportInfo {
42
+ scrollX: number;
43
+ scrollY: number;
44
+ }
45
+
46
+ export interface Candidate<N> {
47
+ node: N;
48
+ exact: boolean;
49
+ /** Total childIndex offset from the authored path. */
50
+ offset: number;
51
+ }
52
+
53
+ export interface ResolveOutcome<N> {
54
+ resolution: TargetResolution;
55
+ node: N | null;
56
+ }
57
+
58
+ /** The target a step uses in `band`, or null when the step hides in that band. */
59
+ export function pickBandTarget(
60
+ step: { target?: FeedbackTarget; bandTargets?: Partial<Record<ViewportBand, FeedbackTarget>>; hideIn?: ViewportBand[] },
61
+ band: ViewportBand,
62
+ ): FeedbackTarget | null | undefined {
63
+ if (step.hideIn?.includes(band)) return null;
64
+ return step.bandTargets?.[band] ?? step.target;
65
+ }
66
+
67
+ function walk<N>(tree: TreeAccess<N>, path: readonly PathSegment[], indexes: readonly number[]): N | null {
68
+ let node = tree.root();
69
+ for (let i = 0; i < path.length; i += 1) {
70
+ const index = indexes[i];
71
+ const want = path[i];
72
+ if (index === undefined || want === undefined) return null;
73
+ const next = tree.child(node, index);
74
+ if (next === null || tree.tag(next) !== want.tag) return null;
75
+ node = next;
76
+ }
77
+ return node;
78
+ }
79
+
80
+ /**
81
+ * Index alternatives that change at most two segments by a total of at most three, cheapest
82
+ * first. The order depends only on the path's length, never on the document.
83
+ */
84
+ export function* driftAlternatives(length: number): Generator<{ changes: Array<[number, number]>; cost: number }> {
85
+ for (let cost = 1; cost <= MAX_TOTAL_OFFSET; cost += 1) {
86
+ for (let i = 0; i < length; i += 1) {
87
+ for (const sign of [-1, 1]) yield { changes: [[i, sign * cost]], cost };
88
+ }
89
+ for (let i = 0; i < length; i += 1) {
90
+ for (let j = i + 1; j < length; j += 1) {
91
+ for (let di = 1; di < cost; di += 1) {
92
+ for (const si of [-1, 1]) {
93
+ for (const sj of [-1, 1]) {
94
+ yield { changes: [[i, si * di], [j, sj * (cost - di)]], cost };
95
+ }
96
+ }
97
+ }
98
+ }
99
+ }
100
+ }
101
+ }
102
+
103
+ export function iou(a: Rect, b: Rect): number {
104
+ const w = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x);
105
+ const h = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y);
106
+ if (w <= 0 || h <= 0) return 0;
107
+ const inter = w * h;
108
+ const union = a.width * a.height + b.width * b.height - inter;
109
+ return union <= 0 ? 0 : inter / union;
110
+ }
111
+
112
+ export interface FindResult<N> {
113
+ candidates: Array<Candidate<N>>;
114
+ evaluations: number;
115
+ }
116
+
117
+ /** Exact walk, then the bounded drift search when the walk fails. */
118
+ export function findCandidates<N>(tree: TreeAccess<N>, path: readonly PathSegment[]): FindResult<N> {
119
+ const base = path.map((s) => s.childIndex);
120
+ const exact = walk(tree, path, base);
121
+ if (exact !== null) return { candidates: [{ node: exact, exact: true, offset: 0 }], evaluations: 1 };
122
+ const candidates: Array<Candidate<N>> = [];
123
+ let evaluations = 1;
124
+ for (const alt of driftAlternatives(path.length)) {
125
+ if (evaluations >= DRIFT_EVALUATION_LIMIT) break;
126
+ const indexes = base.slice();
127
+ let valid = true;
128
+ for (const [at, delta] of alt.changes) {
129
+ const moved = (indexes[at] ?? -1) + delta;
130
+ indexes[at] = moved;
131
+ if (moved < 0) valid = false;
132
+ }
133
+ if (!valid) continue;
134
+ evaluations += 1;
135
+ const node = walk(tree, path, indexes);
136
+ if (node !== null) candidates.push({ node, exact: false, offset: alt.cost });
137
+ }
138
+ return { candidates, evaluations };
139
+ }
140
+
141
+ export interface RankContext<N> {
142
+ /** Set only when key 3 applies: the authored bounds in page coordinates. */
143
+ authoredRect: Rect | null;
144
+ tree: TreeAccess<N>;
145
+ }
146
+
147
+ type Ranked<N> = { candidate: Candidate<N>; iou: number | null };
148
+
149
+ function compare<N>(a: Ranked<N>, b: Ranked<N>): number {
150
+ if (a.candidate.exact !== b.candidate.exact) return a.candidate.exact ? -1 : 1;
151
+ if (a.candidate.offset !== b.candidate.offset) return a.candidate.offset - b.candidate.offset;
152
+ if (a.iou !== null && b.iou !== null && a.iou !== b.iou) return b.iou - a.iou;
153
+ return 0;
154
+ }
155
+
156
+ /** The best candidates under the tie-break keys. More than one means a tie after key 3. */
157
+ export function rank<N>(candidates: ReadonlyArray<Candidate<N>>, ctx: RankContext<N>): Array<Ranked<N>> {
158
+ const scored: Array<Ranked<N>> = candidates.map((candidate) => ({
159
+ candidate,
160
+ iou: ctx.authoredRect ? iou(ctx.tree.rect(candidate.node), ctx.authoredRect) : null,
161
+ }));
162
+ scored.sort(compare);
163
+ const best = scored[0];
164
+ return best ? scored.filter((s) => compare(best, s) === 0) : [];
165
+ }
166
+
167
+ function authoredPageRect(t: FeedbackTarget, authored: AuthoredViewport | undefined, viewport: ViewportInfo): Rect | null {
168
+ if (!t.bounds || !authored) return null;
169
+ if (bandOf(viewport.width) !== bandOf(authored.width)) return null;
170
+ return { x: t.bounds.x + authored.scrollX, y: t.bounds.y + authored.scrollY, width: t.bounds.width, height: t.bounds.height };
171
+ }
172
+
173
+ function project(container: Rect, rel: Rect): Rect {
174
+ return {
175
+ x: container.x + rel.x * container.width,
176
+ y: container.y + rel.y * container.height,
177
+ width: rel.width * container.width,
178
+ height: rel.height * container.height,
179
+ };
180
+ }
181
+
182
+ const absent = <N>(reason: Extract<TargetResolution, { state: "absent" }>["reason"]): ResolveOutcome<N> => ({
183
+ resolution: { state: "absent", reason },
184
+ node: null,
185
+ });
186
+
187
+ /** Steps 3-5 and 7: locate the element a structural path names. */
188
+ function locate<N>(
189
+ t: FeedbackTarget,
190
+ tree: TreeAccess<N>,
191
+ viewport: ViewportInfo,
192
+ authored: AuthoredViewport | undefined,
193
+ ): { node: N; match: "exact" | "drifted" | "host" } | Extract<TargetResolution, { state: "ambiguous" | "absent" }> {
194
+ const path = t.structuralPath;
195
+ if (!path || path.length === 0) return { state: "absent", reason: "path-miss" };
196
+ const { candidates } = findCandidates(tree, path);
197
+ if (candidates.length === 0) return { state: "absent", reason: "path-miss" };
198
+
199
+ const visible = candidates.filter((c) => !tree.hidden(c.node));
200
+ if (visible.length === 0) return { state: "absent", reason: "hidden" };
201
+
202
+ const authoredRect = authoredPageRect(t, authored, viewport);
203
+ const best = rank(visible, { authoredRect, tree });
204
+ if (best.length > 1) return { state: "ambiguous", reason: "drift-tie", candidates: best.length };
205
+ const winner = best[0];
206
+ if (winner === undefined) return { state: "absent", reason: "path-miss" };
207
+ if (
208
+ visible.length === 1 &&
209
+ !winner.candidate.exact &&
210
+ winner.iou !== null &&
211
+ winner.iou < GEOMETRY_AGREEMENT_FLOOR
212
+ ) {
213
+ return { state: "ambiguous", reason: "geometry-disagrees", candidates: 1 };
214
+ }
215
+ const node = winner.candidate.node;
216
+ if (t.precision === "host") {
217
+ if (!tree.isHost(node)) return { state: "absent", reason: "host-mismatch" };
218
+ return { node, match: "host" };
219
+ }
220
+ return { node, match: winner.candidate.exact ? "exact" : "drifted" };
221
+ }
222
+
223
+ export function resolveTarget<N>(
224
+ t: FeedbackTarget,
225
+ tree: TreeAccess<N>,
226
+ viewport: ViewportInfo,
227
+ authored?: AuthoredViewport,
228
+ ): ResolveOutcome<N> {
229
+ if (t.kind === "page") {
230
+ return { resolution: { state: "resolved", match: "page", rect: { x: 0, y: 0, width: viewport.width, height: viewport.height } }, node: null };
231
+ }
232
+ if (t.kind === "region") {
233
+ if (!t.structuralPath || t.structuralPath.length === 0) {
234
+ const rect = authoredPageRect(t, authored, viewport);
235
+ if (!rect) return absent(t.bounds ? "viewport-band" : "path-miss");
236
+ return { resolution: { state: "resolved", match: "region", rect }, node: null };
237
+ }
238
+ const found = locate({ ...t, precision: "structure" }, tree, viewport, authored);
239
+ if ("state" in found) return { resolution: found, node: null };
240
+ const container = tree.rect(found.node);
241
+ const rect = t.relativeRegion ? project(container, t.relativeRegion) : container;
242
+ return { resolution: { state: "resolved", match: "region", rect }, node: found.node };
243
+ }
244
+ const found = locate(t, tree, viewport, authored);
245
+ if ("state" in found) return { resolution: found, node: null };
246
+ return { resolution: { state: "resolved", match: found.match, rect: tree.rect(found.node) }, node: found.node };
247
+ }
248
+
249
+ /**
250
+ * `onUnresolved: "region"`: the target's own region data. `relativeRegion` on a resolved
251
+ * container, else `bounds` in the authored band. Null when neither resolves.
252
+ */
253
+ export function resolveRegionFallback<N>(
254
+ t: FeedbackTarget,
255
+ tree: TreeAccess<N>,
256
+ viewport: ViewportInfo,
257
+ authored?: AuthoredViewport,
258
+ ): Extract<TargetResolution, { state: "resolved" }> | null {
259
+ if (t.relativeRegion && t.structuralPath && t.structuralPath.length > 0) {
260
+ const found = locate({ ...t, precision: "structure" }, tree, viewport, authored);
261
+ if (!("state" in found)) {
262
+ return { state: "resolved", match: "region", rect: project(tree.rect(found.node), t.relativeRegion), fallback: true };
263
+ }
264
+ }
265
+ const rect = authoredPageRect(t, authored, viewport);
266
+ return rect ? { state: "resolved", match: "region", rect, fallback: true } : null;
267
+ }
@@ -0,0 +1,115 @@
1
+ import { isHostBoundary, safeRect } from "../../primitives/target.js";
2
+ import type { FeedbackTarget, Rect } from "../../v1/types.js";
3
+ import {
4
+ SETTLE_WINDOW_MS,
5
+ resolveRegionFallback,
6
+ resolveTarget,
7
+ type AuthoredViewport,
8
+ type TargetResolution,
9
+ type TreeAccess,
10
+ type ViewportInfo,
11
+ } from "./core.js";
12
+
13
+ /**
14
+ * Reads only: localName, element children, shadowRoot presence (host detection), computed
15
+ * display/visibility, `aria-hidden`/`inert` on ancestors, and the bounding rect. Never textContent,
16
+ * ids, classes or other attributes, and never a click, focus or attribute write.
17
+ */
18
+ export function domTree(doc: Document): TreeAccess<Element> {
19
+ const win = doc.defaultView;
20
+ const scrollX = () => win?.scrollX ?? 0;
21
+ const scrollY = () => win?.scrollY ?? 0;
22
+ return {
23
+ root: () => doc.documentElement,
24
+ child: (node, index) => node.children[index] ?? null,
25
+ tag: (node) => (node.localName || "").toLowerCase(),
26
+ isHost: (node) => isHostBoundary(node),
27
+ hidden(node) {
28
+ const r = node.getBoundingClientRect();
29
+ if (!(r.width > 0 && r.height > 0)) return true;
30
+ const style = win?.getComputedStyle(node);
31
+ if (style && (style.display === "none" || style.visibility === "hidden")) return true;
32
+ for (let cur: Element | null = node; cur; cur = cur.parentElement) {
33
+ if (cur.hasAttribute("inert") || cur.getAttribute("aria-hidden") === "true") return true;
34
+ }
35
+ return false;
36
+ },
37
+ rect(node): Rect {
38
+ const r = node.getBoundingClientRect();
39
+ return safeRect({ x: r.left + scrollX(), y: r.top + scrollY(), width: r.width, height: r.height });
40
+ },
41
+ };
42
+ }
43
+
44
+ export interface DomResolveContext {
45
+ viewport: ViewportInfo;
46
+ authored?: AuthoredViewport;
47
+ }
48
+
49
+ export function viewportOf(doc: Document): ViewportInfo {
50
+ const win = doc.defaultView;
51
+ return { width: win?.innerWidth ?? 0, height: win?.innerHeight ?? 0 };
52
+ }
53
+
54
+ /** One synchronous resolution against the live document. */
55
+ export function resolveInDocument(doc: Document, target: FeedbackTarget, ctx: DomResolveContext) {
56
+ return resolveTarget(target, domTree(doc), ctx.viewport, ctx.authored);
57
+ }
58
+
59
+ export function regionFallbackInDocument(doc: Document, target: FeedbackTarget, ctx: DomResolveContext) {
60
+ return resolveRegionFallback(target, domTree(doc), ctx.viewport, ctx.authored);
61
+ }
62
+
63
+ /**
64
+ * Resolves now, and while the result is `absent` retries on DOM mutation for up to
65
+ * SETTLE_WINDOW_MS, then reports `absent/timeout`. `resolved` and `ambiguous` settle at once.
66
+ * `onSettled` fires exactly once. Returns a cancel function.
67
+ */
68
+ export function settleTarget(
69
+ doc: Document,
70
+ target: FeedbackTarget,
71
+ ctx: DomResolveContext,
72
+ onSettled: (resolution: TargetResolution, element: Element | null) => void,
73
+ ): () => void {
74
+ let done = false;
75
+ let observer: MutationObserver | null = null;
76
+ let timer: ReturnType<typeof setTimeout> | null = null;
77
+
78
+ const finish = (resolution: TargetResolution, element: Element | null) => {
79
+ if (done) return;
80
+ done = true;
81
+ observer?.disconnect();
82
+ if (timer !== null) clearTimeout(timer);
83
+ onSettled(resolution, element);
84
+ };
85
+
86
+ const attempt = () => {
87
+ if (done) return;
88
+ const { resolution, node } = resolveInDocument(doc, target, ctx);
89
+ if (resolution.state !== "absent") finish(resolution, node);
90
+ };
91
+
92
+ const first = resolveInDocument(doc, target, ctx);
93
+ if (first.resolution.state !== "absent") {
94
+ finish(first.resolution, first.node);
95
+ return () => undefined;
96
+ }
97
+
98
+ const Observer = doc.defaultView?.MutationObserver;
99
+ if (Observer) {
100
+ observer = new Observer(attempt);
101
+ observer.observe(doc.documentElement, { childList: true, subtree: true, attributes: true });
102
+ }
103
+ timer = setTimeout(() => finish({ state: "absent", reason: "timeout" }, null), SETTLE_WINDOW_MS);
104
+
105
+ return () => {
106
+ done = true;
107
+ observer?.disconnect();
108
+ if (timer !== null) clearTimeout(timer);
109
+ };
110
+ }
111
+
112
+ /** Scrolls a resolved element into view. The only write the player's resolution makes, and it never touches attributes. */
113
+ export function revealElement(el: Element, reducedMotion: boolean): void {
114
+ el.scrollIntoView({ block: "center", inline: "nearest", behavior: reducedMotion ? "auto" : "smooth" });
115
+ }
@@ -0,0 +1,29 @@
1
+ export {
2
+ DRIFT_EVALUATION_LIMIT,
3
+ GEOMETRY_AGREEMENT_FLOOR,
4
+ SETTLE_WINDOW_MS,
5
+ bandOf,
6
+ driftAlternatives,
7
+ findCandidates,
8
+ iou,
9
+ pickBandTarget,
10
+ rank,
11
+ resolveRegionFallback,
12
+ resolveTarget,
13
+ type AuthoredViewport,
14
+ type Candidate,
15
+ type MatchKind,
16
+ type ResolveOutcome,
17
+ type TargetResolution,
18
+ type TreeAccess,
19
+ type ViewportInfo,
20
+ } from "./core.js";
21
+ export {
22
+ domTree,
23
+ regionFallbackInDocument,
24
+ resolveInDocument,
25
+ revealElement,
26
+ settleTarget,
27
+ viewportOf,
28
+ type DomResolveContext,
29
+ } from "./dom.js";