@justanarthur/payload-www 0.3.5 → 1.2.0

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 (63) hide show
  1. package/README.md +317 -307
  2. package/dist/access.d.ts +2 -2
  3. package/dist/access.js +3 -17
  4. package/dist/blocks.d.ts +7 -12
  5. package/dist/blocks.js +24 -43
  6. package/dist/cli.js +201 -0
  7. package/dist/collections.d.ts +33 -225
  8. package/dist/collections.js +185 -639
  9. package/dist/config.d.ts +19 -105
  10. package/dist/config.js +257 -855
  11. package/dist/fields.d.ts +4 -46
  12. package/dist/fields.js +177 -53
  13. package/dist/imagehash.js +0 -15
  14. package/dist/import-map-provider.d.ts +0 -16
  15. package/dist/import-map-provider.js +0 -15
  16. package/dist/metadata.d.ts +24 -89
  17. package/dist/metadata.js +123 -255
  18. package/dist/pages.d.ts +37 -319
  19. package/dist/pages.js +349 -964
  20. package/dist/render-pages.d.ts +70 -565
  21. package/dist/render-pages.js +464 -1477
  22. package/dist/sitemap.d.ts +10 -0
  23. package/dist/sitemap.js +337 -0
  24. package/dist/translator.js +0 -15
  25. package/dist/utils.d.ts +10 -12
  26. package/dist/utils.js +18 -41
  27. package/package.json +81 -178
  28. package/dist/components.d.ts +0 -6
  29. package/dist/components.js +0 -39
  30. package/dist/core-access.d.ts +0 -11
  31. package/dist/core-access.js +0 -34
  32. package/dist/core-blocks.d.ts +0 -24
  33. package/dist/core-blocks.js +0 -79
  34. package/dist/core-fields.d.ts +0 -73
  35. package/dist/core-fields.js +0 -167
  36. package/dist/core-utils.d.ts +0 -16
  37. package/dist/core-utils.js +0 -63
  38. package/dist/data-collections.d.ts +0 -229
  39. package/dist/data-collections.js +0 -676
  40. package/dist/data-seed.d.ts +0 -76
  41. package/dist/data-seed.js +0 -212
  42. package/dist/data-test.d.ts +0 -30
  43. package/dist/data-test.js +0 -1110
  44. package/dist/globals.d.ts +0 -69
  45. package/dist/globals.js +0 -251
  46. package/dist/hooks.d.ts +0 -108
  47. package/dist/hooks.js +0 -228
  48. package/dist/index.d.ts +0 -6
  49. package/dist/index.js +0 -39
  50. package/dist/render-components.d.ts +0 -42
  51. package/dist/render-components.js +0 -154
  52. package/dist/render-metadata.d.ts +0 -122
  53. package/dist/render-metadata.js +0 -390
  54. package/dist/render-utils.d.ts +0 -166
  55. package/dist/render-utils.js +0 -398
  56. package/dist/seed.d.ts +0 -76
  57. package/dist/seed.js +0 -212
  58. package/dist/server.d.ts +0 -980
  59. package/dist/server.js +0 -2231
  60. package/dist/test.d.ts +0 -30
  61. package/dist/test.js +0 -1110
  62. package/dist/with-www-config.d.ts +0 -108
  63. package/dist/with-www-config.js +0 -1006
@@ -1,398 +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
- return importMap[key.includes("#") ? key : key + "#default"];
189
- }
190
-
191
- // src/render/metadata/query.ts
192
- var queryDocBySlug = cache(async function queryDocBySlug2({
193
- collectionSlug,
194
- slug,
195
- slugField = "slug",
196
- locale,
197
- draft = false,
198
- config
199
- }) {
200
- console.log("[WWW] render/metadata:queryDocBySlug collection=", collectionSlug, "slug=", slug, "slugField=", slugField, "locale=", locale, "draft=", draft);
201
- const payload = await getPayload({ config });
202
- const result = await payload.find({
203
- collection: collectionSlug,
204
- draft,
205
- limit: 1,
206
- pagination: false,
207
- overrideAccess: draft,
208
- where: { [slugField]: { equals: slug } },
209
- locale
210
- });
211
- const doc = result.docs?.[0] ?? null;
212
- console.log("[WWW] render/metadata:queryDocBySlug ->", doc ? "hit" : "miss");
213
- return doc;
214
- });
215
- var queryAllDocs = cache(async function queryAllDocs2({
216
- collectionSlug,
217
- slugField = "slug",
218
- locale,
219
- config
220
- }) {
221
- console.log("[WWW] render/metadata:queryAllDocs collection=", collectionSlug, "locale=", locale);
222
- const payload = await getPayload({ config });
223
- const result = await payload.find({
224
- collection: collectionSlug,
225
- draft: false,
226
- limit: 1000,
227
- pagination: false,
228
- overrideAccess: false,
229
- select: { [slugField]: true },
230
- locale
231
- });
232
- const docs = result.docs ?? [];
233
- console.log("[WWW] render/metadata:queryAllDocs -> count=", docs.length);
234
- return docs;
235
- });
236
- var queryAllLocaleSlugs = cache(async function queryAllLocaleSlugs2({
237
- collectionSlug,
238
- slug,
239
- slugField = "slug",
240
- locale,
241
- config
242
- }) {
243
- console.log("[WWW] render/metadata:queryAllLocaleSlugs collection=", collectionSlug, "slug=", slug, "locale=", locale);
244
- const payload = await getPayload({ config });
245
- const result = await payload.find({
246
- collection: collectionSlug,
247
- draft: false,
248
- limit: 1,
249
- pagination: false,
250
- overrideAccess: false,
251
- locale,
252
- where: { [slugField]: { equals: slug } },
253
- select: { [slugField]: true }
254
- });
255
- const doc = result.docs?.[0];
256
- if (!doc) {
257
- console.log("[WWW] render/metadata:queryAllLocaleSlugs -> undefined (no doc)");
258
- return;
259
- }
260
- let fieldValue = doc[slugField];
261
- if (doc.id != null) {
262
- const allLocales2 = await payload.findByID({
263
- collection: collectionSlug,
264
- id: doc.id,
265
- locale: "all",
266
- draft: false,
267
- overrideAccess: false,
268
- select: { [slugField]: true }
269
- }).catch(() => null);
270
- if (allLocales2)
271
- fieldValue = allLocales2[slugField];
272
- }
273
- if (fieldValue && typeof fieldValue === "object") {
274
- console.log("[WWW] render/metadata:queryAllLocaleSlugs -> localized map=", JSON.stringify(fieldValue));
275
- return fieldValue;
276
- }
277
- const resolved = await config;
278
- const rawLocales = Array.isArray(resolved?.localization?.localeCodes) ? resolved.localization.localeCodes : resolved?.localization?.locales?.map((l) => l.code) ?? [];
279
- const out = {};
280
- for (const l of rawLocales)
281
- out[l] = String(fieldValue ?? slug);
282
- console.log("[WWW] render/metadata:queryAllLocaleSlugs -> flat-fanout locales=", rawLocales.length, "slug=", JSON.stringify(fieldValue ?? slug));
283
- return out;
284
- });
285
- var queryGlobal = cache(async function queryGlobal2({
286
- globalSlug,
287
- locale,
288
- depth = 0,
289
- draft = false,
290
- config
291
- }) {
292
- console.log("[WWW] render/metadata:queryGlobal global=", globalSlug, "locale=", locale, "depth=", depth, "draft=", draft);
293
- const payload = await getPayload({ config });
294
- try {
295
- const global = await payload.findGlobal({
296
- slug: globalSlug,
297
- depth,
298
- draft,
299
- locale
300
- });
301
- console.log("[WWW] render/metadata:queryGlobal -> hit");
302
- return global;
303
- } catch (error) {
304
- console.warn("[WWW] render/metadata:queryGlobal failed for slug=", globalSlug, "err=", String(error));
305
- return null;
306
- }
307
- });
308
- function getRenderModuleExports(exportName, collection, importMap) {
309
- const path = collection?.custom?.path;
310
- if (!path) {
311
- console.log("[WWW] render/metadata:getRenderModuleExports no custom.path exportName=", exportName);
312
- return;
313
- }
314
- const mod = getFromImportMap(path, importMap);
315
- const value = mod?.[exportName];
316
- console.log("[WWW] render/metadata:getRenderModuleExports exportName=", exportName, "path=", path, "hit=", Boolean(value));
317
- return value;
318
- }
319
-
320
- // src/render/sitemap/createSitemapFile.ts
321
- function createSitemapFile(options) {
322
- const { collections } = options;
323
- return async function sitemap() {
324
- console.log("[WWW] render/sitemap:createSitemapFile:sitemap collections=", JSON.stringify(options.collections), "localePrefix=", options.localePrefix ?? "always");
325
- const cfg = await options.config;
326
- const allLocales2 = Array.isArray(cfg.localization?.locales) ? cfg.localization.locales.map((l) => typeof l === "string" ? l : l.code) : [cfg.localization?.defaultLocale ?? "en"];
327
- const defaultLocale = cfg.localization?.defaultLocale ?? allLocales2[0];
328
- const activeLocales = Array.isArray(options.locales) && options.locales.length > 0 ? options.locales.filter((l) => allLocales2.includes(l)) : allLocales2;
329
- console.log("[WWW] render/sitemap:createSitemapFile:sitemap allLocales=", JSON.stringify(allLocales2), "default=", defaultLocale, "active=", JSON.stringify(activeLocales));
330
- const entries = [];
331
- const seen = new Set;
332
- for (const collectionSlug of collections) {
333
- const collectionDefaults = options.perCollection?.[collectionSlug] ?? {};
334
- const urlPrefix = (options.urlPrefixes?.[collectionSlug] ?? "").replace(/\/$/, "");
335
- const siteUrl = options.getServerSideURL().replace(/\/$/, "");
336
- const isNested = options.nested?.[collectionSlug] ?? false;
337
- for (const locale of activeLocales) {
338
- const docs = await queryAllDocs({
339
- collectionSlug,
340
- slugField: "slug",
341
- locale,
342
- config: options.config
343
- });
344
- for (const doc of docs) {
345
- const storedSlug = doc.slug;
346
- if (typeof storedSlug !== "string" || storedSlug === "")
347
- continue;
348
- const dedupeKey = `${collectionSlug}:${locale}:${storedSlug}`;
349
- if (seen.has(dedupeKey))
350
- continue;
351
- seen.add(dedupeKey);
352
- const slugPath = isNested ? storedSlug.replaceAll("_", "/") : storedSlug;
353
- const url = `${siteUrl}${prefixFor(locale, defaultLocale, options.localePrefix ?? "always")}${urlPrefix}/${slugPath}`;
354
- const languages = await buildHreflangAlternates({
355
- siteUrl,
356
- locale,
357
- urlPrefix,
358
- storedSlug,
359
- nested: isNested,
360
- homeSlug: "",
361
- defaultLocale,
362
- locales: activeLocales,
363
- localePrefix: options.localePrefix,
364
- queryAllLocaleSlugs: async (s, l) => {
365
- const result = await queryAllLocaleSlugs({
366
- collectionSlug,
367
- slug: s,
368
- slugField: "slug",
369
- locale: l,
370
- config: options.config
371
- });
372
- return result ?? undefined;
373
- }
374
- });
375
- entries.push({
376
- url,
377
- lastModified: doc.updatedAt ? new Date(doc.updatedAt) : undefined,
378
- changeFrequency: collectionDefaults.changefreq ?? "weekly",
379
- priority: collectionDefaults.priority ?? 0.5,
380
- alternates: { languages }
381
- });
382
- }
383
- }
384
- }
385
- console.log("[WWW] render/sitemap:createSitemapFile:sitemap -> entries=", entries.length);
386
- return entries;
387
- };
388
- }
389
-
390
- // src/exports/render-utils.ts
391
- init_LocaleSwitcher();
392
- var render_utils_default = { createPreviewHandler, createSitemapFile, LocaleSwitcher };
393
- export {
394
- render_utils_default as default,
395
- createSitemapFile,
396
- createPreviewHandler,
397
- LocaleSwitcher
398
- };
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
- };