Files
webstudio/packages/sdk/src/resource-loader.ts
Oleg Isonen 3d0a0657aa feat: Support async resource dependencies (#6030)
## Summary

Make `Resource<Document>` the lazy document-resolution abstraction
shared by Content Engine graphs, generated sites, and Builder previews.
Expressions use one async computation interface: referenced resource
documents resolve first, independent requests run concurrently, and
unused resources stay unloaded.

Ref #6029
Ref #6031

## Implementation checklist

- [x] Define one resource contract for synchronous or asynchronous
document resolution.
- [x] Resolve explicit roots lazily with memoization, bounded
concurrency, cancellation, and structured errors.
- [x] Preserve cycle, duplicate, and missing-resource diagnostics.
- [x] Extract resource dependencies with the existing expression AST.
- [x] Discover consumed resource roots from the current page tree and
page metadata.
- [x] Generate a lazy request graph for published page data, including
independent requests.
- [x] Resolve dependency documents before evaluating dependent request
expressions.
- [x] Integrate dependency-first loading with Builder preview caching
and invalidation.
- [x] Expose safe Resource bindings in the editor and reject
self/indirect cycles.
- [x] Adapt REST, GraphQL, Assets, date, and sitemap requests through
the same Resource contract.
- [x] Cover laziness, chains, shared dependencies, concurrency,
invalidation, cancellation, failures, and cycles with fail/pass tests.
- [x] Review documentation impact and document dependent Resources in
the Data variables guide.
- [x] Track collection-item and component-parameter-dependent resources
as follow-up #6031.
- [x] Regenerate and review affected fixtures.
- [x] Resolve action-resource request dependencies when an action is
invoked.
- [x] Reproduce and fix cached form submissions and multi-root
dependency-cycle hangs.
- [x] Document uncached form actions and regenerate affected fixtures.
- [x] Preserve single and multi-selected content until a cut
successfully writes to the clipboard.
- [x] Preserve boolean expression values in the search-exclusion
checkbox.
- [x] Cancel cut deletion if project data changes while preparing or
writing the clipboard; cover content/property edits and project switches
for single and multi-selection, and document the retry behavior.

- [x] Validate pending cuts after the final await, immediately before
deletion, and reproduce the queued-update race for single and
multi-selection.

## Technical direction

The persisted, revisioned `DocumentGraph` remains the Content Engine
artifact. `Resource<Document>` is the execution abstraction for
obtaining a document; its resolver evaluates only the dependency closure
reachable from requested roots. Static and remote documents therefore
differ by Resource implementation, not by expression value type.

Generated pages always emit a `ResourceRequestGraph`. Each node owns its
output name, dependencies, and request factory. Roots come from resource
variables actually referenced by the current page's metadata, props,
actions, or expression children. Unused and off-page resources remain
unresolved. The loader still accepts legacy request maps for
compatibility.

Builder preview uses the same page-root discovery as published
generation. Its existing cache remains the lifecycle boundary: cached
dependency documents unlock dependent requests, while invalidation
removes downstream requests until their inputs resolve again. The
separate canvas frame recomputes its local plan from the synchronized
cache so rendered expressions receive those documents.

Action requests and their dependencies resolve when a form is submitted.
Each submission sends a new action request, bypassing Webstudio's
resource cache. Dependency requests still use their configured cache
lifetime.

## Review simplifications

- Consolidated page resource-root discovery in the SDK and reused it in
Builder.
- Scoped root and action discovery to the current page tree.
- Removed the redundant immediate-resource helper; `Resource.resolve`
already accepts `Document | Promise<Document>`.
- Moved output names onto graph nodes and removed the duplicate
graph-level map.
- Removed unused planner output and corrected transitive cycle discovery
to include only Resource data sources.
- Regenerated fixtures so independent resources also use lazy graph
execution.
- Reused one abort-aware concurrency limiter for document sessions and
Resource resolution.
- Collapsed duplicate generator action scans and removed redundant
generated-resource bookkeeping.
- Unified legacy request maps and request graphs through one resolution
path.
- Shared the 20-request concurrency limit between SDK, Builder preview,
and the server batch boundary.
- Preserved dependency failure paths and original causes, including the
first cancellation reason.
- Removed invalid-request logging that could expose Resource headers or
request bodies.
- Made editor cycle detection alias-safe by comparing underlying
Resource IDs.
- Memoized page settings values to prevent repeated async validation
renders.

## Verification

Latest local verification for `bbca6395e3`:

- Both queued-update regression cases failed before the fix and passed
afterward. Validation now runs synchronously immediately before
deletion, after the final await, in both cut paths.
- Passed: 255 copy/paste and command tests, Builder typecheck, lint,
package boundaries, formatting, and diff checks.
- Reviewed documentation: the existing copy/paste safety description
remains accurate. Fixture inputs and outputs are unaffected; no fixture
regeneration was needed. Agent evaluations were not run because separate
approval is required.
- CI for the new commit is pending.

Previous local verification for `ffbc75b152`:

- Six regression cases failed before the fix and passed afterward:
content edits, property edits, and project switches during a pending
cut, with both single and multiple selections.
- Passed: 253 copy/paste and command tests, Builder typecheck, lint,
package boundaries, source formatting, and diff checks.
- An unchanged content-block test file initially failed to import in the
browser. Its isolated rerun and the full 253-test rerun passed without
code changes.
- The guard conservatively treats any project-data change as a reason to
keep the clipboard copy without deleting content. It shows a retry
message. Copy/paste documentation now describes this behavior.
- Fixture inputs and outputs are unaffected; fixtures were not
regenerated. Agent evaluations were not run because separate approval is
required. CI for the new commit is pending.

Previous local verification for `3eb580697c`:

- Reproduced both regressions with failing tests before fixing them:
premature deletion during cut and false search exclusion appearing
checked.
- Passed: 203 copy/paste and page-settings tests, Builder typecheck,
lint, package boundaries, formatting, and diff checks.
- Cut coverage includes keyboard and programmatic entry points, single
and multiple selections, delayed successful writes, rejected writes, and
disabled copying.
- Reviewed documentation impact: these fixes restore existing behavior;
no documentation update is needed. Only Builder UI and clipboard files
changed; fixture inputs and outputs are unaffected, so fixtures were not
regenerated for this commit.
- CI status for this older commit was recorded as pending at handoff.
Agent evaluations were not run; they require separate approval.

Previous local verification for `858b348ad`, rebased onto `cf606ca4c`:

- Regression tests failed before each fix and passed afterward: repeated
submissions in both generated route templates, plus three
multi-root/branching cycle cases.
- Passed: 590 SDK tests, 1,129 CLI tests, 72 focused Builder tests,
SDK/CLI/Builder typechecks, lint, package boundaries, and fixture
link/sync/build.
- Initial concurrent runs hit timeouts. The complete CLI suite passed
with one worker; the focused Builder suites passed without file
parallelism.
- Documentation and generated fixture changes reviewed. Agent
evaluations were not run; they require separate approval.
- CI for `858b348ad` passed: Main (including all six E2E shards), Visual
Regression, Lint PR, and Check submodules.

Earlier verification (before this update):

TDD fail/pass evidence includes resolver creation, AST dependency
discovery, published graph reachability, dependency-gated request
generation, Builder dependency-first planning, Resource editor cycle
filtering, page-tree root scoping, off-page action isolation, transitive
Resource-only cycle discovery, abort/timeout precedence, server batch
limits, and the rebased SSG fixture consuming its lazy Resource.

- `pnpm checks` passed after rebasing onto `ce84ddcf12`; it covered
workspace tests, typechecks, lint, package boundaries, generated
API/docs validation, and fixture link/sync/build.
- Earlier focused checks passed: Builder typecheck, 12
page-settings/pages unit tests, lint, formatting, and `git diff
--check`.
- Local generated-resource E2E passed for HTTP, GraphQL, and
current-date resources (3 tests).
- The page-actions and Marketplace page-settings persistence E2Es both
pass locally.
- CI for `6b8b08a70` passed: Main workflow (including all six Builder
E2E shards), Visual Regression, Lint PR, and Check submodules.
- Agent evaluations were not run because they require separate explicit
approval.

## Current behavior and limitations

- A failed dependency blocks its dependents and reports the resource
path and cause.
- One published resolution call is the memoization boundary; Builder
maps dependency readiness onto its versioned request-cache lifecycle.
- Scoped collection-item and component-parameter resources remain in
#6031.
- Builder skips cyclic dependency paths without blocking independent
resources.
2026-09-22 21:04:42 +02:00

516 lines
16 KiB
TypeScript

import hash from "@emotion/hash";
import {
awaitWithSignal,
resolveResources as resolveResourceGraph,
type Resource,
} from "@webstudio-is/content-engine";
import type { ResourceRequest } from "./schema/resources";
import { serializeValue } from "./to-string";
const LOCAL_RESOURCE_PREFIX = "$resources";
const RESOURCE_ERROR_DETAIL_LIMIT = 2000;
export const resourceLoadConcurrency = 20;
const formatResourceErrorDetail = (data: unknown) => {
let detail = "";
if (typeof data === "string") {
detail = data;
} else if (
typeof data === "object" &&
data !== null &&
Array.isArray(data) === false
) {
const record = data as Record<string, unknown>;
const structuredDetail: Record<string, unknown> = {};
for (const key of ["code", "message", "issues"]) {
if (record[key] !== undefined) {
structuredDetail[key] = record[key];
}
}
if (Object.keys(structuredDetail).length > 0) {
detail = JSON.stringify(structuredDetail, undefined, 2);
}
}
return detail.length > RESOURCE_ERROR_DETAIL_LIMIT
? `${detail.slice(0, RESOURCE_ERROR_DETAIL_LIMIT)}\n…truncated`
: detail;
};
/**
* Prevents fetch cycles by prefixing local resources.
*/
export const isLocalResource = (pathname: string, resourceName?: string) => {
const pathEnd = [pathname.indexOf("?"), pathname.indexOf("#")]
.filter((index) => index !== -1)
.reduce((first, index) => Math.min(first, index), pathname.length);
const path = pathname.slice(0, pathEnd);
if (path.startsWith("//")) {
return false;
}
const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
const segments = normalizedPath.split("/");
if (resourceName === undefined) {
return segments[0] === LOCAL_RESOURCE_PREFIX;
}
return segments.join("/") === `${LOCAL_RESOURCE_PREFIX}/${resourceName}`;
};
export const sitemapResourceUrl = `/${LOCAL_RESOURCE_PREFIX}/sitemap.xml`;
export const currentDateResourceUrl = `/${LOCAL_RESOURCE_PREFIX}/current-date`;
export const assetsResourceUrl = `/${LOCAL_RESOURCE_PREFIX}/assets`;
// Direct HTTP endpoints described by the Assets OpenAPI document. These are
// separate from the virtual System resource URLs above, which are resolved
// only inside Builder's batched resource loader.
export const assetsApiUrl = "/rest/assets";
export const assetsUploadsApiUrl = `${assetsApiUrl}/uploads`;
export const assetsFoldersApiUrl = `${assetsApiUrl}/folders`;
export const getAssetUploadApiUrl = (name: string) =>
`${assetsUploadsApiUrl}/${encodeURIComponent(name)}`;
export const getAssetContentApiUrl = (assetId: string) =>
`${assetsApiUrl}/${encodeURIComponent(assetId)}/content`;
export const getAssetApiUrl = (assetId: string) =>
`${assetsApiUrl}/${encodeURIComponent(assetId)}`;
export const getAssetFolderApiUrl = (folderId: string) =>
`${assetsFoldersApiUrl}/${encodeURIComponent(folderId)}`;
export const assetsQueryApiUrl = `${assetsApiUrl}/query`;
export const assetsIndexRefreshApiUrl = `${assetsApiUrl}/index/refresh`;
export const assetsFieldCatalogApiUrl = `${assetsApiUrl}/field-catalog`;
export const assetsOpenApiUrl = `${assetsApiUrl}/openapi.json`;
export const assetsQuerySchemaApiUrl = `${assetsApiUrl}/query-schema.json`;
export type ResourceLoadOptions = {
signal?: AbortSignal;
timeoutMs?: number;
};
export type ResourceGraphLoadOptions = ResourceLoadOptions & {
requestOverrides?: ReadonlyMap<
string,
Partial<ResourceRequest> & { fetch?: typeof fetch }
>;
};
export type ResourceRequestResource = Readonly<{
id: string;
outputName: string;
dependencies: readonly string[];
createRequest: (documents: ReadonlyMap<string, unknown>) => ResourceRequest;
}>;
export type ResourceRequestGraph = Readonly<{
resources: readonly ResourceRequestResource[];
rootIds: readonly string[];
}>;
export const createResourceFetchBatchProvider = ({
baseUrl,
shouldBatch,
execute,
}: {
baseUrl: string | URL;
shouldBatch: (input: RequestInfo | URL, init?: RequestInit) => boolean;
execute: (requests: readonly Request[]) => Promise<readonly Response[]>;
}) => {
const pending: Array<{
request: Request;
resolve: (response: Response) => void;
reject: (error: unknown) => void;
}> = [];
let didFlush = false;
let flushPromise: Promise<void> | undefined;
return {
fetch: (
input: RequestInfo | URL,
init?: RequestInit
): Promise<Response> | undefined => {
if (didFlush || shouldBatch(input, init) === false) {
return;
}
const request =
typeof input === "string"
? new Request(new URL(input, baseUrl), init)
: new Request(input, init);
return new Promise<Response>((resolve, reject) => {
pending.push({ request, resolve, reject });
});
},
flush: () => {
if (flushPromise !== undefined) {
return flushPromise;
}
didFlush = true;
const batch = pending.splice(0);
flushPromise = Promise.resolve().then(async () => {
if (batch.length === 0) {
return;
}
try {
const responses = await execute(batch.map(({ request }) => request));
if (responses.length !== batch.length) {
throw new Error(
"Resource batch response count does not match requests"
);
}
for (const [index, response] of responses.entries()) {
batch[index].resolve(response);
}
} catch (error) {
for (const item of batch) {
item.reject(error);
}
}
});
return flushPromise;
},
};
};
export const isAssetsResourceRequest = (request: ResourceRequest) =>
request.method === "post" && isLocalResource(request.url, "assets");
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && Array.isArray(value) === false;
// Assets expose one ID-keyed resource contract. Query execution uses an array
// internally for ordering and pagination.
const includesAssetId = (body: unknown) => {
if (isRecord(body) === false || isRecord(body.query) === false) {
return false;
}
const { output } = body.query;
if (isRecord(output) === false) {
return false;
}
if (output.includeMetadata === true) {
return true;
}
return (
output.mode === "fields" &&
Array.isArray(output.fields) &&
output.fields.some(
(field) => Array.isArray(field) && field.length === 1 && field[0] === "id"
)
);
};
const formatAssetsResourceResult = (value: unknown, body: unknown) => {
const preview =
isRecord(value) && isRecord(value.data) ? value.data : undefined;
const collection = preview ?? value;
const resultMode =
isRecord(body) &&
isRecord(body.query) &&
typeof body.query.result === "string"
? body.query.result
: "many";
const diagnostics = isRecord(value) ? value.__diagnostics__ : undefined;
const performance = isRecord(value) ? value.__performance__ : undefined;
const internalMetadata = {
...(preview === undefined || diagnostics === undefined
? {}
: { __diagnostics__: diagnostics }),
...(performance === undefined ? {} : { __performance__: performance }),
};
if (
resultMode !== "many" &&
isRecord(collection) &&
Object.hasOwn(collection, "item") &&
(collection.item === null || isRecord(collection.item)) &&
typeof collection.totalCount === "number"
) {
return {
data: collection.item,
meta: { totalCount: collection.totalCount },
...internalMetadata,
};
}
if (
isRecord(collection) === false ||
Array.isArray(collection.items) === false ||
typeof collection.totalCount !== "number" ||
typeof collection.hasMore !== "boolean"
) {
return;
}
const includeId = includesAssetId(body);
const entries: Array<[string, Record<string, unknown>]> = [];
for (const item of collection.items) {
if (isRecord(item) === false || typeof item.id !== "string") {
return;
}
const { id, ...fields } = item;
entries.push([id, includeId ? item : fields]);
}
return {
data: Object.fromEntries(entries),
meta: {
totalCount: collection.totalCount,
hasMore: collection.hasMore,
},
...internalMetadata,
};
};
const transportFailure = ({
code,
message,
retryable,
status,
}: {
code: "REQUEST_CANCELLED" | "REQUEST_TIMEOUT" | "NETWORK_ERROR";
message: string;
retryable: boolean;
status: number;
}) => ({
ok: false,
data: { ok: false, error: { code, message, retryable } },
status,
statusText: message,
});
export const loadResource = async (
customFetch: typeof fetch,
resourceRequest: ResourceRequest,
baseUrl?: string | URL,
options: ResourceLoadOptions = {}
) => {
const controller = new AbortController();
let didTimeout = false;
const cancel = () => controller.abort(options.signal?.reason);
if (options.signal?.aborted) {
cancel();
} else {
options.signal?.addEventListener("abort", cancel, { once: true });
}
const timeoutId =
options.timeoutMs === undefined
? undefined
: setTimeout(() => {
if (controller.signal.aborted) {
return;
}
didTimeout = true;
controller.abort();
}, options.timeoutMs);
try {
const { method, searchParams, headers, body } = resourceRequest;
let href = resourceRequest.url;
try {
// cloudflare workers fail when fetching url contains spaces
// even though new URL suppose to trim them on parsing by spec
const sourceUrl = resourceRequest.url.trim();
const local = isLocalResource(sourceUrl);
const resolutionBase = local
? new URL("https://webstudio.local")
: baseUrl === undefined
? undefined
: new URL("/", baseUrl);
const url = new URL(sourceUrl, resolutionBase);
if (searchParams) {
for (const { name, value } of searchParams) {
url.searchParams.append(name, serializeValue(value));
}
}
href = local ? `${url.pathname}${url.search}` : url.href;
} catch {
// empty block
}
const requestHeaders = new Headers(
headers.map(({ name, value }): [string, string] => [
name,
serializeValue(value),
])
);
const requestInit: RequestInit = {
method,
headers: requestHeaders,
};
let signal: AbortSignal | undefined;
if (options.signal !== undefined || options.timeoutMs !== undefined) {
signal = controller.signal;
requestInit.signal = signal;
}
if (method !== "get" && body !== undefined) {
requestInit.body = serializeValue(body);
}
const response = await awaitWithSignal(
customFetch(href, requestInit),
signal
);
let data = await awaitWithSignal(response.text(), signal);
try {
// If it looks like JSON and quacks like JSON, then it probably is JSON.
data = JSON.parse(data);
} catch {
// ignore, leave data as text
}
if (!response.ok) {
const detail = formatResourceErrorDetail(data);
console.error(
`Failed to load resource request: ${response.status}${detail === "" ? "" : `\n${detail}`}`
);
}
const result = {
ok: response.ok,
status: response.status,
statusText: response.statusText,
data,
};
if (response.ok && isAssetsResourceRequest(resourceRequest)) {
const formatted = formatAssetsResourceResult(data, resourceRequest.body);
if (formatted !== undefined) {
return { ...result, ...formatted };
}
}
return result;
} catch (error) {
if (didTimeout) {
return transportFailure({
code: "REQUEST_TIMEOUT",
message: `Resource request exceeded ${options.timeoutMs}ms`,
retryable: true,
status: 504,
});
}
if (options.signal?.aborted) {
return transportFailure({
code: "REQUEST_CANCELLED",
message: "Resource request was cancelled",
retryable: false,
status: 499,
});
}
console.error("Resource request failed");
return transportFailure({
code: "NETWORK_ERROR",
message: "Resource request failed",
retryable: true,
status: 502,
});
} finally {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
options.signal?.removeEventListener("abort", cancel);
}
};
export const loadResources = async (
customFetch: typeof fetch,
requests: Map<string, ResourceRequest> | ResourceRequestGraph,
baseUrl?: string | URL,
options?: ResourceGraphLoadOptions
) => {
const isLegacyMap = requests instanceof Map;
const graph: ResourceRequestGraph = isLegacyMap
? {
resources: Array.from(requests, ([name, request]) => ({
id: name,
outputName: name,
dependencies: [],
createRequest: () => request,
})),
rootIds: Array.from(requests.keys()),
}
: requests;
const resources: Resource<unknown>[] = graph.resources.map((resource) => ({
id: resource.id,
dependencies: resource.dependencies,
resolve: ({ documents, signal }) => {
const { requestOverrides, ...loadOptions } = options ?? {};
const { fetch: requestFetch = customFetch, ...overrides } =
requestOverrides?.get(resource.id) ?? {};
const request = resource.createRequest(documents);
const resolvedRequest = {
...request,
...overrides,
};
return loadResource(requestFetch, resolvedRequest, baseUrl, {
...loadOptions,
signal: signal ?? options?.signal,
});
},
}));
const resolved = await resolveResourceGraph({
resources,
rootIds: graph.rootIds,
concurrency: resourceLoadConcurrency,
// Legacy maps expose cancellation as a structured transport document.
// Graph callers use resolver-level cancellation instead.
signal: isLegacyMap ? undefined : options?.signal,
});
const resourcesById = new Map(
graph.resources.map((resource) => [resource.id, resource])
);
const output = new Map<string, unknown>();
for (const resourceId of graph.rootIds) {
const resource = resourcesById.get(resourceId);
if (resource !== undefined && resolved.documents.has(resourceId)) {
output.set(resource.outputName, resolved.documents.get(resourceId));
}
}
return Object.fromEntries(output);
};
/**
* cache api supports only get method
* put hash of method and body into url
* to support for example graphql queries
*/
export const getResourceCacheKey = async (request: Request) => {
const url = new URL(request.url);
const method = request.method;
const body = await request.clone().text();
// invalidate cache when cache-control is changed
const cacheControl = request.headers.get("Cache-Control");
const resourceHash = hash(`${method}:${body}:${cacheControl}`);
url.searchParams.set("ws-resource-hash", resourceHash);
return url;
};
export const cachedFetch = async (
namespace: string,
input: RequestInfo | URL,
init?: RequestInit
) => {
if (globalThis.caches) {
const request = new Request(input, init);
const requestCacheControl = request.headers.get("Cache-Control");
// make cache opt in with cache-control header
if (!requestCacheControl) {
return fetch(input, init);
}
const cache = await caches.open(namespace);
const cacheKey = await getResourceCacheKey(request);
let response = await cache.match(cacheKey);
if (response) {
// avoid mutating cached response
return new Response(response.body, response);
}
// load response when missing in cache
response = await fetch(request);
// avoid caching failed responses
if (!response.ok) {
return response;
}
// put Cache-Control from request into response
// https://developers.cloudflare.com/workers/reference/how-the-cache-works/#cache-api
// response.clone() does not remove read-only constraint from headers
response = new Response(response.body, response);
response.headers.set("Cache-Control", requestCacheControl);
// avoid mutating cached response
await cache.put(cacheKey, response.clone());
return response;
}
return fetch(input, init);
};