@intlayer/api 6.1.6 → 7.0.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/cjs/_virtual/rolldown_runtime.cjs +25 -0
  2. package/dist/cjs/distantDictionary/fetchDistantDictionaries.cjs +18 -55
  3. package/dist/cjs/distantDictionary/fetchDistantDictionaries.cjs.map +1 -1
  4. package/dist/cjs/distantDictionary/fetchDistantDictionary.cjs +20 -58
  5. package/dist/cjs/distantDictionary/fetchDistantDictionary.cjs.map +1 -1
  6. package/dist/cjs/distantDictionary/index.cjs +5 -25
  7. package/dist/cjs/fetcher.cjs +113 -89
  8. package/dist/cjs/fetcher.cjs.map +1 -1
  9. package/dist/cjs/getIntlayerAPI/ai.cjs +163 -188
  10. package/dist/cjs/getIntlayerAPI/ai.cjs.map +1 -1
  11. package/dist/cjs/getIntlayerAPI/dictionary.cjs +69 -117
  12. package/dist/cjs/getIntlayerAPI/dictionary.cjs.map +1 -1
  13. package/dist/cjs/getIntlayerAPI/editor.cjs +37 -74
  14. package/dist/cjs/getIntlayerAPI/editor.cjs.map +1 -1
  15. package/dist/cjs/getIntlayerAPI/index.cjs +27 -49
  16. package/dist/cjs/getIntlayerAPI/index.cjs.map +1 -1
  17. package/dist/cjs/getIntlayerAPI/newsletter.cjs +40 -77
  18. package/dist/cjs/getIntlayerAPI/newsletter.cjs.map +1 -1
  19. package/dist/cjs/getIntlayerAPI/oAuth.cjs +26 -65
  20. package/dist/cjs/getIntlayerAPI/oAuth.cjs.map +1 -1
  21. package/dist/cjs/getIntlayerAPI/organization.cjs +93 -130
  22. package/dist/cjs/getIntlayerAPI/organization.cjs.map +1 -1
  23. package/dist/cjs/getIntlayerAPI/project.cjs +109 -154
  24. package/dist/cjs/getIntlayerAPI/project.cjs.map +1 -1
  25. package/dist/cjs/getIntlayerAPI/search.cjs +22 -58
  26. package/dist/cjs/getIntlayerAPI/search.cjs.map +1 -1
  27. package/dist/cjs/getIntlayerAPI/stripe.cjs +38 -77
  28. package/dist/cjs/getIntlayerAPI/stripe.cjs.map +1 -1
  29. package/dist/cjs/getIntlayerAPI/tag.cjs +47 -86
  30. package/dist/cjs/getIntlayerAPI/tag.cjs.map +1 -1
  31. package/dist/cjs/getIntlayerAPI/user.cjs +79 -106
  32. package/dist/cjs/getIntlayerAPI/user.cjs.map +1 -1
  33. package/dist/cjs/index.cjs +30 -49
  34. package/dist/cjs/proxy.cjs +90 -115
  35. package/dist/cjs/proxy.cjs.map +1 -1
  36. package/dist/cjs/types.cjs +0 -17
  37. package/dist/esm/distantDictionary/fetchDistantDictionaries.mjs +17 -20
  38. package/dist/esm/distantDictionary/fetchDistantDictionaries.mjs.map +1 -1
  39. package/dist/esm/distantDictionary/fetchDistantDictionary.mjs +19 -23
  40. package/dist/esm/distantDictionary/fetchDistantDictionary.mjs.map +1 -1
  41. package/dist/esm/distantDictionary/index.mjs +4 -3
  42. package/dist/esm/fetcher.mjs +111 -64
  43. package/dist/esm/fetcher.mjs.map +1 -1
  44. package/dist/esm/getIntlayerAPI/ai.mjs +160 -153
  45. package/dist/esm/getIntlayerAPI/ai.mjs.map +1 -1
  46. package/dist/esm/getIntlayerAPI/dictionary.mjs +66 -82
  47. package/dist/esm/getIntlayerAPI/dictionary.mjs.map +1 -1
  48. package/dist/esm/getIntlayerAPI/editor.mjs +34 -39
  49. package/dist/esm/getIntlayerAPI/editor.mjs.map +1 -1
  50. package/dist/esm/getIntlayerAPI/index.mjs +16 -14
  51. package/dist/esm/getIntlayerAPI/index.mjs.map +1 -1
  52. package/dist/esm/getIntlayerAPI/newsletter.mjs +37 -42
  53. package/dist/esm/getIntlayerAPI/newsletter.mjs.map +1 -1
  54. package/dist/esm/getIntlayerAPI/oAuth.mjs +23 -30
  55. package/dist/esm/getIntlayerAPI/oAuth.mjs.map +1 -1
  56. package/dist/esm/getIntlayerAPI/organization.mjs +90 -95
  57. package/dist/esm/getIntlayerAPI/organization.mjs.map +1 -1
  58. package/dist/esm/getIntlayerAPI/project.mjs +106 -119
  59. package/dist/esm/getIntlayerAPI/project.mjs.map +1 -1
  60. package/dist/esm/getIntlayerAPI/search.mjs +19 -23
  61. package/dist/esm/getIntlayerAPI/search.mjs.map +1 -1
  62. package/dist/esm/getIntlayerAPI/stripe.mjs +35 -42
  63. package/dist/esm/getIntlayerAPI/stripe.mjs.map +1 -1
  64. package/dist/esm/getIntlayerAPI/tag.mjs +44 -51
  65. package/dist/esm/getIntlayerAPI/tag.mjs.map +1 -1
  66. package/dist/esm/getIntlayerAPI/user.mjs +76 -71
  67. package/dist/esm/getIntlayerAPI/user.mjs.map +1 -1
  68. package/dist/esm/index.mjs +16 -15
  69. package/dist/esm/proxy.mjs +89 -90
  70. package/dist/esm/proxy.mjs.map +1 -1
  71. package/dist/esm/types.mjs +0 -1
  72. package/dist/types/distantDictionary/fetchDistantDictionaries.d.ts +8 -3
  73. package/dist/types/distantDictionary/fetchDistantDictionaries.d.ts.map +1 -1
  74. package/dist/types/distantDictionary/fetchDistantDictionary.d.ts +8 -3
  75. package/dist/types/distantDictionary/fetchDistantDictionary.d.ts.map +1 -1
  76. package/dist/types/distantDictionary/index.d.ts +3 -3
  77. package/dist/types/fetcher.d.ts +14 -11
  78. package/dist/types/fetcher.d.ts.map +1 -1
  79. package/dist/types/getIntlayerAPI/ai.d.ts +22 -18
  80. package/dist/types/getIntlayerAPI/ai.d.ts.map +1 -1
  81. package/dist/types/getIntlayerAPI/dictionary.d.ts +16 -12
  82. package/dist/types/getIntlayerAPI/dictionary.d.ts.map +1 -1
  83. package/dist/types/getIntlayerAPI/editor.d.ts +11 -7
  84. package/dist/types/getIntlayerAPI/editor.d.ts.map +1 -1
  85. package/dist/types/getIntlayerAPI/index.d.ts +30 -27
  86. package/dist/types/getIntlayerAPI/index.d.ts.map +1 -1
  87. package/dist/types/getIntlayerAPI/newsletter.d.ts +11 -7
  88. package/dist/types/getIntlayerAPI/newsletter.d.ts.map +1 -1
  89. package/dist/types/getIntlayerAPI/oAuth.d.ts +8 -5
  90. package/dist/types/getIntlayerAPI/oAuth.d.ts.map +1 -1
  91. package/dist/types/getIntlayerAPI/organization.d.ts +18 -13
  92. package/dist/types/getIntlayerAPI/organization.d.ts.map +1 -1
  93. package/dist/types/getIntlayerAPI/project.d.ts +19 -15
  94. package/dist/types/getIntlayerAPI/project.d.ts.map +1 -1
  95. package/dist/types/getIntlayerAPI/search.d.ts +9 -5
  96. package/dist/types/getIntlayerAPI/search.d.ts.map +1 -1
  97. package/dist/types/getIntlayerAPI/stripe.d.ts +11 -7
  98. package/dist/types/getIntlayerAPI/stripe.d.ts.map +1 -1
  99. package/dist/types/getIntlayerAPI/tag.d.ts +12 -8
  100. package/dist/types/getIntlayerAPI/tag.d.ts.map +1 -1
  101. package/dist/types/getIntlayerAPI/user.d.ts +16 -12
  102. package/dist/types/getIntlayerAPI/user.d.ts.map +1 -1
  103. package/dist/types/index.d.ts +16 -15
  104. package/dist/types/proxy.d.ts +10 -5
  105. package/dist/types/proxy.d.ts.map +1 -1
  106. package/dist/types/types.d.ts +13 -12
  107. package/dist/types/types.d.ts.map +1 -1
  108. package/package.json +29 -38
  109. package/LICENSE +0 -202
  110. package/dist/cjs/distantDictionary/index.cjs.map +0 -1
  111. package/dist/cjs/index.cjs.map +0 -1
  112. package/dist/cjs/types.cjs.map +0 -1
  113. package/dist/esm/distantDictionary/index.mjs.map +0 -1
  114. package/dist/esm/index.mjs.map +0 -1
  115. package/dist/esm/types.mjs.map +0 -1
  116. package/dist/types/distantDictionary/index.d.ts.map +0 -1
  117. package/dist/types/index.d.ts.map +0 -1
@@ -1,73 +1,120 @@
1
+ //#region src/fetcher.ts
2
+ /**
3
+ * Default options for the fetcher function.
4
+ * Sets the default method to 'GET', the 'Content-Type' header to 'application/json',
5
+ * and includes credentials in the request.
6
+ */
1
7
  const fetcherOptions = {
2
- method: "GET",
3
- // Default HTTP method
4
- headers: {
5
- "Content-Type": "application/json"
6
- // Default content type
7
- },
8
- credentials: "include"
8
+ method: "GET",
9
+ headers: { "Content-Type": "application/json" },
10
+ credentials: "include"
9
11
  };
12
+ /**
13
+ * Utility function to remove properties with undefined values from an object.
14
+ * This helps prevent sending undefined values in the request options.
15
+ *
16
+ * @param obj - The object to clean.
17
+ * @returns The cleaned object without undefined values.
18
+ */
10
19
  const removeUndefined = (obj) => {
11
- Object.keys(obj).forEach((key) => {
12
- if (obj[key] === void 0) {
13
- delete obj[key];
14
- }
15
- });
16
- return obj;
20
+ Object.keys(obj).forEach((key) => {
21
+ if (obj[key] === void 0) delete obj[key];
22
+ });
23
+ return obj;
17
24
  };
25
+ /**
26
+ * Deeply merges an array of objects into a single object.
27
+ * Later objects in the array overwrite properties of earlier ones.
28
+ *
29
+ * @template T - The type of objects being merged.
30
+ * @param objects - An array of objects to merge.
31
+ * @returns The merged object.
32
+ */
18
33
  const deepMerge = (objects) => objects.reduce((acc, obj) => {
19
- const acc1 = acc ?? {};
20
- const obj1 = removeUndefined(obj ?? {});
21
- if (typeof acc1 === "object" && typeof obj1 === "object") {
22
- return { ...acc1, ...obj1 };
23
- }
24
- return obj1 ?? acc1;
34
+ const acc1 = acc ?? {};
35
+ const obj1 = removeUndefined(obj ?? {});
36
+ if (typeof acc1 === "object" && typeof obj1 === "object") return {
37
+ ...acc1,
38
+ ...obj1
39
+ };
40
+ return obj1 ?? acc1;
25
41
  }, {});
42
+ /**
43
+ * Fetcher function to make HTTP requests.
44
+ * It merges default options with user-provided options,
45
+ * handles query parameters and request body,
46
+ * and returns the parsed JSON response.
47
+ *
48
+ * @template T - The expected type of the response data.
49
+ * @param url - The endpoint URL.
50
+ * @param options - Additional options to customize the request.
51
+ * @returns A promise that resolves with the response data of type T.
52
+ *
53
+ * @example
54
+ * ```typescript
55
+ * // Making a GET request with query parameters
56
+ * const data = await fetcher<MyResponseType>('https://api.example.com/data', {
57
+ * params: { search: 'query' },
58
+ * });
59
+ *
60
+ * // Making a POST request with a JSON body
61
+ * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {
62
+ * method: 'POST',
63
+ * body: { key: 'value' },
64
+ * });
65
+ *
66
+ * // Merge body, headers, and params
67
+ * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {
68
+ * method: 'POST',
69
+ * body: { key: 'value' },
70
+ * headers: { 'Content-Type': 'application/json' },
71
+ * params: { search: 'query' },
72
+ * },
73
+ * {
74
+ * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
75
+ * params: { page: 1 },
76
+ * });
77
+ * ```
78
+ *
79
+ * Result:
80
+ * ```typescript
81
+ * {
82
+ * method: 'POST',
83
+ * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
84
+ * params: { page: 1, search: 'query' },
85
+ * body: { key: 'value' },
86
+ * }
87
+ * ```
88
+ */
26
89
  const fetcher = async (url, ...options) => {
27
- const { signal } = new AbortController();
28
- let paramsString = "";
29
- let bodyString = void 0;
30
- const otherOptions = options.map(
31
- ({ body, params: params2, headers, ...otherOptions2 }) => otherOptions2
32
- );
33
- const mergedOptions = deepMerge([fetcherOptions, ...otherOptions]);
34
- const mergedHeaders = deepMerge([
35
- fetcherOptions.headers,
36
- ...options.map((option) => option.headers)
37
- ]);
38
- const params = deepMerge(options.map((option) => option.params));
39
- const method = mergedOptions.method;
40
- if (method !== "GET" && method !== "HEAD") {
41
- const body = deepMerge(options.map((option) => option.body));
42
- if (mergedHeaders?.["Content-Type"] === "application/x-www-form-urlencoded") {
43
- bodyString = new URLSearchParams(
44
- body
45
- ).toString();
46
- } else {
47
- bodyString = JSON.stringify(body);
48
- }
49
- }
50
- if (Object.entries(params).length > 0) {
51
- paramsString = `?${new URLSearchParams(
52
- params
53
- ).toString()}`;
54
- }
55
- const formattedOptions = {
56
- ...mergedOptions,
57
- headers: mergedHeaders,
58
- body: bodyString,
59
- signal
60
- };
61
- const urlResult = `${url}${paramsString}`;
62
- const response = await fetch(urlResult, formattedOptions);
63
- if (!response.ok) {
64
- const result = await response.json();
65
- throw new Error(JSON.stringify(result.error) ?? "An error occurred");
66
- }
67
- return await response.json();
68
- };
69
- export {
70
- fetcher,
71
- fetcherOptions
90
+ const { signal } = new AbortController();
91
+ let paramsString = "";
92
+ let bodyString;
93
+ const mergedOptions = deepMerge([fetcherOptions, ...options.map(({ body, params: params$1, headers,...otherOptions }) => otherOptions)]);
94
+ const mergedHeaders = deepMerge([fetcherOptions.headers, ...options.map((option) => option.headers)]);
95
+ const params = deepMerge(options.map((option) => option.params));
96
+ const method = mergedOptions.method;
97
+ if (method !== "GET" && method !== "HEAD") {
98
+ const body = deepMerge(options.map((option) => option.body));
99
+ if (mergedHeaders?.["Content-Type"] === "application/x-www-form-urlencoded") bodyString = new URLSearchParams(body).toString();
100
+ else bodyString = JSON.stringify(body);
101
+ }
102
+ if (Object.entries(params).length > 0) paramsString = `?${new URLSearchParams(params).toString()}`;
103
+ const formattedOptions = {
104
+ ...mergedOptions,
105
+ headers: mergedHeaders,
106
+ body: bodyString,
107
+ signal
108
+ };
109
+ const urlResult = `${url}${paramsString}`;
110
+ const response = await fetch(urlResult, formattedOptions);
111
+ if (!response.ok) {
112
+ const result = await response.json();
113
+ throw new Error(JSON.stringify(result.error) ?? "An error occurred");
114
+ }
115
+ return await response.json();
72
116
  };
117
+
118
+ //#endregion
119
+ export { fetcher, fetcherOptions };
73
120
  //# sourceMappingURL=fetcher.mjs.map
@@ -1 +1 @@
1
- {"version":3,"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 = 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 }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C;AAC3D,QACE,gBAAgB,cAAmC,MACnD,qCACA;AAEA,mBAAa,IAAI;AAAA,QACf;AAAA,MACF,EAAE,SAAS;AAAA,IACb,OAAO;AAEL,mBAAa,KAAK,UAAU,IAAI;AAAA,IAClC;AAAA,EACF;AAGA,MAAI,OAAO,QAAQ,MAAM,EAAE,SAAS,GAAG;AACrC,mBAAe,IAAI,IAAI;AAAA,MACrB;AAAA,IACF,EAAE,SAAS,CAAC;AAAA,EACd;AAGA,QAAM,mBAAgC;AAAA,IACpC,GAAG;AAAA,IACH,SAAS;AAAA,IACT,MAAM;AAAA,IACN;AAAA,EACF;AAGA,QAAM,YAAY,GAAG,GAAG,GAAG,YAAY;AAGvC,QAAM,WAAW,MAAM,MAAM,WAAW,gBAAgB;AAExD,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,SAAS,MAAM,SAAS,KAAK;AAGnC,UAAM,IAAI,MAAM,KAAK,UAAU,OAAO,KAAK,KAAK,mBAAmB;AAAA,EACrE;AACA,SAAO,MAAM,SAAS,KAAK;AAC7B;","names":["params","otherOptions"]}
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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;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,157 +1,164 @@
1
- import configuration from "@intlayer/config/built";
2
1
  import { fetcher } from "../fetcher.mjs";
2
+ import configuration from "@intlayer/config/built";
3
+
4
+ //#region src/getIntlayerAPI/ai.ts
3
5
  const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
4
- const backendURL = intlayerConfig?.editor?.backendURL ?? configuration.editor?.backendURL;
5
- if (!backendURL) {
6
- throw new Error(
7
- "Backend URL is not defined in the Intlayer configuration."
8
- );
9
- }
10
- const AI_API_ROUTE = `${backendURL}/api/ai`;
11
- const customQuery = async (body, otherOptions = {}) => await fetcher(
12
- AI_API_ROUTE,
13
- authAPIOptions,
14
- otherOptions,
15
- {
16
- method: "POST",
17
- body
18
- }
19
- );
20
- const translateJSON = async (body, otherOptions = {}) => await fetcher(
21
- `${AI_API_ROUTE}/translate/json`,
22
- authAPIOptions,
23
- otherOptions,
24
- {
25
- method: "POST",
26
- body
27
- }
28
- );
29
- const auditContentDeclaration = async (body, otherOptions = {}) => await fetcher(
30
- `${AI_API_ROUTE}/audit/dictionary`,
31
- authAPIOptions,
32
- otherOptions,
33
- {
34
- method: "POST",
35
- body
36
- }
37
- );
38
- const auditContentDeclarationField = async (body, otherOptions = {}) => await fetcher(
39
- `${AI_API_ROUTE}/audit/dictionary/field`,
40
- authAPIOptions,
41
- otherOptions,
42
- {
43
- method: "POST",
44
- body
45
- }
46
- );
47
- const auditContentDeclarationMetadata = async (body, otherOptions = {}) => await fetcher(
48
- `${AI_API_ROUTE}/audit/dictionary/metadata`,
49
- authAPIOptions,
50
- otherOptions,
51
- {
52
- method: "POST",
53
- body
54
- }
55
- );
56
- const auditTag = async (body, otherOptions = {}) => await fetcher(
57
- `${AI_API_ROUTE}/audit/tag`,
58
- authAPIOptions,
59
- otherOptions,
60
- {
61
- method: "POST",
62
- body
63
- }
64
- );
65
- const askDocQuestion = async (body, otherOptions = {}) => {
66
- if (!body) return;
67
- const { onMessage, onDone, ...rest } = body;
68
- const abortController = new AbortController();
69
- try {
70
- const response = await fetch(`${AI_API_ROUTE}/ask`, {
71
- method: "POST",
72
- headers: {
73
- "Content-Type": "application/json",
74
- ...authAPIOptions.headers,
75
- ...otherOptions.headers
76
- },
77
- body: JSON.stringify({
78
- ...rest,
79
- ...authAPIOptions.body,
80
- ...otherOptions.body
81
- }),
82
- signal: abortController.signal,
83
- credentials: "include"
84
- });
85
- if (!response.ok) {
86
- let errorMessage = "An error occurred";
87
- try {
88
- const errorData = await response.json();
89
- errorMessage = JSON.stringify(errorData.error) ?? "An error occurred";
90
- } catch {
91
- try {
92
- const errorText = await response.text();
93
- if (errorText) {
94
- errorMessage = errorText;
95
- }
96
- } catch {
97
- }
98
- }
99
- throw new Error(errorMessage);
100
- }
101
- const reader = response.body?.getReader();
102
- if (!reader) {
103
- throw new Error("No reader available");
104
- }
105
- const decoder = new TextDecoder();
106
- let buffer = "";
107
- while (true) {
108
- const { done, value } = await reader.read();
109
- if (done) break;
110
- buffer += decoder.decode(value, { stream: true });
111
- const lines = buffer.split("\n");
112
- buffer = lines.pop() ?? "";
113
- for (const line of lines) {
114
- if (line.startsWith("data: ")) {
115
- try {
116
- const data = JSON.parse(line.slice(6));
117
- if (data.chunk) {
118
- onMessage?.(data.chunk);
119
- }
120
- if (data.done && data.response) {
121
- onDone?.(data.response);
122
- }
123
- } catch (e) {
124
- console.error("Failed to parse SSE data:", e);
125
- }
126
- }
127
- }
128
- }
129
- } catch (error) {
130
- console.error("Error in askDocQuestion:", error);
131
- throw error;
132
- }
133
- };
134
- const autocomplete = async (body, otherOptions = {}) => await fetcher(
135
- `${AI_API_ROUTE}/autocomplete`,
136
- authAPIOptions,
137
- otherOptions,
138
- {
139
- method: "POST",
140
- body
141
- }
142
- );
143
- return {
144
- customQuery,
145
- translateJSON,
146
- auditContentDeclaration,
147
- auditContentDeclarationField,
148
- auditContentDeclarationMetadata,
149
- auditTag,
150
- askDocQuestion,
151
- autocomplete
152
- };
153
- };
154
- export {
155
- getAiAPI
6
+ const backendURL = intlayerConfig?.editor?.backendURL ?? configuration?.editor?.backendURL;
7
+ if (!backendURL) throw new Error("Backend URL is not defined in the Intlayer configuration.");
8
+ const AI_API_ROUTE = `${backendURL}/api/ai`;
9
+ /**
10
+ * Custom query
11
+ * @param body - Custom query parameters.
12
+ * @returns Custom query result.
13
+ */
14
+ const customQuery = async (body, otherOptions = {}) => await fetcher(AI_API_ROUTE, authAPIOptions, otherOptions, {
15
+ method: "POST",
16
+ body
17
+ });
18
+ /**
19
+ * Translate a JSON
20
+ * @param body - Audit file parameters.
21
+ * @returns Audited file content.
22
+ */
23
+ const translateJSON = async (body, otherOptions = {}) => await fetcher(`${AI_API_ROUTE}/translate/json`, authAPIOptions, otherOptions, {
24
+ method: "POST",
25
+ body
26
+ });
27
+ /**
28
+ * Audits a content declaration file
29
+ * @param body - Audit file parameters.
30
+ * @returns Audited file content.
31
+ */
32
+ const auditContentDeclaration = async (body, otherOptions = {}) => await fetcher(`${AI_API_ROUTE}/audit/dictionary`, authAPIOptions, otherOptions, {
33
+ method: "POST",
34
+ body
35
+ });
36
+ /**
37
+ * Audits a content declaration field
38
+ * @param body - Audit file parameters.
39
+ * @returns Audited file content.
40
+ */
41
+ const auditContentDeclarationField = async (body, otherOptions = {}) => await fetcher(`${AI_API_ROUTE}/audit/dictionary/field`, authAPIOptions, otherOptions, {
42
+ method: "POST",
43
+ body
44
+ });
45
+ /**
46
+ * Audits a content declaration file to retrieve title, description and tags
47
+ * @param body - Audit file parameters.
48
+ * @returns Audited file content.
49
+ */
50
+ const auditContentDeclarationMetadata = async (body, otherOptions = {}) => await fetcher(`${AI_API_ROUTE}/audit/dictionary/metadata`, authAPIOptions, otherOptions, {
51
+ method: "POST",
52
+ body
53
+ });
54
+ /**
55
+ * Audits a tag
56
+ * @param body - Audit tag parameters.
57
+ * @returns Audited tag content.
58
+ */
59
+ const auditTag = async (body, otherOptions = {}) => await fetcher(`${AI_API_ROUTE}/audit/tag`, authAPIOptions, otherOptions, {
60
+ method: "POST",
61
+ body
62
+ });
63
+ /**
64
+ * Asks a question to the AI related to the documentation **and streams the
65
+ * answer as Server‑Sent Events (SSE)**.
66
+ *
67
+ * The function **returns immediately** with a handle exposing:
68
+ * - `promise` → resolves when the stream completes (or rejects on error)
69
+ * - `abort()` allows canceling the request on demand
70
+ *
71
+ * Usage example:
72
+ * ```ts
73
+ * const { promise, abort } = ai.askDocQuestion({
74
+ * ...body,
75
+ * onMessage: console.log,
76
+ * onDone: (full) => console.log("✔", full),
77
+ * });
78
+ * // later → abort();
79
+ * await promise; // waits for completion if desired
80
+ * ```
81
+ */
82
+ const askDocQuestion = async (body, otherOptions = {}) => {
83
+ if (!body) return;
84
+ const { onMessage, onDone,...rest } = body;
85
+ const abortController = new AbortController();
86
+ try {
87
+ const response = await fetch(`${AI_API_ROUTE}/ask`, {
88
+ method: "POST",
89
+ headers: {
90
+ "Content-Type": "application/json",
91
+ ...authAPIOptions.headers,
92
+ ...otherOptions.headers
93
+ },
94
+ body: JSON.stringify({
95
+ ...rest,
96
+ ...authAPIOptions.body,
97
+ ...otherOptions.body
98
+ }),
99
+ signal: abortController.signal,
100
+ credentials: "include"
101
+ });
102
+ if (!response.ok) {
103
+ let errorMessage = "An error occurred";
104
+ try {
105
+ const errorData = await response.json();
106
+ errorMessage = JSON.stringify(errorData.error) ?? "An error occurred";
107
+ } catch {
108
+ try {
109
+ const errorText = await response.text();
110
+ if (errorText) errorMessage = errorText;
111
+ } catch {}
112
+ }
113
+ throw new Error(errorMessage);
114
+ }
115
+ const reader = response.body?.getReader();
116
+ if (!reader) throw new Error("No reader available");
117
+ const decoder = new TextDecoder();
118
+ let buffer = "";
119
+ while (true) {
120
+ const { done, value } = await reader.read();
121
+ if (done) break;
122
+ buffer += decoder.decode(value, { stream: true });
123
+ const lines = buffer.split("\n");
124
+ buffer = lines.pop() ?? "";
125
+ for (const line of lines) if (line.startsWith("data: ")) try {
126
+ const data = JSON.parse(line.slice(6));
127
+ if (data.chunk) onMessage?.(data.chunk);
128
+ if (data.done && data.response) onDone?.(data.response);
129
+ } catch (e) {
130
+ console.error("Failed to parse SSE data:", e);
131
+ }
132
+ }
133
+ } catch (error) {
134
+ console.error("Error in askDocQuestion:", error);
135
+ throw error;
136
+ }
137
+ };
138
+ const autocomplete = async (body, otherOptions = {}) => await fetcher(`${AI_API_ROUTE}/autocomplete`, authAPIOptions, otherOptions, {
139
+ method: "POST",
140
+ body
141
+ });
142
+ /**
143
+ * Retrieves discussions with filters and pagination. Only user or admin can access.
144
+ */
145
+ const getDiscussions = async (params, otherOptions = {}) => await fetcher(`${AI_API_ROUTE}/discussions`, authAPIOptions, otherOptions, {
146
+ method: "GET",
147
+ params
148
+ });
149
+ return {
150
+ customQuery,
151
+ translateJSON,
152
+ auditContentDeclaration,
153
+ auditContentDeclarationField,
154
+ auditContentDeclarationMetadata,
155
+ auditTag,
156
+ askDocQuestion,
157
+ autocomplete,
158
+ getDiscussions
159
+ };
156
160
  };
161
+
162
+ //#endregion
163
+ export { getAiAPI };
157
164
  //# sourceMappingURL=ai.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/getIntlayerAPI/ai.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/config/client';\nimport { fetcher, type FetcherOptions } 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 TranslateJSONBody,\n TranslateJSONResult,\n} from '../types';\n\nexport type AskDocQuestionBody = {\n messages: ChatCompletionRequestMessage[];\n discutionId: 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 return {\n customQuery,\n translateJSON,\n auditContentDeclaration,\n auditContentDeclarationField,\n auditContentDeclarationMetadata,\n auditTag,\n askDocQuestion,\n autocomplete,\n };\n};\n"],"mappings":"AAAA,OAAO,mBAAmB;AAE1B,SAAS,eAAoC;AA6BtC,MAAM,WAAW,CACtB,iBAAiC,CAAC,GAClC,mBACG;AACH,QAAM,aACJ,gBAAgB,QAAQ,cAAc,cAAc,QAAQ;AAE9D,MAAI,CAAC,YAAY;AACf,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AA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KAAK,QAAQ;AAAA,cACxB;AAAA,YACF,SAAS,GAAG;AACV,sBAAQ,MAAM,6BAA6B,CAAC;AAAA,YAC9C;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AACd,cAAQ,MAAM,4BAA4B,KAAK;AAC/C,YAAM;AAAA,IACR;AAAA,EACF;AAEA,QAAM,eAAe,OACnB,MACA,eAA+B,CAAC,MAEhC,MAAM;AAAA,IACJ,GAAG,YAAY;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEF,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
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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