theprogrammablemind_4wp 8.0.0-beta.41 → 8.0.0-beta.43

Sign up to get free protection for your applications and to get access to all the features.
package/client.js CHANGED
@@ -1,5 +1,7 @@
1
1
  const { Semantics, Semantic } = require('./src/semantics')
2
2
  const { Generators, Generator } = require('./src/generators')
3
+ const { Config } = require('./src/config')
4
+ const { loadInstance, ErrorReason, listable, setupArgs, gs, processContext, getObjects, setupProcessB, processContextsB } = require('./src/configHelpers')
3
5
  const DigraphInternal = require('./src/digraph_internal')
4
6
  const Digraph = require('./src/digraph')
5
7
  const { project } = require('./src/project')
@@ -10,36 +12,10 @@ const _ = require('lodash')
10
12
  const stringify = require('json-stable-stringify')
11
13
  const Lines = require('./lines')
12
14
  const flattens = require('./src/flatten')
13
- const { appendNoDups, InitCalls, updateQueries, safeNoDups, stableId } = require('./src/helpers')
15
+ const { appendNoDups, InitCalls, updateQueries, safeNoDups, stableId, where } = require('./src/helpers')
14
16
  const runtime = require('./runtime')
15
17
  const sortJson = runtime.sortJson
16
18
 
17
- function where (goUp = 2) {
18
- const e = new Error()
19
- const regexForm1 = /\((.*):(\d+):(\d+)\)$/
20
- const regexForm2 = /at (.*):(\d+):(\d+)$/
21
- const lines = e.stack.split('\n')
22
- let line
23
- let match
24
- for (line of lines.slice(1)) {
25
- // if (!(line.includes('config.js:') || line.includes('client.js:') || line.includes('<anonymous>'))) {
26
- if (!(line.includes('config.js:') || line.includes('client.js:'))) {
27
- match = regexForm1.exec(line) || regexForm2.exec(line)
28
- if (!match) {
29
- continue
30
- }
31
- break
32
- }
33
- }
34
- // const line = e.stack.split("\n")[goUp];
35
- // const match = regexForm1.exec(line) || regexForm2.exec(line)
36
- if (match) {
37
- return `${match[1]}:${match[2]}`
38
- } else {
39
- return 'running in browser'
40
- }
41
- }
42
-
43
19
  const getConfig_getObjectsCheck = (config, testConfig) => {
44
20
  let testConfigName = config.name
45
21
  if (testConfig.testModuleName) {
@@ -108,163 +84,6 @@ const vimdiff = (actualJSON, expectedJSON, title) => {
108
84
  }
109
85
  }
110
86
 
111
- const listable = (hierarchy) => (c, type) => {
112
- if (!c) {
113
- return false
114
- }
115
- if (hierarchy.isA(c.marker, type)) {
116
- return true
117
- }
118
- if (c.marker === 'list') {
119
- for (const t of c.types) {
120
- if (hierarchy.isA(t, type)) {
121
- return true
122
- }
123
- }
124
- }
125
- return false
126
- }
127
-
128
- const isA = (hierarchy) => (child, parent) => {
129
- if (!child || !parent) {
130
- return false
131
- }
132
- if (child.marker) {
133
- child = child.marker
134
- }
135
- if (parent.marker) {
136
- parent = parent.marker
137
- }
138
- return hierarchy.isA(child, parent)
139
- }
140
-
141
- const asList = (context) => {
142
- if (context.marker === 'list') {
143
- return context
144
- }
145
- return {
146
- marker: 'list',
147
- types: [context.marker],
148
- value: [context]
149
- }
150
- }
151
-
152
- class ErrorReason extends Error {
153
- constructor (context) {
154
- super(JSON.stringify(context))
155
- this.reason = context
156
- }
157
- }
158
-
159
- const setupArgs = (args, config, logs, hierarchy, uuidForScoping) => {
160
-
161
- // callId
162
- args.calls = new InitCalls(args.isInstance ? `${args.isInstance}#${config.name}` : config.name)
163
- if (global.theprogrammablemind && global.theprogrammablemind.loadForTesting) {
164
- args.calls = new InitCalls(Object.keys(global.theprogrammablemind.loadForTesting)[0])
165
- }
166
- args.km = (name) => config.getConfig(name)
167
- args.api = (name) => config.getConfig(name).api
168
- args.error = (context) => {
169
- throw new ErrorReason(context)
170
- }
171
- args.kms = config.getConfigs()
172
- args.config = config
173
- args.hierarchy = hierarchy
174
- args.isA = isA(hierarchy)
175
- args.listable = listable(hierarchy)
176
- args.asList = asList
177
- args.retry = () => { throw new RetryError() }
178
- args.fragments = (query) => config.fragment(query)
179
- args.breakOnSemantics = false
180
- args.theDebugger = {
181
- breakOnSemantics: (value) => args.breakOnSemantics = value
182
- }
183
- if (!logs) {
184
- }
185
- args.log = (message) => logs.push(message)
186
-
187
- args.addAssumedScoped = (args, assumed) => {
188
- const addAssumed = (args, ...moreAssumed) => {
189
- return { ...args, assumed: Object.assign({}, assumed, (args.assumed || {}), ...moreAssumed) }
190
- }
191
-
192
- args.s = (c) => config.getSemantics(logs).apply(args, c)
193
- args.g = (c, a = {}) => {
194
- return config.getGenerators(logs).apply(addAssumed(args, a), c, a)
195
- }
196
- args.gp = (c, a = {}) => {
197
- return config.getGenerators(logs).apply(addAssumed(args, a, { paraphrase: true, isResponse: false, response: false }), c, { paraphrase: true, isResponse: false, response: false })
198
- }
199
- args.gr = (c, a = {}) => {
200
- return config.getGenerators(logs).apply(addAssumed(args, a, { paraphrase: false, isResponse: true }), { ...c, paraphrase: false, isResponse: true })
201
- }
202
- args.e = (c) => {
203
- return config.getEvaluator(args.s, args.calls, logs, c)
204
- }
205
- args.gs = gs(args.g)
206
- args.gsp = gs(args.gp)
207
- args.gsr = gs(args.gr)
208
- }
209
- // for semantics
210
- args.addAssumedScoped(args, {})
211
-
212
- const getAPI = (uuid) => {
213
- if (config && config.getAPI) {
214
- return config.getAPI(uuid)
215
- }
216
- }
217
- const getAPIs = (uuid) => {
218
- if (config && config.getAPIs) {
219
- return config.getAPIs(uuid)
220
- }
221
- }
222
- args.getUUIDScoped = (uuid) => {
223
- return {
224
- api: getAPI(uuid),
225
- apis: getAPIs(uuid)
226
- }
227
- }
228
- config.getAddedArgs(args)
229
-
230
- Object.assign(args, args.getUUIDScoped(uuidForScoping || config.uuid))
231
- /*
232
- if (uuidForScoping) {
233
- Object.assign(args, args.getUUIDScoped(uuidForScoping))
234
- }
235
- */
236
- // sets args for all the API. that make a copy so the args must be fully setup by here except for scoped
237
- config.setArgs(args)
238
- }
239
-
240
- const gs = (g) => async (contexts, separator, lastSeparator) => {
241
- if (!Array.isArray(contexts)) {
242
- throw new Error('Expected a list')
243
- }
244
-
245
- let s = ''
246
- if (!separator) {
247
- separator = ' '
248
- }
249
- if (!lastSeparator) {
250
- lastSeparator = separator
251
- }
252
- let nextSeparator = ''
253
- for (let i = 0; i < contexts.length; ++i) {
254
- const context = contexts[i]
255
- const value = await g(context)
256
- if (i > 0) {
257
- if (i === contexts.length - 1) {
258
- nextSeparator = lastSeparator
259
- } else {
260
- nextSeparator = separator
261
- }
262
- }
263
- s += nextSeparator + value
264
- }
265
- return s
266
- }
267
-
268
87
  const matching = (actual, expected) => {
269
88
  if (!deepEqual(stringify(sortJson(actual, { depth: 25 })), stringify(sortJson(expected, { depth: 25 })))) {
270
89
  return false
@@ -301,44 +120,6 @@ const processContexts = async (contexts, params) => {
301
120
  return { contexts: contextsPrime, generated, logs }
302
121
  }
303
122
 
304
- const getObjects = (objects) => {
305
- return (uuid) => {
306
- if (objects && objects.namespaced) {
307
- return objects.namespaced[uuid]
308
- }
309
- return objects
310
- }
311
- }
312
-
313
- const processContext = async (context, { objects = {}, config, logs = [] }) => {
314
- const generators = config.getGenerators(logs)
315
- const semantics = config.getSemantics(logs)
316
-
317
- // map to hash
318
- config = config || {}
319
- if (config.config) {
320
- config = config
321
- }
322
-
323
- const response = {} // NA but passed in
324
- // generators = new Generators(generators.map((g) => new Generator(normalizeGenerator(g))))
325
- // semantics = new Semantics(semantics.map((g) => new Semantic(normalizeSemantic(g))))
326
- const hierarchy = new DigraphInternal((config.config || {}).hierarchy || [])
327
-
328
- const args = { objects, response, getObjects: getObjects(objects) }
329
- setupArgs(args, config, logs, hierarchy)
330
-
331
- context = await semantics.apply(args, context)
332
- const generated = await generators.apply(args, context)
333
- const assumed = { paraphrase: true, response: false, isResponse: false }
334
- const paraphrases = await generators.apply({ ...args, assumed }, context, { paraphrase: true, response: false, isResponse: false })
335
- let responses = []
336
- if (context.isResponse) {
337
- responses = generated
338
- }
339
- return { context, generated, paraphrases, responses }
340
- }
341
-
342
123
  const convertToStable = (objects) => {
343
124
  if (true) {
344
125
  return objects
@@ -430,139 +211,6 @@ const overlaps = (r1, context) => {
430
211
  return false
431
212
  }
432
213
 
433
- const setupContexts = (rawContexts) => {
434
- let first = true
435
- const contexts = []
436
- contexts.push({ marker: 'controlStart', controlRemove: true })
437
- for (const context of rawContexts) {
438
- if (first) {
439
- first = false
440
- } else {
441
- contexts.push({ marker: 'controlBetween', controlRemove: true })
442
- }
443
- contexts.push(context)
444
- }
445
- contexts.push({ marker: 'controlEnd', controlRemove: true })
446
- return contexts
447
- }
448
-
449
- const processContextsB = async ({ config, hierarchy, semantics, generators, json, isTest, rebuildingTemplate, isInstance, instance, query, data, retries, url, commandLineArgs }) => {
450
- // TODO fix this name to contextsPrime
451
- const contextsPrime = []
452
- const generatedPrime = []
453
- const paraphrasesPrime = []
454
- const paraphrasesParenthesizedPrime = []
455
- const generatedParenthesizedPrime = []
456
- const responsesPrime = []
457
- const contexts = setupContexts(json.contexts)
458
-
459
- const objects = config.get('objects')
460
- const args = { objects, isResponse: true, response: json, isTest, isInstance, getObjects: getObjects(objects), instance }
461
- if (!json.logs) {
462
- json.logs = []
463
- }
464
- setupArgs(args, config, json.logs, hierarchy)
465
- const toDo = [...contexts]
466
- args.insert = (context) => toDo.unshift(context)
467
- let overlap, lastRange
468
- config.debugLoops = commandLineArgs && commandLineArgs.debugLoops
469
- while (toDo.length > 0) {
470
- const context = toDo.shift()
471
- args.calls.next()
472
- let contextPrime = context
473
- context.topLevel = true
474
- try {
475
- if (json.has_errors) {
476
- throw new Error('There are errors in the logs. Run with the -d flag and grep for Error')
477
- }
478
- const generateParenthesized = isTest || (commandLineArgs && commandLineArgs.save)
479
- if (!config.get('skipSemantics')) {
480
- const semantics = config.getSemantics(json.logs)
481
- try {
482
- contextPrime = await semantics.apply(args, context)
483
- } catch (e) {
484
- if (e.message == 'Maximum call stack size exceeded') {
485
- const mostCalled = semantics.getMostCalled()
486
- e.message += `\nThe most called semantic was:\nnotes: ${mostCalled.notes}\nmatch: ${mostCalled.matcher.toString()}\napply: ${mostCalled._apply.toString()}\n`
487
- }
488
- // contextPrime = semantics.apply(args, { marker: 'error', context, error: e })
489
- if (isInstance) {
490
- console.log('error', e.error)
491
- }
492
- contextPrime = await semantics.apply(args, {
493
- marker: 'error',
494
- context,
495
- text: e ? e.toString() : 'not available',
496
- reason: e.reason,
497
- error: e.stack || e.error
498
- })
499
- if (rebuildingTemplate) {
500
- throw e
501
- }
502
- }
503
- }
504
- if (contextPrime.controlRemove) {
505
- continue
506
- }
507
- let assumed = { isResponse: true }
508
- const generated = contextPrime.isResponse ? await config.getGenerators(json.logs).apply({ ...args, assumed }, contextPrime, assumed) : ''
509
- let generatedParenthesized = []
510
- if (generateParenthesized) {
511
- config.parenthesized = true
512
- generatedParenthesized = contextPrime.isResponse ? await config.getGenerators(json.logs).apply({ ...args, assumed }, contextPrime, assumed) : ''
513
- config.parenthesized = false
514
- }
515
- // assumed = { paraphrase: true, response: false };
516
- assumed = { paraphrase: true, isResponse: false, response: false }
517
- if (generateParenthesized) {
518
- config.parenthesized = false
519
- }
520
- const paraphrases = await config.getGenerators(json.logs).apply({ ...args, assumed }, contextPrime, assumed)
521
- let paraphrasesParenthesized = []
522
- if (generateParenthesized) {
523
- config.parenthesized = true
524
- paraphrasesParenthesized = await config.getGenerators(json.logs).apply({ ...args, assumed }, contextPrime, assumed)
525
- config.parenthesized = false
526
- }
527
- contextsPrime.push(contextPrime)
528
- generatedPrime.push(generated)
529
- paraphrasesPrime.push(paraphrases)
530
- if (generateParenthesized) {
531
- paraphrasesParenthesizedPrime.push(paraphrasesParenthesized)
532
- generatedParenthesizedPrime.push(generatedParenthesized)
533
- }
534
- if (contextPrime.isResponse) {
535
- responsesPrime.push(generated)
536
- } else {
537
- responsesPrime.push('')
538
- }
539
-
540
- // add results to processed list
541
- config.config.objects.processed = config.config.objects.processed || []
542
- config.config.objects.processed = config.config.objects.processed.slice(0, 5)
543
- config.config.objects.processed.unshift({ context: contextPrime, paraphrases: paraphrases, paraphrasesParenthesized, generatedParenthesized, responses: responsesPrime })
544
- } catch (e) {
545
- if (Array.isArray(e)) {
546
- e = {
547
- errors: e
548
- }
549
- }
550
- e.context = contextPrime
551
- if (e.logs) {
552
- e.logs = e.logs.concat(json.logs)
553
- } else {
554
- e.logs = json.logs
555
- }
556
- e.metadata = json.metadata
557
- if (json.trace) {
558
- e.trace = json.trace
559
- }
560
- throw e
561
- }
562
- }
563
- return { contextsPrime, generatedPrime, paraphrasesPrime, paraphrasesParenthesizedPrime, generatedParenthesizedPrime, responsesPrime }
564
- }
565
-
566
214
  const doWithRetries = async (n, url, queryParams, data) => {
567
215
  if (!queryParams) {
568
216
  queryParams = ''
@@ -597,93 +245,6 @@ const doWithRetries = async (n, url, queryParams, data) => {
597
245
  }
598
246
  }
599
247
 
600
- const setupProcessB = ({ config, initializer, allowDelta = false } = {}) => {
601
- const key = config._key
602
-
603
- const data = Object.assign({ key, version: '3' }, { uuid: config._uuid })
604
- if (allowDelta && config.allowDelta && config.hasDelta()) {
605
- // console.log('config', config)
606
- data.delta = config.delta()
607
- } else {
608
- config.toData(data)
609
- // Object.assign(data, config.config)
610
- }
611
-
612
- // config.toServer(data)
613
-
614
- if (data.namespaces) {
615
- for (const uuid of Object.keys(data.namespaces)) {
616
- const km = config.configs.find((km) => km.uuid === uuid)
617
- data.namespaces[uuid].name = km.name
618
- }
619
- }
620
-
621
- // const generators = new Generators((data.generators || []).map((g) => new Generator(normalizeGenerator(g))))
622
- delete data.generators
623
- // const semantics = new Semantics((data.semantics || []).map((g) => new Semantic(normalizeSemantic(g))))
624
- delete data.semantics
625
- const hierarchy = new DigraphInternal((config.config || {}).hierarchy || [])
626
-
627
- return {
628
- data,
629
- // generators,
630
- // semantics,
631
- hierarchy
632
- }
633
- }
634
-
635
- // instance template loadTemplate
636
- const loadInstance = async (config, instance) => {
637
- const transitoryMode = global.transitoryMode
638
- global.transitoryMode = false
639
-
640
- if (instance && (instance.associations || instance.learned_contextual_priorities)) {
641
- if (!config.config.retrain) {
642
- if (instance.associations) {
643
- config.addAssociations(instance.associations)
644
- }
645
- if (instance.learned_contextual_priorities && instance.learned_contextual_priorities.length > 0) {
646
- config.addPriorities(instance.learned_contextual_priorities)
647
- }
648
- }
649
- }
650
-
651
- const { /* data, generators, semantics, */ hierarchy } = setupProcessB({ config })
652
- // for (const results of (instance.resultss || [])) {
653
- for (const i in (instance.resultss || [])) {
654
- const results = instance.resultss[i]
655
- if (results.extraConfig) {
656
- // config.addInternal(results, useOldVersion = true, skipObjects = false, includeNamespaces = true, allowNameToBeNull = false)
657
- const uuid = config.nameToUUID(instance.name)
658
- // used to do a CLONE
659
- config.addInternal(instance.template.configs[i], { uuid, addFirst: true, handleCalculatedProps: true })
660
- } else if (results.apply) {
661
- const objects = config.get('objects')
662
- const args = { objects, getObjects: getObjects(objects) }
663
- if (instance.configs) {
664
- args.isInstance = `instance${i}`
665
- args.instance = instance.configs[i]
666
- }
667
-
668
- const uuid = config.nameToUUID(instance.name)
669
- setupArgs(args, config, config.logs, hierarchy, uuid)
670
- await results.apply(args)
671
- } else {
672
- if (results.skipSemantics) {
673
- config.config.skipSemantics = results.skipSemantics
674
- }
675
- const args = { config, hierarchy, json: results, commandLineArgs: {} }
676
- args.isInstance = `instance${i}`
677
- args.instance = ''
678
- await processContextsB(args)
679
- if (results.skipSemantics) {
680
- config.config.skipSemantics = null
681
- }
682
- }
683
- }
684
- global.transitoryMode = transitoryMode
685
- }
686
-
687
248
  const throwErrorHandler = (error) => {
688
249
  throw error
689
250
  }
@@ -1508,11 +1069,15 @@ const checkTest = (testConfig) => {
1508
1069
  }
1509
1070
 
1510
1071
  const knowledgeModuleImpl = async ({
1072
+ includes,
1073
+ config : configStruct,
1074
+ api,
1075
+ initializer,
1076
+ multiApiInitializer,
1077
+
1511
1078
  module: moduleFromJSFile,
1512
1079
  description,
1513
1080
  section,
1514
- // config, createConfig,
1515
- createConfig,
1516
1081
  newWay,
1517
1082
  demo,
1518
1083
  test,
@@ -1520,7 +1085,6 @@ const knowledgeModuleImpl = async ({
1520
1085
  errorHandler = defaultErrorHandler,
1521
1086
  process: processResults = defaultProcess,
1522
1087
  stopAtFirstFailure = true,
1523
- acceptsAdditionalConfig = false,
1524
1088
  ...rest
1525
1089
  } = {}) => {
1526
1090
  const unknownArgs = Object.keys(rest)
@@ -1533,10 +1097,28 @@ const knowledgeModuleImpl = async ({
1533
1097
  if (!moduleFromJSFile) {
1534
1098
  throw new Error("'module' is a required parameter. The value should be either 'module' or a lambda that will be called when the file is acting as a module.")
1535
1099
  }
1536
- // if (!config && !createConfig) {
1537
- if (!createConfig) {
1100
+
1101
+ if (!configStruct) {
1538
1102
  throw new Error("'config' or 'createConfig' is a required parameter. The value should the config that defines the knowledge module.")
1539
1103
  }
1104
+
1105
+ const createConfig = async () => {
1106
+ const config = new Config(configStruct, moduleFromJSFile)
1107
+ config.stop_auto_rebuild()
1108
+ await config.add(...(includes || []))
1109
+ if (api) {
1110
+ config.setApi(api())
1111
+ }
1112
+ if (multiApiInitializer) {
1113
+ await config.setMultiApi(multiApiInitializer)
1114
+ }
1115
+ if (initializer) {
1116
+ config.initializer(initializer)
1117
+ }
1118
+ await config.restart_auto_rebuild()
1119
+ return config
1120
+ }
1121
+
1540
1122
  if (!description) {
1541
1123
  throw new Error("'description' is a required parameter. The value should the description of the knowledge module.")
1542
1124
  }
@@ -1863,7 +1445,7 @@ const knowledgeModuleImpl = async ({
1863
1445
  config.config.rebuild = true
1864
1446
  }
1865
1447
  try {
1866
- await config.load(template.template, template.instance, { rebuild: needsRebuild.needsRebuild || options.rebuild, previousResultss: needsRebuild.previousResultss, startOfChanges: needsRebuild.startOfChanges })
1448
+ await config.load(rebuildTemplate, template.template, template.instance, { rebuild: needsRebuild.needsRebuild || options.rebuild, previousResultss: needsRebuild.previousResultss, startOfChanges: needsRebuild.startOfChanges })
1867
1449
  } catch (e) {
1868
1450
  console.error(`Error loading template for ${config.name}. ${e.error ? e.error : e}${e.stack ? e.stack : ''}`)
1869
1451
  runtime.process.exit(-1)
@@ -2114,6 +1696,8 @@ const knowledgeModuleImpl = async ({
2114
1696
  const initConfig = async (config) => {
2115
1697
  if (template) {
2116
1698
  if (config.needsRebuild(template.template, template.instance, { isModule: !isProcess }).needsRebuild) {
1699
+ debugger
1700
+ config.needsRebuild(template.template, template.instance, { isModule: !isProcess })
2117
1701
  const error = `This module "${config.name}" cannot be used because the instance file needs rebuilding. Run on the command line with no arguments or the -rt argument to rebuild.`
2118
1702
  throw new Error(error)
2119
1703
  }
@@ -2146,15 +1730,17 @@ const knowledgeModuleImpl = async ({
2146
1730
 
2147
1731
  if (template) {
2148
1732
  try {
2149
- await config.load(template.template, template.instance)
1733
+ await config.load(rebuildTemplate, template.template, template.instance)
2150
1734
  } catch (e) {
2151
1735
  errorHandler(e)
2152
1736
  }
2153
1737
  }
2154
1738
  }
2155
1739
 
1740
+ // no cache 21 minutes + rebuild fails "node tester_rebuild -m colors"
1741
+ // cache okay
2156
1742
  createConfigExport = async () => {
2157
- if (createConfig.cached) {
1743
+ if (false && createConfig.cached) {
2158
1744
  return createConfig.cached
2159
1745
  }
2160
1746
  const config = await createConfig()
@@ -2187,11 +1773,6 @@ const ensureTestFile = (module, name, type) => {
2187
1773
  }
2188
1774
  }
2189
1775
 
2190
- function w (func) {
2191
- func.where = where(3)
2192
- return func
2193
- }
2194
-
2195
1776
  const knowledgeModule = async (...args) => {
2196
1777
  await knowledgeModuleImpl(...args).catch((e) => {
2197
1778
  console.error(e)
@@ -2202,9 +1783,6 @@ const knowledgeModule = async (...args) => {
2202
1783
  module.exports = {
2203
1784
  process: _process,
2204
1785
  stableId,
2205
- where,
2206
- w,
2207
- // submitBug,
2208
1786
  ensureTestFile,
2209
1787
  rebuildTemplate,
2210
1788
  processContext,
package/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  const { Semantics, Semantic } = require('./src/semantics')
2
2
  const { Generators, Generator } = require('./src/generators')
3
3
  const { Config } = require('./src/config')
4
+ const { w, where } = require('./src/helpers')
4
5
  const Digraph = require('./src/digraph')
5
6
  const client = require('./client')
6
7
  const flattens = require('./src/flatten')
@@ -14,9 +15,9 @@ module.exports = {
14
15
  runTests: client.runTests,
15
16
  knowledgeModule: client.knowledgeModule,
16
17
  ensureTestFile: client.ensureTestFile,
17
- where: client.where,
18
+ where,
18
19
  stableId: client.stableId,
19
- w: client.w,
20
+ w,
20
21
  Config,
21
22
  Semantics,
22
23
  Semantic,
package/package.json CHANGED
@@ -64,6 +64,6 @@
64
64
  "sort-json": "^2.0.0",
65
65
  "uuid": "^8.3.2"
66
66
  },
67
- "version": "8.0.0-beta.41",
67
+ "version": "8.0.0-beta.43",
68
68
  "license": "UNLICENSED"
69
69
  }
package/src/config.js CHANGED
@@ -2,9 +2,10 @@
2
2
  const { Semantics, normalizeGenerator } = require('./semantics')
3
3
  const { Generators } = require('./generators')
4
4
  const { v4: uuidv4 } = require('uuid')
5
- const client = require('../client')
5
+ const configHelpers = require('./configHelpers')
6
6
  const DigraphInternal = require('./digraph_internal')
7
7
  const helpers = require('./helpers')
8
+ const { InitCalls } = require('./helpers')
8
9
  const { ecatch } = require('./helpers')
9
10
  const runtime = require('../runtime')
10
11
  const _ = require('lodash')
@@ -351,7 +352,7 @@ const handleBridgeProps = (config, bridge, { addFirst, uuid } = {}) => {
351
352
  const level = bridge.generatorp.level >= 0 ? bridge.generatorp.level : bridge.level + 1
352
353
 
353
354
  const generator = {
354
- where: bridge.generatorp.where || bridge.where || client.where(4),
355
+ where: bridge.generatorp.where || bridge.where || helpers.where(4),
355
356
  match: async (args) => bridge.id == args.context.marker && args.context.level == level && args.context.paraphrase && await match(args),
356
357
  apply: (args) => apply(args),
357
358
  applyWrapped: apply,
@@ -368,7 +369,7 @@ const handleBridgeProps = (config, bridge, { addFirst, uuid } = {}) => {
368
369
  const apply = typeof bridge.generatorr === 'function' ? bridge.generatorr : bridge.generatorr.apply || bridge.generatorr
369
370
  const level = bridge.generatorr.level >= 0 ? bridge.generatorr.level : bridge.level + 1
370
371
  const generator = {
371
- where: bridge.generatorr.where || bridge.where || client.where(4),
372
+ where: bridge.generatorr.where || bridge.where || helpers.where(4),
372
373
  match: async (args) => bridge.id == args.context.marker && args.context.level == level && !args.context.paraphrase && (args.context.response || args.context.isResponse) && await match(args),
373
374
  apply: (args) => apply(args),
374
375
  applyWrapped: apply,
@@ -382,7 +383,7 @@ const handleBridgeProps = (config, bridge, { addFirst, uuid } = {}) => {
382
383
  }
383
384
  if (bridge.evaluator) {
384
385
  const semantic = {
385
- where: bridge.evaluator.where || bridge.where || client.where(3),
386
+ where: bridge.evaluator.where || bridge.where || helpers.where(3),
386
387
  match: ({ context }) => bridge.id == context.marker && context.evaluate,
387
388
  apply: (args) => bridge.evaluator(args),
388
389
  applyWrapped: bridge.evaluator,
@@ -396,7 +397,7 @@ const handleBridgeProps = (config, bridge, { addFirst, uuid } = {}) => {
396
397
  }
397
398
  if (bridge.semantic) {
398
399
  const semantic = {
399
- where: bridge.semantic.where || bridge.where || client.where(3),
400
+ where: bridge.semantic.where || bridge.where || helpers.where(3),
400
401
  match: ({ context }) => bridge.id == context.marker && !context.evaluate,
401
402
  apply: (args) => bridge.semantic(args),
402
403
  applyWrapped: bridge.semantic,
@@ -990,21 +991,6 @@ class Config {
990
991
 
991
992
  // value is in response field
992
993
  // TODO maybe generalize out query+evaluate along the lines of set value and set reference
993
- /*
994
- getEvaluator (s, log, context) {
995
- const instance = s({ ...context, evaluate: true })
996
- if (!instance.evalue && !instance.verbatim && !instance.value) {
997
- this.warningNotEvaluated(log, context);
998
- }
999
- if (!instance.evalue) {
1000
- instance.evalue = instance.value
1001
- instance.edefault = true
1002
- }
1003
- delete instance.evaluate
1004
- instance.instance = true;
1005
- return instance
1006
- }
1007
- */
1008
994
  async getEvaluator (s, calls, log, context) {
1009
995
  const instance = await s({ ...context, evaluate: true })
1010
996
  calls.touch(instance)
@@ -1095,6 +1081,27 @@ class Config {
1095
1081
  } else {
1096
1082
  const config = { ...queryOrConfig }
1097
1083
  delete config.where
1084
+
1085
+ if (config.words && config.words.hierarchy) {
1086
+ config.words.hierarchy = config.words.hierarchy.map( (value) => {
1087
+ value = {...value}
1088
+ delete value.uuid
1089
+ return value
1090
+ })
1091
+ }
1092
+
1093
+ if (config.words && config.words.patterns) {
1094
+ config.words.patterns = config.words.patterns.map( (value) => {
1095
+ value = {...value}
1096
+ value.defs = value.defs.map( (value) => {
1097
+ value = {...value}
1098
+ delete value.uuid
1099
+ return value
1100
+ })
1101
+ return value
1102
+ })
1103
+ }
1104
+
1098
1105
  config.operators = (config.operators || []).map((operator) => {
1099
1106
  if (typeof operator === 'string') {
1100
1107
  return { pattern: operator }
@@ -1122,6 +1129,9 @@ class Config {
1122
1129
  delete bridge.generatorpr
1123
1130
  delete bridge.evaluator
1124
1131
  delete bridge.semantic
1132
+ if (!bridge.bridge) {
1133
+ bridge.bridge = "{ ...next(operator) }"
1134
+ }
1125
1135
  return bridge
1126
1136
  })
1127
1137
  } else {
@@ -1226,7 +1236,7 @@ class Config {
1226
1236
  }
1227
1237
 
1228
1238
  // loadTemplate
1229
- async load (template, instance, options = { rebuild: false, previousResultss: undefined, startOfChanges: undefined }) {
1239
+ async load (rebuildTemplate, template, instance, options = { rebuild: false, previousResultss: undefined, startOfChanges: undefined }) {
1230
1240
  this.validifyTemplate(template)
1231
1241
  instance.template = template
1232
1242
  this.logs.push(`loading template for ${this.name}`)
@@ -1234,7 +1244,7 @@ class Config {
1234
1244
  // TODO fix beforeQuery
1235
1245
  template = { fragments: [], configs: [], ...template }
1236
1246
  template.fragments = template.fragments.concat(this.dynamicFragments)
1237
- client.rebuildTemplate({ config: this, target: this.name, previousResultss: options.previousResultss, startOfChanges: options.startOfChanges, beforeQuery: () => {}, template, ...options })
1247
+ rebuildTemplate({ config: this, target: this.name, previousResultss: options.previousResultss, startOfChanges: options.startOfChanges, beforeQuery: () => {}, template, ...options })
1238
1248
  } else {
1239
1249
  // no change
1240
1250
  // this.initInstances.push({ ...instance, name: config.name })
@@ -1259,7 +1269,7 @@ class Config {
1259
1269
  instance.name = this.name
1260
1270
  this.initInstances.push(instance)
1261
1271
  this.instances.push(instance)
1262
- await client.loadInstance(this, instance)
1272
+ await configHelpers.loadInstance(this, instance)
1263
1273
  }
1264
1274
  }
1265
1275
  }
@@ -1408,7 +1418,7 @@ class Config {
1408
1418
  }
1409
1419
 
1410
1420
  if (!generator.where) {
1411
- generator.where = client.where(3)
1421
+ generator.where = helpers.where(3)
1412
1422
  }
1413
1423
 
1414
1424
  const generators = this.config.generators
@@ -1431,7 +1441,7 @@ class Config {
1431
1441
  }
1432
1442
 
1433
1443
  if (!semantic.where) {
1434
- semantic.where = client.where(3)
1444
+ semantic.where = helpers.where(3)
1435
1445
  }
1436
1446
 
1437
1447
  const semantics = this.config.semantics
@@ -1619,11 +1629,7 @@ class Config {
1619
1629
  }
1620
1630
 
1621
1631
  async processContext (context) {
1622
- return await client.processContext(context, this.getParams())
1623
- }
1624
-
1625
- process (query, options) {
1626
- return client.process(this, query, options)
1632
+ return await configHelpers.processContext(context, this.getParams())
1627
1633
  }
1628
1634
 
1629
1635
  query (query, options) {
@@ -2529,7 +2535,7 @@ class Config {
2529
2535
  }
2530
2536
  const instance = this.instances.find((instance) => instance.name == name)
2531
2537
  if (instance) {
2532
- await client.loadInstance(this, instance)
2538
+ await configHelpers.loadInstance(this, instance)
2533
2539
  }
2534
2540
  this.hierarchy.edges = this.config.hierarchy
2535
2541
  }
package/src/helpers.js CHANGED
@@ -1,6 +1,37 @@
1
1
  const deepEqual = require('deep-equal')
2
2
  const stringify = require('json-stable-stringify')
3
3
 
4
+ function where (goUp = 2) {
5
+ const e = new Error()
6
+ const regexForm1 = /\((.*):(\d+):(\d+)\)$/
7
+ const regexForm2 = /at (.*):(\d+):(\d+)$/
8
+ const lines = e.stack.split('\n')
9
+ let line
10
+ let match
11
+ for (line of lines.slice(1)) {
12
+ // if (!(line.includes('config.js:') || line.includes('client.js:') || line.includes('<anonymous>'))) {
13
+ if (!(line.includes('config.js:') || line.includes('client.js:'))) {
14
+ match = regexForm1.exec(line) || regexForm2.exec(line)
15
+ if (!match) {
16
+ continue
17
+ }
18
+ break
19
+ }
20
+ }
21
+ // const line = e.stack.split("\n")[goUp];
22
+ // const match = regexForm1.exec(line) || regexForm2.exec(line)
23
+ if (match) {
24
+ return `${match[1]}:${match[2]}`
25
+ } else {
26
+ return 'running in browser'
27
+ }
28
+ }
29
+
30
+ function w (func) {
31
+ func.where = where(3)
32
+ return func
33
+ }
34
+
4
35
  // properties - the properties that correspond to types
5
36
  // types - the expected types of the properties
6
37
  // returns list of properties found matching order of types
@@ -403,5 +434,7 @@ module.exports = {
403
434
  InitCalls,
404
435
  hashCode,
405
436
  sortJson,
406
- subPriority
437
+ subPriority,
438
+ where,
439
+ w,
407
440
  }
package/src/semantics.js CHANGED
@@ -49,76 +49,49 @@ class Semantic {
49
49
  }
50
50
  }
51
51
 
52
- async matches (baseArgs, context, options = {}) {
53
- const hierarchy = baseArgs.hierarchy
54
- const config = baseArgs.config
55
-
56
- const objects = baseArgs.getObjects(this.uuid)
57
- // const ask = baseArgs.getAsk(this.uuid)
58
-
59
- // return this.matcher(Object.assign({}, argsBase, {args: contextArgs(context, hierarchy), objects: objects, global: objects, context: context, hierarchy: hierarchy, api: this.getAPI(config)})
60
- const callId = baseArgs.calls.current()
61
- const moreArgs = {
62
- uuid: this.uuid,
63
- args: contextArgs(context, hierarchy),
64
- objects,
65
- global: objects,
66
- context: context,
67
- // hierarchy: hierarchy,
68
- callId,
69
- api: this.getAPI(config),
70
- apis: this.getAPIs(config)
52
+ fixUpArgs (args, context) {
53
+ args.uuid = this.uuid
54
+ args.callId = args.calls.current()
55
+ const objects = args.getObjects(this.uuid)
56
+ args.objects = objects
57
+ args.global = objects
58
+ const config = args.config
59
+ args.api = this.getAPI(config)
60
+ args.apis = this.getAPIs(config)
61
+ args.args = contextArgs(context, args.hierarchy)
62
+ args.context = context
63
+ let n = (id) => id
64
+ if (config && 'nsToString' in config) {
65
+ n = (id) => config.nsToString(id)
71
66
  }
72
- const args = Object.assign({}, baseArgs, moreArgs, (baseArgs.getUUIDScoped || (() => { return {} }))(this.uuid))
67
+ args.n = n
68
+ args.uuid = this.uuid
69
+ Object.assign(args, (args.getUUIDScoped || (() => { return {} }))(this.uuid))
70
+ }
73
71
 
72
+ async matches (args, context, options = {}) {
73
+ this.fixUpArgs(args, context)
74
74
  const matches = await this.matcher(args)
75
- if (matches && (options.debug || {}).match ||
76
- callId == this.callId) {
75
+ if (matches && (options.debug || {}).match || args.callId == this.callId) {
77
76
  debugger // next line is the matcher
78
77
  await this.matcher(args)
79
78
  }
80
79
  return matches
81
80
  }
82
81
 
83
- async apply (baseArgs, context, s, log, options = {}) {
84
- const { hierarchy, config, response } = baseArgs
85
- const objects = baseArgs.getObjects(this.uuid)
82
+ async apply (args, context, s, options = {}) {
83
+ const { config } = args
86
84
  if (config && config.debugLoops) {
87
85
  console.log('apply', this.toLabel())
88
86
  }
89
- if (baseArgs.calls && config && baseArgs.calls.stack.length > config.maxDepth) {
87
+ if (args.calls && config && args.calls.stack.length > config.maxDepth) {
90
88
  throw new Error(`Max depth of ${config.maxDepth} for calls has been exceeded. maxDepth can be set on the config object. To see the calls run with the --dl or set the debugLoops property on the config`)
91
89
  }
92
90
 
93
- // const ask = baseArgs.getAsk(this.uuid)
94
- if (!log) {
95
- console.trace()
96
- throw new Error('log is a required argument')
97
- }
98
91
  const contextPrime = Object.assign({}, context)
99
- let n = (id) => id
100
- if (config && 'nsToString' in config) {
101
- n = (id) => config.nsToString(id)
102
- }
103
- const callId = baseArgs.calls.current()
104
- const moreArgs = {
105
- uuid: this.uuid,
106
- callId,
107
- args: contextArgs(context, hierarchy),
108
- objects,
109
- log,
110
- global: objects,
111
- n,
112
- context: contextPrime,
113
- uuid: this.uuid,
114
- // config,
115
- response,
116
- api: this.getAPI(config),
117
- apis: this.getAPIs(config)
118
- }
119
- const args = Object.assign({}, baseArgs, moreArgs, (baseArgs.getUUIDScoped || (() => { return {} }))(this.uuid))
120
- if ((options.debug || {}).apply ||
121
- callId == this.callId) {
92
+ this.fixUpArgs(args, contextPrime)
93
+
94
+ if ((options.debug || {}).apply || args.callId == this.callId) {
122
95
  debugger
123
96
  }
124
97
  if (args.breakOnSemantics) {
@@ -181,6 +154,7 @@ class Semantics {
181
154
  if (!(context instanceof Array || context instanceof Object)) {
182
155
  return context
183
156
  }
157
+ args = { ...args }
184
158
  const config = args.config
185
159
  let contextPrime = Object.assign({}, context)
186
160
  const s = (context, options) => this.apply(args, context, options)
@@ -188,6 +162,8 @@ class Semantics {
188
162
  const stack = args.calls.push()
189
163
  let counter = 0
190
164
  let seenQuestion = false
165
+ const deferred = []
166
+ args.log = (message) => { this.logs.push(message) }
191
167
  for (const isemantic in this.semantics) {
192
168
  const semantic = this.semantics[isemantic]
193
169
  if (!semantic) {
@@ -202,17 +178,28 @@ class Semantics {
202
178
  this.calls[counter] = 0
203
179
  }
204
180
  this.calls[counter] += 1
205
- const log = (message) => { this.logs.push(message) }
206
181
  try {
207
- contextPrime = await semantic.apply(args, context, s, log, options)
182
+ let deferWasCalled = false
183
+ const defer = (listener) => {
184
+ deferred.push({ semantic, listener })
185
+ deferWasCalled = true
186
+ }
187
+ args.defer = defer
188
+ contextPrime = await semantic.apply(args, context, s, options)
189
+ if (deferWasCalled) {
190
+ continue
191
+ }
208
192
  if (!contextPrime.controlKeepMotivation && semantic.oneShot) {
209
193
  // semantic.tied_ids.forEach((tied_id) => args.config.removeSemantic(tied_id))
210
194
  args.config.removeSemantic(semantic)
211
195
  }
196
+ for (const { listener } of deferred) {
197
+ listener(args)
198
+ }
212
199
  } catch (e) {
213
200
  contextPrime = null
214
201
  let errorMessage
215
- e.retryCall = () => semantic.apply(args, context, s, log, options)
202
+ e.retryCall = () => semantic.apply(args, context, s, options)
216
203
  const help = 'The error has a retryCall property that will recall the function that failed.'
217
204
  if (e.stack && e.message) {
218
205
  const info = `${semantic.notes ? semantic.notes : ''}${semantic.where ? semantic.where : ''}`
@@ -280,6 +267,13 @@ class Semantics {
280
267
  lines.setElement(0, 1, 'RESULT')
281
268
  lines.setElement(0, 2, `(HASHCODE ${helpers.hashCode(JSON.stringify(helpers.sortJson(contextPrime, { depth: 25 })))})`)
282
269
  lines.setElement(1, 2, JSON.stringify(contextPrime, null, 2))
270
+ for (const { semantic } of deferred) {
271
+ lines.setElement(0, 1, 'DEFERRED')
272
+ lines.setElement(0, 2, semantic.toLabel())
273
+ lines.newRow()
274
+ lines.setElement(0, 2, semantic.toString())
275
+ lines.newRow()
276
+ }
283
277
  this.logs.push(lines.toString())
284
278
  }
285
279
  applied = true