UNPKG

bot-form

Version:

> Formularios con UX de chatbot

755 lines (740 loc) 42.6 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@ngrx/store'), require('@ngrx/effects'), require('rxjs'), require('rxjs/operators')) : typeof define === 'function' && define.amd ? define('bot-form', ['exports', '@ngrx/store', '@ngrx/effects', 'rxjs', 'rxjs/operators'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['bot-form'] = {}, global.store, global.effects, global.rxjs, global.rxjs.operators)); }(this, (function (exports, store, effects, rxjs, operators) { 'use strict'; exports.BotFormSender = void 0; (function (BotFormSender) { BotFormSender["Bot"] = "bot"; BotFormSender["User"] = "user"; })(exports.BotFormSender || (exports.BotFormSender = {})); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function () { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(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()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function () { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function (o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } }); }) : (function (o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } /** @deprecated */ function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } /** @deprecated */ function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __spreadArray(to, from) { for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) to[j] = from[i]; return to; } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } ; var __setModuleDefault = Object.create ? (function (o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function (o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); } function __classPrivateFieldSet(receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; } var botFormAdapterFactory = function () { // tslint:disable-next-line: variable-name var _updateArray = function (arr, indexToUpdate, newElement) { return __spread(arr.slice(0, indexToUpdate), [ newElement ], arr.slice(indexToUpdate + 1)); }; // tslint:disable-next-line: variable-name var _findStep = function (state, key) { var index = state.steps.findIndex(function (s) { return key === s.key; }); var step = state.steps[index]; var isLastStep = index === state.steps.length - 1; return { index: index, step: step, isLastStep: isLastStep, }; }; // tslint:disable-next-line: variable-name var _findActiveStep = function (state) { return _findStep(state, state.activeKey); }; // tslint:disable-next-line: variable-name var _addElementsToArrayAfterIndex = function (arr, index, elements) { return __spread(arr.slice(0, index + 1), elements, arr.slice(index + 1)); }; return { addErrorMessageOnInvalidInput: function (event) { return function (state) { return (Object.assign(Object.assign({}, state), { isValidatingInput: false, isPassingToNextStep: false, messages: __spread(state.messages, [ { sender: exports.BotFormSender.Bot, text: event === null || event === void 0 ? void 0 : event.error, key: event === null || event === void 0 ? void 0 : event.key, }, ]) })); }; }, addErrorMessageOnFetchFailure: function (event) { return function (state) { return (Object.assign(Object.assign({}, state), { isFetchingOptions: false, messages: __spread(state.messages, [ { sender: exports.BotFormSender.Bot, text: event === null || event === void 0 ? void 0 : event.error, key: state.activeKey, }, ]) })); }; }, addExtraSteps: function (event) { return function (state) { var index = _findStep(state, event === null || event === void 0 ? void 0 : event.key).index; var updatedSteps = _addElementsToArrayAfterIndex(state.steps, index, event === null || event === void 0 ? void 0 : event.steps); return Object.assign(Object.assign({}, state), { steps: updatedSteps, isComplete: false }); }; }, addFulfillmentMessage: function (event) { return function (state) { return (Object.assign(Object.assign({}, state), { fulfillmentPayload: event === null || event === void 0 ? void 0 : event.data, isFulfilling: false, isFulfilled: true, messages: __spread(state.messages, [ { sender: exports.BotFormSender.Bot, text: event === null || event === void 0 ? void 0 : event.message, key: 'fulfillmentSuccess', }, ]) })); }; }, addUserMessage: function (event) { return function (state) { var _a; var step = _findActiveStep(state).step; var text = "" + (event === null || event === void 0 ? void 0 : event.input); // truco para cast number a string; if (step.inputType === 'select' && step.selectOptions) { text = (_a = step.selectOptions.find(function (_b) { var value = _b.value; return (event === null || event === void 0 ? void 0 : event.input) === value; })) === null || _a === void 0 ? void 0 : _a.text; } return Object.assign(Object.assign({}, state), { isValidatingInput: true, isPassingToNextStep: true, messages: __spread(state.messages, [ { sender: exports.BotFormSender.User, text: text, key: state.activeKey, }, ]) }); }; }, addValidInputToDto: function (event) { return function (state) { var _b; return (Object.assign(Object.assign({}, state), { dto: Object.assign(Object.assign({}, state.dto), (_b = {}, _b[event === null || event === void 0 ? void 0 : event.key] = event === null || event === void 0 ? void 0 : event.input, _b)), isValidatingInput: false })); }; }, initConversation: function () { return function (state) { var messages = [ { sender: exports.BotFormSender.Bot, key: state.steps[0].key, text: state.steps[0].prompt, }, ]; if (state.welcomeMessage) { messages.unshift({ sender: exports.BotFormSender.Bot, key: 'welcome', text: state.welcomeMessage, }); } return Object.assign(Object.assign({}, state), { messages: messages }); }; }, promptNextStep: function (event) { return function (state) { var _b = _findStep(state, event === null || event === void 0 ? void 0 : event.key).step, prompt = _b.prompt, key = _b.key; return Object.assign(Object.assign({}, state), { isPassingToNextStep: false, activeKey: key, messages: __spread(state.messages, [ { sender: exports.BotFormSender.Bot, text: prompt, key: event === null || event === void 0 ? void 0 : event.key, }, ]) }); }; }, setSelectOptions: function (event) { return function (state) { var _b = _findStep(state, event === null || event === void 0 ? void 0 : event.key), step = _b.step, index = _b.index; var newStep = Object.assign(Object.assign({}, step), { selectOptions: event === null || event === void 0 ? void 0 : event.options }); var updatedSteps = _updateArray(state.steps, index, newStep); return Object.assign(Object.assign({}, state), { steps: updatedSteps, isFetchingOptions: false }); }; }, passToNextStep: function () { return function (state) { var index = _findStep(state, state.activeKey).index; var nextStep = state.steps[index + 1]; if (nextStep) { return Object.assign(Object.assign({}, state), { activeKey: nextStep.key }); } return Object.assign(Object.assign({}, state), { isComplete: true }); }; }, undo: function () { return function (state) { var _b; var _a; var activeKey = state.activeKey, steps = state.steps, messages = state.messages, dto = state.dto, isComplete = state.isComplete; var previousKey = activeKey; var activeStepIndex = _findStep(state, activeKey).index; if (activeStepIndex > 0) { previousKey = isComplete ? activeKey : steps[activeStepIndex - 1].key; } var indexOfTheFirstMessageOfThePreviousKey = messages.findIndex(function (_b) { var key = _b.key; return key === previousKey; }); var startingIndex = indexOfTheFirstMessageOfThePreviousKey === 0 && state.welcomeMessage ? 1 : 0; // prevents the first prompt from being removed when there is a welcomeMessage var updatedMessages = messages.slice(startingIndex, indexOfTheFirstMessageOfThePreviousKey + 1); var updatedDto = Object.assign(Object.assign({}, dto), (_b = {}, _b[previousKey] = undefined, _b)); var conditionedStepsToWhichActiveKeyIsFirstPositionOf = (_a = state.conditionedSteps) === null || _a === void 0 ? void 0 : _a.find(function (conditionedSteps) { return conditionedSteps.steps.findIndex(function (_b) { var key = _b.key; return key === activeKey; }) === 0; }); var updatedSteps = steps; if (conditionedStepsToWhichActiveKeyIsFirstPositionOf) { updatedSteps = __spread(steps.slice(0, activeStepIndex), steps.slice(activeStepIndex + conditionedStepsToWhichActiveKeyIsFirstPositionOf.steps.length)); } return Object.assign(Object.assign({}, state), { activeKey: previousKey, messages: updatedMessages, dto: updatedDto, steps: updatedSteps, isComplete: false, isFulfilling: false, isConfirmed: false }); }; }, }; }; var botFormEventsFactory = function (botName) { var userInput = store.createAction("[" + botName + "] User Input", store.props()); var successfulUserInput = store.createAction("[" + botName + "] Successful User Input", store.props()); var failedUserInput = store.createAction("[" + botName + "] Failed User Input", store.props()); var lastStepCompleted = store.createAction("[" + botName + "] Last Step Completed"); var thereIsANextStep = store.createAction("[" + botName + "] There Is A Next Step", store.props()); var extraStepsConditionMet = store.createAction("[" + botName + "] Extra Steps Condition Met", store.props()); var extraStepsConditionNotMet = store.createAction("[" + botName + "] Extra Steps Condition Not Met"); var fetchOptionsStart = store.createAction("[" + botName + "] Fetch Options Start"); var fetchOptionsSuccess = store.createAction("[" + botName + "] Fetch Options Success", store.props()); var fetchOptionsFailure = store.createAction("[" + botName + "] Fetch Options Failure", store.props()); var fulfillmentSuccess = store.createAction("[" + botName + "] Fulfillment Success", store.props()); var fulfillmentFailure = store.createAction("[" + botName + "] Fulfillment Failure", store.props()); var conversationInit = store.createAction("[" + botName + "] Conversation Init"); var confirmed = store.createAction("[" + botName + "] Form Confirmed"); var cancelConfirmation = store.createAction("[" + botName + "] Cancel Confirmation"); var undoClicked = store.createAction("[" + botName + "] Undo Clicked"); return { userInput: userInput, successfulUserInput: successfulUserInput, failedUserInput: failedUserInput, lastStepCompleted: lastStepCompleted, thereIsANextStep: thereIsANextStep, extraStepsConditionMet: extraStepsConditionMet, extraStepsConditionNotMet: extraStepsConditionNotMet, fetchOptionsStart: fetchOptionsStart, fetchOptionsSuccess: fetchOptionsSuccess, fetchOptionsFailure: fetchOptionsFailure, fulfillmentSuccess: fulfillmentSuccess, fulfillmentFailure: fulfillmentFailure, conversationInit: conversationInit, undoClicked: undoClicked, confirmed: confirmed, cancelConfirmation: cancelConfirmation, }; }; var botFormReducerFactory = function (INITIAL_STATE, EVENTS, ADAPTER) { return store.createReducer(INITIAL_STATE, store.on(EVENTS.conversationInit, function (state) { return ADAPTER.initConversation()(state); }), store.on(EVENTS.userInput, function (state, event) { return ADAPTER.addUserMessage(event)(state); }), store.on(EVENTS.successfulUserInput, function (state, event) { return ADAPTER.addValidInputToDto(event)(state); }), store.on(EVENTS.failedUserInput, function (state, event) { return ADAPTER.addErrorMessageOnInvalidInput(event)(state); }), store.on(EVENTS.thereIsANextStep, function (state, event) { return ADAPTER.promptNextStep(event)(state); }), store.on(EVENTS.extraStepsConditionMet, function (state, event) { return ADAPTER.addExtraSteps(event)(state); }), store.on(EVENTS.fetchOptionsStart, function (state) { return (Object.assign(Object.assign({}, state), { isFetchingOptions: true })); }), store.on(EVENTS.fetchOptionsSuccess, function (state, event) { return ADAPTER.setSelectOptions(event)(state); }), store.on(EVENTS.lastStepCompleted, function (state) { return (Object.assign(Object.assign({}, state), { isComplete: true, isPassingToNextStep: false })); }), store.on(EVENTS.fetchOptionsFailure, function (state, event) { return ADAPTER.addErrorMessageOnFetchFailure(event)(state); }), store.on(EVENTS.undoClicked, function (state) { return ADAPTER.undo()(state); }), store.on(EVENTS.confirmed, function (state) { return (Object.assign(Object.assign({}, state), { isConfirmed: true, isFulfilling: true })); }), store.on(EVENTS.cancelConfirmation, function (state) { return ADAPTER.undo()(state); }), store.on(EVENTS.fulfillmentSuccess, function (state, event) { return ADAPTER.addFulfillmentMessage(event)(state); }), store.on(EVENTS.fulfillmentFailure, function (state) { return ADAPTER.undo()(state); })); }; var botFormSelectorsFactory = function (botFormReducerKey) { var selectBotFormState = store.createFeatureSelector(botFormReducerKey); var selectActiveKey = store.createSelector(selectBotFormState, function (_a) { var activeKey = _a.activeKey; return activeKey; }); var selectIsFetchingOptions = store.createSelector(selectBotFormState, function (_a) { var isFetchingOptions = _a.isFetchingOptions; return isFetchingOptions; }); var selectSteps = store.createSelector(selectBotFormState, function (_a) { var steps = _a.steps; return steps; }); var selectShouldUserInputBeSupressed = store.createSelector(selectBotFormState, function (_a) { var isFetchingOptions = _a.isFetchingOptions, isPassingToNextStep = _a.isPassingToNextStep, isValidatingInput = _a.isValidatingInput, isFulfilling = _a.isFulfilling, isComplete = _a.isComplete; return isFetchingOptions || isPassingToNextStep || isValidatingInput || isFulfilling || isComplete; }); var selectMessages = store.createSelector(selectBotFormState, function (_a) { var messages = _a.messages; return messages; }); var selectIsComplete = store.createSelector(selectBotFormState, function (_a) { var isComplete = _a.isComplete; return isComplete; }); var selectIsFulfilling = store.createSelector(selectBotFormState, function (_a) { var isFulfilling = _a.isFulfilling; return isFulfilling; }); var selectIsLoading = store.createSelector(selectBotFormState, function (_a) { var isFulfilling = _a.isFulfilling, isValidatingInput = _a.isValidatingInput, isFetchingOptions = _a.isFetchingOptions; return isFulfilling || isValidatingInput || isFetchingOptions; }); var selectActiveStep = store.createSelector(selectBotFormState, function (_a) { var steps = _a.steps, activeKey = _a.activeKey; return steps.find(function (step) { return step.key === activeKey; }); }); var selectStepsUpToCurrent = store.createSelector(selectBotFormState, function (_a) { var steps = _a.steps, activeKey = _a.activeKey; var activeStepIndex = steps.findIndex(function (step) { return step.key === activeKey; }); return steps.slice(0, activeStepIndex + 1); }); var selectWasLastStepReached = store.createSelector(selectBotFormState, function (_a) { var activeKey = _a.activeKey, steps = _a.steps; var activeStepIndex = steps.findIndex(function (step) { return step.key === activeKey; }); var isLastStep = activeStepIndex === steps.length - 1; return isLastStep; }); var selectStepsDto = store.createSelector(selectBotFormState, function (_a) { var dto = _a.dto; return dto; }); var selectIsFulfilled = store.createSelector(selectBotFormState, function (_a) { var isFulfilled = _a.isFulfilled; return isFulfilled; }); return { selectBotFormState: selectBotFormState, selectSteps: selectSteps, selectActiveKey: selectActiveKey, selectActiveStep: selectActiveStep, selectStepsUpToCurrent: selectStepsUpToCurrent, selectWasLastStepReached: selectWasLastStepReached, selectIsComplete: selectIsComplete, selectIsFetchingOptions: selectIsFetchingOptions, selectStepsDto: selectStepsDto, selectIsFulfilling: selectIsFulfilling, selectMessages: selectMessages, selectIsLoading: selectIsLoading, selectShouldUserInputBeSupressed: selectShouldUserInputBeSupressed, selectIsFulfilled: selectIsFulfilled, }; }; var BotFormEffects = /** @class */ (function () { function BotFormEffects(actions$, store, events, selectors, fulfillment) { var _this = this; this.actions$ = actions$; this.store = store; this.events = events; this.selectors = selectors; this.fulfillment = fulfillment; this.validateUserInput$ = effects.createEffect(function () { return _this.actions$.pipe(effects.ofType(_this.events.userInput), operators.withLatestFrom(_this.store.select(_this.selectors.selectActiveStep), _this.store.select(_this.selectors.selectBotFormState)), operators.delay(700), operators.tap(function (_c) { var _d = __read(_c, 3), event = _d[0], step = _d[1], state = _d[2]; return __awaiter(_this, void 0, void 0, function () { var _a, _b, curatedInput, schemaValidationResult, isSchemaValid, asyncReponse, _c, error_1; return __generator(this, function (_d) { switch (_d.label) { case 0: curatedInput = step.curator ? step.curator(event.input) : event.input; _d.label = 1; case 1: _d.trys.push([1, 5, , 6]); schemaValidationResult = (_a = step.validationSchema) === null || _a === void 0 ? void 0 : _a.validate(curatedInput); isSchemaValid = !(schemaValidationResult === null || schemaValidationResult === void 0 ? void 0 : schemaValidationResult.error); if (!(step.asyncValidator && isSchemaValid)) return [3 /*break*/, 3]; return [4 /*yield*/, step.asyncValidator(curatedInput, state)]; case 2: _c = _d.sent(); return [3 /*break*/, 4]; case 3: _c = null; _d.label = 4; case 4: asyncReponse = _c; if (isSchemaValid && (!asyncReponse || asyncReponse.isValid)) { this.store.dispatch(this.events.successfulUserInput({ input: curatedInput, key: step.key, })); } else { this.store.dispatch(this.events.failedUserInput({ input: curatedInput, key: step.key, error: ((_b = schemaValidationResult === null || schemaValidationResult === void 0 ? void 0 : schemaValidationResult.error) === null || _b === void 0 ? void 0 : _b.message) || (asyncReponse === null || asyncReponse === void 0 ? void 0 : asyncReponse.error) || 'Error', })); } return [3 /*break*/, 6]; case 5: error_1 = _d.sent(); this.store.dispatch(this.events.failedUserInput({ input: curatedInput, key: step.key, error: 'Ocurrió un problema con nuestros servidores, intenta luego ¡Lo sentimos!', })); return [3 /*break*/, 6]; case 6: return [2 /*return*/]; } }); }); })); }, { dispatch: false }); this.addExtraSteps$ = effects.createEffect(function () { return _this.actions$.pipe(effects.ofType(_this.events.successfulUserInput), operators.withLatestFrom(_this.store.select(_this.selectors.selectBotFormState)), operators.map(function (_c) { var _d = __read(_c, 2), event = _d[0], state = _d[1]; var _a, _b; if ((_a = state.conditionedSteps) === null || _a === void 0 ? void 0 : _a.some(function (steps) { return steps.condition(event, state); })) { var _e = __read((_b = state.conditionedSteps) === null || _b === void 0 ? void 0 : _b.filter(function (_c) { var condition = _c.condition; return condition(event, state); }), 1), steps = _e[0].steps; return _this.events.extraStepsConditionMet({ steps: steps, key: event.key, }); } return _this.events.extraStepsConditionNotMet(); })); }); this.isThereANextStep$ = effects.createEffect(function () { return _this.actions$.pipe(effects.ofType(_this.events.extraStepsConditionNotMet, _this.events.extraStepsConditionMet), operators.withLatestFrom(_this.store.select(_this.selectors.selectSteps), _this.store.select(_this.selectors.selectActiveKey), _this.store.select(_this.selectors.selectWasLastStepReached)), operators.map(function (_c) { var _d = __read(_c, 4), _ = _d[0], steps = _d[1], activeKey = _d[2], wasLastStepReached = _d[3]; if (!wasLastStepReached) { var activeStepIndex = steps.findIndex(function (step) { return step.key === activeKey; }); return _this.events.thereIsANextStep({ key: steps[activeStepIndex + 1].key, }); } return _this.events.lastStepCompleted(); })); }); this.fetchOptions$ = effects.createEffect(function () { return _this.actions$.pipe(effects.ofType(_this.events.thereIsANextStep), operators.withLatestFrom(_this.store.select(_this.selectors.selectActiveStep), _this.store.select(_this.selectors.selectBotFormState)), operators.filter(function (_c) { var _d = __read(_c, 2), _ = _d[0], step = _d[1]; return !!step.optionsFetcher; }), operators.tap(function (_c) { var _d = __read(_c, 3), _ = _d[0], step = _d[1], state = _d[2]; return __awaiter(_this, void 0, void 0, function () { var options, error_2; return __generator(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 2, , 3]); this.store.dispatch(this.events.fetchOptionsStart()); return [4 /*yield*/, step.optionsFetcher(state)]; case 1: options = _c.sent(); this.store.dispatch(this.events.fetchOptionsSuccess({ options: options, key: step.key, })); return [3 /*break*/, 3]; case 2: error_2 = _c.sent(); this.store.dispatch(this.events.fetchOptionsFailure({ error: 'Error de servidor', })); return [3 /*break*/, 3]; case 3: return [2 /*return*/]; } }); }); })); }, { dispatch: false }); this.runFulfillment$ = effects.createEffect(function () { return _this.actions$.pipe(effects.ofType(_this.events.confirmed), operators.withLatestFrom(_this.store.select(_this.selectors.selectBotFormState)), operators.filter(function (_c) { var _d = __read(_c, 2), _ = _d[0], isComplete = _d[1].isComplete; return isComplete; }), operators.switchMap(function (_c) { var _d = __read(_c, 2), _ = _d[0], state = _d[1]; return _this.fulfillment(state).pipe(operators.map(function (fulfillmentPayload) { return _this.events.fulfillmentSuccess(fulfillmentPayload); }), operators.catchError(function (err) { return rxjs.of(_this.events.fulfillmentFailure({ error: err.message })); })); })); }); } return BotFormEffects; }()); // tslint:disable-next-line: typedef function getBotFormKit(_a) { var name = _a.name, steps = _a.steps, conditionedSteps = _a.conditionedSteps, welcomeMessage = _a.welcomeMessage; if (!steps.length) { throw Error('[Bot Form "getBotFormKit"] Steps must have at least 1 entry!'); } var adapter = botFormAdapterFactory(); var events = botFormEventsFactory(name); var selectors = botFormSelectorsFactory(name); var state = { activeKey: steps[0].key, steps: steps, conditionedSteps: conditionedSteps, messages: [], welcomeMessage: welcomeMessage, dto: {}, isComplete: false, isFulfilled: false, isFetchingOptions: false, isFulfilling: false, isValidatingInput: false, isPassingToNextStep: false, isConfirmed: false, }; var reducer = botFormReducerFactory(state, events, adapter); return { events: events, selectors: selectors, reducer: reducer, }; } /** * Generated bundle index. Do not edit. */ exports.BotFormEffects = BotFormEffects; exports.getBotFormKit = getBotFormKit; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=bot-form.umd.js.map