@agility/content-fetch 2.0.9 → 2.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/.jsdoc.json CHANGED
@@ -1,29 +1,29 @@
1
- {
2
- "source": {
3
- "include": ["src", "README.md", "package.json"],
4
- "includePattern": ".js$",
5
- "excludePattern": "(node_modules/|docs)"
6
- },
7
- "plugins": [
8
- "plugins/markdown"
9
- ],
10
- "recurse": 10,
11
- "templates": {
12
- "cleverLinks": false,
13
- "monospaceLinks": true,
14
- "useLongnameInNav": true,
15
- "showInheritedInNav": true
16
- },
17
- "tags": {
18
- "allowUnknownTags": true,
19
- "dictionaries": ["jsdoc"]
20
- },
21
- "source-type": "module",
22
- "opts": {
23
- "destination": "./docs/",
24
- "encoding": "utf8",
25
- "private": false,
26
- "recurse": true,
27
- "template": "./node_modules/agility-jsdoc-template"
28
- }
1
+ {
2
+ "source": {
3
+ "include": ["src", "README.md", "package.json"],
4
+ "includePattern": ".js$",
5
+ "excludePattern": "(node_modules/|docs)"
6
+ },
7
+ "plugins": [
8
+ "plugins/markdown"
9
+ ],
10
+ "recurse": 10,
11
+ "templates": {
12
+ "cleverLinks": false,
13
+ "monospaceLinks": true,
14
+ "useLongnameInNav": true,
15
+ "showInheritedInNav": true
16
+ },
17
+ "tags": {
18
+ "allowUnknownTags": true,
19
+ "dictionaries": ["jsdoc"]
20
+ },
21
+ "source-type": "module",
22
+ "opts": {
23
+ "destination": "./docs/",
24
+ "encoding": "utf8",
25
+ "private": false,
26
+ "recurse": true,
27
+ "template": "./node_modules/agility-jsdoc-template"
28
+ }
29
29
  }
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2019 Agility
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Agility
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,102 +1,102 @@
1
- [![Build Status](https://agility.visualstudio.com/Agility%20CMS/_apis/build/status/Fetch%20API/Agility%20Content%20Fetch%20JS%20SDK?branchName=master)](https://agility.visualstudio.com/Agility%20CMS/_build/latest?definitionId=59&branchName=master)
2
- [![Netlify Status](https://api.netlify.com/api/v1/badges/c45f5d6e-923b-4019-820e-826e6185017d/deploy-status)](https://app.netlify.com/sites/agilitydocs/deploys)
3
-
4
- # Agility Content Fetch JS SDK
5
-
6
- This is the official JavaScript/TypeScript library for accessing live and preview content from your [Agility CMS](https://agilitycms.com) instance.
7
-
8
- You can use this in both node and browser based JS apps.
9
-
10
- Don't have an Agility CMS instance? Sign up for [Free Trial](https://agilitycms.com/free) today!
11
-
12
- ## Features
13
-
14
- - Queries the high-availability, CDN backed Agility Fetch REST API
15
- - Get a sitemap for a given channel
16
- - Get a page, including its content zones, modules, and their content
17
- - Get a content item
18
- - Query a content list using a filter syntax
19
- - Get the details of a media gallery
20
- - Keep track of syncing content to your app
21
-
22
- ## Getting Started
23
-
24
- In order to use this sdk, you'll need to install the `@agility/content-fetch` package and you'll also need to authenticate your requests.
25
-
26
- ### Prerequisites
27
-
28
- You must have access to an Agility instance to retrieve the _guid_ and generate your _apiKey_. Or, you must have these values provided to you.
29
-
30
- ### Installation
31
-
32
- **npm**
33
-
34
- ```
35
- npm install @agility/content-fetch
36
- ```
37
-
38
- **yarn**
39
-
40
- ```
41
- yarn add @agility/content-fetch
42
- ```
43
-
44
- ### Making a Request
45
-
46
- ```javascript
47
- import agility from "@agility/content-fetch"
48
-
49
- //initialize the api client
50
- const api = agility.getApi({
51
- guid: "[guid]",
52
- apiKey: "[your-api-key]",
53
- })
54
-
55
- //make the request: get a content item with the ID 22 in locale 'en-us'
56
- const contentItems = await api.getContentItem({
57
- contentID: 22,
58
- locale: "en-us",
59
- })
60
- ```
61
-
62
- ## Documentation
63
-
64
- Full documentation for this SDK can be found in our [Agility Fetch JS SDK Reference Doc](https://agilitydocs.netlify.com/agility-content-fetch-js-sdk/).
65
-
66
- For docs & help around Agility CMS, please see [Agility CMS Documentation](https://help.agilitycms.com/hc/en-us)
67
-
68
- ## Tutorials
69
-
70
- [About the Content Fetch API](https://help.agilitycms.com/hc/en-us/articles/360031985112-About-the-Content-Fetch-API)
71
-
72
- [Authenticating your Content Fetch API Calls](https://help.agilitycms.com/hc/en-us/articles/360032225191-Authenticating-your-Content-Fetch-API-Calls)
73
-
74
- [Retrieving your API Key(s), Guid, and API URL](https://help.agilitycms.com/hc/en-us/articles/360031919212-Retrieving-your-API-Key-s-Guid-and-API-URL-)
75
-
76
- [Making your First Call with the Content Fetch API](https://help.agilitycms.com/hc/en-us/articles/360031918152-Making-your-First-API-Call-with-the-Content-Fetch-API)
77
-
78
- [Calilng the Content Fetch API using the Javascript SDK](https://help.agilitycms.com/hc/en-us/articles/360031945912-Calling-the-Content-Fetch-API-using-the-JavaScript-SDK)
79
-
80
- [Page Management in a Headless CMS](https://help.agilitycms.com/hc/en-us/articles/360032554331-Page-Management-in-a-Headless-CMS)
81
-
82
- [Using Agility CMS with Create React App](https://help.agilitycms.com/hc/en-us/articles/360031121692-Using-Agility-CMS-with-Create-React-App-CRA-)
83
-
84
- [Creating a Module for the Agility CMS Create React App](https://help.agilitycms.com/hc/en-us/articles/360031590791-Creating-a-Module-for-the-Agility-CMS-Create-React-App)
85
-
86
- [Creating a Page Template for the Agility CMS Create React App](https://help.agilitycms.com/hc/en-us/articles/360032611011-Creating-a-Page-Template-for-the-Agility-CMS-Create-React-App)
87
-
88
- [Deploying your Agility CMS Create React App](https://help.agilitycms.com/hc/en-us/articles/360032203552-Deploying-your-Agility-CMS-Create-React-App)
89
-
90
- [Content Webhooks](https://help.agilitycms.com/hc/en-us/articles/360035934911)
91
-
92
- ## Contributing
93
-
94
- If you would like to contribute to this SDK, you can fork the repository and submit a pull request. We'd love to include your updates.
95
-
96
- ### Running the Tests
97
-
98
- An essential part of contributing to this SDK is adding and running unit tests to ensure the stability of the project.
99
-
100
- ```
101
- > npm run test
102
- ```
1
+ [![Build Status](https://agility.visualstudio.com/Agility%20CMS/_apis/build/status/Fetch%20API/Agility%20Content%20Fetch%20JS%20SDK?branchName=master)](https://agility.visualstudio.com/Agility%20CMS/_build/latest?definitionId=59&branchName=master)
2
+ [![Netlify Status](https://api.netlify.com/api/v1/badges/c45f5d6e-923b-4019-820e-826e6185017d/deploy-status)](https://app.netlify.com/sites/agilitydocs/deploys)
3
+
4
+ # Agility Content Fetch JS SDK
5
+
6
+ This is the official JavaScript/TypeScript library for accessing live and preview content from your [Agility CMS](https://agilitycms.com) instance.
7
+
8
+ You can use this in both node and browser based JS apps.
9
+
10
+ Don't have an Agility CMS instance? Sign up for [Free Trial](https://agilitycms.com/free) today!
11
+
12
+ ## Features
13
+
14
+ - Queries the high-availability, CDN backed Agility Fetch REST API
15
+ - Get a sitemap for a given channel
16
+ - Get a page, including its content zones, modules, and their content
17
+ - Get a content item
18
+ - Query a content list using a filter syntax
19
+ - Get the details of a media gallery
20
+ - Keep track of syncing content to your app
21
+
22
+ ## Getting Started
23
+
24
+ In order to use this sdk, you'll need to install the `@agility/content-fetch` package and you'll also need to authenticate your requests.
25
+
26
+ ### Prerequisites
27
+
28
+ You must have access to an Agility instance to retrieve the _guid_ and generate your _apiKey_. Or, you must have these values provided to you.
29
+
30
+ ### Installation
31
+
32
+ **npm**
33
+
34
+ ```
35
+ npm install @agility/content-fetch
36
+ ```
37
+
38
+ **yarn**
39
+
40
+ ```
41
+ yarn add @agility/content-fetch
42
+ ```
43
+
44
+ ### Making a Request
45
+
46
+ ```javascript
47
+ import agility from "@agility/content-fetch"
48
+
49
+ //initialize the api client
50
+ const api = agility.getApi({
51
+ guid: "[guid]",
52
+ apiKey: "[your-api-key]",
53
+ })
54
+
55
+ //make the request: get a content item with the ID 22 in locale 'en-us'
56
+ const contentItems = await api.getContentItem({
57
+ contentID: 22,
58
+ locale: "en-us",
59
+ })
60
+ ```
61
+
62
+ ## Documentation
63
+
64
+ Full documentation for this SDK can be found in our [Agility Fetch JS SDK Reference Doc](https://agilitydocs.netlify.com/agility-content-fetch-js-sdk/).
65
+
66
+ For docs & help around Agility CMS, please see [Agility CMS Documentation](https://help.agilitycms.com/hc/en-us)
67
+
68
+ ## Tutorials
69
+
70
+ [About the Content Fetch API](https://help.agilitycms.com/hc/en-us/articles/360031985112-About-the-Content-Fetch-API)
71
+
72
+ [Authenticating your Content Fetch API Calls](https://help.agilitycms.com/hc/en-us/articles/360032225191-Authenticating-your-Content-Fetch-API-Calls)
73
+
74
+ [Retrieving your API Key(s), Guid, and API URL](https://help.agilitycms.com/hc/en-us/articles/360031919212-Retrieving-your-API-Key-s-Guid-and-API-URL-)
75
+
76
+ [Making your First Call with the Content Fetch API](https://help.agilitycms.com/hc/en-us/articles/360031918152-Making-your-First-API-Call-with-the-Content-Fetch-API)
77
+
78
+ [Calilng the Content Fetch API using the Javascript SDK](https://help.agilitycms.com/hc/en-us/articles/360031945912-Calling-the-Content-Fetch-API-using-the-JavaScript-SDK)
79
+
80
+ [Page Management in a Headless CMS](https://help.agilitycms.com/hc/en-us/articles/360032554331-Page-Management-in-a-Headless-CMS)
81
+
82
+ [Using Agility CMS with Create React App](https://help.agilitycms.com/hc/en-us/articles/360031121692-Using-Agility-CMS-with-Create-React-App-CRA-)
83
+
84
+ [Creating a Module for the Agility CMS Create React App](https://help.agilitycms.com/hc/en-us/articles/360031590791-Creating-a-Module-for-the-Agility-CMS-Create-React-App)
85
+
86
+ [Creating a Page Template for the Agility CMS Create React App](https://help.agilitycms.com/hc/en-us/articles/360032611011-Creating-a-Page-Template-for-the-Agility-CMS-Create-React-App)
87
+
88
+ [Deploying your Agility CMS Create React App](https://help.agilitycms.com/hc/en-us/articles/360032203552-Deploying-your-Agility-CMS-Create-React-App)
89
+
90
+ [Content Webhooks](https://help.agilitycms.com/hc/en-us/articles/360035934911)
91
+
92
+ ## Contributing
93
+
94
+ If you would like to contribute to this SDK, you can fork the repository and submit a pull request. We'd love to include your updates.
95
+
96
+ ### Running the Tests
97
+
98
+ An essential part of contributing to this SDK is adding and running unit tests to ensure the stability of the project.
99
+
100
+ ```
101
+ > npm run test
102
+ ```
package/build.js CHANGED
@@ -1,24 +1,24 @@
1
- const esbuild = require('esbuild');
2
- const { execSync } = require('child_process');
3
- const path = require('path');
4
-
5
- console.log("Building...", path.resolve(__dirname, "src/index.ts"))
6
- console.log("Building...", path.resolve(__dirname, "dist/browser.js"))
7
-
8
- execSync('tsc --emitDeclarationOnly');
9
-
10
- // Build for browser
11
- esbuild.build({
12
- entryPoints: ['./src/index.ts'],
13
- bundle: true,
14
- outfile: './dist/browser.js',
15
- platform: 'browser',
16
- }).catch(() => process.exit(1));
17
-
18
- // Build for Node.js
19
- esbuild.build({
20
- entryPoints: ['./src/index.ts'],
21
- bundle: true,
22
- outfile: './dist/node.js',
23
- platform: 'node',
24
- }).catch(() => process.exit(1));
1
+ const esbuild = require('esbuild');
2
+ const { execSync } = require('child_process');
3
+ const path = require('path');
4
+
5
+ console.log("Building...", path.resolve(__dirname, "src/index.ts"))
6
+ console.log("Building...", path.resolve(__dirname, "dist/browser.js"))
7
+
8
+ execSync('tsc --emitDeclarationOnly');
9
+
10
+ // Build for browser
11
+ esbuild.build({
12
+ entryPoints: ['./src/index.ts'],
13
+ bundle: true,
14
+ outfile: './dist/browser.js',
15
+ platform: 'browser',
16
+ }).catch(() => process.exit(1));
17
+
18
+ // Build for Node.js
19
+ esbuild.build({
20
+ entryPoints: ['./src/index.ts'],
21
+ bundle: true,
22
+ outfile: './dist/node.js',
23
+ platform: 'node',
24
+ }).catch(() => process.exit(1));
package/dist/browser.js CHANGED
@@ -21,6 +21,38 @@
21
21
  return;
22
22
  console.error("\x1B[41m%s\x1B[0m", message);
23
23
  }
24
+ function sanitizeHeaders(headers) {
25
+ const sanitized = {};
26
+ if (headers instanceof Headers) {
27
+ headers.forEach((value, key) => {
28
+ if (key.toLowerCase() === "apikey") {
29
+ sanitized[key] = "***REDACTED***";
30
+ } else {
31
+ sanitized[key] = value;
32
+ }
33
+ });
34
+ } else {
35
+ Object.keys(headers).forEach((key) => {
36
+ if (key.toLowerCase() === "apikey") {
37
+ sanitized[key] = "***REDACTED***";
38
+ } else {
39
+ sanitized[key] = headers[key];
40
+ }
41
+ });
42
+ }
43
+ return sanitized;
44
+ }
45
+ function logDebugDetails({ config, details }) {
46
+ if (!config.debug)
47
+ return;
48
+ const sanitizedDetails = {
49
+ ...details,
50
+ headers: details.headers ? sanitizeHeaders(details.headers) : void 0
51
+ };
52
+ console.log("\x1B[36m%s\x1B[0m", "=== AgilityCMS Fetch API Debug ===");
53
+ console.log(JSON.stringify(sanitizedDetails, null, 2));
54
+ console.log("\x1B[36m%s\x1B[0m", "===================================");
55
+ }
24
56
  function buildRequestUrlPath(config, locale) {
25
57
  let apiFetchOrPreview = "";
26
58
  if (config.isPreview === true || config.isPreview === "true") {
@@ -493,20 +525,24 @@
493
525
  }
494
526
  };
495
527
  function buildBaseUrl(guid) {
496
- let baseUrlSuffixes = {
528
+ const baseUrlSuffixes = {
497
529
  u: "",
498
530
  c: "-ca",
499
531
  e: "-eu",
500
532
  a: "-aus",
501
- d: "-dev"
533
+ d: "-dev",
534
+ us2: "-usa2"
502
535
  };
503
- let suffix = guid.substr(guid.length - 2, 2);
504
- let env = suffix.substr(1);
505
- if (suffix.startsWith("-") && baseUrlSuffixes.hasOwnProperty(env)) {
506
- return `https://api${baseUrlSuffixes[env]}.aglty.io/${guid}`;
507
- } else {
508
- return `https://${guid}-api.agilitycms.cloud`;
536
+ const match = guid.match(/-(us2|[ucead])$/);
537
+ if (match) {
538
+ const env = match[1];
539
+ if (baseUrlSuffixes.hasOwnProperty(env)) {
540
+ const url = `https://api${baseUrlSuffixes[env]}.aglty.io/${guid}`;
541
+ return url;
542
+ }
509
543
  }
544
+ const legacyUrl = `https://${guid}-api.agilitycms.cloud`;
545
+ return legacyUrl;
510
546
  }
511
547
  function validateConfigParams(configParams) {
512
548
  if (!configParams.guid || configParams.guid.length == 0) {
@@ -568,6 +604,7 @@
568
604
  //the function that actually makes ALL our requests
569
605
  async makeRequest(reqConfig) {
570
606
  const isPreview = !!this.config.isPreview;
607
+ const startTime = Date.now();
571
608
  logDebug({ config: this.config, message: `AgilityCMS Fetch API LOG: ${reqConfig.baseURL}${reqConfig.url}` });
572
609
  try {
573
610
  const fullUrl = `${reqConfig.baseURL}${reqConfig.url}`;
@@ -584,8 +621,48 @@
584
621
  init.cache = "no-store";
585
622
  delete init.next;
586
623
  }
624
+ if (this.config.debug) {
625
+ logDebugDetails({
626
+ config: this.config,
627
+ details: {
628
+ type: "request",
629
+ url: fullUrl,
630
+ method: init.method,
631
+ headers: init.headers,
632
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
633
+ }
634
+ });
635
+ }
587
636
  const response = await fetch(fullUrl, init);
637
+ const duration = Date.now() - startTime;
588
638
  if (!response.ok) {
639
+ if (this.config.debug) {
640
+ const responseHeaders = {};
641
+ response.headers.forEach((value, key) => {
642
+ responseHeaders[key] = value;
643
+ });
644
+ let errorBody = "";
645
+ try {
646
+ errorBody = await response.text();
647
+ } catch (e) {
648
+ errorBody = "Unable to read error response body";
649
+ }
650
+ logDebugDetails({
651
+ config: this.config,
652
+ details: {
653
+ type: "error",
654
+ url: fullUrl,
655
+ method: init.method,
656
+ statusCode: response.status,
657
+ statusText: response.statusText,
658
+ headers: responseHeaders,
659
+ responsePreview: errorBody.substring(0, 500),
660
+ // First 500 chars
661
+ duration,
662
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
663
+ }
664
+ });
665
+ }
589
666
  if (response.status === 404) {
590
667
  logInfo({ config: this.config, message: `AgilityCMS Fetch API: Request returned a ${response.status} response for ${reqConfig.baseURL}${reqConfig.url}. ${response.statusText}` });
591
668
  return;
@@ -595,10 +672,40 @@
595
672
  }
596
673
  let data = await response.json();
597
674
  if (this.config.debug) {
675
+ const responseHeaders = {};
676
+ response.headers.forEach((value, key) => {
677
+ responseHeaders[key] = value;
678
+ });
679
+ logDebugDetails({
680
+ config: this.config,
681
+ details: {
682
+ type: "response",
683
+ url: fullUrl,
684
+ method: init.method,
685
+ statusCode: response.status,
686
+ statusText: response.statusText,
687
+ headers: responseHeaders,
688
+ duration,
689
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
690
+ }
691
+ });
598
692
  data["agilityResponseHeaders"] = response.headers;
599
693
  }
600
694
  return data;
601
695
  } catch (error) {
696
+ const duration = Date.now() - startTime;
697
+ if (this.config.debug) {
698
+ logDebugDetails({
699
+ config: this.config,
700
+ details: {
701
+ type: "error",
702
+ url: `${reqConfig.baseURL}${reqConfig.url}`,
703
+ errorMessage: error instanceof Error ? error.message : String(error),
704
+ duration,
705
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
706
+ }
707
+ });
708
+ }
602
709
  logError({ config: this.config, message: `AgilityCMS Fetch API ERROR: Request failed for ${reqConfig.baseURL}${reqConfig.url} ... ${error}` });
603
710
  }
604
711
  }
package/dist/node.js CHANGED
@@ -39,6 +39,38 @@ function logError({ config, message }) {
39
39
  return;
40
40
  console.error("\x1B[41m%s\x1B[0m", message);
41
41
  }
42
+ function sanitizeHeaders(headers) {
43
+ const sanitized = {};
44
+ if (headers instanceof Headers) {
45
+ headers.forEach((value, key) => {
46
+ if (key.toLowerCase() === "apikey") {
47
+ sanitized[key] = "***REDACTED***";
48
+ } else {
49
+ sanitized[key] = value;
50
+ }
51
+ });
52
+ } else {
53
+ Object.keys(headers).forEach((key) => {
54
+ if (key.toLowerCase() === "apikey") {
55
+ sanitized[key] = "***REDACTED***";
56
+ } else {
57
+ sanitized[key] = headers[key];
58
+ }
59
+ });
60
+ }
61
+ return sanitized;
62
+ }
63
+ function logDebugDetails({ config, details }) {
64
+ if (!config.debug)
65
+ return;
66
+ const sanitizedDetails = {
67
+ ...details,
68
+ headers: details.headers ? sanitizeHeaders(details.headers) : void 0
69
+ };
70
+ console.log("\x1B[36m%s\x1B[0m", "=== AgilityCMS Fetch API Debug ===");
71
+ console.log(JSON.stringify(sanitizedDetails, null, 2));
72
+ console.log("\x1B[36m%s\x1B[0m", "===================================");
73
+ }
42
74
  function buildRequestUrlPath(config, locale) {
43
75
  let apiFetchOrPreview = "";
44
76
  if (config.isPreview === true || config.isPreview === "true") {
@@ -511,20 +543,24 @@ var defaultConfig = {
511
543
  }
512
544
  };
513
545
  function buildBaseUrl(guid) {
514
- let baseUrlSuffixes = {
546
+ const baseUrlSuffixes = {
515
547
  u: "",
516
548
  c: "-ca",
517
549
  e: "-eu",
518
550
  a: "-aus",
519
- d: "-dev"
551
+ d: "-dev",
552
+ us2: "-usa2"
520
553
  };
521
- let suffix = guid.substr(guid.length - 2, 2);
522
- let env = suffix.substr(1);
523
- if (suffix.startsWith("-") && baseUrlSuffixes.hasOwnProperty(env)) {
524
- return `https://api${baseUrlSuffixes[env]}.aglty.io/${guid}`;
525
- } else {
526
- return `https://${guid}-api.agilitycms.cloud`;
554
+ const match = guid.match(/-(us2|[ucead])$/);
555
+ if (match) {
556
+ const env = match[1];
557
+ if (baseUrlSuffixes.hasOwnProperty(env)) {
558
+ const url = `https://api${baseUrlSuffixes[env]}.aglty.io/${guid}`;
559
+ return url;
560
+ }
527
561
  }
562
+ const legacyUrl = `https://${guid}-api.agilitycms.cloud`;
563
+ return legacyUrl;
528
564
  }
529
565
  function validateConfigParams(configParams) {
530
566
  if (!configParams.guid || configParams.guid.length == 0) {
@@ -586,6 +622,7 @@ var ApiClient = class {
586
622
  //the function that actually makes ALL our requests
587
623
  async makeRequest(reqConfig) {
588
624
  const isPreview = !!this.config.isPreview;
625
+ const startTime = Date.now();
589
626
  logDebug({ config: this.config, message: `AgilityCMS Fetch API LOG: ${reqConfig.baseURL}${reqConfig.url}` });
590
627
  try {
591
628
  const fullUrl = `${reqConfig.baseURL}${reqConfig.url}`;
@@ -602,8 +639,48 @@ var ApiClient = class {
602
639
  init.cache = "no-store";
603
640
  delete init.next;
604
641
  }
642
+ if (this.config.debug) {
643
+ logDebugDetails({
644
+ config: this.config,
645
+ details: {
646
+ type: "request",
647
+ url: fullUrl,
648
+ method: init.method,
649
+ headers: init.headers,
650
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
651
+ }
652
+ });
653
+ }
605
654
  const response = await fetch(fullUrl, init);
655
+ const duration = Date.now() - startTime;
606
656
  if (!response.ok) {
657
+ if (this.config.debug) {
658
+ const responseHeaders = {};
659
+ response.headers.forEach((value, key) => {
660
+ responseHeaders[key] = value;
661
+ });
662
+ let errorBody = "";
663
+ try {
664
+ errorBody = await response.text();
665
+ } catch (e) {
666
+ errorBody = "Unable to read error response body";
667
+ }
668
+ logDebugDetails({
669
+ config: this.config,
670
+ details: {
671
+ type: "error",
672
+ url: fullUrl,
673
+ method: init.method,
674
+ statusCode: response.status,
675
+ statusText: response.statusText,
676
+ headers: responseHeaders,
677
+ responsePreview: errorBody.substring(0, 500),
678
+ // First 500 chars
679
+ duration,
680
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
681
+ }
682
+ });
683
+ }
607
684
  if (response.status === 404) {
608
685
  logInfo({ config: this.config, message: `AgilityCMS Fetch API: Request returned a ${response.status} response for ${reqConfig.baseURL}${reqConfig.url}. ${response.statusText}` });
609
686
  return;
@@ -613,10 +690,40 @@ var ApiClient = class {
613
690
  }
614
691
  let data = await response.json();
615
692
  if (this.config.debug) {
693
+ const responseHeaders = {};
694
+ response.headers.forEach((value, key) => {
695
+ responseHeaders[key] = value;
696
+ });
697
+ logDebugDetails({
698
+ config: this.config,
699
+ details: {
700
+ type: "response",
701
+ url: fullUrl,
702
+ method: init.method,
703
+ statusCode: response.status,
704
+ statusText: response.statusText,
705
+ headers: responseHeaders,
706
+ duration,
707
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
708
+ }
709
+ });
616
710
  data["agilityResponseHeaders"] = response.headers;
617
711
  }
618
712
  return data;
619
713
  } catch (error) {
714
+ const duration = Date.now() - startTime;
715
+ if (this.config.debug) {
716
+ logDebugDetails({
717
+ config: this.config,
718
+ details: {
719
+ type: "error",
720
+ url: `${reqConfig.baseURL}${reqConfig.url}`,
721
+ errorMessage: error instanceof Error ? error.message : String(error),
722
+ duration,
723
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
724
+ }
725
+ });
726
+ }
620
727
  logError({ config: this.config, message: `AgilityCMS Fetch API ERROR: Request failed for ${reqConfig.baseURL}${reqConfig.url} ... ${error}` });
621
728
  }
622
729
  }
@@ -30,7 +30,12 @@ export interface Config {
30
30
  */
31
31
  logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent';
32
32
  /**
33
- * Used for debugging purposes. Default is false.
33
+ * Enable debug mode for detailed logging. Default is false.
34
+ * When enabled:
35
+ * - Adds comprehensive request/response logging with timing information
36
+ * - Includes response headers in the returned data as 'agilityResponseHeaders'
37
+ * - Logs error details including status codes, headers, and response bodies
38
+ * - Sanitizes sensitive data (API keys) in debug output
34
39
  */
35
40
  debug?: boolean;
36
41
  /**
package/dist/utils.d.ts CHANGED
@@ -7,8 +7,27 @@ declare function logDebug({ config, message }: LogProps): void;
7
7
  declare function logInfo({ config, message }: LogProps): void;
8
8
  declare function logWarning({ config, message }: LogProps): void;
9
9
  declare function logError({ config, message }: LogProps): void;
10
+ interface DebugDetails {
11
+ type: 'request' | 'response' | 'error';
12
+ url?: string;
13
+ method?: string;
14
+ headers?: Record<string, any>;
15
+ statusCode?: number;
16
+ statusText?: string;
17
+ duration?: number;
18
+ timestamp?: string;
19
+ errorMessage?: string;
20
+ responsePreview?: string;
21
+ }
22
+ /**
23
+ * Logs detailed debug information about requests and responses
24
+ */
25
+ declare function logDebugDetails({ config, details }: {
26
+ config: Config;
27
+ details: DebugDetails;
28
+ }): void;
10
29
  declare function buildRequestUrlPath(config: any, locale: any): string;
11
30
  declare function buildPathUrl(contentType: any, referenceName: any, skip: any, take: any, sort: any, direction: any, filters: any, filtersLogicOperator: any, filterString: any, contentLinkDepth: any, expandAllContentLinks: any): string;
12
31
  declare function buildAuthHeader(config: any): any;
13
32
  declare function isHttps(url: any): boolean;
14
- export { buildPathUrl, buildAuthHeader, buildRequestUrlPath, isHttps, logError, logDebug, logInfo, logWarning };
33
+ export { buildPathUrl, buildAuthHeader, buildRequestUrlPath, isHttps, logError, logDebug, logInfo, logWarning, logDebugDetails };
package/jest.config.js CHANGED
@@ -1,6 +1,6 @@
1
- module.exports = {
2
- preset: "ts-jest",
3
- testEnvironment: "node",
4
- testMatch: ["<rootDir>/test/**/*.tests.ts"],
5
- };
1
+ module.exports = {
2
+ preset: "ts-jest",
3
+ testEnvironment: "node",
4
+ testMatch: ["<rootDir>/test/**/*.tests.ts"],
5
+ };
6
6
 
package/package.json CHANGED
@@ -1,53 +1,53 @@
1
- {
2
- "name": "@agility/content-fetch",
3
- "version": "2.0.9",
4
- "description": "JS/TS library for the Agility Fetch API",
5
- "repository": {
6
- "type": "git",
7
- "url": "https://github.com/agility/agility-content-fetch-js-sdk.git"
8
- },
9
- "bugs": {
10
- "url": "https://github.com/agility/agility-content-fetch-js-sdk.git/issues"
11
- },
12
- "homepage": "https://github.com/agility/agility-content-fetch-js-sdk.git#readme",
13
- "main": "./dist/node.js",
14
- "browser": "./dist/browser.js",
15
- "module": "./dist/browser.js",
16
- "types": "./dist/index.d.ts",
17
- "engines": {
18
- "node": ">= 18.0.0"
19
- },
20
- "scripts": {
21
- "clean": "rimraf dist",
22
- "build": "node build.js",
23
- "prepare": "yarn build",
24
- "test": "jest",
25
- "generate-docs": "node_modules/.bin/jsdoc --configure .jsdoc.json --verbose"
26
- },
27
- "keywords": [
28
- "typescript",
29
- "agility",
30
- "cms",
31
- "headlesscms",
32
- "fetch-sdk"
33
- ],
34
- "author": "Agility CMS",
35
- "contributors": [
36
- "Kevin Tran",
37
- "Joel Varty",
38
- "Aaron Taylor"
39
- ],
40
- "license": "MIT",
41
- "dependencies": {},
42
- "devDependencies": {
43
- "@types/jest": "^29.5.3",
44
- "@types/node": "^18.11.9",
45
- "agility-jsdoc-template": "1.0.3",
46
- "esbuild": "^0.19.0",
47
- "jest": "^29.6.2",
48
- "npm-dts": "^1.3.12",
49
- "rimraf": "^5.0.1",
50
- "ts-jest": "^29.1.1",
51
- "typescript": "^5.1.6"
52
- }
1
+ {
2
+ "name": "@agility/content-fetch",
3
+ "version": "2.0.11",
4
+ "description": "JS/TS library for the Agility Fetch API",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/agility/agility-content-fetch-js-sdk.git"
8
+ },
9
+ "bugs": {
10
+ "url": "https://github.com/agility/agility-content-fetch-js-sdk.git/issues"
11
+ },
12
+ "homepage": "https://github.com/agility/agility-content-fetch-js-sdk.git#readme",
13
+ "main": "./dist/node.js",
14
+ "browser": "./dist/browser.js",
15
+ "module": "./dist/browser.js",
16
+ "types": "./dist/index.d.ts",
17
+ "engines": {
18
+ "node": ">= 18.0.0"
19
+ },
20
+ "scripts": {
21
+ "clean": "rimraf dist",
22
+ "build": "node build.js",
23
+ "prepare": "yarn build",
24
+ "test": "jest",
25
+ "generate-docs": "node_modules/.bin/jsdoc --configure .jsdoc.json --verbose"
26
+ },
27
+ "keywords": [
28
+ "typescript",
29
+ "agility",
30
+ "cms",
31
+ "headlesscms",
32
+ "fetch-sdk"
33
+ ],
34
+ "author": "Agility CMS",
35
+ "contributors": [
36
+ "Kevin Tran",
37
+ "Joel Varty",
38
+ "Aaron Taylor"
39
+ ],
40
+ "license": "MIT",
41
+ "dependencies": {},
42
+ "devDependencies": {
43
+ "@types/jest": "^29.5.3",
44
+ "@types/node": "^18.11.9",
45
+ "agility-jsdoc-template": "1.0.3",
46
+ "esbuild": "^0.19.0",
47
+ "jest": "^29.6.2",
48
+ "npm-dts": "^1.3.12",
49
+ "rimraf": "^5.0.1",
50
+ "ts-jest": "^29.1.1",
51
+ "typescript": "^5.1.6"
52
+ }
53
53
  }
package/tsconfig.json CHANGED
@@ -1,15 +1,15 @@
1
- {
2
- "compilerOptions": {
3
- "module" : "commonjs",
4
- "allowJs": true,
5
- "declaration": true,
6
- "jsx": "react-jsx",
7
- "target": "es5",
8
- "outDir": "./dist/",
9
- "lib": ["es2016", "dom"],
10
- "esModuleInterop": true,
11
- "skipLibCheck": true,
12
- "allowSyntheticDefaultImports": true
13
- },
14
- "include": ["src", "src/api-client.ts"]
1
+ {
2
+ "compilerOptions": {
3
+ "module" : "commonjs",
4
+ "allowJs": true,
5
+ "declaration": true,
6
+ "jsx": "react-jsx",
7
+ "target": "es5",
8
+ "outDir": "./dist/",
9
+ "lib": ["es2016", "dom"],
10
+ "esModuleInterop": true,
11
+ "skipLibCheck": true,
12
+ "allowSyntheticDefaultImports": true
13
+ },
14
+ "include": ["src", "src/api-client.ts"]
15
15
  }