@justanarthur/payload-www 0.3.4 → 1.0.1

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 (62) hide show
  1. package/README.md +317 -307
  2. package/dist/access.d.ts +2 -2
  3. package/dist/access.js +6 -30
  4. package/dist/blocks.d.ts +0 -10
  5. package/dist/blocks.js +8 -33
  6. package/dist/collections.d.ts +33 -225
  7. package/dist/collections.js +186 -661
  8. package/dist/config.d.ts +19 -105
  9. package/dist/config.js +263 -868
  10. package/dist/fields.d.ts +4 -46
  11. package/dist/fields.js +183 -73
  12. package/dist/imagehash.js +0 -15
  13. package/dist/import-map-provider.d.ts +0 -16
  14. package/dist/import-map-provider.js +0 -15
  15. package/dist/metadata.d.ts +24 -89
  16. package/dist/metadata.js +123 -258
  17. package/dist/pages.d.ts +37 -319
  18. package/dist/pages.js +355 -973
  19. package/dist/render-pages.d.ts +69 -564
  20. package/dist/render-pages.js +476 -1502
  21. package/dist/sitemap.d.ts +10 -0
  22. package/dist/sitemap.js +324 -0
  23. package/dist/translator.js +0 -15
  24. package/dist/utils.d.ts +4 -12
  25. package/dist/utils.js +10 -56
  26. package/package.json +75 -178
  27. package/dist/components.d.ts +0 -6
  28. package/dist/components.js +0 -39
  29. package/dist/core-access.d.ts +0 -11
  30. package/dist/core-access.js +0 -44
  31. package/dist/core-blocks.d.ts +0 -24
  32. package/dist/core-blocks.js +0 -89
  33. package/dist/core-fields.d.ts +0 -73
  34. package/dist/core-fields.js +0 -181
  35. package/dist/core-utils.d.ts +0 -16
  36. package/dist/core-utils.js +0 -73
  37. package/dist/data-collections.d.ts +0 -229
  38. package/dist/data-collections.js +0 -697
  39. package/dist/data-seed.d.ts +0 -76
  40. package/dist/data-seed.js +0 -212
  41. package/dist/data-test.d.ts +0 -30
  42. package/dist/data-test.js +0 -1134
  43. package/dist/globals.d.ts +0 -69
  44. package/dist/globals.js +0 -259
  45. package/dist/hooks.d.ts +0 -108
  46. package/dist/hooks.js +0 -228
  47. package/dist/index.d.ts +0 -6
  48. package/dist/index.js +0 -39
  49. package/dist/render-components.d.ts +0 -42
  50. package/dist/render-components.js +0 -154
  51. package/dist/render-metadata.d.ts +0 -122
  52. package/dist/render-metadata.js +0 -393
  53. package/dist/render-utils.d.ts +0 -166
  54. package/dist/render-utils.js +0 -401
  55. package/dist/seed.d.ts +0 -76
  56. package/dist/seed.js +0 -212
  57. package/dist/server.d.ts +0 -980
  58. package/dist/server.js +0 -2265
  59. package/dist/test.d.ts +0 -30
  60. package/dist/test.js +0 -1134
  61. package/dist/with-www-config.d.ts +0 -108
  62. package/dist/with-www-config.js +0 -1030
@@ -1,401 +0,0 @@
1
-
2
- var __defProp = Object.defineProperty;
3
- var __returnValue = (v) => v;
4
- function __exportSetter(name, newValue) {
5
- this[name] = __returnValue.bind(null, newValue);
6
- }
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, {
10
- get: all[name],
11
- enumerable: true,
12
- configurable: true,
13
- set: __exportSetter.bind(all, name)
14
- });
15
- };
16
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
-
18
- // src/render/components/LocaleSwitcher.tsx
19
- var exports_LocaleSwitcher = {};
20
- __export(exports_LocaleSwitcher, {
21
- LocaleSwitcher: () => LocaleSwitcher
22
- });
23
- import { jsx, jsxs } from "react/jsx-runtime";
24
- function LocaleSwitcher({
25
- currentLocale,
26
- hreflangAlternates,
27
- labels
28
- }) {
29
- const locales = Object.keys(hreflangAlternates).filter((k) => k !== "x-default");
30
- console.log("[WWW] render/components:LocaleSwitcher currentLocale=", currentLocale, "locales=", JSON.stringify(locales), "hasXDefault=", Boolean(hreflangAlternates["x-default"]));
31
- return /* @__PURE__ */ jsx("nav", {
32
- "aria-label": "Language",
33
- className: "locale-switcher",
34
- children: /* @__PURE__ */ jsxs("ul", {
35
- className: "flex flex-wrap gap-2 list-none p-0 m-0",
36
- children: [
37
- locales.map((locale) => {
38
- const href = hreflangAlternates[locale];
39
- if (!href)
40
- return null;
41
- const isCurrent = locale === currentLocale;
42
- return /* @__PURE__ */ jsx("li", {
43
- children: /* @__PURE__ */ jsx("a", {
44
- href,
45
- "aria-current": isCurrent ? "true" : undefined,
46
- hrefLang: locale,
47
- className: "locale-switcher__link",
48
- "data-locale": locale,
49
- children: labels?.[locale] ?? locale.toUpperCase()
50
- })
51
- }, locale);
52
- }),
53
- hreflangAlternates["x-default"] ? /* @__PURE__ */ jsx("li", {
54
- children: /* @__PURE__ */ jsx("a", {
55
- href: hreflangAlternates["x-default"],
56
- hrefLang: "x-default",
57
- className: "locale-switcher__link",
58
- "data-locale": "x-default",
59
- children: labels?.["x-default"] ?? "Default"
60
- })
61
- }, "x-default") : null
62
- ]
63
- })
64
- });
65
- }
66
- var init_LocaleSwitcher = () => {};
67
-
68
- // src/render/preview/createPreviewHandler.ts
69
- function createPreviewHandler(options) {
70
- const { getServerSideURL: _getServerSideURL, secret, enableDraftMode = true } = options;
71
- return async function GET(req) {
72
- const { draftMode } = await import("next/headers");
73
- const { redirect } = await import("next/navigation");
74
- const url = new URL(req.url);
75
- const path = url.searchParams.get("path") ?? "/";
76
- const previewSecret = url.searchParams.get("previewSecret");
77
- console.log("[WWW] render/preview:createPreviewHandler:GET path=", path, "hasSecret=", Boolean(previewSecret), "enableDraftMode=", enableDraftMode);
78
- if (!previewSecret || previewSecret !== secret) {
79
- console.warn("[WWW] render/preview:createPreviewHandler:GET invalid preview secret (401)");
80
- return new Response("Invalid preview secret", { status: 401 });
81
- }
82
- if (enableDraftMode) {
83
- (await draftMode()).enable();
84
- console.log("[WWW] render/preview:createPreviewHandler:GET draftMode enabled");
85
- }
86
- redirect(path);
87
- return new Response(null, { status: 204 });
88
- };
89
- }
90
-
91
- // src/render/_locale.ts
92
- function prefixFor(locale, defaultLocale, mode) {
93
- let result;
94
- if (mode === "never")
95
- result = "";
96
- else if (mode === "as-needed" && locale === defaultLocale)
97
- result = "";
98
- else
99
- result = `/${locale}`;
100
- console.log("[WWW] render/_locale:prefixFor locale=", locale, "default=", defaultLocale, "mode=", mode, "->", JSON.stringify(result));
101
- return result;
102
- }
103
- function resolveLocale(req) {
104
- if (!req || typeof req !== "object") {
105
- console.log('[WWW] render/_locale:resolveLocale -> "" (no req)');
106
- return "";
107
- }
108
- const r = req;
109
- if (typeof r.locale === "string" && r.locale.length > 0) {
110
- console.log("[WWW] render/_locale:resolveLocale ->", r.locale, "(from req.locale)");
111
- return r.locale;
112
- }
113
- const fallback = r.payload?.config?.localization?.defaultLocale;
114
- if (typeof fallback === "string" && fallback.length > 0) {
115
- console.log("[WWW] render/_locale:resolveLocale ->", fallback, "(from config.localization.defaultLocale)");
116
- return fallback;
117
- }
118
- console.log('[WWW] render/_locale:resolveLocale -> "" (no locale anywhere)');
119
- return "";
120
- }
121
- function allLocales(req) {
122
- if (!req || typeof req !== "object") {
123
- console.log("[WWW] render/_locale:allLocales -> [] (no req)");
124
- return [];
125
- }
126
- const r = req;
127
- const list = r.payload?.config?.localization?.locales;
128
- if (!Array.isArray(list) || list.length === 0) {
129
- console.log("[WWW] render/_locale:allLocales -> [] (no locales declared)");
130
- return [];
131
- }
132
- const out = [];
133
- for (const entry of list) {
134
- if (typeof entry === "string" && entry.length > 0) {
135
- out.push(entry);
136
- } else if (entry && typeof entry === "object" && "code" in entry) {
137
- const code = entry.code;
138
- if (typeof code === "string" && code.length > 0)
139
- out.push(code);
140
- }
141
- }
142
- console.log("[WWW] render/_locale:allLocales ->", JSON.stringify(out));
143
- return out;
144
- }
145
-
146
- // src/render/metadata/hreflang.ts
147
- async function buildHreflangAlternates({
148
- siteUrl,
149
- locale,
150
- urlPrefix,
151
- storedSlug,
152
- queryAllLocaleSlugs,
153
- nested,
154
- homeSlug,
155
- defaultLocale,
156
- locales,
157
- localePrefix = "always"
158
- }) {
159
- const allLocaleSlugs = await queryAllLocaleSlugs(storedSlug, locale);
160
- console.log("[WWW] render/metadata:buildHreflangAlternates storedSlug=", storedSlug, "locale=", locale, "allLocaleSlugs=", JSON.stringify(allLocaleSlugs));
161
- const languages = {};
162
- const urlFor = (l, slug) => {
163
- const trimmedPrefix = urlPrefix.replace(/^\/|\/$/g, "");
164
- const prefixSegment = trimmedPrefix ? `/${trimmedPrefix}` : "";
165
- const urlPath = slug === homeSlug ? "/" : nested ? "/" + slug.replaceAll("_", "/") : "/" + slug;
166
- const localeSegment = localePrefix === "never" ? "" : localePrefix === "as-needed" && l === defaultLocale ? "" : `/${l}`;
167
- return `${siteUrl}${localeSegment}${prefixSegment}${urlPath}`;
168
- };
169
- for (const l of locales) {
170
- const slugForLocale = allLocaleSlugs?.[l];
171
- if (!slugForLocale)
172
- continue;
173
- languages[l] = urlFor(l, slugForLocale);
174
- }
175
- if (allLocaleSlugs?.[defaultLocale]) {
176
- languages["x-default"] = urlFor(defaultLocale, allLocaleSlugs[defaultLocale]);
177
- }
178
- console.log("[WWW] render/metadata:buildHreflangAlternates ->", JSON.stringify(languages));
179
- return languages;
180
- }
181
-
182
- // src/render/metadata/query.ts
183
- import { getPayload } from "payload";
184
- import { cache } from "react";
185
-
186
- // src/core/utils/getFromImportMap.ts
187
- function getFromImportMap(key, importMap) {
188
- const resolvedKey = key.includes("#") ? key : key + "#default";
189
- const value = importMap[resolvedKey];
190
- console.log("[WWW] core/utils:getFromImportMap key=", key, "resolved=", resolvedKey, "hit=", Boolean(value));
191
- return value;
192
- }
193
-
194
- // src/render/metadata/query.ts
195
- var queryDocBySlug = cache(async function queryDocBySlug2({
196
- collectionSlug,
197
- slug,
198
- slugField = "slug",
199
- locale,
200
- draft = false,
201
- config
202
- }) {
203
- console.log("[WWW] render/metadata:queryDocBySlug collection=", collectionSlug, "slug=", slug, "slugField=", slugField, "locale=", locale, "draft=", draft);
204
- const payload = await getPayload({ config });
205
- const result = await payload.find({
206
- collection: collectionSlug,
207
- draft,
208
- limit: 1,
209
- pagination: false,
210
- overrideAccess: draft,
211
- where: { [slugField]: { equals: slug } },
212
- locale
213
- });
214
- const doc = result.docs?.[0] ?? null;
215
- console.log("[WWW] render/metadata:queryDocBySlug ->", doc ? "hit" : "miss");
216
- return doc;
217
- });
218
- var queryAllDocs = cache(async function queryAllDocs2({
219
- collectionSlug,
220
- slugField = "slug",
221
- locale,
222
- config
223
- }) {
224
- console.log("[WWW] render/metadata:queryAllDocs collection=", collectionSlug, "locale=", locale);
225
- const payload = await getPayload({ config });
226
- const result = await payload.find({
227
- collection: collectionSlug,
228
- draft: false,
229
- limit: 1000,
230
- pagination: false,
231
- overrideAccess: false,
232
- select: { [slugField]: true },
233
- locale
234
- });
235
- const docs = result.docs ?? [];
236
- console.log("[WWW] render/metadata:queryAllDocs -> count=", docs.length);
237
- return docs;
238
- });
239
- var queryAllLocaleSlugs = cache(async function queryAllLocaleSlugs2({
240
- collectionSlug,
241
- slug,
242
- slugField = "slug",
243
- locale,
244
- config
245
- }) {
246
- console.log("[WWW] render/metadata:queryAllLocaleSlugs collection=", collectionSlug, "slug=", slug, "locale=", locale);
247
- const payload = await getPayload({ config });
248
- const result = await payload.find({
249
- collection: collectionSlug,
250
- draft: false,
251
- limit: 1,
252
- pagination: false,
253
- overrideAccess: false,
254
- locale,
255
- where: { [slugField]: { equals: slug } },
256
- select: { [slugField]: true }
257
- });
258
- const doc = result.docs?.[0];
259
- if (!doc) {
260
- console.log("[WWW] render/metadata:queryAllLocaleSlugs -> undefined (no doc)");
261
- return;
262
- }
263
- let fieldValue = doc[slugField];
264
- if (doc.id != null) {
265
- const allLocales2 = await payload.findByID({
266
- collection: collectionSlug,
267
- id: doc.id,
268
- locale: "all",
269
- draft: false,
270
- overrideAccess: false,
271
- select: { [slugField]: true }
272
- }).catch(() => null);
273
- if (allLocales2)
274
- fieldValue = allLocales2[slugField];
275
- }
276
- if (fieldValue && typeof fieldValue === "object") {
277
- console.log("[WWW] render/metadata:queryAllLocaleSlugs -> localized map=", JSON.stringify(fieldValue));
278
- return fieldValue;
279
- }
280
- const resolved = await config;
281
- const rawLocales = Array.isArray(resolved?.localization?.localeCodes) ? resolved.localization.localeCodes : resolved?.localization?.locales?.map((l) => l.code) ?? [];
282
- const out = {};
283
- for (const l of rawLocales)
284
- out[l] = String(fieldValue ?? slug);
285
- console.log("[WWW] render/metadata:queryAllLocaleSlugs -> flat-fanout locales=", rawLocales.length, "slug=", JSON.stringify(fieldValue ?? slug));
286
- return out;
287
- });
288
- var queryGlobal = cache(async function queryGlobal2({
289
- globalSlug,
290
- locale,
291
- depth = 0,
292
- draft = false,
293
- config
294
- }) {
295
- console.log("[WWW] render/metadata:queryGlobal global=", globalSlug, "locale=", locale, "depth=", depth, "draft=", draft);
296
- const payload = await getPayload({ config });
297
- try {
298
- const global = await payload.findGlobal({
299
- slug: globalSlug,
300
- depth,
301
- draft,
302
- locale
303
- });
304
- console.log("[WWW] render/metadata:queryGlobal -> hit");
305
- return global;
306
- } catch (error) {
307
- console.warn("[WWW] render/metadata:queryGlobal failed for slug=", globalSlug, "err=", String(error));
308
- return null;
309
- }
310
- });
311
- function getRenderModuleExports(exportName, collection, importMap) {
312
- const path = collection?.custom?.path;
313
- if (!path) {
314
- console.log("[WWW] render/metadata:getRenderModuleExports no custom.path exportName=", exportName);
315
- return;
316
- }
317
- const mod = getFromImportMap(path, importMap);
318
- const value = mod?.[exportName];
319
- console.log("[WWW] render/metadata:getRenderModuleExports exportName=", exportName, "path=", path, "hit=", Boolean(value));
320
- return value;
321
- }
322
-
323
- // src/render/sitemap/createSitemapFile.ts
324
- function createSitemapFile(options) {
325
- const { collections } = options;
326
- return async function sitemap() {
327
- console.log("[WWW] render/sitemap:createSitemapFile:sitemap collections=", JSON.stringify(options.collections), "localePrefix=", options.localePrefix ?? "always");
328
- const cfg = await options.config;
329
- const allLocales2 = Array.isArray(cfg.localization?.locales) ? cfg.localization.locales.map((l) => typeof l === "string" ? l : l.code) : [cfg.localization?.defaultLocale ?? "en"];
330
- const defaultLocale = cfg.localization?.defaultLocale ?? allLocales2[0];
331
- const activeLocales = Array.isArray(options.locales) && options.locales.length > 0 ? options.locales.filter((l) => allLocales2.includes(l)) : allLocales2;
332
- console.log("[WWW] render/sitemap:createSitemapFile:sitemap allLocales=", JSON.stringify(allLocales2), "default=", defaultLocale, "active=", JSON.stringify(activeLocales));
333
- const entries = [];
334
- const seen = new Set;
335
- for (const collectionSlug of collections) {
336
- const collectionDefaults = options.perCollection?.[collectionSlug] ?? {};
337
- const urlPrefix = (options.urlPrefixes?.[collectionSlug] ?? "").replace(/\/$/, "");
338
- const siteUrl = options.getServerSideURL().replace(/\/$/, "");
339
- const isNested = options.nested?.[collectionSlug] ?? false;
340
- for (const locale of activeLocales) {
341
- const docs = await queryAllDocs({
342
- collectionSlug,
343
- slugField: "slug",
344
- locale,
345
- config: options.config
346
- });
347
- for (const doc of docs) {
348
- const storedSlug = doc.slug;
349
- if (typeof storedSlug !== "string" || storedSlug === "")
350
- continue;
351
- const dedupeKey = `${collectionSlug}:${locale}:${storedSlug}`;
352
- if (seen.has(dedupeKey))
353
- continue;
354
- seen.add(dedupeKey);
355
- const slugPath = isNested ? storedSlug.replaceAll("_", "/") : storedSlug;
356
- const url = `${siteUrl}${prefixFor(locale, defaultLocale, options.localePrefix ?? "always")}${urlPrefix}/${slugPath}`;
357
- const languages = await buildHreflangAlternates({
358
- siteUrl,
359
- locale,
360
- urlPrefix,
361
- storedSlug,
362
- nested: isNested,
363
- homeSlug: "",
364
- defaultLocale,
365
- locales: activeLocales,
366
- localePrefix: options.localePrefix,
367
- queryAllLocaleSlugs: async (s, l) => {
368
- const result = await queryAllLocaleSlugs({
369
- collectionSlug,
370
- slug: s,
371
- slugField: "slug",
372
- locale: l,
373
- config: options.config
374
- });
375
- return result ?? undefined;
376
- }
377
- });
378
- entries.push({
379
- url,
380
- lastModified: doc.updatedAt ? new Date(doc.updatedAt) : undefined,
381
- changeFrequency: collectionDefaults.changefreq ?? "weekly",
382
- priority: collectionDefaults.priority ?? 0.5,
383
- alternates: { languages }
384
- });
385
- }
386
- }
387
- }
388
- console.log("[WWW] render/sitemap:createSitemapFile:sitemap -> entries=", entries.length);
389
- return entries;
390
- };
391
- }
392
-
393
- // src/exports/render-utils.ts
394
- init_LocaleSwitcher();
395
- var render_utils_default = { createPreviewHandler, createSitemapFile, LocaleSwitcher };
396
- export {
397
- render_utils_default as default,
398
- createSitemapFile,
399
- createPreviewHandler,
400
- LocaleSwitcher
401
- };
package/dist/seed.d.ts DELETED
@@ -1,76 +0,0 @@
1
- import { Payload } from "payload";
2
- type SeedPageInput = {
3
- slug: string;
4
- title: Record<string, string>;
5
- meta?: Record<string, {
6
- title?: string;
7
- description?: string;
8
- }>;
9
- blocks?: Array<Record<string, unknown>>;
10
- status?: "draft" | "published";
11
- publishedAt?: string;
12
- };
13
- type SeedPostInput = {
14
- slug: string;
15
- title: Record<string, string>;
16
- excerpt?: Record<string, string>;
17
- content?: Record<string, unknown>;
18
- status?: "draft" | "published";
19
- publishedAt?: string;
20
- };
21
- type SeedUserInput = {
22
- email: string;
23
- password?: string;
24
- name?: string;
25
- };
26
- type SeedCategoryInput = {
27
- title: string;
28
- slug?: string;
29
- };
30
- type CreateBaseSeedOptions = {
31
- defaultLocale?: string;
32
- locales?: string[];
33
- users?: SeedUserInput[];
34
- categories?: SeedCategoryInput[];
35
- pages?: SeedPageInput[];
36
- posts?: SeedPostInput[];
37
- dryRun?: boolean;
38
- };
39
- type CreateBaseSeedResult = {
40
- users: Array<{
41
- id: string | number;
42
- email: string;
43
- }>;
44
- categories: Array<{
45
- id: string | number;
46
- title: string;
47
- slug: string;
48
- }>;
49
- pages: Array<{
50
- id: string | number;
51
- slug: string;
52
- locale: string;
53
- }>;
54
- posts: Array<{
55
- id: string | number;
56
- slug: string;
57
- locale: string;
58
- }>;
59
- };
60
- /**
61
- * Idempotent seeder for the lib's collections. Re-running on the
62
- * same database is a no-op for users (matched by email) and
63
- * categories (matched by title); pages and posts are matched by
64
- * slug and re-created if missing.
65
- *
66
- * Pages and posts are created once per slug — localized values are
67
- * stored in a single doc per slug. Tests assert the alternate
68
- * resolution by querying `locale: 'all'`.
69
- *
70
- * Throws on:
71
- * - any block slug in a Page's `layout` that doesn't exist on the
72
- * Pages collection's `blocks` field
73
- * - a block without a `blockType`
74
- */
75
- declare function createBaseSeed(payload: Payload, options?: CreateBaseSeedOptions): Promise<CreateBaseSeedResult>;
76
- export { createBaseSeed as default, createBaseSeed, SeedUserInput, SeedPostInput, SeedPageInput, SeedCategoryInput, CreateBaseSeedResult, CreateBaseSeedOptions };
package/dist/seed.js DELETED
@@ -1,212 +0,0 @@
1
-
2
- var __defProp = Object.defineProperty;
3
- var __returnValue = (v) => v;
4
- function __exportSetter(name, newValue) {
5
- this[name] = __returnValue.bind(null, newValue);
6
- }
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, {
10
- get: all[name],
11
- enumerable: true,
12
- configurable: true,
13
- set: __exportSetter.bind(all, name)
14
- });
15
- };
16
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
17
-
18
- // src/data/seed/createBaseSeed.ts
19
- var simpleRichText = (text) => ({
20
- root: {
21
- type: "root",
22
- format: "",
23
- indent: 0,
24
- version: 1,
25
- direction: "ltr",
26
- children: [
27
- {
28
- type: "paragraph",
29
- format: "",
30
- indent: 0,
31
- version: 1,
32
- direction: "ltr",
33
- textFormat: 0,
34
- children: [
35
- { mode: "normal", text, type: "text", style: "", detail: 0, format: 0, version: 1 }
36
- ]
37
- }
38
- ]
39
- }
40
- });
41
- async function createBaseSeed(payload, options = {}) {
42
- const localization = payload.config.localization;
43
- const defaultLocale = options.defaultLocale ?? (typeof localization === "object" && localization ? typeof localization.defaultLocale === "string" ? localization.defaultLocale : "en" : "en");
44
- const configLocales = typeof localization === "object" && localization ? (localization.locales ?? []).map((l) => typeof l === "string" ? l : l.code) : [];
45
- const locales = options.locales ?? (configLocales.length > 0 ? configLocales : [defaultLocale]);
46
- const result = { users: [], categories: [], pages: [], posts: [] };
47
- const pagesCollection = payload.collections["pages"];
48
- if (!pagesCollection) {
49
- throw new Error("createBaseSeed: no `pages` collection registered with this payload instance");
50
- }
51
- const findBlocksField = (fields) => {
52
- for (const f of fields) {
53
- if (f.name === "blocks" && Array.isArray(f.blocks))
54
- return f;
55
- if (Array.isArray(f.fields)) {
56
- const found = findBlocksField(f.fields);
57
- if (found)
58
- return found;
59
- }
60
- if (Array.isArray(f.tabs)) {
61
- for (const t of f.tabs) {
62
- if (Array.isArray(t.fields)) {
63
- const found = findBlocksField(t.fields);
64
- if (found)
65
- return found;
66
- }
67
- }
68
- }
69
- }
70
- return;
71
- };
72
- const layoutField = findBlocksField(pagesCollection.config.fields);
73
- const validBlockSlugs = new Set((layoutField?.blocks ?? []).map((b) => b.slug));
74
- for (const page of options.pages ?? []) {
75
- for (const block of page.blocks ?? []) {
76
- const slug = block.blockType;
77
- if (!slug) {
78
- throw new Error(`createBaseSeed: page "${page.slug}" has a block without blockType`);
79
- }
80
- if (!validBlockSlugs.has(slug)) {
81
- throw new Error(`createBaseSeed: page "${page.slug}" references unknown block slug "${slug}". Allowed: ${[...validBlockSlugs].join(", ")}`);
82
- }
83
- }
84
- }
85
- if (options.dryRun)
86
- return result;
87
- for (const user of options.users ?? [{ email: "dev@payloadcms.com", password: "test", name: "Dev User" }]) {
88
- const existing = await payload.find({
89
- collection: "users",
90
- where: { email: { equals: user.email } },
91
- limit: 1,
92
- overrideAccess: true
93
- });
94
- let id;
95
- if (existing.docs.length > 0) {
96
- id = existing.docs[0].id;
97
- } else {
98
- const created = await payload.create({
99
- collection: "users",
100
- data: { email: user.email, password: user.password ?? "test", name: user.name ?? "" },
101
- overrideAccess: true
102
- });
103
- id = created.id;
104
- }
105
- result.users.push({ id, email: user.email });
106
- }
107
- for (const cat of options.categories ?? []) {
108
- const slug = cat.slug ?? cat.title.toLowerCase().replace(/\s+/g, "-");
109
- const existing = await payload.find({
110
- collection: "categories",
111
- where: { title: { equals: cat.title } },
112
- limit: 1,
113
- overrideAccess: true
114
- });
115
- let id;
116
- if (existing.docs.length > 0) {
117
- id = existing.docs[0].id;
118
- } else {
119
- const created = await payload.create({
120
- collection: "categories",
121
- data: { title: cat.title, slug },
122
- overrideAccess: true
123
- });
124
- id = created.id;
125
- }
126
- result.categories.push({ id, title: cat.title, slug });
127
- }
128
- for (const page of options.pages ?? []) {
129
- const existing = await payload.find({
130
- collection: "pages",
131
- where: { slug: { equals: page.slug } },
132
- limit: 1,
133
- overrideAccess: true
134
- });
135
- const data = {
136
- slug: page.slug,
137
- title: { ...page.title },
138
- blocks: page.blocks ?? [],
139
- publishedAt: page.publishedAt ?? new Date().toISOString(),
140
- _status: page.status === "draft" ? "draft" : "published"
141
- };
142
- if (page.meta)
143
- data.meta = { ...page.meta };
144
- let id;
145
- if (existing.docs.length === 0) {
146
- const created = await payload.create({
147
- collection: "pages",
148
- data,
149
- overrideAccess: true,
150
- draft: page.status === "draft"
151
- });
152
- id = created.id;
153
- } else {
154
- id = existing.docs[0].id;
155
- await payload.update({
156
- collection: "pages",
157
- id,
158
- data,
159
- overrideAccess: true,
160
- draft: page.status === "draft"
161
- });
162
- }
163
- for (const locale of locales)
164
- result.pages.push({ id, slug: page.slug, locale });
165
- }
166
- for (const post of options.posts ?? []) {
167
- const existing = await payload.find({
168
- collection: "posts",
169
- where: { slug: { equals: post.slug } },
170
- limit: 1,
171
- overrideAccess: true
172
- });
173
- const data = {
174
- slug: post.slug,
175
- title: { ...post.title },
176
- ...post.excerpt ? { excerpt: { ...post.excerpt } } : {},
177
- content: post.content ?? simpleRichText("Hello world"),
178
- publishedAt: post.publishedAt ?? new Date().toISOString(),
179
- authors: result.users.length > 0 ? [result.users[0].id] : [],
180
- _status: post.status === "draft" ? "draft" : "published"
181
- };
182
- let id;
183
- if (existing.docs.length === 0) {
184
- const created = await payload.create({
185
- collection: "posts",
186
- data,
187
- overrideAccess: true,
188
- draft: post.status === "draft"
189
- });
190
- id = created.id;
191
- } else {
192
- id = existing.docs[0].id;
193
- await payload.update({
194
- collection: "posts",
195
- id,
196
- data,
197
- overrideAccess: true,
198
- draft: post.status === "draft"
199
- });
200
- }
201
- for (const locale of locales)
202
- result.posts.push({ id, slug: post.slug, locale });
203
- }
204
- return result;
205
- }
206
-
207
- // src/exports/seed.ts
208
- var seed_default = createBaseSeed;
209
- export {
210
- seed_default as default,
211
- createBaseSeed
212
- };