1 | 'use strict';
|
2 | const _ = require('lodash');
|
3 | const bases = require('bases');
|
4 | const builtInSlotsMap = require('./built-in-slots-map');
|
5 | const builtInIntentsMap = require('./built-in-intents-map');
|
6 | const validator = require('./validator');
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | module.exports = (intents, name, richUtterances, handler) => {
|
16 |
|
17 | richUtterances = _.isArray(richUtterances) ? richUtterances : [richUtterances];
|
18 |
|
19 |
|
20 | if(!name) {
|
21 | name = generateIntentName(intents);
|
22 |
|
23 | } else if(!validator.isNameValid(name)) {
|
24 | throw Error(`Intent name ${name} is invalid. Only lowercase and uppercase letters are allowed`);
|
25 |
|
26 | } else if(builtInIntentsMap[name]) {
|
27 |
|
28 | name = builtInIntentsMap[name];
|
29 | }
|
30 |
|
31 |
|
32 | let slots = [];
|
33 | let utterances = [];
|
34 |
|
35 | parseRichUtterances(richUtterances, slots, utterances)
|
36 |
|
37 | return {
|
38 | name: name,
|
39 | slots: slots,
|
40 | utterances: utterances,
|
41 | handler: handler
|
42 | };
|
43 | }
|
44 |
|
45 | const generateIntentName = (intents) => {
|
46 | let position = 0;
|
47 | let generatedName;
|
48 |
|
49 |
|
50 | while(intents[(generatedName = bases.toBase52(position++))] && !builtInIntentsMap[generatedName]);
|
51 |
|
52 | return generatedName;
|
53 | };
|
54 |
|
55 | const parseRichUtterances = (richUtterances, slots, utterances) => {
|
56 |
|
57 | _.each(richUtterances, function(utterance) {
|
58 | var matches = findUtteranceMatches(utterance);
|
59 |
|
60 | _.each(matches, function(match) {
|
61 |
|
62 |
|
63 | slots.push({
|
64 | name: match[1],
|
65 | type: transformSlotType(match[2])
|
66 | });
|
67 |
|
68 |
|
69 | utterance = utterance.replace(match[0], '{' + match[1] + '}');
|
70 | });
|
71 |
|
72 | if(validator.isUtteranceValid(utterance)) {
|
73 |
|
74 | utterances.push(utterance);
|
75 | } else {
|
76 | throw new Error(`Error: Sample utterance: '${utterance}' is not valid. Each sample utterance must consist only of alphabet characters, spaces, dots, hyphens, brackets and single quotes`);
|
77 | }
|
78 |
|
79 | });
|
80 | };
|
81 |
|
82 | const transformSlotType = (type) => {
|
83 | const transformedType = builtInSlotsMap[type];
|
84 | return transformedType ? transformedType : type;
|
85 | }
|
86 |
|
87 | const findUtteranceMatches = (utterance) => {
|
88 |
|
89 |
|
90 | var myregex = /{(.*?):(.*?)\}/gmi;
|
91 | var result, allMatches = [];
|
92 |
|
93 | while((result = myregex.exec(utterance)) != null) {
|
94 | allMatches.push(result);
|
95 | }
|
96 |
|
97 | return allMatches;
|
98 | } |
\ | No newline at end of file |