react 0.2.4 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +146 -94
  2. package/doc/alternate-dsls.md +103 -0
  3. package/{lib → dsl}/chain.js +5 -3
  4. package/{lib → dsl}/fstr.js +17 -6
  5. package/{lib → dsl}/pcode.js +19 -8
  6. package/examples/chain-events1.js +28 -7
  7. package/examples/chain1.js +2 -2
  8. package/examples/default-events1.js +33 -6
  9. package/examples/default-log-events.js +43 -0
  10. package/examples/fstr-events1.js +4 -17
  11. package/examples/fstr1.js +3 -2
  12. package/examples/pcode1.js +2 -2
  13. package/lib/base-task.js +8 -6
  14. package/lib/cb-task.js +14 -1
  15. package/lib/core.js +46 -15
  16. package/lib/dsl.js +14 -6
  17. package/lib/event-manager.js +29 -15
  18. package/lib/finalcb-first-task.js +16 -10
  19. package/lib/finalcb-task.js +17 -10
  20. package/lib/input-parser.js +7 -3
  21. package/lib/log-events.js +71 -0
  22. package/lib/parse.js +6 -3
  23. package/lib/promise-task.js +89 -0
  24. package/lib/ret-task.js +1 -1
  25. package/lib/task.js +32 -23
  26. package/lib/track-tasks.js +117 -0
  27. package/lib/validate.js +14 -5
  28. package/lib/vcon.js +8 -3
  29. package/lib/when-task.js +81 -0
  30. package/package.json +4 -2
  31. package/promise-resolve.js +35 -0
  32. package/react.js +0 -4
  33. package/test/core-deferred.test.js +134 -0
  34. package/test/core-promised.test.js +132 -0
  35. package/test/core-when.test.js +84 -0
  36. package/test/core.test.js +108 -60
  37. package/test/dsl.test.js +58 -6
  38. package/test/{chain.test.js → dsl/chain.test.js} +85 -1
  39. package/test/{fstr.test.js → dsl/fstr.test.js} +13 -1
  40. package/test/{pcode.test.js → dsl/pcode.test.js} +128 -1
  41. package/test/exec-options.test.js +2 -1
  42. package/test/finalcb-task.test.js +6 -5
  43. package/test/input-parser.test.js +10 -6
  44. package/test/module-use.test.js +13 -199
  45. package/test/promise-auto-resolve.test.js +51 -0
  46. package/test/validate.test.js +30 -1
  47. package/test/vcon.test.js +13 -0
  48. package/oldExamples/analyze.js +0 -29
  49. package/oldExamples/analyze2.js +0 -29
  50. package/oldExamples/example10-dsl.js +0 -63
  51. package/oldExamples/example11.js +0 -62
  52. package/oldExamples/example12.js +0 -63
  53. package/oldExamples/example13.js +0 -63
  54. package/oldExamples/example14.js +0 -63
  55. package/oldExamples/example15.js +0 -75
  56. package/oldExamples/example6-ast.js +0 -47
  57. package/oldExamples/example6-dsl.js +0 -49
  58. package/oldExamples/example8-ast.js +0 -55
  59. package/oldExamples/example8-dsl.js +0 -53
  60. package/oldExamples/example9-ast.js +0 -58
  61. package/oldExamples/example9-dsl.js +0 -57
  62. package/oldExamples/function-str-ex1.js +0 -33
  63. package/oldExamples/function-str-ex2.js +0 -67
  64. package/oldExamples/trait1.js +0 -41
  65. package/oldExamples/trait2.js +0 -44
package/README.md CHANGED
@@ -1,13 +1,8 @@
1
1
  # React.js
2
2
 
3
- React is a javascript module to make it easier to work with asynchronous code,
4
- by reducing boilerplate code and improving error and exception handling while
5
- allowing variable and task dependencies when defining flow. This project is
6
- applying the concepts of Reactive programming or Dataflow to controlling
7
- application flow.
3
+ React is a javascript module to make it easier to work with asynchronous code, by reducing boilerplate code and improving error and exception handling while allowing variable and task dependencies when defining flow. This project is applying the concepts of Reactive programming or Dataflow to controlling application flow.
8
4
 
9
- This async flow control module is initially designed to work with Node.js but
10
- is planned to be extended to browser and other environments.
5
+ This async flow control module is initially designed to work with Node.js but is planned to be extended to browser and other environments.
11
6
 
12
7
  React gets its name from similarities with how "chain reactions" work in the physical world. You start the reaction and then it cascades and continues until complete.
13
8
 
@@ -40,8 +35,8 @@ It takes inspiration from several projects including:
40
35
  - object instance method calls
41
36
  - class method calls
42
37
  - selectFirst flow where the first task that returns defined, non-null value is used
43
- - (planned) promise style functions - also automatic resolution of promise inputs
44
- - (planned) use of resulting flow function as callback style or promise style (if no callback provided)
38
+ - promise style functions - also automatic resolution of promise inputs (optional require('react/promise-resolve');)
39
+ - use of resulting flow function as callback style or promise style (if no callback provided) (provided via plugin corresponding to the promise library used)
45
40
  - (planned) iteration on arrays, streams, sockets
46
41
  - (planned) event emitter integration
47
42
 
@@ -49,7 +44,8 @@ The tasks can be mixed, meaning you can use async, sync, object method calls, cl
49
44
 
50
45
  ## Concept
51
46
 
52
- Borrowing heavily from Tim and Elijah's ideas for conductor, this async flow control module provides a way to construct a flow from a collection of functions or methods (referred to as _tasks_ in this module). It allows dependencies to be defined between the tasks so they can run in parallel as their dependencies are satisfied. React can us both variable dependencies and task dependencies.
47
+ Borrowing heavily from Tim and Elijah's ideas for conductor, this async flow control module provides a way to construct a flow from a
48
+ collection of rules based on functions or methods (referred to as _tasks_ in this module). It allows dependencies to be defined between the tasks so they can run in parallel as their dependencies are satisfied. React can us both variable dependencies and task dependencies.
53
49
 
54
50
  As tasks complete, React watches the dependencies and kicks off additional tasks that have all their dependencies met and are ready to execute. This allows the flow to run at maximum speed without needing to arbitrarily block tasks into groups of parallel and serial flow.
55
51
 
@@ -57,11 +53,12 @@ To reduce the boilerplate code needed and improve error handling, React automati
57
53
 
58
54
  1. check for error and handle by calling outer callback function with this error after augmenting it with additional context information for easier debugging
59
55
  2. save the callback variables into a context for future reference
60
- 3. call back into React (and it will kick off additional tasks that are now ready to go)
56
+ 3. call back into React (and it will kick off additional tasks that are now ready to go)
57
+ 4. Using the dependencies specified for each
61
58
 
62
59
  ## Design
63
60
 
64
- - Parse and validate DSL rules at module load time
61
+ - Parse and validate DSL rules at module load time creating AST
65
62
  - Validate the flow AST at module load time - determine if dependencies can all be met as defined
66
63
  - Execute the flow AST by calling the function with arguments
67
64
 
@@ -75,11 +72,10 @@ Pull from github - http://github.com/jeffbski/react
75
72
 
76
73
  ## Examples
77
74
 
78
- 1. [Default DSL](#defaultDSL)
79
- 2. [Direct AST](#directAST)
80
- 3. [Using pseudocode DSL](#pcode)
81
- 4. [Using jquery-like chaining DSL](#chain)
75
+ 1. [Direct AST](#directAST)
76
+ 2. [Default DSL](#defaultDSL)
82
77
 
78
+ ### Example using the default DSL
83
79
 
84
80
  These live in the examples folder so they are ready to run.
85
81
  Also see test/module-use.test.js for more examples as well
@@ -153,96 +149,148 @@ fn('foo', 'pre-', '-post', function cb(err, lres) {
153
149
  });
154
150
  ```
155
151
 
156
- <a name="fstr"/>
157
- ### Example using Function String DSL interface
152
+ ### Alternate interfaces (DSL's)
153
+
154
+ 1. [Using pseudocode DSL](http://github.com/jeffbski/react/raw/master/doc/alternate-dsls.md#pcode)
155
+ 2. [Using jquery-like chaining DSL](http://github.com/jeffbski/react/raw/master/doc/alternate-dsls.md#chain)
156
+ 3. [Using function string DSL](http://github.com/jeffbski/react/raw/master/doc/alternate-dsls.md#fstr)
157
+
158
+
159
+ ## User API
160
+
161
+ ### Default DSL
162
+
163
+ The main function returned from require('react') can be used to define the AST used for the processing of the rules or flow.
164
+
165
+ It takes the following arguments to define a flow function:
158
166
 
159
167
  ```javascript
160
168
  var react = require('react');
169
+ var fn = react('my-flow-name', 'paramName1, paramName2, cb -> err, outParamName1, outParamName2',
170
+ functionRefOrMethodStr, 'paramName1, cb -> err, outParamName2', // async cb task
171
+ functionRefOrMethodStr2, 'paramName2, paramName1 -> outParamName1' // sync task
172
+ );
173
+ ```
161
174
 
162
- function loadUser(uid, cb){ setTimeout(cb, 100, null, "User"+uid); }
163
- function loadFile(filename, cb){ setTimeout(cb, 100, null, 'Filedata'+filename); }
164
- function markdown(filedata) { return 'html'+filedata; }
165
- function prepareDirectory(outDirname, cb){ setTimeout(cb, 200, null, 'dircreated-'+outDirname); }
166
- function writeOutput(html, user, cb){ setTimeout(cb, 300, null, html+'_bytesWritten'); }
167
- function loadEmailTemplate(cb) { setTimeout(cb, 50, null, 'emailmd'); }
168
- function customizeEmail(user, emailHtml, cb) { return 'cust-'+user+emailHtml; }
169
- function deliverEmail(custEmailHtml, cb) { setTimeout(cb, 100, null, 'delivered-'+custEmailHtml); }
170
-
171
- function useHtml(err, html, user, bytesWritten) {
172
- if(err) {
173
- console.log('***Error: %s', err);
174
- return;
175
- }
176
- console.log('final result: %s, user: %s, written:%s', html, user, bytesWritten);
177
- }
175
+ 1. **flow/function name** - string - represents the name of the flow or function that will be created. React will use the name when generating events so you can monitor progress and performance and also when errors occur.
176
+ 2. **in/out flow parameter definition** - string - the inputs and outputs for the flow function. The parameters are specified in one single string for easy typing, separated by commas. The output follows the input after being separated by a `->`. Use the parameter name `cb` or `callback` to specify the Node style callback and `err` to represent the error parameter as the first output parameter of the callback. Literal values can also be specified directly (true, false, numbers, this, null). Literal strings can simply be quoted using single or double quotes.
177
+ 3. **optional flow options** - object - If an object is provided immediately after the in/out flow def, then these options will be provided to react to customize the flow. This is reserved for future use.
178
+ 3. **function reference or method string** - Specify the function to be called for this task, or if calling a method off of an object being passed in or returned by a task, use a string to specify like `'obj.method'`. These can be asynchronous Node-style callback `cb(err, ...)` functions or synchronous functions which simply return values directly.
179
+ 4. **in/out task parameter definition** - string - similar to the in/out flow parameter definition above, these are the inputs and outputs that are passed to a task function and returned from a task function. The inputs will need to match either those from the flow inputs or outputs from other tasks that will run before this task. React will use the inputs as dependencies, so it will invoke and wait for response from the tasks that provide the dependent inputs. So simply by specifying inputs and outputs for the tasks, React will prioritize and parallelize tasks to run as fast as possible. Use `cb` or `callback` along with `err` to specify asynchronous Node style `cb(err, ...)` task, or omit both to specify a synchronous task.A synchronous task can only have a single return parameter.
180
+ 5. **optional task options** - object - if an object is provided this can be used to specify additional options for this task. Currently the valid options for a task are:
181
+ - **name** - string - specifies a name for a task, otherwise React will try to use the function name or method string if it is unique in the flow. If a name is not unique subsequent tasks will have `_index` (zero based index of the task) added to create unique name. If you specify a name, you will also want to indicate a unique name for within the flow otherwise it will get a suffix as well. Example: `{ name: 'myTaskName' }`
182
+ - **after** - string, function reference, or array of string or function refs - specify additional preconditions that need to be complete before this task can run. In addition to the input dependencies being met, wait for these named tasks to complete before running. The preconditions are specified using the name of the task or if the task function was only used once and is a named function (not anonymous), you can just provide the function reference and it will determine name from it. Example: `{ after: 'foo' }` or `{ after: ['foo', 'bar'] }`
183
+ 6. **repeat 3-5** - repeat steps 3-5 to specify additional tasks in this flow. As dependencies are met for tasks, React will invoke additional tasks that are ready to run in the order they are defined in this flow definition. So while the order does have some influence on the execution, it is primarily defined by the input dependencies and any other additonal preconditions specified with the `after` option. If you want to guarantee that something only runs after something else completes, then it will need to use an output from that task or specify the dependency with an `after`.
184
+
185
+
186
+ The flow function created by react from the input definition is a normal Node-style function which can be used like any other. These flow functions can be defined in a module and exported, they can be passed into other functions, used as methods on objects (the `this` context is passed in and available).
178
187
 
179
- var loadAndSave = react.fstrDefine('filename, uid, outDirname, cb', [ // input params
180
- loadUser, 'uid -> err, user', // calling async fn loadUser with uid, callback is called with err and user
181
- loadFile, 'filename -> err, filedata',
182
- markdown, 'filedata -> returns html', // using a sync function
183
- prepareDirectory, 'outDirname -> err, dircreated',
184
- writeOutput, 'html, user -> err, bytesWritten', { after: prepareDirectory }, // only after prepareDirectory done
185
- loadEmailTemplate, ' -> err, emailmd',
186
- markdown, 'emailmd -> returns emailHtml', // using a sync function
187
- customizeEmail, 'user, emailHtml -> returns custEmailHtml',
188
- deliverEmail, 'custEmailHtml -> err, deliveredEmail', { after: writeOutput } // only after writeOutput is done
189
- ], 'err, html, user, bytesWritten'); // callback output params
190
-
191
- loadAndSave('file.md', 100, '/tmp/foo', useHtml); // executing the flow
192
- ```
193
188
 
194
- <a name="pcode"/>
195
- ### Example using pseudocode DSL interface
189
+ ### AST
190
+
191
+ The abstract syntax tree or AST provided by React represents the data necessary to define the flow. By abstracting this from the DSL, it allows new skins or interfaces to be developed without need to change the core engine.
192
+
193
+ The AST is normally created at parse time when the React main function is called (or one of the alternate DSL's is called). This can be done a module load time such that after loading the React defined flow function's AST is generated and ready to process eliminating parsing and validation overhead when it is invoked in the future. This has the added advantage that since validation has also been performed that additional syntax issues or incomplete flow defintion errors can be caught quickly.
194
+
195
+ After the flow function has been created, you can review the generated AST for a function by accessing the ast.
196
196
 
197
197
  ```javascript
198
198
  var react = require('react');
199
+ var fn = react('my-flow-name', 'paramName1, paramName2, cb -> err, outParamName1, outParamName2',
200
+ functionRefOrMethodStr, 'paramName1, cb -> err, outParamName2', // async cb task
201
+ functionRefOrMethodStr2, 'paramName2, paramName1 -> outParamName1' // sync task
202
+ );
199
203
 
200
- function multiply(a, b, cb) { cb(null, a * b); }
201
- function add(a, b) { return a + b; }
202
- var locals = { // since pcodeDefine uses strings, need references to functions passed into react
203
- multiply: multiply,
204
- add: add
205
- };
206
-
207
- var fn = react.pcodeDefine('a, b, cb', [ // input params
208
- 'm := multiply(a, b)', // using a callback function, use :=
209
- 's = add(m, a)', // using a sync function, use =
210
- 'cb(err, m, s)' // output params for final callback
211
- ], locals); // hash of functions that will be used
212
-
213
- fn(2, 3, function (err, m, s) {
214
- console.error('err:', err); // null
215
- console.error('m:', m); // 2 * 3 = 6
216
- console.error('s:', s); // 6 + 2 = 8
217
- });
204
+ console.error(fn.ast); // output the generated AST
218
205
  ```
219
206
 
220
- <a name="chain"/>
221
- ### Example using jquery-like chaining DSL interface
207
+ The AST contains the following pieces:
222
208
 
223
209
  ```javascript
224
- var react = require('react');
210
+ var ast = {
211
+ name: flowName,
212
+ inParams: [],
213
+ tasks: [],
214
+ outTask: {},
215
+ locals: {}
216
+ };
217
+ ```
218
+ - **name** - string - represents the name of the flow or function that will be created. React will use the name when generating events so you can monitor progress and performance and also when errors occur.
219
+ - **inParams** - array of strings - the flow input parameter names (excluding the callback param)
220
+ - **tasks** - array of task defintion objects - each containing:
221
+ - **f** - function reference or method string - async or sync function to be used for this task
222
+ - **a** - array of input parameter names (excluding the callback param)
223
+ - **out** - array of output parameter names (excluding the err parame)
224
+ - **type** - type of function determining how function is invoked and its output style - one of: ('cb', 'ret', 'promise', 'when')
225
+ - **name** - string - unique name for each task provided or generated by React
226
+ - **outTask** - task definition object specifying the flow's output style and parameters containing:
227
+ - **f** - will contain reference to the callback function at runtime
228
+ - **a** - parameters being passed as output from the flow
229
+ - **locals** - object provided which contains additional values that will become part of the React variable space like input parameters but can be defined in advance at flow definition. This can be used to provide functions and objects to React enabling string based DSL's like the pcode DSL can be utilized.
225
230
 
226
- function multiply(a, b, cb) { cb(null, a * b); }
227
- function add(a, b) { return a + b; }
228
231
 
229
- var fn = react.chainDefine()
230
- .in('a', 'b', 'cb') // input params
231
- .out('err', 'm', 's') // final callback output params
232
- .async(multiply).in('a', 'b', 'cb').out('err', 'm') // task def - async fn, in params, callback out params
233
- .sync(add).in('m', 'a').out('s') // task def - sync fn, in params, return value
234
- .end();
232
+ ### Plugins (optional requires which turn on additional functionality)
235
233
 
236
- fn(2, 3, function (err, m, s) {
237
- console.error('err:', err); // null
238
- console.error('m:', m); // 2 * 3 = 6
239
- console.error('s:', s); // 6 + 2 = 8
240
- });
234
+ Additional functionality which is not enabled by default but available by requiring additional modules.
235
+
236
+
237
+ #### LogEvents - log react progress to stderr
238
+
239
+ For convenience in debugging or in monitoring flow and performance, React has a built-in plugin for easily logging progress to stderr which is activiated by requiring it and specifying a particular flow function to log or use the main react for global logging of all react modules.
240
+
241
+ ```javascript
242
+ require('react/lib/log-events').logEvents(react); // turn on logging for all react functions
243
+
244
+ // OR
245
+
246
+ require('react/lib/log-events').logEvents(myReactFn); // turn on logging for a specific function, repeat for other functions as needed
247
+ ```
248
+
249
+ #### Automatic Promise Resolution for inputs
250
+
251
+ If you want to automatically resolve promises in React without having to manually call `when` or `then`, React provides a plugin which will detect the existence of a `then` method (indicating a promise) at runtime from any inputs to the flow and will internally create `when` tasks to resolve them before passing the values to other tasks.
252
+
253
+ ```javascript
254
+ require('react/promise-resolve');
255
+ ```
256
+
257
+ #### Track tasks
258
+
259
+ Instead of only logging events to stderr (like LogEvents), this plugin fires events that can be directly monitored. The LogEvent plugin uses this internally to get access to the metrics.
260
+
261
+ It also provides a simple accumulator which can be used to accumulate events. Note that this accumulator is designed for short term debug use, as it will continue to accumulate events and does not have any size restrictions.
262
+
263
+ Thus while the tracking can be used in production because it simply fires events, the accumulator should only be used for convenience in debugging and testing.
264
+
265
+ ```javascript
266
+ require('react/lib/track-tasks'); // enable tracking and events
267
+
268
+ // if you want to use the accumulator
269
+
270
+ var EventCollector = require('react/lib/track-tasks').EventCollector;
271
+ var collector = new EventCollector();
272
+
273
+ collector.captureGlobal('*'); // capture all react events for all flows
274
+
275
+ // OR
276
+
277
+ collector.capture(flowFn, 'task.'); // capture task events on a flow
278
+ collector.capture(flowFn, 'flow.'); // add capture flow events on a flow
279
+
280
+ var events = collector.list(); // retrieve the list of events
241
281
  ```
242
282
 
283
+ #### Alternate DSL's
284
+
285
+ Additional DSL's can be loaded by requiring them. See the [Alternate DSL](http://github.com/jeffbski/react/raw/master/doc/alternate-dsls.md) page for more info.
286
+
287
+
243
288
  ## Status
244
289
 
245
- - 2012-01-11 - Provide warning/error when name is skipped in default DSL (v0.2.4)
290
+ - 2012-01-17 - Additional documentation (v0.3.4)
291
+ - 2012-01-16 - Refine events and create logging plugin (v0.3.3)
292
+ - 2012-01-13 - Add promise tasks, promise resolution, refactor alternate DSL interfaces as optional requires (v0.3.0)
293
+ - 2012-01-11 - Provide warning/error when name is skipped in default DSL, literal check in validate (v0.2.5)
246
294
  - 2012-01-10 - Create default DSL for react(), create error for missing variables, list remaining tasks when flow won't complete
247
295
  - 2011-12-21 - Refactor from ground up with tests, changes to the interfaces
248
296
  - 2011-10-26 - React is in active development and interface may change frequently in these early stages. Current code is functional but does not perform validation yet. Additional interfaces are planned to make it easy to define flows in a variety of ways. Documentation and examples forthcoming.
@@ -252,23 +300,27 @@ fn(2, 3, function (err, m, s) {
252
300
  ```bash
253
301
  ok ast.test.js .................... 10/10
254
302
  ok cb-task.test.js ................ 31/31
255
- ok chain.test.js .................. 56/56
256
- ok core.test.js ................... 98/98
257
- ok dsl.test.js .................... 58/58
303
+ ok core-deferred.test.js .......... 11/11
304
+ ok core-promised.test.js .......... 11/11
305
+ ok core-when.test.js ................ 6/6
306
+ ok core.test.js ................. 104/104
307
+ ok chain.test.js .................. 74/74
308
+ ok fstr.test.js ................... 67/67
309
+ ok pcode.test.js .................. 94/94
310
+ ok dsl.test.js .................... 70/70
258
311
  ok event-manager.test.js .......... 13/13
259
312
  ok exec-options.test.js ............. 3/3
260
313
  ok finalcb-task.test.js ............. 5/5
261
- ok fstr.test.js ................... 64/64
262
314
  ok input-parser.test.js ........... 15/15
263
- ok module-use.test.js ............. 64/64
264
- ok pcode.test.js .................. 65/65
315
+ ok module-use.test.js ............. 21/21
316
+ ok promise-auto-resolve.test.js ..... 4/4
265
317
  ok ret-task.test.js ............... 31/31
266
318
  ok task.test.js ..................... 1/1
267
319
  ok validate-cb-task.test.js ......... 6/6
268
320
  ok validate-ret-task.test.js ........ 7/7
269
- ok validate.test.js ............... 26/26
270
- ok vcon.test.js ................... 42/42
271
- total ........................... 613/613
321
+ ok validate.test.js ............... 31/31
322
+ ok vcon.test.js ................... 55/55
323
+ total ........................... 692/692
272
324
 
273
325
  ok
274
326
  ```
@@ -0,0 +1,103 @@
1
+ # Alternate DSL's
2
+
3
+ These DSL's are not loaded by default and thus require a separate require if you want to use one.
4
+
5
+ Since React is an AST based rules system, it allows custom DSL's to be created easily, they only need to generate the AST and they are fully functional, allowing many different interfaces for the same system.
6
+
7
+
8
+ ### Examples using the AST directly or alternate DSL's
9
+
10
+
11
+ 1. [Using pseudocode DSL](#pcode)
12
+ 2. [Using jquery-like chaining DSL](#chain)
13
+ 3. [Function String DSL](#fstr) (Deprecated)
14
+
15
+
16
+ <a name="pcode"/>
17
+ ### Example using pseudocode DSL interface
18
+
19
+ ```javascript
20
+ var pcodeDefine = require('react/dsl/pcode');
21
+
22
+ function multiply(a, b, cb) { cb(null, a * b); }
23
+ function add(a, b) { return a + b; }
24
+ var locals = { // since pcodeDefine uses strings, need references to functions passed into react
25
+ multiply: multiply,
26
+ add: add
27
+ };
28
+
29
+ var fn = pcodeDefine('a, b, cb', [ // input params
30
+ 'm := multiply(a, b)', // using a callback function, use :=
31
+ 's = add(m, a)', // using a sync function, use =
32
+ 'cb(err, m, s)' // output params for final callback
33
+ ], locals); // hash of functions that will be used
34
+
35
+ fn(2, 3, function (err, m, s) {
36
+ console.error('err:', err); // null
37
+ console.error('m:', m); // 2 * 3 = 6
38
+ console.error('s:', s); // 6 + 2 = 8
39
+ });
40
+ ```
41
+
42
+ <a name="chain"/>
43
+ ### Example using jquery-like chaining DSL interface
44
+
45
+ ```javascript
46
+ var chainDefine = require('react/dsl/chain');
47
+
48
+ function multiply(a, b, cb) { cb(null, a * b); }
49
+ function add(a, b) { return a + b; }
50
+
51
+ var fn = chainDefine()
52
+ .in('a', 'b', 'cb') // input params
53
+ .out('err', 'm', 's') // final callback output params
54
+ .async(multiply).in('a', 'b', 'cb').out('err', 'm') // task def - async fn, in params, callback out params
55
+ .sync(add).in('m', 'a').out('s') // task def - sync fn, in params, return value
56
+ .end();
57
+
58
+ fn(2, 3, function (err, m, s) {
59
+ console.error('err:', err); // null
60
+ console.error('m:', m); // 2 * 3 = 6
61
+ console.error('s:', s); // 6 + 2 = 8
62
+ });
63
+ ```
64
+
65
+ <a name="fstr"/>
66
+ ### Example using Function String DSL interface
67
+
68
+ The Function String DSL interface is deprecated since it morphed into the default DSL which is very similar. It is recommended that you use the default DSL instead.
69
+
70
+ ```javascript
71
+ var fstrDefine = require('react/dsl/fstr');
72
+
73
+ function loadUser(uid, cb){ setTimeout(cb, 100, null, "User"+uid); }
74
+ function loadFile(filename, cb){ setTimeout(cb, 100, null, 'Filedata'+filename); }
75
+ function markdown(filedata) { return 'html'+filedata; }
76
+ function prepareDirectory(outDirname, cb){ setTimeout(cb, 200, null, 'dircreated-'+outDirname); }
77
+ function writeOutput(html, user, cb){ setTimeout(cb, 300, null, html+'_bytesWritten'); }
78
+ function loadEmailTemplate(cb) { setTimeout(cb, 50, null, 'emailmd'); }
79
+ function customizeEmail(user, emailHtml, cb) { return 'cust-'+user+emailHtml; }
80
+ function deliverEmail(custEmailHtml, cb) { setTimeout(cb, 100, null, 'delivered-'+custEmailHtml); }
81
+
82
+ function useHtml(err, html, user, bytesWritten) {
83
+ if(err) {
84
+ console.log('***Error: %s', err);
85
+ return;
86
+ }
87
+ console.log('final result: %s, user: %s, written:%s', html, user, bytesWritten);
88
+ }
89
+
90
+ var loadAndSave = fstrDefine('filename, uid, outDirname, cb', [ // input params
91
+ loadUser, 'uid -> err, user', // calling async fn loadUser with uid, callback is called with err and user
92
+ loadFile, 'filename -> err, filedata',
93
+ markdown, 'filedata -> returns html', // using a sync function
94
+ prepareDirectory, 'outDirname -> err, dircreated',
95
+ writeOutput, 'html, user -> err, bytesWritten', { after: prepareDirectory }, // only after prepareDirectory done
96
+ loadEmailTemplate, ' -> err, emailmd',
97
+ markdown, 'emailmd -> returns emailHtml', // using a sync function
98
+ customizeEmail, 'user, emailHtml -> returns custEmailHtml',
99
+ deliverEmail, 'custEmailHtml -> err, deliveredEmail', { after: writeOutput } // only after writeOutput is done
100
+ ], 'err, html, user, bytesWritten'); // callback output params
101
+
102
+ loadAndSave('file.md', 100, '/tmp/foo', useHtml); // executing the flow
103
+ ```
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  var sprintf = require('sprintf').sprintf;
4
- var core = require('./core.js');
5
- var tutil = require('./task.js');
4
+ var core = require('../lib/core.js');
5
+ var tutil = require('../lib/task.js');
6
6
 
7
7
  // err for task type cb is implied and thus optional, but allow for clarity.
8
8
  var ERROR_NAMES_RE = /^err$/i; // first out param matching this is skipped as being the err object
@@ -145,4 +145,6 @@ FlowBuilder.prototype.end = function end() {
145
145
  return reactFn;
146
146
  };
147
147
 
148
- module.exports = chainDefine;
148
+ module.exports = chainDefine;
149
+ module.exports.options = core.options;
150
+ module.exports.events = core.events;
@@ -1,23 +1,32 @@
1
1
  'use strict';
2
+ /*jshint regexp: false */
2
3
 
3
4
  var sprintf = require('sprintf').sprintf;
4
- var core = require('./core.js');
5
- var parse = require('./parse.js');
6
- var tutil = require('./task.js');
5
+ var core = require('../lib/core.js');
6
+ var parse = require('../lib/parse.js');
7
+ var tutil = require('../lib/task.js');
7
8
 
8
9
  var INPARAMS_NO_MATCH = 'input params in wrong format, wanted "foo, bar" - found: %s';
9
10
  var OUTPARAMS_NO_MATCH = 'output params in wrong format, wanted "foo, bar" - found: %s';
10
11
  var INOUT_PARAMS_NO_MATCH = 'task params in wrong format, wanted "foo, bar -> err, baz" - found: %s';
11
12
  var EXTRA_TASKARG = 'extra unmatched task arg: %s';
12
13
 
14
+ var ERR_NAMES_RE = /^err$/i; // err, ERR, Err, ...
15
+
16
+ function filterOutLeadingErrParam(args) { // if leading err param, filter it out
17
+ if (args.length && args[0].match(ERR_NAMES_RE)) args.shift();
18
+ return args;
19
+ }
20
+
21
+
13
22
  var inOutDefParse = {
14
- regex: /^([^-]*)(->)?\s*(er{0,2}\s*,|returns?\s+)?(.*)$/i,
23
+ regex: /^([^\-]*)(->)?\s*(returns?\s+)?(.*)$/i, //TODO this will not work if literal has dash
15
24
  fn: function (m) {
16
25
  var reMatchReturns = /returns?/i;
17
26
  return {
18
27
  type: (m[3] && m[3].match(reMatchReturns)) ? 'ret' : 'cb',
19
28
  inDef: parse.splitTrimFilterArgs(m[1]),
20
- outDef: parse.splitTrimFilterArgs(m[4])
29
+ outDef: filterOutLeadingErrParam(parse.splitTrimFilterArgs(m[4]))
21
30
  };
22
31
  }
23
32
  };
@@ -107,4 +116,6 @@ function selectFirst(inParamStr, taskDefArr, outParamStr, options) {
107
116
  }
108
117
 
109
118
  module.exports = fstrDefine;
110
- module.exports.selectFirst = selectFirst;
119
+ module.exports.selectFirst = selectFirst;
120
+ module.exports.options = core.options;
121
+ module.exports.events = core.events;