mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-02 05:15:21 +09:00
## Summary Introduce a document graph architecture for Assets resources so structured documents can reference one another while keeping full document payloads on CDN-backed storage. The content database will retain the searchable index and dependency graph. At runtime, the server will select a root document, determine its complete dependency set before performing I/O, fetch each unique document concurrently, and assemble the final result server-side. ## Implementation todos ### Document graph foundation - [x] Add normalized internal reference contracts for whole documents, JSON paths, Markdown body, and Markdown frontmatter. - [x] Add an immutable graph abstraction with deterministic ordering, dependency traversal, revision validation, and cycle detection. - [x] Add a storage-independent resolver with dependency closure, bounded parallel loading, shared-content deduplication, representation selection, assembly hooks, cancellation, and structured errors. - [x] Add focused unit coverage for the isolated document-graph abstraction. - [x] Define and validate the external remote-document reference syntax. - [x] Add a pure graph compiler that resolves canonical document URLs into IDs and revisions and validates missing, duplicate, and cyclic dependencies. ### Build-time graph - [x] Add a storage-independent source-catalog compiler for bounded parallel reference discovery and deterministic graph compilation. - [x] Add a versioned deterministic document graph artifact with canonical serialization and integrity verification. - [x] Discover and normalize statically declared references while Assets resources are processed. - [x] Resolve document identities and revisions and report missing, stale, or cyclic dependencies with document context. - [x] Persist document nodes and dependency edges alongside searchable resource metadata. - [x] Include persisted graph data in artifact integrity and size validation. ### Document representations - [x] Add a standalone JSON document adapter for exact reference markers, compiler occurrences, JSON path selection, and immutable assembly. - [x] Add a standalone Markdown document adapter for bounded decoding, frontmatter references, immutable assembly, and source, body, and frontmatter selection. - [x] Parse fetched JSON and Markdown documents through format-specific adapters. - [x] Select complete documents, JSON fragments, Markdown body, and Markdown frontmatter through the shared reference model. - [x] Assemble nested and shared references into the final server-side value. ### Runtime resolution - [x] Enforce reachable-document, per-document byte, and aggregate-byte limits before parsing and assembly. - [x] Add a revision-keyed bounded source-cache wrapper with replayable bytes, stale-entry fallback, and in-flight deduplication. - [x] Add a storage-neutral loaded-source contract that rejects revision mismatches before parsing. - [x] Resolve graph-backed property paths before filtering, sorting, pagination, and projection; skip graph loading for unrelated queries. - [x] Add an injected HTTP/CDN document loader with revision metadata validation. - [x] Apply runtime payload limits, bounded concurrency, caching, and structured failure mapping. - [x] Ensure shared documents are fetched and parsed once per resolution. ### Product integration - [x] Integrate equivalent behavior in local preview, SSR, SSG, and published runtime paths. - [x] Preserve existing embedded Assets resource behavior without requiring migration. - [x] Add observability for graph loading, document fetching, caching, and resolution failures. - [x] Document the public reference and resolution behavior. ### Review hardening - [x] Enforce graph, artifact, cache, and published-storage identity consistency. - [x] Compile only graph sources reachable from selected build entries. - [x] Resolve graph-backed fields before query evaluation and avoid unnecessary graph loading. - [x] Consolidate duplicated graph schemas, utilities, and document content-type detection. - [x] Correct runtime documentation and use structural evaluation validation. ### Verification - [x] Keep a deterministic high-impact agent evaluation for Markdown-to-JSON references across the dynamic blog overview and article routes. - [x] Add a separate discoverability evaluation that must learn the reference workflow from MCP guidance without prompt-supplied syntax, queries, bindings, or call order. - [ ] Re-run the complete local agent evaluation suite after the discoverability fixture change and compare every fixture with its accepted baseline. - [x] Add integration coverage for CDN-backed hydration, parallel fetching, caching, and shared dependencies. - [x] Add integration coverage for missing references, cycles, revision changes, limits, and cancellation. - [x] Verify equivalent behavior across preview, SSR, SSG, and published deployments. - [x] Verify that existing embedded Assets resources retain their current behavior. ## Intended outcome - Storage-backed documents do not require their complete payloads to be embedded in the content database. - The server knows the complete statically discoverable dependency set before fetching document content. - Shared dependencies are fetched once per resolution and independent resources can be fetched in parallel. - JSON fragments and Markdown body/frontmatter representations use the same document-resolution system. - Reference and payload revisions cannot be mixed silently. - Existing Assets resources continue to work without migration. ## Verification results - `@webstudio-is/content-engine`: 37 files / 244 tests passed; typecheck passed. - `@webstudio-is/asset-uploader`: 22 files / 182 tests passed; typecheck passed. - CLI: 57 files / 925 tests passed, including generated SSR and SSG build/prerender coverage; typecheck passed. - Repository-wide `pnpm oxfmt --check` passed across 2,757 files. - Package-boundary validation passed. - Previous `pnpm evaluations` run: all 4 original high-impact fixtures passed. The complete 5-fixture rerun is pending explicit approval after adding the discoverability fixture.
272 lines
7.3 KiB
TypeScript
272 lines
7.3 KiB
TypeScript
import { json, record, strictObject, string } from "zod";
|
|
import {
|
|
ByteLimitExceededError,
|
|
decodeUtf8,
|
|
readBoundedBytes,
|
|
stripUtf8ByteOrderMark,
|
|
type ByteSource,
|
|
} from "../byte-stream";
|
|
import { normalizeJsonValue, type JsonValue } from "../canonical-json";
|
|
import { extractMarkdownFrontmatter } from "../frontmatter";
|
|
import { contentEngineLimits } from "../limits";
|
|
import { extractMarkdownBody } from "../markdown-body";
|
|
import type { DocumentRepresentation } from "./reference";
|
|
import type { SourceReferenceOccurrence } from "./reference-codec";
|
|
import {
|
|
analyzeJsonDocument,
|
|
assembleJsonDocument,
|
|
JsonDocumentError,
|
|
} from "./json-document";
|
|
|
|
export type MarkdownDocument = Readonly<{
|
|
source: string;
|
|
body: string;
|
|
frontmatter: { readonly [key: string]: JsonValue };
|
|
}>;
|
|
|
|
export type MarkdownDocumentErrorCode =
|
|
| "CONTENT_LIMIT_EXCEEDED"
|
|
| "CONTENT_DECODING_FAILED"
|
|
| "INVALID_DOCUMENT"
|
|
| "INVALID_REFERENCE_MARKER"
|
|
| "INVALID_REFERENCE"
|
|
| "REFERENCE_NOT_FOUND"
|
|
| "INVALID_RESOLVED_VALUE"
|
|
| "UNUSED_REFERENCE"
|
|
| "UNSUPPORTED_REPRESENTATION";
|
|
|
|
export class MarkdownDocumentError extends Error {
|
|
readonly code: MarkdownDocumentErrorCode;
|
|
readonly referenceId?: string;
|
|
|
|
constructor({
|
|
code,
|
|
message,
|
|
referenceId,
|
|
cause,
|
|
}: {
|
|
code: MarkdownDocumentErrorCode;
|
|
message: string;
|
|
referenceId?: string;
|
|
cause?: unknown;
|
|
}) {
|
|
super(message, { cause });
|
|
this.name = "MarkdownDocumentError";
|
|
this.code = code;
|
|
this.referenceId = referenceId;
|
|
}
|
|
}
|
|
|
|
const markdownDocumentSchema = strictObject({
|
|
source: string(),
|
|
body: string(),
|
|
frontmatter: record(string(), json()),
|
|
});
|
|
|
|
const normalizeMarkdownDocument = (input: unknown): MarkdownDocument => {
|
|
let parsed;
|
|
try {
|
|
parsed = markdownDocumentSchema.parse(input);
|
|
} catch (cause) {
|
|
throw new MarkdownDocumentError({
|
|
code: "INVALID_DOCUMENT",
|
|
message: "Markdown document is invalid",
|
|
cause,
|
|
});
|
|
}
|
|
return Object.freeze({
|
|
source: parsed.source,
|
|
body: parsed.body,
|
|
frontmatter: normalizeJsonValue(parsed.frontmatter) as {
|
|
readonly [key: string]: JsonValue;
|
|
},
|
|
});
|
|
};
|
|
|
|
const markdownReferencePrefix = "#frontmatter";
|
|
|
|
const toMarkdownReferenceId = (jsonReferenceId: string) =>
|
|
`${markdownReferencePrefix}${jsonReferenceId.slice(1)}`;
|
|
|
|
const toJsonReferenceId = (markdownReferenceId: string) => {
|
|
if (
|
|
markdownReferenceId !== markdownReferencePrefix &&
|
|
markdownReferenceId.startsWith(`${markdownReferencePrefix}/`) === false
|
|
) {
|
|
throw new MarkdownDocumentError({
|
|
code: "UNUSED_REFERENCE",
|
|
message: `Resolved Markdown reference ${markdownReferenceId} is outside frontmatter`,
|
|
referenceId: markdownReferenceId,
|
|
});
|
|
}
|
|
return `#${markdownReferenceId.slice(markdownReferencePrefix.length)}`;
|
|
};
|
|
|
|
const throwMarkdownJsonError = (error: JsonDocumentError): never => {
|
|
const referenceId =
|
|
error.referenceId === undefined
|
|
? undefined
|
|
: toMarkdownReferenceId(error.referenceId);
|
|
let code: MarkdownDocumentErrorCode = "INVALID_DOCUMENT";
|
|
if (
|
|
error.code === "INVALID_REFERENCE_MARKER" ||
|
|
error.code === "INVALID_REFERENCE" ||
|
|
error.code === "REFERENCE_NOT_FOUND" ||
|
|
error.code === "INVALID_RESOLVED_VALUE" ||
|
|
error.code === "UNUSED_REFERENCE"
|
|
) {
|
|
code = error.code;
|
|
}
|
|
throw new MarkdownDocumentError({
|
|
code,
|
|
message: error.message,
|
|
referenceId,
|
|
cause: error,
|
|
});
|
|
};
|
|
|
|
/** Reads and normalizes one bounded Markdown source. */
|
|
export const parseMarkdownDocumentSource = async ({
|
|
source,
|
|
maximumBytes = contentEngineLimits.hydratedFileBytes,
|
|
}: {
|
|
source: ByteSource;
|
|
maximumBytes?: number;
|
|
}): Promise<MarkdownDocument> => {
|
|
let bytes: Uint8Array;
|
|
try {
|
|
bytes = await readBoundedBytes(source, maximumBytes);
|
|
} catch (cause) {
|
|
if (cause instanceof ByteLimitExceededError) {
|
|
throw new MarkdownDocumentError({
|
|
code: "CONTENT_LIMIT_EXCEEDED",
|
|
message: "Markdown document exceeds the byte limit",
|
|
cause,
|
|
});
|
|
}
|
|
throw cause;
|
|
}
|
|
let sourceText: string;
|
|
try {
|
|
sourceText = stripUtf8ByteOrderMark(decodeUtf8(bytes));
|
|
} catch (cause) {
|
|
throw new MarkdownDocumentError({
|
|
code: "CONTENT_DECODING_FAILED",
|
|
message: "Markdown document is not valid UTF-8",
|
|
cause,
|
|
});
|
|
}
|
|
const [body, frontmatter] = await Promise.all([
|
|
extractMarkdownBody(bytes, maximumBytes),
|
|
extractMarkdownFrontmatter(bytes),
|
|
]);
|
|
return normalizeMarkdownDocument({
|
|
source: sourceText,
|
|
body: body.body,
|
|
frontmatter: frontmatter.properties,
|
|
});
|
|
};
|
|
|
|
/** Reads one bounded Markdown source and discovers references in frontmatter. */
|
|
export const analyzeMarkdownDocument = async ({
|
|
source,
|
|
sourceDocumentId,
|
|
documentUrl,
|
|
maximumBytes = contentEngineLimits.hydratedFileBytes,
|
|
}: {
|
|
source: ByteSource;
|
|
sourceDocumentId: string;
|
|
documentUrl: string | URL;
|
|
maximumBytes?: number;
|
|
}): Promise<
|
|
Readonly<{
|
|
document: MarkdownDocument;
|
|
references: readonly SourceReferenceOccurrence[];
|
|
}>
|
|
> => {
|
|
const parsed = await parseMarkdownDocumentSource({ source, maximumBytes });
|
|
let analyzedFrontmatter;
|
|
try {
|
|
analyzedFrontmatter = analyzeJsonDocument({
|
|
value: parsed.frontmatter,
|
|
sourceDocumentId,
|
|
documentUrl,
|
|
});
|
|
} catch (cause) {
|
|
if (cause instanceof JsonDocumentError) {
|
|
throwMarkdownJsonError(cause);
|
|
}
|
|
throw cause;
|
|
}
|
|
const document = normalizeMarkdownDocument({
|
|
source: parsed.source,
|
|
body: parsed.body,
|
|
frontmatter: analyzedFrontmatter.document,
|
|
});
|
|
return Object.freeze({
|
|
document,
|
|
references: Object.freeze(
|
|
analyzedFrontmatter.references.map((occurrence) =>
|
|
Object.freeze({
|
|
...occurrence,
|
|
referenceId: toMarkdownReferenceId(occurrence.referenceId),
|
|
})
|
|
)
|
|
),
|
|
});
|
|
};
|
|
|
|
/** Assembles frontmatter references while preserving the original source and body. */
|
|
export const assembleMarkdownDocument = ({
|
|
document: input,
|
|
references,
|
|
allowUnresolvedReferences = false,
|
|
}: {
|
|
document: unknown;
|
|
references: ReadonlyMap<string, unknown>;
|
|
allowUnresolvedReferences?: boolean;
|
|
}): MarkdownDocument => {
|
|
const document = normalizeMarkdownDocument(input);
|
|
const jsonReferences = new Map<string, unknown>();
|
|
for (const [referenceId, value] of references) {
|
|
jsonReferences.set(toJsonReferenceId(referenceId), value);
|
|
}
|
|
let frontmatter: JsonValue;
|
|
try {
|
|
frontmatter = assembleJsonDocument({
|
|
document: document.frontmatter,
|
|
references: jsonReferences,
|
|
allowUnresolvedReferences,
|
|
});
|
|
} catch (cause) {
|
|
if (cause instanceof JsonDocumentError) {
|
|
throwMarkdownJsonError(cause);
|
|
}
|
|
throw cause;
|
|
}
|
|
return normalizeMarkdownDocument({ ...document, frontmatter });
|
|
};
|
|
|
|
export const selectMarkdownDocumentRepresentation = ({
|
|
document: input,
|
|
representation,
|
|
}: {
|
|
document: unknown;
|
|
representation: DocumentRepresentation;
|
|
}): JsonValue => {
|
|
const document = normalizeMarkdownDocument(input);
|
|
if (representation.type === "document") {
|
|
return document.source;
|
|
}
|
|
if (representation.type === "markdown-body") {
|
|
return document.body;
|
|
}
|
|
if (representation.type === "markdown-frontmatter") {
|
|
return document.frontmatter;
|
|
}
|
|
throw new MarkdownDocumentError({
|
|
code: "UNSUPPORTED_REPRESENTATION",
|
|
message: `Markdown documents do not support ${representation.type}`,
|
|
});
|
|
};
|