@szymonpiatek/nextwordpress 0.0.10 → 0.0.11
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.
- package/dist/client/index.cjs +1372 -0
- package/dist/client/index.cjs.map +1 -0
- package/dist/client/index.d.cts +4 -0
- package/dist/client/index.d.ts +4 -0
- package/dist/client/index.js +1348 -0
- package/dist/client/index.js.map +1 -0
- package/dist/server/index.cjs +4274 -0
- package/dist/server/index.cjs.map +1 -0
- package/dist/server/index.d.cts +2 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +4231 -0
- package/dist/server/index.js.map +1 -0
- package/package.json +11 -1
|
@@ -0,0 +1,1372 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var react = require('react');
|
|
4
|
+
var jsxRuntime = require('react/jsx-runtime');
|
|
5
|
+
var useSWR2 = require('swr');
|
|
6
|
+
|
|
7
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
8
|
+
|
|
9
|
+
var useSWR2__default = /*#__PURE__*/_interopDefault(useSWR2);
|
|
10
|
+
|
|
11
|
+
var __defProp = Object.defineProperty;
|
|
12
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
13
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
14
|
+
|
|
15
|
+
// src/shared/url.ts
|
|
16
|
+
function resolveBaseUrl(config) {
|
|
17
|
+
return typeof window === "undefined" ? config.serverURL : config.clientURL;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// src/shared/errors/codes.ts
|
|
21
|
+
var ErrorCode = {
|
|
22
|
+
// WordPress REST API
|
|
23
|
+
WP_REQUEST_FAILED: "WP_REQUEST_FAILED",
|
|
24
|
+
WP_NOT_FOUND: "WP_NOT_FOUND",
|
|
25
|
+
WP_UNAUTHORIZED: "WP_UNAUTHORIZED",
|
|
26
|
+
WP_FORBIDDEN: "WP_FORBIDDEN",
|
|
27
|
+
// WPGraphQL
|
|
28
|
+
GQL_REQUEST_FAILED: "GQL_REQUEST_FAILED",
|
|
29
|
+
GQL_NO_DATA: "GQL_NO_DATA",
|
|
30
|
+
GQL_ERRORS_IN_RESPONSE: "GQL_ERRORS_IN_RESPONSE",
|
|
31
|
+
// WooCommerce — generic
|
|
32
|
+
WOO_REQUEST_FAILED: "WOO_REQUEST_FAILED",
|
|
33
|
+
WOO_NOT_FOUND: "WOO_NOT_FOUND",
|
|
34
|
+
WOO_UNAUTHORIZED: "WOO_UNAUTHORIZED",
|
|
35
|
+
WOO_FORBIDDEN: "WOO_FORBIDDEN",
|
|
36
|
+
// WooCommerce — resource-specific
|
|
37
|
+
WOO_COUPON_NOT_FOUND: "WOO_COUPON_NOT_FOUND",
|
|
38
|
+
WOO_PRODUCT_NOT_FOUND: "WOO_PRODUCT_NOT_FOUND",
|
|
39
|
+
WOO_ORDER_NOT_FOUND: "WOO_ORDER_NOT_FOUND",
|
|
40
|
+
WOO_CUSTOMER_NOT_FOUND: "WOO_CUSTOMER_NOT_FOUND",
|
|
41
|
+
WOO_CATEGORY_NOT_FOUND: "WOO_CATEGORY_NOT_FOUND",
|
|
42
|
+
WOO_REVIEW_NOT_FOUND: "WOO_REVIEW_NOT_FOUND",
|
|
43
|
+
WOO_WEBHOOK_NOT_FOUND: "WOO_WEBHOOK_NOT_FOUND",
|
|
44
|
+
WOO_SHIPPING_ZONE_NOT_FOUND: "WOO_SHIPPING_ZONE_NOT_FOUND",
|
|
45
|
+
// Auth
|
|
46
|
+
AUTH_JWT_FAILED: "AUTH_JWT_FAILED",
|
|
47
|
+
AUTH_CREDENTIALS_INVALID: "AUTH_CREDENTIALS_INVALID",
|
|
48
|
+
AUTH_TOKEN_INVALID: "AUTH_TOKEN_INVALID"
|
|
49
|
+
};
|
|
50
|
+
var defaultMessages = {
|
|
51
|
+
WP_REQUEST_FAILED: "WordPress API request failed",
|
|
52
|
+
WP_NOT_FOUND: "WordPress resource not found",
|
|
53
|
+
WP_UNAUTHORIZED: "WordPress authentication required",
|
|
54
|
+
WP_FORBIDDEN: "WordPress access denied",
|
|
55
|
+
GQL_REQUEST_FAILED: "WPGraphQL request failed",
|
|
56
|
+
GQL_NO_DATA: "No data returned from WPGraphQL",
|
|
57
|
+
GQL_ERRORS_IN_RESPONSE: "WPGraphQL returned errors",
|
|
58
|
+
WOO_REQUEST_FAILED: "WooCommerce API request failed",
|
|
59
|
+
WOO_NOT_FOUND: "WooCommerce resource not found",
|
|
60
|
+
WOO_UNAUTHORIZED: "WooCommerce authentication required",
|
|
61
|
+
WOO_FORBIDDEN: "WooCommerce access denied",
|
|
62
|
+
WOO_COUPON_NOT_FOUND: "Coupon not found",
|
|
63
|
+
WOO_PRODUCT_NOT_FOUND: "Product not found",
|
|
64
|
+
WOO_ORDER_NOT_FOUND: "Order not found",
|
|
65
|
+
WOO_CUSTOMER_NOT_FOUND: "Customer not found",
|
|
66
|
+
WOO_CATEGORY_NOT_FOUND: "Category not found",
|
|
67
|
+
WOO_TAG_NOT_FOUND: "Tag not found",
|
|
68
|
+
WOO_REVIEW_NOT_FOUND: "Product review not found",
|
|
69
|
+
WOO_WEBHOOK_NOT_FOUND: "Webhook not found",
|
|
70
|
+
WOO_SHIPPING_ZONE_NOT_FOUND: "Shipping zone not found",
|
|
71
|
+
AUTH_JWT_FAILED: "JWT authentication failed",
|
|
72
|
+
AUTH_CREDENTIALS_INVALID: "Invalid credentials",
|
|
73
|
+
AUTH_TOKEN_INVALID: "JWT token is invalid or expired"
|
|
74
|
+
};
|
|
75
|
+
function resolveMessage(code, overrides) {
|
|
76
|
+
return overrides?.[code] ?? defaultMessages[code];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/auth/types.ts
|
|
80
|
+
var AuthenticationError = class extends Error {
|
|
81
|
+
constructor(code, status, message, detail) {
|
|
82
|
+
super(detail ? `${message}: ${detail}` : message);
|
|
83
|
+
__publicField(this, "code", code);
|
|
84
|
+
__publicField(this, "status", status);
|
|
85
|
+
this.name = "AuthenticationError";
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
// src/auth/jwt.ts
|
|
90
|
+
function resolveAuthErrorCode(status) {
|
|
91
|
+
if (status === 401) return ErrorCode.AUTH_CREDENTIALS_INVALID;
|
|
92
|
+
if (status === 403) return ErrorCode.AUTH_TOKEN_INVALID;
|
|
93
|
+
return ErrorCode.AUTH_JWT_FAILED;
|
|
94
|
+
}
|
|
95
|
+
async function authenticateJwt(config, credentials) {
|
|
96
|
+
const url = `${resolveBaseUrl(config)}/wp-json/jwt-auth/v1/token`;
|
|
97
|
+
const response = await fetch(url, {
|
|
98
|
+
method: "POST",
|
|
99
|
+
headers: { "Content-Type": "application/json" },
|
|
100
|
+
body: JSON.stringify(credentials),
|
|
101
|
+
cache: "no-store"
|
|
102
|
+
});
|
|
103
|
+
if (!response.ok) {
|
|
104
|
+
const code = resolveAuthErrorCode(response.status);
|
|
105
|
+
throw new AuthenticationError(
|
|
106
|
+
code,
|
|
107
|
+
response.status,
|
|
108
|
+
resolveMessage(code, config.errorMessages),
|
|
109
|
+
response.statusText
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
return response.json();
|
|
113
|
+
}
|
|
114
|
+
async function validateJwtToken(config, token) {
|
|
115
|
+
const url = `${resolveBaseUrl(config)}/wp-json/jwt-auth/v1/token/validate`;
|
|
116
|
+
const response = await fetch(url, {
|
|
117
|
+
method: "POST",
|
|
118
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
119
|
+
cache: "no-store"
|
|
120
|
+
});
|
|
121
|
+
return response.ok;
|
|
122
|
+
}
|
|
123
|
+
var AuthContext = react.createContext(null);
|
|
124
|
+
var TOKEN_KEY = "nw_auth_token";
|
|
125
|
+
var USER_KEY = "nw_auth_user";
|
|
126
|
+
function AuthProvider({
|
|
127
|
+
config,
|
|
128
|
+
children
|
|
129
|
+
}) {
|
|
130
|
+
const [user, setUser] = react.useState(null);
|
|
131
|
+
const [isLoading, setIsLoading] = react.useState(true);
|
|
132
|
+
const [error, setError] = react.useState(null);
|
|
133
|
+
const clearStorage = react.useCallback(() => {
|
|
134
|
+
localStorage.removeItem(TOKEN_KEY);
|
|
135
|
+
localStorage.removeItem(USER_KEY);
|
|
136
|
+
}, []);
|
|
137
|
+
react.useEffect(() => {
|
|
138
|
+
const token = localStorage.getItem(TOKEN_KEY);
|
|
139
|
+
const storedUser = localStorage.getItem(USER_KEY);
|
|
140
|
+
if (!token || !storedUser) {
|
|
141
|
+
setIsLoading(false);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
validateJwtToken(config, token).then((valid) => {
|
|
145
|
+
if (valid) {
|
|
146
|
+
setUser(JSON.parse(storedUser));
|
|
147
|
+
} else {
|
|
148
|
+
clearStorage();
|
|
149
|
+
}
|
|
150
|
+
}).catch(() => clearStorage()).finally(() => setIsLoading(false));
|
|
151
|
+
}, []);
|
|
152
|
+
const login = async (credentials) => {
|
|
153
|
+
setError(null);
|
|
154
|
+
setIsLoading(true);
|
|
155
|
+
try {
|
|
156
|
+
const response = await authenticateJwt(config, credentials);
|
|
157
|
+
const authUser = {
|
|
158
|
+
token: response.token,
|
|
159
|
+
email: response.user_email,
|
|
160
|
+
nicename: response.user_nicename,
|
|
161
|
+
displayName: response.user_display_name
|
|
162
|
+
};
|
|
163
|
+
localStorage.setItem(TOKEN_KEY, response.token);
|
|
164
|
+
localStorage.setItem(USER_KEY, JSON.stringify(authUser));
|
|
165
|
+
setUser(authUser);
|
|
166
|
+
} catch (err) {
|
|
167
|
+
const message = err instanceof Error ? err.message : "Authentication failed";
|
|
168
|
+
setError(message);
|
|
169
|
+
throw err;
|
|
170
|
+
} finally {
|
|
171
|
+
setIsLoading(false);
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
const logout = () => {
|
|
175
|
+
clearStorage();
|
|
176
|
+
setUser(null);
|
|
177
|
+
setError(null);
|
|
178
|
+
};
|
|
179
|
+
return /* @__PURE__ */ jsxRuntime.jsx(AuthContext.Provider, { value: { user, isLoggedIn: !!user, isLoading, error, login, logout }, children });
|
|
180
|
+
}
|
|
181
|
+
function useAuth() {
|
|
182
|
+
const ctx = react.useContext(AuthContext);
|
|
183
|
+
if (!ctx) throw new Error("useAuth must be used within an AuthProvider");
|
|
184
|
+
return ctx;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// src/integrations/restApi/core/client/types.ts
|
|
188
|
+
var WordPressAPIError = class extends Error {
|
|
189
|
+
constructor(code, status, endpoint, message, detail) {
|
|
190
|
+
super(detail ? `${message}: ${detail}` : message);
|
|
191
|
+
__publicField(this, "code", code);
|
|
192
|
+
__publicField(this, "status", status);
|
|
193
|
+
__publicField(this, "endpoint", endpoint);
|
|
194
|
+
this.name = "WordPressAPIError";
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
// src/integrations/restApi/core/client/url.ts
|
|
199
|
+
function buildUrl(config, path, query) {
|
|
200
|
+
const base = resolveBaseUrl(config);
|
|
201
|
+
if (!query) return `${base}${path}`;
|
|
202
|
+
const params = new URLSearchParams();
|
|
203
|
+
for (const [key, value] of Object.entries(query)) {
|
|
204
|
+
if (value !== void 0 && value !== null) {
|
|
205
|
+
params.set(key, String(value));
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const qs = params.toString();
|
|
209
|
+
return qs ? `${base}${path}?${qs}` : `${base}${path}`;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// src/integrations/restApi/core/client/fetcher.ts
|
|
213
|
+
var USER_AGENT = "NextWordpress Client";
|
|
214
|
+
function resolveWpErrorCode(status) {
|
|
215
|
+
if (status === 401) return ErrorCode.WP_UNAUTHORIZED;
|
|
216
|
+
if (status === 403) return ErrorCode.WP_FORBIDDEN;
|
|
217
|
+
if (status === 404) return ErrorCode.WP_NOT_FOUND;
|
|
218
|
+
return ErrorCode.WP_REQUEST_FAILED;
|
|
219
|
+
}
|
|
220
|
+
function createFetcher(config) {
|
|
221
|
+
const cacheTtl = config.cacheTTL ?? 300;
|
|
222
|
+
async function doFetch(url, init = {}) {
|
|
223
|
+
const response = await fetch(url, init);
|
|
224
|
+
if (!response.ok) {
|
|
225
|
+
const code = resolveWpErrorCode(response.status);
|
|
226
|
+
throw new WordPressAPIError(
|
|
227
|
+
code,
|
|
228
|
+
response.status,
|
|
229
|
+
url,
|
|
230
|
+
resolveMessage(code, config.errorMessages),
|
|
231
|
+
response.statusText
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
return response;
|
|
235
|
+
}
|
|
236
|
+
async function wpFetch(path, query, tags = ["wordpress"]) {
|
|
237
|
+
const url = buildUrl(config, path, query);
|
|
238
|
+
const res = await doFetch(url, {
|
|
239
|
+
headers: { "User-Agent": USER_AGENT },
|
|
240
|
+
next: { tags, revalidate: cacheTtl }
|
|
241
|
+
});
|
|
242
|
+
return await res.json();
|
|
243
|
+
}
|
|
244
|
+
async function wpFetchGraceful(path, fallback, query, tags = ["wordpress"]) {
|
|
245
|
+
try {
|
|
246
|
+
return await wpFetch(path, query, tags);
|
|
247
|
+
} catch {
|
|
248
|
+
console.warn(`WordPress fetch failed for ${path}`);
|
|
249
|
+
return fallback;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
async function wpFetchPaginated(path, query, tags = ["wordpress"]) {
|
|
253
|
+
const url = buildUrl(config, path, query);
|
|
254
|
+
const res = await doFetch(url, {
|
|
255
|
+
headers: { "User-Agent": USER_AGENT },
|
|
256
|
+
next: { tags, revalidate: cacheTtl }
|
|
257
|
+
});
|
|
258
|
+
return {
|
|
259
|
+
data: await res.json(),
|
|
260
|
+
headers: {
|
|
261
|
+
total: parseInt(res.headers.get("X-WP-Total") ?? "0", 10),
|
|
262
|
+
totalPages: parseInt(res.headers.get("X-WP-TotalPages") ?? "0", 10)
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
async function wpFetchPaginatedGraceful(path, query, tags = ["wordpress"]) {
|
|
267
|
+
const empty = { data: [], headers: { total: 0, totalPages: 0 } };
|
|
268
|
+
try {
|
|
269
|
+
return await wpFetchPaginated(path, query, tags);
|
|
270
|
+
} catch {
|
|
271
|
+
console.warn(`WordPress paginated fetch failed for ${path}`);
|
|
272
|
+
return empty;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
async function wpMutate(path, body, method = "POST", authToken) {
|
|
276
|
+
const url = buildUrl(config, path);
|
|
277
|
+
const headers = {
|
|
278
|
+
"Content-Type": "application/json",
|
|
279
|
+
"User-Agent": USER_AGENT
|
|
280
|
+
};
|
|
281
|
+
if (authToken) {
|
|
282
|
+
headers["Authorization"] = authToken.startsWith("Basic ") || authToken.startsWith("Bearer ") ? authToken : `Bearer ${authToken}`;
|
|
283
|
+
}
|
|
284
|
+
const res = await doFetch(url, {
|
|
285
|
+
method,
|
|
286
|
+
headers,
|
|
287
|
+
body: JSON.stringify(body),
|
|
288
|
+
cache: "no-store"
|
|
289
|
+
});
|
|
290
|
+
return await res.json();
|
|
291
|
+
}
|
|
292
|
+
async function wpUpload(path, file, filename, mimeType, authToken) {
|
|
293
|
+
const url = buildUrl(config, path);
|
|
294
|
+
const res = await doFetch(url, {
|
|
295
|
+
method: "POST",
|
|
296
|
+
headers: {
|
|
297
|
+
"Content-Disposition": `attachment; filename="${filename}"`,
|
|
298
|
+
"Content-Type": mimeType,
|
|
299
|
+
"User-Agent": USER_AGENT,
|
|
300
|
+
"Authorization": authToken.startsWith("Basic ") || authToken.startsWith("Bearer ") ? authToken : `Bearer ${authToken}`
|
|
301
|
+
},
|
|
302
|
+
body: file,
|
|
303
|
+
cache: "no-store"
|
|
304
|
+
});
|
|
305
|
+
return await res.json();
|
|
306
|
+
}
|
|
307
|
+
return { wpFetch, wpFetchGraceful, wpFetchPaginated, wpFetchPaginatedGraceful, wpMutate, wpUpload };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// src/integrations/restApi/core/posts/queries.ts
|
|
311
|
+
function createPostsQueries(fetcher) {
|
|
312
|
+
const { wpFetch, wpFetchGraceful, wpFetchPaginated, wpFetchPaginatedGraceful } = fetcher;
|
|
313
|
+
async function getPostsPaginated(page = 1, perPage = 9, filterParams) {
|
|
314
|
+
const query = { _embed: true, per_page: perPage, page };
|
|
315
|
+
const cacheTags = ["wordpress", "posts", `posts-page-${page}`];
|
|
316
|
+
if (filterParams?.search) {
|
|
317
|
+
query.search = filterParams.search;
|
|
318
|
+
cacheTags.push("posts-search");
|
|
319
|
+
}
|
|
320
|
+
if (filterParams?.author) {
|
|
321
|
+
query.author = filterParams.author;
|
|
322
|
+
cacheTags.push(`posts-author-${filterParams.author}`);
|
|
323
|
+
}
|
|
324
|
+
if (filterParams?.tag) {
|
|
325
|
+
query.tags = filterParams.tag;
|
|
326
|
+
cacheTags.push(`posts-tag-${filterParams.tag}`);
|
|
327
|
+
}
|
|
328
|
+
if (filterParams?.category) {
|
|
329
|
+
query.categories = filterParams.category;
|
|
330
|
+
cacheTags.push(`posts-category-${filterParams.category}`);
|
|
331
|
+
}
|
|
332
|
+
return wpFetchPaginatedGraceful("/wp-json/wp/v2/posts", query, cacheTags);
|
|
333
|
+
}
|
|
334
|
+
async function getRecentPosts(filterParams) {
|
|
335
|
+
const query = { _embed: true, per_page: 100 };
|
|
336
|
+
if (filterParams?.search) query.search = filterParams.search;
|
|
337
|
+
if (filterParams?.author) query.author = filterParams.author;
|
|
338
|
+
if (filterParams?.tag) query.tags = filterParams.tag;
|
|
339
|
+
if (filterParams?.category) query.categories = filterParams.category;
|
|
340
|
+
return wpFetchGraceful("/wp-json/wp/v2/posts", [], query, ["wordpress", "posts"]);
|
|
341
|
+
}
|
|
342
|
+
async function getPostById(id) {
|
|
343
|
+
return wpFetch(`/wp-json/wp/v2/posts/${id}`);
|
|
344
|
+
}
|
|
345
|
+
async function getPostBySlug(slug) {
|
|
346
|
+
const posts = await wpFetchGraceful("/wp-json/wp/v2/posts", [], { slug, _embed: true });
|
|
347
|
+
return posts[0];
|
|
348
|
+
}
|
|
349
|
+
async function getPostsByCategory(categoryId) {
|
|
350
|
+
return wpFetch("/wp-json/wp/v2/posts", { categories: categoryId });
|
|
351
|
+
}
|
|
352
|
+
async function getPostsByTag(tagId) {
|
|
353
|
+
return wpFetch("/wp-json/wp/v2/posts", { tags: tagId });
|
|
354
|
+
}
|
|
355
|
+
async function getPostsByAuthor(authorId) {
|
|
356
|
+
return wpFetch("/wp-json/wp/v2/posts", { author: authorId });
|
|
357
|
+
}
|
|
358
|
+
async function getPostsByCategoryPaginated(categoryId, page = 1, perPage = 9) {
|
|
359
|
+
return wpFetchPaginatedGraceful("/wp-json/wp/v2/posts", {
|
|
360
|
+
_embed: true,
|
|
361
|
+
per_page: perPage,
|
|
362
|
+
page,
|
|
363
|
+
categories: categoryId
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
async function getPostsByTagPaginated(tagId, page = 1, perPage = 9) {
|
|
367
|
+
return wpFetchPaginatedGraceful("/wp-json/wp/v2/posts", {
|
|
368
|
+
_embed: true,
|
|
369
|
+
per_page: perPage,
|
|
370
|
+
page,
|
|
371
|
+
tags: tagId
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
async function getPostsByAuthorPaginated(authorId, page = 1, perPage = 9) {
|
|
375
|
+
return wpFetchPaginatedGraceful("/wp-json/wp/v2/posts", {
|
|
376
|
+
_embed: true,
|
|
377
|
+
per_page: perPage,
|
|
378
|
+
page,
|
|
379
|
+
author: authorId
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
async function getAllPostSlugs() {
|
|
383
|
+
try {
|
|
384
|
+
const allSlugs = [];
|
|
385
|
+
let page = 1;
|
|
386
|
+
let hasMore = true;
|
|
387
|
+
while (hasMore) {
|
|
388
|
+
const response = await wpFetchPaginated(
|
|
389
|
+
"/wp-json/wp/v2/posts",
|
|
390
|
+
{ per_page: 100, page, _fields: "slug" }
|
|
391
|
+
);
|
|
392
|
+
allSlugs.push(...response.data.map((post) => ({ slug: post.slug })));
|
|
393
|
+
hasMore = page < response.headers.totalPages;
|
|
394
|
+
page++;
|
|
395
|
+
}
|
|
396
|
+
return allSlugs;
|
|
397
|
+
} catch {
|
|
398
|
+
console.warn("WordPress unavailable, skipping static generation for posts");
|
|
399
|
+
return [];
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
async function getAllPostsForSitemap() {
|
|
403
|
+
try {
|
|
404
|
+
const allPosts = [];
|
|
405
|
+
let page = 1;
|
|
406
|
+
let hasMore = true;
|
|
407
|
+
while (hasMore) {
|
|
408
|
+
const response = await wpFetchPaginated(
|
|
409
|
+
"/wp-json/wp/v2/posts",
|
|
410
|
+
{ per_page: 100, page, _fields: "slug,modified" }
|
|
411
|
+
);
|
|
412
|
+
allPosts.push(...response.data.map((post) => ({ slug: post.slug, modified: post.modified })));
|
|
413
|
+
hasMore = page < response.headers.totalPages;
|
|
414
|
+
page++;
|
|
415
|
+
}
|
|
416
|
+
return allPosts;
|
|
417
|
+
} catch {
|
|
418
|
+
console.warn("WordPress unavailable, skipping sitemap generation");
|
|
419
|
+
return [];
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return {
|
|
423
|
+
getPostsPaginated,
|
|
424
|
+
getRecentPosts,
|
|
425
|
+
getPostById,
|
|
426
|
+
getPostBySlug,
|
|
427
|
+
getPostsByCategory,
|
|
428
|
+
getPostsByTag,
|
|
429
|
+
getPostsByAuthor,
|
|
430
|
+
getPostsByCategoryPaginated,
|
|
431
|
+
getPostsByTagPaginated,
|
|
432
|
+
getPostsByAuthorPaginated,
|
|
433
|
+
getAllPostSlugs,
|
|
434
|
+
getAllPostsForSitemap
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// src/hooks/core/usePosts.ts
|
|
439
|
+
function usePosts(config, filter, swrOptions) {
|
|
440
|
+
const key = ["wp-posts", config.clientURL, JSON.stringify(filter ?? null)];
|
|
441
|
+
return useSWR2__default.default(
|
|
442
|
+
key,
|
|
443
|
+
() => {
|
|
444
|
+
const fetcher = createFetcher(config);
|
|
445
|
+
return createPostsQueries(fetcher).getRecentPosts(filter);
|
|
446
|
+
},
|
|
447
|
+
swrOptions
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
function usePost(config, id, swrOptions) {
|
|
451
|
+
const key = id != null ? ["wp-post", config.clientURL, id] : null;
|
|
452
|
+
return useSWR2__default.default(
|
|
453
|
+
key,
|
|
454
|
+
() => {
|
|
455
|
+
const fetcher = createFetcher(config);
|
|
456
|
+
return createPostsQueries(fetcher).getPostById(id);
|
|
457
|
+
},
|
|
458
|
+
swrOptions
|
|
459
|
+
);
|
|
460
|
+
}
|
|
461
|
+
function usePostBySlug(config, slug, swrOptions) {
|
|
462
|
+
const key = slug ? ["wp-post-slug", config.clientURL, slug] : null;
|
|
463
|
+
return useSWR2__default.default(
|
|
464
|
+
key,
|
|
465
|
+
() => {
|
|
466
|
+
const fetcher = createFetcher(config);
|
|
467
|
+
return createPostsQueries(fetcher).getPostBySlug(slug);
|
|
468
|
+
},
|
|
469
|
+
swrOptions
|
|
470
|
+
);
|
|
471
|
+
}
|
|
472
|
+
function usePostsPaginated(config, page = 1, perPage = 9, filter, swrOptions) {
|
|
473
|
+
const key = ["wp-posts-paginated", config.clientURL, page, perPage, JSON.stringify(filter ?? null)];
|
|
474
|
+
return useSWR2__default.default(
|
|
475
|
+
key,
|
|
476
|
+
() => {
|
|
477
|
+
const fetcher = createFetcher(config);
|
|
478
|
+
return createPostsQueries(fetcher).getPostsPaginated(page, perPage, filter);
|
|
479
|
+
},
|
|
480
|
+
swrOptions
|
|
481
|
+
);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// src/integrations/restApi/woocommerce/client/types.ts
|
|
485
|
+
var WooCommerceError = class extends Error {
|
|
486
|
+
constructor(code, status, endpoint, message, upstreamCode, detail) {
|
|
487
|
+
super(detail ? `${message}: ${detail}` : message);
|
|
488
|
+
__publicField(this, "code", code);
|
|
489
|
+
__publicField(this, "status", status);
|
|
490
|
+
__publicField(this, "endpoint", endpoint);
|
|
491
|
+
__publicField(this, "upstreamCode", upstreamCode);
|
|
492
|
+
this.name = "WooCommerceError";
|
|
493
|
+
}
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
// src/integrations/restApi/woocommerce/client/errorMap.ts
|
|
497
|
+
var upstreamToErrorCode = {
|
|
498
|
+
woocommerce_rest_coupon_invalid_id: ErrorCode.WOO_COUPON_NOT_FOUND,
|
|
499
|
+
woocommerce_rest_product_invalid_id: ErrorCode.WOO_PRODUCT_NOT_FOUND,
|
|
500
|
+
woocommerce_rest_order_invalid_id: ErrorCode.WOO_ORDER_NOT_FOUND,
|
|
501
|
+
woocommerce_rest_customer_invalid_id: ErrorCode.WOO_CUSTOMER_NOT_FOUND,
|
|
502
|
+
woocommerce_rest_term_invalid: ErrorCode.WOO_CATEGORY_NOT_FOUND,
|
|
503
|
+
woocommerce_rest_review_invalid_id: ErrorCode.WOO_REVIEW_NOT_FOUND,
|
|
504
|
+
woocommerce_rest_webhook_invalid_id: ErrorCode.WOO_WEBHOOK_NOT_FOUND,
|
|
505
|
+
woocommerce_rest_shipping_zone_invalid_id: ErrorCode.WOO_SHIPPING_ZONE_NOT_FOUND
|
|
506
|
+
};
|
|
507
|
+
function resolveWooErrorCode(status, upstreamCode) {
|
|
508
|
+
if (status === 401) return ErrorCode.WOO_UNAUTHORIZED;
|
|
509
|
+
if (status === 403) return ErrorCode.WOO_FORBIDDEN;
|
|
510
|
+
if (status === 404) {
|
|
511
|
+
if (upstreamCode) {
|
|
512
|
+
const mapped = upstreamToErrorCode[upstreamCode];
|
|
513
|
+
if (mapped) return mapped;
|
|
514
|
+
}
|
|
515
|
+
return ErrorCode.WOO_NOT_FOUND;
|
|
516
|
+
}
|
|
517
|
+
return ErrorCode.WOO_REQUEST_FAILED;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// src/integrations/restApi/woocommerce/client/fetcher.ts
|
|
521
|
+
var USER_AGENT2 = "NextWordpress WooCommerce Client";
|
|
522
|
+
var DEFAULT_CACHE_TTL = 3600;
|
|
523
|
+
function toQueryString(params) {
|
|
524
|
+
const pairs = [];
|
|
525
|
+
for (const [key, value] of Object.entries(params)) {
|
|
526
|
+
if (value === void 0 || value === null) continue;
|
|
527
|
+
pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
|
|
528
|
+
}
|
|
529
|
+
return pairs.join("&");
|
|
530
|
+
}
|
|
531
|
+
function createWooCommerceFetcher(config) {
|
|
532
|
+
const cacheTTL = config.cacheTTL ?? DEFAULT_CACHE_TTL;
|
|
533
|
+
function withAuth(query) {
|
|
534
|
+
return { ...query, consumer_key: config.consumerKey, consumer_secret: config.consumerSecret };
|
|
535
|
+
}
|
|
536
|
+
function buildUrl2(path, query) {
|
|
537
|
+
const base = typeof window !== "undefined" && config.clientURL ? config.clientURL : config.serverURL;
|
|
538
|
+
return `${base}${path}?${toQueryString(withAuth(query))}`;
|
|
539
|
+
}
|
|
540
|
+
async function throwWooError(response, url) {
|
|
541
|
+
const body = await response.json().catch(() => ({}));
|
|
542
|
+
const errorCode = resolveWooErrorCode(response.status, body.code);
|
|
543
|
+
throw new WooCommerceError(
|
|
544
|
+
errorCode,
|
|
545
|
+
response.status,
|
|
546
|
+
url,
|
|
547
|
+
resolveMessage(errorCode, config.errorMessages),
|
|
548
|
+
body.code,
|
|
549
|
+
body.message
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
async function wcFetch(path, query, tags = ["woocommerce"], options) {
|
|
553
|
+
const url = buildUrl2(path, query);
|
|
554
|
+
const isMutation = options?.method && options.method !== "GET";
|
|
555
|
+
const noStore = options?.cache === "no-store";
|
|
556
|
+
const response = await fetch(url, {
|
|
557
|
+
...options,
|
|
558
|
+
headers: {
|
|
559
|
+
"User-Agent": USER_AGENT2,
|
|
560
|
+
"Content-Type": "application/json",
|
|
561
|
+
...options?.headers
|
|
562
|
+
},
|
|
563
|
+
next: isMutation || noStore ? void 0 : { tags, revalidate: cacheTTL }
|
|
564
|
+
});
|
|
565
|
+
if (!response.ok) {
|
|
566
|
+
await throwWooError(response, url);
|
|
567
|
+
}
|
|
568
|
+
return response.json();
|
|
569
|
+
}
|
|
570
|
+
async function wcFetchGraceful(path, fallback, query, tags = ["woocommerce"]) {
|
|
571
|
+
try {
|
|
572
|
+
return await wcFetch(path, query, tags);
|
|
573
|
+
} catch (err) {
|
|
574
|
+
console.warn(`WooCommerce fetch failed for ${path}`, err);
|
|
575
|
+
return fallback;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
async function wcFetchPaginated(path, query, tags = ["woocommerce"]) {
|
|
579
|
+
const url = buildUrl2(path, query);
|
|
580
|
+
const response = await fetch(url, {
|
|
581
|
+
headers: { "User-Agent": USER_AGENT2 },
|
|
582
|
+
next: { tags, revalidate: cacheTTL }
|
|
583
|
+
});
|
|
584
|
+
if (!response.ok) {
|
|
585
|
+
await throwWooError(response, url);
|
|
586
|
+
}
|
|
587
|
+
return {
|
|
588
|
+
data: await response.json(),
|
|
589
|
+
headers: {
|
|
590
|
+
total: parseInt(response.headers.get("X-WP-Total") ?? "0", 10),
|
|
591
|
+
totalPages: parseInt(response.headers.get("X-WP-TotalPages") ?? "0", 10)
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
async function wcFetchPaginatedGraceful(path, query, tags = ["woocommerce"]) {
|
|
596
|
+
const empty = { data: [], headers: { total: 0, totalPages: 0 } };
|
|
597
|
+
try {
|
|
598
|
+
return await wcFetchPaginated(path, query, tags);
|
|
599
|
+
} catch (err) {
|
|
600
|
+
console.warn(`WooCommerce paginated fetch failed for ${path}`, err);
|
|
601
|
+
return empty;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
async function wcMutate(path, body, method = "POST") {
|
|
605
|
+
return wcFetch(path, void 0, ["woocommerce"], {
|
|
606
|
+
method,
|
|
607
|
+
body: JSON.stringify(body)
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
return { wcFetch, wcFetchGraceful, wcFetchPaginated, wcFetchPaginatedGraceful, wcMutate };
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// src/integrations/restApi/woocommerce/products/queries.ts
|
|
614
|
+
function buildProductQuery(base, filterParams) {
|
|
615
|
+
const query = { ...base };
|
|
616
|
+
if (!filterParams) return query;
|
|
617
|
+
if (filterParams.category !== void 0) query.category = filterParams.category;
|
|
618
|
+
if (filterParams.tag !== void 0) query.tag = filterParams.tag;
|
|
619
|
+
if (filterParams.featured !== void 0) query.featured = filterParams.featured;
|
|
620
|
+
if (filterParams.on_sale !== void 0) query.on_sale = filterParams.on_sale;
|
|
621
|
+
if (filterParams.min_price !== void 0) query.min_price = filterParams.min_price;
|
|
622
|
+
if (filterParams.max_price !== void 0) query.max_price = filterParams.max_price;
|
|
623
|
+
if (filterParams.search !== void 0) query.search = filterParams.search;
|
|
624
|
+
if (filterParams.orderby !== void 0) query.orderby = filterParams.orderby;
|
|
625
|
+
if (filterParams.order !== void 0) query.order = filterParams.order;
|
|
626
|
+
if (filterParams.stock_status !== void 0) query.stock_status = filterParams.stock_status;
|
|
627
|
+
if (filterParams.type !== void 0) query.type = filterParams.type;
|
|
628
|
+
return query;
|
|
629
|
+
}
|
|
630
|
+
function createProductsQueries(fetcher) {
|
|
631
|
+
const { wcFetch, wcFetchGraceful, wcFetchPaginated, wcFetchPaginatedGraceful } = fetcher;
|
|
632
|
+
async function getProducts(filterParams) {
|
|
633
|
+
const query = buildProductQuery({ per_page: 100, status: "publish" }, filterParams);
|
|
634
|
+
return wcFetchGraceful("/wp-json/wc/v3/products", [], query, [
|
|
635
|
+
"woocommerce",
|
|
636
|
+
"products"
|
|
637
|
+
]);
|
|
638
|
+
}
|
|
639
|
+
async function getProductsPaginated(page = 1, perPage = 12, filterParams) {
|
|
640
|
+
const query = buildProductQuery({ per_page: perPage, page, status: "publish" }, filterParams);
|
|
641
|
+
const cacheTags = ["woocommerce", "products", `products-page-${page}`];
|
|
642
|
+
if (filterParams?.category) cacheTags.push(`products-category-${filterParams.category}`);
|
|
643
|
+
if (filterParams?.tag) cacheTags.push(`products-tag-${filterParams.tag}`);
|
|
644
|
+
if (filterParams?.search) cacheTags.push("products-search");
|
|
645
|
+
return wcFetchPaginatedGraceful("/wp-json/wc/v3/products", query, cacheTags);
|
|
646
|
+
}
|
|
647
|
+
async function getProductById(id) {
|
|
648
|
+
return wcFetch(`/wp-json/wc/v3/products/${id}`, void 0, [
|
|
649
|
+
"woocommerce",
|
|
650
|
+
"products",
|
|
651
|
+
`product-${id}`
|
|
652
|
+
]);
|
|
653
|
+
}
|
|
654
|
+
async function getProductBySlug(slug) {
|
|
655
|
+
const products = await wcFetchGraceful(
|
|
656
|
+
"/wp-json/wc/v3/products",
|
|
657
|
+
[],
|
|
658
|
+
{ slug },
|
|
659
|
+
["woocommerce", "products", `product-slug-${slug}`]
|
|
660
|
+
);
|
|
661
|
+
return products[0];
|
|
662
|
+
}
|
|
663
|
+
async function getFeaturedProducts(limit = 10) {
|
|
664
|
+
return wcFetchGraceful(
|
|
665
|
+
"/wp-json/wc/v3/products",
|
|
666
|
+
[],
|
|
667
|
+
{ featured: true, per_page: limit, status: "publish" },
|
|
668
|
+
["woocommerce", "products", "featured"]
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
async function getOnSaleProducts(limit = 10) {
|
|
672
|
+
return wcFetchGraceful(
|
|
673
|
+
"/wp-json/wc/v3/products",
|
|
674
|
+
[],
|
|
675
|
+
{ on_sale: true, per_page: limit, status: "publish" },
|
|
676
|
+
["woocommerce", "products", "on-sale"]
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
async function getRelatedProducts(productId) {
|
|
680
|
+
const product = await getProductById(productId);
|
|
681
|
+
if (!product.related_ids.length) return [];
|
|
682
|
+
return wcFetchGraceful(
|
|
683
|
+
"/wp-json/wc/v3/products",
|
|
684
|
+
[],
|
|
685
|
+
{ include: product.related_ids.join(","), per_page: 10, status: "publish" },
|
|
686
|
+
["woocommerce", "products", `related-${productId}`]
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
async function getAllProductSlugs() {
|
|
690
|
+
try {
|
|
691
|
+
const allSlugs = [];
|
|
692
|
+
let page = 1;
|
|
693
|
+
let hasMore = true;
|
|
694
|
+
while (hasMore) {
|
|
695
|
+
const response = await wcFetchPaginated("/wp-json/wc/v3/products", {
|
|
696
|
+
per_page: 100,
|
|
697
|
+
page,
|
|
698
|
+
status: "publish",
|
|
699
|
+
_fields: "slug"
|
|
700
|
+
});
|
|
701
|
+
allSlugs.push(...response.data.map((p) => ({ slug: p.slug })));
|
|
702
|
+
hasMore = page < response.headers.totalPages;
|
|
703
|
+
page++;
|
|
704
|
+
}
|
|
705
|
+
return allSlugs;
|
|
706
|
+
} catch {
|
|
707
|
+
console.warn("WooCommerce unavailable, skipping static generation for products");
|
|
708
|
+
return [];
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
async function getProductVariations(productId) {
|
|
712
|
+
return wcFetchGraceful(
|
|
713
|
+
`/wp-json/wc/v3/products/${productId}/variations`,
|
|
714
|
+
[],
|
|
715
|
+
{ per_page: 100 },
|
|
716
|
+
["woocommerce", "products", `product-${productId}`, "variations"]
|
|
717
|
+
);
|
|
718
|
+
}
|
|
719
|
+
async function getProductVariationById(productId, variationId) {
|
|
720
|
+
return wcFetch(
|
|
721
|
+
`/wp-json/wc/v3/products/${productId}/variations/${variationId}`,
|
|
722
|
+
void 0,
|
|
723
|
+
["woocommerce", "products", `product-${productId}`, `variation-${variationId}`]
|
|
724
|
+
);
|
|
725
|
+
}
|
|
726
|
+
return {
|
|
727
|
+
getProducts,
|
|
728
|
+
getProductsPaginated,
|
|
729
|
+
getProductById,
|
|
730
|
+
getProductBySlug,
|
|
731
|
+
getFeaturedProducts,
|
|
732
|
+
getOnSaleProducts,
|
|
733
|
+
getRelatedProducts,
|
|
734
|
+
getAllProductSlugs,
|
|
735
|
+
getProductVariations,
|
|
736
|
+
getProductVariationById
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
// src/hooks/woocommerce/useProducts.ts
|
|
741
|
+
function useProducts(config, filter, swrOptions) {
|
|
742
|
+
const key = ["wc-products", config.serverURL, JSON.stringify(filter ?? null)];
|
|
743
|
+
return useSWR2__default.default(
|
|
744
|
+
key,
|
|
745
|
+
() => {
|
|
746
|
+
const fetcher = createWooCommerceFetcher(config);
|
|
747
|
+
return createProductsQueries(fetcher).getProducts(filter);
|
|
748
|
+
},
|
|
749
|
+
swrOptions
|
|
750
|
+
);
|
|
751
|
+
}
|
|
752
|
+
function useProduct(config, id, swrOptions) {
|
|
753
|
+
const key = id != null ? ["wc-product", config.serverURL, id] : null;
|
|
754
|
+
return useSWR2__default.default(
|
|
755
|
+
key,
|
|
756
|
+
() => {
|
|
757
|
+
const fetcher = createWooCommerceFetcher(config);
|
|
758
|
+
return createProductsQueries(fetcher).getProductById(id);
|
|
759
|
+
},
|
|
760
|
+
swrOptions
|
|
761
|
+
);
|
|
762
|
+
}
|
|
763
|
+
function useProductBySlug(config, slug, swrOptions) {
|
|
764
|
+
const key = slug ? ["wc-product-slug", config.serverURL, slug] : null;
|
|
765
|
+
return useSWR2__default.default(
|
|
766
|
+
key,
|
|
767
|
+
() => {
|
|
768
|
+
const fetcher = createWooCommerceFetcher(config);
|
|
769
|
+
return createProductsQueries(fetcher).getProductBySlug(slug);
|
|
770
|
+
},
|
|
771
|
+
swrOptions
|
|
772
|
+
);
|
|
773
|
+
}
|
|
774
|
+
function useProductsPaginated(config, page = 1, perPage = 12, filter, swrOptions) {
|
|
775
|
+
const key = ["wc-products-paginated", config.serverURL, page, perPage, JSON.stringify(filter ?? null)];
|
|
776
|
+
return useSWR2__default.default(
|
|
777
|
+
key,
|
|
778
|
+
() => {
|
|
779
|
+
const fetcher = createWooCommerceFetcher(config);
|
|
780
|
+
return createProductsQueries(fetcher).getProductsPaginated(page, perPage, filter);
|
|
781
|
+
},
|
|
782
|
+
swrOptions
|
|
783
|
+
);
|
|
784
|
+
}
|
|
785
|
+
function useFeaturedProducts(config, limit = 10, swrOptions) {
|
|
786
|
+
const key = ["wc-products-featured", config.serverURL, limit];
|
|
787
|
+
return useSWR2__default.default(
|
|
788
|
+
key,
|
|
789
|
+
() => {
|
|
790
|
+
const fetcher = createWooCommerceFetcher(config);
|
|
791
|
+
return createProductsQueries(fetcher).getFeaturedProducts(limit);
|
|
792
|
+
},
|
|
793
|
+
swrOptions
|
|
794
|
+
);
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
// src/integrations/restApi/woocommerce/orders/queries.ts
|
|
798
|
+
function createOrdersQueries(fetcher) {
|
|
799
|
+
const { wcFetch, wcFetchGraceful, wcMutate } = fetcher;
|
|
800
|
+
async function createOrder(input) {
|
|
801
|
+
return wcMutate("/wp-json/wc/v3/orders", input, "POST");
|
|
802
|
+
}
|
|
803
|
+
async function getOrderById(id) {
|
|
804
|
+
return wcFetch(`/wp-json/wc/v3/orders/${id}`, void 0, [
|
|
805
|
+
"woocommerce",
|
|
806
|
+
"orders",
|
|
807
|
+
`order-${id}`
|
|
808
|
+
]);
|
|
809
|
+
}
|
|
810
|
+
async function updateOrder(id, data) {
|
|
811
|
+
return wcMutate(`/wp-json/wc/v3/orders/${id}`, data, "PUT");
|
|
812
|
+
}
|
|
813
|
+
async function getOrdersByCustomer(customerId) {
|
|
814
|
+
return wcFetchGraceful(
|
|
815
|
+
"/wp-json/wc/v3/orders",
|
|
816
|
+
[],
|
|
817
|
+
{ customer: customerId, per_page: 100 },
|
|
818
|
+
["woocommerce", "orders", `orders-customer-${customerId}`]
|
|
819
|
+
);
|
|
820
|
+
}
|
|
821
|
+
async function deleteOrder(id, force = true) {
|
|
822
|
+
return wcMutate(
|
|
823
|
+
`/wp-json/wc/v3/orders/${id}`,
|
|
824
|
+
{ force },
|
|
825
|
+
"DELETE"
|
|
826
|
+
);
|
|
827
|
+
}
|
|
828
|
+
return {
|
|
829
|
+
createOrder,
|
|
830
|
+
getOrderById,
|
|
831
|
+
updateOrder,
|
|
832
|
+
getOrdersByCustomer,
|
|
833
|
+
deleteOrder
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
var STORAGE_KEY = "nw-cart";
|
|
837
|
+
function isSame(a, b) {
|
|
838
|
+
return a.productId === b.productId && (a.variationId ?? 0) === (b.variationId ?? 0);
|
|
839
|
+
}
|
|
840
|
+
function cartReducer(state, action) {
|
|
841
|
+
switch (action.type) {
|
|
842
|
+
case "LOAD":
|
|
843
|
+
return { items: action.items };
|
|
844
|
+
case "ADD": {
|
|
845
|
+
const existing = state.items.find((i) => isSame(i, action.item));
|
|
846
|
+
if (existing) {
|
|
847
|
+
return {
|
|
848
|
+
items: state.items.map(
|
|
849
|
+
(i) => isSame(i, action.item) ? { ...i, quantity: i.quantity + action.item.quantity } : i
|
|
850
|
+
)
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
return { items: [...state.items, action.item] };
|
|
854
|
+
}
|
|
855
|
+
case "REMOVE":
|
|
856
|
+
return { items: state.items.filter((i) => !isSame(i, action)) };
|
|
857
|
+
case "UPDATE":
|
|
858
|
+
if (action.quantity <= 0) {
|
|
859
|
+
return { items: state.items.filter((i) => !isSame(i, action)) };
|
|
860
|
+
}
|
|
861
|
+
return {
|
|
862
|
+
items: state.items.map(
|
|
863
|
+
(i) => isSame(i, action) ? { ...i, quantity: action.quantity } : i
|
|
864
|
+
)
|
|
865
|
+
};
|
|
866
|
+
case "CLEAR":
|
|
867
|
+
return { items: [] };
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
var CartContext = react.createContext(null);
|
|
871
|
+
function CartProvider({ children }) {
|
|
872
|
+
const [state, dispatch] = react.useReducer(cartReducer, { items: [] });
|
|
873
|
+
react.useEffect(() => {
|
|
874
|
+
try {
|
|
875
|
+
const stored = localStorage.getItem(STORAGE_KEY);
|
|
876
|
+
if (stored) dispatch({ type: "LOAD", items: JSON.parse(stored) });
|
|
877
|
+
} catch {
|
|
878
|
+
}
|
|
879
|
+
}, []);
|
|
880
|
+
react.useEffect(() => {
|
|
881
|
+
try {
|
|
882
|
+
localStorage.setItem(STORAGE_KEY, JSON.stringify(state.items));
|
|
883
|
+
} catch {
|
|
884
|
+
}
|
|
885
|
+
}, [state.items]);
|
|
886
|
+
const totalItems = state.items.reduce((sum, i) => sum + i.quantity, 0);
|
|
887
|
+
const subtotal = state.items.reduce((sum, i) => sum + parseFloat(i.price) * i.quantity, 0).toFixed(2);
|
|
888
|
+
function addItem(item, quantity = 1) {
|
|
889
|
+
dispatch({ type: "ADD", item: { ...item, quantity } });
|
|
890
|
+
}
|
|
891
|
+
function removeItem(productId, variationId) {
|
|
892
|
+
dispatch({ type: "REMOVE", productId, variationId });
|
|
893
|
+
}
|
|
894
|
+
function updateQuantity(productId, quantity, variationId) {
|
|
895
|
+
dispatch({ type: "UPDATE", productId, quantity, variationId });
|
|
896
|
+
}
|
|
897
|
+
function clearCart() {
|
|
898
|
+
dispatch({ type: "CLEAR" });
|
|
899
|
+
}
|
|
900
|
+
async function checkout(config, options = {}) {
|
|
901
|
+
if (state.items.length === 0) throw new Error("Cannot checkout with an empty cart");
|
|
902
|
+
const fetcher = createWooCommerceFetcher(config);
|
|
903
|
+
const input = {
|
|
904
|
+
status: "pending",
|
|
905
|
+
line_items: state.items.map((i) => ({
|
|
906
|
+
product_id: i.productId,
|
|
907
|
+
...i.variationId !== void 0 ? { variation_id: i.variationId } : {},
|
|
908
|
+
quantity: i.quantity
|
|
909
|
+
})),
|
|
910
|
+
...options.billing ? { billing: options.billing } : {},
|
|
911
|
+
...options.shipping ? { shipping: options.shipping } : {},
|
|
912
|
+
...options.paymentMethod ? { payment_method: options.paymentMethod } : {},
|
|
913
|
+
...options.paymentMethodTitle ? { payment_method_title: options.paymentMethodTitle } : {},
|
|
914
|
+
...options.customerNote ? { customer_note: options.customerNote } : {},
|
|
915
|
+
...options.couponCodes ? { coupon_lines: options.couponCodes.map((code) => ({ code })) } : {}
|
|
916
|
+
};
|
|
917
|
+
const order = await createOrdersQueries(fetcher).createOrder(input);
|
|
918
|
+
dispatch({ type: "CLEAR" });
|
|
919
|
+
return order;
|
|
920
|
+
}
|
|
921
|
+
return /* @__PURE__ */ jsxRuntime.jsx(
|
|
922
|
+
CartContext.Provider,
|
|
923
|
+
{
|
|
924
|
+
value: { items: state.items, totalItems, subtotal, isEmpty: state.items.length === 0, addItem, removeItem, updateQuantity, clearCart, checkout },
|
|
925
|
+
children
|
|
926
|
+
}
|
|
927
|
+
);
|
|
928
|
+
}
|
|
929
|
+
function useCart() {
|
|
930
|
+
const ctx = react.useContext(CartContext);
|
|
931
|
+
if (!ctx) throw new Error("useCart must be used within a CartProvider");
|
|
932
|
+
return ctx;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// src/integrations/restApi/woocommerce/customers/queries.ts
|
|
936
|
+
function createCustomersQueries(fetcher) {
|
|
937
|
+
const { wcFetch, wcFetchGraceful, wcMutate } = fetcher;
|
|
938
|
+
async function getCustomerById(id) {
|
|
939
|
+
return wcFetch(`/wp-json/wc/v3/customers/${id}`, void 0, [
|
|
940
|
+
"woocommerce",
|
|
941
|
+
"customers",
|
|
942
|
+
`customer-${id}`
|
|
943
|
+
]);
|
|
944
|
+
}
|
|
945
|
+
async function getCustomerByEmail(email) {
|
|
946
|
+
const customers = await wcFetchGraceful(
|
|
947
|
+
"/wp-json/wc/v3/customers",
|
|
948
|
+
[],
|
|
949
|
+
{ email },
|
|
950
|
+
["woocommerce", "customers"]
|
|
951
|
+
);
|
|
952
|
+
return customers[0];
|
|
953
|
+
}
|
|
954
|
+
async function getCustomerByEmailNoCache(email) {
|
|
955
|
+
try {
|
|
956
|
+
const customers = await wcFetch(
|
|
957
|
+
"/wp-json/wc/v3/customers",
|
|
958
|
+
{ email },
|
|
959
|
+
["woocommerce", "customers"],
|
|
960
|
+
{ cache: "no-store" }
|
|
961
|
+
);
|
|
962
|
+
return customers[0];
|
|
963
|
+
} catch {
|
|
964
|
+
return void 0;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
async function createCustomer(data) {
|
|
968
|
+
return wcFetch(
|
|
969
|
+
"/wp-json/wc/v3/customers",
|
|
970
|
+
void 0,
|
|
971
|
+
["woocommerce", "customers"],
|
|
972
|
+
{ method: "POST", body: JSON.stringify(data) }
|
|
973
|
+
);
|
|
974
|
+
}
|
|
975
|
+
async function updateCustomer(id, data) {
|
|
976
|
+
return wcMutate(`/wp-json/wc/v3/customers/${id}`, data, "PUT");
|
|
977
|
+
}
|
|
978
|
+
async function deleteCustomer(id, reassign) {
|
|
979
|
+
return wcMutate(
|
|
980
|
+
`/wp-json/wc/v3/customers/${id}`,
|
|
981
|
+
{ force: true, ...reassign !== void 0 && { reassign } },
|
|
982
|
+
"DELETE"
|
|
983
|
+
);
|
|
984
|
+
}
|
|
985
|
+
return {
|
|
986
|
+
getCustomerById,
|
|
987
|
+
getCustomerByEmail,
|
|
988
|
+
getCustomerByEmailNoCache,
|
|
989
|
+
createCustomer,
|
|
990
|
+
updateCustomer,
|
|
991
|
+
deleteCustomer
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
var CustomerContext = react.createContext(null);
|
|
995
|
+
function WooCommerceCustomerProvider({
|
|
996
|
+
config,
|
|
997
|
+
children
|
|
998
|
+
}) {
|
|
999
|
+
const { user, isLoggedIn } = useAuth();
|
|
1000
|
+
const [customer, setCustomer] = react.useState(null);
|
|
1001
|
+
const [orders, setOrders] = react.useState([]);
|
|
1002
|
+
const [isLoading, setIsLoading] = react.useState(false);
|
|
1003
|
+
const [error, setError] = react.useState(null);
|
|
1004
|
+
const [tick, setTick] = react.useState(0);
|
|
1005
|
+
const fetchData = react.useCallback(async () => {
|
|
1006
|
+
if (!isLoggedIn || !user?.email) {
|
|
1007
|
+
setCustomer(null);
|
|
1008
|
+
setOrders([]);
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
setIsLoading(true);
|
|
1012
|
+
setError(null);
|
|
1013
|
+
try {
|
|
1014
|
+
const fetcher = createWooCommerceFetcher(config);
|
|
1015
|
+
const foundCustomer = await createCustomersQueries(fetcher).getCustomerByEmailNoCache(user.email);
|
|
1016
|
+
if (!foundCustomer) {
|
|
1017
|
+
setCustomer(null);
|
|
1018
|
+
setOrders([]);
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
const customerOrders = await createOrdersQueries(fetcher).getOrdersByCustomer(foundCustomer.id);
|
|
1022
|
+
setCustomer(foundCustomer);
|
|
1023
|
+
setOrders(customerOrders);
|
|
1024
|
+
} catch (err) {
|
|
1025
|
+
setError(err instanceof Error ? err.message : "Failed to load customer data");
|
|
1026
|
+
} finally {
|
|
1027
|
+
setIsLoading(false);
|
|
1028
|
+
}
|
|
1029
|
+
}, [isLoggedIn, user?.email, config, tick]);
|
|
1030
|
+
react.useEffect(() => {
|
|
1031
|
+
void fetchData();
|
|
1032
|
+
}, [fetchData]);
|
|
1033
|
+
const updateCustomer = async (data) => {
|
|
1034
|
+
if (!customer) throw new Error("No customer loaded");
|
|
1035
|
+
const fetcher = createWooCommerceFetcher(config);
|
|
1036
|
+
const updated = await createCustomersQueries(fetcher).updateCustomer(customer.id, data);
|
|
1037
|
+
setCustomer(updated);
|
|
1038
|
+
return updated;
|
|
1039
|
+
};
|
|
1040
|
+
const refetch = () => setTick((t) => t + 1);
|
|
1041
|
+
return /* @__PURE__ */ jsxRuntime.jsx(CustomerContext.Provider, { value: { customer, orders, isLoading, error, updateCustomer, refetch }, children });
|
|
1042
|
+
}
|
|
1043
|
+
function useCustomer() {
|
|
1044
|
+
const ctx = react.useContext(CustomerContext);
|
|
1045
|
+
if (!ctx) throw new Error("useCustomer must be used within a WooCommerceCustomerProvider");
|
|
1046
|
+
return ctx;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
// src/integrations/wpGraphQL/client/types.ts
|
|
1050
|
+
var WPGraphQLError = class extends Error {
|
|
1051
|
+
constructor(code, status, endpoint, message, gqlErrors) {
|
|
1052
|
+
super(message);
|
|
1053
|
+
__publicField(this, "code", code);
|
|
1054
|
+
__publicField(this, "status", status);
|
|
1055
|
+
__publicField(this, "endpoint", endpoint);
|
|
1056
|
+
__publicField(this, "gqlErrors", gqlErrors);
|
|
1057
|
+
this.name = "WPGraphQLError";
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
|
|
1061
|
+
// src/integrations/wpGraphQL/client/fetcher.ts
|
|
1062
|
+
var USER_AGENT3 = "NextWordpress WPGraphQL Client";
|
|
1063
|
+
function createWPGraphQLFetcher(config) {
|
|
1064
|
+
const url = `${resolveBaseUrl(config)}/graphql`;
|
|
1065
|
+
const cacheTTL = config.cacheTTL ?? 300;
|
|
1066
|
+
async function gqlFetch(document, variables, tags = ["wpgraphql"]) {
|
|
1067
|
+
const response = await fetch(url, {
|
|
1068
|
+
method: "POST",
|
|
1069
|
+
headers: {
|
|
1070
|
+
"Content-Type": "application/json",
|
|
1071
|
+
"User-Agent": USER_AGENT3
|
|
1072
|
+
},
|
|
1073
|
+
body: JSON.stringify({ query: document, variables }),
|
|
1074
|
+
next: { tags, revalidate: cacheTTL }
|
|
1075
|
+
});
|
|
1076
|
+
if (!response.ok) {
|
|
1077
|
+
throw new WPGraphQLError(
|
|
1078
|
+
ErrorCode.GQL_REQUEST_FAILED,
|
|
1079
|
+
response.status,
|
|
1080
|
+
url,
|
|
1081
|
+
resolveMessage(ErrorCode.GQL_REQUEST_FAILED, config.errorMessages)
|
|
1082
|
+
);
|
|
1083
|
+
}
|
|
1084
|
+
const parsed = await response.json();
|
|
1085
|
+
if (parsed.errors && parsed.errors.length > 0) {
|
|
1086
|
+
throw new WPGraphQLError(
|
|
1087
|
+
ErrorCode.GQL_ERRORS_IN_RESPONSE,
|
|
1088
|
+
200,
|
|
1089
|
+
url,
|
|
1090
|
+
resolveMessage(ErrorCode.GQL_ERRORS_IN_RESPONSE, config.errorMessages),
|
|
1091
|
+
parsed.errors
|
|
1092
|
+
);
|
|
1093
|
+
}
|
|
1094
|
+
if (parsed.data === void 0) {
|
|
1095
|
+
throw new WPGraphQLError(
|
|
1096
|
+
ErrorCode.GQL_NO_DATA,
|
|
1097
|
+
200,
|
|
1098
|
+
url,
|
|
1099
|
+
resolveMessage(ErrorCode.GQL_NO_DATA, config.errorMessages)
|
|
1100
|
+
);
|
|
1101
|
+
}
|
|
1102
|
+
return parsed.data;
|
|
1103
|
+
}
|
|
1104
|
+
async function gqlFetchGraceful(document, fallback, variables, tags = ["wpgraphql"]) {
|
|
1105
|
+
try {
|
|
1106
|
+
return await gqlFetch(document, variables, tags);
|
|
1107
|
+
} catch {
|
|
1108
|
+
console.warn(`WPGraphQL fetch failed for query`);
|
|
1109
|
+
return fallback;
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
async function gqlMutate(document, variables, authToken) {
|
|
1113
|
+
const headers = {
|
|
1114
|
+
"Content-Type": "application/json",
|
|
1115
|
+
"User-Agent": USER_AGENT3
|
|
1116
|
+
};
|
|
1117
|
+
if (authToken) {
|
|
1118
|
+
headers["Authorization"] = authToken;
|
|
1119
|
+
}
|
|
1120
|
+
const response = await fetch(url, {
|
|
1121
|
+
method: "POST",
|
|
1122
|
+
headers,
|
|
1123
|
+
body: JSON.stringify({ query: document, variables }),
|
|
1124
|
+
cache: "no-store"
|
|
1125
|
+
});
|
|
1126
|
+
if (!response.ok) {
|
|
1127
|
+
throw new WPGraphQLError(
|
|
1128
|
+
ErrorCode.GQL_REQUEST_FAILED,
|
|
1129
|
+
response.status,
|
|
1130
|
+
url,
|
|
1131
|
+
resolveMessage(ErrorCode.GQL_REQUEST_FAILED, config.errorMessages)
|
|
1132
|
+
);
|
|
1133
|
+
}
|
|
1134
|
+
const parsed = await response.json();
|
|
1135
|
+
if (parsed.errors && parsed.errors.length > 0) {
|
|
1136
|
+
throw new WPGraphQLError(
|
|
1137
|
+
ErrorCode.GQL_ERRORS_IN_RESPONSE,
|
|
1138
|
+
200,
|
|
1139
|
+
url,
|
|
1140
|
+
resolveMessage(ErrorCode.GQL_ERRORS_IN_RESPONSE, config.errorMessages),
|
|
1141
|
+
parsed.errors
|
|
1142
|
+
);
|
|
1143
|
+
}
|
|
1144
|
+
if (parsed.data === void 0) {
|
|
1145
|
+
throw new WPGraphQLError(
|
|
1146
|
+
ErrorCode.GQL_NO_DATA,
|
|
1147
|
+
200,
|
|
1148
|
+
url,
|
|
1149
|
+
resolveMessage(ErrorCode.GQL_NO_DATA, config.errorMessages)
|
|
1150
|
+
);
|
|
1151
|
+
}
|
|
1152
|
+
return parsed.data;
|
|
1153
|
+
}
|
|
1154
|
+
return { gqlFetch, gqlFetchGraceful, gqlMutate };
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
// src/integrations/wpGraphQL/core/posts/queries.ts
|
|
1158
|
+
var DEFAULT_FIRST = 10;
|
|
1159
|
+
var BATCH_FIRST = 100;
|
|
1160
|
+
var POST_FIELDS = `
|
|
1161
|
+
id
|
|
1162
|
+
databaseId
|
|
1163
|
+
slug
|
|
1164
|
+
title
|
|
1165
|
+
excerpt
|
|
1166
|
+
date
|
|
1167
|
+
modified
|
|
1168
|
+
status
|
|
1169
|
+
uri
|
|
1170
|
+
author {
|
|
1171
|
+
node {
|
|
1172
|
+
databaseId
|
|
1173
|
+
name
|
|
1174
|
+
slug
|
|
1175
|
+
avatar { url }
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
featuredImage {
|
|
1179
|
+
node {
|
|
1180
|
+
sourceUrl
|
|
1181
|
+
altText
|
|
1182
|
+
mediaDetails { width height }
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
categories {
|
|
1186
|
+
nodes { databaseId name slug }
|
|
1187
|
+
}
|
|
1188
|
+
tags {
|
|
1189
|
+
nodes { databaseId name slug }
|
|
1190
|
+
}
|
|
1191
|
+
`;
|
|
1192
|
+
var POST_FIELDS_WITH_CONTENT = `
|
|
1193
|
+
${POST_FIELDS}
|
|
1194
|
+
content
|
|
1195
|
+
`;
|
|
1196
|
+
var GQL_GET_POSTS = `
|
|
1197
|
+
query GetPosts($first: Int, $after: String, $where: RootQueryToPostConnectionWhereArgs) {
|
|
1198
|
+
posts(first: $first, after: $after, where: $where) {
|
|
1199
|
+
nodes { ${POST_FIELDS} }
|
|
1200
|
+
pageInfo { hasNextPage hasPreviousPage startCursor endCursor }
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
`;
|
|
1204
|
+
var GQL_GET_POST_BY_SLUG = `
|
|
1205
|
+
query GetPostBySlug($slug: ID!) {
|
|
1206
|
+
post(id: $slug, idType: SLUG) { ${POST_FIELDS_WITH_CONTENT} }
|
|
1207
|
+
}
|
|
1208
|
+
`;
|
|
1209
|
+
var GQL_GET_POST_BY_DATABASE_ID = `
|
|
1210
|
+
query GetPostByDatabaseId($id: ID!) {
|
|
1211
|
+
post(id: $id, idType: DATABASE_ID) { ${POST_FIELDS_WITH_CONTENT} }
|
|
1212
|
+
}
|
|
1213
|
+
`;
|
|
1214
|
+
var GQL_GET_ALL_POST_SLUGS = `
|
|
1215
|
+
query GetAllPostSlugs($first: Int, $after: String) {
|
|
1216
|
+
posts(first: $first, after: $after) {
|
|
1217
|
+
nodes { slug }
|
|
1218
|
+
pageInfo { hasNextPage endCursor }
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
`;
|
|
1222
|
+
var GQL_GET_ALL_POSTS_FOR_SITEMAP = `
|
|
1223
|
+
query GetAllPostsForSitemap($first: Int, $after: String) {
|
|
1224
|
+
posts(first: $first, after: $after) {
|
|
1225
|
+
nodes { slug modified }
|
|
1226
|
+
pageInfo { hasNextPage endCursor }
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
`;
|
|
1230
|
+
function createPostsQueries2(fetcher) {
|
|
1231
|
+
const { gqlFetch, gqlFetchGraceful } = fetcher;
|
|
1232
|
+
async function getPosts(first = DEFAULT_FIRST, after, filter) {
|
|
1233
|
+
const where = {};
|
|
1234
|
+
if (filter?.authorName) where["authorName"] = filter.authorName;
|
|
1235
|
+
if (filter?.categoryName) where["categoryName"] = filter.categoryName;
|
|
1236
|
+
if (filter?.tag) where["tag"] = filter.tag;
|
|
1237
|
+
if (filter?.search) where["search"] = filter.search;
|
|
1238
|
+
if (filter?.status) where["status"] = filter.status;
|
|
1239
|
+
const data = await gqlFetchGraceful(
|
|
1240
|
+
GQL_GET_POSTS,
|
|
1241
|
+
{ posts: { nodes: [], pageInfo: { hasNextPage: false, hasPreviousPage: false } } },
|
|
1242
|
+
{ first, after, where: Object.keys(where).length > 0 ? where : void 0 },
|
|
1243
|
+
["wpgraphql", "gql-posts"]
|
|
1244
|
+
);
|
|
1245
|
+
return data.posts;
|
|
1246
|
+
}
|
|
1247
|
+
async function getPostBySlug(slug) {
|
|
1248
|
+
const data = await gqlFetchGraceful(
|
|
1249
|
+
GQL_GET_POST_BY_SLUG,
|
|
1250
|
+
{ post: null },
|
|
1251
|
+
{ slug },
|
|
1252
|
+
["wpgraphql", "gql-posts", `gql-post-${slug}`]
|
|
1253
|
+
);
|
|
1254
|
+
return data.post;
|
|
1255
|
+
}
|
|
1256
|
+
async function getPostByDatabaseId(id) {
|
|
1257
|
+
const data = await gqlFetchGraceful(
|
|
1258
|
+
GQL_GET_POST_BY_DATABASE_ID,
|
|
1259
|
+
{ post: null },
|
|
1260
|
+
{ id: String(id) },
|
|
1261
|
+
["wpgraphql", "gql-posts", `gql-post-id-${id}`]
|
|
1262
|
+
);
|
|
1263
|
+
return data.post;
|
|
1264
|
+
}
|
|
1265
|
+
async function getRecentPosts(first = DEFAULT_FIRST) {
|
|
1266
|
+
const connection = await getPosts(first);
|
|
1267
|
+
return connection.nodes;
|
|
1268
|
+
}
|
|
1269
|
+
async function getAllPostSlugs() {
|
|
1270
|
+
try {
|
|
1271
|
+
const all = [];
|
|
1272
|
+
let after = void 0;
|
|
1273
|
+
let hasNextPage = true;
|
|
1274
|
+
while (hasNextPage) {
|
|
1275
|
+
const data = await gqlFetch(GQL_GET_ALL_POST_SLUGS, { first: BATCH_FIRST, after }, ["wpgraphql"]);
|
|
1276
|
+
all.push(...data.posts.nodes);
|
|
1277
|
+
hasNextPage = data.posts.pageInfo.hasNextPage;
|
|
1278
|
+
after = data.posts.pageInfo.endCursor;
|
|
1279
|
+
}
|
|
1280
|
+
return all;
|
|
1281
|
+
} catch {
|
|
1282
|
+
console.warn("WPGraphQL unavailable, skipping static generation for posts");
|
|
1283
|
+
return [];
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
async function getAllPostsForSitemap() {
|
|
1287
|
+
try {
|
|
1288
|
+
const all = [];
|
|
1289
|
+
let after = void 0;
|
|
1290
|
+
let hasNextPage = true;
|
|
1291
|
+
while (hasNextPage) {
|
|
1292
|
+
const data = await gqlFetch(
|
|
1293
|
+
GQL_GET_ALL_POSTS_FOR_SITEMAP,
|
|
1294
|
+
{ first: BATCH_FIRST, after },
|
|
1295
|
+
["wpgraphql"]
|
|
1296
|
+
);
|
|
1297
|
+
all.push(...data.posts.nodes);
|
|
1298
|
+
hasNextPage = data.posts.pageInfo.hasNextPage;
|
|
1299
|
+
after = data.posts.pageInfo.endCursor;
|
|
1300
|
+
}
|
|
1301
|
+
return all;
|
|
1302
|
+
} catch {
|
|
1303
|
+
console.warn("WPGraphQL unavailable, skipping sitemap generation");
|
|
1304
|
+
return [];
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
return {
|
|
1308
|
+
getPosts,
|
|
1309
|
+
getPostBySlug,
|
|
1310
|
+
getPostByDatabaseId,
|
|
1311
|
+
getRecentPosts,
|
|
1312
|
+
getAllPostSlugs,
|
|
1313
|
+
getAllPostsForSitemap
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
// src/hooks/wpgraphql/useWPGraphQL.ts
|
|
1318
|
+
function useWPGraphQL(config, query, variables, tags, swrOptions) {
|
|
1319
|
+
const key = ["wpgraphql", config.clientURL, query, JSON.stringify(variables ?? null)];
|
|
1320
|
+
return useSWR2__default.default(
|
|
1321
|
+
key,
|
|
1322
|
+
() => {
|
|
1323
|
+
const fetcher = createWPGraphQLFetcher(config);
|
|
1324
|
+
return fetcher.gqlFetch(query, variables, tags);
|
|
1325
|
+
},
|
|
1326
|
+
swrOptions
|
|
1327
|
+
);
|
|
1328
|
+
}
|
|
1329
|
+
function useGQLPosts(config, first, after, filter, swrOptions) {
|
|
1330
|
+
const key = ["wpgraphql-posts", config.clientURL, first, after, JSON.stringify(filter ?? null)];
|
|
1331
|
+
return useSWR2__default.default(
|
|
1332
|
+
key,
|
|
1333
|
+
() => {
|
|
1334
|
+
const fetcher = createWPGraphQLFetcher(config);
|
|
1335
|
+
return createPostsQueries2(fetcher).getPosts(first, after, filter);
|
|
1336
|
+
},
|
|
1337
|
+
swrOptions
|
|
1338
|
+
);
|
|
1339
|
+
}
|
|
1340
|
+
function useGQLPostBySlug(config, slug, swrOptions) {
|
|
1341
|
+
const key = slug ? ["wpgraphql-post-slug", config.clientURL, slug] : null;
|
|
1342
|
+
return useSWR2__default.default(
|
|
1343
|
+
key,
|
|
1344
|
+
() => {
|
|
1345
|
+
const fetcher = createWPGraphQLFetcher(config);
|
|
1346
|
+
return createPostsQueries2(fetcher).getPostBySlug(slug);
|
|
1347
|
+
},
|
|
1348
|
+
swrOptions
|
|
1349
|
+
);
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
exports.AuthProvider = AuthProvider;
|
|
1353
|
+
exports.CartProvider = CartProvider;
|
|
1354
|
+
exports.WooCommerceCustomerProvider = WooCommerceCustomerProvider;
|
|
1355
|
+
exports.cartReducer = cartReducer;
|
|
1356
|
+
exports.useAuth = useAuth;
|
|
1357
|
+
exports.useCart = useCart;
|
|
1358
|
+
exports.useCustomer = useCustomer;
|
|
1359
|
+
exports.useFeaturedProducts = useFeaturedProducts;
|
|
1360
|
+
exports.useGQLPostBySlug = useGQLPostBySlug;
|
|
1361
|
+
exports.useGQLPosts = useGQLPosts;
|
|
1362
|
+
exports.usePost = usePost;
|
|
1363
|
+
exports.usePostBySlug = usePostBySlug;
|
|
1364
|
+
exports.usePosts = usePosts;
|
|
1365
|
+
exports.usePostsPaginated = usePostsPaginated;
|
|
1366
|
+
exports.useProduct = useProduct;
|
|
1367
|
+
exports.useProductBySlug = useProductBySlug;
|
|
1368
|
+
exports.useProducts = useProducts;
|
|
1369
|
+
exports.useProductsPaginated = useProductsPaginated;
|
|
1370
|
+
exports.useWPGraphQL = useWPGraphQL;
|
|
1371
|
+
//# sourceMappingURL=index.cjs.map
|
|
1372
|
+
//# sourceMappingURL=index.cjs.map
|