@settlemint/sdk-utils 2.3.2-pra61423f8 → 2.3.2-pra76ade69
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/dist/environment.cjs +3 -2
- package/dist/environment.cjs.map +1 -1
- package/dist/environment.d.cts +2 -2
- package/dist/environment.d.ts +2 -2
- package/dist/environment.mjs +3 -2
- package/dist/environment.mjs.map +1 -1
- package/dist/http.cjs +18 -0
- package/dist/http.cjs.map +1 -1
- package/dist/http.d.cts +6 -1
- package/dist/http.d.ts +6 -1
- package/dist/http.mjs +17 -0
- package/dist/http.mjs.map +1 -1
- package/dist/index.cjs +9 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -1
- package/dist/index.d.ts +17 -1
- package/dist/index.mjs +8 -0
- package/dist/index.mjs.map +1 -1
- package/dist/validation.cjs +5 -2
- package/dist/validation.cjs.map +1 -1
- package/dist/validation.d.cts +7 -3
- package/dist/validation.d.ts +7 -3
- package/dist/validation.mjs +4 -2
- package/dist/validation.mjs.map +1 -1
- package/package.json +1 -1
package/dist/http.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/http.ts","../src/retry.ts","../src/http/fetch-with-retry.ts","../src/http/graphql-fetch-with-retry.ts"],"sourcesContent":["export { fetchWithRetry } from \"./http/fetch-with-retry.js\";\nexport { graphqlFetchWithRetry } from \"./http/graphql-fetch-with-retry.js\";\n","/**\n * Retry a function when it fails.\n * @param fn - The function to retry.\n * @param maxRetries - The maximum number of retries.\n * @param initialSleepTime - The initial time to sleep between exponential backoff retries.\n * @param stopOnError - The function to stop on error.\n * @returns The result of the function or undefined if it fails.\n * @example\n * import { retryWhenFailed } from \"@settlemint/sdk-utils\";\n * import { readFile } from \"node:fs/promises\";\n *\n * const result = await retryWhenFailed(() => readFile(\"/path/to/file.txt\"), 3, 1_000);\n */\nexport async function retryWhenFailed<T>(\n fn: () => Promise<T>,\n maxRetries = 5,\n initialSleepTime = 1_000,\n stopOnError?: (error: Error) => boolean,\n): Promise<T> {\n let attempt = 0;\n\n while (attempt < maxRetries) {\n try {\n return await fn();\n } catch (e) {\n if (typeof stopOnError === \"function\") {\n const error = e as Error;\n if (stopOnError(error)) {\n throw error;\n }\n }\n attempt += 1;\n if (attempt >= maxRetries) {\n throw e;\n }\n // Exponential backoff with full jitter to prevent thundering herd\n const jitter = Math.random();\n const delay = 2 ** attempt * initialSleepTime * jitter; // 0-1x of 1s, 2s, 4s base\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new Error(\"Retry failed\");\n}\n","import { retryWhenFailed } from \"../retry.js\";\n\n/**\n * Retry an HTTP request with exponential backoff and jitter.\n * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.\n *\n * @param input - The URL or Request object to fetch\n * @param init - The fetch init options\n * @param maxRetries - Maximum number of retry attempts\n * @param initialSleepTime - Initial sleep time between retries in ms\n * @returns The fetch Response\n * @throws Error if all retries fail\n * @example\n * import { fetchWithRetry } from \"@settlemint/sdk-utils/http\";\n *\n * const response = await fetchWithRetry(\"https://api.example.com/data\");\n */\nexport async function fetchWithRetry(\n input: RequestInfo | URL,\n init?: RequestInit,\n maxRetries = 5,\n initialSleepTime = 3_000,\n): Promise<Response> {\n return retryWhenFailed(\n async () => {\n const response = await fetch(input, init);\n if (response.ok) {\n return response;\n }\n // Only retry on 5xx server errors, 429 rate limit, timeout, and network errors\n if (response.status < 500 && response.status !== 429 && response.status !== 408 && response.status !== 0) {\n return response;\n }\n throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`);\n },\n maxRetries,\n initialSleepTime,\n );\n}\n","import { retryWhenFailed } from \"../retry.js\";\nimport { fetchWithRetry } from \"./fetch-with-retry.js\";\n\n/**\n * Executes a GraphQL request with automatic retries using exponential backoff and jitter.\n * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.\n * Will also retry if the GraphQL response contains errors.\n *\n * @param input - The URL or Request object for the GraphQL endpoint\n * @param init - Optional fetch configuration options\n * @param maxRetries - Maximum retry attempts before failing (default: 5)\n * @param initialSleepTime - Initial delay between retries in milliseconds (default: 3000)\n * @returns The parsed GraphQL response data\n * @throws Error if all retries fail or if GraphQL response contains errors\n * @example\n * import { graphqlFetchWithRetry } from \"@settlemint/sdk-utils/http\";\n *\n * const data = await graphqlFetchWithRetry<{ user: { id: string } }>(\n * \"https://api.example.com/graphql\",\n * {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({\n * query: `query GetUser($id: ID!) {\n * user(id: $id) {\n * id\n * }\n * }`,\n * variables: { id: \"123\" }\n * })\n * }\n * );\n */\nexport async function graphqlFetchWithRetry<Data>(\n input: RequestInfo | URL,\n init?: RequestInit,\n maxRetries = 5,\n initialSleepTime = 3_000,\n): Promise<Data> {\n return retryWhenFailed<Data>(\n async () => {\n const response = await fetchWithRetry(input, init);\n const json: { errors?: { message: string }[]; data: Data } = await response.json();\n if (json.errors) {\n throw new Error(`GraphQL errors in response: ${json.errors.map((error) => error.message).join(\", \")}`);\n }\n return json.data;\n },\n maxRetries,\n initialSleepTime,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaA,eAAsB,gBACpB,IACA,aAAa,GACb,mBAAmB,KACnB,aACY;AACZ,MAAI,UAAU;AAEd,SAAO,UAAU,YAAY;AAC3B,QAAI;AACF,aAAO,MAAM,GAAG;AAAA,IAClB,SAAS,GAAG;AACV,UAAI,OAAO,gBAAgB,YAAY;AACrC,cAAM,QAAQ;AACd,YAAI,YAAY,KAAK,GAAG;AACtB,gBAAM;AAAA,QACR;AAAA,MACF;AACA,iBAAW;AACX,UAAI,WAAW,YAAY;AACzB,cAAM;AAAA,MACR;AAEA,YAAM,SAAS,KAAK,OAAO;AAC3B,YAAM,QAAQ,KAAK,UAAU,mBAAmB;AAChD,YAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,KAAK,CAAC;AAAA,IAC3D;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,cAAc;AAChC;;;AC1BA,eAAsB,eACpB,OACA,MACA,aAAa,GACb,mBAAmB,KACA;AACnB,SAAO;AAAA,IACL,YAAY;AACV,YAAM,WAAW,MAAM,MAAM,OAAO,IAAI;AACxC,UAAI,SAAS,IAAI;AACf,eAAO;AAAA,MACT;AAEA,UAAI,SAAS,SAAS,OAAO,SAAS,WAAW,OAAO,SAAS,WAAW,OAAO,SAAS,WAAW,GAAG;AACxG,eAAO;AAAA,MACT;AACA,YAAM,IAAI,MAAM,uBAAuB,SAAS,MAAM,IAAI,SAAS,UAAU,EAAE;AAAA,IACjF;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;ACLA,eAAsB,sBACpB,OACA,MACA,aAAa,GACb,mBAAmB,KACJ;AACf,SAAO;AAAA,IACL,YAAY;AACV,YAAM,WAAW,MAAM,eAAe,OAAO,IAAI;AACjD,YAAM,OAAuD,MAAM,SAAS,KAAK;AACjF,UAAI,KAAK,QAAQ;AACf,cAAM,IAAI,MAAM,+BAA+B,KAAK,OAAO,IAAI,CAAC,UAAU,MAAM,OAAO,EAAE,KAAK,IAAI,CAAC,EAAE;AAAA,MACvG;AACA,aAAO,KAAK;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/http.ts","../src/retry.ts","../src/http/fetch-with-retry.ts","../src/http/graphql-fetch-with-retry.ts","../src/http/headers.ts"],"sourcesContent":["export { fetchWithRetry } from \"./http/fetch-with-retry.js\";\nexport { graphqlFetchWithRetry } from \"./http/graphql-fetch-with-retry.js\";\nexport { appendHeaders } from \"./http/headers.js\";\n","/**\n * Retry a function when it fails.\n * @param fn - The function to retry.\n * @param maxRetries - The maximum number of retries.\n * @param initialSleepTime - The initial time to sleep between exponential backoff retries.\n * @param stopOnError - The function to stop on error.\n * @returns The result of the function or undefined if it fails.\n * @example\n * import { retryWhenFailed } from \"@settlemint/sdk-utils\";\n * import { readFile } from \"node:fs/promises\";\n *\n * const result = await retryWhenFailed(() => readFile(\"/path/to/file.txt\"), 3, 1_000);\n */\nexport async function retryWhenFailed<T>(\n fn: () => Promise<T>,\n maxRetries = 5,\n initialSleepTime = 1_000,\n stopOnError?: (error: Error) => boolean,\n): Promise<T> {\n let attempt = 0;\n\n while (attempt < maxRetries) {\n try {\n return await fn();\n } catch (e) {\n if (typeof stopOnError === \"function\") {\n const error = e as Error;\n if (stopOnError(error)) {\n throw error;\n }\n }\n attempt += 1;\n if (attempt >= maxRetries) {\n throw e;\n }\n // Exponential backoff with full jitter to prevent thundering herd\n const jitter = Math.random();\n const delay = 2 ** attempt * initialSleepTime * jitter; // 0-1x of 1s, 2s, 4s base\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new Error(\"Retry failed\");\n}\n","import { retryWhenFailed } from \"../retry.js\";\n\n/**\n * Retry an HTTP request with exponential backoff and jitter.\n * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.\n *\n * @param input - The URL or Request object to fetch\n * @param init - The fetch init options\n * @param maxRetries - Maximum number of retry attempts\n * @param initialSleepTime - Initial sleep time between retries in ms\n * @returns The fetch Response\n * @throws Error if all retries fail\n * @example\n * import { fetchWithRetry } from \"@settlemint/sdk-utils/http\";\n *\n * const response = await fetchWithRetry(\"https://api.example.com/data\");\n */\nexport async function fetchWithRetry(\n input: RequestInfo | URL,\n init?: RequestInit,\n maxRetries = 5,\n initialSleepTime = 3_000,\n): Promise<Response> {\n return retryWhenFailed(\n async () => {\n const response = await fetch(input, init);\n if (response.ok) {\n return response;\n }\n // Only retry on 5xx server errors, 429 rate limit, timeout, and network errors\n if (response.status < 500 && response.status !== 429 && response.status !== 408 && response.status !== 0) {\n return response;\n }\n throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`);\n },\n maxRetries,\n initialSleepTime,\n );\n}\n","import { retryWhenFailed } from \"../retry.js\";\nimport { fetchWithRetry } from \"./fetch-with-retry.js\";\n\n/**\n * Executes a GraphQL request with automatic retries using exponential backoff and jitter.\n * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.\n * Will also retry if the GraphQL response contains errors.\n *\n * @param input - The URL or Request object for the GraphQL endpoint\n * @param init - Optional fetch configuration options\n * @param maxRetries - Maximum retry attempts before failing (default: 5)\n * @param initialSleepTime - Initial delay between retries in milliseconds (default: 3000)\n * @returns The parsed GraphQL response data\n * @throws Error if all retries fail or if GraphQL response contains errors\n * @example\n * import { graphqlFetchWithRetry } from \"@settlemint/sdk-utils/http\";\n *\n * const data = await graphqlFetchWithRetry<{ user: { id: string } }>(\n * \"https://api.example.com/graphql\",\n * {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({\n * query: `query GetUser($id: ID!) {\n * user(id: $id) {\n * id\n * }\n * }`,\n * variables: { id: \"123\" }\n * })\n * }\n * );\n */\nexport async function graphqlFetchWithRetry<Data>(\n input: RequestInfo | URL,\n init?: RequestInit,\n maxRetries = 5,\n initialSleepTime = 3_000,\n): Promise<Data> {\n return retryWhenFailed<Data>(\n async () => {\n const response = await fetchWithRetry(input, init);\n const json: { errors?: { message: string }[]; data: Data } = await response.json();\n if (json.errors) {\n throw new Error(`GraphQL errors in response: ${json.errors.map((error) => error.message).join(\", \")}`);\n }\n return json.data;\n },\n maxRetries,\n initialSleepTime,\n );\n}\n","type MaybeLazy<T> = T | (() => T);\n\nexport function appendHeaders(\n headers: MaybeLazy<HeadersInit> | undefined,\n additionalHeaders: Record<string, string | undefined>,\n) {\n const defaultHeaders = typeof headers === \"function\" ? headers() : headers;\n const filteredAdditionalHeaders = Object.entries(additionalHeaders).filter(([_, value]) => value !== undefined) as [\n string,\n string,\n ][];\n if (Array.isArray(defaultHeaders)) {\n return [...defaultHeaders, ...filteredAdditionalHeaders];\n }\n if (defaultHeaders instanceof Headers) {\n return new Headers([...defaultHeaders, ...filteredAdditionalH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F,UAAI,KAAK,QAAQ;AACf,cAAM,IAAI,MAAM,+BAA+B,KAAK,OAAO,IAAI,CAAC,UAAU,MAAM,OAAO,EAAE,KAAK,IAAI,CAAC,EAAE;AAAA,MACvG;AACA,aAAO,KAAK;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;ACjDO,SAAS,cACd,SACA,mBACA;AACA,QAAM,iBAAiB,OAAO,YAAY,aAAa,QAAQ,IAAI;AACnE,QAAM,4BAA4B,OAAO,QAAQ,iBAAiB,EAAE,OAAO,CAAC,CAAC,GAAG,KAAK,MAAM,UAAU,MAAS;AAI9G,MAAI,MAAM,QAAQ,cAAc,GAAG;AACjC,WAAO,CAAC,GAAG,gBAAgB,GAAG,yBAAyB;AAAA,EACzD;AACA,MAAI,0BAA0B,SAAS;AACrC,WAAO,IAAI,QAAQ,CAAC,GAAG,gBAAgB,GAAG,yBAAyB,CAAC;AAAA,EACtE;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAG,OAAO,YAAY,yBAAyB;AAAA,EACjD;AACF;","names":[]}
|
package/dist/http.d.cts
CHANGED
|
@@ -47,4 +47,9 @@ declare function fetchWithRetry(input: RequestInfo | URL, init?: RequestInit, ma
|
|
|
47
47
|
*/
|
|
48
48
|
declare function graphqlFetchWithRetry<Data>(input: RequestInfo | URL, init?: RequestInit, maxRetries?: number, initialSleepTime?: number): Promise<Data>;
|
|
49
49
|
|
|
50
|
-
|
|
50
|
+
type MaybeLazy<T> = T | (() => T);
|
|
51
|
+
declare function appendHeaders(headers: MaybeLazy<HeadersInit> | undefined, additionalHeaders: Record<string, string | undefined>): [string, string][] | Headers | {
|
|
52
|
+
[x: string]: string;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export { appendHeaders, fetchWithRetry, graphqlFetchWithRetry };
|
package/dist/http.d.ts
CHANGED
|
@@ -47,4 +47,9 @@ declare function fetchWithRetry(input: RequestInfo | URL, init?: RequestInit, ma
|
|
|
47
47
|
*/
|
|
48
48
|
declare function graphqlFetchWithRetry<Data>(input: RequestInfo | URL, init?: RequestInit, maxRetries?: number, initialSleepTime?: number): Promise<Data>;
|
|
49
49
|
|
|
50
|
-
|
|
50
|
+
type MaybeLazy<T> = T | (() => T);
|
|
51
|
+
declare function appendHeaders(headers: MaybeLazy<HeadersInit> | undefined, additionalHeaders: Record<string, string | undefined>): [string, string][] | Headers | {
|
|
52
|
+
[x: string]: string;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export { appendHeaders, fetchWithRetry, graphqlFetchWithRetry };
|
package/dist/http.mjs
CHANGED
|
@@ -56,7 +56,24 @@ async function graphqlFetchWithRetry(input, init, maxRetries = 5, initialSleepTi
|
|
|
56
56
|
initialSleepTime
|
|
57
57
|
);
|
|
58
58
|
}
|
|
59
|
+
|
|
60
|
+
// src/http/headers.ts
|
|
61
|
+
function appendHeaders(headers, additionalHeaders) {
|
|
62
|
+
const defaultHeaders = typeof headers === "function" ? headers() : headers;
|
|
63
|
+
const filteredAdditionalHeaders = Object.entries(additionalHeaders).filter(([_, value]) => value !== void 0);
|
|
64
|
+
if (Array.isArray(defaultHeaders)) {
|
|
65
|
+
return [...defaultHeaders, ...filteredAdditionalHeaders];
|
|
66
|
+
}
|
|
67
|
+
if (defaultHeaders instanceof Headers) {
|
|
68
|
+
return new Headers([...defaultHeaders, ...filteredAdditionalHeaders]);
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
...defaultHeaders,
|
|
72
|
+
...Object.fromEntries(filteredAdditionalHeaders)
|
|
73
|
+
};
|
|
74
|
+
}
|
|
59
75
|
export {
|
|
76
|
+
appendHeaders,
|
|
60
77
|
fetchWithRetry,
|
|
61
78
|
graphqlFetchWithRetry
|
|
62
79
|
};
|
package/dist/http.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/retry.ts","../src/http/fetch-with-retry.ts","../src/http/graphql-fetch-with-retry.ts"],"sourcesContent":["/**\n * Retry a function when it fails.\n * @param fn - The function to retry.\n * @param maxRetries - The maximum number of retries.\n * @param initialSleepTime - The initial time to sleep between exponential backoff retries.\n * @param stopOnError - The function to stop on error.\n * @returns The result of the function or undefined if it fails.\n * @example\n * import { retryWhenFailed } from \"@settlemint/sdk-utils\";\n * import { readFile } from \"node:fs/promises\";\n *\n * const result = await retryWhenFailed(() => readFile(\"/path/to/file.txt\"), 3, 1_000);\n */\nexport async function retryWhenFailed<T>(\n fn: () => Promise<T>,\n maxRetries = 5,\n initialSleepTime = 1_000,\n stopOnError?: (error: Error) => boolean,\n): Promise<T> {\n let attempt = 0;\n\n while (attempt < maxRetries) {\n try {\n return await fn();\n } catch (e) {\n if (typeof stopOnError === \"function\") {\n const error = e as Error;\n if (stopOnError(error)) {\n throw error;\n }\n }\n attempt += 1;\n if (attempt >= maxRetries) {\n throw e;\n }\n // Exponential backoff with full jitter to prevent thundering herd\n const jitter = Math.random();\n const delay = 2 ** attempt * initialSleepTime * jitter; // 0-1x of 1s, 2s, 4s base\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new Error(\"Retry failed\");\n}\n","import { retryWhenFailed } from \"../retry.js\";\n\n/**\n * Retry an HTTP request with exponential backoff and jitter.\n * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.\n *\n * @param input - The URL or Request object to fetch\n * @param init - The fetch init options\n * @param maxRetries - Maximum number of retry attempts\n * @param initialSleepTime - Initial sleep time between retries in ms\n * @returns The fetch Response\n * @throws Error if all retries fail\n * @example\n * import { fetchWithRetry } from \"@settlemint/sdk-utils/http\";\n *\n * const response = await fetchWithRetry(\"https://api.example.com/data\");\n */\nexport async function fetchWithRetry(\n input: RequestInfo | URL,\n init?: RequestInit,\n maxRetries = 5,\n initialSleepTime = 3_000,\n): Promise<Response> {\n return retryWhenFailed(\n async () => {\n const response = await fetch(input, init);\n if (response.ok) {\n return response;\n }\n // Only retry on 5xx server errors, 429 rate limit, timeout, and network errors\n if (response.status < 500 && response.status !== 429 && response.status !== 408 && response.status !== 0) {\n return response;\n }\n throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`);\n },\n maxRetries,\n initialSleepTime,\n );\n}\n","import { retryWhenFailed } from \"../retry.js\";\nimport { fetchWithRetry } from \"./fetch-with-retry.js\";\n\n/**\n * Executes a GraphQL request with automatic retries using exponential backoff and jitter.\n * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.\n * Will also retry if the GraphQL response contains errors.\n *\n * @param input - The URL or Request object for the GraphQL endpoint\n * @param init - Optional fetch configuration options\n * @param maxRetries - Maximum retry attempts before failing (default: 5)\n * @param initialSleepTime - Initial delay between retries in milliseconds (default: 3000)\n * @returns The parsed GraphQL response data\n * @throws Error if all retries fail or if GraphQL response contains errors\n * @example\n * import { graphqlFetchWithRetry } from \"@settlemint/sdk-utils/http\";\n *\n * const data = await graphqlFetchWithRetry<{ user: { id: string } }>(\n * \"https://api.example.com/graphql\",\n * {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({\n * query: `query GetUser($id: ID!) {\n * user(id: $id) {\n * id\n * }\n * }`,\n * variables: { id: \"123\" }\n * })\n * }\n * );\n */\nexport async function graphqlFetchWithRetry<Data>(\n input: RequestInfo | URL,\n init?: RequestInit,\n maxRetries = 5,\n initialSleepTime = 3_000,\n): Promise<Data> {\n return retryWhenFailed<Data>(\n async () => {\n const response = await fetchWithRetry(input, init);\n const json: { errors?: { message: string }[]; data: Data } = await response.json();\n if (json.errors) {\n throw new Error(`GraphQL errors in response: ${json.errors.map((error) => error.message).join(\", \")}`);\n }\n return json.data;\n },\n maxRetries,\n initialSleepTime,\n );\n}\n"],"mappings":";AAaA,eAAsB,gBACpB,IACA,aAAa,GACb,mBAAmB,KACnB,aACY;AACZ,MAAI,UAAU;AAEd,SAAO,UAAU,YAAY;AAC3B,QAAI;AACF,aAAO,MAAM,GAAG;AAAA,IAClB,SAAS,GAAG;AACV,UAAI,OAAO,gBAAgB,YAAY;AACrC,cAAM,QAAQ;AACd,YAAI,YAAY,KAAK,GAAG;AACtB,gBAAM;AAAA,QACR;AAAA,MACF;AACA,iBAAW;AACX,UAAI,WAAW,YAAY;AACzB,cAAM;AAAA,MACR;AAEA,YAAM,SAAS,KAAK,OAAO;AAC3B,YAAM,QAAQ,KAAK,UAAU,mBAAmB;AAChD,YAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,KAAK,CAAC;AAAA,IAC3D;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,cAAc;AAChC;;;AC1BA,eAAsB,eACpB,OACA,MACA,aAAa,GACb,mBAAmB,KACA;AACnB,SAAO;AAAA,IACL,YAAY;AACV,YAAM,WAAW,MAAM,MAAM,OAAO,IAAI;AACxC,UAAI,SAAS,IAAI;AACf,eAAO;AAAA,MACT;AAEA,UAAI,SAAS,SAAS,OAAO,SAAS,WAAW,OAAO,SAAS,WAAW,OAAO,SAAS,WAAW,GAAG;AACxG,eAAO;AAAA,MACT;AACA,YAAM,IAAI,MAAM,uBAAuB,SAAS,MAAM,IAAI,SAAS,UAAU,EAAE;AAAA,IACjF;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;ACLA,eAAsB,sBACpB,OACA,MACA,aAAa,GACb,mBAAmB,KACJ;AACf,SAAO;AAAA,IACL,YAAY;AACV,YAAM,WAAW,MAAM,eAAe,OAAO,IAAI;AACjD,YAAM,OAAuD,MAAM,SAAS,KAAK;AACjF,UAAI,KAAK,QAAQ;AACf,cAAM,IAAI,MAAM,+BAA+B,KAAK,OAAO,IAAI,CAAC,UAAU,MAAM,OAAO,EAAE,KAAK,IAAI,CAAC,EAAE;AAAA,MACvG;AACA,aAAO,KAAK;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/retry.ts","../src/http/fetch-with-retry.ts","../src/http/graphql-fetch-with-retry.ts","../src/http/headers.ts"],"sourcesContent":["/**\n * Retry a function when it fails.\n * @param fn - The function to retry.\n * @param maxRetries - The maximum number of retries.\n * @param initialSleepTime - The initial time to sleep between exponential backoff retries.\n * @param stopOnError - The function to stop on error.\n * @returns The result of the function or undefined if it fails.\n * @example\n * import { retryWhenFailed } from \"@settlemint/sdk-utils\";\n * import { readFile } from \"node:fs/promises\";\n *\n * const result = await retryWhenFailed(() => readFile(\"/path/to/file.txt\"), 3, 1_000);\n */\nexport async function retryWhenFailed<T>(\n fn: () => Promise<T>,\n maxRetries = 5,\n initialSleepTime = 1_000,\n stopOnError?: (error: Error) => boolean,\n): Promise<T> {\n let attempt = 0;\n\n while (attempt < maxRetries) {\n try {\n return await fn();\n } catch (e) {\n if (typeof stopOnError === \"function\") {\n const error = e as Error;\n if (stopOnError(error)) {\n throw error;\n }\n }\n attempt += 1;\n if (attempt >= maxRetries) {\n throw e;\n }\n // Exponential backoff with full jitter to prevent thundering herd\n const jitter = Math.random();\n const delay = 2 ** attempt * initialSleepTime * jitter; // 0-1x of 1s, 2s, 4s base\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new Error(\"Retry failed\");\n}\n","import { retryWhenFailed } from \"../retry.js\";\n\n/**\n * Retry an HTTP request with exponential backoff and jitter.\n * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.\n *\n * @param input - The URL or Request object to fetch\n * @param init - The fetch init options\n * @param maxRetries - Maximum number of retry attempts\n * @param initialSleepTime - Initial sleep time between retries in ms\n * @returns The fetch Response\n * @throws Error if all retries fail\n * @example\n * import { fetchWithRetry } from \"@settlemint/sdk-utils/http\";\n *\n * const response = await fetchWithRetry(\"https://api.example.com/data\");\n */\nexport async function fetchWithRetry(\n input: RequestInfo | URL,\n init?: RequestInit,\n maxRetries = 5,\n initialSleepTime = 3_000,\n): Promise<Response> {\n return retryWhenFailed(\n async () => {\n const response = await fetch(input, init);\n if (response.ok) {\n return response;\n }\n // Only retry on 5xx server errors, 429 rate limit, timeout, and network errors\n if (response.status < 500 && response.status !== 429 && response.status !== 408 && response.status !== 0) {\n return response;\n }\n throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`);\n },\n maxRetries,\n initialSleepTime,\n );\n}\n","import { retryWhenFailed } from \"../retry.js\";\nimport { fetchWithRetry } from \"./fetch-with-retry.js\";\n\n/**\n * Executes a GraphQL request with automatic retries using exponential backoff and jitter.\n * Only retries on server errors (5xx), rate limits (429), timeouts (408), and network errors.\n * Will also retry if the GraphQL response contains errors.\n *\n * @param input - The URL or Request object for the GraphQL endpoint\n * @param init - Optional fetch configuration options\n * @param maxRetries - Maximum retry attempts before failing (default: 5)\n * @param initialSleepTime - Initial delay between retries in milliseconds (default: 3000)\n * @returns The parsed GraphQL response data\n * @throws Error if all retries fail or if GraphQL response contains errors\n * @example\n * import { graphqlFetchWithRetry } from \"@settlemint/sdk-utils/http\";\n *\n * const data = await graphqlFetchWithRetry<{ user: { id: string } }>(\n * \"https://api.example.com/graphql\",\n * {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify({\n * query: `query GetUser($id: ID!) {\n * user(id: $id) {\n * id\n * }\n * }`,\n * variables: { id: \"123\" }\n * })\n * }\n * );\n */\nexport async function graphqlFetchWithRetry<Data>(\n input: RequestInfo | URL,\n init?: RequestInit,\n maxRetries = 5,\n initialSleepTime = 3_000,\n): Promise<Data> {\n return retryWhenFailed<Data>(\n async () => {\n const response = await fetchWithRetry(input, init);\n const json: { errors?: { message: string }[]; data: Data } = await response.json();\n if (json.errors) {\n throw new Error(`GraphQL errors in response: ${json.errors.map((error) => error.message).join(\", \")}`);\n }\n return json.data;\n },\n maxRetries,\n initialSleepTime,\n );\n}\n","type MaybeLazy<T> = T | (() => T);\n\nexport function appendHeaders(\n headers: MaybeLazy<HeadersInit> | undefined,\n additionalHeaders: Record<string, string | undefined>,\n) {\n const defaultHeaders = typeof headers === \"function\" ? headers() : headers;\n const filteredAdditionalHeaders = Object.entries(additionalHeaders).filter(([_, value]) => value !== undefined) as [\n string,\n string,\n ][];\n if (Array.isArray(defaultHeaders)) {\n return [...defaultHeaders, ...filteredAdditionalHeaders];\n }\n if (defaultHeaders instanceof Headers) {\n return new Headers([...defaultHeaders, ...filteredAdditionalHeaders]);\n }\n return {\n ...defaultHeaders,\n ...Object.fromEntries(filteredAdditionalHeaders),\n };\n}\n"],"mappings":";AAaA,eAAsB,gBACpB,IACA,aAAa,GACb,mBAAmB,KACnB,aACY;AACZ,MAAI,UAAU;AAEd,SAAO,UAAU,YAAY;AAC3B,QAAI;AACF,aAAO,MAAM,GAAG;AAAA,IAClB,SAAS,GAAG;AACV,UAAI,OAAO,gBAAgB,YAAY;AACrC,cAAM,QAAQ;AACd,YAAI,YAAY,KAAK,GAAG;AACtB,gBAAM;AAAA,QACR;AAAA,MACF;AACA,iBAAW;AACX,UAAI,WAAW,YAAY;AACzB,cAAM;AAAA,MACR;AAEA,YAAM,SAAS,KAAK,OAAO;AAC3B,YAAM,QAAQ,KAAK,UAAU,mBAAmB;AAChD,YAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,KAAK,CAAC;AAAA,IAC3D;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,cAAc;AAChC;;;AC1BA,eAAsB,eACpB,OACA,MACA,aAAa,GACb,mBAAmB,KACA;AACnB,SAAO;AAAA,IACL,YAAY;AACV,YAAM,WAAW,MAAM,MAAM,OAAO,IAAI;AACxC,UAAI,SAAS,IAAI;AACf,eAAO;AAAA,MACT;AAEA,UAAI,SAAS,SAAS,OAAO,SAAS,WAAW,OAAO,SAAS,WAAW,OAAO,SAAS,WAAW,GAAG;AACxG,eAAO;AAAA,MACT;AACA,YAAM,IAAI,MAAM,uBAAuB,SAAS,MAAM,IAAI,SAAS,UAAU,EAAE;AAAA,IACjF;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;ACLA,eAAsB,sBACpB,OACA,MACA,aAAa,GACb,mBAAmB,KACJ;AACf,SAAO;AAAA,IACL,YAAY;AACV,YAAM,WAAW,MAAM,eAAe,OAAO,IAAI;AACjD,YAAM,OAAuD,MAAM,SAAS,KAAK;AACjF,UAAI,KAAK,QAAQ;AACf,cAAM,IAAI,MAAM,+BAA+B,KAAK,OAAO,IAAI,CAAC,UAAU,MAAM,OAAO,EAAE,KAAK,IAAI,CAAC,EAAE;AAAA,MACvG;AACA,aAAO,KAAK;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;ACjDO,SAAS,cACd,SACA,mBACA;AACA,QAAM,iBAAiB,OAAO,YAAY,aAAa,QAAQ,IAAI;AACnE,QAAM,4BAA4B,OAAO,QAAQ,iBAAiB,EAAE,OAAO,CAAC,CAAC,GAAG,KAAK,MAAM,UAAU,MAAS;AAI9G,MAAI,MAAM,QAAQ,cAAc,GAAG;AACjC,WAAO,CAAC,GAAG,gBAAgB,GAAG,yBAAyB;AAAA,EACzD;AACA,MAAI,0BAA0B,SAAS;AACrC,WAAO,IAAI,QAAQ,CAAC,GAAG,gBAAgB,GAAG,yBAAyB,CAAC;AAAA,EACtE;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAG,OAAO,YAAY,yBAAyB;AAAA,EACjD;AACF;","names":[]}
|
package/dist/index.cjs
CHANGED
|
@@ -22,6 +22,7 @@ var index_exports = {};
|
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
camelCaseToWords: () => camelCaseToWords,
|
|
24
24
|
capitalizeFirstLetter: () => capitalizeFirstLetter,
|
|
25
|
+
extractBaseUrlBeforeSegment: () => extractBaseUrlBeforeSegment,
|
|
25
26
|
extractJsonObject: () => extractJsonObject,
|
|
26
27
|
makeJsonStringifiable: () => makeJsonStringifiable,
|
|
27
28
|
replaceUnderscoresAndHyphensWithSpaces: () => replaceUnderscoresAndHyphensWithSpaces,
|
|
@@ -110,10 +111,18 @@ function truncate(value, maxLength) {
|
|
|
110
111
|
}
|
|
111
112
|
return `${value.slice(0, maxLength)}...`;
|
|
112
113
|
}
|
|
114
|
+
|
|
115
|
+
// src/url.ts
|
|
116
|
+
function extractBaseUrlBeforeSegment(baseUrl, pathSegment) {
|
|
117
|
+
const url = new URL(baseUrl);
|
|
118
|
+
const segmentIndex = url.pathname.indexOf(pathSegment);
|
|
119
|
+
return url.origin + (segmentIndex >= 0 ? url.pathname.substring(0, segmentIndex) : url.pathname);
|
|
120
|
+
}
|
|
113
121
|
// Annotate the CommonJS export names for ESM import in node:
|
|
114
122
|
0 && (module.exports = {
|
|
115
123
|
camelCaseToWords,
|
|
116
124
|
capitalizeFirstLetter,
|
|
125
|
+
extractBaseUrlBeforeSegment,
|
|
117
126
|
extractJsonObject,
|
|
118
127
|
makeJsonStringifiable,
|
|
119
128
|
replaceUnderscoresAndHyphensWithSpaces,
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/json.ts","../src/retry.ts","../src/string.ts"],"sourcesContent":["export * from \"./json.js\";\nexport * from \"./retry.js\";\nexport * from \"./string.js\";\n","/**\n * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.\n *\n * @param value - The JSON string to parse\n * @param defaultValue - The value to return if parsing fails or results in null/undefined\n * @returns The parsed JSON value as type T, or the default value if parsing fails\n *\n * @example\n * import { tryParseJson } from \"@settlemint/sdk-utils\";\n *\n * const config = tryParseJson<{ port: number }>(\n * '{\"port\": 3000}',\n * { port: 8080 }\n * );\n * // Returns: { port: 3000 }\n *\n * const invalid = tryParseJson<string[]>(\n * 'invalid json',\n * []\n * );\n * // Returns: []\n */\nexport function tryParseJson<T>(value: string, defaultValue: T | null = null): T | null {\n try {\n const parsed = JSON.parse(value) as T;\n if (parsed === undefined || parsed === null) {\n return defaultValue;\n }\n return parsed;\n } catch (err) {\n // Invalid json\n return defaultValue;\n }\n}\n\n/**\n * Extracts a JSON object from a string.\n *\n * @param value - The string to extract the JSON object from\n * @returns The parsed JSON object, or null if no JSON object is found\n * @throws {Error} If the input string is too long (longer than 5000 characters)\n * @example\n * import { extractJsonObject } from \"@settlemint/sdk-utils\";\n *\n * const json = extractJsonObject<{ port: number }>(\n * 'port info: {\"port\": 3000}',\n * );\n * // Returns: { port: 3000 }\n */\nexport function extractJsonObject<T>(value: string): T | null {\n if (value.length > 5000) {\n throw new Error(\"Input too long\");\n }\n const result = /\\{([\\s\\S]*)\\}/.exec(value);\n if (!result) {\n return null;\n }\n return tryParseJson<T>(result[0]);\n}\n\n/**\n * Converts a value to a JSON stringifiable format.\n *\n * @param value - The value to convert\n * @returns The JSON stringifiable value\n *\n * @example\n * import { makeJsonStringifiable } from \"@settlemint/sdk-utils\";\n *\n * const json = makeJsonStringifiable<{ amount: bigint }>({ amount: BigInt(1000) });\n * // Returns: '{\"amount\":\"1000\"}'\n */\nexport function makeJsonStringifiable<T>(value: unknown): T {\n if (value === undefined || value === null) {\n return value as T;\n }\n return tryParseJson<T>(\n JSON.stringify(\n value,\n (_, value) => (typeof value === \"bigint\" ? value.toString() : value), // return everything else unchanged\n ),\n ) as T;\n}\n","/**\n * Retry a function when it fails.\n * @param fn - The function to retry.\n * @param maxRetries - The maximum number of retries.\n * @param initialSleepTime - The initial time to sleep between exponential backoff retries.\n * @param stopOnError - The function to stop on error.\n * @returns The result of the function or undefined if it fails.\n * @example\n * import { retryWhenFailed } from \"@settlemint/sdk-utils\";\n * import { readFile } from \"node:fs/promises\";\n *\n * const result = await retryWhenFailed(() => readFile(\"/path/to/file.txt\"), 3, 1_000);\n */\nexport async function retryWhenFailed<T>(\n fn: () => Promise<T>,\n maxRetries = 5,\n initialSleepTime = 1_000,\n stopOnError?: (error: Error) => boolean,\n): Promise<T> {\n let attempt = 0;\n\n while (attempt < maxRetries) {\n try {\n return await fn();\n } catch (e) {\n if (typeof stopOnError === \"function\") {\n const error = e as Error;\n if (stopOnError(error)) {\n throw error;\n }\n }\n attempt += 1;\n if (attempt >= maxRetries) {\n throw e;\n }\n // Exponential backoff with full jitter to prevent thundering herd\n const jitter = Math.random();\n const delay = 2 ** attempt * initialSleepTime * jitter; // 0-1x of 1s, 2s, 4s base\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new Error(\"Retry failed\");\n}\n","/**\n * Capitalizes the first letter of a string.\n *\n * @param val - The string to capitalize\n * @returns The input string with its first letter capitalized\n *\n * @example\n * import { capitalizeFirstLetter } from \"@settlemint/sdk-utils\";\n *\n * const capitalized = capitalizeFirstLetter(\"hello\");\n * // Returns: \"Hello\"\n */\nexport function capitalizeFirstLetter(val: string) {\n return String(val).charAt(0).toUpperCase() + String(val).slice(1);\n}\n\n/**\n * Converts a camelCase string to a human-readable string.\n *\n * @param s - The camelCase string to convert\n * @returns The human-readable string\n *\n * @example\n * import { camelCaseToWords } from \"@settlemint/sdk-utils\";\n *\n * const words = camelCaseToWords(\"camelCaseString\");\n * // Returns: \"Camel Case String\"\n */\nexport function camelCaseToWords(s: string) {\n const result = s.replace(/([a-z])([A-Z])/g, \"$1 $2\");\n const withSpaces = result.replace(/([A-Z])([a-z])/g, \" $1$2\");\n const capitalized = capitalizeFirstLetter(withSpaces);\n return capitalized.replace(/\\s+/g, \" \").trim();\n}\n\n/**\n * Replaces underscores and hyphens with spaces.\n *\n * @param s - The string to replace underscores and hyphens with spaces\n * @returns The input string with underscores and hyphens replaced with spaces\n *\n * @example\n * import { replaceUnderscoresAndHyphensWithSpaces } from \"@settlemint/sdk-utils\";\n *\n * const result = replaceUnderscoresAndHyphensWithSpaces(\"Already_Spaced-Second\");\n * // Returns: \"Already Spaced Second\"\n */\nexport function replaceUnderscoresAndHyphensWithSpaces(s: string) {\n return s.replace(/[-_]/g, \" \");\n}\n\n/**\n * Truncates a string to a maximum length and appends \"...\" if it is longer.\n *\n * @param value - The string to truncate\n * @param maxLength - The maximum length of the string\n * @returns The truncated string or the original string if it is shorter than the maximum length\n *\n * @example\n * import { truncate } from \"@settlemint/sdk-utils\";\n *\n * const truncated = truncate(\"Hello, world!\", 10);\n * // Returns: \"Hello, wor...\"\n */\nexport function truncate(value: string, maxLength: number) {\n if (value.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mB;AAChD,YAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,KAAK,CAAC;AAAA,IAC3D;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,cAAc;AAChC;;;AC/BO,SAAS,sBAAsB,KAAa;AACjD,SAAO,OAAO,GAAG,EAAE,OAAO,CAAC,EAAE,YAAY,IAAI,OAAO,GAAG,EAAE,MAAM,CAAC;AAClE;AAcO,SAAS,iBAAiB,GAAW;AAC1C,QAAM,SAAS,EAAE,QAAQ,mBAAmB,OAAO;AACnD,QAAM,aAAa,OAAO,QAAQ,mBAAmB,OAAO;AAC5D,QAAM,cAAc,sBAAsB,UAAU;AACpD,SAAO,YAAY,QAAQ,QAAQ,GAAG,EAAE,KAAK;AAC/C;AAcO,SAAS,uCAAuC,GAAW;AAChE,SAAO,EAAE,QAAQ,SAAS,GAAG;AAC/B;AAeO,SAAS,SAAS,OAAe,WAAmB;AACzD,MAAI,MAAM,UAAU,WAAW;AAC7B,WAAO;AAAA,EACT;AACA,SAAO,GAAG,MAAM,MAAM,GAAG,SAAS,CAAC;AACrC;","names":["value"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/json.ts","../src/retry.ts","../src/string.ts","../src/url.ts"],"sourcesContent":["export * from \"./json.js\";\nexport * from \"./retry.js\";\nexport * from \"./string.js\";\nexport * from \"./url.js\";\n","/**\n * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.\n *\n * @param value - The JSON string to parse\n * @param defaultValue - The value to return if parsing fails or results in null/undefined\n * @returns The parsed JSON value as type T, or the default value if parsing fails\n *\n * @example\n * import { tryParseJson } from \"@settlemint/sdk-utils\";\n *\n * const config = tryParseJson<{ port: number }>(\n * '{\"port\": 3000}',\n * { port: 8080 }\n * );\n * // Returns: { port: 3000 }\n *\n * const invalid = tryParseJson<string[]>(\n * 'invalid json',\n * []\n * );\n * // Returns: []\n */\nexport function tryParseJson<T>(value: string, defaultValue: T | null = null): T | null {\n try {\n const parsed = JSON.parse(value) as T;\n if (parsed === undefined || parsed === null) {\n return defaultValue;\n }\n return parsed;\n } catch (err) {\n // Invalid json\n return defaultValue;\n }\n}\n\n/**\n * Extracts a JSON object from a string.\n *\n * @param value - The string to extract the JSON object from\n * @returns The parsed JSON object, or null if no JSON object is found\n * @throws {Error} If the input string is too long (longer than 5000 characters)\n * @example\n * import { extractJsonObject } from \"@settlemint/sdk-utils\";\n *\n * const json = extractJsonObject<{ port: number }>(\n * 'port info: {\"port\": 3000}',\n * );\n * // Returns: { port: 3000 }\n */\nexport function extractJsonObject<T>(value: string): T | null {\n if (value.length > 5000) {\n throw new Error(\"Input too long\");\n }\n const result = /\\{([\\s\\S]*)\\}/.exec(value);\n if (!result) {\n return null;\n }\n return tryParseJson<T>(result[0]);\n}\n\n/**\n * Converts a value to a JSON stringifiable format.\n *\n * @param value - The value to convert\n * @returns The JSON stringifiable value\n *\n * @example\n * import { makeJsonStringifiable } from \"@settlemint/sdk-utils\";\n *\n * const json = makeJsonStringifiable<{ amount: bigint }>({ amount: BigInt(1000) });\n * // Returns: '{\"amount\":\"1000\"}'\n */\nexport function makeJsonStringifiable<T>(value: unknown): T {\n if (value === undefined || value === null) {\n return value as T;\n }\n return tryParseJson<T>(\n JSON.stringify(\n value,\n (_, value) => (typeof value === \"bigint\" ? value.toString() : value), // return everything else unchanged\n ),\n ) as T;\n}\n","/**\n * Retry a function when it fails.\n * @param fn - The function to retry.\n * @param maxRetries - The maximum number of retries.\n * @param initialSleepTime - The initial time to sleep between exponential backoff retries.\n * @param stopOnError - The function to stop on error.\n * @returns The result of the function or undefined if it fails.\n * @example\n * import { retryWhenFailed } from \"@settlemint/sdk-utils\";\n * import { readFile } from \"node:fs/promises\";\n *\n * const result = await retryWhenFailed(() => readFile(\"/path/to/file.txt\"), 3, 1_000);\n */\nexport async function retryWhenFailed<T>(\n fn: () => Promise<T>,\n maxRetries = 5,\n initialSleepTime = 1_000,\n stopOnError?: (error: Error) => boolean,\n): Promise<T> {\n let attempt = 0;\n\n while (attempt < maxRetries) {\n try {\n return await fn();\n } catch (e) {\n if (typeof stopOnError === \"function\") {\n const error = e as Error;\n if (stopOnError(error)) {\n throw error;\n }\n }\n attempt += 1;\n if (attempt >= maxRetries) {\n throw e;\n }\n // Exponential backoff with full jitter to prevent thundering herd\n const jitter = Math.random();\n const delay = 2 ** attempt * initialSleepTime * jitter; // 0-1x of 1s, 2s, 4s base\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new Error(\"Retry failed\");\n}\n","/**\n * Capitalizes the first letter of a string.\n *\n * @param val - The string to capitalize\n * @returns The input string with its first letter capitalized\n *\n * @example\n * import { capitalizeFirstLetter } from \"@settlemint/sdk-utils\";\n *\n * const capitalized = capitalizeFirstLetter(\"hello\");\n * // Returns: \"Hello\"\n */\nexport function capitalizeFirstLetter(val: string) {\n return String(val).charAt(0).toUpperCase() + String(val).slice(1);\n}\n\n/**\n * Converts a camelCase string to a human-readable string.\n *\n * @param s - The camelCase string to convert\n * @returns The human-readable string\n *\n * @example\n * import { camelCaseToWords } from \"@settlemint/sdk-utils\";\n *\n * const words = camelCaseToWords(\"camelCaseString\");\n * // Returns: \"Camel Case String\"\n */\nexport function camelCaseToWords(s: string) {\n const result = s.replace(/([a-z])([A-Z])/g, \"$1 $2\");\n const withSpaces = result.replace(/([A-Z])([a-z])/g, \" $1$2\");\n const capitalized = capitalizeFirstLetter(withSpaces);\n return capitalized.replace(/\\s+/g, \" \").trim();\n}\n\n/**\n * Replaces underscores and hyphens with spaces.\n *\n * @param s - The string to replace underscores and hyphens with spaces\n * @returns The input string with underscores and hyphens replaced with spaces\n *\n * @example\n * import { replaceUnderscoresAndHyphensWithSpaces } from \"@settlemint/sdk-utils\";\n *\n * const result = replaceUnderscoresAndHyphensWithSpaces(\"Already_Spaced-Second\");\n * // Returns: \"Already Spaced Second\"\n */\nexport function replaceUnderscoresAndHyphensWithSpaces(s: string) {\n return s.replace(/[-_]/g, \" \");\n}\n\n/**\n * Truncates a string to a maximum length and appends \"...\" if it is longer.\n *\n * @param value - The string to truncate\n * @param maxLength - The maximum length of the string\n * @returns The truncated string or the original string if it is shorter than the maximum length\n *\n * @example\n * import { truncate } from \"@settlemint/sdk-utils\";\n *\n * const truncated = truncate(\"Hello, world!\", 10);\n * // Returns: \"Hello, wor...\"\n */\nexport function truncate(value: string, maxLength: number) {\n if (value.length <= maxLength) {\n return value;\n }\n return `${value.slice(0, maxLength)}...`;\n}\n","/**\n * Extracts the base URL before a specific segment in a URL.\n *\n * @param baseUrl - The base URL to extract the path from\n * @param pathSegment - The path segment to start from\n * @returns The base URL before the specified segment\n * @example\n * ```typescript\n * import { extractBaseUrlBeforeSegment } from \"@settlemint/sdk-utils/url\";\n *\n * const baseUrl = extractBaseUrlBeforeSegment(\"https://example.com/api/v1/subgraphs/name/my-subgraph\", \"/subgraphs\");\n * // Returns: \"https://example.com/api/v1\"\n * ```\n */\nexport function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string) {\n const url = new URL(baseUrl);\n const segmentIndex = url.pathname.indexOf(pathSegment);\n return url.origin + (segmentIndex >= 0 ? url.pathname.substring(0, segmentIndex) : url.pathname);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsBO,SAAS,aAAgB,OAAe,eAAyB,MAAgB;AACtF,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,QAAI,WAAW,UAAa,WAAW,MAAM;AAC3C,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT,SAAS,KAAK;AAEZ,WAAO;AAAA,EACT;AACF;AAgBO,SAAS,kBAAqB,OAAyB;AAC5D,MAAI,MAAM,SAAS,KAAM;AACvB,UAAM,IAAI,MAAM,gBAAgB;AAAA,EAClC;AACA,QAAM,SAAS,gBAAgB,KAAK,KAAK;AACzC,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AACA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;AACzD,MAAI,MAAM,UAAU,WAAW;AAC7B,WAAO;AAAA,EACT;AACA,SAAO,GAAG,MAAM,MAAM,GAAG,SAAS,CAAC;AACrC;;;ACvDO,SAAS,4BAA4B,SAAiB,aAAqB;AAChF,QAAM,MAAM,IAAI,IAAI,OAAO;AAC3B,QAAM,eAAe,IAAI,SAAS,QAAQ,WAAW;AACrD,SAAO,IAAI,UAAU,gBAAgB,IAAI,IAAI,SAAS,UAAU,GAAG,YAAY,IAAI,IAAI;AACzF;","names":["value"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -119,4 +119,20 @@ declare function replaceUnderscoresAndHyphensWithSpaces(s: string): string;
|
|
|
119
119
|
*/
|
|
120
120
|
declare function truncate(value: string, maxLength: number): string;
|
|
121
121
|
|
|
122
|
-
|
|
122
|
+
/**
|
|
123
|
+
* Extracts the base URL before a specific segment in a URL.
|
|
124
|
+
*
|
|
125
|
+
* @param baseUrl - The base URL to extract the path from
|
|
126
|
+
* @param pathSegment - The path segment to start from
|
|
127
|
+
* @returns The base URL before the specified segment
|
|
128
|
+
* @example
|
|
129
|
+
* ```typescript
|
|
130
|
+
* import { extractBaseUrlBeforeSegment } from "@settlemint/sdk-utils/url";
|
|
131
|
+
*
|
|
132
|
+
* const baseUrl = extractBaseUrlBeforeSegment("https://example.com/api/v1/subgraphs/name/my-subgraph", "/subgraphs");
|
|
133
|
+
* // Returns: "https://example.com/api/v1"
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
declare function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string): string;
|
|
137
|
+
|
|
138
|
+
export { camelCaseToWords, capitalizeFirstLetter, extractBaseUrlBeforeSegment, extractJsonObject, makeJsonStringifiable, replaceUnderscoresAndHyphensWithSpaces, retryWhenFailed, truncate, tryParseJson };
|
package/dist/index.d.ts
CHANGED
|
@@ -119,4 +119,20 @@ declare function replaceUnderscoresAndHyphensWithSpaces(s: string): string;
|
|
|
119
119
|
*/
|
|
120
120
|
declare function truncate(value: string, maxLength: number): string;
|
|
121
121
|
|
|
122
|
-
|
|
122
|
+
/**
|
|
123
|
+
* Extracts the base URL before a specific segment in a URL.
|
|
124
|
+
*
|
|
125
|
+
* @param baseUrl - The base URL to extract the path from
|
|
126
|
+
* @param pathSegment - The path segment to start from
|
|
127
|
+
* @returns The base URL before the specified segment
|
|
128
|
+
* @example
|
|
129
|
+
* ```typescript
|
|
130
|
+
* import { extractBaseUrlBeforeSegment } from "@settlemint/sdk-utils/url";
|
|
131
|
+
*
|
|
132
|
+
* const baseUrl = extractBaseUrlBeforeSegment("https://example.com/api/v1/subgraphs/name/my-subgraph", "/subgraphs");
|
|
133
|
+
* // Returns: "https://example.com/api/v1"
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
declare function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string): string;
|
|
137
|
+
|
|
138
|
+
export { camelCaseToWords, capitalizeFirstLetter, extractBaseUrlBeforeSegment, extractJsonObject, makeJsonStringifiable, replaceUnderscoresAndHyphensWithSpaces, retryWhenFailed, truncate, tryParseJson };
|
package/dist/index.mjs
CHANGED
|
@@ -77,9 +77,17 @@ function truncate(value, maxLength) {
|
|
|
77
77
|
}
|
|
78
78
|
return `${value.slice(0, maxLength)}...`;
|
|
79
79
|
}
|
|
80
|
+
|
|
81
|
+
// src/url.ts
|
|
82
|
+
function extractBaseUrlBeforeSegment(baseUrl, pathSegment) {
|
|
83
|
+
const url = new URL(baseUrl);
|
|
84
|
+
const segmentIndex = url.pathname.indexOf(pathSegment);
|
|
85
|
+
return url.origin + (segmentIndex >= 0 ? url.pathname.substring(0, segmentIndex) : url.pathname);
|
|
86
|
+
}
|
|
80
87
|
export {
|
|
81
88
|
camelCaseToWords,
|
|
82
89
|
capitalizeFirstLetter,
|
|
90
|
+
extractBaseUrlBeforeSegment,
|
|
83
91
|
extractJsonObject,
|
|
84
92
|
makeJsonStringifiable,
|
|
85
93
|
replaceUnderscoresAndHyphensWithSpaces,
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/json.ts","../src/retry.ts","../src/string.ts"],"sourcesContent":["/**\n * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.\n *\n * @param value - The JSON string to parse\n * @param defaultValue - The value to return if parsing fails or results in null/undefined\n * @returns The parsed JSON value as type T, or the default value if parsing fails\n *\n * @example\n * import { tryParseJson } from \"@settlemint/sdk-utils\";\n *\n * const config = tryParseJson<{ port: number }>(\n * '{\"port\": 3000}',\n * { port: 8080 }\n * );\n * // Returns: { port: 3000 }\n *\n * const invalid = tryParseJson<string[]>(\n * 'invalid json',\n * []\n * );\n * // Returns: []\n */\nexport function tryParseJson<T>(value: string, defaultValue: T | null = null): T | null {\n try {\n const parsed = JSON.parse(value) as T;\n if (parsed === undefined || parsed === null) {\n return defaultValue;\n }\n return parsed;\n } catch (err) {\n // Invalid json\n return defaultValue;\n }\n}\n\n/**\n * Extracts a JSON object from a string.\n *\n * @param value - The string to extract the JSON object from\n * @returns The parsed JSON object, or null if no JSON object is found\n * @throws {Error} If the input string is too long (longer than 5000 characters)\n * @example\n * import { extractJsonObject } from \"@settlemint/sdk-utils\";\n *\n * const json = extractJsonObject<{ port: number }>(\n * 'port info: {\"port\": 3000}',\n * );\n * // Returns: { port: 3000 }\n */\nexport function extractJsonObject<T>(value: string): T | null {\n if (value.length > 5000) {\n throw new Error(\"Input too long\");\n }\n const result = /\\{([\\s\\S]*)\\}/.exec(value);\n if (!result) {\n return null;\n }\n return tryParseJson<T>(result[0]);\n}\n\n/**\n * Converts a value to a JSON stringifiable format.\n *\n * @param value - The value to convert\n * @returns The JSON stringifiable value\n *\n * @example\n * import { makeJsonStringifiable } from \"@settlemint/sdk-utils\";\n *\n * const json = makeJsonStringifiable<{ amount: bigint }>({ amount: BigInt(1000) });\n * // Returns: '{\"amount\":\"1000\"}'\n */\nexport function makeJsonStringifiable<T>(value: unknown): T {\n if (value === undefined || value === null) {\n return value as T;\n }\n return tryParseJson<T>(\n JSON.stringify(\n value,\n (_, value) => (typeof value === \"bigint\" ? value.toString() : value), // return everything else unchanged\n ),\n ) as T;\n}\n","/**\n * Retry a function when it fails.\n * @param fn - The function to retry.\n * @param maxRetries - The maximum number of retries.\n * @param initialSleepTime - The initial time to sleep between exponential backoff retries.\n * @param stopOnError - The function to stop on error.\n * @returns The result of the function or undefined if it fails.\n * @example\n * import { retryWhenFailed } from \"@settlemint/sdk-utils\";\n * import { readFile } from \"node:fs/promises\";\n *\n * const result = await retryWhenFailed(() => readFile(\"/path/to/file.txt\"), 3, 1_000);\n */\nexport async function retryWhenFailed<T>(\n fn: () => Promise<T>,\n maxRetries = 5,\n initialSleepTime = 1_000,\n stopOnError?: (error: Error) => boolean,\n): Promise<T> {\n let attempt = 0;\n\n while (attempt < maxRetries) {\n try {\n return await fn();\n } catch (e) {\n if (typeof stopOnError === \"function\") {\n const error = e as Error;\n if (stopOnError(error)) {\n throw error;\n }\n }\n attempt += 1;\n if (attempt >= maxRetries) {\n throw e;\n }\n // Exponential backoff with full jitter to prevent thundering herd\n const jitter = Math.random();\n const delay = 2 ** attempt * initialSleepTime * jitter; // 0-1x of 1s, 2s, 4s base\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new Error(\"Retry failed\");\n}\n","/**\n * Capitalizes the first letter of a string.\n *\n * @param val - The string to capitalize\n * @returns The input string with its first letter capitalized\n *\n * @example\n * import { capitalizeFirstLetter } from \"@settlemint/sdk-utils\";\n *\n * const capitalized = capitalizeFirstLetter(\"hello\");\n * // Returns: \"Hello\"\n */\nexport function capitalizeFirstLetter(val: string) {\n return String(val).charAt(0).toUpperCase() + String(val).slice(1);\n}\n\n/**\n * Converts a camelCase string to a human-readable string.\n *\n * @param s - The camelCase string to convert\n * @returns The human-readable string\n *\n * @example\n * import { camelCaseToWords } from \"@settlemint/sdk-utils\";\n *\n * const words = camelCaseToWords(\"camelCaseString\");\n * // Returns: \"Camel Case String\"\n */\nexport function camelCaseToWords(s: string) {\n const result = s.replace(/([a-z])([A-Z])/g, \"$1 $2\");\n const withSpaces = result.replace(/([A-Z])([a-z])/g, \" $1$2\");\n const capitalized = capitalizeFirstLetter(withSpaces);\n return capitalized.replace(/\\s+/g, \" \").trim();\n}\n\n/**\n * Replaces underscores and hyphens with spaces.\n *\n * @param s - The string to replace underscores and hyphens with spaces\n * @returns The input string with underscores and hyphens replaced with spaces\n *\n * @example\n * import { replaceUnderscoresAndHyphensWithSpaces } from \"@settlemint/sdk-utils\";\n *\n * const result = replaceUnderscoresAndHyphensWithSpaces(\"Already_Spaced-Second\");\n * // Returns: \"Already Spaced Second\"\n */\nexport function replaceUnderscoresAndHyphensWithSpaces(s: string) {\n return s.replace(/[-_]/g, \" \");\n}\n\n/**\n * Truncates a string to a maximum length and appends \"...\" if it is longer.\n *\n * @param value - The string to truncate\n * @param maxLength - The maximum length of the string\n * @returns The truncated string or the original string if it is shorter than the maximum length\n *\n * @example\n * import { truncate } from \"@settlemint/sdk-utils\";\n *\n * const truncated = truncate(\"Hello, world!\", 10);\n * // Returns: \"Hello, wor...\"\n */\nexport function truncate(value: string, maxLength: number) {\n if (value.length <= maxLength) {\n return value;\n }\n return `${value.slice(0, maxLength)}...`;\n}\n"],"mappings":";AAsBO,SAAS,aAAgB,OAAe,eAAyB,MAAgB;AACtF,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,QAAI,WAAW,UAAa,WAAW,MAAM;AAC3C,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT,SAAS,KAAK;AAEZ,WAAO;AAAA,EACT;AACF;AAgBO,SAAS,kBAAqB,OAAyB;AAC5D,MAAI,MAAM,SAAS,KAAM;AACvB,UAAM,IAAI,MAAM,gBAAgB;AAAA,EAClC;AACA,QAAM,SAAS,gBAAgB,KAAK,KAAK;AACzC,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,EACT;AACA,SAAO,aAAgB,OAAO,CAAC,CAAC;AAClC;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WAAO;AAAA,EACT;AACA,SAAO,GAAG,MAAM,MAAM,GAAG,SAAS,CAAC;AACrC;","names":["value"]}
|
|
1
|
+
{"version":3,"sources":["../src/json.ts","../src/retry.ts","../src/string.ts","../src/url.ts"],"sourcesContent":["/**\n * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.\n *\n * @param value - The JSON string to parse\n * @param defaultValue - The value to return if parsing fails or results in null/undefined\n * @returns The parsed JSON value as type T, or the default value if parsing fails\n *\n * @example\n * import { tryParseJson } from \"@settlemint/sdk-utils\";\n *\n * const config = tryParseJson<{ port: number }>(\n * '{\"port\": 3000}',\n * { port: 8080 }\n * );\n * // Returns: { port: 3000 }\n *\n * const invalid = tryParseJson<string[]>(\n * 'invalid json',\n * []\n * );\n * // Returns: []\n */\nexport function tryParseJson<T>(value: string, defaultValue: T | null = null): T | null {\n try {\n const parsed = JSON.parse(value) as T;\n if (parsed === undefined || parsed === null) {\n return defaultValue;\n }\n return parsed;\n } catch (err) {\n // Invalid json\n return defaultValue;\n }\n}\n\n/**\n * Extracts a JSON object from a string.\n *\n * @param value - The string to extract the JSON object from\n * @returns The parsed JSON object, or null if no JSON object is found\n * @throws {Error} If the input string is too long (longer than 5000 characters)\n * @example\n * import { extractJsonObject } from \"@settlemint/sdk-utils\";\n *\n * const json = extractJsonObject<{ port: number }>(\n * 'port info: {\"port\": 3000}',\n * );\n * // Returns: { port: 3000 }\n */\nexport function extractJsonObject<T>(value: string): T | null {\n if (value.length > 5000) {\n throw new Error(\"Input too long\");\n }\n const result = /\\{([\\s\\S]*)\\}/.exec(value);\n if (!result) {\n return null;\n }\n return tryParseJson<T>(result[0]);\n}\n\n/**\n * Converts a value to a JSON stringifiable format.\n *\n * @param value - The value to convert\n * @returns The JSON stringifiable value\n *\n * @example\n * import { makeJsonStringifiable } from \"@settlemint/sdk-utils\";\n *\n * const json = makeJsonStringifiable<{ amount: bigint }>({ amount: BigInt(1000) });\n * // Returns: '{\"amount\":\"1000\"}'\n */\nexport function makeJsonStringifiable<T>(value: unknown): T {\n if (value === undefined || value === null) {\n return value as T;\n }\n return tryParseJson<T>(\n JSON.stringify(\n value,\n (_, value) => (typeof value === \"bigint\" ? value.toString() : value), // return everything else unchanged\n ),\n ) as T;\n}\n","/**\n * Retry a function when it fails.\n * @param fn - The function to retry.\n * @param maxRetries - The maximum number of retries.\n * @param initialSleepTime - The initial time to sleep between exponential backoff retries.\n * @param stopOnError - The function to stop on error.\n * @returns The result of the function or undefined if it fails.\n * @example\n * import { retryWhenFailed } from \"@settlemint/sdk-utils\";\n * import { readFile } from \"node:fs/promises\";\n *\n * const result = await retryWhenFailed(() => readFile(\"/path/to/file.txt\"), 3, 1_000);\n */\nexport async function retryWhenFailed<T>(\n fn: () => Promise<T>,\n maxRetries = 5,\n initialSleepTime = 1_000,\n stopOnError?: (error: Error) => boolean,\n): Promise<T> {\n let attempt = 0;\n\n while (attempt < maxRetries) {\n try {\n return await fn();\n } catch (e) {\n if (typeof stopOnError === \"function\") {\n const error = e as Error;\n if (stopOnError(error)) {\n throw error;\n }\n }\n attempt += 1;\n if (attempt >= maxRetries) {\n throw e;\n }\n // Exponential backoff with full jitter to prevent thundering herd\n const jitter = Math.random();\n const delay = 2 ** attempt * initialSleepTime * jitter; // 0-1x of 1s, 2s, 4s base\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw new Error(\"Retry failed\");\n}\n","/**\n * Capitalizes the first letter of a string.\n *\n * @param val - The string to capitalize\n * @returns The input string with its first letter capitalized\n *\n * @example\n * import { capitalizeFirstLetter } from \"@settlemint/sdk-utils\";\n *\n * const capitalized = capitalizeFirstLetter(\"hello\");\n * // Returns: \"Hello\"\n */\nexport function capitalizeFirstLetter(val: string) {\n return String(val).charAt(0).toUpperCase() + String(val).slice(1);\n}\n\n/**\n * Converts a camelCase string to a human-readable string.\n *\n * @param s - The camelCase string to convert\n * @returns The human-readable string\n *\n * @example\n * import { camelCaseToWords } from \"@settlemint/sdk-utils\";\n *\n * const words = camelCaseToWords(\"camelCaseString\");\n * // Returns: \"Camel Case String\"\n */\nexport function camelCaseToWords(s: string) {\n const result = s.replace(/([a-z])([A-Z])/g, \"$1 $2\");\n const withSpaces = result.replace(/([A-Z])([a-z])/g, \" $1$2\");\n const capitalized = capitalizeFirstLetter(withSpaces);\n return capitalized.replace(/\\s+/g, \" \").trim();\n}\n\n/**\n * Replaces underscores and hyphens with spaces.\n *\n * @param s - The string to replace underscores and hyphens with spaces\n * @returns The input string with underscores and hyphens replaced with spaces\n *\n * @example\n * import { replaceUnderscoresAndHyphensWithSpaces } from \"@settlemint/sdk-utils\";\n *\n * const result = replaceUnderscoresAndHyphensWithSpaces(\"Already_Spaced-Second\");\n * // Returns: \"Already Spaced Second\"\n */\nexport function replaceUnderscoresAndHyphensWithSpaces(s: string) {\n return s.replace(/[-_]/g, \" \");\n}\n\n/**\n * Truncates a string to a maximum length and appends \"...\" if it is longer.\n *\n * @param value - The string to truncate\n * @param maxLength - The maximum length of the string\n * @returns The truncated string or the original string if it is shorter than the maximum length\n *\n * @example\n * import { truncate } from \"@settlemint/sdk-utils\";\n *\n * const truncated = truncate(\"Hello, world!\", 10);\n * // Returns: \"Hello, wor...\"\n */\nexport function truncate(value: string, maxLength: number) {\n if (value.length <= maxLength) {\n return value;\n }\n return `${value.slice(0, maxLength)}...`;\n}\n","/**\n * Extracts the base URL before a specific segment in a URL.\n *\n * @param baseUrl - The base URL to extract the path from\n * @param pathSegment - The path segment to start from\n * @returns The base URL before the specified segment\n * @example\n * ```typescript\n * import { extractBaseUrlBeforeSegment } from \"@settlemint/sdk-utils/url\";\n *\n * const baseUrl = extractBaseUrlBeforeSegment(\"https://example.com/api/v1/subgraphs/name/my-subgraph\", \"/subgraphs\");\n * // Returns: \"https://example.com/api/v1\"\n * ```\n */\nexport function extractBaseUrlBeforeSegment(baseUrl: string, pathSegment: string) {\n const url = new URL(baseUrl);\n const segmentIndex = url.pathname.indexOf(pathSegment);\n return url.origin + (segmentIndex >= 0 ? url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AAc;AAChC;;;AC/BO,SAAS,sBAAsB,KAAa;AACjD,SAAO,OAAO,GAAG,EAAE,OAAO,CAAC,EAAE,YAAY,IAAI,OAAO,GAAG,EAAE,MAAM,CAAC;AAClE;AAcO,SAAS,iBAAiB,GAAW;AAC1C,QAAM,SAAS,EAAE,QAAQ,mBAAmB,OAAO;AACnD,QAAM,aAAa,OAAO,QAAQ,mBAAmB,OAAO;AAC5D,QAAM,cAAc,sBAAsB,UAAU;AACpD,SAAO,YAAY,QAAQ,QAAQ,GAAG,EAAE,KAAK;AAC/C;AAcO,SAAS,uCAAuC,GAAW;AAChE,SAAO,EAAE,QAAQ,SAAS,GAAG;AAC/B;AAeO,SAAS,SAAS,OAAe,WAAmB;AACzD,MAAI,MAAM,UAAU,WAAW;AAC7B,WAAO;AAAA,EACT;AACA,SAAO,GAAG,MAAM,MAAM,GAAG,SAAS,CAAC;AACrC;;;ACvDO,SAAS,4BAA4B,SAAiB,aAAqB;AAChF,QAAM,MAAM,IAAI,IAAI,OAAO;AAC3B,QAAM,eAAe,IAAI,SAAS,QAAQ,WAAW;AACrD,SAAO,IAAI,UAAU,gBAAgB,IAAI,IAAI,SAAS,UAAU,GAAG,YAAY,IAAI,IAAI;AACzF;","names":["value"]}
|
package/dist/validation.cjs
CHANGED
|
@@ -26,6 +26,7 @@ __export(validation_exports, {
|
|
|
26
26
|
DotEnvSchemaPartial: () => DotEnvSchemaPartial,
|
|
27
27
|
IdSchema: () => IdSchema,
|
|
28
28
|
PersonalAccessTokenSchema: () => PersonalAccessTokenSchema,
|
|
29
|
+
STANDALONE_INSTANCE: () => STANDALONE_INSTANCE,
|
|
29
30
|
UniqueNameSchema: () => UniqueNameSchema,
|
|
30
31
|
UrlOrPathSchema: () => UrlOrPathSchema,
|
|
31
32
|
UrlPathSchema: () => UrlPathSchema,
|
|
@@ -84,9 +85,10 @@ var UrlPathSchema = import_v44.z.string().regex(/^\/(?:[a-zA-Z0-9-_]+(?:\/[a-zA-
|
|
|
84
85
|
var UrlOrPathSchema = import_v44.z.union([UrlSchema, UrlPathSchema]);
|
|
85
86
|
|
|
86
87
|
// src/validation/dot-env.schema.ts
|
|
88
|
+
var STANDALONE_INSTANCE = "standalone";
|
|
87
89
|
var DotEnvSchema = import_v45.z.object({
|
|
88
|
-
/** Base URL of the SettleMint platform instance */
|
|
89
|
-
SETTLEMINT_INSTANCE: UrlSchema.default("https://console.settlemint.com"),
|
|
90
|
+
/** Base URL of the SettleMint platform instance, set to standalone if your resources are not part of the SettleMint platform */
|
|
91
|
+
SETTLEMINT_INSTANCE: import_v45.z.union([UrlSchema, import_v45.z.literal(STANDALONE_INSTANCE)]).default("https://console.settlemint.com"),
|
|
90
92
|
/** Application access token for authenticating with SettleMint services */
|
|
91
93
|
SETTLEMINT_ACCESS_TOKEN: ApplicationAccessTokenSchema.optional(),
|
|
92
94
|
/** @internal */
|
|
@@ -187,6 +189,7 @@ var IdSchema = import_v46.z.union([
|
|
|
187
189
|
DotEnvSchemaPartial,
|
|
188
190
|
IdSchema,
|
|
189
191
|
PersonalAccessTokenSchema,
|
|
192
|
+
STANDALONE_INSTANCE,
|
|
190
193
|
UniqueNameSchema,
|
|
191
194
|
UrlOrPathSchema,
|
|
192
195
|
UrlPathSchema,
|
package/dist/validation.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/validation.ts","../src/validation/validate.ts","../src/validation/access-token.schema.ts","../src/json.ts","../src/validation/dot-env.schema.ts","../src/validation/unique-name.schema.ts","../src/validation/url.schema.ts","../src/validation/id.schema.ts"],"sourcesContent":["export { validate } from \"./validation/validate.js\";\nexport {\n ApplicationAccessTokenSchema,\n type ApplicationAccessToken,\n PersonalAccessTokenSchema,\n type PersonalAccessToken,\n AccessTokenSchema,\n type AccessToken,\n} from \"./validation/access-token.schema.js\";\nexport { DotEnvSchema, DotEnvSchemaPartial, type DotEnv, type DotEnvPartial } from \"./validation/dot-env.schema.js\";\nexport { IdSchema, type Id } from \"./validation/id.schema.js\";\nexport { UniqueNameSchema } from \"./validation/unique-name.schema.js\";\nexport {\n UrlOrPathSchema,\n UrlPathSchema,\n UrlSchema,\n type Url,\n type UrlOrPath,\n type UrlPath,\n} from \"./validation/url.schema.js\";\n","import { ZodError, type ZodType } from \"zod/v4\";\n\n/**\n * Validates a value against a given Zod schema.\n *\n * @param schema - The Zod schema to validate against.\n * @param value - The value to validate.\n * @returns The validated and parsed value.\n * @throws Will throw an error if validation fails, with formatted error messages.\n *\n * @example\n * import { validate } from \"@settlemint/sdk-utils/validation\";\n *\n * const validatedId = validate(IdSchema, \"550e8400-e29b-41d4-a716-446655440000\");\n */\nexport function validate<T extends ZodType>(schema: T, value: unknown): T[\"_output\"] {\n try {\n return schema.parse(value);\n } catch (error) {\n if (error instanceof ZodError) {\n const formattedErrors = error.issues.map((err) => `- ${err.path.join(\".\")}: ${err.message}`).join(\"\\n\");\n throw new Error(`Validation error${error.issues.length > 1 ? \"s\" : \"\"}:\\n${formattedErrors}`);\n }\n throw error; // Re-throw if it's not a ZodError\n }\n}\n","import { type ZodString, z } from \"zod/v4\";\n\n/**\n * Schema for validating application access tokens.\n * Application access tokens start with 'sm_aat_' prefix.\n */\nexport const ApplicationAccessTokenSchema: ZodString = z.string().regex(/^sm_aat_.*$/);\nexport type ApplicationAccessToken = z.infer<typeof ApplicationAccessTokenSchema>;\n\n/**\n * Schema for validating personal access tokens.\n * Personal access tokens start with 'sm_pat_' prefix.\n */\nexport const PersonalAccessTokenSchema: ZodString = z.string().regex(/^sm_pat_.*$/);\nexport type PersonalAccessToken = z.infer<typeof PersonalAccessTokenSchema>;\n\n/**\n * Schema for validating both application and personal access tokens.\n * Accepts tokens starting with either 'sm_pat_' or 'sm_aat_' prefix.\n */\nexport const AccessTokenSchema: ZodString = z.string().regex(/^sm_pat_.*|sm_aat_.*$/);\nexport type AccessToken = z.infer<typeof AccessTokenSchema>;\n","/**\n * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.\n *\n * @param value - The JSON string to parse\n * @param defaultValue - The value to return if parsing fails or results in null/undefined\n * @returns The parsed JSON value as type T, or the default value if parsing fails\n *\n * @example\n * import { tryParseJson } from \"@settlemint/sdk-utils\";\n *\n * const config = tryParseJson<{ port: number }>(\n * '{\"port\": 3000}',\n * { port: 8080 }\n * );\n * // Returns: { port: 3000 }\n *\n * const invalid = tryParseJson<string[]>(\n * 'invalid json',\n * []\n * );\n * // Returns: []\n */\nexport function tryParseJson<T>(value: string, defaultValue: T | null = null): T | null {\n try {\n const parsed = JSON.parse(value) as T;\n if (parsed === undefined || parsed === null) {\n return defaultValue;\n }\n return parsed;\n } catch (err) {\n // Invalid json\n return defaultValue;\n }\n}\n\n/**\n * Extracts a JSON object from a string.\n *\n * @param value - The string to extract the JSON object from\n * @returns The parsed JSON object, or null if no JSON object is found\n * @throws {Error} If the input string is too long (longer than 5000 characters)\n * @example\n * import { extractJsonObject } from \"@settlemint/sdk-utils\";\n *\n * const json = extractJsonObject<{ port: number }>(\n * 'port info: {\"port\": 3000}',\n * );\n * // Returns: { port: 3000 }\n */\nexport function extractJsonObject<T>(value: string): T | null {\n if (value.length > 5000) {\n throw new Error(\"Input too long\");\n }\n const result = /\\{([\\s\\S]*)\\}/.exec(value);\n if (!result) {\n return null;\n }\n return tryParseJson<T>(result[0]);\n}\n\n/**\n * Converts a value to a JSON stringifiable format.\n *\n * @param value - The value to convert\n * @returns The JSON stringifiable value\n *\n * @example\n * import { makeJsonStringifiable } from \"@settlemint/sdk-utils\";\n *\n * const json = makeJsonStringifiable<{ amount: bigint }>({ amount: BigInt(1000) });\n * // Returns: '{\"amount\":\"1000\"}'\n */\nexport function makeJsonStringifiable<T>(value: unknown): T {\n if (value === undefined || value === null) {\n return value as T;\n }\n return tryParseJson<T>(\n JSON.stringify(\n value,\n (_, value) => (typeof value === \"bigint\" ? value.toString() : value), // return everything else unchanged\n ),\n ) as T;\n}\n","import { tryParseJson } from \"@/json.js\";\nimport { z } from \"zod/v4\";\nimport { ApplicationAccessTokenSchema, PersonalAccessTokenSchema } from \"./access-token.schema.js\";\nimport { UniqueNameSchema } from \"./unique-name.schema.js\";\nimport { UrlSchema } from \"./url.schema.js\";\n\n/**\n * Schema for validating environment variables used by the SettleMint SDK.\n * Defines validation rules and types for configuration values like URLs,\n * access tokens, workspace names, and service endpoints.\n */\nexport const DotEnvSchema = z.object({\n /** Base URL of the SettleMint platform instance */\n SETTLEMINT_INSTANCE: UrlSchema.default(\"https://console.settlemint.com\"),\n /** Application access token for authenticating with SettleMint services */\n SETTLEMINT_ACCESS_TOKEN: ApplicationAccessTokenSchema.optional(),\n /** @internal */\n SETTLEMINT_PERSONAL_ACCESS_TOKEN: PersonalAccessTokenSchema.optional(),\n /** Unique name of the workspace */\n SETTLEMINT_WORKSPACE: UniqueNameSchema.optional(),\n /** Unique name of the application */\n SETTLEMINT_APPLICATION: UniqueNameSchema.optional(),\n /** Unique name of the blockchain network */\n SETTLEMINT_BLOCKCHAIN_NETWORK: UniqueNameSchema.optional(),\n /** Chain ID of the blockchain network */\n SETTLEMINT_BLOCKCHAIN_NETWORK_CHAIN_ID: z.string().optional(),\n /** Unique name of the blockchain node (should have a private key for signing transactions) */\n SETTLEMINT_BLOCKCHAIN_NODE: UniqueNameSchema.optional(),\n /** JSON RPC endpoint for the blockchain node */\n SETTLEMINT_BLOCKCHAIN_NODE_JSON_RPC_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the blockchain node or load balancer */\n SETTLEMINT_BLOCKCHAIN_NODE_OR_LOAD_BALANCER: UniqueNameSchema.optional(),\n /** JSON RPC endpoint for the blockchain node or load balancer */\n SETTLEMINT_BLOCKCHAIN_NODE_OR_LOAD_BALANCER_JSON_RPC_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the Hasura instance */\n SETTLEMINT_HASURA: UniqueNameSchema.optional(),\n /** Endpoint URL for the Hasura GraphQL API */\n SETTLEMINT_HASURA_ENDPOINT: UrlSchema.optional(),\n /** Admin secret for authenticating with Hasura */\n SETTLEMINT_HASURA_ADMIN_SECRET: z.string().optional(),\n /** Database connection URL for Hasura */\n SETTLEMINT_HASURA_DATABASE_URL: z.string().optional(),\n /** Unique name of The Graph instance */\n SETTLEMINT_THEGRAPH: UniqueNameSchema.optional(),\n /** Array of endpoint URLs for The Graph subgraphs */\n SETTLEMINT_THEGRAPH_SUBGRAPHS_ENDPOINTS: z.preprocess(\n (value) => tryParseJson(value as string, []),\n z.array(UrlSchema).optional(),\n ),\n /** Default The Graph subgraph to use */\n SETTLEMINT_THEGRAPH_DEFAULT_SUBGRAPH: z.string().optional(),\n /** Unique name of the Smart Contract Portal instance */\n SETTLEMINT_PORTAL: UniqueNameSchema.optional(),\n /** GraphQL endpoint URL for the Portal */\n SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT: UrlSchema.optional(),\n /** REST endpoint URL for the Portal */\n SETTLEMINT_PORTAL_REST_ENDPOINT: UrlSchema.optional(),\n /** WebSocket endpoint URL for the Portal */\n SETTLEMINT_PORTAL_WS_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the HD private key */\n SETTLEMINT_HD_PRIVATE_KEY: UniqueNameSchema.optional(),\n /** Address of the HD private key forwarder */\n SETTLEMINT_HD_PRIVATE_KEY_FORWARDER_ADDRESS: z.string().optional(),\n /** Unique name of the accessible private key */\n SETTLEMINT_ACCESSIBLE_PRIVATE_KEY: UniqueNameSchema.optional(),\n /** Unique name of the MinIO instance */\n SETTLEMINT_MINIO: UniqueNameSchema.optional(),\n /** Endpoint URL for MinIO */\n SETTLEMINT_MINIO_ENDPOINT: UrlSchema.optional(),\n /** Access key for MinIO authentication */\n SETTLEMINT_MINIO_ACCESS_KEY: z.string().optional(),\n /** Secret key for MinIO authentication */\n SETTLEMINT_MINIO_SECRET_KEY: z.string().optional(),\n /** Unique name of the IPFS instance */\n SETTLEMINT_IPFS: UniqueNameSchema.optional(),\n /** API endpoint URL for IPFS */\n SETTLEMINT_IPFS_API_ENDPOINT: UrlSchema.optional(),\n /** Pinning service endpoint URL for IPFS */\n SETTLEMINT_IPFS_PINNING_ENDPOINT: UrlSchema.optional(),\n /** Gateway endpoint URL for IPFS */\n SETTLEMINT_IPFS_GATEWAY_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the custom deployment */\n SETTLEMINT_CUSTOM_DEPLOYMENT: UniqueNameSchema.optional(),\n /** Endpoint URL for the custom deployment */\n SETTLEMINT_CUSTOM_DEPLOYMENT_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the Blockscout instance */\n SETTLEMINT_BLOCKSCOUT: UniqueNameSchema.optional(),\n /** GraphQL endpoint URL for Blockscout */\n SETTLEMINT_BLOCKSCOUT_GRAPHQL_ENDPOINT: UrlSchema.optional(),\n /** UI endpoint URL for Blockscout */\n SETTLEMINT_BLOCKSCOUT_UI_ENDPOINT: UrlSchema.optional(),\n /** Name of the new project being created */\n SETTLEMINT_NEW_PROJECT_NAME: z.string().optional(),\n /** The log level to use */\n SETTLEMINT_LOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\", \"none\"]).default(\"warn\"),\n});\n\n/**\n * Type definition for the environment variables schema.\n */\nexport type DotEnv = z.infer<typeof DotEnvSchema>;\n\n/**\n * Partial version of the environment variables schema where all fields are optional.\n * Useful for validating incomplete configurations during development or build time.\n */\nexport const DotEnvSchemaPartial = DotEnvSchema.partial();\n\n/**\n * Type definition for the partial environment variables schema.\n */\nexport type DotEnvPartial = z.infer<typeof DotEnvSchemaPartial>;\n","import { z } from \"zod/v4\";\n\n/**\n * Schema for validating unique names used across the SettleMint platform.\n * Only accepts lowercase alphanumeric characters and hyphens.\n * Used for workspace names, application names, service names etc.\n *\n * @example\n * import { UniqueNameSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate a workspace name\n * const isValidName = UniqueNameSchema.safeParse(\"my-workspace-123\").success;\n * // true\n *\n * // Invalid names will fail validation\n * const isInvalidName = UniqueNameSchema.safeParse(\"My Workspace!\").success;\n * // false\n */\nexport const UniqueNameSchema = z.string().regex(/^[a-z0-9-]+$/);\n\n/**\n * Type definition for unique names, inferred from UniqueNameSchema.\n */\nexport type UniqueName = z.infer<typeof UniqueNameSchema>;\n","import { z } from \"zod/v4\";\n\n/**\n * Schema for validating URLs.\n *\n * @example\n * import { UrlSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate a URL\n * const isValidUrl = UrlSchema.safeParse(\"https://console.settlemint.com\").success;\n * // true\n *\n * // Invalid URLs will fail validation\n * const isInvalidUrl = UrlSchema.safeParse(\"not-a-url\").success;\n * // false\n */\nexport const UrlSchema = z.string().url();\nexport type Url = z.infer<typeof UrlSchema>;\n\n/**\n * Schema for validating URL paths.\n *\n * @example\n * import { UrlPathSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate a URL path\n * const isValidPath = UrlPathSchema.safeParse(\"/api/v1/users\").success;\n * // true\n *\n * // Invalid paths will fail validation\n * const isInvalidPath = UrlPathSchema.safeParse(\"not-a-path\").success;\n * // false\n */\nexport const UrlPathSchema = z.string().regex(/^\\/(?:[a-zA-Z0-9-_]+(?:\\/[a-zA-Z0-9-_]+)*\\/?)?$/, {\n message: \"Invalid URL path format. Must start with '/' and can contain letters, numbers, hyphens, and underscores.\",\n});\n\nexport type UrlPath = z.infer<typeof UrlPathSchema>;\n\n/**\n * Schema that accepts either a full URL or a URL path.\n *\n * @example\n * import { UrlOrPathSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate a URL\n * const isValidUrl = UrlOrPathSchema.safeParse(\"https://console.settlemint.com\").success;\n * // true\n *\n * // Validate a path\n * const isValidPath = UrlOrPathSchema.safeParse(\"/api/v1/users\").success;\n * // true\n */\nexport const UrlOrPathSchema = z.union([UrlSchema, UrlPathSchema]);\nexport type UrlOrPath = z.infer<typeof UrlOrPathSchema>;\n","import { z } from \"zod/v4\";\n\n/**\n * Schema for validating database IDs. Accepts both PostgreSQL UUIDs and MongoDB ObjectIDs.\n * PostgreSQL UUIDs are 32 hexadecimal characters with hyphens (e.g. 123e4567-e89b-12d3-a456-426614174000).\n * MongoDB ObjectIDs are 24 hexadecimal characters (e.g. 507f1f77bcf86cd799439011).\n *\n * @example\n * import { IdSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate PostgreSQL UUID\n * const isValidUuid = IdSchema.safeParse(\"123e4567-e89b-12d3-a456-426614174000\").success;\n *\n * // Validate MongoDB ObjectID\n * const isValidObjectId = IdSchema.safeParse(\"507f1f77bcf86cd799439011\").success;\n */\nexport const IdSchema = z.union([\n z\n .string()\n .uuid(), // PostgreSQL UUID\n z\n .string()\n .regex(/^[0-9a-fA-F]{24}$/), // MongoDB ObjectID\n]);\n\n/**\n * Type definition for database IDs, inferred from IdSchema.\n * Can be either a PostgreSQL UUID string or MongoDB ObjectID string.\n */\nexport type Id = z.infer<typeof IdSchema>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,gBAAuC;AAehC,SAAS,SAA4B,QAAW,OAA8B;AACnF,MAAI;AACF,WAAO,OAAO,MAAM,KAAK;AAAA,EAC3B,SAAS,OAAO;AACd,QAAI,iBAAiB,oBAAU;AAC7B,YAAM,kBAAkB,MAAM,OAAO,IAAI,CAAC,QAAQ,KAAK,IAAI,KAAK,KAAK,GAAG,CAAC,KAAK,IAAI,OAAO,EAAE,EAAE,KAAK,IAAI;AACtG,YAAM,IAAI,MAAM,mBAAmB,MAAM,OAAO,SAAS,IAAI,MAAM,EAAE;AAAA,EAAM,eAAe,EAAE;AAAA,IAC9F;AACA,UAAM;AAAA,EACR;AACF;;;ACzBA,IAAAA,aAAkC;AAM3B,IAAM,+BAA0C,aAAE,OAAO,EAAE,MAAM,aAAa;AAO9E,IAAM,4BAAuC,aAAE,OAAO,EAAE,MAAM,aAAa;AAO3E,IAAM,oBAA+B,aAAE,OAAO,EAAE,MAAM,uBAAuB;;;ACE7E,SAAS,aAA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AAQ;;;AG1GxD,IAAAC,aAAkB;AAgBX,IAAM,WAAW,aAAE,MAAM;AAAA,EAC9B,aACG,OAAO,EACP,KAAK;AAAA;AAAA,EACR,aACG,OAAO,EACP,MAAM,mBAAmB;AAAA;AAC9B,CAAC;","names":["import_v4","import_v4","import_v4","import_v4","import_v4"]}
|
|
1
|
+
{"version":3,"sources":["../src/validation.ts","../src/validation/validate.ts","../src/validation/access-token.schema.ts","../src/json.ts","../src/validation/dot-env.schema.ts","../src/validation/unique-name.schema.ts","../src/validation/url.schema.ts","../src/validation/id.schema.ts"],"sourcesContent":["export { validate } from \"./validation/validate.js\";\nexport {\n ApplicationAccessTokenSchema,\n type ApplicationAccessToken,\n PersonalAccessTokenSchema,\n type PersonalAccessToken,\n AccessTokenSchema,\n type AccessToken,\n} from \"./validation/access-token.schema.js\";\nexport {\n DotEnvSchema,\n DotEnvSchemaPartial,\n type DotEnv,\n type DotEnvPartial,\n STANDALONE_INSTANCE,\n} from \"./validation/dot-env.schema.js\";\nexport { IdSchema, type Id } from \"./validation/id.schema.js\";\nexport { UniqueNameSchema } from \"./validation/unique-name.schema.js\";\nexport {\n UrlOrPathSchema,\n UrlPathSchema,\n UrlSchema,\n type Url,\n type UrlOrPath,\n type UrlPath,\n} from \"./validation/url.schema.js\";\n","import { ZodError, type ZodType } from \"zod/v4\";\n\n/**\n * Validates a value against a given Zod schema.\n *\n * @param schema - The Zod schema to validate against.\n * @param value - The value to validate.\n * @returns The validated and parsed value.\n * @throws Will throw an error if validation fails, with formatted error messages.\n *\n * @example\n * import { validate } from \"@settlemint/sdk-utils/validation\";\n *\n * const validatedId = validate(IdSchema, \"550e8400-e29b-41d4-a716-446655440000\");\n */\nexport function validate<T extends ZodType>(schema: T, value: unknown): T[\"_output\"] {\n try {\n return schema.parse(value);\n } catch (error) {\n if (error instanceof ZodError) {\n const formattedErrors = error.issues.map((err) => `- ${err.path.join(\".\")}: ${err.message}`).join(\"\\n\");\n throw new Error(`Validation error${error.issues.length > 1 ? \"s\" : \"\"}:\\n${formattedErrors}`);\n }\n throw error; // Re-throw if it's not a ZodError\n }\n}\n","import { type ZodString, z } from \"zod/v4\";\n\n/**\n * Schema for validating application access tokens.\n * Application access tokens start with 'sm_aat_' prefix.\n */\nexport const ApplicationAccessTokenSchema: ZodString = z.string().regex(/^sm_aat_.*$/);\nexport type ApplicationAccessToken = z.infer<typeof ApplicationAccessTokenSchema>;\n\n/**\n * Schema for validating personal access tokens.\n * Personal access tokens start with 'sm_pat_' prefix.\n */\nexport const PersonalAccessTokenSchema: ZodString = z.string().regex(/^sm_pat_.*$/);\nexport type PersonalAccessToken = z.infer<typeof PersonalAccessTokenSchema>;\n\n/**\n * Schema for validating both application and personal access tokens.\n * Accepts tokens starting with either 'sm_pat_' or 'sm_aat_' prefix.\n */\nexport const AccessTokenSchema: ZodString = z.string().regex(/^sm_pat_.*|sm_aat_.*$/);\nexport type AccessToken = z.infer<typeof AccessTokenSchema>;\n","/**\n * Attempts to parse a JSON string into a typed value, returning a default value if parsing fails.\n *\n * @param value - The JSON string to parse\n * @param defaultValue - The value to return if parsing fails or results in null/undefined\n * @returns The parsed JSON value as type T, or the default value if parsing fails\n *\n * @example\n * import { tryParseJson } from \"@settlemint/sdk-utils\";\n *\n * const config = tryParseJson<{ port: number }>(\n * '{\"port\": 3000}',\n * { port: 8080 }\n * );\n * // Returns: { port: 3000 }\n *\n * const invalid = tryParseJson<string[]>(\n * 'invalid json',\n * []\n * );\n * // Returns: []\n */\nexport function tryParseJson<T>(value: string, defaultValue: T | null = null): T | null {\n try {\n const parsed = JSON.parse(value) as T;\n if (parsed === undefined || parsed === null) {\n return defaultValue;\n }\n return parsed;\n } catch (err) {\n // Invalid json\n return defaultValue;\n }\n}\n\n/**\n * Extracts a JSON object from a string.\n *\n * @param value - The string to extract the JSON object from\n * @returns The parsed JSON object, or null if no JSON object is found\n * @throws {Error} If the input string is too long (longer than 5000 characters)\n * @example\n * import { extractJsonObject } from \"@settlemint/sdk-utils\";\n *\n * const json = extractJsonObject<{ port: number }>(\n * 'port info: {\"port\": 3000}',\n * );\n * // Returns: { port: 3000 }\n */\nexport function extractJsonObject<T>(value: string): T | null {\n if (value.length > 5000) {\n throw new Error(\"Input too long\");\n }\n const result = /\\{([\\s\\S]*)\\}/.exec(value);\n if (!result) {\n return null;\n }\n return tryParseJson<T>(result[0]);\n}\n\n/**\n * Converts a value to a JSON stringifiable format.\n *\n * @param value - The value to convert\n * @returns The JSON stringifiable value\n *\n * @example\n * import { makeJsonStringifiable } from \"@settlemint/sdk-utils\";\n *\n * const json = makeJsonStringifiable<{ amount: bigint }>({ amount: BigInt(1000) });\n * // Returns: '{\"amount\":\"1000\"}'\n */\nexport function makeJsonStringifiable<T>(value: unknown): T {\n if (value === undefined || value === null) {\n return value as T;\n }\n return tryParseJson<T>(\n JSON.stringify(\n value,\n (_, value) => (typeof value === \"bigint\" ? value.toString() : value), // return everything else unchanged\n ),\n ) as T;\n}\n","import { tryParseJson } from \"@/json.js\";\nimport { z } from \"zod/v4\";\nimport { ApplicationAccessTokenSchema, PersonalAccessTokenSchema } from \"./access-token.schema.js\";\nimport { UniqueNameSchema } from \"./unique-name.schema.js\";\nimport { UrlSchema } from \"./url.schema.js\";\n\n/**\n * Use this value to indicate that the resources are not part of the SettleMint platform.\n */\nexport const STANDALONE_INSTANCE = \"standalone\";\n\n/**\n * Schema for validating environment variables used by the SettleMint SDK.\n * Defines validation rules and types for configuration values like URLs,\n * access tokens, workspace names, and service endpoints.\n */\nexport const DotEnvSchema = z.object({\n /** Base URL of the SettleMint platform instance, set to standalone if your resources are not part of the SettleMint platform */\n SETTLEMINT_INSTANCE: z.union([UrlSchema, z.literal(STANDALONE_INSTANCE)]).default(\"https://console.settlemint.com\"),\n /** Application access token for authenticating with SettleMint services */\n SETTLEMINT_ACCESS_TOKEN: ApplicationAccessTokenSchema.optional(),\n /** @internal */\n SETTLEMINT_PERSONAL_ACCESS_TOKEN: PersonalAccessTokenSchema.optional(),\n /** Unique name of the workspace */\n SETTLEMINT_WORKSPACE: UniqueNameSchema.optional(),\n /** Unique name of the application */\n SETTLEMINT_APPLICATION: UniqueNameSchema.optional(),\n /** Unique name of the blockchain network */\n SETTLEMINT_BLOCKCHAIN_NETWORK: UniqueNameSchema.optional(),\n /** Chain ID of the blockchain network */\n SETTLEMINT_BLOCKCHAIN_NETWORK_CHAIN_ID: z.string().optional(),\n /** Unique name of the blockchain node (should have a private key for signing transactions) */\n SETTLEMINT_BLOCKCHAIN_NODE: UniqueNameSchema.optional(),\n /** JSON RPC endpoint for the blockchain node */\n SETTLEMINT_BLOCKCHAIN_NODE_JSON_RPC_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the blockchain node or load balancer */\n SETTLEMINT_BLOCKCHAIN_NODE_OR_LOAD_BALANCER: UniqueNameSchema.optional(),\n /** JSON RPC endpoint for the blockchain node or load balancer */\n SETTLEMINT_BLOCKCHAIN_NODE_OR_LOAD_BALANCER_JSON_RPC_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the Hasura instance */\n SETTLEMINT_HASURA: UniqueNameSchema.optional(),\n /** Endpoint URL for the Hasura GraphQL API */\n SETTLEMINT_HASURA_ENDPOINT: UrlSchema.optional(),\n /** Admin secret for authenticating with Hasura */\n SETTLEMINT_HASURA_ADMIN_SECRET: z.string().optional(),\n /** Database connection URL for Hasura */\n SETTLEMINT_HASURA_DATABASE_URL: z.string().optional(),\n /** Unique name of The Graph instance */\n SETTLEMINT_THEGRAPH: UniqueNameSchema.optional(),\n /** Array of endpoint URLs for The Graph subgraphs */\n SETTLEMINT_THEGRAPH_SUBGRAPHS_ENDPOINTS: z.preprocess(\n (value) => tryParseJson(value as string, []),\n z.array(UrlSchema).optional(),\n ),\n /** Default The Graph subgraph to use */\n SETTLEMINT_THEGRAPH_DEFAULT_SUBGRAPH: z.string().optional(),\n /** Unique name of the Smart Contract Portal instance */\n SETTLEMINT_PORTAL: UniqueNameSchema.optional(),\n /** GraphQL endpoint URL for the Portal */\n SETTLEMINT_PORTAL_GRAPHQL_ENDPOINT: UrlSchema.optional(),\n /** REST endpoint URL for the Portal */\n SETTLEMINT_PORTAL_REST_ENDPOINT: UrlSchema.optional(),\n /** WebSocket endpoint URL for the Portal */\n SETTLEMINT_PORTAL_WS_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the HD private key */\n SETTLEMINT_HD_PRIVATE_KEY: UniqueNameSchema.optional(),\n /** Address of the HD private key forwarder */\n SETTLEMINT_HD_PRIVATE_KEY_FORWARDER_ADDRESS: z.string().optional(),\n /** Unique name of the accessible private key */\n SETTLEMINT_ACCESSIBLE_PRIVATE_KEY: UniqueNameSchema.optional(),\n /** Unique name of the MinIO instance */\n SETTLEMINT_MINIO: UniqueNameSchema.optional(),\n /** Endpoint URL for MinIO */\n SETTLEMINT_MINIO_ENDPOINT: UrlSchema.optional(),\n /** Access key for MinIO authentication */\n SETTLEMINT_MINIO_ACCESS_KEY: z.string().optional(),\n /** Secret key for MinIO authentication */\n SETTLEMINT_MINIO_SECRET_KEY: z.string().optional(),\n /** Unique name of the IPFS instance */\n SETTLEMINT_IPFS: UniqueNameSchema.optional(),\n /** API endpoint URL for IPFS */\n SETTLEMINT_IPFS_API_ENDPOINT: UrlSchema.optional(),\n /** Pinning service endpoint URL for IPFS */\n SETTLEMINT_IPFS_PINNING_ENDPOINT: UrlSchema.optional(),\n /** Gateway endpoint URL for IPFS */\n SETTLEMINT_IPFS_GATEWAY_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the custom deployment */\n SETTLEMINT_CUSTOM_DEPLOYMENT: UniqueNameSchema.optional(),\n /** Endpoint URL for the custom deployment */\n SETTLEMINT_CUSTOM_DEPLOYMENT_ENDPOINT: UrlSchema.optional(),\n /** Unique name of the Blockscout instance */\n SETTLEMINT_BLOCKSCOUT: UniqueNameSchema.optional(),\n /** GraphQL endpoint URL for Blockscout */\n SETTLEMINT_BLOCKSCOUT_GRAPHQL_ENDPOINT: UrlSchema.optional(),\n /** UI endpoint URL for Blockscout */\n SETTLEMINT_BLOCKSCOUT_UI_ENDPOINT: UrlSchema.optional(),\n /** Name of the new project being created */\n SETTLEMINT_NEW_PROJECT_NAME: z.string().optional(),\n /** The log level to use */\n SETTLEMINT_LOG_LEVEL: z.enum([\"debug\", \"info\", \"warn\", \"error\", \"none\"]).default(\"warn\"),\n});\n\n/**\n * Type definition for the environment variables schema.\n */\nexport type DotEnv = z.infer<typeof DotEnvSchema>;\n\n/**\n * Partial version of the environment variables schema where all fields are optional.\n * Useful for validating incomplete configurations during development or build time.\n */\nexport const DotEnvSchemaPartial = DotEnvSchema.partial();\n\n/**\n * Type definition for the partial environment variables schema.\n */\nexport type DotEnvPartial = z.infer<typeof DotEnvSchemaPartial>;\n","import { z } from \"zod/v4\";\n\n/**\n * Schema for validating unique names used across the SettleMint platform.\n * Only accepts lowercase alphanumeric characters and hyphens.\n * Used for workspace names, application names, service names etc.\n *\n * @example\n * import { UniqueNameSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate a workspace name\n * const isValidName = UniqueNameSchema.safeParse(\"my-workspace-123\").success;\n * // true\n *\n * // Invalid names will fail validation\n * const isInvalidName = UniqueNameSchema.safeParse(\"My Workspace!\").success;\n * // false\n */\nexport const UniqueNameSchema = z.string().regex(/^[a-z0-9-]+$/);\n\n/**\n * Type definition for unique names, inferred from UniqueNameSchema.\n */\nexport type UniqueName = z.infer<typeof UniqueNameSchema>;\n","import { z } from \"zod/v4\";\n\n/**\n * Schema for validating URLs.\n *\n * @example\n * import { UrlSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate a URL\n * const isValidUrl = UrlSchema.safeParse(\"https://console.settlemint.com\").success;\n * // true\n *\n * // Invalid URLs will fail validation\n * const isInvalidUrl = UrlSchema.safeParse(\"not-a-url\").success;\n * // false\n */\nexport const UrlSchema = z.string().url();\nexport type Url = z.infer<typeof UrlSchema>;\n\n/**\n * Schema for validating URL paths.\n *\n * @example\n * import { UrlPathSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate a URL path\n * const isValidPath = UrlPathSchema.safeParse(\"/api/v1/users\").success;\n * // true\n *\n * // Invalid paths will fail validation\n * const isInvalidPath = UrlPathSchema.safeParse(\"not-a-path\").success;\n * // false\n */\nexport const UrlPathSchema = z.string().regex(/^\\/(?:[a-zA-Z0-9-_]+(?:\\/[a-zA-Z0-9-_]+)*\\/?)?$/, {\n message: \"Invalid URL path format. Must start with '/' and can contain letters, numbers, hyphens, and underscores.\",\n});\n\nexport type UrlPath = z.infer<typeof UrlPathSchema>;\n\n/**\n * Schema that accepts either a full URL or a URL path.\n *\n * @example\n * import { UrlOrPathSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate a URL\n * const isValidUrl = UrlOrPathSchema.safeParse(\"https://console.settlemint.com\").success;\n * // true\n *\n * // Validate a path\n * const isValidPath = UrlOrPathSchema.safeParse(\"/api/v1/users\").success;\n * // true\n */\nexport const UrlOrPathSchema = z.union([UrlSchema, UrlPathSchema]);\nexport type UrlOrPath = z.infer<typeof UrlOrPathSchema>;\n","import { z } from \"zod/v4\";\n\n/**\n * Schema for validating database IDs. Accepts both PostgreSQL UUIDs and MongoDB ObjectIDs.\n * PostgreSQL UUIDs are 32 hexadecimal characters with hyphens (e.g. 123e4567-e89b-12d3-a456-426614174000).\n * MongoDB ObjectIDs are 24 hexadecimal characters (e.g. 507f1f77bcf86cd799439011).\n *\n * @example\n * import { IdSchema } from \"@settlemint/sdk-utils/validation\";\n *\n * // Validate PostgreSQL UUID\n * const isValidUuid = IdSchema.safeParse(\"123e4567-e89b-12d3-a456-426614174000\").success;\n *\n * // Validate MongoDB ObjectID\n * const isValidObjectId = IdSchema.safeParse(\"507f1f77bcf86cd799439011\").success;\n */\nexport const IdSchema = z.union([\n z\n .string()\n .uuid(), // PostgreSQL UUID\n z\n .string()\n .regex(/^[0-9a-fA-F]{24}$/), // MongoDB ObjectID\n]);\n\n/**\n * Type definition for database IDs, inferred from IdSchema.\n * Can be either a PostgreSQL UU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A,EAElD,2BAA2B,iBAAiB,SAAS;AAAA;AAAA,EAErD,6CAA6C,aAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEjE,mCAAmC,iBAAiB,SAAS;AAAA;AAAA,EAE7D,kBAAkB,iBAAiB,SAAS;AAAA;AAAA,EAE5C,2BAA2B,UAAU,SAAS;AAAA;AAAA,EAE9C,6BAA6B,aAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEjD,6BAA6B,aAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEjD,iBAAiB,iBAAiB,SAAS;AAAA;AAAA,EAE3C,8BAA8B,UAAU,SAAS;AAAA;AAAA,EAEjD,kCAAkC,UAAU,SAAS;AAAA;AAAA,EAErD,kCAAkC,UAAU,SAAS;AAAA;AAAA,EAErD,8BAA8B,iBAAiB,SAAS;AAAA;AAAA,EAExD,uCAAuC,UAAU,SAAS;AAAA;AAAA,EAE1D,uBAAuB,iBAAiB,SAAS;AAAA;AAAA,EAEjD,wCAAwC,UAAU,SAAS;AAAA;AAAA,EAE3D,mCAAmC,UAAU,SAAS;AAAA;AAAA,EAEtD,6BAA6B,aAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEjD,sBAAsB,aAAE,KAAK,CAAC,SAAS,QAAQ,QAAQ,SAAS,MAAM,CAAC,EAAE,QAAQ,MAAM;AACzF,CAAC;AAWM,IAAM,sBAAsB,aAAa,QAAQ;;;AG/GxD,IAAAC,aAAkB;AAgBX,IAAM,WAAW,aAAE,MAAM;AAAA,EAC9B,aACG,OAAO,EACP,KAAK;AAAA;AAAA,EACR,aACG,OAAO,EACP,MAAM,mBAAmB;AAAA;AAC9B,CAAC;","names":["import_v4","import_v4","import_v4","import_v4","import_v4"]}
|
package/dist/validation.d.cts
CHANGED
|
@@ -34,13 +34,17 @@ type PersonalAccessToken = z.infer<typeof PersonalAccessTokenSchema>;
|
|
|
34
34
|
declare const AccessTokenSchema: ZodString;
|
|
35
35
|
type AccessToken = z.infer<typeof AccessTokenSchema>;
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Use this value to indicate that the resources are not part of the SettleMint platform.
|
|
39
|
+
*/
|
|
40
|
+
declare const STANDALONE_INSTANCE = "standalone";
|
|
37
41
|
/**
|
|
38
42
|
* Schema for validating environment variables used by the SettleMint SDK.
|
|
39
43
|
* Defines validation rules and types for configuration values like URLs,
|
|
40
44
|
* access tokens, workspace names, and service endpoints.
|
|
41
45
|
*/
|
|
42
46
|
declare const DotEnvSchema: z.ZodObject<{
|
|
43
|
-
SETTLEMINT_INSTANCE: z.ZodDefault<z.ZodString
|
|
47
|
+
SETTLEMINT_INSTANCE: z.ZodDefault<z.ZodUnion<readonly [z.ZodString, z.ZodLiteral<"standalone">]>>;
|
|
44
48
|
SETTLEMINT_ACCESS_TOKEN: z.ZodOptional<z.ZodString>;
|
|
45
49
|
SETTLEMINT_PERSONAL_ACCESS_TOKEN: z.ZodOptional<z.ZodString>;
|
|
46
50
|
SETTLEMINT_WORKSPACE: z.ZodOptional<z.ZodString>;
|
|
@@ -96,7 +100,7 @@ type DotEnv = z.infer<typeof DotEnvSchema>;
|
|
|
96
100
|
* Useful for validating incomplete configurations during development or build time.
|
|
97
101
|
*/
|
|
98
102
|
declare const DotEnvSchemaPartial: z.ZodObject<{
|
|
99
|
-
SETTLEMINT_INSTANCE: z.ZodOptional<z.ZodDefault<z.ZodString
|
|
103
|
+
SETTLEMINT_INSTANCE: z.ZodOptional<z.ZodDefault<z.ZodUnion<readonly [z.ZodString, z.ZodLiteral<"standalone">]>>>;
|
|
100
104
|
SETTLEMINT_ACCESS_TOKEN: z.ZodOptional<z.ZodOptional<z.ZodString>>;
|
|
101
105
|
SETTLEMINT_PERSONAL_ACCESS_TOKEN: z.ZodOptional<z.ZodOptional<z.ZodString>>;
|
|
102
106
|
SETTLEMINT_WORKSPACE: z.ZodOptional<z.ZodOptional<z.ZodString>>;
|
|
@@ -236,4 +240,4 @@ type UrlPath = z.infer<typeof UrlPathSchema>;
|
|
|
236
240
|
declare const UrlOrPathSchema: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
|
|
237
241
|
type UrlOrPath = z.infer<typeof UrlOrPathSchema>;
|
|
238
242
|
|
|
239
|
-
export { type AccessToken, AccessTokenSchema, type ApplicationAccessToken, ApplicationAccessTokenSchema, type DotEnv, type DotEnvPartial, DotEnvSchema, DotEnvSchemaPartial, type Id, IdSchema, type PersonalAccessToken, PersonalAccessTokenSchema, UniqueNameSchema, type Url, type UrlOrPath, UrlOrPathSchema, type UrlPath, UrlPathSchema, UrlSchema, validate };
|
|
243
|
+
export { type AccessToken, AccessTokenSchema, type ApplicationAccessToken, ApplicationAccessTokenSchema, type DotEnv, type DotEnvPartial, DotEnvSchema, DotEnvSchemaPartial, type Id, IdSchema, type PersonalAccessToken, PersonalAccessTokenSchema, STANDALONE_INSTANCE, UniqueNameSchema, type Url, type UrlOrPath, UrlOrPathSchema, type UrlPath, UrlPathSchema, UrlSchema, validate };
|
package/dist/validation.d.ts
CHANGED
|
@@ -34,13 +34,17 @@ type PersonalAccessToken = z.infer<typeof PersonalAccessTokenSchema>;
|
|
|
34
34
|
declare const AccessTokenSchema: ZodString;
|
|
35
35
|
type AccessToken = z.infer<typeof AccessTokenSchema>;
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* Use this value to indicate that the resources are not part of the SettleMint platform.
|
|
39
|
+
*/
|
|
40
|
+
declare const STANDALONE_INSTANCE = "standalone";
|
|
37
41
|
/**
|
|
38
42
|
* Schema for validating environment variables used by the SettleMint SDK.
|
|
39
43
|
* Defines validation rules and types for configuration values like URLs,
|
|
40
44
|
* access tokens, workspace names, and service endpoints.
|
|
41
45
|
*/
|
|
42
46
|
declare const DotEnvSchema: z.ZodObject<{
|
|
43
|
-
SETTLEMINT_INSTANCE: z.ZodDefault<z.ZodString
|
|
47
|
+
SETTLEMINT_INSTANCE: z.ZodDefault<z.ZodUnion<readonly [z.ZodString, z.ZodLiteral<"standalone">]>>;
|
|
44
48
|
SETTLEMINT_ACCESS_TOKEN: z.ZodOptional<z.ZodString>;
|
|
45
49
|
SETTLEMINT_PERSONAL_ACCESS_TOKEN: z.ZodOptional<z.ZodString>;
|
|
46
50
|
SETTLEMINT_WORKSPACE: z.ZodOptional<z.ZodString>;
|
|
@@ -96,7 +100,7 @@ type DotEnv = z.infer<typeof DotEnvSchema>;
|
|
|
96
100
|
* Useful for validating incomplete configurations during development or build time.
|
|
97
101
|
*/
|
|
98
102
|
declare const DotEnvSchemaPartial: z.ZodObject<{
|
|
99
|
-
SETTLEMINT_INSTANCE: z.ZodOptional<z.ZodDefault<z.ZodString
|
|
103
|
+
SETTLEMINT_INSTANCE: z.ZodOptional<z.ZodDefault<z.ZodUnion<readonly [z.ZodString, z.ZodLiteral<"standalone">]>>>;
|
|
100
104
|
SETTLEMINT_ACCESS_TOKEN: z.ZodOptional<z.ZodOptional<z.ZodString>>;
|
|
101
105
|
SETTLEMINT_PERSONAL_ACCESS_TOKEN: z.ZodOptional<z.ZodOptional<z.ZodString>>;
|
|
102
106
|
SETTLEMINT_WORKSPACE: z.ZodOptional<z.ZodOptional<z.ZodString>>;
|
|
@@ -236,4 +240,4 @@ type UrlPath = z.infer<typeof UrlPathSchema>;
|
|
|
236
240
|
declare const UrlOrPathSchema: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
|
|
237
241
|
type UrlOrPath = z.infer<typeof UrlOrPathSchema>;
|
|
238
242
|
|
|
239
|
-
export { type AccessToken, AccessTokenSchema, type ApplicationAccessToken, ApplicationAccessTokenSchema, type DotEnv, type DotEnvPartial, DotEnvSchema, DotEnvSchemaPartial, type Id, IdSchema, type PersonalAccessToken, PersonalAccessTokenSchema, UniqueNameSchema, type Url, type UrlOrPath, UrlOrPathSchema, type UrlPath, UrlPathSchema, UrlSchema, validate };
|
|
243
|
+
export { type AccessToken, AccessTokenSchema, type ApplicationAccessToken, ApplicationAccessTokenSchema, type DotEnv, type DotEnvPartial, DotEnvSchema, DotEnvSchemaPartial, type Id, IdSchema, type PersonalAccessToken, PersonalAccessTokenSchema, STANDALONE_INSTANCE, UniqueNameSchema, type Url, type UrlOrPath, UrlOrPathSchema, type UrlPath, UrlPathSchema, UrlSchema, validate };
|
package/dist/validation.mjs
CHANGED
|
@@ -48,9 +48,10 @@ var UrlPathSchema = z3.string().regex(/^\/(?:[a-zA-Z0-9-_]+(?:\/[a-zA-Z0-9-_]+)*
|
|
|
48
48
|
var UrlOrPathSchema = z3.union([UrlSchema, UrlPathSchema]);
|
|
49
49
|
|
|
50
50
|
// src/validation/dot-env.schema.ts
|
|
51
|
+
var STANDALONE_INSTANCE = "standalone";
|
|
51
52
|
var DotEnvSchema = z4.object({
|
|
52
|
-
/** Base URL of the SettleMint platform instance */
|
|
53
|
-
SETTLEMINT_INSTANCE: UrlSchema.default("https://console.settlemint.com"),
|
|
53
|
+
/** Base URL of the SettleMint platform instance, set to standalone if your resources are not part of the SettleMint platform */
|
|
54
|
+
SETTLEMINT_INSTANCE: z4.union([UrlSchema, z4.literal(STANDALONE_INSTANCE)]).default("https://console.settlemint.com"),
|
|
54
55
|
/** Application access token for authenticating with SettleMint services */
|
|
55
56
|
SETTLEMINT_ACCESS_TOKEN: ApplicationAccessTokenSchema.optional(),
|
|
56
57
|
/** @internal */
|
|
@@ -150,6 +151,7 @@ export {
|
|
|
150
151
|
DotEnvSchemaPartial,
|
|
151
152
|
IdSchema,
|
|
152
153
|
PersonalAccessTokenSchema,
|
|
154
|
+
STANDALONE_INSTANCE,
|
|
153
155
|
UniqueNameSchema,
|
|
154
156
|
UrlOrPathSchema,
|
|
155
157
|
UrlPathSchema,
|