@szymonpiatek/nextwordpress 0.0.4 → 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.
package/dist/index.cjs CHANGED
@@ -9,6 +9,133 @@ function resolveBaseUrl(config) {
9
9
  return typeof window === "undefined" ? config.serverURL : config.clientURL;
10
10
  }
11
11
 
12
+ // src/integrations/restApi/core/client/types.ts
13
+ var WordPressAPIError = class extends Error {
14
+ constructor(message, status, endpoint) {
15
+ super(message);
16
+ __publicField(this, "status", status);
17
+ __publicField(this, "endpoint", endpoint);
18
+ this.name = "WordPressAPIError";
19
+ }
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/contactForm7/queries.ts
126
+ function createCF7Queries(config) {
127
+ async function submitForm(formId, data) {
128
+ const url = buildUrl(config, `/wp-json/contact-form-7/v1/contact-forms/${formId}/feedback`);
129
+ const body = new FormData();
130
+ for (const [key, value] of Object.entries(data)) {
131
+ body.append(key, value);
132
+ }
133
+ const res = await fetch(url, { method: "POST", body, cache: "no-store" });
134
+ return res.json();
135
+ }
136
+ return { submitForm };
137
+ }
138
+
12
139
  // src/integrations/restApi/core/mutations/posts/mutations.ts
13
140
  function createPostsMutations(fetcher) {
14
141
  const { wpMutate } = fetcher;
@@ -202,119 +329,6 @@ function createMediaMutations(fetcher) {
202
329
  return { uploadMedia, updateMedia, deleteMedia };
203
330
  }
204
331
 
205
- // src/integrations/restApi/core/client/types.ts
206
- var WordPressAPIError = class extends Error {
207
- constructor(message, status, endpoint) {
208
- super(message);
209
- __publicField(this, "status", status);
210
- __publicField(this, "endpoint", endpoint);
211
- this.name = "WordPressAPIError";
212
- }
213
- };
214
-
215
- // src/integrations/restApi/core/client/url.ts
216
- function buildUrl(config, path, query) {
217
- const base = resolveBaseUrl(config);
218
- if (!query) return `${base}${path}`;
219
- const params = new URLSearchParams();
220
- for (const [key, value] of Object.entries(query)) {
221
- if (value !== void 0 && value !== null) {
222
- params.set(key, String(value));
223
- }
224
- }
225
- const qs = params.toString();
226
- return qs ? `${base}${path}?${qs}` : `${base}${path}`;
227
- }
228
-
229
- // src/integrations/restApi/core/client/fetcher.ts
230
- var USER_AGENT = "NextWordpress Client";
231
- async function doFetch(url, init = {}) {
232
- const response = await fetch(url, init);
233
- if (!response.ok) {
234
- throw new WordPressAPIError(
235
- `WordPress API request failed: ${response.statusText}`,
236
- response.status,
237
- url
238
- );
239
- }
240
- return response;
241
- }
242
- function createFetcher(config) {
243
- const cacheTtl = 300;
244
- async function wpFetch(path, query, tags = ["wordpress"]) {
245
- const url = buildUrl(config, path, query);
246
- const res = await doFetch(url, {
247
- headers: { "User-Agent": USER_AGENT },
248
- next: { tags, revalidate: cacheTtl }
249
- });
250
- return await res.json();
251
- }
252
- async function wpFetchGraceful(path, fallback, query, tags = ["wordpress"]) {
253
- try {
254
- return await wpFetch(path, query, tags);
255
- } catch {
256
- console.warn(`WordPress fetch failed for ${path}`);
257
- return fallback;
258
- }
259
- }
260
- async function wpFetchPaginated(path, query, tags = ["wordpress"]) {
261
- const url = buildUrl(config, path, query);
262
- const res = await doFetch(url, {
263
- headers: { "User-Agent": USER_AGENT },
264
- next: { tags, revalidate: cacheTtl }
265
- });
266
- return {
267
- data: await res.json(),
268
- headers: {
269
- total: parseInt(res.headers.get("X-WP-Total") ?? "0", 10),
270
- totalPages: parseInt(res.headers.get("X-WP-TotalPages") ?? "0", 10)
271
- }
272
- };
273
- }
274
- async function wpFetchPaginatedGraceful(path, query, tags = ["wordpress"]) {
275
- const empty = { data: [], headers: { total: 0, totalPages: 0 } };
276
- try {
277
- return await wpFetchPaginated(path, query, tags);
278
- } catch {
279
- console.warn(`WordPress paginated fetch failed for ${path}`);
280
- return empty;
281
- }
282
- }
283
- async function wpMutate(path, body, method = "POST", authToken) {
284
- const url = buildUrl(config, path);
285
- const headers = {
286
- "Content-Type": "application/json",
287
- "User-Agent": USER_AGENT
288
- };
289
- if (authToken) {
290
- headers["Authorization"] = authToken;
291
- }
292
- const res = await doFetch(url, {
293
- method,
294
- headers,
295
- body: JSON.stringify(body),
296
- cache: "no-store"
297
- });
298
- return await res.json();
299
- }
300
- async function wpUpload(path, file, filename, mimeType, authToken) {
301
- const url = buildUrl(config, path);
302
- const res = await doFetch(url, {
303
- method: "POST",
304
- headers: {
305
- "Content-Disposition": `attachment; filename="${filename}"`,
306
- "Content-Type": mimeType,
307
- "User-Agent": USER_AGENT,
308
- "Authorization": authToken
309
- },
310
- body: file,
311
- cache: "no-store"
312
- });
313
- return await res.json();
314
- }
315
- return { wpFetch, wpFetchGraceful, wpFetchPaginated, wpFetchPaginatedGraceful, wpMutate, wpUpload };
316
- }
317
-
318
332
  // src/integrations/restApi/core/mutations/index.ts
319
333
  function createWordPressMutationsClient(config) {
320
334
  const fetcher = createFetcher(config);
@@ -3190,6 +3204,91 @@ function createRevalidationHandler(config, revalidateTag) {
3190
3204
  };
3191
3205
  }
3192
3206
 
3207
+ // src/nextjs/faust.ts
3208
+ function createFaustAuthHandler(config) {
3209
+ const cookieName = config.cookieName ?? "faustwp-rt";
3210
+ return async function handler(request, routePath) {
3211
+ if (routePath === "auth/token") {
3212
+ const url = new URL(request.url);
3213
+ const code = url.searchParams.get("code");
3214
+ const redirectUri = url.searchParams.get("redirect_uri") ?? "/";
3215
+ const refreshToken = parseCookie(request, cookieName);
3216
+ if (!code && !refreshToken) {
3217
+ return Response.json({ error: "Unauthorized" }, { status: 401 });
3218
+ }
3219
+ const wpRes = await fetch(`${config.wpUrl}/?rest_route=/faustwp/v1/authorize`, {
3220
+ method: "POST",
3221
+ headers: {
3222
+ "Content-Type": "application/json",
3223
+ "x-faustwp-secret": config.secretKey
3224
+ },
3225
+ body: JSON.stringify({ code, refreshToken })
3226
+ });
3227
+ if (!wpRes.ok) {
3228
+ const body = await wpRes.text();
3229
+ return new Response(body, { status: wpRes.status });
3230
+ }
3231
+ const data = await wpRes.json();
3232
+ return new Response(null, {
3233
+ status: 302,
3234
+ headers: {
3235
+ Location: new URL(redirectUri, request.url).toString(),
3236
+ "Set-Cookie": buildSetCookie(cookieName, data.refreshToken, 2592e3)
3237
+ }
3238
+ });
3239
+ }
3240
+ if (routePath === "auth/logout") {
3241
+ return new Response(JSON.stringify({}), {
3242
+ status: 200,
3243
+ headers: {
3244
+ "Content-Type": "application/json",
3245
+ "Set-Cookie": `${cookieName}=; Max-Age=0; Path=/; HttpOnly`
3246
+ }
3247
+ });
3248
+ }
3249
+ return Response.json({ error: "Not Found" }, { status: 404 });
3250
+ };
3251
+ }
3252
+ function createPreviewHandler(config, deps) {
3253
+ const previewPath = config.previewPath ?? "posts";
3254
+ return async function handler(request) {
3255
+ const url = new URL(request.url);
3256
+ const postId = url.searchParams.get("postId");
3257
+ const previewPathname = url.searchParams.get("previewPathname");
3258
+ if (!postId) {
3259
+ return new Response("Missing postId", { status: 400 });
3260
+ }
3261
+ const slug = await resolvePreviewSlug(config, postId, previewPathname);
3262
+ if (!slug) {
3263
+ return new Response("Post not found", { status: 404 });
3264
+ }
3265
+ await deps.enableDraftMode();
3266
+ deps.redirect(`/${previewPath}/${slug}?postId=${postId}`);
3267
+ };
3268
+ }
3269
+ function parseCookie(request, name) {
3270
+ const header = request.headers.get("cookie") ?? "";
3271
+ const match = header.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
3272
+ return match?.[1];
3273
+ }
3274
+ function buildSetCookie(name, value, maxAge) {
3275
+ const secure = process.env.NODE_ENV === "production" ? "; Secure" : "";
3276
+ return `${name}=${value}; HttpOnly; Path=/; SameSite=Strict; Max-Age=${maxAge}${secure}`;
3277
+ }
3278
+ async function resolvePreviewSlug(config, postId, previewPathname) {
3279
+ if (previewPathname && !previewPathname.includes("p=")) {
3280
+ const slug = previewPathname.replace(/\/$/, "").split("/").pop();
3281
+ if (slug) return slug;
3282
+ }
3283
+ const res = await fetch(`${config.wpUrl}/wp-json/wp/v2/posts/${postId}?_fields=slug`, {
3284
+ headers: { "x-faustwp-secret": config.secretKey },
3285
+ cache: "no-store"
3286
+ });
3287
+ if (!res.ok) return null;
3288
+ const data = await res.json();
3289
+ return data.slug ?? `preview-${postId}`;
3290
+ }
3291
+
3193
3292
  // src/auth/applicationPassword.ts
3194
3293
  function createApplicationPasswordToken(username, appPassword) {
3195
3294
  const encoded = Buffer.from(`${username}:${appPassword}`).toString("base64");
@@ -3241,13 +3340,16 @@ exports.buildPostWithACFQuery = buildPostWithACFQuery;
3241
3340
  exports.buildPostsWithACFQuery = buildPostsWithACFQuery;
3242
3341
  exports.createApplicationPasswordToken = createApplicationPasswordToken;
3243
3342
  exports.createAuthorsMutations = createAuthorsMutations;
3343
+ exports.createCF7Queries = createCF7Queries;
3244
3344
  exports.createCPTQueries = createCPTQueries;
3245
3345
  exports.createCategoriesMutations = createCategoriesMutations;
3246
3346
  exports.createCommentsMutations = createCommentsMutations;
3347
+ exports.createFaustAuthHandler = createFaustAuthHandler;
3247
3348
  exports.createMediaMutations = createMediaMutations;
3248
3349
  exports.createMenusMutations = createMenusMutations;
3249
3350
  exports.createPagesMutations = createPagesMutations;
3250
3351
  exports.createPostsMutations = createPostsMutations;
3352
+ exports.createPreviewHandler = createPreviewHandler;
3251
3353
  exports.createRevalidationHandler = createRevalidationHandler;
3252
3354
  exports.createTagsMutations = createTagsMutations;
3253
3355
  exports.createWPGraphQLClient = createWPGraphQLCoreClient;