@phtngyn/cms 0.1.0-beta.1 → 0.1.0-beta.3

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.
Files changed (143) hide show
  1. package/README.md +212 -12
  2. package/bin/cms.mjs +2 -0
  3. package/package.json +30 -15
  4. package/src/{Configuration-DyKo0sLS.js → Configuration-CDMYfTre.js} +26 -147
  5. package/src/Configuration-CDMYfTre.js.map +1 -0
  6. package/src/Configuration.d.ts +24 -8
  7. package/src/Configuration.js +0 -1
  8. package/src/Configuration.js.map +1 -1
  9. package/src/ContentTransfer-C3Av9sWz.js +53 -0
  10. package/src/ContentTransfer-C3Av9sWz.js.map +1 -0
  11. package/src/{DocumentEngine-DYObwMDY.js → DocumentEngine-J7g-emdf.js} +75 -27
  12. package/src/DocumentEngine-J7g-emdf.js.map +1 -0
  13. package/src/DocumentModel.d.ts +8 -9
  14. package/src/DocumentModel.js +13 -3
  15. package/src/DocumentModel.js.map +1 -1
  16. package/src/Forms-BsJMev5_.d.ts +74 -0
  17. package/src/Forms-CfcI3tPU.js +79 -0
  18. package/src/Forms-CfcI3tPU.js.map +1 -0
  19. package/src/Forms-Dj6NuW66.js +367 -0
  20. package/src/Forms-Dj6NuW66.js.map +1 -0
  21. package/src/Forms.d.ts +51 -0
  22. package/src/Forms.js +13 -0
  23. package/src/Forms.js.map +1 -0
  24. package/src/{HttpPaths-BbS21Jy8.js → HttpPaths-c9nLZ9H2.js} +6 -2
  25. package/src/HttpPaths-c9nLZ9H2.js.map +1 -0
  26. package/src/I18n.d.ts +20 -0
  27. package/src/I18n.js +1 -0
  28. package/src/Module.js +59 -14
  29. package/src/Module.js.map +1 -1
  30. package/src/S3MediaObjects-CpPSzJto.js +2777 -0
  31. package/src/S3MediaObjects-CpPSzJto.js.map +1 -0
  32. package/src/Seo-402YumpT.d.ts +198 -0
  33. package/src/cli/content.js +258 -0
  34. package/src/cli/content.js.map +1 -0
  35. package/src/cli.js +71 -0
  36. package/src/cli.js.map +1 -0
  37. package/src/{connection-CBTY-TzB.js → connection-CBAy2qGy.js} +5 -7
  38. package/src/connection-CBAy2qGy.js.map +1 -0
  39. package/src/{installation-DeuBiFRE.js → installation-CNfIriVm.js} +1007 -2246
  40. package/src/installation-CNfIriVm.js.map +1 -0
  41. package/src/internal/authoring-catalog.js +10 -4
  42. package/src/internal/authoring-catalog.js.map +1 -1
  43. package/src/internal/authoring-compiler.js +0 -1
  44. package/src/internal/authoring-compiler.js.map +1 -1
  45. package/src/internal/authoring-metadata.js +4 -4
  46. package/src/internal/authoring-metadata.js.map +1 -1
  47. package/src/internal/cms-config.js +0 -1
  48. package/src/internal/cms-config.js.map +1 -1
  49. package/src/internal/configuration.js +26 -17
  50. package/src/internal/configuration.js.map +1 -1
  51. package/src/internal/document-model.js +69 -21
  52. package/src/internal/document-model.js.map +1 -1
  53. package/src/internal/form-capabilities.js +12 -0
  54. package/src/internal/form-capabilities.js.map +1 -0
  55. package/src/internal/i18n.js +47 -0
  56. package/src/internal/i18n.js.map +1 -0
  57. package/src/internal/studio-app.js +2 -2
  58. package/src/internal/studio-app.js.map +1 -1
  59. package/src/{location-DtYv2aes.js → location-BTqdfIzX.js} +2 -3
  60. package/src/location-BTqdfIzX.js.map +1 -0
  61. package/src/{metadata-DE1Mc2td.js → metadata-BEZPWh-3.js} +3 -72
  62. package/src/metadata-BEZPWh-3.js.map +1 -0
  63. package/src/{models-C3witQBK.js → models-B4IoTmp7.js} +3 -2
  64. package/src/models-B4IoTmp7.js.map +1 -0
  65. package/src/{models-BkMgeaOL.js → models-Bah5B3bT.js} +205 -51
  66. package/src/models-Bah5B3bT.js.map +1 -0
  67. package/src/runtime/blocks.js +22 -9
  68. package/src/runtime/blocks.js.map +1 -1
  69. package/src/runtime/collaboration.js.map +1 -1
  70. package/src/runtime/delivery/DocumentRenderer.js +7 -4
  71. package/src/runtime/delivery/DocumentRenderer.js.map +1 -1
  72. package/src/runtime/delivery/blocks.js +3 -1
  73. package/src/runtime/delivery/blocks.js.map +1 -1
  74. package/src/runtime/delivery/context.js +1 -1
  75. package/src/runtime/delivery/document-page.js +12 -12
  76. package/src/runtime/delivery/document-page.js.map +1 -1
  77. package/src/runtime/delivery/document.js +4 -2
  78. package/src/runtime/delivery/document.js.map +1 -1
  79. package/src/runtime/delivery/error.js.map +1 -1
  80. package/src/runtime/delivery/plugin.js +28 -2
  81. package/src/runtime/delivery/plugin.js.map +1 -1
  82. package/src/runtime/delivery/types.d.ts +5 -0
  83. package/src/runtime/delivery/useCmsDocumentSeo.d.ts +59 -0
  84. package/src/runtime/delivery/useCmsDocumentSeo.js +101 -0
  85. package/src/runtime/delivery/useCmsDocumentSeo.js.map +1 -0
  86. package/src/runtime/delivery/useDocument.js +2 -2
  87. package/src/runtime/delivery/useDocument.js.map +1 -1
  88. package/src/runtime/delivery/useDocumentQuery.js +2 -2
  89. package/src/runtime/delivery/useDocumentQuery.js.map +1 -1
  90. package/src/runtime/forms/document.js +38 -0
  91. package/src/runtime/forms/document.js.map +1 -0
  92. package/src/runtime/forms/useCmsForm.js +190 -0
  93. package/src/runtime/forms/useCmsForm.js.map +1 -0
  94. package/src/runtime/i18n/translator.js +51 -0
  95. package/src/runtime/i18n/translator.js.map +1 -0
  96. package/src/runtime/i18n/useCmsI18n.d.ts +11 -0
  97. package/src/runtime/i18n/useCmsI18n.js +37 -0
  98. package/src/runtime/i18n/useCmsI18n.js.map +1 -0
  99. package/src/runtime/installation.js +1 -1
  100. package/src/runtime/plugin.js +3 -3
  101. package/src/runtime/plugin.js.map +1 -1
  102. package/src/runtime/preview/comark-document.js +0 -1
  103. package/src/runtime/preview/comark-document.js.map +1 -1
  104. package/src/runtime/preview/connection.js +1 -1
  105. package/src/runtime/preview/controller.js +10 -3
  106. package/src/runtime/preview/controller.js.map +1 -1
  107. package/src/runtime/preview/overlay.js.map +1 -1
  108. package/src/runtime/preview/plugin.client.js +59 -48
  109. package/src/runtime/preview/plugin.client.js.map +1 -1
  110. package/src/runtime/preview/protocol.js.map +1 -1
  111. package/src/runtime/preview/store.js +1 -1
  112. package/src/runtime/preview/targets.js +0 -1
  113. package/src/runtime/preview/targets.js.map +1 -1
  114. package/src/runtime/sitemap-entries.js +17 -0
  115. package/src/runtime/sitemap-entries.js.map +1 -0
  116. package/src/runtime/sitemap.js +24 -0
  117. package/src/runtime/sitemap.js.map +1 -0
  118. package/src/runtime/studio-app.js.map +1 -1
  119. package/src/runtime/studio-entry.js +2 -2
  120. package/src/runtime/studio-entry.js.map +1 -1
  121. package/src/runtime/studio-navigation.js +1 -1
  122. package/src/scalars-B2lgGUnj.js +26 -0
  123. package/src/scalars-B2lgGUnj.js.map +1 -0
  124. package/src/{store-CfFFx9Ua.js → store-b2CSXgMt.js} +12 -7
  125. package/src/store-b2CSXgMt.js.map +1 -0
  126. package/studio/{CreateDocumentDialog--L9lTfx6.js → CreateDocumentDialog-GGey1uBc.js} +44 -44
  127. package/studio/{collaboration-DUuu678R.js → collaboration-DcK2F6v9.js} +7 -6
  128. package/studio/{documentPlanning-BXX04Woe.js → documentPlanning-DRErYmBU.js} +7340 -6469
  129. package/studio/{editor-PexnXkJY.js → editor-Bzlh3zXt.js} +7965 -7955
  130. package/studio/host.css +1 -1
  131. package/studio/host.js +10416 -7981
  132. package/src/Configuration-DyKo0sLS.js.map +0 -1
  133. package/src/DocumentEngine-DYObwMDY.js.map +0 -1
  134. package/src/HttpPaths-BbS21Jy8.js.map +0 -1
  135. package/src/StudioHttp-jR2-bc01.js +0 -718
  136. package/src/StudioHttp-jR2-bc01.js.map +0 -1
  137. package/src/connection-CBTY-TzB.js.map +0 -1
  138. package/src/installation-DeuBiFRE.js.map +0 -1
  139. package/src/location-DtYv2aes.js.map +0 -1
  140. package/src/metadata-DE1Mc2td.js.map +0 -1
  141. package/src/models-BkMgeaOL.js.map +0 -1
  142. package/src/models-C3witQBK.js.map +0 -1
  143. package/src/store-CfFFx9Ua.js.map +0 -1
@@ -1,9 +1,10 @@
1
- import { d as DocumentIssue, n as CmsMarkdownDocument, r as CompiledDocument, t as CmsDocumentAnalysis, v as DocumentSourceMapping, wt as SourcePath, x as DocumentValidationResult, yt as PublicPath } from "./models-BkMgeaOL.js";
2
- import { c as createCmsComarkRenderData, s as cmsComarkTextContent } from "./metadata-DE1Mc2td.js";
3
- import { E as normalizeCmsComponentBindings, O as resolveCmsComarkAttributes, c as validateAuthoringDocument, f as DOCUMENT_ENGINE_FINGERPRINT, k as withCmsComarkProps, l as validateCollectionBody, m as SOURCE_MAPPINGS_META_KEY, p as createDocumentParser } from "./Configuration-DyKo0sLS.js";
4
- import { Effect, Option, Predicate, Result, Schema } from "effect";
1
+ import { d as SourcePath, o as PublicPath } from "./scalars-B2lgGUnj.js";
2
+ import { c as resolveCmsComarkAttributes, d as createCmsComarkRenderData, l as withCmsComarkProps, o as normalizeCmsComponentBindings, u as cmsComarkTextContent } from "./Forms-Dj6NuW66.js";
3
+ import { M as DocumentSeo, c as DocumentIssue, h as DocumentSourceMapping, n as CmsMarkdownDocument, r as CompiledDocument, t as CmsDocumentAnalysis, v as DocumentValidationResult } from "./models-Bah5B3bT.js";
4
+ import { f as DOCUMENT_ENGINE_FINGERPRINT, l as validateCollectionBody, m as SOURCE_MAPPINGS_META_KEY, o as createAuthoringDocumentValidator, p as createDocumentParser } from "./Configuration-CDMYfTre.js";
5
+ import { DateTime, Effect, Option, Predicate, Result, Schema } from "effect";
5
6
 
6
- //#region ../protocol/src/internal/documents/address.ts
7
+ //#region ../document/src/internal/document-address.ts
7
8
  const addressTokenPattern = /:([a-z][\w.]*)(\*)?/giu;
8
9
  function parseDocumentAddress(pattern) {
9
10
  const tokens = [...pattern.matchAll(addressTokenPattern)].map((match) => ({
@@ -220,7 +221,7 @@ const validateFrontmatter = Effect.fn("DocumentEngine.validateFrontmatter")(func
220
221
  };
221
222
  }
222
223
  const parsed = Schema.decodeUnknownOption(Schema.JsonObject)(result.value);
223
- if (parsed._tag === "None") {
224
+ if (Option.isNone(parsed)) {
224
225
  issues.push(issue("schema.constraint", "The collection schema output must be a JSON-compatible object.", type, sourcePath, "frontmatter"));
225
226
  return {
226
227
  data: projection.value,
@@ -280,8 +281,10 @@ const compileCompiledDocument = Effect.fn("DocumentEngine.compileDocument")(func
280
281
  const parsedBody = yield* parseBody(parseMarkdown, source);
281
282
  const mappings = yield* sourceMappings(parsedBody, source);
282
283
  const body = normalizeCmsComponentBindings(withoutSourceMappings(parsedBody), configuration.components);
284
+ const { collectionFrontmatter, rawSeo } = splitFrontmatter(body.frontmatter);
285
+ const seoProjection = projectSeo(rawSeo, source.sourcePath);
283
286
  const relativeKey = yield* fromAddressResult(documentKeyFromSourcePath(location.relativeSourcePath), source.sourcePath);
284
- const validation = yield* validateFrontmatter(body.frontmatter, location.type.schema, location.type.definition, source.sourcePath).pipe(Effect.mapError((cause) => new DocumentCompilationFailed({ issues: [{
287
+ const validation = yield* validateFrontmatter(collectionFrontmatter, location.type.schema, location.type.definition, source.sourcePath).pipe(Effect.mapError((cause) => new DocumentCompilationFailed({ issues: [{
285
288
  code: "schema.constraint",
286
289
  collection: location.type.definition.collection,
287
290
  message: cause.message,
@@ -294,8 +297,9 @@ const compileCompiledDocument = Effect.fn("DocumentEngine.compileDocument")(func
294
297
  const title = stringValue(validation.data.title) ?? stringValue(body.meta.title) ?? titleFromSource(location.relativeSourcePath);
295
298
  const description = stringValue(validation.data.description) ?? stringValue(body.meta.description);
296
299
  const issues = Result.isSuccess(address) ? validation.issues : [...validation.issues, addressIssue(address.failure, source.sourcePath)];
300
+ const canonicalFrontmatter = rawSeo === void 0 ? validation.data : Object.assign({ _seo: rawSeo }, validation.data);
297
301
  const canonicalBody = CmsMarkdownDocument.make({
298
- frontmatter: validation.data,
302
+ frontmatter: canonicalFrontmatter,
299
303
  meta: body.meta,
300
304
  nodes: body.nodes
301
305
  });
@@ -311,21 +315,48 @@ const compileCompiledDocument = Effect.fn("DocumentEngine.compileDocument")(func
311
315
  draft: source.draft,
312
316
  title,
313
317
  data: validation.data,
314
- issues: [...issues, ...validateAuthoringDocument(canonicalBody, configuration.components, location.type.definition.body).map((message) => ({
315
- code: "reference.component",
316
- message,
317
- severity: "error",
318
- sourcePath: source.sourcePath
319
- }))],
318
+ issues: [
319
+ ...issues,
320
+ ...seoProjection.issues,
321
+ ...(configuration.validateAuthoringDocument?.(canonicalBody, location.type.definition.body) ?? []).map((message) => ({
322
+ code: "reference.component",
323
+ message,
324
+ severity: "error",
325
+ sourcePath: source.sourcePath
326
+ }))
327
+ ],
320
328
  analysis,
321
329
  body: canonicalBody,
322
330
  engineFingerprint: DOCUMENT_ENGINE_FINGERPRINT,
323
331
  source: {
324
332
  path: source.sourcePath,
325
- mappings
333
+ mappings,
334
+ ...source.publishedAt === void 0 ? void 0 : { publishedAt: source.publishedAt }
326
335
  }
327
- }, location.locale === void 0 ? void 0 : { locale: location.locale }, description === void 0 ? void 0 : { description }));
336
+ }, location.locale === void 0 ? void 0 : { locale: location.locale }, description === void 0 ? void 0 : { description }, seoProjection.seo === void 0 ? void 0 : { seo: seoProjection.seo }));
328
337
  });
338
+ function splitFrontmatter(frontmatter) {
339
+ const { _seo: rawSeo, ...collectionFrontmatter } = frontmatter;
340
+ return {
341
+ collectionFrontmatter,
342
+ rawSeo
343
+ };
344
+ }
345
+ function projectSeo(rawSeo, sourcePath) {
346
+ if (rawSeo === void 0) return { issues: [] };
347
+ const decoded = Schema.decodeUnknownResult(DocumentSeo)(rawSeo, { onExcessProperty: "error" });
348
+ if (Result.isSuccess(decoded)) return {
349
+ issues: [],
350
+ seo: decoded.success
351
+ };
352
+ return { issues: [{
353
+ code: "seo.invalid",
354
+ field: "_seo",
355
+ message: `Document SEO is invalid: ${String(decoded.failure)}`,
356
+ severity: "error",
357
+ sourcePath
358
+ }] };
359
+ }
329
360
  function provisionalKey(documentId) {
330
361
  return PublicPath.make(`/_cms-invalid/${documentId}`);
331
362
  }
@@ -602,10 +633,9 @@ function createDocumentReferenceIndex(documents, configuration, findByPath) {
602
633
  const all = [];
603
634
  const byTarget = /* @__PURE__ */ new Map();
604
635
  const issues = /* @__PURE__ */ new Map();
605
- for (const document of documents) visit(document.body.nodes, createCmsComarkRenderData(document.body), (tag, attributes, children, nodePath) => {
606
- const targets = [referenceTarget(tag, attributes, document.path, configuration.mediaBaseUrl), ...propertyTargets(configuration.components?.get(tag.toLowerCase())?.authoring.props ?? [], Object.fromEntries([...attributes].flatMap(([key, value]) => value === void 0 ? [] : [[key, value]])), document.path, configuration.mediaBaseUrl)];
607
- for (const target of targets) {
608
- if (!target) continue;
636
+ for (const document of documents) {
637
+ const indexTarget = (target, nodePath) => {
638
+ if (!target) return;
609
639
  const reference = freezeReference({
610
640
  nodePath,
611
641
  source: {
@@ -627,8 +657,14 @@ function createDocumentReferenceIndex(documents, configuration, findByPath) {
627
657
  severity: "error",
628
658
  sourcePath: document.source.path
629
659
  });
630
- }
631
- });
660
+ };
661
+ const seoImageTarget = document.seo?.socialImage ? referenceTarget("img", /* @__PURE__ */ new Map([["src", document.seo.socialImage.url]]), document.path, configuration.mediaBaseUrl) : void 0;
662
+ indexTarget(seoImageTarget?.kind === "media" ? Object.assign({}, seoImageTarget, { mediaId: document.seo?.socialImage?.mediaId }) : seoImageTarget, []);
663
+ visit(document.body.nodes, createCmsComarkRenderData(document.body), (tag, attributes, children, nodePath) => {
664
+ const targets = [referenceTarget(tag, attributes, document.path, configuration.mediaBaseUrl), ...propertyTargets(configuration.components?.get(tag.toLowerCase())?.authoring.props ?? [], Object.fromEntries([...attributes].flatMap(([key, value]) => value === void 0 ? [] : [[key, value]])), document.path, configuration.mediaBaseUrl)];
665
+ for (const target of targets) indexTarget(target, nodePath);
666
+ });
667
+ }
632
668
  const frozenAll = Object.freeze(all);
633
669
  const frozenByTarget = new Map([...byTarget].map(([key, references]) => [key, Object.freeze(references)]));
634
670
  return {
@@ -724,10 +760,12 @@ function resolveDocumentEngineConfiguration(documents, options) {
724
760
  if (locales.fallbackLocale && !locales.locales.includes(locales.fallbackLocale)) return invalid(`Fallback locale "${locales.fallbackLocale}" is not configured.`, "locales.fallbackLocale");
725
761
  }
726
762
  let components;
763
+ let validateAuthoringDocument;
727
764
  if (options.components !== void 0) {
728
765
  const result = resolveComponents(options.components);
729
766
  if (Result.isFailure(result)) return Result.fail(result.failure);
730
- components = result.success;
767
+ components = result.success.components;
768
+ validateAuthoringDocument = result.success.validateAuthoringDocument;
731
769
  for (const definition of documents.types) {
732
770
  const issues = validateCollectionBody(options.components, definition.body);
733
771
  if (issues.length) return invalid(`${definition.label}: ${issues.join(" ")}`, "body");
@@ -740,6 +778,7 @@ function resolveDocumentEngineConfiguration(documents, options) {
740
778
  types: resolved
741
779
  };
742
780
  if (components !== void 0) configuration.components = components;
781
+ if (validateAuthoringDocument !== void 0) configuration.validateAuthoringDocument = validateAuthoringDocument;
743
782
  if (mediaBaseUrl !== void 0) configuration.mediaBaseUrl = mediaBaseUrl;
744
783
  return Result.succeed(configuration);
745
784
  }
@@ -750,7 +789,14 @@ function resolveComponents(definitions) {
750
789
  if (components.has(name)) return invalid(`Document component "${component.name}" is defined more than once.`, "components");
751
790
  components.set(name, component);
752
791
  }
753
- return Result.succeed(components);
792
+ try {
793
+ return Result.succeed({
794
+ components,
795
+ validateAuthoringDocument: createAuthoringDocumentValidator(components)
796
+ });
797
+ } catch (cause) {
798
+ return invalid(cause instanceof Error ? cause.message : "The component authoring catalog is invalid.", "components");
799
+ }
754
800
  }
755
801
  function directoryDepth(directory) {
756
802
  return directory === "." ? 0 : directory.split("/").length;
@@ -765,7 +811,6 @@ function invalid(message, field) {
765
811
  //#endregion
766
812
  //#region ../document/src/DocumentEngine.ts
767
813
  const isDocumentParseFailed = Schema.is(DocumentParseFailed);
768
- /** Resolves installation configuration once and rejects an unusable engine before any Source is compiled. */
769
814
  const createDocumentEngine = Effect.fn("DocumentEngine.make")(function* (documents, options) {
770
815
  const configuration = yield* Effect.fromResult(resolveDocumentEngineConfiguration(documents, options));
771
816
  const parseMarkdown = createDocumentParser();
@@ -818,7 +863,10 @@ const createDocumentEngine = Effect.fn("DocumentEngine.make")(function* (documen
818
863
  };
819
864
  });
820
865
  function sameCompilationSource(left, right) {
821
- return left.documentId === right.documentId && left.draft === right.draft && left.markdown === right.markdown && left.sourcePath === right.sourcePath;
866
+ return left.documentId === right.documentId && left.draft === right.draft && left.markdown === right.markdown && left.sourcePath === right.sourcePath && samePublishedAt(left.publishedAt, right.publishedAt);
867
+ }
868
+ function samePublishedAt(left, right) {
869
+ return left === void 0 || right === void 0 ? left === right : DateTime.Equivalence(left, right);
822
870
  }
823
871
  function errorMessage(cause) {
824
872
  return cause instanceof Error && cause.message ? cause.message : "Markdown could not be parsed.";
@@ -826,4 +874,4 @@ function errorMessage(cause) {
826
874
 
827
875
  //#endregion
828
876
  export { normalizeDocumentRelativePath as a, resolveDocumentAddress as c, localizeDocumentPath as i, referenceTarget as n, normalizePublicPath as o, DocumentCompilationFailed as r, parseDocumentAddress as s, createDocumentEngine as t };
829
- //# sourceMappingURL=DocumentEngine-DYObwMDY.js.map
877
+ //# sourceMappingURL=DocumentEngine-J7g-emdf.js.map
@@ -0,0 +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 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,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,WAAW,cAAc;GAErF,OAAO,CAAC,OAAO,YAAY;IAAE;IAAU;GAAO,CAAC;EACjD,CAAC,CACH,CACF;EAEA,OAAO;CACT,CAAC;CAED,MAAM,WAAW,OAAO,GAAG,yBAAyB,CAAC,CAAC,WAAW,QAAmC;EAClG,MAAM,SAAS,OAAO,OAAO,OAAO,QAAQ,MAAM,CAAC;EAEnD,IAAI,OAAO,UAAU,MAAM,GAAG;GAC5B,MAAM,WAAW,OAAO;GAExB,OAAOC,yBAA+B,KAAK;IACzC,OAAO,CAAC,SAAS,OAAO,MAAM,UAAU,MAAM,aAAa,OAAO;IAClE;IACA,QAAQ,SAAS;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"}
@@ -1,4 +1,5 @@
1
- import { ZodObject, ZodType } from "zod";
1
+ import { Schema } from "effect";
2
+ import { StandardJSONSchemaV1, StandardSchemaV1 } from "effect/StandardSchema";
2
3
  //#region src/DocumentModel.d.ts
3
4
  export type CmsFieldInput = 'date' | 'multiselect' | 'number' | 'select' | 'text' | 'textarea' | 'toggle';
4
5
  export interface CmsFieldPresentation {
@@ -16,19 +17,17 @@ export interface CmsCollectionOptions {
16
17
  readonly hierarchy?: boolean;
17
18
  readonly label: string;
18
19
  readonly route: string;
19
- readonly schema: ZodObject;
20
+ readonly schema: CmsCollectionSchema;
20
21
  readonly source?: string;
21
22
  }
22
23
  export interface CmsDocumentModelOptions {
23
24
  readonly collections: Readonly<Record<string, CmsCollectionOptions>>;
24
- readonly locales?: {
25
- readonly defaultLocale: string;
26
- readonly fallbackLocale?: null | string;
27
- readonly locales: ReadonlyArray<string>;
28
- readonly prefixDefaultLocale?: boolean;
29
- };
30
25
  }
31
26
  /** Adds CMS presentation metadata without changing the schema's inferred input or output types. */
32
- export declare function field<const FieldSchema extends ZodType>(schema: FieldSchema, presentation: CmsFieldPresentation): FieldSchema;
27
+ export declare function field<const FieldSchema extends Schema.Top>(schema: FieldSchema, presentation: CmsFieldPresentation): FieldSchema['Rebuild'];
28
+ /** Effect schemas work directly; other libraries supply validation and input JSON Schema. */
29
+ export type CmsCollectionSchema = Schema.ConstraintDecoder<unknown> | (StandardSchemaV1 & StandardJSONSchemaV1);
30
+ /** A calendar date stored as YYYY-MM-DD, without converting document data to a Date. */
31
+ export declare const CalendarDate: Schema.String;
33
32
  //#endregion
34
33
  //# sourceMappingURL=DocumentModel.d.ts.map
@@ -1,15 +1,25 @@
1
1
  import { FIELD_INPUT_METADATA } from "./internal/field-metadata.js";
2
+ import { DateTime, Option, Schema } from "effect";
2
3
 
3
4
  //#region src/DocumentModel.ts
4
5
  /** Adds CMS presentation metadata without changing the schema's inferred input or output types. */
5
6
  function field(schema, presentation) {
6
- return schema.meta({
7
+ return schema.pipe(Schema.annotateEncoded({
7
8
  ...presentation.description === void 0 ? void 0 : { description: presentation.description },
8
9
  ...presentation.input === void 0 ? void 0 : { [FIELD_INPUT_METADATA]: presentation.input },
9
10
  ...presentation.label === void 0 ? void 0 : { title: presentation.label }
10
- });
11
+ }));
11
12
  }
13
+ /** A calendar date stored as YYYY-MM-DD, without converting document data to a Date. */
14
+ const CalendarDate = Schema.String.annotate({ format: "date" }).check(Schema.makeFilter((value) => {
15
+ if (!/^\d{4}-\d{2}-\d{2}$/u.test(value)) return false;
16
+ const parsed = DateTime.make(value);
17
+ return Option.isSome(parsed) && DateTime.formatIsoDate(parsed.value) === value;
18
+ }, {
19
+ message: "Expected a valid date in YYYY-MM-DD format.",
20
+ toJsonSchema: () => ({})
21
+ }));
12
22
 
13
23
  //#endregion
14
- export { field };
24
+ export { CalendarDate, field };
15
25
  //# sourceMappingURL=DocumentModel.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"DocumentModel.js","names":[],"sources":["../../../src/DocumentModel.ts"],"sourcesContent":["import type { ZodObject, ZodType } from 'zod'\nimport { FIELD_INPUT_METADATA } from './internal/field-metadata'\n\nexport type CmsFieldInput = 'date' | 'multiselect' | 'number' | 'select' | 'text' | 'textarea' | 'toggle'\n\nexport interface CmsFieldPresentation {\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: ZodObject\n readonly source?: string\n}\n\nexport interface CmsDocumentModelOptions {\n readonly collections: Readonly<Record<string, CmsCollectionOptions>>\n readonly locales?: {\n readonly defaultLocale: string\n readonly fallbackLocale?: null | string\n readonly locales: ReadonlyArray<string>\n readonly prefixDefaultLocale?: boolean\n }\n}\n\n/** Adds CMS presentation metadata without changing the schema's inferred input or output types. */\nexport function field<const FieldSchema extends ZodType>(\n schema: FieldSchema,\n presentation: CmsFieldPresentation,\n): FieldSchema {\n return schema.meta({\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"],"mappings":";;;;AAoCA,SAAgB,MACd,QACA,cACa;CACb,OAAO,OAAO,KAAK;EACjB,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;AACH"}
1
+ {"version":3,"file":"DocumentModel.js","names":[],"sources":["../../../src/DocumentModel.ts"],"sourcesContent":["import type { StandardJSONSchemaV1, StandardSchemaV1 } from 'effect/StandardSchema'\nimport { DateTime, Option, 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 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>(\n schema: FieldSchema,\n presentation: CmsFieldPresentation,\n): FieldSchema['Rebuild'] {\n return schema.pipe(\n Schema.annotateEncoded({\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\n/** Effect schemas work directly; other libraries supply validation and input JSON Schema. */\nexport type CmsCollectionSchema = Schema.ConstraintDecoder<unknown> | (StandardSchemaV1 & StandardJSONSchemaV1)\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":";;;;;AA+BA,SAAgB,MACd,QACA,cACwB;CACxB,OAAO,OAAO,KACZ,OAAO,gBAAgB;EACrB,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;AACF;;AAMA,MAAa,eAAe,OAAO,OAAO,SAAS,EAAE,QAAQ,OAAO,CAAC,CAAC,CAAC,MACrE,OAAO,YACJ,UAAU;CACT,IAAI,CAAC,uBAAuB,KAAK,KAAK,GAAG,OAAO;CAChD,MAAM,SAAS,SAAS,KAAK,KAAK;CAElC,OAAO,OAAO,OAAO,MAAM,KAAK,SAAS,cAAc,OAAO,KAAK,MAAM;AAC3E,GACA;CAAE,SAAS;CAA+C,qBAAqB,CAAC;AAAG,CACrF,CACF"}
@@ -0,0 +1,74 @@
1
+ import { Schema } from "effect";
2
+ //#region ../protocol/src/internal/documents/scalars.d.ts
3
+ declare const DocumentId: Schema.brand<Schema.String, "DocumentId">;
4
+ type DocumentId = typeof DocumentId.Type;
5
+ //#endregion
6
+ //#region ../protocol/src/Forms.d.ts
7
+ type FormFieldType = 'text' | 'email' | 'textarea' | 'number' | 'checkbox' | 'select';
8
+ declare const FormFieldType: Schema.Codec<FormFieldType>;
9
+ type FormRule = 'required' | 'minLength' | 'maxLength' | 'min' | 'max';
10
+ declare const FormRule: Schema.Codec<FormRule>;
11
+ interface FormCapabilities {
12
+ readonly label: string;
13
+ readonly fieldTypes: ReadonlyArray<FormFieldType>;
14
+ readonly rules: ReadonlyArray<FormRule>;
15
+ }
16
+ declare const FormCapabilities: Schema.Codec<FormCapabilities>;
17
+ interface FormOption {
18
+ readonly id: string;
19
+ readonly label: string;
20
+ }
21
+ declare const FormOption: Schema.Codec<FormOption>;
22
+ interface FormField {
23
+ readonly id: string;
24
+ readonly label: string;
25
+ readonly type: FormFieldType;
26
+ readonly help?: string;
27
+ readonly required?: boolean;
28
+ readonly minLength?: number;
29
+ readonly maxLength?: number;
30
+ readonly min?: number;
31
+ readonly max?: number;
32
+ readonly options?: ReadonlyArray<FormOption>;
33
+ }
34
+ declare const FormField: Schema.Codec<FormField>;
35
+ interface FormStep {
36
+ readonly id: string;
37
+ readonly title: string;
38
+ readonly fields: ReadonlyArray<FormField>;
39
+ }
40
+ declare const FormStep: Schema.Codec<FormStep>;
41
+ interface FormReference {
42
+ readonly documentId: DocumentId;
43
+ readonly nodePath: ReadonlyArray<number>;
44
+ readonly revision: string;
45
+ }
46
+ declare const FormReference: Schema.Codec<FormReference, {
47
+ readonly documentId: string;
48
+ readonly nodePath: ReadonlyArray<number>;
49
+ readonly revision: string;
50
+ }>;
51
+ interface FormDefinition extends FormReference {
52
+ readonly name: string;
53
+ readonly steps: ReadonlyArray<FormStep>;
54
+ readonly preview: boolean;
55
+ }
56
+ type FormValues = Readonly<Record<string, string | number | boolean | null>>;
57
+ declare const FormValues: Schema.Codec<FormValues>;
58
+ interface FormSubmission extends FormReference {
59
+ readonly values: FormValues;
60
+ }
61
+ declare const FormSubmission: Schema.Codec<FormSubmission, {
62
+ readonly documentId: string;
63
+ readonly nodePath: ReadonlyArray<number>;
64
+ readonly revision: string;
65
+ readonly values: FormValues;
66
+ }>;
67
+ interface FormResult {
68
+ readonly status: 'accepted' | 'invalid' | 'stale' | 'unavailable' | 'failed';
69
+ readonly errors: Readonly<Record<string, string>>;
70
+ }
71
+ declare const FormResult: Schema.Codec<FormResult>;
72
+ //#endregion
73
+ export { FormStep as a, FormResult as i, FormDefinition as n, FormSubmission as o, FormField as r, FormValues as s, FormCapabilities as t };
74
+ //# sourceMappingURL=Forms-BsJMev5_.d.ts.map
@@ -0,0 +1,79 @@
1
+ import { r as DocumentId } from "./scalars-B2lgGUnj.js";
2
+ import { Schema } from "effect";
3
+
4
+ //#region ../protocol/src/Forms.ts
5
+ const FORM_SUBMISSION_MAX_BYTES = 131072;
6
+ /** Budget for the JSON-escaped revision, leaving space for the envelope and answers. */
7
+ const FORM_REVISION_MAX_BYTES = 6e4;
8
+ const FormFieldType = Schema.Literals([
9
+ "text",
10
+ "email",
11
+ "textarea",
12
+ "number",
13
+ "checkbox",
14
+ "select"
15
+ ]);
16
+ const FormRule = Schema.Literals([
17
+ "required",
18
+ "minLength",
19
+ "maxLength",
20
+ "min",
21
+ "max"
22
+ ]);
23
+ const FormCapabilities = Schema.Struct({
24
+ label: Schema.NonEmptyString,
25
+ fieldTypes: Schema.Array(FormFieldType).check(Schema.isMinLength(1)),
26
+ rules: Schema.Array(FormRule)
27
+ });
28
+ const FormOption = Schema.Struct({
29
+ id: Schema.NonEmptyString,
30
+ label: Schema.NonEmptyString
31
+ });
32
+ const FormField = Schema.Struct({
33
+ id: Schema.NonEmptyString,
34
+ label: Schema.NonEmptyString,
35
+ type: FormFieldType,
36
+ help: Schema.optionalKey(Schema.String),
37
+ required: Schema.optionalKey(Schema.Boolean),
38
+ minLength: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
39
+ maxLength: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
40
+ min: Schema.optionalKey(Schema.Finite),
41
+ max: Schema.optionalKey(Schema.Finite),
42
+ options: Schema.optionalKey(Schema.Array(FormOption))
43
+ });
44
+ const FormStep = Schema.Struct({
45
+ id: Schema.NonEmptyString,
46
+ title: Schema.NonEmptyString,
47
+ fields: Schema.Array(FormField).check(Schema.isMinLength(1), Schema.isMaxLength(100))
48
+ });
49
+ const FormSteps = Schema.Array(FormStep).check(Schema.isMinLength(1), Schema.isMaxLength(20));
50
+ const referenceFields = {
51
+ documentId: DocumentId,
52
+ nodePath: Schema.Array(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))).check(Schema.isMinLength(1), Schema.isMaxLength(64)),
53
+ revision: Schema.String.check(Schema.isMaxLength(FORM_REVISION_MAX_BYTES))
54
+ };
55
+ const FormReference = Schema.Struct(referenceFields);
56
+ const FormValues = Schema.Record(Schema.String, Schema.Union([
57
+ Schema.String,
58
+ Schema.Finite,
59
+ Schema.Boolean,
60
+ Schema.Null
61
+ ]));
62
+ const FormSubmission = Schema.Struct({
63
+ ...referenceFields,
64
+ values: FormValues
65
+ });
66
+ const FormResult = Schema.Struct({
67
+ status: Schema.Literals([
68
+ "accepted",
69
+ "invalid",
70
+ "stale",
71
+ "unavailable",
72
+ "failed"
73
+ ]),
74
+ errors: Schema.Record(Schema.String, Schema.String)
75
+ });
76
+
77
+ //#endregion
78
+ export { FormSteps as a, FormResult as i, FORM_SUBMISSION_MAX_BYTES as n, FormSubmission as o, FormCapabilities as r, FORM_REVISION_MAX_BYTES as t };
79
+ //# sourceMappingURL=Forms-CfcI3tPU.js.map