@griddo/cx 11.9.7-rc.2 → 11.9.8-rc.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 (222) hide show
  1. package/README.md +78 -193
  2. package/build/commands/end-render.js +31 -0
  3. package/build/commands/end-render.js.map +7 -0
  4. package/build/commands/prepare-assets-directory.js +9 -0
  5. package/build/commands/prepare-assets-directory.js.map +7 -0
  6. package/build/commands/prepare-domains-render.js +38 -0
  7. package/build/commands/prepare-domains-render.js.map +7 -0
  8. package/build/commands/reset-render.js +31 -0
  9. package/build/commands/reset-render.js.map +7 -0
  10. package/build/commands/start-embeddings.js +31 -0
  11. package/build/commands/start-embeddings.js.map +7 -0
  12. package/build/commands/start-render.js +66 -0
  13. package/build/commands/start-render.js.map +7 -0
  14. package/build/commands/upload-search-content.js +31 -0
  15. package/build/commands/upload-search-content.js.map +7 -0
  16. package/build/core/GriddoLog.d.ts +16 -0
  17. package/build/core/db.d.ts +4 -0
  18. package/build/core/dist-rollback.d.ts +2 -0
  19. package/build/{errors/index.d.ts → core/errors.d.ts} +5 -4
  20. package/build/core/fs.d.ts +69 -0
  21. package/build/core/logger.d.ts +18 -0
  22. package/build/index.d.ts +10 -29
  23. package/build/index.js +406 -73
  24. package/build/services/auth.d.ts +2 -5
  25. package/build/services/manage-store.d.ts +48 -0
  26. package/build/services/render.d.ts +70 -0
  27. package/build/shared/envs.d.ts +19 -0
  28. package/build/{errors/errors-data.d.ts → shared/errors.d.ts} +5 -3
  29. package/build/shared/npm-modules/brush.d.ts +18 -0
  30. package/build/shared/npm-modules/find-up-simple.d.ts +34 -0
  31. package/build/shared/npm-modules/pkg-dir.d.ts +7 -0
  32. package/build/{types → shared/types}/api.d.ts +18 -18
  33. package/build/{types → shared/types}/global.d.ts +15 -16
  34. package/build/{types → shared/types}/navigation.d.ts +5 -5
  35. package/build/{types → shared/types}/pages.d.ts +9 -9
  36. package/build/shared/types/render.d.ts +54 -0
  37. package/build/{types → shared/types}/sites.d.ts +18 -19
  38. package/cli.mjs +239 -0
  39. package/exporter/build-esbuild.noop +42 -0
  40. package/exporter/build.sh +17 -28
  41. package/exporter/commands/README.md +151 -0
  42. package/exporter/commands/end-render.ts +65 -86
  43. package/exporter/commands/prepare-assets-directory.ts +34 -0
  44. package/exporter/commands/prepare-domains-render.ts +143 -35
  45. package/exporter/commands/reset-render.ts +12 -7
  46. package/exporter/commands/single-domain-upload-search-content.noop +206 -0
  47. package/exporter/commands/start-embeddings.ts +29 -0
  48. package/exporter/commands/start-render.ts +26 -64
  49. package/exporter/commands/upload-search-content.ts +201 -26
  50. package/exporter/core/GriddoLog.ts +45 -0
  51. package/exporter/core/check-env-health.ts +200 -0
  52. package/exporter/core/db-class.ts +54 -0
  53. package/exporter/core/db.ts +33 -0
  54. package/exporter/core/dist-rollback.ts +40 -0
  55. package/exporter/core/errors.ts +82 -0
  56. package/exporter/core/fs.ts +385 -0
  57. package/exporter/{utils → core}/images.ts +1 -6
  58. package/exporter/{utils → core}/instance.ts +9 -13
  59. package/exporter/core/life-cycle.ts +73 -0
  60. package/exporter/core/logger.ts +141 -0
  61. package/exporter/core/objects.ts +37 -0
  62. package/exporter/core/print-logos.ts +21 -0
  63. package/exporter/index.ts +14 -56
  64. package/exporter/services/api.ts +306 -0
  65. package/exporter/services/auth.ts +8 -10
  66. package/exporter/services/domains.ts +23 -8
  67. package/exporter/services/manage-sites.ts +116 -0
  68. package/exporter/services/manage-store.ts +235 -0
  69. package/exporter/services/navigation.ts +12 -18
  70. package/exporter/{utils → services}/pages.ts +27 -92
  71. package/exporter/services/reference-fields.ts +14 -32
  72. package/exporter/services/render-artifacts.ts +44 -0
  73. package/exporter/services/render.ts +229 -0
  74. package/exporter/services/robots.ts +33 -61
  75. package/exporter/services/sitemaps.ts +129 -0
  76. package/exporter/services/sites.ts +40 -28
  77. package/exporter/services/store.ts +386 -319
  78. package/exporter/shared/context.ts +49 -0
  79. package/exporter/{constants → shared}/endpoints.ts +12 -11
  80. package/exporter/shared/envs.ts +62 -0
  81. package/exporter/{errors/errors-data.ts → shared/errors.ts} +24 -14
  82. package/exporter/shared/npm-modules/README.md +36 -0
  83. package/exporter/shared/npm-modules/brush.ts +34 -0
  84. package/exporter/shared/npm-modules/find-up-simple.ts +100 -0
  85. package/exporter/shared/npm-modules/pkg-dir.ts +17 -0
  86. package/exporter/shared/npm-modules/xml-parser.ts +57 -0
  87. package/exporter/{types → shared/types}/api.ts +40 -41
  88. package/exporter/{types → shared/types}/global.ts +17 -21
  89. package/exporter/{types → shared/types}/navigation.ts +3 -3
  90. package/exporter/{types → shared/types}/pages.ts +10 -11
  91. package/exporter/shared/types/render.ts +63 -0
  92. package/exporter/{types → shared/types}/sites.ts +18 -19
  93. package/exporter/ssg-adapters/gatsby/actions/clean.ts +26 -0
  94. package/exporter/ssg-adapters/gatsby/actions/close.ts +17 -0
  95. package/exporter/ssg-adapters/gatsby/actions/data.ts +22 -0
  96. package/exporter/ssg-adapters/gatsby/actions/healthCheck.ts +10 -0
  97. package/exporter/ssg-adapters/gatsby/actions/init.ts +12 -0
  98. package/exporter/ssg-adapters/gatsby/actions/logs.ts +10 -0
  99. package/exporter/ssg-adapters/gatsby/actions/meta.ts +13 -0
  100. package/exporter/ssg-adapters/gatsby/actions/prepare.ts +9 -0
  101. package/exporter/ssg-adapters/gatsby/actions/relocation.ts +15 -0
  102. package/exporter/ssg-adapters/gatsby/actions/restore.ts +21 -0
  103. package/exporter/ssg-adapters/gatsby/actions/ssg.ts +12 -0
  104. package/exporter/ssg-adapters/gatsby/actions/sync.ts +65 -0
  105. package/exporter/ssg-adapters/gatsby/index.ts +114 -0
  106. package/exporter/ssg-adapters/gatsby/shared/artifacts.ts +16 -0
  107. package/exporter/ssg-adapters/gatsby/shared/diff-assets.ts +128 -0
  108. package/exporter/ssg-adapters/gatsby/shared/extract-assets.ts +75 -0
  109. package/exporter/ssg-adapters/gatsby/shared/gatsby-build.ts +58 -0
  110. package/exporter/ssg-adapters/gatsby/shared/sync-render.ts +300 -0
  111. package/exporter/ssg-adapters/gatsby/shared/types.ts +35 -0
  112. package/exporter/ssg-adapters/gatsby/shared/utils.ts +33 -0
  113. package/gatsby-browser.tsx +41 -58
  114. package/gatsby-config.ts +10 -17
  115. package/gatsby-node.ts +20 -80
  116. package/gatsby-ssr.tsx +2 -1
  117. package/package.json +41 -92
  118. package/plugins/gatsby-plugin-svgr-loader/gatsby-node.js +55 -0
  119. package/plugins/gatsby-plugin-svgr-loader/package.json +8 -0
  120. package/react/DynamicScript/index.tsx +33 -0
  121. package/{exporter/react/Favicon → react/GriddoFavicon}/index.tsx +3 -9
  122. package/{exporter/react → react}/GriddoIntegrations/index.tsx +17 -23
  123. package/{exporter/react → react}/GriddoIntegrations/utils.ts +24 -12
  124. package/react/GriddoOpenGraph/index.tsx +39 -0
  125. package/src/components/Head.tsx +30 -73
  126. package/src/components/template.tsx +8 -30
  127. package/src/gatsby-node-utils.ts +76 -2
  128. package/src/html.tsx +2 -11
  129. package/src/types.ts +5 -5
  130. package/tsconfig.commands.json +36 -0
  131. package/tsconfig.exporter.json +20 -0
  132. package/tsconfig.json +5 -3
  133. package/build/adapters/gatsby/index.d.ts +0 -4
  134. package/build/adapters/gatsby/utils.d.ts +0 -22
  135. package/build/artifacts/index.d.ts +0 -6
  136. package/build/commands/end-render.d.ts +0 -2
  137. package/build/commands/move-assets.d.ts +0 -1
  138. package/build/commands/prepare-domains-render.d.ts +0 -1
  139. package/build/commands/reset-render.d.ts +0 -2
  140. package/build/commands/start-render.d.ts +0 -2
  141. package/build/commands/upload-search-content.d.ts +0 -2
  142. package/build/constants/envs.d.ts +0 -37
  143. package/build/constants/index.d.ts +0 -57
  144. package/build/end-render.js +0 -74
  145. package/build/end-render.js.map +0 -7
  146. package/build/index.js.map +0 -7
  147. package/build/prepare-domains-render.js +0 -73
  148. package/build/prepare-domains-render.js.map +0 -7
  149. package/build/react/Favicon/index.d.ts +0 -5
  150. package/build/react/Favicon/utils.d.ts +0 -9
  151. package/build/react/GriddoIntegrations/index.d.ts +0 -20
  152. package/build/react/GriddoIntegrations/utils.d.ts +0 -26
  153. package/build/react/index.d.ts +0 -3
  154. package/build/react/index.js +0 -3
  155. package/build/registers/api.d.ts +0 -9
  156. package/build/registers/gatsby.d.ts +0 -9
  157. package/build/registers/index.d.ts +0 -3
  158. package/build/reset-render.js +0 -74
  159. package/build/reset-render.js.map +0 -7
  160. package/build/services/domains.d.ts +0 -6
  161. package/build/services/navigation.d.ts +0 -50
  162. package/build/services/reference-fields.d.ts +0 -20
  163. package/build/services/register.d.ts +0 -36
  164. package/build/services/robots.d.ts +0 -19
  165. package/build/services/settings.d.ts +0 -4
  166. package/build/services/sites.d.ts +0 -29
  167. package/build/services/store.d.ts +0 -6
  168. package/build/start-render.js +0 -100
  169. package/build/start-render.js.map +0 -7
  170. package/build/types/templates.d.ts +0 -8
  171. package/build/upload-search-content.js +0 -74
  172. package/build/upload-search-content.js.map +0 -7
  173. package/build/utils/alerts.d.ts +0 -3
  174. package/build/utils/api.d.ts +0 -23
  175. package/build/utils/cache.d.ts +0 -35
  176. package/build/utils/core-utils.d.ts +0 -107
  177. package/build/utils/create-build-data.d.ts +0 -8
  178. package/build/utils/domains.d.ts +0 -13
  179. package/build/utils/folders.d.ts +0 -53
  180. package/build/utils/health-checks.d.ts +0 -7
  181. package/build/utils/images.d.ts +0 -16
  182. package/build/utils/loggin.d.ts +0 -51
  183. package/build/utils/pages.d.ts +0 -34
  184. package/build/utils/render.d.ts +0 -13
  185. package/build/utils/searches.d.ts +0 -15
  186. package/build/utils/sites.d.ts +0 -31
  187. package/build/utils/store.d.ts +0 -81
  188. package/cx.config.d.ts +0 -5
  189. package/cx.config.js +0 -36
  190. package/exporter/adapters/gatsby/index.ts +0 -162
  191. package/exporter/adapters/gatsby/utils.ts +0 -161
  192. package/exporter/artifacts/README.md +0 -34
  193. package/exporter/artifacts/index.ts +0 -33
  194. package/exporter/commands/move-assets.ts +0 -11
  195. package/exporter/constants/envs.ts +0 -94
  196. package/exporter/constants/index.ts +0 -129
  197. package/exporter/errors/index.ts +0 -40
  198. package/exporter/react/index.tsx +0 -11
  199. package/exporter/registers/api.ts +0 -14
  200. package/exporter/registers/gatsby.ts +0 -14
  201. package/exporter/registers/index.ts +0 -4
  202. package/exporter/services/register.ts +0 -113
  203. package/exporter/services/settings.ts +0 -17
  204. package/exporter/utils/alerts.ts +0 -29
  205. package/exporter/utils/api.ts +0 -243
  206. package/exporter/utils/cache.ts +0 -142
  207. package/exporter/utils/core-utils.ts +0 -458
  208. package/exporter/utils/create-build-data.ts +0 -17
  209. package/exporter/utils/domains.ts +0 -39
  210. package/exporter/utils/folders.ts +0 -320
  211. package/exporter/utils/health-checks.ts +0 -64
  212. package/exporter/utils/loggin.ts +0 -184
  213. package/exporter/utils/render.ts +0 -71
  214. package/exporter/utils/searches.ts +0 -156
  215. package/exporter/utils/sites.ts +0 -312
  216. package/exporter/utils/store.ts +0 -314
  217. package/src/README.md +0 -7
  218. package/start-render.js +0 -7
  219. /package/build/{utils → core}/instance.d.ts +0 -0
  220. /package/build/{constants → shared}/endpoints.d.ts +0 -0
  221. /package/exporter/{types → shared/types}/templates.ts +0 -0
  222. /package/{exporter/react/Favicon → react/GriddoFavicon}/utils.ts +0 -0
@@ -1,14 +0,0 @@
1
- import { MemoryRegister, Register } from "../services/register";
2
-
3
- const entries = {
4
- GATSBY_PAGE_SIZE_TOO_BIG: {
5
- title: "Gatsby JSON page size is too large",
6
- description:
7
- "The JSON of some Gatsby pages (page-data folder) are too large and may affect rendering performance",
8
- entries: [],
9
- },
10
- };
11
-
12
- const register = new Register(new MemoryRegister(entries));
13
-
14
- export default register;
@@ -1,4 +0,0 @@
1
- import apiRegister from "./api";
2
- import gatsbyRegister from "./gatsby";
3
-
4
- export { apiRegister, gatsbyRegister };
@@ -1,113 +0,0 @@
1
- import fsx from "fs-extra";
2
-
3
- type Entry = Record<string, unknown>;
4
-
5
- type EntryData = {
6
- title: string;
7
- description: string;
8
- entries: Array<Entry>;
9
- };
10
-
11
- type Entries = Record<string, EntryData>;
12
-
13
- interface RegisterBase<T extends Entries> {
14
- insert(name: keyof T, entry: Entry): void;
15
- get(name: keyof T): EntryData;
16
- getAll(): T;
17
- }
18
-
19
- class MemoryRegister<T extends Entries> implements RegisterBase<T> {
20
- entries: T;
21
-
22
- constructor(entries: T) {
23
- this.entries = entries;
24
- }
25
-
26
- insert(name: keyof T, entry: Entry) {
27
- this.entries[name].entries.push(entry);
28
- }
29
-
30
- get(name: keyof T) {
31
- return this.entries[name];
32
- }
33
-
34
- getAll() {
35
- return this.entries;
36
- }
37
- }
38
-
39
- class FileRegister<T extends Entries> implements RegisterBase<T> {
40
- private readonly filePath: string;
41
- entries: T;
42
-
43
- constructor(filePath: string, entries: T) {
44
- this.entries = entries;
45
- this.filePath = filePath;
46
- try {
47
- fsx.writeJSONSync(this.filePath, this.entries);
48
- } catch (e) {
49
- console.error(`Error writing ${this.filePath}`, e);
50
- }
51
- }
52
-
53
- private getCurrentEntries(): T {
54
- return fsx.readJSONSync(this.filePath, "utf8") as T;
55
- }
56
-
57
- insert(name: keyof T, entry: Entry) {
58
- try {
59
- const currentEntries = this.getCurrentEntries();
60
- currentEntries[name].entries.push(entry);
61
- fsx.writeJSONSync(this.filePath, currentEntries);
62
- } catch (e) {
63
- console.error(e);
64
- }
65
- }
66
-
67
- get(name: keyof T) {
68
- try {
69
- return fsx.readJSONSync(this.filePath, "utf8")[name] as EntryData;
70
- } catch (e) {
71
- console.error(e);
72
- throw new Error(`Error reading ${this.filePath}`);
73
- }
74
- }
75
-
76
- getAll() {
77
- try {
78
- return fsx.readJSONSync(this.filePath, "utf8") as T;
79
- } catch (e) {
80
- console.error(e);
81
- throw new Error(`Error reading ${this.filePath}`);
82
- }
83
- }
84
- }
85
-
86
- class Register<T extends Entries> {
87
- private strategy: RegisterBase<T>;
88
-
89
- constructor(strategy: RegisterBase<T>) {
90
- this.strategy = strategy;
91
- }
92
-
93
- insert<K extends keyof T>(name: K, entry: Entry) {
94
- this.strategy.insert(name, entry);
95
- }
96
-
97
- get<K extends keyof T>(name: K) {
98
- return this.strategy.get(name);
99
- }
100
-
101
- getAll() {
102
- return this.strategy.getAll();
103
- }
104
- }
105
-
106
- export {
107
- FileRegister,
108
- MemoryRegister,
109
- Register,
110
- type Entries,
111
- type Entry,
112
- type EntryData,
113
- };
@@ -1,17 +0,0 @@
1
- import type { Settings } from "../types/global";
2
-
3
- import { endpoints } from "../constants";
4
- import { get, post } from "../utils/api";
5
-
6
- async function getAllSettings() {
7
- return get<Settings>({ endpoint: endpoints.SETTINGS });
8
- }
9
-
10
- async function resetRender() {
11
- await post({
12
- endpoint: endpoints.RESET_RENDER,
13
- useApiCacheDir: false,
14
- });
15
- }
16
-
17
- export { getAllSettings, resetRender };
@@ -1,29 +0,0 @@
1
- import type { GriddoAlertRegisterProps } from "@griddo/core";
2
-
3
- import axios from "axios";
4
-
5
- import { endpoints } from "../constants";
6
-
7
- // Esta función está duplicada de core de manera intencionada por si esta recibe
8
- // cambios necesitados solo por CX.
9
- // Nota: Sí estamos reutilizando el type.
10
- async function insertAlert({
11
- area,
12
- description,
13
- fullData,
14
- instantNotification = false,
15
- level,
16
- }: Omit<GriddoAlertRegisterProps, "publicApiUrl">) {
17
- const url = endpoints.ALERT;
18
- const body = { level, area, description, fullData, instantNotification };
19
-
20
- try {
21
- await axios.post(url, body, {
22
- headers: { "Content-Type": "application/json", Connection: "close" },
23
- });
24
- } catch (error) {
25
- console.error("Error creating Griddo alert:", error);
26
- }
27
- }
28
-
29
- export { insertAlert };
@@ -1,243 +0,0 @@
1
- import type {
2
- APIRequest,
3
- APIResponses,
4
- GetAPI,
5
- PostAPI,
6
- PutAPI,
7
- ShowApiErrorOptions,
8
- } from "../types/api";
9
- import type { AxiosError, Method } from "axios";
10
-
11
- import axios from "axios";
12
- import dotenv from "dotenv";
13
- import kleur from "kleur";
14
-
15
- import { saveCache, searchCacheData } from "./cache";
16
- import { delay, getSafeSiteId, msToSec } from "./core-utils";
17
- import { buildLog } from "./loggin";
18
- import { envs } from "../constants";
19
- import { apiRegister } from "../registers";
20
- import { AuthService } from "../services/auth";
21
-
22
- dotenv.config();
23
-
24
- // Envs
25
- const {
26
- env: { RETRY_WAIT_SECONDS = "4", RETRY_ATTEMPTS = "4" },
27
- } = process;
28
-
29
- /**
30
- * Make a GET/PUT/POST request to the Griddo API.
31
- *
32
- * @template T Response Type returned.
33
- * @returns {Promise<T>} A promise that is resolved with the data from the API response.
34
- *
35
- * @example
36
- * const response = await requestAPI<Site>(
37
- * { endpoint: "...", cacheKey: "...", ... },
38
- * "get",
39
- * "..."
40
- * );
41
- */
42
- async function requestAPI<T extends APIResponses>(
43
- props: APIRequest,
44
- method: Method,
45
- appendToLog = "",
46
- ): Promise<T> {
47
- const {
48
- endpoint,
49
- body,
50
- cacheKey = "",
51
- attempt = 1,
52
- headers,
53
- useApiCacheDir = true,
54
- } = props;
55
- const cacheOptions = { endpoint, body, headers, cacheKey };
56
-
57
- // Cache
58
- if (cacheKey && useApiCacheDir) {
59
- const start = new Date();
60
- const cacheData = searchCacheData<T>(cacheOptions);
61
-
62
- if (cacheData) {
63
- const siteId = getSafeSiteId(cacheData);
64
- const siteIdMsg = siteId ? `site: ${siteId}` : "";
65
- const duration = msToSec(new Date().getTime() - start.getTime());
66
- buildLog(
67
- `${method} (cache) ${siteIdMsg} ${endpoint} - ${duration}s ${appendToLog}`,
68
- );
69
- return cacheData;
70
- }
71
- }
72
-
73
- // Network
74
- try {
75
- const start = new Date();
76
- const {
77
- data,
78
- headers: responseHeaders,
79
- }: { data: T; headers: { "content-length": string } } = await axios({
80
- url: endpoint,
81
- method,
82
- headers: Object.assign({}, headers, AuthService.headers),
83
- data: body,
84
- });
85
-
86
- const siteId = getSafeSiteId(data);
87
- const siteIdMsg = siteId ? `site: ${siteId}` : "";
88
- const duration = msToSec(new Date().getTime() - start.getTime());
89
- buildLog(
90
- `${method} (fetch) ${siteIdMsg} ${endpoint} - ${duration}s ${appendToLog}`,
91
- );
92
-
93
- if (useApiCacheDir) {
94
- saveCache(cacheOptions, data);
95
- }
96
-
97
- // Only save registers if alerts are enabled
98
- if (envs.GRIDDO_ALERT_FEATURE) {
99
- const responseSize = Number.parseInt(responseHeaders["content-length"]);
100
- if (responseSize > envs.GRIDDO_API_MAX_RESPONSE_SIZE) {
101
- apiRegister.insert("API_RESPONSE_TOO_BIG", {
102
- endpoint,
103
- responseSize,
104
- duration,
105
- });
106
- }
107
- }
108
-
109
- return data;
110
- } catch (e) {
111
- const error = e as AxiosError;
112
-
113
- if (error.response?.status === 404) {
114
- // @ts-expect-error page maybe will be 404
115
- return null;
116
- }
117
-
118
- if (attempt > parseInt(RETRY_ATTEMPTS)) {
119
- console.log(`
120
- Max attempts ${RETRY_ATTEMPTS} reached
121
- --------------------------------------
122
- - ${method.toUpperCase()} ${endpoint}
123
- - BODY: ${JSON.stringify(body)}
124
- - HEADERS: ${JSON.stringify(headers)}
125
- - RESPONSE: ${error.response?.status} ${JSON.stringify(error.response?.data)}
126
- --------------------------------------
127
- `);
128
-
129
- console.log(JSON.stringify(error, null, 2));
130
- process.exit(1);
131
- }
132
-
133
- if (!error.response) {
134
- console.log("Unknown error occurred");
135
- console.log(JSON.stringify(error, null, 2));
136
- process.exit(1);
137
- }
138
-
139
- showApiError(error, {
140
- callInfo: { endpoint, body },
141
- });
142
-
143
- console.warn(`Waiting for retry: ${method}`, endpoint);
144
-
145
- await delay(parseInt(RETRY_WAIT_SECONDS) * 1000);
146
-
147
- return requestAPI<T>(
148
- {
149
- endpoint,
150
- body,
151
- headers,
152
- cacheKey,
153
- attempt: attempt + 1,
154
- },
155
- method,
156
- appendToLog,
157
- );
158
- }
159
- }
160
-
161
- /**
162
- * Make a GET request to the Griddo API.
163
- *
164
- * @template T Response Type returned.
165
- * @returns A promise that is resolved with the data from the API response.
166
- */
167
- async function getApi<T extends APIResponses>(props: GetAPI) {
168
- return requestAPI<T>(props, "get");
169
- }
170
-
171
- /**
172
- * Make a PUT request to the Griddo API.
173
- *
174
- * @template T Response Type returned.
175
- * @returns A promise that is resolved with the data from the API response.
176
- */
177
- async function putApi<T extends APIResponses>(props: PutAPI) {
178
- return requestAPI<T>(props, "put");
179
- }
180
-
181
- /**
182
- * Make a POST request to the Griddo API.
183
- *
184
- * @template T Response Type returned.
185
- * @returns A promise that is resolved with the data from the API response.
186
- */
187
- async function postApi<T extends APIResponses>(props: PostAPI) {
188
- const { endpoint, body, headers } = props;
189
- const referenceFieldBodyParams =
190
- endpoint.endsWith("/distributor") &&
191
- `# ReferenceField body: ${JSON.stringify(body)} lang: ${JSON.stringify(
192
- headers?.lang,
193
- )}`;
194
-
195
- return requestAPI<T>(props, "post", referenceFieldBodyParams || "");
196
- }
197
-
198
- /**
199
- * Shows an API error through the terminal.
200
- */
201
- function showApiError(error: AxiosError, options: ShowApiErrorOptions) {
202
- const { response, message, stack } = error;
203
- const { callInfo } = options;
204
- const { status, statusText, data } = response || {};
205
- const callInfoArray = [];
206
-
207
- for (const item of Object.keys(callInfo) as Array<keyof typeof callInfo>) {
208
- callInfoArray.push(
209
- `${item}: ${
210
- typeof callInfo[item] === "object"
211
- ? JSON.stringify(callInfo[item])
212
- : callInfo[item]
213
- }`,
214
- );
215
- }
216
-
217
- // Compose the errors output
218
- const callInfoStr = callInfoArray.join("\n");
219
- const apiResponseStr = response
220
- ? `Code: ${status} - ${statusText}\nResponse: ${JSON.stringify(data)}`
221
- : "";
222
- const errorDetailsStr = `${message}\n${stack}`;
223
-
224
- // Print the error
225
- console.warn(
226
- kleur.red(`
227
- =============
228
-
229
- { Call info }
230
- ${callInfoStr}
231
-
232
- { API Response }
233
- ${apiResponseStr}
234
-
235
- { Error details }
236
- ${errorDetailsStr}
237
-
238
- =============
239
- `),
240
- );
241
- }
242
-
243
- export { getApi as get, postApi as post, putApi as put };
@@ -1,142 +0,0 @@
1
- import type { Petition } from "../types/global";
2
- import type { HashSites, SiteHash } from "../types/sites";
3
-
4
- import crypto from "node:crypto";
5
- import fs from "node:fs";
6
- import path from "node:path";
7
-
8
- import fsx from "fs-extra";
9
-
10
- import { getConfig } from "./core-utils";
11
-
12
- const config = getConfig();
13
-
14
- /**
15
- * Creates an `apiCache` dir to store pages fetched from them API.
16
- */
17
- function createAPICacheDir() {
18
- const { __cx } = config.paths();
19
- const apiCacheDir = path.join(__cx, "apiCache");
20
-
21
- if (!fs.existsSync(apiCacheDir)) {
22
- fs.mkdirSync(apiCacheDir);
23
- }
24
-
25
- console.info("Cache initialized");
26
- }
27
-
28
- /**
29
- * Generate a filename with a hash using a Petition object
30
- *
31
- * @todo Merge with createSha256
32
- * @param petition An object
33
- */
34
- function generateFilenameWithHash(petition: Petition) {
35
- const { __cx } = config.paths();
36
- const apiCacheDir = path.join(__cx, "apiCache");
37
-
38
- const hashSum = crypto.createHash("sha256");
39
- hashSum.update(JSON.stringify(petition));
40
-
41
- return `${apiCacheDir}/${hashSum.digest("hex")}`;
42
- }
43
-
44
- /**
45
- * Generate a filename with a hash using a string.
46
- *
47
- * @todo Merge with generateFilenameWithHash
48
- * @param data A string to create a sha256 based on.
49
- */
50
- function createSha256(data: string) {
51
- const uniqueString = crypto.randomBytes(16).toString("hex");
52
- const hash = crypto.createHash("sha256");
53
- hash.update(`${data}${uniqueString}`);
54
-
55
- return hash.digest("hex");
56
- }
57
-
58
- /**
59
- * Save a file using a hash name.
60
- *
61
- * @param petition An object.
62
- * @param content Content to be saved.
63
- */
64
- function saveCache<T>(petition: Petition, content: T) {
65
- const stringContent =
66
- typeof content === "string" ? content : JSON.stringify(content);
67
- const filename = generateFilenameWithHash(petition);
68
- const filepath = path.dirname(filename);
69
- if (!fs.existsSync(filepath)) {
70
- fs.mkdirSync(filepath, { recursive: true });
71
- }
72
- fs.writeFileSync(filename, stringContent, "utf8");
73
- }
74
-
75
- /**
76
- * Search in the `apiCache` dir for a file using the petition as hash generator.
77
- * Return the file content if found or null if not.
78
- *
79
- * @param petition An object
80
- */
81
- function searchCacheData<T>(petition: Petition) {
82
- try {
83
- const file = generateFilenameWithHash(petition);
84
- const jsonData = fsx.readJSONSync(file, {
85
- encoding: "utf-8",
86
- });
87
- return jsonData as T;
88
- } catch {
89
- return null;
90
- }
91
- }
92
-
93
- /**
94
- * Get site hashes from the file as an object
95
- */
96
- function getHashSites(): HashSites {
97
- const { __cx } = config.paths();
98
- const apiCacheDir = path.join(__cx, "apiCache");
99
- const siteHasFilename = `${apiCacheDir}/siteHash.json`;
100
-
101
- try {
102
- const jsonData = fsx.readJSONSync(siteHasFilename, {
103
- encoding: "utf-8",
104
- });
105
- return jsonData || {};
106
- } catch {
107
- return {};
108
- }
109
- }
110
-
111
- /**
112
- * Update (write) the site hash file.
113
- *
114
- * @param siteId The id of the site.
115
- * @param siteHash The has of the site.
116
- */
117
- function updatedSiteHash(siteId: number, siteHash: SiteHash) {
118
- const allHash = getHashSites();
119
- const lastHash = allHash[siteId];
120
- const currentHash = siteHash || lastHash || new Date().valueOf();
121
-
122
- const { __cx } = config.paths();
123
- const apiCacheDir = path.join(__cx, "apiCache");
124
- const siteHasFilename = `${apiCacheDir}/siteHash.json`;
125
-
126
- if (currentHash !== lastHash) {
127
- allHash[siteId] = currentHash;
128
- fs.writeFileSync(siteHasFilename, JSON.stringify(allHash), {
129
- encoding: "utf-8",
130
- });
131
- }
132
-
133
- return currentHash.toString();
134
- }
135
-
136
- export {
137
- createAPICacheDir,
138
- createSha256,
139
- saveCache,
140
- searchCacheData,
141
- updatedSiteHash,
142
- };