Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .talismanrc
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ fileignoreconfig:
ignore_detectors:
- filecontent
- filename: package-lock.json
checksum: 497081f339bddec3868c2469b5266cb248a1aed8ce6fbab57bbc77fb9f412be6
checksum: d55fde89f42bf080e243915bc5c3fd1d0302e1d11c0b14deb62fef3574c5ba56
- filename: src/entry-editable.ts
checksum: 3ba7af9ed1c1adef2e2bd5610099716562bebb8ba750d4b41ddda99fc9eaf115
- filename: .husky/pre-commit
Expand Down
22 changes: 16 additions & 6 deletions __test__/endpoints.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
import { getContentstackEndpoint, ContentstackEndpoints, RegionData, RegionsResponse } from '../src/endpoints';
import { getContentstackEndpoint, ContentstackEndpoints } from '../src/endpoints';
import * as path from 'path';
import * as fs from 'fs';

// Mock console.warn to avoid noise in tests
const originalConsoleWarn = console.warn;

beforeAll(() => {
console.warn = jest.fn();

// Verify build completed - dist/lib/regions.json must exist
// The pretest hook ensures build runs before tests
const regionsPath = path.join(process.cwd(), 'dist', 'lib', 'regions.json');

if (!fs.existsSync(regionsPath)) {
throw new Error('dist/lib/regions.json not found. Please run "npm run build" first. The pretest hook should have handled this automatically.');
}
});

afterAll(() => {
Expand Down Expand Up @@ -114,11 +125,10 @@ describe('getContentstackEndpoint', () => {
});

it('should handle malformed regions data gracefully', () => {
const malformedData: RegionsResponse = {
regions: null as any
};

const result = getContentstackEndpoint('us', 'contentDelivery', false, malformedData);
// Note: This test now verifies that invalid regions fallback to default endpoint
// The malformed data scenario is handled by getRegions() throwing an error
// which causes getContentstackEndpoint to fall back to getDefaultEndpoint
const result = getContentstackEndpoint('us', 'contentDelivery', false);

expect(result).toBe('https://cdn.contentstack.io');
});
Expand Down
5 changes: 5 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ export default [
ecmaVersion: 'latest',
sourceType: 'module',
},
globals: {
console: 'readonly',
__dirname: 'readonly',
require: 'readonly',
},
},
plugins: {
'@typescript-eslint': tseslint,
Expand Down
93 changes: 60 additions & 33 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,20 @@
"scripts": {
"clear:reports": "rm -rf reports",
"clear:badges": "rm -rf badges",
"pretest": "npm run build",
"test": "npm run clear:reports && jest --ci --json --coverage --testLocationInResults --outputFile=./reports/report.json",
"test:badges": "npm run clear:badges && npm run test && jest-coverage-badges --input ./reports/coverage/coverage-summary.json --output ./badges",
"test:debug": "jest --watchAll --runInBand",
"prebuild": "rimraf dist",
"prebuild": "rimraf dist && mkdir -p dist/lib && curl -s --max-time 30 --fail https://artifacts.contentstack.com/regions.json -o dist/lib/regions.json || echo 'Warning: Failed to download regions.json'",
"build": "tsc && rollup -c",
"format": "prettier --write \"src/**/*.ts\"",
"prepare": "husky install && npm run build",
"prepublishOnly": "npm test",
"pre-commit": "husky install && husky && chmod +x .husky/pre-commit && ./.husky/pre-commit",
"version": "npm run format && git add -A src",
"postversion": "git push && git push --tags",
"postinstall": "curl -s --max-time 30 --fail https://artifacts.contentstack.com/regions.json -o regions.json || echo 'Warning: Failed to download regions.json, using existing file if available'",
"postupdate": "curl -s --max-time 30 --fail https://artifacts.contentstack.com/regions.json -o regions.json || echo 'Warning: Failed to download regions.json, using existing file if available'"
"postinstall": "curl -s --max-time 30 --fail https://artifacts.contentstack.com/regions.json -o dist/lib/regions.json || echo 'Warning: Failed to download regions.json, using existing file if available'",
"postupdate": "curl -s --max-time 30 --fail https://artifacts.contentstack.com/regions.json -o dist/lib/regions.json || echo 'Warning: Failed to download regions.json, using existing file if available'"
},
"author": "Contentstack",
"license": "MIT",
Expand Down
5 changes: 5 additions & 0 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ module.exports = {
external: [
...Object.keys(pkg.dependencies || {}),
...Object.keys(pkg.peerDependencies || {}),
// Node.js built-ins
'fs',
'path',
// Exclude regions.json from bundling - it's loaded at runtime
/regions\.json$/,
],
plugins: [
// Allow json resolution
Expand Down
48 changes: 41 additions & 7 deletions src/endpoints.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import regions from '../regions.json'
/// <reference types="node" />
import * as path from 'path';
import * as fs from 'fs';

// Type declarations for CommonJS runtime (rollup outputs CommonJS format)
declare const __dirname: string;

export interface ContentstackEndpoints {
[key: string]: string | ContentstackEndpoints;
}
Expand All @@ -17,17 +23,44 @@ export interface RegionsResponse {
regions: RegionData[];
}

export function getContentstackEndpoint(region: string = 'us', service: string = '', omitHttps: boolean = false, localRegionsData?: RegionsResponse): string | ContentstackEndpoints {
// Load regions.json at runtime from the dist/lib directory
function loadRegions(): RegionsResponse {
// The bundled file is at dist/index.es.js, regions.json is at dist/lib/regions.json
// So __dirname will be 'dist/' and we need to go to 'dist/lib/regions.json'
const regionsPath = path.join(__dirname, 'lib', 'regions.json');

if (fs.existsSync(regionsPath)) {
try {
const regionsData = fs.readFileSync(regionsPath, 'utf-8');
return JSON.parse(regionsData);
} catch (error) {
throw new Error(`Failed to parse regions.json: ${error instanceof Error ? error.message : String(error)}`);
}
}

// If not found, throw clear error
throw new Error('regions.json file not found at dist/lib/regions.json. Please ensure the package is properly installed and postinstall script has run.');
}

// Cache the loaded regions data
let cachedRegions: RegionsResponse | null = null;

function getRegions(): RegionsResponse {
if (!cachedRegions) {
cachedRegions = loadRegions();
}
return cachedRegions;
}

export function getContentstackEndpoint(region: string = 'us', service: string = '', omitHttps: boolean = false): string | ContentstackEndpoints {
// Validate empty region before any processing
if (region === '') {
console.warn('Invalid region: empty or invalid region provided');
throw new Error('Unable to set the host. Please put valid host');
}

try {
let regionsData: RegionsResponse;

regionsData = regions;
const regionsData: RegionsResponse = getRegions();

// Normalize the region input
const normalizedRegion = region.toLowerCase().trim() || 'us';
Expand Down Expand Up @@ -64,7 +97,7 @@ export function getContentstackEndpoint(region: string = 'us', service: string =

if (!endpoint) {
// For invalid services, return undefined (as expected by some tests)
return undefined as any;
return undefined as unknown as ContentstackEndpoints;
}
} else {
return omitHttps ? stripHttps(regionData.endpoints) : regionData.endpoints;
Expand All @@ -78,7 +111,8 @@ export function getContentstackEndpoint(region: string = 'us', service: string =
}

function getDefaultEndpoint(service: string, omitHttps: boolean): string {
const defaultEndpoints: ContentstackEndpoints = regions.regions.find(r => r.isDefault)?.endpoints || {};
const regions = getRegions();
const defaultEndpoints: ContentstackEndpoints = regions.regions.find((r: RegionData) => r.isDefault)?.endpoints || {};

const value = defaultEndpoints[service];
const endpoint = typeof value === 'string' ? value : 'https://cdn.contentstack.io';
Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"resolveJsonModule": true,
"strictNullChecks": false,
"sourceMap": true,
"skipLibCheck": true,
},
"include": ["src"],
"exclude": ["node_modules", "__test__"]
Expand Down
Loading