8(4912)51-02-49
8-930-783-02-49
Макс/ВК/Telegram
510249@mail.ru
звонки принимаются
ежедневно с 8.00 до 20.00





В нашем ассортименте грандиозное пополнение — игровые спорткомплексы для детей от 1 года Perfetto Kids
Все модели в наличие на складе!
Играград W22 115 600 руб. (неокрашенная)
с горкой-труба — 154 600 руб. (неокрашенная)
143 800 руб. (окрашенная)
с горкой-труба — 182 800 руб. (окрашенная)
Играград W17 65 100 руб. (неокрашенная)
Читать далее
Играград W16 56 700 руб. (неокрашенная)
Читать далее
Играград W14 77 000 руб. (неокрашенная)
с горкой-труба — 116 000 (неокрашенная)
96 000 руб. (окрашенная)
с горкой-труба — 135 000 руб. (окрашенная)
8 октября компания Играград спразднует свой 14-ый день рождение и в связи с этим дарит скидки на популярные модели площадок:: IgraGrad Панда Фани Fort с сеткой, IgraGrad Панда Фани с винтовой трубой, IgraGrad Панда Фани Gride с рукоходом, IgraGrad Панда Фани Tower скалодром и IgraGrad Панда Фани с балконом. Акция действует с 04.10.2022 года. Большинство моделей в наличии на складе. Количество товара ограничено.Батут Sky MAX от 51 590 руб.
диаметр 3,05 — 4,88 м
Батут двусторонний: с одной стороны — зеленый, с другой — синий.
Romana детский воркаут 115 840 руб.
Габариты конструкции: длина — 1687 мм, ширина — 1687 мм, высота — 2518 мм.
Бетонируется на глубину 600 мм, диаметр трубы 108 мм.
Гарантия 1 год.
Качели двойные Romana 50 100 руб.
Габариты конструкции: длина — 2825 мм, ширина — 1466 мм, высота — 2680 мм.
Бетонируется на глубину 600 мм, диаметр трубы 57 х 3 мм.
Гарантия 1 год.
ROMANA D7 12 990 руб.
Компактная шведская стенка для улицы устанавливается к внешней стене дома. Качественные материалы, используемые в производстве, обеспечивают долговечность эксплуатации: сталь устойчива к коррозии и погодным условиям, а краска — к выцветанию.
Комплектация: шведская стенка, канат, турник, веревочный лаз, рукоход
Габариты 1540 х 863 х 2196 мм, максимальная нагрузка до 100 кг.
Романа D2 14 310 руб. без качелей,
качели (при покупке с комплексом, можно разные): фанерные — 890 руб., пластиковые — 1990 руб., цепные — 3490 руб., качели-гнездо — 3 990 руб., качели-гнездо лодка — 6780., гнездо — сетка 100 см — 5 190 руб., 80 см — 4 660 руб., качели — диск — 2 200 руб., качели — сетка для малышей — 3 200 руб.,брусья навесные — 3690 руб., можно вместо качелей повесить трапецию, веревочную лестницу и т.д.
ROMANA D3 18 590 руб.
Комплекс в виде полусферы с контрастными перекладинами, которые надежно соединены между собой металлическими крепежами. Комплекс многофункционален: из него можно сделать шалаш или летний домик, дополнить тентом или гамаком.
Габариты 2753 х 2753 х 1403 мм, максимальная нагрузка до 50 кг.
Батут Perfetto Sport Dynamics в ассортименте
3,7 м
от 13 250 руб.
Внутренняя сеть безопасности!!!
Производитель — Perfetto Sport (Италия), страна производства — Китай.
Детский домик Dohany 5075 М
15 000 руб.
1130*1110*1200(в) мм; сделан из пластика; производитель — Dohany (Венгрия)
Детский домик 11976 10 500 руб. 12 000 руб.
1020*880*1080(в) мм; сделан из пластика; производитель — Mochtoys (Польша)
Airpool Box в ассортименте
5 330 руб.
сухой бассейн с шариками для детей
Возможные цвета: серый, голубой и розовый.
В комплекте: бассейн, 150 шариков. Материалы: велюр, поролон. Размеры: 900 мм х 900 мм, высота 400 мм. Упаковка 850 x 600 x 450 мм, вес изделия — 4 кг. Рекомендуем для этой модели дополнительно купить шарики для сухого бассейна — 200-300 шт.
Airpool Малышарики в ассортименте
4 500 руб.
сухой бассейн с шариками для детей
Возможные цвета: желтый, салатовый, голубой и розовый.
В комплекте: бассейн, 150 шариков. Материалы: трикотаж, поролон. Диаметр 800 мм, высота 330 мм. Упаковка 700 x 500 x 350 мм, вес изделия — 4 кг. Рекомендуем для этой модели дополнительно купить шарики для сухого бассейна — 200-300 шт.
Распродажа деревянных площадок серии КРАФТ PRO от компании ИграГрад. Быстрая доставка игровых комплексов этой серии. Спишите, количество товара отграничено.Резиновая плитка
RUBBLEX ACTIVE
Резиновое покрытие Rubblex Active предназначено специально для использования в качестве покрытия детских площадок. Особенностью Rubblex Active является высокая амортизация (на 20-25% чем у аналогичных резиновых плит, произведенных альтернативным методом). Высокая амортизация обеспечивает безопасность эксплуатации детской площадки. Именно поэтому покрытие и называется травмобезопасным. Rubblex Active используется на детских игровых площадках, детских спортивных площадках, скалодромах и других местах, повышенной опасности падения человека. При высокой плотности материала, покрытие остается мягким и эластичным, что снижает риск получения травм при падении. Покрытия Rubblex Active не имеют ограничений по трафику и могут быть использованы, как для частных детских площадок, так и для коммерческих детских игровых площадок.
Повышение цен на комплексы Формула здоровья — торопитесь купить складские позиции по низкой стоимости до 1 мая 2021 г.
Восьмой Элемент 45 000 руб.
Игровые элементы детской спортивной площадки 8 Элемент:
Седьмой Элемент 42 000 руб.
Игровые элементы детской спортивной площадки 7 Элемент:
Нулевой Элемент 28 900 руб.
Игровые элементы детской спортивной площадки 0 Элемент:
no images were found
Romana S12 8 080 руб.
с массажными ступенями. Крепление к стене. Возможные цвета: Белый прованс с серыми ступенями.
Romana S9 7 890 руб.
с массажными ступенями. Крепление к стене. Возможные цвета: белый антик/золото, черный матовый.
Romana R10 13 390 руб.
с массажными ступенями. Крепление враспор между полом и потолком. Возможные цвета: белый антик/золото, черный матовый.
Romana R9 8 690 руб.
с массажными ступенями. Крепление враспор между полом и потолком. Возможные цвета: белый антик золото, черный матовый.
Romana S6 10 990 руб.
(распродажа остатков)
с массажными ступенями. Крепится к стене. Возможные цвета: синяя слива, зеленое яблоко.
На складе появились уличные ДСК серии Формула здоровья:
Приобретайте сейчас, по сегодняшним ценам, пока всё в наличии, не дожидаясь сезонного подорожания и увеличения сроков поставки.
На складе появились уличные ДСК серии Романа:
На остальные комплексы действует предзаказ —
заказывайте сейчас, чтобы приобрести то, что вам нравится, а не то, что осталось.
Формула здоровья «Стрит 3»с гнездом
52 410 руб. 56 550 руб. Варианты каркаса: оранжевый/синий/салатовый/белый, ступени с ПВХ — радуга.
Акция от производителя детских площадок Самсон! Скидка 15 % на площадку 3 Элемент. Акция действует с 13 мая 2019 г. по 13 июня 2019 г. Количество товара ограничено.Чердак Можга ДК5
35 499 руб. 36 998 руб. (возможные цвета: розовый, бирюзовый). Текстиль в комплект не входит.
Читать далее
Горка «Apple» 8 400 руб.
Размеры: 1150*470*570(в) мм. Возможные цвета: серый, оранжевый. Производитель — Южная Корея.
Качели Космос Зеленые 15 000 руб.
4-местные — 15 300 руб. (бордовые)
Качели садовые раскладные;
размеры: 2300*1490*1770 (в)мм, размер сиденья 1680*540 мм (1800*650 мм); нагрузка до 260 (350) кг.
Комплектация: металлический каркас, текстильный набор 3-местный (4-местный), 2 подушки, 2 подстаканника,водоотталкивающая крыша (Оксфорд, полиэстер).
Олимпик-Ракета 13 900 руб.
+ сетка 14 700 руб.
+сетка с горкой 15 900 руб.
Крепление к стене
Олимпик-Грибок 15 550 руб.
с сеткой 16 800 руб., с горкой 16 950 руб.; возможные варианты цвета: синий, зелёный, фиолетовый, жёлтый. Крепление к стене.
Микс «Море» 1 250 руб.

Обучающие фигуры 6 090 руб. 6 500 руб.Размеры: 1200 х 1200 х 100(в) мм.
Состав: прямоугольник 300 х 300 х 100 мм — 12 шт.
Акция от производителя детских площадок Самсон! Скидка 10 % на площадки классической серии: Амстердам, Тасмания, Мадагаскар, Аляска, Кирибати и Бретань. Акция действует до 30.11.2018 г. Количество товара ограничено.
Сухой бассейн «Долька» Размеры: 1600 х 1150 х 400 мм. В комплекте — 300 шариков. Материал: кожзам, поролон.
Airpool 5 000 руб. (диаметр 800 мм, высота 330 мм)
сухой бассейн с шариками для детей
Возможные цвета: серый, розовый, бирюзовый, темно-синий.
В комплекте: бассейн, 150 шариков. Материалы: трикотаж, поролон. Упаковка 700 x 500 x 350 мм, вес изделия — 4 кг. Рекомендуем для этой модели дополнительно купить шарики для сухого бассейна — 200-300 шт.
Мягкий коврик «Дорога России»
2 800 руб.
Размеры -2000 х 1800 х 5 мм., материал — вспененный пищевой полипропилен, оборотная сторона — влагостойкая фольга.
Читать далее
Игровой комплекс
«Маленький спортсмен»
17 000 руб.
Размеры: 1600*1520*1040 (в) мм.
Горка «Динозаврик» 12 300 руб.
Размеры: 820*1610*1080 (в) мм.
Игровой комплекс «Дом» 35 000 руб.1430*2690*1190(в) мм; сделан из пластика.
Домик пластиковый с горкой 19 890 руб.1870*1080*1190(в) мм; сделан из пластика.
Домик пластиковый 10 500 руб.1080*1080*1190(в) мм; сделан из пластика.
Можга Цветочный 45 990 руб. 67 999 руб. два варианта расцветки: желтый и зеленый.
1550 х 1200 х 1850 мм
Акция от производителя детских площадок Самсон! Скидка 20 % на площадки Сибирика Мини, Сибирика с рукоходом и Сибирика с двумя горками (модели площадок по акции укомплектованы цветной крышей из ткани Оксфорд). Количество товара ограничено.


Можга 7
(деревянная крыша) 103 500 руб.
(крыша тент) 93 500 руб.
Игровые элементы детского игрового городка Можга 7:
Можга 6 с широким скалодромом
(деревянная крыша) 118 500 руб.
(крыша тент) 108 500 руб.
Игровые элементы детского игрового городка Можга 6 с широким скалодромом:
Можга 6 с качелями и широким скалодромом
(деревянная крыша) 131 000 руб.
(крыша тент) 121 000 руб.
Игровые элементы детского игрового городка Можга 6 с качелями и широким скалодромом:
Можга 6 с качелями и узким скалодромом
( крыша тент) 117 500 руб.
деревянная крыша 130 100 руб.
Игровые элементы детского игрового городка Можга 6 с качелями и узким скалодромом:
Можга 6 с качелями
(деревянная крыша) 124 000 руб.
крыша тент 114 000 руб.
Игровые элементы детского игрового городка Можга 6 с качелями:
Можга 6 с узким скалодромом
(деревянная крыша) 122 000 руб.
(крыша тент) 105 000 руб.
Игровые элементы детского игрового городка Можга 6 с узким скалодромом:
Можга 8 (со скалодромом) 123 500 руб.
с деревянной лесенкой 122 000 руб.
Игровые элементы детского игрового городка Можга 8:
Можга 1 с качелями 58 100 руб. Игровые элементы детского игрового городка Можга 1 с качелями:
Можга 5 (крыша тент) 47 500 руб. деревянная крыша 52 500 руб.
Игровые элементы детского игрового городка Можга 5:
Можга Избушка 91 500 руб.
Игровые элементы детского игрового городка Можга Избушка:
Можга 4 (крыша тент) 42 000 руб.деревянная крыша 47 300 руб.
Игровые элементы детского игрового городка Можга 4:
Можга 3 (крыша тент) 37 749 руб.
деревянная крыша 48 990 руб. Игровые элементы детского игрового городка Можга 3:
Можга 2 (крыша тент) 38 990 руб. деревянная крыша 43 990 руб.
Игровые элементы детского игрового городка Можга 2:
Можга 1 (крыша тент) 40 500 руб.
деревянная крыша 45 500 руб.Игровые элементы детского игрового городка Можга 1:
Розовые грёзы 1 200 руб.
Читать далее
Замок динозаврика 1 700 руб.
Читать далее
Веселая школа 1 200 руб.
Читать далее
Парк динозавров 1 200 руб.
Читать далее
Пожарная станция 1 200 руб.
Читать далее
Домик-ферма 20 750 руб. Размеры в собранном виде: 1390*1180*1200(в) мм.
Сделан из гипоаллергенного пластика. Страна производства — Польша.

Цветная песочница №1 6 500 руб.
Материал — сосна, обработанная антисептиком.
Размеры: 1400 х 1400 х 300 мм.

Песочница Сахара 8 500 руб.
Материал — сосна, обработанная антисептиком.
Размеры: 1400 х 1400 х 1500(в) мм, борт 120 мм.

Цветная песочница №25 7 500 руб.
Материал — сосна, обработанная антисептиком.
Размеры: 1400 х 1400 х 230 мм.





Песочница №4 9 000 руб.
Материал — импрегнированная сосна (пропитана защитным средством по технологии вакуум-давление-вакуум), имеет фисташковый оттенок.
Размеры: 1470х1470х1700 мм.

Мини-песочница №3 9 900 руб.
Материал — сосна, цвет — натуральное дерево. Все элементы отшлифованы и покрыты пропиткой. Размеры: 1000х1000х160 мм.
Песочница Романа 8 990 руб.
Размеры: 1500 х 1500 х 250 мм
Изделие представляет собой сборно-разборную каркасную конструкцию из фанерных листов, установленную на забетонированные стойки.
Романа «Лето» 13 191 руб. без качелей,
качели (при покупке с комплексом, можно разные): фанерные — 699 руб., пластиковые — 1589 руб., цепные — 2861 руб., качели-гнездо — 3 999 руб.
Мягкий коврик «Город» 2 300 руб.
(количество товара ограничено)
Размеры -2000 х 1600 х 5 мм., материал — вспененный пищевой полипропилен, оборотная сторона — влагостойкая фольга.
Читать далее
Мягкий коврик «Медвежата»
2 700 руб.
Размеры — 2000 х 1800 х 5 мм., материал — вспененный пищевой полипропилен, оборотная сторона — влагостойкая фольга.
Читать далее
Мягкий коврик «Совята»
2 700 руб.
Размеры — 2000 х 1800 х 5 мм., материал — вспененный пищевой полипропилен, оборотная сторона — влагостойкая фольга.
Читать далее
Мягкий коврик «Русский алфавит»
2 700 руб.
Размеры — 2000 х 1800 х 5 мм., материал — вспененный пищевой полипропилен, оборотная сторона — фольга.
Читать далее
Садовый домик (бежевый) 17 100 руб. 1220*1200*1205(в) мм; сделан из пластика; страна производства — Польша
Горка детская Большая 6 700 руб.
Размеры: 1800*640*1100 (в) мм. Производство — Польша.
Ветеринарная клиника 1 050 руб.
Читать далее
Покрытие «Мозаика» ( 300*300*15 мм) 800 руб.
(стоимость указана за упаковку — 6 элементов)
Уралец универсальный 11 750 руб.
Крепится к стене или в распор между полом и потолком. Возможные цвета: оранжевый/радуга, синий/радуга, салатовый/радуга, белый/салатовый, зеленый/радуга, белый/голубой, голубой/радуга, фиолетовый/радуга, бежевый/коричневый, белый/радуга, белый/черный, красный/радуга.
Читать далее
Орленок 11 120 руб.
Крепится к стене. Возможные цвета: белый/голубой, бежевый/коричневый, белый/салатовый, белый/черный, белый/радуга, фиолетовый/радуга, голубой/радуга, зеленый/радуга, оранжевый/радуга, синий/радуга, салатовый/радуга, красный/радуга.
Читать далее
Непоседа 8 380 руб.
Крепится к стене. Возможные цвета: белый/черный, бежевый/коричневый, белый/голубой, красный/радуга, голубой/радуга, белый/салатовый, белый/радуга, оранжевый/радуга, синий/радуга, салатовый/радуга, салатово-голубой, зеленый/радуга.
Читать далее
Карапуз 9 000 руб.
Крепится к стене. Возможные цвета: белый/радуга, бежевый/коричневый, фиолетовый/радуга, оранжевый/радуга, синий/радуга, салатовый/радуга, белый/салатовый, голубой/радуга, красный/радуга,зеленый/радуга, белый/черный, белый/голубой.
Читать далее
Мечта — 1 В Плюс 7 100 руб.
Крепится к стене. Возможные цвета: оранжевый/радуга, синий/радуга, салатовый/радуга.
Читать далее
Жирафик универсальный 9 990 руб.
Крепится к стене и враспор. Возможные цвета: белый/черный, белый/салатовый, фиолетовый/радуга, белый/радуга, белый/голубой, бежевый/коричневый, салатовый/радуга, голубой/радуга, красный/радуга, оранжевый/радуга, синий/радуга, зеленый/радуга.
Читать далее
Атлант 13 410 руб.
Крепится враспор между полом и потолком. Возможные цвета: белый/радуга, белый/черный, бежевый/коричневый, белый/салатовый, красный/радуга, белый/голубой, фиолетовый/радуга, голубой/радуга, оранжевый/радуга, салатовый/радуга, синий/радуга, зеленый/радуга.
Читать далее
Аистенок — 1 А Плюс 6 500 руб. 7 100 руб.
Крепится к стене. Возможные цвета: оранжевый/радуга, салатовый/радуга, синий/радуга.
Читать далее
Сигма — 1 А Плюс 7 700 руб.
Крепится к стене. Возможные цвета: оранжевый/радуга, салатовый/радуга, синий/радуга, красный/радуга, фиолетовый/радуга.
Читать далее
Великан — 1 С Плюс 11 500 руб.
Крепится враспор между полом и потолком. Возможные цвета: оранжевый/радуга, зеленый/радуга, синий/радуга.
Читать далее
Слоненок 22 380 руб.
Крепится враспор между полом и потолком. Возможные цвета: белый/голубой, оранжевый/радуга,голубой/радуга, салатовый/радуга, синий/радуга, бежевый/коричневый, фиолетовый/радуга, белый/радуга,зеленый/радуга, красный/радуга, белый/салатовый. белый/черный.
Читать далее
Счастливчик X Плюс 19 200 руб.
Способ установки — напольный. Возможные цвета: оранжевый/радуга,синий/радуга, зеленый/радуга.
Читать далее
Игрунок 17 280 руб.
Способ установки — напольный. Возможные цвета: розовый/радуга, белый/черный, зеленый/радуга, фиолетовый/радуга, салатовый/радуга, красный/радуга, оранжевый/радуга,синий/радуга, салатовый/радуга, голубой/радуга.
Читать далее
Вершинка 2.0 27 600 руб.
Способ установки — напольный. Возможные цвета: оранжевый/радуга,синий/радуга, салатовый/радуга.
Читать далее
Артек N Плюс 20 900 руб.
Способ установки — напольный. Возможные цвета: оранжевый/радуга,синий/радуга, салатовый/радуга.
Читать далее
Гамма 10 500 руб.
Крепится к стене. Возможные цвета: оранжевый/радуга, салатовый/радуга, синий/радуга, бело-черный, зеленый/радуга, красный/радуга, голубой/радуга, белый/салатовый, бежевый/коричневый, белый/голубой, белый/радуга.
Читать далее

Сухой бассейн Ручеёк Размеры: 1400 х 1400 х 550 мм. В комплекте — 300 шариков. Материал: кожзам, поролон.

Сухой бассейн Калейдоскоп
Размеры: 1800 х 1800 х 400 мм. В комплекте — 300 шариков.
Материал: кожзам, поролон.
Romana Karusel — S5 8 930 руб.
C массажными ступенями. Крепится к стене. Возможные цвета: сине-желтый, зелено-желтый, красно-желтый.
Romana Karusel S3 12 690 руб.
(распродажа остатков)
С массажными ступенями. Крепится к стене. Сетка устанавливается в любую сторону. Возможные цвета: зеленая яблоко, синяя слива.
Romana R3 12 390 руб.
C массажными ступенями. Крепится враспор между полом и потолком. Возможные цвета: синяя слива, зеленая яблоко, белый прованс.
Romana NEXT Skalolaz 25 970 руб.
(распродажа остатков)
с массажными ступенями. Крепится к стене. Возможные цвета: синяя слива, зеленое яблоко, белый прованс.
Romana Transformer 10 190 руб.
с массажными ступенями. Крепится враспор между полом и потолком. Возможные цвета: красно-желтый, сине-желтый, зелено-желтый и бело-желтый.
Игровая палатка «Дачный домик»
1 050 руб.
Читать далее
Игровой домик «Волшебный замок»
1 750 руб.
Читать далее
Игровой домик «Малышка пони»
950 руб.
Читать далее
Игровой домик «Принцесса»с туннелем
1 400 руб.
Читать далее
Игровой домик с туннелем Пират
1 400 руб.
Читать далее
Туннель Гусеница 1 300 руб.
Читать далее
материал: каркас — металл, 3 лыжи — пластик.
Размеры: 1160 х 530 х 450 мм, максимальная нагрузка — 100 кг,
количество мест — 1.
материал: каркас — металл, 3 лыжи — пластик.
Размеры: 740 х 340 х 460 мм, максимальная нагрузка — 100 кг,
количество мест — 1.
материал: каркас — металл, 3 лыжи — пластик.
Размеры: 1100 х 490 х 440 мм, максимальная нагрузка — 100 кг,
высота от сиденья — 290 мм, количество мест — 1.
Материал: каркас — металл, 3 лыжи — пластик.
Размеры: 1100 х 490 х 420 мм, максимальная нагрузка — 100 кг,
высота от сиденья — 440 мм, количество мест — 1.
Покрытие «Классики» 1 500 руб.
35 шор, в комплекте 9 элементов 300*300*15 мм и 1 элемент 600*300*15 мм
Пергола малая 27 500 руб.
Размеры: 1400 х 2800 мм, высота 2400 мм
(материал: каркас — клееный брус лиственницы, ограждение — массив сосны)
Стол дачный большой 16 500 руб.
Размеры: 1300 х 1400 мм, высота 700 мм
(материал: каркас — клееный брус лиственницы, ограждение — массив сосны)
Седар Саммит 41 900 руб.
Деревянная детская площадка Седар Саммит:
Romana R3 13 190 руб.
(распродажа остатков)
C массажными ступенями. Крепится враспор между полом и потолком. Возможные цвета: сиренево/голубой, зеленое яблоко.
Романа Карусель R-8 6 470 руб.
с массажными ступенями. Крепится враспор между полом и потолком. Возможные цвета: белый антик золото
Romana Karusel — R55 8 300 руб.
(верхняя ступень — ЭКОНО на хомутах)
с массажными ступенями. Крепится враспор между полом и потолком. Возможные цвета: сине-желтый, зелено-желтый, красно-желтый, розовый.
Romana R6 12 300 руб.
(распродажа остатков)
с массажными ступенями. Крепится враспор между полом и потолком. Возможные цвета: зеленое яблоко.
Romana Kometa — 2 8 320 руб.
Предыдущая модель — 7470 руб. C массажными ступенями. Крепится враспор между полом и потолком. Возможные цвета: бело-желтый,красно-желтый, сине-желтый, зелено-желтый.
Романа Карусель — S8 6 310 руб.
с массажными ступенями. Крепится к стене. Цвет — бело-черный.
Romana Karusel — S5 9 390 руб.
с массажными ступенями. Крепится к стене. Возможные цвета: сине-желтый, зелено-желтый, красно-желтый.
Romana Karusel — S3 11 860 руб.
(модель 2017 г.)
С массажными ступенями. Крепится к стене. Сетка устанавливается в любую сторону. Возможные цвета: сине-желтый, зелено-желтый, красно-желтый, бело-желтый.
Шестой Элемент 64 000 руб.Игровые элементы детского игрового городка 6 Элемент:
Пятый Элемент 64 000 руб.
Игровые элементы детской спортивной площадки 5 Элемент:
Четвертый Элемент 57 000 руб.
Игровые элементы детской площадки Элемент 4:
Третий Элемент 50 000 руб. Игровые элементы детской площадки 3 Элемент:
Второй Элемент 43 000 руб.
Игровые элементы детской площадки 2 Элемент:
Первый Элемент 38 000 руб.
Игровые элементы детской площадки 1 Элемент:
Большой домик с заборчиком
17 000 руб.
1270*1900*1180(в) мм; сделан из пластика; страна производства — Польша
Садовый домик со столом
15 000 руб.1220*1800*1205(в) мм; сделан из пластика; страна производства — Польша
Горка Большой 13 750 руб.
Размеры: 2000*1400*2200(в) мм, длина спуска 2000 мм.
Можно подключить воду. Производство — Венгрия.
Горка средняя 5500 руб.
Размеры: 1300*850*760(в) мм. Производство — Венгрия.
Горка детская 4 000 руб.
Размеры: 1280*550*810(в) мм. Производство — Польша.
Турник Пионер-1 5 500 руб.
Размеры: 1300*300 мм, высота 1500 мм, нагрузка до 100 кг.
Диаметр перекладины 32 мм, ширина — 1000 мм. Основание бетонируется.
Турник Пионер-2 8 000 руб.
Размеры: 2600*300 мм, высота 1500/1800 мм, нагрузка до 100 кг.
Диаметр перекладины 32 мм, ширина — 1000 мм. Основание бетонируется.
Турник Пионер-3 10 500 руб.
Размеры: 3900*300 мм, высота 1500/1800/2100 мм, нагрузка до 100 кг.
Диаметр перекладины 32 мм, ширина — 1000 мм. Основание бетонируется.

Качели-балансир 360° 3 200 руб.
не бетонируются, крутятся по кругу как карусель
Размеры: 2000 х 670 х 700(в) мм
Панда Макси с качелями 86 250 руб.
все детали шлифованы, без покрытия
Комплектация игрового комплекса для дачи Панда Макси с качелями:
Большая Панда 58 900 руб.
все детали шлифованы, без покрытия
Комплектация игрового спортивно-игрового комплекса с горкой Большая Панда:
Панда с качелями и скалодромом
46 900 руб.
все детали шлифованы, без покрытия
Комплектация игрового комплекса Панда с качелями и скалодромом:
Панда с качелями 53 900 руб.
все детали шлифованы, без покрытия
Комплектация игрового комплекса Панда с качелями:
Панда Вуд 43 900 руб.
все детали шлифованы, без покрытия
Комплектация детской площадки Панда Вуд:
Горка «Великан» 25 000 руб.
Размеры: 3700*1800*2000(в) мм. Производство — Израиль.
Горка с водой 9 700 руб.
Размеры: 2300*1200*1400(в) мм. Производство — Польша.
Горка «Весёлый спуск» 14 300 руб.
Размеры: 2300*1200*1400(в) мм. Производство — Израиль.
Песочница-бассейн Сердечко 3 200 руб.
Размеры: 900*800*200(в) мм х 2 шт. Производство — Израиль.
В жаркую погоду детям нравится играть в песке и возиться в воде.
Сказочный домик 13 700 руб.1600*1300*1180(в) мм; длина ската — 1300 мм, высота ската — 650 мм;
Детская пластиковая горка с баскетбольным кольцом, тоннелем, воротами и двумя надувными мячами в комплекте.
Большой садовый домик
16 500 руб. 1270*1500*1180(в) мм; сделан из пластика; страна производства — Польша
Садовый домик (коричн.) 12 500 руб.1220*1200*1205(в) мм; сделан из пластика; страна производства — Польша
Садовый домик (серый) 12 500 руб.1220*1200*1205(в) мм; сделан из пластика; страна производства — Польша
Садовый домик с заборчиком
18 300 руб. 20 700 руб.1650*1200*1205(в) мм; сделан из пластика; страна производства — Польша
Домик Мастерская 13 500 руб.1010*1050*1105(в) мм; сделан из пластика; производитель — Palplay (Израиль)
Домик Кухня 13 500 руб. 14 300 руб.1010*1050*1105(в) мм; сделан из пластика; производитель — Palplay (Израиль)
Пожарная машина 37 000 руб.Материал — сосна. Размеры: 2600 х 1500 х 1800(в) мм.
Песочница Машинка 29 000 руб.
Материал — сосна. Размеры: 1500 х 1500 х 1850 мм.
Песочница №11 цветная со складными лавочками 14 000 руб.
Материал — сосна, обработанная антисептиком.
Размеры: 1500 х 1500 х 300 мм.
Романа «Избушка» 67 990 руб. без качелей,
качели (при покупке с комплексом, можно разные): фанерные — 790 руб., пластиковые — 1990 руб., цепные — 2790 руб., качели-гнездо — 3 990 руб., качели-гнездо лодка — 6780 руб., можно вместо качелей повесить трапецию, веревочную лестницу и т.д.
Терра 3 650 руб.
сухой бассейн с шариками для детей
В комплекте: бассейн, 150 шариков, прозрачная сумка. Материалы: тафетта, мебельная ткань. Диаметр 1000 мм, высота 330 мм. Упаковка (сумка) 710 x 510 x 360 мм, вес изделия — 4,5 кг. Рекомендуем для этой модели дополнительно купить шарики для сухого бассейна — 200-300 шт.
Летняя сказка 4 995 руб.
сухой бассейн с шариками для детей
В комплекте: бассейн, 150 шариков, прозрачная сумка. Материалы: тафетта, габардин. Диаметр 1000 мм, высота 330 мм. Упаковка (сумка) 710 x 510 x 360 мм, вес изделия — 5 кг. Рекомендуем для этой модели дополнительно купить шарики для сухого бассейна — 200-300 шт.
Подводный мир 4 995 руб.
сухой бассейн с шариками для детей
В комплекте: бассейн, 150 шариков, прозрачная сумка. Материалы: тафетта, габардин. Диаметр 1000 мм, высота 330 мм. Упаковка (сумка) 710 x 510 x 360 мм, вес изделия — 5 кг. Рекомендуем для этой модели дополнительно купить шарики для сухого бассейна — 200-300 шт.
Сухой бассейн Весёлая поляна
4 300 руб.
сухой бассейн с шариками для детей
В комплекте: бассейн, 100 шариков, прозрачная сумка. Материалы: поролон, тафетта, оксфорд. Диаметр 1000 мм, высота 330 мм, толщина 40 мм. Упаковка (сумка) 710 x 510 x 360 мм, вес изделия — 5 кг. Рекомендуем для этой модели дополнительно купить шарики для сухого бассейна — 200-300 шт.
Тюбинг Мультгерои от 2 700 руб.
(Тюбинг Холодное сердце 100 см и др. мультгерои — 3350 руб., d 80 см — 2700 руб., доставка по Рязани — 100 руб., надувка ватрушки — 100 руб.)
Ватрушка снабжена двумя ручками и буксировочным тросом, есть молния, чтобы снег не попадал внутрь. Материалы — низ — ПВХ, верх — ПВХ.
/**
* Kupivkredit Software Development Kit.
*
* Version: 1.0.0
* Date: 2016-10-17 16:42:30
*
* Copyright (c) 2016 Tinkoff Bank (closed joint-stock company)
*/
(function(root, factory) {
var isCJS, isAMD,
sdk, conflict;
isCJS = typeof module === «object» && module.exports;
isAMD = typeof define === «function» && define.amd;
sdk = factory.call(root);
if (isCJS) {
module.exports = sdk;
} else if (isAMD) {
define([], function() {
return sdk;
});
}
// save conflict
conflict = root.KVK;
// register KVK anyway
root.KVK = sdk;
// resolve conflict
root.KVK.noConflict = function() {
root.KVK = conflict;
}
})(this, function() {
var require, register, response,
define, // disable amd fallbacks
__DEBUG__, __BUILD__;
__DEBUG__ = true;
__BUILD__ = «17299b8a21f600c82c96520e261846dbd216a073»;
// this function will be called by an index cjs
register = function(obj) {
response = obj;
};
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==»function»&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error(«Cannot find module ‘»+o+»‘»)}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require==»function»&&require;for(var o=0;o
*/
Actor = function(uuid, options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
this.uuid = uuid;
this.subjectId = null;
this.known = [];
};
Actor.DEFAULTS = {};
Actor.prototype = {
constructor: Actor,
injectCommutation: function(commutation) {
assert(_.isEmpty(this.commutation), «Commutation is already set»);
assert(commutation instanceof Commutation, «Commutation is expected»);
this.commutation = commutation;
},
_isKnown: function(message) {
return _.indexOf(this.known, message.id) !== -1;
}
};
Actor.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Actor;
},{«./commutation»:2,»assert»:62,»inherits-js»:80,»lodash»:»7ZYSzK»}],2:[function(require,module,exports){
var _ = require(«lodash»),
inherits = require(«inherits-js»),
Commutation;
/**
* Commutation
*
* @class Commutation
* @constructor
* @abstract
*
* @param {Object} [options]
*
* @author Sergey Kamardin
*/
Commutation = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
Commutation.DEFAULTS = {};
Commutation.prototype = {
constructor: Commutation,
/**
* @abstract
*/
getWriter: function(window, options) {
throw new Error(«Method ‘getWriter’ must be implemented»);
},
/**
* @abstract
*/
getReader: function(options) {
throw new Error(«Method ‘getReader’ must be implemented»);
}
};
Commutation.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Commutation;
},{«inherits-js»:80,»lodash»:»7ZYSzK»}],»1kWZSB»:[function(require,module,exports){
var Commutation = require(«../commutation»),
_ = require(«lodash»),
ConditionCommutation;
/**
* ConditionCommutation
*
* @class ConditionCommutation
* @extends Commutation
* @author Sergey Kamardin
*/
ConditionCommutation = Commutation.extend(
/**
* @lends ConditionCommutation.prototype
*/
{
constructor: function(options) {
Commutation.prototype.constructor.apply(this, arguments);
if (window && window.postMessage) {
this.commutation = options.postMessage;
} else {
this.commutation = options.hash;
}
},
getWriter: function(window, options) {
return this.commutation.getWriter(window, options);
},
getReader: function(options) {
return this.commutation.getReader(options);
}
}
);
module.exports = ConditionCommutation;
},{«../commutation»:2,»lodash»:»7ZYSzK»}],»/common/script/src/communication/commutation/condition.js»:[function(require,module,exports){
module.exports=require(‘1kWZSB’);
},{}],»/common/script/src/communication/commutation/hash.js»:[function(require,module,exports){
module.exports=require(‘jdt5C8’);
},{}],»jdt5C8″:[function(require,module,exports){
var Commutation = require(«../commutation»),
_ = require(«lodash»),
HashWriter = require(«../writer/hash»),
HashReader = require(«../reader/hash»),
DefaultCommutation;
/**
* DefaultCommutation
*
* @class DefaultCommutation
* @extends Commutation
* @author Sergey Kamardin
*/
DefaultCommutation = Commutation.extend(
/**
* @lends DefaultCommutation.prototype
*/
{
getWriter: function(window, options) {
return new HashWriter(window, _.extend({}, this.options.writer, options));
},
getReader: function(options) {
return new HashReader(options, _.extend({}, this.options.reader, options));
}
},
/**
* @lends DefaultCommutation
*/
{
DEFAULTS: {
writer: {},
reader: {}
}
}
);
module.exports = DefaultCommutation;
},{«../commutation»:2,»../reader/hash»:16,»../writer/hash»:19,»lodash»:»7ZYSzK»}],»/common/script/src/communication/commutation/post-message.js»:[function(require,module,exports){
module.exports=require(‘k4NLRU’);
},{}],»k4NLRU»:[function(require,module,exports){
var Commutation = require(«../commutation»),
_ = require(«lodash»),
PostMessageWriter = require(«../writer/post-message»),
PostMessageReader = require(«../reader/post-message»),
DefaultCommutation;
/**
* DefaultCommutation
*
* @class DefaultCommutation
* @extends Commutation
* @author Sergey Kamardin
*/
DefaultCommutation = Commutation.extend(
/**
* @lends DefaultCommutation.prototype
*/
{
getWriter: function(window, options) {
return new PostMessageWriter(window, _.extend({}, this.options.writer, options));
},
getReader: function(options) {
return new PostMessageReader(options, _.extend({}, this.options.reader, options));
}
},
/**
* @lends DefaultCommutation
*/
{
DEFAULTS: {
writer: {},
reader: {}
}
}
);
module.exports = DefaultCommutation;
},{«../commutation»:2,»../reader/post-message»:17,»../writer/post-message»:20,»lodash»:»7ZYSzK»}],9:[function(require,module,exports){
var EventEmitter = require(«../events/emitter/node»),
_ = require(«lodash»),
RSVP = require(«rsvp»),
Connection;
/**
* Connection
*
* @class Connection
* @extends EventEmitter
* @author Sergey Kamardin
*/
Connection = EventEmitter.extend(
/**
* @lends Connection.prototype
*/
{
constructor: function(id, uuid) {
EventEmitter.prototype.constructor.apply(this, arguments);
this.established = false;
this.buffer = [];
this.id = id;
this.uuid = uuid;
},
isEstablished: function(value) {
var self = this;
if (_.isBoolean(value) && this.established !== value) {
this.emit(«established», this.established = value);
if (value) {
_.times(this.buffer.length, function() {
self.post.apply(self, self.buffer.pop());
});
}
}
return this.established;
},
handle: function(topic, data) {
this.emit(topic, data);
},
response: function(id, response) {
this.post([«rpc», «response», id].join(«:»), response);
},
request: function(method, params) {
var self = this;
return new RSVP.Promise(function(resolve, reject) {
var id;
self.post(«rpc:request», {
method: method,
params: params,
id: (id = self.uuid.generate(«rpc» + self.id))
});
self.once([«rpc», «response», id].join(«:»), function(response) {
if (response.error) {
reject(err);
return;
}
resolve(response.result);
});
});
},
post: function(topic, data) {
var self = this;
return new RSVP.Promise(function(resolve, reject) {
if (!self.isEstablished()) {
self.buffer.push(_.toArray(arguments).concat(resolve));
return;
}
self.emit(«post», topic, data, resolve);
});
}
}
);
module.exports = Connection;
},{«../events/emitter/node»:31,»lodash»:»7ZYSzK»,»rsvp»:84}],10:[function(require,module,exports){
var Actor = require(«./actor»),
_ = require(«lodash»),
MasterActor;
/**
* MasterActor
*
* @class MasterActor
* @extends Actor
* @author Sergey Kamardin
*/
MasterActor = Actor.extend(
/**
* @lends MasterActor.prototype
*/
{
/**
* @abstract
*/
connect: function(otherWindow, options) {
throw new Error(«Method ‘connect’ must be implemented»);
}
}
);
module.exports = MasterActor;
},{«./actor»:1,»lodash»:»7ZYSzK»}],»qBxYoh»:[function(require,module,exports){
/**
* Master
*
* @package Master
* @author Sergey Kamardin
*/
var Master = require(«../master»),
_ = require(«lodash»),
Connection = require(«../connection»),
Poster = require(«./../poster/rotating»);
module.exports = Master.extend({
constructor: function() {
Master.prototype.constructor.apply(this, arguments);
this.subjectID = this.uuid.generate(«master»);
this.connections = {};
this.posters = {};
this.posts = {};
},
connect: function(otherWindow, options) {
var self = this,
connection, recipient, poster,
postOptions;
// generate slave id
recipient = this.uuid.generate(«slave»);
postOptions = {
recipient: recipient,
subject: this.subjectID
};
// get post handler
poster = new Poster(this.commutation.getWriter(otherWindow, options));
// set message id generator
poster.injectIDGenerator(function() {
return self.uuid.generate(«message»);
});
this.posters[recipient] = poster;
this.connections[recipient] = connection = new Connection(recipient, this.uuid);
// listen signals to post something
connection.on(«post», function(topic, data, done) {
var id;
id = poster.post(topic, data, postOptions);
self.posts[recipient] || (self.posts[recipient] = {});
self.posts[recipient][id] = done;
});
// start listening messages
this.reader = self.commutation.getReader();
this.reader.initialize();
this.reader.on(«message», _.bind(self._onMessage, self));
//init connection
poster.post(«handshake», {
id: recipient,
location: window.location.href // punycode
}, postOptions);
// return connection
return connection;
},
_onMessage: function(message) {
var connection, poster, subject, resolver;
subject = message.subject;
poster = this.posters[subject];
if (message.topic !== «delivered» && poster) {
poster.add(«delivered», message.id, { ack: true });
}
if (this._isKnown(message)) {
return;
}
this.known.push(message.id);
switch (message.topic) {
case «handshake»: {
if ((connection = this.connections[subject]) && !connection.isEstablished()) {
connection.isEstablished(true);
}
break;
}
case «delivered»: {
poster && poster.remove(message.data);
if (this.posts[subject] && _.isFunction(resolver = this.posts[subject][message.data])) {
resolver.call();
}
break;
}
default: {
if ((connection = this.connections[subject]) && connection.isEstablished()) {
connection.handle(message.topic, message.data);
}
}
}
poster.flush();
}
});
},{«../connection»:9,»../master»:10,»./../poster/rotating»:14,»lodash»:»7ZYSzK»}],»/common/script/src/communication/master/default.js»:[function(require,module,exports){
module.exports=require(‘qBxYoh’);
},{}],13:[function(require,module,exports){
var _ = require(«lodash»),
inherits = require(«inherits-js»),
assert = require(«assert»),
Writer = require(«./writer»),
Poster;
/**
* Poster
*
* @class Poster
* @constructor
* @abstract
*
* @param {Writer} writer
* @param {Object} options
*
* @author Sergey Kamardin
*/
Poster = function(writer, options) {
assert(writer instanceof Writer);
this.writer = writer;
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
Poster.DEFAULTS = {};
Poster.prototype = {
constructor: Poster,
/**
* Injection
* @param {Function} IDGenerator
*/
injectIDGenerator: function(IDGenerator) {
assert(_.isEmpty(this.IDGenerator), «IdGenerator is already set»);
assert(_.isFunction(IDGenerator), «Function is expected»);
this.IDGenerator = IDGenerator;
},
/**
* @abstract
*/
add: function(topic, data, options) {
throw new Error(«Method ‘add’ must be implemented»);
},
/**
* @abstract
*/
post: function(topic, data, options) {
throw new Error(«Method ‘post’ must be implemented»);
},
/**
* @abstract
*/
remove: function(id) {
throw new Error(«Method ‘remove’ must be implemented»);
},
/**
* @abstract
*/
flush: function() {
throw new Error(«Method ‘flush’ must be implemented»);
}
};
Poster.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Poster;
},{«./writer»:18,»assert»:62,»inherits-js»:80,»lodash»:»7ZYSzK»}],14:[function(require,module,exports){
var Poster = require(«../poster»),
_ = require(«lodash»),
RotatingPoster;
/**
* RotatingPoster
*
* @class RotatingPoster
* @extends Poster
* @author Sergey Kamardin
*/
RotatingPoster = Poster.extend(
/**
* @lends RotatingPoster.prototype
*/
{
constructor: function() {
Poster.prototype.constructor.apply(this, arguments);
this.acks = [];
this.messages = [];
this._flushID = null;
this._repeatID = null;
},
add: function(topic, data, options) {
var message;
options = options || {};
message = {
topic: topic,
data: data,
subject: options.subject,
recipient: options.recipient,
id: this.IDGenerator()
};
if (options.ack) {
this.acks.push(message.id);
}
this.messages.push(message);
this._registerRepeat();
return message.id;
},
_registerRepeat: function() {
var self = this;
clearInterval(this._repeatID);
this._repeatID = setInterval(function() {
if (_.isEmpty(self.messages)) {
clearInterval(self._repeatID);
return;
}
self.flush();
}, this.options.interval);
},
post: function(topic, data, options) {
var id;
id = this.add(topic, data, options);
this.flush();
return id;
},
remove: function(id) {
_.remove(this.messages, { id: id });
},
flush: function() {
var self = this;
clearTimeout(this._flushID);
this._flushID = setTimeout(function() {
self.writer.write(self.messages);
self._clearAcks();
}, 0);
},
_clearAcks: function() {
// remove acks from queue
_.forEach(this.acks, _.bind(this.remove, this));
this.acks = [];
}
},
/**
* @lends RotatingPoster
*/
{
DEFAULTS: {
interval: 500
}
}
);
module.exports = RotatingPoster;
},{«../poster»:13,»lodash»:»7ZYSzK»}],15:[function(require,module,exports){
var _ = require(«lodash»),
inherits = require(«inherits-js»),
EventEmitter = require(«events»).EventEmitter,
Reader;
/**
* Reader
*
* @class Reader
* @extends EventEmitter
* @constructor
* @abstract
*
* @param {Object} [options]
*
* @author Sergey Kamardin
*/
Reader = inherits(EventEmitter,
/**
* @lends Reader.prototype
*/
{
constructor: function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
},
/**
* @abstract
*/
initialize: function() {
throw new Error(«Method ‘initialize’ must be implemented»);
},
parseMessage: function(message) {
try {
if (_.isObject(message = JSON.parse(message))) {
return message;
}
} catch (err) {}
return null;
}
},
/**
* @lends Reader
*/
{
DEFAULTS: {}
}
);
Reader.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Reader;
},{«events»:63,»inherits-js»:80,»lodash»:»7ZYSzK»}],16:[function(require,module,exports){
var Reader = require(«../reader»),
_ = require(«lodash»),
HashReader;
/**
* HashReader
*
* @class HashReader
* @extends Reader
* @author Sergey Kamardin
*/
HashReader = Reader.extend(
/**
* @lends HashReader.prototype
*/
{
constructor: function() {
Reader.prototype.constructor.apply(this, arguments);
this.pattern = new RegExp(«\\(%(.+?)%\\)», «g»);
},
initialize: function() {
this._start();
},
_start: function() {
var self = this;
if (this.intervalId) {
return;
}
this.intervalId = setInterval(function() {
_.forEach(self._extractMessages(), _.bind(self._onMessage, self));
}, this.options.interval);
console.log(‘this.options.interval’, this.options.interval);
},
_stop: function() {
if (this.intervalId) {
clearInterval(this.intervalId);
this.intervalId = null;
}
},
_extractMessages: function() {
var self = this,
hash, messages;
messages = [];
hash = window.location.hash;
hash = hash.replace(this.pattern, function(str, message) {
if (message = self.parseMessage(message)) {
messages.push(message);
return «»;
}
// safe replace
return str;
});
if (hash == «» || hash == «#») {
hash = «#!»;
}
// this._throwAnchor();
window.location.hash = hash;
return messages;
},
_onMessage: function(message) {
this.emit(«message», message);
},
_throwAnchor: function() {
var anchor;
anchor = document.createElement(‘div’);
_.extend(anchor.style, {
height: «1px»,
width: «1px»,
position: «absolute»,
top: this.utils.getBodyScrollTop() + ‘px’
});
document.body.appendChild(anchor);
anchor.scrollIntoView();
anchor.parentNode.removeChild(anchor);
}
},
/**
* @lends HashReader
*/
{
DEFAULTS: {
interval: 100
}
}
);
module.exports = HashReader;
},{«../reader»:15,»lodash»:»7ZYSzK»}],17:[function(require,module,exports){
var Reader = require(«../reader»),
_ = require(«lodash»),
PostMessageReader;
/**
* PostMessageReader
*
* @class PostMessageReader
* @extends Reader
* @author Sergey Kamardin
*/
PostMessageReader = Reader.extend(
/**
* @lends PostMessageReader.prototype
*/
{
initialize: function() {
var self = this,
handler;
handler = function(event) {
var message;
if (!(message = self.parseMessage(event.data))) {
return;
}
self.emit(«message», message);
};
if (window.addEventListener) {
window.addEventListener(«message», handler);
} else if (window.attachEvent) {
window.attachEvent(«onmessage», handler);
}
}
}
);
module.exports = PostMessageReader;
},{«../reader»:15,»lodash»:»7ZYSzK»}],18:[function(require,module,exports){
var _ = require(«lodash»),
inherits = require(«inherits-js»),
Writer;
/**
* Writer
*
* @class Writer
* @constructor
* @abstract
*
* @param {Window} window
* @param {Object} [options]
*
* @author Sergey Kamardin
*/
Writer = function(window, options) {
this.window = window;
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
Writer.DEFAULTS = {};
Writer.prototype = {
constructor: Writer,
/**
* @abstract
*/
write: function(message) {
throw new Error(«Method ‘write’ must be implemented»);
},
stringifyMessage: function(message) {
return JSON.stringify(message);
}
};
Writer.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Writer;
},{«inherits-js»:80,»lodash»:»7ZYSzK»}],19:[function(require,module,exports){
var Writer = require(«../writer»),
_ = require(«lodash»),
assert = require(«assert»),
HashWriter;
/**
* HashWriter
*
* @class HashWriter
* @extends Writer
* @author Sergey Kamardin
*/
HashWriter = Writer.extend(
/**
* @lends HashWriter.prototype
*/
{
constructor: function(window, options) {
Writer.prototype.constructor.apply(this, arguments);
assert(!_.isUndefined(options.location), «Other window location is necessary option for hash communication»);
this.location = options.location;
},
/**
*
* @param {Array|Object} messages
*/
write: function(messages) {
var self = this,
buffer;
assert(!_.isUndefined(messages), «Message is expected to be an Object or Array»);
if (!_.isArray(messages)) {
messages = [messages]
}
buffer = [];
buffer.push(this.location.indexOf(«#») !== -1 ? «» : «#!»);
_.forEach(messages, function(message) {
buffer.push(self.stringifyMessage(message));
});
this.window.location.replace(this.location + buffer.join(»));
},
stringifyMessage: function(message) {
return ‘(%’ + Writer.prototype.stringifyMessage.call(this, message) + ‘%)’;
}
}
);
module.exports = HashWriter;
},{«../writer»:18,»assert»:62,»lodash»:»7ZYSzK»}],20:[function(require,module,exports){
var Writer = require(«../writer»),
_ = require(«lodash»),
assert = require(«assert»),
PostMessageWriter;
/**
* PostMessageWriter
*
* @class PostMessageWriter
* @extends Writer
* @author Sergey Kamardin
*/
PostMessageWriter = Writer.extend(
/**
* @lends PostMessageWriter.prototype
*/
{
write: function(messages) {
var self = this;
assert(!_.isUndefined(messages), «Message is expected to be an Object or Array»);
if (!_.isArray(messages)) {
messages = [messages]
}
_.forEach(messages, function(message) {
self.window.postMessage(self.stringifyMessage(message), self.options.origin);
});
}
},
/**
* @lends PostMessageWriter
*/
{
DEFAULTS: {
origin: «*»
}
}
);
module.exports = PostMessageWriter;
},{«../writer»:18,»assert»:62,»lodash»:»7ZYSzK»}],21:[function(require,module,exports){
var _ = require(«lodash»),
inherits = require(«inherits-js»),
Cookie;
/**
* Cookie
*
* @class Cookie
* @constructor
* @abstract
*
* @param {Object} [options]
*
* @author Sergey Kamardin
*/
Cookie = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
Cookie.DEFAULTS = {};
Cookie.prototype = {
constructor: Cookie,
/**
* @abstract
*/
get: function(key) {
throw new Error(«Method ‘get’ must be implemented»);
},
/**
* @abstract
*/
set: function(key, value, options) {
throw new Error(«Method ‘set’ must be implemented»);
},
/**
* @abstract
*/
remove: function(key) {
throw new Error(«Method ‘remove’ must be implemented»);
},
/**
* @abstract
*/
wait: function(key, options, done) {
throw new Error(«Method ‘wait’ must be implemented»);
},
/**
* @abstract
*/
all: function() {
throw new Error(«Method ‘all’ must be implemented»);
}
};
Cookie.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Cookie;
},{«inherits-js»:80,»lodash»:»7ZYSzK»}],»/common/script/src/cookie/service/default.js»:[function(require,module,exports){
module.exports=require(‘UIXSt0’);
},{}],»UIXSt0″:[function(require,module,exports){
var Cookie = require(«../service»),
_ = require(«lodash»),
DefaultCookie;
/**
* DefaultCookie
*
* @class DefaultCookie
* @extends Cookie
* @author Sergey Kamardin
*/
DefaultCookie = Cookie.extend(
/**
* @lends DefaultCookie.prototype
*/
{
constructor: function() {
Cookie.prototype.constructor.apply(this, arguments);
this.namespace = this.options.namespace == «» ? «» : this.options.namespace + «.»;
},
/**
* Get out cookie by filter function
*
* @param {string} key
*
* @returns mixed|null
*/
get: function(key) {
var result = null;
this.each(function(value, name) {
if (name === key) {
result = value;
return true;
}
});
return result;
},
/**
* Sets cookie with options
*
* @param {string} key
* @param {string} value
* @param {Object} options
*/
set: function(key, value, options) {
var self = this,
installString, pairs;
// If is given a hash of values
if (_.isObject(key)) {
pairs = _.reduce(key, function(pairs, value, name) {
pairs.push([name, value]);
return pairs;
}, []);
options = value || {};
} else {
pairs = [[name, value]];
options = options || {};
}
// Prepare options
options = _.reduce(_.extend({}, this.options.store, options), function(options, value, option) {
switch (option) {
case «expires»: {
options[option] = self.expire(value);
break;
}
case «path»:
case «domain»: {
options[option] = value;
break;
}
default: {
//
}
}
return options;
}, {});
_.each(pairs, function(pair) {
var name = pair[0],
value = pair[1];
if (!_.isString(value)) throw new TypeError(«Set value must be a string»);
installString = self.wrap(self.trim(name), self.namespace) + «=» + value;
_.each(options, function(value, key) {
installString+= «; » + key + «=» + value;
});
document.cookie = installString;
});
},
/**
* Removes cookie
*
* @param {string} key
*/
remove: function(key) {
this.set(key, «», {expires: -1});
},
/**
* Waits for cookie
*
* @param key
* @param options
* @param done
*/
wait: function(key, options, done) {
var self = this,
counter, start, delay, ticker, intervalID;
if (_.isFunction(options)) {
done = options;
options = {};
}
if (_.isNumber(options)) {
options = {
time: options
};
}
options = _.extend(options || {}, self.options.wait);
counter = 0;
start = this.stamp();
delay = Math.floor(options.time / options.ticks);
ticker = function() {
var mustBreak, current, duration;
current = self.get(name);
counter++;
duration = self.stamp() — start;
mustBreak = false;
mustBreak = mustBreak || current !== options.exclude;
mustBreak = mustBreak || counter > options.ticks;
mustBreak = mustBreak || duration > options.time;
if (mustBreak) {
done(null, current);
}
return mustBreak;
};
if (!ticker()) {
intervalID = setInterval(function() {
if (ticker()) clearInterval(intervalID);
},delay);
}
},
/**
* Retrieves all cookies.
*
* @returns {Object}
*/
all: function() {
var memo;
memo = {};
this.each(function(value, name) {
memo[name] = value;
});
return memo;
},
/**
* @private
*/
stamp: function() {
return (new Date()).getTime();
},
/**
* @private
* @param value
* @param prefix
* @returns {*}
*/
wrap: function(value, prefix) {
if (_.isString(value)) {
value = prefix + value;
}
return value;
},
/**
* @private
* @param value
* @param prefix
* @returns {*}
*/
unwrap: function(value, prefix) {
if (_.isString(value)) {
if (value.indexOf(prefix) == 0) {
value = value.substr(prefix.length);
}
}
return value;
},
trim: function(str) {
var native;
if (_.isFunction(native = String.prototype.trim)) {
return native.call(str);
}
return str.replace(/^\s+|\s+$/g, »);
},
/**
* @private
* @param time
* @returns {string}
*/
expire: function(time) {
var date = new Date();
date.setTime(date.getTime() + parseInt(time, 10));
return date.toUTCString();
},
/**
* Each cookie iterator
*
* @private
* @param {Function} iterator
* @param {Object} [context]
*/
each: function(iterator, context) {
var cookies, len, x, split, name, value;
if (!_.isFunction(iterator)) {
return;
}
if ((cookies = document.cookie).length == 0) {
return;
}
cookies = cookies.split(«;»);
len = cookies.length;
try {
for (x = 0; x < len; x++) {
split = cookies[x].split("=");
name = this.unwrap(this.trim(split[0]), this.namespace);
value = decodeURIComponent(split[1]);
if (iterator.call(context, value, name) != void 0) {
return;
}
}
} catch (e) {
return;
}
}
},
{
DEFAULTS: {
wait: {
time: 3000,
ticks: 10
},
namespace: "",
store: {
path: "/"
}
}
}
);
module.exports = DefaultCookie;
},{"../service":21,"lodash":"7ZYSzK"}],24:[function(require,module,exports){
/**
* Bus
*
* @package Bus
* @author Sergey Kamardin
*/
var _ = require(«lodash»),
inherits = require(«inherits-js»),
Bus;
Bus = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
Bus.DEFAULTS = {};
Bus.prototype = {
constructor: Bus,
on: function(event, filter, callback, context) {
throw new Error(«Method must be implemented»);
},
once: function(event, filter, callback, context) {
throw new Error(«Method must be implemented»);
},
off: function(event, filter, callback, context) {
throw new Error(«Method must be implemented»);
},
emit: function(event) {
throw new Error(«Method must be implemented»);
}
};
Bus.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Bus;
},{«inherits-js»:80,»lodash»:»7ZYSzK»}],»ICIzPU»:[function(require,module,exports){
var Bus = require(«../bus»),
EventEmitter = require(«../emitter/node»),
_ = require(«lodash»),
EmitterBus;
/**
* EmitterBus
*
* @class EmitterBus
* @extends Bus
* @author Sergey Kamardin
*/
EmitterBus = Bus.extend(
/**
* @lends EmitterBus.prototype
*/
{
constructor: function() {
this.emitter = new EventEmitter;
this.listeners = [];
},
_getListener: function(event, filter, callback, context) {
var listener, obj;
if (_.isFunction())
if (_.isFunction(filter) && !_.isFunction(callback)) {
context = callback;
callback = filter;
filter = null;
}
obj = {
event: event,
filter: filter,
callback: callback,
context: context
};
if (!(listener = _.find(this.listeners, obj))) {
listener = _.extend(obj, {
func: function() {
var valid;
valid = true;
if (_.isFunction(filter)) {
valid = valid && filter.apply(context, arguments);
}
if (valid) {
callback.apply(context, arguments);
}
}
});
this.listeners.push(listener);
}
return listener.func;
},
on: function(event, filter, callback, context) {
this.emitter.on(event, this._getListener.apply(this, arguments));
},
once: function(event, filter, callback, context) {
this.emitter.once(event, this._getListener.apply(this, arguments));
},
off: function(event, filter, callback, context) {
if (!_.isFunction(filter)) {
this.emitter.removeAllListeners(event);
} else {
this.emitter.removeListener(event, this._getListener.apply(this, arguments));
}
},
emit: function(event) {
this.emitter.emit.apply(this.emitter, arguments);
}
}
);
module.exports = EmitterBus;
},{«../bus»:24,»../emitter/node»:31,»lodash»:»7ZYSzK»}],»/common/script/src/events/bus/emitter.js»:[function(require,module,exports){
module.exports=require(‘ICIzPU’);
},{}],27:[function(require,module,exports){
var _ = require(«lodash»),
inherits = require(«inherits-js»),
ElementEventManager;
/**
* ElementEventManager
*
* @class ElementEventManager
* @constructor
* @abstract
*
* @param {Object} [options]
*
* @author Sergey Kamardin
*/
ElementEventManager = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
ElementEventManager.DEFAULTS = {};
ElementEventManager.prototype = {
constructor: ElementEventManager,
/**
* @abstract
*/
on: function(target, topic, handler) {
throw new Error(«Method ‘on’ must be implemented»);
},
/**
* @abstract
*/
once: function(target, topic, handler) {
throw new Error(«Method ‘once’ must be implemented»);
},
/**
* @abstract
*/
off: function(target, topic, handler) {
throw new Error(«Method ‘off’ must be implemented»);
}
};
ElementEventManager.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = ElementEventManager;
},{«inherits-js»:80,»lodash»:»7ZYSzK»}],»4MvLV1″:[function(require,module,exports){
var ElementEventManager = require(«../element»),
_ = require(«lodash»),
DefaultElementEventManager;
/**
* DefaultElementEventManager
*
* @class DefaultElementEventManager
* @extends ElementEventManager
* @author Sergey Kamardin
*/
DefaultElementEventManager = ElementEventManager.extend(
/**
* @lends DefaultElementEventManager.prototype
*/
{
constructor: function() {
ElementEventManager.prototype.constructor.apply(this, arguments);
this.guid = 0;
},
on: function(target, topic, handler) {
var self = this,
events, pool;
if (!(events = target._events)) {
target._events = events = {};
target._handle = function(event) {
if (typeof event !== «undefined») {
return self._handle.call(self, target, event);
}
}
}
if (!(pool = events[topic])) {
events[topic] = pool = [];
if (target.addEventListener) {
target.addEventListener(topic, target._handle, false);
} else if (target.attachEvent) {
target.attachEvent(«on» + topic, target._handle);
}
}
pool.push(handler);
},
off: function(target, topic, handler) {
var events, handlers;
if (!(events = target._events) || !(handlers = events[topic])) {
return;
}
if (handler) {
_.remove(handlers, function(existing) {
return existing === handler;
});
}
if (!handler || _.isEmpty(handlers)) {
delete events[topic];
if (target.removeEventListener) {
target.removeEventListener(topic, target._handle, false);
} else if (target.detachEvent) {
target.detachEvent(«on» + topic, target._handle);
}
}
if (_.isEmpty(target._events)) {
try {
delete target._events;
delete target._handle;
} catch(err) {
target[«_events»] = void 0;
target[«_handle»] = void 0;
}
}
},
once: function(target, topic, handler) {
var self = this,
once;
once = function(event) {
handler.call(null, event);
self.off(target, topic, once);
};
this.on(target, topic, once);
},
_handle: function(target, event) {
var events, handlers;
if ((events = target._events) && (handlers = events[event.type])) {
// here we slicing, cause in `once` case array could change
// after handler#call
_.forEach(handlers.slice(), function(handler) {
handler.call(null, event);
});
}
}
}
);
module.exports = DefaultElementEventManager;
},{«../element»:27,»lodash»:»7ZYSzK»}],»/common/script/src/events/element/default.js»:[function(require,module,exports){
module.exports=require(‘4MvLV1’);
},{}],30:[function(require,module,exports){
/**
* Abstract EventEmitter.
*
* @package EventEmitter
* @author Sergey Kamardin
*/
var _ = require(«lodash»),
inherits = require(«inherits-js»),
EventEmitter;
EventEmitter = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
EventEmitter.DEFAULTS = {};
EventEmitter.ALL = «*»;
EventEmitter.prototype = {
constructor: EventEmitter,
/**
* Add listener.
*
* @param event
* @param listener
*/
addListener: function(event, listener) {
throw new Error(«Method must be implemented»);
},
/**
* @proxy addListener
* @param event
* @param listener
*/
on: function(event, listener) {
throw new Error(«Method must be implemented»);
},
/**
* Add listener for one event.
*
* @param event
* @param listener
*/
once: function(event, listener) {
throw new Error(«Method must be implemented»);
},
/**
* Removes listener.
*
* @param event
* @param listener
*/
removeListener: function(event, listener) {
throw new Error(«Method must be implemented»);
},
/**
* @proxy removeListener|removeAllListeners
* @param [event]
* @param [listener]
*/
off: function(event, listener) {
throw new Error(«Method must be implemented»);
},
/**
* Removes all listeners.
* @param [event]
*/
removeAllListeners: function(event) {
throw new Error(«Method must be implemented»);
},
/**
* Sets maximum for listeners.
*
* @param n
*/
setMaxListeners: function(n) {
throw new Error(«Method must be implemented»);
},
/**
* Return list of listeners.
*
* @param event
* @returns Array
*/
listeners: function(event) {
throw new Error(«Method must be implemented»);
},
/**
* Emits event.
* @param event
*/
emit: function(event) {
throw new Error(«Method must be implemented»);
}
};
EventEmitter.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = EventEmitter;
},{«inherits-js»:80,»lodash»:»7ZYSzK»}],31:[function(require,module,exports){
/**
* Emitter
*
* @package Emitter
* @author Sergey Kamardin
*/
var Emitter = require(«../emitter»),
EventEmitter = require(«events»).EventEmitter,
_ = require(«lodash»);
module.exports = Emitter.extend({
constructor: function() {
Emitter.prototype.constructor.apply(this, arguments);
this._emitter = new EventEmitter;
},
/**
* Add listener.
*
* @param event
* @param listener
*/
addListener: function(event, listener) {
return this._emitter.addListener(event, listener);
},
/**
* @proxy addListener
* @param event
* @param listener
*/
on: function(event, listener) {
return this._emitter.on(event, listener);
},
/**
* Add listener for one event.
*
* @param event
* @param listener
*/
once: function(event, listener) {
return this._emitter.once(event, listener);
},
/**
* Removes listener.
*
* @param event
* @param listener
*/
removeListener: function(event, listener) {
return this._emitter.removeListener(event, listener);
},
/**
* @proxy removeListener|removeAllListeners
* @param [event]
* @param [listener]
*/
off: function(event, listener) {
if (!_.isUndefined(listener)) {
return this._emitter.removeListener(event, listener);
} else {
return this.removeAllListeners(event);
}
},
/**
* Removes all listeners.
* @param [event]
*/
removeAllListeners: function(event) {
return this._emitter.removeAllListeners(event);
},
/**
* Sets maximum for listeners.
*
* @param n
*/
setMaxListeners: function(n) {
return this._emitter.setMaxListeners(n);
},
/**
* Return list of listeners.
*
* @param event
* @returns Array
*/
listeners: function(event) {
return this._emitter.listeners(event);
},
/**
* Emits event.
* @param event
*/
emit: function(event) {
var args;
// construct args for all event
args = Array.prototype.slice.call(arguments);
args.unshift(Emitter.ALL);
// emit normal event
this._emitter.emit.apply(this._emitter, arguments);
// emit all event
this._emitter.emit.apply(this._emitter, args);
}
});
},{«../emitter»:30,»events»:63,»lodash»:»7ZYSzK»}],32:[function(require,module,exports){
/**
* Handler
*
* @package Handler
* @author Sergey Kamardin
*/
var _ = require(«lodash»),
inherits = require(«inherits-js»),
Handler;
Handler = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
Handler.DEFAULTS = {};
Handler.prototype = {
constructor: Handler,
handle: function(event) {
throw new Error(«Method must be implemented»);
}
};
Handler.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Handler;
},{«inherits-js»:80,»lodash»:»7ZYSzK»}],»/common/script/src/events/handler/bus.js»:[function(require,module,exports){
module.exports=require(‘afxkls’);
},{}],»afxkls»:[function(require,module,exports){
/**
* Event handler
*
* @package Handler
* @author Sergey Kamardin
*/
var Handler = require(«../handler»),
_ = require(«lodash»),
RSVP = require(«rsvp»);
module.exports = Handler.extend({
setBus: function(bus) {
this.bus = bus;
},
handle: function() {
this.bus.emit.apply(this.bus, arguments);
}
});
},{«../handler»:32,»lodash»:»7ZYSzK»,»rsvp»:84}],35:[function(require,module,exports){
var _ = require(«lodash»),
EventEmitter = require(«../emitter»);
module.exports = {
_proxy: function(event, options) {
var self = this,
prefixer, isAll;
if (_.isObject(event) || _.isUndefined(event)) {
options = event;
event = EventEmitter.ALL;
}
isAll = event === EventEmitter.ALL;
options = options || {};
prefixer = options.prefixer || function(event) {
return event;
};
return function() {
var args;
args = Array.prototype.slice.call(arguments);
options.self && args.unshift(self);
args.unshift(prefixer(isAll ? args.shift() : event));
self.emit.apply(self, args);
_.forEach(self.handlers, function(handler) {
handler.handle.apply(handler, args)
});
}
}
};
},{«../emitter»:30,»lodash»:»7ZYSzK»}],36:[function(require,module,exports){
var _ = require(«lodash»),
inherits = require(«inherits-js»),
assert = require(«assert»),
Query;
/**
* Query
*
* @class Query
* @constructor
* @abstract
*
* @param {Object} [options]
*
* @author Sergey Kamardin
*/
Query = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
Query.DEFAULTS = {};
Query.prototype = {
constructor: Query,
/**
* @abstract
*/
getQuery: function(property) {
throw new Error(«Method ‘getQuery’ must be implemented»);
},
/**
* @abstract
*/
getReferrer: function() {
throw new Error(«Method ‘getReferrer’ must be implemented»);
},
/**
* @abstract
*/
getPathName: function() {
throw new Error(«Method ‘getPathName’ must be implemented»);
},
/**
* @abstract
*/
getOrigin: function() {
throw new Error(«Method ‘getOrigin’ must be implemented»);
},
/**
* @abstract
*/
getHostName: function() {
throw new Error(«Method ‘getHostName’ must be implemented»);
},
/**
* @abstract
*/
getURL: function() {
throw new Error(«Method ‘getURL’ must be implemented»);
}
};
Query.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Query;
},{«assert»:62,»inherits-js»:80,»lodash»:»7ZYSzK»}],»/common/script/src/location/query/document.js»:[function(require,module,exports){
module.exports=require(‘sr8Lnt’);
},{}],»sr8Lnt»:[function(require,module,exports){
var Query = require(«../query»),
_ = require(«lodash»),
assert = require(«assert»),
DocumentQuery;
/**
* DocumentQuery
*
* @class DocumentQuery
* @extends Query
* @author Sergey Kamardin
*/
DocumentQuery = Query.extend(
/**
* @lends DocumentQuery.prototype
*/
{
constructor: function() {
Query.prototype.constructor.apply(this, arguments);
this.queryCache = null;
},
getQuery: (function() {
// Extractor regexp
// Search masks are:
// 1) name
// 2) isArray sign
// 3) value
var pattern = new RegExp(«[\\?&]([a-zA-Z0-9\\-\\.\\_\\~]+)(\\[\\])?=([^&#]*)», «g»);
function extractor(query) {
var parameters = {},
result, name, isArr, value;
try {
while ((result = pattern.exec(decodeURIComponent(query))) != null) {
name = result[1];
isArr = result[2];
value = result[3].replace(/\+/g, » «);
if (isArr) {
parameters[name] ? parameters[name].push(value) : (parameters[name] = [value]);
} else {
parameters[name] = value;
}
}
} catch (e) {}
return parameters;
}
return function(parameter) {
if (this.queryCache != document.location.search) {
this.query = extractor(document.location.search);
this.queryCache = document.location.search;
}
return parameter ? (this.query[parameter] || null) : this.query;
}
})(),
getOrigin: function() {
return document.location.origin;
},
getHostName: function() {
return document.location.hostname;
},
getPathName: function() {
return document.location.pathname;
},
getReferrer: function() {
return document.referrer;
},
getURL: function() {
return document.location.href;
},
extractHostName: function(value) {
assert(_.isString(value), «String is expected»);
return value.replace(this.constructor.hostNameRegex, ‘$1’);
}
},
{
hostNameRegex: /^([a-z]{3,5}:\/\/)?([^:/]+)(:\d+)?([^:]+)?$/i
}
);
module.exports = DocumentQuery;
},{«../query»:36,»assert»:62,»lodash»:»7ZYSzK»}],39:[function(require,module,exports){
module.exports = {
linear: function(t, b, c, d) {
return c*(t/=d) + b;
},
easeInQuad: function (t, b, c, d) {
return c*(t/=d)*t + b;
},
easeOutQuad: function (t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
},
easeInOutQuad: function (t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t + b;
return -c/2 * ((--t)*(t-2) - 1) + b;
},
easeInCubic: function (t, b, c, d) {
return c*(t/=d)*t*t + b;
},
easeOutCubic: function (t, b, c, d) {
return c*((t=t/d-1)*t*t + 1) + b;
},
easeInOutCubic: function (t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t + b;
return c/2*((t-=2)*t*t + 2) + b;
},
easeInQuart: function (t, b, c, d) {
return c*(t/=d)*t*t*t + b;
},
easeOutQuart: function (t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
easeInOutQuart: function (t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
easeInQuint: function (t, b, c, d) {
return c*(t/=d)*t*t*t*t + b;
},
easeOutQuint: function (t, b, c, d) {
return c*((t=t/d-1)*t*t*t*t + 1) + b;
},
easeInOutQuint: function (t, b, c, d) {
if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
return c/2*((t-=2)*t*t*t*t + 2) + b;
},
easeInSine: function (t, b, c, d) {
return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
},
easeOutSine: function (t, b, c, d) {
return c * Math.sin(t/d * (Math.PI/2)) + b;
},
easeInOutSine: function (t, b, c, d) {
return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
},
easeInExpo: function (t, b, c, d) {
return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
},
easeOutExpo: function (t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
},
easeInOutExpo: function (t, b, c, d) {
if (t==0) return b;
if (t==d) return b+c;
if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
},
easeInCirc: function (t, b, c, d) {
return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
},
easeOutCirc: function (t, b, c, d) {
return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
},
easeInOutCirc: function (t, b, c, d) {
if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
},
easeInElastic: function (t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; s=p/4; }
else s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
easeOutElastic: function (t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; s=p/4; }
else s = p/(2*Math.PI) * Math.asin (c/a);
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
easeInOutElastic: function (t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
if (a < Math.abs(c)) { a=c; s=p/4; }
else s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
},
easeInBack: function (t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
easeOutBack: function (t, b, c, d, s) {
if (s == undefined) s = 1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
easeInOutBack: function (t, b, c, d, s) {
if (s == undefined) s = 1.70158;
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
easeOutBounce: function (t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
}
}
};
},{}],40:[function(require,module,exports){
var _ = require("lodash"),
inherits = require("inherits-js"),
Source;
/**
* Source
*
* @class Source
* @constructor
* @abstract
*
* @param {Object} [options]
*
* @author Sergey Kamardin
*/
Source = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
Source.DEFAULTS = {};
Source.prototype = {
constructor: Source,
/**
* @abstract
*/
get: function(parameter, done) {
throw new Error(«Method ‘get’ must be implemented»);
}
};
Source.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Source;
},{«inherits-js»:80,»lodash»:»7ZYSzK»}],»4VLKn9″:[function(require,module,exports){
var Source = require(«../source»),
_ = require(«lodash»),
async = require(«async»),
assert = require(«assert»),
CompositeSource;
/**
* CompositeSource
*
* @class CompositeSource
* @extends Source
* @author Sergey Kamardin
*/
CompositeSource = Source.extend(
/**
* @lends CompositeSource.prototype
*/
{
constructor: function() {
Source.prototype.constructor.apply(this, arguments);
this.sources = [];
},
addSource: function(source) {
assert(source instanceof Source, «Source is expected»);
this.sources.push(source);
},
get: function(parameter, done) {
async.reduce(this.sources, null, function(value, source, nextSource) {
if (!_.isEmpty(value)) {
nextSource(null, value);
return;
}
source.get(parameter, nextSource);
}, done);
}
}
);
module.exports = CompositeSource;
},{«../source»:40,»assert»:62,»async»:»cEACDx»,»lodash»:»7ZYSzK»}],»/common/script/src/utm/source/composite.js»:[function(require,module,exports){
module.exports=require(‘4VLKn9’);
},{}],43:[function(require,module,exports){
var Source = require(«../source»),
_ = require(«lodash»),
assert = require(«assert»),
Cookie = require(«../../cookie/service»),
CookieSource;
/**
* CookieSource
*
* @class CookieSource
* @extends Source
* @author Sergey Kamardin
*/
CookieSource = Source.extend(
/**
* @lends CookieSource.prototype
*/
{
injectCookie: function(cookie) {
assert(_.isEmpty(this.cookie), «Cookie is already set»);
assert(cookie instanceof Cookie, «Cookie is expected»);
this.cookie = cookie;
}
}
);
module.exports = CookieSource;
},{«../../cookie/service»:21,»../source»:40,»assert»:62,»lodash»:»7ZYSzK»}],»/common/script/src/utm/source/cookie/plain.js»:[function(require,module,exports){
module.exports=require(‘Ov31qG’);
},{}],»Ov31qG»:[function(require,module,exports){
var CookieSource = require(«../cookie»),
_ = require(«lodash»),
PlainCookieSource;
/**
* PlainCookieSource
*
* @class PlainCookieSource
* @extends CookieSource
* @author Sergey Kamardin
*/
PlainCookieSource = CookieSource.extend(
/**
* @lends PlainCookieSource.prototype
*/
{
get: function(parameter, done) {
try {
done(null, this.cookie.get(parameter));
} catch (err) {
done(err);
}
}
}
);
module.exports = PlainCookieSource;
},{«../cookie»:43,»lodash»:»7ZYSzK»}],»lrpT+8″:[function(require,module,exports){
var CookieSource = require(«../cookie»),
_ = require(«lodash»),
UtmzCookieSource;
/**
* UtmzCookieSource
*
* @class UtmzCookieSource
* @extends CookieSource
* @author Sergey Kamardin
*/
UtmzCookieSource = CookieSource.extend(
/**
* @lends UtmzCookieSource.prototype
*/
{
mapping: {
utm_campaign: 6,
utm_medium: 7,
utm_term: 8
},
get: function(parameter, done) {
var self = this,
index;
if (!_.has(this.mapping, parameter)) {
done(null, null);
return;
}
index = this.mapping[parameter];
this.cookie.wait(«__utmz», this.options.wait, function(err, utmz) {
var match, result;
if (err) {
done(err);
return;
}
if (_.isString(utmz)) {
if (match = utmz.match(self.constructor.REGEXP)) {
result = match[index];
}
done(null, result || null);
return;
}
done(null, null);
});
}
},
{
// Retreiver from google’s utmz cookie
// Groups are:
// 1) domain hash
// 2) last update time in unix time format
// 3) time of visits fro resource by referrers from other pages
// 4) unique number of referrer pages
// 5) utmcsr — search engine
// 6) utmccn — adwords campaign (utm_campaign)
// 7) utmcmd — name of campaign (utm_medium)
// 8) utmctr — key words of search.
REGEXP: /([a-f0-9]+)\.(\d+)\.(\d+).(\d+)\.utmcsr=([^|]+)\|utmccn=([^|]*)\|utmcmd=([^|]*)\|utmctr=([^|]*)/i
}
);
module.exports = UtmzCookieSource;
},{«../cookie»:43,»lodash»:»7ZYSzK»}],»/common/script/src/utm/source/cookie/utmz.js»:[function(require,module,exports){
module.exports=require(‘lrpT+8’);
},{}],48:[function(require,module,exports){
var Source = require(«../source»),
_ = require(«lodash»),
assert = require(«assert»),
Query = require(«../../location/query»),
QuerySource;
/**
* QuerySource
*
* @class QuerySource
* @extends Source
* @author Sergey Kamardin
*/
QuerySource = Source.extend(
/**
* @lends QuerySource.prototype
*/
{
injectQuery: function(query) {
assert(_.isEmpty(this.query), «Query is already set»);
assert(query instanceof Query, «Query is expected»);
this.query = query;
}
}
);
module.exports = QuerySource;
},{«../../location/query»:36,»../source»:40,»assert»:62,»lodash»:»7ZYSzK»}],»A5jZcW»:[function(require,module,exports){
var QuerySource = require(«../query»),
_ = require(«lodash»),
LPQuerySource;
/**
* LPQuerySource
*
* @class LPQuerySource
* @extends QuerySource
* @author Sergey Kamardin
*/
LPQuerySource = QuerySource.extend(
/**
* @lends LPQuerySource.prototype
*/
{
get: function(parameter, done) {
if (parameter !== «lp») {
done(null, null);
return;
}
done(null, this.query.getOrigin() + this.query.getPathName());
}
}
);
module.exports = LPQuerySource;
},{«../query»:48,»lodash»:»7ZYSzK»}],»/common/script/src/utm/source/query/lp.js»:[function(require,module,exports){
module.exports=require(‘A5jZcW’);
},{}],»/common/script/src/utm/source/query/plain.js»:[function(require,module,exports){
module.exports=require(‘lMplo+’);
},{}],»lMplo+»:[function(require,module,exports){
var QuerySource = require(«../query»),
_ = require(«lodash»),
PlainQuerySource;
/**
* PlainQuerySource
*
* @class PlainQuerySource
* @extends QuerySource
* @author Sergey Kamardin
*/
PlainQuerySource = QuerySource.extend(
/**
* @lends PlainQuerySource.prototype
*/
{
get: function(parameter, done) {
done(null, this.query.getQuery(parameter));
}
}
);
module.exports = PlainQuerySource;
},{«../query»:48,»lodash»:»7ZYSzK»}],»w3TYPB»:[function(require,module,exports){
var QuerySource = require(«../query»),
_ = require(«lodash»),
UtmSourceQuerySource;
/**
* UtmSourceQuerySource
*
* @class UtmSourceQuerySource
* @extends QuerySource
* @author Sergey Kamardin
*/
UtmSourceQuerySource = QuerySource.extend(
/**
* @lends UtmSourceQuerySource.prototype
*/
{
get: function(parameter, done) {
var host, referrer,
result;
if (parameter !== «utm_source») {
done(null, null);
return;
}
host = this.query.getHostName();
referrer = this.query.getReferrer();
if (_.isEmpty(referrer)) {
done(null, null);
return;
}
result = this.normalize(host) !== this.normalize(this.query.extractHostName(referrer)) ? referrer : null;
done(null, result);
},
/**
* @private
* @param value
*/
normalize: function(value) {
return (value.indexOf(‘www.’) == 0) ? value.substring(4) : value;
}
}
);
module.exports = UtmSourceQuerySource;
},{«../query»:48,»lodash»:»7ZYSzK»}],»/common/script/src/utm/source/query/utm_source.js»:[function(require,module,exports){
module.exports=require(‘w3TYPB’);
},{}],55:[function(require,module,exports){
var _ = require(«lodash»),
assert = require(«assert»),
inherits = require(«inherits-js»),
Source = require(«./source»),
Cookie = require(«../cookie/service»),
UTM;
/**
* UTM
*
* @class UTM
* @constructor
* @abstract
*
* @param {Object} [options]
*
* @author Sergey Kamardin
*/
UTM = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
this.sources = [];
};
UTM.DEFAULTS = {};
UTM.prototype = {
constructor: UTM,
injectCookie: function(cookie) {
assert(_.isEmpty(this.cookie), «Cookie is already set»);
assert(cookie instanceof Cookie, «Cookie is expected»);
this.cookie = cookie;
},
addSource: function(source, isSupplement) {
assert(source instanceof Source, «Source is expected»);
this.sources.push({ source: source, isSupplement: isSupplement });
},
/**
* @abstract
*/
get: function(done) {
throw new Error(«Method ‘get’ must be implemented»);
}
};
UTM.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = UTM;
},{«../cookie/service»:21,»./source»:40,»assert»:62,»inherits-js»:80,»lodash»:»7ZYSzK»}],»/common/script/src/utm/utm/default.js»:[function(require,module,exports){
module.exports=require(‘M+jhLg’);
},{}],»M+jhLg»:[function(require,module,exports){
var UTM = require(«../utm»),
_ = require(«lodash»),
async = require(«async»),
DefaultUTM;
/**
* DefaultUTM
*
* @class DefaultUTM
* @extends UTM
* @author Sergey Kamardin
*/
DefaultUTM = UTM.extend(
/**
* @lends DefaultUTM.prototype
*/
{
get: function(done) {
var self = this,
parameters, necessary;
parameters = _.pluck(this.constructor.PARAMETERS, «name»);
necessary = _.chain(this.constructor.PARAMETERS)
.where({ necessary: true })
.pluck(«name»)
.value();
function isFull(utm) {
return _.difference(necessary, _.keys(utm)).length === 0;
}
async.reduce(
this.sources,
{},
function(result, definition, nextSource) {
var need, isSupplement, isMain;
isSupplement = definition.isSupplement;
if ((isMain = !isSupplement) && isFull(result)) {
nextSource(null, result);
return;
}
need = isSupplement ? _.difference(parameters, _.keys(result)) : parameters;
async.reduce(
need,
{},
function(utm, parameter, nextParameter) {
definition.source.get(parameter, function(err, value) {
if (err) {
nextParameter(err);
return;
}
if (!_.isEmpty(value)) {
utm[parameter] = value;
}
nextParameter(null, utm);
});
},
function(err, utm) {
if (err) {
nextSource(err);
return;
}
// if source is main and gave us all necessary fields
// then modify final result
if (isMain && !isFull(utm)) {
nextSource(null, result);
return;
}
nextSource(null, _.extend({}, result, utm));
}
);
},
function(err, result) {
if (err) {
done(err);
return;
}
self.cookie.set(result, self.options.cookie);
done(null, result);
}
);
}
},
{
PARAMETERS: [
{
name: «utm_source»,
necessary: true
},
{
name: «utm_medium»,
necessary: false
},
{
name: «utm_campaign»,
necessary: false
},
{
name: «utm_term»,
necessary: false
},
{
name: «utm_content»,
necessary: false
},
{
name: «wm»,
necessary: false
},
{
name: «sid»,
necessary: false
},
{
name: «lp»,
necessary: false
}
],
DEFAULTS: {
cookie: {
// per 3 hours
expires: 1000 * 60 * 60 * 3
}
}
}
);
module.exports = DefaultUTM;
},{«../utm»:55,»async»:»cEACDx»,»lodash»:»7ZYSzK»}],58:[function(require,module,exports){
var Subscriber = require(«./subscriber»),
utils = require(«./utils»),
resolve = utils.resolve,
reject = utils.reject,
noop = utils.noop,
Promise;
Promise = function(resolver, options) {
var self = this,
doResolve, doReject;
if (!(this instanceof Promise)) {
throw new TypeError(«Failed to construct ‘Promise’: Please use the ‘new’ operator, this object constructor cannot be called as a function.»);
}
if (!utils.isFunction(resolver)) {
throw new TypeError(‘You must pass a resolver function as the first argument to the promise constructor’);
}
this.options = utils.extend({}, this.constructor.DEFAULTS, options || {});
this._subscribers = [];
this._state = null;
this._value = null;
this._error = null;
doResolve = resolve(this);
doReject = reject(this);
try {
resolver(doResolve, doReject);
} catch (err) {
doReject(err);
}
};
Promise.DEFAULTS = {};
Promise.prototype = {
constructor: Promise,
«then»: function(onResolve, onReject) {
var subscriber;
this._subscribers.push((subscriber = new Subscriber(onResolve, onReject, new Promise(noop))));
// if promise is fullfilled already
if (!utils.isNull(this._state)) {
this._state ? subscriber.resolve(this._value) : subscriber.reject(this._error);
}
return subscriber.promise;
},
«finally»: function(onAnyWay) {
return this.then(function(value) {
onAnyWay(null, value);
}, function(err) {
onAnyWay(err);
});
},
«catch»: function(onReject) {
return this.then(null, onReject);
},
/**
* @deprecated
*/
«done»: function() {
return this.value();
},
«value»: function() {
if (!this._state) {
if (this._error) {
throw this._error;
}
throw new Error(«Can not retrieve value from not fullfilled promise»);
}
return this._value;
}
};
Promise.all = function(promises, strict) {
return new Promise(function(resolve, reject) {
var i, len, results, remaining, rejected,
target, getComplete, complete, next;
len = promises.length;
remaining = len;
rejected = false;
strict = utils.isBoolean(strict) ? strict : true;
if (!utils.isArray(promises)) {
throw new TypeError(«Array is expected»);
}
results = new Array(len);
if (!remaining) {
resolve(results);
return;
}
getComplete = function(i) {
return function(value) {
results[i] = value;
}
};
next = function() {
remaining—;
if (remaining === 0 && !rejected) {
resolve(results);
}
};
for (i = 0; i < len; i++) {
target = promises[i];
complete = getComplete(i);
if (target instanceof Promise) {
target
.then(complete)
['catch'](function(error) {
if (strict && !rejected) {
reject(error);
rejected = true;
}
})
['finally'](next);
} else {
complete(target);
next();
}
}
});
};
Promise.resolve = function(value) {
if (value instanceof Promise) {
return value;
}
return new Promise(function(resolve) {
resolve(value);
});
};
Promise.reject = function(err) {
return new Promise(function(resolve, reject) {
reject(err);
});
};
module.exports = Promise;
},{"./subscriber":59,"./utils":60}],59:[function(require,module,exports){
var utils = require("./utils"),
resolve = utils.resolve,
reject = utils.reject,
noop = utils.noop,
Subscriber;
Subscriber = function(resolve, reject, promise) {
this._resolve = resolve;
this._reject = reject;
this.promise = promise;
};
Subscriber.prototype = {
constructor: Subscriber,
_notify: function(action, error, val) {
var response, err, strategy, value;
strategy = error ? reject : resolve;
value = error ? error : val;
if (!utils.isFunction(action)) {
strategy(this.promise)(value);
return;
}
try {
response = action.call(null, value);
} catch(_err) {
reject(this.promise)(_err);
return;
}
if (response && response.then && utils.isFunction(response.then)) {
response.then(resolve(this.promise), reject(this.promise));
} else {
resolve(this.promise)(response);
}
},
resolve: function(value) {
this._notify(this._resolve, null, value);
},
reject: function(error) {
this._notify(this._reject, error);
}
};
module.exports = Subscriber;
},{"./utils":60}],60:[function(require,module,exports){
function toStringType(obj) {
return Object.prototype.toString.call(obj).replace(/\[object\s([a-zA-Z]+)\]/, "$1");
}
exports.resolve = function(promise) {
return function(value) {
if (!exports.isNull(promise._state)) {
throw new Error("Can not resolve fulfilled promise");
}
promise._state = true;
promise._value = value;
exports.forEach(promise._subscribers, function(subscriber) {
subscriber.resolve(value);
});
}
};
exports.reject = function(promise) {
return function(error) {
if (!exports.isNull(promise._state)) {
throw new Error("Can not reject fulfilled promise");
}
promise._state = false;
promise._error = error;
exports.forEach(promise._subscribers, function(subscriber) {
subscriber.reject(error);
});
};
};
exports.isArray = function(obj) {
return toStringType(obj) === "Array";
};
exports.isFunction = function(obj) {
return toStringType(obj) === "Function";
};
exports.isNull = function(obj) {
return toStringType(obj) === "Null";
};
exports.isBoolean = function(obj) {
return toStringType(obj) === "Boolean";
};
exports.noop = function() {};
exports.forEach = function(obj, iterator, context) {
var len, i;
if (!exports.isArray(obj)) {
throw new TypeError("Only Array");
}
len = obj.length;
for (i = 0; i < len; i++) {
iterator.call(context, obj[i], i, obj);
};
};
exports.extend = function(target) {
var args, len, i, prop, source;
if ( (len = arguments.length) < 2 || target == null ) {
return target;
}
args = Array.prototype.slice.call(arguments, 1);
len-= 1;
for (i = 0; i < len; i++) {
source = args[i];
for (prop in source) if (source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
return target;
};
},{}],61:[function(require,module,exports){
},{}],62:[function(require,module,exports){
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the ‘Software’), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// when used in node, this will actually load the util module we depend on
// versus loading the builtin util module as happens otherwise
// this is a bug in node module loading as far as I am concerned
var util = require(‘util/’);
var pSlice = Array.prototype.slice;
var hasOwn = Object.prototype.hasOwnProperty;
// 1. The assert module provides functions that throw
// AssertionError’s when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
assert.AssertionError = function AssertionError(options) {
this.name = ‘AssertionError’;
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
}
else {
// non v8 browsers so we can have a stacktrace
var err = new Error();
if (err.stack) {
var out = err.stack;
// try to strip useless frames
var fn_name = stackStartFunction.name;
var idx = out.indexOf(‘\n’ + fn_name);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
var next_line = out.indexOf(‘\n’, idx + 1);
out = out.substring(next_line + 1);
}
this.stack = out;
}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function replacer(key, value) {
if (util.isUndefined(value)) {
return » + value;
}
if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) {
return value.toString();
}
if (util.isFunction(value) || util.isRegExp(value)) {
return value.toString();
}
return value;
}
function truncate(s, n) {
if (util.isString(s)) {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function getMessage(self) {
return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
self.operator + ' ' +
truncate(JSON.stringify(self.expected, replacer), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
function _deepEqual(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (util.isBuffer(actual) && util.isBuffer(expected)) {
if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false;
}
return true;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (!util.isObject(actual) && !util.isObject(expected)) {
return actual == expected;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected);
}
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b) {
if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b);
}
try {
var ka = objectKeys(a),
kb = objectKeys(b),
key, i;
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i—) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length — 1; i >= 0; i—) {
key = ka[i];
if (!_deepEqual(a[key], b[key])) return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected)) {
fail(actual, expected, message, ‘notDeepEqual’, assert.notDeepEqual);
}
};
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, ‘===’, assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, ‘!==’, assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == ‘[object RegExp]’) {
return expected.test(actual);
} else if (actual instanceof expected) {
return true;
} else if (expected.call({}, actual) === true) {
return true;
}
return false;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (util.isString(expected)) {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
message = (expected && expected.name ? ‘ (‘ + expected.name + ‘).’ : ‘.’) +
(message ? ‘ ‘ + message : ‘.’);
if (shouldThrow && !actual) {
fail(actual, expected, ‘Missing expected exception’ + message);
}
if (!shouldThrow && expectedException(actual, expected)) {
fail(actual, expected, ‘Got unwanted exception’ + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws.apply(this, [true].concat(pSlice.call(arguments)));
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/message) {
_throws.apply(this, [false].concat(pSlice.call(arguments)));
};
assert.ifError = function(err) { if (err) {throw err;}};
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
},{«util/»:68}],63:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// «Software»), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error(‘(node) warning: possible EventEmitter memory ‘ +
‘leak detected. %d listeners added. ‘ +
‘Use emitter.setMaxListeners() to increase limit.’,
this._events[type].length);
if (typeof console.trace === ‘function’) {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError(‘listener must be a function’);
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a ‘removeListener’ event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError(‘listener must be a function’);
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit(‘removeListener’, type, listener);
} else if (isObject(list)) {
for (i = length; i— > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],64:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length — 1; i >= 0; i—) {
var last = parts[i];
if (last === ‘.’) {
parts.splice(i, 1);
} else if (last === ‘..’) {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up—;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up—; up) {
parts.unshift(‘..’);
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// ‘root’ is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from …], to)
// posix version
exports.resolve = function() {
var resolvedPath = »,
resolvedAbsolute = false;
for (var i = arguments.length — 1; i >= -1 && !resolvedAbsolute; i—) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== ‘string’) {
throw new TypeError(‘Arguments to path.resolve must be strings’);
} else if (!path) {
continue;
}
resolvedPath = path + ‘/’ + resolvedPath;
resolvedAbsolute = path.charAt(0) === ‘/’;
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split(‘/’), function(p) {
return !!p;
}), !resolvedAbsolute).join(‘/’);
return ((resolvedAbsolute ? ‘/’ : ») + resolvedPath) || ‘.’;
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === ‘/’;
// Normalize the path
path = normalizeArray(filter(path.split(‘/’), function(p) {
return !!p;
}), !isAbsolute).join(‘/’);
if (!path && !isAbsolute) {
path = ‘.’;
}
if (path && trailingSlash) {
path += ‘/’;
}
return (isAbsolute ? ‘/’ : ») + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === ‘/’;
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== ‘string’) {
throw new TypeError(‘Arguments to path.join must be strings’);
}
return p;
}).join(‘/’));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end—) {
if (arr[end] !== ») break;
}
if (start > end) return [];
return arr.slice(start, end — start + 1);
}
var fromParts = trim(from.split(‘/’));
var toParts = trim(to.split(‘/’));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,require("+xKvab"))
},{"+xKvab":65}],65:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
if (canPost) {
var queue = [];
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage(‘process-tick’, ‘*’);
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = ‘browser’;
process.browser = true;
process.env = {};
process.argv = [];
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error(‘process.binding is not supported’);
}
// TODO(shtylman)
process.cwd = function () { return ‘/’ };
process.chdir = function (dir) {
throw new Error(‘process.chdir is not supported’);
};
},{}],66:[function(require,module,exports){
if (typeof Object.create === ‘function’) {
// implementation from standard node.js ‘util’ module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],67:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === ‘object’
&& typeof arg.copy === ‘function’
&& typeof arg.fill === ‘function’
&& typeof arg.readUInt8 === ‘function’;
}
},{}],68:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// «Software»), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case ‘%s’: return String(args[i++]);
case ‘%d’: return Number(args[i++]);
case ‘%j’:
try {
return JSON.stringify(args[i++]);
} catch (_) {
return ‘[Circular]’;
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy…
ctx.showHidden = opts;
} else if (opts) {
// got an «options» object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
‘bold’ : [1, 22],
‘italic’ : [3, 23],
‘underline’ : [4, 24],
‘inverse’ : [7, 27],
‘white’ : [37, 39],
‘grey’ : [90, 39],
‘black’ : [30, 39],
‘blue’ : [34, 39],
‘cyan’ : [36, 39],
‘green’ : [32, 39],
‘magenta’ : [35, 39],
‘red’ : [31, 39],
‘yellow’ : [33, 39]
};
// Don’t use ‘blue’ not visible on cmd.exe
inspect.styles = {
‘special’: ‘cyan’,
‘number’: ‘yellow’,
‘boolean’: ‘yellow’,
‘undefined’: ‘grey’,
‘null’: ‘bold’,
‘string’: ‘green’,
‘date’: ‘magenta’,
// «name»: intentionally not styling
‘regexp’: ‘red’
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return ‘\u001b[‘ + inspect.colors[style][0] + ‘m’ + str +
‘\u001b[‘ + inspect.colors[style][1] + ‘m’;
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it’s inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn’t make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf(‘message’) >= 0 || keys.indexOf(‘description’) >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ‘: ‘ + value.name : »;
return ctx.stylize(‘[Function’ + name + ‘]’, ‘special’);
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), ‘regexp’);
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), ‘date’);
}
if (isError(value)) {
return formatError(value);
}
}
var base = », array = false, braces = [‘{‘, ‘}’];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = [‘[‘, ‘]’];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ‘: ‘ + value.name : »;
base = ‘ [Function’ + n + ‘]’;
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ‘ ‘ + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ‘ ‘ + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ‘ ‘ + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split(‘\n’).map(function(line) {
return ‘ ‘ + line;
}).join(‘\n’).substr(2);
} else {
str = ‘\n’ + str.split(‘\n’).map(function(line) {
return ‘ ‘ + line;
}).join(‘\n’);
}
}
} else {
str = ctx.stylize(‘[Circular]’, ‘special’);
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify(» + key);
if (name.match(/^»([a-zA-Z_][a-zA-Z_0-9]*)»$/)) {
name = name.substr(1, name.length — 2);
name = ctx.stylize(name, ‘name’);
} else {
name = name.replace(/’/g, «\\'»)
.replace(/\\»/g, ‘»‘)
.replace(/(^»|»$)/g, «‘»);
name = ctx.stylize(name, ‘string’);
}
}
return name + ‘: ‘ + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf(‘\n’) >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, »).length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === » ? » : base + ‘\n ‘) +
‘ ‘ +
output.join(‘,\n ‘) +
‘ ‘ +
braces[1];
}
return braces[0] + base + ‘ ‘ + output.join(‘, ‘) + ‘ ‘ + braces[1];
}
// NOTE: These type checking functions intentionally don’t use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === ‘boolean’;
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === ‘number’;
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === ‘string’;
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === ‘symbol’;
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === ‘[object RegExp]’;
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === ‘object’ && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === ‘[object Date]’;
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === ‘[object Error]’ || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === ‘function’;
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === ‘boolean’ ||
typeof arg === ‘number’ ||
typeof arg === ‘string’ ||
typeof arg === ‘symbol’ || // ES6 symbol
typeof arg === ‘undefined’;
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require(‘./support/isBuffer’);
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require("+xKvab"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"+xKvab":65,"./support/isBuffer":67,"inherits":66}],69:[function(require,module,exports){
var DependencyManager = require("./src/dm"),
loaderAMD = require("./src/dm/adapter/loader/amd"),
loaderCJS = require("./src/dm/adapter/loader/cjs"),
asyncRSVP = require("./src/dm/adapter/async/rsvp");
module.exports = {
DependencyManager: DependencyManager,
loader: {
amd: loaderAMD,
cjs: loaderCJS
},
async: {
RSVP: asyncRSVP
}
};
},{"./src/dm":70,"./src/dm/adapter/async/rsvp":73,"./src/dm/adapter/loader/amd":75,"./src/dm/adapter/loader/cjs":76}],70:[function(require,module,exports){
/*
import {
objectType,
isString,
isNumber,
isFunction,
isBoolean,
isDate,
isObject,
isRegExp,
isArray,
isUndefined,
forEachOwn,
forEachSimple,
map,
clone,
sprintf
} from "./dm/utils";
import Async from "./dm/adapter/async";
import Loader from "./dm/adapter/loader";
*/
var utils = require("./dm/utils"),
Async = require("./dm/adapter/async"),
Loader = require("./dm/adapter/loader"),
Factory = require("./dm/factory"),
inherits = require("inherits-js"),
objectType = utils.objectType,
isString = utils.isString,
isNumber = utils.isNumber,
isFunction = utils.isFunction,
isBoolean = utils.isBoolean,
isDate = utils.isDate,
isObject = utils.isObject,
isRegExp = utils.isRegExp,
isArray = utils.isArray,
isUndefined = utils.isUndefined,
forEach = utils.forEach,
forEachOwn = utils.forEachOwn,
forEachSimple = utils.forEachSimple,
map = utils.map,
bind = utils.bind,
clone = utils.clone,
extend = utils.extend,
sprintf = utils.sprintf,
async = utils.async,
DefaultFactory = require("./dm/factory/default"),
defaultFactory,
DependencyManager;
// may be turn it inside as internal service? "@:::factory.default"
defaultFactory = new DefaultFactory();
/**
* DM Constructor.
* @constructor
*/
DependencyManager = function(options) {
/**
* Service map.
*
* @private
* @type {Object}
*/
var _config = null;
var _configCopy = null;
/**
* Global properties.
*
* @private
* @type {Object}
*/
var _parameters = {};
/**
* Options for DM.
* @type {Object}
*/
this.options = extend({}, this.constructor.DEFAULTS, options || {});
/**
* Sets up the service map.
*
* @param {Object} config
* @param {Object} [parameters]
* @throws {Error}
*/
this.setConfig = function(config, parameters) {
if (_config !== null) {
throw new Error("Dependency Manager is already configured");
}
if (!isObject(config)) {
throw new Error("Config is expected to be an Object");
}
if (isObject(parameters)) {
forEachOwn(parameters, function(value, key) {
this.setParameter(key, value);
}, this);
}
_config = config;
_configCopy = clone(config);
};
/**
* Returns the deep copy of config.
*
* @returns {Object}
*/
this.getConfig = function(key) {
if (_config === null) {
throw new Error("Dependency Manager is not configured yet");
}
return key ? _configCopy[key] : _configCopy;
};
/**
* Sets up the global parameter.
*/
this.setParameter = function(key, value) {
if (!isUndefined(_parameters[key])) {
throw new Error("Dependency Manager property '" + key + "' is already set");
}
_parameters[key] = value;
};
/**
* Returns value of property.
*
* @param {String} key
*
* @returns {*}
*/
this.getParameter = function(key) {
return !isUndefined(_parameters[key]) ? _parameters[key] : null;
};
/**
* Services map
* @type {{}}
*/
this.services = {};
};
DependencyManager.prototype = (function() {
/**
* Template for checking reference to service.
*
* Could be applied to string in format:
* @
*
* @type {RegExp}
* @private
* @static
*/
var SERVICE_REGEX = /^@([^:]+)(?::([^\[\]]+)(\[.*\])?)?$/i;
/**
* Template for checking reference to property.
*
* @type {RegExp}
* @private
* @static
*/
var PROPERTY_REGEX = /^%(.*)%$/i;
/**
* Template for checking reference to property in string context.
*
* @type {RegExp}
* @private
* @static
*/
var LIVE_PROPERTY_REGEX = /%\{([^%]+?)\}/gi;
/**
* Template for checking reference to resource.
*
* @type {RegExp}
* @private
* @static
*/
var RESOURCE_REGEX = /^#(?:([^!]+)!)?(.*)#$/i;
return {
constructor: DependencyManager,
setAsync: function(adapter) {
if (!(adapter instanceof Async)) {
throw new Error(«Async is expected»);
}
this.async = adapter;
return this;
},
setLoader: function(adapter) {
if (!(adapter instanceof Loader)) {
throw new Error(«Loader is expected»);
}
this.loader = adapter;
return this;
},
// @service:getSome(@service:getVar(text, hello, @someService, %property%))
parseString: function(string) {
var self = this,
args, name,
property, handler, callArgs,
path,
promises;
if (!isString(string)) {
return self.async.reject(new Error(«String is expected»));
}
// todo Refactor parsing in this way:
// todo Parsers in constructor, add ability to register custom parsers
//
// [PropertyTemplateParser, PropertyLinkParser, ContainerLinkParser, ServiceLinkParser, ResourceParser]
// chain.add(…);
// chain.add(…);
// chain.parse(string);
//
// Finally there could be:
// — final (returning) link parsers
// — continuous (not returning) template parses
//
// Links are @, #…#, %…%
// Templates are @{service[method|property|toString]}, #{resource}, %{parameter}
// Live replacement property
// We do not resolve promise with this
// Cause it can contain another useful matching
if (string.match(LIVE_PROPERTY_REGEX)) {
string = string.replace(LIVE_PROPERTY_REGEX, function(match, name) {
return self.getParameter(name) || match;
});
}
// Property
if ((args = string.match(PROPERTY_REGEX))) {
name = args[1];
return self.async.resolve(self.getParameter(name));
}
// Self link
if (string === DependencyManager.SELF) {
return this.async.resolve(this);
}
// Service
if ((args = string.match(SERVICE_REGEX))) {
name = args[1];
property = args[2];
callArgs = args[3];
promises = [this.parseString(name)];
if (property && isString(property)) {
promises.push(this.parseString(property));
if (callArgs) {
try {
callArgs = JSON.parse(args[3]);
} catch (err) {
return self.async.reject(new Error(«Service method call parse error»));
}
callArgs = map(callArgs, this.parse, this);
promises.push(this.async.all(callArgs));
}
}
return this.async.all(promises)
.then(function(results) {
var key, options;
key = results[0];
options = {
property: results[1],
arguments: results[2]
};
return self.get(key, options);
});
}
// Resource
if ((args = string.match(RESOURCE_REGEX))) {
path = args[2];
handler = args[1];
promises = [this.parseString(path)];
if (handler && isString(handler)) {
promises.push(this.parseString(handler));
}
return this.async.all(promises).then(function(args) {
return self.getResource.apply(self, args);
});
}
return this.async.resolve(string);
},
parseObject: function(object) {
var self = this,
iterator, parsed, promises, escaped;
switch (objectType(object)) {
case «Object»: {
parsed = {};
iterator = forEachOwn;
break;
}
case «Array»: {
parsed = [];
iterator = forEachSimple;
break;
}
default: {
return self.async.reject(new Error(«Object or Array is expected»));
}
}
if ((escaped = DependencyManager.unEscape(object))) {
return this.async.resolve(escaped);
}
promises = [];
iterator(object, function(value, key) {
promises.push(self.parse(value).then(function(value) {
parsed[key] = value;
}));
});
return self.async.all(promises)
.then(function() {
return parsed;
});
},
/**
* Finds out references to services, parameters and resources in given object.
* Returns promise of getting them, which is resolved then with object having
* parsed values.
*
* @param config {*}
*/
parse: function(config) {
switch (objectType(config)) {
case ‘String’: {
return this.parseString(config);
}
case ‘Object’:
case ‘Array’: {
return this.parseObject(config);
}
default: {
return this.async.resolve(config);
}
}
},
/**
* Собирает сервис.
*
* @param config {Object}
*
* @returns {Promise}
*/
build: function(config) {
var self = this,
options;
options = {
base: this.options.base
};
// do not combine path loading and parsing arguments, cause it can produce side effects
// on amd builds — when dependencies compiled in ‘path’ file, but loaded earlier from separate files
return this.loader.require(config.path, options)
.then(function(constructor) {
return self.async.all([
self.parse(config.arguments || []),
self.parse(config.calls || []),
self.parse(config.properties || {}),
self.parse(config.factory)
])
.then(function(inputs) {
var definition, factory;
definition = {
constructor: constructor,
arguments: inputs[0],
calls: inputs[1],
properties: inputs[2]
};
factory = inputs[3] || defaultFactory;
if (isObject(factory)) {
if (!isFunction(factory.factory)) {
throw new TypeError(«Given factory object does not have #factory method»);
}
factory = bind(factory.factory, factory);
} else if (!isFunction(factory)) {
throw new TypeError(«Given factory must be a function»);
}
// could be a value or a Promise
return factory(definition);
});
});
},
// @handler:handle!/var/resource
// %tpl%!/var/template.html
// %tpl%!%path%
getResource: function(path, handler) {
var options;
if (!isString(path)) {
return this.async.reject(new Error(«Path must be a string»));
}
options = {
base: this.options.base
};
if (isFunction(handler)) {
return this.loader.read(path, options).then(handler);
}
// path handler to loader for any cases
options.handler = handler;
return this.loader.read(path, options);
},
/**
*
* @param {string} key
* @param {Object} [options]
*/
has: function(key, options) {
return !!this.getConfig(key);
},
/**
*
* @param {string} key
* @param {Object} [options]
*/
initialized: function(key, options) {
return !!this.services[key];
},
/**
*
* @param {string} key
* @param {*} service
* @param {Object} [options]
*/
set: function(key, service, options) {
var config;
if (!(config = this.getConfig(key))) {
throw new Error(sprintf(«Service with key ‘%s’ is not present in configuration», key));
}
if (!config.synthetic) {
throw new Error(sprintf(«Could not inject service with key ‘%s’, cause it is not synthetic», key));
}
this.services[key] = this.async.resolve(service);
},
/**
*
*/
get: function(key, options) {
var config, promise,
alias,
isShared, isSynthetic, isAlias, isSingleProperty;
if (!isString(key)) {
return this.async.reject(new Error(sprintf(«Key is expected to be string, %s given», typeof key)));
}
if (!(config = this.getConfig(key))) {
return this.async.reject(new Error(sprintf(«Service with key ‘%s’ is not present in configuration», key)));
}
options = options || {};
isShared = isBoolean(config.share) ? config.share : true;
isSynthetic = isBoolean(config.synthetic) ? config.synthetic : false;
isAlias = isString(config.alias) ? true : false;
// Sign of custom property (synthetic, aliased or smth)
isSingleProperty = isSynthetic || isAlias;
if (!isSingleProperty && !isString(config.path)) {
return this.async.reject(new Error(sprintf(«Path is expected in service configuration with key ‘%s'», key)));
}
if (isSynthetic && !this.initialized(key)) {
return this.async.reject(new Error(sprintf(«Service with key ‘%s’ is synthetic, and not injected yet», key)));
}
if (isAlias) {
if (!this.has(alias = config.alias)) {
return this.async.reject(new Error(sprintf(«Service with key ‘%s’ could not be alias for not existing ‘%s’ service», key, alias)));
}
return this.get(alias);
}
if (!isShared) {
promise = this.build(config);
} else if (!(promise = this.services[key])) {
promise = this.services[key] = this.build(config);
}
// todo move this logic in Service parser
return promise.then(function(service) {
var property, isFunc;
if (isString(options.property)) {
property = service[options.property];
isFunc = isFunction(property);
if (isArray(options.arguments)) {
if (!isFunc) {
throw new TypeError(sprintf(«Service ‘%s’ does not have the method ‘%s'», key, options.property));
}
return property.apply(service, options.arguments);
}
return isFunc ? bind(property, service) : property;
}
return service;
});
}
};
})();
// Default options
DependencyManager.DEFAULTS = {
base: null
};
DependencyManager.ESCAPE_FLAG = ‘__escape__’;
DependencyManager.ESCAPE_VALUE = ‘__value__’;
DependencyManager.SELF = «@_@»;
DependencyManager.escape = function(value) {
var wrapper = {};
wrapper[DependencyManager.ESCAPE_FLAG] = true;
wrapper[DependencyManager.ESCAPE_VALUE] = value;
return wrapper;
};
DependencyManager.unEscape = function(obj) {
if (obj[DependencyManager.ESCAPE_FLAG] === true) {
return obj[DependencyManager.ESCAPE_VALUE];
}
return null;
};
DependencyManager.extend = function(prototypeProps, staticProps) {
return inherits(this, prototypeProps, staticProps);
};
module.exports = DependencyManager;
// Module registration
// ——————-
/*
var isNode = typeof module !== «undefined» && module.exports,
isAMD = typeof define === ‘function’ && typeof define.amd === ‘object’ && define.amd;
if (isNode) {
module.exports = DependencyManager;
} else if (isAMD) {
define([], function() {return DependencyManager;});
} else if ( typeof window === «object» && typeof window.document === «object» ) {
window.DependencyManager = DependencyManager;
}*/
},{«./dm/adapter/async»:72,»./dm/adapter/loader»:74,»./dm/factory»:77,»./dm/factory/default»:78,»./dm/utils»:79,»inherits-js»:80}],71:[function(require,module,exports){
var inherits = require(«inherits-js»),
Adapter;
Adapter = function(adaptee) {
this.adaptee = adaptee;
};
Adapter.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Adapter;
},{«inherits-js»:80}],72:[function(require,module,exports){
var Adapter = require(«../adapter»),
Async;
Async = Adapter.extend({
/**
* Creates new Promise with given resolver.
*
* @param {Function} resolver
*/
promise: function(resolver) {
throw new Error(«Method ‘promise’ must be implemented»);
},
/**
* Creates new Promise, that waiting for all given promises/values is resolved.
*
* @param {Array} list
*/
all: function(list) {
throw new Error(«Method ‘all’ must be implemented»);
},
/**
* Creates new resolved with given value Promise.
*
* @param {*} value
*/
resolve: function(value) {
throw new Error(«Method ‘resolve’ must be implemented»);
},
/**
* Creates new rejected with given value Promise.
*
* @param {*} value
*/
reject: function(value) {
throw new Error(«Method ‘reject’ must be implemented»);
}
});
module.exports = Async;
},{«../adapter»:71}],73:[function(require,module,exports){
var Async = require(«../async»),
RSVP;
RSVP = Async.extend({
constructor: function() {
Async.prototype.constructor.apply(this, arguments);
this.RSVP = this.adaptee;
},
promise: function(resolver) {
return new this.RSVP.Promise(resolver);
},
all: function(promises) {
return this.RSVP.all(promises);
},
resolve: function(value) {
return this.RSVP.Promise.resolve(value);
},
reject: function(error) {
return this.RSVP.Promise.reject(error);
}
});
module.exports = RSVP;
},{«../async»:72}],74:[function(require,module,exports){
var Adapter = require(«../adapter»),
Async = require(«./async»),
Loader;
Loader = Adapter.extend({
/**
* Injects async adapter.
*
* @param {Async} adapter
*/
setAsync: function(adapter) {
if (!adapter instanceof Async) {
throw new Error(«Async is expected»);
}
this.async = adapter;
return this;
},
/**
* Requires a module.
*
* @param {string} path
* @param {Object} options
*/
require: function(path, options) {
throw new Error(«Method must be implemented»);
},
/**
* Loads resource.
*
* @param {string} path
* @param {Object} options
*/
read: function(path, options) {
throw new Error(«Method must be implemented»);
}
});
module.exports = Loader;
},{«../adapter»:71,»./async»:72}],75:[function(require,module,exports){
var Loader = require(«../loader»),
Requirejs;
Requirejs = Loader.extend({
constructor: function() {
Loader.prototype.constructor.apply(this, arguments);
this.requirejs = this.adaptee;
},
require: function(path) {
var self = this;
return this.async.promise(function(resolve, reject) {
self.requirejs([path], resolve, reject);
});
},
read: function(path, options) {
var self = this;
options = options || {};
return this.async.promise(function(resolve, reject) {
self.requirejs([[options.handler || «text», path].join(‘!’)], resolve, reject);
});
}
});
module.exports = Requirejs;
},{«../loader»:74}],76:[function(require,module,exports){
var Loader = require(«../loader»),
fs = require(«fs»),
_path = require(«path»),
CJS;
CJS = Loader.extend({
_normalizePath: function(path, options) {
var base;
if ((base = options.base)) {
// normalize path
if (path.charAt(0) === «/») {
path = path.slice(1);
}
return _path.resolve(base, path);
}
return path;
},
require: function(path, options) {
path = this._normalizePath(path, options);
return this.async.promise(function(resolve, reject) {
try {
resolve(require(path));
} catch (err) {
reject(err);
}
});
},
read: function(path, options) {
path = this._normalizePath(path, options);
// how it should work at client side with browserify?
if (fs && fs.readFile) {
return this.async.promise(function(resolve, reject) {
fs.readFile(path, function(err, src) {
if (err) {
reject(err);
} else {
resolve(src);
}
});
});
} else {
// fallback for client side
return this.require(path, options);
}
}
});
module.exports = CJS;
},{«../loader»:74,»fs»:61,»path»:64}],77:[function(require,module,exports){
var inherits = require(«inherits-js»),
Factory;
Factory = function() {
//
};
Factory.prototype = {
constructor: Factory,
/**
*
* @param definition
*
* @returns {Object|Promise}
*/
factory: function(definition) {
throw new Error(«Method must be implemented»);
}
};
Factory.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Factory;
},{«inherits-js»:80}],78:[function(require,module,exports){
var Factory = require(«../factory»),
utils = require(«../../dm/utils»),
isFunction = utils.isFunction,
forEachOwn = utils.forEachOwn,
forEachSimple = utils.forEachSimple;
module.exports = Factory.extend({
newInstanceWithArgs: function(constructor, args) {
var service;
// @see http://jsperf.com/dynamic-arguments-to-the-constructor
function Service() {}
Service.prototype = constructor.prototype;
service = new Service();
try {
constructor.apply(service, args);
} catch (error) {
console.error(«Cannot instantiate service», error);
throw error;
}
return service;
},
makeCall: function(service, method, args) {
if (isFunction(service[method])) {
service[method].apply(service, args);
}
},
setProperty: function(service, property, value) {
service[property] = value;
},
factory: function(definition) {
var self = this,
service;
// Arguments
service = this.newInstanceWithArgs(definition.constructor, definition.arguments);
// Calls
forEachSimple(definition.calls, function(call) {
self.makeCall(service, call[0], call[1]);
});
// Properties
forEachOwn(definition.properties, function(value, property) {
self.setProperty(service, property, value);
});
return service;
}
});
},{«../../dm/utils»:79,»../factory»:77}],79:[function(require,module,exports){
var toString = Object.prototype.toString;
function objectType(obj) {
if (obj === void 0) {
return ‘Undefined’;
} else if (obj === null) {
return ‘Null’;
} else {
return toString.call(obj).replace(/\[object ([a-zA-Z]+)\]/i, ‘$1’);
}
}
function isString(obj) {
return toString.call(obj) == ‘[object String]’;
}
function isNumber(obj) {
return toString.call(obj) == ‘[object Number]’;
}
function isFunction(obj) {
return toString.call(obj) == ‘[object Function]’;
}
function isBoolean(obj) {
return toString.call(obj) == ‘[object Boolean]’;
}
function isDate(obj) {
return toString.call(obj) == ‘[object Date]’;
}
function isObject(obj) {
return toString.call(obj) == ‘[object Object]’ && obj !== void 0;
}
function isRegExp(obj) {
return toString.call(obj) == ‘[object RegExp]’;
}
function isArray(obj) {
return toString.call(obj) == ‘[object Array]’;
}
function isUndefined(obj) {
return toString.call(obj) == ‘[object Undefined]’ || obj === void 0;
}
function noop() {
//
}
var async = {
each: function(obj, iterator, callback) {
var remain, next;
callback = callback || noop;
remain = keys(obj).length;
if (!remain) {
return callback();
}
next = function(err) {
if (err) {
callback(err);
callback = noop;
} else {
remain—;
if (!remain) {
callback();
}
}
};
forEach(obj, function(value, index) {
iterator(value, index, next);
});
return null;
},
eachSeries: function(obj, iterator, callback) {
var index, iteration, next, indexes, remain;
callback = callback || noop;
indexes = keys(obj);
remain = indexes.length;
index = 0;
next = function(err) {
if (err) {
callback(err);
callback = noop;
} else {
remain—;
index++;
if (!remain) {
callback();
} else {
iteration();
}
}
};
iteration = function() {
var key;
key = indexes[index];
iterator(obj[key], key, next);
};
iteration();
},
map: function(arr, iterator, callback) {
var result;
result = [];
this.each(arr, function(value, index, next) {
iterator(value, index, function(err, value) {
result[index] = value;
next(err);
});
}, function(err) {
callback(err, result);
});
},
reduce: function(obj, memo, iterator, callback) {
this.eachSeries(obj, function(value, index, next) {
iterator(memo, value, index, function(err, value) {
memo = value;
next(err);
});
}, function(err) {
callback(err, memo);
});
}
};
function keys(obj) {
var result;
result = [];
if (!isObject(obj) && !isArray(obj)) {
throw new TypeError(«Object or Array is expected»);
}
if (Object.keys) {
return Object.keys(obj);
}
forEach(obj, function(value, key) {
result.push(key);
});
return result;
}
function forEach(obj, iterator, context) {
if (isArray(obj)) {
return forEachSimple(obj, iterator, context);
} else if (isObject(obj)) {
return forEachOwn(obj, iterator, context);
}
throw new TypeError(«Array or Object is expected»);
}
// Iterates over object
// Breaks, if iterator return the value
function forEachOwn(obj, iterator, context) {
var result;
for (var x in obj) {
if (obj.hasOwnProperty(x)) {
result = iterator.call(context, obj[x], x, obj);
if (result !== undefined) {
return result;
}
}
}
return result;
}
// Iterates over array
// Breaks, if iterator return the value
function forEachSimple(arr, iterator, context) {
var result;
for (var x = 0; x < arr.length; x++) {
result = iterator.call(context, arr[x], x, arr);
if (result !== undefined) {
return result;
}
}
return result;
}
function map(array, iterator, context) {
var results = [];
if (array === null) {
return results;
}
if (isFunction(array.map)) {
return array.map(iterator, context);
}
forEachSimple(array, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
return results;
}
function bind(func, context) {
var args, slice;
slice = Array.prototype.slice;
if (isFunction(func.bind)) {
return func.bind.apply(func, slice.call(arguments, 1));
}
args = slice.call(arguments, 2);
return function() {
return func.apply(context, args.concat(slice.call(arguments)));
};
}
// Shallow copy of sprintf
// Only uses '%s' placeholder
function sprintf(pattern) {
var args = Array.prototype.slice.call(arguments, 1),
counter = 0;
if (!isString(pattern)) {
throw new Error("String is expected");
}
return pattern.replace(/%s/g, function(match) {
return (args[counter++]).toString() || match;
});
}
// Clone deeply
function clone(value) {
var result, isArr;
if (typeof value == "object") {
/* jshint ignore:start */
if (isBoolean(value)) {
return new Boolean(+value);
}
if (isDate(value)) {
return new Date(+value);
}
if (isNumber(value)) {
return new Number(value);
}
if (isString(value)) {
return new String(value);
}
if (isRegExp(value)) {
result = new RegExp(value.source, /\w*$/.exec(value));
result.lastIndex = value.lastIndex;
return result;
}
isArr = isArray(value);
result = isArr ? new Array(value.length) : new Object();
/* jshint ignore:end */
} else {
return value;
}
(isArr ? forEachSimple : forEachOwn)(value, function(value, key) {
result[key] = clone(value);
});
return result;
}
// Extend object with others
function extend(obj) {
forEachSimple(Array.prototype.slice.call(arguments, 1), function(source) {
if (source) {
forEachOwn(source, function(value, key) {
obj[key] = value;
});
}
});
return obj;
}
module.exports = {
objectType: objectType,
isString: isString,
isNumber: isNumber,
isFunction: isFunction,
isBoolean: isBoolean,
isDate: isDate,
isObject: isObject,
isRegExp: isRegExp,
isArray: isArray,
isUndefined: isUndefined,
forEach: forEach,
forEachOwn: forEachOwn,
forEachSimple: forEachSimple,
map: map,
sprintf: sprintf,
clone: clone,
extend: extend,
bind: bind,
async: async,
keys: keys
};
},{}],80:[function(require,module,exports){
var extend = require("./utils/extend");
module.exports = function(Parent, protoProps, staticProps) {
var Child;
protoProps = protoProps || {};
staticProps = staticProps || {};
if (protoProps.hasOwnProperty("constructor") && typeof protoProps.constructor === 'function') {
Child = protoProps.constructor;
} else {
Child = function() {
Parent.apply(this, arguments);
};
}
// set the static props to the new Enum
extend(Child, Parent, staticProps);
// create prototype of Child, that created with Parent prototype
//
// __proto__ <---- __proto__
// ^ ^
// | |
// Parent Child
//
function Surrogate(){}
Surrogate.prototype = Parent.prototype;
Child.prototype = new Surrogate();
// extend prototype
extend(Child.prototype, protoProps, {
constructor: Child
});
return Child;
};
},{"./utils/extend":82}],81:[function(require,module,exports){
/**
* Each iterator.
*
* @param {object} obj
* @param {function} func
* @param {object} [context]
*
* @returns {*}
*/
module.exports = function(obj, func, context) {
var result;
context || (context = null);
for (var x in obj) {
if (obj.hasOwnProperty(x)) {
result = func.call(context, obj[x], x, obj);
if (result !== undefined) {
return result;
}
}
}
return result;
};
},{}],82:[function(require,module,exports){
var each = require("./each");
/**
* Extends one object by multiple others.
*
* @param {object} to
*
* @returns {object}
*/
module.exports = function(to) {
var from = Array.prototype.slice.call(arguments, 1);
var func = function(value, prop) {
to[prop] = value;
};
for (var x = 0; x < from.length; x++) {
each(from[x], func);
}
return to;
};
},{"./each":81}],83:[function(require,module,exports){
(function(){
var _global = this;
/**
* JS Implementation of MurmurHash2
*
* @author Gary Court
* @see http://github.com/garycourt/murmurhash-js
* @author Austin Appleby
* @see http://sites.google.com/site/murmurhash/
*
* @param {string} str ASCII only
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
function MurmurHashV2(str, seed) {
var
l = str.length,
h = seed ^ l,
i = 0,
k;
while (l >= 4) {
k =
((str.charCodeAt(i) & 0xff)) |
((str.charCodeAt(++i) & 0xff) << 8) |
((str.charCodeAt(++i) & 0xff) << 16) |
((str.charCodeAt(++i) & 0xff) << 24);
k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));
k ^= k >>> 24;
k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));
h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k;
l -= 4;
++i;
}
switch (l) {
case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1: h ^= (str.charCodeAt(i) & 0xff);
h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));
}
h ^= h >>> 13;
h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));
h ^= h >>> 15;
return h >>> 0;
};
/**
* JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)
*
* @author Gary Court
* @see http://github.com/garycourt/murmurhash-js
* @author Austin Appleby
* @see http://sites.google.com/site/murmurhash/
*
* @param {string} key ASCII only
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
function MurmurHashV3(key, seed) {
var remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i;
remainder = key.length & 3; // key.length % 4
bytes = key.length — remainder;
h1 = seed;
c1 = 0xcc9e2d51;
c2 = 0x1b873593;
i = 0;
while (i < bytes) {
k1 =
((key.charCodeAt(i) & 0xff)) |
((key.charCodeAt(++i) & 0xff) << 8) |
((key.charCodeAt(++i) & 0xff) << 16) |
((key.charCodeAt(++i) & 0xff) << 24);
++i;
k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19);
h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;
h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));
}
k1 = 0;
switch (remainder) {
case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
case 1: k1 ^= (key.charCodeAt(i) & 0xff);
k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1;
}
h1 ^= key.length;
h1 ^= h1 >>> 16;
h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
h1 ^= h1 >>> 13;
h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;
h1 ^= h1 >>> 16;
return h1 >>> 0;
}
var murmur = MurmurHashV3;
murmur.v2 = MurmurHashV2;
murmur.v3 = MurmurHashV3;
if (typeof(module) != ‘undefined’) {
module.exports = murmur;
} else {
var _previousRoot = _global.murmur;
murmur.noConflict = function() {
_global.murmur = _previousRoot;
return murmur;
}
_global.murmur = murmur;
}
}());
},{}],84:[function(require,module,exports){
(function (process){
/*!
* @overview RSVP — a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/tildeio/rsvp.js/master/LICENSE
* @version 3.0.14
*/
(function() {
«use strict»;
function $$rsvp$events$$indexOf(callbacks, callback) {
for (var i=0, l=callbacks.length; i
throw new Error(‘Second argument not supported’);
}
if (typeof o !== ‘object’) {
throw new TypeError(‘Argument must be an object’);
}
$$utils$$F.prototype = o;
return new $$utils$$F();
});
var $$instrument$$queue = [];
var $$instrument$$default = function instrument(eventName, promise, child) {
if (1 === $$instrument$$queue.push({
name: eventName,
payload: {
guid: promise._guidKey + promise._id,
eventName: eventName,
detail: promise._result,
childGuid: child && promise._guidKey + child._id,
label: promise._label,
timeStamp: $$utils$$now(),
stack: new Error(promise._label).stack
}})) {
setTimeout(function() {
var entry;
for (var i = 0; i < $$instrument$$queue.length; i++) {
entry = $$instrument$$queue[i];
$$rsvp$config$$config.trigger(entry.name, entry.payload);
}
$$instrument$$queue.length = 0;
}, 50);
}
};
function $$$internal$$noop() {}
var $$$internal$$PENDING = void 0;
var $$$internal$$FULFILLED = 1;
var $$$internal$$REJECTED = 2;
var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject();
function $$$internal$$getThen(promise) {
try {
return promise.then;
} catch(error) {
$$$internal$$GET_THEN_ERROR.error = error;
return $$$internal$$GET_THEN_ERROR;
}
}
function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch(e) {
return e;
}
}
function $$$internal$$handleForeignThenable(promise, thenable, then) {
$$rsvp$config$$config.async(function(promise) {
var sealed = false;
var error = $$$internal$$tryThen(then, thenable, function(value) {
if (sealed) { return; }
sealed = true;
if (thenable !== value) {
$$$internal$$resolve(promise, value);
} else {
$$$internal$$fulfill(promise, value);
}
}, function(reason) {
if (sealed) { return; }
sealed = true;
$$$internal$$reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
$$$internal$$reject(promise, error);
}
}, promise);
}
function $$$internal$$handleOwnThenable(promise, thenable) {
if (thenable._state === $$$internal$$FULFILLED) {
$$$internal$$fulfill(promise, thenable._result);
} else if (promise._state === $$$internal$$REJECTED) {
$$$internal$$reject(promise, thenable._result);
} else {
$$$internal$$subscribe(thenable, undefined, function(value) {
if (thenable !== value) {
$$$internal$$resolve(promise, value);
} else {
$$$internal$$fulfill(promise, value);
}
}, function(reason) {
$$$internal$$reject(promise, reason);
});
}
}
function $$$internal$$handleMaybeThenable(promise, maybeThenable) {
if (maybeThenable.constructor === promise.constructor) {
$$$internal$$handleOwnThenable(promise, maybeThenable);
} else {
var then = $$$internal$$getThen(maybeThenable);
if (then === $$$internal$$GET_THEN_ERROR) {
$$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error);
} else if (then === undefined) {
$$$internal$$fulfill(promise, maybeThenable);
} else if ($$utils$$isFunction(then)) {
$$$internal$$handleForeignThenable(promise, maybeThenable, then);
} else {
$$$internal$$fulfill(promise, maybeThenable);
}
}
}
function $$$internal$$resolve(promise, value) {
if (promise === value) {
$$$internal$$fulfill(promise, value);
} else if ($$utils$$objectOrFunction(value)) {
$$$internal$$handleMaybeThenable(promise, value);
} else {
$$$internal$$fulfill(promise, value);
}
}
function $$$internal$$publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
$$$internal$$publish(promise);
}
function $$$internal$$fulfill(promise, value) {
if (promise._state !== $$$internal$$PENDING) { return; }
promise._result = value;
promise._state = $$$internal$$FULFILLED;
if (promise._subscribers.length === 0) {
if ($$rsvp$config$$config.instrument) {
$$instrument$$default('fulfilled', promise);
}
} else {
$$rsvp$config$$config.async($$$internal$$publish, promise);
}
}
function $$$internal$$reject(promise, reason) {
if (promise._state !== $$$internal$$PENDING) { return; }
promise._state = $$$internal$$REJECTED;
promise._result = reason;
$$rsvp$config$$config.async($$$internal$$publishRejection, promise);
}
function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
parent._onerror = null;
subscribers[length] = child;
subscribers[length + $$$internal$$FULFILLED] = onFulfillment;
subscribers[length + $$$internal$$REJECTED] = onRejection;
if (length === 0 && parent._state) {
$$rsvp$config$$config.async($$$internal$$publish, parent);
}
}
function $$$internal$$publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if ($$rsvp$config$$config.instrument) {
$$instrument$$default(settled === $$$internal$$FULFILLED ? 'fulfilled' : 'rejected', promise);
}
if (subscribers.length === 0) { return; }
var child, callback, detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
$$$internal$$invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function $$$internal$$ErrorObject() {
this.error = null;
}
var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject();
function $$$internal$$tryCatch(callback, detail) {
try {
return callback(detail);
} catch(e) {
$$$internal$$TRY_CATCH_ERROR.error = e;
return $$$internal$$TRY_CATCH_ERROR;
}
}
function $$$internal$$invokeCallback(settled, promise, callback, detail) {
var hasCallback = $$utils$$isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
value = $$$internal$$tryCatch(callback, detail);
if (value === $$$internal$$TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
$$$internal$$reject(promise, new TypeError('A promises callback cannot return that same promise.'));
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== $$$internal$$PENDING) {
// noop
} else if (hasCallback && succeeded) {
$$$internal$$resolve(promise, value);
} else if (failed) {
$$$internal$$reject(promise, error);
} else if (settled === $$$internal$$FULFILLED) {
$$$internal$$fulfill(promise, value);
} else if (settled === $$$internal$$REJECTED) {
$$$internal$$reject(promise, value);
}
}
function $$$internal$$initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value){
$$$internal$$resolve(promise, value);
}, function rejectPromise(reason) {
$$$internal$$reject(promise, reason);
});
} catch(e) {
$$$internal$$reject(promise, e);
}
}
function $$enumerator$$makeSettledResult(state, position, value) {
if (state === $$$internal$$FULFILLED) {
return {
state: 'fulfilled',
value: value
};
} else {
return {
state: 'rejected',
reason: value
};
}
}
function $$enumerator$$Enumerator(Constructor, input, abortOnReject, label) {
this._instanceConstructor = Constructor;
this.promise = new Constructor($$$internal$$noop, label);
this._abortOnReject = abortOnReject;
if (this._validateInput(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._init();
if (this.length === 0) {
$$$internal$$fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
$$$internal$$fulfill(this.promise, this._result);
}
}
} else {
$$$internal$$reject(this.promise, this._validationError());
}
}
$$enumerator$$Enumerator.prototype._validateInput = function(input) {
return $$utils$$isArray(input);
};
$$enumerator$$Enumerator.prototype._validationError = function() {
return new Error('Array Methods must be provided an Array');
};
$$enumerator$$Enumerator.prototype._init = function() {
this._result = new Array(this.length);
};
var $$enumerator$$default = $$enumerator$$Enumerator;
$$enumerator$$Enumerator.prototype._enumerate = function() {
var length = this.length;
var promise = this.promise;
var input = this._input;
for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
this._eachEntry(input[i], i);
}
};
$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
var c = this._instanceConstructor;
if ($$utils$$isMaybeThenable(entry)) {
if (entry.constructor === c && entry._state !== $$$internal$$PENDING) {
entry._onerror = null;
this._settledAt(entry._state, i, entry._result);
} else {
this._willSettleAt(c.resolve(entry), i);
}
} else {
this._remaining--;
this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry);
}
};
$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
var promise = this.promise;
if (promise._state === $$$internal$$PENDING) {
this._remaining--;
if (this._abortOnReject && state === $$$internal$$REJECTED) {
$$$internal$$reject(promise, value);
} else {
this._result[i] = this._makeResult(state, i, value);
}
}
if (this._remaining === 0) {
$$$internal$$fulfill(promise, this._result);
}
};
$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) {
return value;
};
$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
var enumerator = this;
$$$internal$$subscribe(promise, undefined, function(value) {
enumerator._settledAt($$$internal$$FULFILLED, i, value);
}, function(reason) {
enumerator._settledAt($$$internal$$REJECTED, i, reason);
});
};
var $$promise$all$$default = function all(entries, label) {
return new $$enumerator$$default(this, entries, true /* abort on reject */, label).promise;
};
var $$promise$race$$default = function race(entries, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor($$$internal$$noop, label);
if (!$$utils$$isArray(entries)) {
$$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
return promise;
}
var length = entries.length;
function onFulfillment(value) {
$$$internal$$resolve(promise, value);
}
function onRejection(reason) {
$$$internal$$reject(promise, reason);
}
for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
$$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
}
return promise;
};
var $$promise$resolve$$default = function resolve(object, label) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor($$$internal$$noop, label);
$$$internal$$resolve(promise, object);
return promise;
};
var $$promise$reject$$default = function reject(reason, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor($$$internal$$noop, label);
$$$internal$$reject(promise, reason);
return promise;
};
var $$rsvp$promise$$guidKey = 'rsvp_' + $$utils$$now() + '-';
var $$rsvp$promise$$counter = 0;
function $$rsvp$promise$$needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function $$rsvp$promise$$needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
var $$rsvp$promise$$default = $$rsvp$promise$$Promise;
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise’s eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
var promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
«`
@class RSVP.Promise
@param {function} resolver
@param {String} label optional string for labeling the promise.
Useful for tooling.
@constructor
*/
function $$rsvp$promise$$Promise(resolver, label) {
this._id = $$rsvp$promise$$counter++;
this._label = label;
this._state = undefined;
this._result = undefined;
this._subscribers = [];
if ($$rsvp$config$$config.instrument) {
$$instrument$$default(‘created’, this);
}
if ($$$internal$$noop !== resolver) {
if (!$$utils$$isFunction(resolver)) {
$$rsvp$promise$$needsResolver();
}
if (!(this instanceof $$rsvp$promise$$Promise)) {
$$rsvp$promise$$needsNew();
}
$$$internal$$initializePromise(this, resolver);
}
}
// deprecated
$$rsvp$promise$$Promise.cast = $$promise$resolve$$default;
$$rsvp$promise$$Promise.all = $$promise$all$$default;
$$rsvp$promise$$Promise.race = $$promise$race$$default;
$$rsvp$promise$$Promise.resolve = $$promise$resolve$$default;
$$rsvp$promise$$Promise.reject = $$promise$reject$$default;
$$rsvp$promise$$Promise.prototype = {
constructor: $$rsvp$promise$$Promise,
_guidKey: $$rsvp$promise$$guidKey,
_onerror: function (reason) {
$$rsvp$config$$config.trigger(‘error’, reason);
},
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise’s eventual value or the
reason why the promise cannot be fulfilled.
«`js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
«`
Chaining
———
The return value of `then` is itself a promise. This second, ‘downstream’
promise is resolved with the return value of the first promise’s fulfillment
or rejection handler, or rejected if the handler throws an exception.
«`js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return ‘default name’;
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user’s name, otherwise it
// will be `’default name’`
});
findUser().then(function (user) {
throw new Error(‘Found user, but still unhappy’);
}, function (reason) {
throw new Error(‘`findUser` rejected and we’re unhappy’);
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be ‘Found user, but still unhappy’.
// If `findUser` rejected, `reason` will be ‘`findUser` rejected and we’re unhappy’.
});
«`
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
«`js
findUser().then(function (user) {
throw new PedagogicalException(‘Upstream error’);
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
«`
Assimilation
————
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
«`js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user’s comments are now available
});
«`
If the assimliated promise rejects, then the downstream promise will also reject.
«`js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we’ll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we’ll have the reason here
});
«`
Simple Example
—————
Synchronous Example
«`javascript
var result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
«`
Errback Example
«`js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
«`
Promise Example;
«`javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
«`
Advanced Example
—————
Synchronous Example
«`javascript
var author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
«`
Errback Example
«`js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
«`
Promise Example;
«`javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
})[‘catch’](function(reason){
// something went wrong
});
«`
@method then
@param {Function} onFulfilled
@param {Function} onRejected
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
*/
then: function(onFulfillment, onRejection, label) {
var parent = this;
var state = parent._state;
if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) {
if ($$rsvp$config$$config.instrument) {
$$instrument$$default(‘chained’, this, this);
}
return this;
}
parent._onerror = null;
var child = new this.constructor($$$internal$$noop, label);
var result = parent._result;
if ($$rsvp$config$$config.instrument) {
$$instrument$$default(‘chained’, parent, child);
}
if (state) {
var callback = arguments[state — 1];
$$rsvp$config$$config.async(function(){
$$$internal$$invokeCallback(state, child, callback, result);
});
} else {
$$$internal$$subscribe(parent, child, onFulfillment, onRejection);
}
return child;
},
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
«`js
function findAuthor(){
throw new Error(‘couldn’t find that author’);
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor()[‘catch’](function(reason){
// something went wrong
});
«`
@method catch
@param {Function} onRejection
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
*/
‘catch’: function(onRejection, label) {
return this.then(null, onRejection, label);
},
/**
`finally` will be invoked regardless of the promise’s fate just as native
try/catch/finally behaves
Synchronous example:
«`js
findAuthor() {
if (Math.random() > 0.5) {
throw new Error();
}
return new Author();
}
try {
return findAuthor(); // succeed or fail
} catch(error) {
return findOtherAuther();
} finally {
// always runs
// doesn’t affect the return value
}
«`
Asynchronous example:
«`js
findAuthor()[‘catch’](function(reason){
return findOtherAuther();
})[‘finally’](function(){
// author was either found, or not
});
«`
@method finally
@param {Function} callback
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise}
*/
‘finally’: function(callback, label) {
var constructor = this.constructor;
return this.then(function(value) {
return constructor.resolve(callback()).then(function(){
return value;
});
}, function(reason) {
return constructor.resolve(callback()).then(function(){
throw reason;
});
}, label);
}
};
function $$rsvp$node$$Result() {
this.value = undefined;
}
var $$rsvp$node$$ERROR = new $$rsvp$node$$Result();
var $$rsvp$node$$GET_THEN_ERROR = new $$rsvp$node$$Result();
function $$rsvp$node$$getThen(obj) {
try {
return obj.then;
} catch(error) {
$$rsvp$node$$ERROR.value= error;
return $$rsvp$node$$ERROR;
}
}
function $$rsvp$node$$tryApply(f, s, a) {
try {
f.apply(s, a);
} catch(error) {
$$rsvp$node$$ERROR.value = error;
return $$rsvp$node$$ERROR;
}
}
function $$rsvp$node$$makeObject(_, argumentNames) {
var obj = {};
var name;
var i;
var length = _.length;
var args = new Array(length);
for (var x = 0; x < length; x++) {
args[x] = _[x];
}
for (i = 0; i < argumentNames.length; i++) {
name = argumentNames[i];
obj[name] = args[i + 1];
}
return obj;
}
function $$rsvp$node$$arrayResult(_) {
var length = _.length;
var args = new Array(length - 1);
for (var i = 1; i < length; i++) {
args[i - 1] = _[i];
}
return args;
}
function $$rsvp$node$$wrapThenable(then, promise) {
return {
then: function(onFulFillment, onRejection) {
return then.call(promise, onFulFillment, onRejection);
}
};
}
var $$rsvp$node$$default = function denodeify(nodeFunc, options) {
var fn = function() {
var self = this;
var l = arguments.length;
var args = new Array(l + 1);
var arg;
var promiseInput = false;
for (var i = 0; i < l; ++i) {
arg = arguments[i];
if (!promiseInput) {
// TODO: clean this up
promiseInput = $$rsvp$node$$needsPromiseInput(arg);
if (promiseInput === $$rsvp$node$$GET_THEN_ERROR) {
var p = new $$rsvp$promise$$default($$$internal$$noop);
$$$internal$$reject(p, $$rsvp$node$$GET_THEN_ERROR.value);
return p;
} else if (promiseInput && promiseInput !== true) {
arg = $$rsvp$node$$wrapThenable(promiseInput, arg);
}
}
args[i] = arg;
}
var promise = new $$rsvp$promise$$default($$$internal$$noop);
args[l] = function(err, val) {
if (err)
$$$internal$$reject(promise, err);
else if (options === undefined)
$$$internal$$resolve(promise, val);
else if (options === true)
$$$internal$$resolve(promise, $$rsvp$node$$arrayResult(arguments));
else if ($$utils$$isArray(options))
$$$internal$$resolve(promise, $$rsvp$node$$makeObject(arguments, options));
else
$$$internal$$resolve(promise, val);
};
if (promiseInput) {
return $$rsvp$node$$handlePromiseInput(promise, args, nodeFunc, self);
} else {
return $$rsvp$node$$handleValueInput(promise, args, nodeFunc, self);
}
};
fn.__proto__ = nodeFunc;
return fn;
};
function $$rsvp$node$$handleValueInput(promise, args, nodeFunc, self) {
var result = $$rsvp$node$$tryApply(nodeFunc, self, args);
if (result === $$rsvp$node$$ERROR) {
$$$internal$$reject(promise, result.value);
}
return promise;
}
function $$rsvp$node$$handlePromiseInput(promise, args, nodeFunc, self){
return $$rsvp$promise$$default.all(args).then(function(args){
var result = $$rsvp$node$$tryApply(nodeFunc, self, args);
if (result === $$rsvp$node$$ERROR) {
$$$internal$$reject(promise, result.value);
}
return promise;
});
}
function $$rsvp$node$$needsPromiseInput(arg) {
if (arg && typeof arg === 'object') {
if (arg.constructor === $$rsvp$promise$$default) {
return true;
} else {
return $$rsvp$node$$getThen(arg);
}
} else {
return false;
}
}
var $$rsvp$all$$default = function all(array, label) {
return $$rsvp$promise$$default.all(array, label);
};
function $$rsvp$all$settled$$AllSettled(Constructor, entries, label) {
this._superConstructor(Constructor, entries, false /* don't abort on reject */, label);
}
$$rsvp$all$settled$$AllSettled.prototype = $$utils$$o_create($$enumerator$$default.prototype);
$$rsvp$all$settled$$AllSettled.prototype._superConstructor = $$enumerator$$default;
$$rsvp$all$settled$$AllSettled.prototype._makeResult = $$enumerator$$makeSettledResult;
$$rsvp$all$settled$$AllSettled.prototype._validationError = function() {
return new Error('allSettled must be called with an array');
};
var $$rsvp$all$settled$$default = function allSettled(entries, label) {
return new $$rsvp$all$settled$$AllSettled($$rsvp$promise$$default, entries, label).promise;
};
var $$rsvp$race$$default = function race(array, label) {
return $$rsvp$promise$$default.race(array, label);
};
function $$promise$hash$$PromiseHash(Constructor, object, label) {
this._superConstructor(Constructor, object, true, label);
}
var $$promise$hash$$default = $$promise$hash$$PromiseHash;
$$promise$hash$$PromiseHash.prototype = $$utils$$o_create($$enumerator$$default.prototype);
$$promise$hash$$PromiseHash.prototype._superConstructor = $$enumerator$$default;
$$promise$hash$$PromiseHash.prototype._init = function() {
this._result = {};
};
$$promise$hash$$PromiseHash.prototype._validateInput = function(input) {
return input && typeof input === 'object';
};
$$promise$hash$$PromiseHash.prototype._validationError = function() {
return new Error('Promise.hash must be called with an object');
};
$$promise$hash$$PromiseHash.prototype._enumerate = function() {
var promise = this.promise;
var input = this._input;
var results = [];
for (var key in input) {
if (promise._state === $$$internal$$PENDING && input.hasOwnProperty(key)) {
results.push({
position: key,
entry: input[key]
});
}
}
var length = results.length;
this._remaining = length;
var result;
for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
result = results[i];
this._eachEntry(result.entry, result.position);
}
};
var $$rsvp$hash$$default = function hash(object, label) {
return new $$promise$hash$$default($$rsvp$promise$$default, object, label).promise;
};
function $$rsvp$hash$settled$$HashSettled(Constructor, object, label) {
this._superConstructor(Constructor, object, false, label);
}
$$rsvp$hash$settled$$HashSettled.prototype = $$utils$$o_create($$promise$hash$$default.prototype);
$$rsvp$hash$settled$$HashSettled.prototype._superConstructor = $$enumerator$$default;
$$rsvp$hash$settled$$HashSettled.prototype._makeResult = $$enumerator$$makeSettledResult;
$$rsvp$hash$settled$$HashSettled.prototype._validationError = function() {
return new Error('hashSettled must be called with an object');
};
var $$rsvp$hash$settled$$default = function hashSettled(object, label) {
return new $$rsvp$hash$settled$$HashSettled($$rsvp$promise$$default, object, label).promise;
};
var $$rsvp$rethrow$$default = function rethrow(reason) {
setTimeout(function() {
throw reason;
});
throw reason;
};
var $$rsvp$defer$$default = function defer(label) {
var deferred = { };
deferred.promise = new $$rsvp$promise$$default(function(resolve, reject) {
deferred.resolve = resolve;
deferred.reject = reject;
}, label);
return deferred;
};
var $$rsvp$map$$default = function map(promises, mapFn, label) {
return $$rsvp$promise$$default.all(promises, label).then(function(values) {
if (!$$utils$$isFunction(mapFn)) {
throw new TypeError("You must pass a function as map's second argument.");
}
var length = values.length;
var results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = mapFn(values[i]);
}
return $$rsvp$promise$$default.all(results, label);
});
};
var $$rsvp$resolve$$default = function resolve(value, label) {
return $$rsvp$promise$$default.resolve(value, label);
};
var $$rsvp$reject$$default = function reject(reason, label) {
return $$rsvp$promise$$default.reject(reason, label);
};
var $$rsvp$filter$$default = function filter(promises, filterFn, label) {
return $$rsvp$promise$$default.all(promises, label).then(function(values) {
if (!$$utils$$isFunction(filterFn)) {
throw new TypeError("You must pass a function as filter's second argument.");
}
var length = values.length;
var filtered = new Array(length);
for (var i = 0; i < length; i++) {
filtered[i] = filterFn(values[i]);
}
return $$rsvp$promise$$default.all(filtered, label).then(function(filtered) {
var results = new Array(length);
var newLength = 0;
for (var i = 0; i < length; i++) {
if (filtered[i]) {
results[newLength] = values[i];
newLength++;
}
}
results.length = newLength;
return results;
});
});
};
var $$rsvp$asap$$len = 0;
var $$rsvp$asap$$default = function asap(callback, arg) {
$$rsvp$asap$$queue[$$rsvp$asap$$len] = callback;
$$rsvp$asap$$queue[$$rsvp$asap$$len + 1] = arg;
$$rsvp$asap$$len += 2;
if ($$rsvp$asap$$len === 2) {
// If len is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
$$rsvp$asap$$scheduleFlush();
}
};
var $$rsvp$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {};
var $$rsvp$asap$$BrowserMutationObserver = $$rsvp$asap$$browserGlobal.MutationObserver || $$rsvp$asap$$browserGlobal.WebKitMutationObserver;
// test for web worker but not in IE10
var $$rsvp$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
// node
function $$rsvp$asap$$useNextTick() {
return function() {
process.nextTick($$rsvp$asap$$flush);
};
}
function $$rsvp$asap$$useMutationObserver() {
var iterations = 0;
var observer = new $$rsvp$asap$$BrowserMutationObserver($$rsvp$asap$$flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
// web worker
function $$rsvp$asap$$useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = $$rsvp$asap$$flush;
return function () {
channel.port2.postMessage(0);
};
}
function $$rsvp$asap$$useSetTimeout() {
return function() {
setTimeout($$rsvp$asap$$flush, 1);
};
}
var $$rsvp$asap$$queue = new Array(1000);
function $$rsvp$asap$$flush() {
for (var i = 0; i < $$rsvp$asap$$len; i+=2) {
var callback = $$rsvp$asap$$queue[i];
var arg = $$rsvp$asap$$queue[i+1];
callback(arg);
$$rsvp$asap$$queue[i] = undefined;
$$rsvp$asap$$queue[i+1] = undefined;
}
$$rsvp$asap$$len = 0;
}
var $$rsvp$asap$$scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
$$rsvp$asap$$scheduleFlush = $$rsvp$asap$$useNextTick();
} else if ($$rsvp$asap$$BrowserMutationObserver) {
$$rsvp$asap$$scheduleFlush = $$rsvp$asap$$useMutationObserver();
} else if ($$rsvp$asap$$isWorker) {
$$rsvp$asap$$scheduleFlush = $$rsvp$asap$$useMessageChannel();
} else {
$$rsvp$asap$$scheduleFlush = $$rsvp$asap$$useSetTimeout();
}
// default async is asap;
$$rsvp$config$$config.async = $$rsvp$asap$$default;
var $$rsvp$$cast = $$rsvp$resolve$$default;
function $$rsvp$$async(callback, arg) {
$$rsvp$config$$config.async(callback, arg);
}
function $$rsvp$$on() {
$$rsvp$config$$config.on.apply($$rsvp$config$$config, arguments);
}
function $$rsvp$$off() {
$$rsvp$config$$config.off.apply($$rsvp$config$$config, arguments);
}
// Set up instrumentation through `window.__PROMISE_INTRUMENTATION__`
if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') {
var $$rsvp$$callbacks = window['__PROMISE_INSTRUMENTATION__'];
$$rsvp$config$$configure('instrument', true);
for (var $$rsvp$$eventName in $$rsvp$$callbacks) {
if ($$rsvp$$callbacks.hasOwnProperty($$rsvp$$eventName)) {
$$rsvp$$on($$rsvp$$eventName, $$rsvp$$callbacks[$$rsvp$$eventName]);
}
}
}
var rsvp$umd$$RSVP = {
'race': $$rsvp$race$$default,
'Promise': $$rsvp$promise$$default,
'allSettled': $$rsvp$all$settled$$default,
'hash': $$rsvp$hash$$default,
'hashSettled': $$rsvp$hash$settled$$default,
'denodeify': $$rsvp$node$$default,
'on': $$rsvp$$on,
'off': $$rsvp$$off,
'map': $$rsvp$map$$default,
'filter': $$rsvp$filter$$default,
'resolve': $$rsvp$resolve$$default,
'reject': $$rsvp$reject$$default,
'all': $$rsvp$all$$default,
'rethrow': $$rsvp$rethrow$$default,
'defer': $$rsvp$defer$$default,
'EventTarget': $$rsvp$events$$default,
'configure': $$rsvp$config$$configure,
'async': $$rsvp$$async
};
/* global define:true module:true window: true */
if (typeof define === 'function' && define.amd) {
define(function() { return rsvp$umd$$RSVP; });
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = rsvp$umd$$RSVP;
} else if (typeof this !== 'undefined') {
this['RSVP'] = rsvp$umd$$RSVP;
}
}).call(this);
}).call(this,require("+xKvab"))
},{"+xKvab":65}],85:[function(require,module,exports){
module.exports={"parameters":{"onload":null,"submit_direct":"https://form-test.kupivkredit.ru:443/form","sdk_path":"https://form-test.kupivkredit.ru:443/sdk/v1/sdk.js","button_path":"https://kupivkredit-test-fe.tcsbank.ru:443/button/index.php","build":"17299b8a21f600c82c96520e261846dbd216a073"},"services":{"factory":{"path":"/sdk/src/utils/factory.js"},"factory.sdk":{"path":"/sdk/src/utils/factory/sdk.js"},"bus":{"path":"/common/script/src/events/bus/emitter.js"},"uuid":{"path":"/sdk/src/uuid/murmurhash.js"},"utils":{"path":"/sdk/src/utils/impl.js","arguments":["@events.element"]},"query":{"path":"/common/script/src/location/query/document.js"},"cookie":{"path":"/common/script/src/cookie/service/default.js"},"cookie.prefix":{"path":"/common/script/src/cookie/service/default.js","arguments":[{"namespace":"kvk"}]},"utm":{"path":"/common/script/src/utm/utm/default.js","arguments":[{"cookie":{"expires":10800000}}],"calls":[["injectCookie",["@cookie.prefix"]],["addSource",["@utm.source.query.plain",false]],["addSource",["@utm.source.cookie.plain",false]],["addSource",["@utm.source.cookie.utmz",true]],["addSource",["@utm.source.query.utm_source",true]],["addSource",["@utm.source.query.lp",true]]]},"utm.source.query.plain":{"path":"/common/script/src/utm/source/query/plain.js","calls":[["injectQuery",["@query"]]]},"utm.source.query.utm_source":{"path":"/common/script/src/utm/source/query/utm_source.js","calls":[["injectQuery",["@query"]]]},"utm.source.query.lp":{"path":"/common/script/src/utm/source/query/lp.js","calls":[["injectQuery",["@query"]]]},"utm.source.cookie.plain":{"path":"/common/script/src/utm/source/cookie/plain.js","calls":[["injectCookie",["@cookie.prefix"]]]},"utm.source.cookie.utmz":{"path":"/common/script/src/utm/source/cookie/utmz.js","calls":[["injectCookie",["@cookie"]]]},"utm.source.composite.cookie":{"path":"/common/script/src/utm/source/composite.js","calls":[["addSource",["@utm.source.cookie.plain"]],["addSource",["@utm.source.cookie.utmz"]]]},"sdk.adapter":{"path":"/sdk/src/sdk/adapter.js","arguments":["@sdk.loader",{"button_path":"%{button_path}"}]},"sdk.loader":{"path":"/sdk/src/sdk/loader/script.js","arguments":[{"path":"%{sdk_path}","callback":"kvk_sdk_loader_%{build}"}]},"sdk":{"path":"/sdk/src/sdk/sdk.js","factory":"@factory.sdk","arguments":[{"onload":"%onload%"}],"calls":[["setBus",["@bus"]],["add",["ui","@ui",{"isFunctor":true}]]]},"ui":{"path":"/sdk/src/sdk/ui/impl.js","calls":[["setBus",["@bus"]],["addElementBuilder",["form","@builder.form"]],["addEventsHandler",["@events.handler.bus"]]]},"builder.form":{"path":"/sdk/src/sdk/ui/element/builder/form.js","calls":[["setUUID",["@uuid"]],["setSubmitter",["@submitter.form"]],["setCommunicationMaster",["@communication.master"]],["setUtils",["@utils"]],["setElementEventManager",["@events.element"]]]},"submitter.form":{"path":"/sdk/src/sdk/ui/element/submitter/form.js","calls":[["setTransport",["@transport.direct"]],["injectUTM",["@utm"]]]},"transport.direct":{"path":"/sdk/src/transport/form.js","calls":[["setUUID",["@uuid"]],["setElementEventManager",["@events.element"]],["setUtils",["@utils"]]],"arguments":[{"action":"%submit_direct%","method":"POST"}]},"communication.master":{"path":"/common/script/src/communication/master/default.js","arguments":["@uuid"],"calls":[["injectCommutation",["@communication.commutation"]]]},"communication.commutation":{"path":"/common/script/src/communication/commutation/condition.js","arguments":[{"postMessage":"@communication.commutation.post_message","hash":"@communication.commutation.hash"}]},"communication.commutation.hash":{"path":"/common/script/src/communication/commutation/hash.js","arguments":[{"reader":{"interval":100}}]},"communication.commutation.post_message":{"path":"/common/script/src/communication/commutation/post-message.js"},"events.handler.bus":{"path":"/common/script/src/events/handler/bus.js","calls":[["setBus",["@bus"]]]},"events.element":{"path":"/common/script/src/events/element/default.js"}}}
},{}],86:[function(require,module,exports){
var DM = require("dm"),
BroodyPromise = require("broody-promises"),
config = require("./config.json"),
dm, async, loader,
SDK;
async = new (DM.async.RSVP.extend({
promise: function(resolver) {
return new BroodyPromise(resolver);
},
all: function(list) {
return BroodyPromise.all(list);
},
resolve: function(value) {
return BroodyPromise.resolve(value);
},
reject: function(value) {
return BroodyPromise.reject(value);
}
}));
loader = (new DM.loader.cjs(require)).setAsync(async);
dm = (new DM.DependencyManager()).setAsync(async).setLoader(loader);
dm.setConfig(config.services, config.parameters);
module.exports = dm;
},{"./config.json":85,"broody-promises":58,"dm":69}],87:[function(require,module,exports){
var sdk;
module.exports = sdk = require("./dm")
.get("sdk")
.done();
// call wrapper function, if it is present for bundling
if (typeof register == "function") {
register(sdk);
}
},{"./dm":86}],"/sdk/src/sdk/sdk.js":[function(require,module,exports){
module.exports=require('wfDo2d');
},{}],"wfDo2d":[function(require,module,exports){
/**
* Kupivkredit SDK.
*
* @package kvk
* @author Sergey Kamardin
*/
var _ = require(«lodash»),
inherits = require(«inherits-js»),
assert = require(«assert»),
util = require(«util»),
SDK;
SDK = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
SDK.DEFAULTS = {};
SDK.prototype = {
constructor: SDK,
/**
* Inject the bus.
*
* @param {Bus} bus
*/
setBus: function(bus) {
this.bus = bus;
},
/**
* Initialize sdk.
*
* @param {Object} parameters
* @param {Object} [options]
*/
initialize: function(parameters, options) {
// do nothing
},
onload: function() {
var fnName;
if (fnName = this.options.onload) {
if (_.isFunction(window[fnName])) {
window[fnName].call(null, this);
} else {
// warn
}
}
},
/**
* Add sdk module.
*
* @param {String} name
* @param {Object} object
* @param {Object} [options]
*
* @returns {SDK}
*/
add: function(name, object, options) {
assert(_.isUndefined(this[name]), util.format(«Can not register module with name ‘%s'», name));
assert(_.isObject(object), util.format(«Object is expected for module with name ‘%s'», name));
options = options || {};
if (options.isFunctor) {
this[name] = function() {
return object.call.apply(object, arguments);
}
} else {
this[name] = object;
}
if (_.isFunction(object.boot)) {
object.boot(options);
}
return this;
}
};
SDK.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = SDK;
},{«assert»:62,»inherits-js»:80,»lodash»:»7ZYSzK»,»util»:68}],90:[function(require,module,exports){
var EventEmitter = require(«../../../common/script/src/events/emitter/node»),
_ = require(«lodash»),
UI;
/**
* UI
*
* @class UI
* @extends EventEmitter
* @author Sergey Kamardin
*/
UI = EventEmitter.extend(
/**
* @lends UI.prototype
*/
{
constructor: function(options) {
EventEmitter.prototype.constructor.apply(this, arguments);
this.options = _.extend({}, this.constructor.DEFAULTS, options);
},
/**
* Inject the bus.
*
* @param {Bus} bus
*/
setBus: function(bus) {
this.bus = bus;
},
addEventsHandler: function(handler) {
throw new Error(«Method must be implemented»);
},
call: function(name, parameters, options) {
throw new Error(«Method must be implemented»);
},
addElement: function(name, element) {
throw new Error(«Method must be implemented»);
}
}
);
module.exports = UI;
},{«../../../common/script/src/events/emitter/node»:31,»lodash»:»7ZYSzK»}],91:[function(require,module,exports){
var EventEmitter = require(«../../../../common/script/src/events/emitter/node»),
_ = require(«lodash»),
Element;
/**
* Element
*
* @class Element
* @extends EventEmitter
* @author Sergey Kamardin
*/
Element = EventEmitter.extend(
/**
* @lends Element.prototype
*/
{
constructor: function(options) {
EventEmitter.prototype.constructor.apply(this, arguments);
this.options = _.extend({}, this.constructor.DEFAULTS, options);
},
setUtils: function(utils) {
this.utils = utils;
},
setElementEventManager: function(events) {
this.events = events;
}
}
);
module.exports = Element;
},{«../../../../common/script/src/events/emitter/node»:31,»lodash»:»7ZYSzK»}],92:[function(require,module,exports){
/**
* Builder
*
* @package Builder
* @author Sergey Kamardin
*/
var _ = require(«lodash»),
inherits = require(«inherits-js»),
Builder;
Builder = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
Builder.DEFAULTS = {};
Builder.prototype = {
constructor: Builder,
setUtils: function(utils) {
this.utils = utils;
},
setElementEventManager: function(events) {
this.events = events;
},
build: function(parameters, options) {
throw new Error(«Method must be implemented»);
},
getConstructor: function() {
throw new Error(«Method must be implemented»);
}
};
Builder.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Builder;
},{«inherits-js»:80,»lodash»:»7ZYSzK»}],»8SfbTa»:[function(require,module,exports){
/**
* Builder
*
* @package Builder
* @author Sergey Kamardin
*/
var Builder = require(«../builder»),
Form = require(«../form»),
_ = require(«lodash»);
module.exports = Builder.extend({
setSubmitter: function(submitter) {
this.submitter = submitter;
},
setUUID: function(uuid) {
this.uuid = uuid;
},
setCommunicationMaster: function(communicationMaster) {
this.communicationMaster = communicationMaster;
},
build: function(parameters, options) {
var form;
form = new Form(options);
form.setSubmitter(this.submitter);
form.setUUID(this.uuid);
form.setUtils(this.utils);
form.setElementEventManager(this.events);
form.setCommunicationMaster(this.communicationMaster);
form.initialize(parameters);
return form;
}
});
},{«../builder»:92,»../form»:95,»lodash»:»7ZYSzK»}],»/sdk/src/sdk/ui/element/builder/form.js»:[function(require,module,exports){
module.exports=require(‘8SfbTa’);
},{}],95:[function(require,module,exports){
/**
* Element
*
* @package Element
* @author Sergey Kamardin
*/
var Element = require(«../element»),
_ = require(«lodash»),
Promise = require(«broody-promises»),
ProxyTrait = require(«../../../../../common/script/src/events/trait/proxy»);
module.exports = Element.extend(_.extend({
constructor: function(options) {
Element.prototype.constructor.apply(this, arguments);
this.background = null;
this.frame = null;
this.parameters = null;
this.pending = null;
this.connection = null;
},
setUUID: function(uuid) {
this.uuid = uuid;
},
setSubmitter: function(submitter) {
this.submitter = submitter;
},
setCommunicationMaster: function(communicationMaster) {
this.communicationMaster = communicationMaster;
},
initialize: function(parameters) {
var err;
if (err = this.submitter.validate(parameters)) {
throw err;
}
this.parameters = parameters;
},
_createLoader: function() {
var loader;
loader = document.createElement(«div»);
_.extend(loader.style, {
«position»: «absolute»,
«top»: «0»,
«left»: «0»,
«bottom»: «0»,
«right»: «0»,
«width»: «100%»,
«height»: «100%»,
«zIndex»: «9998»,
«background»: «#fff»,
«opacity»: «0.5»,
«filter»: «alpha(opacity=50)»
});
return Promise.resolve(loader);
},
_getContainer: function() {
var self = this,
container;
if (!(container = this.container)) {
this.container = container = Promise.all([this.utils.getDocumentHeight(), this.utils.getHighestIndex()])
.then(function(list) {
var height, index, container;
height = list[0];
index = list[1];
container = document.createElement(«div»);
_.extend(container.style, {
«position»: «absolute»,
«top»: «0»,
«left»: «0»,
«width»: «100%»,
«height»: height + «px»,
«zIndex»: index.toString()
});
self.events.on(window, «resize», (function() {
var timeoutID;
return function() {
clearTimeout(timeoutID);
timeoutID = setTimeout(function() {
// getting height of viewport — the doc height, or higher
self.utils.getCanvasHeight(height).then(function(height) {
container.style.height = height + «px»;
});
}, 30);
};
})());
return container;
});
}
return container;
},
_getBackground: function() {
var background;
if (!(background = this.background)) {
this.background = background = this.utils.getDocumentHeight().then(function(height) {
var background;
background = document.createElement(«div»);
_.extend(background.style, {
«position»: «absolute»,
«top»: «0»,
«left»: «0»,
«width»: «100%»,
«height»: «100%»,
«zIndex»: «9997»,
«background»: «#000»,
«opacity»: «0.4»,
«filter»: «alpha(opacity=40)»
});
return background;
});
}
return background;
},
_getFrame: function() {
var self = this,
frame;
if (!(frame = this.frame)) {
this.frame = frame = Promise.all([this.utils.getBodyScrollTop()])
.then(function(list) {
var scrollTop;
scrollTop = list[0];
frame = document.createElement(«iframe»);
frame.setAttribute(«allowTransparency», «true»);
frame.setAttribute(«frameBorder», «0»);
frame.setAttribute(«scrolling», «auto»);
frame.setAttribute(«name», self.uuid.generate(«kvk_form»));
frame.scrollIntoView = function() {
self.utils.getBodyScrollTop()
.then(function(actualScrollTop) {
if (actualScrollTop == scrollTop) {
return;
}
self.utils.animate(function(easing) {
self.utils.setBodyScrollTop(actualScrollTop — ((actualScrollTop — scrollTop) * easing));
}, 500, «easeOutQuart»);
});
};
_.extend(frame.style, {
«border»: «0px»,
«position»: «absolute»,
«top»: scrollTop + «px»,
«left»: «0»,
«width»: «100%»,
«height»: «100%»,
«zIndex»: «9998»
});
return frame;
});
}
return frame;
},
_listenConnection: function(connection) {
var self = this;
this.connection = connection;
// «_NEW_» => «open»
// «onClose» => «close»
// «onStep» => «page» (ignored)
// «onFormComplete» => «complete»
// «onDecision» => «decision»
// «onAccept» => «admit»
// «onCancel» => «deny»
// ——————————
// «onBeforeClose» => «escape» // todo
// proxy events to client
_.forEach([«decision», «admit», «deny», «escape», «complete»], function(event) {
connection.on(event, self._proxy(event, {
self: true
}));
});
connection.on(«rpc:request», function(request) {
var method, params, id;
method = request.method;
params = request.params;
id = request.id;
switch (method) {
case «viewport:height»: {
self.utils.getViewportHeight()
.then(function(height) {
connection.response(id, { result: height });
});
break;
}
}
});
connection.on(«close», function() {
self.close();
});
},
open: function() {
var self = this,
pending;
if (!(pending = this.pending)) {
pending = this.pending = this.utils.documentReady()
.then(function() {
return Promise.all([self._getContainer(), self._getBackground(), self._getFrame(), self._createLoader()]);
})
.then(function(deps) {
var container, background, frame, loader;
container = deps[0];
background = deps[1];
frame = deps[2];
loader = deps[3];
container.appendChild(background);
container.appendChild(loader);
container.appendChild(frame);
document.body.appendChild(container);
return self.submitter.submit(self.parameters, self.options, { frame: frame })
.then(function() {
container.removeChild(loader);
})
.then(function() {
return self.communicationMaster.connect(frame.contentWindow, {
location: self.submitter.getUrl()
});
})
.then(function(connection) {
self._listenConnection(connection);
});
});
}
return Promise.all([self._getContainer(), self._getFrame(), pending])
.then(function(list) {
var container, frame;
container = list[0];
frame = list[1];
// if it was closed
container.style.display = «block»;
frame.scrollIntoView();
self.emit(«open»);
self.connection.on(«page», function() {
frame.scrollIntoView();
});
// self.connection.on(«dimensions», function(dimensions) {
// self._getFrame().then(function(frame) {
// _.extend(frame.style, dimensions);
// });
// });
});
},
close: function() {
var self = this;
return this._getContainer()
.then(function(container) {
container.style.display = «none»;
self.emit(«close»);
});
}
},
_.extend(
{
DEFAULTS: {}
},
ProxyTrait
)
));
},{«../../../../../common/script/src/events/trait/proxy»:35,»../element»:91,»broody-promises»:58,»lodash»:»7ZYSzK»}],96:[function(require,module,exports){
/**
* Submitter
*
* @package submitter
* @author Sergey Kamardin
*/
var _ = require(«lodash»),
inherits = require(«inherits-js»),
Promise = require(«broody-promises»),
util = require(«util»),
Submitter;
Submitter = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
Submitter.DEFAULTS = {};
Submitter.prototype = {
constructor: Submitter,
parameters: {
// key: necessary
},
setTransport: function(transport) {
this.transport = transport;
},
_extract: function(parameters) {
return _.reduce(this.parameters, function(memo, definition) {
var key, isNecessary, defaultValue, value;
key = definition.name;
isNecessary = definition.necessary;
defaultValue = definition.value;
if (_.isUndefined(value = parameters[key])) {
if (isNecessary) {
throw new Error(util.format(«Necessary parameter ‘%s’ is expected», key));
} else {
value = defaultValue;
}
}
memo[key] = value;
return memo;
}, {});
},
validate: function(parameters) {
try {
this._extract(parameters);
return null;
} catch (err) {
return err;
}
},
submit: function(parameters, options, cfg) {
var self = this;
return this.getExtra()
.then(function(extra) {
return self.transport.send({
parameters: _.extend(self._extract(parameters), { extra: extra }),
options: options
}, cfg);
});
},
getUrl: function() {
return this.transport.getUrl();
},
getExtra: function() {
return Promise.resolve({});
}
};
Submitter.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Submitter;
},{«broody-promises»:58,»inherits-js»:80,»lodash»:»7ZYSzK»,»util»:68}],»/sdk/src/sdk/ui/element/submitter/form.js»:[function(require,module,exports){
module.exports=require(‘jIG+UT’);
},{}],»jIG+UT»:[function(require,module,exports){
/**
* Submitter
*
* @package Submitter
* @author Sergey Kamardin
*/
var Submitter = require(«../submitter»),
UTM = require(«../../../../../../common/script/src/utm/utm»),
assert = require(«assert»),
Promise = require(«broody-promises»),
_ = require(«lodash»);
module.exports = Submitter.extend({
parameters: [
{
name: «sign»,
necessary: true
},
{
name: «order»,
necessary: true
},
{
name: «type»,
necessary: false,
value: «full»
},
{
name: «login»,
necessary: false,
value: null
}
,
{
name: «goodIdentity»,
necessary: false,
value: null
}
],
injectUTM: function(utm) {
assert(_.isEmpty(this.utm), «UTM is already set»);
assert(utm instanceof UTM, «UTM is expected»);
this.utm = utm;
},
getExtra: function() {
var self = this;
return new Promise(function(resolve, reject) {
self.utm.get(function(err, utm) {
if (err) {
reject(err);
return;
}
resolve({utm: utm});
});
});
}
});
},{«../../../../../../common/script/src/utm/utm»:55,»../submitter»:96,»assert»:62,»broody-promises»:58,»lodash»:»7ZYSzK»}],»/sdk/src/sdk/ui/impl.js»:[function(require,module,exports){
module.exports=require(‘H6HCnk’);
},{}],»H6HCnk»:[function(require,module,exports){
/**
* UI
*
* @package UI
* @author Sergey Kamardin
*/
var UI = require(«../ui»),
util = require(«util»),
assert = require(«assert»),
_ = require(«lodash»),
Builder = require(«./element/builder»),
Handler = require(«../../../../common/script/src/events/handler»),
EventEmitter = require(«../../../../common/script/src/events/emitter»),
ProxyTrait = require(«../../../../common/script/src/events/trait/proxy»);
module.exports = UI.extend(_.extend({
constructor: function() {
UI.prototype.constructor.apply(this, arguments);
this.builders = {};
this.elements = {};
this.handlers = [];
},
addEventsHandler: function(handler) {
assert(handler instanceof Handler, «Handler is expected»);
this.handlers.push(handler);
},
registerElement: function(name, element) {
var elements;
if (!(elements = this.elements[name])) {
this.elements[name] = [element];
} else {
elements.push(element);
}
element.on(EventEmitter.ALL, this._proxy({
prefixer: function(event) {
return util.format(«ui:%s:%s», name, event);
}
}));
},
call: function(name, parameters, options) {
var builder, element;
if (!(builder = this.builders[name])) {
throw new Error(util.format(«Unknown element ‘%s'», name));
}
this.registerElement(name, (element = builder.build(parameters, options)));
return element;
},
addElementBuilder: function(name, builder) {
assert(builder instanceof Builder, «Builder is expected»);
this.builders[name] = builder;
}
}, ProxyTrait));
},{«../../../../common/script/src/events/emitter»:30,»../../../../common/script/src/events/handler»:32,»../../../../common/script/src/events/trait/proxy»:35,»../ui»:90,»./element/builder»:92,»assert»:62,»lodash»:»7ZYSzK»,»util»:68}],»/sdk/src/transport/form.js»:[function(require,module,exports){
module.exports=require(‘PIvlzb’);
},{}],»PIvlzb»:[function(require,module,exports){
/**
* Transport
*
* @package Transport
* @author Sergey Kamardin
*/
var Transport = require(«./transport»),
_ = require(«lodash»),
Promise = require(«broody-promises»),
FormTransport;
FormTransport = Transport.extend({
_createFrame: function() {
var frame, unique;
frame = document.createElement(«iframe»);
unique = this.uuid.generate(«kvk_transport»);
frame.setAttribute(«allowTransparency», «true»);
frame.setAttribute(«frameBorder», «0»);
frame.setAttribute(«name», unique);
_.extend(frame.style, {
border: «0px»,
position: «absolute»,
top: «-10000px»,
left: «-10000px»
});
return frame;
},
setElementEventManager: function(events) {
this.events = events;
},
setUtils: function(utils) {
this.utils = utils;
},
send: function(parameters, options) {
var self = this;
return new Promise(function(resolve) {
var form, frame;
form = document.createElement(«form»);
if (!(frame = options.frame)) {
frame = self._createFrame();
document.body.appendChild(frame);
} else {
if (!frame.getAttribute(«name»)) {
throw new Error(«Frame must have name»);
}
}
self.events.once(frame, «load», resolve);
form.setAttribute(«method», self.options.method);
form.setAttribute(«action», self.options.action);
form.setAttribute(«target», frame.getAttribute(«name»));
_.forEach(self.utils.flatten(parameters), function(value, parameter) {
var input;
input = document.createElement(‘input’);
input.setAttribute(«type», «hidden»);
input.setAttribute(«name», parameter);
if (!_.isNull(value)) {
input.setAttribute(«value», value);
}
form.appendChild(input);
});
document.body.appendChild(form);
form.submit();
});
}
});
FormTransport.DEFAULTS = {
method: «POST»
};
module.exports = FormTransport;
},{«./transport»:103,»broody-promises»:58,»lodash»:»7ZYSzK»}],103:[function(require,module,exports){
/**
* Transport
*
* @package Transport
* @author Sergey Kamardin
*/
var _ = require(«lodash»),
inherits = require(«inherits-js»),
Transport;
Transport = function(options) {
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
Transport.DEFAULTS = {};
Transport.prototype = {
constructor: Transport,
setUUID: function(uuid) {
this.uuid = uuid;
},
send: function(parameters, options) {
throw new Error(«Method must be implemented»);
},
getUrl: function() {
return this.options.action;
}
};
Transport.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Transport;
},{«inherits-js»:80,»lodash»:»7ZYSzK»}],»cEACDx»:[function(require,module,exports){
var _ = require(«lodash»);
module.exports = {
each: function(obj, iterator, callback) {
var remain, next;
callback = callback || _.noop;
remain = _.keys(obj).length;
if (!remain) {
return callback();
}
next = function(err) {
if (err) {
callback(err);
callback = _.noop;
} else {
remain—;
if (!remain) {
callback();
}
}
};
_.forEach(obj, function(value, index) {
iterator(value, index, next);
});
return null;
},
eachSeries: function(obj, iterator, callback) {
var index, iteration, next, indexes, remain;
callback = callback || _.noop;
indexes = _.keys(obj);
remain = indexes.length;
index = 0;
if (!remain) {
return callback();
}
next = function(err) {
if (err) {
callback(err);
} else {
remain—;
index++;
if (!remain) {
callback();
} else {
iteration();
}
}
};
iteration = function() {
var key;
key = indexes[index];
try {
iterator(obj[key], key, next);
} catch (err) {
next(err);
}
};
iteration();
},
map: function(arr, iterator, callback) {
var result;
result = [];
this.each(arr, function(value, index, next) {
iterator(value, function(err, value) {
result[index] = value;
next(err);
});
}, function(err) {
callback(err, result);
});
},
reduce: function(obj, memo, iterator, callback) {
this.eachSeries(obj, function(value, index, next) {
try {
iterator(memo, value, function(err, value) {
memo = value;
next(err);
});
} catch (err) {
next(err);
}
}, function(err) {
callback(err, memo);
});
}
};
},{«lodash»:»7ZYSzK»}],»async»:[function(require,module,exports){
module.exports=require(‘cEACDx’);
},{}],»27mqzb»:[function(require,module,exports){
/**
* Router factory
*
* @package util
* @author Sergey Kamardin
*/
var _ = require(«lodash»),
inherits = require(«inherits-js»),
Factory;
Factory = function() {
};
Factory.prototype = {
constructor: Factory,
_new: function(constructor, args) {
var service;
function Service() {}
Service.prototype = constructor.prototype;
service = new Service();
try {
constructor.apply(service, args);
} catch (error) {
console.error(«Cannot instantiate service», error);
throw error;
}
return service;
},
_makeCall: function(service, key, args) {
if (_.isFunction(service[key])) {
service[key].apply(service, args);
}
},
_setProperty: function(service, key, value) {
service[key] = value;
},
_factory: function(definition) {
var self = this,
service;
// Arguments
service = this._new(definition.constructor, definition.arguments);
// Calls
_.each(definition.calls, function(call) {
self._makeCall(service, call[0], call[1]);
});
// Properties
_.each(definition.properties, function(value, key) {
self._setProperty(service, key, value);
});
return service;
},
_initialize: function(service) {
if (_.isFunction(service.initialize)) {
service.initialize();
}
},
factory: function (definition) {
var service = this._factory(definition);
this._initialize(service);
return service;
}
};
Factory.extend = function(protos, statics) {
return inherits(this, protos, statics);
};
module.exports = Factory;
},{«inherits-js»:80,»lodash»:»7ZYSzK»}],»/sdk/src/utils/factory.js»:[function(require,module,exports){
module.exports=require(’27mqzb’);
},{}],»IOBVlz»:[function(require,module,exports){
/**
* Factory
*
* @package Factory
* @author Sergey Kamardin
*/
var Factory = require(«../factory»),
_ = require(«lodash»);
module.exports = Factory.extend({
_initialize: function(service) {
service.onload();
}
});
},{«../factory»:»27mqzb»,»lodash»:»7ZYSzK»}],»/sdk/src/utils/factory/sdk.js»:[function(require,module,exports){
module.exports=require(‘IOBVlz’);
},{}],»/sdk/src/utils/impl.js»:[function(require,module,exports){
module.exports=require(‘GAgsTt’);
},{}],»GAgsTt»:[function(require,module,exports){
var Utils = require(«./utils»),
Promise = require(«broody-promises»),
_ = require(«lodash»),
_easing = require(«../../../common/script/src/util/easing»),
DefaultUtils;
/**
* DefaultUtils
*
* @class DefaultUtils
* @extends Utils
* @author Sergey Kamardin
*/
DefaultUtils = Utils.extend(
/**
* @lends DefaultUtils.prototype
*/
{
// DOMReady + images + scripts handler
/*pageReady: function() {
var self = this;
return new Promise(function(resolve) {
var resolveOnce;
if (document.readyState === «complete») {
resolve();
} else {
resolveOnce = _.once(resolve);
self.events.once(window, «load», resolveOnce);
// fallback for broken scripts/images
if (document.readyState === «interactive») {
setTimeout(resolveOnce, 1000);
}
}
});
},*/
// DOMReady handler
documentReady: function() {
var self = this;
return new Promise(function(resolve) {
var resolveOnce;
// jquery says that interactive is bringing some jsp errors
// but some kvk partners have interactive state on payment pages
// so keep on interactive and pray
if (document.readyState === «complete» || document.readyState === «interactive») {
resolve();
} else {
resolveOnce = _.once(resolve);
self.events.once(window, «load», resolveOnce);
self.events.once(window, «DOMContentLoaded», resolveOnce);
}
});
},
getDocumentHeight: function() {
return this.documentReady()
.then(function() {
var body, element;
body = document.body;
element = document.documentElement;
return Math.max(
Math.max(body.scrollHeight, element.scrollHeight),
Math.max(body.offsetHeight, element.offsetHeight),
Math.max(body.clientHeight, element.clientHeight)
);
});
},
getViewportHeight: function() {
return this.documentReady()
.then(function() {
return Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
});
},
getCanvasHeight: function(height) {
return Promise.all([height || this.getDocumentHeight(), this.getViewportHeight()])
.then(function(list) {
var docHeight, winHeight;
docHeight = list[0];
winHeight = list[1];
return docHeight > winHeight ? docHeight : winHeight;
});
//
// return Promise.resolve(window.innerHeight);
},
getBodyScrollTop: function() {
return this.documentReady()
.then(function() {
return parseInt((document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop), 10);
});
},
getStyle: function(element, property) {
try {
if (window.getComputedStyle) {
return document.defaultView.getComputedStyle(element, null).getPropertyValue(property);
} else if (element.currentStyle) {
return element.currentStyle[property];
} else if (element.style) {
return element.style[property] || null;
}
} catch (err) {}
return null;
},
getHighestIndex: function(defaultIndex) {
var self = this;
defaultIndex = defaultIndex || 9999;
function indexes(element) {
var test, zIndex;
if (self.getStyle(element, «position») === «static») {
return _.reduce(element.children || [], function(list, child) {
return list.concat(indexes(child));
}, []);
}
test = true;
test = test && (zIndex = self.getStyle(element, «z-index»)) !== «auto»;
test = test && !_.isNaN(zIndex = parseInt(zIndex));
return test ? [zIndex] : [];
}
return this.documentReady()
.then(function() {
var list;
list = indexes(document.body).concat(defaultIndex);
if (list.length > 5000) {
return defaultIndex;
}
return Math.max.apply(Math, list);
});
},
setBodyScrollTop: function(value) {
return this.documentReady()
.then(function() {
var element;
element = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement : document.body;
element.scrollTop = value;
});
},
flatten: function(obj) {
function flatten(obj) {
return _.reduce(obj, function(memo, value, key) {
if (_.isObject(value)) {
_.forEach(flatten(value), function(v, k) {
memo[key + «.» + k] = v;
});
} else {
memo[key] = value;
}
return memo;
}, {})
}
return flatten(obj);
},
animate: (function() {
var requestAnimationFrame;
function now() {
return Date.now ? Date.now() : (new Date).getTime();
}
requestAnimationFrame = window.requestAnimationFrame || (function() {
var vendors, found,
lastTime;
vendors = [‘ms’, ‘moz’, ‘webkit’, ‘o’];
for(var x = 0; x < vendors.length && !found; ++x) {
found = window[vendors[x]+'RequestAnimationFrame'];
}
if (!found) {
lastTime = 0;
found = function(fn) {
var timeoutID, currentTime, timeToNext, nextLastTime;
currentTime = now();
timeToNext = Math.max(0, 16 - (currentTime - lastTime));
nextLastTime = currentTime + timeToNext;
// console.log("poly", timeToNext, nextLastTime);
timeoutID = setTimeout(function() {
fn.call(null, nextLastTime);
}, timeToNext);
lastTime = nextLastTime;
return timeoutID;
};
}
return found;
})();
return function(fn, duration, easing) {
easing = _easing[easing] || _easing["linear"];
return new Promise(function(resolve) {
var start;
start = now();
function tick() {
var time, factor, current;
current = now();
time = current - start;
if (time < duration) {
factor = easing(time, 0, 1, duration);
// console.log(time, factor);
fn.call(null, factor);
requestAnimationFrame(tick);
} else {
fn.call(null, 1);
// console.log(time, 'STOP');
resolve();
}
}
requestAnimationFrame(tick);
});
}
})()
}
);
module.exports = DefaultUtils;
},{"../../../common/script/src/util/easing":39,"./utils":112,"broody-promises":58,"lodash":"7ZYSzK"}],112:[function(require,module,exports){
var _ = require("lodash"),
inherits = require("inherits-js"),
Events = require("../../../common/script/src/events/element"),
Utils;
/**
* Utils
*
* @class Utils
* @constructor
* @abstract
*
* @param {Events} events
* @param {Object} [options]
*
* @author Sergey Kamardin
*/
Utils = function(events, options) {
if (!(events instanceof Events)) {
throw new TypeError(«Events is expected»);
}
this.events = events;
this.options = _.extend({}, this.constructor.DEFAULTS, options);
};
Utils.DEFAULTS = {};
Utils.prototype = {
constructor: Utils,
/**
* @abstract
*/
flatten: function(obj) {
throw new Error(«Method ‘flatten’ must be implemented»);
},
/**
* @abstract
*/
unflatten: function(obj) {
throw new Error(«Method ‘unflatten’ must be implemented»);
},
/**
* @abstract
*/
documentReady: function() {
throw new Error(«Method ‘windowReady’ must be implemented»);
},
/**
* @abstract
*/
getDocumentHeight: function() {
throw new Error(«Method must be implemented»);
},
/**
* @abstract
*/
getCanvasHeight: function(height) {
throw new Error(«Method must be implemented»);
},
/**
* @abstract
*/
getViewportHeight: function() {
throw new Error(«Method must be implemented»);
},
/**
* @abstract
*/
getBodyScrollTop: function() {
throw new Error(«Method must be implemented»);
},
/**
* @abstract
*/
getBodyScrollLeft: function() {
throw new Error(«Method must be implemented»);
},
/**
* @abstract
*/
animate: function(fn, duration, easing) {
throw new Error(«Method must be implemented»);
}
};
Utils.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = Utils;
},{«../../../common/script/src/events/element»:27,»inherits-js»:80,»lodash»:»7ZYSzK»}],»/sdk/src/uuid/murmurhash.js»:[function(require,module,exports){
module.exports=require(‘wBycvh’);
},{}],»wBycvh»:[function(require,module,exports){
/**
* UUID
*
* @package UUID
* @author Sergey Kamardin
*/
var UUID = require(«./uuid»),
_ = require(«lodash»),
murmurhash = require(«murmurhash»);
module.exports = UUID.extend({
generate: function(key) {
var buffer;
buffer = [];
buffer.push(new Date().getTime());
buffer.push(Math.random() * (1000 — 1) + 1);
return (_.isString(key) ? key : «»).concat(murmurhash(buffer.join(»)));
}
});
},{«./uuid»:115,»lodash»:»7ZYSzK»,»murmurhash»:83}],115:[function(require,module,exports){
/**
* UUID
*
* @package UUID
* @author Sergey Kamardin
*/
var _ = require(«lodash»),
inherits = require(«inherits-js»),
UUID;
UUID = function(options) {
this.options = _.extend({}, UUID.DEFAULTS, options);
};
UUID.DEFAULTS = {};
UUID.prototype = {
constructor: UUID,
generate: function(key, options) {
throw new Error(«Method must be implemented»);
}
};
UUID.extend = function(prots, statics) {
return inherits(this, prots, statics);
};
module.exports = UUID;
},{«inherits-js»:80,»lodash»:»7ZYSzK»}],»7ZYSzK»:[function(require,module,exports){
(function (global){
/**
* @license
* Lo-Dash 2.4.1 (Custom Build)
* Build: `lodash exports=»node» include=»forEach,map,extend,merge,find,isNull,isNaN,isEmpty,isUndefined,isFunction,isBoolean,isString,isObject,has,reduce,once,indexOf,remove,bind,any,times,pluck,chain,where,keys,difference» -d -o lodash.js`
* Copyright 2012-2013 The Dojo Foundation
* Based on Underscore.js 1.5.2
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license
*/
;(function() {
/** Used to pool arrays and objects used internally */
var arrayPool = [],
objectPool = [];
/** Used internally to indicate various things */
var indicatorObject = {};
/** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
var keyPrefix = +new Date + »;
/** Used as the size when optimizations are enabled for large arrays */
var largeArraySize = 75;
/** Used as the max size of the `arrayPool` and `objectPool` */
var maxPoolSize = 40;
/** Used to detected named functions */
var reFuncName = /^\s*function[ \n\r\t]+\w/;
/** Used to detect functions containing a `this` reference */
var reThis = /\bthis\b/;
/** Used to fix the JScript [[DontEnum]] bug */
var shadowedProps = [
‘constructor’, ‘hasOwnProperty’, ‘isPrototypeOf’, ‘propertyIsEnumerable’,
‘toLocaleString’, ‘toString’, ‘valueOf’
];
/** `Object#toString` result shortcuts */
var argsClass = ‘[object Arguments]’,
arrayClass = ‘[object Array]’,
boolClass = ‘[object Boolean]’,
dateClass = ‘[object Date]’,
errorClass = ‘[object Error]’,
funcClass = ‘[object Function]’,
numberClass = ‘[object Number]’,
objectClass = ‘[object Object]’,
regexpClass = ‘[object RegExp]’,
stringClass = ‘[object String]’;
/** Used as the property descriptor for `__bindData__` */
var descriptor = {
‘configurable’: false,
‘enumerable’: false,
‘value’: null,
‘writable’: false
};
/** Used as the data object for `iteratorTemplate` */
var iteratorData = {
‘args’: »,
‘array’: null,
‘bottom’: »,
‘firstArg’: »,
‘init’: »,
‘keys’: null,
‘loop’: »,
‘shadowedProps’: null,
‘support’: null,
‘top’: »,
‘useHas’: false
};
/** Used to determine if values are of the language type Object */
var objectTypes = {
‘boolean’: false,
‘function’: true,
‘object’: true,
‘number’: false,
‘string’: false,
‘undefined’: false
};
/** Used as a reference to the global object */
var root = (objectTypes[typeof window] && window) || this;
/** Detect free variable `exports` */
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
/** Detect free variable `module` */
var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports` */
var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
/** Detect free variable `global` from Node.js or Browserified code and use it as `root` */
var freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
/*—————————————————————————*/
/**
* The base implementation of `_.indexOf` without support for binary searches
* or `fromIndex` constraints.
*
* @private
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value or `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
var index = (fromIndex || 0) — 1,
length = array ? array.length : 0;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* An implementation of `_.contains` for cache objects that mimics the return
* signature of `_.indexOf` by returning `0` if the value is found, else `-1`.
*
* @private
* @param {Object} cache The cache object to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns `0` if `value` is found, else `-1`.
*/
function cacheIndexOf(cache, value) {
var type = typeof value;
cache = cache.cache;
if (type == 'boolean' || value == null) {
return cache[value] ? 0 : -1;
}
if (type != 'number' && type != 'string') {
type = 'object';
}
var key = type == 'number' ? value : keyPrefix + value;
cache = (cache = cache[type]) && cache[key];
return type == 'object'
? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1)
: (cache ? 0 : -1);
}
/**
* Adds a given value to the corresponding cache object.
*
* @private
* @param {*} value The value to add to the cache.
*/
function cachePush(value) {
var cache = this.cache,
type = typeof value;
if (type == ‘boolean’ || value == null) {
cache[value] = true;
} else {
if (type != ‘number’ && type != ‘string’) {
type = ‘object’;
}
var key = type == ‘number’ ? value : keyPrefix + value,
typeCache = cache[type] || (cache[type] = {});
if (type == ‘object’) {
(typeCache[key] || (typeCache[key] = [])).push(value);
} else {
typeCache[key] = true;
}
}
}
/**
* Creates a cache object to optimize linear searches of large arrays.
*
* @private
* @param {Array} [array=[]] The array to search.
* @returns {null|Object} Returns the cache object or `null` if caching should not be used.
*/
function createCache(array) {
var index = -1,
length = array.length,
first = array[0],
mid = array[(length / 2) | 0],
last = array[length — 1];
if (first && typeof first == ‘object’ &&
mid && typeof mid == ‘object’ && last && typeof last == ‘object’) {
return false;
}
var cache = getObject();
cache[‘false’] = cache[‘null’] = cache[‘true’] = cache[‘undefined’] = false;
var result = getObject();
result.array = array;
result.cache = cache;
result.push = cachePush;
while (++index < length) {
result.push(array[index]);
}
return result;
}
/**
* Gets an array from the array pool or creates a new one if the pool is empty.
*
* @private
* @returns {Array} The array from the pool.
*/
function getArray() {
return arrayPool.pop() || [];
}
/**
* Gets an object from the object pool or creates a new one if the pool is empty.
*
* @private
* @returns {Object} The object from the pool.
*/
function getObject() {
return objectPool.pop() || {
'array': null,
'cache': null,
'false': false,
'null': false,
'number': null,
'object': null,
'push': null,
'string': null,
'true': false,
'undefined': false
};
}
/**
* Checks if `value` is a DOM node in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a DOM node, else `false`.
*/
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
/**
* Releases the given array back to the array pool.
*
* @private
* @param {Array} [array] The array to release.
*/
function releaseArray(array) {
array.length = 0;
if (arrayPool.length < maxPoolSize) {
arrayPool.push(array);
}
}
/**
* Releases the given object back to the object pool.
*
* @private
* @param {Object} [object] The object to release.
*/
function releaseObject(object) {
var cache = object.cache;
if (cache) {
releaseObject(cache);
}
object.array = object.cache =object.object = object.number = object.string =null;
if (objectPool.length < maxPoolSize) {
objectPool.push(object);
}
}
/**
* Slices the `collection` from the `start` index up to, but not including,
* the `end` index.
*
* Note: This function is used instead of `Array#slice` to support node lists
* in IE < 9 and to ensure dense arrays are returned.
*
* @private
* @param {Array|Object|string} collection The collection to slice.
* @param {number} start The start index.
* @param {number} end The end index.
* @returns {Array} Returns the new array.
*/
function slice(array, start, end) {
start || (start = 0);
if (typeof end == 'undefined') {
end = array ? array.length : 0;
}
var index = -1,
length = end - start || 0,
result = Array(length < 0 ? 0 : length);
while (++index < length) {
result[index] = array[start + index];
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Used for `Array` method references.
*
* Normally `Array.prototype` would suffice, however, using an array literal
* avoids issues in Narwhal.
*/
var arrayRef = [];
/** Used for native method references */
var errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype;
/** Used to resolve the internal [[Class]] of values */
var toString = objectProto.toString;
/** Used to detect if a method is native */
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
/** Native method shortcuts */
var fnToString = Function.prototype.toString,
getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
hasOwnProperty = objectProto.hasOwnProperty,
push = arrayRef.push,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayRef.splice,
unshift = arrayRef.unshift;
/** Used to set meta data on functions */
var defineProperty = (function() {
// IE 8 only accepts DOM elements
try {
var o = {},
func = isNative(func = Object.defineProperty) && func,
result = func(o, o, o) && func;
} catch(e) { }
return result;
}());
/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate,
nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray,
nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys,
nativeMax = Math.max;
/** Used to avoid iterating non-enumerable properties in IE < 9 */
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
(function() {
var length = shadowedProps.length;
while (length--) {
var key = shadowedProps[length];
for (var className in nonEnumProps) {
if (hasOwnProperty.call(nonEnumProps, className) && !hasOwnProperty.call(nonEnumProps[className], key)) {
nonEnumProps[className][key] = false;
}
}
}
}());
/*--------------------------------------------------------------------------*/
/**
* Creates a `lodash` object which wraps the given value to enable intuitive
* method chaining.
*
* In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
* `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
* and `unshift`
*
* Chaining is supported in custom builds as long as the `value` method is
* implicitly or explicitly included in the build.
*
* The chainable wrapper functions are:
* `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
* `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`,
* `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`,
* `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
* `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
* `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`,
* `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`,
* `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`,
* `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`,
* `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`,
* and `zip`
*
* The non-chainable wrapper functions are:
* `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`,
* `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`,
* `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
* `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`,
* `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`,
* `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`,
* `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`,
* `template`, `unescape`, `uniqueId`, and `value`
*
* The wrapper functions `first` and `last` return wrapped values when `n` is
* provided, otherwise they return unwrapped values.
*
* Explicit chaining can be enabled by using the `_.chain` method.
*
* @name _
* @constructor
* @category Chaining
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns a `lodash` instance.
* @example
*
* var wrapped = _([1, 2, 3]);
*
* // returns an unwrapped value
* wrapped.reduce(function(sum, num) {
* return sum + num;
* });
* // => 6
*
* // returns a wrapped value
* var squares = wrapped.map(function(num) {
* return num * num;
* });
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
// don’t wrap if already wrapped, even if wrapped by a different `lodash` constructor
return (value && typeof value == ‘object’ && !isArray(value) && hasOwnProperty.call(value, ‘__wrapped__’))
? value
: new lodashWrapper(value);
}
/**
* A fast path for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap in a `lodash` instance.
* @param {boolean} chainAll A flag to enable chaining for all methods
* @returns {Object} Returns a `lodash` instance.
*/
function lodashWrapper(value, chainAll) {
this.__chain__ = !!chainAll;
this.__wrapped__ = value;
}
// ensure `new lodashWrapper` is an instance of `lodash`
lodashWrapper.prototype = lodash.prototype;
/**
* An object used to flag environments features.
*
* @static
* @memberOf _
* @type Object
*/
var support = lodash.support = {};
(function() {
var ctor = function() { this.x = 1; },
object = { ‘0’: 1, ‘length’: 1 },
props = [];
ctor.prototype = { ‘valueOf’: 1, ‘y’: 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
/**
* Detect if an `arguments` object’s [[Class]] is resolvable (all but Firefox < 4, IE < 9).
*
* @memberOf _.support
* @type boolean
*/
support.argsClass = toString.call(arguments) == argsClass;
/**
* Detect if `arguments` objects are `Object` objects (all but Narwhal and Opera < 10.5).
*
* @memberOf _.support
* @type boolean
*/
support.argsObject = arguments.constructor == Object && !(arguments instanceof Array);
/**
* Detect if `name` or `message` properties of `Error.prototype` are
* enumerable by default. (IE < 9, Safari < 5.1)
*
* @memberOf _.support
* @type boolean
*/
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
/**
* Detect if `prototype` properties are enumerable by default.
*
* Firefox < 3.6, Opera > 9.50 — Opera < 11.60, and Safari < 5.1
* (if the prototype or a property on the prototype has been set)
* incorrectly sets a function's `prototype` property [[Enumerable]]
* value to `true`.
*
* @memberOf _.support
* @type boolean
*/
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
/**
* Detect if functions can be decompiled by `Function#toString`
* (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps).
*
* @memberOf _.support
* @type boolean
*/
support.funcDecomp = !isNative(root.WinRTError) && reThis.test(function() { return this; });
/**
* Detect if `Function#name` is supported (all but IE).
*
* @memberOf _.support
* @type boolean
*/
support.funcNames = typeof Function.name == 'string';
/**
* Detect if `arguments` object indexes are non-enumerable
* (Firefox < 4, IE < 9, PhantomJS, Safari < 5.1).
*
* @memberOf _.support
* @type boolean
*/
support.nonEnumArgs = key != 0;
/**
* Detect if properties shadowing those on `Object.prototype` are non-enumerable.
*
* In IE < 9 an objects own properties, shadowing non-enumerable ones, are
* made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug).
*
* @memberOf _.support
* @type boolean
*/
support.nonEnumShadows = !/valueOf/.test(props);
/**
* Detect if own properties are iterated after inherited properties (all but IE < 9).
*
* @memberOf _.support
* @type boolean
*/
support.ownLast = props[0] != 'x';
/**
* Detect if `Array#shift` and `Array#splice` augment array-like objects correctly.
*
* Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()`
* and `splice()` functions that fail to remove the last element, `value[0]`,
* of array-like objects even though the `length` property is set to `0`.
* The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
* is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
*
* @memberOf _.support
* @type boolean
*/
support.spliceObjects = (arrayRef.splice.call(object, 0, 1), !object[0]);
/**
* Detect lack of support for accessing string characters by index.
*
* IE < 8 can't access characters by index and IE 8 can only access
* characters by index on string literals.
*
* @memberOf _.support
* @type boolean
*/
support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx';
/**
* Detect if a DOM node's [[Class]] is resolvable (all but IE < 9)
* and that the JS engine errors when attempting to coerce an object to
* a string without a `toString` function.
*
* @memberOf _.support
* @type boolean
*/
try {
support.nodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
support.nodeClass = true;
}
}(1));
/*--------------------------------------------------------------------------*/
/**
* The template used to create iterator functions.
*
* @private
* @param {Object} data The data object used to populate the text.
* @returns {string} Returns the interpolated text.
*/
var iteratorTemplate = function(obj) {
var __p = 'var index, iterable = ' +
(obj.firstArg) +
', result = ' +
(obj.init) +
';\nif (!iterable) return result;\n' +
(obj.top) +
';';
if (obj.array) {
__p += '\nvar length = iterable.length; index = -1;\nif (' +
(obj.array) +
') { ';
if (support.unindexedChars) {
__p += '\n if (isString(iterable)) {\n iterable = iterable.split(\'\')\n } ';
}
__p += '\n while (++index < length) {\n ' +
(obj.loop) +
';\n }\n}\nelse { ';
} else if (support.nonEnumArgs) {
__p += '\n var length = iterable.length; index = -1;\n if (length && isArguments(iterable)) {\n while (++index < length) {\n index += \'\';\n ' +
(obj.loop) +
';\n }\n } else { ';
}
if (support.enumPrototypes) {
__p += '\n var skipProto = typeof iterable == \'function\';\n ';
}
if (support.enumErrorProps) {
__p += '\n var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n ';
}
var conditions = []; if (support.enumPrototypes) { conditions.push('!(skipProto && index == "prototype")'); } if (support.enumErrorProps) { conditions.push('!(skipErrorProps && (index == "message" || index == "name"))'); }
if (obj.useHas && obj.keys) {
__p += '\n var ownIndex = -1,\n ownProps = objectTypes[typeof iterable] && keys(iterable),\n length = ownProps ? ownProps.length : 0;\n\n while (++ownIndex < length) {\n index = ownProps[ownIndex];\n';
if (conditions.length) {
__p += ' if (' +
(conditions.join(' && ')) +
') {\n ';
}
__p +=
(obj.loop) +
'; ';
if (conditions.length) {
__p += '\n }';
}
__p += '\n } ';
} else {
__p += '\n for (index in iterable) {\n';
if (obj.useHas) { conditions.push("hasOwnProperty.call(iterable, index)"); } if (conditions.length) {
__p += ' if (' +
(conditions.join(' && ')) +
') {\n ';
}
__p +=
(obj.loop) +
'; ';
if (conditions.length) {
__p += '\n }';
}
__p += '\n } ';
if (support.nonEnumShadows) {
__p += '\n\n if (iterable !== objectProto) {\n var ctor = iterable.constructor,\n isProto = iterable === (ctor && ctor.prototype),\n className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n nonEnum = nonEnumProps[className];\n ';
for (k = 0; k < 7; k++) {
__p += '\n index = \'' +
(obj.shadowedProps[k]) +
'\';\n if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))';
if (!obj.useHas) {
__p += ' || (!nonEnum[index] && iterable[index] !== objectProto[index])';
}
__p += ') {\n ' +
(obj.loop) +
';\n } ';
}
__p += '\n } ';
}
}
if (obj.array || support.nonEnumArgs) {
__p += '\n}';
}
__p +=
(obj.bottom) +
';\nreturn result';
return __p
};
/*--------------------------------------------------------------------------*/
/**
* The base implementation of `_.bind` that creates the bound function and
* sets its meta data.
*
* @private
* @param {Array} bindData The bind data array.
* @returns {Function} Returns the new bound function.
*/
function baseBind(bindData) {
var func = bindData[0],
partialArgs = bindData[2],
thisArg = bindData[4];
function bound() {
// `Function#bind` spec
// http://es5.github.io/#x15.3.4.5
if (partialArgs) {
// avoid `arguments` object deoptimizations by using `slice` instead
// of `Array.prototype.slice.call` and not assigning `arguments` to a
// variable as a ternary expression
var args = slice(partialArgs);
push.apply(args, arguments);
}
// mimic the constructor's `return` behavior
// http://es5.github.io/#x13.2.2
if (this instanceof bound) {
// ensure `new bound` is an instance of `func`
var thisBinding = baseCreate(func.prototype),
result = func.apply(thisBinding, args || arguments);
return isObject(result) ? result : thisBinding;
}
return func.apply(thisArg, args || arguments);
}
setBindData(bound, bindData);
return bound;
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} prototype The object to inherit from.
* @returns {Object} Returns the new object.
*/
function baseCreate(prototype, properties) {
return isObject(prototype) ? nativeCreate(prototype) : {};
}
// fallback for browsers without `Object.create`
if (!nativeCreate) {
baseCreate = (function() {
function Object() {}
return function(prototype) {
if (isObject(prototype)) {
Object.prototype = prototype;
var result = new Object;
Object.prototype = null;
}
return result || root.Object();
};
}());
}
/**
* The base implementation of `_.createCallback` without support for creating
* "_.pluck" or "_.where" style callbacks.
*
* @private
* @param {*} [func=identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of the created callback.
* @param {number} [argCount] The number of arguments the callback accepts.
* @returns {Function} Returns a callback function.
*/
function baseCreateCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
// exit early for no `thisArg` or already bound by `Function#bind`
if (typeof thisArg == 'undefined' || !('prototype' in func)) {
return func;
}
var bindData = func.__bindData__;
if (typeof bindData == 'undefined') {
if (support.funcNames) {
bindData = !func.name;
}
bindData = bindData || !support.funcDecomp;
if (!bindData) {
var source = fnToString.call(func);
if (!support.funcNames) {
bindData = !reFuncName.test(source);
}
if (!bindData) {
// checks if `func` references the `this` keyword and stores the result
bindData = reThis.test(source);
setBindData(func, bindData);
}
}
}
// exit early if there are no `this` references or `func` is bound
if (bindData === false || (bindData !== true && bindData[1] & 1)) {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 2: return function(a, b) {
return func.call(thisArg, a, b);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
}
return bind(func, thisArg);
}
/**
* The base implementation of `createWrapper` that creates the wrapper and
* sets its meta data.
*
* @private
* @param {Array} bindData The bind data array.
* @returns {Function} Returns the new function.
*/
function baseCreateWrapper(bindData) {
var func = bindData[0],
bitmask = bindData[1],
partialArgs = bindData[2],
partialRightArgs = bindData[3],
thisArg = bindData[4],
arity = bindData[5];
var isBind = bitmask & 1,
isBindKey = bitmask & 2,
isCurry = bitmask & 4,
isCurryBound = bitmask & 8,
key = func;
function bound() {
var thisBinding = isBind ? thisArg : this;
if (partialArgs) {
var args = slice(partialArgs);
push.apply(args, arguments);
}
if (partialRightArgs || isCurry) {
args || (args = slice(arguments));
if (partialRightArgs) {
push.apply(args, partialRightArgs);
}
if (isCurry && args.length < arity) {
bitmask |= 16 & ~32;
return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]);
}
}
args || (args = arguments);
if (isBindKey) {
func = thisBinding[key];
}
if (this instanceof bound) {
thisBinding = baseCreate(func.prototype);
var result = func.apply(thisBinding, args);
return isObject(result) ? result : thisBinding;
}
return func.apply(thisBinding, args);
}
setBindData(bound, bindData);
return bound;
}
/**
* The base implementation of `_.difference` that accepts a single array
* of values to exclude.
*
* @private
* @param {Array} array The array to process.
* @param {Array} [values] The array of values to exclude.
* @returns {Array} Returns a new array of filtered values.
*/
function baseDifference(array, values) {
var index = -1,
indexOf = getIndexOf(),
length = array ? array.length : 0,
isLarge = length >= largeArraySize && indexOf === baseIndexOf,
result = [];
if (isLarge) {
var cache = createCache(values);
if (cache) {
indexOf = cacheIndexOf;
values = cache;
} else {
isLarge = false;
}
}
while (++index < length) {
var value = array[index];
if (indexOf(values, value) < 0) {
result.push(value);
}
}
if (isLarge) {
releaseObject(values);
}
return result;
}
/**
* The base implementation of `_.flatten` without support for callback
* shorthands or `thisArg` binding.
*
* @private
* @param {Array} array The array to flatten.
* @param {boolean} [isShallow=false] A flag to restrict flattening to a single level.
* @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects.
* @param {number} [fromIndex=0] The index to start from.
* @returns {Array} Returns a new flattened array.
*/
function baseFlatten(array, isShallow, isStrict, fromIndex) {
var index = (fromIndex || 0) - 1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value && typeof value == 'object' && typeof value.length == 'number'
&& (isArray(value) || isArguments(value))) {
// recursively flatten arrays (susceptible to call stack limits)
if (!isShallow) {
value = baseFlatten(value, isShallow, isStrict);
}
var valIndex = -1,
valLength = value.length,
resIndex = result.length;
result.length += valLength;
while (++valIndex < valLength) {
result[resIndex++] = value[valIndex];
}
} else if (!isStrict) {
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.isEqual`, without support for `thisArg` binding,
* that allows partial "_.where" style comparisons.
*
* @private
* @param {*} a The value to compare.
* @param {*} b The other value to compare.
* @param {Function} [callback] The function to customize comparing values.
* @param {Function} [isWhere=false] A flag to indicate performing partial comparisons.
* @param {Array} [stackA=[]] Tracks traversed `a` objects.
* @param {Array} [stackB=[]] Tracks traversed `b` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(a, b, callback, isWhere, stackA, stackB) {
// used to indicate that when comparing objects, `a` has at least the properties of `b`
if (callback) {
var result = callback(a, b);
if (typeof result != 'undefined') {
return !!result;
}
}
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a &&
!(a && objectTypes[type]) &&
!(b && objectTypes[otherType])) {
return false;
}
// exit early for `null` and `undefined` avoiding ES3's Function#call behavior
// http://es5.github.io/#x15.3.4.4
if (a == null || b == null) {
return a === b;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `+0` vs. `-0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// unwrap any `lodash` wrapped values
var aWrapped = hasOwnProperty.call(a, '__wrapped__'),
bWrapped = hasOwnProperty.call(b, '__wrapped__');
if (aWrapped || bWrapped) {
return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB);
}
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = getArray());
stackB || (stackB = getArray());
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result || isWhere) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (isWhere) {
while (index--) {
if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) {
break;
}
}
} else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
forIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB));
}
});
if (result && !isWhere) {
// ensure both objects have the same number of properties
forIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
if (initedStack) {
releaseArray(stackA);
releaseArray(stackB);
}
return result;
}
/**
* The base implementation of `_.merge` without argument juggling or support
* for `thisArg` binding.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [callback] The function to customize merging properties.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
*/
function baseMerge(object, source, callback, stackA, stackB) {
(isArray(source) ? forEach : forOwn)(source, function(source, key) {
var found,
isArr,
result = source,
value = object[key];
if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
// avoid merging previously merged cyclic sources
var stackLength = stackA.length;
while (stackLength—) {
if ((found = stackA[stackLength] == source)) {
value = stackB[stackLength];
break;
}
}
if (!found) {
var isShallow;
if (callback) {
result = callback(value, source);
if ((isShallow = typeof result != ‘undefined’)) {
value = result;
}
}
if (!isShallow) {
value = isArr
? (isArray(value) ? value : [])
: (isPlainObject(value) ? value : {});
}
// add `source` and associated `value` to the stack of traversed objects
stackA.push(source);
stackB.push(value);
// recursively merge objects and arrays (susceptible to call stack limits)
if (!isShallow) {
baseMerge(value, source, callback, stackA, stackB);
}
}
}
else {
if (callback) {
result = callback(value, source);
if (typeof result == ‘undefined’) {
result = source;
}
}
if (typeof result != ‘undefined’) {
value = result;
}
}
object[key] = value;
});
}
/**
* Creates a function that, when called, either curries or invokes `func`
* with an optional `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to reference.
* @param {number} bitmask The bitmask of method flags to compose.
* The bitmask may be composed of the following flags:
* 1 — `_.bind`
* 2 — `_.bindKey`
* 4 — `_.curry`
* 8 — `_.curry` (bound)
* 16 — `_.partial`
* 32 — `_.partialRight`
* @param {Array} [partialArgs] An array of arguments to prepend to those
* provided to the new function.
* @param {Array} [partialRightArgs] An array of arguments to append to those
* provided to the new function.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new function.
*/
function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) {
var isBind = bitmask & 1,
isBindKey = bitmask & 2,
isCurry = bitmask & 4,
isCurryBound = bitmask & 8,
isPartial = bitmask & 16,
isPartialRight = bitmask & 32;
if (!isBindKey && !isFunction(func)) {
throw new TypeError;
}
if (isPartial && !partialArgs.length) {
bitmask &= ~16;
isPartial = partialArgs = false;
}
if (isPartialRight && !partialRightArgs.length) {
bitmask &= ~32;
isPartialRight = partialRightArgs = false;
}
var bindData = func && func.__bindData__;
if (bindData && bindData !== true) {
// clone `bindData`
bindData = slice(bindData);
if (bindData[2]) {
bindData[2] = slice(bindData[2]);
}
if (bindData[3]) {
bindData[3] = slice(bindData[3]);
}
// set `thisBinding` is not previously bound
if (isBind && !(bindData[1] & 1)) {
bindData[4] = thisArg;
}
// set if previously bound but not currently (subsequent curried functions)
if (!isBind && bindData[1] & 1) {
bitmask |= 8;
}
// set curried arity if not yet set
if (isCurry && !(bindData[1] & 4)) {
bindData[5] = arity;
}
// append partial left arguments
if (isPartial) {
push.apply(bindData[2] || (bindData[2] = []), partialArgs);
}
// append partial right arguments
if (isPartialRight) {
unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs);
}
// merge flags
bindData[1] |= bitmask;
return createWrapper.apply(null, bindData);
}
// fast path for `_.bind`
var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper;
return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]);
}
/**
* Creates compiled iteration functions.
*
* @private
* @param {…Object} [options] The compile options object(s).
* @param {string} [options.array] Code to determine if the iterable is an array or array-like.
* @param {boolean} [options.useHas] Specify using `hasOwnProperty` checks in the object loop.
* @param {Function} [options.keys] A reference to `_.keys` for use in own property iteration.
* @param {string} [options.args] A comma separated string of iteration function arguments.
* @param {string} [options.top] Code to execute before the iteration branches.
* @param {string} [options.loop] Code to execute in the object loop.
* @param {string} [options.bottom] Code to execute after the iteration branches.
* @returns {Function} Returns the compiled function.
*/
function createIterator() {
// data properties
iteratorData.shadowedProps = shadowedProps;
// iterator options
iteratorData.array = iteratorData.bottom = iteratorData.loop = iteratorData.top = »;
iteratorData.init = ‘iterable’;
iteratorData.useHas = true;
// merge options into a template data object
for (var object, index = 0; object = arguments[index]; index++) {
for (var key in object) {
iteratorData[key] = object[key];
}
}
var args = iteratorData.args;
iteratorData.firstArg = /^[^,]+/.exec(args)[0];
// create the function factory
var factory = Function(
‘baseCreateCallback, errorClass, errorProto, hasOwnProperty, ‘ +
‘indicatorObject, isArguments, isArray, isString, keys, objectProto, ‘ +
‘objectTypes, nonEnumProps, stringClass, stringProto, toString’,
‘return function(‘ + args + ‘) {\n’ + iteratorTemplate(iteratorData) + ‘\n}’
);
// return the compiled function
return factory(
baseCreateCallback, errorClass, errorProto, hasOwnProperty,
indicatorObject, isArguments, isArray, isString, iteratorData.keys, objectProto,
objectTypes, nonEnumProps, stringClass, stringProto, toString
);
}
/**
* Gets the appropriate «indexOf» function. If the `_.indexOf` method is
* customized, this method returns the custom method, otherwise it returns
* the `baseIndexOf` function.
*
* @private
* @returns {Function} Returns the «indexOf» function.
*/
function getIndexOf() {
var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result;
return result;
}
/**
* Checks if `value` is a native function.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a native function, else `false`.
*/
function isNative(value) {
return typeof value == ‘function’ && reNative.test(value);
}
/**
* Sets `this` binding data on a given function.
*
* @private
* @param {Function} func The function to set data on.
* @param {Array} value The data array to set.
*/
var setBindData = !defineProperty ? noop : function(func, value) {
descriptor.value = value;
defineProperty(func, ‘__bindData__’, descriptor);
};
/**
* A fallback implementation of `isPlainObject` which checks if a given value
* is an object created by the `Object` constructor, assuming objects created
* by the `Object` constructor have no inherited enumerable properties and that
* there are no `Object.prototype` extensions.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
*/
function shimIsPlainObject(value) {
var ctor,
result;
// avoid non Object objects, `arguments` objects, and DOM elements
if (!(value && toString.call(value) == objectClass) ||
(ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor)) ||
(!support.argsClass && isArguments(value)) ||
(!support.nodeClass && isNode(value))) {
return false;
}
// IE < 9 iterates inherited properties before own properties. If the first
// iterated property is an object's own property then there are no inherited
// enumerable properties.
if (support.ownLast) {
forIn(value, function(value, key, object) {
result = hasOwnProperty.call(object, key);
return false;
});
return result !== false;
}
// In most environments an object's own properties are iterated before
// its inherited properties. If the last iterated property is an object's
// own property then there are no inherited enumerable properties.
forIn(value, function(value, key) {
result = key;
});
return typeof result == 'undefined' || hasOwnProperty.call(value, result);
}
/*--------------------------------------------------------------------------*/
/**
* Checks if `value` is an `arguments` object.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`.
* @example
*
* (function() { return _.isArguments(arguments); })(1, 2, 3);
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return value && typeof value == ‘object’ && typeof value.length == ‘number’ &&
toString.call(value) == argsClass || false;
}
// fallback for browsers that can’t detect `arguments` objects by [[Class]]
if (!support.argsClass) {
isArguments = function(value) {
return value && typeof value == ‘object’ && typeof value.length == ‘number’ &&
hasOwnProperty.call(value, ‘callee’) && !propertyIsEnumerable.call(value, ‘callee’) || false;
};
}
/**
* Checks if `value` is an array.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is an array, else `false`.
* @example
*
* (function() { return _.isArray(arguments); })();
* // => false
*
* _.isArray([1, 2, 3]);
* // => true
*/
var isArray = nativeIsArray || function(value) {
return value && typeof value == ‘object’ && typeof value.length == ‘number’ &&
toString.call(value) == arrayClass || false;
};
/**
* A fallback implementation of `Object.keys` which produces an array of the
* given object’s own enumerable property names.
*
* @private
* @type Function
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property names.
*/
var shimKeys = createIterator({
‘args’: ‘object’,
‘init’: ‘[]’,
‘top’: ‘if (!(objectTypes[typeof object])) return result’,
‘loop’: ‘result.push(index)’
});
/**
* Creates an array composed of the own enumerable property names of an object.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property names.
* @example
*
* _.keys({ ‘one’: 1, ‘two’: 2, ‘three’: 3 });
* // => [‘one’, ‘two’, ‘three’] (property order is not guaranteed across environments)
*/
var keys = !nativeKeys ? shimKeys : function(object) {
if (!isObject(object)) {
return [];
}
if ((support.enumPrototypes && typeof object == ‘function’) ||
(support.nonEnumArgs && object.length && isArguments(object))) {
return shimKeys(object);
}
return nativeKeys(object);
};
/** Reusable iterator options shared by `each`, `forIn`, and `forOwn` */
var eachIteratorOptions = {
‘args’: ‘collection, callback, thisArg’,
‘top’: «callback = callback && typeof thisArg == ‘undefined’ ? callback : baseCreateCallback(callback, thisArg, 3)»,
‘array’: «typeof length == ‘number'»,
‘keys’: keys,
‘loop’: ‘if (callback(iterable[index], index, collection) === false) return result’
};
/** Reusable iterator options for `assign` and `defaults` */
var defaultsIteratorOptions = {
‘args’: ‘object, source, guard’,
‘top’:
‘var args = arguments,\n’ +
‘ argsIndex = 0,\n’ +
» argsLength = typeof guard == ‘number’ ? 2 : args.length;\n» +
‘while (++argsIndex < argsLength) {\n' +
' iterable = args[argsIndex];\n' +
' if (iterable && objectTypes[typeof iterable]) {',
'keys': keys,
'loop': "if (typeof result[index] == 'undefined') result[index] = iterable[index]",
'bottom': ' }\n}'
};
/** Reusable iterator options for `forIn` and `forOwn` */
var forOwnIteratorOptions = {
'top': 'if (!objectTypes[typeof iterable]) return result;\n' + eachIteratorOptions.top,
'array': false
};
/**
* A function compiled to iterate `arguments` objects, arrays, objects, and
* strings consistenly across environments, executing the callback for each
* element in the collection. The callback is bound to `thisArg` and invoked
* with three arguments; (value, index|key, collection). Callbacks may exit
* iteration early by explicitly returning `false`.
*
* @private
* @type Function
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array|Object|string} Returns `collection`.
*/
var baseEach = createIterator(eachIteratorOptions);
/*--------------------------------------------------------------------------*/
/**
* Assigns own enumerable properties of source object(s) to the destination
* object. Subsequent sources will overwrite property assignments of previous
* sources. If a callback is provided it will be executed to produce the
* assigned values. The callback is bound to `thisArg` and invoked with two
* arguments; (objectValue, sourceValue).
*
* @static
* @memberOf _
* @type Function
* @alias extend
* @category Objects
* @param {Object} object The destination object.
* @param {...Object} [source] The source objects.
* @param {Function} [callback] The function to customize assigning values.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the destination object.
* @example
*
* _.assign({ 'name': 'fred' }, { 'employer': 'slate' });
* // => { ‘name’: ‘fred’, ’employer’: ‘slate’ }
*
* var defaults = _.partialRight(_.assign, function(a, b) {
* return typeof a == ‘undefined’ ? b : a;
* });
*
* var object = { ‘name’: ‘barney’ };
* defaults(object, { ‘name’: ‘fred’, ’employer’: ‘slate’ });
* // => { ‘name’: ‘barney’, ’employer’: ‘slate’ }
*/
var assign = createIterator(defaultsIteratorOptions, {
‘top’:
defaultsIteratorOptions.top.replace(‘;’,
‘;\n’ +
«if (argsLength > 3 && typeof args[argsLength — 2] == ‘function’) {\n» +
‘ var callback = baseCreateCallback(args[—argsLength — 1], args[argsLength—], 2);\n’ +
«} else if (argsLength > 2 && typeof args[argsLength — 1] == ‘function’) {\n» +
‘ callback = args[—argsLength];\n’ +
‘}’
),
‘loop’: ‘result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]’
});
/**
* Iterates over own and inherited enumerable properties of an object,
* executing the callback for each property. The callback is bound to `thisArg`
* and invoked with three arguments; (value, key, object). Callbacks may exit
* iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* Shape.prototype.move = function(x, y) {
* this.x += x;
* this.y += y;
* };
*
* _.forIn(new Shape, function(value, key) {
* console.log(key);
* });
* // => logs ‘x’, ‘y’, and ‘move’ (property order is not guaranteed across environments)
*/
var forIn = createIterator(eachIteratorOptions, forOwnIteratorOptions, {
‘useHas’: false
});
/**
* Iterates over own enumerable properties of an object, executing the callback
* for each property. The callback is bound to `thisArg` and invoked with three
* arguments; (value, key, object). Callbacks may exit iteration early by
* explicitly returning `false`.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* _.forOwn({ ‘0’: ‘zero’, ‘1’: ‘one’, ‘length’: 2 }, function(num, key) {
* console.log(key);
* });
* // => logs ‘0’, ‘1’, and ‘length’ (property order is not guaranteed across environments)
*/
var forOwn = createIterator(eachIteratorOptions, forOwnIteratorOptions);
/**
* Creates a sorted array of property names of all enumerable properties,
* own and inherited, of `object` that have function values.
*
* @static
* @memberOf _
* @alias methods
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns an array of property names that have function values.
* @example
*
* _.functions(_);
* // => [‘all’, ‘any’, ‘bind’, ‘bindAll’, ‘clone’, ‘compact’, ‘compose’, …]
*/
function functions(object) {
var result = [];
forIn(object, function(value, key) {
if (isFunction(value)) {
result.push(key);
}
});
return result.sort();
}
/**
* Checks if the specified property name exists as a direct property of `object`,
* instead of an inherited property.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @param {string} key The name of the property to check.
* @returns {boolean} Returns `true` if key is a direct property, else `false`.
* @example
*
* _.has({ ‘a’: 1, ‘b’: 2, ‘c’: 3 }, ‘b’);
* // => true
*/
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
/**
* Checks if `value` is a boolean value.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`.
* @example
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
value && typeof value == ‘object’ && toString.call(value) == boolClass || false;
}
/**
* Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
* length of `0` and objects with no own enumerable properties are considered
* «empty».
*
* @static
* @memberOf _
* @category Objects
* @param {Array|Object|string} value The value to inspect.
* @returns {boolean} Returns `true` if the `value` is empty, else `false`.
* @example
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({});
* // => true
*
* _.isEmpty(»);
* // => true
*/
function isEmpty(value) {
var result = true;
if (!value) {
return result;
}
var className = toString.call(value),
length = value.length;
if ((className == arrayClass || className == stringClass ||
(support.argsClass ? className == argsClass : isArguments(value))) ||
(className == objectClass && typeof length == ‘number’ && isFunction(value.splice))) {
return !length;
}
forOwn(value, function() {
return (result = false);
});
return result;
}
/**
* Checks if `value` is a function.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*/
function isFunction(value) {
return typeof value == ‘function’;
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return typeof value == ‘function’ && toString.call(value) == funcClass;
};
}
/**
* Checks if `value` is the language type of Object.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String(»)`)
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// http://code.google.com/p/v8/issues/detail?id=2291
return !!(value && objectTypes[typeof value]);
}
/**
* Checks if `value` is `NaN`.
*
* Note: This is not the same as native `isNaN` which will return `true` for
* `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// `NaN` as a primitive is the only value that is not equal to itself
// (perform the [[Class]] check first to avoid errors with some host objects in IE)
return isNumber(value) && value != +value;
}
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(undefined);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is a number.
*
* Note: `NaN` is considered a number. See http://es5.github.io/#x8.5.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a number, else `false`.
* @example
*
* _.isNumber(8.4 * 5);
* // => true
*/
function isNumber(value) {
return typeof value == ‘number’ ||
value && typeof value == ‘object’ && toString.call(value) == numberClass || false;
}
/**
* Checks if `value` is an object created by the `Object` constructor.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* _.isPlainObject(new Shape);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ ‘x’: 0, ‘y’: 0 });
* // => true
*/
var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) {
if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) {
return false;
}
var valueOf = value.valueOf,
objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
return objProto
? (value == objProto || getPrototypeOf(value) == objProto)
: shimIsPlainObject(value);
};
/**
* Checks if `value` is a string.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is a string, else `false`.
* @example
*
* _.isString(‘fred’);
* // => true
*/
function isString(value) {
return typeof value == ‘string’ ||
value && typeof value == ‘object’ && toString.call(value) == stringClass || false;
}
/**
* Checks if `value` is `undefined`.
*
* @static
* @memberOf _
* @category Objects
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*/
function isUndefined(value) {
return typeof value == ‘undefined’;
}
/**
* Recursively merges own enumerable properties of the source object(s), that
* don’t resolve to `undefined` into the destination object. Subsequent sources
* will overwrite property assignments of previous sources. If a callback is
* provided it will be executed to produce the merged values of the destination
* and source properties. If the callback returns `undefined` merging will
* be handled by the method instead. The callback is bound to `thisArg` and
* invoked with two arguments; (objectValue, sourceValue).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The destination object.
* @param {…Object} [source] The source objects.
* @param {Function} [callback] The function to customize merging properties.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the destination object.
* @example
*
* var names = {
* ‘characters’: [
* { ‘name’: ‘barney’ },
* { ‘name’: ‘fred’ }
* ]
* };
*
* var ages = {
* ‘characters’: [
* { ‘age’: 36 },
* { ‘age’: 40 }
* ]
* };
*
* _.merge(names, ages);
* // => { ‘characters’: [{ ‘name’: ‘barney’, ‘age’: 36 }, { ‘name’: ‘fred’, ‘age’: 40 }] }
*
* var food = {
* ‘fruits’: [‘apple’],
* ‘vegetables’: [‘beet’]
* };
*
* var otherFood = {
* ‘fruits’: [‘banana’],
* ‘vegetables’: [‘carrot’]
* };
*
* _.merge(food, otherFood, function(a, b) {
* return _.isArray(a) ? a.concat(b) : undefined;
* });
* // => { ‘fruits’: [‘apple’, ‘banana’], ‘vegetables’: [‘beet’, ‘carrot] }
*/
function merge(object) {
var args = arguments,
length = 2;
if (!isObject(object)) {
return object;
}
// allows working with `_.reduce` and `_.reduceRight` without using
// their `index` and `collection` arguments
if (typeof args[2] != ‘number’) {
length = args.length;
}
if (length > 3 && typeof args[length — 2] == ‘function’) {
var callback = baseCreateCallback(args[—length — 1], args[length—], 2);
} else if (length > 2 && typeof args[length — 1] == ‘function’) {
callback = args[—length];
}
var sources = slice(arguments, 1, length),
index = -1,
stackA = getArray(),
stackB = getArray();
while (++index < length) {
baseMerge(object, sources[index], callback, stackA, stackB);
}
releaseArray(stackA);
releaseArray(stackB);
return object;
}
/*--------------------------------------------------------------------------*/
/**
* Iterates over elements of a collection, returning an array of all elements
* the callback returns truey for. The callback is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias select
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of elements that passed the callback check.
* @example
*
* var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [2, 4, 6]
*
* var characters = [
* { ‘name’: ‘barney’, ‘age’: 36, ‘blocked’: false },
* { ‘name’: ‘fred’, ‘age’: 40, ‘blocked’: true }
* ];
*
* // using «_.pluck» callback shorthand
* _.filter(characters, ‘blocked’);
* // => [{ ‘name’: ‘fred’, ‘age’: 40, ‘blocked’: true }]
*
* // using «_.where» callback shorthand
* _.filter(characters, { ‘age’: 36 });
* // => [{ ‘name’: ‘barney’, ‘age’: 36, ‘blocked’: false }]
*/
function filter(collection, callback, thisArg) {
var result = [];
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (callback(value, index, collection)) {
result.push(value);
}
}
} else {
baseEach(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result.push(value);
}
});
}
return result;
}
/**
* Iterates over elements of a collection, returning the first element that
* the callback returns truey for. The callback is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias detect, findWhere
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the found element, else `undefined`.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'blocked': false },
* { 'name': 'fred', 'age': 40, 'blocked': true },
* { 'name': 'pebbles', 'age': 1, 'blocked': false }
* ];
*
* _.find(characters, function(chr) {
* return chr.age < 40;
* });
* // => { ‘name’: ‘barney’, ‘age’: 36, ‘blocked’: false }
*
* // using «_.where» callback shorthand
* _.find(characters, { ‘age’: 1 });
* // => { ‘name’: ‘pebbles’, ‘age’: 1, ‘blocked’: false }
*
* // using «_.pluck» callback shorthand
* _.find(characters, ‘blocked’);
* // => { ‘name’: ‘fred’, ‘age’: 40, ‘blocked’: true }
*/
function find(collection, callback, thisArg) {
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (callback(value, index, collection)) {
return value;
}
}
} else {
var result;
baseEach(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result = value;
return false;
}
});
return result;
}
}
/**
* Iterates over elements of a collection, executing the callback for each
* element. The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection). Callbacks may exit iteration early by
* explicitly returning `false`.
*
* Note: As with other "Collections" methods, objects with a `length` property
* are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
* may be used for object iteration.
*
* @static
* @memberOf _
* @alias each
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array|Object|string} Returns `collection`.
* @example
*
* _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(',');
* // => logs each number and returns ‘1,2,3’
*
* _.forEach({ ‘one’: 1, ‘two’: 2, ‘three’: 3 }, function(num) { console.log(num); });
* // => logs each number and returns the object (property order is not guaranteed across environments)
*/
function forEach(collection, callback, thisArg) {
if (callback && typeof thisArg == ‘undefined’ && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
if (callback(collection[index], index, collection) === false) {
break;
}
}
} else {
baseEach(collection, callback, thisArg);
}
return collection;
}
/**
* Creates an array of values by running each element in the collection
* through the callback. The callback is bound to `thisArg` and invoked with
* three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias collect
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of the results of each `callback` execution.
* @example
*
* _.map([1, 2, 3], function(num) { return num * 3; });
* // => [3, 6, 9]
*
* _.map({ ‘one’: 1, ‘two’: 2, ‘three’: 3 }, function(num) { return num * 3; });
* // => [3, 6, 9] (property order is not guaranteed across environments)
*
* var characters = [
* { ‘name’: ‘barney’, ‘age’: 36 },
* { ‘name’: ‘fred’, ‘age’: 40 }
* ];
*
* // using «_.pluck» callback shorthand
* _.map(characters, ‘name’);
* // => [‘barney’, ‘fred’]
*/
function map(collection, callback, thisArg) {
var index = -1,
length = collection ? collection.length : 0,
result = Array(typeof length == ‘number’ ? length : 0);
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
while (++index < length) {
result[index] = callback(collection[index], index, collection);
}
} else {
baseEach(collection, function(value, key, collection) {
result[++index] = callback(value, key, collection);
});
}
return result;
}
/**
* Retrieves the value of a specified property from all elements in the collection.
*
* @static
* @memberOf _
* @type Function
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {string} property The name of the property to pluck.
* @returns {Array} Returns a new array of property values.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 }
* ];
*
* _.pluck(characters, 'name');
* // => [‘barney’, ‘fred’]
*/
var pluck = map;
/**
* Reduces a collection to a value which is the accumulated result of running
* each element in the collection through the callback, where each successive
* callback execution consumes the return value of the previous execution. If
* `accumulator` is not provided the first element of the collection will be
* used as the initial `accumulator` value. The callback is bound to `thisArg`
* and invoked with four arguments; (accumulator, value, index|key, collection).
*
* @static
* @memberOf _
* @alias foldl, inject
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {*} [accumulator] Initial value of the accumulator.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {*} Returns the accumulated value.
* @example
*
* var sum = _.reduce([1, 2, 3], function(sum, num) {
* return sum + num;
* });
* // => 6
*
* var mapped = _.reduce({ ‘a’: 1, ‘b’: 2, ‘c’: 3 }, function(result, num, key) {
* result[key] = num * 3;
* return result;
* }, {});
* // => { ‘a’: 3, ‘b’: 6, ‘c’: 9 }
*/
function reduce(collection, callback, accumulator, thisArg) {
var noaccum = arguments.length < 3;
callback = lodash.createCallback(callback, thisArg, 4);
if (isArray(collection)) {
var index = -1,
length = collection.length;
if (noaccum) {
accumulator = collection[++index];
}
while (++index < length) {
accumulator = callback(accumulator, collection[index], index, collection);
}
} else {
baseEach(collection, function(value, index, collection) {
accumulator = noaccum
? (noaccum = false, value)
: callback(accumulator, value, index, collection)
});
}
return accumulator;
}
/**
* Checks if the callback returns a truey value for **any** element of a
* collection. The function returns as soon as it finds a passing value and
* does not iterate over the entire collection. The callback is bound to
* `thisArg` and invoked with three arguments; (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias any
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {boolean} Returns `true` if any element passed the callback check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var characters = [
* { ‘name’: ‘barney’, ‘age’: 36, ‘blocked’: false },
* { ‘name’: ‘fred’, ‘age’: 40, ‘blocked’: true }
* ];
*
* // using «_.pluck» callback shorthand
* _.some(characters, ‘blocked’);
* // => true
*
* // using «_.where» callback shorthand
* _.some(characters, { ‘age’: 1 });
* // => false
*/
function some(collection, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg, 3);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
if ((result = callback(collection[index], index, collection))) {
break;
}
}
} else {
baseEach(collection, function(value, index, collection) {
return !(result = callback(value, index, collection));
});
}
return !!result;
}
/**
* Performs a deep comparison of each element in a `collection` to the given
* `properties` object, returning an array of all elements that have equivalent
* property values.
*
* @static
* @memberOf _
* @type Function
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Object} props The object of property values to filter by.
* @returns {Array} Returns a new array of elements that have the given properties.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] },
* { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }
* ];
*
* _.where(characters, { 'age': 36 });
* // => [{ ‘name’: ‘barney’, ‘age’: 36, ‘pets’: [‘hoppy’] }]
*
* _.where(characters, { ‘pets’: [‘dino’] });
* // => [{ ‘name’: ‘fred’, ‘age’: 40, ‘pets’: [‘baby puss’, ‘dino’] }]
*/
var where = filter;
/*—————————————————————————*/
/**
* Creates an array excluding all values of the provided arrays using strict
* equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to process.
* @param {…Array} [values] The arrays of values to exclude.
* @returns {Array} Returns a new array of filtered values.
* @example
*
* _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
* // => [1, 3, 4]
*/
function difference(array) {
return baseDifference(array, baseFlatten(arguments, true, true, 1));
}
/**
* Gets the index at which the first occurrence of `value` is found using
* strict equality for comparisons, i.e. `===`. If the array is already sorted
* providing `true` for `fromIndex` will run a faster binary search.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {boolean|number} [fromIndex=0] The index to search from or `true`
* to perform a binary search on a sorted array.
* @returns {number} Returns the index of the matched value or `-1`.
* @example
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2);
* // => 1
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 4
*
* _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
* // => 2
*/
function indexOf(array, value, fromIndex) {
if (typeof fromIndex == ‘number’) {
var length = array ? array.length : 0;
fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0);
} else if (fromIndex) {
var index = sortedIndex(array, value);
return array[index] === value ? index : -1;
}
return baseIndexOf(array, value, fromIndex);
}
/**
* Removes all elements from an array that the callback returns truey for
* and returns an array of removed elements. The callback is bound to `thisArg`
* and invoked with three arguments; (value, index, array).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to modify.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4, 5, 6];
* var evens = _.remove(array, function(num) { return num % 2 == 0; });
*
* console.log(array);
* // => [1, 3, 5]
*
* console.log(evens);
* // => [2, 4, 6]
*/
function remove(array, callback, thisArg) {
var index = -1,
length = array ? array.length : 0,
result = [];
callback = lodash.createCallback(callback, thisArg, 3);
while (++index < length) {
var value = array[index];
if (callback(value, index, array)) {
result.push(value);
splice.call(array, index--, 1);
length--;
}
}
return result;
}
/**
* Uses a binary search to determine the smallest index at which a value
* should be inserted into a given sorted array in order to maintain the sort
* order of the array. If a callback is provided it will be executed for
* `value` and each element of `array` to compute their sort ranking. The
* callback is bound to `thisArg` and invoked with one argument; (value).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to inspect.
* @param {*} value The value to evaluate.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([20, 30, 50], 40);
* // => 2
*
* // using «_.pluck» callback shorthand
* _.sortedIndex([{ ‘x’: 20 }, { ‘x’: 30 }, { ‘x’: 50 }], { ‘x’: 40 }, ‘x’);
* // => 2
*
* var dict = {
* ‘wordToNumber’: { ‘twenty’: 20, ‘thirty’: 30, ‘fourty’: 40, ‘fifty’: 50 }
* };
*
* _.sortedIndex([‘twenty’, ‘thirty’, ‘fifty’], ‘fourty’, function(word) {
* return dict.wordToNumber[word];
* });
* // => 2
*
* _.sortedIndex([‘twenty’, ‘thirty’, ‘fifty’], ‘fourty’, function(word) {
* return this.wordToNumber[word];
* }, dict);
* // => 2
*/
function sortedIndex(array, value, callback, thisArg) {
var low = 0,
high = array ? array.length : low;
// explicitly reference `identity` for better inlining in Firefox
callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity;
value = callback(value);
while (low < high) {
var mid = (low + high) >>> 1;
(callback(array[mid]) < value)
? low = mid + 1
: high = mid;
}
return low;
}
/*--------------------------------------------------------------------------*/
/**
* Creates a function that, when called, invokes `func` with the `this`
* binding of `thisArg` and prepends any additional `bind` arguments to those
* provided to the bound function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to bind.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {...*} [arg] Arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var func = function(greeting) {
* return greeting + ' ' + this.name;
* };
*
* func = _.bind(func, { 'name': 'fred' }, 'hi');
* func();
* // => ‘hi fred’
*/
function bind(func, thisArg) {
return arguments.length > 2
? createWrapper(func, 17, slice(arguments, 2), null, thisArg)
: createWrapper(func, 1, null, null, thisArg);
}
/**
* Creates a function that is restricted to execute `func` once. Repeat calls to
* the function will return the value of the first call. The `func` is executed
* with the `this` binding of the created function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // `initialize` executes `createApplication` once
*/
function once(func) {
var ran,
result;
if (!isFunction(func)) {
throw new TypeError;
}
return function() {
if (ran) {
return result;
}
ran = true;
result = func.apply(this, arguments);
// clear the `func` variable so the function may be garbage collected
func = null;
return result;
};
}
/*—————————————————————————*/
/**
* Produces a callback bound to an optional `thisArg`. If `func` is a property
* name the created callback will return the property value for a given element.
* If `func` is an object the created callback will return `true` for elements
* that contain the equivalent object properties, otherwise it will return `false`.
*
* @static
* @memberOf _
* @category Utilities
* @param {*} [func=identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of the created callback.
* @param {number} [argCount] The number of arguments the callback accepts.
* @returns {Function} Returns a callback function.
* @example
*
* var characters = [
* { ‘name’: ‘barney’, ‘age’: 36 },
* { ‘name’: ‘fred’, ‘age’: 40 }
* ];
*
* // wrap to create custom callback shorthands
* _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
* var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
* return !match ? func(callback, thisArg) : function(object) {
* return match[2] == ‘gt’ ? object[match[1]] > match[3] : object[match[1]] < match[3];
* };
* });
*
* _.filter(characters, 'age__gt38');
* // => [{ ‘name’: ‘fred’, ‘age’: 40 }]
*/
function createCallback(func, thisArg, argCount) {
var type = typeof func;
if (func == null || type == ‘function’) {
return baseCreateCallback(func, thisArg, argCount);
}
// handle «_.pluck» style callback shorthands
if (type != ‘object’) {
return property(func);
}
var props = keys(func),
key = props[0],
a = func[key];
// handle «_.where» style callback shorthands
if (props.length == 1 && a === a && !isObject(a)) {
// fast path the common case of providing an object with a single
// property containing a primitive value
return function(object) {
var b = object[key];
return a === b && (a !== 0 || (1 / a == 1 / b));
};
}
return function(object) {
var length = props.length,
result = false;
while (length—) {
if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) {
break;
}
}
return result;
};
}
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utilities
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { ‘name’: ‘fred’ };
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
/**
* Adds function properties of a source object to the destination object.
* If `object` is a function methods will be added to its prototype as well.
*
* @static
* @memberOf _
* @category Utilities
* @param {Function|Object} [object=lodash] object The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options] The options object.
* @param {boolean} [options.chain=true] Specify whether the functions added are chainable.
* @example
*
* function capitalize(string) {
* return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
* }
*
* _.mixin({ ‘capitalize’: capitalize });
* _.capitalize(‘fred’);
* // => ‘Fred’
*
* _(‘fred’).capitalize().value();
* // => ‘Fred’
*
* _.mixin({ ‘capitalize’: capitalize }, { ‘chain’: false });
* _(‘fred’).capitalize();
* // => ‘Fred’
*/
function mixin(object, source, options) {
var chain = true,
methodNames = source && functions(source);
if (!source || (!options && !methodNames.length)) {
if (options == null) {
options = source;
}
ctor = lodashWrapper;
source = object;
object = lodash;
methodNames = functions(source);
}
if (options === false) {
chain = false;
} else if (isObject(options) && ‘chain’ in options) {
chain = options.chain;
}
var ctor = object,
isFunc = isFunction(ctor);
forEach(methodNames, function(methodName) {
var func = object[methodName] = source[methodName];
if (isFunc) {
ctor.prototype[methodName] = function() {
var chainAll = this.__chain__,
value = this.__wrapped__,
args = [value];
push.apply(args, arguments);
var result = func.apply(object, args);
if (chain || chainAll) {
if (value === result && isObject(result)) {
return this;
}
result = new ctor(result);
result.__chain__ = chainAll;
}
return result;
};
}
});
}
/**
* A no-operation function.
*
* @static
* @memberOf _
* @category Utilities
* @example
*
* var object = { ‘name’: ‘fred’ };
* _.noop(object) === undefined;
* // => true
*/
function noop() {
// no operation performed
}
/**
* Creates a «_.pluck» style function, which returns the `key` value of a
* given object.
*
* @static
* @memberOf _
* @category Utilities
* @param {string} key The name of the property to retrieve.
* @returns {Function} Returns the new function.
* @example
*
* var characters = [
* { ‘name’: ‘fred’, ‘age’: 40 },
* { ‘name’: ‘barney’, ‘age’: 36 }
* ];
*
* var getName = _.property(‘name’);
*
* _.map(characters, getName);
* // => [‘barney’, ‘fred’]
*
* _.sortBy(characters, getName);
* // => [{ ‘name’: ‘barney’, ‘age’: 36 }, { ‘name’: ‘fred’, ‘age’: 40 }]
*/
function property(key) {
return function(object) {
return object[key];
};
}
/**
* Executes the callback `n` times, returning an array of the results
* of each callback execution. The callback is bound to `thisArg` and invoked
* with one argument; (index).
*
* @static
* @memberOf _
* @category Utilities
* @param {number} n The number of times to execute the callback.
* @param {Function} callback The function called per iteration.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns an array of the results of each `callback` execution.
* @example
*
* var diceRolls = _.times(3, _.partial(_.random, 1, 6));
* // => [3, 6, 4]
*
* _.times(3, function(n) { mage.castSpell(n); });
* // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
*
* _.times(3, function(n) { this.cast(n); }, mage);
* // => also calls `mage.castSpell(n)` three times
*/
function times(n, callback, thisArg) {
n = (n = +n) > -1 ? n : 0;
var index = -1,
result = Array(n);
callback = baseCreateCallback(callback, thisArg, 1);
while (++index < n) {
result[index] = callback(index);
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Creates a `lodash` object that wraps the given value with explicit
* method chaining enabled.
*
* @static
* @memberOf _
* @category Chaining
* @param {*} value The value to wrap.
* @returns {Object} Returns the wrapper object.
* @example
*
* var characters = [
* { 'name': 'barney', 'age': 36 },
* { 'name': 'fred', 'age': 40 },
* { 'name': 'pebbles', 'age': 1 }
* ];
*
* var youngest = _.chain(characters)
* .sortBy('age')
* .map(function(chr) { return chr.name + ' is ' + chr.age; })
* .first()
* .value();
* // => ‘pebbles is 1’
*/
function chain(value) {
value = new lodashWrapper(value);
value.__chain__ = true;
return value;
}
/**
* Enables explicit method chaining on the wrapper object.
*
* @name chain
* @memberOf _
* @category Chaining
* @returns {*} Returns the wrapper object.
* @example
*
* var characters = [
* { ‘name’: ‘barney’, ‘age’: 36 },
* { ‘name’: ‘fred’, ‘age’: 40 }
* ];
*
* // without explicit chaining
* _(characters).first();
* // => { ‘name’: ‘barney’, ‘age’: 36 }
*
* // with explicit chaining
* _(characters).chain()
* .first()
* .pick(‘age’)
* .value();
* // => { ‘age’: 36 }
*/
function wrapperChain() {
this.__chain__ = true;
return this;
}
/**
* Produces the `toString` result of the wrapped value.
*
* @name toString
* @memberOf _
* @category Chaining
* @returns {string} Returns the string result.
* @example
*
* _([1, 2, 3]).toString();
* // => ‘1,2,3’
*/
function wrapperToString() {
return String(this.__wrapped__);
}
/**
* Extracts the wrapped value.
*
* @name valueOf
* @memberOf _
* @alias value
* @category Chaining
* @returns {*} Returns the wrapped value.
* @example
*
* _([1, 2, 3]).valueOf();
* // => [1, 2, 3]
*/
function wrapperValueOf() {
return this.__wrapped__;
}
/*—————————————————————————*/
lodash.assign = assign;
lodash.bind = bind;
lodash.chain = chain;
lodash.createCallback = createCallback;
lodash.difference = difference;
lodash.filter = filter;
lodash.forEach = forEach;
lodash.forIn = forIn;
lodash.forOwn = forOwn;
lodash.functions = functions;
lodash.keys = keys;
lodash.map = map;
lodash.merge = merge;
lodash.once = once;
lodash.pluck = pluck;
lodash.property = property;
lodash.remove = remove;
lodash.times = times;
lodash.where = where;
// add aliases
lodash.collect = map;
lodash.each = forEach;
lodash.extend = assign;
lodash.methods = functions;
lodash.select = filter;
// add functions to `lodash.prototype`
mixin(lodash);
/*—————————————————————————*/
lodash.find = find;
lodash.has = has;
lodash.identity = identity;
lodash.indexOf = indexOf;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isBoolean = isBoolean;
lodash.isEmpty = isEmpty;
lodash.isFunction = isFunction;
lodash.isNaN = isNaN;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isPlainObject = isPlainObject;
lodash.isString = isString;
lodash.isUndefined = isUndefined;
lodash.mixin = mixin;
lodash.noop = noop;
lodash.reduce = reduce;
lodash.some = some;
lodash.sortedIndex = sortedIndex;
lodash.any = some;
lodash.detect = find;
lodash.findWhere = find;
lodash.foldl = reduce;
lodash.inject = reduce;
mixin(function() {
var source = {}
forOwn(lodash, function(func, methodName) {
if (!lodash.prototype[methodName]) {
source[methodName] = func;
}
});
return source;
}(), false);
/*—————————————————————————*/
forOwn(lodash, function(func, methodName) {
var callbackable = methodName !== ‘sample’;
if (!lodash.prototype[methodName]) {
lodash.prototype[methodName]= function(n, guard) {
var chainAll = this.__chain__,
result = func(this.__wrapped__, n, guard);
return !chainAll && (n == null || (guard && !(callbackable && typeof n == ‘function’)))
? result
: new lodashWrapper(result, chainAll);
};
}
});
/*—————————————————————————*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type string
*/
lodash.VERSION = ‘2.4.1’;
// add «Chaining» functions to the wrapper
lodash.prototype.chain = wrapperChain;
lodash.prototype.toString = wrapperToString;
lodash.prototype.value = wrapperValueOf;
lodash.prototype.valueOf = wrapperValueOf;
// add `Array` functions that return unwrapped values
baseEach([‘join’, ‘pop’, ‘shift’], function(methodName) {
var func = arrayRef[methodName];
lodash.prototype[methodName] = function() {
var chainAll = this.__chain__,
result = func.apply(this.__wrapped__, arguments);
return chainAll
? new lodashWrapper(result, chainAll)
: result;
};
});
// add `Array` functions that return the existing wrapped value
baseEach([‘push’, ‘reverse’, ‘sort’, ‘unshift’], function(methodName) {
var func = arrayRef[methodName];
lodash.prototype[methodName] = function() {
func.apply(this.__wrapped__, arguments);
return this;
};
});
// add `Array` functions that return new wrapped values
baseEach([‘concat’, ‘slice’, ‘splice’], function(methodName) {
var func = arrayRef[methodName];
lodash.prototype[methodName] = function() {
return new lodashWrapper(func.apply(this.__wrapped__, arguments), this.__chain__);
};
});
// avoid array-like object bugs with `Array#shift` and `Array#splice`
// in IE < 9, Firefox < 10, Narwhal, and RingoJS
if (!support.spliceObjects) {
baseEach([‘pop’, ‘shift’, ‘splice’], function(methodName) {
var func = arrayRef[methodName],
isSplice = methodName == ‘splice’;
lodash.prototype[methodName] = function() {
var chainAll = this.__chain__,
value = this.__wrapped__,
result = func.apply(value, arguments);
if (value.length === 0) {
delete value[0];
}
return (chainAll || isSplice)
? new lodashWrapper(result, chainAll)
: result;
};
});
}
/*—————————————————————————*/
if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = lodash)._ = lodash;
}
}
}.call(this));
}).call(this,typeof self !== «undefined» ? self : typeof window !== «undefined» ? window : {})
},{}],»lodash»:[function(require,module,exports){
module.exports=require(‘7ZYSzK’);
},{}]},{},[87]);
return response;
});
Самсон 4 9 360 руб.
салатово -бежевый цвет, 11 500 — желто-сине-красный.
устанавливается враспор между полом и потолком
В случае обнаружения потребителем недостатков товара и предъявления требования о его замене товар подлежит замене в срок до семи дней, а при необходимости дополнительной проверки качества такого товара — в срок до двадцати дней. Если необходимый для замены товар отсутствует на складе, замена должна быть проведена в течение месяца.
Покупатель вправе отказаться от товара в любое время до его передачи, а после передачи товара — в течение 7 дней. Возврат товара надлежащего качества, если он не входит в перечень товаров, не подлежащих обмену, возможен в случае, если сохранены его товарный вид, потребительские свойства, а также документ, подтверждающий факт и условия покупки указанного товара.
Покупатель не вправе отказаться от товара надлежащего качества, имеющего индивидуально-определенные свойства, если указанный товар может быть использован исключительно приобретающим его потребителем.
При отказе покупателя от товара продавец возвращает сумму, уплаченную покупателем, за исключением расходов продавца на доставку товара, не позднее чем через 10 дней с даты предъявления покупателем соответствующего требования.
Romana Karusel — R33 11 170 руб.
с массажными ступенями, крепится враспор между полом и потолком. Возможные цвета: сине-желтый, зелено-желтый, красно-желтый, белый антик/золото-желтый.
Леда «Домик 3»
снят с производства6500*5250*4000(в) мм
Пик 159 000 руб.
Игровые элементы игровой площадки Пик:
Джорджия-2 44 000 руб. 49 000 руб.детский домик с игровыми элементами
1750 х 1270 х 1670 мм

Резиновая плитка
покрытие для площадки

Песок для песочницы
для детского сада

Канатная дорога
тарзанка zip line
Рид 174 000 руб.
Игровые элементы детской площадки:
Лидер Д1 24 500 руб.
с металлическими качелями на подшипниках
цвет — сине-желтый/зелено-желтый/красно-желтый
Рукоход 17 000 руб.
ДОПОЛНИТЕЛЬНАЯ КОМПЛЕКТАЦИЯ К ДЕТСКОЙ ПЛОЩАДКЕ САМСОН
Изготовлен из массива сосны толщиной 42 мм, метал. перекладины.
Размеры: высота 2200 мм, ширина 650 мм, длина 2800мм.
Изготовлено в России. Гарантия 12 месяцев.
Виндейл 89 000 руб. 99 000 руб.
Игровые элементы детской площадки:
Материал: дерево.
Размеры: длина 1200 мм, ширина 400 мм.
Максимальная нагрузка — 60 кг.
Изготовлены в России. Гарантия 12 месяцев.
Материал: дерево, покрытое лаком.
Размеры: диаметр 240 мм.
Изготовлены в России. Гарантия 12 месяцев.
Материал: хлопок.
Изготовлены в России. Гарантия 12 месяцев.
Материал: дерево, покрытое лаком. Размеры: 310 х 310 мм. Рекомендуем использовать с 2-х лет.
Изготовлены в России. Гарантия 12 месяцев.
Материал: прочное текстильное полотно, приятное на ощупь. Крепление — «карабины». Максимальная нагрузка — 20 кг.
Изготовлены в России. Гарантия 12 месяцев.
Диск-качели. Размеры: диаметр 200 мм, длина веревки -1700 мм.
Сделаны из дерева и полипропиленнового каната.
Рекомендуется использовать с 3-х лет.
Изготовлены в России. Гарантия 12 месяцев.
Деревянный скалодром. Размеры: 1400х550 мм.
Сделан издерева и гипса.
Изготовлены в России. Гарантия 12 месяцев.
Тканевая крыша (триколор) 1 100 руб.
Материал: ткань — Оксфорд плащевка (100% ПЭ с пропиткой)
(дополнительная комплектация к детским площадкам Самсон)
Верона 73 300 руб. с кольцами,
с качелями «Овал» — 78 600 руб., с качелями-шиной — 75 400 руб.
Комплектация игрового комплекса Верона:
Сан Ремо 73 600 руб. с кольцами,
с качелями-шиной — 75 700 руб., с качелями «Овал» — 78 900 руб.
Комплектация игрового комплекса Сан Ремо:
Римини 76 500 руб. с кольцами,
с качелями «Овал» — 81 900 руб., с качелями-шиной — 78 700 руб.
Комплектация игрового комплекса Римини:
Милано 71 100 руб. с кольцами,
с качелями-шиной — 73 200 руб., с качелями «Овал» — 76 500 руб.
Комплектация игрового комплекса Милано:
Комплектация металлического игрового комплекса для дачи:
Romana Kometa — 1 9 590 руб.
Предыдущая модель — 8990 руб. С массажными ступенями. Крепится враспор между полом и потолком. Возможные цвета: бело-желтый,красно-желтый, сине-желтый, зелено-желтый.
Карусель дачный скалодром 29 300 руб. Читать далее

Батут Trampoline 4,6 м 17 000 руб.
Допустимая нагрузка до 120/130 кг, цвет — синий
Комплектация: батут, защитная сетка, ножки (4/6 шт.)
Страна производства — Китай

Батут Perfetto Sport 2,1 м
14 500 руб.
Диаметр — 2100 мм, нагрузка до 100 кг, цвет — синий
Комплектация: батут, защитная сетка, мат, ножки (3 шт.)
Производитель — Perfetto Sport (Италия), страна производства — Тайвань.

Батут Мув & Фан 1,2 м 12 500 руб.
Диаметр — 1220 мм, нагрузка до 50 кг, цвет — сине-оранжевый
Комплектация: батут, чехол, сетка, защита стоек пенопреновая

Качели-балансир «Птички» 5 000 руб.
Песочница Росинка-Кубик 7 500 руб.
Размеры: 1400 х 1400 х 300 мм
Песочница Росинка-Ладушки 12 000 руб.
Размеры: 1400 х 1400 х 300 мм
Самсон 5
СНЯТ С ПРОИЗВОДСТВА
но хорошая новость, что еще очень много похожих вариантов в рубрике «Шведские стенки»
Самсон 2 7 600 руб.
устанавливается враспор между полом и потолком Читать далее
Самсон 1 6800 руб.
салатово-бежевый цвет, 8000 руб. — желто-сине-красный.
устанавливается враспор между полом и потолком
Самсон 52
СНЯТ С ПРОИЗВОДСТВА
но хорошая новость, что еще очень много похожих вариантов в рубрике «Шведские стенки»
Гренландия (без покрытия) 140 000 руб.
Гренландия (покрытие масло) 180 000 руб.
Гренландия (грунт акриловый) 195 000 руб.
Исландия (без покрытия) 86 000 руб.
Исландия (покрытие масло) 106 000 руб.
Исландия (грунт акриловый) 116 000 руб.
Урал (без покрытия) 45 000 руб.
Урал (покрытие масло) 53 000 руб.
Урал (грунт акриловый) 56 000 руб.
Ямал (без покрытия) 55 000 руб.
Ямал (покрытие масло) 68 000 руб.
Ямал (грунт акриловый) 73 000 руб.

Детская игровая комната Радость
220 690 руб.
Элементы детской игровой комнаты:

Спортивный комплекс с тележкой
19 450 руб.
Комплектация спортивного комплекса:

Сухой бассейн Большой прямоугольник 62 000 руб.
Размеры: 2800 х 2400 х 700 мм. Для данной модели необходимо 3500 шт. шариков (шарики в комплект не входят)

Сухой бассейн Океан 13 450 руб.
Размеры: 1500 х 1500 х 40 мм. Для данной модели необходимо 1000 шт. шариков (шарики в комплект не входят)

Спуск в бассейн Китенок 24 000 руб.
Размеры: 1250 х 500 х 500 мм. Материал: поролон, обшитый искусственной кожей. Состоит из ската со ступенями и двух боковых стенок.
Сухой бассейн круглый — от 4800 руб.

Сухой бассейн 6 элементов конструктора
8 000 руб.
Для данной модели необходимо 2000 шт. шариков (шарики в комплект не входят)
Детские качели-балансир-карусель
8 500 руб. 10 000 руб. Материал: гальванизированная сталь толщиной 1,2 мм с дополнительным защитным лаковым покрытием.
Качаться можно не только «вверх-вниз», но и по кругу, как на карусели.
Худора 64012 18 500 руб. Материал: гальванизированная сталь толщиной 1,5 мм с дополнительным защитным лаковым покрытием.
Пластмассовые подвесные качели, качалка для двоих детей, две лестницы для лазанья и 6 анкерных креплений для бетонирования.
Детский игровой спортивный комплекс
16 000 руб.
Материал: гальванизированная сталь толщиной 1,5 мм с дополнительным защитным лаковым покрытием.
Пластмассовые качели и качалка для двоих детей.
Детские качели одноместные 10 000 руб.
Материал: гальванизированная сталь толщиной 1,5 мм с дополнительным защитным лаковым покрытием. Пластмассовое сиденье и 4 анкерных крепления для бетонирования. Сделано в Германии.
Песочница №5 с крышкой 13 500 руб.
Крыша опускается и превращается в крышку.
Материал — сосна, покрытая антисептиком.
Размеры: 1500 х 1500 х 1850(в) мм, борт 300 мм.
Песочница грузовик 35 500 руб.Материал — сосна. Размеры: 2600 х 1500 х 1800(в) мм.
Крышка превращается в лавочки.
Песочница №10: цветная, с крышей и лавочками 20 500 руб. 23 000 руб.Материал — сосна, обработанная антисептиком.
Размеры: 1500 х 1500 х 1800(в) мм, борт 300 мм.
(навес над песочницей регулируется по высоте,
лавочки преобразуются в крышку)
Игровой центр 11-в-1 4500 х 3800 х 2300 мм
Песочница №3 со складными лавочками
13 500 руб.
Материал — сосна, покрытая антисептиком, цвет — натуральное дерево.
Размеры: 1500 х 1500 х 300 мм
Комплектация металлического игрового комплекса для дачи:
Комплектация металлического игрового комплекса для дачи:
Алтоп 143 100 руб. 182 000 руб.
Игровые элементы детской площадки:
Голденридж 152 100 руб. 169 000 руб.
В этот детский комплекс входит:
Кингсвуд 84 500 руб. 139 000 руб.
Игровой оборудования детского комплекса:
Составляющие игрового комплекса для детей:
Атлантис 85 000 руб. 108 000 руб.
Элементы детского игрового комплекса:
Брайтсайд 71 100 руб. 79 000 руб.
Игровые элементы детской площадки из Великобритании:
Провидэнс 42 500 руб. 59 000 руб.
Комплектация детской игровой площадки для малышей:
Задний двор 299 000 169 000 руб.
Комплектация уличной детской площадки из металла Задний двор:
Атлант 399 000 руб.
Игровое оборудование площадки для детей Атлант:
Маугли
Игровое оборудование детской площадки Маугли:
Рейнджер 3 189 000 руб.
Устройство детской площадки Рэйнджер 3:
Пикник 239 000 199 000 руб.
Комплектация детского комплекса Пикник:
Крепость свободы 2 239 000 руб.
Комплектация игрового городка Крепость свободы 2:
Крепость свободы 119 000 руб.
Оборудование детской игровой площадки Крепость свободы:
Зеленый замок нет в наличии
Комплектация детского игрового комплекса Зеленый замок:
Лучик нет в наличии
Комплектация детской игровой площадки Лучик:
Деревянная лестница с деревянными ступеньками.
Очень удобна для малышей из-за более широких ступеней).

Деревянная крыша 7 500 руб.
Поможет превратить игровой комплекс Самсон в детский домик.
Сделана из карельской сосны (каркас — многослойный клееный брус 85 мм, крыша — массив 18 мм), покрыта лаком акриловым на водной основе.
Размеры: 1600х1600х300 мм.
Изготовлено в России. Гарантия 12 месяцев.
снята с производства
смотрите Беседка Гоа
Детская деревянная беседка для дачи и частного дома «Бали» от российского производителя детских игровых комплексов «Самсон». Деревянные детские беседки Самсон имеют каркас, изготовленный из соснового многослойного клееного бруса 85 миллиметров, все ограждения и пол – из массива сосны 17 миллиметров. Монтаж беседки рекомендуется на ровной, свободной от насаждений территории; для более надежной фиксации закрепление конструкции производится с помощью анкеров любой формы.