parse.js 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933
  1. 'use strict';
  2. var test = require('tape');
  3. var hasPropertyDescriptors = require('has-property-descriptors')();
  4. var iconv = require('iconv-lite');
  5. var mockProperty = require('mock-property');
  6. var hasOverrideMistake = require('has-override-mistake')();
  7. var SaferBuffer = require('safer-buffer').Buffer;
  8. var v = require('es-value-fixtures');
  9. var inspect = require('object-inspect');
  10. var emptyTestCases = require('./empty-keys-cases').emptyTestCases;
  11. var hasProto = require('has-proto')();
  12. var qs = require('../');
  13. var utils = require('../lib/utils');
  14. var characterizeParse = function characterizeParse(st, input, opts, expected, label) {
  15. var result;
  16. st.doesNotThrow(function () { result = qs.parse(input, opts); }, label + ': does not throw');
  17. st.deepEqual(result, expected, label + ': parses to the current lenient output');
  18. };
  19. test('parse()', function (t) {
  20. t.test('parses a simple string', function (st) {
  21. st.deepEqual(qs.parse('0=foo'), { 0: 'foo' });
  22. st.deepEqual(qs.parse('foo=c++'), { foo: 'c ' });
  23. st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } });
  24. st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } });
  25. st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } });
  26. st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null });
  27. st.deepEqual(qs.parse('foo'), { foo: '' });
  28. st.deepEqual(qs.parse('foo='), { foo: '' });
  29. st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' });
  30. st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' });
  31. st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' });
  32. st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' });
  33. st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' });
  34. st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null });
  35. st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' });
  36. st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), {
  37. cht: 'p3',
  38. chd: 't:60,40',
  39. chs: '250x100',
  40. chl: 'Hello|World'
  41. });
  42. st.end();
  43. });
  44. t.test('comma: false', function (st) {
  45. st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] });
  46. st.deepEqual(qs.parse('a[0]=b&a[1]=c'), { a: ['b', 'c'] });
  47. st.deepEqual(qs.parse('a=b,c'), { a: 'b,c' });
  48. st.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] });
  49. st.end();
  50. });
  51. t.test('comma: true', function (st) {
  52. st.deepEqual(qs.parse('a[]=b&a[]=c', { comma: true }), { a: ['b', 'c'] });
  53. st.deepEqual(qs.parse('a[0]=b&a[1]=c', { comma: true }), { a: ['b', 'c'] });
  54. st.deepEqual(qs.parse('a=b,c', { comma: true }), { a: ['b', 'c'] });
  55. st.deepEqual(qs.parse('a=b&a=c', { comma: true }), { a: ['b', 'c'] });
  56. st.end();
  57. });
  58. t.test('allows enabling dot notation', function (st) {
  59. st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' });
  60. st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } });
  61. st.end();
  62. });
  63. t.test('decode dot keys correctly', function (st) {
  64. st.deepEqual(
  65. qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: false, decodeDotInKeys: false }),
  66. { 'name%2Eobj.first': 'John', 'name%2Eobj.last': 'Doe' },
  67. 'with allowDots false and decodeDotInKeys false'
  68. );
  69. st.deepEqual(
  70. qs.parse('name.obj.first=John&name.obj.last=Doe', { allowDots: true, decodeDotInKeys: false }),
  71. { name: { obj: { first: 'John', last: 'Doe' } } },
  72. 'with allowDots false and decodeDotInKeys false'
  73. );
  74. st.deepEqual(
  75. qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: true, decodeDotInKeys: false }),
  76. { 'name%2Eobj': { first: 'John', last: 'Doe' } },
  77. 'with allowDots true and decodeDotInKeys false'
  78. );
  79. st.deepEqual(
  80. qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe', { allowDots: true, decodeDotInKeys: true }),
  81. { 'name.obj': { first: 'John', last: 'Doe' } },
  82. 'with allowDots true and decodeDotInKeys true'
  83. );
  84. st.deepEqual(
  85. qs.parse(
  86. 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe',
  87. { allowDots: false, decodeDotInKeys: false }
  88. ),
  89. { 'name%2Eobj%2Esubobject.first%2Egodly%2Ename': 'John', 'name%2Eobj%2Esubobject.last': 'Doe' },
  90. 'with allowDots false and decodeDotInKeys false'
  91. );
  92. st.deepEqual(
  93. qs.parse(
  94. 'name.obj.subobject.first.godly.name=John&name.obj.subobject.last=Doe',
  95. { allowDots: true, decodeDotInKeys: false }
  96. ),
  97. { name: { obj: { subobject: { first: { godly: { name: 'John' } }, last: 'Doe' } } } },
  98. 'with allowDots true and decodeDotInKeys false'
  99. );
  100. st.deepEqual(
  101. qs.parse(
  102. 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe',
  103. { allowDots: true, decodeDotInKeys: true }
  104. ),
  105. { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } },
  106. 'with allowDots true and decodeDotInKeys true'
  107. );
  108. st.deepEqual(
  109. qs.parse('name%252Eobj.first=John&name%252Eobj.last=Doe'),
  110. { 'name%2Eobj.first': 'John', 'name%2Eobj.last': 'Doe' },
  111. 'with allowDots and decodeDotInKeys undefined'
  112. );
  113. st.end();
  114. });
  115. t.test('decodes dot in key of object, and allow enabling dot notation when decodeDotInKeys is set to true and allowDots is undefined', function (st) {
  116. st.deepEqual(
  117. qs.parse(
  118. 'name%252Eobj%252Esubobject.first%252Egodly%252Ename=John&name%252Eobj%252Esubobject.last=Doe',
  119. { decodeDotInKeys: true }
  120. ),
  121. { 'name.obj.subobject': { 'first.godly.name': 'John', last: 'Doe' } },
  122. 'with allowDots undefined and decodeDotInKeys true'
  123. );
  124. st.end();
  125. });
  126. t.test('throws when decodeDotInKeys is not of type boolean', function (st) {
  127. st['throws'](
  128. function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: 'foobar' }); },
  129. TypeError
  130. );
  131. st['throws'](
  132. function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: 0 }); },
  133. TypeError
  134. );
  135. st['throws'](
  136. function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: NaN }); },
  137. TypeError
  138. );
  139. st['throws'](
  140. function () { qs.parse('foo[]&bar=baz', { decodeDotInKeys: null }); },
  141. TypeError
  142. );
  143. st.end();
  144. });
  145. t.test('allows empty arrays in obj values', function (st) {
  146. st.deepEqual(qs.parse('foo[]&bar=baz', { allowEmptyArrays: true }), { foo: [], bar: 'baz' });
  147. st.deepEqual(qs.parse('foo[]&bar=baz', { allowEmptyArrays: false }), { foo: [''], bar: 'baz' });
  148. st.end();
  149. });
  150. t.test('throws when allowEmptyArrays is not of type boolean', function (st) {
  151. st['throws'](
  152. function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: 'foobar' }); },
  153. TypeError
  154. );
  155. st['throws'](
  156. function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: 0 }); },
  157. TypeError
  158. );
  159. st['throws'](
  160. function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: NaN }); },
  161. TypeError
  162. );
  163. st['throws'](
  164. function () { qs.parse('foo[]&bar=baz', { allowEmptyArrays: null }); },
  165. TypeError
  166. );
  167. st.end();
  168. });
  169. t.test('allowEmptyArrays + strictNullHandling', function (st) {
  170. st.deepEqual(
  171. qs.parse('testEmptyArray[]', { strictNullHandling: true, allowEmptyArrays: true }),
  172. { testEmptyArray: [] }
  173. );
  174. st.end();
  175. });
  176. t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string');
  177. t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string');
  178. t.deepEqual(
  179. qs.parse('a[b][c][d][e][f][g][h]=i'),
  180. { a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } },
  181. 'defaults to a depth of 5'
  182. );
  183. t.test('only parses one level when depth = 1', function (st) {
  184. st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } });
  185. st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } });
  186. st.end();
  187. });
  188. t.test('uses original key when depth = 0', function (st) {
  189. st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: 0 }), { 'a[0]': 'b', 'a[1]': 'c' });
  190. st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: 0 }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' });
  191. st.deepEqual(qs.parse('a.b=c', { depth: 0, allowDots: true }), { 'a[b]': 'c' }, 'normalizes dots before applying depth-0 behavior');
  192. st.deepEqual(qs.parse('toString=foo', { depth: 0 }), {}, 'respects prototype guard at depth 0');
  193. st.deepEqual(qs.parse('toString=foo', { depth: 0, allowPrototypes: true }), { toString: 'foo' }, 'allows prototypes at depth 0 when enabled');
  194. st.end();
  195. });
  196. t.test('ignores prototype keys when depth = 0 and allowPrototypes is false', function (st) {
  197. st.deepEqual(qs.parse('toString=foo', { depth: 0 }), {});
  198. st.deepEqual(qs.parse('hasOwnProperty=bar', { depth: 0 }), {});
  199. st.deepEqual(qs.parse('toString=foo&a=b', { depth: 0 }), { a: 'b' });
  200. st.end();
  201. });
  202. t.test('allows prototype keys when depth = 0 and allowPrototypes is true', function (st) {
  203. st.deepEqual(qs.parse('toString=foo', { depth: 0, allowPrototypes: true }), { toString: 'foo' });
  204. st.end();
  205. });
  206. t.test('uses original key when depth = false', function (st) {
  207. st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: false }), { 'a[0]': 'b', 'a[1]': 'c' });
  208. st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: false }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' });
  209. st.end();
  210. });
  211. t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array');
  212. t.test('parses an explicit array', function (st) {
  213. st.deepEqual(qs.parse('a[]=b'), { a: ['b'] });
  214. st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] });
  215. st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] });
  216. st.end();
  217. });
  218. t.test('parses a mix of simple and explicit arrays', function (st) {
  219. st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] });
  220. st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] });
  221. st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] });
  222. st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] });
  223. st.deepEqual(qs.parse('a[1]=b&a=c', { arrayLimit: 20 }), { a: ['b', 'c'] });
  224. st.deepEqual(qs.parse('a[]=b&a=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } });
  225. st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] });
  226. st.deepEqual(qs.parse('a=b&a[1]=c', { arrayLimit: 20 }), { a: ['b', 'c'] });
  227. st.deepEqual(qs.parse('a=b&a[]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } });
  228. st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] });
  229. st.end();
  230. });
  231. t.test('parses a nested array', function (st) {
  232. st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } });
  233. st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } });
  234. st.end();
  235. });
  236. t.test('parses keys with literal [] inside a bracket group (#493)', function (st) {
  237. // A bracket pair inside a bracket group should be treated literally as part of the key
  238. st.deepEqual(
  239. qs.parse('search[withbracket[]]=foobar'),
  240. { search: { 'withbracket[]': 'foobar' } },
  241. 'treats inner [] literally when inside a bracket group'
  242. );
  243. // Single-level variant
  244. st.deepEqual(
  245. qs.parse('a[b[]]=c'),
  246. { a: { 'b[]': 'c' } },
  247. 'keeps "b[]" as a literal key'
  248. );
  249. // Nested with an array push on the outer level
  250. st.deepEqual(
  251. qs.parse('list[][x[]]=y'),
  252. { list: [{ 'x[]': 'y' }] },
  253. 'preserves inner [] while still treating outer [] as array push'
  254. );
  255. // Multiple nested bracket pairs: inner [] remains literal as part of the key
  256. st.deepEqual(
  257. qs.parse('a[b[c[]]]=d'),
  258. { a: { 'b[c[]]': 'd' } },
  259. 'treats "b[c[]]" as a literal key inside the bracket group'
  260. );
  261. // Depth limits with literal brackets: preserve inner [] while limiting bracket-group parsing
  262. st.deepEqual(
  263. qs.parse('a[b[c[]]][d]=e', { depth: 1 }),
  264. { a: { 'b[c[]]': { '[d]': 'e' } } },
  265. 'respects depth: 1 and preserves literal inner [] in the parsed key'
  266. );
  267. // Unterminated inner bracket group is wrapped as a literal remainder segment
  268. st.deepEqual(
  269. qs.parse('a[[]b=c'),
  270. { a: { '[[]b': 'c' } },
  271. 'handles unterminated inner bracket groups without throwing'
  272. );
  273. st.end();
  274. });
  275. t.test('currently parses unbalanced bracket keys after a parent leniently to literal segments (issue #558)', function (st) {
  276. characterizeParse(st, 'a[bc=v', undefined, { a: { '[bc': 'v' } }, 'unclosed group after a parent');
  277. characterizeParse(st, 'a[=v', undefined, { a: { '[': 'v' } }, 'bare unclosed bracket after a parent');
  278. characterizeParse(st, 'a[b][c=v', undefined, { a: { b: { '[c': 'v' } } }, 'unclosed group after a valid one');
  279. characterizeParse(st, 'a[b]c[d=v', undefined, { a: { b: { '[d': 'v' } } }, 'unclosed group after text following a valid one');
  280. characterizeParse(st, 'filters[customtags:Env: Prod=v', undefined, { filters: { '[customtags:Env: Prod': 'v' } }, 'the issue #558 reproduction');
  281. characterizeParse(st, '][a=v', undefined, { ']': { '[a': 'v' } }, 'stray close bracket before an unclosed group');
  282. characterizeParse(st, 'a][b=v', undefined, { 'a]': { '[b': 'v' } }, 'stray close bracket inside the parent');
  283. st.end();
  284. });
  285. t.test('currently parses unbalanced bracket keys containing inner brackets leniently (issue #558)', function (st) {
  286. characterizeParse(st, 'a[b[c=v', undefined, { a: { '[b[c': 'v' } }, 'unclosed group containing an inner bracket');
  287. characterizeParse(st, 'a[b[c]=v', undefined, { a: { '[b[c]': 'v' } }, 'unbalanced group with an inner bracket and one close');
  288. characterizeParse(st, 'a[b][c[d=v', undefined, { a: { b: { '[c[d': 'v' } } }, 'unclosed inner-bracket group after a valid one');
  289. st.end();
  290. });
  291. t.test('currently parses bracket-prefixed unbalanced keys leniently (issue #558)', function (st) {
  292. characterizeParse(st, '[abc=v', undefined, { '[abc': 'v' }, 'key starting with an unclosed bracket');
  293. characterizeParse(st, '[[]b=v', undefined, { '[[]b': 'v' }, 'key starting with an unbalanced bracket group');
  294. st.end();
  295. });
  296. t.test('lenient unbalanced-bracket handling currently depends on the depth option (issue #558)', function (st) {
  297. characterizeParse(st, 'a[b]c[d]e[f=v', { depth: 5 }, { a: { b: { d: { '[f': 'v' } } } }, 'consumes groups up to the depth budget then keeps the unclosed remainder literal');
  298. characterizeParse(st, 'a[b]c[d]e[f=v', { depth: 1 }, { a: { b: { '[d]e[f': 'v' } } }, 'a lower depth keeps more of the unclosed remainder literal');
  299. characterizeParse(st, 'a[bc=v', { depth: 0 }, { 'a[bc': 'v' }, 'depth 0 keeps the entire key literal');
  300. st.end();
  301. });
  302. t.test('currently parses an allowDots key with a trailing unclosed bracket leniently (issue #558)', function (st) {
  303. characterizeParse(st, 'a.b[c=v', { allowDots: true }, { a: { b: { '[c': 'v' } } }, 'allowDots expands the dot then keeps the unclosed bracket literal');
  304. st.end();
  305. });
  306. t.test('valid and stray-close bracket keys are unaffected by unbalanced-bracket handling', function (st) {
  307. characterizeParse(st, 'a]b=v', undefined, { 'a]b': 'v' }, 'stray close bracket with no open bracket stays a flat key');
  308. characterizeParse(st, 'a[b]extra=v', undefined, { a: { b: 'v' } }, 'text after a balanced group is ignored');
  309. st.end();
  310. });
  311. t.test('allows to specify array indices', function (st) {
  312. st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] });
  313. st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] });
  314. st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 20 }), { a: ['c'] });
  315. st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 0 }), { a: { 1: 'c' } });
  316. st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] });
  317. st.end();
  318. });
  319. t.test('limits specific array indices to arrayLimit', function (st) {
  320. st.deepEqual(qs.parse('a[19]=a', { arrayLimit: 20 }), { a: ['a'] });
  321. st.deepEqual(qs.parse('a[20]=a', { arrayLimit: 20 }), { a: { 20: 'a' } });
  322. st.deepEqual(qs.parse('a[19]=a'), { a: ['a'] });
  323. st.deepEqual(qs.parse('a[20]=a'), { a: { 20: 'a' } });
  324. st.end();
  325. });
  326. t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number');
  327. t.test('supports encoded = signs', function (st) {
  328. st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' });
  329. st.end();
  330. });
  331. t.test('is ok with url encoded strings', function (st) {
  332. st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } });
  333. st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } });
  334. st.end();
  335. });
  336. t.test('allows brackets in the value', function (st) {
  337. st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' });
  338. st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' });
  339. st.end();
  340. });
  341. t.test('allows empty values', function (st) {
  342. st.deepEqual(qs.parse(''), {});
  343. st.deepEqual(qs.parse(null), {});
  344. st.deepEqual(qs.parse(undefined), {});
  345. st.end();
  346. });
  347. t.test('transforms arrays to objects', function (st) {
  348. st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } });
  349. st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', 0: 'bar' } });
  350. st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', 0: 'bar' } });
  351. st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } });
  352. st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } });
  353. st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
  354. st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: false }), { a: { 0: 'b', t: 'u' } });
  355. st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: true }), { a: { 0: 'b', t: 'u', hasOwnProperty: 'c' } });
  356. st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: false }), { a: { 0: 'b', x: 'y' } });
  357. st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: true }), { a: { 0: 'b', hasOwnProperty: 'c', x: 'y' } });
  358. st.end();
  359. });
  360. t.test('transforms arrays to objects (dot notation)', function (st) {
  361. st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } });
  362. st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } });
  363. st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } });
  364. st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] });
  365. st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] });
  366. st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } });
  367. st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } });
  368. st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { 0: 'bar', bad: 'baz' } });
  369. st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } });
  370. st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
  371. st.end();
  372. });
  373. t.test('correctly prunes undefined values when converting an array to an object', function (st) {
  374. st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { 2: 'b', 99999999: 'c' } });
  375. st.end();
  376. });
  377. t.test('supports malformed uri characters', function (st) {
  378. st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null });
  379. st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' });
  380. st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' });
  381. st.end();
  382. });
  383. t.test('doesn\'t produce empty keys', function (st) {
  384. st.deepEqual(qs.parse('_r=1&'), { _r: '1' });
  385. st.end();
  386. });
  387. t.test('cannot access Object prototype', function (st) {
  388. qs.parse('constructor[prototype][bad]=bad');
  389. qs.parse('bad[constructor][prototype][bad]=bad');
  390. st.equal(typeof Object.prototype.bad, 'undefined');
  391. st.end();
  392. });
  393. t.test('parses arrays of objects', function (st) {
  394. st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] });
  395. st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] });
  396. st.end();
  397. });
  398. t.test('allows for empty strings in arrays', function (st) {
  399. st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] });
  400. st.deepEqual(
  401. qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }),
  402. { a: ['b', null, 'c', ''] },
  403. 'with arrayLimit 20 + array indices: null then empty string works'
  404. );
  405. st.deepEqual(
  406. qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }),
  407. { a: { 0: 'b', 1: null, 2: 'c', 3: '' } },
  408. 'with arrayLimit 0 + array brackets: null then empty string works'
  409. );
  410. st.deepEqual(
  411. qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }),
  412. { a: ['b', '', 'c', null] },
  413. 'with arrayLimit 20 + array indices: empty string then null works'
  414. );
  415. st.deepEqual(
  416. qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }),
  417. { a: { 0: 'b', 1: '', 2: 'c', 3: null } },
  418. 'with arrayLimit 0 + array brackets: empty string then null works'
  419. );
  420. st.deepEqual(
  421. qs.parse('a[]=&a[]=b&a[]=c'),
  422. { a: ['', 'b', 'c'] },
  423. 'array brackets: empty strings work'
  424. );
  425. st.end();
  426. });
  427. t.test('compacts sparse arrays', function (st) {
  428. st.deepEqual(qs.parse('a[10]=1&a[2]=2', { arrayLimit: 20 }), { a: ['2', '1'] });
  429. st.deepEqual(qs.parse('a[1][b][2][c]=1', { arrayLimit: 20 }), { a: [{ b: [{ c: '1' }] }] });
  430. st.deepEqual(qs.parse('a[1][2][3][c]=1', { arrayLimit: 20 }), { a: [[[{ c: '1' }]]] });
  431. st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { arrayLimit: 20 }), { a: [[[{ c: ['1'] }]]] });
  432. st.end();
  433. });
  434. t.test('parses sparse arrays', function (st) {
  435. /* eslint no-sparse-arrays: 0 */
  436. st.deepEqual(qs.parse('a[4]=1&a[1]=2', { allowSparse: true }), { a: [, '2', , , '1'] });
  437. st.deepEqual(qs.parse('a[1][b][2][c]=1', { allowSparse: true }), { a: [, { b: [, , { c: '1' }] }] });
  438. st.deepEqual(qs.parse('a[1][2][3][c]=1', { allowSparse: true }), { a: [, [, , [, , , { c: '1' }]]] });
  439. st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { allowSparse: true }), { a: [, [, , [, , , { c: [, '1'] }]]] });
  440. st.end();
  441. });
  442. t.test('parses semi-parsed strings', function (st) {
  443. st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } });
  444. st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } });
  445. st.end();
  446. });
  447. t.test('parses buffers correctly', function (st) {
  448. var b = SaferBuffer.from('test');
  449. st.deepEqual(qs.parse({ a: b }), { a: b });
  450. st.end();
  451. });
  452. t.test('parses jquery-param strings', function (st) {
  453. // readable = 'filter[0][]=int1&filter[0][]==&filter[0][]=77&filter[]=and&filter[2][]=int2&filter[2][]==&filter[2][]=8'
  454. var encoded = 'filter%5B0%5D%5B%5D=int1&filter%5B0%5D%5B%5D=%3D&filter%5B0%5D%5B%5D=77&filter%5B%5D=and&filter%5B2%5D%5B%5D=int2&filter%5B2%5D%5B%5D=%3D&filter%5B2%5D%5B%5D=8';
  455. var expected = { filter: [['int1', '=', '77'], 'and', ['int2', '=', '8']] };
  456. st.deepEqual(qs.parse(encoded), expected);
  457. st.end();
  458. });
  459. t.test('continues parsing when no parent is found', function (st) {
  460. st.deepEqual(qs.parse('[]=&a=b'), { 0: '', a: 'b' });
  461. st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { 0: null, a: 'b' });
  462. st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' });
  463. st.end();
  464. });
  465. t.test('does not error when parsing a very long array', function (st) {
  466. var str = 'a[]=a';
  467. while (Buffer.byteLength(str) < 128 * 1024) {
  468. str = str + '&' + str;
  469. }
  470. st.doesNotThrow(function () {
  471. qs.parse(str);
  472. });
  473. st.end();
  474. });
  475. t.test('does not throw when a native prototype has an enumerable property', function (st) {
  476. st.intercept(Object.prototype, 'crash', { value: '' });
  477. st.intercept(Array.prototype, 'crash', { value: '' });
  478. st.doesNotThrow(qs.parse.bind(null, 'a=b'));
  479. st.deepEqual(qs.parse('a=b'), { a: 'b' });
  480. st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c'));
  481. st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] });
  482. st.end();
  483. });
  484. t.test('parses a string with an alternative string delimiter', function (st) {
  485. st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' });
  486. st.end();
  487. });
  488. t.test('parses a string with an alternative RegExp delimiter', function (st) {
  489. st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' });
  490. st.end();
  491. });
  492. t.test('does not use non-splittable objects as delimiters', function (st) {
  493. st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' });
  494. st.end();
  495. });
  496. t.test('allows overriding parameter limit', function (st) {
  497. st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' });
  498. st.end();
  499. });
  500. t.test('allows setting the parameter limit to Infinity', function (st) {
  501. st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' });
  502. st.end();
  503. });
  504. t.test('allows overriding array limit', function (st) {
  505. st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { 0: 'b' } });
  506. st.deepEqual(qs.parse('a[0]=b', { arrayLimit: 0 }), { a: { 0: 'b' } });
  507. st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } });
  508. st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: 0 }), { a: { '-1': 'b' } });
  509. st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: -1 }), { a: { 0: 'b', 1: 'c' } });
  510. st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } });
  511. st.end();
  512. });
  513. t.test('allows disabling array parsing', function (st) {
  514. var indices = qs.parse('a[0]=b&a[1]=c', { parseArrays: false });
  515. st.deepEqual(indices, { a: { 0: 'b', 1: 'c' } });
  516. st.equal(Array.isArray(indices.a), false, 'parseArrays:false, indices case is not an array');
  517. var emptyBrackets = qs.parse('a[]=b', { parseArrays: false });
  518. st.deepEqual(emptyBrackets, { a: { 0: 'b' } });
  519. st.equal(Array.isArray(emptyBrackets.a), false, 'parseArrays:false, empty brackets case is not an array');
  520. st.end();
  521. });
  522. t.test('allows for query string prefix', function (st) {
  523. st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' });
  524. st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' });
  525. st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' });
  526. st.end();
  527. });
  528. t.test('parses an object', function (st) {
  529. var input = {
  530. 'user[name]': { 'pop[bob]': 3 },
  531. 'user[email]': null
  532. };
  533. var expected = {
  534. user: {
  535. name: { 'pop[bob]': 3 },
  536. email: null
  537. }
  538. };
  539. var result = qs.parse(input);
  540. st.deepEqual(result, expected);
  541. st.end();
  542. });
  543. t.test('parses string with comma as array divider', function (st) {
  544. st.deepEqual(qs.parse('foo=bar,tee', { comma: true }), { foo: ['bar', 'tee'] });
  545. st.deepEqual(qs.parse('foo[bar]=coffee,tee', { comma: true }), { foo: { bar: ['coffee', 'tee'] } });
  546. st.deepEqual(qs.parse('foo=', { comma: true }), { foo: '' });
  547. st.deepEqual(qs.parse('foo', { comma: true }), { foo: '' });
  548. st.deepEqual(qs.parse('foo', { comma: true, strictNullHandling: true }), { foo: null });
  549. // test cases inversed from from stringify tests
  550. st.deepEqual(qs.parse('a[0]=c'), { a: ['c'] });
  551. st.deepEqual(qs.parse('a[]=c'), { a: ['c'] });
  552. st.deepEqual(qs.parse('a[]=c', { comma: true }), { a: ['c'] });
  553. st.deepEqual(qs.parse('a[0]=c&a[1]=d'), { a: ['c', 'd'] });
  554. st.deepEqual(qs.parse('a[]=c&a[]=d'), { a: ['c', 'd'] });
  555. st.deepEqual(qs.parse('a=c,d', { comma: true }), { a: ['c', 'd'] });
  556. st.end();
  557. });
  558. t.test('parses values with comma as array divider', function (st) {
  559. st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: false }), { foo: 'bar,tee' });
  560. st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: true }), { foo: ['bar', 'tee'] });
  561. st.end();
  562. });
  563. t.test('use number decoder, parses string that has one number with comma option enabled', function (st) {
  564. var decoder = function (str, defaultDecoder, charset, type) {
  565. if (!isNaN(Number(str))) {
  566. return parseFloat(str);
  567. }
  568. return defaultDecoder(str, defaultDecoder, charset, type);
  569. };
  570. st.deepEqual(qs.parse('foo=1', { comma: true, decoder: decoder }), { foo: 1 });
  571. st.deepEqual(qs.parse('foo=0', { comma: true, decoder: decoder }), { foo: 0 });
  572. st.end();
  573. });
  574. t.test('parses brackets holds array of arrays when having two parts of strings with comma as array divider', function (st) {
  575. st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=4,5,6', { comma: true }), { foo: [['1', '2', '3'], ['4', '5', '6']] });
  576. st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=', { comma: true }), { foo: [['1', '2', '3'], ''] });
  577. st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=,', { comma: true }), { foo: [['1', '2', '3'], ['', '']] });
  578. st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=a', { comma: true }), { foo: [['1', '2', '3'], 'a'] });
  579. st.end();
  580. });
  581. t.test('parses url-encoded brackets holds array of arrays when having two parts of strings with comma as array divider', function (st) {
  582. st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=4,5,6', { comma: true }), { foo: [['1', '2', '3'], ['4', '5', '6']] });
  583. st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=', { comma: true }), { foo: [['1', '2', '3'], ''] });
  584. st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=,', { comma: true }), { foo: [['1', '2', '3'], ['', '']] });
  585. st.deepEqual(qs.parse('foo%5B%5D=1,2,3&foo%5B%5D=a', { comma: true }), { foo: [['1', '2', '3'], 'a'] });
  586. st.end();
  587. });
  588. t.test('parses comma delimited array while having percent-encoded comma treated as normal text', function (st) {
  589. st.deepEqual(qs.parse('foo=a%2Cb', { comma: true }), { foo: 'a,b' });
  590. st.deepEqual(qs.parse('foo=a%2C%20b,d', { comma: true }), { foo: ['a, b', 'd'] });
  591. st.deepEqual(qs.parse('foo=a%2C%20b,c%2C%20d', { comma: true }), { foo: ['a, b', 'c, d'] });
  592. st.end();
  593. });
  594. t.test('parses an object in dot notation', function (st) {
  595. var input = {
  596. 'user.name': { 'pop[bob]': 3 },
  597. 'user.email.': null
  598. };
  599. var expected = {
  600. user: {
  601. name: { 'pop[bob]': 3 },
  602. email: null
  603. }
  604. };
  605. var result = qs.parse(input, { allowDots: true });
  606. st.deepEqual(result, expected);
  607. st.end();
  608. });
  609. t.test('parses an object and not child values', function (st) {
  610. var input = {
  611. 'user[name]': { 'pop[bob]': { test: 3 } },
  612. 'user[email]': null
  613. };
  614. var expected = {
  615. user: {
  616. name: { 'pop[bob]': { test: 3 } },
  617. email: null
  618. }
  619. };
  620. var result = qs.parse(input);
  621. st.deepEqual(result, expected);
  622. st.end();
  623. });
  624. t.test('does not blow up when Buffer global is missing', function (st) {
  625. var restore = mockProperty(global, 'Buffer', { 'delete': true });
  626. var result = qs.parse('a=b&c=d');
  627. restore();
  628. st.deepEqual(result, { a: 'b', c: 'd' });
  629. st.end();
  630. });
  631. t.test('does not crash when parsing circular references', function (st) {
  632. var a = {};
  633. a.b = a;
  634. var parsed;
  635. st.doesNotThrow(function () {
  636. parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a });
  637. });
  638. st.equal('foo' in parsed, true, 'parsed has "foo" property');
  639. st.equal('bar' in parsed.foo, true);
  640. st.equal('baz' in parsed.foo, true);
  641. st.equal(parsed.foo.bar, 'baz');
  642. st.deepEqual(parsed.foo.baz, a);
  643. st.end();
  644. });
  645. t.test('does not crash on multi-step circular references', function (st) {
  646. var a = {};
  647. a.b = { c: { d: a } };
  648. var parsed;
  649. st.doesNotThrow(function () {
  650. parsed = qs.parse({ foo: a });
  651. });
  652. st.equal('foo' in parsed, true, 'parsed has "foo" property');
  653. st.equal(parsed.foo.b.c.d, parsed.foo, 'the multi-step cycle is preserved');
  654. st.end();
  655. });
  656. t.test('does not crash when parsing deep objects', function (st) {
  657. var parsed;
  658. var str = 'foo';
  659. for (var i = 0; i < 5000; i++) {
  660. str += '[p]';
  661. }
  662. str += '=bar';
  663. st.doesNotThrow(function () {
  664. parsed = qs.parse(str, { depth: 5000 });
  665. });
  666. st.equal('foo' in parsed, true, 'parsed has "foo" property');
  667. var depth = 0;
  668. var ref = parsed.foo;
  669. while ((ref = ref.p)) {
  670. depth += 1;
  671. }
  672. st.equal(depth, 5000, 'parsed is 5000 properties deep');
  673. st.end();
  674. });
  675. t.test('parses null objects correctly', { skip: !hasProto }, function (st) {
  676. var a = { __proto__: null, b: 'c' };
  677. st.deepEqual(qs.parse(a), { b: 'c' });
  678. var result = qs.parse({ a: a });
  679. st.equal('a' in result, true, 'result has "a" property');
  680. st.deepEqual(result.a, a);
  681. st.end();
  682. });
  683. t.test('parses dates correctly', function (st) {
  684. var now = new Date();
  685. st.deepEqual(qs.parse({ a: now }), { a: now });
  686. st.end();
  687. });
  688. t.test('parses regular expressions correctly', function (st) {
  689. var re = /^test$/;
  690. st.deepEqual(qs.parse({ a: re }), { a: re });
  691. st.end();
  692. });
  693. t.test('does not allow overwriting prototype properties', function (st) {
  694. st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: false }), {});
  695. st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: false }), {});
  696. st.deepEqual(
  697. qs.parse('toString', { allowPrototypes: false }),
  698. {},
  699. 'bare "toString" results in {}'
  700. );
  701. st.end();
  702. });
  703. t.test('can allow overwriting prototype properties', function (st) {
  704. st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } });
  705. st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' });
  706. st.deepEqual(
  707. qs.parse('toString', { allowPrototypes: true }),
  708. { toString: '' },
  709. 'bare "toString" results in { toString: "" }'
  710. );
  711. st.end();
  712. });
  713. t.test('does not crash when the global Object prototype is frozen', { skip: !hasPropertyDescriptors || !hasOverrideMistake }, function (st) {
  714. // We can't actually freeze the global Object prototype as that will interfere with other tests, and once an object is frozen, it
  715. // can't be unfrozen. Instead, we add a new non-writable property to simulate this.
  716. st.teardown(mockProperty(Object.prototype, 'frozenProp', { value: 'foo', nonWritable: true, nonEnumerable: true }));
  717. st['throws'](
  718. function () {
  719. var obj = {};
  720. obj.frozenProp = 'bar';
  721. },
  722. // node < 6 has a different error message
  723. /^TypeError: Cannot assign to read only property 'frozenProp' of (?:object '#<Object>'|#<Object>)/,
  724. 'regular assignment of an inherited non-writable property throws'
  725. );
  726. var parsed;
  727. st.doesNotThrow(
  728. function () {
  729. parsed = qs.parse('frozenProp', { allowPrototypes: false });
  730. },
  731. 'parsing a nonwritable Object.prototype property does not throw'
  732. );
  733. st.deepEqual(parsed, {}, 'bare "frozenProp" results in {}');
  734. st.end();
  735. });
  736. t.test('params starting with a closing bracket', function (st) {
  737. st.deepEqual(qs.parse(']=toString'), { ']': 'toString' });
  738. st.deepEqual(qs.parse(']]=toString'), { ']]': 'toString' });
  739. st.deepEqual(qs.parse(']hello]=toString'), { ']hello]': 'toString' });
  740. st.end();
  741. });
  742. t.test('params starting with a starting bracket', function (st) {
  743. st.deepEqual(qs.parse('[=toString'), { '[': 'toString' });
  744. st.deepEqual(qs.parse('[[=toString'), { '[[': 'toString' });
  745. st.deepEqual(qs.parse('[hello[=toString'), { '[hello[': 'toString' });
  746. st.end();
  747. });
  748. t.test('add keys to objects', function (st) {
  749. st.deepEqual(
  750. qs.parse('a[b]=c&a=d', { strictMerge: false }),
  751. { a: { b: 'c', d: true } },
  752. 'can add keys to objects'
  753. );
  754. st.deepEqual(
  755. qs.parse('a[b]=c&a=toString', { strictMerge: false }),
  756. { a: { b: 'c' } },
  757. 'can not overwrite prototype'
  758. );
  759. st.deepEqual(
  760. qs.parse('a[b]=c&a=toString', { strictMerge: false, allowPrototypes: true }),
  761. { a: { b: 'c', toString: true } },
  762. 'can overwrite prototype with allowPrototypes true'
  763. );
  764. st.deepEqual(
  765. qs.parse('a[b]=c&a=toString', { strictMerge: false, plainObjects: true }),
  766. { __proto__: null, a: { __proto__: null, b: 'c', toString: true } },
  767. 'can overwrite prototype with plainObjects true'
  768. );
  769. st.end();
  770. });
  771. t.test('strictMerge wraps object and primitive into an array', function (st) {
  772. st.deepEqual(
  773. qs.parse('a[b]=c&a=d'),
  774. { a: [{ b: 'c' }, 'd'] },
  775. 'object then primitive produces array'
  776. );
  777. st.deepEqual(
  778. qs.parse('a=d&a[b]=c'),
  779. { a: ['d', { b: 'c' }] },
  780. 'primitive then object produces array'
  781. );
  782. st.deepEqual(
  783. qs.parse('a[b]=c&a=toString'),
  784. { a: [{ b: 'c' }, 'toString'] },
  785. 'prototype-colliding value is preserved in array'
  786. );
  787. st.deepEqual(
  788. qs.parse('a[b]=c&a=toString', { plainObjects: true }),
  789. { __proto__: null, a: [{ __proto__: null, b: 'c' }, 'toString'] },
  790. 'plainObjects preserved in array wrapping'
  791. );
  792. st.end();
  793. });
  794. t.test('dunder proto is ignored', function (st) {
  795. var payload = 'categories[__proto__]=login&categories[__proto__]&categories[length]=42';
  796. var result = qs.parse(payload, { allowPrototypes: true });
  797. st.deepEqual(
  798. result,
  799. {
  800. categories: {
  801. length: '42'
  802. }
  803. },
  804. 'silent [[Prototype]] payload'
  805. );
  806. var plainResult = qs.parse(payload, { allowPrototypes: true, plainObjects: true });
  807. st.deepEqual(
  808. plainResult,
  809. {
  810. __proto__: null,
  811. categories: {
  812. __proto__: null,
  813. length: '42'
  814. }
  815. },
  816. 'silent [[Prototype]] payload: plain objects'
  817. );
  818. var query = qs.parse('categories[__proto__]=cats&categories[__proto__]=dogs&categories[some][json]=toInject', { allowPrototypes: true });
  819. st.notOk(Array.isArray(query.categories), 'is not an array');
  820. st.notOk(query.categories instanceof Array, 'is not instanceof an array');
  821. st.deepEqual(query.categories, { some: { json: 'toInject' } });
  822. st.equal(JSON.stringify(query.categories), '{"some":{"json":"toInject"}}', 'stringifies as a non-array');
  823. st.deepEqual(
  824. qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true }),
  825. {
  826. foo: {
  827. bar: 'stuffs'
  828. }
  829. },
  830. 'hidden values'
  831. );
  832. st.deepEqual(
  833. qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true, plainObjects: true }),
  834. {
  835. __proto__: null,
  836. foo: {
  837. __proto__: null,
  838. bar: 'stuffs'
  839. }
  840. },
  841. 'hidden values: plain objects'
  842. );
  843. st.end();
  844. });
  845. t.test('object-valued input with own `__proto__` does not mutate sub-object [[Prototype]]', function (st) {
  846. // JSON.parse creates own data `__proto__` properties (via CreateDataProperty),
  847. // which would trigger the Object.prototype.__proto__ accessor if merged via `acc[key] = value`.
  848. var out = qs.parse({
  849. 'user[name]': 'alice',
  850. user: JSON.parse('{"__proto__":{"isAdmin":true}}')
  851. }, { allowPrototypes: false });
  852. st.equal(out.user.name, 'alice', 'name from bracket key is preserved');
  853. st.equal(out.user.isAdmin, undefined, 'attacker-controlled inherited property is not exposed');
  854. st.equal(Object.getPrototypeOf(out.user), Object.prototype, 'sub-object [[Prototype]] is unchanged');
  855. st.equal(Object.prototype.isAdmin, undefined, 'Object.prototype is not polluted');
  856. st.end();
  857. });
  858. t.test('can return null objects', { skip: !hasProto }, function (st) {
  859. var expected = {
  860. __proto__: null,
  861. a: {
  862. __proto__: null,
  863. b: 'c',
  864. hasOwnProperty: 'd'
  865. }
  866. };
  867. st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected);
  868. st.deepEqual(qs.parse(null, { plainObjects: true }), { __proto__: null });
  869. var expectedArray = {
  870. __proto__: null,
  871. a: {
  872. __proto__: null,
  873. 0: 'b',
  874. c: 'd'
  875. }
  876. };
  877. st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray);
  878. st.end();
  879. });
  880. t.test('can parse with custom encoding', function (st) {
  881. st.deepEqual(qs.parse('%8c%a7=%91%e5%8d%e3%95%7b', {
  882. decoder: function (str) {
  883. var reg = /%([0-9A-F]{2})/ig;
  884. var result = [];
  885. var parts = reg.exec(str);
  886. while (parts) {
  887. result.push(parseInt(parts[1], 16));
  888. parts = reg.exec(str);
  889. }
  890. return String(iconv.decode(SaferBuffer.from(result), 'shift_jis'));
  891. }
  892. }), { 県: '大阪府' });
  893. st.end();
  894. });
  895. t.test('receives the default decoder as a second argument', function (st) {
  896. st.plan(1);
  897. qs.parse('a', {
  898. decoder: function (str, defaultDecoder) {
  899. st.equal(defaultDecoder, utils.decode);
  900. }
  901. });
  902. st.end();
  903. });
  904. t.test('throws error with wrong decoder', function (st) {
  905. st['throws'](function () {
  906. qs.parse({}, { decoder: 'string' });
  907. }, new TypeError('Decoder has to be a function.'));
  908. st.end();
  909. });
  910. t.test('does not mutate the options argument', function (st) {
  911. var options = {};
  912. qs.parse('a[b]=true', options);
  913. st.deepEqual(options, {});
  914. st.end();
  915. });
  916. t.test('throws if an invalid charset is specified', function (st) {
  917. st['throws'](function () {
  918. qs.parse('a=b', { charset: 'foobar' });
  919. }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'));
  920. st.end();
  921. });
  922. t.test('parses an iso-8859-1 string if asked to', function (st) {
  923. st.deepEqual(qs.parse('%A2=%BD', { charset: 'iso-8859-1' }), { '¢': '½' });
  924. st.end();
  925. });
  926. var urlEncodedCheckmarkInUtf8 = '%E2%9C%93';
  927. var urlEncodedOSlashInUtf8 = '%C3%B8';
  928. var urlEncodedNumCheckmark = '%26%2310003%3B';
  929. var urlEncodedNumSmiley = '%26%239786%3B';
  930. t.test('prefers an utf-8 charset specified by the utf8 sentinel to a default charset of iso-8859-1', function (st) {
  931. st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'iso-8859-1' }), { ø: 'ø' });
  932. st.end();
  933. });
  934. t.test('prefers an iso-8859-1 charset specified by the utf8 sentinel to a default charset of utf-8', function (st) {
  935. st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { 'ø': 'ø' });
  936. st.end();
  937. });
  938. t.test('does not require the utf8 sentinel to be defined before the parameters whose decoding it affects', function (st) {
  939. st.deepEqual(qs.parse('a=' + urlEncodedOSlashInUtf8 + '&utf8=' + urlEncodedNumCheckmark, { charsetSentinel: true, charset: 'utf-8' }), { a: 'ø' });
  940. st.end();
  941. });
  942. t.test('ignores an utf8 sentinel with an unknown value', function (st) {
  943. st.deepEqual(qs.parse('utf8=foo&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { ø: 'ø' });
  944. st.end();
  945. });
  946. t.test('uses the utf8 sentinel to switch to utf-8 when no default charset is given', function (st) {
  947. st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { ø: 'ø' });
  948. st.end();
  949. });
  950. t.test('uses the utf8 sentinel to switch to iso-8859-1 when no default charset is given', function (st) {
  951. st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { 'ø': 'ø' });
  952. st.end();
  953. });
  954. t.test('interprets numeric entities in iso-8859-1 when `interpretNumericEntities`', function (st) {
  955. st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1', interpretNumericEntities: true }), { foo: '☺' });
  956. st.end();
  957. });
  958. t.test('handles a custom decoder returning `null`, in the `iso-8859-1` charset, when `interpretNumericEntities`', function (st) {
  959. st.deepEqual(qs.parse('foo=&bar=' + urlEncodedNumSmiley, {
  960. charset: 'iso-8859-1',
  961. decoder: function (str, defaultDecoder, charset) {
  962. return str ? defaultDecoder(str, defaultDecoder, charset) : null;
  963. },
  964. interpretNumericEntities: true
  965. }), { foo: null, bar: '☺' });
  966. st.end();
  967. });
  968. t.test('handles a custom decoder returning `null`, with a string key of `null`', function (st) {
  969. st.deepEqual(
  970. qs.parse('null=1&ToNull=2', {
  971. decoder: function (str, defaultDecoder, charset) {
  972. return str === 'ToNull' ? null : defaultDecoder(str, defaultDecoder, charset);
  973. }
  974. }),
  975. { 'null': '1' },
  976. '"null" key is not overridden by `null` decoder result'
  977. );
  978. st.end();
  979. });
  980. t.test('does not interpret numeric entities in iso-8859-1 when `interpretNumericEntities` is absent', function (st) {
  981. st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1' }), { foo: '&#9786;' });
  982. st.end();
  983. });
  984. t.test('does not interpret numeric entities when the charset is utf-8, even when `interpretNumericEntities`', function (st) {
  985. st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'utf-8', interpretNumericEntities: true }), { foo: '&#9786;' });
  986. st.end();
  987. });
  988. t.test('interpretNumericEntities with comma:true and iso charset does not crash', function (st) {
  989. st.deepEqual(
  990. qs.parse('b&a[]=1,' + urlEncodedNumSmiley, { comma: true, charset: 'iso-8859-1', interpretNumericEntities: true }),
  991. { b: '', a: ['1,☺'] }
  992. );
  993. st.end();
  994. });
  995. t.test('does not interpret %uXXXX syntax in iso-8859-1 mode', function (st) {
  996. st.deepEqual(qs.parse('%u263A=%u263A', { charset: 'iso-8859-1' }), { '%u263A': '%u263A' });
  997. st.end();
  998. });
  999. t.test('allows for decoding keys and values differently', function (st) {
  1000. var decoder = function (str, defaultDecoder, charset, type) {
  1001. if (type === 'key') {
  1002. return defaultDecoder(str, defaultDecoder, charset, type).toLowerCase();
  1003. }
  1004. if (type === 'value') {
  1005. return defaultDecoder(str, defaultDecoder, charset, type).toUpperCase();
  1006. }
  1007. throw 'this should never happen! type: ' + type;
  1008. };
  1009. st.deepEqual(qs.parse('KeY=vAlUe', { decoder: decoder }), { key: 'VALUE' });
  1010. var noopDecoder = function () { return 'x'; };
  1011. noopDecoder();
  1012. st['throws'](
  1013. function () { decoder('x', noopDecoder, 'utf-8', 'unknown'); },
  1014. 'this should never happen! type: unknown',
  1015. 'decoder throws for unexpected type'
  1016. );
  1017. st.end();
  1018. });
  1019. t.test('parameter limit tests', function (st) {
  1020. st.test('does not throw error when within parameter limit', function (sst) {
  1021. var result = qs.parse('a=1&b=2&c=3', { parameterLimit: 5, throwOnLimitExceeded: true });
  1022. sst.deepEqual(result, { a: '1', b: '2', c: '3' }, 'parses without errors');
  1023. sst.end();
  1024. });
  1025. st.test('throws error when throwOnLimitExceeded is present but not boolean', function (sst) {
  1026. sst['throws'](
  1027. function () {
  1028. qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: 3, throwOnLimitExceeded: 'true' });
  1029. },
  1030. new TypeError('`throwOnLimitExceeded` option must be a boolean'),
  1031. 'throws error when throwOnLimitExceeded is present and not boolean'
  1032. );
  1033. sst.end();
  1034. });
  1035. st.test('throws error when parameter limit exceeded', function (sst) {
  1036. sst['throws'](
  1037. function () {
  1038. qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: 3, throwOnLimitExceeded: true });
  1039. },
  1040. new RangeError('Parameter limit exceeded. Only 3 parameters allowed.'),
  1041. 'throws error when parameter limit is exceeded'
  1042. );
  1043. sst['throws'](
  1044. function () {
  1045. qs.parse('a=1&b=2', { parameterLimit: 1, throwOnLimitExceeded: true });
  1046. },
  1047. new RangeError('Parameter limit exceeded. Only 1 parameter allowed.'),
  1048. 'throws error with singular "parameter" when parameterLimit is 1'
  1049. );
  1050. sst.end();
  1051. });
  1052. st.test('silently truncates when throwOnLimitExceeded is not given', function (sst) {
  1053. var result = qs.parse('a=1&b=2&c=3&d=4&e=5', { parameterLimit: 3 });
  1054. sst.deepEqual(result, { a: '1', b: '2', c: '3' }, 'parses and truncates silently');
  1055. sst.end();
  1056. });
  1057. st.test('silently truncates when parameter limit exceeded without error', function (sst) {
  1058. var result = qs.parse('a=1&b=2&c=3&d=4&e=5', { parameterLimit: 3, throwOnLimitExceeded: false });
  1059. sst.deepEqual(result, { a: '1', b: '2', c: '3' }, 'parses and truncates silently');
  1060. sst.end();
  1061. });
  1062. st.test('allows unlimited parameters when parameterLimit set to Infinity', function (sst) {
  1063. var result = qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: Infinity });
  1064. sst.deepEqual(result, { a: '1', b: '2', c: '3', d: '4', e: '5', f: '6' }, 'parses all parameters without truncation');
  1065. sst.end();
  1066. });
  1067. st.test('allows unlimited parameters when parameterLimit is Infinity and throwOnLimitExceeded is true', function (sst) {
  1068. var result = qs.parse('a=1&b=2&c=3&d=4&e=5&f=6', { parameterLimit: Infinity, throwOnLimitExceeded: true });
  1069. sst.deepEqual(result, { a: '1', b: '2', c: '3', d: '4', e: '5', f: '6' }, 'parses all parameters without truncation or throwing');
  1070. sst.end();
  1071. });
  1072. st.end();
  1073. });
  1074. t.test('array limit tests', function (st) {
  1075. st.test('does not throw error when array is within limit', function (sst) {
  1076. var result = qs.parse('a[]=1&a[]=2&a[]=3', { arrayLimit: 5, throwOnLimitExceeded: true });
  1077. sst.deepEqual(result, { a: ['1', '2', '3'] }, 'parses array without errors');
  1078. sst.end();
  1079. });
  1080. st.test('throws error when throwOnLimitExceeded is present but not boolean for array limit', function (sst) {
  1081. sst['throws'](
  1082. function () {
  1083. qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3, throwOnLimitExceeded: 'true' });
  1084. },
  1085. new TypeError('`throwOnLimitExceeded` option must be a boolean'),
  1086. 'throws error when throwOnLimitExceeded is present and not boolean for array limit'
  1087. );
  1088. sst.end();
  1089. });
  1090. st.test('throws error when array limit exceeded', function (sst) {
  1091. // 4 elements exceeds limit of 3
  1092. sst['throws'](
  1093. function () {
  1094. qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3, throwOnLimitExceeded: true });
  1095. },
  1096. new RangeError('Array limit exceeded. Only 3 elements allowed in an array.'),
  1097. 'throws error when array limit is exceeded'
  1098. );
  1099. sst.end();
  1100. });
  1101. st.test('does not throw when at limit', function (sst) {
  1102. // 3 elements = limit of 3, should not throw
  1103. var result = qs.parse('a[]=1&a[]=2&a[]=3', { arrayLimit: 3, throwOnLimitExceeded: true });
  1104. sst.ok(Array.isArray(result.a), 'result is an array');
  1105. sst.deepEqual(result.a, ['1', '2', '3'], 'all values present');
  1106. sst.end();
  1107. });
  1108. st.test('converts array to object if length is greater than limit', function (sst) {
  1109. var result = qs.parse('a[1]=1&a[2]=2&a[3]=3&a[4]=4&a[5]=5&a[6]=6', { arrayLimit: 5 });
  1110. sst.deepEqual(result, { a: { 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6' } }, 'parses into object if array length is greater than limit');
  1111. sst.end();
  1112. });
  1113. st.test('throws error when indexed notation exceeds arrayLimit with throwOnLimitExceeded', function (sst) {
  1114. sst['throws'](
  1115. function () {
  1116. qs.parse('a[1001]=b', { arrayLimit: 1000, throwOnLimitExceeded: true });
  1117. },
  1118. new RangeError('Array limit exceeded. Only 1000 elements allowed in an array.'),
  1119. 'throws error for a single index exceeding arrayLimit'
  1120. );
  1121. sst['throws'](
  1122. function () {
  1123. qs.parse('a[0]=1&a[1]=2&a[2]=3&a[10]=4', { arrayLimit: 6, throwOnLimitExceeded: true, allowSparse: true });
  1124. },
  1125. new RangeError('Array limit exceeded. Only 6 elements allowed in an array.'),
  1126. 'throws error when a sparse index exceeds arrayLimit'
  1127. );
  1128. sst['throws'](
  1129. function () {
  1130. qs.parse('a[2]=b', { arrayLimit: 1, throwOnLimitExceeded: true });
  1131. },
  1132. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1133. 'throws error with singular "element" when arrayLimit is 1'
  1134. );
  1135. sst.end();
  1136. });
  1137. st.test('does not throw for indexed notation within arrayLimit with throwOnLimitExceeded', function (sst) {
  1138. var result = qs.parse('a[4]=b', { arrayLimit: 5, throwOnLimitExceeded: true, allowSparse: true });
  1139. sst.ok(Array.isArray(result.a), 'result is an array');
  1140. sst.equal(result.a.length, 5, 'array has correct length');
  1141. sst.equal(result.a[4], 'b', 'value at index 4 is correct');
  1142. sst.end();
  1143. });
  1144. st.test('silently converts to object for indexed notation exceeding arrayLimit without throwOnLimitExceeded', function (sst) {
  1145. var result = qs.parse('a[1001]=b', { arrayLimit: 1000 });
  1146. sst.deepEqual(result, { a: { 1001: 'b' } }, 'converts to object without throwing');
  1147. sst.end();
  1148. });
  1149. st.test('throws when duplicate bracket keys exceed arrayLimit with throwOnLimitExceeded', function (sst) {
  1150. sst['throws'](
  1151. function () {
  1152. qs.parse('a[]=1&a[]=2&a[]=3&a[]=4&a[]=5&a[]=6', { arrayLimit: 5, throwOnLimitExceeded: true });
  1153. },
  1154. new RangeError('Array limit exceeded. Only 5 elements allowed in an array.'),
  1155. 'throws error when duplicate bracket notation exceeds array limit'
  1156. );
  1157. sst.end();
  1158. });
  1159. st.test('throws when cumulative comma + duplicate-key combine exceeds arrayLimit', function (sst) {
  1160. sst['throws'](
  1161. function () {
  1162. qs.parse('a=1,2,3&a=4,5,6', { comma: true, arrayLimit: 5, throwOnLimitExceeded: true });
  1163. },
  1164. new RangeError('Array limit exceeded. Only 5 elements allowed in an array.'),
  1165. 'throws when comma groups within the limit cumulatively exceed it across duplicate keys'
  1166. );
  1167. sst['throws'](
  1168. function () {
  1169. qs.parse('a=v,v,v,v,v&a=v,v,v,v,v&a=v,v,v,v,v', { comma: true, arrayLimit: 5, throwOnLimitExceeded: true });
  1170. },
  1171. new RangeError('Array limit exceeded. Only 5 elements allowed in an array.'),
  1172. 'throws on a subsequent part once the cumulative array is already over the limit'
  1173. );
  1174. sst.end();
  1175. });
  1176. st.test('throws when plain duplicate keys combine past arrayLimit at the boundary', function (sst) {
  1177. sst['throws'](
  1178. function () { qs.parse('a=x&a=y', { arrayLimit: 1, throwOnLimitExceeded: true }); },
  1179. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1180. 'duplicate scalar keys'
  1181. );
  1182. sst['throws'](
  1183. function () { qs.parse('a[]=x&a[]=y', { arrayLimit: 1, throwOnLimitExceeded: true }); },
  1184. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1185. 'duplicate bracket keys'
  1186. );
  1187. sst.end();
  1188. });
  1189. st.test('throws when mixed index and key notation merge past arrayLimit', function (sst) {
  1190. sst['throws'](
  1191. function () { qs.parse('a=x&a[0]=y', { arrayLimit: 1, throwOnLimitExceeded: true }); },
  1192. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1193. 'scalar then index that overflows on merge'
  1194. );
  1195. sst['throws'](
  1196. function () { qs.parse('a[0]=1&a[1]=2&a=3', { arrayLimit: 1, throwOnLimitExceeded: true }); },
  1197. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1198. 'indexed array then scalar that overflows on merge'
  1199. );
  1200. sst.end();
  1201. });
  1202. st.test('enforces arrayLimit on merge at the boundary, consistently with combine', function (sst) {
  1203. sst['throws'](
  1204. function () { qs.parse('a[0]=x&a=y', { arrayLimit: 1, throwOnLimitExceeded: true }); },
  1205. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1206. 'a trailing scalar merged into an at-limit array throws'
  1207. );
  1208. sst.deepEqual(
  1209. qs.parse('a[0]=x&a=y', { arrayLimit: 1 }),
  1210. { a: { 0: 'x', 1: 'y' } },
  1211. 'and converts to an overflow object without throwOnLimitExceeded'
  1212. );
  1213. sst['throws'](
  1214. function () { qs.parse('a[0]=x&a[]=y', { arrayLimit: 1, throwOnLimitExceeded: true }); },
  1215. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1216. 'mixed index and bracket notation merged past the limit throws'
  1217. );
  1218. sst.deepEqual(
  1219. qs.parse('a[0]=x&a[]=y', { arrayLimit: 1 }),
  1220. { a: { 0: 'x', 1: 'y' } },
  1221. 'mixed index and bracket notation converts like duplicate-bracket combine'
  1222. );
  1223. sst.end();
  1224. });
  1225. st.test('does not throw when cumulative comma combine stays within arrayLimit', function (sst) {
  1226. var result = qs.parse('a=1,2,3&a=4', { comma: true, arrayLimit: 5, throwOnLimitExceeded: true });
  1227. sst.deepEqual(result, { a: ['1', '2', '3', '4'] }, 'combined array within limit is preserved');
  1228. sst.end();
  1229. });
  1230. st.test('silently combines to an overflow object when throwOnLimitExceeded is not set', function (sst) {
  1231. var result = qs.parse('a=1,2,3&a=4,5,6', { comma: true, arrayLimit: 5 });
  1232. sst.deepEqual(result, { a: { 0: '1', 1: '2', 2: '3', 3: '4', 4: '5', 5: '6' } }, 'converts to object without throwing');
  1233. sst.end();
  1234. });
  1235. st.test('does not throw for comma groups nested under bracket notation, counting each group as one element', function (sst) {
  1236. var result = qs.parse('a[]=1,2,3&a[]=4,5,6', { comma: true, arrayLimit: 5, throwOnLimitExceeded: true });
  1237. sst.deepEqual(result, { a: [['1', '2', '3'], ['4', '5', '6']] }, 'nested comma groups count as one element each');
  1238. sst.end();
  1239. });
  1240. st.test('throws before splitting when a single comma value exceeds arrayLimit', function (sst) {
  1241. sst['throws'](
  1242. function () {
  1243. qs.parse('a=1,2,3,4,5,6', { comma: true, arrayLimit: 5, throwOnLimitExceeded: true });
  1244. },
  1245. new RangeError('Array limit exceeded. Only 5 elements allowed in an array.'),
  1246. 'a flat comma value over the limit throws'
  1247. );
  1248. sst['throws'](
  1249. function () {
  1250. qs.parse('a=1,2', { comma: true, arrayLimit: 1, throwOnLimitExceeded: true });
  1251. },
  1252. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1253. 'singular message at arrayLimit 1'
  1254. );
  1255. sst['throws'](
  1256. function () {
  1257. qs.parse('a[b]=1,2,3,4,5,6', { comma: true, arrayLimit: 5, throwOnLimitExceeded: true });
  1258. },
  1259. new RangeError('Array limit exceeded. Only 5 elements allowed in an array.'),
  1260. 'a non-bracket nested key comma value over the limit throws'
  1261. );
  1262. sst.end();
  1263. });
  1264. st.test('does not throw for a single comma value within arrayLimit', function (sst) {
  1265. sst.deepEqual(
  1266. qs.parse('a=1,2,3', { comma: true, arrayLimit: 5, throwOnLimitExceeded: true }),
  1267. { a: ['1', '2', '3'] },
  1268. 'within the limit'
  1269. );
  1270. sst.deepEqual(
  1271. qs.parse('a=1,2,3,4,5', { comma: true, arrayLimit: 5, throwOnLimitExceeded: true }),
  1272. { a: ['1', '2', '3', '4', '5'] },
  1273. 'exactly at the limit'
  1274. );
  1275. sst.end();
  1276. });
  1277. st.test('does not throw for a bracketed comma group within arrayLimit', function (sst) {
  1278. var result = qs.parse('a[]=1,2,3,4,5,6', { comma: true, arrayLimit: 5, throwOnLimitExceeded: true });
  1279. sst.deepEqual(result, { a: [['1', '2', '3', '4', '5', '6']] }, 'a bracketed comma group is a single element');
  1280. sst.end();
  1281. });
  1282. st.test('throws for a bracketed comma group when arrayLimit is 0', function (sst) {
  1283. sst['throws'](
  1284. function () {
  1285. qs.parse('a[]=1,2,3', { comma: true, arrayLimit: 0, throwOnLimitExceeded: true });
  1286. },
  1287. new RangeError('Array limit exceeded. Only 0 elements allowed in an array.'),
  1288. 'a single bracketed element still exceeds arrayLimit 0'
  1289. );
  1290. sst.end();
  1291. });
  1292. st.end();
  1293. });
  1294. t.end();
  1295. });
  1296. test('parses empty keys', function (t) {
  1297. emptyTestCases.forEach(function (testCase) {
  1298. t.test('skips empty string key with ' + testCase.input, function (st) {
  1299. st.deepEqual(qs.parse(testCase.input), testCase.noEmptyKeys);
  1300. st.end();
  1301. });
  1302. });
  1303. });
  1304. test('`duplicates` option', function (t) {
  1305. v.nonStrings.concat('not a valid option').forEach(function (invalidOption) {
  1306. if (typeof invalidOption !== 'undefined') {
  1307. t['throws'](
  1308. function () { qs.parse('', { duplicates: invalidOption }); },
  1309. TypeError,
  1310. 'throws on invalid option: ' + inspect(invalidOption)
  1311. );
  1312. }
  1313. });
  1314. t.deepEqual(
  1315. qs.parse('foo=bar&foo=baz'),
  1316. { foo: ['bar', 'baz'] },
  1317. 'duplicates: default, combine'
  1318. );
  1319. t.deepEqual(
  1320. qs.parse('foo=bar&foo=baz', { duplicates: 'combine' }),
  1321. { foo: ['bar', 'baz'] },
  1322. 'duplicates: combine'
  1323. );
  1324. t.deepEqual(
  1325. qs.parse('foo=bar&foo=baz', { duplicates: 'first' }),
  1326. { foo: 'bar' },
  1327. 'duplicates: first'
  1328. );
  1329. t.deepEqual(
  1330. qs.parse('foo=bar&foo=baz', { duplicates: 'last' }),
  1331. { foo: 'baz' },
  1332. 'duplicates: last'
  1333. );
  1334. t.test('bracket notation always combines regardless of duplicates', function (st) {
  1335. st.deepEqual(
  1336. qs.parse('a=1&a=2&b[]=1&b[]=2', { duplicates: 'last' }),
  1337. { a: '2', b: ['1', '2'] },
  1338. 'duplicates last: unbracketed takes last, bracketed combines'
  1339. );
  1340. st.deepEqual(
  1341. qs.parse('b[]=1&b[]=2', { duplicates: 'last' }),
  1342. { b: ['1', '2'] },
  1343. 'duplicates last: bracketed always combines'
  1344. );
  1345. st.deepEqual(
  1346. qs.parse('b[]=1&b[]=2', { duplicates: 'first' }),
  1347. { b: ['1', '2'] },
  1348. 'duplicates first: bracketed always combines'
  1349. );
  1350. st.deepEqual(
  1351. qs.parse('a=1&a=2&b[]=1&b[]=2', { duplicates: 'first' }),
  1352. { a: '1', b: ['1', '2'] },
  1353. 'duplicates first: unbracketed takes first, bracketed combines'
  1354. );
  1355. st.end();
  1356. });
  1357. t.end();
  1358. });
  1359. test('qs strictDepth option - throw cases', function (t) {
  1360. t.test('throws an exception when depth exceeds the limit with strictDepth: true', function (st) {
  1361. st['throws'](
  1362. function () {
  1363. qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1, strictDepth: true });
  1364. },
  1365. RangeError,
  1366. 'throws RangeError'
  1367. );
  1368. st.end();
  1369. });
  1370. t.test('throws an exception for multiple nested arrays with strictDepth: true', function (st) {
  1371. st['throws'](
  1372. function () {
  1373. qs.parse('a[0][1][2][3][4]=b', { depth: 3, strictDepth: true });
  1374. },
  1375. RangeError,
  1376. 'throws RangeError'
  1377. );
  1378. st.end();
  1379. });
  1380. t.test('throws an exception for nested objects and arrays with strictDepth: true', function (st) {
  1381. st['throws'](
  1382. function () {
  1383. qs.parse('a[b][c][0][d][e]=f', { depth: 3, strictDepth: true });
  1384. },
  1385. RangeError,
  1386. 'throws RangeError'
  1387. );
  1388. st.end();
  1389. });
  1390. t.test('throws an exception for different types of values with strictDepth: true', function (st) {
  1391. st['throws'](
  1392. function () {
  1393. qs.parse('a[b][c][d][e]=true&a[b][c][d][f]=42', { depth: 3, strictDepth: true });
  1394. },
  1395. RangeError,
  1396. 'throws RangeError'
  1397. );
  1398. st.end();
  1399. });
  1400. });
  1401. test('qs strictDepth option - non-throw cases', function (t) {
  1402. t.test('when depth is 0 and strictDepth true, do not throw', function (st) {
  1403. st.doesNotThrow(
  1404. function () {
  1405. qs.parse('a[b][c][d][e]=true&a[b][c][d][f]=42', { depth: 0, strictDepth: true });
  1406. },
  1407. RangeError,
  1408. 'does not throw RangeError'
  1409. );
  1410. st.end();
  1411. });
  1412. t.test('parses successfully when depth is within the limit with strictDepth: true', function (st) {
  1413. st.doesNotThrow(
  1414. function () {
  1415. var result = qs.parse('a[b]=c', { depth: 1, strictDepth: true });
  1416. st.deepEqual(result, { a: { b: 'c' } }, 'parses correctly');
  1417. }
  1418. );
  1419. st.end();
  1420. });
  1421. t.test('does not throw an exception when depth exceeds the limit with strictDepth: false', function (st) {
  1422. st.doesNotThrow(
  1423. function () {
  1424. var result = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 });
  1425. st.deepEqual(result, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }, 'parses with depth limit');
  1426. }
  1427. );
  1428. st.end();
  1429. });
  1430. t.test('parses successfully when depth is within the limit with strictDepth: false', function (st) {
  1431. st.doesNotThrow(
  1432. function () {
  1433. var result = qs.parse('a[b]=c', { depth: 1 });
  1434. st.deepEqual(result, { a: { b: 'c' } }, 'parses correctly');
  1435. }
  1436. );
  1437. st.end();
  1438. });
  1439. t.test('does not throw when depth is exactly at the limit with strictDepth: true', function (st) {
  1440. st.doesNotThrow(
  1441. function () {
  1442. var result = qs.parse('a[b][c]=d', { depth: 2, strictDepth: true });
  1443. st.deepEqual(result, { a: { b: { c: 'd' } } }, 'parses correctly');
  1444. }
  1445. );
  1446. st.end();
  1447. });
  1448. });
  1449. test('DOS', function (t) {
  1450. var arr = [];
  1451. for (var i = 0; i < 105; i++) {
  1452. arr[arr.length] = 'x';
  1453. }
  1454. var attack = 'a[]=' + arr.join('&a[]=');
  1455. var result = qs.parse(attack, { arrayLimit: 100 });
  1456. t.notOk(Array.isArray(result.a), 'arrayLimit is respected: result is an object, not an array');
  1457. t.equal(Object.keys(result.a).length, 105, 'all values are preserved');
  1458. t.end();
  1459. });
  1460. test('arrayLimit boundary conditions', function (t) {
  1461. // arrayLimit is the max number of elements allowed in an array
  1462. t.test('exactly at the limit stays as array', function (st) {
  1463. // 3 elements = limit of 3
  1464. var result = qs.parse('a[]=1&a[]=2&a[]=3', { arrayLimit: 3 });
  1465. st.ok(Array.isArray(result.a), 'result is an array when count equals limit');
  1466. st.deepEqual(result.a, ['1', '2', '3'], 'all values present');
  1467. st.end();
  1468. });
  1469. t.test('one over the limit converts to object', function (st) {
  1470. // 4 elements exceeds limit of 3
  1471. var result = qs.parse('a[]=1&a[]=2&a[]=3&a[]=4', { arrayLimit: 3 });
  1472. st.notOk(Array.isArray(result.a), 'result is not an array when over limit');
  1473. st.deepEqual(result.a, { 0: '1', 1: '2', 2: '3', 3: '4' }, 'all values preserved as object');
  1474. st.end();
  1475. });
  1476. t.test('arrayLimit 1 with one value', function (st) {
  1477. // 1 element = limit of 1
  1478. var result = qs.parse('a[]=1', { arrayLimit: 1 });
  1479. st.ok(Array.isArray(result.a), 'result is an array when count equals limit');
  1480. st.deepEqual(result.a, ['1'], 'value preserved as array');
  1481. st.end();
  1482. });
  1483. t.test('arrayLimit 1 with two values converts to object', function (st) {
  1484. // 2 elements exceeds limit of 1
  1485. var result = qs.parse('a[]=1&a[]=2', { arrayLimit: 1 });
  1486. st.notOk(Array.isArray(result.a), 'result is not an array');
  1487. st.deepEqual(result.a, { 0: '1', 1: '2' }, 'all values preserved as object');
  1488. st.end();
  1489. });
  1490. t.end();
  1491. });
  1492. test('comma + arrayLimit', function (t) {
  1493. t.test('comma-separated values within arrayLimit stay as array', function (st) {
  1494. var result = qs.parse('a=1,2,3', { comma: true, arrayLimit: 5 });
  1495. st.ok(Array.isArray(result.a), 'result is an array');
  1496. st.deepEqual(result.a, ['1', '2', '3'], 'all values present');
  1497. st.end();
  1498. });
  1499. t.test('comma-separated values exceeding arrayLimit convert to object', function (st) {
  1500. var result = qs.parse('a=1,2,3,4', { comma: true, arrayLimit: 3 });
  1501. st.notOk(Array.isArray(result.a), 'result is not an array when over limit');
  1502. st.deepEqual(result.a, { 0: '1', 1: '2', 2: '3', 3: '4' }, 'all values preserved as object');
  1503. st.end();
  1504. });
  1505. t.test('comma-separated values exceeding arrayLimit with throwOnLimitExceeded throws', function (st) {
  1506. st['throws'](
  1507. function () {
  1508. qs.parse('a=1,2,3,4', { comma: true, arrayLimit: 3, throwOnLimitExceeded: true });
  1509. },
  1510. new RangeError('Array limit exceeded. Only 3 elements allowed in an array.'),
  1511. 'throws error when comma-split exceeds array limit'
  1512. );
  1513. st['throws'](
  1514. function () {
  1515. qs.parse('a=1,2,3', { comma: true, arrayLimit: 1, throwOnLimitExceeded: true });
  1516. },
  1517. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1518. 'throws error with singular "element" when arrayLimit is 1'
  1519. );
  1520. st.end();
  1521. });
  1522. t.test('comma-separated values at exactly arrayLimit stay as array', function (st) {
  1523. var result = qs.parse('a=1,2,3', { comma: true, arrayLimit: 3 });
  1524. st.ok(Array.isArray(result.a), 'result is an array when exactly at limit');
  1525. st.deepEqual(result.a, ['1', '2', '3'], 'all values present');
  1526. st.end();
  1527. });
  1528. t.end();
  1529. });
  1530. test('mixed array and object notation', function (t) {
  1531. t.test('array brackets with object key - under limit', function (st) {
  1532. st.deepEqual(
  1533. qs.parse('a[]=b&a[c]=d'),
  1534. { a: { 0: 'b', c: 'd' } },
  1535. 'mixing [] and [key] converts to object'
  1536. );
  1537. st.end();
  1538. });
  1539. t.test('array index with object key - under limit', function (st) {
  1540. st.deepEqual(
  1541. qs.parse('a[0]=b&a[c]=d'),
  1542. { a: { 0: 'b', c: 'd' } },
  1543. 'mixing [0] and [key] produces object'
  1544. );
  1545. st.end();
  1546. });
  1547. t.test('plain value with array brackets - under limit', function (st) {
  1548. st.deepEqual(
  1549. qs.parse('a=b&a[]=c', { arrayLimit: 20 }),
  1550. { a: ['b', 'c'] },
  1551. 'plain value combined with [] stays as array under limit'
  1552. );
  1553. st.end();
  1554. });
  1555. t.test('array brackets with plain value - under limit', function (st) {
  1556. st.deepEqual(
  1557. qs.parse('a[]=b&a=c', { arrayLimit: 20 }),
  1558. { a: ['b', 'c'] },
  1559. '[] combined with plain value stays as array under limit'
  1560. );
  1561. st.end();
  1562. });
  1563. t.test('plain value with array index - under limit', function (st) {
  1564. st.deepEqual(
  1565. qs.parse('a=b&a[0]=c', { arrayLimit: 20 }),
  1566. { a: ['b', 'c'] },
  1567. 'plain value combined with [0] stays as array under limit'
  1568. );
  1569. st.end();
  1570. });
  1571. t.test('multiple plain values with duplicates combine', function (st) {
  1572. st.deepEqual(
  1573. qs.parse('a=b&a=c&a=d', { arrayLimit: 20 }),
  1574. { a: ['b', 'c', 'd'] },
  1575. 'duplicate plain keys combine into array'
  1576. );
  1577. st.end();
  1578. });
  1579. t.test('multiple plain values exceeding limit', function (st) {
  1580. // 3 elements (indices 0-2), max index 2 > limit 1
  1581. st.deepEqual(
  1582. qs.parse('a=b&a=c&a=d', { arrayLimit: 1 }),
  1583. { a: { 0: 'b', 1: 'c', 2: 'd' } },
  1584. 'duplicate plain keys convert to object when exceeding limit'
  1585. );
  1586. st.end();
  1587. });
  1588. t.test('mixed notation produces consistent results when arrayLimit is exceeded', function (st) {
  1589. var expected = { a: { 0: 'b', 1: 'c', 2: 'd' } };
  1590. st.deepEqual(
  1591. qs.parse('a[]=b&a[1]=c&a=d', { arrayLimit: -1 }),
  1592. expected,
  1593. 'arrayLimit -1'
  1594. );
  1595. st.deepEqual(
  1596. qs.parse('a[]=b&a[1]=c&a=d', { arrayLimit: 0 }),
  1597. expected,
  1598. 'arrayLimit 0'
  1599. );
  1600. st.deepEqual(
  1601. qs.parse('a[]=b&a[1]=c&a=d', { arrayLimit: 1 }),
  1602. expected,
  1603. 'arrayLimit 1'
  1604. );
  1605. st.end();
  1606. });
  1607. t.test('uses existing array length for currentArrayLength when parsing object input with bracket keys', function (st) {
  1608. var input = {};
  1609. var arr = ['x', 'y'];
  1610. arr.a = ['z', 'w'];
  1611. input['a[]'] = arr;
  1612. st.deepEqual(qs.parse(input), { a: ['x', 'y'] }, 'parses object input with bracket keys using existing array values');
  1613. st.end();
  1614. });
  1615. t.test('throws with singular message when object input bracket key exceeds arrayLimit of 1', function (st) {
  1616. var input = {};
  1617. var arr = ['x'];
  1618. arr.a = ['z', 'w'];
  1619. input['a[]'] = arr;
  1620. st['throws'](
  1621. function () {
  1622. qs.parse(input, { throwOnLimitExceeded: true, arrayLimit: 1 });
  1623. },
  1624. new RangeError('Array limit exceeded. Only 1 element allowed in an array.'),
  1625. 'throws singular error for object input exceeding arrayLimit 1'
  1626. );
  1627. st.end();
  1628. });
  1629. t.end();
  1630. });