@biza-gov/center-sdk 0.0.0-stage → 1.0.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.
- package/CHANGELOG.md +36 -0
- package/README.md +209 -3
- package/dist/chunk-HRJMMM7P.mjs +260 -0
- package/dist/client-uAuKf1a3.d.mts +4148 -0
- package/dist/client-uAuKf1a3.d.ts +4148 -0
- package/dist/index.d.mts +65 -0
- package/dist/index.d.ts +65 -0
- package/dist/index.js +292 -0
- package/dist/index.mjs +18 -0
- package/dist/testing.d.mts +32 -0
- package/dist/testing.d.ts +32 -0
- package/dist/testing.js +331 -0
- package/dist/testing.mjs +56 -0
- package/package.json +54 -4
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { c as components } from './client-uAuKf1a3.mjs';
|
|
2
|
+
export { A as ApiMethod, G as GOVCENTER_API_URLS, a as GovCenterClient, b as GovCenterClientConfig, d as GovCenterClientInfo, e as GovCenterEnvironment, f as GovCenterPaths, H as HttpMethod, O as Operation, P as PathFor, Q as QueryValue, R as RequestOptions, g as ResponseOf, T as TypedOptions, h as createGovCenterClient } from './client-uAuKf1a3.mjs';
|
|
3
|
+
|
|
4
|
+
type GovCenterErrorCode = 'VALIDATION' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'MISSING_SCOPE' | 'NOT_FOUND' | 'CONFLICT' | 'RATE_LIMITED' | 'UPSTREAM' | 'TIMEOUT' | 'NETWORK' | 'HTTP_ERROR';
|
|
5
|
+
/**
|
|
6
|
+
* Codes GovCenter itself sends in the error body (`GovCenterError.code` carries them as-is).
|
|
7
|
+
* Not exhaustive: new codes may appear, so compare with these but keep a default branch.
|
|
8
|
+
*/
|
|
9
|
+
type GovCenterApiCode = 'MISSING_SCOPE' | 'MUNICIPALITY_NOT_BOUND' | 'MUNICIPALITY_NOT_FOUND' | 'HOUSE_NOT_FOUND' | 'HOUSE_CODE_LOOKUP_LIMIT' | 'CONSENT_REQUIRED' | 'CALLBACK_NOT_ALLOWED' | 'TOTP_REQUIRED' | 'MFA_REQUIRED';
|
|
10
|
+
interface GovCenterErrorOptions {
|
|
11
|
+
status: number;
|
|
12
|
+
message: string;
|
|
13
|
+
code?: string;
|
|
14
|
+
requiredScope?: string;
|
|
15
|
+
retryAfter?: number;
|
|
16
|
+
requestId?: string;
|
|
17
|
+
details?: unknown;
|
|
18
|
+
}
|
|
19
|
+
/** Maps an HTTP status to the SDK error code used when the response body has none. */
|
|
20
|
+
declare function codeForStatus(status: number, requiredScope?: string): GovCenterErrorCode;
|
|
21
|
+
declare class GovCenterError extends Error {
|
|
22
|
+
readonly status: number;
|
|
23
|
+
readonly code: string;
|
|
24
|
+
readonly requiredScope?: string;
|
|
25
|
+
/** Seconds to wait before retrying, from the Retry-After header. */
|
|
26
|
+
readonly retryAfter?: number;
|
|
27
|
+
readonly requestId?: string;
|
|
28
|
+
readonly details?: unknown;
|
|
29
|
+
constructor(options: GovCenterErrorOptions);
|
|
30
|
+
get isRateLimited(): boolean;
|
|
31
|
+
get isUnauthorized(): boolean;
|
|
32
|
+
get isForbidden(): boolean;
|
|
33
|
+
get isNotFound(): boolean;
|
|
34
|
+
get isServerError(): boolean;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
declare function isRetryableStatus(status: number): boolean;
|
|
38
|
+
/** Seconds from a Retry-After header (seconds or HTTP date); undefined when absent or unreadable. */
|
|
39
|
+
declare function parseRetryAfter(header?: string | null): number | undefined;
|
|
40
|
+
declare function calculateBackoff(attempt: number, baseDelayMs?: number, maxDelayMs?: number, retryAfterHeader?: string | null): number;
|
|
41
|
+
|
|
42
|
+
type GovCenterSchemas = components['schemas'];
|
|
43
|
+
/** POST /e-services/sso/verify-code */
|
|
44
|
+
type SsoVerifyResponse = GovCenterSchemas['SsoVerifyResponseDto'];
|
|
45
|
+
type SsoUser = SsoVerifyResponse['user'];
|
|
46
|
+
type SsoMembership = SsoUser['memberships'][number];
|
|
47
|
+
/** ADMIN = municipality admin, MEMBER = everyone else. Duties come from positions. */
|
|
48
|
+
type MunicipalityRole = SsoMembership['role'];
|
|
49
|
+
/** A FILLED seat (C4-08). Council seats carry only branch and level. */
|
|
50
|
+
type SsoPosition = GovCenterSchemas['SsoPositionDto'];
|
|
51
|
+
/** GET /e-services/profiles/:userId (fields outside scope or consent are null) */
|
|
52
|
+
type EServiceProfile = GovCenterSchemas['EServiceProfileDto'];
|
|
53
|
+
type EServiceProfileConsent = GovCenterSchemas['EServiceProfileConsentDto'];
|
|
54
|
+
/** GET /e-services/residences, /by-house-code/:houseCode, /:id?include=members */
|
|
55
|
+
type EServiceResidencePage = GovCenterSchemas['EServiceResidencePageDto'];
|
|
56
|
+
type EServiceResidenceSummary = GovCenterSchemas['EServiceResidenceSummaryDto'];
|
|
57
|
+
type EServiceResidenceDetail = GovCenterSchemas['EServiceResidenceDetailDto'];
|
|
58
|
+
/** GET /e-services/municipalities/:id, /org-units, /staff (scope org:read) */
|
|
59
|
+
type EServiceMunicipality = GovCenterSchemas['EServiceMunicipalityDto'];
|
|
60
|
+
type EServiceOrgUnit = GovCenterSchemas['EServiceOrgUnitDto'];
|
|
61
|
+
type EServiceStaff = GovCenterSchemas['EServiceStaffDto'];
|
|
62
|
+
/** GET /master-data/municipalities/nearby */
|
|
63
|
+
type NearbyMunicipality = GovCenterSchemas['NearbyMunicipalityDto'];
|
|
64
|
+
|
|
65
|
+
export { type EServiceMunicipality, type EServiceOrgUnit, type EServiceProfile, type EServiceProfileConsent, type EServiceResidenceDetail, type EServiceResidencePage, type EServiceResidenceSummary, type EServiceStaff, type GovCenterApiCode, GovCenterError, type GovCenterErrorCode, type GovCenterErrorOptions, type GovCenterSchemas, type MunicipalityRole, type NearbyMunicipality, type SsoMembership, type SsoPosition, type SsoUser, type SsoVerifyResponse, calculateBackoff, codeForStatus, isRetryableStatus, parseRetryAfter };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { c as components } from './client-uAuKf1a3.js';
|
|
2
|
+
export { A as ApiMethod, G as GOVCENTER_API_URLS, a as GovCenterClient, b as GovCenterClientConfig, d as GovCenterClientInfo, e as GovCenterEnvironment, f as GovCenterPaths, H as HttpMethod, O as Operation, P as PathFor, Q as QueryValue, R as RequestOptions, g as ResponseOf, T as TypedOptions, h as createGovCenterClient } from './client-uAuKf1a3.js';
|
|
3
|
+
|
|
4
|
+
type GovCenterErrorCode = 'VALIDATION' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'MISSING_SCOPE' | 'NOT_FOUND' | 'CONFLICT' | 'RATE_LIMITED' | 'UPSTREAM' | 'TIMEOUT' | 'NETWORK' | 'HTTP_ERROR';
|
|
5
|
+
/**
|
|
6
|
+
* Codes GovCenter itself sends in the error body (`GovCenterError.code` carries them as-is).
|
|
7
|
+
* Not exhaustive: new codes may appear, so compare with these but keep a default branch.
|
|
8
|
+
*/
|
|
9
|
+
type GovCenterApiCode = 'MISSING_SCOPE' | 'MUNICIPALITY_NOT_BOUND' | 'MUNICIPALITY_NOT_FOUND' | 'HOUSE_NOT_FOUND' | 'HOUSE_CODE_LOOKUP_LIMIT' | 'CONSENT_REQUIRED' | 'CALLBACK_NOT_ALLOWED' | 'TOTP_REQUIRED' | 'MFA_REQUIRED';
|
|
10
|
+
interface GovCenterErrorOptions {
|
|
11
|
+
status: number;
|
|
12
|
+
message: string;
|
|
13
|
+
code?: string;
|
|
14
|
+
requiredScope?: string;
|
|
15
|
+
retryAfter?: number;
|
|
16
|
+
requestId?: string;
|
|
17
|
+
details?: unknown;
|
|
18
|
+
}
|
|
19
|
+
/** Maps an HTTP status to the SDK error code used when the response body has none. */
|
|
20
|
+
declare function codeForStatus(status: number, requiredScope?: string): GovCenterErrorCode;
|
|
21
|
+
declare class GovCenterError extends Error {
|
|
22
|
+
readonly status: number;
|
|
23
|
+
readonly code: string;
|
|
24
|
+
readonly requiredScope?: string;
|
|
25
|
+
/** Seconds to wait before retrying, from the Retry-After header. */
|
|
26
|
+
readonly retryAfter?: number;
|
|
27
|
+
readonly requestId?: string;
|
|
28
|
+
readonly details?: unknown;
|
|
29
|
+
constructor(options: GovCenterErrorOptions);
|
|
30
|
+
get isRateLimited(): boolean;
|
|
31
|
+
get isUnauthorized(): boolean;
|
|
32
|
+
get isForbidden(): boolean;
|
|
33
|
+
get isNotFound(): boolean;
|
|
34
|
+
get isServerError(): boolean;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
declare function isRetryableStatus(status: number): boolean;
|
|
38
|
+
/** Seconds from a Retry-After header (seconds or HTTP date); undefined when absent or unreadable. */
|
|
39
|
+
declare function parseRetryAfter(header?: string | null): number | undefined;
|
|
40
|
+
declare function calculateBackoff(attempt: number, baseDelayMs?: number, maxDelayMs?: number, retryAfterHeader?: string | null): number;
|
|
41
|
+
|
|
42
|
+
type GovCenterSchemas = components['schemas'];
|
|
43
|
+
/** POST /e-services/sso/verify-code */
|
|
44
|
+
type SsoVerifyResponse = GovCenterSchemas['SsoVerifyResponseDto'];
|
|
45
|
+
type SsoUser = SsoVerifyResponse['user'];
|
|
46
|
+
type SsoMembership = SsoUser['memberships'][number];
|
|
47
|
+
/** ADMIN = municipality admin, MEMBER = everyone else. Duties come from positions. */
|
|
48
|
+
type MunicipalityRole = SsoMembership['role'];
|
|
49
|
+
/** A FILLED seat (C4-08). Council seats carry only branch and level. */
|
|
50
|
+
type SsoPosition = GovCenterSchemas['SsoPositionDto'];
|
|
51
|
+
/** GET /e-services/profiles/:userId (fields outside scope or consent are null) */
|
|
52
|
+
type EServiceProfile = GovCenterSchemas['EServiceProfileDto'];
|
|
53
|
+
type EServiceProfileConsent = GovCenterSchemas['EServiceProfileConsentDto'];
|
|
54
|
+
/** GET /e-services/residences, /by-house-code/:houseCode, /:id?include=members */
|
|
55
|
+
type EServiceResidencePage = GovCenterSchemas['EServiceResidencePageDto'];
|
|
56
|
+
type EServiceResidenceSummary = GovCenterSchemas['EServiceResidenceSummaryDto'];
|
|
57
|
+
type EServiceResidenceDetail = GovCenterSchemas['EServiceResidenceDetailDto'];
|
|
58
|
+
/** GET /e-services/municipalities/:id, /org-units, /staff (scope org:read) */
|
|
59
|
+
type EServiceMunicipality = GovCenterSchemas['EServiceMunicipalityDto'];
|
|
60
|
+
type EServiceOrgUnit = GovCenterSchemas['EServiceOrgUnitDto'];
|
|
61
|
+
type EServiceStaff = GovCenterSchemas['EServiceStaffDto'];
|
|
62
|
+
/** GET /master-data/municipalities/nearby */
|
|
63
|
+
type NearbyMunicipality = GovCenterSchemas['NearbyMunicipalityDto'];
|
|
64
|
+
|
|
65
|
+
export { type EServiceMunicipality, type EServiceOrgUnit, type EServiceProfile, type EServiceProfileConsent, type EServiceResidenceDetail, type EServiceResidencePage, type EServiceResidenceSummary, type EServiceStaff, type GovCenterApiCode, GovCenterError, type GovCenterErrorCode, type GovCenterErrorOptions, type GovCenterSchemas, type MunicipalityRole, type NearbyMunicipality, type SsoMembership, type SsoPosition, type SsoUser, type SsoVerifyResponse, calculateBackoff, codeForStatus, isRetryableStatus, parseRetryAfter };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
GOVCENTER_API_URLS: () => GOVCENTER_API_URLS,
|
|
24
|
+
GovCenterError: () => GovCenterError,
|
|
25
|
+
calculateBackoff: () => calculateBackoff,
|
|
26
|
+
codeForStatus: () => codeForStatus,
|
|
27
|
+
createGovCenterClient: () => createGovCenterClient,
|
|
28
|
+
isRetryableStatus: () => isRetryableStatus,
|
|
29
|
+
parseRetryAfter: () => parseRetryAfter
|
|
30
|
+
});
|
|
31
|
+
module.exports = __toCommonJS(index_exports);
|
|
32
|
+
|
|
33
|
+
// src/error.ts
|
|
34
|
+
function codeForStatus(status, requiredScope) {
|
|
35
|
+
if (status === 400 || status === 422) return "VALIDATION";
|
|
36
|
+
if (status === 401) return "UNAUTHORIZED";
|
|
37
|
+
if (status === 403) return requiredScope ? "MISSING_SCOPE" : "FORBIDDEN";
|
|
38
|
+
if (status === 404) return "NOT_FOUND";
|
|
39
|
+
if (status === 409) return "CONFLICT";
|
|
40
|
+
if (status === 429) return "RATE_LIMITED";
|
|
41
|
+
if (status >= 500) return "UPSTREAM";
|
|
42
|
+
return "HTTP_ERROR";
|
|
43
|
+
}
|
|
44
|
+
var GovCenterError = class _GovCenterError extends Error {
|
|
45
|
+
status;
|
|
46
|
+
code;
|
|
47
|
+
requiredScope;
|
|
48
|
+
/** Seconds to wait before retrying, from the Retry-After header. */
|
|
49
|
+
retryAfter;
|
|
50
|
+
requestId;
|
|
51
|
+
details;
|
|
52
|
+
constructor(options) {
|
|
53
|
+
super(options.message);
|
|
54
|
+
this.name = "GovCenterError";
|
|
55
|
+
this.status = options.status;
|
|
56
|
+
this.code = options.code ?? codeForStatus(options.status, options.requiredScope);
|
|
57
|
+
this.requiredScope = options.requiredScope;
|
|
58
|
+
this.retryAfter = options.retryAfter;
|
|
59
|
+
this.requestId = options.requestId;
|
|
60
|
+
this.details = options.details;
|
|
61
|
+
Object.setPrototypeOf(this, _GovCenterError.prototype);
|
|
62
|
+
}
|
|
63
|
+
get isRateLimited() {
|
|
64
|
+
return this.status === 429;
|
|
65
|
+
}
|
|
66
|
+
get isUnauthorized() {
|
|
67
|
+
return this.status === 401;
|
|
68
|
+
}
|
|
69
|
+
get isForbidden() {
|
|
70
|
+
return this.status === 403;
|
|
71
|
+
}
|
|
72
|
+
get isNotFound() {
|
|
73
|
+
return this.status === 404;
|
|
74
|
+
}
|
|
75
|
+
get isServerError() {
|
|
76
|
+
return this.status >= 500;
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// src/retry.ts
|
|
81
|
+
function isRetryableStatus(status) {
|
|
82
|
+
return status === 429 || status === 502 || status === 503 || status === 504;
|
|
83
|
+
}
|
|
84
|
+
async function wait(ms) {
|
|
85
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
86
|
+
}
|
|
87
|
+
function parseRetryAfter(header) {
|
|
88
|
+
if (!header) return void 0;
|
|
89
|
+
const seconds = Number(header);
|
|
90
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds;
|
|
91
|
+
const date = Date.parse(header);
|
|
92
|
+
if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1e3));
|
|
93
|
+
return void 0;
|
|
94
|
+
}
|
|
95
|
+
function calculateBackoff(attempt, baseDelayMs = 300, maxDelayMs = 5e3, retryAfterHeader) {
|
|
96
|
+
const retryAfter = parseRetryAfter(retryAfterHeader);
|
|
97
|
+
if (retryAfter !== void 0) {
|
|
98
|
+
return Math.min(retryAfter * 1e3, maxDelayMs);
|
|
99
|
+
}
|
|
100
|
+
const exp = Math.min(baseDelayMs * Math.pow(2, attempt), maxDelayMs);
|
|
101
|
+
const jitter = exp * (0.8 + Math.random() * 0.4);
|
|
102
|
+
return Math.floor(jitter);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// src/client.ts
|
|
106
|
+
var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
|
|
107
|
+
var GOVCENTER_API_URLS = Object.freeze({
|
|
108
|
+
production: "https://api-auth.govcenter.co",
|
|
109
|
+
uat: "https://uat-api-auth.govcenter.co"
|
|
110
|
+
});
|
|
111
|
+
function readEnvironment(value) {
|
|
112
|
+
if (!value) return null;
|
|
113
|
+
const name = value.trim().toLowerCase();
|
|
114
|
+
if (name === "prod") return "production";
|
|
115
|
+
if (name === "production" || name === "uat") return name;
|
|
116
|
+
throw new Error(`Unknown GovCenter environment "${value}": use "uat" or "production"`);
|
|
117
|
+
}
|
|
118
|
+
function generateRequestId() {
|
|
119
|
+
if (typeof globalThis !== "undefined" && globalThis.crypto && typeof globalThis.crypto.randomUUID === "function") {
|
|
120
|
+
return globalThis.crypto.randomUUID();
|
|
121
|
+
}
|
|
122
|
+
return `gc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 11)}`;
|
|
123
|
+
}
|
|
124
|
+
function isBrowser() {
|
|
125
|
+
const g = globalThis;
|
|
126
|
+
return typeof g.window !== "undefined" && typeof g.document !== "undefined";
|
|
127
|
+
}
|
|
128
|
+
function needsApiKey(path) {
|
|
129
|
+
return path === "/e-services" || path.startsWith("/e-services/");
|
|
130
|
+
}
|
|
131
|
+
function errorMessage(body, fallback) {
|
|
132
|
+
const message = body?.message;
|
|
133
|
+
if (Array.isArray(message)) return message.join(", ");
|
|
134
|
+
if (typeof message === "string" && message) return message;
|
|
135
|
+
return fallback;
|
|
136
|
+
}
|
|
137
|
+
function createGovCenterClient(config = {}) {
|
|
138
|
+
if (isBrowser() && !config.dangerouslyAllowBrowser) {
|
|
139
|
+
throw new Error(
|
|
140
|
+
"gov-center-sdk runs on the server only: the API key would be visible to every visitor. Call your own backend from the browser instead."
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
const env = globalThis.process?.env ?? {};
|
|
144
|
+
const environment = readEnvironment(config.environment ?? env.GOVCENTER_ENV);
|
|
145
|
+
const baseUrl = (config.baseUrl || env.GOVCENTER_API_URL || env.IAM_API_URL || (environment ? GOVCENTER_API_URLS[environment] : "http://localhost:4001")).replace(/\/+$/, "");
|
|
146
|
+
const apiKey = config.apiKey ?? env.E_SERVICE_API_KEY ?? "";
|
|
147
|
+
const apiSecret = config.apiSecret ?? env.E_SERVICE_API_SECRET ?? "";
|
|
148
|
+
const serviceCode = (config.serviceCode ?? env.E_SERVICE_CODE ?? "").trim();
|
|
149
|
+
const timeoutMs = config.timeoutMs ?? 1e4;
|
|
150
|
+
const maxRetries = config.maxRetries ?? 2;
|
|
151
|
+
const customFetch = config.fetch || globalThis.fetch;
|
|
152
|
+
let parsedBase;
|
|
153
|
+
try {
|
|
154
|
+
parsedBase = new URL(baseUrl);
|
|
155
|
+
} catch {
|
|
156
|
+
throw new Error(`Invalid GovCenter baseUrl: ${baseUrl}`);
|
|
157
|
+
}
|
|
158
|
+
if (parsedBase.protocol !== "https:" && !(parsedBase.protocol === "http:" && LOCAL_HOSTS.has(parsedBase.hostname))) {
|
|
159
|
+
throw new Error(`GovCenter baseUrl must use https (http is allowed only for localhost): ${baseUrl}`);
|
|
160
|
+
}
|
|
161
|
+
if (typeof customFetch !== "function") {
|
|
162
|
+
throw new Error(
|
|
163
|
+
"Global fetch is not available in this environment. Please pass a custom fetch to createGovCenterClient({ fetch })."
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
function resolvePath(path, params) {
|
|
167
|
+
let resolved = path.startsWith("/") ? path : `/${path}`;
|
|
168
|
+
if (params) {
|
|
169
|
+
for (const [key, val] of Object.entries(params)) {
|
|
170
|
+
resolved = resolved.replace(new RegExp(`:${key}\\b`, "g"), encodeURIComponent(String(val)));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
const missing = resolved.match(/\/:([A-Za-z_][A-Za-z0-9_]*)/);
|
|
174
|
+
if (missing) {
|
|
175
|
+
throw new Error(`Missing path parameter "${missing[1]}" for ${path}`);
|
|
176
|
+
}
|
|
177
|
+
if (baseUrl.endsWith("/v1") && (resolved === "/v1" || resolved.startsWith("/v1/"))) {
|
|
178
|
+
resolved = resolved.slice(3) || "/";
|
|
179
|
+
}
|
|
180
|
+
return resolved;
|
|
181
|
+
}
|
|
182
|
+
function buildUrl(resolvedPath, query) {
|
|
183
|
+
let url = `${baseUrl}${resolvedPath}`;
|
|
184
|
+
if (query) {
|
|
185
|
+
const searchParams = new URLSearchParams();
|
|
186
|
+
for (const [key, val] of Object.entries(query)) {
|
|
187
|
+
if (val === void 0 || val === null) continue;
|
|
188
|
+
searchParams.append(key, Array.isArray(val) ? val.join(",") : String(val));
|
|
189
|
+
}
|
|
190
|
+
const qs = searchParams.toString();
|
|
191
|
+
if (qs) url += (url.includes("?") ? "&" : "?") + qs;
|
|
192
|
+
}
|
|
193
|
+
return url;
|
|
194
|
+
}
|
|
195
|
+
async function executeRequest(method, path, options = {}) {
|
|
196
|
+
const resolvedPath = resolvePath(path, options.params);
|
|
197
|
+
const url = buildUrl(resolvedPath, options.query);
|
|
198
|
+
const requestId = generateRequestId();
|
|
199
|
+
const headers = {
|
|
200
|
+
Accept: "application/json",
|
|
201
|
+
"x-request-id": requestId,
|
|
202
|
+
...options.headers
|
|
203
|
+
};
|
|
204
|
+
if (apiKey && needsApiKey(resolvedPath)) {
|
|
205
|
+
headers["x-api-key"] = apiKey;
|
|
206
|
+
if (serviceCode) headers["x-e-service-code"] = serviceCode;
|
|
207
|
+
}
|
|
208
|
+
if (options.idempotencyKey) {
|
|
209
|
+
headers["Idempotency-Key"] = options.idempotencyKey;
|
|
210
|
+
}
|
|
211
|
+
let requestBody;
|
|
212
|
+
if (options.body !== void 0 && options.body !== null) {
|
|
213
|
+
headers["Content-Type"] = "application/json";
|
|
214
|
+
requestBody = typeof options.body === "string" ? options.body : JSON.stringify(options.body);
|
|
215
|
+
}
|
|
216
|
+
const currentTimeout = options.timeoutMs ?? timeoutMs;
|
|
217
|
+
const canRetry = method === "GET" || Boolean(options.idempotencyKey);
|
|
218
|
+
let attempt = 0;
|
|
219
|
+
while (true) {
|
|
220
|
+
const controller = new AbortController();
|
|
221
|
+
const timer = setTimeout(() => controller.abort(), currentTimeout);
|
|
222
|
+
let response;
|
|
223
|
+
try {
|
|
224
|
+
response = await customFetch(url, { method, headers, body: requestBody, signal: controller.signal });
|
|
225
|
+
} catch (err) {
|
|
226
|
+
clearTimeout(timer);
|
|
227
|
+
const isAbort = err?.name === "AbortError";
|
|
228
|
+
if (canRetry && attempt < maxRetries) {
|
|
229
|
+
await wait(calculateBackoff(attempt));
|
|
230
|
+
attempt++;
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
throw new GovCenterError({
|
|
234
|
+
status: 0,
|
|
235
|
+
code: isAbort ? "TIMEOUT" : "NETWORK",
|
|
236
|
+
message: isAbort ? `GovCenter request timeout after ${currentTimeout}ms` : err?.message || "Network request failed",
|
|
237
|
+
requestId
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
clearTimeout(timer);
|
|
241
|
+
if (response.ok) {
|
|
242
|
+
if (response.status === 204) return void 0;
|
|
243
|
+
const text = await response.text();
|
|
244
|
+
return text ? JSON.parse(text) : void 0;
|
|
245
|
+
}
|
|
246
|
+
const retryAfterHeader = response.headers?.get?.("Retry-After") ?? null;
|
|
247
|
+
if (canRetry && isRetryableStatus(response.status) && attempt < maxRetries) {
|
|
248
|
+
await wait(calculateBackoff(attempt, 300, 5e3, retryAfterHeader));
|
|
249
|
+
attempt++;
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
let errorBody = void 0;
|
|
253
|
+
try {
|
|
254
|
+
const text = await response.text();
|
|
255
|
+
errorBody = text ? JSON.parse(text) : void 0;
|
|
256
|
+
} catch {
|
|
257
|
+
errorBody = void 0;
|
|
258
|
+
}
|
|
259
|
+
const body = errorBody ?? {};
|
|
260
|
+
const message = errorMessage(errorBody, response.statusText || `Request failed with status ${response.status}`);
|
|
261
|
+
const scopeInMessage = response.status === 403 ? message.match(/missing [\w-]* ?scope:\s*([\w:.-]+)/i)?.[1] : void 0;
|
|
262
|
+
throw new GovCenterError({
|
|
263
|
+
status: response.status,
|
|
264
|
+
message,
|
|
265
|
+
code: typeof body.code === "string" ? body.code : void 0,
|
|
266
|
+
requiredScope: typeof body.requiredScope === "string" ? body.requiredScope : scopeInMessage,
|
|
267
|
+
retryAfter: parseRetryAfter(retryAfterHeader),
|
|
268
|
+
requestId: response.headers?.get?.("x-request-id") || requestId,
|
|
269
|
+
details: errorBody
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const call = (method) => (path, options) => executeRequest(method, path, options);
|
|
274
|
+
return {
|
|
275
|
+
get: call("GET"),
|
|
276
|
+
post: call("POST"),
|
|
277
|
+
patch: call("PATCH"),
|
|
278
|
+
delete: call("DELETE"),
|
|
279
|
+
request: (method, path, options) => executeRequest(method, path, options),
|
|
280
|
+
getConfig: () => Object.freeze({ baseUrl, environment, timeoutMs, maxRetries, hasApiKey: Boolean(apiKey), hasApiSecret: Boolean(apiSecret), serviceCode })
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
284
|
+
0 && (module.exports = {
|
|
285
|
+
GOVCENTER_API_URLS,
|
|
286
|
+
GovCenterError,
|
|
287
|
+
calculateBackoff,
|
|
288
|
+
codeForStatus,
|
|
289
|
+
createGovCenterClient,
|
|
290
|
+
isRetryableStatus,
|
|
291
|
+
parseRetryAfter
|
|
292
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import {
|
|
2
|
+
GOVCENTER_API_URLS,
|
|
3
|
+
GovCenterError,
|
|
4
|
+
calculateBackoff,
|
|
5
|
+
codeForStatus,
|
|
6
|
+
createGovCenterClient,
|
|
7
|
+
isRetryableStatus,
|
|
8
|
+
parseRetryAfter
|
|
9
|
+
} from "./chunk-HRJMMM7P.mjs";
|
|
10
|
+
export {
|
|
11
|
+
GOVCENTER_API_URLS,
|
|
12
|
+
GovCenterError,
|
|
13
|
+
calculateBackoff,
|
|
14
|
+
codeForStatus,
|
|
15
|
+
createGovCenterClient,
|
|
16
|
+
isRetryableStatus,
|
|
17
|
+
parseRetryAfter
|
|
18
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { H as HttpMethod, b as GovCenterClientConfig, a as GovCenterClient } from './client-uAuKf1a3.mjs';
|
|
2
|
+
|
|
3
|
+
interface MockRequest {
|
|
4
|
+
method: HttpMethod;
|
|
5
|
+
path: string;
|
|
6
|
+
params: Record<string, string>;
|
|
7
|
+
query: Record<string, string>;
|
|
8
|
+
body: unknown;
|
|
9
|
+
headers: Record<string, string>;
|
|
10
|
+
}
|
|
11
|
+
/** A plain value is returned as-is; a function gets the request. Return a `MockResponse` to set the status. */
|
|
12
|
+
type MockHandler = unknown | ((req: MockRequest) => unknown | Promise<unknown>);
|
|
13
|
+
interface MockResponse {
|
|
14
|
+
__mockResponse: true;
|
|
15
|
+
status: number;
|
|
16
|
+
body?: unknown;
|
|
17
|
+
headers?: Record<string, string>;
|
|
18
|
+
}
|
|
19
|
+
/** Answer a mocked call with a specific status, e.g. `mockResponse(403, { message: 'no scope' })`. */
|
|
20
|
+
declare function mockResponse(status: number, body?: unknown, headers?: Record<string, string>): MockResponse;
|
|
21
|
+
/**
|
|
22
|
+
* A GovCenter client for tests: requests go to the given routes instead of the network.
|
|
23
|
+
* Unknown routes answer 404, so a typo in a path fails the test.
|
|
24
|
+
*
|
|
25
|
+
* const gc = createGovCenterMock({ 'GET /e-services/gis/catalog': { layers: [] } });
|
|
26
|
+
* gc.calls // every request made, in order
|
|
27
|
+
*/
|
|
28
|
+
declare function createGovCenterMock(routes: Record<string, MockHandler>, config?: Omit<GovCenterClientConfig, 'fetch'>): GovCenterClient & {
|
|
29
|
+
calls: MockRequest[];
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export { type MockHandler, type MockRequest, type MockResponse, createGovCenterMock, mockResponse };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { H as HttpMethod, b as GovCenterClientConfig, a as GovCenterClient } from './client-uAuKf1a3.js';
|
|
2
|
+
|
|
3
|
+
interface MockRequest {
|
|
4
|
+
method: HttpMethod;
|
|
5
|
+
path: string;
|
|
6
|
+
params: Record<string, string>;
|
|
7
|
+
query: Record<string, string>;
|
|
8
|
+
body: unknown;
|
|
9
|
+
headers: Record<string, string>;
|
|
10
|
+
}
|
|
11
|
+
/** A plain value is returned as-is; a function gets the request. Return a `MockResponse` to set the status. */
|
|
12
|
+
type MockHandler = unknown | ((req: MockRequest) => unknown | Promise<unknown>);
|
|
13
|
+
interface MockResponse {
|
|
14
|
+
__mockResponse: true;
|
|
15
|
+
status: number;
|
|
16
|
+
body?: unknown;
|
|
17
|
+
headers?: Record<string, string>;
|
|
18
|
+
}
|
|
19
|
+
/** Answer a mocked call with a specific status, e.g. `mockResponse(403, { message: 'no scope' })`. */
|
|
20
|
+
declare function mockResponse(status: number, body?: unknown, headers?: Record<string, string>): MockResponse;
|
|
21
|
+
/**
|
|
22
|
+
* A GovCenter client for tests: requests go to the given routes instead of the network.
|
|
23
|
+
* Unknown routes answer 404, so a typo in a path fails the test.
|
|
24
|
+
*
|
|
25
|
+
* const gc = createGovCenterMock({ 'GET /e-services/gis/catalog': { layers: [] } });
|
|
26
|
+
* gc.calls // every request made, in order
|
|
27
|
+
*/
|
|
28
|
+
declare function createGovCenterMock(routes: Record<string, MockHandler>, config?: Omit<GovCenterClientConfig, 'fetch'>): GovCenterClient & {
|
|
29
|
+
calls: MockRequest[];
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export { type MockHandler, type MockRequest, type MockResponse, createGovCenterMock, mockResponse };
|