pika-shared 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/index.js.map +1 -1
  2. package/dist/index.mjs.map +1 -1
  3. package/dist/types/chatbot/bedrock-lambda-error.js.map +1 -1
  4. package/dist/types/chatbot/bedrock-lambda-error.mjs.map +1 -1
  5. package/dist/types/chatbot/chatbot-types.d.mts +467 -14
  6. package/dist/types/chatbot/chatbot-types.d.ts +467 -14
  7. package/dist/types/chatbot/chatbot-types.js +6 -2
  8. package/dist/types/chatbot/chatbot-types.js.map +1 -1
  9. package/dist/types/chatbot/chatbot-types.mjs +6 -3
  10. package/dist/types/chatbot/chatbot-types.mjs.map +1 -1
  11. package/dist/types/chatbot/webcomp-types.d.mts +107 -0
  12. package/dist/types/chatbot/webcomp-types.d.ts +107 -0
  13. package/dist/types/chatbot/webcomp-types.js +4 -0
  14. package/dist/types/chatbot/webcomp-types.js.map +1 -0
  15. package/dist/types/chatbot/webcomp-types.mjs +3 -0
  16. package/dist/types/chatbot/webcomp-types.mjs.map +1 -0
  17. package/dist/util/api-gateway-utils.js +14 -1
  18. package/dist/util/api-gateway-utils.js.map +1 -1
  19. package/dist/util/api-gateway-utils.mjs +14 -1
  20. package/dist/util/api-gateway-utils.mjs.map +1 -1
  21. package/dist/util/bad-request-error.d.mts +7 -0
  22. package/dist/util/bad-request-error.d.ts +7 -0
  23. package/dist/util/bad-request-error.js +20 -0
  24. package/dist/util/bad-request-error.js.map +1 -0
  25. package/dist/util/bad-request-error.mjs +18 -0
  26. package/dist/util/bad-request-error.mjs.map +1 -0
  27. package/dist/util/bedrock.js.map +1 -1
  28. package/dist/util/bedrock.mjs.map +1 -1
  29. package/dist/util/chatbot-shared-utils.js.map +1 -1
  30. package/dist/util/chatbot-shared-utils.mjs.map +1 -1
  31. package/dist/util/forbidden-error.d.mts +7 -0
  32. package/dist/util/forbidden-error.d.ts +7 -0
  33. package/dist/util/forbidden-error.js +20 -0
  34. package/dist/util/forbidden-error.js.map +1 -0
  35. package/dist/util/forbidden-error.mjs +18 -0
  36. package/dist/util/forbidden-error.mjs.map +1 -0
  37. package/dist/util/http-status-error.js.map +1 -1
  38. package/dist/util/http-status-error.mjs.map +1 -1
  39. package/dist/util/instruction-assistance-utils.js.map +1 -1
  40. package/dist/util/instruction-assistance-utils.mjs.map +1 -1
  41. package/dist/util/jwt.js.map +1 -1
  42. package/dist/util/jwt.mjs.map +1 -1
  43. package/dist/util/server-client-utils.js.map +1 -1
  44. package/dist/util/server-client-utils.mjs.map +1 -1
  45. package/dist/util/server-utils.d.mts +41 -1
  46. package/dist/util/server-utils.d.ts +41 -1
  47. package/dist/util/server-utils.js +303 -0
  48. package/dist/util/server-utils.js.map +1 -1
  49. package/dist/util/server-utils.mjs +301 -1
  50. package/dist/util/server-utils.mjs.map +1 -1
  51. package/dist/util/unauthorized-error.d.mts +7 -0
  52. package/dist/util/unauthorized-error.d.ts +7 -0
  53. package/dist/util/unauthorized-error.js +20 -0
  54. package/dist/util/unauthorized-error.js.map +1 -0
  55. package/dist/util/unauthorized-error.mjs +18 -0
  56. package/dist/util/unauthorized-error.mjs.map +1 -0
  57. package/dist/util/wc-utils.d.mts +22 -0
  58. package/dist/util/wc-utils.d.ts +22 -0
  59. package/dist/util/wc-utils.js +26 -0
  60. package/dist/util/wc-utils.js.map +1 -0
  61. package/dist/util/wc-utils.mjs +24 -0
  62. package/dist/util/wc-utils.mjs.map +1 -0
  63. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/chatbot-shared-utils.ts"],"names":[],"mappings":";;;;AAwBO,SAAS,+BAAA,CAAgC,MAAgB,EAAA,QAAA,EAAkB,MAAwB,EAAA;AACtG,EAAA,OAAO,CAAW,QAAA,EAAA,MAAM,CAAI,CAAA,EAAA,MAAM,IAAI,QAAQ,CAAA,CAAA;AAClD;AAQO,SAAS,iBAAiB,QAA0B,EAAA;AACvD,EAAM,MAAA,YAAA,GAAe,QAAS,CAAA,WAAA,CAAY,GAAG,CAAA;AAG7C,EAAA,IAAI,iBAAiB,EAAM,IAAA,YAAA,KAAiB,SAAS,MAAS,GAAA,CAAA,IAAK,iBAAiB,CAAG,EAAA;AACnF,IAAO,OAAA,QAAA,CAAS,OAAQ,CAAA,iBAAA,EAAmB,EAAE,CAAA;AAAA;AAGjD,EAAA,MAAM,oBAAuB,GAAA,QAAA,CAAS,SAAU,CAAA,CAAA,EAAG,YAAY,CAAA;AAC/D,EAAA,MAAM,SAAY,GAAA,QAAA,CAAS,SAAU,CAAA,YAAA,GAAe,CAAC,CAAA;AAErD,EAAA,MAAM,aAAgB,GAAA,oBAAA,CAAqB,OAAQ,CAAA,iBAAA,EAAmB,EAAE,CAAA;AACxE,EAAA,MAAM,kBAAqB,GAAA,SAAA,CAAU,OAAQ,CAAA,iBAAA,EAAmB,EAAE,CAAA;AAElE,EAAA,OAAO,gBAAgB,GAAM,GAAA,kBAAA;AACjC;AAcO,SAAS,mBAAqC,IAAuB,EAAA;AACxE,EAAA,OAAO,aAAc,CAAA,IAAA,EAAM,EAAE,IAAA,EAAM,MAAM,CAAA;AAC7C;AAEO,SAAS,mBAAqD,IAAuB,EAAA;AACxF,EAAA,OAAO,aAAc,CAAA,IAAA,EAAM,EAAE,IAAA,EAAM,MAAM,CAAA;AAC7C;AAEO,SAAS,yBAAyB,GAAqB,EAAA;AAC1D,EAAA,MAAM,OAAU,GAAA,EAAE,CAAC,GAAG,GAAG,IAAK,EAAA;AAC9B,EAAM,MAAA,SAAA,GAAY,cAAc,OAAO,CAAA;AACvC,EAAA,OAAO,MAAO,CAAA,IAAA,CAAK,SAAS,CAAA,CAAE,CAAC,CAAA;AACnC","file":"chatbot-shared-utils.mjs","sourcesContent":["/**\n * These utilities are meant to be shared both client and server.\n * Don't add anything that can't be shared (especially dependencies)\n */\n\nimport type { ChatApp, ChatAppFeature, FeatureIdType } from '../types/chatbot/chatbot-types';\nimport camelcaseKeys from 'camelcase-keys';\nimport snakecaseKeys from 'snakecase-keys';\n\n/**\n * Generate a unique S3 key name for a chat file upload.\n *\n * Use the uuid module to generate the v7 uuid as in\n *\n * Replace punctation that isn't _ or - with a _\n *\n * import { v7 as uuidv7 } from 'uuid';\n * uuidv7()\n *\n * @param userId - The user id of the user uploading the file\n * @param fileName - The name of the file to upload. it should already be sanitized by calling sanitizeFileName\n * @param v7Uuid - The uuidv7 uuid of the file\n * @returns The S3 key name for the file\n */\nexport function generateChatFileUploadS3KeyName(userId: string, fileName: string, v7Uuid: string): string {\n return `uploads/${userId}/${v7Uuid}_${fileName}`;\n}\n\n/**\n * Remove all punctuation from a file name except for the ending period for the file extension if it exists\n *\n * @param fileName - The name of the file to sanitize\n * @returns The sanitized file name\n */\nexport function sanitizeFileName(fileName: string): string {\n const lastDotIndex = fileName.lastIndexOf('.');\n\n // If there's no dot, or the dot is at the end, or the dot is at the beginning, just remove all punctuation\n if (lastDotIndex === -1 || lastDotIndex === fileName.length - 1 || lastDotIndex === 0) {\n return fileName.replace(/[^a-zA-Z0-9_-]/g, '');\n }\n\n const nameWithoutExtension = fileName.substring(0, lastDotIndex);\n const extension = fileName.substring(lastDotIndex + 1);\n\n const sanitizedName = nameWithoutExtension.replace(/[^a-zA-Z0-9_-]/g, '');\n const sanitizedExtension = extension.replace(/[^a-zA-Z0-9_-]/g, '');\n\n return sanitizedName + '.' + sanitizedExtension;\n}\n\ntype ToSnakeCase<S extends string> = S extends `${infer T}${infer U}` ? `${T extends Capitalize<T> ? '_' : ''}${Lowercase<T>}${ToSnakeCase<U>}` : S;\n\ntype ToCamelCase<S extends string> = S extends `${infer P1}_${infer P2}${infer P3}` ? `${Lowercase<P1>}${Uppercase<P2>}${ToCamelCase<P3>}` : Lowercase<S>;\n\nexport type SnakeCase<T> = {\n [K in keyof T as K extends string ? ToSnakeCase<K> : K]: T[K] extends object ? SnakeCase<T[K]> : T[K];\n};\n\nexport type CamelCase<T> = {\n [K in keyof T as K extends string ? ToCamelCase<K> : K]: T[K] extends object ? CamelCase<T[K]> : T[K];\n};\n\nexport function convertToCamelCase<T extends object>(data: SnakeCase<T>): T {\n return camelcaseKeys(data, { deep: true }) as unknown as T;\n}\n\nexport function convertToSnakeCase<T extends { [key: string]: any }>(data: T): SnakeCase<T> {\n return snakecaseKeys(data, { deep: true }) as SnakeCase<T>;\n}\n\nexport function convertStringToSnakeCase(str: string): string {\n const tempObj = { [str]: true };\n const converted = snakecaseKeys(tempObj);\n return Object.keys(converted)[0];\n}\n\n// /**\n// * This lets us get a feature from a chat app and make sure it is the correct type.\n// */\n// export function getFeature<T extends FeatureIdType>(chatApp: ChatApp, featureId: T): Extract<ChatAppFeature, { featureId: T }> | undefined {\n// const feature = chatApp.features?.[featureId];\n\n// if (feature && feature.featureId === featureId) {\n// return feature as Extract<ChatAppFeature, { featureId: T }>;\n// }\n\n// return undefined;\n// }\n"]}
1
+ {"version":3,"sources":["../../src/util/chatbot-shared-utils.ts"],"names":[],"mappings":";;;;AAwBO,SAAS,+BAAA,CAAgC,MAAA,EAAgB,QAAA,EAAkB,MAAA,EAAwB;AACtG,EAAA,OAAO,CAAA,QAAA,EAAW,MAAM,CAAA,CAAA,EAAI,MAAM,IAAI,QAAQ,CAAA,CAAA;AAClD;AAQO,SAAS,iBAAiB,QAAA,EAA0B;AACvD,EAAA,MAAM,YAAA,GAAe,QAAA,CAAS,WAAA,CAAY,GAAG,CAAA;AAG7C,EAAA,IAAI,iBAAiB,EAAA,IAAM,YAAA,KAAiB,SAAS,MAAA,GAAS,CAAA,IAAK,iBAAiB,CAAA,EAAG;AACnF,IAAA,OAAO,QAAA,CAAS,OAAA,CAAQ,iBAAA,EAAmB,EAAE,CAAA;AAAA,EACjD;AAEA,EAAA,MAAM,oBAAA,GAAuB,QAAA,CAAS,SAAA,CAAU,CAAA,EAAG,YAAY,CAAA;AAC/D,EAAA,MAAM,SAAA,GAAY,QAAA,CAAS,SAAA,CAAU,YAAA,GAAe,CAAC,CAAA;AAErD,EAAA,MAAM,aAAA,GAAgB,oBAAA,CAAqB,OAAA,CAAQ,iBAAA,EAAmB,EAAE,CAAA;AACxE,EAAA,MAAM,kBAAA,GAAqB,SAAA,CAAU,OAAA,CAAQ,iBAAA,EAAmB,EAAE,CAAA;AAElE,EAAA,OAAO,gBAAgB,GAAA,GAAM,kBAAA;AACjC;AAcO,SAAS,mBAAqC,IAAA,EAAuB;AACxE,EAAA,OAAO,aAAA,CAAc,IAAA,EAAM,EAAE,IAAA,EAAM,MAAM,CAAA;AAC7C;AAEO,SAAS,mBAAqD,IAAA,EAAuB;AACxF,EAAA,OAAO,aAAA,CAAc,IAAA,EAAM,EAAE,IAAA,EAAM,MAAM,CAAA;AAC7C;AAEO,SAAS,yBAAyB,GAAA,EAAqB;AAC1D,EAAA,MAAM,OAAA,GAAU,EAAE,CAAC,GAAG,GAAG,IAAA,EAAK;AAC9B,EAAA,MAAM,SAAA,GAAY,cAAc,OAAO,CAAA;AACvC,EAAA,OAAO,MAAA,CAAO,IAAA,CAAK,SAAS,CAAA,CAAE,CAAC,CAAA;AACnC","file":"chatbot-shared-utils.mjs","sourcesContent":["/**\n * These utilities are meant to be shared both client and server.\n * Don't add anything that can't be shared (especially dependencies)\n */\n\nimport type { ChatApp, ChatAppFeature, FeatureIdType } from '../types/chatbot/chatbot-types';\nimport camelcaseKeys from 'camelcase-keys';\nimport snakecaseKeys from 'snakecase-keys';\n\n/**\n * Generate a unique S3 key name for a chat file upload.\n *\n * Use the uuid module to generate the v7 uuid as in\n *\n * Replace punctation that isn't _ or - with a _\n *\n * import { v7 as uuidv7 } from 'uuid';\n * uuidv7()\n *\n * @param userId - The user id of the user uploading the file\n * @param fileName - The name of the file to upload. it should already be sanitized by calling sanitizeFileName\n * @param v7Uuid - The uuidv7 uuid of the file\n * @returns The S3 key name for the file\n */\nexport function generateChatFileUploadS3KeyName(userId: string, fileName: string, v7Uuid: string): string {\n return `uploads/${userId}/${v7Uuid}_${fileName}`;\n}\n\n/**\n * Remove all punctuation from a file name except for the ending period for the file extension if it exists\n *\n * @param fileName - The name of the file to sanitize\n * @returns The sanitized file name\n */\nexport function sanitizeFileName(fileName: string): string {\n const lastDotIndex = fileName.lastIndexOf('.');\n\n // If there's no dot, or the dot is at the end, or the dot is at the beginning, just remove all punctuation\n if (lastDotIndex === -1 || lastDotIndex === fileName.length - 1 || lastDotIndex === 0) {\n return fileName.replace(/[^a-zA-Z0-9_-]/g, '');\n }\n\n const nameWithoutExtension = fileName.substring(0, lastDotIndex);\n const extension = fileName.substring(lastDotIndex + 1);\n\n const sanitizedName = nameWithoutExtension.replace(/[^a-zA-Z0-9_-]/g, '');\n const sanitizedExtension = extension.replace(/[^a-zA-Z0-9_-]/g, '');\n\n return sanitizedName + '.' + sanitizedExtension;\n}\n\ntype ToSnakeCase<S extends string> = S extends `${infer T}${infer U}` ? `${T extends Capitalize<T> ? '_' : ''}${Lowercase<T>}${ToSnakeCase<U>}` : S;\n\ntype ToCamelCase<S extends string> = S extends `${infer P1}_${infer P2}${infer P3}` ? `${Lowercase<P1>}${Uppercase<P2>}${ToCamelCase<P3>}` : Lowercase<S>;\n\nexport type SnakeCase<T> = {\n [K in keyof T as K extends string ? ToSnakeCase<K> : K]: T[K] extends object ? SnakeCase<T[K]> : T[K];\n};\n\nexport type CamelCase<T> = {\n [K in keyof T as K extends string ? ToCamelCase<K> : K]: T[K] extends object ? CamelCase<T[K]> : T[K];\n};\n\nexport function convertToCamelCase<T extends object>(data: SnakeCase<T>): T {\n return camelcaseKeys(data, { deep: true }) as unknown as T;\n}\n\nexport function convertToSnakeCase<T extends { [key: string]: any }>(data: T): SnakeCase<T> {\n return snakecaseKeys(data, { deep: true }) as SnakeCase<T>;\n}\n\nexport function convertStringToSnakeCase(str: string): string {\n const tempObj = { [str]: true };\n const converted = snakecaseKeys(tempObj);\n return Object.keys(converted)[0];\n}\n\n// /**\n// * This lets us get a feature from a chat app and make sure it is the correct type.\n// */\n// export function getFeature<T extends FeatureIdType>(chatApp: ChatApp, featureId: T): Extract<ChatAppFeature, { featureId: T }> | undefined {\n// const feature = chatApp.features?.[featureId];\n\n// if (feature && feature.featureId === featureId) {\n// return feature as Extract<ChatAppFeature, { featureId: T }>;\n// }\n\n// return undefined;\n// }\n"]}
@@ -0,0 +1,7 @@
1
+ import { HttpStatusError } from './http-status-error.mjs';
2
+
3
+ declare class ForbiddenError extends HttpStatusError {
4
+ constructor(message: string);
5
+ }
6
+
7
+ export { ForbiddenError };
@@ -0,0 +1,7 @@
1
+ import { HttpStatusError } from './http-status-error.js';
2
+
3
+ declare class ForbiddenError extends HttpStatusError {
4
+ constructor(message: string);
5
+ }
6
+
7
+ export { ForbiddenError };
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+
3
+ // src/util/http-status-error.ts
4
+ var HttpStatusError = class extends Error {
5
+ constructor(message, statusCode) {
6
+ super(message);
7
+ this.statusCode = statusCode;
8
+ }
9
+ };
10
+
11
+ // src/util/forbidden-error.ts
12
+ var ForbiddenError = class extends HttpStatusError {
13
+ constructor(message) {
14
+ super(message, 403);
15
+ }
16
+ };
17
+
18
+ exports.ForbiddenError = ForbiddenError;
19
+ //# sourceMappingURL=forbidden-error.js.map
20
+ //# sourceMappingURL=forbidden-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/http-status-error.ts","../../src/util/forbidden-error.ts"],"names":[],"mappings":";;;AAGO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACvC,WAAA,CACI,SACgB,UAAA,EAClB;AACE,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA,EAGpB;AACJ,CAAA;;;ACRO,IAAM,cAAA,GAAN,cAA6B,eAAA,CAAgB;AAAA,EAChD,YAAY,OAAA,EAAiB;AACzB,IAAA,KAAA,CAAM,SAAS,GAAG,CAAA;AAAA,EACtB;AACJ","file":"forbidden-error.js","sourcesContent":["/**\n * Throw this error to return a specific HTTP status code from an API Gateway Lambda function.\n */\nexport class HttpStatusError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number\n ) {\n super(message);\n }\n}\n","import { HttpStatusError } from './http-status-error';\n\nexport class ForbiddenError extends HttpStatusError {\n constructor(message: string) {\n super(message, 403);\n }\n}\n"]}
@@ -0,0 +1,18 @@
1
+ // src/util/http-status-error.ts
2
+ var HttpStatusError = class extends Error {
3
+ constructor(message, statusCode) {
4
+ super(message);
5
+ this.statusCode = statusCode;
6
+ }
7
+ };
8
+
9
+ // src/util/forbidden-error.ts
10
+ var ForbiddenError = class extends HttpStatusError {
11
+ constructor(message) {
12
+ super(message, 403);
13
+ }
14
+ };
15
+
16
+ export { ForbiddenError };
17
+ //# sourceMappingURL=forbidden-error.mjs.map
18
+ //# sourceMappingURL=forbidden-error.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/http-status-error.ts","../../src/util/forbidden-error.ts"],"names":[],"mappings":";AAGO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACvC,WAAA,CACI,SACgB,UAAA,EAClB;AACE,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA,EAGpB;AACJ,CAAA;;;ACRO,IAAM,cAAA,GAAN,cAA6B,eAAA,CAAgB;AAAA,EAChD,YAAY,OAAA,EAAiB;AACzB,IAAA,KAAA,CAAM,SAAS,GAAG,CAAA;AAAA,EACtB;AACJ","file":"forbidden-error.mjs","sourcesContent":["/**\n * Throw this error to return a specific HTTP status code from an API Gateway Lambda function.\n */\nexport class HttpStatusError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number\n ) {\n super(message);\n }\n}\n","import { HttpStatusError } from './http-status-error';\n\nexport class ForbiddenError extends HttpStatusError {\n constructor(message: string) {\n super(message, 403);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/http-status-error.ts"],"names":[],"mappings":";;;AAGa,IAAA,eAAA,GAAN,cAA8B,KAAM,CAAA;AAAA,EACvC,WAAA,CACI,SACgB,UAClB,EAAA;AACE,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA;AAIxB","file":"http-status-error.js","sourcesContent":["/**\n * Throw this error to return a specific HTTP status code from an API Gateway Lambda function.\n */\nexport class HttpStatusError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number\n ) {\n super(message);\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/util/http-status-error.ts"],"names":[],"mappings":";;;AAGO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACvC,WAAA,CACI,SACgB,UAAA,EAClB;AACE,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA,EAGpB;AACJ","file":"http-status-error.js","sourcesContent":["/**\n * Throw this error to return a specific HTTP status code from an API Gateway Lambda function.\n */\nexport class HttpStatusError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number\n ) {\n super(message);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/http-status-error.ts"],"names":[],"mappings":";AAGa,IAAA,eAAA,GAAN,cAA8B,KAAM,CAAA;AAAA,EACvC,WAAA,CACI,SACgB,UAClB,EAAA;AACE,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA;AAIxB","file":"http-status-error.mjs","sourcesContent":["/**\n * Throw this error to return a specific HTTP status code from an API Gateway Lambda function.\n */\nexport class HttpStatusError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number\n ) {\n super(message);\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/util/http-status-error.ts"],"names":[],"mappings":";AAGO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACvC,WAAA,CACI,SACgB,UAAA,EAClB;AACE,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA,EAGpB;AACJ","file":"http-status-error.mjs","sourcesContent":["/**\n * Throw this error to return a specific HTTP status code from an API Gateway Lambda function.\n */\nexport class HttpStatusError extends Error {\n constructor(\n message: string,\n public readonly statusCode: number\n ) {\n super(message);\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/instruction-assistance-utils.ts"],"names":[],"mappings":";;;AAgCO,SAAS,oCACZ,CAAA,2BAAA,EACA,IACA,EAAA,uBAAA,EACA,cAC2B,EAAA;AAC3B,EAAA,OAAA,CAAQ,IAAI,4CAA8C,EAAA;AAAA,IACtD,SAAS,uBAAyB,EAAA,OAAA;AAAA,IAClC,qCAAqC,uBAAyB,EAAA,mCAAA;AAAA,IAC9D,4BAA4B,uBAAyB,EAAA,0BAAA;AAAA,IACrD,wBAAwB,uBAAyB,EAAA,iCAAA;AAAA,IACjD,iBAAiB,uBAAyB,EAAA;AAAA,GAC7C,CAAA;AAED,EAAA,IAAI,4BAA+B,GAAA,EAAA;AACnC,EAAA,IAAI,eAAkB,GAAA,EAAA;AACtB,EAAA,IAAI,8BAAiC,GAAA,EAAA;AACrC,EAAA,IAAI,iCAAoC,GAAA,EAAA;AAExC,EAAI,IAAA,CAAC,yBAAyB,OAAS,EAAA;AACnC,IAAO,OAAA;AAAA,MACH,4BAAA;AAAA,MACA,eAAA;AAAA,MACA,8BAAA;AAAA,MACA;AAAA,KACJ;AAAA;AAIJ,EAAA,IAAI,wBAAwB,mCAAqC,EAAA;AAC7D,IAAA,4BAAA,GACI,6BAA6B,4BAC7B,IAAA,CAAA;AAAA;AAAA,0FAAA,CAAA;AAAA;AAMR,EAAA,IAAI,wBAAwB,0BAA8B,IAAA,IAAA,IAAQ,IAAK,CAAA,WAAA,EAAa,SAAS,CAAG,EAAA;AAC5F,IAAQ,OAAA,CAAA,GAAA,CAAI,sDAAwD,EAAA,IAAA,CAAK,WAAW,CAAA;A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AA,MACN,uDAAuD,MAAO,CAAA,IAAA,CAAK,MAAM,CAAA,CACpE,OAAO,CAAC,GAAA,KAAQ,CAAC,YAAA,CAAa,SAAS,GAAG,CAAC,CAC3C,CAAA,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,KACnB;AAAA;AAGJ,EAAO,OAAA;AAAA,IACH,4BAAA,EAA8B,OAAO,gCAAgC,CAAA;AAAA,IACrE,8BAAA,EAAgC,OAAO,+BAA+B,CAAA;AAAA,IACtE,iCAAA,EAAmC,OAAO,8BAA8B;AAAA,GAC5E;AACJ","file":"instruction-assistance-utils.js","sourcesContent":["/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * The functions in this utility are used both by the front end svelte kit web client in the browser\n * and in the backend lambda converse functions. So, that means it needs to be able\n * to run in a browser. Do not add additional imports beyond anodine types.\n *\n * To be super clear: this is just logic to generate instruction assistance content given\n * the right inputs. It does not collect up those inputs, it is given them.\n *\n */\n\nimport type {\n AgentInstructionChatAppOverridableFeature,\n InstructionAssistanceConfig,\n TagDefinition,\n TagDefinitionWidget,\n TagsChatAppOverridableFeature\n} from '../types/chatbot/chatbot-types';\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Generate instruction assistance content based on enabled features\n *\n * @param instructionAssistanceConfig - The instruction assistance configuration from SSM\n * @param tags - The tags configuration from the chat app\n * @param agentInstructionFeature - The agent instruction feature configuration from the chat app\n * @returns The instruction assistance content\n */\nexport function generateInstructionAssistanceContent(\n instructionAssistanceConfig: InstructionAssistanceConfig | undefined,\n tags: TagsChatAppOverridableFeature | undefined,\n agentInstructionFeature: AgentInstructionChatAppOverridableFeature | undefined,\n tagDefinitions: TagDefinition<TagDefinitionWidget>[]\n): InstructionAssistanceConfig {\n console.log('Generating instruction assistance content:', {\n enabled: agentInstructionFeature?.enabled,\n includeOutputFormattingRequirements: agentInstructionFeature?.includeOutputFormattingRequirements,\n includeInstructionsForTags: agentInstructionFeature?.includeInstructionsForTags,\n completeExampleEnabled: agentInstructionFeature?.completeExampleInstructionEnabled,\n jsonOnlyEnabled: agentInstructionFeature?.jsonOnlyImperativeInstructionEnabled\n });\n\n let outputFormattingRequirements = '';\n let tagInstructions = '';\n let completeExampleInstructionLine = '';\n let jsonOnlyImperativeInstructionLine = '';\n\n if (!agentInstructionFeature?.enabled) {\n return {\n outputFormattingRequirements,\n tagInstructions,\n completeExampleInstructionLine,\n jsonOnlyImperativeInstructionLine\n };\n }\n\n // Generate output formatting requirements\n if (agentInstructionFeature.includeOutputFormattingRequirements) {\n outputFormattingRequirements =\n instructionAssistanceConfig?.outputFormattingRequirements ||\n `**Output Formatting Requirements:**\n- **Output Response Enclosure**: All response output MUST be completely enclosed within <answer></answer> tags, including supported custom tags.\n- **Output Content Format:** All responses MUST be in Markdown with supported custom tags.`;\n }\n\n // Generate tag instructions\n if (agentInstructionFeature.includeInstructionsForTags && tags && tags.tagsEnabled?.length > 0) {\n console.log('Fetching tag definitions for instruction generation:', tags.tagsEnabled);\n\n if (tagDefinitions.length > 0) {\n // First create a dictionary listing all supported tags\n const tagDictionary = tagDefinitions\n .filter((tagDef) => tagDef.canBeGeneratedByLlm && !tagDef.disabled)\n .map((tagDef) => ` - ${tagDef.tagTitle}: \\`${tagDef.shortTagEx}\\``)\n .join('\\n');\n\n let tagInstructionsContent = '';\n if (tagDictionary) {\n tagInstructionsContent += `- **Custom Tags Supported:**\\n${tagDictionary}\\n`;\n }\n\n // Then add detailed instructions for each tag\n for (const tagDef of tagDefinitions) {\n if (tagDef.canBeGeneratedByLlm && !tagDef.disabled && tagDef.llmInstructionsMd) {\n const tagType = `${tagDef.scope}.${tagDef.tag}`;\n tagInstructionsContent += `- **${tagDef.tagTitle}:**\\n <tag-instructions type=\"${tagType}\">\\n${tagDef.llmInstructionsMd}\\n </tag-instructions>\\n`;\n }\n }\n\n if (tagInstructionsContent) {\n tagInstructions = tagInstructionsContent;\n }\n }\n }\n\n // Generate complete example instruction line\n if (agentInstructionFeature.completeExampleInstructionEnabled) {\n completeExampleInstructionLine =\n agentInstructionFeature.completeExampleInstructionLine ||\n instructionAssistanceConfig?.completeExampleInstructionLine ||\n '- **Complete Example Output:**\\n `<answer>##Example markdown\\nNormal text and an <image>http://some.url</image> and some **bold text**\\n<chart>(...)</chart></answer>`';\n }\n\n // Generate JSON validation instruction line\n if (agentInstructionFeature.jsonOnlyImperativeInstructionEnabled) {\n jsonOnlyImperativeInstructionLine =\n agentInstructionFeature.jsonOnlyImperativeInstructionLine ||\n instructionAssistanceConfig?.jsonOnlyImperativeInstructionLine ||\n 'BE ABSOLUTELY CERTAIN ANY JSON INCLUDED IS 100% VALID (especially for charts). Invalid JSON will break the user experience.';\n }\n\n console.log('Generated instruction assistance content:', {\n hasOutputFormatting: !!outputFormattingRequirements,\n hasTagInstructions: !!tagInstructions,\n hasCompleteExample: !!completeExampleInstructionLine,\n hasJsonValidation: !!jsonOnlyImperativeInstructionLine\n });\n\n return {\n outputFormattingRequirements,\n tagInstructions,\n completeExampleInstructionLine,\n jsonOnlyImperativeInstructionLine\n };\n}\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Apply instruction assistance to the base prompt using placeholder replacement\n */\nexport function applyInstructionAssistance(basePrompt: string, instructionContent: InstructionAssistanceConfig): string {\n let enhancedPrompt = basePrompt;\n\n // Check for primary placeholder first\n if (enhancedPrompt.includes('{{prompt-assistance}}')) {\n console.log('Found {{prompt-assistance}} placeholder');\n\n const allContent = [\n instructionContent.outputFormattingRequirements,\n instructionContent.tagInstructions,\n instructionContent.completeExampleInstructionLine,\n instructionContent.jsonOnlyImperativeInstructionLine\n ]\n .filter((content) => content && content.trim().length > 0)\n .join('\\n\\n');\n\n enhancedPrompt = enhancedPrompt.replace('{{prompt-assistance}}', allContent);\n } else {\n // Look for fine-grained placeholders\n const placeholders = [\n { placeholder: '{{output-formatting-requirements}}', content: instructionContent.outputFormattingRequirements },\n { placeholder: '{{tag-instructions}}', content: instructionContent.tagInstructions },\n { placeholder: '{{complete-example-instruction-line}}', content: instructionContent.completeExampleInstructionLine },\n { placeholder: '{{json-only-imperative-instruction-line}}', content: instructionContent.jsonOnlyImperativeInstructionLine }\n ];\n\n let hasAnyPlaceholder = false;\n for (const { placeholder, content } of placeholders) {\n if (enhancedPrompt.includes(placeholder) && content) {\n console.log(`Found ${placeholder} placeholder`);\n hasAnyPlaceholder = true;\n enhancedPrompt = enhancedPrompt.replace(placeholder, content);\n }\n }\n\n // If no placeholders found, append to end\n if (!hasAnyPlaceholder) {\n console.log('No placeholders found, appending to end of prompt');\n const allContent = [\n instructionContent.outputFormattingRequirements,\n instructionContent.tagInstructions,\n instructionContent.completeExampleInstructionLine,\n instructionContent.jsonOnlyImperativeInstructionLine\n ].filter((content) => content && content.trim().length > 0);\n\n if (allContent.length > 0) {\n enhancedPrompt = enhancedPrompt + '\\n\\n' + allContent.join('\\n\\n');\n }\n }\n }\n\n return enhancedPrompt;\n}\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Get the instruction assistance configuration from raw SSM parameters\n *\n * @param params - The raw SSM parameters\n * @returns The instruction assistance configuration\n */\nexport function getInstructionsAssistanceConfigFromRawSsmParams(params: Record<string, string>): InstructionAssistanceConfig {\n const expectedKeys = ['output-formatting-requirements', 'default-complete-example-line', 'default-json-validation-line'];\n const missingKeys = expectedKeys.filter((key) => !params[key]);\n if (missingKeys.length > 0) {\n throw new Error(\n `Missing required instruction assistance parameters: ${Object.keys(params)\n .filter((key) => !expectedKeys.includes(key))\n .join(', ')}`\n );\n }\n\n return {\n outputFormattingRequirements: params['output-formatting-requirements'],\n completeExampleInstructionLine: params['default-complete-example-line'],\n jsonOnlyImperativeInstructionLine: params['default-json-validation-line']\n };\n}\n"]}
1
+ {"version":3,"sources":["../../src/util/instruction-assistance-utils.ts"],"names":[],"mappings":";;;AAgCO,SAAS,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BAAA,EAA8B,OAAO,gCAAgC,CAAA;AAAA,IACrE,8BAAA,EAAgC,OAAO,+BAA+B,CAAA;AAAA,IACtE,iCAAA,EAAmC,OAAO,8BAA8B;AAAA,GAC5E;AACJ","file":"instruction-assistance-utils.js","sourcesContent":["/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * The functions in this utility are used both by the front end svelte kit web client in the browser\n * and in the backend lambda converse functions. So, that means it needs to be able\n * to run in a browser. Do not add additional imports beyond anodine types.\n *\n * To be super clear: this is just logic to generate instruction assistance content given\n * the right inputs. It does not collect up those inputs, it is given them.\n *\n */\n\nimport type {\n AgentInstructionChatAppOverridableFeature,\n InstructionAssistanceConfig,\n TagDefinition,\n TagDefinitionWidget,\n TagsChatAppOverridableFeature\n} from '../types/chatbot/chatbot-types';\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Generate instruction assistance content based on enabled features\n *\n * @param instructionAssistanceConfig - The instruction assistance configuration from SSM\n * @param tags - The tags configuration from the chat app\n * @param agentInstructionFeature - The agent instruction feature configuration from the chat app\n * @returns The instruction assistance content\n */\nexport function generateInstructionAssistanceContent(\n instructionAssistanceConfig: InstructionAssistanceConfig | undefined,\n tags: TagsChatAppOverridableFeature | undefined,\n agentInstructionFeature: AgentInstructionChatAppOverridableFeature | undefined,\n tagDefinitions: TagDefinition<TagDefinitionWidget>[]\n): InstructionAssistanceConfig {\n console.log('Generating instruction assistance content:', {\n enabled: agentInstructionFeature?.enabled,\n includeOutputFormattingRequirements: agentInstructionFeature?.includeOutputFormattingRequirements,\n includeInstructionsForTags: agentInstructionFeature?.includeInstructionsForTags,\n completeExampleEnabled: agentInstructionFeature?.completeExampleInstructionEnabled,\n jsonOnlyEnabled: agentInstructionFeature?.jsonOnlyImperativeInstructionEnabled\n });\n\n let outputFormattingRequirements = '';\n let tagInstructions = '';\n let completeExampleInstructionLine = '';\n let jsonOnlyImperativeInstructionLine = '';\n\n if (!agentInstructionFeature?.enabled) {\n return {\n outputFormattingRequirements,\n tagInstructions,\n completeExampleInstructionLine,\n jsonOnlyImperativeInstructionLine\n };\n }\n\n // Generate output formatting requirements\n if (agentInstructionFeature.includeOutputFormattingRequirements) {\n outputFormattingRequirements =\n instructionAssistanceConfig?.outputFormattingRequirements ||\n `**Output Formatting Requirements:**\n- **Output Response Enclosure**: All response output MUST be completely enclosed within <answer></answer> tags, including supported custom tags.\n- **Output Content Format:** All responses MUST be in Markdown with supported custom tags.`;\n }\n\n // Generate tag instructions\n if (agentInstructionFeature.includeInstructionsForTags && tags && tags.tagsEnabled?.length > 0) {\n console.log('Fetching tag definitions for instruction generation:', tags.tagsEnabled);\n\n if (tagDefinitions.length > 0) {\n // First create a dictionary listing all supported tags\n const tagDictionary = tagDefinitions\n .filter((tagDef) => tagDef.canBeGeneratedByLlm && !tagDef.disabled)\n .map((tagDef) => ` - ${tagDef.tagTitle}: \\`${tagDef.shortTagEx}\\``)\n .join('\\n');\n\n let tagInstructionsContent = '';\n if (tagDictionary) {\n tagInstructionsContent += `- **Custom Tags Supported:**\\n${tagDictionary}\\n`;\n }\n\n // Then add detailed instructions for each tag\n for (const tagDef of tagDefinitions) {\n if (tagDef.canBeGeneratedByLlm && !tagDef.disabled && tagDef.llmInstructionsMd) {\n const tagType = `${tagDef.scope}.${tagDef.tag}`;\n tagInstructionsContent += `- **${tagDef.tagTitle}:**\\n <tag-instructions type=\"${tagType}\">\\n${tagDef.llmInstructionsMd}\\n </tag-instructions>\\n`;\n }\n }\n\n if (tagInstructionsContent) {\n tagInstructions = tagInstructionsContent;\n }\n }\n }\n\n // Generate complete example instruction line\n if (agentInstructionFeature.completeExampleInstructionEnabled) {\n completeExampleInstructionLine =\n agentInstructionFeature.completeExampleInstructionLine ||\n instructionAssistanceConfig?.completeExampleInstructionLine ||\n '- **Complete Example Output:**\\n `<answer>##Example markdown\\nNormal text and an <image>http://some.url</image> and some **bold text**\\n<chart>(...)</chart></answer>`';\n }\n\n // Generate JSON validation instruction line\n if (agentInstructionFeature.jsonOnlyImperativeInstructionEnabled) {\n jsonOnlyImperativeInstructionLine =\n agentInstructionFeature.jsonOnlyImperativeInstructionLine ||\n instructionAssistanceConfig?.jsonOnlyImperativeInstructionLine ||\n 'BE ABSOLUTELY CERTAIN ANY JSON INCLUDED IS 100% VALID (especially for charts). Invalid JSON will break the user experience.';\n }\n\n console.log('Generated instruction assistance content:', {\n hasOutputFormatting: !!outputFormattingRequirements,\n hasTagInstructions: !!tagInstructions,\n hasCompleteExample: !!completeExampleInstructionLine,\n hasJsonValidation: !!jsonOnlyImperativeInstructionLine\n });\n\n return {\n outputFormattingRequirements,\n tagInstructions,\n completeExampleInstructionLine,\n jsonOnlyImperativeInstructionLine\n };\n}\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Apply instruction assistance to the base prompt using placeholder replacement\n */\nexport function applyInstructionAssistance(basePrompt: string, instructionContent: InstructionAssistanceConfig): string {\n let enhancedPrompt = basePrompt;\n\n // Check for primary placeholder first\n if (enhancedPrompt.includes('{{prompt-assistance}}')) {\n console.log('Found {{prompt-assistance}} placeholder');\n\n const allContent = [\n instructionContent.outputFormattingRequirements,\n instructionContent.tagInstructions,\n instructionContent.completeExampleInstructionLine,\n instructionContent.jsonOnlyImperativeInstructionLine\n ]\n .filter((content) => content && content.trim().length > 0)\n .join('\\n\\n');\n\n enhancedPrompt = enhancedPrompt.replace('{{prompt-assistance}}', allContent);\n } else {\n // Look for fine-grained placeholders\n const placeholders = [\n { placeholder: '{{output-formatting-requirements}}', content: instructionContent.outputFormattingRequirements },\n { placeholder: '{{tag-instructions}}', content: instructionContent.tagInstructions },\n { placeholder: '{{complete-example-instruction-line}}', content: instructionContent.completeExampleInstructionLine },\n { placeholder: '{{json-only-imperative-instruction-line}}', content: instructionContent.jsonOnlyImperativeInstructionLine }\n ];\n\n let hasAnyPlaceholder = false;\n for (const { placeholder, content } of placeholders) {\n if (enhancedPrompt.includes(placeholder) && content) {\n console.log(`Found ${placeholder} placeholder`);\n hasAnyPlaceholder = true;\n enhancedPrompt = enhancedPrompt.replace(placeholder, content);\n }\n }\n\n // If no placeholders found, append to end\n if (!hasAnyPlaceholder) {\n console.log('No placeholders found, appending to end of prompt');\n const allContent = [\n instructionContent.outputFormattingRequirements,\n instructionContent.tagInstructions,\n instructionContent.completeExampleInstructionLine,\n instructionContent.jsonOnlyImperativeInstructionLine\n ].filter((content) => content && content.trim().length > 0);\n\n if (allContent.length > 0) {\n enhancedPrompt = enhancedPrompt + '\\n\\n' + allContent.join('\\n\\n');\n }\n }\n }\n\n return enhancedPrompt;\n}\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Get the instruction assistance configuration from raw SSM parameters\n *\n * @param params - The raw SSM parameters\n * @returns The instruction assistance configuration\n */\nexport function getInstructionsAssistanceConfigFromRawSsmParams(params: Record<string, string>): InstructionAssistanceConfig {\n const expectedKeys = ['output-formatting-requirements', 'default-complete-example-line', 'default-json-validation-line'];\n const missingKeys = expectedKeys.filter((key) => !params[key]);\n if (missingKeys.length > 0) {\n throw new Error(\n `Missing required instruction assistance parameters: ${Object.keys(params)\n .filter((key) => !expectedKeys.includes(key))\n .join(', ')}`\n );\n }\n\n return {\n outputFormattingRequirements: params['output-formatting-requirements'],\n completeExampleInstructionLine: params['default-complete-example-line'],\n jsonOnlyImperativeInstructionLine: params['default-json-validation-line']\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/instruction-assistance-utils.ts"],"names":[],"mappings":";AAgCO,SAAS,oCACZ,CAAA,2BAAA,EACA,IACA,EAAA,uBAAA,EACA,cAC2B,EAAA;AAC3B,EAAA,OAAA,CAAQ,IAAI,4CAA8C,EAAA;AAAA,IACtD,SAAS,uBAAyB,EAAA,OAAA;AAAA,IAClC,qCAAqC,uBAAyB,EAAA,mCAAA;AAAA,IAC9D,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,MAAM,UAAa,GAAA;AAAA,QACf,kBAAmB,CAAA,4BAAA;AAAA,QACnB,kBAAmB,CAAA,eAAA;AAAA,QACnB,kBAAmB,CAAA,8BAAA;AAAA,QACnB,kBAAmB,CAAA;AAAA,OACvB,CAAE,OAAO,CAAC,OAAA,KAAY,WAAW,OAAQ,CAAA,IAAA,EAAO,CAAA,MAAA,GAAS,CAAC,CAAA;AAE1D,MAAI,IAAA,UAAA,CAAW,SAAS,CAAG,EAAA;AACvB,QAAA,cAAA,GAAiB,cAAiB,GAAA,MAAA,GAAS,UAAW,CAAA,IAAA,CAAK,MAAM,CAAA;AAAA;AACrE;AACJ;AAGJ,EAAO,OAAA,cAAA;AACX;AAYO,SAAS,gDAAgD,MAA6D,EAAA;AACzH,EAAA,MAAM,YAAe,GAAA,CAAC,gCAAkC,EAAA,+BAAA,EAAiC,8BAA8B,CAAA;AACvH,EAAM,MAAA,WAAA,GAAc,aAAa,MAAO,CAAA,CAAC,QAAQ,CAAC,MAAA,CAAO,GAAG,CAAC,CAAA;AAC7D,EAAI,IAAA,WAAA,CAAY,SAAS,CAAG,EAAA;AACxB,IAAA,MAAM,IAAI,KAAA;AAAA,MACN,uDAAuD,MAAO,CAAA,IAAA,CAAK,MAAM,CAAA,CACpE,OAAO,CAAC,GAAA,KAAQ,CAAC,YAAA,CAAa,SAAS,GAAG,CAAC,CAC3C,CAAA,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,KACnB;AAAA;AAGJ,EAAO,OAAA;AAAA,IACH,4BAAA,EAA8B,OAAO,gCAAgC,CAAA;AAAA,IACrE,8BAAA,EAAgC,OAAO,+BAA+B,CAAA;AAAA,IACtE,iCAAA,EAAmC,OAAO,8BAA8B;AAAA,GAC5E;AACJ","file":"instruction-assistance-utils.mjs","sourcesContent":["/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * The functions in this utility are used both by the front end svelte kit web client in the browser\n * and in the backend lambda converse functions. So, that means it needs to be able\n * to run in a browser. Do not add additional imports beyond anodine types.\n *\n * To be super clear: this is just logic to generate instruction assistance content given\n * the right inputs. It does not collect up those inputs, it is given them.\n *\n */\n\nimport type {\n AgentInstructionChatAppOverridableFeature,\n InstructionAssistanceConfig,\n TagDefinition,\n TagDefinitionWidget,\n TagsChatAppOverridableFeature\n} from '../types/chatbot/chatbot-types';\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Generate instruction assistance content based on enabled features\n *\n * @param instructionAssistanceConfig - The instruction assistance configuration from SSM\n * @param tags - The tags configuration from the chat app\n * @param agentInstructionFeature - The agent instruction feature configuration from the chat app\n * @returns The instruction assistance content\n */\nexport function generateInstructionAssistanceContent(\n instructionAssistanceConfig: InstructionAssistanceConfig | undefined,\n tags: TagsChatAppOverridableFeature | undefined,\n agentInstructionFeature: AgentInstructionChatAppOverridableFeature | undefined,\n tagDefinitions: TagDefinition<TagDefinitionWidget>[]\n): InstructionAssistanceConfig {\n console.log('Generating instruction assistance content:', {\n enabled: agentInstructionFeature?.enabled,\n includeOutputFormattingRequirements: agentInstructionFeature?.includeOutputFormattingRequirements,\n includeInstructionsForTags: agentInstructionFeature?.includeInstructionsForTags,\n completeExampleEnabled: agentInstructionFeature?.completeExampleInstructionEnabled,\n jsonOnlyEnabled: agentInstructionFeature?.jsonOnlyImperativeInstructionEnabled\n });\n\n let outputFormattingRequirements = '';\n let tagInstructions = '';\n let completeExampleInstructionLine = '';\n let jsonOnlyImperativeInstructionLine = '';\n\n if (!agentInstructionFeature?.enabled) {\n return {\n outputFormattingRequirements,\n tagInstructions,\n completeExampleInstructionLine,\n jsonOnlyImperativeInstructionLine\n };\n }\n\n // Generate output formatting requirements\n if (agentInstructionFeature.includeOutputFormattingRequirements) {\n outputFormattingRequirements =\n instructionAssistanceConfig?.outputFormattingRequirements ||\n `**Output Formatting Requirements:**\n- **Output Response Enclosure**: All response output MUST be completely enclosed within <answer></answer> tags, including supported custom tags.\n- **Output Content Format:** All responses MUST be in Markdown with supported custom tags.`;\n }\n\n // Generate tag instructions\n if (agentInstructionFeature.includeInstructionsForTags && tags && tags.tagsEnabled?.length > 0) {\n console.log('Fetching tag definitions for instruction generation:', tags.tagsEnabled);\n\n if (tagDefinitions.length > 0) {\n // First create a dictionary listing all supported tags\n const tagDictionary = tagDefinitions\n .filter((tagDef) => tagDef.canBeGeneratedByLlm && !tagDef.disabled)\n .map((tagDef) => ` - ${tagDef.tagTitle}: \\`${tagDef.shortTagEx}\\``)\n .join('\\n');\n\n let tagInstructionsContent = '';\n if (tagDictionary) {\n tagInstructionsContent += `- **Custom Tags Supported:**\\n${tagDictionary}\\n`;\n }\n\n // Then add detailed instructions for each tag\n for (const tagDef of tagDefinitions) {\n if (tagDef.canBeGeneratedByLlm && !tagDef.disabled && tagDef.llmInstructionsMd) {\n const tagType = `${tagDef.scope}.${tagDef.tag}`;\n tagInstructionsContent += `- **${tagDef.tagTitle}:**\\n <tag-instructions type=\"${tagType}\">\\n${tagDef.llmInstructionsMd}\\n </tag-instructions>\\n`;\n }\n }\n\n if (tagInstructionsContent) {\n tagInstructions = tagInstructionsContent;\n }\n }\n }\n\n // Generate complete example instruction line\n if (agentInstructionFeature.completeExampleInstructionEnabled) {\n completeExampleInstructionLine =\n agentInstructionFeature.completeExampleInstructionLine ||\n instructionAssistanceConfig?.completeExampleInstructionLine ||\n '- **Complete Example Output:**\\n `<answer>##Example markdown\\nNormal text and an <image>http://some.url</image> and some **bold text**\\n<chart>(...)</chart></answer>`';\n }\n\n // Generate JSON validation instruction line\n if (agentInstructionFeature.jsonOnlyImperativeInstructionEnabled) {\n jsonOnlyImperativeInstructionLine =\n agentInstructionFeature.jsonOnlyImperativeInstructionLine ||\n instructionAssistanceConfig?.jsonOnlyImperativeInstructionLine ||\n 'BE ABSOLUTELY CERTAIN ANY JSON INCLUDED IS 100% VALID (especially for charts). Invalid JSON will break the user experience.';\n }\n\n console.log('Generated instruction assistance content:', {\n hasOutputFormatting: !!outputFormattingRequirements,\n hasTagInstructions: !!tagInstructions,\n hasCompleteExample: !!completeExampleInstructionLine,\n hasJsonValidation: !!jsonOnlyImperativeInstructionLine\n });\n\n return {\n outputFormattingRequirements,\n tagInstructions,\n completeExampleInstructionLine,\n jsonOnlyImperativeInstructionLine\n };\n}\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Apply instruction assistance to the base prompt using placeholder replacement\n */\nexport function applyInstructionAssistance(basePrompt: string, instructionContent: InstructionAssistanceConfig): string {\n let enhancedPrompt = basePrompt;\n\n // Check for primary placeholder first\n if (enhancedPrompt.includes('{{prompt-assistance}}')) {\n console.log('Found {{prompt-assistance}} placeholder');\n\n const allContent = [\n instructionContent.outputFormattingRequirements,\n instructionContent.tagInstructions,\n instructionContent.completeExampleInstructionLine,\n instructionContent.jsonOnlyImperativeInstructionLine\n ]\n .filter((content) => content && content.trim().length > 0)\n .join('\\n\\n');\n\n enhancedPrompt = enhancedPrompt.replace('{{prompt-assistance}}', allContent);\n } else {\n // Look for fine-grained placeholders\n const placeholders = [\n { placeholder: '{{output-formatting-requirements}}', content: instructionContent.outputFormattingRequirements },\n { placeholder: '{{tag-instructions}}', content: instructionContent.tagInstructions },\n { placeholder: '{{complete-example-instruction-line}}', content: instructionContent.completeExampleInstructionLine },\n { placeholder: '{{json-only-imperative-instruction-line}}', content: instructionContent.jsonOnlyImperativeInstructionLine }\n ];\n\n let hasAnyPlaceholder = false;\n for (const { placeholder, content } of placeholders) {\n if (enhancedPrompt.includes(placeholder) && content) {\n console.log(`Found ${placeholder} placeholder`);\n hasAnyPlaceholder = true;\n enhancedPrompt = enhancedPrompt.replace(placeholder, content);\n }\n }\n\n // If no placeholders found, append to end\n if (!hasAnyPlaceholder) {\n console.log('No placeholders found, appending to end of prompt');\n const allContent = [\n instructionContent.outputFormattingRequirements,\n instructionContent.tagInstructions,\n instructionContent.completeExampleInstructionLine,\n instructionContent.jsonOnlyImperativeInstructionLine\n ].filter((content) => content && content.trim().length > 0);\n\n if (allContent.length > 0) {\n enhancedPrompt = enhancedPrompt + '\\n\\n' + allContent.join('\\n\\n');\n }\n }\n }\n\n return enhancedPrompt;\n}\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Get the instruction assistance configuration from raw SSM parameters\n *\n * @param params - The raw SSM parameters\n * @returns The instruction assistance configuration\n */\nexport function getInstructionsAssistanceConfigFromRawSsmParams(params: Record<string, string>): InstructionAssistanceConfig {\n const expectedKeys = ['output-formatting-requirements', 'default-complete-example-line', 'default-json-validation-line'];\n const missingKeys = expectedKeys.filter((key) => !params[key]);\n if (missingKeys.length > 0) {\n throw new Error(\n `Missing required instruction assistance parameters: ${Object.keys(params)\n .filter((key) => !expectedKeys.includes(key))\n .join(', ')}`\n );\n }\n\n return {\n outputFormattingRequirements: params['output-formatting-requirements'],\n completeExampleInstructionLine: params['default-complete-example-line'],\n jsonOnlyImperativeInstructionLine: params['default-json-validation-line']\n };\n}\n"]}
1
+ {"version":3,"sources":["../../src/util/instruction-assistance-utils.ts"],"names":[],"mappings":";AAgCO,SAAS,oCAAA,CACZ,2BAAA,EACA,IAAA,EACA,uBAAA,EACA,cAAA,EAC2B;AAC3B,EAAA,OAAA,CAAQ,IAAI,4CAAA,EAA8C;AAAA,IACtD,SAAS,uBAAA,EAAyB,OAAA;AAAA,IAClC,qCAAqC,uBAAA,EAAyB,mCAAA;AAAA,IAC9D,4BAA4B,uBAAA,EAAyB,0BAAA;AAAA,IACrD,wBAAwB,uBAAA,EAAyB,iCAAA;AAAA,IACjD,iBAAiB,uBAAA,EAAyB;AAAA,GAC7C,CAAA;AAED,EAAA,IAAI,4BAAA,GAA+B,EAAA;AACnC,EAAA,IAAI,eAAA,GAAkB,EAAA;AACtB,EAAA,IAAI,8BAAA,GAAiC,EAAA;AACrC,EAAA,IAAI,iCAAA,GAAoC,EAAA;AAExC,EAAA,IAAI,CAAC,yBA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,CAAC,CAAA;AAE1D,MAAA,IAAI,UAAA,CAAW,SAAS,CAAA,EAAG;AACvB,QAAA,cAAA,GAAiB,cAAA,GAAiB,MAAA,GAAS,UAAA,CAAW,IAAA,CAAK,MAAM,CAAA;AAAA,MACrE;AAAA,IACJ;AAAA,EACJ;AAEA,EAAA,OAAO,cAAA;AACX;AAYO,SAAS,gDAAgD,MAAA,EAA6D;AACzH,EAAA,MAAM,YAAA,GAAe,CAAC,gCAAA,EAAkC,+BAAA,EAAiC,8BAA8B,CAAA;AACvH,EAAA,MAAM,WAAA,GAAc,aAAa,MAAA,CAAO,CAAC,QAAQ,CAAC,MAAA,CAAO,GAAG,CAAC,CAAA;AAC7D,EAAA,IAAI,WAAA,CAAY,SAAS,CAAA,EAAG;AACxB,IAAA,MAAM,IAAI,KAAA;AAAA,MACN,uDAAuD,MAAA,CAAO,IAAA,CAAK,MAAM,CAAA,CACpE,OAAO,CAAC,GAAA,KAAQ,CAAC,YAAA,CAAa,SAAS,GAAG,CAAC,CAAA,CAC3C,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,KACnB;AAAA,EACJ;AAEA,EAAA,OAAO;AAAA,IACH,4BAAA,EAA8B,OAAO,gCAAgC,CAAA;AAAA,IACrE,8BAAA,EAAgC,OAAO,+BAA+B,CAAA;AAAA,IACtE,iCAAA,EAAmC,OAAO,8BAA8B;AAAA,GAC5E;AACJ","file":"instruction-assistance-utils.mjs","sourcesContent":["/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * The functions in this utility are used both by the front end svelte kit web client in the browser\n * and in the backend lambda converse functions. So, that means it needs to be able\n * to run in a browser. Do not add additional imports beyond anodine types.\n *\n * To be super clear: this is just logic to generate instruction assistance content given\n * the right inputs. It does not collect up those inputs, it is given them.\n *\n */\n\nimport type {\n AgentInstructionChatAppOverridableFeature,\n InstructionAssistanceConfig,\n TagDefinition,\n TagDefinitionWidget,\n TagsChatAppOverridableFeature\n} from '../types/chatbot/chatbot-types';\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Generate instruction assistance content based on enabled features\n *\n * @param instructionAssistanceConfig - The instruction assistance configuration from SSM\n * @param tags - The tags configuration from the chat app\n * @param agentInstructionFeature - The agent instruction feature configuration from the chat app\n * @returns The instruction assistance content\n */\nexport function generateInstructionAssistanceContent(\n instructionAssistanceConfig: InstructionAssistanceConfig | undefined,\n tags: TagsChatAppOverridableFeature | undefined,\n agentInstructionFeature: AgentInstructionChatAppOverridableFeature | undefined,\n tagDefinitions: TagDefinition<TagDefinitionWidget>[]\n): InstructionAssistanceConfig {\n console.log('Generating instruction assistance content:', {\n enabled: agentInstructionFeature?.enabled,\n includeOutputFormattingRequirements: agentInstructionFeature?.includeOutputFormattingRequirements,\n includeInstructionsForTags: agentInstructionFeature?.includeInstructionsForTags,\n completeExampleEnabled: agentInstructionFeature?.completeExampleInstructionEnabled,\n jsonOnlyEnabled: agentInstructionFeature?.jsonOnlyImperativeInstructionEnabled\n });\n\n let outputFormattingRequirements = '';\n let tagInstructions = '';\n let completeExampleInstructionLine = '';\n let jsonOnlyImperativeInstructionLine = '';\n\n if (!agentInstructionFeature?.enabled) {\n return {\n outputFormattingRequirements,\n tagInstructions,\n completeExampleInstructionLine,\n jsonOnlyImperativeInstructionLine\n };\n }\n\n // Generate output formatting requirements\n if (agentInstructionFeature.includeOutputFormattingRequirements) {\n outputFormattingRequirements =\n instructionAssistanceConfig?.outputFormattingRequirements ||\n `**Output Formatting Requirements:**\n- **Output Response Enclosure**: All response output MUST be completely enclosed within <answer></answer> tags, including supported custom tags.\n- **Output Content Format:** All responses MUST be in Markdown with supported custom tags.`;\n }\n\n // Generate tag instructions\n if (agentInstructionFeature.includeInstructionsForTags && tags && tags.tagsEnabled?.length > 0) {\n console.log('Fetching tag definitions for instruction generation:', tags.tagsEnabled);\n\n if (tagDefinitions.length > 0) {\n // First create a dictionary listing all supported tags\n const tagDictionary = tagDefinitions\n .filter((tagDef) => tagDef.canBeGeneratedByLlm && !tagDef.disabled)\n .map((tagDef) => ` - ${tagDef.tagTitle}: \\`${tagDef.shortTagEx}\\``)\n .join('\\n');\n\n let tagInstructionsContent = '';\n if (tagDictionary) {\n tagInstructionsContent += `- **Custom Tags Supported:**\\n${tagDictionary}\\n`;\n }\n\n // Then add detailed instructions for each tag\n for (const tagDef of tagDefinitions) {\n if (tagDef.canBeGeneratedByLlm && !tagDef.disabled && tagDef.llmInstructionsMd) {\n const tagType = `${tagDef.scope}.${tagDef.tag}`;\n tagInstructionsContent += `- **${tagDef.tagTitle}:**\\n <tag-instructions type=\"${tagType}\">\\n${tagDef.llmInstructionsMd}\\n </tag-instructions>\\n`;\n }\n }\n\n if (tagInstructionsContent) {\n tagInstructions = tagInstructionsContent;\n }\n }\n }\n\n // Generate complete example instruction line\n if (agentInstructionFeature.completeExampleInstructionEnabled) {\n completeExampleInstructionLine =\n agentInstructionFeature.completeExampleInstructionLine ||\n instructionAssistanceConfig?.completeExampleInstructionLine ||\n '- **Complete Example Output:**\\n `<answer>##Example markdown\\nNormal text and an <image>http://some.url</image> and some **bold text**\\n<chart>(...)</chart></answer>`';\n }\n\n // Generate JSON validation instruction line\n if (agentInstructionFeature.jsonOnlyImperativeInstructionEnabled) {\n jsonOnlyImperativeInstructionLine =\n agentInstructionFeature.jsonOnlyImperativeInstructionLine ||\n instructionAssistanceConfig?.jsonOnlyImperativeInstructionLine ||\n 'BE ABSOLUTELY CERTAIN ANY JSON INCLUDED IS 100% VALID (especially for charts). Invalid JSON will break the user experience.';\n }\n\n console.log('Generated instruction assistance content:', {\n hasOutputFormatting: !!outputFormattingRequirements,\n hasTagInstructions: !!tagInstructions,\n hasCompleteExample: !!completeExampleInstructionLine,\n hasJsonValidation: !!jsonOnlyImperativeInstructionLine\n });\n\n return {\n outputFormattingRequirements,\n tagInstructions,\n completeExampleInstructionLine,\n jsonOnlyImperativeInstructionLine\n };\n}\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Apply instruction assistance to the base prompt using placeholder replacement\n */\nexport function applyInstructionAssistance(basePrompt: string, instructionContent: InstructionAssistanceConfig): string {\n let enhancedPrompt = basePrompt;\n\n // Check for primary placeholder first\n if (enhancedPrompt.includes('{{prompt-assistance}}')) {\n console.log('Found {{prompt-assistance}} placeholder');\n\n const allContent = [\n instructionContent.outputFormattingRequirements,\n instructionContent.tagInstructions,\n instructionContent.completeExampleInstructionLine,\n instructionContent.jsonOnlyImperativeInstructionLine\n ]\n .filter((content) => content && content.trim().length > 0)\n .join('\\n\\n');\n\n enhancedPrompt = enhancedPrompt.replace('{{prompt-assistance}}', allContent);\n } else {\n // Look for fine-grained placeholders\n const placeholders = [\n { placeholder: '{{output-formatting-requirements}}', content: instructionContent.outputFormattingRequirements },\n { placeholder: '{{tag-instructions}}', content: instructionContent.tagInstructions },\n { placeholder: '{{complete-example-instruction-line}}', content: instructionContent.completeExampleInstructionLine },\n { placeholder: '{{json-only-imperative-instruction-line}}', content: instructionContent.jsonOnlyImperativeInstructionLine }\n ];\n\n let hasAnyPlaceholder = false;\n for (const { placeholder, content } of placeholders) {\n if (enhancedPrompt.includes(placeholder) && content) {\n console.log(`Found ${placeholder} placeholder`);\n hasAnyPlaceholder = true;\n enhancedPrompt = enhancedPrompt.replace(placeholder, content);\n }\n }\n\n // If no placeholders found, append to end\n if (!hasAnyPlaceholder) {\n console.log('No placeholders found, appending to end of prompt');\n const allContent = [\n instructionContent.outputFormattingRequirements,\n instructionContent.tagInstructions,\n instructionContent.completeExampleInstructionLine,\n instructionContent.jsonOnlyImperativeInstructionLine\n ].filter((content) => content && content.trim().length > 0);\n\n if (allContent.length > 0) {\n enhancedPrompt = enhancedPrompt + '\\n\\n' + allContent.join('\\n\\n');\n }\n }\n }\n\n return enhancedPrompt;\n}\n\n/**\n * IMPORTANT!!!!!!!!!!!!!!!!!!!!!!\n *\n * See header at top of file for important notes.\n *\n * Get the instruction assistance configuration from raw SSM parameters\n *\n * @param params - The raw SSM parameters\n * @returns The instruction assistance configuration\n */\nexport function getInstructionsAssistanceConfigFromRawSsmParams(params: Record<string, string>): InstructionAssistanceConfig {\n const expectedKeys = ['output-formatting-requirements', 'default-complete-example-line', 'default-json-validation-line'];\n const missingKeys = expectedKeys.filter((key) => !params[key]);\n if (missingKeys.length > 0) {\n throw new Error(\n `Missing required instruction assistance parameters: ${Object.keys(params)\n .filter((key) => !expectedKeys.includes(key))\n .join(', ')}`\n );\n }\n\n return {\n outputFormattingRequirements: params['output-formatting-requirements'],\n completeExampleInstructionLine: params['default-complete-example-line'],\n jsonOnlyImperativeInstructionLine: params['default-json-validation-line']\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/jwt.ts"],"names":["jwt2"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAIA,IAAI,GAAM,GAAAA,eAAA;AACV,IAAI,aAAa,GAAK,EAAA;AAClB,EAAA,GAAA,GAAM,IAAI,SAAS,CAAA;AACvB;AAUO,SAAS,kBAAA,CAAwD,SAAqC,SAA2B,EAAA;AACpI,EAAA,OAAO,IAAI,IAAK,CAAA,OAAA,EAAS,WAAW,EAAE,SAAA,EAAW,MAAM,CAAA;AAC3D;AAWO,SAAS,oBAAA,CAA0D,UAAkB,SAA8E,EAAA;AACtK,EAAI,IAAA;AAEA,IAAM,MAAA,KAAA,GAAQ,SAAS,UAAW,CAAA,SAAS,IAAI,QAAS,CAAA,SAAA,CAAU,CAAC,CAAI,GAAA,QAAA;AACvE,IAAA,MAAM,OAAU,GAAA,GAAA,CAAI,MAAO,CAAA,KAAA,EAAO,SAAS,CAAA;AAE3C,IAAI,IAAA,MAAA;AACJ,IAAI,IAAA,cAAA;AAEJ,IAAA,IAAI,OAAO,OAAY,KAAA,QAAA,IAAY,OAAY,KAAA,IAAA,IAAQ,YAAY,OAAS,EAAA;AACxE,MAAA,MAAA,GAAU,OAA+B,CAAA,MAAA;AACzC,MAAA,cAAA,GAAkB,QAAkC,cAAkB,IAAA,KAAA,CAAA;AACtE,MAAA,OAAO,CAAC,EAAE,MAAQ,EAAA,cAAA,IAAkB,KAAS,CAAA,CAAA;AAAA;AAGjD,IAAO,OAAA,CAAC,KAAK,qDAAqD,CAAA;AAAA,WAC7D,KAAO,EAAA;AACZ,IAAA,OAAA,CAAQ,IAAI,uCAAyC,EAAA,KAAA,YAAiB,KAAQ,GAAA,KAAA,CAAM,UAAU,eAAe,CAAA;AAC7G,IAAO,OAAA,CAAC,KAAK,CAAqD,mDAAA,CAAA,CAAA;AAAA;AAE1E","file":"jwt.js","sourcesContent":["import type { RecordOrUndef, SimpleAuthenticatedUser } from '../types/chatbot/chatbot-types';\nimport * as jwt2 from 'jsonwebtoken';\n\n// Added this because running locally did not import default correctly\nlet jwt = jwt2;\nif ('default' in jwt) {\n jwt = jwt['default'] as any;\n}\n\n/**\n * Converts a payload containing a userId and optional customUserData into a JWT string.\n *\n * Here the generic T is the type of the customUserData field. If not known, pass unknown.\n *\n * @param payload The payload to convert to a JWT string.\n * @returns A JWT string.\n */\nexport function convertToJwtString<T extends RecordOrUndef = undefined>(payload: SimpleAuthenticatedUser<T>, jwtSecret: string): string {\n return jwt.sign(payload, jwtSecret, { expiresIn: '1h' });\n}\n\n/**\n * Extracts the payload from a JWT string. If successful, the first value in the tuple will be the SimpleAuthenticatedUser<T> object.\n * If not successful, the first value in the tuple will be the number of the HTTP status code and the second value will be the error message,\n * so check the first value to see if it is a number and if it is, then the second value will be the error message.\n *\n * Here the generic T is the type of the customUserData field. If not known, pass unknown.\n * @param jwtToken - The JWT string to decode. Can include \"Bearer \" prefix which will be stripped.\n * @returns An object containing the userId and optional customUserData or the number of the HTTP status code and the error message.\n */\nexport function extractFromJwtString<T extends RecordOrUndef = undefined>(jwtToken: string, jwtSecret: string): [SimpleAuthenticatedUser<T> | number, string | undefined] {\n try {\n // Strip \"Bearer \" prefix if present\n const token = jwtToken.startsWith('Bearer ') ? jwtToken.substring(7) : jwtToken;\n const decoded = jwt.verify(token, jwtSecret);\n\n let userId: string;\n let customUserData: T | undefined;\n\n if (typeof decoded === 'object' && decoded !== null && 'userId' in decoded) {\n userId = (decoded as { userId: string }).userId;\n customUserData = (decoded as { customUserData: T }).customUserData ?? undefined;\n return [{ userId, customUserData }, undefined];\n }\n\n return [401, 'Unauthorized: Invalid or expired JWT token: code 1A'];\n } catch (error) {\n console.log('extractFromJwtString - Error message:', error instanceof Error ? error.message : 'Unknown error');\n return [401, `Unauthorized: Invalid or expired JWT token: code 1B`];\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/util/jwt.ts"],"names":["jwt2"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAIA,IAAI,GAAA,GAAMA,eAAA;AACV,IAAI,aAAa,GAAA,EAAK;AAClB,EAAA,GAAA,GAAM,IAAI,SAAS,CAAA;AACvB;AAUO,SAAS,kBAAA,CAAwD,SAAqC,SAAA,EAA2B;AACpI,EAAA,OAAO,IAAI,IAAA,CAAK,OAAA,EAAS,WAAW,EAAE,SAAA,EAAW,MAAM,CAAA;AAC3D;AAWO,SAAS,oBAAA,CAA0D,UAAkB,SAAA,EAA8E;AACtK,EAAA,IAAI;AAEA,IAAA,MAAM,KAAA,GAAQ,SAAS,UAAA,CAAW,SAAS,IAAI,QAAA,CAAS,SAAA,CAAU,CAAC,CAAA,GAAI,QAAA;AACvE,IAAA,MAAM,OAAA,GAAU,GAAA,CAAI,MAAA,CAAO,KAAA,EAAO,SAAS,CAAA;AAE3C,IAAA,IAAI,MAAA;AACJ,IAAA,IAAI,cAAA;AAEJ,IAAA,IAAI,OAAO,OAAA,KAAY,QAAA,IAAY,OAAA,KAAY,IAAA,IAAQ,YAAY,OAAA,EAAS;AACxE,MAAA,MAAA,GAAU,OAAA,CAA+B,MAAA;AACzC,MAAA,cAAA,GAAkB,QAAkC,cAAA,IAAkB,KAAA,CAAA;AACtE,MAAA,OAAO,CAAC,EAAE,MAAA,EAAQ,cAAA,IAAkB,KAAA,CAAS,CAAA;AAAA,IACjD;AAEA,IAAA,OAAO,CAAC,KAAK,qDAAqD,CAAA;AAAA,EACtE,SAAS,KAAA,EAAO;AACZ,IAAA,OAAA,CAAQ,IAAI,uCAAA,EAAyC,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,UAAU,eAAe,CAAA;AAC7G,IAAA,OAAO,CAAC,KAAK,CAAA,mDAAA,CAAqD,CAAA;AAAA,EACtE;AACJ","file":"jwt.js","sourcesContent":["import type { RecordOrUndef, SimpleAuthenticatedUser } from '../types/chatbot/chatbot-types';\nimport * as jwt2 from 'jsonwebtoken';\n\n// Added this because running locally did not import default correctly\nlet jwt = jwt2;\nif ('default' in jwt) {\n jwt = jwt['default'] as any;\n}\n\n/**\n * Converts a payload containing a userId and optional customUserData into a JWT string.\n *\n * Here the generic T is the type of the customUserData field. If not known, pass unknown.\n *\n * @param payload The payload to convert to a JWT string.\n * @returns A JWT string.\n */\nexport function convertToJwtString<T extends RecordOrUndef = undefined>(payload: SimpleAuthenticatedUser<T>, jwtSecret: string): string {\n return jwt.sign(payload, jwtSecret, { expiresIn: '1h' });\n}\n\n/**\n * Extracts the payload from a JWT string. If successful, the first value in the tuple will be the SimpleAuthenticatedUser<T> object.\n * If not successful, the first value in the tuple will be the number of the HTTP status code and the second value will be the error message,\n * so check the first value to see if it is a number and if it is, then the second value will be the error message.\n *\n * Here the generic T is the type of the customUserData field. If not known, pass unknown.\n * @param jwtToken - The JWT string to decode. Can include \"Bearer \" prefix which will be stripped.\n * @returns An object containing the userId and optional customUserData or the number of the HTTP status code and the error message.\n */\nexport function extractFromJwtString<T extends RecordOrUndef = undefined>(jwtToken: string, jwtSecret: string): [SimpleAuthenticatedUser<T> | number, string | undefined] {\n try {\n // Strip \"Bearer \" prefix if present\n const token = jwtToken.startsWith('Bearer ') ? jwtToken.substring(7) : jwtToken;\n const decoded = jwt.verify(token, jwtSecret);\n\n let userId: string;\n let customUserData: T | undefined;\n\n if (typeof decoded === 'object' && decoded !== null && 'userId' in decoded) {\n userId = (decoded as { userId: string }).userId;\n customUserData = (decoded as { customUserData: T }).customUserData ?? undefined;\n return [{ userId, customUserData }, undefined];\n }\n\n return [401, 'Unauthorized: Invalid or expired JWT token: code 1A'];\n } catch (error) {\n console.log('extractFromJwtString - Error message:', error instanceof Error ? error.message : 'Unknown error');\n return [401, `Unauthorized: Invalid or expired JWT token: code 1B`];\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/jwt.ts"],"names":[],"mappings":";;;AAIA,IAAI,GAAM,GAAA,IAAA;AACV,IAAI,aAAa,GAAK,EAAA;AAClB,EAAA,GAAA,GAAM,IAAI,SAAS,CAAA;AACvB;AAUO,SAAS,kBAAA,CAAwD,SAAqC,SAA2B,EAAA;AACpI,EAAA,OAAO,IAAI,IAAK,CAAA,OAAA,EAAS,WAAW,EAAE,SAAA,EAAW,MAAM,CAAA;AAC3D;AAWO,SAAS,oBAAA,CAA0D,UAAkB,SAA8E,EAAA;AACtK,EAAI,IAAA;AAEA,IAAM,MAAA,KAAA,GAAQ,SAAS,UAAW,CAAA,SAAS,IAAI,QAAS,CAAA,SAAA,CAAU,CAAC,CAAI,GAAA,QAAA;AACvE,IAAA,MAAM,OAAU,GAAA,GAAA,CAAI,MAAO,CAAA,KAAA,EAAO,SAAS,CAAA;AAE3C,IAAI,IAAA,MAAA;AACJ,IAAI,IAAA,cAAA;AAEJ,IAAA,IAAI,OAAO,OAAY,KAAA,QAAA,IAAY,OAAY,KAAA,IAAA,IAAQ,YAAY,OAAS,EAAA;AACxE,MAAA,MAAA,GAAU,OAA+B,CAAA,MAAA;AACzC,MAAA,cAAA,GAAkB,QAAkC,cAAkB,IAAA,KAAA,CAAA;AACtE,MAAA,OAAO,CAAC,EAAE,MAAQ,EAAA,cAAA,IAAkB,KAAS,CAAA,CAAA;AAAA;AAGjD,IAAO,OAAA,CAAC,KAAK,qDAAqD,CAAA;AAAA,WAC7D,KAAO,EAAA;AACZ,IAAA,OAAA,CAAQ,IAAI,uCAAyC,EAAA,KAAA,YAAiB,KAAQ,GAAA,KAAA,CAAM,UAAU,eAAe,CAAA;AAC7G,IAAO,OAAA,CAAC,KAAK,CAAqD,mDAAA,CAAA,CAAA;AAAA;AAE1E","file":"jwt.mjs","sourcesContent":["import type { RecordOrUndef, SimpleAuthenticatedUser } from '../types/chatbot/chatbot-types';\nimport * as jwt2 from 'jsonwebtoken';\n\n// Added this because running locally did not import default correctly\nlet jwt = jwt2;\nif ('default' in jwt) {\n jwt = jwt['default'] as any;\n}\n\n/**\n * Converts a payload containing a userId and optional customUserData into a JWT string.\n *\n * Here the generic T is the type of the customUserData field. If not known, pass unknown.\n *\n * @param payload The payload to convert to a JWT string.\n * @returns A JWT string.\n */\nexport function convertToJwtString<T extends RecordOrUndef = undefined>(payload: SimpleAuthenticatedUser<T>, jwtSecret: string): string {\n return jwt.sign(payload, jwtSecret, { expiresIn: '1h' });\n}\n\n/**\n * Extracts the payload from a JWT string. If successful, the first value in the tuple will be the SimpleAuthenticatedUser<T> object.\n * If not successful, the first value in the tuple will be the number of the HTTP status code and the second value will be the error message,\n * so check the first value to see if it is a number and if it is, then the second value will be the error message.\n *\n * Here the generic T is the type of the customUserData field. If not known, pass unknown.\n * @param jwtToken - The JWT string to decode. Can include \"Bearer \" prefix which will be stripped.\n * @returns An object containing the userId and optional customUserData or the number of the HTTP status code and the error message.\n */\nexport function extractFromJwtString<T extends RecordOrUndef = undefined>(jwtToken: string, jwtSecret: string): [SimpleAuthenticatedUser<T> | number, string | undefined] {\n try {\n // Strip \"Bearer \" prefix if present\n const token = jwtToken.startsWith('Bearer ') ? jwtToken.substring(7) : jwtToken;\n const decoded = jwt.verify(token, jwtSecret);\n\n let userId: string;\n let customUserData: T | undefined;\n\n if (typeof decoded === 'object' && decoded !== null && 'userId' in decoded) {\n userId = (decoded as { userId: string }).userId;\n customUserData = (decoded as { customUserData: T }).customUserData ?? undefined;\n return [{ userId, customUserData }, undefined];\n }\n\n return [401, 'Unauthorized: Invalid or expired JWT token: code 1A'];\n } catch (error) {\n console.log('extractFromJwtString - Error message:', error instanceof Error ? error.message : 'Unknown error');\n return [401, `Unauthorized: Invalid or expired JWT token: code 1B`];\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/util/jwt.ts"],"names":[],"mappings":";;;AAIA,IAAI,GAAA,GAAM,IAAA;AACV,IAAI,aAAa,GAAA,EAAK;AAClB,EAAA,GAAA,GAAM,IAAI,SAAS,CAAA;AACvB;AAUO,SAAS,kBAAA,CAAwD,SAAqC,SAAA,EAA2B;AACpI,EAAA,OAAO,IAAI,IAAA,CAAK,OAAA,EAAS,WAAW,EAAE,SAAA,EAAW,MAAM,CAAA;AAC3D;AAWO,SAAS,oBAAA,CAA0D,UAAkB,SAAA,EAA8E;AACtK,EAAA,IAAI;AAEA,IAAA,MAAM,KAAA,GAAQ,SAAS,UAAA,CAAW,SAAS,IAAI,QAAA,CAAS,SAAA,CAAU,CAAC,CAAA,GAAI,QAAA;AACvE,IAAA,MAAM,OAAA,GAAU,GAAA,CAAI,MAAA,CAAO,KAAA,EAAO,SAAS,CAAA;AAE3C,IAAA,IAAI,MAAA;AACJ,IAAA,IAAI,cAAA;AAEJ,IAAA,IAAI,OAAO,OAAA,KAAY,QAAA,IAAY,OAAA,KAAY,IAAA,IAAQ,YAAY,OAAA,EAAS;AACxE,MAAA,MAAA,GAAU,OAAA,CAA+B,MAAA;AACzC,MAAA,cAAA,GAAkB,QAAkC,cAAA,IAAkB,KAAA,CAAA;AACtE,MAAA,OAAO,CAAC,EAAE,MAAA,EAAQ,cAAA,IAAkB,KAAA,CAAS,CAAA;AAAA,IACjD;AAEA,IAAA,OAAO,CAAC,KAAK,qDAAqD,CAAA;AAAA,EACtE,SAAS,KAAA,EAAO;AACZ,IAAA,OAAA,CAAQ,IAAI,uCAAA,EAAyC,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,UAAU,eAAe,CAAA;AAC7G,IAAA,OAAO,CAAC,KAAK,CAAA,mDAAA,CAAqD,CAAA;AAAA,EACtE;AACJ","file":"jwt.mjs","sourcesContent":["import type { RecordOrUndef, SimpleAuthenticatedUser } from '../types/chatbot/chatbot-types';\nimport * as jwt2 from 'jsonwebtoken';\n\n// Added this because running locally did not import default correctly\nlet jwt = jwt2;\nif ('default' in jwt) {\n jwt = jwt['default'] as any;\n}\n\n/**\n * Converts a payload containing a userId and optional customUserData into a JWT string.\n *\n * Here the generic T is the type of the customUserData field. If not known, pass unknown.\n *\n * @param payload The payload to convert to a JWT string.\n * @returns A JWT string.\n */\nexport function convertToJwtString<T extends RecordOrUndef = undefined>(payload: SimpleAuthenticatedUser<T>, jwtSecret: string): string {\n return jwt.sign(payload, jwtSecret, { expiresIn: '1h' });\n}\n\n/**\n * Extracts the payload from a JWT string. If successful, the first value in the tuple will be the SimpleAuthenticatedUser<T> object.\n * If not successful, the first value in the tuple will be the number of the HTTP status code and the second value will be the error message,\n * so check the first value to see if it is a number and if it is, then the second value will be the error message.\n *\n * Here the generic T is the type of the customUserData field. If not known, pass unknown.\n * @param jwtToken - The JWT string to decode. Can include \"Bearer \" prefix which will be stripped.\n * @returns An object containing the userId and optional customUserData or the number of the HTTP status code and the error message.\n */\nexport function extractFromJwtString<T extends RecordOrUndef = undefined>(jwtToken: string, jwtSecret: string): [SimpleAuthenticatedUser<T> | number, string | undefined] {\n try {\n // Strip \"Bearer \" prefix if present\n const token = jwtToken.startsWith('Bearer ') ? jwtToken.substring(7) : jwtToken;\n const decoded = jwt.verify(token, jwtSecret);\n\n let userId: string;\n let customUserData: T | undefined;\n\n if (typeof decoded === 'object' && decoded !== null && 'userId' in decoded) {\n userId = (decoded as { userId: string }).userId;\n customUserData = (decoded as { customUserData: T }).customUserData ?? undefined;\n return [{ userId, customUserData }, undefined];\n }\n\n return [401, 'Unauthorized: Invalid or expired JWT token: code 1A'];\n } catch (error) {\n console.log('extractFromJwtString - Error message:', error instanceof Error ? error.message : 'Unknown error');\n return [401, `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,KAAA,CAAM,CAA6B,0BAAA,EAAA,KAAK,CAAE,CAAA,CAAA;AACxD","file":"server-client-utils.js","sourcesContent":["/*\n * These are utils that are safe to use both on the server and the client.\n */\n\n/**\n * Helper function to redact sensitive data from specified attributes\n * @param data - The object containing data to redact\n * @param attributesToRedact - Single attribute name or array of attribute names to redact\n * @returns A new object with specified attributes redacted\n */\nfunction redactData(data: any, attributesToRedact: string | string[]): any {\n if (!data || typeof data !== 'object') {\n return data;\n }\n\n const attributes = Array.isArray(attributesToRedact) ? attributesToRedact : [attributesToRedact];\n const redacted = { ...data };\n\n for (const attr of attributes) {\n if (attr in redacted) {\n redacted[attr] = redactValue(redacted[attr]);\n }\n }\n\n return redacted;\n}\n\n/**\n * Recursively redacts a value based on its type\n * @param value - The value to redact\n * @returns The redacted value\n */\nfunction redactValue(value: any): any {\n if (typeof value === 'string') {\n return '[REDACTED]';\n } else if (Array.isArray(value)) {\n return value.map((item) => redactValue(item));\n } else if (value && typeof value === 'object') {\n const redactedObj: any = {};\n for (const key in value) {\n if (value.hasOwnProperty(key)) {\n redactedObj[key] = redactValue(value[key]);\n }\n }\n return redactedObj;\n }\n return value; // Return as-is for other types (numbers, booleans, null, etc.)\n}\n\n/**\n * Validates that a scope value doesn't contain the '#' character which is reserved for scope construction\n */\nfunction validateScopeValue(scopeValue: string | number | Record<string, string | number>, scopeType: string): void {\n if (typeof scopeValue === 'string' && scopeValue.includes('#')) {\n throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType} scope value: ${scopeValue}`);\n }\n if (typeof scopeValue === 'object' && scopeValue !== null) {\n for (const [key, value] of Object.entries(scopeValue)) {\n if (typeof value === 'string' && value.includes('#')) {\n throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType}.${key}: ${value}`);\n }\n }\n }\n}\n\n/**\n * Constructs a scope string from scopeType and scopeValue\n * @param scopeType - The type of scope (chatapp, agent, tool, entity, agent-entity)\n * @param scopeValue - The value(s) for the scope\n * @returns The constructed scope string\n */\nfunction constructScope(scopeType: string, scopeValue: string | number | Record<string, string | number>): string {\n // Validate scope value doesn't contain '#'\n validateScopeValue(scopeValue, scopeType);\n\n switch (scopeType) {\n case 'chatapp':\n case 'agent':\n case 'tool':\n case 'entity':\n return `${scopeType}#${scopeValue}`;\n case 'agent-entity':\n if (typeof scopeValue !== 'object' || scopeValue === null) {\n throw new Error('agent-entity scopeType requires an object with agent and entity properties');\n }\n\n const agentEntityValue = scopeValue as Record<string, string | number>;\n if (!('agent' in agentEntityValue) || !('entity' in agentEntityValue)) {\n throw new Error('agent-entity scopeType requires an object with both agent and entity properties');\n }\n\n return `agent#${agentEntityValue.agent}#entity#${agentEntityValue.entity}`;\n\n default:\n throw new Error(`Unsupported scopeType: ${scopeType}`);\n }\n}\n\n/**\n * Parses a scope string back into scopeType and scopeValue\n * @param scope - The scope string to parse\n * @returns Object containing scopeType and scopeValue\n */\nfunction parseScope(scope: string): { scopeType: string; scopeValue: string | number | Record<string, string | number> } {\n if (!scope || typeof scope !== 'string') {\n throw new Error('Invalid scope: must be a non-empty string');\n }\n\n const parts = scope.split('#');\n if (parts.length < 2) {\n throw new Error(`Invalid scope format: ${scope}. Expected format: scopeType#scopeValue`);\n }\n\n const [firstType, firstValue, ...remaining] = parts;\n\n // Handle compound scopes (agent-entity)\n if (remaining.length >= 2 && firstType === 'agent' && remaining[0] === 'entity') {\n return {\n scopeType: 'agent-entity',\n scopeValue: {\n agent: firstValue,\n entity: remaining[1]\n }\n };\n }\n\n // Handle simple scopes\n if (remaining.length === 0) {\n // For simple scopes, try to convert to number if it's numeric\n const numericValue = Number(firstValue);\n const scopeValue = !isNaN(numericValue) && isFinite(numericValue) ? numericValue : firstValue;\n\n return {\n scopeType: firstType,\n scopeValue: scopeValue\n };\n }\n\n throw new Error(`Unsupported scope format: ${scope}`);\n}\n\n// Export both functions\nexport { redactData, redactValue, constructScope, parseScope };\n"]}
1
+ {"version":3,"sources":["../../src/util/server-client-utils.ts"],"names":[],"mappings":";;;AAUA,S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A,EAA6B,KAAK,CAAA,CAAE,CAAA;AACxD","file":"server-client-utils.js","sourcesContent":["/*\n * These are utils that are safe to use both on the server and the client.\n */\n\n/**\n * Helper function to redact sensitive data from specified attributes\n * @param data - The object containing data to redact\n * @param attributesToRedact - Single attribute name or array of attribute names to redact\n * @returns A new object with specified attributes redacted\n */\nfunction redactData(data: any, attributesToRedact: string | string[]): any {\n if (!data || typeof data !== 'object') {\n return data;\n }\n\n const attributes = Array.isArray(attributesToRedact) ? attributesToRedact : [attributesToRedact];\n const redacted = { ...data };\n\n for (const attr of attributes) {\n if (attr in redacted) {\n redacted[attr] = redactValue(redacted[attr]);\n }\n }\n\n return redacted;\n}\n\n/**\n * Recursively redacts a value based on its type\n * @param value - The value to redact\n * @returns The redacted value\n */\nfunction redactValue(value: any): any {\n if (typeof value === 'string') {\n return '[REDACTED]';\n } else if (Array.isArray(value)) {\n return value.map((item) => redactValue(item));\n } else if (value && typeof value === 'object') {\n const redactedObj: any = {};\n for (const key in value) {\n if (value.hasOwnProperty(key)) {\n redactedObj[key] = redactValue(value[key]);\n }\n }\n return redactedObj;\n }\n return value; // Return as-is for other types (numbers, booleans, null, etc.)\n}\n\n/**\n * Validates that a scope value doesn't contain the '#' character which is reserved for scope construction\n */\nfunction validateScopeValue(scopeValue: string | number | Record<string, string | number>, scopeType: string): void {\n if (typeof scopeValue === 'string' && scopeValue.includes('#')) {\n throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType} scope value: ${scopeValue}`);\n }\n if (typeof scopeValue === 'object' && scopeValue !== null) {\n for (const [key, value] of Object.entries(scopeValue)) {\n if (typeof value === 'string' && value.includes('#')) {\n throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType}.${key}: ${value}`);\n }\n }\n }\n}\n\n/**\n * Constructs a scope string from scopeType and scopeValue\n * @param scopeType - The type of scope (chatapp, agent, tool, entity, agent-entity)\n * @param scopeValue - The value(s) for the scope\n * @returns The constructed scope string\n */\nfunction constructScope(scopeType: string, scopeValue: string | number | Record<string, string | number>): string {\n // Validate scope value doesn't contain '#'\n validateScopeValue(scopeValue, scopeType);\n\n switch (scopeType) {\n case 'chatapp':\n case 'agent':\n case 'tool':\n case 'entity':\n return `${scopeType}#${scopeValue}`;\n case 'agent-entity':\n if (typeof scopeValue !== 'object' || scopeValue === null) {\n throw new Error('agent-entity scopeType requires an object with agent and entity properties');\n }\n\n const agentEntityValue = scopeValue as Record<string, string | number>;\n if (!('agent' in agentEntityValue) || !('entity' in agentEntityValue)) {\n throw new Error('agent-entity scopeType requires an object with both agent and entity properties');\n }\n\n return `agent#${agentEntityValue.agent}#entity#${agentEntityValue.entity}`;\n\n default:\n throw new Error(`Unsupported scopeType: ${scopeType}`);\n }\n}\n\n/**\n * Parses a scope string back into scopeType and scopeValue\n * @param scope - The scope string to parse\n * @returns Object containing scopeType and scopeValue\n */\nfunction parseScope(scope: string): { scopeType: string; scopeValue: string | number | Record<string, string | number> } {\n if (!scope || typeof scope !== 'string') {\n throw new Error('Invalid scope: must be a non-empty string');\n }\n\n const parts = scope.split('#');\n if (parts.length < 2) {\n throw new Error(`Invalid scope format: ${scope}. Expected format: scopeType#scopeValue`);\n }\n\n const [firstType, firstValue, ...remaining] = parts;\n\n // Handle compound scopes (agent-entity)\n if (remaining.length >= 2 && firstType === 'agent' && remaining[0] === 'entity') {\n return {\n scopeType: 'agent-entity',\n scopeValue: {\n agent: firstValue,\n entity: remaining[1]\n }\n };\n }\n\n // Handle simple scopes\n if (remaining.length === 0) {\n // For simple scopes, try to convert to number if it's numeric\n const numericValue = Number(firstValue);\n const scopeValue = !isNaN(numericValue) && isFinite(numericValue) ? numericValue : firstValue;\n\n return {\n scopeType: firstType,\n scopeValue: scopeValue\n };\n }\n\n throw new Error(`Unsupported scope format: ${scope}`);\n}\n\n// Export both functions\nexport { redactData, redactValue, constructScope, parseScope };\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/util/server-client-utils.ts"],"names":[],"mappings":";AAUA,SAAS,UAAA,CA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Helper function to redact sensitive data from specified attributes\n * @param data - The object containing data to redact\n * @param attributesToRedact - Single attribute name or array of attribute names to redact\n * @returns A new object with specified attributes redacted\n */\nfunction redactData(data: any, attributesToRedact: string | string[]): any {\n if (!data || typeof data !== 'object') {\n return data;\n }\n\n const attributes = Array.isArray(attributesToRedact) ? attributesToRedact : [attributesToRedact];\n const redacted = { ...data };\n\n for (const attr of attributes) {\n if (attr in redacted) {\n redacted[attr] = redactValue(redacted[attr]);\n }\n }\n\n return redacted;\n}\n\n/**\n * Recursively redacts a value based on its type\n * @param value - The value to redact\n * @returns The redacted value\n */\nfunction redactValue(value: any): any {\n if (typeof value === 'string') {\n return '[REDACTED]';\n } else if (Array.isArray(value)) {\n return value.map((item) => redactValue(item));\n } else if (value && typeof value === 'object') {\n const redactedObj: any = {};\n for (const key in value) {\n if (value.hasOwnProperty(key)) {\n redactedObj[key] = redactValue(value[key]);\n }\n }\n return redactedObj;\n }\n return value; // Return as-is for other types (numbers, booleans, null, etc.)\n}\n\n/**\n * Validates that a scope value doesn't contain the '#' character which is reserved for scope construction\n */\nfunction validateScopeValue(scopeValue: string | number | Record<string, string | number>, scopeType: string): void {\n if (typeof scopeValue === 'string' && scopeValue.includes('#')) {\n throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType} scope value: ${scopeValue}`);\n }\n if (typeof scopeValue === 'object' && scopeValue !== null) {\n for (const [key, value] of Object.entries(scopeValue)) {\n if (typeof value === 'string' && value.includes('#')) {\n throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType}.${key}: ${value}`);\n }\n }\n }\n}\n\n/**\n * Constructs a scope string from scopeType and scopeValue\n * @param scopeType - The type of scope (chatapp, agent, tool, entity, agent-entity)\n * @param scopeValue - The value(s) for the scope\n * @returns The constructed scope string\n */\nfunction constructScope(scopeType: string, scopeValue: string | number | Record<string, string | number>): string {\n // Validate scope value doesn't contain '#'\n validateScopeValue(scopeValue, scopeType);\n\n switch (scopeType) {\n case 'chatapp':\n case 'agent':\n case 'tool':\n case 'entity':\n return `${scopeType}#${scopeValue}`;\n case 'agent-entity':\n if (typeof scopeValue !== 'object' || scopeValue === null) {\n throw new Error('agent-entity scopeType requires an object with agent and entity properties');\n }\n\n const agentEntityValue = scopeValue as Record<string, string | number>;\n if (!('agent' in agentEntityValue) || !('entity' in agentEntityValue)) {\n throw new Error('agent-entity scopeType requires an object with both agent and entity properties');\n }\n\n return `agent#${agentEntityValue.agent}#entity#${agentEntityValue.entity}`;\n\n default:\n throw new Error(`Unsupported scopeType: ${scopeType}`);\n }\n}\n\n/**\n * Parses a scope string back into scopeType and scopeValue\n * @param scope - The scope string to parse\n * @returns Object containing scopeType and scopeValue\n */\nfunction parseScope(scope: string): { scopeType: string; scopeValue: string | number | Record<string, string | number> } {\n if (!scope || typeof scope !== 'string') {\n throw new Error('Invalid scope: must be a non-empty string');\n }\n\n const parts = scope.split('#');\n if (parts.length < 2) {\n throw new Error(`Invalid scope format: ${scope}. Expected format: scopeType#scopeValue`);\n }\n\n const [firstType, firstValue, ...remaining] = parts;\n\n // Handle compound scopes (agent-entity)\n if (remaining.length >= 2 && firstType === 'agent' && remaining[0] === 'entity') {\n return {\n scopeType: 'agent-entity',\n scopeValue: {\n agent: firstValue,\n entity: remaining[1]\n }\n };\n }\n\n // Handle simple scopes\n if (remaining.length === 0) {\n // For simple scopes, try to convert to number if it's numeric\n const numericValue = Number(firstValue);\n const scopeValue = !isNaN(numericValue) && isFinite(numericValue) ? numericValue : firstValue;\n\n return {\n scopeType: firstType,\n scopeValue: scopeValue\n };\n }\n\n throw new Error(`Unsupported scope format: ${scope}`);\n}\n\n// Export both functions\nexport { redactData, redactValue, constructScope, parseScope };\n"]}
1
+ {"version":3,"sources":["../../src/util/server-client-utils.ts"],"names":[],"mappings":";AAUA,SAAS,UAAA,CAAW,MAAW,kBAAA,EAA4C;AACvE,EAAA,IAAI,CAAC,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,EAAU;AACnC,IAAA,OAAO,IAAA;AAA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AAA,EAA0B,SAAS,CAAA,CAAE,CAAA;AAAA;AAEjE;AAOA,SAAS,WAAW,KAAA,EAAqG;AACrH,EAAA,IAAI,CAAC,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,EAAU;AACrC,IAAA,MAAM,IAAI,MAAM,2CAA2C,CAAA;AAAA,EAC/D;AAEA,EAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,KAAA,CAAM,GAAG,CAAA;AAC7B,EAAA,IAAI,KAAA,CAAM,SAAS,CAAA,EAAG;AAClB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,sBAAA,EAAyB,KAAK,CAAA,uCAAA,CAAyC,CAAA;AAAA,EAC3F;AAEA,EAAA,MAAM,CAAC,SAAA,EAAW,UAAA,EAAY,GAAG,SAAS,CAAA,GAAI,KAAA;AAG9C,EAAA,IAAI,SAAA,CAAU,UAAU,CAAA,IAAK,SAAA,KAAc,WAAW,SAAA,CAAU,CAAC,MAAM,QAAA,EAAU;AAC7E,IAAA,OAAO;AAAA,MACH,SAAA,EAAW,cAAA;AAAA,MACX,UAAA,EAAY;AAAA,QACR,KAAA,EAAO,UAAA;AAAA,QACP,MAAA,EAAQ,UAAU,CAAC;AAAA;AACvB,KACJ;AAAA,EACJ;AAGA,EAAA,IAAI,SAAA,CAAU,WAAW,CAAA,EAAG;AAExB,IAAA,MAAM,YAAA,GAAe,OAAO,UAAU,CAAA;AACtC,IAAA,MAAM,UAAA,GAAa,CAAC,KAAA,CAAM,YAAY,KAAK,QAAA,CAAS,YAAY,IAAI,YAAA,GAAe,UAAA;AAEnF,IAAA,OAAO;AAAA,MACH,SAAA,EAAW,SAAA;AAAA,MACX;AAAA,KACJ;AAAA,EACJ;AAEA,EAAA,MAAM,IAAI,KAAA,CAAM,CAAA,0BAAA,EAA6B,KAAK,CAAA,CAAE,CAAA;AACxD","file":"server-client-utils.mjs","sourcesContent":["/*\n * These are utils that are safe to use both on the server and the client.\n */\n\n/**\n * Helper function to redact sensitive data from specified attributes\n * @param data - The object containing data to redact\n * @param attributesToRedact - Single attribute name or array of attribute names to redact\n * @returns A new object with specified attributes redacted\n */\nfunction redactData(data: any, attributesToRedact: string | string[]): any {\n if (!data || typeof data !== 'object') {\n return data;\n }\n\n const attributes = Array.isArray(attributesToRedact) ? attributesToRedact : [attributesToRedact];\n const redacted = { ...data };\n\n for (const attr of attributes) {\n if (attr in redacted) {\n redacted[attr] = redactValue(redacted[attr]);\n }\n }\n\n return redacted;\n}\n\n/**\n * Recursively redacts a value based on its type\n * @param value - The value to redact\n * @returns The redacted value\n */\nfunction redactValue(value: any): any {\n if (typeof value === 'string') {\n return '[REDACTED]';\n } else if (Array.isArray(value)) {\n return value.map((item) => redactValue(item));\n } else if (value && typeof value === 'object') {\n const redactedObj: any = {};\n for (const key in value) {\n if (value.hasOwnProperty(key)) {\n redactedObj[key] = redactValue(value[key]);\n }\n }\n return redactedObj;\n }\n return value; // Return as-is for other types (numbers, booleans, null, etc.)\n}\n\n/**\n * Validates that a scope value doesn't contain the '#' character which is reserved for scope construction\n */\nfunction validateScopeValue(scopeValue: string | number | Record<string, string | number>, scopeType: string): void {\n if (typeof scopeValue === 'string' && scopeValue.includes('#')) {\n throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType} scope value: ${scopeValue}`);\n }\n if (typeof scopeValue === 'object' && scopeValue !== null) {\n for (const [key, value] of Object.entries(scopeValue)) {\n if (typeof value === 'string' && value.includes('#')) {\n throw new Error(`Scope value cannot contain '#' character. Found in ${scopeType}.${key}: ${value}`);\n }\n }\n }\n}\n\n/**\n * Constructs a scope string from scopeType and scopeValue\n * @param scopeType - The type of scope (chatapp, agent, tool, entity, agent-entity)\n * @param scopeValue - The value(s) for the scope\n * @returns The constructed scope string\n */\nfunction constructScope(scopeType: string, scopeValue: string | number | Record<string, string | number>): string {\n // Validate scope value doesn't contain '#'\n validateScopeValue(scopeValue, scopeType);\n\n switch (scopeType) {\n case 'chatapp':\n case 'agent':\n case 'tool':\n case 'entity':\n return `${scopeType}#${scopeValue}`;\n case 'agent-entity':\n if (typeof scopeValue !== 'object' || scopeValue === null) {\n throw new Error('agent-entity scopeType requires an object with agent and entity properties');\n }\n\n const agentEntityValue = scopeValue as Record<string, string | number>;\n if (!('agent' in agentEntityValue) || !('entity' in agentEntityValue)) {\n throw new Error('agent-entity scopeType requires an object with both agent and entity properties');\n }\n\n return `agent#${agentEntityValue.agent}#entity#${agentEntityValue.entity}`;\n\n default:\n throw new Error(`Unsupported scopeType: ${scopeType}`);\n }\n}\n\n/**\n * Parses a scope string back into scopeType and scopeValue\n * @param scope - The scope string to parse\n * @returns Object containing scopeType and scopeValue\n */\nfunction parseScope(scope: string): { scopeType: string; scopeValue: string | number | Record<string, string | number> } {\n if (!scope || typeof scope !== 'string') {\n throw new Error('Invalid scope: must be a non-empty string');\n }\n\n const parts = scope.split('#');\n if (parts.length < 2) {\n throw new Error(`Invalid scope format: ${scope}. Expected format: scopeType#scopeValue`);\n }\n\n const [firstType, firstValue, ...remaining] = parts;\n\n // Handle compound scopes (agent-entity)\n if (remaining.length >= 2 && firstType === 'agent' && remaining[0] === 'entity') {\n return {\n scopeType: 'agent-entity',\n scopeValue: {\n agent: firstValue,\n entity: remaining[1]\n }\n };\n }\n\n // Handle simple scopes\n if (remaining.length === 0) {\n // For simple scopes, try to convert to number if it's numeric\n const numericValue = Number(firstValue);\n const scopeValue = !isNaN(numericValue) && isFinite(numericValue) ? numericValue : firstValue;\n\n return {\n scopeType: firstType,\n scopeValue: scopeValue\n };\n }\n\n throw new Error(`Unsupported scope format: ${scope}`);\n}\n\n// Export both functions\nexport { redactData, redactValue, constructScope, parseScope };\n"]}
@@ -1,4 +1,44 @@
1
+ import { SiteFeatures, ChatApp, AuthenticatedUser, RecordOrUndef, ChatAppOverridableFeatures, AccessRules, ChatUser } from '../types/chatbot/chatbot-types.mjs';
2
+ import '@aws-sdk/client-bedrock-agent-runtime';
3
+ import '@aws-sdk/client-bedrock-agentcore';
4
+
1
5
  declare function gunzipBase64EncodedString(base64EncodedString: string): string;
2
6
  declare function gzipAndBase64EncodeString(string: string): string;
7
+ /**
8
+ * Compute what features the user is and isn't allowed to use for this chat app.
9
+ *
10
+ * Feature hierarchy (in order of precedence):
11
+ * 1. Site level (<root>/pika-config.ts) - Controls ultimate availability
12
+ * 2. Chat app level (chatApp.features) - Can override site settings
13
+ * 3. Admin override level (chatApp.override.features) - Can override chat app settings
14
+ *
15
+ * Note that we always return siteAdmin: { websiteEnabled: false } because we only check that for real when they try to access the admin page itself.
16
+ *
17
+ * Override rules:
18
+ * - Site level controls whether a feature can be used at all
19
+ * - Chat apps can override site level (but only to restrict)
20
+ * - Admins can override chat app level completely (but cannot enable features disabled at site level)
21
+ * - When overriding, complete feature configuration must be provided (no merging)
22
+ */
23
+ declare function getOverridableFeatures(siteFeatures: SiteFeatures, chatApp: ChatApp, user: AuthenticatedUser<RecordOrUndef, RecordOrUndef>): ChatAppOverridableFeatures;
24
+ /**
25
+ * Generic function to check if a user has access to a feature based on user types and roles.
26
+ * This implements the same logic used in get for checking user access rules.
27
+ *
28
+ * **Access Control Logic:**
29
+ * - If the feature is disabled (`enabled: false`), no access regardless of other rules
30
+ * - If no userTypes or userRoles are specified, no access is granted (secure by default)
31
+ * - If multiple userTypes are provided, a user need only have one of them to have access (OR logic)
32
+ * - If multiple userRoles are provided, a user need only have one of them to have access (OR logic)
33
+ * - If both userTypes and userRoles are provided, the `applyRulesAs` setting determines how they're combined:
34
+ * - `'and'` (default): User must match a userType AND have a userRole
35
+ * - `'or'`: User must match a userType OR have a userRole
36
+ *
37
+ * @param user - The authenticated user to check access for
38
+ * @param feature - The feature configuration with user access rules
39
+ * @returns Whether the user has access to the feature
40
+ */
41
+ declare function checkUserAccessToFeature(user: AuthenticatedUser<RecordOrUndef, RecordOrUndef>, feature: AccessRules): boolean;
42
+ declare function getEntityIdForUser(user: ChatUser<RecordOrUndef>, overrideDataForThisChatApp: RecordOrUndef, entityAttributeName?: string): string | undefined;
3
43
 
4
- export { gunzipBase64EncodedString, gzipAndBase64EncodeString };
44
+ export { checkUserAccessToFeature, getEntityIdForUser, getOverridableFeatures, gunzipBase64EncodedString, gzipAndBase64EncodeString };
@@ -1,4 +1,44 @@
1
+ import { SiteFeatures, ChatApp, AuthenticatedUser, RecordOrUndef, ChatAppOverridableFeatures, AccessRules, ChatUser } from '../types/chatbot/chatbot-types.js';
2
+ import '@aws-sdk/client-bedrock-agent-runtime';
3
+ import '@aws-sdk/client-bedrock-agentcore';
4
+
1
5
  declare function gunzipBase64EncodedString(base64EncodedString: string): string;
2
6
  declare function gzipAndBase64EncodeString(string: string): string;
7
+ /**
8
+ * Compute what features the user is and isn't allowed to use for this chat app.
9
+ *
10
+ * Feature hierarchy (in order of precedence):
11
+ * 1. Site level (<root>/pika-config.ts) - Controls ultimate availability
12
+ * 2. Chat app level (chatApp.features) - Can override site settings
13
+ * 3. Admin override level (chatApp.override.features) - Can override chat app settings
14
+ *
15
+ * Note that we always return siteAdmin: { websiteEnabled: false } because we only check that for real when they try to access the admin page itself.
16
+ *
17
+ * Override rules:
18
+ * - Site level controls whether a feature can be used at all
19
+ * - Chat apps can override site level (but only to restrict)
20
+ * - Admins can override chat app level completely (but cannot enable features disabled at site level)
21
+ * - When overriding, complete feature configuration must be provided (no merging)
22
+ */
23
+ declare function getOverridableFeatures(siteFeatures: SiteFeatures, chatApp: ChatApp, user: AuthenticatedUser<RecordOrUndef, RecordOrUndef>): ChatAppOverridableFeatures;
24
+ /**
25
+ * Generic function to check if a user has access to a feature based on user types and roles.
26
+ * This implements the same logic used in get for checking user access rules.
27
+ *
28
+ * **Access Control Logic:**
29
+ * - If the feature is disabled (`enabled: false`), no access regardless of other rules
30
+ * - If no userTypes or userRoles are specified, no access is granted (secure by default)
31
+ * - If multiple userTypes are provided, a user need only have one of them to have access (OR logic)
32
+ * - If multiple userRoles are provided, a user need only have one of them to have access (OR logic)
33
+ * - If both userTypes and userRoles are provided, the `applyRulesAs` setting determines how they're combined:
34
+ * - `'and'` (default): User must match a userType AND have a userRole
35
+ * - `'or'`: User must match a userType OR have a userRole
36
+ *
37
+ * @param user - The authenticated user to check access for
38
+ * @param feature - The feature configuration with user access rules
39
+ * @returns Whether the user has access to the feature
40
+ */
41
+ declare function checkUserAccessToFeature(user: AuthenticatedUser<RecordOrUndef, RecordOrUndef>, feature: AccessRules): boolean;
42
+ declare function getEntityIdForUser(user: ChatUser<RecordOrUndef>, overrideDataForThisChatApp: RecordOrUndef, entityAttributeName?: string): string | undefined;
3
43
 
4
- export { gunzipBase64EncodedString, gzipAndBase64EncodeString };
44
+ export { checkUserAccessToFeature, getEntityIdForUser, getOverridableFeatures, gunzipBase64EncodedString, gzipAndBase64EncodeString };