@intlayer/api 8.1.2 → 8.1.3-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 (86) hide show
  1. package/dist/cjs/_virtual/_rolldown/runtime.cjs +1 -29
  2. package/dist/cjs/distantDictionary/fetchDistantDictionaries.cjs +1 -20
  3. package/dist/cjs/distantDictionary/fetchDistantDictionaries.cjs.map +1 -1
  4. package/dist/cjs/distantDictionary/fetchDistantDictionary.cjs +1 -22
  5. package/dist/cjs/distantDictionary/fetchDistantDictionary.cjs.map +1 -1
  6. package/dist/cjs/distantDictionary/index.cjs +1 -6
  7. package/dist/cjs/fetcher.cjs +1 -122
  8. package/dist/cjs/fetcher.cjs.map +1 -1
  9. package/dist/cjs/getIntlayerAPI/ai.cjs +2 -166
  10. package/dist/cjs/getIntlayerAPI/ai.cjs.map +1 -1
  11. package/dist/cjs/getIntlayerAPI/audit.cjs +1 -41
  12. package/dist/cjs/getIntlayerAPI/audit.cjs.map +1 -1
  13. package/dist/cjs/getIntlayerAPI/bitbucket.cjs +1 -74
  14. package/dist/cjs/getIntlayerAPI/bitbucket.cjs.map +1 -1
  15. package/dist/cjs/getIntlayerAPI/dictionary.cjs +1 -72
  16. package/dist/cjs/getIntlayerAPI/dictionary.cjs.map +1 -1
  17. package/dist/cjs/getIntlayerAPI/editor.cjs +1 -40
  18. package/dist/cjs/getIntlayerAPI/editor.cjs.map +1 -1
  19. package/dist/cjs/getIntlayerAPI/github.cjs +1 -74
  20. package/dist/cjs/getIntlayerAPI/github.cjs.map +1 -1
  21. package/dist/cjs/getIntlayerAPI/gitlab.cjs +1 -88
  22. package/dist/cjs/getIntlayerAPI/gitlab.cjs.map +1 -1
  23. package/dist/cjs/getIntlayerAPI/index.cjs +1 -38
  24. package/dist/cjs/getIntlayerAPI/index.cjs.map +1 -1
  25. package/dist/cjs/getIntlayerAPI/newsletter.cjs +1 -43
  26. package/dist/cjs/getIntlayerAPI/newsletter.cjs.map +1 -1
  27. package/dist/cjs/getIntlayerAPI/oAuth.cjs +1 -29
  28. package/dist/cjs/getIntlayerAPI/oAuth.cjs.map +1 -1
  29. package/dist/cjs/getIntlayerAPI/organization.cjs +1 -96
  30. package/dist/cjs/getIntlayerAPI/organization.cjs.map +1 -1
  31. package/dist/cjs/getIntlayerAPI/project.cjs +1 -144
  32. package/dist/cjs/getIntlayerAPI/project.cjs.map +1 -1
  33. package/dist/cjs/getIntlayerAPI/search.cjs +1 -25
  34. package/dist/cjs/getIntlayerAPI/search.cjs.map +1 -1
  35. package/dist/cjs/getIntlayerAPI/stripe.cjs +1 -41
  36. package/dist/cjs/getIntlayerAPI/stripe.cjs.map +1 -1
  37. package/dist/cjs/getIntlayerAPI/tag.cjs +1 -50
  38. package/dist/cjs/getIntlayerAPI/tag.cjs.map +1 -1
  39. package/dist/cjs/getIntlayerAPI/user.cjs +1 -82
  40. package/dist/cjs/getIntlayerAPI/user.cjs.map +1 -1
  41. package/dist/cjs/index.cjs +1 -43
  42. package/dist/cjs/proxy.cjs +1 -101
  43. package/dist/cjs/proxy.cjs.map +1 -1
  44. package/dist/esm/distantDictionary/fetchDistantDictionaries.mjs +1 -19
  45. package/dist/esm/distantDictionary/fetchDistantDictionaries.mjs.map +1 -1
  46. package/dist/esm/distantDictionary/fetchDistantDictionary.mjs +1 -21
  47. package/dist/esm/distantDictionary/fetchDistantDictionary.mjs.map +1 -1
  48. package/dist/esm/distantDictionary/index.mjs +1 -4
  49. package/dist/esm/fetcher.mjs +1 -119
  50. package/dist/esm/fetcher.mjs.map +1 -1
  51. package/dist/esm/getIntlayerAPI/ai.mjs +2 -163
  52. package/dist/esm/getIntlayerAPI/ai.mjs.map +1 -1
  53. package/dist/esm/getIntlayerAPI/audit.mjs +1 -38
  54. package/dist/esm/getIntlayerAPI/audit.mjs.map +1 -1
  55. package/dist/esm/getIntlayerAPI/bitbucket.mjs +1 -71
  56. package/dist/esm/getIntlayerAPI/bitbucket.mjs.map +1 -1
  57. package/dist/esm/getIntlayerAPI/dictionary.mjs +1 -69
  58. package/dist/esm/getIntlayerAPI/dictionary.mjs.map +1 -1
  59. package/dist/esm/getIntlayerAPI/editor.mjs +1 -37
  60. package/dist/esm/getIntlayerAPI/editor.mjs.map +1 -1
  61. package/dist/esm/getIntlayerAPI/github.mjs +1 -71
  62. package/dist/esm/getIntlayerAPI/github.mjs.map +1 -1
  63. package/dist/esm/getIntlayerAPI/gitlab.mjs +1 -85
  64. package/dist/esm/getIntlayerAPI/gitlab.mjs.map +1 -1
  65. package/dist/esm/getIntlayerAPI/index.mjs +1 -37
  66. package/dist/esm/getIntlayerAPI/index.mjs.map +1 -1
  67. package/dist/esm/getIntlayerAPI/newsletter.mjs +1 -40
  68. package/dist/esm/getIntlayerAPI/newsletter.mjs.map +1 -1
  69. package/dist/esm/getIntlayerAPI/oAuth.mjs +1 -26
  70. package/dist/esm/getIntlayerAPI/oAuth.mjs.map +1 -1
  71. package/dist/esm/getIntlayerAPI/organization.mjs +1 -93
  72. package/dist/esm/getIntlayerAPI/organization.mjs.map +1 -1
  73. package/dist/esm/getIntlayerAPI/project.mjs +1 -141
  74. package/dist/esm/getIntlayerAPI/project.mjs.map +1 -1
  75. package/dist/esm/getIntlayerAPI/search.mjs +1 -22
  76. package/dist/esm/getIntlayerAPI/search.mjs.map +1 -1
  77. package/dist/esm/getIntlayerAPI/stripe.mjs +1 -38
  78. package/dist/esm/getIntlayerAPI/stripe.mjs.map +1 -1
  79. package/dist/esm/getIntlayerAPI/tag.mjs +1 -47
  80. package/dist/esm/getIntlayerAPI/tag.mjs.map +1 -1
  81. package/dist/esm/getIntlayerAPI/user.mjs +1 -79
  82. package/dist/esm/getIntlayerAPI/user.mjs.map +1 -1
  83. package/dist/esm/index.mjs +1 -22
  84. package/dist/esm/proxy.mjs +1 -100
  85. package/dist/esm/proxy.mjs.map +1 -1
  86. package/package.json +5 -5
@@ -1,29 +1 @@
1
- //#region \0rolldown/runtime.js
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) {
13
- __defProp(to, key, {
14
- get: ((k) => from[k]).bind(null, key),
15
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
- });
17
- }
18
- }
19
- }
20
- return to;
21
- };
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
- value: mod,
24
- enumerable: true
25
- }) : target, mod));
26
-
27
- //#endregion
28
-
29
- exports.__toESM = __toESM;
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));exports.__toESM=s;
@@ -1,21 +1,2 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_proxy = require('../proxy.cjs');
3
-
4
- //#region src/distantDictionary/fetchDistantDictionaries.ts
5
- /**
6
- * Fetch distant dictionary
7
- */
8
- const fetchDistantDictionaries = async (intlayerConfig) => {
9
- try {
10
- const { clientId, clientSecret } = intlayerConfig.editor;
11
- if (!clientId || !clientSecret) throw new Error("Missing OAuth2 client ID or client secret. To get access token go to https://app.intlayer.org/project.");
12
- return (await require_proxy.getIntlayerAPIProxy(void 0, intlayerConfig).dictionary.getDictionaries()).data;
13
- } catch (error) {
14
- console.error(error);
15
- return;
16
- }
17
- };
18
-
19
- //#endregion
20
- exports.fetchDistantDictionaries = fetchDistantDictionaries;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../proxy.cjs`),t=async t=>{try{let{clientId:n,clientSecret:r}=t.editor;if(!n||!r)throw Error(`Missing OAuth2 client ID or client secret. To get access token go to https://app.intlayer.org/project.`);return(await e.getIntlayerAPIProxy(void 0,t).dictionary.getDictionaries()).data}catch(e){console.error(e);return}};exports.fetchDistantDictionaries=t;
21
2
  //# sourceMappingURL=fetchDistantDictionaries.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetchDistantDictionaries.cjs","names":["getIntlayerAPIProxy"],"sources":["../../../src/distantDictionary/fetchDistantDictionaries.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types';\nimport { getIntlayerAPIProxy } from '../proxy';\nimport type { DictionaryAPI } from '../types';\n\n/**\n * Fetch distant dictionary\n */\nexport const fetchDistantDictionaries = async (\n intlayerConfig: IntlayerConfig\n): Promise<DictionaryAPI[] | null | undefined> => {\n try {\n const { clientId, clientSecret } = intlayerConfig.editor;\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://app.intlayer.org/project.'\n );\n }\n\n const api = getIntlayerAPIProxy(undefined, intlayerConfig);\n\n // Fetch the dictionary list\n const getDictionaryResult = await api.dictionary.getDictionaries();\n\n const distantDictionaries = getDictionaryResult.data;\n\n return distantDictionaries;\n } catch (error) {\n console.error(error);\n return undefined;\n }\n};\n"],"mappings":";;;;;;;AAOA,MAAa,2BAA2B,OACtC,mBACgD;AAChD,KAAI;EACF,MAAM,EAAE,UAAU,iBAAiB,eAAe;AAElD,MAAI,CAAC,YAAY,CAAC,aAChB,OAAM,IAAI,MACR,yGACD;AAUH,UAJ4B,MAHhBA,kCAAoB,QAAW,eAAe,CAGpB,WAAW,iBAAiB,EAElB;UAGzC,OAAO;AACd,UAAQ,MAAM,MAAM;AACpB"}
1
+ {"version":3,"file":"fetchDistantDictionaries.cjs","names":["getIntlayerAPIProxy"],"sources":["../../../src/distantDictionary/fetchDistantDictionaries.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types';\nimport { getIntlayerAPIProxy } from '../proxy';\nimport type { DictionaryAPI } from '../types';\n\n/**\n * Fetch distant dictionary\n */\nexport const fetchDistantDictionaries = async (\n intlayerConfig: IntlayerConfig\n): Promise<DictionaryAPI[] | null | undefined> => {\n try {\n const { clientId, clientSecret } = intlayerConfig.editor;\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://app.intlayer.org/project.'\n );\n }\n\n const api = getIntlayerAPIProxy(undefined, intlayerConfig);\n\n // Fetch the dictionary list\n const getDictionaryResult = await api.dictionary.getDictionaries();\n\n const distantDictionaries = getDictionaryResult.data;\n\n return distantDictionaries;\n } catch (error) {\n console.error(error);\n return undefined;\n }\n};\n"],"mappings":"mGAOa,EAA2B,KACtC,IACgD,CAChD,GAAI,CACF,GAAM,CAAE,WAAU,gBAAiB,EAAe,OAElD,GAAI,CAAC,GAAY,CAAC,EAChB,MAAU,MACR,yGACD,CAUH,OAJ4B,MAHhBA,EAAAA,oBAAoB,IAAA,GAAW,EAAe,CAGpB,WAAW,iBAAiB,EAElB,WAGzC,EAAO,CACd,QAAQ,MAAM,EAAM,CACpB"}
@@ -1,23 +1,2 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_proxy = require('../proxy.cjs');
3
-
4
- //#region src/distantDictionary/fetchDistantDictionary.ts
5
- /**
6
- * Fetch distant dictionary
7
- */
8
- const fetchDistantDictionary = async (dictionaryKey, intlayerConfig) => {
9
- try {
10
- const { clientId, clientSecret } = intlayerConfig.editor;
11
- if (!clientId || !clientSecret) throw new Error("Missing OAuth2 client ID or client secret. To get access token go to https://app.intlayer.org/project.");
12
- const distantDictionary = (await require_proxy.getIntlayerAPIProxy(void 0, intlayerConfig).dictionary.getDictionary(dictionaryKey)).data;
13
- if (!distantDictionary) throw new Error(`Dictionary ${dictionaryKey} not found on remote`);
14
- return distantDictionary;
15
- } catch (error) {
16
- console.error(error);
17
- return;
18
- }
19
- };
20
-
21
- //#endregion
22
- exports.fetchDistantDictionary = fetchDistantDictionary;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../proxy.cjs`),t=async(t,n)=>{try{let{clientId:r,clientSecret:i}=n.editor;if(!r||!i)throw Error(`Missing OAuth2 client ID or client secret. To get access token go to https://app.intlayer.org/project.`);let a=(await e.getIntlayerAPIProxy(void 0,n).dictionary.getDictionary(t)).data;if(!a)throw Error(`Dictionary ${t} not found on remote`);return a}catch(e){console.error(e);return}};exports.fetchDistantDictionary=t;
23
2
  //# sourceMappingURL=fetchDistantDictionary.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetchDistantDictionary.cjs","names":["getIntlayerAPIProxy"],"sources":["../../../src/distantDictionary/fetchDistantDictionary.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types';\nimport { getIntlayerAPIProxy } from '../proxy';\nimport type { DictionaryAPI } from '../types';\n\n/**\n * Fetch distant dictionary\n */\nexport const fetchDistantDictionary = async (\n dictionaryKey: string,\n intlayerConfig: IntlayerConfig\n): Promise<DictionaryAPI | undefined> => {\n try {\n const { clientId, clientSecret } = intlayerConfig.editor;\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://app.intlayer.org/project.'\n );\n }\n\n const api = getIntlayerAPIProxy(undefined, intlayerConfig);\n\n // Fetch the dictionary\n const getDictionaryResult =\n await api.dictionary.getDictionary(dictionaryKey);\n\n const distantDictionary = getDictionaryResult.data;\n\n if (!distantDictionary) {\n throw new Error(`Dictionary ${dictionaryKey} not found on remote`);\n }\n\n return distantDictionary;\n } catch (error) {\n console.error(error);\n return undefined;\n }\n};\n"],"mappings":";;;;;;;AAOA,MAAa,yBAAyB,OACpC,eACA,mBACuC;AACvC,KAAI;EACF,MAAM,EAAE,UAAU,iBAAiB,eAAe;AAElD,MAAI,CAAC,YAAY,CAAC,aAChB,OAAM,IAAI,MACR,yGACD;EASH,MAAM,qBAFJ,MAJUA,kCAAoB,QAAW,eAAe,CAI9C,WAAW,cAAc,cAAc,EAEL;AAE9C,MAAI,CAAC,kBACH,OAAM,IAAI,MAAM,cAAc,cAAc,sBAAsB;AAGpE,SAAO;UACA,OAAO;AACd,UAAQ,MAAM,MAAM;AACpB"}
1
+ {"version":3,"file":"fetchDistantDictionary.cjs","names":["getIntlayerAPIProxy"],"sources":["../../../src/distantDictionary/fetchDistantDictionary.ts"],"sourcesContent":["import type { IntlayerConfig } from '@intlayer/types';\nimport { getIntlayerAPIProxy } from '../proxy';\nimport type { DictionaryAPI } from '../types';\n\n/**\n * Fetch distant dictionary\n */\nexport const fetchDistantDictionary = async (\n dictionaryKey: string,\n intlayerConfig: IntlayerConfig\n): Promise<DictionaryAPI | undefined> => {\n try {\n const { clientId, clientSecret } = intlayerConfig.editor;\n\n if (!clientId || !clientSecret) {\n throw new Error(\n 'Missing OAuth2 client ID or client secret. To get access token go to https://app.intlayer.org/project.'\n );\n }\n\n const api = getIntlayerAPIProxy(undefined, intlayerConfig);\n\n // Fetch the dictionary\n const getDictionaryResult =\n await api.dictionary.getDictionary(dictionaryKey);\n\n const distantDictionary = getDictionaryResult.data;\n\n if (!distantDictionary) {\n throw new Error(`Dictionary ${dictionaryKey} not found on remote`);\n }\n\n return distantDictionary;\n } catch (error) {\n console.error(error);\n return undefined;\n }\n};\n"],"mappings":"mGAOa,EAAyB,MACpC,EACA,IACuC,CACvC,GAAI,CACF,GAAM,CAAE,WAAU,gBAAiB,EAAe,OAElD,GAAI,CAAC,GAAY,CAAC,EAChB,MAAU,MACR,yGACD,CASH,IAAM,GAFJ,MAJUA,EAAAA,oBAAoB,IAAA,GAAW,EAAe,CAI9C,WAAW,cAAc,EAAc,EAEL,KAE9C,GAAI,CAAC,EACH,MAAU,MAAM,cAAc,EAAc,sBAAsB,CAGpE,OAAO,QACA,EAAO,CACd,QAAQ,MAAM,EAAM,CACpB"}
@@ -1,6 +1 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_distantDictionary_fetchDistantDictionaries = require('./fetchDistantDictionaries.cjs');
3
- const require_distantDictionary_fetchDistantDictionary = require('./fetchDistantDictionary.cjs');
4
-
5
- exports.fetchDistantDictionaries = require_distantDictionary_fetchDistantDictionaries.fetchDistantDictionaries;
6
- exports.fetchDistantDictionary = require_distantDictionary_fetchDistantDictionary.fetchDistantDictionary;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./fetchDistantDictionaries.cjs`),t=require(`./fetchDistantDictionary.cjs`);exports.fetchDistantDictionaries=e.fetchDistantDictionaries,exports.fetchDistantDictionary=t.fetchDistantDictionary;
@@ -1,123 +1,2 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
-
3
- //#region src/fetcher.ts
4
- /**
5
- * Default options for the fetcher function.
6
- * Sets the default method to 'GET', the 'Content-Type' header to 'application/json',
7
- * and includes credentials in the request.
8
- */
9
- const fetcherOptions = {
10
- method: "GET",
11
- headers: { "Content-Type": "application/json" },
12
- credentials: "include"
13
- };
14
- /**
15
- * Utility function to remove properties with undefined values from an object.
16
- * This helps prevent sending undefined values in the request options.
17
- *
18
- * @param obj - The object to clean.
19
- * @returns The cleaned object without undefined values.
20
- */
21
- const removeUndefined = (obj) => {
22
- Object.keys(obj).forEach((key) => {
23
- if (obj[key] === void 0) delete obj[key];
24
- });
25
- return obj;
26
- };
27
- /**
28
- * Deeply merges an array of objects into a single object.
29
- * Later objects in the array overwrite properties of earlier ones.
30
- *
31
- * @template T - The type of objects being merged.
32
- * @param objects - An array of objects to merge.
33
- * @returns The merged object.
34
- */
35
- const deepMerge = (objects) => objects.reduce((acc, obj) => {
36
- const acc1 = acc ?? {};
37
- const obj1 = removeUndefined(obj ?? {});
38
- if (typeof acc1 === "object" && typeof obj1 === "object") return {
39
- ...acc1,
40
- ...obj1
41
- };
42
- return obj1 ?? acc1;
43
- }, {});
44
- /**
45
- * Fetcher function to make HTTP requests.
46
- * It merges default options with user-provided options,
47
- * handles query parameters and request body,
48
- * and returns the parsed JSON response.
49
- *
50
- * @template T - The expected type of the response data.
51
- * @param url - The endpoint URL.
52
- * @param options - Additional options to customize the request.
53
- * @returns A promise that resolves with the response data of type T.
54
- *
55
- * @example
56
- * ```typescript
57
- * // Making a GET request with query parameters
58
- * const data = await fetcher<MyResponseType>('https://api.example.com/data', {
59
- * params: { search: 'query' },
60
- * });
61
- *
62
- * // Making a POST request with a JSON body
63
- * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {
64
- * method: 'POST',
65
- * body: { key: 'value' },
66
- * });
67
- *
68
- * // Merge body, headers, and params
69
- * const result = await fetcher<AnotherResponseType>('https://api.example.com/submit', {
70
- * method: 'POST',
71
- * body: { key: 'value' },
72
- * headers: { 'Content-Type': 'application/json' },
73
- * params: { search: 'query' },
74
- * },
75
- * {
76
- * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
77
- * params: { page: 1 },
78
- * });
79
- * ```
80
- *
81
- * Result:
82
- * ```typescript
83
- * {
84
- * method: 'POST',
85
- * headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
86
- * params: { page: 1, search: 'query' },
87
- * body: { key: 'value' },
88
- * }
89
- * ```
90
- */
91
- const fetcher = async (url, ...options) => {
92
- const { signal } = new AbortController();
93
- let paramsString = "";
94
- let bodyString;
95
- const mergedOptions = deepMerge([fetcherOptions, ...options.map(({ body, params, headers, ...otherOptions }) => otherOptions)]);
96
- const mergedHeaders = deepMerge([fetcherOptions.headers, ...options.map((option) => option.headers)]);
97
- const params = deepMerge(options.map((option) => option.params));
98
- const method = mergedOptions.method;
99
- if (method !== "GET" && method !== "HEAD") {
100
- const body = deepMerge(options.map((option) => option.body));
101
- if (mergedHeaders?.["Content-Type"] === "application/x-www-form-urlencoded") bodyString = new URLSearchParams(body).toString();
102
- else bodyString = JSON.stringify(body);
103
- }
104
- if (Object.entries(params).length > 0) paramsString = `?${new URLSearchParams(params).toString()}`;
105
- const formattedOptions = {
106
- ...mergedOptions,
107
- headers: mergedHeaders,
108
- body: bodyString,
109
- signal
110
- };
111
- const urlResult = `${url}${paramsString}`;
112
- const response = await fetch(urlResult, formattedOptions);
113
- if (!response.ok) {
114
- const result = await response.json();
115
- throw new Error(JSON.stringify(result.error) ?? "An error occurred");
116
- }
117
- return await response.json();
118
- };
119
-
120
- //#endregion
121
- exports.fetcher = fetcher;
122
- exports.fetcherOptions = fetcherOptions;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e={method:`GET`,headers:{"Content-Type":`application/json`},credentials:`include`},t=e=>(Object.keys(e).forEach(t=>{e[t]===void 0&&delete e[t]}),e),n=e=>e.reduce((e,n)=>{let r=e??{},i=t(n??{});return typeof r==`object`&&typeof i==`object`?{...r,...i}:i??r},{}),r=async(t,...r)=>{let{signal:i}=new AbortController,a=``,o,s=n([e,...r.map(({body:e,params:t,headers:n,...r})=>r)]),c=n([e.headers,...r.map(e=>e.headers)]),l=n(r.map(e=>e.params)),u=s.method;if(u!==`GET`&&u!==`HEAD`){let e=n(r.map(e=>e.body));o=c?.[`Content-Type`]===`application/x-www-form-urlencoded`?new URLSearchParams(e).toString():JSON.stringify(e)}Object.entries(l).length>0&&(a=`?${new URLSearchParams(l).toString()}`);let d={...s,headers:c,body:o,signal:i},f=`${t}${a}`,p=await fetch(f,d);if(!p.ok){let e=await p.json();throw Error(JSON.stringify(e.error)??`An error occurred`)}return await p.json()};exports.fetcher=r,exports.fetcherOptions=e;
123
2
  //# sourceMappingURL=fetcher.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fetcher.cjs","names":[],"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,MAAa,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,MAAM,OAAW,OAAO,EAAE;CAC1B,MAAM,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,IAAI;CAQJ,MAAM,gBAAgB,UAAU,CAAC,gBAAgB,GAL5B,QAAQ,KAC1B,EAAE,MAAM,QAAQ,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,MAAM,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.cjs","names":[],"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":"mEAwBA,MAAa,EAAiC,CAC5C,OAAQ,MACR,QAAS,CACP,eAAgB,mBACjB,CACD,YAAa,UACd,CASK,EAAmB,IACvB,OAAO,KAAK,EAAI,CAAC,QAAS,GAAQ,CAC5B,EAAI,KAA6B,IAAA,IACnC,OAAO,EAAI,IAEb,CACK,GAWH,EAA+B,GACnC,EAAQ,QAAQ,EAAK,IAAQ,CAC3B,IAAM,EAAW,GAAO,EAAE,CACpB,EAAU,EAAgB,GAAO,EAAE,CAAC,CAQ1C,OANI,OAAO,GAAS,UAAY,OAAO,GAAS,SAEvC,CAAE,GAAG,EAAM,GAAG,EAAM,CAItB,GAAQ,GACd,EAAE,CAAM,CAiDA,EAAU,MACrB,EACA,GAAG,IACY,CACf,GAAM,CAAE,UAAW,IAAI,gBAGnB,EAAe,GACf,EAQE,EAAgB,EAAU,CAAC,EAAgB,GAL5B,EAAQ,KAC1B,CAAE,OAAM,SAAQ,UAAS,GAAG,KAAmB,EACjD,CAGgE,CAAC,CAG5D,EAAgB,EAAU,CAC9B,EAAe,QACf,GAAG,EAAQ,IAAK,GAAW,EAAO,QAAQ,CAC3C,CAAC,CAGI,EAAS,EAAU,EAAQ,IAAK,GAAW,EAAO,OAAO,CAAC,CAE1D,EAAS,EAAc,OAG7B,GAAI,IAAW,OAAS,IAAW,OAAQ,CAEzC,IAAM,EAAO,EAAU,EAAQ,IAAK,GAAW,EAAO,KAAK,CAAC,CAC5D,AAUE,EATA,IAAgB,kBAChB,oCAGa,IAAI,gBACf,EACD,CAAC,UAAU,CAGC,KAAK,UAAU,EAAK,CAKjC,OAAO,QAAQ,EAAO,CAAC,OAAS,IAClC,EAAe,IAAI,IAAI,gBACrB,EACD,CAAC,UAAU,IAId,IAAM,EAAgC,CACpC,GAAG,EACH,QAAS,EACT,KAAM,EACN,SACD,CAGK,EAAY,GAAG,IAAM,IAGrB,EAAW,MAAM,MAAM,EAAW,EAAiB,CAEzD,GAAI,CAAC,EAAS,GAAI,CAChB,IAAM,EAAS,MAAM,EAAS,MAAM,CAGpC,MAAU,MAAM,KAAK,UAAU,EAAO,MAAM,EAAI,oBAAoB,CAEtE,OAAO,MAAM,EAAS,MAAM"}
@@ -1,167 +1,3 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
- const require_fetcher = require('../fetcher.cjs');
4
- let _intlayer_config_built = require("@intlayer/config/built");
5
- _intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
6
-
7
- //#region src/getIntlayerAPI/ai.ts
8
- const getAiAPI = (authAPIOptions = {}, intlayerConfig) => {
9
- const backendURL = intlayerConfig?.editor?.backendURL ?? _intlayer_config_built.default?.editor?.backendURL;
10
- if (!backendURL) throw new Error("Backend URL is not defined in the Intlayer configuration.");
11
- const AI_API_ROUTE = `${backendURL}/api/ai`;
12
- /**
13
- * Custom query
14
- * @param body - Custom query parameters.
15
- * @returns Custom query result.
16
- */
17
- const customQuery = async (body, otherOptions = {}) => await require_fetcher.fetcher(AI_API_ROUTE, authAPIOptions, otherOptions, {
18
- method: "POST",
19
- body
20
- });
21
- /**
22
- * Translate a JSON
23
- * @param body - Audit file parameters.
24
- * @returns Audited file content.
25
- */
26
- const translateJSON = async (body, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/translate/json`, authAPIOptions, otherOptions, {
27
- method: "POST",
28
- body
29
- });
30
- /**
31
- * Audits a content declaration file
32
- * @param body - Audit file parameters.
33
- * @returns Audited file content.
34
- */
35
- const auditContentDeclaration = async (body, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/audit/dictionary`, authAPIOptions, otherOptions, {
36
- method: "POST",
37
- body
38
- });
39
- /**
40
- * Audits a content declaration field
41
- * @param body - Audit file parameters.
42
- * @returns Audited file content.
43
- */
44
- const auditContentDeclarationField = async (body, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/audit/dictionary/field`, authAPIOptions, otherOptions, {
45
- method: "POST",
46
- body
47
- });
48
- /**
49
- * Audits a content declaration file to retrieve title, description and tags
50
- * @param body - Audit file parameters.
51
- * @returns Audited file content.
52
- */
53
- const auditContentDeclarationMetadata = async (body, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/audit/dictionary/metadata`, authAPIOptions, otherOptions, {
54
- method: "POST",
55
- body
56
- });
57
- /**
58
- * Audits a tag
59
- * @param body - Audit tag parameters.
60
- * @returns Audited tag content.
61
- */
62
- const auditTag = async (body, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/audit/tag`, authAPIOptions, otherOptions, {
63
- method: "POST",
64
- body
65
- });
66
- /**
67
- * Asks a question to the AI related to the documentation **and streams the
68
- * answer as Server‑Sent Events (SSE)**.
69
- *
70
- * The function **returns immediately** with a handle exposing:
71
- * - `promise` → resolves when the stream completes (or rejects on error)
72
- * - `abort()` → allows canceling the request on demand
73
- *
74
- * Usage example:
75
- * ```ts
76
- * const { promise, abort } = ai.askDocQuestion({
77
- * ...body,
78
- * onMessage: console.log,
79
- * onDone: (full) => console.log("✔", full),
80
- * });
81
- * // later → abort();
82
- * await promise; // waits for completion if desired
83
- * ```
84
- */
85
- const askDocQuestion = async (body, otherOptions = {}) => {
86
- if (!body) return;
87
- const { onMessage, onDone, ...rest } = body;
88
- const abortController = new AbortController();
89
- try {
90
- const response = await fetch(`${AI_API_ROUTE}/ask`, {
91
- method: "POST",
92
- headers: {
93
- "Content-Type": "application/json",
94
- ...authAPIOptions.headers,
95
- ...otherOptions.headers
96
- },
97
- body: JSON.stringify({
98
- ...rest,
99
- ...authAPIOptions.body,
100
- ...otherOptions.body
101
- }),
102
- signal: abortController.signal,
103
- credentials: "include"
104
- });
105
- if (!response.ok) {
106
- let errorMessage = "An error occurred";
107
- try {
108
- const errorData = await response.json();
109
- errorMessage = JSON.stringify(errorData.error) ?? "An error occurred";
110
- } catch {
111
- try {
112
- const errorText = await response.text();
113
- if (errorText) errorMessage = errorText;
114
- } catch {}
115
- }
116
- throw new Error(errorMessage);
117
- }
118
- const reader = response.body?.getReader();
119
- if (!reader) throw new Error("No reader available");
120
- const decoder = new TextDecoder();
121
- let buffer = "";
122
- while (true) {
123
- const { done, value } = await reader.read();
124
- if (done) break;
125
- buffer += decoder.decode(value, { stream: true });
126
- const lines = buffer.split("\n");
127
- buffer = lines.pop() ?? "";
128
- for (const line of lines) if (line.startsWith("data: ")) try {
129
- const data = JSON.parse(line.slice(6));
130
- if (data.chunk) onMessage?.(data.chunk);
131
- if (data.done && data.response) onDone?.(data.response);
132
- } catch (e) {
133
- console.error("Failed to parse SSE data:", e);
134
- }
135
- }
136
- } catch (error) {
137
- console.error("Error in askDocQuestion:", error);
138
- throw error;
139
- }
140
- };
141
- const autocomplete = async (body, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/autocomplete`, authAPIOptions, otherOptions, {
142
- method: "POST",
143
- body
144
- });
145
- /**
146
- * Retrieves discussions with filters and pagination. Only user or admin can access.
147
- */
148
- const getDiscussions = async (params, otherOptions = {}) => await require_fetcher.fetcher(`${AI_API_ROUTE}/discussions`, authAPIOptions, otherOptions, {
149
- method: "GET",
150
- params
151
- });
152
- return {
153
- customQuery,
154
- translateJSON,
155
- auditContentDeclaration,
156
- auditContentDeclarationField,
157
- auditContentDeclarationMetadata,
158
- auditTag,
159
- askDocQuestion,
160
- autocomplete,
161
- getDiscussions
162
- };
163
- };
164
-
165
- //#endregion
166
- exports.getAiAPI = getAiAPI;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../fetcher.cjs`);let n=require(`@intlayer/config/built`);n=e.__toESM(n);const r=(e={},r)=>{let i=r?.editor?.backendURL??n.default?.editor?.backendURL;if(!i)throw Error(`Backend URL is not defined in the Intlayer configuration.`);let a=`${i}/api/ai`;return{customQuery:async(n,r={})=>await t.fetcher(a,e,r,{method:`POST`,body:n}),translateJSON:async(n,r={})=>await t.fetcher(`${a}/translate/json`,e,r,{method:`POST`,body:n}),auditContentDeclaration:async(n,r={})=>await t.fetcher(`${a}/audit/dictionary`,e,r,{method:`POST`,body:n}),auditContentDeclarationField:async(n,r={})=>await t.fetcher(`${a}/audit/dictionary/field`,e,r,{method:`POST`,body:n}),auditContentDeclarationMetadata:async(n,r={})=>await t.fetcher(`${a}/audit/dictionary/metadata`,e,r,{method:`POST`,body:n}),auditTag:async(n,r={})=>await t.fetcher(`${a}/audit/tag`,e,r,{method:`POST`,body:n}),askDocQuestion:async(t,n={})=>{if(!t)return;let{onMessage:r,onDone:i,...o}=t,s=new AbortController;try{let t=await fetch(`${a}/ask`,{method:`POST`,headers:{"Content-Type":`application/json`,...e.headers,...n.headers},body:JSON.stringify({...o,...e.body,...n.body}),signal:s.signal,credentials:`include`});if(!t.ok){let e=`An error occurred`;try{let n=await t.json();e=JSON.stringify(n.error)??`An error occurred`}catch{try{let n=await t.text();n&&(e=n)}catch{}}throw Error(e)}let c=t.body?.getReader();if(!c)throw Error(`No reader available`);let l=new TextDecoder,u=``;for(;;){let{done:e,value:t}=await c.read();if(e)break;u+=l.decode(t,{stream:!0});let n=u.split(`
2
+ `);u=n.pop()??``;for(let e of n)if(e.startsWith(`data: `))try{let t=JSON.parse(e.slice(6));t.chunk&&r?.(t.chunk),t.done&&t.response&&i?.(t.response)}catch(e){console.error(`Failed to parse SSE data:`,e)}}}catch(e){throw console.error(`Error in askDocQuestion:`,e),e}},autocomplete:async(n,r={})=>await t.fetcher(`${a}/autocomplete`,e,r,{method:`POST`,body:n}),getDiscussions:async(n,r={})=>await t.fetcher(`${a}/discussions`,e,r,{method:`GET`,params:n})}};exports.getAiAPI=r;
167
3
  //# sourceMappingURL=ai.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ai.cjs","names":["configuration","fetcher"],"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":"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"}
1
+ {"version":3,"file":"ai.cjs","names":["configuration","fetcher"],"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":"2MAiCA,MAAa,GACX,EAAiC,EAAE,CACnC,IACG,CACH,IAAM,EACJ,GAAgB,QAAQ,YAAcA,EAAAA,SAAe,QAAQ,WAE/D,GAAI,CAAC,EACH,MAAU,MACR,4DACD,CAGH,IAAM,EAAe,GAAG,EAAW,SA+PnC,MAAO,CACL,YAzPkB,MAClB,EACA,EAA+B,EAAE,GAEjC,MAAMC,EAAAA,QACJ,EACA,EACA,EACA,CACE,OAAQ,OACF,OACP,CACF,CA8OD,cAvOoB,MACpB,EACA,EAA+B,EAAE,GAEjC,MAAMA,EAAAA,QACJ,GAAG,EAAa,iBAChB,EACA,EACA,CACE,OAAQ,OACF,OACP,CACF,CA4ND,wBArN8B,MAC9B,EACA,EAA+B,EAAE,GAEjC,MAAMA,EAAAA,QACJ,GAAG,EAAa,mBAChB,EACA,EACA,CACE,OAAQ,OACF,OACP,CACF,CA0MD,6BAnMmC,MACnC,EACA,EAA+B,EAAE,GAEjC,MAAMA,EAAAA,QACJ,GAAG,EAAa,yBAChB,EACA,EACA,CACE,OAAQ,OACF,OACP,CACF,CAwLD,gCAjLsC,MACtC,EACA,EAA+B,EAAE,GAEjC,MAAMA,EAAAA,QACJ,GAAG,EAAa,4BAChB,EACA,EACA,CACE,OAAQ,OACF,OACP,CACF,CAsKD,SA/Je,MACf,EACA,EAA+B,EAAE,GAEjC,MAAMA,EAAAA,QACJ,GAAG,EAAa,YAChB,EACA,EACA,CACE,OAAQ,OACF,OACP,CACF,CAoJD,eA/HqB,MACrB,EACA,EAA+B,EAAE,GAC9B,CACH,GAAI,CAAC,EAAM,OAEX,GAAM,CAAE,YAAW,SAAQ,GAAG,GAAS,EACjC,EAAkB,IAAI,gBAE5B,GAAI,CACF,IAAM,EAAW,MAAM,MAAM,GAAG,EAAa,MAAO,CAClD,OAAQ,OACR,QAAS,CACP,eAAgB,mBAChB,GAAG,EAAe,QAClB,GAAG,EAAa,QACjB,CACD,KAAM,KAAK,UAAU,CACnB,GAAG,EACH,GAAG,EAAe,KAClB,GAAG,EAAa,KACjB,CAAC,CACF,OAAQ,EAAgB,OACxB,YAAa,UACd,CAAC,CAEF,GAAI,CAAC,EAAS,GAAI,CAGhB,IAAI,EAAuB,oBAE3B,GAAI,CAEF,IAAM,EAAY,MAAM,EAAS,MAAM,CACvC,EAAe,KAAK,UAAU,EAAU,MAAM,EAAI,yBAC5C,CAEN,GAAI,CACF,IAAM,EAAY,MAAM,EAAS,MAAM,CACnC,IACF,EAAe,QAEX,GAKV,MAAU,MAAM,EAAa,CAG/B,IAAM,EAAS,EAAS,MAAM,WAAW,CACzC,GAAI,CAAC,EACH,MAAU,MAAM,sBAAsB,CAGxC,IAAM,EAAU,IAAI,YAChB,EAAS,GAEb,OAAa,CACX,GAAM,CAAE,OAAM,SAAU,MAAM,EAAO,MAAM,CAC3C,GAAI,EAAM,MAEV,GAAU,EAAQ,OAAO,EAAO,CAAE,OAAQ,GAAM,CAAC,CACjD,IAAM,EAAQ,EAAO,MAAM;EAAK,CAChC,EAAS,EAAM,KAAK,EAAI,GAExB,IAAK,IAAM,KAAQ,EACjB,GAAI,EAAK,WAAW,SAAS,CAC3B,GAAI,CACF,IAAM,EAAO,KAAK,MAAM,EAAK,MAAM,EAAE,CAAC,CAClC,EAAK,OACP,IAAY,EAAK,MAAM,CAErB,EAAK,MAAQ,EAAK,UACpB,IAAS,EAAK,SAAS,OAElB,EAAG,CACV,QAAQ,MAAM,4BAA6B,EAAE,SAK9C,EAAO,CAEd,MADA,QAAQ,MAAM,2BAA4B,EAAM,CAC1C,IA4CR,aAxCmB,MACnB,EACA,EAA+B,EAAE,GAEjC,MAAMA,EAAAA,QACJ,GAAG,EAAa,eAChB,EACA,EACA,CACE,OAAQ,OACF,OACP,CACF,CA6BD,eAxBqB,MACrB,EACA,EAA+B,EAAE,GAEjC,MAAMA,EAAAA,QACJ,GAAG,EAAa,cAChB,EACA,EACA,CACE,OAAQ,MAER,SACD,CACF,CAYF"}
@@ -1,42 +1,2 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
- const require_fetcher = require('../fetcher.cjs');
4
- let _intlayer_config_built = require("@intlayer/config/built");
5
- _intlayer_config_built = require_runtime.__toESM(_intlayer_config_built);
6
-
7
- //#region src/getIntlayerAPI/audit.ts
8
- const getAuditAPI = (authAPIOptions = {}, intlayerConfig) => {
9
- const backendURL = intlayerConfig?.editor?.backendURL ?? _intlayer_config_built.default?.editor?.backendURL;
10
- if (!backendURL) throw new Error("Backend URL is not defined in the Intlayer configuration.");
11
- const AUDIT_API_ROUTE = `${backendURL}/api/audit`;
12
- /**
13
- * Creates a new audit in the database.
14
- * @param audit - Audit data.
15
- */
16
- const createAudit = async (audit, otherOptions = {}) => await require_fetcher.fetcher(`${AUDIT_API_ROUTE}`, authAPIOptions, otherOptions, {
17
- method: "POST",
18
- body: audit
19
- });
20
- /**
21
- * Retrieves audits for the current user or project.
22
- * @param params - Query parameters (page, pageSize).
23
- */
24
- const getAudits = async (params, otherOptions = {}) => await require_fetcher.fetcher(AUDIT_API_ROUTE, authAPIOptions, otherOptions, {
25
- cache: "no-store",
26
- params
27
- });
28
- /**
29
- * Retrieves an audit by its ID.
30
- * @param auditId - Audit ID.
31
- */
32
- const getAuditById = async (auditId, otherOptions = {}) => await require_fetcher.fetcher(`${AUDIT_API_ROUTE}/${String(auditId)}`, authAPIOptions, otherOptions, { cache: "no-store" });
33
- return {
34
- createAudit,
35
- getAudits,
36
- getAuditById
37
- };
38
- };
39
-
40
- //#endregion
41
- exports.getAuditAPI = getAuditAPI;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../_virtual/_rolldown/runtime.cjs`),t=require(`../fetcher.cjs`);let n=require(`@intlayer/config/built`);n=e.__toESM(n);const r=(e={},r)=>{let i=r?.editor?.backendURL??n.default?.editor?.backendURL;if(!i)throw Error(`Backend URL is not defined in the Intlayer configuration.`);let a=`${i}/api/audit`;return{createAudit:async(n,r={})=>await t.fetcher(`${a}`,e,r,{method:`POST`,body:n}),getAudits:async(n,r={})=>await t.fetcher(a,e,r,{cache:`no-store`,params:n}),getAuditById:async(n,r={})=>await t.fetcher(`${a}/${String(n)}`,e,r,{cache:`no-store`})}};exports.getAuditAPI=r;
42
2
  //# sourceMappingURL=audit.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"audit.cjs","names":["configuration","fetcher"],"sources":["../../../src/getIntlayerAPI/audit.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { type FetcherOptions, fetcher } from '../fetcher';\nimport type {\n CreateAuditBody,\n CreateAuditResult,\n GetAuditByIdParams,\n GetAuditByIdResult,\n GetAuditsParams,\n GetAuditsResult,\n} from '../types';\n\nexport const getAuditAPI = (\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 AUDIT_API_ROUTE = `${backendURL}/api/audit`;\n\n /**\n * Creates a new audit in the database.\n * @param audit - Audit data.\n */\n const createAudit = async (\n audit: CreateAuditBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<CreateAuditResult>(\n `${AUDIT_API_ROUTE}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body: audit,\n }\n );\n\n /**\n * Retrieves audits for the current user or project.\n * @param params - Query parameters (page, pageSize).\n */\n const getAudits = async (\n params?: GetAuditsParams,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetAuditsResult>(\n AUDIT_API_ROUTE,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n // @ts-ignore Number of parameter will be stringified by the fetcher\n params,\n }\n );\n\n /**\n * Retrieves an audit by its ID.\n * @param auditId - Audit ID.\n */\n const getAuditById = async (\n auditId: GetAuditByIdParams['auditId'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetAuditByIdResult>(\n `${AUDIT_API_ROUTE}/${String(auditId)}`,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n }\n );\n\n return {\n createAudit,\n getAudits,\n getAuditById,\n };\n};\n"],"mappings":";;;;;;;AAYA,MAAa,eACX,iBAAiC,EAAE,EACnC,mBACG;CACH,MAAM,aACJ,gBAAgB,QAAQ,cAAcA,gCAAe,QAAQ;AAE/D,KAAI,CAAC,WACH,OAAM,IAAI,MACR,4DACD;CAGH,MAAM,kBAAkB,GAAG,WAAW;;;;;CAMtC,MAAM,cAAc,OAClB,OACA,eAA+B,EAAE,KAEjC,MAAMC,wBACJ,GAAG,mBACH,gBACA,cACA;EACE,QAAQ;EACR,MAAM;EACP,CACF;;;;;CAMH,MAAM,YAAY,OAChB,QACA,eAA+B,EAAE,KAEjC,MAAMA,wBACJ,iBACA,gBACA,cACA;EACE,OAAO;EAEP;EACD,CACF;;;;;CAMH,MAAM,eAAe,OACnB,SACA,eAA+B,EAAE,KAEjC,MAAMA,wBACJ,GAAG,gBAAgB,GAAG,OAAO,QAAQ,IACrC,gBACA,cACA,EACE,OAAO,YACR,CACF;AAEH,QAAO;EACL;EACA;EACA;EACD"}
1
+ {"version":3,"file":"audit.cjs","names":["configuration","fetcher"],"sources":["../../../src/getIntlayerAPI/audit.ts"],"sourcesContent":["import configuration from '@intlayer/config/built';\nimport type { IntlayerConfig } from '@intlayer/types';\nimport { type FetcherOptions, fetcher } from '../fetcher';\nimport type {\n CreateAuditBody,\n CreateAuditResult,\n GetAuditByIdParams,\n GetAuditByIdResult,\n GetAuditsParams,\n GetAuditsResult,\n} from '../types';\n\nexport const getAuditAPI = (\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 AUDIT_API_ROUTE = `${backendURL}/api/audit`;\n\n /**\n * Creates a new audit in the database.\n * @param audit - Audit data.\n */\n const createAudit = async (\n audit: CreateAuditBody,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<CreateAuditResult>(\n `${AUDIT_API_ROUTE}`,\n authAPIOptions,\n otherOptions,\n {\n method: 'POST',\n body: audit,\n }\n );\n\n /**\n * Retrieves audits for the current user or project.\n * @param params - Query parameters (page, pageSize).\n */\n const getAudits = async (\n params?: GetAuditsParams,\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetAuditsResult>(\n AUDIT_API_ROUTE,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n // @ts-ignore Number of parameter will be stringified by the fetcher\n params,\n }\n );\n\n /**\n * Retrieves an audit by its ID.\n * @param auditId - Audit ID.\n */\n const getAuditById = async (\n auditId: GetAuditByIdParams['auditId'],\n otherOptions: FetcherOptions = {}\n ) =>\n await fetcher<GetAuditByIdResult>(\n `${AUDIT_API_ROUTE}/${String(auditId)}`,\n authAPIOptions,\n otherOptions,\n {\n cache: 'no-store',\n }\n );\n\n return {\n createAudit,\n getAudits,\n getAuditById,\n };\n};\n"],"mappings":"2MAYA,MAAa,GACX,EAAiC,EAAE,CACnC,IACG,CACH,IAAM,EACJ,GAAgB,QAAQ,YAAcA,EAAAA,SAAe,QAAQ,WAE/D,GAAI,CAAC,EACH,MAAU,MACR,4DACD,CAGH,IAAM,EAAkB,GAAG,EAAW,YAwDtC,MAAO,CACL,YAnDkB,MAClB,EACA,EAA+B,EAAE,GAEjC,MAAMC,EAAAA,QACJ,GAAG,IACH,EACA,EACA,CACE,OAAQ,OACR,KAAM,EACP,CACF,CAwCD,UAlCgB,MAChB,EACA,EAA+B,EAAE,GAEjC,MAAMA,EAAAA,QACJ,EACA,EACA,EACA,CACE,MAAO,WAEP,SACD,CACF,CAsBD,aAhBmB,MACnB,EACA,EAA+B,EAAE,GAEjC,MAAMA,EAAAA,QACJ,GAAG,EAAgB,GAAG,OAAO,EAAQ,GACrC,EACA,EACA,CACE,MAAO,WACR,CACF,CAMF"}