No Description

oboe-browser.js 81KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704
  1. // This file is the concatenation of many js files.
  2. // See http://github.com/jimhigson/oboe.js for the raw source
  3. // having a local undefined, window, Object etc allows slightly better minification:
  4. (function (window, Object, Array, Error, JSON, undefined ) {
  5. // v2.1.1-1-gb70a959
  6. /*
  7. Copyright (c) 2013, Jim Higson
  8. All rights reserved.
  9. Redistribution and use in source and binary forms, with or without
  10. modification, are permitted provided that the following conditions are
  11. met:
  12. 1. Redistributions of source code must retain the above copyright
  13. notice, this list of conditions and the following disclaimer.
  14. 2. Redistributions in binary form must reproduce the above copyright
  15. notice, this list of conditions and the following disclaimer in the
  16. documentation and/or other materials provided with the distribution.
  17. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  18. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  19. TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  20. PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21. HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
  23. TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  24. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  25. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  26. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. /**
  30. * Partially complete a function.
  31. *
  32. * var add3 = partialComplete( function add(a,b){return a+b}, 3 );
  33. *
  34. * add3(4) // gives 7
  35. *
  36. * function wrap(left, right, cen){return left + " " + cen + " " + right;}
  37. *
  38. * var pirateGreeting = partialComplete( wrap , "I'm", ", a mighty pirate!" );
  39. *
  40. * pirateGreeting("Guybrush Threepwood");
  41. * // gives "I'm Guybrush Threepwood, a mighty pirate!"
  42. */
  43. var partialComplete = varArgs(function( fn, args ) {
  44. // this isn't the shortest way to write this but it does
  45. // avoid creating a new array each time to pass to fn.apply,
  46. // otherwise could just call boundArgs.concat(callArgs)
  47. var numBoundArgs = args.length;
  48. return varArgs(function( callArgs ) {
  49. for (var i = 0; i < callArgs.length; i++) {
  50. args[numBoundArgs + i] = callArgs[i];
  51. }
  52. args.length = numBoundArgs + callArgs.length;
  53. return fn.apply(this, args);
  54. });
  55. }),
  56. /**
  57. * Compose zero or more functions:
  58. *
  59. * compose(f1, f2, f3)(x) = f1(f2(f3(x))))
  60. *
  61. * The last (inner-most) function may take more than one parameter:
  62. *
  63. * compose(f1, f2, f3)(x,y) = f1(f2(f3(x,y))))
  64. */
  65. compose = varArgs(function(fns) {
  66. var fnsList = arrayAsList(fns);
  67. function next(params, curFn) {
  68. return [apply(params, curFn)];
  69. }
  70. return varArgs(function(startParams){
  71. return foldR(next, startParams, fnsList)[0];
  72. });
  73. });
  74. /**
  75. * A more optimised version of compose that takes exactly two functions
  76. * @param f1
  77. * @param f2
  78. */
  79. function compose2(f1, f2){
  80. return function(){
  81. return f1.call(this,f2.apply(this,arguments));
  82. }
  83. }
  84. /**
  85. * Generic form for a function to get a property from an object
  86. *
  87. * var o = {
  88. * foo:'bar'
  89. * }
  90. *
  91. * var getFoo = attr('foo')
  92. *
  93. * fetFoo(o) // returns 'bar'
  94. *
  95. * @param {String} key the property name
  96. */
  97. function attr(key) {
  98. return function(o) { return o[key]; };
  99. }
  100. /**
  101. * Call a list of functions with the same args until one returns a
  102. * truthy result. Similar to the || operator.
  103. *
  104. * So:
  105. * lazyUnion([f1,f2,f3 ... fn])( p1, p2 ... pn )
  106. *
  107. * Is equivalent to:
  108. * apply([p1, p2 ... pn], f1) ||
  109. * apply([p1, p2 ... pn], f2) ||
  110. * apply([p1, p2 ... pn], f3) ... apply(fn, [p1, p2 ... pn])
  111. *
  112. * @returns the first return value that is given that is truthy.
  113. */
  114. var lazyUnion = varArgs(function(fns) {
  115. return varArgs(function(params){
  116. var maybeValue;
  117. for (var i = 0; i < len(fns); i++) {
  118. maybeValue = apply(params, fns[i]);
  119. if( maybeValue ) {
  120. return maybeValue;
  121. }
  122. }
  123. });
  124. });
  125. /**
  126. * This file declares various pieces of functional programming.
  127. *
  128. * This isn't a general purpose functional library, to keep things small it
  129. * has just the parts useful for Oboe.js.
  130. */
  131. /**
  132. * Call a single function with the given arguments array.
  133. * Basically, a functional-style version of the OO-style Function#apply for
  134. * when we don't care about the context ('this') of the call.
  135. *
  136. * The order of arguments allows partial completion of the arguments array
  137. */
  138. function apply(args, fn) {
  139. return fn.apply(undefined, args);
  140. }
  141. /**
  142. * Define variable argument functions but cut out all that tedious messing about
  143. * with the arguments object. Delivers the variable-length part of the arguments
  144. * list as an array.
  145. *
  146. * Eg:
  147. *
  148. * var myFunction = varArgs(
  149. * function( fixedArgument, otherFixedArgument, variableNumberOfArguments ){
  150. * console.log( variableNumberOfArguments );
  151. * }
  152. * )
  153. *
  154. * myFunction('a', 'b', 1, 2, 3); // logs [1,2,3]
  155. *
  156. * var myOtherFunction = varArgs(function( variableNumberOfArguments ){
  157. * console.log( variableNumberOfArguments );
  158. * })
  159. *
  160. * myFunction(1, 2, 3); // logs [1,2,3]
  161. *
  162. */
  163. function varArgs(fn){
  164. var numberOfFixedArguments = fn.length -1,
  165. slice = Array.prototype.slice;
  166. if( numberOfFixedArguments == 0 ) {
  167. // an optimised case for when there are no fixed args:
  168. return function(){
  169. return fn.call(this, slice.call(arguments));
  170. }
  171. } else if( numberOfFixedArguments == 1 ) {
  172. // an optimised case for when there are is one fixed args:
  173. return function(){
  174. return fn.call(this, arguments[0], slice.call(arguments, 1));
  175. }
  176. }
  177. // general case
  178. // we know how many arguments fn will always take. Create a
  179. // fixed-size array to hold that many, to be re-used on
  180. // every call to the returned function
  181. var argsHolder = Array(fn.length);
  182. return function(){
  183. for (var i = 0; i < numberOfFixedArguments; i++) {
  184. argsHolder[i] = arguments[i];
  185. }
  186. argsHolder[numberOfFixedArguments] =
  187. slice.call(arguments, numberOfFixedArguments);
  188. return fn.apply( this, argsHolder);
  189. }
  190. }
  191. /**
  192. * Swap the order of parameters to a binary function
  193. *
  194. * A bit like this flip: http://zvon.org/other/haskell/Outputprelude/flip_f.html
  195. */
  196. function flip(fn){
  197. return function(a, b){
  198. return fn(b,a);
  199. }
  200. }
  201. /**
  202. * Create a function which is the intersection of two other functions.
  203. *
  204. * Like the && operator, if the first is truthy, the second is never called,
  205. * otherwise the return value from the second is returned.
  206. */
  207. function lazyIntersection(fn1, fn2) {
  208. return function (param) {
  209. return fn1(param) && fn2(param);
  210. };
  211. }
  212. /**
  213. * A function which does nothing
  214. */
  215. function noop(){}
  216. /**
  217. * A function which is always happy
  218. */
  219. function always(){return true}
  220. /**
  221. * Create a function which always returns the same
  222. * value
  223. *
  224. * var return3 = functor(3);
  225. *
  226. * return3() // gives 3
  227. * return3() // still gives 3
  228. * return3() // will always give 3
  229. */
  230. function functor(val){
  231. return function(){
  232. return val;
  233. }
  234. }
  235. /**
  236. * This file defines some loosely associated syntactic sugar for
  237. * Javascript programming
  238. */
  239. /**
  240. * Returns true if the given candidate is of type T
  241. */
  242. function isOfType(T, maybeSomething){
  243. return maybeSomething && maybeSomething.constructor === T;
  244. }
  245. var len = attr('length'),
  246. isString = partialComplete(isOfType, String);
  247. /**
  248. * I don't like saying this:
  249. *
  250. * foo !=== undefined
  251. *
  252. * because of the double-negative. I find this:
  253. *
  254. * defined(foo)
  255. *
  256. * easier to read.
  257. */
  258. function defined( value ) {
  259. return value !== undefined;
  260. }
  261. /**
  262. * Returns true if object o has a key named like every property in
  263. * the properties array. Will give false if any are missing, or if o
  264. * is not an object.
  265. */
  266. function hasAllProperties(fieldList, o) {
  267. return (o instanceof Object)
  268. &&
  269. all(function (field) {
  270. return (field in o);
  271. }, fieldList);
  272. }
  273. /**
  274. * Like cons in Lisp
  275. */
  276. function cons(x, xs) {
  277. /* Internally lists are linked 2-element Javascript arrays.
  278. Ideally the return here would be Object.freeze([x,xs])
  279. so that bugs related to mutation are found fast.
  280. However, cons is right on the critical path for
  281. performance and this slows oboe-mark down by
  282. ~25%. Under theoretical future JS engines that freeze more
  283. efficiently (possibly even use immutability to
  284. run faster) this should be considered for
  285. restoration.
  286. */
  287. return [x,xs];
  288. }
  289. /**
  290. * The empty list
  291. */
  292. var emptyList = null,
  293. /**
  294. * Get the head of a list.
  295. *
  296. * Ie, head(cons(a,b)) = a
  297. */
  298. head = attr(0),
  299. /**
  300. * Get the tail of a list.
  301. *
  302. * Ie, head(cons(a,b)) = a
  303. */
  304. tail = attr(1);
  305. /**
  306. * Converts an array to a list
  307. *
  308. * asList([a,b,c])
  309. *
  310. * is equivalent to:
  311. *
  312. * cons(a, cons(b, cons(c, emptyList)))
  313. **/
  314. function arrayAsList(inputArray){
  315. return reverseList(
  316. inputArray.reduce(
  317. flip(cons),
  318. emptyList
  319. )
  320. );
  321. }
  322. /**
  323. * A varargs version of arrayAsList. Works a bit like list
  324. * in LISP.
  325. *
  326. * list(a,b,c)
  327. *
  328. * is equivalent to:
  329. *
  330. * cons(a, cons(b, cons(c, emptyList)))
  331. */
  332. var list = varArgs(arrayAsList);
  333. /**
  334. * Convert a list back to a js native array
  335. */
  336. function listAsArray(list){
  337. return foldR( function(arraySoFar, listItem){
  338. arraySoFar.unshift(listItem);
  339. return arraySoFar;
  340. }, [], list );
  341. }
  342. /**
  343. * Map a function over a list
  344. */
  345. function map(fn, list) {
  346. return list
  347. ? cons(fn(head(list)), map(fn,tail(list)))
  348. : emptyList
  349. ;
  350. }
  351. /**
  352. * foldR implementation. Reduce a list down to a single value.
  353. *
  354. * @pram {Function} fn (rightEval, curVal) -> result
  355. */
  356. function foldR(fn, startValue, list) {
  357. return list
  358. ? fn(foldR(fn, startValue, tail(list)), head(list))
  359. : startValue
  360. ;
  361. }
  362. /**
  363. * foldR implementation. Reduce a list down to a single value.
  364. *
  365. * @pram {Function} fn (rightEval, curVal) -> result
  366. */
  367. function foldR1(fn, list) {
  368. return tail(list)
  369. ? fn(foldR1(fn, tail(list)), head(list))
  370. : head(list)
  371. ;
  372. }
  373. /**
  374. * Return a list like the one given but with the first instance equal
  375. * to item removed
  376. */
  377. function without(list, test, removedFn) {
  378. return withoutInner(list, removedFn || noop);
  379. function withoutInner(subList, removedFn) {
  380. return subList
  381. ? ( test(head(subList))
  382. ? (removedFn(head(subList)), tail(subList))
  383. : cons(head(subList), withoutInner(tail(subList), removedFn))
  384. )
  385. : emptyList
  386. ;
  387. }
  388. }
  389. /**
  390. * Returns true if the given function holds for every item in
  391. * the list, false otherwise
  392. */
  393. function all(fn, list) {
  394. return !list ||
  395. ( fn(head(list)) && all(fn, tail(list)) );
  396. }
  397. /**
  398. * Call every function in a list of functions with the same arguments
  399. *
  400. * This doesn't make any sense if we're doing pure functional because
  401. * it doesn't return anything. Hence, this is only really useful if the
  402. * functions being called have side-effects.
  403. */
  404. function applyEach(fnList, args) {
  405. if( fnList ) {
  406. head(fnList).apply(null, args);
  407. applyEach(tail(fnList), args);
  408. }
  409. }
  410. /**
  411. * Reverse the order of a list
  412. */
  413. function reverseList(list){
  414. // js re-implementation of 3rd solution from:
  415. // http://www.haskell.org/haskellwiki/99_questions/Solutions/5
  416. function reverseInner( list, reversedAlready ) {
  417. if( !list ) {
  418. return reversedAlready;
  419. }
  420. return reverseInner(tail(list), cons(head(list), reversedAlready))
  421. }
  422. return reverseInner(list, emptyList);
  423. }
  424. function first(test, list) {
  425. return list &&
  426. (test(head(list))
  427. ? head(list)
  428. : first(test,tail(list)));
  429. }
  430. /*
  431. This is a slightly hacked-up browser only version of clarinet
  432. * some features removed to help keep browser Oboe under
  433. the 5k micro-library limit
  434. * plug directly into event bus
  435. For the original go here:
  436. https://github.com/dscape/clarinet
  437. We receive the events:
  438. STREAM_DATA
  439. STREAM_END
  440. We emit the events:
  441. SAX_KEY
  442. SAX_VALUE_OPEN
  443. SAX_VALUE_CLOSE
  444. FAIL_EVENT
  445. */
  446. function clarinet(eventBus) {
  447. "use strict";
  448. var
  449. // shortcut some events on the bus
  450. emitSaxKey = eventBus(SAX_KEY).emit,
  451. emitValueOpen = eventBus(SAX_VALUE_OPEN).emit,
  452. emitValueClose = eventBus(SAX_VALUE_CLOSE).emit,
  453. emitFail = eventBus(FAIL_EVENT).emit,
  454. MAX_BUFFER_LENGTH = 64 * 1024
  455. , stringTokenPattern = /[\\"\n]/g
  456. , _n = 0
  457. // states
  458. , BEGIN = _n++
  459. , VALUE = _n++ // general stuff
  460. , OPEN_OBJECT = _n++ // {
  461. , CLOSE_OBJECT = _n++ // }
  462. , OPEN_ARRAY = _n++ // [
  463. , CLOSE_ARRAY = _n++ // ]
  464. , STRING = _n++ // ""
  465. , OPEN_KEY = _n++ // , "a"
  466. , CLOSE_KEY = _n++ // :
  467. , TRUE = _n++ // r
  468. , TRUE2 = _n++ // u
  469. , TRUE3 = _n++ // e
  470. , FALSE = _n++ // a
  471. , FALSE2 = _n++ // l
  472. , FALSE3 = _n++ // s
  473. , FALSE4 = _n++ // e
  474. , NULL = _n++ // u
  475. , NULL2 = _n++ // l
  476. , NULL3 = _n++ // l
  477. , NUMBER_DECIMAL_POINT = _n++ // .
  478. , NUMBER_DIGIT = _n // [0-9]
  479. // setup initial parser values
  480. , bufferCheckPosition = MAX_BUFFER_LENGTH
  481. , latestError
  482. , c
  483. , p
  484. , textNode = ""
  485. , numberNode = ""
  486. , slashed = false
  487. , closed = false
  488. , state = BEGIN
  489. , stack = []
  490. , unicodeS = null
  491. , unicodeI = 0
  492. , depth = 0
  493. , position = 0
  494. , column = 0 //mostly for error reporting
  495. , line = 1
  496. ;
  497. function checkBufferLength () {
  498. var maxActual = 0;
  499. if (textNode.length > MAX_BUFFER_LENGTH) {
  500. emitError("Max buffer length exceeded: textNode");
  501. maxActual = Math.max(maxActual, textNode.length);
  502. }
  503. if (numberNode.length > MAX_BUFFER_LENGTH) {
  504. emitError("Max buffer length exceeded: numberNode");
  505. maxActual = Math.max(maxActual, numberNode.length);
  506. }
  507. bufferCheckPosition = (MAX_BUFFER_LENGTH - maxActual)
  508. + position;
  509. }
  510. eventBus(STREAM_DATA).on(handleData);
  511. /* At the end of the http content close the clarinet
  512. This will provide an error if the total content provided was not
  513. valid json, ie if not all arrays, objects and Strings closed properly */
  514. eventBus(STREAM_END).on(handleStreamEnd);
  515. function emitError (errorString) {
  516. if (textNode) {
  517. emitValueOpen(textNode);
  518. emitValueClose();
  519. textNode = "";
  520. }
  521. latestError = Error(errorString + "\nLn: "+line+
  522. "\nCol: "+column+
  523. "\nChr: "+c);
  524. emitFail(errorReport(undefined, undefined, latestError));
  525. }
  526. function handleStreamEnd() {
  527. if( state == BEGIN ) {
  528. // Handle the case where the stream closes without ever receiving
  529. // any input. This isn't an error - response bodies can be blank,
  530. // particularly for 204 http responses
  531. // Because of how Oboe is currently implemented, we parse a
  532. // completely empty stream as containing an empty object.
  533. // This is because Oboe's done event is only fired when the
  534. // root object of the JSON stream closes.
  535. // This should be decoupled and attached instead to the input stream
  536. // from the http (or whatever) resource ending.
  537. // If this decoupling could happen the SAX parser could simply emit
  538. // zero events on a completely empty input.
  539. emitValueOpen({});
  540. emitValueClose();
  541. closed = true;
  542. return;
  543. }
  544. if (state !== VALUE || depth !== 0)
  545. emitError("Unexpected end");
  546. if (textNode) {
  547. emitValueOpen(textNode);
  548. emitValueClose();
  549. textNode = "";
  550. }
  551. closed = true;
  552. }
  553. function whitespace(c){
  554. return c == '\r' || c == '\n' || c == ' ' || c == '\t';
  555. }
  556. function handleData (chunk) {
  557. // this used to throw the error but inside Oboe we will have already
  558. // gotten the error when it was emitted. The important thing is to
  559. // not continue with the parse.
  560. if (latestError)
  561. return;
  562. if (closed) {
  563. return emitError("Cannot write after close");
  564. }
  565. var i = 0;
  566. c = chunk[0];
  567. while (c) {
  568. p = c;
  569. c = chunk[i++];
  570. if(!c) break;
  571. position ++;
  572. if (c == "\n") {
  573. line ++;
  574. column = 0;
  575. } else column ++;
  576. switch (state) {
  577. case BEGIN:
  578. if (c === "{") state = OPEN_OBJECT;
  579. else if (c === "[") state = OPEN_ARRAY;
  580. else if (!whitespace(c))
  581. return emitError("Non-whitespace before {[.");
  582. continue;
  583. case OPEN_KEY:
  584. case OPEN_OBJECT:
  585. if (whitespace(c)) continue;
  586. if(state === OPEN_KEY) stack.push(CLOSE_KEY);
  587. else {
  588. if(c === '}') {
  589. emitValueOpen({});
  590. emitValueClose();
  591. state = stack.pop() || VALUE;
  592. continue;
  593. } else stack.push(CLOSE_OBJECT);
  594. }
  595. if(c === '"')
  596. state = STRING;
  597. else
  598. return emitError("Malformed object key should start with \" ");
  599. continue;
  600. case CLOSE_KEY:
  601. case CLOSE_OBJECT:
  602. if (whitespace(c)) continue;
  603. if(c===':') {
  604. if(state === CLOSE_OBJECT) {
  605. stack.push(CLOSE_OBJECT);
  606. if (textNode) {
  607. // was previously (in upstream Clarinet) one event
  608. // - object open came with the text of the first
  609. emitValueOpen({});
  610. emitSaxKey(textNode);
  611. textNode = "";
  612. }
  613. depth++;
  614. } else {
  615. if (textNode) {
  616. emitSaxKey(textNode);
  617. textNode = "";
  618. }
  619. }
  620. state = VALUE;
  621. } else if (c==='}') {
  622. if (textNode) {
  623. emitValueOpen(textNode);
  624. emitValueClose();
  625. textNode = "";
  626. }
  627. emitValueClose();
  628. depth--;
  629. state = stack.pop() || VALUE;
  630. } else if(c===',') {
  631. if(state === CLOSE_OBJECT)
  632. stack.push(CLOSE_OBJECT);
  633. if (textNode) {
  634. emitValueOpen(textNode);
  635. emitValueClose();
  636. textNode = "";
  637. }
  638. state = OPEN_KEY;
  639. } else
  640. return emitError('Bad object');
  641. continue;
  642. case OPEN_ARRAY: // after an array there always a value
  643. case VALUE:
  644. if (whitespace(c)) continue;
  645. if(state===OPEN_ARRAY) {
  646. emitValueOpen([]);
  647. depth++;
  648. state = VALUE;
  649. if(c === ']') {
  650. emitValueClose();
  651. depth--;
  652. state = stack.pop() || VALUE;
  653. continue;
  654. } else {
  655. stack.push(CLOSE_ARRAY);
  656. }
  657. }
  658. if(c === '"') state = STRING;
  659. else if(c === '{') state = OPEN_OBJECT;
  660. else if(c === '[') state = OPEN_ARRAY;
  661. else if(c === 't') state = TRUE;
  662. else if(c === 'f') state = FALSE;
  663. else if(c === 'n') state = NULL;
  664. else if(c === '-') { // keep and continue
  665. numberNode += c;
  666. } else if(c==='0') {
  667. numberNode += c;
  668. state = NUMBER_DIGIT;
  669. } else if('123456789'.indexOf(c) !== -1) {
  670. numberNode += c;
  671. state = NUMBER_DIGIT;
  672. } else
  673. return emitError("Bad value");
  674. continue;
  675. case CLOSE_ARRAY:
  676. if(c===',') {
  677. stack.push(CLOSE_ARRAY);
  678. if (textNode) {
  679. emitValueOpen(textNode);
  680. emitValueClose();
  681. textNode = "";
  682. }
  683. state = VALUE;
  684. } else if (c===']') {
  685. if (textNode) {
  686. emitValueOpen(textNode);
  687. emitValueClose();
  688. textNode = "";
  689. }
  690. emitValueClose();
  691. depth--;
  692. state = stack.pop() || VALUE;
  693. } else if (whitespace(c))
  694. continue;
  695. else
  696. return emitError('Bad array');
  697. continue;
  698. case STRING:
  699. // thanks thejh, this is an about 50% performance improvement.
  700. var starti = i-1;
  701. STRING_BIGLOOP: while (true) {
  702. // zero means "no unicode active". 1-4 mean "parse some more". end after 4.
  703. while (unicodeI > 0) {
  704. unicodeS += c;
  705. c = chunk.charAt(i++);
  706. if (unicodeI === 4) {
  707. // TODO this might be slow? well, probably not used too often anyway
  708. textNode += String.fromCharCode(parseInt(unicodeS, 16));
  709. unicodeI = 0;
  710. starti = i-1;
  711. } else {
  712. unicodeI++;
  713. }
  714. // we can just break here: no stuff we skipped that still has to be sliced out or so
  715. if (!c) break STRING_BIGLOOP;
  716. }
  717. if (c === '"' && !slashed) {
  718. state = stack.pop() || VALUE;
  719. textNode += chunk.substring(starti, i-1);
  720. if(!textNode) {
  721. emitValueOpen("");
  722. emitValueClose();
  723. }
  724. break;
  725. }
  726. if (c === '\\' && !slashed) {
  727. slashed = true;
  728. textNode += chunk.substring(starti, i-1);
  729. c = chunk.charAt(i++);
  730. if (!c) break;
  731. }
  732. if (slashed) {
  733. slashed = false;
  734. if (c === 'n') { textNode += '\n'; }
  735. else if (c === 'r') { textNode += '\r'; }
  736. else if (c === 't') { textNode += '\t'; }
  737. else if (c === 'f') { textNode += '\f'; }
  738. else if (c === 'b') { textNode += '\b'; }
  739. else if (c === 'u') {
  740. // \uxxxx. meh!
  741. unicodeI = 1;
  742. unicodeS = '';
  743. } else {
  744. textNode += c;
  745. }
  746. c = chunk.charAt(i++);
  747. starti = i-1;
  748. if (!c) break;
  749. else continue;
  750. }
  751. stringTokenPattern.lastIndex = i;
  752. var reResult = stringTokenPattern.exec(chunk);
  753. if (!reResult) {
  754. i = chunk.length+1;
  755. textNode += chunk.substring(starti, i-1);
  756. break;
  757. }
  758. i = reResult.index+1;
  759. c = chunk.charAt(reResult.index);
  760. if (!c) {
  761. textNode += chunk.substring(starti, i-1);
  762. break;
  763. }
  764. }
  765. continue;
  766. case TRUE:
  767. if (!c) continue; // strange buffers
  768. if (c==='r') state = TRUE2;
  769. else
  770. return emitError( 'Invalid true started with t'+ c);
  771. continue;
  772. case TRUE2:
  773. if (!c) continue;
  774. if (c==='u') state = TRUE3;
  775. else
  776. return emitError('Invalid true started with tr'+ c);
  777. continue;
  778. case TRUE3:
  779. if (!c) continue;
  780. if(c==='e') {
  781. emitValueOpen(true);
  782. emitValueClose();
  783. state = stack.pop() || VALUE;
  784. } else
  785. return emitError('Invalid true started with tru'+ c);
  786. continue;
  787. case FALSE:
  788. if (!c) continue;
  789. if (c==='a') state = FALSE2;
  790. else
  791. return emitError('Invalid false started with f'+ c);
  792. continue;
  793. case FALSE2:
  794. if (!c) continue;
  795. if (c==='l') state = FALSE3;
  796. else
  797. return emitError('Invalid false started with fa'+ c);
  798. continue;
  799. case FALSE3:
  800. if (!c) continue;
  801. if (c==='s') state = FALSE4;
  802. else
  803. return emitError('Invalid false started with fal'+ c);
  804. continue;
  805. case FALSE4:
  806. if (!c) continue;
  807. if (c==='e') {
  808. emitValueOpen(false);
  809. emitValueClose();
  810. state = stack.pop() || VALUE;
  811. } else
  812. return emitError('Invalid false started with fals'+ c);
  813. continue;
  814. case NULL:
  815. if (!c) continue;
  816. if (c==='u') state = NULL2;
  817. else
  818. return emitError('Invalid null started with n'+ c);
  819. continue;
  820. case NULL2:
  821. if (!c) continue;
  822. if (c==='l') state = NULL3;
  823. else
  824. return emitError('Invalid null started with nu'+ c);
  825. continue;
  826. case NULL3:
  827. if (!c) continue;
  828. if(c==='l') {
  829. emitValueOpen(null);
  830. emitValueClose();
  831. state = stack.pop() || VALUE;
  832. } else
  833. return emitError('Invalid null started with nul'+ c);
  834. continue;
  835. case NUMBER_DECIMAL_POINT:
  836. if(c==='.') {
  837. numberNode += c;
  838. state = NUMBER_DIGIT;
  839. } else
  840. return emitError('Leading zero not followed by .');
  841. continue;
  842. case NUMBER_DIGIT:
  843. if('0123456789'.indexOf(c) !== -1) numberNode += c;
  844. else if (c==='.') {
  845. if(numberNode.indexOf('.')!==-1)
  846. return emitError('Invalid number has two dots');
  847. numberNode += c;
  848. } else if (c==='e' || c==='E') {
  849. if(numberNode.indexOf('e')!==-1 ||
  850. numberNode.indexOf('E')!==-1 )
  851. return emitError('Invalid number has two exponential');
  852. numberNode += c;
  853. } else if (c==="+" || c==="-") {
  854. if(!(p==='e' || p==='E'))
  855. return emitError('Invalid symbol in number');
  856. numberNode += c;
  857. } else {
  858. if (numberNode) {
  859. emitValueOpen(parseFloat(numberNode));
  860. emitValueClose();
  861. numberNode = "";
  862. }
  863. i--; // go back one
  864. state = stack.pop() || VALUE;
  865. }
  866. continue;
  867. default:
  868. return emitError("Unknown state: " + state);
  869. }
  870. }
  871. if (position >= bufferCheckPosition)
  872. checkBufferLength();
  873. }
  874. }
  875. /**
  876. * A bridge used to assign stateless functions to listen to clarinet.
  877. *
  878. * As well as the parameter from clarinet, each callback will also be passed
  879. * the result of the last callback.
  880. *
  881. * This may also be used to clear all listeners by assigning zero handlers:
  882. *
  883. * ascentManager( clarinet, {} )
  884. */
  885. function ascentManager(oboeBus, handlers){
  886. "use strict";
  887. var listenerId = {},
  888. ascent;
  889. function stateAfter(handler) {
  890. return function(param){
  891. ascent = handler( ascent, param);
  892. }
  893. }
  894. for( var eventName in handlers ) {
  895. oboeBus(eventName).on(stateAfter(handlers[eventName]), listenerId);
  896. }
  897. oboeBus(NODE_SWAP).on(function(newNode) {
  898. var oldHead = head(ascent),
  899. key = keyOf(oldHead),
  900. ancestors = tail(ascent),
  901. parentNode;
  902. if( ancestors ) {
  903. parentNode = nodeOf(head(ancestors));
  904. parentNode[key] = newNode;
  905. }
  906. });
  907. oboeBus(NODE_DROP).on(function() {
  908. var oldHead = head(ascent),
  909. key = keyOf(oldHead),
  910. ancestors = tail(ascent),
  911. parentNode;
  912. if( ancestors ) {
  913. parentNode = nodeOf(head(ancestors));
  914. delete parentNode[key];
  915. }
  916. });
  917. oboeBus(ABORTING).on(function(){
  918. for( var eventName in handlers ) {
  919. oboeBus(eventName).un(listenerId);
  920. }
  921. });
  922. }
  923. // based on gist https://gist.github.com/monsur/706839
  924. /**
  925. * XmlHttpRequest's getAllResponseHeaders() method returns a string of response
  926. * headers according to the format described here:
  927. * http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders-method
  928. * This method parses that string into a user-friendly key/value pair object.
  929. */
  930. function parseResponseHeaders(headerStr) {
  931. var headers = {};
  932. headerStr && headerStr.split('\u000d\u000a')
  933. .forEach(function(headerPair){
  934. // Can't use split() here because it does the wrong thing
  935. // if the header value has the string ": " in it.
  936. var index = headerPair.indexOf('\u003a\u0020');
  937. headers[headerPair.substring(0, index)]
  938. = headerPair.substring(index + 2);
  939. });
  940. return headers;
  941. }
  942. /**
  943. * Detect if a given URL is cross-origin in the scope of the
  944. * current page.
  945. *
  946. * Browser only (since cross-origin has no meaning in Node.js)
  947. *
  948. * @param {Object} pageLocation - as in window.location
  949. * @param {Object} ajaxHost - an object like window.location describing the
  950. * origin of the url that we want to ajax in
  951. */
  952. function isCrossOrigin(pageLocation, ajaxHost) {
  953. /*
  954. * NB: defaultPort only knows http and https.
  955. * Returns undefined otherwise.
  956. */
  957. function defaultPort(protocol) {
  958. return {'http:':80, 'https:':443}[protocol];
  959. }
  960. function portOf(location) {
  961. // pageLocation should always have a protocol. ajaxHost if no port or
  962. // protocol is specified, should use the port of the containing page
  963. return location.port || defaultPort(location.protocol||pageLocation.protocol);
  964. }
  965. // if ajaxHost doesn't give a domain, port is the same as pageLocation
  966. // it can't give a protocol but not a domain
  967. // it can't give a port but not a domain
  968. return !!( (ajaxHost.protocol && (ajaxHost.protocol != pageLocation.protocol)) ||
  969. (ajaxHost.host && (ajaxHost.host != pageLocation.host)) ||
  970. (ajaxHost.host && (portOf(ajaxHost) != portOf(pageLocation)))
  971. );
  972. }
  973. /* turn any url into an object like window.location */
  974. function parseUrlOrigin(url) {
  975. // url could be domain-relative
  976. // url could give a domain
  977. // cross origin means:
  978. // same domain
  979. // same port
  980. // some protocol
  981. // so, same everything up to the first (single) slash
  982. // if such is given
  983. //
  984. // can ignore everything after that
  985. var URL_HOST_PATTERN = /(\w+:)?(?:\/\/)([\w.-]+)?(?::(\d+))?\/?/,
  986. // if no match, use an empty array so that
  987. // subexpressions 1,2,3 are all undefined
  988. // and will ultimately return all empty
  989. // strings as the parse result:
  990. urlHostMatch = URL_HOST_PATTERN.exec(url) || [];
  991. return {
  992. protocol: urlHostMatch[1] || '',
  993. host: urlHostMatch[2] || '',
  994. port: urlHostMatch[3] || ''
  995. };
  996. }
  997. function httpTransport(){
  998. return new XMLHttpRequest();
  999. }
  1000. /**
  1001. * A wrapper around the browser XmlHttpRequest object that raises an
  1002. * event whenever a new part of the response is available.
  1003. *
  1004. * In older browsers progressive reading is impossible so all the
  1005. * content is given in a single call. For newer ones several events
  1006. * should be raised, allowing progressive interpretation of the response.
  1007. *
  1008. * @param {Function} oboeBus an event bus local to this Oboe instance
  1009. * @param {XMLHttpRequest} xhr the xhr to use as the transport. Under normal
  1010. * operation, will have been created using httpTransport() above
  1011. * but for tests a stub can be provided instead.
  1012. * @param {String} method one of 'GET' 'POST' 'PUT' 'PATCH' 'DELETE'
  1013. * @param {String} url the url to make a request to
  1014. * @param {String|Null} data some content to be sent with the request.
  1015. * Only valid if method is POST or PUT.
  1016. * @param {Object} [headers] the http request headers to send
  1017. * @param {boolean} withCredentials the XHR withCredentials property will be
  1018. * set to this value
  1019. */
  1020. function streamingHttp(oboeBus, xhr, method, url, data, headers, withCredentials) {
  1021. "use strict";
  1022. var emitStreamData = oboeBus(STREAM_DATA).emit,
  1023. emitFail = oboeBus(FAIL_EVENT).emit,
  1024. numberOfCharsAlreadyGivenToCallback = 0,
  1025. stillToSendStartEvent = true;
  1026. // When an ABORTING message is put on the event bus abort
  1027. // the ajax request
  1028. oboeBus( ABORTING ).on( function(){
  1029. // if we keep the onreadystatechange while aborting the XHR gives
  1030. // a callback like a successful call so first remove this listener
  1031. // by assigning null:
  1032. xhr.onreadystatechange = null;
  1033. xhr.abort();
  1034. });
  1035. /**
  1036. * Handle input from the underlying xhr: either a state change,
  1037. * the progress event or the request being complete.
  1038. */
  1039. function handleProgress() {
  1040. var textSoFar = xhr.responseText,
  1041. newText = textSoFar.substr(numberOfCharsAlreadyGivenToCallback);
  1042. /* Raise the event for new text.
  1043. On older browsers, the new text is the whole response.
  1044. On newer/better ones, the fragment part that we got since
  1045. last progress. */
  1046. if( newText ) {
  1047. emitStreamData( newText );
  1048. }
  1049. numberOfCharsAlreadyGivenToCallback = len(textSoFar);
  1050. }
  1051. if('onprogress' in xhr){ // detect browser support for progressive delivery
  1052. xhr.onprogress = handleProgress;
  1053. }
  1054. xhr.onreadystatechange = function() {
  1055. function sendStartIfNotAlready() {
  1056. // Internet Explorer is very unreliable as to when xhr.status etc can
  1057. // be read so has to be protected with try/catch and tried again on
  1058. // the next readyState if it fails
  1059. try{
  1060. stillToSendStartEvent && oboeBus( HTTP_START ).emit(
  1061. xhr.status,
  1062. parseResponseHeaders(xhr.getAllResponseHeaders()) );
  1063. stillToSendStartEvent = false;
  1064. } catch(e){/* do nothing, will try again on next readyState*/}
  1065. }
  1066. switch( xhr.readyState ) {
  1067. case 2: // HEADERS_RECEIVED
  1068. case 3: // LOADING
  1069. return sendStartIfNotAlready();
  1070. case 4: // DONE
  1071. sendStartIfNotAlready(); // if xhr.status hasn't been available yet, it must be NOW, huh IE?
  1072. // is this a 2xx http code?
  1073. var successful = String(xhr.status)[0] == 2;
  1074. if( successful ) {
  1075. // In Chrome 29 (not 28) no onprogress is emitted when a response
  1076. // is complete before the onload. We need to always do handleInput
  1077. // in case we get the load but have not had a final progress event.
  1078. // This looks like a bug and may change in future but let's take
  1079. // the safest approach and assume we might not have received a
  1080. // progress event for each part of the response
  1081. handleProgress();
  1082. oboeBus(STREAM_END).emit();
  1083. } else {
  1084. emitFail( errorReport(
  1085. xhr.status,
  1086. xhr.responseText
  1087. ));
  1088. }
  1089. }
  1090. };
  1091. try{
  1092. xhr.open(method, url, true);
  1093. for( var headerName in headers ){
  1094. xhr.setRequestHeader(headerName, headers[headerName]);
  1095. }
  1096. if( !isCrossOrigin(window.location, parseUrlOrigin(url)) ) {
  1097. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  1098. }
  1099. xhr.withCredentials = withCredentials;
  1100. xhr.send(data);
  1101. } catch( e ) {
  1102. // To keep a consistent interface with Node, we can't emit an event here.
  1103. // Node's streaming http adaptor receives the error as an asynchronous
  1104. // event rather than as an exception. If we emitted now, the Oboe user
  1105. // has had no chance to add a .fail listener so there is no way
  1106. // the event could be useful. For both these reasons defer the
  1107. // firing to the next JS frame.
  1108. window.setTimeout(
  1109. partialComplete(emitFail, errorReport(undefined, undefined, e))
  1110. , 0
  1111. );
  1112. }
  1113. }
  1114. var jsonPathSyntax = (function() {
  1115. var
  1116. /**
  1117. * Export a regular expression as a simple function by exposing just
  1118. * the Regex#exec. This allows regex tests to be used under the same
  1119. * interface as differently implemented tests, or for a user of the
  1120. * tests to not concern themselves with their implementation as regular
  1121. * expressions.
  1122. *
  1123. * This could also be expressed point-free as:
  1124. * Function.prototype.bind.bind(RegExp.prototype.exec),
  1125. *
  1126. * But that's far too confusing! (and not even smaller once minified
  1127. * and gzipped)
  1128. */
  1129. regexDescriptor = function regexDescriptor(regex) {
  1130. return regex.exec.bind(regex);
  1131. }
  1132. /**
  1133. * Join several regular expressions and express as a function.
  1134. * This allows the token patterns to reuse component regular expressions
  1135. * instead of being expressed in full using huge and confusing regular
  1136. * expressions.
  1137. */
  1138. , jsonPathClause = varArgs(function( componentRegexes ) {
  1139. // The regular expressions all start with ^ because we
  1140. // only want to find matches at the start of the
  1141. // JSONPath fragment we are inspecting
  1142. componentRegexes.unshift(/^/);
  1143. return regexDescriptor(
  1144. RegExp(
  1145. componentRegexes.map(attr('source')).join('')
  1146. )
  1147. );
  1148. })
  1149. , possiblyCapturing = /(\$?)/
  1150. , namedNode = /([\w-_]+|\*)/
  1151. , namePlaceholder = /()/
  1152. , nodeInArrayNotation = /\["([^"]+)"\]/
  1153. , numberedNodeInArrayNotation = /\[(\d+|\*)\]/
  1154. , fieldList = /{([\w ]*?)}/
  1155. , optionalFieldList = /(?:{([\w ]*?)})?/
  1156. // foo or *
  1157. , jsonPathNamedNodeInObjectNotation = jsonPathClause(
  1158. possiblyCapturing,
  1159. namedNode,
  1160. optionalFieldList
  1161. )
  1162. // ["foo"]
  1163. , jsonPathNamedNodeInArrayNotation = jsonPathClause(
  1164. possiblyCapturing,
  1165. nodeInArrayNotation,
  1166. optionalFieldList
  1167. )
  1168. // [2] or [*]
  1169. , jsonPathNumberedNodeInArrayNotation = jsonPathClause(
  1170. possiblyCapturing,
  1171. numberedNodeInArrayNotation,
  1172. optionalFieldList
  1173. )
  1174. // {a b c}
  1175. , jsonPathPureDuckTyping = jsonPathClause(
  1176. possiblyCapturing,
  1177. namePlaceholder,
  1178. fieldList
  1179. )
  1180. // ..
  1181. , jsonPathDoubleDot = jsonPathClause(/\.\./)
  1182. // .
  1183. , jsonPathDot = jsonPathClause(/\./)
  1184. // !
  1185. , jsonPathBang = jsonPathClause(
  1186. possiblyCapturing,
  1187. /!/
  1188. )
  1189. // nada!
  1190. , emptyString = jsonPathClause(/$/)
  1191. ;
  1192. /* We export only a single function. When called, this function injects
  1193. into another function the descriptors from above.
  1194. */
  1195. return function (fn){
  1196. return fn(
  1197. lazyUnion(
  1198. jsonPathNamedNodeInObjectNotation
  1199. , jsonPathNamedNodeInArrayNotation
  1200. , jsonPathNumberedNodeInArrayNotation
  1201. , jsonPathPureDuckTyping
  1202. )
  1203. , jsonPathDoubleDot
  1204. , jsonPathDot
  1205. , jsonPathBang
  1206. , emptyString
  1207. );
  1208. };
  1209. }());
  1210. /**
  1211. * Get a new key->node mapping
  1212. *
  1213. * @param {String|Number} key
  1214. * @param {Object|Array|String|Number|null} node a value found in the json
  1215. */
  1216. function namedNode(key, node) {
  1217. return {key:key, node:node};
  1218. }
  1219. /** get the key of a namedNode */
  1220. var keyOf = attr('key');
  1221. /** get the node from a namedNode */
  1222. var nodeOf = attr('node');
  1223. /**
  1224. * This file provides various listeners which can be used to build up
  1225. * a changing ascent based on the callbacks provided by Clarinet. It listens
  1226. * to the low-level events from Clarinet and emits higher-level ones.
  1227. *
  1228. * The building up is stateless so to track a JSON file
  1229. * ascentManager.js is required to store the ascent state
  1230. * between calls.
  1231. */
  1232. /**
  1233. * A special value to use in the path list to represent the path 'to' a root
  1234. * object (which doesn't really have any path). This prevents the need for
  1235. * special-casing detection of the root object and allows it to be treated
  1236. * like any other object. We might think of this as being similar to the
  1237. * 'unnamed root' domain ".", eg if I go to
  1238. * http://en.wikipedia.org./wiki/En/Main_page the dot after 'org' deliminates
  1239. * the unnamed root of the DNS.
  1240. *
  1241. * This is kept as an object to take advantage that in Javascript's OO objects
  1242. * are guaranteed to be distinct, therefore no other object can possibly clash
  1243. * with this one. Strings, numbers etc provide no such guarantee.
  1244. **/
  1245. var ROOT_PATH = {};
  1246. /**
  1247. * Create a new set of handlers for clarinet's events, bound to the emit
  1248. * function given.
  1249. */
  1250. function incrementalContentBuilder( oboeBus ) {
  1251. var emitNodeOpened = oboeBus(NODE_OPENED).emit,
  1252. emitNodeClosed = oboeBus(NODE_CLOSED).emit,
  1253. emitRootOpened = oboeBus(ROOT_PATH_FOUND).emit,
  1254. emitRootClosed = oboeBus(ROOT_NODE_FOUND).emit;
  1255. function arrayIndicesAreKeys( possiblyInconsistentAscent, newDeepestNode) {
  1256. /* for values in arrays we aren't pre-warned of the coming paths
  1257. (Clarinet gives no call to onkey like it does for values in objects)
  1258. so if we are in an array we need to create this path ourselves. The
  1259. key will be len(parentNode) because array keys are always sequential
  1260. numbers. */
  1261. var parentNode = nodeOf( head( possiblyInconsistentAscent));
  1262. return isOfType( Array, parentNode)
  1263. ?
  1264. keyFound( possiblyInconsistentAscent,
  1265. len(parentNode),
  1266. newDeepestNode
  1267. )
  1268. :
  1269. // nothing needed, return unchanged
  1270. possiblyInconsistentAscent
  1271. ;
  1272. }
  1273. function nodeOpened( ascent, newDeepestNode ) {
  1274. if( !ascent ) {
  1275. // we discovered the root node,
  1276. emitRootOpened( newDeepestNode);
  1277. return keyFound( ascent, ROOT_PATH, newDeepestNode);
  1278. }
  1279. // we discovered a non-root node
  1280. var arrayConsistentAscent = arrayIndicesAreKeys( ascent, newDeepestNode),
  1281. ancestorBranches = tail( arrayConsistentAscent),
  1282. previouslyUnmappedName = keyOf( head( arrayConsistentAscent));
  1283. appendBuiltContent(
  1284. ancestorBranches,
  1285. previouslyUnmappedName,
  1286. newDeepestNode
  1287. );
  1288. return cons(
  1289. namedNode( previouslyUnmappedName, newDeepestNode ),
  1290. ancestorBranches
  1291. );
  1292. }
  1293. /**
  1294. * Add a new value to the object we are building up to represent the
  1295. * parsed JSON
  1296. */
  1297. function appendBuiltContent( ancestorBranches, key, node ){
  1298. nodeOf( head( ancestorBranches))[key] = node;
  1299. }
  1300. /**
  1301. * For when we find a new key in the json.
  1302. *
  1303. * @param {String|Number|Object} newDeepestName the key. If we are in an
  1304. * array will be a number, otherwise a string. May take the special
  1305. * value ROOT_PATH if the root node has just been found
  1306. *
  1307. * @param {String|Number|Object|Array|Null|undefined} [maybeNewDeepestNode]
  1308. * usually this won't be known so can be undefined. Can't use null
  1309. * to represent unknown because null is a valid value in JSON
  1310. **/
  1311. function keyFound(ascent, newDeepestName, maybeNewDeepestNode) {
  1312. if( ascent ) { // if not root
  1313. // If we have the key but (unless adding to an array) no known value
  1314. // yet. Put that key in the output but against no defined value:
  1315. appendBuiltContent( ascent, newDeepestName, maybeNewDeepestNode );
  1316. }
  1317. var ascentWithNewPath = cons(
  1318. namedNode( newDeepestName,
  1319. maybeNewDeepestNode),
  1320. ascent
  1321. );
  1322. emitNodeOpened( ascentWithNewPath);
  1323. return ascentWithNewPath;
  1324. }
  1325. /**
  1326. * For when the current node ends.
  1327. */
  1328. function nodeClosed( ascent ) {
  1329. emitNodeClosed( ascent);
  1330. return tail( ascent) ||
  1331. // If there are no nodes left in the ascent the root node
  1332. // just closed. Emit a special event for this:
  1333. emitRootClosed(nodeOf(head(ascent)));
  1334. }
  1335. var contentBuilderHandlers = {};
  1336. contentBuilderHandlers[SAX_VALUE_OPEN] = nodeOpened;
  1337. contentBuilderHandlers[SAX_VALUE_CLOSE] = nodeClosed;
  1338. contentBuilderHandlers[SAX_KEY] = keyFound;
  1339. return contentBuilderHandlers;
  1340. }
  1341. /**
  1342. * The jsonPath evaluator compiler used for Oboe.js.
  1343. *
  1344. * One function is exposed. This function takes a String JSONPath spec and
  1345. * returns a function to test candidate ascents for matches.
  1346. *
  1347. * String jsonPath -> (List ascent) -> Boolean|Object
  1348. *
  1349. * This file is coded in a pure functional style. That is, no function has
  1350. * side effects, every function evaluates to the same value for the same
  1351. * arguments and no variables are reassigned.
  1352. */
  1353. // the call to jsonPathSyntax injects the token syntaxes that are needed
  1354. // inside the compiler
  1355. var jsonPathCompiler = jsonPathSyntax(function (pathNodeSyntax,
  1356. doubleDotSyntax,
  1357. dotSyntax,
  1358. bangSyntax,
  1359. emptySyntax ) {
  1360. var CAPTURING_INDEX = 1;
  1361. var NAME_INDEX = 2;
  1362. var FIELD_LIST_INDEX = 3;
  1363. var headKey = compose2(keyOf, head),
  1364. headNode = compose2(nodeOf, head);
  1365. /**
  1366. * Create an evaluator function for a named path node, expressed in the
  1367. * JSONPath like:
  1368. * foo
  1369. * ["bar"]
  1370. * [2]
  1371. */
  1372. function nameClause(previousExpr, detection ) {
  1373. var name = detection[NAME_INDEX],
  1374. matchesName = ( !name || name == '*' )
  1375. ? always
  1376. : function(ascent){return headKey(ascent) == name};
  1377. return lazyIntersection(matchesName, previousExpr);
  1378. }
  1379. /**
  1380. * Create an evaluator function for a a duck-typed node, expressed like:
  1381. *
  1382. * {spin, taste, colour}
  1383. * .particle{spin, taste, colour}
  1384. * *{spin, taste, colour}
  1385. */
  1386. function duckTypeClause(previousExpr, detection) {
  1387. var fieldListStr = detection[FIELD_LIST_INDEX];
  1388. if (!fieldListStr)
  1389. return previousExpr; // don't wrap at all, return given expr as-is
  1390. var hasAllrequiredFields = partialComplete(
  1391. hasAllProperties,
  1392. arrayAsList(fieldListStr.split(/\W+/))
  1393. ),
  1394. isMatch = compose2(
  1395. hasAllrequiredFields,
  1396. headNode
  1397. );
  1398. return lazyIntersection(isMatch, previousExpr);
  1399. }
  1400. /**
  1401. * Expression for $, returns the evaluator function
  1402. */
  1403. function capture( previousExpr, detection ) {
  1404. // extract meaning from the detection
  1405. var capturing = !!detection[CAPTURING_INDEX];
  1406. if (!capturing)
  1407. return previousExpr; // don't wrap at all, return given expr as-is
  1408. return lazyIntersection(previousExpr, head);
  1409. }
  1410. /**
  1411. * Create an evaluator function that moves onto the next item on the
  1412. * lists. This function is the place where the logic to move up a
  1413. * level in the ascent exists.
  1414. *
  1415. * Eg, for JSONPath ".foo" we need skip1(nameClause(always, [,'foo']))
  1416. */
  1417. function skip1(previousExpr) {
  1418. if( previousExpr == always ) {
  1419. /* If there is no previous expression this consume command
  1420. is at the start of the jsonPath.
  1421. Since JSONPath specifies what we'd like to find but not
  1422. necessarily everything leading down to it, when running
  1423. out of JSONPath to check against we default to true */
  1424. return always;
  1425. }
  1426. /** return true if the ascent we have contains only the JSON root,
  1427. * false otherwise
  1428. */
  1429. function notAtRoot(ascent){
  1430. return headKey(ascent) != ROOT_PATH;
  1431. }
  1432. return lazyIntersection(
  1433. /* If we're already at the root but there are more
  1434. expressions to satisfy, can't consume any more. No match.
  1435. This check is why none of the other exprs have to be able
  1436. to handle empty lists; skip1 is the only evaluator that
  1437. moves onto the next token and it refuses to do so once it
  1438. reaches the last item in the list. */
  1439. notAtRoot,
  1440. /* We are not at the root of the ascent yet.
  1441. Move to the next level of the ascent by handing only
  1442. the tail to the previous expression */
  1443. compose2(previousExpr, tail)
  1444. );
  1445. }
  1446. /**
  1447. * Create an evaluator function for the .. (double dot) token. Consumes
  1448. * zero or more levels of the ascent, the fewest that are required to find
  1449. * a match when given to previousExpr.
  1450. */
  1451. function skipMany(previousExpr) {
  1452. if( previousExpr == always ) {
  1453. /* If there is no previous expression this consume command
  1454. is at the start of the jsonPath.
  1455. Since JSONPath specifies what we'd like to find but not
  1456. necessarily everything leading down to it, when running
  1457. out of JSONPath to check against we default to true */
  1458. return always;
  1459. }
  1460. var
  1461. // In JSONPath .. is equivalent to !.. so if .. reaches the root
  1462. // the match has succeeded. Ie, we might write ..foo or !..foo
  1463. // and both should match identically.
  1464. terminalCaseWhenArrivingAtRoot = rootExpr(),
  1465. terminalCaseWhenPreviousExpressionIsSatisfied = previousExpr,
  1466. recursiveCase = skip1(function(ascent) {
  1467. return cases(ascent);
  1468. }),
  1469. cases = lazyUnion(
  1470. terminalCaseWhenArrivingAtRoot
  1471. , terminalCaseWhenPreviousExpressionIsSatisfied
  1472. , recursiveCase
  1473. );
  1474. return cases;
  1475. }
  1476. /**
  1477. * Generate an evaluator for ! - matches only the root element of the json
  1478. * and ignores any previous expressions since nothing may precede !.
  1479. */
  1480. function rootExpr() {
  1481. return function(ascent){
  1482. return headKey(ascent) == ROOT_PATH;
  1483. };
  1484. }
  1485. /**
  1486. * Generate a statement wrapper to sit around the outermost
  1487. * clause evaluator.
  1488. *
  1489. * Handles the case where the capturing is implicit because the JSONPath
  1490. * did not contain a '$' by returning the last node.
  1491. */
  1492. function statementExpr(lastClause) {
  1493. return function(ascent) {
  1494. // kick off the evaluation by passing through to the last clause
  1495. var exprMatch = lastClause(ascent);
  1496. return exprMatch === true ? head(ascent) : exprMatch;
  1497. };
  1498. }
  1499. /**
  1500. * For when a token has been found in the JSONPath input.
  1501. * Compiles the parser for that token and returns in combination with the
  1502. * parser already generated.
  1503. *
  1504. * @param {Function} exprs a list of the clause evaluator generators for
  1505. * the token that was found
  1506. * @param {Function} parserGeneratedSoFar the parser already found
  1507. * @param {Array} detection the match given by the regex engine when
  1508. * the feature was found
  1509. */
  1510. function expressionsReader( exprs, parserGeneratedSoFar, detection ) {
  1511. // if exprs is zero-length foldR will pass back the
  1512. // parserGeneratedSoFar as-is so we don't need to treat
  1513. // this as a special case
  1514. return foldR(
  1515. function( parserGeneratedSoFar, expr ){
  1516. return expr(parserGeneratedSoFar, detection);
  1517. },
  1518. parserGeneratedSoFar,
  1519. exprs
  1520. );
  1521. }
  1522. /**
  1523. * If jsonPath matches the given detector function, creates a function which
  1524. * evaluates against every clause in the clauseEvaluatorGenerators. The
  1525. * created function is propagated to the onSuccess function, along with
  1526. * the remaining unparsed JSONPath substring.
  1527. *
  1528. * The intended use is to create a clauseMatcher by filling in
  1529. * the first two arguments, thus providing a function that knows
  1530. * some syntax to match and what kind of generator to create if it
  1531. * finds it. The parameter list once completed is:
  1532. *
  1533. * (jsonPath, parserGeneratedSoFar, onSuccess)
  1534. *
  1535. * onSuccess may be compileJsonPathToFunction, to recursively continue
  1536. * parsing after finding a match or returnFoundParser to stop here.
  1537. */
  1538. function generateClauseReaderIfTokenFound (
  1539. tokenDetector, clauseEvaluatorGenerators,
  1540. jsonPath, parserGeneratedSoFar, onSuccess) {
  1541. var detected = tokenDetector(jsonPath);
  1542. if(detected) {
  1543. var compiledParser = expressionsReader(
  1544. clauseEvaluatorGenerators,
  1545. parserGeneratedSoFar,
  1546. detected
  1547. ),
  1548. remainingUnparsedJsonPath = jsonPath.substr(len(detected[0]));
  1549. return onSuccess(remainingUnparsedJsonPath, compiledParser);
  1550. }
  1551. }
  1552. /**
  1553. * Partially completes generateClauseReaderIfTokenFound above.
  1554. */
  1555. function clauseMatcher(tokenDetector, exprs) {
  1556. return partialComplete(
  1557. generateClauseReaderIfTokenFound,
  1558. tokenDetector,
  1559. exprs
  1560. );
  1561. }
  1562. /**
  1563. * clauseForJsonPath is a function which attempts to match against
  1564. * several clause matchers in order until one matches. If non match the
  1565. * jsonPath expression is invalid and an error is thrown.
  1566. *
  1567. * The parameter list is the same as a single clauseMatcher:
  1568. *
  1569. * (jsonPath, parserGeneratedSoFar, onSuccess)
  1570. */
  1571. var clauseForJsonPath = lazyUnion(
  1572. clauseMatcher(pathNodeSyntax , list( capture,
  1573. duckTypeClause,
  1574. nameClause,
  1575. skip1 ))
  1576. , clauseMatcher(doubleDotSyntax , list( skipMany))
  1577. // dot is a separator only (like whitespace in other languages) but
  1578. // rather than make it a special case, use an empty list of
  1579. // expressions when this token is found
  1580. , clauseMatcher(dotSyntax , list() )
  1581. , clauseMatcher(bangSyntax , list( capture,
  1582. rootExpr))
  1583. , clauseMatcher(emptySyntax , list( statementExpr))
  1584. , function (jsonPath) {
  1585. throw Error('"' + jsonPath + '" could not be tokenised')
  1586. }
  1587. );
  1588. /**
  1589. * One of two possible values for the onSuccess argument of
  1590. * generateClauseReaderIfTokenFound.
  1591. *
  1592. * When this function is used, generateClauseReaderIfTokenFound simply
  1593. * returns the compiledParser that it made, regardless of if there is
  1594. * any remaining jsonPath to be compiled.
  1595. */
  1596. function returnFoundParser(_remainingJsonPath, compiledParser){
  1597. return compiledParser
  1598. }
  1599. /**
  1600. * Recursively compile a JSONPath expression.
  1601. *
  1602. * This function serves as one of two possible values for the onSuccess
  1603. * argument of generateClauseReaderIfTokenFound, meaning continue to
  1604. * recursively compile. Otherwise, returnFoundParser is given and
  1605. * compilation terminates.
  1606. */
  1607. function compileJsonPathToFunction( uncompiledJsonPath,
  1608. parserGeneratedSoFar ) {
  1609. /**
  1610. * On finding a match, if there is remaining text to be compiled
  1611. * we want to either continue parsing using a recursive call to
  1612. * compileJsonPathToFunction. Otherwise, we want to stop and return
  1613. * the parser that we have found so far.
  1614. */
  1615. var onFind = uncompiledJsonPath
  1616. ? compileJsonPathToFunction
  1617. : returnFoundParser;
  1618. return clauseForJsonPath(
  1619. uncompiledJsonPath,
  1620. parserGeneratedSoFar,
  1621. onFind
  1622. );
  1623. }
  1624. /**
  1625. * This is the function that we expose to the rest of the library.
  1626. */
  1627. return function(jsonPath){
  1628. try {
  1629. // Kick off the recursive parsing of the jsonPath
  1630. return compileJsonPathToFunction(jsonPath, always);
  1631. } catch( e ) {
  1632. throw Error( 'Could not compile "' + jsonPath +
  1633. '" because ' + e.message
  1634. );
  1635. }
  1636. }
  1637. });
  1638. /**
  1639. * A pub/sub which is responsible for a single event type. A
  1640. * multi-event type event bus is created by pubSub by collecting
  1641. * several of these.
  1642. *
  1643. * @param {String} eventType
  1644. * the name of the events managed by this singleEventPubSub
  1645. * @param {singleEventPubSub} [newListener]
  1646. * place to notify of new listeners
  1647. * @param {singleEventPubSub} [removeListener]
  1648. * place to notify of when listeners are removed
  1649. */
  1650. function singleEventPubSub(eventType, newListener, removeListener){
  1651. /** we are optimised for emitting events over firing them.
  1652. * As well as the tuple list which stores event ids and
  1653. * listeners there is a list with just the listeners which
  1654. * can be iterated more quickly when we are emitting
  1655. */
  1656. var listenerTupleList,
  1657. listenerList;
  1658. function hasId(id){
  1659. return function(tuple) {
  1660. return tuple.id == id;
  1661. };
  1662. }
  1663. return {
  1664. /**
  1665. * @param {Function} listener
  1666. * @param {*} listenerId
  1667. * an id that this listener can later by removed by.
  1668. * Can be of any type, to be compared to other ids using ==
  1669. */
  1670. on:function( listener, listenerId ) {
  1671. var tuple = {
  1672. listener: listener
  1673. , id: listenerId || listener // when no id is given use the
  1674. // listener function as the id
  1675. };
  1676. if( newListener ) {
  1677. newListener.emit(eventType, listener, tuple.id);
  1678. }
  1679. listenerTupleList = cons( tuple, listenerTupleList );
  1680. listenerList = cons( listener, listenerList );
  1681. return this; // chaining
  1682. },
  1683. emit:function () {
  1684. applyEach( listenerList, arguments );
  1685. },
  1686. un: function( listenerId ) {
  1687. var removed;
  1688. listenerTupleList = without(
  1689. listenerTupleList,
  1690. hasId(listenerId),
  1691. function(tuple){
  1692. removed = tuple;
  1693. }
  1694. );
  1695. if( removed ) {
  1696. listenerList = without( listenerList, function(listener){
  1697. return listener == removed.listener;
  1698. });
  1699. if( removeListener ) {
  1700. removeListener.emit(eventType, removed.listener, removed.id);
  1701. }
  1702. }
  1703. },
  1704. listeners: function(){
  1705. // differs from Node EventEmitter: returns list, not array
  1706. return listenerList;
  1707. },
  1708. hasListener: function(listenerId){
  1709. var test = listenerId? hasId(listenerId) : always;
  1710. return defined(first( test, listenerTupleList));
  1711. }
  1712. };
  1713. }
  1714. /**
  1715. * pubSub is a curried interface for listening to and emitting
  1716. * events.
  1717. *
  1718. * If we get a bus:
  1719. *
  1720. * var bus = pubSub();
  1721. *
  1722. * We can listen to event 'foo' like:
  1723. *
  1724. * bus('foo').on(myCallback)
  1725. *
  1726. * And emit event foo like:
  1727. *
  1728. * bus('foo').emit()
  1729. *
  1730. * or, with a parameter:
  1731. *
  1732. * bus('foo').emit('bar')
  1733. *
  1734. * All functions can be cached and don't need to be
  1735. * bound. Ie:
  1736. *
  1737. * var fooEmitter = bus('foo').emit
  1738. * fooEmitter('bar'); // emit an event
  1739. * fooEmitter('baz'); // emit another
  1740. *
  1741. * There's also an uncurried[1] shortcut for .emit and .on:
  1742. *
  1743. * bus.on('foo', callback)
  1744. * bus.emit('foo', 'bar')
  1745. *
  1746. * [1]: http://zvon.org/other/haskell/Outputprelude/uncurry_f.html
  1747. */
  1748. function pubSub(){
  1749. var singles = {},
  1750. newListener = newSingle('newListener'),
  1751. removeListener = newSingle('removeListener');
  1752. function newSingle(eventName) {
  1753. return singles[eventName] = singleEventPubSub(
  1754. eventName,
  1755. newListener,
  1756. removeListener
  1757. );
  1758. }
  1759. /** pubSub instances are functions */
  1760. function pubSubInstance( eventName ){
  1761. return singles[eventName] || newSingle( eventName );
  1762. }
  1763. // add convenience EventEmitter-style uncurried form of 'emit' and 'on'
  1764. ['emit', 'on', 'un'].forEach(function(methodName){
  1765. pubSubInstance[methodName] = varArgs(function(eventName, parameters){
  1766. apply( parameters, pubSubInstance( eventName )[methodName]);
  1767. });
  1768. });
  1769. return pubSubInstance;
  1770. }
  1771. /**
  1772. * This file declares some constants to use as names for event types.
  1773. */
  1774. var // the events which are never exported are kept as
  1775. // the smallest possible representation, in numbers:
  1776. _S = 1,
  1777. // fired whenever a new node starts in the JSON stream:
  1778. NODE_OPENED = _S++,
  1779. // fired whenever a node closes in the JSON stream:
  1780. NODE_CLOSED = _S++,
  1781. // called if a .node callback returns a value -
  1782. NODE_SWAP = _S++,
  1783. NODE_DROP = _S++,
  1784. FAIL_EVENT = 'fail',
  1785. ROOT_NODE_FOUND = _S++,
  1786. ROOT_PATH_FOUND = _S++,
  1787. HTTP_START = 'start',
  1788. STREAM_DATA = 'data',
  1789. STREAM_END = 'end',
  1790. ABORTING = _S++,
  1791. // SAX events butchered from Clarinet
  1792. SAX_KEY = _S++,
  1793. SAX_VALUE_OPEN = _S++,
  1794. SAX_VALUE_CLOSE = _S++;
  1795. function errorReport(statusCode, body, error) {
  1796. try{
  1797. var jsonBody = JSON.parse(body);
  1798. }catch(e){}
  1799. return {
  1800. statusCode:statusCode,
  1801. body:body,
  1802. jsonBody:jsonBody,
  1803. thrown:error
  1804. };
  1805. }
  1806. /**
  1807. * The pattern adaptor listens for newListener and removeListener
  1808. * events. When patterns are added or removed it compiles the JSONPath
  1809. * and wires them up.
  1810. *
  1811. * When nodes and paths are found it emits the fully-qualified match
  1812. * events with parameters ready to ship to the outside world
  1813. */
  1814. function patternAdapter(oboeBus, jsonPathCompiler) {
  1815. var predicateEventMap = {
  1816. node:oboeBus(NODE_CLOSED)
  1817. , path:oboeBus(NODE_OPENED)
  1818. };
  1819. function emitMatchingNode(emitMatch, node, ascent) {
  1820. /*
  1821. We're now calling to the outside world where Lisp-style
  1822. lists will not be familiar. Convert to standard arrays.
  1823. Also, reverse the order because it is more common to
  1824. list paths "root to leaf" than "leaf to root" */
  1825. var descent = reverseList(ascent);
  1826. emitMatch(
  1827. node,
  1828. // To make a path, strip off the last item which is the special
  1829. // ROOT_PATH token for the 'path' to the root node
  1830. listAsArray(tail(map(keyOf,descent))), // path
  1831. listAsArray(map(nodeOf, descent)) // ancestors
  1832. );
  1833. }
  1834. /*
  1835. * Set up the catching of events such as NODE_CLOSED and NODE_OPENED and, if
  1836. * matching the specified pattern, propagate to pattern-match events such as
  1837. * oboeBus('node:!')
  1838. *
  1839. *
  1840. *
  1841. * @param {Function} predicateEvent
  1842. * either oboeBus(NODE_CLOSED) or oboeBus(NODE_OPENED).
  1843. * @param {Function} compiledJsonPath
  1844. */
  1845. function addUnderlyingListener( fullEventName, predicateEvent, compiledJsonPath ){
  1846. var emitMatch = oboeBus(fullEventName).emit;
  1847. predicateEvent.on( function (ascent) {
  1848. var maybeMatchingMapping = compiledJsonPath(ascent);
  1849. /* Possible values for maybeMatchingMapping are now:
  1850. false:
  1851. we did not match
  1852. an object/array/string/number/null:
  1853. we matched and have the node that matched.
  1854. Because nulls are valid json values this can be null.
  1855. undefined:
  1856. we matched but don't have the matching node yet.
  1857. ie, we know there is an upcoming node that matches but we
  1858. can't say anything else about it.
  1859. */
  1860. if (maybeMatchingMapping !== false) {
  1861. emitMatchingNode(
  1862. emitMatch,
  1863. nodeOf(maybeMatchingMapping),
  1864. ascent
  1865. );
  1866. }
  1867. }, fullEventName);
  1868. oboeBus('removeListener').on( function(removedEventName){
  1869. // if the fully qualified match event listener is later removed, clean up
  1870. // by removing the underlying listener if it was the last using that pattern:
  1871. if( removedEventName == fullEventName ) {
  1872. if( !oboeBus(removedEventName).listeners( )) {
  1873. predicateEvent.un( fullEventName );
  1874. }
  1875. }
  1876. });
  1877. }
  1878. oboeBus('newListener').on( function(fullEventName){
  1879. var match = /(node|path):(.*)/.exec(fullEventName);
  1880. if( match ) {
  1881. var predicateEvent = predicateEventMap[match[1]];
  1882. if( !predicateEvent.hasListener( fullEventName) ) {
  1883. addUnderlyingListener(
  1884. fullEventName,
  1885. predicateEvent,
  1886. jsonPathCompiler( match[2] )
  1887. );
  1888. }
  1889. }
  1890. })
  1891. }
  1892. /**
  1893. * The instance API is the thing that is returned when oboe() is called.
  1894. * it allows:
  1895. *
  1896. * - listeners for various events to be added and removed
  1897. * - the http response header/headers to be read
  1898. */
  1899. function instanceApi(oboeBus, contentSource){
  1900. var oboeApi,
  1901. fullyQualifiedNamePattern = /^(node|path):./,
  1902. rootNodeFinishedEvent = oboeBus(ROOT_NODE_FOUND),
  1903. emitNodeDrop = oboeBus(NODE_DROP).emit,
  1904. emitNodeSwap = oboeBus(NODE_SWAP).emit,
  1905. /**
  1906. * Add any kind of listener that the instance api exposes
  1907. */
  1908. addListener = varArgs(function( eventId, parameters ){
  1909. if( oboeApi[eventId] ) {
  1910. // for events added as .on(event, callback), if there is a
  1911. // .event() equivalent with special behaviour , pass through
  1912. // to that:
  1913. apply(parameters, oboeApi[eventId]);
  1914. } else {
  1915. // we have a standard Node.js EventEmitter 2-argument call.
  1916. // The first parameter is the listener.
  1917. var event = oboeBus(eventId),
  1918. listener = parameters[0];
  1919. if( fullyQualifiedNamePattern.test(eventId) ) {
  1920. // allow fully-qualified node/path listeners
  1921. // to be added
  1922. addForgettableCallback(event, listener);
  1923. } else {
  1924. // the event has no special handling, pass through
  1925. // directly onto the event bus:
  1926. event.on( listener);
  1927. }
  1928. }
  1929. return oboeApi; // chaining
  1930. }),
  1931. /**
  1932. * Remove any kind of listener that the instance api exposes
  1933. */
  1934. removeListener = function( eventId, p2, p3 ){
  1935. if( eventId == 'done' ) {
  1936. rootNodeFinishedEvent.un(p2);
  1937. } else if( eventId == 'node' || eventId == 'path' ) {
  1938. // allow removal of node and path
  1939. oboeBus.un(eventId + ':' + p2, p3);
  1940. } else {
  1941. // we have a standard Node.js EventEmitter 2-argument call.
  1942. // The second parameter is the listener. This may be a call
  1943. // to remove a fully-qualified node/path listener but requires
  1944. // no special handling
  1945. var listener = p2;
  1946. oboeBus(eventId).un(listener);
  1947. }
  1948. return oboeApi; // chaining
  1949. };
  1950. /**
  1951. * Add a callback, wrapped in a try/catch so as to not break the
  1952. * execution of Oboe if an exception is thrown (fail events are
  1953. * fired instead)
  1954. *
  1955. * The callback is used as the listener id so that it can later be
  1956. * removed using .un(callback)
  1957. */
  1958. function addProtectedCallback(eventName, callback) {
  1959. oboeBus(eventName).on(protectedCallback(callback), callback);
  1960. return oboeApi; // chaining
  1961. }
  1962. /**
  1963. * Add a callback where, if .forget() is called during the callback's
  1964. * execution, the callback will be de-registered
  1965. */
  1966. function addForgettableCallback(event, callback, listenerId) {
  1967. // listenerId is optional and if not given, the original
  1968. // callback will be used
  1969. listenerId = listenerId || callback;
  1970. var safeCallback = protectedCallback(callback);
  1971. event.on( function() {
  1972. var discard = false;
  1973. oboeApi.forget = function(){
  1974. discard = true;
  1975. };
  1976. apply( arguments, safeCallback );
  1977. delete oboeApi.forget;
  1978. if( discard ) {
  1979. event.un(listenerId);
  1980. }
  1981. }, listenerId);
  1982. return oboeApi; // chaining
  1983. }
  1984. /**
  1985. * wrap a callback so that if it throws, Oboe.js doesn't crash but instead
  1986. * handles it like a normal error
  1987. */
  1988. function protectedCallback( callback ) {
  1989. return function() {
  1990. try{
  1991. return callback.apply(oboeApi, arguments);
  1992. }catch(e) {
  1993. // An error occured during the callback, publish it on the event bus
  1994. oboeBus(FAIL_EVENT).emit( errorReport(undefined, undefined, e));
  1995. }
  1996. }
  1997. }
  1998. /**
  1999. * Return the fully qualified event for when a pattern matches
  2000. * either a node or a path
  2001. *
  2002. * @param type {String} either 'node' or 'path'
  2003. */
  2004. function fullyQualifiedPatternMatchEvent(type, pattern) {
  2005. return oboeBus(type + ':' + pattern);
  2006. }
  2007. function wrapCallbackToSwapNodeIfSomethingReturned( callback ) {
  2008. return function() {
  2009. var returnValueFromCallback = callback.apply(this, arguments);
  2010. if( defined(returnValueFromCallback) ) {
  2011. if( returnValueFromCallback == oboe.drop ) {
  2012. emitNodeDrop();
  2013. } else {
  2014. emitNodeSwap(returnValueFromCallback);
  2015. }
  2016. }
  2017. }
  2018. }
  2019. function addSingleNodeOrPathListener(eventId, pattern, callback) {
  2020. var effectiveCallback;
  2021. if( eventId == 'node' ) {
  2022. effectiveCallback = wrapCallbackToSwapNodeIfSomethingReturned(callback);
  2023. } else {
  2024. effectiveCallback = callback;
  2025. }
  2026. addForgettableCallback(
  2027. fullyQualifiedPatternMatchEvent(eventId, pattern),
  2028. effectiveCallback,
  2029. callback
  2030. );
  2031. }
  2032. /**
  2033. * Add several listeners at a time, from a map
  2034. */
  2035. function addMultipleNodeOrPathListeners(eventId, listenerMap) {
  2036. for( var pattern in listenerMap ) {
  2037. addSingleNodeOrPathListener(eventId, pattern, listenerMap[pattern]);
  2038. }
  2039. }
  2040. /**
  2041. * implementation behind .onPath() and .onNode()
  2042. */
  2043. function addNodeOrPathListenerApi( eventId, jsonPathOrListenerMap, callback ){
  2044. if( isString(jsonPathOrListenerMap) ) {
  2045. addSingleNodeOrPathListener(eventId, jsonPathOrListenerMap, callback);
  2046. } else {
  2047. addMultipleNodeOrPathListeners(eventId, jsonPathOrListenerMap);
  2048. }
  2049. return oboeApi; // chaining
  2050. }
  2051. // some interface methods are only filled in after we receive
  2052. // values and are noops before that:
  2053. oboeBus(ROOT_PATH_FOUND).on( function(rootNode) {
  2054. oboeApi.root = functor(rootNode);
  2055. });
  2056. /**
  2057. * When content starts make the headers readable through the
  2058. * instance API
  2059. */
  2060. oboeBus(HTTP_START).on( function(_statusCode, headers) {
  2061. oboeApi.header = function(name) {
  2062. return name ? headers[name]
  2063. : headers
  2064. ;
  2065. }
  2066. });
  2067. /**
  2068. * Construct and return the public API of the Oboe instance to be
  2069. * returned to the calling application
  2070. */
  2071. return oboeApi = {
  2072. on : addListener,
  2073. addListener : addListener,
  2074. removeListener : removeListener,
  2075. emit : oboeBus.emit,
  2076. node : partialComplete(addNodeOrPathListenerApi, 'node'),
  2077. path : partialComplete(addNodeOrPathListenerApi, 'path'),
  2078. done : partialComplete(addForgettableCallback, rootNodeFinishedEvent),
  2079. start : partialComplete(addProtectedCallback, HTTP_START ),
  2080. // fail doesn't use protectedCallback because
  2081. // could lead to non-terminating loops
  2082. fail : oboeBus(FAIL_EVENT).on,
  2083. // public api calling abort fires the ABORTING event
  2084. abort : oboeBus(ABORTING).emit,
  2085. // initially return nothing for header and root
  2086. header : noop,
  2087. root : noop,
  2088. source : contentSource
  2089. };
  2090. }
  2091. /**
  2092. * This file sits just behind the API which is used to attain a new
  2093. * Oboe instance. It creates the new components that are required
  2094. * and introduces them to each other.
  2095. */
  2096. function wire (httpMethodName, contentSource, body, headers, withCredentials){
  2097. var oboeBus = pubSub();
  2098. // Wire the input stream in if we are given a content source.
  2099. // This will usually be the case. If not, the instance created
  2100. // will have to be passed content from an external source.
  2101. if( contentSource ) {
  2102. streamingHttp( oboeBus,
  2103. httpTransport(),
  2104. httpMethodName,
  2105. contentSource,
  2106. body,
  2107. headers,
  2108. withCredentials
  2109. );
  2110. }
  2111. clarinet(oboeBus);
  2112. ascentManager(oboeBus, incrementalContentBuilder(oboeBus));
  2113. patternAdapter(oboeBus, jsonPathCompiler);
  2114. return instanceApi(oboeBus, contentSource);
  2115. }
  2116. function applyDefaults( passthrough, url, httpMethodName, body, headers, withCredentials, cached ){
  2117. headers = headers ?
  2118. // Shallow-clone the headers array. This allows it to be
  2119. // modified without side effects to the caller. We don't
  2120. // want to change objects that the user passes in.
  2121. JSON.parse(JSON.stringify(headers))
  2122. : {};
  2123. if( body ) {
  2124. if( !isString(body) ) {
  2125. // If the body is not a string, stringify it. This allows objects to
  2126. // be given which will be sent as JSON.
  2127. body = JSON.stringify(body);
  2128. // Default Content-Type to JSON unless given otherwise.
  2129. headers['Content-Type'] = headers['Content-Type'] || 'application/json';
  2130. }
  2131. } else {
  2132. body = null;
  2133. }
  2134. // support cache busting like jQuery.ajax({cache:false})
  2135. function modifiedUrl(baseUrl, cached) {
  2136. if( cached === false ) {
  2137. if( baseUrl.indexOf('?') == -1 ) {
  2138. baseUrl += '?';
  2139. } else {
  2140. baseUrl += '&';
  2141. }
  2142. baseUrl += '_=' + new Date().getTime();
  2143. }
  2144. return baseUrl;
  2145. }
  2146. return passthrough( httpMethodName || 'GET', modifiedUrl(url, cached), body, headers, withCredentials || false );
  2147. }
  2148. // export public API
  2149. function oboe(arg1) {
  2150. // We use duck-typing to detect if the parameter given is a stream, with the
  2151. // below list of parameters.
  2152. // Unpipe and unshift would normally be present on a stream but this breaks
  2153. // compatibility with Request streams.
  2154. // See https://github.com/jimhigson/oboe.js/issues/65
  2155. var nodeStreamMethodNames = list('resume', 'pause', 'pipe'),
  2156. isStream = partialComplete(
  2157. hasAllProperties
  2158. , nodeStreamMethodNames
  2159. );
  2160. if( arg1 ) {
  2161. if (isStream(arg1) || isString(arg1)) {
  2162. // simple version for GETs. Signature is:
  2163. // oboe( url )
  2164. // or, under node:
  2165. // oboe( readableStream )
  2166. return applyDefaults(
  2167. wire,
  2168. arg1 // url
  2169. );
  2170. } else {
  2171. // method signature is:
  2172. // oboe({method:m, url:u, body:b, headers:{...}})
  2173. return applyDefaults(
  2174. wire,
  2175. arg1.url,
  2176. arg1.method,
  2177. arg1.body,
  2178. arg1.headers,
  2179. arg1.withCredentials,
  2180. arg1.cached
  2181. );
  2182. }
  2183. } else {
  2184. // wire up a no-AJAX, no-stream Oboe. Will have to have content
  2185. // fed in externally and using .emit.
  2186. return wire();
  2187. }
  2188. }
  2189. /* oboe.drop is a special value. If a node callback returns this value the
  2190. parsed node is deleted from the JSON
  2191. */
  2192. oboe.drop = function() {
  2193. return oboe.drop;
  2194. };
  2195. if ( typeof define === "function" && define.amd ) {
  2196. define( "oboe", [], function () { return oboe; } );
  2197. } else if (typeof exports === 'object') {
  2198. module.exports = oboe;
  2199. } else {
  2200. window.oboe = oboe;
  2201. }
  2202. })((function(){
  2203. // Access to the window object throws an exception in HTML5 web workers so
  2204. // point it to "self" if it runs in a web worker
  2205. try {
  2206. return window;
  2207. } catch (e) {
  2208. return self;
  2209. }
  2210. }()), Object, Array, Error, JSON);