mirror of
https://github.com/foomo/walker.git
synced 2026-11-29 08:21:41 +00:00
fix: resolve rendered shape groups and clarify excluded head elements
This commit is contained in:
@@ -247,6 +247,10 @@ final class ShapeDevModel {
|
||||
}
|
||||
validationCount += 1
|
||||
let count = validationCount
|
||||
let requestedSource = source
|
||||
let requestedGroup = group
|
||||
let requestedHeader = groupHeader
|
||||
let requestedRoot = shapeRoot
|
||||
isValidating = true
|
||||
defer {
|
||||
if count == validationCount {
|
||||
@@ -255,20 +259,30 @@ final class ShapeDevModel {
|
||||
}
|
||||
do {
|
||||
var html = ""
|
||||
if source == .rendered {
|
||||
var resolvedGroup = requestedGroup
|
||||
if requestedSource == .rendered {
|
||||
if requestedGroup.isEmpty, !effectiveGroupHeader.isEmpty {
|
||||
resolvedGroup = try await highlighter.groupHeaderValue(effectiveGroupHeader)
|
||||
}
|
||||
guard !Task.isCancelled, count == validationCount, highlighter.pageURL == url else { return }
|
||||
guard let snapshot = await highlighter.snapshot() else {
|
||||
error = "the page has no DOM to validate yet"
|
||||
return
|
||||
}
|
||||
html = snapshot
|
||||
}
|
||||
let validation = try await client.validateShape(shapeRoot: shapeRoot, group: group, groupHeader: groupHeader, targetURL: url.absoluteString, html: html)
|
||||
var validation = try await client.validateShape(shapeRoot: requestedRoot, group: resolvedGroup, groupHeader: requestedHeader, targetURL: url.absoluteString, html: html)
|
||||
if requestedSource == .rendered, requestedGroup.isEmpty {
|
||||
validation.detectedGroup = resolvedGroup
|
||||
}
|
||||
guard !Task.isCancelled, count == validationCount else { return }
|
||||
guard (highlighter.pageURL ?? pageURL) == url else { return }
|
||||
apply(validation)
|
||||
error = nil
|
||||
} catch is CancellationError {
|
||||
return
|
||||
} catch {
|
||||
guard !Task.isCancelled, count == validationCount, (highlighter.pageURL ?? pageURL) == url else { return }
|
||||
self.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,9 +208,16 @@ private struct HeadRow: View {
|
||||
.lineLimit(3)
|
||||
}
|
||||
if !isValidated {
|
||||
Label("not in the shape", systemImage: "questionmark.circle")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.orange)
|
||||
if isExcludedFromMatching {
|
||||
Label("excluded from semantic matching", systemImage: "minus.circle")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.help("Walker excludes scripts and styles from its semantic tree. JSON-LD is validated separately.")
|
||||
} else {
|
||||
Label("not in the shape", systemImage: "questionmark.circle")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.orange)
|
||||
}
|
||||
}
|
||||
}
|
||||
.help(element.locator)
|
||||
@@ -230,6 +237,12 @@ private struct HeadRow: View {
|
||||
element.attributes ?? []
|
||||
}
|
||||
|
||||
private var isExcludedFromMatching: Bool {
|
||||
if ["style", "template", "noscript"].contains(element.tag) { return true }
|
||||
let type = attributes.first { $0.key == "type" }?.value.lowercased() ?? ""
|
||||
return element.tag == "script" && type != "application/ld+json"
|
||||
}
|
||||
|
||||
/// source shows the tag purple, attribute names secondary and the values -
|
||||
/// the attributes the selected shape node checks get a background
|
||||
private var source: Text {
|
||||
|
||||
@@ -176,6 +176,28 @@ final class ShapeHighlighter {
|
||||
return pageURL != nil && !webView.isLoading
|
||||
}
|
||||
|
||||
/// Resolve the configured group header using the browser's current session.
|
||||
func groupHeaderValue(_ header: String) async throws -> String {
|
||||
guard let webView else { return "" }
|
||||
return try await webView.callAsyncJavaScript(
|
||||
Self.groupHeaderScript, arguments: ["header": header], in: nil, contentWorld: .page
|
||||
) as? String ?? ""
|
||||
}
|
||||
|
||||
// Fetch in the browser so cookies and client-side navigation use the current page.
|
||||
private static let groupHeaderScript = """
|
||||
const url = window.location.href;
|
||||
const options = {cache: 'no-store', credentials: 'same-origin', signal: AbortSignal.timeout(10000)};
|
||||
let response = await fetch(url, {...options, method: 'HEAD'});
|
||||
if (response.status === 405 || response.status === 501) {
|
||||
response = await fetch(url, {...options, method: 'GET'});
|
||||
if (response.body) await response.body.cancel();
|
||||
}
|
||||
if (!response.ok) throw new Error('Could not read page group: HTTP ' + response.status);
|
||||
const group = response.headers.get(header) || '';
|
||||
return group.endsWith('/') ? group + 'index' : group;
|
||||
"""
|
||||
|
||||
/// snapshot is the html of the DOM as it is now
|
||||
func snapshot() async -> String? {
|
||||
guard let webView else { return nil }
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// Run with node --test macos/tests/shape-group.test.mjs. No browser or network needed.
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import test from 'node:test';
|
||||
|
||||
const source = await readFile(new URL('../Walker/Views/ShapeWebView.swift', import.meta.url), 'utf8');
|
||||
const script = source.match(/private static let groupHeaderScript = """([\s\S]*?)"""/);
|
||||
assert(script, 'Use the JavaScript actually sent to WKWebView');
|
||||
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
|
||||
const lookup = new AsyncFunction('window', 'fetch', 'header', 'AbortSignal', script[1]);
|
||||
const page = () => ({ location: { href: 'https://fixture.invalid/catalog' } });
|
||||
|
||||
test('uses the configured header and the current browser session', async () => {
|
||||
const window = page();
|
||||
const value = await lookup(window, async (url, options) => {
|
||||
assert.equal(url, window.location.href);
|
||||
assert.equal(options.method, 'HEAD');
|
||||
assert.equal(options.credentials, 'same-origin');
|
||||
assert.equal(options.cache, 'no-store');
|
||||
assert(options.signal instanceof AbortSignal);
|
||||
return new Response(null, { headers: { 'X-Page-Kind': 'catalog' } });
|
||||
}, 'x-page-kind', AbortSignal);
|
||||
assert.equal(value, 'catalog');
|
||||
});
|
||||
|
||||
test('reads the new URL after client-side navigation', async () => {
|
||||
const window = page();
|
||||
const fetch = async url => new Response(null, { headers: { 'X-Group': new URL(url).pathname.slice(1) } });
|
||||
assert.equal(await lookup(window, fetch, 'X-Group', AbortSignal), 'catalog');
|
||||
window.location.href = 'https://fixture.invalid/article';
|
||||
assert.equal(await lookup(window, fetch, 'X-Group', AbortSignal), 'article');
|
||||
});
|
||||
|
||||
test('normalizes directory groups like the crawler', async () => {
|
||||
const fetch = async () => new Response(null, { headers: { 'X-Group': 'content/' } });
|
||||
assert.equal(await lookup(page(), fetch, 'X-Group', AbortSignal), 'content/index');
|
||||
});
|
||||
|
||||
test('missing headers resolve to the default shape without a second request', async () => {
|
||||
let requests = 0;
|
||||
const fetch = async () => { requests++; return new Response(null); };
|
||||
assert.equal(await lookup(page(), fetch, 'X-Group', AbortSignal), '');
|
||||
assert.equal(requests, 1);
|
||||
});
|
||||
|
||||
for (const status of [405, 501]) {
|
||||
test(`falls back to GET for HTTP ${status} and cancels the unused body`, async () => {
|
||||
const window = page();
|
||||
const originalURL = window.location.href;
|
||||
const methods = [];
|
||||
let signal;
|
||||
let cancelled = false;
|
||||
const fetch = async (url, options) => {
|
||||
assert.equal(url, originalURL, 'fallback must not switch to a newly navigated page');
|
||||
methods.push(options.method);
|
||||
if (options.method === 'HEAD') {
|
||||
signal = options.signal;
|
||||
window.location.href = 'https://fixture.invalid/another-page';
|
||||
return new Response(null, { status });
|
||||
}
|
||||
assert.equal(options.signal, signal, 'both requests share one deadline');
|
||||
const body = new ReadableStream({ cancel() { cancelled = true; } });
|
||||
return new Response(body, { headers: { 'X-Group': 'catalog' } });
|
||||
};
|
||||
assert.equal(await lookup(window, fetch, 'X-Group', AbortSignal), 'catalog');
|
||||
assert.deepEqual(methods, ['HEAD', 'GET']);
|
||||
assert(cancelled);
|
||||
});
|
||||
}
|
||||
|
||||
test('does not silently use the default shape on an HTTP failure', async () => {
|
||||
let requests = 0;
|
||||
const fetch = async () => { requests++; return new Response(null, { status: 403 }); };
|
||||
await assert.rejects(lookup(page(), fetch, 'X-Group', AbortSignal), /HTTP 403/);
|
||||
assert.equal(requests, 1);
|
||||
});
|
||||
|
||||
test('bounds the lookup and propagates a timeout', async () => {
|
||||
const controller = new AbortController();
|
||||
const deadline = {
|
||||
timeout(milliseconds) {
|
||||
assert.equal(milliseconds, 10_000);
|
||||
queueMicrotask(() => controller.abort(new Error('lookup timed out')));
|
||||
return controller.signal;
|
||||
},
|
||||
};
|
||||
const fetch = async (_url, { signal }) => new Promise((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
||||
});
|
||||
await assert.rejects(lookup(page(), fetch, 'X-Group', deadline), /lookup timed out/);
|
||||
});
|
||||
Reference in New Issue
Block a user