@intlayer/api 7.1.5 → 7.1.7

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.
@@ -91,7 +91,7 @@ const fetcher = async (url, ...options) => {
91
91
  const { signal } = new AbortController();
92
92
  let paramsString = "";
93
93
  let bodyString;
94
- const mergedOptions = deepMerge([fetcherOptions, ...options.map(({ body, params: params$1, headers,...otherOptions }) => otherOptions)]);
94
+ const mergedOptions = deepMerge([fetcherOptions, ...options.map(({ body, params: params$1, headers, ...otherOptions }) => otherOptions)]);
95
95
  const mergedHeaders = deepMerge([fetcherOptions.headers, ...options.map((option) => option.headers)]);
96
96
  const params = deepMerge(options.map((option) => option.params));
97
97
  const method = mergedOptions.method;
@@ -1 +1 @@
1
- {"version":3,"file":"fetcher.cjs","names":["fetcherOptions: FetcherOptions","acc1: T","obj1: T","bodyString: string | undefined","formattedOptions: RequestInit"],"sources":["../../src/fetcher.ts"],"sourcesContent":["/**\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<string, string | string[] | undefined>\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\n const urlResult = `${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();\n\n // You can customize the error message or include more details\n throw new Error(JSON.stringify(result.error) ?? 'An error occurred');\n }\n return await response.json();\n};\n"],"mappings":";;;;;;;AAwBA,MAAaA,iBAAiC;CAC5C,QAAQ;CACR,SAAS,EACP,gBAAgB,oBACjB;CACD,aAAa;CACd;;;;;;;;AASD,MAAM,mBAAmB,QAAgB;AACvC,QAAO,KAAK,IAAI,CAAC,SAAS,QAAQ;AAChC,MAAI,IAAI,SAA6B,OACnC,QAAO,IAAI;GAEb;AACF,QAAO;;;;;;;;;;AAWT,MAAM,aAA+B,YACnC,QAAQ,QAAQ,K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OAAO,MAAM,IAAI,oBAAoB;;AAEtE,QAAO,MAAM,SAAS,MAAM"}
1
+ {"version":3,"file":"fetcher.cjs","names":["fetcherOptions: FetcherOptions","acc1: T","obj1: T","bodyString: string | undefined","formattedOptions: RequestInit"],"sources":["../../src/fetcher.ts"],"sourcesContent":["/**\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<string, string | string[] | undefined>\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\n const urlResult = `${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();\n\n // You can customize the error message or include more details\n throw new Error(JSON.stringify(result.error) ?? 'An error occurred');\n }\n return await response.json();\n};\n"],"mappings":";;;;;;;AAwBA,MAAaA,iBAAiC;CAC5C,QAAQ;CACR,SAAS,EACP,gBAAgB,oBACjB;CACD,aAAa;CACd;;;;;;;;AASD,MAAM,mBAAmB,QAAgB;AACvC,QAAO,KAAK,IAAI,CAAC,SAAS,QAAQ;AAChC,MAAI,IAAI,SAA6B,OACnC,QAAO,IAAI;GAEb;AACF,QAAO;;;;;;;;;;AAWT,MAAM,aAA+B,YACnC,QAAQ,QAAQ,KAAK,QAAQ;CAC3B,MAAMC,OAAW,OAAO,EAAE;CAC1B,MAAMC,OAAU,gBAAgB,OAAO,EAAE,CAAC;AAE1C,KAAI,OAAO,SAAS,YAAY,OAAO,SAAS,SAE9C,QAAO;EAAE,GAAG;EAAM,GAAG;EAAM;AAI7B,QAAO,QAAQ;GACd,EAAE,CAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDb,MAAa,UAAU,OACrB,KACA,GAAG,YACY;CACf,MAAM,EAAE,WAAW,IAAI,iBAAiB;CAGxC,IAAI,eAAe;CACnB,IAAIC;CAQJ,MAAM,gBAAgB,UAAU,CAAC,gBAAgB,GAL5B,QAAQ,KAC1B,EAAE,MAAM,kBAAQ,SAAS,GAAG,mBAAmB,aACjD,CAGgE,CAAC;CAGlE,MAAM,gBAAgB,UAAU,CAC9B,eAAe,SACf,GAAG,QAAQ,KAAK,WAAW,OAAO,QAAQ,CAC3C,CAAC;CAGF,MAAM,SAAS,UAAU,QAAQ,KAAK,WAAW,OAAO,OAAO,CAAC;CAEhE,MAAM,SAAS,cAAc;AAG7B,KAAI,WAAW,SAAS,WAAW,QAAQ;EAEzC,MAAM,OAAO,UAAU,QAAQ,KAAK,WAAW,OAAO,KAAK,CAAC;AAC5D,MACE,gBAAgB,oBAChB,oCAGA,cAAa,IAAI,gBACf,KACD,CAAC,UAAU;MAGZ,cAAa,KAAK,UAAU,KAAK;;AAKrC,KAAI,OAAO,QAAQ,OAAO,CAAC,SAAS,EAClC,gBAAe,IAAI,IAAI,gBACrB,OACD,CAAC,UAAU;CAId,MAAMC,mBAAgC;EACpC,GAAG;EACH,SAAS;EACT,MAAM;EACN;EACD;CAGD,MAAM,YAAY,GAAG,MAAM;CAG3B,MAAM,WAAW,MAAM,MAAM,WAAW,iBAAiB;AAEzD,KAAI,CAAC,SAAS,IAAI;EAChB,MAAM,SAAS,MAAM,SAAS,MAAM;AAGpC,QAAM,IAAI,MAAM,KAAK,UAAU,OAAO,MAAM,IAAI,oBAAoB;;AAEtE,QAAO,MAAM,SAAS,MAAM"}
@@ -83,7 +83,7 @@ const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
83
83
  */
84
84
  const askDocQuestion = async (body, otherOptions = {}) => {
85
85
  if (!body) return;
86
- const { onMessage, onDone,...rest } = body;
86
+ const { onMessage, onDone, ...rest } = body;
87
87
  const abortController = new AbortController();
88
88
  try {
89
89
  const response = await fetch(`${AI_API_ROUTE}/ask`, {
@@ -1 +1 @@
1
- {"version":3,"file":"ai.cjs","names":["configuration","fetcher","errorMessage: string"],"sources":["../../../src/getIntlayerAPI/ai.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { type FetcherOptions, fetcher } from '../fetcher';\nimport type {\n AskDocQuestionResult,\n AuditContentDeclarationBody,\n AuditContentDeclarationFieldBody,\n AuditContentDeclarationFieldResult,\n AuditContentDeclarationMetadataBody,\n AuditContentDeclarationMetadataResult,\n AuditContentDeclarationResult,\n AuditTagBody,\n AuditTagResult,\n AutocompleteBody,\n AutocompleteResponse,\n ChatCompletionRequestMessage,\n CustomQueryBody,\n CustomQueryResult,\n GetDiscussionsParams,\n GetDiscussionsResult,\n TranslateJSONBody,\n TranslateJSONResult,\n} from '../types';\n\nexport type AskDocQuestionBody = {\n messages: ChatCompletionRequestMessage[];\n discussionId: string;\n onMessage?: (chunk: string) => void;\n onDone?: (response: AskDocQuestionResult) => void;\n};\n\nexport type { AskDocQuestionResult };\n\nexport const getAiAPI = (\n authAPIOptions: FetcherOptions = {},\n intlayerConfig?: IntlayerConfig\n) => {\n const backendURL =\n intlayerConfig?.editor?.backendURL ?? configuration?.editor?.backendURL;\n\n if (!backendURL) {\n throw new Error(\n 'Backend URL is not defined in the Intlayer configuration.'\n );\n }\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 errorMessage = JSON.stringify(errorData.error) ?? '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 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 return {\n customQuery,\n translateJSON,\n auditContentDeclaration,\n auditContentDeclarationField,\n auditContentDeclarationMetadata,\n auditTag,\n askDocQuestion,\n autocomplete,\n getDiscussions,\n };\n};\n"],"mappings":";;;;;;AAiCA,MAAa,YACX,iBAAiC,EAAE,EACnC,mBACG;CACH,MAAM,aACJ,gBAAgB,QAAQ,cAAcA,iCAAe,QAAQ;AAE/D,KAAI,CAAC,WACH,OAAM,IAAI,MACR,4DACD;CAGH,MAAM,eAAe,GAAG,WAAW;;;;;;CAOnC,MAAM,cAAc,OAClB,MACA,eAA+B,EAAE,KAEjC,MAAMC,wBACJ,cACA,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;;;CAOH,MAAM,gBAAgB,OACpB,MACA,eAA+B,EAAE,KAEjC,MAAMA,wBACJ,GAAG,aAAa,kBAChB,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;;;CAOH,MAAM,0BAA0B,OAC9B,MACA,eAA+B,EAAE,KAEjC,MAAMA,wBACJ,GAAG,aAAa,oBAChB,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;;;CAOH,MAAM,+BAA+B,OACnC,MACA,eAA+B,EAAE,KAEjC,MAAMA,wBACJ,GAAG,aAAa,0BAChB,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;;;CAOH,MAAM,kCAAkC,OACtC,MACA,eAA+B,EAAE,KAEjC,MAAMA,wBACJ,GAAG,aAAa,6BAChB,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;;;CAOH,MAAM,WAAW,OACf,MACA,eAA+B,EAAE,KAEjC,MAAMA,wBACJ,GAAG,aAAa,aAChB,gBACA,cACA;EACE,QAAQ;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AAI,KAAK,QAAQ,KAAK,SACpB,UAAS,KAAK,SAAS;aAElB,GAAG;AACV,aAAQ,MAAM,6BAA6B,EAAE;;;WAK9C,OAAO;AACd,WAAQ,MAAM,4BAA4B,MAAM;AAChD,SAAM;;;CAIV,MAAM,eAAe,OACnB,MACA,eAA+B,EAAE,KAEjC,MAAMD,wBACJ,GAAG,aAAa,gBAChB,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;CAKH,MAAM,iBAAiB,OACrB,QACA,eAA+B,EAAE,KAEjC,MAAMA,wBACJ,GAAG,aAAa,eAChB,gBACA,cACA;EACE,QAAQ;EAER;EACD,CACF;AAEH,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
1
+ {"version":3,"file":"ai.cjs","names":["configuration","fetcher","errorMessage: string"],"sources":["../../../src/getIntlayerAPI/ai.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { type FetcherOptions, fetcher } from '../fetcher';\nimport type {\n AskDocQuestionResult,\n AuditContentDeclarationBody,\n AuditContentDeclarationFieldBody,\n AuditContentDeclarationFieldResult,\n AuditContentDeclarationMetadataBody,\n AuditContentDeclarationMetadataResult,\n AuditContentDeclarationResult,\n AuditTagBody,\n AuditTagResult,\n AutocompleteBody,\n AutocompleteResponse,\n ChatCompletionRequestMessage,\n CustomQueryBody,\n CustomQueryResult,\n GetDiscussionsParams,\n GetDiscussionsResult,\n TranslateJSONBody,\n TranslateJSONResult,\n} from '../types';\n\nexport type AskDocQuestionBody = {\n messages: ChatCompletionRequestMessage[];\n discussionId: string;\n onMessage?: (chunk: string) => void;\n onDone?: (response: AskDocQuestionResult) => void;\n};\n\nexport type { AskDocQuestionResult };\n\nexport const getAiAPI = (\n authAPIOptions: FetcherOptions = {},\n intlayerConfig?: IntlayerConfig\n) => {\n const backendURL =\n intlayerConfig?.editor?.backendURL ?? configuration?.editor?.backendURL;\n\n if (!backendURL) {\n throw new Error(\n 'Backend URL is not defined in the Intlayer configuration.'\n );\n }\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 errorMessage = JSON.stringify(errorData.error) ?? '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 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 return {\n customQuery,\n translateJSON,\n auditContentDeclaration,\n auditContentDeclarationField,\n auditContentDeclarationMetadata,\n auditTag,\n askDocQuestion,\n autocomplete,\n getDiscussions,\n };\n};\n"],"mappings":";;;;;;AAiCA,MAAa,YACX,iBAAiC,EAAE,EACnC,mBACG;CACH,MAAM,aACJ,gBAAgB,QAAQ,cAAcA,iCAAe,QAAQ;AAE/D,KAAI,CAAC,WACH,OAAM,IAAI,MACR,4DACD;CAGH,MAAM,eAAe,GAAG,WAAW;;;;;;CAOnC,MAAM,cAAc,OAClB,MACA,eAA+B,EAAE,KAEjC,MAAMC,wBACJ,cACA,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;;;CAOH,MAAM,gBAAgB,OACpB,MACA,eAA+B,EAAE,KAEjC,MAAM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F,gBAAe;aAEX;;AAKV,UAAM,IAAI,MAAM,aAAa;;GAG/B,MAAM,SAAS,SAAS,MAAM,WAAW;AACzC,OAAI,CAAC,OACH,OAAM,IAAI,MAAM,sBAAsB;GAGxC,MAAM,UAAU,IAAI,aAAa;GACjC,IAAI,SAAS;AAEb,UAAO,MAAM;IACX,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,MAAM;AAC3C,QAAI,KAAM;AAEV,cAAU,QAAQ,OAAO,OAAO,EAAE,QAAQ,MAAM,CAAC;IACjD,MAAM,QAAQ,OAAO,MAAM,KAAK;AAChC,aAAS,MAAM,KAAK,IAAI;AAExB,SAAK,MAAM,QAAQ,MACjB,KAAI,KAAK,WAAW,SAAS,CAC3B,KAAI;KACF,MAAM,OAAO,KAAK,MAAM,KAAK,MAAM,EAAE,CAAC;AACtC,SAAI,KAAK,MACP,aAAY,KAAK,MAAM;AAEzB,SAAI,KAAK,QAAQ,KAAK,SACpB,UAAS,KAAK,SAAS;aAElB,GAAG;AACV,aAAQ,MAAM,6BAA6B,EAAE;;;WAK9C,OAAO;AACd,WAAQ,MAAM,4BAA4B,MAAM;AAChD,SAAM;;;CAIV,MAAM,eAAe,OACnB,MACA,eAA+B,EAAE,KAEjC,MAAMD,wBACJ,GAAG,aAAa,gBAChB,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;CAKH,MAAM,iBAAiB,OACrB,QACA,eAA+B,EAAE,KAEjC,MAAMA,wBACJ,GAAG,aAAa,eAChB,gBACA,cACA;EACE,QAAQ;EAER;EACD,CACF;AAEH,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
@@ -90,7 +90,7 @@ const fetcher = async (url, ...options) => {
90
90
  const { signal } = new AbortController();
91
91
  let paramsString = "";
92
92
  let bodyString;
93
- const mergedOptions = deepMerge([fetcherOptions, ...options.map(({ body, params: params$1, headers,...otherOptions }) => otherOptions)]);
93
+ const mergedOptions = deepMerge([fetcherOptions, ...options.map(({ body, params: params$1, headers, ...otherOptions }) => otherOptions)]);
94
94
  const mergedHeaders = deepMerge([fetcherOptions.headers, ...options.map((option) => option.headers)]);
95
95
  const params = deepMerge(options.map((option) => option.params));
96
96
  const method = mergedOptions.method;
@@ -1 +1 @@
1
- {"version":3,"file":"fetcher.mjs","names":["fetcherOptions: FetcherOptions","acc1: T","obj1: T","bodyString: string | undefined","formattedOptions: RequestInit"],"sources":["../../src/fetcher.ts"],"sourcesContent":["/**\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<string, string | string[] | undefined>\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\n const urlResult = `${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();\n\n // You can customize the error message or include more details\n throw new Error(JSON.stringify(result.error) ?? 'An error occurred');\n }\n return await response.json();\n};\n"],"mappings":";;;;;;AAwBA,MAAaA,iBAAiC;CAC5C,QAAQ;CACR,SAAS,EACP,gBAAgB,oBACjB;CACD,aAAa;CACd;;;;;;;;AASD,MAAM,mBAAmB,QAAgB;AACvC,QAAO,KAAK,IAAI,CAAC,SAAS,QAAQ;AAChC,MAAI,IAAI,SAA6B,OACnC,QAAO,IAAI;GAEb;AACF,QAAO;;;;;;;;;;AAWT,MAAM,aAA+B,YACnC,QAAQ,QAAQ,KAAK,QAAQ;CAC3B,MAAMC,OAAW,OAAO,EAAE;CAC1B,MAAMC,OAAU,gBAAgB,OAAO,EAAE,CAAC;AAE1C,KAAI,OAAO,SAAS,YAAY,OAAO,SAAS,SAE9C,QAAO;EAAE,GAAG;EAAM,GAAG;EAAM;AAI7B,QAAO,QAAQ;GACd,EAAE,CAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDb,MAAa,UAAU,OACrB,KACA,GAAG,YACY;CACf,MAAM,EAAE,WAAW,IAAI,iBAAiB;CAGxC,IAAI,eAAe;CACnB,IAAIC;CAQJ,MAAM,gBAAgB,UAAU,CAAC,gBAAgB,GAL5B,QAAQ,KAC1B,EAAE,MAAM,kBAAQ,QAAS,GAAG,mBAAmB,aACjD,CAGgE,CAAC;CAGlE,MAAM,gBAAgB,UAAU,CAC9B,eAAe,SACf,GAAG,QAAQ,KAAK,WAAW,OAAO,QAAQ,CAC3C,CAAC;CAGF,MAAM,SAAS,UAAU,QAAQ,KAAK,WAAW,OAAO,OAAO,CAAC;CAEhE,MAAM,SAAS,cAAc;AAG7B,KAAI,WAAW,SAAS,WAAW,QAAQ;EAEzC,MAAM,OAAO,UAAU,QAAQ,KAAK,WAAW,OAAO,KAAK,CAAC;AAC5D,MACE,gBAAgB,oBAChB,oCAGA,cAAa,IAAI,gBACf,KACD,CAAC,UAAU;MAGZ,cAAa,KAAK,UAAU,KAAK;;AAKrC,KAAI,OAAO,QAAQ,OAAO,CAAC,SAAS,EAClC,gBAAe,IAAI,IAAI,gBACrB,OACD,CAAC,UAAU;CAId,MAAMC,mBAAgC;EACpC,GAAG;EACH,SAAS;EACT,MAAM;EACN;EACD;CAGD,MAAM,YAAY,GAAG,MAAM;CAG3B,MAAM,WAAW,MAAM,MAAM,WAAW,iBAAiB;AAEzD,KAAI,CAAC,SAAS,IAAI;EAChB,MAAM,SAAS,MAAM,SAAS,MAAM;AAGpC,QAAM,IAAI,MAAM,KAAK,UAAU,OAAO,MAAM,IAAI,oBAAoB;;AAEtE,QAAO,MAAM,SAAS,MAAM"}
1
+ {"version":3,"file":"fetcher.mjs","names":["fetcherOptions: FetcherOptions","acc1: T","obj1: T","bodyString: string | undefined","formattedOptions: RequestInit"],"sources":["../../src/fetcher.ts"],"sourcesContent":["/**\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<string, string | string[] | undefined>\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\n const urlResult = `${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();\n\n // You can customize the error message or include more details\n throw new Error(JSON.stringify(result.error) ?? 'An error occurred');\n }\n return await response.json();\n};\n"],"mappings":";;;;;;AAwBA,MAAaA,iBAAiC;CAC5C,QAAQ;CACR,SAAS,EACP,gBAAgB,oBACjB;CACD,aAAa;CACd;;;;;;;;AASD,MAAM,mBAAmB,QAAgB;AACvC,QAAO,KAAK,IAAI,CAAC,SAAS,QAAQ;AAChC,MAAI,IAAI,SAA6B,OACnC,QAAO,IAAI;GAEb;AACF,QAAO;;;;;;;;;;AAWT,MAAM,aAA+B,YACnC,QAAQ,QAAQ,KAAK,QAAQ;CAC3B,MAAMC,OAAW,OAAO,EAAE;CAC1B,MAAMC,OAAU,gBAAgB,OAAO,EAAE,CAAC;AAE1C,KAAI,OAAO,SAAS,YAAY,OAAO,SAAS,SAE9C,QAAO;EAAE,GAAG;EAAM,GAAG;EAAM;AAI7B,QAAO,QAAQ;GACd,EAAE,CAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDb,MAAa,UAAU,OACrB,KACA,GAAG,YACY;CACf,MAAM,EAAE,WAAW,IAAI,iBAAiB;CAGxC,IAAI,eAAe;CACnB,IAAIC;CAQJ,MAAM,gBAAgB,UAAU,CAAC,gBAAgB,GAL5B,QAAQ,KAC1B,EAAE,MAAM,kBAAQ,SAAS,GAAG,mBAAmB,aACjD,CAGgE,CAAC;CAGlE,MAAM,gBAAgB,UAAU,CAC9B,eAAe,SACf,GAAG,QAAQ,KAAK,WAAW,OAAO,QAAQ,CAC3C,CAAC;CAGF,MAAM,SAAS,UAAU,QAAQ,KAAK,WAAW,OAAO,OAAO,CAAC;CAEhE,MAAM,SAAS,cAAc;AAG7B,KAAI,WAAW,SAAS,WAAW,QAAQ;EAEzC,MAAM,OAAO,UAAU,QAAQ,KAAK,WAAW,OAAO,KAAK,CAAC;AAC5D,MACE,gBAAgB,oBAChB,oCAGA,cAAa,IAAI,gBACf,KACD,CAAC,UAAU;MAGZ,cAAa,KAAK,UAAU,KAAK;;AAKrC,KAAI,OAAO,QAAQ,OAAO,CAAC,SAAS,EAClC,gBAAe,IAAI,IAAI,gBACrB,OACD,CAAC,UAAU;CAId,MAAMC,mBAAgC;EACpC,GAAG;EACH,SAAS;EACT,MAAM;EACN;EACD;CAGD,MAAM,YAAY,GAAG,MAAM;CAG3B,MAAM,WAAW,MAAM,MAAM,WAAW,iBAAiB;AAEzD,KAAI,CAAC,SAAS,IAAI;EAChB,MAAM,SAAS,MAAM,SAAS,MAAM;AAGpC,QAAM,IAAI,MAAM,KAAK,UAAU,OAAO,MAAM,IAAI,oBAAoB;;AAEtE,QAAO,MAAM,SAAS,MAAM"}
@@ -81,7 +81,7 @@ const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
81
81
  */
82
82
  const askDocQuestion = async (body, otherOptions = {}) => {
83
83
  if (!body) return;
84
- const { onMessage, onDone,...rest } = body;
84
+ const { onMessage, onDone, ...rest } = body;
85
85
  const abortController = new AbortController();
86
86
  try {
87
87
  const response = await fetch(`${AI_API_ROUTE}/ask`, {
@@ -1 +1 @@
1
- {"version":3,"file":"ai.mjs","names":["errorMessage: string"],"sources":["../../../src/getIntlayerAPI/ai.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { type FetcherOptions, fetcher } from '../fetcher';\nimport type {\n AskDocQuestionResult,\n AuditContentDeclarationBody,\n AuditContentDeclarationFieldBody,\n AuditContentDeclarationFieldResult,\n AuditContentDeclarationMetadataBody,\n AuditContentDeclarationMetadataResult,\n AuditContentDeclarationResult,\n AuditTagBody,\n AuditTagResult,\n AutocompleteBody,\n AutocompleteResponse,\n ChatCompletionRequestMessage,\n CustomQueryBody,\n CustomQueryResult,\n GetDiscussionsParams,\n GetDiscussionsResult,\n TranslateJSONBody,\n TranslateJSONResult,\n} from '../types';\n\nexport type AskDocQuestionBody = {\n messages: ChatCompletionRequestMessage[];\n discussionId: string;\n onMessage?: (chunk: string) => void;\n onDone?: (response: AskDocQuestionResult) => void;\n};\n\nexport type { AskDocQuestionResult };\n\nexport const getAiAPI = (\n authAPIOptions: FetcherOptions = {},\n intlayerConfig?: IntlayerConfig\n) => {\n const backendURL =\n intlayerConfig?.editor?.backendURL ?? configuration?.editor?.backendURL;\n\n if (!backendURL) {\n throw new Error(\n 'Backend URL is not defined in the Intlayer configuration.'\n );\n }\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 errorMessage = JSON.stringify(errorData.error) ?? '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 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 return {\n customQuery,\n translateJSON,\n auditContentDeclaration,\n auditContentDeclarationField,\n auditContentDeclarationMetadata,\n auditTag,\n askDocQuestion,\n autocomplete,\n getDiscussions,\n };\n};\n"],"mappings":";;;;AAiCA,MAAa,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AAa,eAChB,gBACA,cACA;EACE,QAAQ;EAER;EACD,CACF;AAEH,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
1
+ {"version":3,"file":"ai.mjs","names":["errorMessage: string"],"sources":["../../../src/getIntlayerAPI/ai.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { type FetcherOptions, fetcher } from '../fetcher';\nimport type {\n AskDocQuestionResult,\n AuditContentDeclarationBody,\n AuditContentDeclarationFieldBody,\n AuditContentDeclarationFieldResult,\n AuditContentDeclarationMetadataBody,\n AuditContentDeclarationMetadataResult,\n AuditContentDeclarationResult,\n AuditTagBody,\n AuditTagResult,\n AutocompleteBody,\n AutocompleteResponse,\n ChatCompletionRequestMessage,\n CustomQueryBody,\n CustomQueryResult,\n GetDiscussionsParams,\n GetDiscussionsResult,\n TranslateJSONBody,\n TranslateJSONResult,\n} from '../types';\n\nexport type AskDocQuestionBody = {\n messages: ChatCompletionRequestMessage[];\n discussionId: string;\n onMessage?: (chunk: string) => void;\n onDone?: (response: AskDocQuestionResult) => void;\n};\n\nexport type { AskDocQuestionResult };\n\nexport const getAiAPI = (\n authAPIOptions: FetcherOptions = {},\n intlayerConfig?: IntlayerConfig\n) => {\n const backendURL =\n intlayerConfig?.editor?.backendURL ?? configuration?.editor?.backendURL;\n\n if (!backendURL) {\n throw new Error(\n 'Backend URL is not defined in the Intlayer configuration.'\n );\n }\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 errorMessage = JSON.stringify(errorData.error) ?? '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 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 return {\n customQuery,\n translateJSON,\n auditContentDeclaration,\n auditContentDeclarationField,\n auditContentDeclarationMetadata,\n auditTag,\n askDocQuestion,\n autocomplete,\n getDiscussions,\n };\n};\n"],"mappings":";;;;AAiCA,MAAa,YACX,iBAAiC,EAAE,EACnC,mBACG;CACH,MAAM,aACJ,gBAAgB,QAAQ,cAAc,eAAe,QAAQ;AAE/D,KAAI,CAAC,WACH,OAAM,IAAI,MACR,4DACD;CAGH,MAAM,eAAe,GAAG,WAAW;;;;;;CAOnC,MAAM,cAAc,OAClB,MACA,eAA+B,EAAE,KAEjC,MAAM,QACJ,cACA,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;;;CAOH,MAAM,gBAAgB,OACpB,MACA,eAA+B,EAAE,KAEjC,MAAM,QACJ,GAAG,aAAa,kBAChB,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;;;CAOH,MAAM,0BAA0B,OAC9B,MACA,eAA+B,EAAE,KAEjC,MAAM,QACJ,GAAG,aAAa,oBAChB,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;;;CAOH,MAAM,+BAA+B,OACnC,MACA,eAA+B,EAAE,KAEjC,MAAM,QACJ,GAAG,aAAa,0BAChB,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;;;CAOH,MAAM,kCAAkC,OACtC,MACA,eAA+B,EAAE,KA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AK,IAAI;AAExB,SAAK,MAAM,QAAQ,MACjB,KAAI,KAAK,WAAW,SAAS,CAC3B,KAAI;KACF,MAAM,OAAO,KAAK,MAAM,KAAK,MAAM,EAAE,CAAC;AACtC,SAAI,KAAK,MACP,aAAY,KAAK,MAAM;AAEzB,SAAI,KAAK,QAAQ,KAAK,SACpB,UAAS,KAAK,SAAS;aAElB,GAAG;AACV,aAAQ,MAAM,6BAA6B,EAAE;;;WAK9C,OAAO;AACd,WAAQ,MAAM,4BAA4B,MAAM;AAChD,SAAM;;;CAIV,MAAM,eAAe,OACnB,MACA,eAA+B,EAAE,KAEjC,MAAM,QACJ,GAAG,aAAa,gBAChB,gBACA,cACA;EACE,QAAQ;EACF;EACP,CACF;;;;CAKH,MAAM,iBAAiB,OACrB,QACA,eAA+B,EAAE,KAEjC,MAAM,QACJ,GAAG,aAAa,eAChB,gBACA,cACA;EACE,QAAQ;EAER;EACD,CACF;AAEH,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intlayer/api",
3
- "version": "7.1.5",
3
+ "version": "7.1.7",
4
4
  "private": false,
5
5
  "description": "SDK for interacting with the Intlayer API, enabling content auditing, and managing organizations, projects, and users.",
6
6
  "keywords": [
@@ -72,7 +72,7 @@
72
72
  "typecheck": "tsc --noEmit --project tsconfig.types.json"
73
73
  },
74
74
  "dependencies": {
75
- "@intlayer/config": "7.1.5"
75
+ "@intlayer/config": "7.1.7"
76
76
  },
77
77
  "devDependencies": {
78
78
  "@types/node": "24.10.1",
@@ -82,11 +82,11 @@
82
82
  "rimraf": "6.1.0",
83
83
  "tsdown": "0.16.5",
84
84
  "typescript": "5.9.3",
85
- "vitest": "4.0.8"
85
+ "vitest": "4.0.10"
86
86
  },
87
87
  "peerDependencies": {
88
- "@intlayer/backend": "7.1.5",
89
- "intlayer-editor": "7.1.5"
88
+ "@intlayer/backend": "7.1.7",
89
+ "intlayer-editor": "7.1.7"
90
90
  },
91
91
  "peerDependenciesMeta": {
92
92
  "@intlayer/backend": {