@szymonpiatek/nextwordpress 0.0.3 → 0.0.5

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,855 @@
1
+ import useSWR2 from 'swr';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
+
7
+ // src/integrations/restApi/core/client/types.ts
8
+ var WordPressAPIError = class extends Error {
9
+ constructor(message, status, endpoint) {
10
+ super(message);
11
+ __publicField(this, "status", status);
12
+ __publicField(this, "endpoint", endpoint);
13
+ this.name = "WordPressAPIError";
14
+ }
15
+ };
16
+
17
+ // src/shared/url.ts
18
+ function resolveBaseUrl(config) {
19
+ return typeof window === "undefined" ? config.serverURL : config.clientURL;
20
+ }
21
+
22
+ // src/integrations/restApi/core/client/url.ts
23
+ function buildUrl(config, path, query) {
24
+ const base = resolveBaseUrl(config);
25
+ if (!query) return `${base}${path}`;
26
+ const params = new URLSearchParams();
27
+ for (const [key, value] of Object.entries(query)) {
28
+ if (value !== void 0 && value !== null) {
29
+ params.set(key, String(value));
30
+ }
31
+ }
32
+ const qs = params.toString();
33
+ return qs ? `${base}${path}?${qs}` : `${base}${path}`;
34
+ }
35
+
36
+ // src/integrations/restApi/core/client/fetcher.ts
37
+ var USER_AGENT = "NextWordpress Client";
38
+ async function doFetch(url, init = {}) {
39
+ const response = await fetch(url, init);
40
+ if (!response.ok) {
41
+ throw new WordPressAPIError(
42
+ `WordPress API request failed: ${response.statusText}`,
43
+ response.status,
44
+ url
45
+ );
46
+ }
47
+ return response;
48
+ }
49
+ function createFetcher(config) {
50
+ const cacheTtl = 300;
51
+ async function wpFetch(path, query, tags = ["wordpress"]) {
52
+ const url = buildUrl(config, path, query);
53
+ const res = await doFetch(url, {
54
+ headers: { "User-Agent": USER_AGENT },
55
+ next: { tags, revalidate: cacheTtl }
56
+ });
57
+ return await res.json();
58
+ }
59
+ async function wpFetchGraceful(path, fallback, query, tags = ["wordpress"]) {
60
+ try {
61
+ return await wpFetch(path, query, tags);
62
+ } catch {
63
+ console.warn(`WordPress fetch failed for ${path}`);
64
+ return fallback;
65
+ }
66
+ }
67
+ async function wpFetchPaginated(path, query, tags = ["wordpress"]) {
68
+ const url = buildUrl(config, path, query);
69
+ const res = await doFetch(url, {
70
+ headers: { "User-Agent": USER_AGENT },
71
+ next: { tags, revalidate: cacheTtl }
72
+ });
73
+ return {
74
+ data: await res.json(),
75
+ headers: {
76
+ total: parseInt(res.headers.get("X-WP-Total") ?? "0", 10),
77
+ totalPages: parseInt(res.headers.get("X-WP-TotalPages") ?? "0", 10)
78
+ }
79
+ };
80
+ }
81
+ async function wpFetchPaginatedGraceful(path, query, tags = ["wordpress"]) {
82
+ const empty = { data: [], headers: { total: 0, totalPages: 0 } };
83
+ try {
84
+ return await wpFetchPaginated(path, query, tags);
85
+ } catch {
86
+ console.warn(`WordPress paginated fetch failed for ${path}`);
87
+ return empty;
88
+ }
89
+ }
90
+ async function wpMutate(path, body, method = "POST", authToken) {
91
+ const url = buildUrl(config, path);
92
+ const headers = {
93
+ "Content-Type": "application/json",
94
+ "User-Agent": USER_AGENT
95
+ };
96
+ if (authToken) {
97
+ headers["Authorization"] = authToken;
98
+ }
99
+ const res = await doFetch(url, {
100
+ method,
101
+ headers,
102
+ body: JSON.stringify(body),
103
+ cache: "no-store"
104
+ });
105
+ return await res.json();
106
+ }
107
+ async function wpUpload(path, file, filename, mimeType, authToken) {
108
+ const url = buildUrl(config, path);
109
+ const res = await doFetch(url, {
110
+ method: "POST",
111
+ headers: {
112
+ "Content-Disposition": `attachment; filename="${filename}"`,
113
+ "Content-Type": mimeType,
114
+ "User-Agent": USER_AGENT,
115
+ "Authorization": authToken
116
+ },
117
+ body: file,
118
+ cache: "no-store"
119
+ });
120
+ return await res.json();
121
+ }
122
+ return { wpFetch, wpFetchGraceful, wpFetchPaginated, wpFetchPaginatedGraceful, wpMutate, wpUpload };
123
+ }
124
+
125
+ // src/integrations/restApi/core/posts/queries.ts
126
+ function createPostsQueries(fetcher) {
127
+ const { wpFetch, wpFetchGraceful, wpFetchPaginated, wpFetchPaginatedGraceful } = fetcher;
128
+ async function getPostsPaginated(page = 1, perPage = 9, filterParams) {
129
+ const query = { _embed: true, per_page: perPage, page };
130
+ const cacheTags = ["wordpress", "posts", `posts-page-${page}`];
131
+ if (filterParams?.search) {
132
+ query.search = filterParams.search;
133
+ cacheTags.push("posts-search");
134
+ }
135
+ if (filterParams?.author) {
136
+ query.author = filterParams.author;
137
+ cacheTags.push(`posts-author-${filterParams.author}`);
138
+ }
139
+ if (filterParams?.tag) {
140
+ query.tags = filterParams.tag;
141
+ cacheTags.push(`posts-tag-${filterParams.tag}`);
142
+ }
143
+ if (filterParams?.category) {
144
+ query.categories = filterParams.category;
145
+ cacheTags.push(`posts-category-${filterParams.category}`);
146
+ }
147
+ return wpFetchPaginatedGraceful("/wp-json/wp/v2/posts", query, cacheTags);
148
+ }
149
+ async function getRecentPosts(filterParams) {
150
+ const query = { _embed: true, per_page: 100 };
151
+ if (filterParams?.search) query.search = filterParams.search;
152
+ if (filterParams?.author) query.author = filterParams.author;
153
+ if (filterParams?.tag) query.tags = filterParams.tag;
154
+ if (filterParams?.category) query.categories = filterParams.category;
155
+ return wpFetchGraceful("/wp-json/wp/v2/posts", [], query, ["wordpress", "posts"]);
156
+ }
157
+ async function getPostById(id) {
158
+ return wpFetch(`/wp-json/wp/v2/posts/${id}`);
159
+ }
160
+ async function getPostBySlug(slug) {
161
+ const posts = await wpFetchGraceful("/wp-json/wp/v2/posts", [], { slug, _embed: true });
162
+ return posts[0];
163
+ }
164
+ async function getPostsByCategory(categoryId) {
165
+ return wpFetch("/wp-json/wp/v2/posts", { categories: categoryId });
166
+ }
167
+ async function getPostsByTag(tagId) {
168
+ return wpFetch("/wp-json/wp/v2/posts", { tags: tagId });
169
+ }
170
+ async function getPostsByAuthor(authorId) {
171
+ return wpFetch("/wp-json/wp/v2/posts", { author: authorId });
172
+ }
173
+ async function getPostsByCategoryPaginated(categoryId, page = 1, perPage = 9) {
174
+ return wpFetchPaginatedGraceful("/wp-json/wp/v2/posts", {
175
+ _embed: true,
176
+ per_page: perPage,
177
+ page,
178
+ categories: categoryId
179
+ });
180
+ }
181
+ async function getPostsByTagPaginated(tagId, page = 1, perPage = 9) {
182
+ return wpFetchPaginatedGraceful("/wp-json/wp/v2/posts", {
183
+ _embed: true,
184
+ per_page: perPage,
185
+ page,
186
+ tags: tagId
187
+ });
188
+ }
189
+ async function getPostsByAuthorPaginated(authorId, page = 1, perPage = 9) {
190
+ return wpFetchPaginatedGraceful("/wp-json/wp/v2/posts", {
191
+ _embed: true,
192
+ per_page: perPage,
193
+ page,
194
+ author: authorId
195
+ });
196
+ }
197
+ async function getAllPostSlugs() {
198
+ try {
199
+ const allSlugs = [];
200
+ let page = 1;
201
+ let hasMore = true;
202
+ while (hasMore) {
203
+ const response = await wpFetchPaginated(
204
+ "/wp-json/wp/v2/posts",
205
+ { per_page: 100, page, _fields: "slug" }
206
+ );
207
+ allSlugs.push(...response.data.map((post) => ({ slug: post.slug })));
208
+ hasMore = page < response.headers.totalPages;
209
+ page++;
210
+ }
211
+ return allSlugs;
212
+ } catch {
213
+ console.warn("WordPress unavailable, skipping static generation for posts");
214
+ return [];
215
+ }
216
+ }
217
+ async function getAllPostsForSitemap() {
218
+ try {
219
+ const allPosts = [];
220
+ let page = 1;
221
+ let hasMore = true;
222
+ while (hasMore) {
223
+ const response = await wpFetchPaginated(
224
+ "/wp-json/wp/v2/posts",
225
+ { per_page: 100, page, _fields: "slug,modified" }
226
+ );
227
+ allPosts.push(...response.data.map((post) => ({ slug: post.slug, modified: post.modified })));
228
+ hasMore = page < response.headers.totalPages;
229
+ page++;
230
+ }
231
+ return allPosts;
232
+ } catch {
233
+ console.warn("WordPress unavailable, skipping sitemap generation");
234
+ return [];
235
+ }
236
+ }
237
+ return {
238
+ getPostsPaginated,
239
+ getRecentPosts,
240
+ getPostById,
241
+ getPostBySlug,
242
+ getPostsByCategory,
243
+ getPostsByTag,
244
+ getPostsByAuthor,
245
+ getPostsByCategoryPaginated,
246
+ getPostsByTagPaginated,
247
+ getPostsByAuthorPaginated,
248
+ getAllPostSlugs,
249
+ getAllPostsForSitemap
250
+ };
251
+ }
252
+
253
+ // src/hooks/usePosts.ts
254
+ function usePosts(config, filter, swrOptions) {
255
+ const key = ["wp-posts", config.clientURL, JSON.stringify(filter ?? null)];
256
+ return useSWR2(
257
+ key,
258
+ () => {
259
+ const fetcher = createFetcher(config);
260
+ return createPostsQueries(fetcher).getRecentPosts(filter);
261
+ },
262
+ swrOptions
263
+ );
264
+ }
265
+ function usePost(config, id, swrOptions) {
266
+ const key = id != null ? ["wp-post", config.clientURL, id] : null;
267
+ return useSWR2(
268
+ key,
269
+ () => {
270
+ const fetcher = createFetcher(config);
271
+ return createPostsQueries(fetcher).getPostById(id);
272
+ },
273
+ swrOptions
274
+ );
275
+ }
276
+ function usePostBySlug(config, slug, swrOptions) {
277
+ const key = slug ? ["wp-post-slug", config.clientURL, slug] : null;
278
+ return useSWR2(
279
+ key,
280
+ () => {
281
+ const fetcher = createFetcher(config);
282
+ return createPostsQueries(fetcher).getPostBySlug(slug);
283
+ },
284
+ swrOptions
285
+ );
286
+ }
287
+ function usePostsPaginated(config, page = 1, perPage = 9, filter, swrOptions) {
288
+ const key = ["wp-posts-paginated", config.clientURL, page, perPage, JSON.stringify(filter ?? null)];
289
+ return useSWR2(
290
+ key,
291
+ () => {
292
+ const fetcher = createFetcher(config);
293
+ return createPostsQueries(fetcher).getPostsPaginated(page, perPage, filter);
294
+ },
295
+ swrOptions
296
+ );
297
+ }
298
+
299
+ // src/integrations/restApi/woocommerce/client/fetcher.ts
300
+ var USER_AGENT2 = "NextWordpress WooCommerce Client";
301
+ var DEFAULT_CACHE_TTL = 3600;
302
+ function toQueryString(params) {
303
+ const pairs = [];
304
+ for (const [key, value] of Object.entries(params)) {
305
+ if (value === void 0 || value === null) continue;
306
+ pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
307
+ }
308
+ return pairs.join("&");
309
+ }
310
+ function createWooCommerceFetcher(config) {
311
+ const cacheTTL = config.cacheTTL ?? DEFAULT_CACHE_TTL;
312
+ function withAuth(query) {
313
+ return { ...query, consumer_key: config.consumerKey, consumer_secret: config.consumerSecret };
314
+ }
315
+ function buildUrl2(path, query) {
316
+ return `${config.serverURL}${path}?${toQueryString(withAuth(query))}`;
317
+ }
318
+ async function wcFetch(path, query, tags = ["woocommerce"], options) {
319
+ const url = buildUrl2(path, query);
320
+ const isMutation = options?.method && options.method !== "GET";
321
+ const noStore = options?.cache === "no-store";
322
+ const response = await fetch(url, {
323
+ ...options,
324
+ headers: {
325
+ "User-Agent": USER_AGENT2,
326
+ "Content-Type": "application/json",
327
+ ...options?.headers
328
+ },
329
+ next: isMutation || noStore ? void 0 : { tags, revalidate: cacheTTL }
330
+ });
331
+ if (!response.ok) {
332
+ const body = await response.json().catch(() => ({}));
333
+ const detail = body.message ? ` \u2013 ${body.message}` : "";
334
+ throw new Error(`WooCommerce API ${response.status}: ${response.statusText}${detail} [${url}]`);
335
+ }
336
+ return response.json();
337
+ }
338
+ async function wcFetchGraceful(path, fallback, query, tags = ["woocommerce"]) {
339
+ try {
340
+ return await wcFetch(path, query, tags);
341
+ } catch (err) {
342
+ console.warn(`WooCommerce fetch failed for ${path}`, err);
343
+ return fallback;
344
+ }
345
+ }
346
+ async function wcFetchPaginated(path, query, tags = ["woocommerce"]) {
347
+ const url = buildUrl2(path, query);
348
+ const response = await fetch(url, {
349
+ headers: { "User-Agent": USER_AGENT2 },
350
+ next: { tags, revalidate: cacheTTL }
351
+ });
352
+ if (!response.ok) {
353
+ throw new Error(`WooCommerce API ${response.status}: ${response.statusText} [${url}]`);
354
+ }
355
+ return {
356
+ data: await response.json(),
357
+ headers: {
358
+ total: parseInt(response.headers.get("X-WP-Total") ?? "0", 10),
359
+ totalPages: parseInt(response.headers.get("X-WP-TotalPages") ?? "0", 10)
360
+ }
361
+ };
362
+ }
363
+ async function wcFetchPaginatedGraceful(path, query, tags = ["woocommerce"]) {
364
+ const empty = { data: [], headers: { total: 0, totalPages: 0 } };
365
+ try {
366
+ return await wcFetchPaginated(path, query, tags);
367
+ } catch (err) {
368
+ console.warn(`WooCommerce paginated fetch failed for ${path}`, err);
369
+ return empty;
370
+ }
371
+ }
372
+ async function wcMutate(path, body, method = "POST") {
373
+ return wcFetch(path, void 0, ["woocommerce"], {
374
+ method,
375
+ body: JSON.stringify(body)
376
+ });
377
+ }
378
+ return { wcFetch, wcFetchGraceful, wcFetchPaginated, wcFetchPaginatedGraceful, wcMutate };
379
+ }
380
+
381
+ // src/integrations/restApi/woocommerce/products/queries.ts
382
+ function buildProductQuery(base, filterParams) {
383
+ const query = { ...base };
384
+ if (!filterParams) return query;
385
+ if (filterParams.category !== void 0) query.category = filterParams.category;
386
+ if (filterParams.tag !== void 0) query.tag = filterParams.tag;
387
+ if (filterParams.featured !== void 0) query.featured = filterParams.featured;
388
+ if (filterParams.on_sale !== void 0) query.on_sale = filterParams.on_sale;
389
+ if (filterParams.min_price !== void 0) query.min_price = filterParams.min_price;
390
+ if (filterParams.max_price !== void 0) query.max_price = filterParams.max_price;
391
+ if (filterParams.search !== void 0) query.search = filterParams.search;
392
+ if (filterParams.orderby !== void 0) query.orderby = filterParams.orderby;
393
+ if (filterParams.order !== void 0) query.order = filterParams.order;
394
+ if (filterParams.stock_status !== void 0) query.stock_status = filterParams.stock_status;
395
+ if (filterParams.type !== void 0) query.type = filterParams.type;
396
+ return query;
397
+ }
398
+ function createProductsQueries(fetcher) {
399
+ const { wcFetch, wcFetchGraceful, wcFetchPaginated, wcFetchPaginatedGraceful } = fetcher;
400
+ async function getProducts(filterParams) {
401
+ const query = buildProductQuery({ per_page: 100, status: "publish" }, filterParams);
402
+ return wcFetchGraceful("/wp-json/wc/v3/products", [], query, [
403
+ "woocommerce",
404
+ "products"
405
+ ]);
406
+ }
407
+ async function getProductsPaginated(page = 1, perPage = 12, filterParams) {
408
+ const query = buildProductQuery({ per_page: perPage, page, status: "publish" }, filterParams);
409
+ const cacheTags = ["woocommerce", "products", `products-page-${page}`];
410
+ if (filterParams?.category) cacheTags.push(`products-category-${filterParams.category}`);
411
+ if (filterParams?.tag) cacheTags.push(`products-tag-${filterParams.tag}`);
412
+ if (filterParams?.search) cacheTags.push("products-search");
413
+ return wcFetchPaginatedGraceful("/wp-json/wc/v3/products", query, cacheTags);
414
+ }
415
+ async function getProductById(id) {
416
+ return wcFetch(`/wp-json/wc/v3/products/${id}`, void 0, [
417
+ "woocommerce",
418
+ "products",
419
+ `product-${id}`
420
+ ]);
421
+ }
422
+ async function getProductBySlug(slug) {
423
+ const products = await wcFetchGraceful(
424
+ "/wp-json/wc/v3/products",
425
+ [],
426
+ { slug },
427
+ ["woocommerce", "products", `product-slug-${slug}`]
428
+ );
429
+ return products[0];
430
+ }
431
+ async function getFeaturedProducts(limit = 10) {
432
+ return wcFetchGraceful(
433
+ "/wp-json/wc/v3/products",
434
+ [],
435
+ { featured: true, per_page: limit, status: "publish" },
436
+ ["woocommerce", "products", "featured"]
437
+ );
438
+ }
439
+ async function getOnSaleProducts(limit = 10) {
440
+ return wcFetchGraceful(
441
+ "/wp-json/wc/v3/products",
442
+ [],
443
+ { on_sale: true, per_page: limit, status: "publish" },
444
+ ["woocommerce", "products", "on-sale"]
445
+ );
446
+ }
447
+ async function getRelatedProducts(productId) {
448
+ const product = await getProductById(productId);
449
+ if (!product.related_ids.length) return [];
450
+ return wcFetchGraceful(
451
+ "/wp-json/wc/v3/products",
452
+ [],
453
+ { include: product.related_ids.join(","), per_page: 10, status: "publish" },
454
+ ["woocommerce", "products", `related-${productId}`]
455
+ );
456
+ }
457
+ async function getAllProductSlugs() {
458
+ try {
459
+ const allSlugs = [];
460
+ let page = 1;
461
+ let hasMore = true;
462
+ while (hasMore) {
463
+ const response = await wcFetchPaginated("/wp-json/wc/v3/products", {
464
+ per_page: 100,
465
+ page,
466
+ status: "publish",
467
+ _fields: "slug"
468
+ });
469
+ allSlugs.push(...response.data.map((p) => ({ slug: p.slug })));
470
+ hasMore = page < response.headers.totalPages;
471
+ page++;
472
+ }
473
+ return allSlugs;
474
+ } catch {
475
+ console.warn("WooCommerce unavailable, skipping static generation for products");
476
+ return [];
477
+ }
478
+ }
479
+ async function getProductVariations(productId) {
480
+ return wcFetchGraceful(
481
+ `/wp-json/wc/v3/products/${productId}/variations`,
482
+ [],
483
+ { per_page: 100 },
484
+ ["woocommerce", "products", `product-${productId}`, "variations"]
485
+ );
486
+ }
487
+ async function getProductVariationById(productId, variationId) {
488
+ return wcFetch(
489
+ `/wp-json/wc/v3/products/${productId}/variations/${variationId}`,
490
+ void 0,
491
+ ["woocommerce", "products", `product-${productId}`, `variation-${variationId}`]
492
+ );
493
+ }
494
+ return {
495
+ getProducts,
496
+ getProductsPaginated,
497
+ getProductById,
498
+ getProductBySlug,
499
+ getFeaturedProducts,
500
+ getOnSaleProducts,
501
+ getRelatedProducts,
502
+ getAllProductSlugs,
503
+ getProductVariations,
504
+ getProductVariationById
505
+ };
506
+ }
507
+
508
+ // src/hooks/useProducts.ts
509
+ function useProducts(config, filter, swrOptions) {
510
+ const key = ["wc-products", config.serverURL, JSON.stringify(filter ?? null)];
511
+ return useSWR2(
512
+ key,
513
+ () => {
514
+ const fetcher = createWooCommerceFetcher(config);
515
+ return createProductsQueries(fetcher).getProducts(filter);
516
+ },
517
+ swrOptions
518
+ );
519
+ }
520
+ function useProduct(config, id, swrOptions) {
521
+ const key = id != null ? ["wc-product", config.serverURL, id] : null;
522
+ return useSWR2(
523
+ key,
524
+ () => {
525
+ const fetcher = createWooCommerceFetcher(config);
526
+ return createProductsQueries(fetcher).getProductById(id);
527
+ },
528
+ swrOptions
529
+ );
530
+ }
531
+ function useProductBySlug(config, slug, swrOptions) {
532
+ const key = slug ? ["wc-product-slug", config.serverURL, slug] : null;
533
+ return useSWR2(
534
+ key,
535
+ () => {
536
+ const fetcher = createWooCommerceFetcher(config);
537
+ return createProductsQueries(fetcher).getProductBySlug(slug);
538
+ },
539
+ swrOptions
540
+ );
541
+ }
542
+ function useProductsPaginated(config, page = 1, perPage = 12, filter, swrOptions) {
543
+ const key = ["wc-products-paginated", config.serverURL, page, perPage, JSON.stringify(filter ?? null)];
544
+ return useSWR2(
545
+ key,
546
+ () => {
547
+ const fetcher = createWooCommerceFetcher(config);
548
+ return createProductsQueries(fetcher).getProductsPaginated(page, perPage, filter);
549
+ },
550
+ swrOptions
551
+ );
552
+ }
553
+ function useFeaturedProducts(config, limit = 10, swrOptions) {
554
+ const key = ["wc-products-featured", config.serverURL, limit];
555
+ return useSWR2(
556
+ key,
557
+ () => {
558
+ const fetcher = createWooCommerceFetcher(config);
559
+ return createProductsQueries(fetcher).getFeaturedProducts(limit);
560
+ },
561
+ swrOptions
562
+ );
563
+ }
564
+
565
+ // src/integrations/wpGraphQL/client/types.ts
566
+ var WPGraphQLError = class extends Error {
567
+ constructor(message, status, endpoint, gqlErrors) {
568
+ super(message);
569
+ __publicField(this, "status", status);
570
+ __publicField(this, "endpoint", endpoint);
571
+ __publicField(this, "gqlErrors", gqlErrors);
572
+ this.name = "WPGraphQLError";
573
+ }
574
+ };
575
+
576
+ // src/integrations/wpGraphQL/client/fetcher.ts
577
+ var USER_AGENT3 = "NextWordpress WPGraphQL Client";
578
+ var CACHE_TTL = 300;
579
+ function createWPGraphQLFetcher(config) {
580
+ const url = `${resolveBaseUrl(config)}/graphql`;
581
+ async function gqlFetch(document, variables, tags = ["wpgraphql"]) {
582
+ const response = await fetch(url, {
583
+ method: "POST",
584
+ headers: {
585
+ "Content-Type": "application/json",
586
+ "User-Agent": USER_AGENT3
587
+ },
588
+ body: JSON.stringify({ query: document, variables }),
589
+ next: { tags, revalidate: CACHE_TTL }
590
+ });
591
+ if (!response.ok) {
592
+ throw new WPGraphQLError(
593
+ `WPGraphQL request failed: ${response.statusText}`,
594
+ response.status,
595
+ url
596
+ );
597
+ }
598
+ const parsed = await response.json();
599
+ if (parsed.errors && parsed.errors.length > 0) {
600
+ throw new WPGraphQLError(
601
+ parsed.errors[0].message,
602
+ 200,
603
+ url,
604
+ parsed.errors
605
+ );
606
+ }
607
+ if (parsed.data === void 0) {
608
+ throw new WPGraphQLError("No data returned from WPGraphQL", 200, url);
609
+ }
610
+ return parsed.data;
611
+ }
612
+ async function gqlFetchGraceful(document, fallback, variables, tags = ["wpgraphql"]) {
613
+ try {
614
+ return await gqlFetch(document, variables, tags);
615
+ } catch {
616
+ console.warn(`WPGraphQL fetch failed for query`);
617
+ return fallback;
618
+ }
619
+ }
620
+ async function gqlMutate(document, variables, authToken) {
621
+ const headers = {
622
+ "Content-Type": "application/json",
623
+ "User-Agent": USER_AGENT3
624
+ };
625
+ if (authToken) {
626
+ headers["Authorization"] = authToken;
627
+ }
628
+ const response = await fetch(url, {
629
+ method: "POST",
630
+ headers,
631
+ body: JSON.stringify({ query: document, variables }),
632
+ cache: "no-store"
633
+ });
634
+ if (!response.ok) {
635
+ throw new WPGraphQLError(
636
+ `WPGraphQL mutation failed: ${response.statusText}`,
637
+ response.status,
638
+ url
639
+ );
640
+ }
641
+ const parsed = await response.json();
642
+ if (parsed.errors && parsed.errors.length > 0) {
643
+ throw new WPGraphQLError(
644
+ parsed.errors[0].message,
645
+ 200,
646
+ url,
647
+ parsed.errors
648
+ );
649
+ }
650
+ if (parsed.data === void 0) {
651
+ throw new WPGraphQLError("No data returned from WPGraphQL mutation", 200, url);
652
+ }
653
+ return parsed.data;
654
+ }
655
+ return { gqlFetch, gqlFetchGraceful, gqlMutate };
656
+ }
657
+
658
+ // src/integrations/wpGraphQL/core/posts/queries.ts
659
+ var DEFAULT_FIRST = 10;
660
+ var BATCH_FIRST = 100;
661
+ var POST_FIELDS = `
662
+ id
663
+ databaseId
664
+ slug
665
+ title
666
+ excerpt
667
+ date
668
+ modified
669
+ status
670
+ uri
671
+ author {
672
+ node {
673
+ databaseId
674
+ name
675
+ slug
676
+ avatar { url }
677
+ }
678
+ }
679
+ featuredImage {
680
+ node {
681
+ sourceUrl
682
+ altText
683
+ mediaDetails { width height }
684
+ }
685
+ }
686
+ categories {
687
+ nodes { databaseId name slug }
688
+ }
689
+ tags {
690
+ nodes { databaseId name slug }
691
+ }
692
+ `;
693
+ var POST_FIELDS_WITH_CONTENT = `
694
+ ${POST_FIELDS}
695
+ content
696
+ `;
697
+ var GQL_GET_POSTS = `
698
+ query GetPosts($first: Int, $after: String, $where: RootQueryToPostConnectionWhereArgs) {
699
+ posts(first: $first, after: $after, where: $where) {
700
+ nodes { ${POST_FIELDS} }
701
+ pageInfo { hasNextPage hasPreviousPage startCursor endCursor }
702
+ }
703
+ }
704
+ `;
705
+ var GQL_GET_POST_BY_SLUG = `
706
+ query GetPostBySlug($slug: ID!) {
707
+ post(id: $slug, idType: SLUG) { ${POST_FIELDS_WITH_CONTENT} }
708
+ }
709
+ `;
710
+ var GQL_GET_POST_BY_DATABASE_ID = `
711
+ query GetPostByDatabaseId($id: ID!) {
712
+ post(id: $id, idType: DATABASE_ID) { ${POST_FIELDS_WITH_CONTENT} }
713
+ }
714
+ `;
715
+ var GQL_GET_ALL_POST_SLUGS = `
716
+ query GetAllPostSlugs($first: Int, $after: String) {
717
+ posts(first: $first, after: $after) {
718
+ nodes { slug }
719
+ pageInfo { hasNextPage endCursor }
720
+ }
721
+ }
722
+ `;
723
+ var GQL_GET_ALL_POSTS_FOR_SITEMAP = `
724
+ query GetAllPostsForSitemap($first: Int, $after: String) {
725
+ posts(first: $first, after: $after) {
726
+ nodes { slug modified }
727
+ pageInfo { hasNextPage endCursor }
728
+ }
729
+ }
730
+ `;
731
+ function createPostsQueries2(fetcher) {
732
+ const { gqlFetch, gqlFetchGraceful } = fetcher;
733
+ async function getPosts(first = DEFAULT_FIRST, after, filter) {
734
+ const where = {};
735
+ if (filter?.authorName) where["authorName"] = filter.authorName;
736
+ if (filter?.categoryName) where["categoryName"] = filter.categoryName;
737
+ if (filter?.tag) where["tag"] = filter.tag;
738
+ if (filter?.search) where["search"] = filter.search;
739
+ if (filter?.status) where["status"] = filter.status;
740
+ const data = await gqlFetchGraceful(
741
+ GQL_GET_POSTS,
742
+ { posts: { nodes: [], pageInfo: { hasNextPage: false, hasPreviousPage: false } } },
743
+ { first, after, where: Object.keys(where).length > 0 ? where : void 0 },
744
+ ["wpgraphql", "gql-posts"]
745
+ );
746
+ return data.posts;
747
+ }
748
+ async function getPostBySlug(slug) {
749
+ const data = await gqlFetchGraceful(
750
+ GQL_GET_POST_BY_SLUG,
751
+ { post: null },
752
+ { slug },
753
+ ["wpgraphql", "gql-posts", `gql-post-${slug}`]
754
+ );
755
+ return data.post;
756
+ }
757
+ async function getPostByDatabaseId(id) {
758
+ const data = await gqlFetchGraceful(
759
+ GQL_GET_POST_BY_DATABASE_ID,
760
+ { post: null },
761
+ { id: String(id) },
762
+ ["wpgraphql", "gql-posts", `gql-post-id-${id}`]
763
+ );
764
+ return data.post;
765
+ }
766
+ async function getRecentPosts(first = DEFAULT_FIRST) {
767
+ const connection = await getPosts(first);
768
+ return connection.nodes;
769
+ }
770
+ async function getAllPostSlugs() {
771
+ try {
772
+ const all = [];
773
+ let after = void 0;
774
+ let hasNextPage = true;
775
+ while (hasNextPage) {
776
+ const data = await gqlFetch(GQL_GET_ALL_POST_SLUGS, { first: BATCH_FIRST, after }, ["wpgraphql"]);
777
+ all.push(...data.posts.nodes);
778
+ hasNextPage = data.posts.pageInfo.hasNextPage;
779
+ after = data.posts.pageInfo.endCursor;
780
+ }
781
+ return all;
782
+ } catch {
783
+ console.warn("WPGraphQL unavailable, skipping static generation for posts");
784
+ return [];
785
+ }
786
+ }
787
+ async function getAllPostsForSitemap() {
788
+ try {
789
+ const all = [];
790
+ let after = void 0;
791
+ let hasNextPage = true;
792
+ while (hasNextPage) {
793
+ const data = await gqlFetch(
794
+ GQL_GET_ALL_POSTS_FOR_SITEMAP,
795
+ { first: BATCH_FIRST, after },
796
+ ["wpgraphql"]
797
+ );
798
+ all.push(...data.posts.nodes);
799
+ hasNextPage = data.posts.pageInfo.hasNextPage;
800
+ after = data.posts.pageInfo.endCursor;
801
+ }
802
+ return all;
803
+ } catch {
804
+ console.warn("WPGraphQL unavailable, skipping sitemap generation");
805
+ return [];
806
+ }
807
+ }
808
+ return {
809
+ getPosts,
810
+ getPostBySlug,
811
+ getPostByDatabaseId,
812
+ getRecentPosts,
813
+ getAllPostSlugs,
814
+ getAllPostsForSitemap
815
+ };
816
+ }
817
+
818
+ // src/hooks/useWPGraphQL.ts
819
+ function useWPGraphQL(config, query, variables, tags, swrOptions) {
820
+ const key = ["wpgraphql", config.clientURL, query, JSON.stringify(variables ?? null)];
821
+ return useSWR2(
822
+ key,
823
+ () => {
824
+ const fetcher = createWPGraphQLFetcher(config);
825
+ return fetcher.gqlFetch(query, variables, tags);
826
+ },
827
+ swrOptions
828
+ );
829
+ }
830
+ function useGQLPosts(config, first, after, filter, swrOptions) {
831
+ const key = ["wpgraphql-posts", config.clientURL, first, after, JSON.stringify(filter ?? null)];
832
+ return useSWR2(
833
+ key,
834
+ () => {
835
+ const fetcher = createWPGraphQLFetcher(config);
836
+ return createPostsQueries2(fetcher).getPosts(first, after, filter);
837
+ },
838
+ swrOptions
839
+ );
840
+ }
841
+ function useGQLPostBySlug(config, slug, swrOptions) {
842
+ const key = slug ? ["wpgraphql-post-slug", config.clientURL, slug] : null;
843
+ return useSWR2(
844
+ key,
845
+ () => {
846
+ const fetcher = createWPGraphQLFetcher(config);
847
+ return createPostsQueries2(fetcher).getPostBySlug(slug);
848
+ },
849
+ swrOptions
850
+ );
851
+ }
852
+
853
+ export { useFeaturedProducts, useGQLPostBySlug, useGQLPosts, usePost, usePostBySlug, usePosts, usePostsPaginated, useProduct, useProductBySlug, useProducts, useProductsPaginated, useWPGraphQL };
854
+ //# sourceMappingURL=index.js.map
855
+ //# sourceMappingURL=index.js.map