@phtngyn/cms 0.1.0-beta.5 → 0.2.0-beta.2
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/CHANGELOG.md +13 -0
- package/README.md +114 -41
- package/package.json +13 -1
- package/src/ApplicationTypes.d.ts +84 -0
- package/src/ApplicationTypes.js +1 -0
- package/src/{Configuration-CDMYfTre.js → Configuration-BU-UyGoH.js} +4 -4
- package/src/{Configuration-CDMYfTre.js.map → Configuration-BU-UyGoH.js.map} +1 -1
- package/src/Configuration.d.ts +43 -21
- package/src/Configuration.js.map +1 -1
- package/src/Content.d.ts +67 -0
- package/src/Content.js +291 -0
- package/src/Content.js.map +1 -0
- package/src/{ContentTransfer-C3Av9sWz.js → ContentTransfer-BhF9G56s.js} +8 -4
- package/src/ContentTransfer-BhF9G56s.js.map +1 -0
- package/src/ContentTransfer-CRQet3QJ.d.ts +48 -0
- package/src/{DocumentEngine-J7g-emdf.js → DocumentEngine-ClhFXW9M.js} +4 -4
- package/src/{DocumentEngine-J7g-emdf.js.map → DocumentEngine-ClhFXW9M.js.map} +1 -1
- package/src/DocumentModel.d.ts +14 -2
- package/src/DocumentModel.js +32 -4
- package/src/DocumentModel.js.map +1 -1
- package/src/{Forms-CfcI3tPU.js → Forms-BbkE7QfC.js} +47 -16
- package/src/Forms-BbkE7QfC.js.map +1 -0
- package/src/{Forms-Dj6NuW66.js → Forms-DoB56hfe.js} +24 -7
- package/src/Forms-DoB56hfe.js.map +1 -0
- package/src/{Forms-BsJMev5_.d.ts → Forms-R0HoTR-o.d.ts} +31 -13
- package/src/Forms.d.ts +23 -11
- package/src/Forms.js.map +1 -1
- package/src/I18n-zbqpWxki.d.ts +29 -0
- package/src/I18n.d.ts +2 -20
- package/src/Module.js +18 -7
- package/src/Module.js.map +1 -1
- package/src/{S3MediaObjects-CpPSzJto.js → S3MediaObjects-D5Ns4FM6.js} +61 -40
- package/src/S3MediaObjects-D5Ns4FM6.js.map +1 -0
- package/src/cli/content.js +63 -221
- package/src/cli/content.js.map +1 -1
- package/src/cli.js +120 -5
- package/src/cli.js.map +1 -1
- package/src/{connection-CBAy2qGy.js → connection-D5S9Iph-.js} +2 -2
- package/src/{connection-CBAy2qGy.js.map → connection-D5S9Iph-.js.map} +1 -1
- package/src/dev-lifecycle-CZ7iCzG9.js +515 -0
- package/src/dev-lifecycle-CZ7iCzG9.js.map +1 -0
- package/src/{installation-CNfIriVm.js → installation-BNuoRDOz.js} +601 -468
- package/src/installation-BNuoRDOz.js.map +1 -0
- package/src/internal/application-types.js +43 -0
- package/src/internal/application-types.js.map +1 -0
- package/src/internal/authoring-catalog.js +9 -4
- package/src/internal/authoring-catalog.js.map +1 -1
- package/src/internal/authoring-metadata.js +1 -1
- package/src/internal/configuration.js +149 -46
- package/src/internal/configuration.js.map +1 -1
- package/src/internal/dev-lifecycle.js +3 -0
- package/src/internal/diagnostics.js +47 -0
- package/src/internal/diagnostics.js.map +1 -0
- package/src/internal/document-model.js +2 -2
- package/src/internal/document-model.js.map +1 -1
- package/src/internal/form-capabilities.js +1 -1
- package/src/internal/i18n.js +27 -1
- package/src/internal/i18n.js.map +1 -1
- package/src/{location-BTqdfIzX.js → location-CPX7oj0o.js} +2 -2
- package/src/{location-BTqdfIzX.js.map → location-CPX7oj0o.js.map} +1 -1
- package/src/{models-B4IoTmp7.js → models-C9kF9JlQ.js} +2 -2
- package/src/{models-B4IoTmp7.js.map → models-C9kF9JlQ.js.map} +1 -1
- package/src/{models-Bah5B3bT.js → models-ChRxBChy.js} +9 -2
- package/src/models-ChRxBChy.js.map +1 -0
- package/src/runtime/delivery/context.js +1 -1
- package/src/runtime/delivery/plugin.js +28 -5
- package/src/runtime/delivery/plugin.js.map +1 -1
- package/src/runtime/delivery/preview.d.ts +1 -1
- package/src/runtime/delivery/types.d.ts +2 -85
- package/src/runtime/delivery/useCmsDocumentSeo.d.ts +8 -1
- package/src/runtime/delivery/useCmsDocumentSeo.js +19 -7
- package/src/runtime/delivery/useCmsDocumentSeo.js.map +1 -1
- package/src/runtime/delivery/useDocument.d.ts +2 -2
- package/src/runtime/delivery/useDocument.js.map +1 -1
- package/src/runtime/delivery/useDocumentQuery.d.ts +3 -3
- package/src/runtime/delivery/useDocumentQuery.js.map +1 -1
- package/src/runtime/forms/document.js +1 -1
- package/src/runtime/forms/useCmsForm.js +89 -45
- package/src/runtime/forms/useCmsForm.js.map +1 -1
- package/src/runtime/i18n/useCmsI18n.d.ts +9 -7
- package/src/runtime/i18n/useCmsI18n.js +5 -4
- package/src/runtime/i18n/useCmsI18n.js.map +1 -1
- package/src/runtime/installation.js +2 -2
- package/src/runtime/plugin.js +12 -4
- package/src/runtime/plugin.js.map +1 -1
- package/src/runtime/preview/connection.js +1 -1
- package/src/runtime/preview/controller.js +2 -2
- package/src/runtime/preview/plugin.client.js +3 -3
- package/src/runtime/preview/store.js +1 -1
- package/src/runtime/sitemap.js +1 -1
- package/src/scalars-CA6kyipS.d.ts +7 -0
- package/src/{store-b2CSXgMt.js → store-B49J21NA.js} +3 -3
- package/src/{store-b2CSXgMt.js.map → store-B49J21NA.js.map} +1 -1
- package/src/types-DutFRtaG.d.ts +90 -0
- package/studio/{CreateDocumentDialog-GGey1uBc.js → CreateDocumentDialog-DJ8c0WZb.js} +3 -3
- package/studio/{documentPlanning-DRErYmBU.js → documentPlanning-CDb31mnl.js} +5935 -5869
- package/studio/host.css +1 -1
- package/studio/host.js +7608 -7250
- package/src/ContentTransfer-C3Av9sWz.js.map +0 -1
- package/src/Forms-CfcI3tPU.js.map +0 -1
- package/src/Forms-Dj6NuW66.js.map +0 -1
- package/src/S3MediaObjects-CpPSzJto.js.map +0 -1
- package/src/installation-CNfIriVm.js.map +0 -1
- package/src/models-Bah5B3bT.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DocumentEngine-J7g-emdf.js","names":["nestedValue","PublicPathSchema","CmsDocumentAnalysisSchema","visit","isDocumentParseFailed","DocumentSourceMappingSchema","EffectResult","CompiledDocumentSchema","DocumentParseFailedError","DocumentValidationResultSchema"],"sources":["../../../../document/src/internal/document-address.ts","../../../../document/src/internal/document-engine/errors.ts","../../../../document/src/internal/comark/analysis.ts","../../../../document/src/internal/document-engine/frontmatter-validation.ts","../../../../document/src/internal/document-engine/compilation.ts","../../../../document/src/internal/document-engine/catalog-lookup.ts","../../../../document/src/internal/document-engine/catalog-issues.ts","../../../../document/src/internal/document-engine/reference-target.ts","../../../../document/src/internal/document-engine/references.ts","../../../../document/src/internal/document-engine/catalog.ts","../../../../document/src/internal/document-engine/configuration.ts","../../../../document/src/DocumentEngine.ts"],"sourcesContent":["import type { AddressPattern, Locale, LocaleConfiguration } from '@internal/protocol/Configuration'\nimport { Predicate, Result, Schema } from 'effect'\nimport { PublicPath as PublicPathSchema, type PublicPath } from '@internal/protocol/Documents'\n\nexport interface DocumentAddressToken {\n readonly catchAll: boolean\n readonly name: string\n}\n\nexport interface DocumentAddress {\n readonly pattern: AddressPattern\n readonly tokens: ReadonlyArray<DocumentAddressToken>\n}\n\nexport interface DocumentAddressError {\n readonly field?: string\n readonly message: string\n}\n\nconst addressTokenPattern = /:([a-z][\\w.]*)(\\*)?/giu\n\nexport function parseDocumentAddress(pattern: AddressPattern): Result.Result<DocumentAddress, DocumentAddressError> {\n const matches = [...pattern.matchAll(addressTokenPattern)]\n\n const tokens = matches.map((match) => ({\n catchAll: match[2] === '*',\n name: match[1] ?? '',\n }))\n\n const remainder = pattern.replace(addressTokenPattern, '')\n\n if (remainder.includes(':') || tokens.some((token) => !token.name)) {\n return Result.fail({\n field: 'addressPattern',\n message: `Document address pattern \"${pattern}\" contains an invalid token.`,\n })\n }\n\n if (tokens.filter((token) => token.catchAll).length > 1) {\n return Result.fail({\n field: 'addressPattern',\n message: `Document address pattern \"${pattern}\" contains more than one catch-all token.`,\n })\n }\n\n if (new Set(tokens.map((token) => token.name)).size !== tokens.length) {\n return Result.fail({\n field: 'addressPattern',\n message: `Document address pattern \"${pattern}\" contains duplicate tokens.`,\n })\n }\n\n return Result.succeed({ pattern, tokens })\n}\n\nexport function resolveDocumentAddress(\n address: DocumentAddress,\n relativeKey: PublicPath,\n data: Schema.JsonObject,\n): Result.Result<PublicPath, DocumentAddressError> {\n const relativePath = relativeKey === '/' ? '' : relativeKey.slice(1)\n let resolved: string = address.pattern\n\n for (const token of address.tokens) {\n const authored = nestedValue(data, token.name)\n const fallback = token.catchAll ? relativePath : undefined\n\n const value =\n authored === undefined ? fallback : Predicate.isString(authored) && authored.trim() ? authored : undefined\n\n if (value === undefined) {\n return Result.fail({\n field: token.name,\n message:\n authored === undefined\n ? `Document address field \"${token.name}\" is required by pattern \"${address.pattern}\".`\n : `Document address field \"${token.name}\" must be a non-empty string.`,\n })\n }\n\n const normalized = token.catchAll ? normalizeDocumentRelativePath(value) : normalizeDocumentSegment(value)\n\n if (Result.isFailure(normalized)) return Result.fail(normalized.failure)\n resolved = resolved.replace(`:${token.name}${token.catchAll ? '*' : ''}`, normalized.success)\n }\n\n return normalizePublicPath(resolved)\n}\n\nexport function documentKeyFromSourcePath(relativeSourcePath: string): Result.Result<PublicPath, DocumentAddressError> {\n const extension = relativeSourcePath.match(/\\.(?:md|mdc)$/iu)?.[0]\n\n if (!extension) {\n return Result.fail({\n field: 'sourcePath',\n message: `Document source must be a Markdown file: \"${relativeSourcePath}\".`,\n })\n }\n\n const segments = relativeSourcePath.slice(0, -extension.length).split('/')\n\n if (segments.at(-1)?.toLocaleLowerCase() === 'index') segments.pop()\n\n return normalizeDocumentRelativePath(segments.join('/')).pipe(Result.flatMap(normalizePublicPath))\n}\n\nexport function localizeDocumentPath(\n key: PublicPath,\n locale: Locale | undefined,\n configuration: LocaleConfiguration | undefined,\n): PublicPath {\n if (!configuration || !locale || (locale === configuration.defaultLocale && !configuration.prefixDefaultLocale)) {\n return key\n }\n\n return PublicPathSchema.make(`/${locale}${key === '/' ? '' : key}`)\n}\n\nexport function normalizePublicPath(value: string): Result.Result<PublicPath, DocumentAddressError> {\n const path = `/${value.replace(/\\\\/gu, '/').replace(/^\\/+|\\/+$/gu, '')}`.replace(/\\/{2,}/gu, '/')\n\n return Schema.decodeResult(PublicPathSchema)(path).pipe(\n Result.mapError(() => ({\n field: 'path',\n message: `Document path \"${value}\" cannot be normalized into a public path.`,\n })),\n )\n}\n\nexport function normalizeDocumentRelativePath(value: string): Result.Result<string, DocumentAddressError> {\n if (!value.trim()) return Result.succeed('')\n\n const segments = value.replace(/\\\\/gu, '/').split('/').filter(Boolean)\n const normalized: string[] = []\n\n for (const segment of segments) {\n const result = normalizeDocumentSegment(segment)\n\n if (Result.isFailure(result)) return result\n normalized.push(result.success)\n }\n\n return Result.succeed(normalized.join('/'))\n}\n\nexport function normalizeDocumentSegment(value: string): Result.Result<string, DocumentAddressError> {\n const normalized = value\n .trim()\n .normalize('NFKC')\n .toLocaleLowerCase()\n .replace(/[^\\p{Letter}\\p{Number}_-]+/gu, '-')\n .replace(/^-+|-+$/gu, '')\n\n return normalized\n ? Result.succeed(normalized)\n : Result.fail({ message: `Document path segment \"${value}\" is empty after normalization.` })\n}\n\nfunction nestedValue(value: Schema.JsonObject, path: string): Schema.Json | undefined {\n return path.split('.').reduce<Schema.Json | undefined>((current, segment) => {\n if (!Schema.is(Schema.JsonObject)(current)) return undefined\n\n return current[segment]\n }, value)\n}\n","import { DocumentIssue } from '@internal/protocol/Documents'\nimport { SourcePath } from '@internal/protocol/Documents'\nimport { Schema } from 'effect'\n\nexport class DocumentEngineConfigurationInvalid extends Schema.TaggedError<DocumentEngineConfigurationInvalid>()(\n 'DocumentEngine.ConfigurationInvalid',\n {\n message: Schema.NonEmptyString,\n field: Schema.optionalKey(Schema.NonEmptyString),\n },\n) {}\n\nexport class DocumentParseFailed extends Schema.TaggedError<DocumentParseFailed>()(\n 'DocumentEngine.DocumentParseFailed',\n {\n sourcePath: SourcePath,\n cause: Schema.Defect(),\n },\n) {}\n\nexport class DocumentCompilationFailed extends Schema.TaggedError<DocumentCompilationFailed>()(\n 'DocumentEngine.DocumentCompilationFailed',\n {\n issues: Schema.Array(DocumentIssue),\n },\n) {}\n","import type { CmsDocumentAnalysis, CmsMarkdownDocument, MarkdownNode } from '@internal/protocol/Documents'\nimport { CmsDocumentAnalysis as CmsDocumentAnalysisSchema } from '@internal/protocol/Documents'\nimport { Predicate } from 'effect'\nimport { cmsComarkTextContent } from './document-adapter'\n\nexport const CMS_STANDARD_TAGS = new Set([\n 'a',\n 'abbr',\n 'address',\n 'article',\n 'aside',\n 'b',\n 'blockquote',\n 'br',\n 'button',\n 'caption',\n 'code',\n 'col',\n 'colgroup',\n 'dd',\n 'del',\n 'details',\n 'div',\n 'dl',\n 'dt',\n 'em',\n 'figcaption',\n 'figure',\n 'footer',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hr',\n 'i',\n 'img',\n 'kbd',\n 'li',\n 'main',\n 'mark',\n 'nav',\n 'ol',\n 'p',\n 'pre',\n 'q',\n 's',\n 'section',\n 'small',\n 'span',\n 'strong',\n 'sub',\n 'summary',\n 'sup',\n 'table',\n 'tbody',\n 'td',\n 'template',\n 'tfoot',\n 'th',\n 'thead',\n 'tr',\n 'u',\n 'ul',\n])\n\nexport function analyzeCmsDocument(\n body: CmsMarkdownDocument,\n metadata: { readonly description?: string; readonly title: string },\n): CmsDocumentAnalysis {\n const headings: Array<{ readonly depth: number; readonly id: string; readonly text: string }> = []\n const components = new Set<string>()\n\n visit(body.nodes, (node) => {\n const tag = node[0].toLocaleLowerCase()\n\n if (/^h[1-6]$/u.test(tag)) {\n headings.push({\n depth: Number(tag.slice(1)),\n id: Predicate.isString(node[1].id) ? node[1].id : '',\n text: cmsComarkTextContent(node).trim(),\n })\n } else if (!CMS_STANDARD_TAGS.has(tag)) {\n components.add(tag)\n }\n })\n\n const bodyText = normalizeText(body.nodes.map(cmsComarkTextContent).join(' '))\n const summary = normalizeText(metadata.description ?? firstParagraph(body.nodes) ?? metadata.title)\n const searchText = normalizeText([metadata.title, metadata.description, bodyText].filter(Boolean).join(' '))\n\n return CmsDocumentAnalysisSchema.make({\n components: [...components].sort(),\n headings,\n searchText,\n summary,\n })\n}\n\nfunction visit(\n nodes: ReadonlyArray<MarkdownNode>,\n inspect: (node: Exclude<MarkdownNode, string | readonly [null, object, string]>) => void,\n): void {\n for (const node of nodes) {\n if (Predicate.isString(node) || node[0] === null) continue\n inspect(node)\n const [, , ...children] = node\n visit(children, inspect)\n }\n}\n\nfunction firstParagraph(nodes: ReadonlyArray<MarkdownNode>): string | undefined {\n const paragraph = nodes.find((node) => Array.isArray(node) && node[0] === 'p')\n\n if (!paragraph || Predicate.isString(paragraph) || paragraph[0] === null) return undefined\n const text = normalizeText(cmsComarkTextContent(paragraph))\n\n return text || undefined\n}\n\nfunction normalizeText(value: string): string {\n return value.replace(/\\s+/gu, ' ').trim()\n}\n","import type { CollectionDefinition } from '@internal/protocol/Configuration'\nimport type { DocumentIssue } from '@internal/protocol/Documents'\nimport type { SourcePath } from '@internal/protocol/Documents'\nimport type { DocumentSchemaIssue, ExecutableDocumentSchema } from './document-schema'\nimport { Effect, Option, Predicate, Schema } from 'effect'\n\nexport const validateFrontmatter = Effect.fn('DocumentEngine.validateFrontmatter')(function* (\n raw: Schema.JsonObject,\n schema: ExecutableDocumentSchema,\n type: CollectionDefinition,\n sourcePath: SourcePath,\n) {\n const projection = schema.project(raw)\n\n const issues = projection.unknownPaths\n .toSorted()\n .map((path): DocumentIssue => unknownFieldIssue(path, type, sourcePath))\n\n const result = yield* schema.validate(projection.value)\n\n if ('issues' in result) {\n issues.push(...result.issues.map((issue) => schemaIssue(issue, projection.value, type, sourcePath)))\n\n return { data: projection.value, issues }\n }\n\n const parsed = Schema.decodeUnknownOption(Schema.JsonObject)(result.value)\n\n if (Option.isNone(parsed)) {\n issues.push(\n issue(\n 'schema.constraint',\n 'The collection schema output must be a JSON-compatible object.',\n type,\n sourcePath,\n 'frontmatter',\n ),\n )\n\n return { data: projection.value, issues }\n }\n\n return issues.length === 0 ? { data: parsed.value, issues } : { data: projection.value, issues }\n})\n\nfunction unknownFieldIssue(path: string, type: CollectionDefinition, sourcePath: SourcePath): DocumentIssue {\n if (path === 'id') {\n return issue(\n 'document.id',\n 'Document identity is managed by the CMS and cannot be authored in frontmatter.',\n type,\n sourcePath,\n path,\n )\n }\n\n return issue(\n 'schema.unknown',\n `Frontmatter field \"${path}\" is not declared by collection \"${type.collection}\".`,\n type,\n sourcePath,\n path,\n )\n}\n\nfunction schemaIssue(\n error: DocumentSchemaIssue,\n input: Schema.JsonObject,\n type: CollectionDefinition,\n sourcePath: SourcePath,\n): DocumentIssue {\n const field = issuePath(error.path)\n const code = issueCode(error, input, field)\n\n return issue(code, error.message, type, sourcePath, field || undefined)\n}\n\nfunction issueCode(error: DocumentSchemaIssue, input: Schema.JsonObject, field: string): DocumentIssue['code'] {\n if (error.code === 'invalid_type') return nestedValue(input, field) === undefined ? 'schema.required' : 'schema.type'\n\n if (error.code === 'invalid_value') return 'schema.option'\n\n return 'schema.constraint'\n}\n\nfunction issuePath(path: DocumentSchemaIssue['path']): string {\n return (path ?? [])\n .map((segment) => (Predicate.hasProperty(segment, 'key') ? segment.key : segment))\n .map(String)\n .join('.')\n}\n\nfunction nestedValue(value: Schema.JsonObject, path: string): Schema.Json | undefined {\n if (!path) return value\n\n return path.split('.').reduce<Schema.Json | undefined>((current, segment) => {\n if (Array.isArray(current)) {\n const index = Number(segment)\n\n return Number.isSafeInteger(index) ? current[index] : undefined\n }\n\n return Schema.is(Schema.JsonObject)(current) ? current[segment] : undefined\n }, value)\n}\n\nfunction issue(\n code: DocumentIssue['code'],\n message: string,\n type: CollectionDefinition,\n sourcePath: SourcePath,\n field?: string,\n): DocumentIssue {\n return {\n code,\n collection: type.collection,\n ...(field === undefined ? undefined : { field }),\n message,\n severity: 'error',\n sourcePath,\n }\n}\n","import type {\n DocumentIssue,\n DocumentSourceMapping,\n CmsMarkdownDocument as MarkdownDocumentType,\n} from '@internal/protocol/Documents'\nimport type { DocumentSeo as DocumentSeoType } from '@internal/protocol/Seo'\nimport type { Locale } from '@internal/protocol/Configuration'\nimport type { ComarkParseFn } from 'comark'\nimport type { DocumentCompilationSource } from './compilation-source'\nimport type { ResolvedDocumentEngineConfiguration, ResolvedCollection } from './configuration'\nimport {\n CompiledDocument,\n DocumentSourceMapping as DocumentSourceMappingSchema,\n CmsMarkdownDocument,\n} from '@internal/protocol/Documents'\nimport { PublicPath } from '@internal/protocol/Documents'\nimport { documentKeyFromSourcePath, localizeDocumentPath, resolveDocumentAddress } from '../document-address'\nimport { DocumentSeo } from '@internal/protocol/Seo'\nimport { Effect, Predicate, Result, Schema } from 'effect'\nimport { DocumentCompilationFailed, DocumentParseFailed } from './errors'\nimport { normalizeCmsComponentBindings } from '../comark/bindings'\nimport { analyzeCmsDocument } from '../comark/analysis'\nimport { DOCUMENT_ENGINE_FINGERPRINT } from '../comark/grammar'\nimport { validateFrontmatter } from './frontmatter-validation'\nimport { SOURCE_MAPPINGS_META_KEY } from '../comark/source-mapping'\n\nconst isDocumentParseFailed = Schema.is(DocumentParseFailed)\n\nexport const compileCompiledDocument = Effect.fn('DocumentEngine.compileDocument')(function* (\n configuration: ResolvedDocumentEngineConfiguration,\n parseMarkdown: ComarkParseFn,\n source: DocumentCompilationSource,\n) {\n const location = yield* resolveSourceLocation(configuration, source)\n const parsedBody = yield* parseBody(parseMarkdown, source)\n const mappings = yield* sourceMappings(parsedBody, source)\n const body = normalizeCmsComponentBindings(withoutSourceMappings(parsedBody), configuration.components)\n const { collectionFrontmatter, rawSeo } = splitFrontmatter(body.frontmatter)\n const seoProjection = projectSeo(rawSeo, source.sourcePath)\n\n const relativeKey = yield* fromAddressResult(\n documentKeyFromSourcePath(location.relativeSourcePath),\n source.sourcePath,\n )\n\n const validation = yield* validateFrontmatter(\n collectionFrontmatter,\n location.type.schema,\n location.type.definition,\n source.sourcePath,\n ).pipe(\n Effect.mapError(\n (cause) =>\n new DocumentCompilationFailed({\n issues: [\n {\n code: 'schema.constraint',\n collection: location.type.definition.collection,\n message: cause.message,\n severity: 'error',\n sourcePath: source.sourcePath,\n },\n ],\n }),\n ),\n )\n\n const address = resolveDocumentAddress(location.type.address, relativeKey, validation.data)\n const key = Result.isSuccess(address) ? address.success : provisionalKey(source.documentId)\n const path = localizeDocumentPath(key, location.locale, configuration.documents.locales)\n\n const title =\n stringValue(validation.data.title) ?? stringValue(body.meta.title) ?? titleFromSource(location.relativeSourcePath)\n\n const description = stringValue(validation.data.description) ?? stringValue(body.meta.description)\n\n const issues = Result.isSuccess(address)\n ? validation.issues\n : [...validation.issues, addressIssue(address.failure, source.sourcePath)]\n\n const canonicalFrontmatter = rawSeo === undefined ? validation.data : Object.assign({ _seo: rawSeo }, validation.data)\n\n const canonicalBody = CmsMarkdownDocument.make({\n frontmatter: canonicalFrontmatter,\n meta: body.meta,\n nodes: body.nodes,\n })\n\n const analysis = analyzeCmsDocument(canonicalBody, description === undefined ? { title } : { description, title })\n\n return CompiledDocument.make(\n Object.assign(\n {\n id: source.documentId,\n key,\n path,\n collection: location.type.definition.collection,\n draft: source.draft,\n title,\n data: validation.data,\n issues: [\n ...issues,\n ...seoProjection.issues,\n ...(configuration.validateAuthoringDocument?.(canonicalBody, location.type.definition.body) ?? []).map(\n (message): DocumentIssue => ({\n code: 'reference.component',\n message,\n severity: 'error',\n sourcePath: source.sourcePath,\n }),\n ),\n ],\n analysis,\n body: canonicalBody,\n engineFingerprint: DOCUMENT_ENGINE_FINGERPRINT,\n source: {\n path: source.sourcePath,\n mappings,\n ...(source.publishedAt === undefined ? undefined : { publishedAt: source.publishedAt }),\n },\n },\n location.locale === undefined ? undefined : { locale: location.locale },\n description === undefined ? undefined : { description },\n seoProjection.seo === undefined ? undefined : { seo: seoProjection.seo },\n ),\n )\n})\n\ninterface FrontmatterProjection {\n readonly collectionFrontmatter: Schema.JsonObject\n readonly rawSeo: Schema.Json | undefined\n}\n\nfunction splitFrontmatter(frontmatter: Schema.JsonObject): FrontmatterProjection {\n const { _seo: rawSeo, ...collectionFrontmatter } = frontmatter\n\n return { collectionFrontmatter, rawSeo }\n}\n\ninterface SeoProjection {\n readonly seo?: DocumentSeoType\n readonly issues: ReadonlyArray<DocumentIssue>\n}\n\nfunction projectSeo(\n rawSeo: Schema.Json | undefined,\n sourcePath: DocumentCompilationSource['sourcePath'],\n): SeoProjection {\n if (rawSeo === undefined) return { issues: [] }\n\n const decoded = Schema.decodeUnknownResult(DocumentSeo)(rawSeo, { onExcessProperty: 'error' })\n\n if (Result.isSuccess(decoded)) return { issues: [], seo: decoded.success }\n\n return {\n issues: [\n {\n code: 'seo.invalid',\n field: '_seo',\n message: `Document SEO is invalid: ${String(decoded.failure)}`,\n severity: 'error',\n sourcePath,\n },\n ],\n }\n}\n\nfunction provisionalKey(documentId: DocumentCompilationSource['documentId']): PublicPath {\n return PublicPath.make(`/_cms-invalid/${documentId}`)\n}\n\nfunction addressIssue(\n error: { readonly field?: string; readonly message: string },\n sourcePath: DocumentCompilationSource['sourcePath'],\n): DocumentIssue {\n const issue = {\n code: 'document.invalid' as const,\n message: error.message,\n severity: 'error' as const,\n sourcePath,\n }\n\n return error.field === undefined ? issue : { ...issue, field: error.field }\n}\n\ninterface SourceLocation {\n readonly locale?: Locale\n readonly relativeSourcePath: string\n readonly type: ResolvedCollection\n}\n\nfunction resolveSourceLocation(\n configuration: ResolvedDocumentEngineConfiguration,\n source: DocumentCompilationSource,\n): Effect.Effect<SourceLocation, DocumentCompilationFailed> {\n const segments = source.sourcePath.split('/')\n let locale: Locale | undefined\n\n if (configuration.documents.locales) {\n const candidate = segments.shift()\n locale = configuration.documents.locales.locales.find((value) => value === candidate)\n\n if (!locale) {\n return compilationFailure({\n code: 'document.invalid',\n field: 'locale',\n message: `Localized document \"${source.sourcePath}\" must begin with a configured locale.`,\n severity: 'error',\n sourcePath: source.sourcePath,\n })\n }\n }\n\n const localizedSourcePath = segments.join('/')\n\n const type = configuration.types.find(\n ({ definition }) => definition.directory === '.' || localizedSourcePath.startsWith(`${definition.directory}/`),\n )\n\n if (!type) {\n return compilationFailure({\n code: 'document.invalid',\n field: 'sourcePath',\n message: `No document collection contains \"${source.sourcePath}\".`,\n severity: 'error',\n sourcePath: source.sourcePath,\n })\n }\n\n const relativeSourcePath =\n type.definition.directory === '.'\n ? localizedSourcePath\n : localizedSourcePath.slice(type.definition.directory.length + 1)\n\n if (!relativeSourcePath) {\n return compilationFailure({\n code: 'document.invalid',\n field: 'sourcePath',\n message: `Document source \"${source.sourcePath}\" has no collection-relative path.`,\n severity: 'error',\n sourcePath: source.sourcePath,\n })\n }\n\n return Effect.succeed(locale === undefined ? { relativeSourcePath, type } : { locale, relativeSourcePath, type })\n}\n\nfunction parseBody(\n parseMarkdown: ComarkParseFn,\n source: DocumentCompilationSource,\n): Effect.Effect<MarkdownDocumentType, DocumentParseFailed> {\n return Effect.tryPromise({\n try: () => parseMarkdown(source.markdown),\n catch: (cause) => new DocumentParseFailed({ cause, sourcePath: source.sourcePath }),\n }).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(CmsMarkdownDocument)),\n Effect.mapError((cause) =>\n isDocumentParseFailed(cause) ? cause : new DocumentParseFailed({ cause, sourcePath: source.sourcePath }),\n ),\n )\n}\n\nfunction sourceMappings(\n body: MarkdownDocumentType,\n source: DocumentCompilationSource,\n): Effect.Effect<ReadonlyArray<DocumentSourceMapping>, DocumentParseFailed> {\n return Schema.decodeUnknownEffect(Schema.Array(DocumentSourceMappingSchema))(\n body.meta[SOURCE_MAPPINGS_META_KEY] ?? [],\n ).pipe(Effect.mapError((cause) => new DocumentParseFailed({ cause, sourcePath: source.sourcePath })))\n}\n\nfunction withoutSourceMappings(body: MarkdownDocumentType): MarkdownDocumentType {\n const { [SOURCE_MAPPINGS_META_KEY]: _mappings, ...meta } = body.meta\n\n return CmsMarkdownDocument.make({ frontmatter: body.frontmatter, meta, nodes: body.nodes })\n}\n\nfunction fromAddressResult<A>(\n result: Result.Result<A, { readonly field?: string; readonly message: string }>,\n sourcePath: DocumentCompilationSource['sourcePath'],\n): Effect.Effect<A, DocumentCompilationFailed> {\n if (Result.isSuccess(result)) return Effect.succeed(result.success)\n\n return compilationFailure(addressIssue(result.failure, sourcePath))\n}\n\nfunction compilationFailure(issue: DocumentIssue): Effect.Effect<never, DocumentCompilationFailed> {\n return Effect.fail(new DocumentCompilationFailed({ issues: [issue] }))\n}\n\nfunction stringValue(value: Schema.Json | undefined): string | undefined {\n return Predicate.isString(value) && value.trim() ? value.trim() : undefined\n}\n\nfunction titleFromSource(sourcePath: string): string {\n const file = sourcePath.split('/').at(-1) ?? 'content'\n const stem = file.replace(/\\.(?:md|mdc)$/iu, '')\n const title = stem.toLocaleLowerCase() === 'index' ? (sourcePath.split('/').at(-2) ?? 'home') : stem\n\n return title.replace(/[-_]+/gu, ' ').replace(/^./u, (character) => character.toLocaleUpperCase())\n}\n","import type { Locale } from '@internal/protocol/Configuration'\nimport type { CompiledDocument, PublicPath } from '@internal/protocol/Documents'\nimport type { ResolvedDocumentEngineConfiguration } from './configuration'\nimport { normalizePublicPath } from '../document-address'\nimport { Option, Result } from 'effect'\n\nexport interface CatalogLookup {\n readonly findByKey: (key: string, locale?: Locale) => Option.Option<CompiledDocument>\n readonly findByPath: (path: string) => Option.Option<CompiledDocument>\n}\n\nexport function createCatalogLookup(\n documents: ReadonlyArray<CompiledDocument>,\n configuration: ResolvedDocumentEngineConfiguration,\n): CatalogLookup {\n const byPath = new Map(documents.map((document) => [document.path, document]))\n const byVariant = new Map(documents.map((document) => [localeAndKey(document.locale, document.key), document]))\n\n const findByKey = (input: string, locale?: Locale) => {\n const keyResult = normalizePublicPath(input)\n\n if (Result.isFailure(keyResult)) return Option.none<CompiledDocument>()\n const key = keyResult.success\n const locales = configuration.documents.locales\n\n if (!locales) return Option.fromNullishOr(byVariant.get(localeAndKey(undefined, key)))\n const requestedLocale = locale ?? locales.defaultLocale\n const localized = byVariant.get(localeAndKey(requestedLocale, key))\n\n if (localized) return Option.some(localized)\n\n if (!locales.fallbackLocale) return Option.none()\n\n return Option.fromNullishOr(byVariant.get(localeAndKey(locales.fallbackLocale, key)))\n }\n\n const findByPath = (input: string) => {\n const pathResult = normalizePublicPath(input)\n\n if (Result.isFailure(pathResult)) return Option.none<CompiledDocument>()\n const path = pathResult.success\n const direct = byPath.get(path)\n\n if (direct) return Option.some(direct)\n\n const locales = configuration.documents.locales\n\n if (!locales) return Option.none()\n const request = localizedRequest(path, locales.locales, locales.defaultLocale, locales.prefixDefaultLocale)\n\n if (!request) return Option.none()\n const localized = byVariant.get(localeAndKey(request.locale, request.key))\n\n if (localized) return Option.some(localized)\n\n if (!locales.fallbackLocale) return Option.none()\n\n return Option.fromNullishOr(byVariant.get(localeAndKey(locales.fallbackLocale, request.key)))\n }\n\n return { findByKey, findByPath }\n}\n\nexport function localeAndKey(locale: Locale | undefined, key: PublicPath): string {\n return `${locale ?? ''}:${key}`\n}\n\nfunction localizedRequest(\n path: PublicPath,\n locales: ReadonlyArray<Locale>,\n defaultLocale: Locale,\n prefixDefaultLocale: boolean,\n): { readonly key: PublicPath; readonly locale: Locale } | undefined {\n const segments = path === '/' ? [] : path.slice(1).split('/')\n const possibleLocale = locales.find((locale) => locale === segments[0])\n\n const prefixedLocale =\n possibleLocale && (possibleLocale !== defaultLocale || prefixDefaultLocale) ? possibleLocale : undefined\n\n if (prefixedLocale) {\n const keyResult = normalizePublicPath(segments.slice(1).join('/'))\n\n return Result.isSuccess(keyResult) ? { key: keyResult.success, locale: prefixedLocale } : undefined\n }\n\n if (prefixDefaultLocale) return undefined\n\n return { key: path, locale: defaultLocale }\n}\n","import type { CompiledDocument, DocumentIssue, PublicPath } from '@internal/protocol/Documents'\nimport type { ResolvedDocumentEngineConfiguration } from './configuration'\nimport { localeAndKey } from './catalog-lookup'\n\nexport function collisionIssues(documents: ReadonlyArray<CompiledDocument>): DocumentIssue[] {\n const issues: DocumentIssue[] = []\n const byId = new Map<string, CompiledDocument>()\n const byPath = new Map<string, CompiledDocument>()\n const byVariant = new Map<string, CompiledDocument>()\n\n for (const document of documents) {\n const identityCollision = byId.get(document.id)\n\n if (identityCollision) {\n issues.push(\n collisionIssue(\n `Document identity collision for \"${document.id}\" between \"${identityCollision.source.path}\" and \"${document.source.path}\".`,\n document,\n ),\n )\n } else byId.set(document.id, document)\n\n const pathCollision = byPath.get(document.path)\n\n if (pathCollision) {\n issues.push(\n collisionIssue(\n `Document route collision at \"${document.path}\" between \"${pathCollision.source.path}\" and \"${document.source.path}\".`,\n document,\n document.path,\n ),\n )\n } else byPath.set(document.path, document)\n\n const variant = localeAndKey(document.locale, document.key)\n const variantCollision = byVariant.get(variant)\n\n if (variantCollision && variantCollision.path !== pathCollision?.path) {\n issues.push(\n collisionIssue(\n `Document locale collision at \"${document.key}\" between \"${variantCollision.source.path}\" and \"${document.source.path}\".`,\n document,\n document.key,\n ),\n )\n } else byVariant.set(variant, document)\n }\n\n return issues\n}\n\nexport function translationIssues(\n documents: ReadonlyArray<CompiledDocument>,\n configuration: ResolvedDocumentEngineConfiguration,\n): DocumentIssue[] {\n const locales = configuration.documents.locales\n\n if (!locales) return []\n const variants = new Set(documents.map((document) => localeAndKey(document.locale, document.key)))\n const keys = new Set(documents.map((document) => document.key))\n\n return [...keys].flatMap((key) =>\n locales.locales.flatMap((locale): DocumentIssue[] =>\n variants.has(localeAndKey(locale, key))\n ? []\n : [\n {\n code: 'i18n.missing-translation',\n key,\n locale,\n message: `Document \"${key}\" is missing its \"${locale}\" translation.`,\n severity: 'warning',\n },\n ],\n ),\n )\n}\n\nfunction collisionIssue(message: string, document: CompiledDocument, key?: PublicPath): DocumentIssue {\n const issue = {\n code: 'document.collision' as const,\n message,\n severity: 'error' as const,\n sourcePath: document.source.path,\n }\n\n return key === undefined ? issue : Object.assign(issue, { key })\n}\n","import type { PublicPath } from '@internal/protocol/Documents'\nimport type { MediaId } from '@internal/protocol/Media'\nimport type { CmsComarkAttributeValue, CmsComarkAttributes } from '../comark/bindings'\nimport { normalizePublicPath } from '../document-address'\nimport { Predicate, Result } from 'effect'\nimport { CMS_STANDARD_TAGS } from '../comark/analysis'\n\nexport type DocumentReferenceTarget =\n | { readonly kind: 'component'; readonly name: string }\n | { readonly kind: 'document'; readonly path: PublicPath }\n | { readonly kind: 'media'; readonly key: string; readonly mediaId?: MediaId }\n\nexport function referenceTarget(\n tag: string,\n attributes: CmsComarkAttributes,\n documentPath: PublicPath,\n mediaBaseUrl: string | undefined,\n): DocumentReferenceTarget | undefined {\n if (tag === 'a') {\n const path = documentTarget(attributes.get('href'), documentPath)\n\n return path ? { kind: 'document', path } : undefined\n }\n\n if (tag === 'img') {\n const key = mediaKey(attributes.get('src'), mediaBaseUrl)\n\n return key ? { kind: 'media', key } : undefined\n }\n\n const normalizedTag = tag.toLocaleLowerCase()\n\n return CMS_STANDARD_TAGS.has(normalizedTag) ? undefined : { kind: 'component', name: normalizedTag }\n}\n\nexport function targetKey(target: DocumentReferenceTarget): string {\n switch (target.kind) {\n case 'component':\n return `component:${target.name.toLocaleLowerCase()}`\n case 'document':\n return `document:${target.path}`\n case 'media':\n return `media:${target.key}`\n }\n}\n\nfunction mediaKey(value: CmsComarkAttributeValue, mediaBaseUrl: string | undefined): string | undefined {\n if (!Predicate.isString(value) || mediaBaseUrl === undefined) return undefined\n const prefix = `${mediaBaseUrl}/`\n\n if (!value.startsWith(prefix)) return undefined\n const encodedKey = value.slice(prefix.length).split(/[?#]/u, 1)[0]\n\n if (!encodedKey) return undefined\n\n try {\n const segments = encodedKey.split('/').map(decodeURIComponent)\n\n if (\n segments.some(\n (segment) =>\n !segment ||\n segment === '.' ||\n segment === '..' ||\n segment.includes('/') ||\n segment.includes('\\\\') ||\n hasControlCharacter(segment),\n )\n ) {\n return undefined\n }\n\n const key = segments.join('/')\n\n return key.startsWith('media/') ? key : undefined\n } catch {\n return undefined\n }\n}\n\nfunction documentTarget(value: CmsComarkAttributeValue, documentPath: PublicPath): PublicPath | undefined {\n if (!Predicate.isString(value)) return undefined\n const href = value.trim()\n\n if (\n !href ||\n href.startsWith('#') ||\n href.startsWith('?') ||\n href.startsWith('//') ||\n /^[a-z][a-z\\d+.-]*:/iu.test(href)\n ) {\n return undefined\n }\n\n const path = href.split(/[?#]/u)[0] ?? ''\n const resolvedPath = resolveRelativePath(path, documentPath)\n const lastSegment = resolvedPath.split('/').at(-1) ?? ''\n\n if (lastSegment.includes('.')) return undefined\n const normalized = normalizePublicPath(resolvedPath)\n\n return Result.isSuccess(normalized) ? normalized.success : undefined\n}\n\nfunction resolveRelativePath(href: string, documentPath: PublicPath): string {\n const normalizedHref = href.replace(/\\\\/gu, '/')\n const segments = normalizedHref.startsWith('/') ? [] : documentPath.split('/').filter(Boolean).slice(0, -1)\n\n for (const segment of normalizedHref.split('/')) {\n if (!segment || segment === '.') continue\n\n if (segment === '..') segments.pop()\n else segments.push(segment)\n }\n\n return `/${segments.join('/')}`\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0)\n\n if (codePoint !== undefined && (codePoint <= 31 || codePoint === 127)) return true\n }\n\n return false\n}\n","import type { BlockProp } from '@internal/protocol/Authoring'\nimport type { CompiledDocument, DocumentId, DocumentIssue, MarkdownNode } from '@internal/protocol/Documents'\nimport type { PublicPath, SourcePath } from '@internal/protocol/Documents'\nimport type { CmsComarkAttributes } from '../comark/bindings'\nimport type { NodeRenderData } from 'comark'\nimport type { ResolvedDocumentEngineConfiguration } from './configuration'\nimport type { DocumentReferenceTarget } from './reference-target'\nimport { Option, Predicate, Schema } from 'effect'\nimport { resolveCmsComarkAttributes, withCmsComarkProps } from '../comark/bindings'\nimport { createCmsComarkRenderData } from '../comark/document-adapter'\nimport { referenceTarget, targetKey } from './reference-target'\n\nexport type { DocumentReferenceTarget } from './reference-target'\n\nexport interface DocumentReference {\n readonly nodePath: ReadonlyArray<number>\n readonly source: {\n readonly documentId: DocumentId\n readonly path: PublicPath\n readonly sourcePath: SourcePath\n }\n readonly target: DocumentReferenceTarget\n}\n\nexport interface DocumentReferenceIndex {\n readonly all: ReadonlyArray<DocumentReference>\n readonly impact: (target: DocumentReferenceTarget) => ReadonlyArray<DocumentReference>\n}\n\ninterface IndexedDocumentReferences {\n readonly index: DocumentReferenceIndex\n readonly issues: ReadonlyMap<SourcePath, ReadonlyArray<DocumentIssue>>\n}\n\nconst noReferences: ReadonlyArray<DocumentReference> = Object.freeze([])\n\nexport function createDocumentReferenceIndex(\n documents: ReadonlyArray<CompiledDocument>,\n configuration: ResolvedDocumentEngineConfiguration,\n findByPath: (path: string) => Option.Option<CompiledDocument>,\n): IndexedDocumentReferences {\n const all: DocumentReference[] = []\n const byTarget = new Map<string, DocumentReference[]>()\n const issues = new Map<SourcePath, DocumentIssue[]>()\n\n for (const document of documents) {\n const indexTarget = (target: DocumentReferenceTarget | undefined, nodePath: ReadonlyArray<number>): void => {\n if (!target) return\n\n const reference = freezeReference({\n nodePath,\n source: {\n documentId: document.id,\n path: document.path,\n sourcePath: document.source.path,\n },\n target,\n })\n\n all.push(reference)\n const key = targetKey(target)\n const matching = byTarget.get(key) ?? []\n matching.push(reference)\n byTarget.set(key, matching)\n\n if (target.kind === 'document' && Option.isNone(findByPath(target.path))) {\n addIssue(issues, document.source.path, {\n code: 'reference.document',\n key: target.path,\n message: `Document link \"${target.path}\" does not resolve.`,\n severity: 'error',\n sourcePath: document.source.path,\n })\n }\n }\n\n const seoImageTarget = document.seo?.socialImage\n ? referenceTarget(\n 'img',\n new Map([['src', document.seo.socialImage.url]]),\n document.path,\n configuration.mediaBaseUrl,\n )\n : undefined\n\n indexTarget(\n seoImageTarget?.kind === 'media'\n ? Object.assign({}, seoImageTarget, { mediaId: document.seo?.socialImage?.mediaId })\n : seoImageTarget,\n [],\n )\n\n visit(document.body.nodes, createCmsComarkRenderData(document.body), (tag, attributes, children, nodePath) => {\n const targets = [\n referenceTarget(tag, attributes, document.path, configuration.mediaBaseUrl),\n ...propertyTargets(\n configuration.components?.get(tag.toLowerCase())?.authoring.props ?? [],\n Object.fromEntries([...attributes].flatMap(([key, value]) => (value === undefined ? [] : [[key, value]]))),\n document.path,\n configuration.mediaBaseUrl,\n ),\n ]\n\n for (const target of targets) indexTarget(target, nodePath)\n })\n }\n\n const frozenAll = Object.freeze(all)\n const frozenByTarget = new Map([...byTarget].map(([key, references]) => [key, Object.freeze(references)] as const))\n\n return {\n index: Object.freeze({\n all: frozenAll,\n impact: (target: DocumentReferenceTarget) => frozenByTarget.get(targetKey(target)) ?? noReferences,\n }),\n issues,\n }\n}\n\nfunction visit(\n nodes: CompiledDocument['body']['nodes'],\n renderData: NodeRenderData,\n onElement: (\n tag: string,\n attributes: CmsComarkAttributes,\n children: ReadonlyArray<MarkdownNode>,\n nodePath: ReadonlyArray<number>,\n ) => void,\n parentPath: ReadonlyArray<number> = [],\n): void {\n nodes.forEach((node, index) => {\n if (Predicate.isString(node) || node[0] === null) return\n const [tag, attributes, ...children] = node\n const nodePath = [...parentPath, index]\n const resolved = resolveCmsComarkAttributes(attributes, renderData)\n onElement(tag, resolved, children, nodePath)\n const childrenRenderData = withCmsComarkProps(renderData, resolved)\n visit(children, childrenRenderData, onElement, nodePath)\n })\n}\n\nfunction freezeReference(reference: DocumentReference): DocumentReference {\n return Object.freeze({\n nodePath: Object.freeze([...reference.nodePath]),\n source: Object.freeze({ ...reference.source }),\n target: Object.freeze({ ...reference.target }),\n })\n}\n\nfunction addIssue(issues: Map<SourcePath, DocumentIssue[]>, sourcePath: SourcePath, issue: DocumentIssue): void {\n const sourceIssues = issues.get(sourcePath) ?? []\n sourceIssues.push(issue)\n issues.set(sourcePath, sourceIssues)\n}\n\nfunction propertyTargets(\n fields: ReadonlyArray<BlockProp>,\n values: Schema.JsonObject,\n path: PublicPath,\n mediaBaseUrl: string | undefined,\n): DocumentReferenceTarget[] {\n return fields.flatMap((field) => {\n const value = values[field.name] === undefined ? field.defaultValue : values[field.name]\n\n if (field.input === 'link' || field.input === 'image') {\n const target = referenceTarget(\n field.input === 'link' ? 'a' : 'img',\n new Map([[field.input === 'link' ? 'href' : 'src', value]]),\n path,\n mediaBaseUrl,\n )\n\n return target ? [target] : []\n }\n\n if (field.fields)\n return (Array.isArray(value) ? value : [value]).flatMap((entry) =>\n Schema.is(Schema.JsonObject)(entry) ? propertyTargets(field.fields ?? [], entry, path, mediaBaseUrl) : [],\n )\n\n return []\n })\n}\n","import type { Locale } from '@internal/protocol/Configuration'\nimport type { CompiledDocument, DocumentIssue } from '@internal/protocol/Documents'\nimport type { Option, Result } from 'effect'\nimport type { ResolvedDocumentEngineConfiguration } from './configuration'\nimport type { DocumentReferenceIndex } from './references'\nimport { CompiledDocument as CompiledDocumentSchema } from '@internal/protocol/Documents'\nimport { Result as EffectResult } from 'effect'\nimport { collisionIssues, translationIssues } from './catalog-issues'\nimport { createCatalogLookup } from './catalog-lookup'\nimport { DocumentCompilationFailed } from './errors'\nimport { createDocumentReferenceIndex } from './references'\n\nexport interface DocumentCatalog {\n readonly documents: ReadonlyArray<CompiledDocument>\n readonly issues: ReadonlyArray<DocumentIssue>\n readonly findByKey: (key: string, locale?: Locale) => Option.Option<CompiledDocument>\n readonly findByPath: (path: string) => Option.Option<CompiledDocument>\n readonly references: DocumentReferenceIndex\n}\n\nexport function createDocumentCatalog(\n configuration: ResolvedDocumentEngineConfiguration,\n input: ReadonlyArray<CompiledDocument>,\n): Result.Result<DocumentCatalog, DocumentCompilationFailed> {\n const documents = [...input].sort((left, right) => left.source.path.localeCompare(right.source.path))\n const collisions = collisionIssues(documents)\n\n if (collisions.length > 0) return EffectResult.fail(new DocumentCompilationFailed({ issues: collisions }))\n\n const lookup = createCatalogLookup(documents, configuration)\n const references = createDocumentReferenceIndex(documents, configuration, lookup.findByPath)\n\n const withReferenceIssues = documents.map((document) => {\n const additional = references.issues.get(document.source.path) ?? []\n\n return additional.length === 0\n ? document\n : CompiledDocumentSchema.make(Object.assign({}, document, { issues: [...document.issues, ...additional] }))\n })\n\n return EffectResult.succeed({\n documents: withReferenceIssues,\n issues: [\n ...withReferenceIssues.flatMap((document) => document.issues),\n ...translationIssues(withReferenceIssues, configuration),\n ],\n ...createCatalogLookup(withReferenceIssues, configuration),\n references: references.index,\n } satisfies DocumentCatalog)\n}\n","import type { ComponentDefinition, DocumentConfiguration, CollectionDefinition } from '@internal/protocol/Configuration'\nimport type { DocumentAddress } from '../document-address'\nimport type { ExecutableDocumentModel, ExecutableDocumentSchema } from './document-schema'\nimport { parseDocumentAddress } from '../document-address'\nimport { createAuthoringDocumentValidator, validateCollectionBody } from '../../AuthoringSchema'\nimport { Result } from 'effect'\nimport { DocumentEngineConfigurationInvalid } from './errors'\n\nexport interface ResolvedCollection {\n readonly address: DocumentAddress\n readonly definition: CollectionDefinition\n readonly schema: ExecutableDocumentSchema\n}\n\nexport interface ResolvedDocumentEngineConfiguration {\n readonly components?: ReadonlyMap<string, ComponentDefinition>\n readonly validateAuthoringDocument?: ReturnType<typeof createAuthoringDocumentValidator>\n readonly documents: DocumentConfiguration\n readonly mediaBaseUrl?: string\n readonly types: ReadonlyArray<ResolvedCollection>\n}\n\nexport interface DocumentEngineOptions {\n readonly components?: ReadonlyArray<ComponentDefinition>\n readonly documentModel: ExecutableDocumentModel\n readonly mediaBaseUrl?: string\n}\n\ntype ResolvedDocumentEngineConfigurationBuilder = {\n -readonly [Key in keyof ResolvedDocumentEngineConfiguration]: ResolvedDocumentEngineConfiguration[Key]\n}\n\nexport function resolveDocumentEngineConfiguration(\n documents: DocumentConfiguration,\n options: DocumentEngineOptions,\n): Result.Result<ResolvedDocumentEngineConfiguration, DocumentEngineConfigurationInvalid> {\n if (documents.types.length === 0) return invalid('Documents must define at least one collection.', 'types')\n\n const collections = new Set<string>()\n const directories = new Map<string, string>()\n const resolved: ResolvedCollection[] = []\n\n for (const definition of documents.types) {\n if (collections.has(definition.collection)) {\n return invalid(`Document collection \"${definition.collection}\" is defined more than once.`, 'types')\n }\n\n collections.add(definition.collection)\n\n const existing = directories.get(definition.directory)\n\n if (existing) {\n return invalid(\n `Document collections \"${existing}\" and \"${definition.collection}\" use the same directory \"${definition.directory}\".`,\n 'types',\n )\n }\n\n directories.set(definition.directory, definition.collection)\n\n const addressResult = parseDocumentAddress(definition.addressPattern)\n\n if (Result.isFailure(addressResult)) return invalid(addressResult.failure.message, addressResult.failure.field)\n\n if (definition.hierarchy && !addressResult.success.tokens.some((token) => token.catchAll)) {\n return invalid(\n `Document collection \"${definition.collection}\" can only enable hierarchy with a catch-all address.`,\n 'types',\n )\n }\n\n const schema = options.documentModel.types[definition.collection]\n\n if (!schema)\n return invalid(`Document collection \"${definition.collection}\" has no executable schema.`, 'documentModel')\n\n resolved.push({ address: addressResult.success, definition, schema })\n }\n\n const locales = documents.locales\n\n if (locales) {\n if (new Set(locales.locales).size !== locales.locales.length)\n return invalid('Document locales must be unique.', 'locales.locales')\n\n if (!locales.locales.includes(locales.defaultLocale)) {\n return invalid(`Default locale \"${locales.defaultLocale}\" is not configured.`, 'locales.defaultLocale')\n }\n\n if (locales.fallbackLocale && !locales.locales.includes(locales.fallbackLocale)) {\n return invalid(`Fallback locale \"${locales.fallbackLocale}\" is not configured.`, 'locales.fallbackLocale')\n }\n }\n\n let components: ReadonlyMap<string, ComponentDefinition> | undefined\n let validateAuthoringDocument: ReturnType<typeof createAuthoringDocumentValidator> | undefined\n\n if (options.components !== undefined) {\n const result = resolveComponents(options.components)\n\n if (Result.isFailure(result)) return Result.fail(result.failure)\n components = result.success.components\n validateAuthoringDocument = result.success.validateAuthoringDocument\n\n for (const definition of documents.types) {\n const issues = validateCollectionBody(options.components, definition.body)\n\n if (issues.length) return invalid(`${definition.label}: ${issues.join(' ')}`, 'body')\n }\n }\n\n const mediaBaseUrl = options.mediaBaseUrl?.replace(/\\/+$/u, '')\n\n resolved.sort((left, right) => directoryDepth(right.definition.directory) - directoryDepth(left.definition.directory))\n\n const configuration: ResolvedDocumentEngineConfigurationBuilder = {\n documents,\n types: resolved,\n }\n\n if (components !== undefined) configuration.components = components\n\n if (validateAuthoringDocument !== undefined) configuration.validateAuthoringDocument = validateAuthoringDocument\n\n if (mediaBaseUrl !== undefined) configuration.mediaBaseUrl = mediaBaseUrl\n\n return Result.succeed(configuration satisfies ResolvedDocumentEngineConfiguration)\n}\n\nfunction resolveComponents(definitions: ReadonlyArray<ComponentDefinition>): Result.Result<\n {\n readonly components: ReadonlyMap<string, ComponentDefinition>\n readonly validateAuthoringDocument: ReturnType<typeof createAuthoringDocumentValidator>\n },\n DocumentEngineConfigurationInvalid\n> {\n const components = new Map<string, ComponentDefinition>()\n\n for (const component of definitions) {\n const name = component.name.toLocaleLowerCase()\n\n if (components.has(name))\n return invalid(`Document component \"${component.name}\" is defined more than once.`, 'components')\n components.set(name, component)\n }\n\n try {\n return Result.succeed({ components, validateAuthoringDocument: createAuthoringDocumentValidator(components) })\n } catch (cause) {\n return invalid(cause instanceof Error ? cause.message : 'The component authoring catalog is invalid.', 'components')\n }\n}\n\nfunction directoryDepth(directory: string): number {\n return directory === '.' ? 0 : directory.split('/').length\n}\n\nfunction invalid(message: string, field?: string): Result.Result<never, DocumentEngineConfigurationInvalid> {\n return Result.fail(new DocumentEngineConfigurationInvalid(field === undefined ? { message } : { field, message }))\n}\n","import type { DocumentConfiguration } from '@internal/protocol/Configuration'\nimport type { CompiledDocument, DocumentIssue, DocumentValidationResult } from '@internal/protocol/Documents'\nimport type { DocumentCompilationSource } from './internal/document-engine/compilation-source'\nimport type { DocumentEngineOptions } from './internal/document-engine/configuration'\nimport type { DocumentCompilationFailed, DocumentParseFailed } from './internal/document-engine/errors'\nimport type { DocumentCatalog } from './internal/document-engine/catalog'\nimport { DocumentValidationResult as DocumentValidationResultSchema } from '@internal/protocol/Documents'\nimport { DateTime, Effect, Result, Schema } from 'effect'\nimport { compileCompiledDocument } from './internal/document-engine/compilation'\nimport { DOCUMENT_ENGINE_FINGERPRINT, createDocumentParser } from './internal/comark/grammar'\nimport { createDocumentCatalog } from './internal/document-engine/catalog'\nimport { resolveDocumentEngineConfiguration } from './internal/document-engine/configuration'\nimport { DocumentParseFailed as DocumentParseFailedError } from './internal/document-engine/errors'\n\ntype CompilationError = DocumentCompilationFailed | DocumentParseFailed\n\nexport interface DocumentCatalogCompilation {\n readonly previous?: DocumentCatalog\n readonly sources: ReadonlyArray<DocumentCompilationSource>\n}\n\nconst isDocumentParseFailed = Schema.is(DocumentParseFailedError)\n\n/**\n * Portable authority for compiled Documents. `compileAll` reuses unchanged\n * source compilations from `previous`, then rebuilds the catalog-wide collision,\n * translation, and reference projection. `validate` reports every parse or\n * compilation failure as data and therefore has no error channel.\n */\nexport interface DocumentEngine {\n readonly fingerprint: string\n readonly compile: (source: DocumentCompilationSource) => Effect.Effect<CompiledDocument, CompilationError>\n readonly compileAll: (input: DocumentCatalogCompilation) => Effect.Effect<DocumentCatalog, CompilationError>\n readonly validate: (source: DocumentCompilationSource) => Effect.Effect<DocumentValidationResult>\n}\n\nexport const createDocumentEngine = Effect.fn('DocumentEngine.make')(function* (\n documents: DocumentConfiguration,\n options: DocumentEngineOptions,\n) {\n const configuration = yield* Effect.fromResult(resolveDocumentEngineConfiguration(documents, options))\n const parseMarkdown = createDocumentParser()\n\n const compilations = new WeakMap<\n DocumentCatalog,\n ReadonlyMap<string, { readonly document: CompiledDocument; readonly source: DocumentCompilationSource }>\n >()\n\n const compile = Effect.fn('DocumentEngine.compile')((source: DocumentCompilationSource) =>\n compileCompiledDocument(configuration, parseMarkdown, source),\n )\n\n const compileAll = Effect.fn('DocumentEngine.compileAll')(function* (input: DocumentCatalogCompilation) {\n const previous = input.previous ? compilations.get(input.previous) : undefined\n\n const compiled = yield* Effect.forEach(input.sources, (source) => {\n const cached = previous?.get(source.documentId)\n\n return cached && sameCompilationSource(cached.source, source) ? Effect.succeed(cached.document) : compile(source)\n })\n\n const catalog = yield* Effect.fromResult(createDocumentCatalog(configuration, compiled))\n compilations.set(\n catalog,\n new Map(\n input.sources.map((source, index) => {\n const document = compiled[index]\n\n if (!document) throw new Error(`Compiled document \"${source.documentId}\" is missing.`)\n\n return [source.documentId, { document, source }] as const\n }),\n ),\n )\n\n return catalog\n })\n\n const validate = Effect.fn('DocumentEngine.validate')(function* (source: DocumentCompilationSource) {\n const result = yield* Effect.result(compile(source))\n\n if (Result.isSuccess(result)) {\n const document = result.success\n\n return DocumentValidationResultSchema.make({\n valid: !document.issues.some((issue) => issue.severity === 'error'),\n document,\n issues: document.issues,\n })\n }\n\n const error = result.failure\n\n const issues: ReadonlyArray<DocumentIssue> = isDocumentParseFailed(error)\n ? [\n {\n code: 'markdown.parse',\n message: errorMessage(error.cause),\n severity: 'error',\n sourcePath: error.sourcePath,\n },\n ]\n : error.issues\n\n return DocumentValidationResultSchema.make({\n valid: false,\n issues,\n })\n })\n\n return {\n compile,\n compileAll,\n fingerprint: DOCUMENT_ENGINE_FINGERPRINT,\n validate,\n } satisfies DocumentEngine\n})\n\nfunction sameCompilationSource(left: DocumentCompilationSource, right: DocumentCompilationSource): boolean {\n return (\n left.documentId === right.documentId &&\n left.draft === right.draft &&\n left.markdown === right.markdown &&\n left.sourcePath === right.sourcePath &&\n samePublishedAt(left.publishedAt, right.publishedAt)\n )\n}\n\nfunction samePublishedAt(\n left: DocumentCompilationSource['publishedAt'],\n right: DocumentCompilationSource['publishedAt'],\n): boolean {\n return left === undefined || right === undefined ? left === right : DateTime.Equivalence(left, right)\n}\n\nfunction errorMessage(cause: unknown): string {\n return cause instanceof Error && cause.message ? cause.message : 'Markdown could not be parsed.'\n}\n\nexport { DocumentCompilationSource } from './internal/document-engine/compilation-source'\n\nexport type { DocumentCatalog } from './internal/document-engine/catalog'\n\nexport type { DocumentEngineOptions } from './internal/document-engine/configuration'\n\nexport {\n DocumentCompilationFailed,\n DocumentEngineConfigurationInvalid,\n DocumentParseFailed,\n} from './internal/document-engine/errors'\n\nexport type {\n DocumentReference,\n DocumentReferenceIndex,\n DocumentReferenceTarget,\n} from './internal/document-engine/references'\n\nexport type {\n DocumentSchemaIssue,\n DocumentSchemaProjection,\n DocumentSch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AK,aAAa,MAAM,YACxB,KAAK,eAAe,MAAM,cAC1B,gBAAgB,KAAK,aAAa,MAAM,WAAW;AAEvD;AAEA,SAAS,gBACP,MACA,OACS;CACT,OAAO,SAAS,UAAa,UAAU,SAAY,SAAS,QAAQ,SAAS,YAAY,MAAM,KAAK;AACtG;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,SAAS,MAAM,UAAU,MAAM,UAAU;AACnE"}
|
|
1
|
+
{"version":3,"file":"DocumentEngine-ClhFXW9M.js","names":["nestedValue","PublicPathSchema","CmsDocumentAnalysisSchema","visit","isDocumentParseFailed","DocumentSourceMappingSchema","EffectResult","CompiledDocumentSchema","DocumentParseFailedError","DocumentValidationResultSchema"],"sources":["../../../../document/src/internal/document-address.ts","../../../../document/src/internal/document-engine/errors.ts","../../../../document/src/internal/comark/analysis.ts","../../../../document/src/internal/document-engine/frontmatter-validation.ts","../../../../document/src/internal/document-engine/compilation.ts","../../../../document/src/internal/document-engine/catalog-lookup.ts","../../../../document/src/internal/document-engine/catalog-issues.ts","../../../../document/src/internal/document-engine/reference-target.ts","../../../../document/src/internal/document-engine/references.ts","../../../../document/src/internal/document-engine/catalog.ts","../../../../document/src/internal/document-engine/configuration.ts","../../../../document/src/DocumentEngine.ts"],"sourcesContent":["import type { AddressPattern, Locale, LocaleConfiguration } from '@internal/protocol/Configuration'\nimport { Predicate, Result, Schema } from 'effect'\nimport { PublicPath as PublicPathSchema, type PublicPath } from '@internal/protocol/Documents'\n\nexport interface DocumentAddressToken {\n readonly catchAll: boolean\n readonly name: string\n}\n\nexport interface DocumentAddress {\n readonly pattern: AddressPattern\n readonly tokens: ReadonlyArray<DocumentAddressToken>\n}\n\nexport interface DocumentAddressError {\n readonly field?: string\n readonly message: string\n}\n\nconst addressTokenPattern = /:([a-z][\\w.]*)(\\*)?/giu\n\nexport function parseDocumentAddress(pattern: AddressPattern): Result.Result<DocumentAddress, DocumentAddressError> {\n const matches = [...pattern.matchAll(addressTokenPattern)]\n\n const tokens = matches.map((match) => ({\n catchAll: match[2] === '*',\n name: match[1] ?? '',\n }))\n\n const remainder = pattern.replace(addressTokenPattern, '')\n\n if (remainder.includes(':') || tokens.some((token) => !token.name)) {\n return Result.fail({\n field: 'addressPattern',\n message: `Document address pattern \"${pattern}\" contains an invalid token.`,\n })\n }\n\n if (tokens.filter((token) => token.catchAll).length > 1) {\n return Result.fail({\n field: 'addressPattern',\n message: `Document address pattern \"${pattern}\" contains more than one catch-all token.`,\n })\n }\n\n if (new Set(tokens.map((token) => token.name)).size !== tokens.length) {\n return Result.fail({\n field: 'addressPattern',\n message: `Document address pattern \"${pattern}\" contains duplicate tokens.`,\n })\n }\n\n return Result.succeed({ pattern, tokens })\n}\n\nexport function resolveDocumentAddress(\n address: DocumentAddress,\n relativeKey: PublicPath,\n data: Schema.JsonObject,\n): Result.Result<PublicPath, DocumentAddressError> {\n const relativePath = relativeKey === '/' ? '' : relativeKey.slice(1)\n let resolved: string = address.pattern\n\n for (const token of address.tokens) {\n const authored = nestedValue(data, token.name)\n const fallback = token.catchAll ? relativePath : undefined\n\n const value =\n authored === undefined ? fallback : Predicate.isString(authored) && authored.trim() ? authored : undefined\n\n if (value === undefined) {\n return Result.fail({\n field: token.name,\n message:\n authored === undefined\n ? `Document address field \"${token.name}\" is required by pattern \"${address.pattern}\".`\n : `Document address field \"${token.name}\" must be a non-empty string.`,\n })\n }\n\n const normalized = token.catchAll ? normalizeDocumentRelativePath(value) : normalizeDocumentSegment(value)\n\n if (Result.isFailure(normalized)) return Result.fail(normalized.failure)\n resolved = resolved.replace(`:${token.name}${token.catchAll ? '*' : ''}`, normalized.success)\n }\n\n return normalizePublicPath(resolved)\n}\n\nexport function documentKeyFromSourcePath(relativeSourcePath: string): Result.Result<PublicPath, DocumentAddressError> {\n const extension = relativeSourcePath.match(/\\.(?:md|mdc)$/iu)?.[0]\n\n if (!extension) {\n return Result.fail({\n field: 'sourcePath',\n message: `Document source must be a Markdown file: \"${relativeSourcePath}\".`,\n })\n }\n\n const segments = relativeSourcePath.slice(0, -extension.length).split('/')\n\n if (segments.at(-1)?.toLocaleLowerCase() === 'index') segments.pop()\n\n return normalizeDocumentRelativePath(segments.join('/')).pipe(Result.flatMap(normalizePublicPath))\n}\n\nexport function localizeDocumentPath(\n key: PublicPath,\n locale: Locale | undefined,\n configuration: LocaleConfiguration | undefined,\n): PublicPath {\n if (!configuration || !locale || (locale === configuration.defaultLocale && !configuration.prefixDefaultLocale)) {\n return key\n }\n\n return PublicPathSchema.make(`/${locale}${key === '/' ? '' : key}`)\n}\n\nexport function normalizePublicPath(value: string): Result.Result<PublicPath, DocumentAddressError> {\n const path = `/${value.replace(/\\\\/gu, '/').replace(/^\\/+|\\/+$/gu, '')}`.replace(/\\/{2,}/gu, '/')\n\n return Schema.decodeResult(PublicPathSchema)(path).pipe(\n Result.mapError(() => ({\n field: 'path',\n message: `Document path \"${value}\" cannot be normalized into a public path.`,\n })),\n )\n}\n\nexport function normalizeDocumentRelativePath(value: string): Result.Result<string, DocumentAddressError> {\n if (!value.trim()) return Result.succeed('')\n\n const segments = value.replace(/\\\\/gu, '/').split('/').filter(Boolean)\n const normalized: string[] = []\n\n for (const segment of segments) {\n const result = normalizeDocumentSegment(segment)\n\n if (Result.isFailure(result)) return result\n normalized.push(result.success)\n }\n\n return Result.succeed(normalized.join('/'))\n}\n\nexport function normalizeDocumentSegment(value: string): Result.Result<string, DocumentAddressError> {\n const normalized = value\n .trim()\n .normalize('NFKC')\n .toLocaleLowerCase()\n .replace(/[^\\p{Letter}\\p{Number}_-]+/gu, '-')\n .replace(/^-+|-+$/gu, '')\n\n return normalized\n ? Result.succeed(normalized)\n : Result.fail({ message: `Document path segment \"${value}\" is empty after normalization.` })\n}\n\nfunction nestedValue(value: Schema.JsonObject, path: string): Schema.Json | undefined {\n return path.split('.').reduce<Schema.Json | undefined>((current, segment) => {\n if (!Schema.is(Schema.JsonObject)(current)) return undefined\n\n return current[segment]\n }, value)\n}\n","import { DocumentIssue } from '@internal/protocol/Documents'\nimport { SourcePath } from '@internal/protocol/Documents'\nimport { Schema } from 'effect'\n\nexport class DocumentEngineConfigurationInvalid extends Schema.TaggedError<DocumentEngineConfigurationInvalid>()(\n 'DocumentEngine.ConfigurationInvalid',\n {\n message: Schema.NonEmptyString,\n field: Schema.optionalKey(Schema.NonEmptyString),\n },\n) {}\n\nexport class DocumentParseFailed extends Schema.TaggedError<DocumentParseFailed>()(\n 'DocumentEngine.DocumentParseFailed',\n {\n sourcePath: SourcePath,\n cause: Schema.Defect(),\n },\n) {}\n\nexport class DocumentCompilationFailed extends Schema.TaggedError<DocumentCompilationFailed>()(\n 'DocumentEngine.DocumentCompilationFailed',\n {\n issues: Schema.Array(DocumentIssue),\n },\n) {}\n","import type { CmsDocumentAnalysis, CmsMarkdownDocument, MarkdownNode } from '@internal/protocol/Documents'\nimport { CmsDocumentAnalysis as CmsDocumentAnalysisSchema } from '@internal/protocol/Documents'\nimport { Predicate } from 'effect'\nimport { cmsComarkTextContent } from './document-adapter'\n\nexport const CMS_STANDARD_TAGS = new Set([\n 'a',\n 'abbr',\n 'address',\n 'article',\n 'aside',\n 'b',\n 'blockquote',\n 'br',\n 'button',\n 'caption',\n 'code',\n 'col',\n 'colgroup',\n 'dd',\n 'del',\n 'details',\n 'div',\n 'dl',\n 'dt',\n 'em',\n 'figcaption',\n 'figure',\n 'footer',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hr',\n 'i',\n 'img',\n 'kbd',\n 'li',\n 'main',\n 'mark',\n 'nav',\n 'ol',\n 'p',\n 'pre',\n 'q',\n 's',\n 'section',\n 'small',\n 'span',\n 'strong',\n 'sub',\n 'summary',\n 'sup',\n 'table',\n 'tbody',\n 'td',\n 'template',\n 'tfoot',\n 'th',\n 'thead',\n 'tr',\n 'u',\n 'ul',\n])\n\nexport function analyzeCmsDocument(\n body: CmsMarkdownDocument,\n metadata: { readonly description?: string; readonly title: string },\n): CmsDocumentAnalysis {\n const headings: Array<{ readonly depth: number; readonly id: string; readonly text: string }> = []\n const components = new Set<string>()\n\n visit(body.nodes, (node) => {\n const tag = node[0].toLocaleLowerCase()\n\n if (/^h[1-6]$/u.test(tag)) {\n headings.push({\n depth: Number(tag.slice(1)),\n id: Predicate.isString(node[1].id) ? node[1].id : '',\n text: cmsComarkTextContent(node).trim(),\n })\n } else if (!CMS_STANDARD_TAGS.has(tag)) {\n components.add(tag)\n }\n })\n\n const bodyText = normalizeText(body.nodes.map(cmsComarkTextContent).join(' '))\n const summary = normalizeText(metadata.description ?? firstParagraph(body.nodes) ?? metadata.title)\n const searchText = normalizeText([metadata.title, metadata.description, bodyText].filter(Boolean).join(' '))\n\n return CmsDocumentAnalysisSchema.make({\n components: [...components].sort(),\n headings,\n searchText,\n summary,\n })\n}\n\nfunction visit(\n nodes: ReadonlyArray<MarkdownNode>,\n inspect: (node: Exclude<MarkdownNode, string | readonly [null, object, string]>) => void,\n): void {\n for (const node of nodes) {\n if (Predicate.isString(node) || node[0] === null) continue\n inspect(node)\n const [, , ...children] = node\n visit(children, inspect)\n }\n}\n\nfunction firstParagraph(nodes: ReadonlyArray<MarkdownNode>): string | undefined {\n const paragraph = nodes.find((node) => Array.isArray(node) && node[0] === 'p')\n\n if (!paragraph || Predicate.isString(paragraph) || paragraph[0] === null) return undefined\n const text = normalizeText(cmsComarkTextContent(paragraph))\n\n return text || undefined\n}\n\nfunction normalizeText(value: string): string {\n return value.replace(/\\s+/gu, ' ').trim()\n}\n","import type { CollectionDefinition } from '@internal/protocol/Configuration'\nimport type { DocumentIssue } from '@internal/protocol/Documents'\nimport type { SourcePath } from '@internal/protocol/Documents'\nimport type { DocumentSchemaIssue, ExecutableDocumentSchema } from './document-schema'\nimport { Effect, Option, Predicate, Schema } from 'effect'\n\nexport const validateFrontmatter = Effect.fn('DocumentEngine.validateFrontmatter')(function* (\n raw: Schema.JsonObject,\n schema: ExecutableDocumentSchema,\n type: CollectionDefinition,\n sourcePath: SourcePath,\n) {\n const projection = schema.project(raw)\n\n const issues = projection.unknownPaths\n .toSorted()\n .map((path): DocumentIssue => unknownFieldIssue(path, type, sourcePath))\n\n const result = yield* schema.validate(projection.value)\n\n if ('issues' in result) {\n issues.push(...result.issues.map((issue) => schemaIssue(issue, projection.value, type, sourcePath)))\n\n return { data: projection.value, issues }\n }\n\n const parsed = Schema.decodeUnknownOption(Schema.JsonObject)(result.value)\n\n if (Option.isNone(parsed)) {\n issues.push(\n issue(\n 'schema.constraint',\n 'The collection schema output must be a JSON-compatible object.',\n type,\n sourcePath,\n 'frontmatter',\n ),\n )\n\n return { data: projection.value, issues }\n }\n\n return issues.length === 0 ? { data: parsed.value, issues } : { data: projection.value, issues }\n})\n\nfunction unknownFieldIssue(path: string, type: CollectionDefinition, sourcePath: SourcePath): DocumentIssue {\n if (path === 'id') {\n return issue(\n 'document.id',\n 'Document identity is managed by the CMS and cannot be authored in frontmatter.',\n type,\n sourcePath,\n path,\n )\n }\n\n return issue(\n 'schema.unknown',\n `Frontmatter field \"${path}\" is not declared by collection \"${type.collection}\".`,\n type,\n sourcePath,\n path,\n )\n}\n\nfunction schemaIssue(\n error: DocumentSchemaIssue,\n input: Schema.JsonObject,\n type: CollectionDefinition,\n sourcePath: SourcePath,\n): DocumentIssue {\n const field = issuePath(error.path)\n const code = issueCode(error, input, field)\n\n return issue(code, error.message, type, sourcePath, field || undefined)\n}\n\nfunction issueCode(error: DocumentSchemaIssue, input: Schema.JsonObject, field: string): DocumentIssue['code'] {\n if (error.code === 'invalid_type') return nestedValue(input, field) === undefined ? 'schema.required' : 'schema.type'\n\n if (error.code === 'invalid_value') return 'schema.option'\n\n return 'schema.constraint'\n}\n\nfunction issuePath(path: DocumentSchemaIssue['path']): string {\n return (path ?? [])\n .map((segment) => (Predicate.hasProperty(segment, 'key') ? segment.key : segment))\n .map(String)\n .join('.')\n}\n\nfunction nestedValue(value: Schema.JsonObject, path: string): Schema.Json | undefined {\n if (!path) return value\n\n return path.split('.').reduce<Schema.Json | undefined>((current, segment) => {\n if (Array.isArray(current)) {\n const index = Number(segment)\n\n return Number.isSafeInteger(index) ? current[index] : undefined\n }\n\n return Schema.is(Schema.JsonObject)(current) ? current[segment] : undefined\n }, value)\n}\n\nfunction issue(\n code: DocumentIssue['code'],\n message: string,\n type: CollectionDefinition,\n sourcePath: SourcePath,\n field?: string,\n): DocumentIssue {\n return {\n code,\n collection: type.collection,\n ...(field === undefined ? undefined : { field }),\n message,\n severity: 'error',\n sourcePath,\n }\n}\n","import type {\n DocumentIssue,\n DocumentSourceMapping,\n CmsMarkdownDocument as MarkdownDocumentType,\n} from '@internal/protocol/Documents'\nimport type { DocumentSeo as DocumentSeoType } from '@internal/protocol/Seo'\nimport type { Locale } from '@internal/protocol/Configuration'\nimport type { ComarkParseFn } from 'comark'\nimport type { DocumentCompilationSource } from './compilation-source'\nimport type { ResolvedDocumentEngineConfiguration, ResolvedCollection } from './configuration'\nimport {\n CompiledDocument,\n DocumentSourceMapping as DocumentSourceMappingSchema,\n CmsMarkdownDocument,\n} from '@internal/protocol/Documents'\nimport { PublicPath } from '@internal/protocol/Documents'\nimport { documentKeyFromSourcePath, localizeDocumentPath, resolveDocumentAddress } from '../document-address'\nimport { DocumentSeo } from '@internal/protocol/Seo'\nimport { Effect, Predicate, Result, Schema } from 'effect'\nimport { DocumentCompilationFailed, DocumentParseFailed } from './errors'\nimport { normalizeCmsComponentBindings } from '../comark/bindings'\nimport { analyzeCmsDocument } from '../comark/analysis'\nimport { DOCUMENT_ENGINE_FINGERPRINT } from '../comark/grammar'\nimport { validateFrontmatter } from './frontmatter-validation'\nimport { SOURCE_MAPPINGS_META_KEY } from '../comark/source-mapping'\n\nconst isDocumentParseFailed = Schema.is(DocumentParseFailed)\n\nexport const compileCompiledDocument = Effect.fn('DocumentEngine.compileDocument')(function* (\n configuration: ResolvedDocumentEngineConfiguration,\n parseMarkdown: ComarkParseFn,\n source: DocumentCompilationSource,\n) {\n const location = yield* resolveSourceLocation(configuration, source)\n const parsedBody = yield* parseBody(parseMarkdown, source)\n const mappings = yield* sourceMappings(parsedBody, source)\n const body = normalizeCmsComponentBindings(withoutSourceMappings(parsedBody), configuration.components)\n const { collectionFrontmatter, rawSeo } = splitFrontmatter(body.frontmatter)\n const seoProjection = projectSeo(rawSeo, source.sourcePath)\n\n const relativeKey = yield* fromAddressResult(\n documentKeyFromSourcePath(location.relativeSourcePath),\n source.sourcePath,\n )\n\n const validation = yield* validateFrontmatter(\n collectionFrontmatter,\n location.type.schema,\n location.type.definition,\n source.sourcePath,\n ).pipe(\n Effect.mapError(\n (cause) =>\n new DocumentCompilationFailed({\n issues: [\n {\n code: 'schema.constraint',\n collection: location.type.definition.collection,\n message: cause.message,\n severity: 'error',\n sourcePath: source.sourcePath,\n },\n ],\n }),\n ),\n )\n\n const address = resolveDocumentAddress(location.type.address, relativeKey, validation.data)\n const key = Result.isSuccess(address) ? address.success : provisionalKey(source.documentId)\n const path = localizeDocumentPath(key, location.locale, configuration.documents.locales)\n\n const title =\n stringValue(validation.data.title) ?? stringValue(body.meta.title) ?? titleFromSource(location.relativeSourcePath)\n\n const description = stringValue(validation.data.description) ?? stringValue(body.meta.description)\n\n const issues = Result.isSuccess(address)\n ? validation.issues\n : [...validation.issues, addressIssue(address.failure, source.sourcePath)]\n\n const canonicalFrontmatter = rawSeo === undefined ? validation.data : Object.assign({ _seo: rawSeo }, validation.data)\n\n const canonicalBody = CmsMarkdownDocument.make({\n frontmatter: canonicalFrontmatter,\n meta: body.meta,\n nodes: body.nodes,\n })\n\n const analysis = analyzeCmsDocument(canonicalBody, description === undefined ? { title } : { description, title })\n\n return CompiledDocument.make(\n Object.assign(\n {\n id: source.documentId,\n key,\n path,\n collection: location.type.definition.collection,\n draft: source.draft,\n title,\n data: validation.data,\n issues: [\n ...issues,\n ...seoProjection.issues,\n ...(configuration.validateAuthoringDocument?.(canonicalBody, location.type.definition.body) ?? []).map(\n (message): DocumentIssue => ({\n code: 'reference.component',\n message,\n severity: 'error',\n sourcePath: source.sourcePath,\n }),\n ),\n ],\n analysis,\n body: canonicalBody,\n engineFingerprint: DOCUMENT_ENGINE_FINGERPRINT,\n source: {\n path: source.sourcePath,\n mappings,\n ...(source.publishedAt === undefined ? undefined : { publishedAt: source.publishedAt }),\n },\n },\n location.locale === undefined ? undefined : { locale: location.locale },\n description === undefined ? undefined : { description },\n seoProjection.seo === undefined ? undefined : { seo: seoProjection.seo },\n ),\n )\n})\n\ninterface FrontmatterProjection {\n readonly collectionFrontmatter: Schema.JsonObject\n readonly rawSeo: Schema.Json | undefined\n}\n\nfunction splitFrontmatter(frontmatter: Schema.JsonObject): FrontmatterProjection {\n const { _seo: rawSeo, ...collectionFrontmatter } = frontmatter\n\n return { collectionFrontmatter, rawSeo }\n}\n\ninterface SeoProjection {\n readonly seo?: DocumentSeoType\n readonly issues: ReadonlyArray<DocumentIssue>\n}\n\nfunction projectSeo(\n rawSeo: Schema.Json | undefined,\n sourcePath: DocumentCompilationSource['sourcePath'],\n): SeoProjection {\n if (rawSeo === undefined) return { issues: [] }\n\n const decoded = Schema.decodeUnknownResult(DocumentSeo)(rawSeo, { onExcessProperty: 'error' })\n\n if (Result.isSuccess(decoded)) return { issues: [], seo: decoded.success }\n\n return {\n issues: [\n {\n code: 'seo.invalid',\n field: '_seo',\n message: `Document SEO is invalid: ${String(decoded.failure)}`,\n severity: 'error',\n sourcePath,\n },\n ],\n }\n}\n\nfunction provisionalKey(documentId: DocumentCompilationSource['documentId']): PublicPath {\n return PublicPath.make(`/_cms-invalid/${documentId}`)\n}\n\nfunction addressIssue(\n error: { readonly field?: string; readonly message: string },\n sourcePath: DocumentCompilationSource['sourcePath'],\n): DocumentIssue {\n const issue = {\n code: 'document.invalid' as const,\n message: error.message,\n severity: 'error' as const,\n sourcePath,\n }\n\n return error.field === undefined ? issue : { ...issue, field: error.field }\n}\n\ninterface SourceLocation {\n readonly locale?: Locale\n readonly relativeSourcePath: string\n readonly type: ResolvedCollection\n}\n\nfunction resolveSourceLocation(\n configuration: ResolvedDocumentEngineConfiguration,\n source: DocumentCompilationSource,\n): Effect.Effect<SourceLocation, DocumentCompilationFailed> {\n const segments = source.sourcePath.split('/')\n let locale: Locale | undefined\n\n if (configuration.documents.locales) {\n const candidate = segments.shift()\n locale = configuration.documents.locales.locales.find((value) => value === candidate)\n\n if (!locale) {\n return compilationFailure({\n code: 'document.invalid',\n field: 'locale',\n message: `Localized document \"${source.sourcePath}\" must begin with a configured locale.`,\n severity: 'error',\n sourcePath: source.sourcePath,\n })\n }\n }\n\n const localizedSourcePath = segments.join('/')\n\n const type = configuration.types.find(\n ({ definition }) => definition.directory === '.' || localizedSourcePath.startsWith(`${definition.directory}/`),\n )\n\n if (!type) {\n return compilationFailure({\n code: 'document.invalid',\n field: 'sourcePath',\n message: `No document collection contains \"${source.sourcePath}\".`,\n severity: 'error',\n sourcePath: source.sourcePath,\n })\n }\n\n const relativeSourcePath =\n type.definition.directory === '.'\n ? localizedSourcePath\n : localizedSourcePath.slice(type.definition.directory.length + 1)\n\n if (!relativeSourcePath) {\n return compilationFailure({\n code: 'document.invalid',\n field: 'sourcePath',\n message: `Document source \"${source.sourcePath}\" has no collection-relative path.`,\n severity: 'error',\n sourcePath: source.sourcePath,\n })\n }\n\n return Effect.succeed(locale === undefined ? { relativeSourcePath, type } : { locale, relativeSourcePath, type })\n}\n\nfunction parseBody(\n parseMarkdown: ComarkParseFn,\n source: DocumentCompilationSource,\n): Effect.Effect<MarkdownDocumentType, DocumentParseFailed> {\n return Effect.tryPromise({\n try: () => parseMarkdown(source.markdown),\n catch: (cause) => new DocumentParseFailed({ cause, sourcePath: source.sourcePath }),\n }).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(CmsMarkdownDocument)),\n Effect.mapError((cause) =>\n isDocumentParseFailed(cause) ? cause : new DocumentParseFailed({ cause, sourcePath: source.sourcePath }),\n ),\n )\n}\n\nfunction sourceMappings(\n body: MarkdownDocumentType,\n source: DocumentCompilationSource,\n): Effect.Effect<ReadonlyArray<DocumentSourceMapping>, DocumentParseFailed> {\n return Schema.decodeUnknownEffect(Schema.Array(DocumentSourceMappingSchema))(\n body.meta[SOURCE_MAPPINGS_META_KEY] ?? [],\n ).pipe(Effect.mapError((cause) => new DocumentParseFailed({ cause, sourcePath: source.sourcePath })))\n}\n\nfunction withoutSourceMappings(body: MarkdownDocumentType): MarkdownDocumentType {\n const { [SOURCE_MAPPINGS_META_KEY]: _mappings, ...meta } = body.meta\n\n return CmsMarkdownDocument.make({ frontmatter: body.frontmatter, meta, nodes: body.nodes })\n}\n\nfunction fromAddressResult<A>(\n result: Result.Result<A, { readonly field?: string; readonly message: string }>,\n sourcePath: DocumentCompilationSource['sourcePath'],\n): Effect.Effect<A, DocumentCompilationFailed> {\n if (Result.isSuccess(result)) return Effect.succeed(result.success)\n\n return compilationFailure(addressIssue(result.failure, sourcePath))\n}\n\nfunction compilationFailure(issue: DocumentIssue): Effect.Effect<never, DocumentCompilationFailed> {\n return Effect.fail(new DocumentCompilationFailed({ issues: [issue] }))\n}\n\nfunction stringValue(value: Schema.Json | undefined): string | undefined {\n return Predicate.isString(value) && value.trim() ? value.trim() : undefined\n}\n\nfunction titleFromSource(sourcePath: string): string {\n const file = sourcePath.split('/').at(-1) ?? 'content'\n const stem = file.replace(/\\.(?:md|mdc)$/iu, '')\n const title = stem.toLocaleLowerCase() === 'index' ? (sourcePath.split('/').at(-2) ?? 'home') : stem\n\n return title.replace(/[-_]+/gu, ' ').replace(/^./u, (character) => character.toLocaleUpperCase())\n}\n","import type { Locale } from '@internal/protocol/Configuration'\nimport type { CompiledDocument, PublicPath } from '@internal/protocol/Documents'\nimport type { ResolvedDocumentEngineConfiguration } from './configuration'\nimport { normalizePublicPath } from '../document-address'\nimport { Option, Result } from 'effect'\n\nexport interface CatalogLookup {\n readonly findByKey: (key: string, locale?: Locale) => Option.Option<CompiledDocument>\n readonly findByPath: (path: string) => Option.Option<CompiledDocument>\n}\n\nexport function createCatalogLookup(\n documents: ReadonlyArray<CompiledDocument>,\n configuration: ResolvedDocumentEngineConfiguration,\n): CatalogLookup {\n const byPath = new Map(documents.map((document) => [document.path, document]))\n const byVariant = new Map(documents.map((document) => [localeAndKey(document.locale, document.key), document]))\n\n const findByKey = (input: string, locale?: Locale) => {\n const keyResult = normalizePublicPath(input)\n\n if (Result.isFailure(keyResult)) return Option.none<CompiledDocument>()\n const key = keyResult.success\n const locales = configuration.documents.locales\n\n if (!locales) return Option.fromNullishOr(byVariant.get(localeAndKey(undefined, key)))\n const requestedLocale = locale ?? locales.defaultLocale\n const localized = byVariant.get(localeAndKey(requestedLocale, key))\n\n if (localized) return Option.some(localized)\n\n if (!locales.fallbackLocale) return Option.none()\n\n return Option.fromNullishOr(byVariant.get(localeAndKey(locales.fallbackLocale, key)))\n }\n\n const findByPath = (input: string) => {\n const pathResult = normalizePublicPath(input)\n\n if (Result.isFailure(pathResult)) return Option.none<CompiledDocument>()\n const path = pathResult.success\n const direct = byPath.get(path)\n\n if (direct) return Option.some(direct)\n\n const locales = configuration.documents.locales\n\n if (!locales) return Option.none()\n const request = localizedRequest(path, locales.locales, locales.defaultLocale, locales.prefixDefaultLocale)\n\n if (!request) return Option.none()\n const localized = byVariant.get(localeAndKey(request.locale, request.key))\n\n if (localized) return Option.some(localized)\n\n if (!locales.fallbackLocale) return Option.none()\n\n return Option.fromNullishOr(byVariant.get(localeAndKey(locales.fallbackLocale, request.key)))\n }\n\n return { findByKey, findByPath }\n}\n\nexport function localeAndKey(locale: Locale | undefined, key: PublicPath): string {\n return `${locale ?? ''}:${key}`\n}\n\nfunction localizedRequest(\n path: PublicPath,\n locales: ReadonlyArray<Locale>,\n defaultLocale: Locale,\n prefixDefaultLocale: boolean,\n): { readonly key: PublicPath; readonly locale: Locale } | undefined {\n const segments = path === '/' ? [] : path.slice(1).split('/')\n const possibleLocale = locales.find((locale) => locale === segments[0])\n\n const prefixedLocale =\n possibleLocale && (possibleLocale !== defaultLocale || prefixDefaultLocale) ? possibleLocale : undefined\n\n if (prefixedLocale) {\n const keyResult = normalizePublicPath(segments.slice(1).join('/'))\n\n return Result.isSuccess(keyResult) ? { key: keyResult.success, locale: prefixedLocale } : undefined\n }\n\n if (prefixDefaultLocale) return undefined\n\n return { key: path, locale: defaultLocale }\n}\n","import type { CompiledDocument, DocumentIssue, PublicPath } from '@internal/protocol/Documents'\nimport type { ResolvedDocumentEngineConfiguration } from './configuration'\nimport { localeAndKey } from './catalog-lookup'\n\nexport function collisionIssues(documents: ReadonlyArray<CompiledDocument>): DocumentIssue[] {\n const issues: DocumentIssue[] = []\n const byId = new Map<string, CompiledDocument>()\n const byPath = new Map<string, CompiledDocument>()\n const byVariant = new Map<string, CompiledDocument>()\n\n for (const document of documents) {\n const identityCollision = byId.get(document.id)\n\n if (identityCollision) {\n issues.push(\n collisionIssue(\n `Document identity collision for \"${document.id}\" between \"${identityCollision.source.path}\" and \"${document.source.path}\".`,\n document,\n ),\n )\n } else byId.set(document.id, document)\n\n const pathCollision = byPath.get(document.path)\n\n if (pathCollision) {\n issues.push(\n collisionIssue(\n `Document route collision at \"${document.path}\" between \"${pathCollision.source.path}\" and \"${document.source.path}\".`,\n document,\n document.path,\n ),\n )\n } else byPath.set(document.path, document)\n\n const variant = localeAndKey(document.locale, document.key)\n const variantCollision = byVariant.get(variant)\n\n if (variantCollision && variantCollision.path !== pathCollision?.path) {\n issues.push(\n collisionIssue(\n `Document locale collision at \"${document.key}\" between \"${variantCollision.source.path}\" and \"${document.source.path}\".`,\n document,\n document.key,\n ),\n )\n } else byVariant.set(variant, document)\n }\n\n return issues\n}\n\nexport function translationIssues(\n documents: ReadonlyArray<CompiledDocument>,\n configuration: ResolvedDocumentEngineConfiguration,\n): DocumentIssue[] {\n const locales = configuration.documents.locales\n\n if (!locales) return []\n const variants = new Set(documents.map((document) => localeAndKey(document.locale, document.key)))\n const keys = new Set(documents.map((document) => document.key))\n\n return [...keys].flatMap((key) =>\n locales.locales.flatMap((locale): DocumentIssue[] =>\n variants.has(localeAndKey(locale, key))\n ? []\n : [\n {\n code: 'i18n.missing-translation',\n key,\n locale,\n message: `Document \"${key}\" is missing its \"${locale}\" translation.`,\n severity: 'warning',\n },\n ],\n ),\n )\n}\n\nfunction collisionIssue(message: string, document: CompiledDocument, key?: PublicPath): DocumentIssue {\n const issue = {\n code: 'document.collision' as const,\n message,\n severity: 'error' as const,\n sourcePath: document.source.path,\n }\n\n return key === undefined ? issue : Object.assign(issue, { key })\n}\n","import type { PublicPath } from '@internal/protocol/Documents'\nimport type { MediaId } from '@internal/protocol/Media'\nimport type { CmsComarkAttributeValue, CmsComarkAttributes } from '../comark/bindings'\nimport { normalizePublicPath } from '../document-address'\nimport { Predicate, Result } from 'effect'\nimport { CMS_STANDARD_TAGS } from '../comark/analysis'\n\nexport type DocumentReferenceTarget =\n | { readonly kind: 'component'; readonly name: string }\n | { readonly kind: 'document'; readonly path: PublicPath }\n | { readonly kind: 'media'; readonly key: string; readonly mediaId?: MediaId }\n\nexport function referenceTarget(\n tag: string,\n attributes: CmsComarkAttributes,\n documentPath: PublicPath,\n mediaBaseUrl: string | undefined,\n): DocumentReferenceTarget | undefined {\n if (tag === 'a') {\n const path = documentTarget(attributes.get('href'), documentPath)\n\n return path ? { kind: 'document', path } : undefined\n }\n\n if (tag === 'img') {\n const key = mediaKey(attributes.get('src'), mediaBaseUrl)\n\n return key ? { kind: 'media', key } : undefined\n }\n\n const normalizedTag = tag.toLocaleLowerCase()\n\n return CMS_STANDARD_TAGS.has(normalizedTag) ? undefined : { kind: 'component', name: normalizedTag }\n}\n\nexport function targetKey(target: DocumentReferenceTarget): string {\n switch (target.kind) {\n case 'component':\n return `component:${target.name.toLocaleLowerCase()}`\n case 'document':\n return `document:${target.path}`\n case 'media':\n return `media:${target.key}`\n }\n}\n\nfunction mediaKey(value: CmsComarkAttributeValue, mediaBaseUrl: string | undefined): string | undefined {\n if (!Predicate.isString(value) || mediaBaseUrl === undefined) return undefined\n const prefix = `${mediaBaseUrl}/`\n\n if (!value.startsWith(prefix)) return undefined\n const encodedKey = value.slice(prefix.length).split(/[?#]/u, 1)[0]\n\n if (!encodedKey) return undefined\n\n try {\n const segments = encodedKey.split('/').map(decodeURIComponent)\n\n if (\n segments.some(\n (segment) =>\n !segment ||\n segment === '.' ||\n segment === '..' ||\n segment.includes('/') ||\n segment.includes('\\\\') ||\n hasControlCharacter(segment),\n )\n ) {\n return undefined\n }\n\n const key = segments.join('/')\n\n return key.startsWith('media/') ? key : undefined\n } catch {\n return undefined\n }\n}\n\nfunction documentTarget(value: CmsComarkAttributeValue, documentPath: PublicPath): PublicPath | undefined {\n if (!Predicate.isString(value)) return undefined\n const href = value.trim()\n\n if (\n !href ||\n href.startsWith('#') ||\n href.startsWith('?') ||\n href.startsWith('//') ||\n /^[a-z][a-z\\d+.-]*:/iu.test(href)\n ) {\n return undefined\n }\n\n const path = href.split(/[?#]/u)[0] ?? ''\n const resolvedPath = resolveRelativePath(path, documentPath)\n const lastSegment = resolvedPath.split('/').at(-1) ?? ''\n\n if (lastSegment.includes('.')) return undefined\n const normalized = normalizePublicPath(resolvedPath)\n\n return Result.isSuccess(normalized) ? normalized.success : undefined\n}\n\nfunction resolveRelativePath(href: string, documentPath: PublicPath): string {\n const normalizedHref = href.replace(/\\\\/gu, '/')\n const segments = normalizedHref.startsWith('/') ? [] : documentPath.split('/').filter(Boolean).slice(0, -1)\n\n for (const segment of normalizedHref.split('/')) {\n if (!segment || segment === '.') continue\n\n if (segment === '..') segments.pop()\n else segments.push(segment)\n }\n\n return `/${segments.join('/')}`\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (const character of value) {\n const codePoint = character.codePointAt(0)\n\n if (codePoint !== undefined && (codePoint <= 31 || codePoint === 127)) return true\n }\n\n return false\n}\n","import type { BlockProp } from '@internal/protocol/Authoring'\nimport type { CompiledDocument, DocumentId, DocumentIssue, MarkdownNode } from '@internal/protocol/Documents'\nimport type { PublicPath, SourcePath } from '@internal/protocol/Documents'\nimport type { CmsComarkAttributes } from '../comark/bindings'\nimport type { NodeRenderData } from 'comark'\nimport type { ResolvedDocumentEngineConfiguration } from './configuration'\nimport type { DocumentReferenceTarget } from './reference-target'\nimport { Option, Predicate, Schema } from 'effect'\nimport { resolveCmsComarkAttributes, withCmsComarkProps } from '../comark/bindings'\nimport { createCmsComarkRenderData } from '../comark/document-adapter'\nimport { referenceTarget, targetKey } from './reference-target'\n\nexport type { DocumentReferenceTarget } from './reference-target'\n\nexport interface DocumentReference {\n readonly nodePath: ReadonlyArray<number>\n readonly source: {\n readonly documentId: DocumentId\n readonly path: PublicPath\n readonly sourcePath: SourcePath\n }\n readonly target: DocumentReferenceTarget\n}\n\nexport interface DocumentReferenceIndex {\n readonly all: ReadonlyArray<DocumentReference>\n readonly impact: (target: DocumentReferenceTarget) => ReadonlyArray<DocumentReference>\n}\n\ninterface IndexedDocumentReferences {\n readonly index: DocumentReferenceIndex\n readonly issues: ReadonlyMap<SourcePath, ReadonlyArray<DocumentIssue>>\n}\n\nconst noReferences: ReadonlyArray<DocumentReference> = Object.freeze([])\n\nexport function createDocumentReferenceIndex(\n documents: ReadonlyArray<CompiledDocument>,\n configuration: ResolvedDocumentEngineConfiguration,\n findByPath: (path: string) => Option.Option<CompiledDocument>,\n): IndexedDocumentReferences {\n const all: DocumentReference[] = []\n const byTarget = new Map<string, DocumentReference[]>()\n const issues = new Map<SourcePath, DocumentIssue[]>()\n\n for (const document of documents) {\n const indexTarget = (target: DocumentReferenceTarget | undefined, nodePath: ReadonlyArray<number>): void => {\n if (!target) return\n\n const reference = freezeReference({\n nodePath,\n source: {\n documentId: document.id,\n path: document.path,\n sourcePath: document.source.path,\n },\n target,\n })\n\n all.push(reference)\n const key = targetKey(target)\n const matching = byTarget.get(key) ?? []\n matching.push(reference)\n byTarget.set(key, matching)\n\n if (target.kind === 'document' && Option.isNone(findByPath(target.path))) {\n addIssue(issues, document.source.path, {\n code: 'reference.document',\n key: target.path,\n message: `Document link \"${target.path}\" does not resolve.`,\n severity: 'error',\n sourcePath: document.source.path,\n })\n }\n }\n\n const seoImageTarget = document.seo?.socialImage\n ? referenceTarget(\n 'img',\n new Map([['src', document.seo.socialImage.url]]),\n document.path,\n configuration.mediaBaseUrl,\n )\n : undefined\n\n indexTarget(\n seoImageTarget?.kind === 'media'\n ? Object.assign({}, seoImageTarget, { mediaId: document.seo?.socialImage?.mediaId })\n : seoImageTarget,\n [],\n )\n\n visit(document.body.nodes, createCmsComarkRenderData(document.body), (tag, attributes, children, nodePath) => {\n const targets = [\n referenceTarget(tag, attributes, document.path, configuration.mediaBaseUrl),\n ...propertyTargets(\n configuration.components?.get(tag.toLowerCase())?.authoring.props ?? [],\n Object.fromEntries([...attributes].flatMap(([key, value]) => (value === undefined ? [] : [[key, value]]))),\n document.path,\n configuration.mediaBaseUrl,\n ),\n ]\n\n for (const target of targets) indexTarget(target, nodePath)\n })\n }\n\n const frozenAll = Object.freeze(all)\n const frozenByTarget = new Map([...byTarget].map(([key, references]) => [key, Object.freeze(references)] as const))\n\n return {\n index: Object.freeze({\n all: frozenAll,\n impact: (target: DocumentReferenceTarget) => frozenByTarget.get(targetKey(target)) ?? noReferences,\n }),\n issues,\n }\n}\n\nfunction visit(\n nodes: CompiledDocument['body']['nodes'],\n renderData: NodeRenderData,\n onElement: (\n tag: string,\n attributes: CmsComarkAttributes,\n children: ReadonlyArray<MarkdownNode>,\n nodePath: ReadonlyArray<number>,\n ) => void,\n parentPath: ReadonlyArray<number> = [],\n): void {\n nodes.forEach((node, index) => {\n if (Predicate.isString(node) || node[0] === null) return\n const [tag, attributes, ...children] = node\n const nodePath = [...parentPath, index]\n const resolved = resolveCmsComarkAttributes(attributes, renderData)\n onElement(tag, resolved, children, nodePath)\n const childrenRenderData = withCmsComarkProps(renderData, resolved)\n visit(children, childrenRenderData, onElement, nodePath)\n })\n}\n\nfunction freezeReference(reference: DocumentReference): DocumentReference {\n return Object.freeze({\n nodePath: Object.freeze([...reference.nodePath]),\n source: Object.freeze({ ...reference.source }),\n target: Object.freeze({ ...reference.target }),\n })\n}\n\nfunction addIssue(issues: Map<SourcePath, DocumentIssue[]>, sourcePath: SourcePath, issue: DocumentIssue): void {\n const sourceIssues = issues.get(sourcePath) ?? []\n sourceIssues.push(issue)\n issues.set(sourcePath, sourceIssues)\n}\n\nfunction propertyTargets(\n fields: ReadonlyArray<BlockProp>,\n values: Schema.JsonObject,\n path: PublicPath,\n mediaBaseUrl: string | undefined,\n): DocumentReferenceTarget[] {\n return fields.flatMap((field) => {\n const value = values[field.name] === undefined ? field.defaultValue : values[field.name]\n\n if (field.input === 'link' || field.input === 'image') {\n const target = referenceTarget(\n field.input === 'link' ? 'a' : 'img',\n new Map([[field.input === 'link' ? 'href' : 'src', value]]),\n path,\n mediaBaseUrl,\n )\n\n return target ? [target] : []\n }\n\n if (field.fields)\n return (Array.isArray(value) ? value : [value]).flatMap((entry) =>\n Schema.is(Schema.JsonObject)(entry) ? propertyTargets(field.fields ?? [], entry, path, mediaBaseUrl) : [],\n )\n\n return []\n })\n}\n","import type { Locale } from '@internal/protocol/Configuration'\nimport type { CompiledDocument, DocumentIssue } from '@internal/protocol/Documents'\nimport type { Option, Result } from 'effect'\nimport type { ResolvedDocumentEngineConfiguration } from './configuration'\nimport type { DocumentReferenceIndex } from './references'\nimport { CompiledDocument as CompiledDocumentSchema } from '@internal/protocol/Documents'\nimport { Result as EffectResult } from 'effect'\nimport { collisionIssues, translationIssues } from './catalog-issues'\nimport { createCatalogLookup } from './catalog-lookup'\nimport { DocumentCompilationFailed } from './errors'\nimport { createDocumentReferenceIndex } from './references'\n\nexport interface DocumentCatalog {\n readonly documents: ReadonlyArray<CompiledDocument>\n readonly issues: ReadonlyArray<DocumentIssue>\n readonly findByKey: (key: string, locale?: Locale) => Option.Option<CompiledDocument>\n readonly findByPath: (path: string) => Option.Option<CompiledDocument>\n readonly references: DocumentReferenceIndex\n}\n\nexport function createDocumentCatalog(\n configuration: ResolvedDocumentEngineConfiguration,\n input: ReadonlyArray<CompiledDocument>,\n): Result.Result<DocumentCatalog, DocumentCompilationFailed> {\n const documents = [...input].sort((left, right) => left.source.path.localeCompare(right.source.path))\n const collisions = collisionIssues(documents)\n\n if (collisions.length > 0) return EffectResult.fail(new DocumentCompilationFailed({ issues: collisions }))\n\n const lookup = createCatalogLookup(documents, configuration)\n const references = createDocumentReferenceIndex(documents, configuration, lookup.findByPath)\n\n const withReferenceIssues = documents.map((document) => {\n const additional = references.issues.get(document.source.path) ?? []\n\n return additional.length === 0\n ? document\n : CompiledDocumentSchema.make(Object.assign({}, document, { issues: [...document.issues, ...additional] }))\n })\n\n return EffectResult.succeed({\n documents: withReferenceIssues,\n issues: [\n ...withReferenceIssues.flatMap((document) => document.issues),\n ...translationIssues(withReferenceIssues, configuration),\n ],\n ...createCatalogLookup(withReferenceIssues, configuration),\n references: references.index,\n } satisfies DocumentCatalog)\n}\n","import type { ComponentDefinition, DocumentConfiguration, CollectionDefinition } from '@internal/protocol/Configuration'\nimport type { DocumentAddress } from '../document-address'\nimport type { ExecutableDocumentModel, ExecutableDocumentSchema } from './document-schema'\nimport { parseDocumentAddress } from '../document-address'\nimport { createAuthoringDocumentValidator, validateCollectionBody } from '../../AuthoringSchema'\nimport { Result } from 'effect'\nimport { DocumentEngineConfigurationInvalid } from './errors'\n\nexport interface ResolvedCollection {\n readonly address: DocumentAddress\n readonly definition: CollectionDefinition\n readonly schema: ExecutableDocumentSchema\n}\n\nexport interface ResolvedDocumentEngineConfiguration {\n readonly components?: ReadonlyMap<string, ComponentDefinition>\n readonly validateAuthoringDocument?: ReturnType<typeof createAuthoringDocumentValidator>\n readonly documents: DocumentConfiguration\n readonly mediaBaseUrl?: string\n readonly types: ReadonlyArray<ResolvedCollection>\n}\n\nexport interface DocumentEngineOptions {\n readonly components?: ReadonlyArray<ComponentDefinition>\n readonly documentModel: ExecutableDocumentModel\n readonly mediaBaseUrl?: string\n}\n\ntype ResolvedDocumentEngineConfigurationBuilder = {\n -readonly [Key in keyof ResolvedDocumentEngineConfiguration]: ResolvedDocumentEngineConfiguration[Key]\n}\n\nexport function resolveDocumentEngineConfiguration(\n documents: DocumentConfiguration,\n options: DocumentEngineOptions,\n): Result.Result<ResolvedDocumentEngineConfiguration, DocumentEngineConfigurationInvalid> {\n if (documents.types.length === 0) return invalid('Documents must define at least one collection.', 'types')\n\n const collections = new Set<string>()\n const directories = new Map<string, string>()\n const resolved: ResolvedCollection[] = []\n\n for (const definition of documents.types) {\n if (collections.has(definition.collection)) {\n return invalid(`Document collection \"${definition.collection}\" is defined more than once.`, 'types')\n }\n\n collections.add(definition.collection)\n\n const existing = directories.get(definition.directory)\n\n if (existing) {\n return invalid(\n `Document collections \"${existing}\" and \"${definition.collection}\" use the same directory \"${definition.directory}\".`,\n 'types',\n )\n }\n\n directories.set(definition.directory, definition.collection)\n\n const addressResult = parseDocumentAddress(definition.addressPattern)\n\n if (Result.isFailure(addressResult)) return invalid(addressResult.failure.message, addressResult.failure.field)\n\n if (definition.hierarchy && !addressResult.success.tokens.some((token) => token.catchAll)) {\n return invalid(\n `Document collection \"${definition.collection}\" can only enable hierarchy with a catch-all address.`,\n 'types',\n )\n }\n\n const schema = options.documentModel.types[definition.collection]\n\n if (!schema)\n return invalid(`Document collection \"${definition.collection}\" has no executable schema.`, 'documentModel')\n\n resolved.push({ address: addressResult.success, definition, schema })\n }\n\n const locales = documents.locales\n\n if (locales) {\n if (new Set(locales.locales).size !== locales.locales.length)\n return invalid('Document locales must be unique.', 'locales.locales')\n\n if (!locales.locales.includes(locales.defaultLocale)) {\n return invalid(`Default locale \"${locales.defaultLocale}\" is not configured.`, 'locales.defaultLocale')\n }\n\n if (locales.fallbackLocale && !locales.locales.includes(locales.fallbackLocale)) {\n return invalid(`Fallback locale \"${locales.fallbackLocale}\" is not configured.`, 'locales.fallbackLocale')\n }\n }\n\n let components: ReadonlyMap<string, ComponentDefinition> | undefined\n let validateAuthoringDocument: ReturnType<typeof createAuthoringDocumentValidator> | undefined\n\n if (options.components !== undefined) {\n const result = resolveComponents(options.components)\n\n if (Result.isFailure(result)) return Result.fail(result.failure)\n components = result.success.components\n validateAuthoringDocument = result.success.validateAuthoringDocument\n\n for (const definition of documents.types) {\n const issues = validateCollectionBody(options.components, definition.body)\n\n if (issues.length) return invalid(`${definition.label}: ${issues.join(' ')}`, 'body')\n }\n }\n\n const mediaBaseUrl = options.mediaBaseUrl?.replace(/\\/+$/u, '')\n\n resolved.sort((left, right) => directoryDepth(right.definition.directory) - directoryDepth(left.definition.directory))\n\n const configuration: ResolvedDocumentEngineConfigurationBuilder = {\n documents,\n types: resolved,\n }\n\n if (components !== undefined) configuration.components = components\n\n if (validateAuthoringDocument !== undefined) configuration.validateAuthoringDocument = validateAuthoringDocument\n\n if (mediaBaseUrl !== undefined) configuration.mediaBaseUrl = mediaBaseUrl\n\n return Result.succeed(configuration satisfies ResolvedDocumentEngineConfiguration)\n}\n\nfunction resolveComponents(definitions: ReadonlyArray<ComponentDefinition>): Result.Result<\n {\n readonly components: ReadonlyMap<string, ComponentDefinition>\n readonly validateAuthoringDocument: ReturnType<typeof createAuthoringDocumentValidator>\n },\n DocumentEngineConfigurationInvalid\n> {\n const components = new Map<string, ComponentDefinition>()\n\n for (const component of definitions) {\n const name = component.name.toLocaleLowerCase()\n\n if (components.has(name))\n return invalid(`Document component \"${component.name}\" is defined more than once.`, 'components')\n components.set(name, component)\n }\n\n try {\n return Result.succeed({ components, validateAuthoringDocument: createAuthoringDocumentValidator(components) })\n } catch (cause) {\n return invalid(cause instanceof Error ? cause.message : 'The component authoring catalog is invalid.', 'components')\n }\n}\n\nfunction directoryDepth(directory: string): number {\n return directory === '.' ? 0 : directory.split('/').length\n}\n\nfunction invalid(message: string, field?: string): Result.Result<never, DocumentEngineConfigurationInvalid> {\n return Result.fail(new DocumentEngineConfigurationInvalid(field === undefined ? { message } : { field, message }))\n}\n","import type { DocumentConfiguration } from '@internal/protocol/Configuration'\nimport type { CompiledDocument, DocumentIssue, DocumentValidationResult } from '@internal/protocol/Documents'\nimport type { DocumentCompilationSource } from './internal/document-engine/compilation-source'\nimport type { DocumentEngineOptions } from './internal/document-engine/configuration'\nimport type { DocumentCompilationFailed, DocumentParseFailed } from './internal/document-engine/errors'\nimport type { DocumentCatalog } from './internal/document-engine/catalog'\nimport { DocumentValidationResult as DocumentValidationResultSchema } from '@internal/protocol/Documents'\nimport { DateTime, Effect, Result, Schema } from 'effect'\nimport { compileCompiledDocument } from './internal/document-engine/compilation'\nimport { DOCUMENT_ENGINE_FINGERPRINT, createDocumentParser } from './internal/comark/grammar'\nimport { createDocumentCatalog } from './internal/document-engine/catalog'\nimport { resolveDocumentEngineConfiguration } from './internal/document-engine/configuration'\nimport { DocumentParseFailed as DocumentParseFailedError } from './internal/document-engine/errors'\n\ntype CompilationError = DocumentCompilationFailed | DocumentParseFailed\n\nexport interface DocumentCatalogCompilation {\n readonly previous?: DocumentCatalog\n readonly sources: ReadonlyArray<DocumentCompilationSource>\n}\n\nconst isDocumentParseFailed = Schema.is(DocumentParseFailedError)\n\n/**\n * Portable authority for compiled Documents. `compileAll` reuses unchanged\n * source compilations from `previous`, then rebuilds the catalog-wide collision,\n * translation, and reference projection. `validate` reports every parse or\n * compilation failure as data and therefore has no error channel.\n */\nexport interface DocumentEngine {\n readonly fingerprint: string\n readonly compile: (source: DocumentCompilationSource) => Effect.Effect<CompiledDocument, CompilationError>\n readonly compileAll: (input: DocumentCatalogCompilation) => Effect.Effect<DocumentCatalog, CompilationError>\n readonly validate: (source: DocumentCompilationSource) => Effect.Effect<DocumentValidationResult>\n}\n\nexport const createDocumentEngine = Effect.fn('DocumentEngine.make')(function* (\n documents: DocumentConfiguration,\n options: DocumentEngineOptions,\n) {\n const configuration = yield* Effect.fromResult(resolveDocumentEngineConfiguration(documents, options))\n const parseMarkdown = createDocumentParser()\n\n const compilations = new WeakMap<\n DocumentCatalog,\n ReadonlyMap<string, { readonly document: CompiledDocument; readonly source: DocumentCompilationSource }>\n >()\n\n const compile = Effect.fn('DocumentEngine.compile')((source: DocumentCompilationSource) =>\n compileCompiledDocument(configuration, parseMarkdown, source),\n )\n\n const compileAll = Effect.fn('DocumentEngine.compileAll')(function* (input: DocumentCatalogCompilation) {\n const previous = input.previous ? compilations.get(input.previous) : undefined\n\n const compiled = yield* Effect.forEach(input.sources, (source) => {\n const cached = previous?.get(source.documentId)\n\n return cached && sameCompilationSource(cached.source, source) ? Effect.succeed(cached.document) : compile(source)\n })\n\n const catalog = yield* Effect.fromResult(createDocumentCatalog(configuration, compiled))\n compilations.set(\n catalog,\n new Map(\n input.sources.map((source, index) => {\n const document = compiled[index]\n\n if (!document) throw new Error(`Compiled document \"${source.documentId}\" is missing.`)\n\n return [source.documentId, { document, source }] as const\n }),\n ),\n )\n\n return catalog\n })\n\n const validate = Effect.fn('DocumentEngine.validate')(function* (source: DocumentCompilationSource) {\n const result = yield* Effect.result(compile(source))\n\n if (Result.isSuccess(result)) {\n const document = result.success\n\n return DocumentValidationResultSchema.make({\n valid: !document.issues.some((issue) => issue.severity === 'error'),\n document,\n issues: document.issues,\n })\n }\n\n const error = result.failure\n\n const issues: ReadonlyArray<DocumentIssue> = isDocumentParseFailed(error)\n ? [\n {\n code: 'markdown.parse',\n message: errorMessage(error.cause),\n severity: 'error',\n sourcePath: error.sourcePath,\n },\n ]\n : error.issues\n\n return DocumentValidationResultSchema.make({\n valid: false,\n issues,\n })\n })\n\n return {\n compile,\n compileAll,\n fingerprint: DOCUMENT_ENGINE_FINGERPRINT,\n validate,\n } satisfies DocumentEngine\n})\n\nfunction sameCompilationSource(left: DocumentCompilationSource, right: DocumentCompilationSource): boolean {\n return (\n left.documentId === right.documentId &&\n left.draft === right.draft &&\n left.markdown === right.markdown &&\n left.sourcePath === right.sourcePath &&\n samePublishedAt(left.publishedAt, right.publishedAt)\n )\n}\n\nfunction samePublishedAt(\n left: DocumentCompilationSource['publishedAt'],\n right: DocumentCompilationSource['publishedAt'],\n): boolean {\n return left === undefined || right === undefined ? left === right : DateTime.Equivalence(left, right)\n}\n\nfunction errorMessage(cause: unknown): string {\n return cause instanceof Error && cause.message ? cause.message : 'Markdown could not be parsed.'\n}\n\nexport { DocumentCompilationSource } from './internal/document-engine/compilation-source'\n\nexport type { DocumentCatalog } from './internal/document-engine/catalog'\n\nexport type { DocumentEngineOptions } from './internal/document-engine/configuration'\n\nexport {\n DocumentCompilationFailed,\n DocumentEngineConfigurationInvalid,\n DocumentParseFailed,\n} from './internal/document-engine/errors'\n\nexport type {\n DocumentReference,\n DocumentReferenceIndex,\n DocumentReferenceTarget,\n} from './internal/document-engine/references'\n\nexport type {\n DocumentSchemaIssue,\n DocumentSchemaProjection,\n DocumentSchemaValidation,\n ExecutableDocumentModel,\n ExecutableDocumentSchema,\n} from './internal/document-engine/document-schema'\n"],"mappings":";;;;;;;AAmBA,MAAM,sBAAsB;AAE5B,SAAgB,qBAAqB,SAA+E;CAGlH,MAAM,SAAS,CAFE,GAAG,QAAQ,SAAS,mBAAmB,CAEnC,CAAC,CAAC,KAAK,WAAW;EACrC,UAAU,MAAM,OAAO;EACvB,MAAM,MAAM,MAAM;CACpB,EAAE;CAIF,IAFkB,QAAQ,QAAQ,qBAAqB,EAE3C,CAAC,CAAC,SAAS,GAAG,KAAK,OAAO,MAAM,UAAU,CAAC,MAAM,IAAI,GAC/D,OAAO,OAAO,KAAK;EACjB,OAAO;EACP,SAAS,6BAA6B,QAAQ;CAChD,CAAC;CAGH,IAAI,OAAO,QAAQ,UAAU,MAAM,QAAQ,CAAC,CAAC,SAAS,GACpD,OAAO,OAAO,KAAK;EACjB,OAAO;EACP,SAAS,6BAA6B,QAAQ;CAChD,CAAC;CAGH,IAAI,IAAI,IAAI,OAAO,KAAK,UAAU,MAAM,IAAI,CAAC,CAAC,CAAC,SAAS,OAAO,QAC7D,OAAO,OAAO,KAAK;EACjB,OAAO;EACP,SAAS,6BAA6B,QAAQ;CAChD,CAAC;CAGH,OAAO,OAAO,QAAQ;EAAE;EAAS;CAAO,CAAC;AAC3C;AAEA,SAAgB,uBACd,SAC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;GACnB,CAAC;EACH;EAEA,MAAM,QAAQ,OAAO;EAErB,MAAM,SAAuC,sBAAsB,KAAK,IACpE,CACE;GACE,MAAM;GACN,SAAS,aAAa,MAAM,KAAK;GACjC,UAAU;GACV,YAAY,MAAM;EACpB,CACF,IACA,MAAM;EAEV,OAAOA,yBAA+B,KAAK;GACzC,OAAO;GACP;EACF,CAAC;CACH,CAAC;CAED,OAAO;EACL;EACA;EACA,aAAa;EACb;CACF;AACF,CAAC;AAED,SAAS,sBAAsB,MAAiC,OAA2C;CACzG,OACE,KAAK,eAAe,MAAM,cAC1B,KAAK,UAAU,MAAM,SACrB,KAAK,aAAa,MAAM,YACxB,KAAK,eAAe,MAAM,cAC1B,gBAAgB,KAAK,aAAa,MAAM,WAAW;AAEvD;AAEA,SAAS,gBACP,MACA,OACS;CACT,OAAO,SAAS,UAAa,UAAU,SAAY,SAAS,QAAQ,SAAS,YAAY,MAAM,KAAK;AACtG;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,SAAS,MAAM,UAAU,MAAM,UAAU;AACnE"}
|
package/src/DocumentModel.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
|
-
import { StandardJSONSchemaV1, StandardSchemaV1 } from "
|
|
2
|
+
import { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
3
|
//#region src/DocumentModel.d.ts
|
|
4
4
|
export type CmsFieldInput = 'date' | 'multiselect' | 'number' | 'select' | 'text' | 'textarea' | 'toggle';
|
|
5
5
|
export interface CmsFieldPresentation {
|
|
6
|
+
/** Use this encoded value only when the containing object key is absent. */
|
|
7
|
+
readonly default?: Schema.Json;
|
|
6
8
|
readonly description?: string;
|
|
7
9
|
readonly input?: CmsFieldInput;
|
|
8
10
|
readonly label?: string;
|
|
@@ -24,9 +26,19 @@ export interface CmsDocumentModelOptions {
|
|
|
24
26
|
readonly collections: Readonly<Record<string, CmsCollectionOptions>>;
|
|
25
27
|
}
|
|
26
28
|
/** Adds CMS presentation metadata without changing the schema's inferred input or output types. */
|
|
27
|
-
export declare function field<const FieldSchema extends Schema.Top>(schema: FieldSchema, presentation: CmsFieldPresentation
|
|
29
|
+
export declare function field<const FieldSchema extends Schema.Top & Schema.Constraint>(schema: FieldSchema, presentation: CmsFieldPresentation & {
|
|
30
|
+
readonly default: FieldSchema['Encoded'] & Schema.Json;
|
|
31
|
+
}): Schema.withDecodingDefaultKey<FieldSchema>;
|
|
32
|
+
export declare function field<const FieldSchema extends Schema.Top & Schema.Constraint>(schema: FieldSchema, presentation: CmsFieldPresentation): FieldSchema['Rebuild'];
|
|
28
33
|
/** Effect schemas work directly; other libraries supply validation and input JSON Schema. */
|
|
29
34
|
export type CmsCollectionSchema = Schema.ConstraintDecoder<unknown> | (StandardSchemaV1 & StandardJSONSchemaV1);
|
|
35
|
+
export interface CmsSchemaOptions<Input, Output> {
|
|
36
|
+
readonly validator: StandardSchemaV1<Input, Output>;
|
|
37
|
+
readonly jsonSchema: StandardJSONSchemaV1<Input, Output>['~standard']['jsonSchema'];
|
|
38
|
+
readonly fields?: Readonly<Record<string, CmsFieldPresentation>>;
|
|
39
|
+
}
|
|
40
|
+
/** Combines library-neutral validation, JSON Schema conversion, and CMS field presentation. */
|
|
41
|
+
export declare function defineCmsSchema<Input, Output>(options: CmsSchemaOptions<Input, Output>): StandardSchemaV1<Input, Output> & StandardJSONSchemaV1<Input, Output>;
|
|
30
42
|
/** A calendar date stored as YYYY-MM-DD, without converting document data to a Date. */
|
|
31
43
|
export declare const CalendarDate: Schema.String;
|
|
32
44
|
//#endregion
|
package/src/DocumentModel.js
CHANGED
|
@@ -1,14 +1,42 @@
|
|
|
1
1
|
import { FIELD_INPUT_METADATA } from "./internal/field-metadata.js";
|
|
2
|
-
import { DateTime, Option, Schema } from "effect";
|
|
2
|
+
import { DateTime, Effect, Option, Result, Schema } from "effect";
|
|
3
3
|
|
|
4
4
|
//#region src/DocumentModel.ts
|
|
5
|
-
/** Adds CMS presentation metadata without changing the schema's inferred input or output types. */
|
|
6
5
|
function field(schema, presentation) {
|
|
7
|
-
|
|
6
|
+
const annotated = schema.pipe(Schema.annotateEncoded({
|
|
7
|
+
...presentation.default === void 0 ? void 0 : { default: presentation.default },
|
|
8
8
|
...presentation.description === void 0 ? void 0 : { description: presentation.description },
|
|
9
9
|
...presentation.input === void 0 ? void 0 : { [FIELD_INPUT_METADATA]: presentation.input },
|
|
10
10
|
...presentation.label === void 0 ? void 0 : { title: presentation.label }
|
|
11
11
|
}));
|
|
12
|
+
return presentation.default === void 0 ? annotated : annotated.pipe(Schema.withDecodingDefaultKey(Effect.succeed(presentation.default)));
|
|
13
|
+
}
|
|
14
|
+
/** Combines library-neutral validation, JSON Schema conversion, and CMS field presentation. */
|
|
15
|
+
function defineCmsSchema(options) {
|
|
16
|
+
return { "~standard": {
|
|
17
|
+
...options.validator["~standard"],
|
|
18
|
+
jsonSchema: {
|
|
19
|
+
input: (conversion) => applyFieldPresentation(options.jsonSchema.input(conversion), options.fields),
|
|
20
|
+
output: options.jsonSchema.output
|
|
21
|
+
}
|
|
22
|
+
} };
|
|
23
|
+
}
|
|
24
|
+
function applyFieldPresentation(schema, fields) {
|
|
25
|
+
if (!fields) return schema;
|
|
26
|
+
const copy = Result.getOrThrow(Schema.decodeUnknownResult(Schema.JsonObject)(structuredClone(schema)));
|
|
27
|
+
for (const [path, presentation] of Object.entries(fields)) {
|
|
28
|
+
let current = copy;
|
|
29
|
+
for (const segment of path.split(".")) {
|
|
30
|
+
const properties = current.properties;
|
|
31
|
+
const property = Schema.is(Schema.JsonObject)(properties) ? properties[segment] : void 0;
|
|
32
|
+
if (!Schema.is(Schema.JsonObject)(property)) throw new Error(`CMS field presentation path ${path} does not exist in the input JSON Schema.`);
|
|
33
|
+
current = property;
|
|
34
|
+
}
|
|
35
|
+
if (presentation.description !== void 0) Object.assign(current, { description: presentation.description });
|
|
36
|
+
if (presentation.input !== void 0) Object.assign(current, { "x-cms-input": presentation.input });
|
|
37
|
+
if (presentation.label !== void 0) Object.assign(current, { title: presentation.label });
|
|
38
|
+
}
|
|
39
|
+
return copy;
|
|
12
40
|
}
|
|
13
41
|
/** A calendar date stored as YYYY-MM-DD, without converting document data to a Date. */
|
|
14
42
|
const CalendarDate = Schema.String.annotate({ format: "date" }).check(Schema.makeFilter((value) => {
|
|
@@ -21,5 +49,5 @@ const CalendarDate = Schema.String.annotate({ format: "date" }).check(Schema.mak
|
|
|
21
49
|
}));
|
|
22
50
|
|
|
23
51
|
//#endregion
|
|
24
|
-
export { CalendarDate, field };
|
|
52
|
+
export { CalendarDate, defineCmsSchema, field };
|
|
25
53
|
//# sourceMappingURL=DocumentModel.js.map
|
package/src/DocumentModel.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DocumentModel.js","names":[],"sources":["../../../src/DocumentModel.ts"],"sourcesContent":["import type { StandardJSONSchemaV1, StandardSchemaV1 } from '
|
|
1
|
+
{"version":3,"file":"DocumentModel.js","names":[],"sources":["../../../src/DocumentModel.ts"],"sourcesContent":["import type { StandardJSONSchemaV1, StandardSchemaV1 } from '@standard-schema/spec'\nimport { DateTime, Effect, Option, Result, Schema } from 'effect'\nimport { FIELD_INPUT_METADATA } from './internal/field-metadata'\n\nexport type CmsFieldInput = 'date' | 'multiselect' | 'number' | 'select' | 'text' | 'textarea' | 'toggle'\n\nexport interface CmsFieldPresentation {\n /** Use this encoded value only when the containing object key is absent. */\n readonly default?: Schema.Json\n readonly description?: string\n readonly input?: CmsFieldInput\n readonly label?: string\n}\n\nexport interface CmsCollectionOptions {\n readonly body?: {\n readonly blocks?: ReadonlyArray<string>\n readonly groups?: ReadonlyArray<string>\n }\n readonly canCreate?: boolean\n readonly description?: string\n readonly hierarchy?: boolean\n readonly label: string\n readonly route: string\n readonly schema: CmsCollectionSchema\n readonly source?: string\n}\n\nexport interface CmsDocumentModelOptions {\n readonly collections: Readonly<Record<string, CmsCollectionOptions>>\n}\n\n/** Adds CMS presentation metadata without changing the schema's inferred input or output types. */\nexport function field<const FieldSchema extends Schema.Top & Schema.Constraint>(\n schema: FieldSchema,\n presentation: CmsFieldPresentation & { readonly default: FieldSchema['Encoded'] & Schema.Json },\n): Schema.withDecodingDefaultKey<FieldSchema>\nexport function field<const FieldSchema extends Schema.Top & Schema.Constraint>(\n schema: FieldSchema,\n presentation: CmsFieldPresentation,\n): FieldSchema['Rebuild']\nexport function field(\n schema: Schema.Top & Schema.Constraint,\n presentation: CmsFieldPresentation,\n): Schema.Top & Schema.Constraint {\n const annotated = schema.pipe(\n Schema.annotateEncoded({\n ...(presentation.default === undefined ? undefined : { default: presentation.default }),\n ...(presentation.description === undefined ? undefined : { description: presentation.description }),\n ...(presentation.input === undefined ? undefined : { [FIELD_INPUT_METADATA]: presentation.input }),\n ...(presentation.label === undefined ? undefined : { title: presentation.label }),\n }),\n )\n\n return presentation.default === undefined\n ? annotated\n : annotated.pipe(Schema.withDecodingDefaultKey(Effect.succeed(presentation.default)))\n}\n\n/** Effect schemas work directly; other libraries supply validation and input JSON Schema. */\nexport type CmsCollectionSchema = Schema.ConstraintDecoder<unknown> | (StandardSchemaV1 & StandardJSONSchemaV1)\n\nexport interface CmsSchemaOptions<Input, Output> {\n readonly validator: StandardSchemaV1<Input, Output>\n readonly jsonSchema: StandardJSONSchemaV1<Input, Output>['~standard']['jsonSchema']\n readonly fields?: Readonly<Record<string, CmsFieldPresentation>>\n}\n\ntype JsonSchema = ReturnType<StandardJSONSchemaV1['~standard']['jsonSchema']['input']>\n\n/** Combines library-neutral validation, JSON Schema conversion, and CMS field presentation. */\nexport function defineCmsSchema<Input, Output>(\n options: CmsSchemaOptions<Input, Output>,\n): StandardSchemaV1<Input, Output> & StandardJSONSchemaV1<Input, Output> {\n return {\n '~standard': {\n ...options.validator['~standard'],\n jsonSchema: {\n input: (conversion) => applyFieldPresentation(options.jsonSchema.input(conversion), options.fields),\n output: options.jsonSchema.output,\n },\n },\n }\n}\n\nfunction applyFieldPresentation(\n schema: JsonSchema,\n fields?: Readonly<Record<string, CmsFieldPresentation>>,\n): JsonSchema {\n if (!fields) return schema\n const copy = Result.getOrThrow(Schema.decodeUnknownResult(Schema.JsonObject)(structuredClone(schema)))\n\n for (const [path, presentation] of Object.entries(fields)) {\n let current: Schema.JsonObject = copy\n\n for (const segment of path.split('.')) {\n const properties = current.properties\n const property = Schema.is(Schema.JsonObject)(properties) ? properties[segment] : undefined\n\n if (!Schema.is(Schema.JsonObject)(property)) {\n throw new Error(`CMS field presentation path ${path} does not exist in the input JSON Schema.`)\n }\n\n current = property\n }\n\n if (presentation.description !== undefined) Object.assign(current, { description: presentation.description })\n\n if (presentation.input !== undefined) Object.assign(current, { 'x-cms-input': presentation.input })\n\n if (presentation.label !== undefined) Object.assign(current, { title: presentation.label })\n }\n\n return copy\n}\n\n/** A calendar date stored as YYYY-MM-DD, without converting document data to a Date. */\nexport const CalendarDate = Schema.String.annotate({ format: 'date' }).check(\n Schema.makeFilter(\n (value) => {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/u.test(value)) return false\n const parsed = DateTime.make(value)\n\n return Option.isSome(parsed) && DateTime.formatIsoDate(parsed.value) === value\n },\n { message: 'Expected a valid date in YYYY-MM-DD format.', toJsonSchema: () => ({}) },\n ),\n)\n"],"mappings":";;;;AAyCA,SAAgB,MACd,QACA,cACgC;CAChC,MAAM,YAAY,OAAO,KACvB,OAAO,gBAAgB;EACrB,GAAI,aAAa,YAAY,SAAY,SAAY,EAAE,SAAS,aAAa,QAAQ;EACrF,GAAI,aAAa,gBAAgB,SAAY,SAAY,EAAE,aAAa,aAAa,YAAY;EACjG,GAAI,aAAa,UAAU,SAAY,SAAY,GAAG,uBAAuB,aAAa,MAAM;EAChG,GAAI,aAAa,UAAU,SAAY,SAAY,EAAE,OAAO,aAAa,MAAM;CACjF,CAAC,CACH;CAEA,OAAO,aAAa,YAAY,SAC5B,YACA,UAAU,KAAK,OAAO,uBAAuB,OAAO,QAA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,KAAK,SAAS,cAAc,OAAO,KAAK,MAAM;AAC3E,GACA;CAAE,SAAS;CAA+C,qBAAqB,CAAC;AAAG,CACrF,CACF"}
|
|
@@ -29,18 +29,41 @@ const FormOption = Schema.Struct({
|
|
|
29
29
|
id: Schema.NonEmptyString,
|
|
30
30
|
label: Schema.NonEmptyString
|
|
31
31
|
});
|
|
32
|
-
const
|
|
32
|
+
const formFieldBase = {
|
|
33
33
|
id: Schema.NonEmptyString,
|
|
34
34
|
label: Schema.NonEmptyString,
|
|
35
|
-
type: FormFieldType,
|
|
36
35
|
help: Schema.optionalKey(Schema.String),
|
|
37
|
-
required: Schema.optionalKey(Schema.Boolean)
|
|
36
|
+
required: Schema.optionalKey(Schema.Boolean)
|
|
37
|
+
};
|
|
38
|
+
const formTextField = (type) => Schema.Struct({
|
|
39
|
+
...formFieldBase,
|
|
40
|
+
type: Schema.Literals([type]),
|
|
38
41
|
minLength: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
|
|
39
|
-
maxLength: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)))
|
|
42
|
+
maxLength: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)))
|
|
43
|
+
});
|
|
44
|
+
const FormNumberField = Schema.Struct({
|
|
45
|
+
...formFieldBase,
|
|
46
|
+
type: Schema.Literals(["number"]),
|
|
40
47
|
min: Schema.optionalKey(Schema.Finite),
|
|
41
|
-
max: Schema.optionalKey(Schema.Finite)
|
|
42
|
-
|
|
48
|
+
max: Schema.optionalKey(Schema.Finite)
|
|
49
|
+
});
|
|
50
|
+
const FormCheckboxField = Schema.Struct({
|
|
51
|
+
...formFieldBase,
|
|
52
|
+
type: Schema.Literals(["checkbox"])
|
|
53
|
+
});
|
|
54
|
+
const FormSelectField = Schema.Struct({
|
|
55
|
+
...formFieldBase,
|
|
56
|
+
type: Schema.Literals(["select"]),
|
|
57
|
+
options: Schema.NonEmptyArray(FormOption)
|
|
43
58
|
});
|
|
59
|
+
const FormField = Schema.Union([
|
|
60
|
+
formTextField("text"),
|
|
61
|
+
formTextField("email"),
|
|
62
|
+
formTextField("textarea"),
|
|
63
|
+
FormNumberField,
|
|
64
|
+
FormCheckboxField,
|
|
65
|
+
FormSelectField
|
|
66
|
+
]);
|
|
44
67
|
const FormStep = Schema.Struct({
|
|
45
68
|
id: Schema.NonEmptyString,
|
|
46
69
|
title: Schema.NonEmptyString,
|
|
@@ -63,17 +86,25 @@ const FormSubmission = Schema.Struct({
|
|
|
63
86
|
...referenceFields,
|
|
64
87
|
values: FormValues
|
|
65
88
|
});
|
|
66
|
-
const
|
|
67
|
-
status: Schema.Literals([
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
"failed"
|
|
73
|
-
]),
|
|
89
|
+
const AcceptedFormResult = Schema.Struct({
|
|
90
|
+
status: Schema.Literals(["accepted"]),
|
|
91
|
+
reference: Schema.optionalKey(Schema.NonEmptyString)
|
|
92
|
+
});
|
|
93
|
+
const InvalidFormResult = Schema.Struct({
|
|
94
|
+
status: Schema.Literals(["invalid"]),
|
|
74
95
|
errors: Schema.Record(Schema.String, Schema.String)
|
|
75
96
|
});
|
|
97
|
+
const StaleFormResult = Schema.Struct({ status: Schema.Literals(["stale"]) });
|
|
98
|
+
const UnavailableFormResult = Schema.Struct({ status: Schema.Literals(["unavailable"]) });
|
|
99
|
+
const FailedFormResult = Schema.Struct({ status: Schema.Literals(["failed"]) });
|
|
100
|
+
const FormResult = Schema.Union([
|
|
101
|
+
AcceptedFormResult,
|
|
102
|
+
InvalidFormResult,
|
|
103
|
+
StaleFormResult,
|
|
104
|
+
UnavailableFormResult,
|
|
105
|
+
FailedFormResult
|
|
106
|
+
]);
|
|
76
107
|
|
|
77
108
|
//#endregion
|
|
78
|
-
export {
|
|
79
|
-
//# sourceMappingURL=Forms-
|
|
109
|
+
export { FormOption as a, FormSubmission as c, FormFieldType as i, FORM_SUBMISSION_MAX_BYTES as n, FormResult as o, FormCapabilities as r, FormSteps as s, FORM_REVISION_MAX_BYTES as t };
|
|
110
|
+
//# sourceMappingURL=Forms-BbkE7QfC.js.map
|