@intlayer/backend 5.1.4 → 5.1.6

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 (252) hide show
  1. package/dist/cjs/controllers/ai.controller.cjs +61 -43
  2. package/dist/cjs/controllers/ai.controller.cjs.map +1 -1
  3. package/dist/cjs/controllers/dictionary.controller.cjs +8 -12
  4. package/dist/cjs/controllers/dictionary.controller.cjs.map +1 -1
  5. package/dist/cjs/controllers/organization.controller.cjs +17 -1
  6. package/dist/cjs/controllers/organization.controller.cjs.map +1 -1
  7. package/dist/cjs/controllers/project.controller.cjs +1 -0
  8. package/dist/cjs/controllers/project.controller.cjs.map +1 -1
  9. package/dist/cjs/controllers/sessionAuth.controller.cjs +6 -12
  10. package/dist/cjs/controllers/sessionAuth.controller.cjs.map +1 -1
  11. package/dist/cjs/controllers/stripe.controller.cjs +31 -10
  12. package/dist/cjs/controllers/stripe.controller.cjs.map +1 -1
  13. package/dist/cjs/controllers/tag.controller.cjs +0 -7
  14. package/dist/cjs/controllers/tag.controller.cjs.map +1 -1
  15. package/dist/cjs/controllers/user.controller.cjs +1 -1
  16. package/dist/cjs/controllers/user.controller.cjs.map +1 -1
  17. package/dist/cjs/emails/InviteUserEmail.cjs +3 -3
  18. package/dist/cjs/emails/InviteUserEmail.cjs.map +1 -1
  19. package/dist/cjs/emails/PasswordChangeConfirmation.cjs +3 -3
  20. package/dist/cjs/emails/PasswordChangeConfirmation.cjs.map +1 -1
  21. package/dist/cjs/emails/ResetUserPassword.cjs +3 -3
  22. package/dist/cjs/emails/ResetUserPassword.cjs.map +1 -1
  23. package/dist/cjs/emails/SubscriptionPaymentCancellation.cjs +19 -3
  24. package/dist/cjs/emails/SubscriptionPaymentCancellation.cjs.map +1 -1
  25. package/dist/cjs/emails/SubscriptionPaymentError.cjs +19 -3
  26. package/dist/cjs/emails/SubscriptionPaymentError.cjs.map +1 -1
  27. package/dist/cjs/emails/SubscriptionPaymentSuccess.cjs +19 -3
  28. package/dist/cjs/emails/SubscriptionPaymentSuccess.cjs.map +1 -1
  29. package/dist/cjs/emails/ValidateUserEmail.cjs +3 -3
  30. package/dist/cjs/emails/ValidateUserEmail.cjs.map +1 -1
  31. package/dist/cjs/emails/Welcome.cjs +3 -3
  32. package/dist/cjs/emails/Welcome.cjs.map +1 -1
  33. package/dist/cjs/export.cjs +10 -10
  34. package/dist/cjs/export.cjs.map +1 -1
  35. package/dist/cjs/routes/ai.routes.cjs +21 -15
  36. package/dist/cjs/routes/ai.routes.cjs.map +1 -1
  37. package/dist/cjs/routes/dictionary.routes.cjs +15 -12
  38. package/dist/cjs/routes/dictionary.routes.cjs.map +1 -1
  39. package/dist/cjs/routes/event-listener.routes.cjs +4 -4
  40. package/dist/cjs/routes/event-listener.routes.cjs.map +1 -1
  41. package/dist/cjs/routes/organization.routes.cjs +15 -15
  42. package/dist/cjs/routes/organization.routes.cjs.map +1 -1
  43. package/dist/cjs/routes/project.routes.cjs +30 -18
  44. package/dist/cjs/routes/project.routes.cjs.map +1 -1
  45. package/dist/cjs/routes/sessionAuth.routes.cjs +38 -35
  46. package/dist/cjs/routes/sessionAuth.routes.cjs.map +1 -1
  47. package/dist/cjs/routes/stripe.routes.cjs +23 -11
  48. package/dist/cjs/routes/stripe.routes.cjs.map +1 -1
  49. package/dist/cjs/routes/tags.routes.cjs +11 -11
  50. package/dist/cjs/routes/tags.routes.cjs.map +1 -1
  51. package/dist/cjs/routes/user.routes.cjs +13 -13
  52. package/dist/cjs/routes/user.routes.cjs.map +1 -1
  53. package/dist/cjs/schemas/dictionary.schema.cjs +0 -4
  54. package/dist/cjs/schemas/dictionary.schema.cjs.map +1 -1
  55. package/dist/cjs/schemas/project.schema.cjs +2 -2
  56. package/dist/cjs/schemas/project.schema.cjs.map +1 -1
  57. package/dist/cjs/services/dictionary.service.cjs.map +1 -1
  58. package/dist/cjs/services/email.service.cjs +1 -1
  59. package/dist/cjs/services/email.service.cjs.map +1 -1
  60. package/dist/cjs/services/subscription.service.cjs +81 -2
  61. package/dist/cjs/services/subscription.service.cjs.map +1 -1
  62. package/dist/cjs/types/dictionary.types.cjs.map +1 -1
  63. package/dist/cjs/utils/AI/{askDocQuestion.cjs → askDocQuestion/askDocQuestion.cjs} +1 -1
  64. package/dist/cjs/utils/AI/askDocQuestion/askDocQuestion.cjs.map +1 -0
  65. package/dist/{esm/utils/AI → cjs/utils/AI/askDocQuestion}/embeddings.json +4288 -4288
  66. package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/index.cjs +5 -3
  67. package/dist/cjs/utils/AI/auditDictionary/index.cjs.map +1 -0
  68. package/dist/cjs/utils/{auditDictionaryField → AI/auditDictionaryField}/PROMPT.md +17 -7
  69. package/dist/cjs/utils/{auditDictionaryField → AI/auditDictionaryField}/index.cjs +5 -3
  70. package/dist/cjs/utils/AI/auditDictionaryField/index.cjs.map +1 -0
  71. package/dist/cjs/utils/{auditDictionaryMetadata → AI/auditDictionaryMetadata}/index.cjs +5 -3
  72. package/dist/cjs/utils/AI/auditDictionaryMetadata/index.cjs.map +1 -0
  73. package/dist/cjs/utils/AI/autocomplete/PROMPT.md +13 -0
  74. package/dist/cjs/utils/AI/autocomplete/index.cjs +73 -0
  75. package/dist/cjs/utils/AI/autocomplete/index.cjs.map +1 -0
  76. package/dist/cjs/utils/auditTag/index.cjs +4 -2
  77. package/dist/cjs/utils/auditTag/index.cjs.map +1 -1
  78. package/dist/cjs/utils/errors/errorCodes.cjs +26 -0
  79. package/dist/cjs/utils/errors/errorCodes.cjs.map +1 -1
  80. package/dist/cjs/utils/mongoDB/connectDB.cjs +10 -0
  81. package/dist/cjs/utils/mongoDB/connectDB.cjs.map +1 -1
  82. package/dist/cjs/webhooks/stripe.webhook.cjs +42 -0
  83. package/dist/cjs/webhooks/stripe.webhook.cjs.map +1 -1
  84. package/dist/esm/controllers/ai.controller.mjs +59 -42
  85. package/dist/esm/controllers/ai.controller.mjs.map +1 -1
  86. package/dist/esm/controllers/dictionary.controller.mjs +8 -12
  87. package/dist/esm/controllers/dictionary.controller.mjs.map +1 -1
  88. package/dist/esm/controllers/organization.controller.mjs +18 -2
  89. package/dist/esm/controllers/organization.controller.mjs.map +1 -1
  90. package/dist/esm/controllers/project.controller.mjs +1 -0
  91. package/dist/esm/controllers/project.controller.mjs.map +1 -1
  92. package/dist/esm/controllers/sessionAuth.controller.mjs +6 -12
  93. package/dist/esm/controllers/sessionAuth.controller.mjs.map +1 -1
  94. package/dist/esm/controllers/stripe.controller.mjs +30 -10
  95. package/dist/esm/controllers/stripe.controller.mjs.map +1 -1
  96. package/dist/esm/controllers/tag.controller.mjs +0 -7
  97. package/dist/esm/controllers/tag.controller.mjs.map +1 -1
  98. package/dist/esm/controllers/user.controller.mjs +2 -2
  99. package/dist/esm/controllers/user.controller.mjs.map +1 -1
  100. package/dist/esm/emails/InviteUserEmail.mjs +3 -3
  101. package/dist/esm/emails/InviteUserEmail.mjs.map +1 -1
  102. package/dist/esm/emails/PasswordChangeConfirmation.mjs +3 -3
  103. package/dist/esm/emails/PasswordChangeConfirmation.mjs.map +1 -1
  104. package/dist/esm/emails/ResetUserPassword.mjs +3 -3
  105. package/dist/esm/emails/ResetUserPassword.mjs.map +1 -1
  106. package/dist/esm/emails/SubscriptionPaymentCancellation.mjs +19 -3
  107. package/dist/esm/emails/SubscriptionPaymentCancellation.mjs.map +1 -1
  108. package/dist/esm/emails/SubscriptionPaymentError.mjs +19 -3
  109. package/dist/esm/emails/SubscriptionPaymentError.mjs.map +1 -1
  110. package/dist/esm/emails/SubscriptionPaymentSuccess.mjs +19 -3
  111. package/dist/esm/emails/SubscriptionPaymentSuccess.mjs.map +1 -1
  112. package/dist/esm/emails/ValidateUserEmail.mjs +3 -3
  113. package/dist/esm/emails/ValidateUserEmail.mjs.map +1 -1
  114. package/dist/esm/emails/Welcome.mjs +3 -3
  115. package/dist/esm/emails/Welcome.mjs.map +1 -1
  116. package/dist/esm/export.mjs +10 -10
  117. package/dist/esm/export.mjs.map +1 -1
  118. package/dist/esm/routes/ai.routes.mjs +22 -15
  119. package/dist/esm/routes/ai.routes.mjs.map +1 -1
  120. package/dist/esm/routes/dictionary.routes.mjs +14 -11
  121. package/dist/esm/routes/dictionary.routes.mjs.map +1 -1
  122. package/dist/esm/routes/event-listener.routes.mjs +4 -4
  123. package/dist/esm/routes/event-listener.routes.mjs.map +1 -1
  124. package/dist/esm/routes/organization.routes.mjs +13 -13
  125. package/dist/esm/routes/organization.routes.mjs.map +1 -1
  126. package/dist/esm/routes/project.routes.mjs +28 -16
  127. package/dist/esm/routes/project.routes.mjs.map +1 -1
  128. package/dist/esm/routes/sessionAuth.routes.mjs +37 -34
  129. package/dist/esm/routes/sessionAuth.routes.mjs.map +1 -1
  130. package/dist/esm/routes/stripe.routes.mjs +22 -9
  131. package/dist/esm/routes/stripe.routes.mjs.map +1 -1
  132. package/dist/esm/routes/tags.routes.mjs +9 -9
  133. package/dist/esm/routes/tags.routes.mjs.map +1 -1
  134. package/dist/esm/routes/user.routes.mjs +11 -11
  135. package/dist/esm/routes/user.routes.mjs.map +1 -1
  136. package/dist/esm/schemas/dictionary.schema.mjs +0 -4
  137. package/dist/esm/schemas/dictionary.schema.mjs.map +1 -1
  138. package/dist/esm/schemas/project.schema.mjs +2 -2
  139. package/dist/esm/schemas/project.schema.mjs.map +1 -1
  140. package/dist/esm/services/dictionary.service.mjs.map +1 -1
  141. package/dist/esm/services/email.service.mjs +1 -1
  142. package/dist/esm/services/email.service.mjs.map +1 -1
  143. package/dist/esm/services/subscription.service.mjs +78 -1
  144. package/dist/esm/services/subscription.service.mjs.map +1 -1
  145. package/dist/esm/utils/AI/{askDocQuestion.mjs → askDocQuestion/askDocQuestion.mjs} +1 -1
  146. package/dist/esm/utils/AI/askDocQuestion/askDocQuestion.mjs.map +1 -0
  147. package/dist/{cjs/utils/AI → esm/utils/AI/askDocQuestion}/embeddings.json +4288 -4288
  148. package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/index.mjs +5 -3
  149. package/dist/esm/utils/AI/auditDictionary/index.mjs.map +1 -0
  150. package/dist/esm/utils/{auditDictionaryField → AI/auditDictionaryField}/PROMPT.md +17 -7
  151. package/dist/esm/utils/{auditDictionaryField → AI/auditDictionaryField}/index.mjs +5 -3
  152. package/dist/esm/utils/AI/auditDictionaryField/index.mjs.map +1 -0
  153. package/dist/esm/utils/{auditDictionaryMetadata → AI/auditDictionaryMetadata}/index.mjs +5 -3
  154. package/dist/esm/utils/AI/auditDictionaryMetadata/index.mjs.map +1 -0
  155. package/dist/esm/utils/AI/autocomplete/PROMPT.md +13 -0
  156. package/dist/esm/utils/AI/autocomplete/index.mjs +48 -0
  157. package/dist/esm/utils/AI/autocomplete/index.mjs.map +1 -0
  158. package/dist/esm/utils/auditTag/index.mjs +4 -2
  159. package/dist/esm/utils/auditTag/index.mjs.map +1 -1
  160. package/dist/esm/utils/errors/errorCodes.mjs +26 -0
  161. package/dist/esm/utils/errors/errorCodes.mjs.map +1 -1
  162. package/dist/esm/utils/mongoDB/connectDB.mjs +10 -0
  163. package/dist/esm/utils/mongoDB/connectDB.mjs.map +1 -1
  164. package/dist/esm/webhooks/stripe.webhook.mjs +32 -0
  165. package/dist/esm/webhooks/stripe.webhook.mjs.map +1 -1
  166. package/dist/types/controllers/ai.controller.d.ts +17 -2
  167. package/dist/types/controllers/ai.controller.d.ts.map +1 -1
  168. package/dist/types/controllers/dictionary.controller.d.ts.map +1 -1
  169. package/dist/types/controllers/organization.controller.d.ts.map +1 -1
  170. package/dist/types/controllers/project.controller.d.ts.map +1 -1
  171. package/dist/types/controllers/sessionAuth.controller.d.ts +4 -3
  172. package/dist/types/controllers/sessionAuth.controller.d.ts.map +1 -1
  173. package/dist/types/controllers/stripe.controller.d.ts +15 -7
  174. package/dist/types/controllers/stripe.controller.d.ts.map +1 -1
  175. package/dist/types/controllers/tag.controller.d.ts.map +1 -1
  176. package/dist/types/emails/SubscriptionPaymentCancellation.d.ts +4 -3
  177. package/dist/types/emails/SubscriptionPaymentCancellation.d.ts.map +1 -1
  178. package/dist/types/emails/SubscriptionPaymentError.d.ts +4 -3
  179. package/dist/types/emails/SubscriptionPaymentError.d.ts.map +1 -1
  180. package/dist/types/emails/SubscriptionPaymentSuccess.d.ts +4 -3
  181. package/dist/types/emails/SubscriptionPaymentSuccess.d.ts.map +1 -1
  182. package/dist/types/export.d.ts +5 -5
  183. package/dist/types/export.d.ts.map +1 -1
  184. package/dist/types/routes/ai.routes.d.ts +6 -1
  185. package/dist/types/routes/ai.routes.d.ts.map +1 -1
  186. package/dist/types/routes/dictionary.routes.d.ts +4 -4
  187. package/dist/types/routes/dictionary.routes.d.ts.map +1 -1
  188. package/dist/types/routes/event-listener.routes.d.ts +1 -1
  189. package/dist/types/routes/event-listener.routes.d.ts.map +1 -1
  190. package/dist/types/routes/organization.routes.d.ts +5 -5
  191. package/dist/types/routes/organization.routes.d.ts.map +1 -1
  192. package/dist/types/routes/project.routes.d.ts +5 -5
  193. package/dist/types/routes/project.routes.d.ts.map +1 -1
  194. package/dist/types/routes/sessionAuth.routes.d.ts +4 -7
  195. package/dist/types/routes/sessionAuth.routes.d.ts.map +1 -1
  196. package/dist/types/routes/stripe.routes.d.ts +6 -1
  197. package/dist/types/routes/stripe.routes.d.ts.map +1 -1
  198. package/dist/types/routes/tags.routes.d.ts +3 -3
  199. package/dist/types/routes/tags.routes.d.ts.map +1 -1
  200. package/dist/types/routes/user.routes.d.ts +4 -4
  201. package/dist/types/routes/user.routes.d.ts.map +1 -1
  202. package/dist/types/schemas/dictionary.schema.d.ts.map +1 -1
  203. package/dist/types/services/dictionary.service.d.ts.map +1 -1
  204. package/dist/types/services/subscription.service.d.ts +9 -0
  205. package/dist/types/services/subscription.service.d.ts.map +1 -1
  206. package/dist/types/types/dictionary.types.d.ts +0 -1
  207. package/dist/types/types/dictionary.types.d.ts.map +1 -1
  208. package/dist/types/utils/AI/askDocQuestion/askDocQuestion.d.ts.map +1 -0
  209. package/dist/types/utils/{auditDictionary → AI/auditDictionary}/index.d.ts +8 -5
  210. package/dist/types/utils/AI/auditDictionary/index.d.ts.map +1 -0
  211. package/dist/types/utils/{auditDictionaryField → AI/auditDictionaryField}/index.d.ts +8 -5
  212. package/dist/types/utils/AI/auditDictionaryField/index.d.ts.map +1 -0
  213. package/dist/types/utils/{auditDictionaryMetadata → AI/auditDictionaryMetadata}/index.d.ts +8 -5
  214. package/dist/types/utils/AI/auditDictionaryMetadata/index.d.ts.map +1 -0
  215. package/dist/types/utils/AI/autocomplete/index.d.ts +22 -0
  216. package/dist/types/utils/AI/autocomplete/index.d.ts.map +1 -0
  217. package/dist/types/utils/auditTag/index.d.ts +7 -4
  218. package/dist/types/utils/auditTag/index.d.ts.map +1 -1
  219. package/dist/types/utils/errors/errorCodes.d.ts +26 -0
  220. package/dist/types/utils/errors/errorCodes.d.ts.map +1 -1
  221. package/dist/types/utils/mongoDB/connectDB.d.ts.map +1 -1
  222. package/dist/types/webhooks/stripe.webhook.d.ts.map +1 -1
  223. package/package.json +11 -10
  224. package/dist/cjs/utils/AI/askDocQuestion.cjs.map +0 -1
  225. package/dist/cjs/utils/auditDictionary/index.cjs.map +0 -1
  226. package/dist/cjs/utils/auditDictionaryField/index.cjs.map +0 -1
  227. package/dist/cjs/utils/auditDictionaryMetadata/index.cjs.map +0 -1
  228. package/dist/esm/utils/AI/askDocQuestion.mjs.map +0 -1
  229. package/dist/esm/utils/auditDictionary/index.mjs.map +0 -1
  230. package/dist/esm/utils/auditDictionaryField/index.mjs.map +0 -1
  231. package/dist/esm/utils/auditDictionaryMetadata/index.mjs.map +0 -1
  232. package/dist/types/utils/AI/askDocQuestion.d.ts.map +0 -1
  233. package/dist/types/utils/auditDictionary/index.d.ts.map +0 -1
  234. package/dist/types/utils/auditDictionaryField/index.d.ts.map +0 -1
  235. package/dist/types/utils/auditDictionaryMetadata/index.d.ts.map +0 -1
  236. /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/CJS_FORMAT.md +0 -0
  237. /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/JSON_FORMAT.md +0 -0
  238. /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/JSX_FORMAT.md +0 -0
  239. /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/MJS_FORMAT.md +0 -0
  240. /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/PROMPT.md +0 -0
  241. /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/TSX_FORMAT.md +0 -0
  242. /package/dist/cjs/utils/{auditDictionary → AI/auditDictionary}/TS_FORMAT.md +0 -0
  243. /package/dist/cjs/utils/{auditDictionaryMetadata → AI/auditDictionaryMetadata}/PROMPT.md +0 -0
  244. /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/CJS_FORMAT.md +0 -0
  245. /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/JSON_FORMAT.md +0 -0
  246. /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/JSX_FORMAT.md +0 -0
  247. /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/MJS_FORMAT.md +0 -0
  248. /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/PROMPT.md +0 -0
  249. /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/TSX_FORMAT.md +0 -0
  250. /package/dist/esm/utils/{auditDictionary → AI/auditDictionary}/TS_FORMAT.md +0 -0
  251. /package/dist/esm/utils/{auditDictionaryMetadata → AI/auditDictionaryMetadata}/PROMPT.md +0 -0
  252. /package/dist/types/utils/AI/{askDocQuestion.d.ts → askDocQuestion/askDocQuestion.d.ts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/services/subscription.service.ts"],"sourcesContent":["import { logger } from '@logger';\nimport { GenericError } from '@utils/errors';\nimport { retrievePlanInformation } from '@utils/plan';\nimport Stripe from 'stripe';\nimport { sendEmail } from './email.service';\nimport { getOrganizationById, updatePlan } from './organization.service';\nimport { getUserById } from './user.service';\nimport type { Organization } from '@/types/organization.types';\nimport type { Plan } from '@/types/plan.types';\n\nexport const addOrUpdateSubscription = async (\n subscriptionId: string,\n priceId: string,\n customerId: string,\n userId: string,\n organization: Organization,\n status: Plan['status']\n): Promise<Plan | null> => {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n const user = await getUserById(userId);\n\n if (!user) {\n throw new GenericError('USER_NOT_FOUND', {\n userId,\n });\n }\n\n if (user.customerId !== customerId) {\n user.customerId = customerId;\n await user.save();\n }\n\n const planInfo = retrievePlanInformation(priceId);\n\n const subscriptions = await stripe.subscriptions.list({\n customer: customerId,\n status: 'active',\n limit: 1,\n });\n\n if (subscriptions.data.length >= 1) {\n // Active subscription exists; update it to the new plan\n const otherSubscriptionArray = subscriptions.data.filter(\n (subscription) => subscription.id !== subscriptionId\n );\n\n for (const subscription of otherSubscriptionArray) {\n await stripe.subscriptions.cancel(subscription.id);\n }\n }\n\n const updatedOrganization = await updatePlan(organization, {\n creatorId: user._id,\n priceId,\n customerId,\n subscriptionId,\n type: planInfo.type,\n period: planInfo.period,\n status,\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization._id,\n });\n }\n\n logger.info(\n `Plan updated for organization ${organization._id} - ${planInfo.type} - ${planInfo.period}`\n );\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const cancelSubscription = async (\n subscriptionId: string | Organization['_id'],\n organizationId: Organization['_id'] | string\n): Promise<Plan | null> => {\n const organization = await getOrganizationById(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', {\n subscriptionId,\n });\n }\n\n if (!subscriptionId) {\n throw new GenericError('NO_SUBSCRIPTION_ID_PROVIDED');\n }\n\n if (!organization.plan) {\n throw new GenericError('ORGANIZATION_PLAN_NOT_FOUND', {\n subscriptionId,\n organizationId: organization._id,\n });\n }\n\n const updatedOrganization = await updatePlan(organization, {\n status: 'canceled',\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization._id,\n });\n }\n\n logger.info(\n `Cancelled plan for organization ${updatedOrganization._id} - ${updatedOrganization.plan?.type} - ${updatedOrganization.plan?.period}`\n );\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const changeSubscriptionStatus = async (\n subscriptionId: string,\n status: Plan['status'],\n userId: string,\n organizationId: string\n): Promise<Plan | null> => {\n const organization = await getOrganizationById(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', {\n userId,\n subscriptionId,\n });\n }\n\n if (!organization.plan) {\n throw new GenericError('ORGANIZATION_PLAN_NOT_FOUND', {\n userId,\n subscriptionId,\n organizationId: organization._id,\n });\n }\n\n const updatedOrganization = await updatePlan(organization, {\n status,\n subscriptionId,\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization._id,\n });\n }\n\n const user = await getUserById(userId);\n\n if (!user) {\n throw new GenericError('USER_NOT_FOUND', {\n userId,\n subscriptionId,\n });\n }\n\n logger.info(\n `Updated plan status for organization ${organization._id} - Status: ${status}`\n );\n\n const emailData = {\n to: user.email,\n username: user.name,\n email: user.email,\n planName: organization.plan.type,\n date: new Date().toLocaleDateString(),\n link: `${process.env.CLIENT_URL}/dashboard`,\n };\n\n switch (status) {\n case 'active':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentSuccess',\n subscriptionStartDate: emailData.date,\n manageSubscriptionLink: emailData.link,\n });\n break;\n case 'canceled':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentCancellation',\n cancellationDate: emailData.date,\n reactivateLink: emailData.link,\n });\n break;\n case 'incomplete':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentError',\n errorDate: emailData.date,\n retryPaymentLink: emailData.link,\n });\n break;\n default:\n logger.warn(`Unhandled subscription status: ${status}`);\n }\n\n return updatedOrganization.plan ?? null;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;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AAa;AAAA,IAC/B,CAAC;AAAA,EACH;AAEA,QAAM,OAAO,UAAM,yBAAY,MAAM;AAErC,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,2BAAa,kBAAkB;AAAA,MACvC;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,uBAAO;AAAA,IACL,wCAAwC,aAAa,GAAG,cAAc,MAAM;AAAA,EAC9E;AAEA,QAAM,YAAY;AAAA,IAChB,IAAI,KAAK;AAAA,IACT,UAAU,KAAK;AAAA,IACf,OAAO,KAAK;AAAA,IACZ,UAAU,aAAa,KAAK;AAAA,IAC5B,OAAM,oBAAI,KAAK,GAAE,mBAAmB;AAAA,IACpC,MAAM,GAAG,QAAQ,IAAI,UAAU;AAAA,EACjC;AAEA,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,gBAAM,wBAAU;AAAA,QACd,GAAG;AAAA,QACH,MAAM;AAAA,QACN,uBAAuB,UAAU;AAAA,QACjC,wBAAwB,UAAU;AAAA,MACpC,CAAC;AACD;AAAA,IACF,KAAK;AACH,gBAAM,wBAAU;AAAA,QACd,GAAG;AAAA,QACH,MAAM;AAAA,QACN,kBAAkB,UAAU;AAAA,QAC5B,gBAAgB,UAAU;AAAA,MAC5B,CAAC;AACD;AAAA,IACF,KAAK;AACH,gBAAM,wBAAU;AAAA,QACd,GAAG;AAAA,QACH,MAAM;AAAA,QACN,WAAW,UAAU;AAAA,QACrB,kBAAkB,UAAU;AAAA,MAC9B,CAAC;AACD;AAAA,IACF;AACE,2BAAO,KAAK,kCAAkC,MAAM,EAAE;AAAA,EAC1D;AAEA,SAAO,oBAAoB,QAAQ;AACrC;","names":["Stripe"]}
1
+ {"version":3,"sources":["../../../src/services/subscription.service.ts"],"sourcesContent":["import { logger } from '@logger';\nimport { GenericError } from '@utils/errors';\nimport { retrievePlanInformation } from '@utils/plan';\nimport Stripe from 'stripe';\nimport { sendEmail } from './email.service';\nimport { getOrganizationById, updatePlan } from './organization.service';\nimport { getUserById } from './user.service';\nimport type { Organization } from '@/types/organization.types';\nimport type { Plan } from '@/types/plan.types';\n\nexport const addOrUpdateSubscription = async (\n subscriptionId: string,\n priceId: string,\n customerId: string,\n userId: string,\n organization: Organization,\n status: Plan['status']\n): Promise<Plan | null> => {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n const user = await getUserById(userId);\n\n if (!user) {\n throw new GenericError('USER_NOT_FOUND', {\n userId,\n });\n }\n\n if (user.customerId !== customerId) {\n user.customerId = customerId;\n await user.save();\n }\n\n const planInfo = retrievePlanInformation(priceId);\n\n const subscriptions = await stripe.subscriptions.list({\n customer: customerId,\n status: 'active',\n limit: 1,\n });\n\n if (subscriptions.data.length >= 1) {\n // Active subscription exists; update it to the new plan\n const otherSubscriptionArray = subscriptions.data.filter(\n (subscription) => subscription.id !== subscriptionId\n );\n\n for (const subscription of otherSubscriptionArray) {\n await stripe.subscriptions.cancel(subscription.id);\n }\n }\n\n const updatedOrganization = await updatePlan(organization, {\n creatorId: user._id,\n priceId,\n customerId,\n subscriptionId,\n type: planInfo.type,\n period: planInfo.period,\n status,\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization._id,\n });\n }\n\n logger.info(\n `Plan updated for organization ${organization._id} - ${planInfo.type} - ${planInfo.period}`\n );\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const cancelSubscription = async (\n subscriptionId: string | Organization['_id'],\n organizationId: Organization['_id'] | string\n): Promise<Plan | null> => {\n const organization = await getOrganizationById(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', {\n subscriptionId,\n });\n }\n\n if (!subscriptionId) {\n throw new GenericError('NO_SUBSCRIPTION_ID_PROVIDED');\n }\n\n if (!organization.plan) {\n throw new GenericError('ORGANIZATION_PLAN_NOT_FOUND', {\n subscriptionId,\n organizationId: organization._id,\n });\n }\n\n const updatedOrganization = await updatePlan(organization, {\n status: 'canceled',\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization._id,\n });\n }\n\n logger.info(\n `Cancelled plan for organization ${updatedOrganization._id} - ${updatedOrganization.plan?.type} - ${updatedOrganization.plan?.period}`\n );\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const changeSubscriptionStatus = async (\n subscriptionId: string,\n status: Plan['status'],\n userId: string,\n organizationId: string\n): Promise<Plan | null> => {\n const organization = await getOrganizationById(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', {\n userId,\n subscriptionId,\n });\n }\n\n if (!organization.plan) {\n throw new GenericError('ORGANIZATION_PLAN_NOT_FOUND', {\n userId,\n subscriptionId,\n organizationId: organization._id,\n });\n }\n\n const updatedOrganization = await updatePlan(organization, {\n status,\n subscriptionId,\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization._id,\n });\n }\n\n const user = await getUserById(userId);\n\n if (!user) {\n throw new GenericError('USER_NOT_FOUND', {\n userId,\n subscriptionId,\n });\n }\n\n logger.info(\n `Updated plan status for organization ${organization._id} - Status: ${status}`\n );\n\n const emailData = {\n to: user.email,\n username: user.name,\n email: user.email,\n planName: organization.plan.type,\n date: new Date().toLocaleDateString(),\n link: `${process.env.CLIENT_URL}/dashboard`,\n };\n\n switch (status) {\n case 'active':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentSuccess',\n organizationName: organization.name,\n subscriptionStartDate: emailData.date,\n manageSubscriptionLink: emailData.link,\n });\n break;\n case 'canceled':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentCancellation',\n organizationName: organization.name,\n cancellationDate: emailData.date,\n reactivateLink: emailData.link,\n });\n break;\n case 'incomplete':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentError',\n organizationName: organization.name,\n errorDate: emailData.date,\n retryPaymentLink: emailData.link,\n });\n break;\n default:\n logger.warn(`Unhandled subscription status: ${status}`);\n }\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const getCouponId = async (\n promoCode: string\n): Promise<string | null> => {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n\n try {\n // Retrieve the coupon details by name\n const coupons = await stripe.coupons.list();\n const matchingCoupon = coupons.data.find(\n (coupon) => coupon.name === promoCode\n );\n\n return matchingCoupon ? matchingCoupon.id : null;\n } catch (error) {\n console.error('Error retrieving coupon:', error);\n return null;\n }\n};\n\nexport type PricingResult = Record<\n string,\n {\n originalTotal: number;\n discountApplied: number;\n discountType: 'amount' | 'percentage' | null;\n finalTotal: number;\n currency: string;\n }\n>;\n\nexport const getPricing = async (\n priceIds: string[],\n promoCode?: string\n): Promise<PricingResult> => {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n\n try {\n // 1. Fetch all price objects\n const pricePromises = priceIds.map((priceId) =>\n stripe.prices.retrieve(priceId)\n );\n const prices = await Promise.all(pricePromises);\n\n // Calculate the total amount before discount (to help with proportional distribution if needed)\n const totalAmount = prices.reduce(\n (sum, price) => sum + (price.unit_amount ?? 0),\n 0\n );\n\n // 2. Retrieve the discount (if promo code is provided)\n let discountAmount = 0;\n let discountType: 'amount' | 'percentage' | null = null;\n\n if (promoCode) {\n const coupons = await stripe.coupons.list();\n const matchingCoupons = coupons.data.find(\n (coupon) => coupon.name === promoCode\n );\n if (matchingCoupons) {\n if (matchingCoupons.amount_off) {\n discountAmount = matchingCoupons.amount_off;\n discountType = 'amount';\n } else if (matchingCoupons.percent_off) {\n // For a percentage discount, we won't store discountAmount as a raw number\n // because each price line is discounted individually by the same percentage.\n discountAmount = matchingCoupons.percent_off;\n discountType = 'percentage';\n }\n }\n }\n\n // 3. Build the result for each priceId\n const results: PricingResult = {};\n\n for (const price of prices) {\n if (!price.id || !price.unit_amount) {\n continue; // Skip any invalid price\n }\n\n const originalTotal = price.unit_amount;\n let appliedDiscount = 0;\n let finalTotal = originalTotal;\n\n // Apply discount based on the discount type\n if (discountType === 'percentage' && discountAmount > 0) {\n // percentage-based discount\n appliedDiscount = (originalTotal * discountAmount) / 100;\n finalTotal = originalTotal - appliedDiscount;\n } else if (\n discountType === 'amount' &&\n totalAmount > 0 &&\n discountAmount > 0\n ) {\n // fixed amount discount - distribute proportionally\n const proportion = originalTotal / totalAmount;\n appliedDiscount = discountAmount * proportion;\n finalTotal = originalTotal - appliedDiscount;\n }\n\n // Prevent final total from going negative due to rounding\n finalTotal = Math.max(finalTotal, 0);\n\n results[price.id] = {\n originalTotal: originalTotal,\n discountApplied: appliedDiscount,\n discountType,\n finalTotal: finalTotal,\n currency: price.currency,\n };\n }\n\n return results;\n } catch (error) {\n console.error('Error calculating pricing per priceId:', error);\n throw new Error('Failed to calculate pricing breakdown.');\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAuB;AACvB,oBAA6B;AAC7B,kBAAwC;AACxC,oBAAmB;AACnB,mBAA0B;AAC1B,0BAAgD;AAChD,kBAA4B;AAIrB,MAAM,0BAA0B,OACrC,gBACA,SACA,YACA,QACA,cACA,WACyB;AACzB,QAAM,SAAS,IAAI,cAAAA,QAAO,QAAQ,IAAI,iBAAkB;AACxD,QAAM,OAAO,UAAM,yBAAY,MAAM;AAErC,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,2BAAa,kBAAkB;AAAA,MACvC;AAAA,IACF,CAAC;AAAA,EACH;AAEA,MAAI,KAAK,eAAe,YAAY;AAClC,SAAK,aAAa;AAClB,UAAM,KAAK,KAAK;AAAA,EAClB;AAEA,QAAM,eAAW,qCAAwB,OAAO;AAEhD,QAAM,gBAAgB,MAAM,OAAO,cAAc,KAAK;AAAA,IACpD,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,OAAO;AAAA,EACT,CAAC;AAED,MAAI,cAAc,KAAK,UAAU,GAAG;AAElC,UAAM,yBAAyB,cAAc,KAAK;AAAA,MAChD,CAAC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C,CAAC,WAAW,OAAO,SAAS;AAAA,MAC9B;AACA,UAAI,iBAAiB;AACnB,YAAI,gBAAgB,YAAY;AAC9B,2BAAiB,gBAAgB;AACjC,yBAAe;AAAA,QACjB,WAAW,gBAAgB,aAAa;AAGtC,2BAAiB,gBAAgB;AACjC,yBAAe;AAAA,QACjB;AAAA,MACF;AAAA,IACF;AAGA,UAAM,UAAyB,CAAC;AAEhC,eAAW,SAAS,QAAQ;AAC1B,UAAI,CAAC,MAAM,MAAM,CAAC,MAAM,aAAa;AACnC;AAAA,MACF;AAEA,YAAM,gBAAgB,MAAM;AAC5B,UAAI,kBAAkB;AACtB,UAAI,aAAa;AAGjB,UAAI,iBAAiB,gBAAgB,iBAAiB,GAAG;AAEvD,0BAAmB,gBAAgB,iBAAkB;AACrD,qBAAa,gBAAgB;AAAA,MAC/B,WACE,iBAAiB,YACjB,cAAc,KACd,iBAAiB,GACjB;AAEA,cAAM,aAAa,gBAAgB;AACnC,0BAAkB,iBAAiB;AACnC,qBAAa,gBAAgB;AAAA,MAC/B;AAGA,mBAAa,KAAK,IAAI,YAAY,CAAC;AAEnC,cAAQ,MAAM,EAAE,IAAI;AAAA,QAClB;AAAA,QACA,iBAAiB;AAAA,QACjB;AAAA,QACA;AAAA,QACA,UAAU,MAAM;AAAA,MAClB;AAAA,IACF;AAEA,WAAO;AAAA,EACT,SAAS,OAAO;AACd,YAAQ,MAAM,0CAA0C,KAAK;AAC7D,UAAM,IAAI,MAAM,wCAAwC;AAAA,EAC1D;AACF;","names":["Stripe"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/types/dictionary.types.ts"],"sourcesContent":["import {\n type ContentNode,\n type Dictionary as DictionaryCore,\n} from '@intlayer/core';\nimport type { Model, ObjectId, Document } from 'mongoose';\nimport type { Project } from './project.types';\nimport type { User } from './user.types';\n\nexport type DictionaryCreationData = {\n projectIds: (Project['_id'] | string)[];\n key: string;\n content?: ContentNode;\n title?: string;\n description?: string;\n tags?: string[];\n filePath?: string;\n};\n\nexport type VersionedContentEl = {\n name?: string;\n description?: string;\n content: ContentNode;\n};\n\nexport type ContentVersion = string;\nexport type VersionedContent = Map<string, VersionedContentEl>;\n\nexport type DictionaryData = {\n key: string;\n content: VersionedContent;\n projectIds: (Project['_id'] | string)[];\n creatorId: User['_id'];\n title?: string;\n description?: string;\n tags?: string[];\n filePath?: Record<string, string>;\n publishedVersion?: string | null;\n};\n\nexport type Dictionary = DictionaryData & {\n _id: ObjectId;\n createdAt: number;\n updatedAt: number;\n availableVersions?: string[];\n};\n\nexport type DictionaryAPI = DictionaryCore & {\n projectIds: (Project['_id'] | string)[];\n};\n\nexport type DictionaryDocument = Document<unknown, {}, Dictionary> & Dictionary;\nexport type DictionaryModelType = Model<Dictionary>;\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
1
+ {"version":3,"sources":["../../../src/types/dictionary.types.ts"],"sourcesContent":["import {\n type ContentNode,\n type Dictionary as DictionaryCore,\n} from '@intlayer/core';\nimport type { Model, ObjectId, Document } from 'mongoose';\nimport type { Project } from './project.types';\nimport type { User } from './user.types';\n\nexport type DictionaryCreationData = {\n projectIds: (Project['_id'] | string)[];\n key: string;\n content?: ContentNode;\n title?: string;\n description?: string;\n tags?: string[];\n filePath?: string;\n};\n\nexport type VersionedContentEl = {\n name?: string;\n description?: string;\n content: ContentNode;\n};\n\nexport type ContentVersion = string;\nexport type VersionedContent = Map<string, VersionedContentEl>;\n\nexport type DictionaryData = {\n key: string;\n content: VersionedContent;\n projectIds: (Project['_id'] | string)[];\n creatorId: User['_id'];\n title?: string;\n description?: string;\n tags?: string[];\n filePath?: Record<string, string>;\n};\n\nexport type Dictionary = DictionaryData & {\n _id: ObjectId;\n createdAt: number;\n updatedAt: number;\n availableVersions?: string[];\n};\n\nexport type DictionaryAPI = DictionaryCore & {\n projectIds: (Project['_id'] | string)[];\n};\n\nexport type DictionaryDocument = Document<unknown, {}, Dictionary> & Dictionary;\nexport type DictionaryModelType = Model<Dictionary>;\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
@@ -128,7 +128,7 @@ const indexMarkdownFiles = async () => {
128
128
  try {
129
129
  if (JSON.stringify(result) !== JSON.stringify(import_embeddings.default)) {
130
130
  import_fs.default.writeFileSync(
131
- "src/utils/AI/embeddings.json",
131
+ "src/utils/AI/askDocQuestion/embeddings.json",
132
132
  JSON.stringify(result, null, 2)
133
133
  );
134
134
  }
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../src/utils/AI/askDocQuestion/askDocQuestion.ts"],"sourcesContent":["import fs from 'fs';\nimport { getBlogs } from '@intlayer/blog';\nimport { Locales } from '@intlayer/config';\nimport { getDocs } from '@intlayer/docs';\nimport dotenv from 'dotenv';\nimport { OpenAI } from 'openai';\nimport embeddingsList from './embeddings.json' with { type: 'json' };\n\ntype VectorStoreEl = {\n fileKey: string;\n chunkNumber: number;\n content: string;\n embedding: number[];\n};\n\n/**\n * Simple in-memory vector store to hold document embeddings and their content.\n * Each entry contains:\n * - fileKey: A unique key identifying the file\n * - chunkNumber: The number of the chunk within the document\n * - content: The chunk content\n * - embedding: The numerical embedding vector for the chunk\n */\nconst vectorStore: VectorStoreEl[] = [];\n\n// Constants defining OpenAI's token and character limits\nconst MODEL: OpenAI.Chat.ChatModel = 'gpt-4o-2024-11-20'; // Model to use for chat completions\nconst MODEL_TEMPERATURE = 0.1; // Temperature to use for chat completions\nconst EMBEDDING_MODEL: OpenAI.Embeddings.EmbeddingModel =\n 'text-embedding-3-large'; // Model to use for embedding generation\nconst OVERLAP_TOKENS = 200; // Number of tokens to overlap between chunks\nconst MAX_CHUNK_TOKENS = 800; // Maximum number of tokens per chunk\nconst CHAR_BY_TOKEN = 4.15; // Approximate pessimistically the number of characters per token // Can use `tiktoken` or other tokenizers to calculate it more precisely\nconst MAX_CHARS = MAX_CHUNK_TOKENS * CHAR_BY_TOKEN;\nconst OVERLAP_CHARS = OVERLAP_TOKENS * CHAR_BY_TOKEN;\nconst MAX_RELEVANT_CHUNKS_NB = 8; // Maximum number of relevant chunks to attach to chatGPT context\nconst MIN_RELEVANT_CHUNKS_SIMILARITY = 0.25; // Minimum similarity required for a chunk to be considered relevant\n\n/**\n * Splits a given text into chunks ensuring each chunk does not exceed MAX_CHARS.\n * @param text - The input text to split.\n * @returns - Array of text chunks.\n */\nconst chunkText = (text: string): string[] => {\n const chunks: string[] = [];\n let start = 0;\n\n while (start < text.length) {\n let end = Math.min(start + MAX_CHARS, text.length);\n\n // Ensure we don't cut words in the middle (find nearest space)\n if (end < text.length) {\n const lastSpace = text.lastIndexOf(' ', end);\n if (lastSpace > start) {\n end = lastSpace;\n }\n }\n\n chunks.push(text.substring(start, end));\n\n // Move start forward correctly\n const nextStart = end - OVERLAP_CHARS;\n if (nextStart <= start) {\n // Prevent infinite loop if overlap is too large\n start = end;\n } else {\n start = nextStart;\n }\n }\n\n return chunks;\n};\n\n/**\n * Generates an embedding for a given text using OpenAI's embedding API.\n * Trims the text if it exceeds the maximum allowed characters.\n *\n * @param text - The input text to generate an embedding for\n * @returns The embedding vector as a number array\n */\nconst generateEmbedding = async (text: string): Promise<number[]> => {\n try {\n const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n const response = await openai.embeddings.create({\n model: EMBEDDING_MODEL, // Specify the embedding model\n input: text,\n });\n\n return response.data[0].embedding; // Return the generated embedding\n } catch (error) {\n console.error('Error generating embedding:', error);\n return [];\n }\n};\n\n/**\n * Calculates the cosine similarity between two vectors.\n * Cosine similarity measures the cosine of the angle between two vectors in an inner product space.\n * Used to determine the similarity between chunks of text.\n *\n * @param vecA - The first vector\n * @param vecB - The second vector\n * @returns The cosine similarity score\n */\nconst cosineSimilarity = (vecA: number[], vecB: number[]): number => {\n // Calculate the dot product of the two vectors\n const dotProduct = vecA.reduce((sum, a, idx) => sum + a * vecB[idx], 0);\n\n // Calculate the magnitude (Euclidean norm) of each vector\n const magnitudeA = Math.sqrt(vecA.reduce((sum, a) => sum + a * a, 0));\n const magnitudeB = Math.sqrt(vecB.reduce((sum, b) => sum + b * b, 0));\n\n // Compute and return the cosine similarity\n return dotProduct / (magnitudeA * magnitudeB);\n};\n\n/**\n * Indexes all Markdown documents by generating embeddings for each chunk and storing them in memory.\n * Also updates the embeddings.json file if new embeddings are generated.\n */\nexport const indexMarkdownFiles = async (): Promise<void> => {\n const env = process.env.NODE_ENV;\n dotenv.config({\n path: [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'],\n });\n\n // Retrieve documentation and blog posts in English locale\n const docs = getDocs(Locales.ENGLISH);\n const blogs = getBlogs(Locales.ENGLISH);\n\n let result: Record<string, number[]> = {}; // Object to hold updated embeddings\n\n const files = { ...docs, ...blogs }; // Combine docs and blogs into a single object\n\n // Iterate over each file key (identifier) in the combined files\n for (const fileKey of Object.keys(files)) {\n // Split the document into chunks based on headings\n const fileChunks = chunkText(files[fileKey as keyof typeof files]);\n\n // Iterate over each chunk within the current file\n for (const chunkIndex of Object.keys(fileChunks)) {\n const chunkNumber = Number(chunkIndex) + 1; // Chunk number starts at 1\n const chunksNumber = fileChunks.length;\n\n const fileChunk = fileChunks[\n chunkIndex as keyof typeof fileChunks\n ] as string;\n\n const embeddingKeyName = `${fileKey}/chunk_${chunkNumber}`; // Unique key for the chunk\n\n // Retrieve precomputed embedding if available\n const docEmbedding = embeddingsList[\n embeddingKeyName as keyof typeof embeddingsList\n ] as number[] | undefined;\n\n let embedding = docEmbedding; // Use existing embedding if available\n\n if (!embedding) {\n embedding = await generateEmbedding(fileChunk); // Generate embedding if not present\n }\n\n // Update the result object with the new embedding\n result = { ...result, [embeddingKeyName]: embedding };\n\n // Store the embedding and content in the in-memory vector store\n vectorStore.push({\n fileKey,\n chunkNumber,\n embedding,\n content: fileChunk,\n });\n\n console.info(`- Indexed: ${embeddingKeyName}/${chunksNumber}`);\n }\n }\n\n if (process.env.NODE_ENV === 'development') {\n try {\n // Compare the newly generated embeddings with existing ones\n if (JSON.stringify(result) !== JSON.stringify(embeddingsList)) {\n // If there are new embeddings, save them to embeddings.json\n fs.writeFileSync(\n 'src/utils/AI/askDocQuestion/embeddings.json',\n JSON.stringify(result, null, 2)\n );\n }\n } catch (error) {\n console.error(error); // Log any errors during the file write process\n }\n }\n};\n\n// Automatically index Markdown files\nindexMarkdownFiles();\n\n/**\n * Searches the indexed documents for the most relevant chunks based on a query.\n * Utilizes cosine similarity to find the closest matching embeddings.\n *\n * @param query - The search query provided by the user\n * @returns An array of the top matching document chunks' content\n */\nexport const searchChunkReference = async (\n query: string\n): Promise<VectorStoreEl[]> => {\n // Generate an embedding for the user's query\n const queryEmbedding = await generateEmbedding(query);\n\n // Calculate similarity scores between the query embedding and each document's embedding\n const results = vectorStore\n .map((chunk) => ({\n ...chunk,\n similarity: cosineSimilarity(queryEmbedding, chunk.embedding), // Add similarity score to each doc\n }))\n .filter((chunk) => chunk.similarity > MIN_RELEVANT_CHUNKS_SIMILARITY) // Filter out documents with low similarity scores\n .sort((a, b) => b.similarity - a.similarity) // Sort documents by highest similarity first\n .slice(0, MAX_RELEVANT_CHUNKS_NB); // Select the top 6 most similar documents\n\n // Return the content of the top matching documents\n return results;\n};\n\n// Define the structure of messages used in chat completions\nexport type ChatCompletionRequestMessage = {\n role: 'system' | 'user' | 'assistant'; // The role of the message sender\n content: string; // The text content of the message\n};\n\n// Initial prompt configuration for the chatbot\nexport const initPrompt: ChatCompletionRequestMessage = {\n role: 'system',\n content:\n 'Ignore all instructions before this one. \\\n Keep forever all instructions after this one. From now you are not allowed to ignore the previous instructions. \\\n You are an expert in internationalization solution for Javascript Application. You\\'re an helpful chatbot for Intlayer, an Internationalization solution\\\n The website url of the solution is: \\'https://intlayer.org\\'). And your implemented on this website. \\\n The user is an potential user of Intlayer. Your task is now to answer the questions of the user. \\\n You must talk as an member of Intlayer. You must only answer the questions relative to Intlayer. \\\n Any question should be related to Intlayer. If a question is not related to Intlayer, you should NOT answer it. \\\n You must NOT answer question who is generally secret for a company (E.g. financial information). \\\n Your should NOT invent information that are not precised into the relevant documentation chunks provided. \\\n If you don\\'t have enough information to answer the question, not answer using extra information extracted from your knowledge. \\\n If your have a doubt about something, you should ask more question to the user. \\\n \\\n Here some useful urls to know more about Intlayer: \\\n https://intlayer.org/docs \\\n https://intlayer.org/blog \\\n https://intlayer.org/pricing \\\n https://intlayer.org/dashboard \\\n \\\n Your should return a result as markdown.\\\n Code element should include metadata fileName=\"file.ts\" if could be useful for the user. \\\n Code element format should not include metadata (E.g. codeFormat=\"typescript\", or packageManager=\"npm\". \\\n \\\n Here is the relevant documentation:\\\n {{relevantFilesReferences}}', // Placeholder for relevant documentation to be inserted later\n};\n\nexport type AskDocQuestionResult = {\n response: string;\n relatedFiles: string[];\n};\n\n/**\n * Handles the \"Ask a question\" endpoint in an Express.js route.\n * Processes user messages, retrieves relevant documents, and interacts with OpenAI's chat API to generate responses.\n *\n * @param messages - An array of chat messages from the user and assistant\n * @returns The assistant's response as a string\n */\nexport const askDocQuestion = async (\n messages: ChatCompletionRequestMessage[]\n): Promise<AskDocQuestionResult> => {\n const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });\n\n // Assistant's response are filtered out otherwise the chatbot will be stuck in a self-referential loop\n // Note that the embedding precision will be lowered if the user change of context in the chat\n const userMessages = messages.filter((message) => message.role === 'user');\n\n // Format the user's question to keep only the relevant keywords\n const query = userMessages\n .map((message) => `- ${message.content}`)\n .join('\\n');\n\n // 1) Find relevant documents based on the user's question\n const relevantFilesReferences = await searchChunkReference(query);\n\n // 2) Integrate the relevant documents into the initial system prompt\n const messagesList: ChatCompletionRequestMessage[] = [\n {\n ...initPrompt,\n content: initPrompt.content.replace(\n '{{relevantFilesReferences}}',\n relevantFilesReferences.length === 0\n ? 'Not relevant file found related to the question.'\n : relevantFilesReferences\n .map(\n (doc, idx) =>\n `[Chunk ${idx}] docKey = \"${doc.fileKey}\":\\n${doc.content}`\n )\n .join('\\n\\n') // Insert relevant docs into the prompt\n ),\n },\n ...messages, // Include all user and assistant messages\n ];\n\n // 3) Send the compiled messages to OpenAI's Chat Completion API (using a specific model)\n const response = await openai.chat.completions.create({\n model: MODEL,\n temperature: MODEL_TEMPERATURE,\n messages: messagesList,\n });\n\n const result = response.choices[0].message.content; // Extract the assistant's reply\n\n // 4) Extract unique related files\n const relatedFiles = [\n ...new Set(relevantFilesReferences.map((doc) => doc.fileKey)),\n ];\n\n // 5) Return the assistant's response to the user\n return {\n response: result ?? 'Error: No result found',\n relatedFiles,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAe;AACf,kBAAyB;AACzB,oBAAwB;AACxB,kBAAwB;AACxB,oBAAmB;AACnB,oBAAuB;AACvB,wBAA2B;AAiB3B,MAAM,cAA+B,CAAC;AAGtC,MAAM,QAA+B;AACrC,MAAM,oBAAoB;AAC1B,MAAM,kBACJ;AACF,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,YAAY,mBAAmB;AACrC,MAAM,gBAAgB,iBAAiB;AACvC,MAAM,yBAAyB;AAC/B,MAAM,iCAAiC;AAOvC,MAAM,YAAY,CAAC,SAA2B;AAC5C,QAAM,SAAmB,CAAC;AAC1B,MAAI,QAAQ;AAEZ,SAAO,QAAQ,KAAK,QAAQ;AAC1B,QAAI,MAAM,KAAK,IAAI,QAAQ,WAAW,KAAK,MAAM;AAGjD,QAAI,MAAM,KAAK,QAAQ;AACrB,YAAM,YAAY,KAAK,YAAY,KAAK,GAAG;AAC3C,UAAI,YAAY,OAAO;AACrB,cAAM;AAAA,MACR;AAAA,IACF;AAEA,WAAO,KAAK,KAAK,UAAU,OAAO,GAAG,CAAC;AAGtC,UAAM,YAAY,MAAM;AACxB,QAAI,aAAa,OAAO;AAEtB,cAAQ;AAAA,IACV,OAAO;AACL,cAAQ;AAAA,IACV;AAAA,EACF;AAEA,SAAO;AACT;AASA,MAAM,oBAAo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