@intlayer/api 9.6.0 → 9.7.1
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/cjs/cms/createAuthManager.cjs +2 -3
- package/dist/cjs/cms/createIntlayerCMS.cjs +2 -3
- package/dist/cjs/cms/index.cjs +2 -2
- package/dist/cjs/distantDictionary/fetchDistantDictionaries.cjs +3 -4
- package/dist/cjs/distantDictionary/fetchDistantDictionaries.cjs.map +1 -1
- package/dist/cjs/distantDictionary/fetchDistantDictionary.cjs +3 -4
- package/dist/cjs/distantDictionary/fetchDistantDictionary.cjs.map +1 -1
- package/dist/cjs/distantDictionary/index.cjs +2 -2
- package/dist/cjs/fetcher.cjs +2 -3
- package/dist/cjs/fetcher.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/ai.cjs +79 -26
- package/dist/cjs/getIntlayerAPI/ai.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/analytics.cjs +47 -14
- package/dist/cjs/getIntlayerAPI/analytics.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/asset.cjs +41 -12
- package/dist/cjs/getIntlayerAPI/asset.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/audit.cjs +73 -20
- package/dist/cjs/getIntlayerAPI/audit.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/bitbucket.cjs +42 -13
- package/dist/cjs/getIntlayerAPI/bitbucket.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/codeberg.cjs +20 -0
- package/dist/cjs/getIntlayerAPI/codeberg.cjs.map +1 -0
- package/dist/cjs/getIntlayerAPI/dictionary.cjs +62 -17
- package/dist/cjs/getIntlayerAPI/dictionary.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/editor.cjs +3 -4
- package/dist/cjs/getIntlayerAPI/editor.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/environment.cjs +47 -14
- package/dist/cjs/getIntlayerAPI/environment.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/forge.cjs +63 -0
- package/dist/cjs/getIntlayerAPI/forge.cjs.map +1 -0
- package/dist/cjs/getIntlayerAPI/gitee.cjs +20 -0
- package/dist/cjs/getIntlayerAPI/gitee.cjs.map +1 -0
- package/dist/cjs/getIntlayerAPI/github.cjs +47 -14
- package/dist/cjs/getIntlayerAPI/github.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/gitlab.cjs +42 -13
- package/dist/cjs/getIntlayerAPI/gitlab.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/index.cjs +27 -24
- package/dist/cjs/getIntlayerAPI/index.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/newsletter.cjs +31 -10
- package/dist/cjs/getIntlayerAPI/newsletter.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/oAuth.cjs +33 -8
- package/dist/cjs/getIntlayerAPI/oAuth.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/organization.cjs +75 -24
- package/dist/cjs/getIntlayerAPI/organization.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/project.cjs +115 -33
- package/dist/cjs/getIntlayerAPI/project.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/reviewer.cjs +145 -35
- package/dist/cjs/getIntlayerAPI/reviewer.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/search.cjs +18 -7
- package/dist/cjs/getIntlayerAPI/search.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/showcaseProject.cjs +64 -19
- package/dist/cjs/getIntlayerAPI/showcaseProject.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/status.cjs +19 -7
- package/dist/cjs/getIntlayerAPI/status.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/stripe.cjs +144 -39
- package/dist/cjs/getIntlayerAPI/stripe.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/tag.cjs +36 -11
- package/dist/cjs/getIntlayerAPI/tag.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/translate.cjs +49 -12
- package/dist/cjs/getIntlayerAPI/translate.cjs.map +1 -1
- package/dist/cjs/getIntlayerAPI/user.cjs +61 -18
- package/dist/cjs/getIntlayerAPI/user.cjs.map +1 -1
- package/dist/cjs/index.cjs +38 -30
- package/dist/cjs/proxy.cjs +28 -25
- package/dist/cjs/proxy.cjs.map +1 -1
- package/dist/cjs/public/createPublicClient.cjs +26 -7
- package/dist/cjs/public/createPublicClient.cjs.map +1 -1
- package/dist/cjs/public/index.cjs +1 -1
- package/dist/cjs/resolveInternalBackendUrl.cjs +1 -2
- package/dist/esm/cms/createAuthManager.mjs +1 -2
- package/dist/esm/cms/createIntlayerCMS.mjs +1 -2
- package/dist/esm/distantDictionary/fetchDistantDictionaries.mjs +1 -2
- package/dist/esm/distantDictionary/fetchDistantDictionaries.mjs.map +1 -1
- package/dist/esm/distantDictionary/fetchDistantDictionary.mjs +1 -2
- package/dist/esm/distantDictionary/fetchDistantDictionary.mjs.map +1 -1
- package/dist/esm/fetcher.mjs +1 -2
- package/dist/esm/fetcher.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/ai.mjs +78 -25
- package/dist/esm/getIntlayerAPI/ai.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/analytics.mjs +46 -13
- package/dist/esm/getIntlayerAPI/analytics.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/asset.mjs +40 -11
- package/dist/esm/getIntlayerAPI/asset.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/audit.mjs +72 -19
- package/dist/esm/getIntlayerAPI/audit.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/bitbucket.mjs +41 -12
- package/dist/esm/getIntlayerAPI/bitbucket.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/codeberg.mjs +18 -0
- package/dist/esm/getIntlayerAPI/codeberg.mjs.map +1 -0
- package/dist/esm/getIntlayerAPI/dictionary.mjs +61 -16
- package/dist/esm/getIntlayerAPI/dictionary.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/editor.mjs +2 -3
- package/dist/esm/getIntlayerAPI/editor.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/environment.mjs +46 -13
- package/dist/esm/getIntlayerAPI/environment.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/forge.mjs +62 -0
- package/dist/esm/getIntlayerAPI/forge.mjs.map +1 -0
- package/dist/esm/getIntlayerAPI/gitee.mjs +18 -0
- package/dist/esm/getIntlayerAPI/gitee.mjs.map +1 -0
- package/dist/esm/getIntlayerAPI/github.mjs +46 -13
- package/dist/esm/getIntlayerAPI/github.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/gitlab.mjs +41 -12
- package/dist/esm/getIntlayerAPI/gitlab.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/index.mjs +6 -3
- package/dist/esm/getIntlayerAPI/index.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/newsletter.mjs +30 -9
- package/dist/esm/getIntlayerAPI/newsletter.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/oAuth.mjs +32 -7
- package/dist/esm/getIntlayerAPI/oAuth.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/organization.mjs +74 -23
- package/dist/esm/getIntlayerAPI/organization.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/project.mjs +114 -32
- package/dist/esm/getIntlayerAPI/project.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/reviewer.mjs +144 -34
- package/dist/esm/getIntlayerAPI/reviewer.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/search.mjs +17 -6
- package/dist/esm/getIntlayerAPI/search.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/showcaseProject.mjs +63 -18
- package/dist/esm/getIntlayerAPI/showcaseProject.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/status.mjs +18 -6
- package/dist/esm/getIntlayerAPI/status.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/stripe.mjs +143 -38
- package/dist/esm/getIntlayerAPI/stripe.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/tag.mjs +35 -10
- package/dist/esm/getIntlayerAPI/tag.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/translate.mjs +48 -11
- package/dist/esm/getIntlayerAPI/translate.mjs.map +1 -1
- package/dist/esm/getIntlayerAPI/user.mjs +60 -17
- package/dist/esm/getIntlayerAPI/user.mjs.map +1 -1
- package/dist/esm/index.mjs +10 -7
- package/dist/esm/proxy.mjs +6 -3
- package/dist/esm/proxy.mjs.map +1 -1
- package/dist/esm/public/createPublicClient.mjs +26 -7
- package/dist/esm/public/createPublicClient.mjs.map +1 -1
- package/dist/esm/resolveInternalBackendUrl.mjs +1 -2
- package/dist/types/cms/createAuthManager.d.ts +1 -2
- package/dist/types/cms/createAuthManager.d.ts.map +1 -1
- package/dist/types/cms/createIntlayerCMS.d.ts +0 -2
- package/dist/types/cms/createIntlayerCMS.d.ts.map +1 -1
- package/dist/types/distantDictionary/fetchDistantDictionaries.d.ts +1 -3
- package/dist/types/distantDictionary/fetchDistantDictionaries.d.ts.map +1 -1
- package/dist/types/distantDictionary/fetchDistantDictionary.d.ts +1 -3
- package/dist/types/distantDictionary/fetchDistantDictionary.d.ts.map +1 -1
- package/dist/types/fetcher.d.ts +1 -3
- package/dist/types/fetcher.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/ai.d.ts +3 -5
- package/dist/types/getIntlayerAPI/ai.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/analytics.d.ts +3 -5
- package/dist/types/getIntlayerAPI/analytics.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/asset.d.ts +3 -4
- package/dist/types/getIntlayerAPI/asset.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/audit.d.ts +49 -7
- package/dist/types/getIntlayerAPI/audit.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/bitbucket.d.ts +2 -4
- package/dist/types/getIntlayerAPI/bitbucket.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/codeberg.d.ts +59 -0
- package/dist/types/getIntlayerAPI/codeberg.d.ts.map +1 -0
- package/dist/types/getIntlayerAPI/dictionary.d.ts +3 -5
- package/dist/types/getIntlayerAPI/dictionary.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/editor.d.ts +4 -5
- package/dist/types/getIntlayerAPI/editor.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/environment.d.ts +3 -5
- package/dist/types/getIntlayerAPI/environment.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/forge.d.ts +34 -0
- package/dist/types/getIntlayerAPI/forge.d.ts.map +1 -0
- package/dist/types/getIntlayerAPI/gitee.d.ts +59 -0
- package/dist/types/getIntlayerAPI/gitee.d.ts.map +1 -0
- package/dist/types/getIntlayerAPI/github.d.ts +2 -4
- package/dist/types/getIntlayerAPI/github.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/gitlab.d.ts +2 -4
- package/dist/types/getIntlayerAPI/gitlab.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/index.d.ts +6 -3
- package/dist/types/getIntlayerAPI/index.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/newsletter.d.ts +3 -5
- package/dist/types/getIntlayerAPI/newsletter.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/oAuth.d.ts +2 -2
- package/dist/types/getIntlayerAPI/oAuth.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/organization.d.ts +3 -7
- package/dist/types/getIntlayerAPI/organization.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/project.d.ts +4 -5
- package/dist/types/getIntlayerAPI/project.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/reviewer.d.ts +682 -39
- package/dist/types/getIntlayerAPI/reviewer.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/search.d.ts +3 -5
- package/dist/types/getIntlayerAPI/search.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/showcaseProject.d.ts +3 -5
- package/dist/types/getIntlayerAPI/showcaseProject.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/status.d.ts +5 -8
- package/dist/types/getIntlayerAPI/status.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/stripe.d.ts +3 -5
- package/dist/types/getIntlayerAPI/stripe.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/tag.d.ts +3 -5
- package/dist/types/getIntlayerAPI/tag.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/translate.d.ts +3 -5
- package/dist/types/getIntlayerAPI/translate.d.ts.map +1 -1
- package/dist/types/getIntlayerAPI/user.d.ts +6 -8
- package/dist/types/getIntlayerAPI/user.d.ts.map +1 -1
- package/dist/types/index.d.ts +12 -9
- package/dist/types/proxy.d.ts +0 -2
- package/dist/types/proxy.d.ts.map +1 -1
- package/dist/types/public/createPublicClient.d.ts +1 -9
- package/dist/types/public/createPublicClient.d.ts.map +1 -1
- package/dist/types/resolveInternalBackendUrl.d.ts +0 -2
- package/dist/types/resolveInternalBackendUrl.d.ts.map +1 -1
- package/dist/types/types.d.ts +5 -2
- package/package.json +23 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPublicClient.cjs","names":["editor"],"sources":["../../../src/public/createPublicClient.ts"],"sourcesContent":["import type { DictionaryAPI } from '@intlayer/backend';\nimport { editor } from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Browser-safe Intlayer client, authenticated without any confidential\n * credential.\n *\n * This is the Google-Analytics model applied to the whole SDK: the page ships\n * only the **public** `editor.clientId`, exchanges it for a short-lived scoped\n * token, and calls the API directly. No server route, no server action, and no\n * `clientSecret` in the bundle.\n *\n * What it can do is deliberately narrow, and that is what makes shipping the\n * key safe: read the project's published dictionary content — the content the\n * page already renders — and submit analytics events. Writing content, reading\n * a project, an organization or a user still require a real credential\n * (server-side) or a signed-in user.\n *\n * @example\n * ```ts\n * import { createPublicClient } from '@intlayer/api/public';\n *\n * const client = createPublicClient();\n *\n * const keys = await client.getDictionaryKeys();\n * const [dictionary] = await client.getDictionaries(['navbar']);\n * ```\n */\n\n/** `sessionStorage` key holding the cached token for this tab. */\nconst TOKEN_STORAGE_KEY = '__intlayer_public_token__';\n\n/**\n * Refresh margin: a token within this window of expiry is treated as expired,\n * so a request is never sent with a token that dies in flight.\n */\nconst EXPIRY_MARGIN_MS = 60 * 1000;\n\ntype CachedToken = {\n token: string;\n /** Epoch milliseconds. */\n expiresAt: number;\n};\n\n/** Reads the cached token for this tab, ignoring an unusable cache. */\nconst readStoredToken = (): CachedToken | null => {\n try {\n const raw = globalThis.sessionStorage?.getItem(TOKEN_STORAGE_KEY);\n if (!raw) return null;\n\n const parsed = JSON.parse(raw) as CachedToken;\n\n if (typeof parsed?.token !== 'string') return null;\n if (typeof parsed?.expiresAt !== 'number') return null;\n\n return parsed;\n } catch {\n // Private mode, disabled storage, or a corrupted entry — start fresh.\n return null;\n }\n};\n\n/** Persists the token for this tab. Best-effort: storage may be unavailable. */\nconst writeStoredToken = (cached: CachedToken): void => {\n try {\n globalThis.sessionStorage?.setItem(\n TOKEN_STORAGE_KEY,\n JSON.stringify(cached)\n );\n } catch {\n /* ignore — the in-memory cache still applies for this page */\n }\n};\n\n/** Options accepted by {@link createPublicClient}. */\nexport type PublicClientOptions = {\n /** Overrides the build-time `editor` configuration. */\n intlayerConfig?: Pick<IntlayerConfig, 'editor'>;\n};\n\n/** The credential-free client returned by {@link createPublicClient}. */\nexport type PublicClient = {\n /**\n * Returns the current token, exchanging the public `clientId` for one when\n * needed. `null` when the project is unknown or the origin is not allowed.\n */\n getToken: () => Promise<string | null>;\n /** Every dictionary key published for the project. */\n getDictionaryKeys: () => Promise<string[]>;\n /**\n * Published dictionary content for the given keys.\n *\n * @param keys - Dictionary keys to fetch (at most 100 per call).\n */\n getDictionaries: (keys: string[]) => Promise<DictionaryAPI[]>;\n};\n\n/**\n * Creates a {@link PublicClient} for the configured project.\n *\n * @param options - Optional configuration override.\n * @returns A client that authenticates itself with the public project key.\n */\nexport const createPublicClient = ({\n intlayerConfig,\n}: PublicClientOptions = {}): PublicClient => {\n const resolvedEditor = intlayerConfig?.editor ?? editor;\n const backendURL = (resolvedEditor?.backendURL ?? '').replace(/\\/$/, '');\n const clientId = resolvedEditor?.clientId;\n\n let cached: CachedToken | null = null;\n let pendingExchange: Promise<string | null> | null = null;\n\n const isUsable = (candidate: CachedToken | null): candidate is CachedToken =>\n candidate !== null && candidate.expiresAt - EXPIRY_MARGIN_MS > Date.now();\n\n const exchange = async (): Promise<string | null> => {\n const response = await fetch(`${backendURL}
|
|
1
|
+
{"version":3,"file":"createPublicClient.cjs","names":["editor"],"sources":["../../../src/public/createPublicClient.ts"],"sourcesContent":["import type { RouteEndpoints } from '@intlayer/backend-contract/defineRoute';\nimport type { DictionaryAPI } from '@intlayer/backend-contract/dictionary';\nimport type {\n PublicRoutes,\n publicContract,\n} from '@intlayer/backend-contract/public';\nimport { editor } from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types/config';\n\n/**\n * Browser-safe Intlayer client, authenticated without any confidential\n * credential.\n *\n * This is the Google-Analytics model applied to the whole SDK: the page ships\n * only the **public** `editor.clientId`, exchanges it for a short-lived scoped\n * token, and calls the API directly. No server route, no server action, and no\n * `clientSecret` in the bundle.\n *\n * What it can do is deliberately narrow, and that is what makes shipping the\n * key safe: read the project's published dictionary content — the content the\n * page already renders — and submit analytics events. Writing content, reading\n * a project, an organization or a user still require a real credential\n * (server-side) or a signed-in user.\n *\n * @example\n * ```ts\n * import { createPublicClient } from '@intlayer/api/public';\n *\n * const client = createPublicClient();\n *\n * const keys = await client.getDictionaryKeys();\n * const [dictionary] = await client.getDictionaries(['navbar']);\n * ```\n */\n\n/** `sessionStorage` key holding the cached token for this tab. */\nconst TOKEN_STORAGE_KEY = '__intlayer_public_token__';\n\n/**\n * Refresh margin: a token within this window of expiry is treated as expired,\n * so a request is never sent with a token that dies in flight.\n */\nconst EXPIRY_MARGIN_MS = 60 * 1000;\n\ntype CachedToken = {\n token: string;\n /** Epoch milliseconds. */\n expiresAt: number;\n};\n\n/** Reads the cached token for this tab, ignoring an unusable cache. */\nconst readStoredToken = (): CachedToken | null => {\n try {\n const raw = globalThis.sessionStorage?.getItem(TOKEN_STORAGE_KEY);\n if (!raw) return null;\n\n const parsed = JSON.parse(raw) as CachedToken;\n\n if (typeof parsed?.token !== 'string') return null;\n if (typeof parsed?.expiresAt !== 'number') return null;\n\n return parsed;\n } catch {\n // Private mode, disabled storage, or a corrupted entry — start fresh.\n return null;\n }\n};\n\n/** Persists the token for this tab. Best-effort: storage may be unavailable. */\nconst writeStoredToken = (cached: CachedToken): void => {\n try {\n globalThis.sessionStorage?.setItem(\n TOKEN_STORAGE_KEY,\n JSON.stringify(cached)\n );\n } catch {\n /* ignore — the in-memory cache still applies for this page */\n }\n};\n\n/** Options accepted by {@link createPublicClient}. */\nexport type PublicClientOptions = {\n /** Overrides the build-time `editor` configuration. */\n intlayerConfig?: Pick<IntlayerConfig, 'editor'>;\n};\n\n/** The credential-free client returned by {@link createPublicClient}. */\nexport type PublicClient = {\n /**\n * Returns the current token, exchanging the public `clientId` for one when\n * needed. `null` when the project is unknown or the origin is not allowed.\n */\n getToken: () => Promise<string | null>;\n /** Every dictionary key published for the project. */\n getDictionaryKeys: () => Promise<string[]>;\n /**\n * Published dictionary content for the given keys.\n *\n * @param keys - Dictionary keys to fetch (at most 100 per call).\n */\n getDictionaries: (keys: string[]) => Promise<DictionaryAPI[]>;\n};\n\n/**\n * Creates a {@link PublicClient} for the configured project.\n *\n * @param options - Optional configuration override.\n * @returns A client that authenticates itself with the public project key.\n */\n/**\n * Public routes, checked against the backend contract at compile time. Kept\n * as plain strings: this client ships in end-user browser bundles.\n */\nconst publicPrefix = '/api/public' satisfies (typeof publicContract)['prefix'];\nconst publicEndpoints = {\n createPublicBrowserToken: { method: 'POST', path: '/token' },\n getPublicDictionaryKeys: { method: 'GET', path: '/dictionaries/keys' },\n getPublicDictionaries: { method: 'GET', path: '/dictionaries' },\n} as const satisfies RouteEndpoints<PublicRoutes>;\n\nexport const createPublicClient = ({\n intlayerConfig,\n}: PublicClientOptions = {}): PublicClient => {\n const resolvedEditor = intlayerConfig?.editor ?? editor;\n const backendURL = (resolvedEditor?.backendURL ?? '').replace(/\\/$/, '');\n const clientId = resolvedEditor?.clientId;\n\n let cached: CachedToken | null = null;\n let pendingExchange: Promise<string | null> | null = null;\n\n const isUsable = (candidate: CachedToken | null): candidate is CachedToken =>\n candidate !== null && candidate.expiresAt - EXPIRY_MARGIN_MS > Date.now();\n\n const exchange = async (): Promise<string | null> => {\n const { method, path } = publicEndpoints.createPublicBrowserToken;\n const response = await fetch(`${backendURL}${publicPrefix}${path}`, {\n method,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ clientId }),\n // Authorised by `Origin`, never by cookies.\n credentials: 'omit',\n mode: 'cors',\n });\n\n if (!response.ok) return null;\n\n const payload = (await response.json()) as {\n data?: { token?: string | null; expiresIn?: number };\n };\n\n const token = payload?.data?.token;\n const expiresIn = payload?.data?.expiresIn ?? 0;\n\n if (!token || expiresIn <= 0) return null;\n\n cached = { token, expiresAt: Date.now() + expiresIn * 1000 };\n writeStoredToken(cached);\n\n return token;\n };\n\n const getToken = async (): Promise<string | null> => {\n if (isUsable(cached)) return cached.token;\n\n const stored = readStoredToken();\n if (isUsable(stored)) {\n cached = stored;\n return stored.token;\n }\n\n if (!clientId) return null;\n\n // De-duplicate concurrent exchanges so a burst of calls triggers one fetch.\n pendingExchange ??= exchange().finally(() => {\n pendingExchange = null;\n });\n\n return await pendingExchange;\n };\n\n /** Issues an authorised GET against the public surface. */\n const request = async <Result>(\n path: string,\n fallback: Result\n ): Promise<Result> => {\n const token = await getToken();\n\n if (!token) return fallback;\n\n const response = await fetch(`${backendURL}${publicPrefix}${path}`, {\n headers: { Authorization: `Bearer ${token}` },\n credentials: 'omit',\n mode: 'cors',\n });\n\n if (!response.ok) return fallback;\n\n const payload = (await response.json()) as { data?: Result };\n\n return payload?.data ?? fallback;\n };\n\n return {\n getToken,\n getDictionaryKeys: () =>\n request<string[]>(publicEndpoints.getPublicDictionaryKeys.path, []),\n getDictionaries: (keys) =>\n request<DictionaryAPI[]>(\n `${publicEndpoints.getPublicDictionaries.path}?keys=${encodeURIComponent(keys.join(','))}`,\n []\n ),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAM,oBAAoB;;;;;AAM1B,MAAM,mBAAmB;;AASzB,MAAM,wBAA4C;CAChD,IAAI;EACF,MAAM,MAAM,WAAW,gBAAgB,QAAQ,iBAAiB;EAChE,IAAI,CAAC,KAAK,OAAO;EAEjB,MAAM,SAAS,KAAK,MAAM,GAAG;EAE7B,IAAI,OAAO,QAAQ,UAAU,UAAU,OAAO;EAC9C,IAAI,OAAO,QAAQ,cAAc,UAAU,OAAO;EAElD,OAAO;CACT,QAAQ;EAEN,OAAO;CACT;AACF;;AAGA,MAAM,oBAAoB,WAA8B;CACtD,IAAI;EACF,WAAW,gBAAgB,QACzB,mBACA,KAAK,UAAU,MAAM,CACvB;CACF,QAAQ,CAER;AACF;;;;;;;;;;;AAmCA,MAAM,eAAe;AACrB,MAAM,kBAAkB;CACtB,0BAA0B;EAAE,QAAQ;EAAQ,MAAM;CAAS;CAC3D,yBAAyB;EAAE,QAAQ;EAAO,MAAM;CAAqB;CACrE,uBAAuB;EAAE,QAAQ;EAAO,MAAM;CAAgB;AAChE;AAEA,MAAa,sBAAsB,EACjC,mBACuB,CAAC,MAAoB;CAC5C,MAAM,iBAAiB,gBAAgB,UAAUA;CACjD,MAAM,cAAc,gBAAgB,cAAc,GAAE,CAAE,QAAQ,OAAO,EAAE;CACvE,MAAM,WAAW,gBAAgB;CAEjC,IAAI,SAA6B;CACjC,IAAI,kBAAiD;CAErD,MAAM,YAAY,cAChB,cAAc,QAAQ,UAAU,YAAY,mBAAmB,KAAK,IAAI;CAE1E,MAAM,WAAW,YAAoC;EACnD,MAAM,EAAE,QAAQ,SAAS,gBAAgB;EACzC,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H;CACJ;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_public_createPublicClient = require(
|
|
2
|
+
const require_public_createPublicClient = require("./createPublicClient.cjs");
|
|
3
3
|
|
|
4
4
|
exports.createPublicClient = require_public_createPublicClient.createPublicClient;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
let _intlayer_config_built = require("@intlayer/config/built");
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
// src/resolveInternalBackendUrl.ts
|
|
5
5
|
/**
|
|
6
6
|
* Server-only override for the backend origin.
|
|
7
7
|
*
|
|
@@ -45,7 +45,6 @@ const resolveInternalBackendUrl = (url, publicBackendUrl = _intlayer_config_buil
|
|
|
45
45
|
}
|
|
46
46
|
};
|
|
47
47
|
|
|
48
|
-
//#endregion
|
|
49
48
|
exports.BACKEND_INTERNAL_URL_ENVIRONMENT_VARIABLE = BACKEND_INTERNAL_URL_ENVIRONMENT_VARIABLE;
|
|
50
49
|
exports.resolveInternalBackendUrl = resolveInternalBackendUrl;
|
|
51
50
|
//# sourceMappingURL=resolveInternalBackendUrl.cjs.map
|
|
@@ -3,7 +3,7 @@ import { editor } from "@intlayer/config/built";
|
|
|
3
3
|
import { getEditorClientSecret } from "@intlayer/config/secrets";
|
|
4
4
|
import { defu } from "defu";
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
// src/cms/createAuthManager.ts
|
|
7
7
|
const ONE_MINUTE_MS = 6e4;
|
|
8
8
|
/**
|
|
9
9
|
* Process-wide token states, keyed by backend URL and credentials. Build
|
|
@@ -152,6 +152,5 @@ const createAuthManager = (intlayerConfig = { editor }, options = {}) => {
|
|
|
152
152
|
};
|
|
153
153
|
};
|
|
154
154
|
|
|
155
|
-
//#endregion
|
|
156
155
|
export { clearAccessTokenCache, createAuthManager };
|
|
157
156
|
//# sourceMappingURL=createAuthManager.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createAuthManager } from "./createAuthManager.mjs";
|
|
2
2
|
import { editor } from "@intlayer/config/built";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
// src/cms/createIntlayerCMS.ts
|
|
5
5
|
/**
|
|
6
6
|
* Creates an Intlayer CMS authenticator handling authentication automatically
|
|
7
7
|
* (OAuth2 `client_credentials`, or a CLI session token).
|
|
@@ -57,6 +57,5 @@ const createIntlayerCMS = (intlayerConfig = { editor }, options = {}) => createA
|
|
|
57
57
|
*/
|
|
58
58
|
const createEndpoint = (factory, options) => (cms = createIntlayerCMS()) => cms.bindSection(factory, options);
|
|
59
59
|
|
|
60
|
-
//#endregion
|
|
61
60
|
export { createEndpoint, createIntlayerCMS };
|
|
62
61
|
//# sourceMappingURL=createIntlayerCMS.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createIntlayerCMS } from "../cms/createIntlayerCMS.mjs";
|
|
2
2
|
import { dictionaryEndpoint } from "../getIntlayerAPI/dictionary.mjs";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
// src/distantDictionary/fetchDistantDictionaries.ts
|
|
5
5
|
/**
|
|
6
6
|
* Fetch distant dictionary
|
|
7
7
|
*/
|
|
@@ -16,6 +16,5 @@ const fetchDistantDictionaries = async (intlayerConfig) => {
|
|
|
16
16
|
}
|
|
17
17
|
};
|
|
18
18
|
|
|
19
|
-
//#endregion
|
|
20
19
|
export { fetchDistantDictionaries };
|
|
21
20
|
//# sourceMappingURL=fetchDistantDictionaries.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchDistantDictionaries.mjs","names":[],"sources":["../../../src/distantDictionary/fetchDistantDictionaries.ts"],"sourcesContent":["import type { DictionaryAPI } from '@intlayer/backend';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createIntlayerCMS } from '../cms/createIntlayerCMS';\nimport { dictionaryEndpoint } from '../getIntlayerAPI/dictionary';\n\n/**\n * Fetch distant dictionary\n */\nexport const fetchDistantDictionaries = async (\n intlayerConfig: IntlayerConfig\n): Promise<DictionaryAPI[] | null | undefined> => {\n try {\n const { clientId, clientSecret } = intlayerConfig.editor;\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://app.intlayer.org/project.'\n );\n }\n\n const dictionary = dictionaryEndpoint(createIntlayerCMS(intlayerConfig));\n\n // Fetch the dictionary list\n const getDictionaryResult = await dictionary.getDictionaries();\n\n const distantDictionaries = getDictionaryResult.data;\n\n return distantDictionaries;\n } catch (error) {\n console.error(error);\n return undefined;\n }\n};\n"],"mappings":";;;;;;;AAQA,MAAa,2BAA2B,OACtC,mBACgD;CAChD,IAAI;EACF,MAAM,EAAE,UAAU,iBAAiB,eAAe;EAElD,IAAI,CAAC,YAAY,CAAC,cAChB,MAAM,IAAI,MACR,wGACF;EAUF,QAF4B,MALT,mBAAmB,kBAAkB,cAAc,CAG3B,CAAC,CAAC,gBAAgB,EAEd,CAAC;CAGlD,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;EACnB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"fetchDistantDictionaries.mjs","names":[],"sources":["../../../src/distantDictionary/fetchDistantDictionaries.ts"],"sourcesContent":["import type { DictionaryAPI } from '@intlayer/backend-contract/dictionary';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createIntlayerCMS } from '../cms/createIntlayerCMS';\nimport { dictionaryEndpoint } from '../getIntlayerAPI/dictionary';\n\n/**\n * Fetch distant dictionary\n */\nexport const fetchDistantDictionaries = async (\n intlayerConfig: IntlayerConfig\n): Promise<DictionaryAPI[] | null | undefined> => {\n try {\n const { clientId, clientSecret } = intlayerConfig.editor;\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://app.intlayer.org/project.'\n );\n }\n\n const dictionary = dictionaryEndpoint(createIntlayerCMS(intlayerConfig));\n\n // Fetch the dictionary list\n const getDictionaryResult = await dictionary.getDictionaries();\n\n const distantDictionaries = getDictionaryResult.data;\n\n return distantDictionaries;\n } catch (error) {\n console.error(error);\n return undefined;\n }\n};\n"],"mappings":";;;;;;;AAQA,MAAa,2BAA2B,OACtC,mBACgD;CAChD,IAAI;EACF,MAAM,EAAE,UAAU,iBAAiB,eAAe;EAElD,IAAI,CAAC,YAAY,CAAC,cAChB,MAAM,IAAI,MACR,wGACF;EAUF,QAF4B,MALT,mBAAmB,kBAAkB,cAAc,CAG3B,CAAC,CAAC,gBAAgB,EAEd,CAAC;CAGlD,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;EACnB;CACF;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createIntlayerCMS } from "../cms/createIntlayerCMS.mjs";
|
|
2
2
|
import { dictionaryEndpoint } from "../getIntlayerAPI/dictionary.mjs";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
// src/distantDictionary/fetchDistantDictionary.ts
|
|
5
5
|
/**
|
|
6
6
|
* Fetch distant dictionary
|
|
7
7
|
*/
|
|
@@ -18,6 +18,5 @@ const fetchDistantDictionary = async (dictionaryKey, intlayerConfig) => {
|
|
|
18
18
|
}
|
|
19
19
|
};
|
|
20
20
|
|
|
21
|
-
//#endregion
|
|
22
21
|
export { fetchDistantDictionary };
|
|
23
22
|
//# sourceMappingURL=fetchDistantDictionary.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchDistantDictionary.mjs","names":[],"sources":["../../../src/distantDictionary/fetchDistantDictionary.ts"],"sourcesContent":["import type { DictionaryAPI } from '@intlayer/backend';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createIntlayerCMS } from '../cms/createIntlayerCMS';\nimport { dictionaryEndpoint } from '../getIntlayerAPI/dictionary';\n\n/**\n * Fetch distant dictionary\n */\nexport const fetchDistantDictionary = async (\n dictionaryKey: string,\n intlayerConfig: IntlayerConfig\n): Promise<DictionaryAPI | undefined> => {\n try {\n const { clientId, clientSecret } = intlayerConfig.editor;\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://app.intlayer.org/project.'\n );\n }\n\n const dictionary = dictionaryEndpoint(createIntlayerCMS(intlayerConfig));\n\n // Fetch the dictionary\n const getDictionaryResult = await dictionary.getDictionary(dictionaryKey);\n\n const distantDictionary = getDictionaryResult.data;\n\n if (!distantDictionary) {\n throw new Error(`Dictionary ${dictionaryKey} not found on remote`);\n }\n\n return distantDictionary;\n } catch (error) {\n console.error(error);\n return undefined;\n }\n};\n"],"mappings":";;;;;;;AAQA,MAAa,yBAAyB,OACpC,eACA,mBACuC;CACvC,IAAI;EACF,MAAM,EAAE,UAAU,iBAAiB,eAAe;EAElD,IAAI,CAAC,YAAY,CAAC,cAChB,MAAM,IAAI,MACR,wGACF;EAQF,MAAM,qBAAoB,MALP,mBAAmB,kBAAkB,cAAc,CAG3B,CAAC,CAAC,cAAc,aAAa,EAE3B,CAAC;EAE9C,IAAI,CAAC,mBACH,MAAM,IAAI,MAAM,cAAc,cAAc,qBAAqB;EAGnE,OAAO;CACT,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;EACnB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"fetchDistantDictionary.mjs","names":[],"sources":["../../../src/distantDictionary/fetchDistantDictionary.ts"],"sourcesContent":["import type { DictionaryAPI } from '@intlayer/backend-contract/dictionary';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createIntlayerCMS } from '../cms/createIntlayerCMS';\nimport { dictionaryEndpoint } from '../getIntlayerAPI/dictionary';\n\n/**\n * Fetch distant dictionary\n */\nexport const fetchDistantDictionary = async (\n dictionaryKey: string,\n intlayerConfig: IntlayerConfig\n): Promise<DictionaryAPI | undefined> => {\n try {\n const { clientId, clientSecret } = intlayerConfig.editor;\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://app.intlayer.org/project.'\n );\n }\n\n const dictionary = dictionaryEndpoint(createIntlayerCMS(intlayerConfig));\n\n // Fetch the dictionary\n const getDictionaryResult = await dictionary.getDictionary(dictionaryKey);\n\n const distantDictionary = getDictionaryResult.data;\n\n if (!distantDictionary) {\n throw new Error(`Dictionary ${dictionaryKey} not found on remote`);\n }\n\n return distantDictionary;\n } catch (error) {\n console.error(error);\n return undefined;\n }\n};\n"],"mappings":";;;;;;;AAQA,MAAa,yBAAyB,OACpC,eACA,mBACuC;CACvC,IAAI;EACF,MAAM,EAAE,UAAU,iBAAiB,eAAe;EAElD,IAAI,CAAC,YAAY,CAAC,cAChB,MAAM,IAAI,MACR,wGACF;EAQF,MAAM,qBAAoB,MALP,mBAAmB,kBAAkB,cAAc,CAG3B,CAAC,CAAC,cAAc,aAAa,EAE3B,CAAC;EAE9C,IAAI,CAAC,mBACH,MAAM,IAAI,MAAM,cAAc,cAAc,qBAAqB;EAGnE,OAAO;CACT,SAAS,OAAO;EACd,QAAQ,MAAM,KAAK;EACnB;CACF;AACF"}
|
package/dist/esm/fetcher.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { resolveInternalBackendUrl } from "./resolveInternalBackendUrl.mjs";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
// src/fetcher.ts
|
|
4
4
|
/**
|
|
5
5
|
* Error thrown when the backend answers with a non-ok response.
|
|
6
6
|
*
|
|
@@ -144,6 +144,5 @@ const fetcher = async (url, ...options) => {
|
|
|
144
144
|
return await response.json();
|
|
145
145
|
};
|
|
146
146
|
|
|
147
|
-
//#endregion
|
|
148
147
|
export { FetcherError, fetcher, fetcherOptions };
|
|
149
148
|
//# sourceMappingURL=fetcher.mjs.map
|
package/dist/esm/fetcher.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetcher.mjs","names":[],"sources":["../../src/fetcher.ts"],"sourcesContent":["import { resolveInternalBackendUrl } from './resolveInternalBackendUrl';\n\n/**\n * Error thrown when the backend answers with a non-ok response.\n *\n * Carries the HTTP status and the backend error code alongside the message, so\n * callers can tell a transient failure (5xx, network) from a deterministic one\n * (4xx) instead of blindly retrying.\n */\nexport class FetcherError extends Error {\n /** HTTP status code of the response. */\n public readonly status: number;\n /** Error code returned by the backend, when available (ex: `DICTIONARY_NOT_FOUND`). */\n public readonly code?: string;\n /** Raw error payload returned by the backend. */\n public readonly data?: unknown;\n\n constructor(\n message: string,\n details: { status: number; code?: string; data?: unknown }\n ) {\n super(message);\n\n this.name = 'FetcherError';\n this.status = details.status;\n this.code = details.code;\n this.data = details.data;\n }\n}\n\n/**\n * Type definition for options used in the fetcher function.\n * Extends the standard RequestInit interface (excluding 'body'),\n * and adds 'body' and 'params' properties for convenience.\n */\nexport type FetcherOptions = Omit<RequestInit, 'body'> & {\n /**\n * Body of the request. Should be a key-value pair object.\n */\n body?: Record<string, unknown>;\n /**\n * Query parameters to be appended to the URL.\n */\n params?:\n | Record
|
|
1
|
+
{"version":3,"file":"fetcher.mjs","names":[],"sources":["../../src/fetcher.ts"],"sourcesContent":["import { resolveInternalBackendUrl } from './resolveInternalBackendUrl';\n\n/**\n * Error thrown when the backend answers with a non-ok response.\n *\n * Carries the HTTP status and the backend error code alongside the message, so\n * callers can tell a transient failure (5xx, network) from a deterministic one\n * (4xx) instead of blindly retrying.\n */\nexport class FetcherError extends Error {\n /** HTTP status code of the response. */\n public readonly status: number;\n /** Error code returned by the backend, when available (ex: `DICTIONARY_NOT_FOUND`). */\n public readonly code?: string;\n /** Raw error payload returned by the backend. */\n public readonly data?: unknown;\n\n constructor(\n message: string,\n details: { status: number; code?: string; data?: unknown }\n ) {\n super(message);\n\n this.name = 'FetcherError';\n this.status = details.status;\n this.code = details.code;\n this.data = details.data;\n }\n}\n\n/**\n * Type definition for options used in the fetcher function.\n * Extends the standard RequestInit interface (excluding 'body'),\n * and adds 'body' and 'params' properties for convenience.\n */\nexport type FetcherOptions = Omit<RequestInit, 'body'> & {\n /**\n * Body of the request. Should be a key-value pair object.\n */\n body?: Record<string, unknown>;\n /**\n * Query parameters to be appended to the URL.\n */\n params?:\n | Record<\n string,\n string | number | boolean | (string | number)[] | undefined\n >\n | string[]\n | URLSearchParams;\n};\n\n/**\n * Default options for the fetcher function.\n * Sets the default method to 'GET', the 'Content-Type' header to 'application/json',\n * and includes credentials in the request.\n */\nexport const fetcherOptions: FetcherOptions = {\n method: 'GET', // Default HTTP method\n headers: {\n 'Content-Type': 'application/json', // Default content type\n },\n credentials: 'include',\n};\n\n/**\n * Utility function to remove properties with undefined values from an object.\n * This helps prevent sending undefined values in the request options.\n *\n * @param obj - The object to clean.\n * @returns The cleaned object without undefined values.\n */\nconst removeUndefined = (obj: object) => {\n Object.keys(obj).forEach((key) => {\n if (obj[key as keyof typeof obj] === undefined) {\n delete obj[key as keyof typeof obj];\n }\n });\n return obj;\n};\n\n/**\n * Deeply merges an array of objects into a single object.\n * Later objects in the array overwrite properties of earlier ones.\n *\n * @template T - The type of objects being merged.\n * @param objects - An array of objects to merge.\n * @returns The merged object.\n */\nconst deepMerge = <T extends object>(objects: (T | undefined)[]): T =>\n objects.reduce((acc, obj) => {\n const acc1: T = (acc ?? {}) as T;\n const obj1: T = removeUndefined(obj ?? {}) as T;\n\n if (typeof acc1 === 'object' && typeof obj1 === 'object') {\n // Merge the two objects\n return { ...acc1, ...obj1 };\n }\n\n // If one of them is not an object, return the defined one\n return obj1 ?? acc1;\n }, {} as T)!;\n\n/**\n * Fetcher function to make HTTP requests.\n * It merges default options with user-provided options,\n * handles query parameters and request body,\n * and returns the parsed JSON response.\n *\n * @template T - The expected type of the response data.\n * @param url - The endpoint URL.\n * @param options - Additional options to customize the request.\n * @returns A promise that resolves with the response data of type T.\n *\n * @example\n * ```typescript\n * // Making a GET request with query parameters\n * const data = await fetcher<MyResponseType>('https://api.example.com/data', {\n * params: { search: 'query' },\n * });\n *\n * // Making a POST request with a JSON body\n * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {\n * method: 'POST',\n * body: { key: 'value' },\n * });\n *\n * // Merge body, headers, and params\n * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {\n * method: 'POST',\n * body: { key: 'value' },\n * headers: { 'Content-Type': 'application/json' },\n * params: { search: 'query' },\n * },\n * {\n * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n * params: { page: 1 },\n * });\n * ```\n *\n * Result:\n * ```typescript\n * {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n * params: { page: 1, search: 'query' },\n * body: { key: 'value' },\n * }\n * ```\n */\nexport const fetcher = async <T>(\n url: string,\n ...options: FetcherOptions[]\n): Promise<T> => {\n const { signal } = new AbortController();\n\n // Initialize query parameters string and request body string\n let paramsString = '';\n let bodyString: string | undefined;\n\n // Extract other options excluding 'body', 'params', and 'headers'\n const otherOptions = options.map(\n ({ body, params, headers, ...otherOptions }) => otherOptions\n );\n\n // Merge default options with user-provided options\n const mergedOptions = deepMerge([fetcherOptions, ...otherOptions]);\n\n // Merge default headers with user-provided headers\n const mergedHeaders = deepMerge([\n fetcherOptions.headers,\n ...options.map((option) => option.headers),\n ]);\n\n // Merge query parameters\n const params = deepMerge(options.map((option) => option.params));\n\n const method = mergedOptions.method;\n\n // If the request method is not 'GET' or 'HEAD', prepare the request body\n if (method !== 'GET' && method !== 'HEAD') {\n // Merge all 'body' options\n const body = deepMerge(options.map((option) => option.body));\n if (\n mergedHeaders?.['Content-Type' as keyof HeadersInit] ===\n 'application/x-www-form-urlencoded'\n ) {\n // If the content type is 'application/x-www-form-urlencoded', encode the body accordingly\n bodyString = new URLSearchParams(\n body as Record<string, string>\n ).toString();\n } else {\n // Otherwise, stringify the body as JSON\n bodyString = JSON.stringify(body);\n }\n }\n\n // If there are query parameters, append them to the URL\n if (Object.entries(params).length > 0) {\n paramsString = `?${new URLSearchParams(\n params as Record<string, string>\n ).toString()}`;\n }\n\n // Prepare the final request options\n const formattedOptions: RequestInit = {\n ...mergedOptions,\n headers: mergedHeaders,\n body: bodyString,\n signal,\n };\n\n // Construct the full URL with query parameters. Server code inside a private\n // network may need to reach the backend under another origin — see\n // `resolveInternalBackendUrl`.\n const urlResult = resolveInternalBackendUrl(`${url}${paramsString}`);\n\n // Make the HTTP request using fetch\n const response = await fetch(urlResult, formattedOptions);\n\n if (!response.ok) {\n const result = await response.json().catch(() => undefined);\n\n // You can customize the error message or include more details\n throw new FetcherError(\n JSON.stringify(result?.error) ?? 'An error occurred',\n {\n status: response.status,\n code: result?.error?.code,\n data: result?.error,\n }\n );\n }\n return await response.json();\n};\n"],"mappings":";;;;;;;;;;AASA,IAAa,eAAb,cAAkC,MAAM;;CAEtC,AAAgB;;CAEhB,AAAgB;;CAEhB,AAAgB;CAEhB,YACE,SACA,SACA;EACA,MAAM,OAAO;EAEb,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;EACtB,KAAK,OAAO,QAAQ;EACpB,KAAK,OAAO,QAAQ;CACtB;AACF;;;;;;AA6BA,MAAa,iBAAiC;CAC5C,QAAQ;CACR,SAAS,EACP,gBAAgB,mBAClB;CACA,aAAa;AACf;;;;;;;;AASA,MAAM,mBAAmB,QAAgB;CACvC,OAAO,KAAK,GAAG,CAAC,CAAC,SAAS,QAAQ;EAChC,IAAI,IAAI,SAA6B,QACnC,OAAO,IAAI;CAEf,CAAC;CACD,OAAO;AACT;;;;;;;;;AAUA,MAAM,aAA+B,YACnC,QAAQ,QAAQ,KAAK,QAAQ;CAC3B,MAAM,OAAW,OAAO,CAAC;CACzB,MAAM,OAAU,gBAAgB,OAAO,CAAC,CAAC;CAEzC,IAAI,OAAO,SAAS,YAAY,OAAO,SAAS,UAE9C,OAAO;EAAE,GAAG;EAAM,GAAG;CAAK;CAI5B,OAAO,QAAQ;AACjB,GAAG,CAAC,CAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDZ,MAAa,UAAU,OACrB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} from "../cms/createIntlayerCMS.mjs";
|
|
2
|
+
import { fetcher } from "../fetcher.mjs";
|
|
3
3
|
import { editor } from "@intlayer/config/built";
|
|
4
|
+
import { buildRouteURL } from "@intlayer/backend-contract/defineRoute";
|
|
5
|
+
import { BACKEND_URL } from "@intlayer/config/defaultValues";
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
// src/getIntlayerAPI/ai.ts
|
|
8
|
+
/** Prefix of the routes, checked against the backend contract. */
|
|
9
|
+
const aiGroup = { prefix: "/api/ai" };
|
|
10
|
+
/**
|
|
11
|
+
* Method and path of every route, checked against the backend contract at
|
|
12
|
+
* compile time (the contract's zod schemas are never loaded).
|
|
13
|
+
*/
|
|
14
|
+
const aiEndpoints = {
|
|
15
|
+
customQuery: {
|
|
16
|
+
method: "POST",
|
|
17
|
+
path: "/"
|
|
18
|
+
},
|
|
19
|
+
translateJSON: {
|
|
20
|
+
method: "POST",
|
|
21
|
+
path: "/translate/json"
|
|
22
|
+
},
|
|
23
|
+
auditContentDeclaration: {
|
|
24
|
+
method: "POST",
|
|
25
|
+
path: "/audit/dictionary"
|
|
26
|
+
},
|
|
27
|
+
auditContentDeclarationField: {
|
|
28
|
+
method: "POST",
|
|
29
|
+
path: "/audit/dictionary/field"
|
|
30
|
+
},
|
|
31
|
+
auditContentDeclarationMetadata: {
|
|
32
|
+
method: "POST",
|
|
33
|
+
path: "/audit/dictionary/metadata"
|
|
34
|
+
},
|
|
35
|
+
auditTag: {
|
|
36
|
+
method: "POST",
|
|
37
|
+
path: "/audit/tag"
|
|
38
|
+
},
|
|
39
|
+
ask: {
|
|
40
|
+
method: "POST",
|
|
41
|
+
path: "/ask"
|
|
42
|
+
},
|
|
43
|
+
chat: {
|
|
44
|
+
method: "POST",
|
|
45
|
+
path: "/chat"
|
|
46
|
+
},
|
|
47
|
+
autocomplete: {
|
|
48
|
+
method: "POST",
|
|
49
|
+
path: "/autocomplete"
|
|
50
|
+
},
|
|
51
|
+
getDiscussions: {
|
|
52
|
+
method: "GET",
|
|
53
|
+
path: "/discussions"
|
|
54
|
+
},
|
|
55
|
+
getAIStats: {
|
|
56
|
+
method: "GET",
|
|
57
|
+
path: "/stats"
|
|
58
|
+
}
|
|
59
|
+
};
|
|
6
60
|
const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
7
|
-
const
|
|
61
|
+
const backendURL = intlayerConfig?.editor?.backendURL ?? editor.backendURL ?? BACKEND_URL;
|
|
8
62
|
/**
|
|
9
63
|
* Custom query
|
|
10
64
|
* @param body - Custom query parameters.
|
|
11
65
|
* @returns Custom query result.
|
|
12
66
|
*/
|
|
13
|
-
const customQuery = async (body, otherOptions = {}) => await fetcher(
|
|
14
|
-
method:
|
|
67
|
+
const customQuery = async (body, otherOptions = {}) => await fetcher(buildRouteURL(backendURL, aiGroup, aiEndpoints.customQuery), authAPIOptions, otherOptions, {
|
|
68
|
+
method: aiEndpoints.customQuery.method,
|
|
15
69
|
body
|
|
16
70
|
});
|
|
17
71
|
/**
|
|
@@ -19,8 +73,8 @@ const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
19
73
|
* @param body - Audit file parameters.
|
|
20
74
|
* @returns Audited file content.
|
|
21
75
|
*/
|
|
22
|
-
const translateJSON = async (body, otherOptions = {}) => await fetcher(
|
|
23
|
-
method:
|
|
76
|
+
const translateJSON = async (body, otherOptions = {}) => await fetcher(buildRouteURL(backendURL, aiGroup, aiEndpoints.translateJSON), authAPIOptions, otherOptions, {
|
|
77
|
+
method: aiEndpoints.translateJSON.method,
|
|
24
78
|
body
|
|
25
79
|
});
|
|
26
80
|
/**
|
|
@@ -28,8 +82,8 @@ const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
28
82
|
* @param body - Audit file parameters.
|
|
29
83
|
* @returns Audited file content.
|
|
30
84
|
*/
|
|
31
|
-
const auditContentDeclaration = async (body, otherOptions = {}) => await fetcher(
|
|
32
|
-
method:
|
|
85
|
+
const auditContentDeclaration = async (body, otherOptions = {}) => await fetcher(buildRouteURL(backendURL, aiGroup, aiEndpoints.auditContentDeclaration), authAPIOptions, otherOptions, {
|
|
86
|
+
method: aiEndpoints.auditContentDeclaration.method,
|
|
33
87
|
body
|
|
34
88
|
});
|
|
35
89
|
/**
|
|
@@ -37,8 +91,8 @@ const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
37
91
|
* @param body - Audit file parameters.
|
|
38
92
|
* @returns Audited file content.
|
|
39
93
|
*/
|
|
40
|
-
const auditContentDeclarationField = async (body, otherOptions = {}) => await fetcher(
|
|
41
|
-
method:
|
|
94
|
+
const auditContentDeclarationField = async (body, otherOptions = {}) => await fetcher(buildRouteURL(backendURL, aiGroup, aiEndpoints.auditContentDeclarationField), authAPIOptions, otherOptions, {
|
|
95
|
+
method: aiEndpoints.auditContentDeclarationField.method,
|
|
42
96
|
body
|
|
43
97
|
});
|
|
44
98
|
/**
|
|
@@ -46,8 +100,8 @@ const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
46
100
|
* @param body - Audit file parameters.
|
|
47
101
|
* @returns Audited file content.
|
|
48
102
|
*/
|
|
49
|
-
const auditContentDeclarationMetadata = async (body, otherOptions = {}) => await fetcher(
|
|
50
|
-
method:
|
|
103
|
+
const auditContentDeclarationMetadata = async (body, otherOptions = {}) => await fetcher(buildRouteURL(backendURL, aiGroup, aiEndpoints.auditContentDeclarationMetadata), authAPIOptions, otherOptions, {
|
|
104
|
+
method: aiEndpoints.auditContentDeclarationMetadata.method,
|
|
51
105
|
body
|
|
52
106
|
});
|
|
53
107
|
/**
|
|
@@ -55,8 +109,8 @@ const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
55
109
|
* @param body - Audit tag parameters.
|
|
56
110
|
* @returns Audited tag content.
|
|
57
111
|
*/
|
|
58
|
-
const auditTag = async (body, otherOptions = {}) => await fetcher(
|
|
59
|
-
method:
|
|
112
|
+
const auditTag = async (body, otherOptions = {}) => await fetcher(buildRouteURL(backendURL, aiGroup, aiEndpoints.auditTag), authAPIOptions, otherOptions, {
|
|
113
|
+
method: aiEndpoints.auditTag.method,
|
|
60
114
|
body
|
|
61
115
|
});
|
|
62
116
|
/**
|
|
@@ -83,8 +137,8 @@ const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
83
137
|
const { onMessage, onDone, ...rest } = body;
|
|
84
138
|
const abortController = new AbortController();
|
|
85
139
|
try {
|
|
86
|
-
const response = await fetch(
|
|
87
|
-
method:
|
|
140
|
+
const response = await fetch(buildRouteURL(backendURL, aiGroup, aiEndpoints.ask), {
|
|
141
|
+
method: aiEndpoints.ask.method,
|
|
88
142
|
headers: {
|
|
89
143
|
"Content-Type": "application/json",
|
|
90
144
|
...authAPIOptions.headers,
|
|
@@ -140,8 +194,8 @@ const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
140
194
|
const { onMessage, onDone, onAction, ...rest } = body;
|
|
141
195
|
const abortController = new AbortController();
|
|
142
196
|
try {
|
|
143
|
-
const response = await fetch(
|
|
144
|
-
method:
|
|
197
|
+
const response = await fetch(buildRouteURL(backendURL, aiGroup, aiEndpoints.chat), {
|
|
198
|
+
method: aiEndpoints.chat.method,
|
|
145
199
|
headers: {
|
|
146
200
|
"Content-Type": "application/json",
|
|
147
201
|
...authAPIOptions.headers,
|
|
@@ -193,22 +247,22 @@ const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
193
247
|
throw error;
|
|
194
248
|
}
|
|
195
249
|
};
|
|
196
|
-
const autocomplete = async (body, otherOptions = {}) => await fetcher(
|
|
197
|
-
method:
|
|
250
|
+
const autocomplete = async (body, otherOptions = {}) => await fetcher(buildRouteURL(backendURL, aiGroup, aiEndpoints.autocomplete), authAPIOptions, otherOptions, {
|
|
251
|
+
method: aiEndpoints.autocomplete.method,
|
|
198
252
|
body
|
|
199
253
|
});
|
|
200
254
|
/**
|
|
201
255
|
* Retrieves discussions with filters and pagination. Only user or admin can access.
|
|
202
256
|
*/
|
|
203
|
-
const getDiscussions = async (params, otherOptions = {}) => await fetcher(
|
|
204
|
-
method:
|
|
257
|
+
const getDiscussions = async (params, otherOptions = {}) => await fetcher(buildRouteURL(backendURL, aiGroup, aiEndpoints.getDiscussions), authAPIOptions, otherOptions, {
|
|
258
|
+
method: aiEndpoints.getDiscussions.method,
|
|
205
259
|
params
|
|
206
260
|
});
|
|
207
261
|
/**
|
|
208
262
|
* Retrieves aggregated AI token-usage statistics for the currently selected
|
|
209
263
|
* project.
|
|
210
264
|
*/
|
|
211
|
-
const getAIStats = async (otherOptions = {}) => await fetcher(
|
|
265
|
+
const getAIStats = async (otherOptions = {}) => await fetcher(buildRouteURL(backendURL, aiGroup, aiEndpoints.getAIStats), authAPIOptions, otherOptions, { method: aiEndpoints.getAIStats.method });
|
|
212
266
|
return {
|
|
213
267
|
customQuery,
|
|
214
268
|
translateJSON,
|
|
@@ -231,6 +285,5 @@ const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
231
285
|
*/
|
|
232
286
|
const aiEndpoint = createEndpoint(getAiAPI);
|
|
233
287
|
|
|
234
|
-
//#endregion
|
|
235
288
|
export { aiEndpoint, getAiAPI };
|
|
236
289
|
//# sourceMappingURL=ai.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai.mjs","names":[],"sources":["../../../src/getIntlayerAPI/ai.ts"],"sourcesContent":["import type {\n AIOptions,\n AskDocQuestionResult,\n AuditContentDeclarationBody,\n AuditContentDeclarationFieldBody,\n AuditContentDeclarationFieldResult,\n AuditContentDeclarationMetadataBody,\n AuditContentDeclarationMetadataResult,\n AuditContentDeclarationResult,\n AuditTagBody,\n AuditTagResult,\n AutocompleteResponse,\n ChatCompletionRequestMessage,\n ChatResult,\n CustomQueryBody,\n CustomQueryResult,\n GetAIStatsResult,\n GetDiscussionsParams,\n GetDiscussionsResult,\n TranslateJSONBody,\n TranslateJSONResult,\n} from '@intlayer/backend';\nimport { editor } from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createEndpoint } from '../cms/createIntlayerCMS';\nimport { type FetcherOptions, fetcher } from '../fetcher';\n\nexport type AutocompleteBody = {\n text: string;\n aiOptions?: AIOptions;\n contextBefore?: string;\n currentLine?: string;\n contextAfter?: string;\n};\n\nexport type AskDocQuestionBody = {\n messages: ChatCompletionRequestMessage[];\n discussionId: string;\n onMessage?: (chunk: string) => void;\n onDone?: (response: AskDocQuestionResult) => void;\n};\n\nexport type ClientAction =\n | { type: 'navigate'; path: string }\n | { type: 'invalidate_queries' };\n\nexport type ChatBody = {\n messages: ChatCompletionRequestMessage[];\n discussionId: string;\n onMessage?: (chunk: string) => void;\n onDone?: (response: ChatResult) => void;\n onAction?: (action: ClientAction) => void;\n};\n\nexport type { AskDocQuestionResult, ChatResult };\n\nexport const getAiAPI = (\n authAPIOptions: FetcherOptions = {},\n intlayerConfig?: IntlayerConfig\n) => {\n const backendURL = intlayerConfig?.editor?.backendURL ?? editor.backendURL;\n\n const AI_API_ROUTE = `${backendURL}/api/ai`;\n\n /**\n * Custom query\n * @param body - Custom query parameters.\n * @returns Custom query result.\n */\n const customQuery = async (\n body?: CustomQueryBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<CustomQueryResult>(\n AI_API_ROUTE,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body: body,\n }\n );\n\n /**\n * Translate a JSON\n * @param body - Audit file parameters.\n * @returns Audited file content.\n */\n const translateJSON = async (\n body?: TranslateJSONBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<TranslateJSONResult>(\n `${AI_API_ROUTE}/translate/json`,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body: body,\n }\n );\n\n /**\n * Audits a content declaration file\n * @param body - Audit file parameters.\n * @returns Audited file content.\n */\n const auditContentDeclaration = async (\n body?: AuditContentDeclarationBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AuditContentDeclarationResult>(\n `${AI_API_ROUTE}/audit/dictionary`,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body: body,\n }\n );\n\n /**\n * Audits a content declaration field\n * @param body - Audit file parameters.\n * @returns Audited file content.\n */\n const auditContentDeclarationField = async (\n body?: AuditContentDeclarationFieldBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AuditContentDeclarationFieldResult>(\n `${AI_API_ROUTE}/audit/dictionary/field`,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body: body,\n }\n );\n\n /**\n * Audits a content declaration file to retrieve title, description and tags\n * @param body - Audit file parameters.\n * @returns Audited file content.\n */\n const auditContentDeclarationMetadata = async (\n body?: AuditContentDeclarationMetadataBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AuditContentDeclarationMetadataResult>(\n `${AI_API_ROUTE}/audit/dictionary/metadata`,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body: body,\n }\n );\n\n /**\n * Audits a tag\n * @param body - Audit tag parameters.\n * @returns Audited tag content.\n */\n const auditTag = async (\n body?: AuditTagBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AuditTagResult>(\n `${AI_API_ROUTE}/audit/tag`,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body: body,\n }\n );\n\n /**\n * Asks a question to the AI related to the documentation **and streams the\n * answer as Server‑Sent Events (SSE)**.\n *\n * The function **returns immediately** with a handle exposing:\n * - `promise` → resolves when the stream completes (or rejects on error)\n * - `abort()` → allows canceling the request on demand\n *\n * Usage example:\n * ```ts\n * const { promise, abort } = ai.askDocQuestion({\n * ...body,\n * onMessage: console.log,\n * onDone: (full) => console.log(\"✔\", full),\n * });\n * // later → abort();\n * await promise; // waits for completion if desired\n * ```\n */\n const askDocQuestion = async (\n body?: AskDocQuestionBody,\n otherOptions: FetcherOptions = {}\n ) => {\n if (!body) return;\n\n const { onMessage, onDone, ...rest } = body;\n const abortController = new AbortController();\n\n try {\n const response = await fetch(`${AI_API_ROUTE}/ask`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...authAPIOptions.headers,\n ...otherOptions.headers,\n },\n body: JSON.stringify({\n ...rest,\n ...authAPIOptions.body,\n ...otherOptions.body,\n }),\n signal: abortController.signal,\n credentials: 'include',\n });\n\n if (!response.ok) {\n // Align error handling with generic `fetcher` utility so that callers receive\n // meaningful messages (e.g. for 429 \"Too Many Requests\" responses).\n let errorMessage: string = 'An error occurred';\n\n try {\n // Attempt to parse JSON error payload produced by backend\n const errorData = await response.json();\n const errorObj = errorData.error ?? errorData;\n errorMessage = JSON.stringify(errorObj) ?? 'An error occurred';\n } catch {\n // Fallback to plain-text body or HTTP status text\n try {\n const errorText = await response.text();\n if (errorText) {\n errorMessage = errorText;\n }\n } catch {\n // ignore – we already have a default message\n }\n }\n\n throw new Error(errorMessage);\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n throw new Error('No reader available');\n }\n\n const decoder = new TextDecoder();\n let buffer = '';\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.startsWith('data: ')) {\n try {\n const data = JSON.parse(line.slice(6));\n if (data.chunk) {\n onMessage?.(data.chunk);\n }\n if (data.done && data.response) {\n onDone?.(data.response);\n }\n } catch (e) {\n console.error('Failed to parse SSE data:', e);\n }\n }\n }\n }\n } catch (error) {\n console.error('Error in askDocQuestion:', error);\n throw error;\n }\n };\n\n const chat = async (body?: ChatBody, otherOptions: FetcherOptions = {}) => {\n if (!body) return;\n\n const { onMessage, onDone, onAction, ...rest } = body;\n const abortController = new AbortController();\n\n try {\n const response = await fetch(`${AI_API_ROUTE}/chat`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...authAPIOptions.headers,\n ...otherOptions.headers,\n },\n body: JSON.stringify({\n ...rest,\n ...authAPIOptions.body,\n ...otherOptions.body,\n }),\n signal: abortController.signal,\n credentials: 'include',\n });\n\n if (!response.ok) {\n let errorMessage: string = 'An error occurred';\n\n try {\n const errorData = await response.json();\n const errorObj = errorData.error ?? errorData;\n errorMessage = JSON.stringify(errorObj) ?? 'An error occurred';\n } catch {\n try {\n const errorText = await response.text();\n if (errorText) {\n errorMessage = errorText;\n }\n } catch {\n // ignore\n }\n }\n\n throw new Error(errorMessage);\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n throw new Error('No reader available');\n }\n\n const decoder = new TextDecoder();\n let buffer = '';\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.startsWith('data: ')) {\n try {\n const data = JSON.parse(line.slice(6));\n if (data.chunk) {\n onMessage?.(data.chunk);\n }\n if (data.action) {\n onAction?.(data.action);\n }\n if (data.done && data.response) {\n onDone?.(data.response);\n }\n } catch (e) {\n console.error('Failed to parse SSE data:', e);\n }\n }\n }\n }\n } catch (error) {\n console.error('Error in chat:', error);\n throw error;\n }\n };\n\n const autocomplete = async (\n body?: AutocompleteBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AutocompleteResponse>(\n `${AI_API_ROUTE}/autocomplete`,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body: body,\n }\n );\n\n /**\n * Retrieves discussions with filters and pagination. Only user or admin can access.\n */\n const getDiscussions = async (\n params?: GetDiscussionsParams,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDiscussionsResult>(\n `${AI_API_ROUTE}/discussions`,\n authAPIOptions,\n otherOptions,\n {\n method: 'GET',\n // @ts-ignore Number of parameter will be stringified by the fetcher\n params,\n }\n );\n\n /**\n * Retrieves aggregated AI token-usage statistics for the currently selected\n * project.\n */\n const getAIStats = async (otherOptions: FetcherOptions = {}) =>\n await fetcher<GetAIStatsResult>(\n `${AI_API_ROUTE}/stats`,\n authAPIOptions,\n otherOptions,\n {\n method: 'GET',\n }\n );\n\n return {\n customQuery,\n translateJSON,\n auditContentDeclaration,\n auditContentDeclarationField,\n auditContentDeclarationMetadata,\n auditTag,\n askDocQuestion,\n chat,\n autocomplete,\n getDiscussions,\n getAIStats,\n };\n};\n\n/**\n * Authenticated `ai` endpoint bound to an Intlayer CMS authenticator.\n *\n * Pass an authenticator created with `createIntlayerCMS`, or omit it to use\n * the build-time configuration (`@intlayer/config/built`).\n */\nexport const aiEndpoint = createEndpoint(getAiAPI);\n"],"mappings":";;;;;AAwDA,MAAa,YACX,iBAAiC,CAAC,GAClC,mBACG;CAGH,MAAM,eAAe,GAFF,gBAAgB,QAAQ,cAAc,OAAO,WAE7B;;;;;;CAOnC,MAAM,cAAc,OAClB,MACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,cACA,gBACA,cACA;EACE,QAAQ;EACF;CACR,CACF;;;;;;CAOF,MAAM,gBAAgB,OACpB,MACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,aAAa,kBAChB,gBACA,cACA;EACE,QAAQ;EACF;CACR,CACF;;;;;;CAOF,MAAM,0BAA0B,OAC9B,MACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,aAAa,oBAChB,gBACA,cACA;EACE,QAAQ;EACF;CACR,CACF;;;;;;CAOF,MAAM,+BAA+B,OACnC,MACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,aAAa,0BAChB,gBACA,cACA;EACE,QAAQ;EACF;CACR,CACF;;;;;;CAOF,MAAM,kCAAkC,OACtC,MACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,aAAa,6BAChB,gBACA,cACA;EACE,QAAQ;EACF;CACR,CACF;;;;;;CAOF,MAAM,WAAW,OACf,MACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,aAAa,aAChB,gBACA,cACA;EACE,QAAQ;EACF;CACR,CACF;;;;;;;;;;;;;;;;;;;;CAqBF,MAAM,iBAAiB,OACrB,MAC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M,IAAI,KAAK;IAExB,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,WAAW,QAAQ,GAC1B,IAAI;KACF,MAAM,OAAO,KAAK,MAAM,KAAK,MAAM,CAAC,CAAC;KACrC,IAAI,KAAK,OACP,YAAY,KAAK,KAAK;KAExB,IAAI,KAAK,QACP,WAAW,KAAK,MAAM;KAExB,IAAI,KAAK,QAAQ,KAAK,UACpB,SAAS,KAAK,QAAQ;IAE1B,SAAS,GAAG;KACV,QAAQ,MAAM,6BAA6B,CAAC;IAC9C;GAGN;EACF,SAAS,OAAO;GACd,QAAQ,MAAM,kBAAkB,KAAK;GACrC,MAAM;EACR;CACF;CAEA,MAAM,eAAe,OACnB,MACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,aAAa,gBAChB,gBACA,cACA;EACE,QAAQ;EACF;CACR,CACF;;;;CAKF,MAAM,iBAAiB,OACrB,QACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,GAAG,aAAa,eAChB,gBACA,cACA;EACE,QAAQ;EAER;CACF,CACF;;;;;CAMF,MAAM,aAAa,OAAO,eAA+B,CAAC,MACxD,MAAM,QACJ,GAAG,aAAa,SAChB,gBACA,cACA,EACE,QAAQ,MACV,CACF;CAEF,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;;;;;;;AAQA,MAAa,aAAa,eAAe,QAAQ"}
|
|
1
|
+
{"version":3,"file":"ai.mjs","names":[],"sources":["../../../src/getIntlayerAPI/ai.ts"],"sourcesContent":["import type {\n AIOptions,\n AIRoutes,\n AskDocQuestionResult,\n AuditContentDeclarationBody,\n AuditContentDeclarationFieldBody,\n AuditContentDeclarationFieldResult,\n AuditContentDeclarationMetadataBody,\n AuditContentDeclarationMetadataResult,\n AuditContentDeclarationResult,\n AuditTagBody,\n AuditTagResult,\n AutocompleteResponse,\n aiContract,\n ChatCompletionRequestMessage,\n ChatResult,\n CustomQueryBody,\n CustomQueryResult,\n GetAIStatsResult,\n GetDiscussionsParams,\n GetDiscussionsResult,\n TranslateJSONBody,\n TranslateJSONResult,\n} from '@intlayer/backend-contract/ai';\nimport type { RouteEndpoints } from '@intlayer/backend-contract/defineRoute';\nimport { buildRouteURL } from '@intlayer/backend-contract/defineRoute';\nimport { editor } from '@intlayer/config/built';\nimport { BACKEND_URL } from '@intlayer/config/defaultValues';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { createEndpoint } from '../cms/createIntlayerCMS';\nimport { type FetcherOptions, fetcher } from '../fetcher';\n\nexport type AutocompleteBody = {\n text: string;\n aiOptions?: AIOptions;\n contextBefore?: string;\n currentLine?: string;\n contextAfter?: string;\n};\n\nexport type AskDocQuestionBody = {\n messages: ChatCompletionRequestMessage[];\n discussionId: string;\n onMessage?: (chunk: string) => void;\n onDone?: (response: AskDocQuestionResult) => void;\n};\n\nexport type ClientAction =\n | { type: 'navigate'; path: string }\n | { type: 'invalidate_queries' };\n\nexport type ChatBody = {\n messages: ChatCompletionRequestMessage[];\n discussionId: string;\n onMessage?: (chunk: string) => void;\n onDone?: (response: ChatResult) => void;\n onAction?: (action: ClientAction) => void;\n};\n\nexport type { AskDocQuestionResult, ChatResult };\n\n/** Prefix of the routes, checked against the backend contract. */\nconst aiGroup = {\n prefix: '/api/ai',\n} as const satisfies Pick<typeof aiContract, 'prefix'>;\n\n/**\n * Method and path of every route, checked against the backend contract at\n * compile time (the contract's zod schemas are never loaded).\n */\nconst aiEndpoints = {\n customQuery: { method: 'POST', path: '/' },\n translateJSON: { method: 'POST', path: '/translate/json' },\n auditContentDeclaration: { method: 'POST', path: '/audit/dictionary' },\n auditContentDeclarationField: {\n method: 'POST',\n path: '/audit/dictionary/field',\n },\n auditContentDeclarationMetadata: {\n method: 'POST',\n path: '/audit/dictionary/metadata',\n },\n auditTag: { method: 'POST', path: '/audit/tag' },\n ask: { method: 'POST', path: '/ask' },\n chat: { method: 'POST', path: '/chat' },\n autocomplete: { method: 'POST', path: '/autocomplete' },\n getDiscussions: { method: 'GET', path: '/discussions' },\n getAIStats: { method: 'GET', path: '/stats' },\n} as const satisfies RouteEndpoints<AIRoutes>;\n\nexport const getAiAPI = (\n authAPIOptions: FetcherOptions = {},\n intlayerConfig?: IntlayerConfig\n) => {\n const backendURL =\n intlayerConfig?.editor?.backendURL ?? editor.backendURL ?? BACKEND_URL;\n\n /**\n * Custom query\n * @param body - Custom query parameters.\n * @returns Custom query result.\n */\n const customQuery = async (\n body?: CustomQueryBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<CustomQueryResult>(\n buildRouteURL(backendURL, aiGroup, aiEndpoints.customQuery),\n authAPIOptions,\n otherOptions,\n {\n method: aiEndpoints.customQuery.method,\n body: body,\n }\n );\n\n /**\n * Translate a JSON\n * @param body - Audit file parameters.\n * @returns Audited file content.\n */\n const translateJSON = async (\n body?: TranslateJSONBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<TranslateJSONResult>(\n buildRouteURL(backendURL, aiGroup, aiEndpoints.translateJSON),\n authAPIOptions,\n otherOptions,\n {\n method: aiEndpoints.translateJSON.method,\n body: body,\n }\n );\n\n /**\n * Audits a content declaration file\n * @param body - Audit file parameters.\n * @returns Audited file content.\n */\n const auditContentDeclaration = async (\n body?: AuditContentDeclarationBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AuditContentDeclarationResult>(\n buildRouteURL(backendURL, aiGroup, aiEndpoints.auditContentDeclaration),\n authAPIOptions,\n otherOptions,\n {\n method: aiEndpoints.auditContentDeclaration.method,\n body: body,\n }\n );\n\n /**\n * Audits a content declaration field\n * @param body - Audit file parameters.\n * @returns Audited file content.\n */\n const auditContentDeclarationField = async (\n body?: AuditContentDeclarationFieldBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AuditContentDeclarationFieldResult>(\n buildRouteURL(\n backendURL,\n aiGroup,\n aiEndpoints.auditContentDeclarationField\n ),\n authAPIOptions,\n otherOptions,\n {\n method: aiEndpoints.auditContentDeclarationField.method,\n body: body,\n }\n );\n\n /**\n * Audits a content declaration file to retrieve title, description and tags\n * @param body - Audit file parameters.\n * @returns Audited file content.\n */\n const auditContentDeclarationMetadata = async (\n body?: AuditContentDeclarationMetadataBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AuditContentDeclarationMetadataResult>(\n buildRouteURL(\n backendURL,\n aiGroup,\n aiEndpoints.auditContentDeclarationMetadata\n ),\n authAPIOptions,\n otherOptions,\n {\n method: aiEndpoints.auditContentDeclarationMetadata.method,\n body: body,\n }\n );\n\n /**\n * Audits a tag\n * @param body - Audit tag parameters.\n * @returns Audited tag content.\n */\n const auditTag = async (\n body?: AuditTagBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AuditTagResult>(\n buildRouteURL(backendURL, aiGroup, aiEndpoints.auditTag),\n authAPIOptions,\n otherOptions,\n {\n method: aiEndpoints.auditTag.method,\n body: body,\n }\n );\n\n /**\n * Asks a question to the AI related to the documentation **and streams the\n * answer as Server‑Sent Events (SSE)**.\n *\n * The function **returns immediately** with a handle exposing:\n * - `promise` → resolves when the stream completes (or rejects on error)\n * - `abort()` → allows canceling the request on demand\n *\n * Usage example:\n * ```ts\n * const { promise, abort } = ai.askDocQuestion({\n * ...body,\n * onMessage: console.log,\n * onDone: (full) => console.log(\"✔\", full),\n * });\n * // later → abort();\n * await promise; // waits for completion if desired\n * ```\n */\n const askDocQuestion = async (\n body?: AskDocQuestionBody,\n otherOptions: FetcherOptions = {}\n ) => {\n if (!body) return;\n\n const { onMessage, onDone, ...rest } = body;\n const abortController = new AbortController();\n\n try {\n const response = await fetch(\n buildRouteURL(backendURL, aiGroup, aiEndpoints.ask),\n {\n method: aiEndpoints.ask.method,\n headers: {\n 'Content-Type': 'application/json',\n ...authAPIOptions.headers,\n ...otherOptions.headers,\n },\n body: JSON.stringify({\n ...rest,\n ...authAPIOptions.body,\n ...otherOptions.body,\n }),\n signal: abortController.signal,\n credentials: 'include',\n }\n );\n\n if (!response.ok) {\n // Align error handling with generic `fetcher` utility so that callers receive\n // meaningful messages (e.g. for 429 \"Too Many Requests\" responses).\n let errorMessage: string = 'An error occurred';\n\n try {\n // Attempt to parse JSON error payload produced by backend\n const errorData = await response.json();\n const errorObj = errorData.error ?? errorData;\n errorMessage = JSON.stringify(errorObj) ?? 'An error occurred';\n } catch {\n // Fallback to plain-text body or HTTP status text\n try {\n const errorText = await response.text();\n if (errorText) {\n errorMessage = errorText;\n }\n } catch {\n // ignore – we already have a default message\n }\n }\n\n throw new Error(errorMessage);\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n throw new Error('No reader available');\n }\n\n const decoder = new TextDecoder();\n let buffer = '';\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.startsWith('data: ')) {\n try {\n const data = JSON.parse(line.slice(6));\n if (data.chunk) {\n onMessage?.(data.chunk);\n }\n if (data.done && data.response) {\n onDone?.(data.response);\n }\n } catch (e) {\n console.error('Failed to parse SSE data:', e);\n }\n }\n }\n }\n } catch (error) {\n console.error('Error in askDocQuestion:', error);\n throw error;\n }\n };\n\n const chat = async (body?: ChatBody, otherOptions: FetcherOptions = {}) => {\n if (!body) return;\n\n const { onMessage, onDone, onAction, ...rest } = body;\n const abortController = new AbortController();\n\n try {\n const response = await fetch(\n buildRouteURL(backendURL, aiGroup, aiEndpoints.chat),\n {\n method: aiEndpoints.chat.method,\n headers: {\n 'Content-Type': 'application/json',\n ...authAPIOptions.headers,\n ...otherOptions.headers,\n },\n body: JSON.stringify({\n ...rest,\n ...authAPIOptions.body,\n ...otherOptions.body,\n }),\n signal: abortController.signal,\n credentials: 'include',\n }\n );\n\n if (!response.ok) {\n let errorMessage: string = 'An error occurred';\n\n try {\n const errorData = await response.json();\n const errorObj = errorData.error ?? errorData;\n errorMessage = JSON.stringify(errorObj) ?? 'An error occurred';\n } catch {\n try {\n const errorText = await response.text();\n if (errorText) {\n errorMessage = errorText;\n }\n } catch {\n // ignore\n }\n }\n\n throw new Error(errorMessage);\n }\n\n const reader = response.body?.getReader();\n if (!reader) {\n throw new Error('No reader available');\n }\n\n const decoder = new TextDecoder();\n let buffer = '';\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n if (line.startsWith('data: ')) {\n try {\n const data = JSON.parse(line.slice(6));\n if (data.chunk) {\n onMessage?.(data.chunk);\n }\n if (data.action) {\n onAction?.(data.action);\n }\n if (data.done && data.response) {\n onDone?.(data.response);\n }\n } catch (e) {\n console.error('Failed to parse SSE data:', e);\n }\n }\n }\n }\n } catch (error) {\n console.error('Error in chat:', error);\n throw error;\n }\n };\n\n const autocomplete = async (\n body?: AutocompleteBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<AutocompleteResponse>(\n buildRouteURL(backendURL, aiGroup, aiEndpoints.autocomplete),\n authAPIOptions,\n otherOptions,\n {\n method: aiEndpoints.autocomplete.method,\n body: body,\n }\n );\n\n /**\n * Retrieves discussions with filters and pagination. Only user or admin can access.\n */\n const getDiscussions = async (\n params?: GetDiscussionsParams,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetDiscussionsResult>(\n buildRouteURL(backendURL, aiGroup, aiEndpoints.getDiscussions),\n authAPIOptions,\n otherOptions,\n {\n method: aiEndpoints.getDiscussions.method,\n // @ts-ignore Number of parameter will be stringified by the fetcher\n params,\n }\n );\n\n /**\n * Retrieves aggregated AI token-usage statistics for the currently selected\n * project.\n */\n const getAIStats = async (otherOptions: FetcherOptions = {}) =>\n await fetcher<GetAIStatsResult>(\n buildRouteURL(backendURL, aiGroup, aiEndpoints.getAIStats),\n authAPIOptions,\n otherOptions,\n {\n method: aiEndpoints.getAIStats.method,\n }\n );\n\n return {\n customQuery,\n translateJSON,\n auditContentDeclaration,\n auditContentDeclarationField,\n auditContentDeclarationMetadata,\n auditTag,\n askDocQuestion,\n chat,\n autocomplete,\n getDiscussions,\n getAIStats,\n };\n};\n\n/**\n * Authenticated `ai` endpoint bound to an Intlayer CMS authenticator.\n *\n * Pass an authenticator created with `createIntlayerCMS`, or omit it to use\n * the build-time configuration (`@intlayer/config/built`).\n */\nexport const aiEndpoint = createEndpoint(getAiAPI);\n"],"mappings":";;;;;;;;AA8DA,MAAM,UAAU,EACd,QAAQ,UACV;;;;;AAMA,MAAM,cAAc;CAClB,aAAa;EAAE,QAAQ;EAAQ,MAAM;CAAI;CACzC,eAAe;EAAE,QAAQ;EAAQ,MAAM;CAAkB;CACzD,yBAAyB;EAAE,QAAQ;EAAQ,MAAM;CAAoB;CACrE,8BAA8B;EAC5B,QAAQ;EACR,MAAM;CACR;CACA,iCAAiC;EAC/B,QAAQ;EACR,MAAM;CACR;CACA,UAAU;EAAE,QAAQ;EAAQ,MAAM;CAAa;CAC/C,KAAK;EAAE,QAAQ;EAAQ,MAAM;CAAO;CACpC,MAAM;EAAE,QAAQ;EAAQ,MAAM;CAAQ;CACtC,cAAc;EAAE,QAAQ;EAAQ,MAAM;CAAgB;CACtD,gBAAgB;EAAE,QAAQ;EAAO,MAAM;CAAe;CACtD,YAAY;EAAE,QAAQ;EAAO,MAAM;CAAS;AAC9C;AAEA,MAAa,YACX,iBAAiC,CAAC,GAClC,mBACG;CACH,MAAM,aACJ,gBAAgB,QAAQ,cAAc,OAAO,cAAc;;;;;;CAO7D,MAAM,cAAc,OAClB,MACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,cAAc,YAAY,SAAS,YAAY,WAAW,GAC1D,gBACA,cACA;EACE,QAAQ,YAAY,YAAY;EAC1B;CACR,CACF;;;;;;CAOF,MAAM,gBAAgB,OACpB,MACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,cAAc,YAAY,SAAS,YAAY,aAAa,GAC5D,gBACA,cACA;EACE,QAAQ,YAAY,cAA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AAc,YAAY,SAAS,YAAY,YAAY,GAC3D,gBACA,cACA;EACE,QAAQ,YAAY,aAAa;EAC3B;CACR,CACF;;;;CAKF,MAAM,iBAAiB,OACrB,QACA,eAA+B,CAAC,MAEhC,MAAM,QACJ,cAAc,YAAY,SAAS,YAAY,cAAc,GAC7D,gBACA,cACA;EACE,QAAQ,YAAY,eAAe;EAEnC;CACF,CACF;;;;;CAMF,MAAM,aAAa,OAAO,eAA+B,CAAC,MACxD,MAAM,QACJ,cAAc,YAAY,SAAS,YAAY,UAAU,GACzD,gBACA,cACA,EACE,QAAQ,YAAY,WAAW,OACjC,CACF;CAEF,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF;;;;;;;AAQA,MAAa,aAAa,eAAe,QAAQ"}
|
|
@@ -1,25 +1,59 @@
|
|
|
1
|
-
import { fetcher } from "../fetcher.mjs";
|
|
2
1
|
import { createEndpoint } from "../cms/createIntlayerCMS.mjs";
|
|
2
|
+
import { fetcher } from "../fetcher.mjs";
|
|
3
3
|
import { editor } from "@intlayer/config/built";
|
|
4
|
+
import { buildRouteURL } from "@intlayer/backend-contract/defineRoute";
|
|
5
|
+
import { BACKEND_URL } from "@intlayer/config/defaultValues";
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
// src/getIntlayerAPI/analytics.ts
|
|
8
|
+
/** Prefix of the routes, checked against the backend contract. */
|
|
9
|
+
const analyticsGroup = { prefix: "/api/analytics" };
|
|
10
|
+
/**
|
|
11
|
+
* Method and path of every route, checked against the backend contract at
|
|
12
|
+
* compile time (the contract's zod schemas are never loaded).
|
|
13
|
+
*/
|
|
14
|
+
const analyticsEndpoints = {
|
|
15
|
+
ingestAnalyticsEvents: {
|
|
16
|
+
method: "POST",
|
|
17
|
+
path: "/events"
|
|
18
|
+
},
|
|
19
|
+
getAnalyticsOverview: {
|
|
20
|
+
method: "GET",
|
|
21
|
+
path: "/overview"
|
|
22
|
+
},
|
|
23
|
+
getAnalyticsAudience: {
|
|
24
|
+
method: "GET",
|
|
25
|
+
path: "/audience"
|
|
26
|
+
},
|
|
27
|
+
getContentStats: {
|
|
28
|
+
method: "GET",
|
|
29
|
+
path: "/content-stats"
|
|
30
|
+
},
|
|
31
|
+
getExperimentResults: {
|
|
32
|
+
method: "GET",
|
|
33
|
+
path: "/experiments/:experimentKey"
|
|
34
|
+
},
|
|
35
|
+
getPageMetadata: {
|
|
36
|
+
method: "GET",
|
|
37
|
+
path: "/page-metadata"
|
|
38
|
+
}
|
|
39
|
+
};
|
|
6
40
|
const getAnalyticsAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
7
|
-
const
|
|
41
|
+
const backendURL = intlayerConfig?.editor?.backendURL ?? editor.backendURL ?? BACKEND_URL;
|
|
8
42
|
/**
|
|
9
43
|
* Ingest a batch of analytics events. Public — attribution is by the
|
|
10
44
|
* project's `clientId` in the body.
|
|
11
45
|
* @param body - Session id, sdk version, and the collected events.
|
|
12
46
|
* @returns The number of accepted events.
|
|
13
47
|
*/
|
|
14
|
-
const sendEvents = async (body, otherOptions = {}) => await fetcher(
|
|
15
|
-
method:
|
|
48
|
+
const sendEvents = async (body, otherOptions = {}) => await fetcher(buildRouteURL(backendURL, analyticsGroup, analyticsEndpoints.ingestAnalyticsEvents), authAPIOptions, otherOptions, {
|
|
49
|
+
method: analyticsEndpoints.ingestAnalyticsEvents.method,
|
|
16
50
|
body
|
|
17
51
|
});
|
|
18
52
|
/**
|
|
19
53
|
* Page/locale totals for the authenticated project.
|
|
20
54
|
* @returns Views grouped by url and locale.
|
|
21
55
|
*/
|
|
22
|
-
const getOverview = async (otherOptions = {}) => await fetcher(
|
|
56
|
+
const getOverview = async (otherOptions = {}) => await fetcher(buildRouteURL(backendURL, analyticsGroup, analyticsEndpoints.getAnalyticsOverview), authAPIOptions, otherOptions, { method: analyticsEndpoints.getAnalyticsOverview.method });
|
|
23
57
|
/**
|
|
24
58
|
* Audience report: distinct visitors (today / 7d / window), page views, the
|
|
25
59
|
* evolution series, and locale + country breakdowns.
|
|
@@ -27,28 +61,28 @@ const getAnalyticsAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
27
61
|
* `30d`, `90d`, `6mo`, `1y`, `3y`) or a number of days (default 30).
|
|
28
62
|
* @returns The audience statistics.
|
|
29
63
|
*/
|
|
30
|
-
const getAudience = async (range = 30, otherOptions = {}) => await fetcher(
|
|
31
|
-
method:
|
|
64
|
+
const getAudience = async (range = 30, otherOptions = {}) => await fetcher(buildRouteURL(backendURL, analyticsGroup, analyticsEndpoints.getAnalyticsAudience), authAPIOptions, otherOptions, {
|
|
65
|
+
method: analyticsEndpoints.getAnalyticsAudience.method,
|
|
32
66
|
params: typeof range === "number" ? { days: String(range) } : { range }
|
|
33
67
|
});
|
|
34
68
|
/**
|
|
35
69
|
* Per-content exposure totals — "which content is actually shown".
|
|
36
70
|
* @returns Exposures grouped by dictionary key, key path, and locale.
|
|
37
71
|
*/
|
|
38
|
-
const getContentStats = async (otherOptions = {}) => await fetcher(
|
|
72
|
+
const getContentStats = async (otherOptions = {}) => await fetcher(buildRouteURL(backendURL, analyticsGroup, analyticsEndpoints.getContentStats), authAPIOptions, otherOptions, { method: analyticsEndpoints.getContentStats.method });
|
|
39
73
|
/**
|
|
40
74
|
* A/B experiment results with per-variant conversion rates and significance.
|
|
41
75
|
* @param experimentKey - The experiment to evaluate.
|
|
42
76
|
* @returns The experiment result set.
|
|
43
77
|
*/
|
|
44
|
-
const getExperimentResults = async (experimentKey, otherOptions = {}) => await fetcher(
|
|
78
|
+
const getExperimentResults = async (experimentKey, otherOptions = {}) => await fetcher(buildRouteURL(backendURL, analyticsGroup, analyticsEndpoints.getExperimentResults, { experimentKey }), authAPIOptions, otherOptions, { method: analyticsEndpoints.getExperimentResults.method });
|
|
45
79
|
/**
|
|
46
80
|
* Page metadata (title and meta description) for a given url.
|
|
47
81
|
* @param url - The page url to inspect.
|
|
48
82
|
* @returns Title and description of the page.
|
|
49
83
|
*/
|
|
50
|
-
const getPageMetadata = async (url, otherOptions = {}) => await fetcher(
|
|
51
|
-
method:
|
|
84
|
+
const getPageMetadata = async (url, otherOptions = {}) => await fetcher(buildRouteURL(backendURL, analyticsGroup, analyticsEndpoints.getPageMetadata), authAPIOptions, otherOptions, {
|
|
85
|
+
method: analyticsEndpoints.getPageMetadata.method,
|
|
52
86
|
params: { url }
|
|
53
87
|
});
|
|
54
88
|
return {
|
|
@@ -68,6 +102,5 @@ const getAnalyticsAPI = (authAPIOptions = {}, intlayerConfig) => {
|
|
|
68
102
|
*/
|
|
69
103
|
const analyticsEndpoint = createEndpoint(getAnalyticsAPI);
|
|
70
104
|
|
|
71
|
-
//#endregion
|
|
72
105
|
export { analyticsEndpoint, getAnalyticsAPI };
|
|
73
106
|
//# sourceMappingURL=analytics.mjs.map
|