@griddo/cx 1.75.193 → 1.75.196

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/src/utils/api.ts CHANGED
@@ -1,4 +1,3 @@
1
- // Types
2
1
  import type {
3
2
  APIRequest,
4
3
  APIResponses,
@@ -6,19 +5,17 @@ import type {
6
5
  GetAPI,
7
6
  PostAPI,
8
7
  PutAPI,
8
+ ShowApiErrorOptions,
9
9
  } from "../types/api";
10
+ import type { Method } from "axios";
10
11
 
11
- // External libraries
12
- import axios, { Method } from "axios";
12
+ import axios from "axios";
13
13
  import chalk from "chalk";
14
14
  import dotenv from "dotenv";
15
15
 
16
- // Services
17
- import { AuthService } from "../services/auth";
18
-
19
- // Utils
20
16
  import { getCache, saveCache } from "./cache";
21
17
  import { delay, getSafeSiteId, logInfo, msToSec } from "./shared";
18
+ import { AuthService } from "../services/auth";
22
19
 
23
20
  dotenv.config();
24
21
 
@@ -32,7 +29,7 @@ const {
32
29
  *
33
30
  * @template T Response Type returned.
34
31
  * @returns {Promise<T>} A promise that is resolved with the data from the API response.
35
- * @todo Maybe remove the loggin responsability
32
+ *
36
33
  * @example
37
34
  * const response = await requestAPI<Site>({
38
35
  * endpoint: "...",
@@ -69,14 +66,13 @@ async function requestAPI<T extends APIResponses>(
69
66
  } catch (e) {
70
67
  const error = e as Error;
71
68
 
72
- showApiError(
73
- error,
74
- { endpoint, body, attempt },
75
- error.response.status !== 404
76
- );
69
+ showApiError(error, {
70
+ callInfo: { endpoint, body, attempt },
71
+ breakProcess: error.response.status !== 404,
72
+ });
77
73
 
78
74
  if (error.response.status === 404) {
79
- // @ts-expect-error
75
+ // @ts-expect-error page maybe will be 404
80
76
  return null;
81
77
  }
82
78
 
@@ -98,6 +94,12 @@ async function requestAPI<T extends APIResponses>(
98
94
  }
99
95
  }
100
96
 
97
+ /**
98
+ * Make a GET request to the Griddo API.
99
+ *
100
+ * @template T Response Type returned.
101
+ * @returns A promise that is resolved with the data from the API response.
102
+ */
101
103
  async function getApi<T extends APIResponses>(props: GetAPI) {
102
104
  // Starts
103
105
  const start = new Date();
@@ -117,6 +119,12 @@ async function getApi<T extends APIResponses>(props: GetAPI) {
117
119
  return response;
118
120
  }
119
121
 
122
+ /**
123
+ * Make a PUT request to the Griddo API.
124
+ *
125
+ * @template T Response Type returned.
126
+ * @returns A promise that is resolved with the data from the API response.
127
+ */
120
128
  async function putApi<T extends APIResponses>(props: PutAPI) {
121
129
  // Starts
122
130
  const start = new Date();
@@ -134,6 +142,12 @@ async function putApi<T extends APIResponses>(props: PutAPI) {
134
142
  return response;
135
143
  }
136
144
 
145
+ /**
146
+ * Make a POST request to the Griddo API.
147
+ *
148
+ * @template T Response Type returned.
149
+ * @returns A promise that is resolved with the data from the API response.
150
+ */
137
151
  async function postApi<T extends APIResponses>(props: PostAPI) {
138
152
  // Starts
139
153
  const start = new Date();
@@ -161,18 +175,9 @@ async function postApi<T extends APIResponses>(props: PostAPI) {
161
175
  /**
162
176
  * Shows an API error through the terminal.
163
177
  */
164
- function showApiError(
165
- error: Error,
166
- callInfo: {
167
- endpoint?: string;
168
- // TODO: Remove any's
169
- body?: any;
170
- headers?: any;
171
- attempt?: number;
172
- } = {},
173
- breakProcess = true
174
- ) {
178
+ function showApiError(error: Error, options: ShowApiErrorOptions) {
175
179
  const { response, message, stack } = error;
180
+ const { breakProcess, callInfo } = options;
176
181
  const { status, statusText, data } = response || {};
177
182
  const callInfoArray = [];
178
183
 
@@ -1,13 +1,11 @@
1
- // Types
2
1
  import type { Petition } from "../types/global";
3
2
  import type { HashSites, SiteHash } from "../types/sites";
4
3
 
5
- // External libraries
6
4
  import crypto from "crypto";
7
5
  import fs from "fs";
8
6
  import path from "path";
9
7
 
10
- // Constants
8
+ // Consts
11
9
  const API_CACHE_DIR_PATH = path.resolve(__dirname, "./../../apiCache");
12
10
  const SITE_HASH_FILENAME = `${API_CACHE_DIR_PATH}/siteHash.json`;
13
11
 
@@ -24,8 +22,8 @@ function initCache() {
24
22
 
25
23
  /**
26
24
  * Generate a filename with a hash using a Petition object
27
- * TODO: Merge with createSha256
28
25
  *
26
+ * @todo Merge with createSha256
29
27
  * @param petition An object
30
28
  */
31
29
  function generateFilenameWithHash(petition: Petition) {
@@ -37,8 +35,8 @@ function generateFilenameWithHash(petition: Petition) {
37
35
 
38
36
  /**
39
37
  * Generate a filename with a hash using a string.
40
- * TODO: Merge with generateFilenameWithHash
41
38
  *
39
+ * @todo Merge with generateFilenameWithHash
42
40
  * @param data A string to create a sha256 based on.
43
41
  */
44
42
  function createSha256(data: string) {
@@ -54,11 +52,11 @@ function createSha256(data: string) {
54
52
  * @param petition An object.
55
53
  * @param content Content to be saved.
56
54
  */
57
- const saveCache = <T>(petition: Petition, content: T) => {
55
+ function saveCache<T>(petition: Petition, content: T) {
58
56
  const stringContent =
59
57
  typeof content === "string" ? content : JSON.stringify(content);
60
58
  fs.writeFileSync(generateFilenameWithHash(petition), stringContent, "utf8");
61
- };
59
+ }
62
60
 
63
61
  /**
64
62
  * Read a cache file and return it as an object
@@ -1,7 +1,5 @@
1
- // Types
2
1
  import type { Domains } from "../types/global";
3
2
 
4
- // Services
5
3
  import { AuthService } from "../services/auth";
6
4
  import { DomainsService } from "../services/domains";
7
5
 
@@ -1,11 +1,9 @@
1
- // Types
2
1
  import type { Site } from "../types/sites";
3
2
 
4
- // External libraries
5
- import fs from "fs-extra";
6
3
  import path from "path";
7
4
 
8
- // Utils
5
+ import fs from "fs-extra";
6
+
9
7
  import { resolveComponentsPath } from "./instance";
10
8
  import { logInfo } from "./shared";
11
9
 
@@ -107,21 +105,6 @@ async function updateDist() {
107
105
  }
108
106
  }
109
107
 
110
- /**
111
- * Copy the Griddo's `/dist` folder into the Griddo's `/public` folder.
112
- */
113
- async function prepareServe() {
114
- const src = "./dist";
115
- const dest = "./public";
116
-
117
- try {
118
- await fs.copy(src, dest);
119
- logInfo("Public copied");
120
- } catch (err) {
121
- console.warn("error", err);
122
- }
123
- }
124
-
125
108
  /**
126
109
  * Copy the instance's `/static` folder into the Gatsby's to take it into account for bundle.
127
110
  */
@@ -144,4 +127,4 @@ function prepareStaticFolder() {
144
127
  }
145
128
  }
146
129
 
147
- export { deleteSites, updateDist, prepareServe, prepareStaticFolder };
130
+ export { deleteSites, updateDist, prepareStaticFolder };
@@ -0,0 +1,41 @@
1
+ import type { GatsbyNode } from "gatsby";
2
+
3
+ import { IS_COMPONENT_LIBRARY, PROJECT_ALIASES } from "./instance";
4
+
5
+ // TODO: Use webpack types
6
+ const onCreateWebpackConfig: GatsbyNode["onCreateWebpackConfig"] = ({
7
+ actions,
8
+ plugins,
9
+ loaders,
10
+ getConfig,
11
+ }) => {
12
+ if (IS_COMPONENT_LIBRARY) {
13
+ const config = getConfig();
14
+ config.module.rules = [
15
+ // Omit the default rule where test === '\.jsx?$'
16
+ ...config.module.rules.filter(
17
+ (rule: { test: string }) => String(rule.test) !== String(/\.jsx?$/)
18
+ ),
19
+ // Recreate it with custom exclude filter
20
+ {
21
+ ...loaders.js(),
22
+ test: /\.jsx?$/,
23
+ // Exclude all node_modules from transpilation, except for '@griddo/cx'
24
+ exclude: (modulePath: string) =>
25
+ /node_modules/.test(modulePath) && !/@griddo\/cx/.test(modulePath),
26
+ },
27
+ ];
28
+ actions.replaceWebpackConfig(config);
29
+ }
30
+
31
+ // Add component-system aliases to Webpack's Resolve:
32
+ actions.setWebpackConfig({
33
+ resolve: {
34
+ fallback: { path: false },
35
+ alias: PROJECT_ALIASES,
36
+ },
37
+ plugins: [plugins.provide({ process: "process/browser", React: "react" })],
38
+ });
39
+ };
40
+
41
+ export { onCreateWebpackConfig };
@@ -1,11 +1,11 @@
1
- // External libraries
2
- import findUp from "find-up";
3
1
  import path from "path";
2
+
3
+ import findUp from "find-up";
4
4
  import pkgDir from "pkg-dir";
5
5
 
6
- // Envs
7
- const isComponentLibraryEnv = __dirname.includes("node_modules");
8
- const projectAliases = getComponentsLibAliases();
6
+ // Consts
7
+ const IS_COMPONENT_LIBRARY = __dirname.includes("node_modules");
8
+ const PROJECT_ALIASES = getComponentsLibAliases();
9
9
 
10
10
  /**
11
11
  * Returns the instance or monorepo paths.
@@ -13,7 +13,7 @@ const projectAliases = getComponentsLibAliases();
13
13
  * @param customPath The path for the instance components
14
14
  */
15
15
  function resolveComponentsPath(customPath = "") {
16
- return isComponentLibraryEnv
16
+ return IS_COMPONENT_LIBRARY
17
17
  ? path.resolve(pkgDir.sync(__dirname) as string, "../../../", customPath)
18
18
  : path.resolve(
19
19
  pkgDir.sync(__dirname) as string,
@@ -40,6 +40,7 @@ function getComponentsJSConfig() {
40
40
  * Get the instance webpack aliases
41
41
  */
42
42
  function getComponentsLibAliases() {
43
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
43
44
  const xsConfig = require(getComponentsJSConfig() as string);
44
45
 
45
46
  return Object.keys(xsConfig?.compilerOptions?.paths).reduce(
@@ -65,7 +66,7 @@ function getComponentsLibAliases() {
65
66
  export {
66
67
  getComponentsJSConfig,
67
68
  getComponentsLibAliases,
68
- isComponentLibraryEnv,
69
- projectAliases,
69
+ IS_COMPONENT_LIBRARY,
70
+ PROJECT_ALIASES,
70
71
  resolveComponentsPath,
71
72
  };
@@ -1,5 +1,3 @@
1
- // Types
2
- import type { Core, Fields } from "@griddo/core";
3
1
  import type {
4
2
  APIPageObject,
5
3
  GatsbyPageObject,
@@ -10,15 +8,15 @@ import type {
10
8
  PageAdditionalInfo,
11
9
  } from "../types/pages";
12
10
  import type { TemplateWithDistributor } from "../types/templates";
11
+ import type { Core, Fields } from "@griddo/core";
13
12
 
14
- // External libraries
15
- import dotenv from "dotenv";
16
13
  import fs from "fs";
17
14
  import path from "path";
18
15
 
19
- // Utils
20
- import { formatImage } from "../components/utils";
16
+ import dotenv from "dotenv";
17
+
21
18
  import { postSearchInfo } from "./searches";
19
+ import { formatImage } from "../components/utils";
22
20
 
23
21
  dotenv.config();
24
22
 
@@ -28,7 +26,7 @@ const GRIDDO_SEARCH_FEATURE = !!JSON.parse(
28
26
  );
29
27
  const HAS_ASSET_PREFIX = !!process.env.GRIDDO_ASSET_PREFIX;
30
28
 
31
- // Constants
29
+ // Consts
32
30
  const DEFAULT_ITEMS_PER_PAGE_FOR_LIST_TEMPLATES = 25;
33
31
  const COMPONENT = path.resolve(__dirname, "../../src/components/template.tsx");
34
32
 
@@ -328,7 +326,7 @@ function createGriddoMultiPages(
328
326
  ({ sectionSlug }: { sectionSlug: string }) => sectionSlug === "/"
329
327
  )
330
328
  ) {
331
- // @ts-expect-error
329
+ // @ts-expect-error ? ? ?
332
330
  multiPageElements.push({});
333
331
  }
334
332
 
@@ -384,7 +382,7 @@ function getMultiPageElements(page: TemplateWithDistributor) {
384
382
  const getMultiPageComponent = (
385
383
  // No puede ser Core.Page['template'] porque a medida que va bajando en
386
384
  // el árbol ya no es la estructura de un template.
387
- template: Record<string, any>,
385
+ template: Record<string, unknown>,
388
386
  level = 0
389
387
  ) => {
390
388
  // If it doesn't have a "template strcuture"
@@ -392,7 +390,11 @@ function getMultiPageElements(page: TemplateWithDistributor) {
392
390
 
393
391
  // For each prop in the "template"
394
392
  for (const key in template) {
395
- const currentComponent = template[key];
393
+ const currentComponent = template[key] as {
394
+ component: string;
395
+ hasGriddoMultiPage: boolean;
396
+ elements: Array<Record<string, unknown>>;
397
+ };
396
398
  const isValidComponent =
397
399
  currentComponent || typeof currentComponent === "object";
398
400
  const hasGriddoMultiPageProp = JSON.stringify(
@@ -415,7 +417,9 @@ function getMultiPageElements(page: TemplateWithDistributor) {
415
417
  if (!level) resolve(null);
416
418
  };
417
419
 
418
- getMultiPageComponent([page]); // ==> En array para que también revise la propia template como objeto.
420
+ // `page` en un array para que también revise la propia template como objeto.
421
+ // @ts-expect-error remove the array
422
+ getMultiPageComponent([page]);
419
423
  });
420
424
 
421
425
  return multiPageElements as Promise<MultiPageElements>;
@@ -492,7 +496,6 @@ function getPaginatedPages(listTemplate: TemplateWithDistributor) {
492
496
  * addPageNumberToUrl("web.com", 3) // "web.com/3"
493
497
  * addPageNumberToUrl("web.com", 3, { addEndingSlash: true }) // "web.com/3/"
494
498
  */
495
-
496
499
  function addPageNumberToUrl(
497
500
  url: string,
498
501
  pageNumber: number,
@@ -1,8 +1,6 @@
1
- // Types
2
1
  import type { PostSearchInfoResponse } from "../types/api";
3
2
  import type { PostSearchInfoProps } from "../types/global";
4
3
 
5
- // API
6
4
  import { post } from "./api";
7
5
 
8
6
  // Envs
@@ -1,10 +1,11 @@
1
- // External libraries
2
1
  import chalk from "chalk";
3
2
  import dotenv from "dotenv";
4
3
  import fs from "fs-extra";
5
4
  import gradient from "gradient-string";
6
- import { APIResponses } from "../types/api";
5
+
7
6
  import { version } from "../../package.json";
7
+ import { APIResponses } from "../types/api";
8
+ import { Site } from "../types/sites";
8
9
 
9
10
  dotenv.config();
10
11
 
@@ -48,7 +49,7 @@ function logBox(str: string) {
48
49
  /**
49
50
  * Custom basic logging function controlled by a environment variable.
50
51
  *
51
- * @params str The string or strings separated by commans to be logged.
52
+ * @param str The string or strings separated by commans to be logged.
52
53
  */
53
54
  function logInfo(...str: Array<unknown>) {
54
55
  if (GRIDDO_BUILD_LOGS) {
@@ -124,40 +125,61 @@ function measureFunctions(...funcs: Array<() => void>) {
124
125
  }
125
126
 
126
127
  /**
127
- * Print a f**king great Griddo builder logo.
128
+ * Remove props from an object
129
+ *
130
+ * @param obj The object
131
+ * @param props An array of props to be removed
132
+ */
133
+ function removeProperties(obj: Record<string, unknown>, props: Array<string>) {
134
+ for (const key in obj) {
135
+ if (props.includes(key)) {
136
+ delete obj[key];
137
+ } else if (typeof obj[key] === "object") {
138
+ removeProperties(obj[key] as Record<string, unknown>, props);
139
+ }
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Return a list of sites with their names and ids.
145
+ *
146
+ * @param sites An array of sites objects
147
+ */
148
+ function siteList(sites: Array<Site>) {
149
+ return sites.map(({ name, id }) => `${name} (${id})`).join(", ");
150
+ }
151
+
152
+ /**
153
+ * Print a f**king great Griddo build domain logo.
128
154
  */
129
155
  function splash() {
130
156
  const logo = `
131
- ··
132
- ·· ______ ______ _____ ______ ______ _____
133
- ·· | ____ |_____/ | | \\ | \\ | |
134
- ·· |_____| | \\_ __|__ |_____/ |_____/ |_____|
135
- ·· ______ _ _ _____ ______ _______ ______
136
- ·· |_____] | | | | | \\ |______ |_____/
137
- ·· |_____] |_____| __|__ |_____ |_____/ |______ | \\_
138
- ··
139
- ·· ${version}
157
+ ___ _ _ _ _ ___ ___ ____ _ _ ____ _ __ _
158
+ |==] |__| | |___ |__> |__> [__] |\\/| |--| | | \\|
140
159
  `;
141
160
 
142
161
  console.log(gradient.cristal(logo));
143
162
  }
144
163
 
164
+ /**
165
+ * Print a f**king great Griddo builder logo.
166
+ */
145
167
  function exporterLogo() {
146
168
  const logo = `
147
169
  ··
148
- ·· /
149
- ·· / //
150
- ·· ______ ______ _____ ______ ______ _____ /· /
151
- ·· | ____ |_____/ | | \\ | \\ | | / · / /
152
- ·· |_____| | \\_ __|__ |_____/ |_____/ |_____| · · / / · /
170
+ ··
171
+ ··
172
+ ·· ______ ______ _____ ______ ______ _____
173
+ ·· | ____ |_____/ | | \\ | \\ | |
174
+ ·· |_____| | \\_ __|__ |_____/ |_____/ |_____|
153
175
  ·· _______ _ _ _____ _____ ______ _______ _______ ______
154
176
  ·· |______ \\___/ |_____] | | |_____/ | |______ |_____/
155
177
  ·· |______ _/ \\_ | |_____| | \\_ | |______ | \\_
156
178
  ··
157
- ·· Griddo exporter orchestrator / / / · / /
158
- ·· ${version} / / /· /
159
- ·· /· /
160
- ·· /
179
+ ·· Griddo exporter orchestrator
180
+ ·· ${version}
181
+ ··
182
+ ··
161
183
  ··
162
184
  `;
163
185
 
@@ -171,6 +193,8 @@ export {
171
193
  logInfo,
172
194
  logPageSize,
173
195
  measureFunctions,
196
+ removeProperties,
197
+ siteList,
174
198
  splash,
175
199
  walk,
176
200
  };
@@ -1,21 +1,17 @@
1
- // Types
2
1
  import type { BuildProcessData } from "../types/global";
3
2
  import type { Site, SiteData } from "../types/sites";
4
3
 
5
- // External libraries
4
+ import path from "path";
5
+
6
6
  import chalk from "chalk";
7
7
  import fs from "fs-extra";
8
8
  import { parse } from "js2xmlparser";
9
- import path from "path";
10
9
 
11
- // Services
10
+ import { deleteSites } from "./folders";
11
+ import { logInfo } from "./shared";
12
12
  import { AuthService } from "../services/auth";
13
13
  import { SitesService } from "../services/sites";
14
-
15
- // Utils
16
14
  import { AllPagesResponse } from "../types/api";
17
- import { deleteSites } from "./folders";
18
- import { logInfo } from "./shared";
19
15
 
20
16
  // Envs
21
17
  const API_URL = process.env.API_URL;
@@ -55,13 +51,12 @@ async function checkSites() {
55
51
  const langResponse = await SitesService.getLanguages(site.id);
56
52
 
57
53
  return (site.domains = langResponse.items
58
- .filter((item) => {
59
- return (
54
+ .filter(
55
+ (item) =>
60
56
  item.domain &&
61
57
  (!process.env.DOMAIN ||
62
58
  item.domain.slug.indexOf(process.env.DOMAIN) > 0)
63
- );
64
- })
59
+ )
65
60
  .map((item) => ({ [item.id]: `${item.domain.slug}${item.path}` })));
66
61
  });
67
62
 
@@ -126,8 +121,8 @@ async function getSiteData(siteID: number, cached: boolean) {
126
121
  const socials = await SitesService.getSocials(siteID, cached);
127
122
  const siteLangsInfo = siteLangs.items;
128
123
  const defaultLang = siteLangsInfo.find((lang) => lang.isDefault);
129
- // eliminado para validar que efectivamente no rompe nada
130
- // si el cambio es correcto, hay que eliminar las 7 líneas que contienen "sitePages"
124
+ // TODO: Eliminado para validar que efectivamente no rompe nada si el cambio
125
+ // es correcto, hay que eliminar las 7 líneas que contienen "sitePages":
131
126
  // const sitePages = await SitesService.getPages(siteID, cached);
132
127
  const sitePages: AllPagesResponse = [];
133
128
 
@@ -154,18 +149,36 @@ async function getSiteData(siteID: number, cached: boolean) {
154
149
  }
155
150
 
156
151
  /**
157
- * Send end render signal to the API for all pages.
152
+ * Save a file with the end of build process
158
153
  *
154
+ * @param filePathName The pathname for the file report
159
155
  * @param buildProcessData The whole build process data.
160
- * @param createdPages An array of pages ids.
161
156
  */
162
- async function setPagesRenderEnd(
163
- buildProcessData: BuildProcessData,
164
- createdPages: Array<number>
157
+ async function generateBuildReport(
158
+ filePathName: string,
159
+ buildProcessData: BuildProcessData
165
160
  ) {
161
+ // Get the token
162
+ const authControl = await AuthService.login();
163
+
164
+ const buildSitesInfo = Object.keys(buildProcessData).map((siteID) => ({
165
+ ...buildProcessData[siteID],
166
+ siteId: parseInt(siteID),
167
+ }));
168
+
169
+ const report = {
170
+ authControl,
171
+ sites: buildSitesInfo,
172
+ };
173
+
174
+ fs.writeFileSync(filePathName, JSON.stringify(report));
175
+
176
+ logInfo(`Build report saved for ${buildSitesInfo.length} site(s)`);
177
+
178
+ // API version
179
+ // TODO: Revemo when the file version is implemented.
166
180
  const promises = Object.keys(buildProcessData).map(async (siteID) => {
167
181
  const body = buildProcessData[siteID];
168
-
169
182
  logInfo(`Deploying ending call to site ${siteID}:`);
170
183
 
171
184
  return SitesService.endSiteRender(parseInt(siteID), body);
@@ -173,7 +186,7 @@ async function setPagesRenderEnd(
173
186
 
174
187
  await Promise.all(promises);
175
188
 
176
- logInfo(`Set pages as deployed. Total ${createdPages.length}`);
189
+ logInfo(`Build end signal sent for ${buildSitesInfo.length} site(s)`);
177
190
  }
178
191
 
179
192
  /**
@@ -273,7 +286,7 @@ function saveFile(filePath: string, content: string) {
273
286
  export {
274
287
  checkSites,
275
288
  unpublishSites,
276
- setPagesRenderEnd,
289
+ generateBuildReport,
277
290
  getSiteData,
278
291
  generateSitemaps,
279
292
  };