UNPKG

skyflow-node

Version:
479 lines 21.1 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.isValidURL = exports.generateSDKMetrics = exports.parameterizedString = exports.printLog = exports.LogLevelOptions = exports.TokenType = exports.DetectEntities = exports.MaskingMethod = exports.DetectOutputTranscription = exports.CONTROLLER_TYPES = exports.DeidenitfyFileRequestTypes = exports.TYPES = exports.OrderByEnum = exports.RedactionType = exports.Env = exports.RequestMethod = exports.MessageType = exports.AuthType = exports.LogLevel = exports.TokenMode = exports.CONNECTION = exports.VAULT = exports.CONNECTION_ID = exports.VAULT_ID = exports.CREDENTIALS = exports.LOGLEVEL = exports.REQUEST_ID_KEY = exports.SKYFLOW_AUTH_HEADER_KEY = exports.BAD_REQUEST = exports.SKYFLOW_ID = exports.SDK_METRICS_HEADER_KEY = void 0; exports.getVaultURL = getVaultURL; exports.getConnectionBaseURL = getConnectionBaseURL; exports.validateToken = validateToken; exports.removeSDKVersion = removeSDKVersion; exports.getToken = getToken; exports.getBearerToken = getBearerToken; exports.getBaseUrl = getBaseUrl; exports.fillUrlWithPathAndQueryParams = fillUrlWithPathAndQueryParams; const error_1 = __importDefault(require("../error")); const sdkDetails = __importStar(require("../../package.json")); const service_account_1 = require("../service-account"); const dotenv_1 = __importDefault(require("dotenv")); const logs_1 = __importDefault(require("./logs")); const os_1 = __importDefault(require("os")); const process_1 = __importDefault(require("process")); const codes_1 = __importDefault(require("../error/codes")); const jwt_utils_1 = require("./jwt-utils"); const validations_1 = require("./validations"); dotenv_1.default.config(); exports.SDK_METRICS_HEADER_KEY = "sky-metadata"; exports.SKYFLOW_ID = "skyflowId"; exports.BAD_REQUEST = "Bad Request"; exports.SKYFLOW_AUTH_HEADER_KEY = "x-skyflow-authorization"; exports.REQUEST_ID_KEY = "x-request-id"; exports.LOGLEVEL = "loglevel"; exports.CREDENTIALS = "credentials"; exports.VAULT_ID = "vaultId"; exports.CONNECTION_ID = "connectionId"; exports.VAULT = "vault"; exports.CONNECTION = "connection"; var TokenMode; (function (TokenMode) { TokenMode["DISABLE"] = "DISABLE"; TokenMode["ENABLE"] = "ENABLE"; TokenMode["ENABLE_STRICT"] = "ENABLE_STRICT"; })(TokenMode || (exports.TokenMode = TokenMode = {})); ; var LogLevel; (function (LogLevel) { LogLevel["WARN"] = "WARN"; LogLevel["INFO"] = "INFO"; LogLevel["DEBUG"] = "DEBUG"; LogLevel["ERROR"] = "ERROR"; LogLevel["OFF"] = "OFF"; })(LogLevel || (exports.LogLevel = LogLevel = {})); var AuthType; (function (AuthType) { AuthType["TOKEN"] = "TOKEN"; AuthType["API_KEY"] = "API_KEY"; })(AuthType || (exports.AuthType = AuthType = {})); var MessageType; (function (MessageType) { MessageType["LOG"] = "LOG"; MessageType["WARN"] = "WARN"; MessageType["ERROR"] = "ERROR"; })(MessageType || (exports.MessageType = MessageType = {})); var RequestMethod; (function (RequestMethod) { RequestMethod["POST"] = "POST"; RequestMethod["GET"] = "GET"; RequestMethod["PUT"] = "PUT"; RequestMethod["PATCH"] = "PATCH"; })(RequestMethod || (exports.RequestMethod = RequestMethod = {})); var Env; (function (Env) { Env["DEV"] = "DEV"; Env["STAGE"] = "STAGE"; Env["SANDBOX"] = "SANDBOX"; Env["PROD"] = "PROD"; })(Env || (exports.Env = Env = {})); var RedactionType; (function (RedactionType) { RedactionType["DEFAULT"] = "DEFAULT"; RedactionType["PLAIN_TEXT"] = "PLAIN_TEXT"; RedactionType["MASKED"] = "MASKED"; RedactionType["REDACTED"] = "REDACTED"; })(RedactionType || (exports.RedactionType = RedactionType = {})); var OrderByEnum; (function (OrderByEnum) { OrderByEnum["ASCENDING"] = "ASCENDING"; OrderByEnum["DESCENDING"] = "DESCENDING"; OrderByEnum["NONE"] = "NONE"; })(OrderByEnum || (exports.OrderByEnum = OrderByEnum = {})); ; exports.TYPES = { INSERT: 'INSERT', INSERT_BATCH: 'INSERT_BATCH', DETOKENIZE: 'DETOKENIZE', TOKENIZE: 'TOKENIZE', DELETE: 'DELETE', UPDATE: 'UPDATE', GET: 'GET', FILE_UPLOAD: 'FILE_UPLOAD', QUERY: 'QUERY', DETECT: 'DETECT', INVOKE_CONNECTION: 'INVOKE_CONNECTION', DEIDENTIFY_TEXT: 'DEIDENTIFY_TEXT', REIDENTIFY_TEXT: 'REIDENTIFY_TEXT', DEIDENTIFY_FILE: 'DEIDENTIFY_FILE', DETECT_RUN: 'DETECT_RUN', }; var DeidenitfyFileRequestTypes; (function (DeidenitfyFileRequestTypes) { DeidenitfyFileRequestTypes["IMAGE"] = "IMAGE"; DeidenitfyFileRequestTypes["FILE"] = "FILE"; DeidenitfyFileRequestTypes["AUDIO"] = "AUDIO"; DeidenitfyFileRequestTypes["PPT"] = "PPT"; DeidenitfyFileRequestTypes["DOCUMENT"] = "DOCUMENT"; DeidenitfyFileRequestTypes["PDF"] = "PDF"; DeidenitfyFileRequestTypes["SPREADSHEET"] = "SPREADSHEET"; DeidenitfyFileRequestTypes["STRUCTURED_TEXT"] = "STRUCTURED_TEXT"; DeidenitfyFileRequestTypes["TEXT"] = "TEXT"; })(DeidenitfyFileRequestTypes || (exports.DeidenitfyFileRequestTypes = DeidenitfyFileRequestTypes = {})); exports.CONTROLLER_TYPES = { DETECT: 'DETECT', VAULT: 'VAULT', CONNECTION: 'CONNECTION', }; var DetectOutputTranscription; (function (DetectOutputTranscription) { DetectOutputTranscription["DIARIZED_TRANSCRIPTION"] = "diarized_transcription"; DetectOutputTranscription["MEDICAL_DIARIZED_TRANSCRIPTION"] = "medical_diarized_transcription"; DetectOutputTranscription["MEDICAL_TRANSCRIPTION"] = "medical_transcription"; DetectOutputTranscription["PLAINTEXT_TRANSCRIPTION"] = "plaintext_transcription"; DetectOutputTranscription["TRANSCRIPTION"] = "transcription"; })(DetectOutputTranscription || (exports.DetectOutputTranscription = DetectOutputTranscription = {})); var MaskingMethod; (function (MaskingMethod) { MaskingMethod["Blackbox"] = "blackbox"; MaskingMethod["Blur"] = "blur"; })(MaskingMethod || (exports.MaskingMethod = MaskingMethod = {})); var DetectEntities; (function (DetectEntities) { DetectEntities["ACCOUNT_NUMBER"] = "account_number"; DetectEntities["AGE"] = "age"; DetectEntities["ALL"] = "all"; DetectEntities["BANK_ACCOUNT"] = "bank_account"; DetectEntities["BLOOD_TYPE"] = "blood_type"; DetectEntities["CONDITION"] = "condition"; DetectEntities["CORPORATE_ACTION"] = "corporate_action"; DetectEntities["CREDIT_CARD"] = "credit_card"; DetectEntities["CREDIT_CARD_EXPIRATION"] = "credit_card_expiration"; DetectEntities["CVV"] = "cvv"; DetectEntities["DAY"] = "day"; DetectEntities["DATE"] = "date"; DetectEntities["DATE_INTERVAL"] = "date_interval"; DetectEntities["DOB"] = "dob"; DetectEntities["DOSE"] = "dose"; DetectEntities["DRIVER_LICENSE"] = "driver_license"; DetectEntities["DRUG"] = "drug"; DetectEntities["DURATION"] = "duration"; DetectEntities["EFFECT"] = "effect"; DetectEntities["EMAIL_ADDRESS"] = "email_address"; DetectEntities["EVENT"] = "event"; DetectEntities["FILENAME"] = "filename"; DetectEntities["FINANCIAL_METRIC"] = "financial_metric"; DetectEntities["GENDER"] = "gender"; DetectEntities["HEALTHCARE_NUMBER"] = "healthcare_number"; DetectEntities["INJURY"] = "injury"; DetectEntities["IP_ADDRESS"] = "ip_address"; DetectEntities["LANGUAGE"] = "language"; DetectEntities["LOCATION"] = "location"; DetectEntities["LOCATION_ADDRESS"] = "location_address"; DetectEntities["LOCATION_ADDRESS_STREET"] = "location_address_street"; DetectEntities["LOCATION_CITY"] = "location_city"; DetectEntities["LOCATION_COORDINATE"] = "location_coordinate"; DetectEntities["LOCATION_COUNTRY"] = "location_country"; DetectEntities["LOCATION_STATE"] = "location_state"; DetectEntities["LOCATION_ZIP"] = "location_zip"; DetectEntities["MARITAL_STATUS"] = "marital_status"; DetectEntities["MEDICAL_CODE"] = "medical_code"; DetectEntities["MEDICAL_PROCESS"] = "medical_process"; DetectEntities["MONEY"] = "money"; DetectEntities["MONTH"] = "month"; DetectEntities["NAME"] = "name"; DetectEntities["NAME_FAMILY"] = "name_family"; DetectEntities["NAME_GIVEN"] = "name_given"; DetectEntities["NAME_MEDICAL_PROFESSIONAL"] = "name_medical_professional"; DetectEntities["NUMERICAL_PII"] = "numerical_pii"; DetectEntities["OCCUPATION"] = "occupation"; DetectEntities["ORGANIZATION"] = "organization"; DetectEntities["ORGANIZATION_ID"] = "organization_id"; DetectEntities["ORGANIZATION_MEDICAL_FACILITY"] = "organization_medical_facility"; DetectEntities["ORIGIN"] = "origin"; DetectEntities["PASSPORT_NUMBER"] = "passport_number"; DetectEntities["PASSWORD"] = "password"; DetectEntities["PHONE_NUMBER"] = "phone_number"; DetectEntities["PROJECT"] = "project"; DetectEntities["PHYSICAL_ATTRIBUTE"] = "physical_attribute"; DetectEntities["POLITICAL_AFFILIATION"] = "political_affiliation"; DetectEntities["PRODUCT"] = "product"; DetectEntities["RELIGION"] = "religion"; DetectEntities["ROUTING_NUMBER"] = "routing_number"; DetectEntities["SEXUALITY"] = "sexuality"; DetectEntities["SSN"] = "ssn"; DetectEntities["STATISTICS"] = "statistics"; DetectEntities["TIME"] = "time"; DetectEntities["TREND"] = "trend"; DetectEntities["URL"] = "url"; DetectEntities["USERNAME"] = "username"; DetectEntities["VEHICLE_ID"] = "vehicle_id"; DetectEntities["ZODIAC_SIGN"] = "zodiac_sign"; })(DetectEntities || (exports.DetectEntities = DetectEntities = {})); var TokenType; (function (TokenType) { TokenType["ENTITY_UNIQUE_COUNTER"] = "entity_unq_counter"; TokenType["ENTITY_ONLY"] = "entity_only"; TokenType["VAULT_TOKEN"] = "vault_token"; })(TokenType || (exports.TokenType = TokenType = {})); function getVaultURL(clusterID, env) { switch (env) { case Env.PROD: return `https://${clusterID}.vault.skyflowapis.com`; case Env.SANDBOX: return `https://${clusterID}.vault.skyflowapis-preview.com`; case Env.DEV: return `https://${clusterID}.vault.skyflowapis.dev`; case Env.STAGE: return `https://${clusterID}.vault.skyflowapis.tech`; default: return `https://${clusterID}.vault.skyflowapis.com`; } } function getConnectionBaseURL(clusterID, env) { switch (env) { case Env.PROD: return `https://${clusterID}.gateway.skyflowapis.com`; case Env.SANDBOX: return `https://${clusterID}.gateway.skyflowapis-preview.com`; case Env.DEV: return `https://${clusterID}.gateway.skyflowapis.dev`; case Env.STAGE: return `https://${clusterID}.gateway.skyflowapis.tech`; default: return `https://${clusterID}.gateway.skyflowapis.com`; } } function validateToken(token) { if ((0, jwt_utils_1.isExpired)(token)) { throw new error_1.default(codes_1.default.TOKEN_EXPIRED); } return token; } function removeSDKVersion(message) { const sdkVersionPattern = /Skyflow Node SDK v[\d\.a-zA-Z\-]+/; const cleanedMessage = message.replace(sdkVersionPattern, '').trim(); return cleanedMessage; } function getToken(credentials, logLevel) { return __awaiter(this, void 0, void 0, function* () { if ('credentialsString' in credentials) { const stringCred = credentials; (0, exports.printLog)(logs_1.default.infoLogs.USING_CREDENTIALS_STRING, MessageType.LOG, logLevel); return (0, service_account_1.generateBearerTokenFromCreds)(stringCred.credentialsString, { roleIDs: stringCred.roles, ctx: stringCred.context, logLevel, }); } if ('path' in credentials) { const pathCred = credentials; (0, exports.printLog)(logs_1.default.infoLogs.USING_PATH, MessageType.LOG, logLevel); return (0, service_account_1.generateBearerToken)(pathCred.path, { roleIDs: pathCred.roles, ctx: pathCred.context, logLevel, }); } throw new error_1.default(codes_1.default.INVALID_CREDENTIALS); }); } function getBearerToken(credentials, logLevel) { return __awaiter(this, void 0, void 0, function* () { try { if (!credentials && process_1.default.env.SKYFLOW_CREDENTIALS === undefined) { throw new error_1.default(codes_1.default.EMPTY_CREDENTIALS); } if (!credentials && process_1.default.env.SKYFLOW_CREDENTIALS) { (0, exports.printLog)(logs_1.default.infoLogs.USING_SKYFLOW_CREDENTIALS_ENV, MessageType.LOG, logLevel); credentials = { credentialsString: process_1.default.env.SKYFLOW_CREDENTIALS }; } if ('apiKey' in credentials) { const apiKeyCred = credentials; if (apiKeyCred.apiKey.trim().length > 0 && (0, validations_1.isValidAPIKey)(apiKeyCred.apiKey)) { (0, exports.printLog)(logs_1.default.infoLogs.USING_API_KEY, MessageType.LOG, logLevel); return { type: AuthType.API_KEY, key: apiKeyCred.apiKey }; } throw new error_1.default(codes_1.default.INVALID_API_KEY); } if ('token' in credentials) { const tokenCred = credentials; (0, exports.printLog)(logs_1.default.infoLogs.USING_BEARER_TOKEN, MessageType.LOG, logLevel); return { type: AuthType.TOKEN, key: validateToken(tokenCred.token) }; } (0, exports.printLog)(logs_1.default.infoLogs.BEARER_TOKEN_LISTENER, MessageType.LOG, logLevel); const token = yield getToken(credentials, logLevel); (0, exports.printLog)(logs_1.default.infoLogs.BEARER_TOKEN_RESOLVED, MessageType.LOG, logLevel); return { type: AuthType.TOKEN, key: token.accessToken }; } catch (err) { throw new error_1.default(codes_1.default.INVALID_CREDENTIALS); } }); } function getBaseUrl(url) { try { const parsedUrl = new URL(url); return `${parsedUrl.protocol}//${parsedUrl.hostname}`; } catch (error) { return ''; } } function fillUrlWithPathAndQueryParams(url, pathParams, queryParams) { let filledUrl = url; if (pathParams) { Object.entries(pathParams).forEach(([key, value]) => { filledUrl = url.replace(`{${key}}`, String(value)); }); } if (queryParams) { filledUrl += '?'; Object.entries(queryParams).forEach(([key, value]) => { filledUrl += `${key}=${value}&`; }); filledUrl = filledUrl.substring(0, filledUrl.length - 1); } return filledUrl; } exports.LogLevelOptions = { DEBUG: { showDebugLogs: true, showInfoLogs: true, showWarnLogs: true, showErrorLogs: true, }, INFO: { showDebugLogs: false, showInfoLogs: true, showWarnLogs: true, showErrorLogs: true, }, WARN: { showDebugLogs: false, showInfoLogs: false, showWarnLogs: true, showErrorLogs: true, }, ERROR: { showDebugLogs: false, showInfoLogs: false, showWarnLogs: false, showErrorLogs: true, }, OFF: { showDebugLogs: false, showInfoLogs: false, showWarnLogs: false, showErrorLogs: false, } }; const printLog = (message, messageType, logLevel = LogLevel.ERROR) => { const { showDebugLogs, showInfoLogs, showWarnLogs, showErrorLogs, } = exports.LogLevelOptions[logLevel]; const version = (sdkDetails === null || sdkDetails === void 0 ? void 0 : sdkDetails.version) ? `v${sdkDetails === null || sdkDetails === void 0 ? void 0 : sdkDetails.version}` : ''; if (messageType === MessageType.LOG && showDebugLogs) { console.log(`DEBUG: [Skyflow Node SDK ${version}] ` + message); } else if (messageType === MessageType.LOG && showInfoLogs) { console.log(`INFO: [Skyflow Node SDK ${version}] ` + message); } else if (messageType === MessageType.WARN && showWarnLogs) { console.warn(`WARN: [Skyflow Node SDK ${version}] ` + message); } else if (messageType === MessageType.ERROR && showErrorLogs) { console.error(`ERROR: [Skyflow Node SDK ${version}] ` + message); } }; exports.printLog = printLog; const parameterizedString = (message, ...args) => { const str = message; if (!str) return ''; return str.replace(/%s[0-9]+/g, (matchedStr) => { const variableIndex = parseInt(matchedStr.replace('%s', '')) - 1; return args[variableIndex]; }); }; exports.parameterizedString = parameterizedString; const generateSDKMetrics = (logLevel) => { let sdkNameVersion = ""; let clientDeviceModel = ""; let clientOSDetails = ""; let runtimeDetails = ""; try { sdkNameVersion = `${sdkDetails.name ? `${sdkDetails.name}@` : ""}${sdkDetails.version ? sdkDetails.version : ""}`; } catch (err) { (0, exports.printLog)((0, exports.parameterizedString)(logs_1.default.infoLogs.UNABLE_TO_GENERATE_SDK_METRIC, "sdkNameVersion"), MessageType.LOG, logLevel); sdkNameVersion = ""; } try { clientDeviceModel = `${process_1.default.platform ? `${process_1.default.platform}` : ""} ${process_1.default.arch ? process_1.default.arch : ""}`; } catch (err) { (0, exports.printLog)((0, exports.parameterizedString)(logs_1.default.infoLogs.UNABLE_TO_GENERATE_SDK_METRIC, "clientDeviceModel"), MessageType.LOG, logLevel); clientDeviceModel = ""; } try { clientOSDetails = `${os_1.default.release() && os_1.default.platform() ? os_1.default.platform() + '-' + os_1.default.release() : ""}`; } catch (err) { (0, exports.printLog)((0, exports.parameterizedString)(logs_1.default.infoLogs.UNABLE_TO_GENERATE_SDK_METRIC, "clientOSDetails"), MessageType.LOG, logLevel); clientOSDetails = ""; } try { runtimeDetails = `${process_1.default.version ? `Node@${process_1.default.version}` : ""}`; } catch (err) { (0, exports.printLog)((0, exports.parameterizedString)(logs_1.default.infoLogs.UNABLE_TO_GENERATE_SDK_METRIC, "runtimeDetails"), MessageType.LOG, logLevel); runtimeDetails = ""; } return { sdk_name_version: sdkNameVersion, sdk_client_device_model: clientDeviceModel, sdk_client_os_details: clientOSDetails, sdk_runtime_details: runtimeDetails, }; }; exports.generateSDKMetrics = generateSDKMetrics; const isValidURL = (url) => { if (url && url.substring(0, 5).toLowerCase() !== 'https') { return false; } try { const tempUrl = new URL(url); if (tempUrl) return true; } catch (err) { return false; } }; exports.isValidURL = isValidURL; //# sourceMappingURL=index.js.map