@xleddyl/nuxt-cms 0.1.41 → 0.1.43

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.
@@ -0,0 +1,23 @@
1
+ import type { AsyncData } from 'nuxt/app';
2
+ import type { CmsCollectionName, CmsCollectionTypes, CmsPagePath, CmsPageTypes, CmsSingleName, CmsSingleTypes } from '#cms-types';
3
+ import type { CmsAsyncDataOptions } from './cms-query-disabled.js';
4
+ export interface CmsSortInput<Entry> {
5
+ field: Extract<keyof Entry, string>;
6
+ direction?: 'asc' | 'desc';
7
+ }
8
+ export interface CmsSingleOptions<ResT, DefaultT> extends CmsAsyncDataOptions<ResT, DefaultT> {
9
+ locale?: string;
10
+ }
11
+ export interface CmsPageOptions<ResT, DefaultT> extends CmsAsyncDataOptions<ResT, DefaultT> {
12
+ locale?: string;
13
+ }
14
+ export interface CmsCollectionOptions<ResT, DefaultT, Entry> extends CmsAsyncDataOptions<ResT, DefaultT> {
15
+ locale?: string;
16
+ filters?: Record<string, unknown>;
17
+ sort?: CmsSortInput<Entry>[];
18
+ limit?: number;
19
+ offset?: number;
20
+ }
21
+ export declare function useCmsSingle<K extends CmsSingleName, DefaultT = null>(name: K, options?: CmsSingleOptions<CmsSingleTypes[K] | null, DefaultT>): AsyncData<CmsSingleTypes[K] | DefaultT | null, Error | undefined>;
22
+ export declare function useCmsCollection<K extends CmsCollectionName, DefaultT = CmsCollectionTypes[K][]>(name: K, options?: CmsCollectionOptions<CmsCollectionTypes[K][], DefaultT, CmsCollectionTypes[K]>): AsyncData<CmsCollectionTypes[K][] | DefaultT, Error | undefined>;
23
+ export declare function useCmsPage<P extends CmsPagePath, DefaultT = null>(path: P, options?: CmsPageOptions<CmsPageTypes[P] | null, DefaultT>): AsyncData<CmsPageTypes[P] | DefaultT | null, Error | undefined>;
@@ -0,0 +1,23 @@
1
+ import { useAsyncData } from "#imports";
2
+ export function useCmsSingle(name, options = {}) {
3
+ const { locale, key, default: fallback } = options;
4
+ return useAsyncData(
5
+ key ?? `cms-single:${String(name)}:${locale ?? ""}`,
6
+ async () => fallback ? fallback() : null
7
+ );
8
+ }
9
+ export function useCmsCollection(name, options = {}) {
10
+ const { locale, filters, sort, limit, offset, key, default: fallback } = options;
11
+ const variables = { locale, filters, sort, limit, offset };
12
+ return useAsyncData(
13
+ key ?? `cms-collection:${String(name)}:${JSON.stringify(variables)}`,
14
+ async () => fallback ? fallback() : []
15
+ );
16
+ }
17
+ export function useCmsPage(path, options = {}) {
18
+ const { locale, key, default: fallback } = options;
19
+ return useAsyncData(
20
+ `cms-page:${String(path)}:${locale ?? ""}`,
21
+ async () => fallback ? fallback() : null
22
+ );
23
+ }
@@ -0,0 +1,23 @@
1
+ import type { AsyncData } from 'nuxt/app';
2
+ import type { CmsCollectionName, CmsCollectionTypes, CmsPagePath, CmsPageTypes, CmsSingleName, CmsSingleTypes } from '#cms-types';
3
+ import type { CmsAsyncDataOptions } from './cms-query.js';
4
+ export interface CmsSortInput<Entry> {
5
+ field: Extract<keyof Entry, string>;
6
+ direction?: 'asc' | 'desc';
7
+ }
8
+ export interface CmsSingleOptions<ResT, DefaultT> extends CmsAsyncDataOptions<ResT, DefaultT> {
9
+ locale?: string;
10
+ }
11
+ export interface CmsPageOptions<ResT, DefaultT> extends CmsAsyncDataOptions<ResT, DefaultT> {
12
+ locale?: string;
13
+ }
14
+ export interface CmsCollectionOptions<ResT, DefaultT, Entry> extends CmsAsyncDataOptions<ResT, DefaultT> {
15
+ locale?: string;
16
+ filters?: Record<string, unknown>;
17
+ sort?: CmsSortInput<Entry>[];
18
+ limit?: number;
19
+ offset?: number;
20
+ }
21
+ export declare function useCmsSingle<K extends CmsSingleName, DefaultT = null>(name: K, options?: CmsSingleOptions<CmsSingleTypes[K] | null, DefaultT>): AsyncData<CmsSingleTypes[K] | DefaultT | null, Error | undefined>;
22
+ export declare function useCmsCollection<K extends CmsCollectionName, DefaultT = CmsCollectionTypes[K][]>(name: K, options?: CmsCollectionOptions<CmsCollectionTypes[K][], DefaultT, CmsCollectionTypes[K]>): AsyncData<CmsCollectionTypes[K][] | DefaultT, Error | undefined>;
23
+ export declare function useCmsPage<P extends CmsPagePath, DefaultT = null>(path: P, options?: CmsPageOptions<CmsPageTypes[P] | null, DefaultT>): AsyncData<CmsPageTypes[P] | DefaultT | null, Error | undefined>;
@@ -0,0 +1,67 @@
1
+ import { cmsCollectionQueries, cmsPageQueries, cmsSingleQueries } from "#cms-queries";
2
+ import { useAsyncData } from "#imports";
3
+ import { $cmsQuery } from "./cms-query.js";
4
+ function unknownEntry(name) {
5
+ throw new Error(`[nuxt-cms] no generated query for "${name}"; check cms.config.ts`);
6
+ }
7
+ export function useCmsSingle(name, options = {}) {
8
+ const { locale, key, default: fallback, ...asyncDataOptions } = options;
9
+ const entryName = String(name);
10
+ const query = cmsSingleQueries[entryName];
11
+ return useAsyncData(
12
+ key ?? `cms-single:${entryName}:${locale ?? ""}`,
13
+ async () => {
14
+ if (!query) unknownEntry(entryName);
15
+ const result = await $cmsQuery(query, { locale });
16
+ return result?.[entryName] ?? null;
17
+ },
18
+ {
19
+ default: fallback ?? (() => null),
20
+ ...asyncDataOptions
21
+ }
22
+ );
23
+ }
24
+ export function useCmsCollection(name, options = {}) {
25
+ const {
26
+ locale,
27
+ filters,
28
+ sort,
29
+ limit,
30
+ offset,
31
+ key,
32
+ default: fallback,
33
+ ...asyncDataOptions
34
+ } = options;
35
+ const entryName = String(name);
36
+ const query = cmsCollectionQueries[entryName];
37
+ const variables = { locale, filters, sort, limit, offset };
38
+ return useAsyncData(
39
+ key ?? `cms-collection:${entryName}:${JSON.stringify(variables)}`,
40
+ async () => {
41
+ if (!query) unknownEntry(entryName);
42
+ const result = await $cmsQuery(query, variables);
43
+ return result?.[entryName] ?? [];
44
+ },
45
+ {
46
+ default: fallback ?? (() => []),
47
+ ...asyncDataOptions
48
+ }
49
+ );
50
+ }
51
+ export function useCmsPage(path, options = {}) {
52
+ const { locale, key, default: fallback, ...asyncDataOptions } = options;
53
+ const pagePath = String(path);
54
+ const query = cmsPageQueries[pagePath];
55
+ return useAsyncData(
56
+ key ?? `cms-page:${pagePath}:${locale ?? ""}`,
57
+ async () => {
58
+ if (!query) unknownEntry(pagePath);
59
+ const result = await $cmsQuery(query, { path: pagePath, locale });
60
+ return result?.page ?? null;
61
+ },
62
+ {
63
+ default: fallback ?? (() => null),
64
+ ...asyncDataOptions
65
+ }
66
+ );
67
+ }
@@ -71,6 +71,11 @@ const groups = computed(
71
71
  icon: "document-text",
72
72
  links: links.filter((l) => l.kind === "single")
73
73
  },
74
+ {
75
+ title: "Pages",
76
+ icon: "window",
77
+ links: links.filter((l) => l.kind === "page")
78
+ },
74
79
  {
75
80
  title: "Library",
76
81
  icon: "photo",
@@ -30,6 +30,49 @@
30
30
  />
31
31
  </div>
32
32
 
33
+ <template v-else-if="config.kind === 'page'">
34
+ <div class="cms-toolbar">
35
+ <CmsInput
36
+ v-if="total || searchTerm"
37
+ v-model="search"
38
+ icon="magnifying-glass"
39
+ placeholder="Search…"
40
+ class="flex-1"
41
+ />
42
+ </div>
43
+
44
+ <div v-if="rows.length" class="cms-card divide-y divide-(--cms-line)">
45
+ <NuxtLink
46
+ v-for="row in rows"
47
+ :key="String(row.id)"
48
+ :to="`/cms/${name}/${row.id}`"
49
+ class="flex items-center gap-4 px-4 py-3 transition-colors hover:bg-(--ui-bg-elevated)"
50
+ >
51
+ <div class="min-w-0 flex-1">
52
+ <div class="truncate font-medium text-(--ui-text-highlighted)">
53
+ {{ row.label }}
54
+ </div>
55
+ <div class="cms-label truncate">{{ row.path }}</div>
56
+ </div>
57
+ <span class="cms-label shrink-0">{{ row.updatedAt ? "edited" : "empty" }}</span>
58
+ <CmsIcon name="chevron-right" class="size-4 shrink-0 text-(--ui-text-dimmed)" />
59
+ </NuxtLink>
60
+ </div>
61
+
62
+ <CmsSpinner v-else-if="status === 'pending'" />
63
+
64
+ <CmsEmptyState v-else-if="searchTerm" icon="magnifying-glass" title="No matching pages" />
65
+
66
+ <CmsEmptyState
67
+ v-else
68
+ icon="document-text"
69
+ title="No pages yet"
70
+ body="Pages come from the routes of the app."
71
+ />
72
+
73
+ <CmsPagination v-model:page="page" :total="total" :items-per-page="PAGE_SIZE" />
74
+ </template>
75
+
33
76
  <template v-else>
34
77
  <div class="cms-toolbar">
35
78
  <CmsInput
@@ -168,7 +211,7 @@ const listQuery = computed(() => ({
168
211
  ...sort.value ? { sort: sort.value.key, order: sort.value.order } : {}
169
212
  }));
170
213
  const { data, refresh, error, status } = await useFetch(endpoint, {
171
- query: config.kind === "collection" ? listQuery : void 0
214
+ query: config.kind === "single" ? void 0 : listQuery
172
215
  });
173
216
  function isList(value) {
174
217
  return !!value && Array.isArray(value.items);
@@ -1,6 +1,6 @@
1
1
  <template>
2
2
  <div class="cms-page">
3
- <CmsPageHeader :title="isNew ? 'New entry' : 'Edit entry'">
3
+ <CmsPageHeader :title="headerTitle">
4
4
  <template v-if="drafts" #badge>
5
5
  <CmsStatusBadge :published="published" />
6
6
  </template>
@@ -21,7 +21,7 @@
21
21
  <div class="cms-card cms-panel">
22
22
  <CmsEntryForm
23
23
  v-model="formState"
24
- :fields="config.fields"
24
+ :fields="fields"
25
25
  :drafts="drafts"
26
26
  :form-id="FORM_ID"
27
27
  :loading="saving"
@@ -33,6 +33,7 @@
33
33
  </template>
34
34
 
35
35
  <script setup>
36
+ import { pageFields, pageRouteOf } from "#nuxt-cms";
36
37
  import {
37
38
  computed,
38
39
  createError,
@@ -61,13 +62,20 @@ const route = useRoute();
61
62
  const toast = useCmsToast();
62
63
  const name = route.params.collection;
63
64
  const config = cmsConfig[name];
64
- if (!config || config.kind !== "collection") {
65
+ if (!config || config.kind !== "collection" && config.kind !== "page") {
65
66
  throw createError({ statusCode: 404, statusMessage: "Unknown collection", fatal: true });
66
67
  }
67
68
  const id = route.params.id;
68
- const isNew = id === void 0;
69
- const drafts = !!config.drafts;
70
- const fieldKeys = Object.keys(config.fields);
69
+ const isPage = config.kind === "page";
70
+ const pageRoute = isPage && id ? pageRouteOf(config, id) : void 0;
71
+ if (isPage && !pageRoute) {
72
+ throw createError({ statusCode: 404, statusMessage: "Unknown page", fatal: true });
73
+ }
74
+ const isNew = !isPage && id === void 0;
75
+ const drafts = !isPage && !!config.drafts;
76
+ const fields = pageRoute ? pageFields(config, pageRoute.path) : config.fields;
77
+ const headerTitle = pageRoute ? pageRoute.label : isNew ? "New entry" : "Edit entry";
78
+ const fieldKeys = Object.keys(fields);
71
79
  const formKeys = drafts ? [...fieldKeys, "status"] : fieldKeys;
72
80
  const endpoint = `/api/cms/admin/${name}`;
73
81
  function emptyState() {
@@ -2,6 +2,7 @@ import { asc, count, desc, sql } from "drizzle-orm";
2
2
  import { defineEventHandler, getValidatedQuery } from "h3";
3
3
  import { z } from "zod";
4
4
  import { useDb } from "#cms-db";
5
+ import { pageRoutes } from "../../shared/index.js";
5
6
  import { decodeRows, getRegistryEntry, idColumn, tableColumns } from "../utils/registry.js";
6
7
  import { attachManyToMany, relationTitles } from "../utils/relations.js";
7
8
  import { requireAdmin } from "../utils/require-admin.js";
@@ -29,6 +30,24 @@ export default defineEventHandler(async (event) => {
29
30
  event,
30
31
  querySchema.parse
31
32
  );
33
+ if (entry.kind === "page") {
34
+ const rows = await db.select().from(table);
35
+ decodeRows(entry, rows);
36
+ const saved = new Map(rows.map((row) => [row.id, row]));
37
+ const items2 = pageRoutes(entry).map((route) => {
38
+ const row = saved.get(route.key) ?? {};
39
+ return { ...row, id: route.key, path: route.path, label: route.label };
40
+ });
41
+ const term = search?.toLowerCase();
42
+ const matching = term ? items2.filter(
43
+ (item) => item.path.toLowerCase().includes(term) || item.label.toLowerCase().includes(term)
44
+ ) : items2;
45
+ return {
46
+ items: matching.slice(offset, offset + limit),
47
+ total: matching.length,
48
+ relations: {}
49
+ };
50
+ }
32
51
  const columns = tableColumns(table);
33
52
  const titleColumn = entry.titleField && Object.hasOwn(columns, entry.titleField) ? columns[entry.titleField] : void 0;
34
53
  let where;
@@ -8,7 +8,10 @@ export default defineEventHandler(async (event) => {
8
8
  await requireAdmin(event);
9
9
  const { entry, table } = getRegistryEntry(event);
10
10
  if (entry.kind !== "collection") {
11
- throw createError({ statusCode: 405, statusMessage: "Single objects cannot be deleted" });
11
+ throw createError({
12
+ statusCode: 405,
13
+ statusMessage: "Only collection entries can be deleted"
14
+ });
12
15
  }
13
16
  const id = parseId(event);
14
17
  return mapConstraintErrors(async () => {
@@ -1,18 +1,29 @@
1
1
  import { eq } from "drizzle-orm";
2
2
  import { createError, defineEventHandler } from "h3";
3
3
  import { useDb } from "#cms-db";
4
- import { decodeRows, getRegistryEntry, idColumn, parseId } from "../utils/registry.js";
4
+ import {
5
+ decodeRows,
6
+ getRegistryEntry,
7
+ idColumn,
8
+ parseId,
9
+ requirePageRoute
10
+ } from "../utils/registry.js";
5
11
  import { attachManyToMany } from "../utils/relations.js";
6
12
  import { requireAdmin } from "../utils/require-admin.js";
7
13
  export default defineEventHandler(async (event) => {
8
14
  await requireAdmin(event);
9
15
  const { name, entry, table } = getRegistryEntry(event);
10
- if (entry.kind !== "collection") {
16
+ if (entry.kind === "single") {
11
17
  throw createError({ statusCode: 404, statusMessage: "Single objects have no items" });
12
18
  }
13
19
  const id = parseId(event);
14
20
  const db = useDb();
15
21
  const rows = await db.select().from(table).where(eq(idColumn(table), id)).limit(1);
22
+ if (entry.kind === "page") {
23
+ const route = requirePageRoute(entry, id);
24
+ if (!rows[0]) return { id: route.key, path: route.path };
25
+ return decodeRows(entry, [rows[0]])[0];
26
+ }
16
27
  if (!rows[0]) throw createError({ statusCode: 404, statusMessage: "Row not found" });
17
28
  const [attached] = await attachManyToMany(db, name, entry, [rows[0]]);
18
29
  return decodeRows(entry, [attached])[0];
@@ -8,6 +8,7 @@ import {
8
8
  getRegistryEntry,
9
9
  idColumn,
10
10
  parseId,
11
+ requirePageRoute,
11
12
  withUpdatedAt
12
13
  } from "../utils/registry.js";
13
14
  import {
@@ -21,13 +22,25 @@ import { mapConstraintErrors } from "../utils/db-errors.js";
21
22
  export default defineEventHandler(async (event) => {
22
23
  await requireAdmin(event);
23
24
  const { name, entry, table } = getRegistryEntry(event);
24
- if (entry.kind !== "collection") {
25
+ if (entry.kind === "single") {
25
26
  throw createError({
26
27
  statusCode: 405,
27
28
  statusMessage: "Single objects are updated with PUT without id"
28
29
  });
29
30
  }
30
31
  const id = parseId(event);
32
+ if (entry.kind === "page") {
33
+ const route = requirePageRoute(entry, id);
34
+ const body2 = await readValidatedBody(event, buildValidator(entry, route.path).parse);
35
+ const values2 = encodeColumnValues(entry, body2);
36
+ const set2 = withUpdatedAt(table, values2);
37
+ return mapConstraintErrors(
38
+ () => withTransaction(async (db) => {
39
+ const [row] = await db.insert(table).values({ id: route.key, path: route.path, ...set2 }).onConflictDoUpdate({ target: idColumn(table), set: set2 }).returning();
40
+ return decodeRows(entry, [row])[0];
41
+ })
42
+ );
43
+ }
31
44
  const body = await readValidatedBody(event, buildValidator(entry).parse);
32
45
  const { values, lists } = splitRelationValues(
33
46
  entry,
@@ -21,6 +21,7 @@ import * as cmsTables from "#cms-tables";
21
21
  import { useRuntimeConfig } from "#imports";
22
22
  import {
23
23
  decodeTranslatableMedia,
24
+ entryFieldsFor,
24
25
  hasTranslatableBlockFields,
25
26
  isPrivateField,
26
27
  isTranslatableMediaField,
@@ -102,8 +103,9 @@ function resolveLocaleArg(locale) {
102
103
  function localizeRow(entry, row, locale) {
103
104
  const { defaultLocale } = getContentI18n();
104
105
  const result = { ...row, [LOCALE]: locale };
106
+ const fields = entryFieldsFor(entry);
105
107
  for (const key of translatableFieldKeys(entry)) {
106
- if (isTranslatableMediaField(entry.fields[key])) {
108
+ if (isTranslatableMediaField(fields[key])) {
107
109
  const media = decodeTranslatableMedia(row[key], defaultLocale);
108
110
  result[key] = pickTranslatedMedia(media, locale, defaultLocale);
109
111
  continue;
@@ -111,7 +113,7 @@ function localizeRow(entry, row, locale) {
111
113
  const value = row[key];
112
114
  result[key] = value?.[locale] ?? value?.[defaultLocale] ?? null;
113
115
  }
114
- for (const [key, field] of Object.entries(entry.fields)) {
116
+ for (const [key, field] of Object.entries(fields)) {
115
117
  if (isPrivateField(field) || !hasTranslatableBlockFields(field)) continue;
116
118
  result[key] = localizeBlocks(field, result[key], locale, defaultLocale);
117
119
  }
@@ -268,7 +270,7 @@ function mediaObject(key, row) {
268
270
  }
269
271
  function entryResolvers(config, name, entry) {
270
272
  const resolvers = {};
271
- for (const [key, field] of Object.entries(entry.fields)) {
273
+ for (const [key, field] of Object.entries(entryFieldsFor(entry))) {
272
274
  if (isPrivateField(field)) continue;
273
275
  if (field.type === "relation" && field.cardinality === "many-to-many") {
274
276
  resolvers[key] = async (parent, _args, ctx) => {
@@ -313,10 +315,25 @@ export function buildCmsSchema() {
313
315
  const gqlType = typeName(name);
314
316
  const fieldLevel = entryResolvers(config, name, entry);
315
317
  if (Object.keys(fieldLevel).length) typeResolvers[gqlType] = fieldLevel;
316
- for (const [key, field] of Object.entries(entry.fields)) {
318
+ for (const [key, field] of Object.entries(entryFieldsFor(entry))) {
317
319
  if (field.type === "blocks" && !isPrivateField(field))
318
320
  Object.assign(typeResolvers, blockResolvers(name, key, field));
319
321
  }
322
+ if (entry.kind === "page") {
323
+ queryResolvers[name] = async (_, args) => {
324
+ const locale = resolveLocaleArg(args.locale);
325
+ const table = tableFor(name);
326
+ const rows = await useDb().select().from(table).orderBy(asc(tableColumns(table).path));
327
+ return rows.map((row) => localizeRow(entry, row, locale));
328
+ };
329
+ queryResolvers[`${name}ByPath`] = async (_, args) => {
330
+ const locale = resolveLocaleArg(args.locale);
331
+ const table = tableFor(name);
332
+ const [row] = await useDb().select().from(table).where(eq(tableColumns(table).path, args.path)).limit(1);
333
+ return row ? localizeRow(entry, row, locale) : null;
334
+ };
335
+ continue;
336
+ }
320
337
  if (entry.kind === "single") {
321
338
  queryResolvers[name] = async (_, args) => {
322
339
  const locale = resolveLocaleArg(args.locale);
@@ -1,7 +1,7 @@
1
1
  import type { AnySQLiteColumn, SQLiteTable } from 'drizzle-orm/sqlite-core';
2
2
  import type { H3Event } from 'h3';
3
3
  import { z } from 'zod';
4
- import type { CmsEntry, CmsI18n } from '../../shared/index.js';
4
+ import type { CmsEntry, CmsI18n, CmsPageRoute } from '../../shared/index.js';
5
5
  export declare function getContentI18n(): CmsI18n;
6
6
  export declare function resolveTable(name: string): SQLiteTable | undefined;
7
7
  export declare function tableColumns(table: SQLiteTable): Record<string, AnySQLiteColumn>;
@@ -14,9 +14,10 @@ export declare function getRegistryEntry(event: H3Event): {
14
14
  entry: CmsEntry;
15
15
  table: SQLiteTable;
16
16
  };
17
- export declare function buildValidator(entry: CmsEntry): z.ZodObject<{
17
+ export declare function buildValidator(entry: CmsEntry, path?: string): z.ZodObject<{
18
18
  [x: string]: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
19
19
  }, z.core.$strip>;
20
+ export declare function requirePageRoute(entry: CmsEntry, key: string): CmsPageRoute;
20
21
  export declare function encodeColumnValues(entry: CmsEntry, values: Record<string, unknown>): Record<string, unknown>;
21
22
  export declare function decodeRows<T extends Record<string, unknown>>(entry: CmsEntry, rows: T[]): T[];
22
23
  export declare function parseId(event: H3Event): string;
@@ -3,7 +3,12 @@ import { z } from "zod";
3
3
  import cmsConfig from "#cms-config";
4
4
  import * as cmsTables from "#cms-tables";
5
5
  import { useRuntimeConfig } from "#imports";
6
- import { decodeEntryTranslatableMedia, encodeEntryTranslatableMedia } from "../../shared/index.js";
6
+ import {
7
+ decodeEntryTranslatableMedia,
8
+ encodeEntryTranslatableMedia,
9
+ pageFields,
10
+ pageRouteOf
11
+ } from "../../shared/index.js";
7
12
  import { buildEntrySchema } from "../../shared/validation.js";
8
13
  let contentI18n;
9
14
  export function getContentI18n() {
@@ -40,8 +45,14 @@ export function getRegistryEntry(event) {
40
45
  }
41
46
  return { name, entry: config[name], table };
42
47
  }
43
- export function buildValidator(entry) {
44
- return buildEntrySchema(entry, getContentI18n());
48
+ export function buildValidator(entry, path) {
49
+ const fields = path ? pageFields(entry, path) : entry.fields;
50
+ return buildEntrySchema({ ...entry, fields }, getContentI18n());
51
+ }
52
+ export function requirePageRoute(entry, key) {
53
+ const route = pageRouteOf(entry, key);
54
+ if (!route) throw createError({ statusCode: 404, statusMessage: `Unknown page: ${key}` });
55
+ return route;
45
56
  }
46
57
  export function encodeColumnValues(entry, values) {
47
58
  return encodeEntryTranslatableMedia(entry, values);
@@ -3,9 +3,10 @@ import { createError } from "h3";
3
3
  import cmsConfig from "#cms-config";
4
4
  import { useDb } from "#cms-db";
5
5
  import * as cmsTables from "#cms-tables";
6
+ import { entryFieldsFor } from "../../shared/index.js";
6
7
  import { resolveTable, tableColumns } from "./registry.js";
7
8
  function manyToManyKeys(entry) {
8
- return Object.entries(entry.fields).filter(([, field]) => field.type === "relation" && field.cardinality === "many-to-many").map(([key]) => key);
9
+ return Object.entries(entryFieldsFor(entry)).filter(([, field]) => field.type === "relation" && field.cardinality === "many-to-many").map(([key]) => key);
9
10
  }
10
11
  function joinTable(name, key) {
11
12
  const table = cmsTables[`${name}_${key}`];
@@ -34,7 +35,7 @@ export async function assertRelationTargets(entry, lists) {
34
35
  const db = useDb();
35
36
  for (const [key, ids] of Object.entries(lists)) {
36
37
  if (!ids.length) continue;
37
- const field = entry.fields[key];
38
+ const field = entryFieldsFor(entry)[key];
38
39
  const target = resolveTable(field.to);
39
40
  if (!target) continue;
40
41
  const idCol = tableColumns(target).id;
@@ -61,7 +62,7 @@ export async function saveManyToMany(db, name, sourceId, lists) {
61
62
  export async function relationTitles(db, entry, rows) {
62
63
  const config = cmsConfig;
63
64
  const titles = {};
64
- for (const [key, field] of Object.entries(entry.fields)) {
65
+ for (const [key, field] of Object.entries(entryFieldsFor(entry))) {
65
66
  if (field.type !== "relation" || !field.to) continue;
66
67
  const targetEntry = config[field.to];
67
68
  const target = resolveTable(field.to);
@@ -1,12 +1,17 @@
1
1
  import {
2
+ PAGE_PATH_FIELD,
2
3
  blockTypeName,
3
4
  blocksFieldTypeName,
4
5
  isPrivateField,
5
6
  isRequiredField,
6
7
  isTranslatableField,
8
+ pageAllFields,
7
9
  typeName
8
10
  } from "./index.js";
9
11
  export { blockTypeName, blocksFieldTypeName, typeName };
12
+ function entryFields(entry) {
13
+ return entry.kind === "page" ? pageAllFields(entry) : entry.fields;
14
+ }
10
15
  function scalarFor(field) {
11
16
  switch (field.type) {
12
17
  case "number":
@@ -62,7 +67,8 @@ function fieldSdl(config, entryName, key, field) {
62
67
  }
63
68
  function entrySdl(config, name, entry) {
64
69
  const lines = [" id: ID!"];
65
- for (const [key, field] of Object.entries(entry.fields)) {
70
+ if (entry.kind === "page") lines.push(` ${PAGE_PATH_FIELD}: String!`);
71
+ for (const [key, field] of Object.entries(entryFields(entry))) {
66
72
  if (isPrivateField(field)) continue;
67
73
  lines.push(fieldSdl(config, name, key, field));
68
74
  }
@@ -146,7 +152,7 @@ export function renderGraphqlSdl(config) {
146
152
  for (const [name, entry] of Object.entries(config)) {
147
153
  const gqlType = typeName(name);
148
154
  types.push(entrySdl(config, name, entry));
149
- for (const [key, field] of Object.entries(entry.fields)) {
155
+ for (const [key, field] of Object.entries(entryFields(entry))) {
150
156
  if (field.type === "blocks" && !isPrivateField(field))
151
157
  types.push(...blocksSdl(name, key, field));
152
158
  }
@@ -154,6 +160,11 @@ export function renderGraphqlSdl(config) {
154
160
  queryLines.push(` ${name}(locale: String): ${gqlType}`);
155
161
  continue;
156
162
  }
163
+ if (entry.kind === "page") {
164
+ queryLines.push(` ${name}(locale: String): [${gqlType}!]!`);
165
+ queryLines.push(` ${name}ByPath(path: String!, locale: String): ${gqlType}`);
166
+ continue;
167
+ }
157
168
  types.push(filterSdl(name, entry));
158
169
  queryLines.push(
159
170
  ` ${name}(filters: ${gqlType}Filters, sort: [${gqlType}Sort!], limit: Int, offset: Int, locale: String): [${gqlType}!]!`
@@ -79,25 +79,51 @@ export declare function decodeTranslatableValue(value: unknown, defaultLocale: s
79
79
  export declare const decodeTranslatableMedia: typeof decodeTranslatableValue;
80
80
  export declare function encodeTranslatableMedia(value: unknown): string | null;
81
81
  export declare function pickTranslatedMedia(values: Record<string, string> | null | undefined, locale: string, defaultLocale: string): string | null;
82
- export declare function translatableMediaKeys(entry: Pick<CmsEntry, 'fields'>): string[];
83
- export declare function encodeEntryTranslatableMedia(entry: Pick<CmsEntry, 'fields'>, values: Record<string, unknown>): Record<string, unknown>;
84
- export declare function decodeEntryTranslatableMedia<T extends Record<string, unknown>>(entry: Pick<CmsEntry, 'fields'>, rows: T[], defaultLocale: string): T[];
82
+ export declare function translatableMediaKeys(entry: EntryLike): string[];
83
+ export declare function encodeEntryTranslatableMedia(entry: EntryLike, values: Record<string, unknown>): Record<string, unknown>;
84
+ export declare function decodeEntryTranslatableMedia<T extends Record<string, unknown>>(entry: EntryLike, rows: T[], defaultLocale: string): T[];
85
85
  export declare function isMultiSelect(field: FieldConfig): boolean;
86
- export declare function translatableFieldKeys(entry: CmsEntry): string[];
86
+ export declare function translatableFieldKeys(entry: EntryLike): string[];
87
87
  export declare function translatableBlockFieldKeys(block: BlockConfig): string[];
88
88
  export declare function hasTranslatableBlockFields(field: FieldConfig): boolean;
89
89
  export declare function localizeBlock(field: FieldConfig, item: unknown, locale: string, defaultLocale: string): unknown;
90
90
  export declare function localizeBlocks(field: FieldConfig, value: unknown, locale: string, defaultLocale: string): unknown;
91
+ export type CmsEntryKind = 'collection' | 'single' | 'page';
92
+ export interface CmsPageRoute {
93
+ path: string;
94
+ key: string;
95
+ label: string;
96
+ }
91
97
  export interface CmsEntry {
92
98
  id: string;
93
99
  label: string;
94
- kind: 'collection' | 'single';
100
+ kind: CmsEntryKind;
95
101
  titleField?: string;
96
102
  drafts?: boolean;
97
103
  fields: Record<string, FieldConfig>;
104
+ routes?: 'auto' | string[];
105
+ include?: string[];
106
+ exclude?: string[];
107
+ order?: string[];
108
+ labels?: Record<string, string>;
109
+ overrides?: Record<string, Record<string, FieldConfig>>;
110
+ pages?: CmsPageRoute[];
98
111
  table?: CmsTable;
99
112
  }
100
113
  export type CmsConfig = Record<string, CmsEntry>;
114
+ export declare const PAGE_PATH_FIELD = "path";
115
+ export declare function isPageEntry(entry: CmsEntry): boolean;
116
+ export declare function pageSegments(path: string): string[];
117
+ export declare function pageKeyFromPath(path: string): string;
118
+ export declare function pageLabelFromPath(path: string): string;
119
+ export declare function pageParentPath(path: string): string | undefined;
120
+ export declare function pageRoutes(entry: CmsEntry): CmsPageRoute[];
121
+ export declare function pageRouteOf(entry: CmsEntry, key: string): CmsPageRoute | undefined;
122
+ export declare function pageOverrideFields(entry: CmsEntry, path: string): Record<string, FieldConfig>;
123
+ export declare function pageFields(entry: CmsEntry, path: string): Record<string, FieldConfig>;
124
+ export declare function pageAllFields(entry: CmsEntry): Record<string, FieldConfig>;
125
+ type EntryLike = Pick<CmsEntry, 'fields'> & Partial<Pick<CmsEntry, 'kind' | 'overrides'>>;
126
+ export declare function entryFieldsFor(entry: EntryLike, path?: string): Record<string, FieldConfig>;
101
127
  export declare function typeName(name: string): string;
102
128
  export declare function blocksFieldTypeName(entryName: string, fieldKey: string): string;
103
129
  export declare function blockTypeName(entryName: string, fieldKey: string, blockName: string): string;
@@ -178,7 +204,18 @@ export interface CmsSingleInput extends CmsEntryInputBase {
178
204
  kind: 'single';
179
205
  titleField?: never;
180
206
  }
181
- export type CmsEntryInput = CmsCollectionInput | CmsSingleInput;
207
+ export interface CmsPageInput extends CmsEntryInputBase {
208
+ kind: 'page';
209
+ titleField?: never;
210
+ drafts?: never;
211
+ routes?: 'auto' | string[];
212
+ include?: string[];
213
+ exclude?: string[];
214
+ order?: string[];
215
+ labels?: Record<string, string>;
216
+ overrides?: Record<string, Record<string, CmsFieldInput>>;
217
+ }
218
+ export type CmsEntryInput = CmsCollectionInput | CmsSingleInput | CmsPageInput;
182
219
  export type CmsConfigInput = Record<string, CmsEntryInput>;
183
220
  export declare function defineCmsConfig<T extends CmsConfigInput>(config: T): T;
184
221
  export {};