How to use updated method in storybook-root

Best JavaScript code snippet using storybook-root

language-models.manage.model.ts

Source:language-models.manage.model.ts Github

copy

Full Screen

1import { LocalizationObject, LocalizedString, } from "healthbotcommon/tenantcontent";2import { defaultLocalizationClient, mergeLocalizationObjects } from "healthbotcommon/tenantcontent/localization";3import { tenantContents } from "../../../modules/globals";4import { logLanguageModelsChange, logLocalizationChange } from "../../../services/auditTrailsLogger";5import * as mainModel from "../main.model";6import * as localizationModel from "./configuration.localization.model";7import { QnAMakerKnowledgeBase } from "./qnmaker/QnAMakerKnowledgeBase.class";8const config = require('config');9const _ = require("underscore");10enum MethodType {11 LUIS = "luis",12 RegEx = "regex",13 QnA = "qna"14}15const builtinScenarios = [16 "/builtin/help",17 "/builtin/terms",18 "/builtin/greeting",19 "/builtin/log",20 "/builtin/feedback",21 "/builtin/forget_me",22 "/builtin/need_to_know",23 "/builtin/triage",24 "/builtin/handoff/teams/agentlogin",25 "/builtin/infermedica/triage",26 "/builtin/capita/triage",27 "/medication/information",28 "/builtin/condition/information",29 "/builtin/condition/symptoms",30 "/builtin/condition/causes",31 "/builtin/condition/complications",32 "/builtin/condition/resources",33 "/builtin/condition/specialties",34 "/builtin/nih/condition/information",35 "/builtin/nih/condition/symptoms",36 "/builtin/nih/condition/resources"37];38async function updateLocalizedString(localizedString: LocalizedString, defaultLocalizedStrings: LocalizationObject, systemLocalizedStrings: LocalizationObject, accountId, accountName, user) {39 if (!localizedString.stringId?.trim() || defaultLocalizedStrings.stringIds.includes(localizedString.stringId)) {40 localizedString.stringId = localizationModel.getStringId(localizedString["en-us"]);41 }42 const existingLocalizedString = getLocalizedString(localizedString.stringId, systemLocalizedStrings);43 if (existingLocalizedString["en-us"] !== localizedString["en-us"]) {44 await tenantContents[accountName].localization.system.saveChanges([localizedString]);45 logLocalizationChange(accountName, "modified", user, "system");46 mainModel.updateLocalizationSettings(accountName);47 mainModel.reloadTenant(accountName);48 }49 return localizedString.stringId;50}51function getLocalizedString(stringId, localizedStrings: LocalizationObject) {52 const translation = localizedStrings["en-us"]?.[stringId];53 return translation ?54 { stringId, "en-us": translation } :55 { "stringId": "", "en-us": "" };56}57function updateLocalizedStringExpression(objectToUpdate, localizedStrings: LocalizationObject) {58 for (const key of Object.keys(objectToUpdate)) {59 if (key.startsWith("_convict")) {60 delete objectToUpdate[key];61 continue;62 }63 const model = objectToUpdate[key];64 const currentExpression = model.expression;65 model.expression = getLocalizedString(model.expression, localizedStrings);66 if (model.expression.stringId === "" && model.expression["en-us"] === "") {67 model.expression["en-us"] = currentExpression;68 }69 }70}71export async function getLuisModels(accountName: string) {72 const config = await tenantContents[accountName].config.load();73 return config.get("language_understanding.luis_models");74}75export interface ILanguageUnderstanding {76 custom_regexp_recognizers: Record<string, any>;77 builtin_regexp_recognizers: Record<string, any>;78 builtin_recognizers: IBuiltinRecognizers;79 intent_handler_map: Record<string, any>;80 qna_recognizers: Record<string, any>;81}82export interface IQnAModel {83 enabled: boolean;84 description: string;85 intent: string;86 qnaEndpoint: string;87 kbId: string;88 subscription_key: string;89 threshold?: number;90 api_key?: string;91}92export interface IBuiltinRecognizers {93 triage_recognizer: Record<string, any>;94}95function getLanguageUnderstanding(tenantConfig): ILanguageUnderstanding {96 const language: ILanguageUnderstanding = tenantConfig.get("language_understanding");97 return language;98}99export async function read(account: { id: string; name: string; }) {100 const [systemLocalizedStrings, isLocalizationEnabled] = await Promise.all([101 tenantContents[account.name].localization.system.get(),102 tenantContents[account.name].config.load().then((tenantConfig) => tenantConfig.get("localizationSettings.isLocalizationEnabled"))103 ]);104 const localizedStrings = mergeLocalizationObjects(defaultLocalizationClient.get(), systemLocalizedStrings);105 const tenantConfig = await tenantContents[account.name].config.load({ localizedStrings });106 const language: ILanguageUnderstanding = getLanguageUnderstanding(tenantConfig);107 const scenarios = (await tenantContents[account.name].scenarios.listLightScenarios()).map((scenario) => ({108 name: scenario.name,109 scenario_trigger: scenario.scenario_trigger,110 RowKey: scenario.RowKey111 }));112 if (language.custom_regexp_recognizers) {113 updateLocalizedStringExpression(language.custom_regexp_recognizers, localizedStrings);114 }115 Object.keys(language.builtin_regexp_recognizers).forEach((key) => {116 if (key.startsWith("_convict")) {117 return;118 }119 if (language.builtin_regexp_recognizers[key].hide) {120 delete language.builtin_regexp_recognizers[key];121 }122 });123 Object.keys(language).forEach((key) => {124 cleanUpConvictFields(language[key]);125 });126 return {127 language,128 scenarios: _.sortBy(scenarios, 'scenario_trigger'),129 builtinScenarios,130 isLocalizationEnabled131 };132}133function cleanUpConvictFields(objectToClean: Record<string, any>) {134 for (const key of Object.keys(objectToClean)) {135 if (key.toLowerCase().startsWith("_convict")) {136 delete objectToClean[key];137 }138 }139}140export async function createNewModel(accountId: string, accountName: string, user: string, updatedModel: any) {141 const defaultLocalizedStrings = defaultLocalizationClient.get();142 const [systemLocalizedStrings, isLocalizationEnabled, specific] = await Promise.all([143 tenantContents[accountName].localization.system.get(),144 tenantContents[accountName].config.load().then((tenantConfig) => tenantConfig.get("localizationSettings.isLocalizationEnabled")),145 tenantContents[accountName].config.getOverrides()146 ]);147 specific.language_understanding = specific.language_understanding || {};148 const tenantConfig = await tenantContents[accountName].config.load({ localizedStrings: mergeLocalizationObjects(defaultLocalizedStrings, systemLocalizedStrings) });149 const language: ILanguageUnderstanding = getLanguageUnderstanding(tenantConfig);150 let modelToReturn;151 switch (updatedModel.type) {152 case MethodType.RegEx:153 if (updatedModel.expression.stringId === null) {154 updatedModel.expression.stringId = localizationModel.getStringId(updatedModel.expression["en-us"]);155 await tenantContents[accountName].localization.system.saveChanges([updatedModel.expression]);156 logLocalizationChange(accountName, "modified", user, "system");157 mainModel.updateLocalizationSettings(accountName);158 mainModel.reloadTenant(accountName);159 }160 let updatedStringId = updatedModel.expression.stringId;161 if (!isLocalizationEnabled) {162 updatedStringId = await updateLocalizedString(updatedModel.expression, defaultLocalizedStrings, systemLocalizedStrings, accountId, accountName, user);163 }164 specific.language_understanding.custom_regexp_recognizers = specific.language_understanding.custom_regexp_recognizers || {};165 specific.language_understanding.custom_regexp_recognizers[updatedModel.name] = {166 enabled: true,167 description: updatedModel.description,168 scope: updatedModel.scope,169 intent: updatedModel.intent,170 expression: updatedStringId171 };172 modelToReturn = JSON.parse(JSON.stringify(specific.language_understanding.custom_regexp_recognizers[updatedModel.name]));173 modelToReturn.expression = {174 "stringId": updatedStringId,175 "en-us": updatedModel.expression['en-us']176 };177 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};178 specific.language_understanding.intent_handler_map[updatedModel.intent] = language.intent_handler_map[updatedModel.intent] || {};179 specific.language_understanding.intent_handler_map[updatedModel.intent].handler = !(typeof (updatedModel.target) === 'string') || updatedModel.target.trim() === "" ? null : updatedModel.target;180 break;181 case MethodType.LUIS:182 specific.language_understanding.luis_models = specific.language_understanding.luis_models || {};183 specific.language_understanding.luis_models[updatedModel.name] = {184 application_id: updatedModel.application_id,185 subscription_key: updatedModel.subscription_key,186 staging: updatedModel.staging,187 verbose: updatedModel.verbose,188 region: updatedModel.region,189 bing_spell_check_subscription_key: updatedModel.bing_spell_check_subscription_key,190 enabled: updatedModel.enabled,191 description: updatedModel.description,192 scope: updatedModel.scope,193 intents: updatedModel.intents.map((intent) => intent.intent),194 };195 modelToReturn = specific.language_understanding.luis_models[updatedModel.name];196 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};197 for (const intent of updatedModel.intents) {198 specific.language_understanding.intent_handler_map[intent.intent] = language.intent_handler_map[intent.intent] || {};199 specific.language_understanding.intent_handler_map[intent.intent].handler = !intent.target || !intent.target.handler || !(typeof (intent.target.handler) === 'string') || intent.target.handler.trim() === "" ? null : intent.target.handler;200 }201 break;202 case MethodType.QnA:203 specific.language_understanding.qna_recognizers = specific.language_understanding.qna_recognizers || {};204 specific.language_understanding.qna_recognizers[updatedModel.name] = {205 enabled: true,206 description: updatedModel.description,207 intent: updatedModel.intent,208 qnaEndpoint: updatedModel.qnaEndpoint,209 kbId: updatedModel.kbId,210 subscription_key: updatedModel.subscription_key,211 threshold: Number(updatedModel.threshold) || config.get("qna.minimum_score")212 };213 modelToReturn = JSON.parse(JSON.stringify(specific.language_understanding.qna_recognizers[updatedModel.name]));214 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};215 specific.language_understanding.intent_handler_map[updatedModel.intent] = language.intent_handler_map[updatedModel.intent] || {};216 specific.language_understanding.intent_handler_map[updatedModel.intent].handler = !(typeof (updatedModel.target) === 'string') || updatedModel.target.trim() === "" ? null : updatedModel.target;217 break;218 }219 await tenantContents[accountName].config.save(specific);220 mainModel.reloadTenant(accountName);221 logLanguageModelsChange(accountName, "created", user, updatedModel.name);222 return {223 name: updatedModel.name,224 model: modelToReturn,225 intent_handler_map: (await tenantContents[accountName].config.load()).get("language_understanding.intent_handler_map")226 };227}228export async function resetModels(accountName: string, user: string) {229 const specific = await tenantContents[accountName].config.getOverrides();230 specific.language_understanding = specific.language_understanding || {};231 delete specific.language_understanding.intent_handler_map;232 delete specific.language_understanding.builtin_recognizers;233 delete specific.language_understanding.builtin_regexp_recognizers;234 delete specific.language_understanding.luis_models;235 delete specific.language_understanding.qna_recognizers;236 delete specific.language_understanding.custom_regexp_recognizers;237 await tenantContents[accountName].config.save(specific);238 mainModel.reloadTenant(accountName);239 logLanguageModelsChange(accountName, "deleted", user, 'all');240}241export async function updateQnaModel(accountId: string, accountName: string, modelToUpdate: { model: IQnAModel }) {242 const specific = await tenantContents[accountName].config.getOverrides();243 specific.language_understanding = specific.language_understanding || {};244 const qnaModels = specific.language_understanding.qna_recognizers || {};245 let found = false;246 for (const model of [...Object.values(qnaModels)] as IQnAModel[]) {247 if (model.api_key === modelToUpdate.model.api_key && model.kbId === modelToUpdate.model.kbId) {248 found = true;249 const qnaMakerKnowledgeBase = new QnAMakerKnowledgeBase({250 tenant: {251 id: accountId,252 name: accountName,253 },254 blobURIs: [config.get('qna.covid_19_cdc_knowledge_base')],255 subscriptionKey: model.api_key,256 });257 try {258 const kbs = await qnaMakerKnowledgeBase.getKnowledgeBases();259 const kb = kbs.find((knowledgeBase) => knowledgeBase.id === model.kbId);260 if (!kb) { throw new Error('Knowledgebase id does not match subscription key'); }261 const kbDetails = await qnaMakerKnowledgeBase.getKBDetails(model.kbId);262 await qnaMakerKnowledgeBase.updateKnowledgeBase(model.kbId, kbDetails.urls);263 await qnaMakerKnowledgeBase.publishKnowledgeBase(model.kbId);264 } catch (error) {265 throw new Error('an error occurred, please check your subscription key and try again in a few minutes');266 }267 }268 }269 if (!found) {270 throw new Error("Keys doesn't match");271 }272}273export async function deleteModel(accountName: string, user: string, modelToDelete: any) {274 const specific = await tenantContents[accountName].config.getOverrides();275 specific.language_understanding = specific.language_understanding || {};276 if (modelToDelete.type === 'custom_regexp_recognizers') {277 const intent = specific.language_understanding.custom_regexp_recognizers[modelToDelete.model.name].intent;278 delete specific.language_understanding.custom_regexp_recognizers[modelToDelete.model.name];279 delete specific.language_understanding.intent_handler_map[intent];280 } else if (modelToDelete.type === 'luis_models') {281 for (const intent of modelToDelete.model.intents) {282 if (intent && intent.trim() !== "") {283 delete specific.language_understanding.intent_handler_map[intent];284 }285 }286 delete specific.language_understanding.luis_models[modelToDelete.model.name];287 } else if (modelToDelete.type === 'qna_recognizers') {288 const intent = specific.language_understanding.qna_recognizers[modelToDelete.model.name].intent;289 delete specific.language_understanding.qna_recognizers[modelToDelete.model.name];290 delete specific.language_understanding.intent_handler_map[intent];291 }292 await tenantContents[accountName].config.save(specific);293 mainModel.reloadTenant(accountName);294 logLanguageModelsChange(accountName, "deleted", user, modelToDelete.model.name);295 return {296 name: modelToDelete.model.name,297 intent_handler_map: (await tenantContents[accountName].config.load()).get("language_understanding.intent_handler_map")298 };299}300export async function saveModel(accountId: string, accountName: string, user: string, updatedModel: any) {301 const defaultLocalizedStrings = defaultLocalizationClient.get();302 const [systemLocalizedStrings, isLocalizationEnabled] = await Promise.all([303 tenantContents[accountName].localization.system.get(),304 tenantContents[accountName].config.load().then((tenantConfig) => tenantConfig.get("localizationSettings.isLocalizationEnabled"))305 ]);306 const specific = await tenantContents[accountName].config.getOverrides();307 specific.language_understanding = specific.language_understanding || {};308 const tenantConfig = await tenantContents[accountName].config.load({ localizedStrings: mergeLocalizationObjects(defaultLocalizedStrings, systemLocalizedStrings) });309 const language: ILanguageUnderstanding = getLanguageUnderstanding(tenantConfig);310 let modelToReturn;311 if (updatedModel.type === 'custom_regexp_recognizers') {312 if (updatedModel.model.expression.stringId === null) {313 updatedModel.model.expression.stringId = localizationModel.getStringId(updatedModel.model.expression["en-us"]);314 await tenantContents[accountName].localization.system.saveChanges([updatedModel.model.expression]);315 logLocalizationChange(accountName, "modified", user, "system");316 mainModel.updateLocalizationSettings(accountName);317 mainModel.reloadTenant(accountName);318 }319 let updatedStringId = updatedModel.model.expression.stringId;320 if (!isLocalizationEnabled) {321 updatedStringId = await updateLocalizedString(updatedModel.model.expression, defaultLocalizedStrings, systemLocalizedStrings, accountId, accountName, user);322 }323 const previousIntent = language.custom_regexp_recognizers[updatedModel.model.name].intent;324 specific.language_understanding.custom_regexp_recognizers = specific.language_understanding.custom_regexp_recognizers || {};325 specific.language_understanding.custom_regexp_recognizers[updatedModel.model.name] = {326 enabled: updatedModel.model.enabled,327 description: updatedModel.model.description,328 scope: updatedModel.model.scope,329 intent: updatedModel.model.intent,330 expression: updatedStringId331 };332 modelToReturn = JSON.parse(JSON.stringify(specific.language_understanding.custom_regexp_recognizers[updatedModel.model.name]));333 modelToReturn.expression = {334 "stringId": updatedStringId,335 "en-us": updatedModel.model.expression['en-us']336 };337 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};338 delete specific.language_understanding.intent_handler_map[previousIntent];339 specific.language_understanding.intent_handler_map[updatedModel.model.intent] = language.intent_handler_map[updatedModel.model.intent] || {};340 specific.language_understanding.intent_handler_map[updatedModel.model.intent].handler = !(typeof (updatedModel.model.target) === 'string') || updatedModel.model.target.trim() === "" ? null : updatedModel.model.target;341 } else if (updatedModel.type === 'builtin_regexp_recognizers') {342 if (updatedModel.model.expression.stringId === null) {343 updatedModel.model.expression.stringId = localizationModel.getStringId(updatedModel.model.expression["en-us"]);344 await tenantContents[accountName].localization.system.saveChanges([updatedModel.model.expression]);345 logLocalizationChange(accountName, "modified", user, "system");346 mainModel.updateLocalizationSettings(accountName);347 mainModel.reloadTenant(accountName);348 }349 let updatedStringId = updatedModel.model.expression.stringId;350 if (!isLocalizationEnabled) {351 updatedStringId = await updateLocalizedString(updatedModel.model.expression, defaultLocalizedStrings, systemLocalizedStrings, accountId, accountName, user);352 }353 specific.language_understanding.builtin_regexp_recognizers = specific.language_understanding.builtin_regexp_recognizers || {};354 specific.language_understanding.builtin_regexp_recognizers[updatedModel.model.name] = specific.language_understanding.builtin_regexp_recognizers[updatedModel.model.name] || {};355 if (language.builtin_regexp_recognizers[updatedModel.model.name].scope !== updatedModel.model.scope) {356 specific.language_understanding.builtin_regexp_recognizers[updatedModel.model.name].scope = updatedModel.model.scope;357 }358 if (language.builtin_regexp_recognizers[updatedModel.model.name].expression.stringId !== updatedStringId) {359 specific.language_understanding.builtin_regexp_recognizers[updatedModel.model.name].expression = updatedStringId;360 }361 if (_.isEmpty(specific.language_understanding.builtin_regexp_recognizers[updatedModel.model.name])) {362 delete specific.language_understanding.builtin_regexp_recognizers[updatedModel.model.name];363 }364 if (_.isEmpty(specific.language_understanding.builtin_regexp_recognizers)) {365 delete specific.language_understanding.builtin_regexp_recognizers;366 }367 modelToReturn = (await tenantContents[accountName].config.load()).get("language_understanding.builtin_regexp_recognizers")[updatedModel.model.name];368 const previousIntent = language.builtin_regexp_recognizers[updatedModel.model.name].intent;369 if (language.intent_handler_map[previousIntent].handler !== updatedModel.model.target) {370 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};371 delete specific.language_understanding.intent_handler_map[previousIntent];372 specific.language_understanding.intent_handler_map[updatedModel.model.intent] = language.intent_handler_map[updatedModel.model.intent] || {};373 specific.language_understanding.intent_handler_map[updatedModel.model.intent].handler = !(typeof (updatedModel.model.target) === 'string') || updatedModel.model.target.trim() === "" ? null : updatedModel.model.target;374 }375 } else if (updatedModel.type === 'luis_models') {376 specific.language_understanding.luis_models[updatedModel.model.name].scope = updatedModel.model.scope;377 specific.language_understanding.luis_models[updatedModel.model.name].region = updatedModel.model.region;378 specific.language_understanding.luis_models[updatedModel.model.name].bing_spell_check_subscription_key = updatedModel.model.bing_spell_check_subscription_key;379 specific.language_understanding.luis_models[updatedModel.model.name].subscription_key = updatedModel.model.subscription_key;380 specific.language_understanding.luis_models[updatedModel.model.name].staging = updatedModel.model.staging;381 specific.language_understanding.luis_models[updatedModel.model.name].verbose = updatedModel.model.verbose;382 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};383 for (const intent of specific.language_understanding.luis_models[updatedModel.model.name].intents) {384 if (intent && intent.trim() !== "") {385 delete specific.language_understanding.intent_handler_map[intent];386 }387 }388 specific.language_understanding.luis_models[updatedModel.model.name].intents = updatedModel.model.intents.map((intent) => intent.intent);389 modelToReturn = specific.language_understanding.luis_models[updatedModel.model.name];390 for (const intent of updatedModel.model.intents) {391 specific.language_understanding.intent_handler_map[intent.intent] = language.intent_handler_map[intent.intent] || {};392 specific.language_understanding.intent_handler_map[intent.intent].handler = !(typeof (intent.target) === 'string') || intent.target.trim() === "" ? null : intent.target;393 }394 } else if (updatedModel.type === 'builtin_recognizers') {395 if (language.builtin_recognizers[updatedModel.model.name].scope !== updatedModel.model.scope) {396 specific.language_understanding.builtin_recognizers = specific.language_understanding.builtin_recognizers || {};397 specific.language_understanding.builtin_recognizers[updatedModel.model.name] = specific.language_understanding.builtin_recognizers[updatedModel.model.name] || {};398 specific.language_understanding.builtin_recognizers[updatedModel.model.name].scope = updatedModel.model.scope;399 }400 modelToReturn = (await tenantContents[accountName].config.load()).get("language_understanding.builtin_recognizers")[updatedModel.model.name];401 for (const intent of updatedModel.model.intents) {402 if (language.intent_handler_map[intent.intent].handler !== intent.target) {403 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};404 specific.language_understanding.intent_handler_map[intent.intent] = language.intent_handler_map[intent.intent] || {};405 specific.language_understanding.intent_handler_map[intent.intent].handler = !(typeof (intent.target) === 'string') || intent.target.trim() === "" ? null : intent.target;406 }407 }408 } else if (updatedModel.type === 'qna_recognizers') {409 const previousIntent = language.qna_recognizers[updatedModel.model.name].intent;410 specific.language_understanding.qna_recognizers = specific.language_understanding.qna_recognizers || {};411 specific.language_understanding.qna_recognizers[updatedModel.model.name] = {412 enabled: updatedModel.model.enabled,413 description: updatedModel.model.description,414 intent: updatedModel.model.intent,415 qnaEndpoint: updatedModel.model.qnaEndpoint,416 kbId: updatedModel.model.kbId,417 subscription_key: updatedModel.model.subscription_key,418 threshold: updatedModel.model.threshold ? Number(updatedModel.model.threshold) : undefined,419 api_key: updatedModel.model.api_key420 };421 modelToReturn = JSON.parse(JSON.stringify(specific.language_understanding.qna_recognizers[updatedModel.model.name]));422 specific.language_understanding.intent_handler_map = specific.language_understanding.intent_handler_map || {};423 delete specific.language_understanding.intent_handler_map[previousIntent];424 specific.language_understanding.intent_handler_map[updatedModel.model.intent] = language.intent_handler_map[updatedModel.model.intent] || {};425 specific.language_understanding.intent_handler_map[updatedModel.model.intent].handler = !(typeof (updatedModel.model.target) === 'string') || updatedModel.model.target.trim() === "" ? null : updatedModel.model.target;426 }427 await tenantContents[accountName].config.save(specific);428 mainModel.reloadTenant(accountName);429 logLanguageModelsChange(accountName, "modified", user, updatedModel.model.name);430 return {431 name: updatedModel.model.name,432 model: modelToReturn,433 intent_handler_map: (await tenantContents[accountName].config.load()).get("language_understanding.intent_handler_map")434 };435}436export async function toggleEnabled(accountName: string, user: string, modelToChange: any) {437 const enabled = modelToChange.enabled;438 const name = modelToChange.name;439 const modelType = modelToChange.type;440 const specific = await tenantContents[accountName].config.getOverrides();441 const tenantConfig = await tenantContents[accountName].config.load();442 const language: ILanguageUnderstanding = getLanguageUnderstanding(tenantConfig);443 if (language[modelType][name].enabled !== enabled) {444 specific.language_understanding = specific.language_understanding || {};445 specific.language_understanding[modelType] = specific.language_understanding[modelType] || {};446 specific.language_understanding[modelType][name] = specific.language_understanding[modelType][name] || {};447 specific.language_understanding[modelType][name].enabled = enabled;448 await tenantContents[accountName].config.save(specific);449 mainModel.reloadTenant(accountName);450 logLanguageModelsChange(accountName, "modified", user, name);451 }...

Full Screen

Full Screen

browser_ext_tabs_onUpdated.js

Source:browser_ext_tabs_onUpdated.js Github

copy

Full Screen

1/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */2/* vim: set sts=2 sw=2 et tw=80: */3"use strict";4requestLongerTimeout(2);5add_task(async function() {6 let win1 = await BrowserTestUtils.openNewBrowserWindow();7 await focusWindow(win1);8 let extension = ExtensionTestUtils.loadExtension({9 manifest: {10 "permissions": ["tabs"],11 "content_scripts": [{12 "matches": ["http://mochi.test/*/context_tabs_onUpdated_page.html"],13 "js": ["content-script.js"],14 "run_at": "document_start",15 }],16 },17 background: function() {18 let pageURL = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html";19 let expectedSequence = [20 {status: "loading"},21 {status: "loading", url: pageURL},22 {status: "complete"},23 ];24 let collectedSequence = [];25 browser.tabs.onUpdated.addListener(function(tabId, updatedInfo) {26 // onUpdated also fires with updatedInfo.faviconUrl, so explicitly27 // check for updatedInfo.status before recording the event.28 if ("status" in updatedInfo) {29 collectedSequence.push(updatedInfo);30 }31 });32 browser.runtime.onMessage.addListener(function() {33 if (collectedSequence.length !== expectedSequence.length) {34 browser.test.assertEq(35 JSON.stringify(expectedSequence),36 JSON.stringify(collectedSequence),37 "got unexpected number of updateInfo data"38 );39 } else {40 for (let i = 0; i < expectedSequence.length; i++) {41 browser.test.assertEq(42 expectedSequence[i].status,43 collectedSequence[i].status,44 "check updatedInfo status"45 );46 if (expectedSequence[i].url || collectedSequence[i].url) {47 browser.test.assertEq(48 expectedSequence[i].url,49 collectedSequence[i].url,50 "check updatedInfo url"51 );52 }53 }54 }55 browser.test.notifyPass("tabs.onUpdated");56 });57 browser.tabs.create({url: pageURL});58 },59 files: {60 "content-script.js": `61 window.addEventListener("message", function(evt) {62 if (evt.data == "frame-updated") {63 browser.runtime.sendMessage("load-completed");64 }65 }, true);66 `,67 },68 });69 await Promise.all([70 extension.startup(),71 extension.awaitFinish("tabs.onUpdated"),72 ]);73 await extension.unload();74 await BrowserTestUtils.closeWindow(win1);75});76async function do_test_update(background, withPermissions = true) {77 let win1 = await BrowserTestUtils.openNewBrowserWindow();78 await focusWindow(win1);79 let manifest = {};80 if (withPermissions) {81 manifest.permissions = ["tabs", "http://mochi.test/"];82 }83 let extension = ExtensionTestUtils.loadExtension({manifest, background});84 await Promise.all([85 await extension.startup(),86 await extension.awaitFinish("finish"),87 ]);88 await extension.unload();89 await BrowserTestUtils.closeWindow(win1);90}91add_task(async function test_pinned() {92 await do_test_update(function background() {93 // Create a new tab for testing update.94 browser.tabs.create({}, function(tab) {95 browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {96 // Check callback97 browser.test.assertEq(tabId, tab.id, "Check tab id");98 browser.test.log("onUpdate: " + JSON.stringify(changeInfo));99 if ("pinned" in changeInfo) {100 browser.test.assertTrue(changeInfo.pinned, "Check changeInfo.pinned");101 browser.tabs.onUpdated.removeListener(onUpdated);102 // Remove created tab.103 browser.tabs.remove(tabId);104 browser.test.notifyPass("finish");105 }106 });107 browser.tabs.update(tab.id, {pinned: true});108 });109 });110});111add_task(async function test_unpinned() {112 await do_test_update(function background() {113 // Create a new tab for testing update.114 browser.tabs.create({pinned: true}, function(tab) {115 browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {116 // Check callback117 browser.test.assertEq(tabId, tab.id, "Check tab id");118 browser.test.log("onUpdate: " + JSON.stringify(changeInfo));119 if ("pinned" in changeInfo) {120 browser.test.assertFalse(changeInfo.pinned, "Check changeInfo.pinned");121 browser.tabs.onUpdated.removeListener(onUpdated);122 // Remove created tab.123 browser.tabs.remove(tabId);124 browser.test.notifyPass("finish");125 }126 });127 browser.tabs.update(tab.id, {pinned: false});128 });129 });130});131add_task(async function test_url() {132 await do_test_update(function background() {133 // Create a new tab for testing update.134 browser.tabs.create({}, function(tab) {135 browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {136 if ("url" in changeInfo) {137 // When activity stream is enabled, about:newtab runs in the content process138 // which causes some timing issues for onUpdated. So if we encounter139 // about:newtab, return early and continue waiting for about:blank.140 if (changeInfo.url === "about:newtab") {141 return;142 }143 browser.test.assertEq("about:blank", changeInfo.url,144 "Check changeInfo.url");145 browser.tabs.onUpdated.removeListener(onUpdated);146 // Remove created tab.147 browser.tabs.remove(tabId);148 browser.test.notifyPass("finish");149 }150 // Check callback151 browser.test.assertEq(tabId, tab.id, "Check tab id");152 browser.test.log("onUpdate: " + JSON.stringify(changeInfo));153 });154 browser.tabs.update(tab.id, {url: "about:blank"});155 });156 });157});158add_task(async function test_title() {159 await do_test_update(async function background() {160 const url = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html";161 const tab = await browser.tabs.create({url});162 browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {163 browser.test.assertEq(tabId, tab.id, "Check tab id");164 browser.test.log(`onUpdated: ${JSON.stringify(changeInfo)}`);165 if ("title" in changeInfo && changeInfo.title === "New Message (1)") {166 browser.test.log("changeInfo.title is correct");167 browser.tabs.onUpdated.removeListener(onUpdated);168 browser.tabs.remove(tabId);169 browser.test.notifyPass("finish");170 }171 });172 browser.tabs.executeScript(tab.id, {code: "document.title = 'New Message (1)'"});173 });174});175add_task(async function test_without_tabs_permission() {176 await do_test_update(async function background() {177 const url = "http://mochi.test:8888/browser/browser/components/extensions/test/browser/context_tabs_onUpdated_page.html";178 const tab = await browser.tabs.create({url});179 let count = 0;180 browser.tabs.onUpdated.addListener(function onUpdated(tabId, changeInfo) {181 browser.test.assertEq(tabId, tab.id, "Check tab id");182 browser.test.log(`onUpdated: ${JSON.stringify(changeInfo)}`);183 browser.test.assertFalse("url" in changeInfo, "url should not be included without tabs permission");184 browser.test.assertFalse("favIconUrl" in changeInfo, "favIconUrl should not be included without tabs permission");185 browser.test.assertFalse("title" in changeInfo, "title should not be included without tabs permission");186 if (changeInfo.status == "complete") {187 count++;188 if (count === 2) {189 browser.test.log("Reload complete");190 browser.tabs.onUpdated.removeListener(onUpdated);191 browser.tabs.remove(tabId);192 browser.test.notifyPass("finish");193 }194 }195 });196 browser.tabs.reload(tab.id);197 }, false /* withPermissions */);198});...

Full Screen

Full Screen

audit-fields.vo.spec.ts

Source:audit-fields.vo.spec.ts Github

copy

Full Screen

1import {2 AuditFields,3 AuditFieldsProps,4} from "#seedwork/domain/value-objects/audit-fields.vo";5describe("AuditFields Unit Tests", () => {6 let validateSpy: any;7 beforeEach(() => {8 validateSpy = jest.spyOn(AuditFields, "validate");9 });10 describe("should throw an error when created_by is invalid", () => {11 const arrange = [12 {13 testCase: 1,14 created_by: null as any,15 message: {16 created_by: [17 "created_by should not be empty",18 "created_by must be a string",19 "created_by must be shorter than or equal to 255 characters",20 ],21 updated_by: [22 "updated_by should not be empty",23 "updated_by must be a string",24 "updated_by must be shorter than or equal to 255 characters",25 ],26 },27 },28 {29 testCase: 2,30 created_by: undefined as any,31 message: {32 created_by: [33 "created_by should not be empty",34 "created_by must be a string",35 "created_by must be shorter than or equal to 255 characters",36 ],37 updated_by: [38 "updated_by should not be empty",39 "updated_by must be a string",40 "updated_by must be shorter than or equal to 255 characters",41 ],42 },43 },44 {45 testCase: 3,46 created_by: "",47 message: {48 created_by: ["created_by should not be empty"],49 updated_by: ["updated_by should not be empty"],50 },51 },52 {53 testCase: 4,54 created_by: 5 as any,55 message: {56 created_by: [57 "created_by must be a string",58 "created_by must be shorter than or equal to 255 characters",59 ],60 updated_by: [61 "updated_by must be a string",62 "updated_by must be shorter than or equal to 255 characters",63 ],64 },65 },66 {67 testCase: 5,68 created_by: true as any,69 message: {70 created_by: [71 "created_by must be a string",72 "created_by must be shorter than or equal to 255 characters",73 ],74 updated_by: [75 "updated_by must be a string",76 "updated_by must be shorter than or equal to 255 characters",77 ],78 },79 },80 ];81 test.each(arrange)("$testCase) when created_by is $created_by", (i) => {82 expect(83 () => new AuditFields({ created_by: i.created_by })84 ).containsErrorMessages(i.message);85 expect(validateSpy).toHaveBeenCalledTimes(1);86 });87 });88 describe("should throw an error when props are invalid", () => {89 type Arrange = {90 testCase: number;91 props: AuditFieldsProps;92 message: {};93 };94 const created_at = new Date();95 const arrange: Arrange[] = [96 {97 testCase: 1,98 props: { created_by: "user", created_at: "fake" as any },99 message: {100 created_at: ["created_at must be a Date instance"],101 updated_at: [102 "updated_at cannot be older than created_at",103 "updated_at must be a Date instance",104 ],105 },106 },107 {108 testCase: 2,109 props: {110 created_by: "user",111 created_at,112 updated_by: true as any,113 },114 message: {115 updated_by: [116 "updated_by must be a string",117 "updated_by must be shorter than or equal to 255 characters",118 ],119 },120 },121 {122 testCase: 3,123 props: {124 created_by: "user",125 created_at,126 updated_by: "user",127 updated_at: true as any,128 },129 message: {130 updated_at: [131 "updated_at cannot be older than created_at",132 "updated_at must be a Date instance",133 ],134 },135 },136 {137 testCase: 4,138 props: {139 created_by: "user",140 created_at,141 updated_by: "user",142 updated_at: new Date(created_at.getTime() - 100),143 },144 message: {145 updated_at: ["updated_at cannot be older than created_at"],146 },147 },148 ];149 test.each(arrange)("$testCase) when props are $props", (i) => {150 expect(() => new AuditFields(i.props)).containsErrorMessages(i.message);151 expect(validateSpy).toHaveBeenCalledTimes(1);152 });153 });154 it("should create a valid vo with created_by only", () => {155 const vo = new AuditFields({ created_by: "user" });156 expect(vo.value.created_by).toBe("user");157 expect(vo.value.updated_by).toBe(vo.value.created_by);158 expect(vo.value.created_at).toBeInstanceOf(Date);159 expect(vo.value.updated_at).toBe(vo.value.created_at);160 expect(validateSpy).toHaveBeenCalledTimes(1);161 });162 it("should create a valid vo with created_by and created_at", () => {163 const created_at = new Date();164 const vo = new AuditFields({ created_by: "user", created_at });165 expect(vo.value.created_by).toBe("user");166 expect(vo.value.updated_by).toBe(vo.value.created_by);167 expect(vo.value.created_at).toBe(created_at);168 expect(vo.value.updated_at).toBe(created_at);169 expect(validateSpy).toHaveBeenCalledTimes(1);170 });171 it("should create a valid vo with created_by, created_at and updated_by", () => {172 const created_at = new Date();173 const updated_at = new Date(created_at.getTime() + 100);174 const vo = new AuditFields({175 created_by: "user",176 created_at,177 updated_by: "new user",178 updated_at,179 });180 expect(vo.value.created_by).toBe("user");181 expect(vo.value.updated_by).toBe("new user");182 expect(vo.value.created_at).toBe(created_at);183 expect(vo.value.updated_at).toBe(updated_at);184 expect(validateSpy).toHaveBeenCalledTimes(1);185 });...

Full Screen

Full Screen

jobs.js

Source:jobs.js Github

copy

Full Screen

1export const GET = 'GET_JOBS';2export const CREATE = 'CREATE';3export const CREATE_ERROR = 'CREATE_ERROR';4export const UPDATE = 'UPDATE_JOB';5export const APPLY = 'APPLY';6export const APPLY_ERROR = 'APPLY_ERROR';7export const UNAPPLY = 'UNAPPLY';8export const UNAPPLY_ERROR = 'UNAPPLY_ERROR';9export const APPROVE = 'APPROVE';10export const APPROVE_ERROR = 'APPROVE_ERROR';11export const DECLINE = 'DECLINE';12export const DECLINE_ERROR = 'DECLINE_ERROR';13export const DELETE = 'DELETE_JOB';14import * as _ from 'lodash';15export const getJobs = JobIds => {16 return { type: GET, data: JobIds }17};18export const create = (payload) => {19 let job = payload;20 job.createdTime = new Date();21 return(dispatch, getState, {getFirestore, }) => {22 const firestore = getFirestore();23 firestore.collection('jobs').add(24 job25 ).then(() => {26 dispatch({ type: "CREATE", data: payload});27 }).catch((err) => {28 dispatch({ type: "CREATE_ERROR", err});29 })30 }31};32export const updateJob = Job => {33 34 return { type: UPDATE, data: Job }35};36export const apply = (job, uid) => {37 console.log("Job Action: ", job.id, uid);38 let updatedJob = job;39 console.log("Applicants before::: ", updatedJob.applicants);40 let newApplicants = [...updatedJob.applicants, uid];41 console.log("NEW APPLICANTS: ", newApplicants);42 updatedJob = {43 ...updatedJob,44 applicants: [ ...updatedJob.applicants, uid ],45 };46 console.log(" APPLY ACTION, UPDATED JOB: ", updatedJob.applicants);47 return(dispatch, getState, {getFirestore, }) => {48 const firestore = getFirestore();49 firestore.collection('jobs').doc(job.id).set(50 updatedJob51 ).then(() => {52 dispatch({ type: "APPLY", job: job, uid: uid });53 }).catch((err) => {54 dispatch({ type: "APPLY_ERROR", err});55 })56}57};58export const unApply = (job, uid) => {59 console.log("Job UNAPPLY Action: ", job.id, uid);60 let updatedJob = job;61 console.log("Applicants before::: ", updatedJob.applicants);62 updatedJob = {63 ...updatedJob,64 applicants: _.without(updatedJob.applicants, uid),65 };66 console.log(" APPLY ACTION, UPDATED JOB: ", updatedJob.applicants);67 return(dispatch, getState, {getFirestore, }) => {68 const firestore = getFirestore();69 firestore.collection('jobs').doc(job.id).set(70 updatedJob71 ).then(() => {72 dispatch({ type: "UNAPPLY", job: job, uid: uid });73 }).catch((err) => {74 dispatch({ type: "UNAPPLY_ERROR", err});75 })76}77};78export const approve = (job, approvedApplicant) => {79 console.log("Job Approve Action: ", job.id, approvedApplicant);80 let updatedJob = job;81 console.log("Applicants before::: ", updatedJob.applicants);82 updatedJob = {83 ...updatedJob,84 applicants: _.without( updatedJob.applicants, approvedApplicant.id ),85 isFilled: true,86 approvedApplicant: approvedApplicant,87 };88 console.log(" Approve ACTION, UPDATED JOB: ", updatedJob.applicants);89 return(dispatch, getState, {getFirestore, }) => {90 const firestore = getFirestore();91 firestore.collection('jobs').doc(job.id).set(92 updatedJob93 ).then(() => {94 dispatch({ type: "APPROVE", job: job, uid: uid });95 }).catch((err) => {96 dispatch({ type: "APPROVE_ERROR", err});97 })98}99};100export const decline = (job, declinedApplicantId) => {101 let updatedJob = job;102 updatedJob = {103 ...updatedJob,104 applicants: _.without( updatedJob.applicants, declinedApplicantId),105 declinedApplicants: _.concat(updatedJob.declinedApplicants, declinedApplicantId),106 isFilled: false,107 };108 return(dispatch, getState, {getFirestore, }) => {109 const firestore = getFirestore();110 firestore.collection('jobs').doc(job.id).set(111 updatedJob112 ).then(() => {113 dispatch({ type: "DECLINE", job: job, uid: uid });114 }).catch((err) => {115 dispatch({ type: "DECLINE_ERROR", err});116 })117 }118};119export const deleteJob = JobId => {120 return { type: DELETE, data: JobId }...

Full Screen

Full Screen

shop.reducer.js

Source:shop.reducer.js Github

copy

Full Screen

1import {2 ADD_PRODUCT_TO_CART,3 DECREMENT_CART_ITEM_QUANTITY,4 INCREMENT_CART_ITEM_QUANTITY,5 REMOVE_PRODUCT_FROM_CART6} from '../actions';7import {phones} from "../data/phones";8const initialState = {9 products: phones,10 cart: []11};12const shopReducer = (state = initialState, action ) => {13 let updatedCart;14 let updatedItemIndex;15 switch (action.type) {16 case INCREMENT_CART_ITEM_QUANTITY:17 updatedCart = [...state.cart];18 updatedItemIndex = updatedCart.findIndex(19 item => item.id === action.payload20 );21 const incrementedItem = {22 ...updatedCart[updatedItemIndex]23 };24 incrementedItem.quantity++;25 updatedCart[updatedItemIndex] = incrementedItem;26 return {...state, cart: updatedCart};27 case DECREMENT_CART_ITEM_QUANTITY:28 updatedCart = [...state.cart];29 updatedItemIndex = updatedCart.findIndex(30 item => item.id === action.payload31 );32 const decrementedItem = {33 ...updatedCart[updatedItemIndex]34 };35 decrementedItem.quantity--;36 updatedCart[updatedItemIndex] = decrementedItem;37 return {...state, cart: updatedCart};38 case ADD_PRODUCT_TO_CART:39 updatedCart = [...state.cart];40 updatedItemIndex = updatedCart.findIndex(item => item.id === action.payload.id);41 if(updatedItemIndex < 0) {42 updatedCart.push({...action.payload, quantity: 1});43 } else {44 const updatedItem = {45 ...updatedCart[updatedItemIndex]46 };47 updatedItem.quantity++;48 updatedCart[updatedItemIndex] = updatedItem;49 }50 return {...state, cart: updatedCart};51 case REMOVE_PRODUCT_FROM_CART:52 updatedCart = [...state.cart];53 updatedItemIndex = updatedCart.findIndex(54 item => item.id === action.payload55 );56 updatedCart.splice(updatedItemIndex, 1);57 return {...state, cart: updatedCart};58 default:59 return state;60 }61};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { getStorybookUI, configure } from '@storybook/react-native';2import { loadStories } from './storyLoader';3configure(() => {4 loadStories();5}, module);6const StorybookUIRoot = getStorybookUI({ port: 7007, host: 'localhost' });7export default StorybookUIRoot;8import { addDecorator, configure } from '@storybook/react-native';9import { withKnobs } from '@storybook/addon-knobs';10import { withBackgrounds } from '@storybook/addon-ondevice-backgrounds';11import { loadStories } from './storyLoader';12addDecorator(withKnobs);13addDecorator(withBackgrounds);14configure(() => {15 loadStories();16}, module);17import React from 'react';18import StorybookUIRoot from './storybook';19const App = () => <StorybookUIRoot />;20export default App;21module.exports = {22 {23 alias: {24 },25 },26};27module.exports = {28 {29 alias: {30 },31 },32};33import { loadStories } from './storyLoader';34configure(() => {35 loadStories();36}, module);37export { loadStories };38import { loadStories } from './storyLoader';39configure(() => {40 loadStories();41}, module);42export { loadStories };43import { loadStories } from './storyLoader';44configure(() => {45 loadStories();46}, module);47export { loadStories };48import { loadStories }

Full Screen

Using AI Code Generation

copy

Full Screen

1import { configure } from 'storybook-root';2configure();3import { configure } from 'storybook-react';4configure();5import { configure } from 'storybook-vue';6configure();7import { configure } from 'storybook-root';8configure();9import { configure }

Full Screen

Using AI Code Generation

copy

Full Screen

1const root = require('@storybook/react/node_modules/@storybook/core/dist/server/preview');2root.getPreviewBuilder().configDir = './storybook';3root.getPreviewBuilder().configType = 'DEVELOPMENT';4root.getPreviewBuilder().config = require('./storybook/preview');5const root = require('@storybook/react/node_modules/@storybook/core/dist/server/preview');6root.getPreviewBuilder().configDir = './storybook';7root.getPreviewBuilder().configType = 'PRODUCTION';8root.getPreviewBuilder().config = require('./storybook/preview');9const root = require('@storybook/react/node_modules/@storybook/core/dist/server/preview');10root.getPreviewBuilder().configDir = './storybook';11root.getPreviewBuilder().configType = 'PRODUCTION';12root.getPreviewBuilder().config = require('./storybook/preview');13const root = require('@storybook/react/node_modules/@storybook/core/dist/server/preview');14root.getPreviewBuilder().configDir = './storybook';15root.getPreviewBuilder().configType = 'PRODUCTION';16root.getPreviewBuilder().config = require('./storybook/preview');17const root = require('@storybook/react/node_modules/@storybook/core/dist/server/preview');18root.getPreviewBuilder().configDir = './storybook';19root.getPreviewBuilder().configType = 'PRODUCTION';20root.getPreviewBuilder().config = require('./storybook/preview');21const root = require('@storybook/react/node_modules/@storybook/core/dist/server/preview');22root.getPreviewBuilder().configDir = './storybook';23root.getPreviewBuilder().configType = 'PRODUCTION';24root.getPreviewBuilder().config = require('./storybook/preview');25const root = require('@storybook/react/node_modules/@storybook/core/dist/server/preview');26root.getPreviewBuilder().configDir = './storybook';27root.getPreviewBuilder().configType = 'PRODUCTION';28root.getPreviewBuilder().config = require('./storybook/preview');29const root = require('@storybook/react/node_modules/@storybook/core/dist/server/preview');30root.getPreviewBuilder().configDir = './storybook';31root.getPreviewBuilder().configType = 'PRODUCTION';32root.getPreviewBuilder().config = require('./storybook

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful