@studiocms/devapps 0.1.0-beta.9 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +3 -23
  3. package/dist/effects/WordPressAPI/configs.d.ts +87 -0
  4. package/dist/effects/WordPressAPI/configs.js +88 -0
  5. package/dist/effects/WordPressAPI/converters.d.ts +57 -0
  6. package/dist/effects/WordPressAPI/converters.js +331 -0
  7. package/dist/effects/WordPressAPI/errors.d.ts +12 -0
  8. package/dist/effects/WordPressAPI/errors.js +6 -0
  9. package/dist/effects/WordPressAPI/importers.d.ts +19 -0
  10. package/dist/effects/WordPressAPI/importers.js +122 -0
  11. package/dist/effects/WordPressAPI/schema.d.ts +478 -0
  12. package/dist/effects/WordPressAPI/schema.js +127 -0
  13. package/dist/effects/WordPressAPI/utils.d.ts +17 -0
  14. package/dist/effects/WordPressAPI/utils.js +239 -0
  15. package/dist/effects/wpImporter.d.ts +14 -0
  16. package/dist/effects/wpImporter.js +88 -0
  17. package/dist/index.d.ts +0 -3
  18. package/dist/index.js +0 -16
  19. package/dist/routes/wp-importer.d.ts +0 -25
  20. package/dist/routes/wp-importer.js +9 -54
  21. package/dist/schema/index.d.ts +0 -24
  22. package/dist/schema/index.js +1 -13
  23. package/dist/utils/pathGenerator.js +3 -1
  24. package/dist/virt.d.ts +1 -5
  25. package/package.json +25 -31
  26. package/dist/apps/libsql-viewer.d.ts +0 -46
  27. package/dist/apps/libsql-viewer.js +0 -95
  28. package/dist/schema/wp-api.d.ts +0 -439
  29. package/dist/schema/wp-api.js +0 -72
  30. package/dist/utils/wp-api/converters.d.ts +0 -74
  31. package/dist/utils/wp-api/converters.js +0 -181
  32. package/dist/utils/wp-api/index.d.ts +0 -6
  33. package/dist/utils/wp-api/index.js +0 -3
  34. package/dist/utils/wp-api/pages.d.ts +0 -13
  35. package/dist/utils/wp-api/pages.js +0 -38
  36. package/dist/utils/wp-api/posts.d.ts +0 -10
  37. package/dist/utils/wp-api/posts.js +0 -38
  38. package/dist/utils/wp-api/settings.d.ts +0 -18
  39. package/dist/utils/wp-api/settings.js +0 -45
  40. package/dist/utils/wp-api/utils.d.ts +0 -66
  41. package/dist/utils/wp-api/utils.js +0 -138
  42. package/dist/virt.d.js +0 -0
@@ -1,181 +0,0 @@
1
- import path from "node:path";
2
- import { db, eq } from "astro:db";
3
- import { userProjectRoot } from "virtual:studiocms-devapps/config";
4
- import { decode } from "html-entities";
5
- import { tsPageDataCategories, tsPageDataTags } from "studiocms/sdk/tables";
6
- import TurndownService from "turndown";
7
- import {
8
- apiEndpoint,
9
- cleanUpHtml,
10
- downloadAndUpdateImages,
11
- downloadPostImage,
12
- stripHtml
13
- } from "./utils";
14
- const ASTROPUBLICFOLDER = path.resolve(userProjectRoot, "public");
15
- const WPImportFolder = path.resolve(ASTROPUBLICFOLDER, "wp-import");
16
- const pagesImagesFolder = path.resolve(WPImportFolder, "pages");
17
- const postsImagesFolder = path.resolve(WPImportFolder, "posts");
18
- const ConvertToPageData = async (page, endpoint) => {
19
- const data = page;
20
- const titleImageId = data.featured_media;
21
- const titleImageURL = apiEndpoint(endpoint, "media", `${titleImageId}`);
22
- const titleImageResponse = await fetch(titleImageURL);
23
- const titleImageJson = await titleImageResponse.json();
24
- const titleImage = await downloadPostImage(titleImageJson.source_url, pagesImagesFolder);
25
- const pageData = {
26
- id: crypto.randomUUID(),
27
- title: data.title.rendered,
28
- description: decode(stripHtml(data.excerpt.rendered)),
29
- slug: data.slug,
30
- publishedAt: new Date(data.date_gmt),
31
- updatedAt: new Date(data.modified_gmt),
32
- showOnNav: false,
33
- contentLang: "default",
34
- package: "studiocms"
35
- };
36
- if (titleImage) {
37
- pageData.heroImage = titleImage;
38
- }
39
- return pageData;
40
- };
41
- const ConvertToPageContent = async (pageData, page) => {
42
- const data = page;
43
- if (pageData.id === void 0) {
44
- throw new Error("pageData is missing id");
45
- }
46
- const cleanupContent = cleanUpHtml(data.content.rendered);
47
- const htmlWithImages = await downloadAndUpdateImages(cleanupContent, pagesImagesFolder);
48
- const turndownService = new TurndownService({
49
- bulletListMarker: "-",
50
- codeBlockStyle: "fenced",
51
- emDelimiter: "*"
52
- });
53
- const content = turndownService.turndown(htmlWithImages);
54
- const pageContent = {
55
- id: crypto.randomUUID(),
56
- contentId: pageData.id,
57
- contentLang: "default",
58
- content
59
- };
60
- return pageContent;
61
- };
62
- const generateCategories = async (categories, endpoint) => {
63
- const newCategories = [];
64
- for (const categoryId of categories) {
65
- const categoryExists = await db.select().from(tsPageDataCategories).where(eq(tsPageDataCategories.id, categoryId)).get();
66
- if (categoryExists) {
67
- console.log(`Category with id ${categoryId} already exists in the database`);
68
- continue;
69
- }
70
- const categoryURL = apiEndpoint(endpoint, "categories", `${categoryId}`);
71
- const response = await fetch(categoryURL);
72
- const json = await response.json();
73
- newCategories.push(json);
74
- }
75
- if (newCategories.length > 0) {
76
- const categoryData = newCategories.map((category) => {
77
- const data = {
78
- id: category.id,
79
- name: category.name,
80
- slug: category.slug,
81
- description: category.description,
82
- meta: JSON.stringify(category.meta)
83
- };
84
- if (category.parent) {
85
- data.parent = category.parent;
86
- }
87
- return data;
88
- });
89
- for (const category of categoryData) {
90
- console.log(`Inserting category with id ${category.id} into the database`);
91
- await db.insert(tsPageDataCategories).values(category);
92
- }
93
- }
94
- };
95
- const generateTags = async (tags, endpoint) => {
96
- const newTags = [];
97
- for (const tagId of tags) {
98
- const tagExists = await db.select().from(tsPageDataTags).where(eq(tsPageDataTags.id, tagId)).get();
99
- if (tagExists) {
100
- console.log(`Tag with id ${tagId} already exists in the database`);
101
- continue;
102
- }
103
- const tagURL = apiEndpoint(endpoint, "tags", `${tagId}`);
104
- const response = await fetch(tagURL);
105
- const json = await response.json();
106
- newTags.push(json);
107
- }
108
- if (newTags.length > 0) {
109
- const tagData = newTags.map((tag) => {
110
- const data = {
111
- id: tag.id,
112
- name: tag.name,
113
- slug: tag.slug,
114
- description: tag.description,
115
- meta: JSON.stringify(tag.meta)
116
- };
117
- return data;
118
- });
119
- for (const tag of tagData) {
120
- console.log(`Inserting tag with id ${tag.id} into the database`);
121
- await db.insert(tsPageDataTags).values(tag);
122
- }
123
- }
124
- };
125
- const ConvertToPostData = async (post, useBlogPkg, endpoint) => {
126
- const data = post;
127
- const titleImageId = data.featured_media;
128
- const titleImageURL = apiEndpoint(endpoint, "media", `${titleImageId}`);
129
- const titleImageResponse = await fetch(titleImageURL);
130
- const titleImageJson = await titleImageResponse.json();
131
- const titleImage = await downloadPostImage(titleImageJson.source_url, pagesImagesFolder);
132
- const pkg = useBlogPkg ? "@studiocms/blog" : "studiocms/markdown";
133
- await generateCategories(data.categories, endpoint);
134
- await generateTags(data.tags, endpoint);
135
- const pageData = {
136
- id: crypto.randomUUID(),
137
- title: data.title.rendered,
138
- description: decode(stripHtml(data.excerpt.rendered)),
139
- slug: data.slug,
140
- publishedAt: new Date(data.date_gmt),
141
- updatedAt: new Date(data.modified_gmt),
142
- showOnNav: false,
143
- contentLang: "default",
144
- package: pkg,
145
- categories: JSON.stringify(data.categories),
146
- tags: JSON.stringify(data.tags)
147
- };
148
- if (titleImage) {
149
- pageData.heroImage = titleImage;
150
- }
151
- return pageData;
152
- };
153
- const ConvertToPostContent = async (pageData, post) => {
154
- const data = post;
155
- if (pageData.id === void 0) {
156
- throw new Error("pageData is missing id");
157
- }
158
- const cleanupContent = cleanUpHtml(data.content.rendered);
159
- const htmlWithImages = await downloadAndUpdateImages(cleanupContent, postsImagesFolder);
160
- const turndownService = new TurndownService({
161
- bulletListMarker: "-",
162
- codeBlockStyle: "fenced",
163
- emDelimiter: "*"
164
- });
165
- const content = turndownService.turndown(htmlWithImages);
166
- const pageContent = {
167
- id: crypto.randomUUID(),
168
- contentId: pageData.id,
169
- contentLang: "default",
170
- content
171
- };
172
- return pageContent;
173
- };
174
- export {
175
- ConvertToPageContent,
176
- ConvertToPageData,
177
- ConvertToPostContent,
178
- ConvertToPostData,
179
- generateCategories,
180
- generateTags
181
- };
@@ -1,6 +0,0 @@
1
- import type { tsPageContent, tsPageData } from 'studiocms/sdk/tables';
2
- export type PageData = typeof tsPageData.$inferInsert;
3
- export type PageContent = typeof tsPageContent.$inferInsert;
4
- export * from './pages.js';
5
- export * from './posts.js';
6
- export * from './settings.js';
@@ -1,3 +0,0 @@
1
- export * from "./pages.js";
2
- export * from "./posts.js";
3
- export * from "./settings.js";
@@ -1,13 +0,0 @@
1
- /**
2
- * Imports pages from a WordPress API endpoint.
3
- *
4
- * This function fetches all pages from the specified WordPress API endpoint
5
- * and imports each page individually.
6
- *
7
- * @param endpoint - The WordPress API endpoint to fetch pages from.
8
- *
9
- * @returns A promise that resolves when all pages have been imported.
10
- *
11
- * @throws Will throw an error if the pages cannot be imported.
12
- */
13
- export declare const importPagesFromWPAPI: (endpoint: string) => Promise<void>;
@@ -1,38 +0,0 @@
1
- import { db } from "astro:db";
2
- import { tsPageContent, tsPageData } from "studiocms/sdk/tables";
3
- import { ConvertToPageContent, ConvertToPageData } from "./converters.js";
4
- import { apiEndpoint, fetchAll } from "./utils.js";
5
- const generatePageFromData = async (page, endpoint) => {
6
- const pageData = await ConvertToPageData(page, endpoint);
7
- const pageContent = await ConvertToPageContent(pageData, page);
8
- return { pageData, pageContent };
9
- };
10
- const importPage = async (page, endpoint) => {
11
- const { pageData, pageContent } = await generatePageFromData(page, endpoint);
12
- const pageDataResult = await db.insert(tsPageData).values(pageData).returning({ id: tsPageData.id, title: tsPageData.title }).get();
13
- if (pageDataResult === void 0) {
14
- throw new Error("Failed to insert page data");
15
- }
16
- const pageContentResult = await db.insert(tsPageContent).values(pageContent).returning({ id: tsPageContent.id }).get();
17
- if (pageContentResult === void 0) {
18
- throw new Error("Failed to insert page content");
19
- }
20
- console.log("- Imported new page from WP-API: ", pageDataResult.title);
21
- };
22
- const importPagesFromWPAPI = async (endpoint) => {
23
- const url = apiEndpoint(endpoint, "pages");
24
- console.log("fetching pages from: ", url.origin);
25
- const pages = await fetchAll(url);
26
- console.log("Total pages: ", pages.length);
27
- try {
28
- for (const page of pages) {
29
- console.log("importing page:", page.title.rendered);
30
- await importPage(page, endpoint);
31
- }
32
- } catch (error) {
33
- console.error("Failed to import pages from WP-API:", error);
34
- }
35
- };
36
- export {
37
- importPagesFromWPAPI
38
- };
@@ -1,10 +0,0 @@
1
- /**
2
- * Imports posts from a WordPress API endpoint.
3
- *
4
- * @param endpoint - The API endpoint to fetch posts from.
5
- * @param useBlogPkg - A boolean indicating whether to use the blog package.
6
- * @returns A promise that resolves when all posts have been imported.
7
- *
8
- * @throws Will throw an error if the import process fails.
9
- */
10
- export declare const importPostsFromWPAPI: (endpoint: string, useBlogPkg: boolean) => Promise<void>;
@@ -1,38 +0,0 @@
1
- import { db } from "astro:db";
2
- import { tsPageContent, tsPageData } from "studiocms/sdk/tables";
3
- import { ConvertToPostContent, ConvertToPostData } from "./converters.js";
4
- import { apiEndpoint, fetchAll } from "./utils.js";
5
- const generatePostFromData = async (post, useBlogPkg, endpoint) => {
6
- const pageData = await ConvertToPostData(post, useBlogPkg, endpoint);
7
- const pageContent = await ConvertToPostContent(pageData, post);
8
- return { pageData, pageContent };
9
- };
10
- const importPost = async (post, useBlogPkg, endpoint) => {
11
- const { pageData, pageContent } = await generatePostFromData(post, useBlogPkg, endpoint);
12
- const pageDataResult = await db.insert(tsPageData).values(pageData).returning({ id: tsPageData.id, title: tsPageData.title }).get();
13
- if (pageDataResult === void 0) {
14
- throw new Error("Failed to insert post data");
15
- }
16
- const pageContentResult = await db.insert(tsPageContent).values(pageContent).returning({ id: tsPageContent.id }).get();
17
- if (pageContentResult === void 0) {
18
- throw new Error("Failed to insert post content");
19
- }
20
- console.log("- Imported new post from WP-API:", pageDataResult.title);
21
- };
22
- const importPostsFromWPAPI = async (endpoint, useBlogPkg) => {
23
- const url = apiEndpoint(endpoint, "posts");
24
- console.log("Fetching posts from: ", url.origin);
25
- const posts = await fetchAll(url);
26
- console.log("Total posts: ", posts.length);
27
- try {
28
- for (const post of posts) {
29
- console.log("importing post: ", post.title.rendered);
30
- await importPost(post, useBlogPkg, endpoint);
31
- }
32
- } catch (error) {
33
- console.error("Failed to import posts from WP-API: ", error);
34
- }
35
- };
36
- export {
37
- importPostsFromWPAPI
38
- };
@@ -1,18 +0,0 @@
1
- /**
2
- * Imports site settings from a WordPress API endpoint and updates the local database.
3
- *
4
- * @param endpoint - The WordPress API endpoint to fetch settings from.
5
- *
6
- * This function performs the following steps:
7
- * 1. Constructs the URL for the settings endpoint.
8
- * 2. Fetches the site settings from the constructed URL.
9
- * 3. Logs the fetched settings.
10
- * 4. Downloads the site icon if available.
11
- * 5. If the site icon is not available, attempts to download the site logo.
12
- * 6. Constructs the site configuration object.
13
- * 7. Updates the local database with the fetched settings.
14
- * 8. Logs the success or failure of the database update.
15
- *
16
- * @throws Will log an error message if the fetch or database update fails.
17
- */
18
- export declare const importSettingsFromWPAPI: (endpoint: string) => Promise<void>;
@@ -1,45 +0,0 @@
1
- import path from "node:path";
2
- import { db, eq } from "astro:db";
3
- import { userProjectRoot } from "virtual:studiocms-devapps/config";
4
- import { CMSSiteConfigId } from "studiocms/consts";
5
- import { tsSiteConfig } from "studiocms/sdk/tables";
6
- import { apiEndpoint, downloadPostImage } from "./utils.js";
7
- const ASTROPUBLICFOLDER = path.resolve(userProjectRoot, "public");
8
- const importSettingsFromWPAPI = async (endpoint) => {
9
- const url = apiEndpoint(endpoint, "settings");
10
- console.log("Fetching site settings from: ", url.origin);
11
- const response = await fetch(url);
12
- const settings = await response.json();
13
- console.log("Importing site settings: ", settings);
14
- let siteIcon = void 0;
15
- if (settings.site_icon_url) {
16
- siteIcon = await downloadPostImage(settings.site_icon_url, ASTROPUBLICFOLDER);
17
- }
18
- if (!settings.site_icon_url && settings.site_logo) {
19
- const siteLogoURL = apiEndpoint(endpoint, "media", `${settings.site_logo}`);
20
- const siteLogoResponse = await fetch(siteLogoURL);
21
- const siteLogoJson = await siteLogoResponse.json();
22
- siteIcon = await downloadPostImage(siteLogoJson.source_url, ASTROPUBLICFOLDER);
23
- }
24
- const siteConfig = {
25
- id: CMSSiteConfigId,
26
- title: settings.name,
27
- description: settings.description
28
- };
29
- if (siteIcon) {
30
- siteConfig.siteIcon = siteIcon;
31
- }
32
- try {
33
- const insert = await db.update(tsSiteConfig).set(siteConfig).where(eq(tsSiteConfig.id, CMSSiteConfigId)).returning({ id: tsSiteConfig.id }).get();
34
- if (insert) {
35
- console.log("Updated site settings");
36
- } else {
37
- console.error("Failed to update site settings");
38
- }
39
- } catch (error) {
40
- console.error("Failed to import site settings from WP-API: ", error);
41
- }
42
- };
43
- export {
44
- importSettingsFromWPAPI
45
- };
@@ -1,66 +0,0 @@
1
- /**
2
- * Removes all HTML tags from a given string.
3
- *
4
- * @param string - The input string containing HTML tags.
5
- * @returns The input string with all HTML tags removed.
6
- */
7
- export declare function stripHtml(string: string): string;
8
- /**
9
- * Cleans up the provided HTML string by removing certain attributes from images
10
- * and modifying specific elements related to WordPress polls.
11
- *
12
- * @param html - The HTML string to be cleaned up.
13
- * @returns The cleaned-up HTML string.
14
- */
15
- export declare const cleanUpHtml: (html: string) => string;
16
- /**
17
- * Downloads an image from the specified URL and saves it to the given destination.
18
- *
19
- * @param {string | URL} imageUrl - The URL of the image to download.
20
- * @param {string | URL} destination - The file path where the image should be saved.
21
- * @returns {Promise<boolean>} - A promise that resolves to true if the image was successfully downloaded,
22
- * or false if the download failed or the file already exists.
23
- *
24
- * @throws {Error} - Throws an error if there is an issue with the fetch request or file writing.
25
- */
26
- export declare function downloadImage(imageUrl: string | URL, destination: string | URL): Promise<boolean>;
27
- /**
28
- * Downloads an image from the given source URL and saves it to the specified folder.
29
- *
30
- * @param src - The URL of the image to download.
31
- * @param pathToFolder - The path to the folder where the image should be saved.
32
- * @returns The file name of the downloaded image if successful, otherwise `undefined`.
33
- *
34
- * @remarks
35
- * - If the `src` or `pathToFolder` parameters are not provided, the function will return immediately.
36
- * - If the specified folder does not exist, it will be created recursively.
37
- * - If the image already exists in the specified folder, the function will log a message and skip the download.
38
- * - If the image download fails, the source URL will be added to the `imagesNotDownloaded` array.
39
- */
40
- export declare const downloadPostImage: (src: string, pathToFolder: string) => Promise<string | undefined>;
41
- /**
42
- * Downloads and updates the image sources in the provided HTML string.
43
- *
44
- * This function parses the given HTML string, finds all image elements,
45
- * downloads the images to the specified folder, and updates the image
46
- * sources to point to the downloaded images.
47
- *
48
- * @param html - The HTML string containing image elements to be processed.
49
- * @param pathToFolder - The path to the folder where images should be downloaded.
50
- * @returns A promise that resolves to the updated HTML string with new image sources.
51
- */
52
- export declare const downloadAndUpdateImages: (html: string, pathToFolder: string) => Promise<string>;
53
- /**
54
- * Constructs a WordPress API endpoint URL based on the provided parameters.
55
- *
56
- * @param endpoint - The base URL of the WordPress website.
57
- * @param type - The type of resource to access. Can be 'posts', 'pages', 'media', 'categories', 'tags', or 'settings'.
58
- * @param path - An optional path to append to the endpoint.
59
- * @returns The constructed URL object pointing to the desired API endpoint.
60
- * @throws {AstroError} If the `endpoint` argument is missing.
61
- */
62
- export declare const apiEndpoint: (endpoint: string, type: "posts" | "pages" | "media" | "categories" | "tags" | "settings", path?: string) => URL;
63
- /**
64
- * Fetch all pages for a paginated WP endpoint.
65
- */
66
- export declare function fetchAll(url: URL, page?: number, results?: any[]): Promise<any[]>;
@@ -1,138 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { AstroError } from "astro/errors";
4
- import * as cheerio from "cheerio";
5
- const imagesNotDownloaded = [];
6
- function stripHtml(string) {
7
- return string.replace(/<[^>]*>/g, "");
8
- }
9
- const cleanUpHtml = (html) => {
10
- const $ = cheerio.load(html);
11
- const images = $("img");
12
- for (const image of images) {
13
- $(image).removeAttr("class width height data-recalc-dims sizes srcset");
14
- }
15
- $(".wp-polls").html(
16
- "<em>Polls have been temporarily removed while we migrate to a new platform.</em>"
17
- );
18
- $(".wp-polls-loading").remove();
19
- return $.html();
20
- };
21
- async function downloadImage(imageUrl, destination) {
22
- if (fs.existsSync(destination)) {
23
- console.error("File already exists:", destination);
24
- return true;
25
- }
26
- try {
27
- const response = await fetch(imageUrl);
28
- if (response.ok && response.body) {
29
- const reader = response.body.getReader();
30
- const chunks = [];
31
- let done = false;
32
- while (!done) {
33
- const { done: readerDone, value } = await reader.read();
34
- if (value) {
35
- chunks.push(value);
36
- }
37
- done = readerDone;
38
- }
39
- const fileBuffer = Buffer.concat(chunks);
40
- fs.writeFileSync(destination, fileBuffer, { flag: "wx" });
41
- console.log("Downloaded image:", imageUrl);
42
- return true;
43
- }
44
- console.error("Failed to download image:", imageUrl);
45
- return false;
46
- } catch (error) {
47
- console.error("Failed to download image:", imageUrl, error);
48
- return false;
49
- }
50
- }
51
- const downloadPostImage = async (src, pathToFolder) => {
52
- if (!src || !pathToFolder) {
53
- return;
54
- }
55
- if (!fs.existsSync(pathToFolder)) {
56
- fs.mkdirSync(pathToFolder, { recursive: true });
57
- }
58
- const fileName = path.basename(src).split("?")[0];
59
- const destinationFile = path.resolve(pathToFolder, fileName);
60
- if (fs.existsSync(destinationFile)) {
61
- console.log(`Post/Page image "${destinationFile}" already exists, skipping...`);
62
- return fileName;
63
- }
64
- const imageDownloaded = await downloadImage(src, destinationFile);
65
- if (!imageDownloaded) {
66
- imagesNotDownloaded.push(src);
67
- }
68
- return imageDownloaded ? fileName : void 0;
69
- };
70
- const downloadAndUpdateImages = async (html, pathToFolder) => {
71
- const $ = cheerio.load(html);
72
- const images = $("img");
73
- for (const image of images) {
74
- const src = $(image).attr("src");
75
- if (src) {
76
- const newSrc = await downloadPostImage(src, pathToFolder);
77
- $(image).attr("src", newSrc);
78
- }
79
- }
80
- return $.html();
81
- };
82
- const apiEndpoint = (endpoint, type, path2) => {
83
- if (!endpoint) {
84
- throw new AstroError(
85
- "Missing `endpoint` argument.",
86
- "Please pass a URL to your WordPress website as the `endpoint` option to the WordPress importer. Most commonly this looks something like `https://example.com/`"
87
- );
88
- }
89
- let newEndpoint = endpoint;
90
- if (!newEndpoint.endsWith("/")) newEndpoint += "/";
91
- const apiBase = new URL(newEndpoint);
92
- if (type === "settings") {
93
- apiBase.pathname = "wp-json/";
94
- return apiBase;
95
- }
96
- apiBase.pathname = `wp-json/wp/v2/${type}/${path2 ? `${path2}/` : ""}`;
97
- return apiBase;
98
- };
99
- async function fetchAll(url, page = 1, results = []) {
100
- url.searchParams.set("per_page", "100");
101
- url.searchParams.set("page", String(page));
102
- const response = await fetch(url);
103
- let data = await response.json();
104
- if (!Array.isArray(data)) {
105
- if (typeof data === "object") {
106
- data = Object.entries(data).map(([id, val]) => {
107
- if (typeof val === "object") return { id, ...val };
108
- return { id };
109
- });
110
- } else {
111
- throw new AstroError(
112
- "Expected WordPress API to return an array of items.",
113
- `Received ${typeof data}:
114
-
115
- \`\`\`json
116
- ${JSON.stringify(data, null, 2)}
117
- \`\`\``
118
- );
119
- }
120
- }
121
- results.push(...data);
122
- const totalPages = Number.parseInt(response.headers.get("X-WP-TotalPages") || "1");
123
- console.log("Fetched page", page, "of", totalPages);
124
- if (page < totalPages) {
125
- console.log("Fetching next page...");
126
- return fetchAll(url, page + 1, results);
127
- }
128
- return results;
129
- }
130
- export {
131
- apiEndpoint,
132
- cleanUpHtml,
133
- downloadAndUpdateImages,
134
- downloadImage,
135
- downloadPostImage,
136
- fetchAll,
137
- stripHtml
138
- };
package/dist/virt.d.js DELETED
File without changes