code
stringlengths 2
1.05M
|
|---|
exp_poiimportante = {
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [{ "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12715",
"titolo": "Privato: mariateresa.bergoglio@parcodelpo-vcal.it", "url_post": "http://www.monferratopaesaggi.org/mariateresa-bergoglioparcodelpo-vcal-it/",
"tipo": "centro_storico", "wpid_comun": "", "comune": "Privato: mariateresa.bergoglio@parcodelpo-vcal.it",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/centro_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.307627081958344, 45.17054780129273 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12707",
"titolo": "Privato: biancaat@tiscali.it", "url_post": "http://www.monferratopaesaggi.org/biancaattiscali-it/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: biancaat@tiscali.it",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.307627081958344, 45.17054780129273 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12706",
"titolo": "Privato: silvanasicco@hotmail.it", "url_post": "http://www.monferratopaesaggi.org/silvanasiccohotmail-it-3/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: silvanasicco@hotmail.it",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.307627081958344, 45.17054780129273 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12705",
"titolo": "Privato: alvan68@yahoo.it", "url_post": "http://www.monferratopaesaggi.org/alvan68yahoo-it-4/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: alvan68@yahoo.it",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.307627081958344, 45.17054780129273 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12674",
"titolo": "Privato: alvan68@yahoo.it", "url_post": "http://www.monferratopaesaggi.org/alvan68yahoo-it-3/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: alvan68@yahoo.it",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.307627081958344, 45.17054780129273 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12673",
"titolo": "Privato: alvan68@yahoo.it", "url_post": "http://www.monferratopaesaggi.org/alvan68yahoo-it-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: alvan68@yahoo.it",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.307627081958344, 45.17054780129273 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12672",
"titolo": "Privato: alvan68@yahoo.it", "url_post": "http://www.monferratopaesaggi.org/alvan68yahoo-it/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: alvan68@yahoo.it",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.307627081958344, 45.17054780129273 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12658",
"titolo": "Privato: giuseppe.visconti@gmail.com", "url_post": "http://www.monferratopaesaggi.org/giuseppe-viscontigmail-com/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: giuseppe.visconti@gmail.com",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.307627081958344, 45.17054780129273 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12656",
"titolo": "Privato: guiboss@libero.it", "url_post": "http://www.monferratopaesaggi.org/guibosslibero-it/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: guiboss@libero.it",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.307627081958344, 45.17054780129273 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12623",
"titolo": "Museo Storico delle Truppe Alpine", "url_post": "http://www.monferratopaesaggi.org/museo-storico-delle-truppe-alpine/",
"tipo": "museo", "wpid_comun": "", "comune": "Museo Storico delle Truppe Alpine",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.217724999999973, 45.159023 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12614",
"titolo": "Privato: silvanasicco@hotmail.it", "url_post": "http://www.monferratopaesaggi.org/silvanasiccohotmail-it-2/",
"tipo": "puntooss", "wpid_comun": "", "comune": "Privato: silvanasicco@hotmail.it",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.290622234344482, 44.51120834330289 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12613",
"titolo": "Privato: silvanasicco@hotmail.it", "url_post": "http://www.monferratopaesaggi.org/silvanasiccohotmail-it/",
"tipo": "interesse_paesaggistico", "wpid_comun": "", "comune": "Privato: silvanasicco@hotmail.it",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/interesse_paesaggistico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.315448760986328, 44.49760732471434 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12612",
"titolo": "Privato: roberto1510@gmail.com", "url_post": "http://www.monferratopaesaggi.org/roberto1510gmail-com/",
"tipo": "edstorico", "wpid_comun": "", "comune": "Privato: roberto1510@gmail.com",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.351849019527435, 44.99442665865936 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12311",
"titolo": "Infernot via Fucina", "url_post": "http://www.monferratopaesaggi.org/infernot-via-fucina/",
"tipo": "infernot", "wpid_comun": "", "comune": "Infernot via Fucina",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.160454630851746, 45.15466989273043 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12308",
"titolo": "Infernot Cascina Marole", "url_post": "http://www.monferratopaesaggi.org/infernot-cascina-marole/",
"tipo": "infernot", "wpid_comun": "", "comune": "Infernot Cascina Marole",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.238404989242554, 45.09685205276264 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "12151",
"titolo": "Privato: amministrazione@ilcastellodiuviglie.com", "url_post": "http://www.monferratopaesaggi.org/amministrazioneilcastellodiuviglie-com/",
"tipo": "edstorico", "wpid_comun": "", "comune": "Privato: amministrazione@ilcastellodiuviglie.com",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.40978741645813, 45.0745964868116 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11774",
"titolo": "Privato: info@verdeabitare.it", "url_post": "http://www.monferratopaesaggi.org/infoverdeabitare-it/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: info@verdeabitare.it",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11773",
"titolo": "Privato: angelini.4@libero.it", "url_post": "http://www.monferratopaesaggi.org/angelini-4libero-it/",
"tipo": "edreligioso", "wpid_comun": "", "comune": "Privato: angelini.4@libero.it",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.121278285816515, 45.12072737093091 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11747",
"titolo": "Privato: Corteranzo", "url_post": "http://www.monferratopaesaggi.org/corteranzo/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Corteranzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11746",
"titolo": "Privato: Pieve romanica", "url_post": "http://www.monferratopaesaggi.org/pieve-romanica/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Pieve romanica",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.331067, 44.976933 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11745",
"titolo": "Privato: Cimitero Gabiano", "url_post": "http://www.monferratopaesaggi.org/cimitero-gabiano/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Cimitero Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11744",
"titolo": "Privato: La canna domestica (Arundo Donax)", "url_post": "http://www.monferratopaesaggi.org/la-canna-domestica-arundo-donax/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: La canna domestica (Arundo Donax)",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11743",
"titolo": "Privato: alcune foto nelle Langhe domenica mattina", "url_post": "http://www.monferratopaesaggi.org/alcune-foto-nelle-langhe-domenica-mattina-4/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: alcune foto nelle Langhe domenica mattina",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11742",
"titolo": "Privato: alcune foto nelle Langhe domenica mattina", "url_post": "http://www.monferratopaesaggi.org/alcune-foto-nelle-langhe-domenica-mattina-3/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: alcune foto nelle Langhe domenica mattina",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11741",
"titolo": "Privato: alcune foto nelle Langhe domenica mattina", "url_post": "http://www.monferratopaesaggi.org/alcune-foto-nelle-langhe-domenica-mattina-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: alcune foto nelle Langhe domenica mattina",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11740",
"titolo": "Privato: alcune foto nelle Langhe domenica mattina", "url_post": "http://www.monferratopaesaggi.org/alcune-foto-nelle-langhe-domenica-mattina/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: alcune foto nelle Langhe domenica mattina",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11738",
"titolo": "Privato: Sunset. Snow in the wineyard – Neve sulla vigna al tramonto", "url_post": "http://www.monferratopaesaggi.org/sunset-snow-in-the-wineyard-neve-sulla-vigna-al-tramonto/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Sunset. Snow in the wineyard – Neve sulla vigna al tramonto",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.341242, 45.011072 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11451",
"titolo": "Privato: lima.cityplanner@gmail.com", "url_post": "http://www.monferratopaesaggi.org/lima-cityplannergmail-com-2/",
"tipo": "none", "wpid_comun": "0", "comune": "Privato: lima.cityplanner@gmail.com",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 7.723114371474367, 44.549580912327016 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11429",
"titolo": "Infernot via Roma, 61", "url_post": "http://www.monferratopaesaggi.org/infernot-via-roma-61/",
"tipo": "infernot", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.250850439071655, 45.13283044839087 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11425",
"titolo": "Infernot via Roma, 87", "url_post": "http://www.monferratopaesaggi.org/infernot-via-roma/",
"tipo": "infernot", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.251832127571106, 45.133678150436474 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11422",
"titolo": "Infernot via Mameli", "url_post": "http://www.monferratopaesaggi.org/infernot-via-mameli/",
"tipo": "infernot", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.31839919090271, 45.03830845554792 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11420",
"titolo": "Infernot via Santa Lucia", "url_post": "http://www.monferratopaesaggi.org/infernot-via-santa-lucia/",
"tipo": "infernot", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.19205105304718, 45.12901563325583 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11412",
"titolo": "Cimitero di Moncestino", "url_post": "http://www.monferratopaesaggi.org/cimitero-di-moncestino/",
"tipo": "edreligioso", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.151769638061523, 45.15374835552467 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11399",
"titolo": "Infernot via XX settembre", "url_post": "http://www.monferratopaesaggi.org/infernot-via-xx-settembre/",
"tipo": "infernot", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.386366367340088, 45.03234540626007 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11397",
"titolo": "Infernot via alla Chiesa", "url_post": "http://www.monferratopaesaggi.org/infernot-via-alla-chiesa/",
"tipo": "infernot", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.197394990490693, 45.12349558880949 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11395",
"titolo": "Infernot via Barbano, 10", "url_post": "http://www.monferratopaesaggi.org/infernot-via-barbano-10/",
"tipo": "infernot", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.39232623577118, 45.07426690597466 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11391",
"titolo": "Infernot via Cei, 18", "url_post": "http://www.monferratopaesaggi.org/infernot-via-cei-18/",
"tipo": "infernot", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.38283121585846, 45.081466109773935 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11383",
"titolo": "Infernot piazza Vallino, 1", "url_post": "http://www.monferratopaesaggi.org/infernot-piazza-vallino/",
"tipo": "infernot", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.391551077365875, 45.074598380948835 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11378",
"titolo": "Infernot via Barbano, 38", "url_post": "http://www.monferratopaesaggi.org/infernot-via-barbano-38/",
"tipo": "infernot", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.389129042625427, 45.07572916967901 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11352",
"titolo": "Privato: maxcarcione@email.it", "url_post": "http://www.monferratopaesaggi.org/maxcarcioneemail-it/",
"tipo": "none", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.389129042625427, 45.07572916967901 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11344",
"titolo": "Privato: Presso Piscina Villanova", "url_post": "http://www.monferratopaesaggi.org/presso-piscina-villanova/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Presso Piscina Villanova",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11343",
"titolo": "Privato: Ecco la neve", "url_post": "http://www.monferratopaesaggi.org/ecco-la-neve-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Ecco la neve",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11342",
"titolo": "Privato: Ecco la neve", "url_post": "http://www.monferratopaesaggi.org/ecco-la-neve/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Ecco la neve",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11341",
"titolo": "Privato: Alba su Vignale", "url_post": "http://www.monferratopaesaggi.org/alba-su-vignale/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Alba su Vignale",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11340",
"titolo": "Privato: Prime colline dall’abitato di Casale Monferrato", "url_post": "http://www.monferratopaesaggi.org/prime-colline-dallabitato-di-casale-monferrato/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Prime colline dall’abitato di Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11339",
"titolo": "Privato: Centro storico di Moncalvo", "url_post": "http://www.monferratopaesaggi.org/centro-storico-di-moncalvo/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Centro storico di Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11317",
"titolo": "Privato: Alba da Vignale verso il mare", "url_post": "http://www.monferratopaesaggi.org/alba-da-vignale-verso-il-mare/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Alba da Vignale verso il mare",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11316",
"titolo": "Privato: Due foto invernali…. (quando nevicava)", "url_post": "http://www.monferratopaesaggi.org/due-foto-invernali-quando-nevicava-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Due foto invernali…. (quando nevicava)",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11315",
"titolo": "Privato: Due foto invernali…. (quando nevicava)", "url_post": "http://www.monferratopaesaggi.org/due-foto-invernali-quando-nevicava/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Due foto invernali…. (quando nevicava)",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11314",
"titolo": "Privato: Cereseto e dintorni", "url_post": "http://www.monferratopaesaggi.org/cereseto-e-dintorni/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Cereseto e dintorni",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11313",
"titolo": "Privato: Edmond Bircaj si trova qui: Moncalvo", "url_post": "http://www.monferratopaesaggi.org/edmond-bircaj-si-trova-qui-moncalvo/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Edmond Bircaj si trova qui: Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11296",
"titolo": "Privato: presso San Giorgio Monferrato", "url_post": "http://www.monferratopaesaggi.org/presso-san-giorgio-monferrato/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: presso San Giorgio Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11294",
"titolo": "Privato: mariateresa.bergoglio@parcodelpo-vcal.it", "url_post": "http://www.monferratopaesaggi.org/mariateresa-bergoglioparcodelpo-vcal-it-5/",
"tipo": "interesse_paesaggistico", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/interesse_paesaggistico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.345968008106865, 45.13967830978009 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11293",
"titolo": "Privato: mariateresa.bergoglio@parcodelpo-vcal.it", "url_post": "http://www.monferratopaesaggi.org/mariateresa-bergoglioparcodelpo-vcal-it-4/",
"tipo": "interesse_paesaggistico", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/interesse_paesaggistico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.431335210734687, 45.13933495232029 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11286",
"titolo": "Privato: Presso Montalero", "url_post": "http://www.monferratopaesaggi.org/presso-montalero-3/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Presso Montalero",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11285",
"titolo": "Privato: Presso Montalero", "url_post": "http://www.monferratopaesaggi.org/presso-montalero-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Presso Montalero",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11284",
"titolo": "Privato: Presso Montalero", "url_post": "http://www.monferratopaesaggi.org/presso-montalero/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Presso Montalero",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11279",
"titolo": "Privato: Rocca a Odalengo Grande", "url_post": "http://www.monferratopaesaggi.org/rocca-a-odalengo-grande/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Rocca a Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11270",
"titolo": "Privato: nebbia e neve tra Vignale e Casorzo", "url_post": "http://www.monferratopaesaggi.org/nebbia-e-neve-tra-vignale-e-casorzo-3/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: nebbia e neve tra Vignale e Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11269",
"titolo": "Privato: nebbia e neve tra Vignale e Casorzo", "url_post": "http://www.monferratopaesaggi.org/nebbia-e-neve-tra-vignale-e-casorzo-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: nebbia e neve tra Vignale e Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11268",
"titolo": "Privato: nebbia e neve tra Vignale e Casorzo", "url_post": "http://www.monferratopaesaggi.org/nebbia-e-neve-tra-vignale-e-casorzo/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: nebbia e neve tra Vignale e Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11267",
"titolo": "Privato: questo segnale stradale andrebbe bene?", "url_post": "http://www.monferratopaesaggi.org/questo-segnale-stradale-andrebbe-bene/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: questo segnale stradale andrebbe bene?",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11266",
"titolo": "Privato: Manca qualcosa?", "url_post": "http://www.monferratopaesaggi.org/manca-qualcosa/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Manca qualcosa?",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11135",
"titolo": "Privato: La prima neve in Monferrato", "url_post": "http://www.monferratopaesaggi.org/la-prima-neve-in-monferrato/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: La prima neve in Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11120",
"titolo": "Privato: Onde verdi", "url_post": "http://www.monferratopaesaggi.org/edmondbircajgmail-com-18/",
"tipo": "puntooss", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.382922410964966, 45.13934683397255 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11112",
"titolo": "Privato: Risaie Monferrato", "url_post": "http://www.monferratopaesaggi.org/risaie-monferrato-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Risaie Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11111",
"titolo": "Privato: Monferrato", "url_post": "http://www.monferratopaesaggi.org/monferrato-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11110",
"titolo": "Privato: Monferrato", "url_post": "http://www.monferratopaesaggi.org/monferrato/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11109",
"titolo": "Privato: Casale", "url_post": "http://www.monferratopaesaggi.org/casale-3/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.446649014949799, 45.14320068717176 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11108",
"titolo": "Privato: Casale", "url_post": "http://www.monferratopaesaggi.org/casale-2/",
"tipo": "puntooss", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.447821140289307, 45.14033822806712 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11107",
"titolo": "Privato: Casale", "url_post": "http://www.monferratopaesaggi.org/casale/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45259815454483, 45.13637822452563 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11106",
"titolo": "Privato: Lungo il Po’", "url_post": "http://www.monferratopaesaggi.org/lungo-il-po-3/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Lungo il Po’",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11105",
"titolo": "Privato: Lungo il Po’", "url_post": "http://www.monferratopaesaggi.org/lungo-il-po-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Lungo il Po’",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11104",
"titolo": "Privato: Lungo Po’", "url_post": "http://www.monferratopaesaggi.org/lungo-po-3/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Lungo Po’",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11103",
"titolo": "Privato: Lungo il Po’", "url_post": "http://www.monferratopaesaggi.org/lungo-il-po/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Lungo il Po’",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11102",
"titolo": "Privato: Quarti di Pontestura", "url_post": "http://www.monferratopaesaggi.org/quarti-di-pontestura-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Quarti di Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11101",
"titolo": "Privato: Il Po’", "url_post": "http://www.monferratopaesaggi.org/il-po-3/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Il Po’",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11100",
"titolo": "Privato: Terrugia", "url_post": "http://www.monferratopaesaggi.org/terrugia/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Terrugia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11099",
"titolo": "Privato: Il Po’", "url_post": "http://www.monferratopaesaggi.org/il-po-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Il Po’",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11098",
"titolo": "Privato: Piazza castello", "url_post": "http://www.monferratopaesaggi.org/piazza-castello/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.447381258010864, 45.13733372116971 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11097",
"titolo": "Privato: Lungo Po", "url_post": "http://www.monferratopaesaggi.org/lungo-po-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Lungo Po",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11095",
"titolo": "Privato: Quarti di pontestura", "url_post": "http://www.monferratopaesaggi.org/quarti-di-pontestura/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Quarti di pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11094",
"titolo": "Privato: Il ponte", "url_post": "http://www.monferratopaesaggi.org/il-ponte/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.446651697158813, 45.14323284881714 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11092",
"titolo": "Privato: San Martino", "url_post": "http://www.monferratopaesaggi.org/san-martino-4/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: San Martino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11091",
"titolo": "Privato: San Martino", "url_post": "http://www.monferratopaesaggi.org/san-martino-3/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: San Martino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11090",
"titolo": "Privato: San Martino", "url_post": "http://www.monferratopaesaggi.org/san-martino-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: San Martino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11088",
"titolo": "Privato: San germano", "url_post": "http://www.monferratopaesaggi.org/san-germano/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: San germano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11087",
"titolo": "Privato: Il profilo di Varengo", "url_post": "http://www.monferratopaesaggi.org/il-profilo-di-varengo/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Il profilo di Varengo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11086",
"titolo": "Privato: La chiesa di Pozzengo all’alba", "url_post": "http://www.monferratopaesaggi.org/la-chiesa-di-pozzengo-allalba/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: La chiesa di Pozzengo all’alba",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11085",
"titolo": "Privato: Alto Monferrato – immagini dicembrine", "url_post": "http://www.monferratopaesaggi.org/alto-monferrato-immagini-dicembrine-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Alto Monferrato – immagini dicembrine",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11084",
"titolo": "Privato: Alto Monferrato – immagini dicembrine", "url_post": "http://www.monferratopaesaggi.org/alto-monferrato-immagini-dicembrine/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Alto Monferrato – immagini dicembrine",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11083",
"titolo": "primo inverno in Monferrato in attesa della neve", "url_post": "http://www.monferratopaesaggi.org/primo-inverno-in-monferrato-in-attesa-della-neve-3/",
"tipo": "puntooss", "wpid_comun": "", "comune": "primo inverno in Monferrato in attesa della neve",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11082",
"titolo": "Privato: primo inverno in Monferrato in attesa della neve", "url_post": "http://www.monferratopaesaggi.org/primo-inverno-in-monferrato-in-attesa-della-neve-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: primo inverno in Monferrato in attesa della neve",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11081",
"titolo": "Privato: primo inverno in Monferrato in attesa della neve", "url_post": "http://www.monferratopaesaggi.org/primo-inverno-in-monferrato-in-attesa-della-neve/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: primo inverno in Monferrato in attesa della neve",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11080",
"titolo": "Passeggiata tra Cuccaro e Lu", "url_post": "http://www.monferratopaesaggi.org/passeggiata-tra-cuccaro-e-lu-2/",
"tipo": "puntooss", "wpid_comun": "", "comune": "Passeggiata tra Cuccaro e Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11079",
"titolo": "Privato: San Giorgio", "url_post": "http://www.monferratopaesaggi.org/san-giorgio/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: San Giorgio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11078",
"titolo": "Privato: Vignale al tramonto visto", "url_post": "http://www.monferratopaesaggi.org/vignale-al-tramonto-visto/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Vignale al tramonto visto",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11077",
"titolo": "Privato: Paesaggio Monferrino", "url_post": "http://www.monferratopaesaggi.org/paesaggio-monferrino/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Paesaggio Monferrino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11076",
"titolo": "Privato: Presso Varengo", "url_post": "http://www.monferratopaesaggi.org/presso-varengo/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Presso Varengo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11075",
"titolo": "Privato: Orizzonte al tramonto con Monviso", "url_post": "http://www.monferratopaesaggi.org/orizzonte-al-tramonto-con-monviso/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Orizzonte al tramonto con Monviso",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11074",
"titolo": "Privato: Uno splendido gennaio!", "url_post": "http://www.monferratopaesaggi.org/uno-splendido-gennaio/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Uno splendido gennaio!",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11073",
"titolo": "Privato: Colori del Monferrato", "url_post": "http://www.monferratopaesaggi.org/colori-del-monferrato-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Colori del Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11072",
"titolo": "Privato: Colori del Monferrato", "url_post": "http://www.monferratopaesaggi.org/colori-del-monferrato/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Colori del Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11071",
"titolo": "Valle Ghenza", "url_post": "http://www.monferratopaesaggi.org/valle-ghenza/",
"tipo": "none", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.39947, 45.07963 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11070",
"titolo": "Privato: Vendemmiando in Monferrato: una rossa rosa, vicino, appresso molto…", "url_post": "http://www.monferratopaesaggi.org/vendemmiando-in-monferrato-una-rossa-rosa-vicino-appresso-molto/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Vendemmiando in Monferrato: una rossa rosa, vicino, appresso molto…",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11068",
"titolo": "Privato: Mattino colline di Cavagnolo", "url_post": "http://www.monferratopaesaggi.org/mattino-colline-di-cavagnolo/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Mattino colline di Cavagnolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11067",
"titolo": "Welcome to winter season", "url_post": "http://www.monferratopaesaggi.org/welcome-to-winter-season/",
"tipo": "none", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.28225, 45.16083 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11066",
"titolo": "Privato: Cella Monte al tramonto", "url_post": "http://www.monferratopaesaggi.org/cella-monte-al-tramonto/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Cella Monte al tramonto",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11065",
"titolo": "Riflessi nel lago del castello di Gabiano", "url_post": "http://www.monferratopaesaggi.org/riflessi-nel-lago-del-castello-di-gabiano/",
"tipo": "puntooss", "wpid_comun": "", "comune": "Riflessi nel lago del castello di Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.183341802655036, 45.154523124062585 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11064",
"titolo": "Privato: Castello di Cereseto", "url_post": "http://www.monferratopaesaggi.org/castello-di-cereseto/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Castello di Cereseto",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11063",
"titolo": "Privato: ONDE VERSO IL BORGO", "url_post": "http://www.monferratopaesaggi.org/onde-verso-il-borgo/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: ONDE VERSO IL BORGO",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11062",
"titolo": "Privato: PATCHWORK", "url_post": "http://www.monferratopaesaggi.org/patchwork/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: PATCHWORK",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11061",
"titolo": "Privato: Lei che non sta ferma mai", "url_post": "http://www.monferratopaesaggi.org/lei-che-non-sta-ferma-mai/",
"tipo": "none", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.4961, 45.0767 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11060",
"titolo": "Privato: I colori del Barbera", "url_post": "http://www.monferratopaesaggi.org/i-colori-del-barbera/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: I colori del Barbera",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11059",
"titolo": "Privato: Rosignano Monferrato", "url_post": "http://www.monferratopaesaggi.org/rosignano-monferrato/",
"tipo": "none", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.410279, 45.075806 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11058",
"titolo": "Nuove prospettive", "url_post": "http://www.monferratopaesaggi.org/nuove-prospettive-3/",
"tipo": "centro_storico", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/centro_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.450704514980316, 45.13812648742042 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11057",
"titolo": "Privato: Nuove prospettive", "url_post": "http://www.monferratopaesaggi.org/nuove-prospettive-2/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448454141616821, 45.137469949090146 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11056",
"titolo": "Nuove prospettive", "url_post": "http://www.monferratopaesaggi.org/nuove-prospettive/",
"tipo": "centro_storico", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/centro_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448430001735687, 45.137464272933286 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11055",
"titolo": "Privato: RIENTRO", "url_post": "http://www.monferratopaesaggi.org/rientro/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448430001735687, 45.137464272933286 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11054",
"titolo": "Privato: LUCI ED OMBRE (bosco di Treville)", "url_post": "http://www.monferratopaesaggi.org/luci-ed-ombre-bosco-di-treville/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448430001735687, 45.137464272933286 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11053",
"titolo": "Privato: Monviso al tramonto", "url_post": "http://www.monferratopaesaggi.org/monviso-al-tramonto/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448430001735687, 45.137464272933286 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11052",
"titolo": "Privato: Coniolo e le Alpi", "url_post": "http://www.monferratopaesaggi.org/coniolo-e-le-alpi/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448430001735687, 45.137464272933286 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11051",
"titolo": "Privato: Uno sguardo alle Alpi dalle colline dietro San Giorgio Monferrato", "url_post": "http://www.monferratopaesaggi.org/uno-sguardo-alle-alpi-dalle-colline-dietro-san-giorgio-monferrato/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448430001735687, 45.137464272933286 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11050",
"titolo": "Privato: Vista su Pontestura e fiume Po da Rocchetta", "url_post": "http://www.monferratopaesaggi.org/vista-su-pontestura-e-fiume-po-da-rocchetta/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448430001735687, 45.137464272933286 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11049",
"titolo": "Privato: TAVOLOZZA OZZANESE", "url_post": "http://www.monferratopaesaggi.org/tavolozza-ozzanese/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448430001735687, 45.137464272933286 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11048",
"titolo": "Privato: Sfondo panoramico", "url_post": "http://www.monferratopaesaggi.org/sfondo-panoramico/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448430001735687, 45.137464272933286 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11046",
"titolo": "Privato: Autunno è iniziato in Valcerrina", "url_post": "http://www.monferratopaesaggi.org/lautunno-e-iniziato-in-valcerrina/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Autunno è iniziato in Valcerrina",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11041",
"titolo": "Privato: Panorama", "url_post": "http://www.monferratopaesaggi.org/panorama/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Panorama",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11039",
"titolo": "Chiesa di San Bononio", "url_post": "http://www.monferratopaesaggi.org/chiesa-di-san-bononio/",
"tipo": "none", "wpid_comun": "", "comune": "Chiesa di San Bononio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11022",
"titolo": "Archivio Ass. Culturale C’era una volta e Davide Giovinazzo", "url_post": "http://www.monferratopaesaggi.org/archivio-ass-culturale-cera-una-volta-e-davide-giovinazzo-5/",
"tipo": "edreligioso", "wpid_comun": "", "comune": "Archivio Ass. Culturale C’era una volta e Davide Giovinazzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11023",
"titolo": "Privato: Archivio Ass. Culturale C’era una volta e Davide Giovinazzo", "url_post": "http://www.monferratopaesaggi.org/archivio-ass-culturale-cera-una-volta-e-davide-giovinazzo-4/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Archivio Ass. Culturale C’era una volta e Davide Giovinazzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11024",
"titolo": "Privato: Archivio Ass. Culturale C’era una volta e Davide Giovinazzo", "url_post": "http://www.monferratopaesaggi.org/archivio-ass-culturale-cera-una-volta-e-davide-giovinazzo-3/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Archivio Ass. Culturale C’era una volta e Davide Giovinazzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11025",
"titolo": "Privato: Archivio Ass. Culturale C’era una volta e Davide Giovinazzo", "url_post": "http://www.monferratopaesaggi.org/archivio-ass-culturale-cera-una-volta-e-davide-giovinazzo-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Archivio Ass. Culturale C’era una volta e Davide Giovinazzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11026",
"titolo": "Privato: Archivio Ass. Culturale C’era una volta e Davide Giovinazzo", "url_post": "http://www.monferratopaesaggi.org/archivio-ass-culturale-cera-una-volta-e-davide-giovinazzo/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Archivio Ass. Culturale C’era una volta e Davide Giovinazzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11016",
"titolo": "Privato: azienda agricola nazzari franco", "url_post": "http://www.monferratopaesaggi.org/azienda-agricola-nazzari-franco-5/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: azienda agricola nazzari franco",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11015",
"titolo": "Privato: azienda agricola nazzari franco", "url_post": "http://www.monferratopaesaggi.org/azienda-agricola-nazzari-franco-4/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: azienda agricola nazzari franco",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11014",
"titolo": "Privato: azienda agricola nazzari franco", "url_post": "http://www.monferratopaesaggi.org/azienda-agricola-nazzari-franco-3/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: azienda agricola nazzari franco",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11013",
"titolo": "Privato: azienda agricola nazzari franco", "url_post": "http://www.monferratopaesaggi.org/azienda-agricola-nazzari-franco-2/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: azienda agricola nazzari franco",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11012",
"titolo": "Privato: Azienda agricola nazzari franco", "url_post": "http://www.monferratopaesaggi.org/azienda-agricola-nazzari-franco/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: Azienda agricola nazzari franco",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11010",
"titolo": "Privato: MANUTENZIONE", "url_post": "http://www.monferratopaesaggi.org/manutenzione/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: MANUTENZIONE",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11004",
"titolo": "Privato: edmondbircaj@gmail.com", "url_post": "http://www.monferratopaesaggi.org/edmondbircajgmail-com-17/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: edmondbircaj@gmail.com",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11003",
"titolo": "Privato: edmondbircaj@gmail.com", "url_post": "http://www.monferratopaesaggi.org/edmondbircajgmail-com-16/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: edmondbircaj@gmail.com",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "11001",
"titolo": "Colline", "url_post": "http://www.monferratopaesaggi.org/colline-vialarda/",
"tipo": "puntooss", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.361475467681885, 45.13833650240866 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10996",
"titolo": "Guardo verso le montagne", "url_post": "http://www.monferratopaesaggi.org/guardo-verso-le-montagne/",
"tipo": "puntooss", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.361728666641284, 45.13837661366091 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10994",
"titolo": "Privato: edmondbircaj@gmail.com", "url_post": "http://www.monferratopaesaggi.org/edmondbircajgmail-com-12/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.361728666641284, 45.13837661366091 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10993",
"titolo": "Privato: edmondbircaj@gmail.com", "url_post": "http://www.monferratopaesaggi.org/edmondbircajgmail-com-11/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.361728666641284, 45.13837661366091 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10992",
"titolo": "Privato: edmondbircaj@gmail.com", "url_post": "http://www.monferratopaesaggi.org/edmondbircajgmail-com-10/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.361728666641284, 45.13837661366091 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10991",
"titolo": "Privato: edmondbircaj@gmail.com", "url_post": "http://www.monferratopaesaggi.org/edmondbircajgmail-com-9/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.361728666641284, 45.13837661366091 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10989",
"titolo": "Privato: edndbircaj@gmail.com", "url_post": "http://www.monferratopaesaggi.org/edndbircajgmail-com/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.361728666641284, 45.13837661366091 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10936",
"titolo": "Privato: edmondbircaj@gmail.com", "url_post": "http://www.monferratopaesaggi.org/edmondbircajgmail-com-6/",
"tipo": "none", "wpid_comun": "", "comune": "Privato: edmondbircaj@gmail.com",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ , ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10935",
"titolo": "Privato: edmondbircaj@gmail.com", "url_post": "http://www.monferratopaesaggi.org/edmondbircajgmail-com-5/",
"tipo": "interesse_paesaggistico", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/interesse_paesaggistico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.407191038131714, 45.09155407528707 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10932",
"titolo": "Privato: edmondbircaj@gmail.com", "url_post": "http://www.monferratopaesaggi.org/edmondbircajgmail-com-3/",
"tipo": "interesse_paesaggistico", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/interesse_paesaggistico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.337732553482056, 45.107355666823764 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10912",
"titolo": "All’ombra di …", "url_post": "http://www.monferratopaesaggi.org/allombradi-edmond/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.221134271163919, 45.1591733919838 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10907",
"titolo": "Privato: iride.a@libero.it", "url_post": "http://www.monferratopaesaggi.org/iride-alibero-it-4/",
"tipo": "none", "wpid_comun": "6135", "comune": "Coniolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.363513946533203, 45.14626352951393 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10906",
"titolo": "Privato: Vista su Cuccaro (mattino)", "url_post": "http://www.monferratopaesaggi.org/vista-su-cuccaro-mattino/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.429110050201416, 45.01038708377795 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10897",
"titolo": "Privato: marco.vedoa@gmail.com", "url_post": "http://www.monferratopaesaggi.org/marco-vedoagmail-com/",
"tipo": "none", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.429110050201416, 45.01038708377795 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10896",
"titolo": "Privato: lavi1987@libero.it", "url_post": "http://www.monferratopaesaggi.org/lavi1987libero-it/",
"tipo": "none", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.429110050201416, 45.01038708377795 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10786",
"titolo": "Privato: Squadra di basket di Carlo Baviera", "url_post": "http://www.monferratopaesaggi.org/carlobaviera49gmail-com-2/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.457069396972656, 45.1302267133234 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10723",
"titolo": "Privato: Chiesa Parrocchiale di San giorgio", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-di-san-giorgio/",
"tipo": "edreligioso", "wpid_comun": "6065", "comune": "San Giorgio Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.414701223373413, 45.1073783834332 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10652",
"titolo": "Privato: Il Presepio in piazza a Mirabello Monferrato", "url_post": "http://www.monferratopaesaggi.org/lima-cityplannergmail-com-12/",
"tipo": "none", "wpid_comun": "6065", "comune": "San Giorgio Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.523818850517273, 45.03556583331845 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10648",
"titolo": "Privato: Cold Night, Bright Night", "url_post": "http://www.monferratopaesaggi.org/lima-cityplannergmail-com-11/",
"tipo": "none", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.419079760118848, 45.09200484204425 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10610",
"titolo": "Vista di Rosignano", "url_post": "http://www.monferratopaesaggi.org/vista-di-rosignano/",
"tipo": "puntooss", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.398097813096683, 45.0800437659818 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10609",
"titolo": "Chiesa Parrocchiale di San Maurizio Conzano", "url_post": "http://www.monferratopaesaggi.org/san-maurizio-conzano/",
"tipo": "edreligioso", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.459042966333072, 45.0492947984177 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10605",
"titolo": "Valle Ghenza da Rosignano Monferrato", "url_post": "http://www.monferratopaesaggi.org/mattmonzegmail-com-2/",
"tipo": "puntooss", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.399383127689362, 45.079628987954656 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10578",
"titolo": "Privato: Albero di Natale di Vignale", "url_post": "http://www.monferratopaesaggi.org/lavi1987libero-it-9/",
"tipo": "none", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.396590948104858, 45.0108839028745 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "10469",
"titolo": "Paesaggio nei pressi di Cascina Monsaietto", "url_post": "http://www.monferratopaesaggi.org/paesaggio-nei-pressi-di-cascina-monsaietto/",
"tipo": "puntooss", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.351344982208957, 45.05035749376466 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9802",
"titolo": "Palazzo Sannazzaro", "url_post": "http://www.monferratopaesaggi.org/palazzo-sannazaro/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.454054594039917, 45.137237226195836 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9789",
"titolo": "Veduta su cupola di Santa Caterina", "url_post": "http://www.monferratopaesaggi.org/cortile/",
"tipo": "puntooss", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448033034801483, 45.136321461844936 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9764",
"titolo": "Palazzo del Seminario Vescovile", "url_post": "http://www.monferratopaesaggi.org/palazzo-seminario-vescovile/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45474660396576, 45.13783227593339 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9721",
"titolo": "Chiesa Parrocchiale di San Germano", "url_post": "http://www.monferratopaesaggi.org/chiesa-9/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.456189632415771, 45.09874542084463 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9719",
"titolo": "Pozzo Sant’Evasio", "url_post": "http://www.monferratopaesaggi.org/chiesa-8/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.435933589935303, 45.10595100557878 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9650",
"titolo": "Scorcio torrione", "url_post": "http://www.monferratopaesaggi.org/scorcio-torrione/",
"tipo": "puntooss", "wpid_comun": "6065", "comune": "San Giorgio Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.412673473358154, 45.10803621465967 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9641",
"titolo": "Vergine Immacolata di Lourdes", "url_post": "http://www.monferratopaesaggi.org/chiesa-7/",
"tipo": "edreligioso", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.41626763343811, 45.06407169108483 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9638",
"titolo": "Chiesa di San Martino (fine ‘800)", "url_post": "http://www.monferratopaesaggi.org/chiesa-san-martino-800/",
"tipo": "edreligioso", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.413504958152771, 45.06611012177668 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9526",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-126/",
"tipo": "puntooss", "wpid_comun": "6122", "comune": "Sala Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.356497287750244, 45.077066388446205 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9524",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-125/",
"tipo": "puntooss", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.197267949581146, 45.1123152453911 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9522",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-124/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.280995786190033, 45.0930424059499 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9520",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-123/",
"tipo": "puntooss", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265111744403839, 45.08435235505272 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9518",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-122/",
"tipo": "puntooss", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.23979839682579, 45.127976733144905 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9516",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-121/",
"tipo": "puntooss", "wpid_comun": "6077", "comune": "Alfiano Natta",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.206588625907898, 45.04936006134896 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9514",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-120/",
"tipo": "puntooss", "wpid_comun": "6108", "comune": "Murisengo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.138396143913269, 45.07811568551019 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9512",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-119/",
"tipo": "puntooss", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.16503718495369, 45.067059217586596 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9510",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-118/",
"tipo": "puntooss", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.179659247398376, 45.06243293712725 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9507",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-117/",
"tipo": "puntooss", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.182777315378189, 45.06878118951059 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9505",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-116/",
"tipo": "puntooss", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.168860673904419, 45.134506918378925 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9502",
"titolo": "Strada per il percorso Po", "url_post": "http://www.monferratopaesaggi.org/strada-per-percorso-po/",
"tipo": "none", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.292328119277954, 45.16042727121142 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9487",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-115/",
"tipo": "puntooss", "wpid_comun": "6077", "comune": "Alfiano Natta",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.187464475631714, 45.05933149037456 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9445",
"titolo": "Punto di veduta Ecomuseo", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-114/",
"tipo": "puntooss", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.391100466251373, 45.07542421880788 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "9173",
"titolo": "Ex mattatoio", "url_post": "http://www.monferratopaesaggi.org/hotel-candiani-2/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45609575510025, 45.13956441239723 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8994",
"titolo": "Chiesa di Sant’Eusebio", "url_post": "http://www.monferratopaesaggi.org/chiesa-santeusebio/",
"tipo": "edreligioso", "wpid_comun": "6126", "comune": "Solonghello",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.29107016324997, 45.14142798489276 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8989",
"titolo": "Chiesa di San Michele", "url_post": "http://www.monferratopaesaggi.org/chiesa-san-michele-2/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.27107161283493, 45.131290171802675 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8986",
"titolo": "Castello", "url_post": "http://www.monferratopaesaggi.org/castello-2/",
"tipo": "edstorico", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.281754851341248, 45.0963824877628 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8984",
"titolo": "Santuario di Crea e sacro monte", "url_post": "http://www.monferratopaesaggi.org/santuario-crea-sacro-monte/",
"tipo": "edreligioso", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.275603204965591, 45.09422490056251 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8980",
"titolo": "Centro studi Parco di Crea", "url_post": "http://www.monferratopaesaggi.org/centro-studi-parco-crea/",
"tipo": "none", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.268837332725525, 45.092841691863626 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8978",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-113/",
"tipo": "puntooss", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.287159502506256, 45.085263272272236 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8964",
"titolo": "Cascina Gigliola", "url_post": "http://www.monferratopaesaggi.org/cascina-gigliola/",
"tipo": "ed_civile", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.23401689529419, 45.087709988405905 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8962",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-112/",
"tipo": "puntooss", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.212320506572723, 45.101627006572976 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8960",
"titolo": "Chiesa di Santo Spirito", "url_post": "http://www.monferratopaesaggi.org/chiesa-santo-spirito/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.247886598110199, 45.1032816753493 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8958",
"titolo": "Palazzo dell’Aglio", "url_post": "http://www.monferratopaesaggi.org/palazzo-dellaglio/",
"tipo": "ed_civile", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.247937560081482, 45.10301284226637 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8955",
"titolo": "Chiesa parrocchiale di San Candido", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-san-candido/",
"tipo": "edreligioso", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.232518881559372, 45.107485340681094 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8950",
"titolo": "Chiesa di San Michele", "url_post": "http://www.monferratopaesaggi.org/chiesa-san-michele/",
"tipo": "edreligioso", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.233015090227127, 45.11158553291308 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8933",
"titolo": "Cimitero", "url_post": "http://www.monferratopaesaggi.org/cimitero/",
"tipo": "edreligioso", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.227069973945618, 45.16040079314133 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8800",
"titolo": "Cascine Ramengo", "url_post": "http://www.monferratopaesaggi.org/cascine-ramengo/",
"tipo": "ed_civile", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.222354650497437, 45.09513660707389 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8797",
"titolo": "Case Carisio", "url_post": "http://www.monferratopaesaggi.org/case-carisio/",
"tipo": "ed_civile", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.212966918945312, 45.09443223696683 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8794",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-111/",
"tipo": "puntooss", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.214050531387329, 45.09380738524503 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8786",
"titolo": "Chiesa di San Rocco", "url_post": "http://www.monferratopaesaggi.org/chiesa-san-rocco/",
"tipo": "edreligioso", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.215429186820984, 45.09894895417618 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8784",
"titolo": "Casa Bosco", "url_post": "http://www.monferratopaesaggi.org/casa-bosco/",
"tipo": "ed_civile", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.213565051555634, 45.101130975239954 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8740",
"titolo": "Castello di Lignano", "url_post": "http://www.monferratopaesaggi.org/castello-lignano/",
"tipo": "edstorico", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.412635922431946, 45.03742901118246 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8736",
"titolo": "Chiesa parrocchiale di San Maurizio", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-san-maurizio/",
"tipo": "edreligioso", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.459166884422302, 45.04927383998701 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8728",
"titolo": "Torre Veglio (XIX secolo)", "url_post": "http://www.monferratopaesaggi.org/torre-veglio-xix-secolo/",
"tipo": "edstorico", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.431599140167236, 45.09031187649019 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8726",
"titolo": "Villa Maria o dei Morbelli", "url_post": "http://www.monferratopaesaggi.org/villa-maria-dei-morbelli/",
"tipo": "ed_civile", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.42352569103241, 45.08296606646384 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8718",
"titolo": "Cappella di San Bartolomeo", "url_post": "http://www.monferratopaesaggi.org/cappella-san-bartolomeo/",
"tipo": "edreligioso", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.419269025325775, 45.08162898576485 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8717",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-110/",
"tipo": "puntooss", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.41915637254715, 45.081683908959384 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8721",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-109/",
"tipo": "puntooss", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.418324887752533, 45.081358156826404 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8711",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-108/",
"tipo": "puntooss", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.41290682554245, 45.08031838904616 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8707",
"titolo": "Cava di tufo abbandonata", "url_post": "http://www.monferratopaesaggi.org/cava-tufo-abbandonata/",
"tipo": "none", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.413563966751099, 45.0779717397609 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8704",
"titolo": "Punto di veduta castello d’Uviglie", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-107/",
"tipo": "puntooss", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.40952455997467, 45.07518745458696 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8620",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-106/",
"tipo": "puntooss", "wpid_comun": "6077", "comune": "Alfiano Natta",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.200009167194366, 45.040118476303974 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8617",
"titolo": "Edificio d’interesse", "url_post": "http://www.monferratopaesaggi.org/edificio-dinteresse-2/",
"tipo": "ed_civile", "wpid_comun": "6077", "comune": "Alfiano Natta",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.206749558448792, 45.05208591585838 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8611",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-105/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.266788125038147, 45.04909571192648 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8604",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-104/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.34786057472229, 45.0208686736627 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8601",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-103/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.43148648738861, 45.01953014043001 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8597",
"titolo": "Murales", "url_post": "http://www.monferratopaesaggi.org/murales-2/",
"tipo": "none", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.432800769805908, 45.01969129693793 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8485",
"titolo": "Monumento Badoglio (cippo)", "url_post": "http://www.monferratopaesaggi.org/monumento-badoglio-cippo/",
"tipo": "none", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.311736583709717, 45.055989242140576 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8435",
"titolo": "Chiesa di San Giorgio", "url_post": "http://www.monferratopaesaggi.org/chiesa-san-giorgio/",
"tipo": "edreligioso", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.161785006523132, 45.05024405968328 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8433",
"titolo": "Reperto archeologia industriale recente", "url_post": "http://www.monferratopaesaggi.org/reperto-archeologia-industriale-recente/",
"tipo": "arc_industriale", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.168678283691406, 45.05977483515755 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8431",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-102/",
"tipo": "puntooss", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.177902400493622, 45.05598166312347 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8327",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-101/",
"tipo": "puntooss", "wpid_comun": "2201", "comune": "Cereseto",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.317418843507767, 45.09316169795 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8321",
"titolo": "Chiesa di San Defendente", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-defendente/",
"tipo": "edreligioso", "wpid_comun": "2201", "comune": "Cereseto",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.3175690472126, 45.087900305198225 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8319",
"titolo": "Castello Gualino", "url_post": "http://www.monferratopaesaggi.org/castello-gualino/",
"tipo": "edstorico", "wpid_comun": "2201", "comune": "Cereseto",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.316756337881088, 45.08676786360259 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8317",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-100/",
"tipo": "puntooss", "wpid_comun": "2201", "comune": "Cereseto",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.315289169549942, 45.086461077900836 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8315",
"titolo": "Chiesa Parrocchiale dei Santi Pietro Apostolo e Paolo", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-dei-santi-pietro-apostolo-paolo/",
"tipo": "edreligioso", "wpid_comun": "2201", "comune": "Cereseto",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.315576165914536, 45.086430777989044 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8313",
"titolo": "Chiesa di San Rocco (Seicento)", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-rocco-seicento/",
"tipo": "edreligioso", "wpid_comun": "2201", "comune": "Cereseto",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.317194879055023, 45.08558805525255 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8311",
"titolo": "Chiesa di San Giacomo (Settecento)", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-giacomo-settecento/",
"tipo": "edreligioso", "wpid_comun": "2201", "comune": "Cereseto",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.3176589012146, 45.085428031216054 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8304",
"titolo": "Infernot Cascina Allegra", "url_post": "http://www.monferratopaesaggi.org/infernot-21/",
"tipo": "infernot", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.324188739061356, 45.04789143798602 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8300",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-18/",
"tipo": "puntooss", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.338781297206879, 45.055483340606486 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8298",
"titolo": "Castello", "url_post": "http://www.monferratopaesaggi.org/castello-10/",
"tipo": "edstorico", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.338526487350464, 45.05505796300643 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8296",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-99/",
"tipo": "puntooss", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.338326662778854, 45.05454163182407 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8294",
"titolo": "Chiesa di San Germano", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-germano/",
"tipo": "edreligioso", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.338440656661987, 45.05437488901522 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8292",
"titolo": "Infernot via Marconi", "url_post": "http://www.monferratopaesaggi.org/infernot-20/",
"tipo": "infernot", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.339619487524033, 45.054081193112744 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8290",
"titolo": "Infernot via Mazza", "url_post": "http://www.monferratopaesaggi.org/infernot-19/",
"tipo": "infernot", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.339359313249588, 45.05314609320938 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8285",
"titolo": "Chiesa di Sant’Eusebio", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-eusebio-2/",
"tipo": "edreligioso", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.337649405002594, 45.05176188990497 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8276",
"titolo": "Cedro del Libano", "url_post": "http://www.monferratopaesaggi.org/cedro-libano/",
"tipo": "giardino", "wpid_comun": "6136", "comune": "Olivola",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.363409340381622, 45.03784883383186 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8274",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-98/",
"tipo": "puntooss", "wpid_comun": "6136", "comune": "Olivola",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.36528554558754, 45.03877660253139 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8272",
"titolo": "Chiesa di San Sebastiano", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-sebastiano-3/",
"tipo": "edreligioso", "wpid_comun": "6136", "comune": "Olivola",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.365433067083359, 45.038694155870914 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8269",
"titolo": "Villa Candiani", "url_post": "http://www.monferratopaesaggi.org/villa-candiani/",
"tipo": "ed_civile", "wpid_comun": "6136", "comune": "Olivola",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.365429043769836, 45.0385681164936 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8265",
"titolo": "Chiesa parrocchiale", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-2/",
"tipo": "edreligioso", "wpid_comun": "6136", "comune": "Olivola",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.367623090744019, 45.037219572546704 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8261",
"titolo": "Oratorio San Pietro", "url_post": "http://www.monferratopaesaggi.org/oratorio-s-pietro/",
"tipo": "edreligioso", "wpid_comun": "6136", "comune": "Olivola",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.367554694414139, 45.03702055774809 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8257",
"titolo": "Infernot via Pugno", "url_post": "http://www.monferratopaesaggi.org/infernot-18/",
"tipo": "infernot", "wpid_comun": "6136", "comune": "Olivola",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.367341458797455, 45.03676941903817 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8255",
"titolo": "Chiesa dei Santi Pietro e Paolo", "url_post": "http://www.monferratopaesaggi.org/chiesa-dei-ss-pietro-paolo/",
"tipo": "edreligioso", "wpid_comun": "6136", "comune": "Olivola",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.367915451526642, 45.03554308814773 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8253",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-97/",
"tipo": "puntooss", "wpid_comun": "6136", "comune": "Olivola",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.367875218391418, 45.03545589824296 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8251",
"titolo": "La chiesetta di San Michele a Moleto", "url_post": "http://www.monferratopaesaggi.org/chiesetta-3/",
"tipo": "edreligioso", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.371591418981552, 45.052079283766616 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8249",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-96/",
"tipo": "puntooss", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.371745645999908, 45.05200443582065 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8245",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-30/",
"tipo": "ed_civile", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.36939200758934, 45.05308545803731 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8243",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-29/",
"tipo": "ed_civile", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.369760811328888, 45.05277659663189 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8241",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-28/",
"tipo": "ed_civile", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.370275795459747, 45.05195706365231 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8239",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-18/",
"tipo": "ed_civile", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.369802385568619, 45.05171072774451 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8237",
"titolo": "Cave di gesso", "url_post": "http://www.monferratopaesaggi.org/cave-gesso/",
"tipo": "interesse_paesaggistico", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/interesse_paesaggistico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.370509147644043, 45.04956756057738 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8235",
"titolo": "Chiesa di San Bernardo di Chiaravalle", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-bernardo-chiaravalle/",
"tipo": "edreligioso", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.385152667760849, 45.03910923095525 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8231",
"titolo": "Chiesa di Santa Maria delle Grazie", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-maria-delle-grazie/",
"tipo": "edreligioso", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.385403454303741, 45.03577243487167 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8229",
"titolo": "Infernot via Umberto I, 13", "url_post": "http://www.monferratopaesaggi.org/infernot-17/",
"tipo": "infernot", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.38688537478447, 45.03286193781101 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8227",
"titolo": "Infernot via Umberto I, 12", "url_post": "http://www.monferratopaesaggi.org/infernot-16/",
"tipo": "infernot", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.38677003979683, 45.03260130320744 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8224",
"titolo": "Infernot via Torrione", "url_post": "http://www.monferratopaesaggi.org/infernot-15/",
"tipo": "infernot", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.387138843536377, 45.03272166915369 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8221",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-95/",
"tipo": "puntooss", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.387219309806824, 45.03238047368718 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8217",
"titolo": "Castello Sacchi Nemours", "url_post": "http://www.monferratopaesaggi.org/castello-sacchi-nemours/",
"tipo": "edstorico", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.387687355279922, 45.03228001018994 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8215",
"titolo": "Ex chiesa dei Santi Angeli, ora salone comunale", "url_post": "http://www.monferratopaesaggi.org/ex-chiesa-dei-santi-angeli-salone-comunale/",
"tipo": "edreligioso", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.387213945388794, 45.03222883060468 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8209",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-31/",
"tipo": "puntooss", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.38645488023758, 45.03177958561445 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8207",
"titolo": "Sagrato", "url_post": "http://www.monferratopaesaggi.org/sagrato/",
"tipo": "edreligioso", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.386845141649246, 45.03170186776888 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8203",
"titolo": "Chiesa Parrocchiale dell’Assunzione di Maria Vergine o di San Spiridione", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-dellassunzione-maria-vergine-san-spiridione/",
"tipo": "edreligioso", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.387087881565094, 45.03164784432627 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8200",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-17/",
"tipo": "puntooss", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.387227356433868, 45.03152937168584 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8198",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-30/",
"tipo": "puntooss", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.387124091386795, 45.031360666222604 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8192",
"titolo": "Chiesa di Sant’Anna", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-anna/",
"tipo": "edreligioso", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.388736099004745, 45.03150188599822 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8190",
"titolo": "Chiesa di San Giuseppe", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-giuseppe-3/",
"tipo": "edreligioso", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.389652073383331, 45.0314099510161 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8188",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-16/",
"tipo": "puntooss", "wpid_comun": "6106", "comune": "Frassinello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.393133580684662, 45.03120617707571 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8184",
"titolo": "Parco comunale", "url_post": "http://www.monferratopaesaggi.org/parco-comunale/",
"tipo": "giardino", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.441552817821503, 45.08509472527482 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8182",
"titolo": "Villa Poggio o Villa Adele", "url_post": "http://www.monferratopaesaggi.org/villa-poggio-villa-adele/",
"tipo": "ed_civile", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.441157191991806, 45.08370656086539 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8180",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-94/",
"tipo": "puntooss", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.44182774424553, 45.083773791979006 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8178",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-17/",
"tipo": "ed_civile", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.441833108663559, 45.08291871994802 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8175",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-93/",
"tipo": "puntooss", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.441939055919647, 45.08298595198878 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8173",
"titolo": "Teatro delle Muse", "url_post": "http://www.monferratopaesaggi.org/teatro-delle-muse/",
"tipo": "teatro", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/teatro.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.442077189683914, 45.083066440947604 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8170",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-11/",
"tipo": "ed_civile", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.442454040050507, 45.08310810577585 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8163",
"titolo": "Chiesa parrocchiale di San Martino", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-s-martino/",
"tipo": "edreligioso", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.442707508802414, 45.083388395648925 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8161",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-92/",
"tipo": "puntooss", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.442885875701904, 45.083343890254156 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8157",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-91/",
"tipo": "puntooss", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.44325065612793, 45.08319048841502 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8155",
"titolo": "Palazzo Biletta", "url_post": "http://www.monferratopaesaggi.org/palazzo-biletta-2/",
"tipo": "ed_civile", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.44381257891655, 45.082829708392055 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8153",
"titolo": "Chiesa di San Grato", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-grato-2/",
"tipo": "edreligioso", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.444275259971619, 45.08239222404793 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8151",
"titolo": "Villa Pavia", "url_post": "http://www.monferratopaesaggi.org/villa-pavia/",
"tipo": "ed_civile", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.442775905132294, 45.081161189519335 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8149",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-90/",
"tipo": "puntooss", "wpid_comun": "6127", "comune": "Terruggia",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.446654379367828, 45.07959394949021 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8147",
"titolo": "Museo di Cristoforo Colombo o colombiano", "url_post": "http://www.monferratopaesaggi.org/museo-cristoforo-colombo-colombiano/",
"tipo": "museo", "wpid_comun": "6134", "comune": "Cuccaro Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.457211554050446, 44.99067202422576 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8143",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-89/",
"tipo": "puntooss", "wpid_comun": "6134", "comune": "Cuccaro Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.456728756427765, 44.9908237773795 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8140",
"titolo": "Chiesa parrocchiale", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale/",
"tipo": "edreligioso", "wpid_comun": "6134", "comune": "Cuccaro Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.456448465585709, 44.99092526207686 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8136",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-88/",
"tipo": "puntooss", "wpid_comun": "6134", "comune": "Cuccaro Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45627948641777, 44.99103717957214 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8133",
"titolo": "Area pic nic a Cuccaro Monferrato", "url_post": "http://www.monferratopaesaggi.org/area-pic-nic-5/",
"tipo": "picnic", "wpid_comun": "6134", "comune": "Cuccaro Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/pic-nic.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.455879837274551, 44.99097173631754 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8130",
"titolo": "Parco della Rimembranza", "url_post": "http://www.monferratopaesaggi.org/parco-rimembranza-2/",
"tipo": "giardino", "wpid_comun": "6134", "comune": "Cuccaro Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.455851674079895, 44.990793426780904 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8128",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-10/",
"tipo": "ed_civile", "wpid_comun": "6134", "comune": "Cuccaro Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.455541878938675, 44.99072229250244 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8121",
"titolo": "Murales", "url_post": "http://www.monferratopaesaggi.org/murales/",
"tipo": "none", "wpid_comun": "6134", "comune": "Cuccaro Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.455997854471207, 44.99153796026411 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8119",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-15/",
"tipo": "puntooss", "wpid_comun": "6134", "comune": "Cuccaro Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.456176221370697, 44.99249113869501 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8112",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-87/",
"tipo": "puntooss", "wpid_comun": "6134", "comune": "Cuccaro Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.457664847373962, 44.99670959278795 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8108",
"titolo": "Madonna della Neve", "url_post": "http://www.monferratopaesaggi.org/madonna-neve/",
"tipo": "edreligioso", "wpid_comun": "6134", "comune": "Cuccaro Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.457572311162949, 44.99678356470705 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8106",
"titolo": "Area pic nic a Cuccaro Monferrato", "url_post": "http://www.monferratopaesaggi.org/area-pic-nic-4/",
"tipo": "picnic", "wpid_comun": "6134", "comune": "Cuccaro Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/pic-nic.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.457454293966293, 44.99686038159893 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8099",
"titolo": "Viale della Rimembranza", "url_post": "http://www.monferratopaesaggi.org/viale-rimembranza/",
"tipo": "none", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.488070368766785, 45.002979796427404 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8092",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-86/",
"tipo": "puntooss", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.48405510187149, 45.00195756866402 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8090",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-9/",
"tipo": "ed_civile", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.48400816321373, 45.00186179314317 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8088",
"titolo": "Chiesa di Santa Maria Nuova", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-maria-nuova/",
"tipo": "edreligioso", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.484979122877121, 45.00201067185412 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8086",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-85/",
"tipo": "puntooss", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.48457008600235, 45.00137912001228 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8084",
"titolo": "Casa storica", "url_post": "http://www.monferratopaesaggi.org/casa-storica-2/",
"tipo": "ed_civile", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.484677374362946, 45.00119325658279 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8082",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-84/",
"tipo": "puntooss", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.48398670554161, 45.0015649828388 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8077",
"titolo": "Scuola materna", "url_post": "http://www.monferratopaesaggi.org/scuola-materna/",
"tipo": "ed_civile", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.482870906591415, 45.00180489671832 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8075",
"titolo": "Chiesa di San Giuseppe", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-giuseppe-2/",
"tipo": "edreligioso", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.481663912534714, 45.00166170713244 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8072",
"titolo": "Chiesa di San Nazario", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-nazario/",
"tipo": "edreligioso", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.48379760980606, 45.000958081583384 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8070",
"titolo": "Chiesa della Santissima Trinità", "url_post": "http://www.monferratopaesaggi.org/chiesa-ss-trinita-2/",
"tipo": "edreligioso", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.482781052589417, 45.001007392550356 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8068",
"titolo": "Palazzo Paleologi", "url_post": "http://www.monferratopaesaggi.org/palazzo-paleologi/",
"tipo": "ed_civile", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.482656329870224, 45.00056833379352 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8066",
"titolo": "Casa Bobba", "url_post": "http://www.monferratopaesaggi.org/casa-bobba/",
"tipo": "ed_civile", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.483065366744995, 45.0002772065856 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8064",
"titolo": "Casa storica", "url_post": "http://www.monferratopaesaggi.org/casa-storica/",
"tipo": "ed_civile", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.482469916343689, 45.00013970299262 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8062",
"titolo": "Chiesa di San Francesco", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-francesco-2/",
"tipo": "edreligioso", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.482715338468552, 45.00008090825213 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8060",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-83/",
"tipo": "puntooss", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.457538783550262, 45.01983064955261 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8057",
"titolo": "Torre civica", "url_post": "http://www.monferratopaesaggi.org/torre-civica-4/",
"tipo": "edstorico", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.457462340593338, 45.01984960906583 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8054",
"titolo": "Chiesetta di San Biagio", "url_post": "http://www.monferratopaesaggi.org/chiesetta-s-biagio/",
"tipo": "edreligioso", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45729872584343, 45.019867620597545 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8052",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-82/",
"tipo": "puntooss", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.457157909870148, 45.01968086917761 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8050",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-81/",
"tipo": "puntooss", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.457064032554626, 45.019867620597545 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8046",
"titolo": "Giardino di Villa Vidua", "url_post": "http://www.monferratopaesaggi.org/giardino-villa-vidua/",
"tipo": "giardino", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.456864207983017, 45.01997568966891 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8044",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-paese/",
"tipo": "puntooss", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.456746190786362, 45.019852452992254 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8042",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-29/",
"tipo": "puntooss", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.456567823886871, 45.02028662410496 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8040",
"titolo": "Villa Vidua", "url_post": "http://www.monferratopaesaggi.org/villa-vidua/",
"tipo": "ed_civile", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.456465899944305, 45.02010176999439 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8038",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-80/",
"tipo": "puntooss", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45640555024147, 45.01989226794756 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8036",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-8/",
"tipo": "ed_civile", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.456138670444489, 45.02059945277865 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8034",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-79/",
"tipo": "puntooss", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.4556183218956, 45.02005626735256 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8031",
"titolo": "Chiesa parrocchiale di San Lucia", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-s-lucia/",
"tipo": "edreligioso", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.455846309661865, 45.02029799972304 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8024",
"titolo": "Infernot vicolo Morra", "url_post": "http://www.monferratopaesaggi.org/infernot-14/",
"tipo": "infernot", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.431884795427322, 45.01896040113912 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8022",
"titolo": "Chiesetta", "url_post": "http://www.monferratopaesaggi.org/chiesetta-2/",
"tipo": "edreligioso", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.43089371919632, 45.01862860359886 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8019",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-16/",
"tipo": "ed_civile", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.430876284837723, 45.018487352062536 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8017",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-15/",
"tipo": "ed_civile", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.430731445550919, 45.018316712157926 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8015",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-28/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.43063086271286, 45.01837643618238 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8013",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-7/",
"tipo": "ed_civile", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.430329114198685, 45.01774316875148 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8008",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-27/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.4306201338768, 45.017843657763436 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8004",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-78/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.430199027061462, 45.01762466733158 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8002",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-77/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.430101126432419, 45.017630355405345 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "8000",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-76/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.430162817239761, 45.01861817564502 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7998",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-75/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.430156111717224, 45.01823802803061 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7996",
"titolo": "Rocca", "url_post": "http://www.monferratopaesaggi.org/rocca/",
"tipo": "edstorico", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.429819494485855, 45.018114787613904 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7994",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-26/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.429406434297562, 45.01810530757084 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7992",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-25/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.429470807313919, 45.017689132134436 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7990",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-24/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.429592847824097, 45.017512801766166 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7988",
"titolo": "Museo della Resistenza del Basso Monferrato presso Casa Giambone", "url_post": "http://www.monferratopaesaggi.org/museo-resistenza-basso-monferrato-presso-casa-giambone/",
"tipo": "museo", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.430020660161972, 45.01750806169499 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7986",
"titolo": "Infernot via Monteacuto 31", "url_post": "http://www.monferratopaesaggi.org/infernot-13/",
"tipo": "infernot", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.427998274564743, 45.01969129693793 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7984",
"titolo": "Infernot via Monteacuto 14", "url_post": "http://www.monferratopaesaggi.org/infernot-12/",
"tipo": "infernot", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.428373783826828, 45.019111131386545 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7982",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-74/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.4284408390522, 45.01770145627967 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7980",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-23/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.42849850654602, 45.01752322992133 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7978",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-14/",
"tipo": "ed_civile", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.42869833111763, 45.01761329118238 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7974",
"titolo": "Chiesa di Sant’Eusebio", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-eusebio/",
"tipo": "edreligioso", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.428861945867538, 45.01746350500686 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7971",
"titolo": "Bici", "url_post": "http://www.monferratopaesaggi.org/bici-2/",
"tipo": "none", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.428686261177063, 45.017232188877664 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7969",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-73/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.428790867328644, 45.01723503293409 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7967",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-22/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.4287828207016, 45.01708998587535 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7965",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-21/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.428859263658524, 45.01639508212479 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7963",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-20/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.42814177274704, 45.01487062525615 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7961",
"titolo": "Bici", "url_post": "http://www.monferratopaesaggi.org/bici/",
"tipo": "none", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.427976816892624, 45.012484313715255 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7959",
"titolo": "Punto di veduta chiesa di San Lorenzo", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-72/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.42165619134903, 44.99752327864626 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7957",
"titolo": "Chiesa di San Lorenzo", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-lorenzo/",
"tipo": "edreligioso", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.421527445316315, 44.99764751171744 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7955",
"titolo": "Museo di arte contadina", "url_post": "http://www.monferratopaesaggi.org/museo-arte-contadina/",
"tipo": "museo", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.420205116271973, 45.001201791141234 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7953",
"titolo": "Chiesa della Madonna di Fossano", "url_post": "http://www.monferratopaesaggi.org/chiesa-madonna-fossano/",
"tipo": "edreligioso", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.42232272028923, 45.02074923075065 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7950",
"titolo": "Chiesa di San Sebastiano", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-sebastiano-2/",
"tipo": "edreligioso", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.40335950255394, 45.0101642722872 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7948",
"titolo": "Archeologia agricola", "url_post": "http://www.monferratopaesaggi.org/archeologia-agricola/",
"tipo": "none", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.401638865470886, 45.01000498524334 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7946",
"titolo": "Cartellone con percorso storico dedicato a “Carlo Ferraris”", "url_post": "http://www.monferratopaesaggi.org/cartellone-percorso-storico/",
"tipo": "none", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.399161845445633, 45.01007419931089 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7937",
"titolo": "Scorcio interno via Roma", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-19/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.398105055093765, 45.0101102285184 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7935",
"titolo": "Antiche mura", "url_post": "http://www.monferratopaesaggi.org/antiche-mura-2/",
"tipo": "edstorico", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.397010713815689, 45.00988836409106 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7933",
"titolo": "Castello Callori", "url_post": "http://www.monferratopaesaggi.org/castello-callori/",
"tipo": "edstorico", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.397508263587952, 45.01104697995906 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7931",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-71/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.397261500358582, 45.01140821301042 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7926",
"titolo": "Palazzo", "url_post": "http://www.monferratopaesaggi.org/palazzo-2/",
"tipo": "ed_civile", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.396987915039062, 45.0105065483054 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7924",
"titolo": "Palazzo Vitale", "url_post": "http://www.monferratopaesaggi.org/palazzo-vitale/",
"tipo": "ed_civile", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.396745175123215, 45.01069143339236 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7922",
"titolo": "Palazzo municipale", "url_post": "http://www.monferratopaesaggi.org/palazzo-municipale/",
"tipo": "ed_civile", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.396625816822052, 45.01089528036055 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7920",
"titolo": "Scorcio interno piazza del Popolo 2", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-18/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.396467566490173, 45.0108848509984 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7918",
"titolo": "Cartellone con percorso artistico diffuso “Giorno Notte” di Gianni Colonna", "url_post": "http://www.monferratopaesaggi.org/cartellone-percorso-artista-colonna/",
"tipo": "none", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.396541327238083, 45.01052551090589 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7916",
"titolo": "Scorcio interno piazza del Popolo", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-17/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.39627981185913, 45.01060041311643 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7914",
"titolo": "Torre civica", "url_post": "http://www.monferratopaesaggi.org/torre-civica-3/",
"tipo": "edstorico", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.39607059955597, 45.01058903557179 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7905",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-16/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.395924419164658, 45.009943356208716 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7903",
"titolo": "Scorcio interno via Besso", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-15/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.396337479352951, 45.009765105704496 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7899",
"titolo": "Chiesa della purificazione di Maria Vergine o Chiesa dei Battuti", "url_post": "http://www.monferratopaesaggi.org/chiesa-purificazione-maria-vergine-chiesa-dei-battuti/",
"tipo": "edreligioso", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.395758122205734, 45.00964469148614 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7896",
"titolo": "Porta urbis", "url_post": "http://www.monferratopaesaggi.org/porta-urbis/",
"tipo": "edstorico", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.395532816648483, 45.009280602860706 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7890",
"titolo": "Scorcio interno via Giuseppe Mazzini", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-14/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.395267277956009, 45.012171440705195 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7888",
"titolo": "Edificio d’interesse", "url_post": "http://www.monferratopaesaggi.org/edificio-dinteresse/",
"tipo": "ed_civile", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.395027220249176, 45.01214679003178 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7884",
"titolo": "Bastioni con ambienti ricavati nel sottostante banco di arenaria", "url_post": "http://www.monferratopaesaggi.org/bastioni-ambienti-ricavati-nel-sottostante-banco-arenaria/",
"tipo": "edstorico", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.394516259431839, 45.01005997724904 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7882",
"titolo": "Scorcio interno piazza Italia", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-13/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.39455246925354, 45.00948729929142 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7880",
"titolo": "Portale ingresso ex Convento Servi di Maria", "url_post": "http://www.monferratopaesaggi.org/portale-ingresso-ex-convento-servi-maria/",
"tipo": "edstorico", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.39547649025917, 45.00901606826717 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7876",
"titolo": "Parco della Rimembranza", "url_post": "http://www.monferratopaesaggi.org/parco-rimembranza/",
"tipo": "interesse_paesaggistico", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/interesse_paesaggistico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.394630253314972, 45.0088871190618 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7874",
"titolo": "Ex Convento Servi di Maria, ora Casa della Salute", "url_post": "http://www.monferratopaesaggi.org/ex-convento-servi-maria-casa-salute/",
"tipo": "edstorico", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.395032584667206, 45.00863490874741 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7872",
"titolo": "Punto di veduta Casa della Salute", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-70/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.39487299323082, 45.0083694230062 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7870",
"titolo": "Chiesa dell’Annunziata", "url_post": "http://www.monferratopaesaggi.org/chiesa-dellannunziata/",
"tipo": "edreligioso", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.363280594348907, 45.010610842530376 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7867",
"titolo": "Chiesa di San Giorgio e della Madonna delle Grazie", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-giorgio-madonna-delle-grazie/",
"tipo": "edreligioso", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.339830040931702, 45.02251335826342 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7865",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/scorcio-paese/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.328820914030075, 45.02145166525231 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7863",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-69/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.329014033079147, 45.02079283692203 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7859",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-68/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.342214524745941, 45.02349919843034 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7857",
"titolo": "Parco giochi bambini", "url_post": "http://www.monferratopaesaggi.org/parco-giochi-bambini/",
"tipo": "giardino", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.34081307053566, 45.022653651938576 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7855",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-67/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.34005132317543, 45.0225180979202 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7852",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-66/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.339767009019852, 45.022564546536096 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7847",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-12/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.337914943695068, 45.02308685388739 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7845",
"titolo": "Palazzo Biletta", "url_post": "http://www.monferratopaesaggi.org/palazzo-biletta/",
"tipo": "ed_civile", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.337678909301758, 45.02298353030669 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7843",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-65/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.337311446666718, 45.02307168713492 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7841",
"titolo": "Confraternita della Santissima Trinità", "url_post": "http://www.monferratopaesaggi.org/confraternita-ss-trinita/",
"tipo": "edreligioso", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.337316811084747, 45.023174062636066 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7839",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-64/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.335838913917542, 45.023279281710366 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7835",
"titolo": "Palazzo residenza evangelica per anziani", "url_post": "http://www.monferratopaesaggi.org/palazzo-residenza-evangelica-per-anziani/",
"tipo": "ed_civile", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.335828185081482, 45.023567448275145 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7833",
"titolo": "Chiesa dei Batù", "url_post": "http://www.monferratopaesaggi.org/chiesa-dei-batu/",
"tipo": "edreligioso", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.334583640098572, 45.02387931111386 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7829",
"titolo": "Albero secolare (castagno?)", "url_post": "http://www.monferratopaesaggi.org/albero-secolare-castagno/",
"tipo": "giardino", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.333980143070221, 45.023588302378144 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7827",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-63/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.33362877368927, 45.02349066719405 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7824",
"titolo": "Chiesa parrocchiale di San Vincenzo Martire", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-s-vincenzo-martire/",
"tipo": "edreligioso", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.334378451108932, 45.023174062636066 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7822",
"titolo": "Canonica", "url_post": "http://www.monferratopaesaggi.org/canonica/",
"tipo": "edreligioso", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.33456888794899, 45.02298353030669 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7820",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-14/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.334153145551682, 45.02271337143923 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7816",
"titolo": "Punto informazioni", "url_post": "http://www.monferratopaesaggi.org/punto-informazioni-2/",
"tipo": "info", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/info.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.337256461381912, 45.02170287118035 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7810",
"titolo": "Torre", "url_post": "http://www.monferratopaesaggi.org/torre/",
"tipo": "edstorico", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.339679837226868, 45.021439341914274 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7808",
"titolo": "Bialbero Casorzo", "url_post": "http://www.monferratopaesaggi.org/bialbero-casorzo/",
"tipo": "giardino", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.323097079992294, 45.00476248766094 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7804",
"titolo": "Infernot Alasio (Via Roma 49/A)", "url_post": "http://www.monferratopaesaggi.org/infernot-alasio-via-roma-49a/",
"tipo": "infernot", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.308861255645752, 45.04081214447438 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7799",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-62/",
"tipo": "puntooss", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.31353634595871, 45.03952525067822 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7797",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-61/",
"tipo": "puntooss", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.313608765602112, 45.039772586710725 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7793",
"titolo": "Abbazia di Grazzano Badoglio dei Santi Vittore e Corona", "url_post": "http://www.monferratopaesaggi.org/chiesa-dei-ss-vittore-corona/",
"tipo": "edreligioso", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.313868939876556, 45.039684455603336 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7787",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-60/",
"tipo": "puntooss", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.313197046518326, 45.03941153260333 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7783",
"titolo": "Chiesa di Santo Spirito", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-spirito/",
"tipo": "edreligioso", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.313430398702621, 45.038885583567016 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7781",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-6/",
"tipo": "ed_civile", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.313548415899277, 45.03893107124223 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7779",
"titolo": "Infernot Mosso-Redoglia", "url_post": "http://www.monferratopaesaggi.org/infernot-mosso-redoglia/",
"tipo": "infernot", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.31347867846489, 45.03876902123424 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7777",
"titolo": "Infernot Monti-Colombaro", "url_post": "http://www.monferratopaesaggi.org/infernot-monti-colombaro/",
"tipo": "infernot", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.313391506671906, 45.03874912032444 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7773",
"titolo": "Chiostro dell’Abbazia", "url_post": "http://www.monferratopaesaggi.org/chiostro-dellabbazia/",
"tipo": "edreligioso", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.314198851585388, 45.039567894898006 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7771",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-59/",
"tipo": "puntooss", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.314173370599747, 45.03948734467837 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7769",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-13/",
"tipo": "ed_civile", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.314617276191711, 45.03938784130927 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7767",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-58/",
"tipo": "puntooss", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.315619081258774, 45.03950724533141 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7765",
"titolo": "Casa Brion", "url_post": "http://www.monferratopaesaggi.org/casa-brion/",
"tipo": "ed_civile", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.315446078777313, 45.03919546763837 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7763",
"titolo": "Casa Redoglia", "url_post": "http://www.monferratopaesaggi.org/casa-redoglia/",
"tipo": "ed_civile", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.317452371120453, 45.03868941755348 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7761",
"titolo": "Infernot Testa", "url_post": "http://www.monferratopaesaggi.org/infernot-testa/",
"tipo": "infernot", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.318248987197876, 45.03860318010763 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7759",
"titolo": "Tenuta Santa Caterina", "url_post": "http://www.monferratopaesaggi.org/tenuta-santa-caterina/",
"tipo": "edstorico", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.31413447856903, 45.03561795763389 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7757",
"titolo": "Chiesa di Santa Caterina d’Alessandria", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-caterina-dalessandria/",
"tipo": "edreligioso", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.301679641008377, 45.06851314118451 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7755",
"titolo": "Chiesa di Santa Croce (XVI secolo)", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-croce-xvi-secolo/",
"tipo": "edreligioso", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.292494416236877, 45.0570701890344 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7751",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-57/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.292426019906998, 45.05700671594275 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7749",
"titolo": "Chiesa di San Pietro in Vincoli o Chiesetta “La Pieve”", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-pietro-in-vincoli/",
"tipo": "edreligioso", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.252076208591461, 45.04535110429882 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7747",
"titolo": "Convento dei Cappuccini (1642?)", "url_post": "http://www.monferratopaesaggi.org/convento-dei-cappuccini-1642/",
"tipo": "edstorico", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.261237293481827, 45.04638582302102 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7745",
"titolo": "Villa Foà", "url_post": "http://www.monferratopaesaggi.org/villa-foa/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.256731182336807, 45.04871197671991 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7730",
"titolo": "Residenza dei primi del Novecento", "url_post": "http://www.monferratopaesaggi.org/residenza-dei-primi-novecento/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.254951536655426, 45.05102192901737 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7724",
"titolo": "Ex ospedale", "url_post": "http://www.monferratopaesaggi.org/ex-ospedale-2/",
"tipo": "none", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.258356600999832, 45.05273680455039 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7722",
"titolo": "Chiesa di San Marco", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-marco/",
"tipo": "edreligioso", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.25880452990532, 45.05279175551279 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7720",
"titolo": "Casa di C. Ferraris", "url_post": "http://www.monferratopaesaggi.org/casa-c-ferraris/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.260637819766998, 45.05234172452482 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7718",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-12/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.261670470237732, 45.0520442284117 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7716",
"titolo": "Edificio medievale", "url_post": "http://www.monferratopaesaggi.org/edificio-medievale/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.26234370470047, 45.051888847661004 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7714",
"titolo": "Edificio anni ’30", "url_post": "http://www.monferratopaesaggi.org/edificio-anni-30/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.262209594249725, 45.05159229664194 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7712",
"titolo": "Punto di veduta Belvedere Bonaventura", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-belvedere-bonaventura/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.266941010951996, 45.05213234047912 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7710",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-sulle-mura-2/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.2672119140625, 45.0521617111381 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7707",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-interno-torre/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.267331272363663, 45.05205938748674 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7705",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-sulle-mura/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.267270922660828, 45.05191442866728 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7703",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-13/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.266463577747345, 45.05225550765768 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7695",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-torre/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265923112630844, 45.05164440635729 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7693",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/scorcio-panoramico/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.263248950242996, 45.051701253265335 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7691",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-11/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.263342827558517, 45.05159229664194 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7689",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-11/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.262755423784256, 45.05131279826752 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7687",
"titolo": "Museo civico", "url_post": "http://www.monferratopaesaggi.org/museo-civico/",
"tipo": "museo", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.263440728187561, 45.05144828409078 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7684",
"titolo": "Palazzo Manacorda", "url_post": "http://www.monferratopaesaggi.org/palazzo-manacorda/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.264266848564148, 45.05135069643223 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7682",
"titolo": "Teatro comunale", "url_post": "http://www.monferratopaesaggi.org/teatro-comunale/",
"tipo": "teatro", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/teatro.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265291452407837, 45.05127205771245 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7680",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-10/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265316933393478, 45.050875072645034 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7678",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-10/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265004456043243, 45.050911076177655 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7676",
"titolo": "Casa dei Marchesi di Monferrato o Palazzo Paleologo (metà XV secolo)", "url_post": "http://www.monferratopaesaggi.org/casa-dei-marchesi-monferrato-palazzo-paleologo-meta-xv-secolo/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265118449926376, 45.05089117949138 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7674",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-9/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.26497495174408, 45.05082769954126 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7672",
"titolo": "Ex sinagoga", "url_post": "http://www.monferratopaesaggi.org/ex-sinagoga/",
"tipo": "edstorico", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265878856182098, 45.05097739841525 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7670",
"titolo": "Casa Lanfrancone", "url_post": "http://www.monferratopaesaggi.org/casa-lanfrancone/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265734016895294, 45.050708319145734 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7668",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-8/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265687078237534, 45.050700739429665 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7666",
"titolo": "Palazzo Testa Fochi", "url_post": "http://www.monferratopaesaggi.org/palazzo-testa-fochi/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.264645040035248, 45.05065905097336 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7662",
"titolo": "Scorcio interno", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno-7/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.264100551605225, 45.05015878712745 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7658",
"titolo": "Palazzo dal Pozzo", "url_post": "http://www.monferratopaesaggi.org/palazzo-dal-pozzo/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265679031610489, 45.04952208135886 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7656",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-56/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.266436755657196, 45.04945102000751 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7654",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-55/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.266930282115936, 45.04886547111148 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7652",
"titolo": "Parco e monumento ai caduti", "url_post": "http://www.monferratopaesaggi.org/parco-monumento-caduti/",
"tipo": "interesse_paesaggistico", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/interesse_paesaggistico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.2681305706501, 45.04780331938513 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7649",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-54/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.26959639787674, 45.04697802998533 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7644",
"titolo": "Chiesa parrocchiale di San Marzano", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-s-marziano/",
"tipo": "edreligioso", "wpid_comun": "6077", "comune": "Alfiano Natta",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.206961452960968, 45.04929563221163 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7641",
"titolo": "Chiesetta", "url_post": "http://www.monferratopaesaggi.org/chiesetta/",
"tipo": "edreligioso", "wpid_comun": "6077", "comune": "Alfiano Natta",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.212624937295914, 45.04788670043028 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7639",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-belvedere/",
"tipo": "puntooss", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.25218215584755, 45.13413700175629 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7636",
"titolo": "Chiesetta di San Martino", "url_post": "http://www.monferratopaesaggi.org/chiesetta-s-martino/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.252391368150711, 45.133886289637 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7634",
"titolo": "Palazzo Tornelli", "url_post": "http://www.monferratopaesaggi.org/palazzo-tornelli/",
"tipo": "ed_civile", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.251498192548752, 45.133179559353124 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7632",
"titolo": "Chiesa dei San Pietro Apostolo e Sant’Anna", "url_post": "http://www.monferratopaesaggi.org/chiesa-dei-ss-pietro-apostolo-anna/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.251153528690338, 45.13311806299723 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7629",
"titolo": "Antiche mura", "url_post": "http://www.monferratopaesaggi.org/antiche-mura/",
"tipo": "none", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.251372128725052, 45.13292695082182 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7626",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-53/",
"tipo": "puntooss", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.251228630542755, 45.13285315485991 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7623",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-5/",
"tipo": "ed_civile", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.250949680805206, 45.13304142898401 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7621",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-52/",
"tipo": "puntooss", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.249575048685074, 45.13232806545091 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7617",
"titolo": "Chiesa di San Sebastiano", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-sebastiano/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.249329626560211, 45.13174336560933 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7615",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-9/",
"tipo": "ed_civile", "wpid_comun": "6126", "comune": "Solonghello",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.281129896640778, 45.131208804683624 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7609",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-51/",
"tipo": "puntooss", "wpid_comun": "6126", "comune": "Solonghello",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.282251060009003, 45.130874819827625 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7607",
"titolo": "Palazzo Crova", "url_post": "http://www.monferratopaesaggi.org/palazzo-crova/",
"tipo": "ed_civile", "wpid_comun": "6126", "comune": "Solonghello",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.283160328865051, 45.13083129757778 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7605",
"titolo": "Chiesa", "url_post": "http://www.monferratopaesaggi.org/chiesa-6/",
"tipo": "edreligioso", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.302536606788635, 45.0896311173665 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7602",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-50/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.302515149116516, 45.089518445741476 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7579",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-49/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.278593868017197, 45.101684750398476 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7575",
"titolo": "Chiesa di San Giacomo", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-giacomo-2/",
"tipo": "edreligioso", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.279811590909958, 45.10119629258934 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7573",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-48/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.281647562980652, 45.100861185396404 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7568",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-47/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.281750828027725, 45.100393546647574 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7566",
"titolo": "Ex macelleria, ora biblioteca Cesare Pavese", "url_post": "http://www.monferratopaesaggi.org/ex-macelleria-biblioteca-cesare-pavese/",
"tipo": "ed_civile", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.282555490732193, 45.10040963954263 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7560",
"titolo": "Chiesa di San Rocco", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-rocco-3/",
"tipo": "edreligioso", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.285071402788162, 45.100393546647574 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7557",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-46/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.272444903850555, 45.0960653398625 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7555",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-45/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.271048814058304, 45.09543103877767 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7553",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-44/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.27247440814972, 45.095315538418866 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7551",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-43/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.275356441736221, 45.09460833030808 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7547",
"titolo": "Santuario Diocesano", "url_post": "http://www.monferratopaesaggi.org/chiesa-5/",
"tipo": "edreligioso", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.275792300701141, 45.09424667565405 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7545",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-42/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.275668919086456, 45.09406016699232 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7541",
"titolo": "Dimora al Sagittario", "url_post": "http://www.monferratopaesaggi.org/dimora-sagittario/",
"tipo": "ed_civile", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.267877101898193, 45.07955417607216 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7514",
"titolo": "Palazzo Nazzari", "url_post": "http://www.monferratopaesaggi.org/palazzo-nazzari/",
"tipo": "ed_civile", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.262279331684113, 45.08552082627408 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7512",
"titolo": "Ex municipio", "url_post": "http://www.monferratopaesaggi.org/ex-municipio-2/",
"tipo": "ed_civile", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.261820673942566, 45.08533618289795 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7509",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-41/",
"tipo": "puntooss", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.258156776428223, 45.08622530628813 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7507",
"titolo": "Edificio ottocentesco", "url_post": "http://www.monferratopaesaggi.org/edificio-ottocentesco/",
"tipo": "ed_civile", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.22745218873024, 45.064222302530794 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7505",
"titolo": "Chiesa del Santissimo nome di Maria", "url_post": "http://www.monferratopaesaggi.org/chiesa-ss-maria/",
"tipo": "edreligioso", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.227312713861465, 45.06373447156573 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7503",
"titolo": "Villa storica ottocentesca", "url_post": "http://www.monferratopaesaggi.org/villa-storica-ottocentesca/",
"tipo": "ed_civile", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.2497239112854, 45.07511926630938 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7501",
"titolo": "Chiesa di Sant’Antonio", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-antonio/",
"tipo": "edreligioso", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.249286711215973, 45.0736418336492 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7495",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-4/",
"tipo": "ed_civile", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.24075996875763, 45.0751486251611 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7485",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-12/",
"tipo": "puntooss", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.240408599376678, 45.07505297207264 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7483",
"titolo": "Palazzo storico", "url_post": "http://www.monferratopaesaggi.org/palazzo-storico-2/",
"tipo": "ed_civile", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.240084052085876, 45.07355091346867 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7481",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-40/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.188497126102448, 45.13356272746148 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7477",
"titolo": "Ex canonica", "url_post": "http://www.monferratopaesaggi.org/ex-canonica/",
"tipo": "edreligioso", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.188867270946503, 45.13301588429005 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7448",
"titolo": "Chiesa di San Rocco", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-rocco-2/",
"tipo": "edreligioso", "wpid_comun": "6065", "comune": "San Giorgio Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.411833941936493, 45.109759791170035 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7418",
"titolo": "Edificio padronale", "url_post": "http://www.monferratopaesaggi.org/edificio-interessante/",
"tipo": "ed_civile", "wpid_comun": "6065", "comune": "San Giorgio Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.41638296842575, 45.10757147424832 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7406",
"titolo": "Infernot chiesetta Madonna delle Grazie", "url_post": "http://www.monferratopaesaggi.org/infernot-11/",
"tipo": "infernot", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.391210436820984, 45.08510419422044 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7400",
"titolo": "Punto di veduta soprastante viale della Repubblica", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-36/",
"tipo": "puntooss", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.398417532444, 45.0811450911998 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7398",
"titolo": "Castello Bacino", "url_post": "http://www.monferratopaesaggi.org/castello-6/",
"tipo": "edstorico", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.39893251657486, 45.08092255514147 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7396",
"titolo": "Punto di veduta via Bacino nord", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-35/",
"tipo": "puntooss", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.399849832057953, 45.08077672253097 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7394",
"titolo": "Infernot via Bacino", "url_post": "http://www.monferratopaesaggi.org/infernot-10/",
"tipo": "infernot", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.39956283569336, 45.08073126813474 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7392",
"titolo": "Punto di veduta via Bacino sud", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-34/",
"tipo": "puntooss", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.400000035762787, 45.08014319862297 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7389",
"titolo": "Chiesa parrocchiale di San Vittore Martire (fine Quattrocento)", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-s-vittore-martire-quattrocento/",
"tipo": "edreligioso", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.397901207208633, 45.08023505529029 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7387",
"titolo": "Torre civica", "url_post": "http://www.monferratopaesaggi.org/torre-civica-2/",
"tipo": "edstorico", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.397999107837677, 45.080098690700275 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7385",
"titolo": "Parrocchia di Sant’Antonio (XII secolo)", "url_post": "http://www.monferratopaesaggi.org/parrocchia-s-antonio/",
"tipo": "edreligioso", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.398337066173553, 45.080093008835284 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7377",
"titolo": "Punto di veduta termine via Barbano", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-33/",
"tipo": "puntooss", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.3884397149086, 45.07785999215289 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7360",
"titolo": "Monumento ai Caduti (di L. Bistolfi)", "url_post": "http://www.monferratopaesaggi.org/monumento-caduti-l-bistolfi/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.458415865898132, 45.13276232892955 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7354",
"titolo": "Palazzo Gambera-Mellana", "url_post": "http://www.monferratopaesaggi.org/palazzo-gambera-mellana/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.453362584114075, 45.13336783239968 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7352",
"titolo": "Casa Tornielli o Palazzo del Carretto", "url_post": "http://www.monferratopaesaggi.org/casa-tornielli/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45224678516388, 45.13328079167152 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7348",
"titolo": "Infernot via Cascinotto", "url_post": "http://www.monferratopaesaggi.org/infernot-9/",
"tipo": "infernot", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.357822299003601, 45.09892434088164 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7346",
"titolo": "Infernot Regione Savoia", "url_post": "http://www.monferratopaesaggi.org/infernot-8/",
"tipo": "infernot", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.373676836490631, 45.08410615871627 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7343",
"titolo": "Infernot Regione Monti, 4", "url_post": "http://www.monferratopaesaggi.org/infernot-7/",
"tipo": "infernot", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.38207483291626, 45.08078998005641 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7341",
"titolo": "Infernot via Barbano, 22", "url_post": "http://www.monferratopaesaggi.org/infernot-6/",
"tipo": "infernot", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.39093416929245, 45.07478495316008 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7339",
"titolo": "Infernot via Barbano, 37", "url_post": "http://www.monferratopaesaggi.org/infernot-5/",
"tipo": "infernot", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.389528691768646, 45.07581440410355 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7337",
"titolo": "Infernot via Cei, 6", "url_post": "http://www.monferratopaesaggi.org/infernot-4/",
"tipo": "infernot", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.386787474155426, 45.07878995287656 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7335",
"titolo": "Infernot piazza Vallino", "url_post": "http://www.monferratopaesaggi.org/infernot-3/",
"tipo": "infernot", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.390901982784271, 45.075293525079125 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7331",
"titolo": "Infernot via Barbano, 65", "url_post": "http://www.monferratopaesaggi.org/infernot-2/",
"tipo": "infernot", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.38879108428955, 45.07626140922611 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7329",
"titolo": "Infernot Regione Monti, 11", "url_post": "http://www.monferratopaesaggi.org/infernot/",
"tipo": "infernot", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/infenot.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.382407426834106, 45.08081270723567 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7326",
"titolo": "Area pic nic a Cella Monte", "url_post": "http://www.monferratopaesaggi.org/area-pic-nic-2/",
"tipo": "picnic", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/pic-nic.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.388427644968033, 45.07728231035523 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7322",
"titolo": "Punto di veduta retro San Quirico", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-32/",
"tipo": "puntooss", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.388597965240479, 45.07712036899994 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7318",
"titolo": "Punto di veduta sagrato San Quirico", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-31/",
"tipo": "puntooss", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.388337790966034, 45.07707680575 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7316",
"titolo": "Punto di veduta metà via Barbano", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-30/",
"tipo": "puntooss", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.389855921268463, 45.07574716362366 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7308",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-3/",
"tipo": "ed_civile", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.390496969223022, 45.07492322455815 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7306",
"titolo": "EcoMuseo della Pietra da Cantoni", "url_post": "http://www.monferratopaesaggi.org/ecomuseo-pietra-cantoni/",
"tipo": "museo", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.3909972012043, 45.075231966335274 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7298",
"titolo": "Punto di veduta San Rocco", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-29/",
"tipo": "puntooss", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.393383026123047, 45.072677693535745 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7296",
"titolo": "Chiesa di San Rocco", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-rocco/",
"tipo": "edreligioso", "wpid_comun": "6104", "comune": "Cella Monte",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.393364250659943, 45.0726208674812 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7287",
"titolo": "Chiesa di San Francesco", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-francesco/",
"tipo": "edreligioso", "wpid_comun": "6122", "comune": "Sala Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.356917053461075, 45.07664117142408 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7285",
"titolo": "Punto di veduta cinta rocca", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-27/",
"tipo": "puntooss", "wpid_comun": "6122", "comune": "Sala Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.358239382505417, 45.07614397601563 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7282",
"titolo": "Chiesa parrocchiale di San Giacomo", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-s-giacomo/",
"tipo": "edreligioso", "wpid_comun": "6122", "comune": "Sala Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.357222825288773, 45.075566276869566 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7280",
"titolo": "Edificio neoromanico", "url_post": "http://www.monferratopaesaggi.org/edificio-7/",
"tipo": "ed_civile", "wpid_comun": "6122", "comune": "Sala Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.357495069503784, 45.07566761140445 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7273",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-2/",
"tipo": "ed_civile", "wpid_comun": "6122", "comune": "Sala Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.358199149370193, 45.07538444248733 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7233",
"titolo": "Chiesetta di San Quirico", "url_post": "http://www.monferratopaesaggi.org/chiesetta-s-quirico/",
"tipo": "edreligioso", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.356937170028687, 45.1028121632243 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7230",
"titolo": "Chiesa di San Giacomo", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-giacomo/",
"tipo": "edreligioso", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.358818739652634, 45.09719191695657 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7228",
"titolo": "Cantinone con attrezzatura d’epoca per uso vitivinicolo", "url_post": "http://www.monferratopaesaggi.org/cantinone-attrezzatura-depoca-per-uso-vitivinicolo/",
"tipo": "ed_civile", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.359683752059937, 45.09843112608886 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7225",
"titolo": "Area pic nic attrezzata a Treville", "url_post": "http://www.monferratopaesaggi.org/area-pic-nic-attrezzata/",
"tipo": "picnic", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/pic-nic.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.36136281490326, 45.09755639302249 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7216",
"titolo": "Punto di veduta di via G. Marconi", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-26/",
"tipo": "puntooss", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.36063727736473, 45.09739166906264 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7214",
"titolo": "Punto di veduta di via G. Marconi", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-25/",
"tipo": "puntooss", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.360190689563751, 45.09751757879889 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7211",
"titolo": "Punto di veduta del sagrato", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-24/",
"tipo": "puntooss", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.359998911619186, 45.0973358142787 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7208",
"titolo": "Punto di veduta vicolo di via Roma", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-23/",
"tipo": "puntooss", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.360407948493958, 45.09695240284651 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7206",
"titolo": "Scorcio interno su chiesa", "url_post": "http://www.monferratopaesaggi.org/scorcio-interno/",
"tipo": "puntooss", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.360654711723328, 45.09701204479395 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7204",
"titolo": "Punto di veduta di via Roma", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-22/",
"tipo": "puntooss", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.36108922958374, 45.09689465423488 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7202",
"titolo": "Punto di veduta Terrazza delle Rose", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-terrazza-delle-rose/",
"tipo": "puntooss", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.362246602773666, 45.096721408049575 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7200",
"titolo": "Cascina Sinaccio", "url_post": "http://www.monferratopaesaggi.org/cascina-sinaccio/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.373644649982452, 45.12345190380423 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7192",
"titolo": "Cascina del Mago e ingresso galleria", "url_post": "http://www.monferratopaesaggi.org/casacina-mago-ingresso-galleria/",
"tipo": "arc_industriale", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.371252119541168, 45.11840812233264 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7190",
"titolo": "Pozzone Cavallera", "url_post": "http://www.monferratopaesaggi.org/pozzone-cavallera/",
"tipo": "arc_industriale", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.370517194271088, 45.11751666093022 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7185",
"titolo": "Abitazione cavatori", "url_post": "http://www.monferratopaesaggi.org/abitazione-cavatori/",
"tipo": "arc_industriale", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.37033212184906, 45.116600579926676 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7182",
"titolo": "Ruderi stabilimento Unione Cementi Marchino", "url_post": "http://www.monferratopaesaggi.org/ruderi-stabilimento-unione-cementi-marchino/",
"tipo": "arc_industriale", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.368953466415405, 45.11392417638612 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7178",
"titolo": "Ex fabbrica Italcementi", "url_post": "http://www.monferratopaesaggi.org/ex-fabbrica-italcementi/",
"tipo": "arc_industriale", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.368508219718933, 45.10802580300148 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7172",
"titolo": "Complesso di edifici del primo Novecento", "url_post": "http://www.monferratopaesaggi.org/complesso-edifici-novecento/",
"tipo": "ed_civile", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.376929014921188, 45.10727899820021 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7169",
"titolo": "Fornace da calce ex Bargero", "url_post": "http://www.monferratopaesaggi.org/fornace-calce-ex-bargero/",
"tipo": "arc_industriale", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.376946449279785, 45.10627851054934 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7167",
"titolo": "Punto di veduta Largo Pelegano", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-largo-pelegano/",
"tipo": "puntooss", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.37408185005188, 45.10431061281313 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7163",
"titolo": "Chiesetta di San Giovanni Battista", "url_post": "http://www.monferratopaesaggi.org/chiesetta-s-giovanni-battista/",
"tipo": "edreligioso", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.375984877347946, 45.10404841063879 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7161",
"titolo": "Casa Massa ex Calleri", "url_post": "http://www.monferratopaesaggi.org/casa-massa-ex-calleri/",
"tipo": "ed_civile", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.377175778150558, 45.10343596982159 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7159",
"titolo": "Palazzo Squassi", "url_post": "http://www.monferratopaesaggi.org/palazzo-squassi/",
"tipo": "ed_civile", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.377051055431366, 45.103009055875866 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7149",
"titolo": "Parco dei cementieri", "url_post": "http://www.monferratopaesaggi.org/parco-dei-cementieri/",
"tipo": "giardino", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45248281955719, 45.12933354426273 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7147",
"titolo": "Palazzo Langosco", "url_post": "http://www.monferratopaesaggi.org/palazzo-langosco/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.451624512672424, 45.13426850691779 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7145",
"titolo": "Palazzo Ardizzone – D’Arco", "url_post": "http://www.monferratopaesaggi.org/palazzo-ardizzone-darco/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.449049592018127, 45.13885869848592 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7143",
"titolo": "Ospizio di carità – ora Casa di riposo", "url_post": "http://www.monferratopaesaggi.org/ospizio-carita/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.455610275268555, 45.13528647905952 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7141",
"titolo": "Monastero di San Bartolomeo e San Marco", "url_post": "http://www.monferratopaesaggi.org/monastero-san-bartolomeo/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45445692539215, 45.139172770635014 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7139",
"titolo": "Chiesa del Santissimo Crocefisso e Beata Vergine Addolorata", "url_post": "http://www.monferratopaesaggi.org/chiesa-santissimo-crocefisso-beata-vergine-addolorata/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45698893070221, 45.13767429036052 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7137",
"titolo": "Chiesa di San Michele (primi ‘500)", "url_post": "http://www.monferratopaesaggi.org/chiesa-san-michele-primi-500/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45283418893814, 45.13651918493831 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7134",
"titolo": "Chiesa di San Filippo Neri", "url_post": "http://www.monferratopaesaggi.org/chiesa-san-filippo-1728/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45497727394104, 45.13760996078033 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7132",
"titolo": "Chiesa di Sant’Antonio Abate", "url_post": "http://www.monferratopaesaggi.org/chiesa-santantonio-abate/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45345914363861, 45.133996035455056 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7130",
"titolo": "Villa Braccio", "url_post": "http://www.monferratopaesaggi.org/villa-braccio/",
"tipo": "ed_civile", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.37555706501007, 45.103120754289776 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7126",
"titolo": "Casa Barbano", "url_post": "http://www.monferratopaesaggi.org/casa-barbano/",
"tipo": "ed_civile", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.376761376857758, 45.10269857100106 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7124",
"titolo": "Casa Bonaria-Simonetti", "url_post": "http://www.monferratopaesaggi.org/casa-bonaria-simonetti/",
"tipo": "ed_civile", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.376232981681824, 45.102404176770605 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7114",
"titolo": "Info point", "url_post": "http://www.monferratopaesaggi.org/info-point-2/",
"tipo": "info", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/info.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.373676836490631, 45.10200186708772 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7112",
"titolo": "Museo del Cavatore", "url_post": "http://www.monferratopaesaggi.org/museo-cavatore/",
"tipo": "museo", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.375414907932281, 45.100988980744376 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7108",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio/",
"tipo": "ed_civile", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.376278579235077, 45.101925191273565 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7105",
"titolo": "Info point", "url_post": "http://www.monferratopaesaggi.org/info-point/",
"tipo": "info", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/info.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.376380503177643, 45.10188070032186 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7103",
"titolo": "Villa ottocentesca", "url_post": "http://www.monferratopaesaggi.org/villa-ottocentesca/",
"tipo": "ed_civile", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.377056419849396, 45.100619793403105 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7101",
"titolo": "Chiesa di Santa Maria Assunta", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-maria-assunta/",
"tipo": "edreligioso", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.377281725406647, 45.10011428686368 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7098",
"titolo": "Ex asilo", "url_post": "http://www.monferratopaesaggi.org/ex-asilo/",
"tipo": "ed_civile", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.167020678520203, 45.072247708319225 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7094",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-19/",
"tipo": "puntooss", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.167803883552551, 45.07229032814372 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7092",
"titolo": "Chiesa della Santissima Trinità", "url_post": "http://www.monferratopaesaggi.org/chiesa-ss-trinita/",
"tipo": "edreligioso", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.167837411165237, 45.072169098337326 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7090",
"titolo": "Villa Feltrinelli", "url_post": "http://www.monferratopaesaggi.org/villa-feltrinelli/",
"tipo": "ed_civile", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.167675137519836, 45.073176813287205 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7088",
"titolo": "Chiesa parrocchiale dei Santi Remigio, Grato e Maria Assunta", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-dei-ss-remigio-grato-maria-assunta/",
"tipo": "edreligioso", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.168654143810272, 45.07241061058806 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7084",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-18/",
"tipo": "puntooss", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.16932201385498, 45.072479749201335 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7082",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-17/",
"tipo": "puntooss", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.169312626123428, 45.07234810163281 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7080",
"titolo": "Museo Labar", "url_post": "http://www.monferratopaesaggi.org/museo-labar/",
"tipo": "museo", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.167453855276108, 45.07166333996469 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7078",
"titolo": "Palazzo Labar", "url_post": "http://www.monferratopaesaggi.org/palazzo-labar/",
"tipo": "ed_civile", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.167522251605988, 45.07166807555074 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7076",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-16/",
"tipo": "puntooss", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.167487382888794, 45.071463497875996 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7074",
"titolo": "Chiesa di San Remigio", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-remigio/",
"tipo": "edreligioso", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.165843188762665, 45.07087438585165 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7072",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-15/",
"tipo": "puntooss", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.16465362906456, 45.0706925365405 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7066",
"titolo": "Parco giochi", "url_post": "http://www.monferratopaesaggi.org/parco-giochi/",
"tipo": "giardino", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.160650432109833, 45.052200556180004 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7062",
"titolo": "Area pic nic a Odalengo Piccolo", "url_post": "http://www.monferratopaesaggi.org/area-pic-nic/",
"tipo": "picnic", "wpid_comun": "6112", "comune": "Odalengo Piccolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/pic-nic.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.209482729434967, 45.078878023728755 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7060",
"titolo": "Osservatorio astronomico di Odalengo Piccolo", "url_post": "http://www.monferratopaesaggi.org/osservatorio-astronomico/",
"tipo": "museo", "wpid_comun": "6112", "comune": "Odalengo Piccolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.20942372083664, 45.07824637278429 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "7055",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-14/",
"tipo": "puntooss", "wpid_comun": "6112", "comune": "Odalengo Piccolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.202058374881744, 45.07506623092613 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6989",
"titolo": "Chiesa di San Pietro", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-pietro/",
"tipo": "edreligioso", "wpid_comun": "6112", "comune": "Odalengo Piccolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.209779113531113, 45.071067600110815 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6987",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-13/",
"tipo": "puntooss", "wpid_comun": "6112", "comune": "Odalengo Piccolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.218446671962738, 45.07123429424094 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6985",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-12/",
"tipo": "puntooss", "wpid_comun": "6112", "comune": "Odalengo Piccolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.217105567455292, 45.07009015656458 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6979",
"titolo": "Castello", "url_post": "http://www.monferratopaesaggi.org/castello-4/",
"tipo": "edstorico", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.167543709278107, 45.10993205131024 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6954",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-11/",
"tipo": "puntooss", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.167482018470764, 45.1096140321838 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6951",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-10/",
"tipo": "puntooss", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.168206214904785, 45.10944934301119 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6896",
"titolo": "Chiesa di San Filippo", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-filippo/",
"tipo": "edreligioso", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.139214217662811, 45.1377840288887 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6893",
"titolo": "Punto di veduta Case Curto", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-case-curto/",
"tipo": "puntooss", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.151415586471558, 45.143352035933006 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6885",
"titolo": "Monastero di Santa Liberata", "url_post": "http://www.monferratopaesaggi.org/monastero-s-liberata/",
"tipo": "edreligioso", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.179108053445816, 45.13361949288822 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6879",
"titolo": "Punto di veduta Borgata Monterizzolo", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-borgata-monterizzolo/",
"tipo": "puntooss", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.17582905292511, 45.14085662193237 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6861",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-10/",
"tipo": "puntooss", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.169580847024918, 45.134812499867614 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6856",
"titolo": "Punto di veduta Colle di Monte Croce", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-colle-monte-croce/",
"tipo": "puntooss", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.160567283630371, 45.13027969748921 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6854",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-9/",
"tipo": "puntooss", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.100952506065369, 45.10200754677355 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6845",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-9/",
"tipo": "puntooss", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.09837356209755, 45.101631739675625 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6843",
"titolo": "Casale Armanda", "url_post": "http://www.monferratopaesaggi.org/casale-armanda/",
"tipo": "ed_civile", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.097425401210785, 45.10101169988739 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6841",
"titolo": "Parco giochi con panchine", "url_post": "http://www.monferratopaesaggi.org/parco-giochi-panchine/",
"tipo": "giardino", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.096730709075928, 45.10035946756066 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6839",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-8/",
"tipo": "puntooss", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.095987737178802, 45.09959362938214 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6836",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punt-panoramico/",
"tipo": "puntooss", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.105936050415039, 45.09659833666965 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6737",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-5/",
"tipo": "ed_civile", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.097100853919983, 45.10037366718268 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6702",
"titolo": "Chiesa di San Martino", "url_post": "http://www.monferratopaesaggi.org/chiesa-2/",
"tipo": "edreligioso", "wpid_comun": "6108", "comune": "Murisengo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.120293915271759, 45.097590473782454 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6698",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-8/",
"tipo": "puntooss", "wpid_comun": "6108", "comune": "Murisengo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.120119571685791, 45.097381255462984 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6674",
"titolo": "Casa Cormanni", "url_post": "http://www.monferratopaesaggi.org/casa-cormanni/",
"tipo": "ed_civile", "wpid_comun": "6108", "comune": "Murisengo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.13968226313591, 45.08516952990247 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6672",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-7/",
"tipo": "puntooss", "wpid_comun": "6108", "comune": "Murisengo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.139833807945251, 45.08553029514906 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6635",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-4/",
"tipo": "ed_civile", "wpid_comun": "6108", "comune": "Murisengo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.14018115401268, 45.08480876237753 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6630",
"titolo": "Architettura primi ‘900", "url_post": "http://www.monferratopaesaggi.org/architettura-primi-900/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.441889435052872, 45.13582951624541 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6624",
"titolo": "Ex asilo Lavazza", "url_post": "http://www.monferratopaesaggi.org/ex-asilo-lavazza-2/",
"tipo": "ed_civile", "wpid_comun": "6108", "comune": "Murisengo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.138870894908905, 45.08498299159792 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6589",
"titolo": "Chiesa di San Pietro", "url_post": "http://www.monferratopaesaggi.org/chiesa-san-pietro/",
"tipo": "edreligioso", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.189352750778198, 45.15430672714695 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6572",
"titolo": "Casetta dell’acqua", "url_post": "http://www.monferratopaesaggi.org/casetta-dellacqua/",
"tipo": "none", "wpid_comun": "6108", "comune": "Murisengo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.135662972927094, 45.07976724763159 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6561",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-5/",
"tipo": "puntooss", "wpid_comun": "6108", "comune": "Murisengo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.135913693822658, 45.07848771138267 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6546",
"titolo": "Ex cava di gesso", "url_post": "http://www.monferratopaesaggi.org/ex-cava-gesso/",
"tipo": "none", "wpid_comun": "6108", "comune": "Murisengo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.13686728477478, 45.07858540069607 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6527",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-4/",
"tipo": "puntooss", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.28392744064331, 45.15986744653748 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6520",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-3/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.192328661680222, 45.15877898788882 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6476",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-3/",
"tipo": "ed_civile", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.160889148712158, 45.15466421828598 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6473",
"titolo": "Arenaria (pietra da cantone)", "url_post": "http://www.monferratopaesaggi.org/banco-arenaria/",
"tipo": "none", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.162442147731781, 45.1548022962737 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6469",
"titolo": "Cascina", "url_post": "http://www.monferratopaesaggi.org/cascina/",
"tipo": "ed_civile", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.183905184268951, 45.15778129466892 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6466",
"titolo": "Parco storico del Basso Monferrato", "url_post": "http://www.monferratopaesaggi.org/parco-storico-basso-monferrato/",
"tipo": "museo", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.189874440431595, 45.156384494812926 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6463",
"titolo": "Castello di Gabiano", "url_post": "http://www.monferratopaesaggi.org/castello-gabiano/",
"tipo": "edstorico", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.19265991449356, 45.15976909839159 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6461",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edifici/",
"tipo": "ed_civile", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.192844986915588, 45.159127939972045 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6459",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-2/",
"tipo": "ed_civile", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.192968368530273, 45.15843759909436 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6457",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-2/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.193220496177673, 45.158688203256695 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6455",
"titolo": "Villa del Novecento", "url_post": "http://www.monferratopaesaggi.org/villa-novecento-2/",
"tipo": "ed_civile", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.193530291318893, 45.15864281088638 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6453",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.194765448570251, 45.15865510465693 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6449",
"titolo": "Villa del Novecento", "url_post": "http://www.monferratopaesaggi.org/villa-novecento/",
"tipo": "ed_civile", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.195360898971558, 45.158223875428476 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6441",
"titolo": "Museo di Colombotto Rosso", "url_post": "http://www.monferratopaesaggi.org/museo-colombotto-rosso/",
"tipo": "museo", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.332498222589493, 45.14357905832152 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6439",
"titolo": "Museo dei giocattoli", "url_post": "http://www.monferratopaesaggi.org/museo-dei-giocattoli/",
"tipo": "museo", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.332574665546417, 45.14360932790502 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6437",
"titolo": "Edifici di origine rurale", "url_post": "http://www.monferratopaesaggi.org/edificio/",
"tipo": "ed_civile", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.33261489868164, 45.141847989774966 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6435",
"titolo": "Chiesa e oratorio di San Giacomo", "url_post": "http://www.monferratopaesaggi.org/chiesa-oratorio-s-giacomo/",
"tipo": "edreligioso", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.333011865615845, 45.142846907875054 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6417",
"titolo": "Cornale", "url_post": "http://www.monferratopaesaggi.org/cornale/",
"tipo": "none", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.291845321655273, 45.15976909839159 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6352",
"titolo": "Area ex Eternit", "url_post": "http://www.monferratopaesaggi.org/area-ex-eternit/",
"tipo": "arc_industriale", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.4309983253479, 45.13538865369851 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6337",
"titolo": "Chiesa di San Sebastiano", "url_post": "http://www.monferratopaesaggi.org/chiesa/",
"tipo": "edreligioso", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.214206099510193, 45.12105592662694 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6335",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-4/",
"tipo": "puntooss", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.215850293636322, 45.12083543867924 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6331",
"titolo": "Municipio e info point", "url_post": "http://www.monferratopaesaggi.org/municipio-info-point/",
"tipo": "ed_civile", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.215174376964569, 45.12022223166644 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6329",
"titolo": "Casaforte", "url_post": "http://www.monferratopaesaggi.org/casaforte/",
"tipo": "edstorico", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.21545735001564, 45.12020898329405 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6326",
"titolo": "Chiesa parrocchiale dei Santi Nazario e Celso", "url_post": "http://www.monferratopaesaggi.org/chke/",
"tipo": "edreligioso", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.21579396724701, 45.120359446771 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6304",
"titolo": "La Furnasetta", "url_post": "http://www.monferratopaesaggi.org/furnasetta/",
"tipo": "arc_industriale", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.447622656822205, 45.12686211799634 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6302",
"titolo": "Cittadella", "url_post": "http://www.monferratopaesaggi.org/cittadella/",
"tipo": "edstorico", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.458560705184937, 45.12753202512801 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6300",
"titolo": "Paraboloide", "url_post": "http://www.monferratopaesaggi.org/paraboloide/",
"tipo": "arc_industriale", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.454934358596802, 45.13046892625109 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6294",
"titolo": "Palazzo Biandrà di Reaglie", "url_post": "http://www.monferratopaesaggi.org/palazzo/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.447762131690979, 45.14021525072857 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6292",
"titolo": "Ex panificio Militare", "url_post": "http://www.monferratopaesaggi.org/ex-panificio/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.447983413934708, 45.140020378402745 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6290",
"titolo": "Chiesa di Sant’Ilario", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-ilario/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448132276535034, 45.13950576090363 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6288",
"titolo": "Palazzo Scozia di Calliano", "url_post": "http://www.monferratopaesaggi.org/palazzo-scoria-calliano/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.447933793067932, 45.138919242649266 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6284",
"titolo": "Punto informazioni", "url_post": "http://www.monferratopaesaggi.org/punto-informazioni/",
"tipo": "info", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/info.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448440730571747, 45.13745670472327 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6282",
"titolo": "Teatro municipale", "url_post": "http://www.monferratopaesaggi.org/teatro-municipale/",
"tipo": "teatro", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/teatro.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448397815227509, 45.13782186971153 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6280",
"titolo": "Palazzo Sacchi Nemour di Frassinello", "url_post": "http://www.monferratopaesaggi.org/palazzo-sacchi-nemour-frassinello/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.4486123919487, 45.13772348351998 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6278",
"titolo": "Chiesa di Santo Stefano", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-stefano/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.449883759021759, 45.1372703372347 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6276",
"titolo": "Torre civica", "url_post": "http://www.monferratopaesaggi.org/torre-civica/",
"tipo": "edstorico", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.450168073177338, 45.13732426088537 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6274",
"titolo": "Chiesa di Santa Caterina (Santa Maria delle Grazie)", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-caterina/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.448411226272583, 45.1365428359801 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6272",
"titolo": "Palazzo Anna d’Alençon", "url_post": "http://www.monferratopaesaggi.org/palazzo-anna-dalencon/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.4479458630085, 45.13598656087873 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6270",
"titolo": "Palazzo Vitta", "url_post": "http://www.monferratopaesaggi.org/palazzo-vitta/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.449911922216415, 45.13651918493831 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6268",
"titolo": "Edificio di fine Settecento", "url_post": "http://www.monferratopaesaggi.org/edificio-settecento/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.450206965208054, 45.13593358201463 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6266",
"titolo": "Sinagoga e Museo Ebraico", "url_post": "http://www.monferratopaesaggi.org/sinagoga-museo-israelitico/",
"tipo": "museo", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.449814021587372, 45.13551447962277 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6264",
"titolo": "Ex chiesa di Santa Croce", "url_post": "http://www.monferratopaesaggi.org/santa-croce/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.450925797224045, 45.1350556393863 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6262",
"titolo": "Museo civico e gipsoteca", "url_post": "http://www.monferratopaesaggi.org/museo-civico-gipsoteca/",
"tipo": "museo", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.451628535985947, 45.13495535628631 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6260",
"titolo": "Palazzo Gaspardone – Ottavi", "url_post": "http://www.monferratopaesaggi.org/palazzo-gaspardoni/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.451471626758575, 45.13518051998129 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6258",
"titolo": "Dimora del governatore Gonzaga", "url_post": "http://www.monferratopaesaggi.org/dimora-governatore-gonzaga/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45185250043869, 45.1351010505434 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6256",
"titolo": "Istituto Leardi", "url_post": "http://www.monferratopaesaggi.org/scuola-leardi/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45272958278656, 45.13393927040312 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6254",
"titolo": "Ex convento francescani", "url_post": "http://www.monferratopaesaggi.org/ex-convento-francescani/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.453432321548462, 45.13461666300346 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6247",
"titolo": "Palazzo Gozzani di San Giorgio", "url_post": "http://www.monferratopaesaggi.org/palazzo-s-giorgio/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.452856987714767, 45.135026311328126 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6245",
"titolo": "Chiesa di San Paolo dei Barnabiti e convento", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-paolo-dei-barnabiti-convento/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.453185558319092, 45.135138893146674 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6243",
"titolo": "Palazzo Magnacavalli", "url_post": "http://www.monferratopaesaggi.org/palazzo-magnacavalli/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.453027307987213, 45.135566512818556 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6239",
"titolo": "Palazzo del Vescovado", "url_post": "http://www.monferratopaesaggi.org/palazzo-vescovado/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.453603982925415, 45.13717100406048 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6235",
"titolo": "Chiesa dei Santi Pietro e Paolo", "url_post": "http://www.monferratopaesaggi.org/chiesa-dei-santi-pietro-paolo/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.452665209770203, 45.13818324830433 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6233",
"titolo": "Palazzo la Rosa Rossa", "url_post": "http://www.monferratopaesaggi.org/palazzo-rosa-rossa/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.452042937278748, 45.13819081641791 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6231",
"titolo": "Casa Taricco", "url_post": "http://www.monferratopaesaggi.org/casa-taricco/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.451839089393616, 45.13847556596163 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6229",
"titolo": "Ex chiesa della Misericordia", "url_post": "http://www.monferratopaesaggi.org/confraternita-misericordia/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45173716545105, 45.138802884278384 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6227",
"titolo": "Chiesa di San Domenico", "url_post": "http://www.monferratopaesaggi.org/chiesa-san-domenico/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.451995998620987, 45.13900722077203 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6225",
"titolo": "Chiostro", "url_post": "http://www.monferratopaesaggi.org/chiostro/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.452276289463043, 45.13919547457874 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6223",
"titolo": "Palazzo della Misericordia", "url_post": "http://www.monferratopaesaggi.org/palazzo-misericordia/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.451073318719864, 45.13911128074203 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6221",
"titolo": "San Pietro Martire (Santa Rita)", "url_post": "http://www.monferratopaesaggi.org/santa-rita/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45161110162735, 45.139237098452085 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6219",
"titolo": "Palazzo Morelli", "url_post": "http://www.monferratopaesaggi.org/palazzo-morelli/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.45099151134491, 45.13954360058383 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6217",
"titolo": "Palazzo Scorza – ex ospedale di Santo Spirito", "url_post": "http://www.monferratopaesaggi.org/ex-ospedale/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.450707197189331, 45.13969495905352 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6214",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-3/",
"tipo": "puntooss", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.26073169708252, 45.08492996536971 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6210",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta-2/",
"tipo": "puntooss", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.260482251644135, 45.085454544105154 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6206",
"titolo": "Villa Vittorio Veneto o castello dei Conti Cavallero", "url_post": "http://www.monferratopaesaggi.org/villa-vittorio-veneto-castello-dei-conti-cavallero/",
"tipo": "ed_civile", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.260581493377686, 45.085702628399744 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "6003",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-veduta/",
"tipo": "puntooss", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.168753385543823, 45.07230074631803 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5893",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-28/",
"tipo": "puntooss", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.311361, 45.056145 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5894",
"titolo": "Cippo", "url_post": "http://www.monferratopaesaggi.org/cippo-6/",
"tipo": "none", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.321738958335914, 45.05235862431945 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5896",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-149/",
"tipo": "puntooss", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.32470255092619, 45.050354832798725 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5904",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-29/",
"tipo": "puntooss", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.457997, 45.048241 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5906",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-del-cimitero-6/",
"tipo": "puntooss", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.454194, 45.022743 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5908",
"titolo": "Castello dei primi del ‘900", "url_post": "http://www.monferratopaesaggi.org/castello-dei-primi-del-900-6/",
"tipo": "edstorico", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.444278, 45.022266 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5912",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-30/",
"tipo": "puntooss", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.362972, 45.041512 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5915",
"titolo": "Fontanella", "url_post": "http://www.monferratopaesaggi.org/fontanella-6/",
"tipo": "none", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.345882, 45.051308 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5863",
"titolo": "Punto di veduta Belvedere Melvin Jones", "url_post": "http://www.monferratopaesaggi.org/punto-belvedere-5/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.395464, 45.010170 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5864",
"titolo": "Casa del serpentello", "url_post": "http://www.monferratopaesaggi.org/casa-particolare-3/",
"tipo": "ed_civile", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.395368, 45.009480 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5866",
"titolo": "Punto di veduta piazza Italia", "url_post": "http://www.monferratopaesaggi.org/visuale-panoramica-piazza-italia-3/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.394306, 45.009838 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5867",
"titolo": "Punto di veduta SP68", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-regione-san-bernardo-3/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.412995, 45.016552 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5868",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/monumento-ai-caduti-di-camagna-3/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.427919, 45.011669 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5869",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/visuale-panoramica-ingresso-camagna-3/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.427329, 45.013538 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5871",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/visuale-panoramica-da-zona-bar-3/",
"tipo": "puntooss", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.428665, 45.018024 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5879",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/scorcio-panoramico-chiesa-s-giacomo-3/",
"tipo": "puntooss", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.486391, 45.002941 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5880",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-terrazza-mephisto-3/",
"tipo": "puntooss", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.485544, 45.003006 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5881",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-stradina-dissestata-3/",
"tipo": "puntooss", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.485125, 45.002983 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5886",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-semi-panoramico-chiesa-san-nazario-3/",
"tipo": "puntooss", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.483865, 45.000870 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5887",
"titolo": "Antico Monastero", "url_post": "http://www.monferratopaesaggi.org/antico-monastero-3/",
"tipo": "edreligioso", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.483398, 45.000481 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5833",
"titolo": "Municipio – ex convento", "url_post": "http://www.monferratopaesaggi.org/municipio-ex-convento-3/",
"tipo": "ed_civile", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.263441, 45.051407 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5834",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/belvedere-di-fronte-a-casa-ferraris-e-acquedotto-3/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.261187440475396, 45.05226510246632 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5836",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-cimitero-moncalvo-3/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.269165, 45.047649 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5839",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/visuale-panoramica-7/",
"tipo": "puntooss", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.313662, 45.039555 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5840",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/visuale-panoramica-8/",
"tipo": "puntooss", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.313925, 45.039478 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5842",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/visuale-panoramica-9/",
"tipo": "puntooss", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.314011, 45.039989 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5844",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/visuale-panoramica-zona-madonna-dei-monti-3/",
"tipo": "puntooss", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.316468, 45.053471 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5847",
"titolo": "Cantina sociale Moncalvo", "url_post": "http://www.monferratopaesaggi.org/cantina-sociale-moncalvo-3/",
"tipo": "none", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.270237, 45.052013 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5850",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-sotto-chiesa-5/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.333736, 45.023037 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5851",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-piazza-del-popolo-3/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.334696, 45.022442 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5852",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-torrione-3/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.333875262565584, 45.0236630417558 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5854",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-casorzo-3/",
"tipo": "ed_civile", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.33425071163947, 45.02283941578076 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5855",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-sotto-chiesa-6/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.333929, 45.023136 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5856",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-vicino-municipio-casorzo-3/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.334058, 45.022972 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5857",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/visuale-panoramica-parco-rimembranza-3/",
"tipo": "puntooss", "wpid_comun": "6079", "comune": "Casorzo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.340039, 45.022579 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5860",
"titolo": "Punto di veduta chiesa di San Bartolomeo", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-da-chiesa-di-vignale-3/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.396401, 45.011616 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5861",
"titolo": "Enoteca Regionale", "url_post": "http://www.monferratopaesaggi.org/enoteca-regionale-3/",
"tipo": "none", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.396301067459035, 45.01004090408682 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5862",
"titolo": "Giardino pubblico comunale (parco giochi)", "url_post": "http://www.monferratopaesaggi.org/parco-giochi-3/",
"tipo": "giardino", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.396569, 45.010151 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5808",
"titolo": "Resti di edifici industriali (XX secolo)", "url_post": "http://www.monferratopaesaggi.org/segnaposto-43-3/",
"tipo": "arc_industriale", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.434448, 45.134987 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5812",
"titolo": "Stazione idraulica con ponte sul canale", "url_post": "http://www.monferratopaesaggi.org/edificio-primi-900-6/",
"tipo": "arc_industriale", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.439367, 45.135757 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5813",
"titolo": "Diga e veduta sul Po", "url_post": "http://www.monferratopaesaggi.org/diga-e-veduta-sul-po-3/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.417351, 45.136932 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5815",
"titolo": "Architettura contemporanea", "url_post": "http://www.monferratopaesaggi.org/edificio-scolatstico-3/",
"tipo": "none", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.436457, 45.135078 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5816",
"titolo": "Palazzina primi ‘900", "url_post": "http://www.monferratopaesaggi.org/palazzina-primi-900-3/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.431775, 45.134209 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5817",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-chiesa-s-giorgio-zanco-3/",
"tipo": "puntooss", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.161596787696908, 45.050290735402484 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5818",
"titolo": "Castello di Razzano", "url_post": "http://www.monferratopaesaggi.org/castello-di-razzano-3/",
"tipo": "edstorico", "wpid_comun": "6077", "comune": "Alfiano Natta",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.19979690674586, 45.040513284114816 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5819",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-cimitero-di-sanico-3/",
"tipo": "puntooss", "wpid_comun": "6077", "comune": "Alfiano Natta",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.223191440475489, 45.03452665491 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5820",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-pratone-frazione-castelmerlino-3/",
"tipo": "puntooss", "wpid_comun": "6077", "comune": "Alfiano Natta",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.225048, 45.029392 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5821",
"titolo": "Punto di veduta Belvedere", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-belvedere-alfiano-3/",
"tipo": "puntooss", "wpid_comun": "6077", "comune": "Alfiano Natta",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.206015, 45.051991 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5823",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/visuale-panoramica-in-fondo-a-via-testafochi-3/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.264020, 45.050137 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5829",
"titolo": "Portici", "url_post": "http://www.monferratopaesaggi.org/portici-3/",
"tipo": "none", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.266410, 45.052124 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5784",
"titolo": "Villa Sordi", "url_post": "http://www.monferratopaesaggi.org/villa-sordi-3/",
"tipo": "ed_civile", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.390942, 45.139374 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5785",
"titolo": "Sopravia di protezione per passaggio teleferica", "url_post": "http://www.monferratopaesaggi.org/reperto-di-archeologia-industriale-3/",
"tipo": "arc_industriale", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.387765, 45.139820 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5786",
"titolo": "Area verde Coniolo fiori", "url_post": "http://www.monferratopaesaggi.org/area-verde-coniolo-fiori-3/",
"tipo": "giardino", "wpid_comun": "6135", "comune": "Coniolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.374507, 45.147423 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5788",
"titolo": "Totem percorso Cemento", "url_post": "http://www.monferratopaesaggi.org/totem-percorso-cemento-3/",
"tipo": "none", "wpid_comun": "6135", "comune": "Coniolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.372273, 45.147194 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5792",
"titolo": "Cascina Bagiana", "url_post": "http://www.monferratopaesaggi.org/cascina-bagiana-3/",
"tipo": "ed_civile", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.334011, 45.134472 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5793",
"titolo": "Ex mulino", "url_post": "http://www.monferratopaesaggi.org/ex-mulino-3/",
"tipo": "arc_industriale", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.335336, 45.139297 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5794",
"titolo": "Edificio civile", "url_post": "http://www.monferratopaesaggi.org/edificio-25/",
"tipo": "ed_civile", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.335630, 45.141464 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5795",
"titolo": "Monumento ai caduti", "url_post": "http://www.monferratopaesaggi.org/monumento-ai-caduti-3/",
"tipo": "none", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.335140, 45.142197 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5796",
"titolo": "Edificio con palinsesto di scritte", "url_post": "http://www.monferratopaesaggi.org/edificio-26/",
"tipo": "ed_civile", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.334981, 45.142315 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5799",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-41/",
"tipo": "ed_civile", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.332725, 45.143623 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5800",
"titolo": "Museo etnografico", "url_post": "http://www.monferratopaesaggi.org/museo-coniolo-3/",
"tipo": "museo", "wpid_comun": "6135", "comune": "Coniolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/museo.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.372113, 45.146816 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5803",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-148/",
"tipo": "puntooss", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.357686, 45.143227 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5761",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-24/",
"tipo": "ed_civile", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.262191, 45.156410 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5763",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/sosta-per-veduta-3/",
"tipo": "puntooss", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.253254, 45.160923 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5766",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-146/",
"tipo": "none", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.225635, 45.160011 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5769",
"titolo": "Teatro Verdi", "url_post": "http://www.monferratopaesaggi.org/teatro-verdi-3/",
"tipo": "teatro", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/teatro.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.333530, 45.143593 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5771",
"titolo": "Laghetto", "url_post": "http://www.monferratopaesaggi.org/laghetto-3/",
"tipo": "none", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.339782, 45.140995 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5772",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-147/",
"tipo": "puntooss", "wpid_comun": "6135", "comune": "Coniolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.363973, 45.146652 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5774",
"titolo": "Punto di veduta con belvedere", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-con-belvedere-3/",
"tipo": "puntooss", "wpid_comun": "6135", "comune": "Coniolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.368160, 45.147938 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5744",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-142/",
"tipo": "none", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.196552, 45.158112 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5751",
"titolo": "Reperto archeologia industriale", "url_post": "http://www.monferratopaesaggi.org/reperto-archeologia-industriale-3/",
"tipo": "arc_industriale", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.295411, 45.151470 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5752",
"titolo": "Residenza primi ‘900", "url_post": "http://www.monferratopaesaggi.org/residenza-primi-900-3/",
"tipo": "ed_civile", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.291832, 45.159294 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5753",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/scorcio-5/",
"tipo": "puntooss", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.29219291534423, 45.16015626079647 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5754",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/scorcio-6/",
"tipo": "puntooss", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.290995, 45.163815 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5755",
"titolo": "Edificio residenziale", "url_post": "http://www.monferratopaesaggi.org/edificio-residenziale-3/",
"tipo": "ed_civile", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.277156, 45.168941 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5757",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-143/",
"tipo": "puntooss", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.287288, 45.162075 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5759",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-144/",
"tipo": "puntooss", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.283887, 45.162788 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5760",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-145/",
"tipo": "puntooss", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.276997, 45.162365 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5721",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-140/",
"tipo": "puntooss", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.277302, 45.168671 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5726",
"titolo": "Parrocchiale", "url_post": "http://www.monferratopaesaggi.org/parrocchiale-3/",
"tipo": "edreligioso", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265039, 45.172134 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5727",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-parrocchiale-9/",
"tipo": "puntooss", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265055, 45.172287 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5729",
"titolo": "Villetta", "url_post": "http://www.monferratopaesaggi.org/villetta-6/",
"tipo": "ed_civile", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.264779, 45.170532 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5734",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-141/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.236613, 45.153027 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5737",
"titolo": "Locanda del Rubino", "url_post": "http://www.monferratopaesaggi.org/locanda-del-rubino-6/",
"tipo": "ed_civile", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.226276, 45.159378 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5738",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-con-papere-e-galline-6/",
"tipo": "none", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.224200, 45.159958 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5740",
"titolo": "Punto di veduta Belvedere di Cantavenna", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-belvedere-di-cantavenna-6/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.219672, 45.159779 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5743",
"titolo": "Punto di veduta Belvedere “Le rocche di Zoalengo”", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-belvedere-le-rocche-di-zoalengo-6/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.206717, 45.156937 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5705",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-138/",
"tipo": "puntooss", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.281098, 45.160847 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5707",
"titolo": "Castello", "url_post": "http://www.monferratopaesaggi.org/castello-9/",
"tipo": "edstorico", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.281028, 45.162136 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5708",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-139/",
"tipo": "puntooss", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.282246, 45.160831 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5709",
"titolo": "Cappelletta settecentesca", "url_post": "http://www.monferratopaesaggi.org/cappelletta-3/",
"tipo": "edreligioso", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.283804, 45.162704 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5710",
"titolo": "Casa dei primi ‘900", "url_post": "http://www.monferratopaesaggi.org/casa-6/",
"tipo": "ed_civile", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.286159, 45.162460 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5711",
"titolo": "Edificio primi ‘900", "url_post": "http://www.monferratopaesaggi.org/edificio-23/",
"tipo": "ed_civile", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.287637, 45.162045 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5690",
"titolo": "Palazzo", "url_post": "http://www.monferratopaesaggi.org/palazzo-21/",
"tipo": "ed_civile", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.152537, 45.156277 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5694",
"titolo": "Fabbrica", "url_post": "http://www.monferratopaesaggi.org/fabbrica-3/",
"tipo": "ed_civile", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.176143, 45.159706 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5697",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-137/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.189235, 45.154083 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5698",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/casetta-3/",
"tipo": "ed_civile", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.190008396329858, 45.15583306259851 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5677",
"titolo": "Punto di veduta di via Circonvallazione", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-136/",
"tipo": "puntooss", "wpid_comun": "6129", "comune": "Treville",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.361531559524565, 45.09741145589293 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5681",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-parrocchiale-8/",
"tipo": "puntooss", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.160591, 45.155212 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5683",
"titolo": "Municipio – Palazzo Giustiniani", "url_post": "http://www.monferratopaesaggi.org/municipio-40/",
"tipo": "ed_civile", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.158279, 45.154930 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5684",
"titolo": "Ruderi", "url_post": "http://www.monferratopaesaggi.org/stalle-6/",
"tipo": "none", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.158902, 45.154972 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5685",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-comune-6/",
"tipo": "puntooss", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.158354, 45.155060 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5687",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-22/",
"tipo": "ed_civile", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.160173, 45.154812 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5651",
"titolo": "Punto di veduta strada Baldovina 2", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-133/",
"tipo": "puntooss", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.380943, 45.124214 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5653",
"titolo": "Reperto archeologia industriale", "url_post": "http://www.monferratopaesaggi.org/parte-di-traliccio-vecchio-3/",
"tipo": "arc_industriale", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/arch_industriale.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.385984201223437, 45.12667310758963 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5622",
"titolo": "Villa", "url_post": "http://www.monferratopaesaggi.org/villa-10/",
"tipo": "ed_civile", "wpid_comun": "6075", "comune": "Camagna Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.419788, 45.033539 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5624",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-26/",
"tipo": "puntooss", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.362972, 45.041512 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5630",
"titolo": "Punto di veduta castello d’Uviglie", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-27/",
"tipo": "puntooss", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.41112737301637, 45.07702991478982 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5631",
"titolo": "Castello San Bartolomeo", "url_post": "http://www.monferratopaesaggi.org/castello-san-bartolomeo-3/",
"tipo": "edstorico", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.419631, 45.081455 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5632",
"titolo": "Castello d’Uviglie", "url_post": "http://www.monferratopaesaggi.org/castello-duviglie-3/",
"tipo": "edstorico", "wpid_comun": "6120", "comune": "Rosignano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.409712, 45.074688 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5639",
"titolo": "Edificio primi ‘900", "url_post": "http://www.monferratopaesaggi.org/villetta-5/",
"tipo": "ed_civile", "wpid_comun": "6065", "comune": "San Giorgio Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.406834321426459, 45.11466214383581 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5641",
"titolo": "Parco giochi bimbi", "url_post": "http://www.monferratopaesaggi.org/parco-giochi-bimbi-3/",
"tipo": "giardino", "wpid_comun": "6065", "comune": "San Giorgio Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/parco-giardino.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.412258, 45.107780 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5644",
"titolo": "Villa padronale primi ‘900", "url_post": "http://www.monferratopaesaggi.org/villa-11/",
"tipo": "ed_civile", "wpid_comun": "6030", "comune": "Ozzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.384135, 45.116432 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5647",
"titolo": "Punto di veduta strada Baldovina 1", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-132/",
"tipo": "puntooss", "wpid_comun": "6065", "comune": "San Giorgio Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.402524, 45.113991 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5598",
"titolo": "Punto di veduta Belvedere di Cantavenna", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-belvedere-di-cantavenna-5/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.219672, 45.159779 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5601",
"titolo": "Punto di veduta Belvedere “Le rocche di Zoalengo”", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-belvedere-le-rocche-di-zoalengo-5/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.206717, 45.156937 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5602",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-128/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.196552, 45.158112 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5606",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-129/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.225635, 45.160011 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5618",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-25/",
"tipo": "puntooss", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.457997, 45.048241 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5619",
"titolo": "Convento Romanico San Maurizio", "url_post": "http://www.monferratopaesaggi.org/convento-romanico-5/",
"tipo": "edreligioso", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.459204, 45.048828 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5620",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-del-cimitero-5/",
"tipo": "puntooss", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.454194, 45.022743 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5571",
"titolo": "Palazzo dei primi del ‘900", "url_post": "http://www.monferratopaesaggi.org/castello-dei-primi-del-900-5/",
"tipo": "ed_civile", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.444278, 45.022266 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5572",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-cascina-mario-3/",
"tipo": "puntooss", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.246162, 45.087582 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5574",
"titolo": "Villa il Cedro", "url_post": "http://www.monferratopaesaggi.org/palazzo-20/",
"tipo": "ed_civile", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.260206, 45.084911 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5575",
"titolo": "Arco", "url_post": "http://www.monferratopaesaggi.org/arco-3/",
"tipo": "none", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.262030, 45.085403 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5582",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-127/",
"tipo": "puntooss", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.241253, 45.075645 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5583",
"titolo": "Casa", "url_post": "http://www.monferratopaesaggi.org/casa-5/",
"tipo": "ed_civile", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.240240, 45.074020 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5588",
"titolo": "Chiesa di San Rocco (XIX secolo)", "url_post": "http://www.monferratopaesaggi.org/segnaposto-7-11/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.237554949737614, 45.140296474010825 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5589",
"titolo": "Pieve di San Bernardo da Mentone", "url_post": "http://www.monferratopaesaggi.org/segnaposto-8-5/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.237082640892027, 45.14503050668687 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5594",
"titolo": "Locanda del Rubino", "url_post": "http://www.monferratopaesaggi.org/locanda-del-rubino-5/",
"tipo": "ed_civile", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.226276, 45.159378 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5595",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-con-papere-e-galline-5/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.224200, 45.159958 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5597",
"titolo": "Cascina", "url_post": "http://www.monferratopaesaggi.org/cascina-3/",
"tipo": "ed_civile", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.272442, 45.158806 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5551",
"titolo": "Cappelletta di Sant’Anna", "url_post": "http://www.monferratopaesaggi.org/cappelletta-s-anna-3/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.25426326504703, 45.139224782108144 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5552",
"titolo": "Portale barocco", "url_post": "http://www.monferratopaesaggi.org/portale-3/",
"tipo": "none", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.254236265047098, 45.13897912997044 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5559",
"titolo": "Monumento ai partigiani", "url_post": "http://www.monferratopaesaggi.org/monumento-ai-partigiani-3/",
"tipo": "none", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.254050, 45.118351 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5561",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-cimitero-3/",
"tipo": "puntooss", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.208651046626983, 45.103202222932666 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5562",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-cascina-ramengo-3/",
"tipo": "puntooss", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.223229, 45.094364 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5563",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-24/",
"tipo": "puntooss", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.230348, 45.090504 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5564",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-cascina-gigliola-3/",
"tipo": "puntooss", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.232751, 45.088158 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5565",
"titolo": "Area pic-nic a Ponzano Monferrato", "url_post": "http://www.monferratopaesaggi.org/punto-di-sosta-attrezzato-3/",
"tipo": "picnic", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/pic-nic.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.257070481777191, 45.0865248339224 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5566",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-cascina-zanavreia-3/",
"tipo": "puntooss", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.264192, 45.086933 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5567",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/scorcio-esterno-verso-valle-3/",
"tipo": "puntooss", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.228899, 45.084724 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5568",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/scorcio-esterno-3/",
"tipo": "puntooss", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.230176, 45.084133 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5569",
"titolo": "Rovine Castello dei Merli", "url_post": "http://www.monferratopaesaggi.org/rovine-castello-dei-merli-3/",
"tipo": "edstorico", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.230433, 45.087490 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5570",
"titolo": "Villa dei primi del ‘900", "url_post": "http://www.monferratopaesaggi.org/villa-dei-primi-del-900-5/",
"tipo": "ed_civile", "wpid_comun": "6085", "comune": "Conzano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.450585, 45.020763 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5521",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-attrezzato-3/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.269862, 45.094254 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5523",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-tenuta-la-tenaglia-3/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.274947, 45.091778 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5524",
"titolo": "Prima cappella Sacro Monte Crea", "url_post": "http://www.monferratopaesaggi.org/prima-cappella-sacro-monte-crea-3/",
"tipo": "edreligioso", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.27981800859834, 45.09406352071431 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5531",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-vista-3/",
"tipo": "puntooss", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.283707, 45.099998 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5532",
"titolo": "Edificio", "url_post": "http://www.monferratopaesaggi.org/edificio-21/",
"tipo": "ed_civile", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.282978152114879, 45.100347521676504 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5538",
"titolo": "Pesa pubblica", "url_post": "http://www.monferratopaesaggi.org/pesa-pubblica-3/",
"tipo": "none", "wpid_comun": "6126", "comune": "Solonghello",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.289604460153555, 45.1388736003591 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5539",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-cimitero-3/",
"tipo": "puntooss", "wpid_comun": "6126", "comune": "Solonghello",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.290568530094106, 45.14093323616042 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5495",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-122/",
"tipo": "puntooss", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.273295, 45.136425 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5496",
"titolo": "Canonica", "url_post": "http://www.monferratopaesaggi.org/canonica-3/",
"tipo": "edreligioso", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.283809545963322, 45.085357699518916 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5497",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-123/",
"tipo": "puntooss", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.28343685515597, 45.0854866630935 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5498",
"titolo": "Castello dei Conti Davico", "url_post": "http://www.monferratopaesaggi.org/palazzo-17/",
"tipo": "edstorico", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.284469134918254, 45.08547584978878 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5499",
"titolo": "Villa Larbel", "url_post": "http://www.monferratopaesaggi.org/villa-larbel-3/",
"tipo": "ed_civile", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.287438845577299, 45.085027867652364 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5501",
"titolo": "Santuario dell’Addolorata", "url_post": "http://www.monferratopaesaggi.org/santuario-delladdolorata-3/",
"tipo": "edreligioso", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.221727, 45.123234 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5502",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-attrezzato-3/",
"tipo": "puntooss", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.219943, 45.123829 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5505",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-124/",
"tipo": "puntooss", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.189726, 45.131645 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5509",
"titolo": "Palazzo", "url_post": "http://www.monferratopaesaggi.org/palazzo-18/",
"tipo": "ed_civile", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.185225, 45.140297 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5510",
"titolo": "Villa", "url_post": "http://www.monferratopaesaggi.org/villa-9/",
"tipo": "ed_civile", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.190109, 45.147583 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5514",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-125/",
"tipo": "puntooss", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.2309340846557, 45.10691239599498 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5515",
"titolo": "Palazzo", "url_post": "http://www.monferratopaesaggi.org/palazzo-19/",
"tipo": "ed_civile", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.230916635581934, 45.10673499999998 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5517",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-23/",
"tipo": "puntooss", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.266498, 45.087753 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5463",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-del-cimitero-3/",
"tipo": "puntooss", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.166921, 45.133007 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5464",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-22/",
"tipo": "puntooss", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.167203, 45.133389 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5468",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-parrocchiale-7/",
"tipo": "puntooss", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.160591, 45.155212 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5469",
"titolo": "Villa del Carretto", "url_post": "http://www.monferratopaesaggi.org/palazzo-castello-5/",
"tipo": "ed_civile", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.161549, 45.155636 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5471",
"titolo": "Ruderi", "url_post": "http://www.monferratopaesaggi.org/stalle-5/",
"tipo": "none", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/vuoto.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.158902, 45.154972 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5472",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-comune-5/",
"tipo": "puntooss", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.158354, 45.155060 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5476",
"titolo": "Chiesa dei Santi Rocco e Sebastiano", "url_post": "http://www.monferratopaesaggi.org/tempietto-votivo-5/",
"tipo": "edreligioso", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.153674, 45.156708 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5486",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-121/",
"tipo": "puntooss", "wpid_comun": "6126", "comune": "Solonghello",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.281701, 45.130836 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5488",
"titolo": "Castello di Solonghello", "url_post": "http://www.monferratopaesaggi.org/castello-solonghello/",
"tipo": "edstorico", "wpid_comun": "6126", "comune": "Solonghello",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.282331093254129, 45.131302 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5489",
"titolo": "Casina Fornacetta", "url_post": "http://www.monferratopaesaggi.org/casina-fornacetta-3/",
"tipo": "ed_civile", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.297102, 45.115849 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5493",
"titolo": "Cascina Gambarello", "url_post": "http://www.monferratopaesaggi.org/cascina-gambarello-3/",
"tipo": "ed_civile", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.278810, 45.113846 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5434",
"titolo": "Torretta", "url_post": "http://www.monferratopaesaggi.org/torretta-3/",
"tipo": "edstorico", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.186534, 45.095158 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5451",
"titolo": "Palazzo", "url_post": "http://www.monferratopaesaggi.org/palazzo-15/",
"tipo": "ed_civile", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.145045, 45.108257 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5452",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-119/",
"tipo": "puntooss", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.144281, 45.109749 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5456",
"titolo": "San Pietro Martire", "url_post": "http://www.monferratopaesaggi.org/san-pietro-martire-3/",
"tipo": "edreligioso", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.151279, 45.138638 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5459",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-38/",
"tipo": "ed_civile", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.169778, 45.134510 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5461",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-120/",
"tipo": "puntooss", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.170955084655816, 45.13477838212945 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5405",
"titolo": "Pallazzo", "url_post": "http://www.monferratopaesaggi.org/segnaposto-24-9/",
"tipo": "ed_civile", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.098453185180688, 45.10259567049426 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5406",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-114/",
"tipo": "puntooss", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.099530699405705, 45.10219760167383 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5408",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-37/",
"tipo": "ed_civile", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.099512250331827, 45.10231378643685 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5409",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-115/",
"tipo": "puntooss", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.10081879629513, 45.10225538814139 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5410",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-116/",
"tipo": "puntooss", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.097884, 45.101398 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5411",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-117/",
"tipo": "puntooss", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.097456667493816, 45.10139611774031 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5418",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-panoramico-21/",
"tipo": "puntooss", "wpid_comun": "2506", "comune": "Villadeati",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.167611, 45.059658 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5427",
"titolo": "Castello Odalengo Piccolo", "url_post": "http://www.monferratopaesaggi.org/castello-di-pessine-3/",
"tipo": "edstorico", "wpid_comun": "6112", "comune": "Odalengo Piccolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/ed_storico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.200462084655783, 45.08024624204983 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5429",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-118/",
"tipo": "puntooss", "wpid_comun": "6112", "comune": "Odalengo Piccolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.200216, 45.080212 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5377",
"titolo": "Cimitero ebrei", "url_post": "http://www.monferratopaesaggi.org/cimitero-ebrei-3/",
"tipo": "edreligioso", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.278177, 45.045223 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5378",
"titolo": "Cimitero", "url_post": "http://www.monferratopaesaggi.org/cimitero-56/",
"tipo": "edreligioso", "wpid_comun": "6087", "comune": "Grazzano Badoglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.319241, 45.036968 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5380",
"titolo": "Chiesa di Madonna dei Monti", "url_post": "http://www.monferratopaesaggi.org/chiesa-153/",
"tipo": "edreligioso", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.325094224536883, 45.050264416313865 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5382",
"titolo": "Chiesa San Giacomo", "url_post": "http://www.monferratopaesaggi.org/chiesa-san-giacomo-e-museo-3/",
"tipo": "edreligioso", "wpid_comun": "6089", "comune": "Lu",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.486519644180362, 45.00276603483694 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5384",
"titolo": "Chiesetta di Sant’Eusebio", "url_post": "http://www.monferratopaesaggi.org/chiesetta-di-santeusebio-3/",
"tipo": "edreligioso", "wpid_comun": "6114", "comune": "Ottiglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.328380, 45.047165 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5393",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-111/",
"tipo": "puntooss", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.121023, 45.120831 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5396",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-112/",
"tipo": "puntooss", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.111048, 45.114742 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5404",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-113/",
"tipo": "puntooss", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.099244063823676, 45.102056815152025 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5358",
"titolo": "Chiesetta", "url_post": "http://www.monferratopaesaggi.org/chiesetta-38/",
"tipo": "edreligioso", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.205221, 45.155231 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5359",
"titolo": "Chiesa di Santi Rocco e Stefano", "url_post": "http://www.monferratopaesaggi.org/chiesa-di-santi-rocco-e-stefano-3/",
"tipo": "edreligioso", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.278249, 45.169388 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5360",
"titolo": "Chiesetta di San Pietro Apostolo", "url_post": "http://www.monferratopaesaggi.org/chiesa-147/",
"tipo": "edreligioso", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.268046, 45.157997 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5361",
"titolo": "Chiesa", "url_post": "http://www.monferratopaesaggi.org/chiesa-148/",
"tipo": "edreligioso", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.261165, 45.156975 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5362",
"titolo": "Chiesa", "url_post": "http://www.monferratopaesaggi.org/chiesa-149/",
"tipo": "edreligioso", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.252519, 45.168308 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5363",
"titolo": "Chiesa S. Sebastiano Rocca delle Donne", "url_post": "http://www.monferratopaesaggi.org/chiesa-150/",
"tipo": "edreligioso", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.247649, 45.169216 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5365",
"titolo": "Chiesa di Sant’Agata", "url_post": "http://www.monferratopaesaggi.org/chiesa-di-santagata-3/",
"tipo": "edreligioso", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.331652, 45.143452 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5366",
"titolo": "Antica cascina", "url_post": "http://www.monferratopaesaggi.org/segnaposto-35-3/",
"tipo": "ed_civile", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.096422, 45.096142 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5369",
"titolo": "Chiesa Parrocchiale dell’Assunta e di Sant’Eusebio", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-dellassunta-e-di-santeusebio-3/",
"tipo": "edreligioso", "wpid_comun": "6135", "comune": "Coniolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.367639, 45.147827 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5370",
"titolo": "Chiesa della Natività di Maria", "url_post": "http://www.monferratopaesaggi.org/chiesa-151/",
"tipo": "edreligioso", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.354647, 45.129581 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5371",
"titolo": "Chiesa Madonna delle Grazie", "url_post": "http://www.monferratopaesaggi.org/chiesa-152/",
"tipo": "edreligioso", "wpid_comun": "2203", "comune": "Pontestura",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.335459, 45.142181 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5372",
"titolo": "Chiesetta abbandonata", "url_post": "http://www.monferratopaesaggi.org/chiesetta-39/",
"tipo": "edreligioso", "wpid_comun": "6101", "comune": "Casale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.429327, 45.133411 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5373",
"titolo": "Chiesa della Madonna delle Grazie", "url_post": "http://www.monferratopaesaggi.org/chiesa-della-madonna-3/",
"tipo": "edreligioso", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.264759915344257, 45.05048373167663 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5374",
"titolo": "Chiesa di Sant’Antonio abate", "url_post": "http://www.monferratopaesaggi.org/chiesa-di-santantonio-3/",
"tipo": "edreligioso", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.265919, 45.050220 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5375",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/chiesetta-la-pieve-punto-panoramico-sui-gessi-3/",
"tipo": "puntooss", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.252031, 45.045410 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5376",
"titolo": "Chiesa San Francesco", "url_post": "http://www.monferratopaesaggi.org/chiesa-san-francesco-3/",
"tipo": "edreligioso", "wpid_comun": "5941", "comune": "Moncalvo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.267019, 45.048328 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5340",
"titolo": "Chiesa della Madonna del Carmine (XVII secolo)", "url_post": "http://www.monferratopaesaggi.org/chiesa-madonna-del-6/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.237270055225395, 45.13511307869914 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5341",
"titolo": "Chiesa di San Bononio (XVII secolo)", "url_post": "http://www.monferratopaesaggi.org/chiesa-di-s-bononio-6/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.238413445438368, 45.13795953454558 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5342",
"titolo": "Chiesetta", "url_post": "http://www.monferratopaesaggi.org/chiesetta-33/",
"tipo": "edreligioso", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.232716, 45.153522 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5343",
"titolo": "Chiesa", "url_post": "http://www.monferratopaesaggi.org/chiesa-142/",
"tipo": "edreligioso", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.226517, 45.159801 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5344",
"titolo": "Chiesetta di Sant’Aurelio", "url_post": "http://www.monferratopaesaggi.org/chiesetta-34/",
"tipo": "edreligioso", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.205221, 45.155231 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5349",
"titolo": "Cimitero", "url_post": "http://www.monferratopaesaggi.org/cimitero-54/",
"tipo": "edreligioso", "wpid_comun": "6122", "comune": "Sala Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.354580, 45.070709 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5352",
"titolo": "Chiesa parrocchiale Assunzione di Maria Vergine (1763)", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-assunzione-di-maria-vergine-1763-9/",
"tipo": "edreligioso", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.160731, 45.155216 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5354",
"titolo": "Chiesetta", "url_post": "http://www.monferratopaesaggi.org/chiesetta-37/",
"tipo": "edreligioso", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.232716, 45.153522 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5355",
"titolo": "Chiesa", "url_post": "http://www.monferratopaesaggi.org/chiesa-145/",
"tipo": "edreligioso", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.292285, 45.158989 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5357",
"titolo": "Chiesa di San Carpoforo", "url_post": "http://www.monferratopaesaggi.org/chiesa-146/",
"tipo": "edreligioso", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.226517, 45.159801 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5326",
"titolo": "Chiesa Sant’Antonio Abate", "url_post": "http://www.monferratopaesaggi.org/chiesa-santantonio-6/",
"tipo": "edreligioso", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.283608583991963, 45.0854932307163 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5327",
"titolo": "Chiesa di Sant’Eusebio", "url_post": "http://www.monferratopaesaggi.org/chiesa-133/",
"tipo": "edreligioso", "wpid_comun": "2205", "comune": "Gabiano",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.188666, 45.133434 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5328",
"titolo": "Chiesa", "url_post": "http://www.monferratopaesaggi.org/chiesa-134/",
"tipo": "edreligioso", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.196318, 45.124458 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5329",
"titolo": "Chiesa di San Sebastiano", "url_post": "http://www.monferratopaesaggi.org/chiesa-135/",
"tipo": "edreligioso", "wpid_comun": "6124", "comune": "Serralunga di Crea",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.281891991401608, 45.10043643875292 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5330",
"titolo": "Chiesa dei Santi Fabiano e Eusebio", "url_post": "http://www.monferratopaesaggi.org/chiesa-136/",
"tipo": "edreligioso", "wpid_comun": "6126", "comune": "Solonghello",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.289141944774656, 45.13896905605418 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5331",
"titolo": "Chiesa di San Grato", "url_post": "http://www.monferratopaesaggi.org/chiesa-137/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.267303588954974, 45.14094180965955 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5332",
"titolo": "Chiesa di Sant’Anna", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-anna-6/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.254200889549224, 45.13976439545172 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5333",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/cimitero-51/",
"tipo": "puntooss", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.253543, 45.137394 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5335",
"titolo": "Chiesa di Sant’Antonio Abate", "url_post": "http://www.monferratopaesaggi.org/chiesa-139/",
"tipo": "edreligioso", "wpid_comun": "6083", "comune": "Cerrina Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.212103, 45.101601 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5336",
"titolo": "Chiesa parrocchiale di San Giovanni Battista", "url_post": "http://www.monferratopaesaggi.org/chiesa-140/",
"tipo": "edreligioso", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.260911, 45.084915 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5337",
"titolo": "Chiesa di San Sebastiano", "url_post": "http://www.monferratopaesaggi.org/chiesetta-32/",
"tipo": "edreligioso", "wpid_comun": "6116", "comune": "Ponzano Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.261721, 45.085468 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5338",
"titolo": "Chiesa di Sant’Eusebio", "url_post": "http://www.monferratopaesaggi.org/chiesa-141/",
"tipo": "edreligioso", "wpid_comun": "6081", "comune": "Castelletto Merli",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.241279982803349, 45.075102705820846 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5339",
"titolo": "Santuario di San Gottardo (XVIII-XIX secolo)", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-gottardo-6/",
"tipo": "edreligioso", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.239768, 45.128105 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5310",
"titolo": "Chiesetta", "url_post": "http://www.monferratopaesaggi.org/chiesetta-31/",
"tipo": "edreligioso", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.121310521495843, 45.1207446109008 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5311",
"titolo": "Chiesa", "url_post": "http://www.monferratopaesaggi.org/chiesa-125/",
"tipo": "edreligioso", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.106735, 45.113827 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5312",
"titolo": "Chiesa parrocchiale di San Giacomo Apostolo e della Beata Vergine Assunta", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-di-s-giacomo-apostolo-6/",
"tipo": "edreligioso", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.098453955854438, 45.10168289323932 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5313",
"titolo": "Chiesa di San Francesco", "url_post": "http://www.monferratopaesaggi.org/chiesa-126/",
"tipo": "edreligioso", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.095593, 45.099724 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5314",
"titolo": "Chiesa", "url_post": "http://www.monferratopaesaggi.org/chiesa-127/",
"tipo": "edreligioso", "wpid_comun": "6112", "comune": "Odalengo Piccolo",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.201989, 45.075275 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5315",
"titolo": "Chiesa", "url_post": "http://www.monferratopaesaggi.org/chiesa-128/",
"tipo": "edreligioso", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.181419, 45.099674 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5316",
"titolo": "Chiesa di San Vittore", "url_post": "http://www.monferratopaesaggi.org/chiesa-129/",
"tipo": "edreligioso", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.166508228172233, 45.10986335471923 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5317",
"titolo": "Cimitero", "url_post": "http://www.monferratopaesaggi.org/cimitero-50/",
"tipo": "edreligioso", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.162952, 45.114399 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5318",
"titolo": "Chiesa", "url_post": "http://www.monferratopaesaggi.org/chiesa-130/",
"tipo": "edreligioso", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.164427, 45.095295 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5319",
"titolo": "Chiesa", "url_post": "http://www.monferratopaesaggi.org/chiesa-131/",
"tipo": "edreligioso", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.145487504299126, 45.10809098597228 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5320",
"titolo": "Chiesa dei Santi Filippo e Michele", "url_post": "http://www.monferratopaesaggi.org/chiesa-ss-filippo-e-michele-6/",
"tipo": "edreligioso", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.171056918979616, 45.134658741030854 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5321",
"titolo": "Chiesa di San Michele", "url_post": "http://www.monferratopaesaggi.org/chiesa-di-s-michele-6/",
"tipo": "edreligioso", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.167186975479126, 45.133174828866466 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5322",
"titolo": "Chiesa di Santo Stefano", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-stefano-6/",
"tipo": "edreligioso", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.161155, 45.141685 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5323",
"titolo": "Chiesa di Santa Liberata", "url_post": "http://www.monferratopaesaggi.org/chiesa-s-liberata-6/",
"tipo": "edreligioso", "wpid_comun": "6132", "comune": "Villamiroglio",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.172452, 45.148006 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5324",
"titolo": "Chiesa parrocchiale Assunzione di Maria Vergine (1763)", "url_post": "http://www.monferratopaesaggi.org/chiesa-parrocchiale-assunzione-di-maria-vergine-1763-8/",
"tipo": "edreligioso", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.160731, 45.155216 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5325",
"titolo": "Chiesa di Sant’Andrea", "url_post": "http://www.monferratopaesaggi.org/chiesa-132/",
"tipo": "edreligioso", "wpid_comun": "6126", "comune": "Solonghello",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.281459504299164, 45.13103049172794 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5297",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-109/",
"tipo": "puntooss", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.142652588954888, 45.10882732507847 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5298",
"titolo": "Municipio", "url_post": "http://www.monferratopaesaggi.org/municipio-36/",
"tipo": "ed_civile", "wpid_comun": "6110", "comune": "Odalengo Grande",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/edificio-civile.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.166903, 45.109570 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5301",
"titolo": "Chiesa Parrocchiale San Lorenzo Martire", "url_post": "http://www.monferratopaesaggi.org/chiesa-123/",
"tipo": "edreligioso", "wpid_comun": "6041", "comune": "Camino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.290933, 45.161205 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5304",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/punto-di-veduta-110/",
"tipo": "puntooss", "wpid_comun": "6091", "comune": "Mombello Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.252132830688424, 45.13378149045003 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5305",
"titolo": "Cimitero", "url_post": "http://www.monferratopaesaggi.org/cimitero-48/",
"tipo": "edreligioso", "wpid_comun": "6118", "comune": "Robella",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.095384, 45.099667 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5306",
"titolo": "Punto di veduta", "url_post": "http://www.monferratopaesaggi.org/visuale-da-stradina-per-ostello-6/",
"tipo": "puntooss", "wpid_comun": "6131", "comune": "Vignale Monferrato",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/punto_panoramico.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.397036, 45.011246 ] } }
, { "type": "Feature", "properties": {
"color_qgis2leaf": "#c783d8", "radius_qgis2leaf": 4.0, "borderColor_qgis2leaf": "#000000",
"transp_qgis2leaf": 1.0, "transp_fill_qgis2leaf": 1.0, "unico": "5308",
"titolo": "Chiesa di Santa Maria", "url_post": "http://www.monferratopaesaggi.org/chiesa-124/",
"tipo": "edreligioso", "wpid_comun": "2199", "comune": "Moncestino",
"icon_exp": "http://www.monferratopaesaggi.org/wp-content/uploads/chiesa.png"
}, "geometry": { "type": "Point", "coordinates": [ 8.151349, 45.154503 ] } }
],
"type" : "FeatureCollection"
}
|
import EditFormNewRoute from 'ember-flexberry/routes/edit-form-new';
export default EditFormNewRoute.extend({
/**
* Name of model projection to be used as record's properties limitation.
*
* @property modelProjection
* @type String
* @default 'SuggestionTypeE'
*/
modelProjection: 'SuggestionTypeE',
/**
* Name of model to be used as form's record type.
*
* @property modelName
* @type String
* @default 'ember-flexberry-dummy-suggestion-type'
*/
modelName: 'ember-flexberry-dummy-suggestion-type',
/**
* Name of controller to be used.
*
* @property controllerName
* @type String
* @default 'ember-flexberry-dummy-suggestion-type-edit'
*/
controllerName: 'ember-flexberry-dummy-suggestion-type-edit',
/**
* Name of template to be rendered.
*
* @property templateName
* @type String
* @default 'ember-flexberry-dummy-suggestion-type-edit'
*/
templateName: 'ember-flexberry-dummy-suggestion-type-edit'
});
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap/dist/js/bootstrap.min
//= require moment/min/moment.min
//= require angular/angular.min
//= require angular-sanitize/angular-sanitize.min
//= require angular-aria/angular-aria.min
//= require angular-animate/angular-animate.min
//= require angular-material/angular-material.min
//= require angular-route/angular-route.min
//= require jquery-sticky/jquery.sticky
//= require jquery-bridget/jquery-bridget
//= require ev-emitter/ev-emitter
//= require desandro-matches-selector/matches-selector
//= require fizzy-ui-utils/utils.js
//= require get-size/get-size
//= require outlayer/item
//= require outlayer/outlayer
//= require masonry/masonry
//= require imagesloaded/imagesloaded
//= require angular-masonry/angular-masonry
//= require ng-file-upload/ng-file-upload-all.min
//= require ngInfiniteScroll/build/ng-infinite-scroll.min
//= require ngToast/dist/ngToast.min
//= require_self
|
define([], function() {
var plugin = function() { };
plugin.prototype = {
init: function( graph, options ) {
this._zoomingSquare = document.createElementNS(graph.ns, 'rect');
graph.setAttributeTo(this._zoomingSquare, {
'display': 'none',
'fill': 'rgba(171,12,12,0.2)',
'stroke': 'rgba(171,12,12,1)',
'shape-rendering': 'crispEdges',
'x': 0,
'y': 0,
'height': 0,
'width': 0
});
this.options = options;
this.graph = graph;
graph.dom.appendChild(this._zoomingSquare);
},
onMouseDown: function(graph, x, y, e, target) {
var zoomMode = this.options.zoomMode;
if( ! zoomMode ) {
return;
}
this._zoomingMode = zoomMode;
this._zoomingXStart = x;
this._zoomingYStart = y;
this.x1 = x - graph.getPaddingLeft();
this.y1 = y - graph.getPaddingTop();
this._zoomingSquare.setAttribute('width', 0);
this._zoomingSquare.setAttribute('height', 0);
this._zoomingSquare.setAttribute('display', 'block');
switch(zoomMode) {
case 'x':
this._zoomingSquare.setAttribute('y', graph.options.paddingTop);
this._zoomingSquare.setAttribute('height', graph.getDrawingHeight() - graph.shift[0]);
break;
case 'y':
this._zoomingSquare.setAttribute('x', graph.options.paddingLeft/* + this.shift[1]*/);
this._zoomingSquare.setAttribute('width', graph.getDrawingWidth()/* - this.shift[1] - this.shift[2]*/);
break;
}
},
onMouseMove: function(graph, x, y, e, target) {
switch(this._zoomingMode) {
case 'xy':
this._zoomingSquare.setAttribute('x', Math.min(this._zoomingXStart, x));
this._zoomingSquare.setAttribute('y', Math.min(this._zoomingYStart, y));
this._zoomingSquare.setAttribute('width', Math.abs(this._zoomingXStart - x));
this._zoomingSquare.setAttribute('height', Math.abs(this._zoomingYStart - y));
break;
case 'x':
this._zoomingSquare.setAttribute('x', Math.min(this._zoomingXStart, x));
this._zoomingSquare.setAttribute('width', Math.abs(this._zoomingXStart - x));
break;
case 'y':
this._zoomingSquare.setAttribute('y', Math.min(this._zoomingYStart, y));
this._zoomingSquare.setAttribute('height', Math.abs(this._zoomingYStart - y));
break;
}
},
onMouseUp: function(graph, x, y, e, target) {
this._zoomingSquare.setAttribute('display', 'none');
var _x = x - graph.options.paddingLeft;
var _y = y - graph.options.paddingTop;
if((x - this._zoomingXStart == 0 && this._zoomingMode != 'y') || (y - this._zoomingYStart == 0 && this._zoomingMode != 'x')) {
return;
}
switch(this._zoomingMode) {
case 'x':
graph.applyToAxes('_doZoom', [_x, this.x1], true, false);
break;
case 'y':
graph.applyToAxes('_doZoom', [_y, this.y1], false, true);
break;
case 'xy':
graph.applyToAxes('_doZoom', [_x, this.x1], true, false);
graph.applyToAxes('_doZoom', [_y, this.y1], false, true);
break;
}
graph.redraw(true);
graph.drawSeries();
},
onMouseWheel: function( delta, e ) {
var serie;
if( ( serie = this.graph.getSelectedSerie() ) ) {
serie.getYAxis().handleMouseWheel( delta, e );
return;
}
this.graph.applyToAxes('handleMouseWheel', [ delta, e ], false, true);
},
onDblClick: function( x, y, pref, e ) {
var xAxis = this.graph.getXAxis(),
yAxis = this.graph.getYAxis();
if( pref.mode == 'total' ) {
this.graph.autoscaleAxes();
this.graph.redraw();
this.graph.drawSeries();
if( yAxis.options.onZoom ) {
yAxis.options.onZoom( yAxis.getMinValue(), yAxis.getMaxValue() );
}
if( xAxis.options.onZoom ) {
xAxis.options.onZoom( xAxis.getMinValue(), xAxis.getMaxValue() );
}
return;
}
x -= this.graph.options.paddingLeft;
y -= this.graph.options.paddingTop;
var
xMin = xAxis.getActualMin(),
xMax = xAxis.getActualMax(),
xActual = xAxis.getVal(x),
diffX = xMax - xMin,
yMin = yAxis.getActualMin(),
yMax = yAxis.getActualMax(),
yActual = yAxis.getVal(y),
diffY = yMax - yMin;
if(pref.mode == 'gradualXY' || pref.mode == 'gradualX') {
var ratio = (xActual - xMin) / (xMax - xMin);
xMin = Math.max(xAxis.getMinValue(), xMin - diffX * ratio);
xMax = Math.min(xAxis.getMaxValue(), xMax + diffX * (1 - ratio));
xAxis.setCurrentMin(xMin);
xAxis.setCurrentMax(xMax);
if( xAxis.options.onZoom ) {
xAxis.options.onZoom( xMin, xMax );
}
}
if(pref.mode == 'gradualXY' || pref.mode == 'gradualY') {
var ratio = (yActual - yMin) / (yMax - yMin);
yMin = Math.max(yAxis.getMinValue(), yMin - diffY * ratio);
yMax = Math.min(yAxis.getMaxValue(), yMax + diffY * (1 - ratio));
yAxis.setCurrentMin(yMin);
yAxis.setCurrentMax(yMax);
if( yAxis.options.onZoom ) {
yAxis.options.onZoom( yMin, yMax );
}
}
this.graph.redraw( );
this.graph.drawSeries( );
}
}
return plugin;
});
|
var fs = require('fs');
var shell = require('shelljs');
module.exports.readJsonFile = function(fileLocation, callback) {
fs.readFile(shell.pwd() + fileLocation, 'UTF8', function(err, fileContents) {
if(err){
callback(true, err);
}else{
callback(null, JSON.parse(fileContents));
}
});
};
module.exports.writeJsonSchema = function(path, schemaName, schemaDefinition, callback) {
var jsonSchema = {
name: schemaName,
fields: schemaDefinition
};
var jsonPrettified = JSON.stringify(jsonSchema, null, 4);
fs.writeFile(path, jsonPrettified, function(err, msg) {
if(err) {
callback(err, msg)
} else {
callback(null, "Schema written to file successfully");
}
})
};
module.exports.removeJsonSchema = function(path, schemaName, callback) {
fs.unlink(path + schemaName + '.json', callback)
};
|
'use babel';
import SelectListView from './select-list-view';
import Utils from './utils';
import { CompositeDisposable } from 'atom';
export default {
selectList: null,
utils: null,
subscriptions: null,
componentsDir: null,
activate(state) {
this.selectList = new SelectListView();
this.utils = new Utils();
// Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
this.subscriptions = new CompositeDisposable();
// Register command that toggles this view
this.subscriptions.add(atom.commands.add('atom-workspace', {
'atom-catberry:show-files': () => this.getComponentDir(),
'atom-catberry:show-component-uses': () => this.getComponentUses()
}));
const directorys = atom.project.getDirectories();
const that = this;
directorys.some((dir) => {
that.componentsDir = dir.getSubdirectory('catberry_components');
if (that.componentsDir.existsSync()) {
return true;
}
that.componentsDir = false;
return false;
});
},
deactivate() {
this.selectList.destroy();
this.subscriptions.dispose();
this.utils.destroy();
},
/**
* Remove if|else|unless blocks, replace handlebars variables to text string
* @param {string} componentStr component string
* @returns {string}
*/
clearComponent(componentStr) {
const replaceText = 'There must be a text or a number';
return componentStr
.replace(/{{#(if|unless) [\w.]+}}|{{\/(if|unless)}}/g, '')
.replace(/{{else}}/g, '')
.replace(/="{{(?!l10n)[ \.\w\"]+}}"/g, `="${replaceText}"`)
.replace(/class="[\w\-]+"/g, '');
},
/**
* Return component with attributes
* @param {string} str search string
* @param {string} name component name
* @returns {array|null}
*/
getComponents(str, name) {
const attributes = '[ \\-\\wа-яА-ЯёЁ:="{}\\n\\t._#\\/]+><\\/';
const componentReg = new RegExp(`<${name}${attributes}${name}>`, 'g');
return str.match(componentReg);
},
/**
* Return params name-value object
* @param {type} componentStr component string
* @returns {object}
*/
getParams(componentStr) {
let params = componentStr.match(/[\wа-яА-ЯёЁ-]+="[\wа-яА-ЯёЁ{}\-. "\/]+"/g);
if (!params) return null;
const result = {};
params.forEach(function(paramStr) {
const paramPare = paramStr.split('=');
const name = paramPare[0];
const value = paramPare[1];
result[name] = value.replace(/"{{(?!l10n)/g, '{');
});
return result;
},
/**
* Create a component row view
* @param {object} params component params
* @param {string} comp component code
* @return {string} html string of component view
*/
createComponentRowView(params, comp) {
let rowStr = '<tr>\n<td>';
for (var x in params) {
rowStr += `${x}=${params[x]}\n<br/>`;
}
rowStr += `</td><td>${comp}</td>\n</tr>`;
return rowStr;
},
/**
* Creates a new tab with a list of a component uses
* @return {null}
*/
getComponentUses() {
const name = this.getCatTagName();
if (!name || !this.componentsDir.existsSync()) return;
const templateFiles = this.utils.getAllTemplates(this.componentsDir);
let resultTable = name + '\n<br/><table cellpadding="5" border="1" width="100%">';
const that = this;
templateFiles.forEach(function(file) {
const components = that.getComponents(file.readSync(), name);
if (components) {
components.forEach(function(componentStr) {
const componentParams = that.getParams(componentStr);
const clearComp = that.clearComponent(componentStr);
resultTable += that.createComponentRowView(componentParams, clearComp);
});
}
});
resultTable += '</table>';
atom.workspace.open().then(function(textEd) {
textEd.insertText(resultTable);
});
},
/**
* Show a list of files of component
* @return {null}
*/
getComponentDir() {
const name = this.getCatTagName();
if (!name || !this.componentsDir.existsSync()) return;
const dir = this.utils.getDir(this.componentsDir, name.replace('cat-', ''));
if (dir) {
this.selectList.show(dir);
}
},
/**
* Return a cat component name from a cursor position
* @return {strng|null}
*/
getCatTagName() {
const editor = atom.workspace.getActiveTextEditor();
const cursor = editor.getCursors()[0];
const optionsStart = {
wordRegex: /<[a-z-]*/g
}
const range = cursor.getCurrentWordBufferRange(optionsStart);
const startText = editor.getTextInBufferRange(range);
const endPoint = cursor.getEndOfCurrentWordBufferPosition({
wordRegex: /[a-z-]+/g
});
range.end = endPoint;
const endText = editor.getTextInBufferRange(range);
if (endText === '' || /^<cat-/g.test(endText) === false) return false;
return endText.replace('<', '').split(/\s/g)[0];
}
};
|
function FactigisModuleList(){
return [
{module: 'GENERAR_FACTIBILIDAD', alias: 'CREAR', widgets:["CREAR_FACTIBILIDAD","BUSCAR_FOLIO","CREAR_DIRECCION"] , Available: 'yes', Permission: 'no', Insert: 'no', Update: 'no', Delete: 'no', url:'factigis.html', color: 'transparent', img:'dist/css/images/factigis_images/icono_planificacion.png' },
{module: 'REVISAR_FACTIBILIDAD', alias: 'REVISAR', widgets:["BUSCAR_FACTIBILIDADES", "LISTAR_FACTIBILIDAD","MODIFICAR_ESTADO_FACTIBILIDAD"] , Available: 'yes', Permission: 'no', Insert: 'no', Update: 'no', Delete: 'no',url:'backoffice_factigis.html', color: 'transparent', img:'dist/css/images/factigis_images/icono_verificarcliente.png'},
{module: 'REVISAR_HISTORIAL_FACTIBILIDAD',alias: 'REVISAR HISTORIAL', widget:["BUSCAR_HISTORIA_FACTIBILIDAD","LISTAR_FACTIBILIDAD", "VER_FACTIBILIDAD"] , Available: 'yes', Permission: 'no', Insert: 'no', Update: 'no', Delete: 'no',url:'backoffice2_factigis.html', color: 'transparent', img:'dist/css/images/factigis_images/icono_factigis_revision.png'}
];
}
function FactigisInsertMyData(list, permissions){
var newList = [];
permissions.forEach(permission => {
list.forEach(array => {
if(array.module === permission.module){
newList.push({
module: array['module'],
alias: array['alias'],
available: array['Available'],
Permission: 'yes',
Insert: permission['insert'],
Update: permission['update'],
Delete: permission['delete'],
url:array['url'],
color: array['color'],
img: array['img']
});
}
});
});
return newList;
}
function excludeDataFactigis(allList, yourList,yourPropList){
var props = yourPropList;
var result = allList.filter(function(o1){
// filter out (!) items in result2
return !yourList.some(function(o2){
return o1.module === o2.module; // assumes unique id
});
}).map(function(o){
// use reduce to make objects with only the required properties
// and map to apply this to the filtered array as a whole
return props.reduce(function(newo, name){
newo[name] = o[name];
return newo;
}, {});
});
return result;
}
export {FactigisModuleList,FactigisInsertMyData,excludeDataFactigis};
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _unstyled = require("@material-ui/unstyled");
var _styled = _interopRequireDefault(require("../styles/styled"));
var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps"));
var _CheckCircle = _interopRequireDefault(require("../internal/svg-icons/CheckCircle"));
var _Warning = _interopRequireDefault(require("../internal/svg-icons/Warning"));
var _SvgIcon = _interopRequireDefault(require("../SvgIcon"));
var _stepIconClasses = _interopRequireWildcard(require("./stepIconClasses"));
var _jsxRuntime = require("react/jsx-runtime");
var _circle;
const _excluded = ["active", "className", "completed", "error", "icon"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const useUtilityClasses = ownerState => {
const {
classes,
active,
completed,
error
} = ownerState;
const slots = {
root: ['root', active && 'active', completed && 'completed', error && 'error'],
text: ['text']
};
return (0, _unstyled.unstable_composeClasses)(slots, _stepIconClasses.getStepIconUtilityClass, classes);
};
const StepIconRoot = (0, _styled.default)(_SvgIcon.default, {
name: 'MuiStepIcon',
slot: 'Root',
overridesResolver: (props, styles) => styles.root
})(({
theme
}) => ({
display: 'block',
transition: theme.transitions.create('color', {
duration: theme.transitions.duration.shortest
}),
color: theme.palette.text.disabled,
[`&.${_stepIconClasses.default.completed}`]: {
color: theme.palette.primary.main
},
[`&.${_stepIconClasses.default.active}`]: {
color: theme.palette.primary.main
},
[`&.${_stepIconClasses.default.error}`]: {
color: theme.palette.error.main
}
}));
const StepIconText = (0, _styled.default)('text', {
name: 'MuiStepIcon',
slot: 'Text',
overridesResolver: (props, styles) => styles.text
})(({
theme
}) => ({
fill: theme.palette.primary.contrastText,
fontSize: theme.typography.caption.fontSize,
fontFamily: theme.typography.fontFamily
}));
const StepIcon = /*#__PURE__*/React.forwardRef(function StepIcon(inProps, ref) {
const props = (0, _useThemeProps.default)({
props: inProps,
name: 'MuiStepIcon'
});
const {
active = false,
className: classNameProp,
completed = false,
error = false,
icon
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
const ownerState = (0, _extends2.default)({}, props, {
active,
completed,
error
});
const classes = useUtilityClasses(ownerState);
if (typeof icon === 'number' || typeof icon === 'string') {
const className = (0, _clsx.default)(classNameProp, classes.root);
if (error) {
return /*#__PURE__*/(0, _jsxRuntime.jsx)(StepIconRoot, (0, _extends2.default)({
as: _Warning.default,
className: className,
ref: ref,
ownerState: ownerState
}, other));
}
if (completed) {
return /*#__PURE__*/(0, _jsxRuntime.jsx)(StepIconRoot, (0, _extends2.default)({
as: _CheckCircle.default,
className: className,
ref: ref,
ownerState: ownerState
}, other));
}
return /*#__PURE__*/(0, _jsxRuntime.jsxs)(StepIconRoot, (0, _extends2.default)({
className: className,
ref: ref,
ownerState: ownerState
}, other, {
children: [_circle || (_circle = /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", {
cx: "12",
cy: "12",
r: "12"
})), /*#__PURE__*/(0, _jsxRuntime.jsx)(StepIconText, {
className: classes.text,
x: "12",
y: "16",
textAnchor: "middle",
ownerState: ownerState,
children: icon
})]
}));
}
return icon;
});
process.env.NODE_ENV !== "production" ? StepIcon.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* Whether this step is active.
* @default false
*/
active: _propTypes.default.bool,
/**
* Override or extend the styles applied to the component.
*/
classes: _propTypes.default.object,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* Mark the step as completed. Is passed to child components.
* @default false
*/
completed: _propTypes.default.bool,
/**
* If `true`, the step is marked as failed.
* @default false
*/
error: _propTypes.default.bool,
/**
* The label displayed in the step icon.
*/
icon: _propTypes.default.node,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: _propTypes.default.object
} : void 0;
var _default = StepIcon;
exports.default = _default;
|
/*!
* DevExtreme (dx.messages.it.js)
* Version: 21.2.4
* Build date: Mon Dec 06 2021
*
* Copyright (c) 2012 - 2021 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
"use strict";
! function(root, factory) {
if ("function" === typeof define && define.amd) {
define((function(require) {
factory(require("devextreme/localization"))
}))
} else if ("object" === typeof module && module.exports) {
factory(require("devextreme/localization"))
} else {
factory(DevExpress.localization)
}
}(0, (function(localization) {
localization.loadMessages({
it: {
Yes: "S\xec",
No: "No",
Cancel: "Annulla",
Clear: "Cancella",
Done: "Fatto",
Loading: "Caricamento...",
Select: "Seleziona...",
Search: "Cerca",
Back: "Indietro",
OK: "OK",
"dxCollectionWidget-noDataText": "Nessun dato da mostrare",
"dxDropDownEditor-selectLabel": "Seleziona",
"validation-required": "Richiesto",
"validation-required-formatted": "{0} \xe8 richiesto",
"validation-numeric": "Il valore deve essere numerico",
"validation-numeric-formatted": "{0} deve essere numerico",
"validation-range": "Il valore non \xe8 compreso nell'intervallo",
"validation-range-formatted": "{0} non \xe8 compreso nell'intervallo",
"validation-stringLength": "Lunghezza del valore errata",
"validation-stringLength-formatted": "La lunghezza di {0} \xe8 errata",
"validation-custom": "Il valore non \xe8 corretto",
"validation-custom-formatted": "{0} non \xe8 corretto",
"validation-async": "Il valore non \xe8 corretto",
"validation-async-formatted": "{0} non \xe8 corretto",
"validation-compare": "I valori non corrispondono",
"validation-compare-formatted": "{0} non corrisponde",
"validation-pattern": "Il valore non \xe8 corretto",
"validation-pattern-formatted": "{0} non \xe8 corretto",
"validation-email": "L'Email non \xe8 corretta",
"validation-email-formatted": "{0} non \xe8 una email corretta",
"validation-mask": "Il valore non \xe8 corretto",
"dxLookup-searchPlaceholder": "Lunghezza minima: {0}",
"dxList-pullingDownText": "Trascina in basso per aggiornare...",
"dxList-pulledDownText": "Rilascia per aggiornare...",
"dxList-refreshingText": "Aggiornamento...",
"dxList-pageLoadingText": "Caricamento...",
"dxList-nextButtonText": "Carica altri risultati",
"dxList-selectAll": "Seleziona tutti",
"dxListEditDecorator-delete": "Elimina",
"dxListEditDecorator-more": "Ancora",
"dxScrollView-pullingDownText": "Trascina in basso per aggiornare...",
"dxScrollView-pulledDownText": "Rilascia per aggiornare...",
"dxScrollView-refreshingText": "Aggiornamento...",
"dxScrollView-reachBottomText": "Caricamento...",
"dxDateBox-simulatedDataPickerTitleTime": "Seleziona orario",
"dxDateBox-simulatedDataPickerTitleDate": "Seleziona data",
"dxDateBox-simulatedDataPickerTitleDateTime": "Seleziona data e ora",
"dxDateBox-validation-datetime": "Il valore deve essere una data o un orario",
"dxFileUploader-selectFile": "Seleziona file",
"dxFileUploader-dropFile": "o trascina il file qui",
"dxFileUploader-bytes": "bytes",
"dxFileUploader-kb": "kb",
"dxFileUploader-Mb": "Mb",
"dxFileUploader-Gb": "Gb",
"dxFileUploader-upload": "Carica",
"dxFileUploader-uploaded": "Caricato",
"dxFileUploader-readyToUpload": "Pronto per caricare",
"dxFileUploader-uploadAbortedMessage": "TODO",
"dxFileUploader-uploadFailedMessage": "Caricamento fallito",
"dxFileUploader-invalidFileExtension": "",
"dxFileUploader-invalidMaxFileSize": "",
"dxFileUploader-invalidMinFileSize": "",
"dxRangeSlider-ariaFrom": "Da",
"dxRangeSlider-ariaTill": "fino a",
"dxSwitch-switchedOnText": "ON",
"dxSwitch-switchedOffText": "OFF",
"dxForm-optionalMark": "opzionale",
"dxForm-requiredMessage": "{0} \xe8 richiesto",
"dxNumberBox-invalidValueMessage": "Il valore deve essere numerico",
"dxNumberBox-noDataText": "Nessun dato",
"dxDataGrid-columnChooserTitle": "Selezione colonne",
"dxDataGrid-columnChooserEmptyText": "Trascina qui una colonna per nasconderla",
"dxDataGrid-groupContinuesMessage": "Pagina successiva",
"dxDataGrid-groupContinuedMessage": "Continua da pagina precedente",
"dxDataGrid-groupHeaderText": "Raggruppa per questa colonna",
"dxDataGrid-ungroupHeaderText": "Separa",
"dxDataGrid-ungroupAllText": "Separa tutti",
"dxDataGrid-editingEditRow": "Modifica",
"dxDataGrid-editingSaveRowChanges": "Salva",
"dxDataGrid-editingCancelRowChanges": "Annulla",
"dxDataGrid-editingDeleteRow": "Elimina",
"dxDataGrid-editingUndeleteRow": "Ripristina",
"dxDataGrid-editingConfirmDeleteMessage": "Sei certo di voler eliminare questo record?",
"dxDataGrid-validationCancelChanges": "Annulla le modifiche",
"dxDataGrid-groupPanelEmptyText": "Trascina qui l'intestazione di una colonna per raggrupparla",
"dxDataGrid-noDataText": "Nessun dato",
"dxDataGrid-searchPanelPlaceholder": "Cerca...",
"dxDataGrid-filterRowShowAllText": "(Tutti)",
"dxDataGrid-filterRowResetOperationText": "Annulla",
"dxDataGrid-filterRowOperationEquals": "Uguale",
"dxDataGrid-filterRowOperationNotEquals": "Diverso",
"dxDataGrid-filterRowOperationLess": "Minore di",
"dxDataGrid-filterRowOperationLessOrEquals": "Minore o uguale a",
"dxDataGrid-filterRowOperationGreater": "Maggiore di",
"dxDataGrid-filterRowOperationGreaterOrEquals": "Maggiore o uguale a",
"dxDataGrid-filterRowOperationStartsWith": "Inizia con",
"dxDataGrid-filterRowOperationContains": "Contiene",
"dxDataGrid-filterRowOperationNotContains": "Non contiene",
"dxDataGrid-filterRowOperationEndsWith": "Termina con",
"dxDataGrid-filterRowOperationBetween": "Compreso",
"dxDataGrid-filterRowOperationBetweenStartText": "Inizio",
"dxDataGrid-filterRowOperationBetweenEndText": "Fine",
"dxDataGrid-applyFilterText": "Applica filtro",
"dxDataGrid-trueText": "vero",
"dxDataGrid-falseText": "falso",
"dxDataGrid-sortingAscendingText": "Ordinamento ascendente",
"dxDataGrid-sortingDescendingText": "Ordinamento discendente",
"dxDataGrid-sortingClearText": "Annulla ordinamento",
"dxDataGrid-editingSaveAllChanges": "Salva le modifiche",
"dxDataGrid-editingCancelAllChanges": "Annulla le modifiche",
"dxDataGrid-editingAddRow": "Aggiungi una riga",
"dxDataGrid-summaryMin": "Min: {0}",
"dxDataGrid-summaryMinOtherColumn": "Min di {1} \xe8 {0}",
"dxDataGrid-summaryMax": "Max: {0}",
"dxDataGrid-summaryMaxOtherColumn": "Max di {1} \xe8 {0}",
"dxDataGrid-summaryAvg": "Media: {0}",
"dxDataGrid-summaryAvgOtherColumn": "Media di {1} \xe8 {0}",
"dxDataGrid-summarySum": "Somma: {0}",
"dxDataGrid-summarySumOtherColumn": "Somma di {1} \xe8 {0}",
"dxDataGrid-summaryCount": "Elementi: {0}",
"dxDataGrid-columnFixingFix": "Blocca",
"dxDataGrid-columnFixingUnfix": "Sblocca",
"dxDataGrid-columnFixingLeftPosition": "Alla sinistra",
"dxDataGrid-columnFixingRightPosition": "Alla destra",
"dxDataGrid-exportTo": "Esporta",
"dxDataGrid-exportToExcel": "Esporta in Excel",
"dxDataGrid-exporting": "Esportare...",
"dxDataGrid-excelFormat": "File Excel",
"dxDataGrid-selectedRows": "Righe selezionate",
"dxDataGrid-exportSelectedRows": "Esporta le righe selezionate",
"dxDataGrid-exportAll": "Esporta tutti i dati",
"dxDataGrid-headerFilterEmptyValue": "(vuoto)",
"dxDataGrid-headerFilterOK": "OK",
"dxDataGrid-headerFilterCancel": "Annulla",
"dxDataGrid-ariaColumn": "Colonna",
"dxDataGrid-ariaValue": "Valore",
"dxDataGrid-ariaFilterCell": "Filtra cella",
"dxDataGrid-ariaCollapse": "Chiudi",
"dxDataGrid-ariaExpand": "Espandi",
"dxDataGrid-ariaDataGrid": "Griglia dati",
"dxDataGrid-ariaSearchInGrid": "Cerca nella griglia",
"dxDataGrid-ariaSelectAll": "Seleziona tutti",
"dxDataGrid-ariaSelectRow": "Seleziona riga",
"dxDataGrid-filterBuilderPopupTitle": "Composizione filtro",
"dxDataGrid-filterPanelCreateFilter": "Nuovo filtro",
"dxDataGrid-filterPanelClearFilter": "Cancella",
"dxDataGrid-filterPanelFilterEnabledHint": "Attiva il filtro",
"dxTreeList-ariaTreeList": "Albero",
"dxTreeList-editingAddRowToNode": "Aggiungi",
"dxPager-infoText": "Pagina {0} di {1} ({2} elementi)",
"dxPager-pagesCountText": "di",
"dxPager-pageSizesAllText": "Tutti",
"dxPivotGrid-grandTotal": "Totale",
"dxPivotGrid-total": "{0} Totale",
"dxPivotGrid-fieldChooserTitle": "Selezione campi",
"dxPivotGrid-showFieldChooser": "Mostra selezione campi",
"dxPivotGrid-expandAll": "Espandi tutto",
"dxPivotGrid-collapseAll": "Comprimi tutto",
"dxPivotGrid-sortColumnBySummary": 'Ordina "{0}" per questa colonna',
"dxPivotGrid-sortRowBySummary": 'Ordina "{0}" per questa riga',
"dxPivotGrid-removeAllSorting": "Rimuovi ordinamenti",
"dxPivotGrid-dataNotAvailable": "N/A",
"dxPivotGrid-rowFields": "Campi riga",
"dxPivotGrid-columnFields": "Campi colonna",
"dxPivotGrid-dataFields": "Campi dati",
"dxPivotGrid-filterFields": "Campi filtro",
"dxPivotGrid-allFields": "Tutti i campi",
"dxPivotGrid-columnFieldArea": "Trascina qui i campi colonna",
"dxPivotGrid-dataFieldArea": "Trascina qui i campi dati",
"dxPivotGrid-rowFieldArea": "Trascina qui i campi riga",
"dxPivotGrid-filterFieldArea": "Trascina qui i campi filtro",
"dxScheduler-editorLabelTitle": "Oggetto",
"dxScheduler-editorLabelStartDate": "Data inizio",
"dxScheduler-editorLabelEndDate": "Data fine",
"dxScheduler-editorLabelDescription": "Descrizione",
"dxScheduler-editorLabelRecurrence": "Ripeti",
"dxScheduler-openAppointment": "Apri appuntamento",
"dxScheduler-recurrenceNever": "Mai",
"dxScheduler-recurrenceMinutely": "Minutely",
"dxScheduler-recurrenceHourly": "Hourly",
"dxScheduler-recurrenceDaily": "Giornaliero",
"dxScheduler-recurrenceWeekly": "Settimanale",
"dxScheduler-recurrenceMonthly": "Mensile",
"dxScheduler-recurrenceYearly": "Annuale",
"dxScheduler-recurrenceRepeatEvery": "Ogni",
"dxScheduler-recurrenceRepeatOn": "Repeat On",
"dxScheduler-recurrenceEnd": "Termina ripetizione",
"dxScheduler-recurrenceAfter": "Dopo",
"dxScheduler-recurrenceOn": "Di",
"dxScheduler-recurrenceRepeatMinutely": "minute(s)",
"dxScheduler-recurrenceRepeatHourly": "hour(s)",
"dxScheduler-recurrenceRepeatDaily": "giorno(i)",
"dxScheduler-recurrenceRepeatWeekly": "settimana(e)",
"dxScheduler-recurrenceRepeatMonthly": "mese(i)",
"dxScheduler-recurrenceRepeatYearly": "anno(i)",
"dxScheduler-switcherDay": "Giorno",
"dxScheduler-switcherWeek": "Settimana",
"dxScheduler-switcherWorkWeek": "Settimana lavorativa",
"dxScheduler-switcherMonth": "Mese",
"dxScheduler-switcherAgenda": "Agenda",
"dxScheduler-switcherTimelineDay": "Cronologia giornaliera",
"dxScheduler-switcherTimelineWeek": "Cronologia settimanale",
"dxScheduler-switcherTimelineWorkWeek": "Cronologia settimana lavorativa",
"dxScheduler-switcherTimelineMonth": "Cronologia mensile",
"dxScheduler-recurrenceRepeatOnDate": "alla data",
"dxScheduler-recurrenceRepeatCount": "occorrenza(e)",
"dxScheduler-allDay": "Tutto il giorno",
"dxScheduler-confirmRecurrenceEditMessage": "Vuoi modificare solo questo appuntamento o tutte le sue ricorrenze?",
"dxScheduler-confirmRecurrenceDeleteMessage": "Vuoi eliminare solo questo appuntamento o tutte le sue ricorrenze?",
"dxScheduler-confirmRecurrenceEditSeries": "Modifica serie",
"dxScheduler-confirmRecurrenceDeleteSeries": "Elimina serie",
"dxScheduler-confirmRecurrenceEditOccurrence": "Modifica appuntamento",
"dxScheduler-confirmRecurrenceDeleteOccurrence": "Elimina appuntamento",
"dxScheduler-noTimezoneTitle": "Nessun fuso orario",
"dxScheduler-moreAppointments": "{0} ancora",
"dxCalendar-todayButtonText": "Oggi",
"dxCalendar-ariaWidgetName": "Calendario",
"dxColorView-ariaRed": "Rosso",
"dxColorView-ariaGreen": "Verde",
"dxColorView-ariaBlue": "Blu",
"dxColorView-ariaAlpha": "Trasparenza",
"dxColorView-ariaHex": "Colore",
"dxTagBox-selected": "{0} selezionati",
"dxTagBox-allSelected": "Tutti selezionati ({0})",
"dxTagBox-moreSelected": "{0} ancora",
"vizExport-printingButtonText": "Stampa",
"vizExport-titleMenuText": "Esportazione/Stampa",
"vizExport-exportButtonText": "{0} file",
"dxFilterBuilder-and": "E",
"dxFilterBuilder-or": "O",
"dxFilterBuilder-notAnd": "E non",
"dxFilterBuilder-notOr": "O non",
"dxFilterBuilder-addCondition": "Aggiungi condizione",
"dxFilterBuilder-addGroup": "Aggiungi gruppo",
"dxFilterBuilder-enterValueText": "<inserire un valore>",
"dxFilterBuilder-filterOperationEquals": "Uguale a",
"dxFilterBuilder-filterOperationNotEquals": "Diverso da",
"dxFilterBuilder-filterOperationLess": "Minore di",
"dxFilterBuilder-filterOperationLessOrEquals": "Minore o uguale a",
"dxFilterBuilder-filterOperationGreater": "Maggiore di",
"dxFilterBuilder-filterOperationGreaterOrEquals": "Maggiore o uguale a",
"dxFilterBuilder-filterOperationStartsWith": "Inizia con",
"dxFilterBuilder-filterOperationContains": "Contiene",
"dxFilterBuilder-filterOperationNotContains": "Non contiene",
"dxFilterBuilder-filterOperationEndsWith": "Termina con",
"dxFilterBuilder-filterOperationIsBlank": "\xc8 vuoto",
"dxFilterBuilder-filterOperationIsNotBlank": "Non \xe8 vuoto",
"dxFilterBuilder-filterOperationBetween": "Compreso",
"dxFilterBuilder-filterOperationAnyOf": "Include",
"dxFilterBuilder-filterOperationNoneOf": "Non include",
"dxHtmlEditor-dialogColorCaption": "Cambia il colore del testo",
"dxHtmlEditor-dialogBackgroundCaption": "Cambia il colore di sfondo",
"dxHtmlEditor-dialogLinkCaption": "Aggiungi link",
"dxHtmlEditor-dialogLinkUrlField": "URL",
"dxHtmlEditor-dialogLinkTextField": "Testo",
"dxHtmlEditor-dialogLinkTargetField": "Apri link in una nuova finestra",
"dxHtmlEditor-dialogImageCaption": "Agguingi Immagine",
"dxHtmlEditor-dialogImageUrlField": "URL",
"dxHtmlEditor-dialogImageAltField": "Testo alternativo",
"dxHtmlEditor-dialogImageWidthField": "Larghezza (px)",
"dxHtmlEditor-dialogImageHeightField": "Altezza (px)",
"dxHtmlEditor-dialogInsertTableRowsField": "!TODO",
"dxHtmlEditor-dialogInsertTableColumnsField": "!TODO",
"dxHtmlEditor-dialogInsertTableCaption": "!TODO",
"dxHtmlEditor-heading": "Intestazione",
"dxHtmlEditor-normalText": "Testo Normale",
"dxHtmlEditor-background": "TODO",
"dxHtmlEditor-bold": "TODO",
"dxHtmlEditor-color": "TODO",
"dxHtmlEditor-font": "TODO",
"dxHtmlEditor-italic": "TODO",
"dxHtmlEditor-link": "TODO",
"dxHtmlEditor-image": "TODO",
"dxHtmlEditor-size": "TODO",
"dxHtmlEditor-strike": "TODO",
"dxHtmlEditor-subscript": "TODO",
"dxHtmlEditor-superscript": "TODO",
"dxHtmlEditor-underline": "TODO",
"dxHtmlEditor-blockquote": "TODO",
"dxHtmlEditor-header": "TODO",
"dxHtmlEditor-increaseIndent": "TODO",
"dxHtmlEditor-decreaseIndent": "TODO",
"dxHtmlEditor-orderedList": "TODO",
"dxHtmlEditor-bulletList": "TODO",
"dxHtmlEditor-alignLeft": "TODO",
"dxHtmlEditor-alignCenter": "TODO",
"dxHtmlEditor-alignRight": "TODO",
"dxHtmlEditor-alignJustify": "TODO",
"dxHtmlEditor-codeBlock": "TODO",
"dxHtmlEditor-variable": "TODO",
"dxHtmlEditor-undo": "TODO",
"dxHtmlEditor-redo": "TODO",
"dxHtmlEditor-clear": "TODO",
"dxHtmlEditor-insertTable": "TODO",
"dxHtmlEditor-insertHeaderRow": "TODO",
"dxHtmlEditor-insertRowAbove": "TODO",
"dxHtmlEditor-insertRowBelow": "TODO",
"dxHtmlEditor-insertColumnLeft": "TODO",
"dxHtmlEditor-insertColumnRight": "TODO",
"dxHtmlEditor-deleteColumn": "TODO",
"dxHtmlEditor-deleteRow": "TODO",
"dxHtmlEditor-deleteTable": "TODO",
"dxHtmlEditor-cellProperties": "TODO",
"dxHtmlEditor-tableProperties": "TODO",
"dxHtmlEditor-insert": "TODO",
"dxHtmlEditor-delete": "TODO",
"dxHtmlEditor-border": "TODO",
"dxHtmlEditor-style": "TODO",
"dxHtmlEditor-width": "TODO",
"dxHtmlEditor-height": "TODO",
"dxHtmlEditor-borderColor": "TODO",
"dxHtmlEditor-tableBackground": "TODO",
"dxHtmlEditor-dimensions": "TODO",
"dxHtmlEditor-alignment": "TODO",
"dxHtmlEditor-horizontal": "TODO",
"dxHtmlEditor-vertical": "TODO",
"dxHtmlEditor-paddingVertical": "TODO",
"dxHtmlEditor-paddingHorizontal": "TODO",
"dxHtmlEditor-pixels": "TODO",
"dxHtmlEditor-list": "TODO",
"dxHtmlEditor-ordered": "TODO",
"dxHtmlEditor-bullet": "TODO",
"dxHtmlEditor-align": "TODO",
"dxHtmlEditor-center": "TODO",
"dxHtmlEditor-left": "TODO",
"dxHtmlEditor-right": "TODO",
"dxHtmlEditor-indent": "TODO",
"dxHtmlEditor-justify": "TODO",
"dxFileManager-newDirectoryName": "TODO",
"dxFileManager-rootDirectoryName": "TODO",
"dxFileManager-errorNoAccess": "TODO",
"dxFileManager-errorDirectoryExistsFormat": "TODO",
"dxFileManager-errorFileExistsFormat": "TODO",
"dxFileManager-errorFileNotFoundFormat": "TODO",
"dxFileManager-errorDirectoryNotFoundFormat": "TODO",
"dxFileManager-errorWrongFileExtension": "TODO",
"dxFileManager-errorMaxFileSizeExceeded": "TODO",
"dxFileManager-errorInvalidSymbols": "TODO",
"dxFileManager-errorDefault": "TODO",
"dxFileManager-errorDirectoryOpenFailed": "TODO",
"dxDiagram-categoryGeneral": "TODO",
"dxDiagram-categoryFlowchart": "TODO",
"dxDiagram-categoryOrgChart": "TODO",
"dxDiagram-categoryContainers": "TODO",
"dxDiagram-categoryCustom": "TODO",
"dxDiagram-commandExportToSvg": "TODO",
"dxDiagram-commandExportToPng": "TODO",
"dxDiagram-commandExportToJpg": "TODO",
"dxDiagram-commandUndo": "TODO",
"dxDiagram-commandRedo": "TODO",
"dxDiagram-commandFontName": "TODO",
"dxDiagram-commandFontSize": "TODO",
"dxDiagram-commandBold": "TODO",
"dxDiagram-commandItalic": "TODO",
"dxDiagram-commandUnderline": "TODO",
"dxDiagram-commandTextColor": "TODO",
"dxDiagram-commandLineColor": "TODO",
"dxDiagram-commandLineWidth": "TODO",
"dxDiagram-commandLineStyle": "TODO",
"dxDiagram-commandLineStyleSolid": "TODO",
"dxDiagram-commandLineStyleDotted": "TODO",
"dxDiagram-commandLineStyleDashed": "TODO",
"dxDiagram-commandFillColor": "TODO",
"dxDiagram-commandAlignLeft": "TODO",
"dxDiagram-commandAlignCenter": "TODO",
"dxDiagram-commandAlignRight": "TODO",
"dxDiagram-commandConnectorLineType": "TODO",
"dxDiagram-commandConnectorLineStraight": "TODO",
"dxDiagram-commandConnectorLineOrthogonal": "TODO",
"dxDiagram-commandConnectorLineStart": "TODO",
"dxDiagram-commandConnectorLineEnd": "TODO",
"dxDiagram-commandConnectorLineNone": "TODO",
"dxDiagram-commandConnectorLineArrow": "TODO",
"dxDiagram-commandFullscreen": "TODO",
"dxDiagram-commandUnits": "TODO",
"dxDiagram-commandPageSize": "TODO",
"dxDiagram-commandPageOrientation": "TODO",
"dxDiagram-commandPageOrientationLandscape": "TODO",
"dxDiagram-commandPageOrientationPortrait": "TODO",
"dxDiagram-commandPageColor": "TODO",
"dxDiagram-commandShowGrid": "TODO",
"dxDiagram-commandSnapToGrid": "TODO",
"dxDiagram-commandGridSize": "TODO",
"dxDiagram-commandZoomLevel": "TODO",
"dxDiagram-commandAutoZoom": "TODO",
"dxDiagram-commandFitToContent": "TODO",
"dxDiagram-commandFitToWidth": "TODO",
"dxDiagram-commandAutoZoomByContent": "TODO",
"dxDiagram-commandAutoZoomByWidth": "TODO",
"dxDiagram-commandSimpleView": "TODO",
"dxDiagram-commandCut": "TODO",
"dxDiagram-commandCopy": "TODO",
"dxDiagram-commandPaste": "TODO",
"dxDiagram-commandSelectAll": "TODO",
"dxDiagram-commandDelete": "TODO",
"dxDiagram-commandBringToFront": "TODO",
"dxDiagram-commandSendToBack": "TODO",
"dxDiagram-commandLock": "TODO",
"dxDiagram-commandUnlock": "TODO",
"dxDiagram-commandInsertShapeImage": "TODO",
"dxDiagram-commandEditShapeImage": "TODO",
"dxDiagram-commandDeleteShapeImage": "TODO",
"dxDiagram-commandLayoutLeftToRight": "TODO",
"dxDiagram-commandLayoutRightToLeft": "TODO",
"dxDiagram-commandLayoutTopToBottom": "TODO",
"dxDiagram-commandLayoutBottomToTop": "TODO",
"dxDiagram-unitIn": "TODO",
"dxDiagram-unitCm": "TODO",
"dxDiagram-unitPx": "TODO",
"dxDiagram-dialogButtonOK": "TODO",
"dxDiagram-dialogButtonCancel": "TODO",
"dxDiagram-dialogInsertShapeImageTitle": "TODO",
"dxDiagram-dialogEditShapeImageTitle": "TODO",
"dxDiagram-dialogEditShapeImageSelectButton": "TODO",
"dxDiagram-dialogEditShapeImageLabelText": "TODO",
"dxDiagram-uiExport": "TODO",
"dxDiagram-uiProperties": "TODO",
"dxDiagram-uiSettings": "TODO",
"dxDiagram-uiShowToolbox": "TODO",
"dxDiagram-uiSearch": "TODO",
"dxDiagram-uiStyle": "TODO",
"dxDiagram-uiLayout": "TODO",
"dxDiagram-uiLayoutTree": "TODO",
"dxDiagram-uiLayoutLayered": "TODO",
"dxDiagram-uiDiagram": "TODO",
"dxDiagram-uiText": "TODO",
"dxDiagram-uiObject": "TODO",
"dxDiagram-uiConnector": "TODO",
"dxDiagram-uiPage": "TODO",
"dxDiagram-shapeText": "TODO",
"dxDiagram-shapeRectangle": "TODO",
"dxDiagram-shapeEllipse": "TODO",
"dxDiagram-shapeCross": "TODO",
"dxDiagram-shapeTriangle": "TODO",
"dxDiagram-shapeDiamond": "TODO",
"dxDiagram-shapeHeart": "TODO",
"dxDiagram-shapePentagon": "TODO",
"dxDiagram-shapeHexagon": "TODO",
"dxDiagram-shapeOctagon": "TODO",
"dxDiagram-shapeStar": "TODO",
"dxDiagram-shapeArrowLeft": "TODO",
"dxDiagram-shapeArrowUp": "TODO",
"dxDiagram-shapeArrowRight": "TODO",
"dxDiagram-shapeArrowDown": "TODO",
"dxDiagram-shapeArrowUpDown": "TODO",
"dxDiagram-shapeArrowLeftRight": "TODO",
"dxDiagram-shapeProcess": "TODO",
"dxDiagram-shapeDecision": "TODO",
"dxDiagram-shapeTerminator": "TODO",
"dxDiagram-shapePredefinedProcess": "TODO",
"dxDiagram-shapeDocument": "TODO",
"dxDiagram-shapeMultipleDocuments": "TODO",
"dxDiagram-shapeManualInput": "TODO",
"dxDiagram-shapePreparation": "TODO",
"dxDiagram-shapeData": "TODO",
"dxDiagram-shapeDatabase": "TODO",
"dxDiagram-shapeHardDisk": "TODO",
"dxDiagram-shapeInternalStorage": "TODO",
"dxDiagram-shapePaperTape": "TODO",
"dxDiagram-shapeManualOperation": "TODO",
"dxDiagram-shapeDelay": "TODO",
"dxDiagram-shapeStoredData": "TODO",
"dxDiagram-shapeDisplay": "TODO",
"dxDiagram-shapeMerge": "TODO",
"dxDiagram-shapeConnector": "TODO",
"dxDiagram-shapeOr": "TODO",
"dxDiagram-shapeSummingJunction": "TODO",
"dxDiagram-shapeContainerDefaultText": "TODO",
"dxDiagram-shapeVerticalContainer": "TODO",
"dxDiagram-shapeHorizontalContainer": "TODO",
"dxDiagram-shapeCardDefaultText": "TODO",
"dxDiagram-shapeCardWithImageOnLeft": "TODO",
"dxDiagram-shapeCardWithImageOnTop": "TODO",
"dxDiagram-shapeCardWithImageOnRight": "TODO",
"dxGantt-dialogTitle": "TODO",
"dxGantt-dialogStartTitle": "TODO",
"dxGantt-dialogEndTitle": "TODO",
"dxGantt-dialogProgressTitle": "TODO",
"dxGantt-dialogResourcesTitle": "TODO",
"dxGantt-dialogResourceManagerTitle": "TODO",
"dxGantt-dialogTaskDetailsTitle": "TODO",
"dxGantt-dialogEditResourceListHint": "TODO",
"dxGantt-dialogEditNoResources": "TODO",
"dxGantt-dialogButtonAdd": "TODO",
"dxGantt-contextMenuNewTask": "TODO",
"dxGantt-contextMenuNewSubtask": "TODO",
"dxGantt-contextMenuDeleteTask": "TODO",
"dxGantt-contextMenuDeleteDependency": "TODO",
"dxGantt-dialogTaskDeleteConfirmation": "TODO",
"dxGantt-dialogDependencyDeleteConfirmation": "TODO",
"dxGantt-dialogResourcesDeleteConfirmation": "TODO",
"dxGantt-dialogConstraintCriticalViolationMessage": "TODO",
"dxGantt-dialogConstraintViolationMessage": "TODO",
"dxGantt-dialogCancelOperationMessage": "TODO",
"dxGantt-dialogDeleteDependencyMessage": "TODO",
"dxGantt-dialogMoveTaskAndKeepDependencyMessage": "TODO",
"dxGantt-undo": "TODO",
"dxGantt-redo": "TODO",
"dxGantt-expandAll": "TODO",
"dxGantt-collapseAll": "TODO",
"dxGantt-addNewTask": "TODO",
"dxGantt-deleteSelectedTask": "TODO",
"dxGantt-zoomIn": "TODO",
"dxGantt-zoomOut": "TODO",
"dxGantt-fullScreen": "TODO",
"dxGantt-quarter": "TODO",
"dxGantt-sortingAscendingText": "Ordinamento ascendente",
"dxGantt-sortingDescendingText": "Ordinamento discendente",
"dxGantt-sortingClearText": "Annulla ordinamento",
"dxGantt-showResources": "TODO",
"dxGantt-showDependencies": "TODO",
"dxGantt-dialogStartDateValidation": "TODO",
"dxGantt-dialogEndDateValidation": "TODO"
}
})
}));
|
/*!
* DevExtreme (dx.messages.hu.js)
* Version: 20.1.11 (build 21090-0315)
* Build date: Wed Mar 31 2021
*
* Copyright (c) 2012 - 2021 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
"use strict";
! function(root, factory) {
if ("function" === typeof define && define.amd) {
define(function(require) {
factory(require("devextreme/localization"))
})
} else {
if ("object" === typeof module && module.exports) {
factory(require("devextreme/localization"))
} else {
factory(DevExpress.localization)
}
}
}(this, function(localization) {
localization.loadMessages({
hu: {
Yes: "Igen",
No: "Nem",
Cancel: "M\xe9gse",
Clear: "T\xf6rl\xe9s",
Done: "K\xe9sz",
Loading: "Bet\xf6lt\xe9s...",
Select: "V\xe1laszt\xe1s...",
Search: "Keres\xe9s",
Back: "Vissza",
OK: "OK",
"dxCollectionWidget-noDataText": "Nincs megjelen\xedthet\u0151 adat",
"dxDropDownEditor-selectLabel": "V\xe1laszt\xe1s",
"validation-required": "K\xf6telez\u0151",
"validation-required-formatted": "{0} k\xf6telez\u0151",
"validation-numeric": "Az \xe9rt\xe9k sz\xe1m kell legyen",
"validation-numeric-formatted": "{0} sz\xe1m kell legyen",
"validation-range": "Az \xe9rt\xe9k tartom\xe1nyon k\xedv\xfclre esik",
"validation-range-formatted": "{0} tartom\xe1nyon k\xedv\xfclre esik",
"validation-stringLength": "Az \xe9rt\xe9k hossza helytelen",
"validation-stringLength-formatted": "{0} hossza helytelen",
"validation-custom": "\xc9rv\xe9nytelen \xe9rt\xe9k",
"validation-custom-formatted": "{0} \xe9rv\xe9nytelen",
"validation-async": "\xc9rv\xe9nytelen \xe9rt\xe9k",
"validation-async-formatted": "{0} \xe9rv\xe9nytelen",
"validation-compare": "Az \xe9rt\xe9kek nem egyeznek",
"validation-compare-formatted": "{0} nem egyezik",
"validation-pattern": "Az \xe9rt\xe9k nem illeszthet\u0151 a mint\xe1ra",
"validation-pattern-formatted": "{0} nem illeszthet\u0151 a mint\xe1ra",
"validation-email": "\xc9rv\xe9nytelen email",
"validation-email-formatted": "{0} \xe9rv\xe9nytelen email",
"validation-mask": "\xc9rv\xe9nytelen \xe9rt\xe9k",
"dxLookup-searchPlaceholder": "Minimum karaktersz\xe1m: {0}",
"dxList-pullingDownText": "H\xfazza le a friss\xedt\xe9shez...",
"dxList-pulledDownText": "Engedje el a friss\xedt\xe9shez...",
"dxList-refreshingText": "Friss\xedt\xe9s...",
"dxList-pageLoadingText": "Bet\xf6lt\xe9s...",
"dxList-nextButtonText": "Tov\xe1bb",
"dxList-selectAll": "\xd6sszes kiv\xe1laszt\xe1sa",
"dxListEditDecorator-delete": "T\xf6rl\xe9s",
"dxListEditDecorator-more": "T\xf6bb",
"dxScrollView-pullingDownText": "H\xfazza le a friss\xedt\xe9shez...",
"dxScrollView-pulledDownText": "Engedje el a friss\xedt\xe9shez...",
"dxScrollView-refreshingText": "Friss\xedt\xe9s...",
"dxScrollView-reachBottomText": "Bet\xf6lt\xe9s...",
"dxDateBox-simulatedDataPickerTitleTime": "V\xe1lasszon id\u0151t",
"dxDateBox-simulatedDataPickerTitleDate": "V\xe1lasszon d\xe1tumot",
"dxDateBox-simulatedDataPickerTitleDateTime": "V\xe1lasszon d\xe1tumot \xe9s id\u0151t",
"dxDateBox-validation-datetime": "Az \xe9rt\xe9k d\xe1tum vagy id\u0151 kell legyen",
"dxFileUploader-selectFile": "V\xe1lasszon f\xe1jlt",
"dxFileUploader-dropFile": "vagy h\xfazza a f\xe1jlt ide",
"dxFileUploader-bytes": "b\xe1jt",
"dxFileUploader-kb": "kb",
"dxFileUploader-Mb": "Mb",
"dxFileUploader-Gb": "Gb",
"dxFileUploader-upload": "Felt\xf6lt\xe9s",
"dxFileUploader-uploaded": "Felt\xf6ltve",
"dxFileUploader-readyToUpload": "Felt\xf6lt\xe9sre k\xe9sz",
"dxFileUploader-uploadFailedMessage": "A felt\xf6lt\xe9s sikertelen",
"dxFileUploader-invalidFileExtension": "Nem enged\xe9lyezett f\xe1jlt\xedpus",
"dxFileUploader-invalidMaxFileSize": "T\xfal nagy f\xe1jl",
"dxFileUploader-invalidMinFileSize": "T\xfal kicsi f\xe1jl",
"dxRangeSlider-ariaFrom": "-t\xf3l",
"dxRangeSlider-ariaTill": "-ig",
"dxSwitch-switchedOnText": "BE",
"dxSwitch-switchedOffText": "KI",
"dxForm-optionalMark": "v\xe1laszthat\xf3",
"dxForm-requiredMessage": "{0} k\xf6telez\u0151",
"dxNumberBox-invalidValueMessage": "Az \xe9rt\xe9k sz\xe1m kell legyen",
"dxNumberBox-noDataText": "Nincs adat",
"dxDataGrid-columnChooserTitle": "Oszlopv\xe1laszt\xf3",
"dxDataGrid-columnChooserEmptyText": "H\xfazza ide az oszlopot az elrejt\xe9shez",
"dxDataGrid-groupContinuesMessage": "A k\xf6vetkez\u0151 oldalon folytat\xf3dik",
"dxDataGrid-groupContinuedMessage": "Folytat\xe1s az el\u0151z\u0151 oldalr\xf3l",
"dxDataGrid-groupHeaderText": "Csoportos\xedt\xe1s ezen oszlop szerint",
"dxDataGrid-ungroupHeaderText": "Csoportbont\xe1s",
"dxDataGrid-ungroupAllText": "\xd6sszes csoportbont\xe1sa",
"dxDataGrid-editingEditRow": "Szerkeszt\xe9s",
"dxDataGrid-editingSaveRowChanges": "Ment\xe9s",
"dxDataGrid-editingCancelRowChanges": "M\xe9gse",
"dxDataGrid-editingDeleteRow": "T\xf6rl\xe9s",
"dxDataGrid-editingUndeleteRow": "Vissza\xe1ll\xedt\xe1s",
"dxDataGrid-editingConfirmDeleteMessage": "Biztosan t\xf6rli ezt a rekordot?",
"dxDataGrid-validationCancelChanges": "M\xf3dos\xedt\xe1sok elvet\xe9se",
"dxDataGrid-groupPanelEmptyText": "H\xfazzon ide egy oszlopfejl\xe9cet a csoportos\xedt\xe1shoz",
"dxDataGrid-noDataText": "Nincs adat",
"dxDataGrid-searchPanelPlaceholder": "Keres\xe9s...",
"dxDataGrid-filterRowShowAllText": "(Mind)",
"dxDataGrid-filterRowResetOperationText": "Vissza\xe1ll\xedt\xe1s",
"dxDataGrid-filterRowOperationEquals": "Egyenl\u0151",
"dxDataGrid-filterRowOperationNotEquals": "Nem egyenl\u0151",
"dxDataGrid-filterRowOperationLess": "Kisebb",
"dxDataGrid-filterRowOperationLessOrEquals": "Kisebb vagy egyenl\u0151",
"dxDataGrid-filterRowOperationGreater": "Nagyobb",
"dxDataGrid-filterRowOperationGreaterOrEquals": "Nagyobb vagy egyenl\u0151",
"dxDataGrid-filterRowOperationStartsWith": "Kezd\u0151dik",
"dxDataGrid-filterRowOperationContains": "Tartalmazza",
"dxDataGrid-filterRowOperationNotContains": "Nem tartalmazza",
"dxDataGrid-filterRowOperationEndsWith": "V\xe9gz\u0151dik",
"dxDataGrid-filterRowOperationBetween": "K\xf6z\xf6tt",
"dxDataGrid-filterRowOperationBetweenStartText": "Kezdete",
"dxDataGrid-filterRowOperationBetweenEndText": "V\xe9ge",
"dxDataGrid-applyFilterText": "Sz\u0171r\u0151 alkalmaz\xe1sa",
"dxDataGrid-trueText": "igaz",
"dxDataGrid-falseText": "hamis",
"dxDataGrid-sortingAscendingText": "N\xf6vekv\u0151",
"dxDataGrid-sortingDescendingText": "Cs\xf6kken\u0151",
"dxDataGrid-sortingClearText": "Rendez\xe9s t\xf6rl\xe9se",
"dxDataGrid-editingSaveAllChanges": "M\xf3dos\xedt\xe1sok ment\xe9se",
"dxDataGrid-editingCancelAllChanges": "M\xf3dos\xedt\xe1sok elvet\xe9se",
"dxDataGrid-editingAddRow": "Sor hozz\xe1ad\xe1sa",
"dxDataGrid-summaryMin": "Minimum: {0}",
"dxDataGrid-summaryMinOtherColumn": "{1} minimuma: {0}",
"dxDataGrid-summaryMax": "Maximum: {0}",
"dxDataGrid-summaryMaxOtherColumn": "{1} maximuma: {0}",
"dxDataGrid-summaryAvg": "\xc1tlag: {0}",
"dxDataGrid-summaryAvgOtherColumn": "{1} \xe1tlaga: {0}",
"dxDataGrid-summarySum": "\xd6sszeg: {0}",
"dxDataGrid-summarySumOtherColumn": "{1} \xf6sszege: {0}",
"dxDataGrid-summaryCount": "Darabsz\xe1m: {0}",
"dxDataGrid-columnFixingFix": "R\xf6gz\xedt\xe9s",
"dxDataGrid-columnFixingUnfix": "Felold\xe1s",
"dxDataGrid-columnFixingLeftPosition": "Balra",
"dxDataGrid-columnFixingRightPosition": "Jobbra",
"dxDataGrid-exportTo": "Export\xe1l\xe1s",
"dxDataGrid-exportToExcel": "Export\xe1l\xe1s Excel f\xe1jlba",
"dxDataGrid-exporting": "Export\xe1l\xe1s...",
"dxDataGrid-excelFormat": "Excel f\xe1jl",
"dxDataGrid-selectedRows": "Kiv\xe1lasztott sorok",
"dxDataGrid-exportSelectedRows": "Kiv\xe1lasztott sorok export\xe1l\xe1sa",
"dxDataGrid-exportAll": "Az \xf6sszes adat export\xe1l\xe1sa",
"dxDataGrid-headerFilterEmptyValue": "(\xdcresek)",
"dxDataGrid-headerFilterOK": "OK",
"dxDataGrid-headerFilterCancel": "M\xe9gse",
"dxDataGrid-ariaColumn": "Oszlop",
"dxDataGrid-ariaValue": "\xc9rt\xe9k",
"dxDataGrid-ariaFilterCell": "Sz\u0171r\u0151 cella",
"dxDataGrid-ariaCollapse": "\xd6sszecsuk\xe1s",
"dxDataGrid-ariaExpand": "Kibont\xe1s",
"dxDataGrid-ariaDataGrid": "Adatr\xe1cs",
"dxDataGrid-ariaSearchInGrid": "Keres\xe9s az adatr\xe1csban",
"dxDataGrid-ariaSelectAll": "\xd6sszes kiv\xe1laszt\xe1sa",
"dxDataGrid-ariaSelectRow": "Sor kiv\xe1laszt\xe1sa",
"dxDataGrid-filterBuilderPopupTitle": "Sz\u0171r\u0151k\xe9sz\xedt\u0151",
"dxDataGrid-filterPanelCreateFilter": "Sz\u0171r\u0151 l\xe9trehoz\xe1sa",
"dxDataGrid-filterPanelClearFilter": "T\xf6rl\xe9s",
"dxDataGrid-filterPanelFilterEnabledHint": "Sz\u0171r\u0151 enged\xe9lyez\xe9se",
"dxTreeList-ariaTreeList": "Fa lista",
"dxTreeList-editingAddRowToNode": "Hozz\xe1ad\xe1s",
"dxPager-infoText": "Oldal: {0}/{1} ({2} elem)",
"dxPager-pagesCountText": "/",
"dxPivotGrid-grandTotal": "Teljes \xf6sszeg",
"dxPivotGrid-total": "{0} \xd6sszeg",
"dxPivotGrid-fieldChooserTitle": "Mez\u0151v\xe1laszt\xf3",
"dxPivotGrid-showFieldChooser": "Mez\u0151v\xe1laszt\xf3 megjelen\xedt\xe9se",
"dxPivotGrid-expandAll": "\xd6sszes kibont\xe1sa",
"dxPivotGrid-collapseAll": "\xd6sszes \xf6sszecsuk\xe1sa",
"dxPivotGrid-sortColumnBySummary": 'Rendez\xe9s "{0}" ezen oszlop alapj\xe1n',
"dxPivotGrid-sortRowBySummary": 'Rendez\xe9s "{0}" ezen sor alapj\xe1n',
"dxPivotGrid-removeAllSorting": "\xd6sszes rendez\xe9s t\xf6rl\xe9se",
"dxPivotGrid-dataNotAvailable": "N/A",
"dxPivotGrid-rowFields": "Sormez\u0151",
"dxPivotGrid-columnFields": "Oszlopmez\u0151",
"dxPivotGrid-dataFields": "Adatmez\u0151",
"dxPivotGrid-filterFields": "Sz\u0171r\u0151mez\u0151",
"dxPivotGrid-allFields": "\xd6sszes mez\u0151",
"dxPivotGrid-columnFieldArea": "H\xfazza az oszlopmez\u0151ket ide",
"dxPivotGrid-dataFieldArea": "H\xfazza az adatmez\u0151ket ide",
"dxPivotGrid-rowFieldArea": "H\xfazza a sormez\u0151ket ide",
"dxPivotGrid-filterFieldArea": "H\xfazza a sz\u0171r\u0151mez\u0151ket ide",
"dxScheduler-editorLabelTitle": "T\xe1rgy",
"dxScheduler-editorLabelStartDate": "Kezd\xe9s d\xe1tuma",
"dxScheduler-editorLabelEndDate": "Befejez\xe9s d\xe1tuma",
"dxScheduler-editorLabelDescription": "Le\xedr\xe1s",
"dxScheduler-editorLabelRecurrence": "Ism\xe9tl\u0151d\xe9s",
"dxScheduler-openAppointment": "Tal\xe1lkoz\xf3 megnyit\xe1sa",
"dxScheduler-recurrenceNever": "Soha",
"dxScheduler-recurrenceMinutely": "Minutely",
"dxScheduler-recurrenceHourly": "Hourly",
"dxScheduler-recurrenceDaily": "Naponta",
"dxScheduler-recurrenceWeekly": "Hetente",
"dxScheduler-recurrenceMonthly": "Havonta",
"dxScheduler-recurrenceYearly": "\xc9vente",
"dxScheduler-recurrenceRepeatEvery": "Ism\xe9tl\u0151d\xe9s minden",
"dxScheduler-recurrenceRepeatOn": "Ism\xe9tl\u0151d\xe9s",
"dxScheduler-recurrenceEnd": "Ism\xe9tl\u0151d\xe9s v\xe9ge",
"dxScheduler-recurrenceAfter": "Ut\xe1n",
"dxScheduler-recurrenceOn": "Ekkor",
"dxScheduler-recurrenceRepeatMinutely": "minute(s)",
"dxScheduler-recurrenceRepeatHourly": "hour(s)",
"dxScheduler-recurrenceRepeatDaily": "nap(ok)",
"dxScheduler-recurrenceRepeatWeekly": "h\xe9t(ek)",
"dxScheduler-recurrenceRepeatMonthly": "h\xf3nap(ok)",
"dxScheduler-recurrenceRepeatYearly": "\xe9v(ek)",
"dxScheduler-switcherDay": "Nap",
"dxScheduler-switcherWeek": "H\xe9t",
"dxScheduler-switcherWorkWeek": "Munkah\xe9t",
"dxScheduler-switcherMonth": "H\xf3nap",
"dxScheduler-switcherAgenda": "Napt\xe1r",
"dxScheduler-switcherTimelineDay": "Id\u0151vonal nap",
"dxScheduler-switcherTimelineWeek": "Id\u0151vonal h\xe9t",
"dxScheduler-switcherTimelineWorkWeek": "Id\u0151vonal munkah\xe9t",
"dxScheduler-switcherTimelineMonth": "Id\u0151vonal h\xf3nap",
"dxScheduler-recurrenceRepeatOnDate": "d\xe1tumon",
"dxScheduler-recurrenceRepeatCount": "el\u0151fordul\xe1s(ok)",
"dxScheduler-allDay": "Eg\xe9sz nap",
"dxScheduler-confirmRecurrenceEditMessage": "Csak ezt az alkalmat szeretn\xe9 szerkeszteni, vagy az \xf6sszes ism\xe9tl\u0151d\xe9st?",
"dxScheduler-confirmRecurrenceDeleteMessage": "Csak ezt az alkalmat szeretn\xe9 t\xf6r\xf6lni, vagy az \xf6sszes ism\xe9tl\u0151d\xe9st?",
"dxScheduler-confirmRecurrenceEditSeries": "Ism\xe9tl\u0151d\xe9s szerkeszt\xe9se",
"dxScheduler-confirmRecurrenceDeleteSeries": "Ism\xe9tl\u0151d\xe9s t\xf6rl\xe9se",
"dxScheduler-confirmRecurrenceEditOccurrence": "Alkalom szerkeszt\xe9se",
"dxScheduler-confirmRecurrenceDeleteOccurrence": "Alkalom t\xf6rl\xe9se",
"dxScheduler-noTimezoneTitle": "Nincs id\u0151z\xf3na",
"dxScheduler-moreAppointments": "{0} t\xf6bb",
"dxCalendar-todayButtonText": "Ma",
"dxCalendar-ariaWidgetName": "Napt\xe1r",
"dxColorView-ariaRed": "Piros",
"dxColorView-ariaGreen": "Z\xf6ld",
"dxColorView-ariaBlue": "K\xe9k",
"dxColorView-ariaAlpha": "\xc1tl\xe1tsz\xf3s\xe1g",
"dxColorView-ariaHex": "Sz\xednk\xf3d",
"dxTagBox-selected": "{0} kiv\xe1lasztva",
"dxTagBox-allSelected": "\xd6sszes kiv\xe1lasztva ({0})",
"dxTagBox-moreSelected": "{0} t\xf6bb",
"vizExport-printingButtonText": "Nyomtat\xe1s",
"vizExport-titleMenuText": "Export\xe1l\xe1s/Nyomtat\xe1s",
"vizExport-exportButtonText": "{0} f\xe1jl",
"dxFilterBuilder-and": "\xc9s",
"dxFilterBuilder-or": "Vagy",
"dxFilterBuilder-notAnd": "Nem \xc9s",
"dxFilterBuilder-notOr": "Nem Vagy",
"dxFilterBuilder-addCondition": "Felt\xe9tel hozz\xe1ad\xe1sa",
"dxFilterBuilder-addGroup": "Csoport hozz\xe1ad\xe1sa",
"dxFilterBuilder-enterValueText": "<\xedrjon be egy \xe9rt\xe9ket>",
"dxFilterBuilder-filterOperationEquals": "Egyenl\u0151",
"dxFilterBuilder-filterOperationNotEquals": "Nem egyenl\u0151",
"dxFilterBuilder-filterOperationLess": "Kisebb",
"dxFilterBuilder-filterOperationLessOrEquals": "Kisebb vagy egyenl\u0151",
"dxFilterBuilder-filterOperationGreater": "Nagyobb",
"dxFilterBuilder-filterOperationGreaterOrEquals": "Nagyobb vagy egyenl\u0151",
"dxFilterBuilder-filterOperationStartsWith": "Kezd\u0151dik",
"dxFilterBuilder-filterOperationContains": "Tartalmazza",
"dxFilterBuilder-filterOperationNotContains": "Nem tartalmazza",
"dxFilterBuilder-filterOperationEndsWith": "V\xe9gz\u0151dik",
"dxFilterBuilder-filterOperationIsBlank": "\xdcres",
"dxFilterBuilder-filterOperationIsNotBlank": "Nem \xfcres",
"dxFilterBuilder-filterOperationBetween": "K\xf6z\xf6tt",
"dxFilterBuilder-filterOperationAnyOf": "Valamelyik",
"dxFilterBuilder-filterOperationNoneOf": "Egyik sem",
"dxHtmlEditor-dialogColorCaption": "Bet\u0171sz\xedn v\xe1laszt\xe1s",
"dxHtmlEditor-dialogBackgroundCaption": "H\xe1tt\xe9rsz\xedn v\xe1laszt\xe1s",
"dxHtmlEditor-dialogLinkCaption": "Link hozz\xe1ad\xe1sa",
"dxHtmlEditor-dialogLinkUrlField": "URL",
"dxHtmlEditor-dialogLinkTextField": "Sz\xf6veg",
"dxHtmlEditor-dialogLinkTargetField": "Link megnyit\xe1sa \xfaj ablakban",
"dxHtmlEditor-dialogImageCaption": "K\xe9p hozz\xe1ad\xe1sa",
"dxHtmlEditor-dialogImageUrlField": "URL",
"dxHtmlEditor-dialogImageAltField": "Alternat\xedv sz\xf6veg",
"dxHtmlEditor-dialogImageWidthField": "Sz\xe9less\xe9g (px)",
"dxHtmlEditor-dialogImageHeightField": "Magass\xe1g (px)",
"dxHtmlEditor-heading": "Fejl\xe9c",
"dxHtmlEditor-normalText": "Norm\xe1l sz\xf6veg",
"dxFileManager-newDirectoryName": "N\xe9vtelen k\xf6nyvt\xe1r",
"dxFileManager-rootDirectoryName": "F\xe1jlok",
"dxFileManager-errorNoAccess": "Hozz\xe1f\xe9r\xe9s megtagadva. A m\u0171veletet nem lehet befejezni.",
"dxFileManager-errorDirectoryExistsFormat": "'{0}' nev\u0171 k\xf6nyvt\xe1r m\xe1r l\xe9tezik.",
"dxFileManager-errorFileExistsFormat": "'{0}' nev\u0171 f\xe1jl m\xe1r l\xe9tezik.",
"dxFileManager-errorFileNotFoundFormat": "'{0}' nev\u0171 f\xe1jl nem tal\xe1lhat\xf3",
"dxFileManager-errorDirectoryNotFoundFormat": "'{0}' nev\u0171 k\xf6nyvt\xe1r nem tal\xe1lhat\xf3",
"dxFileManager-errorWrongFileExtension": "Nem enged\xe9lyezett f\xe1jlt\xedpus",
"dxFileManager-errorMaxFileSizeExceeded": "A f\xe1jlm\xe9ret meghaladja a megengedett legnagyobb m\xe9retet",
"dxFileManager-errorDefault": "Ismeretlen hiba.",
"dxFileManager-errorDirectoryOpenFailed": "TODO",
"dxDiagram-categoryGeneral": "\xc1ltal\xe1nos",
"dxDiagram-categoryFlowchart": "Folyamat\xe1bra",
"dxDiagram-categoryOrgChart": "Szervezeti \xe1bra",
"dxDiagram-categoryContainers": "T\xe1rol\xf3k",
"dxDiagram-categoryCustom": "Egyedi",
"dxDiagram-commandExportToSvg": "Export\xe1l\xe1s SVG-be",
"dxDiagram-commandExportToPng": "Export\xe1l\xe1s PNG-be",
"dxDiagram-commandExportToJpg": "Export\xe1l\xe1s JPEG-be",
"dxDiagram-commandUndo": "Visszavon\xe1s",
"dxDiagram-commandRedo": "\xdajra",
"dxDiagram-commandFontName": "Bet\u0171t\xedpus",
"dxDiagram-commandFontSize": "Bet\u0171m\xe9ret",
"dxDiagram-commandBold": "F\xe9lk\xf6v\xe9r",
"dxDiagram-commandItalic": "D\u0151lt",
"dxDiagram-commandUnderline": "Al\xe1h\xfazott",
"dxDiagram-commandTextColor": "Bet\u0171sz\xedn",
"dxDiagram-commandLineColor": "Sor sz\xedne",
"dxDiagram-commandLineWidth": "TODO",
"dxDiagram-commandLineStyle": "TODO",
"dxDiagram-commandLineStyleSolid": "TODO",
"dxDiagram-commandLineStyleDotted": "TODO",
"dxDiagram-commandLineStyleDashed": "TODO",
"dxDiagram-commandFillColor": "Kit\xf6lt\u0151 sz\xedn",
"dxDiagram-commandAlignLeft": "Balra igaz\xedt\xe1s",
"dxDiagram-commandAlignCenter": "K\xf6z\xe9pre igaz\xedt\xe1s",
"dxDiagram-commandAlignRight": "Jobbra igaz\xedt\xe1s",
"dxDiagram-commandConnectorLineType": "\xd6sszek\xf6t\u0151 vonal t\xedpusa",
"dxDiagram-commandConnectorLineStraight": "Egyenes",
"dxDiagram-commandConnectorLineOrthogonal": "Mer\u0151leges",
"dxDiagram-commandConnectorLineStart": "\xd6sszek\xf6t\u0151 vonal kezdete",
"dxDiagram-commandConnectorLineEnd": "\xd6sszek\xf6t\u0151 vonal v\xe9ge",
"dxDiagram-commandConnectorLineNone": "Egyik sem",
"dxDiagram-commandConnectorLineArrow": "Ny\xedl",
"dxDiagram-commandFullscreen": "Teljes k\xe9perny\u0151",
"dxDiagram-commandUnits": "Egys\xe9gek",
"dxDiagram-commandPageSize": "Lapm\xe9ret",
"dxDiagram-commandPageOrientation": "T\xe1jol\xe1s",
"dxDiagram-commandPageOrientationLandscape": "Fekv\u0151",
"dxDiagram-commandPageOrientationPortrait": "\xc1ll\xf3",
"dxDiagram-commandPageColor": "Oldal sz\xedne",
"dxDiagram-commandShowGrid": "R\xe1cs megjelen\xedt\xe9se",
"dxDiagram-commandSnapToGrid": "R\xe1cshoz igaz\xedt\xe1s",
"dxDiagram-commandGridSize": "R\xe1cs m\xe9rete",
"dxDiagram-commandZoomLevel": "Nagy\xedt\xe1s",
"dxDiagram-commandAutoZoom": "Automatikus nagy\xedt\xe1s",
"dxDiagram-commandFitToContent": "TODO",
"dxDiagram-commandFitToWidth": "TODO",
"dxDiagram-commandAutoZoomByContent": "TODO",
"dxDiagram-commandAutoZoomByWidth": "TODO",
"dxDiagram-commandSimpleView": "Egyszer\u0171s\xedtett n\xe9zet",
"dxDiagram-commandCut": "Kiv\xe1g\xe1s",
"dxDiagram-commandCopy": "M\xe1sol\xe1s",
"dxDiagram-commandPaste": "Beilleszt\xe9s",
"dxDiagram-commandSelectAll": "\xd6sszes kiv\xe1laszt\xe1sa",
"dxDiagram-commandDelete": "T\xf6rl\xe9s",
"dxDiagram-commandBringToFront": "El\u0151re hoz",
"dxDiagram-commandSendToBack": "H\xe1tra k\xfcld",
"dxDiagram-commandLock": "R\xf6gz\xedt",
"dxDiagram-commandUnlock": "Felold",
"dxDiagram-commandInsertShapeImage": "K\xe9p besz\xfar\xe1sa...",
"dxDiagram-commandEditShapeImage": "K\xe9p cser\xe9je...",
"dxDiagram-commandDeleteShapeImage": "K\xe9p t\xf6rl\xe9se",
"dxDiagram-commandLayoutLeftToRight": "TODO",
"dxDiagram-commandLayoutRightToLeft": "TODO",
"dxDiagram-commandLayoutTopToBottom": "TODO",
"dxDiagram-commandLayoutBottomToTop": "TODO",
"dxDiagram-unitIn": "in",
"dxDiagram-unitCm": "cm",
"dxDiagram-unitPx": "px",
"dxDiagram-dialogButtonOK": "OK",
"dxDiagram-dialogButtonCancel": "M\xe9gse",
"dxDiagram-dialogInsertShapeImageTitle": "K\xe9p besz\xfar\xe1sa",
"dxDiagram-dialogEditShapeImageTitle": "K\xe9p cser\xe9je",
"dxDiagram-dialogEditShapeImageSelectButton": "K\xe9p kiv\xe1laszt\xe1sa",
"dxDiagram-dialogEditShapeImageLabelText": "vagy h\xfazza a f\xe1jlt ide",
"dxDiagram-uiExport": "Export\xe1l\xe1s",
"dxDiagram-uiProperties": "Tulajdons\xe1gok",
"dxDiagram-uiSettings": "TODO",
"dxDiagram-uiShowToolbox": "TODO",
"dxDiagram-uiSearch": "TODO",
"dxDiagram-uiStyle": "TODO",
"dxDiagram-uiLayout": "TODO",
"dxDiagram-uiLayoutTree": "Fa",
"dxDiagram-uiLayoutLayered": "R\xe9teges",
"dxDiagram-uiDiagram": "TODO",
"dxDiagram-uiText": "TODO",
"dxDiagram-uiObject": "TODO",
"dxDiagram-uiConnector": "TODO",
"dxDiagram-uiPage": "TODO",
"dxDiagram-shapeText": "TODO",
"dxDiagram-shapeRectangle": "TODO",
"dxDiagram-shapeEllipse": "TODO",
"dxDiagram-shapeCross": "TODO",
"dxDiagram-shapeTriangle": "TODO",
"dxDiagram-shapeDiamond": "TODO",
"dxDiagram-shapeHeart": "TODO",
"dxDiagram-shapePentagon": "TODO",
"dxDiagram-shapeHexagon": "TODO",
"dxDiagram-shapeOctagon": "TODO",
"dxDiagram-shapeStar": "TODO",
"dxDiagram-shapeArrowLeft": "TODO",
"dxDiagram-shapeArrowUp": "TODO",
"dxDiagram-shapeArrowRight": "TODO",
"dxDiagram-shapeArrowDown": "TODO",
"dxDiagram-shapeArrowUpDown": "TODO",
"dxDiagram-shapeArrowLeftRight": "TODO",
"dxDiagram-shapeProcess": "TODO",
"dxDiagram-shapeDecision": "TODO",
"dxDiagram-shapeTerminator": "TODO",
"dxDiagram-shapePredefinedProcess": "TODO",
"dxDiagram-shapeDocument": "TODO",
"dxDiagram-shapeMultipleDocuments": "TODO",
"dxDiagram-shapeManualInput": "TODO",
"dxDiagram-shapePreparation": "TODO",
"dxDiagram-shapeData": "TODO",
"dxDiagram-shapeDatabase": "TODO",
"dxDiagram-shapeHardDisk": "TODO",
"dxDiagram-shapeInternalStorage": "TODO",
"dxDiagram-shapePaperTape": "TODO",
"dxDiagram-shapeManualOperation": "TODO",
"dxDiagram-shapeDelay": "TODO",
"dxDiagram-shapeStoredData": "TODO",
"dxDiagram-shapeDisplay": "TODO",
"dxDiagram-shapeMerge": "TODO",
"dxDiagram-shapeConnector": "TODO",
"dxDiagram-shapeOr": "TODO",
"dxDiagram-shapeSummingJunction": "TODO",
"dxDiagram-shapeContainerDefaultText": "TODO",
"dxDiagram-shapeVerticalContainer": "TODO",
"dxDiagram-shapeHorizontalContainer": "TODO",
"dxDiagram-shapeCardDefaultText": "TODO",
"dxDiagram-shapeCardWithImageOnLeft": "TODO",
"dxDiagram-shapeCardWithImageOnTop": "TODO",
"dxDiagram-shapeCardWithImageOnRight": "TODO",
"dxGantt-dialogTitle": "TODO",
"dxGantt-dialogStartTitle": "TODO",
"dxGantt-dialogEndTitle": "TODO",
"dxGantt-dialogProgressTitle": "TODO",
"dxGantt-dialogResourcesTitle": "TODO",
"dxGantt-dialogResourceManagerTitle": "TODO",
"dxGantt-dialogTaskDetailsTitle": "TODO",
"dxGantt-dialogEditResourceListHint": "TODO",
"dxGantt-dialogEditNoResources": "TODO",
"dxGantt-dialogButtonAdd": "TODO",
"dxGantt-contextMenuNewTask": "TODO",
"dxGantt-contextMenuNewSubtask": "TODO",
"dxGantt-contextMenuDeleteTask": "TODO",
"dxGantt-contextMenuDeleteDependency": "TODO",
"dxGantt-dialogTaskDeleteConfirmation": "TODO",
"dxGantt-dialogDependencyDeleteConfirmation": "TODO",
"dxGantt-dialogResourcesDeleteConfirmation": "TODO",
"dxGantt-dialogConstraintCriticalViolationMessage": "TODO",
"dxGantt-dialogConstraintViolationMessage": "TODO",
"dxGantt-dialogCancelOperationMessage": "TODO",
"dxGantt-dialogDeleteDependencyMessage": "TODO",
"dxGantt-dialogMoveTaskAndKeepDependencyMessage": "TODO",
"dxGantt-undo": "TODO",
"dxGantt-redo": "TODO",
"dxGantt-expandAll": "TODO",
"dxGantt-collapseAll": "TODO",
"dxGantt-addNewTask": "TODO",
"dxGantt-deleteSelectedTask": "TODO",
"dxGantt-zoomIn": "TODO",
"dxGantt-zoomOut": "TODO",
"dxGantt-fullScreen": "TODO"
}
})
});
|
/*
Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang("language","pl",{button:"Ustaw język",remove:"Usuń język"});
|
import{W as t}from"./index-fa69192f.js";class s extends t{static get formatter(){}static get params(){return{localized:!0}}init(){super.init()}connected(){super.connected(),this.apply()}changed(t,s){super.changed(t,s),t in this.props&&this.isConnected&&this.apply()}apply(){this.locale||this.setLocale(this.lang),this.host.innerHTML=this.constructor.formatter(this.value,this.locale,this)}fromHostValue(t,s){this.value=t,this.apply()}}export{s as F};
|
import './index-903a7eb6.js';
import InputBehavior from './input-e16f7aac.js';
class TextAreaBehavior extends InputBehavior {
static get params() {
return {
tag: 'textarea',
};
}
}
export default TextAreaBehavior;
|
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.InputMask = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _DomHandler = _interopRequireDefault(require("../utils/DomHandler"));
var _InputText = require("../inputtext/InputText");
var _ClassNames = require("../utils/ClassNames");
var _Tooltip = require("../tooltip/Tooltip");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var InputMask = /*#__PURE__*/function (_Component) {
_inherits(InputMask, _Component);
var _super = _createSuper(InputMask);
function InputMask(props) {
var _this;
_classCallCheck(this, InputMask);
_this = _super.call(this, props);
_this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this));
_this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this));
_this.onKeyDown = _this.onKeyDown.bind(_assertThisInitialized(_this));
_this.onKeyPress = _this.onKeyPress.bind(_assertThisInitialized(_this));
_this.onInput = _this.onInput.bind(_assertThisInitialized(_this));
_this.handleInputChange = _this.handleInputChange.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(InputMask, [{
key: "caret",
value: function caret(first, last) {
var range, begin, end;
if (!this.input.offsetParent || this.input !== document.activeElement) {
return;
}
if (typeof first === 'number') {
begin = first;
end = typeof last === 'number' ? last : begin;
if (this.input.setSelectionRange) {
this.input.setSelectionRange(begin, end);
} else if (this.input['createTextRange']) {
range = this.input['createTextRange']();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', begin);
range.select();
}
} else {
if (this.input.setSelectionRange) {
begin = this.input.selectionStart;
end = this.input.selectionEnd;
} else if (document['selection'] && document['selection'].createRange) {
range = document['selection'].createRange();
begin = 0 - range.duplicate().moveStart('character', -100000);
end = begin + range.text.length;
}
return {
begin: begin,
end: end
};
}
}
}, {
key: "isCompleted",
value: function isCompleted() {
for (var i = this.firstNonMaskPos; i <= this.lastRequiredNonMaskPos; i++) {
if (this.tests[i] && this.buffer[i] === this.getPlaceholder(i)) {
return false;
}
}
return true;
}
}, {
key: "getPlaceholder",
value: function getPlaceholder(i) {
if (i < this.props.slotChar.length) {
return this.props.slotChar.charAt(i);
}
return this.props.slotChar.charAt(0);
}
}, {
key: "getValue",
value: function getValue() {
return this.props.unmask ? this.getUnmaskedValue() : this.input && this.input.value;
}
}, {
key: "seekNext",
value: function seekNext(pos) {
while (++pos < this.len && !this.tests[pos]) {
;
}
return pos;
}
}, {
key: "seekPrev",
value: function seekPrev(pos) {
while (--pos >= 0 && !this.tests[pos]) {
;
}
return pos;
}
}, {
key: "shiftL",
value: function shiftL(begin, end) {
var i, j;
if (begin < 0) {
return;
}
for (i = begin, j = this.seekNext(end); i < this.len; i++) {
if (this.tests[i]) {
if (j < this.len && this.tests[i].test(this.buffer[j])) {
this.buffer[i] = this.buffer[j];
this.buffer[j] = this.getPlaceholder(j);
} else {
break;
}
j = this.seekNext(j);
}
}
this.writeBuffer();
this.caret(Math.max(this.firstNonMaskPos, begin));
}
}, {
key: "shiftR",
value: function shiftR(pos) {
var i, c, j, t;
for (i = pos, c = this.getPlaceholder(pos); i < this.len; i++) {
if (this.tests[i]) {
j = this.seekNext(i);
t = this.buffer[i];
this.buffer[i] = c;
if (j < this.len && this.tests[j].test(t)) {
c = t;
} else {
break;
}
}
}
}
}, {
key: "handleAndroidInput",
value: function handleAndroidInput(e) {
var curVal = this.input.value;
var pos = this.caret();
if (this.oldVal && this.oldVal.length && this.oldVal.length > curVal.length) {
// a deletion or backspace happened
this.checkVal(true);
while (pos.begin > 0 && !this.tests[pos.begin - 1]) {
pos.begin--;
}
if (pos.begin === 0) {
while (pos.begin < this.firstNonMaskPos && !this.tests[pos.begin]) {
pos.begin++;
}
}
this.caret(pos.begin, pos.begin);
} else {
this.checkVal(true);
while (pos.begin < this.len && !this.tests[pos.begin]) {
pos.begin++;
}
this.caret(pos.begin, pos.begin);
}
if (this.props.onComplete && this.isCompleted()) {
this.props.onComplete({
originalEvent: e,
value: this.getValue()
});
}
}
}, {
key: "onBlur",
value: function onBlur(e) {
this.focus = false;
this.checkVal();
this.updateModel(e);
this.updateFilledState();
if (this.props.onBlur) {
this.props.onBlur(e);
}
if (this.input.value !== this.focusText) {
var event = document.createEvent('HTMLEvents');
event.initEvent('change', true, false);
this.input.dispatchEvent(event);
}
}
}, {
key: "onKeyDown",
value: function onKeyDown(e) {
if (this.props.readOnly) {
return;
}
var k = e.which || e.keyCode,
pos,
begin,
end;
var iPhone = /iphone/i.test(_DomHandler.default.getUserAgent());
this.oldVal = this.input.value; //backspace, delete, and escape get special treatment
if (k === 8 || k === 46 || iPhone && k === 127) {
pos = this.caret();
begin = pos.begin;
end = pos.end;
if (end - begin === 0) {
begin = k !== 46 ? this.seekPrev(begin) : end = this.seekNext(begin - 1);
end = k === 46 ? this.seekNext(end) : end;
}
this.clearBuffer(begin, end);
this.shiftL(begin, end - 1);
this.updateModel(e);
e.preventDefault();
} else if (k === 13) {
// enter
this.onBlur(e);
this.updateModel(e);
} else if (k === 27) {
// escape
this.input.value = this.focusText;
this.caret(0, this.checkVal());
this.updateModel(e);
e.preventDefault();
}
}
}, {
key: "onKeyPress",
value: function onKeyPress(e) {
var _this2 = this;
if (this.props.readOnly) {
return;
}
var k = e.which || e.keyCode,
pos = this.caret(),
p,
c,
next,
completed;
if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {
//Ignore
return;
} else if (k && k !== 13) {
if (pos.end - pos.begin !== 0) {
this.clearBuffer(pos.begin, pos.end);
this.shiftL(pos.begin, pos.end - 1);
}
p = this.seekNext(pos.begin - 1);
if (p < this.len) {
c = String.fromCharCode(k);
if (this.tests[p].test(c)) {
this.shiftR(p);
this.buffer[p] = c;
this.writeBuffer();
next = this.seekNext(p);
if (/android/i.test(_DomHandler.default.getUserAgent())) {
//Path for CSP Violation on FireFox OS 1.1
var proxy = function proxy() {
_this2.caret(next);
};
setTimeout(proxy, 0);
} else {
this.caret(next);
}
if (pos.begin <= this.lastRequiredNonMaskPos) {
completed = this.isCompleted();
}
}
}
e.preventDefault();
}
this.updateModel(e);
if (this.props.onComplete && completed) {
this.props.onComplete({
originalEvent: e,
value: this.getValue()
});
}
}
}, {
key: "clearBuffer",
value: function clearBuffer(start, end) {
var i;
for (i = start; i < end && i < this.len; i++) {
if (this.tests[i]) {
this.buffer[i] = this.getPlaceholder(i);
}
}
}
}, {
key: "writeBuffer",
value: function writeBuffer() {
this.input.value = this.buffer.join('');
}
}, {
key: "checkVal",
value: function checkVal(allow) {
this.isValueChecked = true; //try to place characters where they belong
var test = this.input.value,
lastMatch = -1,
i,
c,
pos;
for (i = 0, pos = 0; i < this.len; i++) {
if (this.tests[i]) {
this.buffer[i] = this.getPlaceholder(i);
while (pos++ < test.length) {
c = test.charAt(pos - 1);
if (this.tests[i].test(c)) {
this.buffer[i] = c;
lastMatch = i;
break;
}
}
if (pos > test.length) {
this.clearBuffer(i + 1, this.len);
break;
}
} else {
if (this.buffer[i] === test.charAt(pos)) {
pos++;
}
if (i < this.partialPosition) {
lastMatch = i;
}
}
}
if (allow) {
this.writeBuffer();
} else if (lastMatch + 1 < this.partialPosition) {
if (this.props.autoClear || this.buffer.join('') === this.defaultBuffer) {
// Invalid value. Remove it and replace it with the
// mask, which is the default behavior.
if (this.input.value) this.input.value = '';
this.clearBuffer(0, this.len);
} else {
// Invalid value, but we opt to show the value to the
// user and allow them to correct their mistake.
this.writeBuffer();
}
} else {
this.writeBuffer();
this.input.value = this.input.value.substring(0, lastMatch + 1);
}
return this.partialPosition ? i : this.firstNonMaskPos;
}
}, {
key: "onFocus",
value: function onFocus(e) {
var _this3 = this;
if (this.props.readOnly) {
return;
}
this.focus = true;
clearTimeout(this.caretTimeoutId);
var pos;
this.focusText = this.input.value;
pos = this.checkVal();
this.caretTimeoutId = setTimeout(function () {
if (_this3.input !== document.activeElement) {
return;
}
_this3.writeBuffer();
if (pos === _this3.props.mask.replace("?", "").length) {
_this3.caret(0, pos);
} else {
_this3.caret(pos);
}
_this3.updateFilledState();
}, 10);
if (this.props.onFocus) {
this.props.onFocus(e);
}
}
}, {
key: "onInput",
value: function onInput(event) {
if (this.androidChrome) this.handleAndroidInput(event);else this.handleInputChange(event);
}
}, {
key: "handleInputChange",
value: function handleInputChange(e) {
if (this.props.readOnly) {
return;
}
var pos = this.checkVal(true);
this.caret(pos);
this.updateModel(e);
if (this.props.onComplete && this.isCompleted()) {
this.props.onComplete({
originalEvent: e,
value: this.getValue()
});
}
}
}, {
key: "getUnmaskedValue",
value: function getUnmaskedValue() {
var unmaskedBuffer = [];
for (var i = 0; i < this.buffer.length; i++) {
var c = this.buffer[i];
if (this.tests[i] && c !== this.getPlaceholder(i)) {
unmaskedBuffer.push(c);
}
}
return unmaskedBuffer.join('');
}
}, {
key: "updateModel",
value: function updateModel(e) {
if (this.props.onChange) {
var val = this.props.unmask ? this.getUnmaskedValue() : e && e.target.value;
this.props.onChange({
originalEvent: e,
value: this.defaultBuffer !== val ? val : '',
stopPropagation: function stopPropagation() {},
preventDefault: function preventDefault() {},
target: {
name: this.props.name,
id: this.props.id,
value: this.defaultBuffer !== val ? val : ''
}
});
}
}
}, {
key: "updateFilledState",
value: function updateFilledState() {
if (this.input && this.input.value && this.input.value.length > 0) _DomHandler.default.addClass(this.input, 'p-filled');else _DomHandler.default.removeClass(this.input, 'p-filled');
}
}, {
key: "updateValue",
value: function updateValue(allow) {
var _this4 = this;
var pos;
if (this.input) {
if (this.props.value == null) {
this.input.value = '';
} else {
this.input.value = this.props.value;
pos = this.checkVal(allow);
setTimeout(function () {
if (_this4.input) {
_this4.writeBuffer();
return _this4.checkVal(allow);
}
}, 10);
}
this.focusText = this.input.value;
}
this.updateFilledState();
return pos;
}
}, {
key: "isValueUpdated",
value: function isValueUpdated() {
return this.props.unmask ? this.props.value !== this.getUnmaskedValue() : this.defaultBuffer !== this.input.value && this.input.value !== this.props.value;
}
}, {
key: "init",
value: function init() {
this.tests = [];
this.partialPosition = this.props.mask.length;
this.len = this.props.mask.length;
this.firstNonMaskPos = null;
this.defs = {
'9': '[0-9]',
'a': '[A-Za-z]',
'*': '[A-Za-z0-9]'
};
var ua = _DomHandler.default.getUserAgent();
this.androidChrome = /chrome/i.test(ua) && /android/i.test(ua);
var maskTokens = this.props.mask.split('');
for (var i = 0; i < maskTokens.length; i++) {
var c = maskTokens[i];
if (c === '?') {
this.len--;
this.partialPosition = i;
} else if (this.defs[c]) {
this.tests.push(new RegExp(this.defs[c]));
if (this.firstNonMaskPos === null) {
this.firstNonMaskPos = this.tests.length - 1;
}
if (i < this.partialPosition) {
this.lastRequiredNonMaskPos = this.tests.length - 1;
}
} else {
this.tests.push(null);
}
}
this.buffer = [];
for (var _i = 0; _i < maskTokens.length; _i++) {
var _c = maskTokens[_i];
if (_c !== '?') {
if (this.defs[_c]) this.buffer.push(this.getPlaceholder(_i));else this.buffer.push(_c);
}
}
this.defaultBuffer = this.buffer.join('');
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
this.init();
this.updateValue();
if (this.props.tooltip) {
this.renderTooltip();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.tooltip !== this.props.tooltip) {
if (this.tooltip) this.tooltip.updateContent(this.props.tooltip);else this.renderTooltip();
}
if (this.isValueUpdated()) {
this.updateValue();
}
if (prevProps.mask !== this.props.mask) {
this.init();
this.caret(this.updateValue(true));
this.updateModel();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.tooltip) {
this.tooltip.destroy();
this.tooltip = null;
}
}
}, {
key: "renderTooltip",
value: function renderTooltip() {
this.tooltip = (0, _Tooltip.tip)({
target: this.input,
content: this.props.tooltip,
options: this.props.tooltipOptions
});
}
}, {
key: "render",
value: function render() {
var _this5 = this;
var inputMaskClassName = (0, _ClassNames.classNames)('p-inputmask', this.props.className);
return /*#__PURE__*/_react.default.createElement(_InputText.InputText, {
id: this.props.id,
ref: function ref(el) {
return _this5.input = el;
},
type: this.props.type,
name: this.props.name,
style: this.props.style,
className: inputMaskClassName,
placeholder: this.props.placeholder,
size: this.props.size,
maxLength: this.props.maxlength,
tabIndex: this.props.tabIndex,
disabled: this.props.disabled,
readOnly: this.props.readOnly,
onFocus: this.onFocus,
onBlur: this.onBlur,
onKeyDown: this.onKeyDown,
onKeyPress: this.onKeyPress,
onInput: this.onInput,
onPaste: this.handleInputChange,
required: this.props.required,
"aria-labelledby": this.props.ariaLabelledBy
});
}
}]);
return InputMask;
}(_react.Component);
exports.InputMask = InputMask;
_defineProperty(InputMask, "defaultProps", {
id: null,
value: null,
type: 'text',
mask: null,
slotChar: '_',
autoClear: true,
unmask: false,
style: null,
className: null,
placeholder: null,
size: null,
maxlength: null,
tabIndex: null,
disabled: false,
readOnly: false,
name: null,
required: false,
tooltip: null,
tooltipOptions: null,
ariaLabelledBy: null,
onComplete: null,
onChange: null,
onFocus: null,
onBlur: null
});
_defineProperty(InputMask, "propTypes", {
id: _propTypes.default.string,
value: _propTypes.default.string,
type: _propTypes.default.string,
mask: _propTypes.default.string,
slotChar: _propTypes.default.string,
autoClear: _propTypes.default.bool,
unmask: _propTypes.default.bool,
style: _propTypes.default.object,
className: _propTypes.default.string,
placeholder: _propTypes.default.string,
size: _propTypes.default.number,
maxlength: _propTypes.default.number,
tabIndex: _propTypes.default.number,
disabled: _propTypes.default.bool,
readOnly: _propTypes.default.bool,
name: _propTypes.default.string,
required: _propTypes.default.bool,
tooltip: _propTypes.default.string,
tooltipOptions: _propTypes.default.object,
ariaLabelledBy: _propTypes.default.string,
onComplete: _propTypes.default.func,
onChange: _propTypes.default.func,
onFocus: _propTypes.default.func,
onBlur: _propTypes.default.func
});
|
/*!
* vue-i18n v9.2.0-beta.12
* (c) 2021 kazuya kawaguchi
* Released under the MIT License.
*/
import { ref, getCurrentInstance, computed, watch, createVNode, Text, defineComponent, Fragment, h, nextTick, inject, onMounted, onUnmounted, isRef } from 'vue';
/**
* Original Utilities
* written by kazuya kawaguchi
*/
const inBrowser = typeof window !== 'undefined';
let mark;
let measure;
{
const perf = inBrowser && window.performance;
if (perf &&
perf.mark &&
perf.measure &&
perf.clearMarks &&
perf.clearMeasures) {
mark = (tag) => perf.mark(tag);
measure = (name, startTag, endTag) => {
perf.measure(name, startTag, endTag);
perf.clearMarks(startTag);
perf.clearMarks(endTag);
};
}
}
const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
/* eslint-disable */
function format(message, ...args) {
if (args.length === 1 && isObject(args[0])) {
args = args[0];
}
if (!args || !args.hasOwnProperty) {
args = {};
}
return message.replace(RE_ARGS, (match, identifier) => {
return args.hasOwnProperty(identifier) ? args[identifier] : '';
});
}
const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
const makeSymbol = (name) => hasSymbol ? Symbol(name) : name;
const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
const friendlyJSONstringify = (json) => JSON.stringify(json)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
.replace(/\u0027/g, '\\u0027');
const isNumber = (val) => typeof val === 'number' && isFinite(val);
const isDate = (val) => toTypeString(val) === '[object Date]';
const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
function warn(msg, err) {
if (typeof console !== 'undefined') {
console.warn(`[intlify] ` + msg);
/* istanbul ignore if */
if (err) {
console.warn(err.stack);
}
}
}
const assign = Object.assign;
let _globalThis;
const getGlobalThis = () => {
// prettier-ignore
return (_globalThis ||
(_globalThis =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {}));
};
function escapeHtml(rawText) {
return rawText
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
/* eslint-enable */
/**
* Useful Utilities By Evan you
* Modified by kazuya kawaguchi
* MIT License
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
*/
const isArray = Array.isArray;
const isFunction = (val) => typeof val === 'function';
const isString = (val) => typeof val === 'string';
const isBoolean = (val) => typeof val === 'boolean';
const isObject = (val) => // eslint-disable-line
val !== null && typeof val === 'object';
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const isPlainObject = (val) => toTypeString(val) === '[object Object]';
// for converting list and named values to displayed strings.
const toDisplayString = (val) => {
return val == null
? ''
: isArray(val) || (isPlainObject(val) && val.toString === objectToString)
? JSON.stringify(val, null, 2)
: String(val);
};
const RANGE = 2;
function generateCodeFrame(source, start = 0, end = source.length) {
const lines = source.split(/\r?\n/);
let count = 0;
const res = [];
for (let i = 0; i < lines.length; i++) {
count += lines[i].length + 1;
if (count >= start) {
for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
if (j < 0 || j >= lines.length)
continue;
const line = j + 1;
res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
const lineLength = lines[j].length;
if (j === i) {
// push underline
const pad = start - (count - lineLength) + 1;
const length = Math.max(1, end > count ? lineLength - pad : end - start);
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
}
else if (j > i) {
if (end > count) {
const length = Math.max(Math.min(end - count, lineLength), 1);
res.push(` | ` + '^'.repeat(length));
}
count += lineLength + 1;
}
}
break;
}
}
return res.join('\n');
}
/**
* Event emitter, forked from the below:
* - original repository url: https://github.com/developit/mitt
* - code url: https://github.com/developit/mitt/blob/master/src/index.ts
* - author: Jason Miller (https://github.com/developit)
* - license: MIT
*/
/**
* Create a event emitter
*
* @returns An event emitter
*/
function createEmitter() {
const events = new Map();
const emitter = {
events,
on(event, handler) {
const handlers = events.get(event);
const added = handlers && handlers.push(handler);
if (!added) {
events.set(event, [handler]);
}
},
off(event, handler) {
const handlers = events.get(event);
if (handlers) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
}
},
emit(event, payload) {
(events.get(event) || [])
.slice()
.map(handler => handler(payload));
(events.get('*') || [])
.slice()
.map(handler => handler(event, payload));
}
};
return emitter;
}
const CompileErrorCodes = {
// tokenizer error codes
EXPECTED_TOKEN: 1,
INVALID_TOKEN_IN_PLACEHOLDER: 2,
UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
UNKNOWN_ESCAPE_SEQUENCE: 4,
INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
UNBALANCED_CLOSING_BRACE: 6,
UNTERMINATED_CLOSING_BRACE: 7,
EMPTY_PLACEHOLDER: 8,
NOT_ALLOW_NEST_PLACEHOLDER: 9,
INVALID_LINKED_FORMAT: 10,
// parser error codes
MUST_HAVE_MESSAGES_IN_PLURAL: 11,
UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
UNEXPECTED_EMPTY_LINKED_KEY: 13,
UNEXPECTED_LEXICAL_ANALYSIS: 14,
// Special value for higher-order compilers to pick up the last code
// to avoid collision of error codes. This should always be kept as the last
// item.
__EXTEND_POINT__: 15
};
/** @internal */
const errorMessages$2 = {
// tokenizer error messages
[CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
[CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
[CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
[CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
[CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
[CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
[CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
[CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
[CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
[CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
// parser error messages
[CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
[CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
[CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
[CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`
};
function createCompileError(code, loc, options = {}) {
const { domain, messages, args } = options;
const msg = format((messages || errorMessages$2)[code] || '', ...(args || []))
;
const error = new SyntaxError(String(msg));
error.code = code;
if (loc) {
error.location = loc;
}
error.domain = domain;
return error;
}
/** @internal */
function defaultOnError(error) {
throw error;
}
function createPosition(line, column, offset) {
return { line, column, offset };
}
function createLocation(start, end, source) {
const loc = { start, end };
if (source != null) {
loc.source = source;
}
return loc;
}
const CHAR_SP = ' ';
const CHAR_CR = '\r';
const CHAR_LF = '\n';
const CHAR_LS = String.fromCharCode(0x2028);
const CHAR_PS = String.fromCharCode(0x2029);
function createScanner(str) {
const _buf = str;
let _index = 0;
let _line = 1;
let _column = 1;
let _peekOffset = 0;
const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
const isLF = (index) => _buf[index] === CHAR_LF;
const isPS = (index) => _buf[index] === CHAR_PS;
const isLS = (index) => _buf[index] === CHAR_LS;
const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
const index = () => _index;
const line = () => _line;
const column = () => _column;
const peekOffset = () => _peekOffset;
const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
const currentChar = () => charAt(_index);
const currentPeek = () => charAt(_index + _peekOffset);
function next() {
_peekOffset = 0;
if (isLineEnd(_index)) {
_line++;
_column = 0;
}
if (isCRLF(_index)) {
_index++;
}
_index++;
_column++;
return _buf[_index];
}
function peek() {
if (isCRLF(_index + _peekOffset)) {
_peekOffset++;
}
_peekOffset++;
return _buf[_index + _peekOffset];
}
function reset() {
_index = 0;
_line = 1;
_column = 1;
_peekOffset = 0;
}
function resetPeek(offset = 0) {
_peekOffset = offset;
}
function skipToPeek() {
const target = _index + _peekOffset;
// eslint-disable-next-line no-unmodified-loop-condition
while (target !== _index) {
next();
}
_peekOffset = 0;
}
return {
index,
line,
column,
peekOffset,
charAt,
currentChar,
currentPeek,
next,
peek,
reset,
resetPeek,
skipToPeek
};
}
const EOF = undefined;
const LITERAL_DELIMITER = "'";
const ERROR_DOMAIN$1 = 'tokenizer';
function createTokenizer(source, options = {}) {
const location = options.location !== false;
const _scnr = createScanner(source);
const currentOffset = () => _scnr.index();
const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
const _initLoc = currentPosition();
const _initOffset = currentOffset();
const _context = {
currentType: 14 /* EOF */,
offset: _initOffset,
startLoc: _initLoc,
endLoc: _initLoc,
lastType: 14 /* EOF */,
lastOffset: _initOffset,
lastStartLoc: _initLoc,
lastEndLoc: _initLoc,
braceNest: 0,
inLinked: false,
text: ''
};
const context = () => _context;
const { onError } = options;
function emitError(code, pos, offset, ...args) {
const ctx = context();
pos.column += offset;
pos.offset += offset;
if (onError) {
const loc = createLocation(ctx.startLoc, pos);
const err = createCompileError(code, loc, {
domain: ERROR_DOMAIN$1,
args
});
onError(err);
}
}
function getToken(context, type, value) {
context.endLoc = currentPosition();
context.currentType = type;
const token = { type };
if (location) {
token.loc = createLocation(context.startLoc, context.endLoc);
}
if (value != null) {
token.value = value;
}
return token;
}
const getEndToken = (context) => getToken(context, 14 /* EOF */);
function eat(scnr, ch) {
if (scnr.currentChar() === ch) {
scnr.next();
return ch;
}
else {
emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
return '';
}
}
function peekSpaces(scnr) {
let buf = '';
while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
buf += scnr.currentPeek();
scnr.peek();
}
return buf;
}
function skipSpaces(scnr) {
const buf = peekSpaces(scnr);
scnr.skipToPeek();
return buf;
}
function isIdentifierStart(ch) {
if (ch === EOF) {
return false;
}
const cc = ch.charCodeAt(0);
return ((cc >= 97 && cc <= 122) || // a-z
(cc >= 65 && cc <= 90) || // A-Z
cc === 95 // _
);
}
function isNumberStart(ch) {
if (ch === EOF) {
return false;
}
const cc = ch.charCodeAt(0);
return cc >= 48 && cc <= 57; // 0-9
}
function isNamedIdentifierStart(scnr, context) {
const { currentType } = context;
if (currentType !== 2 /* BraceLeft */) {
return false;
}
peekSpaces(scnr);
const ret = isIdentifierStart(scnr.currentPeek());
scnr.resetPeek();
return ret;
}
function isListIdentifierStart(scnr, context) {
const { currentType } = context;
if (currentType !== 2 /* BraceLeft */) {
return false;
}
peekSpaces(scnr);
const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
const ret = isNumberStart(ch);
scnr.resetPeek();
return ret;
}
function isLiteralStart(scnr, context) {
const { currentType } = context;
if (currentType !== 2 /* BraceLeft */) {
return false;
}
peekSpaces(scnr);
const ret = scnr.currentPeek() === LITERAL_DELIMITER;
scnr.resetPeek();
return ret;
}
function isLinkedDotStart(scnr, context) {
const { currentType } = context;
if (currentType !== 8 /* LinkedAlias */) {
return false;
}
peekSpaces(scnr);
const ret = scnr.currentPeek() === "." /* LinkedDot */;
scnr.resetPeek();
return ret;
}
function isLinkedModifierStart(scnr, context) {
const { currentType } = context;
if (currentType !== 9 /* LinkedDot */) {
return false;
}
peekSpaces(scnr);
const ret = isIdentifierStart(scnr.currentPeek());
scnr.resetPeek();
return ret;
}
function isLinkedDelimiterStart(scnr, context) {
const { currentType } = context;
if (!(currentType === 8 /* LinkedAlias */ ||
currentType === 12 /* LinkedModifier */)) {
return false;
}
peekSpaces(scnr);
const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */;
scnr.resetPeek();
return ret;
}
function isLinkedReferStart(scnr, context) {
const { currentType } = context;
if (currentType !== 10 /* LinkedDelimiter */) {
return false;
}
const fn = () => {
const ch = scnr.currentPeek();
if (ch === "{" /* BraceLeft */) {
return isIdentifierStart(scnr.peek());
}
else if (ch === "@" /* LinkedAlias */ ||
ch === "%" /* Modulo */ ||
ch === "|" /* Pipe */ ||
ch === ":" /* LinkedDelimiter */ ||
ch === "." /* LinkedDot */ ||
ch === CHAR_SP ||
!ch) {
return false;
}
else if (ch === CHAR_LF) {
scnr.peek();
return fn();
}
else {
// other characters
return isIdentifierStart(ch);
}
};
const ret = fn();
scnr.resetPeek();
return ret;
}
function isPluralStart(scnr) {
peekSpaces(scnr);
const ret = scnr.currentPeek() === "|" /* Pipe */;
scnr.resetPeek();
return ret;
}
function isTextStart(scnr, reset = true) {
const fn = (hasSpace = false, prev = '', detectModulo = false) => {
const ch = scnr.currentPeek();
if (ch === "{" /* BraceLeft */) {
return prev === "%" /* Modulo */ ? false : hasSpace;
}
else if (ch === "@" /* LinkedAlias */ || !ch) {
return prev === "%" /* Modulo */ ? true : hasSpace;
}
else if (ch === "%" /* Modulo */) {
scnr.peek();
return fn(hasSpace, "%" /* Modulo */, true);
}
else if (ch === "|" /* Pipe */) {
return prev === "%" /* Modulo */ || detectModulo
? true
: !(prev === CHAR_SP || prev === CHAR_LF);
}
else if (ch === CHAR_SP) {
scnr.peek();
return fn(true, CHAR_SP, detectModulo);
}
else if (ch === CHAR_LF) {
scnr.peek();
return fn(true, CHAR_LF, detectModulo);
}
else {
return true;
}
};
const ret = fn();
reset && scnr.resetPeek();
return ret;
}
function takeChar(scnr, fn) {
const ch = scnr.currentChar();
if (ch === EOF) {
return EOF;
}
if (fn(ch)) {
scnr.next();
return ch;
}
return null;
}
function takeIdentifierChar(scnr) {
const closure = (ch) => {
const cc = ch.charCodeAt(0);
return ((cc >= 97 && cc <= 122) || // a-z
(cc >= 65 && cc <= 90) || // A-Z
(cc >= 48 && cc <= 57) || // 0-9
cc === 95 || // _
cc === 36 // $
);
};
return takeChar(scnr, closure);
}
function takeDigit(scnr) {
const closure = (ch) => {
const cc = ch.charCodeAt(0);
return cc >= 48 && cc <= 57; // 0-9
};
return takeChar(scnr, closure);
}
function takeHexDigit(scnr) {
const closure = (ch) => {
const cc = ch.charCodeAt(0);
return ((cc >= 48 && cc <= 57) || // 0-9
(cc >= 65 && cc <= 70) || // A-F
(cc >= 97 && cc <= 102)); // a-f
};
return takeChar(scnr, closure);
}
function getDigits(scnr) {
let ch = '';
let num = '';
while ((ch = takeDigit(scnr))) {
num += ch;
}
return num;
}
function readText(scnr) {
let buf = '';
while (true) {
const ch = scnr.currentChar();
if (ch === "{" /* BraceLeft */ ||
ch === "}" /* BraceRight */ ||
ch === "@" /* LinkedAlias */ ||
ch === "|" /* Pipe */ ||
!ch) {
break;
}
else if (ch === "%" /* Modulo */) {
if (isTextStart(scnr)) {
buf += ch;
scnr.next();
}
else {
break;
}
}
else if (ch === CHAR_SP || ch === CHAR_LF) {
if (isTextStart(scnr)) {
buf += ch;
scnr.next();
}
else if (isPluralStart(scnr)) {
break;
}
else {
buf += ch;
scnr.next();
}
}
else {
buf += ch;
scnr.next();
}
}
return buf;
}
function readNamedIdentifier(scnr) {
skipSpaces(scnr);
let ch = '';
let name = '';
while ((ch = takeIdentifierChar(scnr))) {
name += ch;
}
if (scnr.currentChar() === EOF) {
emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
}
return name;
}
function readListIdentifier(scnr) {
skipSpaces(scnr);
let value = '';
if (scnr.currentChar() === '-') {
scnr.next();
value += `-${getDigits(scnr)}`;
}
else {
value += getDigits(scnr);
}
if (scnr.currentChar() === EOF) {
emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
}
return value;
}
function readLiteral(scnr) {
skipSpaces(scnr);
eat(scnr, `\'`);
let ch = '';
let literal = '';
const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
while ((ch = takeChar(scnr, fn))) {
if (ch === '\\') {
literal += readEscapeSequence(scnr);
}
else {
literal += ch;
}
}
const current = scnr.currentChar();
if (current === CHAR_LF || current === EOF) {
emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
// TODO: Is it correct really?
if (current === CHAR_LF) {
scnr.next();
eat(scnr, `\'`);
}
return literal;
}
eat(scnr, `\'`);
return literal;
}
function readEscapeSequence(scnr) {
const ch = scnr.currentChar();
switch (ch) {
case '\\':
case `\'`:
scnr.next();
return `\\${ch}`;
case 'u':
return readUnicodeEscapeSequence(scnr, ch, 4);
case 'U':
return readUnicodeEscapeSequence(scnr, ch, 6);
default:
emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
return '';
}
}
function readUnicodeEscapeSequence(scnr, unicode, digits) {
eat(scnr, unicode);
let sequence = '';
for (let i = 0; i < digits; i++) {
const ch = takeHexDigit(scnr);
if (!ch) {
emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
break;
}
sequence += ch;
}
return `\\${unicode}${sequence}`;
}
function readInvalidIdentifier(scnr) {
skipSpaces(scnr);
let ch = '';
let identifiers = '';
const closure = (ch) => ch !== "{" /* BraceLeft */ &&
ch !== "}" /* BraceRight */ &&
ch !== CHAR_SP &&
ch !== CHAR_LF;
while ((ch = takeChar(scnr, closure))) {
identifiers += ch;
}
return identifiers;
}
function readLinkedModifier(scnr) {
let ch = '';
let name = '';
while ((ch = takeIdentifierChar(scnr))) {
name += ch;
}
return name;
}
function readLinkedRefer(scnr) {
const fn = (detect = false, buf) => {
const ch = scnr.currentChar();
if (ch === "{" /* BraceLeft */ ||
ch === "%" /* Modulo */ ||
ch === "@" /* LinkedAlias */ ||
ch === "|" /* Pipe */ ||
!ch) {
return buf;
}
else if (ch === CHAR_SP) {
return buf;
}
else if (ch === CHAR_LF) {
buf += ch;
scnr.next();
return fn(detect, buf);
}
else {
buf += ch;
scnr.next();
return fn(true, buf);
}
};
return fn(false, '');
}
function readPlural(scnr) {
skipSpaces(scnr);
const plural = eat(scnr, "|" /* Pipe */);
skipSpaces(scnr);
return plural;
}
// TODO: We need refactoring of token parsing ...
function readTokenInPlaceholder(scnr, context) {
let token = null;
const ch = scnr.currentChar();
switch (ch) {
case "{" /* BraceLeft */:
if (context.braceNest >= 1) {
emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
}
scnr.next();
token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */);
skipSpaces(scnr);
context.braceNest++;
return token;
case "}" /* BraceRight */:
if (context.braceNest > 0 &&
context.currentType === 2 /* BraceLeft */) {
emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
}
scnr.next();
token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
context.braceNest--;
context.braceNest > 0 && skipSpaces(scnr);
if (context.inLinked && context.braceNest === 0) {
context.inLinked = false;
}
return token;
case "@" /* LinkedAlias */:
if (context.braceNest > 0) {
emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
}
token = readTokenInLinked(scnr, context) || getEndToken(context);
context.braceNest = 0;
return token;
default:
let validNamedIdentifier = true;
let validListIdentifier = true;
let validLiteral = true;
if (isPluralStart(scnr)) {
if (context.braceNest > 0) {
emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
}
token = getToken(context, 1 /* Pipe */, readPlural(scnr));
// reset
context.braceNest = 0;
context.inLinked = false;
return token;
}
if (context.braceNest > 0 &&
(context.currentType === 5 /* Named */ ||
context.currentType === 6 /* List */ ||
context.currentType === 7 /* Literal */)) {
emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
context.braceNest = 0;
return readToken(scnr, context);
}
if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr));
skipSpaces(scnr);
return token;
}
if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
token = getToken(context, 6 /* List */, readListIdentifier(scnr));
skipSpaces(scnr);
return token;
}
if ((validLiteral = isLiteralStart(scnr, context))) {
token = getToken(context, 7 /* Literal */, readLiteral(scnr));
skipSpaces(scnr);
return token;
}
if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
// TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr));
emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
skipSpaces(scnr);
return token;
}
break;
}
return token;
}
// TODO: We need refactoring of token parsing ...
function readTokenInLinked(scnr, context) {
const { currentType } = context;
let token = null;
const ch = scnr.currentChar();
if ((currentType === 8 /* LinkedAlias */ ||
currentType === 9 /* LinkedDot */ ||
currentType === 12 /* LinkedModifier */ ||
currentType === 10 /* LinkedDelimiter */) &&
(ch === CHAR_LF || ch === CHAR_SP)) {
emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
}
switch (ch) {
case "@" /* LinkedAlias */:
scnr.next();
token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */);
context.inLinked = true;
return token;
case "." /* LinkedDot */:
skipSpaces(scnr);
scnr.next();
return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */);
case ":" /* LinkedDelimiter */:
skipSpaces(scnr);
scnr.next();
return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */);
default:
if (isPluralStart(scnr)) {
token = getToken(context, 1 /* Pipe */, readPlural(scnr));
// reset
context.braceNest = 0;
context.inLinked = false;
return token;
}
if (isLinkedDotStart(scnr, context) ||
isLinkedDelimiterStart(scnr, context)) {
skipSpaces(scnr);
return readTokenInLinked(scnr, context);
}
if (isLinkedModifierStart(scnr, context)) {
skipSpaces(scnr);
return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr));
}
if (isLinkedReferStart(scnr, context)) {
skipSpaces(scnr);
if (ch === "{" /* BraceLeft */) {
// scan the placeholder
return readTokenInPlaceholder(scnr, context) || token;
}
else {
return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr));
}
}
if (currentType === 8 /* LinkedAlias */) {
emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
}
context.braceNest = 0;
context.inLinked = false;
return readToken(scnr, context);
}
}
// TODO: We need refactoring of token parsing ...
function readToken(scnr, context) {
let token = { type: 14 /* EOF */ };
if (context.braceNest > 0) {
return readTokenInPlaceholder(scnr, context) || getEndToken(context);
}
if (context.inLinked) {
return readTokenInLinked(scnr, context) || getEndToken(context);
}
const ch = scnr.currentChar();
switch (ch) {
case "{" /* BraceLeft */:
return readTokenInPlaceholder(scnr, context) || getEndToken(context);
case "}" /* BraceRight */:
emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
scnr.next();
return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
case "@" /* LinkedAlias */:
return readTokenInLinked(scnr, context) || getEndToken(context);
default:
if (isPluralStart(scnr)) {
token = getToken(context, 1 /* Pipe */, readPlural(scnr));
// reset
context.braceNest = 0;
context.inLinked = false;
return token;
}
if (isTextStart(scnr)) {
return getToken(context, 0 /* Text */, readText(scnr));
}
if (ch === "%" /* Modulo */) {
scnr.next();
return getToken(context, 4 /* Modulo */, "%" /* Modulo */);
}
break;
}
return token;
}
function nextToken() {
const { currentType, offset, startLoc, endLoc } = _context;
_context.lastType = currentType;
_context.lastOffset = offset;
_context.lastStartLoc = startLoc;
_context.lastEndLoc = endLoc;
_context.offset = currentOffset();
_context.startLoc = currentPosition();
if (_scnr.currentChar() === EOF) {
return getToken(_context, 14 /* EOF */);
}
return readToken(_scnr, _context);
}
return {
nextToken,
currentOffset,
currentPosition,
context
};
}
const ERROR_DOMAIN = 'parser';
// Backslash backslash, backslash quote, uHHHH, UHHHHHH.
const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
function fromEscapeSequence(match, codePoint4, codePoint6) {
switch (match) {
case `\\\\`:
return `\\`;
case `\\\'`:
return `\'`;
default: {
const codePoint = parseInt(codePoint4 || codePoint6, 16);
if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
return String.fromCodePoint(codePoint);
}
// invalid ...
// Replace them with U+FFFD REPLACEMENT CHARACTER.
return '�';
}
}
}
function createParser(options = {}) {
const location = options.location !== false;
const { onError } = options;
function emitError(tokenzer, code, start, offset, ...args) {
const end = tokenzer.currentPosition();
end.offset += offset;
end.column += offset;
if (onError) {
const loc = createLocation(start, end);
const err = createCompileError(code, loc, {
domain: ERROR_DOMAIN,
args
});
onError(err);
}
}
function startNode(type, offset, loc) {
const node = {
type,
start: offset,
end: offset
};
if (location) {
node.loc = { start: loc, end: loc };
}
return node;
}
function endNode(node, offset, pos, type) {
node.end = offset;
if (type) {
node.type = type;
}
if (location && node.loc) {
node.loc.end = pos;
}
}
function parseText(tokenizer, value) {
const context = tokenizer.context();
const node = startNode(3 /* Text */, context.offset, context.startLoc);
node.value = value;
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseList(tokenizer, index) {
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
const node = startNode(5 /* List */, offset, loc);
node.index = parseInt(index, 10);
tokenizer.nextToken(); // skip brach right
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseNamed(tokenizer, key) {
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
const node = startNode(4 /* Named */, offset, loc);
node.key = key;
tokenizer.nextToken(); // skip brach right
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLiteral(tokenizer, value) {
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
const node = startNode(9 /* Literal */, offset, loc);
node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
tokenizer.nextToken(); // skip brach right
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLinkedModifier(tokenizer) {
const token = tokenizer.nextToken();
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
const node = startNode(8 /* LinkedModifier */, offset, loc);
if (token.type !== 12 /* LinkedModifier */) {
// empty modifier
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
node.value = '';
endNode(node, offset, loc);
return {
nextConsumeToken: token,
node
};
}
// check token
if (token.value == null) {
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
}
node.value = token.value || '';
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return {
node
};
}
function parseLinkedKey(tokenizer, value) {
const context = tokenizer.context();
const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc);
node.value = value;
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLinked(tokenizer) {
const context = tokenizer.context();
const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc);
let token = tokenizer.nextToken();
if (token.type === 9 /* LinkedDot */) {
const parsed = parseLinkedModifier(tokenizer);
linkedNode.modifier = parsed.node;
token = parsed.nextConsumeToken || tokenizer.nextToken();
}
// asset check token
if (token.type !== 10 /* LinkedDelimiter */) {
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
}
token = tokenizer.nextToken();
// skip brace left
if (token.type === 2 /* BraceLeft */) {
token = tokenizer.nextToken();
}
switch (token.type) {
case 11 /* LinkedKey */:
if (token.value == null) {
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
}
linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
break;
case 5 /* Named */:
if (token.value == null) {
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
}
linkedNode.key = parseNamed(tokenizer, token.value || '');
break;
case 6 /* List */:
if (token.value == null) {
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
}
linkedNode.key = parseList(tokenizer, token.value || '');
break;
case 7 /* Literal */:
if (token.value == null) {
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
}
linkedNode.key = parseLiteral(tokenizer, token.value || '');
break;
default:
// empty key
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
const nextContext = tokenizer.context();
const emptyLinkedKeyNode = startNode(7 /* LinkedKey */, nextContext.offset, nextContext.startLoc);
emptyLinkedKeyNode.value = '';
endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
linkedNode.key = emptyLinkedKeyNode;
endNode(linkedNode, nextContext.offset, nextContext.startLoc);
return {
nextConsumeToken: token,
node: linkedNode
};
}
endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
return {
node: linkedNode
};
}
function parseMessage(tokenizer) {
const context = tokenizer.context();
const startOffset = context.currentType === 1 /* Pipe */
? tokenizer.currentOffset()
: context.offset;
const startLoc = context.currentType === 1 /* Pipe */
? context.endLoc
: context.startLoc;
const node = startNode(2 /* Message */, startOffset, startLoc);
node.items = [];
let nextToken = null;
do {
const token = nextToken || tokenizer.nextToken();
nextToken = null;
switch (token.type) {
case 0 /* Text */:
if (token.value == null) {
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
}
node.items.push(parseText(tokenizer, token.value || ''));
break;
case 6 /* List */:
if (token.value == null) {
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
}
node.items.push(parseList(tokenizer, token.value || ''));
break;
case 5 /* Named */:
if (token.value == null) {
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
}
node.items.push(parseNamed(tokenizer, token.value || ''));
break;
case 7 /* Literal */:
if (token.value == null) {
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
}
node.items.push(parseLiteral(tokenizer, token.value || ''));
break;
case 8 /* LinkedAlias */:
const parsed = parseLinked(tokenizer);
node.items.push(parsed.node);
nextToken = parsed.nextConsumeToken || null;
break;
}
} while (context.currentType !== 14 /* EOF */ &&
context.currentType !== 1 /* Pipe */);
// adjust message node loc
const endOffset = context.currentType === 1 /* Pipe */
? context.lastOffset
: tokenizer.currentOffset();
const endLoc = context.currentType === 1 /* Pipe */
? context.lastEndLoc
: tokenizer.currentPosition();
endNode(node, endOffset, endLoc);
return node;
}
function parsePlural(tokenizer, offset, loc, msgNode) {
const context = tokenizer.context();
let hasEmptyMessage = msgNode.items.length === 0;
const node = startNode(1 /* Plural */, offset, loc);
node.cases = [];
node.cases.push(msgNode);
do {
const msg = parseMessage(tokenizer);
if (!hasEmptyMessage) {
hasEmptyMessage = msg.items.length === 0;
}
node.cases.push(msg);
} while (context.currentType !== 14 /* EOF */);
if (hasEmptyMessage) {
emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
}
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseResource(tokenizer) {
const context = tokenizer.context();
const { offset, startLoc } = context;
const msgNode = parseMessage(tokenizer);
if (context.currentType === 14 /* EOF */) {
return msgNode;
}
else {
return parsePlural(tokenizer, offset, startLoc, msgNode);
}
}
function parse(source) {
const tokenizer = createTokenizer(source, assign({}, options));
const context = tokenizer.context();
const node = startNode(0 /* Resource */, context.offset, context.startLoc);
if (location && node.loc) {
node.loc.source = source;
}
node.body = parseResource(tokenizer);
// assert whether achieved to EOF
if (context.currentType !== 14 /* EOF */) {
emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
}
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
return { parse };
}
function getTokenCaption(token) {
if (token.type === 14 /* EOF */) {
return 'EOF';
}
const name = (token.value || '').replace(/\r?\n/gu, '\\n');
return name.length > 10 ? name.slice(0, 9) + '…' : name;
}
function createTransformer(ast, options = {} // eslint-disable-line
) {
const _context = {
ast,
helpers: new Set()
};
const context = () => _context;
const helper = (name) => {
_context.helpers.add(name);
return name;
};
return { context, helper };
}
function traverseNodes(nodes, transformer) {
for (let i = 0; i < nodes.length; i++) {
traverseNode(nodes[i], transformer);
}
}
function traverseNode(node, transformer) {
// TODO: if we need pre-hook of transform, should be implemented to here
switch (node.type) {
case 1 /* Plural */:
traverseNodes(node.cases, transformer);
transformer.helper("plural" /* PLURAL */);
break;
case 2 /* Message */:
traverseNodes(node.items, transformer);
break;
case 6 /* Linked */:
const linked = node;
traverseNode(linked.key, transformer);
transformer.helper("linked" /* LINKED */);
break;
case 5 /* List */:
transformer.helper("interpolate" /* INTERPOLATE */);
transformer.helper("list" /* LIST */);
break;
case 4 /* Named */:
transformer.helper("interpolate" /* INTERPOLATE */);
transformer.helper("named" /* NAMED */);
break;
}
// TODO: if we need post-hook of transform, should be implemented to here
}
// transform AST
function transform(ast, options = {} // eslint-disable-line
) {
const transformer = createTransformer(ast);
transformer.helper("normalize" /* NORMALIZE */);
// traverse
ast.body && traverseNode(ast.body, transformer);
// set meta information
const context = transformer.context();
ast.helpers = Array.from(context.helpers);
}
function createCodeGenerator(ast, options) {
const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
const _context = {
source: ast.loc.source,
filename,
code: '',
column: 1,
line: 1,
offset: 0,
map: undefined,
breakLineCode,
needIndent: _needIndent,
indentLevel: 0
};
const context = () => _context;
function push(code, node) {
_context.code += code;
}
function _newline(n, withBreakLine = true) {
const _breakLineCode = withBreakLine ? breakLineCode : '';
push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
}
function indent(withNewLine = true) {
const level = ++_context.indentLevel;
withNewLine && _newline(level);
}
function deindent(withNewLine = true) {
const level = --_context.indentLevel;
withNewLine && _newline(level);
}
function newline() {
_newline(_context.indentLevel);
}
const helper = (key) => `_${key}`;
const needIndent = () => _context.needIndent;
return {
context,
push,
indent,
deindent,
newline,
helper,
needIndent
};
}
function generateLinkedNode(generator, node) {
const { helper } = generator;
generator.push(`${helper("linked" /* LINKED */)}(`);
generateNode(generator, node.key);
if (node.modifier) {
generator.push(`, `);
generateNode(generator, node.modifier);
}
generator.push(`)`);
}
function generateMessageNode(generator, node) {
const { helper, needIndent } = generator;
generator.push(`${helper("normalize" /* NORMALIZE */)}([`);
generator.indent(needIndent());
const length = node.items.length;
for (let i = 0; i < length; i++) {
generateNode(generator, node.items[i]);
if (i === length - 1) {
break;
}
generator.push(', ');
}
generator.deindent(needIndent());
generator.push('])');
}
function generatePluralNode(generator, node) {
const { helper, needIndent } = generator;
if (node.cases.length > 1) {
generator.push(`${helper("plural" /* PLURAL */)}([`);
generator.indent(needIndent());
const length = node.cases.length;
for (let i = 0; i < length; i++) {
generateNode(generator, node.cases[i]);
if (i === length - 1) {
break;
}
generator.push(', ');
}
generator.deindent(needIndent());
generator.push(`])`);
}
}
function generateResource(generator, node) {
if (node.body) {
generateNode(generator, node.body);
}
else {
generator.push('null');
}
}
function generateNode(generator, node) {
const { helper } = generator;
switch (node.type) {
case 0 /* Resource */:
generateResource(generator, node);
break;
case 1 /* Plural */:
generatePluralNode(generator, node);
break;
case 2 /* Message */:
generateMessageNode(generator, node);
break;
case 6 /* Linked */:
generateLinkedNode(generator, node);
break;
case 8 /* LinkedModifier */:
generator.push(JSON.stringify(node.value), node);
break;
case 7 /* LinkedKey */:
generator.push(JSON.stringify(node.value), node);
break;
case 5 /* List */:
generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node);
break;
case 4 /* Named */:
generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node);
break;
case 9 /* Literal */:
generator.push(JSON.stringify(node.value), node);
break;
case 3 /* Text */:
generator.push(JSON.stringify(node.value), node);
break;
default:
{
throw new Error(`unhandled codegen node type: ${node.type}`);
}
}
}
// generate code from AST
const generate = (ast, options = {} // eslint-disable-line
) => {
const mode = isString(options.mode) ? options.mode : 'normal';
const filename = isString(options.filename)
? options.filename
: 'message.intl';
const sourceMap = !!options.sourceMap;
// prettier-ignore
const breakLineCode = options.breakLineCode != null
? options.breakLineCode
: mode === 'arrow'
? ';'
: '\n';
const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
const helpers = ast.helpers || [];
const generator = createCodeGenerator(ast, {
mode,
filename,
sourceMap,
breakLineCode,
needIndent
});
generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
generator.indent(needIndent);
if (helpers.length > 0) {
generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`);
generator.newline();
}
generator.push(`return `);
generateNode(generator, ast);
generator.deindent(needIndent);
generator.push(`}`);
const { code, map } = generator.context();
return {
ast,
code,
map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
};
};
function baseCompile(source, options = {}) {
const assignedOptions = assign({}, options);
// parse source codes
const parser = createParser(assignedOptions);
const ast = parser.parse(source);
// transform ASTs
transform(ast, assignedOptions);
// generate javascript codes
return generate(ast, assignedOptions);
}
const pathStateMachine = [];
pathStateMachine[0 /* BEFORE_PATH */] = {
["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[1 /* IN_PATH */] = {
["w" /* WORKSPACE */]: [1 /* IN_PATH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[2 /* BEFORE_IDENT */] = {
["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
};
pathStateMachine[3 /* IN_IDENT */] = {
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
};
pathStateMachine[4 /* IN_SUB_PATH */] = {
["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [
4 /* IN_SUB_PATH */,
2 /* INC_SUB_PATH_DEPTH */
],
["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
};
pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
};
pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
};
/**
* Check if an expression is a literal value.
*/
const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
function isLiteral(exp) {
return literalValueRE.test(exp);
}
/**
* Strip quotes from a string
*/
function stripQuotes(str) {
const a = str.charCodeAt(0);
const b = str.charCodeAt(str.length - 1);
return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
}
/**
* Determine the type of a character in a keypath.
*/
function getPathCharType(ch) {
if (ch === undefined || ch === null) {
return "o" /* END_OF_FAIL */;
}
const code = ch.charCodeAt(0);
switch (code) {
case 0x5b: // [
case 0x5d: // ]
case 0x2e: // .
case 0x22: // "
case 0x27: // '
return ch;
case 0x5f: // _
case 0x24: // $
case 0x2d: // -
return "i" /* IDENT */;
case 0x09: // Tab (HT)
case 0x0a: // Newline (LF)
case 0x0d: // Return (CR)
case 0xa0: // No-break space (NBSP)
case 0xfeff: // Byte Order Mark (BOM)
case 0x2028: // Line Separator (LS)
case 0x2029: // Paragraph Separator (PS)
return "w" /* WORKSPACE */;
}
return "i" /* IDENT */;
}
/**
* Format a subPath, return its plain form if it is
* a literal string or number. Otherwise prepend the
* dynamic indicator (*).
*/
function formatSubPath(path) {
const trimmed = path.trim();
// invalid leading 0
if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
return false;
}
return isLiteral(trimmed)
? stripQuotes(trimmed)
: "*" /* ASTARISK */ + trimmed;
}
/**
* Parse a string path into an array of segments
*/
function parse(path) {
const keys = [];
let index = -1;
let mode = 0 /* BEFORE_PATH */;
let subPathDepth = 0;
let c;
let key; // eslint-disable-line
let newChar;
let type;
let transition;
let action;
let typeMap;
const actions = [];
actions[0 /* APPEND */] = () => {
if (key === undefined) {
key = newChar;
}
else {
key += newChar;
}
};
actions[1 /* PUSH */] = () => {
if (key !== undefined) {
keys.push(key);
key = undefined;
}
};
actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
actions[0 /* APPEND */]();
subPathDepth++;
};
actions[3 /* PUSH_SUB_PATH */] = () => {
if (subPathDepth > 0) {
subPathDepth--;
mode = 4 /* IN_SUB_PATH */;
actions[0 /* APPEND */]();
}
else {
subPathDepth = 0;
if (key === undefined) {
return false;
}
key = formatSubPath(key);
if (key === false) {
return false;
}
else {
actions[1 /* PUSH */]();
}
}
};
function maybeUnescapeQuote() {
const nextChar = path[index + 1];
if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
nextChar === "'" /* SINGLE_QUOTE */) ||
(mode === 6 /* IN_DOUBLE_QUOTE */ &&
nextChar === "\"" /* DOUBLE_QUOTE */)) {
index++;
newChar = '\\' + nextChar;
actions[0 /* APPEND */]();
return true;
}
}
while (mode !== null) {
index++;
c = path[index];
if (c === '\\' && maybeUnescapeQuote()) {
continue;
}
type = getPathCharType(c);
typeMap = pathStateMachine[mode];
transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
// check parse error
if (transition === 8 /* ERROR */) {
return;
}
mode = transition[0];
if (transition[1] !== undefined) {
action = actions[transition[1]];
if (action) {
newChar = c;
if (action() === false) {
return;
}
}
}
// check parse finish
if (mode === 7 /* AFTER_PATH */) {
return keys;
}
}
}
// path token cache
const cache = new Map();
/**
* key-value message resolver
*
* @remarks
* Resolves messages with the key-value structure. Note that messages with a hierarchical structure such as objects cannot be resolved
*
* @param obj - A target object to be resolved with path
* @param path - A {@link Path | path} to resolve the value of message
*
* @returns A resolved {@link PathValue | path value}
*
* @VueI18nGeneral
*/
function resolveWithKeyValue(obj, path) {
return isObject(obj) ? obj[path] : null;
}
/**
* message resolver
*
* @remarks
* Resolves messages. messages with a hierarchical structure such as objects can be resolved. This resolver is used in VueI18n as default.
*
* @param obj - A target object to be resolved with path
* @param path - A {@link Path | path} to resolve the value of message
*
* @returns A resolved {@link PathValue | path value}
*
* @VueI18nGeneral
*/
function resolveValue(obj, path) {
// check object
if (!isObject(obj)) {
return null;
}
// parse path
let hit = cache.get(path);
if (!hit) {
hit = parse(path);
if (hit) {
cache.set(path, hit);
}
}
// check hit
if (!hit) {
return null;
}
// resolve path value
const len = hit.length;
let last = obj;
let i = 0;
while (i < len) {
const val = last[hit[i]];
if (val === undefined) {
return null;
}
last = val;
i++;
}
return last;
}
const DEFAULT_MODIFIER = (str) => str;
const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
const DEFAULT_MESSAGE_DATA_TYPE = 'text';
const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
const DEFAULT_INTERPOLATE = toDisplayString;
function pluralDefault(choice, choicesLength) {
choice = Math.abs(choice);
if (choicesLength === 2) {
// prettier-ignore
return choice
? choice > 1
? 1
: 0
: 1;
}
return choice ? Math.min(choice, 2) : 0;
}
function getPluralIndex(options) {
// prettier-ignore
const index = isNumber(options.pluralIndex)
? options.pluralIndex
: -1;
// prettier-ignore
return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
? isNumber(options.named.count)
? options.named.count
: isNumber(options.named.n)
? options.named.n
: index
: index;
}
function normalizeNamed(pluralIndex, props) {
if (!props.count) {
props.count = pluralIndex;
}
if (!props.n) {
props.n = pluralIndex;
}
}
function createMessageContext(options = {}) {
const locale = options.locale;
const pluralIndex = getPluralIndex(options);
const pluralRule = isObject(options.pluralRules) &&
isString(locale) &&
isFunction(options.pluralRules[locale])
? options.pluralRules[locale]
: pluralDefault;
const orgPluralRule = isObject(options.pluralRules) &&
isString(locale) &&
isFunction(options.pluralRules[locale])
? pluralDefault
: undefined;
const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
const _list = options.list || [];
const list = (index) => _list[index];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _named = options.named || {};
isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
const named = (key) => _named[key];
// TODO: need to design resolve message function?
function message(key) {
// prettier-ignore
const msg = isFunction(options.messages)
? options.messages(key)
: isObject(options.messages)
? options.messages[key]
: false;
return !msg
? options.parent
? options.parent.message(key) // resolve from parent messages
: DEFAULT_MESSAGE
: msg;
}
const _modifier = (name) => options.modifiers
? options.modifiers[name]
: DEFAULT_MODIFIER;
const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
? options.processor.normalize
: DEFAULT_NORMALIZE;
const interpolate = isPlainObject(options.processor) &&
isFunction(options.processor.interpolate)
? options.processor.interpolate
: DEFAULT_INTERPOLATE;
const type = isPlainObject(options.processor) && isString(options.processor.type)
? options.processor.type
: DEFAULT_MESSAGE_DATA_TYPE;
const ctx = {
["list" /* LIST */]: list,
["named" /* NAMED */]: named,
["plural" /* PLURAL */]: plural,
["linked" /* LINKED */]: (key, modifier) => {
// TODO: should check `key`
const msg = message(key)(ctx);
return isString(modifier) ? _modifier(modifier)(msg) : msg;
},
["message" /* MESSAGE */]: message,
["type" /* TYPE */]: type,
["interpolate" /* INTERPOLATE */]: interpolate,
["normalize" /* NORMALIZE */]: normalize
};
return ctx;
}
const IntlifyDevToolsHooks = {
I18nInit: 'i18n:init',
FunctionTranslate: 'function:translate'
};
let devtools = null;
function setDevToolsHook(hook) {
devtools = hook;
}
function initI18nDevTools(i18n, version, meta) {
// TODO: queue if devtools is undefined
devtools &&
devtools.emit(IntlifyDevToolsHooks.I18nInit, {
timestamp: Date.now(),
i18n,
version,
meta
});
}
const translateDevTools = /* #__PURE__*/ createDevToolsHook(IntlifyDevToolsHooks.FunctionTranslate);
function createDevToolsHook(hook) {
return (payloads) => devtools && devtools.emit(hook, payloads);
}
const CoreWarnCodes = {
NOT_FOUND_KEY: 1,
FALLBACK_TO_TRANSLATE: 2,
CANNOT_FORMAT_NUMBER: 3,
FALLBACK_TO_NUMBER_FORMAT: 4,
CANNOT_FORMAT_DATE: 5,
FALLBACK_TO_DATE_FORMAT: 6,
__EXTEND_POINT__: 7
};
/** @internal */
const warnMessages$1 = {
[CoreWarnCodes.NOT_FOUND_KEY]: `Not found '{key}' key in '{locale}' locale messages.`,
[CoreWarnCodes.FALLBACK_TO_TRANSLATE]: `Fall back to translate '{key}' key with '{target}' locale.`,
[CoreWarnCodes.CANNOT_FORMAT_NUMBER]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
[CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT]: `Fall back to number format '{key}' key with '{target}' locale.`,
[CoreWarnCodes.CANNOT_FORMAT_DATE]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
[CoreWarnCodes.FALLBACK_TO_DATE_FORMAT]: `Fall back to datetime format '{key}' key with '{target}' locale.`
};
function getWarnMessage$1(code, ...args) {
return format(warnMessages$1[code], ...args);
}
/**
* Fallback with simple implemenation
*
* @remarks
* A fallback locale function implemented with a simple fallback algorithm.
*
* Basically, it returns the value as specified in the `fallbackLocale` props, and is processed with the fallback inside intlify.
*
* @param ctx - A {@link CoreContext | context}
* @param fallback - A {@link FallbackLocale | fallback locale}
* @param start - A starting {@link Locale | locale}
*
* @returns Fallback locales
*
* @VueI18nGeneral
*/
function fallbackWithSimple(ctx, fallback, start // eslint-disable-line @typescript-eslint/no-unused-vars
) {
// prettier-ignore
return [...new Set([
start,
...(isArray(fallback)
? fallback
: isObject(fallback)
? Object.keys(fallback)
: isString(fallback)
? [fallback]
: [start])
])];
}
/**
* Fallback with locale chain
*
* @remarks
* A fallback locale function implemented with a fallback chain algorithm. It's used in VueI18n as default.
*
* @param ctx - A {@link CoreContext | context}
* @param fallback - A {@link FallbackLocale | fallback locale}
* @param start - A starting {@link Locale | locale}
*
* @returns Fallback locales
*
* @VueI18nSee [Fallbacking](../guide/essentials/fallback)
*
* @VueI18nGeneral
*/
function fallbackWithLocaleChain(ctx, fallback, start) {
const startLocale = isString(start) ? start : DEFAULT_LOCALE;
const context = ctx;
if (!context.__localeChainCache) {
context.__localeChainCache = new Map();
}
let chain = context.__localeChainCache.get(startLocale);
if (!chain) {
chain = [];
// first block defined by start
let block = [start];
// while any intervening block found
while (isArray(block)) {
block = appendBlockToChain(chain, block, fallback);
}
// prettier-ignore
// last block defined by default
const defaults = isArray(fallback) || !isPlainObject(fallback)
? fallback
: fallback['default']
? fallback['default']
: null;
// convert defaults to array
block = isString(defaults) ? [defaults] : defaults;
if (isArray(block)) {
appendBlockToChain(chain, block, false);
}
context.__localeChainCache.set(startLocale, chain);
}
return chain;
}
function appendBlockToChain(chain, block, blocks) {
let follow = true;
for (let i = 0; i < block.length && isBoolean(follow); i++) {
const locale = block[i];
if (isString(locale)) {
follow = appendLocaleToChain(chain, block[i], blocks);
}
}
return follow;
}
function appendLocaleToChain(chain, locale, blocks) {
let follow;
const tokens = locale.split('-');
do {
const target = tokens.join('-');
follow = appendItemToChain(chain, target, blocks);
tokens.splice(-1, 1);
} while (tokens.length && follow === true);
return follow;
}
function appendItemToChain(chain, target, blocks) {
let follow = false;
if (!chain.includes(target)) {
follow = true;
if (target) {
follow = target[target.length - 1] !== '!';
const locale = target.replace(/!/g, '');
chain.push(locale);
if ((isArray(blocks) || isPlainObject(blocks)) &&
blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
follow = blocks[locale];
}
}
}
return follow;
}
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Intlify core-base version
* @internal
*/
const VERSION$1 = '9.2.0-beta.12';
const NOT_REOSLVED = -1;
const DEFAULT_LOCALE = 'en-US';
const MISSING_RESOLVE_VALUE = '';
function getDefaultLinkedModifiers() {
return {
upper: (val) => (isString(val) ? val.toUpperCase() : val),
lower: (val) => (isString(val) ? val.toLowerCase() : val),
// prettier-ignore
capitalize: (val) => (isString(val)
? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
: val)
};
}
let _compiler;
function registerMessageCompiler(compiler) {
_compiler = compiler;
}
let _resolver;
/**
* Register the message resolver
*
* @param resolver - A {@link MessageResolver} function
*
* @VueI18nGeneral
*/
function registerMessageResolver(resolver) {
_resolver = resolver;
}
let _fallbacker;
/**
* Register the locale fallbacker
*
* @param fallbacker - A {@link LocaleFallbacker} function
*
* @VueI18nGeneral
*/
function registerLocaleFallbacker(fallbacker) {
_fallbacker = fallbacker;
}
// Additional Meta for Intlify DevTools
let _additionalMeta = null;
const setAdditionalMeta = (meta) => {
_additionalMeta = meta;
};
const getAdditionalMeta = () => _additionalMeta;
// ID for CoreContext
let _cid = 0;
function createCoreContext(options = {}) {
// setup options
const version = isString(options.version) ? options.version : VERSION$1;
const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
const fallbackLocale = isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
isString(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const messages = isPlainObject(options.messages)
? options.messages
: { [locale]: {} };
const datetimeFormats = isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [locale]: {} }
;
const numberFormats = isPlainObject(options.numberFormats)
? options.numberFormats
: { [locale]: {} }
;
const modifiers = assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
const pluralRules = options.pluralRules || {};
const missing = isFunction(options.missing) ? options.missing : null;
const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true;
const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
const fallbackFormat = !!options.fallbackFormat;
const unresolving = !!options.unresolving;
const postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null;
const processor = isPlainObject(options.processor) ? options.processor : null;
const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
const escapeParameter = !!options.escapeParameter;
const messageCompiler = isFunction(options.messageCompiler)
? options.messageCompiler
: _compiler;
const messageResolver = isFunction(options.messageResolver)
? options.messageResolver
: _resolver || resolveWithKeyValue;
const localeFallbacker = isFunction(options.localeFallbacker)
? options.localeFallbacker
: _fallbacker || fallbackWithSimple;
const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
// setup internal options
const internalOptions = options;
const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
? internalOptions.__datetimeFormatters
: new Map()
;
const __numberFormatters = isObject(internalOptions.__numberFormatters)
? internalOptions.__numberFormatters
: new Map()
;
const __meta = isObject(internalOptions.__meta) ? internalOptions.__meta : {};
_cid++;
const context = {
version,
cid: _cid,
locale,
fallbackLocale,
messages,
modifiers,
pluralRules,
missing,
missingWarn,
fallbackWarn,
fallbackFormat,
unresolving,
postTranslation,
processor,
warnHtmlMessage,
escapeParameter,
messageCompiler,
messageResolver,
localeFallbacker,
onWarn,
__meta
};
{
context.datetimeFormats = datetimeFormats;
context.numberFormats = numberFormats;
context.__datetimeFormatters = __datetimeFormatters;
context.__numberFormatters = __numberFormatters;
}
// for vue-devtools timeline event
{
context.__v_emitter =
internalOptions.__v_emitter != null
? internalOptions.__v_emitter
: undefined;
}
// NOTE: experimental !!
{
initI18nDevTools(context, version, __meta);
}
return context;
}
/** @internal */
function isTranslateFallbackWarn(fallback, key) {
return fallback instanceof RegExp ? fallback.test(key) : fallback;
}
/** @internal */
function isTranslateMissingWarn(missing, key) {
return missing instanceof RegExp ? missing.test(key) : missing;
}
/** @internal */
function handleMissing(context, key, locale, missingWarn, type) {
const { missing, onWarn } = context;
// for vue-devtools timeline event
{
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("missing" /* MISSING */, {
locale,
key,
type,
groupId: `${type}:${key}`
});
}
}
if (missing !== null) {
const ret = missing(context, locale, key, type);
return isString(ret) ? ret : key;
}
else {
if (isTranslateMissingWarn(missingWarn, key)) {
onWarn(getWarnMessage$1(CoreWarnCodes.NOT_FOUND_KEY, { key, locale }));
}
return key;
}
}
/** @internal */
function updateFallbackLocale(ctx, locale, fallback) {
const context = ctx;
context.__localeChainCache = new Map();
ctx.localeFallbacker(ctx, fallback, locale);
}
/* eslint-enable @typescript-eslint/no-explicit-any */
const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
function checkHtmlMessage(source, options) {
const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
if (warnHtmlMessage && RE_HTML_TAG.test(source)) {
warn(format(WARN_MESSAGE, { source }));
}
}
const defaultOnCacheKey = (source) => source;
let compileCache = Object.create(null);
function compileToFunction(source, options = {}) {
{
// check HTML message
checkHtmlMessage(source, options);
// check caches
const onCacheKey = options.onCacheKey || defaultOnCacheKey;
const key = onCacheKey(source);
const cached = compileCache[key];
if (cached) {
return cached;
}
// compile error detecting
let occurred = false;
const onError = options.onError || defaultOnError;
options.onError = (err) => {
occurred = true;
onError(err);
};
// compile
const { code } = baseCompile(source, options);
// evaluate function
const msg = new Function(`return ${code}`)();
// if occurred compile error, don't cache
return !occurred ? (compileCache[key] = msg) : msg;
}
}
let code$2 = CompileErrorCodes.__EXTEND_POINT__;
const inc$2 = () => code$2++;
const CoreErrorCodes = {
INVALID_ARGUMENT: code$2,
INVALID_DATE_ARGUMENT: inc$2(),
INVALID_ISO_DATE_ARGUMENT: inc$2(),
__EXTEND_POINT__: inc$2() // 18
};
function createCoreError(code) {
return createCompileError(code, null, { messages: errorMessages$1 } );
}
/** @internal */
const errorMessages$1 = {
[CoreErrorCodes.INVALID_ARGUMENT]: 'Invalid arguments',
[CoreErrorCodes.INVALID_DATE_ARGUMENT]: 'The date provided is an invalid Date object.' +
'Make sure your Date represents a valid date.',
[CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT]: 'The argument provided is not a valid ISO date string'
};
const NOOP_MESSAGE_FUNCTION = () => '';
const isMessageFunction = (val) => isFunction(val);
// implementation of `translate` function
function translate(context, ...args) {
const { fallbackFormat, postTranslation, unresolving, fallbackLocale, messages } = context;
const [key, options] = parseTranslateArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const escapeParameter = isBoolean(options.escapeParameter)
? options.escapeParameter
: context.escapeParameter;
const resolvedMessage = !!options.resolvedMessage;
// prettier-ignore
const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
? !isBoolean(options.default)
? options.default
: key
: fallbackFormat // default by `fallbackFormat` option
? key
: '';
const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
const locale = isString(options.locale) ? options.locale : context.locale;
// escape params
escapeParameter && escapeParams(options);
// resolve message format
// eslint-disable-next-line prefer-const
let [format, targetLocale, message] = !resolvedMessage
? resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn)
: [
key,
locale,
messages[locale] || {}
];
// if you use default message, set it as message format!
let cacheBaseKey = key;
if (!resolvedMessage &&
!(isString(format) || isMessageFunction(format))) {
if (enableDefaultMsg) {
format = defaultMsgOrKey;
cacheBaseKey = format;
}
}
// checking message format and target locale
if (!resolvedMessage &&
(!(isString(format) || isMessageFunction(format)) ||
!isString(targetLocale))) {
return unresolving ? NOT_REOSLVED : key;
}
if (isString(format) && context.messageCompiler == null) {
warn(`The message format compilation is not supported in this build. ` +
`Because message compiler isn't included. ` +
`You need to pre-compilation all message format. ` +
`So translate function return '${key}'.`);
return key;
}
// setup compile error detecting
let occurred = false;
const errorDetector = () => {
occurred = true;
};
// compile message format
const msg = !isMessageFunction(format)
? compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector)
: format;
// if occurred compile error, return the message format
if (occurred) {
return format;
}
// evaluate message with context
const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
const msgContext = createMessageContext(ctxOptions);
const messaged = evaluateMessage(context, msg, msgContext);
// if use post translation option, proceed it with handler
const ret = postTranslation ? postTranslation(messaged) : messaged;
// NOTE: experimental !!
{
// prettier-ignore
const payloads = {
timestamp: Date.now(),
key: isString(key)
? key
: isMessageFunction(format)
? format.key
: '',
locale: targetLocale || (isMessageFunction(format)
? format.locale
: ''),
format: isString(format)
? format
: isMessageFunction(format)
? format.source
: '',
message: ret
};
payloads.meta = assign({}, context.__meta, getAdditionalMeta() || {});
translateDevTools(payloads);
}
return ret;
}
function escapeParams(options) {
if (isArray(options.list)) {
options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
}
else if (isObject(options.named)) {
Object.keys(options.named).forEach(key => {
if (isString(options.named[key])) {
options.named[key] = escapeHtml(options.named[key]);
}
});
}
}
function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
const { messages, onWarn, messageResolver: resolveValue, localeFallbacker } = context;
const locales = localeFallbacker(context, fallbackLocale, locale); // eslint-disable-line @typescript-eslint/no-explicit-any
let message = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'translate';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_TRANSLATE, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if (locale !== targetLocale) {
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to,
groupId: `${type}:${key}`
});
}
}
message =
messages[targetLocale] || {};
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if (inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-resolve-start';
endTag = 'intlify-message-resolve-end';
mark && mark(startTag);
}
if ((format = resolveValue(message, key)) === null) {
// if null, resolve with object key path
format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
}
// for vue-devtools timeline event
if (inBrowser) {
const end = window.performance.now();
const emitter = context.__v_emitter;
if (emitter && start && format) {
emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
type: "message-resolve" /* MESSAGE_RESOLVE */,
key,
message: format,
time: end - start,
groupId: `${type}:${key}`
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message resolve', startTag, endTag);
}
}
if (isString(format) || isFunction(format))
break;
const missingRet = handleMissing(context, // eslint-disable-line @typescript-eslint/no-explicit-any
key, targetLocale, missingWarn, type);
if (missingRet !== key) {
format = missingRet;
}
from = to;
}
return [format, targetLocale, message];
}
function compileMessageFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
const { messageCompiler, warnHtmlMessage } = context;
if (isMessageFunction(format)) {
const msg = format;
msg.locale = msg.locale || targetLocale;
msg.key = msg.key || key;
return msg;
}
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if (inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-compilation-start';
endTag = 'intlify-message-compilation-end';
mark && mark(startTag);
}
const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
// for vue-devtools timeline event
if (inBrowser) {
const end = window.performance.now();
const emitter = context.__v_emitter;
if (emitter && start) {
emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
type: "message-compilation" /* MESSAGE_COMPILATION */,
message: format,
time: end - start,
groupId: `${'translate'}:${key}`
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message compilation', startTag, endTag);
}
}
msg.locale = targetLocale;
msg.key = key;
msg.source = format;
return msg;
}
function evaluateMessage(context, msg, msgCtx) {
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if (inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-evaluation-start';
endTag = 'intlify-message-evaluation-end';
mark && mark(startTag);
}
const messaged = msg(msgCtx);
// for vue-devtools timeline event
if (inBrowser) {
const end = window.performance.now();
const emitter = context.__v_emitter;
if (emitter && start) {
emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
type: "message-evaluation" /* MESSAGE_EVALUATION */,
value: messaged,
time: end - start,
groupId: `${'translate'}:${msg.key}`
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message evaluation', startTag, endTag);
}
}
return messaged;
}
/** @internal */
function parseTranslateArgs(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
if (!isString(arg1) && !isNumber(arg1) && !isMessageFunction(arg1)) {
throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
}
// prettier-ignore
const key = isNumber(arg1)
? String(arg1)
: isMessageFunction(arg1)
? arg1
: arg1;
if (isNumber(arg2)) {
options.plural = arg2;
}
else if (isString(arg2)) {
options.default = arg2;
}
else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
options.named = arg2;
}
else if (isArray(arg2)) {
options.list = arg2;
}
if (isNumber(arg3)) {
options.plural = arg3;
}
else if (isString(arg3)) {
options.default = arg3;
}
else if (isPlainObject(arg3)) {
assign(options, arg3);
}
return [key, options];
}
function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
return {
warnHtmlMessage,
onError: (err) => {
errorDetector && errorDetector(err);
{
const message = `Message compilation error: ${err.message}`;
const codeFrame = err.location &&
generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("compile-error" /* COMPILE_ERROR */, {
message: source,
error: err.message,
start: err.location && err.location.start.offset,
end: err.location && err.location.end.offset,
groupId: `${'translate'}:${key}`
});
}
console.error(codeFrame ? `${message}\n${codeFrame}` : message);
}
},
onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
};
}
function getMessageContextOptions(context, locale, message, options) {
const { modifiers, pluralRules, messageResolver: resolveValue } = context;
const resolveMessage = (key) => {
const val = resolveValue(message, key);
if (isString(val)) {
let occurred = false;
const errorDetector = () => {
occurred = true;
};
const msg = compileMessageFormat(context, key, locale, val, key, errorDetector);
return !occurred
? msg
: NOOP_MESSAGE_FUNCTION;
}
else if (isMessageFunction(val)) {
return val;
}
else {
// TODO: should be implemented warning message
return NOOP_MESSAGE_FUNCTION;
}
};
const ctxOptions = {
locale,
modifiers,
pluralRules,
messages: resolveMessage
};
if (context.processor) {
ctxOptions.processor = context.processor;
}
if (options.list) {
ctxOptions.list = options.list;
}
if (options.named) {
ctxOptions.named = options.named;
}
if (isNumber(options.plural)) {
ctxOptions.pluralIndex = options.plural;
}
return ctxOptions;
}
const intlDefined = typeof Intl !== 'undefined';
const Availabilities = {
dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
};
// implementation of `datetime` function
function datetime(context, ...args) {
const { datetimeFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
const { __datetimeFormatters } = context;
if (!Availabilities.dateTimeFormat) {
onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_DATE));
return MISSING_RESOLVE_VALUE;
}
const [key, value, options, overrides] = parseDateTimeArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = isString(options.locale) ? options.locale : context.locale;
const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
fallbackLocale, locale);
if (!isString(key) || key === '') {
return new Intl.DateTimeFormat(locale).format(value);
}
// resolve format
let datetimeFormat = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'datetime format';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if (locale !== targetLocale) {
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to,
groupId: `${type}:${key}`
});
}
}
datetimeFormat =
datetimeFormats[targetLocale] || {};
format = datetimeFormat[key];
if (isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
from = to;
}
// checking format and target locale
if (!isPlainObject(format) || !isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!isEmptyObject(overrides)) {
id = `${id}__${JSON.stringify(overrides)}`;
}
let formatter = __datetimeFormatters.get(id);
if (!formatter) {
formatter = new Intl.DateTimeFormat(targetLocale, assign({}, format, overrides));
__datetimeFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseDateTimeArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let overrides = {};
let value;
if (isString(arg1)) {
// Only allow ISO strings - other date formats are often supported,
// but may cause different results in different browsers.
const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/);
if (!matches) {
throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
}
// Some browsers can not parse the iso datetime separated by space,
// this is a compromise solution by replace the 'T'/' ' with 'T'
const dateTime = matches[3]
? matches[3].trim().startsWith('T')
? `${matches[1].trim()}${matches[3].trim()}`
: `${matches[1].trim()}T${matches[3].trim()}`
: matches[1].trim();
value = new Date(dateTime);
try {
// This will fail if the date is not valid
value.toISOString();
}
catch (e) {
throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT);
}
}
else if (isDate(arg1)) {
if (isNaN(arg1.getTime())) {
throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT);
}
value = arg1;
}
else if (isNumber(arg1)) {
value = arg1;
}
else {
throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
}
if (isString(arg2)) {
options.key = arg2;
}
else if (isPlainObject(arg2)) {
options = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isPlainObject(arg3)) {
overrides = arg3;
}
if (isPlainObject(arg4)) {
overrides = arg4;
}
return [options.key || '', value, options, overrides];
}
/** @internal */
function clearDateTimeFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__datetimeFormatters.has(id)) {
continue;
}
context.__datetimeFormatters.delete(id);
}
}
// implementation of `number` function
function number(context, ...args) {
const { numberFormats, unresolving, fallbackLocale, onWarn, localeFallbacker } = context;
const { __numberFormatters } = context;
if (!Availabilities.numberFormat) {
onWarn(getWarnMessage$1(CoreWarnCodes.CANNOT_FORMAT_NUMBER));
return MISSING_RESOLVE_VALUE;
}
const [key, value, options, overrides] = parseNumberArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = isString(options.locale) ? options.locale : context.locale;
const locales = localeFallbacker(context, // eslint-disable-line @typescript-eslint/no-explicit-any
fallbackLocale, locale);
if (!isString(key) || key === '') {
return new Intl.NumberFormat(locale).format(value);
}
// resolve format
let numberFormat = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'number format';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage$1(CoreWarnCodes.FALLBACK_TO_NUMBER_FORMAT, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if (locale !== targetLocale) {
const emitter = context.__v_emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to,
groupId: `${type}:${key}`
});
}
}
numberFormat =
numberFormats[targetLocale] || {};
format = numberFormat[key];
if (isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type); // eslint-disable-line @typescript-eslint/no-explicit-any
from = to;
}
// checking format and target locale
if (!isPlainObject(format) || !isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!isEmptyObject(overrides)) {
id = `${id}__${JSON.stringify(overrides)}`;
}
let formatter = __numberFormatters.get(id);
if (!formatter) {
formatter = new Intl.NumberFormat(targetLocale, assign({}, format, overrides));
__numberFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseNumberArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let overrides = {};
if (!isNumber(arg1)) {
throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT);
}
const value = arg1;
if (isString(arg2)) {
options.key = arg2;
}
else if (isPlainObject(arg2)) {
options = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isPlainObject(arg3)) {
overrides = arg3;
}
if (isPlainObject(arg4)) {
overrides = arg4;
}
return [options.key || '', value, options, overrides];
}
/** @internal */
function clearNumberFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__numberFormatters.has(id)) {
continue;
}
context.__numberFormatters.delete(id);
}
}
/**
* Vue I18n Version
*
* @remarks
* Semver format. Same format as the package.json `version` field.
*
* @VueI18nGeneral
*/
const VERSION = '9.2.0-beta.12';
/**
* This is only called development env
* istanbul-ignore-next
*/
function initDev() {
{
{
console.info(`You are running a development build of vue-i18n.\n` +
`Make sure to use the production build (*.prod.js) when deploying for production.`);
}
}
}
let code$1 = CoreWarnCodes.__EXTEND_POINT__;
const inc$1 = () => code$1++;
const I18nWarnCodes = {
FALLBACK_TO_ROOT: code$1,
NOT_SUPPORTED_PRESERVE: inc$1(),
NOT_SUPPORTED_FORMATTER: inc$1(),
NOT_SUPPORTED_PRESERVE_DIRECTIVE: inc$1(),
NOT_SUPPORTED_GET_CHOICE_INDEX: inc$1(),
COMPONENT_NAME_LEGACY_COMPATIBLE: inc$1(),
NOT_FOUND_PARENT_SCOPE: inc$1(),
NOT_SUPPORT_MULTI_I18N_INSTANCE: inc$1() // 14
};
const warnMessages = {
[I18nWarnCodes.FALLBACK_TO_ROOT]: `Fall back to {type} '{key}' with root locale.`,
[I18nWarnCodes.NOT_SUPPORTED_PRESERVE]: `Not supported 'preserve'.`,
[I18nWarnCodes.NOT_SUPPORTED_FORMATTER]: `Not supported 'formatter'.`,
[I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE]: `Not supported 'preserveDirectiveContent'.`,
[I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX]: `Not supported 'getChoiceIndex'.`,
[I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE]: `Component name legacy compatible: '{name}' -> 'i18n'`,
[I18nWarnCodes.NOT_FOUND_PARENT_SCOPE]: `Not found parent scope. use the global scope.`,
[I18nWarnCodes.NOT_SUPPORT_MULTI_I18N_INSTANCE]: `Not support multi i18n instance.`
};
function getWarnMessage(code, ...args) {
return format(warnMessages[code], ...args);
}
let code = CompileErrorCodes.__EXTEND_POINT__;
const inc = () => code++;
const I18nErrorCodes = {
// composer module errors
UNEXPECTED_RETURN_TYPE: code,
// legacy module errors
INVALID_ARGUMENT: inc(),
// i18n module errors
MUST_BE_CALL_SETUP_TOP: inc(),
NOT_INSLALLED: inc(),
NOT_AVAILABLE_IN_LEGACY_MODE: inc(),
// directive module errors
REQUIRED_VALUE: inc(),
INVALID_VALUE: inc(),
// vue-devtools errors
CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN: inc(),
NOT_INSLALLED_WITH_PROVIDE: inc(),
// unexpected error
UNEXPECTED_ERROR: inc(),
// not compatible legacy vue-i18n constructor
NOT_COMPATIBLE_LEGACY_VUE_I18N: inc(),
// bridge support vue 2.x only
BRIDGE_SUPPORT_VUE_2_ONLY: inc(),
// for enhancement
__EXTEND_POINT__: inc() // 27
};
function createI18nError(code, ...args) {
return createCompileError(code, null, { messages: errorMessages, args } );
}
const errorMessages = {
[I18nErrorCodes.UNEXPECTED_RETURN_TYPE]: 'Unexpected return type in composer',
[I18nErrorCodes.INVALID_ARGUMENT]: 'Invalid argument',
[I18nErrorCodes.MUST_BE_CALL_SETUP_TOP]: 'Must be called at the top of a `setup` function',
[I18nErrorCodes.NOT_INSLALLED]: 'Need to install with `app.use` function',
[I18nErrorCodes.UNEXPECTED_ERROR]: 'Unexpected error',
[I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE]: 'Not available in legacy mode',
[I18nErrorCodes.REQUIRED_VALUE]: `Required in value: {0}`,
[I18nErrorCodes.INVALID_VALUE]: `Invalid value`,
[I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN]: `Cannot setup vue-devtools plugin`,
[I18nErrorCodes.NOT_INSLALLED_WITH_PROVIDE]: 'Need to install with `provide` function',
[I18nErrorCodes.NOT_COMPATIBLE_LEGACY_VUE_I18N]: 'Not compatible legacy VueI18n.',
[I18nErrorCodes.BRIDGE_SUPPORT_VUE_2_ONLY]: 'vue-i18n-bridge support Vue 2.x only'
};
const TransrateVNodeSymbol =
/* #__PURE__*/ makeSymbol('__transrateVNode');
const DatetimePartsSymbol = /* #__PURE__*/ makeSymbol('__datetimeParts');
const NumberPartsSymbol = /* #__PURE__*/ makeSymbol('__numberParts');
const EnableEmitter = /* #__PURE__*/ makeSymbol('__enableEmitter');
const DisableEmitter = /* #__PURE__*/ makeSymbol('__disableEmitter');
const SetPluralRulesSymbol = makeSymbol('__setPluralRules');
const InejctWithOption = /* #__PURE__*/ makeSymbol('__injectWithOption');
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Transform flat json in obj to normal json in obj
*/
function handleFlatJson(obj) {
// check obj
if (!isObject(obj)) {
return obj;
}
for (const key in obj) {
// check key
if (!hasOwn(obj, key)) {
continue;
}
// handle for normal json
if (!key.includes('.')) {
// recursive process value if value is also a object
if (isObject(obj[key])) {
handleFlatJson(obj[key]);
}
}
// handle for flat json, transform to normal json
else {
// go to the last object
const subKeys = key.split('.');
const lastIndex = subKeys.length - 1;
let currentObj = obj;
for (let i = 0; i < lastIndex; i++) {
if (!(subKeys[i] in currentObj)) {
currentObj[subKeys[i]] = {};
}
currentObj = currentObj[subKeys[i]];
}
// update last object value, delete old property
currentObj[subKeys[lastIndex]] = obj[key];
delete obj[key];
// recursive process value if value is also a object
if (isObject(currentObj[subKeys[lastIndex]])) {
handleFlatJson(currentObj[subKeys[lastIndex]]);
}
}
}
return obj;
}
function getLocaleMessages(locale, options) {
const { messages, __i18n, messageResolver, flatJson } = options;
// prettier-ignore
const ret = isPlainObject(messages)
? messages
: isArray(__i18n)
? {}
: { [locale]: {} };
// merge locale messages of i18n custom block
if (isArray(__i18n)) {
__i18n.forEach(custom => {
if ('locale' in custom && 'resource' in custom) {
const { locale, resource } = custom;
if (locale) {
ret[locale] = ret[locale] || {};
deepCopy(resource, ret[locale]);
}
else {
deepCopy(resource, ret);
}
}
else {
isString(custom) && deepCopy(JSON.parse(custom), ret);
}
});
}
// handle messages for flat json
if (messageResolver == null && flatJson) {
for (const key in ret) {
if (hasOwn(ret, key)) {
handleFlatJson(ret[key]);
}
}
}
return ret;
}
const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val);
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
function deepCopy(src, des) {
// src and des should both be objects, and non of then can be a array
if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) {
throw createI18nError(I18nErrorCodes.INVALID_VALUE);
}
for (const key in src) {
if (hasOwn(src, key)) {
if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) {
// replace with src[key] when:
// src[key] or des[key] is not a object, or
// src[key] or des[key] is a array
des[key] = src[key];
}
else {
// src[key] and des[key] are both object, merge them
deepCopy(src[key], des[key]);
}
}
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getComponentOptions(instance) {
return instance.type ;
}
/* eslint-enable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-explicit-any */
const DEVTOOLS_META = '__INTLIFY_META__';
let composerID = 0;
function defineCoreMissingHandler(missing) {
return ((ctx, locale, key, type) => {
return missing(locale, key, getCurrentInstance() || undefined, type);
});
}
// for Intlify DevTools
const getMetaInfo = () => {
const instance = getCurrentInstance();
let meta = null; // eslint-disable-line @typescript-eslint/no-explicit-any
return instance && (meta = getComponentOptions(instance)[DEVTOOLS_META])
? { [DEVTOOLS_META]: meta } // eslint-disable-line @typescript-eslint/no-explicit-any
: null;
};
/**
* Create composer interface factory
*
* @internal
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function createComposer(options = {}, VueI18nLegacy) {
const { __root } = options;
const _isGlobal = __root === undefined;
let _inheritLocale = isBoolean(options.inheritLocale)
? options.inheritLocale
: true;
const _locale = ref(
// prettier-ignore
__root && _inheritLocale
? __root.locale.value
: isString(options.locale)
? options.locale
: DEFAULT_LOCALE);
const _fallbackLocale = ref(
// prettier-ignore
__root && _inheritLocale
? __root.fallbackLocale.value
: isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: _locale.value);
const _messages = ref(getLocaleMessages(_locale.value, options));
// prettier-ignore
const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [_locale.value]: {} })
;
// prettier-ignore
const _numberFormats = ref(isPlainObject(options.numberFormats)
? options.numberFormats
: { [_locale.value]: {} })
;
// warning suppress options
// prettier-ignore
let _missingWarn = __root
? __root.missingWarn
: isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true;
// prettier-ignore
let _fallbackWarn = __root
? __root.fallbackWarn
: isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
// prettier-ignore
let _fallbackRoot = __root
? __root.fallbackRoot
: isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true;
// configure fall back to root
let _fallbackFormat = !!options.fallbackFormat;
// runtime missing
let _missing = isFunction(options.missing) ? options.missing : null;
let _runtimeMissing = isFunction(options.missing)
? defineCoreMissingHandler(options.missing)
: null;
// postTranslation handler
let _postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null;
let _warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
let _escapeParameter = !!options.escapeParameter;
// custom linked modifiers
// prettier-ignore
const _modifiers = __root
? __root.modifiers
: isPlainObject(options.modifiers)
? options.modifiers
: {};
// pluralRules
let _pluralRules = options.pluralRules || (__root && __root.pluralRules);
// runtime context
// eslint-disable-next-line prefer-const
let _context;
function getCoreContext() {
const ctxOptions = {
version: VERSION,
locale: _locale.value,
fallbackLocale: _fallbackLocale.value,
messages: _messages.value,
modifiers: _modifiers,
pluralRules: _pluralRules,
missing: _runtimeMissing === null ? undefined : _runtimeMissing,
missingWarn: _missingWarn,
fallbackWarn: _fallbackWarn,
fallbackFormat: _fallbackFormat,
unresolving: true,
postTranslation: _postTranslation === null ? undefined : _postTranslation,
warnHtmlMessage: _warnHtmlMessage,
escapeParameter: _escapeParameter,
messageResolver: options.messageResolver,
__meta: { framework: 'vue' }
};
{
ctxOptions.datetimeFormats = _datetimeFormats.value;
ctxOptions.numberFormats = _numberFormats.value;
ctxOptions.__datetimeFormatters = isPlainObject(_context)
? _context.__datetimeFormatters
: undefined;
ctxOptions.__numberFormatters = isPlainObject(_context)
? _context.__numberFormatters
: undefined;
}
{
ctxOptions.__v_emitter = isPlainObject(_context)
? _context.__v_emitter
: undefined;
}
return createCoreContext(ctxOptions);
}
_context = getCoreContext();
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
// track reactivity
function trackReactivityValues() {
return [
_locale.value,
_fallbackLocale.value,
_messages.value,
_datetimeFormats.value,
_numberFormats.value
]
;
}
// locale
const locale = computed({
get: () => _locale.value,
set: val => {
_locale.value = val;
_context.locale = _locale.value;
}
});
// fallbackLocale
const fallbackLocale = computed({
get: () => _fallbackLocale.value,
set: val => {
_fallbackLocale.value = val;
_context.fallbackLocale = _fallbackLocale.value;
updateFallbackLocale(_context, _locale.value, val);
}
});
// messages
const messages = computed(() => _messages.value);
// datetimeFormats
const datetimeFormats = /* #__PURE__*/ computed(() => _datetimeFormats.value);
// numberFormats
const numberFormats = /* #__PURE__*/ computed(() => _numberFormats.value);
// getPostTranslationHandler
function getPostTranslationHandler() {
return isFunction(_postTranslation) ? _postTranslation : null;
}
// setPostTranslationHandler
function setPostTranslationHandler(handler) {
_postTranslation = handler;
_context.postTranslation = handler;
}
// getMissingHandler
function getMissingHandler() {
return _missing;
}
// setMissingHandler
function setMissingHandler(handler) {
if (handler !== null) {
_runtimeMissing = defineCoreMissingHandler(handler);
}
_missing = handler;
_context.missing = _runtimeMissing;
}
function isResolvedTranslateMessage(type, arg // eslint-disable-line @typescript-eslint/no-explicit-any
) {
return type !== 'translate' || !arg.resolvedMessage;
}
function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) {
trackReactivityValues(); // track reactive dependency
// NOTE: experimental !!
let ret;
{
try {
setAdditionalMeta(getMetaInfo());
ret = fn(_context);
}
finally {
setAdditionalMeta(null);
}
}
if (isNumber(ret) && ret === NOT_REOSLVED) {
const [key, arg2] = argumentParser();
if (__root &&
isString(key) &&
isResolvedTranslateMessage(warnType, arg2)) {
if (_fallbackRoot &&
(isTranslateFallbackWarn(_fallbackWarn, key) ||
isTranslateMissingWarn(_missingWarn, key))) {
warn(getWarnMessage(I18nWarnCodes.FALLBACK_TO_ROOT, {
key,
type: warnType
}));
}
// for vue-devtools timeline event
{
const { __v_emitter: emitter } = _context;
if (emitter && _fallbackRoot) {
emitter.emit("fallback" /* FALBACK */, {
type: warnType,
key,
to: 'global',
groupId: `${warnType}:${key}`
});
}
}
}
return __root && _fallbackRoot
? fallbackSuccess(__root)
: fallbackFail(key);
}
else if (successCondition(ret)) {
return ret;
}
else {
/* istanbul ignore next */
throw createI18nError(I18nErrorCodes.UNEXPECTED_RETURN_TYPE);
}
}
// t
function t(...args) {
return wrapWithDeps(context => Reflect.apply(translate, null, [context, ...args]), () => parseTranslateArgs(...args), 'translate', root => Reflect.apply(root.t, root, [...args]), key => key, val => isString(val));
}
// rt
function rt(...args) {
const [arg1, arg2, arg3] = args;
if (arg3 && !isObject(arg3)) {
throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
}
return t(...[arg1, arg2, assign({ resolvedMessage: true }, arg3 || {})]);
}
// d
function d(...args) {
return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format', root => Reflect.apply(root.d, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
}
// n
function n(...args) {
return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format', root => Reflect.apply(root.n, root, [...args]), () => MISSING_RESOLVE_VALUE, val => isString(val));
}
// for custom processor
function normalize(values) {
return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val);
}
const interpolate = (val) => val;
const processor = {
normalize,
interpolate,
type: 'vnode'
};
// transrateVNode, using for `i18n-t` component
function transrateVNode(...args) {
return wrapWithDeps(context => {
let ret;
const _context = context;
try {
_context.processor = processor;
ret = Reflect.apply(translate, null, [_context, ...args]);
}
finally {
_context.processor = null;
}
return ret;
}, () => parseTranslateArgs(...args), 'translate',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val));
}
// numberParts, using for `i18n-n` component
function numberParts(...args) {
return wrapWithDeps(context => Reflect.apply(number, null, [context, ...args]), () => parseNumberArgs(...args), 'number format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val));
}
// datetimeParts, using for `i18n-d` component
function datetimeParts(...args) {
return wrapWithDeps(context => Reflect.apply(datetime, null, [context, ...args]), () => parseDateTimeArgs(...args), 'datetime format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val));
}
function setPluralRules(rules) {
_pluralRules = rules;
_context.pluralRules = _pluralRules;
}
// te
function te(key, locale) {
const targetLocale = isString(locale) ? locale : _locale.value;
const message = getLocaleMessage(targetLocale);
return _context.messageResolver(message, key) !== null;
}
function resolveMessages(key) {
let messages = null;
const locales = fallbackWithLocaleChain(_context, _fallbackLocale.value, _locale.value);
for (let i = 0; i < locales.length; i++) {
const targetLocaleMessages = _messages.value[locales[i]] || {};
const messageValue = _context.messageResolver(targetLocaleMessages, key);
if (messageValue != null) {
messages = messageValue;
break;
}
}
return messages;
}
// tm
function tm(key) {
const messages = resolveMessages(key);
// prettier-ignore
return messages != null
? messages
: __root
? __root.tm(key) || {}
: {};
}
// getLocaleMessage
function getLocaleMessage(locale) {
return (_messages.value[locale] || {});
}
// setLocaleMessage
function setLocaleMessage(locale, message) {
_messages.value[locale] = message;
_context.messages = _messages.value;
}
// mergeLocaleMessage
function mergeLocaleMessage(locale, message) {
_messages.value[locale] = _messages.value[locale] || {};
deepCopy(message, _messages.value[locale]);
_context.messages = _messages.value;
}
// getDateTimeFormat
function getDateTimeFormat(locale) {
return _datetimeFormats.value[locale] || {};
}
// setDateTimeFormat
function setDateTimeFormat(locale, format) {
_datetimeFormats.value[locale] = format;
_context.datetimeFormats = _datetimeFormats.value;
clearDateTimeFormat(_context, locale, format);
}
// mergeDateTimeFormat
function mergeDateTimeFormat(locale, format) {
_datetimeFormats.value[locale] = assign(_datetimeFormats.value[locale] || {}, format);
_context.datetimeFormats = _datetimeFormats.value;
clearDateTimeFormat(_context, locale, format);
}
// getNumberFormat
function getNumberFormat(locale) {
return _numberFormats.value[locale] || {};
}
// setNumberFormat
function setNumberFormat(locale, format) {
_numberFormats.value[locale] = format;
_context.numberFormats = _numberFormats.value;
clearNumberFormat(_context, locale, format);
}
// mergeNumberFormat
function mergeNumberFormat(locale, format) {
_numberFormats.value[locale] = assign(_numberFormats.value[locale] || {}, format);
_context.numberFormats = _numberFormats.value;
clearNumberFormat(_context, locale, format);
}
// for debug
composerID++;
// watch root locale & fallbackLocale
if (__root) {
watch(__root.locale, (val) => {
if (_inheritLocale) {
_locale.value = val;
_context.locale = val;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
});
watch(__root.fallbackLocale, (val) => {
if (_inheritLocale) {
_fallbackLocale.value = val;
_context.fallbackLocale = val;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
});
}
// define basic composition API!
const composer = {
id: composerID,
locale,
fallbackLocale,
get inheritLocale() {
return _inheritLocale;
},
set inheritLocale(val) {
_inheritLocale = val;
if (val && __root) {
_locale.value = __root.locale.value;
_fallbackLocale.value = __root.fallbackLocale.value;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
},
get availableLocales() {
return Object.keys(_messages.value).sort();
},
messages,
get modifiers() {
return _modifiers;
},
get pluralRules() {
return _pluralRules || {};
},
get isGlobal() {
return _isGlobal;
},
get missingWarn() {
return _missingWarn;
},
set missingWarn(val) {
_missingWarn = val;
_context.missingWarn = _missingWarn;
},
get fallbackWarn() {
return _fallbackWarn;
},
set fallbackWarn(val) {
_fallbackWarn = val;
_context.fallbackWarn = _fallbackWarn;
},
get fallbackRoot() {
return _fallbackRoot;
},
set fallbackRoot(val) {
_fallbackRoot = val;
},
get fallbackFormat() {
return _fallbackFormat;
},
set fallbackFormat(val) {
_fallbackFormat = val;
_context.fallbackFormat = _fallbackFormat;
},
get warnHtmlMessage() {
return _warnHtmlMessage;
},
set warnHtmlMessage(val) {
_warnHtmlMessage = val;
_context.warnHtmlMessage = val;
},
get escapeParameter() {
return _escapeParameter;
},
set escapeParameter(val) {
_escapeParameter = val;
_context.escapeParameter = val;
},
t,
getLocaleMessage,
setLocaleMessage,
mergeLocaleMessage,
getPostTranslationHandler,
setPostTranslationHandler,
getMissingHandler,
setMissingHandler,
[SetPluralRulesSymbol]: setPluralRules
};
{
composer.datetimeFormats = datetimeFormats;
composer.numberFormats = numberFormats;
composer.rt = rt;
composer.te = te;
composer.tm = tm;
composer.d = d;
composer.n = n;
composer.getDateTimeFormat = getDateTimeFormat;
composer.setDateTimeFormat = setDateTimeFormat;
composer.mergeDateTimeFormat = mergeDateTimeFormat;
composer.getNumberFormat = getNumberFormat;
composer.setNumberFormat = setNumberFormat;
composer.mergeNumberFormat = mergeNumberFormat;
composer[InejctWithOption] = options.__injectWithOption;
{
composer[TransrateVNodeSymbol] = transrateVNode;
composer[NumberPartsSymbol] = numberParts;
composer[DatetimePartsSymbol] = datetimeParts;
}
}
// for vue-devtools timeline event
{
composer[EnableEmitter] = (emitter) => {
_context.__v_emitter = emitter;
};
composer[DisableEmitter] = () => {
_context.__v_emitter = undefined;
};
}
return composer;
}
/* eslint-enable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Convert to I18n Composer Options from VueI18n Options
*
* @internal
*/
function convertComposerOptions(options) {
const locale = isString(options.locale) ? options.locale : DEFAULT_LOCALE;
const fallbackLocale = isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const missing = isFunction(options.missing) ? options.missing : undefined;
const missingWarn = isBoolean(options.silentTranslationWarn) ||
isRegExp(options.silentTranslationWarn)
? !options.silentTranslationWarn
: true;
const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
isRegExp(options.silentFallbackWarn)
? !options.silentFallbackWarn
: true;
const fallbackRoot = isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true;
const fallbackFormat = !!options.formatFallbackMessages;
const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
const pluralizationRules = options.pluralizationRules;
const postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: undefined;
const warnHtmlMessage = isString(options.warnHtmlInMessage)
? options.warnHtmlInMessage !== 'off'
: true;
const escapeParameter = !!options.escapeParameterHtml;
const inheritLocale = isBoolean(options.sync) ? options.sync : true;
if (options.formatter) {
warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
}
if (options.preserveDirectiveContent) {
warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
}
let messages = options.messages;
if (isPlainObject(options.sharedMessages)) {
const sharedMessages = options.sharedMessages;
const locales = Object.keys(sharedMessages);
messages = locales.reduce((messages, locale) => {
const message = messages[locale] || (messages[locale] = {});
assign(message, sharedMessages[locale]);
return messages;
}, (messages || {}));
}
const { __i18n, __root, __injectWithOption } = options;
const datetimeFormats = options.datetimeFormats;
const numberFormats = options.numberFormats;
const flatJson = options.flatJson;
return {
locale,
fallbackLocale,
messages,
flatJson,
datetimeFormats,
numberFormats,
missing,
missingWarn,
fallbackWarn,
fallbackRoot,
fallbackFormat,
modifiers,
pluralRules: pluralizationRules,
postTranslation,
warnHtmlMessage,
escapeParameter,
messageResolver: options.messageResolver,
inheritLocale,
__i18n,
__root,
__injectWithOption
};
}
/**
* create VueI18n interface factory
*
* @internal
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function createVueI18n(options = {}, VueI18nLegacy) {
{
const composer = createComposer(convertComposerOptions(options));
// defines VueI18n
const vueI18n = {
// id
id: composer.id,
// locale
get locale() {
return composer.locale.value;
},
set locale(val) {
composer.locale.value = val;
},
// fallbackLocale
get fallbackLocale() {
return composer.fallbackLocale.value;
},
set fallbackLocale(val) {
composer.fallbackLocale.value = val;
},
// messages
get messages() {
return composer.messages.value;
},
// datetimeFormats
get datetimeFormats() {
return composer.datetimeFormats.value;
},
// numberFormats
get numberFormats() {
return composer.numberFormats.value;
},
// availableLocales
get availableLocales() {
return composer.availableLocales;
},
// formatter
get formatter() {
warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
// dummy
return {
interpolate() {
return [];
}
};
},
set formatter(val) {
warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_FORMATTER));
},
// missing
get missing() {
return composer.getMissingHandler();
},
set missing(handler) {
composer.setMissingHandler(handler);
},
// silentTranslationWarn
get silentTranslationWarn() {
return isBoolean(composer.missingWarn)
? !composer.missingWarn
: composer.missingWarn;
},
set silentTranslationWarn(val) {
composer.missingWarn = isBoolean(val) ? !val : val;
},
// silentFallbackWarn
get silentFallbackWarn() {
return isBoolean(composer.fallbackWarn)
? !composer.fallbackWarn
: composer.fallbackWarn;
},
set silentFallbackWarn(val) {
composer.fallbackWarn = isBoolean(val) ? !val : val;
},
// modifiers
get modifiers() {
return composer.modifiers;
},
// formatFallbackMessages
get formatFallbackMessages() {
return composer.fallbackFormat;
},
set formatFallbackMessages(val) {
composer.fallbackFormat = val;
},
// postTranslation
get postTranslation() {
return composer.getPostTranslationHandler();
},
set postTranslation(handler) {
composer.setPostTranslationHandler(handler);
},
// sync
get sync() {
return composer.inheritLocale;
},
set sync(val) {
composer.inheritLocale = val;
},
// warnInHtmlMessage
get warnHtmlInMessage() {
return composer.warnHtmlMessage ? 'warn' : 'off';
},
set warnHtmlInMessage(val) {
composer.warnHtmlMessage = val !== 'off';
},
// escapeParameterHtml
get escapeParameterHtml() {
return composer.escapeParameter;
},
set escapeParameterHtml(val) {
composer.escapeParameter = val;
},
// preserveDirectiveContent
get preserveDirectiveContent() {
warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
return true;
},
set preserveDirectiveContent(val) {
warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE_DIRECTIVE));
},
// pluralizationRules
get pluralizationRules() {
return composer.pluralRules || {};
},
// for internal
__composer: composer,
// t
t(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
let list = null;
let named = null;
if (!isString(arg1)) {
throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
}
const key = arg1;
if (isString(arg2)) {
options.locale = arg2;
}
else if (isArray(arg2)) {
list = arg2;
}
else if (isPlainObject(arg2)) {
named = arg2;
}
if (isArray(arg3)) {
list = arg3;
}
else if (isPlainObject(arg3)) {
named = arg3;
}
// return composer.t(key, (list || named || {}) as any, options)
return Reflect.apply(composer.t, composer, [
key,
(list || named || {}),
options
]);
},
rt(...args) {
return Reflect.apply(composer.rt, composer, [...args]);
},
// tc
tc(...args) {
const [arg1, arg2, arg3] = args;
const options = { plural: 1 };
let list = null;
let named = null;
if (!isString(arg1)) {
throw createI18nError(I18nErrorCodes.INVALID_ARGUMENT);
}
const key = arg1;
if (isString(arg2)) {
options.locale = arg2;
}
else if (isNumber(arg2)) {
options.plural = arg2;
}
else if (isArray(arg2)) {
list = arg2;
}
else if (isPlainObject(arg2)) {
named = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isArray(arg3)) {
list = arg3;
}
else if (isPlainObject(arg3)) {
named = arg3;
}
// return composer.t(key, (list || named || {}) as any, options)
return Reflect.apply(composer.t, composer, [
key,
(list || named || {}),
options
]);
},
// te
te(key, locale) {
return composer.te(key, locale);
},
// tm
tm(key) {
return composer.tm(key);
},
// getLocaleMessage
getLocaleMessage(locale) {
return composer.getLocaleMessage(locale);
},
// setLocaleMessage
setLocaleMessage(locale, message) {
composer.setLocaleMessage(locale, message);
},
// mergeLocaleMessage
mergeLocaleMessage(locale, message) {
composer.mergeLocaleMessage(locale, message);
},
// d
d(...args) {
return Reflect.apply(composer.d, composer, [...args]);
},
// getDateTimeFormat
getDateTimeFormat(locale) {
return composer.getDateTimeFormat(locale);
},
// setDateTimeFormat
setDateTimeFormat(locale, format) {
composer.setDateTimeFormat(locale, format);
},
// mergeDateTimeFormat
mergeDateTimeFormat(locale, format) {
composer.mergeDateTimeFormat(locale, format);
},
// n
n(...args) {
return Reflect.apply(composer.n, composer, [...args]);
},
// getNumberFormat
getNumberFormat(locale) {
return composer.getNumberFormat(locale);
},
// setNumberFormat
setNumberFormat(locale, format) {
composer.setNumberFormat(locale, format);
},
// mergeNumberFormat
mergeNumberFormat(locale, format) {
composer.mergeNumberFormat(locale, format);
},
// getChoiceIndex
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getChoiceIndex(choice, choicesLength) {
warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_GET_CHOICE_INDEX));
return -1;
},
// for internal
__onComponentInstanceCreated(target) {
const { componentInstanceCreatedListener } = options;
if (componentInstanceCreatedListener) {
componentInstanceCreatedListener(target, vueI18n);
}
}
};
// for vue-devtools timeline event
{
vueI18n.__enableEmitter = (emitter) => {
const __composer = composer;
__composer[EnableEmitter] && __composer[EnableEmitter](emitter);
};
vueI18n.__disableEmitter = () => {
const __composer = composer;
__composer[DisableEmitter] && __composer[DisableEmitter]();
};
}
return vueI18n;
}
}
/* eslint-enable @typescript-eslint/no-explicit-any */
const baseFormatProps = {
tag: {
type: [String, Object]
},
locale: {
type: String
},
scope: {
type: String,
// NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
validator: (val /* ComponetI18nScope */) => val === 'parent' || val === 'global',
default: 'parent' /* ComponetI18nScope */
},
i18n: {
type: Object
}
};
/**
* Translation Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [TranslationProps](component#translationprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Component Interpolation](../guide/advanced/component)
*
* @example
* ```html
* <div id="app">
* <!-- ... -->
* <i18n path="term" tag="label" for="tos">
* <a :href="url" target="_blank">{{ $t('tos') }}</a>
* </i18n>
* <!-- ... -->
* </div>
* ```
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* const messages = {
* en: {
* tos: 'Term of Service',
* term: 'I accept xxx {0}.'
* },
* ja: {
* tos: '利用規約',
* term: '私は xxx の{0}に同意します。'
* }
* }
*
* const i18n = createI18n({
* locale: 'en',
* messages
* })
*
* const app = createApp({
* data: {
* url: '/term'
* }
* }).use(i18n).mount('#app')
* ```
*
* @VueI18nComponent
*/
const Translation = /* #__PURE__*/ defineComponent({
/* eslint-disable */
name: 'i18n-t',
props: assign({
keypath: {
type: String,
required: true
},
plural: {
type: [Number, String],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
validator: (val) => isNumber(val) || !isNaN(val)
}
}, baseFormatProps),
/* eslint-enable */
setup(props, context) {
const { slots, attrs } = context;
// NOTE: avoid https://github.com/microsoft/rushstack/issues/1050
const i18n = props.i18n ||
useI18n({
useScope: props.scope,
__useComponent: true
});
const keys = Object.keys(slots).filter(key => key !== '_');
return () => {
const options = {};
if (props.locale) {
options.locale = props.locale;
}
if (props.plural !== undefined) {
options.plural = isString(props.plural) ? +props.plural : props.plural;
}
const arg = getInterpolateArg(context, keys);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options);
const assignedAttrs = assign({}, attrs);
const tag = isString(props.tag) || isObject(props.tag) ? props.tag : Fragment;
return h(tag, assignedAttrs, children);
};
}
});
function getInterpolateArg({ slots }, keys) {
if (keys.length === 1 && keys[0] === 'default') {
// default slot only
return slots.default ? slots.default() : [];
}
else {
// named slots
return keys.reduce((arg, key) => {
const slot = slots[key];
if (slot) {
arg[key] = slot();
}
return arg;
}, {});
}
}
function renderFormatter(props, context, slotKeys, partFormatter) {
const { slots, attrs } = context;
return () => {
const options = { part: true };
let overrides = {};
if (props.locale) {
options.locale = props.locale;
}
if (isString(props.format)) {
options.key = props.format;
}
else if (isObject(props.format)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (isString(props.format.key)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options.key = props.format.key;
}
// Filter out number format options only
overrides = Object.keys(props.format).reduce((options, prop) => {
return slotKeys.includes(prop)
? assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
: options;
}, {});
}
const parts = partFormatter(...[props.value, options, overrides]);
let children = [options.key];
if (isArray(parts)) {
children = parts.map((part, index) => {
const slot = slots[part.type];
return slot
? slot({ [part.type]: part.value, index, parts })
: [part.value];
});
}
else if (isString(parts)) {
children = [parts];
}
const assignedAttrs = assign({}, attrs);
const tag = isString(props.tag) || isObject(props.tag) ? props.tag : Fragment;
return h(tag, assignedAttrs, children);
};
}
const NUMBER_FORMAT_KEYS = [
'localeMatcher',
'style',
'unit',
'unitDisplay',
'currency',
'currencyDisplay',
'useGrouping',
'numberingSystem',
'minimumIntegerDigits',
'minimumFractionDigits',
'maximumFractionDigits',
'minimumSignificantDigits',
'maximumSignificantDigits',
'notation',
'formatMatcher'
];
/**
* Number Format Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [FormattableProps](component#formattableprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Custom Formatting](../guide/essentials/number#custom-formatting)
*
* @VueI18nDanger
* Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts)
*
* If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
*
* @VueI18nComponent
*/
const NumberFormat = /* #__PURE__*/ defineComponent({
/* eslint-disable */
name: 'i18n-n',
props: assign({
value: {
type: Number,
required: true
},
format: {
type: [String, Object]
}
}, baseFormatProps),
/* eslint-enable */
setup(props, context) {
const i18n = props.i18n ||
useI18n({ useScope: 'parent', __useComponent: true });
return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
i18n[NumberPartsSymbol](...args));
}
});
const DATETIME_FORMAT_KEYS = [
'dateStyle',
'timeStyle',
'fractionalSecondDigits',
'calendar',
'dayPeriod',
'numberingSystem',
'localeMatcher',
'timeZone',
'hour12',
'hourCycle',
'formatMatcher',
'weekday',
'era',
'year',
'month',
'day',
'hour',
'minute',
'second',
'timeZoneName'
];
/**
* Datetime Format Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [FormattableProps](component#formattableprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Custom Formatting](../guide/essentials/datetime#custom-formatting)
*
* @VueI18nDanger
* Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)
*
* If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
*
* @VueI18nComponent
*/
const DatetimeFormat = /* #__PURE__*/ defineComponent({
/* eslint-disable */
name: 'i18n-d',
props: assign({
value: {
type: [Number, Date],
required: true
},
format: {
type: [String, Object]
}
}, baseFormatProps),
/* eslint-enable */
setup(props, context) {
const i18n = props.i18n ||
useI18n({ useScope: 'parent', __useComponent: true });
return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
i18n[DatetimePartsSymbol](...args));
}
});
function getComposer$2(i18n, instance) {
const i18nInternal = i18n;
if (i18n.mode === 'composition') {
return (i18nInternal.__getInstance(instance) || i18n.global);
}
else {
const vueI18n = i18nInternal.__getInstance(instance);
return vueI18n != null
? vueI18n.__composer
: i18n.global.__composer;
}
}
function vTDirective(i18n) {
const bind = (el, { instance, value, modifiers }) => {
/* istanbul ignore if */
if (!instance || !instance.$) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
}
const composer = getComposer$2(i18n, instance.$);
if (modifiers.preserve) {
warn(getWarnMessage(I18nWarnCodes.NOT_SUPPORTED_PRESERVE));
}
const parsedValue = parseValue(value);
// el.textContent = composer.t(...makeParams(parsedValue))
el.textContent = Reflect.apply(composer.t, composer, [
...makeParams(parsedValue)
]);
};
return {
beforeMount: bind,
beforeUpdate: bind
};
}
function parseValue(value) {
if (isString(value)) {
return { path: value };
}
else if (isPlainObject(value)) {
if (!('path' in value)) {
throw createI18nError(I18nErrorCodes.REQUIRED_VALUE, 'path');
}
return value;
}
else {
throw createI18nError(I18nErrorCodes.INVALID_VALUE);
}
}
function makeParams(value) {
const { path, locale, args, choice, plural } = value;
const options = {};
const named = args || {};
if (isString(locale)) {
options.locale = locale;
}
if (isNumber(choice)) {
options.plural = choice;
}
if (isNumber(plural)) {
options.plural = plural;
}
return [path, named, options];
}
function apply(app, i18n, ...options) {
const pluginOptions = isPlainObject(options[0])
? options[0]
: {};
const useI18nComponentName = !!pluginOptions.useI18nComponentName;
const globalInstall = isBoolean(pluginOptions.globalInstall)
? pluginOptions.globalInstall
: true;
if (globalInstall && useI18nComponentName) {
warn(getWarnMessage(I18nWarnCodes.COMPONENT_NAME_LEGACY_COMPATIBLE, {
name: Translation.name
}));
}
if (globalInstall) {
// install components
app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation);
app.component(NumberFormat.name, NumberFormat);
app.component(DatetimeFormat.name, DatetimeFormat);
}
// install directive
{
app.directive('t', vTDirective(i18n));
}
}
var global$1 = (typeof global !== "undefined" ? global :
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window : {});
function getDevtoolsGlobalHook() {
return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
}
function getTarget() {
// @ts-ignore
return (typeof navigator !== 'undefined' && typeof window !== 'undefined')
? window
: typeof global$1 !== 'undefined'
? global$1
: {};
}
const isProxyAvailable = typeof Proxy === 'function';
const HOOK_SETUP = 'devtools-plugin:setup';
const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set';
class ApiProxy {
constructor(plugin, hook) {
this.target = null;
this.targetQueue = [];
this.onQueue = [];
this.plugin = plugin;
this.hook = hook;
const defaultSettings = {};
if (plugin.settings) {
for (const id in plugin.settings) {
const item = plugin.settings[id];
defaultSettings[id] = item.defaultValue;
}
}
const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
let currentSettings = { ...defaultSettings };
try {
const raw = localStorage.getItem(localSettingsSaveId);
const data = JSON.parse(raw);
Object.assign(currentSettings, data);
}
catch (e) {
// noop
}
this.fallbacks = {
getSettings() {
return currentSettings;
},
setSettings(value) {
try {
localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
}
catch (e) {
// noop
}
currentSettings = value;
}
};
hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
if (pluginId === this.plugin.id) {
this.fallbacks.setSettings(value);
}
});
this.proxiedOn = new Proxy({}, {
get: (_target, prop) => {
if (this.target) {
return this.target.on[prop];
}
else {
return (...args) => {
this.onQueue.push({
method: prop,
args
});
};
}
}
});
this.proxiedTarget = new Proxy({}, {
get: (_target, prop) => {
if (this.target) {
return this.target[prop];
}
else if (prop === 'on') {
return this.proxiedOn;
}
else if (Object.keys(this.fallbacks).includes(prop)) {
return (...args) => {
this.targetQueue.push({
method: prop,
args,
resolve: () => { }
});
return this.fallbacks[prop](...args);
};
}
else {
return (...args) => {
return new Promise(resolve => {
this.targetQueue.push({
method: prop,
args,
resolve
});
});
};
}
}
});
}
async setRealTarget(target) {
this.target = target;
for (const item of this.onQueue) {
this.target.on[item.method](...item.args);
}
for (const item of this.targetQueue) {
item.resolve(await this.target[item.method](...item.args));
}
}
}
function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
const target = getTarget();
const hook = getDevtoolsGlobalHook();
const enableProxy = isProxyAvailable && pluginDescriptor.enableEarlyProxy;
if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
}
else {
const proxy = enableProxy ? new ApiProxy(pluginDescriptor, hook) : null;
const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
list.push({
pluginDescriptor,
setupFn,
proxy
});
if (proxy)
setupFn(proxy.proxiedTarget);
}
}
const VueDevToolsLabels = {
["vue-devtools-plugin-vue-i18n" /* PLUGIN */]: 'Vue I18n devtools',
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'I18n Resources',
["vue-i18n-timeline" /* TIMELINE */]: 'Vue I18n'
};
const VueDevToolsPlaceholders = {
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'Search for scopes ...'
};
const VueDevToolsTimelineColors = {
["vue-i18n-timeline" /* TIMELINE */]: 0xffcd19
};
const VUE_I18N_COMPONENT_TYPES = 'vue-i18n: composer properties';
let devtoolsApi;
async function enableDevTools(app, i18n) {
return new Promise((resolve, reject) => {
try {
setupDevtoolsPlugin({
id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */,
label: VueDevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */],
packageName: 'vue-i18n',
homepage: 'https://vue-i18n.intlify.dev',
logo: 'https://vue-i18n.intlify.dev/vue-i18n-devtools-logo.png',
componentStateTypes: [VUE_I18N_COMPONENT_TYPES],
app
}, api => {
devtoolsApi = api;
api.on.visitComponentTree(({ componentInstance, treeNode }) => {
updateComponentTreeTags(componentInstance, treeNode, i18n);
});
api.on.inspectComponent(({ componentInstance, instanceData }) => {
if (componentInstance.vnode.el &&
componentInstance.vnode.el.__VUE_I18N__ &&
instanceData) {
if (i18n.mode === 'legacy') {
// ignore global scope on legacy mode
if (componentInstance.vnode.el.__VUE_I18N__ !==
i18n.global.__composer) {
inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
}
}
else {
inspectComposer(instanceData, componentInstance.vnode.el.__VUE_I18N__);
}
}
});
api.addInspector({
id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */,
label: VueDevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */],
icon: 'language',
treeFilterPlaceholder: VueDevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]
});
api.on.getInspectorTree(payload => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
registerScope(payload, i18n);
}
});
const roots = new Map();
api.on.getInspectorState(async (payload) => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
api.unhighlightElement();
inspectScope(payload, i18n);
if (payload.nodeId === 'global') {
if (!roots.has(payload.app)) {
const [root] = await api.getComponentInstances(payload.app);
roots.set(payload.app, root);
}
api.highlightElement(roots.get(payload.app));
}
else {
const instance = getComponentInstance(payload.nodeId, i18n);
instance && api.highlightElement(instance);
}
}
});
api.on.editInspectorState(payload => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
editScope(payload, i18n);
}
});
api.addTimelineLayer({
id: "vue-i18n-timeline" /* TIMELINE */,
label: VueDevToolsLabels["vue-i18n-timeline" /* TIMELINE */],
color: VueDevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */]
});
resolve(true);
});
}
catch (e) {
console.error(e);
reject(false);
}
});
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getI18nScopeLable(instance) {
return (instance.type.name ||
instance.type.displayName ||
instance.type.__file ||
'Anonymous');
}
function updateComponentTreeTags(instance, // eslint-disable-line @typescript-eslint/no-explicit-any
treeNode, i18n) {
// prettier-ignore
const global = i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer;
if (instance && instance.vnode.el && instance.vnode.el.__VUE_I18N__) {
// add custom tags local scope only
if (instance.vnode.el.__VUE_I18N__ !== global) {
const tag = {
label: `i18n (${getI18nScopeLable(instance)} Scope)`,
textColor: 0x000000,
backgroundColor: 0xffcd19
};
treeNode.tags.push(tag);
}
}
}
function inspectComposer(instanceData, composer) {
const type = VUE_I18N_COMPONENT_TYPES;
instanceData.state.push({
type,
key: 'locale',
editable: true,
value: composer.locale.value
});
instanceData.state.push({
type,
key: 'availableLocales',
editable: false,
value: composer.availableLocales
});
instanceData.state.push({
type,
key: 'fallbackLocale',
editable: true,
value: composer.fallbackLocale.value
});
instanceData.state.push({
type,
key: 'inheritLocale',
editable: true,
value: composer.inheritLocale
});
instanceData.state.push({
type,
key: 'messages',
editable: false,
value: getLocaleMessageValue(composer.messages.value)
});
{
instanceData.state.push({
type,
key: 'datetimeFormats',
editable: false,
value: composer.datetimeFormats.value
});
instanceData.state.push({
type,
key: 'numberFormats',
editable: false,
value: composer.numberFormats.value
});
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getLocaleMessageValue(messages) {
const value = {};
Object.keys(messages).forEach((key) => {
const v = messages[key];
if (isFunction(v) && 'source' in v) {
value[key] = getMessageFunctionDetails(v);
}
else if (isObject(v)) {
value[key] = getLocaleMessageValue(v);
}
else {
value[key] = v;
}
});
return value;
}
const ESC = {
'<': '<',
'>': '>',
'"': '"',
'&': '&'
};
function escape(s) {
return s.replace(/[<>"&]/g, escapeChar);
}
function escapeChar(a) {
return ESC[a] || a;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getMessageFunctionDetails(func) {
const argString = func.source ? `("${escape(func.source)}")` : `(?)`;
return {
_custom: {
type: 'function',
display: `<span>ƒ</span> ${argString}`
}
};
}
function registerScope(payload, i18n) {
payload.rootNodes.push({
id: 'global',
label: 'Global Scope'
});
// prettier-ignore
const global = i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer;
for (const [keyInstance, instance] of i18n.__instances) {
// prettier-ignore
const composer = i18n.mode === 'composition'
? instance
: instance.__composer;
if (global === composer) {
continue;
}
payload.rootNodes.push({
id: composer.id.toString(),
label: `${getI18nScopeLable(keyInstance)} Scope`
});
}
}
function getComponentInstance(nodeId, i18n) {
let instance = null;
if (nodeId !== 'global') {
for (const [component, composer] of i18n.__instances.entries()) {
if (composer.id.toString() === nodeId) {
instance = component;
break;
}
}
}
return instance;
}
function getComposer$1(nodeId, i18n) {
if (nodeId === 'global') {
return i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer;
}
else {
const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === nodeId);
if (instance) {
return i18n.mode === 'composition'
? instance
: instance.__composer;
}
else {
return null;
}
}
}
function inspectScope(payload, i18n
// eslint-disable-next-line @typescript-eslint/no-explicit-any
) {
const composer = getComposer$1(payload.nodeId, i18n);
if (composer) {
// TODO:
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload.state = makeScopeInspectState(composer);
}
return null;
}
function makeScopeInspectState(composer) {
const state = {};
const localeType = 'Locale related info';
const localeStates = [
{
type: localeType,
key: 'locale',
editable: true,
value: composer.locale.value
},
{
type: localeType,
key: 'fallbackLocale',
editable: true,
value: composer.fallbackLocale.value
},
{
type: localeType,
key: 'availableLocales',
editable: false,
value: composer.availableLocales
},
{
type: localeType,
key: 'inheritLocale',
editable: true,
value: composer.inheritLocale
}
];
state[localeType] = localeStates;
const localeMessagesType = 'Locale messages info';
const localeMessagesStates = [
{
type: localeMessagesType,
key: 'messages',
editable: false,
value: getLocaleMessageValue(composer.messages.value)
}
];
state[localeMessagesType] = localeMessagesStates;
{
const datetimeFormatsType = 'Datetime formats info';
const datetimeFormatsStates = [
{
type: datetimeFormatsType,
key: 'datetimeFormats',
editable: false,
value: composer.datetimeFormats.value
}
];
state[datetimeFormatsType] = datetimeFormatsStates;
const numberFormatsType = 'Datetime formats info';
const numberFormatsStates = [
{
type: numberFormatsType,
key: 'numberFormats',
editable: false,
value: composer.numberFormats.value
}
];
state[numberFormatsType] = numberFormatsStates;
}
return state;
}
function addTimelineEvent(event, payload) {
if (devtoolsApi) {
let groupId;
if (payload && 'groupId' in payload) {
groupId = payload.groupId;
delete payload.groupId;
}
devtoolsApi.addTimelineEvent({
layerId: "vue-i18n-timeline" /* TIMELINE */,
event: {
title: event,
groupId,
time: Date.now(),
meta: {},
data: payload || {},
logType: event === "compile-error" /* COMPILE_ERROR */
? 'error'
: event === "fallback" /* FALBACK */ ||
event === "missing" /* MISSING */
? 'warning'
: 'default'
}
});
}
}
function editScope(payload, i18n) {
const composer = getComposer$1(payload.nodeId, i18n);
if (composer) {
const [field] = payload.path;
if (field === 'locale' && isString(payload.state.value)) {
composer.locale.value = payload.state.value;
}
else if (field === 'fallbackLocale' &&
(isString(payload.state.value) ||
isArray(payload.state.value) ||
isObject(payload.state.value))) {
composer.fallbackLocale.value = payload.state.value;
}
else if (field === 'inheritLocale' && isBoolean(payload.state.value)) {
composer.inheritLocale = payload.state.value;
}
}
}
/**
* Supports compatibility for legacy vue-i18n APIs
* This mixin is used when we use vue-i18n@v9.x or later
*/
function defineMixin(vuei18n, composer, i18n) {
return {
beforeCreate() {
const instance = getCurrentInstance();
/* istanbul ignore if */
if (!instance) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
}
const options = this.$options;
if (options.i18n) {
const optionsI18n = options.i18n;
if (options.__i18n) {
optionsI18n.__i18n = options.__i18n;
}
optionsI18n.__root = composer;
if (this === this.$root) {
this.$i18n = mergeToRoot(vuei18n, optionsI18n);
}
else {
optionsI18n.__injectWithOption = true;
this.$i18n = createVueI18n(optionsI18n);
}
}
else if (options.__i18n) {
if (this === this.$root) {
this.$i18n = mergeToRoot(vuei18n, options);
}
else {
this.$i18n = createVueI18n({
__i18n: options.__i18n,
__injectWithOption: true,
__root: composer
});
}
}
else {
// set global
this.$i18n = vuei18n;
}
vuei18n.__onComponentInstanceCreated(this.$i18n);
i18n.__setInstance(instance, this.$i18n);
// defines vue-i18n legacy APIs
this.$t = (...args) => this.$i18n.t(...args);
this.$rt = (...args) => this.$i18n.rt(...args);
this.$tc = (...args) => this.$i18n.tc(...args);
this.$te = (key, locale) => this.$i18n.te(key, locale);
this.$d = (...args) => this.$i18n.d(...args);
this.$n = (...args) => this.$i18n.n(...args);
this.$tm = (key) => this.$i18n.tm(key);
},
mounted() {
/* istanbul ignore if */
{
this.$el.__VUE_I18N__ = this.$i18n.__composer;
const emitter = (this.__v_emitter =
createEmitter());
const _vueI18n = this.$i18n;
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
emitter.on('*', addTimelineEvent);
}
},
unmounted() {
const instance = getCurrentInstance();
/* istanbul ignore if */
if (!instance) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
}
nextTick(() => {
/* istanbul ignore if */
{
if (this.__v_emitter) {
this.__v_emitter.off('*', addTimelineEvent);
delete this.__v_emitter;
}
const _vueI18n = this.$i18n;
_vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
delete this.$el.__VUE_I18N__;
}
delete this.$t;
delete this.$rt;
delete this.$tc;
delete this.$te;
delete this.$d;
delete this.$n;
delete this.$tm;
i18n.__deleteInstance(instance);
delete this.$i18n;
});
}
};
}
function mergeToRoot(root, options) {
root.locale = options.locale || root.locale;
root.fallbackLocale = options.fallbackLocale || root.fallbackLocale;
root.missing = options.missing || root.missing;
root.silentTranslationWarn =
options.silentTranslationWarn || root.silentFallbackWarn;
root.silentFallbackWarn =
options.silentFallbackWarn || root.silentFallbackWarn;
root.formatFallbackMessages =
options.formatFallbackMessages || root.formatFallbackMessages;
root.postTranslation = options.postTranslation || root.postTranslation;
root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage;
root.escapeParameterHtml =
options.escapeParameterHtml || root.escapeParameterHtml;
root.sync = options.sync || root.sync;
root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules);
const messages = getLocaleMessages(root.locale, {
messages: options.messages,
__i18n: options.__i18n
});
Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale]));
if (options.datetimeFormats) {
Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale]));
}
if (options.numberFormats) {
Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale]));
}
return root;
}
/**
* Injection key for {@link useI18n}
*
* @remarks
* The global injection key for I18n instances with `useI18n`. this injection key is used in Web Components.
* Specify the i18n instance created by {@link createI18n} together with `provide` function.
*
* @VueI18nGeneral
*/
const I18nInjectionKey =
/* #__PURE__*/ makeSymbol('global-vue-i18n');
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
function createI18n(options = {}, VueI18nLegacy) {
// prettier-ignore
const __legacyMode = isBoolean(options.legacy)
? options.legacy
: true;
const __globalInjection = !!options.globalInjection;
const __instances = new Map();
const __global = createGlobal(options, __legacyMode);
const symbol = makeSymbol('vue-i18n' );
function __getInstance(component) {
return __instances.get(component) || null;
}
function __setInstance(component, instance) {
__instances.set(component, instance);
}
function __deleteInstance(component) {
__instances.delete(component);
}
{
const i18n = {
// mode
get mode() {
return __legacyMode
? 'legacy'
: 'composition';
},
// install plugin
async install(app, ...options) {
{
app.__VUE_I18N__ = i18n;
}
// setup global provider
{
app.__VUE_I18N_SYMBOL__ = symbol;
app.provide(app.__VUE_I18N_SYMBOL__, i18n);
}
// global method and properties injection for Composition API
if (!__legacyMode && __globalInjection) {
injectGlobalFields(app, i18n.global);
}
// install built-in components and directive
{
apply(app, i18n, ...options);
}
// setup mixin for Legacy API
if (__legacyMode) {
app.mixin(defineMixin(__global, __global.__composer, i18n));
}
// setup vue-devtools plugin
{
const ret = await enableDevTools(app, i18n);
if (!ret) {
throw createI18nError(I18nErrorCodes.CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN);
}
const emitter = createEmitter();
if (__legacyMode) {
const _vueI18n = __global;
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
}
else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = __global;
_composer[EnableEmitter] && _composer[EnableEmitter](emitter);
}
emitter.on('*', addTimelineEvent);
}
},
// global accessor
get global() {
return __global;
},
// @internal
__instances,
// @internal
__getInstance,
// @internal
__setInstance,
// @internal
__deleteInstance
};
return i18n;
}
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function useI18n(options = {}) {
const instance = getCurrentInstance();
if (instance == null) {
throw createI18nError(I18nErrorCodes.MUST_BE_CALL_SETUP_TOP);
}
if (!instance.isCE &&
instance.appContext.app != null &&
!instance.appContext.app.__VUE_I18N_SYMBOL__) {
throw createI18nError(I18nErrorCodes.NOT_INSLALLED);
}
const i18n = getI18nInstance(instance);
const global = getGlobalComposer(i18n);
const componentOptions = getComponentOptions(instance);
const scope = getScope(options, componentOptions);
if (scope === 'global') {
adjustI18nResources(global, options, componentOptions);
return global;
}
if (scope === 'parent') {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let composer = getComposer(i18n, instance, options.__useComponent);
if (composer == null) {
{
warn(getWarnMessage(I18nWarnCodes.NOT_FOUND_PARENT_SCOPE));
}
composer = global;
}
return composer;
}
// scope 'local' case
if (i18n.mode === 'legacy') {
throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_IN_LEGACY_MODE);
}
const i18nInternal = i18n;
let composer = i18nInternal.__getInstance(instance);
if (composer == null) {
const composerOptions = assign({}, options);
if ('__i18n' in componentOptions) {
composerOptions.__i18n = componentOptions.__i18n;
}
if (global) {
composerOptions.__root = global;
}
composer = createComposer(composerOptions);
setupLifeCycle(i18nInternal, instance, composer);
i18nInternal.__setInstance(instance, composer);
}
return composer;
}
function createGlobal(options, legacyMode, VueI18nLegacy // eslint-disable-line @typescript-eslint/no-explicit-any
) {
{
return legacyMode
? createVueI18n(options)
: createComposer(options);
}
}
function getI18nInstance(instance) {
{
const i18n = inject(!instance.isCE
? instance.appContext.app.__VUE_I18N_SYMBOL__
: I18nInjectionKey);
/* istanbul ignore if */
if (!i18n) {
throw createI18nError(!instance.isCE
? I18nErrorCodes.UNEXPECTED_ERROR
: I18nErrorCodes.NOT_INSLALLED_WITH_PROVIDE);
}
return i18n;
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getScope(options, componentOptions) {
// prettier-ignore
return isEmptyObject(options)
? ('__i18n' in componentOptions)
? 'local'
: 'global'
: !options.useScope
? 'local'
: options.useScope;
}
function getGlobalComposer(i18n) {
// prettier-ignore
return i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer
;
}
function adjustI18nResources(global, options, componentOptions // eslint-disable-line @typescript-eslint/no-explicit-any
) {
let messages = isObject(options.messages) ? options.messages : {};
if ('__i18nGlobal' in componentOptions) {
messages = getLocaleMessages(global.locale.value, {
messages,
__i18n: componentOptions.__i18nGlobal
});
}
// merge locale messages
const locales = Object.keys(messages);
if (locales.length) {
locales.forEach(locale => {
global.mergeLocaleMessage(locale, messages[locale]);
});
}
{
// merge datetime formats
if (isObject(options.datetimeFormats)) {
const locales = Object.keys(options.datetimeFormats);
if (locales.length) {
locales.forEach(locale => {
global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
});
}
}
// merge number formats
if (isObject(options.numberFormats)) {
const locales = Object.keys(options.numberFormats);
if (locales.length) {
locales.forEach(locale => {
global.mergeNumberFormat(locale, options.numberFormats[locale]);
});
}
}
}
}
function getComposer(i18n, target, useComponent = false) {
let composer = null;
const root = target.root;
let current = target.parent;
while (current != null) {
const i18nInternal = i18n;
if (i18n.mode === 'composition') {
composer = i18nInternal.__getInstance(current);
}
else {
{
const vueI18n = i18nInternal.__getInstance(current);
if (vueI18n != null) {
composer = vueI18n
.__composer;
if (useComponent &&
composer &&
!composer[InejctWithOption] // eslint-disable-line @typescript-eslint/no-explicit-any
) {
composer = null;
}
}
}
}
if (composer != null) {
break;
}
if (root === current) {
break;
}
current = current.parent;
}
return composer;
}
function setupLifeCycle(i18n, target, composer) {
let emitter = null;
{
onMounted(() => {
// inject composer instance to DOM for intlify-devtools
if (target.vnode.el) {
target.vnode.el.__VUE_I18N__ = composer;
emitter = createEmitter();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer;
_composer[EnableEmitter] && _composer[EnableEmitter](emitter);
emitter.on('*', addTimelineEvent);
}
}, target);
onUnmounted(() => {
// remove composer instance from DOM for intlify-devtools
if (target.vnode.el &&
target.vnode.el.__VUE_I18N__) {
emitter && emitter.off('*', addTimelineEvent);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer;
_composer[DisableEmitter] && _composer[DisableEmitter]();
delete target.vnode.el.__VUE_I18N__;
}
i18n.__deleteInstance(target);
}, target);
}
}
const globalExportProps = [
'locale',
'fallbackLocale',
'availableLocales'
];
const globalExportMethods = ['t', 'rt', 'd', 'n', 'tm'] ;
function injectGlobalFields(app, composer) {
const i18n = Object.create(null);
globalExportProps.forEach(prop => {
const desc = Object.getOwnPropertyDescriptor(composer, prop);
if (!desc) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
}
const wrap = isRef(desc.value) // check computed props
? {
get() {
return desc.value.value;
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
set(val) {
desc.value.value = val;
}
}
: {
get() {
return desc.get && desc.get();
}
};
Object.defineProperty(i18n, prop, wrap);
});
app.config.globalProperties.$i18n = i18n;
globalExportMethods.forEach(method => {
const desc = Object.getOwnPropertyDescriptor(composer, method);
if (!desc || !desc.value) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR);
}
Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
});
}
// register message compiler at vue-i18n
registerMessageCompiler(compileToFunction);
// register message resolver at vue-i18n
registerMessageResolver(resolveValue);
// register fallback locale at vue-i18n
registerLocaleFallbacker(fallbackWithLocaleChain);
// NOTE: experimental !!
{
const target = getGlobalThis();
target.__INTLIFY__ = true;
setDevToolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
}
{
initDev();
}
export { DatetimeFormat, I18nInjectionKey, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective };
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("zoid", [], factory);
else if(typeof exports === 'object')
exports["zoid"] = factory();
else
root["zoid"] = factory();
})((typeof self !== 'undefined' ? self : this), function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
// CONCATENATED MODULE: ./node_modules/belter/src/device.js
function getUserAgent() {
return window.navigator.mockUserAgent || window.navigator.userAgent;
}
function isDevice(userAgent) {
if (userAgent === void 0) {
userAgent = getUserAgent();
}
if (userAgent.match(/Android|webOS|iPhone|iPad|iPod|bada|Symbian|Palm|CriOS|BlackBerry|IEMobile|WindowsMobile|Opera Mini/i)) {
return true;
}
return false;
}
function isWebView() {
var userAgent = getUserAgent();
return /(iPhone|iPod|iPad|Macintosh).*AppleWebKit(?!.*Safari)/i.test(userAgent) || /\bwv\b/.test(userAgent) || /Android.*Version\/(\d)\.(\d)/i.test(userAgent);
}
function isStandAlone() {
return window.navigator.standalone === true || window.matchMedia('(display-mode: standalone)').matches;
}
function isFacebookWebView(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
return ua.indexOf('FBAN') !== -1 || ua.indexOf('FBAV') !== -1;
}
function isFirefoxIOS(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
return /FxiOS/i.test(ua);
}
function isEdgeIOS(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
return /EdgiOS/i.test(ua);
}
function isOperaMini(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
return ua.indexOf('Opera Mini') > -1;
}
function isAndroid(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
return /Android/.test(ua);
}
function isIos(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
return /iPhone|iPod|iPad/.test(ua);
}
function isGoogleSearchApp(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
return /\bGSA\b/.test(ua);
}
function isQQBrowser(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
return /QQBrowser/.test(ua);
}
function isIosWebview(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
if (isIos(ua)) {
if (isGoogleSearchApp(ua)) {
return true;
}
return /.+AppleWebKit(?!.*Safari)/.test(ua);
}
return false;
}
function isAndroidWebview(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
if (isAndroid(ua)) {
return /Version\/[\d.]+/.test(ua) && !isOperaMini(ua);
}
return false;
}
function device_isIE() {
if (window.document.documentMode) {
return true;
}
return Boolean(window.navigator && window.navigator.userAgent && /Edge|MSIE|rv:11/i.test(window.navigator.userAgent));
}
function isIECompHeader() {
var mHttp = window.document.querySelector('meta[http-equiv="X-UA-Compatible"]');
var mContent = window.document.querySelector('meta[content="IE=edge"]');
if (mHttp && mContent) {
return true;
}
return false;
}
function isElectron() {
if (typeof process !== 'undefined' && process.versions && process.versions.electron) {
return true;
}
return false;
}
function isIEIntranet() {
// This status check only works for older versions of IE with document.documentMode set
if (window.document.documentMode) {
try {
var status = window.status;
window.status = 'testIntranetMode';
if (window.status === 'testIntranetMode') {
window.status = status;
return true;
}
return false;
} catch (err) {
return false;
}
}
return false;
}
function isMacOsCna() {
var userAgent = getUserAgent();
return /Macintosh.*AppleWebKit(?!.*Safari)/i.test(userAgent);
}
function supportsPopups(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
return !(isIosWebview(ua) || isAndroidWebview(ua) || isOperaMini(ua) || isFirefoxIOS(ua) || isEdgeIOS(ua) || isFacebookWebView(ua) || isQQBrowser(ua) || isElectron() || isMacOsCna() || isStandAlone());
}
function isChrome(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
return /Chrome|Chromium|CriOS/.test(ua);
}
function isSafari(ua) {
if (ua === void 0) {
ua = getUserAgent();
}
return /Safari/.test(ua) && !isChrome(ua);
}
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
// CONCATENATED MODULE: ./node_modules/zalgo-promise/src/utils.js
function utils_isPromise(item) {
try {
if (!item) {
return false;
}
if (typeof Promise !== 'undefined' && item instanceof Promise) {
return true;
}
if (typeof window !== 'undefined' && typeof window.Window === 'function' && item instanceof window.Window) {
return false;
}
if (typeof window !== 'undefined' && typeof window.constructor === 'function' && item instanceof window.constructor) {
return false;
}
var _toString = {}.toString;
if (_toString) {
var name = _toString.call(item);
if (name === '[object Window]' || name === '[object global]' || name === '[object DOMWindow]') {
return false;
}
}
if (typeof item.then === 'function') {
return true;
}
} catch (err) {
return false;
}
return false;
}
// CONCATENATED MODULE: ./node_modules/zalgo-promise/src/exceptions.js
var dispatchedErrors = [];
var possiblyUnhandledPromiseHandlers = [];
function dispatchPossiblyUnhandledError(err, promise) {
if (dispatchedErrors.indexOf(err) !== -1) {
return;
}
dispatchedErrors.push(err);
setTimeout(function () {
if (false) {}
throw err;
}, 1);
for (var j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) {
// $FlowFixMe
possiblyUnhandledPromiseHandlers[j](err, promise);
}
}
function exceptions_onPossiblyUnhandledException(handler) {
possiblyUnhandledPromiseHandlers.push(handler);
return {
cancel: function cancel() {
possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1);
}
};
}
// CONCATENATED MODULE: ./node_modules/zalgo-promise/src/flush.js
var activeCount = 0;
var flushPromise;
function flushActive() {
if (!activeCount && flushPromise) {
var promise = flushPromise;
flushPromise = null;
promise.resolve();
}
}
function startActive() {
activeCount += 1;
}
function endActive() {
activeCount -= 1;
flushActive();
}
function awaitActive(Zalgo) {
// eslint-disable-line no-undef
var promise = flushPromise = flushPromise || new Zalgo();
flushActive();
return promise;
}
// CONCATENATED MODULE: ./node_modules/zalgo-promise/src/promise.js
var promise_ZalgoPromise =
/*#__PURE__*/
function () {
function ZalgoPromise(handler) {
var _this = this;
this.resolved = void 0;
this.rejected = void 0;
this.errorHandled = void 0;
this.value = void 0;
this.error = void 0;
this.handlers = void 0;
this.dispatching = void 0;
this.stack = void 0;
this.resolved = false;
this.rejected = false;
this.errorHandled = false;
this.handlers = [];
if (handler) {
var _result;
var _error;
var resolved = false;
var rejected = false;
var isAsync = false;
startActive();
try {
handler(function (res) {
if (isAsync) {
_this.resolve(res);
} else {
resolved = true;
_result = res;
}
}, function (err) {
if (isAsync) {
_this.reject(err);
} else {
rejected = true;
_error = err;
}
});
} catch (err) {
endActive();
this.reject(err);
return;
}
endActive();
isAsync = true;
if (resolved) {
// $FlowFixMe
this.resolve(_result);
} else if (rejected) {
this.reject(_error);
}
}
if (false) {}
}
var _proto = ZalgoPromise.prototype;
_proto.resolve = function resolve(result) {
if (this.resolved || this.rejected) {
return this;
}
if (utils_isPromise(result)) {
throw new Error('Can not resolve promise with another promise');
}
this.resolved = true;
this.value = result;
this.dispatch();
return this;
};
_proto.reject = function reject(error) {
var _this2 = this;
if (this.resolved || this.rejected) {
return this;
}
if (utils_isPromise(error)) {
throw new Error('Can not reject promise with another promise');
}
if (!error) {
// $FlowFixMe
var _err = error && typeof error.toString === 'function' ? error.toString() : Object.prototype.toString.call(error);
error = new Error("Expected reject to be called with Error, got " + _err);
}
this.rejected = true;
this.error = error;
if (!this.errorHandled) {
setTimeout(function () {
if (!_this2.errorHandled) {
dispatchPossiblyUnhandledError(error, _this2);
}
}, 1);
}
this.dispatch();
return this;
};
_proto.asyncReject = function asyncReject(error) {
this.errorHandled = true;
this.reject(error);
return this;
};
_proto.dispatch = function dispatch() {
var dispatching = this.dispatching,
resolved = this.resolved,
rejected = this.rejected,
handlers = this.handlers;
if (dispatching) {
return;
}
if (!resolved && !rejected) {
return;
}
this.dispatching = true;
startActive();
var chain = function chain(firstPromise, secondPromise) {
return firstPromise.then(function (res) {
secondPromise.resolve(res);
}, function (err) {
secondPromise.reject(err);
});
};
for (var i = 0; i < handlers.length; i++) {
var _handlers$i = handlers[i],
onSuccess = _handlers$i.onSuccess,
onError = _handlers$i.onError,
promise = _handlers$i.promise;
var _result2 = void 0;
if (resolved) {
try {
_result2 = onSuccess ? onSuccess(this.value) : this.value;
} catch (err) {
promise.reject(err);
continue;
}
} else if (rejected) {
if (!onError) {
promise.reject(this.error);
continue;
}
try {
_result2 = onError(this.error);
} catch (err) {
promise.reject(err);
continue;
}
}
if (_result2 instanceof ZalgoPromise && (_result2.resolved || _result2.rejected)) {
if (_result2.resolved) {
promise.resolve(_result2.value);
} else {
promise.reject(_result2.error);
}
_result2.errorHandled = true;
} else if (utils_isPromise(_result2)) {
if (_result2 instanceof ZalgoPromise && (_result2.resolved || _result2.rejected)) {
if (_result2.resolved) {
promise.resolve(_result2.value);
} else {
promise.reject(_result2.error);
}
} else {
// $FlowFixMe
chain(_result2, promise);
}
} else {
promise.resolve(_result2);
}
}
handlers.length = 0;
this.dispatching = false;
endActive();
};
_proto.then = function then(onSuccess, onError) {
if (onSuccess && typeof onSuccess !== 'function' && !onSuccess.call) {
throw new Error('Promise.then expected a function for success handler');
}
if (onError && typeof onError !== 'function' && !onError.call) {
throw new Error('Promise.then expected a function for error handler');
}
var promise = new ZalgoPromise();
this.handlers.push({
promise: promise,
onSuccess: onSuccess,
onError: onError
});
this.errorHandled = true;
this.dispatch();
return promise;
};
_proto.catch = function _catch(onError) {
return this.then(undefined, onError);
};
_proto.finally = function _finally(onFinally) {
if (onFinally && typeof onFinally !== 'function' && !onFinally.call) {
throw new Error('Promise.finally expected a function');
}
return this.then(function (result) {
return ZalgoPromise.try(onFinally).then(function () {
return result;
});
}, function (err) {
return ZalgoPromise.try(onFinally).then(function () {
throw err;
});
});
};
_proto.timeout = function timeout(time, err) {
var _this3 = this;
if (this.resolved || this.rejected) {
return this;
}
var timeout = setTimeout(function () {
if (_this3.resolved || _this3.rejected) {
return;
}
_this3.reject(err || new Error("Promise timed out after " + time + "ms"));
}, time);
return this.then(function (result) {
clearTimeout(timeout);
return result;
});
} // $FlowFixMe
;
_proto.toPromise = function toPromise() {
// $FlowFixMe
if (typeof Promise === 'undefined') {
throw new TypeError("Could not find Promise");
} // $FlowFixMe
return Promise.resolve(this); // eslint-disable-line compat/compat
};
ZalgoPromise.resolve = function resolve(value) {
if (value instanceof ZalgoPromise) {
return value;
}
if (utils_isPromise(value)) {
// $FlowFixMe
return new ZalgoPromise(function (resolve, reject) {
return value.then(resolve, reject);
});
}
return new ZalgoPromise().resolve(value);
};
ZalgoPromise.reject = function reject(error) {
return new ZalgoPromise().reject(error);
};
ZalgoPromise.asyncReject = function asyncReject(error) {
return new ZalgoPromise().asyncReject(error);
};
ZalgoPromise.all = function all(promises) {
// eslint-disable-line no-undef
var promise = new ZalgoPromise();
var count = promises.length;
var results = [];
if (!count) {
promise.resolve(results);
return promise;
}
var chain = function chain(i, firstPromise, secondPromise) {
return firstPromise.then(function (res) {
results[i] = res;
count -= 1;
if (count === 0) {
promise.resolve(results);
}
}, function (err) {
secondPromise.reject(err);
});
};
for (var i = 0; i < promises.length; i++) {
var prom = promises[i];
if (prom instanceof ZalgoPromise) {
if (prom.resolved) {
results[i] = prom.value;
count -= 1;
continue;
}
} else if (!utils_isPromise(prom)) {
results[i] = prom;
count -= 1;
continue;
}
chain(i, ZalgoPromise.resolve(prom), promise);
}
if (count === 0) {
promise.resolve(results);
}
return promise;
};
ZalgoPromise.hash = function hash(promises) {
// eslint-disable-line no-undef
var result = {};
return ZalgoPromise.all(Object.keys(promises).map(function (key) {
return ZalgoPromise.resolve(promises[key]).then(function (value) {
result[key] = value;
});
})).then(function () {
return result;
});
};
ZalgoPromise.map = function map(items, method) {
// $FlowFixMe
return ZalgoPromise.all(items.map(method));
};
ZalgoPromise.onPossiblyUnhandledException = function onPossiblyUnhandledException(handler) {
return exceptions_onPossiblyUnhandledException(handler);
};
ZalgoPromise.try = function _try(method, context, args) {
if (method && typeof method !== 'function' && !method.call) {
throw new Error('Promise.try expected a function');
}
var result;
startActive();
try {
// $FlowFixMe
result = method.apply(context, args || []);
} catch (err) {
endActive();
return ZalgoPromise.reject(err);
}
endActive();
return ZalgoPromise.resolve(result);
};
ZalgoPromise.delay = function delay(_delay) {
return new ZalgoPromise(function (resolve) {
setTimeout(resolve, _delay);
});
};
ZalgoPromise.isPromise = function isPromise(value) {
if (value && value instanceof ZalgoPromise) {
return true;
}
return utils_isPromise(value);
};
ZalgoPromise.flush = function flush() {
return awaitActive(ZalgoPromise);
};
return ZalgoPromise;
}();
// CONCATENATED MODULE: ./node_modules/zalgo-promise/src/index.js
// CONCATENATED MODULE: ./node_modules/cross-domain-utils/src/util.js
function isRegex(item) {
return Object.prototype.toString.call(item) === '[object RegExp]';
} // eslint-disable-next-line no-unused-vars
function noop() {// pass
}
// CONCATENATED MODULE: ./node_modules/cross-domain-utils/src/constants.js
var PROTOCOL = {
MOCK: 'mock:',
FILE: 'file:',
ABOUT: 'about:'
};
var WILDCARD = '*';
var WINDOW_TYPE = {
IFRAME: 'iframe',
POPUP: 'popup'
};
// CONCATENATED MODULE: ./node_modules/cross-domain-utils/src/utils.js
/* eslint max-lines: 0 */
var IE_WIN_ACCESS_ERROR = 'Call was rejected by callee.\r\n';
function isFileProtocol(win) {
if (win === void 0) {
win = window;
}
return win.location.protocol === PROTOCOL.FILE;
}
function isAboutProtocol(win) {
if (win === void 0) {
win = window;
}
return win.location.protocol === PROTOCOL.ABOUT;
}
function getParent(win) {
if (win === void 0) {
win = window;
}
if (!win) {
return;
}
try {
if (win.parent && win.parent !== win) {
return win.parent;
}
} catch (err) {// pass
}
}
function getOpener(win) {
if (win === void 0) {
win = window;
}
if (!win) {
return;
} // Make sure we're not actually an iframe which has had window.open() called on us
if (getParent(win)) {
return;
}
try {
return win.opener;
} catch (err) {// pass
}
}
function canReadFromWindow(win) {
try {
// $FlowFixMe
noop(win && win.location && win.location.href);
return true;
} catch (err) {// pass
}
return false;
}
function getActualDomain(win) {
if (win === void 0) {
win = window;
}
var location = win.location;
if (!location) {
throw new Error("Can not read window location");
}
var protocol = location.protocol;
if (!protocol) {
throw new Error("Can not read window protocol");
}
if (protocol === PROTOCOL.FILE) {
return PROTOCOL.FILE + "//";
}
if (protocol === PROTOCOL.ABOUT) {
var parent = getParent(win);
if (parent && canReadFromWindow(parent)) {
// $FlowFixMe
return getActualDomain(parent);
}
return PROTOCOL.ABOUT + "//";
}
var host = location.host;
if (!host) {
throw new Error("Can not read window host");
}
return protocol + "//" + host;
}
function utils_getDomain(win) {
if (win === void 0) {
win = window;
}
var domain = getActualDomain(win);
if (domain && win.mockDomain && win.mockDomain.indexOf(PROTOCOL.MOCK) === 0) {
return win.mockDomain;
}
return domain;
}
function isBlankDomain(win) {
try {
// $FlowFixMe
if (!win.location.href) {
return true;
}
if (win.location.href === 'about:blank') {
return true;
}
} catch (err) {// pass
}
return false;
}
function isActuallySameDomain(win) {
try {
if (win === window) {
return true;
}
} catch (err) {// pass
}
try {
var desc = Object.getOwnPropertyDescriptor(win, 'location');
if (desc && desc.enumerable === false) {
return false;
}
} catch (err) {// pass
}
try {
// $FlowFixMe
if (isAboutProtocol(win) && canReadFromWindow(win)) {
return true;
}
} catch (err) {// pass
}
try {
// $FlowFixMe
if (getActualDomain(win) === getActualDomain(window)) {
return true;
}
} catch (err) {// pass
}
return false;
}
function isSameDomain(win) {
if (!isActuallySameDomain(win)) {
return false;
}
try {
if (win === window) {
return true;
} // $FlowFixMe
if (isAboutProtocol(win) && canReadFromWindow(win)) {
return true;
} // $FlowFixMe
if (utils_getDomain(window) === utils_getDomain(win)) {
return true;
}
} catch (err) {// pass
}
return false;
}
function assertSameDomain(win) {
if (!isSameDomain(win)) {
throw new Error("Expected window to be same domain");
} // $FlowFixMe
return win;
}
function getParents(win) {
var result = [];
try {
while (win.parent !== win) {
result.push(win.parent);
win = win.parent;
}
} catch (err) {// pass
}
return result;
}
function isAncestorParent(parent, child) {
if (!parent || !child) {
return false;
}
var childParent = getParent(child);
if (childParent) {
return childParent === parent;
}
if (getParents(child).indexOf(parent) !== -1) {
return true;
}
return false;
}
function getFrames(win) {
var result = [];
var frames;
try {
frames = win.frames;
} catch (err) {
frames = win;
}
var len;
try {
len = frames.length;
} catch (err) {// pass
}
if (len === 0) {
return result;
}
if (len) {
for (var i = 0; i < len; i++) {
var frame = void 0;
try {
frame = frames[i];
} catch (err) {
continue;
}
result.push(frame);
}
return result;
}
for (var _i = 0; _i < 100; _i++) {
var _frame = void 0;
try {
_frame = frames[_i];
} catch (err) {
return result;
}
if (!_frame) {
return result;
}
result.push(_frame);
}
return result;
}
function getAllChildFrames(win) {
var result = [];
for (var _i3 = 0, _getFrames2 = getFrames(win); _i3 < _getFrames2.length; _i3++) {
var frame = _getFrames2[_i3];
result.push(frame);
for (var _i5 = 0, _getAllChildFrames2 = getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) {
var childFrame = _getAllChildFrames2[_i5];
result.push(childFrame);
}
}
return result;
}
function getTop(win) {
if (win === void 0) {
win = window;
}
try {
if (win.top) {
return win.top;
}
} catch (err) {// pass
}
if (getParent(win) === win) {
return win;
}
try {
if (isAncestorParent(window, win) && window.top) {
return window.top;
}
} catch (err) {// pass
}
try {
if (isAncestorParent(win, window) && window.top) {
return window.top;
}
} catch (err) {// pass
}
for (var _i7 = 0, _getAllChildFrames4 = getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) {
var frame = _getAllChildFrames4[_i7];
try {
if (frame.top) {
return frame.top;
}
} catch (err) {// pass
}
if (getParent(frame) === frame) {
return frame;
}
}
}
function getNextOpener(win) {
if (win === void 0) {
win = window;
}
return getOpener(getTop(win) || win);
}
function getUltimateTop(win) {
if (win === void 0) {
win = window;
}
var opener = getNextOpener(win);
if (opener) {
return getUltimateTop(opener);
}
return top;
}
function getAllFramesInWindow(win) {
var top = getTop(win);
if (!top) {
throw new Error("Can not determine top window");
}
return [].concat(getAllChildFrames(top), [top]);
}
function getAllWindows(win) {
if (win === void 0) {
win = window;
}
var frames = getAllFramesInWindow(win);
var opener = getNextOpener(win);
if (opener) {
return [].concat(getAllWindows(opener), frames);
} else {
return frames;
}
}
function isTop(win) {
return win === getTop(win);
}
function isFrameWindowClosed(frame) {
if (!frame.contentWindow) {
return true;
}
if (!frame.parentNode) {
return true;
}
var doc = frame.ownerDocument;
if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {
return true;
}
return false;
}
function safeIndexOf(collection, item) {
for (var i = 0; i < collection.length; i++) {
try {
if (collection[i] === item) {
return i;
}
} catch (err) {// pass
}
}
return -1;
}
var iframeWindows = [];
var iframeFrames = [];
function isWindowClosed(win, allowMock) {
if (allowMock === void 0) {
allowMock = true;
}
try {
if (win === window) {
return false;
}
} catch (err) {
return true;
}
try {
if (!win) {
return true;
}
} catch (err) {
return true;
}
try {
if (win.closed) {
return true;
}
} catch (err) {
// I love you so much IE
if (err && err.message === IE_WIN_ACCESS_ERROR) {
return false;
}
return true;
}
if (allowMock && isSameDomain(win)) {
try {
// $FlowFixMe
if (win.mockclosed) {
return true;
}
} catch (err) {// pass
}
} // Mobile safari
try {
if (!win.parent || !win.top) {
return true;
}
} catch (err) {} // pass
// Yes, this actually happens in IE. win === win errors out when the window
// is from an iframe, and the iframe was removed from the page.
try {
noop(win === win); // eslint-disable-line no-self-compare
} catch (err) {
return true;
} // IE orphaned frame
var iframeIndex = safeIndexOf(iframeWindows, win);
if (iframeIndex !== -1) {
var frame = iframeFrames[iframeIndex];
if (frame && isFrameWindowClosed(frame)) {
return true;
}
}
return false;
}
function cleanIframes() {
for (var i = 0; i < iframeWindows.length; i++) {
var closed = false;
try {
closed = iframeWindows[i].closed;
} catch (err) {// pass
}
if (closed) {
iframeFrames.splice(i, 1);
iframeWindows.splice(i, 1);
}
}
}
function linkFrameWindow(frame) {
cleanIframes();
if (frame && frame.contentWindow) {
try {
iframeWindows.push(frame.contentWindow);
iframeFrames.push(frame);
} catch (err) {// pass
}
}
}
function utils_getUserAgent(win) {
win = win || window;
return win.navigator.mockUserAgent || win.navigator.userAgent;
}
function getFrameByName(win, name) {
var winFrames = getFrames(win);
for (var _i9 = 0; _i9 < winFrames.length; _i9++) {
var childFrame = winFrames[_i9];
try {
// $FlowFixMe
if (isSameDomain(childFrame) && childFrame.name === name && winFrames.indexOf(childFrame) !== -1) {
return childFrame;
}
} catch (err) {// pass
}
}
try {
// $FlowFixMe
if (winFrames.indexOf(win.frames[name]) !== -1) {
// $FlowFixMe
return win.frames[name];
}
} catch (err) {// pass
}
try {
if (winFrames.indexOf(win[name]) !== -1) {
return win[name];
}
} catch (err) {// pass
}
}
function findChildFrameByName(win, name) {
var frame = getFrameByName(win, name);
if (frame) {
return frame;
}
for (var _i11 = 0, _getFrames4 = getFrames(win); _i11 < _getFrames4.length; _i11++) {
var childFrame = _getFrames4[_i11];
var namedFrame = findChildFrameByName(childFrame, name);
if (namedFrame) {
return namedFrame;
}
}
}
function findFrameByName(win, name) {
var frame;
frame = getFrameByName(win, name);
if (frame) {
return frame;
}
var top = getTop(win) || win;
return findChildFrameByName(top, name);
}
function isParent(win, frame) {
var frameParent = getParent(frame);
if (frameParent) {
return frameParent === win;
}
for (var _i13 = 0, _getFrames6 = getFrames(win); _i13 < _getFrames6.length; _i13++) {
var childFrame = _getFrames6[_i13];
if (childFrame === frame) {
return true;
}
}
return false;
}
function isOpener(parent, child) {
return parent === getOpener(child);
}
function getAncestor(win) {
if (win === void 0) {
win = window;
}
win = win || window;
var opener = getOpener(win);
if (opener) {
return opener;
}
var parent = getParent(win);
if (parent) {
return parent;
}
}
function getAncestors(win) {
var results = [];
var ancestor = win;
while (ancestor) {
ancestor = getAncestor(ancestor);
if (ancestor) {
results.push(ancestor);
}
}
return results;
}
function isAncestor(parent, child) {
var actualParent = getAncestor(child);
if (actualParent) {
if (actualParent === parent) {
return true;
}
return false;
}
if (child === parent) {
return false;
}
if (getTop(child) === child) {
return false;
}
for (var _i15 = 0, _getFrames8 = getFrames(parent); _i15 < _getFrames8.length; _i15++) {
var frame = _getFrames8[_i15];
if (frame === child) {
return true;
}
}
return false;
}
function utils_isPopup(win) {
if (win === void 0) {
win = window;
}
return Boolean(getOpener(win));
}
function isIframe(win) {
if (win === void 0) {
win = window;
}
return Boolean(getParent(win));
}
function isFullpage(win) {
if (win === void 0) {
win = window;
}
return Boolean(!isIframe(win) && !utils_isPopup(win));
}
function anyMatch(collection1, collection2) {
for (var _i17 = 0; _i17 < collection1.length; _i17++) {
var item1 = collection1[_i17];
for (var _i19 = 0; _i19 < collection2.length; _i19++) {
var item2 = collection2[_i19];
if (item1 === item2) {
return true;
}
}
}
return false;
}
function getDistanceFromTop(win) {
if (win === void 0) {
win = window;
}
var distance = 0;
var parent = win;
while (parent) {
parent = getParent(parent);
if (parent) {
distance += 1;
}
}
return distance;
}
function getNthParent(win, n) {
if (n === void 0) {
n = 1;
}
var parent = win;
for (var i = 0; i < n; i++) {
if (!parent) {
return;
}
parent = getParent(parent);
}
return parent;
}
function getNthParentFromTop(win, n) {
if (n === void 0) {
n = 1;
}
return getNthParent(win, getDistanceFromTop(win) - n);
}
function isSameTopWindow(win1, win2) {
var top1 = getTop(win1) || win1;
var top2 = getTop(win2) || win2;
try {
if (top1 && top2) {
if (top1 === top2) {
return true;
}
return false;
}
} catch (err) {// pass
}
var allFrames1 = getAllFramesInWindow(win1);
var allFrames2 = getAllFramesInWindow(win2);
if (anyMatch(allFrames1, allFrames2)) {
return true;
}
var opener1 = getOpener(top1);
var opener2 = getOpener(top2);
if (opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2)) {
return false;
}
if (opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1)) {
return false;
}
return false;
}
function matchDomain(pattern, origin) {
if (typeof pattern === 'string') {
if (typeof origin === 'string') {
return pattern === WILDCARD || origin === pattern;
}
if (isRegex(origin)) {
return false;
}
if (Array.isArray(origin)) {
return false;
}
}
if (isRegex(pattern)) {
if (isRegex(origin)) {
return pattern.toString() === origin.toString();
}
if (Array.isArray(origin)) {
return false;
} // $FlowFixMe
return Boolean(origin.match(pattern));
}
if (Array.isArray(pattern)) {
if (Array.isArray(origin)) {
return JSON.stringify(pattern) === JSON.stringify(origin);
}
if (isRegex(origin)) {
return false;
}
return pattern.some(function (subpattern) {
return matchDomain(subpattern, origin);
});
}
return false;
}
function stringifyDomainPattern(pattern) {
if (Array.isArray(pattern)) {
return "(" + pattern.join(' | ') + ")";
} else if (isRegex(pattern)) {
return "RegExp(" + pattern.toString();
} else {
return pattern.toString();
}
}
function getDomainFromUrl(url) {
var domain;
if (url.match(/^(https?|mock|file):\/\//)) {
domain = url;
} else {
return utils_getDomain();
}
domain = domain.split('/').slice(0, 3).join('/');
return domain;
}
function onCloseWindow(win, callback, delay, maxtime) {
if (delay === void 0) {
delay = 1000;
}
if (maxtime === void 0) {
maxtime = Infinity;
}
var timeout;
var check = function check() {
if (isWindowClosed(win)) {
if (timeout) {
clearTimeout(timeout);
}
return callback();
}
if (maxtime <= 0) {
clearTimeout(timeout);
} else {
maxtime -= delay;
timeout = setTimeout(check, delay);
}
};
check();
return {
cancel: function cancel() {
if (timeout) {
clearTimeout(timeout);
}
}
};
} // eslint-disable-next-line complexity
function isWindow(obj) {
try {
if (obj === window) {
return true;
}
} catch (err) {
if (err && err.message === IE_WIN_ACCESS_ERROR) {
return true;
}
}
try {
if (Object.prototype.toString.call(obj) === '[object Window]') {
return true;
}
} catch (err) {
if (err && err.message === IE_WIN_ACCESS_ERROR) {
return true;
}
}
try {
if (window.Window && obj instanceof window.Window) {
return true;
}
} catch (err) {
if (err && err.message === IE_WIN_ACCESS_ERROR) {
return true;
}
}
try {
if (obj && obj.self === obj) {
return true;
}
} catch (err) {
if (err && err.message === IE_WIN_ACCESS_ERROR) {
return true;
}
}
try {
if (obj && obj.parent === obj) {
return true;
}
} catch (err) {
if (err && err.message === IE_WIN_ACCESS_ERROR) {
return true;
}
}
try {
if (obj && obj.top === obj) {
return true;
}
} catch (err) {
if (err && err.message === IE_WIN_ACCESS_ERROR) {
return true;
}
}
try {
if (noop(obj === obj) === '__unlikely_value__') {
// eslint-disable-line no-self-compare
return false;
}
} catch (err) {
return true;
}
try {
if (obj && obj.__cross_domain_utils_window_check__ === '__unlikely_value__') {
return false;
}
} catch (err) {
return true;
}
return false;
}
function isBrowser() {
return typeof window !== 'undefined' && typeof window.location !== 'undefined';
}
function isCurrentDomain(domain) {
if (!isBrowser()) {
return false;
}
return utils_getDomain() === domain;
}
function isMockDomain(domain) {
return domain.indexOf(PROTOCOL.MOCK) === 0;
}
function normalizeMockUrl(url) {
if (!isMockDomain(getDomainFromUrl(url))) {
return url;
}
if (true) {
throw new Error("Mock urls not supported out of test mode");
}
return url.replace(/^mock:\/\/[^/]+/, getActualDomain(window));
}
function closeWindow(win) {
try {
win.close();
} catch (err) {// pass
}
}
function getFrameForWindow(win) {
if (isSameDomain(win)) {
return assertSameDomain(win).frameElement;
}
for (var _i21 = 0, _document$querySelect2 = document.querySelectorAll('iframe'); _i21 < _document$querySelect2.length; _i21++) {
var frame = _document$querySelect2[_i21];
if (frame && frame.contentWindow && frame.contentWindow === win) {
return frame;
}
}
}
// CONCATENATED MODULE: ./node_modules/cross-domain-utils/src/types.js
// export something to force webpack to see this as an ES module
var TYPES = true;
// CONCATENATED MODULE: ./node_modules/cross-domain-utils/src/index.js
// CONCATENATED MODULE: ./node_modules/cross-domain-safe-weakmap/src/native.js
function hasNativeWeakMap() {
if (typeof WeakMap === 'undefined') {
return false;
}
if (typeof Object.freeze === 'undefined') {
return false;
}
try {
var testWeakMap = new WeakMap();
var testKey = {};
var testValue = '__testvalue__';
Object.freeze(testKey);
testWeakMap.set(testKey, testValue);
if (testWeakMap.get(testKey) === testValue) {
return true;
}
return false;
} catch (err) {
return false;
}
}
// CONCATENATED MODULE: ./node_modules/cross-domain-safe-weakmap/src/util.js
function util_safeIndexOf(collection, item) {
for (var i = 0; i < collection.length; i++) {
try {
if (collection[i] === item) {
return i;
}
} catch (err) {// pass
}
}
return -1;
} // eslint-disable-next-line no-unused-vars
function util_noop() {// pass
}
// CONCATENATED MODULE: ./node_modules/cross-domain-safe-weakmap/src/weakmap.js
var weakmap_CrossDomainSafeWeakMap =
/*#__PURE__*/
function () {
function CrossDomainSafeWeakMap() {
this.name = void 0;
this.weakmap = void 0;
this.keys = void 0;
this.values = void 0;
// eslint-disable-next-line no-bitwise
this.name = "__weakmap_" + (Math.random() * 1e9 >>> 0) + "__";
if (hasNativeWeakMap()) {
try {
this.weakmap = new WeakMap();
} catch (err) {// pass
}
}
this.keys = [];
this.values = [];
}
var _proto = CrossDomainSafeWeakMap.prototype;
_proto._cleanupClosedWindows = function _cleanupClosedWindows() {
var weakmap = this.weakmap;
var keys = this.keys;
for (var i = 0; i < keys.length; i++) {
var value = keys[i];
if (isWindow(value) && isWindowClosed(value)) {
if (weakmap) {
try {
weakmap.delete(value);
} catch (err) {// pass
}
}
keys.splice(i, 1);
this.values.splice(i, 1);
i -= 1;
}
}
};
_proto.isSafeToReadWrite = function isSafeToReadWrite(key) {
if (isWindow(key)) {
return false;
}
try {
util_noop(key && key.self);
util_noop(key && key[this.name]);
} catch (err) {
return false;
}
return true;
};
_proto.set = function set(key, value) {
if (!key) {
throw new Error("WeakMap expected key");
}
var weakmap = this.weakmap;
if (weakmap) {
try {
weakmap.set(key, value);
} catch (err) {
delete this.weakmap;
}
}
if (this.isSafeToReadWrite(key)) {
try {
var name = this.name;
var entry = key[name];
if (entry && entry[0] === key) {
entry[1] = value;
} else {
Object.defineProperty(key, name, {
value: [key, value],
writable: true
});
}
return;
} catch (err) {// pass
}
}
this._cleanupClosedWindows();
var keys = this.keys;
var values = this.values;
var index = util_safeIndexOf(keys, key);
if (index === -1) {
keys.push(key);
values.push(value);
} else {
values[index] = value;
}
};
_proto.get = function get(key) {
if (!key) {
throw new Error("WeakMap expected key");
}
var weakmap = this.weakmap;
if (weakmap) {
try {
if (weakmap.has(key)) {
return weakmap.get(key);
}
} catch (err) {
delete this.weakmap;
}
}
if (this.isSafeToReadWrite(key)) {
try {
var entry = key[this.name];
if (entry && entry[0] === key) {
return entry[1];
}
return;
} catch (err) {// pass
}
}
this._cleanupClosedWindows();
var keys = this.keys;
var index = util_safeIndexOf(keys, key);
if (index === -1) {
return;
}
return this.values[index];
};
_proto.delete = function _delete(key) {
if (!key) {
throw new Error("WeakMap expected key");
}
var weakmap = this.weakmap;
if (weakmap) {
try {
weakmap.delete(key);
} catch (err) {
delete this.weakmap;
}
}
if (this.isSafeToReadWrite(key)) {
try {
var entry = key[this.name];
if (entry && entry[0] === key) {
entry[0] = entry[1] = undefined;
}
} catch (err) {// pass
}
}
this._cleanupClosedWindows();
var keys = this.keys;
var index = util_safeIndexOf(keys, key);
if (index !== -1) {
keys.splice(index, 1);
this.values.splice(index, 1);
}
};
_proto.has = function has(key) {
if (!key) {
throw new Error("WeakMap expected key");
}
var weakmap = this.weakmap;
if (weakmap) {
try {
if (weakmap.has(key)) {
return true;
}
} catch (err) {
delete this.weakmap;
}
}
if (this.isSafeToReadWrite(key)) {
try {
var entry = key[this.name];
if (entry && entry[0] === key) {
return true;
}
return false;
} catch (err) {// pass
}
}
this._cleanupClosedWindows();
var index = util_safeIndexOf(this.keys, key);
return index !== -1;
};
_proto.getOrSet = function getOrSet(key, getter) {
if (this.has(key)) {
// $FlowFixMe
return this.get(key);
}
var value = getter();
this.set(key, value);
return value;
};
return CrossDomainSafeWeakMap;
}();
// CONCATENATED MODULE: ./node_modules/cross-domain-safe-weakmap/src/index.js
// CONCATENATED MODULE: ./node_modules/belter/src/util.js
/* eslint max-lines: 0 */
function getFunctionName(fn) {
return fn.name || fn.__name__ || fn.displayName || 'anonymous';
}
function setFunctionName(fn, name) {
try {
delete fn.name;
fn.name = name;
} catch (err) {// pass
}
fn.__name__ = fn.displayName = name;
return fn;
}
function base64encode(str) {
if (typeof btoa === 'function') {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (m, p1) {
return String.fromCharCode(parseInt(p1, 16));
}));
}
if (typeof Buffer !== 'undefined') {
return Buffer.from(str, 'utf8').toString('base64');
}
throw new Error("Can not find window.btoa or Buffer");
}
function base64decode(str) {
if (typeof atob === 'function') {
return decodeURIComponent(Array.prototype.map.call(atob(str), function (c) {
// eslint-disable-next-line prefer-template
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
if (typeof Buffer !== 'undefined') {
return Buffer.from(str, 'base64').toString('utf8');
}
throw new Error("Can not find window.atob or Buffer");
}
function uniqueID() {
var chars = '0123456789abcdef';
var randomID = 'xxxxxxxxxx'.replace(/./g, function () {
return chars.charAt(Math.floor(Math.random() * chars.length));
});
var timeID = base64encode(new Date().toISOString().slice(11, 19).replace('T', '.')).replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
return randomID + "_" + timeID;
}
function getGlobal() {
if (typeof window !== 'undefined') {
return window;
}
if (typeof window !== 'undefined') {
return window;
}
if (typeof global !== 'undefined') {
return global;
}
throw new Error("No global found");
}
var objectIDs;
function getObjectID(obj) {
objectIDs = objectIDs || new weakmap_CrossDomainSafeWeakMap();
if (obj === null || obj === undefined || typeof obj !== 'object' && typeof obj !== 'function') {
throw new Error("Invalid object");
}
var uid = objectIDs.get(obj);
if (!uid) {
uid = typeof obj + ":" + uniqueID();
objectIDs.set(obj, uid);
}
return uid;
}
function serializeArgs(args) {
try {
return JSON.stringify(Array.prototype.slice.call(args), function (subkey, val) {
if (typeof val === 'function') {
return "memoize[" + getObjectID(val) + "]";
}
return val;
});
} catch (err) {
throw new Error("Arguments not serializable -- can not be used to memoize");
}
}
function memoize(method, options) {
var _this = this;
if (options === void 0) {
options = {};
}
var cacheMap = new weakmap_CrossDomainSafeWeakMap(); // $FlowFixMe
var memoizedFunction = function memoizedFunction() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var cache = cacheMap.getOrSet(options.thisNamespace ? this : method, function () {
return {};
});
var key = serializeArgs(args);
var cacheTime = options.time;
if (cache[key] && cacheTime && Date.now() - cache[key].time < cacheTime) {
delete cache[key];
}
if (cache[key]) {
return cache[key].value;
}
var time = Date.now();
var value = method.apply(this, arguments);
cache[key] = {
time: time,
value: value
};
return cache[key].value;
};
memoizedFunction.reset = function () {
cacheMap.delete(options.thisNamespace ? _this : method);
};
return setFunctionName(memoizedFunction, getFunctionName(method) + "::memoized");
}
function promiseIdentity(item) {
// $FlowFixMe
return promise_ZalgoPromise.resolve(item);
} // eslint-disable-next-line flowtype/no-weak-types
function memoizePromise(method) {
var cache = {}; // eslint-disable-next-line flowtype/no-weak-types
function memoizedPromiseFunction() {
var _arguments = arguments,
_this2 = this;
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var key = serializeArgs(args);
if (cache.hasOwnProperty(key)) {
return cache[key];
}
cache[key] = promise_ZalgoPromise.try(function () {
return method.apply(_this2, _arguments);
}).finally(function () {
delete cache[key];
});
return cache[key];
}
memoizedPromiseFunction.reset = function () {
cache = {};
};
return setFunctionName(memoizedPromiseFunction, getFunctionName(method) + "::promiseMemoized");
} // eslint-disable-next-line flowtype/no-weak-types
function promisify(method, options) {
if (options === void 0) {
options = {};
}
function promisifiedFunction() {
return promise_ZalgoPromise.try(method, this, arguments);
}
if (options.name) {
promisifiedFunction.displayName = options.name + ":promisified";
}
return setFunctionName(promisifiedFunction, getFunctionName(method) + "::promisified");
} // eslint-disable-next-line flowtype/no-weak-types
function inlineMemoize(method, logic, args) {
if (args === void 0) {
args = [];
}
// $FlowFixMe
var cache = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {};
var key = serializeArgs(args);
if (cache.hasOwnProperty(key)) {
return cache[key];
}
var result = cache[key] = logic.apply(void 0, args);
return result;
} // eslint-disable-next-line no-unused-vars
function src_util_noop() {// pass
}
function once(method) {
var called = false;
var onceFunction = function onceFunction() {
if (!called) {
called = true;
return method.apply(this, arguments);
}
};
return setFunctionName(onceFunction, getFunctionName(method) + "::once");
}
function hashStr(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash += str[i].charCodeAt(0) * Math.pow(i % 10 + 1, 5);
}
return Math.floor(Math.pow(Math.sqrt(hash), 5));
}
function strHashStr(str) {
var hash = '';
for (var i = 0; i < str.length; i++) {
var total = str[i].charCodeAt(0) * i;
if (str[i + 1]) {
total += str[i + 1].charCodeAt(0) * (i - 1);
}
hash += String.fromCharCode(97 + Math.abs(total) % 26);
}
return hash;
}
function util_match(str, pattern) {
var regmatch = str.match(pattern);
if (regmatch) {
return regmatch[1];
}
}
function awaitKey(obj, key) {
return new promise_ZalgoPromise(function (resolve) {
var value = obj[key];
if (value) {
return resolve(value);
}
delete obj[key];
Object.defineProperty(obj, key, {
configurable: true,
set: function set(item) {
value = item;
if (value) {
resolve(value);
}
},
get: function get() {
return value;
}
});
});
}
function stringifyError(err, level) {
if (level === void 0) {
level = 1;
}
if (level >= 3) {
return 'stringifyError stack overflow';
}
try {
if (!err) {
return "<unknown error: " + Object.prototype.toString.call(err) + ">";
}
if (typeof err === 'string') {
return err;
}
if (err instanceof Error) {
var stack = err && err.stack;
var message = err && err.message;
if (stack && message) {
if (stack.indexOf(message) !== -1) {
return stack;
} else {
return message + "\n" + stack;
}
} else if (stack) {
return stack;
} else if (message) {
return message;
}
}
if (err && err.toString && typeof err.toString === 'function') {
// $FlowFixMe
return err.toString();
}
return Object.prototype.toString.call(err);
} catch (newErr) {
// eslint-disable-line unicorn/catch-error-name
return "Error while stringifying error: " + stringifyError(newErr, level + 1);
}
}
function stringifyErrorMessage(err) {
var defaultMessage = "<unknown error: " + Object.prototype.toString.call(err) + ">";
if (!err) {
return defaultMessage;
}
if (err instanceof Error) {
return err.message || defaultMessage;
}
if (typeof err.message === 'string') {
return err.message || defaultMessage;
}
return defaultMessage;
}
function stringify(item) {
if (typeof item === 'string') {
return item;
}
if (item && item.toString && typeof item.toString === 'function') {
// $FlowFixMe
return item.toString();
}
return Object.prototype.toString.call(item);
}
function domainMatches(hostname, domain) {
hostname = hostname.split('://')[1];
var index = hostname.indexOf(domain);
return index !== -1 && hostname.slice(index) === domain;
}
function patchMethod(obj, name, handler) {
var original = obj[name];
obj[name] = function patchedMethod() {
var _arguments2 = arguments,
_this3 = this;
return handler({
context: this,
args: Array.prototype.slice.call(arguments),
original: original,
callOriginal: function callOriginal() {
return original.apply(_this3, _arguments2);
}
});
};
}
function extend(obj, source) {
if (!source) {
return obj;
}
if (Object.assign) {
return Object.assign(obj, source);
}
for (var key in source) {
if (source.hasOwnProperty(key)) {
obj[key] = source[key];
}
}
return obj;
}
function util_values(obj) {
var result = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
result.push(obj[key]);
}
}
return result;
}
function perc(pixels, percentage) {
return Math.round(pixels * percentage / 100);
}
function min() {
return Math.min.apply(Math, arguments);
}
function max() {
return Math.max.apply(Math, arguments);
}
function regexMap(str, regexp, handler) {
var results = []; // $FlowFixMe
str.replace(regexp, function regexMapMatcher(item) {
results.push(handler ? handler.apply(null, arguments) : item);
}); // $FlowFixMe
return results;
}
function svgToBase64(svg) {
return "data:image/svg+xml;base64," + base64encode(svg);
}
function objFilter(obj, filter) {
if (filter === void 0) {
filter = Boolean;
}
var result = {};
for (var key in obj) {
if (!obj.hasOwnProperty(key) || !filter(obj[key], key)) {
continue;
}
result[key] = obj[key];
}
return result;
}
function identity(item) {
return item;
}
function regexTokenize(text, regexp) {
var result = [];
text.replace(regexp, function (token) {
result.push(token);
return '';
});
return result;
}
function promiseDebounce(method, delay) {
if (delay === void 0) {
delay = 50;
}
var promise;
var timeout;
var promiseDebounced = function promiseDebounced() {
if (timeout) {
clearTimeout(timeout);
}
var localPromise = promise = promise || new promise_ZalgoPromise();
timeout = setTimeout(function () {
promise = null;
timeout = null;
promise_ZalgoPromise.try(method).then(function (result) {
localPromise.resolve(result);
}, function (err) {
localPromise.reject(err);
});
}, delay);
return localPromise;
};
return setFunctionName(promiseDebounced, getFunctionName(method) + "::promiseDebounced");
}
function safeInterval(method, time) {
var timeout;
function loop() {
timeout = setTimeout(function () {
method();
loop();
}, time);
}
loop();
return {
cancel: function cancel() {
clearTimeout(timeout);
}
};
}
function isInteger(str) {
return Boolean(str.match(/^[0-9]+$/));
}
function isFloat(str) {
return Boolean(str.match(/^[0-9]+\.[0-9]+$/));
}
function serializePrimitive(value) {
return value.toString();
}
function deserializePrimitive(value) {
if (value === 'true') {
return true;
} else if (value === 'false') {
return false;
} else if (isInteger(value)) {
return parseInt(value, 10);
} else if (isFloat(value)) {
return parseFloat(value);
} else {
return value;
}
}
function dotify(obj, prefix, newobj) {
if (prefix === void 0) {
prefix = '';
}
if (newobj === void 0) {
newobj = {};
}
prefix = prefix ? prefix + "." : prefix;
for (var key in obj) {
if (!obj.hasOwnProperty(key) || obj[key] === undefined || obj[key] === null || typeof obj[key] === 'function') {
continue;
} else if (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every(function (val) {
return typeof val !== 'object';
})) {
newobj["" + prefix + key + "[]"] = obj[key].join(',');
} else if (obj[key] && typeof obj[key] === 'object') {
newobj = dotify(obj[key], "" + prefix + key, newobj);
} else {
newobj["" + prefix + key] = serializePrimitive(obj[key]);
}
}
return newobj;
}
function undotify(obj) {
var result = {};
for (var key in obj) {
if (!obj.hasOwnProperty(key) || typeof obj[key] !== 'string') {
continue;
}
var value = obj[key];
if (key.match(/^.+\[\]$/)) {
key = key.slice(0, key.length - 2);
value = value.split(',').map(deserializePrimitive);
} else {
value = deserializePrimitive(value);
}
var keyResult = result;
var parts = key.split('.');
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
var isLast = i + 1 === parts.length;
var isIndex = !isLast && isInteger(parts[i + 1]);
if (part === 'constructor' || part === 'prototype' || part === '__proto__') {
throw new Error("Disallowed key: " + part);
}
if (isLast) {
// $FlowFixMe
keyResult[part] = value;
} else {
// $FlowFixMe
keyResult = keyResult[part] = keyResult[part] || (isIndex ? [] : {});
}
}
}
return result;
}
function eventEmitter() {
var triggered = {};
var handlers = {};
return {
on: function on(eventName, handler) {
var handlerList = handlers[eventName] = handlers[eventName] || [];
handlerList.push(handler);
var cancelled = false;
return {
cancel: function cancel() {
if (!cancelled) {
cancelled = true;
handlerList.splice(handlerList.indexOf(handler), 1);
}
}
};
},
once: function once(eventName, handler) {
var listener = this.on(eventName, function () {
listener.cancel();
handler();
});
return listener;
},
trigger: function trigger(eventName) {
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
var handlerList = handlers[eventName];
var promises = [];
if (handlerList) {
var _loop = function _loop(_i2) {
var handler = handlerList[_i2];
promises.push(promise_ZalgoPromise.try(function () {
return handler.apply(void 0, args);
}));
};
for (var _i2 = 0; _i2 < handlerList.length; _i2++) {
_loop(_i2);
}
}
return promise_ZalgoPromise.all(promises).then(src_util_noop);
},
triggerOnce: function triggerOnce(eventName) {
if (triggered[eventName]) {
return promise_ZalgoPromise.resolve();
}
triggered[eventName] = true;
for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
args[_key4 - 1] = arguments[_key4];
}
return this.trigger.apply(this, [eventName].concat(args));
},
reset: function reset() {
handlers = {};
}
};
}
function camelToDasherize(string) {
return string.replace(/([A-Z])/g, function (g) {
return "-" + g.toLowerCase();
});
}
function dasherizeToCamel(string) {
return string.replace(/-([a-z])/g, function (g) {
return g[1].toUpperCase();
});
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
function util_get(item, path, def) {
if (!path) {
return def;
}
var pathParts = path.split('.'); // Loop through each section of our key path
for (var i = 0; i < pathParts.length; i++) {
// If we have an object, we can get the key
if (typeof item === 'object' && item !== null) {
item = item[pathParts[i]]; // Otherwise, we should return the default (undefined if not provided)
} else {
return def;
}
} // If our final result is undefined, we should return the default
return item === undefined ? def : item;
}
function safeTimeout(method, time) {
var interval = safeInterval(function () {
time -= 100;
if (time <= 0) {
interval.cancel();
method();
}
}, 100);
}
function defineLazyProp(obj, key, getter) {
if (Array.isArray(obj)) {
if (typeof key !== 'number') {
throw new TypeError("Array key must be number");
}
} else if (typeof obj === 'object' && obj !== null) {
if (typeof key !== 'string') {
throw new TypeError("Object key must be string");
}
}
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
get: function get() {
// $FlowFixMe
delete obj[key];
var value = getter(); // $FlowFixMe
obj[key] = value;
return value;
},
set: function set(value) {
// $FlowFixMe
delete obj[key]; // $FlowFixMe
obj[key] = value;
}
});
}
function arrayFrom(item) {
// eslint-disable-line no-undef
return Array.prototype.slice.call(item);
}
function isObject(item) {
return typeof item === 'object' && item !== null;
}
function isObjectObject(obj) {
return isObject(obj) && Object.prototype.toString.call(obj) === '[object Object]';
}
function isPlainObject(obj) {
if (!isObjectObject(obj)) {
return false;
} // $FlowFixMe
var constructor = obj.constructor;
if (typeof constructor !== 'function') {
return false;
}
var prototype = constructor.prototype;
if (!isObjectObject(prototype)) {
return false;
}
if (!prototype.hasOwnProperty('isPrototypeOf')) {
return false;
}
return true;
}
function replaceObject(item, replacer, fullKey) {
if (fullKey === void 0) {
fullKey = '';
}
if (Array.isArray(item)) {
var length = item.length;
var result = [];
var _loop2 = function _loop2(i) {
defineLazyProp(result, i, function () {
var itemKey = fullKey ? fullKey + "." + i : "" + i;
var el = item[i];
var child = replacer(el, i, itemKey);
if (isPlainObject(child) || Array.isArray(child)) {
// $FlowFixMe
child = replaceObject(child, replacer, itemKey);
}
return child;
});
};
for (var i = 0; i < length; i++) {
_loop2(i);
} // $FlowFixMe
return result;
} else if (isPlainObject(item)) {
var _result = {};
var _loop3 = function _loop3(key) {
if (!item.hasOwnProperty(key)) {
return "continue";
}
defineLazyProp(_result, key, function () {
var itemKey = fullKey ? fullKey + "." + key : "" + key; // $FlowFixMe
var el = item[key];
var child = replacer(el, key, itemKey);
if (isPlainObject(child) || Array.isArray(child)) {
// $FlowFixMe
child = replaceObject(child, replacer, itemKey);
}
return child;
});
};
for (var key in item) {
var _ret = _loop3(key);
if (_ret === "continue") continue;
} // $FlowFixMe
return _result;
} else {
throw new Error("Pass an object or array");
}
}
function copyProp(source, target, name, def) {
if (source.hasOwnProperty(name)) {
var descriptor = Object.getOwnPropertyDescriptor(source, name); // $FlowFixMe
Object.defineProperty(target, name, descriptor);
} else {
target[name] = def;
}
}
function util_regex(pattern, string, start) {
if (start === void 0) {
start = 0;
}
if (typeof pattern === 'string') {
// eslint-disable-next-line security/detect-non-literal-regexp
pattern = new RegExp(pattern);
}
var result = string.slice(start).match(pattern);
if (!result) {
return;
} // $FlowFixMe
var index = result.index;
var regmatch = result[0];
return {
text: regmatch,
groups: result.slice(1),
start: start + index,
end: start + index + regmatch.length,
length: regmatch.length,
replace: function replace(text) {
if (!regmatch) {
return '';
}
return "" + regmatch.slice(0, start + index) + text + regmatch.slice(index + regmatch.length);
}
};
}
function regexAll(pattern, string) {
var matches = [];
var start = 0; // eslint-disable-next-line no-constant-condition
while (true) {
var regmatch = util_regex(pattern, string, start);
if (!regmatch) {
break;
}
matches.push(regmatch);
start = util_match.end;
}
return matches;
}
function isDefined(value) {
return value !== null && value !== undefined;
}
function cycle(method) {
return promise_ZalgoPromise.try(method).then(function () {
return cycle(method);
});
}
function debounce(method, time) {
if (time === void 0) {
time = 100;
}
var timeout;
var debounceWrapper = function debounceWrapper() {
var _arguments3 = arguments,
_this4 = this;
clearTimeout(timeout);
timeout = setTimeout(function () {
return method.apply(_this4, _arguments3);
}, time);
};
return setFunctionName(debounceWrapper, getFunctionName(method) + "::debounced");
}
function util_isRegex(item) {
return Object.prototype.toString.call(item) === '[object RegExp]';
}
// eslint-disable-next-line flowtype/no-weak-types
var util_weakMapMemoize = function weakMapMemoize(method) {
var weakmap = new weakmap_CrossDomainSafeWeakMap(); // eslint-disable-next-line flowtype/no-weak-types
return function weakmapMemoized(arg) {
var _this5 = this;
return weakmap.getOrSet(arg, function () {
return method.call(_this5, arg);
});
};
};
// eslint-disable-next-line flowtype/no-weak-types
var util_weakMapMemoizePromise = function weakMapMemoizePromise(method) {
var weakmap = new weakmap_CrossDomainSafeWeakMap(); // eslint-disable-next-line flowtype/no-weak-types
return function weakmapMemoizedPromise(arg) {
var _this6 = this;
return weakmap.getOrSet(arg, function () {
return method.call(_this6, arg).finally(function () {
weakmap.delete(arg);
});
});
};
};
function util_getOrSet(obj, key, getter) {
if (obj.hasOwnProperty(key)) {
return obj[key];
}
var val = getter();
obj[key] = val;
return val;
}
function cleanup(obj) {
var tasks = [];
var cleaned = false;
return {
set: function set(name, item) {
if (!cleaned) {
obj[name] = item;
this.register(function () {
delete obj[name];
});
}
return item;
},
register: function register(method) {
if (cleaned) {
method();
} else {
tasks.push(once(method));
}
},
all: function all() {
var results = [];
cleaned = true;
while (tasks.length) {
var task = tasks.pop();
results.push(task());
}
return promise_ZalgoPromise.all(results).then(src_util_noop);
}
};
}
function tryCatch(fn) {
var result;
var error;
try {
result = fn();
} catch (err) {
error = err;
} // $FlowFixMe
return {
result: result,
error: error
};
}
function removeFromArray(arr, item) {
var index = arr.indexOf(item);
if (index !== -1) {
arr.splice(index, 1);
}
}
function assertExists(name, thing) {
if (thing === null || typeof thing === 'undefined') {
throw new Error("Expected " + name + " to be present");
}
return thing;
}
function unique(arr) {
var result = {};
for (var _i4 = 0; _i4 < arr.length; _i4++) {
var item = arr[_i4];
// eslint-disable-next-line const-immutable/no-mutation
result[item] = true;
}
return Object.keys(result);
}
// CONCATENATED MODULE: ./node_modules/belter/src/constants.js
var KEY_CODES = {
ENTER: 13
};
// CONCATENATED MODULE: ./node_modules/belter/src/dom.js
/* eslint max-lines: off */
function isDocumentReady() {
return Boolean(document.body) && document.readyState === 'complete';
}
function urlEncode(str) {
return str.replace(/\?/g, '%3F').replace(/&/g, '%26').replace(/#/g, '%23').replace(/\+/g, '%2B');
}
function waitForWindowReady() {
return inlineMemoize(waitForWindowReady, function () {
return new promise_ZalgoPromise(function (resolve) {
if (isDocumentReady()) {
resolve();
}
window.addEventListener('load', function () {
return resolve();
});
});
});
}
function waitForDocumentReady() {
return inlineMemoize(waitForDocumentReady, function () {
return new promise_ZalgoPromise(function (resolve) {
if (isDocumentReady()) {
return resolve();
}
var interval = setInterval(function () {
if (isDocumentReady()) {
clearInterval(interval);
return resolve();
}
}, 10);
});
});
}
function waitForDocumentBody() {
return waitForDocumentReady().then(function () {
if (document.body) {
return document.body;
}
throw new Error('Document ready but document.body not present');
});
}
function parseQuery(queryString) {
return inlineMemoize(parseQuery, function () {
var params = {};
if (!queryString) {
return params;
}
if (queryString.indexOf('=') === -1) {
return params;
}
for (var _i2 = 0, _queryString$split2 = queryString.split('&'); _i2 < _queryString$split2.length; _i2++) {
var pair = _queryString$split2[_i2];
pair = pair.split('=');
if (pair[0] && pair[1]) {
params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
}
return params;
}, [queryString]);
}
function getQueryParam(name) {
return parseQuery(window.location.search.slice(1))[name];
}
function urlWillRedirectPage(url) {
if (url.indexOf('#') === -1) {
return true;
}
if (url.indexOf('#') === 0) {
return false;
}
if (url.split('#')[0] === window.location.href.split('#')[0]) {
return false;
}
return true;
}
function formatQuery(obj) {
if (obj === void 0) {
obj = {};
}
return Object.keys(obj).filter(function (key) {
return typeof obj[key] === 'string';
}).map(function (key) {
return urlEncode(key) + "=" + urlEncode(obj[key]);
}).join('&');
}
function extendQuery(originalQuery, props) {
if (props === void 0) {
props = {};
}
if (!props || !Object.keys(props).length) {
return originalQuery;
}
return formatQuery(_extends({}, parseQuery(originalQuery), {}, props));
}
function extendUrl(url, options) {
if (options === void 0) {
options = {};
}
var query = options.query || {};
var hash = options.hash || {};
var originalUrl;
var originalQuery;
var originalHash;
var _url$split = url.split('#');
originalUrl = _url$split[0];
originalHash = _url$split[1];
var _originalUrl$split = originalUrl.split('?');
originalUrl = _originalUrl$split[0];
originalQuery = _originalUrl$split[1];
var queryString = extendQuery(originalQuery, query);
var hashString = extendQuery(originalHash, hash);
if (queryString) {
originalUrl = originalUrl + "?" + queryString;
}
if (hashString) {
originalUrl = originalUrl + "#" + hashString;
}
return originalUrl;
}
function redirect(url, win) {
if (win === void 0) {
win = window;
}
return new promise_ZalgoPromise(function (resolve) {
win.location = url;
if (!urlWillRedirectPage(url)) {
resolve();
}
});
}
function hasMetaViewPort() {
var meta = document.querySelector('meta[name=viewport]');
if (isDevice() && window.screen.width < 660 && !meta) {
return false;
}
return true;
}
function isElementVisible(el) {
return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
}
function enablePerformance() {
return inlineMemoize(enablePerformance, function () {
/* eslint-disable compat/compat */
return Boolean(window.performance && performance.now && performance.timing && performance.timing.connectEnd && performance.timing.navigationStart && Math.abs(performance.now() - Date.now()) > 1000 && performance.now() - (performance.timing.connectEnd - performance.timing.navigationStart) > 0);
/* eslint-enable compat/compat */
});
}
function getPageRenderTime() {
return waitForDocumentReady().then(function () {
if (!enablePerformance()) {
return;
}
var timing = window.performance.timing;
if (timing.connectEnd && timing.domInteractive) {
return timing.domInteractive - timing.connectEnd;
}
});
}
function htmlEncode(html) {
if (html === void 0) {
html = '';
}
return html.toString().replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g, '/');
}
function dom_isBrowser() {
return typeof window !== 'undefined';
}
function querySelectorAll(selector, doc) {
if (doc === void 0) {
doc = window.document;
}
return Array.prototype.slice.call(doc.querySelectorAll(selector));
}
function onClick(element, handler) {
element.addEventListener('touchstart', src_util_noop);
element.addEventListener('click', handler);
element.addEventListener('keypress', function (event) {
// $FlowFixMe
if (event.keyCode === KEY_CODES.ENTER) {
return handler(event);
}
});
}
function getScript(_ref) {
var _ref$host = _ref.host,
host = _ref$host === void 0 ? window.location.host : _ref$host,
path = _ref.path;
return inlineMemoize(getScript, function () {
var url = "" + host + path;
var scripts = Array.prototype.slice.call(document.getElementsByTagName('script'));
for (var _i4 = 0; _i4 < scripts.length; _i4++) {
var script = scripts[_i4];
if (!script.src) {
continue;
}
var src = script.src.replace(/^https?:\/\//, '').split('?')[0];
if (src === url) {
return script;
}
}
}, [path]);
}
function isLocalStorageEnabled() {
return inlineMemoize(isLocalStorageEnabled, function () {
try {
if (typeof window === 'undefined') {
return false;
}
if (window.localStorage) {
var value = Math.random().toString();
window.localStorage.setItem('__test__localStorage__', value);
var result = window.localStorage.getItem('__test__localStorage__');
window.localStorage.removeItem('__test__localStorage__');
if (value === result) {
return true;
}
}
} catch (err) {// pass
}
return false;
});
}
function getBrowserLocales() {
var nav = window.navigator;
var locales = nav.languages ? Array.prototype.slice.apply(nav.languages) : [];
if (nav.language) {
locales.push(nav.language);
}
if (nav.userLanguage) {
locales.push(nav.userLanguage);
}
return locales.map(function (locale) {
if (locale && locale.match(/^[a-z]{2}[-_][A-Z]{2}$/)) {
var _locale$split = locale.split(/[-_]/),
lang = _locale$split[0],
country = _locale$split[1];
return {
country: country,
lang: lang
};
}
if (locale && locale.match(/^[a-z]{2}$/)) {
return {
lang: locale
};
}
return null;
}).filter(Boolean);
}
function appendChild(container, child) {
container.appendChild(child);
}
function isElement(element) {
if (element instanceof window.Element) {
return true;
}
if (element !== null && typeof element === 'object' && element.nodeType === 1 && typeof element.style === 'object' && typeof element.ownerDocument === 'object') {
return true;
}
return false;
}
function getElementSafe(id, doc) {
if (doc === void 0) {
doc = document;
}
if (isElement(id)) {
// $FlowFixMe
return id;
}
if (typeof id === 'string') {
return doc.querySelector(id);
}
}
function getElement(id, doc) {
if (doc === void 0) {
doc = document;
}
var element = getElementSafe(id, doc);
if (element) {
return element;
}
throw new Error("Can not find element: " + stringify(id));
}
function elementReady(id) {
return new promise_ZalgoPromise(function (resolve, reject) {
var name = stringify(id);
var el = getElementSafe(id);
if (el) {
return resolve(el);
}
if (isDocumentReady()) {
return reject(new Error("Document is ready and element " + name + " does not exist"));
}
var interval = setInterval(function () {
el = getElementSafe(id);
if (el) {
clearInterval(interval);
return resolve(el);
}
if (isDocumentReady()) {
clearInterval(interval);
return reject(new Error("Document is ready and element " + name + " does not exist"));
}
}, 10);
});
}
function PopupOpenError(message) {
this.message = message;
}
PopupOpenError.prototype = Object.create(Error.prototype);
function popup(url, options) {
// $FlowFixMe
options = options || {};
var _options = options,
width = _options.width,
height = _options.height;
var top = 0;
var left = 0;
if (width) {
if (window.outerWidth) {
left = Math.round((window.outerWidth - width) / 2) + window.screenX;
} else if (window.screen.width) {
left = Math.round((window.screen.width - width) / 2);
}
}
if (height) {
if (window.outerHeight) {
top = Math.round((window.outerHeight - height) / 2) + window.screenY;
} else if (window.screen.height) {
top = Math.round((window.screen.height - height) / 2);
}
}
if (width && height) {
options = _extends({
top: top,
left: left,
width: width,
height: height,
status: 1,
toolbar: 0,
menubar: 0,
resizable: 1,
scrollbars: 1
}, options);
}
var name = options.name || '';
delete options.name; // eslint-disable-next-line array-callback-return
var params = Object.keys(options).map(function (key) {
// $FlowFixMe
if (options[key] !== null && options[key] !== undefined) {
return key + "=" + stringify(options[key]);
}
}).filter(Boolean).join(',');
var win;
try {
win = window.open(url, name, params, true);
} catch (err) {
throw new PopupOpenError("Can not open popup window - " + (err.stack || err.message));
}
if (isWindowClosed(win)) {
var err = new PopupOpenError("Can not open popup window - blocked");
throw err;
}
window.addEventListener('unload', function () {
return win.close();
});
return win;
}
function writeToWindow(win, html) {
try {
win.document.open();
win.document.write(html);
win.document.close();
} catch (err) {
try {
win.location = "javascript: document.open(); document.write(" + JSON.stringify(html) + "); document.close();";
} catch (err2) {// pass
}
}
}
function writeElementToWindow(win, el) {
var tag = el.tagName.toLowerCase();
if (tag !== 'html') {
throw new Error("Expected element to be html, got " + tag);
}
var documentElement = win.document.documentElement;
for (var _i6 = 0, _arrayFrom2 = arrayFrom(documentElement.children); _i6 < _arrayFrom2.length; _i6++) {
var child = _arrayFrom2[_i6];
documentElement.removeChild(child);
}
for (var _i8 = 0, _arrayFrom4 = arrayFrom(el.children); _i8 < _arrayFrom4.length; _i8++) {
var _child = _arrayFrom4[_i8];
documentElement.appendChild(_child);
}
}
function setStyle(el, styleText, doc) {
if (doc === void 0) {
doc = window.document;
}
// $FlowFixMe
if (el.styleSheet) {
// $FlowFixMe
el.styleSheet.cssText = styleText;
} else {
el.appendChild(doc.createTextNode(styleText));
}
}
var awaitFrameLoadPromises;
function awaitFrameLoad(frame) {
awaitFrameLoadPromises = awaitFrameLoadPromises || new weakmap_CrossDomainSafeWeakMap();
if (awaitFrameLoadPromises.has(frame)) {
var _promise = awaitFrameLoadPromises.get(frame);
if (_promise) {
return _promise;
}
}
var promise = new promise_ZalgoPromise(function (resolve, reject) {
frame.addEventListener('load', function () {
linkFrameWindow(frame);
resolve(frame);
});
frame.addEventListener('error', function (err) {
if (frame.contentWindow) {
resolve(frame);
} else {
reject(err);
}
});
});
awaitFrameLoadPromises.set(frame, promise);
return promise;
}
function awaitFrameWindow(frame) {
return awaitFrameLoad(frame).then(function (loadedFrame) {
if (!loadedFrame.contentWindow) {
throw new Error("Could not find window in iframe");
}
return loadedFrame.contentWindow;
});
}
function createElement(tag, options, container) {
if (tag === void 0) {
tag = 'div';
}
if (options === void 0) {
options = {};
}
tag = tag.toLowerCase();
var element = document.createElement(tag);
if (options.style) {
extend(element.style, options.style);
}
if (options.class) {
element.className = options.class.join(' ');
}
if (options.id) {
element.setAttribute('id', options.id);
}
if (options.attributes) {
for (var _i10 = 0, _Object$keys2 = Object.keys(options.attributes); _i10 < _Object$keys2.length; _i10++) {
var key = _Object$keys2[_i10];
element.setAttribute(key, options.attributes[key]);
}
}
if (options.styleSheet) {
setStyle(element, options.styleSheet);
}
if (container) {
appendChild(container, element);
}
if (options.html) {
if (tag === 'iframe') {
// $FlowFixMe
if (!container || !element.contentWindow) {
throw new Error("Iframe html can not be written unless container provided and iframe in DOM");
} // $FlowFixMe
writeToWindow(element.contentWindow, options.html);
} else {
element.innerHTML = options.html;
}
}
return element;
}
function dom_iframe(options, container) {
if (options === void 0) {
options = {};
}
var attributes = options.attributes || {};
var style = options.style || {};
var frame = createElement('iframe', {
attributes: _extends({
allowTransparency: 'true'
}, attributes),
style: _extends({
backgroundColor: 'transparent',
border: 'none'
}, style),
html: options.html,
class: options.class
});
var isIE = window.navigator.userAgent.match(/MSIE|Edge/i);
if (!frame.hasAttribute('id')) {
frame.setAttribute('id', uniqueID());
} // $FlowFixMe
awaitFrameLoad(frame);
if (container) {
var el = getElement(container);
el.appendChild(frame);
}
if (options.url || isIE) {
frame.setAttribute('src', options.url || 'about:blank');
} // $FlowFixMe
return frame;
}
function addEventListener(obj, event, handler) {
obj.addEventListener(event, handler);
return {
cancel: function cancel() {
obj.removeEventListener(event, handler);
}
};
}
function bindEvents(element, eventNames, handler) {
handler = once(handler);
for (var _i12 = 0; _i12 < eventNames.length; _i12++) {
var eventName = eventNames[_i12];
element.addEventListener(eventName, handler);
}
return {
cancel: once(function () {
for (var _i14 = 0; _i14 < eventNames.length; _i14++) {
var _eventName = eventNames[_i14];
element.removeEventListener(_eventName, handler);
}
})
};
}
var VENDOR_PREFIXES = ['webkit', 'moz', 'ms', 'o'];
function setVendorCSS(element, name, value) {
// $FlowFixMe
element.style[name] = value;
var capitalizedName = capitalizeFirstLetter(name);
for (var _i16 = 0; _i16 < VENDOR_PREFIXES.length; _i16++) {
var prefix = VENDOR_PREFIXES[_i16];
// $FlowFixMe
element.style["" + prefix + capitalizedName] = value;
}
}
var ANIMATION_START_EVENTS = ['animationstart', 'webkitAnimationStart', 'oAnimationStart', 'MSAnimationStart'];
var ANIMATION_END_EVENTS = ['animationend', 'webkitAnimationEnd', 'oAnimationEnd', 'MSAnimationEnd'];
function animate(element, name, clean, timeout) {
if (timeout === void 0) {
timeout = 1000;
}
return new promise_ZalgoPromise(function (resolve, reject) {
var el = getElement(element);
if (!el) {
return resolve();
}
var hasStarted = false;
var startTimeout;
var endTimeout;
var startEvent;
var endEvent;
function cleanUp() {
clearTimeout(startTimeout);
clearTimeout(endTimeout);
startEvent.cancel();
endEvent.cancel();
}
startEvent = bindEvents(el, ANIMATION_START_EVENTS, function (event) {
// $FlowFixMe
if (event.target !== el || event.animationName !== name) {
return;
}
clearTimeout(startTimeout);
event.stopPropagation();
startEvent.cancel();
hasStarted = true;
endTimeout = setTimeout(function () {
cleanUp();
resolve();
}, timeout);
});
endEvent = bindEvents(el, ANIMATION_END_EVENTS, function (event) {
// $FlowFixMe
if (event.target !== el || event.animationName !== name) {
return;
}
cleanUp(); // $FlowFixMe
if (typeof event.animationName === 'string' && event.animationName !== name) {
return reject("Expected animation name to be " + name + ", found " + event.animationName);
}
return resolve();
});
setVendorCSS(el, 'animationName', name);
startTimeout = setTimeout(function () {
if (!hasStarted) {
cleanUp();
return resolve();
}
}, 200);
if (clean) {
clean(cleanUp);
}
});
}
var STYLE = {
DISPLAY: {
NONE: 'none',
BLOCK: 'block'
},
VISIBILITY: {
VISIBLE: 'visible',
HIDDEN: 'hidden'
},
IMPORTANT: 'important'
};
function makeElementVisible(element) {
element.style.setProperty('visibility', '');
}
function makeElementInvisible(element) {
element.style.setProperty('visibility', STYLE.VISIBILITY.HIDDEN, STYLE.IMPORTANT);
}
function showElement(element) {
element.style.setProperty('display', '');
}
function hideElement(element) {
element.style.setProperty('display', STYLE.DISPLAY.NONE, STYLE.IMPORTANT);
}
function destroyElement(element) {
if (element && element.parentNode) {
element.parentNode.removeChild(element);
}
}
function showAndAnimate(element, name, clean) {
var animation = animate(element, name, clean);
showElement(element);
return animation;
}
function animateAndHide(element, name, clean) {
return animate(element, name, clean).then(function () {
hideElement(element);
});
}
function addClass(element, name) {
element.classList.add(name);
}
function removeClass(element, name) {
element.classList.remove(name);
}
function isElementClosed(el) {
if (!el || !el.parentNode) {
return true;
}
return false;
}
function watchElementForClose(element, handler) {
handler = once(handler);
var interval;
if (isElementClosed(element)) {
handler();
} else {
interval = safeInterval(function () {
if (isElementClosed(element)) {
interval.cancel();
handler();
}
}, 50);
}
return {
cancel: function cancel() {
if (interval) {
interval.cancel();
}
}
};
}
function fixScripts(el, doc) {
if (doc === void 0) {
doc = window.document;
}
for (var _i18 = 0, _querySelectorAll2 = querySelectorAll('script', el); _i18 < _querySelectorAll2.length; _i18++) {
var script = _querySelectorAll2[_i18];
var parentNode = script.parentNode;
if (!parentNode) {
continue;
}
var newScript = doc.createElement('script');
newScript.text = script.textContent;
parentNode.replaceChild(newScript, script);
}
}
function onResize(el, handler, _temp) {
var _ref2 = _temp === void 0 ? {} : _temp,
_ref2$width = _ref2.width,
width = _ref2$width === void 0 ? true : _ref2$width,
_ref2$height = _ref2.height,
height = _ref2$height === void 0 ? true : _ref2$height,
_ref2$interval = _ref2.interval,
interval = _ref2$interval === void 0 ? 100 : _ref2$interval,
_ref2$win = _ref2.win,
win = _ref2$win === void 0 ? window : _ref2$win;
var currentWidth = el.offsetWidth;
var currentHeight = el.offsetHeight;
handler({
width: currentWidth,
height: currentHeight
});
var check = function check() {
var newWidth = el.offsetWidth;
var newHeight = el.offsetHeight;
if (width && newWidth !== currentWidth || height && newHeight !== currentHeight) {
handler({
width: newWidth,
height: newHeight
});
}
currentWidth = newWidth;
currentHeight = newHeight;
};
var observer;
var timeout;
if (typeof win.ResizeObserver !== 'undefined') {
observer = new win.ResizeObserver(check);
observer.observe(el);
} else if (typeof win.MutationObserver !== 'undefined') {
observer = new win.MutationObserver(check);
observer.observe(el, {
attributes: true,
childList: true,
subtree: true,
characterData: false
});
win.addEventListener('resize', check);
} else {
var loop = function loop() {
check();
timeout = setTimeout(loop, interval);
};
loop();
}
return {
cancel: function cancel() {
observer.disconnect();
window.removeEventListener('resize', check);
clearTimeout(timeout);
}
};
}
function getResourceLoadTime(url) {
if (!enablePerformance()) {
return;
}
if (!window.performance || typeof window.performance.getEntries !== 'function') {
return;
}
var entries = window.performance.getEntries();
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
if (entry && entry.name && entry.name.indexOf(url) === 0 && typeof entry.duration === 'number') {
return Math.floor(entry.duration);
}
}
}
// CONCATENATED MODULE: ./node_modules/belter/src/storage.js
var DEFAULT_SESSION_STORAGE = 20 * 60 * 1000;
function getStorage(_ref) {
var name = _ref.name,
_ref$lifetime = _ref.lifetime,
lifetime = _ref$lifetime === void 0 ? DEFAULT_SESSION_STORAGE : _ref$lifetime;
return inlineMemoize(getStorage, function () {
var STORAGE_KEY = "__" + name + "_storage__";
var accessedStorage;
function getState(handler) {
var localStorageEnabled = isLocalStorageEnabled();
var storage;
if (accessedStorage) {
storage = accessedStorage;
}
if (!storage && localStorageEnabled) {
var rawStorage = window.localStorage.getItem(STORAGE_KEY);
if (rawStorage) {
storage = JSON.parse(rawStorage);
}
}
if (!storage) {
storage = getGlobal()[STORAGE_KEY];
}
if (!storage) {
storage = {
id: uniqueID()
};
}
if (!storage.id) {
storage.id = uniqueID();
}
accessedStorage = storage;
var result = handler(storage);
if (localStorageEnabled) {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(storage));
} else {
getGlobal()[STORAGE_KEY] = storage;
}
accessedStorage = null;
return result;
}
function getID() {
return getState(function (storage) {
return storage.id;
});
}
function getSession(handler) {
return getState(function (storage) {
var session = storage.__session__;
var now = Date.now();
if (session && now - session.created > lifetime) {
session = null;
}
if (!session) {
session = {
guid: uniqueID(),
created: now
};
}
storage.__session__ = session;
return handler(session);
});
}
function getSessionState(handler) {
return getSession(function (session) {
session.state = session.state || {};
return handler(session.state);
});
}
function getSessionID() {
return getSession(function (session) {
return session.guid;
});
}
return {
getState: getState,
getID: getID,
getSessionState: getSessionState,
getSessionID: getSessionID
};
}, [{
name: name,
lifetime: lifetime
}]);
}
// CONCATENATED MODULE: ./node_modules/belter/src/experiment.js
function getBelterExperimentStorage() {
return getStorage({
name: 'belter_experiment'
});
}
function isEventUnique(name) {
return getBelterExperimentStorage().getSessionState(function (state) {
state.loggedBeacons = state.loggedBeacons || [];
if (state.loggedBeacons.indexOf(name) === -1) {
state.loggedBeacons.push(name);
return true;
}
return false;
});
}
function getThrottlePercentile(name) {
return getBelterExperimentStorage().getState(function (state) {
state.throttlePercentiles = state.throttlePercentiles || {};
state.throttlePercentiles[name] = state.throttlePercentiles[name] || Math.floor(Math.random() * 100);
return state.throttlePercentiles[name];
});
}
var THROTTLE_GROUP = {
TEST: 'test',
CONTROL: 'control',
THROTTLE: 'throttle'
};
function experiment(_ref) {
var name = _ref.name,
_ref$sample = _ref.sample,
sample = _ref$sample === void 0 ? 50 : _ref$sample,
_ref$logTreatment = _ref.logTreatment,
logTreatment = _ref$logTreatment === void 0 ? src_util_noop : _ref$logTreatment,
_ref$logCheckpoint = _ref.logCheckpoint,
logCheckpoint = _ref$logCheckpoint === void 0 ? src_util_noop : _ref$logCheckpoint;
var throttle = getThrottlePercentile(name);
var group;
if (throttle < sample) {
group = THROTTLE_GROUP.TEST;
} else if (sample >= 50 || sample <= throttle && throttle < sample * 2) {
group = THROTTLE_GROUP.CONTROL;
} else {
group = THROTTLE_GROUP.THROTTLE;
}
var treatment = name + "_" + group;
var started = false;
var forced = false;
try {
if (window.localStorage && window.localStorage.getItem(name)) {
forced = true;
}
} catch (err) {// pass
}
return {
isEnabled: function isEnabled() {
return group === THROTTLE_GROUP.TEST || forced;
},
isDisabled: function isDisabled() {
return group !== THROTTLE_GROUP.TEST && !forced;
},
getTreatment: function getTreatment() {
return treatment;
},
log: function log(checkpoint, payload) {
if (payload === void 0) {
payload = {};
}
if (!started) {
return this;
}
if (isEventUnique(name + "_" + treatment + "_" + JSON.stringify(payload))) {
logTreatment({
name: name,
treatment: treatment,
payload: payload
});
}
if (isEventUnique(name + "_" + treatment + "_" + checkpoint + "_" + JSON.stringify(payload))) {
logCheckpoint({
name: name,
treatment: treatment,
checkpoint: checkpoint,
payload: payload
});
}
return this;
},
logStart: function logStart(payload) {
if (payload === void 0) {
payload = {};
}
started = true;
return this.log("start", payload);
},
logComplete: function logComplete(payload) {
if (payload === void 0) {
payload = {};
}
return this.log("complete", payload);
}
};
}
// CONCATENATED MODULE: ./node_modules/belter/src/global.js
function getGlobalNameSpace(_ref) {
var name = _ref.name,
_ref$version = _ref.version,
version = _ref$version === void 0 ? 'latest' : _ref$version;
var global = getGlobal();
var globalKey = "__" + name + "__" + version + "_global__";
var namespace = global[globalKey] = global[globalKey] || {};
return {
get: function get(key, defValue) {
// $FlowFixMe
defValue = defValue || {};
var item = namespace[key] = namespace[key] || defValue;
return item;
}
};
}
// CONCATENATED MODULE: ./node_modules/belter/src/http.js
var HEADERS = {
CONTENT_TYPE: 'content-type',
ACCEPT: 'accept'
};
var headerBuilders = [];
function parseHeaders(rawHeaders) {
if (rawHeaders === void 0) {
rawHeaders = '';
}
var result = {};
for (var _i2 = 0, _rawHeaders$trim$spli2 = rawHeaders.trim().split('\n'); _i2 < _rawHeaders$trim$spli2.length; _i2++) {
var line = _rawHeaders$trim$spli2[_i2];
var _line$split = line.split(':'),
_key = _line$split[0],
values = _line$split.slice(1);
result[_key.toLowerCase()] = values.join(':').trim();
}
return result;
}
function request(_ref) {
var url = _ref.url,
_ref$method = _ref.method,
method = _ref$method === void 0 ? 'get' : _ref$method,
_ref$headers = _ref.headers,
headers = _ref$headers === void 0 ? {} : _ref$headers,
json = _ref.json,
data = _ref.data,
body = _ref.body,
_ref$win = _ref.win,
win = _ref$win === void 0 ? window : _ref$win,
_ref$timeout = _ref.timeout,
timeout = _ref$timeout === void 0 ? 0 : _ref$timeout;
return new promise_ZalgoPromise(function (resolve, reject) {
if (json && data || json && body || data && json) {
throw new Error("Only options.json or options.data or options.body should be passed");
}
var normalizedHeaders = {};
for (var _i4 = 0, _Object$keys2 = Object.keys(headers); _i4 < _Object$keys2.length; _i4++) {
var _key2 = _Object$keys2[_i4];
normalizedHeaders[_key2.toLowerCase()] = headers[_key2];
}
if (json) {
normalizedHeaders[HEADERS.CONTENT_TYPE] = normalizedHeaders[HEADERS.CONTENT_TYPE] || 'application/json';
} else if (data || body) {
normalizedHeaders[HEADERS.CONTENT_TYPE] = normalizedHeaders[HEADERS.CONTENT_TYPE] || 'application/x-www-form-urlencoded; charset=utf-8';
}
normalizedHeaders[HEADERS.ACCEPT] = normalizedHeaders[HEADERS.ACCEPT] || 'application/json';
for (var _i6 = 0; _i6 < headerBuilders.length; _i6++) {
var headerBuilder = headerBuilders[_i6];
var builtHeaders = headerBuilder();
for (var _i8 = 0, _Object$keys4 = Object.keys(builtHeaders); _i8 < _Object$keys4.length; _i8++) {
var _key3 = _Object$keys4[_i8];
normalizedHeaders[_key3.toLowerCase()] = builtHeaders[_key3];
}
}
var xhr = new win.XMLHttpRequest();
xhr.addEventListener('load', function xhrLoad() {
var responseHeaders = parseHeaders(this.getAllResponseHeaders());
if (!this.status) {
return reject(new Error("Request to " + method.toLowerCase() + " " + url + " failed: no response status code."));
}
var contentType = responseHeaders['content-type'];
var isJSON = contentType && (contentType.indexOf('application/json') === 0 || contentType.indexOf('text/json') === 0);
var responseBody = this.responseText;
try {
responseBody = JSON.parse(responseBody);
} catch (err) {
if (isJSON) {
return reject(new Error("Invalid json: " + this.responseText + "."));
}
}
var res = {
status: this.status,
headers: responseHeaders,
body: responseBody
};
return resolve(res);
}, false);
xhr.addEventListener('error', function (evt) {
reject(new Error("Request to " + method.toLowerCase() + " " + url + " failed: " + evt.toString() + "."));
}, false);
xhr.open(method, url, true);
for (var _key4 in normalizedHeaders) {
if (normalizedHeaders.hasOwnProperty(_key4)) {
xhr.setRequestHeader(_key4, normalizedHeaders[_key4]);
}
}
if (json) {
body = JSON.stringify(json);
} else if (data) {
body = Object.keys(data).map(function (key) {
return encodeURIComponent(key) + "=" + (data ? encodeURIComponent(data[key]) : '');
}).join('&');
}
xhr.timeout = timeout;
xhr.ontimeout = function xhrTimeout() {
reject(new Error("Request to " + method.toLowerCase() + " " + url + " has timed out"));
};
xhr.send(body);
});
}
function addHeaderBuilder(method) {
headerBuilders.push(method);
}
// CONCATENATED MODULE: ./node_modules/belter/src/types.js
// export something to force webpack to see this as an ES module
var types_TYPES = true;
// CONCATENATED MODULE: ./node_modules/belter/src/decorators.js
function memoized(target, name, descriptor) {
descriptor.value = memoize(descriptor.value, {
name: name,
thisNamespace: true
});
}
function decorators_promise(target, name, descriptor) {
descriptor.value = promisify(descriptor.value, {
name: name
});
}
// CONCATENATED MODULE: ./node_modules/belter/src/css.js
function isPerc(str) {
return typeof str === 'string' && /^[0-9]+%$/.test(str);
}
function isPx(str) {
return typeof str === 'string' && /^[0-9]+px$/.test(str);
}
function toNum(val) {
if (typeof val === 'number') {
return val;
}
var match = val.match(/^([0-9]+)(px|%)$/);
if (!match) {
throw new Error("Could not match css value from " + val);
}
return parseInt(match[1], 10);
}
function toPx(val) {
return toNum(val) + "px";
}
function toCSS(val) {
if (typeof val === 'number') {
return toPx(val);
}
return isPerc(val) ? val : toPx(val);
}
function percOf(num, perc) {
return parseInt(num * toNum(perc) / 100, 10);
}
function normalizeDimension(dim, max) {
if (typeof dim === 'number') {
return dim;
} else if (isPerc(dim)) {
return percOf(max, dim);
} else if (isPx(dim)) {
return toNum(dim);
} else {
throw new Error("Can not normalize dimension: " + dim);
}
}
// CONCATENATED MODULE: ./node_modules/belter/src/test.js
function wrapPromise(method, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$timeout = _ref.timeout,
timeout = _ref$timeout === void 0 ? 5000 : _ref$timeout;
var expected = [];
var promises = [];
var timer = setTimeout(function () {
if (expected.length) {
promises.push(promise_ZalgoPromise.asyncReject(new Error("Expected " + expected[0] + " to be called")));
}
}, timeout);
var expect = function expect(name, fn) {
if (fn === void 0) {
fn = src_util_noop;
}
expected.push(name); // $FlowFixMe
return function expectWrapper() {
var _this = this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
removeFromArray(expected, name); // $FlowFixMe
var _tryCatch = tryCatch(function () {
var _fn;
return (_fn = fn).call.apply(_fn, [_this].concat(args));
}),
result = _tryCatch.result,
error = _tryCatch.error;
if (error) {
promises.push(promise_ZalgoPromise.asyncReject(error));
throw error;
}
promises.push(promise_ZalgoPromise.resolve(result));
return result;
};
};
var avoid = function avoid(name, fn) {
if (fn === void 0) {
fn = src_util_noop;
}
// $FlowFixMe
return function avoidWrapper() {
var _fn2;
promises.push(promise_ZalgoPromise.asyncReject(new Error("Expected " + name + " to not be called"))); // $FlowFixMe
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return (_fn2 = fn).call.apply(_fn2, [this].concat(args));
};
};
var expectError = function expectError(name, fn) {
if (fn === void 0) {
fn = src_util_noop;
}
expected.push(name); // $FlowFixMe
return function expectErrorWrapper() {
var _this2 = this;
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
removeFromArray(expected, name); // $FlowFixMe
var _tryCatch2 = tryCatch(function () {
var _fn3;
return (_fn3 = fn).call.apply(_fn3, [_this2].concat(args));
}),
result = _tryCatch2.result,
error = _tryCatch2.error;
if (error) {
throw error;
}
promises.push(promise_ZalgoPromise.resolve(result).then(function () {
throw new Error("Expected " + name + " to throw an error");
}, src_util_noop));
return result;
};
};
promises.push(promise_ZalgoPromise.try(function () {
return method({
expect: expect,
avoid: avoid,
expectError: expectError,
error: avoid
});
}));
var drain = function drain() {
return promise_ZalgoPromise.try(function () {
if (promises.length) {
return promises.pop();
}
}).then(function () {
if (promises.length) {
return drain();
}
if (expected.length) {
return promise_ZalgoPromise.delay(10).then(drain);
}
});
};
return drain().then(function () {
clearTimeout(timer);
});
}
// CONCATENATED MODULE: ./node_modules/belter/src/index.js
// CONCATENATED MODULE: ./node_modules/post-robot/src/conf/config.js
var BRIDGE_TIMEOUT = 5000;
var CHILD_WINDOW_TIMEOUT = 5000;
var ACK_TIMEOUT = 2000;
var ACK_TIMEOUT_KNOWN = 10000;
var RES_TIMEOUT = false ? undefined : -1;
var RESPONSE_CYCLE_TIME = 500;
// CONCATENATED MODULE: ./node_modules/post-robot/src/conf/constants.js
var MESSAGE_TYPE = {
REQUEST: 'postrobot_message_request',
RESPONSE: 'postrobot_message_response',
ACK: 'postrobot_message_ack'
};
var MESSAGE_ACK = {
SUCCESS: 'success',
ERROR: 'error'
};
var MESSAGE_NAME = {
METHOD: 'postrobot_method',
HELLO: 'postrobot_hello',
OPEN_TUNNEL: 'postrobot_open_tunnel'
};
var SEND_STRATEGY = {
POST_MESSAGE: 'postrobot_post_message',
BRIDGE: 'postrobot_bridge',
GLOBAL: 'postrobot_global'
};
var BRIDGE_NAME_PREFIX = '__postrobot_bridge__';
var POSTROBOT_PROXY = '__postrobot_proxy__';
var constants_WILDCARD = '*';
var SERIALIZATION_TYPE = {
CROSS_DOMAIN_ZALGO_PROMISE: 'cross_domain_zalgo_promise',
CROSS_DOMAIN_FUNCTION: 'cross_domain_function',
CROSS_DOMAIN_WINDOW: 'cross_domain_window'
};
// CONCATENATED MODULE: ./node_modules/post-robot/src/conf/index.js
// CONCATENATED MODULE: ./node_modules/post-robot/src/global.js
function global_getGlobal(win) {
if (win === void 0) {
win = window;
}
if (win !== window) {
return win["__post_robot_10_0_29__"];
}
var global = win["__post_robot_10_0_29__"] = win["__post_robot_10_0_29__"] || {};
return global;
}
function deleteGlobal() {
delete window["__post_robot_10_0_29__"];
}
var getObj = function getObj() {
return {};
};
function globalStore(key, defStore) {
if (key === void 0) {
key = 'store';
}
if (defStore === void 0) {
defStore = getObj;
}
return util_getOrSet(global_getGlobal(), key, function () {
var store = defStore();
return {
has: function has(storeKey) {
return store.hasOwnProperty(storeKey);
},
get: function get(storeKey, defVal) {
// $FlowFixMe
return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal;
},
set: function set(storeKey, val) {
store[storeKey] = val;
return val;
},
del: function del(storeKey) {
delete store[storeKey];
},
getOrSet: function getOrSet(storeKey, getter) {
// $FlowFixMe
return util_getOrSet(store, storeKey, getter);
},
reset: function reset() {
store = defStore();
},
keys: function keys() {
return Object.keys(store);
}
};
});
}
var WildCard = function WildCard() {};
function getWildcard() {
var global = global_getGlobal();
global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard();
return global.WINDOW_WILDCARD;
}
function windowStore(key, defStore) {
if (key === void 0) {
key = 'store';
}
if (defStore === void 0) {
defStore = getObj;
}
return globalStore('windowStore').getOrSet(key, function () {
var winStore = new weakmap_CrossDomainSafeWeakMap();
var getStore = function getStore(win) {
return winStore.getOrSet(win, defStore);
};
return {
has: function has(win) {
var store = getStore(win);
return store.hasOwnProperty(key);
},
get: function get(win, defVal) {
var store = getStore(win); // $FlowFixMe
return store.hasOwnProperty(key) ? store[key] : defVal;
},
set: function set(win, val) {
var store = getStore(win);
store[key] = val;
return val;
},
del: function del(win) {
var store = getStore(win);
delete store[key];
},
getOrSet: function getOrSet(win, getter) {
var store = getStore(win);
return util_getOrSet(store, key, getter);
}
};
});
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/lib/hello.js
function getInstanceID() {
return globalStore('instance').getOrSet('instanceID', uniqueID);
}
function getHelloPromise(win) {
var helloPromises = windowStore('helloPromises');
return helloPromises.getOrSet(win, function () {
return new promise_ZalgoPromise();
});
}
function resolveHelloPromise(win, _ref) {
var domain = _ref.domain;
var helloPromises = windowStore('helloPromises');
var existingPromise = helloPromises.get(win);
if (existingPromise) {
existingPromise.resolve({
domain: domain
});
}
var newPromise = promise_ZalgoPromise.resolve({
domain: domain
});
helloPromises.set(win, newPromise);
return newPromise;
}
function listenForHello(_ref2) {
var on = _ref2.on;
return on(MESSAGE_NAME.HELLO, {
domain: constants_WILDCARD
}, function (_ref3) {
var source = _ref3.source,
origin = _ref3.origin;
resolveHelloPromise(source, {
domain: origin
});
return {
instanceID: getInstanceID()
};
});
}
function sayHello(win, _ref4) {
var send = _ref4.send;
return send(win, MESSAGE_NAME.HELLO, {
instanceID: getInstanceID()
}, {
domain: constants_WILDCARD,
timeout: -1
}).then(function (_ref5) {
var origin = _ref5.origin,
instanceID = _ref5.data.instanceID;
resolveHelloPromise(win, {
domain: origin
});
return {
win: win,
domain: origin,
instanceID: instanceID
};
});
}
function getWindowInstanceID(win, _ref6) {
var send = _ref6.send;
return windowStore('windowInstanceIDPromises').getOrSet(win, function () {
return sayHello(win, {
send: send
}).then(function (_ref7) {
var instanceID = _ref7.instanceID;
return instanceID;
});
});
}
function initHello(_ref8) {
var on = _ref8.on,
send = _ref8.send;
return globalStore('builtinListeners').getOrSet('helloListener', function () {
var listener = listenForHello({
on: on
});
var parent = getAncestor();
if (parent) {
sayHello(parent, {
send: send
}).catch(src_util_noop);
}
return listener;
});
}
function awaitWindowHello(win, timeout, name) {
if (timeout === void 0) {
timeout = 5000;
}
if (name === void 0) {
name = 'Window';
}
var promise = getHelloPromise(win);
if (timeout !== -1) {
promise = promise.timeout(timeout, new Error(name + " did not load after " + timeout + "ms"));
}
return promise;
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/lib/compat.js
function needsGlobalMessagingForBrowser() {
if (utils_getUserAgent(window).match(/MSIE|rv:11|trident|edge\/12|edge\/13/i)) {
return true;
}
return false;
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/lib/windows.js
function markWindowKnown(win) {
var knownWindows = windowStore('knownWindows');
knownWindows.set(win, true);
}
function isWindowKnown(win) {
var knownWindows = windowStore('knownWindows');
return knownWindows.get(win, false);
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/lib/index.js
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/constants.js
var TYPE = {
FUNCTION: 'function',
ERROR: 'error',
PROMISE: 'promise',
REGEX: 'regex',
DATE: 'date',
ARRAY: 'array',
OBJECT: 'object',
STRING: 'string',
NUMBER: 'number',
BOOLEAN: 'boolean',
NULL: 'null',
UNDEFINED: 'undefined'
};
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/common.js
function isSerializedType(item) {
return typeof item === 'object' && item !== null && typeof item.__type__ === 'string';
}
function determineType(val) {
if (typeof val === 'undefined') {
return TYPE.UNDEFINED;
}
if (val === null) {
return TYPE.NULL;
}
if (Array.isArray(val)) {
return TYPE.ARRAY;
}
if (typeof val === 'function') {
return TYPE.FUNCTION;
}
if (typeof val === 'object') {
if (val instanceof Error) {
return TYPE.ERROR;
}
if (typeof val.then === 'function') {
return TYPE.PROMISE;
}
if (Object.prototype.toString.call(val) === '[object RegExp]') {
return TYPE.REGEX;
}
if (Object.prototype.toString.call(val) === '[object Date]') {
return TYPE.DATE;
}
return TYPE.OBJECT;
}
if (typeof val === 'string') {
return TYPE.STRING;
}
if (typeof val === 'number') {
return TYPE.NUMBER;
}
if (typeof val === 'boolean') {
return TYPE.BOOLEAN;
}
}
function serializeType(type, val) {
return {
__type__: type,
__val__: val
};
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serializers/array.js
function serializeArray(val) {
return val;
}
function deserializeArray(val) {
return val;
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serializers/boolean.js
function serializeBoolean(val) {
return val;
}
function deserializeBoolean(val) {
return val;
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serializers/date.js
function serializeDate(val) {
return serializeType(TYPE.DATE, val.toJSON());
}
function deserializeDate(val) {
return new Date(val);
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serializers/error.js
// $FlowFixMe
function serializeError(_ref) {
var message = _ref.message,
stack = _ref.stack,
code = _ref.code;
return serializeType(TYPE.ERROR, {
message: message,
stack: stack,
code: code
});
}
function deserializeError(_ref2) {
var message = _ref2.message,
stack = _ref2.stack,
code = _ref2.code;
var error = new Error(message); // $FlowFixMe
error.code = code;
error.stack = stack + "\n\n" + error.stack;
return error;
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serializers/function.js
function serializeFunction() {// pass
}
function deserializeFunction() {
throw new Error("Function serialization is not implemented; nothing to deserialize");
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serializers/number.js
function serializeNumber(val) {
return val;
}
function deserializeNumber(val) {
return val;
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serializers/object.js
function serializeObject(val) {
return val;
}
function deserializeObject(val) {
return val;
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serializers/promise.js
function serializePromise() {// pass
}
function deserializePromise() {
throw new Error("Promise serialization is not implemented; nothing to deserialize");
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serializers/regex.js
function serializeRegex(val) {
return serializeType(TYPE.REGEX, val.source);
}
function deserializeRegex(val) {
// eslint-disable-next-line security/detect-non-literal-regexp
return new RegExp(val);
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serializers/string.js
function serializeString(val) {
return val;
}
function deserializeString(val) {
return val;
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serializers/null.js
function serializeNull(val) {
return val;
}
function deserializeNull(val) {
return val;
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serializers/index.js
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/serialize.js
var _SERIALIZER;
var SERIALIZER = (_SERIALIZER = {}, _SERIALIZER[TYPE.FUNCTION] = serializeFunction, _SERIALIZER[TYPE.ERROR] = serializeError, _SERIALIZER[TYPE.PROMISE] = serializePromise, _SERIALIZER[TYPE.REGEX] = serializeRegex, _SERIALIZER[TYPE.DATE] = serializeDate, _SERIALIZER[TYPE.ARRAY] = serializeArray, _SERIALIZER[TYPE.OBJECT] = serializeObject, _SERIALIZER[TYPE.STRING] = serializeString, _SERIALIZER[TYPE.NUMBER] = serializeNumber, _SERIALIZER[TYPE.BOOLEAN] = serializeBoolean, _SERIALIZER[TYPE.NULL] = serializeNull, _SERIALIZER); // $FlowFixMe
var defaultSerializers = {};
function serialize(obj, serializers) {
if (serializers === void 0) {
serializers = defaultSerializers;
}
function replacer(key) {
var val = this[key];
if (isSerializedType(this)) {
return val;
}
var type = determineType(val);
if (!type) {
return val;
} // $FlowFixMe
var serializer = serializers[type] || SERIALIZER[type];
if (!serializer) {
return val;
}
return serializer(val, key);
}
var result = JSON.stringify(obj, replacer);
if (typeof result === 'undefined') {
return TYPE.UNDEFINED;
}
return result;
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/deserialize.js
var _DESERIALIZER;
// $FlowFixMe
var DESERIALIZER = (_DESERIALIZER = {}, _DESERIALIZER[TYPE.FUNCTION] = deserializeFunction, _DESERIALIZER[TYPE.ERROR] = deserializeError, _DESERIALIZER[TYPE.PROMISE] = deserializePromise, _DESERIALIZER[TYPE.REGEX] = deserializeRegex, _DESERIALIZER[TYPE.DATE] = deserializeDate, _DESERIALIZER[TYPE.ARRAY] = deserializeArray, _DESERIALIZER[TYPE.OBJECT] = deserializeObject, _DESERIALIZER[TYPE.STRING] = deserializeString, _DESERIALIZER[TYPE.NUMBER] = deserializeNumber, _DESERIALIZER[TYPE.BOOLEAN] = deserializeBoolean, _DESERIALIZER[TYPE.NULL] = deserializeNull, _DESERIALIZER); // $FlowFixMe
var defaultDeserializers = {};
function deserialize_deserialize(str, deserializers) {
if (deserializers === void 0) {
deserializers = defaultDeserializers;
}
if (str === TYPE.UNDEFINED) {
// $FlowFixMe
return;
}
function replacer(key, val) {
if (isSerializedType(this)) {
return val;
}
var type;
var value;
if (isSerializedType(val)) {
type = val.__type__;
value = val.__val__;
} else {
type = determineType(val);
value = val;
}
if (!type) {
return value;
} // $FlowFixMe
var deserializer = deserializers[type] || DESERIALIZER[type];
if (!deserializer) {
return value;
}
return deserializer(value, key);
}
return JSON.parse(str, replacer);
}
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/types.js
// export something to force webpack to see this as an ES module
var src_types_TYPES = true; // eslint-disable-next-line flowtype/require-exact-type
// CONCATENATED MODULE: ./node_modules/universal-serialize/src/index.js
// CONCATENATED MODULE: ./node_modules/post-robot/src/bridge/bridge.js
function cleanTunnelWindows() {
var tunnelWindows = globalStore('tunnelWindows');
for (var _i2 = 0, _tunnelWindows$keys2 = tunnelWindows.keys(); _i2 < _tunnelWindows$keys2.length; _i2++) {
var key = _tunnelWindows$keys2[_i2];
var tunnelWindow = tunnelWindows[key];
try {
src_util_noop(tunnelWindow.source);
} catch (err) {
tunnelWindows.del(key);
continue;
}
if (isWindowClosed(tunnelWindow.source)) {
tunnelWindows.del(key);
}
}
}
function addTunnelWindow(_ref) {
var name = _ref.name,
source = _ref.source,
canary = _ref.canary,
sendMessage = _ref.sendMessage;
cleanTunnelWindows();
var id = uniqueID();
var tunnelWindows = globalStore('tunnelWindows');
tunnelWindows.set(id, {
name: name,
source: source,
canary: canary,
sendMessage: sendMessage
});
return id;
}
function setupOpenTunnelToParent(_ref2) {
var send = _ref2.send;
global_getGlobal(window).openTunnelToParent = function openTunnelToParent(_ref3) {
var name = _ref3.name,
source = _ref3.source,
canary = _ref3.canary,
sendMessage = _ref3.sendMessage;
var tunnelWindows = globalStore('tunnelWindows');
var parentWindow = getParent(window);
if (!parentWindow) {
throw new Error("No parent window found to open tunnel to");
}
var id = addTunnelWindow({
name: name,
source: source,
canary: canary,
sendMessage: sendMessage
});
return send(parentWindow, MESSAGE_NAME.OPEN_TUNNEL, {
name: name,
sendMessage: function sendMessage() {
var tunnelWindow = tunnelWindows.get(id);
try {
// IE gets antsy if you try to even reference a closed window
src_util_noop(tunnelWindow && tunnelWindow.source);
} catch (err) {
tunnelWindows.del(id);
return;
}
if (!tunnelWindow || !tunnelWindow.source || isWindowClosed(tunnelWindow.source)) {
return;
}
try {
tunnelWindow.canary();
} catch (err) {
return;
}
tunnelWindow.sendMessage.apply(this, arguments);
}
}, {
domain: constants_WILDCARD
});
};
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/bridge/common.js
function needsBridgeForBrowser() {
if (utils_getUserAgent(window).match(/MSIE|trident|edge\/12|edge\/13/i)) {
return true;
}
return false;
}
function needsBridgeForWin(win) {
if (!isSameTopWindow(window, win)) {
return true;
}
return false;
}
function needsBridgeForDomain(domain, win) {
if (domain) {
if (utils_getDomain() !== getDomainFromUrl(domain)) {
return true;
}
} else if (win) {
if (!isSameDomain(win)) {
return true;
}
}
return false;
}
function needsBridge(_ref) {
var win = _ref.win,
domain = _ref.domain;
if (!needsBridgeForBrowser()) {
return false;
}
if (domain && !needsBridgeForDomain(domain, win)) {
return false;
}
if (win && !needsBridgeForWin(win)) {
return false;
}
return true;
}
function getBridgeName(domain) {
domain = domain || getDomainFromUrl(domain);
var sanitizedDomain = domain.replace(/[^a-zA-Z0-9]+/g, '_');
var id = BRIDGE_NAME_PREFIX + "_" + sanitizedDomain;
return id;
}
function isBridge() {
return Boolean(window.name && window.name === getBridgeName(utils_getDomain()));
}
var documentBodyReady = new promise_ZalgoPromise(function (resolve) {
if (window.document && window.document.body) {
return resolve(window.document.body);
}
var interval = setInterval(function () {
if (window.document && window.document.body) {
clearInterval(interval);
return resolve(window.document.body);
}
}, 10);
});
function registerRemoteWindow(win) {
var remoteWindowPromises = windowStore('remoteWindowPromises');
remoteWindowPromises.getOrSet(win, function () {
return new promise_ZalgoPromise();
});
}
function findRemoteWindow(win) {
var remoteWindowPromises = windowStore('remoteWindowPromises');
var remoteWinPromise = remoteWindowPromises.get(win);
if (!remoteWinPromise) {
throw new Error("Remote window promise not found");
}
return remoteWinPromise;
}
function registerRemoteSendMessage(win, domain, sendMessage) {
var sendMessageWrapper = function sendMessageWrapper(remoteWin, remoteDomain, message) {
if (remoteWin !== win) {
throw new Error("Remote window does not match window");
}
if (!matchDomain(remoteDomain, domain)) {
throw new Error("Remote domain " + remoteDomain + " does not match domain " + domain);
}
sendMessage.fireAndForget(message);
};
findRemoteWindow(win).resolve(sendMessageWrapper);
}
function rejectRemoteSendMessage(win, err) {
findRemoteWindow(win).reject(err).catch(src_util_noop);
}
function sendBridgeMessage(win, domain, message) {
var messagingChild = isOpener(window, win);
var messagingParent = isOpener(win, window);
if (!messagingChild && !messagingParent) {
throw new Error("Can only send messages to and from parent and popup windows");
}
return findRemoteWindow(win).then(function (sendMessage) {
return sendMessage(win, domain, message);
});
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/bridge/child.js
function awaitRemoteBridgeForWindow(win) {
return windowStore('remoteBridgeAwaiters').getOrSet(win, function () {
return promise_ZalgoPromise.try(function () {
var frame = getFrameByName(win, getBridgeName(utils_getDomain()));
if (!frame) {
return;
}
if (isSameDomain(frame) && global_getGlobal(assertSameDomain(frame))) {
return frame;
}
return new promise_ZalgoPromise(function (resolve) {
var interval;
var timeout; // eslint-disable-line prefer-const
interval = setInterval(function () {
// eslint-disable-line prefer-const
if (frame && isSameDomain(frame) && global_getGlobal(assertSameDomain(frame))) {
clearInterval(interval);
clearTimeout(timeout);
return resolve(frame);
}
}, 100);
timeout = setTimeout(function () {
clearInterval(interval);
return resolve();
}, 2000);
});
});
});
}
function openTunnelToOpener(_ref) {
var on = _ref.on,
send = _ref.send,
receiveMessage = _ref.receiveMessage;
return promise_ZalgoPromise.try(function () {
var opener = getOpener(window);
if (!opener || !needsBridge({
win: opener
})) {
return;
}
registerRemoteWindow(opener);
return awaitRemoteBridgeForWindow(opener).then(function (bridge) {
if (!bridge) {
return rejectRemoteSendMessage(opener, new Error("Can not register with opener: no bridge found in opener"));
}
if (!window.name) {
return rejectRemoteSendMessage(opener, new Error("Can not register with opener: window does not have a name"));
}
return global_getGlobal(assertSameDomain(bridge)).openTunnelToParent({
name: window.name,
source: window,
canary: function canary() {// pass
},
sendMessage: function sendMessage(message) {
try {
src_util_noop(window);
} catch (err) {
return;
}
if (!window || window.closed) {
return;
}
try {
receiveMessage({
data: message,
origin: this.origin,
source: this.source
}, {
on: on,
send: send
});
} catch (err) {
promise_ZalgoPromise.reject(err);
}
}
}).then(function (_ref2) {
var source = _ref2.source,
origin = _ref2.origin,
data = _ref2.data;
if (source !== opener) {
throw new Error("Source does not match opener");
}
registerRemoteSendMessage(source, origin, data.sendMessage);
}).catch(function (err) {
rejectRemoteSendMessage(opener, err);
throw err;
});
});
});
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/bridge/parent.js
function listenForOpenTunnel(_ref) {
var on = _ref.on,
send = _ref.send,
receiveMessage = _ref.receiveMessage;
var popupWindowsByName = globalStore('popupWindowsByName');
on(MESSAGE_NAME.OPEN_TUNNEL, function (_ref2) {
var source = _ref2.source,
origin = _ref2.origin,
data = _ref2.data;
var bridgePromise = globalStore('bridges').get(origin);
if (!bridgePromise) {
throw new Error("Can not find bridge promise for domain " + origin);
}
return bridgePromise.then(function (bridge) {
if (source !== bridge) {
throw new Error("Message source does not matched registered bridge for domain " + origin);
}
if (!data.name) {
throw new Error("Register window expected to be passed window name");
}
if (!data.sendMessage) {
throw new Error("Register window expected to be passed sendMessage method");
}
if (!popupWindowsByName.has(data.name)) {
throw new Error("Window with name " + data.name + " does not exist, or was not opened by this window");
}
if (!popupWindowsByName.get(data.name).domain) {
throw new Error("We do not have a registered domain for window " + data.name);
}
if (popupWindowsByName.get(data.name).domain !== origin) {
throw new Error("Message origin " + origin + " does not matched registered window origin " + popupWindowsByName.get(data.name).domain);
}
registerRemoteSendMessage(popupWindowsByName.get(data.name).win, origin, data.sendMessage);
return {
sendMessage: function sendMessage(message) {
if (!window || window.closed) {
return;
}
var winDetails = popupWindowsByName.get(data.name);
if (!winDetails) {
return;
}
try {
receiveMessage({
data: message,
origin: winDetails.domain,
source: winDetails.win
}, {
on: on,
send: send
});
} catch (err) {
promise_ZalgoPromise.reject(err);
}
}
};
});
});
}
function openBridgeFrame(name, url) {
var iframe = document.createElement("iframe");
iframe.setAttribute("name", name);
iframe.setAttribute("id", name);
iframe.setAttribute("style", "display: none; margin: 0; padding: 0; border: 0px none; overflow: hidden;");
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("border", "0");
iframe.setAttribute("scrolling", "no");
iframe.setAttribute("allowTransparency", "true");
iframe.setAttribute("tabindex", "-1");
iframe.setAttribute("hidden", "true");
iframe.setAttribute("title", "");
iframe.setAttribute("role", "presentation");
iframe.src = url;
return iframe;
}
function hasBridge(url, domain) {
var bridges = globalStore('bridges');
return bridges.has(domain || getDomainFromUrl(url));
}
function parent_openBridge(url, domain) {
var bridges = globalStore('bridges');
var bridgeFrames = globalStore('bridgeFrames');
domain = domain || getDomainFromUrl(url);
return bridges.getOrSet(domain, function () {
return promise_ZalgoPromise.try(function () {
if (utils_getDomain() === domain) {
throw new Error("Can not open bridge on the same domain as current domain: " + domain);
}
var name = getBridgeName(domain);
var frame = getFrameByName(window, name);
if (frame) {
throw new Error("Frame with name " + name + " already exists on page");
}
var iframe = openBridgeFrame(name, url);
bridgeFrames.set(domain, iframe);
return documentBodyReady.then(function (body) {
body.appendChild(iframe);
var bridge = iframe.contentWindow;
return new promise_ZalgoPromise(function (resolve, reject) {
iframe.addEventListener('load', resolve);
iframe.addEventListener('error', reject);
}).then(function () {
return awaitWindowHello(bridge, BRIDGE_TIMEOUT, "Bridge " + url);
}).then(function () {
return bridge;
});
});
});
});
}
function linkWindow(_ref3) {
var win = _ref3.win,
name = _ref3.name,
domain = _ref3.domain;
var popupWindowsByName = globalStore('popupWindowsByName');
var popupWindowsByWin = windowStore('popupWindowsByWin');
for (var _i2 = 0, _popupWindowsByName$k2 = popupWindowsByName.keys(); _i2 < _popupWindowsByName$k2.length; _i2++) {
var winName = _popupWindowsByName$k2[_i2];
// $FlowFixMe
var _details = popupWindowsByName.get(winName);
if (!_details || isWindowClosed(_details.win)) {
popupWindowsByName.del(winName);
}
}
if (isWindowClosed(win)) {
return {
win: win,
name: name,
domain: domain
};
}
var details = popupWindowsByWin.getOrSet(win, function () {
if (!name) {
return {
win: win
};
}
return popupWindowsByName.getOrSet(name, function () {
return {
win: win,
name: name
};
});
});
if (details.win && details.win !== win) {
throw new Error("Different window already linked for window: " + (name || 'undefined'));
}
if (name) {
details.name = name;
popupWindowsByName.set(name, details);
}
if (domain) {
details.domain = domain;
registerRemoteWindow(win);
}
popupWindowsByWin.set(win, details);
return details;
}
function linkUrl(win, url) {
linkWindow({
win: win,
domain: getDomainFromUrl(url)
});
}
function listenForWindowOpen() {
var windowOpen = window.open;
window.open = function windowOpenWrapper(url, name, options, last) {
var win = windowOpen.call(this, normalizeMockUrl(url), name, options, last);
if (!win) {
return win;
}
linkWindow({
win: win,
name: name,
domain: url ? getDomainFromUrl(url) : null
});
return win;
};
}
function destroyBridges() {
var bridges = globalStore('bridges');
var bridgeFrames = globalStore('bridgeFrames');
for (var _i4 = 0, _bridgeFrames$keys2 = bridgeFrames.keys(); _i4 < _bridgeFrames$keys2.length; _i4++) {
var domain = _bridgeFrames$keys2[_i4];
var frame = bridgeFrames.get(domain);
if (frame && frame.parentNode) {
frame.parentNode.removeChild(frame);
}
}
bridgeFrames.reset();
bridges.reset();
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/bridge/setup.js
function setupBridge(_ref) {
var on = _ref.on,
send = _ref.send,
receiveMessage = _ref.receiveMessage;
listenForWindowOpen();
listenForOpenTunnel({
on: on,
send: send,
receiveMessage: receiveMessage
});
setupOpenTunnelToParent({
on: on,
send: send
});
openTunnelToOpener({
on: on,
send: send,
receiveMessage: receiveMessage
});
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/bridge/index.js
// CONCATENATED MODULE: ./node_modules/post-robot/src/serialize/window.js
function cleanupProxyWindows() {
var idToProxyWindow = globalStore('idToProxyWindow');
for (var _i2 = 0, _idToProxyWindow$keys2 = idToProxyWindow.keys(); _i2 < _idToProxyWindow$keys2.length; _i2++) {
var id = _idToProxyWindow$keys2[_i2];
// $FlowFixMe
if (idToProxyWindow.get(id).shouldClean()) {
idToProxyWindow.del(id);
}
}
}
function getSerializedWindow(winPromise, _ref) {
var send = _ref.send,
_ref$id = _ref.id,
id = _ref$id === void 0 ? uniqueID() : _ref$id;
var windowNamePromise = winPromise.then(function (win) {
if (isSameDomain(win)) {
return assertSameDomain(win).name;
}
});
return {
id: id,
getType: function getType() {
return winPromise.then(function (win) {
return getOpener(win) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME;
});
},
getInstanceID: memoizePromise(function () {
return winPromise.then(function (win) {
return getWindowInstanceID(win, {
send: send
});
});
}),
close: function close() {
return winPromise.then(closeWindow);
},
getName: function getName() {
return winPromise.then(function (win) {
if (isWindowClosed(win)) {
return;
}
if (isSameDomain(win)) {
return assertSameDomain(win).name;
}
return windowNamePromise;
});
},
focus: function focus() {
return winPromise.then(function (win) {
win.focus();
});
},
isClosed: function isClosed() {
return winPromise.then(function (win) {
return isWindowClosed(win);
});
},
setLocation: function setLocation(href) {
return winPromise.then(function (win) {
if (isSameDomain(win)) {
try {
if (win.location && typeof win.location.replace === 'function') {
// $FlowFixMe
win.location.replace(href);
return;
}
} catch (err) {// pass
}
}
win.location = href;
});
},
setName: function setName(name) {
return winPromise.then(function (win) {
if (true) {
linkWindow({
win: win,
name: name
});
}
var sameDomain = isSameDomain(win);
var frame = getFrameForWindow(win);
if (!sameDomain) {
throw new Error("Can not set name for cross-domain window: " + name);
}
assertSameDomain(win).name = name;
if (frame) {
frame.setAttribute('name', name);
}
windowNamePromise = promise_ZalgoPromise.resolve(name);
});
}
};
}
var window_ProxyWindow =
/*#__PURE__*/
function () {
function ProxyWindow(_ref2) {
var send = _ref2.send,
win = _ref2.win,
serializedWindow = _ref2.serializedWindow;
this.id = void 0;
this.isProxyWindow = true;
this.serializedWindow = void 0;
this.actualWindow = void 0;
this.actualWindowPromise = void 0;
this.send = void 0;
this.name = void 0;
this.actualWindowPromise = new promise_ZalgoPromise();
this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, {
send: send
});
globalStore('idToProxyWindow').set(this.getID(), this);
if (win) {
this.setWindow(win, {
send: send
});
}
}
var _proto = ProxyWindow.prototype;
_proto.getID = function getID() {
return this.serializedWindow.id;
};
_proto.getType = function getType() {
return this.serializedWindow.getType();
};
_proto.isPopup = function isPopup() {
return this.getType().then(function (type) {
return type === WINDOW_TYPE.POPUP;
});
};
_proto.setLocation = function setLocation(href) {
var _this = this;
return this.serializedWindow.setLocation(href).then(function () {
return _this;
});
};
_proto.getName = function getName() {
return this.serializedWindow.getName();
};
_proto.setName = function setName(name) {
var _this2 = this;
return this.serializedWindow.setName(name).then(function () {
return _this2;
});
};
_proto.close = function close() {
var _this3 = this;
return this.serializedWindow.close().then(function () {
return _this3;
});
};
_proto.focus = function focus() {
var _this4 = this;
var isPopupPromise = this.isPopup();
var getNamePromise = this.getName();
var reopenPromise = promise_ZalgoPromise.hash({
isPopup: isPopupPromise,
name: getNamePromise
}).then(function (_ref3) {
var isPopup = _ref3.isPopup,
name = _ref3.name;
if (isPopup && name) {
window.open('', name);
}
});
var focusPromise = this.serializedWindow.focus();
return promise_ZalgoPromise.all([reopenPromise, focusPromise]).then(function () {
return _this4;
});
};
_proto.isClosed = function isClosed() {
return this.serializedWindow.isClosed();
};
_proto.getWindow = function getWindow() {
return this.actualWindow;
};
_proto.setWindow = function setWindow(win, _ref4) {
var send = _ref4.send;
this.actualWindow = win;
this.actualWindowPromise.resolve(this.actualWindow);
this.serializedWindow = getSerializedWindow(this.actualWindowPromise, {
send: send,
id: this.getID()
});
windowStore('winToProxyWindow').set(win, this);
};
_proto.awaitWindow = function awaitWindow() {
return this.actualWindowPromise;
};
_proto.matchWindow = function matchWindow(win, _ref5) {
var _this5 = this;
var send = _ref5.send;
return promise_ZalgoPromise.try(function () {
if (_this5.actualWindow) {
return win === _this5.actualWindow;
}
return promise_ZalgoPromise.hash({
proxyInstanceID: _this5.getInstanceID(),
knownWindowInstanceID: getWindowInstanceID(win, {
send: send
})
}).then(function (_ref6) {
var proxyInstanceID = _ref6.proxyInstanceID,
knownWindowInstanceID = _ref6.knownWindowInstanceID;
var match = proxyInstanceID === knownWindowInstanceID;
if (match) {
_this5.setWindow(win, {
send: send
});
}
return match;
});
});
};
_proto.unwrap = function unwrap() {
return this.actualWindow || this;
};
_proto.getInstanceID = function getInstanceID() {
return this.serializedWindow.getInstanceID();
};
_proto.shouldClean = function shouldClean() {
return Boolean(this.actualWindow && isWindowClosed(this.actualWindow));
};
_proto.serialize = function serialize() {
return this.serializedWindow;
};
ProxyWindow.unwrap = function unwrap(win) {
return ProxyWindow.isProxyWindow(win) // $FlowFixMe
? win.unwrap() : win;
};
ProxyWindow.serialize = function serialize(win, _ref7) {
var send = _ref7.send;
cleanupProxyWindows();
return ProxyWindow.toProxyWindow(win, {
send: send
}).serialize();
};
ProxyWindow.deserialize = function deserialize(serializedWindow, _ref8) {
var send = _ref8.send;
cleanupProxyWindows();
return globalStore('idToProxyWindow').get(serializedWindow.id) || new ProxyWindow({
serializedWindow: serializedWindow,
send: send
});
};
ProxyWindow.isProxyWindow = function isProxyWindow(obj) {
// $FlowFixMe
return Boolean(obj && !isWindow(obj) && obj.isProxyWindow);
};
ProxyWindow.toProxyWindow = function toProxyWindow(win, _ref9) {
var send = _ref9.send;
cleanupProxyWindows();
if (ProxyWindow.isProxyWindow(win)) {
// $FlowFixMe
return win;
} // $FlowFixMe
var actualWindow = win;
return windowStore('winToProxyWindow').get(actualWindow) || new ProxyWindow({
win: actualWindow,
send: send
});
};
return ProxyWindow;
}();
function serializeWindow(destination, domain, win, _ref10) {
var send = _ref10.send;
return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW, window_ProxyWindow.serialize(win, {
send: send
}));
}
function deserializeWindow(source, origin, win, _ref11) {
var send = _ref11.send;
return window_ProxyWindow.deserialize(win, {
send: send
});
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/serialize/function.js
function addMethod(id, val, name, source, domain) {
var methodStore = windowStore('methodStore');
var proxyWindowMethods = globalStore('proxyWindowMethods');
if (window_ProxyWindow.isProxyWindow(source)) {
proxyWindowMethods.set(id, {
val: val,
name: name,
domain: domain,
source: source
});
} else {
proxyWindowMethods.del(id); // $FlowFixMe
var methods = methodStore.getOrSet(source, function () {
return {};
});
methods[id] = {
domain: domain,
name: name,
val: val,
source: source
};
}
}
function lookupMethod(source, id) {
var methodStore = windowStore('methodStore');
var proxyWindowMethods = globalStore('proxyWindowMethods');
var methods = methodStore.getOrSet(source, function () {
return {};
});
return methods[id] || proxyWindowMethods.get(id);
}
function listenForFunctionCalls(_ref) {
var on = _ref.on,
send = _ref.send;
return globalStore('builtinListeners').getOrSet('functionCalls', function () {
return on(MESSAGE_NAME.METHOD, {
domain: constants_WILDCARD
}, function (_ref2) {
var source = _ref2.source,
origin = _ref2.origin,
data = _ref2.data;
var id = data.id,
name = data.name;
var meth = lookupMethod(source, id);
if (!meth) {
throw new Error("Could not find method '" + name + "' with id: " + data.id + " in " + utils_getDomain(window));
}
var methodSource = meth.source,
domain = meth.domain,
val = meth.val;
return promise_ZalgoPromise.try(function () {
if (!matchDomain(domain, origin)) {
// $FlowFixMe
throw new Error("Method '" + data.name + "' domain " + JSON.stringify(util_isRegex(meth.domain) ? meth.domain.source : meth.domain) + " does not match origin " + origin + " in " + utils_getDomain(window));
}
if (window_ProxyWindow.isProxyWindow(methodSource)) {
// $FlowFixMe
return methodSource.matchWindow(source, {
send: send
}).then(function (match) {
if (!match) {
throw new Error("Method call '" + data.name + "' failed - proxy window does not match source in " + utils_getDomain(window));
}
});
}
}).then(function () {
return val.apply({
source: source,
origin: origin
}, data.args);
}, function (err) {
return promise_ZalgoPromise.try(function () {
if (val.onError) {
return val.onError(err);
}
}).then(function () {
// $FlowFixMe
if (err.stack) {
// $FlowFixMe
err.stack = "Remote call to " + name + "()\n\n" + err.stack;
}
throw err;
});
}).then(function (result) {
return {
result: result,
id: id,
name: name
};
});
});
});
}
function function_serializeFunction(destination, domain, val, key, _ref3) {
var on = _ref3.on,
send = _ref3.send;
listenForFunctionCalls({
on: on,
send: send
});
var id = val.__id__ || uniqueID();
destination = window_ProxyWindow.unwrap(destination);
var name = val.__name__ || val.name || key;
if (typeof name === 'string' && typeof name.indexOf === 'function' && name.indexOf('anonymous::') === 0) {
name = name.replace('anonymous::', key + "::");
}
if (window_ProxyWindow.isProxyWindow(destination)) {
addMethod(id, val, name, destination, domain); // $FlowFixMe
destination.awaitWindow().then(function (win) {
addMethod(id, val, name, win, domain);
});
} else {
addMethod(id, val, name, destination, domain);
}
return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION, {
id: id,
name: name
});
}
function function_deserializeFunction(source, origin, _ref4, _ref5) {
var id = _ref4.id,
name = _ref4.name;
var send = _ref5.send;
var getDeserializedFunction = function getDeserializedFunction(opts) {
if (opts === void 0) {
opts = {};
}
function crossDomainFunctionWrapper() {
var _arguments = arguments;
var originalStack;
if (false) {}
return window_ProxyWindow.toProxyWindow(source, {
send: send
}).awaitWindow().then(function (win) {
var meth = lookupMethod(win, id);
if (meth && meth.val !== crossDomainFunctionWrapper) {
return meth.val.apply({
source: window,
origin: utils_getDomain()
}, _arguments);
} else {
// $FlowFixMe
var options = {
domain: origin,
fireAndForget: opts.fireAndForget
};
var _args = Array.prototype.slice.call(_arguments);
return send(win, MESSAGE_NAME.METHOD, {
id: id,
name: name,
args: _args
}, options).then(function (res) {
if (!opts.fireAndForget) {
return res.data.result;
}
});
}
}).catch(function (err) {
// $FlowFixMe
if (false) {}
throw err;
});
}
crossDomainFunctionWrapper.__name__ = name;
crossDomainFunctionWrapper.__origin__ = origin;
crossDomainFunctionWrapper.__source__ = source;
crossDomainFunctionWrapper.__id__ = id;
crossDomainFunctionWrapper.origin = origin;
return crossDomainFunctionWrapper;
};
var crossDomainFunctionWrapper = getDeserializedFunction();
crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({
fireAndForget: true
});
return crossDomainFunctionWrapper;
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/serialize/promise.js
function promise_serializePromise(destination, domain, val, key, _ref) {
var on = _ref.on,
send = _ref.send;
return serializeType(SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE, {
then: function_serializeFunction(destination, domain, function (resolve, reject) {
return val.then(resolve, reject);
}, key, {
on: on,
send: send
})
});
}
function promise_deserializePromise(source, origin, _ref2) {
var then = _ref2.then;
return new promise_ZalgoPromise(then);
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/serialize/serialize.js
function serializeMessage(destination, domain, obj, _ref) {
var _serialize;
var on = _ref.on,
send = _ref.send;
return serialize(obj, (_serialize = {}, _serialize[TYPE.PROMISE] = function (val, key) {
return promise_serializePromise(destination, domain, val, key, {
on: on,
send: send
});
}, _serialize[TYPE.FUNCTION] = function (val, key) {
return function_serializeFunction(destination, domain, val, key, {
on: on,
send: send
});
}, _serialize[TYPE.OBJECT] = function (val) {
return isWindow(val) || window_ProxyWindow.isProxyWindow(val) ? serializeWindow(destination, domain, val, {
on: on,
send: send
}) : val;
}, _serialize));
}
function deserializeMessage(source, origin, message, _ref2) {
var _deserialize;
var on = _ref2.on,
send = _ref2.send;
return deserialize_deserialize(message, (_deserialize = {}, _deserialize[SERIALIZATION_TYPE.CROSS_DOMAIN_ZALGO_PROMISE] = function (serializedPromise) {
return promise_deserializePromise(source, origin, serializedPromise);
}, _deserialize[SERIALIZATION_TYPE.CROSS_DOMAIN_FUNCTION] = function (serializedFunction) {
return function_deserializeFunction(source, origin, serializedFunction, {
on: on,
send: send
});
}, _deserialize[SERIALIZATION_TYPE.CROSS_DOMAIN_WINDOW] = function (serializedWindow) {
return deserializeWindow(source, origin, serializedWindow, {
send: send
});
}, _deserialize));
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/serialize/index.js
// CONCATENATED MODULE: ./node_modules/post-robot/src/drivers/send/strategies.js
var SEND_MESSAGE_STRATEGIES = {};
SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.POST_MESSAGE] = function (win, serializedMessage, domain) {
if (false) {}
var domains;
if (Array.isArray(domain)) {
domains = domain;
} else if (typeof domain === 'string') {
domains = [domain];
} else {
domains = [constants_WILDCARD];
}
domains = domains.map(function (dom) {
if (false) { var windowDomain; }
if (dom.indexOf(PROTOCOL.FILE) === 0) {
return constants_WILDCARD;
}
return dom;
});
domains.forEach(function (dom) {
win.postMessage(serializedMessage, dom);
});
};
if (true) {
SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.BRIDGE] = function (win, serializedMessage, domain) {
if (!needsBridgeForBrowser() && !isBridge()) {
throw new Error("Bridge not needed for browser");
}
if (isSameDomain(win)) {
throw new Error("Post message through bridge disabled between same domain windows");
}
if (isSameTopWindow(window, win) !== false) {
throw new Error("Can only use bridge to communicate between two different windows, not between frames");
}
sendBridgeMessage(win, domain, serializedMessage);
};
}
if (true) {
SEND_MESSAGE_STRATEGIES[SEND_STRATEGY.GLOBAL] = function (win, serializedMessage) {
if (!needsGlobalMessagingForBrowser()) {
throw new Error("Global messaging not needed for browser");
}
if (!isSameDomain(win)) {
throw new Error("Post message through global disabled between different domain windows");
}
if (isSameTopWindow(window, win) !== false) {
throw new Error("Can only use global to communicate between two different windows, not between frames");
} // $FlowFixMe
var foreignGlobal = global_getGlobal(win);
if (!foreignGlobal) {
throw new Error("Can not find postRobot global on foreign window");
}
foreignGlobal.receiveMessage({
source: window,
origin: utils_getDomain(),
data: serializedMessage
});
};
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/drivers/send/index.js
function send_sendMessage(win, domain, message, _ref) {
var _serializeMessage;
var on = _ref.on,
send = _ref.send;
if (isWindowClosed(win)) {
throw new Error('Window is closed');
}
var serializedMessage = serializeMessage(win, domain, (_serializeMessage = {}, _serializeMessage["__post_robot_10_0_29__"] = _extends({
id: uniqueID(),
origin: utils_getDomain(window)
}, message), _serializeMessage), {
on: on,
send: send
});
var strategies = Object.keys(SEND_MESSAGE_STRATEGIES);
var errors = [];
for (var _i2 = 0; _i2 < strategies.length; _i2++) {
var strategyName = strategies[_i2];
try {
SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);
} catch (err) {
errors.push(err);
}
}
if (errors.length === strategies.length) {
throw new Error("All post-robot messaging strategies failed:\n\n" + errors.map(function (err, i) {
return i + ". " + stringifyError(err);
}).join('\n\n'));
}
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/drivers/listeners.js
function resetListeners() {
var responseListeners = globalStore('responseListeners');
var erroredResponseListeners = globalStore('erroredResponseListeners');
responseListeners.reset();
erroredResponseListeners.reset();
}
var __DOMAIN_REGEX__ = '__domain_regex__';
function addResponseListener(hash, listener) {
var responseListeners = globalStore('responseListeners');
responseListeners.set(hash, listener);
}
function getResponseListener(hash) {
var responseListeners = globalStore('responseListeners');
return responseListeners.get(hash);
}
function deleteResponseListener(hash) {
var responseListeners = globalStore('responseListeners');
responseListeners.del(hash);
}
function cancelResponseListeners() {
var responseListeners = globalStore('responseListeners');
for (var _i2 = 0, _responseListeners$ke2 = responseListeners.keys(); _i2 < _responseListeners$ke2.length; _i2++) {
var hash = _responseListeners$ke2[_i2];
var listener = responseListeners.get(hash);
if (listener) {
listener.cancelled = true;
}
responseListeners.del(hash);
}
}
function markResponseListenerErrored(hash) {
var erroredResponseListeners = globalStore('erroredResponseListeners');
erroredResponseListeners.set(hash, true);
}
function isResponseListenerErrored(hash) {
var erroredResponseListeners = globalStore('erroredResponseListeners');
return erroredResponseListeners.has(hash);
}
function getRequestListener(_ref) {
var name = _ref.name,
win = _ref.win,
domain = _ref.domain;
var requestListeners = windowStore('requestListeners');
if (win === constants_WILDCARD) {
win = null;
}
if (domain === constants_WILDCARD) {
domain = null;
}
if (!name) {
throw new Error("Name required to get request listener");
}
for (var _i4 = 0, _ref3 = [win, getWildcard()]; _i4 < _ref3.length; _i4++) {
var winQualifier = _ref3[_i4];
if (!winQualifier) {
continue;
}
var nameListeners = requestListeners.get(winQualifier);
if (!nameListeners) {
continue;
}
var domainListeners = nameListeners[name];
if (!domainListeners) {
continue;
}
if (domain && typeof domain === 'string') {
if (domainListeners[domain]) {
return domainListeners[domain];
}
if (domainListeners[__DOMAIN_REGEX__]) {
for (var _i6 = 0, _domainListeners$__DO2 = domainListeners[__DOMAIN_REGEX__]; _i6 < _domainListeners$__DO2.length; _i6++) {
var _domainListeners$__DO3 = _domainListeners$__DO2[_i6],
regex = _domainListeners$__DO3.regex,
listener = _domainListeners$__DO3.listener;
if (matchDomain(regex, domain)) {
return listener;
}
}
}
}
if (domainListeners[constants_WILDCARD]) {
return domainListeners[constants_WILDCARD];
}
}
}
function addRequestListener(_ref4, listener) {
var name = _ref4.name,
win = _ref4.win,
domain = _ref4.domain;
var requestListeners = windowStore('requestListeners');
if (!name || typeof name !== 'string') {
throw new Error("Name required to add request listener");
}
if (Array.isArray(win)) {
var listenersCollection = [];
for (var _i8 = 0, _win2 = win; _i8 < _win2.length; _i8++) {
var item = _win2[_i8];
listenersCollection.push(addRequestListener({
name: name,
domain: domain,
win: item
}, listener));
}
return {
cancel: function cancel() {
for (var _i10 = 0; _i10 < listenersCollection.length; _i10++) {
var cancelListener = listenersCollection[_i10];
cancelListener.cancel();
}
}
};
}
if (Array.isArray(domain)) {
var _listenersCollection = [];
for (var _i12 = 0, _domain2 = domain; _i12 < _domain2.length; _i12++) {
var _item = _domain2[_i12];
_listenersCollection.push(addRequestListener({
name: name,
win: win,
domain: _item
}, listener));
}
return {
cancel: function cancel() {
for (var _i14 = 0; _i14 < _listenersCollection.length; _i14++) {
var cancelListener = _listenersCollection[_i14];
cancelListener.cancel();
}
}
};
}
var existingListener = getRequestListener({
name: name,
win: win,
domain: domain
});
if (!win || win === constants_WILDCARD) {
win = getWildcard();
}
domain = domain || constants_WILDCARD;
if (existingListener) {
if (win && domain) {
throw new Error("Request listener already exists for " + name + " on domain " + domain.toString() + " for " + (win === getWildcard() ? 'wildcard' : 'specified') + " window");
} else if (win) {
throw new Error("Request listener already exists for " + name + " for " + (win === getWildcard() ? 'wildcard' : 'specified') + " window");
} else if (domain) {
throw new Error("Request listener already exists for " + name + " on domain " + domain.toString());
} else {
throw new Error("Request listener already exists for " + name);
}
}
var nameListeners = requestListeners.getOrSet(win, function () {
return {};
});
var domainListeners = util_getOrSet(nameListeners, name, function () {
return {};
});
var strDomain = domain.toString();
var regexListeners;
var regexListener;
if (util_isRegex(domain)) {
regexListeners = util_getOrSet(domainListeners, __DOMAIN_REGEX__, function () {
return [];
});
regexListener = {
regex: domain,
listener: listener
};
regexListeners.push(regexListener);
} else {
domainListeners[strDomain] = listener;
}
return {
cancel: function cancel() {
delete domainListeners[strDomain];
if (regexListener) {
regexListeners.splice(regexListeners.indexOf(regexListener, 1));
if (!regexListeners.length) {
delete domainListeners[__DOMAIN_REGEX__];
}
}
if (!Object.keys(domainListeners).length) {
delete nameListeners[name];
}
if (win && !Object.keys(nameListeners).length) {
requestListeners.del(win);
}
}
};
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/drivers/receive/types.js
var _RECEIVE_MESSAGE_TYPE;
var RECEIVE_MESSAGE_TYPES = (_RECEIVE_MESSAGE_TYPE = {}, _RECEIVE_MESSAGE_TYPE[MESSAGE_TYPE.REQUEST] = function (source, origin, message, _ref) {
var on = _ref.on,
send = _ref.send;
var options = getRequestListener({
name: message.name,
win: source,
domain: origin
});
var logName = message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string' ? message.data.name + "()" : message.name;
if (false) {}
function sendResponse(type, ack, response) {
if (response === void 0) {
response = {};
}
if (message.fireAndForget || isWindowClosed(source)) {
return;
}
if (false) {}
try {
// $FlowFixMe
send_sendMessage(source, origin, _extends({
type: type,
ack: ack,
hash: message.hash,
name: message.name
}, response), {
on: on,
send: send
});
} catch (err) {
throw new Error("Send response message failed for " + logName + " in " + utils_getDomain() + "\n\n" + stringifyError(err));
}
}
return promise_ZalgoPromise.all([sendResponse(MESSAGE_TYPE.ACK), promise_ZalgoPromise.try(function () {
if (!options) {
throw new Error("No handler found for post message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname);
}
if (!matchDomain(options.domain, origin)) {
throw new Error("Request origin " + origin + " does not match domain " + options.domain.toString());
}
var data = message.data;
return options.handler({
source: source,
origin: origin,
data: data
});
}).then(function (data) {
return sendResponse(MESSAGE_TYPE.RESPONSE, MESSAGE_ACK.SUCCESS, {
data: data
});
}, function (error) {
return sendResponse(MESSAGE_TYPE.RESPONSE, MESSAGE_ACK.ERROR, {
error: error
});
})]).then(src_util_noop).catch(function (err) {
if (options && options.handleError) {
return options.handleError(err);
} else {
throw err;
}
});
}, _RECEIVE_MESSAGE_TYPE[MESSAGE_TYPE.ACK] = function (source, origin, message) {
if (isResponseListenerErrored(message.hash)) {
return;
}
var options = getResponseListener(message.hash);
if (!options) {
throw new Error("No handler found for post message ack for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname);
}
try {
if (!matchDomain(options.domain, origin)) {
throw new Error("Ack origin " + origin + " does not match domain " + options.domain.toString());
}
if (source !== options.win) {
throw new Error("Ack source does not match registered window");
}
} catch (err) {
options.promise.reject(err);
}
options.ack = true;
}, _RECEIVE_MESSAGE_TYPE[MESSAGE_TYPE.RESPONSE] = function (source, origin, message) {
if (isResponseListenerErrored(message.hash)) {
return;
}
var options = getResponseListener(message.hash);
if (!options) {
throw new Error("No handler found for post message response for message: " + message.name + " from " + origin + " in " + window.location.protocol + "//" + window.location.host + window.location.pathname);
}
if (!matchDomain(options.domain, origin)) {
throw new Error("Response origin " + origin + " does not match domain " + stringifyDomainPattern(options.domain));
}
if (source !== options.win) {
throw new Error("Response source does not match registered window");
}
deleteResponseListener(message.hash);
var logName = message.name === MESSAGE_NAME.METHOD && message.data && typeof message.data.name === 'string' ? message.data.name + "()" : message.name;
if (message.ack === MESSAGE_ACK.ERROR) {
if (false) {}
options.promise.reject(message.error);
} else if (message.ack === MESSAGE_ACK.SUCCESS) {
if (false) {}
options.promise.resolve({
source: source,
origin: origin,
data: message.data
});
}
}, _RECEIVE_MESSAGE_TYPE);
// CONCATENATED MODULE: ./node_modules/post-robot/src/drivers/receive/index.js
function parseMessage(message, source, origin, _ref) {
var on = _ref.on,
send = _ref.send;
var parsedMessage;
try {
parsedMessage = deserializeMessage(source, origin, message, {
on: on,
send: send
});
} catch (err) {
return;
}
if (!parsedMessage) {
return;
}
if (typeof parsedMessage !== 'object' || parsedMessage === null) {
return;
}
parsedMessage = parsedMessage["__post_robot_10_0_29__"];
if (!parsedMessage || typeof parsedMessage !== 'object' || parsedMessage === null) {
return;
}
if (!parsedMessage.type || typeof parsedMessage.type !== 'string') {
return;
}
if (!RECEIVE_MESSAGE_TYPES[parsedMessage.type]) {
return;
}
return parsedMessage;
}
function receive_receiveMessage(event, _ref2) {
var on = _ref2.on,
send = _ref2.send;
var receivedMessages = globalStore('receivedMessages');
try {
if (!window || window.closed || !event.source) {
return;
}
} catch (err) {
return;
}
var source = event.source,
origin = event.origin,
data = event.data;
if (false) {}
var message = parseMessage(data, source, origin, {
on: on,
send: send
});
if (!message) {
return;
}
markWindowKnown(source);
if (receivedMessages.has(message.id)) {
return;
}
receivedMessages.set(message.id, true);
if (isWindowClosed(source) && !message.fireAndForget) {
return;
}
if (message.origin.indexOf(PROTOCOL.FILE) === 0) {
origin = PROTOCOL.FILE + "//";
}
RECEIVE_MESSAGE_TYPES[message.type](source, origin, message, {
on: on,
send: send
});
}
function setupGlobalReceiveMessage(_ref3) {
var on = _ref3.on,
send = _ref3.send;
var global = global_getGlobal();
global.receiveMessage = global.receiveMessage || function (message) {
return receive_receiveMessage(message, {
on: on,
send: send
});
};
}
function messageListener(event, _ref4) {
var on = _ref4.on,
send = _ref4.send;
try {
src_util_noop(event.source);
} catch (err) {
return;
}
var source = event.source || event.sourceElement;
var origin = event.origin || event.originalEvent && event.originalEvent.origin;
var data = event.data;
if (origin === 'null') {
origin = PROTOCOL.FILE + "//";
}
if (!source) {
return;
}
if (!origin) {
throw new Error("Post message did not have origin domain");
}
if (false) {}
receive_receiveMessage({
source: source,
origin: origin,
data: data
}, {
on: on,
send: send
});
}
function listenForMessages(_ref5) {
var on = _ref5.on,
send = _ref5.send;
return globalStore().getOrSet('postMessageListener', function () {
return addEventListener(window, 'message', function (event) {
// $FlowFixMe
messageListener(event, {
on: on,
send: send
});
});
});
}
function stopListenForMessages() {
var listener = globalStore().get('postMessageListener');
if (listener) {
listener.cancel();
}
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/drivers/index.js
// CONCATENATED MODULE: ./node_modules/post-robot/src/public/on.js
function on_on(name, options, handler) {
if (!name) {
throw new Error('Expected name');
}
if (typeof options === 'function') {
handler = options; // $FlowFixMe
options = {};
}
if (!handler) {
throw new Error('Expected handler');
}
options = options || {};
options.name = name;
options.handler = handler || options.handler;
var win = options.window;
var domain = options.domain;
var listenerOptions = {
handler: options.handler,
handleError: options.errorHandler || function (err) {
throw err;
},
window: win,
domain: domain || constants_WILDCARD,
name: name
};
var requestListener = addRequestListener({
name: name,
win: win,
domain: domain
}, listenerOptions);
return {
cancel: function cancel() {
requestListener.cancel();
}
};
}
function on_once(name, options, handler) {
// $FlowFixMe
options = options || {};
if (typeof options === 'function') {
handler = options; // $FlowFixMe
options = {};
}
var promise = new promise_ZalgoPromise();
var listener; // eslint-disable-line prefer-const
options.errorHandler = function (err) {
listener.cancel();
promise.reject(err);
};
listener = on_on(name, options, function (event) {
listener.cancel();
promise.resolve(event);
if (handler) {
return handler(event);
}
});
promise.cancel = listener.cancel;
return promise;
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/public/send.js
function validateOptions(name, win, domain) {
if (!name) {
throw new Error('Expected name');
}
if (domain) {
if (typeof domain !== 'string' && !Array.isArray(domain) && !util_isRegex(domain)) {
throw new TypeError("Expected domain to be a string, array, or regex");
}
}
if (isWindowClosed(win)) {
throw new Error('Target window is closed');
}
}
function normalizeDomain(win, targetDomain, actualDomain, _ref) {
var send = _ref.send;
if (typeof targetDomain === 'string') {
return promise_ZalgoPromise.resolve(targetDomain);
}
return promise_ZalgoPromise.try(function () {
return actualDomain || sayHello(win, {
send: send
}).then(function (_ref2) {
var domain = _ref2.domain;
return domain;
});
}).then(function (normalizedDomain) {
if (!matchDomain(targetDomain, targetDomain)) {
throw new Error("Domain " + stringify(targetDomain) + " does not match " + stringify(targetDomain));
}
return normalizedDomain;
});
}
var send_send = function send(win, name, data, options) {
options = options || {};
var domain = options.domain || constants_WILDCARD;
var responseTimeout = options.timeout || RES_TIMEOUT;
var childTimeout = options.timeout || CHILD_WINDOW_TIMEOUT;
var fireAndForget = options.fireAndForget || false; // $FlowFixMe
return promise_ZalgoPromise.try(function () {
validateOptions(name, win, domain);
if (isAncestor(window, win)) {
return awaitWindowHello(win, childTimeout);
}
}).then(function (_temp) {
var _ref3 = _temp === void 0 ? {} : _temp,
actualDomain = _ref3.domain;
return normalizeDomain(win, domain, actualDomain, {
send: send
});
}).then(function (targetDomain) {
domain = targetDomain;
var logName = name === MESSAGE_NAME.METHOD && data && typeof data.name === 'string' ? data.name + "()" : name;
if (false) {}
var promise = new promise_ZalgoPromise();
var hash = name + "_" + uniqueID();
if (!fireAndForget) {
var responseListener = {
name: name,
win: win,
domain: domain,
promise: promise
};
addResponseListener(hash, responseListener);
var reqPromises = windowStore('requestPromises').getOrSet(win, function () {
return [];
});
reqPromises.push(promise);
promise.catch(function () {
markResponseListenerErrored(hash);
deleteResponseListener(hash);
});
var totalAckTimeout = isWindowKnown(win) ? ACK_TIMEOUT_KNOWN : ACK_TIMEOUT;
var totalResTimeout = responseTimeout;
var ackTimeout = totalAckTimeout;
var resTimeout = totalResTimeout;
var interval = safeInterval(function () {
if (isWindowClosed(win)) {
return promise.reject(new Error("Window closed for " + name + " before " + (responseListener.ack ? 'response' : 'ack')));
}
if (responseListener.cancelled) {
return promise.reject(new Error("Response listener was cancelled for " + name));
}
ackTimeout = Math.max(ackTimeout - RESPONSE_CYCLE_TIME, 0);
if (resTimeout !== -1) {
resTimeout = Math.max(resTimeout - RESPONSE_CYCLE_TIME, 0);
}
if (!responseListener.ack && ackTimeout === 0) {
return promise.reject(new Error("No ack for postMessage " + logName + " in " + utils_getDomain() + " in " + totalAckTimeout + "ms"));
} else if (resTimeout === 0) {
return promise.reject(new Error("No response for postMessage " + logName + " in " + utils_getDomain() + " in " + totalResTimeout + "ms"));
}
}, RESPONSE_CYCLE_TIME);
promise.finally(function () {
interval.cancel();
reqPromises.splice(reqPromises.indexOf(promise, 1));
}).catch(src_util_noop);
}
try {
send_sendMessage(win, domain, {
type: MESSAGE_TYPE.REQUEST,
hash: hash,
name: name,
data: data,
fireAndForget: fireAndForget
}, {
on: on_on,
send: send
});
} catch (err) {
throw new Error("Send request message failed for " + logName + " in " + utils_getDomain() + "\n\n" + stringifyError(err));
}
return fireAndForget ? promise.resolve() : promise;
});
};
// CONCATENATED MODULE: ./node_modules/post-robot/src/public/index.js
// CONCATENATED MODULE: ./node_modules/post-robot/src/setup.js
function setup_serializeMessage(destination, domain, obj) {
return serializeMessage(destination, domain, obj, {
on: on_on,
send: send_send
});
}
function setup_deserializeMessage(source, origin, message) {
return deserializeMessage(source, origin, message, {
on: on_on,
send: send_send
});
}
function createProxyWindow(win) {
return new window_ProxyWindow({
send: send_send,
win: win
});
}
function setup_toProxyWindow(win) {
return window_ProxyWindow.toProxyWindow(win, {
send: send_send
});
}
function setup() {
if (!global_getGlobal().initialized) {
global_getGlobal().initialized = true;
setupGlobalReceiveMessage({
on: on_on,
send: send_send
});
listenForMessages({
on: on_on,
send: send_send
});
if (true) {
setupBridge({
on: on_on,
send: send_send,
receiveMessage: receive_receiveMessage
});
}
initHello({
on: on_on,
send: send_send
});
}
}
function setup_destroy() {
cancelResponseListeners();
stopListenForMessages();
deleteGlobal();
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/types.js
// export something to force webpack to see this as an ES module
var post_robot_src_types_TYPES = true; // eslint-disable-next-line flowtype/require-exact-type
// CONCATENATED MODULE: ./node_modules/post-robot/src/clean.js
function cleanUpWindow(win) {
var requestPromises = windowStore('requestPromises');
for (var _i2 = 0, _requestPromises$get2 = requestPromises.get(win, []); _i2 < _requestPromises$get2.length; _i2++) {
var promise = _requestPromises$get2[_i2];
promise.reject(new Error("Window cleaned up before response")).catch(src_util_noop);
}
}
// CONCATENATED MODULE: ./node_modules/post-robot/src/index.js
var src_bridge;
if (true) {
src_bridge = {
setupBridge: setupBridge,
openBridge: parent_openBridge,
linkWindow: linkWindow,
linkUrl: linkUrl,
isBridge: isBridge,
needsBridge: needsBridge,
needsBridgeForBrowser: needsBridgeForBrowser,
hasBridge: hasBridge,
needsBridgeForWin: needsBridgeForWin,
needsBridgeForDomain: needsBridgeForDomain,
destroyBridges: destroyBridges
};
}
if (false) {}
// CONCATENATED MODULE: ./src/lib/global.js
function lib_global_getGlobal(win) {
if (win === void 0) {
win = window;
}
if (!isSameDomain(win)) {
throw new Error("Can not get global for window on different domain");
}
if (!win["__zoid_9_0_36__"]) {
win["__zoid_9_0_36__"] = {};
}
return win["__zoid_9_0_36__"];
}
function destroyGlobal() {
delete window["__zoid_9_0_36__"];
}
// CONCATENATED MODULE: ./src/lib/serialize.js
function getProxyObject(obj) {
return {
get: function get() {
var _this = this;
return promise_ZalgoPromise.try(function () {
if (_this.source && _this.source !== window) {
throw new Error("Can not call get on proxy object from a remote window");
}
return obj;
});
}
};
}
// CONCATENATED MODULE: ./src/lib/index.js
// CONCATENATED MODULE: ./src/constants.js
var ZOID = "zoid";
var POST_MESSAGE = {
DELEGATE: ZOID + "_delegate",
ALLOW_DELEGATE: ZOID + "_allow_delegate"
};
var PROP_TYPE = {
STRING: "string",
OBJECT: "object",
FUNCTION: "function",
BOOLEAN: "boolean",
NUMBER: "number",
ARRAY: "array"
};
var INITIAL_PROPS = {
RAW: 'raw',
UID: 'uid'
};
var WINDOW_REFERENCES = {
OPENER: 'opener',
PARENT: 'parent',
GLOBAL: 'global'
};
var PROP_SERIALIZATION = {
JSON: 'json',
DOTIFY: 'dotify',
BASE64: 'base64'
};
var CONTEXT = WINDOW_TYPE;
var src_constants_WILDCARD = '*';
var DEFAULT_DIMENSIONS = {
WIDTH: '300px',
HEIGHT: '150px'
};
var EVENT = {
RENDER: 'zoid-render',
RENDERED: 'zoid-rendered',
DISPLAY: 'zoid-display',
ERROR: 'zoid-error',
CLOSE: 'zoid-close',
PROPS: 'zoid-props',
RESIZE: 'zoid-resize',
FOCUS: 'zoid-focus'
};
// CONCATENATED MODULE: ./src/child/props.js
function normalizeChildProp(component, props, key, value, helpers) {
// $FlowFixMe
var prop = component.getPropDefinition(key);
if (!prop) {
return value;
}
if (typeof prop.childDecorate === 'function') {
var close = helpers.close,
focus = helpers.focus,
onError = helpers.onError,
onProps = helpers.onProps,
resize = helpers.resize,
getParent = helpers.getParent,
getParentDomain = helpers.getParentDomain,
show = helpers.show,
hide = helpers.hide;
return prop.childDecorate({
value: value,
close: close,
focus: focus,
onError: onError,
onProps: onProps,
resize: resize,
getParent: getParent,
getParentDomain: getParentDomain,
show: show,
hide: hide
});
}
return value;
} // eslint-disable-next-line max-params
function normalizeChildProps(parentComponentWindow, component, props, origin, helpers, isUpdate) {
if (isUpdate === void 0) {
isUpdate = false;
}
var result = {};
for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) {
var key = _Object$keys2[_i2];
var prop = component.getPropDefinition(key);
if (prop && prop.sameDomain && (origin !== utils_getDomain(window) || !isSameDomain(parentComponentWindow))) {
continue;
} // $FlowFixMe
var value = normalizeChildProp(component, props, key, props[key], helpers);
result[key] = value;
if (prop && prop.alias && !result[prop.alias]) {
result[prop.alias] = value;
}
}
if (!isUpdate) {
for (var _i4 = 0, _component$getPropNam2 = component.getPropNames(); _i4 < _component$getPropNam2.length; _i4++) {
var _key = _component$getPropNam2[_i4];
if (!props.hasOwnProperty(_key)) {
result[_key] = normalizeChildProp(component, props, _key, props[_key], helpers);
}
}
} // $FlowFixMe
return result;
}
// CONCATENATED MODULE: ./src/child/window.js
function parseChildWindowName(windowName) {
return inlineMemoize(parseChildWindowName, function () {
if (!windowName) {
throw new Error("No window name");
}
var _windowName$split = windowName.split('__'),
zoidcomp = _windowName$split[1],
name = _windowName$split[2],
encodedPayload = _windowName$split[3];
if (zoidcomp !== ZOID) {
throw new Error("Window not rendered by zoid - got " + zoidcomp);
}
if (!name) {
throw new Error("Expected component name");
}
if (!encodedPayload) {
throw new Error("Expected encoded payload");
}
try {
return JSON.parse(base64decode(encodedPayload));
} catch (err) {
throw new Error("Can not decode window name payload: " + encodedPayload + ": " + stringifyError(err));
}
}, [windowName]);
}
function getChildPayload() {
try {
return parseChildWindowName(window.name);
} catch (err) {// pass
}
}
// CONCATENATED MODULE: ./src/child/index.js
/* eslint max-lines: 0 */
/* Child Component
---------------
This is the portion of code which runs inside the frame or popup window containing the component's implementation.
When the component author calls myComponent.attach(), it creates a new instance of ChildComponent, which is then
responsible for managing the state and messaging back up to the parent, and providing props for the component to
utilize.
*/
var child_ChildComponent =
/*#__PURE__*/
function () {
// eslint-disable-line flowtype/no-mutable-array
function ChildComponent(component) {
var _this = this;
this.component = void 0;
this.props = void 0;
this.context = void 0;
this.parent = void 0;
this.parentDomain = void 0;
this.parentComponentWindow = void 0;
this.onPropHandlers = void 0;
this.autoResize = void 0;
promise_ZalgoPromise.try(function () {
_this.component = component;
_this.onPropHandlers = [];
var childPayload = getChildPayload();
if (!childPayload) {
throw new Error("No child payload found");
}
if (childPayload.version !== "9_0_36") {
throw new Error("Parent window has zoid version " + childPayload.version + ", child window has version " + "9_0_36");
}
var parent = childPayload.parent,
parentDomain = childPayload.parentDomain,
exports = childPayload.exports,
context = childPayload.context,
props = childPayload.props;
_this.context = context;
_this.parentComponentWindow = _this.getParentComponentWindow(parent);
_this.parentDomain = parentDomain;
_this.parent = setup_deserializeMessage(_this.parentComponentWindow, parentDomain, exports);
_this.checkParentDomain(parentDomain);
var initialProps = _this.getPropsByRef(_this.parentComponentWindow, parentDomain, props);
_this.setProps(initialProps, parentDomain);
markWindowKnown(_this.parentComponentWindow);
_this.watchForClose();
return _this.parent.init(_this.buildExports());
}).then(function () {
return _this.watchForResize();
}).catch(function (err) {
_this.onError(err);
});
}
var _proto = ChildComponent.prototype;
_proto.getHelpers = function getHelpers() {
var _this2 = this;
return {
focus: function focus() {
return _this2.focus();
},
close: function close() {
return _this2.close();
},
resize: function resize(_ref) {
var width = _ref.width,
height = _ref.height;
return _this2.resize({
width: width,
height: height
});
},
onError: function onError(err) {
return _this2.onError(err);
},
onProps: function onProps(handler) {
return _this2.onProps(handler);
},
getParent: function getParent() {
return _this2.parentComponentWindow;
},
getParentDomain: function getParentDomain() {
return _this2.parentDomain;
},
show: function show() {
return _this2.show();
},
hide: function hide() {
return _this2.hide();
}
};
};
_proto.show = function show() {
return this.parent.show();
};
_proto.hide = function hide() {
return this.parent.hide();
};
_proto.checkParentDomain = function checkParentDomain(domain) {
if (!matchDomain(this.component.allowedParentDomains, domain)) {
throw new Error("Can not be rendered by domain: " + domain);
}
};
_proto.onProps = function onProps(handler) {
this.onPropHandlers.push(handler);
};
_proto.getPropsByRef = function getPropsByRef(parentComponentWindow, domain, _ref2) {
var type = _ref2.type,
value = _ref2.value,
uid = _ref2.uid;
var props;
if (type === INITIAL_PROPS.RAW) {
props = value;
} else if (type === INITIAL_PROPS.UID) {
if (!isSameDomain(parentComponentWindow)) {
throw new Error("Parent component window is on a different domain - expected " + utils_getDomain() + " - can not retrieve props");
}
var global = lib_global_getGlobal(parentComponentWindow);
props = assertExists('props', global && global.props[uid]);
}
if (!props) {
throw new Error("Could not find props");
}
return setup_deserializeMessage(parentComponentWindow, domain, props);
};
_proto.getParentComponentWindow = function getParentComponentWindow(ref) {
var type = ref.type;
if (type === WINDOW_REFERENCES.OPENER) {
return assertExists('opener', getOpener(window));
} else if (type === WINDOW_REFERENCES.PARENT && typeof ref.distance === 'number') {
return assertExists('parent', getNthParentFromTop(window, ref.distance));
} else if (type === WINDOW_REFERENCES.GLOBAL && ref.uid && typeof ref.uid === 'string') {
var uid = ref.uid;
var ancestor = getAncestor(window);
if (!ancestor) {
throw new Error("Can not find ancestor window");
}
for (var _i2 = 0, _getAllFramesInWindow2 = getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) {
var frame = _getAllFramesInWindow2[_i2];
if (isSameDomain(frame)) {
var global = lib_global_getGlobal(frame);
if (global && global.windows && global.windows[uid]) {
return global.windows[uid];
}
}
}
}
throw new Error("Unable to find " + type + " parent component window");
};
_proto.getProps = function getProps() {
// $FlowFixMe
this.props = this.props || {};
return this.props;
};
_proto.setProps = function setProps(props, origin, isUpdate) {
if (isUpdate === void 0) {
isUpdate = false;
}
var helpers = this.getHelpers();
var existingProps = this.getProps();
var normalizedProps = normalizeChildProps(this.parentComponentWindow, this.component, props, origin, helpers, isUpdate);
extend(existingProps, normalizedProps);
for (var _i4 = 0, _this$onPropHandlers2 = this.onPropHandlers; _i4 < _this$onPropHandlers2.length; _i4++) {
var handler = _this$onPropHandlers2[_i4];
handler.call(this, existingProps);
}
};
_proto.watchForClose = function watchForClose() {
var _this3 = this;
window.addEventListener('beforeunload', function () {
_this3.parent.checkClose.fireAndForget();
});
window.addEventListener('unload', function () {
_this3.parent.checkClose.fireAndForget();
});
onCloseWindow(this.parentComponentWindow, function () {
_this3.destroy();
});
};
_proto.getAutoResize = function getAutoResize() {
var _ref3 = this.autoResize || this.component.autoResize || {},
_ref3$width = _ref3.width,
width = _ref3$width === void 0 ? false : _ref3$width,
_ref3$height = _ref3.height,
height = _ref3$height === void 0 ? false : _ref3$height,
_ref3$element = _ref3.element,
element = _ref3$element === void 0 ? 'body' : _ref3$element;
element = getElementSafe(element);
return {
width: width,
height: height,
element: element
};
};
_proto.watchForResize = function watchForResize() {
var _this4 = this;
return waitForDocumentBody().then(function () {
var _this4$getAutoResize = _this4.getAutoResize(),
width = _this4$getAutoResize.width,
height = _this4$getAutoResize.height,
element = _this4$getAutoResize.element;
if (!element || !width && !height || _this4.context === CONTEXT.POPUP) {
return;
}
onResize(element, function (_ref4) {
var newWidth = _ref4.width,
newHeight = _ref4.height;
_this4.resize({
width: width ? newWidth : undefined,
height: height ? newHeight : undefined
});
}, {
width: width,
height: height
});
});
};
_proto.buildExports = function buildExports() {
var self = this;
return {
updateProps: function updateProps(props) {
var _this5 = this;
return promise_ZalgoPromise.try(function () {
return self.setProps(props, _this5.__origin__, true);
});
},
close: function close() {
return promise_ZalgoPromise.try(function () {
return self.destroy();
});
}
};
};
_proto.resize = function resize(_ref5) {
var width = _ref5.width,
height = _ref5.height;
return this.parent.resize.fireAndForget({
width: width,
height: height
});
};
_proto.close = function close() {
return this.parent.close();
};
_proto.destroy = function destroy() {
return promise_ZalgoPromise.try(function () {
window.close();
});
};
_proto.focus = function focus() {
return promise_ZalgoPromise.try(function () {
window.focus();
});
};
_proto.onError = function onError(err) {
var _this6 = this;
return promise_ZalgoPromise.try(function () {
if (_this6.parent && _this6.parent.onError) {
return _this6.parent.onError(err);
} else {
throw err;
}
});
};
return ChildComponent;
}();
// CONCATENATED MODULE: ./src/parent/drivers.js
var RENDER_DRIVERS = {};
RENDER_DRIVERS[CONTEXT.IFRAME] = {
openFrame: function openFrame(_ref) {
var windowName = _ref.windowName;
return getProxyObject(dom_iframe({
attributes: _extends({
name: windowName,
title: this.component.name
}, this.component.attributes.iframe)
}));
},
open: function open(_ref2) {
var _this = this;
var proxyFrame = _ref2.proxyFrame;
if (!proxyFrame) {
throw new Error("Expected proxy frame to be passed");
}
return proxyFrame.get().then(function (frame) {
return awaitFrameWindow(frame).then(function (win) {
var frameWatcher = watchElementForClose(frame, function () {
return _this.close();
});
_this.clean.register(function () {
return frameWatcher.cancel();
});
_this.clean.register(function () {
return destroyElement(frame);
});
_this.clean.register(function () {
return cleanUpWindow(win);
});
return win;
});
});
},
openPrerenderFrame: function openPrerenderFrame() {
return getProxyObject(dom_iframe({
attributes: _extends({
name: "__zoid_prerender_frame__" + this.component.name + "_" + uniqueID() + "__",
title: "prerender__" + this.component.name
}, this.component.attributes.iframe)
}));
},
openPrerender: function openPrerender(proxyWin, proxyPrerenderFrame) {
var _this2 = this;
if (!proxyPrerenderFrame) {
throw new Error("Expected proxy frame to be passed");
}
return proxyPrerenderFrame.get().then(function (prerenderFrame) {
_this2.clean.register(function () {
return destroyElement(prerenderFrame);
});
return awaitFrameWindow(prerenderFrame).then(function (prerenderFrameWindow) {
return assertSameDomain(prerenderFrameWindow);
}).then(function (win) {
return setup_toProxyWindow(win);
});
});
},
delegate: ['getProxyWindow', 'getProxyContainer', 'renderContainer', 'openFrame', 'openPrerenderFrame', 'prerender', 'open', 'openPrerender', 'show', 'hide']
};
if (true) {
RENDER_DRIVERS[CONTEXT.POPUP] = {
open: function open(_ref3) {
var _this3 = this;
var windowName = _ref3.windowName;
return promise_ZalgoPromise.try(function () {
var _this3$component$dime = _this3.component.dimensions,
width = _this3$component$dime.width,
height = _this3$component$dime.height;
width = normalizeDimension(width, window.outerWidth);
height = normalizeDimension(height, window.outerWidth);
var win = popup('', _extends({
name: windowName,
width: width,
height: height
}, _this3.component.attributes.popup));
_this3.clean.register(function () {
closeWindow(win);
cleanUpWindow(win);
});
return win;
});
},
openPrerender: function openPrerender(proxyWin) {
return promise_ZalgoPromise.try(function () {
return proxyWin;
});
},
delegate: ['getProxyContainer', 'renderContainer', 'setProxyWin', 'show', 'hide']
};
}
// CONCATENATED MODULE: ./src/parent/props.js
/* Normalize Props
---------------
Turn props into normalized values, using defaults, function options, etc.
*/
function extendProps(component, props, inputProps, helpers, isUpdate) {
if (isUpdate === void 0) {
isUpdate = false;
}
// eslint-disable-line complexity
// $FlowFixMe
inputProps = inputProps || {};
extend(props, inputProps);
var propNames = isUpdate ? [] : [].concat(component.getPropNames());
for (var _i2 = 0, _Object$keys2 = Object.keys(inputProps); _i2 < _Object$keys2.length; _i2++) {
var key = _Object$keys2[_i2];
if (propNames.indexOf(key) === -1) {
propNames.push(key);
}
}
var aliases = [];
var state = helpers.state,
close = helpers.close,
focus = helpers.focus,
event = helpers.event,
onError = helpers.onError;
for (var _i4 = 0; _i4 < propNames.length; _i4++) {
var _key = propNames[_i4];
var propDef = component.getPropDefinition(_key);
var value = inputProps[_key];
if (!propDef) {
continue;
}
var alias = propDef.alias;
if (alias) {
if (!isDefined(value) && isDefined(inputProps[alias])) {
value = inputProps[alias];
}
aliases.push(alias);
}
if (propDef.value) {
value = propDef.value({
props: props,
state: state,
close: close,
focus: focus,
event: event,
onError: onError
});
}
if (!isDefined(value) && propDef.default) {
value = propDef.default({
props: props,
state: state,
close: close,
focus: focus,
event: event,
onError: onError
});
}
if (isDefined(value)) {
if (propDef.type === 'array' ? !Array.isArray(value) : typeof value !== propDef.type) {
throw new TypeError("Prop is not of type " + propDef.type + ": " + _key);
}
} // $FlowFixMe
props[_key] = value;
}
for (var _i6 = 0; _i6 < aliases.length; _i6++) {
var _alias = aliases[_i6];
delete props[_alias];
} // $FlowFixMe
for (var _i8 = 0, _Object$keys4 = Object.keys(props); _i8 < _Object$keys4.length; _i8++) {
var _key2 = _Object$keys4[_i8];
var _propDef = component.getPropDefinition(_key2);
var _value = props[_key2];
if (!_propDef) {
continue;
}
if (isDefined(_value) && _propDef.validate) {
// $FlowFixMe
_propDef.validate({
value: _value,
props: props
});
}
if (isDefined(_value) && _propDef.decorate) {
props[_key2] = _propDef.decorate({
value: _value,
props: props,
state: state,
close: close,
focus: focus,
event: event,
onError: onError
});
}
}
for (var _i10 = 0, _component$getPropNam2 = component.getPropNames(); _i10 < _component$getPropNam2.length; _i10++) {
var _key3 = _component$getPropNam2[_i10];
var _propDef2 = component.getPropDefinition(_key3);
if (_propDef2.required !== false && !isDefined(props[_key3])) {
throw new Error("Expected prop \"" + _key3 + "\" to be defined");
}
}
} // $FlowFixMe
function props_getQueryParam(prop, key, value) {
return promise_ZalgoPromise.try(function () {
if (typeof prop.queryParam === 'function') {
return prop.queryParam({
value: value
});
} else if (typeof prop.queryParam === 'string') {
return prop.queryParam;
} else {
return key;
}
});
} // $FlowFixMe
function getQueryValue(prop, key, value) {
return promise_ZalgoPromise.try(function () {
if (typeof prop.queryValue === 'function' && isDefined(value)) {
return prop.queryValue({
value: value
});
} else {
return value;
}
});
}
function propsToQuery(propsDef, props) {
var params = {}; // $FlowFixMe
var keys = Object.keys(props);
return promise_ZalgoPromise.all(keys.map(function (key) {
var prop = propsDef[key];
if (!prop) {
return; // eslint-disable-line array-callback-return
}
return promise_ZalgoPromise.resolve().then(function () {
var value = props[key];
if (!value) {
return;
}
if (!prop.queryParam) {
return;
}
return value;
}).then(function (value) {
if (value === null || typeof value === 'undefined') {
return;
}
return promise_ZalgoPromise.all([props_getQueryParam(prop, key, value), getQueryValue(prop, key, value)]).then(function (_ref) {
var queryParam = _ref[0],
queryValue = _ref[1];
var result;
if (typeof queryValue === 'boolean') {
result = queryValue.toString();
} else if (typeof queryValue === 'string') {
result = queryValue.toString();
} else if (typeof queryValue === 'object' && queryValue !== null) {
if (prop.serialization === PROP_SERIALIZATION.JSON) {
result = JSON.stringify(queryValue);
} else if (prop.serialization === PROP_SERIALIZATION.BASE64) {
result = btoa(JSON.stringify(queryValue));
} else if (prop.serialization === PROP_SERIALIZATION.DOTIFY || !prop.serialization) {
result = dotify(queryValue, key);
for (var _i12 = 0, _Object$keys6 = Object.keys(result); _i12 < _Object$keys6.length; _i12++) {
var dotkey = _Object$keys6[_i12];
params[dotkey] = result[dotkey];
}
return;
}
} else if (typeof queryValue === 'number') {
result = queryValue.toString();
}
params[queryParam] = result;
});
});
})).then(function () {
return params;
});
}
// CONCATENATED MODULE: ./src/parent/index.js
/* eslint max-lines: 0 */
var parent_ParentComponent =
/*#__PURE__*/
function () {
// eslint-disable-line flowtype/no-mutable-array
function ParentComponent(component, props) {
var _this = this;
this.component = void 0;
this.driver = void 0;
this.clean = void 0;
this.event = void 0;
this.initPromise = void 0;
this.handledErrors = void 0;
this.props = void 0;
this.state = void 0;
this.child = void 0;
this.proxyContainer = void 0;
this.proxyWin = void 0;
this.visible = true;
this.initPromise = new promise_ZalgoPromise();
this.handledErrors = []; // $FlowFixMe
this.props = {};
this.clean = cleanup(this);
this.state = {};
this.component = component;
this.setupEvents(props.onError);
this.setProps(props);
this.component.registerActiveComponent(this);
this.clean.register(function () {
return _this.component.destroyActiveComponent(_this);
});
this.watchForUnload();
}
var _proto = ParentComponent.prototype;
_proto.setupEvents = function setupEvents(onError) {
var _this2 = this;
this.event = eventEmitter();
this.event.on(EVENT.RENDER, function () {
return _this2.props.onRender();
});
this.event.on(EVENT.DISPLAY, function () {
return _this2.props.onDisplay();
});
this.event.on(EVENT.RENDERED, function () {
return _this2.props.onRendered();
});
this.event.on(EVENT.CLOSE, function () {
return _this2.props.onClose();
});
this.event.on(EVENT.RESIZE, function () {
return _this2.props.onResize();
});
this.event.on(EVENT.FOCUS, function () {
return _this2.props.onFocus();
});
this.event.on(EVENT.PROPS, function (props) {
return _this2.props.onProps(props);
});
this.event.on(EVENT.ERROR, function (err) {
if (_this2.props && _this2.props.onError) {
return _this2.props.onError(err);
} else if (onError) {
return onError(err);
} else {
return _this2.initPromise.reject(err).then(function () {
setTimeout(function () {
throw err;
}, 1);
});
}
});
this.clean.register(function () {
return _this2.event.reset();
});
};
_proto.render = function render(target, container, context) {
var _this3 = this;
return promise_ZalgoPromise.try(function () {
_this3.component.log("render");
_this3.driver = RENDER_DRIVERS[context];
var uid = ZOID + "-" + _this3.component.tag + "-" + uniqueID();
var domain = _this3.getDomain();
var childDomain = _this3.getChildDomain();
_this3.component.checkAllowRender(target, domain, container);
if (target !== window) {
_this3.delegate(context, target);
}
var windowProp = _this3.props.window;
var init = _this3.initPromise;
var buildUrl = _this3.buildUrl();
var onRender = _this3.event.trigger(EVENT.RENDER);
var getProxyContainer = _this3.getProxyContainer(container);
var getProxyWindow = _this3.getProxyWindow();
var buildWindowName = getProxyWindow.then(function (proxyWin) {
return _this3.buildWindowName({
proxyWin: proxyWin,
childDomain: childDomain,
domain: domain,
target: target,
context: context,
uid: uid
});
});
var openFrame = buildWindowName.then(function (windowName) {
return _this3.openFrame({
windowName: windowName
});
});
var openPrerenderFrame = _this3.openPrerenderFrame();
var renderContainer = promise_ZalgoPromise.hash({
proxyContainer: getProxyContainer,
proxyFrame: openFrame,
proxyPrerenderFrame: openPrerenderFrame
}).then(function (_ref) {
var proxyContainer = _ref.proxyContainer,
proxyFrame = _ref.proxyFrame,
proxyPrerenderFrame = _ref.proxyPrerenderFrame;
return _this3.renderContainer(proxyContainer, {
context: context,
uid: uid,
proxyFrame: proxyFrame,
proxyPrerenderFrame: proxyPrerenderFrame,
visible: _this3.visible
});
}).then(function (proxyContainer) {
_this3.proxyContainer = proxyContainer;
return proxyContainer;
});
var open = promise_ZalgoPromise.hash({
windowName: buildWindowName,
proxyFrame: openFrame,
proxyWin: getProxyWindow
}).then(function (_ref2) {
var windowName = _ref2.windowName,
proxyWin = _ref2.proxyWin,
proxyFrame = _ref2.proxyFrame;
return windowProp ? proxyWin : _this3.open({
windowName: windowName,
proxyWin: proxyWin,
proxyFrame: proxyFrame
});
});
var openPrerender = promise_ZalgoPromise.hash({
proxyWin: open,
proxyPrerenderFrame: openPrerenderFrame
}).then(function (_ref3) {
var proxyWin = _ref3.proxyWin,
proxyPrerenderFrame = _ref3.proxyPrerenderFrame;
return _this3.openPrerender(proxyWin, proxyPrerenderFrame);
});
var setState = open.then(function (proxyWin) {
_this3.proxyWin = proxyWin;
return _this3.setProxyWin(proxyWin);
});
var prerender = promise_ZalgoPromise.hash({
proxyPrerenderWin: openPrerender,
state: setState
}).then(function (_ref4) {
var proxyPrerenderWin = _ref4.proxyPrerenderWin;
return _this3.prerender(proxyPrerenderWin, {
context: context,
uid: uid
});
});
var setWindowName = promise_ZalgoPromise.hash({
proxyWin: open,
windowName: buildWindowName
}).then(function (_ref5) {
var proxyWin = _ref5.proxyWin,
windowName = _ref5.windowName;
if (windowProp) {
return proxyWin.setName(windowName);
}
});
var loadUrl = promise_ZalgoPromise.hash({
proxyWin: open,
url: buildUrl,
windowName: setWindowName,
prerender: prerender
}).then(function (_ref6) {
var proxyWin = _ref6.proxyWin,
url = _ref6.url;
return proxyWin.setLocation(url);
});
var watchForClose = open.then(function (proxyWin) {
_this3.watchForClose(proxyWin);
});
var onDisplay = promise_ZalgoPromise.hash({
container: renderContainer,
prerender: prerender
}).then(function () {
return _this3.event.trigger(EVENT.DISPLAY);
});
var openBridge = open.then(function (proxyWin) {
return _this3.openBridge(proxyWin, childDomain, context);
});
var runTimeout = loadUrl.then(function () {
return _this3.runTimeout();
});
var onRendered = init.then(function () {
return _this3.event.trigger(EVENT.RENDERED);
});
return promise_ZalgoPromise.hash({
init: init,
buildUrl: buildUrl,
onRender: onRender,
getProxyContainer: getProxyContainer,
openFrame: openFrame,
openPrerenderFrame: openPrerenderFrame,
renderContainer: renderContainer,
open: open,
openPrerender: openPrerender,
setState: setState,
prerender: prerender,
loadUrl: loadUrl,
buildWindowName: buildWindowName,
setWindowName: setWindowName,
watchForClose: watchForClose,
onDisplay: onDisplay,
openBridge: openBridge,
runTimeout: runTimeout,
onRendered: onRendered
});
}).catch(function (err) {
return promise_ZalgoPromise.all([_this3.onError(err), _this3.destroy(err)]).then(function () {
throw err;
}, function () {
throw err;
});
}).then(src_util_noop);
};
_proto.getProxyWindow = function getProxyWindow() {
var _this4 = this;
return promise_ZalgoPromise.try(function () {
var windowProp = _this4.props.window;
if (windowProp) {
var proxyWin = setup_toProxyWindow(windowProp);
_this4.clean.register(function () {
return windowProp.close();
});
return proxyWin;
}
return new window_ProxyWindow({
send: send_send
});
});
};
_proto.getProxyContainer = function getProxyContainer(container) {
return promise_ZalgoPromise.try(function () {
return elementReady(container);
}).then(function (containerElement) {
return getProxyObject(containerElement);
});
};
_proto.buildWindowName = function buildWindowName(_ref7) {
var proxyWin = _ref7.proxyWin,
childDomain = _ref7.childDomain,
domain = _ref7.domain,
target = _ref7.target,
uid = _ref7.uid,
context = _ref7.context;
var childPayload = this.buildChildPayload({
proxyWin: proxyWin,
childDomain: childDomain,
domain: domain,
target: target,
context: context,
uid: uid
});
return "__" + ZOID + "__" + this.component.name + "__" + base64encode(JSON.stringify(childPayload)) + "__";
};
_proto.getPropsRef = function getPropsRef(proxyWin, childDomain, domain, uid) {
var value = setup_serializeMessage(proxyWin, domain, this.getPropsForChild(domain));
var propRef = childDomain === utils_getDomain() ? {
type: INITIAL_PROPS.UID,
uid: uid
} : {
type: INITIAL_PROPS.RAW,
value: value
};
if (propRef.type === INITIAL_PROPS.UID) {
var global = lib_global_getGlobal(window);
global.props = global.props || {};
global.props[uid] = value;
this.clean.register(function () {
delete global.props[uid];
});
}
return propRef;
};
_proto.buildChildPayload = function buildChildPayload(_temp) {
var _ref8 = _temp === void 0 ? {} : _temp,
proxyWin = _ref8.proxyWin,
childDomain = _ref8.childDomain,
domain = _ref8.domain,
_ref8$target = _ref8.target,
target = _ref8$target === void 0 ? window : _ref8$target,
context = _ref8.context,
uid = _ref8.uid;
return {
uid: uid,
context: context,
version: "9_0_36",
childDomain: childDomain,
parentDomain: utils_getDomain(window),
tag: this.component.tag,
parent: this.getWindowRef(target, childDomain, uid, context),
props: this.getPropsRef(proxyWin, childDomain, domain, uid),
exports: setup_serializeMessage(proxyWin, domain, this.buildParentExports(proxyWin))
};
};
_proto.setProxyWin = function setProxyWin(proxyWin) {
var _this5 = this;
return promise_ZalgoPromise.try(function () {
_this5.proxyWin = proxyWin;
});
};
_proto.getHelpers = function getHelpers() {
var _this6 = this;
return {
state: this.state,
event: this.event,
close: function close() {
return _this6.close();
},
focus: function focus() {
return _this6.focus();
},
resize: function resize(_ref9) {
var width = _ref9.width,
height = _ref9.height;
return _this6.resize({
width: width,
height: height
});
},
onError: function onError(err) {
return _this6.onError(err);
},
updateProps: function updateProps(props) {
return _this6.updateProps(props);
},
show: function show() {
return _this6.show();
},
hide: function hide() {
return _this6.hide();
}
};
};
_proto.show = function show() {
var _this7 = this;
return promise_ZalgoPromise.try(function () {
_this7.visible = true;
if (_this7.proxyContainer) {
return _this7.proxyContainer.get().then(showElement);
}
});
};
_proto.hide = function hide() {
var _this8 = this;
return promise_ZalgoPromise.try(function () {
_this8.visible = false;
if (_this8.proxyContainer) {
return _this8.proxyContainer.get().then(hideElement);
}
});
};
_proto.setProps = function setProps(props, isUpdate) {
if (isUpdate === void 0) {
isUpdate = false;
}
if (this.component.validate) {
this.component.validate({
props: props
});
}
var helpers = this.getHelpers();
extendProps(this.component, this.props, props, helpers, isUpdate);
};
_proto.buildUrl = function buildUrl() {
var _this9 = this;
return propsToQuery(_extends({}, this.component.props, {}, this.component.builtinProps), this.props).then(function (query) {
return extendUrl(normalizeMockUrl(_this9.component.getUrl(_this9.props)), {
query: query
});
});
};
_proto.getDomain = function getDomain() {
return this.component.getDomain(this.props);
};
_proto.getChildDomain = function getChildDomain() {
return this.component.getChildDomain(this.props);
};
_proto.getPropsForChild = function getPropsForChild(domain) {
var result = {};
for (var _i2 = 0, _Object$keys2 = Object.keys(this.props); _i2 < _Object$keys2.length; _i2++) {
var key = _Object$keys2[_i2];
var prop = this.component.getPropDefinition(key);
if (prop && prop.sendToChild === false) {
continue;
}
if (prop && prop.sameDomain && !matchDomain(domain, utils_getDomain(window))) {
continue;
}
result[key] = this.props[key];
} // $FlowFixMe
return result;
};
_proto.updateProps = function updateProps(props) {
var _this10 = this;
this.setProps(props, true);
return this.initPromise.then(function () {
if (_this10.child) {
return _this10.child.updateProps(_this10.getPropsForChild(_this10.getDomain())).catch(function (err) {
if (!_this10.child || !_this10.proxyWin) {
return;
}
return _this10.checkClose(_this10.proxyWin).then(function () {
if (_this10.child) {
throw err;
}
});
});
}
});
};
_proto.openFrame = function openFrame(_ref10) {
var _this11 = this;
var windowName = _ref10.windowName;
return promise_ZalgoPromise.try(function () {
if (_this11.driver.openFrame) {
return _this11.driver.openFrame.call(_this11, {
windowName: windowName
});
}
});
};
_proto.openPrerenderFrame = function openPrerenderFrame() {
var _this12 = this;
return promise_ZalgoPromise.try(function () {
if (_this12.driver.openPrerenderFrame) {
return _this12.driver.openPrerenderFrame.call(_this12);
}
});
};
_proto.open = function open(_ref11) {
var _this13 = this;
var proxyWin = _ref11.proxyWin,
proxyFrame = _ref11.proxyFrame,
windowName = _ref11.windowName;
return promise_ZalgoPromise.try(function () {
_this13.component.log("open");
return _this13.driver.open.call(_this13, {
windowName: windowName,
proxyFrame: proxyFrame
}).then(function (win) {
proxyWin.setWindow(win, {
send: send_send
});
return proxyWin;
});
});
};
_proto.openPrerender = function openPrerender(proxyWin, proxyPrerenderFrame) {
var _this14 = this;
return promise_ZalgoPromise.try(function () {
return _this14.driver.openPrerender.call(_this14, proxyWin, proxyPrerenderFrame);
});
};
_proto.focus = function focus() {
var _this15 = this;
return promise_ZalgoPromise.try(function () {
var proxyWin = _this15.proxyWin;
if (proxyWin) {
_this15.event.trigger(EVENT.FOCUS);
return proxyWin.focus().then(src_util_noop);
}
});
};
_proto.delegate = function delegate(context, target) {
var _this16 = this;
this.component.log("delegate");
var props = {};
for (var _i4 = 0, _this$component$getPr2 = this.component.getPropNames(); _i4 < _this$component$getPr2.length; _i4++) {
var propName = _this$component$getPr2[_i4];
if (this.component.getPropDefinition(propName).allowDelegate) {
props[propName] = this.props[propName];
}
}
var overridesPromise = send_send(target, POST_MESSAGE.DELEGATE + "_" + this.component.name, {
context: context,
props: props,
overrides: {
event: this.event,
close: function close() {
return _this16.close();
},
onError: function onError(err) {
return _this16.onError(err);
}
}
}).then(function (_ref12) {
var data = _ref12.data;
_this16.clean.register(data.destroy);
return data.overrides;
}).catch(function (err) {
throw new Error("Unable to delegate rendering. Possibly the component is not loaded in the target window.\n\n" + stringifyError(err));
});
var _loop = function _loop(_i6, _this$driver$delegate2) {
var key = _this$driver$delegate2[_i6];
// $FlowFixMe
_this16[key] = function overriddenFunction() {
var _arguments = arguments,
_this17 = this;
return overridesPromise.then(function (overrides) {
return overrides[key].apply(_this17, _arguments);
});
};
};
for (var _i6 = 0, _this$driver$delegate2 = this.driver.delegate; _i6 < _this$driver$delegate2.length; _i6++) {
_loop(_i6, _this$driver$delegate2);
}
};
_proto.getWindowRef = function getWindowRef(target, domain, uid, context) {
if (domain === utils_getDomain(window)) {
var global = lib_global_getGlobal(window);
global.windows = global.windows || {};
global.windows[uid] = window;
this.clean.register(function () {
delete global.windows[uid];
});
return {
type: WINDOW_REFERENCES.GLOBAL,
uid: uid
};
}
if (context === CONTEXT.POPUP) {
return {
type: WINDOW_REFERENCES.OPENER
};
}
return {
type: WINDOW_REFERENCES.PARENT,
distance: getDistanceFromTop(window)
};
};
_proto.watchForClose = function watchForClose(proxyWin) {
var _this18 = this;
var cancelled = false;
this.clean.register(function () {
cancelled = true;
});
return promise_ZalgoPromise.delay(2000).then(function () {
return proxyWin.isClosed();
}).then(function (isClosed) {
if (isClosed) {
_this18.component.log("detect_close_child");
return _this18.close();
} else if (!cancelled) {
return _this18.watchForClose(proxyWin);
}
});
};
_proto.watchForUnload = function watchForUnload() {
var _this19 = this;
var unloadWindowListener = addEventListener(window, 'unload', once(function () {
_this19.component.log("navigate_away");
_this19.destroy(new Error("Window navigated away"));
}));
this.clean.register(unloadWindowListener.cancel);
};
_proto.runTimeout = function runTimeout() {
var _this20 = this;
return promise_ZalgoPromise.try(function () {
var timeout = _this20.props.timeout;
if (timeout) {
return _this20.initPromise.timeout(timeout, new Error("Loading component timed out after " + timeout + " milliseconds"));
}
});
};
_proto.initChild = function initChild(child) {
var _this21 = this;
return promise_ZalgoPromise.try(function () {
_this21.clean.set('child', child);
_this21.initPromise.resolve();
});
};
_proto.buildParentExports = function buildParentExports(win) {
var _this22 = this;
var onError = function onError(err) {
return _this22.onError(err);
};
var init = function init(child) {
return _this22.initChild(child);
};
var close = function close() {
return _this22.close();
};
var checkClose = function checkClose() {
return _this22.checkClose(win);
};
var resize = function resize(_ref13) {
var width = _ref13.width,
height = _ref13.height;
return _this22.resize({
width: width,
height: height
});
};
var show = function show() {
return _this22.show();
};
var hide = function hide() {
return _this22.hide();
};
init.onError = onError;
return {
init: init,
close: close,
checkClose: checkClose,
resize: resize,
onError: onError,
show: show,
hide: hide
};
};
_proto.resize = function resize(_ref14) {
var _this23 = this;
var width = _ref14.width,
height = _ref14.height;
return promise_ZalgoPromise.try(function () {
_this23.event.trigger(EVENT.RESIZE, {
width: width,
height: height
});
});
};
_proto.checkClose = function checkClose(win) {
var _this24 = this;
return win.isClosed().then(function (closed) {
if (closed) {
return _this24.close();
}
return promise_ZalgoPromise.delay(200).then(function () {
return win.isClosed();
}).then(function (secondClosed) {
if (secondClosed) {
return _this24.close();
}
});
});
};
_proto.close = function close() {
var _this25 = this;
return promise_ZalgoPromise.try(function () {
_this25.component.log("close");
return _this25.event.trigger(EVENT.CLOSE);
}).then(function () {
if (_this25.child) {
_this25.child.close.fireAndForget().catch(src_util_noop);
}
return _this25.destroy(new Error("Window closed"));
});
};
_proto.prerender = function prerender(proxyPrerenderWin, _ref15) {
var _this26 = this;
var context = _ref15.context,
uid = _ref15.uid;
return promise_ZalgoPromise.try(function () {
var prerenderTemplate = _this26.component.prerenderTemplate;
if (!prerenderTemplate) {
return;
}
var prerenderWindow = proxyPrerenderWin.getWindow();
if (!prerenderWindow || !isSameDomain(prerenderWindow) || !isBlankDomain(prerenderWindow)) {
return;
}
prerenderWindow = assertSameDomain(prerenderWindow);
var doc = prerenderWindow.document;
var el = _this26.renderTemplate(prerenderTemplate, {
context: context,
uid: uid,
doc: doc
});
if (!el) {
return;
}
if (el.ownerDocument !== doc) {
throw new Error("Expected prerender template to have been created with document from child window");
}
writeElementToWindow(prerenderWindow, el);
var _ref16 = _this26.component.autoResize || {},
_ref16$width = _ref16.width,
width = _ref16$width === void 0 ? false : _ref16$width,
_ref16$height = _ref16.height,
height = _ref16$height === void 0 ? false : _ref16$height,
_ref16$element = _ref16.element,
element = _ref16$element === void 0 ? 'body' : _ref16$element;
element = getElementSafe(element, doc);
if (element && (width || height)) {
onResize(element, function (_ref17) {
var newWidth = _ref17.width,
newHeight = _ref17.height;
_this26.resize({
width: width ? newWidth : undefined,
height: height ? newHeight : undefined
});
}, {
width: width,
height: height,
win: prerenderWindow
});
}
});
};
_proto.renderTemplate = function renderTemplate(renderer, _ref18) {
var _this27 = this;
var context = _ref18.context,
uid = _ref18.uid,
container = _ref18.container,
doc = _ref18.doc,
frame = _ref18.frame,
prerenderFrame = _ref18.prerenderFrame;
// $FlowFixMe
return renderer.call(this, {
container: container,
context: context,
uid: uid,
doc: doc,
frame: frame,
prerenderFrame: prerenderFrame,
focus: function focus() {
return _this27.focus();
},
close: function close() {
return _this27.close();
},
state: this.state,
props: this.props,
tag: this.component.tag,
dimensions: this.component.dimensions,
event: this.event
});
};
_proto.renderContainer = function renderContainer(proxyContainer, _ref19) {
var _this28 = this;
var proxyFrame = _ref19.proxyFrame,
proxyPrerenderFrame = _ref19.proxyPrerenderFrame,
context = _ref19.context,
uid = _ref19.uid,
visible = _ref19.visible;
return promise_ZalgoPromise.hash({
container: proxyContainer.get().then(elementReady),
// $FlowFixMe
frame: proxyFrame ? proxyFrame.get() : null,
// $FlowFixMe
prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null
}).then(function (_ref20) {
var container = _ref20.container,
frame = _ref20.frame,
prerenderFrame = _ref20.prerenderFrame;
var innerContainer = _this28.renderTemplate(_this28.component.containerTemplate, {
context: context,
uid: uid,
container: container,
frame: frame,
prerenderFrame: prerenderFrame,
doc: document
});
if (innerContainer) {
if (!visible) {
hideElement(innerContainer);
}
appendChild(container, innerContainer);
_this28.clean.register(function () {
return destroyElement(innerContainer);
});
_this28.proxyContainer = getProxyObject(innerContainer);
return getProxyObject(innerContainer);
}
});
};
_proto.destroy = function destroy(err) {
var _this29 = this;
return promise_ZalgoPromise.try(function () {
return _this29.clean.all();
}).then(function () {
_this29.initPromise.asyncReject(err || new Error('Component destroyed'));
_this29.component.log("destroy");
});
};
_proto.onError = function onError(err) {
var _this30 = this;
return promise_ZalgoPromise.try(function () {
if (_this30.handledErrors.indexOf(err) !== -1) {
return;
}
_this30.handledErrors.push(err);
_this30.initPromise.asyncReject(err);
return _this30.event.trigger(EVENT.ERROR, err);
});
};
_proto.openBridge = function openBridge(proxyWin, domain, context) {
var _this31 = this;
if (true) {
return promise_ZalgoPromise.try(function () {
return proxyWin.awaitWindow();
}).then(function (win) {
if (!src_bridge || !src_bridge.needsBridge({
win: win,
domain: domain
}) || src_bridge.hasBridge(domain, domain)) {
return;
}
var bridgeUrl = _this31.component.getBridgeUrl();
if (!bridgeUrl) {
throw new Error("Bridge needed to render " + context);
}
var bridgeDomain = getDomainFromUrl(bridgeUrl);
src_bridge.linkUrl(win, domain);
return src_bridge.openBridge(normalizeMockUrl(bridgeUrl), bridgeDomain);
});
}
};
return ParentComponent;
}();
// CONCATENATED MODULE: ./src/delegate/index.js
var delegate_DelegateComponent =
/*#__PURE__*/
function () {
function DelegateComponent(component, source, options) {
var _this = this;
this.component = void 0;
this.source = void 0;
this.context = void 0;
this.driver = void 0;
this.props = void 0;
this.clean = void 0;
this.focus = void 0;
this.resize = void 0;
this.renderTemplate = void 0;
this.close = void 0;
this.onError = void 0;
this.event = void 0;
this.component = component;
this.context = options.context;
this.driver = RENDER_DRIVERS[options.context];
this.clean = cleanup(this);
this.focus = parent_ParentComponent.prototype.focus;
this.resize = parent_ParentComponent.prototype.resize;
this.renderTemplate = parent_ParentComponent.prototype.renderTemplate; // $FlowFixMe
this.props = {};
for (var _i2 = 0, _Object$keys2 = Object.keys(options.props); _i2 < _Object$keys2.length; _i2++) {
var propName = _Object$keys2[_i2];
var propDef = this.component.getPropDefinition(propName);
if (propDef && propDef.allowDelegate && options.props[propName]) {
// $FlowFixMe
this.props[propName] = options.props[propName];
}
}
this.close = options.overrides.close;
this.onError = options.overrides.onError;
this.event = options.overrides.event;
this.component.registerActiveComponent(this);
this.clean.register(function () {
return _this.component.destroyActiveComponent(_this);
});
this.watchForSourceClose(source);
}
var _proto = DelegateComponent.prototype;
_proto.getDelegate = function getDelegate() {
var _this2 = this;
return {
overrides: this.getOverrides(),
destroy: function destroy() {
return _this2.destroy();
}
};
};
_proto.watchForSourceClose = function watchForSourceClose(source) {
var _this3 = this;
var closeSourceWindowListener = onCloseWindow(source, function () {
return _this3.destroy();
}, 3000);
this.clean.register(closeSourceWindowListener.cancel);
};
_proto.getOverrides = function getOverrides() {
var overrides = {};
var self = this;
var _loop = function _loop(_i4, _this$driver$delegate2) {
var key = _this$driver$delegate2[_i4];
overrides[key] = function delegateOverride() {
// $FlowFixMe
return parent_ParentComponent.prototype[key].apply(self, arguments);
};
overrides[key].__name__ = key;
};
for (var _i4 = 0, _this$driver$delegate2 = this.driver.delegate; _i4 < _this$driver$delegate2.length; _i4++) {
_loop(_i4, _this$driver$delegate2);
}
return overrides;
};
_proto.destroy = function destroy() {
return this.clean.all();
};
return DelegateComponent;
}();
// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
// CONCATENATED MODULE: ./src/drivers/react.js
/* eslint react/no-deprecated: off, react/no-find-dom-node: off, react/display-name: off, react/no-did-mount-set-state: off, react/destructuring-assignment: off, react/prop-types: off */
var react = {
register: function register(component, _ref) {
var React = _ref.React,
ReactDOM = _ref.ReactDOM;
// $FlowFixMe
return (
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(_class, _React$Component);
function _class() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = _class.prototype;
_proto.render = function render() {
return React.createElement('div', null);
};
_proto.componentDidMount = function componentDidMount() {
component.log("instantiate_react_component");
var el = ReactDOM.findDOMNode(this);
var parent = component.init(extend({}, this.props));
parent.render(el, CONTEXT.IFRAME);
this.setState({
parent: parent
});
};
_proto.componentDidUpdate = function componentDidUpdate() {
if (this.state && this.state.parent) {
this.state.parent.updateProps(extend({}, this.props)).catch(src_util_noop);
}
};
return _class;
}(React.Component)
);
}
};
// CONCATENATED MODULE: ./src/drivers/vue.js
var vue = {
register: function register(component, Vue) {
return Vue.component(component.tag, {
render: function render(createElement) {
return createElement('div');
},
inheritAttrs: false,
mounted: function mounted() {
var el = this.$el;
this.parent = component.init(_extends({}, this.$attrs));
this.parent.render(el, CONTEXT.IFRAME);
},
watch: {
$attrs: {
handler: function handler() {
if (this.parent && this.$attrs) {
this.parent.updateProps(_extends({}, this.$attrs)).catch(src_util_noop);
}
},
deep: true
}
}
});
}
};
// CONCATENATED MODULE: ./src/drivers/angular.js
var angular = {
register: function register(component, ng) {
var module = ng.module(component.tag, []).directive(dasherizeToCamel(component.tag), function () {
var scope = {};
for (var _i2 = 0, _component$getPropNam2 = component.getPropNames(); _i2 < _component$getPropNam2.length; _i2++) {
var key = _component$getPropNam2[_i2];
scope[key] = '=';
}
scope.props = '=';
return {
scope: scope,
restrict: 'E',
controller: ['$scope', '$element', function ($scope, $element) {
component.log("instantiate_angular_component");
function safeApply() {
if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {
try {
$scope.$apply();
} catch (err) {// pass
}
}
}
var getProps = function getProps() {
return replaceObject($scope.props, function (item) {
if (typeof item === 'function') {
return function angularWrapped() {
// $FlowFixMe
var result = item.apply(this, arguments);
safeApply();
return result;
};
}
return item;
});
};
var instance = component.init(getProps());
instance.render($element[0], CONTEXT.IFRAME);
$scope.$watch(function () {
instance.updateProps(getProps()).catch(src_util_noop);
});
}]
};
});
return module;
}
};
// CONCATENATED MODULE: ./src/drivers/angular2.js
/* eslint new-cap: 0 */
var equals = function equals(obj1, obj2) {
var checked = {};
for (var key in obj1) {
if (obj1.hasOwnProperty(key)) {
checked[key] = true;
if (obj1[key] !== obj2[key]) {
return false;
}
}
}
for (var _key in obj2) {
if (!checked[_key]) {
return false;
}
}
return true;
};
var angular2 = {
register: function register(zoid, _ref) {
var AngularComponent = _ref.Component,
NgModule = _ref.NgModule,
ElementRef = _ref.ElementRef,
NgZone = _ref.NgZone;
zoid.log('initializing angular2 component');
var getProps = function getProps(component) {
return replaceObject(_extends({}, component.internalProps, {}, component.props), function (item) {
if (typeof item === 'function') {
return function angular2Wrapped() {
var _arguments = arguments,
_this = this;
// $FlowFixMe
return component.zone.run(function () {
return item.apply(_this, _arguments);
});
};
}
return item;
});
};
var ComponentInstance = AngularComponent({
selector: zoid.tag,
template: '<div></div>',
inputs: ['props']
}).Class({
constructor: [ElementRef, NgZone, function angularConstructor(elementRef, zone) {
this._props = {};
this.elementRef = elementRef;
this.zone = zone;
}],
ngOnInit: function ngOnInit() {
var targetElement = this.elementRef.nativeElement;
this.parent = zoid.init(getProps(this));
this.parent.render(targetElement, CONTEXT.IFRAME);
},
ngDoCheck: function ngDoCheck() {
if (this.parent && !equals(this._props, this.props)) {
this._props = _extends({}, this.props);
this.parent.updateProps(getProps(this));
}
}
});
var ModuleInstance = NgModule({
declarations: [ComponentInstance],
exports: [ComponentInstance]
}).Class({
constructor: function constructor() {// pass
}
});
return ModuleInstance;
}
};
// CONCATENATED MODULE: ./src/drivers/index.js
// CONCATENATED MODULE: ./src/component/validate.js
function validatePropDefinitions(options) {
if (options.props && !(typeof options.props === 'object')) {
throw new Error("Expected options.props to be an object");
}
var PROP_TYPE_LIST = util_values(PROP_TYPE);
if (options.props) {
for (var _i2 = 0, _Object$keys2 = Object.keys(options.props); _i2 < _Object$keys2.length; _i2++) {
var key = _Object$keys2[_i2];
var prop = options.props[key];
if (!prop || !(typeof prop === 'object')) {
throw new Error("Expected options.props." + key + " to be an object");
}
if (!prop.type) {
throw new Error("Expected prop.type");
}
if (PROP_TYPE_LIST.indexOf(prop.type) === -1) {
throw new Error("Expected prop.type to be one of " + PROP_TYPE_LIST.join(', '));
}
if (prop.required && prop.default) {
throw new Error("Required prop can not have a default value");
}
if (prop.type === PROP_TYPE.FUNCTION && prop.queryParam && !prop.queryValue) {
throw new Error("Do not pass queryParam for function prop");
}
}
}
} // eslint-disable-next-line complexity
function validate_validate(options) {
// eslint-ignore-line
if (!options) {
throw new Error("Expected options to be passed");
} // eslint-disable-next-line security/detect-unsafe-regex, unicorn/no-unsafe-regex
if (!options.tag || !options.tag.match(/^([a-z0-9][a-z0-9-]*)+[a-z0-9]+$/)) {
throw new Error("Invalid options.tag: " + options.tag);
}
validatePropDefinitions(options);
if (options.dimensions) {
if (options.dimensions && !isPx(options.dimensions.width) && !isPerc(options.dimensions.width)) {
throw new Error("Expected options.dimensions.width to be a px or % string value");
}
if (options.dimensions && !isPx(options.dimensions.height) && !isPerc(options.dimensions.height)) {
throw new Error("Expected options.dimensions.height to be a px or % string value");
}
}
if (options.defaultContext) {
if (options.defaultContext !== CONTEXT.IFRAME && options.defaultContext !== CONTEXT.POPUP) {
throw new Error("Unsupported context type: " + (options.defaultContext || 'unknown'));
}
}
if (!options.url) {
throw new Error("Must pass url");
}
if (typeof options.url !== 'string' && typeof options.url !== 'function') {
throw new TypeError("Expected url to be string or function");
}
if (options.prerenderTemplate && typeof options.prerenderTemplate !== 'function') {
throw new Error("Expected options.prerenderTemplate to be a function");
}
if ((options.containerTemplate || !true) && typeof options.containerTemplate !== 'function') {
throw new Error("Expected options.containerTemplate to be a function");
}
}
// CONCATENATED MODULE: ./src/component/templates/container.js
/* eslint react/react-in-jsx-scope: off */
var CLASS = {
VISIBLE: 'visible',
INVISIBLE: 'invisible'
};
function defaultContainerTemplate(_ref) {
var uid = _ref.uid,
frame = _ref.frame,
prerenderFrame = _ref.prerenderFrame,
doc = _ref.doc,
props = _ref.props,
event = _ref.event,
_ref$dimensions = _ref.dimensions,
width = _ref$dimensions.width,
height = _ref$dimensions.height;
if (true) {
if (!frame || !prerenderFrame) {
return;
}
var div = doc.createElement('div');
div.setAttribute('id', uid);
var style = doc.createElement('style');
if (props.cspNonce) {
style.setAttribute('nonce', props.cspNonce);
}
style.appendChild(doc.createTextNode("\n #" + uid + " {\n display: inline-block;\n position: relative;\n width: " + width + ";\n height: " + height + ";\n }\n\n #" + uid + " > iframe {\n display: inline-block;\n position: absolute;\n width: 100%;\n height: 100%;\n top: 0;\n left: 0;\n transition: opacity .2s ease-in-out;\n }\n\n #" + uid + " > iframe." + CLASS.INVISIBLE + " {\n opacity: 0;\n }\n\n #" + uid + " > iframe." + CLASS.VISIBLE + " {\n opacity: 1;\n }\n "));
div.appendChild(frame);
div.appendChild(prerenderFrame);
div.appendChild(style);
prerenderFrame.classList.add(CLASS.VISIBLE);
frame.classList.add(CLASS.INVISIBLE);
event.on(EVENT.RENDERED, function () {
prerenderFrame.classList.remove(CLASS.VISIBLE);
prerenderFrame.classList.add(CLASS.INVISIBLE);
frame.classList.remove(CLASS.INVISIBLE);
frame.classList.add(CLASS.VISIBLE);
setTimeout(function () {
destroyElement(prerenderFrame);
}, 1);
});
event.on(EVENT.RESIZE, function (_ref2) {
var newWidth = _ref2.width,
newHeight = _ref2.height;
if (typeof newWidth === 'number') {
div.style.width = toCSS(newWidth);
}
if (typeof newHeight === 'number') {
div.style.height = toCSS(newHeight);
}
});
return div;
}
}
// CONCATENATED MODULE: ./src/component/templates/component.js
/* eslint react/react-in-jsx-scope: off */
function defaultPrerenderTemplate(_ref) {
var doc = _ref.doc,
props = _ref.props;
if (true) {
var html = doc.createElement('html');
var body = doc.createElement('body');
var style = doc.createElement('style');
var spinner = doc.createElement('div');
spinner.classList.add('spinner');
if (props.cspNonce) {
style.setAttribute('nonce', props.cspNonce);
}
html.appendChild(body);
body.appendChild(spinner);
body.appendChild(style);
style.appendChild(doc.createTextNode("\n html, body {\n width: 100%;\n height: 100%;\n }\n\n .spinner {\n position: fixed;\n max-height: 60vmin;\n max-width: 60vmin;\n height: 40px;\n width: 40px;\n top: 50%;\n left: 50%;\n box-sizing: border-box;\n border: 3px solid rgba(0, 0, 0, .2);\n border-top-color: rgba(33, 128, 192, 0.8);\n border-radius: 100%;\n animation: rotation .7s infinite linear;\n }\n\n @keyframes rotation {\n from {\n transform: translateX(-50%) translateY(-50%) rotate(0deg);\n }\n to {\n transform: translateX(-50%) translateY(-50%) rotate(359deg);\n }\n }\n "));
return html;
}
}
// CONCATENATED MODULE: ./src/component/templates/index.js
// CONCATENATED MODULE: ./src/component/props.js
var props_defaultNoop = function defaultNoop() {
return src_util_noop;
};
var props_decorateOnce = function decorateOnce(_ref) {
var value = _ref.value;
return once(value);
};
function getBuiltInProps() {
return {
window: {
type: 'object',
sendToChild: false,
required: false,
allowDelegate: true,
validate: function validate(_ref2) {
var value = _ref2.value;
if (!isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) {
throw new Error("Expected Window or ProxyWindow");
}
if (isWindow(value)) {
// $FlowFixMe
if (isWindowClosed(value)) {
throw new Error("Window is closed");
} // $FlowFixMe
if (!isSameDomain(value)) {
throw new Error("Window is not same domain");
}
}
},
decorate: function decorate(_ref3) {
var value = _ref3.value;
return setup_toProxyWindow(value);
}
},
timeout: {
type: 'number',
required: false,
sendToChild: false
},
close: {
type: 'function',
required: false,
sendToChild: false,
childDecorate: function childDecorate(_ref4) {
var close = _ref4.close;
return close;
}
},
focus: {
type: 'function',
required: false,
sendToChild: false,
childDecorate: function childDecorate(_ref5) {
var focus = _ref5.focus;
return focus;
}
},
resize: {
type: 'function',
required: false,
sendToChild: false,
childDecorate: function childDecorate(_ref6) {
var resize = _ref6.resize;
return resize;
}
},
cspNonce: {
type: 'string',
required: false
},
getParent: {
type: 'function',
required: false,
sendToChild: false,
childDecorate: function childDecorate(_ref7) {
var getParent = _ref7.getParent;
return getParent;
}
},
getParentDomain: {
type: 'function',
required: false,
sendToChild: false,
childDecorate: function childDecorate(_ref8) {
var getParentDomain = _ref8.getParentDomain;
return getParentDomain;
}
},
show: {
type: 'function',
required: false,
sendToChild: false,
childDecorate: function childDecorate(_ref9) {
var show = _ref9.show;
return show;
}
},
hide: {
type: 'function',
required: false,
sendToChild: false,
childDecorate: function childDecorate(_ref10) {
var hide = _ref10.hide;
return hide;
}
},
onDisplay: {
type: 'function',
required: false,
sendToChild: false,
allowDelegate: true,
default: props_defaultNoop,
decorate: props_decorateOnce
},
onRendered: {
type: 'function',
required: false,
sendToChild: false,
default: props_defaultNoop,
decorate: props_decorateOnce
},
onRender: {
type: 'function',
required: false,
sendToChild: false,
default: props_defaultNoop,
decorate: props_decorateOnce
},
onClose: {
type: 'function',
required: false,
sendToChild: false,
allowDelegate: true,
default: props_defaultNoop,
decorate: props_decorateOnce
},
onResize: {
type: 'function',
required: false,
sendToChild: false,
allowDelegate: true,
default: props_defaultNoop
},
onFocus: {
type: 'function',
required: false,
sendToChild: false,
allowDelegate: true,
default: props_defaultNoop
},
onError: {
type: 'function',
required: false,
sendToChild: false,
childDecorate: function childDecorate(_ref11) {
var onError = _ref11.onError;
return onError;
}
},
onProps: {
type: 'function',
required: false,
sendToChild: false,
default: props_defaultNoop,
childDecorate: function childDecorate(_ref12) {
var onProps = _ref12.onProps;
return onProps;
}
}
};
}
// CONCATENATED MODULE: ./src/component/component.js
/* eslint max-lines: 0 */
var component_Component =
/*#__PURE__*/
function () {
function Component(options) {
this.tag = void 0;
this.name = void 0;
this.url = void 0;
this.domain = void 0;
this.bridgeUrl = void 0;
this.props = void 0;
this.builtinProps = void 0;
this.dimensions = void 0;
this.autoResize = void 0;
this.allowedParentDomains = void 0;
this.defaultContext = void 0;
this.attributes = void 0;
this.containerTemplate = void 0;
this.prerenderTemplate = void 0;
this.validate = void 0;
this.driverCache = void 0;
this.xprops = void 0;
this.logger = void 0;
this.propNames = void 0;
validate_validate(options); // The tag name of the component. Used by some drivers (e.g. angular) to turn the component into an html element,
// e.g. <my-component>
this.tag = options.tag;
this.name = this.tag.replace(/-/g, '_');
this.allowedParentDomains = options.allowedParentDomains || src_constants_WILDCARD;
var global = lib_global_getGlobal();
global.components = global.components || {};
if (global.components[this.tag]) {
throw new Error("Can not register multiple components with the same tag: " + this.tag);
} // A json based spec describing what kind of props the component accepts. This is used to validate any props before
// they are passed down to the child.
this.builtinProps = getBuiltInProps();
this.props = options.props || {}; // The dimensions of the component, e.g. { width: '300px', height: '150px' }
var _ref = options.dimensions || {},
_ref$width = _ref.width,
width = _ref$width === void 0 ? DEFAULT_DIMENSIONS.WIDTH : _ref$width,
_ref$height = _ref.height,
height = _ref$height === void 0 ? DEFAULT_DIMENSIONS.HEIGHT : _ref$height;
this.dimensions = {
width: width,
height: height
};
this.url = options.url;
this.domain = options.domain;
this.bridgeUrl = options.bridgeUrl;
this.attributes = options.attributes || {};
this.attributes.iframe = this.attributes.iframe || {};
this.attributes.popup = this.attributes.popup || {};
this.defaultContext = options.defaultContext || CONTEXT.IFRAME;
this.autoResize = options.autoResize;
if (options.containerTemplate) {
this.containerTemplate = options.containerTemplate;
} else if (true) {
this.containerTemplate = defaultContainerTemplate;
}
if (options.prerenderTemplate) {
this.prerenderTemplate = options.prerenderTemplate;
} else if (true) {
this.prerenderTemplate = defaultPrerenderTemplate;
}
this.validate = options.validate;
this.logger = options.logger || {
debug: src_util_noop,
info: src_util_noop,
warn: src_util_noop,
error: src_util_noop
};
this.registerChild();
this.listenDelegate();
global.components[this.tag] = this;
}
var _proto = Component.prototype;
_proto.getPropNames = function getPropNames() {
if (this.propNames) {
return this.propNames;
}
var propNames = Object.keys(this.props);
for (var _i2 = 0, _Object$keys2 = Object.keys(this.builtinProps); _i2 < _Object$keys2.length; _i2++) {
var key = _Object$keys2[_i2];
if (propNames.indexOf(key) === -1) {
propNames.push(key);
}
}
this.propNames = propNames;
return propNames;
};
_proto.getPropDefinition = function getPropDefinition(name) {
return this.props[name] || this.builtinProps[name];
};
_proto.driver = function driver(name, dep) {
if (false) { var drivers; } else {
throw new Error("Driver support not enabled");
}
};
_proto.registerChild = function registerChild() {
if (this.isChild()) {
if (window.xprops) {
throw new Error("Can not register " + this.name + " as child - can not attach multiple components to the same window");
}
var child = new child_ChildComponent(this);
window.xprops = this.xprops = child.getProps();
}
};
_proto.listenDelegate = function listenDelegate() {
var _this = this;
on_on(POST_MESSAGE.ALLOW_DELEGATE + "_" + this.name, function () {
return true;
});
on_on(POST_MESSAGE.DELEGATE + "_" + this.name, function (_ref2) {
var source = _ref2.source,
_ref2$data = _ref2.data,
context = _ref2$data.context,
props = _ref2$data.props,
overrides = _ref2$data.overrides;
var delegate = new delegate_DelegateComponent(_this, source, {
context: context,
props: props,
overrides: overrides
});
return delegate.getDelegate();
});
};
_proto.canRenderTo = function canRenderTo(win) {
return send_send(win, POST_MESSAGE.ALLOW_DELEGATE + "_" + this.name).then(function (_ref3) {
var data = _ref3.data;
return data;
}).catch(function () {
return false;
});
};
_proto.getUrl = function getUrl(props) {
if (typeof this.url === 'function') {
return this.url({
props: props
});
}
return this.url;
};
_proto.getChildDomain = function getChildDomain(props) {
if (this.domain && typeof this.domain === 'string') {
return this.domain;
}
return getDomainFromUrl(this.getUrl(props));
};
_proto.getDomain = function getDomain(props) {
if (this.domain && util_isRegex(this.domain)) {
return this.domain;
}
return this.getChildDomain(props);
};
_proto.getBridgeUrl = function getBridgeUrl() {
if (this.bridgeUrl) {
return this.bridgeUrl;
}
};
_proto.isChild = function isChild() {
var payload = getChildPayload();
return Boolean(payload && payload.tag === this.tag && payload.childDomain === utils_getDomain());
};
_proto.getDefaultContainer = function getDefaultContainer(context, container) {
if (container) {
if (typeof container !== 'string' && !isElement(container)) {
throw new TypeError("Expected string or element selector to be passed");
}
return container;
}
if (context === CONTEXT.POPUP) {
return 'body';
}
throw new Error("Expected element to be passed to render iframe");
};
_proto.getDefaultContext = function getDefaultContext(context, props) {
var _this2 = this;
return promise_ZalgoPromise.try(function () {
if (props.window) {
return setup_toProxyWindow(props.window).getType();
}
if (context) {
if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) {
throw new Error("Unrecognized context: " + context);
}
return context;
}
return _this2.defaultContext;
});
};
_proto.init = function init(props) {
var _this3 = this;
// $FlowFixMe
props = props || {};
var parent = new parent_ParentComponent(this, props);
var _render = function render(target, container, context) {
return promise_ZalgoPromise.try(function () {
if (!isWindow(target)) {
throw new Error("Must pass window to renderTo");
}
return _this3.getDefaultContext(context, props);
}).then(function (finalContext) {
container = _this3.getDefaultContainer(finalContext, container);
return parent.render(target, container, finalContext);
});
};
return _extends({}, parent.getHelpers(), {
render: function render(container, context) {
return _render(window, container, context);
},
renderTo: function renderTo(target, container, context) {
return _render(target, container, context);
}
});
};
_proto.checkAllowRender = function checkAllowRender(target, domain, container) {
if (target === window) {
return;
}
if (!isSameTopWindow(window, target)) {
throw new Error("Can only renderTo an adjacent frame");
}
var origin = utils_getDomain();
if (!matchDomain(domain, origin) && !isSameDomain(target)) {
throw new Error("Can not render remotely to " + domain.toString() + " - can only render to " + origin);
}
if (container && typeof container !== 'string') {
throw new Error("Container passed to renderTo must be a string selector, got " + typeof container + " }");
}
};
_proto.log = function log(event, payload) {
this.logger.info(this.name + "_" + event, payload);
};
_proto.registerActiveComponent = function registerActiveComponent(instance) {
var global = lib_global_getGlobal();
global.activeComponents = global.activeComponents || [];
global.activeComponents.push(instance);
};
_proto.destroyActiveComponent = function destroyActiveComponent(instance) {
var global = lib_global_getGlobal();
global.activeComponents = global.activeComponents || [];
global.activeComponents.splice(global.activeComponents.indexOf(instance), 1);
};
return Component;
}();
function create(options) {
setup();
var component = new component_Component(options);
var init = function init(props) {
return component.init(props);
};
init.driver = function (name, dep) {
return component.driver(name, dep);
};
init.isChild = function () {
return component.isChild();
};
init.canRenderTo = function (win) {
return component.canRenderTo(win);
};
init.xprops = component.xprops;
return init;
}
function destroyAll() {
if (src_bridge) {
src_bridge.destroyBridges();
}
var results = [];
var global = lib_global_getGlobal();
global.activeComponents = global.activeComponents || [];
while (global.activeComponents.length) {
results.push(global.activeComponents[0].destroy(new Error("zoid destroyed all"), false));
}
return promise_ZalgoPromise.all(results).then(src_util_noop);
}
var destroyComponents = destroyAll;
function component_destroy() {
destroyAll();
destroyGlobal();
setup_destroy();
}
// CONCATENATED MODULE: ./src/component/index.js
// CONCATENATED MODULE: ./src/index.js
/* concated harmony reexport PopupOpenError */__webpack_require__.d(__webpack_exports__, "PopupOpenError", function() { return PopupOpenError; });
/* concated harmony reexport create */__webpack_require__.d(__webpack_exports__, "create", function() { return create; });
/* concated harmony reexport destroy */__webpack_require__.d(__webpack_exports__, "destroy", function() { return component_destroy; });
/* concated harmony reexport destroyComponents */__webpack_require__.d(__webpack_exports__, "destroyComponents", function() { return destroyComponents; });
/* concated harmony reexport destroyAll */__webpack_require__.d(__webpack_exports__, "destroyAll", function() { return destroyAll; });
/* concated harmony reexport Component */__webpack_require__.d(__webpack_exports__, "Component", function() { return component_Component; });
/* concated harmony reexport PROP_TYPE */__webpack_require__.d(__webpack_exports__, "PROP_TYPE", function() { return PROP_TYPE; });
/* concated harmony reexport PROP_SERIALIZATION */__webpack_require__.d(__webpack_exports__, "PROP_SERIALIZATION", function() { return PROP_SERIALIZATION; });
/* concated harmony reexport CONTEXT */__webpack_require__.d(__webpack_exports__, "CONTEXT", function() { return CONTEXT; });
/* concated harmony reexport EVENT */__webpack_require__.d(__webpack_exports__, "EVENT", function() { return EVENT; });
/***/ })
/******/ ]);
});
//# sourceMappingURL=zoid.js.map
|
/**
* Tom Select v2.0.0-rc.5
* Licensed under the Apache License, Version 2.0 (the "License");
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.remove_button = factory());
}(this, (function () { 'use strict';
// https://github.com/andrewrk/node-diacritics/blob/master/index.js
const latin_convert = {
'æ': 'ae',
'ⱥ': 'a',
'ø': 'o'
};
new RegExp(Object.keys(latin_convert).join('|'), 'g');
/**
* Return a dom element from either a dom query string, jQuery object, a dom element or html string
* https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518
*
* param query should be {}
*/
const getDom = query => {
if (query.jquery) {
return query[0];
}
if (query instanceof HTMLElement) {
return query;
}
if (query.indexOf('<') > -1) {
let div = document.createElement('div');
div.innerHTML = query.trim(); // Never return a text node of whitespace as the result
return div.firstChild;
}
return document.querySelector(query);
};
/**
* Converts a scalar to its best string representation
* for hash keys and HTML attribute values.
*
* Transformations:
* 'str' -> 'str'
* null -> ''
* undefined -> ''
* true -> '1'
* false -> '0'
* 0 -> '0'
* 1 -> '1'
*
*/
/**
* Escapes a string for use within HTML.
*
*/
const escape_html = str => {
return (str + '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
};
/**
* Prevent default
*
*/
const preventDefault = (evt, stop = false) => {
if (evt) {
evt.preventDefault();
if (stop) {
evt.stopPropagation();
}
}
};
/**
* Prevent default
*
*/
const addEvent = (target, type, callback, options) => {
target.addEventListener(type, callback, options);
};
/**
* Plugin: "remove_button" (Tom Select)
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
*/
function plugin (userOptions) {
const options = Object.assign({
label: '×',
title: 'Remove',
className: 'remove',
append: true
}, userOptions); //options.className = 'remove-single';
var self = this; // override the render method to add remove button to each item
if (!options.append) {
return;
}
var html = '<a href="javascript:void(0)" class="' + options.className + '" tabindex="-1" title="' + escape_html(options.title) + '">' + options.label + '</a>';
self.hook('after', 'setupTemplates', () => {
var orig_render_item = self.settings.render.item;
self.settings.render.item = (data, escape) => {
var rendered = getDom(orig_render_item.call(self, data, escape));
var close_button = getDom(html);
rendered.appendChild(close_button);
addEvent(close_button, 'mousedown', evt => {
preventDefault(evt, true);
});
addEvent(close_button, 'click', evt => {
// propagating will trigger the dropdown to show for single mode
preventDefault(evt, true);
if (self.isLocked) return;
var value = rendered.dataset.value;
self.removeItem(value);
self.refreshOptions(false);
});
return rendered;
};
});
}
return plugin;
})));
//# sourceMappingURL=remove_button.js.map
|
/*!
* froala_editor v3.2.4 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2020 Froala Labs
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) :
typeof define === 'function' && define.amd ? define(['froala-editor'], factory) :
(factory(global.FroalaEditor));
}(this, (function (FE) { 'use strict';
FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE;
/**
* Portuguese spoken in Portugal
*/
FE.LANGUAGE['pt_pt'] = {
translation: {
// Place holder
'Type something': 'Digite algo',
// Basic formatting
'Bold': 'Negrito',
'Italic': "It\xE1lico",
'Underline': 'Sublinhado',
'Strikethrough': 'Rasurado',
// Main buttons
'Insert': 'Inserir',
'Delete': 'Apagar',
'Cancel': 'Cancelar',
'OK': 'Ok',
'Back': 'Voltar',
'Remove': 'Remover',
'More': 'Mais',
'Update': 'Atualizar',
'Style': 'Estilo',
// Font
'Font Family': 'Fonte',
'Font Size': 'Tamanho da fonte',
// Colors
'Colors': 'Cores',
'Background': 'Fundo',
'Text': 'Texto',
'HEX Color': 'Cor hexadecimal',
// Paragraphs
'Paragraph Format': 'Formatos',
'Normal': 'Normal',
'Code': "C\xF3digo",
'Heading 1': "Cabe\xE7alho 1",
'Heading 2': "Cabe\xE7alho 2",
'Heading 3': "Cabe\xE7alho 3",
'Heading 4': "Cabe\xE7alho 4",
// Style
'Paragraph Style': "Estilo de par\xE1grafo",
'Inline Style': 'Estilo embutido',
// Alignment
'Align': 'Alinhar',
'Align Left': "Alinhar \xE0 esquerda",
'Align Center': 'Alinhar ao centro',
'Align Right': "Alinhar \xE0 direita",
'Align Justify': 'Justificado',
'None': 'Nenhum',
// Lists
'Ordered List': 'Lista ordenada',
'Unordered List': "Lista n\xE3o ordenada",
// Indent
'Decrease Indent': "Diminuir avan\xE7o",
'Increase Indent': "Aumentar avan\xE7o",
// Links
'Insert Link': 'Inserir link',
'Open in new tab': 'Abrir em uma nova aba',
'Open Link': 'Abrir link',
'Edit Link': 'Editar link',
'Unlink': 'Remover link',
'Choose Link': 'Escolha o link',
// Images
'Insert Image': 'Inserir imagem',
'Upload Image': 'Carregar imagem',
'By URL': 'Por URL',
'Browse': 'Procurar',
'Drop image': 'Largue imagem',
'or click': 'ou clique em',
'Manage Images': 'Gerenciar as imagens',
'Loading': 'Carregando',
'Deleting': 'Excluindo',
'Tags': 'Etiquetas',
'Are you sure? Image will be deleted.': "Voc\xEA tem certeza? Imagem ser\xE1 apagada.",
'Replace': 'Substituir',
'Uploading': 'Carregando',
'Loading image': 'Carregando imagem',
'Display': 'Exibir',
'Inline': 'Em linha',
'Break Text': 'Texto de quebra',
'Alternative Text': 'Texto alternativo',
'Change Size': 'Alterar tamanho',
'Width': 'Largura',
'Height': 'Altura',
'Something went wrong. Please try again.': 'Algo deu errado. Por favor, tente novamente.',
'Image Caption': 'Legenda da imagem',
'Advanced Edit': 'Edição avançada',
// Video
'Insert Video': "Inserir v\xEDdeo",
'Embedded Code': "C\xF3digo embutido",
'Paste in a video URL': 'Colar em um URL de vídeo',
'Drop video': 'Solte o video',
'Your browser does not support HTML5 video.': 'Seu navegador não suporta o vídeo html5.',
'Upload Video': 'Envio vídeo',
// Tables
'Insert Table': 'Inserir tabela',
'Table Header': "Cabe\xE7alho da tabela",
'Remove Table': 'Remover tabela',
'Table Style': 'estilo de tabela',
'Horizontal Align': 'Alinhamento horizontal',
'Row': 'Linha',
'Insert row above': 'Inserir linha antes',
'Insert row below': 'Inserir linha depois',
'Delete row': 'Eliminar linha',
'Column': 'Coluna',
'Insert column before': 'Inserir coluna antes',
'Insert column after': 'Inserir coluna depois',
'Delete column': 'Eliminar coluna',
'Cell': "C\xE9lula",
'Merge cells': "Unir c\xE9lulas",
'Horizontal split': "Divis\xE3o horizontal",
'Vertical split': "Divis\xE3o vertical",
'Cell Background': "Fundo da c\xE9lula",
'Vertical Align': 'Alinhar vertical',
'Top': 'Topo',
'Middle': 'Meio',
'Bottom': 'Fundo',
'Align Top': 'Alinhar topo',
'Align Middle': 'Alinhar meio',
'Align Bottom': 'Alinhar fundo',
'Cell Style': "Estilo de c\xE9lula",
// Files
'Upload File': 'Upload de arquivo',
'Drop file': 'Largar arquivo',
// Emoticons
'Emoticons': 'Emoticons',
'Grinning face': 'Sorrindo a cara',
'Grinning face with smiling eyes': 'Sorrindo rosto com olhos sorridentes',
'Face with tears of joy': "Rosto com l\xE1grimas de alegria",
'Smiling face with open mouth': 'Rosto de sorriso com a boca aberta',
'Smiling face with open mouth and smiling eyes': 'Rosto de sorriso com a boca aberta e olhos sorridentes',
'Smiling face with open mouth and cold sweat': 'Rosto de sorriso com a boca aberta e suor frio',
'Smiling face with open mouth and tightly-closed eyes': 'Rosto de sorriso com a boca aberta e os olhos bem fechados',
'Smiling face with halo': 'Rosto de sorriso com halo',
'Smiling face with horns': 'Rosto de sorriso com chifres',
'Winking face': 'Pisc a rosto',
'Smiling face with smiling eyes': 'Rosto de sorriso com olhos sorridentes',
'Face savoring delicious food': 'Rosto saboreando uma deliciosa comida',
'Relieved face': 'Rosto aliviado',
'Smiling face with heart-shaped eyes': "Rosto de sorriso com os olhos em forma de cora\xE7\xE3o",
'Smiling face with sunglasses': "Rosto de sorriso com \xF3culos de sol",
'Smirking face': 'Rosto sorridente',
'Neutral face': 'Rosto neutra',
'Expressionless face': 'Rosto inexpressivo',
'Unamused face': "O rosto n\xE3o divertido",
'Face with cold sweat': 'Rosto com suor frio',
'Pensive face': 'O rosto pensativo',
'Confused face': 'Cara confusa',
'Confounded face': "Rosto at\xF4nito",
'Kissing face': 'Beijar Rosto',
'Face throwing a kiss': 'Rosto jogando um beijo',
'Kissing face with smiling eyes': 'Beijar rosto com olhos sorridentes',
'Kissing face with closed eyes': 'Beijando a cara com os olhos fechados',
'Face with stuck out tongue': "Preso de cara com a l\xEDngua para fora",
'Face with stuck out tongue and winking eye': "Rosto com estendeu a l\xEDngua e olho piscando",
'Face with stuck out tongue and tightly-closed eyes': 'Rosto com estendeu a língua e os olhos bem fechados',
'Disappointed face': 'Rosto decepcionado',
'Worried face': 'O rosto preocupado',
'Angry face': 'Rosto irritado',
'Pouting face': 'Beicinho Rosto',
'Crying face': 'Cara de choro',
'Persevering face': 'Perseverar Rosto',
'Face with look of triumph': 'Rosto com olhar de triunfo',
'Disappointed but relieved face': 'Fiquei Desapontado mas aliviado Rosto',
'Frowning face with open mouth': 'Sobrancelhas franzidas rosto com a boca aberta',
'Anguished face': 'O rosto angustiado',
'Fearful face': 'Cara com medo',
'Weary face': 'Rosto cansado',
'Sleepy face': 'Cara de sono',
'Tired face': 'Rosto cansado',
'Grimacing face': 'Fazendo caretas face',
'Loudly crying face': 'Alto chorando rosto',
'Face with open mouth': 'Enfrentar com a boca aberta',
'Hushed face': 'Flagrantes de rosto',
'Face with open mouth and cold sweat': 'Enfrentar com a boca aberta e suor frio',
'Face screaming in fear': 'Cara gritando de medo',
'Astonished face': 'Cara de surpresa',
'Flushed face': 'Rosto vermelho',
'Sleeping face': 'O rosto de sono',
'Dizzy face': 'Cara tonto',
'Face without mouth': 'Rosto sem boca',
'Face with medical mask': "Rosto com m\xE1scara m\xE9dica",
// Line breaker
'Break': 'Partir',
// Math
'Subscript': 'Subscrito',
'Superscript': 'Sobrescrito',
// Full screen
'Fullscreen': 'Tela cheia',
// Horizontal line
'Insert Horizontal Line': 'Inserir linha horizontal',
// Clear formatting
'Clear Formatting': "Remover formata\xE7\xE3o",
// Save
'Save': "Salve",
// Undo, redo
'Undo': 'Anular',
'Redo': 'Restaurar',
// Select all
'Select All': 'Seleccionar tudo',
// Code view
'Code View': "Exibi\xE7\xE3o de c\xF3digo",
// Quote
'Quote': "Cita\xE7\xE3o",
'Increase': 'Aumentar',
'Decrease': 'Diminuir',
// Quick Insert
'Quick Insert': "Inser\xE7\xE3o r\xE1pida",
// Spcial Characters
'Special Characters': 'Caracteres especiais',
'Latin': 'Latino',
'Greek': 'Grego',
'Cyrillic': 'Cirílico',
'Punctuation': 'Pontuação',
'Currency': 'Moeda',
'Arrows': 'Setas; flechas',
'Math': 'Matemática',
'Misc': 'Misc',
// Print.
'Print': 'Impressão',
// Spell Checker.
'Spell Checker': 'Verificador ortográfico',
// Help
'Help': 'Socorro',
'Shortcuts': 'Atalhos',
'Inline Editor': 'Editor em linha',
'Show the editor': 'Mostre o editor',
'Common actions': 'Ações comuns',
'Copy': 'Cópia de',
'Cut': 'Cortar',
'Paste': 'Colar',
'Basic Formatting': 'Formatação básica',
'Increase quote level': 'Aumentar o nível de cotação',
'Decrease quote level': 'Diminuir o nível de cotação',
'Image / Video': 'Imagem / video',
'Resize larger': 'Redimensionar maior',
'Resize smaller': 'Redimensionar menor',
'Table': 'Tabela',
'Select table cell': 'Selecione a célula da tabela',
'Extend selection one cell': 'Ampliar a seleção de uma célula',
'Extend selection one row': 'Ampliar a seleção uma linha',
'Navigation': 'Navegação',
'Focus popup / toolbar': 'Foco popup / barra de ferramentas',
'Return focus to previous position': 'Retornar o foco para a posição anterior',
// Embed.ly
'Embed URL': 'URL de inserção',
'Paste in a URL to embed': 'Colar em url para incorporar',
// Word Paste.
'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'O conteúdo colado vem de um documento Microsoft Word. Você quer manter o formato ou limpá-lo?',
'Keep': 'Guarda',
'Clean': 'Limpar limpo',
'Word Paste Detected': 'Pasta de palavras detectada',
// Character Counter
'Characters': 'Caracteres',
// More Buttons
'More Text': 'Mais Texto',
'More Paragraph': 'Mais Parágrafo',
'More Rich': 'Mais Rico',
'More Misc': 'Mais Misc'
},
direction: 'ltr'
};
})));
//# sourceMappingURL=pt_pt.js.map
|
/**
* Tom Select v1.7.2
* Licensed under the Apache License, Version 2.0 (the "License");
*/
import TomSelect from '../../tom-select.js';
var defaults = {
options: [],
optgroups: [],
plugins: [],
delimiter: ',',
splitOn: null,
// regexp or string for splitting up values from a paste command
persist: true,
diacritics: true,
create: null,
createOnBlur: false,
createFilter: null,
highlight: true,
openOnFocus: true,
shouldOpen: null,
maxOptions: 50,
maxItems: null,
hideSelected: null,
duplicates: false,
addPrecedence: false,
selectOnTab: false,
preload: null,
allowEmptyOption: false,
closeAfterSelect: false,
loadThrottle: 300,
loadingClass: 'loading',
dataAttr: null,
//'data-data',
optgroupField: 'optgroup',
valueField: 'value',
labelField: 'text',
disabledField: 'disabled',
optgroupLabelField: 'label',
optgroupValueField: 'value',
lockOptgroupOrder: false,
sortField: '$order',
searchField: ['text'],
searchConjunction: 'and',
mode: null,
wrapperClass: 'ts-control',
inputClass: 'ts-input',
dropdownClass: 'ts-dropdown',
dropdownContentClass: 'ts-dropdown-content',
itemClass: 'item',
optionClass: 'option',
dropdownParent: null,
controlInput: null,
copyClassesToDropdown: true,
placeholder: null,
hidePlaceholder: null,
shouldLoad: function (query) {
return query.length > 0;
},
/*
load : null, // function(query, callback) { ... }
score : null, // function(search) { ... }
onInitialize : null, // function() { ... }
onChange : null, // function(value) { ... }
onItemAdd : null, // function(value, $item) { ... }
onItemRemove : null, // function(value) { ... }
onClear : null, // function() { ... }
onOptionAdd : null, // function(value, data) { ... }
onOptionRemove : null, // function(value) { ... }
onOptionClear : null, // function() { ... }
onOptionGroupAdd : null, // function(id, data) { ... }
onOptionGroupRemove : null, // function(id) { ... }
onOptionGroupClear : null, // function() { ... }
onDropdownOpen : null, // function(dropdown) { ... }
onDropdownClose : null, // function(dropdown) { ... }
onType : null, // function(str) { ... }
onDelete : null, // function(values) { ... }
*/
render: {
/*
item: null,
optgroup: null,
optgroup_header: null,
option: null,
option_create: null
*/
}
};
/**
* Converts a scalar to its best string representation
* for hash keys and HTML attribute values.
*
* Transformations:
* 'str' -> 'str'
* null -> ''
* undefined -> ''
* true -> '1'
* false -> '0'
* 0 -> '0'
* 1 -> '1'
*
*/
function hash_key(value) {
if (typeof value === 'undefined' || value === null) return null;
if (typeof value === 'boolean') return value ? '1' : '0';
return value + '';
}
/**
* Prevent default
*
*/
function addEvent(target, type, callback, options) {
target.addEventListener(type, callback, options);
}
function getSettings(input, settings_user) {
var settings = Object.assign({}, defaults, settings_user);
var attr_data = settings.dataAttr;
var field_label = settings.labelField;
var field_value = settings.valueField;
var field_disabled = settings.disabledField;
var field_optgroup = settings.optgroupField;
var field_optgroup_label = settings.optgroupLabelField;
var field_optgroup_value = settings.optgroupValueField;
var tag_name = input.tagName.toLowerCase();
var placeholder = input.getAttribute('placeholder') || input.getAttribute('data-placeholder');
if (!placeholder && !settings.allowEmptyOption) {
let option = input.querySelector('option[value=""]');
if (option) {
placeholder = option.textContent;
}
}
var settings_element = {
placeholder: placeholder,
options: [],
optgroups: [],
items: [],
maxItems: null
};
/**
* Initialize from a <select> element.
*
*/
var init_select = () => {
var tagName;
var options = settings_element.options;
var optionsMap = {};
var group_count = 1;
var readData = el => {
var data = Object.assign({}, el.dataset); // get plain object from DOMStringMap
var json = attr_data && data[attr_data];
if (typeof json === 'string' && json.length) {
data = Object.assign(data, JSON.parse(json));
}
return data;
};
var addOption = (option, group) => {
var value = hash_key(option.value);
if (!value && !settings.allowEmptyOption) return; // if the option already exists, it's probably been
// duplicated in another optgroup. in this case, push
// the current group to the "optgroup" property on the
// existing option so that it's rendered in both places.
if (optionsMap.hasOwnProperty(value)) {
if (group) {
var arr = optionsMap[value][field_optgroup];
if (!arr) {
optionsMap[value][field_optgroup] = group;
} else if (!Array.isArray(arr)) {
optionsMap[value][field_optgroup] = [arr, group];
} else {
arr.push(group);
}
}
return;
}
var option_data = readData(option);
option_data[field_label] = option_data[field_label] || option.textContent;
option_data[field_value] = option_data[field_value] || value;
option_data[field_disabled] = option_data[field_disabled] || option.disabled;
option_data[field_optgroup] = option_data[field_optgroup] || group;
option_data.$option = option;
optionsMap[value] = option_data;
options.push(option_data);
if (option.selected) {
settings_element.items.push(value);
}
};
var addGroup = optgroup => {
var id, optgroup_data;
optgroup_data = readData(optgroup);
optgroup_data[field_optgroup_label] = optgroup_data[field_optgroup_label] || optgroup.getAttribute('label') || '';
optgroup_data[field_optgroup_value] = optgroup_data[field_optgroup_value] || group_count++;
optgroup_data[field_disabled] = optgroup_data[field_disabled] || optgroup.disabled;
settings_element.optgroups.push(optgroup_data);
id = optgroup_data[field_optgroup_value];
for (const option of optgroup.children) {
addOption(option, id);
}
};
settings_element.maxItems = input.hasAttribute('multiple') ? null : 1;
for (const child of input.children) {
tagName = child.tagName.toLowerCase();
if (tagName === 'optgroup') {
addGroup(child);
} else if (tagName === 'option') {
addOption(child);
}
}
};
/**
* Initialize from a <input type="text"> element.
*
*/
var init_textbox = () => {
var values, option;
var data_raw = input.getAttribute(attr_data);
if (!data_raw) {
var value = input.value.trim() || '';
if (!settings.allowEmptyOption && !value.length) return;
values = value.split(settings.delimiter);
for (const _value of values) {
option = {};
option[field_label] = _value;
option[field_value] = _value;
settings_element.options.push(option);
}
settings_element.items = values;
} else {
settings_element.options = JSON.parse(data_raw);
for (const opt of settings_element.options) {
settings_element.items.push(opt[field_value]);
}
}
};
if (tag_name === 'select') {
init_select();
} else {
init_textbox();
}
return Object.assign({}, defaults, settings_element, settings_user);
}
/**
* Plugin: "change_listener" (Tom Select)
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
*/
TomSelect.define('change_listener', function (options) {
var self = this;
var changed = false;
addEvent(self.input, 'change', () => {
// prevent infinite loops
if (changed) {
changed = false;
return;
}
changed = true;
var settings = getSettings(self.input, {});
self.setupOptions(settings.options, settings.optgroups);
self.setValue(settings.items);
});
});
//# sourceMappingURL=plugin.js.map
|
typeof window !== "undefined" &&
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Hls"] = factory();
else
root["Hls"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/hls.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/eventemitter3/index.js":
/*!*********************************************!*\
!*** ./node_modules/eventemitter3/index.js ***!
\*********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = Object.prototype.hasOwnProperty
, prefix = '~';
/**
* Constructor to create a storage for our `EE` objects.
* An `Events` instance is a plain object whose properties are event names.
*
* @constructor
* @private
*/
function Events() {}
//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
if (Object.create) {
Events.prototype = Object.create(null);
//
// This hack is needed because the `__proto__` property is still inherited in
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
//
if (!new Events().__proto__) prefix = false;
}
/**
* Representation of a single event listener.
*
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
* @constructor
* @private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Add a listener for a given event.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} once Specify if the listener is a one-time listener.
* @returns {EventEmitter}
* @private
*/
function addListener(emitter, event, fn, context, once) {
if (typeof fn !== 'function') {
throw new TypeError('The listener must be a function');
}
var listener = new EE(fn, context || emitter, once)
, evt = prefix ? prefix + event : event;
if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
else emitter._events[evt] = [emitter._events[evt], listener];
return emitter;
}
/**
* Clear event by name.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} evt The Event name.
* @private
*/
function clearEvent(emitter, evt) {
if (--emitter._eventsCount === 0) emitter._events = new Events();
else delete emitter._events[evt];
}
/**
* Minimal `EventEmitter` interface that is molded against the Node.js
* `EventEmitter` interface.
*
* @constructor
* @public
*/
function EventEmitter() {
this._events = new Events();
this._eventsCount = 0;
}
/**
* Return an array listing the events for which the emitter has registered
* listeners.
*
* @returns {Array}
* @public
*/
EventEmitter.prototype.eventNames = function eventNames() {
var names = []
, events
, name;
if (this._eventsCount === 0) return names;
for (name in (events = this._events)) {
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events));
}
return names;
};
/**
* Return the listeners registered for a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Array} The registered listeners.
* @public
*/
EventEmitter.prototype.listeners = function listeners(event) {
var evt = prefix ? prefix + event : event
, handlers = this._events[evt];
if (!handlers) return [];
if (handlers.fn) return [handlers.fn];
for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
ee[i] = handlers[i].fn;
}
return ee;
};
/**
* Return the number of listeners listening to a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Number} The number of listeners.
* @public
*/
EventEmitter.prototype.listenerCount = function listenerCount(event) {
var evt = prefix ? prefix + event : event
, listeners = this._events[evt];
if (!listeners) return 0;
if (listeners.fn) return 1;
return listeners.length;
};
/**
* Calls each of the listeners registered for a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Boolean} `true` if the event had listeners, else `false`.
* @public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
/**
* Add a listener for a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
return addListener(this, event, fn, context, false);
};
/**
* Add a one-time listener for a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
return addListener(this, event, fn, context, true);
};
/**
* Remove the listeners of a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn Only remove the listeners that match this function.
* @param {*} context Only remove the listeners that have this context.
* @param {Boolean} once Only remove one-time listeners.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
clearEvent(this, evt);
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (
listeners.fn === fn &&
(!once || listeners.once) &&
(!context || listeners.context === context)
) {
clearEvent(this, evt);
}
} else {
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
if (
listeners[i].fn !== fn ||
(once && !listeners[i].once) ||
(context && listeners[i].context !== context)
) {
events.push(listeners[i]);
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
else clearEvent(this, evt);
}
return this;
};
/**
* Remove all listeners, or those of the specified event.
*
* @param {(String|Symbol)} [event] The event name.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) clearEvent(this, evt);
} else {
this._events = new Events();
this._eventsCount = 0;
}
return this;
};
//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
//
// Expose the prefix.
//
EventEmitter.prefixed = prefix;
//
// Allow `EventEmitter` to be imported as module namespace.
//
EventEmitter.EventEmitter = EventEmitter;
//
// Expose the module.
//
if (true) {
module.exports = EventEmitter;
}
/***/ }),
/***/ "./node_modules/url-toolkit/src/url-toolkit.js":
/*!*****************************************************!*\
!*** ./node_modules/url-toolkit/src/url-toolkit.js ***!
\*****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// see https://tools.ietf.org/html/rfc1808
(function (root) {
var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/;
var FIRST_SEGMENT_REGEX = /^([^\/?#]*)([^]*)$/;
var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
var URLToolkit = {
// If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
// E.g
// With opts.alwaysNormalize = false (default, spec compliant)
// http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
// With opts.alwaysNormalize = true (not spec compliant)
// http://a.com/b/cd + /e/f/../g => http://a.com/e/g
buildAbsoluteURL: function (baseURL, relativeURL, opts) {
opts = opts || {};
// remove any remaining space and CRLF
baseURL = baseURL.trim();
relativeURL = relativeURL.trim();
if (!relativeURL) {
// 2a) If the embedded URL is entirely empty, it inherits the
// entire base URL (i.e., is set equal to the base URL)
// and we are done.
if (!opts.alwaysNormalize) {
return baseURL;
}
var basePartsForNormalise = URLToolkit.parseURL(baseURL);
if (!basePartsForNormalise) {
throw new Error('Error trying to parse base URL.');
}
basePartsForNormalise.path = URLToolkit.normalizePath(
basePartsForNormalise.path
);
return URLToolkit.buildURLFromParts(basePartsForNormalise);
}
var relativeParts = URLToolkit.parseURL(relativeURL);
if (!relativeParts) {
throw new Error('Error trying to parse relative URL.');
}
if (relativeParts.scheme) {
// 2b) If the embedded URL starts with a scheme name, it is
// interpreted as an absolute URL and we are done.
if (!opts.alwaysNormalize) {
return relativeURL;
}
relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
return URLToolkit.buildURLFromParts(relativeParts);
}
var baseParts = URLToolkit.parseURL(baseURL);
if (!baseParts) {
throw new Error('Error trying to parse base URL.');
}
if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
// If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
// This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
baseParts.netLoc = pathParts[1];
baseParts.path = pathParts[2];
}
if (baseParts.netLoc && !baseParts.path) {
baseParts.path = '/';
}
var builtParts = {
// 2c) Otherwise, the embedded URL inherits the scheme of
// the base URL.
scheme: baseParts.scheme,
netLoc: relativeParts.netLoc,
path: null,
params: relativeParts.params,
query: relativeParts.query,
fragment: relativeParts.fragment,
};
if (!relativeParts.netLoc) {
// 3) If the embedded URL's <net_loc> is non-empty, we skip to
// Step 7. Otherwise, the embedded URL inherits the <net_loc>
// (if any) of the base URL.
builtParts.netLoc = baseParts.netLoc;
// 4) If the embedded URL path is preceded by a slash "/", the
// path is not relative and we skip to Step 7.
if (relativeParts.path[0] !== '/') {
if (!relativeParts.path) {
// 5) If the embedded URL path is empty (and not preceded by a
// slash), then the embedded URL inherits the base URL path
builtParts.path = baseParts.path;
// 5a) if the embedded URL's <params> is non-empty, we skip to
// step 7; otherwise, it inherits the <params> of the base
// URL (if any) and
if (!relativeParts.params) {
builtParts.params = baseParts.params;
// 5b) if the embedded URL's <query> is non-empty, we skip to
// step 7; otherwise, it inherits the <query> of the base
// URL (if any) and we skip to step 7.
if (!relativeParts.query) {
builtParts.query = baseParts.query;
}
}
} else {
// 6) The last segment of the base URL's path (anything
// following the rightmost slash "/", or the entire path if no
// slash is present) is removed and the embedded URL's path is
// appended in its place.
var baseURLPath = baseParts.path;
var newPath =
baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
relativeParts.path;
builtParts.path = URLToolkit.normalizePath(newPath);
}
}
}
if (builtParts.path === null) {
builtParts.path = opts.alwaysNormalize
? URLToolkit.normalizePath(relativeParts.path)
: relativeParts.path;
}
return URLToolkit.buildURLFromParts(builtParts);
},
parseURL: function (url) {
var parts = URL_REGEX.exec(url);
if (!parts) {
return null;
}
return {
scheme: parts[1] || '',
netLoc: parts[2] || '',
path: parts[3] || '',
params: parts[4] || '',
query: parts[5] || '',
fragment: parts[6] || '',
};
},
normalizePath: function (path) {
// The following operations are
// then applied, in order, to the new path:
// 6a) All occurrences of "./", where "." is a complete path
// segment, are removed.
// 6b) If the path ends with "." as a complete path segment,
// that "." is removed.
path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
// 6c) All occurrences of "<segment>/../", where <segment> is a
// complete path segment not equal to "..", are removed.
// Removal of these path segments is performed iteratively,
// removing the leftmost matching pattern on each iteration,
// until no matching pattern remains.
// 6d) If the path ends with "<segment>/..", where <segment> is a
// complete path segment not equal to "..", that
// "<segment>/.." is removed.
while (
path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
) {}
return path.split('').reverse().join('');
},
buildURLFromParts: function (parts) {
return (
parts.scheme +
parts.netLoc +
parts.path +
parts.params +
parts.query +
parts.fragment
);
},
};
if (true)
module.exports = URLToolkit;
else {}
})(this);
/***/ }),
/***/ "./node_modules/webworkify-webpack/index.js":
/*!**************************************************!*\
!*** ./node_modules/webworkify-webpack/index.js ***!
\**************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
function webpackBootstrapFunc (modules) {
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/ // on error function for async loading
/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
return f.default || f // try to call default if defined to also support babel esmodule exports
}
var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
// http://stackoverflow.com/a/2593661/130442
function quoteRegExp (str) {
return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
}
function isNumeric(n) {
return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN
}
function getModuleDependencies (sources, module, queueName) {
var retval = {}
retval[queueName] = []
var fnString = module.toString()
var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)
if (!wrapperSignature) return retval
var webpackRequireName = wrapperSignature[1]
// main bundle deps
var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
var match
while ((match = re.exec(fnString))) {
if (match[3] === 'dll-reference') continue
retval[queueName].push(match[3])
}
// dll deps
re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
while ((match = re.exec(fnString))) {
if (!sources[match[2]]) {
retval[queueName].push(match[1])
sources[match[2]] = __webpack_require__(match[1]).m
}
retval[match[2]] = retval[match[2]] || []
retval[match[2]].push(match[4])
}
// convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3
var keys = Object.keys(retval);
for (var i = 0; i < keys.length; i++) {
for (var j = 0; j < retval[keys[i]].length; j++) {
if (isNumeric(retval[keys[i]][j])) {
retval[keys[i]][j] = 1 * retval[keys[i]][j];
}
}
}
return retval
}
function hasValuesInQueues (queues) {
var keys = Object.keys(queues)
return keys.reduce(function (hasValues, key) {
return hasValues || queues[key].length > 0
}, false)
}
function getRequiredModules (sources, moduleId) {
var modulesQueue = {
main: [moduleId]
}
var requiredModules = {
main: []
}
var seenModules = {
main: {}
}
while (hasValuesInQueues(modulesQueue)) {
var queues = Object.keys(modulesQueue)
for (var i = 0; i < queues.length; i++) {
var queueName = queues[i]
var queue = modulesQueue[queueName]
var moduleToCheck = queue.pop()
seenModules[queueName] = seenModules[queueName] || {}
if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
seenModules[queueName][moduleToCheck] = true
requiredModules[queueName] = requiredModules[queueName] || []
requiredModules[queueName].push(moduleToCheck)
var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
var newModulesKeys = Object.keys(newModules)
for (var j = 0; j < newModulesKeys.length; j++) {
modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
}
}
}
return requiredModules
}
module.exports = function (moduleId, options) {
options = options || {}
var sources = {
main: __webpack_require__.m
}
var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)
var src = ''
Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
var entryModule = 0
while (requiredModules[module][entryModule]) {
entryModule++
}
requiredModules[module].push(entryModule)
sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n'
})
src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);'
var blob = new window.Blob([src], { type: 'text/javascript' })
if (options.bare) { return blob }
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
var workerUrl = URL.createObjectURL(blob)
var worker = new window.Worker(workerUrl)
worker.objectURL = workerUrl
return worker
}
/***/ }),
/***/ "./src/config.ts":
/*!***********************!*\
!*** ./src/config.ts ***!
\***********************/
/*! exports provided: hlsDefaultConfig, mergeConfig, enableStreamingMode */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hlsDefaultConfig", function() { return hlsDefaultConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeConfig", function() { return mergeConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableStreamingMode", function() { return enableStreamingMode; });
/* harmony import */ var _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./controller/abr-controller */ "./src/controller/abr-controller.ts");
/* harmony import */ var _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./controller/audio-stream-controller */ "./src/controller/audio-stream-controller.ts");
/* harmony import */ var _controller_audio_track_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./controller/audio-track-controller */ "./src/controller/audio-track-controller.ts");
/* harmony import */ var _controller_subtitle_stream_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/subtitle-stream-controller */ "./src/controller/subtitle-stream-controller.ts");
/* harmony import */ var _controller_subtitle_track_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/subtitle-track-controller */ "./src/controller/subtitle-track-controller.ts");
/* harmony import */ var _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/buffer-controller */ "./src/controller/buffer-controller.ts");
/* harmony import */ var _controller_timeline_controller__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/timeline-controller */ "./src/controller/timeline-controller.ts");
/* harmony import */ var _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/cap-level-controller */ "./src/controller/cap-level-controller.ts");
/* harmony import */ var _controller_fps_controller__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./controller/fps-controller */ "./src/controller/fps-controller.ts");
/* harmony import */ var _controller_eme_controller__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./controller/eme-controller */ "./src/controller/eme-controller.ts");
/* harmony import */ var _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./utils/xhr-loader */ "./src/utils/xhr-loader.ts");
/* harmony import */ var _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils/fetch-loader */ "./src/utils/fetch-loader.ts");
/* harmony import */ var _utils_cues__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/cues */ "./src/utils/cues.ts");
/* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
// If possible, keep hlsDefaultConfig shallow
// It is cloned whenever a new Hls instance is created, by keeping the config
// shallow the properties are cloned, and we don't end up manipulating the default
var hlsDefaultConfig = _objectSpread(_objectSpread({
autoStartLoad: true,
// used by stream-controller
startPosition: -1,
// used by stream-controller
defaultAudioCodec: undefined,
// used by stream-controller
debug: false,
// used by logger
capLevelOnFPSDrop: false,
// used by fps-controller
capLevelToPlayerSize: false,
// used by cap-level-controller
initialLiveManifestSize: 1,
// used by stream-controller
maxBufferLength: 30,
// used by stream-controller
backBufferLength: Infinity,
// used by buffer-controller
maxBufferSize: 60 * 1000 * 1000,
// used by stream-controller
maxBufferHole: 0.1,
// used by stream-controller
highBufferWatchdogPeriod: 2,
// used by stream-controller
nudgeOffset: 0.1,
// used by stream-controller
nudgeMaxRetry: 3,
// used by stream-controller
maxFragLookUpTolerance: 0.25,
// used by stream-controller
liveSyncDurationCount: 3,
// used by latency-controller
liveMaxLatencyDurationCount: Infinity,
// used by latency-controller
liveSyncDuration: undefined,
// used by latency-controller
liveMaxLatencyDuration: undefined,
// used by latency-controller
maxLiveSyncPlaybackRate: 1,
// used by latency-controller
liveDurationInfinity: false,
// used by buffer-controller
liveBackBufferLength: null,
// used by buffer-controller
maxMaxBufferLength: 600,
// used by stream-controller
enableWorker: true,
// used by demuxer
enableSoftwareAES: true,
// used by decrypter
manifestLoadingTimeOut: 10000,
// used by playlist-loader
manifestLoadingMaxRetry: 1,
// used by playlist-loader
manifestLoadingRetryDelay: 1000,
// used by playlist-loader
manifestLoadingMaxRetryTimeout: 64000,
// used by playlist-loader
startLevel: undefined,
// used by level-controller
levelLoadingTimeOut: 10000,
// used by playlist-loader
levelLoadingMaxRetry: 4,
// used by playlist-loader
levelLoadingRetryDelay: 1000,
// used by playlist-loader
levelLoadingMaxRetryTimeout: 64000,
// used by playlist-loader
fragLoadingTimeOut: 20000,
// used by fragment-loader
fragLoadingMaxRetry: 6,
// used by fragment-loader
fragLoadingRetryDelay: 1000,
// used by fragment-loader
fragLoadingMaxRetryTimeout: 64000,
// used by fragment-loader
startFragPrefetch: false,
// used by stream-controller
fpsDroppedMonitoringPeriod: 5000,
// used by fps-controller
fpsDroppedMonitoringThreshold: 0.2,
// used by fps-controller
appendErrorMaxRetry: 3,
// used by buffer-controller
loader: _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_10__["default"],
// loader: FetchLoader,
fLoader: undefined,
// used by fragment-loader
pLoader: undefined,
// used by playlist-loader
xhrSetup: undefined,
// used by xhr-loader
licenseXhrSetup: undefined,
// used by eme-controller
licenseResponseCallback: undefined,
// used by eme-controller
abrController: _controller_abr_controller__WEBPACK_IMPORTED_MODULE_0__["default"],
bufferController: _controller_buffer_controller__WEBPACK_IMPORTED_MODULE_5__["default"],
capLevelController: _controller_cap_level_controller__WEBPACK_IMPORTED_MODULE_7__["default"],
fpsController: _controller_fps_controller__WEBPACK_IMPORTED_MODULE_8__["default"],
stretchShortVideoTrack: false,
// used by mp4-remuxer
maxAudioFramesDrift: 1,
// used by mp4-remuxer
forceKeyFrameOnDiscontinuity: true,
// used by ts-demuxer
abrEwmaFastLive: 3,
// used by abr-controller
abrEwmaSlowLive: 9,
// used by abr-controller
abrEwmaFastVoD: 3,
// used by abr-controller
abrEwmaSlowVoD: 9,
// used by abr-controller
abrEwmaDefaultEstimate: 5e5,
// 500 kbps // used by abr-controller
abrBandWidthFactor: 0.95,
// used by abr-controller
abrBandWidthUpFactor: 0.7,
// used by abr-controller
abrMaxWithRealBitrate: false,
// used by abr-controller
maxStarvationDelay: 4,
// used by abr-controller
maxLoadingDelay: 4,
// used by abr-controller
minAutoBitrate: 0,
// used by hls
emeEnabled: false,
// used by eme-controller
widevineLicenseUrl: undefined,
// used by eme-controller
drmSystemOptions: {},
// used by eme-controller
requestMediaKeySystemAccessFunc: _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_13__["requestMediaKeySystemAccess"],
// used by eme-controller
testBandwidth: true,
progressive: false,
lowLatencyMode: true
}, timelineConfig()), {}, {
subtitleStreamController: true ? _controller_subtitle_stream_controller__WEBPACK_IMPORTED_MODULE_3__["SubtitleStreamController"] : undefined,
subtitleTrackController: true ? _controller_subtitle_track_controller__WEBPACK_IMPORTED_MODULE_4__["default"] : undefined,
timelineController: true ? _controller_timeline_controller__WEBPACK_IMPORTED_MODULE_6__["TimelineController"] : undefined,
audioStreamController: true ? _controller_audio_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"] : undefined,
audioTrackController: true ? _controller_audio_track_controller__WEBPACK_IMPORTED_MODULE_2__["default"] : undefined,
emeController: true ? _controller_eme_controller__WEBPACK_IMPORTED_MODULE_9__["default"] : undefined
});
function timelineConfig() {
return {
cueHandler: _utils_cues__WEBPACK_IMPORTED_MODULE_12__["default"],
// used by timeline-controller
enableCEA708Captions: true,
// used by timeline-controller
enableWebVTT: true,
// used by timeline-controller
enableIMSC1: true,
// used by timeline-controller
captionsTextTrack1Label: 'English',
// used by timeline-controller
captionsTextTrack1LanguageCode: 'en',
// used by timeline-controller
captionsTextTrack2Label: 'Spanish',
// used by timeline-controller
captionsTextTrack2LanguageCode: 'es',
// used by timeline-controller
captionsTextTrack3Label: 'Unknown CC',
// used by timeline-controller
captionsTextTrack3LanguageCode: '',
// used by timeline-controller
captionsTextTrack4Label: 'Unknown CC',
// used by timeline-controller
captionsTextTrack4LanguageCode: '',
// used by timeline-controller
renderTextTracksNatively: true
};
}
function mergeConfig(defaultConfig, userConfig) {
if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");
}
if (userConfig.liveMaxLatencyDurationCount !== undefined && (userConfig.liveSyncDurationCount === undefined || userConfig.liveMaxLatencyDurationCount <= userConfig.liveSyncDurationCount)) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');
}
if (userConfig.liveMaxLatencyDuration !== undefined && (userConfig.liveSyncDuration === undefined || userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');
}
return _extends({}, defaultConfig, userConfig);
}
function enableStreamingMode(config) {
var currentLoader = config.loader;
if (currentLoader !== _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_11__["default"] && currentLoader !== _utils_xhr_loader__WEBPACK_IMPORTED_MODULE_10__["default"]) {
// If a developer has configured their own loader, respect that choice
_utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log('[config]: Custom loader detected, cannot enable progressive streaming');
config.progressive = false;
} else {
var canStreamProgressively = Object(_utils_fetch_loader__WEBPACK_IMPORTED_MODULE_11__["fetchSupported"])();
if (canStreamProgressively) {
config.loader = _utils_fetch_loader__WEBPACK_IMPORTED_MODULE_11__["default"];
config.progressive = true;
config.enableSoftwareAES = true;
_utils_logger__WEBPACK_IMPORTED_MODULE_14__["logger"].log('[config]: Progressive streaming enabled, using FetchLoader');
}
}
}
/***/ }),
/***/ "./src/controller/abr-controller.ts":
/*!******************************************!*\
!*** ./src/controller/abr-controller.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/ewma-bandwidth-estimator */ "./src/utils/ewma-bandwidth-estimator.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var AbrController = /*#__PURE__*/function () {
function AbrController(hls) {
this.hls = void 0;
this.lastLoadedFragLevel = 0;
this._nextAutoLevel = -1;
this.timer = void 0;
this.onCheck = this._abandonRulesCheck.bind(this);
this.fragCurrent = null;
this.partCurrent = null;
this.bitrateTestDelay = 0;
this.bwEstimator = void 0;
this.hls = hls;
var config = hls.config;
this.bwEstimator = new _utils_ewma_bandwidth_estimator__WEBPACK_IMPORTED_MODULE_1__["default"](config.abrEwmaSlowVoD, config.abrEwmaFastVoD, config.abrEwmaDefaultEstimate);
this.registerListeners();
}
var _proto = AbrController.prototype;
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.clearTimer(); // @ts-ignore
this.hls = this.onCheck = null;
this.fragCurrent = this.partCurrent = null;
};
_proto.onFragLoading = function onFragLoading(event, data) {
var frag = data.frag;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN) {
if (!this.timer) {
var _data$part;
this.fragCurrent = frag;
this.partCurrent = (_data$part = data.part) != null ? _data$part : null;
this.timer = self.setInterval(this.onCheck, 100);
}
}
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
var config = this.hls.config;
if (data.details.live) {
this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);
} else {
this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);
}
}
/*
This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load
quickly enough to prevent underbuffering
*/
;
_proto._abandonRulesCheck = function _abandonRulesCheck() {
var frag = this.fragCurrent,
part = this.partCurrent,
hls = this.hls;
var autoLevelEnabled = hls.autoLevelEnabled,
config = hls.config,
media = hls.media;
if (!frag || !media) {
return;
}
var stats = part ? part.stats : frag.stats;
var duration = part ? part.duration : frag.duration; // If loading has been aborted and not in lowLatencyMode, stop timer and return
if (stats.aborted) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('frag loader destroy or aborted, disarm abandonRules');
this.clearTimer(); // reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1;
return;
} // This check only runs if we're in ABR mode and actually playing
if (!autoLevelEnabled || media.paused || !media.playbackRate || !media.readyState) {
return;
}
var requestDelay = performance.now() - stats.loading.start;
var playbackRate = Math.abs(media.playbackRate); // In order to work with a stable bandwidth, only begin monitoring bandwidth after half of the fragment has been loaded
if (requestDelay <= 500 * duration / playbackRate) {
return;
}
var levels = hls.levels,
minAutoLevel = hls.minAutoLevel;
var level = levels[frag.level];
var expectedLen = stats.total || Math.max(stats.loaded, Math.round(duration * level.maxBitrate / 8));
var loadRate = Math.max(1, stats.bwEstimate ? stats.bwEstimate / 8 : stats.loaded * 1000 / requestDelay); // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the entire fragment
var fragLoadedDelay = (expectedLen - stats.loaded) / loadRate;
var pos = media.currentTime; // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer
var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // Attempt an emergency downswitch only if less than 2 fragment lengths are buffered, and the time to finish loading
// the current fragment is greater than the amount of buffer we have left
if (bufferStarvationDelay >= 2 * duration / playbackRate || fragLoadedDelay <= bufferStarvationDelay) {
return;
}
var fragLevelNextLoadedDelay = Number.POSITIVE_INFINITY;
var nextLoadLevel; // Iterate through lower level and try to find the largest one that avoids rebuffering
for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
// compute time to load next fragment at lower level
// 0.8 : consider only 80% of current bw to be conservative
// 8 = bits per byte (bps/Bps)
var levelNextBitrate = levels[nextLoadLevel].maxBitrate;
fragLevelNextLoadedDelay = duration * levelNextBitrate / (8 * 0.8 * loadRate);
if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
break;
}
} // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing
// to load the current one
if (fragLevelNextLoadedDelay >= fragLoadedDelay) {
return;
}
var bwEstimate = this.bwEstimator.getEstimate();
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Fragment " + frag.sn + (part ? ' part ' + part.index : '') + " of level " + frag.level + " is loading too slowly and will cause an underbuffer; aborting and switching to level " + nextLoadLevel + "\n Current BW estimate: " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(bwEstimate) ? (bwEstimate / 1024).toFixed(3) : 'Unknown') + " Kb/s\n Estimated load time for current fragment: " + fragLoadedDelay.toFixed(3) + " s\n Estimated load time for the next fragment: " + fragLevelNextLoadedDelay.toFixed(3) + " s\n Time to underbuffer: " + bufferStarvationDelay.toFixed(3) + " s");
hls.nextLoadLevel = nextLoadLevel;
this.bwEstimator.sample(requestDelay, stats.loaded);
this.clearTimer();
if (frag.loader) {
this.fragCurrent = this.partCurrent = null;
frag.loader.abort();
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, {
frag: frag,
part: part,
stats: stats
});
};
_proto.onFragLoaded = function onFragLoaded(event, _ref) {
var frag = _ref.frag,
part = _ref.part;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn)) {
var stats = part ? part.stats : frag.stats;
var duration = part ? part.duration : frag.duration; // stop monitoring bw once frag loaded
this.clearTimer(); // store level id after successful fragment load
this.lastLoadedFragLevel = frag.level; // reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1; // compute level average bitrate
if (this.hls.config.abrMaxWithRealBitrate) {
var level = this.hls.levels[frag.level];
var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + stats.loaded;
var loadedDuration = (level.loaded ? level.loaded.duration : 0) + duration;
level.loaded = {
bytes: loadedBytes,
duration: loadedDuration
};
level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
}
if (frag.bitrateTest) {
var fragBufferedData = {
stats: stats,
frag: frag,
part: part,
id: frag.type
};
this.onFragBuffered(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, fragBufferedData);
frag.bitrateTest = false;
}
}
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
var frag = data.frag,
part = data.part;
var stats = part ? part.stats : frag.stats;
if (stats.aborted) {
return;
} // Only count non-alt-audio frags which were actually buffered in our BW calculations
if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_5__["PlaylistLevelType"].MAIN || frag.sn === 'initSegment') {
return;
} // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;
// rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch
// is used. If we used buffering in that case, our BW estimate sample will be very large.
var processingMs = stats.parsing.end - stats.loading.start;
this.bwEstimator.sample(processingMs, stats.loaded);
stats.bwEstimate = this.bwEstimator.getEstimate();
if (frag.bitrateTest) {
this.bitrateTestDelay = processingMs / 1000;
} else {
this.bitrateTestDelay = 0;
}
};
_proto.onError = function onError(event, data) {
// stop timer in case of frag loading error
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
this.clearTimer();
break;
default:
break;
}
};
_proto.clearTimer = function clearTimer() {
self.clearInterval(this.timer);
this.timer = undefined;
} // return next auto level
;
_proto.getNextABRAutoLevel = function getNextABRAutoLevel() {
var fragCurrent = this.fragCurrent,
partCurrent = this.partCurrent,
hls = this.hls;
var maxAutoLevel = hls.maxAutoLevel,
config = hls.config,
minAutoLevel = hls.minAutoLevel,
media = hls.media;
var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
var pos = media ? media.currentTime : 0; // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as
// if we're playing back at the normal rate.
var playbackRate = media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;
var avgbw = this.bwEstimator ? this.bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate; // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
var bufferStarvationDelay = (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, pos, config.maxBufferHole).end - pos) / playbackRate; // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
var bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor);
if (bestLevel >= 0) {
return bestLevel;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace((bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty') + ", finding optimal quality level"); // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
// if no matching level found, logic will return 0
var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
var bwFactor = config.abrBandWidthFactor;
var bwUpFactor = config.abrBandWidthUpFactor;
if (!bufferStarvationDelay) {
// in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
var bitrateTestDelay = this.bitrateTestDelay;
if (bitrateTestDelay) {
// if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
// max video loading delay used in automatic start level selection :
// in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
// the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
// cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms"); // don't use conservative factor on bitrate test
bwFactor = bwUpFactor = 1;
}
}
bestLevel = this.findBestLevel(avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor);
return Math.max(bestLevel, 0);
};
_proto.findBestLevel = function findBestLevel(currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor) {
var _level$details;
var fragCurrent = this.fragCurrent,
partCurrent = this.partCurrent,
currentLevel = this.lastLoadedFragLevel;
var levels = this.hls.levels;
var level = levels[currentLevel];
var live = !!(level !== null && level !== void 0 && (_level$details = level.details) !== null && _level$details !== void 0 && _level$details.live);
var currentCodecSet = level === null || level === void 0 ? void 0 : level.codecSet;
var currentFragDuration = partCurrent ? partCurrent.duration : fragCurrent ? fragCurrent.duration : 0;
for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
var levelInfo = levels[i];
if (!levelInfo || currentCodecSet && levelInfo.codecSet !== currentCodecSet) {
continue;
}
var levelDetails = levelInfo.details;
var avgDuration = (partCurrent ? levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.partTarget : levelDetails === null || levelDetails === void 0 ? void 0 : levelDetails.averagetargetduration) || currentFragDuration;
var adjustedbw = void 0; // follow algorithm captured from stagefright :
// https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
// Pick the highest bandwidth stream below or equal to estimated bandwidth.
// consider only 80% of the available bandwidth, but if we are switching up,
// be even more conservative (70%) to avoid overestimating and immediately
// switching back.
if (i <= currentLevel) {
adjustedbw = bwFactor * currentBw;
} else {
adjustedbw = bwUpFactor * currentBw;
}
var bitrate = levels[i].maxBitrate;
var fetchDuration = bitrate * avgDuration / adjustedbw;
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: " + i + "/" + Math.round(adjustedbw) + "/" + bitrate + "/" + avgDuration + "/" + maxFetchDuration + "/" + fetchDuration); // if adjusted bw is greater than level bitrate AND
if (adjustedbw > bitrate && ( // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
// we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
// special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1
!fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
// as we are looping from highest to lowest, this will return the best achievable quality level
return i;
}
} // not enough time budget even with quality level 0 ... rebuffering might happen
return -1;
};
_createClass(AbrController, [{
key: "nextAutoLevel",
get: function get() {
var forcedAutoLevel = this._nextAutoLevel;
var bwEstimator = this.bwEstimator; // in case next auto level has been forced, and bw not available or not reliable, return forced value
if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
return forcedAutoLevel;
} // compute next level using ABR logic
var nextABRAutoLevel = this.getNextABRAutoLevel(); // if forced auto level has been defined, use it to cap ABR computed quality level
if (forcedAutoLevel !== -1) {
nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
}
return nextABRAutoLevel;
},
set: function set(nextLevel) {
this._nextAutoLevel = nextLevel;
}
}]);
return AbrController;
}();
/* harmony default export */ __webpack_exports__["default"] = (AbrController);
/***/ }),
/***/ "./src/controller/audio-stream-controller.ts":
/*!***************************************************!*\
!*** ./src/controller/audio-stream-controller.ts ***!
\***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts");
/* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts");
/* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
/* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
/* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts");
/* harmony import */ var _gap_controller__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./gap-controller */ "./src/controller/gap-controller.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var TICK_INTERVAL = 100; // how often to tick in ms
var AudioStreamController = /*#__PURE__*/function (_BaseStreamController) {
_inheritsLoose(AudioStreamController, _BaseStreamController);
function AudioStreamController(hls, fragmentTracker) {
var _this;
_this = _BaseStreamController.call(this, hls, fragmentTracker, '[audio-stream-controller]') || this;
_this.videoBuffer = null;
_this.videoTrackCC = -1;
_this.waitingVideoCC = -1;
_this.audioSwitch = false;
_this.trackId = -1;
_this.waitingData = null;
_this.mainDetails = null;
_this._registerListeners();
return _this;
}
var _proto = AudioStreamController.prototype;
_proto.onHandlerDestroying = function onHandlerDestroying() {
this._unregisterListeners();
this.mainDetails = null;
};
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, this.onError, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
} // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value
;
_proto.onInitPtsFound = function onInitPtsFound(event, _ref) {
var frag = _ref.frag,
id = _ref.id,
initPTS = _ref.initPTS;
// Always update the new INIT PTS
// Can change due level switch
if (id === 'main') {
var cc = frag.cc;
this.initPTS[frag.cc] = initPTS;
this.log("InitPTS for cc: " + cc + " found from main: " + initPTS);
this.videoTrackCC = cc; // If we are waiting, tick immediately to unblock audio fragment transmuxing
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS) {
this.tick();
}
}
};
_proto.startLoad = function startLoad(startPosition) {
if (!this.levels) {
this.startPosition = startPosition;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
return;
}
var lastCurrentTime = this.lastCurrentTime;
this.stopLoad();
this.setInterval(TICK_INTERVAL);
this.fragLoadError = 0;
if (lastCurrentTime > 0 && startPosition === -1) {
this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} else {
this.loadedmetadata = false;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK;
}
this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
this.tick();
};
_proto.doTick = function doTick() {
switch (this.state) {
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE:
this.doTickIdle();
break;
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK:
{
var _levels$trackId;
var levels = this.levels,
trackId = this.trackId;
var details = levels === null || levels === void 0 ? void 0 : (_levels$trackId = levels[trackId]) === null || _levels$trackId === void 0 ? void 0 : _levels$trackId.details;
if (details) {
if (this.waitForCdnTuneIn(details)) {
break;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS;
}
break;
}
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY:
{
var _this$media;
var now = performance.now();
var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
if (!retryDate || now >= retryDate || (_this$media = this.media) !== null && _this$media !== void 0 && _this$media.seeking) {
this.log('RetryDate reached, switch back to IDLE state');
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
break;
}
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS:
{
// Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
var waitingData = this.waitingData;
if (waitingData) {
var frag = waitingData.frag,
part = waitingData.part,
cache = waitingData.cache,
complete = waitingData.complete;
if (this.initPTS[frag.cc] !== undefined) {
this.waitingData = null;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING;
var payload = cache.flush();
var data = {
frag: frag,
part: part,
payload: payload,
networkDetails: null
};
this._handleFragmentLoadProgress(data);
if (complete) {
_BaseStreamController.prototype._handleFragmentLoadComplete.call(this, data);
}
} else if (this.videoTrackCC !== this.waitingVideoCC) {
// Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found
_utils_logger__WEBPACK_IMPORTED_MODULE_15__["logger"].log("Waiting fragment cc (" + frag.cc + ") cancelled because video is at cc " + this.videoTrackCC);
this.clearWaitingFragment();
} else {
// Drop waiting fragment if an earlier fragment is needed
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(this.mediaBuffer, this.media.currentTime, this.config.maxBufferHole);
var waitingFragmentAtPosition = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_11__["fragmentWithinToleranceTest"])(bufferInfo.end, this.config.maxFragLookUpTolerance, frag);
if (waitingFragmentAtPosition < 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_15__["logger"].log("Waiting fragment cc (" + frag.cc + ") @ " + frag.start + " cancelled because another fragment at " + bufferInfo.end + " is needed");
this.clearWaitingFragment();
}
}
} else {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
}
}
this.onTickEnd();
};
_proto.clearWaitingFragment = function clearWaitingFragment() {
var waitingData = this.waitingData;
if (waitingData) {
this.fragmentTracker.removeFragment(waitingData.frag);
this.waitingData = null;
this.waitingVideoCC = -1;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
};
_proto.onTickEnd = function onTickEnd() {
var media = this.media;
if (!media || !media.readyState) {
// Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
return;
}
var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
var buffered = mediaBuffer.buffered;
if (!this.loadedmetadata && buffered.length) {
this.loadedmetadata = true;
}
this.lastCurrentTime = media.currentTime;
};
_proto.doTickIdle = function doTickIdle() {
var _frag$decryptdata, _frag$decryptdata2;
var hls = this.hls,
levels = this.levels,
media = this.media,
trackId = this.trackId;
var config = hls.config;
if (!levels || !levels[trackId]) {
return;
} // if video not attached AND
// start fragment already requested OR start frag prefetch not enabled
// exit loop
// => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
if (!media && (this.startFragRequested || !config.startFragPrefetch)) {
return;
}
var pos = this.getLoadPosition();
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(pos)) {
return;
}
var levelInfo = levels[trackId];
var trackDetails = levelInfo.details;
if (!trackDetails || trackDetails.live && this.levelLastLoaded !== trackId || this.waitForCdnTuneIn(trackDetails)) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK;
return;
}
var frag = trackDetails.initSegment;
var targetBufferTime = 0;
if (!frag || frag.data) {
var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : this.media;
var videoBuffer = this.videoBuffer ? this.videoBuffer : this.media;
var maxBufferHole = pos < config.maxBufferHole ? Math.max(_gap_controller__WEBPACK_IMPORTED_MODULE_13__["MAX_START_GAP_JUMP"], config.maxBufferHole) : config.maxBufferHole;
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(mediaBuffer, pos, maxBufferHole);
var mainBufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(videoBuffer, pos, maxBufferHole);
var bufferLen = bufferInfo.len;
var maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
var maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len);
var audioSwitch = this.audioSwitch; // if buffer length is less than maxBufLen try to load a new fragment
if (bufferLen >= maxBufLen && !audioSwitch) {
return;
}
if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_EOS, {
type: 'audio'
});
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ENDED;
return;
}
var fragments = trackDetails.fragments;
var start = fragments[0].start;
targetBufferTime = bufferInfo.end;
if (audioSwitch) {
targetBufferTime = pos; // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
if (trackDetails.PTSKnown && pos < start) {
// if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
if (bufferInfo.end > start || bufferInfo.nextStart) {
this.log('Alt audio track ahead of main track, seek to start of alt audio track');
media.currentTime = start + 0.05;
}
}
}
frag = this.getNextFragment(targetBufferTime, trackDetails);
if (!frag) {
return;
}
}
if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === 'identity' && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) {
this.loadKey(frag, trackDetails);
} else {
this.loadFragment(frag, trackDetails, targetBufferTime);
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
this.videoBuffer = null;
_BaseStreamController.prototype.onMediaDetaching.call(this);
};
_proto.onAudioTracksUpdated = function onAudioTracksUpdated(event, _ref2) {
var audioTracks = _ref2.audioTracks;
this.resetTransmuxer();
this.levels = audioTracks.map(function (mediaPlaylist) {
return new _types_level__WEBPACK_IMPORTED_MODULE_5__["Level"](mediaPlaylist);
});
};
_proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
// if any URL found on new audio track, it is an alternate audio track
var altAudio = !!data.url;
this.trackId = data.id;
var fragCurrent = this.fragCurrent;
if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null;
this.clearWaitingFragment(); // destroy useless transmuxer when switching audio to main
if (!altAudio) {
this.resetTransmuxer();
} else {
// switching to audio track, start timer if not already started
this.setInterval(TICK_INTERVAL);
} // should we switch tracks ?
if (altAudio) {
this.audioSwitch = true; // main audio track are handled by stream-controller, just do something if switching to alt audio track
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} else {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
}
this.tick();
};
_proto.onManifestLoading = function onManifestLoading() {
this.mainDetails = null;
this.fragmentTracker.removeAllFragments();
this.startPosition = this.lastCurrentTime = 0;
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
if (this.mainDetails === null) {
var mainDetails = this.mainDetails = data.details; // compute start position if we haven't already
var trackId = this.levelLastLoaded;
if (trackId !== null && this.levels && this.startPosition === -1 && mainDetails.live) {
var track = this.levels[trackId];
if (!track.details || !track.details.fragments[0]) {
return;
}
Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__["alignPDT"])(track.details, mainDetails);
this.setStartPosition(track.details, track.details.fragments[0].start);
}
}
};
_proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) {
var _track$details;
var levels = this.levels;
var newDetails = data.details,
trackId = data.id;
if (!levels) {
this.warn("Audio tracks were reset while loading level " + trackId);
return;
}
this.log("Track " + trackId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "],duration:" + newDetails.totalduration);
var track = levels[trackId];
var sliding = 0;
if (newDetails.live || (_track$details = track.details) !== null && _track$details !== void 0 && _track$details.live) {
var _this$mainDetails;
if (!newDetails.fragments[0]) {
newDetails.deltaUpdateFailed = true;
}
if (newDetails.deltaUpdateFailed) {
return;
}
if (!track.details && (_this$mainDetails = this.mainDetails) !== null && _this$mainDetails !== void 0 && _this$mainDetails.hasProgramDateTime && newDetails.hasProgramDateTime) {
Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_12__["alignPDT"])(newDetails, this.mainDetails);
sliding = newDetails.fragments[0].start;
} else {
sliding = this.alignPlaylists(newDetails, track.details);
}
}
track.details = newDetails;
this.levelLastLoaded = trackId; // compute start position if we are aligned with the main playlist
if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {
this.setStartPosition(track.details, sliding);
} // only switch back to IDLE state if we were waiting for track to start downloading a new fragment
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_TRACK && !this.waitForCdnTuneIn(newDetails)) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} // trigger handler right now
this.tick();
};
_proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
var _details$initSegment;
var frag = data.frag,
part = data.part,
payload = data.payload;
var config = this.config,
trackId = this.trackId,
levels = this.levels;
if (!levels) {
this.warn("Audio tracks were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
return;
}
var track = levels[trackId];
console.assert(track, 'Audio track is defined on fragment load progress');
var details = track.details;
console.assert(details, 'Audio track details are defined on fragment load progress');
var audioCodec = config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2';
var transmuxer = this.transmuxer;
if (!transmuxer) {
transmuxer = this.transmuxer = new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_9__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
} // Check if we have video initPTS
// If not we need to wait for it
var initPTS = this.initPTS[frag.cc];
var initSegmentData = (_details$initSegment = details.initSegment) === null || _details$initSegment === void 0 ? void 0 : _details$initSegment.data;
if (initPTS !== undefined) {
// this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);
// time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
var accurateTimeOffset = false; // details.PTSKnown || !details.live;
var partIndex = part ? part.index : -1;
var partial = partIndex !== -1;
var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_10__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
transmuxer.push(payload, initSegmentData, audioCodec, '', frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_15__["logger"].log("Unknown video PTS for cc " + frag.cc + ", waiting for video PTS before demuxing audio frag " + frag.sn + " of [" + details.startSN + " ," + details.endSN + "],track " + trackId);
var _this$waitingData = this.waitingData = this.waitingData || {
frag: frag,
part: part,
cache: new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_8__["default"](),
complete: false
},
cache = _this$waitingData.cache;
cache.push(new Uint8Array(payload));
this.waitingVideoCC = this.videoTrackCC;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS;
}
};
_proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) {
if (this.waitingData) {
this.waitingData.complete = true;
return;
}
_BaseStreamController.prototype._handleFragmentLoadComplete.call(this, fragLoadedData);
};
_proto.onBufferReset = function onBufferReset()
/* event: Events.BUFFER_RESET */
{
// reset reference to sourcebuffers
this.mediaBuffer = this.videoBuffer = null;
this.loadedmetadata = false;
};
_proto.onBufferCreated = function onBufferCreated(event, data) {
var audioTrack = data.tracks.audio;
if (audioTrack) {
this.mediaBuffer = audioTrack.buffer;
}
if (data.tracks.video) {
this.videoBuffer = data.tracks.video.buffer;
}
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
var frag = data.frag,
part = data.part;
if (frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO) {
return;
}
if (this.fragContextChanged(frag)) {
// If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
// Avoid setting state back to IDLE or concluding the audio switch; otherwise, the switched-to track will not buffer
this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state + ", audioSwitch: " + this.audioSwitch);
return;
}
if (frag.sn !== 'initSegment') {
this.fragPrevious = frag;
if (this.audioSwitch) {
this.audioSwitch = false;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHED, {
id: this.trackId
});
}
}
this.fragBufferedComplete(frag, part);
};
_proto.onError = function onError(event, data) {
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].KEY_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].KEY_LOAD_TIMEOUT:
// TODO: Skip fragments that do not belong to this.fragCurrent audio-group id
this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO, data);
break;
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT:
// when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR && this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED) {
// if fatal error, stop processing, otherwise move to IDLE to retry loading
this.state = data.fatal ? _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR : _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
this.warn(data.details + " while loading frag, switching to " + this.state + " state");
}
break;
case _errors__WEBPACK_IMPORTED_MODULE_14__["ErrorDetails"].BUFFER_FULL_ERROR:
// if in appending state
if (data.parent === 'audio' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED)) {
var media = this.mediaBuffer;
var currentTime = this.media.currentTime;
var mediaBuffered = media && _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].isBuffered(media, currentTime) && _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].isBuffered(media, currentTime + 0.5); // reduce max buf len if current position is buffered
if (mediaBuffered) {
this.reduceMaxBufferLength();
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} else {
// current position is not buffered, but browser is still complaining about buffer full error
// this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
// in that case flush the whole audio buffer to recover
this.warn('Buffer full error also media.currentTime is not buffered, flush audio buffer');
this.fragCurrent = null;
_BaseStreamController.prototype.flushMainBuffer.call(this, 0, Number.POSITIVE_INFINITY, 'audio');
}
}
break;
default:
break;
}
};
_proto.onBufferFlushed = function onBufferFlushed(event, _ref3) {
var type = _ref3.type;
if (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO) {
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO);
}
};
_proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
var _id3$samples;
var id = 'audio';
var hls = this.hls;
var remuxResult = transmuxResult.remuxResult,
chunkMeta = transmuxResult.chunkMeta;
var context = this.getCurrentContext(chunkMeta);
if (!context) {
this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered.");
this.resetLiveStartWhenNotLoaded(chunkMeta.level);
return;
}
var frag = context.frag,
part = context.part;
var audio = remuxResult.audio,
text = remuxResult.text,
id3 = remuxResult.id3,
initSegment = remuxResult.initSegment; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
// If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
if (this.fragContextChanged(frag)) {
return;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING;
if (this.audioSwitch && audio) {
this.completeAudioSwitch();
}
if (initSegment !== null && initSegment !== void 0 && initSegment.tracks) {
this._bufferInitSegment(initSegment.tracks, frag, chunkMeta);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_INIT_SEGMENT, {
frag: frag,
id: id,
tracks: initSegment.tracks
}); // Only flush audio from old audio tracks when PTS is known on new audio track
}
if (audio) {
var startPTS = audio.startPTS,
endPTS = audio.endPTS,
startDTS = audio.startDTS,
endDTS = audio.endDTS;
if (part) {
part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO] = {
startPTS: startPTS,
endPTS: endPTS,
startDTS: startDTS,
endDTS: endDTS
};
}
frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, startPTS, endPTS, startDTS, endDTS);
this.bufferFragmentData(audio, frag, part, chunkMeta);
}
if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) {
var emittedID3 = _extends({
frag: frag,
id: id
}, id3);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_METADATA, emittedID3);
}
if (text) {
var emittedText = _extends({
frag: frag,
id: id
}, text);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].FRAG_PARSING_USERDATA, emittedText);
}
};
_proto._bufferInitSegment = function _bufferInitSegment(tracks, frag, chunkMeta) {
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING) {
return;
} // delete any video track found on audio transmuxer
if (tracks.video) {
delete tracks.video;
} // include levelCodec in audio and video tracks
var track = tracks.audio;
if (!track) {
return;
}
track.levelCodec = track.codec;
track.id = 'audio';
this.log("Init audio buffer, container:" + track.container + ", codecs[parsed]=[" + track.codec + "]");
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_CODECS, tracks);
var initSegment = track.initSegment;
if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) {
var segment = {
type: 'audio',
frag: frag,
part: null,
chunkMeta: chunkMeta,
parent: frag.type,
data: initSegment
};
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].BUFFER_APPENDING, segment);
} // trigger handler right now
this.tick();
};
_proto.loadFragment = function loadFragment(frag, trackDetails, targetBufferTime) {
// only load if fragment is not loaded or if in audio switch
var fragState = this.fragmentTracker.getState(frag);
this.fragCurrent = frag; // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
if (this.audioSwitch || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentState"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentState"].PARTIAL) {
if (frag.sn === 'initSegment') {
this._loadInitSegment(frag);
} else if (trackDetails.live && !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.initPTS[frag.cc])) {
this.log("Waiting for video PTS in continuity counter " + frag.cc + " of live stream before loading audio fragment " + frag.sn + " of level " + this.trackId);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_INIT_PTS;
} else {
this.startFragRequested = true;
_BaseStreamController.prototype.loadFragment.call(this, frag, trackDetails, targetBufferTime);
}
}
};
_proto.completeAudioSwitch = function completeAudioSwitch() {
var hls = this.hls,
media = this.media,
trackId = this.trackId;
if (media) {
this.log('Switching audio track : flushing all audio');
_BaseStreamController.prototype.flushMainBuffer.call(this, 0, Number.POSITIVE_INFINITY, 'audio');
}
this.audioSwitch = false;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].AUDIO_TRACK_SWITCHED, {
id: trackId
});
};
return AudioStreamController;
}(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]);
/* harmony default export */ __webpack_exports__["default"] = (AudioStreamController);
/***/ }),
/***/ "./src/controller/audio-track-controller.ts":
/*!**************************************************!*\
!*** ./src/controller/audio-track-controller.ts ***!
\**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var AudioTrackController = /*#__PURE__*/function (_BasePlaylistControll) {
_inheritsLoose(AudioTrackController, _BasePlaylistControll);
function AudioTrackController(hls) {
var _this;
_this = _BasePlaylistControll.call(this, hls, '[audio-track-controller]') || this;
_this.tracks = [];
_this.groupId = null;
_this.tracksInGroup = [];
_this.trackId = -1;
_this.trackName = '';
_this.selectDefaultTrack = true;
_this.registerListeners();
return _this;
}
var _proto = AudioTrackController.prototype;
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.tracks.length = 0;
this.tracksInGroup.length = 0;
_BasePlaylistControll.prototype.destroy.call(this);
};
_proto.onManifestLoading = function onManifestLoading() {
this.tracks = [];
this.groupId = null;
this.tracksInGroup = [];
this.trackId = -1;
this.trackName = '';
this.selectDefaultTrack = true;
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
this.tracks = data.audioTracks || [];
};
_proto.onAudioTrackLoaded = function onAudioTrackLoaded(event, data) {
var id = data.id,
details = data.details;
var currentTrack = this.tracksInGroup[id];
if (!currentTrack) {
this.warn("Invalid audio track id " + id);
return;
}
var curDetails = currentTrack.details;
currentTrack.details = data.details;
this.log("audioTrack " + id + " loaded [" + details.startSN + "-" + details.endSN + "]");
if (id === this.trackId) {
this.retryCount = 0;
this.playlistLoaded(id, data, curDetails);
}
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
this.switchLevel(data.level);
};
_proto.onLevelSwitching = function onLevelSwitching(event, data) {
this.switchLevel(data.level);
};
_proto.switchLevel = function switchLevel(levelIndex) {
var levelInfo = this.hls.levels[levelIndex];
if (!(levelInfo !== null && levelInfo !== void 0 && levelInfo.audioGroupIds)) {
return;
}
var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];
if (this.groupId !== audioGroupId) {
this.groupId = audioGroupId;
var audioTracks = this.tracks.filter(function (track) {
return !audioGroupId || track.groupId === audioGroupId;
}); // Disable selectDefaultTrack if there are no default tracks
if (this.selectDefaultTrack && !audioTracks.some(function (track) {
return track.default;
})) {
this.selectDefaultTrack = false;
}
this.tracksInGroup = audioTracks;
var audioTracksUpdated = {
audioTracks: audioTracks
};
this.log("Updating audio tracks, " + audioTracks.length + " track(s) found in \"" + audioGroupId + "\" group-id");
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACKS_UPDATED, audioTracksUpdated);
this.selectInitialTrack();
}
};
_proto.onError = function onError(event, data) {
_BasePlaylistControll.prototype.onError.call(this, event, data);
if (data.fatal || !data.context) {
return;
}
if (data.context.type === _types_loader__WEBPACK_IMPORTED_MODULE_3__["PlaylistContextType"].AUDIO_TRACK && data.context.id === this.trackId && data.context.groupId === this.groupId) {
this.retryLoadingOrFail(data);
}
};
_proto.setAudioTrack = function setAudioTrack(newId) {
var tracks = this.tracksInGroup; // check if level idx is valid
if (newId < 0 || newId >= tracks.length) {
this.warn('Invalid id passed to audio-track controller');
return;
} // stopping live reloading timer if any
this.clearTimer();
var lastTrack = tracks[this.trackId];
this.log("Now switching to audio-track index " + newId);
var track = tracks[newId];
var id = track.id,
_track$groupId = track.groupId,
groupId = _track$groupId === void 0 ? '' : _track$groupId,
name = track.name,
type = track.type,
url = track.url;
this.trackId = newId;
this.trackName = name;
this.selectDefaultTrack = false;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_SWITCHING, {
id: id,
groupId: groupId,
name: name,
type: type,
url: url
}); // Do not reload track unless live
if (track.details && !track.details.live) {
return;
}
var hlsUrlParameters = this.switchParams(track.url, lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.details);
this.loadPlaylist(hlsUrlParameters);
};
_proto.selectInitialTrack = function selectInitialTrack() {
var audioTracks = this.tracksInGroup;
console.assert(audioTracks.length, 'Initial audio track should be selected when tracks are known');
var currentAudioTrackName = this.trackName;
var trackId = this.findTrackId(currentAudioTrackName) || this.findTrackId();
if (trackId !== -1) {
this.setAudioTrack(trackId);
} else {
this.warn("No track found for running audio group-ID: " + this.groupId);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR,
fatal: true
});
}
};
_proto.findTrackId = function findTrackId(name) {
var audioTracks = this.tracksInGroup;
for (var i = 0; i < audioTracks.length; i++) {
var track = audioTracks[i];
if (!this.selectDefaultTrack || track.default) {
if (!name || name === track.name) {
return track.id;
}
}
}
return -1;
};
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
var audioTrack = this.tracksInGroup[this.trackId];
if (this.shouldLoadTrack(audioTrack)) {
var id = audioTrack.id;
var groupId = audioTrack.groupId;
var url = audioTrack.url;
if (hlsUrlParameters) {
try {
url = hlsUrlParameters.addDirectives(url);
} catch (error) {
this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
}
} // track not retrieved yet, or live playlist we need to (re)load it
this.log("loading audio-track playlist for id: " + id);
this.clearTimer();
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].AUDIO_TRACK_LOADING, {
url: url,
id: id,
groupId: groupId,
deliveryDirectives: hlsUrlParameters || null
});
}
};
_createClass(AudioTrackController, [{
key: "audioTracks",
get: function get() {
return this.tracksInGroup;
}
}, {
key: "audioTrack",
get: function get() {
return this.trackId;
},
set: function set(newId) {
// If audio track is selected from API then don't choose from the manifest default track
this.selectDefaultTrack = false;
this.setAudioTrack(newId);
}
}]);
return AudioTrackController;
}(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__["default"]);
/* harmony default export */ __webpack_exports__["default"] = (AudioTrackController);
/***/ }),
/***/ "./src/controller/base-playlist-controller.ts":
/*!****************************************************!*\
!*** ./src/controller/base-playlist-controller.ts ***!
\****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BasePlaylistController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
var BasePlaylistController = /*#__PURE__*/function () {
function BasePlaylistController(hls, logPrefix) {
this.hls = void 0;
this.timer = -1;
this.canLoad = false;
this.retryCount = 0;
this.log = void 0;
this.warn = void 0;
this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":");
this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"], logPrefix + ":");
this.hls = hls;
}
var _proto = BasePlaylistController.prototype;
_proto.destroy = function destroy() {
this.clearTimer(); // @ts-ignore
this.hls = this.log = this.warn = null;
};
_proto.onError = function onError(event, data) {
if (data.fatal && data.type === _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].NETWORK_ERROR) {
this.clearTimer();
}
};
_proto.clearTimer = function clearTimer() {
clearTimeout(this.timer);
this.timer = -1;
};
_proto.startLoad = function startLoad() {
this.canLoad = true;
this.retryCount = 0;
this.loadPlaylist();
};
_proto.stopLoad = function stopLoad() {
this.canLoad = false;
this.clearTimer();
};
_proto.switchParams = function switchParams(playlistUri, previous) {
var renditionReports = previous === null || previous === void 0 ? void 0 : previous.renditionReports;
if (renditionReports) {
for (var i = 0; i < renditionReports.length; i++) {
var attr = renditionReports[i];
var uri = '' + attr.URI;
if (uri === playlistUri.substr(-uri.length)) {
var msn = parseInt(attr['LAST-MSN']);
var part = parseInt(attr['LAST-PART']);
if (previous && this.hls.config.lowLatencyMode) {
var currentGoal = Math.min(previous.age - previous.partTarget, previous.targetduration);
if (part !== undefined && currentGoal > previous.partTarget) {
part += 1;
}
}
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(msn)) {
return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(part) ? part : undefined, _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No);
}
}
}
}
};
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {};
_proto.shouldLoadTrack = function shouldLoadTrack(track) {
return this.canLoad && track && !!track.url && (!track.details || track.details.live);
};
_proto.playlistLoaded = function playlistLoaded(index, data, previousDetails) {
var _this = this;
var details = data.details,
stats = data.stats; // Set last updated date-time
var elapsed = stats.loading.end ? Math.max(0, self.performance.now() - stats.loading.end) : 0;
details.advancedDateTime = Date.now() - elapsed; // if current playlist is a live playlist, arm a timer to reload it
if (details.live || previousDetails !== null && previousDetails !== void 0 && previousDetails.live) {
details.reloaded(previousDetails);
if (previousDetails) {
this.log("live playlist " + index + " " + (details.advanced ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex : 'MISSED'));
} // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments
if (previousDetails && details.fragments.length > 0) {
_level_helper__WEBPACK_IMPORTED_MODULE_2__["mergeDetails"](previousDetails, details);
}
if (!this.canLoad || !details.live) {
return;
}
var deliveryDirectives;
var msn = undefined;
var part = undefined;
if (details.canBlockReload && details.endSN && details.advanced) {
// Load level with LL-HLS delivery directives
var lowLatencyMode = this.hls.config.lowLatencyMode;
var lastPartSn = details.lastPartSn;
var endSn = details.endSN;
var lastPartIndex = details.lastPartIndex;
var hasParts = lastPartIndex !== -1;
var lastPart = lastPartSn === endSn; // When low latency mode is disabled, we'll skip part requests once the last part index is found
var nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;
if (hasParts) {
msn = lastPart ? endSn + 1 : lastPartSn;
part = lastPart ? nextSnStartIndex : lastPartIndex + 1;
} else {
msn = endSn + 1;
} // Low-Latency CDN Tune-in: "age" header and time since load indicates we're behind by more than one part
// Update directives to obtain the Playlist that has the estimated additional duration of media
var lastAdvanced = details.age;
var cdnAge = lastAdvanced + details.ageHeader;
var currentGoal = Math.min(cdnAge - details.partTarget, details.targetduration * 1.5);
if (currentGoal > 0) {
if (previousDetails && currentGoal > previousDetails.tuneInGoal) {
// If we attempted to get the next or latest playlist update, but currentGoal increased,
// then we either can't catchup, or the "age" header cannot be trusted.
this.warn("CDN Tune-in goal increased from: " + previousDetails.tuneInGoal + " to: " + currentGoal + " with playlist age: " + details.age);
currentGoal = 0;
} else {
var segments = Math.floor(currentGoal / details.targetduration);
msn += segments;
if (part !== undefined) {
var parts = Math.round(currentGoal % details.targetduration / details.partTarget);
part += parts;
}
this.log("CDN Tune-in age: " + details.ageHeader + "s last advanced " + lastAdvanced.toFixed(2) + "s goal: " + currentGoal + " skip sn " + segments + " to part " + part);
}
details.tuneInGoal = currentGoal;
}
deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
if (lowLatencyMode || !lastPart) {
this.loadPlaylist(deliveryDirectives);
return;
}
} else {
deliveryDirectives = this.getDeliveryDirectives(details, data.deliveryDirectives, msn, part);
}
var reloadInterval = Object(_level_helper__WEBPACK_IMPORTED_MODULE_2__["computeReloadInterval"])(details, stats);
if (msn !== undefined && details.canBlockReload) {
reloadInterval -= details.partTarget || 1;
}
this.log("reload live playlist " + index + " in " + Math.round(reloadInterval) + " ms");
this.timer = self.setTimeout(function () {
return _this.loadPlaylist(deliveryDirectives);
}, reloadInterval);
} else {
this.clearTimer();
}
};
_proto.getDeliveryDirectives = function getDeliveryDirectives(details, previousDeliveryDirectives, msn, part) {
var skip = Object(_types_level__WEBPACK_IMPORTED_MODULE_1__["getSkipValue"])(details, msn);
if (previousDeliveryDirectives !== null && previousDeliveryDirectives !== void 0 && previousDeliveryDirectives.skip && details.deltaUpdateFailed) {
msn = previousDeliveryDirectives.msn;
part = previousDeliveryDirectives.part;
skip = _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsSkip"].No;
}
return new _types_level__WEBPACK_IMPORTED_MODULE_1__["HlsUrlParameters"](msn, part, skip);
};
_proto.retryLoadingOrFail = function retryLoadingOrFail(errorEvent) {
var _this2 = this;
var config = this.hls.config;
var retry = this.retryCount < config.levelLoadingMaxRetry;
if (retry) {
var _errorEvent$context;
this.retryCount++;
if (errorEvent.details.indexOf('LoadTimeOut') > -1 && (_errorEvent$context = errorEvent.context) !== null && _errorEvent$context !== void 0 && _errorEvent$context.deliveryDirectives) {
// The LL-HLS request already timed out so retry immediately
this.warn("retry playlist loading #" + this.retryCount + " after \"" + errorEvent.details + "\"");
this.loadPlaylist();
} else {
// exponential backoff capped to max retry timeout
var delay = Math.min(Math.pow(2, this.retryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); // Schedule level/track reload
this.timer = self.setTimeout(function () {
return _this2.loadPlaylist();
}, delay);
this.warn("retry playlist loading #" + this.retryCount + " in " + delay + " ms after \"" + errorEvent.details + "\"");
}
} else {
this.warn("cannot recover from error \"" + errorEvent.details + "\""); // stopping live reloading timer if any
this.clearTimer(); // switch error to fatal
errorEvent.fatal = true;
}
return retry;
};
return BasePlaylistController;
}();
/***/ }),
/***/ "./src/controller/base-stream-controller.ts":
/*!**************************************************!*\
!*** ./src/controller/base-stream-controller.ts ***!
\**************************************************/
/*! exports provided: State, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "State", function() { return State; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BaseStreamController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _task_loop__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../task-loop */ "./src/task-loop.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_discontinuities__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.ts");
/* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
/* harmony import */ var _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../loader/fragment-loader */ "./src/loader/fragment-loader.ts");
/* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
/* harmony import */ var _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../utils/time-ranges */ "./src/utils/time-ranges.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var State = {
STOPPED: 'STOPPED',
IDLE: 'IDLE',
KEY_LOADING: 'KEY_LOADING',
FRAG_LOADING: 'FRAG_LOADING',
FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
WAITING_TRACK: 'WAITING_TRACK',
PARSING: 'PARSING',
PARSED: 'PARSED',
BACKTRACKING: 'BACKTRACKING',
ENDED: 'ENDED',
ERROR: 'ERROR',
WAITING_INIT_PTS: 'WAITING_INIT_PTS',
WAITING_LEVEL: 'WAITING_LEVEL'
};
var BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
_inheritsLoose(BaseStreamController, _TaskLoop);
function BaseStreamController(hls, fragmentTracker, logPrefix) {
var _this;
_this = _TaskLoop.call(this) || this;
_this.hls = void 0;
_this.fragPrevious = null;
_this.fragCurrent = null;
_this.fragmentTracker = void 0;
_this.transmuxer = null;
_this._state = State.STOPPED;
_this.media = void 0;
_this.mediaBuffer = void 0;
_this.config = void 0;
_this.bitrateTest = false;
_this.lastCurrentTime = 0;
_this.nextLoadPosition = 0;
_this.startPosition = 0;
_this.loadedmetadata = false;
_this.fragLoadError = 0;
_this.retryDate = 0;
_this.levels = null;
_this.fragmentLoader = void 0;
_this.levelLastLoaded = null;
_this.startFragRequested = false;
_this.decrypter = void 0;
_this.initPTS = [];
_this.onvseeking = null;
_this.onvended = null;
_this.logPrefix = '';
_this.log = void 0;
_this.warn = void 0;
_this.logPrefix = logPrefix;
_this.log = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].log.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":");
_this.warn = _utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].warn.bind(_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"], logPrefix + ":");
_this.hls = hls;
_this.fragmentLoader = new _loader_fragment_loader__WEBPACK_IMPORTED_MODULE_12__["default"](hls.config);
_this.fragmentTracker = fragmentTracker;
_this.config = hls.config;
_this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_13__["default"](hls, hls.config);
hls.on(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, _this.onKeyLoaded, _assertThisInitialized(_this));
return _this;
}
var _proto = BaseStreamController.prototype;
_proto.doTick = function doTick() {
this.onTickEnd();
};
_proto.onTickEnd = function onTickEnd() {} // eslint-disable-next-line @typescript-eslint/no-unused-vars
;
_proto.startLoad = function startLoad(startPosition) {};
_proto.stopLoad = function stopLoad() {
this.fragmentLoader.abort();
var frag = this.fragCurrent;
if (frag) {
this.fragmentTracker.removeFragment(frag);
}
this.resetTransmuxer();
this.fragCurrent = null;
this.fragPrevious = null;
this.clearInterval();
this.clearNextTick();
this.state = State.STOPPED;
};
_proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
var fragCurrent = this.fragCurrent,
fragmentTracker = this.fragmentTracker; // we just got done loading the final fragment and there is no other buffered range after ...
// rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
// so we should not switch to ENDED in that case, to be able to buffer them
if (!levelDetails.live && fragCurrent && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {
var fragState = fragmentTracker.getState(fragCurrent);
return fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].PARTIAL || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK;
}
return false;
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
var media = this.media = this.mediaBuffer = data.media;
this.onvseeking = this.onMediaSeeking.bind(this);
this.onvended = this.onMediaEnded.bind(this);
media.addEventListener('seeking', this.onvseeking);
media.addEventListener('ended', this.onvended);
var config = this.config;
if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {
this.startLoad(config.startPosition);
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media;
if (media !== null && media !== void 0 && media.ended) {
this.log('MSE detaching and video ended, reset startPosition');
this.startPosition = this.lastCurrentTime = 0;
} // remove video listeners
if (media) {
media.removeEventListener('seeking', this.onvseeking);
media.removeEventListener('ended', this.onvended);
this.onvseeking = this.onvended = null;
}
this.media = this.mediaBuffer = null;
this.loadedmetadata = false;
this.fragmentTracker.removeAllFragments();
this.stopLoad();
};
_proto.onMediaSeeking = function onMediaSeeking() {
var config = this.config,
fragCurrent = this.fragCurrent,
media = this.media,
mediaBuffer = this.mediaBuffer,
state = this.state;
var currentTime = media ? media.currentTime : 0;
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(mediaBuffer || media, currentTime, config.maxBufferHole);
this.log("media seeking to " + (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime) ? currentTime.toFixed(3) : currentTime) + ", state: " + state);
if (state === State.ENDED) {
this.resetLoadingState();
} else if (fragCurrent && !bufferInfo.len) {
// check if we are seeking to a unbuffered area AND if frag loading is in progress
var tolerance = config.maxFragLookUpTolerance;
var fragStartOffset = fragCurrent.start - tolerance;
var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance; // check if the seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
if (fragCurrent.loader) {
this.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
fragCurrent.loader.abort();
}
this.resetLoadingState();
}
}
if (media) {
this.lastCurrentTime = currentTime;
} // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
if (!this.loadedmetadata && !bufferInfo.len) {
this.nextLoadPosition = this.startPosition = currentTime;
} // tick to speed up processing
this.tick();
};
_proto.onMediaEnded = function onMediaEnded() {
// reset startPosition and lastCurrentTime to restart playback @ stream beginning
this.startPosition = this.lastCurrentTime = 0;
};
_proto.onKeyLoaded = function onKeyLoaded(event, data) {
if (this.state !== State.KEY_LOADING || data.frag !== this.fragCurrent || !this.levels) {
return;
}
this.state = State.IDLE;
var levelDetails = this.levels[data.frag.level].details;
if (levelDetails) {
this.loadFragment(data.frag, levelDetails, data.frag.start);
}
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
this.stopLoad();
_TaskLoop.prototype.onHandlerDestroying.call(this);
};
_proto.onHandlerDestroyed = function onHandlerDestroyed() {
this.state = State.STOPPED;
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADED, this.onKeyLoaded, this);
if (this.fragmentLoader) {
this.fragmentLoader.destroy();
}
if (this.decrypter) {
this.decrypter.destroy();
} // @ts-ignore
this.hls = this.log = this.warn = this.decrypter = this.fragmentLoader = this.fragmentTracker = null;
_TaskLoop.prototype.onHandlerDestroyed.call(this);
};
_proto.loadKey = function loadKey(frag, details) {
this.log("Loading key for " + frag.sn + " of [" + details.startSN + "-" + details.endSN + "], " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level);
this.state = State.KEY_LOADING;
this.fragCurrent = frag;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].KEY_LOADING, {
frag: frag
});
};
_proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
this._loadFragForPlayback(frag, levelDetails, targetBufferTime);
};
_proto._loadFragForPlayback = function _loadFragForPlayback(frag, levelDetails, targetBufferTime) {
var _this2 = this;
var progressCallback = function progressCallback(data) {
if (_this2.fragContextChanged(frag)) {
_this2.warn("Fragment " + frag.sn + (data.part ? ' p: ' + data.part.index : '') + " of level " + frag.level + " was dropped during download.");
_this2.fragmentTracker.removeFragment(frag);
return;
}
frag.stats.chunkCount++;
_this2._handleFragmentLoadProgress(data);
};
this._doFragLoad(frag, levelDetails, targetBufferTime, progressCallback).then(function (data) {
if (!data) {
// if we're here we probably needed to backtrack or are waiting for more parts
return;
}
_this2.fragLoadError = 0;
var state = _this2.state;
if (_this2.fragContextChanged(frag)) {
if (state === State.FRAG_LOADING || state === State.BACKTRACKING || !_this2.fragCurrent && state === State.PARSING) {
_this2.fragmentTracker.removeFragment(frag);
_this2.state = State.IDLE;
}
return;
}
if ('payload' in data) {
_this2.log("Loaded fragment " + frag.sn + " of level " + frag.level);
_this2.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, data); // Tracker backtrack must be called after onFragLoaded to update the fragment entity state to BACKTRACKED
// This happens after handleTransmuxComplete when the worker or progressive is disabled
if (_this2.state === State.BACKTRACKING) {
_this2.fragmentTracker.backtrack(frag, data);
_this2.resetFragmentLoading(frag);
return;
}
} // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback
_this2._handleFragmentLoadComplete(data);
}).catch(function (reason) {
_this2.warn(reason);
_this2.resetFragmentLoading(frag);
});
};
_proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset, type) {
if (type === void 0) {
type = null;
}
// When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,
// passing a null type flushes both buffers
var flushScope = {
startOffset: startOffset,
endOffset: endOffset,
type: type
}; // Reset load errors on flush
this.fragLoadError = 0;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_FLUSHING, flushScope);
};
_proto._loadInitSegment = function _loadInitSegment(frag) {
var _this3 = this;
this._doFragLoad(frag).then(function (data) {
if (!data || _this3.fragContextChanged(frag) || !_this3.levels) {
throw new Error('init load aborted');
}
return data;
}).then(function (data) {
var hls = _this3.hls;
var payload = data.payload;
var decryptData = frag.decryptdata; // check to see if the payload needs to be decrypted
if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
var startTime = self.performance.now(); // decrypt the subtitles
return _this3.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) {
var endTime = self.performance.now();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_DECRYPTED, {
frag: frag,
payload: decryptedData,
stats: {
tstart: startTime,
tdecrypt: endTime
}
});
data.payload = decryptedData;
return data;
});
}
return data;
}).then(function (data) {
var fragCurrent = _this3.fragCurrent,
hls = _this3.hls,
levels = _this3.levels;
if (!levels) {
throw new Error('init load aborted, missing levels');
}
var details = levels[frag.level].details;
console.assert(details, 'Level details are defined when init segment is loaded');
var initSegment = details.initSegment;
console.assert(initSegment, 'Fragment initSegment is defined when init segment is loaded');
var stats = frag.stats;
_this3.state = State.IDLE;
_this3.fragLoadError = 0;
initSegment.data = new Uint8Array(data.payload);
stats.parsing.start = stats.buffering.start = self.performance.now();
stats.parsing.end = stats.buffering.end = self.performance.now(); // Silence FRAG_BUFFERED event if fragCurrent is null
if (data.frag === fragCurrent) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_BUFFERED, {
stats: stats,
frag: fragCurrent,
part: null,
id: frag.type
});
}
_this3.tick();
}).catch(function (reason) {
_this3.warn(reason);
_this3.resetFragmentLoading(frag);
});
};
_proto.fragContextChanged = function fragContextChanged(frag) {
var fragCurrent = this.fragCurrent;
return !frag || !fragCurrent || frag.level !== fragCurrent.level || frag.sn !== fragCurrent.sn || frag.urlId !== fragCurrent.urlId;
};
_proto.fragBufferedComplete = function fragBufferedComplete(frag, part) {
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
this.log("Buffered " + frag.type + " sn: " + frag.sn + (part ? ' part: ' + part.index : '') + " of " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + " " + frag.level + " " + _utils_time_ranges__WEBPACK_IMPORTED_MODULE_14__["default"].toString(_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media)));
this.state = State.IDLE;
this.tick();
};
_proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedEndData) {
var transmuxer = this.transmuxer;
if (!transmuxer) {
return;
}
var frag = fragLoadedEndData.frag,
part = fragLoadedEndData.part,
partsLoaded = fragLoadedEndData.partsLoaded; // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data
var complete = !partsLoaded || partsLoaded.length === 0 || partsLoaded.some(function (fragLoaded) {
return !fragLoaded;
});
var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_8__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount + 1, 0, part ? part.index : -1, !complete);
transmuxer.flush(chunkMeta);
} // eslint-disable-next-line @typescript-eslint/no-unused-vars
;
_proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(frag) {};
_proto._doFragLoad = function _doFragLoad(frag, details, targetBufferTime, progressCallback) {
var _this4 = this;
if (targetBufferTime === void 0) {
targetBufferTime = null;
}
if (!this.levels) {
throw new Error('frag load aborted, missing levels');
}
targetBufferTime = Math.max(frag.start, targetBufferTime || 0);
if (this.config.lowLatencyMode && details) {
var partList = details.partList;
if (partList && progressCallback) {
if (targetBufferTime > frag.end && details.fragmentHint) {
frag = details.fragmentHint;
}
var partIndex = this.getNextPart(partList, frag, targetBufferTime);
if (partIndex > -1) {
var part = partList[partIndex];
this.log("Loading part sn: " + frag.sn + " p: " + part.index + " cc: " + frag.cc + " of playlist [" + details.startSN + "-" + details.endSN + "] parts [0-" + partIndex + "-" + (partList.length - 1) + "] " + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3)));
this.nextLoadPosition = part.start + part.duration;
this.state = State.FRAG_LOADING;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, {
frag: frag,
part: partList[partIndex],
targetBufferTime: targetBufferTime
});
return this.doFragPartsLoad(frag, partList, partIndex, progressCallback).catch(function (error) {
return _this4.handleFragLoadError(error);
});
} else if (!frag.url || this.loadedEndOfParts(partList, targetBufferTime)) {
// Fragment hint has no parts
return Promise.resolve(null);
}
}
}
this.log("Loading fragment " + frag.sn + " cc: " + frag.cc + " " + (details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : '') + (this.logPrefix === '[stream-controller]' ? 'level' : 'track') + ": " + frag.level + ", target: " + parseFloat(targetBufferTime.toFixed(3))); // Don't update nextLoadPosition for fragments which are not buffered
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.sn) && !this.bitrateTest) {
this.nextLoadPosition = frag.start + frag.duration;
}
this.state = State.FRAG_LOADING;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADING, {
frag: frag,
targetBufferTime: targetBufferTime
});
return this.fragmentLoader.load(frag, progressCallback).catch(function (error) {
return _this4.handleFragLoadError(error);
});
};
_proto.doFragPartsLoad = function doFragPartsLoad(frag, partList, partIndex, progressCallback) {
var _this5 = this;
return new Promise(function (resolve, reject) {
var partsLoaded = [];
var loadPartIndex = function loadPartIndex(index) {
var part = partList[index];
_this5.fragmentLoader.loadPart(frag, part, progressCallback).then(function (partLoadedData) {
partsLoaded[part.index] = partLoadedData;
var loadedPart = partLoadedData.part;
_this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_LOADED, partLoadedData);
var nextPart = partList[index + 1];
if (nextPart && nextPart.fragment === frag) {
loadPartIndex(index + 1);
} else {
return resolve({
frag: frag,
part: loadedPart,
partsLoaded: partsLoaded
});
}
}).catch(reject);
};
loadPartIndex(partIndex);
});
};
_proto.handleFragLoadError = function handleFragLoadError(_ref) {
var data = _ref.data;
if (data && data.details === _errors__WEBPACK_IMPORTED_MODULE_6__["ErrorDetails"].INTERNAL_ABORTED) {
this.handleFragLoadAborted(data.frag, data.part);
} else {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, data);
}
return null;
};
_proto._handleTransmuxerFlush = function _handleTransmuxerFlush(chunkMeta) {
var context = this.getCurrentContext(chunkMeta);
if (!context || this.state !== State.PARSING) {
if (!this.fragCurrent) {
this.state = State.IDLE;
}
return;
}
var frag = context.frag,
part = context.part,
level = context.level;
var now = self.performance.now();
frag.stats.parsing.end = now;
if (part) {
part.stats.parsing.end = now;
}
this.updateLevelTiming(frag, part, level, chunkMeta.partial);
};
_proto.getCurrentContext = function getCurrentContext(chunkMeta) {
var levels = this.levels;
var levelIndex = chunkMeta.level,
sn = chunkMeta.sn,
partIndex = chunkMeta.part;
if (!levels || !levels[levelIndex]) {
this.warn("Levels object was unset while buffering fragment " + sn + " of level " + levelIndex + ". The current chunk will not be buffered.");
return null;
}
var level = levels[levelIndex];
var part = partIndex > -1 ? _level_helper__WEBPACK_IMPORTED_MODULE_7__["getPartWith"](level, sn, partIndex) : null;
var frag = part ? part.fragment : _level_helper__WEBPACK_IMPORTED_MODULE_7__["getFragmentWithSN"](level, sn);
if (!frag) {
return null;
}
return {
frag: frag,
part: part,
level: level
};
};
_proto.bufferFragmentData = function bufferFragmentData(data, frag, part, chunkMeta) {
if (!data || this.state !== State.PARSING) {
return;
}
var data1 = data.data1,
data2 = data.data2;
var buffer = data1;
if (data1 && data2) {
// Combine the moof + mdat so that we buffer with a single append
buffer = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_9__["appendUint8Array"])(data1, data2);
}
if (!buffer || !buffer.length) {
return;
}
var segment = {
type: data.type,
frag: frag,
part: part,
chunkMeta: chunkMeta,
parent: frag.type,
data: buffer
};
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].BUFFER_APPENDING, segment);
if (data.dropped && data.independent && !part) {
// Clear buffer so that we reload previous segments sequentially if required
this.flushBufferGap(frag);
}
};
_proto.flushBufferGap = function flushBufferGap(frag) {
var media = this.media;
if (!media) {
return;
} // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed
if (!_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].isBuffered(media, media.currentTime)) {
this.flushMainBuffer(0, frag.start);
return;
} // Remove back-buffer without interrupting playback to allow back tracking
var currentTime = media.currentTime;
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].bufferInfo(media, currentTime, 0);
var fragDuration = frag.duration;
var segmentFraction = Math.min(this.config.maxFragLookUpTolerance * 2, fragDuration * 0.25);
var start = Math.max(Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction), currentTime + segmentFraction);
if (frag.start - start > segmentFraction) {
this.flushMainBuffer(start, frag.start);
}
};
_proto.reduceMaxBufferLength = function reduceMaxBufferLength(threshold) {
var config = this.config;
var minLength = threshold || config.maxBufferLength;
if (config.maxMaxBufferLength >= minLength) {
// reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
config.maxMaxBufferLength /= 2;
this.warn("Reduce max buffer length to " + config.maxMaxBufferLength + "s");
return true;
}
return false;
};
_proto.getNextFragment = function getNextFragment(pos, levelDetails) {
var fragments = levelDetails.fragments;
var fragLen = fragments.length;
if (!fragLen) {
return null;
} // find fragment index, contiguous with end of buffer position
var config = this.config;
var start = fragments[0].start;
var frag; // If an initSegment is present, it must be buffered first
if (levelDetails.initSegment && !levelDetails.initSegment.data && !this.bitrateTest) {
frag = levelDetails.initSegment;
} else if (levelDetails.live) {
var initialLiveManifestSize = config.initialLiveManifestSize;
if (fragLen < initialLiveManifestSize) {
this.warn("Not enough fragments to start playback (have: " + fragLen + ", need: " + initialLiveManifestSize + ")");
return null;
} // The real fragment start times for a live stream are only known after the PTS range for that level is known.
// In order to discover the range, we load the best matching fragment for that level and demux it.
// Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that
// we get the fragment matching that start time
if (!levelDetails.PTSKnown && !this.startFragRequested && this.startPosition === -1) {
frag = this.getInitialLiveFragment(levelDetails, fragments);
this.startPosition = frag ? this.hls.liveSyncPosition || frag.start : pos;
}
} else if (pos <= start) {
// VoD playlist: if loadPosition before start of playlist, load first fragment
frag = fragments[0];
} // If we haven't run into any special cases already, just load the fragment most closely matching the requested position
if (!frag) {
var end = config.lowLatencyMode ? levelDetails.partEnd : levelDetails.fragmentEnd;
frag = this.getFragmentAtPosition(pos, end, levelDetails);
}
return frag;
};
_proto.getNextPart = function getNextPart(partList, frag, targetBufferTime) {
var nextPart = -1;
var contiguous = false;
var independentAttrOmitted = true;
for (var i = 0, len = partList.length; i < len; i++) {
var part = partList[i];
independentAttrOmitted = independentAttrOmitted && !part.independent;
if (nextPart > -1 && targetBufferTime < part.start) {
break;
}
var loaded = part.loaded;
if (!loaded && (contiguous || part.independent || independentAttrOmitted) && part.fragment === frag) {
nextPart = i;
}
contiguous = loaded;
}
return nextPart;
};
_proto.loadedEndOfParts = function loadedEndOfParts(partList, targetBufferTime) {
var lastPart = partList[partList.length - 1];
return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;
}
/*
This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the
"sliding" of the playlist, which is its offset from the start of playback. After sliding we can compute the real
start and end times for each fragment in the playlist (after which this method will not need to be called).
*/
;
_proto.getInitialLiveFragment = function getInitialLiveFragment(levelDetails, fragments) {
var fragPrevious = this.fragPrevious;
var frag = null;
if (fragPrevious) {
if (levelDetails.hasProgramDateTime) {
// Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding
this.log("Live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_11__["findFragmentByPDT"])(fragments, fragPrevious.endProgramDateTime, this.config.maxFragLookUpTolerance);
}
if (!frag) {
// SN does not need to be accurate between renditions, but depending on the packaging it may be so.
var targetSN = fragPrevious.sn + 1;
if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
var fragNext = fragments[targetSN - levelDetails.startSN]; // Ensure that we're staying within the continuity range, since PTS resets upon a new range
if (fragPrevious.cc === fragNext.cc) {
frag = fragNext;
this.log("Live playlist, switching playlist, load frag with next SN: " + frag.sn);
}
} // It's important to stay within the continuity range if available; otherwise the fragments in the playlist
// will have the wrong start times
if (!frag) {
frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_11__["findFragWithCC"])(fragments, fragPrevious.cc);
if (frag) {
this.log("Live playlist, switching playlist, load frag with same CC: " + frag.sn);
}
}
}
} else {
// Find a new start fragment when fragPrevious is null
var liveStart = this.hls.liveSyncPosition;
if (liveStart !== null) {
frag = this.getFragmentAtPosition(liveStart, this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge, levelDetails);
}
}
return frag;
}
/*
This method finds the best matching fragment given the provided position.
*/
;
_proto.getFragmentAtPosition = function getFragmentAtPosition(bufferEnd, end, levelDetails) {
var config = this.config,
fragPrevious = this.fragPrevious;
var fragments = levelDetails.fragments,
endSN = levelDetails.endSN;
var fragmentHint = levelDetails.fragmentHint;
var tolerance = config.maxFragLookUpTolerance;
var loadingParts = !!(config.lowLatencyMode && levelDetails.partList && fragmentHint);
if (loadingParts && fragmentHint && !this.bitrateTest) {
// Include incomplete fragment with parts at end
fragments = fragments.concat(fragmentHint);
endSN = fragmentHint.sn;
}
var frag;
if (bufferEnd < end) {
var lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance; // Remove the tolerance if it would put the bufferEnd past the actual end of stream
// Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
frag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_11__["findFragmentByPTS"])(fragPrevious, fragments, bufferEnd, lookupTolerance);
} else {
// reach end of playlist
frag = fragments[fragments.length - 1];
}
if (frag) {
var curSNIdx = frag.sn - levelDetails.startSN;
var sameLevel = fragPrevious && frag.level === fragPrevious.level;
var nextFrag = fragments[curSNIdx + 1];
var fragState = this.fragmentTracker.getState(frag);
if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) {
frag = null;
var i = curSNIdx;
while (fragments[i] && this.fragmentTracker.getState(fragments[i]) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].BACKTRACKED) {
// When fragPrevious is null, backtrack to first the first fragment is not BACKTRACKED for loading
// When fragPrevious is set, we want the first BACKTRACKED fragment for parsing and buffering
if (!fragPrevious) {
frag = fragments[--i];
} else {
frag = fragments[i--];
}
}
if (!frag) {
frag = nextFrag;
}
} else if (fragPrevious && frag.sn === fragPrevious.sn && !loadingParts) {
// Force the next fragment to load if the previous one was already selected. This can occasionally happen with
// non-uniform fragment durations
if (sameLevel) {
if (frag.sn < endSN && this.fragmentTracker.getState(nextFrag) !== _fragment_tracker__WEBPACK_IMPORTED_MODULE_2__["FragmentState"].OK) {
this.log("SN " + frag.sn + " just loaded, load next one: " + nextFrag.sn);
frag = nextFrag;
} else {
frag = null;
}
}
}
}
return frag;
};
_proto.synchronizeToLiveEdge = function synchronizeToLiveEdge(levelDetails) {
var config = this.config,
media = this.media;
if (!media) {
return;
}
var liveSyncPosition = this.hls.liveSyncPosition;
var currentTime = media.currentTime;
var start = levelDetails.fragments[0].start;
var end = levelDetails.edge;
var withinSlidingWindow = currentTime >= start - config.maxFragLookUpTolerance && currentTime <= end; // Continue if we can seek forward to sync position or if current time is outside of sliding window
if (liveSyncPosition !== null && media.duration > liveSyncPosition && (currentTime < liveSyncPosition || !withinSlidingWindow)) {
// Continue if buffer is starving or if current time is behind max latency
var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
if (!withinSlidingWindow && media.readyState < 4 || currentTime < end - maxLatency) {
if (!this.loadedmetadata) {
this.nextLoadPosition = liveSyncPosition;
} // Only seek if ready and there is not a significant forward buffer available for playback
if (media.readyState) {
this.warn("Playback: " + currentTime.toFixed(3) + " is located too far from the end of live sliding playlist: " + end + ", reset currentTime to : " + liveSyncPosition.toFixed(3));
media.currentTime = liveSyncPosition;
}
}
}
};
_proto.alignPlaylists = function alignPlaylists(details, previousDetails) {
var levels = this.levels,
levelLastLoaded = this.levelLastLoaded;
var lastLevel = levelLastLoaded !== null ? levels[levelLastLoaded] : null; // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,
// this could all go in LevelHelper.mergeDetails
var sliding = 0;
if (previousDetails && details.fragments.length > 0) {
sliding = details.fragments[0].start;
if (details.alignedSliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(sliding)) {
this.log("Live playlist sliding:" + sliding.toFixed(3));
} else if (!sliding) {
this.warn("[" + this.constructor.name + "] Live playlist - outdated PTS, unknown sliding");
Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_10__["alignStream"])(this.fragPrevious, lastLevel, details);
}
} else {
this.log('Live playlist - first load, unknown sliding');
Object(_utils_discontinuities__WEBPACK_IMPORTED_MODULE_10__["alignStream"])(this.fragPrevious, lastLevel, details);
}
return sliding;
};
_proto.waitForCdnTuneIn = function waitForCdnTuneIn(details) {
// Wait for Low-Latency CDN Tune-in to get an updated playlist
var advancePartLimit = 3;
return details.live && details.canBlockReload && details.tuneInGoal > Math.max(details.partHoldBack, details.partTarget * advancePartLimit);
};
_proto.setStartPosition = function setStartPosition(details, sliding) {
// compute start position if set to -1. use it straight away if value is defined
var startPosition = this.startPosition;
if (this.startPosition === -1 || this.lastCurrentTime === -1) {
// first, check if start time offset has been set in playlist, if yes, use this value
var startTimeOffset = details.startTimeOffset;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) {
if (startTimeOffset < 0) {
this.log("Negative start time offset " + startTimeOffset + ", count from end of last fragment");
startTimeOffset = sliding + details.totalduration + startTimeOffset;
}
this.log("Start time offset found in playlist, adjust startPosition to " + startTimeOffset);
this.startPosition = startPosition = startTimeOffset;
} else if (details.live) {
// Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has
// not been specified via the config or an as an argument to startLoad (#3736).
startPosition = this.hls.liveSyncPosition || sliding;
} else {
this.startPosition = startPosition = 0;
}
this.lastCurrentTime = startPosition;
}
this.nextLoadPosition = startPosition;
};
_proto.getLoadPosition = function getLoadPosition() {
var media = this.media; // if we have not yet loaded any fragment, start loading from start position
var pos = 0;
if (this.loadedmetadata) {
pos = media.currentTime;
} else if (this.nextLoadPosition) {
pos = this.nextLoadPosition;
}
return pos;
};
_proto.handleFragLoadAborted = function handleFragLoadAborted(frag, part) {
if (this.transmuxer && frag.sn !== 'initSegment') {
this.warn("Fragment " + frag.sn + (part ? ' part' + part.index : '') + " of level " + frag.level + " was aborted");
this.resetFragmentLoading(frag);
}
};
_proto.resetFragmentLoading = function resetFragmentLoading(frag) {
if (!this.fragCurrent || !this.fragContextChanged(frag)) {
this.state = State.IDLE;
}
};
_proto.onFragmentOrKeyLoadError = function onFragmentOrKeyLoadError(filterType, data) {
if (data.fatal) {
return;
}
var frag = data.frag; // Handle frag error related to caller's filterType
if (!frag || frag.type !== filterType) {
return;
}
var fragCurrent = this.fragCurrent;
console.assert(fragCurrent && frag.sn === fragCurrent.sn && frag.level === fragCurrent.level && frag.urlId === fragCurrent.urlId, 'Frag load error must match current frag to retry');
var config = this.config; // keep retrying until the limit will be reached
if (this.fragLoadError + 1 <= config.fragLoadingMaxRetry) {
if (this.resetLiveStartWhenNotLoaded(frag.level)) {
return;
} // exponential backoff capped to config.fragLoadingMaxRetryTimeout
var delay = Math.min(Math.pow(2, this.fragLoadError) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
this.warn("Fragment " + frag.sn + " of " + filterType + " " + frag.level + " failed to load, retrying in " + delay + "ms");
this.retryDate = self.performance.now() + delay;
this.fragLoadError++;
this.state = State.FRAG_LOADING_WAITING_RETRY;
} else if (data.levelRetry) {
if (filterType === _types_loader__WEBPACK_IMPORTED_MODULE_15__["PlaylistLevelType"].AUDIO) {
// Reset current fragment since audio track audio is essential and may not have a fail-over track
this.fragCurrent = null;
} // Fragment errors that result in a level switch or redundant fail-over
// should reset the stream controller state to idle
this.fragLoadError = 0;
this.state = State.IDLE;
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_4__["logger"].error(data.details + " reaches max retry, redispatch as fatal ..."); // switch error to fatal
data.fatal = true;
this.hls.stopLoad();
this.state = State.ERROR;
}
};
_proto.afterBufferFlushed = function afterBufferFlushed(media, bufferType, playlistType) {
if (!media) {
return;
} // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media
// (so that we will check against video.buffered ranges in case of alt audio track)
var bufferedTimeRanges = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_3__["BufferHelper"].getBuffered(media);
this.fragmentTracker.detectEvictedFragments(bufferType, bufferedTimeRanges, playlistType);
if (this.state === State.ENDED) {
this.resetLoadingState();
}
};
_proto.resetLoadingState = function resetLoadingState() {
this.fragCurrent = null;
this.fragPrevious = null;
this.state = State.IDLE;
};
_proto.resetLiveStartWhenNotLoaded = function resetLiveStartWhenNotLoaded(level) {
// if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
var details = this.levels ? this.levels[level].details : null;
if (details !== null && details !== void 0 && details.live) {
// We can't afford to retry after a delay in a live scenario. Update the start position and return to IDLE.
this.startPosition = -1;
this.setStartPosition(details, 0);
this.resetLoadingState();
return true;
}
this.nextLoadPosition = this.startPosition;
}
return false;
};
_proto.updateLevelTiming = function updateLevelTiming(frag, part, level, partial) {
var _this6 = this;
var details = level.details;
console.assert(!!details, 'level.details must be defined');
var parsed = Object.keys(frag.elementaryStreams).reduce(function (result, type) {
var info = frag.elementaryStreams[type];
if (info) {
var parsedDuration = info.endPTS - info.startPTS;
if (parsedDuration <= 0) {
// Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.
// The new transmuxer will be configured with a time offset matching the next fragment start,
// preventing the timeline from shifting.
_this6.warn("Could not parse fragment " + frag.sn + " " + type + " duration reliably (" + parsedDuration + ") resetting transmuxer to fallback to playlist timing");
_this6.resetTransmuxer();
return result || false;
}
var drift = partial ? 0 : _level_helper__WEBPACK_IMPORTED_MODULE_7__["updateFragPTSDTS"](details, frag, info.startPTS, info.endPTS, info.startDTS, info.endDTS);
_this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].LEVEL_PTS_UPDATED, {
details: details,
level: level,
drift: drift,
type: type,
frag: frag,
start: info.startPTS,
end: info.endPTS
});
return true;
}
return result;
}, false);
if (parsed) {
this.state = State.PARSED;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].FRAG_PARSED, {
frag: frag,
part: part
});
} else {
this.resetLoadingState();
}
};
_proto.resetTransmuxer = function resetTransmuxer() {
if (this.transmuxer) {
this.transmuxer.destroy();
this.transmuxer = null;
}
};
_createClass(BaseStreamController, [{
key: "state",
get: function get() {
return this._state;
},
set: function set(nextState) {
var previousState = this._state;
if (previousState !== nextState) {
this._state = nextState;
this.log(previousState + "->" + nextState);
}
}
}]);
return BaseStreamController;
}(_task_loop__WEBPACK_IMPORTED_MODULE_1__["default"]);
/***/ }),
/***/ "./src/controller/buffer-controller.ts":
/*!*********************************************!*\
!*** ./src/controller/buffer-controller.ts ***!
\*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./buffer-operation-queue */ "./src/controller/buffer-operation-queue.ts");
var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])();
var VIDEO_CODEC_PROFILE_REPACE = /([ha]vc.)(?:\.[^.,]+)+/;
var BufferController = /*#__PURE__*/function () {
// The level details used to determine duration, target-duration and live
// cache the self generated object url to detect hijack of video tag
// A queue of buffer operations which require the SourceBuffer to not be updating upon execution
// References to event listeners for each SourceBuffer, so that they can be referenced for event removal
// The number of BUFFER_CODEC events received before any sourceBuffers are created
// The total number of BUFFER_CODEC events received
// A reference to the attached media element
// A reference to the active media source
// counters
function BufferController(_hls) {
var _this = this;
this.details = null;
this._objectUrl = null;
this.operationQueue = void 0;
this.listeners = void 0;
this.hls = void 0;
this.bufferCodecEventsExpected = 0;
this._bufferCodecEventsTotal = 0;
this.media = null;
this.mediaSource = null;
this.appendError = 0;
this.tracks = {};
this.pendingTracks = {};
this.sourceBuffer = void 0;
this._onMediaSourceOpen = function () {
var hls = _this.hls,
media = _this.media,
mediaSource = _this.mediaSource;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source opened');
if (media) {
_this.updateMediaElementDuration();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, {
media: media
});
}
if (mediaSource) {
// once received, don't listen anymore to sourceopen event
mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen);
}
_this.checkPendingTracks();
};
this._onMediaSourceClose = function () {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source closed');
};
this._onMediaSourceEnded = function () {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media source ended');
};
this.hls = _hls;
this._initSourceBuffer();
this.registerListeners();
}
var _proto = BufferController.prototype;
_proto.hasSourceTypes = function hasSourceTypes() {
return this.getSourceBufferTypes().length > 0 || Object.keys(this.pendingTracks).length > 0;
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.details = null;
};
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_RESET, this.onBufferReset, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDING, this.onBufferAppending, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_EOS, this.onBufferEos, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSED, this.onFragParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_CHANGED, this.onFragChanged, this);
};
_proto._initSourceBuffer = function _initSourceBuffer() {
this.sourceBuffer = {};
this.operationQueue = new _buffer_operation_queue__WEBPACK_IMPORTED_MODULE_7__["default"](this.sourceBuffer);
this.listeners = {
audio: [],
video: [],
audiovideo: []
};
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
// in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
// sourcebuffers will be created all at once when the expected nb of tracks will be reached
// in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
// it will contain the expected nb of source buffers, no need to compute it
var codecEvents = 2;
if (data.audio && !data.video || !data.altAudio) {
codecEvents = 1;
}
this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
this.details = null;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected");
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
var media = this.media = data.media;
if (media && MediaSource) {
var ms = this.mediaSource = new MediaSource(); // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound
ms.addEventListener('sourceopen', this._onMediaSourceOpen);
ms.addEventListener('sourceended', this._onMediaSourceEnded);
ms.addEventListener('sourceclose', this._onMediaSourceClose); // link video and media Source
media.src = self.URL.createObjectURL(ms); // cache the locally generated object url
this._objectUrl = media.src;
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media,
mediaSource = this.mediaSource,
_objectUrl = this._objectUrl;
if (mediaSource) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: media source detaching');
if (mediaSource.readyState === 'open') {
try {
// endOfStream could trigger exception if any sourcebuffer is in updating state
// we don't really care about checking sourcebuffer state here,
// as we are anyway detaching the MediaSource
// let's just avoid this exception to propagate
mediaSource.endOfStream();
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: onMediaDetaching: " + err.message + " while calling endOfStream");
}
} // Clean up the SourceBuffers by invoking onBufferReset
this.onBufferReset();
mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);
mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);
mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose); // Detach properly the MediaSource from the HTMLMediaElement as
// suggested in https://github.com/w3c/media-source/issues/53.
if (media) {
if (_objectUrl) {
self.URL.revokeObjectURL(_objectUrl);
} // clean up video tag src only if it's our own url. some external libraries might
// hijack the video tag and change its 'src' without destroying the Hls instance first
if (media.src === _objectUrl) {
media.removeAttribute('src');
media.load();
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[buffer-controller]: media.src was changed by a third party - skip cleanup');
}
}
this.mediaSource = null;
this.media = null;
this._objectUrl = null;
this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
this.pendingTracks = {};
this.tracks = {};
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHED, undefined);
};
_proto.onBufferReset = function onBufferReset() {
var _this2 = this;
var sourceBuffer = this.sourceBuffer;
this.getSourceBufferTypes().forEach(function (type) {
var sb = sourceBuffer[type];
try {
if (sb) {
_this2.removeBufferListeners(type);
if (_this2.mediaSource) {
_this2.mediaSource.removeSourceBuffer(sb);
} // Synchronously remove the SB from the map before the next call in order to prevent an async function from
// accessing it
sourceBuffer[type] = undefined;
}
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to reset the " + type + " buffer", err);
}
});
this._initSourceBuffer();
};
_proto.onBufferCodecs = function onBufferCodecs(event, data) {
var _this3 = this;
var sourceBufferCount = Object.keys(this.sourceBuffer).length;
Object.keys(data).forEach(function (trackName) {
if (sourceBufferCount) {
// check if SourceBuffer codec needs to change
var track = _this3.tracks[trackName];
if (track && typeof track.buffer.changeType === 'function') {
var _data$trackName = data[trackName],
codec = _data$trackName.codec,
levelCodec = _data$trackName.levelCodec,
container = _data$trackName.container;
var currentCodec = (track.levelCodec || track.codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1');
var nextCodec = (levelCodec || codec).replace(VIDEO_CODEC_PROFILE_REPACE, '$1');
if (currentCodec !== nextCodec) {
var mimeType = container + ";codecs=" + (levelCodec || codec);
_this3.appendChangeType(trackName, mimeType);
}
}
} else {
// if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
_this3.pendingTracks[trackName] = data[trackName];
}
}); // if sourcebuffers already created, do nothing ...
if (sourceBufferCount) {
return;
}
this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
if (this.mediaSource && this.mediaSource.readyState === 'open') {
this.checkPendingTracks();
}
};
_proto.appendChangeType = function appendChangeType(type, mimeType) {
var _this4 = this;
var operationQueue = this.operationQueue;
var operation = {
execute: function execute() {
var sb = _this4.sourceBuffer[type];
if (sb) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: changing " + type + " sourceBuffer type to " + mimeType);
sb.changeType(mimeType);
}
operationQueue.shiftAndExecuteNext(type);
},
onStart: function onStart() {},
onComplete: function onComplete() {},
onError: function onError(e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to change " + type + " SourceBuffer type", e);
}
};
operationQueue.append(operation, type);
};
_proto.onBufferAppending = function onBufferAppending(event, eventData) {
var _this5 = this;
var hls = this.hls,
operationQueue = this.operationQueue,
tracks = this.tracks;
var data = eventData.data,
type = eventData.type,
frag = eventData.frag,
part = eventData.part,
chunkMeta = eventData.chunkMeta;
var chunkStats = chunkMeta.buffering[type];
var bufferAppendingStart = self.performance.now();
chunkStats.start = bufferAppendingStart;
var fragBuffering = frag.stats.buffering;
var partBuffering = part ? part.stats.buffering : null;
if (fragBuffering.start === 0) {
fragBuffering.start = bufferAppendingStart;
}
if (partBuffering && partBuffering.start === 0) {
partBuffering.start = bufferAppendingStart;
} // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended
// Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
// in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
// is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).
// More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
var audioTrack = tracks.audio;
var checkTimestampOffset = type === 'audio' && chunkMeta.id === 1 && (audioTrack === null || audioTrack === void 0 ? void 0 : audioTrack.container) === 'audio/mpeg';
var operation = {
execute: function execute() {
chunkStats.executeStart = self.performance.now();
if (checkTimestampOffset) {
var sb = _this5.sourceBuffer[type];
if (sb) {
var delta = frag.start - sb.timestampOffset;
if (Math.abs(delta) >= 0.1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to " + frag.start + " (delta: " + delta + ") sn: " + frag.sn + ")");
sb.timestampOffset = frag.start;
}
}
}
_this5.appendExecutor(data, type);
},
onStart: function onStart() {// logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);
},
onComplete: function onComplete() {
// logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);
var end = self.performance.now();
chunkStats.executeEnd = chunkStats.end = end;
if (fragBuffering.first === 0) {
fragBuffering.first = end;
}
if (partBuffering && partBuffering.first === 0) {
partBuffering.first = end;
}
var sourceBuffer = _this5.sourceBuffer;
var timeRanges = {};
for (var _type in sourceBuffer) {
timeRanges[_type] = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sourceBuffer[_type]);
}
_this5.appendError = 0;
_this5.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_APPENDED, {
type: type,
frag: frag,
part: part,
chunkMeta: chunkMeta,
parent: frag.type,
timeRanges: timeRanges
});
},
onError: function onError(err) {
// in case any error occured while appending, put back segment in segments table
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Error encountered while trying to append to the " + type + " SourceBuffer", err);
var event = {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
parent: frag.type,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR,
err: err,
fatal: false
};
if (err.code === DOMException.QUOTA_EXCEEDED_ERR) {
// QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
// let's stop appending any segments, and report BUFFER_FULL_ERROR error
event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_FULL_ERROR;
} else {
_this5.appendError++;
event.details = _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPEND_ERROR;
/* with UHD content, we could get loop of quota exceeded error until
browser is able to evict some data from sourcebuffer. Retrying can help recover.
*/
if (_this5.appendError > hls.config.appendErrorMaxRetry) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: Failed " + hls.config.appendErrorMaxRetry + " times to append segment in sourceBuffer");
event.fatal = true;
}
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, event);
}
};
operationQueue.append(operation, type);
};
_proto.onBufferFlushing = function onBufferFlushing(event, data) {
var _this6 = this;
var operationQueue = this.operationQueue;
var flushOperation = function flushOperation(type) {
return {
execute: _this6.removeExecutor.bind(_this6, type, data.startOffset, data.endOffset),
onStart: function onStart() {// logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
},
onComplete: function onComplete() {
// logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);
_this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHED, {
type: type
});
},
onError: function onError(e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Failed to remove from " + type + " SourceBuffer", e);
}
};
};
if (data.type) {
operationQueue.append(flushOperation(data.type), data.type);
} else {
operationQueue.append(flushOperation('audio'), 'audio');
operationQueue.append(flushOperation('video'), 'video');
}
};
_proto.onFragParsed = function onFragParsed(event, data) {
var _this7 = this;
var frag = data.frag,
part = data.part;
var buffersAppendedTo = [];
var elementaryStreams = part ? part.elementaryStreams : frag.elementaryStreams;
if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIOVIDEO]) {
buffersAppendedTo.push('audiovideo');
} else {
if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].AUDIO]) {
buffersAppendedTo.push('audio');
}
if (elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_6__["ElementaryStreamTypes"].VIDEO]) {
buffersAppendedTo.push('video');
}
}
var onUnblocked = function onUnblocked() {
var now = self.performance.now();
frag.stats.buffering.end = now;
if (part) {
part.stats.buffering.end = now;
}
var stats = part ? part.stats : frag.stats;
_this7.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_BUFFERED, {
frag: frag,
part: part,
stats: stats,
id: frag.type
});
};
if (buffersAppendedTo.length === 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("Fragments must have at least one ElementaryStreamType set. type: " + frag.type + " level: " + frag.level + " sn: " + frag.sn);
}
this.blockBuffers(onUnblocked, buffersAppendedTo);
};
_proto.onFragChanged = function onFragChanged(event, data) {
this.flushBackBuffer();
} // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
// an undefined data.type will mark all buffers as EOS.
;
_proto.onBufferEos = function onBufferEos(event, data) {
var _this8 = this;
var ended = this.getSourceBufferTypes().reduce(function (acc, type) {
var sb = _this8.sourceBuffer[type];
if (!data.type || data.type === type) {
if (sb && !sb.ended) {
sb.ended = true;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: " + type + " sourceBuffer now EOS");
}
}
return acc && !!(!sb || sb.ended);
}, true);
if (ended) {
this.blockBuffers(function () {
var mediaSource = _this8.mediaSource;
if (!mediaSource || mediaSource.readyState !== 'open') {
return;
} // Allow this to throw and be caught by the enqueueing function
mediaSource.endOfStream();
});
}
};
_proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
var details = _ref.details;
if (!details.fragments.length) {
return;
}
this.details = details;
if (this.getSourceBufferTypes().length) {
this.blockBuffers(this.updateMediaElementDuration.bind(this));
} else {
this.updateMediaElementDuration();
}
};
_proto.flushBackBuffer = function flushBackBuffer() {
var hls = this.hls,
details = this.details,
media = this.media,
sourceBuffer = this.sourceBuffer;
if (!media || details === null) {
return;
}
var sourceBufferTypes = this.getSourceBufferTypes();
if (!sourceBufferTypes.length) {
return;
} // Support for deprecated liveBackBufferLength
var backBufferLength = details.live && hls.config.liveBackBufferLength !== null ? hls.config.liveBackBufferLength : hls.config.backBufferLength;
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(backBufferLength) || backBufferLength < 0) {
return;
}
var currentTime = media.currentTime;
var targetDuration = details.levelTargetDuration;
var maxBackBufferLength = Math.max(backBufferLength, targetDuration);
var targetBackBufferPosition = Math.floor(currentTime / targetDuration) * targetDuration - maxBackBufferLength;
sourceBufferTypes.forEach(function (type) {
var sb = sourceBuffer[type];
if (sb) {
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(sb); // when target buffer start exceeds actual buffer start
if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BACK_BUFFER_REACHED, {
bufferEnd: targetBackBufferPosition
}); // Support for deprecated event:
if (details.live) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LIVE_BACK_BUFFER_REACHED, {
bufferEnd: targetBackBufferPosition
});
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, {
startOffset: 0,
endOffset: targetBackBufferPosition,
type: type
});
}
}
});
}
/**
* Update Media Source duration to current level duration or override to Infinity if configuration parameter
* 'liveDurationInfinity` is set to `true`
* More details: https://github.com/video-dev/hls.js/issues/355
*/
;
_proto.updateMediaElementDuration = function updateMediaElementDuration() {
if (!this.details || !this.media || !this.mediaSource || this.mediaSource.readyState !== 'open') {
return;
}
var details = this.details,
hls = this.hls,
media = this.media,
mediaSource = this.mediaSource;
var levelDuration = details.fragments[0].start + details.totalduration;
var mediaDuration = media.duration;
var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : 0;
if (details.live && hls.config.liveDurationInfinity) {
// Override duration to Infinity
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Media Source duration is set to Infinity');
mediaSource.duration = Infinity;
this.updateSeekableRange(details);
} else if (levelDuration > msDuration && levelDuration > mediaDuration || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaDuration)) {
// levelDuration was the last value we set.
// not using mediaSource.duration as the browser may tweak this value
// only update Media Source duration if its value increase, this is to avoid
// flushing already buffered portion when switching between quality level
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Updating Media Source duration to " + levelDuration.toFixed(3));
mediaSource.duration = levelDuration;
}
};
_proto.updateSeekableRange = function updateSeekableRange(levelDetails) {
var mediaSource = this.mediaSource;
var fragments = levelDetails.fragments;
var len = fragments.length;
if (len && levelDetails.live && mediaSource !== null && mediaSource !== void 0 && mediaSource.setLiveSeekableRange) {
var start = Math.max(0, fragments[0].start);
var end = Math.max(start, start + levelDetails.totalduration);
mediaSource.setLiveSeekableRange(start, end);
}
};
_proto.checkPendingTracks = function checkPendingTracks() {
var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
operationQueue = this.operationQueue,
pendingTracks = this.pendingTracks; // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
// This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
// data has been appended to existing ones.
// 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
var pendingTracksCount = Object.keys(pendingTracks).length;
if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) {
// ok, let's create them now !
this.createSourceBuffers(pendingTracks);
this.pendingTracks = {}; // append any pending segments now !
var buffers = Object.keys(this.sourceBuffer);
if (buffers.length === 0) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_INCOMPATIBLE_CODECS_ERROR,
fatal: true,
reason: 'could not create source buffer for media codec(s)'
});
return;
}
buffers.forEach(function (type) {
operationQueue.executeNext(type);
});
}
};
_proto.createSourceBuffers = function createSourceBuffers(tracks) {
var sourceBuffer = this.sourceBuffer,
mediaSource = this.mediaSource;
if (!mediaSource) {
throw Error('createSourceBuffers called when mediaSource was null');
}
var tracksCreated = 0;
for (var trackName in tracks) {
if (!sourceBuffer[trackName]) {
var track = tracks[trackName];
if (!track) {
throw Error("source buffer exists for track " + trackName + ", however track does not");
} // use levelCodec as first priority
var codec = track.levelCodec || track.codec;
var mimeType = track.container + ";codecs=" + codec;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: creating sourceBuffer(" + mimeType + ")");
try {
var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
var sbName = trackName;
this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);
this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);
this.addBufferListener(sbName, 'error', this._onSBUpdateError);
this.tracks[trackName] = {
buffer: sb,
codec: codec,
container: track.container,
levelCodec: track.levelCodec,
id: track.id
};
tracksCreated++;
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: error while trying to add sourceBuffer: " + err.message);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_ADD_CODEC_ERROR,
fatal: false,
error: err,
mimeType: mimeType
});
}
}
}
if (tracksCreated) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_CREATED, {
tracks: this.tracks
});
}
} // Keep as arrow functions so that we can directly reference these functions directly as event listeners
;
_proto._onSBUpdateStart = function _onSBUpdateStart(type) {
var operationQueue = this.operationQueue;
var operation = operationQueue.current(type);
operation.onStart();
};
_proto._onSBUpdateEnd = function _onSBUpdateEnd(type) {
var operationQueue = this.operationQueue;
var operation = operationQueue.current(type);
operation.onComplete();
operationQueue.shiftAndExecuteNext(type);
};
_proto._onSBUpdateError = function _onSBUpdateError(type, event) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("[buffer-controller]: " + type + " SourceBuffer error", event); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
// SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_3__["ErrorDetails"].BUFFER_APPENDING_ERROR,
fatal: false
}); // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue
var operation = this.operationQueue.current(type);
if (operation) {
operation.onError(event);
}
} // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually
;
_proto.removeExecutor = function removeExecutor(type, startOffset, endOffset) {
var media = this.media,
mediaSource = this.mediaSource,
operationQueue = this.operationQueue,
sourceBuffer = this.sourceBuffer;
var sb = sourceBuffer[type];
if (!media || !mediaSource || !sb) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to remove from the " + type + " SourceBuffer, but it does not exist");
operationQueue.shiftAndExecuteNext(type);
return;
}
var mediaDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(media.duration) ? media.duration : Infinity;
var msDuration = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mediaSource.duration) ? mediaSource.duration : Infinity;
var removeStart = Math.max(0, startOffset);
var removeEnd = Math.min(endOffset, mediaDuration, msDuration);
if (removeEnd > removeStart) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("[buffer-controller]: Removing [" + removeStart + "," + removeEnd + "] from the " + type + " SourceBuffer");
console.assert(!sb.updating, type + " sourceBuffer must not be updating");
sb.remove(removeStart, removeEnd);
} else {
// Cycle the queue
operationQueue.shiftAndExecuteNext(type);
}
} // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually
;
_proto.appendExecutor = function appendExecutor(data, type) {
var operationQueue = this.operationQueue,
sourceBuffer = this.sourceBuffer;
var sb = sourceBuffer[type];
if (!sb) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("[buffer-controller]: Attempting to append to the " + type + " SourceBuffer, but it does not exist");
operationQueue.shiftAndExecuteNext(type);
return;
}
sb.ended = false;
console.assert(!sb.updating, type + " sourceBuffer must not be updating");
sb.appendBuffer(data);
} // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises
// resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue
// upon completion, since we already do it here
;
_proto.blockBuffers = function blockBuffers(onUnblocked, buffers) {
var _this9 = this;
if (buffers === void 0) {
buffers = this.getSourceBufferTypes();
}
if (!buffers.length) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('[buffer-controller]: Blocking operation requested, but no SourceBuffers exist');
Promise.resolve(onUnblocked);
return;
}
var operationQueue = this.operationQueue; // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);
var blockingOperations = buffers.map(function (type) {
return operationQueue.appendBlocker(type);
});
Promise.all(blockingOperations).then(function () {
// logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);
onUnblocked();
buffers.forEach(function (type) {
var sb = _this9.sourceBuffer[type]; // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to
// true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)
// While this is a workaround, it's probably useful to have around
if (!sb || !sb.updating) {
operationQueue.shiftAndExecuteNext(type);
}
});
});
};
_proto.getSourceBufferTypes = function getSourceBufferTypes() {
return Object.keys(this.sourceBuffer);
};
_proto.addBufferListener = function addBufferListener(type, event, fn) {
var buffer = this.sourceBuffer[type];
if (!buffer) {
return;
}
var listener = fn.bind(this, type);
this.listeners[type].push({
event: event,
listener: listener
});
buffer.addEventListener(event, listener);
};
_proto.removeBufferListeners = function removeBufferListeners(type) {
var buffer = this.sourceBuffer[type];
if (!buffer) {
return;
}
this.listeners[type].forEach(function (l) {
buffer.removeEventListener(l.event, l.listener);
});
};
return BufferController;
}();
/***/ }),
/***/ "./src/controller/buffer-operation-queue.ts":
/*!**************************************************!*\
!*** ./src/controller/buffer-operation-queue.ts ***!
\**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BufferOperationQueue; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var BufferOperationQueue = /*#__PURE__*/function () {
function BufferOperationQueue(sourceBufferReference) {
this.buffers = void 0;
this.queues = {
video: [],
audio: [],
audiovideo: []
};
this.buffers = sourceBufferReference;
}
var _proto = BufferOperationQueue.prototype;
_proto.append = function append(operation, type) {
var queue = this.queues[type];
queue.push(operation);
if (queue.length === 1 && this.buffers[type]) {
this.executeNext(type);
}
};
_proto.insertAbort = function insertAbort(operation, type) {
var queue = this.queues[type];
queue.unshift(operation);
this.executeNext(type);
};
_proto.appendBlocker = function appendBlocker(type) {
var execute;
var promise = new Promise(function (resolve) {
execute = resolve;
});
var operation = {
execute: execute,
onStart: function onStart() {},
onComplete: function onComplete() {},
onError: function onError() {}
};
this.append(operation, type);
return promise;
};
_proto.executeNext = function executeNext(type) {
var buffers = this.buffers,
queues = this.queues;
var sb = buffers[type];
var queue = queues[type];
if (queue.length) {
var operation = queue[0];
try {
// Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations
// which do not end with this event must call _onSBUpdateEnd manually
operation.execute();
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn('[buffer-operation-queue]: Unhandled exception executing the current operation');
operation.onError(e); // Only shift the current operation off, otherwise the updateend handler will do this for us
if (!sb || !sb.updating) {
queue.shift();
}
}
}
};
_proto.shiftAndExecuteNext = function shiftAndExecuteNext(type) {
this.queues[type].shift();
this.executeNext(type);
};
_proto.current = function current(type) {
return this.queues[type][0];
};
return BufferOperationQueue;
}();
/***/ }),
/***/ "./src/controller/cap-level-controller.ts":
/*!************************************************!*\
!*** ./src/controller/cap-level-controller.ts ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/*
* cap stream level to media size dimension controller
*/
var CapLevelController = /*#__PURE__*/function () {
function CapLevelController(hls) {
this.autoLevelCapping = void 0;
this.firstLevel = void 0;
this.media = void 0;
this.restrictedLevels = void 0;
this.timer = void 0;
this.hls = void 0;
this.streamController = void 0;
this.clientRect = void 0;
this.hls = hls;
this.autoLevelCapping = Number.POSITIVE_INFINITY;
this.firstLevel = -1;
this.media = null;
this.restrictedLevels = [];
this.timer = undefined;
this.clientRect = null;
this.registerListeners();
}
var _proto = CapLevelController.prototype;
_proto.setStreamController = function setStreamController(streamController) {
this.streamController = streamController;
};
_proto.destroy = function destroy() {
this.unregisterListener();
if (this.hls.config.capLevelToPlayerSize) {
this.stopCapping();
}
this.media = null;
this.clientRect = null; // @ts-ignore
this.hls = this.streamController = null;
};
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
};
_proto.unregisterListener = function unregisterListener() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_CODECS, this.onBufferCodecs, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
};
_proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(event, data) {
// Don't add a restricted level more than once
if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
this.restrictedLevels.push(data.droppedLevel);
}
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
this.media = data.media instanceof HTMLVideoElement ? data.media : null;
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
var hls = this.hls;
this.restrictedLevels = [];
this.firstLevel = data.firstLevel;
if (hls.config.capLevelToPlayerSize && data.video) {
// Start capping immediately if the manifest has signaled video codecs
this.startCapping();
}
} // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
// to the first level
;
_proto.onBufferCodecs = function onBufferCodecs(event, data) {
var hls = this.hls;
if (hls.config.capLevelToPlayerSize && data.video) {
// If the manifest did not signal a video codec capping has been deferred until we're certain video is present
this.startCapping();
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
this.stopCapping();
};
_proto.detectPlayerSize = function detectPlayerSize() {
if (this.media && this.mediaHeight > 0 && this.mediaWidth > 0) {
var levels = this.hls.levels;
if (levels.length) {
var hls = this.hls;
hls.autoLevelCapping = this.getMaxLevel(levels.length - 1);
if (hls.autoLevelCapping > this.autoLevelCapping && this.streamController) {
// if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
// usually happen when the user go to the fullscreen mode.
this.streamController.nextLevelSwitch();
}
this.autoLevelCapping = hls.autoLevelCapping;
}
}
}
/*
* returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
*/
;
_proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
var _this = this;
var levels = this.hls.levels;
if (!levels.length) {
return -1;
}
var validLevels = levels.filter(function (level, index) {
return CapLevelController.isLevelAllowed(index, _this.restrictedLevels) && index <= capLevelIndex;
});
this.clientRect = null;
return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
};
_proto.startCapping = function startCapping() {
if (this.timer) {
// Don't reset capping if started twice; this can happen if the manifest signals a video codec
return;
}
this.autoLevelCapping = Number.POSITIVE_INFINITY;
this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
self.clearInterval(this.timer);
this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);
this.detectPlayerSize();
};
_proto.stopCapping = function stopCapping() {
this.restrictedLevels = [];
this.firstLevel = -1;
this.autoLevelCapping = Number.POSITIVE_INFINITY;
if (this.timer) {
self.clearInterval(this.timer);
this.timer = undefined;
}
};
_proto.getDimensions = function getDimensions() {
if (this.clientRect) {
return this.clientRect;
}
var media = this.media;
var boundsRect = {
width: 0,
height: 0
};
if (media) {
var clientRect = media.getBoundingClientRect();
boundsRect.width = clientRect.width;
boundsRect.height = clientRect.height;
if (!boundsRect.width && !boundsRect.height) {
// When the media element has no width or height (equivalent to not being in the DOM),
// then use its width and height attributes (media.width, media.height)
boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
}
}
this.clientRect = boundsRect;
return boundsRect;
};
CapLevelController.isLevelAllowed = function isLevelAllowed(level, restrictedLevels) {
if (restrictedLevels === void 0) {
restrictedLevels = [];
}
return restrictedLevels.indexOf(level) === -1;
};
CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
if (!levels || !levels.length) {
return -1;
} // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
// to determine whether we've chosen the greatest bandwidth for the media's dimensions
var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {
if (!nextLevel) {
return true;
}
return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
}; // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
// the max level
var maxLevelIndex = levels.length - 1;
for (var i = 0; i < levels.length; i += 1) {
var level = levels[i];
if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
maxLevelIndex = i;
break;
}
}
return maxLevelIndex;
};
_createClass(CapLevelController, [{
key: "mediaWidth",
get: function get() {
return this.getDimensions().width * CapLevelController.contentScaleFactor;
}
}, {
key: "mediaHeight",
get: function get() {
return this.getDimensions().height * CapLevelController.contentScaleFactor;
}
}], [{
key: "contentScaleFactor",
get: function get() {
var pixelRatio = 1;
try {
pixelRatio = self.devicePixelRatio;
} catch (e) {
/* no-op */
}
return pixelRatio;
}
}]);
return CapLevelController;
}();
/* harmony default export */ __webpack_exports__["default"] = (CapLevelController);
/***/ }),
/***/ "./src/controller/eme-controller.ts":
/*!******************************************!*\
!*** ./src/controller/eme-controller.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mediakeys-helper */ "./src/utils/mediakeys-helper.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>
*
* DRM support for Hls.js
*/
var MAX_LICENSE_REQUEST_FAILURES = 3;
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
* @param {Array<string>} audioCodecs List of required audio codecs to support
* @param {Array<string>} videoCodecs List of required video codecs to support
* @param {object} drmSystemOptions Optional parameters/requirements for the key-system
* @returns {Array<MediaSystemConfiguration>} An array of supported configurations
*/
var createWidevineMediaKeySystemConfigurations = function createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions) {
/* jshint ignore:line */
var baseConfig = {
// initDataTypes: ['keyids', 'mp4'],
// label: "",
// persistentState: "not-allowed", // or "required" ?
// distinctiveIdentifier: "not-allowed", // or "required" ?
// sessionTypes: ['temporary'],
audioCapabilities: [],
// { contentType: 'audio/mp4; codecs="mp4a.40.2"' }
videoCapabilities: [] // { contentType: 'video/mp4; codecs="avc1.42E01E"' }
};
audioCodecs.forEach(function (codec) {
baseConfig.audioCapabilities.push({
contentType: "audio/mp4; codecs=\"" + codec + "\"",
robustness: drmSystemOptions.audioRobustness || ''
});
});
videoCodecs.forEach(function (codec) {
baseConfig.videoCapabilities.push({
contentType: "video/mp4; codecs=\"" + codec + "\"",
robustness: drmSystemOptions.videoRobustness || ''
});
});
return [baseConfig];
};
/**
* The idea here is to handle key-system (and their respective platforms) specific configuration differences
* in order to work with the local requestMediaKeySystemAccess method.
*
* We can also rule-out platform-related key-system support at this point by throwing an error.
*
* @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
* @param {Array<string>} audioCodecs List of required audio codecs to support
* @param {Array<string>} videoCodecs List of required video codecs to support
* @throws will throw an error if a unknown key system is passed
* @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects
*/
var getSupportedMediaKeySystemConfigurations = function getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, drmSystemOptions) {
switch (keySystem) {
case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE:
return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions);
default:
throw new Error("Unknown key-system: " + keySystem);
}
};
/**
* Controller to deal with encrypted media extensions (EME)
* @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
*
* @class
* @constructor
*/
var EMEController = /*#__PURE__*/function () {
/**
* @constructs
* @param {Hls} hls Our Hls.js instance
*/
function EMEController(hls) {
this.hls = void 0;
this._widevineLicenseUrl = void 0;
this._licenseXhrSetup = void 0;
this._licenseResponseCallback = void 0;
this._emeEnabled = void 0;
this._requestMediaKeySystemAccess = void 0;
this._drmSystemOptions = void 0;
this._config = void 0;
this._mediaKeysList = [];
this._media = null;
this._hasSetMediaKeys = false;
this._requestLicenseFailureCount = 0;
this.mediaKeysPromise = null;
this._onMediaEncrypted = this.onMediaEncrypted.bind(this);
this.hls = hls;
this._config = hls.config;
this._widevineLicenseUrl = this._config.widevineLicenseUrl;
this._licenseXhrSetup = this._config.licenseXhrSetup;
this._licenseResponseCallback = this._config.licenseResponseCallback;
this._emeEnabled = this._config.emeEnabled;
this._requestMediaKeySystemAccess = this._config.requestMediaKeySystemAccessFunc;
this._drmSystemOptions = this._config.drmSystemOptions;
this._registerListeners();
}
var _proto = EMEController.prototype;
_proto.destroy = function destroy() {
this._unregisterListeners(); // @ts-ignore
this.hls = this._onMediaEncrypted = null;
this._requestMediaKeySystemAccess = null;
};
_proto._registerListeners = function _registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHED, this.onMediaDetached, this);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
}
/**
* @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
* @returns {string} License server URL for key-system (if any configured, otherwise causes error)
* @throws if a unsupported keysystem is passed
*/
;
_proto.getLicenseServerUrl = function getLicenseServerUrl(keySystem) {
switch (keySystem) {
case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE:
if (!this._widevineLicenseUrl) {
break;
}
return this._widevineLicenseUrl;
}
throw new Error("no license server URL configured for key-system \"" + keySystem + "\"");
}
/**
* Requests access object and adds it to our list upon success
* @private
* @param {string} keySystem System ID (see `KeySystems`)
* @param {Array<string>} audioCodecs List of required audio codecs to support
* @param {Array<string>} videoCodecs List of required video codecs to support
* @throws When a unsupported KeySystem is passed
*/
;
_proto._attemptKeySystemAccess = function _attemptKeySystemAccess(keySystem, audioCodecs, videoCodecs) {
var _this = this;
// This can throw, but is caught in event handler callpath
var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this._drmSystemOptions);
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Requesting encrypted media key-system access'); // expecting interface like window.navigator.requestMediaKeySystemAccess
var keySystemAccessPromise = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);
this.mediaKeysPromise = keySystemAccessPromise.then(function (mediaKeySystemAccess) {
return _this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);
});
keySystemAccessPromise.catch(function (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("Failed to obtain key-system \"" + keySystem + "\" access:", err);
});
};
/**
* Handles obtaining access to a key-system
* @private
* @param {string} keySystem
* @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
*/
_proto._onMediaKeySystemAccessObtained = function _onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess) {
var _this2 = this;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Access for key-system \"" + keySystem + "\" obtained");
var mediaKeysListItem = {
mediaKeysSessionInitialized: false,
mediaKeySystemAccess: mediaKeySystemAccess,
mediaKeySystemDomain: keySystem
};
this._mediaKeysList.push(mediaKeysListItem);
var mediaKeysPromise = Promise.resolve().then(function () {
return mediaKeySystemAccess.createMediaKeys();
}).then(function (mediaKeys) {
mediaKeysListItem.mediaKeys = mediaKeys;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Media-keys created for key-system \"" + keySystem + "\"");
_this2._onMediaKeysCreated();
return mediaKeys;
});
mediaKeysPromise.catch(function (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Failed to create media-keys:', err);
});
return mediaKeysPromise;
}
/**
* Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
* for all existing keys where no session exists yet.
*
* @private
*/
;
_proto._onMediaKeysCreated = function _onMediaKeysCreated() {
var _this3 = this;
// check for all key-list items if a session exists, otherwise, create one
this._mediaKeysList.forEach(function (mediaKeysListItem) {
if (!mediaKeysListItem.mediaKeysSession) {
// mediaKeys is definitely initialized here
mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();
_this3._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
}
});
}
/**
* @private
* @param {*} keySession
*/
;
_proto._onNewMediaKeySession = function _onNewMediaKeySession(keySession) {
var _this4 = this;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("New key-system session " + keySession.sessionId);
keySession.addEventListener('message', function (event) {
_this4._onKeySessionMessage(keySession, event.message);
}, false);
}
/**
* @private
* @param {MediaKeySession} keySession
* @param {ArrayBuffer} message
*/
;
_proto._onKeySessionMessage = function _onKeySessionMessage(keySession, message) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Got EME message event, creating license request');
this._requestLicense(message, function (data) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Received license data (length: " + (data ? data.byteLength : data) + "), updating key-session");
keySession.update(data);
});
}
/**
* @private
* @param e {MediaEncryptedEvent}
*/
;
_proto.onMediaEncrypted = function onMediaEncrypted(e) {
var _this5 = this;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Media is encrypted using \"" + e.initDataType + "\" init data type");
if (!this.mediaKeysPromise) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been requested');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_KEYS,
fatal: true
});
return;
}
var finallySetKeyAndStartSession = function finallySetKeyAndStartSession(mediaKeys) {
if (!_this5._media) {
return;
}
_this5._attemptSetMediaKeys(mediaKeys);
_this5._generateRequestWithPreferredKeySession(e.initDataType, e.initData);
}; // Could use `Promise.finally` but some Promise polyfills are missing it
this.mediaKeysPromise.then(finallySetKeyAndStartSession).catch(finallySetKeyAndStartSession);
}
/**
* @private
*/
;
_proto._attemptSetMediaKeys = function _attemptSetMediaKeys(mediaKeys) {
if (!this._media) {
throw new Error('Attempted to set mediaKeys without first attaching a media element');
}
if (!this._hasSetMediaKeys) {
// FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
var keysListItem = this._mediaKeysList[0];
if (!keysListItem || !keysListItem.mediaKeys) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_KEYS,
fatal: true
});
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Setting keys for encrypted media');
this._media.setMediaKeys(keysListItem.mediaKeys);
this._hasSetMediaKeys = true;
}
}
/**
* @private
*/
;
_proto._generateRequestWithPreferredKeySession = function _generateRequestWithPreferredKeySession(initDataType, initData) {
var _this6 = this;
// FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
var keysListItem = this._mediaKeysList[0];
if (!keysListItem) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but not any key-system access has been obtained yet');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_ACCESS,
fatal: true
});
return;
}
if (keysListItem.mediaKeysSessionInitialized) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Key-Session already initialized but requested again');
return;
}
var keySession = keysListItem.mediaKeysSession;
if (!keySession) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal: Media is encrypted but no key-session existing');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_SESSION,
fatal: true
});
return;
} // initData is null if the media is not CORS-same-origin
if (!initData) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Fatal: initData required for generating a key session is null');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_INIT_DATA,
fatal: true
});
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Generating key-session request for \"" + initDataType + "\" init data type");
keysListItem.mediaKeysSessionInitialized = true;
keySession.generateRequest(initDataType, initData).then(function () {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].debug('Key-session generation succeeded');
}).catch(function (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Error generating key-session request:', err);
_this6.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_SESSION,
fatal: false
});
});
}
/**
* @private
* @param {string} url License server URL
* @param {ArrayBuffer} keyMessage Message data issued by key-system
* @param {function} callback Called when XHR has succeeded
* @returns {XMLHttpRequest} Unsent (but opened state) XHR object
* @throws if XMLHttpRequest construction failed
*/
;
_proto._createLicenseXhr = function _createLicenseXhr(url, keyMessage, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);
var licenseXhrSetup = this._licenseXhrSetup;
if (licenseXhrSetup) {
try {
licenseXhrSetup.call(this.hls, xhr, url);
licenseXhrSetup = undefined;
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error(e);
}
}
try {
// if licenseXhrSetup did not yet call open, let's do it now
if (!xhr.readyState) {
xhr.open('POST', url, true);
}
if (licenseXhrSetup) {
licenseXhrSetup.call(this.hls, xhr, url);
}
} catch (e) {
// IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
throw new Error("issue setting up KeySystem license XHR " + e);
}
return xhr;
}
/**
* @private
* @param {XMLHttpRequest} xhr
* @param {string} url License server URL
* @param {ArrayBuffer} keyMessage Message data issued by key-system
* @param {function} callback Called when XHR has succeeded
*/
;
_proto._onLicenseRequestReadyStageChange = function _onLicenseRequestReadyStageChange(xhr, url, keyMessage, callback) {
switch (xhr.readyState) {
case 4:
if (xhr.status === 200) {
this._requestLicenseFailureCount = 0;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('License request succeeded');
var _data = xhr.response;
var licenseResponseCallback = this._licenseResponseCallback;
if (licenseResponseCallback) {
try {
_data = licenseResponseCallback.call(this.hls, xhr, url);
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error(e);
}
}
callback(_data);
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("License Request XHR failed (" + url + "). Status: " + xhr.status + " (" + xhr.statusText + ")");
this._requestLicenseFailureCount++;
if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
fatal: true
});
return;
}
var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("Retrying license request, " + attemptsLeft + " attempts left");
this._requestLicense(keyMessage, callback);
}
break;
}
}
/**
* @private
* @param {MediaKeysListItem} keysListItem
* @param {ArrayBuffer} keyMessage
* @returns {ArrayBuffer} Challenge data posted to license server
* @throws if KeySystem is unsupported
*/
;
_proto._generateLicenseRequestChallenge = function _generateLicenseRequestChallenge(keysListItem, keyMessage) {
switch (keysListItem.mediaKeySystemDomain) {
// case KeySystems.PLAYREADY:
// from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
/*
if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
// For PlayReady CDMs, we need to dig the Challenge out of the XML.
var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
} else {
throw 'Cannot find <Challenge> in key message';
}
var headerNames = keyMessageXml.getElementsByTagName('name');
var headerValues = keyMessageXml.getElementsByTagName('value');
if (headerNames.length !== headerValues.length) {
throw 'Mismatched header <name>/<value> pair in key message';
}
for (var i = 0; i < headerNames.length; i++) {
xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
}
}
break;
*/
case _utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE:
// For Widevine CDMs, the challenge is the keyMessage.
return keyMessage;
}
throw new Error("unsupported key-system: " + keysListItem.mediaKeySystemDomain);
}
/**
* @private
* @param keyMessage
* @param callback
*/
;
_proto._requestLicense = function _requestLicense(keyMessage, callback) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('Requesting content license for key-system');
var keysListItem = this._mediaKeysList[0];
if (!keysListItem) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('Fatal error: Media is encrypted but no key-system access has been obtained yet');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_NO_ACCESS,
fatal: true
});
return;
}
try {
var _url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
var _xhr = this._createLicenseXhr(_url, keyMessage, callback);
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log("Sending license request to URL: " + _url);
var challenge = this._generateLicenseRequestChallenge(keysListItem, keyMessage);
_xhr.send(challenge);
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error("Failure requesting DRM license: " + e);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].KEY_SYSTEM_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_SYSTEM_LICENSE_REQUEST_FAILED,
fatal: true
});
}
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
if (!this._emeEnabled) {
return;
}
var media = data.media; // keep reference of media
this._media = media;
media.addEventListener('encrypted', this._onMediaEncrypted);
};
_proto.onMediaDetached = function onMediaDetached() {
var media = this._media;
var mediaKeysList = this._mediaKeysList;
if (!media) {
return;
}
media.removeEventListener('encrypted', this._onMediaEncrypted);
this._media = null;
this._mediaKeysList = []; // Close all sessions and remove media keys from the video element.
Promise.all(mediaKeysList.map(function (mediaKeysListItem) {
if (mediaKeysListItem.mediaKeysSession) {
return mediaKeysListItem.mediaKeysSession.close().catch(function () {// Ignore errors when closing the sessions. Closing a session that
// generated no key requests will throw an error.
});
}
})).then(function () {
return media.setMediaKeys(null);
}).catch(function () {// Ignore any failures while removing media keys from the video element.
});
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
if (!this._emeEnabled) {
return;
}
var audioCodecs = data.levels.map(function (level) {
return level.audioCodec;
}).filter(function (audioCodec) {
return !!audioCodec;
});
var videoCodecs = data.levels.map(function (level) {
return level.videoCodec;
}).filter(function (videoCodec) {
return !!videoCodec;
});
this._attemptKeySystemAccess(_utils_mediakeys_helper__WEBPACK_IMPORTED_MODULE_3__["KeySystems"].WIDEVINE, audioCodecs, videoCodecs);
};
_createClass(EMEController, [{
key: "requestMediaKeySystemAccess",
get: function get() {
if (!this._requestMediaKeySystemAccess) {
throw new Error('No requestMediaKeySystemAccess function configured');
}
return this._requestMediaKeySystemAccess;
}
}]);
return EMEController;
}();
/* harmony default export */ __webpack_exports__["default"] = (EMEController);
/***/ }),
/***/ "./src/controller/fps-controller.ts":
/*!******************************************!*\
!*** ./src/controller/fps-controller.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var FPSController = /*#__PURE__*/function () {
// stream controller must be provided as a dependency!
function FPSController(hls) {
this.hls = void 0;
this.isVideoPlaybackQualityAvailable = false;
this.timer = void 0;
this.media = null;
this.lastTime = void 0;
this.lastDroppedFrames = 0;
this.lastDecodedFrames = 0;
this.streamController = void 0;
this.hls = hls;
this.registerListeners();
}
var _proto = FPSController.prototype;
_proto.setStreamController = function setStreamController(streamController) {
this.streamController = streamController;
};
_proto.registerListeners = function registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
};
_proto.unregisterListeners = function unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHING, this.onMediaAttaching);
};
_proto.destroy = function destroy() {
if (this.timer) {
clearInterval(this.timer);
}
this.unregisterListeners();
this.isVideoPlaybackQualityAvailable = false;
this.media = null;
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
var config = this.hls.config;
if (config.capLevelOnFPSDrop) {
var media = data.media instanceof self.HTMLVideoElement ? data.media : null;
this.media = media;
if (media && typeof media.getVideoPlaybackQuality === 'function') {
this.isVideoPlaybackQualityAvailable = true;
}
self.clearInterval(this.timer);
this.timer = self.setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
}
};
_proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
var currentTime = performance.now();
if (decodedFrames) {
if (this.lastTime) {
var currentPeriod = currentTime - this.lastTime;
var currentDropped = droppedFrames - this.lastDroppedFrames;
var currentDecoded = decodedFrames - this.lastDecodedFrames;
var droppedFPS = 1000 * currentDropped / currentPeriod;
var hls = this.hls;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP, {
currentDropped: currentDropped,
currentDecoded: currentDecoded,
totalDroppedFrames: droppedFrames
});
if (droppedFPS > 0) {
// logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
var currentLevel = hls.currentLevel;
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
currentLevel = currentLevel - 1;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FPS_DROP_LEVEL_CAPPING, {
level: currentLevel,
droppedLevel: hls.currentLevel
});
hls.autoLevelCapping = currentLevel;
this.streamController.nextLevelSwitch();
}
}
}
}
this.lastTime = currentTime;
this.lastDroppedFrames = droppedFrames;
this.lastDecodedFrames = decodedFrames;
}
};
_proto.checkFPSInterval = function checkFPSInterval() {
var video = this.media;
if (video) {
if (this.isVideoPlaybackQualityAvailable) {
var videoPlaybackQuality = video.getVideoPlaybackQuality();
this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
} else {
// HTMLVideoElement doesn't include the webkit types
this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
}
}
};
return FPSController;
}();
/* harmony default export */ __webpack_exports__["default"] = (FPSController);
/***/ }),
/***/ "./src/controller/fragment-finders.ts":
/*!********************************************!*\
!*** ./src/controller/fragment-finders.ts ***!
\********************************************/
/*! exports provided: findFragmentByPDT, findFragmentByPTS, fragmentWithinToleranceTest, pdtWithinToleranceTest, findFragWithCC */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPDT", function() { return findFragmentByPDT; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragmentByPTS", function() { return findFragmentByPTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fragmentWithinToleranceTest", function() { return fragmentWithinToleranceTest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pdtWithinToleranceTest", function() { return pdtWithinToleranceTest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFragWithCC", function() { return findFragWithCC; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/binary-search */ "./src/utils/binary-search.ts");
/**
* Returns first fragment whose endPdt value exceeds the given PDT.
* @param {Array<Fragment>} fragments - The array of candidate fragments
* @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
* @returns {*|null} fragment - The best matching fragment
*/
function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(PDTValue)) {
return null;
} // if less than start
var startPDT = fragments[0].programDateTime;
if (PDTValue < (startPDT || 0)) {
return null;
}
var endPDT = fragments[fragments.length - 1].endProgramDateTime;
if (PDTValue >= (endPDT || 0)) {
return null;
}
maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
for (var seg = 0; seg < fragments.length; ++seg) {
var frag = fragments[seg];
if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
return frag;
}
}
return null;
}
/**
* Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
* This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
* breaking any traps which would cause the same fragment to be continuously selected within a small range.
* @param {*} fragPrevious - The last frag successfully appended
* @param {Array} fragments - The array of candidate fragments
* @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
* @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
* @returns {*} foundFrag - The best matching fragment
*/
function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) {
if (bufferEnd === void 0) {
bufferEnd = 0;
}
if (maxFragLookUpTolerance === void 0) {
maxFragLookUpTolerance = 0;
}
var fragNext = null;
if (fragPrevious) {
fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1];
} else if (bufferEnd === 0 && fragments[0].start === 0) {
fragNext = fragments[0];
} // Prefer the next fragment if it's within tolerance
if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {
return fragNext;
} // We might be seeking past the tolerance so find the best match
var foundFragment = _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
if (foundFragment) {
return foundFragment;
} // If no match was found return the next fragment after fragPrevious, or null
return fragNext;
}
/**
* The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
* @param {*} candidate - The fragment to test
* @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
* @returns {number} - 0 if it matches, 1 if too low, -1 if too high
*/
function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
if (bufferEnd === void 0) {
bufferEnd = 0;
}
if (maxFragLookUpTolerance === void 0) {
maxFragLookUpTolerance = 0;
}
// offset should be within fragment boundary - config.maxFragLookUpTolerance
// this is to cope with situations like
// bufferEnd = 9.991
// frag[Ø] : [0,10]
// frag[1] : [10,20]
// bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
// frag start frag start+duration
// |-----------------------------|
// <---> <--->
// ...--------><-----------------------------><---------....
// previous frag matching fragment next frag
// return -1 return 0 return 1
// logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
// Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
return 1;
} else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
// if maxFragLookUpTolerance will have negative value then don't return -1 for first element
return -1;
}
return 0;
}
/**
* The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
* This function tests the candidate's program date time values, as represented in Unix time
* @param {*} candidate - The fragment to test
* @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
* @returns {boolean} True if contiguous, false otherwise
*/
function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000; // endProgramDateTime can be null, default to zero
var endProgramDateTime = candidate.endProgramDateTime || 0;
return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
}
function findFragWithCC(fragments, cc) {
return _utils_binary_search__WEBPACK_IMPORTED_MODULE_1__["default"].search(fragments, function (candidate) {
if (candidate.cc < cc) {
return 1;
} else if (candidate.cc > cc) {
return -1;
} else {
return 0;
}
});
}
/***/ }),
/***/ "./src/controller/fragment-tracker.ts":
/*!********************************************!*\
!*** ./src/controller/fragment-tracker.ts ***!
\********************************************/
/*! exports provided: FragmentState, FragmentTracker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentState", function() { return FragmentState; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentTracker", function() { return FragmentTracker; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
var FragmentState;
(function (FragmentState) {
FragmentState["NOT_LOADED"] = "NOT_LOADED";
FragmentState["BACKTRACKED"] = "BACKTRACKED";
FragmentState["APPENDING"] = "APPENDING";
FragmentState["PARTIAL"] = "PARTIAL";
FragmentState["OK"] = "OK";
})(FragmentState || (FragmentState = {}));
var FragmentTracker = /*#__PURE__*/function () {
function FragmentTracker(hls) {
this.activeFragment = null;
this.activeParts = null;
this.fragments = Object.create(null);
this.timeRanges = Object.create(null);
this.bufferPadding = 0.2;
this.hls = void 0;
this.hls = hls;
this._registerListeners();
}
var _proto = FragmentTracker.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_APPENDED, this.onBufferAppended, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_LOADED, this.onFragLoaded, this);
};
_proto.destroy = function destroy() {
this._unregisterListeners(); // @ts-ignore
this.fragments = this.timeRanges = null;
}
/**
* Return a Fragment with an appended range that matches the position and levelType.
* If not found any Fragment, return null
*/
;
_proto.getAppendedFrag = function getAppendedFrag(position, levelType) {
if (levelType === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) {
var activeFragment = this.activeFragment,
activeParts = this.activeParts;
if (!activeFragment) {
return null;
}
if (activeParts) {
for (var i = activeParts.length; i--;) {
var activePart = activeParts[i];
var appendedPTS = activePart ? activePart.end : activeFragment.appendedPTS;
if (activePart.start <= position && appendedPTS !== undefined && position <= appendedPTS) {
// 9 is a magic number. remove parts from lookup after a match but keep some short seeks back.
if (i > 9) {
this.activeParts = activeParts.slice(i - 9);
}
return activePart;
}
}
} else if (activeFragment.start <= position && activeFragment.appendedPTS !== undefined && position <= activeFragment.appendedPTS) {
return activeFragment;
}
}
return this.getBufferedFrag(position, levelType);
}
/**
* Return a buffered Fragment that matches the position and levelType.
* A buffered Fragment is one whose loading, parsing and appending is done (completed or "partial" meaning aborted).
* If not found any Fragment, return null
*/
;
_proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
var fragments = this.fragments;
var keys = Object.keys(fragments);
for (var i = keys.length; i--;) {
var fragmentEntity = fragments[keys[i]];
if ((fragmentEntity === null || fragmentEntity === void 0 ? void 0 : fragmentEntity.body.type) === levelType && fragmentEntity.buffered) {
var frag = fragmentEntity.body;
if (frag.start <= position && position <= frag.end) {
return frag;
}
}
}
return null;
}
/**
* Partial fragments effected by coded frame eviction will be removed
* The browser will unload parts of the buffer to free up memory for new buffer data
* Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
*/
;
_proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange, playlistType) {
var _this = this;
// Check if any flagged fragments have been unloaded
Object.keys(this.fragments).forEach(function (key) {
var fragmentEntity = _this.fragments[key];
if (!fragmentEntity) {
return;
}
if (!fragmentEntity.buffered) {
if (fragmentEntity.body.type === playlistType) {
_this.removeFragment(fragmentEntity.body);
}
return;
}
var esData = fragmentEntity.range[elementaryStream];
if (!esData) {
return;
}
esData.time.some(function (time) {
var isNotBuffered = !_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange);
if (isNotBuffered) {
// Unregister partial fragment as it needs to load again to be reused
_this.removeFragment(fragmentEntity.body);
}
return isNotBuffered;
});
});
}
/**
* Checks if the fragment passed in is loaded in the buffer properly
* Partially loaded fragments will be registered as a partial fragment
*/
;
_proto.detectPartialFragments = function detectPartialFragments(data) {
var _this2 = this;
var timeRanges = this.timeRanges;
var frag = data.frag,
part = data.part;
if (!timeRanges || frag.sn === 'initSegment') {
return;
}
var fragKey = getFragmentKey(frag);
var fragmentEntity = this.fragments[fragKey];
if (!fragmentEntity) {
return;
}
Object.keys(timeRanges).forEach(function (elementaryStream) {
var streamInfo = frag.elementaryStreams[elementaryStream];
if (!streamInfo) {
return;
}
var timeRange = timeRanges[elementaryStream];
var partial = part !== null || streamInfo.partial === true;
fragmentEntity.range[elementaryStream] = _this2.getBufferedTimes(frag, part, partial, timeRange);
});
fragmentEntity.backtrack = fragmentEntity.loaded = null;
if (Object.keys(fragmentEntity.range).length) {
fragmentEntity.buffered = true;
} else {
// remove fragment if nothing was appended
this.removeFragment(fragmentEntity.body);
}
};
_proto.getBufferedTimes = function getBufferedTimes(fragment, part, partial, timeRange) {
var buffered = {
time: [],
partial: partial
};
var startPTS = part ? part.start : fragment.start;
var endPTS = part ? part.end : fragment.end;
var minEndPTS = fragment.minEndPTS || endPTS;
var maxStartPTS = fragment.maxStartPTS || startPTS;
for (var i = 0; i < timeRange.length; i++) {
var startTime = timeRange.start(i) - this.bufferPadding;
var endTime = timeRange.end(i) + this.bufferPadding;
if (maxStartPTS >= startTime && minEndPTS <= endTime) {
// Fragment is entirely contained in buffer
// No need to check the other timeRange times since it's completely playable
buffered.time.push({
startPTS: Math.max(startPTS, timeRange.start(i)),
endPTS: Math.min(endPTS, timeRange.end(i))
});
break;
} else if (startPTS < endTime && endPTS > startTime) {
buffered.partial = true; // Check for intersection with buffer
// Get playable sections of the fragment
buffered.time.push({
startPTS: Math.max(startPTS, timeRange.start(i)),
endPTS: Math.min(endPTS, timeRange.end(i))
});
} else if (endPTS <= startTime) {
// No need to check the rest of the timeRange as it is in order
break;
}
}
return buffered;
}
/**
* Gets the partial fragment for a certain time
*/
;
_proto.getPartialFragment = function getPartialFragment(time) {
var bestFragment = null;
var timePadding;
var startTime;
var endTime;
var bestOverlap = 0;
var bufferPadding = this.bufferPadding,
fragments = this.fragments;
Object.keys(fragments).forEach(function (key) {
var fragmentEntity = fragments[key];
if (!fragmentEntity) {
return;
}
if (isPartial(fragmentEntity)) {
startTime = fragmentEntity.body.start - bufferPadding;
endTime = fragmentEntity.body.end + bufferPadding;
if (time >= startTime && time <= endTime) {
// Use the fragment that has the most padding from start and end time
timePadding = Math.min(time - startTime, endTime - time);
if (bestOverlap <= timePadding) {
bestFragment = fragmentEntity.body;
bestOverlap = timePadding;
}
}
}
});
return bestFragment;
};
_proto.getState = function getState(fragment) {
var fragKey = getFragmentKey(fragment);
var fragmentEntity = this.fragments[fragKey];
if (fragmentEntity) {
if (!fragmentEntity.buffered) {
if (fragmentEntity.backtrack) {
return FragmentState.BACKTRACKED;
}
return FragmentState.APPENDING;
} else if (isPartial(fragmentEntity)) {
return FragmentState.PARTIAL;
} else {
return FragmentState.OK;
}
}
return FragmentState.NOT_LOADED;
};
_proto.backtrack = function backtrack(frag, data) {
var fragKey = getFragmentKey(frag);
var fragmentEntity = this.fragments[fragKey];
if (!fragmentEntity || fragmentEntity.backtrack) {
return null;
}
var backtrack = fragmentEntity.backtrack = data ? data : fragmentEntity.loaded;
fragmentEntity.loaded = null;
return backtrack;
};
_proto.getBacktrackData = function getBacktrackData(fragment) {
var fragKey = getFragmentKey(fragment);
var fragmentEntity = this.fragments[fragKey];
if (fragmentEntity) {
var _backtrack$payload;
var backtrack = fragmentEntity.backtrack; // If data was already sent to Worker it is detached no longer available
if (backtrack !== null && backtrack !== void 0 && (_backtrack$payload = backtrack.payload) !== null && _backtrack$payload !== void 0 && _backtrack$payload.byteLength) {
return backtrack;
} else {
this.removeFragment(fragment);
}
}
return null;
};
_proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
var startTime;
var endTime;
for (var i = 0; i < timeRange.length; i++) {
startTime = timeRange.start(i) - this.bufferPadding;
endTime = timeRange.end(i) + this.bufferPadding;
if (startPTS >= startTime && endPTS <= endTime) {
return true;
}
if (endPTS <= startTime) {
// No need to check the rest of the timeRange as it is in order
return false;
}
}
return false;
};
_proto.onFragLoaded = function onFragLoaded(event, data) {
var frag = data.frag,
part = data.part; // don't track initsegment (for which sn is not a number)
// don't track frags used for bitrateTest, they're irrelevant.
// don't track parts for memory efficiency
if (frag.sn === 'initSegment' || frag.bitrateTest || part) {
return;
}
var fragKey = getFragmentKey(frag);
this.fragments[fragKey] = {
body: frag,
loaded: data,
backtrack: null,
buffered: false,
range: Object.create(null)
};
};
_proto.onBufferAppended = function onBufferAppended(event, data) {
var _this3 = this;
var frag = data.frag,
part = data.part,
timeRanges = data.timeRanges;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_1__["PlaylistLevelType"].MAIN) {
this.activeFragment = frag;
if (part) {
var activeParts = this.activeParts;
if (!activeParts) {
this.activeParts = activeParts = [];
}
activeParts.push(part);
} else {
this.activeParts = null;
}
} // Store the latest timeRanges loaded in the buffer
this.timeRanges = timeRanges;
Object.keys(timeRanges).forEach(function (elementaryStream) {
var timeRange = timeRanges[elementaryStream];
_this3.detectEvictedFragments(elementaryStream, timeRange);
if (!part) {
for (var i = 0; i < timeRange.length; i++) {
frag.appendedPTS = Math.max(timeRange.end(i), frag.appendedPTS || 0);
}
}
});
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
this.detectPartialFragments(data);
};
_proto.hasFragment = function hasFragment(fragment) {
var fragKey = getFragmentKey(fragment);
return !!this.fragments[fragKey];
};
_proto.removeFragment = function removeFragment(fragment) {
var fragKey = getFragmentKey(fragment);
fragment.stats.loaded = 0;
fragment.clearElementaryStreamInfo();
delete this.fragments[fragKey];
};
_proto.removeAllFragments = function removeAllFragments() {
this.fragments = Object.create(null);
this.activeFragment = null;
this.activeParts = null;
};
return FragmentTracker;
}();
function isPartial(fragmentEntity) {
var _fragmentEntity$range, _fragmentEntity$range2;
return fragmentEntity.buffered && (((_fragmentEntity$range = fragmentEntity.range.video) === null || _fragmentEntity$range === void 0 ? void 0 : _fragmentEntity$range.partial) || ((_fragmentEntity$range2 = fragmentEntity.range.audio) === null || _fragmentEntity$range2 === void 0 ? void 0 : _fragmentEntity$range2.partial));
}
function getFragmentKey(fragment) {
return fragment.type + "_" + fragment.level + "_" + fragment.urlId + "_" + fragment.sn;
}
/***/ }),
/***/ "./src/controller/gap-controller.ts":
/*!******************************************!*\
!*** ./src/controller/gap-controller.ts ***!
\******************************************/
/*! exports provided: STALL_MINIMUM_DURATION_MS, MAX_START_GAP_JUMP, SKIP_BUFFER_HOLE_STEP_SECONDS, SKIP_BUFFER_RANGE_START, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STALL_MINIMUM_DURATION_MS", function() { return STALL_MINIMUM_DURATION_MS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_START_GAP_JUMP", function() { return MAX_START_GAP_JUMP; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_HOLE_STEP_SECONDS", function() { return SKIP_BUFFER_HOLE_STEP_SECONDS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SKIP_BUFFER_RANGE_START", function() { return SKIP_BUFFER_RANGE_START; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return GapController; });
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var STALL_MINIMUM_DURATION_MS = 250;
var MAX_START_GAP_JUMP = 2.0;
var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
var SKIP_BUFFER_RANGE_START = 0.05;
var GapController = /*#__PURE__*/function () {
function GapController(config, media, fragmentTracker, hls) {
this.config = void 0;
this.media = void 0;
this.fragmentTracker = void 0;
this.hls = void 0;
this.nudgeRetry = 0;
this.stallReported = false;
this.stalled = null;
this.moved = false;
this.seeking = false;
this.config = config;
this.media = media;
this.fragmentTracker = fragmentTracker;
this.hls = hls;
}
var _proto = GapController.prototype;
_proto.destroy = function destroy() {
// @ts-ignore
this.hls = this.fragmentTracker = this.media = null;
}
/**
* Checks if the playhead is stuck within a gap, and if so, attempts to free it.
* A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
*
* @param {number} lastCurrentTime Previously read playhead position
*/
;
_proto.poll = function poll(lastCurrentTime) {
var config = this.config,
media = this.media,
stalled = this.stalled;
var currentTime = media.currentTime,
seeking = media.seeking;
var seeked = this.seeking && !seeking;
var beginSeek = !this.seeking && seeking;
this.seeking = seeking; // The playhead is moving, no-op
if (currentTime !== lastCurrentTime) {
this.moved = true;
if (stalled !== null) {
// The playhead is now moving, but was previously stalled
if (this.stallReported) {
var _stalledDuration = self.performance.now() - stalled;
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms");
this.stallReported = false;
}
this.stalled = null;
this.nudgeRetry = 0;
}
return;
} // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
if (beginSeek || seeked) {
this.stalled = null;
} // The playhead should not be moving
if (media.paused || media.ended || media.playbackRate === 0 || !_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media).length) {
return;
}
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, 0);
var isBuffered = bufferInfo.len > 0;
var nextStart = bufferInfo.nextStart || 0; // There is no playable buffer (seeked, waiting for buffer)
if (!isBuffered && !nextStart) {
return;
}
if (seeking) {
// Waiting for seeking in a buffered range to complete
var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; // Next buffered range is too far ahead to jump to while still seeking
var noBufferGap = !nextStart || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
if (hasEnoughBuffer || noBufferGap) {
return;
} // Reset moved state when seeking to a point in or before a gap
this.moved = false;
} // Skip start gaps if we haven't played, but the last poll detected the start of a stall
// The addition poll gives the browser a chance to jump the gap for us
if (!this.moved && this.stalled !== null) {
var _level$details;
// Jump start gaps within jump threshold
var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime; // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
// a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
// that begins over 1 target duration after the video start position.
var level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;
var isLive = level === null || level === void 0 ? void 0 : (_level$details = level.details) === null || _level$details === void 0 ? void 0 : _level$details.live;
var maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;
if (startJump > 0 && startJump <= maxStartGapJump) {
this._trySkipBufferHole(null);
return;
}
} // Start tracking stall time
var tnow = self.performance.now();
if (stalled === null) {
this.stalled = tnow;
return;
}
var stalledDuration = tnow - stalled;
if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
// Report stalling after trying to fix
this._reportStall(bufferInfo.len);
}
var bufferedWithHoles = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].bufferInfo(media, currentTime, config.maxBufferHole);
this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
}
/**
* Detects and attempts to fix known buffer stalling issues.
* @param bufferInfo - The properties of the current buffer.
* @param stalledDurationMs - The amount of time Hls.js has been stalling for.
* @private
*/
;
_proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) {
var config = this.config,
fragmentTracker = this.fragmentTracker,
media = this.media;
var currentTime = media.currentTime;
var partial = fragmentTracker.getPartialFragment(currentTime);
if (partial) {
// Try to skip over the buffer hole caused by a partial fragment
// This method isn't limited by the size of the gap between buffered ranges
var targetTime = this._trySkipBufferHole(partial); // we return here in this case, meaning
// the branch below only executes when we don't handle a partial fragment
if (targetTime) {
return;
}
} // if we haven't had to skip over a buffer hole of a partial fragment
// we may just have to "nudge" the playlist as the browser decoding/rendering engine
// needs to cross some sort of threshold covering all source-buffers content
// to start playing properly.
if (bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Trying to nudge playhead over buffer-hole'); // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
// We only try to jump the hole if it's under the configured size
// Reset stalled so to rearm watchdog timer
this.stalled = null;
this._tryNudgeBuffer();
}
}
/**
* Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
* @param bufferLen - The playhead distance from the end of the current buffer segment.
* @private
*/
;
_proto._reportStall = function _reportStall(bufferLen) {
var hls = this.hls,
media = this.media,
stallReported = this.stallReported;
if (!stallReported) {
// Report stalled error once
this.stallReported = true;
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Playback stalling at @" + media.currentTime + " due to low buffer (buffer=" + bufferLen + ")");
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR,
fatal: false,
buffer: bufferLen
});
}
}
/**
* Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
* @param partial - The partial fragment found at the current time (where playback is stalling).
* @private
*/
;
_proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
var config = this.config,
hls = this.hls,
media = this.media;
var currentTime = media.currentTime;
var lastEndTime = 0; // Check if currentTime is between unbuffered regions of partial fragments
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_0__["BufferHelper"].getBuffered(media);
for (var i = 0; i < buffered.length; i++) {
var startTime = buffered.start(i);
if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {
var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
this.moved = true;
this.stalled = null;
media.currentTime = targetTime;
if (partial) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_SEEK_OVER_HOLE,
fatal: false,
reason: "fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime,
frag: partial
});
}
return targetTime;
}
lastEndTime = buffered.end(i);
}
return 0;
}
/**
* Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
* @private
*/
;
_proto._tryNudgeBuffer = function _tryNudgeBuffer() {
var config = this.config,
hls = this.hls,
media = this.media;
var currentTime = media.currentTime;
var nudgeRetry = (this.nudgeRetry || 0) + 1;
this.nudgeRetry = nudgeRetry;
if (nudgeRetry < config.nudgeMaxRetry) {
var targetTime = currentTime + nudgeRetry * config.nudgeOffset; // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
media.currentTime = targetTime;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_NUDGE_ON_STALL,
fatal: false
});
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].BUFFER_STALLED_ERROR,
fatal: true
});
}
};
return GapController;
}();
/***/ }),
/***/ "./src/controller/id3-track-controller.ts":
/*!************************************************!*\
!*** ./src/controller/id3-track-controller.ts ***!
\************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
var MIN_CUE_DURATION = 0.25;
var ID3TrackController = /*#__PURE__*/function () {
function ID3TrackController(hls) {
this.hls = void 0;
this.id3Track = null;
this.media = null;
this.hls = hls;
this._registerListeners();
}
var _proto = ID3TrackController.prototype;
_proto.destroy = function destroy() {
this._unregisterListeners();
};
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
} // Add ID3 metatadata text track.
;
_proto.onMediaAttached = function onMediaAttached(event, data) {
this.media = data.media;
};
_proto.onMediaDetaching = function onMediaDetaching() {
if (!this.id3Track) {
return;
}
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["clearCurrentCues"])(this.id3Track);
this.id3Track = null;
this.media = null;
};
_proto.getID3Track = function getID3Track(textTracks) {
if (!this.media) {
return;
}
for (var i = 0; i < textTracks.length; i++) {
var textTrack = textTracks[i];
if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
// send 'addtrack' when reusing the textTrack for metadata,
// same as what we do for captions
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["sendAddTrackEvent"])(textTrack, this.media);
return textTrack;
}
}
return this.media.addTextTrack('metadata', 'id3');
};
_proto.onFragParsingMetadata = function onFragParsingMetadata(event, data) {
if (!this.media) {
return;
}
var fragment = data.frag;
var samples = data.samples; // create track dynamically
if (!this.id3Track) {
this.id3Track = this.getID3Track(this.media.textTracks);
this.id3Track.mode = 'hidden';
} // Attempt to recreate Safari functionality by creating
// WebKitDataCue objects when available and store the decoded
// ID3 data in the value property of the cue
var Cue = self.WebKitDataCue || self.VTTCue || self.TextTrackCue;
for (var i = 0; i < samples.length; i++) {
var frames = _demux_id3__WEBPACK_IMPORTED_MODULE_2__["getID3Frames"](samples[i].data);
if (frames) {
var startTime = samples[i].pts;
var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.end;
var timeDiff = endTime - startTime;
if (timeDiff <= 0) {
endTime = startTime + MIN_CUE_DURATION;
}
for (var j = 0; j < frames.length; j++) {
var frame = frames[j]; // Safari doesn't put the timestamp frame in the TextTrack
if (!_demux_id3__WEBPACK_IMPORTED_MODULE_2__["isTimeStampFrame"](frame)) {
var cue = new Cue(startTime, endTime, '');
cue.value = frame;
this.id3Track.addCue(cue);
}
}
}
}
};
_proto.onBufferFlushing = function onBufferFlushing(event, _ref) {
var startOffset = _ref.startOffset,
endOffset = _ref.endOffset,
type = _ref.type;
if (!type || type === 'audio') {
// id3 cues come from parsed audio only remove cues when audio buffer is cleared
var id3Track = this.id3Track;
if (id3Track) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["removeCuesInRange"])(id3Track, startOffset, endOffset);
}
}
};
return ID3TrackController;
}();
/* harmony default export */ __webpack_exports__["default"] = (ID3TrackController);
/***/ }),
/***/ "./src/controller/latency-controller.ts":
/*!**********************************************!*\
!*** ./src/controller/latency-controller.ts ***!
\**********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LatencyController; });
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var LatencyController = /*#__PURE__*/function () {
function LatencyController(hls) {
var _this = this;
this.hls = void 0;
this.config = void 0;
this.media = null;
this.levelDetails = null;
this.currentTime = 0;
this.stallCount = 0;
this._latency = null;
this.timeupdateHandler = function () {
return _this.timeupdate();
};
this.hls = hls;
this.config = hls.config;
this.registerListeners();
}
var _proto = LatencyController.prototype;
_proto.destroy = function destroy() {
this.unregisterListeners();
this.onMediaDetaching();
this.levelDetails = null; // @ts-ignore
this.hls = this.timeupdateHandler = null;
};
_proto.registerListeners = function registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated, this);
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHED, this.onMediaAttached);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_UPDATED, this.onLevelUpdated);
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError);
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
this.media = data.media;
this.media.addEventListener('timeupdate', this.timeupdateHandler);
};
_proto.onMediaDetaching = function onMediaDetaching() {
if (this.media) {
this.media.removeEventListener('timeupdate', this.timeupdateHandler);
this.media = null;
}
};
_proto.onManifestLoading = function onManifestLoading() {
this.levelDetails = null;
this._latency = null;
this.stallCount = 0;
};
_proto.onLevelUpdated = function onLevelUpdated(event, _ref) {
var details = _ref.details;
this.levelDetails = details;
if (details.advanced) {
this.timeupdate();
}
if (!details.live && this.media) {
this.media.removeEventListener('timeupdate', this.timeupdateHandler);
}
};
_proto.onError = function onError(event, data) {
if (data.details !== _errors__WEBPACK_IMPORTED_MODULE_0__["ErrorDetails"].BUFFER_STALLED_ERROR) {
return;
}
this.stallCount++;
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('[playback-rate-controller]: Stall detected, adjusting target latency');
};
_proto.timeupdate = function timeupdate() {
var media = this.media,
levelDetails = this.levelDetails;
if (!media || !levelDetails) {
return;
}
this.currentTime = media.currentTime;
var latency = this.computeLatency();
if (latency === null) {
return;
}
this._latency = latency; // Adapt playbackRate to meet target latency in low-latency mode
var _this$config = this.config,
lowLatencyMode = _this$config.lowLatencyMode,
maxLiveSyncPlaybackRate = _this$config.maxLiveSyncPlaybackRate;
if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1) {
return;
}
var targetLatency = this.targetLatency;
if (targetLatency === null) {
return;
}
var distanceFromTarget = latency - targetLatency; // Only adjust playbackRate when within one target duration of targetLatency
// and more than one second from under-buffering.
// Playback further than one target duration from target can be considered DVR playback.
var liveMinLatencyDuration = Math.min(this.maxLatency, targetLatency + levelDetails.targetduration);
var inLiveRange = distanceFromTarget < liveMinLatencyDuration;
if (levelDetails.live && inLiveRange && distanceFromTarget > 0.05 && this.forwardBufferLength > 1) {
var max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));
var rate = Math.round(2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled)) * 20) / 20;
media.playbackRate = Math.min(max, Math.max(1, rate));
} else if (media.playbackRate !== 1 && media.playbackRate !== 0) {
media.playbackRate = 1;
}
};
_proto.estimateLiveEdge = function estimateLiveEdge() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return null;
}
return levelDetails.edge + levelDetails.age;
};
_proto.computeLatency = function computeLatency() {
var liveEdge = this.estimateLiveEdge();
if (liveEdge === null) {
return null;
}
return liveEdge - this.currentTime;
};
_createClass(LatencyController, [{
key: "latency",
get: function get() {
return this._latency || 0;
}
}, {
key: "maxLatency",
get: function get() {
var config = this.config,
levelDetails = this.levelDetails;
if (config.liveMaxLatencyDuration !== undefined) {
return config.liveMaxLatencyDuration;
}
return levelDetails ? config.liveMaxLatencyDurationCount * levelDetails.targetduration : 0;
}
}, {
key: "targetLatency",
get: function get() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return null;
}
var holdBack = levelDetails.holdBack,
partHoldBack = levelDetails.partHoldBack,
targetduration = levelDetails.targetduration;
var _this$config2 = this.config,
liveSyncDuration = _this$config2.liveSyncDuration,
liveSyncDurationCount = _this$config2.liveSyncDurationCount,
lowLatencyMode = _this$config2.lowLatencyMode;
var userConfig = this.hls.userConfig;
var targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;
if (userConfig.liveSyncDuration || userConfig.liveSyncDurationCount || targetLatency === 0) {
targetLatency = liveSyncDuration !== undefined ? liveSyncDuration : liveSyncDurationCount * targetduration;
}
var maxLiveSyncOnStallIncrease = targetduration;
var liveSyncOnStallIncrease = 1.0;
return targetLatency + Math.min(this.stallCount * liveSyncOnStallIncrease, maxLiveSyncOnStallIncrease);
}
}, {
key: "liveSyncPosition",
get: function get() {
var liveEdge = this.estimateLiveEdge();
var targetLatency = this.targetLatency;
var levelDetails = this.levelDetails;
if (liveEdge === null || targetLatency === null || levelDetails === null) {
return null;
}
var edge = levelDetails.edge;
var syncPosition = liveEdge - targetLatency - this.edgeStalled;
var min = edge - levelDetails.totalduration;
var max = edge - (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration);
return Math.min(Math.max(min, syncPosition), max);
}
}, {
key: "drift",
get: function get() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return 1;
}
return levelDetails.drift;
}
}, {
key: "edgeStalled",
get: function get() {
var levelDetails = this.levelDetails;
if (levelDetails === null) {
return 0;
}
var maxLevelUpdateAge = (this.config.lowLatencyMode && levelDetails.partTarget || levelDetails.targetduration) * 3;
return Math.max(levelDetails.age - maxLevelUpdateAge, 0);
}
}, {
key: "forwardBufferLength",
get: function get() {
var media = this.media,
levelDetails = this.levelDetails;
if (!media || !levelDetails) {
return 0;
}
var bufferedRanges = media.buffered.length;
return bufferedRanges ? media.buffered.end(bufferedRanges - 1) : levelDetails.edge - this.currentTime;
}
}]);
return LatencyController;
}();
/***/ }),
/***/ "./src/controller/level-controller.ts":
/*!********************************************!*\
!*** ./src/controller/level-controller.ts ***!
\********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LevelController; });
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts");
/* harmony import */ var _level_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.ts");
/* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/*
* Level Controller
*/
var chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
var LevelController = /*#__PURE__*/function (_BasePlaylistControll) {
_inheritsLoose(LevelController, _BasePlaylistControll);
function LevelController(hls) {
var _this;
_this = _BasePlaylistControll.call(this, hls, '[level-controller]') || this;
_this._levels = [];
_this._firstLevel = -1;
_this._startLevel = void 0;
_this.currentLevelIndex = -1;
_this.manualLevelIndex = -1;
_this.onParsedComplete = void 0;
_this._registerListeners();
return _this;
}
var _proto = LevelController.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, this.onError, this);
};
_proto.destroy = function destroy() {
this._unregisterListeners();
this.manualLevelIndex = -1;
this._levels.length = 0;
_BasePlaylistControll.prototype.destroy.call(this);
};
_proto.startLoad = function startLoad() {
var levels = this._levels; // clean up live level details to force reload them, and reset load errors
levels.forEach(function (level) {
level.loadError = 0;
});
_BasePlaylistControll.prototype.startLoad.call(this);
};
_proto.onManifestLoaded = function onManifestLoaded(event, data) {
var levels = [];
var audioTracks = [];
var subtitleTracks = [];
var bitrateStart;
var levelSet = {};
var levelFromSet;
var resolutionFound = false;
var videoCodecFound = false;
var audioCodecFound = false; // regroup redundant levels together
data.levels.forEach(function (levelParsed) {
var attributes = levelParsed.attrs;
resolutionFound = resolutionFound || !!(levelParsed.width && levelParsed.height);
videoCodecFound = videoCodecFound || !!levelParsed.videoCodec;
audioCodecFound = audioCodecFound || !!levelParsed.audioCodec; // erase audio codec info if browser does not support mp4a.40.34.
// demuxer will autodetect codec and fallback to mpeg/audio
if (chromeOrFirefox && levelParsed.audioCodec && levelParsed.audioCodec.indexOf('mp4a.40.34') !== -1) {
levelParsed.audioCodec = undefined;
}
levelFromSet = levelSet[levelParsed.bitrate]; // FIXME: we would also have to match the resolution here
if (!levelFromSet) {
levelFromSet = new _types_level__WEBPACK_IMPORTED_MODULE_0__["Level"](levelParsed);
levelSet[levelParsed.bitrate] = levelFromSet;
levels.push(levelFromSet);
} else {
levelFromSet.url.push(levelParsed.url);
}
if (attributes) {
if (attributes.AUDIO) {
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'audio', attributes.AUDIO);
}
if (attributes.SUBTITLES) {
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["addGroupId"])(levelFromSet, 'text', attributes.SUBTITLES);
}
}
}); // remove audio-only level if we also have levels with video codecs or RESOLUTION signalled
if ((resolutionFound || videoCodecFound) && audioCodecFound) {
levels = levels.filter(function (_ref) {
var videoCodec = _ref.videoCodec,
width = _ref.width,
height = _ref.height;
return !!videoCodec || !!(width && height);
});
} // only keep levels with supported audio/video codecs
levels = levels.filter(function (_ref2) {
var audioCodec = _ref2.audioCodec,
videoCodec = _ref2.videoCodec;
return (!audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(audioCodec, 'audio')) && (!videoCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(videoCodec, 'video'));
});
if (data.audioTracks) {
audioTracks = data.audioTracks.filter(function (track) {
return !track.audioCodec || Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_3__["isCodecSupportedInMp4"])(track.audioCodec, 'audio');
}); // Assign ids after filtering as array indices by group-id
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(audioTracks);
}
if (data.subtitles) {
subtitleTracks = data.subtitles;
Object(_level_helper__WEBPACK_IMPORTED_MODULE_4__["assignTrackIdsByGroup"])(subtitleTracks);
}
if (levels.length > 0) {
// start bitrate is the first bitrate of the manifest
bitrateStart = levels[0].bitrate; // sort level on bitrate
levels.sort(function (a, b) {
return a.bitrate - b.bitrate;
});
this._levels = levels; // find index of first level in sorted levels
for (var i = 0; i < levels.length; i++) {
if (levels[i].bitrate === bitrateStart) {
this._firstLevel = i;
this.log("manifest loaded, " + levels.length + " level(s) found, first bitrate: " + bitrateStart);
break;
}
} // Audio is only alternate if manifest include a URI along with the audio group tag,
// and this is not an audio-only stream where levels contain audio-only
var audioOnly = audioCodecFound && !videoCodecFound;
var edata = {
levels: levels,
audioTracks: audioTracks,
subtitleTracks: subtitleTracks,
firstLevel: this._firstLevel,
stats: data.stats,
audio: audioCodecFound,
video: videoCodecFound,
altAudio: !audioOnly && audioTracks.some(function (t) {
return !!t.url;
})
};
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_PARSED, edata); // Initiate loading after all controllers have received MANIFEST_PARSED
if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {
this.hls.startLoad(this.hls.config.startPosition);
}
} else {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_INCOMPATIBLE_CODECS_ERROR,
fatal: true,
url: data.url,
reason: 'no level with compatible codecs found in manifest'
});
}
};
_proto.onError = function onError(event, data) {
_BasePlaylistControll.prototype.onError.call(this, event, data);
if (data.fatal) {
return;
} // Switch to redundant level when track fails to load
var context = data.context;
var level = this._levels[this.currentLevelIndex];
if (context && (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && level.audioGroupIds && context.groupId === level.audioGroupIds[level.urlId] || context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && level.textGroupIds && context.groupId === level.textGroupIds[level.urlId])) {
this.redundantFailover(this.currentLevelIndex);
return;
}
var levelError = false;
var levelSwitch = true;
var levelIndex; // try to recover not fatal errors
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].KEY_LOAD_TIMEOUT:
if (data.frag) {
var _level = this._levels[data.frag.level]; // Set levelIndex when we're out of fragment retries
if (_level) {
_level.fragmentError++;
if (_level.fragmentError > this.hls.config.fragLoadingMaxRetry) {
levelIndex = data.frag.level;
}
} else {
levelIndex = data.frag.level;
}
}
break;
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
// Do not perform level switch if an error occurred using delivery directives
// Attempt to reload level without directives first
if (context) {
if (context.deliveryDirectives) {
levelSwitch = false;
}
levelIndex = context.level;
}
levelError = true;
break;
case _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].REMUX_ALLOC_ERROR:
levelIndex = data.level;
levelError = true;
break;
}
if (levelIndex !== undefined) {
this.recoverLevel(data, levelIndex, levelError, levelSwitch);
}
}
/**
* Switch to a redundant stream if any available.
* If redundant stream is not available, emergency switch down if ABR mode is enabled.
*/
;
_proto.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, levelSwitch) {
var errorDetails = errorEvent.details;
var level = this._levels[levelIndex];
level.loadError++;
if (levelError) {
var retrying = this.retryLoadingOrFail(errorEvent);
if (retrying) {
// boolean used to inform stream controller not to switch back to IDLE on non fatal error
errorEvent.levelRetry = true;
} else {
this.currentLevelIndex = -1;
return;
}
}
if (levelSwitch) {
var redundantLevels = level.url.length; // Try redundant fail-over until level.loadError reaches redundantLevels
if (redundantLevels > 1 && level.loadError < redundantLevels) {
errorEvent.levelRetry = true;
this.redundantFailover(levelIndex);
} else if (this.manualLevelIndex === -1) {
// Search for available level in auto level selection mode, cycling from highest to lowest bitrate
var nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
if (this.currentLevelIndex !== nextLevel && this._levels[nextLevel].loadError === 0) {
this.warn(errorDetails + ": switch to " + nextLevel);
errorEvent.levelRetry = true;
this.hls.nextAutoLevel = nextLevel;
}
}
}
};
_proto.redundantFailover = function redundantFailover(levelIndex) {
var level = this._levels[levelIndex];
var redundantLevels = level.url.length;
if (redundantLevels > 1) {
// Update the url id of all levels so that we stay on the same set of variants when level switching
var newUrlId = (level.urlId + 1) % redundantLevels;
this.warn("Switching to redundant URL-id " + newUrlId);
this._levels.forEach(function (level) {
level.urlId = newUrlId;
});
this.level = levelIndex;
}
} // reset errors on the successful load of a fragment
;
_proto.onFragLoaded = function onFragLoaded(event, _ref3) {
var frag = _ref3.frag;
if (frag !== undefined && frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) {
var level = this._levels[frag.level];
if (level !== undefined) {
level.fragmentError = 0;
level.loadError = 0;
}
}
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
var _data$deliveryDirecti2;
var level = data.level,
details = data.details;
var curLevel = this._levels[level];
if (!curLevel) {
var _data$deliveryDirecti;
this.warn("Invalid level index " + level);
if ((_data$deliveryDirecti = data.deliveryDirectives) !== null && _data$deliveryDirecti !== void 0 && _data$deliveryDirecti.skip) {
details.deltaUpdateFailed = true;
}
return;
} // only process level loaded events matching with expected level
if (level === this.currentLevelIndex) {
// reset level load error counter on successful level loaded only if there is no issues with fragments
if (curLevel.fragmentError === 0) {
curLevel.loadError = 0;
this.retryCount = 0;
}
this.playlistLoaded(level, data, curLevel.details);
} else if ((_data$deliveryDirecti2 = data.deliveryDirectives) !== null && _data$deliveryDirecti2 !== void 0 && _data$deliveryDirecti2.skip) {
// received a delta playlist update that cannot be merged
details.deltaUpdateFailed = true;
}
};
_proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
var currentLevel = this.hls.levels[this.currentLevelIndex];
if (!currentLevel) {
return;
}
if (currentLevel.audioGroupIds) {
var urlId = -1;
var audioGroupId = this.hls.audioTracks[data.id].groupId;
for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
if (currentLevel.audioGroupIds[i] === audioGroupId) {
urlId = i;
break;
}
}
if (urlId !== currentLevel.urlId) {
currentLevel.urlId = urlId;
this.startLoad();
}
}
};
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
var level = this.currentLevelIndex;
var currentLevel = this._levels[level];
if (this.canLoad && currentLevel && currentLevel.url.length > 0) {
var id = currentLevel.urlId;
var url = currentLevel.url[id];
if (hlsUrlParameters) {
try {
url = hlsUrlParameters.addDirectives(url);
} catch (error) {
this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
}
}
this.log("Attempt loading level index " + level + (hlsUrlParameters ? ' at sn ' + hlsUrlParameters.msn + ' part ' + hlsUrlParameters.part : '') + " with URL-id " + id + " " + url); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
// console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
this.clearTimer();
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, {
url: url,
level: level,
id: id,
deliveryDirectives: hlsUrlParameters || null
});
}
};
_proto.removeLevel = function removeLevel(levelIndex, urlId) {
var filterLevelAndGroupByIdIndex = function filterLevelAndGroupByIdIndex(url, id) {
return id !== urlId;
};
var levels = this._levels.filter(function (level, index) {
if (index !== levelIndex) {
return true;
}
if (level.url.length > 1 && urlId !== undefined) {
level.url = level.url.filter(filterLevelAndGroupByIdIndex);
if (level.audioGroupIds) {
level.audioGroupIds = level.audioGroupIds.filter(filterLevelAndGroupByIdIndex);
}
if (level.textGroupIds) {
level.textGroupIds = level.textGroupIds.filter(filterLevelAndGroupByIdIndex);
}
level.urlId = 0;
return true;
}
return false;
}).map(function (level, index) {
var details = level.details;
if (details !== null && details !== void 0 && details.fragments) {
details.fragments.forEach(function (fragment) {
fragment.level = index;
});
}
return level;
});
this._levels = levels;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVELS_UPDATED, {
levels: levels
});
};
_createClass(LevelController, [{
key: "levels",
get: function get() {
if (this._levels.length === 0) {
return null;
}
return this._levels;
}
}, {
key: "level",
get: function get() {
return this.currentLevelIndex;
},
set: function set(newLevel) {
var _levels$newLevel;
var levels = this._levels;
if (levels.length === 0) {
return;
}
if (this.currentLevelIndex === newLevel && (_levels$newLevel = levels[newLevel]) !== null && _levels$newLevel !== void 0 && _levels$newLevel.details) {
return;
} // check if level idx is valid
if (newLevel < 0 || newLevel >= levels.length) {
// invalid level id given, trigger error
var fatal = newLevel < 0;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].OTHER_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_SWITCH_ERROR,
level: newLevel,
fatal: fatal,
reason: 'invalid level idx'
});
if (fatal) {
return;
}
newLevel = Math.min(newLevel, levels.length - 1);
} // stopping live reloading timer if any
this.clearTimer();
var lastLevelIndex = this.currentLevelIndex;
var lastLevel = levels[lastLevelIndex];
var level = levels[newLevel];
this.log("switching to level " + newLevel + " from " + lastLevelIndex);
this.currentLevelIndex = newLevel;
var levelSwitchingData = _extends({}, level, {
level: newLevel,
maxBitrate: level.maxBitrate,
uri: level.uri,
urlId: level.urlId
}); // @ts-ignore
delete levelSwitchingData._urlId;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_SWITCHING, levelSwitchingData); // check if we need to load playlist for this level
var levelDetails = level.details;
if (!levelDetails || levelDetails.live) {
// level not retrieved yet, or live playlist we need to (re)load it
var hlsUrlParameters = this.switchParams(level.uri, lastLevel === null || lastLevel === void 0 ? void 0 : lastLevel.details);
this.loadPlaylist(hlsUrlParameters);
}
}
}, {
key: "manualLevel",
get: function get() {
return this.manualLevelIndex;
},
set: function set(newLevel) {
this.manualLevelIndex = newLevel;
if (this._startLevel === undefined) {
this._startLevel = newLevel;
}
if (newLevel !== -1) {
this.level = newLevel;
}
}
}, {
key: "firstLevel",
get: function get() {
return this._firstLevel;
},
set: function set(newLevel) {
this._firstLevel = newLevel;
}
}, {
key: "startLevel",
get: function get() {
// hls.startLevel takes precedence over config.startLevel
// if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
if (this._startLevel === undefined) {
var configStartLevel = this.hls.config.startLevel;
if (configStartLevel !== undefined) {
return configStartLevel;
} else {
return this._firstLevel;
}
} else {
return this._startLevel;
}
},
set: function set(newLevel) {
this._startLevel = newLevel;
}
}, {
key: "nextLoadLevel",
get: function get() {
if (this.manualLevelIndex !== -1) {
return this.manualLevelIndex;
} else {
return this.hls.nextAutoLevel;
}
},
set: function set(nextLevel) {
this.level = nextLevel;
if (this.manualLevelIndex === -1) {
this.hls.nextAutoLevel = nextLevel;
}
}
}]);
return LevelController;
}(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_5__["default"]);
/***/ }),
/***/ "./src/controller/level-helper.ts":
/*!****************************************!*\
!*** ./src/controller/level-helper.ts ***!
\****************************************/
/*! exports provided: addGroupId, assignTrackIdsByGroup, updatePTS, updateFragPTSDTS, mergeDetails, mapPartIntersection, mapFragmentIntersection, adjustSliding, computeReloadInterval, getFragmentWithSN, getPartWith */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addGroupId", function() { return addGroupId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "assignTrackIdsByGroup", function() { return assignTrackIdsByGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updatePTS", function() { return updatePTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateFragPTSDTS", function() { return updateFragPTSDTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeDetails", function() { return mergeDetails; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapPartIntersection", function() { return mapPartIntersection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapFragmentIntersection", function() { return mapFragmentIntersection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSliding", function() { return adjustSliding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeReloadInterval", function() { return computeReloadInterval; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFragmentWithSN", function() { return getFragmentWithSN; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPartWith", function() { return getPartWith; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
* @module LevelHelper
* Providing methods dealing with playlist sliding and drift
* */
function addGroupId(level, type, id) {
switch (type) {
case 'audio':
if (!level.audioGroupIds) {
level.audioGroupIds = [];
}
level.audioGroupIds.push(id);
break;
case 'text':
if (!level.textGroupIds) {
level.textGroupIds = [];
}
level.textGroupIds.push(id);
break;
}
}
function assignTrackIdsByGroup(tracks) {
var groups = {};
tracks.forEach(function (track) {
var groupId = track.groupId || '';
track.id = groups[groupId] = groups[groupId] || 0;
groups[groupId]++;
});
}
function updatePTS(fragments, fromIdx, toIdx) {
var fragFrom = fragments[fromIdx];
var fragTo = fragments[toIdx];
updateFromToPTS(fragFrom, fragTo);
}
function updateFromToPTS(fragFrom, fragTo) {
var fragToPTS = fragTo.startPTS; // if we know startPTS[toIdx]
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragToPTS)) {
// update fragment duration.
// it helps to fix drifts between playlist reported duration and fragment real duration
var duration = 0;
var frag;
if (fragTo.sn > fragFrom.sn) {
duration = fragToPTS - fragFrom.start;
frag = fragFrom;
} else {
duration = fragFrom.start - fragToPTS;
frag = fragTo;
} // TODO? Drift can go either way, or the playlist could be completely accurate
// console.assert(duration > 0,
// `duration of ${duration} computed for frag ${frag.sn}, level ${frag.level}, there should be some duration drift between playlist and fragment!`);
if (frag.duration !== duration) {
frag.duration = duration;
} // we dont know startPTS[toIdx]
} else if (fragTo.sn > fragFrom.sn) {
var contiguous = fragFrom.cc === fragTo.cc; // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS
if (contiguous && fragFrom.minEndPTS) {
fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);
} else {
fragTo.start = fragFrom.start + fragFrom.duration;
}
} else {
fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
}
}
function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
var parsedMediaDuration = endPTS - startPTS;
if (parsedMediaDuration <= 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('Fragment should have a positive duration', frag);
endPTS = startPTS + frag.duration;
endDTS = startDTS + frag.duration;
}
var maxStartPTS = startPTS;
var minEndPTS = endPTS;
var fragStartPts = frag.startPTS;
var fragEndPts = frag.endPTS;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(fragStartPts)) {
// delta PTS between audio and video
var deltaPTS = Math.abs(fragStartPts - startPTS);
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.deltaPTS)) {
frag.deltaPTS = deltaPTS;
} else {
frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
}
maxStartPTS = Math.max(startPTS, fragStartPts);
startPTS = Math.min(startPTS, fragStartPts);
startDTS = Math.min(startDTS, frag.startDTS);
minEndPTS = Math.min(endPTS, fragEndPts);
endPTS = Math.max(endPTS, fragEndPts);
endDTS = Math.max(endDTS, frag.endDTS);
}
frag.duration = endPTS - startPTS;
var drift = startPTS - frag.start;
frag.appendedPTS = endPTS;
frag.start = frag.startPTS = startPTS;
frag.maxStartPTS = maxStartPTS;
frag.startDTS = startDTS;
frag.endPTS = endPTS;
frag.minEndPTS = minEndPTS;
frag.endDTS = endDTS;
var sn = frag.sn; // 'initSegment'
// exit if sn out of range
if (!details || sn < details.startSN || sn > details.endSN) {
return 0;
}
var i;
var fragIdx = sn - details.startSN;
var fragments = details.fragments; // update frag reference in fragments array
// rationale is that fragments array might not contain this frag object.
// this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
// if we don't update frag, we won't be able to propagate PTS info on the playlist
// resulting in invalid sliding computation
fragments[fragIdx] = frag; // adjust fragment PTS/duration from seqnum-1 to frag 0
for (i = fragIdx; i > 0; i--) {
updateFromToPTS(fragments[i], fragments[i - 1]);
} // adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1; i++) {
updateFromToPTS(fragments[i], fragments[i + 1]);
}
if (details.fragmentHint) {
updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);
}
details.PTSKnown = details.alignedSliding = true;
return drift;
}
function mergeDetails(oldDetails, newDetails) {
// potentially retrieve cached initsegment
if (newDetails.initSegment && oldDetails.initSegment) {
newDetails.initSegment = oldDetails.initSegment;
}
if (oldDetails.fragmentHint) {
// prevent PTS and duration from being adjusted on the next hint
delete oldDetails.fragmentHint.endPTS;
} // check if old/new playlists have fragments in common
// loop through overlapping SN and update startPTS , cc, and duration if any found
var ccOffset = 0;
var PTSFrag;
mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
if (oldFrag.relurl) {
// Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.
// It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end
// of the playlist.
ccOffset = oldFrag.cc - newFrag.cc;
}
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.startPTS) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(oldFrag.endPTS)) {
newFrag.start = newFrag.startPTS = oldFrag.startPTS;
newFrag.startDTS = oldFrag.startDTS;
newFrag.appendedPTS = oldFrag.appendedPTS;
newFrag.maxStartPTS = oldFrag.maxStartPTS;
newFrag.endPTS = oldFrag.endPTS;
newFrag.endDTS = oldFrag.endDTS;
newFrag.minEndPTS = oldFrag.minEndPTS;
newFrag.duration = oldFrag.endPTS - oldFrag.startPTS;
if (newFrag.duration) {
PTSFrag = newFrag;
} // PTS is known when any segment has startPTS and endPTS
newDetails.PTSKnown = newDetails.alignedSliding = true;
}
newFrag.elementaryStreams = oldFrag.elementaryStreams;
newFrag.loader = oldFrag.loader;
newFrag.stats = oldFrag.stats;
newFrag.urlId = oldFrag.urlId;
});
if (newDetails.skippedSegments) {
newDetails.deltaUpdateFailed = newDetails.fragments.some(function (frag) {
return !frag;
});
if (newDetails.deltaUpdateFailed) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('[level-helper] Previous playlist missing segments skipped in delta playlist');
for (var i = newDetails.skippedSegments; i--;) {
newDetails.fragments.shift();
}
newDetails.startSN = newDetails.fragments[0].sn;
newDetails.startCC = newDetails.fragments[0].cc;
}
}
var newFragments = newDetails.fragments;
if (ccOffset) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].warn('discontinuity sliding from playlist, take drift into account');
for (var _i = 0; _i < newFragments.length; _i++) {
newFragments[_i].cc += ccOffset;
}
}
if (newDetails.skippedSegments) {
if (!newDetails.initSegment) {
newDetails.initSegment = oldDetails.initSegment;
}
newDetails.startCC = newDetails.fragments[0].cc;
} // Merge parts
mapPartIntersection(oldDetails.partList, newDetails.partList, function (oldPart, newPart) {
newPart.elementaryStreams = oldPart.elementaryStreams;
newPart.stats = oldPart.stats;
}); // if at least one fragment contains PTS info, recompute PTS information for all fragments
if (PTSFrag) {
updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
} else {
// ensure that delta is within oldFragments range
// also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
// in that case we also need to adjust start offset of all fragments
adjustSliding(oldDetails, newDetails);
}
if (newFragments.length) {
newDetails.totalduration = newDetails.edge - newFragments[0].start;
}
newDetails.driftStartTime = oldDetails.driftStartTime;
newDetails.driftStart = oldDetails.driftStart;
var advancedDateTime = newDetails.advancedDateTime;
if (newDetails.advanced && advancedDateTime) {
var edge = newDetails.edge;
if (!newDetails.driftStart) {
newDetails.driftStartTime = advancedDateTime;
newDetails.driftStart = edge;
}
newDetails.driftEndTime = advancedDateTime;
newDetails.driftEnd = edge;
} else {
newDetails.driftEndTime = oldDetails.driftEndTime;
newDetails.driftEnd = oldDetails.driftEnd;
newDetails.advancedDateTime = oldDetails.advancedDateTime;
}
}
function mapPartIntersection(oldParts, newParts, intersectionFn) {
if (oldParts && newParts) {
var delta = 0;
for (var i = 0, len = oldParts.length; i <= len; i++) {
var _oldPart = oldParts[i];
var _newPart = newParts[i + delta];
if (_oldPart && _newPart && _oldPart.index === _newPart.index && _oldPart.fragment.sn === _newPart.fragment.sn) {
intersectionFn(_oldPart, _newPart);
} else {
delta--;
}
}
}
}
function mapFragmentIntersection(oldDetails, newDetails, intersectionFn) {
var skippedSegments = newDetails.skippedSegments;
var start = Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;
var end = (oldDetails.fragmentHint ? 1 : 0) + (skippedSegments ? newDetails.endSN : Math.min(oldDetails.endSN, newDetails.endSN)) - newDetails.startSN;
var delta = newDetails.startSN - oldDetails.startSN;
var newFrags = newDetails.fragmentHint ? newDetails.fragments.concat(newDetails.fragmentHint) : newDetails.fragments;
var oldFrags = oldDetails.fragmentHint ? oldDetails.fragments.concat(oldDetails.fragmentHint) : oldDetails.fragments;
for (var i = start; i <= end; i++) {
var _oldFrag = oldFrags[delta + i];
var _newFrag = newFrags[i];
if (skippedSegments && !_newFrag && i < skippedSegments) {
// Fill in skipped segments in delta playlist
_newFrag = newDetails.fragments[i] = _oldFrag;
}
if (_oldFrag && _newFrag) {
intersectionFn(_oldFrag, _newFrag);
}
}
}
function adjustSliding(oldDetails, newDetails) {
var delta = newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;
var oldFragments = oldDetails.fragments;
var newFragments = newDetails.fragments;
if (delta < 0 || delta >= oldFragments.length) {
return;
}
var playlistStartOffset = oldFragments[delta].start;
if (playlistStartOffset) {
for (var i = newDetails.skippedSegments; i < newFragments.length; i++) {
newFragments[i].start += playlistStartOffset;
}
if (newDetails.fragmentHint) {
newDetails.fragmentHint.start += playlistStartOffset;
}
}
}
function computeReloadInterval(newDetails, stats) {
var reloadInterval = 1000 * newDetails.levelTargetDuration;
var reloadIntervalAfterMiss = reloadInterval / 2;
var timeSinceLastModified = newDetails.age;
var useLastModified = timeSinceLastModified > 0 && timeSinceLastModified < reloadInterval * 3;
var roundTrip = stats.loading.end - stats.loading.start;
var estimatedTimeUntilUpdate;
var availabilityDelay = newDetails.availabilityDelay; // let estimate = 'average';
if (newDetails.updated === false) {
if (useLastModified) {
// estimate = 'miss round trip';
// We should have had a hit so try again in the time it takes to get a response,
// but no less than 1/3 second.
var minRetry = 333 * newDetails.misses;
estimatedTimeUntilUpdate = Math.max(Math.min(reloadIntervalAfterMiss, roundTrip * 2), minRetry);
newDetails.availabilityDelay = (newDetails.availabilityDelay || 0) + estimatedTimeUntilUpdate;
} else {
// estimate = 'miss half average';
// follow HLS Spec, If the client reloads a Playlist file and finds that it has not
// changed then it MUST wait for a period of one-half the target
// duration before retrying.
estimatedTimeUntilUpdate = reloadIntervalAfterMiss;
}
} else if (useLastModified) {
// estimate = 'next modified date';
// Get the closest we've been to timeSinceLastModified on update
availabilityDelay = Math.min(availabilityDelay || reloadInterval / 2, timeSinceLastModified);
newDetails.availabilityDelay = availabilityDelay;
estimatedTimeUntilUpdate = availabilityDelay + reloadInterval - timeSinceLastModified;
} else {
estimatedTimeUntilUpdate = reloadInterval - roundTrip;
} // console.log(`[computeReloadInterval] live reload ${newDetails.updated ? 'REFRESHED' : 'MISSED'}`,
// '\n method', estimate,
// '\n estimated time until update =>', estimatedTimeUntilUpdate,
// '\n average target duration', reloadInterval,
// '\n time since modified', timeSinceLastModified,
// '\n time round trip', roundTrip,
// '\n availability delay', availabilityDelay);
return Math.round(estimatedTimeUntilUpdate);
}
function getFragmentWithSN(level, sn) {
if (!level || !level.details) {
return null;
}
var levelDetails = level.details;
var fragment = levelDetails.fragments[sn - levelDetails.startSN];
if (fragment) {
return fragment;
}
fragment = levelDetails.fragmentHint;
if (fragment && fragment.sn === sn) {
return fragment;
}
return null;
}
function getPartWith(level, sn, partIndex) {
if (!level || !level.details) {
return null;
}
var partList = level.details.partList;
if (partList) {
for (var i = partList.length; i--;) {
var part = partList[i];
if (part.index === partIndex && part.fragment.sn === sn) {
return part;
}
}
}
return null;
}
/***/ }),
/***/ "./src/controller/stream-controller.ts":
/*!*********************************************!*\
!*** ./src/controller/stream-controller.ts ***!
\*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StreamController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
/* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../is-supported */ "./src/is-supported.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../demux/transmuxer-interface */ "./src/demux/transmuxer-interface.ts");
/* harmony import */ var _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../types/transmuxer */ "./src/types/transmuxer.ts");
/* harmony import */ var _gap_controller__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./gap-controller */ "./src/controller/gap-controller.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var TICK_INTERVAL = 100; // how often to tick in ms
var StreamController = /*#__PURE__*/function (_BaseStreamController) {
_inheritsLoose(StreamController, _BaseStreamController);
function StreamController(hls, fragmentTracker) {
var _this;
_this = _BaseStreamController.call(this, hls, fragmentTracker, '[stream-controller]') || this;
_this.audioCodecSwap = false;
_this.gapController = null;
_this.level = -1;
_this._forceStartLoad = false;
_this.altAudio = false;
_this.audioOnly = false;
_this.fragPlaying = null;
_this.onvplaying = null;
_this.onvseeked = null;
_this.fragLastKbps = 0;
_this.stalled = false;
_this.audioCodecSwitch = false;
_this.videoBuffer = null;
_this._registerListeners();
return _this;
}
var _proto = StreamController.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_LOADED, this.onLevelLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOAD_EMERGENCY_ABORTED, this.onFragLoadEmergencyAborted, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, this.onError, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CREATED, this.onBufferCreated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHED, this.onBufferFlushed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVELS_UPDATED, this.onLevelsUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_BUFFERED, this.onFragBuffered, this);
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
this._unregisterListeners();
this.onMediaDetaching();
};
_proto.startLoad = function startLoad(startPosition) {
if (this.levels) {
var lastCurrentTime = this.lastCurrentTime,
hls = this.hls;
this.stopLoad();
this.setInterval(TICK_INTERVAL);
this.level = -1;
this.fragLoadError = 0;
if (!this.startFragRequested) {
// determine load level
var startLevel = hls.startLevel;
if (startLevel === -1) {
if (hls.config.testBandwidth) {
// -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
startLevel = 0;
this.bitrateTest = true;
} else {
startLevel = hls.nextAutoLevel;
}
} // set new level to playlist loader : this will trigger start level load
// hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
this.level = hls.nextLoadLevel = startLevel;
this.loadedmetadata = false;
} // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
if (lastCurrentTime > 0 && startPosition === -1) {
this.log("Override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
startPosition = lastCurrentTime;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
this.tick();
} else {
this._forceStartLoad = true;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].STOPPED;
}
};
_proto.stopLoad = function stopLoad() {
this._forceStartLoad = false;
_BaseStreamController.prototype.stopLoad.call(this);
};
_proto.doTick = function doTick() {
switch (this.state) {
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE:
this.doTickIdle();
break;
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL:
{
var _levels$level;
var levels = this.levels,
level = this.level;
var details = levels === null || levels === void 0 ? void 0 : (_levels$level = levels[level]) === null || _levels$level === void 0 ? void 0 : _levels$level.details;
if (details && (!details.live || this.levelLastLoaded === this.level)) {
if (this.waitForCdnTuneIn(details)) {
break;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
break;
}
break;
}
case _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY:
{
var _this$media;
var now = self.performance.now();
var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
if (!retryDate || now >= retryDate || (_this$media = this.media) !== null && _this$media !== void 0 && _this$media.seeking) {
this.log('retryDate reached, switch back to IDLE state');
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
}
break;
default:
break;
} // check buffer
// check/update current fragment
this.onTickEnd();
};
_proto.onTickEnd = function onTickEnd() {
_BaseStreamController.prototype.onTickEnd.call(this);
this.checkBuffer();
this.checkFragmentChanged();
};
_proto.doTickIdle = function doTickIdle() {
var _frag$decryptdata, _frag$decryptdata2;
var hls = this.hls,
levelLastLoaded = this.levelLastLoaded,
levels = this.levels,
media = this.media;
var config = hls.config,
level = hls.nextLoadLevel; // if start level not parsed yet OR
// if video not attached AND start fragment already requested OR start frag prefetch not enabled
// exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
if (levelLastLoaded === null || !media && (this.startFragRequested || !config.startFragPrefetch)) {
return;
} // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
if (this.altAudio && this.audioOnly) {
return;
}
if (!levels || !levels[level]) {
return;
}
var levelInfo = levels[level]; // if buffer length is less than maxBufLen try to load a new fragment
// set next load level : this will trigger a playlist load if needed
this.level = hls.nextLoadLevel = level;
var levelDetails = levelInfo.details; // if level info not retrieved yet, switch state and wait for level retrieval
// if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
// a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
if (!levelDetails || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL || levelDetails.live && this.levelLastLoaded !== level) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL;
return;
}
var pos = this.getLoadPosition();
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(pos)) {
return;
}
var frag = levelDetails.initSegment;
var targetBufferTime = 0;
if (!frag || frag.data || this.bitrateTest) {
// compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s
var levelBitrate = levelInfo.maxBitrate;
var maxBufLen;
if (levelBitrate) {
maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
} else {
maxBufLen = config.maxBufferLength;
}
maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength); // determine next candidate fragment to be loaded, based on current position and end of buffer position
// ensure up to `config.maxMaxBufferLength` of buffer upfront
var maxBufferHole = pos < config.maxBufferHole ? Math.max(_gap_controller__WEBPACK_IMPORTED_MODULE_10__["MAX_START_GAP_JUMP"], config.maxBufferHole) : config.maxBufferHole;
var bufferInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, maxBufferHole);
var bufferLen = bufferInfo.len; // Stay idle if we are still with buffer margins
if (bufferLen >= maxBufLen) {
return;
}
if (this._streamEnded(bufferInfo, levelDetails)) {
var data = {};
if (this.altAudio) {
data.type = 'video';
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_EOS, data);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ENDED;
return;
}
targetBufferTime = bufferInfo.end;
frag = this.getNextFragment(targetBufferTime, levelDetails); // Avoid loop loading by using nextLoadPosition set for backtracking
if (frag && this.fragmentTracker.getState(frag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].OK && this.nextLoadPosition > targetBufferTime) {
frag = this.getNextFragment(this.nextLoadPosition, levelDetails);
}
if (!frag) {
return;
}
} // We want to load the key if we're dealing with an identity key, because we will decrypt
// this content using the key we fetch. Other keys will be handled by the DRM CDM via EME.
if (((_frag$decryptdata = frag.decryptdata) === null || _frag$decryptdata === void 0 ? void 0 : _frag$decryptdata.keyFormat) === 'identity' && !((_frag$decryptdata2 = frag.decryptdata) !== null && _frag$decryptdata2 !== void 0 && _frag$decryptdata2.key)) {
this.loadKey(frag, levelDetails);
} else {
this.loadFragment(frag, levelDetails, targetBufferTime);
}
};
_proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
var _this$media2;
// Check if fragment is not loaded
var fragState = this.fragmentTracker.getState(frag);
this.fragCurrent = frag; // Use data from loaded backtracked fragment if available
if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].BACKTRACKED) {
var data = this.fragmentTracker.getBacktrackData(frag);
if (data) {
this._handleFragmentLoadProgress(data);
this._handleFragmentLoadComplete(data);
return;
} else {
fragState = _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED;
}
}
if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].NOT_LOADED || fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].PARTIAL) {
if (frag.sn === 'initSegment') {
this._loadInitSegment(frag);
} else if (this.bitrateTest) {
frag.bitrateTest = true;
this.log("Fragment " + frag.sn + " of level " + frag.level + " is being downloaded to test bitrate and will not be buffered");
this._loadBitrateTestFrag(frag);
} else {
this.startFragRequested = true;
_BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime);
}
} else if (fragState === _fragment_tracker__WEBPACK_IMPORTED_MODULE_5__["FragmentState"].APPENDING) {
// Lower the buffer size and try again
if (this.reduceMaxBufferLength(frag.duration)) {
this.fragmentTracker.removeFragment(frag);
}
} else if (((_this$media2 = this.media) === null || _this$media2 === void 0 ? void 0 : _this$media2.buffered.length) === 0) {
// Stop gap for bad tracker / buffer flush behavior
this.fragmentTracker.removeAllFragments();
}
};
_proto.getAppendedFrag = function getAppendedFrag(position) {
var fragOrPart = this.fragmentTracker.getAppendedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
if (fragOrPart && 'fragment' in fragOrPart) {
return fragOrPart.fragment;
}
return fragOrPart;
};
_proto.getBufferedFrag = function getBufferedFrag(position) {
return this.fragmentTracker.getBufferedFrag(position, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
};
_proto.followingBufferedFrag = function followingBufferedFrag(frag) {
if (frag) {
// try to get range of next fragment (500ms after this range)
return this.getBufferedFrag(frag.end + 0.5);
}
return null;
}
/*
on immediate level switch :
- pause playback if playing
- cancel any pending load request
- and trigger a buffer flush
*/
;
_proto.immediateLevelSwitch = function immediateLevelSwitch() {
this.abortCurrentFrag();
this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
}
/**
* try to switch ASAP without breaking video playback:
* in order to ensure smooth but quick level switching,
* we need to find the next flushable buffer range
* we should take into account new segment fetch time
*/
;
_proto.nextLevelSwitch = function nextLevelSwitch() {
var levels = this.levels,
media = this.media; // ensure that media is defined and that metadata are available (to retrieve currentTime)
if (media !== null && media !== void 0 && media.readyState) {
var fetchdelay;
var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {
// flush buffer preceding current fragment (flush until current fragment start offset)
// minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
this.flushMainBuffer(0, fragPlayingCurrent.start - 1);
}
if (!media.paused && levels) {
// add a safety delay of 1s
var nextLevelId = this.hls.nextLoadLevel;
var nextLevel = levels[nextLevelId];
var fragLastKbps = this.fragLastKbps;
if (fragLastKbps && this.fragCurrent) {
fetchdelay = this.fragCurrent.duration * nextLevel.maxBitrate / (1000 * fragLastKbps) + 1;
} else {
fetchdelay = 0;
}
} else {
fetchdelay = 0;
} // this.log('fetchdelay:'+fetchdelay);
// find buffer range that will be reached once new fragment will be fetched
var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
if (bufferedFrag) {
// we can flush buffer range following this one without stalling playback
var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
if (nextBufferedFrag) {
// if we are here, we can also cancel any loading/demuxing in progress, as they are useless
this.abortCurrentFrag(); // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.
var maxStart = nextBufferedFrag.maxStartPTS ? nextBufferedFrag.maxStartPTS : nextBufferedFrag.start;
var fragDuration = nextBufferedFrag.duration;
var startPts = Math.max(bufferedFrag.end, maxStart + Math.min(Math.max(fragDuration - this.config.maxFragLookUpTolerance, fragDuration * 0.5), fragDuration * 0.75));
this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
}
}
}
};
_proto.abortCurrentFrag = function abortCurrentFrag() {
var fragCurrent = this.fragCurrent;
this.fragCurrent = null;
if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
fragCurrent.loader.abort();
}
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].KEY_LOADING) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
this.nextLoadPosition = this.getLoadPosition();
};
_proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
_BaseStreamController.prototype.flushMainBuffer.call(this, startOffset, endOffset, this.altAudio ? 'video' : null);
};
_proto.onMediaAttached = function onMediaAttached(event, data) {
_BaseStreamController.prototype.onMediaAttached.call(this, event, data);
var media = data.media;
this.onvplaying = this.onMediaPlaying.bind(this);
this.onvseeked = this.onMediaSeeked.bind(this);
media.addEventListener('playing', this.onvplaying);
media.addEventListener('seeked', this.onvseeked);
this.gapController = new _gap_controller__WEBPACK_IMPORTED_MODULE_10__["default"](this.config, media, this.fragmentTracker, this.hls);
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media;
if (media) {
media.removeEventListener('playing', this.onvplaying);
media.removeEventListener('seeked', this.onvseeked);
this.onvplaying = this.onvseeked = null;
this.videoBuffer = null;
}
this.fragPlaying = null;
if (this.gapController) {
this.gapController.destroy();
this.gapController = null;
}
_BaseStreamController.prototype.onMediaDetaching.call(this);
};
_proto.onMediaPlaying = function onMediaPlaying() {
// tick to speed up FRAG_CHANGED triggering
this.tick();
};
_proto.onMediaSeeked = function onMediaSeeked() {
var media = this.media;
var currentTime = media ? media.currentTime : null;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(currentTime)) {
this.log("Media seeked to " + currentTime.toFixed(3));
} // tick to speed up FRAG_CHANGED triggering
this.tick();
};
_proto.onManifestLoading = function onManifestLoading() {
// reset buffer on manifest loading
this.log('Trigger BUFFER_RESET');
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_RESET, undefined);
this.fragmentTracker.removeAllFragments();
this.stalled = false;
this.startPosition = this.lastCurrentTime = 0;
this.fragPlaying = null;
};
_proto.onManifestParsed = function onManifestParsed(event, data) {
var aac = false;
var heaac = false;
var codec;
data.levels.forEach(function (level) {
// detect if we have different kind of audio codecs used amongst playlists
codec = level.audioCodec;
if (codec) {
if (codec.indexOf('mp4a.40.2') !== -1) {
aac = true;
}
if (codec.indexOf('mp4a.40.5') !== -1) {
heaac = true;
}
}
});
this.audioCodecSwitch = aac && heaac && !Object(_is_supported__WEBPACK_IMPORTED_MODULE_2__["changeTypeSupported"])();
if (this.audioCodecSwitch) {
this.log('Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
}
this.levels = data.levels;
this.startFragRequested = false;
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
var levels = this.levels;
if (!levels || this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE) {
return;
}
var level = levels[data.level];
if (!level.details || level.details.live && this.levelLastLoaded !== data.level || this.waitForCdnTuneIn(level.details)) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL;
}
};
_proto.onLevelLoaded = function onLevelLoaded(event, data) {
var _curLevel$details;
var levels = this.levels;
var newLevelId = data.level;
var newDetails = data.details;
var duration = newDetails.totalduration;
if (!levels) {
this.warn("Levels were reset while loading level " + newLevelId);
return;
}
this.log("Level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "], cc [" + newDetails.startCC + ", " + newDetails.endCC + "] duration:" + duration);
var fragCurrent = this.fragCurrent;
if (fragCurrent && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].FRAG_LOADING_WAITING_RETRY)) {
if (fragCurrent.level !== data.level && fragCurrent.loader) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
fragCurrent.loader.abort();
}
}
var curLevel = levels[newLevelId];
var sliding = 0;
if (newDetails.live || (_curLevel$details = curLevel.details) !== null && _curLevel$details !== void 0 && _curLevel$details.live) {
if (!newDetails.fragments[0]) {
newDetails.deltaUpdateFailed = true;
}
if (newDetails.deltaUpdateFailed) {
return;
}
sliding = this.alignPlaylists(newDetails, curLevel.details);
} // override level info
curLevel.details = newDetails;
this.levelLastLoaded = newLevelId;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_UPDATED, {
details: newDetails,
level: newLevelId
}); // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) {
if (this.waitForCdnTuneIn(newDetails)) {
// Wait for Low-Latency CDN Tune-in
return;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
if (!this.startFragRequested) {
this.setStartPosition(newDetails, sliding);
} else if (newDetails.live) {
this.synchronizeToLiveEdge(newDetails);
} // trigger handler right now
this.tick();
};
_proto._handleFragmentLoadProgress = function _handleFragmentLoadProgress(data) {
var _details$initSegment;
var frag = data.frag,
part = data.part,
payload = data.payload;
var levels = this.levels;
if (!levels) {
this.warn("Levels were reset while fragment load was in progress. Fragment " + frag.sn + " of level " + frag.level + " will not be buffered");
return;
}
var currentLevel = levels[frag.level];
var details = currentLevel.details;
if (!details) {
this.warn("Dropping fragment " + frag.sn + " of level " + frag.level + " after level details were reset");
return;
}
var videoCodec = currentLevel.videoCodec; // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
var accurateTimeOffset = details.PTSKnown || !details.live;
var initSegmentData = (_details$initSegment = details.initSegment) === null || _details$initSegment === void 0 ? void 0 : _details$initSegment.data;
var audioCodec = this._getAudioCodec(currentLevel); // transmux the MPEG-TS data to ISO-BMFF segments
// this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);
var transmuxer = this.transmuxer = this.transmuxer || new _demux_transmuxer_interface__WEBPACK_IMPORTED_MODULE_8__["default"](this.hls, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, this._handleTransmuxComplete.bind(this), this._handleTransmuxerFlush.bind(this));
var partIndex = part ? part.index : -1;
var partial = partIndex !== -1;
var chunkMeta = new _types_transmuxer__WEBPACK_IMPORTED_MODULE_9__["ChunkMetadata"](frag.level, frag.sn, frag.stats.chunkCount, payload.byteLength, partIndex, partial);
var initPTS = this.initPTS[frag.cc];
transmuxer.push(payload, initSegmentData, audioCodec, videoCodec, frag, part, details.totalduration, accurateTimeOffset, chunkMeta, initPTS);
};
_proto.onAudioTrackSwitching = function onAudioTrackSwitching(event, data) {
// if any URL found on new audio track, it is an alternate audio track
var fromAltAudio = this.altAudio;
var altAudio = !!data.url;
var trackId = data.id; // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
// don't do anything if we switch to alt audio: audio stream controller is handling it.
// we will just have to change buffer scheduling on audioTrackSwitched
if (!altAudio) {
if (this.mediaBuffer !== this.media) {
this.log('Switching on main audio, use media.buffered to schedule main fragment loading');
this.mediaBuffer = this.media;
var fragCurrent = this.fragCurrent; // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
if (fragCurrent !== null && fragCurrent !== void 0 && fragCurrent.loader) {
this.log('Switching to main audio track, cancel main fragment load');
fragCurrent.loader.abort();
} // destroy transmuxer to force init segment generation (following audio switch)
this.resetTransmuxer(); // switch to IDLE state to load new fragment
this.resetLoadingState();
} else if (this.audioOnly) {
// Reset audio transmuxer so when switching back to main audio we're not still appending where we left off
this.resetTransmuxer();
}
var hls = this.hls; // If switching from alt to main audio, flush all audio and trigger track switched
if (fromAltAudio) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_FLUSHING, {
startOffset: 0,
endOffset: Number.POSITIVE_INFINITY,
type: 'audio'
});
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].AUDIO_TRACK_SWITCHED, {
id: trackId
});
}
};
_proto.onAudioTrackSwitched = function onAudioTrackSwitched(event, data) {
var trackId = data.id;
var altAudio = !!this.hls.audioTracks[trackId].url;
if (altAudio) {
var videoBuffer = this.videoBuffer; // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
if (videoBuffer && this.mediaBuffer !== videoBuffer) {
this.log('Switching on alternate audio, use video.buffered to schedule main fragment loading');
this.mediaBuffer = videoBuffer;
}
}
this.altAudio = altAudio;
this.tick();
};
_proto.onBufferCreated = function onBufferCreated(event, data) {
var tracks = data.tracks;
var mediaTrack;
var name;
var alternate = false;
for (var type in tracks) {
var track = tracks[type];
if (track.id === 'main') {
name = type;
mediaTrack = track; // keep video source buffer reference
if (type === 'video') {
var videoTrack = tracks[type];
if (videoTrack) {
this.videoBuffer = videoTrack.buffer;
}
}
} else {
alternate = true;
}
}
if (alternate && mediaTrack) {
this.log("Alternate track found, use " + name + ".buffered to schedule main fragment loading");
this.mediaBuffer = mediaTrack.buffer;
} else {
this.mediaBuffer = this.media;
}
};
_proto.onFragBuffered = function onFragBuffered(event, data) {
var frag = data.frag,
part = data.part;
if (frag && frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN) {
return;
}
if (this.fragContextChanged(frag)) {
// If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion
// Avoid setting state back to IDLE, since that will interfere with a level switch
this.warn("Fragment " + frag.sn + (part ? ' p: ' + part.index : '') + " of level " + frag.level + " finished buffering, but was aborted. state: " + this.state);
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
return;
}
var stats = part ? part.stats : frag.stats;
this.fragLastKbps = Math.round(8 * stats.total / (stats.buffering.end - stats.loading.first));
if (frag.sn !== 'initSegment') {
this.fragPrevious = frag;
}
this.fragBufferedComplete(frag, part);
};
_proto.onError = function onError(event, data) {
switch (data.details) {
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].KEY_LOAD_TIMEOUT:
this.onFragmentOrKeyLoadError(_types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN, data);
break;
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_ERROR:
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR) {
if (data.fatal) {
// if fatal error, stop processing
this.warn("" + data.details);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].ERROR;
} else {
// in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
if (!data.levelRetry && this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].WAITING_LEVEL) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
}
}
}
break;
case _errors__WEBPACK_IMPORTED_MODULE_11__["ErrorDetails"].BUFFER_FULL_ERROR:
// if in appending state
if (data.parent === 'main' && (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING || this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSED)) {
// 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
var mediaBuffered = !!this.media && _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(this.media, this.media.currentTime) && _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(this.media, this.media.currentTime + 0.5); // reduce max buf len if current position is buffered
if (mediaBuffered) {
this.reduceMaxBufferLength();
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
} else {
// current position is not buffered, but browser is still complaining about buffer full error
// this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
// in that case flush the whole buffer to recover
this.warn('buffer full error also media.currentTime is not buffered, flush everything'); // flush everything
this.immediateLevelSwitch();
}
}
break;
default:
break;
}
} // Checks the health of the buffer and attempts to resolve playback stalls.
;
_proto.checkBuffer = function checkBuffer() {
var media = this.media,
gapController = this.gapController;
if (!media || !gapController || !media.readyState) {
// Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
return;
} // Check combined buffer
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media);
if (!this.loadedmetadata && buffered.length) {
this.loadedmetadata = true;
this.seekToStartPos();
} else {
// Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers
gapController.poll(this.lastCurrentTime);
}
this.lastCurrentTime = media.currentTime;
};
_proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE; // if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
this.nextLoadPosition = this.startPosition;
}
this.tick();
};
_proto.onBufferFlushed = function onBufferFlushed(event, _ref) {
var type = _ref.type;
if (type !== _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO || this.audioOnly && !this.altAudio) {
var media = (type === _loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].VIDEO ? this.videoBuffer : this.mediaBuffer) || this.media;
this.afterBufferFlushed(media, type, _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN);
}
};
_proto.onLevelsUpdated = function onLevelsUpdated(event, data) {
this.levels = data.levels;
};
_proto.swapAudioCodec = function swapAudioCodec() {
this.audioCodecSwap = !this.audioCodecSwap;
}
/**
* Seeks to the set startPosition if not equal to the mediaElement's current time.
* @private
*/
;
_proto.seekToStartPos = function seekToStartPos() {
var media = this.media;
var currentTime = media.currentTime;
var startPosition = this.startPosition; // only adjust currentTime if different from startPosition or if startPosition not buffered
// at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
if (startPosition >= 0 && currentTime < startPosition) {
if (media.seeking) {
_utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("could not seek to " + startPosition + ", already seeking at " + currentTime);
return;
}
var buffered = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].getBuffered(media);
var bufferStart = buffered.length ? buffered.start(0) : 0;
var delta = bufferStart - startPosition;
if (delta > 0 && delta < this.config.maxBufferHole) {
_utils_logger__WEBPACK_IMPORTED_MODULE_12__["logger"].log("adjusting start position by " + delta + " to match buffer start");
startPosition += delta;
this.startPosition = startPosition;
}
this.log("seek to target start position " + startPosition + " from current time " + currentTime);
media.currentTime = startPosition;
}
};
_proto._getAudioCodec = function _getAudioCodec(currentLevel) {
var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
if (this.audioCodecSwap && audioCodec) {
this.log('Swapping audio codec');
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
}
return audioCodec;
};
_proto._loadBitrateTestFrag = function _loadBitrateTestFrag(frag) {
var _this2 = this;
this._doFragLoad(frag).then(function (data) {
var hls = _this2.hls;
if (!data || hls.nextLoadLevel || _this2.fragContextChanged(frag)) {
return;
}
_this2.fragLoadError = 0;
_this2.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].IDLE;
_this2.startFragRequested = false;
_this2.bitrateTest = false;
var stats = frag.stats; // Bitrate tests fragments are neither parsed nor buffered
stats.parsing.start = stats.parsing.end = stats.buffering.start = stats.buffering.end = self.performance.now();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_LOADED, data);
});
};
_proto._handleTransmuxComplete = function _handleTransmuxComplete(transmuxResult) {
var _id3$samples;
var id = 'main';
var hls = this.hls;
var remuxResult = transmuxResult.remuxResult,
chunkMeta = transmuxResult.chunkMeta;
var context = this.getCurrentContext(chunkMeta);
if (!context) {
this.warn("The loading context changed while buffering fragment " + chunkMeta.sn + " of level " + chunkMeta.level + ". This chunk will not be buffered.");
this.resetLiveStartWhenNotLoaded(chunkMeta.level);
return;
}
var frag = context.frag,
part = context.part,
level = context.level;
var video = remuxResult.video,
text = remuxResult.text,
id3 = remuxResult.id3,
initSegment = remuxResult.initSegment; // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track
var audio = this.altAudio ? undefined : remuxResult.audio; // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.
// If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.
if (this.fragContextChanged(frag)) {
return;
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING;
if (initSegment) {
if (initSegment.tracks) {
this._bufferInitSegment(level, initSegment.tracks, frag, chunkMeta);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_INIT_SEGMENT, {
frag: frag,
id: id,
tracks: initSegment.tracks
});
} // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038
var initPTS = initSegment.initPTS;
var timescale = initSegment.timescale;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) {
this.initPTS[frag.cc] = initPTS;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].INIT_PTS_FOUND, {
frag: frag,
id: id,
initPTS: initPTS,
timescale: timescale
});
}
} // Avoid buffering if backtracking this fragment
if (video && remuxResult.independent !== false) {
if (level.details) {
var startPTS = video.startPTS,
endPTS = video.endPTS,
startDTS = video.startDTS,
endDTS = video.endDTS;
if (part) {
part.elementaryStreams[video.type] = {
startPTS: startPTS,
endPTS: endPTS,
startDTS: startDTS,
endDTS: endDTS
};
} else if (video.dropped && video.independent) {
// Backtrack if dropped frames create a gap after currentTime
var pos = this.getLoadPosition() + this.config.maxBufferHole;
if (pos < startPTS) {
this.backtrack(frag);
return;
} // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial
frag.setElementaryStreamInfo(video.type, frag.start, endPTS, frag.start, endDTS, true);
}
frag.setElementaryStreamInfo(video.type, startPTS, endPTS, startDTS, endDTS);
this.bufferFragmentData(video, frag, part, chunkMeta);
}
} else if (remuxResult.independent === false) {
this.backtrack(frag);
return;
}
if (audio) {
var _startPTS = audio.startPTS,
_endPTS = audio.endPTS,
_startDTS = audio.startDTS,
_endDTS = audio.endDTS;
if (part) {
part.elementaryStreams[_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO] = {
startPTS: _startPTS,
endPTS: _endPTS,
startDTS: _startDTS,
endDTS: _endDTS
};
}
frag.setElementaryStreamInfo(_loader_fragment__WEBPACK_IMPORTED_MODULE_7__["ElementaryStreamTypes"].AUDIO, _startPTS, _endPTS, _startDTS, _endDTS);
this.bufferFragmentData(audio, frag, part, chunkMeta);
}
if (id3 !== null && id3 !== void 0 && (_id3$samples = id3.samples) !== null && _id3$samples !== void 0 && _id3$samples.length) {
var emittedID3 = {
frag: frag,
id: id,
samples: id3.samples
};
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_METADATA, emittedID3);
}
if (text) {
var emittedText = {
frag: frag,
id: id,
samples: text.samples
};
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_PARSING_USERDATA, emittedText);
}
};
_proto._bufferInitSegment = function _bufferInitSegment(currentLevel, tracks, frag, chunkMeta) {
var _this3 = this;
if (this.state !== _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].PARSING) {
return;
}
this.audioOnly = !!tracks.audio && !tracks.video; // if audio track is expected to come from audio stream controller, discard any coming from main
if (this.altAudio && !this.audioOnly) {
delete tracks.audio;
} // include levelCodec in audio and video tracks
var audio = tracks.audio,
video = tracks.video,
audiovideo = tracks.audiovideo;
if (audio) {
var audioCodec = currentLevel.audioCodec;
var ua = navigator.userAgent.toLowerCase();
if (this.audioCodecSwitch) {
if (audioCodec) {
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
} // In the case that AAC and HE-AAC audio codecs are signalled in manifest,
// force HE-AAC, as it seems that most browsers prefers it.
// don't force HE-AAC if mono stream, or in Firefox
if (audio.metadata.channelCount !== 1 && ua.indexOf('firefox') === -1) {
audioCodec = 'mp4a.40.5';
}
} // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
if (ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {
// Exclude mpeg audio
audioCodec = 'mp4a.40.2';
this.log("Android: force audio codec to " + audioCodec);
}
if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {
this.log("Swapping manifest audio codec \"" + currentLevel.audioCodec + "\" for \"" + audioCodec + "\"");
}
audio.levelCodec = audioCodec;
audio.id = 'main';
this.log("Init audio buffer, container:" + audio.container + ", codecs[selected/level/parsed]=[" + (audioCodec || '') + "/" + (currentLevel.audioCodec || '') + "/" + audio.codec + "]");
}
if (video) {
video.levelCodec = currentLevel.videoCodec;
video.id = 'main';
this.log("Init video buffer, container:" + video.container + ", codecs[level/parsed]=[" + (currentLevel.videoCodec || '') + "/" + video.codec + "]");
}
if (audiovideo) {
this.log("Init audiovideo buffer, container:" + audiovideo.container + ", codecs[level/parsed]=[" + (currentLevel.attrs.CODECS || '') + "/" + audiovideo.codec + "]");
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_CODECS, tracks); // loop through tracks that are going to be provided to bufferController
Object.keys(tracks).forEach(function (trackName) {
var track = tracks[trackName];
var initSegment = track.initSegment;
if (initSegment !== null && initSegment !== void 0 && initSegment.byteLength) {
_this3.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].BUFFER_APPENDING, {
type: trackName,
data: initSegment,
frag: frag,
part: null,
chunkMeta: chunkMeta,
parent: frag.type
});
}
}); // trigger handler right now
this.tick();
};
_proto.backtrack = function backtrack(frag) {
// Causes findFragments to backtrack through fragments to find the keyframe
this.resetTransmuxer();
this.flushBufferGap(frag);
var data = this.fragmentTracker.backtrack(frag);
this.fragPrevious = null;
this.nextLoadPosition = frag.start;
if (data) {
this.resetFragmentLoading(frag);
} else {
// Change state to BACKTRACKING so that fragmentEntity.backtrack data can be added after _doFragLoad
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["State"].BACKTRACKING;
}
};
_proto.checkFragmentChanged = function checkFragmentChanged() {
var video = this.media;
var fragPlayingCurrent = null;
if (video && video.readyState > 1 && video.seeking === false) {
var currentTime = video.currentTime;
/* if video element is in seeked state, currentTime can only increase.
(assuming that playback rate is positive ...)
As sometimes currentTime jumps back to zero after a
media decode error, check this, to avoid seeking back to
wrong position after a media decode error
*/
if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime)) {
fragPlayingCurrent = this.getAppendedFrag(currentTime);
} else if (_utils_buffer_helper__WEBPACK_IMPORTED_MODULE_4__["BufferHelper"].isBuffered(video, currentTime + 0.1)) {
/* ensure that FRAG_CHANGED event is triggered at startup,
when first video frame is displayed and playback is paused.
add a tolerance of 100ms, in case current position is not buffered,
check if current pos+100ms is buffered and use that buffer range
for FRAG_CHANGED event reporting */
fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);
}
if (fragPlayingCurrent) {
var fragPlaying = this.fragPlaying;
var fragCurrentLevel = fragPlayingCurrent.level;
if (!fragPlaying || fragPlayingCurrent.sn !== fragPlaying.sn || fragPlaying.level !== fragCurrentLevel || fragPlayingCurrent.urlId !== fragPlaying.urlId) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].FRAG_CHANGED, {
frag: fragPlayingCurrent
});
if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].LEVEL_SWITCHED, {
level: fragCurrentLevel
});
}
this.fragPlaying = fragPlayingCurrent;
}
}
}
};
_createClass(StreamController, [{
key: "nextLevel",
get: function get() {
var frag = this.nextBufferedFrag;
if (frag) {
return frag.level;
} else {
return -1;
}
}
}, {
key: "currentLevel",
get: function get() {
var media = this.media;
if (media) {
var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
if (fragPlayingCurrent) {
return fragPlayingCurrent.level;
}
}
return -1;
}
}, {
key: "nextBufferedFrag",
get: function get() {
var media = this.media;
if (media) {
// first get end range of current fragment
var fragPlayingCurrent = this.getAppendedFrag(media.currentTime);
return this.followingBufferedFrag(fragPlayingCurrent);
} else {
return null;
}
}
}, {
key: "forceStartLoad",
get: function get() {
return this._forceStartLoad;
}
}]);
return StreamController;
}(_base_stream_controller__WEBPACK_IMPORTED_MODULE_1__["default"]);
/***/ }),
/***/ "./src/controller/subtitle-stream-controller.ts":
/*!******************************************************!*\
!*** ./src/controller/subtitle-stream-controller.ts ***!
\******************************************************/
/*! exports provided: SubtitleStreamController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubtitleStreamController", function() { return SubtitleStreamController; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.ts");
/* harmony import */ var _fragment_finders__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.ts");
/* harmony import */ var _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _types_level__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/level */ "./src/types/level.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var TICK_INTERVAL = 500; // how often to tick in ms
var SubtitleStreamController = /*#__PURE__*/function (_BaseStreamController) {
_inheritsLoose(SubtitleStreamController, _BaseStreamController);
function SubtitleStreamController(hls, fragmentTracker) {
var _this;
_this = _BaseStreamController.call(this, hls, fragmentTracker, '[subtitle-stream-controller]') || this;
_this.levels = [];
_this.currentTrackId = -1;
_this.tracksBuffered = void 0;
_this.config = hls.config;
_this.fragCurrent = null;
_this.fragPrevious = null;
_this.media = null;
_this.mediaBuffer = null;
_this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].STOPPED;
_this.tracksBuffered = [];
_this._registerListeners();
return _this;
}
var _proto = SubtitleStreamController.prototype;
_proto._registerListeners = function _registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);
};
_proto.startLoad = function startLoad() {
this.stopLoad();
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].IDLE; // Check if we already have a track with necessary details to load fragments
var currentTrack = this.levels[this.currentTrackId];
if (currentTrack !== null && currentTrack !== void 0 && currentTrack.details) {
this.setInterval(TICK_INTERVAL);
this.tick();
}
};
_proto.onHandlerDestroyed = function onHandlerDestroyed() {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].STOPPED;
this._unregisterListeners();
_BaseStreamController.prototype.onHandlerDestroyed.call(this);
};
_proto.onSubtitleFragProcessed = function onSubtitleFragProcessed(event, data) {
var frag = data.frag,
success = data.success;
this.fragPrevious = frag;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].IDLE;
if (!success) {
return;
}
var buffered = this.tracksBuffered[this.currentTrackId];
if (!buffered) {
return;
} // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
// so we can re-use the logic used to detect how much have been buffered
var timeRange;
var fragStart = frag.start;
for (var i = 0; i < buffered.length; i++) {
if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
timeRange = buffered[i];
break;
}
}
var fragEnd = frag.start + frag.duration;
if (timeRange) {
timeRange.end = fragEnd;
} else {
timeRange = {
start: fragStart,
end: fragEnd
};
buffered.push(timeRange);
}
};
_proto.onMediaAttached = function onMediaAttached(event, _ref) {
var media = _ref.media;
this.media = media;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].IDLE;
};
_proto.onMediaDetaching = function onMediaDetaching() {
var _this2 = this;
if (!this.media) {
return;
}
this.fragmentTracker.removeAllFragments();
this.fragPrevious = null;
this.currentTrackId = -1;
this.levels.forEach(function (level) {
_this2.tracksBuffered[level.id] = [];
});
this.media = null;
this.mediaBuffer = null;
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].STOPPED;
} // If something goes wrong, proceed to next frag, if we were processing one.
;
_proto.onError = function onError(event, data) {
var _this$fragCurrent;
var frag = data.frag; // don't handle error not related to subtitle fragment
if (!frag || frag.type !== _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].SUBTITLE) {
return;
}
if ((_this$fragCurrent = this.fragCurrent) !== null && _this$fragCurrent !== void 0 && _this$fragCurrent.loader) {
this.fragCurrent.loader.abort();
}
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].IDLE;
} // Got all new subtitle levels.
;
_proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, _ref2) {
var _this3 = this;
var subtitleTracks = _ref2.subtitleTracks;
this.tracksBuffered = [];
this.levels = subtitleTracks.map(function (mediaPlaylist) {
return new _types_level__WEBPACK_IMPORTED_MODULE_7__["Level"](mediaPlaylist);
});
this.fragmentTracker.removeAllFragments();
this.fragPrevious = null;
this.levels.forEach(function (level) {
_this3.tracksBuffered[level.id] = [];
});
this.mediaBuffer = null;
};
_proto.onSubtitleTrackSwitch = function onSubtitleTrackSwitch(event, data) {
this.currentTrackId = data.id;
if (!this.levels.length || this.currentTrackId === -1) {
this.clearInterval();
return;
} // Check if track has the necessary details to load fragments
var currentTrack = this.levels[this.currentTrackId];
if (currentTrack !== null && currentTrack !== void 0 && currentTrack.details) {
this.mediaBuffer = this.mediaBufferTimeRanges;
this.setInterval(TICK_INTERVAL);
} else {
this.mediaBuffer = null;
}
} // Got a new set of subtitle fragments.
;
_proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) {
var _currentTrack$details;
var id = data.id,
details = data.details;
var currentTrackId = this.currentTrackId,
levels = this.levels;
if (!levels.length || !details) {
return;
}
var currentTrack = levels[currentTrackId];
if (id >= levels.length || id !== currentTrackId || !currentTrack) {
return;
}
this.mediaBuffer = this.mediaBufferTimeRanges;
if (details.live || (_currentTrack$details = currentTrack.details) !== null && _currentTrack$details !== void 0 && _currentTrack$details.live) {
if (details.deltaUpdateFailed) {
return;
} // TODO: Subtitle Fragments should be assigned startPTS and endPTS once VTT/TTML is parsed
// otherwise this depends on DISCONTINUITY or PROGRAM-DATE-TIME tags to align playlists
this.alignPlaylists(details, currentTrack.details);
}
currentTrack.details = details;
this.levelLastLoaded = id;
this.setInterval(TICK_INTERVAL);
};
_proto._handleFragmentLoadComplete = function _handleFragmentLoadComplete(fragLoadedData) {
var frag = fragLoadedData.frag,
payload = fragLoadedData.payload;
var decryptData = frag.decryptdata;
var hls = this.hls;
if (this.fragContextChanged(frag)) {
return;
} // check to see if the payload needs to be decrypted
if (payload && payload.byteLength > 0 && decryptData && decryptData.key && decryptData.iv && decryptData.method === 'AES-128') {
var startTime = performance.now(); // decrypt the subtitles
this.decrypter.webCryptoDecrypt(new Uint8Array(payload), decryptData.key.buffer, decryptData.iv.buffer).then(function (decryptedData) {
var endTime = performance.now();
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].FRAG_DECRYPTED, {
frag: frag,
payload: decryptedData,
stats: {
tstart: startTime,
tdecrypt: endTime
}
});
});
}
};
_proto.doTick = function doTick() {
if (!this.media) {
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].IDLE;
return;
}
if (this.state === _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].IDLE) {
var _foundFrag;
var config = this.config,
currentTrackId = this.currentTrackId,
fragmentTracker = this.fragmentTracker,
media = this.media,
levels = this.levels;
if (!levels.length || !levels[currentTrackId] || !levels[currentTrackId].details) {
return;
}
var maxBufferHole = config.maxBufferHole,
maxFragLookUpTolerance = config.maxFragLookUpTolerance;
var maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
var bufferedInfo = _utils_buffer_helper__WEBPACK_IMPORTED_MODULE_2__["BufferHelper"].bufferedInfo(this.mediaBufferTimeRanges, media.currentTime, maxBufferHole);
var targetBufferTime = bufferedInfo.end,
bufferLen = bufferedInfo.len;
if (bufferLen > maxConfigBuffer) {
return;
}
var trackDetails = levels[currentTrackId].details;
console.assert(trackDetails, 'Subtitle track details are defined on idle subtitle stream controller tick');
var fragments = trackDetails.fragments;
var fragLen = fragments.length;
var end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration;
var foundFrag;
var fragPrevious = this.fragPrevious;
if (targetBufferTime < end) {
if (fragPrevious && trackDetails.hasProgramDateTime) {
foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPDT"])(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);
}
if (!foundFrag) {
foundFrag = Object(_fragment_finders__WEBPACK_IMPORTED_MODULE_3__["findFragmentByPTS"])(fragPrevious, fragments, targetBufferTime, maxFragLookUpTolerance);
}
} else {
foundFrag = fragments[fragLen - 1];
}
if ((_foundFrag = foundFrag) !== null && _foundFrag !== void 0 && _foundFrag.encrypted) {
_utils_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Loading key for " + foundFrag.sn);
this.state = _base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["State"].KEY_LOADING;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, {
frag: foundFrag
});
} else if (foundFrag && fragmentTracker.getState(foundFrag) === _fragment_tracker__WEBPACK_IMPORTED_MODULE_4__["FragmentState"].NOT_LOADED) {
// only load if fragment is not loaded
this.loadFragment(foundFrag, trackDetails, targetBufferTime);
}
}
};
_proto.loadFragment = function loadFragment(frag, levelDetails, targetBufferTime) {
this.fragCurrent = frag;
_BaseStreamController.prototype.loadFragment.call(this, frag, levelDetails, targetBufferTime);
};
_proto.stopLoad = function stopLoad() {
this.fragPrevious = null;
_BaseStreamController.prototype.stopLoad.call(this);
};
_createClass(SubtitleStreamController, [{
key: "mediaBufferTimeRanges",
get: function get() {
return this.tracksBuffered[this.currentTrackId] || [];
}
}]);
return SubtitleStreamController;
}(_base_stream_controller__WEBPACK_IMPORTED_MODULE_5__["default"]);
/***/ }),
/***/ "./src/controller/subtitle-track-controller.ts":
/*!*****************************************************!*\
!*** ./src/controller/subtitle-track-controller.ts ***!
\*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
/* harmony import */ var _base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./base-playlist-controller */ "./src/controller/base-playlist-controller.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var SubtitleTrackController = /*#__PURE__*/function (_BasePlaylistControll) {
_inheritsLoose(SubtitleTrackController, _BasePlaylistControll);
// Enable/disable subtitle display rendering
function SubtitleTrackController(hls) {
var _this;
_this = _BasePlaylistControll.call(this, hls, '[subtitle-track-controller]') || this;
_this.media = null;
_this.tracks = [];
_this.groupId = null;
_this.tracksInGroup = [];
_this.trackId = -1;
_this.selectDefaultTrack = true;
_this.queuedDefaultTrack = -1;
_this.trackChangeListener = function () {
return _this.onTextTracksChanged();
};
_this.useTextTrackPolling = false;
_this.subtitlePollingInterval = -1;
_this.subtitleDisplay = true;
_this.registerListeners();
return _this;
}
var _proto = SubtitleTrackController.prototype;
_proto.destroy = function destroy() {
this.unregisterListeners();
this.tracks.length = 0;
this.tracksInGroup.length = 0; // @ts-ignore
this.trackChangeListener = null;
_BasePlaylistControll.prototype.destroy.call(this);
};
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_ATTACHED, this.onMediaAttached, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].MANIFEST_PARSED, this.onManifestParsed, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].LEVEL_SWITCHING, this.onLevelSwitching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, this.onError, this);
} // Listen for subtitle track change, then extract the current track ID.
;
_proto.onMediaAttached = function onMediaAttached(event, data) {
var _this2 = this;
this.media = data.media;
if (!this.media) {
return;
}
if (this.queuedDefaultTrack > -1) {
this.subtitleTrack = this.queuedDefaultTrack;
this.queuedDefaultTrack = -1;
}
this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
if (this.useTextTrackPolling) {
self.clearInterval(this.subtitlePollingInterval);
this.subtitlePollingInterval = self.setInterval(function () {
_this2.trackChangeListener();
}, 500);
} else {
this.media.textTracks.addEventListener('change', this.trackChangeListener);
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
if (!this.media) {
return;
}
if (this.useTextTrackPolling) {
self.clearInterval(this.subtitlePollingInterval);
} else {
this.media.textTracks.removeEventListener('change', this.trackChangeListener);
}
if (this.trackId > -1) {
this.queuedDefaultTrack = this.trackId;
}
var textTracks = filterSubtitleTracks(this.media.textTracks); // Clear loaded cues on media detachment from tracks
textTracks.forEach(function (track) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_1__["clearCurrentCues"])(track);
}); // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.
this.subtitleTrack = -1;
this.media = null;
};
_proto.onManifestLoading = function onManifestLoading() {
this.tracks = [];
this.groupId = null;
this.tracksInGroup = [];
this.trackId = -1;
this.selectDefaultTrack = true;
} // Fired whenever a new manifest is loaded.
;
_proto.onManifestParsed = function onManifestParsed(event, data) {
this.tracks = data.subtitleTracks;
};
_proto.onSubtitleTrackLoaded = function onSubtitleTrackLoaded(event, data) {
var id = data.id,
details = data.details;
var trackId = this.trackId;
var currentTrack = this.tracksInGroup[trackId];
if (!currentTrack) {
this.warn("Invalid subtitle track id " + id);
return;
}
var curDetails = currentTrack.details;
currentTrack.details = data.details;
this.log("subtitle track " + id + " loaded [" + details.startSN + "-" + details.endSN + "]");
if (id === this.trackId) {
this.retryCount = 0;
this.playlistLoaded(id, data, curDetails);
}
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
this.switchLevel(data.level);
};
_proto.onLevelSwitching = function onLevelSwitching(event, data) {
this.switchLevel(data.level);
};
_proto.switchLevel = function switchLevel(levelIndex) {
var levelInfo = this.hls.levels[levelIndex];
if (!(levelInfo !== null && levelInfo !== void 0 && levelInfo.textGroupIds)) {
return;
}
var textGroupId = levelInfo.textGroupIds[levelInfo.urlId];
if (this.groupId !== textGroupId) {
var lastTrack = this.tracksInGroup ? this.tracksInGroup[this.trackId] : undefined;
var subtitleTracks = this.tracks.filter(function (track) {
return !textGroupId || track.groupId === textGroupId;
});
this.tracksInGroup = subtitleTracks;
var initialTrackId = this.findTrackId(lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.name) || this.findTrackId();
this.groupId = textGroupId;
var subtitleTracksUpdated = {
subtitleTracks: subtitleTracks
};
this.log("Updating subtitle tracks, " + subtitleTracks.length + " track(s) found in \"" + textGroupId + "\" group-id");
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);
if (initialTrackId !== -1) {
this.setSubtitleTrack(initialTrackId, lastTrack);
}
}
};
_proto.findTrackId = function findTrackId(name) {
var textTracks = this.tracksInGroup;
for (var i = 0; i < textTracks.length; i++) {
var track = textTracks[i];
if (!this.selectDefaultTrack || track.default) {
if (!name || name === track.name) {
return track.id;
}
}
}
return -1;
};
_proto.onError = function onError(event, data) {
_BasePlaylistControll.prototype.onError.call(this, event, data);
if (data.fatal || !data.context) {
return;
}
if (data.context.type === _types_loader__WEBPACK_IMPORTED_MODULE_3__["PlaylistContextType"].SUBTITLE_TRACK && data.context.id === this.trackId && data.context.groupId === this.groupId) {
this.retryLoadingOrFail(data);
}
}
/** get alternate subtitle tracks list from playlist **/
;
_proto.loadPlaylist = function loadPlaylist(hlsUrlParameters) {
var currentTrack = this.tracksInGroup[this.trackId];
if (this.shouldLoadTrack(currentTrack)) {
var id = currentTrack.id;
var groupId = currentTrack.groupId;
var url = currentTrack.url;
if (hlsUrlParameters) {
try {
url = hlsUrlParameters.addDirectives(url);
} catch (error) {
this.warn("Could not construct new URL with HLS Delivery Directives: " + error);
}
}
this.log("Loading subtitle playlist for id " + id);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_LOADING, {
url: url,
id: id,
groupId: groupId,
deliveryDirectives: hlsUrlParameters || null
});
}
}
/**
* Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
* This operates on the DOM textTracks.
* A value of -1 will disable all subtitle tracks.
*/
;
_proto.toggleTrackModes = function toggleTrackModes(newId) {
var _this3 = this;
var media = this.media,
subtitleDisplay = this.subtitleDisplay,
trackId = this.trackId;
if (!media) {
return;
}
var textTracks = filterSubtitleTracks(media.textTracks);
var groupTracks = textTracks.filter(function (track) {
return track.groupId === _this3.groupId;
});
if (newId === -1) {
[].slice.call(textTracks).forEach(function (track) {
track.mode = 'disabled';
});
} else {
var oldTrack = groupTracks[trackId];
if (oldTrack) {
oldTrack.mode = 'disabled';
}
}
var nextTrack = groupTracks[newId];
if (nextTrack) {
nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';
}
}
/**
* This method is responsible for validating the subtitle index and periodically reloading if live.
* Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
*/
;
_proto.setSubtitleTrack = function setSubtitleTrack(newId, lastTrack) {
var _tracks$newId;
var tracks = this.tracksInGroup; // setting this.subtitleTrack will trigger internal logic
// if media has not been attached yet, it will fail
// we keep a reference to the default track id
// and we'll set subtitleTrack when onMediaAttached is triggered
if (!this.media) {
this.queuedDefaultTrack = newId;
return;
}
if (this.trackId !== newId) {
this.toggleTrackModes(newId);
} // exit if track id as already set or invalid
if (this.trackId === newId && (newId === -1 || (_tracks$newId = tracks[newId]) !== null && _tracks$newId !== void 0 && _tracks$newId.details) || newId < -1 || newId >= tracks.length) {
return;
} // stopping live reloading timer if any
this.clearTimer();
var track = tracks[newId];
this.log("Switching to subtitle track " + newId);
this.trackId = newId;
if (track) {
var id = track.id,
_track$groupId = track.groupId,
groupId = _track$groupId === void 0 ? '' : _track$groupId,
name = track.name,
type = track.type,
url = track.url;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, {
id: id,
groupId: groupId,
name: name,
type: type,
url: url
});
var hlsUrlParameters = this.switchParams(track.url, lastTrack === null || lastTrack === void 0 ? void 0 : lastTrack.details);
this.loadPlaylist(hlsUrlParameters);
} else {
// switch to -1
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].SUBTITLE_TRACK_SWITCH, {
id: newId
});
}
};
_proto.onTextTracksChanged = function onTextTracksChanged() {
// Media is undefined when switching streams via loadSource()
if (!this.media || !this.hls.config.renderTextTracksNatively) {
return;
}
var trackId = -1;
var tracks = filterSubtitleTracks(this.media.textTracks);
for (var id = 0; id < tracks.length; id++) {
if (tracks[id].mode === 'hidden') {
// Do not break in case there is a following track with showing.
trackId = id;
} else if (tracks[id].mode === 'showing') {
trackId = id;
break;
}
} // Setting current subtitleTrack will invoke code.
this.subtitleTrack = trackId;
};
_createClass(SubtitleTrackController, [{
key: "subtitleTracks",
get: function get() {
return this.tracksInGroup;
}
/** get/set index of the selected subtitle track (based on index in subtitle track lists) **/
}, {
key: "subtitleTrack",
get: function get() {
return this.trackId;
},
set: function set(newId) {
this.selectDefaultTrack = false;
var lastTrack = this.tracksInGroup ? this.tracksInGroup[this.trackId] : undefined;
this.setSubtitleTrack(newId, lastTrack);
}
}]);
return SubtitleTrackController;
}(_base_playlist_controller__WEBPACK_IMPORTED_MODULE_2__["default"]);
function filterSubtitleTracks(textTrackList) {
var tracks = [];
for (var i = 0; i < textTrackList.length; i++) {
var track = textTrackList[i]; // Edge adds a track without a label; we don't want to use it
if (track.kind === 'subtitles' && track.label) {
tracks.push(textTrackList[i]);
}
}
return tracks;
}
/* harmony default export */ __webpack_exports__["default"] = (SubtitleTrackController);
/***/ }),
/***/ "./src/controller/timeline-controller.ts":
/*!***********************************************!*\
!*** ./src/controller/timeline-controller.ts ***!
\***********************************************/
/*! exports provided: TimelineController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TimelineController", function() { return TimelineController; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/cea-608-parser */ "./src/utils/cea-608-parser.ts");
/* harmony import */ var _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/output-filter */ "./src/utils/output-filter.ts");
/* harmony import */ var _utils_webvtt_parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/webvtt-parser */ "./src/utils/webvtt-parser.ts");
/* harmony import */ var _utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.ts");
/* harmony import */ var _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/imsc1-ttml-parser */ "./src/utils/imsc1-ttml-parser.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var TimelineController = /*#__PURE__*/function () {
function TimelineController(hls) {
this.hls = void 0;
this.media = null;
this.config = void 0;
this.enabled = true;
this.Cues = void 0;
this.textTracks = [];
this.tracks = [];
this.initPTS = [];
this.timescale = [];
this.unparsedVttFrags = [];
this.captionsTracks = {};
this.nonNativeCaptionsTracks = {};
this.cea608Parser1 = void 0;
this.cea608Parser2 = void 0;
this.lastSn = -1;
this.prevCC = -1;
this.vttCCs = newVTTCCs();
this.captionsProperties = void 0;
this.hls = hls;
this.config = hls.config;
this.Cues = hls.config.cueHandler;
this.captionsProperties = {
textTrack1: {
label: this.config.captionsTextTrack1Label,
languageCode: this.config.captionsTextTrack1LanguageCode
},
textTrack2: {
label: this.config.captionsTextTrack2Label,
languageCode: this.config.captionsTextTrack2LanguageCode
},
textTrack3: {
label: this.config.captionsTextTrack3Label,
languageCode: this.config.captionsTextTrack3LanguageCode
},
textTrack4: {
label: this.config.captionsTextTrack4Label,
languageCode: this.config.captionsTextTrack4LanguageCode
}
};
if (this.config.enableCEA708Captions) {
var channel1 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack1');
var channel2 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack2');
var channel3 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack3');
var channel4 = new _utils_output_filter__WEBPACK_IMPORTED_MODULE_3__["default"](this, 'textTrack4');
this.cea608Parser1 = new _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__["default"](1, channel1, channel2);
this.cea608Parser2 = new _utils_cea_608_parser__WEBPACK_IMPORTED_MODULE_2__["default"](3, channel3, channel4);
}
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, this.onFragDecrypted, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this);
}
var _proto = TimelineController.prototype;
_proto.destroy = function destroy() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_ATTACHING, this.onMediaAttaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MEDIA_DETACHING, this.onMediaDetaching, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, this.onManifestLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADING, this.onFragLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, this.onFragLoaded, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, this.onFragDecrypted, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].INIT_PTS_FOUND, this.onInitPtsFound, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].BUFFER_FLUSHING, this.onBufferFlushing, this); // @ts-ignore
this.hls = this.config = this.cea608Parser1 = this.cea608Parser2 = null;
};
_proto.addCues = function addCues(trackName, startTime, endTime, screen, cueRanges) {
// skip cues which overlap more than 50% with previously parsed time ranges
var merged = false;
for (var i = cueRanges.length; i--;) {
var cueRange = cueRanges[i];
var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
if (overlap >= 0) {
cueRange[0] = Math.min(cueRange[0], startTime);
cueRange[1] = Math.max(cueRange[1], endTime);
merged = true;
if (overlap / (endTime - startTime) > 0.5) {
return;
}
}
}
if (!merged) {
cueRanges.push([startTime, endTime]);
}
if (this.config.renderTextTracksNatively) {
var track = this.captionsTracks[trackName];
this.Cues.newCue(track, startTime, endTime, screen);
} else {
var cues = this.Cues.newCue(null, startTime, endTime, screen);
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].CUES_PARSED, {
type: 'captions',
cues: cues,
track: trackName
});
}
} // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
;
_proto.onInitPtsFound = function onInitPtsFound(event, _ref) {
var _this = this;
var frag = _ref.frag,
id = _ref.id,
initPTS = _ref.initPTS,
timescale = _ref.timescale;
var unparsedVttFrags = this.unparsedVttFrags;
if (id === 'main') {
this.initPTS[frag.cc] = initPTS;
this.timescale[frag.cc] = timescale;
} // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
// Parse any unparsed fragments upon receiving the initial PTS.
if (unparsedVttFrags.length) {
this.unparsedVttFrags = [];
unparsedVttFrags.forEach(function (frag) {
_this.onFragLoaded(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, frag);
});
}
};
_proto.getExistingTrack = function getExistingTrack(trackName) {
var media = this.media;
if (media) {
for (var i = 0; i < media.textTracks.length; i++) {
var textTrack = media.textTracks[i];
if (textTrack[trackName]) {
return textTrack;
}
}
}
return null;
};
_proto.createCaptionsTrack = function createCaptionsTrack(trackName) {
if (this.config.renderTextTracksNatively) {
this.createNativeTrack(trackName);
} else {
this.createNonNativeTrack(trackName);
}
};
_proto.createNativeTrack = function createNativeTrack(trackName) {
if (this.captionsTracks[trackName]) {
return;
}
var captionsProperties = this.captionsProperties,
captionsTracks = this.captionsTracks,
media = this.media;
var _captionsProperties$t = captionsProperties[trackName],
label = _captionsProperties$t.label,
languageCode = _captionsProperties$t.languageCode; // Enable reuse of existing text track.
var existingTrack = this.getExistingTrack(trackName);
if (!existingTrack) {
var textTrack = this.createTextTrack('captions', label, languageCode);
if (textTrack) {
// Set a special property on the track so we know it's managed by Hls.js
textTrack[trackName] = true;
captionsTracks[trackName] = textTrack;
}
} else {
captionsTracks[trackName] = existingTrack;
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(captionsTracks[trackName]);
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["sendAddTrackEvent"])(captionsTracks[trackName], media);
}
};
_proto.createNonNativeTrack = function createNonNativeTrack(trackName) {
if (this.nonNativeCaptionsTracks[trackName]) {
return;
} // Create a list of a single track for the provider to consume
var trackProperties = this.captionsProperties[trackName];
if (!trackProperties) {
return;
}
var label = trackProperties.label;
var track = {
_id: trackName,
label: label,
kind: 'captions',
default: trackProperties.media ? !!trackProperties.media.default : false,
closedCaptions: trackProperties.media
};
this.nonNativeCaptionsTracks[trackName] = track;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].NON_NATIVE_TEXT_TRACKS_FOUND, {
tracks: [track]
});
};
_proto.createTextTrack = function createTextTrack(kind, label, lang) {
var media = this.media;
if (!media) {
return;
}
return media.addTextTrack(kind, label, lang);
};
_proto.onMediaAttaching = function onMediaAttaching(event, data) {
this.media = data.media;
this._cleanTracks();
};
_proto.onMediaDetaching = function onMediaDetaching() {
var captionsTracks = this.captionsTracks;
Object.keys(captionsTracks).forEach(function (trackName) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(captionsTracks[trackName]);
delete captionsTracks[trackName];
});
this.nonNativeCaptionsTracks = {};
};
_proto.onManifestLoading = function onManifestLoading() {
this.lastSn = -1; // Detect discontinuity in fragment parsing
this.prevCC = -1;
this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests
this._cleanTracks();
this.tracks = [];
this.captionsTracks = {};
this.nonNativeCaptionsTracks = {};
this.textTracks = [];
this.unparsedVttFrags = this.unparsedVttFrags || [];
this.initPTS = [];
this.timescale = [];
if (this.cea608Parser1 && this.cea608Parser2) {
this.cea608Parser1.reset();
this.cea608Parser2.reset();
}
};
_proto._cleanTracks = function _cleanTracks() {
// clear outdated subtitles
var media = this.media;
if (!media) {
return;
}
var textTracks = media.textTracks;
if (textTracks) {
for (var i = 0; i < textTracks.length; i++) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(textTracks[i]);
}
}
};
_proto.onSubtitleTracksUpdated = function onSubtitleTracksUpdated(event, data) {
var _this2 = this;
this.textTracks = [];
var tracks = data.subtitleTracks || [];
var hasIMSC1 = tracks.some(function (track) {
return track.textCodec === _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"];
});
if (this.config.enableWebVTT || hasIMSC1 && this.config.enableIMSC1) {
var sameTracks = this.tracks && tracks && this.tracks.length === tracks.length;
this.tracks = tracks || [];
if (this.config.renderTextTracksNatively) {
var inUseTracks = this.media ? this.media.textTracks : [];
this.tracks.forEach(function (track, index) {
var textTrack;
if (index < inUseTracks.length) {
var inUseTrack = null;
for (var i = 0; i < inUseTracks.length; i++) {
if (canReuseVttTextTrack(inUseTracks[i], track)) {
inUseTrack = inUseTracks[i];
break;
}
} // Reuse tracks with the same label, but do not reuse 608/708 tracks
if (inUseTrack) {
textTrack = inUseTrack;
}
}
if (textTrack) {
Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["clearCurrentCues"])(textTrack);
} else {
textTrack = _this2.createTextTrack('subtitles', track.name, track.lang);
if (textTrack) {
textTrack.mode = 'disabled';
}
}
if (textTrack) {
textTrack.groupId = track.groupId;
_this2.textTracks.push(textTrack);
}
});
} else if (!sameTracks && this.tracks && this.tracks.length) {
// Create a list of tracks for the provider to consume
var tracksList = this.tracks.map(function (track) {
return {
label: track.name,
kind: track.type.toLowerCase(),
default: track.default,
subtitleTrack: track
};
});
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].NON_NATIVE_TEXT_TRACKS_FOUND, {
tracks: tracksList
});
}
}
};
_proto.onManifestLoaded = function onManifestLoaded(event, data) {
var _this3 = this;
if (this.config.enableCEA708Captions && data.captions) {
data.captions.forEach(function (captionsTrack) {
var instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId);
if (!instreamIdMatch) {
return;
}
var trackName = "textTrack" + instreamIdMatch[1];
var trackProperties = _this3.captionsProperties[trackName];
if (!trackProperties) {
return;
}
trackProperties.label = captionsTrack.name;
if (captionsTrack.lang) {
// optional attribute
trackProperties.languageCode = captionsTrack.lang;
}
trackProperties.media = captionsTrack;
});
}
};
_proto.onFragLoading = function onFragLoading(event, data) {
var cea608Parser1 = this.cea608Parser1,
cea608Parser2 = this.cea608Parser2,
lastSn = this.lastSn;
if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {
return;
} // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
if (data.frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].MAIN) {
var sn = data.frag.sn;
if (sn !== lastSn + 1) {
cea608Parser1.reset();
cea608Parser2.reset();
}
this.lastSn = sn;
}
};
_proto.onFragLoaded = function onFragLoaded(event, data) {
var frag = data.frag,
payload = data.payload;
var initPTS = this.initPTS,
unparsedVttFrags = this.unparsedVttFrags;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].SUBTITLE) {
// If fragment is subtitle type, parse as WebVTT.
if (payload.byteLength) {
// We need an initial synchronisation PTS. Store fragments as long as none has arrived.
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS[frag.cc])) {
unparsedVttFrags.push(data);
if (initPTS.length) {
// finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: false,
frag: frag,
error: new Error('Missing initial subtitle PTS')
});
}
return;
}
var decryptData = frag.decryptdata; // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
if (decryptData == null || decryptData.key == null || decryptData.method !== 'AES-128') {
var trackPlaylistMedia = this.tracks[frag.level];
var vttCCs = this.vttCCs;
if (!vttCCs[frag.cc]) {
vttCCs[frag.cc] = {
start: frag.start,
prevCC: this.prevCC,
new: true
};
this.prevCC = frag.cc;
}
if (trackPlaylistMedia && trackPlaylistMedia.textCodec === _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"]) {
this._parseIMSC1(frag, payload);
} else {
this._parseVTTs(frag, payload, vttCCs);
}
}
} else {
// In case there is no payload, finish unsuccessfully.
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: false,
frag: frag,
error: new Error('Empty subtitle payload')
});
}
}
};
_proto._parseIMSC1 = function _parseIMSC1(frag, payload) {
var _this4 = this;
var hls = this.hls;
Object(_utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["parseIMSC1"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], function (cues) {
_this4._appendCues(cues, frag.level);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: true,
frag: frag
});
}, function (error) {
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("Failed to parse IMSC1: " + error);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: false,
frag: frag,
error: error
});
});
};
_proto._parseVTTs = function _parseVTTs(frag, payload, vttCCs) {
var _this5 = this;
var hls = this.hls; // Parse the WebVTT file contents.
Object(_utils_webvtt_parser__WEBPACK_IMPORTED_MODULE_4__["parseWebVTT"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], vttCCs, frag.cc, frag.start, function (cues) {
_this5._appendCues(cues, frag.level);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: true,
frag: frag
});
}, function (error) {
_this5._fallbackToIMSC1(frag, payload); // Something went wrong while parsing. Trigger event with success false.
_utils_logger__WEBPACK_IMPORTED_MODULE_8__["logger"].log("Failed to parse VTT cue: " + error);
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_FRAG_PROCESSED, {
success: false,
frag: frag,
error: error
});
});
};
_proto._fallbackToIMSC1 = function _fallbackToIMSC1(frag, payload) {
var _this6 = this;
// If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result
var trackPlaylistMedia = this.tracks[frag.level];
if (!trackPlaylistMedia.textCodec) {
Object(_utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["parseIMSC1"])(payload, this.initPTS[frag.cc], this.timescale[frag.cc], function () {
trackPlaylistMedia.textCodec = _utils_imsc1_ttml_parser__WEBPACK_IMPORTED_MODULE_6__["IMSC1_CODEC"];
_this6._parseIMSC1(frag, payload);
}, function () {
trackPlaylistMedia.textCodec = 'wvtt';
});
}
};
_proto._appendCues = function _appendCues(cues, fragLevel) {
var hls = this.hls;
if (this.config.renderTextTracksNatively) {
var textTrack = this.textTracks[fragLevel]; // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
// before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
// and trying to access getCueById method of cues will throw an exception
// Because we check if the mode is disabled, we can force check `cues` below. They can't be null.
if (textTrack.mode === 'disabled') {
return;
}
cues.forEach(function (cue) {
return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["addCueToTrack"])(textTrack, cue);
});
} else {
var currentTrack = this.tracks[fragLevel];
var track = currentTrack.default ? 'default' : 'subtitles' + fragLevel;
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].CUES_PARSED, {
type: 'subtitles',
cues: cues,
track: track
});
}
};
_proto.onFragDecrypted = function onFragDecrypted(event, data) {
var frag = data.frag;
if (frag.type === _types_loader__WEBPACK_IMPORTED_MODULE_7__["PlaylistLevelType"].SUBTITLE) {
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.initPTS[frag.cc])) {
this.unparsedVttFrags.push(data);
return;
}
this.onFragLoaded(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_LOADED, data);
}
};
_proto.onSubtitleTracksCleared = function onSubtitleTracksCleared() {
this.tracks = [];
this.captionsTracks = {};
};
_proto.onFragParsingUserdata = function onFragParsingUserdata(event, data) {
var cea608Parser1 = this.cea608Parser1,
cea608Parser2 = this.cea608Parser2;
if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {
return;
} // If the event contains captions (found in the bytes property), push all bytes into the parser immediately
// It will create the proper timestamps based on the PTS value
for (var i = 0; i < data.samples.length; i++) {
var ccBytes = data.samples[i].bytes;
if (ccBytes) {
var ccdatas = this.extractCea608Data(ccBytes);
cea608Parser1.addData(data.samples[i].pts, ccdatas[0]);
cea608Parser2.addData(data.samples[i].pts, ccdatas[1]);
}
}
};
_proto.onBufferFlushing = function onBufferFlushing(event, _ref2) {
var startOffset = _ref2.startOffset,
endOffset = _ref2.endOffset,
type = _ref2.type;
// Clear 608 CC cues from the back buffer
// Forward cues are never removed because we can loose streamed 608 content from recent fragments
if (!type || type === 'video') {
var media = this.media;
if (!media || media.currentTime < endOffset) {
return;
}
var captionsTracks = this.captionsTracks;
Object.keys(captionsTracks).forEach(function (trackName) {
return Object(_utils_texttrack_utils__WEBPACK_IMPORTED_MODULE_5__["removeCuesInRange"])(captionsTracks[trackName], startOffset, endOffset);
});
}
};
_proto.extractCea608Data = function extractCea608Data(byteArray) {
var count = byteArray[0] & 31;
var position = 2;
var actualCCBytes = [[], []];
for (var j = 0; j < count; j++) {
var tmpByte = byteArray[position++];
var ccbyte1 = 0x7f & byteArray[position++];
var ccbyte2 = 0x7f & byteArray[position++];
var ccValid = (4 & tmpByte) !== 0;
var ccType = 3 & tmpByte;
if (ccbyte1 === 0 && ccbyte2 === 0) {
continue;
}
if (ccValid) {
if (ccType === 0 || ccType === 1) {
actualCCBytes[ccType].push(ccbyte1);
actualCCBytes[ccType].push(ccbyte2);
}
}
}
return actualCCBytes;
};
return TimelineController;
}();
function canReuseVttTextTrack(inUseTrack, manifestTrack) {
return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
}
function intersection(x1, x2, y1, y2) {
return Math.min(x2, y2) - Math.max(x1, y1);
}
function newVTTCCs() {
return {
ccOffset: 0,
presentationOffset: 0,
0: {
start: 0,
prevCC: -1,
new: false
}
};
}
/***/ }),
/***/ "./src/crypt/aes-crypto.ts":
/*!*********************************!*\
!*** ./src/crypt/aes-crypto.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESCrypto; });
var AESCrypto = /*#__PURE__*/function () {
function AESCrypto(subtle, iv) {
this.subtle = void 0;
this.aesIV = void 0;
this.subtle = subtle;
this.aesIV = iv;
}
var _proto = AESCrypto.prototype;
_proto.decrypt = function decrypt(data, key) {
return this.subtle.decrypt({
name: 'AES-CBC',
iv: this.aesIV
}, key, data);
};
return AESCrypto;
}();
/***/ }),
/***/ "./src/crypt/aes-decryptor.ts":
/*!************************************!*\
!*** ./src/crypt/aes-decryptor.ts ***!
\************************************/
/*! exports provided: removePadding, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removePadding", function() { return removePadding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AESDecryptor; });
/* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
// PKCS7
function removePadding(array) {
var outputBytes = array.byteLength;
var paddingBytes = outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);
if (paddingBytes) {
return Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(array, 0, outputBytes - paddingBytes);
}
return array;
}
var AESDecryptor = /*#__PURE__*/function () {
function AESDecryptor() {
this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
this.sBox = new Uint32Array(256);
this.invSBox = new Uint32Array(256);
this.key = new Uint32Array(0);
this.ksRows = 0;
this.keySize = 0;
this.keySchedule = void 0;
this.invKeySchedule = void 0;
this.initTable();
} // Using view.getUint32() also swaps the byte order.
var _proto = AESDecryptor.prototype;
_proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
var view = new DataView(arrayBuffer);
var newArray = new Uint32Array(4);
for (var i = 0; i < 4; i++) {
newArray[i] = view.getUint32(i * 4);
}
return newArray;
};
_proto.initTable = function initTable() {
var sBox = this.sBox;
var invSBox = this.invSBox;
var subMix = this.subMix;
var subMix0 = subMix[0];
var subMix1 = subMix[1];
var subMix2 = subMix[2];
var subMix3 = subMix[3];
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var d = new Uint32Array(256);
var x = 0;
var xi = 0;
var i = 0;
for (i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = i << 1 ^ 0x11b;
}
}
for (i = 0; i < 256; i++) {
var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
sBox[x] = sx;
invSBox[sx] = x; // Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4]; // Compute sub/invSub bytes, mix columns tables
var t = d[sx] * 0x101 ^ sx * 0x1010100;
subMix0[x] = t << 24 | t >>> 8;
subMix1[x] = t << 16 | t >>> 16;
subMix2[x] = t << 8 | t >>> 24;
subMix3[x] = t; // Compute inv sub bytes, inv mix columns tables
t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
invSubMix0[sx] = t << 24 | t >>> 8;
invSubMix1[sx] = t << 16 | t >>> 16;
invSubMix2[sx] = t << 8 | t >>> 24;
invSubMix3[sx] = t; // Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
};
_proto.expandKey = function expandKey(keyBuffer) {
// convert keyBuffer to Uint32Array
var key = this.uint8ArrayToUint32Array_(keyBuffer);
var sameKey = true;
var offset = 0;
while (offset < key.length && sameKey) {
sameKey = key[offset] === this.key[offset];
offset++;
}
if (sameKey) {
return;
}
this.key = key;
var keySize = this.keySize = key.length;
if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
throw new Error('Invalid aes key size=' + keySize);
}
var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
var ksRow;
var invKsRow;
var keySchedule = this.keySchedule = new Uint32Array(ksRows);
var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
var sbox = this.sBox;
var rcon = this.rcon;
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var prev;
var t;
for (ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
prev = keySchedule[ksRow] = key[ksRow];
continue;
}
t = prev;
if (ksRow % keySize === 0) {
// Rot word
t = t << 8 | t >>> 24; // Sub word
t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; // Mix Rcon
t ^= rcon[ksRow / keySize | 0] << 24;
} else if (keySize > 6 && ksRow % keySize === 4) {
// Sub word
t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
}
keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
}
for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
ksRow = ksRows - invKsRow;
if (invKsRow & 3) {
t = keySchedule[ksRow];
} else {
t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
}
invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
}
} // Adding this as a method greatly improves performance.
;
_proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
};
_proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV) {
var nRounds = this.keySize + 6;
var invKeySchedule = this.invKeySchedule;
var invSBOX = this.invSBox;
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var initVector = this.uint8ArrayToUint32Array_(aesIV);
var initVector0 = initVector[0];
var initVector1 = initVector[1];
var initVector2 = initVector[2];
var initVector3 = initVector[3];
var inputInt32 = new Int32Array(inputArrayBuffer);
var outputInt32 = new Int32Array(inputInt32.length);
var t0, t1, t2, t3;
var s0, s1, s2, s3;
var inputWords0, inputWords1, inputWords2, inputWords3;
var ksRow, i;
var swapWord = this.networkToHostOrderSwap;
while (offset < inputInt32.length) {
inputWords0 = swapWord(inputInt32[offset]);
inputWords1 = swapWord(inputInt32[offset + 1]);
inputWords2 = swapWord(inputInt32[offset + 2]);
inputWords3 = swapWord(inputInt32[offset + 3]);
s0 = inputWords0 ^ invKeySchedule[0];
s1 = inputWords3 ^ invKeySchedule[1];
s2 = inputWords2 ^ invKeySchedule[2];
s3 = inputWords1 ^ invKeySchedule[3];
ksRow = 4; // Iterate through the rounds of decryption
for (i = 1; i < nRounds; i++) {
t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
ksRow = ksRow + 4;
} // Shift rows, sub bytes, add round key
t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Write
outputInt32[offset] = swapWord(t0 ^ initVector0);
outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
outputInt32[offset + 3] = swapWord(t1 ^ initVector3); // reset initVector to last 4 unsigned int
initVector0 = inputWords0;
initVector1 = inputWords1;
initVector2 = inputWords2;
initVector3 = inputWords3;
offset = offset + 4;
}
return outputInt32.buffer;
};
return AESDecryptor;
}();
/***/ }),
/***/ "./src/crypt/decrypter.ts":
/*!********************************!*\
!*** ./src/crypt/decrypter.ts ***!
\********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Decrypter; });
/* harmony import */ var _aes_crypto__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./aes-crypto */ "./src/crypt/aes-crypto.ts");
/* harmony import */ var _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fast-aes-key */ "./src/crypt/fast-aes-key.ts");
/* harmony import */ var _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./aes-decryptor */ "./src/crypt/aes-decryptor.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
var CHUNK_SIZE = 16; // 16 bytes, 128 bits
var Decrypter = /*#__PURE__*/function () {
function Decrypter(observer, config, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$removePKCS7Paddi = _ref.removePKCS7Padding,
removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
this.logEnabled = true;
this.observer = void 0;
this.config = void 0;
this.removePKCS7Padding = void 0;
this.subtle = null;
this.softwareDecrypter = null;
this.key = null;
this.fastAesKey = null;
this.remainderData = null;
this.currentIV = null;
this.currentResult = null;
this.observer = observer;
this.config = config;
this.removePKCS7Padding = removePKCS7Padding; // built in decryptor expects PKCS7 padding
if (removePKCS7Padding) {
try {
var browserCrypto = self.crypto;
if (browserCrypto) {
this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
}
} catch (e) {
/* no-op */
}
}
if (this.subtle === null) {
this.config.enableSoftwareAES = true;
}
}
var _proto = Decrypter.prototype;
_proto.destroy = function destroy() {
// @ts-ignore
this.observer = null;
};
_proto.isSync = function isSync() {
return this.config.enableSoftwareAES;
};
_proto.flush = function flush() {
var currentResult = this.currentResult;
if (!currentResult) {
this.reset();
return;
}
var data = new Uint8Array(currentResult);
this.reset();
if (this.removePKCS7Padding) {
return Object(_aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["removePadding"])(data);
}
return data;
};
_proto.reset = function reset() {
this.currentResult = null;
this.currentIV = null;
this.remainderData = null;
if (this.softwareDecrypter) {
this.softwareDecrypter = null;
}
};
_proto.decrypt = function decrypt(data, key, iv, callback) {
if (this.config.enableSoftwareAES) {
this.softwareDecrypt(new Uint8Array(data), key, iv);
var decryptResult = this.flush();
if (decryptResult) {
callback(decryptResult.buffer);
}
} else {
this.webCryptoDecrypt(new Uint8Array(data), key, iv).then(callback);
}
};
_proto.softwareDecrypt = function softwareDecrypt(data, key, iv) {
var currentIV = this.currentIV,
currentResult = this.currentResult,
remainderData = this.remainderData;
this.logOnce('JS AES decrypt'); // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call
// This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached
// the end on flush(), but by that time we have already received all bytes for the segment.
// Progressive decryption does not work with WebCrypto
if (remainderData) {
data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["appendUint8Array"])(remainderData, data);
this.remainderData = null;
} // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)
var currentChunk = this.getValidChunk(data);
if (!currentChunk.length) {
return null;
}
if (currentIV) {
iv = currentIV;
}
var softwareDecrypter = this.softwareDecrypter;
if (!softwareDecrypter) {
softwareDecrypter = this.softwareDecrypter = new _aes_decryptor__WEBPACK_IMPORTED_MODULE_2__["default"]();
}
softwareDecrypter.expandKey(key);
var result = currentResult;
this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);
this.currentIV = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(currentChunk, -16).buffer;
if (!result) {
return null;
}
return result;
};
_proto.webCryptoDecrypt = function webCryptoDecrypt(data, key, iv) {
var _this = this;
var subtle = this.subtle;
if (this.key !== key || !this.fastAesKey) {
this.key = key;
this.fastAesKey = new _fast_aes_key__WEBPACK_IMPORTED_MODULE_1__["default"](subtle, key);
}
return this.fastAesKey.expandKey().then(function (aesKey) {
// decrypt using web crypto
if (!subtle) {
return Promise.reject(new Error('web crypto not initialized'));
}
var crypto = new _aes_crypto__WEBPACK_IMPORTED_MODULE_0__["default"](subtle, iv);
return crypto.decrypt(data.buffer, aesKey);
}).catch(function (err) {
return _this.onWebCryptoError(err, data, key, iv);
});
};
_proto.onWebCryptoError = function onWebCryptoError(err, data, key, iv) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[decrypter.ts]: WebCrypto Error, disable WebCrypto API:', err);
this.config.enableSoftwareAES = true;
this.logEnabled = true;
return this.softwareDecrypt(data, key, iv);
};
_proto.getValidChunk = function getValidChunk(data) {
var currentChunk = data;
var splitPoint = data.length - data.length % CHUNK_SIZE;
if (splitPoint !== data.length) {
currentChunk = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, 0, splitPoint);
this.remainderData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_5__["sliceUint8"])(data, splitPoint);
}
return currentChunk;
};
_proto.logOnce = function logOnce(msg) {
if (!this.logEnabled) {
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[decrypter.ts]: " + msg);
this.logEnabled = false;
};
return Decrypter;
}();
/***/ }),
/***/ "./src/crypt/fast-aes-key.ts":
/*!***********************************!*\
!*** ./src/crypt/fast-aes-key.ts ***!
\***********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FastAESKey; });
var FastAESKey = /*#__PURE__*/function () {
function FastAESKey(subtle, key) {
this.subtle = void 0;
this.key = void 0;
this.subtle = subtle;
this.key = key;
}
var _proto = FastAESKey.prototype;
_proto.expandKey = function expandKey() {
return this.subtle.importKey('raw', this.key, {
name: 'AES-CBC'
}, false, ['encrypt', 'decrypt']);
};
return FastAESKey;
}();
/***/ }),
/***/ "./src/demux/aacdemuxer.ts":
/*!*********************************!*\
!*** ./src/demux/aacdemuxer.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts");
/* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/**
* AAC demuxer
*/
var AACDemuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
_inheritsLoose(AACDemuxer, _BaseAudioDemuxer);
function AACDemuxer(observer, config) {
var _this;
_this = _BaseAudioDemuxer.call(this) || this;
_this.observer = void 0;
_this.config = void 0;
_this.observer = observer;
_this.config = config;
return _this;
}
var _proto = AACDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
_BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration);
this._audioTrack = {
container: 'audio/adts',
type: 'audio',
id: 0,
pid: -1,
sequenceNumber: 0,
isAAC: true,
samples: [],
manifestCodec: audioCodec,
duration: duration,
inputTimeScale: 90000,
dropped: 0
};
} // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS
;
AACDemuxer.probe = function probe(data) {
if (!data) {
return false;
} // Check for the ADTS sync word
// Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
// Layer bits (position 14 and 15) in header should be always 0 for ADTS
// More info https://wiki.multimedia.cx/index.php?title=ADTS
var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_3__["getID3Data"](data, 0) || [];
var offset = id3Data.length;
for (var length = data.length; offset < length; offset++) {
if (_adts__WEBPACK_IMPORTED_MODULE_1__["probe"](data, offset)) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('ADTS sync word found !');
return true;
}
}
return false;
};
_proto.canParse = function canParse(data, offset) {
return _adts__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset);
};
_proto.appendFrame = function appendFrame(track, data, offset) {
_adts__WEBPACK_IMPORTED_MODULE_1__["initTrackConfig"](track, this.observer, data, offset, track.manifestCodec);
return _adts__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex);
};
return AACDemuxer;
}(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]);
AACDemuxer.minProbeByteLength = 9;
/* harmony default export */ __webpack_exports__["default"] = (AACDemuxer);
/***/ }),
/***/ "./src/demux/adts.ts":
/*!***************************!*\
!*** ./src/demux/adts.ts ***!
\***************************/
/*! exports provided: getAudioConfig, isHeaderPattern, getHeaderLength, getFullFrameLength, canGetFrameLength, isHeader, canParse, probe, initTrackConfig, getFrameDuration, parseFrameHeader, appendFrame */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAudioConfig", function() { return getAudioConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHeaderLength", function() { return getHeaderLength; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFullFrameLength", function() { return getFullFrameLength; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canGetFrameLength", function() { return canGetFrameLength; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initTrackConfig", function() { return initTrackConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFrameDuration", function() { return getFrameDuration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseFrameHeader", function() { return parseFrameHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/**
* ADTS parser helper
* @link https://wiki.multimedia.cx/index.php?title=ADTS
*/
function getAudioConfig(observer, data, offset, audioCodec) {
var adtsObjectType;
var adtsExtensionSamplingIndex;
var adtsChanelConfig;
var config;
var userAgent = navigator.userAgent.toLowerCase();
var manifestCodec = audioCodec;
var adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; // byte 2
adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;
var adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;
if (adtsSamplingIndex > adtsSampleingRates.length - 1) {
observer.trigger(_events__WEBPACK_IMPORTED_MODULE_2__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: true,
reason: "invalid ADTS sampling index:" + adtsSamplingIndex
});
return;
}
adtsChanelConfig = (data[offset + 2] & 0x01) << 2; // byte 3
adtsChanelConfig |= (data[offset + 3] & 0xc0) >>> 6;
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("manifest codec:" + audioCodec + ", ADTS type:" + adtsObjectType + ", samplingIndex:" + adtsSamplingIndex); // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
if (/firefox/i.test(userAgent)) {
if (adtsSamplingIndex >= 6) {
adtsObjectType = 5;
config = new Array(4); // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
// there is a factor 2 between frame sample rate and output sample rate
// multiply frequency by 2 (see table below, equivalent to substract 3)
adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
} else {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSamplingIndex = adtsSamplingIndex;
} // Android : always use AAC
} else if (userAgent.indexOf('android') !== -1) {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSamplingIndex = adtsSamplingIndex;
} else {
/* for other browsers (Chrome/Vivaldi/Opera ...)
always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
*/
adtsObjectType = 5;
config = new Array(4); // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSamplingIndex >= 6) {
// HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
// there is a factor 2 between frame sample rate and output sample rate
// multiply frequency by 2 (see table below, equivalent to substract 3)
adtsExtensionSamplingIndex = adtsSamplingIndex - 3;
} else {
// if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
// Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSamplingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) {
adtsObjectType = 2;
config = new Array(2);
}
adtsExtensionSamplingIndex = adtsSamplingIndex;
}
}
/* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
Audio Profile / Audio Object Type
0: Null
1: AAC Main
2: AAC LC (Low Complexity)
3: AAC SSR (Scalable Sample Rate)
4: AAC LTP (Long Term Prediction)
5: SBR (Spectral Band Replication)
6: AAC Scalable
sampling freq
0: 96000 Hz
1: 88200 Hz
2: 64000 Hz
3: 48000 Hz
4: 44100 Hz
5: 32000 Hz
6: 24000 Hz
7: 22050 Hz
8: 16000 Hz
9: 12000 Hz
10: 11025 Hz
11: 8000 Hz
12: 7350 Hz
13: Reserved
14: Reserved
15: frequency is written explictly
Channel Configurations
These are the channel configurations:
0: Defined in AOT Specifc Config
1: 1 channel: front-center
2: 2 channels: front-left, front-right
*/
// audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
config[0] = adtsObjectType << 3; // samplingFrequencyIndex
config[0] |= (adtsSamplingIndex & 0x0e) >> 1;
config[1] |= (adtsSamplingIndex & 0x01) << 7; // channelConfiguration
config[1] |= adtsChanelConfig << 3;
if (adtsObjectType === 5) {
// adtsExtensionSampleingIndex
config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;
config[2] = (adtsExtensionSamplingIndex & 0x01) << 7; // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
// https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
config[2] |= 2 << 2;
config[3] = 0;
}
return {
config: config,
samplerate: adtsSampleingRates[adtsSamplingIndex],
channelCount: adtsChanelConfig,
codec: 'mp4a.40.' + adtsObjectType,
manifestCodec: manifestCodec
};
}
function isHeaderPattern(data, offset) {
return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
}
function getHeaderLength(data, offset) {
return data[offset + 1] & 0x01 ? 7 : 9;
}
function getFullFrameLength(data, offset) {
return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xe0) >>> 5;
}
function canGetFrameLength(data, offset) {
return offset + 5 < data.length;
}
function isHeader(data, offset) {
// Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
// Layer bits (position 14 and 15) in header should be always 0 for ADTS
// More info https://wiki.multimedia.cx/index.php?title=ADTS
return offset + 1 < data.length && isHeaderPattern(data, offset);
}
function canParse(data, offset) {
return canGetFrameLength(data, offset) && isHeaderPattern(data, offset) && getFullFrameLength(data, offset) <= data.length - offset;
}
function probe(data, offset) {
// same as isHeader but we also check that ADTS frame follows last ADTS frame
// or end of data is reached
if (isHeader(data, offset)) {
// ADTS header Length
var headerLength = getHeaderLength(data, offset);
if (offset + headerLength >= data.length) {
return false;
} // ADTS frame Length
var frameLength = getFullFrameLength(data, offset);
if (frameLength <= headerLength) {
return false;
}
var newOffset = offset + frameLength;
return newOffset === data.length || isHeader(data, newOffset);
}
return false;
}
function initTrackConfig(track, observer, data, offset, audioCodec) {
if (!track.samplerate) {
var config = getAudioConfig(observer, data, offset, audioCodec);
if (!config) {
return;
}
track.config = config.config;
track.samplerate = config.samplerate;
track.channelCount = config.channelCount;
track.codec = config.codec;
track.manifestCodec = config.manifestCodec;
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("parsed codec:" + track.codec + ", rate:" + config.samplerate + ", channels:" + config.channelCount);
}
}
function getFrameDuration(samplerate) {
return 1024 * 90000 / samplerate;
}
function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
var length = data.length; // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
var headerLength = getHeaderLength(data, offset); // retrieve frame size
var frameLength = getFullFrameLength(data, offset);
frameLength -= headerLength;
if (frameLength > 0 && offset + headerLength + frameLength <= length) {
var stamp = pts + frameIndex * frameDuration; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
return {
headerLength: headerLength,
frameLength: frameLength,
stamp: stamp
};
}
}
function appendFrame(track, data, offset, pts, frameIndex) {
var frameDuration = getFrameDuration(track.samplerate);
var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
if (header) {
var stamp = header.stamp;
var headerLength = header.headerLength;
var frameLength = header.frameLength; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
var aacSample = {
unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),
pts: stamp,
dts: stamp
};
track.samples.push(aacSample);
return {
sample: aacSample,
length: frameLength + headerLength
};
}
}
/***/ }),
/***/ "./src/demux/base-audio-demuxer.ts":
/*!*****************************************!*\
!*** ./src/demux/base-audio-demuxer.ts ***!
\*****************************************/
/*! exports provided: initPTSFn, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initPTSFn", function() { return initPTSFn; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_typed_array__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/typed-array */ "./src/utils/typed-array.ts");
var BaseAudioDemuxer = /*#__PURE__*/function () {
function BaseAudioDemuxer() {
this._audioTrack = void 0;
this._id3Track = void 0;
this.frameIndex = 0;
this.cachedData = null;
this.initPTS = null;
}
var _proto = BaseAudioDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
this._id3Track = {
type: 'id3',
id: 0,
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: 0
};
};
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetContiguity = function resetContiguity() {};
_proto.canParse = function canParse(data, offset) {
return false;
};
_proto.appendFrame = function appendFrame(track, data, offset) {} // feed incoming data to the front of the parsing pipeline
;
_proto.demux = function demux(data, timeOffset) {
if (this.cachedData) {
data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, data);
this.cachedData = null;
}
var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0);
var offset = id3Data ? id3Data.length : 0;
var lastDataIndex;
var pts;
var track = this._audioTrack;
var id3Track = this._id3Track;
var timestamp = id3Data ? _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getTimeStamp"](id3Data) : undefined;
var length = data.length;
if (this.frameIndex === 0 || this.initPTS === null) {
this.initPTS = initPTSFn(timestamp, timeOffset);
} // more expressive than alternative: id3Data?.length
if (id3Data && id3Data.length > 0) {
id3Track.samples.push({
pts: this.initPTS,
dts: this.initPTS,
data: id3Data
});
}
pts = this.initPTS;
while (offset < length) {
if (this.canParse(data, offset)) {
var frame = this.appendFrame(track, data, offset);
if (frame) {
this.frameIndex++;
pts = frame.sample.pts;
offset += frame.length;
lastDataIndex = offset;
} else {
offset = length;
}
} else if (_demux_id3__WEBPACK_IMPORTED_MODULE_1__["canParse"](data, offset)) {
// after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data
id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, offset);
id3Track.samples.push({
pts: pts,
dts: pts,
data: id3Data
});
offset += id3Data.length;
lastDataIndex = offset;
} else {
offset++;
}
if (offset === length && lastDataIndex !== length) {
var partialData = Object(_utils_typed_array__WEBPACK_IMPORTED_MODULE_4__["sliceUint8"])(data, lastDataIndex);
if (this.cachedData) {
this.cachedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_3__["appendUint8Array"])(this.cachedData, partialData);
} else {
this.cachedData = partialData;
}
}
}
return {
audioTrack: track,
avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(),
id3Track: id3Track,
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])()
};
};
_proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
return Promise.reject(new Error("[" + this + "] This demuxer does not support Sample-AES decryption"));
};
_proto.flush = function flush(timeOffset) {
// Parse cache in case of remaining frames.
var cachedData = this.cachedData;
if (cachedData) {
this.cachedData = null;
this.demux(cachedData, 0);
}
this.frameIndex = 0;
return {
audioTrack: this._audioTrack,
avcTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])(),
id3Track: this._id3Track,
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_2__["dummyTrack"])()
};
};
_proto.destroy = function destroy() {};
return BaseAudioDemuxer;
}();
/**
* Initialize PTS
* <p>
* use timestamp unless it is undefined, NaN or Infinity
* </p>
*/
var initPTSFn = function initPTSFn(timestamp, timeOffset) {
return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(timestamp) ? timestamp * 90 : timeOffset * 90000;
};
/* harmony default export */ __webpack_exports__["default"] = (BaseAudioDemuxer);
/***/ }),
/***/ "./src/demux/chunk-cache.ts":
/*!**********************************!*\
!*** ./src/demux/chunk-cache.ts ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ChunkCache; });
var ChunkCache = /*#__PURE__*/function () {
function ChunkCache() {
this.chunks = [];
this.dataLength = 0;
}
var _proto = ChunkCache.prototype;
_proto.push = function push(chunk) {
this.chunks.push(chunk);
this.dataLength += chunk.length;
};
_proto.flush = function flush() {
var chunks = this.chunks,
dataLength = this.dataLength;
var result;
if (!chunks.length) {
return new Uint8Array(0);
} else if (chunks.length === 1) {
result = chunks[0];
} else {
result = concatUint8Arrays(chunks, dataLength);
}
this.reset();
return result;
};
_proto.reset = function reset() {
this.chunks.length = 0;
this.dataLength = 0;
};
return ChunkCache;
}();
function concatUint8Arrays(chunks, dataLength) {
var result = new Uint8Array(dataLength);
var offset = 0;
for (var i = 0; i < chunks.length; i++) {
var chunk = chunks[i];
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
/***/ }),
/***/ "./src/demux/dummy-demuxed-track.ts":
/*!******************************************!*\
!*** ./src/demux/dummy-demuxed-track.ts ***!
\******************************************/
/*! exports provided: dummyTrack */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dummyTrack", function() { return dummyTrack; });
function dummyTrack() {
return {
type: '',
id: -1,
pid: -1,
inputTimeScale: 90000,
sequenceNumber: -1,
samples: [],
dropped: 0
};
}
/***/ }),
/***/ "./src/demux/exp-golomb.ts":
/*!*********************************!*\
!*** ./src/demux/exp-golomb.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
* Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
*/
var ExpGolomb = /*#__PURE__*/function () {
function ExpGolomb(data) {
this.data = void 0;
this.bytesAvailable = void 0;
this.word = void 0;
this.bitsAvailable = void 0;
this.data = data; // the number of bytes left to examine in this.data
this.bytesAvailable = data.byteLength; // the current word being examined
this.word = 0; // :uint
// the number of bits left to examine in the current word
this.bitsAvailable = 0; // :uint
} // ():void
var _proto = ExpGolomb.prototype;
_proto.loadWord = function loadWord() {
var data = this.data;
var bytesAvailable = this.bytesAvailable;
var position = data.byteLength - bytesAvailable;
var workingBytes = new Uint8Array(4);
var availableBytes = Math.min(4, bytesAvailable);
if (availableBytes === 0) {
throw new Error('no bytes available');
}
workingBytes.set(data.subarray(position, position + availableBytes));
this.word = new DataView(workingBytes.buffer).getUint32(0); // track the amount of this.data that has been processed
this.bitsAvailable = availableBytes * 8;
this.bytesAvailable -= availableBytes;
} // (count:int):void
;
_proto.skipBits = function skipBits(count) {
var skipBytes; // :int
if (this.bitsAvailable > count) {
this.word <<= count;
this.bitsAvailable -= count;
} else {
count -= this.bitsAvailable;
skipBytes = count >> 3;
count -= skipBytes >> 3;
this.bytesAvailable -= skipBytes;
this.loadWord();
this.word <<= count;
this.bitsAvailable -= count;
}
} // (size:int):uint
;
_proto.readBits = function readBits(size) {
var bits = Math.min(this.bitsAvailable, size); // :uint
var valu = this.word >>> 32 - bits; // :uint
if (size > 32) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error('Cannot read more than 32 bits at a time');
}
this.bitsAvailable -= bits;
if (this.bitsAvailable > 0) {
this.word <<= bits;
} else if (this.bytesAvailable > 0) {
this.loadWord();
}
bits = size - bits;
if (bits > 0 && this.bitsAvailable) {
return valu << bits | this.readBits(bits);
} else {
return valu;
}
} // ():uint
;
_proto.skipLZ = function skipLZ() {
var leadingZeroCount; // :uint
for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
// the first bit of working word is 1
this.word <<= leadingZeroCount;
this.bitsAvailable -= leadingZeroCount;
return leadingZeroCount;
}
} // we exhausted word and still have not found a 1
this.loadWord();
return leadingZeroCount + this.skipLZ();
} // ():void
;
_proto.skipUEG = function skipUEG() {
this.skipBits(1 + this.skipLZ());
} // ():void
;
_proto.skipEG = function skipEG() {
this.skipBits(1 + this.skipLZ());
} // ():uint
;
_proto.readUEG = function readUEG() {
var clz = this.skipLZ(); // :uint
return this.readBits(clz + 1) - 1;
} // ():int
;
_proto.readEG = function readEG() {
var valu = this.readUEG(); // :int
if (0x01 & valu) {
// the number is odd if the low order bit is set
return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
} else {
return -1 * (valu >>> 1); // divide by two then make it negative
}
} // Some convenience functions
// :Boolean
;
_proto.readBoolean = function readBoolean() {
return this.readBits(1) === 1;
} // ():int
;
_proto.readUByte = function readUByte() {
return this.readBits(8);
} // ():int
;
_proto.readUShort = function readUShort() {
return this.readBits(16);
} // ():int
;
_proto.readUInt = function readUInt() {
return this.readBits(32);
}
/**
* Advance the ExpGolomb decoder past a scaling list. The scaling
* list is optionally transmitted as part of a sequence parameter
* set and is not relevant to transmuxing.
* @param count the number of entries in this scaling list
* @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
*/
;
_proto.skipScalingList = function skipScalingList(count) {
var lastScale = 8;
var nextScale = 8;
var deltaScale;
for (var j = 0; j < count; j++) {
if (nextScale !== 0) {
deltaScale = this.readEG();
nextScale = (lastScale + deltaScale + 256) % 256;
}
lastScale = nextScale === 0 ? lastScale : nextScale;
}
}
/**
* Read a sequence parameter set and return some interesting video
* properties. A sequence parameter set is the H264 metadata that
* describes the properties of upcoming video frames.
* @param data {Uint8Array} the bytes of a sequence parameter set
* @return {object} an object with configuration parsed from the
* sequence parameter set, including the dimensions of the
* associated video frames.
*/
;
_proto.readSPS = function readSPS() {
var frameCropLeftOffset = 0;
var frameCropRightOffset = 0;
var frameCropTopOffset = 0;
var frameCropBottomOffset = 0;
var numRefFramesInPicOrderCntCycle;
var scalingListCount;
var i;
var readUByte = this.readUByte.bind(this);
var readBits = this.readBits.bind(this);
var readUEG = this.readUEG.bind(this);
var readBoolean = this.readBoolean.bind(this);
var skipBits = this.skipBits.bind(this);
var skipEG = this.skipEG.bind(this);
var skipUEG = this.skipUEG.bind(this);
var skipScalingList = this.skipScalingList.bind(this);
readUByte();
var profileIdc = readUByte(); // profile_idc
readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)
skipBits(3); // reserved_zero_3bits u(3),
readUByte(); // level_idc u(8)
skipUEG(); // seq_parameter_set_id
// some profiles have more optional data we don't need
if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
var chromaFormatIdc = readUEG();
if (chromaFormatIdc === 3) {
skipBits(1);
} // separate_colour_plane_flag
skipUEG(); // bit_depth_luma_minus8
skipUEG(); // bit_depth_chroma_minus8
skipBits(1); // qpprime_y_zero_transform_bypass_flag
if (readBoolean()) {
// seq_scaling_matrix_present_flag
scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
for (i = 0; i < scalingListCount; i++) {
if (readBoolean()) {
// seq_scaling_list_present_flag[ i ]
if (i < 6) {
skipScalingList(16);
} else {
skipScalingList(64);
}
}
}
}
}
skipUEG(); // log2_max_frame_num_minus4
var picOrderCntType = readUEG();
if (picOrderCntType === 0) {
readUEG(); // log2_max_pic_order_cnt_lsb_minus4
} else if (picOrderCntType === 1) {
skipBits(1); // delta_pic_order_always_zero_flag
skipEG(); // offset_for_non_ref_pic
skipEG(); // offset_for_top_to_bottom_field
numRefFramesInPicOrderCntCycle = readUEG();
for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
skipEG();
} // offset_for_ref_frame[ i ]
}
skipUEG(); // max_num_ref_frames
skipBits(1); // gaps_in_frame_num_value_allowed_flag
var picWidthInMbsMinus1 = readUEG();
var picHeightInMapUnitsMinus1 = readUEG();
var frameMbsOnlyFlag = readBits(1);
if (frameMbsOnlyFlag === 0) {
skipBits(1);
} // mb_adaptive_frame_field_flag
skipBits(1); // direct_8x8_inference_flag
if (readBoolean()) {
// frame_cropping_flag
frameCropLeftOffset = readUEG();
frameCropRightOffset = readUEG();
frameCropTopOffset = readUEG();
frameCropBottomOffset = readUEG();
}
var pixelRatio = [1, 1];
if (readBoolean()) {
// vui_parameters_present_flag
if (readBoolean()) {
// aspect_ratio_info_present_flag
var aspectRatioIdc = readUByte();
switch (aspectRatioIdc) {
case 1:
pixelRatio = [1, 1];
break;
case 2:
pixelRatio = [12, 11];
break;
case 3:
pixelRatio = [10, 11];
break;
case 4:
pixelRatio = [16, 11];
break;
case 5:
pixelRatio = [40, 33];
break;
case 6:
pixelRatio = [24, 11];
break;
case 7:
pixelRatio = [20, 11];
break;
case 8:
pixelRatio = [32, 11];
break;
case 9:
pixelRatio = [80, 33];
break;
case 10:
pixelRatio = [18, 11];
break;
case 11:
pixelRatio = [15, 11];
break;
case 12:
pixelRatio = [64, 33];
break;
case 13:
pixelRatio = [160, 99];
break;
case 14:
pixelRatio = [4, 3];
break;
case 15:
pixelRatio = [3, 2];
break;
case 16:
pixelRatio = [2, 1];
break;
case 255:
{
pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
break;
}
}
}
}
return {
width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
pixelRatio: pixelRatio
};
};
_proto.readSliceType = function readSliceType() {
// skip NALu type
this.readUByte(); // discard first_mb_in_slice
this.readUEG(); // return slice_type
return this.readUEG();
};
return ExpGolomb;
}();
/* harmony default export */ __webpack_exports__["default"] = (ExpGolomb);
/***/ }),
/***/ "./src/demux/id3.ts":
/*!**************************!*\
!*** ./src/demux/id3.ts ***!
\**************************/
/*! exports provided: isHeader, isFooter, getID3Data, canParse, getTimeStamp, isTimeStampFrame, getID3Frames, decodeFrame, utf8ArrayToStr, testables */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFooter", function() { return isFooter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Data", function() { return getID3Data; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getTimeStamp", function() { return getTimeStamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTimeStampFrame", function() { return isTimeStampFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getID3Frames", function() { return getID3Frames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "decodeFrame", function() { return decodeFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8ArrayToStr", function() { return utf8ArrayToStr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "testables", function() { return testables; });
// breaking up those two types in order to clarify what is happening in the decoding path.
/**
* Returns true if an ID3 header can be found at offset in data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {boolean} - True if an ID3 header is found
*/
var isHeader = function isHeader(data, offset) {
/*
* http://id3.org/id3v2.3.0
* [0] = 'I'
* [1] = 'D'
* [2] = '3'
* [3,4] = {Version}
* [5] = {Flags}
* [6-9] = {ID3 Size}
*
* An ID3v2 tag can be detected with the following pattern:
* $49 44 33 yy yy xx zz zz zz zz
* Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
*/
if (offset + 10 <= data.length) {
// look for 'ID3' identifier
if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
// check version is within range
if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
// check size is within range
if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
return true;
}
}
}
}
return false;
};
/**
* Returns true if an ID3 footer can be found at offset in data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {boolean} - True if an ID3 footer is found
*/
var isFooter = function isFooter(data, offset) {
/*
* The footer is a copy of the header, but with a different identifier
*/
if (offset + 10 <= data.length) {
// look for '3DI' identifier
if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
// check version is within range
if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {
// check size is within range
if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
return true;
}
}
}
}
return false;
};
/**
* Returns any adjacent ID3 tags found in data starting at offset, as one block of data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {Uint8Array | undefined} - The block of data containing any ID3 tags found
* or *undefined* if no header is found at the starting offset
*/
var getID3Data = function getID3Data(data, offset) {
var front = offset;
var length = 0;
while (isHeader(data, offset)) {
// ID3 header is 10 bytes
length += 10;
var size = readSize(data, offset + 6);
length += size;
if (isFooter(data, offset + 10)) {
// ID3 footer is 10 bytes
length += 10;
}
offset += length;
}
if (length > 0) {
return data.subarray(front, front + length);
}
return undefined;
};
var readSize = function readSize(data, offset) {
var size = 0;
size = (data[offset] & 0x7f) << 21;
size |= (data[offset + 1] & 0x7f) << 14;
size |= (data[offset + 2] & 0x7f) << 7;
size |= data[offset + 3] & 0x7f;
return size;
};
var canParse = function canParse(data, offset) {
return isHeader(data, offset) && readSize(data, offset + 6) + 10 <= data.length - offset;
};
/**
* Searches for the Elementary Stream timestamp found in the ID3 data chunk
* @param {Uint8Array} data - Block of data containing one or more ID3 tags
* @return {number | undefined} - The timestamp
*/
var getTimeStamp = function getTimeStamp(data) {
var frames = getID3Frames(data);
for (var i = 0; i < frames.length; i++) {
var frame = frames[i];
if (isTimeStampFrame(frame)) {
return readTimeStamp(frame);
}
}
return undefined;
};
/**
* Returns true if the ID3 frame is an Elementary Stream timestamp frame
* @param {ID3 frame} frame
*/
var isTimeStampFrame = function isTimeStampFrame(frame) {
return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
};
var getFrameData = function getFrameData(data) {
/*
Frame ID $xx xx xx xx (four characters)
Size $xx xx xx xx
Flags $xx xx
*/
var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
var size = readSize(data, 4); // skip frame id, size, and flags
var offset = 10;
return {
type: type,
size: size,
data: data.subarray(offset, offset + size)
};
};
/**
* Returns an array of ID3 frames found in all the ID3 tags in the id3Data
* @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
* @return {ID3.Frame[]} - Array of ID3 frame objects
*/
var getID3Frames = function getID3Frames(id3Data) {
var offset = 0;
var frames = [];
while (isHeader(id3Data, offset)) {
var size = readSize(id3Data, offset + 6); // skip past ID3 header
offset += 10;
var end = offset + size; // loop through frames in the ID3 tag
while (offset + 8 < end) {
var frameData = getFrameData(id3Data.subarray(offset));
var frame = decodeFrame(frameData);
if (frame) {
frames.push(frame);
} // skip frame header and frame data
offset += frameData.size + 10;
}
if (isFooter(id3Data, offset)) {
offset += 10;
}
}
return frames;
};
var decodeFrame = function decodeFrame(frame) {
if (frame.type === 'PRIV') {
return decodePrivFrame(frame);
} else if (frame.type[0] === 'W') {
return decodeURLFrame(frame);
}
return decodeTextFrame(frame);
};
var decodePrivFrame = function decodePrivFrame(frame) {
/*
Format: <text string>\0<binary data>
*/
if (frame.size < 2) {
return undefined;
}
var owner = utf8ArrayToStr(frame.data, true);
var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
return {
key: frame.type,
info: owner,
data: privateData.buffer
};
};
var decodeTextFrame = function decodeTextFrame(frame) {
if (frame.size < 2) {
return undefined;
}
if (frame.type === 'TXXX') {
/*
Format:
[0] = {Text Encoding}
[1-?] = {Description}\0{Value}
*/
var index = 1;
var description = utf8ArrayToStr(frame.data.subarray(index), true);
index += description.length + 1;
var value = utf8ArrayToStr(frame.data.subarray(index));
return {
key: frame.type,
info: description,
data: value
};
}
/*
Format:
[0] = {Text Encoding}
[1-?] = {Value}
*/
var text = utf8ArrayToStr(frame.data.subarray(1));
return {
key: frame.type,
data: text
};
};
var decodeURLFrame = function decodeURLFrame(frame) {
if (frame.type === 'WXXX') {
/*
Format:
[0] = {Text Encoding}
[1-?] = {Description}\0{URL}
*/
if (frame.size < 2) {
return undefined;
}
var index = 1;
var description = utf8ArrayToStr(frame.data.subarray(index), true);
index += description.length + 1;
var value = utf8ArrayToStr(frame.data.subarray(index));
return {
key: frame.type,
info: description,
data: value
};
}
/*
Format:
[0-?] = {URL}
*/
var url = utf8ArrayToStr(frame.data);
return {
key: frame.type,
data: url
};
};
var readTimeStamp = function readTimeStamp(timeStampFrame) {
if (timeStampFrame.data.byteLength === 8) {
var data = new Uint8Array(timeStampFrame.data); // timestamp is 33 bit expressed as a big-endian eight-octet number,
// with the upper 31 bits set to zero.
var pts33Bit = data[3] & 0x1;
var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
timestamp /= 45;
if (pts33Bit) {
timestamp += 47721858.84;
} // 2^32 / 90
return Math.round(timestamp);
}
return undefined;
}; // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
/* utf.js - UTF-8 <=> UTF-16 convertion
*
* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
* Version: 1.0
* LastModified: Dec 25 1999
* This library is free. You can redistribute it and/or modify it.
*/
var utf8ArrayToStr = function utf8ArrayToStr(array, exitOnNull) {
if (exitOnNull === void 0) {
exitOnNull = false;
}
var decoder = getTextDecoder();
if (decoder) {
var decoded = decoder.decode(array);
if (exitOnNull) {
// grab up to the first null
var idx = decoded.indexOf('\0');
return idx !== -1 ? decoded.substring(0, idx) : decoded;
} // remove any null characters
return decoded.replace(/\0/g, '');
}
var len = array.length;
var c;
var char2;
var char3;
var out = '';
var i = 0;
while (i < len) {
c = array[i++];
if (c === 0x00 && exitOnNull) {
return out;
} else if (c === 0x00 || c === 0x03) {
// If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
continue;
}
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
out += String.fromCharCode(c);
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
char2 = array[i++];
out += String.fromCharCode((c & 0x1f) << 6 | char2 & 0x3f);
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++];
char3 = array[i++];
out += String.fromCharCode((c & 0x0f) << 12 | (char2 & 0x3f) << 6 | (char3 & 0x3f) << 0);
break;
default:
}
}
return out;
};
var testables = {
decodeTextFrame: decodeTextFrame
};
var decoder;
function getTextDecoder() {
if (!decoder && typeof self.TextDecoder !== 'undefined') {
decoder = new self.TextDecoder('utf-8');
}
return decoder;
}
/***/ }),
/***/ "./src/demux/mp3demuxer.ts":
/*!*********************************!*\
!*** ./src/demux/mp3demuxer.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./base-audio-demuxer */ "./src/demux/base-audio-demuxer.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/**
* MP3 demuxer
*/
var MP3Demuxer = /*#__PURE__*/function (_BaseAudioDemuxer) {
_inheritsLoose(MP3Demuxer, _BaseAudioDemuxer);
function MP3Demuxer() {
return _BaseAudioDemuxer.apply(this, arguments) || this;
}
var _proto = MP3Demuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
_BaseAudioDemuxer.prototype.resetInitSegment.call(this, audioCodec, videoCodec, duration);
this._audioTrack = {
container: 'audio/mpeg',
type: 'audio',
id: 0,
pid: -1,
sequenceNumber: 0,
isAAC: false,
samples: [],
manifestCodec: audioCodec,
duration: duration,
inputTimeScale: 90000,
dropped: 0
};
};
MP3Demuxer.probe = function probe(data) {
if (!data) {
return false;
} // check if data contains ID3 timestamp and MPEG sync word
// Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
// Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
// More info http://www.mp3-tech.org/programmer/frame_header.html
var id3Data = _demux_id3__WEBPACK_IMPORTED_MODULE_1__["getID3Data"](data, 0) || [];
var offset = id3Data.length;
for (var length = data.length; offset < length; offset++) {
if (_mpegaudio__WEBPACK_IMPORTED_MODULE_3__["probe"](data, offset)) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].log('MPEG Audio sync word found !');
return true;
}
}
return false;
};
_proto.canParse = function canParse(data, offset) {
return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["canParse"](data, offset);
};
_proto.appendFrame = function appendFrame(track, data, offset) {
if (this.initPTS === null) {
return;
}
return _mpegaudio__WEBPACK_IMPORTED_MODULE_3__["appendFrame"](track, data, offset, this.initPTS, this.frameIndex);
};
return MP3Demuxer;
}(_base_audio_demuxer__WEBPACK_IMPORTED_MODULE_0__["default"]);
MP3Demuxer.minProbeByteLength = 4;
/* harmony default export */ __webpack_exports__["default"] = (MP3Demuxer);
/***/ }),
/***/ "./src/demux/mp4demuxer.ts":
/*!*********************************!*\
!*** ./src/demux/mp4demuxer.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dummy-demuxed-track */ "./src/demux/dummy-demuxed-track.ts");
/**
* MP4 demuxer
*/
var MP4Demuxer = /*#__PURE__*/function () {
function MP4Demuxer(observer, config) {
this.remainderData = null;
this.config = void 0;
this.config = config;
}
var _proto = MP4Demuxer.prototype;
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetInitSegment = function resetInitSegment() {};
_proto.resetContiguity = function resetContiguity() {};
MP4Demuxer.probe = function probe(data) {
// ensure we find a moof box in the first 16 kB
return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["findBox"])({
data: data,
start: 0,
end: Math.min(data.length, 16384)
}, ['moof']).length > 0;
};
_proto.demux = function demux(data) {
// Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter
var avcSamples = data;
var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])();
if (this.config.progressive) {
// Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.
// This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee
// that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.
if (this.remainderData) {
avcSamples = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["appendUint8Array"])(this.remainderData, data);
}
var segmentedData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["segmentValidRange"])(avcSamples);
this.remainderData = segmentedData.remainder;
avcTrack.samples = segmentedData.valid || new Uint8Array();
} else {
avcTrack.samples = avcSamples;
}
return {
audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
avcTrack: avcTrack,
id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])()
};
};
_proto.flush = function flush() {
var avcTrack = Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])();
avcTrack.samples = this.remainderData || new Uint8Array();
this.remainderData = null;
return {
audioTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
avcTrack: avcTrack,
id3Track: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])(),
textTrack: Object(_dummy_demuxed_track__WEBPACK_IMPORTED_MODULE_1__["dummyTrack"])()
};
};
_proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
return Promise.reject(new Error('The MP4 demuxer does not support SAMPLE-AES decryption'));
};
_proto.destroy = function destroy() {};
return MP4Demuxer;
}();
MP4Demuxer.minProbeByteLength = 1024;
/* harmony default export */ __webpack_exports__["default"] = (MP4Demuxer);
/***/ }),
/***/ "./src/demux/mpegaudio.ts":
/*!********************************!*\
!*** ./src/demux/mpegaudio.ts ***!
\********************************/
/*! exports provided: appendFrame, parseHeader, isHeaderPattern, isHeader, canParse, probe */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendFrame", function() { return appendFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseHeader", function() { return parseHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeaderPattern", function() { return isHeaderPattern; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isHeader", function() { return isHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canParse", function() { return canParse; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "probe", function() { return probe; });
/**
* MPEG parser helper
*/
var chromeVersion = null;
var BitratesMap = [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
var SamplingRateMap = [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000];
var SamplesCoefficients = [// MPEG 2.5
[0, // Reserved
72, // Layer3
144, // Layer2
12 // Layer1
], // Reserved
[0, // Reserved
0, // Layer3
0, // Layer2
0 // Layer1
], // MPEG 2
[0, // Reserved
72, // Layer3
144, // Layer2
12 // Layer1
], // MPEG 1
[0, // Reserved
144, // Layer3
144, // Layer2
12 // Layer1
]];
var BytesInSlot = [0, // Reserved
1, // Layer3
1, // Layer2
4 // Layer1
];
function appendFrame(track, data, offset, pts, frameIndex) {
// Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
if (offset + 24 > data.length) {
return;
}
var header = parseHeader(data, offset);
if (header && offset + header.frameLength <= data.length) {
var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
var stamp = pts + frameIndex * frameDuration;
var sample = {
unit: data.subarray(offset, offset + header.frameLength),
pts: stamp,
dts: stamp
};
track.config = [];
track.channelCount = header.channelCount;
track.samplerate = header.sampleRate;
track.samples.push(sample);
return {
sample: sample,
length: header.frameLength
};
}
}
function parseHeader(data, offset) {
var mpegVersion = data[offset + 1] >> 3 & 3;
var mpegLayer = data[offset + 1] >> 1 & 3;
var bitRateIndex = data[offset + 2] >> 4 & 15;
var sampleRateIndex = data[offset + 2] >> 2 & 3;
if (mpegVersion !== 1 && bitRateIndex !== 0 && bitRateIndex !== 15 && sampleRateIndex !== 3) {
var paddingBit = data[offset + 2] >> 1 & 1;
var channelMode = data[offset + 3] >> 6;
var columnInBitrates = mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;
var bitRate = BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;
var columnInSampleRates = mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;
var sampleRate = SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];
var channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
var sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];
var bytesInSlot = BytesInSlot[mpegLayer];
var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
var frameLength = Math.floor(sampleCoefficient * bitRate / sampleRate + paddingBit) * bytesInSlot;
if (chromeVersion === null) {
var userAgent = navigator.userAgent || '';
var result = userAgent.match(/Chrome\/(\d+)/i);
chromeVersion = result ? parseInt(result[1]) : 0;
}
var needChromeFix = !!chromeVersion && chromeVersion <= 87;
if (needChromeFix && mpegLayer === 2 && bitRate >= 224000 && channelMode === 0) {
// Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)
data[offset + 3] = data[offset + 3] | 0x80;
}
return {
sampleRate: sampleRate,
channelCount: channelCount,
frameLength: frameLength,
samplesPerFrame: samplesPerFrame
};
}
}
function isHeaderPattern(data, offset) {
return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
}
function isHeader(data, offset) {
// Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
// Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
// More info http://www.mp3-tech.org/programmer/frame_header.html
return offset + 1 < data.length && isHeaderPattern(data, offset);
}
function canParse(data, offset) {
var headerSize = 4;
return isHeaderPattern(data, offset) && headerSize <= data.length - offset;
}
function probe(data, offset) {
// same as isHeader but we also check that MPEG frame follows last MPEG frame
// or end of data is reached
if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
// MPEG header Length
var headerLength = 4; // MPEG frame Length
var header = parseHeader(data, offset);
var frameLength = headerLength;
if (header !== null && header !== void 0 && header.frameLength) {
frameLength = header.frameLength;
}
var newOffset = offset + frameLength;
return newOffset === data.length || isHeader(data, newOffset);
}
return false;
}
/***/ }),
/***/ "./src/demux/sample-aes.ts":
/*!*********************************!*\
!*** ./src/demux/sample-aes.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
/* harmony import */ var _tsdemuxer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tsdemuxer */ "./src/demux/tsdemuxer.ts");
/**
* SAMPLE-AES decrypter
*/
var SampleAesDecrypter = /*#__PURE__*/function () {
function SampleAesDecrypter(observer, config, keyData) {
this.keyData = void 0;
this.decrypter = void 0;
this.keyData = keyData;
this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_0__["default"](observer, config, {
removePKCS7Padding: false
});
}
var _proto = SampleAesDecrypter.prototype;
_proto.decryptBuffer = function decryptBuffer(encryptedData, callback) {
this.decrypter.decrypt(encryptedData, this.keyData.key.buffer, this.keyData.iv.buffer, callback);
} // AAC - encrypt all full 16 bytes blocks starting from offset 16
;
_proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) {
var curUnit = samples[sampleIndex].unit;
var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
var localthis = this;
this.decryptBuffer(encryptedBuffer, function (decryptedBuffer) {
var decryptedData = new Uint8Array(decryptedBuffer);
curUnit.set(decryptedData, 16);
if (!sync) {
localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
}
});
};
_proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
for (;; sampleIndex++) {
if (sampleIndex >= samples.length) {
callback();
return;
}
if (samples[sampleIndex].unit.length < 32) {
continue;
}
var sync = this.decrypter.isSync();
this.decryptAacSample(samples, sampleIndex, callback, sync);
if (!sync) {
return;
}
}
} // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
;
_proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
var encryptedData = new Int8Array(encryptedDataLen);
var outputPos = 0;
for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
}
return encryptedData;
};
_proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
var uint8DecryptedData = new Uint8Array(decryptedData);
var inputPos = 0;
for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
decodedData.set(uint8DecryptedData.subarray(inputPos, inputPos + 16), outputPos);
}
return decodedData;
};
_proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
var decodedData = Object(_tsdemuxer__WEBPACK_IMPORTED_MODULE_1__["discardEPB"])(curUnit.data);
var encryptedData = this.getAvcEncryptedData(decodedData);
var localthis = this;
this.decryptBuffer(encryptedData.buffer, function (decryptedBuffer) {
curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedBuffer);
if (!sync) {
localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
}
});
};
_proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
if (samples instanceof Uint8Array) {
throw new Error('Cannot decrypt samples of type Uint8Array');
}
for (;; sampleIndex++, unitIndex = 0) {
if (sampleIndex >= samples.length) {
callback();
return;
}
var curUnits = samples[sampleIndex].units;
for (;; unitIndex++) {
if (unitIndex >= curUnits.length) {
break;
}
var curUnit = curUnits[unitIndex];
if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
continue;
}
var sync = this.decrypter.isSync();
this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
if (!sync) {
return;
}
}
}
};
return SampleAesDecrypter;
}();
/* harmony default export */ __webpack_exports__["default"] = (SampleAesDecrypter);
/***/ }),
/***/ "./src/demux/transmuxer-interface.ts":
/*!*******************************************!*\
!*** ./src/demux/transmuxer-interface.ts ***!
\*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerInterface; });
/* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! webworkify-webpack */ "./node_modules/webworkify-webpack/index.js");
/* harmony import */ var webworkify_webpack__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_6__);
var MediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_5__["getMediaSource"])() || {
isTypeSupported: function isTypeSupported() {
return false;
}
};
var TransmuxerInterface = /*#__PURE__*/function () {
function TransmuxerInterface(hls, id, onTransmuxComplete, onFlush) {
var _this = this;
this.hls = void 0;
this.id = void 0;
this.observer = void 0;
this.frag = null;
this.part = null;
this.worker = void 0;
this.onwmsg = void 0;
this.transmuxer = null;
this.onTransmuxComplete = void 0;
this.onFlush = void 0;
this.hls = hls;
this.id = id;
this.onTransmuxComplete = onTransmuxComplete;
this.onFlush = onFlush;
var config = hls.config;
var forwardMessage = function forwardMessage(ev, data) {
data = data || {};
data.frag = _this.frag;
data.id = _this.id;
hls.trigger(ev, data);
}; // forward events to main thread
this.observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_6__["EventEmitter"]();
this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage);
this.observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage);
var typeSupported = {
mp4: MediaSource.isTypeSupported('video/mp4'),
mpeg: MediaSource.isTypeSupported('audio/mpeg'),
mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
}; // navigator.vendor is not always available in Web Worker
// refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
var vendor = navigator.vendor;
if (config.enableWorker && typeof Worker !== 'undefined') {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('demuxing in webworker');
var worker;
try {
worker = this.worker = webworkify_webpack__WEBPACK_IMPORTED_MODULE_0__(/*require.resolve*/(/*! ../demux/transmuxer-worker.ts */ "./src/demux/transmuxer-worker.ts"));
this.onwmsg = this.onWorkerMessage.bind(this);
worker.addEventListener('message', this.onwmsg);
worker.onerror = function (event) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].OTHER_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].INTERNAL_EXCEPTION,
fatal: true,
event: 'demuxerWorker',
error: new Error(event.message + " (" + event.filename + ":" + event.lineno + ")")
});
};
worker.postMessage({
cmd: 'init',
typeSupported: typeSupported,
vendor: vendor,
id: id,
config: JSON.stringify(config)
});
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Error in worker:', err);
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].error('Error while initializing DemuxerWorker, fallback to inline');
if (worker) {
// revoke the Object URL that was used to create transmuxer worker, so as not to leak it
self.URL.revokeObjectURL(worker.objectURL);
}
this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor);
this.worker = null;
}
} else {
this.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, typeSupported, config, vendor);
}
}
var _proto = TransmuxerInterface.prototype;
_proto.destroy = function destroy() {
var w = this.worker;
if (w) {
w.removeEventListener('message', this.onwmsg);
w.terminate();
this.worker = null;
} else {
var transmuxer = this.transmuxer;
if (transmuxer) {
transmuxer.destroy();
this.transmuxer = null;
}
}
var observer = this.observer;
if (observer) {
observer.removeAllListeners();
} // @ts-ignore
this.observer = null;
};
_proto.push = function push(data, initSegmentData, audioCodec, videoCodec, frag, part, duration, accurateTimeOffset, chunkMeta, defaultInitPTS) {
var _this2 = this;
chunkMeta.transmuxing.start = self.performance.now();
var transmuxer = this.transmuxer,
worker = this.worker;
var timeOffset = part ? part.start : frag.start;
var decryptdata = frag.decryptdata;
var lastFrag = this.frag;
var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
var trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);
var snDiff = lastFrag ? chunkMeta.sn - lastFrag.sn : -1;
var partDiff = this.part ? chunkMeta.part - this.part.index : 1;
var contiguous = !trackSwitch && (snDiff === 1 || snDiff === 0 && partDiff === 1);
var now = self.performance.now();
if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {
frag.stats.parsing.start = now;
}
if (part && (partDiff || !contiguous)) {
part.stats.parsing.start = now;
}
var state = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxState"](discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset);
if (!contiguous || discontinuity) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[transmuxer-interface, " + frag.type + "]: Starting new transmux session for sn: " + chunkMeta.sn + " p: " + chunkMeta.part + " level: " + chunkMeta.level + " id: " + chunkMeta.id + "\n discontinuity: " + discontinuity + "\n trackSwitch: " + trackSwitch + "\n contiguous: " + contiguous + "\n accurateTimeOffset: " + accurateTimeOffset + "\n timeOffset: " + timeOffset);
var config = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["TransmuxConfig"](audioCodec, videoCodec, initSegmentData, duration, defaultInitPTS);
this.configureTransmuxer(config);
}
this.frag = frag;
this.part = part; // Frags with sn of 'initSegment' are not transmuxed
if (worker) {
// post fragment payload as transferable objects for ArrayBuffer (no copy)
worker.postMessage({
cmd: 'demux',
data: data,
decryptdata: decryptdata,
chunkMeta: chunkMeta,
state: state
}, data instanceof ArrayBuffer ? [data] : []);
} else if (transmuxer) {
var _transmuxResult = transmuxer.push(data, decryptdata, chunkMeta, state);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult)) {
_transmuxResult.then(function (data) {
_this2.handleTransmuxComplete(data);
});
} else {
this.handleTransmuxComplete(_transmuxResult);
}
}
};
_proto.flush = function flush(chunkMeta) {
var _this3 = this;
chunkMeta.transmuxing.start = self.performance.now();
var transmuxer = this.transmuxer,
worker = this.worker;
if (worker) {
worker.postMessage({
cmd: 'flush',
chunkMeta: chunkMeta
});
} else if (transmuxer) {
var _transmuxResult2 = transmuxer.flush(chunkMeta);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_2__["isPromise"])(_transmuxResult2)) {
_transmuxResult2.then(function (data) {
_this3.handleFlushResult(data, chunkMeta);
});
} else {
this.handleFlushResult(_transmuxResult2, chunkMeta);
}
}
};
_proto.handleFlushResult = function handleFlushResult(results, chunkMeta) {
var _this4 = this;
results.forEach(function (result) {
_this4.handleTransmuxComplete(result);
});
this.onFlush(chunkMeta);
};
_proto.onWorkerMessage = function onWorkerMessage(ev) {
var data = ev.data;
var hls = this.hls;
switch (data.event) {
case 'init':
{
// revoke the Object URL that was used to create transmuxer worker, so as not to leak it
self.URL.revokeObjectURL(this.worker.objectURL);
break;
}
case 'transmuxComplete':
{
this.handleTransmuxComplete(data.data);
break;
}
case 'flush':
{
this.onFlush(data.data);
break;
}
/* falls through */
default:
{
data.data = data.data || {};
data.data.frag = this.frag;
data.data.id = this.id;
hls.trigger(data.event, data.data);
break;
}
}
};
_proto.configureTransmuxer = function configureTransmuxer(config) {
var worker = this.worker,
transmuxer = this.transmuxer;
if (worker) {
worker.postMessage({
cmd: 'configure',
config: config
});
} else if (transmuxer) {
transmuxer.configure(config);
}
};
_proto.handleTransmuxComplete = function handleTransmuxComplete(result) {
result.chunkMeta.transmuxing.end = self.performance.now();
this.onTransmuxComplete(result);
};
return TransmuxerInterface;
}();
/***/ }),
/***/ "./src/demux/transmuxer-worker.ts":
/*!****************************************!*\
!*** ./src/demux/transmuxer-worker.ts ***!
\****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransmuxerWorker; });
/* harmony import */ var _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../demux/transmuxer */ "./src/demux/transmuxer.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_3__);
function TransmuxerWorker(self) {
var observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_3__["EventEmitter"]();
var forwardMessage = function forwardMessage(ev, data) {
self.postMessage({
event: ev,
data: data
});
}; // forward events to main thread
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].FRAG_DECRYPTED, forwardMessage);
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, forwardMessage);
self.addEventListener('message', function (ev) {
var data = ev.data;
switch (data.cmd) {
case 'init':
{
var config = JSON.parse(data.config);
self.transmuxer = new _demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["default"](observer, data.typeSupported, config, data.vendor);
Object(_utils_logger__WEBPACK_IMPORTED_MODULE_2__["enableLogs"])(config.debug);
forwardMessage('init', null);
break;
}
case 'configure':
{
self.transmuxer.configure(data.config);
break;
}
case 'demux':
{
var transmuxResult = self.transmuxer.push(data.data, data.decryptdata, data.chunkMeta, data.state);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(transmuxResult)) {
transmuxResult.then(function (data) {
emitTransmuxComplete(self, data);
});
} else {
emitTransmuxComplete(self, transmuxResult);
}
break;
}
case 'flush':
{
var id = data.chunkMeta;
var _transmuxResult = self.transmuxer.flush(id);
if (Object(_demux_transmuxer__WEBPACK_IMPORTED_MODULE_0__["isPromise"])(_transmuxResult)) {
_transmuxResult.then(function (results) {
handleFlushResult(self, results, id);
});
} else {
handleFlushResult(self, _transmuxResult, id);
}
break;
}
default:
break;
}
});
}
function emitTransmuxComplete(self, transmuxResult) {
if (isEmptyResult(transmuxResult.remuxResult)) {
return;
}
var transferable = [];
var _transmuxResult$remux = transmuxResult.remuxResult,
audio = _transmuxResult$remux.audio,
video = _transmuxResult$remux.video;
if (audio) {
addToTransferable(transferable, audio);
}
if (video) {
addToTransferable(transferable, video);
}
self.postMessage({
event: 'transmuxComplete',
data: transmuxResult
}, transferable);
} // Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)
// in order to minimize message passing overhead
function addToTransferable(transferable, track) {
if (track.data1) {
transferable.push(track.data1.buffer);
}
if (track.data2) {
transferable.push(track.data2.buffer);
}
}
function handleFlushResult(self, results, chunkMeta) {
results.forEach(function (result) {
emitTransmuxComplete(self, result);
});
self.postMessage({
event: 'flush',
data: chunkMeta
});
}
function isEmptyResult(remuxResult) {
return !remuxResult.audio && !remuxResult.video && !remuxResult.text && !remuxResult.id3 && !remuxResult.initSegment;
}
/***/ }),
/***/ "./src/demux/transmuxer.ts":
/*!*********************************!*\
!*** ./src/demux/transmuxer.ts ***!
\*********************************/
/*! exports provided: default, isPromise, TransmuxConfig, TransmuxState */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Transmuxer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPromise", function() { return isPromise; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxConfig", function() { return TransmuxConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransmuxState", function() { return TransmuxState; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.ts");
/* harmony import */ var _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/aacdemuxer */ "./src/demux/aacdemuxer.ts");
/* harmony import */ var _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../demux/mp4demuxer */ "./src/demux/mp4demuxer.ts");
/* harmony import */ var _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../demux/tsdemuxer */ "./src/demux/tsdemuxer.ts");
/* harmony import */ var _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../demux/mp3demuxer */ "./src/demux/mp3demuxer.ts");
/* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts");
/* harmony import */ var _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../remux/passthrough-remuxer */ "./src/remux/passthrough-remuxer.ts");
/* harmony import */ var _chunk_cache__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./chunk-cache */ "./src/demux/chunk-cache.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var now; // performance.now() not available on WebWorker, at least on Safari Desktop
try {
now = self.performance.now.bind(self.performance);
} catch (err) {
_utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].debug('Unable to use Performance API on this environment');
now = self.Date.now;
}
var muxConfig = [{
demux: _demux_tsdemuxer__WEBPACK_IMPORTED_MODULE_5__["default"],
remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
}, {
demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"],
remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"]
}, {
demux: _demux_aacdemuxer__WEBPACK_IMPORTED_MODULE_3__["default"],
remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
}, {
demux: _demux_mp3demuxer__WEBPACK_IMPORTED_MODULE_6__["default"],
remux: _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_7__["default"]
}];
var minProbeByteLength = 1024;
muxConfig.forEach(function (_ref) {
var demux = _ref.demux;
minProbeByteLength = Math.max(minProbeByteLength, demux.minProbeByteLength);
});
var Transmuxer = /*#__PURE__*/function () {
function Transmuxer(observer, typeSupported, config, vendor) {
this.observer = void 0;
this.typeSupported = void 0;
this.config = void 0;
this.vendor = void 0;
this.demuxer = void 0;
this.remuxer = void 0;
this.decrypter = void 0;
this.probe = void 0;
this.decryptionPromise = null;
this.transmuxConfig = void 0;
this.currentTransmuxState = void 0;
this.cache = new _chunk_cache__WEBPACK_IMPORTED_MODULE_9__["default"]();
this.observer = observer;
this.typeSupported = typeSupported;
this.config = config;
this.vendor = vendor;
}
var _proto = Transmuxer.prototype;
_proto.configure = function configure(transmuxConfig) {
this.transmuxConfig = transmuxConfig;
if (this.decrypter) {
this.decrypter.reset();
}
};
_proto.push = function push(data, decryptdata, chunkMeta, state) {
var _this = this;
var stats = chunkMeta.transmuxing;
stats.executeStart = now();
var uintData = new Uint8Array(data);
var cache = this.cache,
config = this.config,
currentTransmuxState = this.currentTransmuxState,
transmuxConfig = this.transmuxConfig;
if (state) {
this.currentTransmuxState = state;
}
var keyData = getEncryptionType(uintData, decryptdata);
if (keyData && keyData.method === 'AES-128') {
var decrypter = this.getDecrypter(); // Software decryption is synchronous; webCrypto is not
if (config.enableSoftwareAES) {
// Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached
// data is handled in the flush() call
var decryptedData = decrypter.softwareDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer);
if (!decryptedData) {
stats.executeEnd = now();
return emptyResult(chunkMeta);
}
uintData = new Uint8Array(decryptedData);
} else {
this.decryptionPromise = decrypter.webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer).then(function (decryptedData) {
// Calling push here is important; if flush() is called while this is still resolving, this ensures that
// the decrypted data has been transmuxed
var result = _this.push(decryptedData, null, chunkMeta);
_this.decryptionPromise = null;
return result;
});
return this.decryptionPromise;
}
}
var _ref2 = state || currentTransmuxState,
contiguous = _ref2.contiguous,
discontinuity = _ref2.discontinuity,
trackSwitch = _ref2.trackSwitch,
accurateTimeOffset = _ref2.accurateTimeOffset,
timeOffset = _ref2.timeOffset;
var audioCodec = transmuxConfig.audioCodec,
videoCodec = transmuxConfig.videoCodec,
defaultInitPts = transmuxConfig.defaultInitPts,
duration = transmuxConfig.duration,
initSegmentData = transmuxConfig.initSegmentData; // Reset muxers before probing to ensure that their state is clean, even if flushing occurs before a successful probe
if (discontinuity || trackSwitch) {
this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);
}
if (discontinuity) {
this.resetInitialTimestamp(defaultInitPts);
}
if (!contiguous) {
this.resetContiguity();
}
if (this.needsProbing(uintData, discontinuity, trackSwitch)) {
if (cache.dataLength) {
var cachedData = cache.flush();
uintData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_10__["appendUint8Array"])(cachedData, uintData);
}
this.configureTransmuxer(uintData, transmuxConfig);
}
var result = this.transmux(uintData, keyData, timeOffset, accurateTimeOffset, chunkMeta);
var currentState = this.currentTransmuxState;
currentState.contiguous = true;
currentState.discontinuity = false;
currentState.trackSwitch = false;
stats.executeEnd = now();
return result;
} // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)
;
_proto.flush = function flush(chunkMeta) {
var _this2 = this;
var stats = chunkMeta.transmuxing;
stats.executeStart = now();
var decrypter = this.decrypter,
cache = this.cache,
currentTransmuxState = this.currentTransmuxState,
decryptionPromise = this.decryptionPromise;
if (decryptionPromise) {
// Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore
// only flushing is required for async decryption
return decryptionPromise.then(function () {
return _this2.flush(chunkMeta);
});
}
var transmuxResults = [];
var timeOffset = currentTransmuxState.timeOffset;
if (decrypter) {
// The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults
// This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,
// or for progressive downloads with small segments)
var decryptedData = decrypter.flush();
if (decryptedData) {
// Push always returns a TransmuxerResult if decryptdata is null
transmuxResults.push(this.push(decryptedData, null, chunkMeta));
}
}
var bytesSeen = cache.dataLength;
cache.reset();
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
// If probing failed, and each demuxer saw enough bytes to be able to probe, then Hls.js has been given content its not able to handle
if (bytesSeen >= minProbeByteLength) {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: true,
reason: 'no demux matching with content found'
});
}
stats.executeEnd = now();
return [emptyResult(chunkMeta)];
}
var demuxResultOrPromise = demuxer.flush(timeOffset);
if (isPromise(demuxResultOrPromise)) {
// Decrypt final SAMPLE-AES samples
return demuxResultOrPromise.then(function (demuxResult) {
_this2.flushRemux(transmuxResults, demuxResult, chunkMeta);
return transmuxResults;
});
}
this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);
return transmuxResults;
};
_proto.flushRemux = function flushRemux(transmuxResults, demuxResult, chunkMeta) {
var audioTrack = demuxResult.audioTrack,
avcTrack = demuxResult.avcTrack,
id3Track = demuxResult.id3Track,
textTrack = demuxResult.textTrack;
var _this$currentTransmux = this.currentTransmuxState,
accurateTimeOffset = _this$currentTransmux.accurateTimeOffset,
timeOffset = _this$currentTransmux.timeOffset;
_utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].log("[transmuxer.ts]: Flushed fragment " + chunkMeta.sn + (chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : '') + " of level " + chunkMeta.level);
var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, true);
transmuxResults.push({
remuxResult: remuxResult,
chunkMeta: chunkMeta
});
chunkMeta.transmuxing.executeEnd = now();
};
_proto.resetInitialTimestamp = function resetInitialTimestamp(defaultInitPts) {
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
return;
}
demuxer.resetTimeStamp(defaultInitPts);
remuxer.resetTimeStamp(defaultInitPts);
};
_proto.resetContiguity = function resetContiguity() {
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
return;
}
demuxer.resetContiguity();
remuxer.resetNextTimestamp();
};
_proto.resetInitSegment = function resetInitSegment(initSegmentData, audioCodec, videoCodec, duration) {
var demuxer = this.demuxer,
remuxer = this.remuxer;
if (!demuxer || !remuxer) {
return;
}
demuxer.resetInitSegment(audioCodec, videoCodec, duration);
remuxer.resetInitSegment(initSegmentData, audioCodec, videoCodec);
};
_proto.destroy = function destroy() {
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = undefined;
}
if (this.remuxer) {
this.remuxer.destroy();
this.remuxer = undefined;
}
};
_proto.transmux = function transmux(data, keyData, timeOffset, accurateTimeOffset, chunkMeta) {
var result;
if (keyData && keyData.method === 'SAMPLE-AES') {
result = this.transmuxSampleAes(data, keyData, timeOffset, accurateTimeOffset, chunkMeta);
} else {
result = this.transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta);
}
return result;
};
_proto.transmuxUnencrypted = function transmuxUnencrypted(data, timeOffset, accurateTimeOffset, chunkMeta) {
var _demux = this.demuxer.demux(data, timeOffset, false, !this.config.progressive),
audioTrack = _demux.audioTrack,
avcTrack = _demux.avcTrack,
id3Track = _demux.id3Track,
textTrack = _demux.textTrack;
var remuxResult = this.remuxer.remux(audioTrack, avcTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, false);
return {
remuxResult: remuxResult,
chunkMeta: chunkMeta
};
};
_proto.transmuxSampleAes = function transmuxSampleAes(data, decryptData, timeOffset, accurateTimeOffset, chunkMeta) {
var _this3 = this;
return this.demuxer.demuxSampleAes(data, decryptData, timeOffset).then(function (demuxResult) {
var remuxResult = _this3.remuxer.remux(demuxResult.audioTrack, demuxResult.avcTrack, demuxResult.id3Track, demuxResult.textTrack, timeOffset, accurateTimeOffset, false);
return {
remuxResult: remuxResult,
chunkMeta: chunkMeta
};
});
};
_proto.configureTransmuxer = function configureTransmuxer(data, transmuxConfig) {
var config = this.config,
observer = this.observer,
typeSupported = this.typeSupported,
vendor = this.vendor;
var audioCodec = transmuxConfig.audioCodec,
defaultInitPts = transmuxConfig.defaultInitPts,
duration = transmuxConfig.duration,
initSegmentData = transmuxConfig.initSegmentData,
videoCodec = transmuxConfig.videoCodec; // probe for content type
var mux;
for (var i = 0, len = muxConfig.length; i < len; i++) {
if (muxConfig[i].demux.probe(data)) {
mux = muxConfig[i];
break;
}
}
if (!mux) {
// If probing previous configs fail, use mp4 passthrough
_utils_logger__WEBPACK_IMPORTED_MODULE_11__["logger"].warn('Failed to find demuxer by probing frag, treating as mp4 passthrough');
mux = {
demux: _demux_mp4demuxer__WEBPACK_IMPORTED_MODULE_4__["default"],
remux: _remux_passthrough_remuxer__WEBPACK_IMPORTED_MODULE_8__["default"]
};
} // so let's check that current remuxer and demuxer are still valid
var demuxer = this.demuxer;
var remuxer = this.remuxer;
var Remuxer = mux.remux;
var Demuxer = mux.demux;
if (!remuxer || !(remuxer instanceof Remuxer)) {
this.remuxer = new Remuxer(observer, config, typeSupported, vendor);
}
if (!demuxer || !(demuxer instanceof Demuxer)) {
this.demuxer = new Demuxer(observer, config, typeSupported);
this.probe = Demuxer.probe;
} // Ensure that muxers are always initialized with an initSegment
this.resetInitSegment(initSegmentData, audioCodec, videoCodec, duration);
this.resetInitialTimestamp(defaultInitPts);
};
_proto.needsProbing = function needsProbing(data, discontinuity, trackSwitch) {
// in case of continuity change, or track switch
// we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;
};
_proto.getDecrypter = function getDecrypter() {
var decrypter = this.decrypter;
if (!decrypter) {
decrypter = this.decrypter = new _crypt_decrypter__WEBPACK_IMPORTED_MODULE_2__["default"](this.observer, this.config);
}
return decrypter;
};
return Transmuxer;
}();
function getEncryptionType(data, decryptData) {
var encryptionType = null;
if (data.byteLength > 0 && decryptData != null && decryptData.key != null && decryptData.iv !== null && decryptData.method != null) {
encryptionType = decryptData;
}
return encryptionType;
}
var emptyResult = function emptyResult(chunkMeta) {
return {
remuxResult: {},
chunkMeta: chunkMeta
};
};
function isPromise(p) {
return 'then' in p && p.then instanceof Function;
}
var TransmuxConfig = function TransmuxConfig(audioCodec, videoCodec, initSegmentData, duration, defaultInitPts) {
this.audioCodec = void 0;
this.videoCodec = void 0;
this.initSegmentData = void 0;
this.duration = void 0;
this.defaultInitPts = void 0;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this.initSegmentData = initSegmentData;
this.duration = duration;
this.defaultInitPts = defaultInitPts;
};
var TransmuxState = function TransmuxState(discontinuity, contiguous, accurateTimeOffset, trackSwitch, timeOffset) {
this.discontinuity = void 0;
this.contiguous = void 0;
this.accurateTimeOffset = void 0;
this.trackSwitch = void 0;
this.timeOffset = void 0;
this.discontinuity = discontinuity;
this.contiguous = contiguous;
this.accurateTimeOffset = accurateTimeOffset;
this.trackSwitch = trackSwitch;
this.timeOffset = timeOffset;
};
/***/ }),
/***/ "./src/demux/tsdemuxer.ts":
/*!********************************!*\
!*** ./src/demux/tsdemuxer.ts ***!
\********************************/
/*! exports provided: discardEPB, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "discardEPB", function() { return discardEPB; });
/* harmony import */ var _adts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./adts */ "./src/demux/adts.ts");
/* harmony import */ var _mpegaudio__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.ts");
/* harmony import */ var _exp_golomb__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./exp-golomb */ "./src/demux/exp-golomb.ts");
/* harmony import */ var _id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./id3 */ "./src/demux/id3.ts");
/* harmony import */ var _sample_aes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sample-aes */ "./src/demux/sample-aes.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/**
* highly optimized TS demuxer:
* parse PAT, PMT
* extract PES packet from audio and video PIDs
* extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
* trigger the remuxer upon parsing completion
* it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.
* it also controls the remuxing process :
* upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
*/
// We are using fixed track IDs for driving the MP4 remuxer
// instead of following the TS PIDs.
// There is no reason not to do this and some browsers/SourceBuffer-demuxers
// may not like if there are TrackID "switches"
// See https://github.com/video-dev/hls.js/issues/1331
// Here we are mapping our internal track types to constant MP4 track IDs
// With MSE currently one can only have one track of each, and we are muxing
// whatever video/audio rendition in them.
var RemuxerTrackIdConfig = {
video: 1,
audio: 2,
id3: 3,
text: 4
};
var TSDemuxer = /*#__PURE__*/function () {
function TSDemuxer(observer, config, typeSupported) {
this.observer = void 0;
this.config = void 0;
this.typeSupported = void 0;
this.sampleAes = null;
this.pmtParsed = false;
this.audioCodec = void 0;
this.videoCodec = void 0;
this._duration = 0;
this.aacLastPTS = null;
this._initPTS = null;
this._initDTS = null;
this._pmtId = -1;
this._avcTrack = void 0;
this._audioTrack = void 0;
this._id3Track = void 0;
this._txtTrack = void 0;
this.aacOverFlow = null;
this.avcSample = null;
this.remainderData = null;
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
}
TSDemuxer.probe = function probe(data) {
var syncOffset = TSDemuxer.syncOffset(data);
if (syncOffset < 0) {
return false;
} else {
if (syncOffset) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset + ", junk ahead ?");
}
return true;
}
};
TSDemuxer.syncOffset = function syncOffset(data) {
// scan 1000 first bytes
var scanwindow = Math.min(1000, data.length - 3 * 188);
var i = 0;
while (i < scanwindow) {
// a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
return i;
} else {
i++;
}
}
return -1;
}
/**
* Creates a track model internal to demuxer used to drive remuxing input
*
* @param type 'audio' | 'video' | 'id3' | 'text'
* @param duration
* @return TSDemuxer's internal track model
*/
;
TSDemuxer.createTrack = function createTrack(type, duration) {
return {
container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
type: type,
id: RemuxerTrackIdConfig[type],
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: 0,
duration: type === 'audio' ? duration : undefined
};
}
/**
* Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
* Resets all internal track instances of the demuxer.
*/
;
var _proto = TSDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(audioCodec, videoCodec, duration) {
this.pmtParsed = false;
this._pmtId = -1;
this._avcTrack = TSDemuxer.createTrack('video', duration);
this._audioTrack = TSDemuxer.createTrack('audio', duration);
this._id3Track = TSDemuxer.createTrack('id3', duration);
this._txtTrack = TSDemuxer.createTrack('text', duration);
this._audioTrack.isAAC = true; // flush any partial content
this.aacOverFlow = null;
this.aacLastPTS = null;
this.avcSample = null;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this._duration = duration;
};
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetContiguity = function resetContiguity() {
var _audioTrack = this._audioTrack,
_avcTrack = this._avcTrack,
_id3Track = this._id3Track;
if (_audioTrack) {
_audioTrack.pesData = null;
}
if (_avcTrack) {
_avcTrack.pesData = null;
}
if (_id3Track) {
_id3Track.pesData = null;
}
this.aacOverFlow = null;
this.aacLastPTS = null;
};
_proto.demux = function demux(data, timeOffset, isSampleAes, flush) {
if (isSampleAes === void 0) {
isSampleAes = false;
}
if (flush === void 0) {
flush = false;
}
if (!isSampleAes) {
this.sampleAes = null;
}
var pes;
var avcTrack = this._avcTrack;
var audioTrack = this._audioTrack;
var id3Track = this._id3Track;
var avcId = avcTrack.pid;
var avcData = avcTrack.pesData;
var audioId = audioTrack.pid;
var id3Id = id3Track.pid;
var audioData = audioTrack.pesData;
var id3Data = id3Track.pesData;
var unknownPIDs = false;
var pmtParsed = this.pmtParsed;
var pmtId = this._pmtId;
var len = data.length;
if (this.remainderData) {
data = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_6__["appendUint8Array"])(this.remainderData, data);
len = data.length;
this.remainderData = null;
}
if (len < 188 && !flush) {
this.remainderData = data;
return {
audioTrack: audioTrack,
avcTrack: avcTrack,
id3Track: id3Track,
textTrack: this._txtTrack
};
}
var syncOffset = Math.max(0, TSDemuxer.syncOffset(data));
len -= (len + syncOffset) % 188;
if (len < data.byteLength && !flush) {
this.remainderData = new Uint8Array(data.buffer, len, data.buffer.byteLength - len);
} // loop through TS packets
for (var start = syncOffset; start < len; start += 188) {
if (data[start] === 0x47) {
var stt = !!(data[start + 1] & 0x40); // pid is a 13-bit field starting at the last bit of TS[1]
var pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
var atf = (data[start + 3] & 0x30) >> 4; // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
var offset = void 0;
if (atf > 1) {
offset = start + 5 + data[start + 4]; // continue if there is only adaptation field
if (offset === start + 188) {
continue;
}
} else {
offset = start + 4;
}
switch (pid) {
case avcId:
if (stt) {
if (avcData && (pes = parsePES(avcData))) {
this.parseAVCPES(pes, false);
}
avcData = {
data: [],
size: 0
};
}
if (avcData) {
avcData.data.push(data.subarray(offset, start + 188));
avcData.size += start + 188 - offset;
}
break;
case audioId:
if (stt) {
if (audioData && (pes = parsePES(audioData))) {
if (audioTrack.isAAC) {
this.parseAACPES(pes);
} else {
this.parseMPEGPES(pes);
}
}
audioData = {
data: [],
size: 0
};
}
if (audioData) {
audioData.data.push(data.subarray(offset, start + 188));
audioData.size += start + 188 - offset;
}
break;
case id3Id:
if (stt) {
if (id3Data && (pes = parsePES(id3Data))) {
this.parseID3PES(pes);
}
id3Data = {
data: [],
size: 0
};
}
if (id3Data) {
id3Data.data.push(data.subarray(offset, start + 188));
id3Data.size += start + 188 - offset;
}
break;
case 0:
if (stt) {
offset += data[offset] + 1;
}
pmtId = this._pmtId = parsePAT(data, offset);
break;
case pmtId:
{
if (stt) {
offset += data[offset] + 1;
}
var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, isSampleAes); // only update track id if track PID found while parsing PMT
// this is to avoid resetting the PID to -1 in case
// track PID transiently disappears from the stream
// this could happen in case of transient missing audio samples for example
// NOTE this is only the PID of the track as found in TS,
// but we are not using this for MP4 track IDs.
avcId = parsedPIDs.avc;
if (avcId > 0) {
avcTrack.pid = avcId;
}
audioId = parsedPIDs.audio;
if (audioId > 0) {
audioTrack.pid = audioId;
audioTrack.isAAC = parsedPIDs.isAAC;
}
id3Id = parsedPIDs.id3;
if (id3Id > 0) {
id3Track.pid = id3Id;
}
if (unknownPIDs && !pmtParsed) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('reparse from beginning');
unknownPIDs = false; // we set it to -188, the += 188 in the for loop will reset start to 0
start = syncOffset - 188;
}
pmtParsed = this.pmtParsed = true;
break;
}
case 17:
case 0x1fff:
break;
default:
unknownPIDs = true;
break;
}
} else {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: false,
reason: 'TS packet did not start with 0x47'
});
}
}
avcTrack.pesData = avcData;
audioTrack.pesData = audioData;
id3Track.pesData = id3Data;
var demuxResult = {
audioTrack: audioTrack,
avcTrack: avcTrack,
id3Track: id3Track,
textTrack: this._txtTrack
};
if (flush) {
this.extractRemainingSamples(demuxResult);
}
return demuxResult;
};
_proto.flush = function flush() {
var remainderData = this.remainderData;
this.remainderData = null;
var result;
if (remainderData) {
result = this.demux(remainderData, -1, false, true);
} else {
result = {
audioTrack: this._audioTrack,
avcTrack: this._avcTrack,
textTrack: this._txtTrack,
id3Track: this._id3Track
};
}
this.extractRemainingSamples(result);
if (this.sampleAes) {
return this.decrypt(result, this.sampleAes);
}
return result;
};
_proto.extractRemainingSamples = function extractRemainingSamples(demuxResult) {
var audioTrack = demuxResult.audioTrack,
avcTrack = demuxResult.avcTrack,
id3Track = demuxResult.id3Track;
var avcData = avcTrack.pesData;
var audioData = audioTrack.pesData;
var id3Data = id3Track.pesData; // try to parse last PES packets
var pes;
if (avcData && (pes = parsePES(avcData))) {
this.parseAVCPES(pes, true);
avcTrack.pesData = null;
} else {
// either avcData null or PES truncated, keep it for next frag parsing
avcTrack.pesData = avcData;
}
if (audioData && (pes = parsePES(audioData))) {
if (audioTrack.isAAC) {
this.parseAACPES(pes);
} else {
this.parseMPEGPES(pes);
}
audioTrack.pesData = null;
} else {
if (audioData !== null && audioData !== void 0 && audioData.size) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('last AAC PES packet truncated,might overlap between fragments');
} // either audioData null or PES truncated, keep it for next frag parsing
audioTrack.pesData = audioData;
}
if (id3Data && (pes = parsePES(id3Data))) {
this.parseID3PES(pes);
id3Track.pesData = null;
} else {
// either id3Data null or PES truncated, keep it for next frag parsing
id3Track.pesData = id3Data;
}
};
_proto.demuxSampleAes = function demuxSampleAes(data, keyData, timeOffset) {
var demuxResult = this.demux(data, timeOffset, true, !this.config.progressive);
var sampleAes = this.sampleAes = new _sample_aes__WEBPACK_IMPORTED_MODULE_4__["default"](this.observer, this.config, keyData);
return this.decrypt(demuxResult, sampleAes);
};
_proto.decrypt = function decrypt(demuxResult, sampleAes) {
return new Promise(function (resolve) {
var audioTrack = demuxResult.audioTrack,
avcTrack = demuxResult.avcTrack;
if (audioTrack.samples && audioTrack.isAAC) {
sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
if (avcTrack.samples) {
sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () {
resolve(demuxResult);
});
} else {
resolve(demuxResult);
}
});
} else if (avcTrack.samples) {
sampleAes.decryptAvcSamples(avcTrack.samples, 0, 0, function () {
resolve(demuxResult);
});
}
});
};
_proto.destroy = function destroy() {
this._initPTS = this._initDTS = null;
this._duration = 0;
};
_proto.parseAVCPES = function parseAVCPES(pes, last) {
var _this = this;
var track = this._avcTrack;
var units = this.parseAVCNALu(pes.data);
var debug = false;
var avcSample = this.avcSample;
var push;
var spsfound = false; // free pes.data to save up some memory
pes.data = null; // if new NAL units found and last sample still there, let's push ...
// this helps parsing streams with missing AUD (only do this if AUD never found)
if (avcSample && units.length && !track.audFound) {
pushAccessUnit(avcSample, track);
avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
}
units.forEach(function (unit) {
switch (unit.type) {
// NDR
case 1:
{
push = true;
if (!avcSample) {
avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
}
if (debug) {
avcSample.debug += 'NDR ';
}
avcSample.frame = true;
var data = unit.data; // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
if (spsfound && data.length > 4) {
// retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
var sliceType = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](data).readSliceType(); // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
// SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
// An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
// I slice: A slice that is not an SI slice that is decoded using intra prediction only.
// if (sliceType === 2 || sliceType === 7) {
if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
avcSample.key = true;
}
}
break; // IDR
}
case 5:
push = true; // handle PES not starting with AUD
if (!avcSample) {
avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
}
if (debug) {
avcSample.debug += 'IDR ';
}
avcSample.key = true;
avcSample.frame = true;
break;
// SEI
case 6:
{
push = true;
if (debug && avcSample) {
avcSample.debug += 'SEI ';
}
var expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](discardEPB(unit.data)); // skip frameType
expGolombDecoder.readUByte();
var payloadType = 0;
var payloadSize = 0;
var endOfCaptions = false;
var b = 0;
while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
payloadType = 0;
do {
b = expGolombDecoder.readUByte();
payloadType += b;
} while (b === 0xff); // Parse payload size.
payloadSize = 0;
do {
b = expGolombDecoder.readUByte();
payloadSize += b;
} while (b === 0xff); // TODO: there can be more than one payload in an SEI packet...
// TODO: need to read type and size in a while loop to get them all
if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
endOfCaptions = true;
var countryCode = expGolombDecoder.readUByte();
if (countryCode === 181) {
var providerCode = expGolombDecoder.readUShort();
if (providerCode === 49) {
var userStructure = expGolombDecoder.readUInt();
if (userStructure === 0x47413934) {
var userDataType = expGolombDecoder.readUByte(); // Raw CEA-608 bytes wrapped in CEA-708 packet
if (userDataType === 3) {
var firstByte = expGolombDecoder.readUByte();
var secondByte = expGolombDecoder.readUByte();
var totalCCs = 31 & firstByte;
var byteArray = [firstByte, secondByte];
for (var i = 0; i < totalCCs; i++) {
// 3 bytes per CC
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
}
insertSampleInOrder(_this._txtTrack.samples, {
type: 3,
pts: pes.pts,
bytes: byteArray
});
}
}
}
}
} else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {
endOfCaptions = true;
if (payloadSize > 16) {
var uuidStrArray = [];
for (var _i = 0; _i < 16; _i++) {
uuidStrArray.push(expGolombDecoder.readUByte().toString(16));
if (_i === 3 || _i === 5 || _i === 7 || _i === 9) {
uuidStrArray.push('-');
}
}
var length = payloadSize - 16;
var userDataPayloadBytes = new Uint8Array(length);
for (var _i2 = 0; _i2 < length; _i2++) {
userDataPayloadBytes[_i2] = expGolombDecoder.readUByte();
}
insertSampleInOrder(_this._txtTrack.samples, {
pts: pes.pts,
payloadType: payloadType,
uuid: uuidStrArray.join(''),
userData: Object(_id3__WEBPACK_IMPORTED_MODULE_3__["utf8ArrayToStr"])(userDataPayloadBytes),
userDataBytes: userDataPayloadBytes
});
}
} else if (payloadSize < expGolombDecoder.bytesAvailable) {
for (var _i3 = 0; _i3 < payloadSize; _i3++) {
expGolombDecoder.readUByte();
}
}
}
break; // SPS
}
case 7:
push = true;
spsfound = true;
if (debug && avcSample) {
avcSample.debug += 'SPS ';
}
if (!track.sps) {
var _expGolombDecoder = new _exp_golomb__WEBPACK_IMPORTED_MODULE_2__["default"](unit.data);
var config = _expGolombDecoder.readSPS();
track.width = config.width;
track.height = config.height;
track.pixelRatio = config.pixelRatio; // TODO: `track.sps` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.
track.sps = [unit.data];
track.duration = _this._duration;
var codecarray = unit.data.subarray(1, 4);
var codecstring = 'avc1.';
for (var _i4 = 0; _i4 < 3; _i4++) {
var h = codecarray[_i4].toString(16);
if (h.length < 2) {
h = '0' + h;
}
codecstring += h;
}
track.codec = codecstring;
}
break;
// PPS
case 8:
push = true;
if (debug && avcSample) {
avcSample.debug += 'PPS ';
}
if (!track.pps) {
// TODO: `track.pss` is defined as a `number[]`, but we're setting it to a `Uint8Array[]`.
track.pps = [unit.data];
}
break;
// AUD
case 9:
push = false;
track.audFound = true;
if (avcSample) {
pushAccessUnit(avcSample, track);
}
avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
break;
// Filler Data
case 12:
push = false;
break;
default:
push = false;
if (avcSample) {
avcSample.debug += 'unknown NAL ' + unit.type + ' ';
}
break;
}
if (avcSample && push) {
var _units = avcSample.units;
_units.push(unit);
}
}); // if last PES packet, push samples
if (last && avcSample) {
pushAccessUnit(avcSample, track);
this.avcSample = null;
}
};
_proto.getLastNalUnit = function getLastNalUnit() {
var _avcSample;
var avcSample = this.avcSample;
var lastUnit; // try to fallback to previous sample if current one is empty
if (!avcSample || avcSample.units.length === 0) {
var samples = this._avcTrack.samples;
avcSample = samples[samples.length - 1];
}
if ((_avcSample = avcSample) !== null && _avcSample !== void 0 && _avcSample.units) {
var units = avcSample.units;
lastUnit = units[units.length - 1];
}
return lastUnit;
};
_proto.parseAVCNALu = function parseAVCNALu(array) {
var len = array.byteLength;
var track = this._avcTrack;
var state = track.naluState || 0;
var lastState = state;
var units = [];
var i = 0;
var value;
var overflow;
var unitType;
var lastUnitStart = -1;
var lastUnitType = 0; // logger.log('PES:' + Hex.hexDump(array));
if (state === -1) {
// special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
lastUnitStart = 0; // NALu type is value read from offset 0
lastUnitType = array[0] & 0x1f;
state = 0;
i = 1;
}
while (i < len) {
value = array[i++]; // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
if (!state) {
state = value ? 0 : 1;
continue;
}
if (state === 1) {
state = value ? 0 : 2;
continue;
} // here we have state either equal to 2 or 3
if (!value) {
state = 3;
} else if (value === 1) {
if (lastUnitStart >= 0) {
var unit = {
data: array.subarray(lastUnitStart, i - state - 1),
type: lastUnitType
}; // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
units.push(unit);
} else {
// lastUnitStart is undefined => this is the first start code found in this PES packet
// first check if start code delimiter is overlapping between 2 PES packets,
// ie it started in last packet (lastState not zero)
// and ended at the beginning of this PES packet (i <= 4 - lastState)
var lastUnit = this.getLastNalUnit();
if (lastUnit) {
if (lastState && i <= 4 - lastState) {
// start delimiter overlapping between PES packets
// strip start delimiter bytes from the end of last NAL unit
// check if lastUnit had a state different from zero
if (lastUnit.state) {
// strip last bytes
lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
}
} // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
overflow = i - state - 1;
if (overflow > 0) {
// logger.log('first NALU found with overflow:' + overflow);
var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
tmp.set(lastUnit.data, 0);
tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
lastUnit.data = tmp;
}
}
} // check if we can read unit type
if (i < len) {
unitType = array[i] & 0x1f; // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
lastUnitStart = i;
lastUnitType = unitType;
state = 0;
} else {
// not enough byte to read unit type. let's read it on next PES parsing
state = -1;
}
} else {
state = 0;
}
}
if (lastUnitStart >= 0 && state >= 0) {
var _unit = {
data: array.subarray(lastUnitStart, len),
type: lastUnitType,
state: state
};
units.push(_unit); // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
} // no NALu found
if (units.length === 0) {
// append pes.data to previous NAL unit
var _lastUnit = this.getLastNalUnit();
if (_lastUnit) {
var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
_tmp.set(_lastUnit.data, 0);
_tmp.set(array, _lastUnit.data.byteLength);
_lastUnit.data = _tmp;
}
}
track.naluState = state;
return units;
};
_proto.parseAACPES = function parseAACPES(pes) {
var startOffset = 0;
var track = this._audioTrack;
var aacLastPTS = this.aacLastPTS;
var aacOverFlow = this.aacOverFlow;
var data = pes.data;
if (aacOverFlow) {
var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
tmp.set(aacOverFlow, 0);
tmp.set(data, aacOverFlow.byteLength); // logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
data = tmp;
} // look for ADTS header (0xFFFx)
var offset;
var len;
for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) {
break;
}
} // if ADTS header does not start straight from the beginning of the PES payload, raise an error
if (offset) {
var reason;
var fatal;
if (offset < len - 1) {
reason = "AAC PES did not start with ADTS header,offset:" + offset;
fatal = false;
} else {
reason = 'no ADTS header found in AAC PES';
fatal = true;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn("parsing error:" + reason);
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_5__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorTypes"].MEDIA_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_8__["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: fatal,
reason: reason
});
if (fatal) {
return;
}
}
_adts__WEBPACK_IMPORTED_MODULE_0__["initTrackConfig"](track, this.observer, data, offset, this.audioCodec);
var frameIndex = 0;
var frameDuration = _adts__WEBPACK_IMPORTED_MODULE_0__["getFrameDuration"](track.samplerate); // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
// first sample PTS should be equal to last sample PTS + frameDuration
var pts;
if (pes.pts !== undefined) {
pts = pes.pts;
} else if (aacLastPTS !== null) {
pts = aacLastPTS;
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: AAC PES unknown PTS');
return;
}
if (aacOverFlow && aacLastPTS !== null) {
var newPTS = aacLastPTS + frameDuration;
if (Math.abs(newPTS - pts) > 1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log("[tsdemuxer]: AAC: align PTS for overlapping frames by " + Math.round((newPTS - pts) / 90));
pts = newPTS;
}
} // scan for aac samples
var stamp = null;
while (offset < len) {
if (_adts__WEBPACK_IMPORTED_MODULE_0__["isHeader"](data, offset)) {
if (offset + 5 < len) {
var frame = _adts__WEBPACK_IMPORTED_MODULE_0__["appendFrame"](track, data, offset, pts, frameIndex);
if (frame) {
offset += frame.length;
stamp = frame.sample.pts;
frameIndex++;
continue;
}
} // We are at an ADTS header, but do not have enough data for a frame
// Remaining data will be added to aacOverFlow
break;
} else {
// nothing found, keep looking
offset++;
}
}
this.aacOverFlow = offset < len ? data.subarray(offset, len) : null;
this.aacLastPTS = stamp;
};
_proto.parseMPEGPES = function parseMPEGPES(pes) {
var data = pes.data;
var length = data.length;
var frameIndex = 0;
var offset = 0;
var pts = pes.pts;
if (pts === undefined) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: MPEG PES unknown PTS');
return;
}
while (offset < length) {
if (_mpegaudio__WEBPACK_IMPORTED_MODULE_1__["isHeader"](data, offset)) {
var frame = _mpegaudio__WEBPACK_IMPORTED_MODULE_1__["appendFrame"](this._audioTrack, data, offset, pts, frameIndex);
if (frame) {
offset += frame.length;
frameIndex++;
} else {
// logger.log('Unable to parse Mpeg audio frame');
break;
}
} else {
// nothing found, keep looking
offset++;
}
}
};
_proto.parseID3PES = function parseID3PES(pes) {
if (pes.pts === undefined) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('[tsdemuxer]: ID3 PES unknown PTS');
return;
}
this._id3Track.samples.push(pes);
};
return TSDemuxer;
}();
TSDemuxer.minProbeByteLength = 188;
function createAVCSample(key, pts, dts, debug) {
return {
key: key,
frame: false,
pts: pts,
dts: dts,
units: [],
debug: debug,
length: 0
};
}
function parsePAT(data, offset) {
// skip the PSI header and parse the first PMT entry
return (data[offset + 10] & 0x1f) << 8 | data[offset + 11]; // logger.log('PMT PID:' + this._pmtId);
}
function parsePMT(data, offset, mpegSupported, isSampleAes) {
var result = {
audio: -1,
avc: -1,
id3: -1,
isAAC: true
};
var sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
var tableEnd = offset + 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
// long the program info descriptors are
var programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11]; // advance the offset to the first entry in the mapping table
offset += 12 + programInfoLength;
while (offset < tableEnd) {
var pid = (data[offset + 1] & 0x1f) << 8 | data[offset + 2];
switch (data[offset]) {
case 0xcf:
// SAMPLE-AES AAC
if (!isSampleAes) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream');
break;
}
/* falls through */
case 0x0f:
// ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
// logger.log('AAC PID:' + pid);
if (result.audio === -1) {
result.audio = pid;
}
break;
// Packetized metadata (ID3)
case 0x15:
// logger.log('ID3 PID:' + pid);
if (result.id3 === -1) {
result.id3 = pid;
}
break;
case 0xdb:
// SAMPLE-AES AVC
if (!isSampleAes) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('H.264 with AES-128-CBC slice encryption found in unencrypted stream');
break;
}
/* falls through */
case 0x1b:
// ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
// logger.log('AVC PID:' + pid);
if (result.avc === -1) {
result.avc = pid;
}
break;
// ISO/IEC 11172-3 (MPEG-1 audio)
// or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
case 0x03:
case 0x04:
// logger.log('MPEG PID:' + pid);
if (!mpegSupported) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log('MPEG audio found, not supported in this browser');
} else if (result.audio === -1) {
result.audio = pid;
result.isAAC = false;
}
break;
case 0x24:
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn('Unsupported HEVC stream type found');
break;
default:
// logger.log('unknown stream type:' + data[offset]);
break;
} // move to the next table entry
// skip past the elementary stream descriptors, if present
offset += ((data[offset + 3] & 0x0f) << 8 | data[offset + 4]) + 5;
}
return result;
}
function parsePES(stream) {
var i = 0;
var frag;
var pesLen;
var pesHdrLen;
var pesPts;
var pesDts;
var data = stream.data; // safety check
if (!stream || stream.size === 0) {
return null;
} // we might need up to 19 bytes to read PES header
// if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
// usually only one merge is needed (and this is rare ...)
while (data[0].length < 19 && data.length > 1) {
var newData = new Uint8Array(data[0].length + data[1].length);
newData.set(data[0]);
newData.set(data[1], data[0].length);
data[0] = newData;
data.splice(1, 1);
} // retrieve PTS/DTS from first fragment
frag = data[0];
var pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
if (pesPrefix === 1) {
pesLen = (frag[4] << 8) + frag[5]; // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
// minus 6 : PES header size
if (pesLen && pesLen > stream.size - 6) {
return null;
}
var pesFlags = frag[7];
if (pesFlags & 0xc0) {
/* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
as Bitwise operators treat their operands as a sequence of 32 bits */
pesPts = (frag[9] & 0x0e) * 536870912 + // 1 << 29
(frag[10] & 0xff) * 4194304 + // 1 << 22
(frag[11] & 0xfe) * 16384 + // 1 << 14
(frag[12] & 0xff) * 128 + // 1 << 7
(frag[13] & 0xfe) / 2;
if (pesFlags & 0x40) {
pesDts = (frag[14] & 0x0e) * 536870912 + // 1 << 29
(frag[15] & 0xff) * 4194304 + // 1 << 22
(frag[16] & 0xfe) * 16384 + // 1 << 14
(frag[17] & 0xff) * 128 + // 1 << 7
(frag[18] & 0xfe) / 2;
if (pesPts - pesDts > 60 * 90000) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
pesPts = pesDts;
}
} else {
pesDts = pesPts;
}
}
pesHdrLen = frag[8]; // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
var payloadStartOffset = pesHdrLen + 9;
if (stream.size <= payloadStartOffset) {
return null;
}
stream.size -= payloadStartOffset; // reassemble PES packet
var pesData = new Uint8Array(stream.size);
for (var j = 0, dataLen = data.length; j < dataLen; j++) {
frag = data[j];
var len = frag.byteLength;
if (payloadStartOffset) {
if (payloadStartOffset > len) {
// trim full frag if PES header bigger than frag
payloadStartOffset -= len;
continue;
} else {
// trim partial frag if PES header smaller than frag
frag = frag.subarray(payloadStartOffset);
len -= payloadStartOffset;
payloadStartOffset = 0;
}
}
pesData.set(frag, i);
i += len;
}
if (pesLen) {
// payload size : remove PES header + PES extension
pesLen -= pesHdrLen + 3;
}
return {
data: pesData,
pts: pesPts,
dts: pesDts,
len: pesLen
};
}
return null;
}
function pushAccessUnit(avcSample, avcTrack) {
if (avcSample.units.length && avcSample.frame) {
// if sample does not have PTS/DTS, patch with last sample PTS/DTS
if (avcSample.pts === undefined) {
var samples = avcTrack.samples;
var nbSamples = samples.length;
if (nbSamples) {
var lastSample = samples[nbSamples - 1];
avcSample.pts = lastSample.pts;
avcSample.dts = lastSample.dts;
} else {
// dropping samples, no timestamp found
avcTrack.dropped++;
return;
}
}
avcTrack.samples.push(avcSample);
}
if (avcSample.debug.length) {
_utils_logger__WEBPACK_IMPORTED_MODULE_7__["logger"].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
}
}
function insertSampleInOrder(arr, data) {
var len = arr.length;
if (len > 0) {
if (data.pts >= arr[len - 1].pts) {
arr.push(data);
} else {
for (var pos = len - 1; pos >= 0; pos--) {
if (data.pts < arr[pos].pts) {
arr.splice(pos, 0, data);
break;
}
}
}
} else {
arr.push(data);
}
}
/**
* remove Emulation Prevention bytes from a RBSP
*/
function discardEPB(data) {
var length = data.byteLength;
var EPBPositions = [];
var i = 1; // Find all `Emulation Prevention Bytes`
while (i < length - 2) {
if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
EPBPositions.push(i + 2);
i += 2;
} else {
i++;
}
} // If no Emulation Prevention Bytes were found just return the original
// array
if (EPBPositions.length === 0) {
return data;
} // Create a new array to hold the NAL unit data
var newLength = length - EPBPositions.length;
var newData = new Uint8Array(newLength);
var sourceIndex = 0;
for (i = 0; i < newLength; sourceIndex++, i++) {
if (sourceIndex === EPBPositions[0]) {
// Skip this byte
sourceIndex++; // Remove this position index
EPBPositions.shift();
}
newData[i] = data[sourceIndex];
}
return newData;
}
/* harmony default export */ __webpack_exports__["default"] = (TSDemuxer);
/***/ }),
/***/ "./src/errors.ts":
/*!***********************!*\
!*** ./src/errors.ts ***!
\***********************/
/*! exports provided: ErrorTypes, ErrorDetails */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorTypes", function() { return ErrorTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorDetails", function() { return ErrorDetails; });
var ErrorTypes;
/**
* @enum {ErrorDetails}
* @typedef {string} ErrorDetail
*/
(function (ErrorTypes) {
ErrorTypes["NETWORK_ERROR"] = "networkError";
ErrorTypes["MEDIA_ERROR"] = "mediaError";
ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
ErrorTypes["MUX_ERROR"] = "muxError";
ErrorTypes["OTHER_ERROR"] = "otherError";
})(ErrorTypes || (ErrorTypes = {}));
var ErrorDetails;
(function (ErrorDetails) {
ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
ErrorDetails["KEY_SYSTEM_NO_INIT_DATA"] = "keySystemNoInitData";
ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
ErrorDetails["SUBTITLE_LOAD_ERROR"] = "subtitleTrackLoadError";
ErrorDetails["SUBTITLE_TRACK_LOAD_TIMEOUT"] = "subtitleTrackLoadTimeOut";
ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
ErrorDetails["BUFFER_INCOMPATIBLE_CODECS_ERROR"] = "bufferIncompatibleCodecsError";
ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
ErrorDetails["INTERNAL_ABORTED"] = "aborted";
ErrorDetails["UNKNOWN"] = "unknown";
})(ErrorDetails || (ErrorDetails = {}));
/***/ }),
/***/ "./src/events.ts":
/*!***********************!*\
!*** ./src/events.ts ***!
\***********************/
/*! exports provided: Events */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Events", function() { return Events; });
/**
* @readonly
* @enum {string}
*/
var Events;
(function (Events) {
Events["MEDIA_ATTACHING"] = "hlsMediaAttaching";
Events["MEDIA_ATTACHED"] = "hlsMediaAttached";
Events["MEDIA_DETACHING"] = "hlsMediaDetaching";
Events["MEDIA_DETACHED"] = "hlsMediaDetached";
Events["BUFFER_RESET"] = "hlsBufferReset";
Events["BUFFER_CODECS"] = "hlsBufferCodecs";
Events["BUFFER_CREATED"] = "hlsBufferCreated";
Events["BUFFER_APPENDING"] = "hlsBufferAppending";
Events["BUFFER_APPENDED"] = "hlsBufferAppended";
Events["BUFFER_EOS"] = "hlsBufferEos";
Events["BUFFER_FLUSHING"] = "hlsBufferFlushing";
Events["BUFFER_FLUSHED"] = "hlsBufferFlushed";
Events["MANIFEST_LOADING"] = "hlsManifestLoading";
Events["MANIFEST_LOADED"] = "hlsManifestLoaded";
Events["MANIFEST_PARSED"] = "hlsManifestParsed";
Events["LEVEL_SWITCHING"] = "hlsLevelSwitching";
Events["LEVEL_SWITCHED"] = "hlsLevelSwitched";
Events["LEVEL_LOADING"] = "hlsLevelLoading";
Events["LEVEL_LOADED"] = "hlsLevelLoaded";
Events["LEVEL_UPDATED"] = "hlsLevelUpdated";
Events["LEVEL_PTS_UPDATED"] = "hlsLevelPtsUpdated";
Events["LEVELS_UPDATED"] = "hlsLevelsUpdated";
Events["AUDIO_TRACKS_UPDATED"] = "hlsAudioTracksUpdated";
Events["AUDIO_TRACK_SWITCHING"] = "hlsAudioTrackSwitching";
Events["AUDIO_TRACK_SWITCHED"] = "hlsAudioTrackSwitched";
Events["AUDIO_TRACK_LOADING"] = "hlsAudioTrackLoading";
Events["AUDIO_TRACK_LOADED"] = "hlsAudioTrackLoaded";
Events["SUBTITLE_TRACKS_UPDATED"] = "hlsSubtitleTracksUpdated";
Events["SUBTITLE_TRACKS_CLEARED"] = "hlsSubtitleTracksCleared";
Events["SUBTITLE_TRACK_SWITCH"] = "hlsSubtitleTrackSwitch";
Events["SUBTITLE_TRACK_LOADING"] = "hlsSubtitleTrackLoading";
Events["SUBTITLE_TRACK_LOADED"] = "hlsSubtitleTrackLoaded";
Events["SUBTITLE_FRAG_PROCESSED"] = "hlsSubtitleFragProcessed";
Events["CUES_PARSED"] = "hlsCuesParsed";
Events["NON_NATIVE_TEXT_TRACKS_FOUND"] = "hlsNonNativeTextTracksFound";
Events["INIT_PTS_FOUND"] = "hlsInitPtsFound";
Events["FRAG_LOADING"] = "hlsFragLoading";
Events["FRAG_LOAD_EMERGENCY_ABORTED"] = "hlsFragLoadEmergencyAborted";
Events["FRAG_LOADED"] = "hlsFragLoaded";
Events["FRAG_DECRYPTED"] = "hlsFragDecrypted";
Events["FRAG_PARSING_INIT_SEGMENT"] = "hlsFragParsingInitSegment";
Events["FRAG_PARSING_USERDATA"] = "hlsFragParsingUserdata";
Events["FRAG_PARSING_METADATA"] = "hlsFragParsingMetadata";
Events["FRAG_PARSED"] = "hlsFragParsed";
Events["FRAG_BUFFERED"] = "hlsFragBuffered";
Events["FRAG_CHANGED"] = "hlsFragChanged";
Events["FPS_DROP"] = "hlsFpsDrop";
Events["FPS_DROP_LEVEL_CAPPING"] = "hlsFpsDropLevelCapping";
Events["ERROR"] = "hlsError";
Events["DESTROYING"] = "hlsDestroying";
Events["KEY_LOADING"] = "hlsKeyLoading";
Events["KEY_LOADED"] = "hlsKeyLoaded";
Events["LIVE_BACK_BUFFER_REACHED"] = "hlsLiveBackBufferReached";
Events["BACK_BUFFER_REACHED"] = "hlsBackBufferReached";
})(Events || (Events = {}));
/***/ }),
/***/ "./src/hls.ts":
/*!********************!*\
!*** ./src/hls.ts ***!
\********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Hls; });
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./loader/playlist-loader */ "./src/loader/playlist-loader.ts");
/* harmony import */ var _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./loader/key-loader */ "./src/loader/key-loader.ts");
/* harmony import */ var _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./controller/id3-track-controller */ "./src/controller/id3-track-controller.ts");
/* harmony import */ var _controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./controller/latency-controller */ "./src/controller/latency-controller.ts");
/* harmony import */ var _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./controller/level-controller */ "./src/controller/level-controller.ts");
/* harmony import */ var _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./controller/fragment-tracker */ "./src/controller/fragment-tracker.ts");
/* harmony import */ var _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./controller/stream-controller */ "./src/controller/stream-controller.ts");
/* harmony import */ var _is_supported__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./is-supported */ "./src/is-supported.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./config */ "./src/config.ts");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_11__);
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./errors */ "./src/errors.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* @module Hls
* @class
* @constructor
*/
var Hls = /*#__PURE__*/function () {
Hls.isSupported = function isSupported() {
return Object(_is_supported__WEBPACK_IMPORTED_MODULE_8__["isSupported"])();
};
/**
* Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
*
* @constructs Hls
* @param {HlsConfig} config
*/
function Hls(userConfig) {
if (userConfig === void 0) {
userConfig = {};
}
this.config = void 0;
this.userConfig = void 0;
this.coreComponents = void 0;
this.networkControllers = void 0;
this._emitter = new eventemitter3__WEBPACK_IMPORTED_MODULE_11__["EventEmitter"]();
this._autoLevelCapping = void 0;
this.abrController = void 0;
this.bufferController = void 0;
this.capLevelController = void 0;
this.latencyController = void 0;
this.levelController = void 0;
this.streamController = void 0;
this.audioTrackController = void 0;
this.subtitleTrackController = void 0;
this.emeController = void 0;
this._media = null;
this.url = null;
var config = this.config = Object(_config__WEBPACK_IMPORTED_MODULE_10__["mergeConfig"])(Hls.DefaultConfig, userConfig);
this.userConfig = userConfig;
Object(_utils_logger__WEBPACK_IMPORTED_MODULE_9__["enableLogs"])(config.debug);
this._autoLevelCapping = -1;
if (config.progressive) {
Object(_config__WEBPACK_IMPORTED_MODULE_10__["enableStreamingMode"])(config);
} // core controllers and network loaders
var ConfigAbrController = config.abrController,
ConfigBufferController = config.bufferController,
ConfigCapLevelController = config.capLevelController,
ConfigFpsController = config.fpsController;
var abrController = this.abrController = new ConfigAbrController(this);
var bufferController = this.bufferController = new ConfigBufferController(this);
var capLevelController = this.capLevelController = new ConfigCapLevelController(this);
var fpsController = new ConfigFpsController(this);
var playListLoader = new _loader_playlist_loader__WEBPACK_IMPORTED_MODULE_1__["default"](this);
var keyLoader = new _loader_key_loader__WEBPACK_IMPORTED_MODULE_2__["default"](this);
var id3TrackController = new _controller_id3_track_controller__WEBPACK_IMPORTED_MODULE_3__["default"](this); // network controllers
var levelController = this.levelController = new _controller_level_controller__WEBPACK_IMPORTED_MODULE_5__["default"](this); // FragmentTracker must be defined before StreamController because the order of event handling is important
var fragmentTracker = new _controller_fragment_tracker__WEBPACK_IMPORTED_MODULE_6__["FragmentTracker"](this);
var streamController = this.streamController = new _controller_stream_controller__WEBPACK_IMPORTED_MODULE_7__["default"](this, fragmentTracker); // Cap level controller uses streamController to flush the buffer
capLevelController.setStreamController(streamController); // fpsController uses streamController to switch when frames are being dropped
fpsController.setStreamController(streamController);
var networkControllers = [levelController, streamController];
this.networkControllers = networkControllers;
var coreComponents = [playListLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker];
this.audioTrackController = this.createController(config.audioTrackController, null, networkControllers);
this.createController(config.audioStreamController, fragmentTracker, networkControllers); // subtitleTrackController must be defined before because the order of event handling is important
this.subtitleTrackController = this.createController(config.subtitleTrackController, null, networkControllers);
this.createController(config.subtitleStreamController, fragmentTracker, networkControllers);
this.createController(config.timelineController, null, coreComponents);
this.emeController = this.createController(config.emeController, null, coreComponents);
this.latencyController = this.createController(_controller_latency_controller__WEBPACK_IMPORTED_MODULE_4__["default"], null, coreComponents);
this.coreComponents = coreComponents;
}
var _proto = Hls.prototype;
_proto.createController = function createController(ControllerClass, fragmentTracker, components) {
if (ControllerClass) {
var controllerInstance = fragmentTracker ? new ControllerClass(this, fragmentTracker) : new ControllerClass(this);
if (components) {
components.push(controllerInstance);
}
return controllerInstance;
}
return null;
} // Delegate the EventEmitter through the public API of Hls.js
;
_proto.on = function on(event, listener, context) {
if (context === void 0) {
context = this;
}
this._emitter.on(event, listener, context);
};
_proto.once = function once(event, listener, context) {
if (context === void 0) {
context = this;
}
this._emitter.once(event, listener, context);
};
_proto.removeAllListeners = function removeAllListeners(event) {
this._emitter.removeAllListeners(event);
};
_proto.off = function off(event, listener, context, once) {
if (context === void 0) {
context = this;
}
this._emitter.off(event, listener, context, once);
};
_proto.listeners = function listeners(event) {
return this._emitter.listeners(event);
};
_proto.emit = function emit(event, name, eventObject) {
return this._emitter.emit(event, name, eventObject);
};
_proto.trigger = function trigger(event, eventObject) {
if (this.config.debug) {
return this.emit(event, event, eventObject);
} else {
try {
return this.emit(event, event, eventObject);
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].error('An internal error happened while handling event ' + event + '. Error message: "' + e.message + '". Here is a stacktrace:', e);
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorTypes"].OTHER_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"].INTERNAL_EXCEPTION,
fatal: false,
event: event,
error: e
});
}
}
return false;
};
_proto.listenerCount = function listenerCount(event) {
return this._emitter.listenerCount(event);
}
/**
* Dispose of the instance
*/
;
_proto.destroy = function destroy() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('destroy');
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].DESTROYING, undefined);
this.detachMedia();
this.removeAllListeners();
this._autoLevelCapping = -1;
this.url = null;
this.networkControllers.forEach(function (component) {
return component.destroy();
});
this.networkControllers.length = 0;
this.coreComponents.forEach(function (component) {
return component.destroy();
});
this.coreComponents.length = 0;
}
/**
* Attaches Hls.js to a media element
* @param {HTMLMediaElement} media
*/
;
_proto.attachMedia = function attachMedia(media) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('attachMedia');
this._media = media;
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MEDIA_ATTACHING, {
media: media
});
}
/**
* Detach Hls.js from the media
*/
;
_proto.detachMedia = function detachMedia() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('detachMedia');
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MEDIA_DETACHING, undefined);
this._media = null;
}
/**
* Set the source URL. Can be relative or absolute.
* @param {string} url
*/
;
_proto.loadSource = function loadSource(url) {
this.stopLoad();
var media = this.media;
var loadedSource = this.url;
var loadingSource = this.url = url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"](self.location.href, url, {
alwaysNormalize: true
});
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("loadSource:" + loadingSource);
if (media && loadedSource && loadedSource !== loadingSource && this.bufferController.hasSourceTypes()) {
this.detachMedia();
this.attachMedia(media);
} // when attaching to a source URL, trigger a playlist load
this.trigger(_events__WEBPACK_IMPORTED_MODULE_12__["Events"].MANIFEST_LOADING, {
url: url
});
}
/**
* Start loading data from the stream source.
* Depending on default config, client starts loading automatically when a source is set.
*
* @param {number} startPosition Set the start position to stream from
* @default -1 None (from earliest point)
*/
;
_proto.startLoad = function startLoad(startPosition) {
if (startPosition === void 0) {
startPosition = -1;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("startLoad(" + startPosition + ")");
this.networkControllers.forEach(function (controller) {
controller.startLoad(startPosition);
});
}
/**
* Stop loading of any stream data.
*/
;
_proto.stopLoad = function stopLoad() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('stopLoad');
this.networkControllers.forEach(function (controller) {
controller.stopLoad();
});
}
/**
* Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
*/
;
_proto.swapAudioCodec = function swapAudioCodec() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('swapAudioCodec');
this.streamController.swapAudioCodec();
}
/**
* When the media-element fails, this allows to detach and then re-attach it
* as one call (convenience method).
*
* Automatic recovery of media-errors by this process is configurable.
*/
;
_proto.recoverMediaError = function recoverMediaError() {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log('recoverMediaError');
var media = this._media;
this.detachMedia();
if (media) {
this.attachMedia(media);
}
};
_proto.removeLevel = function removeLevel(levelIndex, urlId) {
if (urlId === void 0) {
urlId = 0;
}
this.levelController.removeLevel(levelIndex, urlId);
}
/**
* @type {Level[]}
*/
;
_createClass(Hls, [{
key: "levels",
get: function get() {
var levels = this.levelController.levels;
return levels ? levels : [];
}
/**
* Index of quality level currently played
* @type {number}
*/
}, {
key: "currentLevel",
get: function get() {
return this.streamController.currentLevel;
}
/**
* Set quality level index immediately .
* This will flush the current buffer to replace the quality asap.
* That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
* @type {number} -1 for automatic level selection
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set currentLevel:" + newLevel);
this.loadLevel = newLevel;
this.abrController.clearTimer();
this.streamController.immediateLevelSwitch();
}
/**
* Index of next quality level loaded as scheduled by stream controller.
* @type {number}
*/
}, {
key: "nextLevel",
get: function get() {
return this.streamController.nextLevel;
}
/**
* Set quality level index for next loaded data.
* This will switch the video quality asap, without interrupting playback.
* May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
* @type {number} -1 for automatic level selection
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set nextLevel:" + newLevel);
this.levelController.manualLevel = newLevel;
this.streamController.nextLevelSwitch();
}
/**
* Return the quality level of the currently or last (of none is loaded currently) segment
* @type {number}
*/
}, {
key: "loadLevel",
get: function get() {
return this.levelController.level;
}
/**
* Set quality level index for next loaded data in a conservative way.
* This will switch the quality without flushing, but interrupt current loading.
* Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
* @type {number} newLevel -1 for automatic level selection
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set loadLevel:" + newLevel);
this.levelController.manualLevel = newLevel;
}
/**
* get next quality level loaded
* @type {number}
*/
}, {
key: "nextLoadLevel",
get: function get() {
return this.levelController.nextLoadLevel;
}
/**
* Set quality level of next loaded segment in a fully "non-destructive" way.
* Same as `loadLevel` but will wait for next switch (until current loading is done).
* @type {number} level
*/
,
set: function set(level) {
this.levelController.nextLoadLevel = level;
}
/**
* Return "first level": like a default level, if not set,
* falls back to index of first level referenced in manifest
* @type {number}
*/
}, {
key: "firstLevel",
get: function get() {
return Math.max(this.levelController.firstLevel, this.minAutoLevel);
}
/**
* Sets "first-level", see getter.
* @type {number}
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set firstLevel:" + newLevel);
this.levelController.firstLevel = newLevel;
}
/**
* Return start level (level of first fragment that will be played back)
* if not overrided by user, first level appearing in manifest will be used as start level
* if -1 : automatic start level selection, playback will start from level matching download bandwidth
* (determined from download of first segment)
* @type {number}
*/
}, {
key: "startLevel",
get: function get() {
return this.levelController.startLevel;
}
/**
* set start level (level of first fragment that will be played back)
* if not overrided by user, first level appearing in manifest will be used as start level
* if -1 : automatic start level selection, playback will start from level matching download bandwidth
* (determined from download of first segment)
* @type {number} newLevel
*/
,
set: function set(newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set startLevel:" + newLevel); // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
if (newLevel !== -1) {
newLevel = Math.max(newLevel, this.minAutoLevel);
}
this.levelController.startLevel = newLevel;
}
/**
* Get the current setting for capLevelToPlayerSize
*
* @type {boolean}
*/
}, {
key: "capLevelToPlayerSize",
get: function get() {
return this.config.capLevelToPlayerSize;
}
/**
* set dynamically set capLevelToPlayerSize against (`CapLevelController`)
*
* @type {boolean}
*/
,
set: function set(shouldStartCapping) {
var newCapLevelToPlayerSize = !!shouldStartCapping;
if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
if (newCapLevelToPlayerSize) {
this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
} else {
this.capLevelController.stopCapping();
this.autoLevelCapping = -1;
this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
}
this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
}
}
/**
* Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
* @type {number}
*/
}, {
key: "autoLevelCapping",
get: function get() {
return this._autoLevelCapping;
}
/**
* get bandwidth estimate
* @type {number}
*/
,
set:
/**
* Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
* @type {number}
*/
function set(newLevel) {
if (this._autoLevelCapping !== newLevel) {
_utils_logger__WEBPACK_IMPORTED_MODULE_9__["logger"].log("set autoLevelCapping:" + newLevel);
this._autoLevelCapping = newLevel;
}
}
/**
* True when automatic level selection enabled
* @type {boolean}
*/
}, {
key: "bandwidthEstimate",
get: function get() {
var bwEstimator = this.abrController.bwEstimator;
if (!bwEstimator) {
return NaN;
}
return bwEstimator.getEstimate();
}
}, {
key: "autoLevelEnabled",
get: function get() {
return this.levelController.manualLevel === -1;
}
/**
* Level set manually (if any)
* @type {number}
*/
}, {
key: "manualLevel",
get: function get() {
return this.levelController.manualLevel;
}
/**
* min level selectable in auto mode according to config.minAutoBitrate
* @type {number}
*/
}, {
key: "minAutoLevel",
get: function get() {
var levels = this.levels,
minAutoBitrate = this.config.minAutoBitrate;
if (!levels) return 0;
var len = levels.length;
for (var i = 0; i < len; i++) {
if (levels[i].maxBitrate > minAutoBitrate) {
return i;
}
}
return 0;
}
/**
* max level selectable in auto mode according to autoLevelCapping
* @type {number}
*/
}, {
key: "maxAutoLevel",
get: function get() {
var levels = this.levels,
autoLevelCapping = this.autoLevelCapping;
var maxAutoLevel;
if (autoLevelCapping === -1 && levels && levels.length) {
maxAutoLevel = levels.length - 1;
} else {
maxAutoLevel = autoLevelCapping;
}
return maxAutoLevel;
}
/**
* next automatically selected quality level
* @type {number}
*/
}, {
key: "nextAutoLevel",
get: function get() {
// ensure next auto level is between min and max auto level
return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel);
}
/**
* this setter is used to force next auto level.
* this is useful to force a switch down in auto mode:
* in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
* forced value is valid for one fragment. upon succesful frag loading at forced level,
* this value will be resetted to -1 by ABR controller.
* @type {number}
*/
,
set: function set(nextLevel) {
this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);
}
/**
* @type {AudioTrack[]}
*/
}, {
key: "audioTracks",
get: function get() {
var audioTrackController = this.audioTrackController;
return audioTrackController ? audioTrackController.audioTracks : [];
}
/**
* index of the selected audio track (index in audio track lists)
* @type {number}
*/
}, {
key: "audioTrack",
get: function get() {
var audioTrackController = this.audioTrackController;
return audioTrackController ? audioTrackController.audioTrack : -1;
}
/**
* selects an audio track, based on its index in audio track lists
* @type {number}
*/
,
set: function set(audioTrackId) {
var audioTrackController = this.audioTrackController;
if (audioTrackController) {
audioTrackController.audioTrack = audioTrackId;
}
}
/**
* get alternate subtitle tracks list from playlist
* @type {MediaPlaylist[]}
*/
}, {
key: "subtitleTracks",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
}
/**
* index of the selected subtitle track (index in subtitle track lists)
* @type {number}
*/
}, {
key: "subtitleTrack",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
},
set:
/**
* select an subtitle track, based on its index in subtitle track lists
* @type {number}
*/
function set(subtitleTrackId) {
var subtitleTrackController = this.subtitleTrackController;
if (subtitleTrackController) {
subtitleTrackController.subtitleTrack = subtitleTrackId;
}
}
/**
* @type {boolean}
*/
}, {
key: "media",
get: function get() {
return this._media;
}
}, {
key: "subtitleDisplay",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
}
/**
* Enable/disable subtitle display rendering
* @type {boolean}
*/
,
set: function set(value) {
var subtitleTrackController = this.subtitleTrackController;
if (subtitleTrackController) {
subtitleTrackController.subtitleDisplay = value;
}
}
/**
* get mode for Low-Latency HLS loading
* @type {boolean}
*/
}, {
key: "lowLatencyMode",
get: function get() {
return this.config.lowLatencyMode;
}
/**
* Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.
* @type {boolean}
*/
,
set: function set(mode) {
this.config.lowLatencyMode = mode;
}
/**
* position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)
* @type {number}
*/
}, {
key: "liveSyncPosition",
get: function get() {
return this.latencyController.liveSyncPosition;
}
/**
* estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)
* returns 0 before first playlist is loaded
* @type {number}
*/
}, {
key: "latency",
get: function get() {
return this.latencyController.latency;
}
/**
* maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```
* configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```
* returns 0 before first playlist is loaded
* @type {number}
*/
}, {
key: "maxLatency",
get: function get() {
return this.latencyController.maxLatency;
}
/**
* target distance from the edge as calculated by the latency controller
* @type {number}
*/
}, {
key: "targetLatency",
get: function get() {
return this.latencyController.targetLatency;
}
/**
* the rate at which the edge of the current live playlist is advancing or 1 if there is none
* @type {number}
*/
}, {
key: "drift",
get: function get() {
return this.latencyController.drift;
}
/**
* set to true when startLoad is called before MANIFEST_PARSED event
* @type {boolean}
*/
}, {
key: "forceStartLoad",
get: function get() {
return this.streamController.forceStartLoad;
}
}], [{
key: "version",
get: function get() {
return "1.0.3-0.canary.7273";
}
}, {
key: "Events",
get: function get() {
return _events__WEBPACK_IMPORTED_MODULE_12__["Events"];
}
}, {
key: "ErrorTypes",
get: function get() {
return _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorTypes"];
}
}, {
key: "ErrorDetails",
get: function get() {
return _errors__WEBPACK_IMPORTED_MODULE_13__["ErrorDetails"];
}
}, {
key: "DefaultConfig",
get: function get() {
if (!Hls.defaultConfig) {
return _config__WEBPACK_IMPORTED_MODULE_10__["hlsDefaultConfig"];
}
return Hls.defaultConfig;
}
/**
* @type {HlsConfig}
*/
,
set: function set(defaultConfig) {
Hls.defaultConfig = defaultConfig;
}
}]);
return Hls;
}();
Hls.defaultConfig = void 0;
/***/ }),
/***/ "./src/is-supported.ts":
/*!*****************************!*\
!*** ./src/is-supported.ts ***!
\*****************************/
/*! exports provided: isSupported, changeTypeSupported */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSupported", function() { return isSupported; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "changeTypeSupported", function() { return changeTypeSupported; });
/* harmony import */ var _utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/mediasource-helper */ "./src/utils/mediasource-helper.ts");
function getSourceBuffer() {
return self.SourceBuffer || self.WebKitSourceBuffer;
}
function isSupported() {
var mediaSource = Object(_utils_mediasource_helper__WEBPACK_IMPORTED_MODULE_0__["getMediaSource"])();
if (!mediaSource) {
return false;
}
var sourceBuffer = getSourceBuffer();
var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'); // if SourceBuffer is exposed ensure its API is valid
// safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
return !!isTypeSupported && !!sourceBufferValidAPI;
}
function changeTypeSupported() {
var _sourceBuffer$prototy;
var sourceBuffer = getSourceBuffer();
return typeof (sourceBuffer === null || sourceBuffer === void 0 ? void 0 : (_sourceBuffer$prototy = sourceBuffer.prototype) === null || _sourceBuffer$prototy === void 0 ? void 0 : _sourceBuffer$prototy.changeType) === 'function';
}
/***/ }),
/***/ "./src/loader/fragment-loader.ts":
/*!***************************************!*\
!*** ./src/loader/fragment-loader.ts ***!
\***************************************/
/*! exports provided: default, LoadError */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FragmentLoader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadError", function() { return LoadError; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb
var FragmentLoader = /*#__PURE__*/function () {
function FragmentLoader(config) {
this.config = void 0;
this.loader = null;
this.partLoadTimeout = -1;
this.config = config;
}
var _proto = FragmentLoader.prototype;
_proto.destroy = function destroy() {
if (this.loader) {
this.loader.destroy();
this.loader = null;
}
};
_proto.abort = function abort() {
if (this.loader) {
// Abort the loader for current fragment. Only one may load at any given time
this.loader.abort();
}
};
_proto.load = function load(frag, _onProgress) {
var _this = this;
var url = frag.url;
if (!url) {
return Promise.reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: frag,
networkDetails: null
}, "Fragment does not have a " + (url ? 'part list' : 'url')));
}
this.abort();
var config = this.config;
var FragmentILoader = config.fLoader;
var DefaultILoader = config.loader;
return new Promise(function (resolve, reject) {
if (_this.loader) {
_this.loader.destroy();
}
var loader = _this.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
var loaderContext = createLoaderContext(frag);
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: 0,
maxRetryDelay: config.fragLoadingMaxRetryTimeout,
highWaterMark: MIN_CHUNK_SIZE
}; // Assign frag stats to the loader's stats reference
frag.stats = loader.stats;
loader.load(loaderContext, loaderConfig, {
onSuccess: function onSuccess(response, stats, context, networkDetails) {
_this.resetLoader(frag, loader);
resolve({
frag: frag,
part: null,
payload: response.data,
networkDetails: networkDetails
});
},
onError: function onError(response, context, networkDetails) {
_this.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: frag,
response: response,
networkDetails: networkDetails
}));
},
onAbort: function onAbort(stats, context, networkDetails) {
_this.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED,
fatal: false,
frag: frag,
networkDetails: networkDetails
}));
},
onTimeout: function onTimeout(response, context, networkDetails) {
_this.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT,
fatal: false,
frag: frag,
networkDetails: networkDetails
}));
},
onProgress: function onProgress(stats, context, data, networkDetails) {
if (_onProgress) {
_onProgress({
frag: frag,
part: null,
payload: data,
networkDetails: networkDetails
});
}
}
});
});
};
_proto.loadPart = function loadPart(frag, part, onProgress) {
var _this2 = this;
this.abort();
var config = this.config;
var FragmentILoader = config.fLoader;
var DefaultILoader = config.loader;
return new Promise(function (resolve, reject) {
if (_this2.loader) {
_this2.loader.destroy();
}
var loader = _this2.loader = frag.loader = FragmentILoader ? new FragmentILoader(config) : new DefaultILoader(config);
var loaderContext = createLoaderContext(frag, part);
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: 0,
maxRetryDelay: config.fragLoadingMaxRetryTimeout,
highWaterMark: MIN_CHUNK_SIZE
}; // Assign part stats to the loader's stats reference
part.stats = loader.stats;
loader.load(loaderContext, loaderConfig, {
onSuccess: function onSuccess(response, stats, context, networkDetails) {
_this2.resetLoader(frag, loader);
_this2.updateStatsFromPart(frag, part);
var partLoadedData = {
frag: frag,
part: part,
payload: response.data,
networkDetails: networkDetails
};
onProgress(partLoadedData);
resolve(partLoadedData);
},
onError: function onError(response, context, networkDetails) {
_this2.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: frag,
part: part,
response: response,
networkDetails: networkDetails
}));
},
onAbort: function onAbort(stats, context, networkDetails) {
frag.stats.aborted = part.stats.aborted;
_this2.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].INTERNAL_ABORTED,
fatal: false,
frag: frag,
part: part,
networkDetails: networkDetails
}));
},
onTimeout: function onTimeout(response, context, networkDetails) {
_this2.resetLoader(frag, loader);
reject(new LoadError({
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].FRAG_LOAD_TIMEOUT,
fatal: false,
frag: frag,
part: part,
networkDetails: networkDetails
}));
}
});
});
};
_proto.updateStatsFromPart = function updateStatsFromPart(frag, part) {
var fragStats = frag.stats;
var partStats = part.stats;
var partTotal = partStats.total;
fragStats.loaded += partStats.loaded;
if (partTotal) {
var estTotalParts = Math.round(frag.duration / part.duration);
var estLoadedParts = Math.min(Math.round(fragStats.loaded / partTotal), estTotalParts);
var estRemainingParts = estTotalParts - estLoadedParts;
var estRemainingBytes = estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);
fragStats.total = fragStats.loaded + estRemainingBytes;
} else {
fragStats.total = Math.max(fragStats.loaded, fragStats.total);
}
var fragLoading = fragStats.loading;
var partLoading = partStats.loading;
if (fragLoading.start) {
// add to fragment loader latency
fragLoading.first += partLoading.first - partLoading.start;
} else {
fragLoading.start = partLoading.start;
fragLoading.first = partLoading.first;
}
fragLoading.end = partLoading.end;
};
_proto.resetLoader = function resetLoader(frag, loader) {
frag.loader = null;
if (this.loader === loader) {
self.clearTimeout(this.partLoadTimeout);
this.loader = null;
}
loader.destroy();
};
return FragmentLoader;
}();
function createLoaderContext(frag, part) {
if (part === void 0) {
part = null;
}
var segment = part || frag;
var loaderContext = {
frag: frag,
part: part,
responseType: 'arraybuffer',
url: segment.url,
rangeStart: 0,
rangeEnd: 0
};
var start = segment.byteRangeStartOffset;
var end = segment.byteRangeEndOffset;
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(start) && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(end)) {
loaderContext.rangeStart = start;
loaderContext.rangeEnd = end;
}
return loaderContext;
}
var LoadError = /*#__PURE__*/function (_Error) {
_inheritsLoose(LoadError, _Error);
function LoadError(data) {
var _this3;
for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
_this3 = _Error.call.apply(_Error, [this].concat(params)) || this;
_this3.data = void 0;
_this3.data = data;
return _this3;
}
return LoadError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
/***/ }),
/***/ "./src/loader/fragment.ts":
/*!********************************!*\
!*** ./src/loader/fragment.ts ***!
\********************************/
/*! exports provided: ElementaryStreamTypes, BaseSegment, Fragment, Part */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElementaryStreamTypes", function() { return ElementaryStreamTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseSegment", function() { return BaseSegment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Fragment", function() { return Fragment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Part", function() { return Part; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts");
/* harmony import */ var _load_stats__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./load-stats */ "./src/loader/load-stats.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var ElementaryStreamTypes;
(function (ElementaryStreamTypes) {
ElementaryStreamTypes["AUDIO"] = "audio";
ElementaryStreamTypes["VIDEO"] = "video";
ElementaryStreamTypes["AUDIOVIDEO"] = "audiovideo";
})(ElementaryStreamTypes || (ElementaryStreamTypes = {}));
var BaseSegment = /*#__PURE__*/function () {
// baseurl is the URL to the playlist
// relurl is the portion of the URL that comes from inside the playlist.
// Holds the types of data this fragment supports
function BaseSegment(baseurl) {
var _this$elementaryStrea;
this._byteRange = null;
this._url = null;
this.baseurl = void 0;
this.relurl = void 0;
this.elementaryStreams = (_this$elementaryStrea = {}, _this$elementaryStrea[ElementaryStreamTypes.AUDIO] = null, _this$elementaryStrea[ElementaryStreamTypes.VIDEO] = null, _this$elementaryStrea[ElementaryStreamTypes.AUDIOVIDEO] = null, _this$elementaryStrea);
this.baseurl = baseurl;
} // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
var _proto = BaseSegment.prototype;
_proto.setByteRange = function setByteRange(value, previous) {
var params = value.split('@', 2);
var byteRange = [];
if (params.length === 1) {
byteRange[0] = previous ? previous.byteRangeEndOffset : 0;
} else {
byteRange[0] = parseInt(params[1]);
}
byteRange[1] = parseInt(params[0]) + byteRange[0];
this._byteRange = byteRange;
};
_createClass(BaseSegment, [{
key: "byteRange",
get: function get() {
if (!this._byteRange) {
return [];
}
return this._byteRange;
}
}, {
key: "byteRangeStartOffset",
get: function get() {
return this.byteRange[0];
}
}, {
key: "byteRangeEndOffset",
get: function get() {
return this.byteRange[1];
}
}, {
key: "url",
get: function get() {
if (!this._url && this.baseurl && this.relurl) {
this._url = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"])(this.baseurl, this.relurl, {
alwaysNormalize: true
});
}
return this._url || '';
},
set: function set(value) {
this._url = value;
}
}]);
return BaseSegment;
}();
var Fragment = /*#__PURE__*/function (_BaseSegment) {
_inheritsLoose(Fragment, _BaseSegment);
// EXTINF has to be present for a m38 to be considered valid
// sn notates the sequence number for a segment, and if set to a string can be 'initSegment'
// levelkey is the EXT-X-KEY that applies to this segment for decryption
// core difference from the private field _decryptdata is the lack of the initialized IV
// _decryptdata will set the IV for this segment based on the segment number in the fragment
// A string representing the fragment type
// A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading
// The level/track index to which the fragment belongs
// The continuity counter of the fragment
// The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
// The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.
// The latest Presentation Time Stamp (PTS) appended to the buffer.
// The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
// The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.
// The start time of the fragment, as listed in the manifest. Updated after transmux complete.
// Set by `updateFragPTSDTS` in level-helper
// The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
// The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.
// Load/parse timing information
// A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered
// #EXTINF segment title
function Fragment(type, baseurl) {
var _this;
_this = _BaseSegment.call(this, baseurl) || this;
_this._decryptdata = null;
_this.rawProgramDateTime = null;
_this.programDateTime = null;
_this.tagList = [];
_this.duration = 0;
_this.sn = 0;
_this.levelkey = void 0;
_this.type = void 0;
_this.loader = null;
_this.level = -1;
_this.cc = 0;
_this.startPTS = void 0;
_this.endPTS = void 0;
_this.appendedPTS = void 0;
_this.startDTS = void 0;
_this.endDTS = void 0;
_this.start = 0;
_this.deltaPTS = void 0;
_this.maxStartPTS = void 0;
_this.minEndPTS = void 0;
_this.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"]();
_this.urlId = 0;
_this.data = void 0;
_this.bitrateTest = false;
_this.title = null;
_this.type = type;
return _this;
}
var _proto2 = Fragment.prototype;
/**
* Utility method for parseLevelPlaylist to create an initialization vector for a given segment
* @param {number} segmentNumber - segment number to generate IV with
* @returns {Uint8Array}
*/
_proto2.createInitializationVector = function createInitializationVector(segmentNumber) {
var uint8View = new Uint8Array(16);
for (var i = 12; i < 16; i++) {
uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
}
return uint8View;
}
/**
* Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
* @param levelkey - a playlist's encryption info
* @param segmentNumber - the fragment's segment number
* @returns {LevelKey} - an object to be applied as a fragment's decryptdata
*/
;
_proto2.setDecryptDataFromLevelKey = function setDecryptDataFromLevelKey(levelkey, segmentNumber) {
var decryptdata = levelkey;
if ((levelkey === null || levelkey === void 0 ? void 0 : levelkey.method) === 'AES-128' && levelkey.uri && !levelkey.iv) {
decryptdata = _level_key__WEBPACK_IMPORTED_MODULE_3__["LevelKey"].fromURI(levelkey.uri);
decryptdata.method = levelkey.method;
decryptdata.iv = this.createInitializationVector(segmentNumber);
decryptdata.keyFormat = 'identity';
}
return decryptdata;
};
_proto2.setElementaryStreamInfo = function setElementaryStreamInfo(type, startPTS, endPTS, startDTS, endDTS, partial) {
if (partial === void 0) {
partial = false;
}
var elementaryStreams = this.elementaryStreams;
var info = elementaryStreams[type];
if (!info) {
elementaryStreams[type] = {
startPTS: startPTS,
endPTS: endPTS,
startDTS: startDTS,
endDTS: endDTS,
partial: partial
};
return;
}
info.startPTS = Math.min(info.startPTS, startPTS);
info.endPTS = Math.max(info.endPTS, endPTS);
info.startDTS = Math.min(info.startDTS, startDTS);
info.endDTS = Math.max(info.endDTS, endDTS);
};
_proto2.clearElementaryStreamInfo = function clearElementaryStreamInfo() {
var elementaryStreams = this.elementaryStreams;
elementaryStreams[ElementaryStreamTypes.AUDIO] = null;
elementaryStreams[ElementaryStreamTypes.VIDEO] = null;
elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;
};
_createClass(Fragment, [{
key: "decryptdata",
get: function get() {
if (!this.levelkey && !this._decryptdata) {
return null;
}
if (!this._decryptdata && this.levelkey) {
var sn = this.sn;
if (typeof sn !== 'number') {
// We are fetching decryption data for a initialization segment
// If the segment was encrypted with AES-128
// It must have an IV defined. We cannot substitute the Segment Number in.
if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("missing IV for initialization segment with method=\"" + this.levelkey.method + "\" - compliance issue");
}
/*
Be converted to a Number.
'initSegment' will become NaN.
NaN, which when converted through ToInt32() -> +0.
---
Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
*/
sn = 0;
}
this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);
}
return this._decryptdata;
}
}, {
key: "end",
get: function get() {
return this.start + this.duration;
}
}, {
key: "endProgramDateTime",
get: function get() {
if (this.programDateTime === null) {
return null;
}
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.programDateTime)) {
return null;
}
var duration = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.duration) ? 0 : this.duration;
return this.programDateTime + duration * 1000;
}
}, {
key: "encrypted",
get: function get() {
var _this$decryptdata;
// At the m3u8-parser level we need to add support for manifest signalled keyformats
// when we want the fragment to start reporting that it is encrypted.
// Currently, keyFormat will only be set for identity keys
if ((_this$decryptdata = this.decryptdata) !== null && _this$decryptdata !== void 0 && _this$decryptdata.keyFormat && this.decryptdata.uri) {
return true;
}
return false;
}
}]);
return Fragment;
}(BaseSegment);
var Part = /*#__PURE__*/function (_BaseSegment2) {
_inheritsLoose(Part, _BaseSegment2);
function Part(partAttrs, frag, baseurl, index, previous) {
var _this2;
_this2 = _BaseSegment2.call(this, baseurl) || this;
_this2.fragOffset = 0;
_this2.duration = 0;
_this2.gap = false;
_this2.independent = false;
_this2.relurl = void 0;
_this2.fragment = void 0;
_this2.index = void 0;
_this2.stats = new _load_stats__WEBPACK_IMPORTED_MODULE_4__["LoadStats"]();
_this2.duration = partAttrs.decimalFloatingPoint('DURATION');
_this2.gap = partAttrs.bool('GAP');
_this2.independent = partAttrs.bool('INDEPENDENT');
_this2.relurl = partAttrs.enumeratedString('URI');
_this2.fragment = frag;
_this2.index = index;
var byteRange = partAttrs.enumeratedString('BYTERANGE');
if (byteRange) {
_this2.setByteRange(byteRange, previous);
}
if (previous) {
_this2.fragOffset = previous.fragOffset + previous.duration;
}
return _this2;
}
_createClass(Part, [{
key: "start",
get: function get() {
return this.fragment.start + this.fragOffset;
}
}, {
key: "end",
get: function get() {
return this.start + this.duration;
}
}, {
key: "loaded",
get: function get() {
var elementaryStreams = this.elementaryStreams;
return !!(elementaryStreams.audio || elementaryStreams.video || elementaryStreams.audiovideo);
}
}]);
return Part;
}(BaseSegment);
/***/ }),
/***/ "./src/loader/key-loader.ts":
/*!**********************************!*\
!*** ./src/loader/key-loader.ts ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return KeyLoader; });
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/*
* Decrypt key Loader
*/
var KeyLoader = /*#__PURE__*/function () {
function KeyLoader(hls) {
this.hls = void 0;
this.loaders = {};
this.decryptkey = null;
this.decrypturl = null;
this.hls = hls;
this._registerListeners();
}
var _proto = KeyLoader.prototype;
_proto._registerListeners = function _registerListeners() {
this.hls.on(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading, this);
};
_proto._unregisterListeners = function _unregisterListeners() {
this.hls.off(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADING, this.onKeyLoading);
};
_proto.destroy = function destroy() {
this._unregisterListeners();
for (var loaderName in this.loaders) {
var loader = this.loaders[loaderName];
if (loader) {
loader.destroy();
}
}
this.loaders = {};
};
_proto.onKeyLoading = function onKeyLoading(event, data) {
var frag = data.frag;
var type = frag.type;
var loader = this.loaders[type];
if (!frag.decryptdata) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('Missing decryption data on fragment in onKeyLoading');
return;
} // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved
var uri = frag.decryptdata.uri;
if (uri !== this.decrypturl || this.decryptkey === null) {
var config = this.hls.config;
if (loader) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn("abort previous key loader for type:" + type);
loader.abort();
}
if (!uri) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].warn('key uri is falsy');
return;
}
var Loader = config.loader;
var fragLoader = frag.loader = this.loaders[type] = new Loader(config);
this.decrypturl = uri;
this.decryptkey = null;
var loaderContext = {
url: uri,
frag: frag,
responseType: 'arraybuffer'
}; // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
// key-loader will trigger an error and rely on stream-controller to handle retry logic.
// this will also align retry logic with fragment-loader
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: config.fragLoadingRetryDelay,
maxRetryDelay: config.fragLoadingMaxRetryTimeout,
highWaterMark: 0
};
var loaderCallbacks = {
onSuccess: this.loadsuccess.bind(this),
onError: this.loaderror.bind(this),
onTimeout: this.loadtimeout.bind(this)
};
fragLoader.load(loaderContext, loaderConfig, loaderCallbacks);
} else if (this.decryptkey) {
// Return the key if it's already been loaded
frag.decryptdata.key = this.decryptkey;
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, {
frag: frag
});
}
};
_proto.loadsuccess = function loadsuccess(response, stats, context) {
var frag = context.frag;
if (!frag.decryptdata) {
_utils_logger__WEBPACK_IMPORTED_MODULE_2__["logger"].error('after key load, decryptdata unset');
return;
}
this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); // detach fragment loader on load success
frag.loader = null;
delete this.loaders[frag.type];
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].KEY_LOADED, {
frag: frag
});
};
_proto.loaderror = function loaderror(response, context) {
var frag = context.frag;
var loader = frag.loader;
if (loader) {
loader.abort();
}
delete this.loaders[frag.type];
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_ERROR,
fatal: false,
frag: frag,
response: response
});
};
_proto.loadtimeout = function loadtimeout(stats, context) {
var frag = context.frag;
var loader = frag.loader;
if (loader) {
loader.abort();
}
delete this.loaders[frag.type];
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_0__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_1__["ErrorDetails"].KEY_LOAD_TIMEOUT,
fatal: false,
frag: frag
});
};
return KeyLoader;
}();
/***/ }),
/***/ "./src/loader/level-details.ts":
/*!*************************************!*\
!*** ./src/loader/level-details.ts ***!
\*************************************/
/*! exports provided: LevelDetails */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelDetails", function() { return LevelDetails; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var DEFAULT_TARGET_DURATION = 10;
var LevelDetails = /*#__PURE__*/function () {
// Manifest reload synchronization
function LevelDetails(baseUrl) {
this.PTSKnown = false;
this.alignedSliding = false;
this.averagetargetduration = void 0;
this.endCC = 0;
this.endSN = 0;
this.fragments = void 0;
this.fragmentHint = void 0;
this.partList = null;
this.initSegment = null;
this.live = true;
this.ageHeader = 0;
this.advancedDateTime = void 0;
this.updated = true;
this.advanced = true;
this.availabilityDelay = void 0;
this.misses = 0;
this.needSidxRanges = false;
this.startCC = 0;
this.startSN = 0;
this.startTimeOffset = null;
this.targetduration = 0;
this.totalduration = 0;
this.type = null;
this.url = void 0;
this.m3u8 = '';
this.version = null;
this.canBlockReload = false;
this.canSkipUntil = 0;
this.canSkipDateRanges = false;
this.skippedSegments = 0;
this.recentlyRemovedDateranges = void 0;
this.partHoldBack = 0;
this.holdBack = 0;
this.partTarget = 0;
this.preloadHint = void 0;
this.renditionReports = void 0;
this.tuneInGoal = 0;
this.deltaUpdateFailed = void 0;
this.driftStartTime = 0;
this.driftEndTime = 0;
this.driftStart = 0;
this.driftEnd = 0;
this.fragments = [];
this.url = baseUrl;
}
var _proto = LevelDetails.prototype;
_proto.reloaded = function reloaded(previous) {
if (!previous) {
this.advanced = true;
this.updated = true;
return;
}
var partSnDiff = this.lastPartSn - previous.lastPartSn;
var partIndexDiff = this.lastPartIndex - previous.lastPartIndex;
this.updated = this.endSN !== previous.endSN || !!partIndexDiff || !!partSnDiff;
this.advanced = this.endSN > previous.endSN || partSnDiff > 0 || partSnDiff === 0 && partIndexDiff > 0;
if (this.updated || this.advanced) {
this.misses = Math.floor(previous.misses * 0.6);
} else {
this.misses = previous.misses + 1;
}
this.availabilityDelay = previous.availabilityDelay;
};
_createClass(LevelDetails, [{
key: "hasProgramDateTime",
get: function get() {
if (this.fragments.length) {
return Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this.fragments[this.fragments.length - 1].programDateTime);
}
return false;
}
}, {
key: "levelTargetDuration",
get: function get() {
return this.averagetargetduration || this.targetduration || DEFAULT_TARGET_DURATION;
}
}, {
key: "drift",
get: function get() {
var runTime = this.driftEndTime - this.driftStartTime;
if (runTime > 0) {
var runDuration = this.driftEnd - this.driftStart;
return runDuration * 1000 / runTime;
}
return 1;
}
}, {
key: "edge",
get: function get() {
return this.partEnd || this.fragmentEnd;
}
}, {
key: "partEnd",
get: function get() {
var _this$partList;
if ((_this$partList = this.partList) !== null && _this$partList !== void 0 && _this$partList.length) {
return this.partList[this.partList.length - 1].end;
}
return this.fragmentEnd;
}
}, {
key: "fragmentEnd",
get: function get() {
var _this$fragments;
if ((_this$fragments = this.fragments) !== null && _this$fragments !== void 0 && _this$fragments.length) {
return this.fragments[this.fragments.length - 1].end;
}
return 0;
}
}, {
key: "age",
get: function get() {
if (this.advancedDateTime) {
return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;
}
return 0;
}
}, {
key: "lastPartIndex",
get: function get() {
var _this$partList2;
if ((_this$partList2 = this.partList) !== null && _this$partList2 !== void 0 && _this$partList2.length) {
return this.partList[this.partList.length - 1].index;
}
return -1;
}
}, {
key: "lastPartSn",
get: function get() {
var _this$partList3;
if ((_this$partList3 = this.partList) !== null && _this$partList3 !== void 0 && _this$partList3.length) {
return this.partList[this.partList.length - 1].fragment.sn;
}
return this.endSN;
}
}]);
return LevelDetails;
}();
/***/ }),
/***/ "./src/loader/level-key.ts":
/*!*********************************!*\
!*** ./src/loader/level-key.ts ***!
\*********************************/
/*! exports provided: LevelKey */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LevelKey", function() { return LevelKey; });
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_0__);
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var LevelKey = /*#__PURE__*/function () {
LevelKey.fromURL = function fromURL(baseUrl, relativeUrl) {
return new LevelKey(baseUrl, relativeUrl);
};
LevelKey.fromURI = function fromURI(uri) {
return new LevelKey(uri);
};
function LevelKey(absoluteOrBaseURI, relativeURL) {
this._uri = null;
this.method = null;
this.keyFormat = null;
this.keyFormatVersions = null;
this.keyID = null;
this.key = null;
this.iv = null;
if (relativeURL) {
this._uri = Object(url_toolkit__WEBPACK_IMPORTED_MODULE_0__["buildAbsoluteURL"])(absoluteOrBaseURI, relativeURL, {
alwaysNormalize: true
});
} else {
this._uri = absoluteOrBaseURI;
}
}
_createClass(LevelKey, [{
key: "uri",
get: function get() {
return this._uri;
}
}]);
return LevelKey;
}();
/***/ }),
/***/ "./src/loader/load-stats.ts":
/*!**********************************!*\
!*** ./src/loader/load-stats.ts ***!
\**********************************/
/*! exports provided: LoadStats */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LoadStats", function() { return LoadStats; });
var LoadStats = function LoadStats() {
this.aborted = false;
this.loaded = 0;
this.retry = 0;
this.total = 0;
this.chunkCount = 0;
this.bwEstimate = 0;
this.loading = {
start: 0,
first: 0,
end: 0
};
this.parsing = {
start: 0,
end: 0
};
this.buffering = {
start: 0,
first: 0,
end: 0
};
};
/***/ }),
/***/ "./src/loader/m3u8-parser.ts":
/*!***********************************!*\
!*** ./src/loader/m3u8-parser.ts ***!
\***********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return M3U8Parser; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
/* harmony import */ var url_toolkit__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(url_toolkit__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _level_details__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./level-details */ "./src/loader/level-details.ts");
/* harmony import */ var _level_key__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.ts");
/* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_codecs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.ts");
// https://regex101.com is your friend
var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g;
var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
/(?!#) *(\S[\S ]*)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
/#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
/#.*/.source // All other non-segment oriented tags will match with all groups empty
].join('|'), 'g');
var LEVEL_PLAYLIST_REGEX_SLOW = new RegExp([/#(EXTM3U)/.source, /#EXT-X-(PLAYLIST-TYPE):(.+)/.source, /#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source, /#EXT-X-(SKIP):(.+)/.source, /#EXT-X-(TARGETDURATION): *(\d+)/.source, /#EXT-X-(KEY):(.+)/.source, /#EXT-X-(START):(.+)/.source, /#EXT-X-(ENDLIST)/.source, /#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source, /#EXT-X-(DIS)CONTINUITY/.source, /#EXT-X-(VERSION):(\d+)/.source, /#EXT-X-(MAP):(.+)/.source, /#EXT-X-(SERVER-CONTROL):(.+)/.source, /#EXT-X-(PART-INF):(.+)/.source, /#EXT-X-(GAP)/.source, /#EXT-X-(BITRATE):\s*(\d+)/.source, /#EXT-X-(PART):(.+)/.source, /#EXT-X-(PRELOAD-HINT):(.+)/.source, /#EXT-X-(RENDITION-REPORT):(.+)/.source, /(#)([^:]*):(.*)/.source, /(#)(.*)(?:.*)\r?\n?/.source].join('|'));
var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
function isMP4Url(url) {
var _URLToolkit$parseURL$, _URLToolkit$parseURL;
return MP4_REGEX_SUFFIX.test((_URLToolkit$parseURL$ = (_URLToolkit$parseURL = url_toolkit__WEBPACK_IMPORTED_MODULE_1__["parseURL"](url)) === null || _URLToolkit$parseURL === void 0 ? void 0 : _URLToolkit$parseURL.path) != null ? _URLToolkit$parseURL$ : '');
}
var M3U8Parser = /*#__PURE__*/function () {
function M3U8Parser() {}
M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
if (group.id === mediaGroupId) {
return group;
}
}
};
M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {
// Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported
var avcdata = codec.split('.');
if (avcdata.length > 2) {
var result = avcdata.shift() + '.';
result += parseInt(avcdata.shift()).toString(16);
result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
return result;
}
return codec;
};
M3U8Parser.resolve = function resolve(url, baseUrl) {
return url_toolkit__WEBPACK_IMPORTED_MODULE_1__["buildAbsoluteURL"](baseUrl, url, {
alwaysNormalize: true
});
};
M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
var levels = [];
var sessionData = {};
var hasSessionData = false;
MASTER_PLAYLIST_REGEX.lastIndex = 0;
var result;
while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
if (result[1]) {
// '#EXT-X-STREAM-INF' is found, parse level tag in group 1
var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]);
var level = {
attrs: attrs,
bitrate: attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH'),
name: attrs.NAME,
url: M3U8Parser.resolve(result[2], baseurl)
};
var resolution = attrs.decimalResolution('RESOLUTION');
if (resolution) {
level.width = resolution.width;
level.height = resolution.height;
}
setCodecs((attrs.CODECS || '').split(/[ ,]+/).filter(function (c) {
return c;
}), level);
if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
}
levels.push(level);
} else if (result[3]) {
// '#EXT-X-SESSION-DATA' is found, parse session data in group 3
var sessionAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[3]);
if (sessionAttrs['DATA-ID']) {
hasSessionData = true;
sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;
}
}
}
return {
levels: levels,
sessionData: hasSessionData ? sessionData : null
};
};
M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type, groups) {
if (groups === void 0) {
groups = [];
}
var result;
var medias = [];
var id = 0;
MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
var attrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](result[1]);
if (attrs.TYPE === type) {
var media = {
attrs: attrs,
bitrate: 0,
id: id++,
groupId: attrs['GROUP-ID'],
instreamId: attrs['INSTREAM-ID'],
name: attrs.NAME || attrs.LANGUAGE || '',
type: type,
default: attrs.bool('DEFAULT'),
autoselect: attrs.bool('AUTOSELECT'),
forced: attrs.bool('FORCED'),
lang: attrs.LANGUAGE,
url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : ''
};
if (groups.length) {
// If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track
// If we don't find the track signalled, lets use the first audio groups codec we have
// Acting as a best guess
var groupCodec = M3U8Parser.findGroup(groups, media.groupId) || groups[0];
assignCodec(media, groupCodec, 'audioCodec');
assignCodec(media, groupCodec, 'textCodec');
}
medias.push(media);
}
}
return medias;
};
M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
var level = new _level_details__WEBPACK_IMPORTED_MODULE_3__["LevelDetails"](baseurl);
var fragments = level.fragments;
var currentSN = 0;
var currentPart = 0;
var totalduration = 0;
var discontinuityCounter = 0;
var prevFrag = null;
var frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl);
var result;
var i;
var levelkey;
var firstPdtIndex = -1;
LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
level.m3u8 = string;
while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
var duration = result[1];
if (duration) {
// INF
frag.duration = parseFloat(duration); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var title = (' ' + result[2]).slice(1);
frag.title = title || null;
frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
} else if (result[3]) {
// url
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.duration)) {
frag.start = totalduration;
if (levelkey) {
frag.levelkey = levelkey;
}
frag.sn = currentSN;
frag.level = id;
frag.cc = discontinuityCounter;
frag.urlId = levelUrlId;
fragments.push(frag); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.relurl = (' ' + result[3]).slice(1);
assignProgramDateTime(frag, prevFrag);
prevFrag = frag;
totalduration += frag.duration;
currentSN++;
currentPart = 0;
frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl); // setup the next fragment for part loading
frag.start = totalduration;
frag.sn = currentSN;
frag.cc = discontinuityCounter;
frag.level = id;
}
} else if (result[4]) {
// X-BYTERANGE
var data = (' ' + result[4]).slice(1);
if (prevFrag) {
frag.setByteRange(data, prevFrag);
} else {
frag.setByteRange(data);
}
} else if (result[5]) {
// PROGRAM-DATE-TIME
// avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.rawProgramDateTime = (' ' + result[5]).slice(1);
frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
if (firstPdtIndex === -1) {
firstPdtIndex = fragments.length;
}
} else {
result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
if (!result) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('No matches on slow regex match for level playlist!');
continue;
}
for (i = 1; i < result.length; i++) {
if (typeof result[i] !== 'undefined') {
break;
}
} // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var tag = (' ' + result[i]).slice(1);
var value1 = (' ' + result[i + 1]).slice(1);
var value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';
switch (tag) {
case 'PLAYLIST-TYPE':
level.type = value1.toUpperCase();
break;
case 'MEDIA-SEQUENCE':
currentSN = level.startSN = parseInt(value1);
break;
case 'SKIP':
{
var skipAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
var skippedSegments = skipAttrs.decimalInteger('SKIPPED-SEGMENTS');
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(skippedSegments)) {
level.skippedSegments = skippedSegments; // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`
for (var _i = skippedSegments; _i--;) {
fragments.unshift(null);
}
currentSN += skippedSegments;
}
var recentlyRemovedDateranges = skipAttrs.enumeratedString('RECENTLY-REMOVED-DATERANGES');
if (recentlyRemovedDateranges) {
level.recentlyRemovedDateranges = recentlyRemovedDateranges.split('\t');
}
break;
}
case 'TARGETDURATION':
level.targetduration = parseFloat(value1);
break;
case 'VERSION':
level.version = parseInt(value1);
break;
case 'EXTM3U':
break;
case 'ENDLIST':
level.live = false;
break;
case '#':
if (value1 || value2) {
frag.tagList.push(value2 ? [value1, value2] : [value1]);
}
break;
case 'DIS':
discontinuityCounter++;
/* falls through */
case 'GAP':
frag.tagList.push([tag]);
break;
case 'BITRATE':
frag.tagList.push([tag, value1]);
break;
case 'DISCONTINUITY-SEQ':
discontinuityCounter = parseInt(value1);
break;
case 'KEY':
{
var _keyAttrs$enumeratedS;
// https://tools.ietf.org/html/rfc8216#section-4.3.2.4
var keyAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
var decryptmethod = keyAttrs.enumeratedString('METHOD');
var decrypturi = keyAttrs.URI;
var decryptiv = keyAttrs.hexadecimalInteger('IV');
var decryptkeyformatversions = keyAttrs.enumeratedString('KEYFORMATVERSIONS');
var decryptkeyid = keyAttrs.enumeratedString('KEYID'); // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
var decryptkeyformat = (_keyAttrs$enumeratedS = keyAttrs.enumeratedString('KEYFORMAT')) != null ? _keyAttrs$enumeratedS : 'identity';
var unsupportedKnownKeyformatsInManifest = ['com.apple.streamingkeydelivery', 'com.microsoft.playready', 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed', // widevine (v2)
'com.widevine' // earlier widevine (v1)
];
if (unsupportedKnownKeyformatsInManifest.indexOf(decryptkeyformat) > -1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("Keyformat " + decryptkeyformat + " is not supported from the manifest");
continue;
} else if (decryptkeyformat !== 'identity') {
// We are supposed to skip keys we don't understand.
// As we currently only officially support identity keys
// from the manifest we shouldn't save any other key.
continue;
} // TODO: multiple keys can be defined on a fragment, and we need to support this
// for clients that support both playready and widevine
if (decryptmethod) {
// TODO: need to determine if the level key is actually a relative URL
// if it isn't, then we should instead construct the LevelKey using fromURI.
levelkey = _level_key__WEBPACK_IMPORTED_MODULE_4__["LevelKey"].fromURL(baseurl, decrypturi);
if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
levelkey.method = decryptmethod;
levelkey.keyFormat = decryptkeyformat;
if (decryptkeyid) {
levelkey.keyID = decryptkeyid;
}
if (decryptkeyformatversions) {
levelkey.keyFormatVersions = decryptkeyformatversions;
} // Initialization Vector (IV)
levelkey.iv = decryptiv;
}
}
break;
}
case 'START':
{
var startAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); // TIME-OFFSET can be 0
if (Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(startTimeOffset)) {
level.startTimeOffset = startTimeOffset;
}
break;
}
case 'MAP':
{
var mapAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
frag.relurl = mapAttrs.URI;
if (mapAttrs.BYTERANGE) {
frag.setByteRange(mapAttrs.BYTERANGE);
}
frag.level = id;
frag.sn = 'initSegment';
if (levelkey) {
frag.levelkey = levelkey;
}
level.initSegment = frag;
frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl);
frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;
break;
}
case 'SERVER-CONTROL':
{
var serverControlAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');
level.canSkipUntil = serverControlAttrs.optionalFloat('CAN-SKIP-UNTIL', 0);
level.canSkipDateRanges = level.canSkipUntil > 0 && serverControlAttrs.bool('CAN-SKIP-DATERANGES');
level.partHoldBack = serverControlAttrs.optionalFloat('PART-HOLD-BACK', 0);
level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);
break;
}
case 'PART-INF':
{
var partInfAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');
break;
}
case 'PART':
{
var partList = level.partList;
if (!partList) {
partList = level.partList = [];
}
var previousFragmentPart = currentPart > 0 ? partList[partList.length - 1] : undefined;
var index = currentPart++;
var part = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Part"](new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1), frag, baseurl, index, previousFragmentPart);
partList.push(part);
frag.duration += part.duration;
break;
}
case 'PRELOAD-HINT':
{
var preloadHintAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.preloadHint = preloadHintAttrs;
break;
}
case 'RENDITION-REPORT':
{
var renditionReportAttrs = new _utils_attr_list__WEBPACK_IMPORTED_MODULE_5__["AttrList"](value1);
level.renditionReports = level.renditionReports || [];
level.renditionReports.push(renditionReportAttrs);
break;
}
default:
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn("line parsed but not handled: " + result);
break;
}
}
}
if (prevFrag && !prevFrag.relurl) {
fragments.pop();
totalduration -= prevFrag.duration;
if (level.partList) {
level.fragmentHint = prevFrag;
}
} else if (level.partList) {
assignProgramDateTime(frag, prevFrag);
frag.cc = discontinuityCounter;
level.fragmentHint = frag;
}
var fragmentLength = fragments.length;
var firstFragment = fragments[0];
var lastFragment = fragments[fragmentLength - 1];
totalduration += level.skippedSegments * level.targetduration;
if (totalduration > 0 && fragmentLength && lastFragment) {
level.averagetargetduration = totalduration / fragmentLength;
var lastSn = lastFragment.sn;
level.endSN = lastSn !== 'initSegment' ? lastSn : 0;
if (firstFragment) {
level.startCC = firstFragment.cc;
if (!level.initSegment) {
// this is a bit lurky but HLS really has no other way to tell us
// if the fragments are TS or MP4, except if we download them :/
// but this is to be able to handle SIDX.
if (level.fragments.every(function (frag) {
return frag.relurl && isMP4Url(frag.relurl);
})) {
_utils_logger__WEBPACK_IMPORTED_MODULE_6__["logger"].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
frag = new _fragment__WEBPACK_IMPORTED_MODULE_2__["Fragment"](type, baseurl);
frag.relurl = lastFragment.relurl;
frag.level = id;
frag.sn = 'initSegment';
level.initSegment = frag;
level.needSidxRanges = true;
}
}
}
} else {
level.endSN = 0;
level.startCC = 0;
}
if (level.fragmentHint) {
totalduration += level.fragmentHint.duration;
}
level.totalduration = totalduration;
level.endCC = discontinuityCounter;
/**
* Backfill any missing PDT values
* "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
* one or more Media Segment URIs, the client SHOULD extrapolate
* backward from that tag (using EXTINF durations and/or media
* timestamps) to associate dates with those segments."
* We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
* computed.
*/
if (firstPdtIndex > 0) {
backfillProgramDateTimes(fragments, firstPdtIndex);
}
return level;
};
return M3U8Parser;
}();
function setCodecs(codecs, level) {
['video', 'audio', 'text'].forEach(function (type) {
var filtered = codecs.filter(function (codec) {
return Object(_utils_codecs__WEBPACK_IMPORTED_MODULE_7__["isCodecType"])(codec, type);
});
if (filtered.length) {
var preferred = filtered.filter(function (codec) {
return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
});
level[type + "Codec"] = preferred.length > 0 ? preferred[0] : filtered[0]; // remove from list
codecs = codecs.filter(function (codec) {
return filtered.indexOf(codec) === -1;
});
}
});
level.unknownCodecs = codecs;
}
function assignCodec(media, groupItem, codecProperty) {
var codecValue = groupItem[codecProperty];
if (codecValue) {
media[codecProperty] = codecValue;
}
}
function backfillProgramDateTimes(fragments, firstPdtIndex) {
var fragPrev = fragments[firstPdtIndex];
for (var i = firstPdtIndex; i--;) {
var frag = fragments[i]; // Exit on delta-playlist skipped segments
if (!frag) {
return;
}
frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
fragPrev = frag;
}
}
function assignProgramDateTime(frag, prevFrag) {
if (frag.rawProgramDateTime) {
frag.programDateTime = Date.parse(frag.rawProgramDateTime);
} else if (prevFrag !== null && prevFrag !== void 0 && prevFrag.programDateTime) {
frag.programDateTime = prevFrag.endProgramDateTime;
}
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(frag.programDateTime)) {
frag.programDateTime = null;
frag.rawProgramDateTime = null;
}
}
/***/ }),
/***/ "./src/loader/playlist-loader.ts":
/*!***************************************!*\
!*** ./src/loader/playlist-loader.ts ***!
\***************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./m3u8-parser */ "./src/loader/m3u8-parser.ts");
/* harmony import */ var _types_loader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types/loader */ "./src/types/loader.ts");
/* harmony import */ var _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.ts");
/**
* PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
*
* Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
*
* Uses loader(s) set in config to do actual internal loading of resource tasks.
*
* @module
*
*/
function mapContextToLevelType(context) {
var type = context.type;
switch (type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].AUDIO;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].SUBTITLE;
default:
return _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistLevelType"].MAIN;
}
}
function getResponseUrl(response, context) {
var url = response.url; // responseURL not supported on some browsers (it is used to detect URL redirection)
// data-uri mode also not supported (but no need to detect redirection)
if (url === undefined || url.indexOf('data:') === 0) {
// fallback to initial URL
url = context.url;
}
return url;
}
var PlaylistLoader = /*#__PURE__*/function () {
function PlaylistLoader(hls) {
this.hls = void 0;
this.loaders = Object.create(null);
this.hls = hls;
this.registerListeners();
}
var _proto = PlaylistLoader.prototype;
_proto.registerListeners = function registerListeners() {
var hls = this.hls;
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
hls.on(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
};
_proto.unregisterListeners = function unregisterListeners() {
var hls = this.hls;
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADING, this.onManifestLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADING, this.onLevelLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);
hls.off(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);
}
/**
* Returns defaults or configured loader-type overloads (pLoader and loader config params)
*/
;
_proto.createInternalLoader = function createInternalLoader(context) {
var config = this.hls.config;
var PLoader = config.pLoader;
var Loader = config.loader;
var InternalLoader = PLoader || Loader;
var loader = new InternalLoader(config);
context.loader = loader;
this.loaders[context.type] = loader;
return loader;
};
_proto.getInternalLoader = function getInternalLoader(context) {
return this.loaders[context.type];
};
_proto.resetInternalLoader = function resetInternalLoader(contextType) {
if (this.loaders[contextType]) {
delete this.loaders[contextType];
}
}
/**
* Call `destroy` on all internal loader instances mapped (one per context type)
*/
;
_proto.destroyInternalLoaders = function destroyInternalLoaders() {
for (var contextType in this.loaders) {
var loader = this.loaders[contextType];
if (loader) {
loader.destroy();
}
this.resetInternalLoader(contextType);
}
};
_proto.destroy = function destroy() {
this.unregisterListeners();
this.destroyInternalLoaders();
};
_proto.onManifestLoading = function onManifestLoading(event, data) {
var url = data.url;
this.load({
id: null,
groupId: null,
level: 0,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST,
url: url,
deliveryDirectives: null
});
};
_proto.onLevelLoading = function onLevelLoading(event, data) {
var id = data.id,
level = data.level,
url = data.url,
deliveryDirectives = data.deliveryDirectives;
this.load({
id: id,
groupId: null,
level: level,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL,
url: url,
deliveryDirectives: deliveryDirectives
});
};
_proto.onAudioTrackLoading = function onAudioTrackLoading(event, data) {
var id = data.id,
groupId = data.groupId,
url = data.url,
deliveryDirectives = data.deliveryDirectives;
this.load({
id: id,
groupId: groupId,
level: null,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK,
url: url,
deliveryDirectives: deliveryDirectives
});
};
_proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(event, data) {
var id = data.id,
groupId = data.groupId,
url = data.url,
deliveryDirectives = data.deliveryDirectives;
this.load({
id: id,
groupId: groupId,
level: null,
responseType: 'text',
type: _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK,
url: url,
deliveryDirectives: deliveryDirectives
});
};
_proto.load = function load(context) {
var _context$deliveryDire;
var config = this.hls.config; // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);
// Check if a loader for this context already exists
var loader = this.getInternalLoader(context);
if (loader) {
var loaderContext = loader.context;
if (loaderContext && loaderContext.url === context.url) {
// same URL can't overlap
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].trace('[playlist-loader]: playlist request ongoing');
return;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log("[playlist-loader]: aborting previous loader for type: " + context.type);
loader.abort();
}
var maxRetry;
var timeout;
var retryDelay;
var maxRetryDelay; // apply different configs for retries depending on
// context (manifest, level, audio/subs playlist)
switch (context.type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
maxRetry = config.manifestLoadingMaxRetry;
timeout = config.manifestLoadingTimeOut;
retryDelay = config.manifestLoadingRetryDelay;
maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
// Manage retries in Level/Track Controller
maxRetry = 0;
timeout = config.levelLoadingTimeOut;
break;
default:
maxRetry = config.levelLoadingMaxRetry;
timeout = config.levelLoadingTimeOut;
retryDelay = config.levelLoadingRetryDelay;
maxRetryDelay = config.levelLoadingMaxRetryTimeout;
break;
}
loader = this.createInternalLoader(context); // Override level/track timeout for LL-HLS requests
// (the default of 10000ms is counter productive to blocking playlist reload requests)
if ((_context$deliveryDire = context.deliveryDirectives) !== null && _context$deliveryDire !== void 0 && _context$deliveryDire.part) {
var levelDetails;
if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL && context.level !== null) {
levelDetails = this.hls.levels[context.level].details;
} else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK && context.id !== null) {
levelDetails = this.hls.audioTracks[context.id].details;
} else if (context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK && context.id !== null) {
levelDetails = this.hls.subtitleTracks[context.id].details;
}
if (levelDetails) {
var partTarget = levelDetails.partTarget;
var targetDuration = levelDetails.targetduration;
if (partTarget && targetDuration) {
timeout = Math.min(Math.max(partTarget * 3, targetDuration * 0.8) * 1000, timeout);
}
}
}
var loaderConfig = {
timeout: timeout,
maxRetry: maxRetry,
retryDelay: retryDelay,
maxRetryDelay: maxRetryDelay,
highWaterMark: 0
};
var loaderCallbacks = {
onSuccess: this.loadsuccess.bind(this),
onError: this.loaderror.bind(this),
onTimeout: this.loadtimeout.bind(this)
}; // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);
loader.load(context, loaderConfig, loaderCallbacks);
};
_proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
if (context.isSidxRequest) {
this.handleSidxRequest(response, context);
this.handlePlaylistLoaded(response, stats, context, networkDetails);
return;
}
this.resetInternalLoader(context.type);
var string = response.data; // Validate if it is an M3U8 at all
if (string.indexOf('#EXTM3U') !== 0) {
this.handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
return;
}
stats.parsing.start = performance.now(); // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
this.handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
} else {
this.handleMasterPlaylist(response, stats, context, networkDetails);
}
};
_proto.loaderror = function loaderror(response, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
this.handleNetworkError(context, networkDetails, false, response);
};
_proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
this.handleNetworkError(context, networkDetails, true);
};
_proto.handleMasterPlaylist = function handleMasterPlaylist(response, stats, context, networkDetails) {
var hls = this.hls;
var string = response.data;
var url = getResponseUrl(response, context);
var _M3U8Parser$parseMast = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylist(string, url),
levels = _M3U8Parser$parseMast.levels,
sessionData = _M3U8Parser$parseMast.sessionData;
if (!levels.length) {
this.handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
return;
} // multi level playlist, parse level info
var audioGroups = levels.map(function (level) {
return {
id: level.attrs.AUDIO,
audioCodec: level.audioCodec
};
});
var subtitleGroups = levels.map(function (level) {
return {
id: level.attrs.SUBTITLES,
textCodec: level.textCodec
};
});
var audioTracks = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
var subtitles = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'SUBTITLES', subtitleGroups);
var captions = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS');
if (audioTracks.length) {
// check if we have found an audio track embedded in main playlist (audio track without URI attribute)
var embeddedAudioFound = audioTracks.some(function (audioTrack) {
return !audioTrack.url;
}); // if no embedded audio track defined, but audio codec signaled in quality level,
// we need to signal this main audio track this could happen with playlists with
// alt audio rendition in which quality levels (main)
// contains both audio+video. but with mixed audio track not signaled
if (!embeddedAudioFound && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].log('[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one');
audioTracks.unshift({
type: 'main',
name: 'main',
default: false,
autoselect: false,
forced: false,
id: -1,
attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}),
bitrate: 0,
url: ''
});
}
}
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, {
levels: levels,
audioTracks: audioTracks,
subtitles: subtitles,
captions: captions,
url: url,
stats: stats,
networkDetails: networkDetails,
sessionData: sessionData
});
};
_proto.handleTrackOrLevelPlaylist = function handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
var hls = this.hls;
var id = context.id,
level = context.level,
type = context.type;
var url = getResponseUrl(response, context);
var levelUrlId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(id) ? id : 0;
var levelId = Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(level) ? level : levelUrlId;
var levelType = mapContextToLevelType(context);
var levelDetails = _m3u8_parser__WEBPACK_IMPORTED_MODULE_5__["default"].parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);
if (!levelDetails.fragments.length) {
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_EMPTY_ERROR,
fatal: false,
url: url,
reason: 'no fragments found in level',
level: typeof context.level === 'number' ? context.level : undefined
});
return;
} // We have done our first request (Manifest-type) and receive
// not a master playlist but a chunk-list (track/level)
// We fire the manifest-loaded event anyway with the parsed level-details
// by creating a single-level structure for it.
if (type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST) {
var singleLevel = {
attrs: new _utils_attr_list__WEBPACK_IMPORTED_MODULE_7__["AttrList"]({}),
bitrate: 0,
details: levelDetails,
name: '',
url: url
};
hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].MANIFEST_LOADED, {
levels: [singleLevel],
audioTracks: [],
url: url,
stats: stats,
networkDetails: networkDetails,
sessionData: null
});
} // save parsing time
stats.parsing.end = performance.now(); // in case we need SIDX ranges
// return early after calling load for
// the SIDX box.
if (levelDetails.needSidxRanges) {
var sidxUrl = levelDetails.initSegment.url;
this.load({
url: sidxUrl,
isSidxRequest: true,
type: type,
level: level,
levelDetails: levelDetails,
id: id,
groupId: null,
rangeStart: 0,
rangeEnd: 2048,
responseType: 'arraybuffer',
deliveryDirectives: null
});
return;
} // extend the context with the new levelDetails property
context.levelDetails = levelDetails;
this.handlePlaylistLoaded(response, stats, context, networkDetails);
};
_proto.handleSidxRequest = function handleSidxRequest(response, context) {
var sidxInfo = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_4__["parseSegmentIndex"])(new Uint8Array(response.data)); // if provided fragment does not contain sidx, early return
if (!sidxInfo) {
return;
}
var sidxReferences = sidxInfo.references;
var levelDetails = context.levelDetails;
sidxReferences.forEach(function (segmentRef, index) {
var segRefInfo = segmentRef.info;
var frag = levelDetails.fragments[index];
if (frag.byteRange.length === 0) {
frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start));
}
});
levelDetails.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0');
};
_proto.handleManifestParsingError = function handleManifestParsingError(response, context, reason, networkDetails) {
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_PARSING_ERROR,
fatal: context.type === _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST,
url: response.url,
reason: reason,
response: response,
context: context,
networkDetails: networkDetails
});
};
_proto.handleNetworkError = function handleNetworkError(context, networkDetails, timeout, response) {
if (timeout === void 0) {
timeout = false;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn("[playlist-loader]: A network " + (timeout ? 'timeout' : 'error') + " occurred while loading " + context.type + " level: " + context.level + " id: " + context.id + " group-id: \"" + context.groupId + "\"");
var details = _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].UNKNOWN;
var fatal = false;
var loader = this.getInternalLoader(context);
switch (context.type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].MANIFEST_LOAD_ERROR;
fatal = true;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].LEVEL_LOAD_ERROR;
fatal = false;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR;
fatal = false;
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
details = timeout ? _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_TRACK_LOAD_TIMEOUT : _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorDetails"].SUBTITLE_LOAD_ERROR;
fatal = false;
break;
}
if (loader) {
this.resetInternalLoader(context.type);
}
var errorData = {
type: _errors__WEBPACK_IMPORTED_MODULE_2__["ErrorTypes"].NETWORK_ERROR,
details: details,
fatal: fatal,
url: context.url,
loader: loader,
context: context,
networkDetails: networkDetails
};
if (response) {
errorData.response = response;
}
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].ERROR, errorData);
};
_proto.handlePlaylistLoaded = function handlePlaylistLoaded(response, stats, context, networkDetails) {
var type = context.type,
level = context.level,
id = context.id,
groupId = context.groupId,
loader = context.loader,
levelDetails = context.levelDetails,
deliveryDirectives = context.deliveryDirectives;
if (!(levelDetails !== null && levelDetails !== void 0 && levelDetails.targetduration)) {
this.handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
return;
}
if (!loader) {
return;
}
if (levelDetails.live) {
if (loader.getCacheAge) {
levelDetails.ageHeader = loader.getCacheAge() || 0;
}
if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {
levelDetails.ageHeader = 0;
}
}
switch (type) {
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].MANIFEST:
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].LEVEL:
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].LEVEL_LOADED, {
details: levelDetails,
level: level || 0,
id: id || 0,
stats: stats,
networkDetails: networkDetails,
deliveryDirectives: deliveryDirectives
});
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].AUDIO_TRACK:
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].AUDIO_TRACK_LOADED, {
details: levelDetails,
id: id || 0,
groupId: groupId || '',
stats: stats,
networkDetails: networkDetails,
deliveryDirectives: deliveryDirectives
});
break;
case _types_loader__WEBPACK_IMPORTED_MODULE_6__["PlaylistContextType"].SUBTITLE_TRACK:
this.hls.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["Events"].SUBTITLE_TRACK_LOADED, {
details: levelDetails,
id: id || 0,
groupId: groupId || '',
stats: stats,
networkDetails: networkDetails,
deliveryDirectives: deliveryDirectives
});
break;
}
};
return PlaylistLoader;
}();
/* harmony default export */ __webpack_exports__["default"] = (PlaylistLoader);
/***/ }),
/***/ "./src/polyfills/number.ts":
/*!*********************************!*\
!*** ./src/polyfills/number.ts ***!
\*********************************/
/*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFiniteNumber", function() { return isFiniteNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_SAFE_INTEGER", function() { return MAX_SAFE_INTEGER; });
var isFiniteNumber = Number.isFinite || function (value) {
return typeof value === 'number' && isFinite(value);
};
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
/***/ }),
/***/ "./src/remux/aac-helper.ts":
/*!*********************************!*\
!*** ./src/remux/aac-helper.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* AAC helper
*/
var AAC = /*#__PURE__*/function () {
function AAC() {}
AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
switch (codec) {
case 'mp4a.40.2':
if (channelCount === 1) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
} else if (channelCount === 2) {
return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
} else if (channelCount === 3) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
} else if (channelCount === 4) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
} else if (channelCount === 5) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
} else if (channelCount === 6) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);
}
break;
// handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
default:
if (channelCount === 1) {
// ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
} else if (channelCount === 2) {
// ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
} else if (channelCount === 3) {
// ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
}
break;
}
return undefined;
};
return AAC;
}();
/* harmony default export */ __webpack_exports__["default"] = (AAC);
/***/ }),
/***/ "./src/remux/mp4-generator.ts":
/*!************************************!*\
!*** ./src/remux/mp4-generator.ts ***!
\************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* Generate MP4 Box
*/
var UINT32_MAX = Math.pow(2, 32) - 1;
var MP4 = /*#__PURE__*/function () {
function MP4() {}
MP4.init = function init() {
MP4.types = {
avc1: [],
// codingname
avcC: [],
btrt: [],
dinf: [],
dref: [],
esds: [],
ftyp: [],
hdlr: [],
mdat: [],
mdhd: [],
mdia: [],
mfhd: [],
minf: [],
moof: [],
moov: [],
mp4a: [],
'.mp3': [],
mvex: [],
mvhd: [],
pasp: [],
sdtp: [],
stbl: [],
stco: [],
stsc: [],
stsd: [],
stsz: [],
stts: [],
tfdt: [],
tfhd: [],
traf: [],
trak: [],
trun: [],
trex: [],
tkhd: [],
vmhd: [],
smhd: []
};
var i;
for (i in MP4.types) {
if (MP4.types.hasOwnProperty(i)) {
MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
}
}
var videoHdlr = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
]);
var audioHdlr = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
]);
MP4.HDLR_TYPES = {
video: videoHdlr,
audio: audioHdlr
};
var dref = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01, // entry_count
0x00, 0x00, 0x00, 0x0c, // entry_size
0x75, 0x72, 0x6c, 0x20, // 'url' type
0x00, // version 0
0x00, 0x00, 0x01 // entry_flags
]);
var stco = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00 // entry_count
]);
MP4.STTS = MP4.STSC = MP4.STCO = stco;
MP4.STSZ = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // sample_size
0x00, 0x00, 0x00, 0x00 // sample_count
]);
MP4.VMHD = new Uint8Array([0x00, // version
0x00, 0x00, 0x01, // flags
0x00, 0x00, // graphicsmode
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
]);
MP4.SMHD = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, // balance
0x00, 0x00 // reserved
]);
MP4.STSD = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01]); // entry_count
var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
var minorVersion = new Uint8Array([0, 0, 0, 1]);
MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
};
MP4.box = function box(type) {
var size = 8;
for (var _len = arguments.length, payload = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
payload[_key - 1] = arguments[_key];
}
var i = payload.length;
var len = i; // calculate the total size we need to allocate
while (i--) {
size += payload[i].byteLength;
}
var result = new Uint8Array(size);
result[0] = size >> 24 & 0xff;
result[1] = size >> 16 & 0xff;
result[2] = size >> 8 & 0xff;
result[3] = size & 0xff;
result.set(type, 4); // copy the payload into the result
for (i = 0, size = 8; i < len; i++) {
// copy payload[i] array @ offset size
result.set(payload[i], size);
size += payload[i].byteLength;
}
return result;
};
MP4.hdlr = function hdlr(type) {
return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
};
MP4.mdat = function mdat(data) {
return MP4.box(MP4.types.mdat, data);
};
MP4.mdhd = function mdhd(timescale, duration) {
duration *= timescale;
var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff, // timescale
upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x55, 0xc4, // 'und' language (undetermined)
0x00, 0x00]));
};
MP4.mdia = function mdia(track) {
return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
};
MP4.mfhd = function mfhd(sequenceNumber) {
return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
sequenceNumber >> 24, sequenceNumber >> 16 & 0xff, sequenceNumber >> 8 & 0xff, sequenceNumber & 0xff // sequence_number
]));
};
MP4.minf = function minf(track) {
if (track.type === 'audio') {
return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
} else {
return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
}
};
MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
}
/**
* @param tracks... (optional) {array} the tracks associated with this movie
*/
;
MP4.moov = function moov(tracks) {
var i = tracks.length;
var boxes = [];
while (i--) {
boxes[i] = MP4.trak(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
};
MP4.mvex = function mvex(tracks) {
var i = tracks.length;
var boxes = [];
while (i--) {
boxes[i] = MP4.trex(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
};
MP4.mvhd = function mvhd(timescale, duration) {
duration *= timescale;
var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
var bytes = new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
timescale >> 24 & 0xff, timescale >> 16 & 0xff, timescale >> 8 & 0xff, timescale & 0xff, // timescale
upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x01, 0x00, 0x00, // 1.0 rate
0x01, 0x00, // 1.0 volume
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
0xff, 0xff, 0xff, 0xff // next_track_ID
]);
return MP4.box(MP4.types.mvhd, bytes);
};
MP4.sdtp = function sdtp(track) {
var samples = track.samples || [];
var bytes = new Uint8Array(4 + samples.length);
var i;
var flags; // leave the full box header (4 bytes) all zero
// write the sample table
for (i = 0; i < samples.length; i++) {
flags = samples[i].flags;
bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
}
return MP4.box(MP4.types.sdtp, bytes);
};
MP4.stbl = function stbl(track) {
return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
};
MP4.avc1 = function avc1(track) {
var sps = [];
var pps = [];
var i;
var data;
var len; // assemble the SPSs
for (i = 0; i < track.sps.length; i++) {
data = track.sps[i];
len = data.byteLength;
sps.push(len >>> 8 & 0xff);
sps.push(len & 0xff); // SPS
sps = sps.concat(Array.prototype.slice.call(data));
} // assemble the PPSs
for (i = 0; i < track.pps.length; i++) {
data = track.pps[i];
len = data.byteLength;
pps.push(len >>> 8 & 0xff);
pps.push(len & 0xff);
pps = pps.concat(Array.prototype.slice.call(data));
}
var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
sps[3], // profile
sps[4], // profile compat
sps[5], // level
0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
0xe0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
].concat(sps).concat([track.pps.length // numOfPictureParameterSets
]).concat(pps))); // "PPS"
var width = track.width;
var height = track.height;
var hSpacing = track.pixelRatio[0];
var vSpacing = track.pixelRatio[1];
return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, // pre_defined
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
width >> 8 & 0xff, width & 0xff, // width
height >> 8 & 0xff, height & 0xff, // height
0x00, 0x48, 0x00, 0x00, // horizresolution
0x00, 0x48, 0x00, 0x00, // vertresolution
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, // frame_count
0x12, 0x64, 0x61, 0x69, 0x6c, // dailymotion/hls.js
0x79, 0x6d, 0x6f, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x68, 0x6c, 0x73, 0x2e, 0x6a, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
0x00, 0x18, // depth = 24
0x11, 0x11]), // pre_defined = -1
avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
hSpacing >> 16 & 0xff, hSpacing >> 8 & 0xff, hSpacing & 0xff, vSpacing >> 24, // vSpacing
vSpacing >> 16 & 0xff, vSpacing >> 8 & 0xff, vSpacing & 0xff])));
};
MP4.esds = function esds(track) {
var configlen = track.config.length;
return new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x03, // descriptor_type
0x17 + configlen, // length
0x00, 0x01, // es_id
0x00, // stream_priority
0x04, // descriptor_type
0x0f + configlen, // length
0x40, // codec : mpeg4_audio
0x15, // stream_type
0x00, 0x00, 0x00, // buffer_size
0x00, 0x00, 0x00, 0x00, // maxBitrate
0x00, 0x00, 0x00, 0x00, // avgBitrate
0x05 // descriptor_type
].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
};
MP4.mp4a = function mp4a(track) {
var samplerate = track.samplerate;
return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, track.channelCount, // channelcount
0x00, 0x10, // sampleSize:16bits
0x00, 0x00, 0x00, 0x00, // reserved2
samplerate >> 8 & 0xff, samplerate & 0xff, //
0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
};
MP4.mp3 = function mp3(track) {
var samplerate = track.samplerate;
return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, track.channelCount, // channelcount
0x00, 0x10, // sampleSize:16bits
0x00, 0x00, 0x00, 0x00, // reserved2
samplerate >> 8 & 0xff, samplerate & 0xff, //
0x00, 0x00]));
};
MP4.stsd = function stsd(track) {
if (track.type === 'audio') {
if (!track.isAAC && track.codec === 'mp3') {
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
}
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
} else {
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
}
};
MP4.tkhd = function tkhd(track) {
var id = track.id;
var duration = track.duration * track.timescale;
var width = track.width;
var height = track.height;
var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x07, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
id >> 24 & 0xff, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff, // track_ID
0x00, 0x00, 0x00, 0x00, // reserved
upperWordDuration >> 24, upperWordDuration >> 16 & 0xff, upperWordDuration >> 8 & 0xff, upperWordDuration & 0xff, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xff, lowerWordDuration >> 8 & 0xff, lowerWordDuration & 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, // layer
0x00, 0x00, // alternate_group
0x00, 0x00, // non-audio track volume
0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
width >> 8 & 0xff, width & 0xff, 0x00, 0x00, // width
height >> 8 & 0xff, height & 0xff, 0x00, 0x00 // height
]));
};
MP4.traf = function traf(track, baseMediaDecodeTime) {
var sampleDependencyTable = MP4.sdtp(track);
var id = track.id;
var upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
var lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff // track_ID
])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0xff, upperWordBaseMediaDecodeTime >> 8 & 0xff, upperWordBaseMediaDecodeTime & 0xff, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0xff, lowerWordBaseMediaDecodeTime >> 8 & 0xff, lowerWordBaseMediaDecodeTime & 0xff])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
20 + // tfdt
8 + // traf header
16 + // mfhd
8 + // moof header
8), // mdat header
sampleDependencyTable);
}
/**
* Generate a track box.
* @param track {object} a track definition
* @return {Uint8Array} the track box
*/
;
MP4.trak = function trak(track) {
track.duration = track.duration || 0xffffffff;
return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
};
MP4.trex = function trex(track) {
var id = track.id;
return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
id >> 24, id >> 16 & 0xff, id >> 8 & 0xff, id & 0xff, // track_ID
0x00, 0x00, 0x00, 0x01, // default_sample_description_index
0x00, 0x00, 0x00, 0x00, // default_sample_duration
0x00, 0x00, 0x00, 0x00, // default_sample_size
0x00, 0x01, 0x00, 0x01 // default_sample_flags
]));
};
MP4.trun = function trun(track, offset) {
var samples = track.samples || [];
var len = samples.length;
var arraylen = 12 + 16 * len;
var array = new Uint8Array(arraylen);
var i;
var sample;
var duration;
var size;
var flags;
var cts;
offset += 8 + arraylen;
array.set([0x00, // version 0
0x00, 0x0f, 0x01, // flags
len >>> 24 & 0xff, len >>> 16 & 0xff, len >>> 8 & 0xff, len & 0xff, // sample_count
offset >>> 24 & 0xff, offset >>> 16 & 0xff, offset >>> 8 & 0xff, offset & 0xff // data_offset
], 0);
for (i = 0; i < len; i++) {
sample = samples[i];
duration = sample.duration;
size = sample.size;
flags = sample.flags;
cts = sample.cts;
array.set([duration >>> 24 & 0xff, duration >>> 16 & 0xff, duration >>> 8 & 0xff, duration & 0xff, // sample_duration
size >>> 24 & 0xff, size >>> 16 & 0xff, size >>> 8 & 0xff, size & 0xff, // sample_size
flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xf0 << 8, flags.degradPrio & 0x0f, // sample_flags
cts >>> 24 & 0xff, cts >>> 16 & 0xff, cts >>> 8 & 0xff, cts & 0xff // sample_composition_time_offset
], 12 + 16 * i);
}
return MP4.box(MP4.types.trun, array);
};
MP4.initSegment = function initSegment(tracks) {
if (!MP4.types) {
MP4.init();
}
var movie = MP4.moov(tracks);
var result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
result.set(MP4.FTYP);
result.set(movie, MP4.FTYP.byteLength);
return result;
};
return MP4;
}();
MP4.types = void 0;
MP4.HDLR_TYPES = void 0;
MP4.STTS = void 0;
MP4.STSC = void 0;
MP4.STCO = void 0;
MP4.STSZ = void 0;
MP4.VMHD = void 0;
MP4.SMHD = void 0;
MP4.STSD = void 0;
MP4.FTYP = void 0;
MP4.DINF = void 0;
/* harmony default export */ __webpack_exports__["default"] = (MP4);
/***/ }),
/***/ "./src/remux/mp4-remuxer.ts":
/*!**********************************!*\
!*** ./src/remux/mp4-remuxer.ts ***!
\**********************************/
/*! exports provided: default, normalizePts */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return MP4Remuxer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizePts", function() { return normalizePts; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _aac_helper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./aac-helper */ "./src/remux/aac-helper.ts");
/* harmony import */ var _mp4_generator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./mp4-generator */ "./src/remux/mp4-generator.ts");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../events */ "./src/events.ts");
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../errors */ "./src/errors.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/timescale-conversion */ "./src/utils/timescale-conversion.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
var MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds
var AAC_SAMPLES_PER_FRAME = 1024;
var MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;
var chromeVersion = null;
var safariWebkitVersion = null;
var requiresPositiveDts = false;
var MP4Remuxer = /*#__PURE__*/function () {
function MP4Remuxer(observer, config, typeSupported, vendor) {
if (vendor === void 0) {
vendor = '';
}
this.observer = void 0;
this.config = void 0;
this.typeSupported = void 0;
this.ISGenerated = false;
this._initPTS = void 0;
this._initDTS = void 0;
this.nextAvcDts = null;
this.nextAudioPts = null;
this.isAudioContiguous = false;
this.isVideoContiguous = false;
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
this.ISGenerated = false;
if (chromeVersion === null) {
var userAgent = navigator.userAgent || '';
var result = userAgent.match(/Chrome\/(\d+)/i);
chromeVersion = result ? parseInt(result[1]) : 0;
}
if (safariWebkitVersion === null) {
var _result = navigator.userAgent.match(/Safari\/(\d+)/i);
safariWebkitVersion = _result ? parseInt(_result[1]) : 0;
}
requiresPositiveDts = !!chromeVersion && chromeVersion < 75 || !!safariWebkitVersion && safariWebkitVersion < 600;
}
var _proto = MP4Remuxer.prototype;
_proto.destroy = function destroy() {};
_proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: initPTS & initDTS reset');
this._initPTS = this._initDTS = defaultTimeStamp;
};
_proto.resetNextTimestamp = function resetNextTimestamp() {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: reset next timestamp');
this.isVideoContiguous = false;
this.isAudioContiguous = false;
};
_proto.resetInitSegment = function resetInitSegment() {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: ISGenerated flag reset');
this.ISGenerated = false;
};
_proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
var rolloverDetected = false;
var startPTS = videoSamples.reduce(function (minPTS, sample) {
var delta = sample.pts - minPTS;
if (delta < -4294967296) {
// 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
rolloverDetected = true;
return normalizePts(minPTS, sample.pts);
} else if (delta > 0) {
return minPTS;
} else {
return sample.pts;
}
}, videoSamples[0].pts);
if (rolloverDetected) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].debug('PTS rollover detected');
}
return startPTS;
};
_proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, accurateTimeOffset, flush) {
var video;
var audio;
var initSegment;
var text;
var id3;
var independent;
var audioTimeOffset = timeOffset;
var videoTimeOffset = timeOffset; // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.
// This is done to synchronize the audio and video streams. We know if the current segment will have samples if the "pid"
// parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.
// However, if the initSegment has already been generated, or we've reached the end of a segment (flush),
// then we can remux one track without waiting for the other.
var hasAudio = audioTrack.pid > -1;
var hasVideo = videoTrack.pid > -1;
var enoughAudioSamples = audioTrack.samples.length > 0;
var enoughVideoSamples = videoTrack.samples.length > 1;
var canRemuxAvc = (!hasAudio || enoughAudioSamples) && (!hasVideo || enoughVideoSamples) || this.ISGenerated || flush;
if (canRemuxAvc) {
if (!this.ISGenerated) {
initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
}
var isVideoContiguous = this.isVideoContiguous;
if (enoughVideoSamples && !isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {
var length = videoTrack.samples.length;
var firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);
independent = true;
if (firstKeyFrameIndex > 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Dropped " + firstKeyFrameIndex + " out of " + length + " video samples due to a missing keyframe");
var startPTS = this.getVideoStartPts(videoTrack.samples);
videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);
videoTrack.dropped += firstKeyFrameIndex;
videoTimeOffset += (videoTrack.samples[0].pts - startPTS) / (videoTrack.timescale || 90000);
} else if (firstKeyFrameIndex === -1) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: No keyframe found out of " + length + " video samples");
independent = false;
}
}
if (this.ISGenerated) {
if (enoughAudioSamples && enoughVideoSamples) {
// timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
// if first audio DTS is not aligned with first video DTS then we need to take that into account
// when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
// drift between audio and video streams
var _startPTS = this.getVideoStartPts(videoTrack.samples);
var tsDelta = normalizePts(audioTrack.samples[0].pts, _startPTS) - _startPTS;
var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
} // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.
if (enoughAudioSamples) {
// if initSegment was generated without audio samples, regenerate it again
if (!audioTrack.samplerate) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as audio detected');
initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
delete initSegment.video;
}
audio = this.remuxAudio(audioTrack, audioTimeOffset, this.isAudioContiguous, accurateTimeOffset, enoughVideoSamples ? videoTimeOffset : undefined);
if (enoughVideoSamples) {
var audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0; // if initSegment was generated without video samples, regenerate it again
if (!videoTrack.inputTimeScale) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: regenerate InitSegment as video detected');
initSegment = this.generateIS(audioTrack, videoTrack, timeOffset);
}
video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, audioTrackLength);
}
} else if (enoughVideoSamples) {
video = this.remuxVideo(videoTrack, videoTimeOffset, isVideoContiguous, 0);
}
if (video && independent !== undefined) {
video.independent = independent;
}
}
} // Allow ID3 and text to remux, even if more audio/video samples are required
if (this.ISGenerated) {
if (id3Track.samples.length) {
id3 = this.remuxID3(id3Track, timeOffset);
}
if (textTrack.samples.length) {
text = this.remuxText(textTrack, timeOffset);
}
}
return {
audio: audio,
video: video,
initSegment: initSegment,
independent: independent,
text: text,
id3: id3
};
};
_proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) {
var audioSamples = audioTrack.samples;
var videoSamples = videoTrack.samples;
var typeSupported = this.typeSupported;
var tracks = {};
var computePTSDTS = !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(this._initPTS);
var container = 'audio/mp4';
var initPTS;
var initDTS;
var timescale;
if (computePTSDTS) {
initPTS = initDTS = Infinity;
}
if (audioTrack.config && audioSamples.length) {
// let's use audio sampling rate as MP4 time scale.
// rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
// using audio sampling rate here helps having an integer MP4 frame duration
// this avoids potential rounding issue and AV sync issue
audioTrack.timescale = audioTrack.samplerate;
if (!audioTrack.isAAC) {
if (typeSupported.mpeg) {
// Chrome and Safari
container = 'audio/mpeg';
audioTrack.codec = '';
} else if (typeSupported.mp3) {
// Firefox
audioTrack.codec = 'mp3';
}
}
tracks.audio = {
id: 'audio',
container: container,
codec: audioTrack.codec,
initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([audioTrack]),
metadata: {
channelCount: audioTrack.channelCount
}
};
if (computePTSDTS) {
timescale = audioTrack.inputTimeScale; // remember first PTS of this demuxing context. for audio, PTS = DTS
initPTS = initDTS = audioSamples[0].pts - Math.round(timescale * timeOffset);
}
}
if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
// let's use input time scale as MP4 video timescale
// we use input time scale straight away to avoid rounding issues on frame duration / cts computation
videoTrack.timescale = videoTrack.inputTimeScale;
tracks.video = {
id: 'main',
container: 'video/mp4',
codec: videoTrack.codec,
initSegment: _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].initSegment([videoTrack]),
metadata: {
width: videoTrack.width,
height: videoTrack.height
}
};
if (computePTSDTS) {
timescale = videoTrack.inputTimeScale;
var startPTS = this.getVideoStartPts(videoSamples);
var startOffset = Math.round(timescale * timeOffset);
initDTS = Math.min(initDTS, normalizePts(videoSamples[0].dts, startPTS) - startOffset);
initPTS = Math.min(initPTS, startPTS - startOffset);
}
}
if (Object.keys(tracks).length) {
this.ISGenerated = true;
if (computePTSDTS) {
this._initPTS = initPTS;
this._initDTS = initDTS;
}
return {
tracks: tracks,
initPTS: initPTS,
timescale: timescale
};
}
};
_proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
var timeScale = track.inputTimeScale;
var inputSamples = track.samples;
var outputSamples = [];
var nbSamples = inputSamples.length;
var initPTS = this._initPTS;
var nextAvcDts = this.nextAvcDts;
var offset = 8;
var mp4SampleDuration;
var firstDTS;
var lastDTS;
var minPTS = Number.POSITIVE_INFINITY;
var maxPTS = Number.NEGATIVE_INFINITY;
var ptsDtsShift = 0;
var sortSamples = false; // if parsed fragment is contiguous with last one, let's use last DTS value as reference
if (!contiguous || nextAvcDts === null) {
var pts = timeOffset * timeScale;
var cts = inputSamples[0].pts - normalizePts(inputSamples[0].dts, inputSamples[0].pts); // if not contiguous, let's use target timeOffset
nextAvcDts = pts - cts;
} // PTS is coded on 33bits, and can loop from -2^32 to 2^32
// PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
for (var i = 0; i < nbSamples; i++) {
var sample = inputSamples[i];
sample.pts = normalizePts(sample.pts - initPTS, nextAvcDts);
sample.dts = normalizePts(sample.dts - initPTS, nextAvcDts);
if (sample.dts > sample.pts) {
var PTS_DTS_SHIFT_TOLERANCE_90KHZ = 90000 * 0.2;
ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ);
}
if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
sortSamples = true;
}
} // sort video samples by DTS then PTS then demux id order
if (sortSamples) {
inputSamples.sort(function (a, b) {
var deltadts = a.dts - b.dts;
var deltapts = a.pts - b.pts;
return deltadts || deltapts;
});
} // Get first/last DTS
firstDTS = inputSamples[0].dts;
lastDTS = inputSamples[inputSamples.length - 1].dts; // on Safari let's signal the same sample duration for all samples
// sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
// set this constant duration as being the avg delta between consecutive DTS.
var averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1)); // handle broken streams with PTS < DTS, tolerance up 0.2 seconds
if (ptsDtsShift < 0) {
if (ptsDtsShift < averageSampleDuration * -2) {
// Fix for "CNN special report, with CC" in test-streams (including Safari browser)
// With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, offsetting DTS from PTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(-averageSampleDuration, true) + " ms");
var lastDts = ptsDtsShift;
for (var _i = 0; _i < nbSamples; _i++) {
inputSamples[_i].dts = lastDts = Math.max(lastDts, inputSamples[_i].pts - averageSampleDuration);
inputSamples[_i].pts = Math.max(lastDts, inputSamples[_i].pts);
}
} else {
// Fix for "Custom IV with bad PTS DTS" in test-streams
// With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("PTS < DTS detected in video samples, shifting DTS by " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(ptsDtsShift, true) + " ms to overcome this issue");
for (var _i2 = 0; _i2 < nbSamples; _i2++) {
inputSamples[_i2].dts = inputSamples[_i2].dts + ptsDtsShift;
}
}
firstDTS = inputSamples[0].dts;
} // if fragment are contiguous, detect hole/overlapping between fragments
if (contiguous) {
// check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
var delta = firstDTS - nextAvcDts;
var foundHole = delta > averageSampleDuration;
var foundOverlap = delta < -1;
if (foundHole || foundOverlap) {
if (foundHole) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(delta, true) + " ms (" + delta + "dts) hole between fragments detected, filling it");
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("AVC: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected");
}
firstDTS = nextAvcDts;
var firstPTS = inputSamples[0].pts - delta;
inputSamples[0].dts = firstDTS;
inputSamples[0].pts = firstPTS;
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("Video: First PTS/DTS adjusted: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(firstPTS, true) + "/" + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(firstDTS, true) + ", delta: " + Object(_utils_timescale_conversion__WEBPACK_IMPORTED_MODULE_6__["toMsFromMpegTsClock"])(delta, true) + " ms");
}
}
if (requiresPositiveDts) {
firstDTS = Math.max(0, firstDTS);
}
var nbNalu = 0;
var naluLen = 0;
for (var _i3 = 0; _i3 < nbSamples; _i3++) {
// compute total/avc sample length and nb of NAL units
var _sample = inputSamples[_i3];
var units = _sample.units;
var nbUnits = units.length;
var sampleLen = 0;
for (var j = 0; j < nbUnits; j++) {
sampleLen += units[j].data.length;
}
naluLen += sampleLen;
nbNalu += nbUnits;
_sample.length = sampleLen; // normalize PTS/DTS
// ensure sample monotonic DTS
_sample.dts = Math.max(_sample.dts, firstDTS); // ensure that computed value is greater or equal than sample DTS
_sample.pts = Math.max(_sample.pts, _sample.dts, 0);
minPTS = Math.min(_sample.pts, minPTS);
maxPTS = Math.max(_sample.pts, maxPTS);
}
lastDTS = inputSamples[nbSamples - 1].dts;
/* concatenate the video data and construct the mdat in place
(need 8 more bytes to fill length and mpdat type) */
var mdatSize = naluLen + 4 * nbNalu + 8;
var mdat;
try {
mdat = new Uint8Array(mdatSize);
} catch (err) {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].REMUX_ALLOC_ERROR,
fatal: false,
bytes: mdatSize,
reason: "fail allocating video mdat " + mdatSize
});
return;
}
var view = new DataView(mdat.buffer);
view.setUint32(0, mdatSize);
mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4);
for (var _i4 = 0; _i4 < nbSamples; _i4++) {
var avcSample = inputSamples[_i4];
var avcSampleUnits = avcSample.units;
var mp4SampleLength = 0; // convert NALU bitstream to MP4 format (prepend NALU with size field)
for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
var unit = avcSampleUnits[_j];
var unitData = unit.data;
var unitDataLen = unit.data.byteLength;
view.setUint32(offset, unitDataLen);
offset += 4;
mdat.set(unitData, offset);
offset += unitDataLen;
mp4SampleLength += 4 + unitDataLen;
} // expected sample duration is the Decoding Timestamp diff of consecutive samples
if (_i4 < nbSamples - 1) {
mp4SampleDuration = inputSamples[_i4 + 1].dts - avcSample.dts;
} else {
var config = this.config;
var lastFrameDuration = avcSample.dts - inputSamples[_i4 > 0 ? _i4 - 1 : _i4].dts;
if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {
// In some cases, a segment's audio track duration may exceed the video track duration.
// Since we've already remuxed audio, and we know how long the audio track is, we look to
// see if the delta to the next segment is longer than maxBufferHole.
// If so, playback would potentially get stuck, so we artificially inflate
// the duration of the last frame to minimize any potential gap between segments.
var gapTolerance = Math.floor(config.maxBufferHole * timeScale);
var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
if (deltaToFrameEnd > gapTolerance) {
// We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
// frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
if (mp4SampleDuration < 0) {
mp4SampleDuration = lastFrameDuration;
}
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("[mp4-remuxer]: It is approximately " + deltaToFrameEnd / 90 + " ms to the next segment; using duration " + mp4SampleDuration / 90 + " ms for the last video frame.");
} else {
mp4SampleDuration = lastFrameDuration;
}
} else {
mp4SampleDuration = lastFrameDuration;
}
}
var compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
outputSamples.push(new Mp4Sample(avcSample.key, mp4SampleDuration, mp4SampleLength, compositionTimeOffset));
}
if (outputSamples.length && chromeVersion && chromeVersion < 70) {
// Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue
// https://code.google.com/p/chromium/issues/detail?id=229412
var flags = outputSamples[0].flags;
flags.dependsOn = 2;
flags.isNonSync = 0;
}
console.assert(mp4SampleDuration !== undefined, 'mp4SampleDuration must be computed'); // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;
this.isVideoContiguous = true;
var moof = _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstDTS, _extends({}, track, {
samples: outputSamples
}));
var type = 'video';
var data = {
data1: moof,
data2: mdat,
startPTS: minPTS / timeScale,
endPTS: (maxPTS + mp4SampleDuration) / timeScale,
startDTS: firstDTS / timeScale,
endDTS: nextAvcDts / timeScale,
type: type,
hasAudio: false,
hasVideo: true,
nb: outputSamples.length,
dropped: track.dropped
};
track.samples = [];
track.dropped = 0;
console.assert(mdat.length, 'MDAT length must not be zero');
return data;
};
_proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
var inputTimeScale = track.inputTimeScale;
var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
var scaleFactor = inputTimeScale / mp4timeScale;
var mp4SampleDuration = track.isAAC ? AAC_SAMPLES_PER_FRAME : MPEG_AUDIO_SAMPLE_PER_FRAME;
var inputSampleDuration = mp4SampleDuration * scaleFactor;
var initPTS = this._initPTS;
var rawMPEG = !track.isAAC && this.typeSupported.mpeg;
var outputSamples = [];
var inputSamples = track.samples;
var offset = rawMPEG ? 0 : 8;
var fillFrame;
var nextAudioPts = this.nextAudioPts || -1; // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);
// for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
// for sake of clarity:
// consecutive fragments are frags with
// - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
// - less than 20 audio frames distance
// contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
// this helps ensuring audio continuity
// and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
var timeOffsetMpegTS = timeOffset * inputTimeScale;
this.isAudioContiguous = contiguous = contiguous || inputSamples.length && nextAudioPts > 0 && (accurateTimeOffset && Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000 || Math.abs(normalizePts(inputSamples[0].pts - initPTS, timeOffsetMpegTS) - nextAudioPts) < 20 * inputSampleDuration); // compute normalized PTS
inputSamples.forEach(function (sample) {
sample.pts = sample.dts = normalizePts(sample.pts - initPTS, timeOffsetMpegTS);
});
if (!contiguous || nextAudioPts < 0) {
// filter out sample with negative PTS that are not playable anyway
// if we don't remove these negative samples, they will shift all audio samples forward.
// leading to audio overlap between current / next fragment
inputSamples = inputSamples.filter(function (sample) {
return sample.pts >= 0;
}); // in case all samples have negative PTS, and have been filtered out, return now
if (!inputSamples.length) {
return;
}
if (videoTimeOffset === 0) {
// Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence
nextAudioPts = 0;
} else if (accurateTimeOffset) {
// When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
nextAudioPts = Math.max(0, timeOffsetMpegTS);
} else {
// if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
nextAudioPts = inputSamples[0].pts;
}
} // If the audio track is missing samples, the frames seem to get "left-shifted" within the
// resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
// In an effort to prevent this from happening, we inject frames here where there are gaps.
// When possible, we inject a silent frame; when that's not possible, we duplicate the last
// frame.
if (track.isAAC) {
var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {
// First, let's see how far off this frame is from where we expect it to be
var sample = inputSamples[i];
var pts = sample.pts;
var delta = pts - nextPts;
var duration = Math.abs(1000 * delta / inputTimeScale); // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync
if (delta <= -maxAudioFramesDrift * inputSampleDuration && videoTimeOffset !== undefined) {
if (contiguous || i > 0) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Dropping 1 audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(duration) + " ms overlap.");
inputSamples.splice(i, 1); // Don't touch nextPtsNorm or i
} else {
// When changing qualities we can't trust that audio has been appended up to nextAudioPts
// Warn about the overlap but do not drop samples as that can introduce buffer gaps
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("Audio frame @ " + (pts / inputTimeScale).toFixed(3) + "s overlaps nextAudioPts by " + Math.round(1000 * delta / inputTimeScale) + " ms.");
nextPts = pts + inputSampleDuration;
i++;
}
} // eslint-disable-line brace-style
// Insert missing frames if:
// 1: We're more than maxAudioFramesDrift frame away
// 2: Not more than MAX_SILENT_FRAME_DURATION away
// 3: currentTime (aka nextPtsNorm) is not 0
// 4: remuxing with video (videoTimeOffset !== undefined)
else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && videoTimeOffset !== undefined) {
var missing = Math.floor(delta / inputSampleDuration); // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
// later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
nextPts = pts - missing * inputSampleDuration;
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn("[mp4-remuxer]: Injecting " + missing + " audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(1000 * delta / inputTimeScale) + " ms gap.");
for (var j = 0; j < missing; j++) {
var newStamp = Math.max(nextPts, 0);
fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.');
fillFrame = sample.unit.subarray();
}
inputSamples.splice(i, 0, {
unit: fillFrame,
pts: newStamp,
dts: newStamp
});
nextPts += inputSampleDuration;
i++;
} // Adjust sample to next expected pts
sample.pts = sample.dts = nextPts;
nextPts += inputSampleDuration;
i++;
} else {
// Otherwise, just adjust pts
sample.pts = sample.dts = nextPts;
nextPts += inputSampleDuration;
i++;
}
}
}
var firstPTS = null;
var lastPTS = null;
var mdat;
var mdatSize = 0;
var sampleLength = inputSamples.length;
while (sampleLength--) {
mdatSize += inputSamples[sampleLength].unit.byteLength;
}
for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
var audioSample = inputSamples[_j2];
var unit = audioSample.unit;
var _pts = audioSample.pts;
if (lastPTS !== null) {
// If we have more than one sample, set the duration of the sample to the "real" duration; the PTS diff with
// the previous sample
var prevSample = outputSamples[_j2 - 1];
prevSample.duration = Math.round((_pts - lastPTS) / scaleFactor);
} else {
var _delta = Math.round(1000 * (_pts - nextAudioPts) / inputTimeScale);
var numMissingFrames = 0; // if fragment are contiguous, detect hole/overlapping between fragments
// contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
if (contiguous && track.isAAC) {
if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION) {
numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration);
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("[mp4-remuxer]: " + _delta + " ms hole between AAC samples detected,filling it");
if (numMissingFrames > 0) {
fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
fillFrame = unit.subarray();
}
mdatSize += numMissingFrames * fillFrame.length;
} // if we have frame overlap, overlapping for more than half a frame duraion
} else if (_delta < -12) {
// drop overlapping audio frames... browser will deal with it
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log("[mp4-remuxer]: drop overlapping AAC sample, expected/parsed/delta:" + (nextAudioPts / inputTimeScale).toFixed(3) + "s/" + (_pts / inputTimeScale).toFixed(3) + "s/" + -_delta + "ms");
mdatSize -= unit.byteLength;
continue;
} // set PTS/DTS to expected PTS/DTS
_pts = nextAudioPts;
} // remember first PTS of our audioSamples
firstPTS = _pts;
if (mdatSize > 0) {
/* concatenate the audio data and construct the mdat in place
(need 8 more bytes to fill length and mdat type) */
mdatSize += offset;
try {
mdat = new Uint8Array(mdatSize);
} catch (err) {
this.observer.emit(_events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, _events__WEBPACK_IMPORTED_MODULE_3__["Events"].ERROR, {
type: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorTypes"].MUX_ERROR,
details: _errors__WEBPACK_IMPORTED_MODULE_4__["ErrorDetails"].REMUX_ALLOC_ERROR,
fatal: false,
bytes: mdatSize,
reason: "fail allocating audio mdat " + mdatSize
});
return;
}
if (!rawMPEG) {
var view = new DataView(mdat.buffer);
view.setUint32(0, mdatSize);
mdat.set(_mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].types.mdat, 4);
}
} else {
// no audio samples
return;
}
for (var _i5 = 0; _i5 < numMissingFrames; _i5++) {
fillFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].log('[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating the current frame instead');
fillFrame = unit.subarray();
}
mdat.set(fillFrame, offset);
offset += fillFrame.byteLength;
outputSamples.push(new Mp4Sample(true, AAC_SAMPLES_PER_FRAME, fillFrame.byteLength, 0));
}
}
mdat.set(unit, offset);
var unitLen = unit.byteLength;
offset += unitLen; // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG
// In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration
// becomes the PTS diff with the previous sample
outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));
lastPTS = _pts;
} // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones
var nbSamples = outputSamples.length;
if (!nbSamples) {
return;
} // The next audio sample PTS should be equal to last sample PTS + duration
var lastSample = outputSamples[outputSamples.length - 1];
this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSample.duration; // Set the track samples from inputSamples to outputSamples before remuxing
var moof = rawMPEG ? new Uint8Array(0) : _mp4_generator__WEBPACK_IMPORTED_MODULE_2__["default"].moof(track.sequenceNumber++, firstPTS / scaleFactor, _extends({}, track, {
samples: outputSamples
})); // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared
track.samples = [];
var start = firstPTS / inputTimeScale;
var end = nextAudioPts / inputTimeScale;
var type = 'audio';
var audioData = {
data1: moof,
data2: mdat,
startPTS: start,
endPTS: end,
startDTS: start,
endDTS: end,
type: type,
hasAudio: true,
hasVideo: false,
nb: nbSamples
};
this.isAudioContiguous = true;
console.assert(mdat.length, 'MDAT length must not be zero');
return audioData;
};
_proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
var inputTimeScale = track.inputTimeScale;
var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
var scaleFactor = inputTimeScale / mp4timeScale;
var nextAudioPts = this.nextAudioPts; // sync with video's timestamp
var startDTS = (nextAudioPts !== null ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;
var endDTS = videoData.endDTS * inputTimeScale + this._initDTS; // one sample's duration value
var frameDuration = scaleFactor * AAC_SAMPLES_PER_FRAME; // samples count of this segment's duration
var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration); // silent frame
var silentFrame = _aac_helper__WEBPACK_IMPORTED_MODULE_1__["default"].getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].warn('[mp4-remuxer]: remux empty Audio'); // Can't remux if we can't generate a silent frame...
if (!silentFrame) {
_utils_logger__WEBPACK_IMPORTED_MODULE_5__["logger"].trace('[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec');
return;
}
var samples = [];
for (var i = 0; i < nbSamples; i++) {
var stamp = startDTS + i * frameDuration;
samples.push({
unit: silentFrame,
pts: stamp,
dts: stamp
});
}
track.samples = samples;
return this.remuxAudio(track, timeOffset, contiguous, false);
};
_proto.remuxID3 = function remuxID3(track, timeOffset) {
var length = track.samples.length;
if (!length) {
return;
}
var inputTimeScale = track.inputTimeScale;
var initPTS = this._initPTS;
var initDTS = this._initDTS;
for (var index = 0; index < length; index++) {
var sample = track.samples[index]; // setting id3 pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
sample.dts = normalizePts(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;
}
var samples = track.samples;
track.samples = [];
return {
samples: samples
};
};
_proto.remuxText = function remuxText(track, timeOffset) {
var length = track.samples.length;
if (!length) {
return;
}
var inputTimeScale = track.inputTimeScale;
var initPTS = this._initPTS;
for (var index = 0; index < length; index++) {
var sample = track.samples[index]; // setting text pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = normalizePts(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
}
track.samples.sort(function (a, b) {
return a.pts - b.pts;
});
var samples = track.samples;
track.samples = [];
return {
samples: samples
};
};
return MP4Remuxer;
}();
function normalizePts(value, reference) {
var offset;
if (reference === null) {
return value;
}
if (reference < value) {
// - 2^33
offset = -8589934592;
} else {
// + 2^33
offset = 8589934592;
}
/* PTS is 33bit (from 0 to 2^33 -1)
if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
PTS looping occured. fill the gap */
while (Math.abs(value - reference) > 4294967296) {
value += offset;
}
return value;
}
function findKeyframeIndex(samples) {
for (var i = 0; i < samples.length; i++) {
if (samples[i].key) {
return i;
}
}
return -1;
}
var Mp4Sample = function Mp4Sample(isKeyframe, duration, size, cts) {
this.size = void 0;
this.duration = void 0;
this.cts = void 0;
this.flags = void 0;
this.duration = duration;
this.size = size;
this.cts = cts;
this.flags = new Mp4SampleFlags(isKeyframe);
};
var Mp4SampleFlags = function Mp4SampleFlags(isKeyframe) {
this.isLeading = 0;
this.isDependedOn = 0;
this.hasRedundancy = 0;
this.degradPrio = 0;
this.dependsOn = 1;
this.isNonSync = 1;
this.dependsOn = isKeyframe ? 2 : 1;
this.isNonSync = isKeyframe ? 0 : 1;
};
/***/ }),
/***/ "./src/remux/passthrough-remuxer.ts":
/*!******************************************!*\
!*** ./src/remux/passthrough-remuxer.ts ***!
\******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
var PassThroughRemuxer = /*#__PURE__*/function () {
function PassThroughRemuxer() {
this.emitInitSegment = false;
this.audioCodec = void 0;
this.videoCodec = void 0;
this.initData = void 0;
this.initPTS = void 0;
this.initTracks = void 0;
this.lastEndDTS = null;
}
var _proto = PassThroughRemuxer.prototype;
_proto.destroy = function destroy() {};
_proto.resetTimeStamp = function resetTimeStamp(defaultInitPTS) {
this.initPTS = defaultInitPTS;
this.lastEndDTS = null;
};
_proto.resetNextTimestamp = function resetNextTimestamp() {
this.lastEndDTS = null;
};
_proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec) {
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this.generateInitSegment(initSegment);
this.emitInitSegment = true;
};
_proto.generateInitSegment = function generateInitSegment(initSegment) {
var audioCodec = this.audioCodec,
videoCodec = this.videoCodec;
if (!initSegment || !initSegment.byteLength) {
this.initTracks = undefined;
this.initData = undefined;
return;
}
var initData = this.initData = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["parseInitSegment"])(initSegment); // Get codec from initSegment or fallback to default
if (!audioCodec) {
audioCodec = getParsedTrackCodec(initData.audio, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].AUDIO);
}
if (!videoCodec) {
videoCodec = getParsedTrackCodec(initData.video, _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO);
}
var tracks = {};
if (initData.audio && initData.video) {
tracks.audiovideo = {
container: 'video/mp4',
codec: audioCodec + ',' + videoCodec,
initSegment: initSegment,
id: 'main'
};
} else if (initData.audio) {
tracks.audio = {
container: 'audio/mp4',
codec: audioCodec,
initSegment: initSegment,
id: 'audio'
};
} else if (initData.video) {
tracks.video = {
container: 'video/mp4',
codec: videoCodec,
initSegment: initSegment,
id: 'main'
};
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.');
}
this.initTracks = tracks;
};
_proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset) {
var initPTS = this.initPTS,
lastEndDTS = this.lastEndDTS;
var result = {
audio: undefined,
video: undefined,
text: textTrack,
id3: id3Track,
initSegment: undefined
}; // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the
// lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update
// the media duration (which is what timeOffset is provided as) before we need to process the next chunk.
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(lastEndDTS)) {
lastEndDTS = this.lastEndDTS = timeOffset || 0;
} // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only
// audio or video (or both); adding it to video was an arbitrary choice.
var data = videoTrack.samples;
if (!data || !data.length) {
return result;
}
var initSegment = {
initPTS: undefined,
timescale: 1
};
var initData = this.initData;
if (!initData || !initData.length) {
this.generateInitSegment(data);
initData = this.initData;
}
if (!initData || !initData.length) {
// We can't remux if the initSegment could not be generated
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');
return result;
}
if (this.emitInitSegment) {
initSegment.tracks = this.initTracks;
this.emitInitSegment = false;
}
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(initPTS)) {
this.initPTS = initSegment.initPTS = initPTS = computeInitPTS(initData, data, lastEndDTS);
}
var duration = Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getDuration"])(data, initData);
var startDTS = lastEndDTS;
var endDTS = duration + startDTS;
Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["offsetStartDTS"])(initData, data, initPTS);
if (duration > 0) {
this.lastEndDTS = endDTS;
} else {
_utils_logger__WEBPACK_IMPORTED_MODULE_3__["logger"].warn('Duration parsed from mp4 should be greater than zero');
this.resetNextTimestamp();
}
var hasAudio = !!initData.audio;
var hasVideo = !!initData.video;
var type = '';
if (hasAudio) {
type += 'audio';
}
if (hasVideo) {
type += 'video';
}
var track = {
data1: data,
startPTS: startDTS,
startDTS: startDTS,
endPTS: endDTS,
endDTS: endDTS,
type: type,
hasAudio: hasAudio,
hasVideo: hasVideo,
nb: 1,
dropped: 0
};
result.audio = track.type === 'audio' ? track : undefined;
result.video = track.type !== 'audio' ? track : undefined;
result.text = textTrack;
result.id3 = id3Track;
result.initSegment = initSegment;
return result;
};
return PassThroughRemuxer;
}();
var computeInitPTS = function computeInitPTS(initData, data, timeOffset) {
return Object(_utils_mp4_tools__WEBPACK_IMPORTED_MODULE_1__["getStartDTS"])(initData, data) - timeOffset;
};
function getParsedTrackCodec(track, type) {
var parsedCodec = track === null || track === void 0 ? void 0 : track.codec;
if (parsedCodec && parsedCodec.length > 4) {
return parsedCodec;
} // Since mp4-tools cannot parse full codec string (see 'TODO: Parse codec details'... in mp4-tools)
// Provide defaults based on codec type
// This allows for some playback of some fmp4 playlists without CODECS defined in manifest
if (parsedCodec === 'hvc1') {
return 'hvc1.1.c.L120.90';
}
if (parsedCodec === 'av01') {
return 'av01.0.04M.08';
}
if (parsedCodec === 'avc1' || type === _loader_fragment__WEBPACK_IMPORTED_MODULE_2__["ElementaryStreamTypes"].VIDEO) {
return 'avc1.42e01e';
}
return 'mp4a.40.5';
}
/* harmony default export */ __webpack_exports__["default"] = (PassThroughRemuxer);
/***/ }),
/***/ "./src/task-loop.ts":
/*!**************************!*\
!*** ./src/task-loop.ts ***!
\**************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TaskLoop; });
/**
* Sub-class specialization of EventHandler base class.
*
* TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
* scheduled asynchroneously, avoiding recursive calls in the same tick.
*
* The task itself is implemented in `doTick`. It can be requested and called for single execution
* using the `tick` method.
*
* It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
* no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
*
* If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
* and cancelled with `clearNextTick`.
*
* The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
*
* Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
*
* Further explanations:
*
* The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
* only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
*
* When the task execution (`tick` method) is called in re-entrant way this is detected and
* we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
* task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
*/
var TaskLoop = /*#__PURE__*/function () {
function TaskLoop() {
this._boundTick = void 0;
this._tickTimer = null;
this._tickInterval = null;
this._tickCallCount = 0;
this._boundTick = this.tick.bind(this);
}
var _proto = TaskLoop.prototype;
_proto.destroy = function destroy() {
this.onHandlerDestroying();
this.onHandlerDestroyed();
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
// clear all timers before unregistering from event bus
this.clearNextTick();
this.clearInterval();
};
_proto.onHandlerDestroyed = function onHandlerDestroyed() {}
/**
* @returns {boolean}
*/
;
_proto.hasInterval = function hasInterval() {
return !!this._tickInterval;
}
/**
* @returns {boolean}
*/
;
_proto.hasNextTick = function hasNextTick() {
return !!this._tickTimer;
}
/**
* @param {number} millis Interval time (ms)
* @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
*/
;
_proto.setInterval = function setInterval(millis) {
if (!this._tickInterval) {
this._tickInterval = self.setInterval(this._boundTick, millis);
return true;
}
return false;
}
/**
* @returns {boolean} True when interval was cleared, false when none was set (no effect)
*/
;
_proto.clearInterval = function clearInterval() {
if (this._tickInterval) {
self.clearInterval(this._tickInterval);
this._tickInterval = null;
return true;
}
return false;
}
/**
* @returns {boolean} True when timeout was cleared, false when none was set (no effect)
*/
;
_proto.clearNextTick = function clearNextTick() {
if (this._tickTimer) {
self.clearTimeout(this._tickTimer);
this._tickTimer = null;
return true;
}
return false;
}
/**
* Will call the subclass doTick implementation in this main loop tick
* or in the next one (via setTimeout(,0)) in case it has already been called
* in this tick (in case this is a re-entrant call).
*/
;
_proto.tick = function tick() {
this._tickCallCount++;
if (this._tickCallCount === 1) {
this.doTick(); // re-entrant call to tick from previous doTick call stack
// -> schedule a call on the next main loop iteration to process this task processing request
if (this._tickCallCount > 1) {
// make sure only one timer exists at any time at max
this.clearNextTick();
this._tickTimer = self.setTimeout(this._boundTick, 0);
}
this._tickCallCount = 0;
}
}
/**
* For subclass to implement task logic
* @abstract
*/
;
_proto.doTick = function doTick() {};
return TaskLoop;
}();
/***/ }),
/***/ "./src/types/level.ts":
/*!****************************!*\
!*** ./src/types/level.ts ***!
\****************************/
/*! exports provided: HlsSkip, getSkipValue, HlsUrlParameters, Level */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsSkip", function() { return HlsSkip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSkipValue", function() { return getSkipValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HlsUrlParameters", function() { return HlsUrlParameters; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Level", function() { return Level; });
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var HlsSkip;
(function (HlsSkip) {
HlsSkip["No"] = "";
HlsSkip["Yes"] = "YES";
HlsSkip["v2"] = "v2";
})(HlsSkip || (HlsSkip = {}));
function getSkipValue(details, msn) {
var canSkipUntil = details.canSkipUntil,
canSkipDateRanges = details.canSkipDateRanges,
endSN = details.endSN;
var snChangeGoal = msn !== undefined ? msn - endSN : 0;
if (canSkipUntil && snChangeGoal < canSkipUntil) {
if (canSkipDateRanges) {
return HlsSkip.v2;
}
return HlsSkip.Yes;
}
return HlsSkip.No;
}
var HlsUrlParameters = /*#__PURE__*/function () {
function HlsUrlParameters(msn, part, skip) {
this.msn = void 0;
this.part = void 0;
this.skip = void 0;
this.msn = msn;
this.part = part;
this.skip = skip;
}
var _proto = HlsUrlParameters.prototype;
_proto.addDirectives = function addDirectives(uri) {
var url = new self.URL(uri);
if (this.msn !== undefined) {
url.searchParams.set('_HLS_msn', this.msn.toString());
}
if (this.part !== undefined) {
url.searchParams.set('_HLS_part', this.part.toString());
}
if (this.skip) {
url.searchParams.set('_HLS_skip', this.skip);
}
return url.toString();
};
return HlsUrlParameters;
}();
var Level = /*#__PURE__*/function () {
function Level(data) {
this.attrs = void 0;
this.audioCodec = void 0;
this.bitrate = void 0;
this.codecSet = void 0;
this.height = void 0;
this.id = void 0;
this.name = void 0;
this.videoCodec = void 0;
this.width = void 0;
this.unknownCodecs = void 0;
this.audioGroupIds = void 0;
this.details = void 0;
this.fragmentError = 0;
this.loadError = 0;
this.loaded = void 0;
this.realBitrate = 0;
this.textGroupIds = void 0;
this.url = void 0;
this._urlId = 0;
this.url = [data.url];
this.attrs = data.attrs;
this.bitrate = data.bitrate;
if (data.details) {
this.details = data.details;
}
this.id = data.id || 0;
this.name = data.name;
this.width = data.width || 0;
this.height = data.height || 0;
this.audioCodec = data.audioCodec;
this.videoCodec = data.videoCodec;
this.unknownCodecs = data.unknownCodecs;
this.codecSet = [data.videoCodec, data.audioCodec].filter(function (c) {
return c;
}).join(',').replace(/\.[^.,]+/g, '');
}
_createClass(Level, [{
key: "maxBitrate",
get: function get() {
return Math.max(this.realBitrate, this.bitrate);
}
}, {
key: "uri",
get: function get() {
return this.url[this._urlId] || '';
}
}, {
key: "urlId",
get: function get() {
return this._urlId;
},
set: function set(value) {
var newValue = value % this.url.length;
if (this._urlId !== newValue) {
this.details = undefined;
this._urlId = newValue;
}
}
}]);
return Level;
}();
/***/ }),
/***/ "./src/types/loader.ts":
/*!*****************************!*\
!*** ./src/types/loader.ts ***!
\*****************************/
/*! exports provided: PlaylistContextType, PlaylistLevelType */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistContextType", function() { return PlaylistContextType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaylistLevelType", function() { return PlaylistLevelType; });
var PlaylistContextType;
(function (PlaylistContextType) {
PlaylistContextType["MANIFEST"] = "manifest";
PlaylistContextType["LEVEL"] = "level";
PlaylistContextType["AUDIO_TRACK"] = "audioTrack";
PlaylistContextType["SUBTITLE_TRACK"] = "subtitleTrack";
})(PlaylistContextType || (PlaylistContextType = {}));
var PlaylistLevelType;
(function (PlaylistLevelType) {
PlaylistLevelType["MAIN"] = "main";
PlaylistLevelType["AUDIO"] = "audio";
PlaylistLevelType["SUBTITLE"] = "subtitle";
})(PlaylistLevelType || (PlaylistLevelType = {}));
/***/ }),
/***/ "./src/types/transmuxer.ts":
/*!*********************************!*\
!*** ./src/types/transmuxer.ts ***!
\*********************************/
/*! exports provided: ChunkMetadata */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ChunkMetadata", function() { return ChunkMetadata; });
var ChunkMetadata = function ChunkMetadata(level, sn, id, size, part, partial) {
if (size === void 0) {
size = 0;
}
if (part === void 0) {
part = -1;
}
if (partial === void 0) {
partial = false;
}
this.level = void 0;
this.sn = void 0;
this.part = void 0;
this.id = void 0;
this.size = void 0;
this.partial = void 0;
this.transmuxing = getNewPerformanceTiming();
this.buffering = {
audio: getNewPerformanceTiming(),
video: getNewPerformanceTiming(),
audiovideo: getNewPerformanceTiming()
};
this.level = level;
this.sn = sn;
this.id = id;
this.size = size;
this.part = part;
this.partial = partial;
};
function getNewPerformanceTiming() {
return {
start: 0,
executeStart: 0,
executeEnd: 0,
end: 0
};
}
/***/ }),
/***/ "./src/utils/attr-list.ts":
/*!********************************!*\
!*** ./src/utils/attr-list.ts ***!
\********************************/
/*! exports provided: AttrList */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AttrList", function() { return AttrList; });
var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
var AttrList = /*#__PURE__*/function () {
function AttrList(attrs) {
if (typeof attrs === 'string') {
attrs = AttrList.parseAttrList(attrs);
}
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
this[attr] = attrs[attr];
}
}
}
var _proto = AttrList.prototype;
_proto.decimalInteger = function decimalInteger(attrName) {
var intValue = parseInt(this[attrName], 10);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
};
_proto.hexadecimalInteger = function hexadecimalInteger(attrName) {
if (this[attrName]) {
var stringValue = (this[attrName] || '0x').slice(2);
stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
var value = new Uint8Array(stringValue.length / 2);
for (var i = 0; i < stringValue.length / 2; i++) {
value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
}
return value;
} else {
return null;
}
};
_proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
var intValue = parseInt(this[attrName], 16);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
};
_proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
return parseFloat(this[attrName]);
};
_proto.optionalFloat = function optionalFloat(attrName, defaultValue) {
var value = this[attrName];
return value ? parseFloat(value) : defaultValue;
};
_proto.enumeratedString = function enumeratedString(attrName) {
return this[attrName];
};
_proto.bool = function bool(attrName) {
return this[attrName] === 'YES';
};
_proto.decimalResolution = function decimalResolution(attrName) {
var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
if (res === null) {
return undefined;
}
return {
width: parseInt(res[1], 10),
height: parseInt(res[2], 10)
};
};
AttrList.parseAttrList = function parseAttrList(input) {
var match;
var attrs = {};
var quote = '"';
ATTR_LIST_REGEX.lastIndex = 0;
while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
var value = match[2];
if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
value = value.slice(1, -1);
}
attrs[match[1]] = value;
}
return attrs;
};
return AttrList;
}();
/***/ }),
/***/ "./src/utils/binary-search.ts":
/*!************************************!*\
!*** ./src/utils/binary-search.ts ***!
\************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
var BinarySearch = {
/**
* Searches for an item in an array which matches a certain condition.
* This requires the condition to only match one item in the array,
* and for the array to be ordered.
*
* @param {Array<T>} list The array to search.
* @param {BinarySearchComparison<T>} comparisonFn
* Called and provided a candidate item as the first argument.
* Should return:
* > -1 if the item should be located at a lower index than the provided item.
* > 1 if the item should be located at a higher index than the provided item.
* > 0 if the item is the item you're looking for.
*
* @return {T | null} The object if it is found or null otherwise.
*/
search: function search(list, comparisonFn) {
var minIndex = 0;
var maxIndex = list.length - 1;
var currentIndex = null;
var currentElement = null;
while (minIndex <= maxIndex) {
currentIndex = (minIndex + maxIndex) / 2 | 0;
currentElement = list[currentIndex];
var comparisonResult = comparisonFn(currentElement);
if (comparisonResult > 0) {
minIndex = currentIndex + 1;
} else if (comparisonResult < 0) {
maxIndex = currentIndex - 1;
} else {
return currentElement;
}
}
return null;
}
};
/* harmony default export */ __webpack_exports__["default"] = (BinarySearch);
/***/ }),
/***/ "./src/utils/buffer-helper.ts":
/*!************************************!*\
!*** ./src/utils/buffer-helper.ts ***!
\************************************/
/*! exports provided: BufferHelper */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BufferHelper", function() { return BufferHelper; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
* @module BufferHelper
*
* Providing methods dealing with buffer length retrieval for example.
*
* In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
*
* Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
*/
var noopBuffered = {
length: 0,
start: function start() {
return 0;
},
end: function end() {
return 0;
}
};
var BufferHelper = /*#__PURE__*/function () {
function BufferHelper() {}
/**
* Return true if `media`'s buffered include `position`
* @param {Bufferable} media
* @param {number} position
* @returns {boolean}
*/
BufferHelper.isBuffered = function isBuffered(media, position) {
try {
if (media) {
var buffered = BufferHelper.getBuffered(media);
for (var i = 0; i < buffered.length; i++) {
if (position >= buffered.start(i) && position <= buffered.end(i)) {
return true;
}
}
}
} catch (error) {// this is to catch
// InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
// This SourceBuffer has been removed from the parent media source
}
return false;
};
BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
try {
if (media) {
var vbuffered = BufferHelper.getBuffered(media);
var buffered = [];
var i;
for (i = 0; i < vbuffered.length; i++) {
buffered.push({
start: vbuffered.start(i),
end: vbuffered.end(i)
});
}
return this.bufferedInfo(buffered, pos, maxHoleDuration);
}
} catch (error) {// this is to catch
// InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
// This SourceBuffer has been removed from the parent media source
}
return {
len: 0,
start: pos,
end: pos,
nextStart: undefined
};
};
BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
// sort on buffer.start/smaller end (IE does not always return sorted buffered range)
buffered.sort(function (a, b) {
var diff = a.start - b.start;
if (diff) {
return diff;
} else {
return b.end - a.end;
}
});
var buffered2 = [];
if (maxHoleDuration) {
// there might be some small holes between buffer time range
// consider that holes smaller than maxHoleDuration are irrelevant and build another
// buffer time range representations that discards those holes
for (var i = 0; i < buffered.length; i++) {
var buf2len = buffered2.length;
if (buf2len) {
var buf2end = buffered2[buf2len - 1].end; // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
if (buffered[i].start - buf2end < maxHoleDuration) {
// merge overlapping time ranges
// update lastRange.end only if smaller than item.end
// e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
// whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
if (buffered[i].end > buf2end) {
buffered2[buf2len - 1].end = buffered[i].end;
}
} else {
// big hole
buffered2.push(buffered[i]);
}
} else {
// first value
buffered2.push(buffered[i]);
}
}
} else {
buffered2 = buffered;
}
var bufferLen = 0; // bufferStartNext can possibly be undefined based on the conditional logic below
var bufferStartNext; // bufferStart and bufferEnd are buffer boundaries around current video position
var bufferStart = pos;
var bufferEnd = pos;
for (var _i = 0; _i < buffered2.length; _i++) {
var start = buffered2[_i].start;
var end = buffered2[_i].end; // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
if (pos + maxHoleDuration >= start && pos < end) {
// play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
bufferStart = start;
bufferEnd = end;
bufferLen = bufferEnd - pos;
} else if (pos + maxHoleDuration < start) {
bufferStartNext = start;
break;
}
}
return {
len: bufferLen,
start: bufferStart || 0,
end: bufferEnd || 0,
nextStart: bufferStartNext
};
}
/**
* Safe method to get buffered property.
* SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
*/
;
BufferHelper.getBuffered = function getBuffered(media) {
try {
return media.buffered;
} catch (e) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log('failed to get media.buffered', e);
return noopBuffered;
}
};
return BufferHelper;
}();
/***/ }),
/***/ "./src/utils/cea-608-parser.ts":
/*!*************************************!*\
!*** ./src/utils/cea-608-parser.ts ***!
\*************************************/
/*! exports provided: Row, CaptionScreen, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Row", function() { return Row; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CaptionScreen", function() { return CaptionScreen; });
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/**
*
* This code was ported from the dash.js project at:
* https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
* https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
*
* The original copyright appears below:
*
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2015-2016, DASH Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* 2. Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
*/
var specialCea608CharsCodes = {
0x2a: 0xe1,
// lowercase a, acute accent
0x5c: 0xe9,
// lowercase e, acute accent
0x5e: 0xed,
// lowercase i, acute accent
0x5f: 0xf3,
// lowercase o, acute accent
0x60: 0xfa,
// lowercase u, acute accent
0x7b: 0xe7,
// lowercase c with cedilla
0x7c: 0xf7,
// division symbol
0x7d: 0xd1,
// uppercase N tilde
0x7e: 0xf1,
// lowercase n tilde
0x7f: 0x2588,
// Full block
// THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
// THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
// THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
0x80: 0xae,
// Registered symbol (R)
0x81: 0xb0,
// degree sign
0x82: 0xbd,
// 1/2 symbol
0x83: 0xbf,
// Inverted (open) question mark
0x84: 0x2122,
// Trademark symbol (TM)
0x85: 0xa2,
// Cents symbol
0x86: 0xa3,
// Pounds sterling
0x87: 0x266a,
// Music 8'th note
0x88: 0xe0,
// lowercase a, grave accent
0x89: 0x20,
// transparent space (regular)
0x8a: 0xe8,
// lowercase e, grave accent
0x8b: 0xe2,
// lowercase a, circumflex accent
0x8c: 0xea,
// lowercase e, circumflex accent
0x8d: 0xee,
// lowercase i, circumflex accent
0x8e: 0xf4,
// lowercase o, circumflex accent
0x8f: 0xfb,
// lowercase u, circumflex accent
// THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
// THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
0x90: 0xc1,
// capital letter A with acute
0x91: 0xc9,
// capital letter E with acute
0x92: 0xd3,
// capital letter O with acute
0x93: 0xda,
// capital letter U with acute
0x94: 0xdc,
// capital letter U with diaresis
0x95: 0xfc,
// lowercase letter U with diaeresis
0x96: 0x2018,
// opening single quote
0x97: 0xa1,
// inverted exclamation mark
0x98: 0x2a,
// asterisk
0x99: 0x2019,
// closing single quote
0x9a: 0x2501,
// box drawings heavy horizontal
0x9b: 0xa9,
// copyright sign
0x9c: 0x2120,
// Service mark
0x9d: 0x2022,
// (round) bullet
0x9e: 0x201c,
// Left double quotation mark
0x9f: 0x201d,
// Right double quotation mark
0xa0: 0xc0,
// uppercase A, grave accent
0xa1: 0xc2,
// uppercase A, circumflex
0xa2: 0xc7,
// uppercase C with cedilla
0xa3: 0xc8,
// uppercase E, grave accent
0xa4: 0xca,
// uppercase E, circumflex
0xa5: 0xcb,
// capital letter E with diaresis
0xa6: 0xeb,
// lowercase letter e with diaresis
0xa7: 0xce,
// uppercase I, circumflex
0xa8: 0xcf,
// uppercase I, with diaresis
0xa9: 0xef,
// lowercase i, with diaresis
0xaa: 0xd4,
// uppercase O, circumflex
0xab: 0xd9,
// uppercase U, grave accent
0xac: 0xf9,
// lowercase u, grave accent
0xad: 0xdb,
// uppercase U, circumflex
0xae: 0xab,
// left-pointing double angle quotation mark
0xaf: 0xbb,
// right-pointing double angle quotation mark
// THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
// THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
0xb0: 0xc3,
// Uppercase A, tilde
0xb1: 0xe3,
// Lowercase a, tilde
0xb2: 0xcd,
// Uppercase I, acute accent
0xb3: 0xcc,
// Uppercase I, grave accent
0xb4: 0xec,
// Lowercase i, grave accent
0xb5: 0xd2,
// Uppercase O, grave accent
0xb6: 0xf2,
// Lowercase o, grave accent
0xb7: 0xd5,
// Uppercase O, tilde
0xb8: 0xf5,
// Lowercase o, tilde
0xb9: 0x7b,
// Open curly brace
0xba: 0x7d,
// Closing curly brace
0xbb: 0x5c,
// Backslash
0xbc: 0x5e,
// Caret
0xbd: 0x5f,
// Underscore
0xbe: 0x7c,
// Pipe (vertical line)
0xbf: 0x223c,
// Tilde operator
0xc0: 0xc4,
// Uppercase A, umlaut
0xc1: 0xe4,
// Lowercase A, umlaut
0xc2: 0xd6,
// Uppercase O, umlaut
0xc3: 0xf6,
// Lowercase o, umlaut
0xc4: 0xdf,
// Esszett (sharp S)
0xc5: 0xa5,
// Yen symbol
0xc6: 0xa4,
// Generic currency sign
0xc7: 0x2503,
// Box drawings heavy vertical
0xc8: 0xc5,
// Uppercase A, ring
0xc9: 0xe5,
// Lowercase A, ring
0xca: 0xd8,
// Uppercase O, stroke
0xcb: 0xf8,
// Lowercase o, strok
0xcc: 0x250f,
// Box drawings heavy down and right
0xcd: 0x2513,
// Box drawings heavy down and left
0xce: 0x2517,
// Box drawings heavy up and right
0xcf: 0x251b // Box drawings heavy up and left
};
/**
* Utils
*/
var getCharForByte = function getCharForByte(_byte) {
var charCode = _byte;
if (specialCea608CharsCodes.hasOwnProperty(_byte)) {
charCode = specialCea608CharsCodes[_byte];
}
return String.fromCharCode(charCode);
};
var NR_ROWS = 15;
var NR_COLS = 100; // Tables to look up row from PAC data
var rowsLowCh1 = {
0x11: 1,
0x12: 3,
0x15: 5,
0x16: 7,
0x17: 9,
0x10: 11,
0x13: 12,
0x14: 14
};
var rowsHighCh1 = {
0x11: 2,
0x12: 4,
0x15: 6,
0x16: 8,
0x17: 10,
0x13: 13,
0x14: 15
};
var rowsLowCh2 = {
0x19: 1,
0x1a: 3,
0x1d: 5,
0x1e: 7,
0x1f: 9,
0x18: 11,
0x1b: 12,
0x1c: 14
};
var rowsHighCh2 = {
0x19: 2,
0x1a: 4,
0x1d: 6,
0x1e: 8,
0x1f: 10,
0x1b: 13,
0x1c: 15
};
var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
var VerboseLevel;
(function (VerboseLevel) {
VerboseLevel[VerboseLevel["ERROR"] = 0] = "ERROR";
VerboseLevel[VerboseLevel["TEXT"] = 1] = "TEXT";
VerboseLevel[VerboseLevel["WARNING"] = 2] = "WARNING";
VerboseLevel[VerboseLevel["INFO"] = 2] = "INFO";
VerboseLevel[VerboseLevel["DEBUG"] = 3] = "DEBUG";
VerboseLevel[VerboseLevel["DATA"] = 3] = "DATA";
})(VerboseLevel || (VerboseLevel = {}));
var CaptionsLogger = /*#__PURE__*/function () {
function CaptionsLogger() {
this.time = null;
this.verboseLevel = VerboseLevel.ERROR;
}
var _proto = CaptionsLogger.prototype;
_proto.log = function log(severity, msg) {
if (this.verboseLevel >= severity) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log(this.time + " [" + severity + "] " + msg);
}
};
return CaptionsLogger;
}();
var numArrayToHexArray = function numArrayToHexArray(numArray) {
var hexArray = [];
for (var j = 0; j < numArray.length; j++) {
hexArray.push(numArray[j].toString(16));
}
return hexArray;
};
var PenState = /*#__PURE__*/function () {
function PenState(foreground, underline, italics, background, flash) {
this.foreground = void 0;
this.underline = void 0;
this.italics = void 0;
this.background = void 0;
this.flash = void 0;
this.foreground = foreground || 'white';
this.underline = underline || false;
this.italics = italics || false;
this.background = background || 'black';
this.flash = flash || false;
}
var _proto2 = PenState.prototype;
_proto2.reset = function reset() {
this.foreground = 'white';
this.underline = false;
this.italics = false;
this.background = 'black';
this.flash = false;
};
_proto2.setStyles = function setStyles(styles) {
var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
for (var i = 0; i < attribs.length; i++) {
var style = attribs[i];
if (styles.hasOwnProperty(style)) {
this[style] = styles[style];
}
}
};
_proto2.isDefault = function isDefault() {
return this.foreground === 'white' && !this.underline && !this.italics && this.background === 'black' && !this.flash;
};
_proto2.equals = function equals(other) {
return this.foreground === other.foreground && this.underline === other.underline && this.italics === other.italics && this.background === other.background && this.flash === other.flash;
};
_proto2.copy = function copy(newPenState) {
this.foreground = newPenState.foreground;
this.underline = newPenState.underline;
this.italics = newPenState.italics;
this.background = newPenState.background;
this.flash = newPenState.flash;
};
_proto2.toString = function toString() {
return 'color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics + ', background=' + this.background + ', flash=' + this.flash;
};
return PenState;
}();
/**
* Unicode character with styling and background.
* @constructor
*/
var StyledUnicodeChar = /*#__PURE__*/function () {
function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
this.uchar = void 0;
this.penState = void 0;
this.uchar = uchar || ' '; // unicode character
this.penState = new PenState(foreground, underline, italics, background, flash);
}
var _proto3 = StyledUnicodeChar.prototype;
_proto3.reset = function reset() {
this.uchar = ' ';
this.penState.reset();
};
_proto3.setChar = function setChar(uchar, newPenState) {
this.uchar = uchar;
this.penState.copy(newPenState);
};
_proto3.setPenState = function setPenState(newPenState) {
this.penState.copy(newPenState);
};
_proto3.equals = function equals(other) {
return this.uchar === other.uchar && this.penState.equals(other.penState);
};
_proto3.copy = function copy(newChar) {
this.uchar = newChar.uchar;
this.penState.copy(newChar.penState);
};
_proto3.isEmpty = function isEmpty() {
return this.uchar === ' ' && this.penState.isDefault();
};
return StyledUnicodeChar;
}();
/**
* CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
* @constructor
*/
var Row = /*#__PURE__*/function () {
function Row(logger) {
this.chars = void 0;
this.pos = void 0;
this.currPenState = void 0;
this.cueStartTime = void 0;
this.logger = void 0;
this.chars = [];
for (var i = 0; i < NR_COLS; i++) {
this.chars.push(new StyledUnicodeChar());
}
this.logger = logger;
this.pos = 0;
this.currPenState = new PenState();
}
var _proto4 = Row.prototype;
_proto4.equals = function equals(other) {
var equal = true;
for (var i = 0; i < NR_COLS; i++) {
if (!this.chars[i].equals(other.chars[i])) {
equal = false;
break;
}
}
return equal;
};
_proto4.copy = function copy(other) {
for (var i = 0; i < NR_COLS; i++) {
this.chars[i].copy(other.chars[i]);
}
};
_proto4.isEmpty = function isEmpty() {
var empty = true;
for (var i = 0; i < NR_COLS; i++) {
if (!this.chars[i].isEmpty()) {
empty = false;
break;
}
}
return empty;
}
/**
* Set the cursor to a valid column.
*/
;
_proto4.setCursor = function setCursor(absPos) {
if (this.pos !== absPos) {
this.pos = absPos;
}
if (this.pos < 0) {
this.logger.log(VerboseLevel.DEBUG, 'Negative cursor position ' + this.pos);
this.pos = 0;
} else if (this.pos > NR_COLS) {
this.logger.log(VerboseLevel.DEBUG, 'Too large cursor position ' + this.pos);
this.pos = NR_COLS;
}
}
/**
* Move the cursor relative to current position.
*/
;
_proto4.moveCursor = function moveCursor(relPos) {
var newPos = this.pos + relPos;
if (relPos > 1) {
for (var i = this.pos + 1; i < newPos + 1; i++) {
this.chars[i].setPenState(this.currPenState);
}
}
this.setCursor(newPos);
}
/**
* Backspace, move one step back and clear character.
*/
;
_proto4.backSpace = function backSpace() {
this.moveCursor(-1);
this.chars[this.pos].setChar(' ', this.currPenState);
};
_proto4.insertChar = function insertChar(_byte2) {
if (_byte2 >= 0x90) {
// Extended char
this.backSpace();
}
var _char = getCharForByte(_byte2);
if (this.pos >= NR_COLS) {
this.logger.log(VerboseLevel.ERROR, 'Cannot insert ' + _byte2.toString(16) + ' (' + _char + ') at position ' + this.pos + '. Skipping it!');
return;
}
this.chars[this.pos].setChar(_char, this.currPenState);
this.moveCursor(1);
};
_proto4.clearFromPos = function clearFromPos(startPos) {
var i;
for (i = startPos; i < NR_COLS; i++) {
this.chars[i].reset();
}
};
_proto4.clear = function clear() {
this.clearFromPos(0);
this.pos = 0;
this.currPenState.reset();
};
_proto4.clearToEndOfRow = function clearToEndOfRow() {
this.clearFromPos(this.pos);
};
_proto4.getTextString = function getTextString() {
var chars = [];
var empty = true;
for (var i = 0; i < NR_COLS; i++) {
var _char2 = this.chars[i].uchar;
if (_char2 !== ' ') {
empty = false;
}
chars.push(_char2);
}
if (empty) {
return '';
} else {
return chars.join('');
}
};
_proto4.setPenStyles = function setPenStyles(styles) {
this.currPenState.setStyles(styles);
var currChar = this.chars[this.pos];
currChar.setPenState(this.currPenState);
};
return Row;
}();
/**
* Keep a CEA-608 screen of 32x15 styled characters
* @constructor
*/
var CaptionScreen = /*#__PURE__*/function () {
function CaptionScreen(logger) {
this.rows = void 0;
this.currRow = void 0;
this.nrRollUpRows = void 0;
this.lastOutputScreen = void 0;
this.logger = void 0;
this.rows = [];
for (var i = 0; i < NR_ROWS; i++) {
this.rows.push(new Row(logger));
} // Note that we use zero-based numbering (0-14)
this.logger = logger;
this.currRow = NR_ROWS - 1;
this.nrRollUpRows = null;
this.lastOutputScreen = null;
this.reset();
}
var _proto5 = CaptionScreen.prototype;
_proto5.reset = function reset() {
for (var i = 0; i < NR_ROWS; i++) {
this.rows[i].clear();
}
this.currRow = NR_ROWS - 1;
};
_proto5.equals = function equals(other) {
var equal = true;
for (var i = 0; i < NR_ROWS; i++) {
if (!this.rows[i].equals(other.rows[i])) {
equal = false;
break;
}
}
return equal;
};
_proto5.copy = function copy(other) {
for (var i = 0; i < NR_ROWS; i++) {
this.rows[i].copy(other.rows[i]);
}
};
_proto5.isEmpty = function isEmpty() {
var empty = true;
for (var i = 0; i < NR_ROWS; i++) {
if (!this.rows[i].isEmpty()) {
empty = false;
break;
}
}
return empty;
};
_proto5.backSpace = function backSpace() {
var row = this.rows[this.currRow];
row.backSpace();
};
_proto5.clearToEndOfRow = function clearToEndOfRow() {
var row = this.rows[this.currRow];
row.clearToEndOfRow();
}
/**
* Insert a character (without styling) in the current row.
*/
;
_proto5.insertChar = function insertChar(_char3) {
var row = this.rows[this.currRow];
row.insertChar(_char3);
};
_proto5.setPen = function setPen(styles) {
var row = this.rows[this.currRow];
row.setPenStyles(styles);
};
_proto5.moveCursor = function moveCursor(relPos) {
var row = this.rows[this.currRow];
row.moveCursor(relPos);
};
_proto5.setCursor = function setCursor(absPos) {
this.logger.log(VerboseLevel.INFO, 'setCursor: ' + absPos);
var row = this.rows[this.currRow];
row.setCursor(absPos);
};
_proto5.setPAC = function setPAC(pacData) {
this.logger.log(VerboseLevel.INFO, 'pacData = ' + JSON.stringify(pacData));
var newRow = pacData.row - 1;
if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
newRow = this.nrRollUpRows - 1;
} // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
if (this.nrRollUpRows && this.currRow !== newRow) {
// clear all rows first
for (var i = 0; i < NR_ROWS; i++) {
this.rows[i].clear();
} // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
// topRowIndex - the start of rows to copy (inclusive index)
var topRowIndex = this.currRow + 1 - this.nrRollUpRows; // We only copy if the last position was already shown.
// We use the cueStartTime value to check this.
var lastOutputScreen = this.lastOutputScreen;
if (lastOutputScreen) {
var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
var time = this.logger.time;
if (prevLineTime && time !== null && prevLineTime < time) {
for (var _i = 0; _i < this.nrRollUpRows; _i++) {
this.rows[newRow - this.nrRollUpRows + _i + 1].copy(lastOutputScreen.rows[topRowIndex + _i]);
}
}
}
}
this.currRow = newRow;
var row = this.rows[this.currRow];
if (pacData.indent !== null) {
var indent = pacData.indent;
var prevPos = Math.max(indent - 1, 0);
row.setCursor(pacData.indent);
pacData.color = row.chars[prevPos].penState.foreground;
}
var styles = {
foreground: pacData.color,
underline: pacData.underline,
italics: pacData.italics,
background: 'black',
flash: false
};
this.setPen(styles);
}
/**
* Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
*/
;
_proto5.setBkgData = function setBkgData(bkgData) {
this.logger.log(VerboseLevel.INFO, 'bkgData = ' + JSON.stringify(bkgData));
this.backSpace();
this.setPen(bkgData);
this.insertChar(0x20); // Space
};
_proto5.setRollUpRows = function setRollUpRows(nrRows) {
this.nrRollUpRows = nrRows;
};
_proto5.rollUp = function rollUp() {
if (this.nrRollUpRows === null) {
this.logger.log(VerboseLevel.DEBUG, 'roll_up but nrRollUpRows not set yet');
return; // Not properly setup
}
this.logger.log(VerboseLevel.TEXT, this.getDisplayText());
var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
var topRow = this.rows.splice(topRowIndex, 1)[0];
topRow.clear();
this.rows.splice(this.currRow, 0, topRow);
this.logger.log(VerboseLevel.INFO, 'Rolling up'); // this.logger.log(VerboseLevel.TEXT, this.get_display_text())
}
/**
* Get all non-empty rows with as unicode text.
*/
;
_proto5.getDisplayText = function getDisplayText(asOneRow) {
asOneRow = asOneRow || false;
var displayText = [];
var text = '';
var rowNr = -1;
for (var i = 0; i < NR_ROWS; i++) {
var rowText = this.rows[i].getTextString();
if (rowText) {
rowNr = i + 1;
if (asOneRow) {
displayText.push('Row ' + rowNr + ": '" + rowText + "'");
} else {
displayText.push(rowText.trim());
}
}
}
if (displayText.length > 0) {
if (asOneRow) {
text = '[' + displayText.join(' | ') + ']';
} else {
text = displayText.join('\n');
}
}
return text;
};
_proto5.getTextAndFormat = function getTextAndFormat() {
return this.rows;
};
return CaptionScreen;
}(); // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
var Cea608Channel = /*#__PURE__*/function () {
function Cea608Channel(channelNumber, outputFilter, logger) {
this.chNr = void 0;
this.outputFilter = void 0;
this.mode = void 0;
this.verbose = void 0;
this.displayedMemory = void 0;
this.nonDisplayedMemory = void 0;
this.lastOutputScreen = void 0;
this.currRollUpRow = void 0;
this.writeScreen = void 0;
this.cueStartTime = void 0;
this.logger = void 0;
this.chNr = channelNumber;
this.outputFilter = outputFilter;
this.mode = null;
this.verbose = 0;
this.displayedMemory = new CaptionScreen(logger);
this.nonDisplayedMemory = new CaptionScreen(logger);
this.lastOutputScreen = new CaptionScreen(logger);
this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
this.writeScreen = this.displayedMemory;
this.mode = null;
this.cueStartTime = null; // Keeps track of where a cue started.
this.logger = logger;
}
var _proto6 = Cea608Channel.prototype;
_proto6.reset = function reset() {
this.mode = null;
this.displayedMemory.reset();
this.nonDisplayedMemory.reset();
this.lastOutputScreen.reset();
this.outputFilter.reset();
this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
this.writeScreen = this.displayedMemory;
this.mode = null;
this.cueStartTime = null;
};
_proto6.getHandler = function getHandler() {
return this.outputFilter;
};
_proto6.setHandler = function setHandler(newHandler) {
this.outputFilter = newHandler;
};
_proto6.setPAC = function setPAC(pacData) {
this.writeScreen.setPAC(pacData);
};
_proto6.setBkgData = function setBkgData(bkgData) {
this.writeScreen.setBkgData(bkgData);
};
_proto6.setMode = function setMode(newMode) {
if (newMode === this.mode) {
return;
}
this.mode = newMode;
this.logger.log(VerboseLevel.INFO, 'MODE=' + newMode);
if (this.mode === 'MODE_POP-ON') {
this.writeScreen = this.nonDisplayedMemory;
} else {
this.writeScreen = this.displayedMemory;
this.writeScreen.reset();
}
if (this.mode !== 'MODE_ROLL-UP') {
this.displayedMemory.nrRollUpRows = null;
this.nonDisplayedMemory.nrRollUpRows = null;
}
this.mode = newMode;
};
_proto6.insertChars = function insertChars(chars) {
for (var i = 0; i < chars.length; i++) {
this.writeScreen.insertChar(chars[i]);
}
var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
this.logger.log(VerboseLevel.INFO, screen + ': ' + this.writeScreen.getDisplayText(true));
if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
this.logger.log(VerboseLevel.TEXT, 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
this.outputDataUpdate();
}
};
_proto6.ccRCL = function ccRCL() {
// Resume Caption Loading (switch mode to Pop On)
this.logger.log(VerboseLevel.INFO, 'RCL - Resume Caption Loading');
this.setMode('MODE_POP-ON');
};
_proto6.ccBS = function ccBS() {
// BackSpace
this.logger.log(VerboseLevel.INFO, 'BS - BackSpace');
if (this.mode === 'MODE_TEXT') {
return;
}
this.writeScreen.backSpace();
if (this.writeScreen === this.displayedMemory) {
this.outputDataUpdate();
}
};
_proto6.ccAOF = function ccAOF() {// Reserved (formerly Alarm Off)
};
_proto6.ccAON = function ccAON() {// Reserved (formerly Alarm On)
};
_proto6.ccDER = function ccDER() {
// Delete to End of Row
this.logger.log(VerboseLevel.INFO, 'DER- Delete to End of Row');
this.writeScreen.clearToEndOfRow();
this.outputDataUpdate();
};
_proto6.ccRU = function ccRU(nrRows) {
// Roll-Up Captions-2,3,or 4 Rows
this.logger.log(VerboseLevel.INFO, 'RU(' + nrRows + ') - Roll Up');
this.writeScreen = this.displayedMemory;
this.setMode('MODE_ROLL-UP');
this.writeScreen.setRollUpRows(nrRows);
};
_proto6.ccFON = function ccFON() {
// Flash On
this.logger.log(VerboseLevel.INFO, 'FON - Flash On');
this.writeScreen.setPen({
flash: true
});
};
_proto6.ccRDC = function ccRDC() {
// Resume Direct Captioning (switch mode to PaintOn)
this.logger.log(VerboseLevel.INFO, 'RDC - Resume Direct Captioning');
this.setMode('MODE_PAINT-ON');
};
_proto6.ccTR = function ccTR() {
// Text Restart in text mode (not supported, however)
this.logger.log(VerboseLevel.INFO, 'TR');
this.setMode('MODE_TEXT');
};
_proto6.ccRTD = function ccRTD() {
// Resume Text Display in Text mode (not supported, however)
this.logger.log(VerboseLevel.INFO, 'RTD');
this.setMode('MODE_TEXT');
};
_proto6.ccEDM = function ccEDM() {
// Erase Displayed Memory
this.logger.log(VerboseLevel.INFO, 'EDM - Erase Displayed Memory');
this.displayedMemory.reset();
this.outputDataUpdate(true);
};
_proto6.ccCR = function ccCR() {
// Carriage Return
this.logger.log(VerboseLevel.INFO, 'CR - Carriage Return');
this.writeScreen.rollUp();
this.outputDataUpdate(true);
};
_proto6.ccENM = function ccENM() {
// Erase Non-Displayed Memory
this.logger.log(VerboseLevel.INFO, 'ENM - Erase Non-displayed Memory');
this.nonDisplayedMemory.reset();
};
_proto6.ccEOC = function ccEOC() {
// End of Caption (Flip Memories)
this.logger.log(VerboseLevel.INFO, 'EOC - End Of Caption');
if (this.mode === 'MODE_POP-ON') {
var tmp = this.displayedMemory;
this.displayedMemory = this.nonDisplayedMemory;
this.nonDisplayedMemory = tmp;
this.writeScreen = this.nonDisplayedMemory;
this.logger.log(VerboseLevel.TEXT, 'DISP: ' + this.displayedMemory.getDisplayText());
}
this.outputDataUpdate(true);
};
_proto6.ccTO = function ccTO(nrCols) {
// Tab Offset 1,2, or 3 columns
this.logger.log(VerboseLevel.INFO, 'TO(' + nrCols + ') - Tab Offset');
this.writeScreen.moveCursor(nrCols);
};
_proto6.ccMIDROW = function ccMIDROW(secondByte) {
// Parse MIDROW command
var styles = {
flash: false
};
styles.underline = secondByte % 2 === 1;
styles.italics = secondByte >= 0x2e;
if (!styles.italics) {
var colorIndex = Math.floor(secondByte / 2) - 0x10;
var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
styles.foreground = colors[colorIndex];
} else {
styles.foreground = 'white';
}
this.logger.log(VerboseLevel.INFO, 'MIDROW: ' + JSON.stringify(styles));
this.writeScreen.setPen(styles);
};
_proto6.outputDataUpdate = function outputDataUpdate(dispatch) {
if (dispatch === void 0) {
dispatch = false;
}
var time = this.logger.time;
if (time === null) {
return;
}
if (this.outputFilter) {
if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {
// Start of a new cue
this.cueStartTime = time;
} else {
if (!this.displayedMemory.equals(this.lastOutputScreen)) {
this.outputFilter.newCue(this.cueStartTime, time, this.lastOutputScreen);
if (dispatch && this.outputFilter.dispatchCue) {
this.outputFilter.dispatchCue();
}
this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;
}
}
this.lastOutputScreen.copy(this.displayedMemory);
}
};
_proto6.cueSplitAtTime = function cueSplitAtTime(t) {
if (this.outputFilter) {
if (!this.displayedMemory.isEmpty()) {
if (this.outputFilter.newCue) {
this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
}
this.cueStartTime = t;
}
}
};
return Cea608Channel;
}();
var Cea608Parser = /*#__PURE__*/function () {
function Cea608Parser(field, out1, out2) {
this.channels = void 0;
this.currentChannel = 0;
this.cmdHistory = void 0;
this.logger = void 0;
var logger = new CaptionsLogger();
this.channels = [null, new Cea608Channel(field, out1, logger), new Cea608Channel(field + 1, out2, logger)];
this.cmdHistory = createCmdHistory();
this.logger = logger;
}
var _proto7 = Cea608Parser.prototype;
_proto7.getHandler = function getHandler(channel) {
return this.channels[channel].getHandler();
};
_proto7.setHandler = function setHandler(channel, newHandler) {
this.channels[channel].setHandler(newHandler);
}
/**
* Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
*/
;
_proto7.addData = function addData(time, byteList) {
var cmdFound;
var a;
var b;
var charsFound = false;
this.logger.time = time;
for (var i = 0; i < byteList.length; i += 2) {
a = byteList[i] & 0x7f;
b = byteList[i + 1] & 0x7f;
if (a === 0 && b === 0) {
continue;
} else {
this.logger.log(VerboseLevel.DATA, '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
}
cmdFound = this.parseCmd(a, b);
if (!cmdFound) {
cmdFound = this.parseMidrow(a, b);
}
if (!cmdFound) {
cmdFound = this.parsePAC(a, b);
}
if (!cmdFound) {
cmdFound = this.parseBackgroundAttributes(a, b);
}
if (!cmdFound) {
charsFound = this.parseChars(a, b);
if (charsFound) {
var currChNr = this.currentChannel;
if (currChNr && currChNr > 0) {
var channel = this.channels[currChNr];
channel.insertChars(charsFound);
} else {
this.logger.log(VerboseLevel.WARNING, 'No channel found yet. TEXT-MODE?');
}
}
}
if (!cmdFound && !charsFound) {
this.logger.log(VerboseLevel.WARNING, "Couldn't parse cleaned data " + numArrayToHexArray([a, b]) + ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
}
}
}
/**
* Parse Command.
* @returns {Boolean} Tells if a command was found
*/
;
_proto7.parseCmd = function parseCmd(a, b) {
var cmdHistory = this.cmdHistory;
var cond1 = (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) && b >= 0x20 && b <= 0x2f;
var cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;
if (!(cond1 || cond2)) {
return false;
}
if (hasCmdRepeated(a, b, cmdHistory)) {
setLastCmd(null, null, cmdHistory);
this.logger.log(VerboseLevel.DEBUG, 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
return true;
}
var chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;
var channel = this.channels[chNr];
if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {
if (b === 0x20) {
channel.ccRCL();
} else if (b === 0x21) {
channel.ccBS();
} else if (b === 0x22) {
channel.ccAOF();
} else if (b === 0x23) {
channel.ccAON();
} else if (b === 0x24) {
channel.ccDER();
} else if (b === 0x25) {
channel.ccRU(2);
} else if (b === 0x26) {
channel.ccRU(3);
} else if (b === 0x27) {
channel.ccRU(4);
} else if (b === 0x28) {
channel.ccFON();
} else if (b === 0x29) {
channel.ccRDC();
} else if (b === 0x2a) {
channel.ccTR();
} else if (b === 0x2b) {
channel.ccRTD();
} else if (b === 0x2c) {
channel.ccEDM();
} else if (b === 0x2d) {
channel.ccCR();
} else if (b === 0x2e) {
channel.ccENM();
} else if (b === 0x2f) {
channel.ccEOC();
}
} else {
// a == 0x17 || a == 0x1F
channel.ccTO(b - 0x20);
}
setLastCmd(a, b, cmdHistory);
this.currentChannel = chNr;
return true;
}
/**
* Parse midrow styling command
* @returns {Boolean}
*/
;
_proto7.parseMidrow = function parseMidrow(a, b) {
var chNr = 0;
if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {
if (a === 0x11) {
chNr = 1;
} else {
chNr = 2;
}
if (chNr !== this.currentChannel) {
this.logger.log(VerboseLevel.ERROR, 'Mismatch channel in midrow parsing');
return false;
}
var channel = this.channels[chNr];
if (!channel) {
return false;
}
channel.ccMIDROW(b);
this.logger.log(VerboseLevel.DEBUG, 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
return true;
}
return false;
}
/**
* Parse Preable Access Codes (Table 53).
* @returns {Boolean} Tells if PAC found
*/
;
_proto7.parsePAC = function parsePAC(a, b) {
var row;
var cmdHistory = this.cmdHistory;
var case1 = (a >= 0x11 && a <= 0x17 || a >= 0x19 && a <= 0x1f) && b >= 0x40 && b <= 0x7f;
var case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;
if (!(case1 || case2)) {
return false;
}
if (hasCmdRepeated(a, b, cmdHistory)) {
setLastCmd(null, null, cmdHistory);
return true; // Repeated commands are dropped (once)
}
var chNr = a <= 0x17 ? 1 : 2;
if (b >= 0x40 && b <= 0x5f) {
row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];
} else {
// 0x60 <= b <= 0x7F
row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];
}
var channel = this.channels[chNr];
if (!channel) {
return false;
}
channel.setPAC(this.interpretPAC(row, b));
setLastCmd(a, b, cmdHistory);
this.currentChannel = chNr;
return true;
}
/**
* Interpret the second byte of the pac, and return the information.
* @returns {Object} pacData with style parameters.
*/
;
_proto7.interpretPAC = function interpretPAC(row, _byte3) {
var pacIndex;
var pacData = {
color: null,
italics: false,
indent: null,
underline: false,
row: row
};
if (_byte3 > 0x5f) {
pacIndex = _byte3 - 0x60;
} else {
pacIndex = _byte3 - 0x40;
}
pacData.underline = (pacIndex & 1) === 1;
if (pacIndex <= 0xd) {
pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
} else if (pacIndex <= 0xf) {
pacData.italics = true;
pacData.color = 'white';
} else {
pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;
}
return pacData; // Note that row has zero offset. The spec uses 1.
}
/**
* Parse characters.
* @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
*/
;
_proto7.parseChars = function parseChars(a, b) {
var channelNr;
var charCodes = null;
var charCode1 = null;
if (a >= 0x19) {
channelNr = 2;
charCode1 = a - 8;
} else {
channelNr = 1;
charCode1 = a;
}
if (charCode1 >= 0x11 && charCode1 <= 0x13) {
// Special character
var oneCode;
if (charCode1 === 0x11) {
oneCode = b + 0x50;
} else if (charCode1 === 0x12) {
oneCode = b + 0x70;
} else {
oneCode = b + 0x90;
}
this.logger.log(VerboseLevel.INFO, "Special char '" + getCharForByte(oneCode) + "' in channel " + channelNr);
charCodes = [oneCode];
} else if (a >= 0x20 && a <= 0x7f) {
charCodes = b === 0 ? [a] : [a, b];
}
if (charCodes) {
var hexCodes = numArrayToHexArray(charCodes);
this.logger.log(VerboseLevel.DEBUG, 'Char codes = ' + hexCodes.join(','));
setLastCmd(a, b, this.cmdHistory);
}
return charCodes;
}
/**
* Parse extended background attributes as well as new foreground color black.
* @returns {Boolean} Tells if background attributes are found
*/
;
_proto7.parseBackgroundAttributes = function parseBackgroundAttributes(a, b) {
var case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;
var case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;
if (!(case1 || case2)) {
return false;
}
var index;
var bkgData = {};
if (a === 0x10 || a === 0x18) {
index = Math.floor((b - 0x20) / 2);
bkgData.background = backgroundColors[index];
if (b % 2 === 1) {
bkgData.background = bkgData.background + '_semi';
}
} else if (b === 0x2d) {
bkgData.background = 'transparent';
} else {
bkgData.foreground = 'black';
if (b === 0x2f) {
bkgData.underline = true;
}
}
var chNr = a <= 0x17 ? 1 : 2;
var channel = this.channels[chNr];
channel.setBkgData(bkgData);
setLastCmd(a, b, this.cmdHistory);
return true;
}
/**
* Reset state of parser and its channels.
*/
;
_proto7.reset = function reset() {
for (var i = 0; i < Object.keys(this.channels).length; i++) {
var channel = this.channels[i];
if (channel) {
channel.reset();
}
}
this.cmdHistory = createCmdHistory();
}
/**
* Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
*/
;
_proto7.cueSplitAtTime = function cueSplitAtTime(t) {
for (var i = 0; i < this.channels.length; i++) {
var channel = this.channels[i];
if (channel) {
channel.cueSplitAtTime(t);
}
}
};
return Cea608Parser;
}();
function setLastCmd(a, b, cmdHistory) {
cmdHistory.a = a;
cmdHistory.b = b;
}
function hasCmdRepeated(a, b, cmdHistory) {
return cmdHistory.a === a && cmdHistory.b === b;
}
function createCmdHistory() {
return {
a: null,
b: null
};
}
/* harmony default export */ __webpack_exports__["default"] = (Cea608Parser);
/***/ }),
/***/ "./src/utils/codecs.ts":
/*!*****************************!*\
!*** ./src/utils/codecs.ts ***!
\*****************************/
/*! exports provided: isCodecType, isCodecSupportedInMp4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecType", function() { return isCodecType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isCodecSupportedInMp4", function() { return isCodecSupportedInMp4; });
// from http://mp4ra.org/codecs.html
var sampleEntryCodesISO = {
audio: {
a3ds: true,
'ac-3': true,
'ac-4': true,
alac: true,
alaw: true,
dra1: true,
'dts+': true,
'dts-': true,
dtsc: true,
dtse: true,
dtsh: true,
'ec-3': true,
enca: true,
g719: true,
g726: true,
m4ae: true,
mha1: true,
mha2: true,
mhm1: true,
mhm2: true,
mlpa: true,
mp4a: true,
'raw ': true,
Opus: true,
samr: true,
sawb: true,
sawp: true,
sevc: true,
sqcp: true,
ssmv: true,
twos: true,
ulaw: true
},
video: {
avc1: true,
avc2: true,
avc3: true,
avc4: true,
avcp: true,
av01: true,
drac: true,
dvav: true,
dvhe: true,
encv: true,
hev1: true,
hvc1: true,
mjp2: true,
mp4v: true,
mvc1: true,
mvc2: true,
mvc3: true,
mvc4: true,
resv: true,
rv60: true,
s263: true,
svc1: true,
svc2: true,
'vc-1': true,
vp08: true,
vp09: true
},
text: {
stpp: true,
wvtt: true
}
};
function isCodecType(codec, type) {
var typeCodes = sampleEntryCodesISO[type];
return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
}
function isCodecSupportedInMp4(codec, type) {
return MediaSource.isTypeSupported((type || 'video') + "/mp4;codecs=\"" + codec + "\"");
}
/***/ }),
/***/ "./src/utils/cues.ts":
/*!***************************!*\
!*** ./src/utils/cues.ts ***!
\***************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts");
/* harmony import */ var _webvtt_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./webvtt-parser */ "./src/utils/webvtt-parser.ts");
/* harmony import */ var _texttrack_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./texttrack-utils */ "./src/utils/texttrack-utils.ts");
var WHITESPACE_CHAR = /\s/;
var Cues = {
newCue: function newCue(track, startTime, endTime, captionScreen) {
var result = [];
var row; // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers
var cue;
var indenting;
var indent;
var text;
var Cue = self.VTTCue || self.TextTrackCue;
for (var r = 0; r < captionScreen.rows.length; r++) {
row = captionScreen.rows[r];
indenting = true;
indent = 0;
text = '';
if (!row.isEmpty()) {
for (var c = 0; c < row.chars.length; c++) {
if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {
indent++;
} else {
text += row.chars[c].uchar;
indenting = false;
}
} // To be used for cleaning-up orphaned roll-up captions
row.cueStartTime = startTime; // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
if (startTime === endTime) {
endTime += 0.0001;
}
if (indent >= 16) {
indent--;
} else {
indent++;
}
var cueText = Object(_vttparser__WEBPACK_IMPORTED_MODULE_0__["fixLineBreaks"])(text.trim());
var id = Object(_webvtt_parser__WEBPACK_IMPORTED_MODULE_1__["generateCueId"])(startTime, endTime, cueText); // If this cue already exists in the track do not push it
if (!track || !track.cues || !track.cues.getCueById(id)) {
cue = new Cue(startTime, endTime, cueText);
cue.id = id;
cue.line = r + 1;
cue.align = 'left'; // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code)
// https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608
// Firefox throws an exception and captions break with out of bounds 0-100 values
cue.position = 10 + Math.min(80, Math.floor(indent * 8 / 32) * 10);
result.push(cue);
}
}
}
if (track && result.length) {
// Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome
result.sort(function (cueA, cueB) {
if (cueA.line === 'auto' || cueB.line === 'auto') {
return 0;
}
if (cueA.line > 8 && cueB.line > 8) {
return cueB.line - cueA.line;
}
return cueA.line - cueB.line;
});
result.forEach(function (cue) {
return Object(_texttrack_utils__WEBPACK_IMPORTED_MODULE_2__["addCueToTrack"])(track, cue);
});
}
return result;
}
};
/* harmony default export */ __webpack_exports__["default"] = (Cues);
/***/ }),
/***/ "./src/utils/discontinuities.ts":
/*!**************************************!*\
!*** ./src/utils/discontinuities.ts ***!
\**************************************/
/*! exports provided: findFirstFragWithCC, shouldAlignOnDiscontinuities, findDiscontinuousReferenceFrag, adjustSlidingStart, alignStream, alignPDT */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findFirstFragWithCC", function() { return findFirstFragWithCC; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "shouldAlignOnDiscontinuities", function() { return shouldAlignOnDiscontinuities; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findDiscontinuousReferenceFrag", function() { return findDiscontinuousReferenceFrag; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "adjustSlidingStart", function() { return adjustSlidingStart; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignStream", function() { return alignStream; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "alignPDT", function() { return alignPDT; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
/* harmony import */ var _controller_level_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../controller/level-helper */ "./src/controller/level-helper.ts");
function findFirstFragWithCC(fragments, cc) {
var firstFrag = null;
for (var i = 0, len = fragments.length; i < len; i++) {
var currentFrag = fragments[i];
if (currentFrag && currentFrag.cc === cc) {
firstFrag = currentFrag;
break;
}
}
return firstFrag;
}
function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
if (lastLevel.details) {
if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
return true;
}
}
return false;
} // Find the first frag in the previous level which matches the CC of the first frag of the new level
function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
var prevFrags = prevDetails.fragments;
var curFrags = curDetails.fragments;
if (!curFrags.length || !prevFrags.length) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No fragments to align');
return;
}
var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log('No frag in previous level to align on');
return;
}
return prevStartFrag;
}
function adjustFragmentStart(frag, sliding) {
if (frag) {
var start = frag.start + sliding;
frag.start = frag.startPTS = start;
frag.endPTS = start + frag.duration;
}
}
function adjustSlidingStart(sliding, details) {
// Update segments
var fragments = details.fragments;
for (var i = 0, len = fragments.length; i < len; i++) {
adjustFragmentStart(fragments[i], sliding);
} // Update LL-HLS parts at the end of the playlist
if (details.fragmentHint) {
adjustFragmentStart(details.fragmentHint, sliding);
}
details.alignedSliding = true;
}
/**
* Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
* contiguous stream with the last fragments.
* The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
* download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
* and an extra download.
* @param lastFrag
* @param lastLevel
* @param details
*/
function alignStream(lastFrag, lastLevel, details) {
if (!lastLevel) {
return;
}
alignDiscontinuities(lastFrag, details, lastLevel);
if (!details.alignedSliding && lastLevel.details) {
// If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
// Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
// discontinuity sequence.
alignPDT(details, lastLevel.details);
}
if (!details.alignedSliding && lastLevel.details && !details.skippedSegments) {
// Try to align on sn so that we pick a better start fragment.
// Do not perform this on playlists with delta updates as this is only to align levels on switch
// and adjustSliding only adjusts fragments after skippedSegments.
Object(_controller_level_helper__WEBPACK_IMPORTED_MODULE_2__["adjustSliding"])(lastLevel.details, details);
}
}
/**
* Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
* discontinuity sequence.
* @param lastFrag - The last Fragment which shares the same discontinuity sequence
* @param lastLevel - The details of the last loaded level
* @param details - The details of the new level
*/
function alignDiscontinuities(lastFrag, details, lastLevel) {
if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
if (referenceFrag && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(referenceFrag.start)) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using last level due to CC increase within current level " + details.url);
adjustSlidingStart(referenceFrag.start, details);
}
}
}
/**
* Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
* @param details - The details of the new level
* @param lastDetails - The details of the last loaded level
*/
function alignPDT(details, lastDetails) {
// This check protects the unsafe "!" usage below for null program date time access.
if (!lastDetails.fragments.length || !details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
return;
} // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
// and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
// then we can deduce that playlist B sliding is 1000+8 = 1008s
var lastPDT = lastDetails.fragments[0].programDateTime; // hasProgramDateTime check above makes this safe.
var newPDT = details.fragments[0].programDateTime; // date diff is in ms. frag.start is in seconds
var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
if (sliding && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(sliding)) {
_logger__WEBPACK_IMPORTED_MODULE_1__["logger"].log("Adjusting PTS using programDateTime delta " + (newPDT - lastPDT) + "ms, sliding:" + sliding.toFixed(3) + " " + details.url + " ");
adjustSlidingStart(sliding, details);
}
}
/***/ }),
/***/ "./src/utils/ewma-bandwidth-estimator.ts":
/*!***********************************************!*\
!*** ./src/utils/ewma-bandwidth-estimator.ts ***!
\***********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_ewma__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/ewma */ "./src/utils/ewma.ts");
/*
* EWMA Bandwidth Estimator
* - heavily inspired from shaka-player
* Tracks bandwidth samples and estimates available bandwidth.
* Based on the minimum of two exponentially-weighted moving averages with
* different half-lives.
*/
var EwmaBandWidthEstimator = /*#__PURE__*/function () {
function EwmaBandWidthEstimator(slow, fast, defaultEstimate) {
this.defaultEstimate_ = void 0;
this.minWeight_ = void 0;
this.minDelayMs_ = void 0;
this.slow_ = void 0;
this.fast_ = void 0;
this.defaultEstimate_ = defaultEstimate;
this.minWeight_ = 0.001;
this.minDelayMs_ = 50;
this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow);
this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast);
}
var _proto = EwmaBandWidthEstimator.prototype;
_proto.update = function update(slow, fast) {
var slow_ = this.slow_,
fast_ = this.fast_;
if (this.slow_.halfLife !== slow) {
this.slow_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](slow, slow_.getEstimate(), slow_.getTotalWeight());
}
if (this.fast_.halfLife !== fast) {
this.fast_ = new _utils_ewma__WEBPACK_IMPORTED_MODULE_0__["default"](fast, fast_.getEstimate(), fast_.getTotalWeight());
}
};
_proto.sample = function sample(durationMs, numBytes) {
durationMs = Math.max(durationMs, this.minDelayMs_);
var numBits = 8 * numBytes; // weight is duration in seconds
var durationS = durationMs / 1000; // value is bandwidth in bits/s
var bandwidthInBps = numBits / durationS;
this.fast_.sample(durationS, bandwidthInBps);
this.slow_.sample(durationS, bandwidthInBps);
};
_proto.canEstimate = function canEstimate() {
var fast = this.fast_;
return fast && fast.getTotalWeight() >= this.minWeight_;
};
_proto.getEstimate = function getEstimate() {
if (this.canEstimate()) {
// console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
// console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
// Take the minimum of these two estimates. This should have the effect of
// adapting down quickly, but up more slowly.
return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
} else {
return this.defaultEstimate_;
}
};
_proto.destroy = function destroy() {};
return EwmaBandWidthEstimator;
}();
/* harmony default export */ __webpack_exports__["default"] = (EwmaBandWidthEstimator);
/***/ }),
/***/ "./src/utils/ewma.ts":
/*!***************************!*\
!*** ./src/utils/ewma.ts ***!
\***************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/*
* compute an Exponential Weighted moving average
* - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
* - heavily inspired from shaka-player
*/
var EWMA = /*#__PURE__*/function () {
// About half of the estimated value will be from the last |halfLife| samples by weight.
function EWMA(halfLife, estimate, weight) {
if (estimate === void 0) {
estimate = 0;
}
if (weight === void 0) {
weight = 0;
}
this.halfLife = void 0;
this.alpha_ = void 0;
this.estimate_ = void 0;
this.totalWeight_ = void 0;
this.halfLife = halfLife; // Larger values of alpha expire historical data more slowly.
this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
this.estimate_ = estimate;
this.totalWeight_ = weight;
}
var _proto = EWMA.prototype;
_proto.sample = function sample(weight, value) {
var adjAlpha = Math.pow(this.alpha_, weight);
this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
this.totalWeight_ += weight;
};
_proto.getTotalWeight = function getTotalWeight() {
return this.totalWeight_;
};
_proto.getEstimate = function getEstimate() {
if (this.alpha_) {
var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
if (zeroFactor) {
return this.estimate_ / zeroFactor;
}
}
return this.estimate_;
};
return EWMA;
}();
/* harmony default export */ __webpack_exports__["default"] = (EWMA);
/***/ }),
/***/ "./src/utils/fetch-loader.ts":
/*!***********************************!*\
!*** ./src/utils/fetch-loader.ts ***!
\***********************************/
/*! exports provided: fetchSupported, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fetchSupported", function() { return fetchSupported; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts");
/* harmony import */ var _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/chunk-cache */ "./src/demux/chunk-cache.ts");
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function fetchSupported() {
if ( // @ts-ignore
self.fetch && self.AbortController && self.ReadableStream && self.Request) {
try {
new self.ReadableStream({}); // eslint-disable-line no-new
return true;
} catch (e) {
/* noop */
}
}
return false;
}
var FetchLoader = /*#__PURE__*/function () {
function FetchLoader(config
/* HlsConfig */
) {
this.fetchSetup = void 0;
this.requestTimeout = void 0;
this.request = void 0;
this.response = void 0;
this.controller = void 0;
this.context = void 0;
this.config = null;
this.callbacks = null;
this.stats = void 0;
this.loader = null;
this.fetchSetup = config.fetchSetup || getRequest;
this.controller = new self.AbortController();
this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"]();
}
var _proto = FetchLoader.prototype;
_proto.destroy = function destroy() {
this.loader = this.callbacks = null;
this.abortInternal();
};
_proto.abortInternal = function abortInternal() {
var response = this.response;
if (!response || !response.ok) {
this.stats.aborted = true;
this.controller.abort();
}
};
_proto.abort = function abort() {
var _this$callbacks;
this.abortInternal();
if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {
this.callbacks.onAbort(this.stats, this.context, this.response);
}
};
_proto.load = function load(context, config, callbacks) {
var _this = this;
var stats = this.stats;
if (stats.loading.start) {
throw new Error('Loader can only be used once.');
}
stats.loading.start = self.performance.now();
var initParams = getRequestParameters(context, this.controller.signal);
var onProgress = callbacks.onProgress;
var isArrayBuffer = context.responseType === 'arraybuffer';
var LENGTH = isArrayBuffer ? 'byteLength' : 'length';
this.context = context;
this.config = config;
this.callbacks = callbacks;
this.request = this.fetchSetup(context, initParams);
self.clearTimeout(this.requestTimeout);
this.requestTimeout = self.setTimeout(function () {
_this.abortInternal();
callbacks.onTimeout(stats, context, _this.response);
}, config.timeout);
self.fetch(this.request).then(function (response) {
_this.response = _this.loader = response;
if (!response.ok) {
var status = response.status,
statusText = response.statusText;
throw new FetchError(statusText || 'fetch, bad network response', status, response);
}
stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
stats.total = parseInt(response.headers.get('Content-Length') || '0');
if (onProgress && Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) {
return _this.loadProgressively(response, stats, context, config.highWaterMark, onProgress);
}
if (isArrayBuffer) {
return response.arrayBuffer();
}
return response.text();
}).then(function (responseData) {
var response = _this.response;
self.clearTimeout(_this.requestTimeout);
stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
stats.loaded = stats.total = responseData[LENGTH];
var loaderResponse = {
url: response.url,
data: responseData
};
if (onProgress && !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(config.highWaterMark)) {
onProgress(stats, context, responseData, response);
}
callbacks.onSuccess(loaderResponse, stats, context, response);
}).catch(function (error) {
self.clearTimeout(_this.requestTimeout);
if (stats.aborted) {
return;
} // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior
var code = error.code || 0;
callbacks.onError({
code: code,
text: error.message
}, context, error.details);
});
};
_proto.getCacheAge = function getCacheAge() {
var result = null;
if (this.response) {
var ageHeader = this.response.headers.get('age');
result = ageHeader ? parseFloat(ageHeader) : null;
}
return result;
};
_proto.loadProgressively = function loadProgressively(response, stats, context, highWaterMark, onProgress) {
if (highWaterMark === void 0) {
highWaterMark = 0;
}
var chunkCache = new _demux_chunk_cache__WEBPACK_IMPORTED_MODULE_2__["default"]();
var reader = response.body.getReader();
var pump = function pump() {
return reader.read().then(function (data) {
if (data.done) {
if (chunkCache.dataLength) {
onProgress(stats, context, chunkCache.flush(), response);
}
return Promise.resolve(new ArrayBuffer(0));
}
var chunk = data.value;
var len = chunk.length;
stats.loaded += len;
if (len < highWaterMark || chunkCache.dataLength) {
// The current chunk is too small to to be emitted or the cache already has data
// Push it to the cache
chunkCache.push(chunk);
if (chunkCache.dataLength >= highWaterMark) {
// flush in order to join the typed arrays
onProgress(stats, context, chunkCache.flush(), response);
}
} else {
// If there's nothing cached already, and the chache is large enough
// just emit the progress event
onProgress(stats, context, chunk, response);
}
return pump();
}).catch(function () {
/* aborted */
return Promise.reject();
});
};
return pump();
};
return FetchLoader;
}();
function getRequestParameters(context, signal) {
var initParams = {
method: 'GET',
mode: 'cors',
credentials: 'same-origin',
signal: signal
};
if (context.rangeEnd) {
initParams.headers = new self.Headers({
Range: 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1)
});
}
return initParams;
}
function getRequest(context, initParams) {
return new self.Request(context.url, initParams);
}
var FetchError = /*#__PURE__*/function (_Error) {
_inheritsLoose(FetchError, _Error);
function FetchError(message, code, details) {
var _this2;
_this2 = _Error.call(this, message) || this;
_this2.code = void 0;
_this2.details = void 0;
_this2.code = code;
_this2.details = details;
return _this2;
}
return FetchError;
}( /*#__PURE__*/_wrapNativeSuper(Error));
/* harmony default export */ __webpack_exports__["default"] = (FetchLoader);
/***/ }),
/***/ "./src/utils/imsc1-ttml-parser.ts":
/*!****************************************!*\
!*** ./src/utils/imsc1-ttml-parser.ts ***!
\****************************************/
/*! exports provided: IMSC1_CODEC, parseIMSC1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IMSC1_CODEC", function() { return IMSC1_CODEC; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseIMSC1", function() { return parseIMSC1; });
/* harmony import */ var _mp4_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mp4-tools */ "./src/utils/mp4-tools.ts");
/* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts");
/* harmony import */ var _vttcue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vttcue */ "./src/utils/vttcue.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _timescale_conversion__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./timescale-conversion */ "./src/utils/timescale-conversion.ts");
/* harmony import */ var _webvtt_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./webvtt-parser */ "./src/utils/webvtt-parser.ts");
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
var IMSC1_CODEC = 'stpp.ttml.im1t'; // Time format: h:m:s:frames(.subframes)
var HMSF_REGEX = /^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/; // Time format: hours, minutes, seconds, milliseconds, frames, ticks
var TIME_UNIT_REGEX = /^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/;
var textAlignToLineAlign = {
left: 'start',
center: 'center',
right: 'end',
start: 'start',
end: 'end'
};
function parseIMSC1(payload, initPTS, timescale, callBack, errorCallBack) {
var results = Object(_mp4_tools__WEBPACK_IMPORTED_MODULE_0__["findBox"])(new Uint8Array(payload), ['mdat']);
if (results.length === 0) {
errorCallBack(new Error('Could not parse IMSC1 mdat'));
return;
}
var mdat = results[0];
var ttml = Object(_demux_id3__WEBPACK_IMPORTED_MODULE_3__["utf8ArrayToStr"])(new Uint8Array(payload, mdat.start, mdat.end - mdat.start));
var syncTime = Object(_timescale_conversion__WEBPACK_IMPORTED_MODULE_4__["toTimescaleFromScale"])(initPTS, 1, timescale);
try {
callBack(parseTTML(ttml, syncTime));
} catch (error) {
errorCallBack(error);
}
}
function parseTTML(ttml, syncTime) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(ttml, 'text/xml');
var tt = xmlDoc.getElementsByTagName('tt')[0];
if (!tt) {
throw new Error('Invalid ttml');
}
var defaultRateInfo = {
frameRate: 30,
subFrameRate: 1,
frameRateMultiplier: 0,
tickRate: 0
};
var rateInfo = Object.keys(defaultRateInfo).reduce(function (result, key) {
result[key] = tt.getAttribute("ttp:" + key) || defaultRateInfo[key];
return result;
}, {});
var trim = tt.getAttribute('xml:space') !== 'preserve';
var styleElements = collectionToDictionary(getElementCollection(tt, 'styling', 'style'));
var regionElements = collectionToDictionary(getElementCollection(tt, 'layout', 'region'));
var cueElements = getElementCollection(tt, 'body', '[begin]');
return [].map.call(cueElements, function (cueElement) {
var cueText = getTextContent(cueElement, trim);
if (!cueText || !cueElement.hasAttribute('begin')) {
return null;
}
var startTime = parseTtmlTime(cueElement.getAttribute('begin'), rateInfo);
var duration = parseTtmlTime(cueElement.getAttribute('dur'), rateInfo);
var endTime = parseTtmlTime(cueElement.getAttribute('end'), rateInfo);
if (startTime === null) {
throw timestampParsingError(cueElement);
}
if (endTime === null) {
if (duration === null) {
throw timestampParsingError(cueElement);
}
endTime = startTime + duration;
}
var cue = new _vttcue__WEBPACK_IMPORTED_MODULE_2__["default"](startTime - syncTime, endTime - syncTime, cueText);
cue.id = Object(_webvtt_parser__WEBPACK_IMPORTED_MODULE_5__["generateCueId"])(cue.startTime, cue.endTime, cue.text);
var region = regionElements[cueElement.getAttribute('region')];
var style = styleElements[cueElement.getAttribute('style')]; // TODO: Add regions to track and cue (origin and extend)
// These values are hard-coded (for now) to simulate region settings in the demo
cue.position = 10;
cue.size = 80; // Apply styles to cue
var styles = getTtmlStyles(region, style);
var textAlign = styles.textAlign;
if (textAlign) {
// cue.positionAlign not settable in FF~2016
var lineAlign = textAlignToLineAlign[textAlign];
if (lineAlign) {
cue.lineAlign = lineAlign;
}
cue.align = textAlign;
}
_extends(cue, styles);
return cue;
}).filter(function (cue) {
return cue !== null;
});
}
function getElementCollection(fromElement, parentName, childName) {
var parent = fromElement.getElementsByTagName(parentName)[0];
if (parent) {
return [].slice.call(parent.querySelectorAll(childName));
}
return [];
}
function collectionToDictionary(elementsWithId) {
return elementsWithId.reduce(function (dict, element) {
var id = element.getAttribute('xml:id');
if (id) {
dict[id] = element;
}
return dict;
}, {});
}
function getTextContent(element, trim) {
return [].slice.call(element.childNodes).reduce(function (str, node, i) {
var _node$childNodes;
if (node.nodeName === 'br' && i) {
return str + '\n';
}
if ((_node$childNodes = node.childNodes) !== null && _node$childNodes !== void 0 && _node$childNodes.length) {
return getTextContent(node, trim);
} else if (trim) {
return str + node.textContent.trim().replace(/\s+/g, ' ');
}
return str + node.textContent;
}, '');
}
function getTtmlStyles(region, style) {
var ttsNs = 'http://www.w3.org/ns/ttml#styling';
var styleAttributes = ['displayAlign', 'textAlign', 'color', 'backgroundColor', 'fontSize', 'fontFamily' // 'fontWeight',
// 'lineHeight',
// 'wrapOption',
// 'fontStyle',
// 'direction',
// 'writingMode'
];
return styleAttributes.reduce(function (styles, name) {
var value = getAttributeNS(style, ttsNs, name) || getAttributeNS(region, ttsNs, name);
if (value) {
styles[name] = value;
}
return styles;
}, {});
}
function getAttributeNS(element, ns, name) {
return element.hasAttributeNS(ns, name) ? element.getAttributeNS(ns, name) : null;
}
function timestampParsingError(node) {
return new Error("Could not parse ttml timestamp " + node);
}
function parseTtmlTime(timeAttributeValue, rateInfo) {
if (!timeAttributeValue) {
return null;
}
var seconds = Object(_vttparser__WEBPACK_IMPORTED_MODULE_1__["parseTimeStamp"])(timeAttributeValue);
if (seconds === null) {
if (HMSF_REGEX.test(timeAttributeValue)) {
seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);
} else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {
seconds = parseTimeUnits(timeAttributeValue, rateInfo);
}
}
return seconds;
}
function parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo) {
var m = HMSF_REGEX.exec(timeAttributeValue);
var frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;
return (m[1] | 0) * 3600 + (m[2] | 0) * 60 + (m[3] | 0) + frames / rateInfo.frameRate;
}
function parseTimeUnits(timeAttributeValue, rateInfo) {
var m = TIME_UNIT_REGEX.exec(timeAttributeValue);
var value = Number(m[1]);
var unit = m[2];
switch (unit) {
case 'h':
return value * 3600;
case 'm':
return value * 60;
case 'ms':
return value * 1000;
case 'f':
return value / rateInfo.frameRate;
case 't':
return value / rateInfo.tickRate;
}
return value;
}
/***/ }),
/***/ "./src/utils/logger.ts":
/*!*****************************!*\
!*** ./src/utils/logger.ts ***!
\*****************************/
/*! exports provided: enableLogs, logger */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableLogs", function() { return enableLogs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logger", function() { return logger; });
var noop = function noop() {};
var fakeLogger = {
trace: noop,
debug: noop,
log: noop,
warn: noop,
info: noop,
error: noop
};
var exportedLogger = fakeLogger; // let lastCallTime;
// function formatMsgWithTimeInfo(type, msg) {
// const now = Date.now();
// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
// lastCallTime = now;
// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
// return msg;
// }
function consolePrintFn(type) {
var func = self.console[type];
if (func) {
return func.bind(self.console, "[" + type + "] >");
}
return noop;
}
function exportLoggerFunctions(debugConfig) {
for (var _len = arguments.length, functions = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
functions[_key - 1] = arguments[_key];
}
functions.forEach(function (type) {
exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
});
}
function enableLogs(debugConfig) {
// check that console is available
if (self.console && debugConfig === true || typeof debugConfig === 'object') {
exportLoggerFunctions(debugConfig, // Remove out from list here to hard-disable a log-level
// 'trace',
'debug', 'log', 'info', 'warn', 'error'); // Some browsers don't allow to use bind on console object anyway
// fallback to default if needed
try {
exportedLogger.log();
} catch (e) {
exportedLogger = fakeLogger;
}
} else {
exportedLogger = fakeLogger;
}
}
var logger = exportedLogger;
/***/ }),
/***/ "./src/utils/mediakeys-helper.ts":
/*!***************************************!*\
!*** ./src/utils/mediakeys-helper.ts ***!
\***************************************/
/*! exports provided: KeySystems, requestMediaKeySystemAccess */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeySystems", function() { return KeySystems; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "requestMediaKeySystemAccess", function() { return requestMediaKeySystemAccess; });
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
*/
var KeySystems;
(function (KeySystems) {
KeySystems["WIDEVINE"] = "com.widevine.alpha";
KeySystems["PLAYREADY"] = "com.microsoft.playready";
})(KeySystems || (KeySystems = {}));
var requestMediaKeySystemAccess = function () {
if (typeof self !== 'undefined' && self.navigator && self.navigator.requestMediaKeySystemAccess) {
return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);
} else {
return null;
}
}();
/***/ }),
/***/ "./src/utils/mediasource-helper.ts":
/*!*****************************************!*\
!*** ./src/utils/mediasource-helper.ts ***!
\*****************************************/
/*! exports provided: getMediaSource */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getMediaSource", function() { return getMediaSource; });
/**
* MediaSource helper
*/
function getMediaSource() {
return self.MediaSource || self.WebKitMediaSource;
}
/***/ }),
/***/ "./src/utils/mp4-tools.ts":
/*!********************************!*\
!*** ./src/utils/mp4-tools.ts ***!
\********************************/
/*! exports provided: bin2str, readUint16, readUint32, writeUint32, findBox, parseSegmentIndex, parseInitSegment, getStartDTS, getDuration, computeRawDurationFromSamples, offsetStartDTS, segmentValidRange, appendUint8Array */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bin2str", function() { return bin2str; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint16", function() { return readUint16; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "readUint32", function() { return readUint32; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "writeUint32", function() { return writeUint32; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "findBox", function() { return findBox; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseSegmentIndex", function() { return parseSegmentIndex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseInitSegment", function() { return parseInitSegment; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStartDTS", function() { return getStartDTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDuration", function() { return getDuration; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "computeRawDurationFromSamples", function() { return computeRawDurationFromSamples; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "offsetStartDTS", function() { return offsetStartDTS; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "segmentValidRange", function() { return segmentValidRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "appendUint8Array", function() { return appendUint8Array; });
/* harmony import */ var _typed_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./typed-array */ "./src/utils/typed-array.ts");
/* harmony import */ var _loader_fragment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.ts");
var UINT32_MAX = Math.pow(2, 32) - 1;
var push = [].push;
function bin2str(data) {
return String.fromCharCode.apply(null, data);
}
function readUint16(buffer, offset) {
if ('data' in buffer) {
offset += buffer.start;
buffer = buffer.data;
}
var val = buffer[offset] << 8 | buffer[offset + 1];
return val < 0 ? 65536 + val : val;
}
function readUint32(buffer, offset) {
if ('data' in buffer) {
offset += buffer.start;
buffer = buffer.data;
}
var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
return val < 0 ? 4294967296 + val : val;
}
function writeUint32(buffer, offset, value) {
if ('data' in buffer) {
offset += buffer.start;
buffer = buffer.data;
}
buffer[offset] = value >> 24;
buffer[offset + 1] = value >> 16 & 0xff;
buffer[offset + 2] = value >> 8 & 0xff;
buffer[offset + 3] = value & 0xff;
} // Find the data for a box specified by its path
function findBox(input, path) {
var results = [];
if (!path.length) {
// short-circuit the search for empty paths
return results;
}
var data;
var start;
var end;
if ('data' in input) {
data = input.data;
start = input.start;
end = input.end;
} else {
data = input;
start = 0;
end = data.byteLength;
}
for (var i = start; i < end;) {
var size = readUint32(data, i);
var type = bin2str(data.subarray(i + 4, i + 8));
var endbox = size > 1 ? i + size : end;
if (type === path[0]) {
if (path.length === 1) {
// this is the end of the path and we've found the box we were
// looking for
results.push({
data: data,
start: i + 8,
end: endbox
});
} else {
// recursively search for the next box along the path
var subresults = findBox({
data: data,
start: i + 8,
end: endbox
}, path.slice(1));
if (subresults.length) {
push.apply(results, subresults);
}
}
}
i = endbox;
} // we've finished searching all of data
return results;
}
function parseSegmentIndex(initSegment) {
var moovBox = findBox(initSegment, ['moov']);
var moov = moovBox[0];
var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
var sidxBox = findBox(initSegment, ['sidx']);
if (!sidxBox || !sidxBox[0]) {
return null;
}
var references = [];
var sidx = sidxBox[0];
var version = sidx.data[0]; // set initial offset, we skip the reference ID (not needed)
var index = version === 0 ? 8 : 16;
var timescale = readUint32(sidx, index);
index += 4; // TODO: parse earliestPresentationTime and firstOffset
// usually zero in our case
var earliestPresentationTime = 0;
var firstOffset = 0;
if (version === 0) {
index += 8;
} else {
index += 16;
} // skip reserved
index += 2;
var startByte = sidx.end + firstOffset;
var referencesCount = readUint16(sidx, index);
index += 2;
for (var i = 0; i < referencesCount; i++) {
var referenceIndex = index;
var referenceInfo = readUint32(sidx, referenceIndex);
referenceIndex += 4;
var referenceSize = referenceInfo & 0x7fffffff;
var referenceType = (referenceInfo & 0x80000000) >>> 31;
if (referenceType === 1) {
// eslint-disable-next-line no-console
console.warn('SIDX has hierarchical references (not supported)');
return null;
}
var subsegmentDuration = readUint32(sidx, referenceIndex);
referenceIndex += 4;
references.push({
referenceSize: referenceSize,
subsegmentDuration: subsegmentDuration,
// unscaled
info: {
duration: subsegmentDuration / timescale,
start: startByte,
end: startByte + referenceSize - 1
}
});
startByte += referenceSize; // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
// for |sapDelta|.
referenceIndex += 4; // skip to next ref
index = referenceIndex;
}
return {
earliestPresentationTime: earliestPresentationTime,
timescale: timescale,
version: version,
referencesCount: referencesCount,
references: references,
moovEndOffset: moovEndOffset
};
}
/**
* Parses an MP4 initialization segment and extracts stream type and
* timescale values for any declared tracks. Timescale values indicate the
* number of clock ticks per second to assume for time-based values
* elsewhere in the MP4.
*
* To determine the start time of an MP4, you need two pieces of
* information: the timescale unit and the earliest base media decode
* time. Multiple timescales can be specified within an MP4 but the
* base media decode time is always expressed in the timescale from
* the media header box for the track:
* ```
* moov > trak > mdia > mdhd.timescale
* moov > trak > mdia > hdlr
* ```
* @param initSegment {Uint8Array} the bytes of the init segment
* @return {InitData} a hash of track type to timescale values or null if
* the init segment is malformed.
*/
function parseInitSegment(initSegment) {
var result = [];
var traks = findBox(initSegment, ['moov', 'trak']);
for (var i = 0; i < traks.length; i++) {
var trak = traks[i];
var tkhd = findBox(trak, ['tkhd'])[0];
if (tkhd) {
var version = tkhd.data[tkhd.start];
var _index = version === 0 ? 12 : 20;
var trackId = readUint32(tkhd, _index);
var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
if (mdhd) {
version = mdhd.data[mdhd.start];
_index = version === 0 ? 12 : 20;
var timescale = readUint32(mdhd, _index);
var hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
if (hdlr) {
var hdlrType = bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
var type = {
soun: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO,
vide: _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO
}[hdlrType];
if (type) {
// Parse codec details
var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
var codec = void 0;
if (stsd) {
codec = bin2str(stsd.data.subarray(stsd.start + 12, stsd.start + 16)); // TODO: Parse codec details to be able to build MIME type.
// stsd.start += 8;
// const codecBox = findBox(stsd, [codec])[0];
// if (codecBox) {
// TODO: Codec parsing support for avc1, mp4a, hevc, av01...
// }
}
result[trackId] = {
timescale: timescale,
type: type
};
result[type] = {
timescale: timescale,
id: trackId,
codec: codec
};
}
}
}
}
}
var trex = findBox(initSegment, ['moov', 'mvex', 'trex']);
trex.forEach(function (trex) {
var trackId = readUint32(trex, 4);
var track = result[trackId];
if (track) {
track.default = {
duration: readUint32(trex, 12),
flags: readUint32(trex, 20)
};
}
});
return result;
}
/**
* Determine the base media decode start time, in seconds, for an MP4
* fragment. If multiple fragments are specified, the earliest time is
* returned.
*
* The base media decode time can be parsed from track fragment
* metadata:
* ```
* moof > traf > tfdt.baseMediaDecodeTime
* ```
* It requires the timescale value from the mdhd to interpret.
*
* @param initData {InitData} a hash of track type to timescale values
* @param fmp4 {Uint8Array} the bytes of the mp4 fragment
* @return {number} the earliest base media decode start time for the
* fragment, in seconds
*/
function getStartDTS(initData, fmp4) {
// we need info from two children of each track fragment box
return findBox(fmp4, ['moof', 'traf']).reduce(function (result, traf) {
var tfdt = findBox(traf, ['tfdt'])[0];
var version = tfdt.data[tfdt.start];
var start = findBox(traf, ['tfhd']).reduce(function (result, tfhd) {
// get the track id from the tfhd
var id = readUint32(tfhd, 4);
var track = initData[id];
if (track) {
var baseTime = readUint32(tfdt, 4);
if (version === 1) {
baseTime *= Math.pow(2, 32);
baseTime += readUint32(tfdt, 8);
} // assume a 90kHz clock if no timescale was specified
var scale = track.timescale || 90e3; // convert base time to seconds
var startTime = baseTime / scale;
if (isFinite(startTime) && (result === null || startTime < result)) {
return startTime;
}
}
return result;
}, null);
if (start !== null && isFinite(start) && (result === null || start < result)) {
return start;
}
return result;
}, null) || 0;
}
/*
For Reference:
aligned(8) class TrackFragmentHeaderBox
extends FullBox(‘tfhd’, 0, tf_flags){
unsigned int(32) track_ID;
// all the following are optional fields
unsigned int(64) base_data_offset;
unsigned int(32) sample_description_index;
unsigned int(32) default_sample_duration;
unsigned int(32) default_sample_size;
unsigned int(32) default_sample_flags
}
*/
function getDuration(data, initData) {
var rawDuration = 0;
var videoDuration = 0;
var audioDuration = 0;
var trafs = findBox(data, ['moof', 'traf']);
for (var i = 0; i < trafs.length; i++) {
var traf = trafs[i]; // There is only one tfhd & trun per traf
// This is true for CMAF style content, and we should perhaps check the ftyp
// and only look for a single trun then, but for ISOBMFF we should check
// for multiple track runs.
var tfhd = findBox(traf, ['tfhd'])[0]; // get the track id from the tfhd
var id = readUint32(tfhd, 4);
var track = initData[id];
if (!track) {
continue;
}
var trackDefault = track.default;
var tfhdFlags = readUint32(tfhd, 0) | (trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.flags);
var sampleDuration = trackDefault === null || trackDefault === void 0 ? void 0 : trackDefault.duration;
if (tfhdFlags & 0x000008) {
// 0x000008 indicates the presence of the default_sample_duration field
if (tfhdFlags & 0x000002) {
// 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration
// If present, the default_sample_duration exists at byte offset 12
sampleDuration = readUint32(tfhd, 12);
} else {
// Otherwise, the duration is at byte offset 8
sampleDuration = readUint32(tfhd, 8);
}
} // assume a 90kHz clock if no timescale was specified
var timescale = track.timescale || 90e3;
var truns = findBox(traf, ['trun']);
for (var j = 0; j < truns.length; j++) {
if (sampleDuration) {
var sampleCount = readUint32(truns[j], 4);
rawDuration = sampleDuration * sampleCount;
} else {
rawDuration = computeRawDurationFromSamples(truns[j]);
}
if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].VIDEO) {
videoDuration += rawDuration / timescale;
} else if (track.type === _loader_fragment__WEBPACK_IMPORTED_MODULE_1__["ElementaryStreamTypes"].AUDIO) {
audioDuration += rawDuration / timescale;
}
}
}
if (videoDuration === 0 && audioDuration === 0) {
// If duration samples are not available in the traf use sidx subsegment_duration
var sidx = parseSegmentIndex(data);
if (sidx !== null && sidx !== void 0 && sidx.references) {
return sidx.references.reduce(function (dur, ref) {
return dur + ref.info.duration || 0;
}, 0);
}
}
if (videoDuration) {
return videoDuration;
}
return audioDuration;
}
/*
For Reference:
aligned(8) class TrackRunBox
extends FullBox(‘trun’, version, tr_flags) {
unsigned int(32) sample_count;
// the following are optional fields
signed int(32) data_offset;
unsigned int(32) first_sample_flags;
// all fields in the following array are optional
{
unsigned int(32) sample_duration;
unsigned int(32) sample_size;
unsigned int(32) sample_flags
if (version == 0)
{ unsigned int(32)
else
{ signed int(32)
}[ sample_count ]
}
*/
function computeRawDurationFromSamples(trun) {
var flags = readUint32(trun, 0); // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.
// Each field is an int32, which is 4 bytes
var offset = 8; // data-offset-present flag
if (flags & 0x000001) {
offset += 4;
} // first-sample-flags-present flag
if (flags & 0x000004) {
offset += 4;
}
var duration = 0;
var sampleCount = readUint32(trun, 4);
for (var i = 0; i < sampleCount; i++) {
// sample-duration-present flag
if (flags & 0x000100) {
var sampleDuration = readUint32(trun, offset);
duration += sampleDuration;
offset += 4;
} // sample-size-present flag
if (flags & 0x000200) {
offset += 4;
} // sample-flags-present flag
if (flags & 0x000400) {
offset += 4;
} // sample-composition-time-offsets-present flag
if (flags & 0x000800) {
offset += 4;
}
}
return duration;
}
function offsetStartDTS(initData, fmp4, timeOffset) {
findBox(fmp4, ['moof', 'traf']).forEach(function (traf) {
findBox(traf, ['tfhd']).forEach(function (tfhd) {
// get the track id from the tfhd
var id = readUint32(tfhd, 4);
var track = initData[id];
if (!track) {
return;
} // assume a 90kHz clock if no timescale was specified
var timescale = track.timescale || 90e3; // get the base media decode time from the tfdt
findBox(traf, ['tfdt']).forEach(function (tfdt) {
var version = tfdt.data[tfdt.start];
var baseMediaDecodeTime = readUint32(tfdt, 4);
if (version === 0) {
writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
} else {
baseMediaDecodeTime *= Math.pow(2, 32);
baseMediaDecodeTime += readUint32(tfdt, 8);
baseMediaDecodeTime -= timeOffset * timescale;
baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
writeUint32(tfdt, 4, upper);
writeUint32(tfdt, 8, lower);
}
});
});
});
} // TODO: Check if the last moof+mdat pair is part of the valid range
function segmentValidRange(data) {
var segmentedRange = {
valid: null,
remainder: null
};
var moofs = findBox(data, ['moof']);
if (!moofs) {
return segmentedRange;
} else if (moofs.length < 2) {
segmentedRange.remainder = data;
return segmentedRange;
}
var last = moofs[moofs.length - 1]; // Offset by 8 bytes; findBox offsets the start by as much
segmentedRange.valid = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, 0, last.start - 8);
segmentedRange.remainder = Object(_typed_array__WEBPACK_IMPORTED_MODULE_0__["sliceUint8"])(data, last.start - 8);
return segmentedRange;
}
function appendUint8Array(data1, data2) {
var temp = new Uint8Array(data1.length + data2.length);
temp.set(data1);
temp.set(data2, data1.length);
return temp;
}
/***/ }),
/***/ "./src/utils/output-filter.ts":
/*!************************************!*\
!*** ./src/utils/output-filter.ts ***!
\************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return OutputFilter; });
var OutputFilter = /*#__PURE__*/function () {
function OutputFilter(timelineController, trackName) {
this.timelineController = void 0;
this.cueRanges = [];
this.trackName = void 0;
this.startTime = null;
this.endTime = null;
this.screen = null;
this.timelineController = timelineController;
this.trackName = trackName;
}
var _proto = OutputFilter.prototype;
_proto.dispatchCue = function dispatchCue() {
if (this.startTime === null) {
return;
}
this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen, this.cueRanges);
this.startTime = null;
};
_proto.newCue = function newCue(startTime, endTime, screen) {
if (this.startTime === null || this.startTime > startTime) {
this.startTime = startTime;
}
this.endTime = endTime;
this.screen = screen;
this.timelineController.createCaptionsTrack(this.trackName);
};
_proto.reset = function reset() {
this.cueRanges = [];
};
return OutputFilter;
}();
/***/ }),
/***/ "./src/utils/texttrack-utils.ts":
/*!**************************************!*\
!*** ./src/utils/texttrack-utils.ts ***!
\**************************************/
/*! exports provided: sendAddTrackEvent, addCueToTrack, clearCurrentCues, removeCuesInRange, getCuesInRange */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sendAddTrackEvent", function() { return sendAddTrackEvent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addCueToTrack", function() { return addCueToTrack; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearCurrentCues", function() { return clearCurrentCues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "removeCuesInRange", function() { return removeCuesInRange; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCuesInRange", function() { return getCuesInRange; });
/* harmony import */ var _logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./logger */ "./src/utils/logger.ts");
function sendAddTrackEvent(track, videoEl) {
var event;
try {
event = new Event('addtrack');
} catch (err) {
// for IE11
event = document.createEvent('Event');
event.initEvent('addtrack', false, false);
}
event.track = track;
videoEl.dispatchEvent(event);
}
function addCueToTrack(track, cue) {
// Sometimes there are cue overlaps on segmented vtts so the same
// cue can appear more than once in different vtt files.
// This avoid showing duplicated cues with same timecode and text.
var mode = track.mode;
if (mode === 'disabled') {
track.mode = 'hidden';
}
if (track.cues && !track.cues.getCueById(cue.id)) {
try {
track.addCue(cue);
if (!track.cues.getCueById(cue.id)) {
throw new Error("addCue is failed for: " + cue);
}
} catch (err) {
_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].debug("[texttrack-utils]: " + err);
var textTrackCue = new self.TextTrackCue(cue.startTime, cue.endTime, cue.text);
textTrackCue.id = cue.id;
track.addCue(textTrackCue);
}
}
if (mode === 'disabled') {
track.mode = mode;
}
}
function clearCurrentCues(track) {
// When track.mode is disabled, track.cues will be null.
// To guarantee the removal of cues, we need to temporarily
// change the mode to hidden
var mode = track.mode;
if (mode === 'disabled') {
track.mode = 'hidden';
}
if (!track.cues) {
return;
}
for (var i = track.cues.length; i--;) {
track.removeCue(track.cues[i]);
}
if (mode === 'disabled') {
track.mode = mode;
}
}
function removeCuesInRange(track, start, end) {
var mode = track.mode;
if (mode === 'disabled') {
track.mode = 'hidden';
}
if (!track.cues || !track.cues.length) {
return;
}
var cues = getCuesInRange(track.cues, start, end);
for (var i = 0; i < cues.length; i++) {
track.removeCue(cues[i]);
}
if (mode === 'disabled') {
track.mode = mode;
}
} // Find first cue starting after given time.
// Modified version of binary search O(log(n)).
function getFirstCueIndexAfterTime(cues, time) {
// If first cue starts after time, start there
if (time < cues[0].startTime) {
return 0;
} // If the last cue ends before time there is no overlap
var len = cues.length - 1;
if (time > cues[len].endTime) {
return -1;
}
var left = 0;
var right = len;
while (left <= right) {
var mid = Math.floor((right + left) / 2);
if (time < cues[mid].startTime) {
right = mid - 1;
} else if (time > cues[mid].startTime && left < len) {
left = mid + 1;
} else {
// If it's not lower or higher, it must be equal.
return mid;
}
} // At this point, left and right have swapped.
// No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
return cues[left].startTime - time < time - cues[right].startTime ? left : right;
}
function getCuesInRange(cues, start, end) {
var cuesFound = [];
var firstCueInRange = getFirstCueIndexAfterTime(cues, start);
if (firstCueInRange > -1) {
for (var i = firstCueInRange, len = cues.length; i < len; i++) {
var cue = cues[i];
if (cue.startTime >= start && cue.endTime <= end) {
cuesFound.push(cue);
} else if (cue.startTime > end) {
return cuesFound;
}
}
}
return cuesFound;
}
/***/ }),
/***/ "./src/utils/time-ranges.ts":
/*!**********************************!*\
!*** ./src/utils/time-ranges.ts ***!
\**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* TimeRanges to string helper
*/
var TimeRanges = {
toString: function toString(r) {
var log = '';
var len = r.length;
for (var i = 0; i < len; i++) {
log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
}
return log;
}
};
/* harmony default export */ __webpack_exports__["default"] = (TimeRanges);
/***/ }),
/***/ "./src/utils/timescale-conversion.ts":
/*!*******************************************!*\
!*** ./src/utils/timescale-conversion.ts ***!
\*******************************************/
/*! exports provided: toTimescaleFromBase, toTimescaleFromScale, toMsFromMpegTsClock, toMpegTsClockFromTimescale */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromBase", function() { return toTimescaleFromBase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTimescaleFromScale", function() { return toTimescaleFromScale; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMsFromMpegTsClock", function() { return toMsFromMpegTsClock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toMpegTsClockFromTimescale", function() { return toMpegTsClockFromTimescale; });
var MPEG_TS_CLOCK_FREQ_HZ = 90000;
function toTimescaleFromBase(value, destScale, srcBase, round) {
if (srcBase === void 0) {
srcBase = 1;
}
if (round === void 0) {
round = false;
}
var result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
return round ? Math.round(result) : result;
}
function toTimescaleFromScale(value, destScale, srcScale, round) {
if (srcScale === void 0) {
srcScale = 1;
}
if (round === void 0) {
round = false;
}
return toTimescaleFromBase(value, destScale, 1 / srcScale, round);
}
function toMsFromMpegTsClock(value, round) {
if (round === void 0) {
round = false;
}
return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
}
function toMpegTsClockFromTimescale(value, srcScale) {
if (srcScale === void 0) {
srcScale = 1;
}
return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
}
/***/ }),
/***/ "./src/utils/typed-array.ts":
/*!**********************************!*\
!*** ./src/utils/typed-array.ts ***!
\**********************************/
/*! exports provided: sliceUint8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sliceUint8", function() { return sliceUint8; });
function sliceUint8(array, start, end) {
// @ts-expect-error This polyfills IE11 usage of Uint8Array slice.
// It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.
return Uint8Array.prototype.slice ? array.slice(start, end) : new Uint8Array(Array.prototype.slice.call(array, start, end));
}
/***/ }),
/***/ "./src/utils/vttcue.ts":
/*!*****************************!*\
!*** ./src/utils/vttcue.ts ***!
\*****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* Copyright 2013 vtt.js Contributors
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* harmony default export */ __webpack_exports__["default"] = ((function () {
if (typeof self !== 'undefined' && self.VTTCue) {
return self.VTTCue;
}
var AllowedDirections = ['', 'lr', 'rl'];
var AllowedAlignments = ['start', 'middle', 'end', 'left', 'right'];
function isAllowedValue(allowed, value) {
if (typeof value !== 'string') {
return false;
} // necessary for assuring the generic conforms to the Array interface
if (!Array.isArray(allowed)) {
return false;
} // reset the type so that the next narrowing works well
var lcValue = value.toLowerCase(); // use the allow list to narrow the type to a specific subset of strings
if (~allowed.indexOf(lcValue)) {
return lcValue;
}
return false;
}
function findDirectionSetting(value) {
return isAllowedValue(AllowedDirections, value);
}
function findAlignSetting(value) {
return isAllowedValue(AllowedAlignments, value);
}
function extend(obj) {
for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
var i = 1;
for (; i < arguments.length; i++) {
var cobj = arguments[i];
for (var p in cobj) {
obj[p] = cobj[p];
}
}
return obj;
}
function VTTCue(startTime, endTime, text) {
var cue = this;
var baseObj = {
enumerable: true
};
/**
* Shim implementation specific properties. These properties are not in
* the spec.
*/
// Lets us know when the VTTCue's data has changed in such a way that we need
// to recompute its display state. This lets us compute its display state
// lazily.
cue.hasBeenReset = false;
/**
* VTTCue and TextTrackCue properties
* http://dev.w3.org/html5/webvtt/#vttcue-interface
*/
var _id = '';
var _pauseOnExit = false;
var _startTime = startTime;
var _endTime = endTime;
var _text = text;
var _region = null;
var _vertical = '';
var _snapToLines = true;
var _line = 'auto';
var _lineAlign = 'start';
var _position = 50;
var _positionAlign = 'middle';
var _size = 50;
var _align = 'middle';
Object.defineProperty(cue, 'id', extend({}, baseObj, {
get: function get() {
return _id;
},
set: function set(value) {
_id = '' + value;
}
}));
Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
get: function get() {
return _pauseOnExit;
},
set: function set(value) {
_pauseOnExit = !!value;
}
}));
Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
get: function get() {
return _startTime;
},
set: function set(value) {
if (typeof value !== 'number') {
throw new TypeError('Start time must be set to a number.');
}
_startTime = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
get: function get() {
return _endTime;
},
set: function set(value) {
if (typeof value !== 'number') {
throw new TypeError('End time must be set to a number.');
}
_endTime = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'text', extend({}, baseObj, {
get: function get() {
return _text;
},
set: function set(value) {
_text = '' + value;
this.hasBeenReset = true;
}
})); // todo: implement VTTRegion polyfill?
Object.defineProperty(cue, 'region', extend({}, baseObj, {
get: function get() {
return _region;
},
set: function set(value) {
_region = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
get: function get() {
return _vertical;
},
set: function set(value) {
var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string.
if (setting === false) {
throw new SyntaxError('An invalid or illegal string was specified.');
}
_vertical = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
get: function get() {
return _snapToLines;
},
set: function set(value) {
_snapToLines = !!value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'line', extend({}, baseObj, {
get: function get() {
return _line;
},
set: function set(value) {
if (typeof value !== 'number' && value !== 'auto') {
throw new SyntaxError('An invalid number or illegal string was specified.');
}
_line = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
get: function get() {
return _lineAlign;
},
set: function set(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError('An invalid or illegal string was specified.');
}
_lineAlign = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'position', extend({}, baseObj, {
get: function get() {
return _position;
},
set: function set(value) {
if (value < 0 || value > 100) {
throw new Error('Position must be between 0 and 100.');
}
_position = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
get: function get() {
return _positionAlign;
},
set: function set(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError('An invalid or illegal string was specified.');
}
_positionAlign = setting;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'size', extend({}, baseObj, {
get: function get() {
return _size;
},
set: function set(value) {
if (value < 0 || value > 100) {
throw new Error('Size must be between 0 and 100.');
}
_size = value;
this.hasBeenReset = true;
}
}));
Object.defineProperty(cue, 'align', extend({}, baseObj, {
get: function get() {
return _align;
},
set: function set(value) {
var setting = findAlignSetting(value);
if (!setting) {
throw new SyntaxError('An invalid or illegal string was specified.');
}
_align = setting;
this.hasBeenReset = true;
}
}));
/**
* Other <track> spec defined properties
*/
// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
cue.displayState = undefined;
}
/**
* VTTCue methods
*/
VTTCue.prototype.getCueAsHTML = function () {
// Assume WebVTT.convertCueToDOMTree is on the global.
var WebVTT = self.WebVTT;
return WebVTT.convertCueToDOMTree(self, this.text);
}; // this is a polyfill hack
return VTTCue;
})());
/***/ }),
/***/ "./src/utils/vttparser.ts":
/*!********************************!*\
!*** ./src/utils/vttparser.ts ***!
\********************************/
/*! exports provided: parseTimeStamp, fixLineBreaks, VTTParser */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseTimeStamp", function() { return parseTimeStamp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fixLineBreaks", function() { return fixLineBreaks; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VTTParser", function() { return VTTParser; });
/* harmony import */ var _vttcue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vttcue */ "./src/utils/vttcue.ts");
/*
* Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js
*/
var StringDecoder = /*#__PURE__*/function () {
function StringDecoder() {}
var _proto = StringDecoder.prototype;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_proto.decode = function decode(data, options) {
if (!data) {
return '';
}
if (typeof data !== 'string') {
throw new Error('Error - expected string data.');
}
return decodeURIComponent(encodeURIComponent(data));
};
return StringDecoder;
}(); // Try to parse input as a time stamp.
function parseTimeStamp(input) {
function computeSeconds(h, m, s, f) {
return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);
}
var m = input.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);
if (!m) {
return null;
}
if (parseFloat(m[2]) > 59) {
// Timestamp takes the form of [hours]:[minutes].[milliseconds]
// First position is hours as it's over 59.
return computeSeconds(m[2], m[3], 0, m[4]);
} // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]
return computeSeconds(m[1], m[2], m[3], m[4]);
} // A settings object holds key/value pairs and will ignore anything but the first
// assignment to a specific key.
var Settings = /*#__PURE__*/function () {
function Settings() {
this.values = Object.create(null);
}
var _proto2 = Settings.prototype;
// Only accept the first assignment to any key.
_proto2.set = function set(k, v) {
if (!this.get(k) && v !== '') {
this.values[k] = v;
}
} // Return the value for a key, or a default value.
// If 'defaultKey' is passed then 'dflt' is assumed to be an object with
// a number of possible default values as properties where 'defaultKey' is
// the key of the property that will be chosen; otherwise it's assumed to be
// a single value.
;
_proto2.get = function get(k, dflt, defaultKey) {
if (defaultKey) {
return this.has(k) ? this.values[k] : dflt[defaultKey];
}
return this.has(k) ? this.values[k] : dflt;
} // Check whether we have a value for a key.
;
_proto2.has = function has(k) {
return k in this.values;
} // Accept a setting if its one of the given alternatives.
;
_proto2.alt = function alt(k, v, a) {
for (var n = 0; n < a.length; ++n) {
if (v === a[n]) {
this.set(k, v);
break;
}
}
} // Accept a setting if its a valid (signed) integer.
;
_proto2.integer = function integer(k, v) {
if (/^-?\d+$/.test(v)) {
// integer
this.set(k, parseInt(v, 10));
}
} // Accept a setting if its a valid percentage.
;
_proto2.percent = function percent(k, v) {
if (/^([\d]{1,3})(\.[\d]*)?%$/.test(v)) {
var percent = parseFloat(v);
if (percent >= 0 && percent <= 100) {
this.set(k, percent);
return true;
}
}
return false;
};
return Settings;
}(); // Helper function to parse input into groups separated by 'groupDelim', and
// interpret each group as a key/value pair separated by 'keyValueDelim'.
function parseOptions(input, callback, keyValueDelim, groupDelim) {
var groups = groupDelim ? input.split(groupDelim) : [input];
for (var i in groups) {
if (typeof groups[i] !== 'string') {
continue;
}
var kv = groups[i].split(keyValueDelim);
if (kv.length !== 2) {
continue;
}
var _k = kv[0];
var _v = kv[1];
callback(_k, _v);
}
}
var defaults = new _vttcue__WEBPACK_IMPORTED_MODULE_0__["default"](0, 0, ''); // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
// Safari doesn't yet support this change, but FF and Chrome do.
var center = defaults.align === 'middle' ? 'middle' : 'center';
function parseCue(input, cue, regionList) {
// Remember the original input if we need to throw an error.
var oInput = input; // 4.1 WebVTT timestamp
function consumeTimeStamp() {
var ts = parseTimeStamp(input);
if (ts === null) {
throw new Error('Malformed timestamp: ' + oInput);
} // Remove time stamp from input.
input = input.replace(/^[^\sa-zA-Z-]+/, '');
return ts;
} // 4.4.2 WebVTT cue settings
function consumeCueSettings(input, cue) {
var settings = new Settings();
parseOptions(input, function (k, v) {
var vals;
switch (k) {
case 'region':
// Find the last region we parsed with the same region id.
for (var i = regionList.length - 1; i >= 0; i--) {
if (regionList[i].id === v) {
settings.set(k, regionList[i].region);
break;
}
}
break;
case 'vertical':
settings.alt(k, v, ['rl', 'lr']);
break;
case 'line':
vals = v.split(',');
settings.integer(k, vals[0]);
if (settings.percent(k, vals[0])) {
settings.set('snapToLines', false);
}
settings.alt(k, vals[0], ['auto']);
if (vals.length === 2) {
settings.alt('lineAlign', vals[1], ['start', center, 'end']);
}
break;
case 'position':
vals = v.split(',');
settings.percent(k, vals[0]);
if (vals.length === 2) {
settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
}
break;
case 'size':
settings.percent(k, v);
break;
case 'align':
settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
break;
}
}, /:/, /\s/); // Apply default values for any missing fields.
cue.region = settings.get('region', null);
cue.vertical = settings.get('vertical', '');
var line = settings.get('line', 'auto');
if (line === 'auto' && defaults.line === -1) {
// set numeric line number for Safari
line = -1;
}
cue.line = line;
cue.lineAlign = settings.get('lineAlign', 'start');
cue.snapToLines = settings.get('snapToLines', true);
cue.size = settings.get('size', 100);
cue.align = settings.get('align', center);
var position = settings.get('position', 'auto');
if (position === 'auto' && defaults.position === 50) {
// set numeric position for Safari
position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
}
cue.position = position;
}
function skipWhitespace() {
input = input.replace(/^\s+/, '');
} // 4.1 WebVTT cue timings.
skipWhitespace();
cue.startTime = consumeTimeStamp(); // (1) collect cue start time
skipWhitespace();
if (input.substr(0, 3) !== '-->') {
// (3) next characters must match '-->'
throw new Error("Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
}
input = input.substr(3);
skipWhitespace();
cue.endTime = consumeTimeStamp(); // (5) collect cue end time
// 4.1 WebVTT cue settings list.
skipWhitespace();
consumeCueSettings(input, cue);
}
function fixLineBreaks(input) {
return input.replace(/<br(?: \/)?>/gi, '\n');
}
var VTTParser = /*#__PURE__*/function () {
function VTTParser() {
this.state = 'INITIAL';
this.buffer = '';
this.decoder = new StringDecoder();
this.regionList = [];
this.cue = null;
this.oncue = void 0;
this.onparsingerror = void 0;
this.onflush = void 0;
}
var _proto3 = VTTParser.prototype;
_proto3.parse = function parse(data) {
var _this = this; // If there is no data then we won't decode it, but will just try to parse
// whatever is in buffer already. This may occur in circumstances, for
// example when flush() is called.
if (data) {
// Try to decode the data that we received.
_this.buffer += _this.decoder.decode(data, {
stream: true
});
}
function collectNextLine() {
var buffer = _this.buffer;
var pos = 0;
buffer = fixLineBreaks(buffer);
while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
++pos;
}
var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below.
if (buffer[pos] === '\r') {
++pos;
}
if (buffer[pos] === '\n') {
++pos;
}
_this.buffer = buffer.substr(pos);
return line;
} // 3.2 WebVTT metadata header syntax
function parseHeader(input) {
parseOptions(input, function (k, v) {// switch (k) {
// case 'region':
// 3.3 WebVTT region metadata header syntax
// console.log('parse region', v);
// parseRegion(v);
// break;
// }
}, /:/);
} // 5.1 WebVTT file parsing.
try {
var line = '';
if (_this.state === 'INITIAL') {
// We can't start parsing until we have the first line.
if (!/\r\n|\n/.test(_this.buffer)) {
return this;
}
line = collectNextLine(); // strip of UTF-8 BOM if any
// https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
var m = line.match(/^()?WEBVTT([ \t].*)?$/);
if (!m || !m[0]) {
throw new Error('Malformed WebVTT signature.');
}
_this.state = 'HEADER';
}
var alreadyCollectedLine = false;
while (_this.buffer) {
// We can't parse a line until we have the full line.
if (!/\r\n|\n/.test(_this.buffer)) {
return this;
}
if (!alreadyCollectedLine) {
line = collectNextLine();
} else {
alreadyCollectedLine = false;
}
switch (_this.state) {
case 'HEADER':
// 13-18 - Allow a header (metadata) under the WEBVTT line.
if (/:/.test(line)) {
parseHeader(line);
} else if (!line) {
// An empty line terminates the header and starts the body (cues).
_this.state = 'ID';
}
continue;
case 'NOTE':
// Ignore NOTE blocks.
if (!line) {
_this.state = 'ID';
}
continue;
case 'ID':
// Check for the start of NOTE blocks.
if (/^NOTE($|[ \t])/.test(line)) {
_this.state = 'NOTE';
break;
} // 19-29 - Allow any number of line terminators, then initialize new cue values.
if (!line) {
continue;
}
_this.cue = new _vttcue__WEBPACK_IMPORTED_MODULE_0__["default"](0, 0, '');
_this.state = 'CUE'; // 30-39 - Check if self line contains an optional identifier or timing data.
if (line.indexOf('-->') === -1) {
_this.cue.id = line;
continue;
}
// Process line as start of a cue.
/* falls through */
case 'CUE':
// 40 - Collect cue timings and settings.
if (!_this.cue) {
_this.state = 'BADCUE';
continue;
}
try {
parseCue(line, _this.cue, _this.regionList);
} catch (e) {
// In case of an error ignore rest of the cue.
_this.cue = null;
_this.state = 'BADCUE';
continue;
}
_this.state = 'CUETEXT';
continue;
case 'CUETEXT':
{
var hasSubstring = line.indexOf('-->') !== -1; // 34 - If we have an empty line then report the cue.
// 35 - If we have the special substring '-->' then report the cue,
// but do not collect the line as we need to process the current
// one as a new cue.
if (!line || hasSubstring && (alreadyCollectedLine = true)) {
// We are done parsing self cue.
if (_this.oncue && _this.cue) {
_this.oncue(_this.cue);
}
_this.cue = null;
_this.state = 'ID';
continue;
}
if (_this.cue === null) {
continue;
}
if (_this.cue.text) {
_this.cue.text += '\n';
}
_this.cue.text += line;
}
continue;
case 'BADCUE':
// 54-62 - Collect and discard the remaining cue.
if (!line) {
_this.state = 'ID';
}
}
}
} catch (e) {
// If we are currently parsing a cue, report what we have.
if (_this.state === 'CUETEXT' && _this.cue && _this.oncue) {
_this.oncue(_this.cue);
}
_this.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise
// another exception occurred so enter BADCUE state.
_this.state = _this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
}
return this;
};
_proto3.flush = function flush() {
var _this = this;
try {
// Finish decoding the stream.
// _this.buffer += _this.decoder.decode();
// Synthesize the end of the current cue or region.
if (_this.cue || _this.state === 'HEADER') {
_this.buffer += '\n\n';
_this.parse();
} // If we've flushed, parsed, and we're still on the INITIAL state then
// that means we don't have enough of the stream to parse the first
// line.
if (_this.state === 'INITIAL' || _this.state === 'BADWEBVTT') {
throw new Error('Malformed WebVTT signature.');
}
} catch (e) {
if (_this.onparsingerror) {
_this.onparsingerror(e);
}
}
if (_this.onflush) {
_this.onflush();
}
return this;
};
return VTTParser;
}();
/***/ }),
/***/ "./src/utils/webvtt-parser.ts":
/*!************************************!*\
!*** ./src/utils/webvtt-parser.ts ***!
\************************************/
/*! exports provided: generateCueId, parseWebVTT */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateCueId", function() { return generateCueId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parseWebVTT", function() { return parseWebVTT; });
/* harmony import */ var _home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.ts");
/* harmony import */ var _vttparser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.ts");
/* harmony import */ var _demux_id3__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.ts");
/* harmony import */ var _timescale_conversion__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./timescale-conversion */ "./src/utils/timescale-conversion.ts");
/* harmony import */ var _remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.ts");
var LINEBREAKS = /\r\n|\n\r|\n|\r/g; // String.prototype.startsWith is not supported in IE11
var startsWith = function startsWith(inputString, searchString, position) {
if (position === void 0) {
position = 0;
}
return inputString.substr(position, searchString.length) === searchString;
};
var cueString2millis = function cueString2millis(timeString) {
var ts = parseInt(timeString.substr(-3));
var secs = parseInt(timeString.substr(-6, 2));
var mins = parseInt(timeString.substr(-9, 2));
var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;
if (!Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(ts) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(secs) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(mins) || !Object(_home_runner_work_hls_js_hls_js_src_polyfills_number__WEBPACK_IMPORTED_MODULE_0__["isFiniteNumber"])(hours)) {
throw Error("Malformed X-TIMESTAMP-MAP: Local:" + timeString);
}
ts += 1000 * secs;
ts += 60 * 1000 * mins;
ts += 60 * 60 * 1000 * hours;
return ts;
}; // From https://github.com/darkskyapp/string-hash
var hash = function hash(text) {
var hash = 5381;
var i = text.length;
while (i) {
hash = hash * 33 ^ text.charCodeAt(--i);
}
return (hash >>> 0).toString();
}; // Create a unique hash id for a cue based on start/end times and text.
// This helps timeline-controller to avoid showing repeated captions.
function generateCueId(startTime, endTime, text) {
return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);
}
var calculateOffset = function calculateOffset(vttCCs, cc, presentationTime) {
var currCC = vttCCs[cc];
var prevCC = vttCCs[currCC.prevCC]; // This is the first discontinuity or cues have been processed since the last discontinuity
// Offset = current discontinuity time
if (!prevCC || !prevCC.new && currCC.new) {
vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
currCC.new = false;
return;
} // There have been discontinuities since cues were last parsed.
// Offset = time elapsed
while ((_prevCC = prevCC) !== null && _prevCC !== void 0 && _prevCC.new) {
var _prevCC;
vttCCs.ccOffset += currCC.start - prevCC.start;
currCC.new = false;
currCC = prevCC;
prevCC = vttCCs[currCC.prevCC];
}
vttCCs.presentationOffset = presentationTime;
};
function parseWebVTT(vttByteArray, initPTS, timescale, vttCCs, cc, timeOffset, callBack, errorCallBack) {
var parser = new _vttparser__WEBPACK_IMPORTED_MODULE_1__["VTTParser"](); // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
// Uint8Array.prototype.reduce is not implemented in IE11
var vttLines = Object(_demux_id3__WEBPACK_IMPORTED_MODULE_2__["utf8ArrayToStr"])(new Uint8Array(vttByteArray)).trim().replace(LINEBREAKS, '\n').split('\n');
var cues = [];
var initPTS90Hz = Object(_timescale_conversion__WEBPACK_IMPORTED_MODULE_3__["toMpegTsClockFromTimescale"])(initPTS, timescale);
var cueTime = '00:00.000';
var timestampMapMPEGTS = 0;
var timestampMapLOCAL = 0;
var parsingError;
var inHeader = true;
var timestampMap = false;
parser.oncue = function (cue) {
// Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
var currCC = vttCCs[cc];
var cueOffset = vttCCs.ccOffset; // Calculate subtitle PTS offset
var webVttMpegTsMapOffset = (timestampMapMPEGTS - initPTS90Hz) / 90000; // Update offsets for new discontinuities
if (currCC !== null && currCC !== void 0 && currCC.new) {
if (timestampMapLOCAL !== undefined) {
// When local time is provided, offset = discontinuity start time - local time
cueOffset = vttCCs.ccOffset = currCC.start;
} else {
calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);
}
}
if (webVttMpegTsMapOffset) {
// If we have MPEGTS, offset = presentation time + discontinuity offset
cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;
}
if (timestampMap) {
var duration = cue.endTime - cue.startTime;
var startTime = Object(_remux_mp4_remuxer__WEBPACK_IMPORTED_MODULE_4__["normalizePts"])((cue.startTime + cueOffset - timestampMapLOCAL) * 90000, timeOffset * 90000) / 90000;
cue.startTime = startTime;
cue.endTime = startTime + duration;
} //trim trailing webvtt block whitespaces
var text = cue.text.trim(); // Fix encoding of special characters
cue.text = decodeURIComponent(encodeURIComponent(text)); // If the cue was not assigned an id from the VTT file (line above the content), create one.
if (!cue.id) {
cue.id = generateCueId(cue.startTime, cue.endTime, text);
}
if (cue.endTime > 0) {
cues.push(cue);
}
};
parser.onparsingerror = function (error) {
parsingError = error;
};
parser.onflush = function () {
if (parsingError) {
errorCallBack(parsingError);
return;
}
callBack(cues);
}; // Go through contents line by line.
vttLines.forEach(function (line) {
if (inHeader) {
// Look for X-TIMESTAMP-MAP in header.
if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
// Once found, no more are allowed anyway, so stop searching.
inHeader = false;
timestampMap = true; // Extract LOCAL and MPEGTS.
line.substr(16).split(',').forEach(function (timestamp) {
if (startsWith(timestamp, 'LOCAL:')) {
cueTime = timestamp.substr(6);
} else if (startsWith(timestamp, 'MPEGTS:')) {
timestampMapMPEGTS = parseInt(timestamp.substr(7));
}
});
try {
// Convert cue time to seconds
timestampMapLOCAL = cueString2millis(cueTime) / 1000;
} catch (error) {
timestampMap = false;
parsingError = error;
} // Return without parsing X-TIMESTAMP-MAP line.
return;
} else if (line === '') {
inHeader = false;
}
} // Parse line by default.
parser.parse(line + '\n');
});
parser.flush();
}
/***/ }),
/***/ "./src/utils/xhr-loader.ts":
/*!*********************************!*\
!*** ./src/utils/xhr-loader.ts ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.ts");
/* harmony import */ var _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../loader/load-stats */ "./src/loader/load-stats.ts");
var AGE_HEADER_LINE_REGEX = /^age:\s*[\d.]+\s*$/m;
var XhrLoader = /*#__PURE__*/function () {
function XhrLoader(config
/* HlsConfig */
) {
this.xhrSetup = void 0;
this.requestTimeout = void 0;
this.retryTimeout = void 0;
this.retryDelay = void 0;
this.config = null;
this.callbacks = null;
this.context = void 0;
this.loader = null;
this.stats = void 0;
this.xhrSetup = config ? config.xhrSetup : null;
this.stats = new _loader_load_stats__WEBPACK_IMPORTED_MODULE_1__["LoadStats"]();
this.retryDelay = 0;
}
var _proto = XhrLoader.prototype;
_proto.destroy = function destroy() {
this.callbacks = null;
this.abortInternal();
this.loader = null;
this.config = null;
};
_proto.abortInternal = function abortInternal() {
var loader = this.loader;
self.clearTimeout(this.requestTimeout);
self.clearTimeout(this.retryTimeout);
if (loader) {
loader.onreadystatechange = null;
loader.onprogress = null;
if (loader.readyState !== 4) {
this.stats.aborted = true;
loader.abort();
}
}
};
_proto.abort = function abort() {
var _this$callbacks;
this.abortInternal();
if ((_this$callbacks = this.callbacks) !== null && _this$callbacks !== void 0 && _this$callbacks.onAbort) {
this.callbacks.onAbort(this.stats, this.context, this.loader);
}
};
_proto.load = function load(context, config, callbacks) {
if (this.stats.loading.start) {
throw new Error('Loader can only be used once.');
}
this.stats.loading.start = self.performance.now();
this.context = context;
this.config = config;
this.callbacks = callbacks;
this.retryDelay = config.retryDelay;
this.loadInternal();
};
_proto.loadInternal = function loadInternal() {
var config = this.config,
context = this.context;
if (!config) {
return;
}
var xhr = this.loader = new self.XMLHttpRequest();
var stats = this.stats;
stats.loading.first = 0;
stats.loaded = 0;
var xhrSetup = this.xhrSetup;
try {
if (xhrSetup) {
try {
xhrSetup(xhr, context.url);
} catch (e) {
// fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
// not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
xhr.open('GET', context.url, true);
xhrSetup(xhr, context.url);
}
}
if (!xhr.readyState) {
xhr.open('GET', context.url, true);
}
} catch (e) {
// IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
this.callbacks.onError({
code: xhr.status,
text: e.message
}, context, xhr);
return;
}
if (context.rangeEnd) {
xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
}
xhr.onreadystatechange = this.readystatechange.bind(this);
xhr.onprogress = this.loadprogress.bind(this);
xhr.responseType = context.responseType; // setup timeout before we perform request
self.clearTimeout(this.requestTimeout);
this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
xhr.send();
};
_proto.readystatechange = function readystatechange() {
var context = this.context,
xhr = this.loader,
stats = this.stats;
if (!context || !xhr) {
return;
}
var readyState = xhr.readyState;
var config = this.config; // don't proceed if xhr has been aborted
if (stats.aborted) {
return;
} // >= HEADERS_RECEIVED
if (readyState >= 2) {
// clear xhr timeout and rearm it if readyState less than 4
self.clearTimeout(this.requestTimeout);
if (stats.loading.first === 0) {
stats.loading.first = Math.max(self.performance.now(), stats.loading.start);
}
if (readyState === 4) {
xhr.onreadystatechange = null;
xhr.onprogress = null;
var status = xhr.status; // http status between 200 to 299 are all successful
if (status >= 200 && status < 300) {
stats.loading.end = Math.max(self.performance.now(), stats.loading.first);
var data;
var len;
if (context.responseType === 'arraybuffer') {
data = xhr.response;
len = data.byteLength;
} else {
data = xhr.responseText;
len = data.length;
}
stats.loaded = stats.total = len;
if (!this.callbacks) {
return;
}
var onProgress = this.callbacks.onProgress;
if (onProgress) {
onProgress(stats, context, data, xhr);
}
if (!this.callbacks) {
return;
}
var response = {
url: xhr.responseURL,
data: data
};
this.callbacks.onSuccess(response, stats, context, xhr);
} else {
// if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].error(status + " while loading " + context.url);
this.callbacks.onError({
code: status,
text: xhr.statusText
}, context, xhr);
} else {
// retry
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn(status + " while loading " + context.url + ", retrying in " + this.retryDelay + "..."); // abort and reset internal state
this.abortInternal();
this.loader = null; // schedule retry
self.clearTimeout(this.retryTimeout);
this.retryTimeout = self.setTimeout(this.loadInternal.bind(this), this.retryDelay); // set exponential backoff
this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
stats.retry++;
}
}
} else {
// readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
self.clearTimeout(this.requestTimeout);
this.requestTimeout = self.setTimeout(this.loadtimeout.bind(this), config.timeout);
}
}
};
_proto.loadtimeout = function loadtimeout() {
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].warn("timeout while loading " + this.context.url);
var callbacks = this.callbacks;
if (callbacks) {
this.abortInternal();
callbacks.onTimeout(this.stats, this.context, this.loader);
}
};
_proto.loadprogress = function loadprogress(event) {
var stats = this.stats;
stats.loaded = event.loaded;
if (event.lengthComputable) {
stats.total = event.total;
}
};
_proto.getCacheAge = function getCacheAge() {
var result = null;
if (this.loader && AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())) {
var ageHeader = this.loader.getResponseHeader('age');
result = ageHeader ? parseFloat(ageHeader) : null;
}
return result;
};
return XhrLoader;
}();
/* harmony default export */ __webpack_exports__["default"] = (XhrLoader);
/***/ })
/******/ })["default"];
});
//# sourceMappingURL=hls.js.map
|
import { isElement, isValidElementType, ForwardRef } from 'react-is';
import Stylis from '@emotion/stylis';
import _insertRulePlugin from 'stylis-rule-sheet';
import unitless from '@emotion/unitless';
import validAttr from '@emotion/is-prop-valid';
import merge from 'merge-anything';
import React, { useContext, useState, useMemo, createElement, useDebugValue, useEffect } from 'react';
import shallowequal from 'shallowequal';
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
//
var interleave = (function (strings, interpolations) {
var result = [strings[0]];
for (var i = 0, len = interpolations.length; i < len; i += 1) {
result.push(interpolations[i], strings[i + 1]);
}
return result;
});
//
var isPlainObject = (function (x) {
return typeof x === 'object' && x.constructor === Object;
});
//
var EMPTY_ARRAY = Object.freeze([]);
var EMPTY_OBJECT = Object.freeze({});
//
function isFunction(test) {
return typeof test === 'function';
}
//
function getComponentName(target) {
return (process.env.NODE_ENV !== 'production' ? typeof target === 'string' && target : false) || // $FlowFixMe
target.displayName || // $FlowFixMe
target.name || 'Component';
}
//
function isStatelessFunction(test) {
return typeof test === 'function' && !(test.prototype && test.prototype.isReactComponent);
}
//
function isStyledComponent(target) {
return target && typeof target.styledComponentId === 'string';
}
//
var SC_ATTR = typeof process !== 'undefined' && (process.env.REACT_APP_SC_ATTR || process.env.SC_ATTR) || 'data-styled';
var SC_ATTR_ACTIVE = 'active';
var SC_ATTR_VERSION = 'data-styled-version';
var SC_VERSION = "5.0.0-beta.11-cgsmulti";
var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window;
var DISABLE_SPEEDY = typeof SC_DISABLE_SPEEDY === 'boolean' && SC_DISABLE_SPEEDY || typeof process !== 'undefined' && (process.env.REACT_APP_SC_DISABLE_SPEEDY || process.env.SC_DISABLE_SPEEDY) || process.env.NODE_ENV !== 'production'; // Shared empty execution context when generating static styles
var STATIC_EXECUTION_CONTEXT = {};
var COMMENT_REGEX = /^\s*\/\/.*$/gm;
function createStylisInstance(_temp) {
var _ref = _temp === void 0 ? EMPTY_OBJECT : _temp,
_ref$options = _ref.options,
options = _ref$options === void 0 ? EMPTY_OBJECT : _ref$options,
_ref$plugins = _ref.plugins,
plugins = _ref$plugins === void 0 ? EMPTY_ARRAY : _ref$plugins;
var stylis = new Stylis(options); // Wrap `insertRulePlugin to build a list of rules,
// and then make our own plugin to return the rules. This
// makes it easier to hook into the existing SSR architecture
var parsingRules = []; // eslint-disable-next-line consistent-return
var returnRulesPlugin = function returnRulesPlugin(context) {
if (context === -2) {
var parsedRules = parsingRules;
parsingRules = [];
return parsedRules;
}
};
var parseRulesPlugin = _insertRulePlugin(function (rule) {
parsingRules.push(rule);
});
var _componentId;
var _selector;
var _selectorRegexp;
var selfReferenceReplacer = function selfReferenceReplacer(match, offset, string) {
if ( // the first self-ref is always untouched
offset > 0 && // there should be at least two self-refs to do a replacement (.b > .b)
string.slice(0, offset).indexOf(_selector) !== -1 && // no consecutive self refs (.b.b); that is a precedence boost and treated differently
string.slice(offset - _selector.length, offset) !== _selector) {
return "." + _componentId;
}
return match;
};
/**
* When writing a style like
*
* & + & {
* color: red;
* }
*
* The second ampersand should be a reference to the static component class. stylis
* has no knowledge of static class so we have to intelligently replace the base selector.
*
* https://github.com/thysultan/stylis.js#plugins <- more info about the context phase values
* "2" means this plugin is taking effect at the very end after all other processing is complete
*/
var selfReferenceReplacementPlugin = function selfReferenceReplacementPlugin(context, _, selectors) {
if (context === 2 && selectors.length && selectors[0].lastIndexOf(_selector) > 0) {
// eslint-disable-next-line no-param-reassign
selectors[0] = selectors[0].replace(_selectorRegexp, selfReferenceReplacer);
}
};
stylis.use([].concat(plugins, [selfReferenceReplacementPlugin, parseRulesPlugin, returnRulesPlugin]));
return function stringifyRules(css, selector, prefix, componentId) {
if (componentId === void 0) {
componentId = '&';
}
var flatCSS = css.replace(COMMENT_REGEX, '');
var cssStr = selector && prefix ? prefix + " " + selector + " { " + flatCSS + " }" : flatCSS; // stylis has no concept of state to be passed to plugins
// but since JS is single=threaded, we can rely on that to ensure
// these properties stay in sync with the current stylis run
_componentId = componentId;
_selector = selector;
_selectorRegexp = new RegExp("\\" + _selector + "\\b", 'g');
return stylis(prefix || !selector ? '' : selector, cssStr);
};
}
//
/* eslint-disable camelcase, no-undef */
var getNonce = function getNonce() {
return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null;
};
//
var ELEMENT_TYPE = 1;
/* Node.ELEMENT_TYPE */
/** Find last style element if any inside target */
var findLastStyleTag = function findLastStyleTag(target) {
var childNodes = target.childNodes;
for (var i = childNodes.length; i >= 0; i--) {
var child = childNodes[i];
if (child && child.nodeType === ELEMENT_TYPE && child.hasAttribute(SC_ATTR)) {
return child;
}
}
return undefined;
};
/** Create a style element inside `target` or <head> after the last */
var makeStyleTag = function makeStyleTag(target) {
var head = document.head;
var parent = target || head;
var style = document.createElement('style');
var prevStyle = findLastStyleTag(parent);
var nextSibling = prevStyle !== undefined ? prevStyle.nextSibling : null;
style.setAttribute(SC_ATTR, SC_ATTR_ACTIVE);
style.setAttribute(SC_ATTR_VERSION, SC_VERSION);
var nonce = getNonce();
if (nonce) style.setAttribute('nonce', nonce);
parent.insertBefore(style, nextSibling);
return style;
};
/** Get the CSSStyleSheet instance for a given style element */
var getSheet = function getSheet(tag) {
if (tag.sheet) {
return tag.sheet;
} // Avoid Firefox quirk where the style element might not have a sheet property
var _document = document,
styleSheets = _document.styleSheets;
for (var i = 0, l = styleSheets.length; i < l; i++) {
var sheet = styleSheets[i];
if (sheet.ownerNode === tag) {
return sheet;
}
}
throw new TypeError("CSSStyleSheet could not be found on HTMLStyleElement");
};
//
/** Create a CSSStyleSheet-like tag depending on the environment */
var makeTag = function makeTag(_ref) {
var isServer = _ref.isServer,
useCSSOMInjection = _ref.useCSSOMInjection,
target = _ref.target;
if (isServer) {
return new VirtualTag(target);
} else if (useCSSOMInjection) {
return new CSSOMTag(target);
} else {
return new TextTag(target);
}
};
var CSSOMTag =
/*#__PURE__*/
function () {
function CSSOMTag(target) {
var element = this.element = makeStyleTag(target); // Avoid Edge bug where empty style elements don't create sheets
element.appendChild(document.createTextNode(''));
this.sheet = getSheet(element);
this.length = 0;
}
var _proto = CSSOMTag.prototype;
_proto.insertRule = function insertRule(index, rule) {
try {
this.sheet.insertRule(rule, index);
this.length++;
return true;
} catch (_error) {
return false;
}
};
_proto.deleteRule = function deleteRule(index) {
this.sheet.deleteRule(index);
this.length--;
};
_proto.getRule = function getRule(index) {
var rule = this.sheet.cssRules[index]; // Avoid IE11 quirk where cssText is inaccessible on some invalid rules
if (rule !== undefined && typeof rule.cssText === 'string') {
return rule.cssText;
} else {
return '';
}
};
return CSSOMTag;
}();
/** A Tag that emulates the CSSStyleSheet API but uses text nodes */
var TextTag =
/*#__PURE__*/
function () {
function TextTag(target) {
var element = this.element = makeStyleTag(target);
this.nodes = element.childNodes;
this.length = 0;
}
var _proto2 = TextTag.prototype;
_proto2.insertRule = function insertRule(index, rule) {
if (index <= this.length && index >= 0) {
var node = document.createTextNode(rule);
var refNode = this.nodes[index];
this.element.insertBefore(node, refNode || null);
this.length++;
return true;
} else {
return false;
}
};
_proto2.deleteRule = function deleteRule(index) {
this.element.removeChild(this.nodes[index]);
this.length--;
};
_proto2.getRule = function getRule(index) {
if (index < this.length) {
return this.nodes[index].textContent;
} else {
return '';
}
};
return TextTag;
}();
/** A completely virtual (server-side) Tag that doesn't manipulate the DOM */
var VirtualTag =
/*#__PURE__*/
function () {
function VirtualTag(_target) {
this.rules = [];
this.length = 0;
}
var _proto3 = VirtualTag.prototype;
_proto3.insertRule = function insertRule(index, rule) {
if (index <= this.length) {
this.rules.splice(index, 0, rule);
this.length++;
return true;
} else {
return false;
}
};
_proto3.deleteRule = function deleteRule(index) {
this.rules.splice(index, 1);
this.length--;
};
_proto3.getRule = function getRule(index) {
if (index < this.length) {
return this.rules[index];
} else {
return '';
}
};
return VirtualTag;
}();
//
/* eslint-disable no-use-before-define */
/** Create a GroupedTag with an underlying Tag implementation */
var makeGroupedTag = function makeGroupedTag(tag) {
return new DefaultGroupedTag(tag);
};
var BASE_SIZE = 1 << 8;
var DefaultGroupedTag =
/*#__PURE__*/
function () {
function DefaultGroupedTag(tag) {
this.groupSizes = new Uint32Array(BASE_SIZE);
this.length = BASE_SIZE;
this.tag = tag;
}
var _proto = DefaultGroupedTag.prototype;
_proto.indexOfGroup = function indexOfGroup(group) {
var index = 0;
for (var i = 0; i < group; i++) {
index += this.groupSizes[i];
}
return index;
};
_proto.insertRules = function insertRules(group, rules) {
if (group >= this.groupSizes.length) {
var oldBuffer = this.groupSizes;
var oldSize = oldBuffer.length;
var newSize = BASE_SIZE << (group / BASE_SIZE | 0);
this.groupSizes = new Uint32Array(newSize);
this.groupSizes.set(oldBuffer);
this.length = newSize;
for (var i = oldSize; i < newSize; i++) {
this.groupSizes[i] = 0;
}
}
var ruleIndex = this.indexOfGroup(group + 1);
for (var _i = 0, l = rules.length; _i < l; _i++) {
if (this.tag.insertRule(ruleIndex, rules[_i])) {
this.groupSizes[group]++;
ruleIndex++;
}
}
};
_proto.clearGroup = function clearGroup(group) {
if (group < this.length) {
var length = this.groupSizes[group];
var startIndex = this.indexOfGroup(group);
var endIndex = startIndex + length;
this.groupSizes[group] = 0;
for (var i = startIndex; i < endIndex; i++) {
this.tag.deleteRule(startIndex);
}
}
};
_proto.getGroup = function getGroup(group) {
var css = '';
if (group >= this.length || this.groupSizes[group] === 0) {
return css;
}
var length = this.groupSizes[group];
var startIndex = this.indexOfGroup(group);
var endIndex = startIndex + length;
for (var i = startIndex; i < endIndex; i++) {
css += this.tag.getRule(i) + "\n";
}
return css;
};
return DefaultGroupedTag;
}();
//
var groupIDRegister = new Map();
var reverseRegister = new Map();
var nextFreeGroup = 1;
var getGroupForId = function getGroupForId(id) {
if (groupIDRegister.has(id)) {
return groupIDRegister.get(id);
}
var group = nextFreeGroup++;
groupIDRegister.set(id, group);
reverseRegister.set(group, id);
return group;
};
var getIdForGroup = function getIdForGroup(group) {
return reverseRegister.get(group);
};
var setGroupForId = function setGroupForId(id, group) {
if (group >= nextFreeGroup) {
nextFreeGroup = group + 1;
}
groupIDRegister.set(id, group);
reverseRegister.set(group, id);
};
//
var PLAIN_RULE_TYPE = 1;
var SELECTOR = "style[" + SC_ATTR + "][" + SC_ATTR_VERSION + "=\"" + SC_VERSION + "\"]";
var MARKER_RE = new RegExp("^" + SC_ATTR + "\\.g(\\d+)\\[id=\"([\\w\\d-]+)\"\\]");
var outputSheet = function outputSheet(sheet) {
var tag = sheet.getTag();
var length = tag.length;
var css = '';
for (var group = 0; group < length; group++) {
var id = getIdForGroup(group);
if (id === undefined) continue;
var names = sheet.names.get(id);
var rules = tag.getGroup(group);
if (names === undefined || rules.length === 0) continue;
var selector = SC_ATTR + ".g" + group + "[id=\"" + id + "\"]";
var content = '';
if (names !== undefined) {
names.forEach(function (name) {
if (name.length > 0) {
content += name + ",";
}
});
} // NOTE: It's easier to collect rules and have the marker
// after the actual rules to simplify the rehydration
css += "" + rules + selector + "{content:\"" + content + "\"}\n";
}
return css;
};
var rehydrateNamesFromContent = function rehydrateNamesFromContent(sheet, id, content) {
var names = content.slice(1, -1).split(',');
for (var i = 0, l = names.length; i < l; i++) {
var name = names[i];
if (name.length > 0) {
sheet.registerName(id, name);
}
}
};
var rehydrateSheetFromTag = function rehydrateSheetFromTag(sheet, style) {
var _getSheet = getSheet(style),
cssRules = _getSheet.cssRules;
var rules = [];
for (var i = 0, l = cssRules.length; i < l; i++) {
var cssRule = cssRules[i];
if (typeof cssRule.cssText !== 'string') {
// Avoid IE11 quirk where cssText is inaccessible on some invalid rules
continue;
} else if (cssRule.type !== PLAIN_RULE_TYPE) {
rules.push(cssRule.cssText);
} else {
var marker = cssRule.selectorText.match(MARKER_RE);
if (marker !== null) {
var group = parseInt(marker[1], 10) | 0;
var id = marker[2];
var content = cssRule.style.content;
if (group !== 0) {
// Rehydrate componentId to group index mapping
setGroupForId(id, group); // Rehydrate names and rules
rehydrateNamesFromContent(sheet, id, content);
sheet.getTag().insertRules(group, rules);
}
rules.length = 0;
} else {
rules.push(cssRule.cssText);
}
}
}
};
var rehydrateSheet = function rehydrateSheet(sheet) {
var nodes = document.querySelectorAll(SELECTOR);
for (var i = 0, l = nodes.length; i < l; i++) {
var node = nodes[i];
if (node && node.getAttribute(SC_ATTR) !== SC_ATTR_ACTIVE) {
rehydrateSheetFromTag(sheet, node);
if (node.parentNode) {
node.parentNode.removeChild(node);
}
}
}
};
var SHOULD_REHYDRATE = IS_BROWSER;
var defaultOptions = {
isServer: !IS_BROWSER,
stringifier: createStylisInstance(),
useCSSOMInjection: !DISABLE_SPEEDY
};
/** Contains the main stylesheet logic for stringification and caching */
var StyleSheet =
/*#__PURE__*/
function () {
/** Register a group ID to give it an index */
StyleSheet.registerId = function registerId(id) {
return getGroupForId(id);
};
function StyleSheet(options) {
if (options === void 0) {
options = defaultOptions;
}
this.options = _extends({}, defaultOptions, options);
this.names = new Map(); // We rehydrate only once and use the sheet that is
// created first
if (!this.options.isServer && IS_BROWSER && SHOULD_REHYDRATE) {
SHOULD_REHYDRATE = false;
rehydrateSheet(this);
}
}
var _proto = StyleSheet.prototype;
_proto.reconstructWithOptions = function reconstructWithOptions(options) {
return new StyleSheet(_extends({}, this.options, options));
}
/** Lazily initialises a GroupedTag for when it's actually needed */
;
_proto.getTag = function getTag() {
return this.tag || (this.tag = makeGroupedTag(makeTag(this.options)));
}
/** Check whether a name is known for caching */
;
_proto.hasNameForId = function hasNameForId(id, name) {
return this.names.has(id) && this.names.get(id).has(name);
}
/** Mark a group's name as known for caching */
;
_proto.registerName = function registerName(id, name) {
getGroupForId(id);
if (!this.names.has(id)) {
var groupNames = new Set();
groupNames.add(name);
this.names.set(id, groupNames);
} else {
this.names.get(id).add(name);
}
}
/** Insert new rules which also marks the name as known */
;
_proto.insertRules = function insertRules(id, name, rules) {
this.registerName(id, name);
this.getTag().insertRules(getGroupForId(id), rules);
}
/** Clears all cached names for a given group ID */
;
_proto.clearNames = function clearNames(id) {
if (this.names.has(id)) {
this.names.get(id).clear();
}
}
/** Clears all rules for a given group ID */
;
_proto.clearRules = function clearRules(id) {
this.getTag().clearGroup(getGroupForId(id));
this.clearNames(id);
}
/** Clears the entire tag which deletes all rules but not its names */
;
_proto.clearTag = function clearTag() {
// NOTE: This does not clear the names, since it's only used during SSR
// so that we can continuously output only new rules
this.tag = undefined;
}
/** Outputs the current sheet as a CSS string with markers for SSR */
;
_proto.toString = function toString() {
return outputSheet(this);
};
return StyleSheet;
}();
//
var errorMap = {
"1": "Cannot create styled-component for component: %s.\n\n",
"2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n",
"3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n",
"4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n",
"5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n",
"6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n",
"7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n",
"8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n",
"9": "Missing document `<head>`\n\n",
"10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n",
"11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n",
"12": "It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper which ensures the styles are injected correctly. See https://www.styled-components.com/docs/api#css\n\n",
"13": "%s is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.\n"
};
//
var ERRORS = process.env.NODE_ENV !== 'production' ? errorMap : {};
/**
* super basic version of sprintf
*/
function format() {
var a = arguments.length <= 0 ? undefined : arguments[0];
var b = [];
for (var c = 1, len = arguments.length; c < len; c += 1) {
b.push(c < 0 || arguments.length <= c ? undefined : arguments[c]);
}
b.forEach(function (d) {
a = a.replace(/%[a-z]/, d);
});
return a;
}
/**
* Create an error file out of errors.md for development and a simple web link to the full errors
* in production mode.
*/
function throwStyledComponentsError(code) {
for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
if (process.env.NODE_ENV === 'production') {
throw new Error("An error occurred. See https://github.com/styled-components/styled-components/blob/master/packages/styled-components/src/utils/errors.md#" + code + " for more information." + (interpolations.length > 0 ? " Additional arguments: " + interpolations.join(', ') : ''));
} else {
throw new Error(format.apply(void 0, [ERRORS[code]].concat(interpolations)).trim());
}
}
//
var Keyframes =
/*#__PURE__*/
function () {
function Keyframes(name, stringifyArgs) {
var _this = this;
this.inject = function (styleSheet) {
if (!styleSheet.hasNameForId(_this.id, _this.name)) {
var _styleSheet$options;
styleSheet.insertRules(_this.id, _this.name, (_styleSheet$options = styleSheet.options).stringifier.apply(_styleSheet$options, _this.stringifyArgs));
}
};
this.toString = function () {
return throwStyledComponentsError(12, String(_this.name));
};
this.name = name;
this.id = "sc-keyframes-" + name;
this.stringifyArgs = stringifyArgs;
}
var _proto = Keyframes.prototype;
_proto.getName = function getName() {
return this.name;
};
return Keyframes;
}();
//
/**
* inlined version of
* https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js
*/
var uppercasePattern = /([A-Z])/g;
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
}
//
function addUnitIfNeeded(name, value) {
// https://github.com/amilajack/eslint-plugin-flowtype-errors/issues/133
// $FlowFixMe
if (value == null || typeof value === 'boolean' || value === '') {
return '';
}
if (typeof value === 'number' && value !== 0 && !(name in unitless)) {
return value + "px"; // Presumes implicit 'px' suffix for unitless numbers
}
return String(value).trim();
}
//
/**
* It's falsish not falsy because 0 is allowed.
*/
var isFalsish = function isFalsish(chunk) {
return chunk === undefined || chunk === null || chunk === false || chunk === '';
};
var objToCssArray = function objToCssArray(obj, prevKey) {
var rules = [];
var keys = Object.keys(obj);
keys.forEach(function (key) {
if (!isFalsish(obj[key])) {
if (isPlainObject(obj[key])) {
rules.push.apply(rules, objToCssArray(obj[key], key));
return rules;
} else if (isFunction(obj[key])) {
rules.push(hyphenateStyleName(key) + ":", obj[key], ';');
return rules;
}
rules.push(hyphenateStyleName(key) + ": " + addUnitIfNeeded(key, obj[key]) + ";");
}
return rules;
});
return prevKey ? [prevKey + " {"].concat(rules, ['}']) : rules;
};
function flatten(chunk, executionContext, styleSheet) {
if (Array.isArray(chunk)) {
var ruleSet = [];
for (var i = 0, len = chunk.length, result; i < len; i += 1) {
result = flatten(chunk[i], executionContext, styleSheet);
if (result === '') continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result);
}
return ruleSet;
}
if (isFalsish(chunk)) {
return '';
}
/* Handle other components */
if (isStyledComponent(chunk)) {
return "." + chunk.styledComponentId;
}
/* Either execute or defer the function */
if (isFunction(chunk)) {
if (isStatelessFunction(chunk) && executionContext) {
var _result = chunk(executionContext);
if (process.env.NODE_ENV !== 'production' && isElement(_result)) {
// eslint-disable-next-line no-console
console.warn(getComponentName(chunk) + " is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.");
}
return flatten(_result, executionContext, styleSheet);
} else return chunk;
}
if (chunk instanceof Keyframes) {
if (styleSheet) {
chunk.inject(styleSheet);
return chunk.getName();
} else return chunk;
}
/* Handle objects */
return isPlainObject(chunk) ? objToCssArray(chunk) : chunk.toString();
}
//
function css(styles) {
for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
if (isFunction(styles) || isPlainObject(styles)) {
// $FlowFixMe
return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations)));
} // $FlowFixMe
return flatten(interleave(styles, interpolations));
}
function constructWithOptions(componentConstructor, tag, options) {
if (options === void 0) {
options = EMPTY_OBJECT;
}
if (!isValidElementType(tag)) {
return throwStyledComponentsError(1, String(tag));
}
/* This is callable directly as a template function */
// $FlowFixMe: Not typed to avoid destructuring arguments
var templateFunction = function templateFunction() {
return componentConstructor(tag, options, css.apply(void 0, arguments));
};
/* If config methods are called, wrap up a new template function and merge options */
templateFunction.withConfig = function (config) {
return constructWithOptions(componentConstructor, tag, _extends({}, options, config));
};
/* Modify/inject new props at runtime */
templateFunction.attrs = function (attrs) {
return constructWithOptions(componentConstructor, tag, _extends({}, options, {
attrs: Array.prototype.concat(options.attrs, attrs).filter(Boolean)
}));
};
return templateFunction;
}
//
/* eslint-disable no-bitwise */
/* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised
* counterparts */
var charsLength = 52;
/* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */
var getAlphabeticChar = function getAlphabeticChar(code) {
return String.fromCharCode(code + (code > 25 ? 39 : 97));
};
/* input a number, usually a hash and convert it to base-52 */
function generateAlphabeticName(code) {
var name = '';
var x;
/* get a char and divide by alphabet-length */
for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) {
name = getAlphabeticChar(x % charsLength) + name;
}
return getAlphabeticChar(x % charsLength) + name;
}
//
// version of djb2 where we pretend that we're still looping over
// the same string
var phash = function phash(h, x) {
h = h | 0;
for (var i = 0, l = x.length | 0; i < l; i++) {
h = (h << 5) + h + x.charCodeAt(i);
}
return h;
}; // This is a djb2 hashing function
var hash = function hash(x) {
return phash(5381 | 0, x) >>> 0;
};
var hasher = function hasher(str) {
return generateAlphabeticName(hash(str));
};
//
function isStaticRules(rules) {
for (var i = 0; i < rules.length; i += 1) {
var rule = rules[i];
if (isFunction(rule) && !isStyledComponent(rule)) {
// functions are allowed to be static if they're just being
// used to get the classname of a nested styled component
return false;
}
}
return true;
}
//
/*
ComponentStyle is all the CSS-specific stuff, not
the React-specific stuff.
*/
var ComponentStyle =
/*#__PURE__*/
function () {
function ComponentStyle(rules, componentId) {
this.rules = rules;
this.staticRulesId = '';
this.isStatic = process.env.NODE_ENV === 'production' && isStaticRules(rules);
this.componentId = componentId;
this.baseHash = hash(componentId); // NOTE: This registers the componentId, which ensures a consistent order
// for this component's styles compared to others
StyleSheet.registerId(componentId);
}
/*
* Flattens a rule set into valid CSS
* Hashes it, wraps the whole chunk in a .hash1234 {}
* Returns the hash to be injected on render()
* */
var _proto = ComponentStyle.prototype;
_proto.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) {
var componentId = this.componentId;
if (this.isStatic) {
if (this.staticRulesId && styleSheet.hasNameForId(componentId, this.staticRulesId)) {
return this.staticRulesId;
}
var cssStatic = flatten(this.rules, executionContext, styleSheet).join('');
var name = generateAlphabeticName(phash(this.baseHash, cssStatic.length) >>> 0);
if (!styleSheet.hasNameForId(componentId, name)) {
var cssStaticFormatted = styleSheet.options.stringifier(cssStatic, "." + name, undefined, componentId);
styleSheet.insertRules(componentId, name, cssStaticFormatted);
}
this.staticRulesId = name;
return name;
} else {
var length = this.rules.length;
var dynamicHash = this.baseHash;
var i = 0;
var css = '';
for (i = 0; i < length; i++) {
var partRule = this.rules[i];
if (typeof partRule === 'string') {
css += partRule;
if (process.env.NODE_ENV !== 'production') dynamicHash = phash(dynamicHash, partRule + i);
} else {
var partChunk = flatten(partRule, executionContext, styleSheet);
var partString = Array.isArray(partChunk) ? partChunk.join('') : partChunk;
dynamicHash = phash(dynamicHash, partString + i);
css += partString;
}
}
var _name = generateAlphabeticName(dynamicHash >>> 0);
if (!styleSheet.hasNameForId(componentId, _name)) {
var cssFormatted = styleSheet.options.stringifier(css, "." + _name, undefined, componentId);
styleSheet.insertRules(componentId, _name, cssFormatted);
}
return _name;
}
};
return ComponentStyle;
}();
//
var LIMIT = 200;
var createWarnTooManyClasses = (function (displayName) {
var generatedClasses = {};
var warningSeen = false;
return function (className) {
if (!warningSeen) {
generatedClasses[className] = true;
if (Object.keys(generatedClasses).length >= LIMIT) {
// Unable to find latestRule in test environment.
/* eslint-disable no-console, prefer-template */
console.warn("Over " + LIMIT + " classes were generated for component " + displayName + ". This happens when some of the props you use for styling have many potential values and we need to make a new CSS class for each variant. Over time the stylesheet will grow and slow down your app.\n" + 'For these particular CSS rules with high dynamicity, consider using the attrs() method together with a style object.\n' + 'Example:\n' + ' const Component = styled.div.attrs(props => ({\n' + ' style: {\n' + ' background: props.background,\n' + ' },\n' + ' }))`width: 100%;`\n\n' + ' <Component />');
warningSeen = true;
generatedClasses = {};
}
}
};
});
//
var determineTheme = (function (props, providedTheme, defaultProps) {
if (defaultProps === void 0) {
defaultProps = EMPTY_OBJECT;
}
return props.theme !== defaultProps.theme && props.theme || providedTheme || defaultProps.theme;
});
//
var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g;
var dashesAtEnds = /(^-|-$)/g;
/**
* TODO: Explore using CSS.escape when it becomes more available
* in evergreen browsers.
*/
function escape(str) {
return str // Replace all possible CSS selectors
.replace(escapeRegex, '-') // Remove extraneous hyphens at the start and end
.replace(dashesAtEnds, '');
}
//
function isTag(target) {
return typeof target === 'string' && (process.env.NODE_ENV !== 'production' ? target.charAt(0) === target.charAt(0).toLowerCase() : true);
}
//
function generateDisplayName(target) {
// $FlowFixMe
return isTag(target) ? "styled." + target : "Styled(" + getComponentName(target) + ")";
}
var _TYPE_STATICS;
var REACT_STATICS = {
childContextTypes: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDerivedStateFromProps: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var TYPE_STATICS = (_TYPE_STATICS = {}, _TYPE_STATICS[ForwardRef] = {
$$typeof: true,
render: true
}, _TYPE_STATICS);
var defineProperty = Object.defineProperty,
getOwnPropertyNames = Object.getOwnPropertyNames,
_Object$getOwnPropert = Object.getOwnPropertySymbols,
getOwnPropertySymbols = _Object$getOwnPropert === void 0 ? function () {
return [];
} : _Object$getOwnPropert,
getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor,
getPrototypeOf = Object.getPrototypeOf,
objectPrototype = Object.prototype;
var arrayPrototype = Array.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
var keys = arrayPrototype.concat(getOwnPropertyNames(sourceComponent), // $FlowFixMe
getOwnPropertySymbols(sourceComponent));
var targetStatics = TYPE_STATICS[targetComponent.$$typeof] || REACT_STATICS;
var sourceStatics = TYPE_STATICS[sourceComponent.$$typeof] || REACT_STATICS;
var i = keys.length;
var descriptor;
var key; // eslint-disable-next-line no-plusplus
while (i--) {
key = keys[i];
if ( // $FlowFixMe
!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && // $FlowFixMe
!(targetStatics && targetStatics[key])) {
descriptor = getOwnPropertyDescriptor(sourceComponent, key);
if (descriptor) {
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {
/* fail silently */
}
}
}
}
return targetComponent;
}
return targetComponent;
}
var ThemeContext = React.createContext();
var ThemeConsumer = ThemeContext.Consumer;
function useMergedTheme(theme, outerTheme) {
if (isFunction(theme)) {
var mergedTheme = theme(outerTheme);
if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || typeof mergedTheme !== 'object')) {
return throwStyledComponentsError(7);
}
return mergedTheme;
}
if (theme === null || Array.isArray(theme) || typeof theme !== 'object') {
return throwStyledComponentsError(8);
}
return outerTheme ? _extends({}, outerTheme, theme) : theme;
}
/**
* Provide a theme to an entire react component tree via context
*/
function ThemeProvider(props) {
var outerTheme = useContext(ThemeContext); // NOTE: can't really memoize with props.theme as that'd cause incorrect memoization when it's a function
var themeContext = useMergedTheme(props.theme, outerTheme);
if (!props.children) {
return null;
}
return React.createElement(ThemeContext.Provider, {
value: themeContext
}, props.children);
}
//
var StyleSheetContext = React.createContext();
var StyleSheetConsumer = StyleSheetContext.Consumer;
var masterSheet = new StyleSheet();
function useStyleSheet() {
return useContext(StyleSheetContext) || masterSheet;
}
function StyleSheetManager(props) {
/**
* freeze the stylis modification props on initial mount since they rely on
* reference equality for the useMemo dependencies array and devs will
* likely not store the reference themselves to avoid this issue
*/
var _useState = useState({
disableVendorPrefixes: props.disableVendorPrefixes,
stylisPlugins: props.stylisPlugins
}),
_useState$ = _useState[0],
disableVendorPrefixes = _useState$.disableVendorPrefixes,
stylisPlugins = _useState$.stylisPlugins;
if (process.env.NODE_ENV !== 'production') {
if (!shallowequal(disableVendorPrefixes, props.disableVendorPrefixes)) {
// eslint-disable-next-line no-console
console.warn('disableVendorPrefixes is frozen on initial mount of StyleSheetManager. Changing this prop dynamically will have no effect.');
}
if (!shallowequal(stylisPlugins, props.stylisPlugins)) {
// eslint-disable-next-line no-console
console.warn('stylisPlugins are frozen on initial mount of StyleSheetManager. Changing this prop dynamically will have no effect.');
}
}
var styleSheet = useMemo(function () {
var sheet = masterSheet;
if (props.sheet) {
// eslint-disable-next-line prefer-destructuring
sheet = props.sheet;
} else if (props.target) {
sheet = sheet.reconstructWithOptions({
target: props.target
});
}
if (props.disableCSSOMInjection) {
sheet = sheet.reconstructWithOptions({
useCSSOMInjection: false
});
}
if (disableVendorPrefixes || stylisPlugins) {
sheet = sheet.reconstructWithOptions({
stringifier: createStylisInstance({
options: {
prefix: !disableVendorPrefixes
},
plugins: stylisPlugins
})
});
}
return sheet;
}, [props.disableCSSOMInjection, props.sheet, disableVendorPrefixes, stylisPlugins, props.target]);
return React.createElement(StyleSheetContext.Provider, {
value: styleSheet
}, process.env.NODE_ENV !== 'production' ? React.Children.only(props.children) : props.children);
}
/* global $Call */
var THEME_PROP_R = /\.theme[.[]/;
var identifiers = {};
/* We depend on components having unique IDs */
function generateId(displayName, parentComponentId) {
var name = typeof displayName !== 'string' ? 'sc' : escape(displayName); // Ensure that no displayName can lead to duplicate componentIds
identifiers[name] = (identifiers[name] || 0) + 1;
var componentId = name + "-" + hasher(name + identifiers[name]);
return parentComponentId ? parentComponentId + "-" + componentId : componentId;
}
function useResolvedAttrs(theme, props, attrs) {
if (theme === void 0) {
theme = EMPTY_OBJECT;
}
// NOTE: can't memoize this
// returns [context, resolvedAttrs]
// where resolvedAttrs is only the things injected by the attrs themselves
var context = _extends({}, props, {
theme: theme
});
var resolvedAttrs = {};
attrs.forEach(function (attrDef) {
var resolvedAttrDef = attrDef;
var key;
if (isFunction(resolvedAttrDef)) {
resolvedAttrDef = resolvedAttrDef(context);
}
/* eslint-disable guard-for-in */
for (key in resolvedAttrDef) {
context[key] = resolvedAttrs[key] = resolvedAttrDef[key];
}
/* eslint-enable guard-for-in */
});
return [context, resolvedAttrs];
}
function useInjectedStyle(componentStyle, hasAttrs, resolvedAttrs, warnTooManyClasses) {
var styleSheet = useStyleSheet(); // statically styled-components don't need to build an execution context object,
// and shouldn't be increasing the number of class names
var isStatic = componentStyle.isStatic && !hasAttrs;
var className = isStatic ? componentStyle.generateAndInjectStyles(EMPTY_OBJECT, styleSheet) : componentStyle.generateAndInjectStyles(resolvedAttrs, styleSheet);
useDebugValue(className);
if (process.env.NODE_ENV !== 'production' && !isStatic && warnTooManyClasses) {
warnTooManyClasses(className);
}
return className;
}
function useStyledComponentImpl(forwardedComponent, props, forwardedRef) {
var componentAttrs = forwardedComponent.attrs,
componentStyle = forwardedComponent.componentStyle,
defaultProps = forwardedComponent.defaultProps,
foldedComponentIds = forwardedComponent.foldedComponentIds,
styledComponentId = forwardedComponent.styledComponentId,
target = forwardedComponent.target;
useDebugValue(styledComponentId); // NOTE: the non-hooks version only subscribes to this when !componentStyle.isStatic,
// but that'd be against the rules-of-hooks. We could be naughty and do it anyway as it
// should be an immutable value, but behave for now.
var theme = determineTheme(props, useContext(ThemeContext), defaultProps);
var _useResolvedAttrs = useResolvedAttrs(theme || EMPTY_OBJECT, props, componentAttrs),
context = _useResolvedAttrs[0],
attrs = _useResolvedAttrs[1];
var generatedClassName = useInjectedStyle(componentStyle, componentAttrs.length > 0, context, process.env.NODE_ENV !== 'production' ? forwardedComponent.warnTooManyClasses : undefined);
if (process.env.NODE_ENV !== 'production' && forwardedComponent.usesTheme && !theme) {
console.error("Component " + // $FlowFixMe
forwardedComponent.displayName + " (." + styledComponentId + ") uses \"props.theme\" in its styles but no theme was provided via prop or ThemeProvider."); // cheap way to do "once" ;)
// eslint-disable-next-line no-param-reassign
forwardedComponent.usesTheme = false;
}
var refToForward = forwardedRef;
var elementToBeCreated = props.as || attrs.as || target;
var isTargetTag = isTag(elementToBeCreated);
var computedProps = attrs !== props ? _extends({}, props, attrs) : props;
var shouldFilterProps = isTargetTag || 'as' in computedProps || 'forwardedAs' in computedProps;
var propsForElement = shouldFilterProps ? {} : _extends({}, computedProps);
if (shouldFilterProps) {
// eslint-disable-next-line guard-for-in
for (var key in computedProps) {
if (key === 'forwardedAs') {
propsForElement.as = computedProps[key];
} else if (key !== 'as' && key !== 'forwardedAs' && (!isTargetTag || validAttr(key))) {
// Don't pass through non HTML tags through to HTML elements
propsForElement[key] = computedProps[key];
}
}
}
if (props.style && attrs.style !== props.style) {
propsForElement.style = _extends({}, attrs.style, props.style);
}
propsForElement.className = Array.prototype.concat(foldedComponentIds, styledComponentId, generatedClassName !== styledComponentId ? generatedClassName : null, props.className, attrs.className).filter(Boolean).join(' ');
propsForElement.ref = refToForward;
return createElement(elementToBeCreated, propsForElement);
}
function createStyledComponent(target, options, rules) {
var isTargetStyledComp = isStyledComponent(target);
var isCompositeComponent = !isTag(target);
var _options$displayName = options.displayName,
displayName = _options$displayName === void 0 ? generateDisplayName(target) : _options$displayName,
_options$componentId = options.componentId,
componentId = _options$componentId === void 0 ? generateId(options.displayName, options.parentComponentId) : _options$componentId,
_options$attrs = options.attrs,
attrs = _options$attrs === void 0 ? EMPTY_ARRAY : _options$attrs;
var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + "-" + options.componentId : options.componentId || componentId; // fold the underlying StyledComponent attrs up (implicit extend)
var finalAttrs = // $FlowFixMe
isTargetStyledComp && target.attrs ? Array.prototype.concat(target.attrs, attrs).filter(Boolean) : attrs;
var componentStyle = new ComponentStyle(isTargetStyledComp ? // fold the underlying StyledComponent rules up (implicit extend)
// $FlowFixMe
target.componentStyle.rules.concat(rules) : rules, styledComponentId);
/**
* forwardRef creates a new interim component, which we'll take advantage of
* instead of extending ParentComponent to create _another_ interim class
*/
var WrappedStyledComponent; // eslint-disable-next-line react-hooks/rules-of-hooks
var forwardRef = function forwardRef(props, ref) {
return useStyledComponentImpl(WrappedStyledComponent, props, ref);
};
forwardRef.displayName = displayName; // $FlowFixMe this is a forced cast to merge it StyledComponentWrapperProperties
WrappedStyledComponent = React.forwardRef(forwardRef);
WrappedStyledComponent.attrs = finalAttrs;
WrappedStyledComponent.componentStyle = componentStyle;
WrappedStyledComponent.displayName = displayName; // this static is used to preserve the cascade of static classes for component selector
// purposes; this is especially important with usage of the css prop
WrappedStyledComponent.foldedComponentIds = isTargetStyledComp ? // $FlowFixMe
Array.prototype.concat(target.foldedComponentIds, target.styledComponentId) : EMPTY_ARRAY;
WrappedStyledComponent.styledComponentId = styledComponentId; // fold the underlying StyledComponent target up since we folded the styles
WrappedStyledComponent.target = isTargetStyledComp ? // $FlowFixMe
target.target : target; // $FlowFixMe
WrappedStyledComponent.withComponent = function withComponent(tag) {
var previousComponentId = options.componentId,
optionsToCopy = _objectWithoutPropertiesLoose(options, ["componentId"]);
var newComponentId = previousComponentId && previousComponentId + "-" + (isTag(tag) ? tag : escape(getComponentName(tag)));
var newOptions = _extends({}, optionsToCopy, {
attrs: finalAttrs,
componentId: newComponentId
});
return createStyledComponent(tag, newOptions, rules);
}; // $FlowFixMe
Object.defineProperty(WrappedStyledComponent, 'defaultProps', {
get: function get() {
return this._foldedDefaultProps;
},
set: function set(obj) {
// $FlowFixMe
this._foldedDefaultProps = isTargetStyledComp ? merge(target.defaultProps, obj) : obj;
}
});
if (process.env.NODE_ENV !== 'production') {
WrappedStyledComponent.usesTheme = componentStyle.rules.some(function (x) {
return isFunction(x) && THEME_PROP_R.test(x.toString());
});
WrappedStyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName);
} // $FlowFixMe
WrappedStyledComponent.toString = function () {
return "." + WrappedStyledComponent.styledComponentId;
};
if (isCompositeComponent) {
hoistNonReactStatics(WrappedStyledComponent, target, {
// all SC-specific things should not be hoisted
attrs: true,
componentStyle: true,
displayName: true,
foldedComponentIds: true,
self: true,
styledComponentId: true,
target: true,
withComponent: true
});
}
return WrappedStyledComponent;
}
//
// Thanks to ReactDOMFactories for this handy list!
var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG
'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'marker', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan'];
//
var styled = function styled(tag) {
return constructWithOptions(createStyledComponent, tag);
}; // Shorthands for all valid HTML Elements
domElements.forEach(function (domElement) {
styled[domElement] = styled(domElement);
});
//
var GlobalStyle =
/*#__PURE__*/
function () {
function GlobalStyle(rules, componentId) {
this.rules = rules;
this.componentId = componentId;
this.isStatic = isStaticRules(rules);
}
var _proto = GlobalStyle.prototype;
_proto.createStyles = function createStyles(instance, executionContext, styleSheet) {
var flatCSS = flatten(this.rules, executionContext, styleSheet);
var css = styleSheet.options.stringifier(flatCSS.join(''), '');
var id = this.componentId + instance; // NOTE: We use the id as a name as well, since these rules never change
styleSheet.insertRules(id, id, css);
};
_proto.removeStyles = function removeStyles(instance, styleSheet) {
styleSheet.clearRules(this.componentId + instance);
};
_proto.renderStyles = function renderStyles(instance, executionContext, styleSheet) {
StyleSheet.registerId(this.componentId + instance); // NOTE: Remove old styles, then inject the new ones
this.removeStyles(instance, styleSheet);
this.createStyles(instance, executionContext, styleSheet);
};
return GlobalStyle;
}();
function createGlobalStyle(strings) {
for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
var rules = css.apply(void 0, [strings].concat(interpolations));
var styledComponentId = "sc-global-" + hasher(JSON.stringify(rules));
var globalStyle = new GlobalStyle(rules, styledComponentId);
var count = 0;
function GlobalStyleComponent(props) {
var styleSheet = useStyleSheet();
var theme = useContext(ThemeContext);
var instance = useMemo(function () {
return String(++count);
}, []);
if (process.env.NODE_ENV !== 'production' && React.Children.count(props.children)) {
// eslint-disable-next-line no-console
console.warn("The global style component " + styledComponentId + " was given child JSX. createGlobalStyle does not render children.");
}
if (globalStyle.isStatic) {
globalStyle.renderStyles(instance, STATIC_EXECUTION_CONTEXT, styleSheet);
} else {
var context = _extends({}, props, {
theme: determineTheme(props, theme, GlobalStyleComponent.defaultProps)
});
globalStyle.renderStyles(instance, context, styleSheet);
}
useEffect(function () {
return function () {
return globalStyle.removeStyles(instance, styleSheet);
};
}, []);
return null;
} // $FlowFixMe
return React.memo(GlobalStyleComponent);
}
//
function keyframes(strings) {
/* Warning if you've used keyframes on React Native */
if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
// eslint-disable-next-line no-console
console.warn('`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.');
}
for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
var rules = css.apply(void 0, [strings].concat(interpolations)).join('');
var name = hasher(rules);
return new Keyframes(name, [rules, name, '@keyframes']);
}
var ServerStyleSheet =
/*#__PURE__*/
function () {
function ServerStyleSheet() {
var _this = this;
this._emitSheetCSS = function () {
var css = _this.instance.toString();
var nonce = getNonce();
var attrs = [nonce && "nonce=\"" + nonce + "\"", SC_ATTR, SC_ATTR_VERSION + "=\"" + SC_VERSION + "\""];
var htmlAttr = attrs.filter(Boolean).join(' ');
return "<style " + htmlAttr + ">" + css + "</style>";
};
this.getStyleTags = function () {
if (_this.sealed) {
return throwStyledComponentsError(2);
}
return _this._emitSheetCSS();
};
this.getStyleElement = function () {
var _props;
if (_this.sealed) {
return throwStyledComponentsError(2);
}
var props = (_props = {}, _props[SC_ATTR] = '', _props[SC_ATTR_VERSION] = SC_VERSION, _props.dangerouslySetInnerHTML = {
__html: _this.instance.toString()
}, _props);
var nonce = getNonce();
if (nonce) {
props.nonce = nonce;
} // v4 returned an array for this fn, so we'll do the same for v5 for backward compat
return [React.createElement("style", _extends({}, props, {
key: "sc-0-0"
}))];
};
this.seal = function () {
_this.sealed = true;
};
this.instance = new StyleSheet({
isServer: true
});
this.sealed = false;
}
var _proto = ServerStyleSheet.prototype;
_proto.collectStyles = function collectStyles(children) {
if (this.sealed) {
return throwStyledComponentsError(2);
}
return React.createElement(StyleSheetManager, {
sheet: this.instance
}, children);
};
// eslint-disable-next-line consistent-return
_proto.interleaveWithNodeStream = function interleaveWithNodeStream(input) {
{
return throwStyledComponentsError(3);
}
};
return ServerStyleSheet;
}();
// export default <Config: { theme?: any }, Instance>(
// Component: AbstractComponent<Config, Instance>
// ): AbstractComponent<$Diff<Config, { theme?: any }> & { theme?: any }, Instance>
//
// but the old build system tooling doesn't support the syntax
var withTheme = (function (Component) {
// $FlowFixMe This should be React.forwardRef<Config, Instance>
var WithTheme = React.forwardRef(function (props, ref) {
var theme = useContext(ThemeContext); // $FlowFixMe defaultProps isn't declared so it can be inferrable
var defaultProps = Component.defaultProps;
var themeProp = determineTheme(props, theme, defaultProps);
if (process.env.NODE_ENV !== 'production' && themeProp === undefined) {
// eslint-disable-next-line no-console
console.warn("[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class \"" + getComponentName(Component) + "\"");
}
return React.createElement(Component, _extends({}, props, {
theme: themeProp,
ref: ref
}));
});
hoistNonReactStatics(WithTheme, Component);
WithTheme.displayName = "WithTheme(" + getComponentName(Component) + ")";
return WithTheme;
});
//
var useTheme = function useTheme() {
var outerTheme = useContext(ThemeContext);
return outerTheme;
};
//
var __PRIVATE__ = {
StyleSheet: StyleSheet,
masterSheet: masterSheet
};
//
//
export default styled;
export { ServerStyleSheet, StyleSheetConsumer, StyleSheetContext, StyleSheetManager, ThemeConsumer, ThemeContext, ThemeProvider, __PRIVATE__, createGlobalStyle, css, isStyledComponent, keyframes, useTheme, withTheme };
//# sourceMappingURL=styled-components.browser.esm.js.map
|
/*
* /MathJax-v2/localization/ce/HTML-CSS.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Localization.addTranslation("ce","HTML-CSS",{version:"2.7.9",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/ce/HTML-CSS.js");
|
/*!
* DevExtreme (dx.messages.fi.js)
* Version: 20.2.4
* Build date: Tue Dec 01 2020
*
* Copyright (c) 2012 - 2020 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
"use strict";
! function(root, factory) {
if ("function" === typeof define && define.amd) {
define(function(require) {
factory(require("devextreme/localization"))
})
} else {
if ("object" === typeof module && module.exports) {
factory(require("devextreme/localization"))
} else {
factory(DevExpress.localization)
}
}
}(this, function(localization) {
localization.loadMessages({
fi: {
Yes: "Kyll\xe4",
No: "Ei",
Cancel: "Peruuta",
Clear: "Tyhjenn\xe4",
Done: "Valmis",
Loading: "Ladataan...",
Select: "Valitse...",
Search: "Haku",
Back: "Takaisin",
OK: "OK",
"dxCollectionWidget-noDataText": "Ei n\xe4ytett\xe4vi\xe4 tietoja",
"dxDropDownEditor-selectLabel": "Valitse",
"validation-required": "Pakollinen",
"validation-required-formatted": "{0} on pakollinen",
"validation-numeric": "Arvon on oltava luku",
"validation-numeric-formatted": "{0} on oltava luku",
"validation-range": "Arvo on alueen ulkopuolella",
"validation-range-formatted": "{0} on alueen ulkopuolella",
"validation-stringLength": "Arvon pituus ei ole oikein",
"validation-stringLength-formatted": "Arvolla {0} on v\xe4\xe4r\xe4 pituus",
"validation-custom": "Arvo on virheellinen",
"validation-custom-formatted": "{0} on virheellinen",
"validation-async": "Arvo on virheellinen",
"validation-async-formatted": "{0} on virheellinen",
"validation-compare": "Arvot eiv\xe4t t\xe4sm\xe4\xe4",
"validation-compare-formatted": "{0} eiv\xe4t t\xe4sm\xe4\xe4",
"validation-pattern": "Arvo ei vastaa mallia",
"validation-pattern-formatted": "{0} ei vastaa mallia",
"validation-email": "S\xe4hk\xf6postiosoite on virheellinen",
"validation-email-formatted": "{0} on virheellinen",
"validation-mask": "Arvo on virheellinen",
"dxLookup-searchPlaceholder": "Merkkien v\xe4himm\xe4ism\xe4\xe4r\xe4: {0}",
"dxList-pullingDownText": "P\xe4ivit\xe4 vet\xe4m\xe4ll\xe4 alas...",
"dxList-pulledDownText": "P\xe4ivit\xe4 vapauttamalla...",
"dxList-refreshingText": "P\xe4ivitet\xe4\xe4n...",
"dxList-pageLoadingText": "Ladataan...",
"dxList-nextButtonText": "Lis\xe4\xe4",
"dxList-selectAll": "Valitse kaikki",
"dxListEditDecorator-delete": "Poista",
"dxListEditDecorator-more": "Lis\xe4\xe4",
"dxScrollView-pullingDownText": "P\xe4ivit\xe4 vet\xe4m\xe4ll\xe4 alas...",
"dxScrollView-pulledDownText": "P\xe4ivit\xe4 vapauttamalla...",
"dxScrollView-refreshingText": "P\xe4ivitet\xe4\xe4n...",
"dxScrollView-reachBottomText": "Ladataan...",
"dxDateBox-simulatedDataPickerTitleTime": "Valitse kellonaika",
"dxDateBox-simulatedDataPickerTitleDate": "Valitse p\xe4iv\xe4m\xe4\xe4r\xe4",
"dxDateBox-simulatedDataPickerTitleDateTime": "Valitse p\xe4iv\xe4m\xe4\xe4r\xe4 ja kellonaika",
"dxDateBox-validation-datetime": "Arvon on oltava p\xe4iv\xe4ys tai aika",
"dxFileUploader-selectFile": "Valitse tiedosto",
"dxFileUploader-dropFile": "tai ved\xe4 ja pudota tiedosto t\xe4h\xe4n",
"dxFileUploader-bytes": "tavua",
"dxFileUploader-kb": "kt",
"dxFileUploader-Mb": "Mt",
"dxFileUploader-Gb": "Gt",
"dxFileUploader-upload": "L\xe4het\xe4",
"dxFileUploader-uploaded": "L\xe4hetetty",
"dxFileUploader-readyToUpload": "Valmis l\xe4hetett\xe4v\xe4ksi",
"dxFileUploader-uploadAbortedMessage": "TODO",
"dxFileUploader-uploadFailedMessage": "L\xe4hetys ep\xe4onnistui",
"dxFileUploader-invalidFileExtension": "",
"dxFileUploader-invalidMaxFileSize": "",
"dxFileUploader-invalidMinFileSize": "",
"dxRangeSlider-ariaFrom": "Alkaen",
"dxRangeSlider-ariaTill": "Asti",
"dxSwitch-switchedOnText": "P\xc4\xc4LLE",
"dxSwitch-switchedOffText": "POIS",
"dxForm-optionalMark": "valinnainen",
"dxForm-requiredMessage": "{0} on pakollinen",
"dxNumberBox-invalidValueMessage": "Arvon on oltava numero",
"dxNumberBox-noDataText": "Ei dataa",
"dxDataGrid-columnChooserTitle": "Sarakkeenvalitsin",
"dxDataGrid-columnChooserEmptyText": "Ved\xe4 sarake t\xe4\xe4ll\xe4 piilottaa sen",
"dxDataGrid-groupContinuesMessage": "Jatkuu seuraavalla sivulla",
"dxDataGrid-groupContinuedMessage": "Jatkoa edelliselt\xe4 sivulta",
"dxDataGrid-groupHeaderText": "Ryhmittele t\xe4m\xe4n sarakkeen mukaan",
"dxDataGrid-ungroupHeaderText": "Poista ryhmittely",
"dxDataGrid-ungroupAllText": "Poista kaikki ryhmittym\xe4t",
"dxDataGrid-editingEditRow": "Muokkaa",
"dxDataGrid-editingSaveRowChanges": "Tallenna",
"dxDataGrid-editingCancelRowChanges": "Peruuta",
"dxDataGrid-editingDeleteRow": "Poista",
"dxDataGrid-editingUndeleteRow": "Palauta",
"dxDataGrid-editingConfirmDeleteMessage": "Oletko varma, ett\xe4 haluat poistaa t\xe4m\xe4n tietueen?",
"dxDataGrid-validationCancelChanges": "Peruuta muutokset",
"dxDataGrid-groupPanelEmptyText": "Ved\xe4 sarakeotsikko t\xe4h\xe4n, jos haluat ryhmitell\xe4 kyseisen sarakkeen mukaan",
"dxDataGrid-noDataText": "Ei dataa",
"dxDataGrid-searchPanelPlaceholder": "Haku...",
"dxDataGrid-filterRowShowAllText": "(Kaikki)",
"dxDataGrid-filterRowResetOperationText": "Palauta",
"dxDataGrid-filterRowOperationEquals": "Yht\xe4 suuri kuin",
"dxDataGrid-filterRowOperationNotEquals": "Eri suuri kuin",
"dxDataGrid-filterRowOperationLess": "Pienempi kuin",
"dxDataGrid-filterRowOperationLessOrEquals": "Pienempi tai yht\xe4 suuri kuin",
"dxDataGrid-filterRowOperationGreater": "Suurempi kuin",
"dxDataGrid-filterRowOperationGreaterOrEquals": "Suurempi tai yht\xe4 suuri kuin",
"dxDataGrid-filterRowOperationStartsWith": "Alkaa merkeill\xe4",
"dxDataGrid-filterRowOperationContains": "Sis\xe4lt\xe4\xe4",
"dxDataGrid-filterRowOperationNotContains": "Ei sis\xe4ll\xe4",
"dxDataGrid-filterRowOperationEndsWith": "Loppuu merkeill\xe4",
"dxDataGrid-filterRowOperationBetween": "V\xe4lill\xe4",
"dxDataGrid-filterRowOperationBetweenStartText": "Alkaa",
"dxDataGrid-filterRowOperationBetweenEndText": "Loppu",
"dxDataGrid-applyFilterText": "K\xe4yt\xe4 suodatinta",
"dxDataGrid-trueText": "tosi",
"dxDataGrid-falseText": "ep\xe4tosi",
"dxDataGrid-sortingAscendingText": "Lajittele nouseva",
"dxDataGrid-sortingDescendingText": "Lajittele laskeva",
"dxDataGrid-sortingClearText": "Tyhjenn\xe4 lajittelu",
"dxDataGrid-editingSaveAllChanges": "Tallenna muutokset",
"dxDataGrid-editingCancelAllChanges": "Hylk\xe4\xe4 muutokset",
"dxDataGrid-editingAddRow": "Lis\xe4\xe4 rivi",
"dxDataGrid-summaryMin": "Min: {0}",
"dxDataGrid-summaryMinOtherColumn": "Min {1} on {0}",
"dxDataGrid-summaryMax": "Max: {0}",
"dxDataGrid-summaryMaxOtherColumn": "Max {1} on {0}",
"dxDataGrid-summaryAvg": "Keskiarvo: {0}",
"dxDataGrid-summaryAvgOtherColumn": "Keskiarvo {1} on {0}",
"dxDataGrid-summarySum": "Summa: {0}",
"dxDataGrid-summarySumOtherColumn": "Summa {1} on {0}",
"dxDataGrid-summaryCount": "M\xe4\xe4r\xe4: {0}",
"dxDataGrid-columnFixingFix": "Kiinte\xe4t sarakkeet",
"dxDataGrid-columnFixingUnfix": "Poista kiinte\xe4t sarakkeet",
"dxDataGrid-columnFixingLeftPosition": "Vasemmalle",
"dxDataGrid-columnFixingRightPosition": "Oikealle",
"dxDataGrid-exportTo": "Vie",
"dxDataGrid-exportToExcel": "Vie Exceliin",
"dxDataGrid-exporting": "Vienti...",
"dxDataGrid-excelFormat": "Excel-tiedostot",
"dxDataGrid-selectedRows": "Valitut tietueet",
"dxDataGrid-exportSelectedRows": "Vie valitut tietueet",
"dxDataGrid-exportAll": "Vie kaikki tiedot",
"dxDataGrid-headerFilterEmptyValue": "(Tyhj\xe4t)",
"dxDataGrid-headerFilterOK": "OK",
"dxDataGrid-headerFilterCancel": "Peruuta",
"dxDataGrid-ariaColumn": "Sarake",
"dxDataGrid-ariaValue": "Arvo",
"dxDataGrid-ariaFilterCell": "Suodatinsolu",
"dxDataGrid-ariaCollapse": "Tiivist\xe4",
"dxDataGrid-ariaExpand": "Laajenna",
"dxDataGrid-ariaDataGrid": "Tietoruudukko",
"dxDataGrid-ariaSearchInGrid": "Hae tietorivilt\xe4",
"dxDataGrid-ariaSelectAll": "Valitse kaikki",
"dxDataGrid-ariaSelectRow": "Valitse rivi",
"dxDataGrid-filterBuilderPopupTitle": "Suodattimen muodostin",
"dxDataGrid-filterPanelCreateFilter": "Luo suodatin",
"dxDataGrid-filterPanelClearFilter": "Tyhjenn\xe4",
"dxDataGrid-filterPanelFilterEnabledHint": "Ota suodatin k\xe4ytt\xf6\xf6n",
"dxTreeList-ariaTreeList": "Puu",
"dxTreeList-editingAddRowToNode": "Lis\xe4\xe4",
"dxPager-infoText": "Sivu {0}/{1} ({2} kohdetta)",
"dxPager-pagesCountText": "/",
"dxPager-pageSizesAllText": "Kaikki",
"dxPivotGrid-grandTotal": "Loppusumma",
"dxPivotGrid-total": "{0} Summa",
"dxPivotGrid-fieldChooserTitle": "Kent\xe4n valitseminen",
"dxPivotGrid-showFieldChooser": "Avaa kent\xe4n valitsemistoiminto",
"dxPivotGrid-expandAll": "Laajenna kaikki",
"dxPivotGrid-collapseAll": "Tiivist\xe4 kaikki",
"dxPivotGrid-sortColumnBySummary": 'Lajittele "{0}" t\xe4h\xe4n sarakkeeseen',
"dxPivotGrid-sortRowBySummary": 'Lajittele "{0}" t\xe4m\xe4n rivin mukaan',
"dxPivotGrid-removeAllSorting": "Poista kaikki lajittelu",
"dxPivotGrid-dataNotAvailable": "Puuttuu",
"dxPivotGrid-rowFields": "Rivikent\xe4t",
"dxPivotGrid-columnFields": "Sarakekent\xe4t",
"dxPivotGrid-dataFields": "Tietokent\xe4t",
"dxPivotGrid-filterFields": "Suodatinkent\xe4t",
"dxPivotGrid-allFields": "Kaikki kent\xe4t",
"dxPivotGrid-columnFieldArea": "Pudota sarakekent\xe4t t\xe4h\xe4n",
"dxPivotGrid-dataFieldArea": "Pudota tietokent\xe4t t\xe4h\xe4n",
"dxPivotGrid-rowFieldArea": "Pudota rivikent\xe4t t\xe4h\xe4n",
"dxPivotGrid-filterFieldArea": "Pudota suodatinkent\xe4t t\xe4h\xe4n",
"dxScheduler-editorLabelTitle": "Aihe",
"dxScheduler-editorLabelStartDate": "Alkamisp\xe4iv\xe4",
"dxScheduler-editorLabelEndDate": "P\xe4\xe4ttymisp\xe4iv\xe4",
"dxScheduler-editorLabelDescription": "Kuvaus",
"dxScheduler-editorLabelRecurrence": "Toista",
"dxScheduler-openAppointment": "Avaa tapaaminen",
"dxScheduler-recurrenceNever": "Ei koskaan",
"dxScheduler-recurrenceMinutely": "Minutely",
"dxScheduler-recurrenceHourly": "Hourly",
"dxScheduler-recurrenceDaily": "P\xe4ivitt\xe4in",
"dxScheduler-recurrenceWeekly": "Viikoittain",
"dxScheduler-recurrenceMonthly": "Kuukausittain",
"dxScheduler-recurrenceYearly": "Vuosittain",
"dxScheduler-recurrenceRepeatEvery": "Joka",
"dxScheduler-recurrenceRepeatOn": "Repeat On",
"dxScheduler-recurrenceEnd": "Loppu",
"dxScheduler-recurrenceAfter": "J\xe4lkeen",
"dxScheduler-recurrenceOn": "Aika",
"dxScheduler-recurrenceRepeatMinutely": "minute(s)",
"dxScheduler-recurrenceRepeatHourly": "hour(s)",
"dxScheduler-recurrenceRepeatDaily": "p\xe4ivitt\xe4in",
"dxScheduler-recurrenceRepeatWeekly": "viikon v\xe4lein",
"dxScheduler-recurrenceRepeatMonthly": "kuukauden v\xe4lein",
"dxScheduler-recurrenceRepeatYearly": "vuosittain",
"dxScheduler-switcherDay": "P\xe4iv\xe4",
"dxScheduler-switcherWeek": "Viikko",
"dxScheduler-switcherWorkWeek": "Ty\xf6viikko",
"dxScheduler-switcherMonth": "Kuukausi",
"dxScheduler-switcherAgenda": "Esityslista",
"dxScheduler-switcherTimelineDay": "Aikajana p\xe4iv\xe4",
"dxScheduler-switcherTimelineWeek": "Aikajana viikko",
"dxScheduler-switcherTimelineWorkWeek": "Aikajana ty\xf6viikko",
"dxScheduler-switcherTimelineMonth": "Aikajana kuukausi",
"dxScheduler-recurrenceRepeatOnDate": "p\xe4iv\xe4m\xe4\xe4r\xe4ll\xe4",
"dxScheduler-recurrenceRepeatCount": "esiintymi\xe4",
"dxScheduler-allDay": "Koko p\xe4iv\xe4",
"dxScheduler-confirmRecurrenceEditMessage": "Haluatko muokata vain t\xe4m\xe4n tapaamisen tai koko sarja?",
"dxScheduler-confirmRecurrenceDeleteMessage": "Haluatko poistaa vain t\xe4m\xe4n tapaamisen tai koko sarja?",
"dxScheduler-confirmRecurrenceEditSeries": "Muokkaa sarjaa",
"dxScheduler-confirmRecurrenceDeleteSeries": "Poista sarja",
"dxScheduler-confirmRecurrenceEditOccurrence": "Muokkaa tapaaminen",
"dxScheduler-confirmRecurrenceDeleteOccurrence": "Poista tapaaminen",
"dxScheduler-noTimezoneTitle": "Ei aikavy\xf6hyke",
"dxScheduler-moreAppointments": "{0} lis\xe4\xe4",
"dxCalendar-todayButtonText": "T\xe4n\xe4\xe4n",
"dxCalendar-ariaWidgetName": "Kalenteri",
"dxColorView-ariaRed": "Punainen",
"dxColorView-ariaGreen": "Vihre\xe4",
"dxColorView-ariaBlue": "Sininen",
"dxColorView-ariaAlpha": "L\xe4pin\xe4kyvyys",
"dxColorView-ariaHex": "V\xe4rikoodi",
"dxTagBox-selected": "{0} valittu",
"dxTagBox-allSelected": "Kaikki valitut ({0})",
"dxTagBox-moreSelected": "{0} lis\xe4\xe4",
"vizExport-printingButtonText": "Tulosta",
"vizExport-titleMenuText": "Vienti/Tulostus",
"vizExport-exportButtonText": "{0} tiedosto",
"dxFilterBuilder-and": "Ja",
"dxFilterBuilder-or": "Tai",
"dxFilterBuilder-notAnd": "Ei ja",
"dxFilterBuilder-notOr": "Ei tai",
"dxFilterBuilder-addCondition": "Lis\xe4\xe4 ehto",
"dxFilterBuilder-addGroup": "Lis\xe4\xe4 ryhm\xe4",
"dxFilterBuilder-enterValueText": "<anna arvo>",
"dxFilterBuilder-filterOperationEquals": "On sama kuin",
"dxFilterBuilder-filterOperationNotEquals": "Ei ole sama kuin",
"dxFilterBuilder-filterOperationLess": "Pienempi kuin",
"dxFilterBuilder-filterOperationLessOrEquals": "Pienempi tai yht\xe4 suuri kuin",
"dxFilterBuilder-filterOperationGreater": "Suurempi kuin",
"dxFilterBuilder-filterOperationGreaterOrEquals": "Suurempi tai yht\xe4 suuri kuin",
"dxFilterBuilder-filterOperationStartsWith": "Alkaa merkill\xe4",
"dxFilterBuilder-filterOperationContains": "Sis\xe4lt\xe4\xe4",
"dxFilterBuilder-filterOperationNotContains": "Ei sis\xe4ll\xe4",
"dxFilterBuilder-filterOperationEndsWith": "Loppuu merkill\xe4",
"dxFilterBuilder-filterOperationIsBlank": "On tyhj\xe4",
"dxFilterBuilder-filterOperationIsNotBlank": "Ei ole tyhj\xe4",
"dxFilterBuilder-filterOperationBetween": "V\xe4lill\xe4",
"dxFilterBuilder-filterOperationAnyOf": "Joku n\xe4ist\xe4",
"dxFilterBuilder-filterOperationNoneOf": "Ei mik\xe4\xe4n n\xe4ist\xe4",
"dxHtmlEditor-dialogColorCaption": "!TODO!",
"dxHtmlEditor-dialogBackgroundCaption": "!TODO!",
"dxHtmlEditor-dialogLinkCaption": "!TODO!",
"dxHtmlEditor-dialogLinkUrlField": "!TODO!",
"dxHtmlEditor-dialogLinkTextField": "!TODO!",
"dxHtmlEditor-dialogLinkTargetField": "!TODO!",
"dxHtmlEditor-dialogImageCaption": "!TODO!",
"dxHtmlEditor-dialogImageUrlField": "!TODO!",
"dxHtmlEditor-dialogImageAltField": "!TODO!",
"dxHtmlEditor-dialogImageWidthField": "!TODO!",
"dxHtmlEditor-dialogImageHeightField": "!TODO!",
"dxHtmlEditor-dialogInsertTableRowsField": "!TODO",
"dxHtmlEditor-dialogInsertTableColumnsField": "!TODO",
"dxHtmlEditor-dialogInsertTableCaption": "!TODO",
"dxHtmlEditor-heading": "!TODO!",
"dxHtmlEditor-normalText": "!TODO!",
"dxFileManager-newDirectoryName": "TODO",
"dxFileManager-rootDirectoryName": "TODO",
"dxFileManager-errorNoAccess": "TODO",
"dxFileManager-errorDirectoryExistsFormat": "TODO",
"dxFileManager-errorFileExistsFormat": "TODO",
"dxFileManager-errorFileNotFoundFormat": "TODO",
"dxFileManager-errorDirectoryNotFoundFormat": "TODO",
"dxFileManager-errorWrongFileExtension": "TODO",
"dxFileManager-errorMaxFileSizeExceeded": "TODO",
"dxFileManager-errorInvalidSymbols": "TODO",
"dxFileManager-errorDefault": "TODO",
"dxFileManager-errorDirectoryOpenFailed": "TODO",
"dxDiagram-categoryGeneral": "TODO",
"dxDiagram-categoryFlowchart": "TODO",
"dxDiagram-categoryOrgChart": "TODO",
"dxDiagram-categoryContainers": "TODO",
"dxDiagram-categoryCustom": "TODO",
"dxDiagram-commandExportToSvg": "TODO",
"dxDiagram-commandExportToPng": "TODO",
"dxDiagram-commandExportToJpg": "TODO",
"dxDiagram-commandUndo": "TODO",
"dxDiagram-commandRedo": "TODO",
"dxDiagram-commandFontName": "TODO",
"dxDiagram-commandFontSize": "TODO",
"dxDiagram-commandBold": "TODO",
"dxDiagram-commandItalic": "TODO",
"dxDiagram-commandUnderline": "TODO",
"dxDiagram-commandTextColor": "TODO",
"dxDiagram-commandLineColor": "TODO",
"dxDiagram-commandLineWidth": "TODO",
"dxDiagram-commandLineStyle": "TODO",
"dxDiagram-commandLineStyleSolid": "TODO",
"dxDiagram-commandLineStyleDotted": "TODO",
"dxDiagram-commandLineStyleDashed": "TODO",
"dxDiagram-commandFillColor": "TODO",
"dxDiagram-commandAlignLeft": "TODO",
"dxDiagram-commandAlignCenter": "TODO",
"dxDiagram-commandAlignRight": "TODO",
"dxDiagram-commandConnectorLineType": "TODO",
"dxDiagram-commandConnectorLineStraight": "TODO",
"dxDiagram-commandConnectorLineOrthogonal": "TODO",
"dxDiagram-commandConnectorLineStart": "TODO",
"dxDiagram-commandConnectorLineEnd": "TODO",
"dxDiagram-commandConnectorLineNone": "TODO",
"dxDiagram-commandConnectorLineArrow": "TODO",
"dxDiagram-commandFullscreen": "TODO",
"dxDiagram-commandUnits": "TODO",
"dxDiagram-commandPageSize": "TODO",
"dxDiagram-commandPageOrientation": "TODO",
"dxDiagram-commandPageOrientationLandscape": "TODO",
"dxDiagram-commandPageOrientationPortrait": "TODO",
"dxDiagram-commandPageColor": "TODO",
"dxDiagram-commandShowGrid": "TODO",
"dxDiagram-commandSnapToGrid": "TODO",
"dxDiagram-commandGridSize": "TODO",
"dxDiagram-commandZoomLevel": "TODO",
"dxDiagram-commandAutoZoom": "TODO",
"dxDiagram-commandFitToContent": "TODO",
"dxDiagram-commandFitToWidth": "TODO",
"dxDiagram-commandAutoZoomByContent": "TODO",
"dxDiagram-commandAutoZoomByWidth": "TODO",
"dxDiagram-commandSimpleView": "TODO",
"dxDiagram-commandCut": "TODO",
"dxDiagram-commandCopy": "TODO",
"dxDiagram-commandPaste": "TODO",
"dxDiagram-commandSelectAll": "TODO",
"dxDiagram-commandDelete": "TODO",
"dxDiagram-commandBringToFront": "TODO",
"dxDiagram-commandSendToBack": "TODO",
"dxDiagram-commandLock": "TODO",
"dxDiagram-commandUnlock": "TODO",
"dxDiagram-commandInsertShapeImage": "TODO",
"dxDiagram-commandEditShapeImage": "TODO",
"dxDiagram-commandDeleteShapeImage": "TODO",
"dxDiagram-commandLayoutLeftToRight": "TODO",
"dxDiagram-commandLayoutRightToLeft": "TODO",
"dxDiagram-commandLayoutTopToBottom": "TODO",
"dxDiagram-commandLayoutBottomToTop": "TODO",
"dxDiagram-unitIn": "TODO",
"dxDiagram-unitCm": "TODO",
"dxDiagram-unitPx": "TODO",
"dxDiagram-dialogButtonOK": "TODO",
"dxDiagram-dialogButtonCancel": "TODO",
"dxDiagram-dialogInsertShapeImageTitle": "TODO",
"dxDiagram-dialogEditShapeImageTitle": "TODO",
"dxDiagram-dialogEditShapeImageSelectButton": "TODO",
"dxDiagram-dialogEditShapeImageLabelText": "TODO",
"dxDiagram-uiExport": "TODO",
"dxDiagram-uiProperties": "TODO",
"dxDiagram-uiSettings": "TODO",
"dxDiagram-uiShowToolbox": "TODO",
"dxDiagram-uiSearch": "TODO",
"dxDiagram-uiStyle": "TODO",
"dxDiagram-uiLayout": "TODO",
"dxDiagram-uiLayoutTree": "TODO",
"dxDiagram-uiLayoutLayered": "TODO",
"dxDiagram-uiDiagram": "TODO",
"dxDiagram-uiText": "TODO",
"dxDiagram-uiObject": "TODO",
"dxDiagram-uiConnector": "TODO",
"dxDiagram-uiPage": "TODO",
"dxDiagram-shapeText": "TODO",
"dxDiagram-shapeRectangle": "TODO",
"dxDiagram-shapeEllipse": "TODO",
"dxDiagram-shapeCross": "TODO",
"dxDiagram-shapeTriangle": "TODO",
"dxDiagram-shapeDiamond": "TODO",
"dxDiagram-shapeHeart": "TODO",
"dxDiagram-shapePentagon": "TODO",
"dxDiagram-shapeHexagon": "TODO",
"dxDiagram-shapeOctagon": "TODO",
"dxDiagram-shapeStar": "TODO",
"dxDiagram-shapeArrowLeft": "TODO",
"dxDiagram-shapeArrowUp": "TODO",
"dxDiagram-shapeArrowRight": "TODO",
"dxDiagram-shapeArrowDown": "TODO",
"dxDiagram-shapeArrowUpDown": "TODO",
"dxDiagram-shapeArrowLeftRight": "TODO",
"dxDiagram-shapeProcess": "TODO",
"dxDiagram-shapeDecision": "TODO",
"dxDiagram-shapeTerminator": "TODO",
"dxDiagram-shapePredefinedProcess": "TODO",
"dxDiagram-shapeDocument": "TODO",
"dxDiagram-shapeMultipleDocuments": "TODO",
"dxDiagram-shapeManualInput": "TODO",
"dxDiagram-shapePreparation": "TODO",
"dxDiagram-shapeData": "TODO",
"dxDiagram-shapeDatabase": "TODO",
"dxDiagram-shapeHardDisk": "TODO",
"dxDiagram-shapeInternalStorage": "TODO",
"dxDiagram-shapePaperTape": "TODO",
"dxDiagram-shapeManualOperation": "TODO",
"dxDiagram-shapeDelay": "TODO",
"dxDiagram-shapeStoredData": "TODO",
"dxDiagram-shapeDisplay": "TODO",
"dxDiagram-shapeMerge": "TODO",
"dxDiagram-shapeConnector": "TODO",
"dxDiagram-shapeOr": "TODO",
"dxDiagram-shapeSummingJunction": "TODO",
"dxDiagram-shapeContainerDefaultText": "TODO",
"dxDiagram-shapeVerticalContainer": "TODO",
"dxDiagram-shapeHorizontalContainer": "TODO",
"dxDiagram-shapeCardDefaultText": "TODO",
"dxDiagram-shapeCardWithImageOnLeft": "TODO",
"dxDiagram-shapeCardWithImageOnTop": "TODO",
"dxDiagram-shapeCardWithImageOnRight": "TODO",
"dxGantt-dialogTitle": "TODO",
"dxGantt-dialogStartTitle": "TODO",
"dxGantt-dialogEndTitle": "TODO",
"dxGantt-dialogProgressTitle": "TODO",
"dxGantt-dialogResourcesTitle": "TODO",
"dxGantt-dialogResourceManagerTitle": "TODO",
"dxGantt-dialogTaskDetailsTitle": "TODO",
"dxGantt-dialogEditResourceListHint": "TODO",
"dxGantt-dialogEditNoResources": "TODO",
"dxGantt-dialogButtonAdd": "TODO",
"dxGantt-contextMenuNewTask": "TODO",
"dxGantt-contextMenuNewSubtask": "TODO",
"dxGantt-contextMenuDeleteTask": "TODO",
"dxGantt-contextMenuDeleteDependency": "TODO",
"dxGantt-dialogTaskDeleteConfirmation": "TODO",
"dxGantt-dialogDependencyDeleteConfirmation": "TODO",
"dxGantt-dialogResourcesDeleteConfirmation": "TODO",
"dxGantt-dialogConstraintCriticalViolationMessage": "TODO",
"dxGantt-dialogConstraintViolationMessage": "TODO",
"dxGantt-dialogCancelOperationMessage": "TODO",
"dxGantt-dialogDeleteDependencyMessage": "TODO",
"dxGantt-dialogMoveTaskAndKeepDependencyMessage": "TODO",
"dxGantt-undo": "TODO",
"dxGantt-redo": "TODO",
"dxGantt-expandAll": "TODO",
"dxGantt-collapseAll": "TODO",
"dxGantt-addNewTask": "TODO",
"dxGantt-deleteSelectedTask": "TODO",
"dxGantt-zoomIn": "TODO",
"dxGantt-zoomOut": "TODO",
"dxGantt-fullScreen": "TODO"
}
})
});
|
typeof window !== "undefined" &&
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["Hls"] = factory();
else
root["Hls"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/hls.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/eventemitter3/index.js":
/*!*********************************************!*\
!*** ./node_modules/eventemitter3/index.js ***!
\*********************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = Object.prototype.hasOwnProperty
, prefix = '~';
/**
* Constructor to create a storage for our `EE` objects.
* An `Events` instance is a plain object whose properties are event names.
*
* @constructor
* @private
*/
function Events() {}
//
// We try to not inherit from `Object.prototype`. In some engines creating an
// instance in this way is faster than calling `Object.create(null)` directly.
// If `Object.create(null)` is not supported we prefix the event names with a
// character to make sure that the built-in object properties are not
// overridden or used as an attack vector.
//
if (Object.create) {
Events.prototype = Object.create(null);
//
// This hack is needed because the `__proto__` property is still inherited in
// some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
//
if (!new Events().__proto__) prefix = false;
}
/**
* Representation of a single event listener.
*
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} [once=false] Specify if the listener is a one-time listener.
* @constructor
* @private
*/
function EE(fn, context, once) {
this.fn = fn;
this.context = context;
this.once = once || false;
}
/**
* Add a listener for a given event.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} context The context to invoke the listener with.
* @param {Boolean} once Specify if the listener is a one-time listener.
* @returns {EventEmitter}
* @private
*/
function addListener(emitter, event, fn, context, once) {
if (typeof fn !== 'function') {
throw new TypeError('The listener must be a function');
}
var listener = new EE(fn, context || emitter, once)
, evt = prefix ? prefix + event : event;
if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
else emitter._events[evt] = [emitter._events[evt], listener];
return emitter;
}
/**
* Clear event by name.
*
* @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
* @param {(String|Symbol)} evt The Event name.
* @private
*/
function clearEvent(emitter, evt) {
if (--emitter._eventsCount === 0) emitter._events = new Events();
else delete emitter._events[evt];
}
/**
* Minimal `EventEmitter` interface that is molded against the Node.js
* `EventEmitter` interface.
*
* @constructor
* @public
*/
function EventEmitter() {
this._events = new Events();
this._eventsCount = 0;
}
/**
* Return an array listing the events for which the emitter has registered
* listeners.
*
* @returns {Array}
* @public
*/
EventEmitter.prototype.eventNames = function eventNames() {
var names = []
, events
, name;
if (this._eventsCount === 0) return names;
for (name in (events = this._events)) {
if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
}
if (Object.getOwnPropertySymbols) {
return names.concat(Object.getOwnPropertySymbols(events));
}
return names;
};
/**
* Return the listeners registered for a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Array} The registered listeners.
* @public
*/
EventEmitter.prototype.listeners = function listeners(event) {
var evt = prefix ? prefix + event : event
, handlers = this._events[evt];
if (!handlers) return [];
if (handlers.fn) return [handlers.fn];
for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
ee[i] = handlers[i].fn;
}
return ee;
};
/**
* Return the number of listeners listening to a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Number} The number of listeners.
* @public
*/
EventEmitter.prototype.listenerCount = function listenerCount(event) {
var evt = prefix ? prefix + event : event
, listeners = this._events[evt];
if (!listeners) return 0;
if (listeners.fn) return 1;
return listeners.length;
};
/**
* Calls each of the listeners registered for a given event.
*
* @param {(String|Symbol)} event The event name.
* @returns {Boolean} `true` if the event had listeners, else `false`.
* @public
*/
EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};
/**
* Add a listener for a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.on = function on(event, fn, context) {
return addListener(this, event, fn, context, false);
};
/**
* Add a one-time listener for a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn The listener function.
* @param {*} [context=this] The context to invoke the listener with.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.once = function once(event, fn, context) {
return addListener(this, event, fn, context, true);
};
/**
* Remove the listeners of a given event.
*
* @param {(String|Symbol)} event The event name.
* @param {Function} fn Only remove the listeners that match this function.
* @param {*} context Only remove the listeners that have this context.
* @param {Boolean} once Only remove one-time listeners.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return this;
if (!fn) {
clearEvent(this, evt);
return this;
}
var listeners = this._events[evt];
if (listeners.fn) {
if (
listeners.fn === fn &&
(!once || listeners.once) &&
(!context || listeners.context === context)
) {
clearEvent(this, evt);
}
} else {
for (var i = 0, events = [], length = listeners.length; i < length; i++) {
if (
listeners[i].fn !== fn ||
(once && !listeners[i].once) ||
(context && listeners[i].context !== context)
) {
events.push(listeners[i]);
}
}
//
// Reset the array, or remove it completely if we have no more listeners.
//
if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
else clearEvent(this, evt);
}
return this;
};
/**
* Remove all listeners, or those of the specified event.
*
* @param {(String|Symbol)} [event] The event name.
* @returns {EventEmitter} `this`.
* @public
*/
EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
var evt;
if (event) {
evt = prefix ? prefix + event : event;
if (this._events[evt]) clearEvent(this, evt);
} else {
this._events = new Events();
this._eventsCount = 0;
}
return this;
};
//
// Alias methods names because people roll like that.
//
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
//
// Expose the prefix.
//
EventEmitter.prefixed = prefix;
//
// Allow `EventEmitter` to be imported as module namespace.
//
EventEmitter.EventEmitter = EventEmitter;
//
// Expose the module.
//
if (true) {
module.exports = EventEmitter;
}
/***/ }),
/***/ "./node_modules/url-toolkit/src/url-toolkit.js":
/*!*****************************************************!*\
!*** ./node_modules/url-toolkit/src/url-toolkit.js ***!
\*****************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
// see https://tools.ietf.org/html/rfc1808
(function (root) {
var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/;
var FIRST_SEGMENT_REGEX = /^([^\/?#]*)(.*)$/;
var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
var URLToolkit = {
// If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
// E.g
// With opts.alwaysNormalize = false (default, spec compliant)
// http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
// With opts.alwaysNormalize = true (not spec compliant)
// http://a.com/b/cd + /e/f/../g => http://a.com/e/g
buildAbsoluteURL: function (baseURL, relativeURL, opts) {
opts = opts || {};
// remove any remaining space and CRLF
baseURL = baseURL.trim();
relativeURL = relativeURL.trim();
if (!relativeURL) {
// 2a) If the embedded URL is entirely empty, it inherits the
// entire base URL (i.e., is set equal to the base URL)
// and we are done.
if (!opts.alwaysNormalize) {
return baseURL;
}
var basePartsForNormalise = URLToolkit.parseURL(baseURL);
if (!basePartsForNormalise) {
throw new Error('Error trying to parse base URL.');
}
basePartsForNormalise.path = URLToolkit.normalizePath(
basePartsForNormalise.path
);
return URLToolkit.buildURLFromParts(basePartsForNormalise);
}
var relativeParts = URLToolkit.parseURL(relativeURL);
if (!relativeParts) {
throw new Error('Error trying to parse relative URL.');
}
if (relativeParts.scheme) {
// 2b) If the embedded URL starts with a scheme name, it is
// interpreted as an absolute URL and we are done.
if (!opts.alwaysNormalize) {
return relativeURL;
}
relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
return URLToolkit.buildURLFromParts(relativeParts);
}
var baseParts = URLToolkit.parseURL(baseURL);
if (!baseParts) {
throw new Error('Error trying to parse base URL.');
}
if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
// If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
// This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
baseParts.netLoc = pathParts[1];
baseParts.path = pathParts[2];
}
if (baseParts.netLoc && !baseParts.path) {
baseParts.path = '/';
}
var builtParts = {
// 2c) Otherwise, the embedded URL inherits the scheme of
// the base URL.
scheme: baseParts.scheme,
netLoc: relativeParts.netLoc,
path: null,
params: relativeParts.params,
query: relativeParts.query,
fragment: relativeParts.fragment,
};
if (!relativeParts.netLoc) {
// 3) If the embedded URL's <net_loc> is non-empty, we skip to
// Step 7. Otherwise, the embedded URL inherits the <net_loc>
// (if any) of the base URL.
builtParts.netLoc = baseParts.netLoc;
// 4) If the embedded URL path is preceded by a slash "/", the
// path is not relative and we skip to Step 7.
if (relativeParts.path[0] !== '/') {
if (!relativeParts.path) {
// 5) If the embedded URL path is empty (and not preceded by a
// slash), then the embedded URL inherits the base URL path
builtParts.path = baseParts.path;
// 5a) if the embedded URL's <params> is non-empty, we skip to
// step 7; otherwise, it inherits the <params> of the base
// URL (if any) and
if (!relativeParts.params) {
builtParts.params = baseParts.params;
// 5b) if the embedded URL's <query> is non-empty, we skip to
// step 7; otherwise, it inherits the <query> of the base
// URL (if any) and we skip to step 7.
if (!relativeParts.query) {
builtParts.query = baseParts.query;
}
}
} else {
// 6) The last segment of the base URL's path (anything
// following the rightmost slash "/", or the entire path if no
// slash is present) is removed and the embedded URL's path is
// appended in its place.
var baseURLPath = baseParts.path;
var newPath =
baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +
relativeParts.path;
builtParts.path = URLToolkit.normalizePath(newPath);
}
}
}
if (builtParts.path === null) {
builtParts.path = opts.alwaysNormalize
? URLToolkit.normalizePath(relativeParts.path)
: relativeParts.path;
}
return URLToolkit.buildURLFromParts(builtParts);
},
parseURL: function (url) {
var parts = URL_REGEX.exec(url);
if (!parts) {
return null;
}
return {
scheme: parts[1] || '',
netLoc: parts[2] || '',
path: parts[3] || '',
params: parts[4] || '',
query: parts[5] || '',
fragment: parts[6] || '',
};
},
normalizePath: function (path) {
// The following operations are
// then applied, in order, to the new path:
// 6a) All occurrences of "./", where "." is a complete path
// segment, are removed.
// 6b) If the path ends with "." as a complete path segment,
// that "." is removed.
path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
// 6c) All occurrences of "<segment>/../", where <segment> is a
// complete path segment not equal to "..", are removed.
// Removal of these path segments is performed iteratively,
// removing the leftmost matching pattern on each iteration,
// until no matching pattern remains.
// 6d) If the path ends with "<segment>/..", where <segment> is a
// complete path segment not equal to "..", that
// "<segment>/.." is removed.
while (
path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length
) {}
return path.split('').reverse().join('');
},
buildURLFromParts: function (parts) {
return (
parts.scheme +
parts.netLoc +
parts.path +
parts.params +
parts.query +
parts.fragment
);
},
};
if (true)
module.exports = URLToolkit;
else {}
})(this);
/***/ }),
/***/ "./node_modules/webworkify-webpack/index.js":
/*!**************************************************!*\
!*** ./node_modules/webworkify-webpack/index.js ***!
\**************************************************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports, __webpack_require__) {
function webpackBootstrapFunc (modules) {
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/ // on error function for async loading
/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
return f.default || f // try to call default if defined to also support babel esmodule exports
}
var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
var dependencyRegExp = '\\(\\s*(\/\\*.*?\\*\/)?\\s*.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
// http://stackoverflow.com/a/2593661/130442
function quoteRegExp (str) {
return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
}
function isNumeric(n) {
return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN
}
function getModuleDependencies (sources, module, queueName) {
var retval = {}
retval[queueName] = []
var fnString = module.toString()
var wrapperSignature = fnString.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/)
if (!wrapperSignature) return retval
var webpackRequireName = wrapperSignature[1]
// main bundle deps
var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
var match
while ((match = re.exec(fnString))) {
if (match[3] === 'dll-reference') continue
retval[queueName].push(match[3])
}
// dll deps
re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
while ((match = re.exec(fnString))) {
if (!sources[match[2]]) {
retval[queueName].push(match[1])
sources[match[2]] = __webpack_require__(match[1]).m
}
retval[match[2]] = retval[match[2]] || []
retval[match[2]].push(match[4])
}
// convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3
var keys = Object.keys(retval);
for (var i = 0; i < keys.length; i++) {
for (var j = 0; j < retval[keys[i]].length; j++) {
if (isNumeric(retval[keys[i]][j])) {
retval[keys[i]][j] = 1 * retval[keys[i]][j];
}
}
}
return retval
}
function hasValuesInQueues (queues) {
var keys = Object.keys(queues)
return keys.reduce(function (hasValues, key) {
return hasValues || queues[key].length > 0
}, false)
}
function getRequiredModules (sources, moduleId) {
var modulesQueue = {
main: [moduleId]
}
var requiredModules = {
main: []
}
var seenModules = {
main: {}
}
while (hasValuesInQueues(modulesQueue)) {
var queues = Object.keys(modulesQueue)
for (var i = 0; i < queues.length; i++) {
var queueName = queues[i]
var queue = modulesQueue[queueName]
var moduleToCheck = queue.pop()
seenModules[queueName] = seenModules[queueName] || {}
if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
seenModules[queueName][moduleToCheck] = true
requiredModules[queueName] = requiredModules[queueName] || []
requiredModules[queueName].push(moduleToCheck)
var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
var newModulesKeys = Object.keys(newModules)
for (var j = 0; j < newModulesKeys.length; j++) {
modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
}
}
}
return requiredModules
}
module.exports = function (moduleId, options) {
options = options || {}
var sources = {
main: __webpack_require__.m
}
var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)
var src = ''
Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
var entryModule = 0
while (requiredModules[module][entryModule]) {
entryModule++
}
requiredModules[module].push(entryModule)
sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n'
})
src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);'
var blob = new window.Blob([src], { type: 'text/javascript' })
if (options.bare) { return blob }
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
var workerUrl = URL.createObjectURL(blob)
var worker = new window.Worker(workerUrl)
worker.objectURL = workerUrl
return worker
}
/***/ }),
/***/ "./src/demux/demuxer-inline.js":
/*!**************************************************!*\
!*** ./src/demux/demuxer-inline.js + 16 modules ***!
\**************************************************/
/*! exports provided: default */
/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/id3.js because of ./src/hls.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/mp4demuxer.js because of ./src/hls.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/errors.ts because of ./src/hls.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/events.js because of ./src/hls.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/polyfills/number.js because of ./src/hls.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/get-self-scope.js because of ./src/hls.ts */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/logger.js because of ./src/hls.ts */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXTERNAL MODULE: ./src/events.js
var events = __webpack_require__("./src/events.js");
// EXTERNAL MODULE: ./src/errors.ts
var errors = __webpack_require__("./src/errors.ts");
// CONCATENATED MODULE: ./src/crypt/aes-crypto.js
var AESCrypto = /*#__PURE__*/function () {
function AESCrypto(subtle, iv) {
this.subtle = subtle;
this.aesIV = iv;
}
var _proto = AESCrypto.prototype;
_proto.decrypt = function decrypt(data, key) {
return this.subtle.decrypt({
name: 'AES-CBC',
iv: this.aesIV
}, key, data);
};
return AESCrypto;
}();
// CONCATENATED MODULE: ./src/crypt/fast-aes-key.js
var FastAESKey = /*#__PURE__*/function () {
function FastAESKey(subtle, key) {
this.subtle = subtle;
this.key = key;
}
var _proto = FastAESKey.prototype;
_proto.expandKey = function expandKey() {
return this.subtle.importKey('raw', this.key, {
name: 'AES-CBC'
}, false, ['encrypt', 'decrypt']);
};
return FastAESKey;
}();
/* harmony default export */ var fast_aes_key = (FastAESKey);
// CONCATENATED MODULE: ./src/crypt/aes-decryptor.js
// PKCS7
function removePadding(buffer) {
var outputBytes = buffer.byteLength;
var paddingBytes = outputBytes && new DataView(buffer).getUint8(outputBytes - 1);
if (paddingBytes) {
return buffer.slice(0, outputBytes - paddingBytes);
} else {
return buffer;
}
}
var AESDecryptor = /*#__PURE__*/function () {
function AESDecryptor() {
// Static after running initTable
this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
this.sBox = new Uint32Array(256);
this.invSBox = new Uint32Array(256); // Changes during runtime
this.key = new Uint32Array(0);
this.initTable();
} // Using view.getUint32() also swaps the byte order.
var _proto = AESDecryptor.prototype;
_proto.uint8ArrayToUint32Array_ = function uint8ArrayToUint32Array_(arrayBuffer) {
var view = new DataView(arrayBuffer);
var newArray = new Uint32Array(4);
for (var i = 0; i < 4; i++) {
newArray[i] = view.getUint32(i * 4);
}
return newArray;
};
_proto.initTable = function initTable() {
var sBox = this.sBox;
var invSBox = this.invSBox;
var subMix = this.subMix;
var subMix0 = subMix[0];
var subMix1 = subMix[1];
var subMix2 = subMix[2];
var subMix3 = subMix[3];
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var d = new Uint32Array(256);
var x = 0;
var xi = 0;
var i = 0;
for (i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = i << 1 ^ 0x11b;
}
}
for (i = 0; i < 256; i++) {
var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4;
sx = sx >>> 8 ^ sx & 0xff ^ 0x63;
sBox[x] = sx;
invSBox[sx] = x; // Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4]; // Compute sub/invSub bytes, mix columns tables
var t = d[sx] * 0x101 ^ sx * 0x1010100;
subMix0[x] = t << 24 | t >>> 8;
subMix1[x] = t << 16 | t >>> 16;
subMix2[x] = t << 8 | t >>> 24;
subMix3[x] = t; // Compute inv sub bytes, inv mix columns tables
t = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
invSubMix0[sx] = t << 24 | t >>> 8;
invSubMix1[sx] = t << 16 | t >>> 16;
invSubMix2[sx] = t << 8 | t >>> 24;
invSubMix3[sx] = t; // Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
};
_proto.expandKey = function expandKey(keyBuffer) {
// convert keyBuffer to Uint32Array
var key = this.uint8ArrayToUint32Array_(keyBuffer);
var sameKey = true;
var offset = 0;
while (offset < key.length && sameKey) {
sameKey = key[offset] === this.key[offset];
offset++;
}
if (sameKey) {
return;
}
this.key = key;
var keySize = this.keySize = key.length;
if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
throw new Error('Invalid aes key size=' + keySize);
}
var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
var ksRow;
var invKsRow;
var keySchedule = this.keySchedule = new Uint32Array(ksRows);
var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
var sbox = this.sBox;
var rcon = this.rcon;
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var prev;
var t;
for (ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
prev = keySchedule[ksRow] = key[ksRow];
continue;
}
t = prev;
if (ksRow % keySize === 0) {
// Rot word
t = t << 8 | t >>> 24; // Sub word
t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff]; // Mix Rcon
t ^= rcon[ksRow / keySize | 0] << 24;
} else if (keySize > 6 && ksRow % keySize === 4) {
// Sub word
t = sbox[t >>> 24] << 24 | sbox[t >>> 16 & 0xff] << 16 | sbox[t >>> 8 & 0xff] << 8 | sbox[t & 0xff];
}
keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
}
for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
ksRow = ksRows - invKsRow;
if (invKsRow & 3) {
t = keySchedule[ksRow];
} else {
t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[t >>> 16 & 0xff]] ^ invSubMix2[sbox[t >>> 8 & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
}
invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
}
} // Adding this as a method greatly improves performance.
;
_proto.networkToHostOrderSwap = function networkToHostOrderSwap(word) {
return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
};
_proto.decrypt = function decrypt(inputArrayBuffer, offset, aesIV, removePKCS7Padding) {
var nRounds = this.keySize + 6;
var invKeySchedule = this.invKeySchedule;
var invSBOX = this.invSBox;
var invSubMix = this.invSubMix;
var invSubMix0 = invSubMix[0];
var invSubMix1 = invSubMix[1];
var invSubMix2 = invSubMix[2];
var invSubMix3 = invSubMix[3];
var initVector = this.uint8ArrayToUint32Array_(aesIV);
var initVector0 = initVector[0];
var initVector1 = initVector[1];
var initVector2 = initVector[2];
var initVector3 = initVector[3];
var inputInt32 = new Int32Array(inputArrayBuffer);
var outputInt32 = new Int32Array(inputInt32.length);
var t0, t1, t2, t3;
var s0, s1, s2, s3;
var inputWords0, inputWords1, inputWords2, inputWords3;
var ksRow, i;
var swapWord = this.networkToHostOrderSwap;
while (offset < inputInt32.length) {
inputWords0 = swapWord(inputInt32[offset]);
inputWords1 = swapWord(inputInt32[offset + 1]);
inputWords2 = swapWord(inputInt32[offset + 2]);
inputWords3 = swapWord(inputInt32[offset + 3]);
s0 = inputWords0 ^ invKeySchedule[0];
s1 = inputWords3 ^ invKeySchedule[1];
s2 = inputWords2 ^ invKeySchedule[2];
s3 = inputWords1 ^ invKeySchedule[3];
ksRow = 4; // Iterate through the rounds of decryption
for (i = 1; i < nRounds; i++) {
t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[s1 >> 16 & 0xff] ^ invSubMix2[s2 >> 8 & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[s2 >> 16 & 0xff] ^ invSubMix2[s3 >> 8 & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[s3 >> 16 & 0xff] ^ invSubMix2[s0 >> 8 & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[s0 >> 16 & 0xff] ^ invSubMix2[s1 >> 8 & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3]; // Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
ksRow = ksRow + 4;
} // Shift rows, sub bytes, add round key
t0 = invSBOX[s0 >>> 24] << 24 ^ invSBOX[s1 >> 16 & 0xff] << 16 ^ invSBOX[s2 >> 8 & 0xff] << 8 ^ invSBOX[s3 & 0xff] ^ invKeySchedule[ksRow];
t1 = invSBOX[s1 >>> 24] << 24 ^ invSBOX[s2 >> 16 & 0xff] << 16 ^ invSBOX[s3 >> 8 & 0xff] << 8 ^ invSBOX[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
t2 = invSBOX[s2 >>> 24] << 24 ^ invSBOX[s3 >> 16 & 0xff] << 16 ^ invSBOX[s0 >> 8 & 0xff] << 8 ^ invSBOX[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
t3 = invSBOX[s3 >>> 24] << 24 ^ invSBOX[s0 >> 16 & 0xff] << 16 ^ invSBOX[s1 >> 8 & 0xff] << 8 ^ invSBOX[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
ksRow = ksRow + 3; // Write
outputInt32[offset] = swapWord(t0 ^ initVector0);
outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
outputInt32[offset + 3] = swapWord(t1 ^ initVector3); // reset initVector to last 4 unsigned int
initVector0 = inputWords0;
initVector1 = inputWords1;
initVector2 = inputWords2;
initVector3 = inputWords3;
offset = offset + 4;
}
return removePKCS7Padding ? removePadding(outputInt32.buffer) : outputInt32.buffer;
};
_proto.destroy = function destroy() {
this.key = undefined;
this.keySize = undefined;
this.ksRows = undefined;
this.sBox = undefined;
this.invSBox = undefined;
this.subMix = undefined;
this.invSubMix = undefined;
this.keySchedule = undefined;
this.invKeySchedule = undefined;
this.rcon = undefined;
};
return AESDecryptor;
}();
/* harmony default export */ var aes_decryptor = (AESDecryptor);
// EXTERNAL MODULE: ./src/utils/logger.js
var logger = __webpack_require__("./src/utils/logger.js");
// EXTERNAL MODULE: ./src/utils/get-self-scope.js
var get_self_scope = __webpack_require__("./src/utils/get-self-scope.js");
// CONCATENATED MODULE: ./src/crypt/decrypter.js
// see https://stackoverflow.com/a/11237259/589493
var global = Object(get_self_scope["getSelfScope"])(); // safeguard for code that might run both on worker and main thread
var decrypter_Decrypter = /*#__PURE__*/function () {
function Decrypter(observer, config, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$removePKCS7Paddi = _ref.removePKCS7Padding,
removePKCS7Padding = _ref$removePKCS7Paddi === void 0 ? true : _ref$removePKCS7Paddi;
this.logEnabled = true;
this.observer = observer;
this.config = config;
this.removePKCS7Padding = removePKCS7Padding; // built in decryptor expects PKCS7 padding
if (removePKCS7Padding) {
try {
var browserCrypto = global.crypto;
if (browserCrypto) {
this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
}
} catch (e) {}
}
this.disableWebCrypto = !this.subtle;
}
var _proto = Decrypter.prototype;
_proto.isSync = function isSync() {
return this.disableWebCrypto && this.config.enableSoftwareAES;
};
_proto.decrypt = function decrypt(data, key, iv, callback) {
var _this = this;
if (this.disableWebCrypto && this.config.enableSoftwareAES) {
if (this.logEnabled) {
logger["logger"].log('JS AES decrypt');
this.logEnabled = false;
}
var decryptor = this.decryptor;
if (!decryptor) {
this.decryptor = decryptor = new aes_decryptor();
}
decryptor.expandKey(key);
callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));
} else {
if (this.logEnabled) {
logger["logger"].log('WebCrypto AES decrypt');
this.logEnabled = false;
}
var subtle = this.subtle;
if (this.key !== key) {
this.key = key;
this.fastAesKey = new fast_aes_key(subtle, key);
}
this.fastAesKey.expandKey().then(function (aesKey) {
// decrypt using web crypto
var crypto = new AESCrypto(subtle, iv);
crypto.decrypt(data, aesKey).catch(function (err) {
_this.onWebCryptoError(err, data, key, iv, callback);
}).then(function (result) {
callback(result);
});
}).catch(function (err) {
_this.onWebCryptoError(err, data, key, iv, callback);
});
}
};
_proto.onWebCryptoError = function onWebCryptoError(err, data, key, iv, callback) {
if (this.config.enableSoftwareAES) {
logger["logger"].log('WebCrypto Error, disable WebCrypto API');
this.disableWebCrypto = true;
this.logEnabled = true;
this.decrypt(data, key, iv, callback);
} else {
logger["logger"].error("decrypting error : " + err.message);
this.observer.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].FRAG_DECRYPT_ERROR,
fatal: true,
reason: err.message
});
}
};
_proto.destroy = function destroy() {
var decryptor = this.decryptor;
if (decryptor) {
decryptor.destroy();
this.decryptor = undefined;
}
};
return Decrypter;
}();
/* harmony default export */ var crypt_decrypter = (decrypter_Decrypter);
// EXTERNAL MODULE: ./src/polyfills/number.js
var number = __webpack_require__("./src/polyfills/number.js");
// CONCATENATED MODULE: ./src/demux/adts.js
/**
* ADTS parser helper
* @link https://wiki.multimedia.cx/index.php?title=ADTS
*/
function getAudioConfig(observer, data, offset, audioCodec) {
var adtsObjectType,
// :int
adtsSampleingIndex,
// :int
adtsExtensionSampleingIndex,
// :int
adtsChanelConfig,
// :int
config,
userAgent = navigator.userAgent.toLowerCase(),
manifestCodec = audioCodec,
adtsSampleingRates = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]; // byte 2
adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
adtsSampleingIndex = (data[offset + 2] & 0x3C) >>> 2;
if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
observer.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: true,
reason: "invalid ADTS sampling index:" + adtsSampleingIndex
});
return;
}
adtsChanelConfig = (data[offset + 2] & 0x01) << 2; // byte 3
adtsChanelConfig |= (data[offset + 3] & 0xC0) >>> 6;
logger["logger"].log("manifest codec:" + audioCodec + ",ADTS data:type:" + adtsObjectType + ",sampleingIndex:" + adtsSampleingIndex + "[" + adtsSampleingRates[adtsSampleingIndex] + "Hz],channelConfig:" + adtsChanelConfig); // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
if (/firefox/i.test(userAgent)) {
if (adtsSampleingIndex >= 6) {
adtsObjectType = 5;
config = new Array(4); // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
// there is a factor 2 between frame sample rate and output sample rate
// multiply frequency by 2 (see table below, equivalent to substract 3)
adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
} else {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSampleingIndex = adtsSampleingIndex;
} // Android : always use AAC
} else if (userAgent.indexOf('android') !== -1) {
adtsObjectType = 2;
config = new Array(2);
adtsExtensionSampleingIndex = adtsSampleingIndex;
} else {
/* for other browsers (Chrome/Vivaldi/Opera ...)
always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
*/
adtsObjectType = 5;
config = new Array(4); // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
if (audioCodec && (audioCodec.indexOf('mp4a.40.29') !== -1 || audioCodec.indexOf('mp4a.40.5') !== -1) || !audioCodec && adtsSampleingIndex >= 6) {
// HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
// there is a factor 2 between frame sample rate and output sample rate
// multiply frequency by 2 (see table below, equivalent to substract 3)
adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
} else {
// if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
// Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && (adtsSampleingIndex >= 6 && adtsChanelConfig === 1 || /vivaldi/i.test(userAgent)) || !audioCodec && adtsChanelConfig === 1) {
adtsObjectType = 2;
config = new Array(2);
}
adtsExtensionSampleingIndex = adtsSampleingIndex;
}
}
/* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
Audio Profile / Audio Object Type
0: Null
1: AAC Main
2: AAC LC (Low Complexity)
3: AAC SSR (Scalable Sample Rate)
4: AAC LTP (Long Term Prediction)
5: SBR (Spectral Band Replication)
6: AAC Scalable
sampling freq
0: 96000 Hz
1: 88200 Hz
2: 64000 Hz
3: 48000 Hz
4: 44100 Hz
5: 32000 Hz
6: 24000 Hz
7: 22050 Hz
8: 16000 Hz
9: 12000 Hz
10: 11025 Hz
11: 8000 Hz
12: 7350 Hz
13: Reserved
14: Reserved
15: frequency is written explictly
Channel Configurations
These are the channel configurations:
0: Defined in AOT Specifc Config
1: 1 channel: front-center
2: 2 channels: front-left, front-right
*/
// audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
config[0] = adtsObjectType << 3; // samplingFrequencyIndex
config[0] |= (adtsSampleingIndex & 0x0E) >> 1;
config[1] |= (adtsSampleingIndex & 0x01) << 7; // channelConfiguration
config[1] |= adtsChanelConfig << 3;
if (adtsObjectType === 5) {
// adtsExtensionSampleingIndex
config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
config[2] = (adtsExtensionSampleingIndex & 0x01) << 7; // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
// https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
config[2] |= 2 << 2;
config[3] = 0;
}
return {
config: config,
samplerate: adtsSampleingRates[adtsSampleingIndex],
channelCount: adtsChanelConfig,
codec: 'mp4a.40.' + adtsObjectType,
manifestCodec: manifestCodec
};
}
function isHeaderPattern(data, offset) {
return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
}
function getHeaderLength(data, offset) {
return data[offset + 1] & 0x01 ? 7 : 9;
}
function getFullFrameLength(data, offset) {
return (data[offset + 3] & 0x03) << 11 | data[offset + 4] << 3 | (data[offset + 5] & 0xE0) >>> 5;
}
function isHeader(data, offset) {
// Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
// Layer bits (position 14 and 15) in header should be always 0 for ADTS
// More info https://wiki.multimedia.cx/index.php?title=ADTS
if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
return true;
}
return false;
}
function adts_probe(data, offset) {
// same as isHeader but we also check that ADTS frame follows last ADTS frame
// or end of data is reached
if (isHeader(data, offset)) {
// ADTS header Length
var headerLength = getHeaderLength(data, offset);
if (offset + headerLength >= data.length) {
return false;
} // ADTS frame Length
var frameLength = getFullFrameLength(data, offset);
if (frameLength <= headerLength) {
return false;
}
var newOffset = offset + frameLength;
if (newOffset === data.length || newOffset + 1 < data.length && isHeaderPattern(data, newOffset)) {
return true;
}
}
return false;
}
function initTrackConfig(track, observer, data, offset, audioCodec) {
if (!track.samplerate) {
var config = getAudioConfig(observer, data, offset, audioCodec);
track.config = config.config;
track.samplerate = config.samplerate;
track.channelCount = config.channelCount;
track.codec = config.codec;
track.manifestCodec = config.manifestCodec;
logger["logger"].log("parsed codec:" + track.codec + ",rate:" + config.samplerate + ",nb channel:" + config.channelCount);
}
}
function getFrameDuration(samplerate) {
return 1024 * 90000 / samplerate;
}
function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
var headerLength, frameLength, stamp;
var length = data.length; // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
headerLength = getHeaderLength(data, offset); // retrieve frame size
frameLength = getFullFrameLength(data, offset);
frameLength -= headerLength;
if (frameLength > 0 && offset + headerLength + frameLength <= length) {
stamp = pts + frameIndex * frameDuration; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
return {
headerLength: headerLength,
frameLength: frameLength,
stamp: stamp
};
}
return undefined;
}
function appendFrame(track, data, offset, pts, frameIndex) {
var frameDuration = getFrameDuration(track.samplerate);
var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
if (header) {
var stamp = header.stamp;
var headerLength = header.headerLength;
var frameLength = header.frameLength; // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
var aacSample = {
unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),
pts: stamp,
dts: stamp
};
track.samples.push(aacSample);
return {
sample: aacSample,
length: frameLength + headerLength
};
}
return undefined;
}
// EXTERNAL MODULE: ./src/demux/id3.js
var id3 = __webpack_require__("./src/demux/id3.js");
// CONCATENATED MODULE: ./src/demux/aacdemuxer.js
/**
* AAC demuxer
*/
var aacdemuxer_AACDemuxer = /*#__PURE__*/function () {
function AACDemuxer(observer, remuxer, config) {
this.observer = observer;
this.config = config;
this.remuxer = remuxer;
}
var _proto = AACDemuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
this._audioTrack = {
container: 'audio/adts',
type: 'audio',
id: 0,
sequenceNumber: 0,
isAAC: true,
samples: [],
len: 0,
manifestCodec: audioCodec,
duration: duration,
inputTimeScale: 90000
};
};
_proto.resetTimeStamp = function resetTimeStamp() {};
AACDemuxer.probe = function probe(data) {
if (!data) {
return false;
} // Check for the ADTS sync word
// Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
// Layer bits (position 14 and 15) in header should be always 0 for ADTS
// More info https://wiki.multimedia.cx/index.php?title=ADTS
var id3Data = id3["default"].getID3Data(data, 0) || [];
var offset = id3Data.length;
for (var length = data.length; offset < length; offset++) {
if (adts_probe(data, offset)) {
logger["logger"].log('ADTS sync word found !');
return true;
}
}
return false;
} // feed incoming data to the front of the parsing pipeline
;
_proto.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
var track = this._audioTrack;
var id3Data = id3["default"].getID3Data(data, 0) || [];
var timestamp = id3["default"].getTimeStamp(id3Data);
var pts = Object(number["isFiniteNumber"])(timestamp) ? timestamp * 90 : timeOffset * 90000;
var frameIndex = 0;
var stamp = pts;
var length = data.length;
var offset = id3Data.length;
var id3Samples = [{
pts: stamp,
dts: stamp,
data: id3Data
}];
while (offset < length - 1) {
if (isHeader(data, offset) && offset + 5 < length) {
initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
var frame = appendFrame(track, data, offset, pts, frameIndex);
if (frame) {
offset += frame.length;
stamp = frame.sample.pts;
frameIndex++;
} else {
logger["logger"].log('Unable to parse AAC frame');
break;
}
} else if (id3["default"].isHeader(data, offset)) {
id3Data = id3["default"].getID3Data(data, offset);
id3Samples.push({
pts: stamp,
dts: stamp,
data: id3Data
});
offset += id3Data.length;
} else {
// nothing found, keep looking
offset++;
}
}
this.remuxer.remux(track, {
samples: []
}, {
samples: id3Samples,
inputTimeScale: 90000
}, {
samples: []
}, timeOffset, contiguous, accurateTimeOffset);
};
_proto.destroy = function destroy() {};
return AACDemuxer;
}();
/* harmony default export */ var aacdemuxer = (aacdemuxer_AACDemuxer);
// EXTERNAL MODULE: ./src/demux/mp4demuxer.js
var mp4demuxer = __webpack_require__("./src/demux/mp4demuxer.js");
// CONCATENATED MODULE: ./src/demux/mpegaudio.js
/**
* MPEG parser helper
*/
var MpegAudio = {
BitratesMap: [32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],
SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],
SamplesCoefficients: [// MPEG 2.5
[0, // Reserved
72, // Layer3
144, // Layer2
12 // Layer1
], // Reserved
[0, // Reserved
0, // Layer3
0, // Layer2
0 // Layer1
], // MPEG 2
[0, // Reserved
72, // Layer3
144, // Layer2
12 // Layer1
], // MPEG 1
[0, // Reserved
144, // Layer3
144, // Layer2
12 // Layer1
]],
BytesInSlot: [0, // Reserved
1, // Layer3
1, // Layer2
4 // Layer1
],
appendFrame: function appendFrame(track, data, offset, pts, frameIndex) {
// Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
if (offset + 24 > data.length) {
return undefined;
}
var header = this.parseHeader(data, offset);
if (header && offset + header.frameLength <= data.length) {
var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
var stamp = pts + frameIndex * frameDuration;
var sample = {
unit: data.subarray(offset, offset + header.frameLength),
pts: stamp,
dts: stamp
};
track.config = [];
track.channelCount = header.channelCount;
track.samplerate = header.sampleRate;
track.samples.push(sample);
return {
sample: sample,
length: header.frameLength
};
}
return undefined;
},
parseHeader: function parseHeader(data, offset) {
var headerB = data[offset + 1] >> 3 & 3;
var headerC = data[offset + 1] >> 1 & 3;
var headerE = data[offset + 2] >> 4 & 15;
var headerF = data[offset + 2] >> 2 & 3;
var headerG = data[offset + 2] >> 1 & 1;
if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {
var columnInBitrates = headerB === 3 ? 3 - headerC : headerC === 3 ? 3 : 4;
var bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;
var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;
var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];
var channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];
var bytesInSlot = MpegAudio.BytesInSlot[headerC];
var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;
return {
sampleRate: sampleRate,
channelCount: channelCount,
frameLength: frameLength,
samplesPerFrame: samplesPerFrame
};
}
return undefined;
},
isHeaderPattern: function isHeaderPattern(data, offset) {
return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
},
isHeader: function isHeader(data, offset) {
// Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
// Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
// More info http://www.mp3-tech.org/programmer/frame_header.html
if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
return true;
}
return false;
},
probe: function probe(data, offset) {
// same as isHeader but we also check that MPEG frame follows last MPEG frame
// or end of data is reached
if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
// MPEG header Length
var headerLength = 4; // MPEG frame Length
var header = this.parseHeader(data, offset);
var frameLength = headerLength;
if (header && header.frameLength) {
frameLength = header.frameLength;
}
var newOffset = offset + frameLength;
if (newOffset === data.length || newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset)) {
return true;
}
}
return false;
}
};
/* harmony default export */ var mpegaudio = (MpegAudio);
// CONCATENATED MODULE: ./src/demux/exp-golomb.js
/**
* Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
*/
var exp_golomb_ExpGolomb = /*#__PURE__*/function () {
function ExpGolomb(data) {
this.data = data; // the number of bytes left to examine in this.data
this.bytesAvailable = data.byteLength; // the current word being examined
this.word = 0; // :uint
// the number of bits left to examine in the current word
this.bitsAvailable = 0; // :uint
} // ():void
var _proto = ExpGolomb.prototype;
_proto.loadWord = function loadWord() {
var data = this.data,
bytesAvailable = this.bytesAvailable,
position = data.byteLength - bytesAvailable,
workingBytes = new Uint8Array(4),
availableBytes = Math.min(4, bytesAvailable);
if (availableBytes === 0) {
throw new Error('no bytes available');
}
workingBytes.set(data.subarray(position, position + availableBytes));
this.word = new DataView(workingBytes.buffer).getUint32(0); // track the amount of this.data that has been processed
this.bitsAvailable = availableBytes * 8;
this.bytesAvailable -= availableBytes;
} // (count:int):void
;
_proto.skipBits = function skipBits(count) {
var skipBytes; // :int
if (this.bitsAvailable > count) {
this.word <<= count;
this.bitsAvailable -= count;
} else {
count -= this.bitsAvailable;
skipBytes = count >> 3;
count -= skipBytes >> 3;
this.bytesAvailable -= skipBytes;
this.loadWord();
this.word <<= count;
this.bitsAvailable -= count;
}
} // (size:int):uint
;
_proto.readBits = function readBits(size) {
var bits = Math.min(this.bitsAvailable, size),
// :uint
valu = this.word >>> 32 - bits; // :uint
if (size > 32) {
logger["logger"].error('Cannot read more than 32 bits at a time');
}
this.bitsAvailable -= bits;
if (this.bitsAvailable > 0) {
this.word <<= bits;
} else if (this.bytesAvailable > 0) {
this.loadWord();
}
bits = size - bits;
if (bits > 0 && this.bitsAvailable) {
return valu << bits | this.readBits(bits);
} else {
return valu;
}
} // ():uint
;
_proto.skipLZ = function skipLZ() {
var leadingZeroCount; // :uint
for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
if ((this.word & 0x80000000 >>> leadingZeroCount) !== 0) {
// the first bit of working word is 1
this.word <<= leadingZeroCount;
this.bitsAvailable -= leadingZeroCount;
return leadingZeroCount;
}
} // we exhausted word and still have not found a 1
this.loadWord();
return leadingZeroCount + this.skipLZ();
} // ():void
;
_proto.skipUEG = function skipUEG() {
this.skipBits(1 + this.skipLZ());
} // ():void
;
_proto.skipEG = function skipEG() {
this.skipBits(1 + this.skipLZ());
} // ():uint
;
_proto.readUEG = function readUEG() {
var clz = this.skipLZ(); // :uint
return this.readBits(clz + 1) - 1;
} // ():int
;
_proto.readEG = function readEG() {
var valu = this.readUEG(); // :int
if (0x01 & valu) {
// the number is odd if the low order bit is set
return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
} else {
return -1 * (valu >>> 1); // divide by two then make it negative
}
} // Some convenience functions
// :Boolean
;
_proto.readBoolean = function readBoolean() {
return this.readBits(1) === 1;
} // ():int
;
_proto.readUByte = function readUByte() {
return this.readBits(8);
} // ():int
;
_proto.readUShort = function readUShort() {
return this.readBits(16);
} // ():int
;
_proto.readUInt = function readUInt() {
return this.readBits(32);
}
/**
* Advance the ExpGolomb decoder past a scaling list. The scaling
* list is optionally transmitted as part of a sequence parameter
* set and is not relevant to transmuxing.
* @param count {number} the number of entries in this scaling list
* @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
*/
;
_proto.skipScalingList = function skipScalingList(count) {
var lastScale = 8,
nextScale = 8,
j,
deltaScale;
for (j = 0; j < count; j++) {
if (nextScale !== 0) {
deltaScale = this.readEG();
nextScale = (lastScale + deltaScale + 256) % 256;
}
lastScale = nextScale === 0 ? lastScale : nextScale;
}
}
/**
* Read a sequence parameter set and return some interesting video
* properties. A sequence parameter set is the H264 metadata that
* describes the properties of upcoming video frames.
* @param data {Uint8Array} the bytes of a sequence parameter set
* @return {object} an object with configuration parsed from the
* sequence parameter set, including the dimensions of the
* associated video frames.
*/
;
_proto.readSPS = function readSPS() {
var frameCropLeftOffset = 0,
frameCropRightOffset = 0,
frameCropTopOffset = 0,
frameCropBottomOffset = 0,
profileIdc,
profileCompat,
levelIdc,
numRefFramesInPicOrderCntCycle,
picWidthInMbsMinus1,
picHeightInMapUnitsMinus1,
frameMbsOnlyFlag,
scalingListCount,
i,
readUByte = this.readUByte.bind(this),
readBits = this.readBits.bind(this),
readUEG = this.readUEG.bind(this),
readBoolean = this.readBoolean.bind(this),
skipBits = this.skipBits.bind(this),
skipEG = this.skipEG.bind(this),
skipUEG = this.skipUEG.bind(this),
skipScalingList = this.skipScalingList.bind(this);
readUByte();
profileIdc = readUByte(); // profile_idc
profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)
skipBits(3); // reserved_zero_3bits u(3),
levelIdc = readUByte(); // level_idc u(8)
skipUEG(); // seq_parameter_set_id
// some profiles have more optional data we don't need
if (profileIdc === 100 || profileIdc === 110 || profileIdc === 122 || profileIdc === 244 || profileIdc === 44 || profileIdc === 83 || profileIdc === 86 || profileIdc === 118 || profileIdc === 128) {
var chromaFormatIdc = readUEG();
if (chromaFormatIdc === 3) {
skipBits(1);
} // separate_colour_plane_flag
skipUEG(); // bit_depth_luma_minus8
skipUEG(); // bit_depth_chroma_minus8
skipBits(1); // qpprime_y_zero_transform_bypass_flag
if (readBoolean()) {
// seq_scaling_matrix_present_flag
scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
for (i = 0; i < scalingListCount; i++) {
if (readBoolean()) {
// seq_scaling_list_present_flag[ i ]
if (i < 6) {
skipScalingList(16);
} else {
skipScalingList(64);
}
}
}
}
}
skipUEG(); // log2_max_frame_num_minus4
var picOrderCntType = readUEG();
if (picOrderCntType === 0) {
readUEG(); // log2_max_pic_order_cnt_lsb_minus4
} else if (picOrderCntType === 1) {
skipBits(1); // delta_pic_order_always_zero_flag
skipEG(); // offset_for_non_ref_pic
skipEG(); // offset_for_top_to_bottom_field
numRefFramesInPicOrderCntCycle = readUEG();
for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
skipEG();
} // offset_for_ref_frame[ i ]
}
skipUEG(); // max_num_ref_frames
skipBits(1); // gaps_in_frame_num_value_allowed_flag
picWidthInMbsMinus1 = readUEG();
picHeightInMapUnitsMinus1 = readUEG();
frameMbsOnlyFlag = readBits(1);
if (frameMbsOnlyFlag === 0) {
skipBits(1);
} // mb_adaptive_frame_field_flag
skipBits(1); // direct_8x8_inference_flag
if (readBoolean()) {
// frame_cropping_flag
frameCropLeftOffset = readUEG();
frameCropRightOffset = readUEG();
frameCropTopOffset = readUEG();
frameCropBottomOffset = readUEG();
}
var pixelRatio = [1, 1];
if (readBoolean()) {
// vui_parameters_present_flag
if (readBoolean()) {
// aspect_ratio_info_present_flag
var aspectRatioIdc = readUByte();
switch (aspectRatioIdc) {
case 1:
pixelRatio = [1, 1];
break;
case 2:
pixelRatio = [12, 11];
break;
case 3:
pixelRatio = [10, 11];
break;
case 4:
pixelRatio = [16, 11];
break;
case 5:
pixelRatio = [40, 33];
break;
case 6:
pixelRatio = [24, 11];
break;
case 7:
pixelRatio = [20, 11];
break;
case 8:
pixelRatio = [32, 11];
break;
case 9:
pixelRatio = [80, 33];
break;
case 10:
pixelRatio = [18, 11];
break;
case 11:
pixelRatio = [15, 11];
break;
case 12:
pixelRatio = [64, 33];
break;
case 13:
pixelRatio = [160, 99];
break;
case 14:
pixelRatio = [4, 3];
break;
case 15:
pixelRatio = [3, 2];
break;
case 16:
pixelRatio = [2, 1];
break;
case 255:
{
pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
break;
}
}
}
}
return {
width: Math.ceil((picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2),
height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - (frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset),
pixelRatio: pixelRatio
};
};
_proto.readSliceType = function readSliceType() {
// skip NALu type
this.readUByte(); // discard first_mb_in_slice
this.readUEG(); // return slice_type
return this.readUEG();
};
return ExpGolomb;
}();
/* harmony default export */ var exp_golomb = (exp_golomb_ExpGolomb);
// CONCATENATED MODULE: ./src/demux/sample-aes.js
/**
* SAMPLE-AES decrypter
*/
var sample_aes_SampleAesDecrypter = /*#__PURE__*/function () {
function SampleAesDecrypter(observer, config, decryptdata, discardEPB) {
this.decryptdata = decryptdata;
this.discardEPB = discardEPB;
this.decrypter = new crypt_decrypter(observer, config, {
removePKCS7Padding: false
});
}
var _proto = SampleAesDecrypter.prototype;
_proto.decryptBuffer = function decryptBuffer(encryptedData, callback) {
this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);
} // AAC - encrypt all full 16 bytes blocks starting from offset 16
;
_proto.decryptAacSample = function decryptAacSample(samples, sampleIndex, callback, sync) {
var curUnit = samples[sampleIndex].unit;
var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
var localthis = this;
this.decryptBuffer(encryptedBuffer, function (decryptedData) {
decryptedData = new Uint8Array(decryptedData);
curUnit.set(decryptedData, 16);
if (!sync) {
localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
}
});
};
_proto.decryptAacSamples = function decryptAacSamples(samples, sampleIndex, callback) {
for (;; sampleIndex++) {
if (sampleIndex >= samples.length) {
callback();
return;
}
if (samples[sampleIndex].unit.length < 32) {
continue;
}
var sync = this.decrypter.isSync();
this.decryptAacSample(samples, sampleIndex, callback, sync);
if (!sync) {
return;
}
}
} // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
;
_proto.getAvcEncryptedData = function getAvcEncryptedData(decodedData) {
var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
var encryptedData = new Int8Array(encryptedDataLen);
var outputPos = 0;
for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
}
return encryptedData;
};
_proto.getAvcDecryptedUnit = function getAvcDecryptedUnit(decodedData, decryptedData) {
decryptedData = new Uint8Array(decryptedData);
var inputPos = 0;
for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);
}
return decodedData;
};
_proto.decryptAvcSample = function decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync) {
var decodedData = this.discardEPB(curUnit.data);
var encryptedData = this.getAvcEncryptedData(decodedData);
var localthis = this;
this.decryptBuffer(encryptedData.buffer, function (decryptedData) {
curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);
if (!sync) {
localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
}
});
};
_proto.decryptAvcSamples = function decryptAvcSamples(samples, sampleIndex, unitIndex, callback) {
for (;; sampleIndex++, unitIndex = 0) {
if (sampleIndex >= samples.length) {
callback();
return;
}
var curUnits = samples[sampleIndex].units;
for (;; unitIndex++) {
if (unitIndex >= curUnits.length) {
break;
}
var curUnit = curUnits[unitIndex];
if (curUnit.data.length <= 48 || curUnit.type !== 1 && curUnit.type !== 5) {
continue;
}
var sync = this.decrypter.isSync();
this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
if (!sync) {
return;
}
}
}
};
return SampleAesDecrypter;
}();
/* harmony default export */ var sample_aes = (sample_aes_SampleAesDecrypter);
// CONCATENATED MODULE: ./src/demux/tsdemuxer.js
/**
* highly optimized TS demuxer:
* parse PAT, PMT
* extract PES packet from audio and video PIDs
* extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
* trigger the remuxer upon parsing completion
* it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.
* it also controls the remuxing process :
* upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
*/
// import Hex from '../utils/hex';
// We are using fixed track IDs for driving the MP4 remuxer
// instead of following the TS PIDs.
// There is no reason not to do this and some browsers/SourceBuffer-demuxers
// may not like if there are TrackID "switches"
// See https://github.com/video-dev/hls.js/issues/1331
// Here we are mapping our internal track types to constant MP4 track IDs
// With MSE currently one can only have one track of each, and we are muxing
// whatever video/audio rendition in them.
var RemuxerTrackIdConfig = {
video: 1,
audio: 2,
id3: 3,
text: 4
};
var tsdemuxer_TSDemuxer = /*#__PURE__*/function () {
function TSDemuxer(observer, remuxer, config, typeSupported) {
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
this.remuxer = remuxer;
this.sampleAes = null;
this.pmtUnknownTypes = {};
}
var _proto = TSDemuxer.prototype;
_proto.setDecryptData = function setDecryptData(decryptdata) {
if (decryptdata != null && decryptdata.key != null && decryptdata.method === 'SAMPLE-AES') {
this.sampleAes = new sample_aes(this.observer, this.config, decryptdata, this.discardEPB);
} else {
this.sampleAes = null;
}
};
TSDemuxer.probe = function probe(data) {
var syncOffset = TSDemuxer._syncOffset(data);
if (syncOffset < 0) {
return false;
} else {
if (syncOffset) {
logger["logger"].warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset + ", junk ahead ?");
}
return true;
}
};
TSDemuxer._syncOffset = function _syncOffset(data) {
// scan 1000 first bytes
var scanwindow = Math.min(1000, data.length - 3 * 188);
var i = 0;
while (i < scanwindow) {
// a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
return i;
} else {
i++;
}
}
return -1;
}
/**
* Creates a track model internal to demuxer used to drive remuxing input
*
* @param {string} type 'audio' | 'video' | 'id3' | 'text'
* @param {number} duration
* @return {object} TSDemuxer's internal track model
*/
;
TSDemuxer.createTrack = function createTrack(type, duration) {
return {
container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
type: type,
id: RemuxerTrackIdConfig[type],
pid: -1,
inputTimeScale: 90000,
sequenceNumber: 0,
samples: [],
dropped: type === 'video' ? 0 : undefined,
isAAC: type === 'audio' ? true : undefined,
duration: type === 'audio' ? duration : undefined
};
}
/**
* Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
* Resets all internal track instances of the demuxer.
*
* @override Implements generic demuxing/remuxing interface (see DemuxerInline)
* @param {object} initSegment
* @param {string} audioCodec
* @param {string} videoCodec
* @param {number} duration (in TS timescale = 90kHz)
*/
;
_proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
this.pmtParsed = false;
this._pmtId = -1;
this.pmtUnknownTypes = {};
this._avcTrack = TSDemuxer.createTrack('video', duration);
this._audioTrack = TSDemuxer.createTrack('audio', duration);
this._id3Track = TSDemuxer.createTrack('id3', duration);
this._txtTrack = TSDemuxer.createTrack('text', duration); // flush any partial content
this.aacOverFlow = null;
this.aacLastPTS = null;
this.avcSample = null;
this.audioCodec = audioCodec;
this.videoCodec = videoCodec;
this._duration = duration;
}
/**
*
* @override
*/
;
_proto.resetTimeStamp = function resetTimeStamp() {} // feed incoming data to the front of the parsing pipeline
;
_proto.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
var start,
len = data.length,
stt,
pid,
atf,
offset,
pes,
unknownPIDs = false;
this.pmtUnknownTypes = {};
this.contiguous = contiguous;
var pmtParsed = this.pmtParsed,
avcTrack = this._avcTrack,
audioTrack = this._audioTrack,
id3Track = this._id3Track,
avcId = avcTrack.pid,
audioId = audioTrack.pid,
id3Id = id3Track.pid,
pmtId = this._pmtId,
avcData = avcTrack.pesData,
audioData = audioTrack.pesData,
id3Data = id3Track.pesData,
parsePAT = this._parsePAT,
parsePMT = this._parsePMT.bind(this),
parsePES = this._parsePES,
parseAVCPES = this._parseAVCPES.bind(this),
parseAACPES = this._parseAACPES.bind(this),
parseMPEGPES = this._parseMPEGPES.bind(this),
parseID3PES = this._parseID3PES.bind(this);
var syncOffset = TSDemuxer._syncOffset(data); // don't parse last TS packet if incomplete
len -= (len + syncOffset) % 188; // loop through TS packets
for (start = syncOffset; start < len; start += 188) {
if (data[start] === 0x47) {
stt = !!(data[start + 1] & 0x40); // pid is a 13-bit field starting at the last bit of TS[1]
pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
atf = (data[start + 3] & 0x30) >> 4; // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
if (atf > 1) {
offset = start + 5 + data[start + 4]; // continue if there is only adaptation field
if (offset === start + 188) {
continue;
}
} else {
offset = start + 4;
}
switch (pid) {
case avcId:
if (stt) {
if (avcData && (pes = parsePES(avcData))) {
parseAVCPES(pes, false);
}
avcData = {
data: [],
size: 0
};
}
if (avcData) {
avcData.data.push(data.subarray(offset, start + 188));
avcData.size += start + 188 - offset;
}
break;
case audioId:
if (stt) {
if (audioData && (pes = parsePES(audioData))) {
if (audioTrack.isAAC) {
parseAACPES(pes);
} else {
parseMPEGPES(pes);
}
}
audioData = {
data: [],
size: 0
};
}
if (audioData) {
audioData.data.push(data.subarray(offset, start + 188));
audioData.size += start + 188 - offset;
}
break;
case id3Id:
if (stt) {
if (id3Data && (pes = parsePES(id3Data))) {
parseID3PES(pes);
}
id3Data = {
data: [],
size: 0
};
}
if (id3Data) {
id3Data.data.push(data.subarray(offset, start + 188));
id3Data.size += start + 188 - offset;
}
break;
case 0:
if (stt) {
offset += data[offset] + 1;
}
pmtId = this._pmtId = parsePAT(data, offset);
break;
case pmtId:
if (stt) {
offset += data[offset] + 1;
}
var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null); // only update track id if track PID found while parsing PMT
// this is to avoid resetting the PID to -1 in case
// track PID transiently disappears from the stream
// this could happen in case of transient missing audio samples for example
// NOTE this is only the PID of the track as found in TS,
// but we are not using this for MP4 track IDs.
avcId = parsedPIDs.avc;
if (avcId > 0) {
avcTrack.pid = avcId;
}
audioId = parsedPIDs.audio;
if (audioId > 0) {
audioTrack.pid = audioId;
audioTrack.isAAC = parsedPIDs.isAAC;
}
id3Id = parsedPIDs.id3;
if (id3Id > 0) {
id3Track.pid = id3Id;
}
if (unknownPIDs && !pmtParsed) {
logger["logger"].log('reparse from beginning');
unknownPIDs = false; // we set it to -188, the += 188 in the for loop will reset start to 0
start = syncOffset - 188;
}
pmtParsed = this.pmtParsed = true;
break;
case 17:
case 0x1fff:
break;
default:
unknownPIDs = true;
break;
}
} else {
this.observer.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: false,
reason: 'TS packet did not start with 0x47'
});
}
} // try to parse last PES packets
if (avcData && (pes = parsePES(avcData))) {
parseAVCPES(pes, true);
avcTrack.pesData = null;
} else {
// either avcData null or PES truncated, keep it for next frag parsing
avcTrack.pesData = avcData;
}
if (audioData && (pes = parsePES(audioData))) {
if (audioTrack.isAAC) {
parseAACPES(pes);
} else {
parseMPEGPES(pes);
}
audioTrack.pesData = null;
} else {
if (audioData && audioData.size) {
logger["logger"].log('last AAC PES packet truncated,might overlap between fragments');
} // either audioData null or PES truncated, keep it for next frag parsing
audioTrack.pesData = audioData;
}
if (id3Data && (pes = parsePES(id3Data))) {
parseID3PES(pes);
id3Track.pesData = null;
} else {
// either id3Data null or PES truncated, keep it for next frag parsing
id3Track.pesData = id3Data;
}
if (this.sampleAes == null) {
this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
} else {
this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
}
};
_proto.decryptAndRemux = function decryptAndRemux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
if (audioTrack.samples && audioTrack.isAAC) {
var localthis = this;
this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
});
} else {
this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
}
};
_proto.decryptAndRemuxAvc = function decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
if (videoTrack.samples) {
var localthis = this;
this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
});
} else {
this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
}
};
_proto.destroy = function destroy() {
this._initPTS = this._initDTS = undefined;
this._duration = 0;
};
_proto._parsePAT = function _parsePAT(data, offset) {
// skip the PSI header and parse the first PMT entry
return (data[offset + 10] & 0x1F) << 8 | data[offset + 11]; // logger.log('PMT PID:' + this._pmtId);
};
_proto._trackUnknownPmt = function _trackUnknownPmt(type, logLevel, message) {
// Only log unknown and unsupported stream types once per append or stream (by resetting this.pmtUnknownTypes)
// For more information on elementary stream types see:
// https://en.wikipedia.org/wiki/Program-specific_information#Elementary_stream_types
var result = this.pmtUnknownTypes[type] || 0;
if (result === 0) {
this.pmtUnknownTypes[type] = 0;
logLevel.call(logger["logger"], message);
}
this.pmtUnknownTypes[type]++;
return result;
};
_proto._parsePMT = function _parsePMT(data, offset, mpegSupported, isSampleAes) {
var sectionLength,
tableEnd,
programInfoLength,
pid,
result = {
audio: -1,
avc: -1,
id3: -1,
isAAC: true
};
sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
tableEnd = offset + 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
// long the program info descriptors are
programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11]; // advance the offset to the first entry in the mapping table
offset += 12 + programInfoLength;
while (offset < tableEnd) {
pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
switch (data[offset]) {
case 0xcf:
// SAMPLE-AES AAC
if (!isSampleAes) {
this._trackUnknownPmt(data[offset], logger["logger"].warn, 'ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream');
break;
}
/* falls through */
// ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
case 0x0f:
// logger.log('AAC PID:' + pid);
if (result.audio === -1) {
result.audio = pid;
}
break;
// Packetized metadata (ID3)
case 0x15:
// logger.log('ID3 PID:' + pid);
if (result.id3 === -1) {
result.id3 = pid;
}
break;
case 0xdb:
// SAMPLE-AES AVC
if (!isSampleAes) {
this._trackUnknownPmt(data[offset], logger["logger"].warn, 'H.264 with AES-128-CBC slice encryption found in unencrypted stream');
break;
}
/* falls through */
// ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
case 0x1b:
// logger.log('AVC PID:' + pid);
if (result.avc === -1) {
result.avc = pid;
}
break;
// ISO/IEC 11172-3 (MPEG-1 audio)
// or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
case 0x03:
case 0x04:
// logger.log('MPEG PID:' + pid);
if (!mpegSupported) {
this._trackUnknownPmt(data[offset], logger["logger"].warn, 'MPEG audio found, not supported in this browser');
} else if (result.audio === -1) {
result.audio = pid;
result.isAAC = false;
}
break;
case 0x24:
this._trackUnknownPmt(data[offset], logger["logger"].warn, 'Unsupported HEVC stream type found');
break;
default:
this._trackUnknownPmt(data[offset], logger["logger"].log, 'Unknown stream type:' + data[offset]);
break;
} // move to the next table entry
// skip past the elementary stream descriptors, if present
offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
}
return result;
};
_proto._parsePES = function _parsePES(stream) {
var i = 0,
frag,
pesFlags,
pesPrefix,
pesLen,
pesHdrLen,
pesData,
pesPts,
pesDts,
payloadStartOffset,
data = stream.data; // safety check
if (!stream || stream.size === 0) {
return null;
} // we might need up to 19 bytes to read PES header
// if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
// usually only one merge is needed (and this is rare ...)
while (data[0].length < 19 && data.length > 1) {
var newData = new Uint8Array(data[0].length + data[1].length);
newData.set(data[0]);
newData.set(data[1], data[0].length);
data[0] = newData;
data.splice(1, 1);
} // retrieve PTS/DTS from first fragment
frag = data[0];
pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
if (pesPrefix === 1) {
pesLen = (frag[4] << 8) + frag[5]; // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
// minus 6 : PES header size
if (pesLen && pesLen > stream.size - 6) {
return null;
}
pesFlags = frag[7];
if (pesFlags & 0xC0) {
/* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
as Bitwise operators treat their operands as a sequence of 32 bits */
pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
(frag[10] & 0xFF) * 4194304 + // 1 << 22
(frag[11] & 0xFE) * 16384 + // 1 << 14
(frag[12] & 0xFF) * 128 + // 1 << 7
(frag[13] & 0xFE) / 2;
if (pesFlags & 0x40) {
pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
(frag[15] & 0xFF) * 4194304 + // 1 << 22
(frag[16] & 0xFE) * 16384 + // 1 << 14
(frag[17] & 0xFF) * 128 + // 1 << 7
(frag[18] & 0xFE) / 2;
if (pesPts - pesDts > 60 * 90000) {
logger["logger"].warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
pesPts = pesDts;
}
} else {
pesDts = pesPts;
}
}
pesHdrLen = frag[8]; // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
payloadStartOffset = pesHdrLen + 9;
if (stream.size <= payloadStartOffset) {
return null;
}
stream.size -= payloadStartOffset; // reassemble PES packet
pesData = new Uint8Array(stream.size);
for (var j = 0, dataLen = data.length; j < dataLen; j++) {
frag = data[j];
var len = frag.byteLength;
if (payloadStartOffset) {
if (payloadStartOffset > len) {
// trim full frag if PES header bigger than frag
payloadStartOffset -= len;
continue;
} else {
// trim partial frag if PES header smaller than frag
frag = frag.subarray(payloadStartOffset);
len -= payloadStartOffset;
payloadStartOffset = 0;
}
}
pesData.set(frag, i);
i += len;
}
if (pesLen) {
// payload size : remove PES header + PES extension
pesLen -= pesHdrLen + 3;
}
return {
data: pesData,
pts: pesPts,
dts: pesDts,
len: pesLen
};
} else {
return null;
}
};
_proto.pushAccesUnit = function pushAccesUnit(avcSample, avcTrack) {
if (avcSample.units.length && avcSample.frame) {
var samples = avcTrack.samples;
var nbSamples = samples.length; // if sample does not have PTS/DTS, patch with last sample PTS/DTS
if (isNaN(avcSample.pts)) {
if (nbSamples) {
var lastSample = samples[nbSamples - 1];
avcSample.pts = lastSample.pts;
avcSample.dts = lastSample.dts;
} else {
// dropping samples, no timestamp found
avcTrack.dropped++;
return;
}
} // only push AVC sample if starting with a keyframe is not mandatory OR
// if keyframe already found in this fragment OR
// keyframe found in last fragment (track.sps) AND
// samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
if (!this.config.forceKeyFrameOnDiscontinuity || avcSample.key === true || avcTrack.sps && (nbSamples || this.contiguous)) {
avcSample.id = nbSamples;
samples.push(avcSample);
} else {
// dropped samples, track it
avcTrack.dropped++;
}
}
if (avcSample.debug.length) {
logger["logger"].log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
}
};
_proto._parseAVCPES = function _parseAVCPES(pes, last) {
var _this = this;
// logger.log('parse new PES');
var track = this._avcTrack,
units = this._parseAVCNALu(pes.data),
debug = false,
expGolombDecoder,
avcSample = this.avcSample,
push,
spsfound = false,
i,
pushAccesUnit = this.pushAccesUnit.bind(this),
createAVCSample = function createAVCSample(key, pts, dts, debug) {
return {
key: key,
pts: pts,
dts: dts,
units: [],
debug: debug
};
}; // free pes.data to save up some memory
pes.data = null; // if new NAL units found and last sample still there, let's push ...
// this helps parsing streams with missing AUD (only do this if AUD never found)
if (avcSample && units.length && !track.audFound) {
pushAccesUnit(avcSample, track);
avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
}
units.forEach(function (unit) {
switch (unit.type) {
// NDR
case 1:
push = true;
if (!avcSample) {
avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
}
if (debug) {
avcSample.debug += 'NDR ';
}
avcSample.frame = true;
var data = unit.data; // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
if (spsfound && data.length > 4) {
// retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
var sliceType = new exp_golomb(data).readSliceType(); // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
// SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
// An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
// I slice: A slice that is not an SI slice that is decoded using intra prediction only.
// if (sliceType === 2 || sliceType === 7) {
if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
avcSample.key = true;
}
}
break;
// IDR
case 5:
push = true; // handle PES not starting with AUD
if (!avcSample) {
avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
}
if (debug) {
avcSample.debug += 'IDR ';
}
avcSample.key = true;
avcSample.frame = true;
break;
// SEI
case 6:
push = true;
if (debug && avcSample) {
avcSample.debug += 'SEI ';
}
expGolombDecoder = new exp_golomb(_this.discardEPB(unit.data)); // skip frameType
expGolombDecoder.readUByte();
var payloadType = 0;
var payloadSize = 0;
var endOfCaptions = false;
var b = 0;
while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
payloadType = 0;
do {
b = expGolombDecoder.readUByte();
payloadType += b;
} while (b === 0xFF); // Parse payload size.
payloadSize = 0;
do {
b = expGolombDecoder.readUByte();
payloadSize += b;
} while (b === 0xFF); // TODO: there can be more than one payload in an SEI packet...
// TODO: need to read type and size in a while loop to get them all
if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
endOfCaptions = true;
var countryCode = expGolombDecoder.readUByte();
if (countryCode === 181) {
var providerCode = expGolombDecoder.readUShort();
if (providerCode === 49) {
var userStructure = expGolombDecoder.readUInt();
if (userStructure === 0x47413934) {
var userDataType = expGolombDecoder.readUByte(); // Raw CEA-608 bytes wrapped in CEA-708 packet
if (userDataType === 3) {
var firstByte = expGolombDecoder.readUByte();
var secondByte = expGolombDecoder.readUByte();
var totalCCs = 31 & firstByte;
var byteArray = [firstByte, secondByte];
for (i = 0; i < totalCCs; i++) {
// 3 bytes per CC
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
byteArray.push(expGolombDecoder.readUByte());
}
_this._insertSampleInOrder(_this._txtTrack.samples, {
type: 3,
pts: pes.pts,
bytes: byteArray
});
}
}
}
}
} else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {
endOfCaptions = true;
if (payloadSize > 16) {
var uuidStrArray = [];
for (i = 0; i < 16; i++) {
uuidStrArray.push(expGolombDecoder.readUByte().toString(16));
if (i === 3 || i === 5 || i === 7 || i === 9) {
uuidStrArray.push('-');
}
}
var length = payloadSize - 16;
var userDataPayloadBytes = new Uint8Array(length);
for (i = 0; i < length; i++) {
userDataPayloadBytes[i] = expGolombDecoder.readUByte();
}
_this._insertSampleInOrder(_this._txtTrack.samples, {
pts: pes.pts,
payloadType: payloadType,
uuid: uuidStrArray.join(''),
userDataBytes: userDataPayloadBytes,
userData: Object(id3["utf8ArrayToStr"])(userDataPayloadBytes.buffer)
});
}
} else if (payloadSize < expGolombDecoder.bytesAvailable) {
for (i = 0; i < payloadSize; i++) {
expGolombDecoder.readUByte();
}
}
}
break;
// SPS
case 7:
push = true;
spsfound = true;
if (debug && avcSample) {
avcSample.debug += 'SPS ';
}
if (!track.sps) {
expGolombDecoder = new exp_golomb(unit.data);
var config = expGolombDecoder.readSPS();
track.width = config.width;
track.height = config.height;
track.pixelRatio = config.pixelRatio;
track.sps = [unit.data];
track.duration = _this._duration;
var codecarray = unit.data.subarray(1, 4);
var codecstring = 'avc1.';
for (i = 0; i < 3; i++) {
var h = codecarray[i].toString(16);
if (h.length < 2) {
h = '0' + h;
}
codecstring += h;
}
track.codec = codecstring;
}
break;
// PPS
case 8:
push = true;
if (debug && avcSample) {
avcSample.debug += 'PPS ';
}
if (!track.pps) {
track.pps = [unit.data];
}
break;
// AUD
case 9:
push = false;
track.audFound = true;
if (avcSample) {
pushAccesUnit(avcSample, track);
}
avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
break;
// Filler Data
case 12:
push = false;
break;
default:
push = false;
if (avcSample) {
avcSample.debug += 'unknown NAL ' + unit.type + ' ';
}
break;
}
if (avcSample && push) {
var _units = avcSample.units;
_units.push(unit);
}
}); // if last PES packet, push samples
if (last && avcSample) {
pushAccesUnit(avcSample, track);
this.avcSample = null;
}
};
_proto._insertSampleInOrder = function _insertSampleInOrder(arr, data) {
var len = arr.length;
if (len > 0) {
if (data.pts >= arr[len - 1].pts) {
arr.push(data);
} else {
for (var pos = len - 1; pos >= 0; pos--) {
if (data.pts < arr[pos].pts) {
arr.splice(pos, 0, data);
break;
}
}
}
} else {
arr.push(data);
}
};
_proto._getLastNalUnit = function _getLastNalUnit() {
var avcSample = this.avcSample,
lastUnit; // try to fallback to previous sample if current one is empty
if (!avcSample || avcSample.units.length === 0) {
var track = this._avcTrack,
samples = track.samples;
avcSample = samples[samples.length - 1];
}
if (avcSample) {
var units = avcSample.units;
lastUnit = units[units.length - 1];
}
return lastUnit;
};
_proto._parseAVCNALu = function _parseAVCNALu(array) {
var i = 0,
len = array.byteLength,
value,
overflow,
track = this._avcTrack,
state = track.naluState || 0,
lastState = state;
var units = [],
unit,
unitType,
lastUnitStart = -1,
lastUnitType; // logger.log('PES:' + Hex.hexDump(array));
if (state === -1) {
// special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
lastUnitStart = 0; // NALu type is value read from offset 0
lastUnitType = array[0] & 0x1f;
state = 0;
i = 1;
}
while (i < len) {
value = array[i++]; // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
if (!state) {
state = value ? 0 : 1;
continue;
}
if (state === 1) {
state = value ? 0 : 2;
continue;
} // here we have state either equal to 2 or 3
if (!value) {
state = 3;
} else if (value === 1) {
if (lastUnitStart >= 0) {
unit = {
data: array.subarray(lastUnitStart, i - state - 1),
type: lastUnitType
}; // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
units.push(unit);
} else {
// lastUnitStart is undefined => this is the first start code found in this PES packet
// first check if start code delimiter is overlapping between 2 PES packets,
// ie it started in last packet (lastState not zero)
// and ended at the beginning of this PES packet (i <= 4 - lastState)
var lastUnit = this._getLastNalUnit();
if (lastUnit) {
if (lastState && i <= 4 - lastState) {
// start delimiter overlapping between PES packets
// strip start delimiter bytes from the end of last NAL unit
// check if lastUnit had a state different from zero
if (lastUnit.state) {
// strip last bytes
lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
}
} // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
overflow = i - state - 1;
if (overflow > 0) {
// logger.log('first NALU found with overflow:' + overflow);
var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
tmp.set(lastUnit.data, 0);
tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
lastUnit.data = tmp;
}
}
} // check if we can read unit type
if (i < len) {
unitType = array[i] & 0x1f; // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
lastUnitStart = i;
lastUnitType = unitType;
state = 0;
} else {
// not enough byte to read unit type. let's read it on next PES parsing
state = -1;
}
} else {
state = 0;
}
}
if (lastUnitStart >= 0 && state >= 0) {
unit = {
data: array.subarray(lastUnitStart, len),
type: lastUnitType,
state: state
};
units.push(unit); // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
} // no NALu found
if (units.length === 0) {
// append pes.data to previous NAL unit
var _lastUnit = this._getLastNalUnit();
if (_lastUnit) {
var _tmp = new Uint8Array(_lastUnit.data.byteLength + array.byteLength);
_tmp.set(_lastUnit.data, 0);
_tmp.set(array, _lastUnit.data.byteLength);
_lastUnit.data = _tmp;
}
}
track.naluState = state;
return units;
}
/**
* remove Emulation Prevention bytes from a RBSP
*/
;
_proto.discardEPB = function discardEPB(data) {
var length = data.byteLength,
EPBPositions = [],
i = 1,
newLength,
newData; // Find all `Emulation Prevention Bytes`
while (i < length - 2) {
if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
EPBPositions.push(i + 2);
i += 2;
} else {
i++;
}
} // If no Emulation Prevention Bytes were found just return the original
// array
if (EPBPositions.length === 0) {
return data;
} // Create a new array to hold the NAL unit data
newLength = length - EPBPositions.length;
newData = new Uint8Array(newLength);
var sourceIndex = 0;
for (i = 0; i < newLength; sourceIndex++, i++) {
if (sourceIndex === EPBPositions[0]) {
// Skip this byte
sourceIndex++; // Remove this position index
EPBPositions.shift();
}
newData[i] = data[sourceIndex];
}
return newData;
};
_proto._parseAACPES = function _parseAACPES(pes) {
var track = this._audioTrack,
data = pes.data,
pts = pes.pts,
startOffset = 0,
aacOverFlow = this.aacOverFlow,
aacLastPTS = this.aacLastPTS,
frameDuration,
frameIndex,
offset,
stamp,
len;
if (aacOverFlow) {
var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
tmp.set(aacOverFlow, 0);
tmp.set(data, aacOverFlow.byteLength); // logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
data = tmp;
} // look for ADTS header (0xFFFx)
for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
if (isHeader(data, offset)) {
break;
}
} // if ADTS header does not start straight from the beginning of the PES payload, raise an error
if (offset) {
var reason, fatal;
if (offset < len - 1) {
reason = "AAC PES did not start with ADTS header,offset:" + offset;
fatal = false;
} else {
reason = 'no ADTS header found in AAC PES';
fatal = true;
}
logger["logger"].warn("parsing error:" + reason);
this.observer.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: fatal,
reason: reason
});
if (fatal) {
return;
}
}
initTrackConfig(track, this.observer, data, offset, this.audioCodec);
frameIndex = 0;
frameDuration = getFrameDuration(track.samplerate); // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
// first sample PTS should be equal to last sample PTS + frameDuration
if (aacOverFlow && aacLastPTS) {
var newPTS = aacLastPTS + frameDuration;
if (Math.abs(newPTS - pts) > 1) {
logger["logger"].log("AAC: align PTS for overlapping frames by " + Math.round((newPTS - pts) / 90));
pts = newPTS;
}
} // scan for aac samples
while (offset < len) {
if (isHeader(data, offset)) {
if (offset + 5 < len) {
var frame = appendFrame(track, data, offset, pts, frameIndex);
if (frame) {
offset += frame.length;
stamp = frame.sample.pts;
frameIndex++;
continue;
}
} // We are at an ADTS header, but do not have enough data for a frame
// Remaining data will be added to aacOverFlow
break;
} else {
// nothing found, keep looking
offset++;
}
}
if (offset < len) {
aacOverFlow = data.subarray(offset, len); // logger.log(`AAC: overflow detected:${len-offset}`);
} else {
aacOverFlow = null;
}
this.aacOverFlow = aacOverFlow;
this.aacLastPTS = stamp;
};
_proto._parseMPEGPES = function _parseMPEGPES(pes) {
var data = pes.data;
var length = data.length;
var frameIndex = 0;
var offset = 0;
var pts = pes.pts;
while (offset < length) {
if (mpegaudio.isHeader(data, offset)) {
var frame = mpegaudio.appendFrame(this._audioTrack, data, offset, pts, frameIndex);
if (frame) {
offset += frame.length;
frameIndex++;
} else {
// logger.log('Unable to parse Mpeg audio frame');
break;
}
} else {
// nothing found, keep looking
offset++;
}
}
};
_proto._parseID3PES = function _parseID3PES(pes) {
this._id3Track.samples.push(pes);
};
return TSDemuxer;
}();
/* harmony default export */ var tsdemuxer = (tsdemuxer_TSDemuxer);
// CONCATENATED MODULE: ./src/demux/mp3demuxer.js
/**
* MP3 demuxer
*/
var mp3demuxer_MP3Demuxer = /*#__PURE__*/function () {
function MP3Demuxer(observer, remuxer, config) {
this.observer = observer;
this.config = config;
this.remuxer = remuxer;
}
var _proto = MP3Demuxer.prototype;
_proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
this._audioTrack = {
container: 'audio/mpeg',
type: 'audio',
id: -1,
sequenceNumber: 0,
isAAC: false,
samples: [],
len: 0,
manifestCodec: audioCodec,
duration: duration,
inputTimeScale: 90000
};
};
_proto.resetTimeStamp = function resetTimeStamp() {};
MP3Demuxer.probe = function probe(data) {
// check if data contains ID3 timestamp and MPEG sync word
var offset, length;
var id3Data = id3["default"].getID3Data(data, 0);
if (id3Data && id3["default"].getTimeStamp(id3Data) !== undefined) {
// Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
// Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
// More info http://www.mp3-tech.org/programmer/frame_header.html
for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {
if (mpegaudio.probe(data, offset)) {
logger["logger"].log('MPEG Audio sync word found !');
return true;
}
}
}
return false;
} // feed incoming data to the front of the parsing pipeline
;
_proto.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
var id3Data = id3["default"].getID3Data(data, 0) || [];
var timestamp = id3["default"].getTimeStamp(id3Data);
var pts = timestamp !== undefined ? 90 * timestamp : timeOffset * 90000;
var offset = id3Data.length;
var length = data.length;
var frameIndex = 0,
stamp = 0;
var track = this._audioTrack;
var id3Samples = [{
pts: pts,
dts: pts,
data: id3Data
}];
while (offset < length) {
if (mpegaudio.isHeader(data, offset)) {
var frame = mpegaudio.appendFrame(track, data, offset, pts, frameIndex);
if (frame) {
offset += frame.length;
stamp = frame.sample.pts;
frameIndex++;
} else {
// logger.log('Unable to parse Mpeg audio frame');
break;
}
} else if (id3["default"].isHeader(data, offset)) {
id3Data = id3["default"].getID3Data(data, offset);
id3Samples.push({
pts: stamp,
dts: stamp,
data: id3Data
});
offset += id3Data.length;
} else {
// nothing found, keep looking
offset++;
}
}
this.remuxer.remux(track, {
samples: []
}, {
samples: id3Samples,
inputTimeScale: 90000
}, {
samples: []
}, timeOffset, contiguous, accurateTimeOffset);
};
_proto.destroy = function destroy() {};
return MP3Demuxer;
}();
/* harmony default export */ var mp3demuxer = (mp3demuxer_MP3Demuxer);
// CONCATENATED MODULE: ./src/remux/aac-helper.js
/**
* AAC helper
*/
var AAC = /*#__PURE__*/function () {
function AAC() {}
AAC.getSilentFrame = function getSilentFrame(codec, channelCount) {
switch (codec) {
case 'mp4a.40.2':
if (channelCount === 1) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
} else if (channelCount === 2) {
return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
} else if (channelCount === 3) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
} else if (channelCount === 4) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
} else if (channelCount === 5) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
} else if (channelCount === 6) {
return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);
}
break;
// handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
default:
if (channelCount === 1) {
// ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
} else if (channelCount === 2) {
// ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
} else if (channelCount === 3) {
// ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
}
break;
}
return null;
};
return AAC;
}();
/* harmony default export */ var aac_helper = (AAC);
// CONCATENATED MODULE: ./src/remux/mp4-generator.js
/**
* Generate MP4 Box
*/
var UINT32_MAX = Math.pow(2, 32) - 1;
var MP4 = /*#__PURE__*/function () {
function MP4() {}
MP4.init = function init() {
MP4.types = {
avc1: [],
// codingname
avcC: [],
btrt: [],
dinf: [],
dref: [],
esds: [],
ftyp: [],
hdlr: [],
mdat: [],
mdhd: [],
mdia: [],
mfhd: [],
minf: [],
moof: [],
moov: [],
mp4a: [],
'.mp3': [],
mvex: [],
mvhd: [],
pasp: [],
sdtp: [],
stbl: [],
stco: [],
stsc: [],
stsd: [],
stsz: [],
stts: [],
tfdt: [],
tfhd: [],
traf: [],
trak: [],
trun: [],
trex: [],
tkhd: [],
vmhd: [],
smhd: []
};
var i;
for (i in MP4.types) {
if (MP4.types.hasOwnProperty(i)) {
MP4.types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
}
}
var videoHdlr = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
]);
var audioHdlr = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // pre_defined
0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
]);
MP4.HDLR_TYPES = {
'video': videoHdlr,
'audio': audioHdlr
};
var dref = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01, // entry_count
0x00, 0x00, 0x00, 0x0c, // entry_size
0x75, 0x72, 0x6c, 0x20, // 'url' type
0x00, // version 0
0x00, 0x00, 0x01 // entry_flags
]);
var stco = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00 // entry_count
]);
MP4.STTS = MP4.STSC = MP4.STCO = stco;
MP4.STSZ = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, // sample_size
0x00, 0x00, 0x00, 0x00 // sample_count
]);
MP4.VMHD = new Uint8Array([0x00, // version
0x00, 0x00, 0x01, // flags
0x00, 0x00, // graphicsmode
0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
]);
MP4.SMHD = new Uint8Array([0x00, // version
0x00, 0x00, 0x00, // flags
0x00, 0x00, // balance
0x00, 0x00 // reserved
]);
MP4.STSD = new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x01]); // entry_count
var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
var minorVersion = new Uint8Array([0, 0, 0, 1]);
MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
};
MP4.box = function box(type) {
var payload = Array.prototype.slice.call(arguments, 1),
size = 8,
i = payload.length,
len = i,
result; // calculate the total size we need to allocate
while (i--) {
size += payload[i].byteLength;
}
result = new Uint8Array(size);
result[0] = size >> 24 & 0xff;
result[1] = size >> 16 & 0xff;
result[2] = size >> 8 & 0xff;
result[3] = size & 0xff;
result.set(type, 4); // copy the payload into the result
for (i = 0, size = 8; i < len; i++) {
// copy payload[i] array @ offset size
result.set(payload[i], size);
size += payload[i].byteLength;
}
return result;
};
MP4.hdlr = function hdlr(type) {
return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
};
MP4.mdat = function mdat(data) {
return MP4.box(MP4.types.mdat, data);
};
MP4.mdhd = function mdhd(timescale, duration) {
duration *= timescale;
var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
return MP4.box(MP4.types.mdhd, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x55, 0xc4, // 'und' language (undetermined)
0x00, 0x00]));
};
MP4.mdia = function mdia(track) {
return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
};
MP4.mfhd = function mfhd(sequenceNumber) {
return MP4.box(MP4.types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
sequenceNumber >> 24, sequenceNumber >> 16 & 0xFF, sequenceNumber >> 8 & 0xFF, sequenceNumber & 0xFF // sequence_number
]));
};
MP4.minf = function minf(track) {
if (track.type === 'audio') {
return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
} else {
return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
}
};
MP4.moof = function moof(sn, baseMediaDecodeTime, track) {
return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
}
/**
* @param tracks... (optional) {array} the tracks associated with this movie
*/
;
MP4.moov = function moov(tracks) {
var i = tracks.length,
boxes = [];
while (i--) {
boxes[i] = MP4.trak(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
};
MP4.mvex = function mvex(tracks) {
var i = tracks.length,
boxes = [];
while (i--) {
boxes[i] = MP4.trex(tracks[i]);
}
return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
};
MP4.mvhd = function mvhd(timescale, duration) {
duration *= timescale;
var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
var bytes = new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
timescale >> 24 & 0xFF, timescale >> 16 & 0xFF, timescale >> 8 & 0xFF, timescale & 0xFF, // timescale
upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x00, 0x01, 0x00, 0x00, // 1.0 rate
0x01, 0x00, // 1.0 volume
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
0xff, 0xff, 0xff, 0xff // next_track_ID
]);
return MP4.box(MP4.types.mvhd, bytes);
};
MP4.sdtp = function sdtp(track) {
var samples = track.samples || [],
bytes = new Uint8Array(4 + samples.length),
flags,
i; // leave the full box header (4 bytes) all zero
// write the sample table
for (i = 0; i < samples.length; i++) {
flags = samples[i].flags;
bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
}
return MP4.box(MP4.types.sdtp, bytes);
};
MP4.stbl = function stbl(track) {
return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
};
MP4.avc1 = function avc1(track) {
var sps = [],
pps = [],
i,
data,
len; // assemble the SPSs
for (i = 0; i < track.sps.length; i++) {
data = track.sps[i];
len = data.byteLength;
sps.push(len >>> 8 & 0xFF);
sps.push(len & 0xFF); // SPS
sps = sps.concat(Array.prototype.slice.call(data));
} // assemble the PPSs
for (i = 0; i < track.pps.length; i++) {
data = track.pps[i];
len = data.byteLength;
pps.push(len >>> 8 & 0xFF);
pps.push(len & 0xFF);
pps = pps.concat(Array.prototype.slice.call(data));
}
var avcc = MP4.box(MP4.types.avcC, new Uint8Array([0x01, // version
sps[3], // profile
sps[4], // profile compat
sps[5], // level
0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes
0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
].concat(sps).concat([track.pps.length // numOfPictureParameterSets
]).concat(pps))),
// "PPS"
width = track.width,
height = track.height,
hSpacing = track.pixelRatio[0],
vSpacing = track.pixelRatio[1];
return MP4.box(MP4.types.avc1, new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, // pre_defined
0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
width >> 8 & 0xFF, width & 0xff, // width
height >> 8 & 0xFF, height & 0xff, // height
0x00, 0x48, 0x00, 0x00, // horizresolution
0x00, 0x48, 0x00, 0x00, // vertresolution
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x01, // frame_count
0x12, 0x64, 0x61, 0x69, 0x6C, // dailymotion/hls.js
0x79, 0x6D, 0x6F, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x68, 0x6C, 0x73, 0x2E, 0x6A, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
0x00, 0x18, // depth = 24
0x11, 0x11]), // pre_defined = -1
avcc, MP4.box(MP4.types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate
MP4.box(MP4.types.pasp, new Uint8Array([hSpacing >> 24, // hSpacing
hSpacing >> 16 & 0xFF, hSpacing >> 8 & 0xFF, hSpacing & 0xFF, vSpacing >> 24, // vSpacing
vSpacing >> 16 & 0xFF, vSpacing >> 8 & 0xFF, vSpacing & 0xFF])));
};
MP4.esds = function esds(track) {
var configlen = track.config.length;
return new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
0x03, // descriptor_type
0x17 + configlen, // length
0x00, 0x01, // es_id
0x00, // stream_priority
0x04, // descriptor_type
0x0f + configlen, // length
0x40, // codec : mpeg4_audio
0x15, // stream_type
0x00, 0x00, 0x00, // buffer_size
0x00, 0x00, 0x00, 0x00, // maxBitrate
0x00, 0x00, 0x00, 0x00, // avgBitrate
0x05 // descriptor_type
].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
};
MP4.mp4a = function mp4a(track) {
var samplerate = track.samplerate;
return MP4.box(MP4.types.mp4a, new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, track.channelCount, // channelcount
0x00, 0x10, // sampleSize:16bits
0x00, 0x00, 0x00, 0x00, // reserved2
samplerate >> 8 & 0xFF, samplerate & 0xff, //
0x00, 0x00]), MP4.box(MP4.types.esds, MP4.esds(track)));
};
MP4.mp3 = function mp3(track) {
var samplerate = track.samplerate;
return MP4.box(MP4.types['.mp3'], new Uint8Array([0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, // reserved
0x00, 0x01, // data_reference_index
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, track.channelCount, // channelcount
0x00, 0x10, // sampleSize:16bits
0x00, 0x00, 0x00, 0x00, // reserved2
samplerate >> 8 & 0xFF, samplerate & 0xff, //
0x00, 0x00]));
};
MP4.stsd = function stsd(track) {
if (track.type === 'audio') {
if (!track.isAAC && track.codec === 'mp3') {
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
}
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
} else {
return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
}
};
MP4.tkhd = function tkhd(track) {
var id = track.id,
duration = track.duration * track.timescale,
width = track.width,
height = track.height,
upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),
lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
return MP4.box(MP4.types.tkhd, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x07, // flags
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time
id >> 24 & 0xFF, id >> 16 & 0xFF, id >> 8 & 0xFF, id & 0xFF, // track_ID
0x00, 0x00, 0x00, 0x00, // reserved
upperWordDuration >> 24, upperWordDuration >> 16 & 0xFF, upperWordDuration >> 8 & 0xFF, upperWordDuration & 0xFF, lowerWordDuration >> 24, lowerWordDuration >> 16 & 0xFF, lowerWordDuration >> 8 & 0xFF, lowerWordDuration & 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, // layer
0x00, 0x00, // alternate_group
0x00, 0x00, // non-audio track volume
0x00, 0x00, // reserved
0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
width >> 8 & 0xFF, width & 0xFF, 0x00, 0x00, // width
height >> 8 & 0xFF, height & 0xFF, 0x00, 0x00 // height
]));
};
MP4.traf = function traf(track, baseMediaDecodeTime) {
var sampleDependencyTable = MP4.sdtp(track),
id = track.id,
upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),
lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF // track_ID
])), MP4.box(MP4.types.tfdt, new Uint8Array([0x01, // version 1
0x00, 0x00, 0x00, // flags
upperWordBaseMediaDecodeTime >> 24, upperWordBaseMediaDecodeTime >> 16 & 0XFF, upperWordBaseMediaDecodeTime >> 8 & 0XFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >> 24, lowerWordBaseMediaDecodeTime >> 16 & 0XFF, lowerWordBaseMediaDecodeTime >> 8 & 0XFF, lowerWordBaseMediaDecodeTime & 0xFF])), MP4.trun(track, sampleDependencyTable.length + 16 + // tfhd
20 + // tfdt
8 + // traf header
16 + // mfhd
8 + // moof header
8), // mdat header
sampleDependencyTable);
}
/**
* Generate a track box.
* @param track {object} a track definition
* @return {Uint8Array} the track box
*/
;
MP4.trak = function trak(track) {
track.duration = track.duration || 0xffffffff;
return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
};
MP4.trex = function trex(track) {
var id = track.id;
return MP4.box(MP4.types.trex, new Uint8Array([0x00, // version 0
0x00, 0x00, 0x00, // flags
id >> 24, id >> 16 & 0XFF, id >> 8 & 0XFF, id & 0xFF, // track_ID
0x00, 0x00, 0x00, 0x01, // default_sample_description_index
0x00, 0x00, 0x00, 0x00, // default_sample_duration
0x00, 0x00, 0x00, 0x00, // default_sample_size
0x00, 0x01, 0x00, 0x01 // default_sample_flags
]));
};
MP4.trun = function trun(track, offset) {
var samples = track.samples || [],
len = samples.length,
arraylen = 12 + 16 * len,
array = new Uint8Array(arraylen),
i,
sample,
duration,
size,
flags,
cts;
offset += 8 + arraylen;
array.set([0x00, // version 0
0x00, 0x0f, 0x01, // flags
len >>> 24 & 0xFF, len >>> 16 & 0xFF, len >>> 8 & 0xFF, len & 0xFF, // sample_count
offset >>> 24 & 0xFF, offset >>> 16 & 0xFF, offset >>> 8 & 0xFF, offset & 0xFF // data_offset
], 0);
for (i = 0; i < len; i++) {
sample = samples[i];
duration = sample.duration;
size = sample.size;
flags = sample.flags;
cts = sample.cts;
array.set([duration >>> 24 & 0xFF, duration >>> 16 & 0xFF, duration >>> 8 & 0xFF, duration & 0xFF, // sample_duration
size >>> 24 & 0xFF, size >>> 16 & 0xFF, size >>> 8 & 0xFF, size & 0xFF, // sample_size
flags.isLeading << 2 | flags.dependsOn, flags.isDependedOn << 6 | flags.hasRedundancy << 4 | flags.paddingValue << 1 | flags.isNonSync, flags.degradPrio & 0xF0 << 8, flags.degradPrio & 0x0F, // sample_flags
cts >>> 24 & 0xFF, cts >>> 16 & 0xFF, cts >>> 8 & 0xFF, cts & 0xFF // sample_composition_time_offset
], 12 + 16 * i);
}
return MP4.box(MP4.types.trun, array);
};
MP4.initSegment = function initSegment(tracks) {
if (!MP4.types) {
MP4.init();
}
var movie = MP4.moov(tracks),
result;
result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
result.set(MP4.FTYP);
result.set(movie, MP4.FTYP.byteLength);
return result;
};
return MP4;
}();
/* harmony default export */ var mp4_generator = (MP4);
// CONCATENATED MODULE: ./src/utils/timescale-conversion.ts
var MPEG_TS_CLOCK_FREQ_HZ = 90000;
function toTimescaleFromBase(value, destScale, srcBase, round) {
if (srcBase === void 0) {
srcBase = 1;
}
if (round === void 0) {
round = false;
}
var result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`
return round ? Math.round(result) : result;
}
function toTimescaleFromScale(value, destScale, srcScale, round) {
if (srcScale === void 0) {
srcScale = 1;
}
if (round === void 0) {
round = false;
}
return toTimescaleFromBase(value, destScale, 1 / srcScale);
}
function toMsFromMpegTsClock(value, round) {
if (round === void 0) {
round = false;
}
return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);
}
function toMpegTsClockFromTimescale(value, srcScale) {
if (srcScale === void 0) {
srcScale = 1;
}
return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);
}
// CONCATENATED MODULE: ./src/remux/mp4-remuxer.js
/**
* fMP4 remuxer
*/
var MAX_SILENT_FRAME_DURATION_90KHZ = toMpegTsClockFromTimescale(10);
var PTS_DTS_SHIFT_TOLERANCE_90KHZ = toMpegTsClockFromTimescale(0.2);
var chromeVersion = null;
var mp4_remuxer_MP4Remuxer = /*#__PURE__*/function () {
function MP4Remuxer(observer, config, typeSupported, vendor) {
this.observer = observer;
this.config = config;
this.typeSupported = typeSupported;
this.ISGenerated = false;
if (chromeVersion === null) {
var result = navigator.userAgent.match(/Chrome\/(\d+)/i);
chromeVersion = result ? parseInt(result[1]) : 0;
}
}
var _proto = MP4Remuxer.prototype;
_proto.destroy = function destroy() {};
_proto.resetTimeStamp = function resetTimeStamp(defaultTimeStamp) {
this._initPTS = this._initDTS = defaultTimeStamp;
};
_proto.resetInitSegment = function resetInitSegment() {
this.ISGenerated = false;
};
_proto.getVideoStartPts = function getVideoStartPts(videoSamples) {
var rolloverDetected = false;
var startPTS = videoSamples.reduce(function (minPTS, sample) {
var delta = sample.pts - minPTS;
if (delta < -4294967296) {
// 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation
rolloverDetected = true;
return PTSNormalize(minPTS, sample.pts);
} else if (delta > 0) {
return minPTS;
} else {
return sample.pts;
}
}, videoSamples[0].pts);
if (rolloverDetected) {
logger["logger"].debug('PTS rollover detected');
}
return startPTS;
};
_proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
// generate Init Segment if needed
if (!this.ISGenerated) {
this.generateIS(audioTrack, videoTrack, timeOffset);
}
if (this.ISGenerated) {
var nbAudioSamples = audioTrack.samples.length;
var nbVideoSamples = videoTrack.samples.length;
var audioTimeOffset = timeOffset;
var videoTimeOffset = timeOffset;
if (nbAudioSamples && nbVideoSamples) {
// timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
// if first audio DTS is not aligned with first video DTS then we need to take that into account
// when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
// drift between audio and video streams
var startPTS = this.getVideoStartPts(videoTrack.samples);
var tsDelta = PTSNormalize(audioTrack.samples[0].pts, startPTS) - startPTS;
var audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;
audioTimeOffset += Math.max(0, audiovideoTimestampDelta);
videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);
} // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is
// calculated in remuxAudio.
// logger.log('nb AAC samples:' + audioTrack.samples.length);
if (nbAudioSamples) {
// if initSegment was generated without video samples, regenerate it again
if (!audioTrack.timescale) {
logger["logger"].warn('regenerate InitSegment as audio detected');
this.generateIS(audioTrack, videoTrack, timeOffset);
}
var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset, videoTimeOffset); // logger.log('nb AVC samples:' + videoTrack.samples.length);
if (nbVideoSamples) {
var audioTrackLength;
if (audioData) {
audioTrackLength = audioData.endPTS - audioData.startPTS;
} // if initSegment was generated without video samples, regenerate it again
if (!videoTrack.timescale) {
logger["logger"].warn('regenerate InitSegment as video detected');
this.generateIS(audioTrack, videoTrack, timeOffset);
}
this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength);
}
} else {
// logger.log('nb AVC samples:' + videoTrack.samples.length);
if (nbVideoSamples) {
var videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0);
if (videoData && audioTrack.codec) {
this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);
}
}
}
} // logger.log('nb ID3 samples:' + audioTrack.samples.length);
if (id3Track.samples.length) {
this.remuxID3(id3Track, timeOffset);
} // logger.log('nb ID3 samples:' + audioTrack.samples.length);
if (textTrack.samples.length) {
this.remuxText(textTrack, timeOffset);
} // notify end of parsing
this.observer.trigger(events["default"].FRAG_PARSED);
};
_proto.generateIS = function generateIS(audioTrack, videoTrack, timeOffset) {
var observer = this.observer,
audioSamples = audioTrack.samples,
videoSamples = videoTrack.samples,
typeSupported = this.typeSupported,
container = 'audio/mp4',
tracks = {},
data = {
tracks: tracks
},
computePTSDTS = this._initPTS === undefined,
initPTS,
initDTS;
if (computePTSDTS) {
initPTS = initDTS = Infinity;
}
if (audioTrack.config && audioSamples.length) {
// let's use audio sampling rate as MP4 time scale.
// rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
// using audio sampling rate here helps having an integer MP4 frame duration
// this avoids potential rounding issue and AV sync issue
audioTrack.timescale = audioTrack.samplerate;
logger["logger"].log("audio sampling rate : " + audioTrack.samplerate);
if (!audioTrack.isAAC) {
if (typeSupported.mpeg) {
// Chrome and Safari
container = 'audio/mpeg';
audioTrack.codec = '';
} else if (typeSupported.mp3) {
// Firefox
audioTrack.codec = 'mp3';
}
}
tracks.audio = {
container: container,
codec: audioTrack.codec,
initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : mp4_generator.initSegment([audioTrack]),
metadata: {
channelCount: audioTrack.channelCount
}
};
if (computePTSDTS) {
// remember first PTS of this demuxing context. for audio, PTS = DTS
initPTS = initDTS = audioSamples[0].pts - Math.round(audioTrack.inputTimeScale * timeOffset);
}
}
if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
// let's use input time scale as MP4 video timescale
// we use input time scale straight away to avoid rounding issues on frame duration / cts computation
var inputTimeScale = videoTrack.inputTimeScale;
videoTrack.timescale = inputTimeScale;
tracks.video = {
container: 'video/mp4',
codec: videoTrack.codec,
initSegment: mp4_generator.initSegment([videoTrack]),
metadata: {
width: videoTrack.width,
height: videoTrack.height
}
};
if (computePTSDTS) {
var startPTS = this.getVideoStartPts(videoSamples);
var startOffset = Math.round(inputTimeScale * timeOffset);
initDTS = Math.min(initDTS, PTSNormalize(videoSamples[0].dts, startPTS) - startOffset);
initPTS = Math.min(initPTS, startPTS - startOffset);
this.observer.trigger(events["default"].INIT_PTS_FOUND, {
initPTS: initPTS
});
}
} else if (computePTSDTS && tracks.audio) {
// initPTS found for audio-only stream with main and alt audio
this.observer.trigger(events["default"].INIT_PTS_FOUND, {
initPTS: initPTS
});
}
if (Object.keys(tracks).length) {
observer.trigger(events["default"].FRAG_PARSING_INIT_SEGMENT, data);
this.ISGenerated = true;
if (computePTSDTS) {
this._initPTS = initPTS;
this._initDTS = initDTS;
}
} else {
observer.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: false,
reason: 'no audio/video samples found'
});
}
};
_proto.remuxVideo = function remuxVideo(track, timeOffset, contiguous, audioTrackLength) {
var timeScale = track.timescale;
var inputSamples = track.samples;
var outputSamples = [];
var nbSamples = inputSamples.length;
var initPTS = this._initPTS;
var offset = 8;
var mp4SampleDuration;
var mdat;
var moof;
var firstDTS;
var lastDTS;
var minPTS = Number.POSITIVE_INFINITY;
var maxPTS = Number.NEGATIVE_INFINITY;
var ptsDtsShift = 0;
var sortSamples = false; // if parsed fragment is contiguous with last one, let's use last DTS value as reference
var nextAvcDts = this.nextAvcDts;
if (nbSamples === 0) {
return;
}
if (!contiguous) {
var pts = timeOffset * timeScale;
var cts = inputSamples[0].pts - PTSNormalize(inputSamples[0].dts, inputSamples[0].pts); // if not contiguous, let's use target timeOffset
nextAvcDts = pts - cts;
} // PTS is coded on 33bits, and can loop from -2^32 to 2^32
// PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
for (var i = 0; i < nbSamples; i++) {
var sample = inputSamples[i];
sample.pts = PTSNormalize(sample.pts - initPTS, nextAvcDts);
sample.dts = PTSNormalize(sample.dts - initPTS, nextAvcDts);
if (sample.dts > sample.pts) {
ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ);
}
if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {
sortSamples = true;
}
} // sort video samples by DTS then PTS then demux id order
if (sortSamples) {
inputSamples.sort(function (a, b) {
var deltadts = a.dts - b.dts;
var deltapts = a.pts - b.pts;
return deltadts || deltapts || a.id - b.id;
});
} // Get first/last DTS
firstDTS = inputSamples[0].dts;
lastDTS = inputSamples[nbSamples - 1].dts; // on Safari let's signal the same sample duration for all samples
// sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
// set this constant duration as being the avg delta between consecutive DTS.
var averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1)); // handle broken streams with PTS < DTS, tolerance up 0.2 seconds
if (ptsDtsShift < 0) {
if (ptsDtsShift < averageSampleDuration * -2) {
// Fix for "CNN special report, with CC" in test-streams (including Safari browser)
// With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values
logger["logger"].warn("PTS < DTS detected in video samples, offsetting DTS from PTS by " + toMsFromMpegTsClock(-averageSampleDuration, true) + " ms");
var lastDts = ptsDtsShift;
for (var _i = 0; _i < nbSamples; _i++) {
inputSamples[_i].dts = lastDts = Math.max(lastDts, inputSamples[_i].pts - averageSampleDuration);
inputSamples[_i].pts = Math.max(lastDts, inputSamples[_i].pts);
}
} else {
// Fix for "Custom IV with bad PTS DTS" in test-streams
// With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari
logger["logger"].warn("PTS < DTS detected in video samples, shifting DTS by " + toMsFromMpegTsClock(ptsDtsShift, true) + " ms to overcome this issue");
for (var _i2 = 0; _i2 < nbSamples; _i2++) {
inputSamples[_i2].dts = inputSamples[_i2].dts + ptsDtsShift;
}
}
firstDTS = inputSamples[0].dts;
lastDTS = inputSamples[nbSamples - 1].dts;
} // if fragment are contiguous, detect hole/overlapping between fragments
if (contiguous) {
// check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)
var delta = firstDTS - nextAvcDts;
var foundHole = delta > averageSampleDuration;
var foundOverlap = delta < -1;
if (foundHole || foundOverlap) {
if (foundHole) {
logger["logger"].warn("AVC: " + toMsFromMpegTsClock(delta, true) + " ms (" + delta + "dts) hole between fragments detected, filling it");
} else {
logger["logger"].warn("AVC: " + toMsFromMpegTsClock(-delta, true) + " ms (" + delta + "dts) overlapping between fragments detected");
}
firstDTS = nextAvcDts;
var firstPTS = inputSamples[0].pts - delta;
inputSamples[0].dts = firstDTS;
inputSamples[0].pts = firstPTS;
logger["logger"].log("Video: First PTS/DTS adjusted: " + toMsFromMpegTsClock(firstPTS, true) + "/" + toMsFromMpegTsClock(firstDTS, true) + ", delta: " + toMsFromMpegTsClock(delta, true) + " ms");
}
}
if (chromeVersion && chromeVersion < 75) {
firstDTS = Math.max(0, firstDTS);
}
var nbNalu = 0;
var naluLen = 0;
for (var _i3 = 0; _i3 < nbSamples; _i3++) {
// compute total/avc sample length and nb of NAL units
var _sample = inputSamples[_i3];
var units = _sample.units;
var nbUnits = units.length;
var sampleLen = 0;
for (var j = 0; j < nbUnits; j++) {
sampleLen += units[j].data.length;
}
naluLen += sampleLen;
nbNalu += nbUnits;
_sample.length = sampleLen; // normalize PTS/DTS
// ensure sample monotonic DTS
_sample.dts = Math.max(_sample.dts, firstDTS); // ensure that computed value is greater or equal than sample DTS
_sample.pts = Math.max(_sample.pts, _sample.dts, 0);
minPTS = Math.min(_sample.pts, minPTS);
maxPTS = Math.max(_sample.pts, maxPTS);
}
lastDTS = inputSamples[nbSamples - 1].dts;
/* concatenate the video data and construct the mdat in place
(need 8 more bytes to fill length and mpdat type) */
var mdatSize = naluLen + 4 * nbNalu + 8;
try {
mdat = new Uint8Array(mdatSize);
} catch (err) {
this.observer.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MUX_ERROR,
details: errors["ErrorDetails"].REMUX_ALLOC_ERROR,
fatal: false,
bytes: mdatSize,
reason: "fail allocating video mdat " + mdatSize
});
return;
}
var view = new DataView(mdat.buffer);
view.setUint32(0, mdatSize);
mdat.set(mp4_generator.types.mdat, 4);
for (var _i4 = 0; _i4 < nbSamples; _i4++) {
var avcSample = inputSamples[_i4];
var avcSampleUnits = avcSample.units;
var mp4SampleLength = 0;
var compositionTimeOffset = void 0; // convert NALU bitstream to MP4 format (prepend NALU with size field)
for (var _j = 0, _nbUnits = avcSampleUnits.length; _j < _nbUnits; _j++) {
var unit = avcSampleUnits[_j];
var unitData = unit.data;
var unitDataLen = unit.data.byteLength;
view.setUint32(offset, unitDataLen);
offset += 4;
mdat.set(unitData, offset);
offset += unitDataLen;
mp4SampleLength += 4 + unitDataLen;
} // expected sample duration is the Decoding Timestamp diff of consecutive samples
if (_i4 < nbSamples - 1) {
mp4SampleDuration = inputSamples[_i4 + 1].dts - avcSample.dts;
} else {
var config = this.config;
var lastFrameDuration = avcSample.dts - inputSamples[_i4 > 0 ? _i4 - 1 : _i4].dts;
if (config.stretchShortVideoTrack) {
// In some cases, a segment's audio track duration may exceed the video track duration.
// Since we've already remuxed audio, and we know how long the audio track is, we look to
// see if the delta to the next segment is longer than maxBufferHole.
// If so, playback would potentially get stuck, so we artificially inflate
// the duration of the last frame to minimize any potential gap between segments.
var maxBufferHole = config.maxBufferHole;
var gapTolerance = Math.floor(maxBufferHole * timeScale);
var deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
if (deltaToFrameEnd > gapTolerance) {
// We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
// frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
if (mp4SampleDuration < 0) {
mp4SampleDuration = lastFrameDuration;
}
logger["logger"].log("It is approximately " + toMsFromMpegTsClock(deltaToFrameEnd, false) + " ms to the next segment; using duration " + toMsFromMpegTsClock(mp4SampleDuration, false) + " ms for the last video frame.");
} else {
mp4SampleDuration = lastFrameDuration;
}
} else {
mp4SampleDuration = lastFrameDuration;
}
}
compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts); // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
outputSamples.push({
size: mp4SampleLength,
// constant duration
duration: mp4SampleDuration,
cts: compositionTimeOffset,
flags: {
isLeading: 0,
isDependedOn: 0,
hasRedundancy: 0,
degradPrio: 0,
dependsOn: avcSample.key ? 2 : 1,
isNonSync: avcSample.key ? 0 : 1
}
});
} // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
this.nextAvcDts = lastDTS + mp4SampleDuration;
var dropped = track.dropped;
track.nbNalu = 0;
track.dropped = 0;
if (outputSamples.length && chromeVersion && chromeVersion < 70) {
var flags = outputSamples[0].flags; // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
// https://code.google.com/p/chromium/issues/detail?id=229412
flags.dependsOn = 2;
flags.isNonSync = 0;
}
track.samples = outputSamples;
moof = mp4_generator.moof(track.sequenceNumber++, firstDTS, track);
track.samples = [];
var data = {
data1: moof,
data2: mdat,
startPTS: minPTS / timeScale,
endPTS: (maxPTS + mp4SampleDuration) / timeScale,
startDTS: firstDTS / timeScale,
endDTS: this.nextAvcDts / timeScale,
type: 'video',
hasAudio: false,
hasVideo: true,
nb: outputSamples.length,
dropped: dropped
};
this.observer.trigger(events["default"].FRAG_PARSING_DATA, data);
return data;
};
_proto.remuxAudio = function remuxAudio(track, timeOffset, contiguous, accurateTimeOffset, videoTimeOffset) {
var inputTimeScale = track.inputTimeScale;
var mp4timeScale = track.timescale;
var scaleFactor = inputTimeScale / mp4timeScale;
var mp4SampleDuration = track.isAAC ? 1024 : 1152;
var inputSampleDuration = mp4SampleDuration * scaleFactor;
var initPTS = this._initPTS;
var rawMPEG = !track.isAAC && this.typeSupported.mpeg;
var mp4Sample;
var fillFrame;
var mdat;
var moof;
var firstPTS;
var lastPTS;
var offset = rawMPEG ? 0 : 8;
var inputSamples = track.samples;
var outputSamples = [];
var nextAudioPts = this.nextAudioPts; // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
// for sake of clarity:
// consecutive fragments are frags with
// - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
// - less than 20 audio frames distance
// contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
// this helps ensuring audio continuity
// and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
contiguous |= inputSamples.length && nextAudioPts && (accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1 || Math.abs(inputSamples[0].pts - nextAudioPts - initPTS) < 20 * inputSampleDuration); // compute normalized PTS
inputSamples.forEach(function (sample) {
sample.pts = sample.dts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale);
}); // filter out sample with negative PTS that are not playable anyway
// if we don't remove these negative samples, they will shift all audio samples forward.
// leading to audio overlap between current / next fragment
inputSamples = inputSamples.filter(function (sample) {
return sample.pts >= 0;
}); // in case all samples have negative PTS, and have been filtered out, return now
if (inputSamples.length === 0) {
return;
}
if (!contiguous) {
if (videoTimeOffset === 0) {
// Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence
nextAudioPts = 0;
} else if (accurateTimeOffset) {
// When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS
nextAudioPts = Math.max(0, timeOffset * inputTimeScale);
} else {
// if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
nextAudioPts = inputSamples[0].pts;
}
} // If the audio track is missing samples, the frames seem to get "left-shifted" within the
// resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
// In an effort to prevent this from happening, we inject frames here where there are gaps.
// When possible, we inject a silent frame; when that's not possible, we duplicate the last
// frame.
if (track.isAAC) {
var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {
// First, let's see how far off this frame is from where we expect it to be
var sample = inputSamples[i];
var pts = sample.pts;
var delta = pts - nextPts; // If we're overlapping by more than a duration, drop this sample
if (delta <= -maxAudioFramesDrift * inputSampleDuration) {
if (contiguous || i > 0) {
logger["logger"].warn("Dropping 1 audio frame @ " + toMsFromMpegTsClock(nextPts, true) / 1000 + "s due to " + toMsFromMpegTsClock(delta, true) + " ms overlap.");
inputSamples.splice(i, 1); // Don't touch nextPtsNorm or i
} else {
// When changing qualities we can't trust that audio has been appended up to nextAudioPts
// Warn about the overlap but do not drop samples as that can introduce buffer gaps
logger["logger"].warn("Audio frame @ " + toMsFromMpegTsClock(pts, true) / 1000 + "s overlaps nextAudioPts by " + toMsFromMpegTsClock(delta, true) + " ms.");
nextPts = pts + inputSampleDuration;
i++;
}
} // eslint-disable-line brace-style
// Insert missing frames if:
// 1: We're more than maxAudioFramesDrift frame away
// 2: Not more than MAX_SILENT_FRAME_DURATION away
else if (delta >= maxAudioFramesDrift * inputSampleDuration && delta < MAX_SILENT_FRAME_DURATION_90KHZ) {
var missing = Math.floor(delta / inputSampleDuration); // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from
// later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.
nextPts = pts - missing * inputSampleDuration;
logger["logger"].warn("Injecting " + missing + " audio frames @ " + toMsFromMpegTsClock(nextPts, true) / 1000 + "s due to " + toMsFromMpegTsClock(delta, true) + " ms gap.");
for (var j = 0; j < missing; j++) {
var newStamp = Math.max(nextPts, 0);
fillFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
logger["logger"].log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
fillFrame = sample.unit.subarray();
}
inputSamples.splice(i, 0, {
unit: fillFrame,
pts: newStamp,
dts: newStamp
});
nextPts += inputSampleDuration;
i++;
} // Adjust sample to next expected pts
sample.pts = sample.dts = nextPts;
nextPts += inputSampleDuration;
i++;
} else {
// Otherwise, just adjust pts
if (Math.abs(delta) > 0.1 * inputSampleDuration) {// logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);
}
sample.pts = sample.dts = nextPts;
nextPts += inputSampleDuration;
i++;
}
}
} // compute mdat size, as we eventually filtered/added some samples
var nbSamples = inputSamples.length;
var mdatSize = 0;
while (nbSamples--) {
mdatSize += inputSamples[nbSamples].unit.byteLength;
}
for (var _j2 = 0, _nbSamples = inputSamples.length; _j2 < _nbSamples; _j2++) {
var audioSample = inputSamples[_j2];
var unit = audioSample.unit;
var _pts = audioSample.pts; // logger.log(`Audio/PTS:${toMsFromMpegTsClock(pts, true)}`);
// if not first sample
if (lastPTS !== undefined && mp4Sample) {
mp4Sample.duration = Math.round((_pts - lastPTS) / scaleFactor);
} else {
var _delta = _pts - nextAudioPts;
var numMissingFrames = 0; // if fragment are contiguous, detect hole/overlapping between fragments
// contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
if (contiguous && track.isAAC) {
// log delta
if (_delta) {
if (_delta > 0 && _delta < MAX_SILENT_FRAME_DURATION_90KHZ) {
// Q: why do we have to round here, shouldn't this always result in an integer if timestamps are correct,
// and if not, shouldn't we actually Math.ceil() instead?
numMissingFrames = Math.round((_pts - nextAudioPts) / inputSampleDuration);
logger["logger"].log(toMsFromMpegTsClock(_delta, true) + " ms hole between AAC samples detected,filling it");
if (numMissingFrames > 0) {
fillFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
fillFrame = unit.subarray();
}
mdatSize += numMissingFrames * fillFrame.length;
} // if we have frame overlap, overlapping for more than half a frame duraion
} else if (_delta < -12) {
// drop overlapping audio frames... browser will deal with it
logger["logger"].log("drop overlapping AAC sample, expected/parsed/delta: " + toMsFromMpegTsClock(nextAudioPts, true) + " ms / " + toMsFromMpegTsClock(_pts, true) + " ms / " + toMsFromMpegTsClock(-_delta, true) + " ms");
mdatSize -= unit.byteLength;
continue;
} // set PTS/DTS to expected PTS/DTS
_pts = nextAudioPts;
}
} // remember first PTS of our audioSamples
firstPTS = _pts;
if (mdatSize > 0) {
mdatSize += offset;
try {
mdat = new Uint8Array(mdatSize);
} catch (err) {
this.observer.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MUX_ERROR,
details: errors["ErrorDetails"].REMUX_ALLOC_ERROR,
fatal: false,
bytes: mdatSize,
reason: "fail allocating audio mdat " + mdatSize
});
return;
}
if (!rawMPEG) {
var view = new DataView(mdat.buffer);
view.setUint32(0, mdatSize);
mdat.set(mp4_generator.types.mdat, 4);
}
} else {
// no audio samples
return;
}
for (var _i5 = 0; _i5 < numMissingFrames; _i5++) {
fillFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
if (!fillFrame) {
logger["logger"].log('Unable to get silent frame for given audio codec; duplicating this frame instead.');
fillFrame = unit.subarray();
}
mdat.set(fillFrame, offset);
offset += fillFrame.byteLength;
mp4Sample = {
size: fillFrame.byteLength,
cts: 0,
duration: 1024,
flags: {
isLeading: 0,
isDependedOn: 0,
hasRedundancy: 0,
degradPrio: 0,
dependsOn: 1
}
};
outputSamples.push(mp4Sample);
}
}
mdat.set(unit, offset);
var unitLen = unit.byteLength;
offset += unitLen; // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');
mp4Sample = {
size: unitLen,
cts: 0,
duration: 0,
flags: {
isLeading: 0,
isDependedOn: 0,
hasRedundancy: 0,
degradPrio: 0,
dependsOn: 1
}
};
outputSamples.push(mp4Sample);
lastPTS = _pts;
}
var lastSampleDuration = 0;
nbSamples = outputSamples.length; // set last sample duration as being identical to previous sample
if (nbSamples >= 2) {
lastSampleDuration = outputSamples[nbSamples - 2].duration;
mp4Sample.duration = lastSampleDuration;
}
if (nbSamples) {
// next audio sample PTS should be equal to last sample PTS + duration
this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration; // logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
track.samples = outputSamples;
if (rawMPEG) {
moof = new Uint8Array();
} else {
moof = mp4_generator.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);
}
track.samples = [];
var start = firstPTS / inputTimeScale;
var end = nextAudioPts / inputTimeScale;
var audioData = {
data1: moof,
data2: mdat,
startPTS: start,
endPTS: end,
startDTS: start,
endDTS: end,
type: 'audio',
hasAudio: true,
hasVideo: false,
nb: nbSamples
};
this.observer.trigger(events["default"].FRAG_PARSING_DATA, audioData);
return audioData;
}
return null;
};
_proto.remuxEmptyAudio = function remuxEmptyAudio(track, timeOffset, contiguous, videoData) {
var inputTimeScale = track.inputTimeScale;
var mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;
var scaleFactor = inputTimeScale / mp4timeScale;
var nextAudioPts = this.nextAudioPts; // sync with video's timestamp
var startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;
var endDTS = videoData.endDTS * inputTimeScale + this._initDTS; // one sample's duration value
var sampleDuration = 1024;
var frameDuration = scaleFactor * sampleDuration; // samples count of this segment's duration
var nbSamples = Math.ceil((endDTS - startDTS) / frameDuration); // silent frame
var silentFrame = aac_helper.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
logger["logger"].warn('remux empty Audio'); // Can't remux if we can't generate a silent frame...
if (!silentFrame) {
logger["logger"].trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');
return;
}
var samples = [];
for (var i = 0; i < nbSamples; i++) {
var stamp = startDTS + i * frameDuration;
samples.push({
unit: silentFrame,
pts: stamp,
dts: stamp
});
}
track.samples = samples;
this.remuxAudio(track, timeOffset, contiguous);
};
_proto.remuxID3 = function remuxID3(track, timeOffset) {
var length = track.samples.length;
if (!length) {
return;
}
var inputTimeScale = track.inputTimeScale;
var initPTS = this._initPTS;
var initDTS = this._initDTS; // consume samples
for (var index = 0; index < length; index++) {
var sample = track.samples[index]; // setting id3 pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
sample.dts = PTSNormalize(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;
}
this.observer.trigger(events["default"].FRAG_PARSING_METADATA, {
samples: track.samples
});
track.samples = [];
};
_proto.remuxText = function remuxText(track, timeOffset) {
var length = track.samples.length;
var inputTimeScale = track.inputTimeScale;
var initPTS = this._initPTS; // consume samples
if (length) {
for (var index = 0; index < length; index++) {
var sample = track.samples[index]; // setting text pts, dts to relative time
// using this._initPTS and this._initDTS to calculate relative time
sample.pts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;
}
track.samples.sort(function (a, b) {
return a.pts - b.pts;
});
this.observer.trigger(events["default"].FRAG_PARSING_USERDATA, {
samples: track.samples
});
}
track.samples = [];
};
return MP4Remuxer;
}();
function PTSNormalize(value, reference) {
var offset;
if (reference === undefined) {
return value;
}
if (reference < value) {
// - 2^33
offset = -8589934592;
} else {
// + 2^33
offset = 8589934592;
}
/* PTS is 33bit (from 0 to 2^33 -1)
if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
PTS looping occured. fill the gap */
while (Math.abs(value - reference) > 4294967296) {
value += offset;
}
return value;
}
/* harmony default export */ var mp4_remuxer = (mp4_remuxer_MP4Remuxer);
// CONCATENATED MODULE: ./src/remux/passthrough-remuxer.js
/**
* passthrough remuxer
*/
var passthrough_remuxer_PassThroughRemuxer = /*#__PURE__*/function () {
function PassThroughRemuxer(observer) {
this.observer = observer;
}
var _proto = PassThroughRemuxer.prototype;
_proto.destroy = function destroy() {};
_proto.resetTimeStamp = function resetTimeStamp() {};
_proto.resetInitSegment = function resetInitSegment() {};
_proto.remux = function remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {
var observer = this.observer;
var streamType = '';
if (audioTrack) {
streamType += 'audio';
}
if (videoTrack) {
streamType += 'video';
}
observer.trigger(events["default"].FRAG_PARSING_DATA, {
data1: rawData,
startPTS: timeOffset,
startDTS: timeOffset,
type: streamType,
hasAudio: !!audioTrack,
hasVideo: !!videoTrack,
nb: 1,
dropped: 0
}); // notify end of parsing
observer.trigger(events["default"].FRAG_PARSED);
};
return PassThroughRemuxer;
}();
/* harmony default export */ var passthrough_remuxer = (passthrough_remuxer_PassThroughRemuxer);
// CONCATENATED MODULE: ./src/demux/demuxer-inline.js
/**
*
* inline demuxer: probe fragments and instantiate
* appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
*
*/
// see https://stackoverflow.com/a/11237259/589493
var demuxer_inline_global = Object(get_self_scope["getSelfScope"])(); // safeguard for code that might run both on worker and main thread
var now; // performance.now() not available on WebWorker, at least on Safari Desktop
try {
now = demuxer_inline_global.performance.now.bind(demuxer_inline_global.performance);
} catch (err) {
logger["logger"].debug('Unable to use Performance API on this environment');
now = demuxer_inline_global.Date.now;
}
var demuxer_inline_DemuxerInline = /*#__PURE__*/function () {
function DemuxerInline(observer, typeSupported, config, vendor) {
this.observer = observer;
this.typeSupported = typeSupported;
this.config = config;
this.vendor = vendor;
}
var _proto = DemuxerInline.prototype;
_proto.destroy = function destroy() {
var demuxer = this.demuxer;
if (demuxer) {
demuxer.destroy();
}
};
_proto.push = function push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
var _this = this;
if (data.byteLength > 0 && decryptdata != null && decryptdata.key != null && decryptdata.method === 'AES-128') {
var decrypter = this.decrypter;
if (decrypter == null) {
decrypter = this.decrypter = new crypt_decrypter(this.observer, this.config);
}
var startTime = now();
decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {
var endTime = now();
_this.observer.trigger(events["default"].FRAG_DECRYPTED, {
stats: {
tstart: startTime,
tdecrypt: endTime
}
});
_this.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
});
} else {
this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
}
};
_proto.pushDecrypted = function pushDecrypted(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
var demuxer = this.demuxer;
var remuxer = this.remuxer;
if (!demuxer || // in case of continuity change, or track switch
// we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
discontinuity || trackSwitch) {
var observer = this.observer;
var typeSupported = this.typeSupported;
var config = this.config; // probing order is TS/MP4/AAC/MP3
var muxConfig = [{
demux: tsdemuxer,
remux: mp4_remuxer
}, {
demux: mp4demuxer["default"],
remux: passthrough_remuxer
}, {
demux: aacdemuxer,
remux: mp4_remuxer
}, {
demux: mp3demuxer,
remux: mp4_remuxer
}]; // probe for content type
var mux;
for (var i = 0, len = muxConfig.length; i < len; i++) {
mux = muxConfig[i];
if (mux.demux.probe(data)) {
break;
}
}
if (!mux) {
observer.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].FRAG_PARSING_ERROR,
fatal: true,
reason: 'no demux matching with content found'
});
return;
} // so let's check that current remuxer and demuxer are still valid
if (!remuxer || !(remuxer instanceof mux.remux)) {
remuxer = new mux.remux(observer, config, typeSupported, this.vendor);
}
if (!demuxer || !(demuxer instanceof mux.demux)) {
demuxer = new mux.demux(observer, remuxer, config, typeSupported);
this.probe = mux.demux.probe;
}
this.demuxer = demuxer;
this.remuxer = remuxer;
}
if (discontinuity || trackSwitch) {
demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);
remuxer.resetInitSegment();
}
if (discontinuity) {
demuxer.resetTimeStamp(defaultInitPTS);
remuxer.resetTimeStamp(defaultInitPTS);
}
if (typeof demuxer.setDecryptData === 'function') {
demuxer.setDecryptData(decryptdata);
}
demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);
};
return DemuxerInline;
}();
/* harmony default export */ var demuxer_inline = __webpack_exports__["default"] = (demuxer_inline_DemuxerInline);
/***/ }),
/***/ "./src/demux/demuxer-worker.js":
/*!*************************************!*\
!*** ./src/demux/demuxer-worker.js ***!
\*************************************/
/*! exports provided: default */
/*! ModuleConcatenation bailout: Module is referenced from these modules with unsupported syntax: ./src/demux/demuxer.js (referenced with require.resolve) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _demux_demuxer_inline__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../demux/demuxer-inline */ "./src/demux/demuxer-inline.js");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.js");
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
/* harmony import */ var eventemitter3__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(eventemitter3__WEBPACK_IMPORTED_MODULE_3__);
/* demuxer web worker.
* - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
* - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.
*/
var DemuxerWorker = function DemuxerWorker(self) {
// observer setup
var observer = new eventemitter3__WEBPACK_IMPORTED_MODULE_3__["EventEmitter"]();
observer.trigger = function trigger(event) {
for (var _len = arguments.length, data = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
data[_key - 1] = arguments[_key];
}
observer.emit.apply(observer, [event, event].concat(data));
};
observer.off = function off(event) {
for (var _len2 = arguments.length, data = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
data[_key2 - 1] = arguments[_key2];
}
observer.removeListener.apply(observer, [event].concat(data));
};
var forwardMessage = function forwardMessage(ev, data) {
self.postMessage({
event: ev,
data: data
});
};
self.addEventListener('message', function (ev) {
var data = ev.data; // console.log('demuxer cmd:' + data.cmd);
switch (data.cmd) {
case 'init':
var config = JSON.parse(data.config);
self.demuxer = new _demux_demuxer_inline__WEBPACK_IMPORTED_MODULE_0__["default"](observer, data.typeSupported, config, data.vendor);
Object(_utils_logger__WEBPACK_IMPORTED_MODULE_2__["enableLogs"])(config.debug); // signal end of worker init
forwardMessage('init', null);
break;
case 'demux':
self.demuxer.push(data.data, data.decryptdata, data.initSegment, data.audioCodec, data.videoCodec, data.timeOffset, data.discontinuity, data.trackSwitch, data.contiguous, data.duration, data.accurateTimeOffset, data.defaultInitPTS);
break;
default:
break;
}
}); // forward events to main thread
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_DECRYPTED, forwardMessage);
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_INIT_SEGMENT, forwardMessage);
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSED, forwardMessage);
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].ERROR, forwardMessage);
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_METADATA, forwardMessage);
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_USERDATA, forwardMessage);
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].INIT_PTS_FOUND, forwardMessage); // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)
observer.on(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_DATA, function (ev, data) {
var transferable = [];
var message = {
event: ev,
data: data
};
if (data.data1) {
message.data1 = data.data1.buffer;
transferable.push(data.data1.buffer);
delete data.data1;
}
if (data.data2) {
message.data2 = data.data2.buffer;
transferable.push(data.data2.buffer);
delete data.data2;
}
self.postMessage(message, transferable);
});
};
/* harmony default export */ __webpack_exports__["default"] = (DemuxerWorker);
/***/ }),
/***/ "./src/demux/id3.js":
/*!**************************!*\
!*** ./src/demux/id3.js ***!
\**************************/
/*! exports provided: default, utf8ArrayToStr */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utf8ArrayToStr", function() { return utf8ArrayToStr; });
/* harmony import */ var _utils_get_self_scope__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/get-self-scope */ "./src/utils/get-self-scope.js");
/**
* ID3 parser
*/
var ID3 = /*#__PURE__*/function () {
function ID3() {}
/**
* Returns true if an ID3 header can be found at offset in data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {boolean} - True if an ID3 header is found
*/
ID3.isHeader = function isHeader(data, offset) {
/*
* http://id3.org/id3v2.3.0
* [0] = 'I'
* [1] = 'D'
* [2] = '3'
* [3,4] = {Version}
* [5] = {Flags}
* [6-9] = {ID3 Size}
*
* An ID3v2 tag can be detected with the following pattern:
* $49 44 33 yy yy xx zz zz zz zz
* Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
*/
if (offset + 10 <= data.length) {
// look for 'ID3' identifier
if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
// check version is within range
if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
// check size is within range
if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
return true;
}
}
}
}
return false;
}
/**
* Returns true if an ID3 footer can be found at offset in data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {boolean} - True if an ID3 footer is found
*/
;
ID3.isFooter = function isFooter(data, offset) {
/*
* The footer is a copy of the header, but with a different identifier
*/
if (offset + 10 <= data.length) {
// look for '3DI' identifier
if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
// check version is within range
if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
// check size is within range
if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
return true;
}
}
}
}
return false;
}
/**
* Returns any adjacent ID3 tags found in data starting at offset, as one block of data
* @param {Uint8Array} data - The data to search in
* @param {number} offset - The offset at which to start searching
* @return {Uint8Array} - The block of data containing any ID3 tags found
*/
;
ID3.getID3Data = function getID3Data(data, offset) {
var front = offset;
var length = 0;
while (ID3.isHeader(data, offset)) {
// ID3 header is 10 bytes
length += 10;
var size = ID3._readSize(data, offset + 6);
length += size;
if (ID3.isFooter(data, offset + 10)) {
// ID3 footer is 10 bytes
length += 10;
}
offset += length;
}
if (length > 0) {
return data.subarray(front, front + length);
}
return undefined;
};
ID3._readSize = function _readSize(data, offset) {
var size = 0;
size = (data[offset] & 0x7f) << 21;
size |= (data[offset + 1] & 0x7f) << 14;
size |= (data[offset + 2] & 0x7f) << 7;
size |= data[offset + 3] & 0x7f;
return size;
}
/**
* Searches for the Elementary Stream timestamp found in the ID3 data chunk
* @param {Uint8Array} data - Block of data containing one or more ID3 tags
* @return {number} - The timestamp
*/
;
ID3.getTimeStamp = function getTimeStamp(data) {
var frames = ID3.getID3Frames(data);
for (var i = 0; i < frames.length; i++) {
var frame = frames[i];
if (ID3.isTimeStampFrame(frame)) {
return ID3._readTimeStamp(frame);
}
}
return undefined;
}
/**
* Returns true if the ID3 frame is an Elementary Stream timestamp frame
* @param {ID3 frame} frame
*/
;
ID3.isTimeStampFrame = function isTimeStampFrame(frame) {
return frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp';
};
ID3._getFrameData = function _getFrameData(data) {
/*
Frame ID $xx xx xx xx (four characters)
Size $xx xx xx xx
Flags $xx xx
*/
var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
var size = ID3._readSize(data, 4); // skip frame id, size, and flags
var offset = 10;
return {
type: type,
size: size,
data: data.subarray(offset, offset + size)
};
}
/**
* Returns an array of ID3 frames found in all the ID3 tags in the id3Data
* @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
* @return {ID3 frame[]} - Array of ID3 frame objects
*/
;
ID3.getID3Frames = function getID3Frames(id3Data) {
var offset = 0;
var frames = [];
while (ID3.isHeader(id3Data, offset)) {
var size = ID3._readSize(id3Data, offset + 6); // skip past ID3 header
offset += 10;
var end = offset + size; // loop through frames in the ID3 tag
while (offset + 8 < end) {
var frameData = ID3._getFrameData(id3Data.subarray(offset));
var frame = ID3._decodeFrame(frameData);
if (frame) {
frames.push(frame);
} // skip frame header and frame data
offset += frameData.size + 10;
}
if (ID3.isFooter(id3Data, offset)) {
offset += 10;
}
}
return frames;
};
ID3._decodeFrame = function _decodeFrame(frame) {
if (frame.type === 'PRIV') {
return ID3._decodePrivFrame(frame);
} else if (frame.type[0] === 'T') {
return ID3._decodeTextFrame(frame);
} else if (frame.type[0] === 'W') {
return ID3._decodeURLFrame(frame);
}
return undefined;
};
ID3._readTimeStamp = function _readTimeStamp(timeStampFrame) {
if (timeStampFrame.data.byteLength === 8) {
var data = new Uint8Array(timeStampFrame.data); // timestamp is 33 bit expressed as a big-endian eight-octet number,
// with the upper 31 bits set to zero.
var pts33Bit = data[3] & 0x1;
var timestamp = (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];
timestamp /= 45;
if (pts33Bit) {
timestamp += 47721858.84;
} // 2^32 / 90
return Math.round(timestamp);
}
return undefined;
};
ID3._decodePrivFrame = function _decodePrivFrame(frame) {
/*
Format: <text string>\0<binary data>
*/
if (frame.size < 2) {
return undefined;
}
var owner = ID3._utf8ArrayToStr(frame.data, true);
var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
return {
key: frame.type,
info: owner,
data: privateData.buffer
};
};
ID3._decodeTextFrame = function _decodeTextFrame(frame) {
if (frame.size < 2) {
return undefined;
}
if (frame.type === 'TXXX') {
/*
Format:
[0] = {Text Encoding}
[1-?] = {Description}\0{Value}
*/
var index = 1;
var description = ID3._utf8ArrayToStr(frame.data.subarray(index), true);
index += description.length + 1;
var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
return {
key: frame.type,
info: description,
data: value
};
} else {
/*
Format:
[0] = {Text Encoding}
[1-?] = {Value}
*/
var text = ID3._utf8ArrayToStr(frame.data.subarray(1));
return {
key: frame.type,
data: text
};
}
};
ID3._decodeURLFrame = function _decodeURLFrame(frame) {
if (frame.type === 'WXXX') {
/*
Format:
[0] = {Text Encoding}
[1-?] = {Description}\0{URL}
*/
if (frame.size < 2) {
return undefined;
}
var index = 1;
var description = ID3._utf8ArrayToStr(frame.data.subarray(index), true);
index += description.length + 1;
var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
return {
key: frame.type,
info: description,
data: value
};
} else {
/*
Format:
[0-?] = {URL}
*/
var url = ID3._utf8ArrayToStr(frame.data);
return {
key: frame.type,
data: url
};
}
} // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
/* utf.js - UTF-8 <=> UTF-16 convertion
*
* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
* Version: 1.0
* LastModified: Dec 25 1999
* This library is free. You can redistribute it and/or modify it.
*/
;
ID3._utf8ArrayToStr = function _utf8ArrayToStr(array, exitOnNull) {
if (exitOnNull === void 0) {
exitOnNull = false;
}
var decoder = getTextDecoder();
if (decoder) {
var decoded = decoder.decode(array);
if (exitOnNull) {
// grab up to the first null
var idx = decoded.indexOf('\0');
return idx !== -1 ? decoded.substring(0, idx) : decoded;
} // remove any null characters
return decoded.replace(/\0/g, '');
}
var len = array.length;
var c;
var char2;
var char3;
var out = '';
var i = 0;
while (i < len) {
c = array[i++];
if (c === 0x00 && exitOnNull) {
return out;
} else if (c === 0x00 || c === 0x03) {
// If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
continue;
}
switch (c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
out += String.fromCharCode(c);
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
char2 = array[i++];
out += String.fromCharCode((c & 0x1F) << 6 | char2 & 0x3F);
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
char2 = array[i++];
char3 = array[i++];
out += String.fromCharCode((c & 0x0F) << 12 | (char2 & 0x3F) << 6 | (char3 & 0x3F) << 0);
break;
default:
}
}
return out;
};
return ID3;
}();
var decoder;
function getTextDecoder() {
var global = Object(_utils_get_self_scope__WEBPACK_IMPORTED_MODULE_0__["getSelfScope"])(); // safeguard for code that might run both on worker and main thread
if (!decoder && typeof global.TextDecoder !== 'undefined') {
decoder = new global.TextDecoder('utf-8');
}
return decoder;
}
var utf8ArrayToStr = ID3._utf8ArrayToStr;
/* harmony default export */ __webpack_exports__["default"] = (ID3);
/***/ }),
/***/ "./src/demux/mp4demuxer.js":
/*!*********************************!*\
!*** ./src/demux/mp4demuxer.js ***!
\*********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _utils_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../events */ "./src/events.js");
/**
* MP4 demuxer
*/
var UINT32_MAX = Math.pow(2, 32) - 1;
var MP4Demuxer = /*#__PURE__*/function () {
function MP4Demuxer(observer, remuxer) {
this.observer = observer;
this.remuxer = remuxer;
}
var _proto = MP4Demuxer.prototype;
_proto.resetTimeStamp = function resetTimeStamp(initPTS) {
this.initPTS = initPTS;
};
_proto.resetInitSegment = function resetInitSegment(initSegment, audioCodec, videoCodec, duration) {
// jshint unused:false
if (initSegment && initSegment.byteLength) {
var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment); // default audio codec if nothing specified
// TODO : extract that from initsegment
if (audioCodec == null) {
audioCodec = 'mp4a.40.5';
}
if (videoCodec == null) {
videoCodec = 'avc1.42e01e';
}
var tracks = {};
if (initData.audio && initData.video) {
tracks.audiovideo = {
container: 'video/mp4',
codec: audioCodec + ',' + videoCodec,
initSegment: duration ? initSegment : null
};
} else {
if (initData.audio) {
tracks.audio = {
container: 'audio/mp4',
codec: audioCodec,
initSegment: duration ? initSegment : null
};
}
if (initData.video) {
tracks.video = {
container: 'video/mp4',
codec: videoCodec,
initSegment: duration ? initSegment : null
};
}
}
this.observer.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["default"].FRAG_PARSING_INIT_SEGMENT, {
tracks: tracks
});
} else {
if (audioCodec) {
this.audioCodec = audioCodec;
}
if (videoCodec) {
this.videoCodec = videoCodec;
}
}
};
MP4Demuxer.probe = function probe(data) {
// ensure we find a moof box in the first 16 kB
return MP4Demuxer.findBox({
data: data,
start: 0,
end: Math.min(data.length, 16384)
}, ['moof']).length > 0;
};
MP4Demuxer.bin2str = function bin2str(buffer) {
return String.fromCharCode.apply(null, buffer);
};
MP4Demuxer.readUint16 = function readUint16(buffer, offset) {
if (buffer.data) {
offset += buffer.start;
buffer = buffer.data;
}
var val = buffer[offset] << 8 | buffer[offset + 1];
return val < 0 ? 65536 + val : val;
};
MP4Demuxer.readUint32 = function readUint32(buffer, offset) {
if (buffer.data) {
offset += buffer.start;
buffer = buffer.data;
}
var val = buffer[offset] << 24 | buffer[offset + 1] << 16 | buffer[offset + 2] << 8 | buffer[offset + 3];
return val < 0 ? 4294967296 + val : val;
};
MP4Demuxer.writeUint32 = function writeUint32(buffer, offset, value) {
if (buffer.data) {
offset += buffer.start;
buffer = buffer.data;
}
buffer[offset] = value >> 24;
buffer[offset + 1] = value >> 16 & 0xff;
buffer[offset + 2] = value >> 8 & 0xff;
buffer[offset + 3] = value & 0xff;
} // Find the data for a box specified by its path
;
MP4Demuxer.findBox = function findBox(data, path) {
var results = [],
i,
size,
type,
end,
subresults,
start,
endbox;
if (data.data) {
start = data.start;
end = data.end;
data = data.data;
} else {
start = 0;
end = data.byteLength;
}
if (!path.length) {
// short-circuit the search for empty paths
return null;
}
for (i = start; i < end;) {
size = MP4Demuxer.readUint32(data, i);
type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));
endbox = size > 1 ? i + size : end;
if (type === path[0]) {
if (path.length === 1) {
// this is the end of the path and we've found the box we were
// looking for
results.push({
data: data,
start: i + 8,
end: endbox
});
} else {
// recursively search for the next box along the path
subresults = MP4Demuxer.findBox({
data: data,
start: i + 8,
end: endbox
}, path.slice(1));
if (subresults.length) {
results = results.concat(subresults);
}
}
}
i = endbox;
} // we've finished searching all of data
return results;
};
MP4Demuxer.parseSegmentIndex = function parseSegmentIndex(initSegment) {
var moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];
var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
var index = 0;
var sidx = MP4Demuxer.findBox(initSegment, ['sidx']);
var references;
if (!sidx || !sidx[0]) {
return null;
}
references = [];
sidx = sidx[0];
var version = sidx.data[0]; // set initial offset, we skip the reference ID (not needed)
index = version === 0 ? 8 : 16;
var timescale = MP4Demuxer.readUint32(sidx, index);
index += 4; // TODO: parse earliestPresentationTime and firstOffset
// usually zero in our case
var earliestPresentationTime = 0;
var firstOffset = 0;
if (version === 0) {
index += 8;
} else {
index += 16;
} // skip reserved
index += 2;
var startByte = sidx.end + firstOffset;
var referencesCount = MP4Demuxer.readUint16(sidx, index);
index += 2;
for (var i = 0; i < referencesCount; i++) {
var referenceIndex = index;
var referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);
referenceIndex += 4;
var referenceSize = referenceInfo & 0x7FFFFFFF;
var referenceType = (referenceInfo & 0x80000000) >>> 31;
if (referenceType === 1) {
console.warn('SIDX has hierarchical references (not supported)');
return;
}
var subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);
referenceIndex += 4;
references.push({
referenceSize: referenceSize,
subsegmentDuration: subsegmentDuration,
// unscaled
info: {
duration: subsegmentDuration / timescale,
start: startByte,
end: startByte + referenceSize - 1
}
});
startByte += referenceSize; // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
// for |sapDelta|.
referenceIndex += 4; // skip to next ref
index = referenceIndex;
}
return {
earliestPresentationTime: earliestPresentationTime,
timescale: timescale,
version: version,
referencesCount: referencesCount,
references: references,
moovEndOffset: moovEndOffset
};
}
/**
* Parses an MP4 initialization segment and extracts stream type and
* timescale values for any declared tracks. Timescale values indicate the
* number of clock ticks per second to assume for time-based values
* elsewhere in the MP4.
*
* To determine the start time of an MP4, you need two pieces of
* information: the timescale unit and the earliest base media decode
* time. Multiple timescales can be specified within an MP4 but the
* base media decode time is always expressed in the timescale from
* the media header box for the track:
* ```
* moov > trak > mdia > mdhd.timescale
* moov > trak > mdia > hdlr
* ```
* @param init {Uint8Array} the bytes of the init segment
* @return {object} a hash of track type to timescale values or null if
* the init segment is malformed.
*/
;
MP4Demuxer.parseInitSegment = function parseInitSegment(initSegment) {
var result = [];
var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);
traks.forEach(function (trak) {
var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];
if (tkhd) {
var version = tkhd.data[tkhd.start];
var index = version === 0 ? 12 : 20;
var trackId = MP4Demuxer.readUint32(tkhd, index);
var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];
if (mdhd) {
version = mdhd.data[mdhd.start];
index = version === 0 ? 12 : 20;
var timescale = MP4Demuxer.readUint32(mdhd, index);
var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];
if (hdlr) {
var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
var type = {
'soun': 'audio',
'vide': 'video'
}[hdlrType];
if (type) {
// extract codec info. TODO : parse codec details to be able to build MIME type
var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);
if (codecBox.length) {
codecBox = codecBox[0];
var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));
_utils_logger__WEBPACK_IMPORTED_MODULE_0__["logger"].log("MP4Demuxer:" + type + ":" + codecType + " found");
}
result[trackId] = {
timescale: timescale,
type: type
};
result[type] = {
timescale: timescale,
id: trackId
};
}
}
}
}
});
return result;
}
/**
* Determine the base media decode start time, in seconds, for an MP4
* fragment. If multiple fragments are specified, the earliest time is
* returned.
*
* The base media decode time can be parsed from track fragment
* metadata:
* ```
* moof > traf > tfdt.baseMediaDecodeTime
* ```
* It requires the timescale value from the mdhd to interpret.
*
* @param timescale {object} a hash of track ids to timescale values.
* @return {number} the earliest base media decode start time for the
* fragment, in seconds
*/
;
MP4Demuxer.getStartDTS = function getStartDTS(initData, fragment) {
var trafs, baseTimes, result; // we need info from two childrend of each track fragment box
trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']); // determine the start times for each track
baseTimes = [].concat.apply([], trafs.map(function (traf) {
return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
var id, scale, baseTime; // get the track id from the tfhd
id = MP4Demuxer.readUint32(tfhd, 4); // assume a 90kHz clock if no timescale was specified
scale = initData[id].timescale || 90e3; // get the base media decode time from the tfdt
baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
var version, result;
version = tfdt.data[tfdt.start];
result = MP4Demuxer.readUint32(tfdt, 4);
if (version === 1) {
result *= Math.pow(2, 32);
result += MP4Demuxer.readUint32(tfdt, 8);
}
return result;
})[0]; // convert base time to seconds
return baseTime / scale;
});
})); // return the minimum
result = Math.min.apply(null, baseTimes);
return isFinite(result) ? result : 0;
};
MP4Demuxer.offsetStartDTS = function offsetStartDTS(initData, fragment, timeOffset) {
MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {
return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
// get the track id from the tfhd
var id = MP4Demuxer.readUint32(tfhd, 4); // assume a 90kHz clock if no timescale was specified
var timescale = initData[id].timescale || 90e3; // get the base media decode time from the tfdt
MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
var version = tfdt.data[tfdt.start];
var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);
if (version === 0) {
MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
} else {
baseMediaDecodeTime *= Math.pow(2, 32);
baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);
baseMediaDecodeTime -= timeOffset * timescale;
baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
MP4Demuxer.writeUint32(tfdt, 4, upper);
MP4Demuxer.writeUint32(tfdt, 8, lower);
}
});
});
});
} // feed incoming data to the front of the parsing pipeline
;
_proto.append = function append(data, timeOffset, contiguous, accurateTimeOffset) {
var initData = this.initData;
if (!initData) {
this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);
initData = this.initData;
}
var startDTS,
initPTS = this.initPTS;
if (initPTS === undefined) {
var _startDTS = MP4Demuxer.getStartDTS(initData, data);
this.initPTS = initPTS = _startDTS - timeOffset;
this.observer.trigger(_events__WEBPACK_IMPORTED_MODULE_1__["default"].INIT_PTS_FOUND, {
initPTS: initPTS
});
}
MP4Demuxer.offsetStartDTS(initData, data, initPTS);
startDTS = MP4Demuxer.getStartDTS(initData, data);
this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);
};
_proto.destroy = function destroy() {};
return MP4Demuxer;
}();
/* harmony default export */ __webpack_exports__["default"] = (MP4Demuxer);
/***/ }),
/***/ "./src/empty.js":
/*!**********************!*\
!*** ./src/empty.js ***!
\**********************/
/*! no static exports found */
/*! ModuleConcatenation bailout: Module is not an ECMAScript module */
/***/ (function(module, exports) {
// This file is inserted as a shim for modules which we do not want to include into the distro.
// This replacement is done in the "resolve" section of the webpack config.
module.exports = void 0;
/***/ }),
/***/ "./src/errors.ts":
/*!***********************!*\
!*** ./src/errors.ts ***!
\***********************/
/*! exports provided: ErrorTypes, ErrorDetails */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorTypes", function() { return ErrorTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorDetails", function() { return ErrorDetails; });
var ErrorTypes;
/**
* @enum {ErrorDetails}
* @typedef {string} ErrorDetail
*/
(function (ErrorTypes) {
ErrorTypes["NETWORK_ERROR"] = "networkError";
ErrorTypes["MEDIA_ERROR"] = "mediaError";
ErrorTypes["KEY_SYSTEM_ERROR"] = "keySystemError";
ErrorTypes["MUX_ERROR"] = "muxError";
ErrorTypes["OTHER_ERROR"] = "otherError";
})(ErrorTypes || (ErrorTypes = {}));
var ErrorDetails;
(function (ErrorDetails) {
ErrorDetails["KEY_SYSTEM_NO_KEYS"] = "keySystemNoKeys";
ErrorDetails["KEY_SYSTEM_NO_ACCESS"] = "keySystemNoAccess";
ErrorDetails["KEY_SYSTEM_NO_SESSION"] = "keySystemNoSession";
ErrorDetails["KEY_SYSTEM_LICENSE_REQUEST_FAILED"] = "keySystemLicenseRequestFailed";
ErrorDetails["KEY_SYSTEM_NO_INIT_DATA"] = "keySystemNoInitData";
ErrorDetails["MANIFEST_LOAD_ERROR"] = "manifestLoadError";
ErrorDetails["MANIFEST_LOAD_TIMEOUT"] = "manifestLoadTimeOut";
ErrorDetails["MANIFEST_PARSING_ERROR"] = "manifestParsingError";
ErrorDetails["MANIFEST_INCOMPATIBLE_CODECS_ERROR"] = "manifestIncompatibleCodecsError";
ErrorDetails["LEVEL_EMPTY_ERROR"] = "levelEmptyError";
ErrorDetails["LEVEL_LOAD_ERROR"] = "levelLoadError";
ErrorDetails["LEVEL_LOAD_TIMEOUT"] = "levelLoadTimeOut";
ErrorDetails["LEVEL_SWITCH_ERROR"] = "levelSwitchError";
ErrorDetails["AUDIO_TRACK_LOAD_ERROR"] = "audioTrackLoadError";
ErrorDetails["AUDIO_TRACK_LOAD_TIMEOUT"] = "audioTrackLoadTimeOut";
ErrorDetails["FRAG_LOAD_ERROR"] = "fragLoadError";
ErrorDetails["FRAG_LOAD_TIMEOUT"] = "fragLoadTimeOut";
ErrorDetails["FRAG_DECRYPT_ERROR"] = "fragDecryptError";
ErrorDetails["FRAG_PARSING_ERROR"] = "fragParsingError";
ErrorDetails["REMUX_ALLOC_ERROR"] = "remuxAllocError";
ErrorDetails["KEY_LOAD_ERROR"] = "keyLoadError";
ErrorDetails["KEY_LOAD_TIMEOUT"] = "keyLoadTimeOut";
ErrorDetails["BUFFER_ADD_CODEC_ERROR"] = "bufferAddCodecError";
ErrorDetails["BUFFER_APPEND_ERROR"] = "bufferAppendError";
ErrorDetails["BUFFER_APPENDING_ERROR"] = "bufferAppendingError";
ErrorDetails["BUFFER_STALLED_ERROR"] = "bufferStalledError";
ErrorDetails["BUFFER_FULL_ERROR"] = "bufferFullError";
ErrorDetails["BUFFER_SEEK_OVER_HOLE"] = "bufferSeekOverHole";
ErrorDetails["BUFFER_NUDGE_ON_STALL"] = "bufferNudgeOnStall";
ErrorDetails["INTERNAL_EXCEPTION"] = "internalException";
})(ErrorDetails || (ErrorDetails = {}));
/***/ }),
/***/ "./src/events.js":
/*!***********************!*\
!*** ./src/events.js ***!
\***********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/**
* @readonly
* @enum {string}
*/
var HlsEvents = {
// fired before MediaSource is attaching to media element - data: { media }
MEDIA_ATTACHING: 'hlsMediaAttaching',
// fired when MediaSource has been succesfully attached to media element - data: { }
MEDIA_ATTACHED: 'hlsMediaAttached',
// fired before detaching MediaSource from media element - data: { }
MEDIA_DETACHING: 'hlsMediaDetaching',
// fired when MediaSource has been detached from media element - data: { }
MEDIA_DETACHED: 'hlsMediaDetached',
// fired when we buffer is going to be reset - data: { }
BUFFER_RESET: 'hlsBufferReset',
// fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
BUFFER_CODECS: 'hlsBufferCodecs',
// fired when sourcebuffers have been created - data: { tracks : tracks }
BUFFER_CREATED: 'hlsBufferCreated',
// fired when we append a segment to the buffer - data: { segment: segment object }
BUFFER_APPENDING: 'hlsBufferAppending',
// fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}
BUFFER_APPENDED: 'hlsBufferAppended',
// fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
BUFFER_EOS: 'hlsBufferEos',
// fired when the media buffer should be flushed - data { startOffset, endOffset }
BUFFER_FLUSHING: 'hlsBufferFlushing',
// fired when the media buffer has been flushed - data: { }
BUFFER_FLUSHED: 'hlsBufferFlushed',
// fired to signal that a manifest loading starts - data: { url : manifestURL}
MANIFEST_LOADING: 'hlsManifestLoading',
// fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
MANIFEST_LOADED: 'hlsManifestLoaded',
// fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
MANIFEST_PARSED: 'hlsManifestParsed',
// fired when a level switch is requested - data: { level : id of new level }
LEVEL_SWITCHING: 'hlsLevelSwitching',
// fired when a level switch is effective - data: { level : id of new level }
LEVEL_SWITCHED: 'hlsLevelSwitched',
// fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
LEVEL_LOADING: 'hlsLevelLoading',
// fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
LEVEL_LOADED: 'hlsLevelLoaded',
// fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }
LEVEL_UPDATED: 'hlsLevelUpdated',
// fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }
LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
// fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }
LEVELS_UPDATED: 'hlsLevelsUpdated',
// fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',
// fired when an audio track switching is requested - data: { id : audio track id }
AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',
// fired when an audio track switch actually occurs - data: { id : audio track id }
AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',
// fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',
// fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }
AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',
// fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',
// fired when an subtitle track switch occurs - data: { id : subtitle track id }
SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',
// fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',
// fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }
SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',
// fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',
// fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }
CUES_PARSED: 'hlsCuesParsed',
// fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }
NON_NATIVE_TEXT_TRACKS_FOUND: 'hlsNonNativeTextTracksFound',
// fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }
INIT_PTS_FOUND: 'hlsInitPtsFound',
// fired when a fragment loading starts - data: { frag : fragment object }
FRAG_LOADING: 'hlsFragLoading',
// fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
// Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
// fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }
FRAG_LOADED: 'hlsFragLoaded',
// fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
FRAG_DECRYPTED: 'hlsFragDecrypted',
// fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }
FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
// fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
// fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
// fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
FRAG_PARSING_DATA: 'hlsFragParsingData',
// fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
FRAG_PARSED: 'hlsFragParsed',
// fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } }
FRAG_BUFFERED: 'hlsFragBuffered',
// fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
FRAG_CHANGED: 'hlsFragChanged',
// Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }
FPS_DROP: 'hlsFpsDrop',
// triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }
FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
// Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }
ERROR: 'hlsError',
// fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }
DESTROYING: 'hlsDestroying',
// fired when a decrypt key loading starts - data: { frag : fragment object }
KEY_LOADING: 'hlsKeyLoading',
// fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }
KEY_LOADED: 'hlsKeyLoaded',
// fired upon stream controller state transitions - data: { previousState, nextState }
STREAM_STATE_TRANSITION: 'hlsStreamStateTransition',
// fired when the live back buffer is reached defined by the liveBackBufferLength config option - data : { bufferEnd: number }
LIVE_BACK_BUFFER_REACHED: 'hlsLiveBackBufferReached'
};
/* harmony default export */ __webpack_exports__["default"] = (HlsEvents);
/***/ }),
/***/ "./src/hls.ts":
/*!*********************************!*\
!*** ./src/hls.ts + 38 modules ***!
\*********************************/
/*! exports provided: default */
/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/demuxer-inline.js because of ./src/demux/demuxer-worker.js */
/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/id3.js because of ./src/demux/demuxer-worker.js */
/*! ModuleConcatenation bailout: Cannot concat with ./src/demux/mp4demuxer.js because of ./src/demux/demuxer-worker.js */
/*! ModuleConcatenation bailout: Cannot concat with ./src/errors.ts because of ./src/demux/demuxer-worker.js */
/*! ModuleConcatenation bailout: Cannot concat with ./src/events.js because of ./src/demux/demuxer-worker.js */
/*! ModuleConcatenation bailout: Cannot concat with ./src/polyfills/number.js because of ./src/demux/demuxer-worker.js */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/get-self-scope.js because of ./src/demux/demuxer-worker.js */
/*! ModuleConcatenation bailout: Cannot concat with ./src/utils/logger.js because of ./src/demux/demuxer-worker.js */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/eventemitter3/index.js (<- Module is not an ECMAScript module) */
/*! ModuleConcatenation bailout: Cannot concat with ./node_modules/url-toolkit/src/url-toolkit.js (<- Module is not an ECMAScript module) */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "default", function() { return /* binding */ hls_Hls; });
// EXTERNAL MODULE: ./node_modules/url-toolkit/src/url-toolkit.js
var url_toolkit = __webpack_require__("./node_modules/url-toolkit/src/url-toolkit.js");
// EXTERNAL MODULE: ./src/errors.ts
var errors = __webpack_require__("./src/errors.ts");
// EXTERNAL MODULE: ./src/polyfills/number.js
var number = __webpack_require__("./src/polyfills/number.js");
// EXTERNAL MODULE: ./src/events.js
var events = __webpack_require__("./src/events.js");
// EXTERNAL MODULE: ./src/utils/logger.js
var logger = __webpack_require__("./src/utils/logger.js");
// CONCATENATED MODULE: ./src/event-handler.ts
/*
*
* All objects in the event handling chain should inherit from this class
*
*/
var FORBIDDEN_EVENT_NAMES = {
'hlsEventGeneric': true,
'hlsHandlerDestroying': true,
'hlsHandlerDestroyed': true
};
var event_handler_EventHandler = /*#__PURE__*/function () {
function EventHandler(hls) {
this.hls = void 0;
this.handledEvents = void 0;
this.useGenericHandler = void 0;
this.hls = hls;
this.onEvent = this.onEvent.bind(this);
for (var _len = arguments.length, events = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
events[_key - 1] = arguments[_key];
}
this.handledEvents = events;
this.useGenericHandler = true;
this.registerListeners();
}
var _proto = EventHandler.prototype;
_proto.destroy = function destroy() {
this.onHandlerDestroying();
this.unregisterListeners();
this.onHandlerDestroyed();
};
_proto.onHandlerDestroying = function onHandlerDestroying() {};
_proto.onHandlerDestroyed = function onHandlerDestroyed() {};
_proto.isEventHandler = function isEventHandler() {
return typeof this.handledEvents === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
};
_proto.registerListeners = function registerListeners() {
if (this.isEventHandler()) {
this.handledEvents.forEach(function (event) {
if (FORBIDDEN_EVENT_NAMES[event]) {
throw new Error('Forbidden event-name: ' + event);
}
this.hls.on(event, this.onEvent);
}, this);
}
};
_proto.unregisterListeners = function unregisterListeners() {
if (this.isEventHandler()) {
this.handledEvents.forEach(function (event) {
this.hls.off(event, this.onEvent);
}, this);
}
}
/**
* arguments: event (string), data (any)
*/
;
_proto.onEvent = function onEvent(event, data) {
this.onEventGeneric(event, data);
};
_proto.onEventGeneric = function onEventGeneric(event, data) {
var eventToFunction = function eventToFunction(event, data) {
var funcName = 'on' + event.replace('hls', '');
if (typeof this[funcName] !== 'function') {
throw new Error("Event " + event + " has no generic handler in this " + this.constructor.name + " class (tried " + funcName + ")");
}
return this[funcName].bind(this, data);
};
try {
eventToFunction.call(this, event, data).call();
} catch (err) {
logger["logger"].error("An internal error happened while handling event " + event + ". Error message: \"" + err.message + "\". Here is a stacktrace:", err);
this.hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].OTHER_ERROR,
details: errors["ErrorDetails"].INTERNAL_EXCEPTION,
fatal: false,
event: event,
err: err
});
}
};
return EventHandler;
}();
/* harmony default export */ var event_handler = (event_handler_EventHandler);
// CONCATENATED MODULE: ./src/types/loader.ts
/**
* `type` property values for this loaders' context object
* @enum
*
*/
var PlaylistContextType;
/**
* @enum {string}
*/
(function (PlaylistContextType) {
PlaylistContextType["MANIFEST"] = "manifest";
PlaylistContextType["LEVEL"] = "level";
PlaylistContextType["AUDIO_TRACK"] = "audioTrack";
PlaylistContextType["SUBTITLE_TRACK"] = "subtitleTrack";
})(PlaylistContextType || (PlaylistContextType = {}));
var PlaylistLevelType;
(function (PlaylistLevelType) {
PlaylistLevelType["MAIN"] = "main";
PlaylistLevelType["AUDIO"] = "audio";
PlaylistLevelType["SUBTITLE"] = "subtitle";
})(PlaylistLevelType || (PlaylistLevelType = {}));
// EXTERNAL MODULE: ./src/demux/mp4demuxer.js
var mp4demuxer = __webpack_require__("./src/demux/mp4demuxer.js");
// CONCATENATED MODULE: ./src/loader/level-key.ts
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var level_key_LevelKey = /*#__PURE__*/function () {
function LevelKey(baseURI, relativeURI) {
this._uri = null;
this.baseuri = void 0;
this.reluri = void 0;
this.method = null;
this.key = null;
this.iv = null;
this.baseuri = baseURI;
this.reluri = relativeURI;
}
_createClass(LevelKey, [{
key: "uri",
get: function get() {
if (!this._uri && this.reluri) {
this._uri = Object(url_toolkit["buildAbsoluteURL"])(this.baseuri, this.reluri, {
alwaysNormalize: true
});
}
return this._uri;
}
}]);
return LevelKey;
}();
// CONCATENATED MODULE: ./src/loader/fragment.ts
function fragment_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function fragment_createClass(Constructor, protoProps, staticProps) { if (protoProps) fragment_defineProperties(Constructor.prototype, protoProps); if (staticProps) fragment_defineProperties(Constructor, staticProps); return Constructor; }
var ElementaryStreamTypes;
(function (ElementaryStreamTypes) {
ElementaryStreamTypes["AUDIO"] = "audio";
ElementaryStreamTypes["VIDEO"] = "video";
})(ElementaryStreamTypes || (ElementaryStreamTypes = {}));
var fragment_Fragment = /*#__PURE__*/function () {
function Fragment() {
var _this$_elementaryStre;
this._url = null;
this._byteRange = null;
this._decryptdata = null;
this._elementaryStreams = (_this$_elementaryStre = {}, _this$_elementaryStre[ElementaryStreamTypes.AUDIO] = false, _this$_elementaryStre[ElementaryStreamTypes.VIDEO] = false, _this$_elementaryStre);
this.deltaPTS = 0;
this.rawProgramDateTime = null;
this.programDateTime = null;
this.title = null;
this.tagList = [];
this.cc = void 0;
this.type = void 0;
this.relurl = void 0;
this.baseurl = void 0;
this.duration = void 0;
this.start = void 0;
this.sn = 0;
this.urlId = 0;
this.level = 0;
this.levelkey = void 0;
this.loader = void 0;
}
var _proto = Fragment.prototype;
// setByteRange converts a EXT-X-BYTERANGE attribute into a two element array
_proto.setByteRange = function setByteRange(value, previousFrag) {
var params = value.split('@', 2);
var byteRange = [];
if (params.length === 1) {
byteRange[0] = previousFrag ? previousFrag.byteRangeEndOffset : 0;
} else {
byteRange[0] = parseInt(params[1]);
}
byteRange[1] = parseInt(params[0]) + byteRange[0];
this._byteRange = byteRange;
};
/**
* @param {ElementaryStreamTypes} type
*/
_proto.addElementaryStream = function addElementaryStream(type) {
this._elementaryStreams[type] = true;
}
/**
* @param {ElementaryStreamTypes} type
*/
;
_proto.hasElementaryStream = function hasElementaryStream(type) {
return this._elementaryStreams[type] === true;
}
/**
* Utility method for parseLevelPlaylist to create an initialization vector for a given segment
* @param {number} segmentNumber - segment number to generate IV with
* @returns {Uint8Array}
*/
;
_proto.createInitializationVector = function createInitializationVector(segmentNumber) {
var uint8View = new Uint8Array(16);
for (var i = 12; i < 16; i++) {
uint8View[i] = segmentNumber >> 8 * (15 - i) & 0xff;
}
return uint8View;
}
/**
* Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
* @param levelkey - a playlist's encryption info
* @param segmentNumber - the fragment's segment number
* @returns {LevelKey} - an object to be applied as a fragment's decryptdata
*/
;
_proto.setDecryptDataFromLevelKey = function setDecryptDataFromLevelKey(levelkey, segmentNumber) {
var decryptdata = levelkey;
if ((levelkey === null || levelkey === void 0 ? void 0 : levelkey.method) && levelkey.uri && !levelkey.iv) {
decryptdata = new level_key_LevelKey(levelkey.baseuri, levelkey.reluri);
decryptdata.method = levelkey.method;
decryptdata.iv = this.createInitializationVector(segmentNumber);
}
return decryptdata;
};
fragment_createClass(Fragment, [{
key: "url",
get: function get() {
if (!this._url && this.relurl) {
this._url = Object(url_toolkit["buildAbsoluteURL"])(this.baseurl, this.relurl, {
alwaysNormalize: true
});
}
return this._url;
},
set: function set(value) {
this._url = value;
}
}, {
key: "byteRange",
get: function get() {
if (!this._byteRange) {
return [];
}
return this._byteRange;
}
/**
* @type {number}
*/
}, {
key: "byteRangeStartOffset",
get: function get() {
return this.byteRange[0];
}
}, {
key: "byteRangeEndOffset",
get: function get() {
return this.byteRange[1];
}
}, {
key: "decryptdata",
get: function get() {
if (!this.levelkey && !this._decryptdata) {
return null;
}
if (!this._decryptdata && this.levelkey) {
var sn = this.sn;
if (typeof sn !== 'number') {
// We are fetching decryption data for a initialization segment
// If the segment was encrypted with AES-128
// It must have an IV defined. We cannot substitute the Segment Number in.
if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) {
logger["logger"].warn("missing IV for initialization segment with method=\"" + this.levelkey.method + "\" - compliance issue");
}
/*
Be converted to a Number.
'initSegment' will become NaN.
NaN, which when converted through ToInt32() -> +0.
---
Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.
*/
sn = 0;
}
this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);
}
return this._decryptdata;
}
}, {
key: "endProgramDateTime",
get: function get() {
if (this.programDateTime === null) {
return null;
}
if (!Object(number["isFiniteNumber"])(this.programDateTime)) {
return null;
}
var duration = !Object(number["isFiniteNumber"])(this.duration) ? 0 : this.duration;
return this.programDateTime + duration * 1000;
}
}, {
key: "encrypted",
get: function get() {
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain
return !!(this.decryptdata && this.decryptdata.uri !== null && this.decryptdata.key === null);
}
}]);
return Fragment;
}();
// CONCATENATED MODULE: ./src/loader/level.js
function level_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function level_createClass(Constructor, protoProps, staticProps) { if (protoProps) level_defineProperties(Constructor.prototype, protoProps); if (staticProps) level_defineProperties(Constructor, staticProps); return Constructor; }
var level_Level = /*#__PURE__*/function () {
function Level(baseUrl) {
// Please keep properties in alphabetical order
this.endCC = 0;
this.endSN = 0;
this.fragments = [];
this.initSegment = null;
this.live = true;
this.needSidxRanges = false;
this.startCC = 0;
this.startSN = 0;
this.startTimeOffset = null;
this.targetduration = 0;
this.totalduration = 0;
this.type = null;
this.url = baseUrl;
this.version = null;
}
level_createClass(Level, [{
key: "hasProgramDateTime",
get: function get() {
return !!(this.fragments[0] && Object(number["isFiniteNumber"])(this.fragments[0].programDateTime));
}
}]);
return Level;
}();
// CONCATENATED MODULE: ./src/utils/attr-list.js
var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
var AttrList = /*#__PURE__*/function () {
function AttrList(attrs) {
if (typeof attrs === 'string') {
attrs = AttrList.parseAttrList(attrs);
}
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
this[attr] = attrs[attr];
}
}
}
var _proto = AttrList.prototype;
_proto.decimalInteger = function decimalInteger(attrName) {
var intValue = parseInt(this[attrName], 10);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
};
_proto.hexadecimalInteger = function hexadecimalInteger(attrName) {
if (this[attrName]) {
var stringValue = (this[attrName] || '0x').slice(2);
stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;
var value = new Uint8Array(stringValue.length / 2);
for (var i = 0; i < stringValue.length / 2; i++) {
value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
}
return value;
} else {
return null;
}
};
_proto.hexadecimalIntegerAsNumber = function hexadecimalIntegerAsNumber(attrName) {
var intValue = parseInt(this[attrName], 16);
if (intValue > Number.MAX_SAFE_INTEGER) {
return Infinity;
}
return intValue;
};
_proto.decimalFloatingPoint = function decimalFloatingPoint(attrName) {
return parseFloat(this[attrName]);
};
_proto.enumeratedString = function enumeratedString(attrName) {
return this[attrName];
};
_proto.decimalResolution = function decimalResolution(attrName) {
var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
if (res === null) {
return undefined;
}
return {
width: parseInt(res[1], 10),
height: parseInt(res[2], 10)
};
};
AttrList.parseAttrList = function parseAttrList(input) {
var match,
attrs = {};
ATTR_LIST_REGEX.lastIndex = 0;
while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
var value = match[2],
quote = '"';
if (value.indexOf(quote) === 0 && value.lastIndexOf(quote) === value.length - 1) {
value = value.slice(1, -1);
}
attrs[match[1]] = value;
}
return attrs;
};
return AttrList;
}();
/* harmony default export */ var attr_list = (AttrList);
// CONCATENATED MODULE: ./src/utils/codecs.ts
// from http://mp4ra.org/codecs.html
var sampleEntryCodesISO = {
audio: {
'a3ds': true,
'ac-3': true,
'ac-4': true,
'alac': true,
'alaw': true,
'dra1': true,
'dts+': true,
'dts-': true,
'dtsc': true,
'dtse': true,
'dtsh': true,
'ec-3': true,
'enca': true,
'g719': true,
'g726': true,
'm4ae': true,
'mha1': true,
'mha2': true,
'mhm1': true,
'mhm2': true,
'mlpa': true,
'mp4a': true,
'raw ': true,
'Opus': true,
'samr': true,
'sawb': true,
'sawp': true,
'sevc': true,
'sqcp': true,
'ssmv': true,
'twos': true,
'ulaw': true
},
video: {
'avc1': true,
'avc2': true,
'avc3': true,
'avc4': true,
'avcp': true,
'drac': true,
'dvav': true,
'dvhe': true,
'encv': true,
'hev1': true,
'hvc1': true,
'mjp2': true,
'mp4v': true,
'mvc1': true,
'mvc2': true,
'mvc3': true,
'mvc4': true,
'resv': true,
'rv60': true,
's263': true,
'svc1': true,
'svc2': true,
'vc-1': true,
'vp08': true,
'vp09': true
}
};
function isCodecType(codec, type) {
var typeCodes = sampleEntryCodesISO[type];
return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
}
function isCodecSupportedInMp4(codec, type) {
return MediaSource.isTypeSupported((type || 'video') + "/mp4;codecs=\"" + codec + "\"");
}
// CONCATENATED MODULE: ./src/loader/m3u8-parser.ts
/**
* M3U8 parser
* @module
*/
// https://regex101.com is your friend
var MASTER_PLAYLIST_REGEX = /(?:#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)|#EXT-X-SESSION-DATA:([^\n\r]*)[\r\n]+)/g;
var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title
/|(?!#)([\S+ ?]+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)
/|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)
/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec
/|#.*/.source // All other non-segment oriented tags will match with all groups empty
].join(''), 'g');
var LEVEL_PLAYLIST_REGEX_SLOW = /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)([^:]*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/;
var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
function backfillProgramDateTimes(fragments, startIndex) {
var fragPrev = fragments[startIndex];
for (var i = startIndex - 1; i >= 0; i--) {
var frag = fragments[i];
frag.programDateTime = fragPrev.programDateTime - frag.duration * 1000;
fragPrev = frag;
}
}
function assignProgramDateTime(frag, prevFrag) {
if (frag.rawProgramDateTime) {
frag.programDateTime = Date.parse(frag.rawProgramDateTime);
} else if (prevFrag === null || prevFrag === void 0 ? void 0 : prevFrag.programDateTime) {
frag.programDateTime = prevFrag.endProgramDateTime;
}
if (!Object(number["isFiniteNumber"])(frag.programDateTime)) {
frag.programDateTime = null;
frag.rawProgramDateTime = null;
}
}
var m3u8_parser_M3U8Parser = /*#__PURE__*/function () {
function M3U8Parser() {}
M3U8Parser.findGroup = function findGroup(groups, mediaGroupId) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
if (group.id === mediaGroupId) {
return group;
}
}
};
M3U8Parser.convertAVC1ToAVCOTI = function convertAVC1ToAVCOTI(codec) {
var avcdata = codec.split('.');
var result;
if (avcdata.length > 2) {
result = avcdata.shift() + '.';
result += parseInt(avcdata.shift()).toString(16);
result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
} else {
result = codec;
}
return result;
};
M3U8Parser.resolve = function resolve(url, baseUrl) {
return url_toolkit["buildAbsoluteURL"](baseUrl, url, {
alwaysNormalize: true
});
};
M3U8Parser.parseMasterPlaylist = function parseMasterPlaylist(string, baseurl) {
// TODO(typescript-level)
var levels = [];
var sessionData = {};
var hasSessionData = false;
MASTER_PLAYLIST_REGEX.lastIndex = 0; // TODO(typescript-level)
function setCodecs(codecs, level) {
['video', 'audio'].forEach(function (type) {
var filtered = codecs.filter(function (codec) {
return isCodecType(codec, type);
});
if (filtered.length) {
var preferred = filtered.filter(function (codec) {
return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
});
level[type + "Codec"] = preferred.length > 0 ? preferred[0] : filtered[0]; // remove from list
codecs = codecs.filter(function (codec) {
return filtered.indexOf(codec) === -1;
});
}
});
level.unknownCodecs = codecs;
}
var result;
while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
if (result[1]) {
// '#EXT-X-STREAM-INF' is found, parse level tag in group 1
// TODO(typescript-level)
var level = {};
var attrs = level.attrs = new attr_list(result[1]);
level.url = M3U8Parser.resolve(result[2], baseurl);
var resolution = attrs.decimalResolution('RESOLUTION');
if (resolution) {
level.width = resolution.width;
level.height = resolution.height;
}
level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
level.name = attrs.NAME;
setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);
if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
}
levels.push(level);
} else if (result[3]) {
// '#EXT-X-SESSION-DATA' is found, parse session data in group 3
var sessionAttrs = new attr_list(result[3]);
if (sessionAttrs['DATA-ID']) {
hasSessionData = true;
sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;
}
}
}
return {
levels: levels,
sessionData: hasSessionData ? sessionData : null
};
};
M3U8Parser.parseMasterPlaylistMedia = function parseMasterPlaylistMedia(string, baseurl, type, audioGroups) {
if (audioGroups === void 0) {
audioGroups = [];
}
var result;
var medias = [];
var id = 0;
MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
var attrs = new attr_list(result[1]);
if (attrs.TYPE === type) {
var media = {
attrs: attrs,
id: id++,
groupId: attrs['GROUP-ID'],
instreamId: attrs['INSTREAM-ID'],
name: attrs.NAME || attrs.LANGUAGE,
type: type,
default: attrs.DEFAULT === 'YES',
autoselect: attrs.AUTOSELECT === 'YES',
forced: attrs.FORCED === 'YES',
lang: attrs.LANGUAGE
};
if (attrs.URI) {
media.url = M3U8Parser.resolve(attrs.URI, baseurl);
}
if (audioGroups.length) {
// If there are audio groups signalled in the manifest, let's look for a matching codec string for this track
var groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId); // If we don't find the track signalled, lets use the first audio groups codec we have
// Acting as a best guess
media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;
}
medias.push(media);
}
}
return medias;
};
M3U8Parser.parseLevelPlaylist = function parseLevelPlaylist(string, baseurl, id, type, levelUrlId) {
var currentSN = 0;
var totalduration = 0;
var level = new level_Level(baseurl);
var discontinuityCounter = 0;
var prevFrag = null;
var frag = new fragment_Fragment();
var result;
var i;
var levelkey;
var firstPdtIndex = null;
LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
var duration = result[1];
if (duration) {
// INF
frag.duration = parseFloat(duration); // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var title = (' ' + result[2]).slice(1);
frag.title = title || null;
frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
} else if (result[3]) {
// url
if (Object(number["isFiniteNumber"])(frag.duration)) {
var sn = currentSN++;
frag.type = type;
frag.start = totalduration;
if (levelkey) {
frag.levelkey = levelkey;
}
frag.sn = sn;
frag.level = id;
frag.cc = discontinuityCounter;
frag.urlId = levelUrlId;
frag.baseurl = baseurl; // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.relurl = (' ' + result[3]).slice(1);
assignProgramDateTime(frag, prevFrag);
level.fragments.push(frag);
prevFrag = frag;
totalduration += frag.duration;
frag = new fragment_Fragment();
}
} else if (result[4]) {
// X-BYTERANGE
var data = (' ' + result[4]).slice(1);
if (prevFrag) {
frag.setByteRange(data, prevFrag);
} else {
frag.setByteRange(data);
}
} else if (result[5]) {
// PROGRAM-DATE-TIME
// avoid sliced strings https://github.com/video-dev/hls.js/issues/939
frag.rawProgramDateTime = (' ' + result[5]).slice(1);
frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
if (firstPdtIndex === null) {
firstPdtIndex = level.fragments.length;
}
} else {
result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
if (!result) {
logger["logger"].warn('No matches on slow regex match for level playlist!');
continue;
}
for (i = 1; i < result.length; i++) {
if (typeof result[i] !== 'undefined') {
break;
}
} // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
var value1 = (' ' + result[i + 1]).slice(1);
var value2 = (' ' + result[i + 2]).slice(1);
switch (result[i]) {
case '#':
frag.tagList.push(value2 ? [value1, value2] : [value1]);
break;
case 'PLAYLIST-TYPE':
level.type = value1.toUpperCase();
break;
case 'MEDIA-SEQUENCE':
currentSN = level.startSN = parseInt(value1);
break;
case 'TARGETDURATION':
level.targetduration = parseFloat(value1);
break;
case 'VERSION':
level.version = parseInt(value1);
break;
case 'EXTM3U':
break;
case 'ENDLIST':
level.live = false;
break;
case 'DIS':
discontinuityCounter++;
frag.tagList.push(['DIS']);
break;
case 'DISCONTINUITY-SEQ':
discontinuityCounter = parseInt(value1);
break;
case 'KEY':
{
// https://tools.ietf.org/html/rfc8216#section-4.3.2.4
var decryptparams = value1;
var keyAttrs = new attr_list(decryptparams);
var decryptmethod = keyAttrs.enumeratedString('METHOD');
var decrypturi = keyAttrs.URI;
var decryptiv = keyAttrs.hexadecimalInteger('IV'); // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of "identity".
var decryptkeyformat = keyAttrs.KEYFORMAT || 'identity';
if (decryptkeyformat === 'com.apple.streamingkeydelivery') {
logger["logger"].warn('Keyformat com.apple.streamingkeydelivery is not supported');
continue;
}
if (decryptmethod) {
levelkey = new level_key_LevelKey(baseurl, decrypturi);
if (decrypturi && ['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0) {
levelkey.method = decryptmethod;
levelkey.key = null; // Initialization Vector (IV)
levelkey.iv = decryptiv;
}
}
break;
}
case 'START':
{
var startAttrs = new attr_list(value1);
var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET'); // TIME-OFFSET can be 0
if (Object(number["isFiniteNumber"])(startTimeOffset)) {
level.startTimeOffset = startTimeOffset;
}
break;
}
case 'MAP':
{
var mapAttrs = new attr_list(value1);
frag.relurl = mapAttrs.URI;
if (mapAttrs.BYTERANGE) {
frag.setByteRange(mapAttrs.BYTERANGE);
}
frag.baseurl = baseurl;
frag.level = id;
frag.type = type;
frag.sn = 'initSegment';
level.initSegment = frag;
frag = new fragment_Fragment();
frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;
break;
}
default:
logger["logger"].warn("line parsed but not handled: " + result);
break;
}
}
}
frag = prevFrag; // logger.log('found ' + level.fragments.length + ' fragments');
if (frag && !frag.relurl) {
level.fragments.pop();
totalduration -= frag.duration;
}
level.totalduration = totalduration;
level.averagetargetduration = totalduration / level.fragments.length;
level.endSN = currentSN - 1;
level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;
level.endCC = discontinuityCounter;
if (!level.initSegment && level.fragments.length) {
// this is a bit lurky but HLS really has no other way to tell us
// if the fragments are TS or MP4, except if we download them :/
// but this is to be able to handle SIDX.
if (level.fragments.every(function (frag) {
return MP4_REGEX_SUFFIX.test(frag.relurl);
})) {
logger["logger"].warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
frag = new fragment_Fragment();
frag.relurl = level.fragments[0].relurl;
frag.baseurl = baseurl;
frag.level = id;
frag.type = type;
frag.sn = 'initSegment';
level.initSegment = frag;
level.needSidxRanges = true;
}
}
/**
* Backfill any missing PDT values
"If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
one or more Media Segment URIs, the client SHOULD extrapolate
backward from that tag (using EXTINF durations and/or media
timestamps) to associate dates with those segments."
* We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
* computed.
*/
if (firstPdtIndex) {
backfillProgramDateTimes(level.fragments, firstPdtIndex);
}
return level;
};
return M3U8Parser;
}();
// CONCATENATED MODULE: ./src/loader/playlist-loader.ts
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
*
* Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
*
* Uses loader(s) set in config to do actual internal loading of resource tasks.
*
* @module
*
*/
var _window = window,
performance = _window.performance;
/**
* @constructor
*/
var playlist_loader_PlaylistLoader = /*#__PURE__*/function (_EventHandler) {
_inheritsLoose(PlaylistLoader, _EventHandler);
/**
* @constructs
* @param {Hls} hls
*/
function PlaylistLoader(hls) {
var _this;
_this = _EventHandler.call(this, hls, events["default"].MANIFEST_LOADING, events["default"].LEVEL_LOADING, events["default"].AUDIO_TRACK_LOADING, events["default"].SUBTITLE_TRACK_LOADING) || this;
_this.loaders = {};
return _this;
}
/**
* @param {PlaylistContextType} type
* @returns {boolean}
*/
PlaylistLoader.canHaveQualityLevels = function canHaveQualityLevels(type) {
return type !== PlaylistContextType.AUDIO_TRACK && type !== PlaylistContextType.SUBTITLE_TRACK;
}
/**
* Map context.type to LevelType
* @param {PlaylistLoaderContext} context
* @returns {LevelType}
*/
;
PlaylistLoader.mapContextToLevelType = function mapContextToLevelType(context) {
var type = context.type;
switch (type) {
case PlaylistContextType.AUDIO_TRACK:
return PlaylistLevelType.AUDIO;
case PlaylistContextType.SUBTITLE_TRACK:
return PlaylistLevelType.SUBTITLE;
default:
return PlaylistLevelType.MAIN;
}
};
PlaylistLoader.getResponseUrl = function getResponseUrl(response, context) {
var url = response.url; // responseURL not supported on some browsers (it is used to detect URL redirection)
// data-uri mode also not supported (but no need to detect redirection)
if (url === undefined || url.indexOf('data:') === 0) {
// fallback to initial URL
url = context.url;
}
return url;
}
/**
* Returns defaults or configured loader-type overloads (pLoader and loader config params)
* Default loader is XHRLoader (see utils)
* @param {PlaylistLoaderContext} context
* @returns {Loader} or other compatible configured overload
*/
;
var _proto = PlaylistLoader.prototype;
_proto.createInternalLoader = function createInternalLoader(context) {
var config = this.hls.config;
var PLoader = config.pLoader;
var Loader = config.loader; // TODO(typescript-config): Verify once config is typed that InternalLoader always returns a Loader
var InternalLoader = PLoader || Loader;
var loader = new InternalLoader(config); // TODO - Do we really need to assign the instance or if the dep has been lost
context.loader = loader;
this.loaders[context.type] = loader;
return loader;
};
_proto.getInternalLoader = function getInternalLoader(context) {
return this.loaders[context.type];
};
_proto.resetInternalLoader = function resetInternalLoader(contextType) {
if (this.loaders[contextType]) {
delete this.loaders[contextType];
}
}
/**
* Call `destroy` on all internal loader instances mapped (one per context type)
*/
;
_proto.destroyInternalLoaders = function destroyInternalLoaders() {
for (var contextType in this.loaders) {
var loader = this.loaders[contextType];
if (loader) {
loader.destroy();
}
this.resetInternalLoader(contextType);
}
};
_proto.destroy = function destroy() {
this.destroyInternalLoaders();
_EventHandler.prototype.destroy.call(this);
};
_proto.onManifestLoading = function onManifestLoading(data) {
this.load({
url: data.url,
type: PlaylistContextType.MANIFEST,
level: 0,
id: null,
responseType: 'text'
});
};
_proto.onLevelLoading = function onLevelLoading(data) {
this.load({
url: data.url,
type: PlaylistContextType.LEVEL,
level: data.level,
id: data.id,
responseType: 'text'
});
};
_proto.onAudioTrackLoading = function onAudioTrackLoading(data) {
this.load({
url: data.url,
type: PlaylistContextType.AUDIO_TRACK,
level: null,
id: data.id,
responseType: 'text'
});
};
_proto.onSubtitleTrackLoading = function onSubtitleTrackLoading(data) {
this.load({
url: data.url,
type: PlaylistContextType.SUBTITLE_TRACK,
level: null,
id: data.id,
responseType: 'text'
});
};
_proto.load = function load(context) {
var config = this.hls.config;
logger["logger"].debug("Loading playlist of type " + context.type + ", level: " + context.level + ", id: " + context.id); // Check if a loader for this context already exists
var loader = this.getInternalLoader(context);
if (loader) {
var loaderContext = loader.context;
if (loaderContext && loaderContext.url === context.url) {
// same URL can't overlap
logger["logger"].trace('playlist request ongoing');
return false;
} else {
logger["logger"].warn("aborting previous loader for type: " + context.type);
loader.abort();
}
}
var maxRetry;
var timeout;
var retryDelay;
var maxRetryDelay; // apply different configs for retries depending on
// context (manifest, level, audio/subs playlist)
switch (context.type) {
case PlaylistContextType.MANIFEST:
maxRetry = config.manifestLoadingMaxRetry;
timeout = config.manifestLoadingTimeOut;
retryDelay = config.manifestLoadingRetryDelay;
maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
break;
case PlaylistContextType.LEVEL:
// Disable internal loader retry logic, since we are managing retries in Level Controller
maxRetry = 0;
maxRetryDelay = 0;
retryDelay = 0;
timeout = config.levelLoadingTimeOut; // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config
break;
default:
maxRetry = config.levelLoadingMaxRetry;
timeout = config.levelLoadingTimeOut;
retryDelay = config.levelLoadingRetryDelay;
maxRetryDelay = config.levelLoadingMaxRetryTimeout;
break;
}
loader = this.createInternalLoader(context);
var loaderConfig = {
timeout: timeout,
maxRetry: maxRetry,
retryDelay: retryDelay,
maxRetryDelay: maxRetryDelay
};
var loaderCallbacks = {
onSuccess: this.loadsuccess.bind(this),
onError: this.loaderror.bind(this),
onTimeout: this.loadtimeout.bind(this)
};
logger["logger"].debug("Calling internal loader delegate for URL: " + context.url);
loader.load(context, loaderConfig, loaderCallbacks);
return true;
};
_proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
if (context.isSidxRequest) {
this._handleSidxRequest(response, context);
this._handlePlaylistLoaded(response, stats, context, networkDetails);
return;
}
this.resetInternalLoader(context.type);
if (typeof response.data !== 'string') {
throw new Error('expected responseType of "text" for PlaylistLoader');
}
var string = response.data;
stats.tload = performance.now(); // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
// Validate if it is an M3U8 at all
if (string.indexOf('#EXTM3U') !== 0) {
this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
return;
} // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
} else {
this._handleMasterPlaylist(response, stats, context, networkDetails);
}
};
_proto.loaderror = function loaderror(response, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
this._handleNetworkError(context, networkDetails, false, response);
};
_proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
this._handleNetworkError(context, networkDetails, true);
} // TODO(typescript-config): networkDetails can currently be a XHR or Fetch impl,
// but with custom loaders it could be generic investigate this further when config is typed
;
_proto._handleMasterPlaylist = function _handleMasterPlaylist(response, stats, context, networkDetails) {
var hls = this.hls;
var string = response.data;
var url = PlaylistLoader.getResponseUrl(response, context);
var _M3U8Parser$parseMast = m3u8_parser_M3U8Parser.parseMasterPlaylist(string, url),
levels = _M3U8Parser$parseMast.levels,
sessionData = _M3U8Parser$parseMast.sessionData;
if (!levels.length) {
this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
return;
} // multi level playlist, parse level info
var audioGroups = levels.map(function (level) {
return {
id: level.attrs.AUDIO,
codec: level.audioCodec
};
});
var audioTracks = m3u8_parser_M3U8Parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
var subtitles = m3u8_parser_M3U8Parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');
var captions = m3u8_parser_M3U8Parser.parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS');
if (audioTracks.length) {
// check if we have found an audio track embedded in main playlist (audio track without URI attribute)
var embeddedAudioFound = false;
audioTracks.forEach(function (audioTrack) {
if (!audioTrack.url) {
embeddedAudioFound = true;
}
}); // if no embedded audio track defined, but audio codec signaled in quality level,
// we need to signal this main audio track this could happen with playlists with
// alt audio rendition in which quality levels (main)
// contains both audio+video. but with mixed audio track not signaled
if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
logger["logger"].log('audio codec signaled in quality level, but no embedded audio track signaled, create one');
audioTracks.unshift({
type: 'main',
name: 'main',
default: false,
autoselect: false,
forced: false,
id: -1,
attrs: {},
url: ''
});
}
}
hls.trigger(events["default"].MANIFEST_LOADED, {
levels: levels,
audioTracks: audioTracks,
subtitles: subtitles,
captions: captions,
url: url,
stats: stats,
networkDetails: networkDetails,
sessionData: sessionData
});
};
_proto._handleTrackOrLevelPlaylist = function _handleTrackOrLevelPlaylist(response, stats, context, networkDetails) {
var hls = this.hls;
var id = context.id,
level = context.level,
type = context.type;
var url = PlaylistLoader.getResponseUrl(response, context); // if the values are null, they will result in the else conditional
var levelUrlId = Object(number["isFiniteNumber"])(id) ? id : 0;
var levelId = Object(number["isFiniteNumber"])(level) ? level : levelUrlId;
var levelType = PlaylistLoader.mapContextToLevelType(context);
var levelDetails = m3u8_parser_M3U8Parser.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId); // set stats on level structure
// TODO(jstackhouse): why? mixing concerns, is it just treated as value bag?
levelDetails.tload = stats.tload;
if (!levelDetails.fragments.length) {
hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].NETWORK_ERROR,
details: errors["ErrorDetails"].LEVEL_EMPTY_ERROR,
fatal: false,
url: url,
reason: 'no fragments found in level',
level: typeof context.level === 'number' ? context.level : undefined
});
return;
} // We have done our first request (Manifest-type) and receive
// not a master playlist but a chunk-list (track/level)
// We fire the manifest-loaded event anyway with the parsed level-details
// by creating a single-level structure for it.
if (type === PlaylistContextType.MANIFEST) {
var singleLevel = {
url: url,
details: levelDetails
};
hls.trigger(events["default"].MANIFEST_LOADED, {
levels: [singleLevel],
audioTracks: [],
url: url,
stats: stats,
networkDetails: networkDetails,
sessionData: null
});
} // save parsing time
stats.tparsed = performance.now(); // in case we need SIDX ranges
// return early after calling load for
// the SIDX box.
if (levelDetails.needSidxRanges) {
var sidxUrl = levelDetails.initSegment.url;
this.load({
url: sidxUrl,
isSidxRequest: true,
type: type,
level: level,
levelDetails: levelDetails,
id: id,
rangeStart: 0,
rangeEnd: 2048,
responseType: 'arraybuffer'
});
return;
} // extend the context with the new levelDetails property
context.levelDetails = levelDetails;
this._handlePlaylistLoaded(response, stats, context, networkDetails);
};
_proto._handleSidxRequest = function _handleSidxRequest(response, context) {
if (typeof response.data === 'string') {
throw new Error('sidx request must be made with responseType of array buffer');
}
var sidxInfo = mp4demuxer["default"].parseSegmentIndex(new Uint8Array(response.data)); // if provided fragment does not contain sidx, early return
if (!sidxInfo) {
return;
}
var sidxReferences = sidxInfo.references;
var levelDetails = context.levelDetails;
sidxReferences.forEach(function (segmentRef, index) {
var segRefInfo = segmentRef.info;
if (!levelDetails) {
return;
}
var frag = levelDetails.fragments[index];
if (frag.byteRange.length === 0) {
frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start));
}
});
if (levelDetails) {
levelDetails.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0');
}
};
_proto._handleManifestParsingError = function _handleManifestParsingError(response, context, reason, networkDetails) {
this.hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].NETWORK_ERROR,
details: errors["ErrorDetails"].MANIFEST_PARSING_ERROR,
fatal: true,
url: response.url,
reason: reason,
networkDetails: networkDetails
});
};
_proto._handleNetworkError = function _handleNetworkError(context, networkDetails, timeout, response) {
if (timeout === void 0) {
timeout = false;
}
if (response === void 0) {
response = null;
}
logger["logger"].info("A network error occured while loading a " + context.type + "-type playlist");
var details;
var fatal;
var loader = this.getInternalLoader(context);
switch (context.type) {
case PlaylistContextType.MANIFEST:
details = timeout ? errors["ErrorDetails"].MANIFEST_LOAD_TIMEOUT : errors["ErrorDetails"].MANIFEST_LOAD_ERROR;
fatal = true;
break;
case PlaylistContextType.LEVEL:
details = timeout ? errors["ErrorDetails"].LEVEL_LOAD_TIMEOUT : errors["ErrorDetails"].LEVEL_LOAD_ERROR;
fatal = false;
break;
case PlaylistContextType.AUDIO_TRACK:
details = timeout ? errors["ErrorDetails"].AUDIO_TRACK_LOAD_TIMEOUT : errors["ErrorDetails"].AUDIO_TRACK_LOAD_ERROR;
fatal = false;
break;
default:
// details = ...?
fatal = false;
}
if (loader) {
loader.abort();
this.resetInternalLoader(context.type);
} // TODO(typescript-events): when error events are handled, type this
var errorData = {
type: errors["ErrorTypes"].NETWORK_ERROR,
details: details,
fatal: fatal,
url: context.url,
loader: loader,
context: context,
networkDetails: networkDetails
};
if (response) {
errorData.response = response;
}
this.hls.trigger(events["default"].ERROR, errorData);
};
_proto._handlePlaylistLoaded = function _handlePlaylistLoaded(response, stats, context, networkDetails) {
var type = context.type,
level = context.level,
id = context.id,
levelDetails = context.levelDetails;
if (!levelDetails || !levelDetails.targetduration) {
this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
return;
}
var canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);
if (canHaveLevels) {
this.hls.trigger(events["default"].LEVEL_LOADED, {
details: levelDetails,
level: level || 0,
id: id || 0,
stats: stats,
networkDetails: networkDetails
});
} else {
switch (type) {
case PlaylistContextType.AUDIO_TRACK:
this.hls.trigger(events["default"].AUDIO_TRACK_LOADED, {
details: levelDetails,
id: id,
stats: stats,
networkDetails: networkDetails
});
break;
case PlaylistContextType.SUBTITLE_TRACK:
this.hls.trigger(events["default"].SUBTITLE_TRACK_LOADED, {
details: levelDetails,
id: id,
stats: stats,
networkDetails: networkDetails
});
break;
}
}
};
return PlaylistLoader;
}(event_handler);
/* harmony default export */ var playlist_loader = (playlist_loader_PlaylistLoader);
// CONCATENATED MODULE: ./src/loader/fragment-loader.js
function fragment_loader_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/*
* Fragment Loader
*/
var fragment_loader_FragmentLoader = /*#__PURE__*/function (_EventHandler) {
fragment_loader_inheritsLoose(FragmentLoader, _EventHandler);
function FragmentLoader(hls) {
var _this;
_this = _EventHandler.call(this, hls, events["default"].FRAG_LOADING) || this;
_this.loaders = {};
return _this;
}
var _proto = FragmentLoader.prototype;
_proto.destroy = function destroy() {
var loaders = this.loaders;
for (var loaderName in loaders) {
var loader = loaders[loaderName];
if (loader) {
loader.destroy();
}
}
this.loaders = {};
_EventHandler.prototype.destroy.call(this);
};
_proto.onFragLoading = function onFragLoading(data) {
var frag = data.frag,
type = frag.type,
loaders = this.loaders,
config = this.hls.config,
FragmentILoader = config.fLoader,
DefaultILoader = config.loader; // reset fragment state
frag.loaded = 0;
var loader = loaders[type];
if (loader) {
logger["logger"].warn("abort previous fragment loader for type: " + type);
loader.abort();
}
loader = loaders[type] = frag.loader = config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);
var loaderContext, loaderConfig, loaderCallbacks;
loaderContext = {
url: frag.url,
frag: frag,
responseType: 'arraybuffer',
progressData: false
};
var start = frag.byteRangeStartOffset,
end = frag.byteRangeEndOffset;
if (Object(number["isFiniteNumber"])(start) && Object(number["isFiniteNumber"])(end)) {
loaderContext.rangeStart = start;
loaderContext.rangeEnd = end;
}
loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: 0,
maxRetryDelay: config.fragLoadingMaxRetryTimeout
};
loaderCallbacks = {
onSuccess: this.loadsuccess.bind(this),
onError: this.loaderror.bind(this),
onTimeout: this.loadtimeout.bind(this),
onProgress: this.loadprogress.bind(this)
};
loader.load(loaderContext, loaderConfig, loaderCallbacks);
};
_proto.loadsuccess = function loadsuccess(response, stats, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
var payload = response.data,
frag = context.frag; // detach fragment loader on load success
frag.loader = undefined;
this.loaders[frag.type] = undefined;
this.hls.trigger(events["default"].FRAG_LOADED, {
payload: payload,
frag: frag,
stats: stats,
networkDetails: networkDetails
});
};
_proto.loaderror = function loaderror(response, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
var frag = context.frag;
var loader = frag.loader;
if (loader) {
loader.abort();
}
this.loaders[frag.type] = undefined;
this.hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].NETWORK_ERROR,
details: errors["ErrorDetails"].FRAG_LOAD_ERROR,
fatal: false,
frag: context.frag,
response: response,
networkDetails: networkDetails
});
};
_proto.loadtimeout = function loadtimeout(stats, context, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
var frag = context.frag;
var loader = frag.loader;
if (loader) {
loader.abort();
}
this.loaders[frag.type] = undefined;
this.hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].NETWORK_ERROR,
details: errors["ErrorDetails"].FRAG_LOAD_TIMEOUT,
fatal: false,
frag: context.frag,
networkDetails: networkDetails
});
} // data will be used for progressive parsing
;
_proto.loadprogress = function loadprogress(stats, context, data, networkDetails) {
if (networkDetails === void 0) {
networkDetails = null;
}
// jshint ignore:line
var frag = context.frag;
frag.loaded = stats.loaded;
this.hls.trigger(events["default"].FRAG_LOAD_PROGRESS, {
frag: frag,
stats: stats,
networkDetails: networkDetails
});
};
return FragmentLoader;
}(event_handler);
/* harmony default export */ var fragment_loader = (fragment_loader_FragmentLoader);
// CONCATENATED MODULE: ./src/loader/key-loader.ts
function key_loader_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/*
* Decrypt key Loader
*/
var key_loader_KeyLoader = /*#__PURE__*/function (_EventHandler) {
key_loader_inheritsLoose(KeyLoader, _EventHandler);
function KeyLoader(hls) {
var _this;
_this = _EventHandler.call(this, hls, events["default"].KEY_LOADING) || this;
_this.loaders = {};
_this.decryptkey = null;
_this.decrypturl = null;
return _this;
}
var _proto = KeyLoader.prototype;
_proto.destroy = function destroy() {
for (var loaderName in this.loaders) {
var loader = this.loaders[loaderName];
if (loader) {
loader.destroy();
}
}
this.loaders = {};
_EventHandler.prototype.destroy.call(this);
};
_proto.onKeyLoading = function onKeyLoading(data) {
var frag = data.frag;
var type = frag.type;
var loader = this.loaders[type];
if (!frag.decryptdata) {
logger["logger"].warn('Missing decryption data on fragment in onKeyLoading');
return;
} // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved
var uri = frag.decryptdata.uri;
if (uri !== this.decrypturl || this.decryptkey === null) {
var config = this.hls.config;
if (loader) {
logger["logger"].warn("abort previous key loader for type:" + type);
loader.abort();
}
if (!uri) {
logger["logger"].warn('key uri is falsy');
return;
}
frag.loader = this.loaders[type] = new config.loader(config);
this.decrypturl = uri;
this.decryptkey = null;
var loaderContext = {
url: uri,
frag: frag,
responseType: 'arraybuffer'
}; // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
// key-loader will trigger an error and rely on stream-controller to handle retry logic.
// this will also align retry logic with fragment-loader
var loaderConfig = {
timeout: config.fragLoadingTimeOut,
maxRetry: 0,
retryDelay: config.fragLoadingRetryDelay,
maxRetryDelay: config.fragLoadingMaxRetryTimeout
};
var loaderCallbacks = {
onSuccess: this.loadsuccess.bind(this),
onError: this.loaderror.bind(this),
onTimeout: this.loadtimeout.bind(this)
};
frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);
} else if (this.decryptkey) {
// Return the key if it's already been loaded
frag.decryptdata.key = this.decryptkey;
this.hls.trigger(events["default"].KEY_LOADED, {
frag: frag
});
}
};
_proto.loadsuccess = function loadsuccess(response, stats, context) {
var frag = context.frag;
if (!frag.decryptdata) {
logger["logger"].error('after key load, decryptdata unset');
return;
}
this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data); // detach fragment loader on load success
frag.loader = undefined;
delete this.loaders[frag.type];
this.hls.trigger(events["default"].KEY_LOADED, {
frag: frag
});
};
_proto.loaderror = function loaderror(response, context) {
var frag = context.frag;
var loader = frag.loader;
if (loader) {
loader.abort();
}
delete this.loaders[frag.type];
this.hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].NETWORK_ERROR,
details: errors["ErrorDetails"].KEY_LOAD_ERROR,
fatal: false,
frag: frag,
response: response
});
};
_proto.loadtimeout = function loadtimeout(stats, context) {
var frag = context.frag;
var loader = frag.loader;
if (loader) {
loader.abort();
}
delete this.loaders[frag.type];
this.hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].NETWORK_ERROR,
details: errors["ErrorDetails"].KEY_LOAD_TIMEOUT,
fatal: false,
frag: frag
});
};
return KeyLoader;
}(event_handler);
/* harmony default export */ var key_loader = (key_loader_KeyLoader);
// CONCATENATED MODULE: ./src/controller/fragment-tracker.js
function fragment_tracker_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var FragmentState = {
NOT_LOADED: 'NOT_LOADED',
APPENDING: 'APPENDING',
PARTIAL: 'PARTIAL',
OK: 'OK'
};
var fragment_tracker_FragmentTracker = /*#__PURE__*/function (_EventHandler) {
fragment_tracker_inheritsLoose(FragmentTracker, _EventHandler);
function FragmentTracker(hls) {
var _this;
_this = _EventHandler.call(this, hls, events["default"].BUFFER_APPENDED, events["default"].FRAG_BUFFERED, events["default"].FRAG_LOADED) || this;
_this.bufferPadding = 0.2;
_this.fragments = Object.create(null);
_this.timeRanges = Object.create(null);
_this.config = hls.config;
return _this;
}
var _proto = FragmentTracker.prototype;
_proto.destroy = function destroy() {
this.fragments = Object.create(null);
this.timeRanges = Object.create(null);
this.config = null;
event_handler.prototype.destroy.call(this);
_EventHandler.prototype.destroy.call(this);
}
/**
* Return a Fragment that match the position and levelType.
* If not found any Fragment, return null
* @param {number} position
* @param {LevelType} levelType
* @returns {Fragment|null}
*/
;
_proto.getBufferedFrag = function getBufferedFrag(position, levelType) {
var fragments = this.fragments;
var bufferedFrags = Object.keys(fragments).filter(function (key) {
var fragmentEntity = fragments[key];
if (fragmentEntity.body.type !== levelType) {
return false;
}
if (!fragmentEntity.buffered) {
return false;
}
var frag = fragmentEntity.body;
return frag.startPTS <= position && position <= frag.endPTS;
});
if (bufferedFrags.length === 0) {
return null;
} else {
// https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566
var bufferedFragKey = bufferedFrags.pop();
return fragments[bufferedFragKey].body;
}
}
/**
* Partial fragments effected by coded frame eviction will be removed
* The browser will unload parts of the buffer to free up memory for new buffer data
* Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
* @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)
* @param {TimeRanges} timeRange TimeRange object from a sourceBuffer
*/
;
_proto.detectEvictedFragments = function detectEvictedFragments(elementaryStream, timeRange) {
var _this2 = this;
// Check if any flagged fragments have been unloaded
Object.keys(this.fragments).forEach(function (key) {
var fragmentEntity = _this2.fragments[key];
if (!fragmentEntity || !fragmentEntity.buffered) {
return;
}
var esData = fragmentEntity.range[elementaryStream];
if (!esData) {
return;
}
var fragmentTimes = esData.time;
for (var i = 0; i < fragmentTimes.length; i++) {
var time = fragmentTimes[i];
if (!_this2.isTimeBuffered(time.startPTS, time.endPTS, timeRange)) {
// Unregister partial fragment as it needs to load again to be reused
_this2.removeFragment(fragmentEntity.body);
break;
}
}
});
}
/**
* Checks if the fragment passed in is loaded in the buffer properly
* Partially loaded fragments will be registered as a partial fragment
* @param {Object} fragment Check the fragment against all sourceBuffers loaded
*/
;
_proto.detectPartialFragments = function detectPartialFragments(fragment) {
var _this3 = this;
var fragKey = this.getFragmentKey(fragment);
var fragmentEntity = this.fragments[fragKey];
if (fragmentEntity) {
fragmentEntity.buffered = true;
Object.keys(this.timeRanges).forEach(function (elementaryStream) {
if (fragment.hasElementaryStream(elementaryStream)) {
var timeRange = _this3.timeRanges[elementaryStream]; // Check for malformed fragments
// Gaps need to be calculated for each elementaryStream
fragmentEntity.range[elementaryStream] = _this3.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);
}
});
}
};
_proto.getBufferedTimes = function getBufferedTimes(startPTS, endPTS, timeRange) {
var fragmentTimes = [];
var startTime, endTime;
var fragmentPartial = false;
for (var i = 0; i < timeRange.length; i++) {
startTime = timeRange.start(i) - this.bufferPadding;
endTime = timeRange.end(i) + this.bufferPadding;
if (startPTS >= startTime && endPTS <= endTime) {
// Fragment is entirely contained in buffer
// No need to check the other timeRange times since it's completely playable
fragmentTimes.push({
startPTS: Math.max(startPTS, timeRange.start(i)),
endPTS: Math.min(endPTS, timeRange.end(i))
});
break;
} else if (startPTS < endTime && endPTS > startTime) {
// Check for intersection with buffer
// Get playable sections of the fragment
fragmentTimes.push({
startPTS: Math.max(startPTS, timeRange.start(i)),
endPTS: Math.min(endPTS, timeRange.end(i))
});
fragmentPartial = true;
} else if (endPTS <= startTime) {
// No need to check the rest of the timeRange as it is in order
break;
}
}
return {
time: fragmentTimes,
partial: fragmentPartial
};
};
_proto.getFragmentKey = function getFragmentKey(fragment) {
return fragment.type + "_" + fragment.level + "_" + fragment.urlId + "_" + fragment.sn;
}
/**
* Gets the partial fragment for a certain time
* @param {Number} time
* @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment
*/
;
_proto.getPartialFragment = function getPartialFragment(time) {
var _this4 = this;
var timePadding, startTime, endTime;
var bestFragment = null;
var bestOverlap = 0;
Object.keys(this.fragments).forEach(function (key) {
var fragmentEntity = _this4.fragments[key];
if (_this4.isPartial(fragmentEntity)) {
startTime = fragmentEntity.body.startPTS - _this4.bufferPadding;
endTime = fragmentEntity.body.endPTS + _this4.bufferPadding;
if (time >= startTime && time <= endTime) {
// Use the fragment that has the most padding from start and end time
timePadding = Math.min(time - startTime, endTime - time);
if (bestOverlap <= timePadding) {
bestFragment = fragmentEntity.body;
bestOverlap = timePadding;
}
}
}
});
return bestFragment;
}
/**
* @param {Object} fragment The fragment to check
* @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded
*/
;
_proto.getState = function getState(fragment) {
var fragKey = this.getFragmentKey(fragment);
var fragmentEntity = this.fragments[fragKey];
var state = FragmentState.NOT_LOADED;
if (fragmentEntity !== undefined) {
if (!fragmentEntity.buffered) {
state = FragmentState.APPENDING;
} else if (this.isPartial(fragmentEntity) === true) {
state = FragmentState.PARTIAL;
} else {
state = FragmentState.OK;
}
}
return state;
};
_proto.isPartial = function isPartial(fragmentEntity) {
return fragmentEntity.buffered === true && (fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true || fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true);
};
_proto.isTimeBuffered = function isTimeBuffered(startPTS, endPTS, timeRange) {
var startTime, endTime;
for (var i = 0; i < timeRange.length; i++) {
startTime = timeRange.start(i) - this.bufferPadding;
endTime = timeRange.end(i) + this.bufferPadding;
if (startPTS >= startTime && endPTS <= endTime) {
return true;
}
if (endPTS <= startTime) {
// No need to check the rest of the timeRange as it is in order
return false;
}
}
return false;
}
/**
* Fires when a fragment loading is completed
*/
;
_proto.onFragLoaded = function onFragLoaded(e) {
var fragment = e.frag; // don't track initsegment (for which sn is not a number)
// don't track frags used for bitrateTest, they're irrelevant.
if (!Object(number["isFiniteNumber"])(fragment.sn) || fragment.bitrateTest) {
return;
}
this.fragments[this.getFragmentKey(fragment)] = {
body: fragment,
range: Object.create(null),
buffered: false
};
}
/**
* Fires when the buffer is updated
*/
;
_proto.onBufferAppended = function onBufferAppended(e) {
var _this5 = this;
// Store the latest timeRanges loaded in the buffer
this.timeRanges = e.timeRanges;
Object.keys(this.timeRanges).forEach(function (elementaryStream) {
var timeRange = _this5.timeRanges[elementaryStream];
_this5.detectEvictedFragments(elementaryStream, timeRange);
});
}
/**
* Fires after a fragment has been loaded into the source buffer
*/
;
_proto.onFragBuffered = function onFragBuffered(e) {
this.detectPartialFragments(e.frag);
}
/**
* Return true if fragment tracker has the fragment.
* @param {Object} fragment
* @returns {boolean}
*/
;
_proto.hasFragment = function hasFragment(fragment) {
var fragKey = this.getFragmentKey(fragment);
return this.fragments[fragKey] !== undefined;
}
/**
* Remove a fragment from fragment tracker until it is loaded again
* @param {Object} fragment The fragment to remove
*/
;
_proto.removeFragment = function removeFragment(fragment) {
var fragKey = this.getFragmentKey(fragment);
delete this.fragments[fragKey];
}
/**
* Remove all fragments from fragment tracker.
*/
;
_proto.removeAllFragments = function removeAllFragments() {
this.fragments = Object.create(null);
};
return FragmentTracker;
}(event_handler);
// CONCATENATED MODULE: ./src/utils/binary-search.ts
var BinarySearch = {
/**
* Searches for an item in an array which matches a certain condition.
* This requires the condition to only match one item in the array,
* and for the array to be ordered.
*
* @param {Array<T>} list The array to search.
* @param {BinarySearchComparison<T>} comparisonFn
* Called and provided a candidate item as the first argument.
* Should return:
* > -1 if the item should be located at a lower index than the provided item.
* > 1 if the item should be located at a higher index than the provided item.
* > 0 if the item is the item you're looking for.
*
* @return {T | null} The object if it is found or null otherwise.
*/
search: function search(list, comparisonFn) {
var minIndex = 0;
var maxIndex = list.length - 1;
var currentIndex = null;
var currentElement = null;
while (minIndex <= maxIndex) {
currentIndex = (minIndex + maxIndex) / 2 | 0;
currentElement = list[currentIndex];
var comparisonResult = comparisonFn(currentElement);
if (comparisonResult > 0) {
minIndex = currentIndex + 1;
} else if (comparisonResult < 0) {
maxIndex = currentIndex - 1;
} else {
return currentElement;
}
}
return null;
}
};
/* harmony default export */ var binary_search = (BinarySearch);
// CONCATENATED MODULE: ./src/utils/buffer-helper.ts
/**
* @module BufferHelper
*
* Providing methods dealing with buffer length retrieval for example.
*
* In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
*
* Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
*/
var noopBuffered = {
length: 0,
start: function start() {
return 0;
},
end: function end() {
return 0;
}
};
var buffer_helper_BufferHelper = /*#__PURE__*/function () {
function BufferHelper() {}
/**
* Return true if `media`'s buffered include `position`
* @param {Bufferable} media
* @param {number} position
* @returns {boolean}
*/
BufferHelper.isBuffered = function isBuffered(media, position) {
try {
if (media) {
var buffered = BufferHelper.getBuffered(media);
for (var i = 0; i < buffered.length; i++) {
if (position >= buffered.start(i) && position <= buffered.end(i)) {
return true;
}
}
}
} catch (error) {// this is to catch
// InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
// This SourceBuffer has been removed from the parent media source
}
return false;
};
BufferHelper.bufferInfo = function bufferInfo(media, pos, maxHoleDuration) {
try {
if (media) {
var vbuffered = BufferHelper.getBuffered(media);
var buffered = [];
var i;
for (i = 0; i < vbuffered.length; i++) {
buffered.push({
start: vbuffered.start(i),
end: vbuffered.end(i)
});
}
return this.bufferedInfo(buffered, pos, maxHoleDuration);
}
} catch (error) {// this is to catch
// InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
// This SourceBuffer has been removed from the parent media source
}
return {
len: 0,
start: pos,
end: pos,
nextStart: undefined
};
};
BufferHelper.bufferedInfo = function bufferedInfo(buffered, pos, maxHoleDuration) {
// sort on buffer.start/smaller end (IE does not always return sorted buffered range)
buffered.sort(function (a, b) {
var diff = a.start - b.start;
if (diff) {
return diff;
} else {
return b.end - a.end;
}
});
var buffered2 = [];
if (maxHoleDuration) {
// there might be some small holes between buffer time range
// consider that holes smaller than maxHoleDuration are irrelevant and build another
// buffer time range representations that discards those holes
for (var i = 0; i < buffered.length; i++) {
var buf2len = buffered2.length;
if (buf2len) {
var buf2end = buffered2[buf2len - 1].end; // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
if (buffered[i].start - buf2end < maxHoleDuration) {
// merge overlapping time ranges
// update lastRange.end only if smaller than item.end
// e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
// whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
if (buffered[i].end > buf2end) {
buffered2[buf2len - 1].end = buffered[i].end;
}
} else {
// big hole
buffered2.push(buffered[i]);
}
} else {
// first value
buffered2.push(buffered[i]);
}
}
} else {
buffered2 = buffered;
}
var bufferLen = 0; // bufferStartNext can possibly be undefined based on the conditional logic below
var bufferStartNext; // bufferStart and bufferEnd are buffer boundaries around current video position
var bufferStart = pos;
var bufferEnd = pos;
for (var _i = 0; _i < buffered2.length; _i++) {
var start = buffered2[_i].start,
end = buffered2[_i].end; // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
if (pos + maxHoleDuration >= start && pos < end) {
// play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
bufferStart = start;
bufferEnd = end;
bufferLen = bufferEnd - pos;
} else if (pos + maxHoleDuration < start) {
bufferStartNext = start;
break;
}
}
return {
len: bufferLen,
start: bufferStart,
end: bufferEnd,
nextStart: bufferStartNext
};
}
/**
* Safe method to get buffered property.
* SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource
*/
;
BufferHelper.getBuffered = function getBuffered(media) {
try {
return media.buffered;
} catch (e) {
logger["logger"].log('failed to get media.buffered', e);
return noopBuffered;
}
};
return BufferHelper;
}();
// EXTERNAL MODULE: ./node_modules/eventemitter3/index.js
var eventemitter3 = __webpack_require__("./node_modules/eventemitter3/index.js");
// EXTERNAL MODULE: ./node_modules/webworkify-webpack/index.js
var webworkify_webpack = __webpack_require__("./node_modules/webworkify-webpack/index.js");
// EXTERNAL MODULE: ./src/demux/demuxer-inline.js + 16 modules
var demuxer_inline = __webpack_require__("./src/demux/demuxer-inline.js");
// CONCATENATED MODULE: ./src/utils/mediasource-helper.ts
/**
* MediaSource helper
*/
function getMediaSource() {
return window.MediaSource || window.WebKitMediaSource;
}
// EXTERNAL MODULE: ./src/utils/get-self-scope.js
var get_self_scope = __webpack_require__("./src/utils/get-self-scope.js");
// CONCATENATED MODULE: ./src/observer.ts
function observer_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* Simple adapter sub-class of Nodejs-like EventEmitter.
*/
var Observer = /*#__PURE__*/function (_EventEmitter) {
observer_inheritsLoose(Observer, _EventEmitter);
function Observer() {
return _EventEmitter.apply(this, arguments) || this;
}
var _proto = Observer.prototype;
/**
* We simply want to pass along the event-name itself
* in every call to a handler, which is the purpose of our `trigger` method
* extending the standard API.
*/
_proto.trigger = function trigger(event) {
for (var _len = arguments.length, data = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
data[_key - 1] = arguments[_key];
}
this.emit.apply(this, [event, event].concat(data));
};
return Observer;
}(eventemitter3["EventEmitter"]);
// CONCATENATED MODULE: ./src/demux/demuxer.js
// see https://stackoverflow.com/a/11237259/589493
var global = Object(get_self_scope["getSelfScope"])(); // safeguard for code that might run both on worker and main thread
var demuxer_MediaSource = getMediaSource() || {
isTypeSupported: function isTypeSupported() {
return false;
}
};
var demuxer_Demuxer = /*#__PURE__*/function () {
function Demuxer(hls, id) {
var _this = this;
this.hls = hls;
this.id = id;
var observer = this.observer = new Observer();
var config = hls.config;
var forwardMessage = function forwardMessage(ev, data) {
data = data || {};
data.frag = _this.frag;
data.id = _this.id;
hls.trigger(ev, data);
}; // forward events to main thread
observer.on(events["default"].FRAG_DECRYPTED, forwardMessage);
observer.on(events["default"].FRAG_PARSING_INIT_SEGMENT, forwardMessage);
observer.on(events["default"].FRAG_PARSING_DATA, forwardMessage);
observer.on(events["default"].FRAG_PARSED, forwardMessage);
observer.on(events["default"].ERROR, forwardMessage);
observer.on(events["default"].FRAG_PARSING_METADATA, forwardMessage);
observer.on(events["default"].FRAG_PARSING_USERDATA, forwardMessage);
observer.on(events["default"].INIT_PTS_FOUND, forwardMessage);
var typeSupported = {
mp4: demuxer_MediaSource.isTypeSupported('video/mp4'),
mpeg: demuxer_MediaSource.isTypeSupported('audio/mpeg'),
mp3: demuxer_MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
}; // navigator.vendor is not always available in Web Worker
// refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
var vendor = navigator.vendor;
if (config.enableWorker && typeof Worker !== 'undefined') {
logger["logger"].log('demuxing in webworker');
var w;
try {
w = this.w = webworkify_webpack(/*require.resolve*/(/*! ../demux/demuxer-worker.js */ "./src/demux/demuxer-worker.js"));
this.onwmsg = this.onWorkerMessage.bind(this);
w.addEventListener('message', this.onwmsg);
w.onerror = function (event) {
hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].OTHER_ERROR,
details: errors["ErrorDetails"].INTERNAL_EXCEPTION,
fatal: true,
event: 'demuxerWorker',
err: {
message: event.message + ' (' + event.filename + ':' + event.lineno + ')'
}
});
};
w.postMessage({
cmd: 'init',
typeSupported: typeSupported,
vendor: vendor,
id: id,
config: JSON.stringify(config)
});
} catch (err) {
logger["logger"].warn('Error in worker:', err);
logger["logger"].error('Error while initializing DemuxerWorker, fallback on DemuxerInline');
if (w) {
// revoke the Object URL that was used to create demuxer worker, so as not to leak it
global.URL.revokeObjectURL(w.objectURL);
}
this.demuxer = new demuxer_inline["default"](observer, typeSupported, config, vendor);
this.w = undefined;
}
} else {
this.demuxer = new demuxer_inline["default"](observer, typeSupported, config, vendor);
}
}
var _proto = Demuxer.prototype;
_proto.destroy = function destroy() {
var w = this.w;
if (w) {
w.removeEventListener('message', this.onwmsg);
w.terminate();
this.w = null;
} else {
var demuxer = this.demuxer;
if (demuxer) {
demuxer.destroy();
this.demuxer = null;
}
}
var observer = this.observer;
if (observer) {
observer.removeAllListeners();
this.observer = null;
}
};
_proto.push = function push(data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {
var w = this.w;
var timeOffset = Object(number["isFiniteNumber"])(frag.startPTS) ? frag.startPTS : frag.start;
var decryptdata = frag.decryptdata;
var lastFrag = this.frag;
var discontinuity = !(lastFrag && frag.cc === lastFrag.cc);
var trackSwitch = !(lastFrag && frag.level === lastFrag.level);
var nextSN = lastFrag && frag.sn === lastFrag.sn + 1;
var contiguous = !trackSwitch && nextSN;
if (discontinuity) {
logger["logger"].log(this.id + ":discontinuity detected");
}
if (trackSwitch) {
logger["logger"].log(this.id + ":switch detected");
}
this.frag = frag;
if (w) {
// post fragment payload as transferable objects for ArrayBuffer (no copy)
w.postMessage({
cmd: 'demux',
data: data,
decryptdata: decryptdata,
initSegment: initSegment,
audioCodec: audioCodec,
videoCodec: videoCodec,
timeOffset: timeOffset,
discontinuity: discontinuity,
trackSwitch: trackSwitch,
contiguous: contiguous,
duration: duration,
accurateTimeOffset: accurateTimeOffset,
defaultInitPTS: defaultInitPTS
}, data instanceof ArrayBuffer ? [data] : []);
} else {
var demuxer = this.demuxer;
if (demuxer) {
demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
}
}
};
_proto.onWorkerMessage = function onWorkerMessage(ev) {
var data = ev.data,
hls = this.hls;
switch (data.event) {
case 'init':
// revoke the Object URL that was used to create demuxer worker, so as not to leak it
global.URL.revokeObjectURL(this.w.objectURL);
break;
// special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects
case events["default"].FRAG_PARSING_DATA:
data.data.data1 = new Uint8Array(data.data1);
if (data.data2) {
data.data.data2 = new Uint8Array(data.data2);
}
/* falls through */
default:
data.data = data.data || {};
data.data.frag = this.frag;
data.data.id = this.id;
hls.trigger(data.event, data.data);
break;
}
};
return Demuxer;
}();
/* harmony default export */ var demux_demuxer = (demuxer_Demuxer);
// CONCATENATED MODULE: ./src/controller/level-helper.js
/**
* @module LevelHelper
*
* Providing methods dealing with playlist sliding and drift
*
* TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.
*
* */
function addGroupId(level, type, id) {
switch (type) {
case 'audio':
if (!level.audioGroupIds) {
level.audioGroupIds = [];
}
level.audioGroupIds.push(id);
break;
case 'text':
if (!level.textGroupIds) {
level.textGroupIds = [];
}
level.textGroupIds.push(id);
break;
}
}
function updatePTS(fragments, fromIdx, toIdx) {
var fragFrom = fragments[fromIdx],
fragTo = fragments[toIdx],
fragToPTS = fragTo.startPTS; // if we know startPTS[toIdx]
if (Object(number["isFiniteNumber"])(fragToPTS)) {
// update fragment duration.
// it helps to fix drifts between playlist reported duration and fragment real duration
if (toIdx > fromIdx) {
fragFrom.duration = fragToPTS - fragFrom.start;
if (fragFrom.duration < 0) {
logger["logger"].warn("negative duration computed for frag " + fragFrom.sn + ",level " + fragFrom.level + ", there should be some duration drift between playlist and fragment!");
}
} else {
fragTo.duration = fragFrom.start - fragToPTS;
if (fragTo.duration < 0) {
logger["logger"].warn("negative duration computed for frag " + fragTo.sn + ",level " + fragTo.level + ", there should be some duration drift between playlist and fragment!");
}
}
} else {
// we dont know startPTS[toIdx]
if (toIdx > fromIdx) {
var contiguous = fragFrom.cc === fragTo.cc;
fragTo.start = fragFrom.start + (contiguous && fragFrom.minEndPTS ? fragFrom.minEndPTS - fragFrom.start : fragFrom.duration);
} else {
fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
}
}
}
function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
// update frag PTS/DTS
var maxStartPTS = startPTS;
var minEndPTS = endPTS;
if (Object(number["isFiniteNumber"])(frag.startPTS)) {
// delta PTS between audio and video
var deltaPTS = Math.abs(frag.startPTS - startPTS);
if (!Object(number["isFiniteNumber"])(frag.deltaPTS)) {
frag.deltaPTS = deltaPTS;
} else {
frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
}
maxStartPTS = Math.max(startPTS, frag.startPTS);
startPTS = Math.min(startPTS, frag.startPTS);
minEndPTS = Math.min(endPTS, frag.endPTS);
endPTS = Math.max(endPTS, frag.endPTS);
startDTS = Math.min(startDTS, frag.startDTS);
endDTS = Math.max(endDTS, frag.endDTS);
}
var drift = startPTS - frag.start;
frag.start = frag.startPTS = startPTS;
frag.maxStartPTS = maxStartPTS;
frag.endPTS = endPTS;
frag.minEndPTS = minEndPTS;
frag.startDTS = startDTS;
frag.endDTS = endDTS;
frag.duration = endPTS - startPTS;
var sn = frag.sn; // exit if sn out of range
if (!details || sn < details.startSN || sn > details.endSN) {
return 0;
}
var fragIdx, fragments, i;
fragIdx = sn - details.startSN;
fragments = details.fragments; // update frag reference in fragments array
// rationale is that fragments array might not contain this frag object.
// this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
// if we don't update frag, we won't be able to propagate PTS info on the playlist
// resulting in invalid sliding computation
fragments[fragIdx] = frag; // adjust fragment PTS/duration from seqnum-1 to frag 0
for (i = fragIdx; i > 0; i--) {
updatePTS(fragments, i, i - 1);
} // adjust fragment PTS/duration from seqnum to last frag
for (i = fragIdx; i < fragments.length - 1; i++) {
updatePTS(fragments, i, i + 1);
}
details.PTSKnown = true;
return drift;
}
function mergeDetails(oldDetails, newDetails) {
// potentially retrieve cached initsegment
if (newDetails.initSegment && oldDetails.initSegment) {
newDetails.initSegment = oldDetails.initSegment;
} // check if old/new playlists have fragments in common
// loop through overlapping SN and update startPTS , cc, and duration if any found
var ccOffset = 0;
var PTSFrag;
mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
ccOffset = oldFrag.cc - newFrag.cc;
if (Object(number["isFiniteNumber"])(oldFrag.startPTS)) {
newFrag.start = newFrag.startPTS = oldFrag.startPTS;
newFrag.endPTS = oldFrag.endPTS;
newFrag.duration = oldFrag.duration;
newFrag.backtracked = oldFrag.backtracked;
newFrag.dropped = oldFrag.dropped;
PTSFrag = newFrag;
} // PTS is known when there are overlapping segments
newDetails.PTSKnown = true;
});
if (!newDetails.PTSKnown) {
return;
}
if (ccOffset) {
logger["logger"].log('discontinuity sliding from playlist, take drift into account');
var newFragments = newDetails.fragments;
for (var i = 0; i < newFragments.length; i++) {
newFragments[i].cc += ccOffset;
}
} // if at least one fragment contains PTS info, recompute PTS information for all fragments
if (PTSFrag) {
updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
} else {
// ensure that delta is within oldFragments range
// also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
// in that case we also need to adjust start offset of all fragments
adjustSliding(oldDetails, newDetails);
} // if we are here, it means we have fragments overlapping between
// old and new level. reliable PTS info is thus relying on old level
newDetails.PTSKnown = oldDetails.PTSKnown;
}
function mergeSubtitlePlaylists(oldPlaylist, newPlaylist, referenceStart) {
if (referenceStart === void 0) {
referenceStart = 0;
}
var lastIndex = -1;
mapFragmentIntersection(oldPlaylist, newPlaylist, function (oldFrag, newFrag, index) {
newFrag.start = oldFrag.start;
lastIndex = index;
});
var frags = newPlaylist.fragments;
if (lastIndex < 0) {
frags.forEach(function (frag) {
frag.start += referenceStart;
});
return;
}
for (var i = lastIndex + 1; i < frags.length; i++) {
frags[i].start = frags[i - 1].start + frags[i - 1].duration;
}
}
function mapFragmentIntersection(oldPlaylist, newPlaylist, intersectionFn) {
if (!oldPlaylist || !newPlaylist) {
return;
}
var start = Math.max(oldPlaylist.startSN, newPlaylist.startSN) - newPlaylist.startSN;
var end = Math.min(oldPlaylist.endSN, newPlaylist.endSN) - newPlaylist.startSN;
var delta = newPlaylist.startSN - oldPlaylist.startSN;
for (var i = start; i <= end; i++) {
var oldFrag = oldPlaylist.fragments[delta + i];
var newFrag = newPlaylist.fragments[i];
if (!oldFrag || !newFrag) {
break;
}
intersectionFn(oldFrag, newFrag, i);
}
}
function adjustSliding(oldPlaylist, newPlaylist) {
var delta = newPlaylist.startSN - oldPlaylist.startSN;
var oldFragments = oldPlaylist.fragments;
var newFragments = newPlaylist.fragments;
if (delta < 0 || delta > oldFragments.length) {
return;
}
for (var i = 0; i < newFragments.length; i++) {
newFragments[i].start += oldFragments[delta].start;
}
}
function computeReloadInterval(currentPlaylist, newPlaylist, lastRequestTime) {
var reloadInterval = 1000 * (newPlaylist.averagetargetduration ? newPlaylist.averagetargetduration : newPlaylist.targetduration);
var minReloadInterval = reloadInterval / 2;
if (currentPlaylist && newPlaylist.endSN === currentPlaylist.endSN) {
// follow HLS Spec, If the client reloads a Playlist file and finds that it has not
// changed then it MUST wait for a period of one-half the target
// duration before retrying.
reloadInterval = minReloadInterval;
}
if (lastRequestTime) {
reloadInterval = Math.max(minReloadInterval, reloadInterval - (window.performance.now() - lastRequestTime));
} // in any case, don't reload more than half of target duration
return Math.round(reloadInterval);
}
// CONCATENATED MODULE: ./src/utils/time-ranges.ts
/**
* TimeRanges to string helper
*/
var TimeRanges = {
toString: function toString(r) {
var log = '';
var len = r.length;
for (var i = 0; i < len; i++) {
log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
}
return log;
}
};
/* harmony default export */ var time_ranges = (TimeRanges);
// CONCATENATED MODULE: ./src/utils/discontinuities.js
function findFirstFragWithCC(fragments, cc) {
var firstFrag = null;
for (var i = 0; i < fragments.length; i += 1) {
var currentFrag = fragments[i];
if (currentFrag && currentFrag.cc === cc) {
firstFrag = currentFrag;
break;
}
}
return firstFrag;
}
function findFragWithCC(fragments, CC) {
return binary_search.search(fragments, function (candidate) {
if (candidate.cc < CC) {
return 1;
} else if (candidate.cc > CC) {
return -1;
} else {
return 0;
}
});
}
function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
var shouldAlign = false;
if (lastLevel && lastLevel.details && details) {
if (details.endCC > details.startCC || lastFrag && lastFrag.cc < details.startCC) {
shouldAlign = true;
}
}
return shouldAlign;
} // Find the first frag in the previous level which matches the CC of the first frag of the new level
function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
var prevFrags = prevDetails.fragments;
var curFrags = curDetails.fragments;
if (!curFrags.length || !prevFrags.length) {
logger["logger"].log('No fragments to align');
return;
}
var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
if (!prevStartFrag || prevStartFrag && !prevStartFrag.startPTS) {
logger["logger"].log('No frag in previous level to align on');
return;
}
return prevStartFrag;
}
function adjustPts(sliding, details) {
details.fragments.forEach(function (frag) {
if (frag) {
var start = frag.start + sliding;
frag.start = frag.startPTS = start;
frag.endPTS = start + frag.duration;
}
});
details.PTSKnown = true;
}
/**
* Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
* contiguous stream with the last fragments.
* The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
* download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
* and an extra download.
* @param lastFrag
* @param lastLevel
* @param details
*/
function alignStream(lastFrag, lastLevel, details) {
alignDiscontinuities(lastFrag, details, lastLevel);
if (!details.PTSKnown && lastLevel) {
// If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
// Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
// discontinuity sequence.
alignPDT(details, lastLevel.details);
}
}
/**
* Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
* discontinuity sequence.
* @param lastLevel - The details of the last loaded level
* @param details - The details of the new level
*/
function alignDiscontinuities(lastFrag, details, lastLevel) {
if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
if (referenceFrag) {
logger["logger"].log('Adjusting PTS using last level due to CC increase within current level');
adjustPts(referenceFrag.start, details);
}
}
}
/**
* Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
* @param details - The details of the new level
* @param lastDetails - The details of the last loaded level
*/
function alignPDT(details, lastDetails) {
if (lastDetails && lastDetails.fragments.length) {
if (!details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
return;
} // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
// and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
// then we can deduce that playlist B sliding is 1000+8 = 1008s
var lastPDT = lastDetails.fragments[0].programDateTime;
var newPDT = details.fragments[0].programDateTime; // date diff is in ms. frag.start is in seconds
var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
if (Object(number["isFiniteNumber"])(sliding)) {
logger["logger"].log("adjusting PTS using programDateTime delta, sliding:" + sliding.toFixed(3));
adjustPts(sliding, details);
}
}
}
// CONCATENATED MODULE: ./src/controller/fragment-finders.ts
/**
* The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
* @param {*} candidate - The fragment to test
* @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
* @returns {number} - 0 if it matches, 1 if too low, -1 if too high
*/
function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
if (bufferEnd === void 0) {
bufferEnd = 0;
}
if (maxFragLookUpTolerance === void 0) {
maxFragLookUpTolerance = 0;
}
// offset should be within fragment boundary - config.maxFragLookUpTolerance
// this is to cope with situations like
// bufferEnd = 9.991
// frag[Ø] : [0,10]
// frag[1] : [10,20]
// bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
// frag start frag start+duration
// |-----------------------------|
// <---> <--->
// ...--------><-----------------------------><---------....
// previous frag matching fragment next frag
// return -1 return 0 return 1
// logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
// Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
return 1;
} else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
// if maxFragLookUpTolerance will have negative value then don't return -1 for first element
return -1;
}
return 0;
}
/**
* The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
* This function tests the candidate's program date time values, as represented in Unix time
* @param {*} candidate - The fragment to test
* @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
* @returns {boolean} True if contiguous, false otherwise
*/
function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000; // endProgramDateTime can be null, default to zero
var endProgramDateTime = candidate.endProgramDateTime || 0;
return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
}
/**
* Returns first fragment whose endPdt value exceeds the given PDT.
* @param {Array<Fragment>} fragments - The array of candidate fragments
* @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
* @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
* @returns {*|null} fragment - The best matching fragment
*/
function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Object(number["isFiniteNumber"])(PDTValue)) {
return null;
} // if less than start
var startPDT = fragments[0].programDateTime;
if (PDTValue < (startPDT || 0)) {
return null;
}
var endPDT = fragments[fragments.length - 1].endProgramDateTime;
if (PDTValue >= (endPDT || 0)) {
return null;
}
maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
for (var seg = 0; seg < fragments.length; ++seg) {
var frag = fragments[seg];
if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
return frag;
}
}
return null;
}
/**
* Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
* This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
* breaking any traps which would cause the same fragment to be continuously selected within a small range.
* @param {*} fragPrevious - The last frag successfully appended
* @param {Array<Fragment>} fragments - The array of candidate fragments
* @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
* @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
* @returns {*} foundFrag - The best matching fragment
*/
function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) {
if (bufferEnd === void 0) {
bufferEnd = 0;
}
if (maxFragLookUpTolerance === void 0) {
maxFragLookUpTolerance = 0;
}
var fragNext = null;
if (fragPrevious) {
fragNext = fragments[fragPrevious.sn - fragments[0].sn + 1];
} else if (bufferEnd === 0 && fragments[0].start === 0) {
fragNext = fragments[0];
} // Prefer the next fragment if it's within tolerance
if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {
return fragNext;
} // We might be seeking past the tolerance so find the best match
var foundFragment = binary_search.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
if (foundFragment) {
return foundFragment;
} // If no match was found return the next fragment after fragPrevious, or null
return fragNext;
}
// CONCATENATED MODULE: ./src/controller/gap-controller.js
var STALL_MINIMUM_DURATION_MS = 250;
var MAX_START_GAP_JUMP = 2.0;
var SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;
var SKIP_BUFFER_RANGE_START = 0.05;
var gap_controller_GapController = /*#__PURE__*/function () {
function GapController(config, media, fragmentTracker, hls) {
this.config = config;
this.media = media;
this.fragmentTracker = fragmentTracker;
this.hls = hls;
this.nudgeRetry = 0;
this.stallReported = false;
this.stalled = null;
this.moved = false;
this.seeking = false;
}
/**
* Checks if the playhead is stuck within a gap, and if so, attempts to free it.
* A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
*
* @param {number} lastCurrentTime Previously read playhead position
*/
var _proto = GapController.prototype;
_proto.poll = function poll(lastCurrentTime) {
var config = this.config,
media = this.media,
stalled = this.stalled;
var currentTime = media.currentTime,
seeking = media.seeking;
var seeked = this.seeking && !seeking;
var beginSeek = !this.seeking && seeking;
this.seeking = seeking; // The playhead is moving, no-op
if (currentTime !== lastCurrentTime) {
this.moved = true;
if (stalled !== null) {
// The playhead is now moving, but was previously stalled
if (this.stallReported) {
var _stalledDuration = self.performance.now() - stalled;
logger["logger"].warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(_stalledDuration) + "ms");
this.stallReported = false;
}
this.stalled = null;
this.nudgeRetry = 0;
}
return;
} // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek
if (beginSeek || seeked) {
this.stalled = null;
} // The playhead should not be moving
if (media.paused || media.ended || media.playbackRate === 0 || !buffer_helper_BufferHelper.getBuffered(media).length) {
return;
}
var bufferInfo = buffer_helper_BufferHelper.bufferInfo(media, currentTime, 0);
var isBuffered = bufferInfo.len > 0;
var nextStart = bufferInfo.nextStart || 0; // There is no playable buffer (waiting for buffer append)
if (!isBuffered && !nextStart) {
return;
}
if (seeking) {
// Waiting for seeking in a buffered range to complete
var hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP; // Next buffered range is too far ahead to jump to while still seeking
var noBufferGap = !nextStart || nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime);
if (hasEnoughBuffer || noBufferGap) {
return;
} // Reset moved state when seeking to a point in or before a gap
this.moved = false;
} // Skip start gaps if we haven't played, but the last poll detected the start of a stall
// The addition poll gives the browser a chance to jump the gap for us
if (!this.moved && this.stalled) {
var _level$details;
// Jump start gaps within jump threshold
var startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime; // When joining a live stream with audio tracks, account for live playlist window sliding by allowing
// a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment
// that begins over 1 target duration after the video start position.
var level = this.hls.levels ? this.hls.levels[this.hls.currentLevel] : null;
var isLive = level === null || level === void 0 ? void 0 : (_level$details = level.details) === null || _level$details === void 0 ? void 0 : _level$details.live;
var maxStartGapJump = isLive ? level.details.targetduration * 2 : MAX_START_GAP_JUMP;
if (startJump > 0 && startJump <= maxStartGapJump) {
this._trySkipBufferHole(null);
return;
}
} // Start tracking stall time
var tnow = self.performance.now();
if (stalled === null) {
this.stalled = tnow;
return;
}
var stalledDuration = tnow - stalled;
if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {
// Report stalling after trying to fix
this._reportStall(bufferInfo.len);
}
var bufferedWithHoles = buffer_helper_BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
this._tryFixBufferStall(bufferedWithHoles, stalledDuration);
}
/**
* Detects and attempts to fix known buffer stalling issues.
* @param bufferInfo - The properties of the current buffer.
* @param stalledDurationMs - The amount of time Hls.js has been stalling for.
* @private
*/
;
_proto._tryFixBufferStall = function _tryFixBufferStall(bufferInfo, stalledDurationMs) {
var config = this.config,
fragmentTracker = this.fragmentTracker,
media = this.media;
var currentTime = media.currentTime;
var partial = fragmentTracker.getPartialFragment(currentTime);
if (partial) {
// Try to skip over the buffer hole caused by a partial fragment
// This method isn't limited by the size of the gap between buffered ranges
var targetTime = this._trySkipBufferHole(partial); // we return here in this case, meaning
// the branch below only executes when we don't handle a partial fragment
if (targetTime) {
return;
}
} // if we haven't had to skip over a buffer hole of a partial fragment
// we may just have to "nudge" the playlist as the browser decoding/rendering engine
// needs to cross some sort of threshold covering all source-buffers content
// to start playing properly.
if (bufferInfo.len > config.maxBufferHole && stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {
logger["logger"].warn('Trying to nudge playhead over buffer-hole'); // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
// We only try to jump the hole if it's under the configured size
// Reset stalled so to rearm watchdog timer
this.stalled = null;
this._tryNudgeBuffer();
}
}
/**
* Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
* @param bufferLen - The playhead distance from the end of the current buffer segment.
* @private
*/
;
_proto._reportStall = function _reportStall(bufferLen) {
var hls = this.hls,
media = this.media,
stallReported = this.stallReported;
if (!stallReported) {
// Report stalled error once
this.stallReported = true;
logger["logger"].warn("Playback stalling at @" + media.currentTime + " due to low buffer (buffer=" + bufferLen + ")");
hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].BUFFER_STALLED_ERROR,
fatal: false,
buffer: bufferLen
});
}
}
/**
* Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
* @param partial - The partial fragment found at the current time (where playback is stalling).
* @private
*/
;
_proto._trySkipBufferHole = function _trySkipBufferHole(partial) {
var config = this.config,
hls = this.hls,
media = this.media;
var currentTime = media.currentTime;
var lastEndTime = 0; // Check if currentTime is between unbuffered regions of partial fragments
var buffered = buffer_helper_BufferHelper.getBuffered(media);
for (var i = 0; i < buffered.length; i++) {
var startTime = buffered.start(i);
if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {
var targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);
logger["logger"].warn("skipping hole, adjusting currentTime from " + currentTime + " to " + targetTime);
this.moved = true;
this.stalled = null;
media.currentTime = targetTime;
if (partial) {
hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].BUFFER_SEEK_OVER_HOLE,
fatal: false,
reason: "fragment loaded with buffer holes, seeking from " + currentTime + " to " + targetTime,
frag: partial
});
}
return targetTime;
}
lastEndTime = buffered.end(i);
}
return 0;
}
/**
* Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
* @private
*/
;
_proto._tryNudgeBuffer = function _tryNudgeBuffer() {
var config = this.config,
hls = this.hls,
media = this.media;
var currentTime = media.currentTime;
var nudgeRetry = (this.nudgeRetry || 0) + 1;
this.nudgeRetry = nudgeRetry;
if (nudgeRetry < config.nudgeMaxRetry) {
var targetTime = currentTime + nudgeRetry * config.nudgeOffset; // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
logger["logger"].warn("Nudging 'currentTime' from " + currentTime + " to " + targetTime);
media.currentTime = targetTime;
hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].BUFFER_NUDGE_ON_STALL,
fatal: false
});
} else {
logger["logger"].error("Playhead still not moving while enough data buffered @" + currentTime + " after " + config.nudgeMaxRetry + " nudges");
hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].BUFFER_STALLED_ERROR,
fatal: true
});
}
};
return GapController;
}();
// CONCATENATED MODULE: ./src/task-loop.ts
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function task_loop_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* Sub-class specialization of EventHandler base class.
*
* TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
* scheduled asynchroneously, avoiding recursive calls in the same tick.
*
* The task itself is implemented in `doTick`. It can be requested and called for single execution
* using the `tick` method.
*
* It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
* no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
*
* If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
* and cancelled with `clearNextTick`.
*
* The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
*
* Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
*
* Further explanations:
*
* The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
* only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
*
* When the task execution (`tick` method) is called in re-entrant way this is detected and
* we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
* task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
*/
var TaskLoop = /*#__PURE__*/function (_EventHandler) {
task_loop_inheritsLoose(TaskLoop, _EventHandler);
function TaskLoop(hls) {
var _this;
for (var _len = arguments.length, events = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
events[_key - 1] = arguments[_key];
}
_this = _EventHandler.call.apply(_EventHandler, [this, hls].concat(events)) || this;
_this._boundTick = void 0;
_this._tickTimer = null;
_this._tickInterval = null;
_this._tickCallCount = 0;
_this._boundTick = _this.tick.bind(_assertThisInitialized(_this));
return _this;
}
/**
* @override
*/
var _proto = TaskLoop.prototype;
_proto.onHandlerDestroying = function onHandlerDestroying() {
// clear all timers before unregistering from event bus
this.clearNextTick();
this.clearInterval();
}
/**
* @returns {boolean}
*/
;
_proto.hasInterval = function hasInterval() {
return !!this._tickInterval;
}
/**
* @returns {boolean}
*/
;
_proto.hasNextTick = function hasNextTick() {
return !!this._tickTimer;
}
/**
* @param {number} millis Interval time (ms)
* @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
*/
;
_proto.setInterval = function setInterval(millis) {
if (!this._tickInterval) {
this._tickInterval = self.setInterval(this._boundTick, millis);
return true;
}
return false;
}
/**
* @returns {boolean} True when interval was cleared, false when none was set (no effect)
*/
;
_proto.clearInterval = function clearInterval() {
if (this._tickInterval) {
self.clearInterval(this._tickInterval);
this._tickInterval = null;
return true;
}
return false;
}
/**
* @returns {boolean} True when timeout was cleared, false when none was set (no effect)
*/
;
_proto.clearNextTick = function clearNextTick() {
if (this._tickTimer) {
self.clearTimeout(this._tickTimer);
this._tickTimer = null;
return true;
}
return false;
}
/**
* Will call the subclass doTick implementation in this main loop tick
* or in the next one (via setTimeout(,0)) in case it has already been called
* in this tick (in case this is a re-entrant call).
*/
;
_proto.tick = function tick() {
this._tickCallCount++;
if (this._tickCallCount === 1) {
this.doTick(); // re-entrant call to tick from previous doTick call stack
// -> schedule a call on the next main loop iteration to process this task processing request
if (this._tickCallCount > 1) {
// make sure only one timer exists at any time at max
this.clearNextTick();
this._tickTimer = self.setTimeout(this._boundTick, 0);
}
this._tickCallCount = 0;
}
}
/**
* For subclass to implement task logic
* @abstract
*/
;
_proto.doTick = function doTick() {};
return TaskLoop;
}(event_handler);
// CONCATENATED MODULE: ./src/controller/base-stream-controller.js
function base_stream_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var State = {
STOPPED: 'STOPPED',
STARTING: 'STARTING',
IDLE: 'IDLE',
PAUSED: 'PAUSED',
KEY_LOADING: 'KEY_LOADING',
FRAG_LOADING: 'FRAG_LOADING',
FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
WAITING_TRACK: 'WAITING_TRACK',
PARSING: 'PARSING',
PARSED: 'PARSED',
BUFFER_FLUSHING: 'BUFFER_FLUSHING',
ENDED: 'ENDED',
ERROR: 'ERROR',
WAITING_INIT_PTS: 'WAITING_INIT_PTS',
WAITING_LEVEL: 'WAITING_LEVEL'
};
var base_stream_controller_BaseStreamController = /*#__PURE__*/function (_TaskLoop) {
base_stream_controller_inheritsLoose(BaseStreamController, _TaskLoop);
function BaseStreamController() {
return _TaskLoop.apply(this, arguments) || this;
}
var _proto = BaseStreamController.prototype;
_proto.doTick = function doTick() {};
_proto.startLoad = function startLoad() {};
_proto.stopLoad = function stopLoad() {
var frag = this.fragCurrent;
if (frag) {
if (frag.loader) {
frag.loader.abort();
}
this.fragmentTracker.removeFragment(frag);
}
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = null;
}
this.fragCurrent = null;
this.fragPrevious = null;
this.clearInterval();
this.clearNextTick();
this.state = State.STOPPED;
};
_proto._streamEnded = function _streamEnded(bufferInfo, levelDetails) {
var fragCurrent = this.fragCurrent,
fragmentTracker = this.fragmentTracker; // we just got done loading the final fragment and there is no other buffered range after ...
// rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
// so we should not switch to ENDED in that case, to be able to buffer them
// dont switch to ENDED if we need to backtrack last fragment
if (!levelDetails.live && fragCurrent && !fragCurrent.backtracked && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {
var fragState = fragmentTracker.getState(fragCurrent);
return fragState === FragmentState.PARTIAL || fragState === FragmentState.OK;
}
return false;
};
_proto.onMediaSeeking = function onMediaSeeking() {
var config = this.config,
media = this.media,
mediaBuffer = this.mediaBuffer,
state = this.state;
var currentTime = media ? media.currentTime : null;
var bufferInfo = buffer_helper_BufferHelper.bufferInfo(mediaBuffer || media, currentTime, this.config.maxBufferHole);
logger["logger"].log("media seeking to " + (Object(number["isFiniteNumber"])(currentTime) ? currentTime.toFixed(3) : currentTime));
if (state === State.FRAG_LOADING) {
var fragCurrent = this.fragCurrent; // check if we are seeking to a unbuffered area AND if frag loading is in progress
if (bufferInfo.len === 0 && fragCurrent) {
var tolerance = config.maxFragLookUpTolerance;
var fragStartOffset = fragCurrent.start - tolerance;
var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance; // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
if (fragCurrent.loader) {
logger["logger"].log('seeking outside of buffer while fragment load in progress, cancel fragment load');
fragCurrent.loader.abort();
}
this.fragCurrent = null;
this.fragPrevious = null; // switch to IDLE state to load new fragment
this.state = State.IDLE;
} else {
logger["logger"].log('seeking outside of buffer but within currently loaded fragment range');
}
}
} else if (state === State.ENDED) {
// if seeking to unbuffered area, clean up fragPrevious
if (bufferInfo.len === 0) {
this.fragPrevious = null;
this.fragCurrent = null;
} // switch to IDLE state to check for potential new fragment
this.state = State.IDLE;
}
if (media) {
this.lastCurrentTime = currentTime;
} // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
if (!this.loadedmetadata) {
this.nextLoadPosition = this.startPosition = currentTime;
} // tick to speed up processing
this.tick();
};
_proto.onMediaEnded = function onMediaEnded() {
// reset startPosition and lastCurrentTime to restart playback @ stream beginning
this.startPosition = this.lastCurrentTime = 0;
};
_proto.onHandlerDestroying = function onHandlerDestroying() {
this.stopLoad();
_TaskLoop.prototype.onHandlerDestroying.call(this);
};
_proto.onHandlerDestroyed = function onHandlerDestroyed() {
this.state = State.STOPPED;
this.fragmentTracker = null;
};
_proto.computeLivePosition = function computeLivePosition(sliding, levelDetails) {
var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;
return sliding + Math.max(0, levelDetails.totalduration - targetLatency);
};
return BaseStreamController;
}(TaskLoop);
// CONCATENATED MODULE: ./src/controller/stream-controller.js
function stream_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function stream_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) stream_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) stream_controller_defineProperties(Constructor, staticProps); return Constructor; }
function stream_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/*
* Stream Controller
*/
var TICK_INTERVAL = 100; // how often to tick in ms
var stream_controller_StreamController = /*#__PURE__*/function (_BaseStreamController) {
stream_controller_inheritsLoose(StreamController, _BaseStreamController);
function StreamController(hls, fragmentTracker) {
var _this;
_this = _BaseStreamController.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHING, events["default"].MANIFEST_LOADING, events["default"].MANIFEST_PARSED, events["default"].LEVEL_LOADED, events["default"].LEVELS_UPDATED, events["default"].KEY_LOADED, events["default"].FRAG_LOADED, events["default"].FRAG_LOAD_EMERGENCY_ABORTED, events["default"].FRAG_PARSING_INIT_SEGMENT, events["default"].FRAG_PARSING_DATA, events["default"].FRAG_PARSED, events["default"].ERROR, events["default"].AUDIO_TRACK_SWITCHING, events["default"].AUDIO_TRACK_SWITCHED, events["default"].BUFFER_CREATED, events["default"].BUFFER_APPENDED, events["default"].BUFFER_FLUSHED) || this;
_this.fragmentTracker = fragmentTracker;
_this.config = hls.config;
_this.audioCodecSwap = false;
_this._state = State.STOPPED;
_this.stallReported = false;
_this.gapController = null;
_this.altAudio = false;
_this.audioOnly = false;
_this.bitrateTest = false;
return _this;
}
var _proto = StreamController.prototype;
_proto.startLoad = function startLoad(startPosition) {
if (this.levels) {
var lastCurrentTime = this.lastCurrentTime,
hls = this.hls;
this.stopLoad();
this.setInterval(TICK_INTERVAL);
this.level = -1;
this.fragLoadError = 0;
if (!this.startFragRequested) {
// determine load level
var startLevel = hls.startLevel;
if (startLevel === -1) {
if (hls.config.testBandwidth) {
// -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
startLevel = 0;
this.bitrateTest = true;
} else {
startLevel = hls.nextAutoLevel;
}
} // set new level to playlist loader : this will trigger start level load
// hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
this.level = hls.nextLoadLevel = startLevel;
this.loadedmetadata = false;
} // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
if (lastCurrentTime > 0 && startPosition === -1) {
logger["logger"].log("override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
startPosition = lastCurrentTime;
}
this.state = State.IDLE;
this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
this.tick();
} else {
this.forceStartLoad = true;
this.state = State.STOPPED;
}
};
_proto.stopLoad = function stopLoad() {
this.forceStartLoad = false;
_BaseStreamController.prototype.stopLoad.call(this);
};
_proto.doTick = function doTick() {
var _this$levels$this$lev;
switch (this.state) {
case State.BUFFER_FLUSHING:
// in buffer flushing state, reset fragLoadError counter
this.fragLoadError = 0;
break;
case State.IDLE:
this._doTickIdle();
break;
case State.WAITING_LEVEL:
var details = (_this$levels$this$lev = this.levels[this.level]) === null || _this$levels$this$lev === void 0 ? void 0 : _this$levels$this$lev.details; // check if playlist is already loaded (must be current level for live)
if (details && (!details.live || this.levelLastLoaded === this.level)) {
this.state = State.IDLE;
}
break;
case State.FRAG_LOADING_WAITING_RETRY:
var now = window.performance.now();
var retryDate = this.retryDate; // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
if (!retryDate || now >= retryDate || this.media && this.media.seeking) {
logger["logger"].log('mediaController: retryDate reached, switch back to IDLE state');
this.state = State.IDLE;
}
break;
case State.ERROR:
case State.STOPPED:
case State.FRAG_LOADING:
case State.PARSING:
case State.PARSED:
case State.ENDED:
break;
default:
break;
} // check buffer
this._checkBuffer(); // check/update current fragment
this._checkFragmentChanged();
} // Ironically the "idle" state is the on we do the most logic in it seems ....
// NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
// played segment, or on pause/play/seek instead of naively checking every 100ms?
;
_proto._doTickIdle = function _doTickIdle() {
var hls = this.hls,
config = hls.config,
media = this.media; // if start level not parsed yet OR
// if video not attached AND start fragment already requested OR start frag prefetch disable
// exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
if (this.levelLastLoaded === undefined || !media && (this.startFragRequested || !config.startFragPrefetch)) {
return;
} // If the "main" level is audio-only but we are loading an alternate track in the same group, do not load anything
if (this.altAudio && this.audioOnly) {
// Clear audio demuxer state so when switching back to main audio we're not still appending where we left off
this.demuxer.frag = null;
return;
} // if we have not yet loaded any fragment, start loading from start position
var pos;
if (this.loadedmetadata) {
pos = media.currentTime;
} else {
pos = this.nextLoadPosition;
} // determine next load level
var level = hls.nextLoadLevel,
levelInfo = this.levels[level];
if (!levelInfo) {
return;
}
var levelBitrate = levelInfo.bitrate,
maxBufLen; // compute max Buffer Length that we could get from this load level, based on level bitrate.
if (levelBitrate) {
maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
} else {
maxBufLen = config.maxBufferLength;
}
maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength); // determine next candidate fragment to be loaded, based on current position and end of buffer position
// ensure up to `config.maxMaxBufferLength` of buffer upfront
var maxBufferHole = pos < config.maxBufferHole ? Math.max(MAX_START_GAP_JUMP, config.maxBufferHole) : config.maxBufferHole;
var bufferInfo = buffer_helper_BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, maxBufferHole);
var bufferLen = bufferInfo.len; // Stay idle if we are still with buffer margins
if (bufferLen >= maxBufLen) {
return;
} // if buffer length is less than maxBufLen try to load a new fragment ...
logger["logger"].trace("buffer length of " + bufferLen.toFixed(3) + " is below max of " + maxBufLen.toFixed(3) + ". checking for more payload ..."); // set next load level : this will trigger a playlist load if needed
this.level = hls.nextLoadLevel = level;
var levelDetails = levelInfo.details; // if level info not retrieved yet, switch state and wait for level retrieval
// if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
// a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
if (!levelDetails || levelDetails.live && this.levelLastLoaded !== level) {
this.state = State.WAITING_LEVEL;
return;
}
if (this._streamEnded(bufferInfo, levelDetails)) {
var data = {};
if (this.altAudio) {
data.type = 'video';
}
this.hls.trigger(events["default"].BUFFER_EOS, data);
this.state = State.ENDED;
return;
} // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);
};
_proto._fetchPayloadOrEos = function _fetchPayloadOrEos(pos, bufferInfo, levelDetails) {
var fragPrevious = this.fragPrevious,
fragments = levelDetails.fragments,
fragLen = fragments.length; // empty playlist
if (fragLen === 0) {
return;
} // find fragment index, contiguous with end of buffer position
var start = fragments[0].start,
end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,
bufferEnd = bufferInfo.end,
frag;
if (levelDetails.initSegment && !levelDetails.initSegment.data) {
frag = levelDetails.initSegment;
} else {
// in case of live playlist we need to ensure that requested position is not located before playlist start
if (levelDetails.live) {
var initialLiveManifestSize = this.config.initialLiveManifestSize;
if (fragLen < initialLiveManifestSize) {
logger["logger"].warn("Can not start playback of a level, reason: not enough fragments " + fragLen + " < " + initialLiveManifestSize);
return;
}
frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments); // if it explicitely returns null don't load any fragment and exit function now
if (frag === null) {
return;
}
} else {
// VoD playlist: if bufferEnd before start of playlist, load first fragment
if (bufferEnd < start) {
frag = fragments[0];
}
}
}
if (!frag) {
frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);
}
if (frag) {
if (frag.encrypted) {
this._loadKey(frag, levelDetails);
} else {
this._loadFragment(frag, levelDetails, pos, bufferEnd);
}
}
};
_proto._ensureFragmentAtLivePoint = function _ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments) {
var config = this.hls.config,
media = this.media;
var frag; // check if requested position is within seekable boundaries :
// logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
var maxLatency = Infinity;
if (config.liveMaxLatencyDuration !== undefined) {
maxLatency = config.liveMaxLatencyDuration;
} else if (Object(number["isFiniteNumber"])(config.liveMaxLatencyDurationCount)) {
maxLatency = config.liveMaxLatencyDurationCount * levelDetails.targetduration;
}
if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);
bufferEnd = liveSyncPosition;
if (media && !media.paused && media.readyState && media.duration > liveSyncPosition && liveSyncPosition > media.currentTime) {
logger["logger"].warn("buffer end: " + bufferEnd.toFixed(3) + " is located too far from the end of live sliding playlist, reset currentTime to : " + liveSyncPosition.toFixed(3));
media.currentTime = liveSyncPosition;
}
this.nextLoadPosition = liveSyncPosition;
} // if end of buffer greater than live edge, don't load any fragment
// this could happen if live playlist intermittently slides in the past.
// level 1 loaded [182580161,182580167]
// level 1 loaded [182580162,182580169]
// Loading 182580168 of [182580162 ,182580169],level 1 ..
// Loading 182580169 of [182580162 ,182580169],level 1 ..
// level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
// level 1 loaded [182580164,182580171]
//
// don't return null in case media not loaded yet (readystate === 0)
if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
return null;
}
if (this.startFragRequested && !levelDetails.PTSKnown) {
/* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
try to load frag matching with next SN.
even if SN are not synchronized between playlists, loading this frag will help us
compute playlist sliding and find the right one after in case it was not the right consecutive one */
if (fragPrevious) {
if (levelDetails.hasProgramDateTime) {
// Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)
logger["logger"].log("live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, config.maxFragLookUpTolerance);
} else {
// Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
var targetSN = fragPrevious.sn + 1;
if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
var fragNext = fragments[targetSN - levelDetails.startSN];
if (fragPrevious.cc === fragNext.cc) {
frag = fragNext;
logger["logger"].log("live playlist, switching playlist, load frag with next SN: " + frag.sn);
}
} // next frag SN not available (or not with same continuity counter)
// look for a frag sharing the same CC
if (!frag) {
frag = binary_search.search(fragments, function (frag) {
return fragPrevious.cc - frag.cc;
});
if (frag) {
logger["logger"].log("live playlist, switching playlist, load frag with same CC: " + frag.sn);
}
}
}
}
}
return frag;
};
_proto._findFragment = function _findFragment(start, fragPreviousLoad, fragmentIndexRange, fragments, bufferEnd, end, levelDetails) {
var config = this.hls.config;
var fragNextLoad;
if (bufferEnd < end) {
var lookupTolerance = bufferEnd > end - config.maxFragLookUpTolerance ? 0 : config.maxFragLookUpTolerance; // Remove the tolerance if it would put the bufferEnd past the actual end of stream
// Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
fragNextLoad = findFragmentByPTS(fragPreviousLoad, fragments, bufferEnd, lookupTolerance);
} else {
// reach end of playlist
fragNextLoad = fragments[fragmentIndexRange - 1];
}
if (fragNextLoad) {
var curSNIdx = fragNextLoad.sn - levelDetails.startSN;
var sameLevel = fragPreviousLoad && fragNextLoad.level === fragPreviousLoad.level;
var prevSnFrag = fragments[curSNIdx - 1];
var nextSnFrag = fragments[curSNIdx + 1]; // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
if (fragPreviousLoad && fragNextLoad.sn === fragPreviousLoad.sn) {
if (sameLevel && !fragNextLoad.backtracked) {
if (fragNextLoad.sn < levelDetails.endSN) {
var deltaPTS = fragPreviousLoad.deltaPTS; // if there is a significant delta between audio and video, larger than max allowed hole,
// and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
// let's try to load previous fragment again to get last keyframe
// then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
if (deltaPTS && deltaPTS > config.maxBufferHole && fragPreviousLoad.dropped && curSNIdx) {
fragNextLoad = prevSnFrag;
logger["logger"].warn('Previous fragment was dropped with large PTS gap between audio and video. Maybe fragment is not starting with a keyframe? Loading previous one to try to overcome this');
} else {
fragNextLoad = nextSnFrag;
if (this.fragmentTracker.getState(fragNextLoad) !== FragmentState.OK) {
logger["logger"].log("Re-loading fragment with SN: " + fragNextLoad.sn);
}
}
} else {
fragNextLoad = null;
}
} else if (fragNextLoad.backtracked) {
// Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes
if (nextSnFrag && nextSnFrag.backtracked) {
logger["logger"].warn("Already backtracked from fragment " + nextSnFrag.sn + ", will not backtrack to fragment " + fragNextLoad.sn + ". Loading fragment " + nextSnFrag.sn);
fragNextLoad = nextSnFrag;
} else {
// If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe
// Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment
logger["logger"].warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');
fragNextLoad.dropped = 0;
if (prevSnFrag) {
fragNextLoad = prevSnFrag;
fragNextLoad.backtracked = true;
} else if (curSNIdx) {
// can't backtrack on very first fragment
fragNextLoad = null;
}
}
}
}
}
return fragNextLoad;
};
_proto._loadKey = function _loadKey(frag, levelDetails) {
logger["logger"].log("Loading key for " + frag.sn + " of [" + levelDetails.startSN + "-" + levelDetails.endSN + "], level " + this.level);
this.state = State.KEY_LOADING;
this.hls.trigger(events["default"].KEY_LOADING, {
frag: frag
});
};
_proto._loadFragment = function _loadFragment(frag, levelDetails, pos, bufferEnd) {
// Check if fragment is not loaded
var fragState = this.fragmentTracker.getState(frag);
this.fragCurrent = frag;
if (frag.sn !== 'initSegment') {
this.startFragRequested = true;
} // Don't update nextLoadPosition for fragments which are not buffered
if (Object(number["isFiniteNumber"])(frag.sn) && !frag.bitrateTest) {
this.nextLoadPosition = frag.start + frag.duration;
} // Allow backtracked fragments to load
if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {
frag.autoLevel = this.hls.autoLevelEnabled;
frag.bitrateTest = this.bitrateTest;
logger["logger"].log("Loading " + frag.sn + " of [" + levelDetails.startSN + "-" + levelDetails.endSN + "], level " + this.level + ", " + (this.loadedmetadata ? 'currentTime' : 'nextLoadPosition') + ": " + parseFloat(pos.toFixed(3)) + ", bufferEnd: " + parseFloat(bufferEnd.toFixed(3)));
this.hls.trigger(events["default"].FRAG_LOADING, {
frag: frag
}); // lazy demuxer init, as this could take some time ... do it during frag loading
if (!this.demuxer) {
this.demuxer = new demux_demuxer(this.hls, 'main');
}
this.state = State.FRAG_LOADING;
} else if (fragState === FragmentState.APPENDING) {
// Lower the buffer size and try again
if (this._reduceMaxBufferLength(frag.duration)) {
this.fragmentTracker.removeFragment(frag);
}
}
};
_proto.getBufferedFrag = function getBufferedFrag(position) {
return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);
};
_proto.followingBufferedFrag = function followingBufferedFrag(frag) {
if (frag) {
// try to get range of next fragment (500ms after this range)
return this.getBufferedFrag(frag.endPTS + 0.5);
}
return null;
};
_proto._checkFragmentChanged = function _checkFragmentChanged() {
var fragPlayingCurrent,
currentTime,
video = this.media;
if (video && video.readyState && video.seeking === false) {
currentTime = video.currentTime;
/* if video element is in seeked state, currentTime can only increase.
(assuming that playback rate is positive ...)
As sometimes currentTime jumps back to zero after a
media decode error, check this, to avoid seeking back to
wrong position after a media decode error
*/
if (currentTime > this.lastCurrentTime) {
this.lastCurrentTime = currentTime;
}
if (buffer_helper_BufferHelper.isBuffered(video, currentTime)) {
fragPlayingCurrent = this.getBufferedFrag(currentTime);
} else if (buffer_helper_BufferHelper.isBuffered(video, currentTime + 0.1)) {
/* ensure that FRAG_CHANGED event is triggered at startup,
when first video frame is displayed and playback is paused.
add a tolerance of 100ms, in case current position is not buffered,
check if current pos+100ms is buffered and use that buffer range
for FRAG_CHANGED event reporting */
fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);
}
if (fragPlayingCurrent) {
var fragPlaying = fragPlayingCurrent;
if (fragPlaying !== this.fragPlaying) {
this.hls.trigger(events["default"].FRAG_CHANGED, {
frag: fragPlaying
});
var fragPlayingLevel = fragPlaying.level;
if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {
this.hls.trigger(events["default"].LEVEL_SWITCHED, {
level: fragPlayingLevel
});
}
this.fragPlaying = fragPlaying;
}
}
}
}
/*
on immediate level switch :
- pause playback if playing
- cancel any pending load request
- and trigger a buffer flush
*/
;
_proto.immediateLevelSwitch = function immediateLevelSwitch() {
logger["logger"].log('immediateLevelSwitch');
if (!this.immediateSwitch) {
this.immediateSwitch = true;
var media = this.media,
previouslyPaused;
if (media) {
previouslyPaused = media.paused;
if (!previouslyPaused) {
media.pause();
}
} else {
// don't restart playback after instant level switch in case media not attached
previouslyPaused = true;
}
this.previouslyPaused = previouslyPaused;
}
var fragCurrent = this.fragCurrent;
if (fragCurrent && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null; // flush everything
this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
}
/**
* on immediate level switch end, after new fragment has been buffered:
* - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)
* - resume the playback if needed
*/
;
_proto.immediateLevelSwitchEnd = function immediateLevelSwitchEnd() {
var media = this.media;
if (media && buffer_helper_BufferHelper.getBuffered(media).length) {
this.immediateSwitch = false;
if (media.currentTime > 0 && buffer_helper_BufferHelper.isBuffered(media, media.currentTime)) {
// only nudge if currentTime is buffered
media.currentTime -= 0.0001;
}
if (!this.previouslyPaused) {
media.play();
}
}
}
/**
* try to switch ASAP without breaking video playback:
* in order to ensure smooth but quick level switching,
* we need to find the next flushable buffer range
* we should take into account new segment fetch time
*/
;
_proto.nextLevelSwitch = function nextLevelSwitch() {
var media = this.media; // ensure that media is defined and that metadata are available (to retrieve currentTime)
if (media && media.readyState) {
var fetchdelay;
var fragPlayingCurrent = this.getBufferedFrag(media.currentTime);
if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {
// flush buffer preceding current fragment (flush until current fragment start offset)
// minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);
}
if (!media.paused) {
// add a safety delay of 1s
var nextLevelId = this.hls.nextLoadLevel,
nextLevel = this.levels[nextLevelId],
fragLastKbps = this.fragLastKbps;
if (fragLastKbps && this.fragCurrent) {
fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
} else {
fetchdelay = 0;
}
} else {
fetchdelay = 0;
} // logger.log('fetchdelay:'+fetchdelay);
// find buffer range that will be reached once new fragment will be fetched
var bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
if (bufferedFrag) {
// we can flush buffer range following this one without stalling playback
var nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);
if (nextBufferedFrag) {
// if we are here, we can also cancel any loading/demuxing in progress, as they are useless
var fragCurrent = this.fragCurrent;
if (fragCurrent && fragCurrent.loader) {
fragCurrent.loader.abort();
}
this.fragCurrent = null; // start flush position is the start PTS of next buffered frag.
// we use frag.naxStartPTS which is max(audio startPTS, video startPTS).
// in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment
var startPts = Math.max(bufferedFrag.endPTS, nextBufferedFrag.maxStartPTS + Math.min(this.config.maxFragLookUpTolerance, nextBufferedFrag.duration));
this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);
}
}
}
};
_proto.flushMainBuffer = function flushMainBuffer(startOffset, endOffset) {
this.state = State.BUFFER_FLUSHING;
var flushScope = {
startOffset: startOffset,
endOffset: endOffset
}; // if alternate audio tracks are used, only flush video, otherwise flush everything
if (this.altAudio) {
flushScope.type = 'video';
}
this.hls.trigger(events["default"].BUFFER_FLUSHING, flushScope);
};
_proto.onMediaAttached = function onMediaAttached(data) {
var media = this.media = this.mediaBuffer = data.media;
this.onvseeking = this.onMediaSeeking.bind(this);
this.onvseeked = this.onMediaSeeked.bind(this);
this.onvended = this.onMediaEnded.bind(this);
media.addEventListener('seeking', this.onvseeking);
media.addEventListener('seeked', this.onvseeked);
media.addEventListener('ended', this.onvended);
var config = this.config;
if (this.levels && config.autoStartLoad) {
this.hls.startLoad(config.startPosition);
}
this.gapController = new gap_controller_GapController(config, media, this.fragmentTracker, this.hls);
};
_proto.onMediaDetaching = function onMediaDetaching() {
var media = this.media;
if (media && media.ended) {
logger["logger"].log('MSE detaching and video ended, reset startPosition');
this.startPosition = this.lastCurrentTime = 0;
} // reset fragment backtracked flag
var levels = this.levels;
if (levels) {
levels.forEach(function (level) {
if (level.details) {
level.details.fragments.forEach(function (fragment) {
fragment.backtracked = undefined;
});
}
});
} // remove video listeners
if (media) {
media.removeEventListener('seeking', this.onvseeking);
media.removeEventListener('seeked', this.onvseeked);
media.removeEventListener('ended', this.onvended);
this.onvseeking = this.onvseeked = this.onvended = null;
}
this.fragmentTracker.removeAllFragments();
this.media = this.mediaBuffer = null;
this.loadedmetadata = false;
this.stopLoad();
};
_proto.onMediaSeeked = function onMediaSeeked() {
var media = this.media;
var currentTime = media ? media.currentTime : undefined;
if (Object(number["isFiniteNumber"])(currentTime)) {
logger["logger"].log("media seeked to " + currentTime.toFixed(3));
} // tick to speed up FRAGMENT_PLAYING triggering
this.tick();
};
_proto.onManifestLoading = function onManifestLoading() {
// reset buffer on manifest loading
logger["logger"].log('trigger BUFFER_RESET');
this.hls.trigger(events["default"].BUFFER_RESET);
this.fragmentTracker.removeAllFragments();
this.stalled = false;
this.startPosition = this.lastCurrentTime = 0;
};
_proto.onManifestParsed = function onManifestParsed(data) {
var aac = false,
heaac = false,
codec;
data.levels.forEach(function (level) {
// detect if we have different kind of audio codecs used amongst playlists
codec = level.audioCodec;
if (codec) {
if (codec.indexOf('mp4a.40.2') !== -1) {
aac = true;
}
if (codec.indexOf('mp4a.40.5') !== -1) {
heaac = true;
}
}
});
this.audioCodecSwitch = aac && heaac;
if (this.audioCodecSwitch) {
logger["logger"].log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
}
this.altAudio = data.altAudio;
this.levels = data.levels;
this.startFragRequested = false;
var config = this.config;
if (config.autoStartLoad || this.forceStartLoad) {
this.hls.startLoad(config.startPosition);
}
};
_proto.onLevelLoaded = function onLevelLoaded(data) {
var newDetails = data.details;
var newLevelId = data.level;
var lastLevel = this.levels[this.levelLastLoaded];
var curLevel = this.levels[newLevelId];
var duration = newDetails.totalduration;
var sliding = 0;
logger["logger"].log("level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "],duration:" + duration);
if (newDetails.live || curLevel.details && curLevel.details.live) {
var curDetails = curLevel.details;
if (curDetails && newDetails.fragments.length > 0) {
// we already have details for that level, merge them
mergeDetails(curDetails, newDetails);
sliding = newDetails.fragments[0].start;
this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
if (newDetails.PTSKnown && Object(number["isFiniteNumber"])(sliding)) {
logger["logger"].log("live playlist sliding:" + sliding.toFixed(3));
} else if (!sliding) {
logger["logger"].log('live playlist - outdated PTS, unknown sliding');
alignStream(this.fragPrevious, lastLevel, newDetails);
}
} else {
logger["logger"].log('live playlist - first load, unknown sliding');
newDetails.PTSKnown = false;
alignStream(this.fragPrevious, lastLevel, newDetails);
}
} else {
newDetails.PTSKnown = false;
} // override level info
curLevel.details = newDetails;
this.levelLastLoaded = newLevelId;
this.hls.trigger(events["default"].LEVEL_UPDATED, {
details: newDetails,
level: newLevelId
});
if (this.startFragRequested === false) {
// compute start position if set to -1. use it straight away if value is defined
if (this.startPosition === -1 || this.lastCurrentTime === -1) {
// first, check if start time offset has been set in playlist, if yes, use this value
var startTimeOffset = newDetails.startTimeOffset;
if (Object(number["isFiniteNumber"])(startTimeOffset)) {
if (startTimeOffset < 0) {
logger["logger"].log("negative start time offset " + startTimeOffset + ", count from end of last fragment");
startTimeOffset = sliding + duration + startTimeOffset;
}
logger["logger"].log("start time offset found in playlist, adjust startPosition to " + startTimeOffset);
this.startPosition = startTimeOffset;
} else {
// if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
if (newDetails.live) {
this.startPosition = this.computeLivePosition(sliding, newDetails);
logger["logger"].log("configure startPosition to " + this.startPosition);
} else {
this.startPosition = 0;
}
}
this.lastCurrentTime = this.startPosition;
}
this.nextLoadPosition = this.startPosition;
} // only switch back to IDLE state if we were waiting for level to start downloading a new fragment
if (this.state === State.WAITING_LEVEL) {
this.state = State.IDLE;
} // trigger handler right now
this.tick();
};
_proto.onKeyLoaded = function onKeyLoaded() {
if (this.state === State.KEY_LOADING) {
this.state = State.IDLE;
this.tick();
}
};
_proto.onFragLoaded = function onFragLoaded(data) {
var fragCurrent = this.fragCurrent,
hls = this.hls,
levels = this.levels,
media = this.media;
var fragLoaded = data.frag;
if (this.state === State.FRAG_LOADING && fragCurrent && fragLoaded.type === 'main' && fragLoaded.level === fragCurrent.level && fragLoaded.sn === fragCurrent.sn) {
var stats = data.stats;
var currentLevel = levels[fragCurrent.level];
var details = currentLevel.details; // reset frag bitrate test in any case after frag loaded event
// if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0
// then this means that we should be able to load a fragment at a higher quality level
this.bitrateTest = false;
this.stats = stats;
logger["logger"].log("Loaded " + fragCurrent.sn + " of [" + details.startSN + " ," + details.endSN + "],level " + fragCurrent.level);
if (fragLoaded.bitrateTest && hls.nextLoadLevel) {
// switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
this.state = State.IDLE;
this.startFragRequested = false;
stats.tparsed = stats.tbuffered = window.performance.now();
hls.trigger(events["default"].FRAG_BUFFERED, {
stats: stats,
frag: fragCurrent,
id: 'main'
});
this.tick();
} else if (fragLoaded.sn === 'initSegment') {
this.state = State.IDLE;
stats.tparsed = stats.tbuffered = window.performance.now();
details.initSegment.data = data.payload;
hls.trigger(events["default"].FRAG_BUFFERED, {
stats: stats,
frag: fragCurrent,
id: 'main'
});
this.tick();
} else {
logger["logger"].log("Parsing " + fragCurrent.sn + " of [" + details.startSN + " ," + details.endSN + "],level " + fragCurrent.level + ", cc " + fragCurrent.cc);
this.state = State.PARSING;
this.pendingBuffering = true;
this.appended = false; // Bitrate test frags are not usually buffered so the fragment tracker ignores them. If Hls.js decides to buffer
// it (and therefore ends up at this line), then the fragment tracker needs to be manually informed.
if (fragLoaded.bitrateTest) {
fragLoaded.bitrateTest = false;
this.fragmentTracker.onFragLoaded({
frag: fragLoaded
});
} // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments)
var accurateTimeOffset = !(media && media.seeking) && (details.PTSKnown || !details.live);
var initSegmentData = details.initSegment ? details.initSegment.data : [];
var audioCodec = this._getAudioCodec(currentLevel); // transmux the MPEG-TS data to ISO-BMFF segments
var demuxer = this.demuxer = this.demuxer || new demux_demuxer(this.hls, 'main');
demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, details.totalduration, accurateTimeOffset);
}
}
this.fragLoadError = 0;
};
_proto.onFragParsingInitSegment = function onFragParsingInitSegment(data) {
var fragCurrent = this.fragCurrent;
var fragNew = data.frag;
if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
var tracks = data.tracks,
trackName,
track;
this.audioOnly = tracks.audio && !tracks.video; // if audio track is expected to come from audio stream controller, discard any coming from main
if (this.altAudio && !this.audioOnly) {
delete tracks.audio;
} // include levelCodec in audio and video tracks
track = tracks.audio;
if (track) {
var audioCodec = this.levels[this.level].audioCodec,
ua = navigator.userAgent.toLowerCase();
if (audioCodec && this.audioCodecSwap) {
logger["logger"].log('swapping playlist audio codec');
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
} // in case AAC and HE-AAC audio codecs are signalled in manifest
// force HE-AAC , as it seems that most browsers prefers that way,
// except for mono streams OR on FF
// these conditions might need to be reviewed ...
if (this.audioCodecSwitch) {
// don't force HE-AAC if mono stream
if (track.metadata.channelCount !== 1 && // don't force HE-AAC if firefox
ua.indexOf('firefox') === -1) {
audioCodec = 'mp4a.40.5';
}
} // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') {
// Exclude mpeg audio
audioCodec = 'mp4a.40.2';
logger["logger"].log("Android: force audio codec to " + audioCodec);
}
track.levelCodec = audioCodec;
track.id = data.id;
}
track = tracks.video;
if (track) {
track.levelCodec = this.levels[this.level].videoCodec;
track.id = data.id;
}
this.hls.trigger(events["default"].BUFFER_CODECS, tracks); // loop through tracks that are going to be provided to bufferController
for (trackName in tracks) {
track = tracks[trackName];
logger["logger"].log("main track:" + trackName + ",container:" + track.container + ",codecs[level/parsed]=[" + track.levelCodec + "/" + track.codec + "]");
var initSegment = track.initSegment;
if (initSegment) {
this.appended = true; // arm pending Buffering flag before appending a segment
this.pendingBuffering = true;
this.hls.trigger(events["default"].BUFFER_APPENDING, {
type: trackName,
data: initSegment,
parent: 'main',
content: 'initSegment'
});
}
} // trigger handler right now
this.tick();
}
};
_proto.onFragParsingData = function onFragParsingData(data) {
var _this2 = this;
var fragCurrent = this.fragCurrent;
var fragNew = data.frag;
if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller
this.state === State.PARSING) {
var level = this.levels[this.level],
frag = fragCurrent;
if (!Object(number["isFiniteNumber"])(data.endPTS)) {
data.endPTS = data.startPTS + fragCurrent.duration;
data.endDTS = data.startDTS + fragCurrent.duration;
}
if (data.hasAudio === true) {
frag.addElementaryStream(ElementaryStreamTypes.AUDIO);
}
if (data.hasVideo === true) {
frag.addElementaryStream(ElementaryStreamTypes.VIDEO);
}
logger["logger"].log("Parsed " + data.type + ",PTS:[" + data.startPTS.toFixed(3) + "," + data.endPTS.toFixed(3) + "],DTS:[" + data.startDTS.toFixed(3) + "/" + data.endDTS.toFixed(3) + "],nb:" + data.nb + ",dropped:" + (data.dropped || 0)); // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)
if (data.type === 'video') {
frag.dropped = data.dropped;
if (frag.dropped) {
if (!frag.backtracked) {
var levelDetails = level.details;
if (levelDetails && frag.sn === levelDetails.startSN) {
logger["logger"].warn('missing video frame(s) on first frag, appending with gap', frag.sn);
} else {
logger["logger"].warn('missing video frame(s), backtracking fragment', frag.sn); // Return back to the IDLE state without appending to buffer
// Causes findFragments to backtrack a segment and find the keyframe
// Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment
this.fragmentTracker.removeFragment(frag);
frag.backtracked = true;
this.nextLoadPosition = data.startPTS;
this.state = State.IDLE;
this.fragPrevious = frag;
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = null;
}
this.tick();
return;
}
} else {
logger["logger"].warn('Already backtracked on this fragment, appending with the gap', frag.sn);
}
} else {
// Only reset the backtracked flag if we've loaded the frag without any dropped frames
frag.backtracked = false;
}
}
var drift = updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),
hls = this.hls;
hls.trigger(events["default"].LEVEL_PTS_UPDATED, {
details: level.details,
level: this.level,
drift: drift,
type: data.type,
start: data.startPTS,
end: data.endPTS
}); // has remuxer dropped video frames located before first keyframe ?
[data.data1, data.data2].forEach(function (buffer) {
// only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
// in that case it is useless to append following segments
if (buffer && buffer.length && _this2.state === State.PARSING) {
_this2.appended = true; // arm pending Buffering flag before appending a segment
_this2.pendingBuffering = true;
hls.trigger(events["default"].BUFFER_APPENDING, {
type: data.type,
data: buffer,
parent: 'main',
content: 'data'
});
}
}); // trigger handler right now
this.tick();
}
};
_proto.onFragParsed = function onFragParsed(data) {
var fragCurrent = this.fragCurrent;
var fragNew = data.frag;
if (fragCurrent && data.id === 'main' && fragNew.sn === fragCurrent.sn && fragNew.level === fragCurrent.level && this.state === State.PARSING) {
this.stats.tparsed = window.performance.now();
this.state = State.PARSED;
this._checkAppendedParsed();
}
};
_proto.onAudioTrackSwitching = function onAudioTrackSwitching(data) {
// if any URL found on new audio track, it is an alternate audio track
var fromAltAudio = this.altAudio;
var altAudio = !!data.url;
var trackId = data.id; // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
// don't do anything if we switch to alt audio: audio stream controller is handling it.
// we will just have to change buffer scheduling on audioTrackSwitched
if (!altAudio) {
if (this.mediaBuffer !== this.media) {
logger["logger"].log('switching on main audio, use media.buffered to schedule main fragment loading');
this.mediaBuffer = this.media;
var fragCurrent = this.fragCurrent; // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
if (fragCurrent.loader) {
logger["logger"].log('switching to main audio track, cancel main fragment load');
fragCurrent.loader.abort();
}
this.fragCurrent = null;
this.fragPrevious = null; // destroy demuxer to force init segment generation (following audio switch)
if (this.demuxer) {
this.demuxer.destroy();
this.demuxer = null;
} // switch to IDLE state to load new fragment
this.state = State.IDLE;
}
var hls = this.hls; // If switching from alt to main audio, flush all audio and trigger track switched
if (fromAltAudio) {
hls.trigger(events["default"].BUFFER_FLUSHING, {
startOffset: 0,
endOffset: Number.POSITIVE_INFINITY,
type: 'audio'
});
}
hls.trigger(events["default"].AUDIO_TRACK_SWITCHED, {
id: trackId
});
}
};
_proto.onAudioTrackSwitched = function onAudioTrackSwitched(data) {
var trackId = data.id,
altAudio = !!this.hls.audioTracks[trackId].url;
if (altAudio) {
var videoBuffer = this.videoBuffer; // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
if (videoBuffer && this.mediaBuffer !== videoBuffer) {
logger["logger"].log('switching on alternate audio, use video.buffered to schedule main fragment loading');
this.mediaBuffer = videoBuffer;
}
}
this.altAudio = altAudio;
this.tick();
};
_proto.onBufferCreated = function onBufferCreated(data) {
var tracks = data.tracks,
mediaTrack,
name,
alternate = false;
for (var type in tracks) {
var track = tracks[type];
if (track.id === 'main') {
name = type;
mediaTrack = track; // keep video source buffer reference
if (type === 'video') {
this.videoBuffer = tracks[type].buffer;
}
} else {
alternate = true;
}
}
if (alternate && mediaTrack) {
logger["logger"].log("alternate track found, use " + name + ".buffered to schedule main fragment loading");
this.mediaBuffer = mediaTrack.buffer;
} else {
this.mediaBuffer = this.media;
}
};
_proto.onBufferAppended = function onBufferAppended(data) {
if (data.parent === 'main') {
var state = this.state;
if (state === State.PARSING || state === State.PARSED) {
// check if all buffers have been appended
this.pendingBuffering = data.pending > 0;
this._checkAppendedParsed();
}
}
};
_proto._checkAppendedParsed = function _checkAppendedParsed() {
// trigger handler right now
if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {
var frag = this.fragCurrent;
if (frag) {
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
logger["logger"].log("main buffered : " + time_ranges.toString(buffer_helper_BufferHelper.getBuffered(media)));
this.fragPrevious = frag;
var stats = this.stats;
stats.tbuffered = window.performance.now(); // we should get rid of this.fragLastKbps
this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));
this.hls.trigger(events["default"].FRAG_BUFFERED, {
stats: stats,
frag: frag,
id: 'main'
});
this.state = State.IDLE;
} // Do not tick when _seekToStartPos needs to be called as seeking to the start can fail on live streams at this point
if (this.loadedmetadata || this.startPosition <= 0) {
this.tick();
}
}
};
_proto.onError = function onError(data) {
var frag = data.frag || this.fragCurrent; // don't handle frag error not related to main fragment
if (frag && frag.type !== 'main') {
return;
} // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
var mediaBuffered = !!this.media && buffer_helper_BufferHelper.isBuffered(this.media, this.media.currentTime) && buffer_helper_BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);
switch (data.details) {
case errors["ErrorDetails"].FRAG_LOAD_ERROR:
case errors["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case errors["ErrorDetails"].KEY_LOAD_ERROR:
case errors["ErrorDetails"].KEY_LOAD_TIMEOUT:
if (!data.fatal) {
// keep retrying until the limit will be reached
if (this.fragLoadError + 1 <= this.config.fragLoadingMaxRetry) {
// exponential backoff capped to config.fragLoadingMaxRetryTimeout
var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);
logger["logger"].warn("mediaController: frag loading failed, retry in " + delay + " ms");
this.retryDate = window.performance.now() + delay; // retry loading state
// if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
this.nextLoadPosition = this.startPosition;
}
this.fragLoadError++;
this.state = State.FRAG_LOADING_WAITING_RETRY;
} else {
logger["logger"].error("mediaController: " + data.details + " reaches max retry, redispatch as fatal ..."); // switch error to fatal
data.fatal = true;
this.state = State.ERROR;
}
}
break;
case errors["ErrorDetails"].LEVEL_LOAD_ERROR:
case errors["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
if (this.state !== State.ERROR) {
if (data.fatal) {
// if fatal error, stop processing
this.state = State.ERROR;
logger["logger"].warn("streamController: " + data.details + ",switch to " + this.state + " state ...");
} else {
// in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
if (!data.levelRetry && this.state === State.WAITING_LEVEL) {
this.state = State.IDLE;
}
}
}
break;
case errors["ErrorDetails"].BUFFER_FULL_ERROR:
// if in appending state
if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {
// reduce max buf len if current position is buffered
if (mediaBuffered) {
this._reduceMaxBufferLength(this.config.maxBufferLength);
this.state = State.IDLE;
} else {
// current position is not buffered, but browser is still complaining about buffer full error
// this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
// in that case flush the whole buffer to recover
logger["logger"].warn('buffer full error also media.currentTime is not buffered, flush everything');
this.fragCurrent = null; // flush everything
this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
}
}
break;
default:
break;
}
};
_proto._reduceMaxBufferLength = function _reduceMaxBufferLength(minLength) {
var config = this.config;
if (config.maxMaxBufferLength >= minLength) {
// reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
config.maxMaxBufferLength /= 2;
logger["logger"].warn("main:reduce max buffer length to " + config.maxMaxBufferLength + "s");
return true;
}
return false;
}
/**
* Checks the health of the buffer and attempts to resolve playback stalls.
* @private
*/
;
_proto._checkBuffer = function _checkBuffer() {
var media = this.media;
if (!media || media.readyState === 0) {
// Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)
return;
}
var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
var buffered = buffer_helper_BufferHelper.getBuffered(mediaBuffer);
if (!this.loadedmetadata && buffered.length) {
this.loadedmetadata = true;
this._seekToStartPos();
} else if (this.immediateSwitch) {
this.immediateLevelSwitchEnd();
} else {
this.gapController.poll(this.lastCurrentTime, buffered);
}
};
_proto.onFragLoadEmergencyAborted = function onFragLoadEmergencyAborted() {
this.state = State.IDLE; // if loadedmetadata is not set, it means that we are emergency switch down on first frag
// in that case, reset startFragRequested flag
if (!this.loadedmetadata) {
this.startFragRequested = false;
this.nextLoadPosition = this.startPosition;
}
this.tick();
};
_proto.onBufferFlushed = function onBufferFlushed() {
/* after successful buffer flushing, filter flushed fragments from bufferedFrags
use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)
*/
var media = this.mediaBuffer ? this.mediaBuffer : this.media;
if (media) {
// filter fragments potentially evicted from buffer. this is to avoid memleak on live streams
var elementaryStreamType = this.audioOnly ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;
this.fragmentTracker.detectEvictedFragments(elementaryStreamType, buffer_helper_BufferHelper.getBuffered(media));
} // reset reference to frag
this.fragPrevious = null; // move to IDLE once flush complete. this should trigger new fragment loading
this.state = State.IDLE;
};
_proto.onLevelsUpdated = function onLevelsUpdated(data) {
this.levels = data.levels;
};
_proto.swapAudioCodec = function swapAudioCodec() {
this.audioCodecSwap = !this.audioCodecSwap;
}
/**
* Seeks to the set startPosition if not equal to the mediaElement's current time.
* @private
*/
;
_proto._seekToStartPos = function _seekToStartPos() {
var media = this.media;
var currentTime = media.currentTime;
var startPosition = this.startPosition; // only adjust currentTime if different from startPosition or if startPosition not buffered
// at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
if (currentTime !== startPosition && startPosition >= 0) {
if (media.seeking) {
logger["logger"].log("could not seek to " + startPosition + ", already seeking at " + currentTime);
return;
}
var buffered = buffer_helper_BufferHelper.getBuffered(media);
var bufferStart = buffered.length ? buffered.start(0) : 0;
var delta = bufferStart - startPosition;
if (delta > 0 && delta < this.config.maxBufferHole) {
logger["logger"].log("adjusting start position by " + delta + " to match buffer start");
startPosition += delta;
this.startPosition = startPosition;
}
logger["logger"].log("seek to target start position " + startPosition + " from current time " + currentTime + ". ready state " + media.readyState);
media.currentTime = startPosition;
}
};
_proto._getAudioCodec = function _getAudioCodec(currentLevel) {
var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
if (this.audioCodecSwap) {
logger["logger"].log('swapping playlist audio codec');
if (audioCodec) {
if (audioCodec.indexOf('mp4a.40.5') !== -1) {
audioCodec = 'mp4a.40.2';
} else {
audioCodec = 'mp4a.40.5';
}
}
}
return audioCodec;
};
stream_controller_createClass(StreamController, [{
key: "state",
set: function set(nextState) {
if (this.state !== nextState) {
var previousState = this.state;
this._state = nextState;
logger["logger"].log("main stream-controller: " + previousState + "->" + nextState);
this.hls.trigger(events["default"].STREAM_STATE_TRANSITION, {
previousState: previousState,
nextState: nextState
});
}
},
get: function get() {
return this._state;
}
}, {
key: "currentLevel",
get: function get() {
var media = this.media;
if (media) {
var frag = this.getBufferedFrag(media.currentTime);
if (frag) {
return frag.level;
}
}
return -1;
}
}, {
key: "nextBufferedFrag",
get: function get() {
var media = this.media;
if (media) {
// first get end range of current fragment
return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));
} else {
return null;
}
}
}, {
key: "nextLevel",
get: function get() {
var frag = this.nextBufferedFrag;
if (frag) {
return frag.level;
} else {
return -1;
}
}
}, {
key: "liveSyncPosition",
get: function get() {
return this._liveSyncPosition;
},
set: function set(value) {
this._liveSyncPosition = value;
}
}]);
return StreamController;
}(base_stream_controller_BaseStreamController);
/* harmony default export */ var stream_controller = (stream_controller_StreamController);
// CONCATENATED MODULE: ./src/controller/level-controller.js
function level_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function level_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) level_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) level_controller_defineProperties(Constructor, staticProps); return Constructor; }
function level_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/*
* Level Controller
*/
var chromeOrFirefox;
var level_controller_LevelController = /*#__PURE__*/function (_EventHandler) {
level_controller_inheritsLoose(LevelController, _EventHandler);
function LevelController(hls) {
var _this;
_this = _EventHandler.call(this, hls, events["default"].MANIFEST_LOADED, events["default"].LEVEL_LOADED, events["default"].AUDIO_TRACK_SWITCHED, events["default"].FRAG_LOADED, events["default"].ERROR) || this;
_this.canload = false;
_this.currentLevelIndex = null;
_this.manualLevelIndex = -1;
_this.timer = null;
chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
return _this;
}
var _proto = LevelController.prototype;
_proto.onHandlerDestroying = function onHandlerDestroying() {
this.clearTimer();
this.manualLevelIndex = -1;
};
_proto.clearTimer = function clearTimer() {
if (this.timer !== null) {
clearTimeout(this.timer);
this.timer = null;
}
};
_proto.startLoad = function startLoad() {
var levels = this._levels;
this.canload = true;
this.levelRetryCount = 0; // clean up live level details to force reload them, and reset load errors
if (levels) {
levels.forEach(function (level) {
level.loadError = 0;
});
} // speed up live playlist refresh if timer exists
if (this.timer !== null) {
this.loadLevel();
}
};
_proto.stopLoad = function stopLoad() {
this.canload = false;
};
_proto.onManifestLoaded = function onManifestLoaded(data) {
var levels = [];
var audioTracks = [];
var bitrateStart;
var levelSet = {};
var levelFromSet = null;
var videoCodecFound = false;
var audioCodecFound = false; // regroup redundant levels together
data.levels.forEach(function (level) {
var attributes = level.attrs;
level.loadError = 0;
level.fragmentError = false;
videoCodecFound = videoCodecFound || !!level.videoCodec;
audioCodecFound = audioCodecFound || !!level.audioCodec; // erase audio codec info if browser does not support mp4a.40.34.
// demuxer will autodetect codec and fallback to mpeg/audio
if (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
level.audioCodec = undefined;
}
levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here
if (!levelFromSet) {
level.url = [level.url];
level.urlId = 0;
levelSet[level.bitrate] = level;
levels.push(level);
} else {
levelFromSet.url.push(level.url);
}
if (attributes) {
if (attributes.AUDIO) {
addGroupId(levelFromSet || level, 'audio', attributes.AUDIO);
}
if (attributes.SUBTITLES) {
addGroupId(levelFromSet || level, 'text', attributes.SUBTITLES);
}
}
}); // remove audio-only level if we also have levels with audio+video codecs signalled
if (videoCodecFound && audioCodecFound) {
levels = levels.filter(function (_ref) {
var videoCodec = _ref.videoCodec;
return !!videoCodec;
});
} // only keep levels with supported audio/video codecs
levels = levels.filter(function (_ref2) {
var audioCodec = _ref2.audioCodec,
videoCodec = _ref2.videoCodec;
return (!audioCodec || isCodecSupportedInMp4(audioCodec, 'audio')) && (!videoCodec || isCodecSupportedInMp4(videoCodec, 'video'));
});
if (data.audioTracks) {
audioTracks = data.audioTracks.filter(function (track) {
return !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio');
}); // Reassign id's after filtering since they're used as array indices
audioTracks.forEach(function (track, index) {
track.id = index;
});
}
if (levels.length > 0) {
// start bitrate is the first bitrate of the manifest
bitrateStart = levels[0].bitrate; // sort level on bitrate
levels.sort(function (a, b) {
return a.bitrate - b.bitrate;
});
this._levels = levels; // find index of first level in sorted levels
for (var i = 0; i < levels.length; i++) {
if (levels[i].bitrate === bitrateStart) {
this._firstLevel = i;
logger["logger"].log("manifest loaded," + levels.length + " level(s) found, first bitrate:" + bitrateStart);
break;
}
} // Audio is only alternate if manifest include a URI along with the audio group tag,
// and this is not an audio-only stream where levels contain audio-only
var audioOnly = audioCodecFound && !videoCodecFound;
this.hls.trigger(events["default"].MANIFEST_PARSED, {
levels: levels,
audioTracks: audioTracks,
firstLevel: this._firstLevel,
stats: data.stats,
audio: audioCodecFound,
video: videoCodecFound,
altAudio: !audioOnly && audioTracks.some(function (t) {
return !!t.url;
})
});
} else {
this.hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].MANIFEST_INCOMPATIBLE_CODECS_ERROR,
fatal: true,
url: this.hls.url,
reason: 'no level with compatible codecs found in manifest'
});
}
};
_proto.setLevelInternal = function setLevelInternal(newLevel) {
var levels = this._levels;
var hls = this.hls; // check if level idx is valid
if (newLevel >= 0 && newLevel < levels.length) {
// stopping live reloading timer if any
this.clearTimer();
if (this.currentLevelIndex !== newLevel) {
logger["logger"].log("switching to level " + newLevel);
this.currentLevelIndex = newLevel;
var levelProperties = levels[newLevel];
levelProperties.level = newLevel;
hls.trigger(events["default"].LEVEL_SWITCHING, levelProperties);
}
var level = levels[newLevel];
var levelDetails = level.details; // check if we need to load playlist for this level
if (!levelDetails || levelDetails.live) {
// level not retrieved yet, or live playlist we need to (re)load it
var urlId = level.urlId;
hls.trigger(events["default"].LEVEL_LOADING, {
url: level.url[urlId],
level: newLevel,
id: urlId
});
}
} else {
// invalid level id given, trigger error
hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].OTHER_ERROR,
details: errors["ErrorDetails"].LEVEL_SWITCH_ERROR,
level: newLevel,
fatal: false,
reason: 'invalid level idx'
});
}
};
_proto.onError = function onError(data) {
if (data.fatal) {
if (data.type === errors["ErrorTypes"].NETWORK_ERROR) {
this.clearTimer();
}
return;
}
var levelError = false,
fragmentError = false;
var levelIndex; // try to recover not fatal errors
switch (data.details) {
case errors["ErrorDetails"].FRAG_LOAD_ERROR:
case errors["ErrorDetails"].FRAG_LOAD_TIMEOUT:
case errors["ErrorDetails"].KEY_LOAD_ERROR:
case errors["ErrorDetails"].KEY_LOAD_TIMEOUT:
levelIndex = data.frag.level;
fragmentError = true;
break;
case errors["ErrorDetails"].LEVEL_LOAD_ERROR:
case errors["ErrorDetails"].LEVEL_LOAD_TIMEOUT:
levelIndex = data.context.level;
levelError = true;
break;
case errors["ErrorDetails"].REMUX_ALLOC_ERROR:
levelIndex = data.level;
levelError = true;
break;
}
if (levelIndex !== undefined) {
this.recoverLevel(data, levelIndex, levelError, fragmentError);
}
}
/**
* Switch to a redundant stream if any available.
* If redundant stream is not available, emergency switch down if ABR mode is enabled.
*
* @param {Object} errorEvent
* @param {Number} levelIndex current level index
* @param {Boolean} levelError
* @param {Boolean} fragmentError
*/
// FIXME Find a better abstraction where fragment/level retry management is well decoupled
;
_proto.recoverLevel = function recoverLevel(errorEvent, levelIndex, levelError, fragmentError) {
var _this2 = this;
var config = this.hls.config;
var errorDetails = errorEvent.details;
var level = this._levels[levelIndex];
var redundantLevels, delay, nextLevel;
level.loadError++;
level.fragmentError = fragmentError;
if (levelError) {
if (this.levelRetryCount + 1 <= config.levelLoadingMaxRetry) {
// exponential backoff capped to max retry timeout
delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout); // Schedule level reload
this.timer = setTimeout(function () {
return _this2.loadLevel();
}, delay); // boolean used to inform stream controller not to switch back to IDLE on non fatal error
errorEvent.levelRetry = true;
this.levelRetryCount++;
logger["logger"].warn("level controller, " + errorDetails + ", retry in " + delay + " ms, current retry count is " + this.levelRetryCount);
} else {
logger["logger"].error("level controller, cannot recover from " + errorDetails + " error");
this.currentLevelIndex = null; // stopping live reloading timer if any
this.clearTimer(); // switch error to fatal
errorEvent.fatal = true;
return;
}
} // Try any redundant streams if available for both errors: level and fragment
// If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down
if (levelError || fragmentError) {
redundantLevels = level.url.length;
if (redundantLevels > 1 && level.loadError < redundantLevels) {
level.urlId = (level.urlId + 1) % redundantLevels;
level.details = undefined;
logger["logger"].warn("level controller, " + errorDetails + " for level " + levelIndex + ": switching to redundant URL-id " + level.urlId); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
// console.log('New video quality level audio group id:', level.attrs.AUDIO);
} else {
// Search for available level
if (this.manualLevelIndex === -1) {
// When lowest level has been reached, let's start hunt from the top
nextLevel = levelIndex === 0 ? this._levels.length - 1 : levelIndex - 1;
logger["logger"].warn("level controller, " + errorDetails + ": switch to " + nextLevel);
this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;
} else if (fragmentError) {
// Allow fragment retry as long as configuration allows.
// reset this._level so that another call to set level() will trigger again a frag load
logger["logger"].warn("level controller, " + errorDetails + ": reload a fragment");
this.currentLevelIndex = null;
}
}
}
} // reset errors on the successful load of a fragment
;
_proto.onFragLoaded = function onFragLoaded(_ref3) {
var frag = _ref3.frag;
if (frag !== undefined && frag.type === 'main') {
var level = this._levels[frag.level];
if (level !== undefined) {
level.fragmentError = false;
level.loadError = 0;
this.levelRetryCount = 0;
}
}
};
_proto.onLevelLoaded = function onLevelLoaded(data) {
var _this3 = this;
var level = data.level,
details = data.details; // only process level loaded events matching with expected level
if (level !== this.currentLevelIndex) {
return;
}
var curLevel = this._levels[level]; // reset level load error counter on successful level loaded only if there is no issues with fragments
if (!curLevel.fragmentError) {
curLevel.loadError = 0;
this.levelRetryCount = 0;
} // if current playlist is a live playlist, arm a timer to reload it
if (details.live) {
var reloadInterval = computeReloadInterval(curLevel.details, details, data.stats.trequest);
logger["logger"].log("live playlist, reload in " + Math.round(reloadInterval) + " ms");
this.timer = setTimeout(function () {
return _this3.loadLevel();
}, reloadInterval);
} else {
this.clearTimer();
}
};
_proto.onAudioTrackSwitched = function onAudioTrackSwitched(data) {
var audioGroupId = this.hls.audioTracks[data.id].groupId;
var currentLevel = this.hls.levels[this.currentLevelIndex];
if (!currentLevel) {
return;
}
if (currentLevel.audioGroupIds) {
var urlId = -1;
for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
if (currentLevel.audioGroupIds[i] === audioGroupId) {
urlId = i;
break;
}
}
if (urlId !== currentLevel.urlId) {
currentLevel.urlId = urlId;
this.startLoad();
}
}
};
_proto.loadLevel = function loadLevel() {
logger["logger"].debug('call to loadLevel');
if (this.currentLevelIndex !== null && this.canload) {
var levelObject = this._levels[this.currentLevelIndex];
if (typeof levelObject === 'object' && levelObject.url.length > 0) {
var level = this.currentLevelIndex;
var id = levelObject.urlId;
var url = levelObject.url[id];
logger["logger"].log("Attempt loading level index " + level + " with URL-id " + id); // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
// console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
this.hls.trigger(events["default"].LEVEL_LOADING, {
url: url,
level: level,
id: id
});
}
}
};
_proto.removeLevel = function removeLevel(levelIndex, urlId) {
var levels = this.levels.filter(function (level, index) {
if (index !== levelIndex) {
return true;
}
if (level.url.length > 1 && urlId !== undefined) {
level.url = level.url.filter(function (url, id) {
return id !== urlId;
});
level.urlId = 0;
return true;
}
return false;
}).map(function (level, index) {
var details = level.details;
if (details && details.fragments) {
details.fragments.forEach(function (fragment) {
fragment.level = index;
});
}
return level;
});
this._levels = levels;
this.hls.trigger(events["default"].LEVELS_UPDATED, {
levels: levels
});
};
level_controller_createClass(LevelController, [{
key: "levels",
get: function get() {
return this._levels;
}
}, {
key: "level",
get: function get() {
return this.currentLevelIndex;
},
set: function set(newLevel) {
var levels = this._levels;
if (levels) {
newLevel = Math.min(newLevel, levels.length - 1);
if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {
this.setLevelInternal(newLevel);
}
}
}
}, {
key: "manualLevel",
get: function get() {
return this.manualLevelIndex;
},
set: function set(newLevel) {
this.manualLevelIndex = newLevel;
if (this._startLevel === undefined) {
this._startLevel = newLevel;
}
if (newLevel !== -1) {
this.level = newLevel;
}
}
}, {
key: "firstLevel",
get: function get() {
return this._firstLevel;
},
set: function set(newLevel) {
this._firstLevel = newLevel;
}
}, {
key: "startLevel",
get: function get() {
// hls.startLevel takes precedence over config.startLevel
// if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
if (this._startLevel === undefined) {
var configStartLevel = this.hls.config.startLevel;
if (configStartLevel !== undefined) {
return configStartLevel;
} else {
return this._firstLevel;
}
} else {
return this._startLevel;
}
},
set: function set(newLevel) {
this._startLevel = newLevel;
}
}, {
key: "nextLoadLevel",
get: function get() {
if (this.manualLevelIndex !== -1) {
return this.manualLevelIndex;
} else {
return this.hls.nextAutoLevel;
}
},
set: function set(nextLevel) {
this.level = nextLevel;
if (this.manualLevelIndex === -1) {
this.hls.nextAutoLevel = nextLevel;
}
}
}]);
return LevelController;
}(event_handler);
// EXTERNAL MODULE: ./src/demux/id3.js
var id3 = __webpack_require__("./src/demux/id3.js");
// CONCATENATED MODULE: ./src/utils/texttrack-utils.ts
function sendAddTrackEvent(track, videoEl) {
var event;
try {
event = new Event('addtrack');
} catch (err) {
// for IE11
event = document.createEvent('Event');
event.initEvent('addtrack', false, false);
}
event.track = track;
videoEl.dispatchEvent(event);
}
function clearCurrentCues(track) {
if (track === null || track === void 0 ? void 0 : track.cues) {
while (track.cues.length > 0) {
track.removeCue(track.cues[0]);
}
}
}
/**
* Given a list of Cues, finds the closest cue matching the given time.
* Modified verison of binary search O(log(n)).
*
* @export
* @param {(TextTrackCueList | TextTrackCue[])} cues - List of cues.
* @param {number} time - Target time, to find closest cue to.
* @returns {TextTrackCue}
*/
function getClosestCue(cues, time) {
// If the offset is less than the first element, the first element is the closest.
if (time < cues[0].endTime) {
return cues[0];
} // If the offset is greater than the last cue, the last is the closest.
if (time > cues[cues.length - 1].endTime) {
return cues[cues.length - 1];
}
var left = 0;
var right = cues.length - 1;
while (left <= right) {
var mid = Math.floor((right + left) / 2);
if (time < cues[mid].endTime) {
right = mid - 1;
} else if (time > cues[mid].endTime) {
left = mid + 1;
} else {
// If it's not lower or higher, it must be equal.
return cues[mid];
}
} // At this point, left and right have swapped.
// No direct match was found, left or right element must be the closest. Check which one has the smallest diff.
return cues[left].endTime - time < time - cues[right].endTime ? cues[left] : cues[right];
}
// CONCATENATED MODULE: ./src/controller/id3-track-controller.js
function id3_track_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/*
* id3 metadata track controller
*/
var MIN_CUE_DURATION = 0.25;
var id3_track_controller_ID3TrackController = /*#__PURE__*/function (_EventHandler) {
id3_track_controller_inheritsLoose(ID3TrackController, _EventHandler);
function ID3TrackController(hls) {
var _this;
_this = _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHED, events["default"].MEDIA_DETACHING, events["default"].FRAG_PARSING_METADATA, events["default"].LIVE_BACK_BUFFER_REACHED) || this;
_this.id3Track = undefined;
_this.media = undefined;
return _this;
}
var _proto = ID3TrackController.prototype;
_proto.destroy = function destroy() {
event_handler.prototype.destroy.call(this);
} // Add ID3 metatadata text track.
;
_proto.onMediaAttached = function onMediaAttached(data) {
this.media = data.media;
if (!this.media) {}
};
_proto.onMediaDetaching = function onMediaDetaching() {
clearCurrentCues(this.id3Track);
this.id3Track = undefined;
this.media = undefined;
};
_proto.getID3Track = function getID3Track(textTracks) {
for (var i = 0; i < textTracks.length; i++) {
var textTrack = textTracks[i];
if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
// send 'addtrack' when reusing the textTrack for metadata,
// same as what we do for captions
sendAddTrackEvent(textTrack, this.media);
return textTrack;
}
}
return this.media.addTextTrack('metadata', 'id3');
};
_proto.onFragParsingMetadata = function onFragParsingMetadata(data) {
var fragment = data.frag;
var samples = data.samples; // create track dynamically
if (!this.id3Track) {
this.id3Track = this.getID3Track(this.media.textTracks);
this.id3Track.mode = 'hidden';
} // Attempt to recreate Safari functionality by creating
// WebKitDataCue objects when available and store the decoded
// ID3 data in the value property of the cue
var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;
for (var i = 0; i < samples.length; i++) {
var frames = id3["default"].getID3Frames(samples[i].data);
if (frames) {
// Ensure the pts is positive - sometimes it's reported as a small negative number
var startTime = Math.max(samples[i].pts, 0);
var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;
if (!endTime) {
endTime = fragment.start + fragment.duration;
}
var timeDiff = endTime - startTime;
if (timeDiff <= 0) {
endTime = startTime + MIN_CUE_DURATION;
}
for (var j = 0; j < frames.length; j++) {
var frame = frames[j]; // Safari doesn't put the timestamp frame in the TextTrack
if (!id3["default"].isTimeStampFrame(frame)) {
var cue = new Cue(startTime, endTime, '');
cue.value = frame;
this.id3Track.addCue(cue);
}
}
}
}
};
_proto.onLiveBackBufferReached = function onLiveBackBufferReached(_ref) {
var bufferEnd = _ref.bufferEnd;
var id3Track = this.id3Track;
if (!id3Track || !id3Track.cues || !id3Track.cues.length) {
return;
}
var foundCue = getClosestCue(id3Track.cues, bufferEnd);
if (!foundCue) {
return;
}
while (id3Track.cues[0] !== foundCue) {
id3Track.removeCue(id3Track.cues[0]);
}
};
return ID3TrackController;
}(event_handler);
/* harmony default export */ var id3_track_controller = (id3_track_controller_ID3TrackController);
// CONCATENATED MODULE: ./src/is-supported.ts
function is_supported_isSupported() {
var mediaSource = getMediaSource();
if (!mediaSource) {
return false;
}
var sourceBuffer = self.SourceBuffer || self.WebKitSourceBuffer; // eslint-disable-line no-restricted-globals
var isTypeSupported = mediaSource && typeof mediaSource.isTypeSupported === 'function' && mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'); // if SourceBuffer is exposed ensure its API is valid
// safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
var sourceBufferValidAPI = !sourceBuffer || sourceBuffer.prototype && typeof sourceBuffer.prototype.appendBuffer === 'function' && typeof sourceBuffer.prototype.remove === 'function';
return !!isTypeSupported && !!sourceBufferValidAPI;
}
// CONCATENATED MODULE: ./src/utils/ewma.ts
/*
* compute an Exponential Weighted moving average
* - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
* - heavily inspired from shaka-player
*/
var EWMA = /*#__PURE__*/function () {
// About half of the estimated value will be from the last |halfLife| samples by weight.
function EWMA(halfLife) {
this.alpha_ = void 0;
this.estimate_ = void 0;
this.totalWeight_ = void 0;
// Larger values of alpha expire historical data more slowly.
this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
this.estimate_ = 0;
this.totalWeight_ = 0;
}
var _proto = EWMA.prototype;
_proto.sample = function sample(weight, value) {
var adjAlpha = Math.pow(this.alpha_, weight);
this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
this.totalWeight_ += weight;
};
_proto.getTotalWeight = function getTotalWeight() {
return this.totalWeight_;
};
_proto.getEstimate = function getEstimate() {
if (this.alpha_) {
var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
return this.estimate_ / zeroFactor;
} else {
return this.estimate_;
}
};
return EWMA;
}();
/* harmony default export */ var ewma = (EWMA);
// CONCATENATED MODULE: ./src/utils/ewma-bandwidth-estimator.ts
/*
* EWMA Bandwidth Estimator
* - heavily inspired from shaka-player
* Tracks bandwidth samples and estimates available bandwidth.
* Based on the minimum of two exponentially-weighted moving averages with
* different half-lives.
*/
var ewma_bandwidth_estimator_EwmaBandWidthEstimator = /*#__PURE__*/function () {
// TODO(typescript-hls)
function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) {
this.hls = void 0;
this.defaultEstimate_ = void 0;
this.minWeight_ = void 0;
this.minDelayMs_ = void 0;
this.slow_ = void 0;
this.fast_ = void 0;
this.hls = hls;
this.defaultEstimate_ = defaultEstimate;
this.minWeight_ = 0.001;
this.minDelayMs_ = 50;
this.slow_ = new ewma(slow);
this.fast_ = new ewma(fast);
}
var _proto = EwmaBandWidthEstimator.prototype;
_proto.sample = function sample(durationMs, numBytes) {
durationMs = Math.max(durationMs, this.minDelayMs_);
var numBits = 8 * numBytes,
// weight is duration in seconds
durationS = durationMs / 1000,
// value is bandwidth in bits/s
bandwidthInBps = numBits / durationS;
this.fast_.sample(durationS, bandwidthInBps);
this.slow_.sample(durationS, bandwidthInBps);
};
_proto.canEstimate = function canEstimate() {
var fast = this.fast_;
return fast && fast.getTotalWeight() >= this.minWeight_;
};
_proto.getEstimate = function getEstimate() {
if (this.canEstimate()) {
// console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
// console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
// Take the minimum of these two estimates. This should have the effect of
// adapting down quickly, but up more slowly.
return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
} else {
return this.defaultEstimate_;
}
};
_proto.destroy = function destroy() {};
return EwmaBandWidthEstimator;
}();
/* harmony default export */ var ewma_bandwidth_estimator = (ewma_bandwidth_estimator_EwmaBandWidthEstimator);
// CONCATENATED MODULE: ./src/controller/abr-controller.js
function abr_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function abr_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) abr_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) abr_controller_defineProperties(Constructor, staticProps); return Constructor; }
function abr_controller_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function abr_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/*
* simple ABR Controller
* - compute next level based on last fragment bw heuristics
* - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
*/
var abr_controller_window = window,
abr_controller_performance = abr_controller_window.performance;
var abr_controller_AbrController = /*#__PURE__*/function (_EventHandler) {
abr_controller_inheritsLoose(AbrController, _EventHandler);
function AbrController(hls) {
var _this;
_this = _EventHandler.call(this, hls, events["default"].FRAG_LOADING, events["default"].FRAG_LOADED, events["default"].FRAG_BUFFERED, events["default"].ERROR) || this;
_this.lastLoadedFragLevel = 0;
_this._nextAutoLevel = -1;
_this.hls = hls;
_this.timer = null;
_this._bwEstimator = null;
_this.onCheck = _this._abandonRulesCheck.bind(abr_controller_assertThisInitialized(_this));
return _this;
}
var _proto = AbrController.prototype;
_proto.destroy = function destroy() {
this.clearTimer();
event_handler.prototype.destroy.call(this);
};
_proto.onFragLoading = function onFragLoading(data) {
var frag = data.frag;
if (frag.type === 'main') {
if (!this.timer) {
this.fragCurrent = frag;
this.timer = setInterval(this.onCheck, 100);
} // lazy init of BwEstimator, rationale is that we use different params for Live/VoD
// so we need to wait for stream manifest / playlist type to instantiate it.
if (!this._bwEstimator) {
var hls = this.hls;
var config = hls.config;
var level = frag.level;
var isLive = hls.levels[level].details.live;
var ewmaFast;
var ewmaSlow;
if (isLive) {
ewmaFast = config.abrEwmaFastLive;
ewmaSlow = config.abrEwmaSlowLive;
} else {
ewmaFast = config.abrEwmaFastVoD;
ewmaSlow = config.abrEwmaSlowVoD;
}
this._bwEstimator = new ewma_bandwidth_estimator(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);
}
}
};
_proto._abandonRulesCheck = function _abandonRulesCheck() {
/*
monitor fragment retrieval time...
we compute expected time of arrival of the complete fragment.
we compare it to expected time of buffer starvation
*/
var hls = this.hls;
var video = hls.media;
var frag = this.fragCurrent;
if (!frag) {
return;
}
var loader = frag.loader; // if loader has been destroyed or loading has been aborted, stop timer and return
if (!loader || loader.stats && loader.stats.aborted) {
logger["logger"].warn('frag loader destroy or aborted, disarm abandonRules');
this.clearTimer(); // reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1;
return;
}
var stats = loader.stats;
/* only monitor frag retrieval time if
(video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */
if (video && stats && (!video.paused && video.playbackRate !== 0 || !video.readyState) && frag.autoLevel && frag.level) {
var requestDelay = abr_controller_performance.now() - stats.trequest;
var playbackRate = Math.abs(video.playbackRate); // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
if (requestDelay > 500 * frag.duration / playbackRate) {
var levels = hls.levels;
var loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay); // byte/s; at least 1 byte/s to avoid division by zero
// compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size
var level = levels[frag.level];
if (!level) {
return;
}
var levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate;
var expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8));
var pos = video.currentTime;
var fragLoadedDelay = (expectedLen - stats.loaded) / loadRate;
var bufferStarvationDelay = (buffer_helper_BufferHelper.bufferInfo(video, pos, hls.config.maxBufferHole).end - pos) / playbackRate; // consider emergency switch down only if we have less than 2 frag buffered AND
// time to finish loading current fragment is bigger than buffer starvation delay
// ie if we risk buffer starvation if bw does not increase quickly
if (bufferStarvationDelay < 2 * frag.duration / playbackRate && fragLoadedDelay > bufferStarvationDelay) {
var minAutoLevel = hls.minAutoLevel;
var fragLevelNextLoadedDelay;
var nextLoadLevel; // lets iterate through lower level and try to find the biggest one that could avoid rebuffering
// we start from current level - 1 and we step down , until we find a matching level
for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
// compute time to load next fragment at lower level
// 0.8 : consider only 80% of current bw to be conservative
// 8 = bits per byte (bps/Bps)
var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;
var _fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);
if (_fragLevelNextLoadedDelay < bufferStarvationDelay) {
// we found a lower level that be rebuffering free with current estimated bw !
break;
}
} // only emergency switch down if it takes less time to load new fragment at lowest level instead
// of finishing loading current one ...
if (fragLevelNextLoadedDelay < fragLoadedDelay) {
logger["logger"].warn("loading too slow, abort fragment loading and switch to level " + nextLoadLevel + ":fragLoadedDelay[" + nextLoadLevel + "]<fragLoadedDelay[" + (frag.level - 1) + "];bufferStarvationDelay:" + fragLevelNextLoadedDelay.toFixed(1) + "<" + fragLoadedDelay.toFixed(1) + ":" + bufferStarvationDelay.toFixed(1)); // force next load level in auto mode
hls.nextLoadLevel = nextLoadLevel; // update bw estimate for this fragment before cancelling load (this will help reducing the bw)
this._bwEstimator.sample(requestDelay, stats.loaded); // abort fragment loading
loader.abort(); // stop abandon rules timer
this.clearTimer();
hls.trigger(events["default"].FRAG_LOAD_EMERGENCY_ABORTED, {
frag: frag,
stats: stats
});
}
}
}
}
};
_proto.onFragLoaded = function onFragLoaded(data) {
var frag = data.frag;
if (frag.type === 'main' && Object(number["isFiniteNumber"])(frag.sn)) {
// stop monitoring bw once frag loaded
this.clearTimer(); // store level id after successful fragment load
this.lastLoadedFragLevel = frag.level; // reset forced auto level value so that next level will be selected
this._nextAutoLevel = -1; // compute level average bitrate
if (this.hls.config.abrMaxWithRealBitrate) {
var level = this.hls.levels[frag.level];
var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;
var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;
level.loaded = {
bytes: loadedBytes,
duration: loadedDuration
};
level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
} // if fragment has been loaded to perform a bitrate test,
if (data.frag.bitrateTest) {
var stats = data.stats;
stats.tparsed = stats.tbuffered = stats.tload;
this.onFragBuffered(data);
}
}
};
_proto.onFragBuffered = function onFragBuffered(data) {
var stats = data.stats;
var frag = data.frag; // only update stats on first frag buffering
// if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
// and leading to wrong bw estimation
// on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)
if (stats.aborted !== true && frag.type === 'main' && Object(number["isFiniteNumber"])(frag.sn) && (!frag.bitrateTest || stats.tload === stats.tbuffered)) {
// use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached
// in case we use config.startFragPrefetch while media is not attached yet, fragment might be parsed while media not attached yet, but it will only be buffered on media attached
// as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation
var fragLoadingProcessingMs = stats.tparsed - stats.trequest;
logger["logger"].log("latency/loading/parsing/append/kbps:" + Math.round(stats.tfirst - stats.trequest) + "/" + Math.round(stats.tload - stats.tfirst) + "/" + Math.round(stats.tparsed - stats.tload) + "/" + Math.round(stats.tbuffered - stats.tparsed) + "/" + Math.round(8 * stats.loaded / (stats.tbuffered - stats.trequest)));
this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);
stats.bwEstimate = this._bwEstimator.getEstimate(); // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration
if (frag.bitrateTest) {
this.bitrateTestDelay = fragLoadingProcessingMs / 1000;
} else {
this.bitrateTestDelay = 0;
}
}
};
_proto.onError = function onError(data) {
// stop timer in case of frag loading error
switch (data.details) {
case errors["ErrorDetails"].FRAG_LOAD_ERROR:
case errors["ErrorDetails"].FRAG_LOAD_TIMEOUT:
this.clearTimer();
break;
default:
break;
}
};
_proto.clearTimer = function clearTimer() {
clearInterval(this.timer);
this.timer = null;
} // return next auto level
;
_proto._findBestLevel = function _findBestLevel(currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {
for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
var levelInfo = levels[i];
if (!levelInfo) {
continue;
}
var levelDetails = levelInfo.details;
var avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration;
var live = levelDetails ? levelDetails.live : false;
var adjustedbw = void 0; // follow algorithm captured from stagefright :
// https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
// Pick the highest bandwidth stream below or equal to estimated bandwidth.
// consider only 80% of the available bandwidth, but if we are switching up,
// be even more conservative (70%) to avoid overestimating and immediately
// switching back.
if (i <= currentLevel) {
adjustedbw = bwFactor * currentBw;
} else {
adjustedbw = bwUpFactor * currentBw;
}
var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
var fetchDuration = bitrate * avgDuration / adjustedbw;
logger["logger"].trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: " + i + "/" + Math.round(adjustedbw) + "/" + bitrate + "/" + avgDuration + "/" + maxFetchDuration + "/" + fetchDuration); // if adjusted bw is greater than level bitrate AND
if (adjustedbw > bitrate && ( // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
// we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
// special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1
!fetchDuration || live && !this.bitrateTestDelay || fetchDuration < maxFetchDuration)) {
// as we are looping from highest to lowest, this will return the best achievable quality level
return i;
}
} // not enough time budget even with quality level 0 ... rebuffering might happen
return -1;
};
abr_controller_createClass(AbrController, [{
key: "nextAutoLevel",
get: function get() {
var forcedAutoLevel = this._nextAutoLevel;
var bwEstimator = this._bwEstimator; // in case next auto level has been forced, and bw not available or not reliable, return forced value
if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
return forcedAutoLevel;
} // compute next level using ABR logic
var nextABRAutoLevel = this._nextABRAutoLevel; // if forced auto level has been defined, use it to cap ABR computed quality level
if (forcedAutoLevel !== -1) {
nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
}
return nextABRAutoLevel;
},
set: function set(nextLevel) {
this._nextAutoLevel = nextLevel;
}
}, {
key: "_nextABRAutoLevel",
get: function get() {
var hls = this.hls;
var maxAutoLevel = hls.maxAutoLevel,
levels = hls.levels,
config = hls.config,
minAutoLevel = hls.minAutoLevel;
var video = hls.media;
var currentLevel = this.lastLoadedFragLevel;
var currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0;
var pos = video ? video.currentTime : 0; // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as
// if we're playing back at the normal rate.
var playbackRate = video && video.playbackRate !== 0 ? Math.abs(video.playbackRate) : 1.0;
var avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate; // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
var bufferStarvationDelay = (buffer_helper_BufferHelper.bufferInfo(video, pos, config.maxBufferHole).end - pos) / playbackRate; // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);
if (bestLevel >= 0) {
return bestLevel;
} else {
logger["logger"].trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering'); // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
// if no matching level found, logic will return 0
var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;
var bwFactor = config.abrBandWidthFactor;
var bwUpFactor = config.abrBandWidthUpFactor;
if (bufferStarvationDelay === 0) {
// in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
var bitrateTestDelay = this.bitrateTestDelay;
if (bitrateTestDelay) {
// if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
// max video loading delay used in automatic start level selection :
// in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
// the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
// cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
logger["logger"].trace("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms"); // don't use conservative factor on bitrate test
bwFactor = bwUpFactor = 1;
}
}
bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);
return Math.max(bestLevel, 0);
}
}
}]);
return AbrController;
}(event_handler);
/* harmony default export */ var abr_controller = (abr_controller_AbrController);
// CONCATENATED MODULE: ./src/controller/buffer-controller.ts
function buffer_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/*
* Buffer Controller
*/
var buffer_controller_MediaSource = getMediaSource();
var buffer_controller_BufferController = /*#__PURE__*/function (_EventHandler) {
buffer_controller_inheritsLoose(BufferController, _EventHandler);
// the value that we have set mediasource.duration to
// (the actual duration may be tweaked slighly by the browser)
// the value that we want to set mediaSource.duration to
// the target duration of the current media playlist
// current stream state: true - for live broadcast, false - for VoD content
// cache the self generated object url to detect hijack of video tag
// signals that the sourceBuffers need to be flushed
// signals that mediaSource should have endOfStream called
// this is optional because this property is removed from the class sometimes
// The number of BUFFER_CODEC events received before any sourceBuffers are created
// The total number of BUFFER_CODEC events received
// A reference to the attached media element
// A reference to the active media source
// List of pending segments to be appended to source buffer
// A guard to see if we are currently appending to the source buffer
// counters
function BufferController(hls) {
var _this;
_this = _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHING, events["default"].MEDIA_DETACHING, events["default"].MANIFEST_PARSED, events["default"].BUFFER_RESET, events["default"].BUFFER_APPENDING, events["default"].BUFFER_CODECS, events["default"].BUFFER_EOS, events["default"].BUFFER_FLUSHING, events["default"].LEVEL_PTS_UPDATED, events["default"].LEVEL_UPDATED) || this;
_this._msDuration = null;
_this._levelDuration = null;
_this._levelTargetDuration = 10;
_this._live = null;
_this._objectUrl = null;
_this._needsFlush = false;
_this._needsEos = false;
_this.config = void 0;
_this.audioTimestampOffset = void 0;
_this.bufferCodecEventsExpected = 0;
_this._bufferCodecEventsTotal = 0;
_this.media = null;
_this.mediaSource = null;
_this.segments = [];
_this.parent = void 0;
_this.appending = false;
_this.appended = 0;
_this.appendError = 0;
_this.flushBufferCounter = 0;
_this.tracks = {};
_this.pendingTracks = {};
_this.sourceBuffer = {};
_this.flushRange = [];
_this._onMediaSourceOpen = function () {
logger["logger"].log('media source opened');
_this.hls.trigger(events["default"].MEDIA_ATTACHED, {
media: _this.media
});
var mediaSource = _this.mediaSource;
if (mediaSource) {
// once received, don't listen anymore to sourceopen event
mediaSource.removeEventListener('sourceopen', _this._onMediaSourceOpen);
}
_this.checkPendingTracks();
};
_this._onMediaSourceClose = function () {
logger["logger"].log('media source closed');
};
_this._onMediaSourceEnded = function () {
logger["logger"].log('media source ended');
};
_this._onSBUpdateEnd = function () {
// update timestampOffset
if (_this.audioTimestampOffset && _this.sourceBuffer.audio) {
var audioBuffer = _this.sourceBuffer.audio;
logger["logger"].warn("change mpeg audio timestamp offset from " + audioBuffer.timestampOffset + " to " + _this.audioTimestampOffset);
audioBuffer.timestampOffset = _this.audioTimestampOffset;
delete _this.audioTimestampOffset;
}
if (_this._needsFlush) {
_this.doFlush();
}
if (_this._needsEos) {
_this.checkEos();
}
_this.appending = false;
var parent = _this.parent; // count nb of pending segments waiting for appending on this sourcebuffer
var pending = _this.segments.reduce(function (counter, segment) {
return segment.parent === parent ? counter + 1 : counter;
}, 0); // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments
var timeRanges = {};
var sbSet = _this.sourceBuffer;
for (var streamType in sbSet) {
var sb = sbSet[streamType];
if (!sb) {
throw Error("handling source buffer update end error: source buffer for " + streamType + " uninitilized and unable to update buffered TimeRanges.");
}
timeRanges[streamType] = buffer_helper_BufferHelper.getBuffered(sb);
}
_this.hls.trigger(events["default"].BUFFER_APPENDED, {
parent: parent,
pending: pending,
timeRanges: timeRanges
}); // don't append in flushing mode
if (!_this._needsFlush) {
_this.doAppending();
}
_this.updateMediaElementDuration(); // appending goes first
if (pending === 0) {
_this.flushLiveBackBuffer();
}
};
_this._onSBUpdateError = function (event) {
logger["logger"].error('sourceBuffer error:', event); // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
// this error might not always be fatal (it is fatal if decode error is set, in that case
// it will be followed by a mediaElement error ...)
_this.hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].BUFFER_APPENDING_ERROR,
fatal: false
}); // we don't need to do more than that, as accordin to the spec, updateend will be fired just after
};
_this.config = hls.config;
return _this;
}
var _proto = BufferController.prototype;
_proto.destroy = function destroy() {
event_handler.prototype.destroy.call(this);
};
_proto.onLevelPtsUpdated = function onLevelPtsUpdated(data) {
var type = data.type;
var audioTrack = this.tracks.audio; // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
// in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
// is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). At the time of change we issue
// `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`
// event if SB is in updating state.
// More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') {
// Chrome audio mp3 track
var audioBuffer = this.sourceBuffer.audio;
if (!audioBuffer) {
throw Error('Level PTS Updated and source buffer for audio uninitalized');
}
var delta = Math.abs(audioBuffer.timestampOffset - data.start); // adjust timestamp offset if time delta is greater than 100ms
if (delta > 0.1) {
var updating = audioBuffer.updating;
try {
audioBuffer.abort();
} catch (err) {
logger["logger"].warn('can not abort audio buffer: ' + err);
}
if (!updating) {
logger["logger"].warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);
audioBuffer.timestampOffset = data.start;
} else {
this.audioTimestampOffset = data.start;
}
}
}
if (this.config.liveDurationInfinity) {
this.updateSeekableRange(data.details);
}
};
_proto.onManifestParsed = function onManifestParsed(data) {
// in case of alt audio (where all tracks have urls) 2 BUFFER_CODECS events will be triggered, one per stream controller
// sourcebuffers will be created all at once when the expected nb of tracks will be reached
// in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
// it will contain the expected nb of source buffers, no need to compute it
var codecEvents = 2;
if (data.audio && !data.video || !data.altAudio) {
codecEvents = 1;
}
this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;
logger["logger"].log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected");
};
_proto.onMediaAttaching = function onMediaAttaching(data) {
var media = this.media = data.media;
if (media && buffer_controller_MediaSource) {
// setup the media source
var ms = this.mediaSource = new buffer_controller_MediaSource(); // Media Source listeners
ms.addEventListener('sourceopen', this._onMediaSourceOpen);
ms.addEventListener('sourceended', this._onMediaSourceEnded);
ms.addEventListener('sourceclose', this._onMediaSourceClose); // link video and media Source
media.src = window.URL.createObjectURL(ms); // cache the locally generated object url
this._objectUrl = media.src;
}
};
_proto.onMediaDetaching = function onMediaDetaching() {
logger["logger"].log('media source detaching');
var ms = this.mediaSource;
if (ms) {
if (ms.readyState === 'open') {
try {
// endOfStream could trigger exception if any sourcebuffer is in updating state
// we don't really care about checking sourcebuffer state here,
// as we are anyway detaching the MediaSource
// let's just avoid this exception to propagate
ms.endOfStream();
} catch (err) {
logger["logger"].warn("onMediaDetaching:" + err.message + " while calling endOfStream");
}
}
ms.removeEventListener('sourceopen', this._onMediaSourceOpen);
ms.removeEventListener('sourceended', this._onMediaSourceEnded);
ms.removeEventListener('sourceclose', this._onMediaSourceClose); // Detach properly the MediaSource from the HTMLMediaElement as
// suggested in https://github.com/w3c/media-source/issues/53.
if (this.media) {
if (this._objectUrl) {
window.URL.revokeObjectURL(this._objectUrl);
} // clean up video tag src only if it's our own url. some external libraries might
// hijack the video tag and change its 'src' without destroying the Hls instance first
if (this.media.src === this._objectUrl) {
this.media.removeAttribute('src');
this.media.load();
} else {
logger["logger"].warn('media.src was changed by a third party - skip cleanup');
}
}
this.mediaSource = null;
this.media = null;
this._objectUrl = null;
this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;
this.pendingTracks = {};
this.tracks = {};
this.sourceBuffer = {};
this.flushRange = [];
this.segments = [];
this.appended = 0;
}
this.hls.trigger(events["default"].MEDIA_DETACHED);
};
_proto.checkPendingTracks = function checkPendingTracks() {
var bufferCodecEventsExpected = this.bufferCodecEventsExpected,
pendingTracks = this.pendingTracks; // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
// This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
// data has been appended to existing ones.
// 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
var pendingTracksCount = Object.keys(pendingTracks).length;
if (pendingTracksCount && !bufferCodecEventsExpected || pendingTracksCount === 2) {
// ok, let's create them now !
this.createSourceBuffers(pendingTracks);
this.pendingTracks = {}; // append any pending segments now !
this.doAppending();
}
};
_proto.onBufferReset = function onBufferReset() {
var sourceBuffer = this.sourceBuffer;
for (var type in sourceBuffer) {
var sb = sourceBuffer[type];
try {
if (sb) {
if (this.mediaSource) {
this.mediaSource.removeSourceBuffer(sb);
}
sb.removeEventListener('updateend', this._onSBUpdateEnd);
sb.removeEventListener('error', this._onSBUpdateError);
}
} catch (err) {}
}
this.sourceBuffer = {};
this.flushRange = [];
this.segments = [];
this.appended = 0;
};
_proto.onBufferCodecs = function onBufferCodecs(tracks) {
var _this2 = this;
// if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
// if sourcebuffers already created, do nothing ...
if (Object.keys(this.sourceBuffer).length) {
return;
}
Object.keys(tracks).forEach(function (trackName) {
_this2.pendingTracks[trackName] = tracks[trackName];
});
this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
if (this.mediaSource && this.mediaSource.readyState === 'open') {
this.checkPendingTracks();
}
};
_proto.createSourceBuffers = function createSourceBuffers(tracks) {
var sourceBuffer = this.sourceBuffer,
mediaSource = this.mediaSource;
if (!mediaSource) {
throw Error('createSourceBuffers called when mediaSource was null');
}
for (var trackName in tracks) {
if (!sourceBuffer[trackName]) {
var track = tracks[trackName];
if (!track) {
throw Error("source buffer exists for track " + trackName + ", however track does not");
} // use levelCodec as first priority
var codec = track.levelCodec || track.codec;
var mimeType = track.container + ";codecs=" + codec;
logger["logger"].log("creating sourceBuffer(" + mimeType + ")");
try {
var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
sb.addEventListener('updateend', this._onSBUpdateEnd);
sb.addEventListener('error', this._onSBUpdateError);
this.tracks[trackName] = {
buffer: sb,
codec: codec,
id: track.id,
container: track.container,
levelCodec: track.levelCodec
};
} catch (err) {
logger["logger"].error("error while trying to add sourceBuffer:" + err.message);
this.hls.trigger(events["default"].ERROR, {
type: errors["ErrorTypes"].MEDIA_ERROR,
details: errors["ErrorDetails"].BUFFER_ADD_CODEC_ERROR,
fatal: false,
err: err,
mimeType: mimeType
});
}
}
}
this.hls.trigger(events["default"].BUFFER_CREATED, {
tracks: this.tracks
});
};
_proto.onBufferAppending = function onBufferAppending(data) {
if (!this._needsFlush) {
if (!this.segments) {
this.segments = [data];
} else {
this.segments.push(data);
}
this.doAppending();
}
} // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
// an undefined data.type will mark all buffers as EOS.
;
_proto.onBufferEos = function onBufferEos(data) {
for (var type in this.sourceBuffer) {
if (!data.type || data.type === type) {
var sb = this.sourceBuffer[type];
if (sb && !sb.ended) {
sb.ended = true;
logger["logger"].log(type + " sourceBuffer now EOS");
}
}
}
this.checkEos();
} // if all source buffers are marked as ended, signal endOfStream() to MediaSource.
;
_proto.checkEos = function checkEos() {
var sourceBuffer = this.sourceBuffer,
mediaSource = this.mediaSource;
if (!mediaSource || mediaSource.readyState !== 'open') {
this._needsEos = false;
return;
}
for (var type in sourceBuffer) {
var sb = sourceBuffer[type];
if (!sb) continue;
if (!sb.ended) {
return;
}
if (sb.updating) {
this._needsEos = true;
return;
}
}
logger["logger"].log('all media data are available, signal endOfStream() to MediaSource and stop loading fragment'); // Notify the media element that it now has all of the media data
try {
mediaSource.endOfStream();
} catch (e) {
logger["logger"].warn('exception while calling mediaSource.endOfStream()');
}
this._needsEos = false;
};
_proto.onBufferFlushing = function onBufferFlushing(data) {
if (data.type) {
this.flushRange.push({
start: data.startOffset,
end: data.endOffset,
type: data.type
});
} else {
this.flushRange.push({
start: data.startOffset,
end: data.endOffset,
type: 'video'
});
this.flushRange.push({
start: data.startOffset,
end: data.endOffset,
type: 'audio'
});
} // attempt flush immediately
this.flushBufferCounter = 0;
this.doFlush();
};
_proto.flushLiveBackBuffer = function flushLiveBackBuffer() {
// clear back buffer for live only
if (!this._live) {
return;
}
var liveBackBufferLength = this.config.liveBackBufferLength;
if (!isFinite(liveBackBufferLength) || liveBackBufferLength < 0) {
return;
}
if (!this.media) {
logger["logger"].error('flushLiveBackBuffer called without attaching media');
return;
}
var currentTime = this.media.currentTime;
var sourceBuffer = this.sourceBuffer;
var bufferTypes = Object.keys(sourceBuffer);
var targetBackBufferPosition = currentTime - Math.max(liveBackBufferLength, this._levelTargetDuration);
for (var index = bufferTypes.length - 1; index >= 0; index--) {
var bufferType = bufferTypes[index];
var sb = sourceBuffer[bufferType];
if (sb) {
var buffered = buffer_helper_BufferHelper.getBuffered(sb); // when target buffer start exceeds actual buffer start
if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
// remove buffer up until current time minus minimum back buffer length (removing buffer too close to current
// time will lead to playback freezing)
// credits for level target duration - https://github.com/videojs/http-streaming/blob/3132933b6aa99ddefab29c10447624efd6fd6e52/src/segment-loader.js#L91
if (this.removeBufferRange(bufferType, sb, 0, targetBackBufferPosition)) {
this.hls.trigger(events["default"].LIVE_BACK_BUFFER_REACHED, {
bufferEnd: targetBackBufferPosition
});
}
}
}
}
};
_proto.onLevelUpdated = function onLevelUpdated(_ref) {
var details = _ref.details;
if (details.fragments.length > 0) {
this._levelDuration = details.totalduration + details.fragments[0].start;
this._levelTargetDuration = details.averagetargetduration || details.targetduration || 10;
this._live = details.live;
this.updateMediaElementDuration();
if (this.config.liveDurationInfinity) {
this.updateSeekableRange(details);
}
}
}
/**
* Update Media Source duration to current level duration or override to Infinity if configuration parameter
* 'liveDurationInfinity` is set to `true`
* More details: https://github.com/video-dev/hls.js/issues/355
*/
;
_proto.updateMediaElementDuration = function updateMediaElementDuration() {
var config = this.config;
var duration;
if (this._levelDuration === null || !this.media || !this.mediaSource || !this.sourceBuffer || this.media.readyState === 0 || this.mediaSource.readyState !== 'open') {
return;
}
for (var type in this.sourceBuffer) {
var sb = this.sourceBuffer[type];
if (sb && sb.updating === true) {
// can't set duration whilst a buffer is updating
return;
}
}
duration = this.media.duration; // initialise to the value that the media source is reporting
if (this._msDuration === null) {
this._msDuration = this.mediaSource.duration;
}
if (this._live === true && config.liveDurationInfinity) {
// Override duration to Infinity
logger["logger"].log('Media Source duration is set to Infinity');
this._msDuration = this.mediaSource.duration = Infinity;
} else if (this._levelDuration > this._msDuration && this._levelDuration > duration || !Object(number["isFiniteNumber"])(duration)) {
// levelDuration was the last value we set.
// not using mediaSource.duration as the browser may tweak this value
// only update Media Source duration if its value increase, this is to avoid
// flushing already buffered portion when switching between quality level
logger["logger"].log("Updating Media Source duration to " + this._levelDuration.toFixed(3));
this._msDuration = this.mediaSource.duration = this._levelDuration;
}
};
_proto.updateSeekableRange = function updateSeekableRange(levelDetails) {
var mediaSource = this.mediaSource;
var fragments = levelDetails.fragments;
var len = fragments.length;
if (len && (mediaSource === null || mediaSource === void 0 ? void 0 : mediaSource.setLiveSeekableRange)) {
var _fragments$;
var start = (_fragments$ = fragments[0]) === null || _fragments$ === void 0 ? void 0 : _fragments$.start;
var end = fragments[len - 1].start + fragments[len - 1].duration;
mediaSource.setLiveSeekableRange(start, end);
}
};
_proto.doFlush = function doFlush() {
// loop through all buffer ranges to flush
while (this.flushRange.length) {
var range = this.flushRange[0]; // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
if (this.flushBuffer(range.start, range.end, range.type)) {
// range flushed, remove from flush array
this.flushRange.shift();
this.flushBufferCounter = 0;
} else {
this._needsFlush = true; // avoid looping, wait for SB update end to retrigger a flush
return;
}
}
if (this.flushRange.length === 0) {
// everything flushed
this._needsFlush = false; // let's recompute this.appended, which is used to avoid flush looping
var appended = 0;
var sourceBuffer = this.sourceBuffer;
for (var type in sourceBuffer) {
var sb = sourceBuffer[type];
if (sb) {
appended += buffer_helper_BufferHelper.getBuffered(sb).length;
}
}
this.appended = appended;
this.hls.trigger(events["default"].BUFFER_FLUSHED);
}
};
_proto.doAppending = function doAppending() {
var config = this.config,
hls = this.hls,
segments = this.segments,
sourceBuffer = this.sourceBuffer;
if (!Object.keys(sourceBuffer).length) {
// early exit if no source buffers have been initialized yet
return;
}
if (!this.media || this.media.error) {
this.segments = [];
logger["logger"].error('trying to append although a media error occured, flush segment and abort');
return;
}
if (this.appending) {
// logger.log(`sb appending in progress`);
return;
}
var segment = segments.shift();
if (!segment) {
// handle undefined shift
return;
}
try {
var sb = sourceBuffer[segment.type];
if (!sb) {
// in case we don't have any source buffer matching with this segment type,
// it means that Mediasource fails to create sourcebuffer
// discard this segment, and trigger update end
this._onSBUpdateEnd();
return;
}
if (sb.updating) {
// if we are still updating the source buffer from the last segment, place this back at the front of the queue
segments.unshift(segment);
return;
} // reset sourceBuffer ended flag before appending segment
sb.ended = false; // logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);
this.parent = segment.parent;
sb.appendBuffer(segment.data);
this.appendError = 0;
this.appended++;
this.appending = true;
} catch (err) {
// in case any error occured while appending, put back segment in segments table
logger["logger"].error("error while trying to append buffer:" + err.message);
segments.unshift(segment);
var event = {
type: errors["ErrorTypes"].MEDIA_ERROR,
parent: segment.parent,
details: '',
fatal: false
};
if (err.code === 22) {
// QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
// let's stop appending any segments, and report BUFFER_FULL_ERROR error
this.segments = [];
event.details = errors["ErrorDetails"].BUFFER_FULL_ERROR;
} else {
this.appendError++;
event.details = errors["ErrorDetails"].BUFFER_APPEND_ERROR;
/* with UHD content, we could get loop of quota exceeded error until
browser is able to evict some data from sourcebuffer. retrying help recovering this
*/
if (this.appendError > config.appendErrorMaxRetry) {
logger["logger"].log("fail " + config.appendErrorMaxRetry + " times to append segment in sourceBuffer");
this.segments = [];
event.fatal = true;
}
}
hls.trigger(events["default"].ERROR, event);
}
}
/*
flush specified buffered range,
return true once range has been flushed.
as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
*/
;
_proto.flushBuffer = function flushBuffer(startOffset, endOffset, sbType) {
var sourceBuffer = this.sourceBuffer; // exit if no sourceBuffers are initialized
if (!Object.keys(sourceBuffer).length) {
return true;
}
var currentTime = 'null';
if (this.media) {
currentTime = this.media.currentTime.toFixed(3);
}
logger["logger"].log("flushBuffer,pos/start/end: " + currentTime + "/" + startOffset + "/" + endOffset); // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
if (this.flushBufferCounter >= this.appended) {
logger["logger"].warn('abort flushing too many retries');
return true;
}
var sb = sourceBuffer[sbType]; // we are going to flush buffer, mark source buffer as 'not ended'
if (sb) {
sb.ended = false;
if (!sb.updating) {
if (this.removeBufferRange(sbType, sb, startOffset, endOffset)) {
this.flushBufferCounter++;
return false;
}
} else {
logger["logger"].warn('cannot flush, sb updating in progress');
return false;
}
}
logger["logger"].log('buffer flushed'); // everything flushed !
return true;
}
/**
* Removes first buffered range from provided source buffer that lies within given start and end offsets.
*
* @param {string} type Type of the source buffer, logging purposes only.
* @param {SourceBuffer} sb Target SourceBuffer instance.
* @param {number} startOffset
* @param {number} endOffset
*
* @returns {boolean} True when source buffer remove requested.
*/
;
_proto.removeBufferRange = function removeBufferRange(type, sb, startOffset, endOffset) {
try {
var buffered = buffer_helper_BufferHelper.getBuffered(sb);
for (var i = 0; i < buffered.length; i++) {
var bufStart = buffered.start(i);
var bufEnd = buffered.end(i);
var removeStart = Math.max(bufStart, startOffset);
var removeEnd = Math.min(bufEnd, endOffset);
/* sometimes sourcebuffer.remove() does not flush
the exact expected time range.
to avoid rounding issues/infinite loop,
only flush buffer range of length greater than 500ms.
*/
if (Math.min(removeEnd, bufEnd) - removeStart > 0.5) {
var currentTime = 'null';
if (this.media) {
currentTime = this.media.currentTime.toString();
}
logger["logger"].log("sb remove " + type + " [" + removeStart + "," + removeEnd + "], of [" + bufStart + "," + bufEnd + "], pos:" + currentTime);
sb.remove(removeStart, removeEnd);
return true;
}
}
} catch (error) {
logger["logger"].warn('removeBufferRange failed', error);
}
return false;
};
return BufferController;
}(event_handler);
/* harmony default export */ var buffer_controller = (buffer_controller_BufferController);
// CONCATENATED MODULE: ./src/controller/cap-level-controller.js
function cap_level_controller_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function cap_level_controller_createClass(Constructor, protoProps, staticProps) { if (protoProps) cap_level_controller_defineProperties(Constructor.prototype, protoProps); if (staticProps) cap_level_controller_defineProperties(Constructor, staticProps); return Constructor; }
function cap_level_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/*
* cap stream level to media size dimension controller
*/
var cap_level_controller_CapLevelController = /*#__PURE__*/function (_EventHandler) {
cap_level_controller_inheritsLoose(CapLevelController, _EventHandler);
function CapLevelController(hls) {
var _this;
_this = _EventHandler.call(this, hls, events["default"].FPS_DROP_LEVEL_CAPPING, events["default"].MEDIA_ATTACHING, events["default"].MANIFEST_PARSED, events["default"].LEVELS_UPDATED, events["default"].BUFFER_CODECS, events["default"].MEDIA_DETACHING) || this;
_this.autoLevelCapping = Number.POSITIVE_INFINITY;
_this.firstLevel = null;
_this.levels = [];
_this.media = null;
_this.restrictedLevels = [];
_this.timer = null;
_this.clientRect = null;
return _this;
}
var _proto = CapLevelController.prototype;
_proto.destroy = function destroy() {
if (this.hls.config.capLevelToPlayerSize) {
this.media = null;
this.clientRect = null;
this.stopCapping();
}
};
_proto.onFpsDropLevelCapping = function onFpsDropLevelCapping(data) {
// Don't add a restricted level more than once
if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
this.restrictedLevels.push(data.droppedLevel);
}
};
_proto.onMediaAttaching = function onMediaAttaching(data) {
this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;
};
_proto.onManifestParsed = function onManifestParsed(data) {
var hls = this.hls;
this.restrictedLevels = [];
this.levels = data.levels;
this.firstLevel = data.firstLevel;
if (hls.config.capLevelToPlayerSize && data.video) {
// Start capping immediately if the manifest has signaled video codecs
this.startCapping();
}
} // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
// to the first level
;
_proto.onBufferCodecs = function onBufferCodecs(data) {
var hls = this.hls;
if (hls.config.capLevelToPlayerSize && data.video) {
// If the manifest did not signal a video codec capping has been deferred until we're certain video is present
this.startCapping();
}
};
_proto.onLevelsUpdated = function onLevelsUpdated(data) {
this.levels = data.levels;
};
_proto.onMediaDetaching = function onMediaDetaching() {
this.stopCapping();
};
_proto.detectPlayerSize = function detectPlayerSize() {
if (this.media) {
var levelsLength = this.levels ? this.levels.length : 0;
if (levelsLength) {
var hls = this.hls;
hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
if (hls.autoLevelCapping > this.autoLevelCapping) {
// if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
// usually happen when the user go to the fullscreen mode.
hls.streamController.nextLevelSwitch();
}
this.autoLevelCapping = hls.autoLevelCapping;
}
}
}
/*
* returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
*/
;
_proto.getMaxLevel = function getMaxLevel(capLevelIndex) {
var _this2 = this;
if (!this.levels) {
return -1;
}
var validLevels = this.levels.filter(function (level, index) {
return CapLevelController.isLevelAllowed(index, _this2.restrictedLevels) && index <= capLevelIndex;
});
this.clientRect = null;
return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
};
_proto.startCapping = function startCapping() {
if (this.timer) {
// Don't reset capping if started twice; this can happen if the manifest signals a video codec
return;
}
this.autoLevelCapping = Number.POSITIVE_INFINITY;
this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
clearInterval(this.timer);
this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
this.detectPlayerSize();
};
_proto.stopCapping = function stopCapping() {
this.restrictedLevels = [];
this.firstLevel = null;
this.autoLevelCapping = Number.POSITIVE_INFINITY;
if (this.timer) {
this.timer = clearInterval(this.timer);
this.timer = null;
}
};
_proto.getDimensions = function getDimensions() {
if (this.clientRect) {
return this.clientRect;
}
var media = this.media;
var boundsRect = {
width: 0,
height: 0
};
if (media) {
var clientRect = media.getBoundingClientRect();
boundsRect.width = clientRect.width;
boundsRect.height = clientRect.height;
if (!boundsRect.width && !boundsRect.height) {
// When the media element has no width or height (equivalent to not being in the DOM),
// then use its width and height attributes (media.width, media.height)
boundsRect.width = clientRect.right - clientRect.left || media.width || 0;
boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;
}
}
this.clientRect = boundsRect;
return boundsRect;
};
CapLevelController.isLevelAllowed = function isLevelAllowed(level, restrictedLevels) {
if (restrictedLevels === void 0) {
restrictedLevels = [];
}
return restrictedLevels.indexOf(level) === -1;
};
CapLevelController.getMaxLevelByMediaSize = function getMaxLevelByMediaSize(levels, width, height) {
if (!levels || levels && !levels.length) {
return -1;
} // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
// to determine whether we've chosen the greatest bandwidth for the media's dimensions
var atGreatestBandiwdth = function atGreatestBandiwdth(curLevel, nextLevel) {
if (!nextLevel) {
return true;
}
return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
}; // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
// the max level
var maxLevelIndex = levels.length - 1;
for (var i = 0; i < levels.length; i += 1) {
var level = levels[i];
if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
maxLevelIndex = i;
break;
}
}
return maxLevelIndex;
};
cap_level_controller_createClass(CapLevelController, [{
key: "mediaWidth",
get: function get() {
return this.getDimensions().width * CapLevelController.contentScaleFactor;
}
}, {
key: "mediaHeight",
get: function get() {
return this.getDimensions().height * CapLevelController.contentScaleFactor;
}
}], [{
key: "contentScaleFactor",
get: function get() {
var pixelRatio = 1;
try {
pixelRatio = window.devicePixelRatio;
} catch (e) {}
return pixelRatio;
}
}]);
return CapLevelController;
}(event_handler);
/* harmony default export */ var cap_level_controller = (cap_level_controller_CapLevelController);
// CONCATENATED MODULE: ./src/controller/fps-controller.js
function fps_controller_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/*
* FPS Controller
*/
var fps_controller_window = window,
fps_controller_performance = fps_controller_window.performance;
var fps_controller_FPSController = /*#__PURE__*/function (_EventHandler) {
fps_controller_inheritsLoose(FPSController, _EventHandler);
function FPSController(hls) {
return _EventHandler.call(this, hls, events["default"].MEDIA_ATTACHING) || this;
}
var _proto = FPSController.prototype;
_proto.destroy = function destroy() {
if (this.timer) {
clearInterval(this.timer);
}
this.isVideoPlaybackQualityAvailable = false;
};
_proto.onMediaAttaching = function onMediaAttaching(data) {
var config = this.hls.config;
if (config.capLevelOnFPSDrop) {
var video = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;
if (typeof video.getVideoPlaybackQuality === 'function') {
this.isVideoPlaybackQualityAvailable = true;
}
clearInterval(this.timer);
this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
}
};
_proto.checkFPS = function checkFPS(video, decodedFrames, droppedFrames) {
var currentTime = fps_controller_performance.now();
if (decodedFrames) {
if (this.lastTime) {
var currentPeriod = currentTime - this.lastTime,
currentDropped = droppedFrames - this.lastDroppedFrames,
currentDecoded = decodedFrames - this.lastDecodedFrames,
droppedFPS = 1000 * currentDropped / currentPeriod,
hls = this.hls;
hls.trigger(events["default"].FPS_DROP, {
currentDropped: currentDropped,
currentDecoded: currentDecoded,
totalDroppedFrames: droppedFrames
});
if (droppedFPS > 0) {
// logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {
var currentLevel = hls.currentLevel;
logger["logger"].warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {
currentLevel = currentLevel - 1;
hls.trigger(events["default"].FPS_DROP_LEVEL_CAPPING, {
level: currentLevel,
droppedLevel: hls.currentLevel
});
hls.autoLevelCapping = currentLevel;
hls.streamController.nextLevelSwitch();
}
}
}
}
this.lastTime = currentTime;
this.lastDroppedFrames = droppedFrames;
this.lastDecodedFrames = decodedFrames;
}
};
_proto.checkFPSInterval = function checkFPSInterval() {
var video = this.video;
if (video) {
if (this.isVideoPlaybackQualityAvailable) {
var videoPlaybackQuality = video.getVideoPlaybackQuality();
this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
} else {
this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
}
}
};
return FPSController;
}(event_handler);
/* harmony default export */ var fps_controller = (fps_controller_FPSController);
// CONCATENATED MODULE: ./src/utils/xhr-loader.js
/**
* XHR based logger
*/
var xhr_loader_XhrLoader = /*#__PURE__*/function () {
function XhrLoader(config) {
if (config && config.xhrSetup) {
this.xhrSetup = config.xhrSetup;
}
}
var _proto = XhrLoader.prototype;
_proto.destroy = function destroy() {
this.abort();
this.loader = null;
};
_proto.abort = function abort() {
var loader = this.loader;
if (loader && loader.readyState !== 4) {
this.stats.aborted = true;
loader.abort();
}
window.clearTimeout(this.requestTimeout);
this.requestTimeout = null;
window.clearTimeout(this.retryTimeout);
this.retryTimeout = null;
};
_proto.load = function load(context, config, callbacks) {
this.context = context;
this.config = config;
this.callbacks = callbacks;
this.stats = {
trequest: window.performance.now(),
retry: 0
};
this.retryDelay = config.retryDelay;
this.loadInternal();
};
_proto.loadInternal = function loadInternal() {
var xhr,
context = this.context;
xhr = this.loader = new window.XMLHttpRequest();
var stats = this.stats;
stats.tfirst = 0;
stats.loaded = 0;
var xhrSetup = this.xhrSetup;
try {
if (xhrSetup) {
try {
xhrSetup(xhr, context.url);
} catch (e) {
// fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
// not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
xhr.open('GET', context.url, true);
xhrSetup(xhr, context.url);
}
}
if (!xhr.readyState) {
xhr.open('GET', context.url, true);
}
} catch (e) {
// IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
this.callbacks.onError({
code: xhr.status,
text: e.message
}, context, xhr);
return;
}
if (context.rangeEnd) {
xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
}
xhr.onreadystatechange = this.readystatechange.bind(this);
xhr.onprogress = this.loadprogress.bind(this);
xhr.responseType = context.responseType; // setup timeout before we perform request
this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);
xhr.send();
};
_proto.readystatechange = function readystatechange(event) {
var xhr = event.currentTarget,
readyState = xhr.readyState,
stats = this.stats,
context = this.context,
config = this.config; // don't proceed if xhr has been aborted
if (stats.aborted) {
return;
} // >= HEADERS_RECEIVED
if (readyState >= 2) {
// clear xhr timeout and rearm it if readyState less than 4
window.clearTimeout(this.requestTimeout);
if (stats.tfirst === 0) {
stats.tfirst = Math.max(window.performance.now(), stats.trequest);
}
if (readyState === 4) {
var status = xhr.status; // http status between 200 to 299 are all successful
if (status >= 200 && status < 300) {
stats.tload = Math.max(stats.tfirst, window.performance.now());
var data, len;
if (context.responseType === 'arraybuffer') {
data = xhr.response;
len = data.byteLength;
} else {
data = xhr.responseText;
len = data.length;
}
stats.loaded = stats.total = len;
var response = {
url: xhr.responseURL,
data: data
};
this.callbacks.onSuccess(response, stats, context, xhr);
} else {
// if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
if (stats.retry >= config.maxRetry || status >= 400 && status < 499) {
logger["logger"].error(status + " while loading " + context.url);
this.callbacks.onError({
code: status,
text: xhr.statusText
}, context, xhr);
} else {
// retry
logger["logger"].warn(status + " while loading " + context.url + ", retrying in " + this.retryDelay + "..."); // aborts and resets internal state
this.destroy(); // schedule retry
this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay); // set exponential backoff
this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
stats.retry++;
}
}
} else {
// readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);
}
}
};
_proto.loadtimeout = function loadtimeout() {
logger["logger"].warn("timeout while loading " + this.context.url);
this.callbacks.onTimeout(this.stats, this.context, null);
};
_proto.loadprogress = function loadprogress(event) {
var xhr = event.currentTarget,
stats = this.stats;
stats.loaded = event.loaded;
if (event.lengthComputable) {
stats.total = event.total;
}
var onProgress = this.callbacks.onProgress;
if (onProgress) {
// third arg is to provide on progress data
onProgress(stats, this.context, null, xhr);
}
};
return XhrLoader;
}();
/* harmony default export */ var xhr_loader = (xhr_loader_XhrLoader);
// EXTERNAL MODULE: ./src/empty.js
var empty = __webpack_require__("./src/empty.js");
// CONCATENATED MODULE: ./src/utils/mediakeys-helper.ts
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
*/
var KeySystems;
(function (KeySystems) {
KeySystems["WIDEVINE"] = "com.widevine.alpha";
KeySystems["PLAYREADY"] = "com.microsoft.playready";
})(KeySystems || (KeySystems = {}));
var requestMediaKeySystemAccess = function () {
if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {
return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);
} else {
return null;
}
}();
// CONCATENATED MODULE: ./src/config.ts
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* HLS config
*/
// import FetchLoader from './utils/fetch-loader';
function timelineConfig() {
return {
cueHandler: empty,
// used by timeline-controller
enableCEA708Captions: false,
// used by timeline-controller
enableWebVTT: false,
// used by timeline-controller
captionsTextTrack1Label: 'English',
// used by timeline-controller
captionsTextTrack1LanguageCode: 'en',
// used by timeline-controller
captionsTextTrack2Label: 'Spanish',
// used by timeline-controller
captionsTextTrack2LanguageCode: 'es',
// used by timeline-controller
captionsTextTrack3Label: 'Unknown CC',
// used by timeline-controller
captionsTextTrack3LanguageCode: '',
// used by timeline-controller
captionsTextTrack4Label: 'Unknown CC',
// used by timeline-controller
captionsTextTrack4LanguageCode: '',
// used by timeline-controller
renderTextTracksNatively: true
};
} // If possible, keep hlsDefaultConfig shallow
// It is cloned whenever a new Hls instance is created, by keeping the config
// shallow the properties are cloned, and we don't end up manipulating the default
var hlsDefaultConfig = _objectSpread(_objectSpread({
autoStartLoad: true,
// used by stream-controller
startPosition: -1,
// used by stream-controller
defaultAudioCodec: void 0,
// used by stream-controller
debug: false,
// used by logger
capLevelOnFPSDrop: false,
// used by fps-controller
capLevelToPlayerSize: false,
// used by cap-level-controller
initialLiveManifestSize: 1,
// used by stream-controller
maxBufferLength: 30,
// used by stream-controller
maxBufferSize: 60 * 1000 * 1000,
// used by stream-controller
maxBufferHole: 0.5,
// used by stream-controller
lowBufferWatchdogPeriod: 0.5,
// used by stream-controller
highBufferWatchdogPeriod: 3,
// used by stream-controller
nudgeOffset: 0.1,
// used by stream-controller
nudgeMaxRetry: 3,
// used by stream-controller
maxFragLookUpTolerance: 0.25,
// used by stream-controller
liveSyncDurationCount: 3,
// used by stream-controller
liveMaxLatencyDurationCount: Infinity,
// used by stream-controller
liveSyncDuration: void 0,
// used by stream-controller
liveMaxLatencyDuration: void 0,
// used by stream-controller
liveDurationInfinity: false,
// used by buffer-controller
liveBackBufferLength: Infinity,
// used by buffer-controller
maxMaxBufferLength: 600,
// used by stream-controller
enableWorker: true,
// used by demuxer
enableSoftwareAES: true,
// used by decrypter
manifestLoadingTimeOut: 10000,
// used by playlist-loader
manifestLoadingMaxRetry: 1,
// used by playlist-loader
manifestLoadingRetryDelay: 1000,
// used by playlist-loader
manifestLoadingMaxRetryTimeout: 64000,
// used by playlist-loader
startLevel: void 0,
// used by level-controller
levelLoadingTimeOut: 10000,
// used by playlist-loader
levelLoadingMaxRetry: 4,
// used by playlist-loader
levelLoadingRetryDelay: 1000,
// used by playlist-loader
levelLoadingMaxRetryTimeout: 64000,
// used by playlist-loader
fragLoadingTimeOut: 20000,
// used by fragment-loader
fragLoadingMaxRetry: 6,
// used by fragment-loader
fragLoadingRetryDelay: 1000,
// used by fragment-loader
fragLoadingMaxRetryTimeout: 64000,
// used by fragment-loader
startFragPrefetch: false,
// used by stream-controller
fpsDroppedMonitoringPeriod: 5000,
// used by fps-controller
fpsDroppedMonitoringThreshold: 0.2,
// used by fps-controller
appendErrorMaxRetry: 3,
// used by buffer-controller
loader: xhr_loader,
// loader: FetchLoader,
fLoader: void 0,
// used by fragment-loader
pLoader: void 0,
// used by playlist-loader
xhrSetup: void 0,
// used by xhr-loader
licenseXhrSetup: void 0,
// used by eme-controller
// fetchSetup: void 0,
abrController: abr_controller,
bufferController: buffer_controller,
capLevelController: cap_level_controller,
fpsController: fps_controller,
stretchShortVideoTrack: false,
// used by mp4-remuxer
maxAudioFramesDrift: 1,
// used by mp4-remuxer
forceKeyFrameOnDiscontinuity: true,
// used by ts-demuxer
abrEwmaFastLive: 3,
// used by abr-controller
abrEwmaSlowLive: 9,
// used by abr-controller
abrEwmaFastVoD: 3,
// used by abr-controller
abrEwmaSlowVoD: 9,
// used by abr-controller
abrEwmaDefaultEstimate: 5e5,
// 500 kbps // used by abr-controller
abrBandWidthFactor: 0.95,
// used by abr-controller
abrBandWidthUpFactor: 0.7,
// used by abr-controller
abrMaxWithRealBitrate: false,
// used by abr-controller
maxStarvationDelay: 4,
// used by abr-controller
maxLoadingDelay: 4,
// used by abr-controller
minAutoBitrate: 0,
// used by hls
emeEnabled: false,
// used by eme-controller
widevineLicenseUrl: void 0,
// used by eme-controller
drmSystemOptions: {},
// used by eme-controller
requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess,
// used by eme-controller
testBandwidth: true
}, timelineConfig()), {}, {
subtitleStreamController: false ? undefined : void 0,
subtitleTrackController: false ? undefined : void 0,
timelineController: false ? undefined : void 0,
audioStreamController: false ? undefined : void 0,
audioTrackController: false ? undefined : void 0,
emeController: false ? undefined : void 0
});
// CONCATENATED MODULE: ./src/hls.ts
function hls_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function hls_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { hls_ownKeys(Object(source), true).forEach(function (key) { hls_defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { hls_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function hls_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function hls_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function hls_defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function hls_createClass(Constructor, protoProps, staticProps) { if (protoProps) hls_defineProperties(Constructor.prototype, protoProps); if (staticProps) hls_defineProperties(Constructor, staticProps); return Constructor; }
function hls_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
/**
* @module Hls
* @class
* @constructor
*/
var hls_Hls = /*#__PURE__*/function (_Observer) {
hls_inheritsLoose(Hls, _Observer);
/**
* @type {boolean}
*/
Hls.isSupported = function isSupported() {
return is_supported_isSupported();
}
/**
* @type {HlsEvents}
*/
;
hls_createClass(Hls, null, [{
key: "version",
/**
* @type {string}
*/
get: function get() {
return "0.14.17-0.alpha.6015";
}
}, {
key: "Events",
get: function get() {
return events["default"];
}
/**
* @type {HlsErrorTypes}
*/
}, {
key: "ErrorTypes",
get: function get() {
return errors["ErrorTypes"];
}
/**
* @type {HlsErrorDetails}
*/
}, {
key: "ErrorDetails",
get: function get() {
return errors["ErrorDetails"];
}
/**
* @type {HlsConfig}
*/
}, {
key: "DefaultConfig",
get: function get() {
if (!Hls.defaultConfig) {
return hlsDefaultConfig;
}
return Hls.defaultConfig;
}
/**
* @type {HlsConfig}
*/
,
set: function set(defaultConfig) {
Hls.defaultConfig = defaultConfig;
}
/**
* Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
*
* @constructs Hls
* @param {HlsConfig} config
*/
}]);
function Hls(userConfig) {
var _this;
if (userConfig === void 0) {
userConfig = {};
}
_this = _Observer.call(this) || this;
_this.config = void 0;
_this._autoLevelCapping = void 0;
_this.abrController = void 0;
_this.capLevelController = void 0;
_this.levelController = void 0;
_this.streamController = void 0;
_this.networkControllers = void 0;
_this.audioTrackController = void 0;
_this.subtitleTrackController = void 0;
_this.emeController = void 0;
_this.coreComponents = void 0;
_this.media = null;
_this.url = null;
var defaultConfig = Hls.DefaultConfig;
if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {
throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
} // Shallow clone
_this.config = hls_objectSpread(hls_objectSpread({}, defaultConfig), userConfig);
var _assertThisInitialize = hls_assertThisInitialized(_this),
config = _assertThisInitialize.config;
if (config.liveMaxLatencyDurationCount !== void 0 && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
}
if (config.liveMaxLatencyDuration !== void 0 && (config.liveSyncDuration === void 0 || config.liveMaxLatencyDuration <= config.liveSyncDuration)) {
throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
}
Object(logger["enableLogs"])(config.debug);
_this._autoLevelCapping = -1; // core controllers and network loaders
/**
* @member {AbrController} abrController
*/
var abrController = _this.abrController = new config.abrController(hls_assertThisInitialized(_this)); // eslint-disable-line new-cap
var bufferController = new config.bufferController(hls_assertThisInitialized(_this)); // eslint-disable-line new-cap
var capLevelController = _this.capLevelController = new config.capLevelController(hls_assertThisInitialized(_this)); // eslint-disable-line new-cap
var fpsController = new config.fpsController(hls_assertThisInitialized(_this)); // eslint-disable-line new-cap
var playListLoader = new playlist_loader(hls_assertThisInitialized(_this));
var fragmentLoader = new fragment_loader(hls_assertThisInitialized(_this));
var keyLoader = new key_loader(hls_assertThisInitialized(_this));
var id3TrackController = new id3_track_controller(hls_assertThisInitialized(_this)); // network controllers
/**
* @member {LevelController} levelController
*/
var levelController = _this.levelController = new level_controller_LevelController(hls_assertThisInitialized(_this)); // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important
var fragmentTracker = new fragment_tracker_FragmentTracker(hls_assertThisInitialized(_this));
/**
* @member {StreamController} streamController
*/
var streamController = _this.streamController = new stream_controller(hls_assertThisInitialized(_this), fragmentTracker);
var networkControllers = [levelController, streamController]; // optional audio stream controller
/**
* @var {ICoreComponent | Controller}
*/
var Controller = config.audioStreamController;
if (Controller) {
networkControllers.push(new Controller(hls_assertThisInitialized(_this), fragmentTracker));
}
/**
* @member {INetworkController[]} networkControllers
*/
_this.networkControllers = networkControllers;
/**
* @var {ICoreComponent[]}
*/
var coreComponents = [playListLoader, fragmentLoader, keyLoader, abrController, bufferController, capLevelController, fpsController, id3TrackController, fragmentTracker]; // optional audio track and subtitle controller
Controller = config.audioTrackController;
if (Controller) {
var audioTrackController = new Controller(hls_assertThisInitialized(_this));
/**
* @member {AudioTrackController} audioTrackController
*/
_this.audioTrackController = audioTrackController;
coreComponents.push(audioTrackController);
}
Controller = config.subtitleTrackController;
if (Controller) {
var subtitleTrackController = new Controller(hls_assertThisInitialized(_this));
/**
* @member {SubtitleTrackController} subtitleTrackController
*/
_this.subtitleTrackController = subtitleTrackController;
networkControllers.push(subtitleTrackController);
}
Controller = config.emeController;
if (Controller) {
var emeController = new Controller(hls_assertThisInitialized(_this));
/**
* @member {EMEController} emeController
*/
_this.emeController = emeController;
coreComponents.push(emeController);
} // optional subtitle controllers
Controller = config.subtitleStreamController;
if (Controller) {
networkControllers.push(new Controller(hls_assertThisInitialized(_this), fragmentTracker));
}
Controller = config.timelineController;
if (Controller) {
coreComponents.push(new Controller(hls_assertThisInitialized(_this)));
}
/**
* @member {ICoreComponent[]}
*/
_this.coreComponents = coreComponents;
return _this;
}
/**
* Dispose of the instance
*/
var _proto = Hls.prototype;
_proto.destroy = function destroy() {
logger["logger"].log('destroy');
this.trigger(events["default"].DESTROYING);
this.detachMedia();
this.coreComponents.concat(this.networkControllers).forEach(function (component) {
component.destroy();
});
this.url = null;
this.removeAllListeners();
this._autoLevelCapping = -1;
}
/**
* Attach a media element
* @param {HTMLMediaElement} media
*/
;
_proto.attachMedia = function attachMedia(media) {
logger["logger"].log('attachMedia');
this.media = media;
this.trigger(events["default"].MEDIA_ATTACHING, {
media: media
});
}
/**
* Detach from the media
*/
;
_proto.detachMedia = function detachMedia() {
logger["logger"].log('detachMedia');
this.trigger(events["default"].MEDIA_DETACHING);
this.media = null;
}
/**
* Set the source URL. Can be relative or absolute.
* @param {string} url
*/
;
_proto.loadSource = function loadSource(url) {
this.stopLoad();
var media = this.media;
if (media && this.url) {
this.detachMedia();
this.attachMedia(media);
}
url = url_toolkit["buildAbsoluteURL"](window.location.href, url, {
alwaysNormalize: true
});
logger["logger"].log("loadSource:" + url);
this.url = url; // when attaching to a source URL, trigger a playlist load
this.trigger(events["default"].MANIFEST_LOADING, {
url: url
});
}
/**
* Start loading data from the stream source.
* Depending on default config, client starts loading automatically when a source is set.
*
* @param {number} startPosition Set the start position to stream from
* @default -1 None (from earliest point)
*/
;
_proto.startLoad = function startLoad(startPosition) {
if (startPosition === void 0) {
startPosition = -1;
}
logger["logger"].log("startLoad(" + startPosition + ")");
this.networkControllers.forEach(function (controller) {
controller.startLoad(startPosition);
});
}
/**
* Stop loading of any stream data.
*/
;
_proto.stopLoad = function stopLoad() {
logger["logger"].log('stopLoad');
this.networkControllers.forEach(function (controller) {
controller.stopLoad();
});
}
/**
* Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
*/
;
_proto.swapAudioCodec = function swapAudioCodec() {
logger["logger"].log('swapAudioCodec');
this.streamController.swapAudioCodec();
}
/**
* When the media-element fails, this allows to detach and then re-attach it
* as one call (convenience method).
*
* Automatic recovery of media-errors by this process is configurable.
*/
;
_proto.recoverMediaError = function recoverMediaError() {
logger["logger"].log('recoverMediaError');
var media = this.media;
this.detachMedia();
if (media) {
this.attachMedia(media);
}
}
/**
* Remove a loaded level from the list of levels, or a level url in from a list of redundant level urls.
* This can be used to remove a rendition or playlist url that errors frequently from the list of levels that a user
* or hls.js can choose from.
*
* @param levelIndex {number} The quality level index to of the level to remove
* @param urlId {number} The quality level url index in the case that fallback levels are available. Defaults to 0.
*/
;
_proto.removeLevel = function removeLevel(levelIndex, urlId) {
if (urlId === void 0) {
urlId = 0;
}
this.levelController.removeLevel(levelIndex, urlId);
}
/**
* @type {QualityLevel[]}
*/
// todo(typescript-levelController)
;
hls_createClass(Hls, [{
key: "levels",
get: function get() {
return this.levelController.levels;
}
/**
* Index of quality level currently played
* @type {number}
*/
}, {
key: "currentLevel",
get: function get() {
return this.streamController.currentLevel;
}
/**
* Set quality level index immediately .
* This will flush the current buffer to replace the quality asap.
* That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
* @param newLevel {number} -1 for automatic level selection
*/
,
set: function set(newLevel) {
logger["logger"].log("set currentLevel:" + newLevel);
this.loadLevel = newLevel;
this.streamController.immediateLevelSwitch();
}
/**
* Index of next quality level loaded as scheduled by stream controller.
* @type {number}
*/
}, {
key: "nextLevel",
get: function get() {
return this.streamController.nextLevel;
}
/**
* Set quality level index for next loaded data.
* This will switch the video quality asap, without interrupting playback.
* May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
* @type {number} -1 for automatic level selection
*/
,
set: function set(newLevel) {
logger["logger"].log("set nextLevel:" + newLevel);
this.levelController.manualLevel = newLevel;
this.streamController.nextLevelSwitch();
}
/**
* Return the quality level of the currently or last (of none is loaded currently) segment
* @type {number}
*/
}, {
key: "loadLevel",
get: function get() {
return this.levelController.level;
}
/**
* Set quality level index for next loaded data in a conservative way.
* This will switch the quality without flushing, but interrupt current loading.
* Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
* @type {number} newLevel -1 for automatic level selection
*/
,
set: function set(newLevel) {
logger["logger"].log("set loadLevel:" + newLevel);
this.levelController.manualLevel = newLevel;
}
/**
* get next quality level loaded
* @type {number}
*/
}, {
key: "nextLoadLevel",
get: function get() {
return this.levelController.nextLoadLevel;
}
/**
* Set quality level of next loaded segment in a fully "non-destructive" way.
* Same as `loadLevel` but will wait for next switch (until current loading is done).
* @type {number} level
*/
,
set: function set(level) {
this.levelController.nextLoadLevel = level;
}
/**
* Return "first level": like a default level, if not set,
* falls back to index of first level referenced in manifest
* @type {number}
*/
}, {
key: "firstLevel",
get: function get() {
return Math.max(this.levelController.firstLevel, this.minAutoLevel);
}
/**
* Sets "first-level", see getter.
* @type {number}
*/
,
set: function set(newLevel) {
logger["logger"].log("set firstLevel:" + newLevel);
this.levelController.firstLevel = newLevel;
}
/**
* Return start level (level of first fragment that will be played back)
* if not overrided by user, first level appearing in manifest will be used as start level
* if -1 : automatic start level selection, playback will start from level matching download bandwidth
* (determined from download of first segment)
* @type {number}
*/
}, {
key: "startLevel",
get: function get() {
return this.levelController.startLevel;
}
/**
* set start level (level of first fragment that will be played back)
* if not overrided by user, first level appearing in manifest will be used as start level
* if -1 : automatic start level selection, playback will start from level matching download bandwidth
* (determined from download of first segment)
* @type {number} newLevel
*/
,
set: function set(newLevel) {
logger["logger"].log("set startLevel:" + newLevel); // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
if (newLevel !== -1) {
newLevel = Math.max(newLevel, this.minAutoLevel);
}
this.levelController.startLevel = newLevel;
}
/**
* Get the current setting for capLevelToPlayerSize
*
* @type {boolean}
*/
}, {
key: "capLevelToPlayerSize",
get: function get() {
return this.config.capLevelToPlayerSize;
}
/**
* set dynamically set capLevelToPlayerSize against (`CapLevelController`)
*
* @type {boolean}
*/
,
set: function set(shouldStartCapping) {
var newCapLevelToPlayerSize = !!shouldStartCapping;
if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {
if (newCapLevelToPlayerSize) {
this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.
} else {
this.capLevelController.stopCapping();
this.autoLevelCapping = -1;
this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.
}
this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;
}
}
/**
* Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
* @type {number}
*/
}, {
key: "autoLevelCapping",
get: function get() {
return this._autoLevelCapping;
}
/**
* get bandwidth estimate
* @type {number}
*/
,
/**
* Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
* @type {number}
*/
set: function set(newLevel) {
logger["logger"].log("set autoLevelCapping:" + newLevel);
this._autoLevelCapping = newLevel;
}
/**
* True when automatic level selection enabled
* @type {boolean}
*/
}, {
key: "bandwidthEstimate",
get: function get() {
var bwEstimator = this.abrController._bwEstimator;
return bwEstimator ? bwEstimator.getEstimate() : NaN;
}
}, {
key: "autoLevelEnabled",
get: function get() {
return this.levelController.manualLevel === -1;
}
/**
* Level set manually (if any)
* @type {number}
*/
}, {
key: "manualLevel",
get: function get() {
return this.levelController.manualLevel;
}
/**
* min level selectable in auto mode according to config.minAutoBitrate
* @type {number}
*/
}, {
key: "minAutoLevel",
get: function get() {
var levels = this.levels,
minAutoBitrate = this.config.minAutoBitrate;
var len = levels ? levels.length : 0;
for (var i = 0; i < len; i++) {
var levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
if (levelNextBitrate > minAutoBitrate) {
return i;
}
}
return 0;
}
/**
* max level selectable in auto mode according to autoLevelCapping
* @type {number}
*/
}, {
key: "maxAutoLevel",
get: function get() {
var levels = this.levels,
autoLevelCapping = this.autoLevelCapping;
var maxAutoLevel;
if (autoLevelCapping === -1 && levels && levels.length) {
maxAutoLevel = levels.length - 1;
} else {
maxAutoLevel = autoLevelCapping;
}
return maxAutoLevel;
}
/**
* next automatically selected quality level
* @type {number}
*/
}, {
key: "nextAutoLevel",
get: function get() {
// ensure next auto level is between min and max auto level
return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel);
}
/**
* this setter is used to force next auto level.
* this is useful to force a switch down in auto mode:
* in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
* forced value is valid for one fragment. upon succesful frag loading at forced level,
* this value will be resetted to -1 by ABR controller.
* @type {number}
*/
,
set: function set(nextLevel) {
this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);
}
/**
* @type {AudioTrack[]}
*/
// todo(typescript-audioTrackController)
}, {
key: "audioTracks",
get: function get() {
var audioTrackController = this.audioTrackController;
return audioTrackController ? audioTrackController.audioTracks : [];
}
/**
* index of the selected audio track (index in audio track lists)
* @type {number}
*/
}, {
key: "audioTrack",
get: function get() {
var audioTrackController = this.audioTrackController;
return audioTrackController ? audioTrackController.audioTrack : -1;
}
/**
* selects an audio track, based on its index in audio track lists
* @type {number}
*/
,
set: function set(audioTrackId) {
var audioTrackController = this.audioTrackController;
if (audioTrackController) {
audioTrackController.audioTrack = audioTrackId;
}
}
/**
* @type {Seconds}
*/
}, {
key: "liveSyncPosition",
get: function get() {
return this.streamController.liveSyncPosition;
}
/**
* get alternate subtitle tracks list from playlist
* @type {SubtitleTrack[]}
*/
// todo(typescript-subtitleTrackController)
}, {
key: "subtitleTracks",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
}
/**
* index of the selected subtitle track (index in subtitle track lists)
* @type {number}
*/
}, {
key: "subtitleTrack",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
}
/**
* select an subtitle track, based on its index in subtitle track lists
* @type {number}
*/
,
set: function set(subtitleTrackId) {
var subtitleTrackController = this.subtitleTrackController;
if (subtitleTrackController) {
subtitleTrackController.subtitleTrack = subtitleTrackId;
}
}
/**
* @type {boolean}
*/
}, {
key: "subtitleDisplay",
get: function get() {
var subtitleTrackController = this.subtitleTrackController;
return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
}
/**
* Enable/disable subtitle display rendering
* @type {boolean}
*/
,
set: function set(value) {
var subtitleTrackController = this.subtitleTrackController;
if (subtitleTrackController) {
subtitleTrackController.subtitleDisplay = value;
}
}
}]);
return Hls;
}(Observer);
hls_Hls.defaultConfig = void 0;
/***/ }),
/***/ "./src/polyfills/number.js":
/*!*********************************!*\
!*** ./src/polyfills/number.js ***!
\*********************************/
/*! exports provided: isFiniteNumber, MAX_SAFE_INTEGER */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFiniteNumber", function() { return isFiniteNumber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MAX_SAFE_INTEGER", function() { return MAX_SAFE_INTEGER; });
var isFiniteNumber = Number.isFinite || function (value) {
return typeof value === 'number' && isFinite(value);
};
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
/***/ }),
/***/ "./src/utils/get-self-scope.js":
/*!*************************************!*\
!*** ./src/utils/get-self-scope.js ***!
\*************************************/
/*! exports provided: getSelfScope */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getSelfScope", function() { return getSelfScope; });
function getSelfScope() {
// see https://stackoverflow.com/a/11237259/589493
if (typeof window === 'undefined') {
/* eslint-disable-next-line no-undef */
return self;
} else {
return window;
}
}
/***/ }),
/***/ "./src/utils/logger.js":
/*!*****************************!*\
!*** ./src/utils/logger.js ***!
\*****************************/
/*! exports provided: enableLogs, logger */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "enableLogs", function() { return enableLogs; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "logger", function() { return logger; });
/* harmony import */ var _get_self_scope__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./get-self-scope */ "./src/utils/get-self-scope.js");
function noop() {}
var fakeLogger = {
trace: noop,
debug: noop,
log: noop,
warn: noop,
info: noop,
error: noop
};
var exportedLogger = fakeLogger; // let lastCallTime;
// function formatMsgWithTimeInfo(type, msg) {
// const now = Date.now();
// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
// lastCallTime = now;
// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
// return msg;
// }
function formatMsg(type, msg) {
msg = '[' + type + '] > ' + msg;
return msg;
}
var global = Object(_get_self_scope__WEBPACK_IMPORTED_MODULE_0__["getSelfScope"])();
function consolePrintFn(type) {
var func = global.console[type];
if (func) {
return function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args[0]) {
args[0] = formatMsg(type, args[0]);
}
func.apply(global.console, args);
};
}
return noop;
}
function exportLoggerFunctions(debugConfig) {
for (var _len2 = arguments.length, functions = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
functions[_key2 - 1] = arguments[_key2];
}
functions.forEach(function (type) {
exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
});
}
var enableLogs = function enableLogs(debugConfig) {
// check that console is available
if (global.console && debugConfig === true || typeof debugConfig === 'object') {
exportLoggerFunctions(debugConfig, // Remove out from list here to hard-disable a log-level
// 'trace',
'debug', 'log', 'info', 'warn', 'error'); // Some browsers don't allow to use bind on console object anyway
// fallback to default if needed
try {
exportedLogger.log();
} catch (e) {
exportedLogger = fakeLogger;
}
} else {
exportedLogger = fakeLogger;
}
};
var logger = exportedLogger;
/***/ })
/******/ })["default"];
});
//# sourceMappingURL=hls.light.js.map
|
it(
"A membrane-like proxy set always returns the same object for a prototype lookup",
function() {
"use strict";
const ShadowKeyMap = new WeakMap();
/**
* Define a shadow target, so we can manipulate the proxy independently of the
* original target.
*
* @argument value {Object} The original target.
*
* @returns {Object} A shadow target to minimally emulate the real one.
* @private
*/
function makeShadowTarget(value) {
"use strict";
var rv;
if (Array.isArray(value))
rv = [];
else if (typeof value == "object")
rv = {};
else if (typeof value == "function") {
rv = function() {};
/* ES7 specification says that functions in strict mode do not have their
* own "arguments" or "length" properties naturally. But in non-strict
* code, V8 adds those properties. (Mozilla adds them for both strict code
* and non-strict code, which technically is a spec violation.) So to make
* the membrane code work correctly with shadow targets, we start with the
* minimalist case (strict mode explicitly on), and add missing properties.
*/
let keys = Reflect.ownKeys(value);
keys.forEach(function(key) {
if (Reflect.getOwnPropertyDescriptor(rv))
return;
let desc = Reflect.getOwnPropertyDescriptor(value, key);
Reflect.defineProperty(rv, key, desc);
});
}
else
throw new Error("Unknown value for makeShadowTarget");
ShadowKeyMap.set(rv, value);
return rv;
}
function getRealTarget(target) {
return ShadowKeyMap.has(target) ? ShadowKeyMap.get(target) : target;
}
function wetA() {}
// this doesn't really matter - it's just a way of identifying the prototype
Reflect.defineProperty(wetA.prototype, "constructorName", {
value: "wetA",
writable: false,
enumerable: true,
configurable: false
});
const wet_a = new wetA();
const wet_b = new wetA();
expect(Reflect.getPrototypeOf(wet_a)).toBe(wetA.prototype);
expect(Reflect.getPrototypeOf(wet_b)).toBe(wetA.prototype);
const handler = {
membrane: {
dryMap: new WeakMap(),
prototypeMap: new WeakMap()
},
wrapPrototype: function(proto)
{
if (!this.membrane.prototypeMap.has(proto))
{
let proxy = new Proxy(Reflect, proto);
this.membrane.prototypeMap.set(proto, proxy);
}
return this.membrane.prototypeMap.get(proto);
},
getOwnPropertyDescriptor: function(shadow, propertyName)
{
const target = getRealTarget(shadow);
let rv = Reflect.getOwnPropertyDescriptor(target, propertyName);
if (rv)
{
if (Reflect.ownKeys(rv).includes("value"))
rv.value = this.getProxy(rv.value);
else
throw new Error("not supported for this test");
if (propertyName === "prototype")
rv.value = this.wrapPrototype(rv.value);
let oldDesc = Reflect.getOwnPropertyDescriptor(shadow, propertyName);
if (!oldDesc.configurable)
rv.configurable = false;
Reflect.defineProperty(shadow, propertyName, rv);
}
return rv;
},
get: function(shadow, propertyName)
{
const target = getRealTarget(shadow);
let rv = this.getProxy(Reflect.get(target, propertyName));
if (propertyName === "prototype")
rv = this.wrapPrototype(rv);
if (shadow[propertyName] !== rv)
shadow[propertyName] = rv;
return rv;
},
getPrototypeOf: function(shadow)
{
const target = getRealTarget(shadow);
const proto = Reflect.getPrototypeOf(target);
const rv = this.wrapPrototype(this.getProxy(proto));
Reflect.setPrototypeOf(shadow, rv);
return rv;
},
getProxy: function(wetValue) {
{
const t = typeof wetValue;
if ((t !== "object") && (t !== "function"))
return wetValue;
}
if (!this.membrane.dryMap.has(wetValue))
{
const shadow = makeShadowTarget(wetValue);
const p = new Proxy(shadow, this);
this.membrane.dryMap.set(wetValue, p);
}
return this.membrane.dryMap.get(wetValue);
}
};
const dryA = handler.getProxy(wetA);
const dry_a = handler.getProxy(wet_a);
const dry_b = handler.getProxy(wet_b);
const dryProto = dryA.prototype;
expect(dryProto).not.toBe(wetA.prototype);
expect(Reflect.getPrototypeOf(dry_a)).toBe(dryProto);
expect(dryA.prototype).toBe(dryProto);
expect(Reflect.getPrototypeOf(dry_b)).toBe(dryProto);
Object.seal(dry_a);
expect(Reflect.getPrototypeOf(dry_a)).toBe(dryProto);
expect(dryA.prototype).toBe(dryProto);
expect(Reflect.getPrototypeOf(dry_b)).toBe(dryProto);
Object.seal(dryA);
expect(Reflect.getPrototypeOf(dry_a)).toBe(dryProto);
expect(dryA.prototype).toBe(dryProto);
expect(Reflect.getPrototypeOf(dry_b)).toBe(dryProto);
Object.seal(dry_b);
expect(Reflect.getPrototypeOf(dry_a)).toBe(dryProto);
expect(dryA.prototype).toBe(dryProto);
expect(Reflect.getPrototypeOf(dry_b)).toBe(dryProto);
Object.freeze(dry_a);
expect(Reflect.getPrototypeOf(dry_a)).toBe(dryProto);
expect(dryA.prototype).toBe(dryProto);
expect(Reflect.getPrototypeOf(dry_b)).toBe(dryProto);
Object.freeze(dryA);
expect(Reflect.getPrototypeOf(dry_a)).toBe(dryProto);
expect(dryA.prototype).toBe(dryProto);
expect(Reflect.getPrototypeOf(dry_b)).toBe(dryProto);
Object.freeze(dry_b);
expect(Reflect.getPrototypeOf(dry_a)).toBe(dryProto);
expect(dryA.prototype).toBe(dryProto);
expect(Reflect.getPrototypeOf(dry_b)).toBe(dryProto);
}
);
|
"use strict";
class ExitError extends Error {
constructor(message, fileName, lineNumber) {
super(message, fileName, lineNumber);
this.exit = true;
}
}
module.exports = ExitError;
|
/*global define*/
define([
'Core/clone',
'Core/defaultValue',
'Core/defined',
'Core/queryToObject',
'Renderer/Context',
'Specs/createCanvas',
'Specs/createFrameState'
], function(
clone,
defaultValue,
defined,
queryToObject,
Context,
createCanvas,
createFrameState) {
"use strict";
function createContext(options, canvasWidth, canvasHeight) {
// clone options so we can change properties
options = clone(defaultValue(options, {}));
options.webgl = clone(defaultValue(options.webgl, {}));
options.webgl.alpha = defaultValue(options.webgl.alpha, true);
options.webgl.antialias = defaultValue(options.webgl.antialias, false);
var canvas = createCanvas(canvasWidth, canvasHeight);
var context = new Context(canvas, options);
var parameters = queryToObject(window.location.search.substring(1));
if (defined(parameters.webglValidation)) {
context.validateShaderProgram = true;
context.validateFramebuffer = true;
context.logShaderCompilation = true;
context.throwOnWebGLError = true;
}
var us = context.uniformState;
us.update(context, createFrameState());
return context;
}
return createContext;
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
AsyncStorage: {}
};
|
'use strict';
const assert = require('assert');
const { capture } = require('..');
describe('.capture()', () => {
it('should return null if no match', () => {
assert.equal(capture('test/*', 'hi/123'), null);
});
it('should return an empty array if there are no captures', () => {
assert.deepEqual(capture('test/hi', 'test/hi'), []);
});
it('should capture stars', () => {
assert.deepEqual(capture('test/*', 'test/foo'), ['foo']);
assert.deepEqual(capture('test/*/bar', 'test/foo/bar'), ['foo']);
assert.deepEqual(capture('test/*/bar/*', 'test/foo/bar/baz'), ['foo', 'baz']);
assert.deepEqual(capture('test/*.js', 'test/foo.js'), ['foo']);
assert.deepEqual(capture('test/*-controller.js', 'test/foo-controller.js'), ['foo']);
});
it('should capture globstars', () => {
assert.deepEqual(capture('test/**/*.js', 'test/a.js'), ['', 'a']);
assert.deepEqual(capture('test/**/*.js', 'test/dir/a.js'), ['dir', 'a']);
assert.deepEqual(capture('test/**/*.js', 'test/dir/test/a.js'), ['dir/test', 'a']);
assert.deepEqual(capture('**/*.js', 'test/dir/a.js'), ['test/dir', 'a']);
});
it('should capture extglobs', () => {
assert.deepEqual(capture('test/+(a|b)/*.js', 'test/a/x.js'), ['a', 'x']);
assert.deepEqual(capture('test/+(a|b)/*.js', 'test/b/x.js'), ['b', 'x']);
assert.deepEqual(capture('test/+(a|b)/*.js', 'test/ab/x.js'), ['ab', 'x']);
});
it('should capture paren groups', () => {
assert.deepEqual(capture('test/(a|b)/x.js', 'test/a/x.js'), ['a']);
assert.deepEqual(capture('test/(a|b)/x.js', 'test/b/x.js'), ['b']);
});
it('should capture star groups', () => {
assert.deepEqual(capture('test/a*(a|b)/x.js', 'test/a/x.js'), ['']);
assert.deepEqual(capture('test/a*(a|b)/x.js', 'test/aa/x.js'), ['a']);
assert.deepEqual(capture('test/a*(a|b)/x.js', 'test/ab/x.js'), ['b']);
assert.deepEqual(capture('test/a*(a|b)/x.js', 'test/aba/x.js'), ['ba']);
});
it('should capture plus groups', () => {
assert.deepEqual(capture('test/+(a|b)/x.js', 'test/a/x.js'), ['a']);
assert.deepEqual(capture('test/+(a|b)/x.js', 'test/b/x.js'), ['b']);
assert.deepEqual(capture('test/+(a|b)/x.js', 'test/ab/x.js'), ['ab']);
assert.deepEqual(capture('test/+(a|b)/x.js', 'test/aba/x.js'), ['aba']);
});
it('should capture optional groups', () => {
assert.deepEqual(capture('test/a?(a|b)/x.js', 'test/a/x.js'), ['']);
assert.deepEqual(capture('test/a?(a|b)/x.js', 'test/ab/x.js'), ['b']);
assert.deepEqual(capture('test/a?(a|b)/x.js', 'test/aa/x.js'), ['a']);
});
it('should capture @ groups', () => {
assert.deepEqual(capture('test/@(a|b)/x.js', 'test/a/x.js'), ['a']);
assert.deepEqual(capture('test/@(a|b)/x.js', 'test/b/x.js'), ['b']);
});
it('should capture negated groups', () => {
assert.deepEqual(capture('test/!(a|b)/x.js', 'test/x/x.js'), ['x']);
assert.deepEqual(capture('test/!(a|b)/x.js', 'test/y/x.js'), ['y']);
});
});
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
const models = require('./index');
/**
* A region consists of multiple lines (e.g. a column of text in a multi-column
* document).
*
*/
class OcrRegion {
/**
* Create a OcrRegion.
* @member {string} [boundingBox] Bounding box of a recognized region. The
* four integers represent the x-coordinate of the left edge, the
* y-coordinate of the top edge, width, and height of the bounding box, in
* the coordinate system of the input image, after it has been rotated around
* its center according to the detected text angle (see textAngle property),
* with the origin at the top-left corner, and the y-axis pointing down.
* @member {array} [lines]
*/
constructor() {
}
/**
* Defines the metadata of OcrRegion
*
* @returns {object} metadata of OcrRegion
*
*/
mapper() {
return {
required: false,
serializedName: 'OcrRegion',
type: {
name: 'Composite',
className: 'OcrRegion',
modelProperties: {
boundingBox: {
required: false,
serializedName: 'boundingBox',
type: {
name: 'String'
}
},
lines: {
required: false,
serializedName: 'lines',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'OcrLineElementType',
type: {
name: 'Composite',
className: 'OcrLine'
}
}
}
}
}
}
};
}
}
module.exports = OcrRegion;
|
'use strict';
var path = require('path');
/**
* Receives a `namespace`, and an Hash of `options` to invoke a given
* generator. The usual list of arguments can be set with `options.args`
* (ex. nopt's argv.remain array)
*
* @param {String} namespace
* @param {Object} options
* @param {Function} cb
*
* @mixin
* @alias actions/invoke
*/
module.exports = function invoke(namespace, options, cb) {
cb = cb || function () {};
options = options || {};
options.args = options.args || [];
var generator = this.env.create(namespace, options);
this.log.emit('up');
this.log.invoke(namespace);
this.log.emit('up');
generator.on('end', this.log.emit.bind(this.log, 'down'));
generator.on('end', this.log.emit.bind(this.log, 'down'));
return generator.run(cb);
};
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Stream_1 = require("../core/Stream");
var Scheduler_1 = require("../core/Scheduler");
var Subject_1 = require("../subject/Subject");
var AutoDetachObserver_1 = require("../observer/AutoDetachObserver");
var JudgeUtils_1 = require("../JudgeUtils");
var SingleDisposable_1 = require("../Disposable/SingleDisposable");
var AnonymousStream = (function (_super) {
__extends(AnonymousStream, _super);
function AnonymousStream(subscribeFunc) {
var _this = _super.call(this, subscribeFunc) || this;
_this.scheduler = Scheduler_1.Scheduler.create();
return _this;
}
AnonymousStream.create = function (subscribeFunc) {
var obj = new this(subscribeFunc);
return obj;
};
AnonymousStream.prototype.buildStream = function (observer) {
return SingleDisposable_1.SingleDisposable.create((this.subscribeFunc(observer) || function () { }));
};
AnonymousStream.prototype.subscribe = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var observer = null;
if (args[0] instanceof Subject_1.Subject) {
var subject = args[0];
this.handleSubject(subject);
return;
}
else if (JudgeUtils_1.JudgeUtils.isIObserver(args[0])) {
observer = AutoDetachObserver_1.AutoDetachObserver.create(args[0]);
}
else {
var onNext = args[0], onError = args[1] || null, onCompleted = args[2] || null;
observer = AutoDetachObserver_1.AutoDetachObserver.create(onNext, onError, onCompleted);
}
observer.setDisposable(this.buildStream(observer));
return observer;
};
return AnonymousStream;
}(Stream_1.Stream));
exports.AnonymousStream = AnonymousStream;
//# sourceMappingURL=AnonymousStream.js.map
|
module.exports = isPromise;
function isPromise(obj) {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
}
|
// Karma configuration
// Generated on Sun Jun 26 2016 14:46:31 GMT+0200 (CEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '../..',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'openslides/static/js/openslides-libs.js',
'node_modules/angular-mocks/angular-mocks.js',
'openslides/motions/static/js/motions/linenumbering.js',
'openslides/motions/static/js/motions/diff.js',
'openslides/core/static/js/core/pdf.js',
'tests/karma/*/*.test.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
client: {
captureConsole: true
},
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome', 'PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
|
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
const updatePasswordSchema = new SimpleSchema({
old: {
type: String,
max: 50,
},
new: {
type: String,
min: 6,
max: 20,
},
confirm: {
type: String,
min: 6,
max: 20,
// TODO: Resolve consistent-return
// eslint-disable-next-line consistent-return
custom () {
// Make sure new password and password confirmation match
if (this.value !== this.field('new').value) {
return 'updatePassword_passwordsMismatch';
}
},
},
});
updatePasswordSchema.i18n('schemas.updatePassword');
export default updatePasswordSchema;
|
(function (angular, window) {
'use strict';
var regModules = ['ng', 'oc.lazyLoad'],
regInvokes = {},
regConfigs = [],
modulesToLoad = [],
// modules to load from angular.module or other sources
realModules = [],
// real modules called from angular.module
recordDeclarations = [],
broadcast = angular.noop,
runBlocks = {},
justLoaded = [];
var ocLazyLoad = angular.module('oc.lazyLoad', ['ng']);
ocLazyLoad.provider('$ocLazyLoad', ["$controllerProvider", "$provide", "$compileProvider", "$filterProvider", "$injector", "$animateProvider", function ($controllerProvider, $provide, $compileProvider, $filterProvider, $injector, $animateProvider) {
var modules = {},
providers = {
$controllerProvider: $controllerProvider,
$compileProvider: $compileProvider,
$filterProvider: $filterProvider,
$provide: $provide, // other things (constant, decorator, provider, factory, service)
$injector: $injector,
$animateProvider: $animateProvider
},
debug = false,
events = false,
moduleCache = [],
modulePromises = {};
moduleCache.push = function (value) {
if (this.indexOf(value) === -1) {
Array.prototype.push.apply(this, arguments);
}
};
this.config = function (config) {
// If we want to define modules configs
if (angular.isDefined(config.modules)) {
if (angular.isArray(config.modules)) {
angular.forEach(config.modules, function (moduleConfig) {
modules[moduleConfig.name] = moduleConfig;
});
} else {
modules[config.modules.name] = config.modules;
}
}
if (angular.isDefined(config.debug)) {
debug = config.debug;
}
if (angular.isDefined(config.events)) {
events = config.events;
}
};
/**
* Get the list of existing registered modules
* @param element
*/
this._init = function _init(element) {
// this is probably useless now because we override angular.bootstrap
if (modulesToLoad.length === 0) {
var elements = [element],
names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/,
append = function append(elm) {
return elm && elements.push(elm);
};
angular.forEach(names, function (name) {
names[name] = true;
append(document.getElementById(name));
name = name.replace(':', '\\:');
if (typeof element[0] !== 'undefined' && element[0].querySelectorAll) {
angular.forEach(element[0].querySelectorAll('.' + name), append);
angular.forEach(element[0].querySelectorAll('.' + name + '\\:'), append);
angular.forEach(element[0].querySelectorAll('[' + name + ']'), append);
}
});
angular.forEach(elements, function (elm) {
if (modulesToLoad.length === 0) {
var className = ' ' + element.className + ' ';
var match = NG_APP_CLASS_REGEXP.exec(className);
if (match) {
modulesToLoad.push((match[2] || '').replace(/\s+/g, ','));
} else {
angular.forEach(elm.attributes, function (attr) {
if (modulesToLoad.length === 0 && names[attr.name]) {
modulesToLoad.push(attr.value);
}
});
}
}
});
}
if (modulesToLoad.length === 0 && !((window.jasmine || window.mocha) && angular.isDefined(angular.mock))) {
console.error('No module found during bootstrap, unable to init ocLazyLoad. You should always use the ng-app directive or angular.boostrap when you use ocLazyLoad.');
}
var addReg = function addReg(moduleName) {
if (regModules.indexOf(moduleName) === -1) {
// register existing modules
regModules.push(moduleName);
var mainModule = angular.module(moduleName);
// register existing components (directives, services, ...)
_invokeQueue(null, mainModule._invokeQueue, moduleName);
_invokeQueue(null, mainModule._configBlocks, moduleName); // angular 1.3+
angular.forEach(mainModule.requires, addReg);
}
};
angular.forEach(modulesToLoad, function (moduleName) {
addReg(moduleName);
});
modulesToLoad = []; // reset for next bootstrap
recordDeclarations.pop(); // wait for the next lazy load
};
/**
* Like JSON.stringify but that doesn't throw on circular references
* @param obj
*/
var stringify = function stringify(obj) {
var cache = [];
return JSON.stringify(obj, function (key, value) {
if (angular.isObject(value) && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
};
var hashCode = function hashCode(str) {
var hash = 0,
i,
chr,
len;
if (str.length == 0) {
return hash;
}
for (i = 0, len = str.length; i < len; i++) {
chr = str.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
function _register(providers, registerModules, params) {
if (registerModules) {
var k,
moduleName,
moduleFn,
tempRunBlocks = [];
for (k = registerModules.length - 1; k >= 0; k--) {
moduleName = registerModules[k];
if (!angular.isString(moduleName)) {
moduleName = getModuleName(moduleName);
}
if (!moduleName || justLoaded.indexOf(moduleName) !== -1 || modules[moduleName] && realModules.indexOf(moduleName) === -1) {
continue;
}
// new if not registered
var newModule = regModules.indexOf(moduleName) === -1;
moduleFn = ngModuleFct(moduleName);
if (newModule) {
regModules.push(moduleName);
_register(providers, moduleFn.requires, params);
}
if (moduleFn._runBlocks.length > 0) {
// new run blocks detected! Replace the old ones (if existing)
runBlocks[moduleName] = [];
while (moduleFn._runBlocks.length > 0) {
runBlocks[moduleName].push(moduleFn._runBlocks.shift());
}
}
if (angular.isDefined(runBlocks[moduleName]) && (newModule || params.rerun)) {
tempRunBlocks = tempRunBlocks.concat(runBlocks[moduleName]);
}
_invokeQueue(providers, moduleFn._invokeQueue, moduleName, params.reconfig);
_invokeQueue(providers, moduleFn._configBlocks, moduleName, params.reconfig); // angular 1.3+
broadcast(newModule ? 'ocLazyLoad.moduleLoaded' : 'ocLazyLoad.moduleReloaded', moduleName);
registerModules.pop();
justLoaded.push(moduleName);
}
// execute the run blocks at the end
var instanceInjector = providers.getInstanceInjector();
angular.forEach(tempRunBlocks, function (fn) {
instanceInjector.invoke(fn);
});
}
}
function _registerInvokeList(args, moduleName) {
var invokeList = args[2][0],
type = args[1],
newInvoke = false;
if (angular.isUndefined(regInvokes[moduleName])) {
regInvokes[moduleName] = {};
}
if (angular.isUndefined(regInvokes[moduleName][type])) {
regInvokes[moduleName][type] = {};
}
var onInvoke = function onInvoke(invokeName, signature) {
if (!regInvokes[moduleName][type].hasOwnProperty(invokeName)) {
regInvokes[moduleName][type][invokeName] = [];
}
if (regInvokes[moduleName][type][invokeName].indexOf(signature) === -1) {
newInvoke = true;
regInvokes[moduleName][type][invokeName].push(signature);
broadcast('ocLazyLoad.componentLoaded', [moduleName, type, invokeName]);
}
};
function signature(data) {
if (angular.isArray(data)) {
// arrays are objects, we need to test for it first
return hashCode(data.toString());
} else if (angular.isObject(data)) {
// constants & values for example
return hashCode(stringify(data));
} else {
if (angular.isDefined(data) && data !== null) {
return hashCode(data.toString());
} else {
// null & undefined constants
return data;
}
}
}
if (angular.isString(invokeList)) {
onInvoke(invokeList, signature(args[2][1]));
} else if (angular.isObject(invokeList)) {
angular.forEach(invokeList, function (invoke, key) {
if (angular.isString(invoke)) {
// decorators for example
onInvoke(invoke, signature(invokeList[1]));
} else {
// components registered as object lists {"componentName": function() {}}
onInvoke(key, signature(invoke));
}
});
} else {
return false;
}
return newInvoke;
}
function _invokeQueue(providers, queue, moduleName, reconfig) {
if (!queue) {
return;
}
var i, len, args, provider;
for (i = 0, len = queue.length; i < len; i++) {
args = queue[i];
if (angular.isArray(args)) {
if (providers !== null) {
if (providers.hasOwnProperty(args[0])) {
provider = providers[args[0]];
} else {
throw new Error('unsupported provider ' + args[0]);
}
}
var isNew = _registerInvokeList(args, moduleName);
if (args[1] !== 'invoke') {
if (isNew && angular.isDefined(provider)) {
provider[args[1]].apply(provider, args[2]);
}
} else {
// config block
var callInvoke = function callInvoke(fct) {
var invoked = regConfigs.indexOf('' + moduleName + '-' + fct);
if (invoked === -1 || reconfig) {
if (invoked === -1) {
regConfigs.push('' + moduleName + '-' + fct);
}
if (angular.isDefined(provider)) {
provider[args[1]].apply(provider, args[2]);
}
}
};
if (angular.isFunction(args[2][0])) {
callInvoke(args[2][0]);
} else if (angular.isArray(args[2][0])) {
for (var j = 0, jlen = args[2][0].length; j < jlen; j++) {
if (angular.isFunction(args[2][0][j])) {
callInvoke(args[2][0][j]);
}
}
}
}
}
}
}
function getModuleName(module) {
var moduleName = null;
if (angular.isString(module)) {
moduleName = module;
} else if (angular.isObject(module) && module.hasOwnProperty('name') && angular.isString(module.name)) {
moduleName = module.name;
}
return moduleName;
}
function moduleExists(moduleName) {
if (!angular.isString(moduleName)) {
return false;
}
try {
return ngModuleFct(moduleName);
} catch (e) {
if (/No module/.test(e) || e.message.indexOf('$injector:nomod') > -1) {
return false;
}
}
}
this.$get = ["$log", "$rootElement", "$rootScope", "$cacheFactory", "$q", function ($log, $rootElement, $rootScope, $cacheFactory, $q) {
var instanceInjector,
filesCache = $cacheFactory('ocLazyLoad');
if (!debug) {
$log = {};
$log['error'] = angular.noop;
$log['warn'] = angular.noop;
$log['info'] = angular.noop;
}
// Make this lazy because when $get() is called the instance injector hasn't been assigned to the rootElement yet
providers.getInstanceInjector = function () {
return instanceInjector ? instanceInjector : instanceInjector = $rootElement.data('$injector') || angular.injector();
};
broadcast = function broadcast(eventName, params) {
if (events) {
$rootScope.$broadcast(eventName, params);
}
if (debug) {
$log.info(eventName, params);
}
};
function reject(e) {
var deferred = $q.defer();
$log.error(e.message);
deferred.reject(e);
return deferred.promise;
}
return {
_broadcast: broadcast,
_$log: $log,
/**
* Returns the files cache used by the loaders to store the files currently loading
* @returns {*}
*/
_getFilesCache: function getFilesCache() {
return filesCache;
},
/**
* Let the service know that it should monitor angular.module because files are loading
* @param watch boolean
*/
toggleWatch: function toggleWatch(watch) {
if (watch) {
recordDeclarations.push(true);
} else {
recordDeclarations.pop();
}
},
/**
* Let you get a module config object
* @param moduleName String the name of the module
* @returns {*}
*/
getModuleConfig: function getModuleConfig(moduleName) {
if (!angular.isString(moduleName)) {
throw new Error('You need to give the name of the module to get');
}
if (!modules[moduleName]) {
return null;
}
return angular.copy(modules[moduleName]);
},
/**
* Let you define a module config object
* @param moduleConfig Object the module config object
* @returns {*}
*/
setModuleConfig: function setModuleConfig(moduleConfig) {
if (!angular.isObject(moduleConfig)) {
throw new Error('You need to give the module config object to set');
}
modules[moduleConfig.name] = moduleConfig;
return moduleConfig;
},
/**
* Returns the list of loaded modules
* @returns {string[]}
*/
getModules: function getModules() {
return regModules;
},
/**
* Let you check if a module has been loaded into Angular or not
* @param modulesNames String/Object a module name, or a list of module names
* @returns {boolean}
*/
isLoaded: function isLoaded(modulesNames) {
var moduleLoaded = function moduleLoaded(module) {
var isLoaded = regModules.indexOf(module) > -1;
if (!isLoaded) {
isLoaded = !!moduleExists(module);
}
return isLoaded;
};
if (angular.isString(modulesNames)) {
modulesNames = [modulesNames];
}
if (angular.isArray(modulesNames)) {
var i, len;
for (i = 0, len = modulesNames.length; i < len; i++) {
if (!moduleLoaded(modulesNames[i])) {
return false;
}
}
return true;
} else {
throw new Error('You need to define the module(s) name(s)');
}
},
/**
* Given a module, return its name
* @param module
* @returns {String}
*/
_getModuleName: getModuleName,
/**
* Returns a module if it exists
* @param moduleName
* @returns {module}
*/
_getModule: function getModule(moduleName) {
try {
return ngModuleFct(moduleName);
} catch (e) {
// this error message really suxx
if (/No module/.test(e) || e.message.indexOf('$injector:nomod') > -1) {
e.message = 'The module "' + stringify(moduleName) + '" that you are trying to load does not exist. ' + e.message;
}
throw e;
}
},
/**
* Check if a module exists and returns it if it does
* @param moduleName
* @returns {boolean}
*/
moduleExists: moduleExists,
/**
* Load the dependencies, and might try to load new files depending on the config
* @param moduleName (String or Array of Strings)
* @param localParams
* @returns {*}
* @private
*/
_loadDependencies: function _loadDependencies(moduleName, localParams) {
var loadedModule,
requires,
diff,
promisesList = [],
self = this;
moduleName = self._getModuleName(moduleName);
if (moduleName === null) {
return $q.when();
} else {
try {
loadedModule = self._getModule(moduleName);
} catch (e) {
return reject(e);
}
// get unloaded requires
requires = self.getRequires(loadedModule);
}
angular.forEach(requires, function (requireEntry) {
// If no configuration is provided, try and find one from a previous load.
// If there isn't one, bail and let the normal flow run
if (angular.isString(requireEntry)) {
var config = self.getModuleConfig(requireEntry);
if (config === null) {
moduleCache.push(requireEntry); // We don't know about this module, but something else might, so push it anyway.
return;
}
requireEntry = config;
// ignore the name because it's probably not a real module name
config.name = undefined;
}
// Check if this dependency has been loaded previously
if (self.moduleExists(requireEntry.name)) {
// compare against the already loaded module to see if the new definition adds any new files
diff = requireEntry.files.filter(function (n) {
return self.getModuleConfig(requireEntry.name).files.indexOf(n) < 0;
});
// If the module was redefined, advise via the console
if (diff.length !== 0) {
self._$log.warn('Module "', moduleName, '" attempted to redefine configuration for dependency. "', requireEntry.name, '"\n Additional Files Loaded:', diff);
}
// Push everything to the file loader, it will weed out the duplicates.
if (angular.isDefined(self.filesLoader)) {
// if a files loader is defined
promisesList.push(self.filesLoader(requireEntry, localParams).then(function () {
return self._loadDependencies(requireEntry);
}));
} else {
return reject(new Error('Error: New dependencies need to be loaded from external files (' + requireEntry.files + '), but no loader has been defined.'));
}
return;
} else if (angular.isArray(requireEntry)) {
var files = [];
angular.forEach(requireEntry, function (entry) {
// let's check if the entry is a file name or a config name
var config = self.getModuleConfig(entry);
if (config === null) {
files.push(entry);
} else if (config.files) {
files = files.concat(config.files);
}
});
if (files.length > 0) {
requireEntry = {
files: files
};
}
} else if (angular.isObject(requireEntry)) {
if (requireEntry.hasOwnProperty('name') && requireEntry['name']) {
// The dependency doesn't exist in the module cache and is a new configuration, so store and push it.
self.setModuleConfig(requireEntry);
moduleCache.push(requireEntry['name']);
}
}
// Check if the dependency has any files that need to be loaded. If there are, push a new promise to the promise list.
if (angular.isDefined(requireEntry.files) && requireEntry.files.length !== 0) {
if (angular.isDefined(self.filesLoader)) {
// if a files loader is defined
promisesList.push(self.filesLoader(requireEntry, localParams).then(function () {
return self._loadDependencies(requireEntry);
}));
} else {
return reject(new Error('Error: the module "' + requireEntry.name + '" is defined in external files (' + requireEntry.files + '), but no loader has been defined.'));
}
}
});
// Create a wrapper promise to watch the promise list and resolve it once everything is done.
return $q.all(promisesList);
},
/**
* Inject new modules into Angular
* @param moduleName
* @param localParams
*/
inject: function inject(moduleName) {
var localParams = arguments[1] === undefined ? {} : arguments[1];
var self = this,
deferred = $q.defer();
if (angular.isDefined(moduleName) && moduleName !== null) {
if (angular.isArray(moduleName)) {
var promisesList = [];
angular.forEach(moduleName, function (module) {
promisesList.push(self.inject(module));
});
return $q.all(promisesList);
} else {
self._addToLoadList(self._getModuleName(moduleName), true);
}
}
if (modulesToLoad.length > 0) {
var res = modulesToLoad.slice(); // clean copy
var loadNext = function loadNext(moduleName) {
moduleCache.push(moduleName);
modulePromises[moduleName] = deferred.promise;
self._loadDependencies(moduleName, localParams).then(function success() {
try {
justLoaded = [];
_register(providers, moduleCache, localParams);
} catch (e) {
self._$log.error(e.message);
deferred.reject(e);
return;
}
if (modulesToLoad.length > 0) {
loadNext(modulesToLoad.shift()); // load the next in list
} else {
deferred.resolve(res); // everything has been loaded, resolve
}
}, function error(err) {
deferred.reject(err);
});
};
// load the first in list
loadNext(modulesToLoad.shift());
} else if (localParams && localParams.name && modulePromises[localParams.name]) {
return modulePromises[localParams.name];
} else {
deferred.resolve();
}
return deferred.promise;
},
/**
* Get the list of required modules/services/... for this module
* @param module
* @returns {Array}
*/
getRequires: function getRequires(module) {
var requires = [];
angular.forEach(module.requires, function (requireModule) {
if (regModules.indexOf(requireModule) === -1) {
requires.push(requireModule);
}
});
return requires;
},
/**
* Invoke the new modules & component by their providers
* @param providers
* @param queue
* @param moduleName
* @param reconfig
* @private
*/
_invokeQueue: _invokeQueue,
/**
* Check if a module has been invoked and registers it if not
* @param args
* @param moduleName
* @returns {boolean} is new
*/
_registerInvokeList: _registerInvokeList,
/**
* Register a new module and loads it, executing the run/config blocks if needed
* @param providers
* @param registerModules
* @param params
* @private
*/
_register: _register,
/**
* Add a module name to the list of modules that will be loaded in the next inject
* @param name
* @param force
* @private
*/
_addToLoadList: _addToLoadList
};
}];
// Let's get the list of loaded modules & components
this._init(angular.element(window.document));
}]);
var bootstrapFct = angular.bootstrap;
angular.bootstrap = function (element, modules, config) {
// we use slice to make a clean copy
angular.forEach(modules.slice(), function (module) {
_addToLoadList(module, true, true);
});
return bootstrapFct(element, modules, config);
};
var _addToLoadList = function _addToLoadList(name, force, real) {
if ((recordDeclarations.length > 0 || force) && angular.isString(name) && modulesToLoad.indexOf(name) === -1) {
modulesToLoad.push(name);
if (real) {
realModules.push(name);
}
}
};
var ngModuleFct = angular.module;
angular.module = function (name, requires, configFn) {
_addToLoadList(name, false, true);
return ngModuleFct(name, requires, configFn);
};
// CommonJS package manager support:
if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports) {
module.exports = 'oc.lazyLoad';
}
})(angular, window);
|
import Ember from "ember-metal/core"; // Ember.Logger, Ember.LOG_BINDINGS, assert
import { get } from "ember-metal/property_get";
import { trySet } from "ember-metal/property_set";
import { guidFor } from "ember-metal/utils";
import {
addObserver,
removeObserver,
_suspendObserver
} from "ember-metal/observer";
import run from "ember-metal/run_loop";
import {
isGlobal as isGlobalPath
} from "ember-metal/path_cache";
// ES6TODO: where is Ember.lookup defined?
/**
@module ember
@submodule ember-metal
*/
// ..........................................................
// CONSTANTS
//
/**
Debug parameter you can turn on. This will log all bindings that fire to
the console. This should be disabled in production code. Note that you
can also enable this from the console or temporarily.
@property LOG_BINDINGS
@for Ember
@type Boolean
@default false
@public
*/
Ember.LOG_BINDINGS = false || !!Ember.ENV.LOG_BINDINGS;
/**
Returns true if the provided path is global (e.g., `MyApp.fooController.bar`)
instead of local (`foo.bar.baz`).
@method isGlobalPath
@for Ember
@private
@param {String} path
@return Boolean
*/
function getWithGlobals(obj, path) {
return get(isGlobalPath(path) ? Ember.lookup : obj, path);
}
// ..........................................................
// BINDING
//
function Binding(toPath, fromPath) {
this._direction = undefined;
this._from = fromPath;
this._to = toPath;
this._readyToSync = undefined;
this._oneWay = undefined;
}
/**
@class Binding
@namespace Ember
@public
*/
Binding.prototype = {
/**
This copies the Binding so it can be connected to another object.
@method copy
@return {Ember.Binding} `this`
@public
*/
copy() {
var copy = new Binding(this._to, this._from);
if (this._oneWay) { copy._oneWay = true; }
return copy;
},
// ..........................................................
// CONFIG
//
/**
This will set `from` property path to the specified value. It will not
attempt to resolve this property path to an actual object until you
connect the binding.
The binding will search for the property path starting at the root object
you pass when you `connect()` the binding. It follows the same rules as
`get()` - see that method for more information.
@method from
@param {String} path the property path to connect to
@return {Ember.Binding} `this`
@public
*/
from(path) {
this._from = path;
return this;
},
/**
This will set the `to` property path to the specified value. It will not
attempt to resolve this property path to an actual object until you
connect the binding.
The binding will search for the property path starting at the root object
you pass when you `connect()` the binding. It follows the same rules as
`get()` - see that method for more information.
@method to
@param {String|Tuple} path A property path or tuple
@return {Ember.Binding} `this`
@public
*/
to(path) {
this._to = path;
return this;
},
/**
Configures the binding as one way. A one-way binding will relay changes
on the `from` side to the `to` side, but not the other way around. This
means that if you change the `to` side directly, the `from` side may have
a different value.
@method oneWay
@return {Ember.Binding} `this`
@public
*/
oneWay() {
this._oneWay = true;
return this;
},
/**
@method toString
@return {String} string representation of binding
@public
*/
toString() {
var oneWay = this._oneWay ? '[oneWay]' : '';
return `Ember.Binding<${guidFor(this)}>(${this._from} -> ${this._to})${oneWay}`;
},
// ..........................................................
// CONNECT AND SYNC
//
/**
Attempts to connect this binding instance so that it can receive and relay
changes. This method will raise an exception if you have not set the
from/to properties yet.
@method connect
@param {Object} obj The root object for this binding.
@return {Ember.Binding} `this`
@public
*/
connect(obj) {
Ember.assert('Must pass a valid object to Ember.Binding.connect()', !!obj);
var fromPath = this._from;
var toPath = this._to;
trySet(obj, toPath, getWithGlobals(obj, fromPath));
// add an observer on the object to be notified when the binding should be updated
addObserver(obj, fromPath, this, this.fromDidChange);
// if the binding is a two-way binding, also set up an observer on the target
if (!this._oneWay) {
addObserver(obj, toPath, this, this.toDidChange);
}
this._readyToSync = true;
return this;
},
/**
Disconnects the binding instance. Changes will no longer be relayed. You
will not usually need to call this method.
@method disconnect
@param {Object} obj The root object you passed when connecting the binding.
@return {Ember.Binding} `this`
@public
*/
disconnect(obj) {
Ember.assert('Must pass a valid object to Ember.Binding.disconnect()', !!obj);
var twoWay = !this._oneWay;
// remove an observer on the object so we're no longer notified of
// changes that should update bindings.
removeObserver(obj, this._from, this, this.fromDidChange);
// if the binding is two-way, remove the observer from the target as well
if (twoWay) {
removeObserver(obj, this._to, this, this.toDidChange);
}
this._readyToSync = false; // disable scheduled syncs...
return this;
},
// ..........................................................
// PRIVATE
//
/* called when the from side changes */
fromDidChange(target) {
this._scheduleSync(target, 'fwd');
},
/* called when the to side changes */
toDidChange(target) {
this._scheduleSync(target, 'back');
},
_scheduleSync(obj, dir) {
var existingDir = this._direction;
// if we haven't scheduled the binding yet, schedule it
if (existingDir === undefined) {
run.schedule('sync', this, this._sync, obj);
this._direction = dir;
}
// If both a 'back' and 'fwd' sync have been scheduled on the same object,
// default to a 'fwd' sync so that it remains deterministic.
if (existingDir === 'back' && dir === 'fwd') {
this._direction = 'fwd';
}
},
_sync(obj) {
var log = Ember.LOG_BINDINGS;
// don't synchronize destroyed objects or disconnected bindings
if (obj.isDestroyed || !this._readyToSync) { return; }
// get the direction of the binding for the object we are
// synchronizing from
var direction = this._direction;
var fromPath = this._from;
var toPath = this._to;
this._direction = undefined;
// if we're synchronizing from the remote object...
if (direction === 'fwd') {
var fromValue = getWithGlobals(obj, this._from);
if (log) {
Ember.Logger.log(' ', this.toString(), '->', fromValue, obj);
}
if (this._oneWay) {
trySet(obj, toPath, fromValue);
} else {
_suspendObserver(obj, toPath, this, this.toDidChange, function () {
trySet(obj, toPath, fromValue);
});
}
// if we're synchronizing *to* the remote object
} else if (direction === 'back') {
var toValue = get(obj, this._to);
if (log) {
Ember.Logger.log(' ', this.toString(), '<-', toValue, obj);
}
_suspendObserver(obj, fromPath, this, this.fromDidChange, function () {
trySet(isGlobalPath(fromPath) ? Ember.lookup : obj, fromPath, toValue);
});
}
}
};
function mixinProperties(to, from) {
for (var key in from) {
if (from.hasOwnProperty(key)) {
to[key] = from[key];
}
}
}
mixinProperties(Binding, {
/*
See `Ember.Binding.from`.
@method from
@static
*/
from(from) {
var C = this;
return new C(undefined, from);
},
/*
See `Ember.Binding.to`.
@method to
@static
*/
to(to) {
var C = this;
return new C(to, undefined);
},
/**
Creates a new Binding instance and makes it apply in a single direction.
A one-way binding will relay changes on the `from` side object (supplied
as the `from` argument) the `to` side, but not the other way around.
This means that if you change the "to" side directly, the "from" side may have
a different value.
See `Binding.oneWay`.
@method oneWay
@param {String} from from path.
@param {Boolean} [flag] (Optional) passing nothing here will make the
binding `oneWay`. You can instead pass `false` to disable `oneWay`, making the
binding two way again.
@return {Ember.Binding} `this`
@public
*/
oneWay(from, flag) {
var C = this;
return new C(undefined, from).oneWay(flag);
}
});
/**
An `Ember.Binding` connects the properties of two objects so that whenever
the value of one property changes, the other property will be changed also.
## Automatic Creation of Bindings with `/^*Binding/`-named Properties
You do not usually create Binding objects directly but instead describe
bindings in your class or object definition using automatic binding
detection.
Properties ending in a `Binding` suffix will be converted to `Ember.Binding`
instances. The value of this property should be a string representing a path
to another object or a custom binding instance created using Binding helpers
(see "One Way Bindings"):
```
valueBinding: "MyApp.someController.title"
```
This will create a binding from `MyApp.someController.title` to the `value`
property of your object instance automatically. Now the two values will be
kept in sync.
## One Way Bindings
One especially useful binding customization you can use is the `oneWay()`
helper. This helper tells Ember that you are only interested in
receiving changes on the object you are binding from. For example, if you
are binding to a preference and you want to be notified if the preference
has changed, but your object will not be changing the preference itself, you
could do:
```
bigTitlesBinding: Ember.Binding.oneWay("MyApp.preferencesController.bigTitles")
```
This way if the value of `MyApp.preferencesController.bigTitles` changes the
`bigTitles` property of your object will change also. However, if you
change the value of your `bigTitles` property, it will not update the
`preferencesController`.
One way bindings are almost twice as fast to setup and twice as fast to
execute because the binding only has to worry about changes to one side.
You should consider using one way bindings anytime you have an object that
may be created frequently and you do not intend to change a property; only
to monitor it for changes (such as in the example above).
## Adding Bindings Manually
All of the examples above show you how to configure a custom binding, but the
result of these customizations will be a binding template, not a fully active
Binding instance. The binding will actually become active only when you
instantiate the object the binding belongs to. It is useful however, to
understand what actually happens when the binding is activated.
For a binding to function it must have at least a `from` property and a `to`
property. The `from` property path points to the object/key that you want to
bind from while the `to` path points to the object/key you want to bind to.
When you define a custom binding, you are usually describing the property
you want to bind from (such as `MyApp.someController.value` in the examples
above). When your object is created, it will automatically assign the value
you want to bind `to` based on the name of your binding key. In the
examples above, during init, Ember objects will effectively call
something like this on your binding:
```javascript
binding = Ember.Binding.from("valueBinding").to("value");
```
This creates a new binding instance based on the template you provide, and
sets the to path to the `value` property of the new object. Now that the
binding is fully configured with a `from` and a `to`, it simply needs to be
connected to become active. This is done through the `connect()` method:
```javascript
binding.connect(this);
```
Note that when you connect a binding you pass the object you want it to be
connected to. This object will be used as the root for both the from and
to side of the binding when inspecting relative paths. This allows the
binding to be automatically inherited by subclassed objects as well.
This also allows you to bind between objects using the paths you declare in
`from` and `to`:
```javascript
// Example 1
binding = Ember.Binding.from("App.someObject.value").to("value");
binding.connect(this);
// Example 2
binding = Ember.Binding.from("parentView.value").to("App.someObject.value");
binding.connect(this);
```
Now that the binding is connected, it will observe both the from and to side
and relay changes.
If you ever needed to do so (you almost never will, but it is useful to
understand this anyway), you could manually create an active binding by
using the `Ember.bind()` helper method. (This is the same method used by
to setup your bindings on objects):
```javascript
Ember.bind(MyApp.anotherObject, "value", "MyApp.someController.value");
```
Both of these code fragments have the same effect as doing the most friendly
form of binding creation like so:
```javascript
MyApp.anotherObject = Ember.Object.create({
valueBinding: "MyApp.someController.value",
// OTHER CODE FOR THIS OBJECT...
});
```
Ember's built in binding creation method makes it easy to automatically
create bindings for you. You should always use the highest-level APIs
available, even if you understand how it works underneath.
@class Binding
@namespace Ember
@since Ember 0.9
@public
*/
// Ember.Binding = Binding; ES6TODO: where to put this?
/**
Global helper method to create a new binding. Just pass the root object
along with a `to` and `from` path to create and connect the binding.
@method bind
@for Ember
@param {Object} obj The root object of the transform.
@param {String} to The path to the 'to' side of the binding.
Must be relative to obj.
@param {String} from The path to the 'from' side of the binding.
Must be relative to obj or a global path.
@return {Ember.Binding} binding instance
@public
*/
export function bind(obj, to, from) {
return new Binding(to, from).connect(obj);
}
/**
@method oneWay
@for Ember
@param {Object} obj The root object of the transform.
@param {String} to The path to the 'to' side of the binding.
Must be relative to obj.
@param {String} from The path to the 'from' side of the binding.
Must be relative to obj or a global path.
@return {Ember.Binding} binding instance
@public
*/
export function oneWay(obj, to, from) {
return new Binding(to, from).oneWay().connect(obj);
}
export {
Binding,
isGlobalPath
};
|
var expect = require('expect.js'),
$ = require('../'),
fruits = require('./fixtures').fruits;
describe('$(...)', function() {
describe('.find', function() {
it('() : should return this', function() {
expect($('ul', fruits).find()[0].name).to.equal('ul');
});
it('(single) : should find one descendant', function() {
expect($('#fruits', fruits).find('.apple')[0].attribs['class']).to.equal('apple');
});
it('(many) : should find all matching descendant', function() {
expect($('#fruits', fruits).find('li')).to.have.length(3);
});
it('(many) : should merge all selected elems with matching descendants');
it('(invalid single) : should return empty if cant find', function() {
expect($('ul', fruits).find('blah')).to.have.length(0);
});
it('should return empty if search already empty result', function() {
expect($('#fruits').find('li')).to.have.length(0);
});
});
describe('.children', function() {
it('() : should get all children', function() {
expect($('ul', fruits).children()).to.have.length(3);
});
it('(selector) : should return children matching selector', function() {
expect($('ul', fruits).children('.orange').hasClass('orange')).to.be.ok();
});
it('(invalid selector) : should return empty', function() {
expect($('ul', fruits).children('.lulz')).to.have.length(0);
});
it('should only match immediate children, not ancestors');
});
describe('.next', function() {
it('() : should return next element', function() {
expect($('.orange', fruits).next().hasClass('pear')).to.be.ok();
});
it('(no next) : should return null (?)');
});
describe('.prev', function() {
it('() : should return previous element', function() {
expect($('.orange', fruits).prev().hasClass('apple')).to.be.ok();
});
it('(no prev) : should return null (?)');
});
describe('.siblings', function() {
it('() : should get all the siblings', function() {
expect($('.orange', fruits).siblings()).to.have.length(2);
});
it('(selector) : should get all siblings that match the selector', function() {
expect($('.orange', fruits).siblings('li')).to.have.length(2);
});
});
describe('.each', function() {
it('( (i, elem) -> ) : should loop selected returning fn with (i, elem)', function() {
var items = [];
$('li', fruits).each(function(idx, elem) {
items[idx] = elem;
});
expect(items[0].attribs['class']).to.equal('apple');
expect(items[1].attribs['class']).to.equal('orange');
expect(items[2].attribs['class']).to.equal('pear');
});
});
describe('.map', function() {
it('(fn) : should return an array of mapped items', function() {
var classes = $('li', fruits).map(function(i, el) {
expect(this).to.be(el);
expect(el.name).to.be('li');
expect(i).to.be.a('number');
return $(this).attr('class');
}).join(', ');
expect(classes).to.be('apple, orange, pear');
});
});
describe('.first', function() {
it('() : should return the first item', function() {
var $src = $('<span>foo</span><span>bar</span><span>baz</span>');
var $elem = $src.first();
expect($elem.length).to.equal(1);
expect($elem.html()).to.equal('foo');
});
it('() : should return an empty object for an empty object', function() {
var $src = $();
var $first = $src.first();
expect($first.length).to.equal(0);
expect($first.html()).to.be(null);
});
});
describe('.last', function() {
it('() : should return the last element', function() {
var $src = $('<span>foo</span><span>bar</span><span>baz</span>');
var $elem = $src.last();
expect($elem.length).to.equal(1);
expect($elem.html()).to.equal('baz');
});
it('() : should return an empty object for an empty object', function() {
var $src = $();
var $last = $src.last();
expect($last.length).to.equal(0);
expect($last.html()).to.be(null);
});
});
describe('.first & .last', function() {
it('() : should return equivalent collections if only one element', function() {
var $src = $('<span>bar</span>');
var $first = $src.first();
var $last = $src.last();
expect($first.length).to.equal(1);
expect($first.html()).to.equal('bar');
expect($last.length).to.equal(1);
expect($last.html()).to.equal('bar');
expect($first[0]).to.equal($last[0]);
});
});
describe('.eq', function() {
it('(i) : should return the element at the specified index', function() {
expect($('li', fruits).eq(0).text()).to.equal('Apple');
expect($('li', fruits).eq(1).text()).to.equal('Orange');
expect($('li', fruits).eq(2).text()).to.equal('Pear');
expect($('li', fruits).eq(3).text()).to.equal('');
expect($('li', fruits).eq(-1).text()).to.equal('Pear');
});
});
});
|
var Chain = Divhide.Chain;
var Maths = new Chain(
/// the chaining fns
{
sum: function(i,j){
return i + j;
},
sub: function(i, j){
return i - j;
}
},
/// the evaluation fns
{
calculate: function(result, err){
return result;
}
},
/// the options
{
/// if true the return of a function is passed as an argument to the next one
/// if false, the evaluation arguments are passed to every chain function (default)
pipe: true
});
var value = Maths.sum(5)
.sub(3)
.sum(10)
.calculate(0);
expect(value)
.toBe(12);
|
/*
* L.TileLayer.Cordova
* A subclass of L.TileLayer which provides caching of tiles to a local filesystem using Cordova's File API
* as well as methods for "switching" the layer between online mode (load from URLs) or offline mode (load from local stash)
* Intended use is with Cordova/Phonegap applications, to cache tiles for later use.
*
* This plugin requires the following Cordova/Phonegap plugins:
* File cordova plugins add org.apache.cordova.file
* File-Transfer cordova plugins add org.apache.cordova.file-transfer
* Additionally, these Cordova/Phonegap plugins are invaluable for development and debugging:
* Console cordova plugins add org.apache.cordova.console
*
* It accepts the usual L.TileLayer options, plus the following (some are REQUIRED).
* folder REQUIRED. A folder path under which tiles are stored. The name of your app may be good, e.g. "My Trail App"
* name REQUIRED. A unique name for this TileLayer, for naming the tiles and then fetching them later. Keep it brief, e.g. "terrain"
* debug Boolean indicating whether to display verbose debugging out to console. Defaults to false. Great for using GapDebug, logcat, Xcode console, ...
*
* Accepts an optional success_callback, which will be called when the time-intensive filesystem activities are complete.
*/
L.tileLayerCordova = function (url,options,success_callback) {
return new L.TileLayer.Cordova(url,options,success_callback);
}
L.TileLayer.Cordova = L.TileLayer.extend({
initialize: function (url, options, success_callback) {
// check required options or else choke and die
options = L.extend({
folder: null,
name: null,
autocache: false,
debug: false
}, options);
if (! options.folder) throw "L.TileLayer.Cordova: missing required option: folder";
if (! options.name) throw "L.TileLayer.Cordova: missing required option: name";
L.TileLayer.prototype.initialize.call(this, url, options);
L.setOptions(this, options);
// connect to the filesystem or else die loudly
// save a handle to the filesystem, and also use it to open a directory handle to our stated folder
// thus: self.fshandle and self.dirhandle
//
// also set the ._url for both online and offline use
// we have two versions of URL which may be the _url at any given time: offline and online
// online is the HTTP one we were given as the 'url' parameter here to initialize()
// offline is underneath the local filesystem: /path/to/sdcard/FOLDER/name-z-x-y.png
// tip: the file extension isn't really relevant; using .png works fine without juggling file extensions from their URL templates
var myself = this;
myself._url_online = myself._url; // Do this early, so it's done before the time-intensive filesystem activity starts.
if (! window.requestFileSystem && this.options.debug) console.log("L.TileLayer.Cordova: device does not support requestFileSystem");
if (! window.requestFileSystem) throw "L.TileLayer.Cordova: device does not support requestFileSystem";
if (myself.options.debug) console.log("Opening filesystem");
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
function (fshandle) {
if (myself.options.debug) console.log("requestFileSystem OK " + options.folder);
myself.fshandle = fshandle;
myself.fshandle.root.getDirectory(
options.folder,
{ create:true, exclusive:false },
function (dirhandle) {
if (myself.options.debug) console.log("getDirectory OK " + options.folder);
myself.dirhandle = dirhandle;
myself.dirhandle.setMetadata(null, null, { "com.apple.MobileBackup":1});
// Android's toURL() has a trailing / but iOS does not; better to have 2 than to have 0 !
myself._url_offline = dirhandle.toURL() + '/' + [ myself.options.name,'{z}','{x}','{y}' ].join('-') + '.png';
if (success_callback) success_callback();
},
function (error) {
if (myself.options.debug) console.log("getDirectory failed (code " + error.code + ")" + options.folder);
throw "L.TileLayer.Cordova: " + options.name + ": getDirectory failed with code " + error.code;
}
);
},
function (error) {
if (myself.options.debug) console.log("requestFileSystem failed (code " + error.code + ")" + options.folder);
throw "L.TileLayer.Cordova: " + options.name + ": requestFileSystem failed with code " + error.code;
}
);
// done, return ourselves because method chaining is cool
return this;
},
/*
* Toggle between online and offline functionality
* essentially this just calls setURL() with either the ._url_online or ._url_offline, and lets L.TileLayer reload the tiles... or try, anyway
*/
goOnline: function () {
// use this layer in online mode
this.setUrl( this._url_online );
},
goOffline: function () {
// use this layer in online mode
this.setUrl( this._url_offline );
},
/*
* Returns current online/offline state.
*/
isOnline: function() {
return (this._url == this._url_online);
},
isOffline: function() {
return (this._url == this._url_offline);
},
/*
* A set of functions to do the tile downloads, and to provide suporting calculations related thereto
* In particular, a user interface for downloading tiles en masse, would call calculateXYZListFromPyramid() to egt a list of tiles,
* then make decisions about whether this is a good idea (e.g. too many tiles), then call downloadXYZList() with success/error callbacks
*/
calculateXYZListFromPyramid: function (lat, lon, zmin, zmax) {
// given a latitude and longitude, and a range of zoom levels, return the list of XYZ trios comprising that view
// the caller may then call downloadXYZList() with progress and error callbacks to do that fetching
var xyzlist = [];
for (z=zmin; z<=zmax; z++) {
var t_x = this.getX(lon, z);
var t_y = this.getY(lat, z);
var radius = z==zmin ? 0 : Math.pow(2 , z - zmin - 1);
if (this.options.debug) console.log("Calculate pyramid: Z " + z + " : " + "Radius of " + radius );
for (var x=t_x-radius; x<=t_x+radius; x++) {
for (var y=t_y-radius; y<=t_y+radius; y++) {
xyzlist.push({ x:x, y:y, z:z });
}
}
}
// done!
return xyzlist;
},
calculateXYZListFromBounds: function(bounds, zmin, zmax) {
// Given a bounds (such as that obtained by calling MAP.getBounds()) and a range of zoom levels, returns the list of XYZ trios comprising that view.
// The caller may then call downloadXYZList() with progress and error callbacks to do the fetching.
var xyzlist = [];
for (z = zmin; z <= zmax; z++) {
// Figure out the tile for the northwest point of the bounds.
t1_x = this.getX(bounds.getNorthWest().lng, z);
t1_y = this.getY(bounds.getNorthWest().lat, z);
// Figure out the tile for the southeast point of the bounds.
t2_x = this.getX(bounds.getSouthEast().lng, z);
t2_y = this.getY(bounds.getSouthEast().lat, z);
// Now that we have the coordinates of the two opposing points (in the correct order!), we can iterate over the square.
for (var x = t1_x; x <= t2_x; x++) {
for (var y = t1_y; y <= t2_y; y++) {
xyzlist.push({ x:x, y:y, z:z });
}
}
}
return xyzlist;
},
getX: function(lon, z) {
return Math.floor((lon+180)/360*Math.pow(2,z));
},
getY: function(lat, z) {
var y = Math.floor((1 - Math.log(Math.tan(lat * Math.PI / 180) + 1 / Math.cos(lat * Math.PI / 180)) / Math.PI) / 2 * Math.pow(2, z));
// issue 25: Y calculation for TMS
if (this.options.tms) {
y = Math.pow(2, z) - y - 1;
}
return y;
},
getLng: function(x, z) {
return (x/Math.pow(2,z)*360-180);
},
getLat: function(y, z) {
var n=Math.PI-2*Math.PI*y/Math.pow(2,z);
return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n))));
},
downloadAndStoreTile: function (x,y,z,success_callback,error_callback) {
var myself = this;
var filename = myself.dirhandle.toURL() + '/' + [ myself.options.name, z, x, y ].join('-') + '.png';
var sourceurl = myself._url_online.replace('{z}',z).replace('{x}',x).replace('{y}',y);
if (myself.options.subdomains) {
var idx = Math.floor(Math.random() * myself.options.subdomains.length);
var dom = myself.options.subdomains[idx];
sourceurl = sourceurl.replace('{s}',dom);
}
if (myself.options.debug) console.log("Download " + sourceurl + " => " + filename);
var transfer = new FileTransfer();
transfer.download(
sourceurl,
filename,
function(file) {
// tile downloaded OK; set the iOS "don't back up" flag then move on
file.setMetadata(null, null, { "com.apple.MobileBackup":1 });
if (success_callback) success_callback();
},
function(error) {
var errmsg;
switch (error.code) {
case FileTransferError.FILE_NOT_FOUND_ERR:
errmsg = "File not found:\n" + sourceurl;
break;
case FileTransferError.INVALID_URL_ERR:
errmsg = "Invalid URL:\n" + sourceurl;
break;
case FileTransferError.CONNECTION_ERR:
errmsg = "Connection error at the web server.\n";
break;
}
if (error_callback) error_callback(errmsg);
}
);
},
downloadXYZList: function (xyzlist,overwrite,progress_callback,complete_callback,error_callback) {
var myself = this;
function runThisOneByIndex(xyzs,index,cbprog,cbdone,cberr) {
var x = xyzs[index].x;
var y = xyzs[index].y;
var z = xyzs[index].z;
// thanks to closures this function would call downloadAndStoreTile() for this XYZ, then do the callbacks and all...
// all we need to do is call it below, depending on the overwrite outcome
function doneWithIt() {
// the download was skipped and not an error, so call the progress callback; then either move on to the next one, or else call our success callback
// if the progress callback returns false (not null, not undefiend... false) then do not proceed to the next tile; this allows cancellation from the caller code
if (cbprog) {
var keepgoing = cbprog(index,xyzs.length);
if (keepgoing === false) {
return;
}
}
if (index+1 < xyzs.length) {
runThisOneByIndex(xyzs,index+1,cbprog,cbdone,cberr);
} else {
if (cbdone) cbdone();
}
}
function yesReally() {
myself.downloadAndStoreTile(
x,y,z,
doneWithIt,
function (errmsg) {
// an error in downloading, so we bail on the whole process and run the error callback
if (cberr) cberr(errmsg);
}
);
}
// trick: if 'overwrite' is true we can just go ahead and download
// BUT... if overwrite is false, then test that the file doesn't exist first by failing to open it
if (overwrite) {
if (myself.options.debug) console.log("Tile " + z + '/' + x + '/' + y + " -- " + "Overwrite=true so proceeding.");
yesReally();
} else {
var filename = [ myself.options.name, z, x, y ].join('-') + '.png';
myself.dirhandle.getFile(
filename,
{ create:false },
function () { // opened the file OK, and we didn't ask for overwrite... we're done here, same as if we had downloaded properly
if (myself.options.debug) console.log(filename + " exists. Skipping.");
doneWithIt();
},
function () { // failed to open file, guess we are good to download it since we don't have it
if (myself.options.debug) console.log(filename + " missing. Fetching.");
yesReally();
}
);
}
}
runThisOneByIndex(xyzlist,0,progress_callback,complete_callback,error_callback);
},
/*
*
* Other maintenance functions, e.g. count up the cache's usage, and empty the cache
*
*/
getDiskUsage: function (callback) {
var myself = this;
var dirReader = myself.dirhandle.createReader();
var name_match = new RegExp('^' + myself.options.name + '-');
dirReader.readEntries(function (entries) {
// a mix of files & directories. In our case we know it's all files and all cached tiles, so just add up the filesize
var files = 0;
var bytes = 0;
function processFileEntry(index) {
if (index >= entries.length) {
if (callback) callback(files,bytes);
return;
}
// workaround for smoeone storing multiple layers in one folder, or other files in this folder
// if this file doesn't start with our own name, it's not for this tile layer
if (entries[index].isFile && name_match.exec(entries[index].name)) {
entries[index].file(
function (fileinfo) {
bytes += fileinfo.size;
files++;
processFileEntry(index+1);
},
function () {
// failed to get file info? impossible, but if it somehow happens just skip on to the next file
processFileEntry(index+1);
}
);
}
else {
// skip it; next!
processFileEntry(index+1);
}
}
processFileEntry(0);
}, function () {
throw "L.TileLayer.Cordova: getDiskUsage: Failed to read directory";
});
},
emptyCache: function (callback) {
var myself = this;
var dirReader = myself.dirhandle.createReader();
var name_match = new RegExp('^' + myself.options.name + '-');
dirReader.readEntries(function (entries) {
var success = 0;
var failed = 0;
function processFileEntry(index) {
if (index >= entries.length) {
if (callback) callback(success,failed);
return;
}
// if this file doesn't start with our own name, it's not for this tile layer
if (entries[index].isFile && name_match.exec(entries[index].name)) {
entries[index].remove(
function () {
success++;
processFileEntry(index+1);
},
function () {
failed++;
processFileEntry(index+1);
}
);
}
else {
// skip it; next!
processFileEntry(index+1);
}
}
processFileEntry(0);
}, function () {
throw "L.TileLayer.Cordova: emptyCache: Failed to read directory";
});
},
getCacheContents: function(done_callback) {
var myself = this;
var dirReader = myself.dirhandle.createReader();
dirReader.readEntries(function (entries) {
var retval = [];
for (var i = 0; i < entries.length; i++) {
var e = entries[i];
if (e.isFile) {
var myEntry = {
name: e.name,
fullPath: e.fullPath,
nativeURL: e.nativeURL
};
// Extract the x,y,z pieces from the filename.
var parts_outer = e.name.split(".");
if (parts_outer.length >= 1) {
var parts = parts_outer[0].split('-');
if (parts.length >= 4) {
myEntry['z'] = parts[1];
myEntry['x'] = parts[2];
myEntry['y'] = parts[3];
myEntry['lat'] = myself.getLat(myEntry.y, myEntry.z);
myEntry['lng'] = myself.getLng(myEntry.x, myEntry.z);
}
}
retval.push(myEntry);
}
}
if (done_callback) done_callback(retval);
}, function() {
throw "L.TileLayer.Cordova: getCacheContents: Failed to read directory";
});
}
}); // end of L.TileLayer.Cordova class
|
/* globals Promise:true */
var _ = require('lodash')
var Promise = require('bluebird')
var errors = require('../../../../lib/errors')
var SQL = require('../../sql')
var qutil = require('../util/query')
module.exports.v1 = {}
module.exports.v2 = {}
function latest (req) {
return req.storage.executeQuery(SQL.select.blocks.latest)
.then(function (result) {
var row = result.rows[0]
return {
height: row.height,
hash: row.hash.toString('hex'),
header: row.header.toString('hex')
}
})
}
module.exports.v1.latest = function (req, res) {
var promise = latest(req)
.then(function (result) {
result.blockid = result.hash
delete result.hash
return result
})
res.promise(promise)
}
module.exports.v2.latest = function (req, res) {
res.promise(latest(req))
}
function query (req, res, shift) {
var result = Promise.try(function () {
var query = {
from: qutil.transformFrom(req.query.from),
to: qutil.transformTo(req.query.to),
count: qutil.transformCount(req.query.count) || 2016
}
return req.storage.executeTransaction(function (client) {
return Promise.try(function () {
if (query.from === undefined) {
return -1
}
return qutil.getHeightForPoint(client, query.from)
})
.then(function (from) {
if (from === null) {
throw new errors.Slave.FromNotFound()
}
if (query.to === undefined) {
return [from, from + query.count]
}
return qutil.getHeightForPoint(client, query.to)
.then(function (to) {
if (to === null) {
throw new errors.Slave.ToNotFound()
}
return [from, to]
})
})
.spread(function (from, to) {
var count = to - from
if (count <= 0 || count > 2016) {
throw new errors.Slave.InvalidRequestedCount()
}
var params = [from + shift, to + shift]
return Promise.all([
from,
client.queryAsync(SQL.select.blocks.headers, params)
])
})
.spread(function (from, result) {
var headers = _.chain(result.rows)
.pluck('header')
.invoke('toString', 'hex')
.join('')
.value()
return {from: from, count: headers.length / 160, headers: headers}
})
})
})
res.promise(result)
}
module.exports.v1.query = function (req, res) { query(req, res, -1) }
module.exports.v2.query = function (req, res) { query(req, res, 0) }
|
/**
* @author Geert Fokke [geert@sector22.com]
* @www sector22.com
*/
//@formatter:off
var Result = require('./Result');
var inherits = require('../../core/utils/inherits');
//@formatter:on
inherits(DataResult, Result);
/**
* An object containing result data with a data object
* @param data {*}
* @constructor
* @extends {Result}
*/
function DataResult(data, success, message, code, opt_url) {
DataResult.super_.call(this, success, message, code, opt_url);
var _data = data;
Object.defineProperty(this, 'data', {
enumerable: true,
get: function () {
return _data;
}
});
}
module.exports = DataResult;
|
$(function() {
$.getJSON('api', updateFeedback);
$('.feedback-form').submit(function(e) {
e.preventDefault();
$.post('api', {
name: $('#feedback-form-name').val(),
title: $('#feedback-form-title').val(),
message: $('#feedback-form-message').val()
}, updateFeedback);
});
$('.feedback-messages').on('click', function(e) {
if (e.target.className == 'glyphicon glyphicon-remove') {
$.ajax({
url: 'api/' + e.target.id,
type: 'DELETE',
success: updateFeedback
}); //ajax
} // the target is a delete button
}); //feedback messages
function updateFeedback(data) {
var output = '';
$.each(data,function(key, item) {
output += ' <div class="feedback-item item-list media-list">';
output += ' <div class="feedback-item media">';
output += ' <div class="media-left"><button class="feedback-delete btn btn-xs btn-danger"><span id="' + key + '" class="glyphicon glyphicon-remove"></span></button></div>';
output += ' <div class="feedback-info media-body">';
output += ' <div class="feedback-head">';
output += ' <div class="feedback-title">' + item.title + ' <small class="feedback-name label label-info">' + item.name + '</small></div>';
output += ' </div>';
output += ' <div class="feedback-message">' + item.message + '</div>';
output += ' </div>';
output += ' </div>';
output += ' </div>';
});
$('.feedback-messages').html(output);
}
});
|
var NRS = (function(NRS, $, undefined) {
NRS.forms.errorMessages.startForging = {
"5": "您无法锻造,主要是您余额是0,而且帐号太新了(至少要超过一天的时间)."
};
NRS.forms.startForgingComplete = function(response, data) {
if ("deadline" in response) {
$("#forging_indicator").addClass("forging");
$("#forging_indicator span").html("Forging");
NRS.isForging = true;
$.growl("Forging started successfully.", {
type: "success"
});
} else {
NRS.isForging = false;
$.growl("Couldn't start forging, unknown error.", {
type: 'danger'
});
}
}
NRS.forms.stopForgingComplete = function(response, data) {
if ($("#stop_forging_modal .show_logout").css("display") == "inline") {
NRS.logout();
return;
}
$("#forging_indicator").removeClass("forging");
$("#forging_indicator span").html("Not forging");
NRS.isForging = false;
if (response.foundAndStopped) {
$.growl("Forging stopped successfully.", {
type: 'success'
});
} else {
$.growl("You weren't forging to begin with.", {
type: 'danger'
});
}
}
$("#forging_indicator").click(function(e) {
e.preventDefault();
if (NRS.downloadingBlockchain) {
$.growl("块链正在下载中,此时您无法锻造,请在块链下载完成后再试一次.", {
"type": "danger"
});
} else if (NRS.state.isScanning) {
$.growl("块链正在重新扫描,这段时间内您无法锻造,请一分钟后再试.", {
"type": "danger"
});
} else if (!NRS.accountInfo.publicKey) {
$.growl("因为您的帐号没有公钥,所以无法锻造,请先发送第一笔交易.", {
"type": "danger"
});
} else if (NRS.accountInfo.effectiveBalanceNXT == 0) {
if (NRS.lastBlockHeight >= NRS.accountInfo.currentLeasingHeightFrom && NRS.lastBlockHeight <= NRS.accountInfo.currentLeasingHeightTo) {
$.growl("您的有效余额已出租,租用期内您暂时无法锻造.", {
"type": "danger"
});
} else {
$.growl("您的有效余额是0,无法进行锻造.", {
"type": "danger"
});
}
} else if ($(this).hasClass("forging")) {
$("#stop_forging_modal").modal("show");
} else {
$("#start_forging_modal").modal("show");
}
});
return NRS;
}(NRS || {}, jQuery));
|
// MooTools: the javascript framework.
// Load this file's selection again by visiting: http://mootools.net/more/8eff294bf56290a32b86a9b78d3695b6
// Or build this file again with packager using: packager build More/Chain.Wait More/Array.Extras More/Date.Extras More/Number.Format More/URI.Relative More/Hash.Extras More/Element.Pin More/Form.Request.Append More/Form.Validator.Inline More/Form.Validator.Extras More/OverText More/Fx.Accordion More/Fx.Move More/Fx.Reveal More/Fx.Slide More/Fx.SmoothScroll More/Fx.Sort More/Slider More/Sortables More/Request.JSONP More/Request.Queue More/Request.Periodical More/Assets More/Color More/Group More/Hash.Cookie More/HtmlTable.Zebra More/HtmlTable.Sort More/HtmlTable.Select More/Keyboard.Extras More/Scroller More/Tips More/Spinner More/Locale
/*
---
script: More.js
name: More
description: MooTools More
license: MIT-style license
authors:
- Guillermo Rauch
- Thomas Aylott
- Scott Kyle
- Arian Stolwijk
- Tim Wienk
- Christoph Pojer
- Aaron Newton
requires:
- Core/MooTools
provides: [MooTools.More]
...
*/
MooTools.More = {
'version': '1.3.0.1',
'build': '6dce99bed2792dffcbbbb4ddc15a1fb9a41994b5'
};
/*
---
script: Chain.Wait.js
name: Chain.Wait
description: value, Adds a method to inject pauses between chained events.
license: MIT-style license.
authors:
- Aaron Newton
requires:
- Core/Chain
- Core/Element
- Core/Fx
- /MooTools.More
provides: [Chain.Wait]
...
*/
(function(){
var wait = {
wait: function(duration){
return this.chain(function(){
this.callChain.delay(duration == null ? 500 : duration, this);
}.bind(this));
}
};
Chain.implement(wait);
if (this.Fx){
Fx.implement(wait);
['Css', 'Tween', 'Elements'].each(function(cls){
if (Fx[cls]) Fx[cls].implement(wait);
});
}
if (this.Element && this.Fx){
Element.implement({
chains: function(effects){
Array.from(effects || ['tween', 'morph', 'reveal']).each(function(effect){
effect = this.get(effect);
if (!effect) return;
effect.setOptions({
link:'chain'
});
}, this);
return this;
},
pauseFx: function(duration, effect){
this.chains(effect).get(effect || 'tween').wait(duration);
return this;
}
});
}
})();
/*
---
script: Array.Extras.js
name: Array.Extras
description: Extends the Array native object to include useful methods to work with arrays.
license: MIT-style license
authors:
- Christoph Pojer
- Sebastian Markbåge
requires:
- Core/Array
provides: [Array.Extras]
...
*/
Array.implement({
min: function(){
return Math.min.apply(null, this);
},
max: function(){
return Math.max.apply(null, this);
},
average: function(){
return this.length ? this.sum() / this.length : 0;
},
sum: function(){
var result = 0, l = this.length;
if (l){
while(l--) result += this[l];
}
return result;
},
unique: function(){
return [].combine(this);
},
shuffle: function(){
for (var i = this.length; i && --i;){
var temp = this[i], r = Math.floor(Math.random() * ( i + 1 ));
this[i] = this[r];
this[r] = temp;
}
return this;
},
reduce: function(fn, value){
var undefined;
for (var i = 0, l = this.length; i < l; i++){
if (i in this) value = value === undefined ? this[i] : fn.call(null, value, this[i], i, this);
}
return value;
},
reduceRight: function(fn, value){
var i = this.length, undefined;
while (i--){
if (i in this) value = value === undefined ? this[i] : fn.call(null, value, this[i], i, this);
}
return value;
}
});
/*
---
script: Object.Extras.js
name: Object.Extras
description: Extra Object generics, like getFromPath which allows a path notation to child elements.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Object
- /MooTools.More
provides: [Object.Extras]
...
*/
(function(){
var defined = function(value){
return value != null;
};
Object.extend({
getFromPath: function(source, key){
var parts = key.split('.');
for (var i = 0, l = parts.length; i < l; i++){
if (source.hasOwnProperty(parts[i])) source = source[parts[i]];
else return null;
}
return source;
},
cleanValues: function(object, method){
method = method || defined;
for (key in object) if (!method(object[key])){
delete object[key];
}
return object;
},
erase: function(object, key){
if (object.hasOwnProperty(key)) delete object[key];
return object;
},
run: function(object){
var args = Array.slice(arguments, 1);
for (key in object) if (object[key].apply){
object[key].apply(object, args);
}
return object;
}
});
})();
/*
---
script: Locale.js
name: Locale
description: Provides methods for localization.
license: MIT-style license
authors:
- Aaron Newton
- Arian Stolwijk
requires:
- Core/Events
- /Object.Extras
- /MooTools.More
provides: [Locale, Lang]
...
*/
(function(){
var current = null,
locales = {},
inherits = {};
var getSet = function(set){
if (instanceOf(set, Locale.Set)) return set;
else return locales[set];
};
var Locale = this.Locale = {
define: function(locale, set, key, value){
var name;
if (instanceOf(locale, Locale.Set)){
name = locale.name;
if (name) locales[name] = locale;
} else {
name = locale;
if (!locales[name]) locales[name] = new Locale.Set(name);
locale = locales[name];
}
if (set) locale.define(set, key, value);
if (!current) current = locale;
return locale;
},
use: function(locale){
locale = getSet(locale);
if (locale){
current = locale;
this.fireEvent('change', locale);
}
return this;
},
getCurrent: function(){
return current;
},
get: function(key, args){
return (current) ? current.get(key, args) : '';
},
inherit: function(locale, inherits, set){
locale = getSet(locale);
if (locale) locale.inherit(inherits, set);
return this;
},
list: function(){
return Object.keys(locales);
}
};
Object.append(Locale, new Events);
Locale.Set = new Class({
sets: {},
inherits: {
locales: [],
sets: {}
},
initialize: function(name){
this.name = name || '';
},
define: function(set, key, value){
var defineData = this.sets[set];
if (!defineData) defineData = {};
if (key){
if (typeOf(key) == 'object') defineData = Object.merge(defineData, key);
else defineData[key] = value;
}
this.sets[set] = defineData;
return this;
},
get: function(key, args, _base){
var value = Object.getFromPath(this.sets, key);
if (value != null){
var type = typeOf(value);
if (type == 'function') value = value.apply(null, Array.from(args));
else if (type == 'object') value = Object.clone(value);
return value;
}
// get value of inherited locales
var index = key.indexOf('.'),
set = index < 0 ? key : key.substr(0, index),
names = (this.inherits.sets[set] || []).combine(this.inherits.locales).include('en-US');
if (!_base) _base = [];
for (var i = 0, l = names.length; i < l; i++){
if (_base.contains(names[i])) continue;
_base.include(names[i]);
var locale = locales[names[i]];
if (!locale) continue;
value = locale.get(key, args, _base);
if (value != null) return value;
}
return '';
},
inherit: function(names, set){
names = Array.from(names);
if (set && !this.inherits.sets[set]) this.inherits.sets[set] = [];
var l = names.length;
while (l--) (set ? this.inherits.sets[set] : this.inherits.locales).unshift(names[l]);
return this;
}
});
})();
/*
---
name: Locale.en-US.Date
description: Date messages for US English.
license: MIT-style license
authors:
- Aaron Newton
requires:
- /Locale
provides: [Locale.en-US.Date]
...
*/
Locale.define('en-US', 'Date', {
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
months_abbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
days_abbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
// Culture's date order: MM/DD/YYYY
dateOrder: ['month', 'date', 'year'],
shortDate: '%m/%d/%Y',
shortTime: '%I:%M%p',
AM: 'AM',
PM: 'PM',
// Date.Extras
ordinal: function(dayOfMonth){
// 1st, 2nd, 3rd, etc.
return (dayOfMonth > 3 && dayOfMonth < 21) ? 'th' : ['th', 'st', 'nd', 'rd', 'th'][Math.min(dayOfMonth % 10, 4)];
},
lessThanMinuteAgo: 'less than a minute ago',
minuteAgo: 'about a minute ago',
minutesAgo: '{delta} minutes ago',
hourAgo: 'about an hour ago',
hoursAgo: 'about {delta} hours ago',
dayAgo: '1 day ago',
daysAgo: '{delta} days ago',
weekAgo: '1 week ago',
weeksAgo: '{delta} weeks ago',
monthAgo: '1 month ago',
monthsAgo: '{delta} months ago',
yearAgo: '1 year ago',
yearsAgo: '{delta} years ago',
lessThanMinuteUntil: 'less than a minute from now',
minuteUntil: 'about a minute from now',
minutesUntil: '{delta} minutes from now',
hourUntil: 'about an hour from now',
hoursUntil: 'about {delta} hours from now',
dayUntil: '1 day from now',
daysUntil: '{delta} days from now',
weekUntil: '1 week from now',
weeksUntil: '{delta} weeks from now',
monthUntil: '1 month from now',
monthsUntil: '{delta} months from now',
yearUntil: '1 year from now',
yearsUntil: '{delta} years from now'
});
/*
---
script: Date.js
name: Date
description: Extends the Date native object to include methods useful in managing dates.
license: MIT-style license
authors:
- Aaron Newton
- Nicholas Barthelemy - https://svn.nbarthelemy.com/date-js/
- Harald Kirshner - mail [at] digitarald.de; http://digitarald.de
- Scott Kyle - scott [at] appden.com; http://appden.com
requires:
- Core/Array
- Core/String
- Core/Number
- /Locale
- /Locale.en-US.Date
- /MooTools.More
provides: [Date]
...
*/
(function(){
var Date = this.Date;
Date.Methods = {
ms: 'Milliseconds',
year: 'FullYear',
min: 'Minutes',
mo: 'Month',
sec: 'Seconds',
hr: 'Hours'
};
['Date', 'Day', 'FullYear', 'Hours', 'Milliseconds', 'Minutes', 'Month', 'Seconds', 'Time', 'TimezoneOffset',
'Week', 'Timezone', 'GMTOffset', 'DayOfYear', 'LastMonth', 'LastDayOfMonth', 'UTCDate', 'UTCDay', 'UTCFullYear',
'AMPM', 'Ordinal', 'UTCHours', 'UTCMilliseconds', 'UTCMinutes', 'UTCMonth', 'UTCSeconds', 'UTCMilliseconds'].each(function(method){
Date.Methods[method.toLowerCase()] = method;
});
var pad = function(what, length, string){
if (!string) string = '0';
return new Array(length - String(what).length + 1).join(string) + what;
};
Date.implement({
set: function(prop, value){
prop = prop.toLowerCase();
var m = Date.Methods;
if (m[prop]) this['set' + m[prop]](value);
return this;
}.overloadSetter(),
get: function(prop){
prop = prop.toLowerCase();
var m = Date.Methods;
if (m[prop]) return this['get' + m[prop]]();
return null;
},
clone: function(){
return new Date(this.get('time'));
},
increment: function(interval, times){
interval = interval || 'day';
times = times != null ? times : 1;
switch (interval){
case 'year':
return this.increment('month', times * 12);
case 'month':
var d = this.get('date');
this.set('date', 1).set('mo', this.get('mo') + times);
return this.set('date', d.min(this.get('lastdayofmonth')));
case 'week':
return this.increment('day', times * 7);
case 'day':
return this.set('date', this.get('date') + times);
}
if (!Date.units[interval]) throw new Error(interval + ' is not a supported interval');
return this.set('time', this.get('time') + times * Date.units[interval]());
},
decrement: function(interval, times){
return this.increment(interval, -1 * (times != null ? times : 1));
},
isLeapYear: function(){
return Date.isLeapYear(this.get('year'));
},
clearTime: function(){
return this.set({hr: 0, min: 0, sec: 0, ms: 0});
},
diff: function(date, resolution){
if (typeOf(date) == 'string') date = Date.parse(date);
return ((date - this) / Date.units[resolution || 'day'](3, 3)).round(); // non-leap year, 30-day month
},
getLastDayOfMonth: function(){
return Date.daysInMonth(this.get('mo'), this.get('year'));
},
getDayOfYear: function(){
return (Date.UTC(this.get('year'), this.get('mo'), this.get('date') + 1)
- Date.UTC(this.get('year'), 0, 1)) / Date.units.day();
},
getWeek: function(){
return (this.get('dayofyear') / 7).ceil();
},
getOrdinal: function(day){
return Date.getMsg('ordinal', day || this.get('date'));
},
getTimezone: function(){
return this.toString()
.replace(/^.*? ([A-Z]{3}).[0-9]{4}.*$/, '$1')
.replace(/^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/, '$1$2$3');
},
getGMTOffset: function(){
var off = this.get('timezoneOffset');
return ((off > 0) ? '-' : '+') + pad((off.abs() / 60).floor(), 2) + pad(off % 60, 2);
},
setAMPM: function(ampm){
ampm = ampm.toUpperCase();
var hr = this.get('hr');
if (hr > 11 && ampm == 'AM') return this.decrement('hour', 12);
else if (hr < 12 && ampm == 'PM') return this.increment('hour', 12);
return this;
},
getAMPM: function(){
return (this.get('hr') < 12) ? 'AM' : 'PM';
},
parse: function(str){
this.set('time', Date.parse(str));
return this;
},
isValid: function(date){
return !isNaN((date || this).valueOf());
},
format: function(f){
if (!this.isValid()) return 'invalid date';
f = f || '%x %X';
f = formats[f.toLowerCase()] || f; // replace short-hand with actual format
var d = this;
return f.replace(/%([a-z%])/gi,
function($0, $1){
switch ($1){
case 'a': return Date.getMsg('days_abbr')[d.get('day')];
case 'A': return Date.getMsg('days')[d.get('day')];
case 'b': return Date.getMsg('months_abbr')[d.get('month')];
case 'B': return Date.getMsg('months')[d.get('month')];
case 'c': return d.format('%a %b %d %H:%m:%S %Y');
case 'd': return pad(d.get('date'), 2);
case 'e': return pad(d.get('date'), 2, ' ');
case 'H': return pad(d.get('hr'), 2);
case 'I': return pad((d.get('hr') % 12) || 12, 2);
case 'j': return pad(d.get('dayofyear'), 3);
case 'k': return pad(d.get('hr'), 2, ' ');
case 'l': return pad((d.get('hr') % 12) || 12, 2, ' ');
case 'L': return pad(d.get('ms'), 3);
case 'm': return pad((d.get('mo') + 1), 2);
case 'M': return pad(d.get('min'), 2);
case 'o': return d.get('ordinal');
case 'p': return Date.getMsg(d.get('ampm'));
case 's': return Math.round(d / 1000);
case 'S': return pad(d.get('seconds'), 2);
case 'U': return pad(d.get('week'), 2);
case 'w': return d.get('day');
case 'x': return d.format(Date.getMsg('shortDate'));
case 'X': return d.format(Date.getMsg('shortTime'));
case 'y': return d.get('year').toString().substr(2);
case 'Y': return d.get('year');
case 'z': return d.get('GMTOffset');
case 'Z': return d.get('Timezone');
}
return $1;
}
);
},
toISOString: function(){
return this.format('iso8601');
}
});
Date.alias('toJSON', 'toISOString');
Date.alias('compare', 'diff');
Date.alias('strftime', 'format');
var formats = {
db: '%Y-%m-%d %H:%M:%S',
compact: '%Y%m%dT%H%M%S',
iso8601: '%Y-%m-%dT%H:%M:%S%T',
rfc822: '%a, %d %b %Y %H:%M:%S %Z',
'short': '%d %b %H:%M',
'long': '%B %d, %Y %H:%M'
};
var parsePatterns = [];
var nativeParse = Date.parse;
var parseWord = function(type, word, num){
var ret = -1;
var translated = Date.getMsg(type + 's');
switch (typeOf(word)){
case 'object':
ret = translated[word.get(type)];
break;
case 'number':
ret = translated[word];
if (!ret) throw new Error('Invalid ' + type + ' index: ' + word);
break;
case 'string':
var match = translated.filter(function(name){
return this.test(name);
}, new RegExp('^' + word, 'i'));
if (!match.length) throw new Error('Invalid ' + type + ' string');
if (match.length > 1) throw new Error('Ambiguous ' + type);
ret = match[0];
}
return (num) ? translated.indexOf(ret) : ret;
};
Date.extend({
getMsg: function(key, args){
return Locale.get('Date.' + key, args);
},
units: {
ms: Function.from(1),
second: Function.from(1000),
minute: Function.from(60000),
hour: Function.from(3600000),
day: Function.from(86400000),
week: Function.from(608400000),
month: function(month, year){
var d = new Date;
return Date.daysInMonth(month != null ? month : d.get('mo'), year != null ? year : d.get('year')) * 86400000;
},
year: function(year){
year = year || new Date().get('year');
return Date.isLeapYear(year) ? 31622400000 : 31536000000;
}
},
daysInMonth: function(month, year){
return [31, Date.isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
isLeapYear: function(year){
return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
},
parse: function(from){
var t = typeOf(from);
if (t == 'number') return new Date(from);
if (t != 'string') return from;
from = from.clean();
if (!from.length) return null;
var parsed;
parsePatterns.some(function(pattern){
var bits = pattern.re.exec(from);
return (bits) ? (parsed = pattern.handler(bits)) : false;
});
return parsed || new Date(nativeParse(from));
},
parseDay: function(day, num){
return parseWord('day', day, num);
},
parseMonth: function(month, num){
return parseWord('month', month, num);
},
parseUTC: function(value){
var localDate = new Date(value);
var utcSeconds = Date.UTC(
localDate.get('year'),
localDate.get('mo'),
localDate.get('date'),
localDate.get('hr'),
localDate.get('min'),
localDate.get('sec'),
localDate.get('ms')
);
return new Date(utcSeconds);
},
orderIndex: function(unit){
return Date.getMsg('dateOrder').indexOf(unit) + 1;
},
defineFormat: function(name, format){
formats[name] = format;
},
defineFormats: function(formats){
for (var name in formats) Date.defineFormat(name, formats[name]);
},
defineParser: function(pattern){
parsePatterns.push((pattern.re && pattern.handler) ? pattern : build(pattern));
},
defineParsers: function(){
Array.flatten(arguments).each(Date.defineParser);
},
define2DigitYearStart: function(year){
startYear = year % 100;
startCentury = year - startYear;
}
});
var startCentury = 1900;
var startYear = 70;
var regexOf = function(type){
return new RegExp('(?:' + Date.getMsg(type).map(function(name){
return name.substr(0, 3);
}).join('|') + ')[a-z]*');
};
var replacers = function(key){
switch(key){
case 'x': // iso8601 covers yyyy-mm-dd, so just check if month is first
return ((Date.orderIndex('month') == 1) ? '%m[-./]%d' : '%d[-./]%m') + '([-./]%y)?';
case 'X':
return '%H([.:]%M)?([.:]%S([.:]%s)?)? ?%p? ?%T?';
}
return null;
};
var keys = {
d: /[0-2]?[0-9]|3[01]/,
H: /[01]?[0-9]|2[0-3]/,
I: /0?[1-9]|1[0-2]/,
M: /[0-5]?\d/,
s: /\d+/,
o: /[a-z]*/,
p: /[ap]\.?m\.?/,
y: /\d{2}|\d{4}/,
Y: /\d{4}/,
T: /Z|[+-]\d{2}(?::?\d{2})?/
};
keys.m = keys.I;
keys.S = keys.M;
var currentLanguage;
var recompile = function(language){
currentLanguage = language;
keys.a = keys.A = regexOf('days');
keys.b = keys.B = regexOf('months');
parsePatterns.each(function(pattern, i){
if (pattern.format) parsePatterns[i] = build(pattern.format);
});
};
var build = function(format){
if (!currentLanguage) return {format: format};
var parsed = [];
var re = (format.source || format) // allow format to be regex
.replace(/%([a-z])/gi,
function($0, $1){
return replacers($1) || $0;
}
).replace(/\((?!\?)/g, '(?:') // make all groups non-capturing
.replace(/ (?!\?|\*)/g, ',? ') // be forgiving with spaces and commas
.replace(/%([a-z%])/gi,
function($0, $1){
var p = keys[$1];
if (!p) return $1;
parsed.push($1);
return '(' + p.source + ')';
}
).replace(/\[a-z\]/gi, '[a-z\\u00c0-\\uffff;\&]'); // handle unicode words
return {
format: format,
re: new RegExp('^' + re + '$', 'i'),
handler: function(bits){
bits = bits.slice(1).associate(parsed);
var date = new Date().clearTime(),
year = bits.y || bits.Y;
if (year != null) handle.call(date, 'y', year); // need to start in the right year
if ('d' in bits) handle.call(date, 'd', 1);
if ('m' in bits || 'b' in bits || 'B' in bits) handle.call(date, 'm', 1);
for (var key in bits) handle.call(date, key, bits[key]);
return date;
}
};
};
var handle = function(key, value){
if (!value) return this;
switch(key){
case 'a': case 'A': return this.set('day', Date.parseDay(value, true));
case 'b': case 'B': return this.set('mo', Date.parseMonth(value, true));
case 'd': return this.set('date', value);
case 'H': case 'I': return this.set('hr', value);
case 'm': return this.set('mo', value - 1);
case 'M': return this.set('min', value);
case 'p': return this.set('ampm', value.replace(/\./g, ''));
case 'S': return this.set('sec', value);
case 's': return this.set('ms', ('0.' + value) * 1000);
case 'w': return this.set('day', value);
case 'Y': return this.set('year', value);
case 'y':
value = +value;
if (value < 100) value += startCentury + (value < startYear ? 100 : 0);
return this.set('year', value);
case 'T':
if (value == 'Z') value = '+00';
var offset = value.match(/([+-])(\d{2}):?(\d{2})?/);
offset = (offset[1] + '1') * (offset[2] * 60 + (+offset[3] || 0)) + this.getTimezoneOffset();
return this.set('time', this - offset * 60000);
}
return this;
};
Date.defineParsers(
'%Y([-./]%m([-./]%d((T| )%X)?)?)?', // "1999-12-31", "1999-12-31 11:59pm", "1999-12-31 23:59:59", ISO8601
'%Y%m%d(T%H(%M%S?)?)?', // "19991231", "19991231T1159", compact
'%x( %X)?', // "12/31", "12.31.99", "12-31-1999", "12/31/2008 11:59 PM"
'%d%o( %b( %Y)?)?( %X)?', // "31st", "31st December", "31 Dec 1999", "31 Dec 1999 11:59pm"
'%b( %d%o)?( %Y)?( %X)?', // Same as above with month and day switched
'%Y %b( %d%o( %X)?)?', // Same as above with year coming first
'%o %b %d %X %T %Y' // "Thu Oct 22 08:11:23 +0000 2009"
);
Locale.addEvent('change', function(language){
if (Locale.get('Date')) recompile(language);
}).fireEvent('change', Locale.getCurrent());
})();
/*
---
script: Date.Extras.js
name: Date.Extras
description: Extends the Date native object to include extra methods (on top of those in Date.js).
license: MIT-style license
authors:
- Aaron Newton
- Scott Kyle
requires:
- /Date
provides: [Date.Extras]
...
*/
Date.implement({
timeDiffInWords: function(relative_to){
return Date.distanceOfTimeInWords(this, relative_to || new Date);
},
timeDiff: function(to, joiner){
if (to == null) to = new Date;
var delta = ((to - this) / 1000).toInt();
if (!delta) return '0s';
var durations = {s: 60, m: 60, h: 24, d: 365, y: 0};
var duration, vals = [];
for (var step in durations){
if (!delta) break;
if ((duration = durations[step])){
vals.unshift((delta % duration) + step);
delta = (delta / duration).toInt();
} else {
vals.unshift(delta + step);
}
}
return vals.join(joiner || ':');
}
});
Date.alias('timeAgoInWords', 'timeDiffInWords');
Date.extend({
distanceOfTimeInWords: function(from, to){
return Date.getTimePhrase(((to - from) / 1000).toInt());
},
getTimePhrase: function(delta){
var suffix = (delta < 0) ? 'Until' : 'Ago';
if (delta < 0) delta *= -1;
var units = {
minute: 60,
hour: 60,
day: 24,
week: 7,
month: 52 / 12,
year: 12,
eon: Infinity
};
var msg = 'lessThanMinute';
for (var unit in units){
var interval = units[unit];
if (delta < 1.5 * interval){
if (delta > 0.75 * interval) msg = unit;
break;
}
delta /= interval;
msg = unit + 's';
}
delta = delta.round();
return Date.getMsg(msg + suffix, delta).substitute({delta: delta});
}
});
Date.defineParsers(
{
// "today", "tomorrow", "yesterday"
re: /^(?:tod|tom|yes)/i,
handler: function(bits){
var d = new Date().clearTime();
switch(bits[0]){
case 'tom': return d.increment();
case 'yes': return d.decrement();
default: return d;
}
}
},
{
// "next Wednesday", "last Thursday"
re: /^(next|last) ([a-z]+)$/i,
handler: function(bits){
var d = new Date().clearTime();
var day = d.getDay();
var newDay = Date.parseDay(bits[2], true);
var addDays = newDay - day;
if (newDay <= day) addDays += 7;
if (bits[1] == 'last') addDays -= 7;
return d.set('date', d.getDate() + addDays);
}
}
);
/*
---
name: Locale.en-US.Number
description: Number messages for US English.
license: MIT-style license
authors:
- Arian Stolwijk
requires:
- /Locale
provides: [Locale.en-US.Number]
...
*/
Locale.define('en-US', 'Number', {
decimal: '.',
group: ',',
/* Commented properties are the defaults for Number.format
decimals: 0,
precision: 0,
scientific: null,
prefix: null,
suffic: null,
// Negative/Currency/percentage will mixin Number
negative: {
prefix: '-'
},*/
currency: {
// decimals: 2,
prefix: '$ '
}/*,
percentage: {
decimals: 2,
suffix: '%'
}*/
});
/*
---
name: Number.Format
description: Extends the Number Type object to include a number formatting method.
license: MIT-style license
authors:
- Arian Stolwijk
requires:
- Core/Number
- /Locale.en-US.Number
provides: [Number.Extras]
...
*/
Number.implement({
format: function(options){
// Thanks dojo and YUI for some inspiration
var value = this;
if (!options) options = {};
var getOption = function(key){
if (options[key] != null) return options[key];
return Locale.get('Number.' + key);
};
var negative = value < 0,
decimal = getOption('decimal'),
precision = getOption('precision'),
group = getOption('group'),
decimals = getOption('decimals');
if (negative){
var negativeLocale = Locale.get('Number.negative') || {};
if (negativeLocale.prefix == null && negativeLocale.suffix == null) negativeLocale.prefix = '-';
Object.each(negativeLocale, function(value, key){
options[key] = (key == 'prefix' || key == 'suffix') ? (getOption(key) + value) : value;
});
value = -value;
}
var prefix = getOption('prefix'),
suffix = getOption('suffix');
if (decimals > 0 && decimals <= 20) value = value.toFixed(decimals);
if (precision >= 1 && precision <= 21) value = value.toPrecision(precision);
value += '';
if (getOption('scientific') === false && value.indexOf('e') > -1){
var match = value.split('e'),
index,
zeros = +match[1];
value = match[0].replace('.', '');
if (zeros < 0){
zeros = -zeros - 1;
index = match[0].indexOf('.');
if (index > -1) zeros -= index - 1;
while (zeros--) value = '0' + value;
value = '0.' + value;
} else {
index = match[0].lastIndexOf('.');
if (index > -1) zeros -= match[0].length - index - 1;
while (zeros--) value += '0';
}
}
if (decimal != '.') value = value.replace('.', decimal);
if (group){
index = value.lastIndexOf(decimal);
index = (index > -1) ? index : value.length;
var newOutput = value.substring(index),
i = index;
while (i--){
if ((index - i - 1) % 3 == 0 && i != (index - 1)) newOutput = group + newOutput;
newOutput = value.charAt(i) + newOutput;
}
value = newOutput;
}
if (prefix) value = prefix + value;
if (suffix) value += suffix;
return value;
},
formatCurrency: function(){
var locale = Locale.get('Number.currency') || {};
if (locale.scientific == null) locale.scientific = false;
if (locale.decimals == null) locale.decimals = 2;
return this.format(locale);
},
formatPercentage: function(){
var locale = Locale.get('Number.percentage') || {};
if (locale.suffix == null) locale.suffix = '%';
if (locale.decimals == null) locale.decimals = 2;
return this.format(locale);
}
});
/*
---
script: Class.Refactor.js
name: Class.Refactor
description: Extends a class onto itself with new property, preserving any items attached to the class's namespace.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Class
- /MooTools.More
# Some modules declare themselves dependent on Class.Refactor
provides: [Class.refactor, Class.Refactor]
...
*/
Class.refactor = function(original, refactors){
Object.each(refactors, function(item, name){
var origin = original.prototype[name];
if (origin && origin.$origin) origin = origin.$origin;
if (origin && typeof item == 'function'){
original.implement(name, function(){
var old = this.previous;
this.previous = origin;
var value = item.apply(this, arguments);
this.previous = old;
return value;
});
} else {
original.implement(name, item);
}
});
return original;
};
/*
---
script: String.QueryString.js
name: String.QueryString
description: Methods for dealing with URI query strings.
license: MIT-style license
authors:
- Sebastian Markbåge
- Aaron Newton
- Lennart Pilon
- Valerio Proietti
requires:
- Core/Array
- Core/String
- /MooTools.More
provides: [String.QueryString]
...
*/
String.implement({
parseQueryString: function(decodeKeys, decodeValues){
if (decodeKeys == null) decodeKeys = true;
if (decodeValues == null) decodeValues = true;
var vars = this.split(/[&;]/),
object = {};
if (!vars.length) return object;
vars.each(function(val){
var index = val.indexOf('='),
value = val.substr(index + 1),
keys = index < 0 ? [''] : val.substr(0, index).match(/([^\]\[]+|(\B)(?=\]))/g),
obj = object;
if (decodeValues) value = decodeURIComponent(value);
keys.each(function(key, i){
if (decodeKeys) key = decodeURIComponent(key);
var current = obj[key];
if (i < keys.length - 1) obj = obj[key] = current || {};
else if (typeOf(current) == 'array') current.push(value);
else obj[key] = current != null ? [current, value] : value;
});
});
return object;
},
cleanQueryString: function(method){
return this.split('&').filter(function(val){
var index = val.indexOf('='),
key = index < 0 ? '' : val.substr(0, index),
value = val.substr(index + 1);
return method ? method.call(null, key, value) : (value || value === 0);
}).join('&');
}
});
/*
---
script: URI.js
name: URI
description: Provides methods useful in managing the window location and uris.
license: MIT-style license
authors:
- Sebastian Markbåge
- Aaron Newton
requires:
- Core/Object
- Core/Class
- Core/Class.Extras
- Core/Element
- /String.QueryString
provides: [URI]
...
*/
(function(){
var toString = function(){
return this.get('value');
};
var URI = this.URI = new Class({
Implements: Options,
options: {
/*base: false*/
},
regex: /^(?:(\w+):)?(?:\/\/(?:(?:([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)?(\.\.?$|(?:[^?#\/]*\/)*)([^?#]*)(?:\?([^#]*))?(?:#(.*))?/,
parts: ['scheme', 'user', 'password', 'host', 'port', 'directory', 'file', 'query', 'fragment'],
schemes: {http: 80, https: 443, ftp: 21, rtsp: 554, mms: 1755, file: 0},
initialize: function(uri, options){
this.setOptions(options);
var base = this.options.base || URI.base;
if (!uri) uri = base;
if (uri && uri.parsed) this.parsed = Object.clone(uri.parsed);
else this.set('value', uri.href || uri.toString(), base ? new URI(base) : false);
},
parse: function(value, base){
var bits = value.match(this.regex);
if (!bits) return false;
bits.shift();
return this.merge(bits.associate(this.parts), base);
},
merge: function(bits, base){
if ((!bits || !bits.scheme) && (!base || !base.scheme)) return false;
if (base){
this.parts.every(function(part){
if (bits[part]) return false;
bits[part] = base[part] || '';
return true;
});
}
bits.port = bits.port || this.schemes[bits.scheme.toLowerCase()];
bits.directory = bits.directory ? this.parseDirectory(bits.directory, base ? base.directory : '') : '/';
return bits;
},
parseDirectory: function(directory, baseDirectory){
directory = (directory.substr(0, 1) == '/' ? '' : (baseDirectory || '/')) + directory;
if (!directory.test(URI.regs.directoryDot)) return directory;
var result = [];
directory.replace(URI.regs.endSlash, '').split('/').each(function(dir){
if (dir == '..' && result.length > 0) result.pop();
else if (dir != '.') result.push(dir);
});
return result.join('/') + '/';
},
combine: function(bits){
return bits.value || bits.scheme + '://' +
(bits.user ? bits.user + (bits.password ? ':' + bits.password : '') + '@' : '') +
(bits.host || '') + (bits.port && bits.port != this.schemes[bits.scheme] ? ':' + bits.port : '') +
(bits.directory || '/') + (bits.file || '') +
(bits.query ? '?' + bits.query : '') +
(bits.fragment ? '#' + bits.fragment : '');
},
set: function(part, value, base){
if (part == 'value'){
var scheme = value.match(URI.regs.scheme);
if (scheme) scheme = scheme[1];
if (scheme && this.schemes[scheme.toLowerCase()] == null) this.parsed = { scheme: scheme, value: value };
else this.parsed = this.parse(value, (base || this).parsed) || (scheme ? { scheme: scheme, value: value } : { value: value });
} else if (part == 'data'){
this.setData(value);
} else {
this.parsed[part] = value;
}
return this;
},
get: function(part, base){
switch(part){
case 'value': return this.combine(this.parsed, base ? base.parsed : false);
case 'data' : return this.getData();
}
return this.parsed[part] || '';
},
go: function(){
document.location.href = this.toString();
},
toURI: function(){
return this;
},
getData: function(key, part){
var qs = this.get(part || 'query');
if (!(qs || qs === 0)) return key ? null : {};
var obj = qs.parseQueryString();
return key ? obj[key] : obj;
},
setData: function(values, merge, part){
if (typeof values == 'string'){
var data = this.getData();
data[arguments[0]] = arguments[1];
values = data;
} else if (merge){
values = Object.merge(this.getData(), values);
}
return this.set(part || 'query', Object.toQueryString(values));
},
clearData: function(part){
return this.set(part || 'query', '');
},
toString: toString,
valueOf: toString
});
URI.regs = {
endSlash: /\/$/,
scheme: /^(\w+):/,
directoryDot: /\.\/|\.$/
};
URI.base = new URI(Array.from(document.getElements('base[href]', true)).getLast(), {base: document.location});
String.implement({
toURI: function(options){
return new URI(this, options);
}
});
})();
/*
---
script: URI.Relative.js
name: URI.Relative
description: Extends the URI class to add methods for computing relative and absolute urls.
license: MIT-style license
authors:
- Sebastian Markbåge
requires:
- /Class.refactor
- /URI
provides: [URI.Relative]
...
*/
URI = Class.refactor(URI, {
combine: function(bits, base){
if (!base || bits.scheme != base.scheme || bits.host != base.host || bits.port != base.port)
return this.previous.apply(this, arguments);
var end = bits.file + (bits.query ? '?' + bits.query : '') + (bits.fragment ? '#' + bits.fragment : '');
if (!base.directory) return (bits.directory || (bits.file ? '' : './')) + end;
var baseDir = base.directory.split('/'),
relDir = bits.directory.split('/'),
path = '',
offset;
var i = 0;
for (offset = 0; offset < baseDir.length && offset < relDir.length && baseDir[offset] == relDir[offset]; offset++);
for (i = 0; i < baseDir.length - offset - 1; i++) path += '../';
for (i = offset; i < relDir.length - 1; i++) path += relDir[i] + '/';
return (path || (bits.file ? '' : './')) + end;
},
toAbsolute: function(base){
base = new URI(base);
if (base) base.set('directory', '').set('file', '');
return this.toRelative(base);
},
toRelative: function(base){
return this.get('value', new URI(base));
}
});
/*
---
name: Hash
description: Contains Hash Prototypes. Provides a means for overcoming the JavaScript practical impossibility of extending native Objects.
license: MIT-style license.
requires:
- Core/Object
- /MooTools.More
provides: [Hash]
...
*/
(function(){
if (this.Hash) return;
var Hash = this.Hash = new Type('Hash', function(object){
if (typeOf(object) == 'hash') object = Object.clone(object.getClean());
for (var key in object) this[key] = object[key];
return this;
});
this.$H = function(object){
return new Hash(object);
};
Hash.implement({
forEach: function(fn, bind){
Object.forEach(this, fn, bind);
},
getClean: function(){
var clean = {};
for (var key in this){
if (this.hasOwnProperty(key)) clean[key] = this[key];
}
return clean;
},
getLength: function(){
var length = 0;
for (var key in this){
if (this.hasOwnProperty(key)) length++;
}
return length;
}
});
Hash.alias('each', 'forEach');
Hash.implement({
has: Object.prototype.hasOwnProperty,
keyOf: function(value){
return Object.keyOf(this, value);
},
hasValue: function(value){
return Object.contains(this, value);
},
extend: function(properties){
Hash.each(properties || {}, function(value, key){
Hash.set(this, key, value);
}, this);
return this;
},
combine: function(properties){
Hash.each(properties || {}, function(value, key){
Hash.include(this, key, value);
}, this);
return this;
},
erase: function(key){
if (this.hasOwnProperty(key)) delete this[key];
return this;
},
get: function(key){
return (this.hasOwnProperty(key)) ? this[key] : null;
},
set: function(key, value){
if (!this[key] || this.hasOwnProperty(key)) this[key] = value;
return this;
},
empty: function(){
Hash.each(this, function(value, key){
delete this[key];
}, this);
return this;
},
include: function(key, value){
if (this[key] == undefined) this[key] = value;
return this;
},
map: function(fn, bind){
return new Hash(Object.map(this, fn, bind));
},
filter: function(fn, bind){
return new Hash(Object.filter(this, fn, bind));
},
every: function(fn, bind){
return Object.every(this, fn, bind);
},
some: function(fn, bind){
return Object.some(this, fn, bind);
},
getKeys: function(){
return Object.keys(this);
},
getValues: function(){
return Object.values(this);
},
toQueryString: function(base){
return Object.toQueryString(this, base);
}
});
Hash.alias({indexOf: 'keyOf', contains: 'hasValue'});
})();
/*
---
script: Hash.Extras.js
name: Hash.Extras
description: Extends the Hash Type to include getFromPath which allows a path notation to child elements.
license: MIT-style license
authors:
- Aaron Newton
requires:
- /Hash
- /Object.Extras
provides: [Hash.Extras]
...
*/
Hash.implement({
getFromPath: function(notation){
return Object.getFromPath(this, notation);
},
cleanValues: function(method){
return new Hash(Object.cleanValues(this, method));
},
run: function(){
Object.run(arguments);
}
});
/*
---
script: Element.Pin.js
name: Element.Pin
description: Extends the Element native object to include the pin method useful for fixed positioning for elements.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Element.Event
- Core/Element.Dimensions
- Core/Element.Style
- /MooTools.More
provides: [Element.Pin]
...
*/
(function(){
var supportsPositionFixed = false,
supportTested = false;
var testPositionFixed = function(){
var test = new Element('div').setStyles({
position: 'fixed',
top: 0,
right: 0
}).inject(document.body);
supportsPositionFixed = (test.offsetTop === 0);
test.dispose();
supportTested = true;
}
Element.implement({
pin: function(enable, forceScroll){
if (!supportTested) testPositionFixed();
if (this.getStyle('display') == 'none') return this;
var pinnedPosition,
scroll = window.getScroll();
if (enable !== false){
pinnedPosition = this.getPosition(supportsPositionFixed ? document.body : this.getOffsetParent());
if (!this.retrieve('pin:_pinned')){
var currentPosition = {
top: pinnedPosition.y - scroll.y,
left: pinnedPosition.x - scroll.x
};
if (supportsPositionFixed && !forceScroll){
this.setStyle('position', 'fixed').setStyles(currentPosition);
} else {
var parent = this.getOffsetParent(),
position = this.getPosition(parent),
styles = this.getStyles('left', 'top');
if (parent && styles.left == 'auto' || styles.top == 'auto') this.setPosition(position);
if (this.getStyle('position') == 'static') this.setStyle('position', 'absolute');
position = {
x: styles.left.toInt() - scroll.x,
y: styles.top.toInt() - scroll.y
};
var scrollFixer = function(){
if (!this.retrieve('pin:_pinned')) return;
var scroll = window.getScroll();
this.setStyles({
left: position.x + scroll.x,
top: position.y + scroll.y
});
}.bind(this);
this.store('pin:_scrollFixer', scrollFixer);
window.addEvent('scroll', scrollFixer);
}
this.store('pin:_pinned', true);
}
} else {
if (!this.retrieve('pin:_pinned')) return this;
var parent = this.getParent(),
offsetParent = (parent.getComputedStyle('position') != 'static' ? parent : parent.getOffsetParent());
pinnedPosition = this.getPosition(offsetParent);
this.store('pin:_pinned', false);
var scrollFixer = this.retrieve('pin:_scrollFixer');
if (!scrollFixer){
this.setStyles({
position: 'absolute',
top: pinnedPosition.y + scroll.y,
left: pinnedPosition.x + scroll.x
});
} else {
this.store('pin:_scrollFixer', null);
window.removeEvent('scroll', scrollFixer);
}
this.removeClass('isPinned');
}
return this;
},
unpin: function(){
return this.pin(false);
},
togglepin: function(){
return this.pin(!this.retrieve('pin:_pinned'));
}
});
})();
/*
---
script: Class.Binds.js
name: Class.Binds
description: Automagically binds specified methods in a class to the instance of the class.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Class
- /MooTools.More
provides: [Class.Binds]
...
*/
Class.Mutators.Binds = function(binds){
return binds;
};
Class.Mutators.initialize = function(initialize){
return function(){
Array.from(this.Binds).each(function(name){
var original = this[name];
if (original) this[name] = original.bind(this);
}, this);
return initialize.apply(this, arguments);
};
};
/*
---
script: Class.Occlude.js
name: Class.Occlude
description: Prevents a class from being applied to a DOM element twice.
license: MIT-style license.
authors:
- Aaron Newton
requires:
- Core/Class
- Core/Element
- /MooTools.More
provides: [Class.Occlude]
...
*/
Class.Occlude = new Class({
occlude: function(property, element){
element = document.id(element || this.element);
var instance = element.retrieve(property || this.property);
if (instance && this.occluded != null)
return this.occluded = instance;
this.occluded = false;
element.store(property || this.property, this);
return this.occluded;
}
});
/*
---
script: Element.Measure.js
name: Element.Measure
description: Extends the Element native object to include methods useful in measuring dimensions.
credits: "Element.measure / .expose methods by Daniel Steigerwald License: MIT-style license. Copyright: Copyright (c) 2008 Daniel Steigerwald, daniel.steigerwald.cz"
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Element.Style
- Core/Element.Dimensions
- /MooTools.More
provides: [Element.Measure]
...
*/
(function(){
var getStylesList = function(styles, planes){
var list = [];
Object.each(planes, function(directions){
Object.each(directions, function(edge){
styles.each(function(style){
list.push(style + '-' + edge + (style == 'border' ? '-width' : ''));
});
});
});
return list;
};
var calculateEdgeSize = function(edge, styles){
var total = 0;
Object.each(styles, function(value, style){
if (style.test(edge)) total = total + value.toInt();
});
return total;
};
Element.implement({
measure: function(fn){
var visibility = function(el){
return !!(!el || el.offsetHeight || el.offsetWidth);
};
if (visibility(this)) return fn.apply(this);
var parent = this.getParent(),
restorers = [],
toMeasure = [];
while (!visibility(parent) && parent != document.body){
toMeasure.push(parent.expose());
parent = parent.getParent();
}
var restore = this.expose();
var result = fn.apply(this);
restore();
toMeasure.each(function(restore){
restore();
});
return result;
},
expose: function(){
if (this.getStyle('display') != 'none') return function(){};
var before = this.style.cssText;
this.setStyles({
display: 'block',
position: 'absolute',
visibility: 'hidden'
});
return function(){
this.style.cssText = before;
}.bind(this);
},
getDimensions: function(options){
options = Object.merge({computeSize: false}, options);
var dim = {x: 0, y: 0};
var getSize = function(el, options){
return (options.computeSize) ? el.getComputedSize(options) : el.getSize();
};
var parent = this.getParent('body');
if (parent && this.getStyle('display') == 'none'){
dim = this.measure(function(){
return getSize(this, options);
});
} else if (parent){
try { //safari sometimes crashes here, so catch it
dim = getSize(this, options);
}catch(e){}
}
return Object.append(dim, (dim.x || dim.x === 0) ? {
width: dim.x,
height: dim.y
} : {
x: dim.width,
y: dim.height
}
);
},
getComputedSize: function(options){
options = Object.merge({
styles: ['padding','border'],
planes: {
height: ['top','bottom'],
width: ['left','right']
},
mode: 'both'
}, options);
var styles = {},
size = {width: 0, height: 0};
if (options.mode == 'vertical'){
delete size.width;
delete options.planes.width;
} else if (options.mode == 'horizontal'){
delete size.height;
delete options.planes.height;
}
getStylesList(options.styles, options.planes).each(function(style){
styles[style] = this.getStyle(style).toInt();
}, this);
Object.each(options.planes, function(edges, plane){
var capitalized = plane.capitalize();
styles[plane] = this.getStyle(plane).toInt();
size['total' + capitalized] = styles[plane];
edges.each(function(edge){
var edgesize = calculateEdgeSize(edge, styles);
size['computed' + edge.capitalize()] = edgesize;
size['total' + capitalized] += edgesize;
});
}, this);
return Object.append(size, styles);
}
});
})();
/*
---
script: Element.Position.js
name: Element.Position
description: Extends the Element native object to include methods useful positioning elements relative to others.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Element.Dimensions
- /Element.Measure
provides: [Element.Position]
...
*/
(function(){
var original = Element.prototype.position;
Element.implement({
position: function(options){
//call original position if the options are x/y values
if (options && (options.x != null || options.y != null)){
return original ? original.apply(this, arguments) : this;
}
Object.each(options || {}, function(v, k){
if (v == null) delete options[k];
});
options = Object.merge({
// minimum: { x: 0, y: 0 },
// maximum: { x: 0, y: 0},
relativeTo: document.body,
position: {
x: 'center', //left, center, right
y: 'center' //top, center, bottom
},
offset: {x: 0, y: 0}/*,
edge: false,
returnPos: false,
relFixedPosition: false,
ignoreMargins: false,
ignoreScroll: false,
allowNegative: false*/
}, options);
//compute the offset of the parent positioned element if this element is in one
var parentOffset = {x: 0, y: 0},
parentPositioned = false;
/* dollar around getOffsetParent should not be necessary, but as it does not return
* a mootools extended element in IE, an error occurs on the call to expose. See:
* http://mootools.lighthouseapp.com/projects/2706/tickets/333-element-getoffsetparent-inconsistency-between-ie-and-other-browsers */
var offsetParent = this.measure(function(){
return document.id(this.getOffsetParent());
});
if (offsetParent && offsetParent != this.getDocument().body){
parentOffset = offsetParent.measure(function(){
return this.getPosition();
});
parentPositioned = offsetParent != document.id(options.relativeTo);
options.offset.x = options.offset.x - parentOffset.x;
options.offset.y = options.offset.y - parentOffset.y;
}
//upperRight, bottomRight, centerRight, upperLeft, bottomLeft, centerLeft
//topRight, topLeft, centerTop, centerBottom, center
var fixValue = function(option){
if (typeOf(option) != 'string') return option;
option = option.toLowerCase();
var val = {};
if (option.test('left')){
val.x = 'left';
} else if (option.test('right')){
val.x = 'right';
} else {
val.x = 'center';
}
if (option.test('upper') || option.test('top')){
val.y = 'top';
} else if (option.test('bottom')){
val.y = 'bottom';
} else {
val.y = 'center';
}
return val;
};
options.edge = fixValue(options.edge);
options.position = fixValue(options.position);
if (!options.edge){
if (options.position.x == 'center' && options.position.y == 'center') options.edge = {x:'center', y:'center'};
else options.edge = {x:'left', y:'top'};
}
this.setStyle('position', 'absolute');
var rel = document.id(options.relativeTo) || document.body,
calc = rel == document.body ? window.getScroll() : rel.getPosition(),
top = calc.y, left = calc.x;
var dim = this.getDimensions({
computeSize: true,
styles:['padding', 'border','margin']
});
var pos = {},
prefY = options.offset.y,
prefX = options.offset.x,
winSize = window.getSize();
switch(options.position.x){
case 'left':
pos.x = left + prefX;
break;
case 'right':
pos.x = left + prefX + rel.offsetWidth;
break;
default: //center
pos.x = left + ((rel == document.body ? winSize.x : rel.offsetWidth)/2) + prefX;
break;
}
switch(options.position.y){
case 'top':
pos.y = top + prefY;
break;
case 'bottom':
pos.y = top + prefY + rel.offsetHeight;
break;
default: //center
pos.y = top + ((rel == document.body ? winSize.y : rel.offsetHeight)/2) + prefY;
break;
}
if (options.edge){
var edgeOffset = {};
switch(options.edge.x){
case 'left':
edgeOffset.x = 0;
break;
case 'right':
edgeOffset.x = -dim.x-dim.computedRight-dim.computedLeft;
break;
default: //center
edgeOffset.x = -(dim.totalWidth/2);
break;
}
switch(options.edge.y){
case 'top':
edgeOffset.y = 0;
break;
case 'bottom':
edgeOffset.y = -dim.y-dim.computedTop-dim.computedBottom;
break;
default: //center
edgeOffset.y = -(dim.totalHeight/2);
break;
}
pos.x += edgeOffset.x;
pos.y += edgeOffset.y;
}
pos = {
left: ((pos.x >= 0 || parentPositioned || options.allowNegative) ? pos.x : 0).toInt(),
top: ((pos.y >= 0 || parentPositioned || options.allowNegative) ? pos.y : 0).toInt()
};
var xy = {left: 'x', top: 'y'};
['minimum', 'maximum'].each(function(minmax){
['left', 'top'].each(function(lr){
var val = options[minmax] ? options[minmax][xy[lr]] : null;
if (val != null && ((minmax == 'minimum') ? pos[lr] < val : pos[lr] > val)) pos[lr] = val;
});
});
if (rel.getStyle('position') == 'fixed' || options.relFixedPosition){
var winScroll = window.getScroll();
pos.top+= winScroll.y;
pos.left+= winScroll.x;
}
if (options.ignoreScroll){
var relScroll = rel.getScroll();
pos.top -= relScroll.y;
pos.left -= relScroll.x;
}
if (options.ignoreMargins){
pos.left += (
options.edge.x == 'right' ? dim['margin-right'] :
options.edge.x == 'center' ? -dim['margin-left'] + ((dim['margin-right'] + dim['margin-left'])/2) :
- dim['margin-left']
);
pos.top += (
options.edge.y == 'bottom' ? dim['margin-bottom'] :
options.edge.y == 'center' ? -dim['margin-top'] + ((dim['margin-bottom'] + dim['margin-top'])/2) :
- dim['margin-top']
);
}
pos.left = Math.ceil(pos.left);
pos.top = Math.ceil(pos.top);
if (options.returnPos) return pos;
else this.setStyles(pos);
return this;
}
});
})();
/*
---
script: IframeShim.js
name: IframeShim
description: Defines IframeShim, a class for obscuring select lists and flash objects in IE.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Element.Event
- Core/Element.Style
- Core/Options
- Core/Events
- /Element.Position
- /Class.Occlude
provides: [IframeShim]
...
*/
var IframeShim = new Class({
Implements: [Options, Events, Class.Occlude],
options: {
className: 'iframeShim',
src: 'javascript:false;document.write("");',
display: false,
zIndex: null,
margin: 0,
offset: {x: 0, y: 0},
browsers: ((Browser.ie && Browser.version == 6) || (Browser.firefox && Browser.version < 3 && Browser.Platform.mac))
},
property: 'IframeShim',
initialize: function(element, options){
this.element = document.id(element);
if (this.occlude()) return this.occluded;
this.setOptions(options);
this.makeShim();
return this;
},
makeShim: function(){
if (this.options.browsers){
var zIndex = this.element.getStyle('zIndex').toInt();
if (!zIndex){
zIndex = 1;
var pos = this.element.getStyle('position');
if (pos == 'static' || !pos) this.element.setStyle('position', 'relative');
this.element.setStyle('zIndex', zIndex);
}
zIndex = ((this.options.zIndex != null || this.options.zIndex === 0) && zIndex > this.options.zIndex) ? this.options.zIndex : zIndex - 1;
if (zIndex < 0) zIndex = 1;
this.shim = new Element('iframe', {
src: this.options.src,
scrolling: 'no',
frameborder: 0,
styles: {
zIndex: zIndex,
position: 'absolute',
border: 'none',
filter: 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'
},
'class': this.options.className
}).store('IframeShim', this);
var inject = (function(){
this.shim.inject(this.element, 'after');
this[this.options.display ? 'show' : 'hide']();
this.fireEvent('inject');
}).bind(this);
if (!IframeShim.ready) window.addEvent('load', inject);
else inject();
} else {
this.position = this.hide = this.show = this.dispose = Function.from(this);
}
},
position: function(){
if (!IframeShim.ready || !this.shim) return this;
var size = this.element.measure(function(){
return this.getSize();
});
if (this.options.margin != undefined){
size.x = size.x - (this.options.margin * 2);
size.y = size.y - (this.options.margin * 2);
this.options.offset.x += this.options.margin;
this.options.offset.y += this.options.margin;
}
this.shim.set({width: size.x, height: size.y}).position({
relativeTo: this.element,
offset: this.options.offset
});
return this;
},
hide: function(){
if (this.shim) this.shim.setStyle('display', 'none');
return this;
},
show: function(){
if (this.shim) this.shim.setStyle('display', 'block');
return this.position();
},
dispose: function(){
if (this.shim) this.shim.dispose();
return this;
},
destroy: function(){
if (this.shim) this.shim.destroy();
return this;
}
});
window.addEvent('load', function(){
IframeShim.ready = true;
});
/*
---
script: Mask.js
name: Mask
description: Creates a mask element to cover another.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Options
- Core/Events
- Core/Element.Event
- /Class.Binds
- /Element.Position
- /IframeShim
provides: [Mask]
...
*/
var Mask = new Class({
Implements: [Options, Events],
Binds: ['position'],
options: {/*
onShow: function(){},
onHide: function(){},
onDestroy: function(){},
onClick: function(){},
inject: {
where: 'after',
target: null,
},
hideOnClick: false,
id: null,
destroyOnHide: false,*/
style: {},
'class': 'mask',
maskMargins: false,
useIframeShim: true,
iframeShimOptions: {}
},
initialize: function(target, options){
this.target = document.id(target) || document.id(document.body);
this.target.store('mask', this);
this.setOptions(options);
this.render();
this.inject();
},
render: function(){
this.element = new Element('div', {
'class': this.options['class'],
id: this.options.id || 'mask-' + String.uniqueID(),
styles: Object.merge(this.options.style, {
display: 'none'
}),
events: {
click: function(){
this.fireEvent('click');
if (this.options.hideOnClick) this.hide();
}.bind(this)
}
});
this.hidden = true;
},
toElement: function(){
return this.element;
},
inject: function(target, where){
where = where || (this.options.inject ? this.options.inject.where : '') || this.target == document.body ? 'inside' : 'after';
target = target || (this.options.inject ? this.options.inject.target : '') || this.target;
this.element.inject(target, where);
if (this.options.useIframeShim){
this.shim = new IframeShim(this.element, this.options.iframeShimOptions);
this.addEvents({
show: this.shim.show.bind(this.shim),
hide: this.shim.hide.bind(this.shim),
destroy: this.shim.destroy.bind(this.shim)
});
}
},
position: function(){
this.resize(this.options.width, this.options.height);
this.element.position({
relativeTo: this.target,
position: 'topLeft',
ignoreMargins: !this.options.maskMargins,
ignoreScroll: this.target == document.body
});
return this;
},
resize: function(x, y){
var opt = {
styles: ['padding', 'border']
};
if (this.options.maskMargins) opt.styles.push('margin');
var dim = this.target.getComputedSize(opt);
if (this.target == document.body){
var win = window.getScrollSize();
if (dim.totalHeight < win.y) dim.totalHeight = win.y;
if (dim.totalWidth < win.x) dim.totalWidth = win.x;
}
this.element.setStyles({
width: Array.pick([x, dim.totalWidth, dim.x]),
height: Array.pick([y, dim.totalHeight, dim.y])
});
return this;
},
show: function(){
if (!this.hidden) return this;
window.addEvent('resize', this.position);
this.position();
this.showMask.apply(this, arguments);
return this;
},
showMask: function(){
this.element.setStyle('display', 'block');
this.hidden = false;
this.fireEvent('show');
},
hide: function(){
if (this.hidden) return this;
window.removeEvent('resize', this.position);
this.hideMask.apply(this, arguments);
if (this.options.destroyOnHide) return this.destroy();
return this;
},
hideMask: function(){
this.element.setStyle('display', 'none');
this.hidden = true;
this.fireEvent('hide');
},
toggle: function(){
this[this.hidden ? 'show' : 'hide']();
},
destroy: function(){
this.hide();
this.element.destroy();
this.fireEvent('destroy');
this.target.eliminate('mask');
}
});
Element.Properties.mask = {
set: function(options){
var mask = this.retrieve('mask');
if (mask) mask.destroy();
return this.eliminate('mask').store('mask:options', options);
},
get: function(){
var mask = this.retrieve('mask');
if (!mask){
mask = new Mask(this, this.retrieve('mask:options'));
this.store('mask', mask);
}
return mask;
}
};
Element.implement({
mask: function(options){
if (options) this.set('mask', options);
this.get('mask').show();
return this;
},
unmask: function(){
this.get('mask').hide();
return this;
}
});
/*
---
script: Spinner.js
name: Spinner
description: Adds a semi-transparent overlay over a dom element with a spinnin ajax icon.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Fx.Tween
- Core/Request
- /Class.refactor
- /Mask
provides: [Spinner]
...
*/
var Spinner = new Class({
Extends: Mask,
Implements: Chain,
options: {/*
message: false,*/
'class': 'spinner',
containerPosition: {},
content: {
'class': 'spinner-content'
},
messageContainer: {
'class': 'spinner-msg'
},
img: {
'class': 'spinner-img'
},
fxOptions: {
link: 'chain'
}
},
initialize: function(target, options){
this.target = document.id(target) || document.id(document.body);
this.target.store('spinner', this);
this.setOptions(options);
this.render();
this.inject();
// Add this to events for when noFx is true; parent methods handle hide/show.
var deactivate = function(){ this.active = false; }.bind(this);
this.addEvents({
hide: deactivate,
show: deactivate
});
},
render: function(){
this.parent();
this.element.set('id', this.options.id || 'spinner-' + String.uniqueID());
this.content = document.id(this.options.content) || new Element('div', this.options.content);
this.content.inject(this.element);
if (this.options.message){
this.msg = document.id(this.options.message) || new Element('p', this.options.messageContainer).appendText(this.options.message);
this.msg.inject(this.content);
}
if (this.options.img){
this.img = document.id(this.options.img) || new Element('div', this.options.img);
this.img.inject(this.content);
}
this.element.set('tween', this.options.fxOptions);
},
show: function(noFx){
if (this.active) return this.chain(this.show.bind(this));
if (!this.hidden){
this.callChain.delay(20, this);
return this;
}
this.active = true;
return this.parent(noFx);
},
showMask: function(noFx){
var pos = function(){
this.content.position(Object.merge({
relativeTo: this.element
}, this.options.containerPosition));
}.bind(this);
if (noFx){
this.parent();
pos();
} else {
if (!this.options.style.opacity) this.options.style.opacity = this.element.getStyle('opacity').toFloat();
this.element.setStyles({
display: 'block',
opacity: 0
}).tween('opacity', this.options.style.opacity);
pos();
this.hidden = false;
this.fireEvent('show');
this.callChain();
}
},
hide: function(noFx){
if (this.active) return this.chain(this.hide.bind(this));
if (this.hidden){
this.callChain.delay(20, this);
return this;
}
this.active = true;
return this.parent(noFx);
},
hideMask: function(noFx){
if (noFx) return this.parent();
this.element.tween('opacity', 0).get('tween').chain(function(){
this.element.setStyle('display', 'none');
this.hidden = true;
this.fireEvent('hide');
this.callChain();
}.bind(this));
},
destroy: function(){
this.content.destroy();
this.parent();
this.target.eliminate('spinner');
}
});
Request = Class.refactor(Request, {
options: {
useSpinner: false,
spinnerOptions: {},
spinnerTarget: false
},
initialize: function(options){
this._send = this.send;
this.send = function(options){
var spinner = this.getSpinner();
if (spinner) spinner.chain(this._send.pass(options, this)).show();
else this._send(options);
return this;
};
this.previous(options);
},
getSpinner: function(){
if (!this.spinner){
var update = document.id(this.options.spinnerTarget) || document.id(this.options.update);
if (this.options.useSpinner && update){
update.set('spinner', this.options.spinnerOptions);
var spinner = this.spinner = update.get('spinner');
['complete', 'exception', 'cancel'].each(function(event){
this.addEvent(event, spinner.hide.bind(spinner));
}, this);
}
}
return this.spinner;
}
});
Element.Properties.spinner = {
set: function(options){
var spinner = this.retrieve('spinner');
if (spinner) spinner.destroy();
return this.eliminate('spinner').store('spinner:options', options);
},
get: function(){
var spinner = this.retrieve('spinner');
if (!spinner){
spinner = new Spinner(this, this.retrieve('spinner:options'));
this.store('spinner', spinner);
}
return spinner;
}
};
Element.implement({
spin: function(options){
if (options) this.set('spinner', options);
this.get('spinner').show();
return this;
},
unspin: function(){
this.get('spinner').hide();
return this;
}
});
/*
---
name: Events.Pseudos
description: Adds the functionallity to add pseudo events
license: MIT-style license
authors:
- Arian Stolwijk
requires: [Core/Class.Extras, Core/Slick.Parser, More/MooTools.More]
provides: [Events.Pseudos]
...
*/
Events.Pseudos = function(pseudos, addEvent, removeEvent){
var storeKey = 'monitorEvents:';
var storageOf = function(object){
return {
store: object.store ? function(key, value){
object.store(storeKey + key, value);
} : function(key, value){
(object.$monitorEvents || (object.$monitorEvents = {}))[key] = value;
},
retrieve: object.retrieve ? function(key, dflt){
return object.retrieve(storeKey + key, dflt);
} : function(key, dflt){
if (!object.$monitorEvents) return dflt;
return object.$monitorEvents[key] || dflt;
}
};
};
var splitType = function(type){
if (type.indexOf(':') == -1) return null;
var parsed = Slick.parse(type).expressions[0][0],
parsedPseudos = parsed.pseudos;
return (pseudos && pseudos[parsedPseudos[0].key]) ? {
event: parsed.tag,
value: parsedPseudos[0].value,
pseudo: parsedPseudos[0].key,
original: type
} : null;
};
return {
addEvent: function(type, fn, internal){
var split = splitType(type);
if (!split) return addEvent.call(this, type, fn, internal);
var storage = storageOf(this),
events = storage.retrieve(type, []),
pseudoArgs = Array.from(pseudos[split.pseudo]),
proxy = pseudoArgs[1];
var self = this;
var monitor = function(){
pseudoArgs[0].call(self, split, fn, arguments, proxy);
};
events.include({event: fn, monitor: monitor});
storage.store(type, events);
var eventType = split.event;
if (proxy && proxy[eventType]) eventType = proxy[eventType].base;
addEvent.call(this, type, fn, internal);
return addEvent.call(this, eventType, monitor, internal);
},
removeEvent: function(type, fn){
var split = splitType(type);
if (!split) return removeEvent.call(this, type, fn);
var storage = storageOf(this),
events = storage.retrieve(type),
pseudoArgs = Array.from(pseudos[split.pseudo]),
proxy = pseudoArgs[1];
if (!events) return this;
var eventType = split.event;
if (proxy && proxy[eventType]) eventType = proxy[eventType].base;
removeEvent.call(this, type, fn);
events.each(function(monitor, i){
if (!fn || monitor.event == fn) removeEvent.call(this, eventType, monitor.monitor);
delete events[i];
}, this);
storage.store(type, events);
return this;
}
};
};
(function(){
var pseudos = {
once: function(split, fn, args){
fn.apply(this, args);
this.removeEvent(split.original, fn);
}
};
Events.definePseudo = function(key, fn){
pseudos[key] = fn;
};
var proto = Events.prototype;
Events.implement(Events.Pseudos(pseudos, proto.addEvent, proto.removeEvent));
})();
/*
---
name: Element.Event.Pseudos
description: Adds the functionality to add pseudo events for Elements
license: MIT-style license
authors:
- Arian Stolwijk
requires: [Core/Element.Event, Events.Pseudos]
provides: [Element.Event.Pseudos]
...
*/
(function(){
var pseudos = {
once: function(split, fn, args){
fn.apply(this, args);
this.removeEvent(split.original, fn);
}
};
Event.definePseudo = function(key, fn, proxy){
pseudos[key] = [fn, proxy];
};
var proto = Element.prototype;
[Element, Window, Document].invoke('implement', Events.Pseudos(pseudos, proto.addEvent, proto.removeEvent));
})();
/*
---
script: Element.Delegation.js
name: Element.Delegation
description: Extends the Element native object to include the delegate method for more efficient event management.
credits:
- "Event checking based on the work of Daniel Steigerwald. License: MIT-style license. Copyright: Copyright (c) 2008 Daniel Steigerwald, daniel.steigerwald.cz"
license: MIT-style license
authors:
- Aaron Newton
- Daniel Steigerwald
requires: [/MooTools.More, Element.Event.Pseudos]
provides: [Element.Delegation]
...
*/
Event.definePseudo('relay', function(split, fn, args, proxy){
var event = args[0];
var check = proxy ? proxy.condition : null;
for (var target = event.target; target && target != this; target = target.parentNode){
var finalTarget = document.id(target);
if (Slick.match(target, split.value) && (!check || check.call(finalTarget, event))){
if (finalTarget) fn.call(finalTarget, event, finalTarget);
return;
}
}
}, {
mouseenter: {
base: 'mouseover',
condition: Element.Events.mouseenter.condition
},
mouseleave: {
base: 'mouseout',
condition: Element.Events.mouseleave.condition
}
});
/*
---
script: Form.Request.js
name: Form.Request
description: Handles the basic functionality of submitting a form and updating a dom element with the result.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Request.HTML
- /Class.Binds
- /Class.Occlude
- /Spinner
- /String.QueryString
- /Element.Delegation
provides: [Form.Request]
...
*/
if (!window.Form) window.Form = {};
(function(){
Form.Request = new Class({
Binds: ['onSubmit', 'onFormValidate'],
Implements: [Options, Events, Class.Occlude],
options: {
//onFailure: function(){},
//onSuccess: #function(){}, //aliased to onComplete,
//onSend: function(){}
requestOptions: {
evalScripts: true,
useSpinner: true,
emulation: false,
link: 'ignore'
},
sendButtonClicked: true,
extraData: {},
resetForm: true
},
property: 'form.request',
initialize: function(form, update, options){
this.element = document.id(form);
if (this.occlude()) return this.occluded;
this.update = document.id(update);
this.setOptions(options);
this.makeRequest();
if (this.options.resetForm){
this.request.addEvent('success', function(){
Function.attempt(function(){ this.element.reset(); }.bind(this));
if (window.OverText) OverText.update();
}.bind(this));
}
this.attach();
},
toElement: function(){
return this.element;
},
makeRequest: function(){
this.request = new Request.HTML(Object.merge({
update: this.update,
emulation: false,
spinnerTarget: this.element,
method: this.element.get('method') || 'post'
}, this.options.requestOptions)).addEvents({
success: function(tree, elements, html, javascript){
['complete', 'success'].each(function(evt){
this.fireEvent(evt, [this.update, tree, elements, html, javascript]);
}, this);
}.bind(this),
failure: function(){
this.fireEvent('complete', arguments).fireEvent('failure', arguments);
}.bind(this),
exception: function(){
this.fireEvent('failure', arguments);
}.bind(this)
});
},
attach: function(attach){
attach = attach != null ? attach : true;
method = attach ? 'addEvent' : 'removeEvent';
this.element[method]('click:relay(button, input[type=submit])', this.saveClickedButton.bind(this));
var fv = this.element.retrieve('validator');
if (fv) fv[method]('onFormValidate', this.onFormValidate);
else this.element[method]('submit', this.onSubmit);
},
detach: function(){
this.attach(false);
return this;
},
//public method
enable: function(){
this.attach();
return this;
},
//public method
disable: function(){
this.detach();
return this;
},
onFormValidate: function(valid, form, e){
//if there's no event, then this wasn't a submit event
if (!e) return;
var fv = this.element.retrieve('validator');
if (valid || (fv && !fv.options.stopOnFailure)){
if (e && e.stop) e.stop();
this.send();
}
},
onSubmit: function(e){
var fv = this.element.retrieve('validator');
if (fv){
//form validator was created after Form.Request
this.element.removeEvent('submit', this.onSubmit);
fv.addEvent('onFormValidate', this.onFormValidate);
this.element.validate();
return;
}
if (e) e.stop();
this.send();
},
saveClickedButton: function(event, target){
if (!this.options.sendButtonClicked) return;
if (!target.get('name')) return;
this.options.extraData[target.get('name')] = target.get('value') || true;
this.clickedCleaner = function(){
delete this.options.extraData[target.get('name')];
this.clickedCleaner = function(){};
}.bind(this);
},
clickedCleaner: function(){},
send: function(){
var str = this.element.toQueryString().trim();
var data = Object.toQueryString(this.options.extraData);
if (str) str += "&" + data;
else str = data;
this.fireEvent('send', [this.element, str.parseQueryString()]);
this.request.send({data: str, url: this.element.get("action")});
this.clickedCleaner();
return this;
}
});
Element.Properties.formRequest = {
set: function(){
var opt = Array.link(arguments, {options: Type.isObject, update: Type.isElement, updateId: Type.isString});
var update = opt.update || opt.updateId;
var updater = this.retrieve('form.request');
if (update){
if (updater) updater.update = document.id(update);
this.store('form.request:update', update);
}
if (opt.options){
if (updater) updater.setOptions(opt.options);
this.store('form.request:options', opt.options);
}
return this;
},
get: function(){
var opt = Array.link(arguments, {options: Type.isObject, update: Type.isElement, updateId: Type.isString});
var update = opt.update || opt.updateId;
if (opt.options || update || !this.retrieve('form.request')){
if (opt.options || !this.retrieve('form.request:options')) this.set('form.request', opt.options);
if (update) this.set('form.request', update);
this.store('form.request', new Form.Request(this, this.retrieve('form.request:update'), this.retrieve('form.request:options')));
}
return this.retrieve('form.request');
}
};
Element.implement({
formUpdate: function(update, options){
this.get('formRequest', update, options).send();
return this;
}
});
})();
/*
---
script: Element.Shortcuts.js
name: Element.Shortcuts
description: Extends the Element native object to include some shortcut methods.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Element.Style
- /MooTools.More
provides: [Element.Shortcuts]
...
*/
Element.implement({
isDisplayed: function(){
return this.getStyle('display') != 'none';
},
isVisible: function(){
var w = this.offsetWidth,
h = this.offsetHeight;
return (w == 0 && h == 0) ? false : (w > 0 && h > 0) ? true : this.style.display != 'none';
},
toggle: function(){
return this[this.isDisplayed() ? 'hide' : 'show']();
},
hide: function(){
var d;
try {
//IE fails here if the element is not in the dom
d = this.getStyle('display');
} catch(e){}
if (d == 'none') return this;
return this.store('element:_originalDisplay', d || '').setStyle('display', 'none');
},
show: function(display){
if (!display && this.isDisplayed()) return this;
display = display || this.retrieve('element:_originalDisplay') || 'block';
return this.setStyle('display', (display == 'none') ? 'block' : display);
},
swapClass: function(remove, add){
return this.removeClass(remove).addClass(add);
}
});
Document.implement({
clearSelection: function(){
if (document.selection && document.selection.empty){
document.selection.empty();
} else if (window.getSelection){
var selection = window.getSelection();
if (selection && selection.removeAllRanges) selection.removeAllRanges();
}
}
});
/*
---
script: Fx.Reveal.js
name: Fx.Reveal
description: Defines Fx.Reveal, a class that shows and hides elements with a transition.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Fx.Morph
- /Element.Shortcuts
- /Element.Measure
provides: [Fx.Reveal]
...
*/
Fx.Reveal = new Class({
Extends: Fx.Morph,
options: {/*
onShow: function(thisElement){},
onHide: function(thisElement){},
onComplete: function(thisElement){},
heightOverride: null,
widthOverride: null,*/
link: 'cancel',
styles: ['padding', 'border', 'margin'],
transitionOpacity: !Browser.ie6,
mode: 'vertical',
display: function(){
return this.element.get('tag') != 'tr' ? 'block' : 'table-row';
},
opacity: 1,
hideInputs: Browser.ie ? 'select, input, textarea, object, embed' : null
},
dissolve: function(){
if (!this.hiding && !this.showing){
if (this.element.getStyle('display') != 'none'){
this.hiding = true;
this.showing = false;
this.hidden = true;
this.cssText = this.element.style.cssText;
var startStyles = this.element.getComputedSize({
styles: this.options.styles,
mode: this.options.mode
});
if (this.options.transitionOpacity) startStyles.opacity = this.options.opacity;
var zero = {};
Object.each(startStyles, function(style, name){
zero[name] = [style, 0];
});
this.element.setStyles({
display: Function.from(this.options.display).call(this),
overflow: 'hidden'
});
var hideThese = this.options.hideInputs ? this.element.getElements(this.options.hideInputs) : null;
if (hideThese) hideThese.setStyle('visibility', 'hidden');
this.$chain.unshift(function(){
if (this.hidden){
this.hiding = false;
this.element.style.cssText = this.cssText;
this.element.setStyle('display', 'none');
if (hideThese) hideThese.setStyle('visibility', 'visible');
}
this.fireEvent('hide', this.element);
this.callChain();
}.bind(this));
this.start(zero);
} else {
this.callChain.delay(10, this);
this.fireEvent('complete', this.element);
this.fireEvent('hide', this.element);
}
} else if (this.options.link == 'chain'){
this.chain(this.dissolve.bind(this));
} else if (this.options.link == 'cancel' && !this.hiding){
this.cancel();
this.dissolve();
}
return this;
},
reveal: function(){
if (!this.showing && !this.hiding){
if (this.element.getStyle('display') == 'none'){
this.hiding = false;
this.showing = true;
this.hidden = false;
this.cssText = this.element.style.cssText;
var startStyles;
this.element.measure(function(){
startStyles = this.element.getComputedSize({
styles: this.options.styles,
mode: this.options.mode
});
}.bind(this));
if (this.options.heightOverride != null) startStyles.height = this.options.heightOverride.toInt();
if (this.options.widthOverride != null) startStyles.width = this.options.widthOverride.toInt();
if (this.options.transitionOpacity){
this.element.setStyle('opacity', 0);
startStyles.opacity = this.options.opacity;
}
var zero = {
height: 0,
display: Function.from(this.options.display).call(this)
};
Object.each(startStyles, function(style, name){
zero[name] = 0;
});
zero.overflow = 'hidden';
this.element.setStyles(zero);
var hideThese = this.options.hideInputs ? this.element.getElements(this.options.hideInputs) : null;
if (hideThese) hideThese.setStyle('visibility', 'hidden');
this.$chain.unshift(function(){
this.element.style.cssText = this.cssText;
this.element.setStyle('display', Function.from(this.options.display).call(this));
if (!this.hidden) this.showing = false;
if (hideThese) hideThese.setStyle('visibility', 'visible');
this.callChain();
this.fireEvent('show', this.element);
}.bind(this));
this.start(startStyles);
} else {
this.callChain();
this.fireEvent('complete', this.element);
this.fireEvent('show', this.element);
}
} else if (this.options.link == 'chain'){
this.chain(this.reveal.bind(this));
} else if (this.options.link == 'cancel' && !this.showing){
this.cancel();
this.reveal();
}
return this;
},
toggle: function(){
if (this.element.getStyle('display') == 'none'){
this.reveal();
} else {
this.dissolve();
}
return this;
},
cancel: function(){
this.parent.apply(this, arguments);
this.element.style.cssText = this.cssText;
this.hiding = false;
this.showing = false;
return this;
}
});
Element.Properties.reveal = {
set: function(options){
this.get('reveal').cancel().setOptions(options);
return this;
},
get: function(){
var reveal = this.retrieve('reveal');
if (!reveal){
reveal = new Fx.Reveal(this);
this.store('reveal', reveal);
}
return reveal;
}
};
Element.Properties.dissolve = Element.Properties.reveal;
Element.implement({
reveal: function(options){
this.get('reveal').setOptions(options).reveal();
return this;
},
dissolve: function(options){
this.get('reveal').setOptions(options).dissolve();
return this;
},
nix: function(options){
var params = Array.link(arguments, {destroy: Type.isBoolean, options: Type.isObject});
this.get('reveal').setOptions(options).dissolve().chain(function(){
this[params.destroy ? 'destroy' : 'dispose']();
}.bind(this));
return this;
},
wink: function(){
var params = Array.link(arguments, {duration: Type.isNumber, options: Type.isObject});
var reveal = this.get('reveal').setOptions(params.options);
reveal.reveal().chain(function(){
(function(){
reveal.dissolve();
}).delay(params.duration || 2000);
});
}
});
/*
---
script: Elements.From.js
name: Elements.From
description: Returns a collection of elements from a string of html.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/String
- Core/Element
- /MooTools.More
provides: [Elements.from, Elements.From]
...
*/
Elements.from = function(text, excludeScripts){
if (excludeScripts || excludeScripts == null) text = text.stripScripts();
var container, match = text.match(/^\s*<(t[dhr]|tbody|tfoot|thead)/i);
if (match){
container = new Element('table');
var tag = match[1].toLowerCase();
if (['td', 'th', 'tr'].contains(tag)){
container = new Element('tbody').inject(container);
if (tag != 'tr') container = new Element('tr').inject(container);
}
}
return (container || new Element('div')).set('html', text).getChildren();
};
/*
---
script: Form.Request.Append.js
name: Form.Request.Append
description: Handles the basic functionality of submitting a form and updating a dom element with the result. The result is appended to the DOM element instead of replacing its contents.
license: MIT-style license
authors:
- Aaron Newton
requires:
- /Form.Request
- /Fx.Reveal
- /Elements.from
provides: [Form.Request.Append]
...
*/
Form.Request.Append = new Class({
Extends: Form.Request,
options: {
//onBeforeEffect: function(){},
useReveal: true,
revealOptions: {},
inject: 'bottom'
},
makeRequest: function(){
this.request = new Request.HTML(Object.merge({
url: this.element.get('action'),
method: this.element.get('method') || 'post',
spinnerTarget: this.element
}, this.options.requestOptions, {
evalScripts: false
})
).addEvents({
success: function(tree, elements, html, javascript){
var container;
var kids = Elements.from(html);
if (kids.length == 1){
container = kids[0];
} else {
container = new Element('div', {
styles: {
display: 'none'
}
}).adopt(kids);
}
container.inject(this.update, this.options.inject);
if (this.options.requestOptions.evalScripts) Browser.exec(javascript);
this.fireEvent('beforeEffect', container);
var finish = function(){
this.fireEvent('success', [container, this.update, tree, elements, html, javascript]);
}.bind(this);
if (this.options.useReveal){
container.set('reveal', this.options.revealOptions).get('reveal').chain(finish);
container.reveal();
} else {
finish();
}
}.bind(this),
failure: function(xhr){
this.fireEvent('failure', xhr);
}.bind(this)
});
}
});
/*
---
script: String.Extras.js
name: String.Extras
description: Extends the String native object to include methods useful in managing various kinds of strings (query strings, urls, html, etc).
license: MIT-style license
authors:
- Aaron Newton
- Guillermo Rauch
- Christopher Pitt
requires:
- Core/String
- Core/Array
provides: [String.Extras]
...
*/
(function(){
var special = {
'a': /[àáâãäåăą]/g,
'A': /[ÀÁÂÃÄÅĂĄ]/g,
'c': /[ćčç]/g,
'C': /[ĆČÇ]/g,
'd': /[ďđ]/g,
'D': /[ĎÐ]/g,
'e': /[èéêëěę]/g,
'E': /[ÈÉÊËĚĘ]/g,
'g': /[ğ]/g,
'G': /[Ğ]/g,
'i': /[ìíîï]/g,
'I': /[ÌÍÎÏ]/g,
'l': /[ĺľł]/g,
'L': /[ĹĽŁ]/g,
'n': /[ñňń]/g,
'N': /[ÑŇŃ]/g,
'o': /[òóôõöøő]/g,
'O': /[ÒÓÔÕÖØ]/g,
'r': /[řŕ]/g,
'R': /[ŘŔ]/g,
's': /[ššş]/g,
'S': /[ŠŞŚ]/g,
't': /[ťţ]/g,
'T': /[ŤŢ]/g,
'ue': /[ü]/g,
'UE': /[Ü]/g,
'u': /[ùúûůµ]/g,
'U': /[ÙÚÛŮ]/g,
'y': /[ÿý]/g,
'Y': /[ŸÝ]/g,
'z': /[žźż]/g,
'Z': /[ŽŹŻ]/g,
'th': /[þ]/g,
'TH': /[Þ]/g,
'dh': /[ð]/g,
'DH': /[Ð]/g,
'ss': /[ß]/g,
'oe': /[œ]/g,
'OE': /[Œ]/g,
'ae': /[æ]/g,
'AE': /[Æ]/g
},
tidy = {
' ': /[\xa0\u2002\u2003\u2009]/g,
'*': /[\xb7]/g,
'\'': /[\u2018\u2019]/g,
'"': /[\u201c\u201d]/g,
'...': /[\u2026]/g,
'-': /[\u2013]/g,
// '--': /[\u2014]/g,
'»': /[\uFFFD]/g
};
var walk = function(string, replacements){
var result = string;
for (key in replacements) result = result.replace(replacements[key], key);
return result;
};
var getRegexForTag = function(tag, contents){
tag = tag || '';
var regstr = contents ? "<" + tag + "(?!\\w)[^>]*>([\\s\\S]*?)<\/" + tag + "(?!\\w)>" : "<\/?" + tag + "([^>]+)?>";
reg = new RegExp(regstr, "gi");
return reg;
};
String.implement({
standardize: function(){
return walk(this, special);
},
repeat: function(times){
return new Array(times + 1).join(this);
},
pad: function(length, str, direction){
if (this.length >= length) return this;
var pad = (str == null ? ' ' : '' + str)
.repeat(length - this.length)
.substr(0, length - this.length);
if (!direction || direction == 'right') return this + pad;
if (direction == 'left') return pad + this;
return pad.substr(0, (pad.length / 2).floor()) + this + pad.substr(0, (pad.length / 2).ceil());
},
getTags: function(tag, contents){
return this.match(getRegexForTag(tag, contents)) || [];
},
stripTags: function(tag, contents){
return this.replace(getRegexForTag(tag, contents), '');
},
tidy: function(){
return walk(this, tidy);
}
});
})();
/*
---
script: Element.Forms.js
name: Element.Forms
description: Extends the Element native object to include methods useful in managing inputs.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Element
- /String.Extras
- /MooTools.More
provides: [Element.Forms]
...
*/
Element.implement({
tidy: function(){
this.set('value', this.get('value').tidy());
},
getTextInRange: function(start, end){
return this.get('value').substring(start, end);
},
getSelectedText: function(){
if (this.setSelectionRange) return this.getTextInRange(this.getSelectionStart(), this.getSelectionEnd());
return document.selection.createRange().text;
},
getSelectedRange: function(){
if (this.selectionStart != null){
return {
start: this.selectionStart,
end: this.selectionEnd
};
}
var pos = {
start: 0,
end: 0
};
var range = this.getDocument().selection.createRange();
if (!range || range.parentElement() != this) return pos;
var duplicate = range.duplicate();
if (this.type == 'text'){
pos.start = 0 - duplicate.moveStart('character', -100000);
pos.end = pos.start + range.text.length;
} else {
var value = this.get('value');
var offset = value.length;
duplicate.moveToElementText(this);
duplicate.setEndPoint('StartToEnd', range);
if (duplicate.text.length) offset -= value.match(/[\n\r]*$/)[0].length;
pos.end = offset - duplicate.text.length;
duplicate.setEndPoint('StartToStart', range);
pos.start = offset - duplicate.text.length;
}
return pos;
},
getSelectionStart: function(){
return this.getSelectedRange().start;
},
getSelectionEnd: function(){
return this.getSelectedRange().end;
},
setCaretPosition: function(pos){
if (pos == 'end') pos = this.get('value').length;
this.selectRange(pos, pos);
return this;
},
getCaretPosition: function(){
return this.getSelectedRange().start;
},
selectRange: function(start, end){
if (this.setSelectionRange){
this.focus();
this.setSelectionRange(start, end);
} else {
var value = this.get('value');
var diff = value.substr(start, end - start).replace(/\r/g, '').length;
start = value.substr(0, start).replace(/\r/g, '').length;
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', start + diff);
range.moveStart('character', start);
range.select();
}
return this;
},
insertAtCursor: function(value, select){
var pos = this.getSelectedRange();
var text = this.get('value');
this.set('value', text.substring(0, pos.start) + value + text.substring(pos.end, text.length));
if (select !== false) this.selectRange(pos.start, pos.start + value.length);
else this.setCaretPosition(pos.start + value.length);
return this;
},
insertAroundCursor: function(options, select){
options = Object.append({
before: '',
defaultMiddle: '',
after: ''
}, options);
var value = this.getSelectedText() || options.defaultMiddle;
var pos = this.getSelectedRange();
var text = this.get('value');
if (pos.start == pos.end){
this.set('value', text.substring(0, pos.start) + options.before + value + options.after + text.substring(pos.end, text.length));
this.selectRange(pos.start + options.before.length, pos.end + options.before.length + value.length);
} else {
var current = text.substring(pos.start, pos.end);
this.set('value', text.substring(0, pos.start) + options.before + current + options.after + text.substring(pos.end, text.length));
var selStart = pos.start + options.before.length;
if (select !== false) this.selectRange(selStart, selStart + current.length);
else this.setCaretPosition(selStart + text.length);
}
return this;
}
});
/*
---
name: Locale.en-US.Form.Validator
description: Form Validator messages for English.
license: MIT-style license
authors:
- Aaron Newton
requires:
- /Locale
provides: [Locale.en-US.Form.Validator]
...
*/
Locale.define('en-US', 'FormValidator', {
required: 'This field is required.',
minLength: 'Please enter at least {minLength} characters (you entered {length} characters).',
maxLength: 'Please enter no more than {maxLength} characters (you entered {length} characters).',
integer: 'Please enter an integer in this field. Numbers with decimals (e.g. 1.25) are not permitted.',
numeric: 'Please enter only numeric values in this field (i.e. "1" or "1.1" or "-1" or "-1.1").',
digits: 'Please use numbers and punctuation only in this field (for example, a phone number with dashes or dots is permitted).',
alpha: 'Please use only letters (a-z) within this field. No spaces or other characters are allowed.',
alphanum: 'Please use only letters (a-z) or numbers (0-9) in this field. No spaces or other characters are allowed.',
dateSuchAs: 'Please enter a valid date such as {date}',
dateInFormatMDY: 'Please enter a valid date such as MM/DD/YYYY (i.e. "12/31/1999")',
email: 'Please enter a valid email address. For example "fred@domain.com".',
url: 'Please enter a valid URL such as http://www.google.com.',
currencyDollar: 'Please enter a valid $ amount. For example $100.00 .',
oneRequired: 'Please enter something for at least one of these inputs.',
errorPrefix: 'Error: ',
warningPrefix: 'Warning: ',
// Form.Validator.Extras
noSpace: 'There can be no spaces in this input.',
reqChkByNode: 'No items are selected.',
requiredChk: 'This field is required.',
reqChkByName: 'Please select a {label}.',
match: 'This field needs to match the {matchName} field',
startDate: 'the start date',
endDate: 'the end date',
currendDate: 'the current date',
afterDate: 'The date should be the same or after {label}.',
beforeDate: 'The date should be the same or before {label}.',
startMonth: 'Please select a start month',
sameMonth: 'These two dates must be in the same month - you must change one or the other.',
creditcard: 'The credit card number entered is invalid. Please check the number and try again. {length} digits entered.'
});
/*
---
script: Form.Validator.js
name: Form.Validator
description: A css-class based form validation system.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Options
- Core/Events
- Core/Slick.Finder
- Core/Element.Event
- Core/Element.Style
- Core/JSON
- /Locale
- /Class.Binds
- /Date
- /Element.Forms
- /Locale.en-US.Form.Validator
- /Element.Shortcuts
provides: [Form.Validator, InputValidator, FormValidator.BaseValidators]
...
*/
if (!window.Form) window.Form = {};
var InputValidator = new Class({
Implements: [Options],
options: {
errorMsg: 'Validation failed.',
test: function(field){return true;}
},
initialize: function(className, options){
this.setOptions(options);
this.className = className;
},
test: function(field, props){
if (document.id(field)) return this.options.test(document.id(field), props || this.getProps(field));
else return false;
},
getError: function(field, props){
var err = this.options.errorMsg;
if (typeOf(err) == 'function') err = err(document.id(field), props || this.getProps(field));
return err;
},
getProps: function(field){
if (!document.id(field)) return {};
return field.get('validatorProps');
}
});
Element.Properties.validatorProps = {
set: function(props){
return this.eliminate('$moo:validatorProps').store('$moo:validatorProps', props);
},
get: function(props){
if (props) this.set(props);
if (this.retrieve('$moo:validatorProps')) return this.retrieve('$moo:validatorProps');
if (this.getProperty('$moo:validatorProps')){
try {
this.store('$moo:validatorProps', JSON.decode(this.getProperty('$moo:validatorProps')));
}catch(e){
return {};
}
} else {
var vals = this.get('class').split(' ').filter(function(cls){
return cls.test(':');
});
if (!vals.length){
this.store('$moo:validatorProps', {});
} else {
props = {};
vals.each(function(cls){
var split = cls.split(':');
if (split[1]){
try {
props[split[0]] = JSON.decode(split[1]);
} catch(e){}
}
});
this.store('$moo:validatorProps', props);
}
}
return this.retrieve('$moo:validatorProps');
}
};
Form.Validator = new Class({
Implements:[Options, Events],
Binds: ['onSubmit'],
options: {/*
onFormValidate: function(isValid, form, event){},
onElementValidate: function(isValid, field, className, warn){},
onElementPass: function(field){},
onElementFail: function(field, validatorsFailed){}, */
fieldSelectors: 'input, select, textarea',
ignoreHidden: true,
ignoreDisabled: true,
useTitles: false,
evaluateOnSubmit: true,
evaluateFieldsOnBlur: true,
evaluateFieldsOnChange: true,
serial: true,
stopOnFailure: true,
warningPrefix: function(){
return Form.Validator.getMsg('warningPrefix') || 'Warning: ';
},
errorPrefix: function(){
return Form.Validator.getMsg('errorPrefix') || 'Error: ';
}
},
initialize: function(form, options){
this.setOptions(options);
this.element = document.id(form);
this.element.store('validator', this);
this.warningPrefix = Function.from(this.options.warningPrefix)();
this.errorPrefix = Function.from(this.options.errorPrefix)();
if (this.options.evaluateOnSubmit) this.element.addEvent('submit', this.onSubmit);
if (this.options.evaluateFieldsOnBlur || this.options.evaluateFieldsOnChange) this.watchFields(this.getFields());
},
toElement: function(){
return this.element;
},
getFields: function(){
return (this.fields = this.element.getElements(this.options.fieldSelectors));
},
watchFields: function(fields){
fields.each(function(el){
if (this.options.evaluateFieldsOnBlur)
el.addEvent('blur', this.validationMonitor.pass([el, false], this));
if (this.options.evaluateFieldsOnChange)
el.addEvent('change', this.validationMonitor.pass([el, true], this));
}, this);
},
validationMonitor: function(){
clearTimeout(this.timer);
this.timer = this.validateField.delay(50, this, arguments);
},
onSubmit: function(event){
if (!this.validate(event) && event) event.preventDefault();
else this.reset();
},
reset: function(){
this.getFields().each(this.resetField, this);
return this;
},
validate: function(event){
var result = this.getFields().map(function(field){
return this.validateField(field, true);
}, this).every(function(v){ return v;});
this.fireEvent('formValidate', [result, this.element, event]);
if (this.options.stopOnFailure && !result && event) event.preventDefault();
return result;
},
validateField: function(field, force){
if (this.paused) return true;
field = document.id(field);
var passed = !field.hasClass('validation-failed');
var failed, warned;
if (this.options.serial && !force){
failed = this.element.getElement('.validation-failed');
warned = this.element.getElement('.warning');
}
if (field && (!failed || force || field.hasClass('validation-failed') || (failed && !this.options.serial))){
var validators = field.className.split(' ').some(function(cn){
return this.getValidator(cn);
}, this);
var validatorsFailed = [];
field.className.split(' ').each(function(className){
if (className && !this.test(className, field)) validatorsFailed.include(className);
}, this);
passed = validatorsFailed.length === 0;
if (validators && !field.hasClass('warnOnly')){
if (passed){
field.addClass('validation-passed').removeClass('validation-failed');
this.fireEvent('elementPass', field);
} else {
field.addClass('validation-failed').removeClass('validation-passed');
this.fireEvent('elementFail', [field, validatorsFailed]);
}
}
if (!warned){
var warnings = field.className.split(' ').some(function(cn){
if (cn.test('^warn-') || field.hasClass('warnOnly'))
return this.getValidator(cn.replace(/^warn-/,''));
else return null;
}, this);
field.removeClass('warning');
var warnResult = field.className.split(' ').map(function(cn){
if (cn.test('^warn-') || field.hasClass('warnOnly'))
return this.test(cn.replace(/^warn-/,''), field, true);
else return null;
}, this);
}
}
return passed;
},
test: function(className, field, warn){
field = document.id(field);
if ((this.options.ignoreHidden && !field.isVisible()) || (this.options.ignoreDisabled && field.get('disabled'))) return true;
var validator = this.getValidator(className);
warn = warn != null ? warn : false;
if (field.hasClass('warnOnly')) warn = true;
var isValid = field.hasClass('ignoreValidation') || (validator ? validator.test(field) : true);
if (validator) this.fireEvent('elementValidate', [isValid, field, className, warn]);
if (warn) return true;
return isValid;
},
resetField: function(field){
field = document.id(field);
if (field){
field.className.split(' ').each(function(className){
if (className.test('^warn-')) className = className.replace(/^warn-/, '');
field.removeClass('validation-failed');
field.removeClass('warning');
field.removeClass('validation-passed');
}, this);
}
return this;
},
stop: function(){
this.paused = true;
return this;
},
start: function(){
this.paused = false;
return this;
},
ignoreField: function(field, warn){
field = document.id(field);
if (field){
this.enforceField(field);
if (warn) field.addClass('warnOnly');
else field.addClass('ignoreValidation');
}
return this;
},
enforceField: function(field){
field = document.id(field);
if (field) field.removeClass('warnOnly').removeClass('ignoreValidation');
return this;
}
});
Form.Validator.getMsg = function(key){
return Locale.get('FormValidator.' + key);
};
Form.Validator.adders = {
validators:{},
add : function(className, options){
this.validators[className] = new InputValidator(className, options);
//if this is a class (this method is used by instances of Form.Validator and the Form.Validator namespace)
//extend these validators into it
//this allows validators to be global and/or per instance
if (!this.initialize){
this.implement({
validators: this.validators
});
}
},
addAllThese : function(validators){
Array.from(validators).each(function(validator){
this.add(validator[0], validator[1]);
}, this);
},
getValidator: function(className){
return this.validators[className.split(':')[0]];
}
};
Object.append(Form.Validator, Form.Validator.adders);
Form.Validator.implement(Form.Validator.adders);
Form.Validator.add('IsEmpty', {
errorMsg: false,
test: function(element){
if (element.type == 'select-one' || element.type == 'select')
return !(element.selectedIndex >= 0 && element.options[element.selectedIndex].value != '');
else
return ((element.get('value') == null) || (element.get('value').length == 0));
}
});
Form.Validator.addAllThese([
['required', {
errorMsg: function(){
return Form.Validator.getMsg('required');
},
test: function(element){
return !Form.Validator.getValidator('IsEmpty').test(element);
}
}],
['minLength', {
errorMsg: function(element, props){
if (typeOf(props.minLength) != 'null')
return Form.Validator.getMsg('minLength').substitute({minLength:props.minLength,length:element.get('value').length });
else return '';
},
test: function(element, props){
if (typeOf(props.minLength) != 'null') return (element.get('value').length >= (props.minLength || 0));
else return true;
}
}],
['maxLength', {
errorMsg: function(element, props){
//props is {maxLength:10}
if (typeOf(props.maxLength) != 'null')
return Form.Validator.getMsg('maxLength').substitute({maxLength:props.maxLength,length:element.get('value').length });
else return '';
},
test: function(element, props){
//if the value is <= than the maxLength value, element passes test
return (element.get('value').length <= (props.maxLength || 10000));
}
}],
['validate-integer', {
errorMsg: Form.Validator.getMsg.pass('integer'),
test: function(element){
return Form.Validator.getValidator('IsEmpty').test(element) || (/^(-?[1-9]\d*|0)$/).test(element.get('value'));
}
}],
['validate-numeric', {
errorMsg: Form.Validator.getMsg.pass('numeric'),
test: function(element){
return Form.Validator.getValidator('IsEmpty').test(element) ||
(/^-?(?:0$0(?=\d*\.)|[1-9]|0)\d*(\.\d+)?$/).test(element.get('value'));
}
}],
['validate-digits', {
errorMsg: Form.Validator.getMsg.pass('digits'),
test: function(element){
return Form.Validator.getValidator('IsEmpty').test(element) || (/^[\d() .:\-\+#]+$/.test(element.get('value')));
}
}],
['validate-alpha', {
errorMsg: Form.Validator.getMsg.pass('alpha'),
test: function(element){
return Form.Validator.getValidator('IsEmpty').test(element) || (/^[a-zA-Z]+$/).test(element.get('value'));
}
}],
['validate-alphanum', {
errorMsg: Form.Validator.getMsg.pass('alphanum'),
test: function(element){
return Form.Validator.getValidator('IsEmpty').test(element) || !(/\W/).test(element.get('value'));
}
}],
['validate-date', {
errorMsg: function(element, props){
if (Date.parse){
var format = props.dateFormat || '%x';
return Form.Validator.getMsg('dateSuchAs').substitute({date: new Date().format(format)});
} else {
return Form.Validator.getMsg('dateInFormatMDY');
}
},
test: function(element, props){
if (Form.Validator.getValidator('IsEmpty').test(element)) return true;
var d;
if (Date.parse){
var format = props.dateFormat || '%x';
d = Date.parse(element.get('value'));
var formatted = d.format(format);
if (formatted != 'invalid date') element.set('value', formatted);
return !isNaN(d);
} else {
var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
if (!regex.test(element.get('value'))) return false;
d = new Date(element.get('value').replace(regex, '$1/$2/$3'));
return (parseInt(RegExp.$1, 10) == (1 + d.getMonth())) &&
(parseInt(RegExp.$2, 10) == d.getDate()) &&
(parseInt(RegExp.$3, 10) == d.getFullYear());
}
}
}],
['validate-email', {
errorMsg: Form.Validator.getMsg.pass('email'),
test: function(element){
return Form.Validator.getValidator('IsEmpty').test(element) || (/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i).test(element.get('value'));
}
}],
['validate-url', {
errorMsg: Form.Validator.getMsg.pass('url'),
test: function(element){
return Form.Validator.getValidator('IsEmpty').test(element) || (/^(https?|ftp|rmtp|mms):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i).test(element.get('value'));
}
}],
['validate-currency-dollar', {
errorMsg: Form.Validator.getMsg.pass('currencyDollar'),
test: function(element){
// [$]1[##][,###]+[.##]
// [$]1###+[.##]
// [$]0.##
// [$].##
return Form.Validator.getValidator('IsEmpty').test(element) || (/^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/).test(element.get('value'));
}
}],
['validate-one-required', {
errorMsg: Form.Validator.getMsg.pass('oneRequired'),
test: function(element, props){
var p = document.id(props['validate-one-required']) || element.getParent(props['validate-one-required']);
return p.getElements('input').some(function(el){
if (['checkbox', 'radio'].contains(el.get('type'))) return el.get('checked');
return el.get('value');
});
}
}]
]);
Element.Properties.validator = {
set: function(options){
var validator = this.retrieve('validator');
if (validator) validator.setOptions(options);
return this.store('$moo:validator:options', options);
},
get: function(options){
if (options || !this.retrieve('validator')){
if (options || !this.retrieve('$moo:validator:options')) this.set('validator', options);
this.store('validator', new Form.Validator(this, this.retrieve('$moo:validator:options')));
}
return this.retrieve('validator');
}
};
Element.implement({
validate: function(options){
if (options) this.set('validator', options);
return this.get('validator', options).validate();
}
});
/*
---
script: Form.Validator.Inline.js
name: Form.Validator.Inline
description: Extends Form.Validator to add inline messages.
license: MIT-style license
authors:
- Aaron Newton
requires:
- /Form.Validator
provides: [Form.Validator.Inline]
...
*/
Form.Validator.Inline = new Class({
Extends: Form.Validator,
options: {
showError: function(errorElement){
if (errorElement.reveal) errorElement.reveal();
else errorElement.setStyle('display', 'block');
},
hideError: function(errorElement){
if (errorElement.dissolve) errorElement.dissolve();
else errorElement.setStyle('display', 'none');
},
scrollToErrorsOnSubmit: true,
scrollToErrorsOnBlur: false,
scrollToErrorsOnChange: false,
scrollFxOptions: {
transition: 'quad:out',
offset: {
y: -20
}
}
},
initialize: function(form, options){
this.parent(form, options);
this.addEvent('onElementValidate', function(isValid, field, className, warn){
var validator = this.getValidator(className);
if (!isValid && validator.getError(field)){
if (warn) field.addClass('warning');
var advice = this.makeAdvice(className, field, validator.getError(field), warn);
this.insertAdvice(advice, field);
this.showAdvice(className, field);
} else {
this.hideAdvice(className, field);
}
});
},
makeAdvice: function(className, field, error, warn){
var errorMsg = (warn) ? this.warningPrefix : this.errorPrefix;
errorMsg += (this.options.useTitles) ? field.title || error:error;
var cssClass = (warn) ? 'warning-advice' : 'validation-advice';
var advice = this.getAdvice(className, field);
if (advice){
advice = advice.set('html', errorMsg);
} else {
advice = new Element('div', {
html: errorMsg,
styles: { display: 'none' },
id: 'advice-' + className.split(':')[0] + '-' + this.getFieldId(field)
}).addClass(cssClass);
}
field.store('$moo:advice-' + className, advice);
return advice;
},
getFieldId : function(field){
return field.id ? field.id : field.id = 'input_' + field.name;
},
showAdvice: function(className, field){
var advice = this.getAdvice(className, field);
if (advice && !field.retrieve('$moo:' + this.getPropName(className))
&& (advice.getStyle('display') == 'none'
|| advice.getStyle('visiblity') == 'hidden'
|| advice.getStyle('opacity') == 0)){
field.store('$moo:' + this.getPropName(className), true);
this.options.showError(advice);
this.fireEvent('showAdvice', [field, advice, className]);
}
},
hideAdvice: function(className, field){
var advice = this.getAdvice(className, field);
if (advice && field.retrieve('$moo:' + this.getPropName(className))){
field.store('$moo:' + this.getPropName(className), false);
this.options.hideError(advice);
this.fireEvent('hideAdvice', [field, advice, className]);
}
},
getPropName: function(className){
return 'advice' + className;
},
resetField: function(field){
field = document.id(field);
if (!field) return this;
this.parent(field);
field.className.split(' ').each(function(className){
this.hideAdvice(className, field);
}, this);
return this;
},
getAllAdviceMessages: function(field, force){
var advice = [];
if (field.hasClass('ignoreValidation') && !force) return advice;
var validators = field.className.split(' ').some(function(cn){
var warner = cn.test('^warn-') || field.hasClass('warnOnly');
if (warner) cn = cn.replace(/^warn-/, '');
var validator = this.getValidator(cn);
if (!validator) return;
advice.push({
message: validator.getError(field),
warnOnly: warner,
passed: validator.test(),
validator: validator
});
}, this);
return advice;
},
getAdvice: function(className, field){
return field.retrieve('$moo:advice-' + className);
},
insertAdvice: function(advice, field){
//Check for error position prop
var props = field.get('validatorProps');
//Build advice
if (!props.msgPos || !document.id(props.msgPos)){
if (field.type && field.type.toLowerCase() == 'radio') field.getParent().adopt(advice);
else advice.inject(document.id(field), 'after');
} else {
document.id(props.msgPos).grab(advice);
}
},
validateField: function(field, force, scroll){
var result = this.parent(field, force);
if (((this.options.scrollToErrorsOnSubmit && scroll == null) || scroll) && !result){
var failed = document.id(this).getElement('.validation-failed');
var par = document.id(this).getParent();
while (par != document.body && par.getScrollSize().y == par.getSize().y){
par = par.getParent();
}
var fx = par.retrieve('$moo:fvScroller');
if (!fx && window.Fx && Fx.Scroll){
fx = new Fx.Scroll(par, this.options.scrollFxOptions);
par.store('$moo:fvScroller', fx);
}
if (failed){
if (fx) fx.toElement(failed);
else par.scrollTo(par.getScroll().x, failed.getPosition(par).y - 20);
}
}
return result;
},
watchFields: function(fields){
fields.each(function(el){
if (this.options.evaluateFieldsOnBlur){
el.addEvent('blur', this.validationMonitor.pass([el, false, this.options.scrollToErrorsOnBlur], this));
}
if (this.options.evaluateFieldsOnChange){
el.addEvent('change', this.validationMonitor.pass([el, true, this.options.scrollToErrorsOnChange], this));
}
}, this);
}
});
/*
---
script: Form.Validator.Extras.js
name: Form.Validator.Extras
description: Additional validators for the Form.Validator class.
license: MIT-style license
authors:
- Aaron Newton
requires:
- /Form.Validator
provides: [Form.Validator.Extras]
...
*/
Form.Validator.addAllThese([
['validate-enforce-oncheck', {
test: function(element, props){
var fv = element.getParent('form').retrieve('validator');
if (!fv) return true;
(props.toEnforce || document.id(props.enforceChildrenOf).getElements('input, select, textarea')).map(function(item){
if (element.checked){
fv.enforceField(item);
} else {
fv.ignoreField(item);
fv.resetField(item);
}
});
return true;
}
}],
['validate-ignore-oncheck', {
test: function(element, props){
var fv = element.getParent('form').retrieve('validator');
if (!fv) return true;
(props.toIgnore || document.id(props.ignoreChildrenOf).getElements('input, select, textarea')).each(function(item){
if (element.checked){
fv.ignoreField(item);
fv.resetField(item);
} else {
fv.enforceField(item);
}
});
return true;
}
}],
['validate-nospace', {
errorMsg: function(){
return Form.Validator.getMsg('noSpace');
},
test: function(element, props){
return !element.get('value').test(/\s/);
}
}],
['validate-toggle-oncheck', {
test: function(element, props){
var fv = element.getParent('form').retrieve('validator');
if (!fv) return true;
var eleArr = props.toToggle || document.id(props.toToggleChildrenOf).getElements('input, select, textarea');
if (!element.checked){
eleArr.each(function(item){
fv.ignoreField(item);
fv.resetField(item);
});
} else {
eleArr.each(function(item){
fv.enforceField(item);
});
}
return true;
}
}],
['validate-reqchk-bynode', {
errorMsg: function(){
return Form.Validator.getMsg('reqChkByNode');
},
test: function(element, props){
return (document.id(props.nodeId).getElements(props.selector || 'input[type=checkbox], input[type=radio]')).some(function(item){
return item.checked;
});
}
}],
['validate-required-check', {
errorMsg: function(element, props){
return props.useTitle ? element.get('title') : Form.Validator.getMsg('requiredChk');
},
test: function(element, props){
return !!element.checked;
}
}],
['validate-reqchk-byname', {
errorMsg: function(element, props){
return Form.Validator.getMsg('reqChkByName').substitute({label: props.label || element.get('type')});
},
test: function(element, props){
var grpName = props.groupName || element.get('name');
var oneCheckedItem = $$(document.getElementsByName(grpName)).some(function(item, index){
return item.checked;
});
var fv = element.getParent('form').retrieve('validator');
if (oneCheckedItem && fv) fv.resetField(element);
return oneCheckedItem;
}
}],
['validate-match', {
errorMsg: function(element, props){
return Form.Validator.getMsg('match').substitute({matchName: props.matchName || document.id(props.matchInput).get('name')});
},
test: function(element, props){
var eleVal = element.get('value');
var matchVal = document.id(props.matchInput) && document.id(props.matchInput).get('value');
return eleVal && matchVal ? eleVal == matchVal : true;
}
}],
['validate-after-date', {
errorMsg: function(element, props){
return Form.Validator.getMsg('afterDate').substitute({
label: props.afterLabel || (props.afterElement ? Form.Validator.getMsg('startDate') : Form.Validator.getMsg('currentDate'))
});
},
test: function(element, props){
var start = document.id(props.afterElement) ? Date.parse(document.id(props.afterElement).get('value')) : new Date();
var end = Date.parse(element.get('value'));
return end && start ? end >= start : true;
}
}],
['validate-before-date', {
errorMsg: function(element, props){
return Form.Validator.getMsg('beforeDate').substitute({
label: props.beforeLabel || (props.beforeElement ? Form.Validator.getMsg('endDate') : Form.Validator.getMsg('currentDate'))
});
},
test: function(element, props){
var start = Date.parse(element.get('value'));
var end = document.id(props.beforeElement) ? Date.parse(document.id(props.beforeElement).get('value')) : new Date();
return end && start ? end >= start : true;
}
}],
['validate-custom-required', {
errorMsg: function(){
return Form.Validator.getMsg('required');
},
test: function(element, props){
return element.get('value') != props.emptyValue;
}
}],
['validate-same-month', {
errorMsg: function(element, props){
var startMo = document.id(props.sameMonthAs) && document.id(props.sameMonthAs).get('value');
var eleVal = element.get('value');
if (eleVal != '') return Form.Validator.getMsg(startMo ? 'sameMonth' : 'startMonth');
},
test: function(element, props){
var d1 = Date.parse(element.get('value'));
var d2 = Date.parse(document.id(props.sameMonthAs) && document.id(props.sameMonthAs).get('value'));
return d1 && d2 ? d1.format('%B') == d2.format('%B') : true;
}
}],
['validate-cc-num', {
errorMsg: function(element){
var ccNum = element.get('value').replace(/[^0-9]/g, '');
return Form.Validator.getMsg('creditcard').substitute({length: ccNum.length});
},
test: function(element){
// required is a different test
if (Form.Validator.getValidator('IsEmpty').test(element)) return true;
// Clean number value
var ccNum = element.get('value');
ccNum = ccNum.replace(/[^0-9]/g, '');
var valid_type = false;
if (ccNum.test(/^4[0-9]{12}([0-9]{3})?$/)) valid_type = 'Visa';
else if (ccNum.test(/^5[1-5]([0-9]{14})$/)) valid_type = 'Master Card';
else if (ccNum.test(/^3[47][0-9]{13}$/)) valid_type = 'American Express';
else if (ccNum.test(/^6011[0-9]{12}$/)) valid_type = 'Discover';
if (valid_type){
var sum = 0;
var cur = 0;
for (var i=ccNum.length-1; i>=0; --i){
cur = ccNum.charAt(i).toInt();
if (cur == 0) continue;
if ((ccNum.length-i) % 2 == 0) cur += cur;
if (cur > 9){
cur = cur.toString().charAt(0).toInt() + cur.toString().charAt(1).toInt();
}
sum += cur;
}
if ((sum % 10) == 0) return true;
}
var chunks = '';
while (ccNum != ''){
chunks += ' ' + ccNum.substr(0,4);
ccNum = ccNum.substr(4);
}
element.getParent('form').retrieve('validator').ignoreField(element);
element.set('value', chunks.clean());
element.getParent('form').retrieve('validator').enforceField(element);
return false;
}
}]
]);
/*
---
script: OverText.js
name: OverText
description: Shows text over an input that disappears when the user clicks into it. The text remains hidden if the user adds a value.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Options
- Core/Events
- Core/Element.Event
- /Class.Binds
- /Class.Occlude
- /Element.Position
- /Element.Shortcuts
provides: [OverText]
...
*/
var OverText = new Class({
Implements: [Options, Events, Class.Occlude],
Binds: ['reposition', 'assert', 'focus', 'hide'],
options: {/*
textOverride: null,
onFocus: function(){},
onTextHide: function(textEl, inputEl){},
onTextShow: function(textEl, inputEl){}, */
element: 'label',
positionOptions: {
position: 'upperLeft',
edge: 'upperLeft',
offset: {
x: 4,
y: 2
}
},
poll: false,
pollInterval: 250,
wrap: false
},
property: 'OverText',
initialize: function(element, options){
this.element = document.id(element);
if (this.occlude()) return this.occluded;
this.setOptions(options);
this.attach(this.element);
OverText.instances.push(this);
if (this.options.poll) this.poll();
return this;
},
toElement: function(){
return this.element;
},
attach: function(){
var val = this.options.textOverride || this.element.get('alt') || this.element.get('title');
if (!val) return;
this.text = new Element(this.options.element, {
'class': 'overTxtLabel',
styles: {
lineHeight: 'normal',
position: 'absolute',
cursor: 'text'
},
html: val,
events: {
click: this.hide.pass(this.options.element == 'label', this)
}
}).inject(this.element, 'after');
if (this.options.element == 'label'){
if (!this.element.get('id')) this.element.set('id', 'input_' + new Date().getTime());
this.text.set('for', this.element.get('id'));
}
if (this.options.wrap){
this.textHolder = new Element('div', {
styles: {
lineHeight: 'normal',
position: 'relative'
},
'class':'overTxtWrapper'
}).adopt(this.text).inject(this.element, 'before');
}
return this.enable();
},
destroy: function(){
this.element.eliminate('OverTextDiv').eliminate('OverText');
this.disable();
if (this.text) this.text.destroy();
if (this.textHolder) this.textHolder.destroy();
return this;
},
disable: function(){
this.element.removeEvents({
focus: this.focus,
blur: this.assert,
change: this.assert
});
window.removeEvent('resize', this.reposition);
this.hide(true, true);
return this;
},
enable: function(){
this.element.addEvents({
focus: this.focus,
blur: this.assert,
change: this.assert
});
window.addEvent('resize', this.reposition);
this.assert(true);
this.reposition();
return this;
},
wrap: function(){
if (this.options.element == 'label'){
if (!this.element.get('id')) this.element.set('id', 'input_' + new Date().getTime());
this.text.set('for', this.element.get('id'));
}
},
startPolling: function(){
this.pollingPaused = false;
return this.poll();
},
poll: function(stop){
//start immediately
//pause on focus
//resumeon blur
if (this.poller && !stop) return this;
var test = function(){
if (!this.pollingPaused) this.assert(true);
}.bind(this);
if (stop) clearInterval(this.poller);
else this.poller = test.periodical(this.options.pollInterval, this);
return this;
},
stopPolling: function(){
this.pollingPaused = true;
return this.poll(true);
},
focus: function(){
if (this.text && (!this.text.isDisplayed() || this.element.get('disabled'))) return;
this.hide();
},
hide: function(suppressFocus, force){
if (this.text && (this.text.isDisplayed() && (!this.element.get('disabled') || force))){
this.text.hide();
this.fireEvent('textHide', [this.text, this.element]);
this.pollingPaused = true;
if (!suppressFocus){
try {
this.element.fireEvent('focus');
this.element.focus();
} catch(e){} //IE barfs if you call focus on hidden elements
}
}
return this;
},
show: function(){
if (this.text && !this.text.isDisplayed()){
this.text.show();
this.reposition();
this.fireEvent('textShow', [this.text, this.element]);
this.pollingPaused = false;
}
return this;
},
assert: function(suppressFocus){
this[this.test() ? 'show' : 'hide'](suppressFocus);
},
test: function(){
var v = this.element.get('value');
return !v;
},
reposition: function(){
this.assert(true);
if (!this.element.isVisible()) return this.stopPolling().hide();
if (this.text && this.test()) this.text.position(Object.merge(this.options.positionOptions, {relativeTo: this.element}));
return this;
}
});
OverText.instances = [];
Object.append(OverText, {
each: function(fn){
return OverText.instances.map(function(ot, i){
if (ot.element && ot.text) return fn.apply(OverText, [ot, i]);
return null; //the input or the text was destroyed
});
},
update: function(){
return OverText.each(function(ot){
return ot.reposition();
});
},
hideAll: function(){
return OverText.each(function(ot){
return ot.hide(true, true);
});
},
showAll: function(){
return OverText.each(function(ot){
return ot.show();
});
}
});
if (window.Fx && Fx.Reveal){
Fx.Reveal.implement({
hideInputs: Browser.ie ? 'select, input, textarea, object, embed, .overTxtLabel' : false
});
}
/*
---
script: Fx.Elements.js
name: Fx.Elements
description: Effect to change any number of CSS properties of any number of Elements.
license: MIT-style license
authors:
- Valerio Proietti
requires:
- Core/Fx.CSS
- /MooTools.More
provides: [Fx.Elements]
...
*/
Fx.Elements = new Class({
Extends: Fx.CSS,
initialize: function(elements, options){
this.elements = this.subject = $$(elements);
this.parent(options);
},
compute: function(from, to, delta){
var now = {};
for (var i in from){
var iFrom = from[i], iTo = to[i], iNow = now[i] = {};
for (var p in iFrom) iNow[p] = this.parent(iFrom[p], iTo[p], delta);
}
return now;
},
set: function(now){
for (var i in now){
if (!this.elements[i]) continue;
var iNow = now[i];
for (var p in iNow) this.render(this.elements[i], p, iNow[p], this.options.unit);
}
return this;
},
start: function(obj){
if (!this.check(obj)) return this;
var from = {}, to = {};
for (var i in obj){
if (!this.elements[i]) continue;
var iProps = obj[i], iFrom = from[i] = {}, iTo = to[i] = {};
for (var p in iProps){
var parsed = this.prepare(this.elements[i], p, iProps[p]);
iFrom[p] = parsed.from;
iTo[p] = parsed.to;
}
}
return this.parent(from, to);
}
});
/*
---
script: Fx.Accordion.js
name: Fx.Accordion
description: An Fx.Elements extension which allows you to easily create accordion type controls.
license: MIT-style license
authors:
- Valerio Proietti
requires:
- Core/Element.Event
- /Fx.Elements
provides: [Fx.Accordion]
...
*/
Fx.Accordion = new Class({
Extends: Fx.Elements,
options: {/*
onActive: function(toggler, section){},
onBackground: function(toggler, section){},*/
fixedHeight: false,
fixedWidth: false,
display: 0,
show: false,
height: true,
width: false,
opacity: true,
alwaysHide: false,
trigger: 'click',
initialDisplayFx: true,
returnHeightToAuto: true
},
initialize: function(){
var defined = function(obj){
return obj != null;
};
var params = Array.link(arguments, {
'container': Type.isElement, //deprecated
'options': Type.isObject,
'togglers': defined,
'elements': defined
});
this.parent(params.elements, params.options);
this.togglers = $$(params.togglers);
this.previous = -1;
this.internalChain = new Chain();
if (this.options.alwaysHide) this.options.wait = true;
if (this.options.show || this.options.show === 0){
this.options.display = false;
this.previous = this.options.show;
}
if (this.options.start){
this.options.display = false;
this.options.show = false;
}
this.effects = {};
if (this.options.opacity) this.effects.opacity = 'fullOpacity';
if (this.options.width) this.effects.width = this.options.fixedWidth ? 'fullWidth' : 'offsetWidth';
if (this.options.height) this.effects.height = this.options.fixedHeight ? 'fullHeight' : 'scrollHeight';
for (var i = 0, l = this.togglers.length; i < l; i++) this.addSection(this.togglers[i], this.elements[i]);
this.elements.each(function(el, i){
if (this.options.show === i){
this.fireEvent('active', [this.togglers[i], el]);
} else {
for (var fx in this.effects) el.setStyle(fx, 0);
}
}, this);
if (this.options.display || this.options.display === 0 || this.options.initialDisplayFx === false){
this.display(this.options.display, this.options.initialDisplayFx);
}
if (this.options.fixedHeight !== false) this.options.returnHeightToAuto = false;
this.addEvent('complete', this.internalChain.callChain.bind(this.internalChain));
},
addSection: function(toggler, element){
toggler = document.id(toggler);
element = document.id(element);
this.togglers.include(toggler);
this.elements.include(element);
var test = this.togglers.contains(toggler);
var idx = this.togglers.indexOf(toggler);
var displayer = this.display.pass(idx, this);
toggler.store('accordion:display', displayer)
.addEvent(this.options.trigger, displayer);
if (this.options.height) element.setStyles({'padding-top': 0, 'border-top': 'none', 'padding-bottom': 0, 'border-bottom': 'none'});
if (this.options.width) element.setStyles({'padding-left': 0, 'border-left': 'none', 'padding-right': 0, 'border-right': 'none'});
element.fullOpacity = 1;
if (this.options.fixedWidth) element.fullWidth = this.options.fixedWidth;
if (this.options.fixedHeight) element.fullHeight = this.options.fixedHeight;
element.setStyle('overflow', 'hidden');
if (!test){
for (var fx in this.effects) element.setStyle(fx, 0);
}
return this;
},
removeSection: function(toggler, displayIndex){
var idx = this.togglers.indexOf(toggler);
var element = this.elements[idx];
var remover = function(){
this.togglers.erase(toggler);
this.elements.erase(element);
this.detach(toggler);
}.bind(this);
if (this.now == idx || displayIndex != null){
this.display(displayIndex != null ? displayIndex : (idx - 1 >= 0 ? idx - 1 : 0)).chain(remover);
} else {
remover();
}
return this;
},
detach: function(toggler){
var remove = function(toggler){
toggler.removeEvent(this.options.trigger, toggler.retrieve('accordion:display'));
}.bind(this);
if (!toggler) this.togglers.each(remove);
else remove(toggler);
return this;
},
display: function(index, useFx){
if (!this.check(index, useFx)) return this;
useFx = useFx != null ? useFx : true;
index = (typeOf(index) == 'element') ? this.elements.indexOf(index) : index;
if (index == this.previous && !this.options.alwaysHide) return this;
if (this.options.returnHeightToAuto){
var prev = this.elements[this.previous];
if (prev && !this.selfHidden){
for (var fx in this.effects){
prev.setStyle(fx, prev[this.effects[fx]]);
}
}
}
if ((this.timer && this.options.wait) || (index === this.previous && !this.options.alwaysHide)) return this;
this.previous = index;
var obj = {};
this.elements.each(function(el, i){
obj[i] = {};
var hide;
if (i != index){
hide = true;
} else if (this.options.alwaysHide && ((el.offsetHeight > 0 && this.options.height) || el.offsetWidth > 0 && this.options.width)){
hide = true;
this.selfHidden = true;
}
this.fireEvent(hide ? 'background' : 'active', [this.togglers[i], el]);
for (var fx in this.effects) obj[i][fx] = hide ? 0 : el[this.effects[fx]];
}, this);
this.internalChain.clearChain();
this.internalChain.chain(function(){
if (this.options.returnHeightToAuto && !this.selfHidden){
var el = this.elements[index];
if (el) el.setStyle('height', 'auto');
};
}.bind(this));
return useFx ? this.start(obj) : this.set(obj);
}
});
/*
---
script: Fx.Move.js
name: Fx.Move
description: Defines Fx.Move, a class that works with Element.Position.js to transition an element from one location to another.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Fx.Morph
- /Element.Position
provides: [Fx.Move]
...
*/
Fx.Move = new Class({
Extends: Fx.Morph,
options: {
relativeTo: document.body,
position: 'center',
edge: false,
offset: {x: 0, y: 0}
},
start: function(destination){
var element = this.element,
topLeft = element.getStyles('top', 'left');
if (topLeft.top == 'auto' || topLeft.left == 'auto'){
element.setPosition(element.getPosition(element.getOffsetParent()));
}
return this.parent(element.position(Object.merge(this.options, destination, {returnPos: true})));
}
});
Element.Properties.move = {
set: function(options){
this.get('move').cancel().setOptions(options);
return this;
},
get: function(){
var move = this.retrieve('move');
if (!move){
move = new Fx.Move(this, {link: 'cancel'});
this.store('move', move);
}
return move;
}
};
Element.implement({
move: function(options){
this.get('move').start(options);
return this;
}
});
/*
---
script: Fx.Slide.js
name: Fx.Slide
description: Effect to slide an element in and out of view.
license: MIT-style license
authors:
- Valerio Proietti
requires:
- Core/Fx
- Core/Element.Style
- /MooTools.More
provides: [Fx.Slide]
...
*/
Fx.Slide = new Class({
Extends: Fx,
options: {
mode: 'vertical',
wrapper: false,
hideOverflow: true,
resetHeight: false
},
initialize: function(element, options){
this.addEvent('complete', function(){
this.open = (this.wrapper['offset' + this.layout.capitalize()] != 0);
if (this.open && this.options.resetHeight) this.wrapper.setStyle('height', '');
}, true);
this.element = this.subject = document.id(element);
this.parent(options);
var wrapper = this.element.retrieve('wrapper');
var styles = this.element.getStyles('margin', 'position', 'overflow');
if (this.options.hideOverflow) styles = Object.append(styles, {overflow: 'hidden'});
if (this.options.wrapper) wrapper = document.id(this.options.wrapper).setStyles(styles);
this.wrapper = wrapper || new Element('div', {
styles: styles
}).wraps(this.element);
this.element.store('wrapper', this.wrapper).setStyle('margin', 0);
this.now = [];
this.open = true;
},
vertical: function(){
this.margin = 'margin-top';
this.layout = 'height';
this.offset = this.element.offsetHeight;
},
horizontal: function(){
this.margin = 'margin-left';
this.layout = 'width';
this.offset = this.element.offsetWidth;
},
set: function(now){
this.element.setStyle(this.margin, now[0]);
this.wrapper.setStyle(this.layout, now[1]);
return this;
},
compute: function(from, to, delta){
return [0, 1].map(function(i){
return Fx.compute(from[i], to[i], delta);
});
},
start: function(how, mode){
if (!this.check(how, mode)) return this;
this[mode || this.options.mode]();
var margin = this.element.getStyle(this.margin).toInt();
var layout = this.wrapper.getStyle(this.layout).toInt();
var caseIn = [[margin, layout], [0, this.offset]];
var caseOut = [[margin, layout], [-this.offset, 0]];
var start;
switch (how){
case 'in': start = caseIn; break;
case 'out': start = caseOut; break;
case 'toggle': start = (layout == 0) ? caseIn : caseOut;
}
return this.parent(start[0], start[1]);
},
slideIn: function(mode){
return this.start('in', mode);
},
slideOut: function(mode){
return this.start('out', mode);
},
hide: function(mode){
this[mode || this.options.mode]();
this.open = false;
return this.set([-this.offset, 0]);
},
show: function(mode){
this[mode || this.options.mode]();
this.open = true;
return this.set([0, this.offset]);
},
toggle: function(mode){
return this.start('toggle', mode);
}
});
Element.Properties.slide = {
set: function(options){
this.get('slide').cancel().setOptions(options);
return this;
},
get: function(){
var slide = this.retrieve('slide');
if (!slide){
slide = new Fx.Slide(this, {link: 'cancel'});
this.store('slide', slide);
}
return slide;
}
};
Element.implement({
slide: function(how, mode){
how = how || 'toggle';
var slide = this.get('slide'), toggle;
switch (how){
case 'hide': slide.hide(mode); break;
case 'show': slide.show(mode); break;
case 'toggle':
var flag = this.retrieve('slide:flag', slide.open);
slide[flag ? 'slideOut' : 'slideIn'](mode);
this.store('slide:flag', !flag);
toggle = true;
break;
default: slide.start(how, mode);
}
if (!toggle) this.eliminate('slide:flag');
return this;
}
});
/*
---
script: Fx.Scroll.js
name: Fx.Scroll
description: Effect to smoothly scroll any element, including the window.
license: MIT-style license
authors:
- Valerio Proietti
requires:
- Core/Fx
- Core/Element.Event
- Core/Element.Dimensions
- /MooTools.More
provides: [Fx.Scroll]
...
*/
(function(){
Fx.Scroll = new Class({
Extends: Fx,
options: {
offset: {x: 0, y: 0},
wheelStops: true
},
initialize: function(element, options){
this.element = this.subject = document.id(element);
this.parent(options);
if (typeOf(this.element) != 'element') this.element = document.id(this.element.getDocument().body);
if (this.options.wheelStops){
var stopper = this.element,
cancel = this.cancel.pass(false, this);
this.addEvent('start', function(){
stopper.addEvent('mousewheel', cancel);
}, true);
this.addEvent('complete', function(){
stopper.removeEvent('mousewheel', cancel);
}, true);
}
},
set: function(){
var now = Array.flatten(arguments);
if (Browser.firefox) now = [Math.round(now[0]), Math.round(now[1])]; // not needed anymore in newer firefox versions
this.element.scrollTo(now[0] + this.options.offset.x, now[1] + this.options.offset.y);
},
compute: function(from, to, delta){
return [0, 1].map(function(i){
return Fx.compute(from[i], to[i], delta);
});
},
start: function(x, y){
if (!this.check(x, y)) return this;
var element = this.element,
scrollSize = element.getScrollSize(),
scroll = element.getScroll(),
size = element.getSize();
values = {x: x, y: y};
for (var z in values){
if (!values[z] && values[z] !== 0) values[z] = scroll[z];
if (typeOf(values[z]) != 'number') values[z] = scrollSize[z] - size[z];
values[z] += this.options.offset[z];
}
return this.parent([scroll.x, scroll.y], [values.x, values.y]);
},
toTop: function(){
return this.start(false, 0);
},
toLeft: function(){
return this.start(0, false);
},
toRight: function(){
return this.start('right', false);
},
toBottom: function(){
return this.start(false, 'bottom');
},
toElement: function(el){
var position = document.id(el).getPosition(this.element),
scroll = isBody(this.element) ? {x: 0, y: 0} : this.element.getScroll();
return this.start(position.x + scroll.x, position.y + scroll.y);
},
scrollIntoView: function(el, axes, offset){
axes = axes ? Array.from(axes) : ['x','y'];
el = document.id(el);
var to = {},
position = el.getPosition(this.element),
size = el.getSize(),
scroll = this.element.getScroll(),
containerSize = this.element.getSize(),
edge = {
x: position.x + size.x,
y: position.y + size.y
};
['x','y'].each(function(axis){
if (axes.contains(axis)){
if (edge[axis] > scroll[axis] + containerSize[axis]) to[axis] = edge[axis] - containerSize[axis];
if (position[axis] < scroll[axis]) to[axis] = position[axis];
}
if (to[axis] == null) to[axis] = scroll[axis];
if (offset && offset[axis]) to[axis] = to[axis] + offset[axis];
}, this);
if (to.x != scroll.x || to.y != scroll.y) this.start(to.x, to.y);
return this;
},
scrollToCenter: function(el, axes, offset){
axes = axes ? Array.from(axes) : ['x', 'y'];
el = document.id(el);
var to = {},
position = el.getPosition(this.element),
size = el.getSize(),
scroll = this.element.getScroll(),
containerSize = this.element.getSize();
['x','y'].each(function(axis){
if (axes.contains(axis)){
to[axis] = position[axis] - (containerSize[axis] - size[axis])/2;
}
if (to[axis] == null) to[axis] = scroll[axis];
if (offset && offset[axis]) to[axis] = to[axis] + offset[axis];
}, this);
if (to.x != scroll.x || to.y != scroll.y) this.start(to.x, to.y);
return this;
}
});
function isBody(element){
return (/^(?:body|html)$/i).test(element.tagName);
};
})();
/*
---
script: Fx.SmoothScroll.js
name: Fx.SmoothScroll
description: Class for creating a smooth scrolling effect to all internal links on the page.
license: MIT-style license
authors:
- Valerio Proietti
requires:
- Core/Slick.Finder
- /Fx.Scroll
provides: [Fx.SmoothScroll]
...
*/
Fx.SmoothScroll = new Class({
Extends: Fx.Scroll,
initialize: function(options, context){
context = context || document;
this.doc = context.getDocument();
this.parent(this.doc, options);
var win = context.getWindow(),
location = win.location.href.match(/^[^#]*/)[0] + '#',
links = $$(this.options.links || this.doc.links);
links.each(function(link){
if (link.href.indexOf(location) != 0) return;
var anchor = link.href.substr(location.length);
if (anchor) this.useLink(link, anchor);
}, this);
},
useLink: function(link, anchor){
link.addEvent('click', function(event){
var el = document.id(anchor) || this.doc.getElement('a[name=' + anchor + ']');
if (!el) return;
event.preventDefault();
this.toElement(el).chain(function(){
this.fireEvent('scrolledTo', [link, el]);
}.bind(this));
}.bind(this));
return this;
}
});
/*
---
script: Fx.Sort.js
name: Fx.Sort
description: Defines Fx.Sort, a class that reorders lists with a transition.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Element.Dimensions
- /Fx.Elements
- /Element.Measure
provides: [Fx.Sort]
...
*/
Fx.Sort = new Class({
Extends: Fx.Elements,
options: {
mode: 'vertical'
},
initialize: function(elements, options){
this.parent(elements, options);
this.elements.each(function(el){
if (el.getStyle('position') == 'static') el.setStyle('position', 'relative');
});
this.setDefaultOrder();
},
setDefaultOrder: function(){
this.currentOrder = this.elements.map(function(el, index){
return index;
});
},
sort: function(){
if (!this.check(arguments)) return this;
var newOrder = Array.flatten(arguments);
var top = 0,
left = 0,
next = {},
zero = {},
vert = this.options.mode == 'vertical';
var current = this.elements.map(function(el, index){
var size = el.getComputedSize({styles: ['border', 'padding', 'margin']});
var val;
if (vert){
val = {
top: top,
margin: size['margin-top'],
height: size.totalHeight
};
top += val.height - size['margin-top'];
} else {
val = {
left: left,
margin: size['margin-left'],
width: size.totalWidth
};
left += val.width;
}
var plane = vert ? 'top' : 'left';
zero[index] = {};
var start = el.getStyle(plane).toInt();
zero[index][plane] = start || 0;
return val;
}, this);
this.set(zero);
newOrder = newOrder.map(function(i){ return i.toInt(); });
if (newOrder.length != this.elements.length){
this.currentOrder.each(function(index){
if (!newOrder.contains(index)) newOrder.push(index);
});
if (newOrder.length > this.elements.length)
newOrder.splice(this.elements.length-1, newOrder.length - this.elements.length);
}
var margin = top = left = 0;
newOrder.each(function(item, index){
var newPos = {};
if (vert){
newPos.top = top - current[item].top - margin;
top += current[item].height;
} else {
newPos.left = left - current[item].left;
left += current[item].width;
}
margin = margin + current[item].margin;
next[item]=newPos;
}, this);
var mapped = {};
Array.clone(newOrder).sort().each(function(index){
mapped[index] = next[index];
});
this.start(mapped);
this.currentOrder = newOrder;
return this;
},
rearrangeDOM: function(newOrder){
newOrder = newOrder || this.currentOrder;
var parent = this.elements[0].getParent();
var rearranged = [];
this.elements.setStyle('opacity', 0);
//move each element and store the new default order
newOrder.each(function(index){
rearranged.push(this.elements[index].inject(parent).setStyles({
top: 0,
left: 0
}));
}, this);
this.elements.setStyle('opacity', 1);
this.elements = $$(rearranged);
this.setDefaultOrder();
return this;
},
getDefaultOrder: function(){
return this.elements.map(function(el, index){
return index;
});
},
forward: function(){
return this.sort(this.getDefaultOrder());
},
backward: function(){
return this.sort(this.getDefaultOrder().reverse());
},
reverse: function(){
return this.sort(this.currentOrder.reverse());
},
sortByElements: function(elements){
return this.sort(elements.map(function(el){
return this.elements.indexOf(el);
}, this));
},
swap: function(one, two){
if (typeOf(one) == 'element') one = this.elements.indexOf(one);
if (typeOf(two) == 'element') two = this.elements.indexOf(two);
var newOrder = Array.clone(this.currentOrder);
newOrder[this.currentOrder.indexOf(one)] = two;
newOrder[this.currentOrder.indexOf(two)] = one;
return this.sort(newOrder);
}
});
/*
---
script: Drag.js
name: Drag
description: The base Drag Class. Can be used to drag and resize Elements using mouse events.
license: MIT-style license
authors:
- Valerio Proietti
- Tom Occhinno
- Jan Kassens
requires:
- Core/Events
- Core/Options
- Core/Element.Event
- Core/Element.Style
- Core/Element.Dimensions
- /MooTools.More
provides: [Drag]
...
*/
var Drag = new Class({
Implements: [Events, Options],
options: {/*
onBeforeStart: function(thisElement){},
onStart: function(thisElement, event){},
onSnap: function(thisElement){},
onDrag: function(thisElement, event){},
onCancel: function(thisElement){},
onComplete: function(thisElement, event){},*/
snap: 6,
unit: 'px',
grid: false,
style: true,
limit: false,
handle: false,
invert: false,
preventDefault: false,
stopPropagation: false,
modifiers: {x: 'left', y: 'top'}
},
initialize: function(){
var params = Array.link(arguments, {
'options': Type.isObject,
'element': function(obj){
return obj != null;
}
});
this.element = document.id(params.element);
this.document = this.element.getDocument();
this.setOptions(params.options || {});
var htype = typeOf(this.options.handle);
this.handles = ((htype == 'array' || htype == 'collection') ? $$(this.options.handle) : document.id(this.options.handle)) || this.element;
this.mouse = {'now': {}, 'pos': {}};
this.value = {'start': {}, 'now': {}};
this.selection = (Browser.ie) ? 'selectstart' : 'mousedown';
if (Browser.ie && !Drag.ondragstartFixed){
document.ondragstart = Function.from(false);
Drag.ondragstartFixed = true;
}
this.bound = {
start: this.start.bind(this),
check: this.check.bind(this),
drag: this.drag.bind(this),
stop: this.stop.bind(this),
cancel: this.cancel.bind(this),
eventStop: Function.from(false)
};
this.attach();
},
attach: function(){
this.handles.addEvent('mousedown', this.bound.start);
return this;
},
detach: function(){
this.handles.removeEvent('mousedown', this.bound.start);
return this;
},
start: function(event){
var options = this.options;
if (event.rightClick) return;
if (options.preventDefault) event.preventDefault();
if (options.stopPropagation) event.stopPropagation();
this.mouse.start = event.page;
this.fireEvent('beforeStart', this.element);
var limit = options.limit;
this.limit = {x: [], y: []};
var styles = this.element.getStyles('left', 'right', 'top', 'bottom');
this._invert = {
x: options.modifiers.x == 'left' && styles.left == 'auto' && !isNaN(styles.right.toInt()) && (options.modifiers.x = 'right'),
y: options.modifiers.y == 'top' && styles.top == 'auto' && !isNaN(styles.bottom.toInt()) && (options.modifiers.y = 'bottom')
};
var z, coordinates;
for (z in options.modifiers){
if (!options.modifiers[z]) continue;
var style = this.element.getStyle(options.modifiers[z]);
// Some browsers (IE and Opera) don't always return pixels.
if (style && !style.match(/px$/)){
if (!coordinates) coordinates = this.element.getCoordinates(this.element.getOffsetParent());
style = coordinates[options.modifiers[z]];
}
if (options.style) this.value.now[z] = (style || 0).toInt();
else this.value.now[z] = this.element[options.modifiers[z]];
if (options.invert) this.value.now[z] *= -1;
if (this._invert[z]) this.value.now[z] *= -1;
this.mouse.pos[z] = event.page[z] - this.value.now[z];
if (limit && limit[z]){
var i = 2;
while (i--){
var limitZI = limit[z][i];
if (limitZI || limitZI === 0) this.limit[z][i] = (typeof limitZI == 'function') ? limitZI() : limitZI;
}
}
}
if (typeOf(this.options.grid) == 'number') this.options.grid = {
x: this.options.grid,
y: this.options.grid
};
var events = {
mousemove: this.bound.check,
mouseup: this.bound.cancel
};
events[this.selection] = this.bound.eventStop;
this.document.addEvents(events);
},
check: function(event){
if (this.options.preventDefault) event.preventDefault();
var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2)));
if (distance > this.options.snap){
this.cancel();
this.document.addEvents({
mousemove: this.bound.drag,
mouseup: this.bound.stop
});
this.fireEvent('start', [this.element, event]).fireEvent('snap', this.element);
}
},
drag: function(event){
var options = this.options;
if (options.preventDefault) event.preventDefault();
this.mouse.now = event.page;
for (var z in options.modifiers){
if (!options.modifiers[z]) continue;
this.value.now[z] = this.mouse.now[z] - this.mouse.pos[z];
if (options.invert) this.value.now[z] *= -1;
if (this._invert[z]) this.value.now[z] *= -1;
if (options.limit && this.limit[z]){
if ((this.limit[z][1] || this.limit[z][1] === 0) && (this.value.now[z] > this.limit[z][1])){
this.value.now[z] = this.limit[z][1];
} else if ((this.limit[z][0] || this.limit[z][0] === 0) && (this.value.now[z] < this.limit[z][0])){
this.value.now[z] = this.limit[z][0];
}
}
if (options.grid[z]) this.value.now[z] -= ((this.value.now[z] - (this.limit[z][0]||0)) % options.grid[z]);
if (options.style) this.element.setStyle(options.modifiers[z], this.value.now[z] + options.unit);
else this.element[options.modifiers[z]] = this.value.now[z];
}
this.fireEvent('drag', [this.element, event]);
},
cancel: function(event){
this.document.removeEvents({
mousemove: this.bound.check,
mouseup: this.bound.cancel
});
if (event){
this.document.removeEvent(this.selection, this.bound.eventStop);
this.fireEvent('cancel', this.element);
}
},
stop: function(event){
var events = {
mousemove: this.bound.drag,
mouseup: this.bound.stop
};
events[this.selection] = this.bound.eventStop;
this.document.removeEvents(events);
if (event) this.fireEvent('complete', [this.element, event]);
}
});
Element.implement({
makeResizable: function(options){
var drag = new Drag(this, Object.merge({
modifiers: {
x: 'width',
y: 'height'
}
}, options));
this.store('resizer', drag);
return drag.addEvent('drag', function(){
this.fireEvent('resize', drag);
}.bind(this));
}
});
/*
---
script: Slider.js
name: Slider
description: Class for creating horizontal and vertical slider controls.
license: MIT-style license
authors:
- Valerio Proietti
requires:
- Core/Element.Dimensions
- /Class.Binds
- /Drag
- /Element.Measure
provides: [Slider]
...
*/
var Slider = new Class({
Implements: [Events, Options],
Binds: ['clickedElement', 'draggedKnob', 'scrolledElement'],
options: {/*
onTick: function(intPosition){},
onChange: function(intStep){},
onComplete: function(strStep){},*/
onTick: function(position){
if (this.options.snap) position = this.toPosition(this.step);
this.knob.setStyle(this.property, position);
},
initialStep: 0,
snap: false,
offset: 0,
range: false,
wheel: false,
steps: 100,
mode: 'horizontal'
},
initialize: function(element, knob, options){
this.setOptions(options);
this.element = document.id(element);
this.knob = document.id(knob);
this.previousChange = this.previousEnd = this.step = -1;
var offset, limit = {}, modifiers = {'x': false, 'y': false};
switch (this.options.mode){
case 'vertical':
this.axis = 'y';
this.property = 'top';
offset = 'offsetHeight';
break;
case 'horizontal':
this.axis = 'x';
this.property = 'left';
offset = 'offsetWidth';
}
this.full = this.element.measure(function(){
this.half = this.knob[offset] / 2;
return this.element[offset] - this.knob[offset] + (this.options.offset * 2);
}.bind(this));
this.setRange(this.options.range);
this.knob.setStyle('position', 'relative').setStyle(this.property, - this.options.offset);
modifiers[this.axis] = this.property;
limit[this.axis] = [- this.options.offset, this.full - this.options.offset];
var dragOptions = {
snap: 0,
limit: limit,
modifiers: modifiers,
onDrag: this.draggedKnob,
onStart: this.draggedKnob,
onBeforeStart: (function(){
this.isDragging = true;
}).bind(this),
onCancel: function(){
this.isDragging = false;
}.bind(this),
onComplete: function(){
this.isDragging = false;
this.draggedKnob();
this.end();
}.bind(this)
};
if (this.options.snap){
dragOptions.grid = Math.ceil(this.stepWidth);
dragOptions.limit[this.axis][1] = this.full;
}
this.drag = new Drag(this.knob, dragOptions);
this.attach();
if (this.options.initialStep != null) this.set(this.options.initialStep)
},
attach: function(){
this.element.addEvent('mousedown', this.clickedElement);
if (this.options.wheel) this.element.addEvent('mousewheel', this.scrolledElement);
this.drag.attach();
return this;
},
detach: function(){
this.element.removeEvent('mousedown', this.clickedElement);
this.element.removeEvent('mousewheel', this.scrolledElement);
this.drag.detach();
return this;
},
set: function(step){
if (!((this.range > 0) ^ (step < this.min))) step = this.min;
if (!((this.range > 0) ^ (step > this.max))) step = this.max;
this.step = Math.round(step);
this.checkStep();
this.fireEvent('tick', this.toPosition(this.step));
this.end();
return this;
},
setRange: function(range, pos){
this.min = Array.pick([range[0], 0]);
this.max = Array.pick([range[1], this.options.steps]);
this.range = this.max - this.min;
this.steps = this.options.steps || this.full;
this.stepSize = Math.abs(this.range) / this.steps;
this.stepWidth = this.stepSize * this.full / Math.abs(this.range);
this.set(Array.pick([pos, this.step]).floor(this.min).max(this.max));
return this;
},
clickedElement: function(event){
if (this.isDragging || event.target == this.knob) return;
var dir = this.range < 0 ? -1 : 1;
var position = event.page[this.axis] - this.element.getPosition()[this.axis] - this.half;
position = position.limit(-this.options.offset, this.full -this.options.offset);
this.step = Math.round(this.min + dir * this.toStep(position));
this.checkStep();
this.fireEvent('tick', position);
this.end();
},
scrolledElement: function(event){
var mode = (this.options.mode == 'horizontal') ? (event.wheel < 0) : (event.wheel > 0);
this.set(mode ? this.step - this.stepSize : this.step + this.stepSize);
event.stop();
},
draggedKnob: function(){
var dir = this.range < 0 ? -1 : 1;
var position = this.drag.value.now[this.axis];
position = position.limit(-this.options.offset, this.full -this.options.offset);
this.step = Math.round(this.min + dir * this.toStep(position));
this.checkStep();
},
checkStep: function(){
if (this.previousChange != this.step){
this.previousChange = this.step;
this.fireEvent('change', this.step);
}
},
end: function(){
if (this.previousEnd !== this.step){
this.previousEnd = this.step;
this.fireEvent('complete', this.step + '');
}
},
toStep: function(position){
var step = (position + this.options.offset) * this.stepSize / this.full * this.steps;
return this.options.steps ? Math.round(step -= step % this.stepSize) : step;
},
toPosition: function(step){
return (this.full * Math.abs(this.min - step)) / (this.steps * this.stepSize) - this.options.offset;
}
});
/*
---
script: Drag.Move.js
name: Drag.Move
description: A Drag extension that provides support for the constraining of draggables to containers and droppables.
license: MIT-style license
authors:
- Valerio Proietti
- Tom Occhinno
- Jan Kassens
- Aaron Newton
- Scott Kyle
requires:
- Core/Element.Dimensions
- /Drag
provides: [Drag.Move]
...
*/
Drag.Move = new Class({
Extends: Drag,
options: {/*
onEnter: function(thisElement, overed){},
onLeave: function(thisElement, overed){},
onDrop: function(thisElement, overed, event){},*/
droppables: [],
container: false,
precalculate: false,
includeMargins: true,
checkDroppables: true
},
initialize: function(element, options){
this.parent(element, options);
element = this.element;
this.droppables = $$(this.options.droppables);
this.container = document.id(this.options.container);
if (this.container && typeOf(this.container) != 'element')
this.container = document.id(this.container.getDocument().body);
if (this.options.style){
if (this.options.modifiers.x == "left" && this.options.modifiers.y == "top"){
var parentStyles,
parent = element.getOffsetParent();
var styles = element.getStyles('left', 'top');
if (parent && (styles.left == 'auto' || styles.top == 'auto')){
element.setPosition(element.getPosition(parent));
}
}
if (element.getStyle('position') == 'static') element.setStyle('position', 'absolute');
}
this.addEvent('start', this.checkDroppables, true);
this.overed = null;
},
start: function(event){
if (this.container) this.options.limit = this.calculateLimit();
if (this.options.precalculate){
this.positions = this.droppables.map(function(el){
return el.getCoordinates();
});
}
this.parent(event);
},
calculateLimit: function(){
var element = this.element,
container = this.container,
offsetParent = document.id(element.getOffsetParent()) || document.body,
containerCoordinates = container.getCoordinates(offsetParent),
elementMargin = {},
elementBorder = {},
containerMargin = {},
containerBorder = {},
offsetParentPadding = {};
['top', 'right', 'bottom', 'left'].each(function(pad){
elementMargin[pad] = element.getStyle('margin-' + pad).toInt();
elementBorder[pad] = element.getStyle('border-' + pad).toInt();
containerMargin[pad] = container.getStyle('margin-' + pad).toInt();
containerBorder[pad] = container.getStyle('border-' + pad).toInt();
offsetParentPadding[pad] = offsetParent.getStyle('padding-' + pad).toInt();
}, this);
var width = element.offsetWidth + elementMargin.left + elementMargin.right,
height = element.offsetHeight + elementMargin.top + elementMargin.bottom,
left = 0,
top = 0,
right = containerCoordinates.right - containerBorder.right - width,
bottom = containerCoordinates.bottom - containerBorder.bottom - height;
if (this.options.includeMargins){
left += elementMargin.left;
top += elementMargin.top;
} else {
right += elementMargin.right;
bottom += elementMargin.bottom;
}
if (element.getStyle('position') == 'relative'){
var coords = element.getCoordinates(offsetParent);
coords.left -= element.getStyle('left').toInt();
coords.top -= element.getStyle('top').toInt();
left -= coords.left;
top -= coords.top;
if (container.getStyle('position') != 'relative'){
left += containerBorder.left;
top += containerBorder.top;
}
right += elementMargin.left - coords.left;
bottom += elementMargin.top - coords.top;
if (container != offsetParent){
left += containerMargin.left + offsetParentPadding.left;
top += ((Browser.ie6 || Browser.ie7) ? 0 : containerMargin.top) + offsetParentPadding.top;
}
} else {
left -= elementMargin.left;
top -= elementMargin.top;
if (container != offsetParent){
left += containerCoordinates.left + containerBorder.left;
top += containerCoordinates.top + containerBorder.top;
}
}
return {
x: [left, right],
y: [top, bottom]
};
},
checkDroppables: function(){
var overed = this.droppables.filter(function(el, i){
el = this.positions ? this.positions[i] : el.getCoordinates();
var now = this.mouse.now;
return (now.x > el.left && now.x < el.right && now.y < el.bottom && now.y > el.top);
}, this).getLast();
if (this.overed != overed){
if (this.overed) this.fireEvent('leave', [this.element, this.overed]);
if (overed) this.fireEvent('enter', [this.element, overed]);
this.overed = overed;
}
},
drag: function(event){
this.parent(event);
if (this.options.checkDroppables && this.droppables.length) this.checkDroppables();
},
stop: function(event){
this.checkDroppables();
this.fireEvent('drop', [this.element, this.overed, event]);
this.overed = null;
return this.parent(event);
}
});
Element.implement({
makeDraggable: function(options){
var drag = new Drag.Move(this, options);
this.store('dragger', drag);
return drag;
}
});
/*
---
script: Sortables.js
name: Sortables
description: Class for creating a drag and drop sorting interface for lists of items.
license: MIT-style license
authors:
- Tom Occhino
requires:
- /Drag.Move
provides: [Sortables]
...
*/
var Sortables = new Class({
Implements: [Events, Options],
options: {/*
onSort: function(element, clone){},
onStart: function(element, clone){},
onComplete: function(element){},*/
snap: 4,
opacity: 1,
clone: false,
revert: false,
handle: false,
constrain: false,
preventDefault: false
},
initialize: function(lists, options){
this.setOptions(options);
this.elements = [];
this.lists = [];
this.idle = true;
this.addLists($$(document.id(lists) || lists));
if (!this.options.clone) this.options.revert = false;
if (this.options.revert) this.effect = new Fx.Morph(null, Object.merge({
duration: 250,
link: 'cancel'
}, this.options.revert));
},
attach: function(){
this.addLists(this.lists);
return this;
},
detach: function(){
this.lists = this.removeLists(this.lists);
return this;
},
addItems: function(){
Array.flatten(arguments).each(function(element){
this.elements.push(element);
var start = element.retrieve('sortables:start', function(event){
this.start.call(this, event, element);
}.bind(this));
(this.options.handle ? element.getElement(this.options.handle) || element : element).addEvent('mousedown', start);
}, this);
return this;
},
addLists: function(){
Array.flatten(arguments).each(function(list){
this.lists.push(list);
this.addItems(list.getChildren());
}, this);
return this;
},
removeItems: function(){
return $$(Array.flatten(arguments).map(function(element){
this.elements.erase(element);
var start = element.retrieve('sortables:start');
(this.options.handle ? element.getElement(this.options.handle) || element : element).removeEvent('mousedown', start);
return element;
}, this));
},
removeLists: function(){
return $$(Array.flatten(arguments).map(function(list){
this.lists.erase(list);
this.removeItems(list.getChildren());
return list;
}, this));
},
getClone: function(event, element){
if (!this.options.clone) return new Element(element.tagName).inject(document.body);
if (typeOf(this.options.clone) == 'function') return this.options.clone.call(this, event, element, this.list);
var clone = element.clone(true).setStyles({
margin: 0,
position: 'absolute',
visibility: 'hidden',
width: element.getStyle('width')
});
//prevent the duplicated radio inputs from unchecking the real one
if (clone.get('html').test('radio')){
clone.getElements('input[type=radio]').each(function(input, i){
input.set('name', 'clone_' + i);
if (input.get('checked')) element.getElements('input[type=radio]')[i].set('checked', true);
});
}
return clone.inject(this.list).setPosition(element.getPosition(element.getOffsetParent()));
},
getDroppables: function(){
var droppables = this.list.getChildren().erase(this.clone).erase(this.element);
if (!this.options.constrain) droppables.append(this.lists).erase(this.list);
return droppables;
},
insert: function(dragging, element){
var where = 'inside';
if (this.lists.contains(element)){
this.list = element;
this.drag.droppables = this.getDroppables();
} else {
where = this.element.getAllPrevious().contains(element) ? 'before' : 'after';
}
this.element.inject(element, where);
this.fireEvent('sort', [this.element, this.clone]);
},
start: function(event, element){
if (
!this.idle ||
event.rightClick ||
['button', 'input'].contains(event.target.get('tag'))
) return;
this.idle = false;
this.element = element;
this.opacity = element.get('opacity');
this.list = element.getParent();
this.clone = this.getClone(event, element);
this.drag = new Drag.Move(this.clone, {
preventDefault: this.options.preventDefault,
snap: this.options.snap,
container: this.options.constrain && this.element.getParent(),
droppables: this.getDroppables(),
onSnap: function(){
event.stop();
this.clone.setStyle('visibility', 'visible');
this.element.set('opacity', this.options.opacity || 0);
this.fireEvent('start', [this.element, this.clone]);
}.bind(this),
onEnter: this.insert.bind(this),
onCancel: this.reset.bind(this),
onComplete: this.end.bind(this)
});
this.clone.inject(this.element, 'before');
this.drag.start(event);
},
end: function(){
this.drag.detach();
this.element.set('opacity', this.opacity);
if (this.effect){
var dim = this.element.getStyles('width', 'height');
var pos = this.clone.computePosition(this.element.getPosition(this.clone.getOffsetParent()));
this.effect.element = this.clone;
this.effect.start({
top: pos.top,
left: pos.left,
width: dim.width,
height: dim.height,
opacity: 0.25
}).chain(this.reset.bind(this));
} else {
this.reset();
}
},
reset: function(){
this.idle = true;
this.clone.destroy();
this.fireEvent('complete', this.element);
},
serialize: function(){
var params = Array.link(arguments, {
modifier: Type.isFunction,
index: function(obj){
return obj != null;
}
});
var serial = this.lists.map(function(list){
return list.getChildren().map(params.modifier || function(element){
return element.get('id');
}, this);
}, this);
var index = params.index;
if (this.lists.length == 1) index = 0;
return (index || index === 0) && index >= 0 && index < this.lists.length ? serial[index] : serial;
}
});
/*
---
script: Request.JSONP.js
name: Request.JSONP
description: Defines Request.JSONP, a class for cross domain javascript via script injection.
license: MIT-style license
authors:
- Aaron Newton
- Guillermo Rauch
- Arian Stolwijk
requires:
- Core/Element
- Core/Request
provides: [Request.JSONP]
...
*/
Request.JSONP = new Class({
Implements: [Chain, Events, Options],
options: {
/*
onRequest: function(src, scriptElement){},
onComplete: function(data){},
onSuccess: function(data){},
onCancel: function(){},
onTimeout: function(){},
onError: function(){}, */
onRequest: function(src){
if (this.options.log && window.console && console.log){
console.log('JSONP retrieving script with url:' + src);
}
},
onError: function(src){
if (this.options.log && window.console && console.warn){
console.warn('JSONP '+ src +' will fail in Internet Explorer, which enforces a 2083 bytes length limit on URIs');
}
},
url: '',
callbackKey: 'callback',
injectScript: document.head,
data: '',
link: 'ignore',
timeout: 0,
log: false
},
initialize: function(options){
this.setOptions(options);
},
send: function(options){
if (!Request.prototype.check.call(this, options)) return this;
this.running = true;
var type = typeOf(options);
if (type == 'string' || type == 'element') options = {data: options};
options = Object.merge(this.options, options || {});
var data = options.data;
switch (typeOf(data)){
case 'element': data = document.id(data).toQueryString(); break;
case 'object': case 'hash': data = Object.toQueryString(data);
}
var index = this.index = Request.JSONP.counter++;
var src = options.url +
(options.url.test('\\?') ? '&' :'?') +
(options.callbackKey) +
'=Request.JSONP.request_map.request_'+ index +
(data ? '&' + data : '');
if (src.length > 2083) this.fireEvent('error', src);
var script = this.getScript(src).inject(options.injectScript);
this.fireEvent('request', [script.get('src'), script]);
Request.JSONP.request_map['request_' + index] = function(){
this.success(arguments, index);
}.bind(this);
if (options.timeout){
(function(){
if (this.running) this.fireEvent('timeout', [script.get('src'), script]).fireEvent('failure').cancel();
}).delay(options.timeout, this);
}
return this;
},
getScript: function(src){
return this.script = new Element('script', {
type: 'text/javascript',
src: src
});
},
success: function(args, index){
if (!this.running) return false;
this.clear()
.fireEvent('complete', args).fireEvent('success', args)
.callChain();
},
cancel: function(){
return this.running ? this.clear().fireEvent('cancel') : this;
},
isRunning: function(){
return !!this.running;
},
clear: function(){
if (this.script) this.script.destroy();
this.running = false;
return this;
}
});
Request.JSONP.counter = 0;
Request.JSONP.request_map = {};
/*
---
script: Request.Queue.js
name: Request.Queue
description: Controls several instances of Request and its variants to run only one request at a time.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Element
- Core/Request
- /Class.Binds
provides: [Request.Queue]
...
*/
Request.Queue = new Class({
Implements: [Options, Events],
Binds: ['attach', 'request', 'complete', 'cancel', 'success', 'failure', 'exception'],
options: {/*
onRequest: function(argsPassedToOnRequest){},
onSuccess: function(argsPassedToOnSuccess){},
onComplete: function(argsPassedToOnComplete){},
onCancel: function(argsPassedToOnCancel){},
onException: function(argsPassedToOnException){},
onFailure: function(argsPassedToOnFailure){},
onEnd: function(){},
*/
stopOnFailure: true,
autoAdvance: true,
concurrent: 1,
requests: {}
},
initialize: function(options){
if (options){
var requests = options.requests;
delete options.requests;
}
this.setOptions(options);
this.requests = {};
this.queue = [];
this.reqBinders = {};
if (requests) this.addRequests(requests);
},
addRequest: function(name, request){
this.requests[name] = request;
this.attach(name, request);
return this;
},
addRequests: function(obj){
Object.each(obj, function(req, name){
this.addRequest(name, req);
}, this);
return this;
},
getName: function(req){
return Object.keyOf(this.requests, req);
},
attach: function(name, req){
if (req._groupSend) return this;
['request', 'complete', 'cancel', 'success', 'failure', 'exception'].each(function(evt){
if (!this.reqBinders[name]) this.reqBinders[name] = {};
this.reqBinders[name][evt] = function(){
this['on' + evt.capitalize()].apply(this, [name, req].append(arguments));
}.bind(this);
req.addEvent(evt, this.reqBinders[name][evt]);
}, this);
req._groupSend = req.send;
req.send = function(options){
this.send(name, options);
return req;
}.bind(this);
return this;
},
removeRequest: function(req){
var name = typeOf(req) == 'object' ? this.getName(req) : req;
if (!name && typeOf(name) != 'string') return this;
req = this.requests[name];
if (!req) return this;
['request', 'complete', 'cancel', 'success', 'failure', 'exception'].each(function(evt){
req.removeEvent(evt, this.reqBinders[name][evt]);
}, this);
req.send = req._groupSend;
delete req._groupSend;
return this;
},
getRunning: function(){
return Object.filter(this.requests, function(r){
return r.running;
});
},
isRunning: function(){
return !!(Object.keys(this.getRunning()).length);
},
send: function(name, options){
var q = function(){
this.requests[name]._groupSend(options);
this.queue.erase(q);
}.bind(this);
q.name = name;
if (Object.keys(this.getRunning()).length >= this.options.concurrent || (this.error && this.options.stopOnFailure)) this.queue.push(q);
else q();
return this;
},
hasNext: function(name){
return (!name) ? !!this.queue.length : !!this.queue.filter(function(q){ return q.name == name; }).length;
},
resume: function(){
this.error = false;
(this.options.concurrent - Object.keys(this.getRunning()).length).times(this.runNext, this);
return this;
},
runNext: function(name){
if (!this.queue.length) return this;
if (!name){
this.queue[0]();
} else {
var found;
this.queue.each(function(q){
if (!found && q.name == name){
found = true;
q();
}
});
}
return this;
},
runAll: function(){
this.queue.each(function(q){
q();
});
return this;
},
clear: function(name){
if (!name){
this.queue.empty();
} else {
this.queue = this.queue.map(function(q){
if (q.name != name) return q;
else return false;
}).filter(function(q){
return q;
});
}
return this;
},
cancel: function(name){
this.requests[name].cancel();
return this;
},
onRequest: function(){
this.fireEvent('request', arguments);
},
onComplete: function(){
this.fireEvent('complete', arguments);
if (!this.queue.length) this.fireEvent('end');
},
onCancel: function(){
if (this.options.autoAdvance && !this.error) this.runNext();
this.fireEvent('cancel', arguments);
},
onSuccess: function(){
if (this.options.autoAdvance && !this.error) this.runNext();
this.fireEvent('success', arguments);
},
onFailure: function(){
this.error = true;
if (!this.options.stopOnFailure && this.options.autoAdvance) this.runNext();
this.fireEvent('failure', arguments);
},
onException: function(){
this.error = true;
if (!this.options.stopOnFailure && this.options.autoAdvance) this.runNext();
this.fireEvent('exception', arguments);
}
});
/*
---
script: Request.Periodical.js
name: Request.Periodical
description: Requests the same URL to pull data from a server but increases the intervals if no data is returned to reduce the load
license: MIT-style license
authors:
- Christoph Pojer
requires:
- Core/Request
- /MooTools.More
provides: [Request.Periodical]
...
*/
Request.implement({
options: {
initialDelay: 5000,
delay: 5000,
limit: 60000
},
startTimer: function(data){
var fn = function(){
if (!this.running) this.send({data: data});
};
this.lastDelay = this.options.initialDelay;
this.timer = fn.delay(this.lastDelay, this);
this.completeCheck = function(response){
clearTimeout(this.timer);
this.lastDelay = (response) ? this.options.delay : (this.lastDelay + this.options.delay).min(this.options.limit);
this.timer = fn.delay(this.lastDelay, this);
};
return this.addEvent('complete', this.completeCheck);
},
stopTimer: function(){
clearTimeout(this.timer);
return this.removeEvent('complete', this.completeCheck);
}
});
/*
---
script: Assets.js
name: Assets
description: Provides methods to dynamically load JavaScript, CSS, and Image files into the document.
license: MIT-style license
authors:
- Valerio Proietti
requires:
- Core/Element.Event
- /MooTools.More
provides: [Assets]
...
*/
var Asset = {
javascript: function(source, properties){
properties = Object.append({
document: document
}, properties);
if (properties.onLoad){
properties.onload = properties.onLoad;
delete properties.onLoad;
}
var script = new Element('script', {src: source, type: 'text/javascript'});
var load = properties.onload || function(){},
doc = properties.document;
delete properties.onload;
delete properties.document;
return script.addEvents({
load: load,
readystatechange: function(){
if (['loaded', 'complete'].contains(this.readyState)) load.call(this);
}
}).set(properties).inject(doc.head);
},
css: function(source, properties){
properties = properties || {};
var onload = properties.onload || properties.onLoad;
if (onload){
properties.events = properties.events || {};
properties.events.load = onload;
delete properties.onload;
delete properties.onLoad;
}
return new Element('link', Object.merge({
rel: 'stylesheet',
media: 'screen',
type: 'text/css',
href: source
}, properties)).inject(document.head);
},
image: function(source, properties){
properties = Object.merge({
onload: function(){},
onabort: function(){},
onerror: function(){}
}, properties);
var image = new Image();
var element = document.id(image) || new Element('img');
['load', 'abort', 'error'].each(function(name){
var type = 'on' + name;
var cap = name.capitalize();
if (properties['on' + cap]){
properties[type] = properties['on' + cap];
delete properties['on' + cap];
}
var event = properties[type];
delete properties[type];
image[type] = function(){
if (!image) return;
if (!element.parentNode){
element.width = image.width;
element.height = image.height;
}
image = image.onload = image.onabort = image.onerror = null;
event.delay(1, element, element);
element.fireEvent(name, element, 1);
};
});
image.src = element.src = source;
if (image && image.complete) image.onload.delay(1);
return element.set(properties);
},
images: function(sources, options){
options = Object.merge({
onComplete: function(){},
onProgress: function(){},
onError: function(){},
properties: {}
}, options);
sources = Array.from(sources);
var counter = 0;
return new Elements(sources.map(function(source, index){
return Asset.image(source, Object.append(options.properties, {
onload: function(){
counter++;
options.onProgress.call(this, counter, index, source);
if (counter == sources.length) options.onComplete();
},
onerror: function(){
counter++;
options.onError.call(this, counter, index, source);
if (counter == sources.length) options.onComplete();
}
}));
}));
}
};
/*
---
script: Color.js
name: Color
description: Class for creating and manipulating colors in JavaScript. Supports HSB -> RGB Conversions and vice versa.
license: MIT-style license
authors:
- Valerio Proietti
requires:
- Core/Array
- Core/String
- Core/Number
- Core/Hash
- Core/Function
provides: [Color]
...
*/
(function(){
var Color = this.Color = new Type('Color', function(color, type){
if (arguments.length >= 3){
type = 'rgb'; color = Array.slice(arguments, 0, 3);
} else if (typeof color == 'string'){
if (color.match(/rgb/)) color = color.rgbToHex().hexToRgb(true);
else if (color.match(/hsb/)) color = color.hsbToRgb();
else color = color.hexToRgb(true);
}
type = type || 'rgb';
switch (type){
case 'hsb':
var old = color;
color = color.hsbToRgb();
color.hsb = old;
break;
case 'hex': color = color.hexToRgb(true); break;
}
color.rgb = color.slice(0, 3);
color.hsb = color.hsb || color.rgbToHsb();
color.hex = color.rgbToHex();
return Object.append(color, this);
});
Color.implement({
mix: function(){
var colors = Array.slice(arguments);
var alpha = (typeOf(colors.getLast()) == 'number') ? colors.pop() : 50;
var rgb = this.slice();
colors.each(function(color){
color = new Color(color);
for (var i = 0; i < 3; i++) rgb[i] = Math.round((rgb[i] / 100 * (100 - alpha)) + (color[i] / 100 * alpha));
});
return new Color(rgb, 'rgb');
},
invert: function(){
return new Color(this.map(function(value){
return 255 - value;
}));
},
setHue: function(value){
return new Color([value, this.hsb[1], this.hsb[2]], 'hsb');
},
setSaturation: function(percent){
return new Color([this.hsb[0], percent, this.hsb[2]], 'hsb');
},
setBrightness: function(percent){
return new Color([this.hsb[0], this.hsb[1], percent], 'hsb');
}
});
var $RGB = function(r, g, b){
return new Color([r, g, b], 'rgb');
};
var $HSB = function(h, s, b){
return new Color([h, s, b], 'hsb');
};
var $HEX = function(hex){
return new Color(hex, 'hex');
};
Array.implement({
rgbToHsb: function(){
var red = this[0],
green = this[1],
blue = this[2],
hue = 0;
var max = Math.max(red, green, blue),
min = Math.min(red, green, blue);
var delta = max - min;
var brightness = max / 255,
saturation = (max != 0) ? delta / max : 0;
if (saturation != 0){
var rr = (max - red) / delta;
var gr = (max - green) / delta;
var br = (max - blue) / delta;
if (red == max) hue = br - gr;
else if (green == max) hue = 2 + rr - br;
else hue = 4 + gr - rr;
hue /= 6;
if (hue < 0) hue++;
}
return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)];
},
hsbToRgb: function(){
var br = Math.round(this[2] / 100 * 255);
if (this[1] == 0){
return [br, br, br];
} else {
var hue = this[0] % 360;
var f = hue % 60;
var p = Math.round((this[2] * (100 - this[1])) / 10000 * 255);
var q = Math.round((this[2] * (6000 - this[1] * f)) / 600000 * 255);
var t = Math.round((this[2] * (6000 - this[1] * (60 - f))) / 600000 * 255);
switch (Math.floor(hue / 60)){
case 0: return [br, t, p];
case 1: return [q, br, p];
case 2: return [p, br, t];
case 3: return [p, q, br];
case 4: return [t, p, br];
case 5: return [br, p, q];
}
}
return false;
}
});
String.implement({
rgbToHsb: function(){
var rgb = this.match(/\d{1,3}/g);
return (rgb) ? rgb.rgbToHsb() : null;
},
hsbToRgb: function(){
var hsb = this.match(/\d{1,3}/g);
return (hsb) ? hsb.hsbToRgb() : null;
}
});
})();
/*
---
script: Group.js
name: Group
description: Class for monitoring collections of events
license: MIT-style license
authors:
- Valerio Proietti
requires:
- Core/Events
- /MooTools.More
provides: [Group]
...
*/
(function(){
this.Group = new Class({
initialize: function(){
this.instances = Array.flatten(arguments);
this.events = {};
this.checker = {};
},
addEvent: function(type, fn){
this.checker[type] = this.checker[type] || {};
this.events[type] = this.events[type] || [];
if (this.events[type].contains(fn)) return false;
else this.events[type].push(fn);
this.instances.each(function(instance, i){
instance.addEvent(type, this.check.pass([type, instance, i], this));
}, this);
return this;
},
check: function(type, instance, i){
this.checker[type][i] = true;
var every = this.instances.every(function(current, j){
return this.checker[type][j] || false;
}, this);
if (!every) return;
this.checker[type] = {};
this.events[type].each(function(event){
event.call(this, this.instances, instance);
}, this);
}
});
})();
/*
---
script: Hash.Cookie.js
name: Hash.Cookie
description: Class for creating, reading, and deleting Cookies in JSON format.
license: MIT-style license
authors:
- Valerio Proietti
- Aaron Newton
requires:
- Core/Cookie
- Core/JSON
- /MooTools.More
- /Hash
provides: [Hash.Cookie]
...
*/
Hash.Cookie = new Class({
Extends: Cookie,
options: {
autoSave: true
},
initialize: function(name, options){
this.parent(name, options);
this.load();
},
save: function(){
var value = JSON.encode(this.hash);
if (!value || value.length > 4096) return false; //cookie would be truncated!
if (value == '{}') this.dispose();
else this.write(value);
return true;
},
load: function(){
this.hash = new Hash(JSON.decode(this.read(), true));
return this;
}
});
Hash.each(Hash.prototype, function(method, name){
if (typeof method == 'function') Hash.Cookie.implement(name, function(){
var value = method.apply(this.hash, arguments);
if (this.options.autoSave) this.save();
return value;
});
});
/*
---
script: HtmlTable.js
name: HtmlTable
description: Builds table elements with methods to add rows.
license: MIT-style license
authors:
- Aaron Newton
requires:
- Core/Options
- Core/Events
- /Class.Occlude
provides: [HtmlTable]
...
*/
var HtmlTable = new Class({
Implements: [Options, Events, Class.Occlude],
options: {
properties: {
cellpadding: 0,
cellspacing: 0,
border: 0
},
rows: [],
headers: [],
footers: []
},
property: 'HtmlTable',
initialize: function(){
var params = Array.link(arguments, {options: Type.isObject, table: Type.isElement});
this.setOptions(params.options);
this.element = params.table || new Element('table', this.options.properties);
if (this.occlude()) return this.occluded;
this.build();
},
build: function(){
this.element.store('HtmlTable', this);
this.body = document.id(this.element.tBodies[0]) || new Element('tbody').inject(this.element);
$$(this.body.rows);
if (this.options.headers.length) this.setHeaders(this.options.headers);
else this.thead = document.id(this.element.tHead);
if (this.thead) this.head = document.id(this.thead.rows[0]);
if (this.options.footers.length) this.setFooters(this.options.footers);
this.tfoot = document.id(this.element.tFoot);
if (this.tfoot) this.foot = document.id(this.tfoot.rows[0]);
this.options.rows.each(function(row){
this.push(row);
}, this);
['adopt', 'inject', 'wraps', 'grab', 'replaces', 'dispose'].each(function(method){
this[method] = this.element[method].bind(this.element);
}, this);
},
toElement: function(){
return this.element;
},
empty: function(){
this.body.empty();
return this;
},
set: function(what, items){
var target = (what == 'headers') ? 'tHead' : 'tFoot';
this[target.toLowerCase()] = (document.id(this.element[target]) || new Element(target.toLowerCase()).inject(this.element, 'top')).empty();
var data = this.push(items, {}, this[target.toLowerCase()], what == 'headers' ? 'th' : 'td');
if (what == 'headers') this.head = document.id(this.thead.rows[0]);
else this.foot = document.id(this.thead.rows[0]);
return data;
},
setHeaders: function(headers){
this.set('headers', headers);
return this;
},
setFooters: function(footers){
this.set('footers', footers);
return this;
},
push: function(row, rowProperties, target, tag){
if (typeOf(row) == "element" && row.get('tag') == 'tr'){
row.inject(target || this.body);
return {
tr: row,
tds: row.getChildren('td')
};
}
var tds = row.map(function(data){
var td = new Element(tag || 'td', data ? data.properties : {}),
type = (data ? data.content : '') || data,
element = document.id(type);
if (typeOf(type) != 'string' && element) td.adopt(element);
else td.set('html', type);
return td;
});
return {
tr: new Element('tr', rowProperties).inject(target || this.body).adopt(tds),
tds: tds
};
}
});
/*
---
script: HtmlTable.Zebra.js
name: HtmlTable.Zebra
description: Builds a stripy table with methods to add rows.
license: MIT-style license
authors:
- Harald Kirschner
- Aaron Newton
requires:
- /HtmlTable
- /Class.refactor
provides: [HtmlTable.Zebra]
...
*/
HtmlTable = Class.refactor(HtmlTable, {
options: {
classZebra: 'table-tr-odd',
zebra: true
},
initialize: function(){
this.previous.apply(this, arguments);
if (this.occluded) return this.occluded;
if (this.options.zebra) this.updateZebras();
},
updateZebras: function(){
Array.each(this.body.rows, this.zebra, this);
},
zebra: function(row, i){
return row[((i % 2) ? 'remove' : 'add')+'Class'](this.options.classZebra);
},
push: function(){
var pushed = this.previous.apply(this, arguments);
if (this.options.zebra) this.updateZebras();
return pushed;
}
});
/*
---
script: HtmlTable.Sort.js
name: HtmlTable.Sort
description: Builds a stripy, sortable table with methods to add rows.
license: MIT-style license
authors:
- Harald Kirschner
- Aaron Newton
requires:
- Core/Hash
- /HtmlTable
- /Class.refactor
- /Element.Delegation
- /String.Extras
- /Date
provides: [HtmlTable.Sort]
...
*/
HtmlTable = Class.refactor(HtmlTable, {
options: {/*
onSort: function(){}, */
sortIndex: 0,
sortReverse: false,
parsers: [],
defaultParser: 'string',
classSortable: 'table-sortable',
classHeadSort: 'table-th-sort',
classHeadSortRev: 'table-th-sort-rev',
classNoSort: 'table-th-nosort',
classGroupHead: 'table-tr-group-head',
classGroup: 'table-tr-group',
classCellSort: 'table-td-sort',
classSortSpan: 'table-th-sort-span',
sortable: false
},
initialize: function (){
this.previous.apply(this, arguments);
if (this.occluded) return this.occluded;
this.sorted = {index: null, dir: 1};
this.bound = {
headClick: this.headClick.bind(this)
};
this.sortSpans = new Elements();
if (this.options.sortable){
this.enableSort();
if (this.options.sortIndex != null) this.sort(this.options.sortIndex, this.options.sortReverse);
}
},
attachSorts: function(attach){
this.element.removeEvents('click:relay(th)');
this.element[attach !== false ? 'addEvent' : 'removeEvent']('click:relay(th)', this.bound.headClick);
},
setHeaders: function(){
this.previous.apply(this, arguments);
if (this.sortEnabled) this.detectParsers();
},
detectParsers: function(force){
if (!this.head) return;
var parsers = this.options.parsers,
rows = this.body.rows;
// auto-detect
this.parsers = $$(this.head.cells).map(function(cell, index){
if (!force && (cell.hasClass(this.options.classNoSort) || cell.retrieve('htmltable-parser'))) return cell.retrieve('htmltable-parser');
var thDiv = new Element('div');
Array.each(cell.childNodes, function(node){
thDiv.adopt(node);
});
thDiv.inject(cell);
var sortSpan = new Element('span', {'html': ' ', 'class': this.options.classSortSpan}).inject(thDiv, 'top');
this.sortSpans.push(sortSpan);
var parser = parsers[index],
cancel;
switch (typeOf(parser)){
case 'function': parser = {convert: parser}; cancel = true; break;
case 'string': parser = parser; cancel = true; break;
}
if (!cancel){
Object.some(HtmlTable.Parsers, function(current){
var match = current.match;
if (!match) return false;
for (var i = 0, j = rows.length; i < j; i++){
var cell = document.id(rows[i].cells[index]);
var text = cell ? cell.get('html').clean() : '';
if (text && match.test(text)){
parser = current;
return true;
}
}
});
}
if (!parser) parser = this.options.defaultParser;
cell.store('htmltable-parser', parser);
return parser;
}, this);
},
headClick: function(event, el){
if (!this.head || el.hasClass(this.options.classNoSort)) return;
var index = Array.indexOf(this.head.cells, el);
this.sort(index);
return false;
},
sort: function(index, reverse, pre){
if (!this.head) return;
var classCellSort = this.options.classCellSort;
var classGroup = this.options.classGroup,
classGroupHead = this.options.classGroupHead;
if (!pre){
if (index != null){
if (this.sorted.index == index){
this.sorted.reverse = !(this.sorted.reverse);
} else {
if (this.sorted.index != null){
this.sorted.reverse = false;
this.head.cells[this.sorted.index].removeClass(this.options.classHeadSort).removeClass(this.options.classHeadSortRev);
} else {
this.sorted.reverse = true;
}
this.sorted.index = index;
}
} else {
index = this.sorted.index;
}
if (reverse != null) this.sorted.reverse = reverse;
var head = document.id(this.head.cells[index]);
if (head){
head.addClass(this.options.classHeadSort);
if (this.sorted.reverse) head.addClass(this.options.classHeadSortRev);
else head.removeClass(this.options.classHeadSortRev);
}
this.body.getElements('td').removeClass(this.options.classCellSort);
}
var parser = this.parsers[index];
if (typeOf(parser) == 'string') parser = HtmlTable.Parsers[parser];
if (!parser) return;
if (!Browser.ie){
var rel = this.body.getParent();
this.body.dispose();
}
var data = Array.map(this.body.rows, function(row, i){
var value = parser.convert.call(document.id(row.cells[index]));
return {
position: i,
value: value,
toString: function(){
return value.toString();
}
};
}, this);
data.reverse(true);
data.sort(function(a, b){
if (a.value === b.value) return 0;
return a.value > b.value ? 1 : -1;
});
if (!this.sorted.reverse) data.reverse(true);
var i = data.length, body = this.body;
var j, position, entry, group;
while (i){
var item = data[--i];
position = item.position;
var row = body.rows[position];
if (row.disabled) continue;
if (!pre){
if (group === item.value){
row.removeClass(classGroupHead).addClass(classGroup);
} else {
group = item.value;
row.removeClass(classGroup).addClass(classGroupHead);
}
if (this.options.zebra) this.zebra(row, i);
row.cells[index].addClass(classCellSort);
}
body.appendChild(row);
for (j = 0; j < i; j++){
if (data[j].position > position) data[j].position--;
}
};
data = null;
if (rel) rel.grab(body);
return this.fireEvent('sort', [body, index]);
},
reSort: function(){
if (this.sortEnabled) this.sort.call(this, this.sorted.index, this.sorted.reverse);
return this;
},
enableSort: function(){
this.element.addClass(this.options.classSortable);
this.attachSorts(true);
this.detectParsers();
this.sortEnabled = true;
return this;
},
disableSort: function(){
this.element.removeClass(this.options.classSortable);
this.attachSorts(false);
this.sortSpans.each(function(span){ span.destroy(); });
this.sortSpans.empty();
this.sortEnabled = false;
return this;
}
});
HtmlTable.Parsers = {
'date': {
match: /^\d{2}[-\/ ]\d{2}[-\/ ]\d{2,4}$/,
convert: function(){
var d = Date.parse(this.get('text').stripTags());
return (typeOf(d) == 'date') ? d.format('db') : '';
},
type: 'date'
},
'input-checked': {
match: / type="(radio|checkbox)" /,
convert: function(){
return this.getElement('input').checked;
}
},
'input-value': {
match: /<input/,
convert: function(){
return this.getElement('input').value;
}
},
'number': {
match: /^\d+[^\d.,]*$/,
convert: function(){
return this.get('text').stripTags().toInt();
},
number: true
},
'numberLax': {
match: /^[^\d]+\d+$/,
convert: function(){
return this.get('text').replace(/[^-?^0-9]/, '').stripTags().toInt();
},
number: true
},
'float': {
match: /^[\d]+\.[\d]+/,
convert: function(){
return this.get('text').replace(/[^-?^\d.]/, '').stripTags().toFloat();
},
number: true
},
'floatLax': {
match: /^[^\d]+[\d]+\.[\d]+$/,
convert: function(){
return this.get('text').replace(/[^-?^\d.]/, '').stripTags();
},
number: true
},
'string': {
match: null,
convert: function(){
return this.get('text').stripTags();
}
},
'title': {
match: null,
convert: function(){
return this.title;
}
}
};
HtmlTable.defineParsers = function(parsers){
HtmlTable.Parsers = Object.append(HtmlTable.Parsers, parsers);
};
/*
---
name: Element.Event.Pseudos.Keys
description: Adds functionallity fire events if certain keycombinations are pressed
license: MIT-style license
authors:
- Arian Stolwijk
requires: [Element.Event.Pseudos]
provides: [Element.Event.Pseudos.Keys]
...
*/
(function(){
var keysStoreKey = '$moo:keys-pressed',
keysKeyupStoreKey = '$moo:keys-keyup';
Event.definePseudo('keys', function(split, fn, args){
var event = args[0],
keys = [],
pressed = this.retrieve(keysStoreKey, []);
keys.append(split.value.replace('++', function(){
keys.push('+'); // shift++ and shift+++a
return '';
}).split('+'));
pressed.include(event.key);
if (keys.every(function(key){
return pressed.contains(key);
})) fn.apply(this, args);
this.store(keysStoreKey, pressed);
if (!this.retrieve(keysKeyupStoreKey)){
var keyup = function(event){
(function(){
pressed = this.retrieve(keysStoreKey, []).erase(event.key);
this.store(keysStoreKey, pressed);
}).delay(0, this); // Fix for IE
};
this.store(keysKeyupStoreKey, keyup).addEvent('keyup', keyup);
}
});
Object.append(Event.Keys, {
'shift': 16,
'control': 17,
'alt': 18,
'capslock': 20,
'pageup': 33,
'pagedown': 34,
'end': 35,
'home': 36,
'numlock': 144,
'scrolllock': 145,
';': 186,
'=': 187,
',': 188,
'-': Browser.firefox ? 109 : 189,
'.': 190,
'/': 191,
'`': 192,
'[': 219,
'\\': 220,
']': 221,
"'": 222,
'+': 107
});
})();
/*
---
script: Keyboard.js
name: Keyboard
description: KeyboardEvents used to intercept events on a class for keyboard and format modifiers in a specific order so as to make alt+shift+c the same as shift+alt+c.
license: MIT-style license
authors:
- Perrin Westrich
- Aaron Newton
- Scott Kyle
requires:
- Core/Events
- Core/Options
- Core/Element.Event
- Element.Event.Pseudos.Keys
provides: [Keyboard]
...
*/
(function(){
var Keyboard = this.Keyboard = new Class({
Extends: Events,
Implements: [Options],
options: {/*
onActivate: function(){},
onDeactivate: function(){},*/
defaultEventType: 'keydown',
active: false,
manager: null,
events: {},
nonParsedEvents: ['activate', 'deactivate', 'onactivate', 'ondeactivate', 'changed', 'onchanged']
},
initialize: function(options){
if (options && options.manager){
this.manager = options.manager;
delete options.manager;
}
this.setOptions(options);
this.setup();
},
setup: function(){
this.addEvents(this.options.events);
//if this is the root manager, nothing manages it
if (Keyboard.manager && !this.manager) Keyboard.manager.manage(this);
if (this.options.active) this.activate();
},
handle: function(event, type){
//Keyboard.stop(event) prevents key propagation
if (event.preventKeyboardPropagation) return;
var bubbles = !!this.manager;
if (bubbles && this.activeKB){
this.activeKB.handle(event, type);
if (event.preventKeyboardPropagation) return;
}
this.fireEvent(type, event);
if (!bubbles && this.activeKB) this.activeKB.handle(event, type);
},
addEvent: function(type, fn, internal){
return this.parent(Keyboard.parse(type, this.options.defaultEventType, this.options.nonParsedEvents), fn, internal);
},
removeEvent: function(type, fn){
return this.parent(Keyboard.parse(type, this.options.defaultEventType, this.options.nonParsedEvents), fn);
},
toggleActive: function(){
return this[this.isActive() ? 'deactivate' : 'activate']();
},
activate: function(instance){
if (instance){
if (instance.isActive()) return this;
//if we're stealing focus, store the last keyboard to have it so the relinquish command works
if (this.activeKB && instance != this.activeKB){
this.previous = this.activeKB;
this.previous.fireEvent('deactivate');
}
//if we're enabling a child, assign it so that events are now passed to it
this.activeKB = instance.fireEvent('activate');
Keyboard.manager.fireEvent('changed');
} else if (this.manager){
//else we're enabling ourselves, we must ask our parent to do it for us
this.manager.activate(this);
}
return this;
},
isActive: function(){
return this.manager ? (this.manager.activeKB == this) : (Keyboard.manager == this);
},
deactivate: function(instance){
if (instance){
if (instance === this.activeKB){
this.activeKB = null;
instance.fireEvent('deactivate');
Keyboard.manager.fireEvent('changed');
}
} else if (this.manager){
this.manager.deactivate(this);
}
return this;
},
relinquish: function(){
if (this.isActive() && this.manager && this.manager.previous) this.manager.activate(this.manager.previous);
},
//management logic
manage: function(instance){
if (instance.manager && instance.manager != Keyboard.manager && this != Keyboard.manager) instance.manager.drop(instance);
this.instances.push(instance);
instance.manager = this;
if (!this.activeKB) this.activate(instance);
},
_disable: function(instance){
if (this.activeKB == instance) this.activeKB = null;
},
drop: function(instance){
this._disable(instance);
this.instances.erase(instance);
Keyboard.manager.manage(instance);
if (this.activeKB == instance && this.previous && this.instances.contains(this.previous)) this.activate(this.previous);
},
instances: [],
trace: function(){
Keyboard.trace(this);
},
each: function(fn){
Keyboard.each(this, fn);
}
});
var parsed = {};
var modifiers = ['shift', 'control', 'alt', 'meta'];
var regex = /^(?:shift|control|ctrl|alt|meta)$/;
Keyboard.parse = function(type, eventType, ignore){
if (ignore && ignore.contains(type.toLowerCase())) return type;
type = type.toLowerCase().replace(/^(keyup|keydown):/, function($0, $1){
eventType = $1;
return '';
});
if (!parsed[type]){
var key, mods = {};
type.split('+').each(function(part){
if (regex.test(part)) mods[part] = true;
else key = part;
});
mods.control = mods.control || mods.ctrl; // allow both control and ctrl
var keys = [];
modifiers.each(function(mod){
if (mods[mod]) keys.push(mod);
});
if (key) keys.push(key);
parsed[type] = keys.join('+');
}
return eventType + ':keys(' + parsed[type] + ')';
};
Keyboard.each = function(keyboard, fn){
var current = keyboard || Keyboard.manager;
while (current){
fn.run(current);
current = current.activeKB;
}
};
Keyboard.stop = function(event){
event.preventKeyboardPropagation = true;
};
Keyboard.manager = new Keyboard({
active: true
});
Keyboard.trace = function(keyboard){
keyboard = keyboard || Keyboard.manager;
var hasConsole = window.console && console.log;
if (hasConsole) console.log('the following items have focus: ');
Keyboard.each(keyboard, function(current){
if (hasConsole) console.log(document.id(current.widget) || current.wiget || current);
});
};
var handler = function(event){
var keys = [];
modifiers.each(function(mod){
if (event[mod]) keys.push(mod);
});
if (!regex.test(event.key)) keys.push(event.key);
Keyboard.manager.handle(event, event.type + ':keys(' + keys.join('+') + ')');
};
document.addEvents({
'keyup': handler,
'keydown': handler
});
})();
/*
---
script: Keyboard.Extras.js
name: Keyboard.Extras
description: Enhances Keyboard by adding the ability to name and describe keyboard shortcuts, and the ability to grab shortcuts by name and bind the shortcut to different keys.
license: MIT-style license
authors:
- Perrin Westrich
requires:
- /Keyboard
- /MooTools.More
provides: [Keyboard.Extras]
...
*/
Keyboard.prototype.options.nonParsedEvents.combine(['rebound', 'onrebound']);
Keyboard.implement({
/*
shortcut should be in the format of:
{
'keys': 'shift+s', // the default to add as an event.
'description': 'blah blah blah', // a brief description of the functionality.
'handler': function(){} // the event handler to run when keys are pressed.
}
*/
addShortcut: function(name, shortcut){
this.shortcuts = this.shortcuts || [];
this.shortcutIndex = this.shortcutIndex || {};
shortcut.getKeyboard = Function.from(this);
shortcut.name = name;
this.shortcutIndex[name] = shortcut;
this.shortcuts.push(shortcut);
if (shortcut.keys) this.addEvent(shortcut.keys, shortcut.handler);
return this;
},
addShortcuts: function(obj){
for (var name in obj) this.addShortcut(name, obj[name]);
return this;
},
removeShortcut: function(name){
var shortcut = this.getShortcut(name);
if (shortcut && shortcut.keys){
this.removeEvent(shortcut.keys, shortcut.handler);
delete this.shortcutIndex[name];
this.shortcuts.erase(shortcut);
}
return this;
},
removeShortcuts: function(names){
names.each(this.removeShortcut, this);
return this;
},
getShortcuts: function(){
return this.shortcuts || [];
},
getShortcut: function(name){
return (this.shortcutIndex || {})[name];
}
});
Keyboard.rebind = function(newKeys, shortcuts){
Array.from(shortcuts).each(function(shortcut){
shortcut.getKeyboard().removeEvent(shortcut.keys, shortcut.handler);
shortcut.getKeyboard().addEvent(newKeys, shortcut.handler);
shortcut.keys = newKeys;
shortcut.getKeyboard().fireEvent('rebound');
});
};
Keyboard.getActiveShortcuts = function(keyboard){
var activeKBS = [], activeSCS = [];
Keyboard.each(keyboard, [].push.bind(activeKBS));
activeKBS.each(function(kb){ activeSCS.extend(kb.getShortcuts()); });
return activeSCS;
};
Keyboard.getShortcut = function(name, keyboard, opts){
opts = opts || {};
var shortcuts = opts.many ? [] : null,
set = opts.many ? function(kb){
var shortcut = kb.getShortcut(name);
if (shortcut) shortcuts.push(shortcut);
} : function(kb){
if (!shortcuts) shortcuts = kb.getShortcut(name);
};
Keyboard.each(keyboard, set);
return shortcuts;
};
Keyboard.getShortcuts = function(name, keyboard){
return Keyboard.getShortcut(name, keyboard, { many: true });
};
/*
---
script: HtmlTable.Select.js
name: HtmlTable.Select
description: Builds a stripy, sortable table with methods to add rows. Rows can be selected with the mouse or keyboard navigation.
license: MIT-style license
authors:
- Harald Kirschner
- Aaron Newton
requires:
- /Keyboard
- /Keyboard.Extras
- /HtmlTable
- /Class.refactor
- /Element.Delegation
- /Element.Shortcuts
provides: [HtmlTable.Select]
...
*/
HtmlTable = Class.refactor(HtmlTable, {
options: {
/*onRowFocus: function(){},
onRowUnfocus: function(){},*/
useKeyboard: true,
classRowSelected: 'table-tr-selected',
classRowHovered: 'table-tr-hovered',
classSelectable: 'table-selectable',
shiftForMultiSelect: true,
allowMultiSelect: true,
selectable: false
},
initialize: function(){
this.previous.apply(this, arguments);
if (this.occluded) return this.occluded;
this._selectedRows = new Elements();
this._bound = {
mouseleave: this._mouseleave.bind(this),
clickRow: this._clickRow.bind(this)
};
if (this.options.selectable) this.enableSelect();
},
enableSelect: function(){
this._selectEnabled = true;
this._attachSelects();
this.element.addClass(this.options.classSelectable);
},
disableSelect: function(){
this._selectEnabled = false;
this._attachSelects(false);
this.element.removeClass(this.options.classSelectable);
},
push: function(){
var ret = this.previous.apply(this, arguments);
this._updateSelects();
return ret;
},
isSelected: function(row){
return this._selectedRows.contains(row);
},
toggleRow: function(row){
return this[(this.isSelected(row) ? 'de' : '') + 'selectRow'](row);
},
selectRow: function(row, _nocheck){
//private variable _nocheck: boolean whether or not to confirm the row is in the table body
//added here for optimization when selecting ranges
if (this.isSelected(row) || (!_nocheck && !this.body.getChildren().contains(row))) return;
if (!this.options.allowMultiSelect) this.selectNone();
if (!this.isSelected(row)){
this._selectedRows.push(row);
row.addClass(this.options.classRowSelected);
this.fireEvent('rowFocus', [row, this._selectedRows]);
}
this._focused = row;
document.clearSelection();
return this;
},
deselectRow: function(row, _nocheck){
if (!this.isSelected(row) || (!_nocheck && !this.body.getChildren().contains(row))) return;
this._selectedRows = new Elements(Array.from(this._selectedRows).erase(row));
row.removeClass(this.options.classRowSelected);
this.fireEvent('rowUnfocus', [row, this._selectedRows]);
return this;
},
selectAll: function(selectNone){
if (!selectNone && !this.options.allowMultiSelect) return;
this.selectRange(0, this.body.rows.length, selectNone);
return this;
},
selectNone: function(){
return this.selectAll(true);
},
selectRange: function(startRow, endRow, _deselect){
if (!this.options.allowMultiSelect && !_deselect) return;
var method = _deselect ? 'deselectRow' : 'selectRow',
rows = Array.clone(this.body.rows);
if (typeOf(startRow) == 'element') startRow = rows.indexOf(startRow);
if (typeOf(endRow) == 'element') endRow = rows.indexOf(endRow);
endRow = endRow < rows.length - 1 ? endRow : rows.length - 1;
if (endRow < startRow){
var tmp = startRow;
startRow = endRow;
endRow = tmp;
}
for(var i = startRow; i <= endRow; i++) this[method](rows[i], true);
return this;
},
deselectRange: function(startRow, endRow){
this.selectRange(startRow, endRow, true);
},
/*
Private methods:
*/
_enterRow: function(row){
if (this._hovered) this._hovered = this._leaveRow(this._hovered);
this._hovered = row.addClass(this.options.classRowHovered);
},
_leaveRow: function(row){
row.removeClass(this.options.classRowHovered);
},
_updateSelects: function(){
Array.each(this.body.rows, function(row){
var binders = row.retrieve('binders');
if ((binders && this._selectEnabled) || (!binders && !this._selectEnabled)) return;
if (!binders){
binders = {
mouseenter: this._enterRow.pass([row], this),
mouseleave: this._leaveRow.pass([row], this)
};
row.store('binders', binders).addEvents(binders);
} else {
row.removeEvents(binders);
}
}, this);
},
_shiftFocus: function(offset, event){
if (!this._focused) return this.selectRow(this.body.rows[0], event);
var to = this._getRowByOffset(offset);
if (to === null || this._focused == this.body.rows[to]) return this;
this.toggleRow(this.body.rows[to], event);
},
_clickRow: function(event, row){
var selecting = (event.shift || event.meta || event.control) && this.options.shiftForMultiSelect;
if (!selecting && !(event.rightClick && this.isSelected(row) && this.options.allowMultiSelect)) this.selectNone();
if (event.rightClick) this.selectRow(row);
else this.toggleRow(row);
if (event.shift){
this.selectRange(this._rangeStart || this.body.rows[0], row, this._rangeStart ? !this.isSelected(row) : true);
this._focused = row;
}
this._rangeStart = row;
},
_getRowByOffset: function(offset){
if (!this._focused) return 0;
var rows = Array.clone(this.body.rows),
index = rows.indexOf(this._focused) + offset;
if (index < 0) index = null;
if (index >= rows.length) index = null;
return index;
},
_attachSelects: function(attach){
attach = attach != null ? attach : true;
var method = attach ? 'addEvents' : 'removeEvents';
this.element[method]({
mouseleave: this._bound.mouseleave
});
this.body[method]({
'click:relay(tr)': this._bound.clickRow,
'contextmenu:relay(tr)': this._bound.clickRow
});
if (this.options.useKeyboard || this.keyboard){
if (!this.keyboard){
var timer, held;
var move = function(offset){
var mover = function(e){
clearTimeout(timer);
e.preventDefault();
var to = this.body.rows[this._getRowByOffset(offset)];
if (e.shift && to && this.isSelected(to)){
this.deselectRow(this._focused);
this._focused = to;
} else {
if (to && (!this.options.allowMultiSelect || !e.shift)){
this.selectNone();
}
this._shiftFocus(offset, e);
}
if (held){
timer = mover.delay(100, this, e);
} else {
timer = (function(){
held = true;
mover(e);
}).delay(400);
}
}.bind(this);
return mover;
}.bind(this);
var clear = function(){
clearTimeout(timer);
held = false;
};
this.keyboard = new Keyboard({
events: {
'keydown:shift+up': move(-1),
'keydown:shift+down': move(1),
'keyup:shift+up': clear,
'keyup:shift+down': clear,
'keyup:up': clear,
'keyup:down': clear
},
active: true
});
var shiftHint = '';
if (this.options.allowMultiSelect && this.options.shiftForMultiSelect && this.options.useKeyboard){
shiftHint = " (Shift multi-selects).";
}
this.keyboard.addShortcuts({
'Select Previous Row': {
keys: 'up',
shortcut: 'up arrow',
handler: move(-1),
description: 'Select the previous row in the table.' + shiftHint
},
'Select Next Row': {
keys: 'down',
shortcut: 'down arrow',
handler: move(1),
description: 'Select the next row in the table.' + shiftHint
}
});
}
this.keyboard[attach ? 'activate' : 'deactivate']();
}
this._updateSelects();
},
_mouseleave: function(){
if (this._hovered) this._leaveRow(this._hovered);
}
});
/*
---
script: Scroller.js
name: Scroller
description: Class which scrolls the contents of any Element (including the window) when the mouse reaches the Element's boundaries.
license: MIT-style license
authors:
- Valerio Proietti
requires:
- Core/Events
- Core/Options
- Core/Element.Event
- Core/Element.Dimensions
provides: [Scroller]
...
*/
var Scroller = new Class({
Implements: [Events, Options],
options: {
area: 20,
velocity: 1,
onChange: function(x, y){
this.element.scrollTo(x, y);
},
fps: 50
},
initialize: function(element, options){
this.setOptions(options);
this.element = document.id(element);
this.docBody = document.id(this.element.getDocument().body);
this.listener = (typeOf(this.element) != 'element') ? this.docBody : this.element;
this.timer = null;
this.bound = {
attach: this.attach.bind(this),
detach: this.detach.bind(this),
getCoords: this.getCoords.bind(this)
};
},
start: function(){
this.listener.addEvents({
mouseenter: this.bound.attach,
mouseleave: this.bound.detach
});
return this;
},
stop: function(){
this.listener.removeEvents({
mouseenter: this.bound.attach,
mouseleave: this.bound.detach
});
this.detach();
this.timer = clearInterval(this.timer);
return this;
},
attach: function(){
this.listener.addEvent('mousemove', this.bound.getCoords);
},
detach: function(){
this.listener.removeEvent('mousemove', this.bound.getCoords);
this.timer = clearInterval(this.timer);
},
getCoords: function(event){
this.page = (this.listener.get('tag') == 'body') ? event.client : event.page;
if (!this.timer) this.timer = this.scroll.periodical(Math.round(1000 / this.options.fps), this);
},
scroll: function(){
var size = this.element.getSize(),
scroll = this.element.getScroll(),
pos = this.element != this.docBody ? this.element.getOffsets() : {x: 0, y:0},
scrollSize = this.element.getScrollSize(),
change = {x: 0, y: 0},
top = this.options.area.top || this.options.area,
bottom = this.options.area.bottom || this.options.area;
for (var z in this.page){
if (this.page[z] < (top + pos[z]) && scroll[z] != 0){
change[z] = (this.page[z] - top - pos[z]) * this.options.velocity;
} else if (this.page[z] + bottom > (size[z] + pos[z]) && scroll[z] + size[z] != scrollSize[z]){
change[z] = (this.page[z] - size[z] + bottom - pos[z]) * this.options.velocity;
}
change[z] = change[z].round();
}
if (change.y || change.x) this.fireEvent('change', [scroll.x + change.x, scroll.y + change.y]);
}
});
/*
---
script: Tips.js
name: Tips
description: Class for creating nice tips that follow the mouse cursor when hovering an element.
license: MIT-style license
authors:
- Valerio Proietti
- Christoph Pojer
- Luis Merino
requires:
- Core/Options
- Core/Events
- Core/Element.Event
- Core/Element.Style
- Core/Element.Dimensions
- /MooTools.More
provides: [Tips]
...
*/
(function(){
var read = function(option, element){
return (option) ? (typeOf(option) == 'function' ? option(element) : element.get(option)) : '';
};
this.Tips = new Class({
Implements: [Events, Options],
options: {/*
onAttach: function(element){},
onDetach: function(element){},
onBound: function(coords){},*/
onShow: function(){
this.tip.setStyle('display', 'block');
},
onHide: function(){
this.tip.setStyle('display', 'none');
},
title: 'title',
text: function(element){
return element.get('rel') || element.get('href');
},
showDelay: 100,
hideDelay: 100,
className: 'tip-wrap',
offset: {x: 16, y: 16},
windowPadding: {x:0, y:0},
fixed: false
},
initialize: function(){
var params = Array.link(arguments, {
options: Type.isObject,
elements: function(obj){
return obj != null;
}
});
this.setOptions(params.options);
if (params.elements) this.attach(params.elements);
this.container = new Element('div', {'class': 'tip'});
},
toElement: function(){
if (this.tip) return this.tip;
this.tip = new Element('div', {
'class': this.options.className,
styles: {
position: 'absolute',
top: 0,
left: 0
}
}).adopt(
new Element('div', {'class': 'tip-top'}),
this.container,
new Element('div', {'class': 'tip-bottom'})
);
return this.tip;
},
attach: function(elements){
$$(elements).each(function(element){
var title = read(this.options.title, element),
text = read(this.options.text, element);
element.set('title', '').store('tip:native', title).retrieve('tip:title', title);
element.retrieve('tip:text', text);
this.fireEvent('attach', [element]);
var events = ['enter', 'leave'];
if (!this.options.fixed) events.push('move');
events.each(function(value){
var event = element.retrieve('tip:' + value);
if (!event) event = function(event){
this['element' + value.capitalize()].apply(this, [event, element]);
}.bind(this);
element.store('tip:' + value, event).addEvent('mouse' + value, event);
}, this);
}, this);
return this;
},
detach: function(elements){
$$(elements).each(function(element){
['enter', 'leave', 'move'].each(function(value){
element.removeEvent('mouse' + value, element.retrieve('tip:' + value)).eliminate('tip:' + value);
});
this.fireEvent('detach', [element]);
if (this.options.title == 'title'){ // This is necessary to check if we can revert the title
var original = element.retrieve('tip:native');
if (original) element.set('title', original);
}
}, this);
return this;
},
elementEnter: function(event, element){
this.container.empty();
['title', 'text'].each(function(value){
var content = element.retrieve('tip:' + value);
if (content) this.fill(new Element('div', {'class': 'tip-' + value}).inject(this.container), content);
}, this);
clearTimeout(this.timer);
this.timer = (function(){
this.show(element);
this.position((this.options.fixed) ? {page: element.getPosition()} : event);
}).delay(this.options.showDelay, this);
},
elementLeave: function(event, element){
clearTimeout(this.timer);
this.timer = this.hide.delay(this.options.hideDelay, this, element);
this.fireForParent(event, element);
},
fireForParent: function(event, element){
element = element.getParent();
if (!element || element == document.body) return;
if (element.retrieve('tip:enter')) element.fireEvent('mouseenter', event);
else this.fireForParent(event, element);
},
elementMove: function(event, element){
this.position(event);
},
position: function(event){
if (!this.tip) document.id(this);
var size = window.getSize(), scroll = window.getScroll(),
tip = {x: this.tip.offsetWidth, y: this.tip.offsetHeight},
props = {x: 'left', y: 'top'},
bounds = {y: false, x2: false, y2: false, x: false},
obj = {};
for (var z in props){
obj[props[z]] = event.page[z] + this.options.offset[z];
if (obj[props[z]] < 0) bounds[z] = true;
if ((obj[props[z]] + tip[z] - scroll[z]) > size[z] - this.options.windowPadding[z]){
obj[props[z]] = event.page[z] - this.options.offset[z] - tip[z];
bounds[z+'2'] = true;
}
}
this.fireEvent('bound', bounds);
this.tip.setStyles(obj);
},
fill: function(element, contents){
if (typeof contents == 'string') element.set('html', contents);
else element.adopt(contents);
},
show: function(element){
if (!this.tip) document.id(this);
if (!this.tip.getParent()) this.tip.inject(document.body);
this.fireEvent('show', [this.tip, element]);
},
hide: function(element){
if (!this.tip) document.id(this);
this.fireEvent('hide', [this.tip, element]);
}
});
})();
|
import tokenize from './tokenizer';
const assert = require('assert');
const inspect = require('util').inspect;
const tests = [
{
jacks: [
'if (x < 153) { let city = "Paris"; }',
'if (x<153) // comment\n{ let city = "Paris"; }',
'if (x < 153) { /* comment */ let city = "Paris"; }',
'if (x < 153) { /* comment */ let city /* other comment */ = "Paris"; }',
'if (x < 153) { /* comment \n comment continues */ let city = "Paris"; }',
'/** doc */ if (x < 153) { let city = "Paris"; }',
'if ( x\n< 153 \r) { let \r\ncity = "Paris" ; \n } \r'
],
tokens: [
{type: 'keyword', value: 'if'},
{type: 'symbol', value: '('},
{type: 'identifier', value: 'x'},
{type: 'symbol', value: '<'},
{type: 'integerConstant', value: 153},
{type: 'symbol', value: ')'},
{type: 'symbol', value: '{'},
{type: 'keyword', value: 'let'},
{type: 'identifier', value: 'city'},
{type: 'symbol', value: '='},
{type: 'stringConstant', value: 'Paris'},
{type: 'symbol', value: ';'},
{type: 'symbol', value: '}'}
]
}
];
for (const test of tests) {
for (const jack of test.jacks) {
const tokens = tokenize(jack);
assert.deepStrictEqual(tokens, test.tokens, `For jack:\n${jack}\n` +
`Expected tokens to be:\n${inspect(test.tokens)}\n` +
`But were:\n${inspect(tokens)}`);
}
}
console.log('Tests passed.');
|
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var config = require('./env/' + process.env.NODE_ENV);
module.exports = config;
|
'use strict';
var chai = require('chai');
var chaiHttp = require('chai-http');
chai.use(chaiHttp);
var expect = chai.expect;
process.env.MONGO_URL = 'mongodb://localhost/user_test';
require(__dirname + '/../server');
var mongoose = require('mongoose');
var User = require(__dirname + '/../models/user');
var host = 'localhost:3000/fl';
describe('user login/signup test', function() {
var testUser = '';
after(function(done) {
mongoose.connection.db.dropDatabase(function() {
done();
});
});
it('should create a new user', function(done) {
chai.request(host)
.post('/signup')
.send({username: 'test', password: 'user', email: 'testemail', invitationCode: process.env.INVITATION_CODE})
.end(function(err, res) {
testUser = res.body.user.token;
expect(err).to.eql(null);
expect(res.body.user.username).to.eql('test');
done();
});
});
it('should log the user out', function(done) {
chai.request(host)
.get('/signout')
.set('authorization', 'BEARER ' + testUser)
.end(function(err, res) {
expect(err).to.eql(null);
done();
});
});
it('should log into an existing user', function(done) {
chai.request(host)
.get('/signin')
.auth('test', 'user')
.end(function(err, res) {
expect(err).to.eql(null);
expect(res.body.user.token).to.be.a('string');
done();
});
});
});
|
define(function(require) {
var zrUtil = require('zrender/core/util');
var graphic = require('../../util/graphic');
var DataDiffer = require('../../data/DataDiffer');
var helper = require('./helper');
var Breadcrumb = require('./Breadcrumb');
var RoamController = require('../../component/helper/RoamController');
var BoundingRect = require('zrender/core/BoundingRect');
var matrix = require('zrender/core/matrix');
var animationUtil = require('../../util/animation');
var bind = zrUtil.bind;
var Group = graphic.Group;
var Rect = graphic.Rect;
var each = zrUtil.each;
var DRAG_THRESHOLD = 3;
var PATH_LABEL_NOAMAL = ['label', 'normal'];
var PATH_LABEL_EMPHASIS = ['label', 'emphasis'];
var PATH_UPPERLABEL_NORMAL = ['upperLabel', 'normal'];
var PATH_UPPERLABEL_EMPHASIS = ['upperLabel', 'emphasis'];
var Z_BASE = 10; // Should bigger than every z.
var Z_BG = 1;
var Z_CONTENT = 2;
return require('../../echarts').extendChartView({
type: 'treemap',
/**
* @override
*/
init: function (o, api) {
/**
* @private
* @type {module:zrender/container/Group}
*/
this._containerGroup;
/**
* @private
* @type {Object.<string, Array.<module:zrender/container/Group>>}
*/
this._storage = createStorage();
/**
* @private
* @type {module:echarts/data/Tree}
*/
this._oldTree;
/**
* @private
* @type {module:echarts/chart/treemap/Breadcrumb}
*/
this._breadcrumb;
/**
* @private
* @type {module:echarts/component/helper/RoamController}
*/
this._controller;
/**
* 'ready', 'animating'
* @private
*/
this._state = 'ready';
/**
* @private
* @type {boolean}
*/
this._mayClick;
},
/**
* @override
*/
render: function (seriesModel, ecModel, api, payload) {
var models = ecModel.findComponents({
mainType: 'series', subType: 'treemap', query: payload
});
if (zrUtil.indexOf(models, seriesModel) < 0) {
return;
}
this.seriesModel = seriesModel;
this.api = api;
this.ecModel = ecModel;
var targetInfo = helper.retrieveTargetInfo(payload, seriesModel);
var payloadType = payload && payload.type;
var layoutInfo = seriesModel.layoutInfo;
var isInit = !this._oldTree;
var thisStorage = this._storage;
// Mark new root when action is treemapRootToNode.
var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
? {
rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
direction: payload.direction
}
: null;
var containerGroup = this._giveContainerGroup(layoutInfo);
var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
(
!isInit && (
!payloadType
|| payloadType === 'treemapZoomToNode'
|| payloadType === 'treemapRootToNode'
)
)
? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
: renderResult.renderFinally();
this._resetController(api);
this._renderBreadcrumb(seriesModel, api, targetInfo);
},
/**
* @private
*/
_giveContainerGroup: function (layoutInfo) {
var containerGroup = this._containerGroup;
if (!containerGroup) {
// FIXME
// 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
containerGroup = this._containerGroup = new Group();
this._initEvents(containerGroup);
this.group.add(containerGroup);
}
containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
return containerGroup;
},
/**
* @private
*/
_doRender: function (containerGroup, seriesModel, reRoot) {
var thisTree = seriesModel.getData().tree;
var oldTree = this._oldTree;
// Clear last shape records.
var lastsForAnimation = createStorage();
var thisStorage = createStorage();
var oldStorage = this._storage;
var willInvisibleEls = [];
var doRenderNode = zrUtil.curry(
renderNode, seriesModel,
thisStorage, oldStorage, reRoot,
lastsForAnimation, willInvisibleEls
);
// Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
// the oldTree is actually losted, so we can not find all of the old graphic
// elements from tree. So we use this stragegy: make element storage, move
// from old storage to new storage, clear old storage.
dualTravel(
thisTree.root ? [thisTree.root] : [],
(oldTree && oldTree.root) ? [oldTree.root] : [],
containerGroup,
thisTree === oldTree || !oldTree,
0
);
// Process all removing.
var willDeleteEls = clearStorage(oldStorage);
this._oldTree = thisTree;
this._storage = thisStorage;
return {
lastsForAnimation: lastsForAnimation,
willDeleteEls: willDeleteEls,
renderFinally: renderFinally
};
function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
// When 'render' is triggered by action,
// 'this' and 'old' may be the same tree,
// we use rawIndex in that case.
if (sameTree) {
oldViewChildren = thisViewChildren;
each(thisViewChildren, function (child, index) {
!child.isRemoved() && processNode(index, index);
});
}
// Diff hierarchically (diff only in each subtree, but not whole).
// because, consistency of view is important.
else {
(new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
.add(processNode)
.update(processNode)
.remove(zrUtil.curry(processNode, null))
.execute();
}
function getKey(node) {
// Identify by name or raw index.
return node.getId();
}
function processNode(newIndex, oldIndex) {
var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
group && dualTravel(
thisNode && thisNode.viewChildren || [],
oldNode && oldNode.viewChildren || [],
group,
sameTree,
depth + 1
);
}
}
function clearStorage(storage) {
var willDeleteEls = createStorage();
storage && each(storage, function (store, storageName) {
var delEls = willDeleteEls[storageName];
each(store, function (el) {
el && (delEls.push(el), el.__tmWillDelete = 1);
});
});
return willDeleteEls;
}
function renderFinally() {
each(willDeleteEls, function (els) {
each(els, function (el) {
el.parent && el.parent.remove(el);
});
});
each(willInvisibleEls, function (el) {
el.invisible = true;
// Setting invisible is for optimizing, so no need to set dirty,
// just mark as invisible.
el.dirty();
});
}
},
/**
* @private
*/
_doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
if (!seriesModel.get('animation')) {
return;
}
var duration = seriesModel.get('animationDurationUpdate');
var easing = seriesModel.get('animationEasing');
var animationWrap = animationUtil.createWrap();
// Make delete animations.
each(renderResult.willDeleteEls, function (store, storageName) {
each(store, function (el, rawIndex) {
if (el.invisible) {
return;
}
var parent = el.parent; // Always has parent, and parent is nodeGroup.
var target;
if (reRoot && reRoot.direction === 'drillDown') {
target = parent === reRoot.rootNodeGroup
// This is the content element of view root.
// Only `content` will enter this branch, because
// `background` and `nodeGroup` will not be deleted.
? {
shape: {
x: 0,
y: 0,
width: parent.__tmNodeWidth,
height: parent.__tmNodeHeight
},
style: {
opacity: 0
}
}
// Others.
: {style: {opacity: 0}};
}
else {
var targetX = 0;
var targetY = 0;
if (!parent.__tmWillDelete) {
// Let node animate to right-bottom corner, cooperating with fadeout,
// which is appropriate for user understanding.
// Divided by 2 for reRoot rolling up effect.
targetX = parent.__tmNodeWidth / 2;
targetY = parent.__tmNodeHeight / 2;
}
target = storageName === 'nodeGroup'
? {position: [targetX, targetY], style: {opacity: 0}}
: {
shape: {x: targetX, y: targetY, width: 0, height: 0},
style: {opacity: 0}
};
}
target && animationWrap.add(el, target, duration, easing);
});
});
// Make other animations
each(this._storage, function (store, storageName) {
each(store, function (el, rawIndex) {
var last = renderResult.lastsForAnimation[storageName][rawIndex];
var target = {};
if (!last) {
return;
}
if (storageName === 'nodeGroup') {
if (last.old) {
target.position = el.position.slice();
el.attr('position', last.old);
}
}
else {
if (last.old) {
target.shape = zrUtil.extend({}, el.shape);
el.setShape(last.old);
}
if (last.fadein) {
el.setStyle('opacity', 0);
target.style = {opacity: 1};
}
// When animation is stopped for succedent animation starting,
// el.style.opacity might not be 1
else if (el.style.opacity !== 1) {
target.style = {opacity: 1};
}
}
animationWrap.add(el, target, duration, easing);
});
}, this);
this._state = 'animating';
animationWrap
.done(bind(function () {
this._state = 'ready';
renderResult.renderFinally();
}, this))
.start();
},
/**
* @private
*/
_resetController: function (api) {
var controller = this._controller;
// Init controller.
if (!controller) {
controller = this._controller = new RoamController(api.getZr());
controller.enable(this.seriesModel.get('roam'));
controller.on('pan', bind(this._onPan, this));
controller.on('zoom', bind(this._onZoom, this));
}
var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
controller.setPointerChecker(function (e, x, y) {
return rect.contain(x, y);
});
},
/**
* @private
*/
_clearController: function () {
var controller = this._controller;
if (controller) {
controller.dispose();
controller = null;
}
},
/**
* @private
*/
_onPan: function (dx, dy) {
this._mayClick = false;
if (this._state !== 'animating'
&& (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)
) {
// These param must not be cached.
var root = this.seriesModel.getData().tree.root;
if (!root) {
return;
}
var rootLayout = root.getLayout();
if (!rootLayout) {
return;
}
this.api.dispatchAction({
type: 'treemapMove',
from: this.uid,
seriesId: this.seriesModel.id,
rootRect: {
x: rootLayout.x + dx, y: rootLayout.y + dy,
width: rootLayout.width, height: rootLayout.height
}
});
}
},
/**
* @private
*/
_onZoom: function (scale, mouseX, mouseY) {
this._mayClick = false;
if (this._state !== 'animating') {
// These param must not be cached.
var root = this.seriesModel.getData().tree.root;
if (!root) {
return;
}
var rootLayout = root.getLayout();
if (!rootLayout) {
return;
}
var rect = new BoundingRect(
rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
);
var layoutInfo = this.seriesModel.layoutInfo;
// Transform mouse coord from global to containerGroup.
mouseX -= layoutInfo.x;
mouseY -= layoutInfo.y;
// Scale root bounding rect.
var m = matrix.create();
matrix.translate(m, m, [-mouseX, -mouseY]);
matrix.scale(m, m, [scale, scale]);
matrix.translate(m, m, [mouseX, mouseY]);
rect.applyTransform(m);
this.api.dispatchAction({
type: 'treemapRender',
from: this.uid,
seriesId: this.seriesModel.id,
rootRect: {
x: rect.x, y: rect.y,
width: rect.width, height: rect.height
}
});
}
},
/**
* @private
*/
_initEvents: function (containerGroup) {
// FIXME
// 不用click以及silent的原因是,animate时视图设置silent true来避免click生效,
// 但是animate中,按下鼠标,animate结束后(silent设回为false)松开鼠标,
// 还是会触发click,期望是不触发。
// Mousedown occurs when drag start, and mouseup occurs when drag end,
// click event should not be triggered in that case.
containerGroup.on('mousedown', function (e) {
this._state === 'ready' && (this._mayClick = true);
}, this);
containerGroup.on('mouseup', function (e) {
if (this._mayClick) {
this._mayClick = false;
this._state === 'ready' && onClick.call(this, e);
}
}, this);
function onClick(e) {
var nodeClick = this.seriesModel.get('nodeClick', true);
if (!nodeClick) {
return;
}
var targetInfo = this.findTarget(e.offsetX, e.offsetY);
if (!targetInfo) {
return;
}
var node = targetInfo.node;
if (node.getLayout().isLeafRoot) {
this._rootToNode(targetInfo);
}
else {
if (nodeClick === 'zoomToNode') {
this._zoomToNode(targetInfo);
}
else if (nodeClick === 'link') {
var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
var link = itemModel.get('link', true);
var linkTarget = itemModel.get('target', true) || 'blank';
link && window.open(link, linkTarget);
}
}
}
},
/**
* @private
*/
_renderBreadcrumb: function (seriesModel, api, targetInfo) {
if (!targetInfo) {
targetInfo = seriesModel.get('leafDepth', true) != null
? {node: seriesModel.getViewRoot()}
// FIXME
// better way?
// Find breadcrumb tail on center of containerGroup.
: this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
if (!targetInfo) {
targetInfo = {node: seriesModel.getData().tree.root};
}
}
(this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
.render(seriesModel, api, targetInfo.node, bind(onSelect, this));
function onSelect(node) {
if (this._state !== 'animating') {
helper.aboveViewRoot(seriesModel.getViewRoot(), node)
? this._rootToNode({node: node})
: this._zoomToNode({node: node});
}
}
},
/**
* @override
*/
remove: function () {
this._clearController();
this._containerGroup && this._containerGroup.removeAll();
this._storage = createStorage();
this._state = 'ready';
this._breadcrumb && this._breadcrumb.remove();
},
dispose: function () {
this._clearController();
},
/**
* @private
*/
_zoomToNode: function (targetInfo) {
this.api.dispatchAction({
type: 'treemapZoomToNode',
from: this.uid,
seriesId: this.seriesModel.id,
targetNode: targetInfo.node
});
},
/**
* @private
*/
_rootToNode: function (targetInfo) {
this.api.dispatchAction({
type: 'treemapRootToNode',
from: this.uid,
seriesId: this.seriesModel.id,
targetNode: targetInfo.node
});
},
/**
* @public
* @param {number} x Global coord x.
* @param {number} y Global coord y.
* @return {Object} info If not found, return undefined;
* @return {number} info.node Target node.
* @return {number} info.offsetX x refer to target node.
* @return {number} info.offsetY y refer to target node.
*/
findTarget: function (x, y) {
var targetInfo;
var viewRoot = this.seriesModel.getViewRoot();
viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
var bgEl = this._storage.background[node.getRawIndex()];
// If invisible, there might be no element.
if (bgEl) {
var point = bgEl.transformCoordToLocal(x, y);
var shape = bgEl.shape;
// For performance consideration, dont use 'getBoundingRect'.
if (shape.x <= point[0]
&& point[0] <= shape.x + shape.width
&& shape.y <= point[1]
&& point[1] <= shape.y + shape.height
) {
targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
}
else {
return false; // Suppress visit subtree.
}
}
}, this);
return targetInfo;
}
});
/**
* @inner
*/
function createStorage() {
return {nodeGroup: [], background: [], content: []};
}
/**
* @inner
* @return Return undefined means do not travel further.
*/
function renderNode(
seriesModel, thisStorage, oldStorage, reRoot,
lastsForAnimation, willInvisibleEls,
thisNode, oldNode, parentGroup, depth
) {
// Whether under viewRoot.
if (!thisNode) {
// Deleting nodes will be performed finally. This method just find
// element from old storage, or create new element, set them to new
// storage, and set styles.
return;
}
// -------------------------------------------------------------------
// Start of closure variables available in "Procedures in renderNode".
var thisLayout = thisNode.getLayout();
if (!thisLayout || !thisLayout.isInView) {
return;
}
var thisWidth = thisLayout.width;
var thisHeight = thisLayout.height;
var borderWidth = thisLayout.borderWidth;
var thisInvisible = thisLayout.invisible;
var thisRawIndex = thisNode.getRawIndex();
var oldRawIndex = oldNode && oldNode.getRawIndex();
var thisViewChildren = thisNode.viewChildren;
var upperHeight = thisLayout.upperHeight;
var isParent = thisViewChildren && thisViewChildren.length;
var itemStyleEmphasisModel = thisNode.getModel('itemStyle.emphasis');
// End of closure ariables available in "Procedures in renderNode".
// -----------------------------------------------------------------
// Node group
var group = giveGraphic('nodeGroup', Group);
if (!group) {
return;
}
parentGroup.add(group);
// x,y are not set when el is above view root.
group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
group.__tmNodeWidth = thisWidth;
group.__tmNodeHeight = thisHeight;
if (thisLayout.isAboveViewRoot) {
return group;
}
// Background
var bg = giveGraphic('background', Rect, depth, Z_BG);
bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
// No children, render content.
if (!isParent) {
var content = giveGraphic('content', Rect, depth, Z_CONTENT);
content && renderContent(group, content);
}
return group;
// ----------------------------
// | Procedures in renderNode |
// ----------------------------
function renderBackground(group, bg, useUpperLabel) {
// For tooltip.
bg.dataIndex = thisNode.dataIndex;
bg.seriesIndex = seriesModel.seriesIndex;
bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
var visualBorderColor = thisNode.getVisual('borderColor', true);
var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
updateStyle(bg, function () {
var normalStyle = {fill: visualBorderColor};
var emphasisStyle = {fill: emphasisBorderColor};
if (useUpperLabel) {
var upperLabelWidth = thisWidth - 2 * borderWidth;
prepareText(
normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
{x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
);
}
// For old bg.
else {
normalStyle.text = emphasisStyle.text = '';
}
bg.setStyle(normalStyle);
graphic.setHoverStyle(bg, emphasisStyle);
});
group.add(bg);
}
function renderContent(group, content) {
// For tooltip.
content.dataIndex = thisNode.dataIndex;
content.seriesIndex = seriesModel.seriesIndex;
var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
content.culling = true;
content.setShape({
x: borderWidth,
y: borderWidth,
width: contentWidth,
height: contentHeight
});
var visualColor = thisNode.getVisual('color', true);
updateStyle(content, function () {
var normalStyle = {fill: visualColor};
var emphasisStyle = itemStyleEmphasisModel.getItemStyle();
prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
content.setStyle(normalStyle);
graphic.setHoverStyle(content, emphasisStyle);
});
group.add(content);
}
function updateStyle(element, cb) {
if (!thisInvisible) {
// If invisible, do not set visual, otherwise the element will
// change immediately before animation. We think it is OK to
// remain its origin color when moving out of the view window.
cb();
if (!element.__tmWillVisible) {
element.invisible = false;
}
}
else {
// Delay invisible setting utill animation finished,
// avoid element vanish suddenly before animation.
!element.invisible && willInvisibleEls.push(element);
}
}
function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
var nodeModel = thisNode.getModel();
var text = zrUtil.retrieve(
seriesModel.getFormattedLabel(
thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
),
nodeModel.get('name')
);
if (!upperLabelRect && thisLayout.isLeafRoot) {
var iconChar = seriesModel.get('drillDownIcon', true);
text = iconChar ? iconChar + ' ' + text : text;
}
setText(
text, normalStyle, nodeModel, upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL,
visualColor, width, height, upperLabelRect
);
setText(
text, emphasisStyle, nodeModel, upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS,
visualColor, width, height, upperLabelRect
);
}
function setText(text, style, nodeModel, labelPath, visualColor, width, height, upperLabelRect) {
var labelModel = nodeModel.getModel(labelPath);
graphic.setText(style, labelModel, visualColor);
upperLabelRect && (style.textPositionRect = zrUtil.clone(upperLabelRect));
var textRect = labelModel.getTextRect(text);
if (!labelModel.getShallow('show') || textRect.height > height) {
style.text = null;
}
else if (textRect.width > width) {
style.text = labelModel.get('ellipsis')
? labelModel.truncateText(
text, width, null, {minChar: 2}
)
: null;
}
else {
style.text = text;
}
}
function giveGraphic(storageName, Ctor, depth, z) {
var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
var lasts = lastsForAnimation[storageName];
if (element) {
// Remove from oldStorage
oldStorage[storageName][oldRawIndex] = null;
prepareAnimationWhenHasOld(lasts, element, storageName);
}
// If invisible and no old element, do not create new element (for optimizing).
else if (!thisInvisible) {
element = new Ctor({z: calculateZ(depth, z)});
element.__tmDepth = depth;
element.__tmStorageName = storageName;
prepareAnimationWhenNoOld(lasts, element, storageName);
}
// Set to thisStorage
return (thisStorage[storageName][thisRawIndex] = element);
}
function prepareAnimationWhenHasOld(lasts, element, storageName) {
var lastCfg = lasts[thisRawIndex] = {};
lastCfg.old = storageName === 'nodeGroup'
? element.position.slice()
: zrUtil.extend({}, element.shape);
}
// If a element is new, we need to find the animation start point carefully,
// otherwise it will looks strange when 'zoomToNode'.
function prepareAnimationWhenNoOld(lasts, element, storageName) {
var lastCfg = lasts[thisRawIndex] = {};
var parentNode = thisNode.parentNode;
if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
var parentOldX = 0;
var parentOldY = 0;
// New nodes appear from right-bottom corner in 'zoomToNode' animation.
// For convenience, get old bounding rect from background.
var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
if (!reRoot && parentOldBg && parentOldBg.old) {
parentOldX = parentOldBg.old.width;
parentOldY = parentOldBg.old.height;
}
// When no parent old shape found, its parent is new too,
// so we can just use {x:0, y:0}.
lastCfg.old = storageName === 'nodeGroup'
? [0, parentOldY]
: {x: parentOldX, y: parentOldY, width: 0, height: 0};
}
// Fade in, user can be aware that these nodes are new.
lastCfg.fadein = storageName !== 'nodeGroup';
}
}
// We can not set all backgroud with the same z, Because the behaviour of
// drill down and roll up differ background creation sequence from tree
// hierarchy sequence, which cause that lowser background element overlap
// upper ones. So we calculate z based on depth.
// Moreover, we try to shrink down z interval to [0, 1] to avoid that
// treemap with large z overlaps other components.
function calculateZ(depth, zInLevel) {
var zb = depth * Z_BASE + zInLevel;
return (zb - 1) / zb;
}
});
|
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
const users = [{
id: 1,
name: 'Christian Alfoni',
githubUsername: 'christianalfoni'
}, {
id: 2,
name: 'Aleksey tha man'
}, {
id: 3,
name: 'Brian Fitch'
}, {
id: 4,
name: 'Garth Williams'
}]
const assignments = [{
id: 1,
title: 'Check out function tree demos',
assignedTo: [1]
}]
app.get('/assignments', (req, res) => {
setTimeout(() => {
res.send(assignments)
}, 500)
})
app.post('/assignments', (req, res) => {
const assignment = req.body
setTimeout(() => {
assignment.id = assignments.length + 1
assignments.unshift(assignment)
res.send({
id: assignment.id
})
}, 500)
})
app.get('/users', (req, res) => {
setTimeout(() => {
res.send(users.filter(user => (
user.name.toLowerCase().indexOf(req.query.name.toLowerCase()) === 0
))[0] || null)
}, 200)
})
app.get('/users/:id', (req, res) => {
setTimeout(() => {
res.send(users.filter(user => user.id === Number(req.params.id))[0])
}, 500)
})
app.listen(4000, () => {
console.log('Running demo, on localhost:4000')
})
|
// Platform specific overrides will be placed in the merges folder versions of this file
|
var _ = require("underscore");
var Fiber = require("fibers");
exports.parallelEach = function (collection, callback, context) {
const errors = [];
context = context || null;
const results = Promise.all(_.map(collection, (...args) => {
async function run() {
return callback.apply(context, args);
}
return run().catch(error => {
// Collect the errors but do not propagate them so that we can
// re-throw the first error after all iterations have completed.
errors.push(error);
});
})).await();
if (errors.length > 0) {
throw errors[0];
}
return results;
};
function disallowedYield() {
throw new Error("Can't call yield in a noYieldsAllowed block!");
}
// Allow testing Fiber.yield.disallowed.
disallowedYield.disallowed = true;
exports.noYieldsAllowed = function (f, context) {
var savedYield = Fiber.yield;
Fiber.yield = disallowedYield;
try {
return f.call(context || null);
} finally {
Fiber.yield = savedYield;
}
};
// Borrowed from packages/meteor/dynamics_nodejs.js
// Used by buildmessage
exports.nodeCodeMustBeInFiber = function () {
if (!Fiber.current) {
throw new Error("Meteor code must always run within a Fiber. " +
"Try wrapping callbacks that you pass to non-Meteor " +
"libraries with Meteor.bindEnvironment.");
}
};
var nextSlot = 0;
exports.EnvironmentVariable = function (defaultValue) {
var self = this;
self.slot = 'slot' + nextSlot++;
self.defaultValue = defaultValue;
};
Object.assign(exports.EnvironmentVariable.prototype, {
get() {
var self = this;
exports.nodeCodeMustBeInFiber();
if (!Fiber.current._meteorDynamics) {
return self.defaultValue;
}
if (!_.has(Fiber.current._meteorDynamics, self.slot)) {
return self.defaultValue;
}
return Fiber.current._meteorDynamics[self.slot];
},
set(value) {
exports.nodeCodeMustBeInFiber();
const fiber = Fiber.current;
const currentValues = fiber._meteorDynamics || (
fiber._meteorDynamics = {}
);
const saved = _.has(currentValues, this.slot)
? currentValues[this.slot]
: this.defaultValue;
currentValues[this.slot] = value;
return () => {
currentValues[this.slot] = saved;
};
},
withValue(value, func) {
const reset = this.set(value);
try {
return func();
} finally {
reset();
}
}
});
// This is like Meteor.bindEnvironment.
// Experimentally, we are NOT including onException or _this in this version.
exports.bindEnvironment = function (func) {
exports.nodeCodeMustBeInFiber();
var boundValues = _.clone(Fiber.current._meteorDynamics || {});
return function (...args) {
var self = this;
var runWithEnvironment = function () {
var savedValues = Fiber.current._meteorDynamics;
try {
// Need to clone boundValues in case two fibers invoke this
// function at the same time
Fiber.current._meteorDynamics = _.clone(boundValues);
return func.apply(self, args);
} finally {
Fiber.current._meteorDynamics = savedValues;
}
};
if (Fiber.current) {
return runWithEnvironment();
}
Fiber(runWithEnvironment).run();
};
};
// Returns a Promise that supports .resolve(result) and .reject(error).
exports.makeFulfillablePromise = function () {
var resolve, reject;
var promise = new Promise(function (res, rej) {
resolve = res;
reject = rej;
});
promise.resolve = resolve;
promise.reject = reject;
return promise;
};
|
(function () {
var app = angular.module('app', ['firebase', 'ui.router'])
.constant('firebaseUrl', "https://popping-torch-4767.firebaseio.com/");
app.config(function ($stateProvider, $urlRouterProvider, firebaseUrl) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'partial-home.html'
})
.state('authenticated', {
url: '/authenticated',
templateUrl: 'partial-authenticated.html',
resolve: {
// controller will not be loaded until $waitForAuth resolves
// Auth refers to our $firebaseAuth wrapper in the example above
"currentAuth": ["$firebaseAuth", function ($firebaseAuth) {
// $waitForAuth returns a promise so the resolve waits for it to complete
var ref = new Firebase(firebaseUrl);
var authObj = $firebaseAuth(ref);
return authObj.$requireAuth();
}]
}
});
});
})();
|
// @flow strict-local
import createSheet from '../../styles/create-sheet';
export type Data = { disabled: boolean };
export default createSheet('Label', {
label: {
display: 'flex',
alignItems: 'center',
},
text: {
padding: '4px 4px 4px 8px',
userSelect: 'none',
cursor: (data: Data) => (data.disabled ? 'disabled' : 'pointer'),
pointerEvents: (data: Data) => (data.disabled ? 'none' : 'auto'),
},
});
|
// 20170424172403
// https://raw.githubusercontent.com/nodemailer/nodemailer/master/lib/well-known/services.json
module.exports = {
"126": {
"host": "smtp.126.com",
"port": 465,
"secure": true
},
"163": {
"host": "smtp.163.com",
"port": 465,
"secure": true
},
"1und1": {
"host": "smtp.1und1.de",
"port": 465,
"secure": true,
"authMethod": "LOGIN"
},
"AOL": {
"domains": [
"aol.com"
],
"host": "smtp.aol.com",
"port": 587
},
"DebugMail": {
"host": "debugmail.io",
"port": 25
},
"DynectEmail": {
"aliases": [
"Dynect"
],
"host": "smtp.dynect.net",
"port": 25
},
"FastMail": {
"domains": [
"fastmail.fm"
],
"host": "mail.messagingengine.com",
"port": 465,
"secure": true
},
"GandiMail": {
"aliases": [
"Gandi",
"Gandi Mail"
],
"host": "mail.gandi.net",
"port": 587
},
"Gmail": {
"aliases": [
"Google Mail"
],
"domains": [
"gmail.com",
"googlemail.com"
],
"host": "smtp.gmail.com",
"port": 465,
"secure": true
},
"Godaddy": {
"host": "smtpout.secureserver.net",
"port": 25
},
"GodaddyAsia": {
"host": "smtp.asia.secureserver.net",
"port": 25
},
"GodaddyEurope": {
"host": "smtp.europe.secureserver.net",
"port": 25
},
"hot.ee": {
"host": "mail.hot.ee"
},
"Hotmail": {
"aliases": [
"Outlook",
"Outlook.com",
"Hotmail.com"
],
"domains": [
"hotmail.com",
"outlook.com"
],
"host": "smtp.live.com",
"port": 587,
"tls": {
"ciphers": "SSLv3"
}
},
"iCloud": {
"aliases": [
"Me",
"Mac"
],
"domains": [
"me.com",
"mac.com"
],
"host": "smtp.mail.me.com",
"port": 587
},
"mail.ee": {
"host": "smtp.mail.ee"
},
"Mail.ru": {
"host": "smtp.mail.ru",
"port": 465,
"secure": true
},
"Maildev": {
"port": 1025,
"ignoreTLS": true
},
"Mailgun": {
"host": "smtp.mailgun.org",
"port": 587
},
"Mailjet": {
"host": "in.mailjet.com",
"port": 587
},
"Mailosaur": {
"host": "mailosaur.io",
"port": 25
},
"Mandrill": {
"host": "smtp.mandrillapp.com",
"port": 587
},
"Naver": {
"host": "smtp.naver.com",
"port": 587
},
"OpenMailBox": {
"aliases": [
"OMB",
"openmailbox.org"
],
"host": "smtp.openmailbox.org",
"port": 465,
"secure": true
},
"Outlook365": {
"host": "smtp.office365.com",
"port": 587,
"secure": false
},
"Postmark": {
"aliases": [
"PostmarkApp"
],
"host": "smtp.postmarkapp.com",
"port": 2525
},
"QQ": {
"domains": [
"qq.com"
],
"host": "smtp.qq.com",
"port": 465,
"secure": true
},
"QQex": {
"aliases": [
"QQ Enterprise"
],
"domains": [
"exmail.qq.com"
],
"host": "smtp.exmail.qq.com",
"port": 465,
"secure": true
},
"SendCloud": {
"host": "smtpcloud.sohu.com",
"port": 25
},
"SendGrid": {
"host": "smtp.sendgrid.net",
"port": 587
},
"SendinBlue": {
"host": "smtp-relay.sendinblue.com",
"port": 587
},
"SendPulse": {
"host": "smtp-pulse.com",
"port": 465,
"secure": true
},
"SES": {
"host": "email-smtp.us-east-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-US-EAST-1": {
"host": "email-smtp.us-east-1.amazonaws.com",
"port": 465,
"secure": true
},
"SES-US-WEST-2": {
"host": "email-smtp.us-west-2.amazonaws.com",
"port": 465,
"secure": true
},
"SES-EU-WEST-1": {
"host": "email-smtp.eu-west-1.amazonaws.com",
"port": 465,
"secure": true
},
"Sparkpost": {
"aliases": [
"SparkPost",
"SparkPost Mail"
],
"domains": [
"sparkpost.com"
],
"host": "smtp.sparkpostmail.com",
"port": 587,
"secure": false
},
"Tipimail": {
"aliases": [
"tipimail"
],
"host": "smtp.tipimail.com",
"port": 587
},
"Yahoo": {
"domains": [
"yahoo.com"
],
"host": "smtp.mail.yahoo.com",
"port": 465,
"secure": true
},
"Yandex": {
"domains": [
"yandex.ru"
],
"host": "smtp.yandex.ru",
"port": 465,
"secure": true
},
"Zoho": {
"host": "smtp.zoho.com",
"port": 465,
"secure": true,
"authMethod": "LOGIN"
},
"qiye.aliyun": {
"host": "smtp.mxhichina.com",
"port": "465",
"secure": true
}
}
|
/**
* Copyright (c) 2008-2011 The Open Planning Project
*
* Published under the BSD license.
* See https://github.com/opengeo/gxp/raw/master/license.txt for the full text
* of the license.
*/
/**
* @requires plugins/LayerSource.js
*/
/** api: (define)
* module = gxp.plugins
* class = GoogleSource
*/
/** api: (extends)
* plugins/LayerSource.js
*/
Ext.namespace("gxp.plugins");
/** api: constructor
* .. class:: GoolgeSource(config)
*
* Plugin for using Google layers with :class:`gxp.Viewer` instances. The
* plugin uses the GMaps v3 API and also takes care of loading the
* required Google resources.
*
* Available layer names for this source are "ROADMAP", "SATELLITE",
* "HYBRID" and "TERRAIN"
*/
/** api: example
* The configuration in the ``sources`` property of the :class:`gxp.Viewer` is
* straightforward:
*
* .. code-block:: javascript
*
* "google": {
* ptype: "gxp_google"
* }
*
* A typical configuration for a layer from this source (in the ``layers``
* array of the viewer's ``map`` config option would look like this:
*
* .. code-block:: javascript
*
* {
* source: "google",
* name: "TERRAIN"
* }
*
*/
gxp.plugins.GoogleSource = Ext.extend(gxp.plugins.LayerSource, {
/** api: ptype = gxp_googlesource */
ptype: "gxp_googlesource",
/** config: config[timeout]
* ``Number``
* The time (in milliseconds) to wait before giving up on the Google Maps
* script loading. This layer source will not be availble if the script
* does not load within the given timeout. Default is 7000 (seven seconds).
*/
timeout: 7000,
/** api: property[store]
* ``GeoExt.data.LayerStore`` containing records with "ROADMAP",
* "SATELLITE", "HYBRID" and "TERRAIN" name fields.
*/
/** api: config[title]
* ``String``
* A descriptive title for this layer source (i18n).
*/
title: "Google Layers",
/** api: config[roadmapAbstract]
* ``String``
* Description of the ROADMAP layer (i18n).
*/
roadmapAbstract: "Show street map",
/** api: config[satelliteAbstract]
* ``String``
* Description of the SATELLITE layer (i18n).
*/
satelliteAbstract: "Show satellite imagery",
/** api: config[hybridAbstract]
* ``String``
* Description of the HYBRID layer (i18n).
*/
hybridAbstract: "Show imagery with street names",
/** api: config[terrainAbstract]
* ``String``
* Description of the TERRAIN layer (i18n).
*/
terrainAbstract: "Show street map with terrain",
constructor: function(config) {
this.config = config;
gxp.plugins.GoogleSource.superclass.constructor.apply(this, arguments);
},
/** api: method[createStore]
*
* Creates a store of layer records. Fires "ready" when store is loaded.
*/
createStore: function() {
gxp.plugins.GoogleSource.loader.onLoad({
timeout: this.timeout,
callback: this.syncCreateStore,
errback: function() {
delete this.store;
this.fireEvent(
"failure",
this,
"The Google Maps script failed to load within the provided timeout (" + (this.timeout / 1000) + " s)."
);
},
scope: this
});
},
/** private: method[syncCreateStore]
*
* Creates a store of layers. This requires that the API script has already
* loaded. Fires the "ready" event when the store is loaded.
*/
syncCreateStore: function() {
// TODO: The abstracts ("alt" properties) should be derived from the
// MapType objects themselves. It doesn't look like there is currently
// a way to get the default map types before creating a map object.
// http://code.google.com/p/gmaps-api-issues/issues/detail?id=2562
// TODO: We may also be able to determine the MAX_ZOOM_LEVEL for each
// layer type. If not, consider setting them on the OpenLayers level.
var mapTypes = {
"ROADMAP": {"abstract": this.roadmapAbstract, MAX_ZOOM_LEVEL: 20},
"SATELLITE": {"abstract": this.satelliteAbstract},
"HYBRID": {"abstract": this.hybridAbstract},
"TERRAIN": {"abstract": this.terrainAbstract, MAX_ZOOM_LEVEL: 15}
};
var layers = [];
var name, mapType;
for (name in mapTypes) {
mapType = google.maps.MapTypeId[name];
layers.push(new OpenLayers.Layer.Google(
// TODO: get MapType object name
// http://code.google.com/p/gmaps-api-issues/issues/detail?id=2562
"Google " + mapType.replace(/\w/, function(c) {return c.toUpperCase();}), {
type: mapType,
typeName: name,
MAX_ZOOM_LEVEL: mapTypes[name].MAX_ZOOM_LEVEL,
maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
restrictedExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
projection: this.projection
}
));
}
this.store = new GeoExt.data.LayerStore({
layers: layers,
fields: [
{name: "source", type: "string"},
{name: "name", type: "string", mapping: "typeName"},
{name: "abstract", type: "string"},
{name: "group", type: "string", defaultValue: "background"},
{name: "fixed", type: "boolean", defaultValue: true},
{name: "selected", type: "boolean"}
]
});
this.store.each(function(l) {
l.set("abstract", mapTypes[l.get("name")]["abstract"]);
});
this.fireEvent("ready", this);
},
/** api: method[createLayerRecord]
* :arg config: ``Object`` The application config for this layer.
* :returns: ``GeoExt.data.LayerRecord``
*
* Create a layer record given the config.
*/
createLayerRecord: function(config) {
var record;
var cmp = function(l) {
return l.get("name") === config.name;
};
// only return layer if app does not have it already
if (this.target.mapPanel.layers.findBy(cmp) == -1) {
// records can be in only one store
record = this.store.getAt(this.store.findBy(cmp)).clone();
var layer = record.getLayer();
// set layer title from config
if (config.title) {
/**
* Because the layer title data is duplicated, we have
* to set it in both places. After records have been
* added to the store, the store handles this
* synchronization.
*/
layer.setName(config.title);
record.set("title", config.title);
}
// set visibility from config
if ("visibility" in config) {
layer.visibility = config.visibility;
}
record.set("selected", config.selected || false);
record.set("source", config.source);
record.set("name", config.name);
if ("group" in config) {
record.set("group", config.group);
}
record.commit();
}
return record;
}
});
/**
* Create a loader singleton that all plugin instances can use.
*/
gxp.plugins.GoogleSource.loader = new (Ext.extend(Ext.util.Observable, {
/** private: property[ready]
* ``Boolean``
* This plugin type is ready to use.
*/
ready: !!(window.google && google.maps),
/** private: property[loading]
* ``Boolean``
* The resources for this plugin type are loading.
*/
loading: false,
constructor: function() {
this.addEvents(
/** private: event[ready]
* Fires when this plugin type is ready.
*/
"ready",
/** private: event[failure]
* Fires when script loading fails.
*/
"failure"
);
return Ext.util.Observable.prototype.constructor.apply(this, arguments);
},
/** private: method[onScriptLoad]
* Called when all resources required by this plugin type have loaded.
*/
onScriptLoad: function() {
// the google loader calls this in the window scope
var monitor = gxp.plugins.GoogleSource.loader;
if (!monitor.ready) {
monitor.ready = true;
monitor.loading = false;
monitor.fireEvent("ready");
}
},
/** api: method[gxp.plugins.GoogleSource.loader.onLoad]
* :arg options: ``Object``
*
* Options:
*
* * callback - ``Function`` Called when script loads.
* * errback - ``Function`` Called if loading fails.
* * timeout - ``Number`` Time to wait before deciding that loading failed
* (in milliseconds).
* * scope - ``Object`` The ``this`` object for callbacks.
*/
onLoad: function(options) {
if (this.ready) {
// call this in the next turn for consistent return before callback
window.setTimeout(function() {
options.callback.call(options.scope);
}, 0);
} else if (!this.loading) {
this.loadScript(options);
} else {
this.on({
ready: options.callback,
failure: options.errback || Ext.emptyFn,
scope: options.scope
});
}
},
/** private: method[onScriptLoad]
* Called when all resources required by this plugin type have loaded.
*/
loadScript: function(options) {
var params = {
autoload: Ext.encode({
modules: [{
name: "maps",
version: 3.3,
nocss: "true",
callback: "gxp.plugins.GoogleSource.loader.onScriptLoad",
other_params: "sensor=false"
}]
})
};
var script = document.createElement("script");
script.src = "http://www.google.com/jsapi?" + Ext.urlEncode(params);
// cancel loading if monitor is not ready within timeout
var errback = options.errback || Ext.emptyFn;
var timeout = options.timeout || gxp.plugins.GoogleSource.prototype.timeout;
window.setTimeout((function() {
if (!gxp.plugins.GoogleSource.loader.ready) {
this.loading = false;
this.ready = false;
document.getElementsByTagName("head")[0].removeChild(script);
errback.call(options.scope);
this.fireEvent("failure");
this.purgeListeners();
}
}).createDelegate(this), timeout);
// register callback for ready
this.on({
ready: options.callback,
scope: options.scope
});
this.loading = true;
document.getElementsByTagName("head")[0].appendChild(script);
}
}))();
Ext.preg(gxp.plugins.GoogleSource.prototype.ptype, gxp.plugins.GoogleSource);
|
function mapFilenames(filenames) {
return filenames.map(filename => `"${filename}"`).join(' ');
}
module.exports = {
'*': () => [
'yarn run test',
'yarn run test:ts',
],
'*.ts': (filenames) => [
`eslint --fix --cache ${mapFilenames(filenames)}`,
],
};
|
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['specs/e2e/ng-sticky-element.js'],
capabilities: {
'browserName': 'firefox'
}
};
|
import React from 'react'
import Icon from 'react-icon-base'
const FaPhone = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m35.9 27.7q0 0.6-0.2 1.6t-0.5 1.5q-0.4 1.1-2.7 2.3-2.1 1.2-4.1 1.2-0.6 0-1.2-0.1t-1.3-0.3-1.1-0.3-1.2-0.5-1.1-0.4q-2.2-0.7-3.9-1.8-2.8-1.8-5.9-4.8t-4.8-5.9q-1.1-1.7-1.9-3.9 0-0.2-0.4-1.1t-0.4-1.3-0.3-1-0.3-1.3-0.1-1.2q0-2 1.1-4.1 1.3-2.3 2.4-2.8 0.6-0.2 1.5-0.4t1.6-0.2q0.3 0 0.5 0 0.4 0.2 1.2 1.7 0.2 0.4 0.6 1.2t0.8 1.4 0.7 1.2q0.1 0.1 0.4 0.6t0.5 0.8 0.1 0.6q0 0.5-0.6 1.1t-1.4 1.3-1.4 1.1-0.6 1.1q0 0.2 0.1 0.5t0.2 0.4 0.3 0.6 0.3 0.4q1.7 3.1 3.8 5.2t5.3 3.9q0 0 0.4 0.3t0.6 0.3 0.4 0.2 0.5 0.1q0.4 0 1-0.6t1.2-1.4 1.3-1.4 1.1-0.6q0.3 0 0.6 0.1t0.8 0.5 0.6 0.4q0.5 0.3 1.1 0.7t1.5 0.8 1.2 0.6q1.5 0.8 1.7 1.2 0 0.2 0 0.5z"/></g>
</Icon>
)
export default FaPhone
|
BlazeComponent.extendComponent({
onCreated() {
this.subscribe('allRules');
this.subscribe('allTriggers');
this.subscribe('allActions');
},
trigger() {
const ruleId = this.data().ruleId;
const rule = Rules.findOne({
_id: ruleId.get(),
});
const trigger = Triggers.findOne({
_id: rule.triggerId,
});
const desc = trigger.description();
const upperdesc = desc.charAt(0).toUpperCase() + desc.substr(1);
return upperdesc;
},
action() {
const ruleId = this.data().ruleId;
const rule = Rules.findOne({
_id: ruleId.get(),
});
const action = Actions.findOne({
_id: rule.actionId,
});
const desc = action.description();
const upperdesc = desc.charAt(0).toUpperCase() + desc.substr(1);
return upperdesc;
},
events() {
return [{}];
},
}).register('ruleDetails');
|
const arrayRemove = require('unordered-array-remove')
const bencode = require('bencode')
const compact2string = require('compact2string')
const debug = require('debug')('bittorrent-tracker:http-tracker')
const get = require('simple-get')
const common = require('../common')
const Tracker = require('./tracker')
const HTTP_SCRAPE_SUPPORT = /\/(announce)[^/]*$/
/**
* HTTP torrent tracker client (for an individual tracker)
*
* @param {Client} client parent bittorrent tracker client
* @param {string} announceUrl announce url of tracker
* @param {Object} opts options object
*/
class HTTPTracker extends Tracker {
constructor (client, announceUrl, opts) {
super(client, announceUrl)
debug('new http tracker %s', announceUrl)
// Determine scrape url (if http tracker supports it)
this.scrapeUrl = null
const match = this.announceUrl.match(HTTP_SCRAPE_SUPPORT)
if (match) {
const pre = this.announceUrl.slice(0, match.index)
const post = this.announceUrl.slice(match.index + 9)
this.scrapeUrl = `${pre}/scrape${post}`
}
this.cleanupFns = []
this.maybeDestroyCleanup = null
}
announce (opts) {
if (this.destroyed) return
const params = Object.assign({}, opts, {
compact: (opts.compact == null) ? 1 : opts.compact,
info_hash: this.client._infoHashBinary,
peer_id: this.client._peerIdBinary,
port: this.client._port
})
if (this._trackerId) params.trackerid = this._trackerId
this._request(this.announceUrl, params, (err, data) => {
if (err) return this.client.emit('warning', err)
this._onAnnounceResponse(data)
})
}
scrape (opts) {
if (this.destroyed) return
if (!this.scrapeUrl) {
this.client.emit('error', new Error(`scrape not supported ${this.announceUrl}`))
return
}
const infoHashes = (Array.isArray(opts.infoHash) && opts.infoHash.length > 0)
? opts.infoHash.map(infoHash => {
return infoHash.toString('binary')
})
: (opts.infoHash && opts.infoHash.toString('binary')) || this.client._infoHashBinary
const params = {
info_hash: infoHashes
}
this._request(this.scrapeUrl, params, (err, data) => {
if (err) return this.client.emit('warning', err)
this._onScrapeResponse(data)
})
}
destroy (cb) {
const self = this
if (this.destroyed) return cb(null)
this.destroyed = true
clearInterval(this.interval)
// If there are no pending requests, destroy immediately.
if (this.cleanupFns.length === 0) return destroyCleanup()
// Otherwise, wait a short time for pending requests to complete, then force
// destroy them.
var timeout = setTimeout(destroyCleanup, common.DESTROY_TIMEOUT)
// But, if all pending requests complete before the timeout fires, do cleanup
// right away.
this.maybeDestroyCleanup = () => {
if (this.cleanupFns.length === 0) destroyCleanup()
}
function destroyCleanup () {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
self.maybeDestroyCleanup = null
self.cleanupFns.slice(0).forEach(cleanup => {
cleanup()
})
self.cleanupFns = []
cb(null)
}
}
_request (requestUrl, params, cb) {
const self = this
const u = requestUrl + (!requestUrl.includes('?') ? '?' : '&') +
common.querystringStringify(params)
this.cleanupFns.push(cleanup)
let request = get.concat({
url: u,
timeout: common.REQUEST_TIMEOUT,
headers: {
'user-agent': this.client._userAgent || ''
}
}, onResponse)
function cleanup () {
if (request) {
arrayRemove(self.cleanupFns, self.cleanupFns.indexOf(cleanup))
request.abort()
request = null
}
if (self.maybeDestroyCleanup) self.maybeDestroyCleanup()
}
function onResponse (err, res, data) {
cleanup()
if (self.destroyed) return
if (err) return cb(err)
if (res.statusCode !== 200) {
return cb(new Error(`Non-200 response code ${res.statusCode} from ${self.announceUrl}`))
}
if (!data || data.length === 0) {
return cb(new Error(`Invalid tracker response from${self.announceUrl}`))
}
try {
data = bencode.decode(data)
} catch (err) {
return cb(new Error(`Error decoding tracker response: ${err.message}`))
}
const failure = data['failure reason']
if (failure) {
debug(`failure from ${requestUrl} (${failure})`)
return cb(new Error(failure))
}
const warning = data['warning message']
if (warning) {
debug(`warning from ${requestUrl} (${warning})`)
self.client.emit('warning', new Error(warning))
}
debug(`response from ${requestUrl}`)
cb(null, data)
}
}
_onAnnounceResponse (data) {
const interval = data.interval || data['min interval']
if (interval) this.setInterval(interval * 1000)
const trackerId = data['tracker id']
if (trackerId) {
// If absent, do not discard previous trackerId value
this._trackerId = trackerId
}
const response = Object.assign({}, data, {
announce: this.announceUrl,
infoHash: common.binaryToHex(data.info_hash)
})
this.client.emit('update', response)
let addrs
if (Buffer.isBuffer(data.peers)) {
// tracker returned compact response
try {
addrs = compact2string.multi(data.peers)
} catch (err) {
return this.client.emit('warning', err)
}
addrs.forEach(addr => {
this.client.emit('peer', addr)
})
} else if (Array.isArray(data.peers)) {
// tracker returned normal response
data.peers.forEach(peer => {
this.client.emit('peer', `${peer.ip}:${peer.port}`)
})
}
if (Buffer.isBuffer(data.peers6)) {
// tracker returned compact response
try {
addrs = compact2string.multi6(data.peers6)
} catch (err) {
return this.client.emit('warning', err)
}
addrs.forEach(addr => {
this.client.emit('peer', addr)
})
} else if (Array.isArray(data.peers6)) {
// tracker returned normal response
data.peers6.forEach(peer => {
const ip = /^\[/.test(peer.ip) || !/:/.test(peer.ip)
? peer.ip /* ipv6 w/ brackets or domain name */
: `[${peer.ip}]` /* ipv6 without brackets */
this.client.emit('peer', `${ip}:${peer.port}`)
})
}
}
_onScrapeResponse (data) {
// NOTE: the unofficial spec says to use the 'files' key, 'host' has been
// seen in practice
data = data.files || data.host || {}
const keys = Object.keys(data)
if (keys.length === 0) {
this.client.emit('warning', new Error('invalid scrape response'))
return
}
keys.forEach(infoHash => {
// TODO: optionally handle data.flags.min_request_interval
// (separate from announce interval)
const response = Object.assign(data[infoHash], {
announce: this.announceUrl,
infoHash: common.binaryToHex(infoHash)
})
this.client.emit('scrape', response)
})
}
}
HTTPTracker.prototype.DEFAULT_ANNOUNCE_INTERVAL = 30 * 60 * 1000 // 30 minutes
module.exports = HTTPTracker
|
module.exports = class ReporterProxy {
constructor () {
this.reporter = null
this.timingsQueue = []
this.eventType = 'find-and-replace-v1'
}
setReporter (reporter) {
this.reporter = reporter
let timingsEvent
while ((timingsEvent = this.timingsQueue.shift())) {
this.reporter.addTiming(this.eventType, timingsEvent.duration, timingsEvent.metadata)
}
}
unsetReporter () {
delete this.reporter
}
sendSearchEvent (duration, numResults, crawler) {
const metadata = {
ec: 'time-to-search',
ev: numResults,
el: crawler
}
this._addTiming(duration, metadata)
}
_addTiming (duration, metadata) {
if (this.reporter) {
this.reporter.addTiming(this.eventType, duration, metadata)
} else {
this.timingsQueue.push({duration, metadata})
}
}
}
|
'use strict'
var Seneca = require('seneca')
var Shared = require('seneca-store-test')
var Lab = require('lab')
var lab = exports.lab = Lab.script()
var before = lab.before
var describe = lab.describe
var DBConfig = require('./dbconfig')
var si = Seneca({
default_plugins: {
'mem-store': false
}
})
describe('seneca-store-query tests ', function () {
before({}, function (done) {
si.use(require('seneca-postgres-store'), DBConfig)
si.ready(function () {
si.use(require('..'))
si.ready(done)
})
})
Shared.basictest({
seneca: si,
script: lab
})
Shared.sorttest({
seneca: si,
script: lab
})
Shared.limitstest({
seneca: si,
script: lab
})
Shared.sqltest({
seneca: si,
script: lab
})
})
|
'use strict'
let immstruct = require('immstruct')
let ReactDom = require('react-dom')
let router = require('./router')
let Logger = require('@arve.knudsen/js-logger')
let ajax = require('./ajax')
let routeMap = require('./workshopsRouteMap')
require('./styles/fonts.css')
Logger.useDefaults({
formatter: (messages, context) => {
messages.unshift(`${context.level.name} - [${context.name}]`)
},
})
Logger.setHandler((messages, context) => {
if (context.level === Logger.ERROR) {
ajax.postJson('/api/logError', {
error: messages[0],
})
}
Logger.getDefaultHandler()(messages, context)
})
let logger = Logger.get('entry')
window.onerror = (message, url, line) => {
// TODO: Show dialog?
logger.error(`Uncaught exception, at ${url}:${line}:\n${message}`)
}
let initialState = JSON.parse(document.getElementById('initial-state').getAttribute('data-json'))
logger.debug(`Initial state as rendered by server:`, initialState)
Stripe.setPublishableKey(initialState.stripeKey)
let structure = immstruct('state', initialState)
router.performInitial(structure.cursor(), routeMap)
let render = () => {
ReactDom.render(router.Router(structure.cursor()), document.getElementById('container'))
}
render()
structure.on('swap', render)
|
(function (angular) {
"use strict";
angular.module("mfl.facility_mgmt.states.upgrade_downgrade", [
"ui.router"
])
.config(["$stateProvider", function ($stateProvider) {
$stateProvider
.state("facilities.upgrade", {
url: "upgrade/:facility_id/",
views: {
"main-content@facility_mgmt": {
templateUrl: "facility_mgmt/tpls/facility_up_down_grade.tpl.html",
controller: "mfl.facility_mgmt.controllers.facility_upgrade"
}
},
permission: "facilities.change_facility,"+
"facilities.add_facilityservice"
})
.state("facilities.downgrade", {
url: "downgrade/:facility_id/",
views: {
"main-content@facility_mgmt": {
templateUrl: "facility_mgmt/tpls/facility_up_down_grade.tpl.html",
controller: "mfl.facility_mgmt.controllers.facility_downgrade"
}
},
permission: "facilities.add_facilitytype,facilities.view_facility"
});
}]);
})(window.angular);
|
declare module 'expo-constants' {
declare export type AppOwnership = 'standalone' | 'expo' | 'guest';
declare export type UserInterfaceIdiom = 'handset' | 'tablet' | 'unsupported';
declare export type IOSManifest = {
buildNumber: string,
platform: string,
model: string,
userInterfaceIdiom: UserInterfaceIdiom,
systemVersion: string,
...
};
declare export type AndroidManifest = { versionCode: number, ... };
declare export type WebManifest = {...};
declare export type AppManifest = {
releaseChannel?: string,
name?: string,
description?: string,
slug?: string,
sdkVersion?: string,
version?: string,
orientation?: string,
primaryColor?: string,
icon?: string,
notification?: {
icon?: string,
color?: string,
...
},
loading?: { icon?: string, ... },
entryPoint?: string,
packagerOpts?: {
hostType?: string,
dev?: boolean,
strict?: boolean,
minify?: boolean,
urlType?: string,
urlRandomness?: string,
lanType?: string,
...
},
xde?: boolean,
developer?: { tool?: string, ... },
bundleUrl: string,
debuggerHost?: string,
mainModuleName?: string,
logUrl?: string,
...
};
declare export type PlatformManifest = {
ios?: IOSManifest,
android?: AndroidManifest,
web?: WebManifest,
detach?: { scheme?: string, ... },
logUrl?: string,
scheme?: string,
hostUri?: string,
developer?: string,
...
};
declare export type NativeConstants = {
debugMode: boolean,
deviceName?: string,
deviceYearClass: number | null,
experienceUrl: string,
expoRuntimeVersion: string,
expoVersion: string,
isDetached?: boolean,
intentUri?: string,
installationId: string,
isDevice: boolean,
isHeadless: boolean,
linkingUri: string,
sessionId: string,
statusBarHeight: number,
systemVersion?: number,
systemFonts: Array<string>,
appOwnership: AppOwnership,
manifest: AppManifest,
platform?: PlatformManifest,
getWebViewUserAgentAsync: () => Promise<string | null>,
...
};
declare export default {
deviceId?: string,
linkingUrl?: string,
...
} & NativeConstants;
}
|
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import config from '../../config';
import { connect } from 'react-redux';
import { logout, loadAuthCookie, loadPersonalInfo } from 'redux/modules/auth';
import { load as loadGenre } from 'redux/modules/genre';
import { loadCartInformations, loadCartEntries } from 'redux/modules/cart';
import Helmet from 'react-helmet';
import { routeActions } from 'react-router-redux';
// import { asyncConnect } from 'redux-async-connect'; how to handle async redux connection
import ga from 'react-ga';
const logo = require('./../../img/logoAphextwin.png');
const NavbarLink = ({to, children}) => (
<Link key={to} to={to}>
{children}
</Link>
);
@connect(
state => ({
user: state.auth.user,
selectGenre: state.genre.selectGenre,
genres: state.genre.genres,
logged: state.auth.logged,
totalBasketItems: state.cart.totalBasketItems
}),
{logout, loadGenre, loadPersonalInfo, loadAuthCookie, loadCartInformations, loadCartEntries, pushState: routeActions.push})
/* Example of async connection in redux
@asyncConnect([{
promise: ({store: {dispatch, getState}}) => {
const promises = [];
if (!isInfoLoaded(getState())) {
promises.push(dispatch(loadInfo()));
}
if (!isAuthLoaded(getState())) {
promises.push(dispatch(loadAuth()));
}
return Promise.all(promises);
}
}])
*/
export default class App extends Component {
static propTypes = {
children: PropTypes.object.isRequired,
user: PropTypes.object,
genres: PropTypes.array,
selectGenre: PropTypes.object,
totalBasketItems: PropTypes.number,
logged: PropTypes.bool.isRequired,
logout: PropTypes.func.isRequired,
loadAuthCookie: PropTypes.func.isRequired,
loadPersonalInfo: PropTypes.func.isRequired,
loadGenre: PropTypes.func.isRequired,
loadCartInformations: PropTypes.func.isRequired,
pushState: PropTypes.func.isRequired,
loadCartEntries: PropTypes.func.isRequired,
location: PropTypes.shape({
pathname: PropTypes.string
}),
};
static contextTypes = {
store: PropTypes.object.isRequired
};
componentWillMount() {
// Load overall informations.
this.props.loadGenre();
// Authentication
this.props.loadAuthCookie();
if (this.props.logged) {
this.props.loadPersonalInfo();
this.props.loadCartInformations();
this.props.loadCartEntries();
}
}
componentDidMount() {
ga.initialize('UA-41334661-1', { debug: true });
ga.pageview(this.props.location.pathname);
}
componentWillReceiveProps(nextProps) {
const isLogged = this.props.logged;
const nextStateIsLogged = nextProps.logged;
if (isLogged === false && nextStateIsLogged === true) {
// I just got logged in succesffuly.
// If there were a query parameter next, move to that location,
// otherwise go to the user profile page.
this.props.loadPersonalInfo();
this.props.loadCartInformations();
this.props.loadCartEntries();
// process to change the route.
const redirectRoute = nextProps.location.query.next || '/me';
this.props.pushState(redirectRoute);
} else if (this.props.logged && !nextProps.logged) {
// logout
this.props.pushState(null, '/beta');
}
}
componentWillUpdate(nextProps) {
if (nextProps.location.pathname !== this.props.location.pathname) {
ga.pageview(nextProps.location.pathname);
}
}
handleLogout = (event) => {
event.preventDefault();
this.props.logout();
};
render() {
const {user, logged, genres, totalBasketItems} = this.props;
const styles = require('./less/aphextwin.less');
return (
<div className={styles}>
<Helmet {...config.app.head}/>
<nav className="navbar navbar-default navbar-fixed-top" role="navigation">
<div className="navbar-background"> </div>
<div className="navbar-header">
<button type="button" className="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<ul className="nav navbar-nav">
<li className="dropdownBackground dropdownBorder">
<Link to="/beta"> <img src={logo} /></Link>
<ul>
<li><NavbarLink to="/track/77">Go to track 77</NavbarLink></li>
<li><NavbarLink to="/track/80">Go to track 80</NavbarLink></li>
<li><NavbarLink to="/release/257">Go to release 257</NavbarLink></li>
<li><NavbarLink to="/tracklist/1">Tracklist</NavbarLink></li>
<li><NavbarLink to="/artist/58">Artist (Siwell)</NavbarLink></li>
<li><a href="#">Labels</a></li>
</ul>
</li>
</ul>
</div>
<div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul className="nav navbar-nav">
<li className="divider-vertical"></li>
<li className="dropdownBackground dropdownBorder">
<a href="#">{this.props.selectGenre && this.props.selectGenre.name || 'Genres'}
<span className="pull-right basic-pictosimply-down icon"></span></a>
<ul>
{genres && genres.map((genre) =>
<li>
<NavbarLink key={genre.id} to={'/genre/' + genre.id}>{genre.name}</NavbarLink>
</li>
)}
<li><a href="#">Techno</a></li>
<li><a href="#">House</a></li>
{user && <li><Link to="/chat">Chat</Link></li>}
<li><Link to="/widgets">Widgets</Link></li>
<li><Link to="/survey">Survey</Link></li>
<li><Link to="/about">About Us</Link></li>
<li><Link to="/me">User Page</Link></li>
</ul>
</li>
<li className="divider-vertical"></li>
<li>
<search_component>
<span className="basic-pictosearch icon"></span>
<input type="search" id="search" placeholder="Search..." />
</search_component>
</li>
</ul>
<ul className="nav navbar-nav navbar-right">
<li className="divider-vertical"></li>
<li className="navbar-text">
<icon className="basic-pictohead icon"></icon>
{!logged && <span><NavbarLink to="/login">Login</NavbarLink> or Register</span>}
{logged && <span><a onClick={::this.handleLogout}>Logout</a></span>}
</li>
<li className="divider-vertical"></li>
<li>
<Link to="/cart">
<span className="basic-pictoshop icon"></span>{totalBasketItems}
</Link>
</li>
</ul>
</div>
</nav>
<div className={styles.appContent}>
{this.props.children}
</div>
<footer className="row darkestrow">
<div className="pull-right col-xs-4 col-sm-4col-md-4 col-lg-4">
<a href="#"><img src={logo} /></a>
<p>2014 - 2016</p>
</div>
</footer>
</div>
);
}
}
|
const A = require('./A');
//class B extends A { }
module.exports = B;
|
import React from 'react';
class Square extends React.Component
{
render()
{
const { black } = this.props;
const backgroundColor = black ? 'black' : 'white';
const color = black ? 'white' : 'black';
return (
<div style={{
color,
backgroundColor,
width: '100%',
height: '100%'}}>
{this.props.children}
</div>
);
}
}
export default Square;
|
import fs from 'fs';
import gulp from 'gulp';
import gutil from 'gulp-util';
import jade from 'gulp-jade';
import rename from 'gulp-rename';
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import prodConfig from './webpack/prod.config';
import devConfig from './webpack/dev.config';
const port = 3000;
/*
* common tasks
*/
gulp.task('replace-webpack-code', () => {
const replaceTasks = [ {
from: './webpack/replace/JsonpMainTemplate.runtime.js',
to: './node_modules/webpack/lib/JsonpMainTemplate.runtime.js'
}, {
from: './webpack/replace/log-apply-result.js',
to: './node_modules/webpack/hot/log-apply-result.js'
} ];
replaceTasks.forEach(task => fs.writeFileSync(task.to, fs.readFileSync(task.from)));
});
/*
* dev tasks
*/
gulp.task('webpack-dev-server', () => {
let myConfig = Object.create(devConfig);
new WebpackDevServer(webpack(myConfig), {
contentBase: `https://localhost:${port}`,
publicPath: myConfig.output.publicPath,
stats: {colors: true},
hot: true,
historyApiFallback: true,
https: true
}).listen(port, 'localhost', (err) => {
if (err) {
throw new gutil.PluginError('webpack-dev-server', err);
}
gutil.log('[webpack-dev-server]', `listening at port ${port}`);
});
});
gulp.task('views:dev', () => {
gulp.src('./chrome/views/*.jade')
.pipe(jade({
locals: { env: 'dev' }
}))
.pipe(gulp.dest('./dev'));
});
gulp.task('copy:dev', () => {
gulp.src('./chrome/manifest.dev.json')
.pipe(rename('manifest.json'))
.pipe(gulp.dest('./dev'));
gulp.src('./chrome/assets/**/*').pipe(gulp.dest('./dev'));
});
/*
* build tasks
*/
gulp.task('webpack:build', (callback) => {
let myConfig = Object.create(prodConfig);
webpack(myConfig, (err, stats) => {
if (err) {
throw new gutil.PluginError('webpack:build', err);
}
gutil.log('[webpack:build]', stats.toString({ colors: true }));
callback();
});
});
gulp.task('views:build', () => {
gulp.src('./chrome/views/*.jade')
.pipe(jade({
locals: { env: 'prod' }
}))
.pipe(gulp.dest('./build'));
});
gulp.task('copy:build', () => {
gulp.src('./chrome/manifest.prod.json')
.pipe(rename('manifest.json'))
.pipe(gulp.dest('./build'));
gulp.src('./chrome/assets/**/*').pipe(gulp.dest('./build'));
});
gulp.task('default', ['replace-webpack-code', 'webpack-dev-server', 'views:dev', 'copy:dev']);
gulp.task('build', ['replace-webpack-code', 'webpack:build', 'views:build', 'copy:build']);
|
import CONST from '../../canvas-const';
import Browser from '../../browser-api';
import PixelateTool from './pixelate-tool';
/**
* Default Pixelate options.
*/
const defaultToolProps = {
label: 'Pixelate',
activeColor: CONST.DEFAULT_ACTIVE_COLOR,
activeOpacity: 0.3,
blocksize: 8
};
Browser.getFromWindow('redraw')
.registerTool(CONST.TOOL.PIXELATE, PixelateTool, defaultToolProps);
|
// @koala-append "custom/_minicart.js"
|
//>>built
define({instructions:"A k\u00f6zvetlen beilleszt\u00e9s le van tiltva. A b\u00f6ng\u00e9sz\u0151 szokv\u00e1nyos beilleszt\u00e9si billenty\u0171kombin\u00e1ci\u00f3j\u00e1val vagy men\u00fcparancs\u00e1val illessze be a tartalmat ebbe a p\u00e1rbesz\u00e9dpanelbe. Ha a beilleszteni k\u00edv\u00e1nt tartalom megfelel\u0151, kattintson a beilleszt\u00e9si gombra. A tartalom beilleszt\u00e9s\u00e9nek megszak\u00edt\u00e1s\u00e1hoz kattintson a M\u00e9gse gombra."});
|
const chai = require('chai');
const metadataValidator = require('../src/metadata/validator/MetadataValidator.js');
const assert = chai.assert;
describe('metadataValidator', function() {
it('validate - Required', function() {
let metadata = [
{
name: 'name',
required: true
}
];
let validation = metadataValidator.validate(metadata, { name: '' });
assert.equal(validation.name, 'Required');
});
it('validate - required - function', function() {
let metadata = [
{
name: 'name',
required: (m) => m.value > 500
}
];
let validation = metadataValidator.validate(metadata, { name: '', value: 1000 });
assert.equal(validation.name, 'Required');
});
it('validate - Required', function() {
let metadata = [
{
name: 'contact',
required: true,
type: 'entity',
fields: [
{
name: 'name',
required: true
}
]
}
];
let validation = metadataValidator.validate(metadata, { contact: { name: '' } });
assert.equal(validation.contact.name, 'Required');
});
});
|
/* global angular */
(function () {
'use strict';
function SummaryModalButtonController(bbModal) {
var ctrl = this;
ctrl.open = function (fullPage) {
bbModal.open(
{
controller: 'SummaryActionbarTestController as summaryCtrl',
templateUrl: 'demo/summaryactionbar/modalform.html'
},
{
fullPage: fullPage
}
);
};
}
SummaryModalButtonController.$inject = ['bbModal'];
angular.module('screenshots', ['sky'])
.controller('SummaryModalButtonController', SummaryModalButtonController)
.controller('SummaryActionbarTestController', angular.noop);
})();
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M20 5h-3.17l-1.24-1.35c-.37-.41-.91-.65-1.47-.65H9.88c-.56 0-1.1.24-1.48.65L7.17 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-8 13c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-9-1.25 2.75L8 13l2.75 1.25L12 17l1.25-2.75L16 13l-2.75-1.25z"
}), 'CameraEnhanceRounded');
exports.default = _default;
|
/*
+----------------------------------------------------------------------+
| BBT StackManager |
| --- StackManager --- |
| Module File |
+----------------------------------------------------------------------+
+----------------------------------------------------------------------+
| JavaScript |
+----------------------------------------------------------------------+
F. Quinonez - Created 2015-12-14
- Geant4 File
+----------------------------------------------------------------------+
| C++ |
+----------------------------------------------------------------------+
*/
define([ '../Random/JamesRandom' ], function( JamesRandom ){
"use strict";
function StackManager( args ){
this.fengine = args.engine || new JamesRandom({});
}
StackManager.Shoot = function( args ){
var sengine = args.engine || new JamesRandom({});
var x = sengine.Flat();
var bit = ( x > 0.5 )? 1: 0;
return bit;
};
StackManager.ShootArray = function( args ){
var ssize = args.size || 1;
var sengine = args.engine || new JamesRandom({});
// var svect = args.vect;
var argsShoot = { engine: sengine };
for( var i = 0; i < ssize; ++i ){
args.vect.push( StackManager.Shoot( argsShoot ) );
}
};
StackManager.prototype = {
constructor: StackManager,
Fire: function(){
var x = this.fengine.Flat();
var bit = ( x > 0.5 )? 1: 0;
return bit;
},
FireArray: function( /* size of vect */ size, /* Array */ vect ){
for( var i = 0; i < size; ++i ){
vect.push( this.Fire() );
}
}
}
return StackManager;
});
|
const { Test, Post, server } = require('./lib/server')
const { describe, it, expect } = global
const { afterAll, fail } = global
const _ = require('lodash')
afterAll(() => { server.close() })
describe('model', function () {
it('validate', async () => {
const data = {
title: 'a',
content: 'b',
test1: 'abc'
}
try {
await Post.forge().save(_.omit(data, ['title']))
fail('failed')
} catch (e) {
expect(e).toBeInstanceOf(Error)
}
const tmp1 = await Post.forge().save(data)
expect(tmp1.get('title')).toBe('a')
const tmp2 = await Post.findById(tmp1.id)
expect(tmp2.get('title')).toBe('a')
const tmp3 = await tmp2.save({content: 'c'})
expect(tmp3.get('content')).toBe('c')
const tmp4 = await tmp3.save(tmp3.toJSON())
expect(tmp4.get('content')).toBe(tmp3.get('content'))
})
it('unique', async () => {
const data = {
slug: 'a',
title: 'a',
content: 'b',
test1: 'abc'
}
const tmp0 = await Post.forge().save(data)
expect(tmp0.get('slug')).toBe(data.slug)
const tmp1 = await Post.findById(tmp0.id)
const tmp2 = await tmp1.save({title: 'b'})
expect(tmp2.get('title')).toBe('b')
const tmp3 = await tmp1.save({slug: data.slug, title: 'b'})
expect(tmp3.get('slug')).toBe(data.slug)
try {
await Post.forge().save(data)
fail('duplicate')
} catch (e) {
expect(e).toBeInstanceOf(Error)
}
})
it('format', async () => {
const data = {
slug: 'b',
title: 'a',
content: 'b',
password: 'abc',
test1: 'test1'
}
const hashed = '900150983cd24fb0d6963f7d28e17f72'
const tmp0 = await Post.forge().save(data)
expect(tmp0.get('password')).toBe('abc')
expect(tmp0.get('id')).not.toBeNull()
expect(tmp0.get('uuid')).toBeUndefined()
await tmp0.refresh()
expect(tmp0.get('password')).toBe(hashed)
expect(tmp0.get('uuid')).not.toBeUndefined()
await tmp0.save({title: 'b'})
expect(tmp0.get('title')).toBe('b')
expect(tmp0.get('password')).toBe(hashed)
})
it('onlyNew', async () => {
const data = {
title: '123'
}
const tmp0 = await Test.forge().save(data)
const id = tmp0.id
expect(tmp0.id).not.toBeUndefined()
await tmp0.save({title: '321'})
expect(tmp0.id).toBe(id)
})
it('object', async () => {
const object = {
'name': '颜色',
'value': 'color',
'options': [{
'name': '黑色',
'value': 'black'
}]
}
// 初始
const post = await Post.forge().save({
title: 'a',
content: 'b',
object,
test1: 'abc'
})
expect(post.get('object')).toEqual(object)
const fetched = await Post.findById(post.get('id'))
expect(fetched.get('object')).toEqual(object)
const saved = await fetched.save({title: 'b', object})
expect(saved.get('object')).toEqual(object)
try {
await saved.save({object: ['array']})
fail('native')
} catch (e) {
expect(e).toBeInstanceOf(Error)
}
expect(saved.get('object')).toEqual(object)
const data = _.pick(saved.toJSON(), ['title'])
// const data = { title: 'b' }
const nochange = await saved.save(data)
expect(nochange.get('object')).toEqual(object)
})
it('array', async () => {
const array = [{
'name': '颜色',
'value': 'color',
'options': [{
'name': '黑色',
'value': 'black'
}]
}]
const tmp0 = Post.forge({
title: 'a',
content: 'b',
array,
test1: 'abc'
})
expect(tmp0.get('array')).toEqual(array)
await tmp0.save()
expect(tmp0.get('array')).toEqual(array)
await tmp0.refresh()
expect(tmp0.get('array')).toEqual(array)
const tmp1 = await Post.findById(tmp0.id)
expect(tmp1.get('array')).toEqual(array)
await tmp1.save()
expect(tmp1.get('array')).toEqual(array)
await tmp1.save({title: 'b'})
expect(tmp1.get('array')).toEqual(array)
expect(tmp1.get('title')).toEqual('b')
const tmp2 = await tmp1.save(tmp1.toJSON())
expect(tmp2.get('array')).toEqual(array)
expect(tmp2.get('title')).toEqual('b')
const tmp3 = await tmp2.save({
title: 'c',
array: ['a', 'b']
})
await tmp3.refresh()
expect(tmp3.get('title')).toBe('c')
expect(tmp3.get('array')).toEqual(['a', 'b'])
})
})
|
function baseinputnumber(widget_id, url, skin, parameters)
{
// Will be using "self" throughout for the various flavors of "this"
// so for consistency ...
self = this
// Initialization
self.widget_id = widget_id
// Store on brightness or fallback to a default
// Parameters may come in useful later on
self.parameters = parameters
self.onChange = onChange
var callbacks = [
{"observable": "SliderValue", "action": "change", "callback": self.onChange},
]
// Define callbacks for entities - this model allows a widget to monitor multiple entities if needed
// Initial will be called when the dashboard loads and state has been gathered for the entity
// Update will be called every time an update occurs for that entity
self.OnStateAvailable = OnStateAvailable
self.OnStateUpdate = OnStateUpdate
if ("entity" in parameters)
{
var monitored_entities =
[
{"entity": parameters.entity, "initial": self.OnStateAvailable, "update": self.OnStateUpdate}
]
}
else
{
var monitored_entities = []
}
// Finally, call the parent constructor to get things moving
WidgetBase.call(self, widget_id, url, skin, parameters, monitored_entities, callbacks)
// Function Definitions
// The StateAvailable function will be called when
// self.state[<entity>] has valid information for the requested entity
// state is the initial state
// Methods
function OnStateAvailable(self, state)
{
self.state = state.state
self.minvalue = state.attributes.min
self.maxvalue = state.attributes.max
self.stepvalue = state.attributes.step
set_options(self, self.minvalue, self.maxvalue, self.stepvalue, state)
set_value(self, state)
}
function OnStateUpdate(self, state)
{
self.state = state.state
set_value(self, state)
}
function set_value(self, state)
{
value = self.map_state(self, state.state)
self.set_field(self, "SliderValue", value)
self.set_field(self, "sliderValue", self.format_number(self,value))
}
function onChange(self, state)
{
if (self.state != self.ViewModel.SliderValue())
{
self.state = self.ViewModel.SliderValue()
args = self.parameters.post_service
args["value"] = self.state
self.call_service(self, args)
}
}
function set_options(self, minvalue, maxvalue, stepvalue, state)
{
//alert(self.maxvalue)
self.set_field(self, "MinValue", minvalue)
self.set_field(self, "MaxValue", maxvalue)
self.set_field(self, "minValue", self.format_number(self,minvalue))
self.set_field(self, "maxValue", self.format_number(self,maxvalue))
self.set_field(self, "StepValue", stepvalue)
}
}
|
/**
* guiders.js
*
* version 1.1.1
*
* Developed at Optimizely. (www.optimizely.com)
* We make A/B testing you'll actually use.
*
* Released under the Apache License 2.0.
* www.apache.org/licenses/LICENSE-2.0.html
*
* Questions about Guiders or Optimizely?
* Email us at jeff+pickhardt@optimizely.com or hello@optimizely.com.
*
* Enjoy!
*/
var guiders = (function($){
var guiders = {
version: "1.1.1",
_defaultSettings: {
attachTo: null,
buttons: [{name: "Close"}],
buttonCustomHTML: "",
description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
isHashable: true,
onShow: null,
overlay: false,
position: 0, // 1-12 follows an analog clock, 0 means centered
offset: {
top: null,
left: null
},
title: "Sample title goes here",
width: 400,
xButton: false // this places a closer "x" button in the top right of the guider
},
_htmlSkeleton: [
"<div class='outty'>",
" <div class='outty_shadow'></div>",
" <div class='outty_container'>",
" <div class='outty_content'>",
" <h4 class='outty_title'></h4>",
" <div class='outty_close'></div>",
" <p class='outty_description'></p>",
" <div class='outty_buttons'></div>",
" </div>",
" </div>",
" ",
" <div class='outty_arrow'></div>",
"</div>"
].join(""),
_arrowShortSize: 28,
_arrowLongSize: 68,
_guiders: {},
_currentGuiderID: null,
_lastCreatedGuiderID: null,
_addButtons: function(myGuider) {
// Add buttons
var guiderButtonsContainer = myGuider.elem.find(".outty_buttons");
for (var i = myGuider.buttons.length-1; i >= 0; i--) {
var thisButton = myGuider.buttons[i];
var thisButtonElem = $("<a href=\"#\"></a>").append(
$("<span />").text(thisButton.name)
);
if (typeof thisButton.classString !== "undefined" && thisButton.classString !== null) {
thisButtonElem.addClass(thisButton.classString);
}
guiderButtonsContainer.append(thisButtonElem);
if (thisButton.onclick) {
thisButtonElem.bind("click", thisButton.onclick);
} else if (!thisButton.onclick && thisButton.name.toLowerCase() === "close") {
thisButtonElem.bind("click", function() { guiders.hideAll(); });
} else if (!thisButton.onclick && thisButton.name.toLowerCase() === "next") {
thisButtonElem.bind("click", function() { guiders.next(); });
}
}
if (myGuider.buttonCustomHTML !== "") {
var myCustomHTML = $(myGuider.buttonCustomHTML);
myGuider.elem.find(".outty_buttons").append(myCustomHTML);
}
},
_addXButton: function(myGuider) {
var xButtonContainer = myGuider.elem.find(".outty_close");
var xButton = $('<div></div>', {
"class" : "x_button",
"role" : "button" });
xButtonContainer.append(xButton);
$('<a href="#" class="close-button-blue"></a>').appendTo(xButton).click(function (e) {
guiders.hideAll();
e.stopPropagation();
e.preventDefault();
});
xButton.click(function() { guiders.hideAll(); });
},
_attach: function(myGuider) {
if (typeof myGuider.attachTo === "undefined" || myGuider === null) {
return;
}
var myHeight = myGuider.elem.innerHeight();
var myWidth = myGuider.elem.innerWidth();
if (myGuider.position === 0) {
myGuider.elem.css("position", "absolute");
myGuider.elem.css("top", ($(window).height() - myHeight) / 3 + $(window).scrollTop() + "px");
myGuider.elem.css("left", ($(window).width() - myWidth) / 2 + $(window).scrollLeft() + "px");
return;
}
myGuider.attachTo = $(myGuider.attachTo);
var base = myGuider.attachTo.offset();
var attachToHeight = myGuider.attachTo.innerHeight();
var attachToWidth = myGuider.attachTo.innerWidth();
var top = base.top;
var left = base.left;
var bufferOffset = 0.9 * guiders._arrowShortSize;
var offsetMap = { // Follows the form: [height, width]
1: [-bufferOffset - myHeight, attachToWidth - myWidth],
2: [0, bufferOffset + attachToWidth],
3: [attachToHeight/2 - myHeight/2, bufferOffset + attachToWidth],
4: [attachToHeight - myHeight, bufferOffset + attachToWidth],
5: [bufferOffset + attachToHeight, attachToWidth - myWidth],
6: [bufferOffset + attachToHeight, attachToWidth/2 - myWidth/2],
7: [bufferOffset + attachToHeight, 0],
8: [attachToHeight - myHeight, -myWidth - bufferOffset],
9: [attachToHeight/2 - myHeight/2, -myWidth - bufferOffset],
10: [0, -myWidth - bufferOffset],
11: [-bufferOffset - myHeight, 0],
12: [-bufferOffset - myHeight, attachToWidth/2 - myWidth/2]
};
offset = offsetMap[myGuider.position];
top += offset[0];
left += offset[1];
if (myGuider.offset.top !== null) {
top += myGuider.offset.top;
}
if (myGuider.offset.left !== null) {
left += myGuider.offset.left;
}
myGuider.elem.css({
"position": "absolute",
"top": top,
"left": left
});
},
_guiderById: function(id) {
if (typeof guiders._guiders[id] === "undefined") {
throw "Cannot find guider with id " + id;
}
return guiders._guiders[id];
},
_showOverlay: function() {
$("#outty_overlay").fadeIn("fast");
},
_hideOverlay: function() {
$("#outty_overlay").fadeOut("fast");
},
_initializeOverlay: function() {
if ($("#outty_overlay").length === 0) {
$("<div id=\"outty_overlay\"></div>").hide().appendTo("body");
}
},
_styleArrow: function(myGuider) {
var position = myGuider.position || 0;
if (!position) {
return;
}
var myGuiderArrow = $(myGuider.elem.find(".outty_arrow"));
var newClass = {
1: "outty_arrow_down",
2: "outty_arrow_left",
3: "outty_arrow_left",
4: "outty_arrow_left",
5: "outty_arrow_up",
6: "outty_arrow_up",
7: "outty_arrow_up",
8: "outty_arrow_right",
9: "outty_arrow_right",
10: "outty_arrow_right",
11: "outty_arrow_down",
12: "outty_arrow_down"
};
myGuiderArrow.addClass(newClass[position]);
var myHeight = myGuider.elem.innerHeight();
var myWidth = myGuider.elem.innerWidth();
var arrowOffset = guiders._arrowLongSize/2;
var positionMap = {
1: ["right", arrowOffset],
2: ["top", arrowOffset],
3: ["top", myHeight/2 - arrowOffset],
4: ["bottom", arrowOffset],
5: ["right", arrowOffset],
6: ["left", myWidth/2 - arrowOffset],
7: ["left", arrowOffset],
8: ["bottom", arrowOffset],
9: ["top", myHeight/2 - arrowOffset],
10: ["top", arrowOffset],
11: ["left", arrowOffset],
12: ["left", myWidth/2 - arrowOffset]
};
var position = positionMap[myGuider.position];
myGuiderArrow.css(position[0], position[1] + "px");
},
/**
* One way to show a guider to new users is to direct new users to a URL such as
* http://www.mysite.com/myapp#guider=welcome
*
* This can also be used to run guiders on multiple pages, by redirecting from
* one page to another, with the guider id in the hash tag.
*
* Alternatively, if you use a session variable or flash messages after sign up,
* you can add selectively add JavaScript to the page: "guiders.show('first');"
*/
_showIfHashed: function(myGuider) {
var GUIDER_HASH_TAG = "guider=";
var hashIndex = window.location.hash.indexOf(GUIDER_HASH_TAG);
if (hashIndex !== -1) {
var hashGuiderId = window.location.hash.substr(hashIndex + GUIDER_HASH_TAG.length);
if (myGuider.id.toLowerCase() === hashGuiderId.toLowerCase()) {
// Success!
guiders.show(myGuider.id);
}
}
},
next: function() {
var currentGuider = guiders._guiders[guiders._currentGuiderID];
if (typeof currentGuider === "undefined") {
return;
}
var nextGuiderId = currentGuider.next || null;
if (nextGuiderId !== null && nextGuiderId !== "") {
var myGuider = guiders._guiderById(nextGuiderId);
var omitHidingOverlay = myGuider.overlay ? true : false;
guiders.hideAll(omitHidingOverlay);
guiders.show(nextGuiderId);
}
},
createGuider: function(passedSettings) {
if (passedSettings === null || passedSettings === undefined) {
passedSettings = {};
}
// Extend those settings with passedSettings
myGuider = $.extend({}, guiders._defaultSettings, passedSettings);
myGuider.id = myGuider.id || String(Math.floor(Math.random() * 1000));
var guiderElement = $(guiders._htmlSkeleton);
myGuider.elem = guiderElement;
myGuider.elem.css("width", myGuider.width + "px");
guiderElement.find("h4.outty_title").html(myGuider.title);
guiderElement.find("p.outty_description").html(myGuider.description);
guiders._addButtons(myGuider);
if (myGuider.xButton) {
guiders._addXButton(myGuider);
}
guiderElement.hide();
guiderElement.appendTo("body");
guiderElement.attr("id", myGuider.id);
// Ensure myGuider.attachTo is a jQuery element.
if (typeof myGuider.attachTo !== "undefined" && myGuider !== null) {
guiders._attach(myGuider);
guiders._styleArrow(myGuider);
}
guiders._initializeOverlay();
guiders._guiders[myGuider.id] = myGuider;
guiders._lastCreatedGuiderID = myGuider.id;
/**
* If the URL of the current window is of the form
* http://www.myurl.com/mypage.html#guider=id
* then show this guider.
*/
if (myGuider.isHashable) {
guiders._showIfHashed(myGuider);
}
return guiders;
},
hideAll: function(omitHidingOverlay) {
$(".outty").fadeOut("fast");
if (typeof omitHidingOverlay !== "undefined" && omitHidingOverlay === true) {
// do nothing for now
} else {
guiders._hideOverlay();
}
return guiders;
},
show: function(id) {
if (!id && guiders._lastCreatedGuiderID) {
id = guiders._lastCreatedGuiderID;
}
var myGuider = guiders._guiderById(id);
if (myGuider.overlay) {
guiders._showOverlay();
}
guiders._attach(myGuider);
// You can use an onShow function to take some action before the guider is shown.
if (myGuider.onShow) {
myGuider.onShow(myGuider);
}
myGuider.elem.fadeIn("fast");
var windowHeight = $(window).height();
var scrollHeight = $(window).scrollTop();
var guiderOffset = myGuider.elem.offset();
var guiderElemHeight = myGuider.elem.height();
if (guiderOffset.top - scrollHeight < 0 ||
guiderOffset.top + guiderElemHeight + 40 > scrollHeight + windowHeight) {
window.scrollTo(0, Math.max(guiderOffset.top + (guiderElemHeight / 2) - (windowHeight / 2), 0));
}
guiders._currentGuiderID = id;
return guiders;
}
};
return guiders;
}).call(this, jQuery);
|
/* =========================================================
* bootstrap-datepicker.js
* Repo: https://github.com/eternicode/bootstrap-datepicker/
* Demo: http://eternicode.github.io/bootstrap-datepicker/
* Docs: http://bootstrap-datepicker.readthedocs.org/
* Forked from http://www.eyecon.ro/bootstrap-datepicker
* =========================================================
* Started by Stefan Petre; improvements by Andrew Rowls + contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================= */
(function($, undefined) {
var $window = $(window);
function UTCDate(){
return new Date(Date.UTC.apply(Date, arguments));
}
function UTCToday(){
var today = new Date();
return UTCDate(today.getFullYear(), today.getMonth(), today.getDate());
}
function alias(method){
return function(){
return this[method].apply(this, arguments);
};
}
var DateArray = (function(){
var extras = {
get: function(i){
return this.slice(i)[0];
},
contains: function(d){
// Array.indexOf is not cross-browser;
// $.inArray doesn't work with Dates
var val = d && d.valueOf();
for (var i=0, l=this.length; i<l; i++)
if (this[i].valueOf() === val)
return i;
return -1;
},
remove: function(i){
this.splice(i,1);
},
replace: function(new_array){
if (!new_array)
return;
if (!$.isArray(new_array))
new_array = [new_array];
this.clear();
this.push.apply(this, new_array);
},
clear: function(){
this.splice(0);
},
copy: function(){
var a = new DateArray();
a.replace(this);
return a;
}
};
return function(){
var a = [];
a.push.apply(a, arguments);
$.extend(a, extras);
return a;
};
})();
// Picker object
var Datepicker = function(element, options) {
this.dates = new DateArray();
this.viewDate = UTCToday();
this.focusDate = null;
this._process_options(options);
this.element = $(element);
this.isInline = false;
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on, .input-group-addon, .btn') : false;
this.hasInput = this.component && this.element.find('input').length;
if(this.component && this.component.length === 0)
this.component = false;
this.picker = $(DPGlobal.template);
this._buildEvents();
this._attachEvents();
if(this.isInline) {
this.picker.addClass('datepicker-inline').appendTo(this.element);
} else {
this.picker.addClass('datepicker-dropdown dropdown-menu');
}
if (this.o.rtl){
this.picker.addClass('datepicker-rtl');
}
this.viewMode = this.o.startView;
if (this.o.calendarWeeks)
this.picker.find('tfoot th.today')
.attr('colspan', function(i, val){
return parseInt(val) + 1;
});
this._allow_update = false;
this.setStartDate(this._o.startDate);
this.setEndDate(this._o.endDate);
this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);
this.fillDow();
this.fillMonths();
this._allow_update = true;
this.update();
this.showMode();
if(this.isInline) {
this.show();
}
};
Datepicker.prototype = {
constructor: Datepicker,
_process_options: function(opts){
// Store raw options for reference
this._o = $.extend({}, this._o, opts);
// Processed options
var o = this.o = $.extend({}, this._o);
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
var lang = o.language;
if (!dates[lang]) {
lang = lang.split('-')[0];
if (!dates[lang])
lang = defaults.language;
}
o.language = lang;
switch(o.startView){
case 2:
case 'decade':
o.startView = 2;
break;
case 1:
case 'year':
o.startView = 1;
break;
default:
o.startView = 0;
}
switch (o.minViewMode) {
case 1:
case 'months':
o.minViewMode = 1;
break;
case 2:
case 'years':
o.minViewMode = 2;
break;
default:
o.minViewMode = 0;
}
o.startView = Math.max(o.startView, o.minViewMode);
// true, false, or Number > 0
if (o.multidate !== true){
o.multidate = Number(o.multidate) || false;
if (o.multidate !== false)
o.multidate = Math.max(0, o.multidate);
else
o.multidate = 1;
}
o.multidateSeparator = String(o.multidateSeparator);
o.weekStart %= 7;
o.weekEnd = ((o.weekStart + 6) % 7);
var format = DPGlobal.parseFormat(o.format);
if (o.startDate !== -Infinity) {
if (!!o.startDate) {
if (o.startDate instanceof Date)
o.startDate = this._local_to_utc(this._zero_time(o.startDate));
else
o.startDate = DPGlobal.parseDate(o.startDate, format, o.language);
} else {
o.startDate = -Infinity;
}
}
if (o.endDate !== Infinity) {
if (!!o.endDate) {
if (o.endDate instanceof Date)
o.endDate = this._local_to_utc(this._zero_time(o.endDate));
else
o.endDate = DPGlobal.parseDate(o.endDate, format, o.language);
} else {
o.endDate = Infinity;
}
}
o.daysOfWeekDisabled = o.daysOfWeekDisabled||[];
if (!$.isArray(o.daysOfWeekDisabled))
o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/);
o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) {
return parseInt(d, 10);
});
var plc = String(o.orientation).toLowerCase().split(/\s+/g),
_plc = o.orientation.toLowerCase();
plc = $.grep(plc, function(word){
return (/^auto|left|right|top|bottom$/).test(word);
});
o.orientation = {x: 'auto', y: 'auto'};
if (!_plc || _plc === 'auto')
; // no action
else if (plc.length === 1){
switch(plc[0]){
case 'top':
case 'bottom':
o.orientation.y = plc[0];
break;
case 'left':
case 'right':
o.orientation.x = plc[0];
break;
}
}
else {
_plc = $.grep(plc, function(word){
return (/^left|right$/).test(word);
});
o.orientation.x = _plc[0] || 'auto';
_plc = $.grep(plc, function(word){
return (/^top|bottom$/).test(word);
});
o.orientation.y = _plc[0] || 'auto';
}
},
_events: [],
_secondaryEvents: [],
_applyEvents: function(evs){
for (var i=0, el, ch, ev; i<evs.length; i++){
el = evs[i][0];
if (evs[i].length === 2){
ch = undefined;
ev = evs[i][1];
}
else if (evs[i].length === 3){
ch = evs[i][1];
ev = evs[i][2];
}
el.on(ev, ch);
}
},
_unapplyEvents: function(evs){
for (var i=0, el, ev, ch; i<evs.length; i++){
el = evs[i][0];
if (evs[i].length === 2){
ch = undefined;
ev = evs[i][1];
}
else if (evs[i].length === 3){
ch = evs[i][1];
ev = evs[i][2];
}
el.off(ev, ch);
}
},
_buildEvents: function(){
if (this.isInput) { // single input
this._events = [
[this.element, {
focus: $.proxy(this.show, this),
keyup: $.proxy(function(e){
if ($.inArray(e.keyCode, [27,37,39,38,40,32,13,9]) === -1)
this.update();
}, this),
keydown: $.proxy(this.keydown, this)
}]
];
}
else if (this.component && this.hasInput){ // component: input + button
this._events = [
// For components that are not readonly, allow keyboard nav
[this.element.find('input'), {
focus: $.proxy(this.show, this),
keyup: $.proxy(function(e){
if ($.inArray(e.keyCode, [27,37,39,38,40,32,13,9]) === -1)
this.update();
}, this),
keydown: $.proxy(this.keydown, this)
}],
[this.component, {
click: $.proxy(this.show, this)
}]
];
}
else if (this.element.is('div')) { // inline datepicker
this.isInline = true;
}
else {
this._events = [
[this.element, {
click: $.proxy(this.show, this)
}]
];
}
this._events.push(
// Component: listen for blur on element descendants
[this.element, '*', {
blur: $.proxy(function(e){
this._focused_from = e.target;
}, this)
}],
// Input: listen for blur on element
[this.element, {
blur: $.proxy(function(e){
this._focused_from = e.target;
}, this)
}]
);
this._secondaryEvents = [
[this.picker, {
click: $.proxy(this.click, this)
}],
[$(window), {
resize: $.proxy(this.place, this)
}],
[$(document), {
'mousedown touchstart': $.proxy(function (e) {
// Clicked outside the datepicker, hide it
if (!(
this.element.is(e.target) ||
this.element.find(e.target).length ||
this.picker.is(e.target) ||
this.picker.find(e.target).length
)) {
this.hide();
}
}, this)
}]
];
},
_attachEvents: function(){
this._detachEvents();
this._applyEvents(this._events);
},
_detachEvents: function(){
this._unapplyEvents(this._events);
},
_attachSecondaryEvents: function(){
this._detachSecondaryEvents();
this._applyEvents(this._secondaryEvents);
},
_detachSecondaryEvents: function(){
this._unapplyEvents(this._secondaryEvents);
},
_trigger: function(event, altdate){
var date = altdate || this.dates.get(-1),
local_date = this._utc_to_local(date);
this.element.trigger({
type: event,
date: local_date,
dates: $.map(this.dates, this._utc_to_local),
format: $.proxy(function(ix, format){
if (arguments.length === 0){
ix = this.dates.length - 1;
format = this.o.format;
}
else if (typeof ix === 'string'){
format = ix;
ix = this.dates.length - 1;
}
format = format || this.o.format;
var date = this.dates.get(ix);
return DPGlobal.formatDate(date, format, this.o.language);
}, this)
});
},
show: function(){
if (!this.isInline)
this.picker.appendTo('body');
this.picker.show();
this.place();
this._attachSecondaryEvents();
this._trigger('show');
},
hide: function(){
if(this.isInline) return;
if (!this.picker.is(':visible')) return;
this.focusDate = null;
this.picker.hide().detach();
this._detachSecondaryEvents();
this.viewMode = this.o.startView;
this.showMode();
if (
this.o.forceParse &&
(
this.isInput && this.element.val() ||
this.hasInput && this.element.find('input').val()
)
)
this.setValue();
this._trigger('hide');
},
remove: function() {
this.hide();
this._detachEvents();
this._detachSecondaryEvents();
this.picker.remove();
delete this.element.data().datepicker;
if (!this.isInput) {
delete this.element.data().date;
}
},
_utc_to_local: function(utc){
return utc && new Date(utc.getTime() + (utc.getTimezoneOffset()*60000));
},
_local_to_utc: function(local){
return local && new Date(local.getTime() - (local.getTimezoneOffset()*60000));
},
_zero_time: function(local){
return local && new Date(local.getFullYear(), local.getMonth(), local.getDate());
},
_zero_utc_time: function(utc){
return utc && new Date(Date.UTC(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate()));
},
getDates: function(){
return $.map(this.dates, this._utc_to_local);
},
getUTCDates: function(){
return $.map(this.dates, function(d){ return new Date(d); });
},
getDate: function() {
return this._utc_to_local(this.getUTCDate());
},
getUTCDate: function() {
return new Date(this.dates.get(-1));
},
setDates: function() {
this.update.apply(this, arguments);
this._trigger('changeDate');
this.setValue();
},
setUTCDates: function() {
this.update.apply(this, $.map(arguments, this._utc_to_local));
this._trigger('changeDate');
this.setValue();
},
setDate: alias('setDates'),
setUTCDate: alias('setUTCDates'),
setValue: function() {
var formatted = this.getFormattedDate();
if (!this.isInput) {
if (this.component){
this.element.find('input').val(formatted).change();
}
} else {
this.element.val(formatted).change();
}
},
getFormattedDate: function(format) {
if (format === undefined)
format = this.o.format;
var lang = this.o.language;
return $.map(this.dates, function(d){
return DPGlobal.formatDate(d, format, lang);
}).join(this.o.multidateSeparator);
},
setStartDate: function(startDate){
this._process_options({startDate: startDate});
this.update();
this.updateNavArrows();
},
setEndDate: function(endDate){
this._process_options({endDate: endDate});
this.update();
this.updateNavArrows();
},
setDaysOfWeekDisabled: function(daysOfWeekDisabled){
this._process_options({daysOfWeekDisabled: daysOfWeekDisabled});
this.update();
this.updateNavArrows();
},
place: function(){
if(this.isInline) return;
var calendarWidth = this.picker.outerWidth(),
calendarHeight = this.picker.outerHeight(),
visualPadding = 10,
windowWidth = $window.width(),
windowHeight = $window.height(),
scrollTop = $window.scrollTop();
var zIndex = parseInt(this.element.parents().filter(function() {
return $(this).css('z-index') !== 'auto';
}).first().css('z-index'))+10;
var offset = this.component ? this.component.parent().offset() : this.element.offset();
var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(false);
var width = this.component ? this.component.outerWidth(true) : this.element.outerWidth(false);
var left = offset.left,
top = offset.top;
this.picker.removeClass(
'datepicker-orient-top datepicker-orient-bottom '+
'datepicker-orient-right datepicker-orient-left'
);
if (this.o.orientation.x !== 'auto') {
this.picker.addClass('datepicker-orient-' + this.o.orientation.x);
if (this.o.orientation.x === 'right')
left -= calendarWidth - width;
}
// auto x orientation is best-placement: if it crosses a window
// edge, fudge it sideways
else {
// Default to left
this.picker.addClass('datepicker-orient-left');
if (offset.left < 0)
left -= offset.left - visualPadding;
else if (offset.left + calendarWidth > windowWidth)
left = windowWidth - calendarWidth - visualPadding;
}
// auto y orientation is best-situation: top or bottom, no fudging,
// decision based on which shows more of the calendar
var yorient = this.o.orientation.y,
top_overflow, bottom_overflow;
if (yorient === 'auto') {
top_overflow = -scrollTop + offset.top - calendarHeight;
bottom_overflow = scrollTop + windowHeight - (offset.top + height + calendarHeight);
if (Math.max(top_overflow, bottom_overflow) === bottom_overflow)
yorient = 'top';
else
yorient = 'bottom';
}
this.picker.addClass('datepicker-orient-' + yorient);
if (yorient === 'top')
top += height;
else
top -= calendarHeight + parseInt(this.picker.css('padding-top'));
this.picker.css({
top: top,
left: left,
zIndex: zIndex
});
},
_allow_update: true,
update: function(){
if (!this._allow_update) return;
var oldDates = this.dates.copy(),
dates = [],
fromArgs = false;
if(arguments.length) {
$.each(arguments, $.proxy(function(i, date){
if (date instanceof Date)
date = this._local_to_utc(date);
dates.push(date);
}, this));
fromArgs = true;
} else {
dates = this.isInput
? this.element.val()
: this.element.data('date') || this.element.find('input').val();
if (dates && this.o.multidate)
dates = dates.split(this.o.multidateSeparator);
else
dates = [dates];
delete this.element.data().date;
}
dates = $.map(dates, $.proxy(function(date){
return DPGlobal.parseDate(date, this.o.format, this.o.language);
}, this));
dates = $.grep(dates, $.proxy(function(date){
return (
date < this.o.startDate ||
date > this.o.endDate ||
!date
);
}, this), true);
this.dates.replace(dates);
if (this.dates.length)
this.viewDate = new Date(this.dates.get(-1));
else if (this.viewDate < this.o.startDate)
this.viewDate = new Date(this.o.startDate);
else if (this.viewDate > this.o.endDate)
this.viewDate = new Date(this.o.endDate);
if (fromArgs) {
// setting date by clicking
this.setValue();
} else if (dates.length) {
// setting date by typing
if (String(oldDates) !== String(this.dates))
this._trigger('changeDate');
}
if (!this.dates.length && oldDates.length)
this._trigger('clearDate');
this.fill();
},
fillDow: function(){
var dowCnt = this.o.weekStart,
html = '<tr>';
if(this.o.calendarWeeks){
var cell = '<th class="cw"> </th>';
html += cell;
this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
}
while (dowCnt < this.o.weekStart + 7) {
html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function(){
var html = '',
i = 0;
while (i < 12) {
html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>';
}
this.picker.find('.datepicker-months td').html(html);
},
setRange: function(range){
if (!range || !range.length)
delete this.range;
else
this.range = $.map(range, function(d){ return d.valueOf(); });
this.fill();
},
getClassNames: function(date){
var cls = [],
year = this.viewDate.getUTCFullYear(),
month = this.viewDate.getUTCMonth(),
today = new Date();
if (date.getUTCFullYear() < year || (date.getUTCFullYear() === year && date.getUTCMonth() < month)) {
cls.push('old');
} else if (date.getUTCFullYear() > year || (date.getUTCFullYear() === year && date.getUTCMonth() > month)) {
cls.push('new');
}
if (this.focusDate && date.valueOf() === this.focusDate.valueOf())
cls.push('focused');
// Compare internal UTC date with local today, not UTC today
if (this.o.todayHighlight &&
date.getUTCFullYear() === today.getFullYear() &&
date.getUTCMonth() === today.getMonth() &&
date.getUTCDate() === today.getDate()) {
cls.push('today');
}
if (this.dates.contains(date) !== -1)
cls.push('active');
if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate ||
$.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) {
cls.push('disabled');
}
if (this.range){
if (date > this.range[0] && date < this.range[this.range.length-1]){
cls.push('range');
}
if ($.inArray(date.valueOf(), this.range) !== -1){
cls.push('selected');
}
}
return cls;
},
fill: function() {
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth(),
startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
tooltip;
this.picker.find('.datepicker-days thead th.datepicker-switch')
.text(dates[this.o.language].months[month]+' '+year);
this.picker.find('tfoot th.today')
.text(dates[this.o.language].today)
.toggle(this.o.todayBtn !== false);
this.picker.find('tfoot th.clear')
.text(dates[this.o.language].clear)
.toggle(this.o.clearBtn !== false);
this.updateNavArrows();
this.fillMonths();
var prevMonth = UTCDate(year, month-1, 28),
day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
prevMonth.setUTCDate(day);
prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7);
var nextMonth = new Date(prevMonth);
nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName;
while(prevMonth.valueOf() < nextMonth) {
if (prevMonth.getUTCDay() === this.o.weekStart) {
html.push('<tr>');
if(this.o.calendarWeeks){
// ISO 8601: First week contains first thursday.
// ISO also states week starts on Monday, but we can be more abstract here.
var
// Start of current week: based on weekstart/current date
ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
// Thursday of this week
th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
// First Thursday of year, year from thursday
yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5),
// Calendar week: ms between thursdays, div ms per day, div 7 days
calWeek = (th - yth) / 864e5 / 7 + 1;
html.push('<td class="cw">'+ calWeek +'</td>');
}
}
clsName = this.getClassNames(prevMonth);
clsName.push('day');
if (this.o.beforeShowDay !== $.noop){
var before = this.o.beforeShowDay(this._utc_to_local(prevMonth));
if (before === undefined)
before = {};
else if (typeof(before) === 'boolean')
before = {enabled: before};
else if (typeof(before) === 'string')
before = {classes: before};
if (before.enabled === false)
clsName.push('disabled');
if (before.classes)
clsName = clsName.concat(before.classes.split(/\s+/));
if (before.tooltip)
tooltip = before.tooltip;
}
clsName = $.unique(clsName);
html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>');
if (prevMonth.getUTCDay() === this.o.weekEnd) {
html.push('</tr>');
}
prevMonth.setUTCDate(prevMonth.getUTCDate()+1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
$.each(this.dates, function(i, d){
if (d.getUTCFullYear() === year)
months.eq(d.getUTCMonth()).addClass('active');
});
if (year < startYear || year > endYear) {
months.addClass('disabled');
}
if (year === startYear) {
months.slice(0, startMonth).addClass('disabled');
}
if (year === endYear) {
months.slice(endMonth+1).addClass('disabled');
}
html = '';
year = parseInt(year/10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
var years = $.map(this.dates, function(d){ return d.getUTCFullYear(); }),
classes;
for (var i = -1; i < 11; i++) {
classes = ['year'];
if (i === -1)
classes.push('old');
else if (i === 10)
classes.push('new');
if ($.inArray(year, years) !== -1)
classes.push('active');
if (year < startYear || year > endYear)
classes.push('disabled');
html += '<span class="' + classes.join(' ') + '">'+year+'</span>';
year += 1;
}
yearCont.html(html);
},
updateNavArrows: function() {
if (!this._allow_update) return;
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth();
switch (this.viewMode) {
case 0:
if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) {
this.picker.find('.prev').css({visibility: 'hidden'});
} else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) {
this.picker.find('.next').css({visibility: 'hidden'});
} else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
case 1:
case 2:
if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) {
this.picker.find('.prev').css({visibility: 'hidden'});
} else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) {
this.picker.find('.next').css({visibility: 'hidden'});
} else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
}
},
click: function(e) {
e.preventDefault();
var target = $(e.target).closest('span, td, th'),
year, month, day;
if (target.length === 1) {
switch(target[0].nodeName.toLowerCase()) {
case 'th':
switch(target[0].className) {
case 'datepicker-switch':
this.showMode(1);
break;
case 'prev':
case 'next':
var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1);
switch(this.viewMode){
case 0:
this.viewDate = this.moveMonth(this.viewDate, dir);
this._trigger('changeMonth', this.viewDate);
break;
case 1:
case 2:
this.viewDate = this.moveYear(this.viewDate, dir);
if (this.viewMode === 1)
this._trigger('changeYear', this.viewDate);
break;
}
this.fill();
break;
case 'today':
var date = new Date();
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
this.showMode(-2);
var which = this.o.todayBtn === 'linked' ? null : 'view';
this._setDate(date, which);
break;
case 'clear':
var element;
if (this.isInput)
element = this.element;
else if (this.component)
element = this.element.find('input');
if (element)
element.val("").change();
this.update();
this._trigger('changeDate');
if (this.o.autoclose)
this.hide();
break;
}
break;
case 'span':
if (!target.is('.disabled')) {
this.viewDate.setUTCDate(1);
if (target.is('.month')) {
day = 1;
month = target.parent().find('span').index(target);
year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
this._trigger('changeMonth', this.viewDate);
if (this.o.minViewMode === 1) {
this._setDate(UTCDate(year, month, day));
}
} else {
day = 1;
month = 0;
year = parseInt(target.text(), 10)||0;
this.viewDate.setUTCFullYear(year);
this._trigger('changeYear', this.viewDate);
if (this.o.minViewMode === 2) {
this._setDate(UTCDate(year, month, day));
}
}
this.showMode(-1);
this.fill();
}
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')){
day = parseInt(target.text(), 10)||1;
year = this.viewDate.getUTCFullYear();
month = this.viewDate.getUTCMonth();
if (target.is('.old')) {
if (month === 0) {
month = 11;
year -= 1;
} else {
month -= 1;
}
} else if (target.is('.new')) {
if (month === 11) {
month = 0;
year += 1;
} else {
month += 1;
}
}
this._setDate(UTCDate(year, month, day));
}
break;
}
}
if (this.picker.is(':visible') && this._focused_from){
$(this._focused_from).focus();
}
delete this._focused_from;
},
_toggle_multidate: function( date ) {
var ix = this.dates.contains(date);
if (!date){
this.dates.clear();
}
else if (ix !== -1){
this.dates.remove(ix);
}
else{
this.dates.push(date);
}
if (typeof this.o.multidate === 'number')
while (this.dates.length > this.o.multidate)
this.dates.remove(0);
},
_setDate: function(date, which){
if (!which || which === 'date')
this._toggle_multidate(date && new Date(date));
if (!which || which === 'view')
this.viewDate = date && new Date(date);
this.fill();
this.setValue();
this._trigger('changeDate');
var element;
if (this.isInput) {
element = this.element;
} else if (this.component){
element = this.element.find('input');
}
if (element) {
element.change();
}
if (this.o.autoclose && (!which || which === 'date')) {
this.hide();
}
},
moveMonth: function(date, dir){
if (!date) return undefined;
if (!dir) return date;
var new_date = new Date(date.valueOf()),
day = new_date.getUTCDate(),
month = new_date.getUTCMonth(),
mag = Math.abs(dir),
new_month, test;
dir = dir > 0 ? 1 : -1;
if (mag === 1){
test = dir === -1
// If going back one month, make sure month is not current month
// (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
? function(){ return new_date.getUTCMonth() === month; }
// If going forward one month, make sure month is as expected
// (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
: function(){ return new_date.getUTCMonth() !== new_month; };
new_month = month + dir;
new_date.setUTCMonth(new_month);
// Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
if (new_month < 0 || new_month > 11)
new_month = (new_month + 12) % 12;
} else {
// For magnitudes >1, move one month at a time...
for (var i=0; i<mag; i++)
// ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
new_date = this.moveMonth(new_date, dir);
// ...then reset the day, keeping it in the new month
new_month = new_date.getUTCMonth();
new_date.setUTCDate(day);
test = function(){ return new_month !== new_date.getUTCMonth(); };
}
// Common date-resetting loop -- if date is beyond end of month, make it
// end of month
while (test()){
new_date.setUTCDate(--day);
new_date.setUTCMonth(new_month);
}
return new_date;
},
moveYear: function(date, dir){
return this.moveMonth(date, dir*12);
},
dateWithinRange: function(date){
return date >= this.o.startDate && date <= this.o.endDate;
},
keydown: function(e){
if (this.picker.is(':not(:visible)')){
if (e.keyCode === 27) // allow escape to hide and re-show picker
this.show();
return;
}
var dateChanged = false,
dir, newDate, newViewDate,
focusDate = this.focusDate || this.viewDate;
switch(e.keyCode){
case 27: // escape
if (this.focusDate){
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.fill();
}
else
this.hide();
e.preventDefault();
break;
case 37: // left
case 39: // right
if (!this.o.keyboardNavigation) break;
dir = e.keyCode === 37 ? -1 : 1;
if (e.ctrlKey){
newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveYear(focusDate, dir);
this._trigger('changeYear', this.viewDate);
} else if (e.shiftKey){
newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveMonth(focusDate, dir);
this._trigger('changeMonth', this.viewDate);
} else {
newDate = new Date(this.dates.get(-1) || UTCToday());
newDate.setUTCDate(newDate.getUTCDate() + dir);
newViewDate = new Date(focusDate);
newViewDate.setUTCDate(focusDate.getUTCDate() + dir);
}
if (this.dateWithinRange(newDate)){
this.focusDate = this.viewDate = newViewDate;
this.setValue();
this.fill();
e.preventDefault();
}
break;
case 38: // up
case 40: // down
if (!this.o.keyboardNavigation) break;
dir = e.keyCode === 38 ? -1 : 1;
if (e.ctrlKey){
newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveYear(focusDate, dir);
this._trigger('changeYear', this.viewDate);
} else if (e.shiftKey){
newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveMonth(focusDate, dir);
this._trigger('changeMonth', this.viewDate);
} else {
newDate = new Date(this.dates.get(-1) || UTCToday());
newDate.setUTCDate(newDate.getUTCDate() + dir * 7);
newViewDate = new Date(focusDate);
newViewDate.setUTCDate(focusDate.getUTCDate() + dir * 7);
}
if (this.dateWithinRange(newDate)){
this.focusDate = this.viewDate = newViewDate;
this.setValue();
this.fill();
e.preventDefault();
}
break;
case 32: // spacebar
// Spacebar is used in manually typing dates in some formats.
// As such, its behavior should not be hijacked.
break;
case 13: // enter
focusDate = this.focusDate || this.dates.get(-1) || this.viewDate;
this._toggle_multidate(focusDate);
dateChanged = true;
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.setValue();
this.fill();
if (this.picker.is(':visible')){
e.preventDefault();
if (this.o.autoclose)
this.hide();
}
break;
case 9: // tab
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.fill();
this.hide();
break;
}
if (dateChanged){
if (this.dates.length)
this._trigger('changeDate');
else
this._trigger('clearDate');
var element;
if (this.isInput) {
element = this.element;
} else if (this.component){
element = this.element.find('input');
}
if (element) {
element.change();
}
}
},
showMode: function(dir) {
if (dir) {
this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir));
}
this.picker
.find('>div')
.hide()
.filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName)
.css('display', 'block');
this.updateNavArrows();
}
};
var DateRangePicker = function(element, options){
this.element = $(element);
this.inputs = $.map(options.inputs, function(i){ return i.jquery ? i[0] : i; });
delete options.inputs;
$(this.inputs)
.datepicker(options)
.bind('changeDate', $.proxy(this.dateUpdated, this));
this.pickers = $.map(this.inputs, function(i){ return $(i).data('datepicker'); });
this.updateDates();
};
DateRangePicker.prototype = {
updateDates: function(){
this.dates = $.map(this.pickers, function(i){ return i.getUTCDate(); });
this.updateRanges();
},
updateRanges: function(){
var range = $.map(this.dates, function(d){ return d.valueOf(); });
$.each(this.pickers, function(i, p){
p.setRange(range);
});
},
dateUpdated: function(e){
// `this.updating` is a workaround for preventing infinite recursion
// between `changeDate` triggering and `setUTCDate` calling. Until
// there is a better mechanism.
if (this.updating)
return;
this.updating = true;
var dp = $(e.target).data('datepicker'),
new_date = dp.getUTCDate(),
i = $.inArray(e.target, this.inputs),
l = this.inputs.length;
if (i === -1)
return;
$.each(this.pickers, function(i, p){
if (!p.getUTCDate())
p.setUTCDate(new_date);
});
if (new_date < this.dates[i]){
// Date being moved earlier/left
while (i>=0 && new_date < this.dates[i]){
this.pickers[i--].setUTCDate(new_date);
}
}
else if (new_date > this.dates[i]){
// Date being moved later/right
while (i<l && new_date > this.dates[i]){
this.pickers[i++].setUTCDate(new_date);
}
}
this.updateDates();
delete this.updating;
},
remove: function(){
$.map(this.pickers, function(p){ p.remove(); });
delete this.element.data().datepicker;
}
};
function opts_from_el(el, prefix){
// Derive options from element data-attrs
var data = $(el).data(),
out = {}, inkey,
replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])');
prefix = new RegExp('^' + prefix.toLowerCase());
function re_lower(_,a){
return a.toLowerCase();
}
for (var key in data)
if (prefix.test(key)){
inkey = key.replace(replace, re_lower);
out[inkey] = data[key];
}
return out;
}
function opts_from_locale(lang){
// Derive options from locale plugins
var out = {};
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
if (!dates[lang]) {
lang = lang.split('-')[0];
if (!dates[lang])
return;
}
var d = dates[lang];
$.each(locale_opts, function(i,k){
if (k in d)
out[k] = d[k];
});
return out;
}
var old = $.fn.datepicker;
$.fn.datepicker = function ( option ) {
var args = Array.apply(null, arguments);
args.shift();
var internal_return;
this.each(function () {
var $this = $(this),
data = $this.data('datepicker'),
options = typeof option === 'object' && option;
if (!data) {
var elopts = opts_from_el(this, 'date'),
// Preliminary otions
xopts = $.extend({}, defaults, elopts, options),
locopts = opts_from_locale(xopts.language),
// Options priority: js args, data-attrs, locales, defaults
opts = $.extend({}, defaults, locopts, elopts, options);
if ($this.is('.input-daterange') || opts.inputs){
var ropts = {
inputs: opts.inputs || $this.find('input').toArray()
};
$this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts))));
}
else{
$this.data('datepicker', (data = new Datepicker(this, opts)));
}
}
if (typeof option === 'string' && typeof data[option] === 'function') {
internal_return = data[option].apply(data, args);
if (internal_return !== undefined)
return false;
}
});
if (internal_return !== undefined)
return internal_return;
else
return this;
};
var defaults = $.fn.datepicker.defaults = {
autoclose: false,
beforeShowDay: $.noop,
calendarWeeks: false,
clearBtn: false,
daysOfWeekDisabled: [],
endDate: Infinity,
forceParse: true,
format: 'mm/dd/yyyy',
keyboardNavigation: true,
language: 'en',
minViewMode: 0,
multidate: false,
multidateSeparator: ',',
orientation: "auto",
rtl: false,
startDate: -Infinity,
startView: 0,
todayBtn: false,
todayHighlight: false,
weekStart: 0
};
var locale_opts = $.fn.datepicker.locale_opts = [
'format',
'rtl',
'weekStart'
];
$.fn.datepicker.Constructor = Datepicker;
var dates = $.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today",
clear: "Clear"
}
};
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
parseFormat: function(format){
// IE treats \0 as a string end in inputs (truncating the value),
// so it's a bad format delimiter, anyway
var separators = format.replace(this.validParts, '\0').split('\0'),
parts = format.match(this.validParts);
if (!separators || !separators.length || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separators: separators, parts: parts};
},
parseDate: function(date, format, language) {
if (!date)
return undefined;
if (date instanceof Date) return date;
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
var part_re = /([\-+]\d+)([dmwy])/,
parts = date.match(/([\-+]\d+)([dmwy])/g),
part, dir, i;
if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) {
date = new Date();
for (i=0; i<parts.length; i++) {
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch(part[2]){
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
}
parts = date && date.match(this.nonpunctuation) || [];
date = new Date();
var parsed = {},
setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
setters_map = {
yyyy: function(d,v){ return d.setUTCFullYear(v); },
yy: function(d,v){ return d.setUTCFullYear(2000+v); },
m: function(d,v){
if (isNaN(d))
return d;
v -= 1;
while (v<0) v += 12;
v %= 12;
d.setUTCMonth(v);
while (d.getUTCMonth() !== v)
d.setUTCDate(d.getUTCDate()-1);
return d;
},
d: function(d,v){ return d.setUTCDate(v); }
},
val, filtered;
setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
setters_map['dd'] = setters_map['d'];
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
var fparts = format.parts.slice();
// Remove noop parts
if (parts.length !== fparts.length) {
fparts = $(fparts).filter(function(i,p){
return $.inArray(p, setters_order) !== -1;
}).toArray();
}
// Process remainder
function match_part(){
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m === p;
}
if (parts.length === fparts.length) {
var cnt;
for (i=0, cnt = fparts.length; i < cnt; i++) {
val = parseInt(parts[i], 10);
part = fparts[i];
if (isNaN(val)) {
switch(part) {
case 'MM':
filtered = $(dates[language].months).filter(match_part);
val = $.inArray(filtered[0], dates[language].months) + 1;
break;
case 'M':
filtered = $(dates[language].monthsShort).filter(match_part);
val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
break;
}
}
parsed[part] = val;
}
var _date, s;
for (i=0; i<setters_order.length; i++){
s = setters_order[i];
if (s in parsed && !isNaN(parsed[s])){
_date = new Date(date);
setters_map[s](_date, parsed[s]);
if (!isNaN(_date))
date = _date;
}
}
}
return date;
},
formatDate: function(date, format, language){
if (!date)
return '';
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
var val = {
d: date.getUTCDate(),
D: dates[language].daysShort[date.getUTCDay()],
DD: dates[language].days[date.getUTCDay()],
m: date.getUTCMonth() + 1,
M: dates[language].monthsShort[date.getUTCMonth()],
MM: dates[language].months[date.getUTCMonth()],
yy: date.getUTCFullYear().toString().substring(2),
yyyy: date.getUTCFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
date = [];
var seps = $.extend([], format.separators);
for (var i=0, cnt = format.parts.length; i <= cnt; i++) {
if (seps.length)
date.push(seps.shift());
date.push(val[format.parts[i]]);
}
return date.join('');
},
headTemplate: '<thead>'+
'<tr>'+
'<th class="prev">«</th>'+
'<th colspan="5" class="datepicker-switch"></th>'+
'<th class="next">»</th>'+
'</tr>'+
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
footTemplate: '<tfoot>'+
'<tr>'+
'<th colspan="7" class="today"></th>'+
'</tr>'+
'<tr>'+
'<th colspan="7" class="clear"></th>'+
'</tr>'+
'</tfoot>'
};
DPGlobal.template = '<div class="datepicker">'+
'<div class="datepicker-days">'+
'<table class=" table-condensed">'+
DPGlobal.headTemplate+
'<tbody></tbody>'+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-months">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'</div>';
$.fn.datepicker.DPGlobal = DPGlobal;
/* DATEPICKER NO CONFLICT
* =================== */
$.fn.datepicker.noConflict = function(){
$.fn.datepicker = old;
return this;
};
/* DATEPICKER DATA-API
* ================== */
$(document).on(
'focus.datepicker.data-api click.datepicker.data-api',
'[data-provide="datepicker"]',
function(e){
var $this = $(this);
if ($this.data('datepicker')) return;
e.preventDefault();
// component click requires us to explicitly show it
$this.datepicker('show');
}
);
$(function(){
$('[data-provide="datepicker-inline"]').datepicker();
});
}( window.jQuery ));
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { Plugin, CordovaInstance } from './plugin';
import { Observable } from 'rxjs/Observable';
/**
* @name ThemeableBrowser
* @description
* In-app browser that allows styling.
*
* @usage
* ```
* import { ThemeableBrowser } from 'ionic-native';
*
* // can add options from the original InAppBrowser in a JavaScript object form (not string)
* // This options object also takes additional parameters introduced by the ThemeableBrowser plugin
* // This example only shows the additional parameters for ThemeableBrowser
* // Note that that `image` and `imagePressed` values refer to resources that are stored in your app
* let options = {
* statusbar: {
* color: '#ffffffff'
* },
* toolbar: {
* height: 44,
* color: '#f0f0f0ff'
* },
* title: {
* color: '#003264ff',
* showPageTitle: true
* },
* backButton: {
* image: 'back',
* imagePressed: 'back_pressed',
* align: 'left',
* event: 'backPressed'
* },
* forwardButton: {
* image: 'forward',
* imagePressed: 'forward_pressed',
* align: 'left',
* event: 'forwardPressed'
* },
* closeButton: {
* image: 'close',
* imagePressed: 'close_pressed',
* align: 'left',
* event: 'closePressed'
* },
* customButtons: [
* {
* image: 'share',
* imagePressed: 'share_pressed',
* align: 'right',
* event: 'sharePressed'
* }
* ],
* menu: {
* image: 'menu',
* imagePressed: 'menu_pressed',
* title: 'Test',
* cancel: 'Cancel',
* align: 'right',
* items: [
* {
* event: 'helloPressed',
* label: 'Hello World!'
* },
* {
* event: 'testPressed',
* label: 'Test!'
* }
* ]
* },
* backButtonCanClose: true
* };
*
* let browser = new ThemeableBrowser('https://ionic.io', '_blank', options);
*
* ```
* We suggest that you refer to the plugin's repository for additional information on usage that may not be covered here.
*/
export var ThemeableBrowser = (function () {
function ThemeableBrowser(url, target, styleOptions) {
try {
this._objectInstance = cordova.ThemeableBrowser.open(url, target, styleOptions);
}
catch (e) {
window.open(url);
console.warn('Native: ThemeableBrowser is not installed or you are running on a browser. Falling back to window.open, all instance methods will NOT work.');
}
}
/**
* Displays an browser window that was opened hidden. Calling this has no effect
* if the browser was already visible.
*/
ThemeableBrowser.prototype.show = function () { };
/**
* Closes the browser window.
*/
ThemeableBrowser.prototype.close = function () { };
/**
* Reloads the current page
*/
ThemeableBrowser.prototype.reload = function () { };
/**
* Injects JavaScript code into the browser window.
* @param script Details of the script to run, specifying either a file or code key.
* @returns {Promise<any>}
*/
ThemeableBrowser.prototype.executeScript = function (script) { return; };
/**
* Injects CSS into the browser window.
* @param css Details of the script to run, specifying either a file or code key.
* @returns {Promise<any>}
*/
ThemeableBrowser.prototype.insertCss = function (css) { return; };
/**
* A method that allows you to listen to events happening in the browser.
* Available events are: `ThemeableBrowserError`, `ThemeableBrowserWarning`, `critical`, `loadfail`, `unexpected`, `undefined`
* @param event Event name
* @returns {Observable<InAppBrowserEvent>} Returns back an observable that will listen to the event on subscribe, and will stop listening to the event on unsubscribe.
*/
ThemeableBrowser.prototype.on = function (event) {
var _this = this;
return new Observable(function (observer) {
_this._objectInstance.addEventListener(event, observer.next.bind(observer));
return function () { return _this._objectInstance.removeEventListener(event, observer.next.bind(observer)); };
});
};
__decorate([
CordovaInstance({ sync: true })
], ThemeableBrowser.prototype, "show", null);
__decorate([
CordovaInstance({ sync: true })
], ThemeableBrowser.prototype, "close", null);
__decorate([
CordovaInstance({ sync: true })
], ThemeableBrowser.prototype, "reload", null);
__decorate([
CordovaInstance()
], ThemeableBrowser.prototype, "executeScript", null);
__decorate([
CordovaInstance()
], ThemeableBrowser.prototype, "insertCss", null);
ThemeableBrowser = __decorate([
Plugin({
pluginName: 'ThemeableBrowser',
plugin: 'cordova-plugin-themeablebrowser',
pluginRef: 'cordova.ThemeableBrowser',
repo: 'https://github.com/initialxy/cordova-plugin-themeablebrowser'
})
], ThemeableBrowser);
return ThemeableBrowser;
}());
//# sourceMappingURL=themeable-browser.js.map
|
/*
* Copyright (c) 2008-2014 The Open Source Geospatial Foundation
*
* Published under the BSD license.
* See https://github.com/geoext/geoext2/blob/master/license.txt for the full
* text of the license.
*/
/*
* @include OpenLayers/Format/JSON.js
* @include OpenLayers/Format/GeoJSON.js
* @include OpenLayers/Util.js
* @include OpenLayers/Geometry/Point.js
* @include OpenLayers/Feature/Vector.js
* @include OpenLayers/Layer/Vector.js
* @requires GeoExt/Version.js
*/
/**
* Provides an interface to a Mapfish or GeoServer print module. For printing,
* one or more instances of {@link GeoExt.data.PrintPage} are also required
* to tell the PrintProvider about the scale and extent (and optionally
* rotation) of the page(s) we want to print.
*
* Minimal code to print as much of the current map extent as possible as
* soon as the print service capabilities are loaded, using the first layout
* reported by the print service:
*
* Example:
*
* var mapPanel = Ext.create('GeoExt.panel.Map', {
* renderTo: "mappanel",
* layers: [new OpenLayers.Layer.WMS("wms", "/geoserver/wms",
* {layers: "topp:tasmania_state_boundaries"})],
* center: [146.56, -41.56],
* zoom: 7
* });
* var printProvider = Ext.create('GeoExt.data.MapfishPrintProvider', {
* url: "/geoserver/pdf",
* listeners: {
* "loadcapabilities": function() {
* var printPage = Ext.create('GeoExt.data.PrintPage', {
* printProvider: printProvider
* });
* printPage.fit(mapPanel, true);
* printProvider.print(mapPanel, printPage);
* }
* }
* });
*
* @class GeoExt.data.MapfishPrintProvider
*/
Ext.define('GeoExt.data.MapfishPrintProvider', {
extend: 'Ext.util.Observable',
requires: [
'Ext.data.JsonStore',
'GeoExt.Version'
],
/**
* Base url of the print service. Will always have a trailing "/".
*
* @private
* @property {String} url
*/
url: null,
/**
* If set to true, the capabilities will be loaded upon instance creation,
* and `loadCapabilities` does not need to be called manually. Setting this
* when `capabilities` and no `url` is provided has no effect. Default is
* false.
*
* @cfg {Boolean} autoLoad
*/
/**
* Capabilities of the print service. Only required if `url`
* is not provided. This is the object returned by the `info.json`
* endpoint of the print service, and is usually obtained by including a
* script tag pointing to http://path/to/printservice/info.json?var=myvar
* in the head of the html document, making the capabilities accessible as
* `window.myvar`.
*
* This property should be used when no local print service or proxy is
* available, or when you do not listen for the `loadcapabilities`
* events before creating components that require the PrintProvider's
* capabilities to be available.
*
* @cfg {Object} capabilities
*/
/**
* Capabilities as returned from the print service.
*
* @private
* @property {Object} capabilities
*/
capabilities: null,
/**
* Either `POST` or `GET` (case-sensitive). Method to use when sending print
* requests to the servlet. If the print service is at the same origin as
* the application (or accessible via proxy), then `POST` is recommended.
* Use `GET` when accessing a remote print service with no proxy available,
* but expect issues with character encoding and URLs exceeding the maximum
* length. Default is `POST`.
*
* @cfg {String} method
*/
/**
* Either `POST` or `GET` (case-sensitive). Method to use when sending print
* requests to the servlet.
*
* @property {String} method
* @private
*/
method: "POST",
/**
* The encoding to set in the headers when requesting the print service.
* Prevent character encoding issues, especially when using IE. Default is
* retrieved from document `charset` or `characterSet` if existing
* or `UTF-8` if not.
*
* @cfg {String} encoding
*/
encoding: document.charset || document.characterSet || "UTF-8",
/**
* Timeout of the POST Ajax request used for the print request (in
* milliseconds). Default of 30 seconds. Has no effect if `method` is set to
* `GET`.
*
* @cfg {Number} timeout
*/
timeout: 30000,
/**
* Key-value pairs of custom data to be sent to the print service. This is
* e.g. useful for complex layout definitions on the server side that
* require additional parameters. Optional.
*
* @property {Object} customParams
*/
customParams: null,
/**
* Key-value pairs of base params to be add to every request to the service.
* Optional.
*
* @cfg {Object} baseParams
*/
/**
* Read-only. A store representing the scales available.
*
* Fields of records in this store:
*
* * name - `String` the name of the scale
* * value - `Float` the scale denominator
*
* @property {Ext.data.JsonStore} scales
*/
scales: null,
/**
* Read-only. A store representing the dpis available.
*
* Fields of records in this store:
*
* * name - `String` the name of the dpi
* * value - `Float` the dots per inch
*
* @property {Ext.data.JsonStore} dpis
*/
dpis: null,
/**
* Read-only. A store representing the layouts available.
*
* Fields of records in this store:
*
* * name - `String` the name of the layout
* * size - `Object` width and height of the map in points
* * rotation - `Boolean` indicates if rotation is supported
*
* @property {Ext.data.JsonStore} layouts
*/
layouts: null,
/**
* The record for the currently used resolution. Read-only, use `#setDpi` to
* set the value.
*
* @property {Ext.data.Record} dpi
*/
dpi: null,
/**
* The record of the currently used layout. Read-only, use `#setLayout` to
* set the value.
*
* @property {Ext.data.Record} layout
*/
layout: null,
/**
* Triggered when the capabilities have finished loading. This
* event will only fire when `#capabilities` is not configured.
*
* Listener arguments:
*
* * printProvider - {@link GeoExt.data.MapfishPrintProvider} this
* PrintProvider.
* * capabilities - `Object` the capabilities.
*
* @event loadcapabilities
*/
/**
* Triggered when the layout is changed.
*
* Listener arguments:
*
* * printProvider - {@link GeoExt.data.MapfishPrintProvider} this
* PrintProvider.
* * layout - {@link Ext.data.Record} the new layout.
*
* @event layoutchange
*/
/**
* Triggered when the dpi value is changed.
*
* Listener arguments:
*
* * printProvider - {@link GeoExt.data.MapfishPrintProvider} this
* PrintProvider.
* * dpi - {@link Ext.data.Record} the new dpi record.
*
* @event dpichange
*/
// TODO: rename this event to beforeencode
/**
* Triggered when the print method is called.
*
* Listener arguments:
*
* * printProvider - {@link GeoExt.data.MapfishPrintProvider} this
* PrintProvider.
* * map - `OpenLayers.Map` the map being printed.
* * pages - Array of {@link GeoExt.data.PrintPage} the print
* pages being printed.
* * options - `Object` the options to the print command.
*
* @event beforeprint
*/
/**
* Triggered when the print document is opened.
*
* Listener arguments:
*
* * printProvider - {@link GeoExt.data.MapfishPrintProvider} this
* PrintProvider.
* * url - `String` the url of the print document.
*
* @event print
*/
/**
* Triggered when using the `POST` method, when the print backend
* returns an exception.
*
* Listener arguments:
*
* * printProvider - {@link GeoExt.data.MapfishPrintProvider} this
* PrintProvider.
* * response - `Object` the response object of the XHR.
*
* @event printexception
*/
/**
* Triggered before a layer is encoded. This can be used to exclude
* layers from the printing, by having the listener return false.
*
* Listener arguments:
*
* * printProvider - {@link GeoExt.data.MapfishPrintProvider} this
* PrintProvider.
* * layer - `OpenLayers.Layer` the layer which is about to be
* encoded.
*
* @event beforeencodelayer
*/
/**
* Triggered when a layer is encoded. This can be used to modify
* the encoded low-level layer object that will be sent to the
* print service.
*
* Listener arguments:
*
* * printProvider - {@link GeoExt.data.MapfishPrintProvider} this
* PrintProvider.
* * layer - `OpenLayers.Layer` the layer which is about to be
* encoded.
* * encodedLayer - `Object` the encoded layer that will be
* sent to the print service.
*
* @event encodelayer
*/
/**
* Triggered before the PDF is downloaded. By returning false from
* a listener, the default handling of the PDF can be cancelled
* and applications can take control over downloading the PDF.
* TODO: rename to beforeprint after the current beforeprint event
* has been renamed to beforeencode.
*
* Listener arguments:
*
* * printProvider - {@link GeoExt.data.MapfishPrintProvider} this
* PrintProvider.
* * url - `String` the url of the print document.
*
* @event beforedownload
*/
/**
* Triggered before the legend is encoded. If the listener
* returns false, the default encoding based on GeoExt.LegendPanel
* will not be executed. This provides an option for application
* to get legend info from a custom component other than
* GeoExt.LegendPanel.
*
* Listener arguments:
*
* * printProvider - {@link GeoExt.data.MapfishPrintProvider} this
* PrintProvider.
* * jsonData - `Object` The data that will be sent to the print
* server. Can be used to populate jsonData.legends.
* * legend - `Object` The legend supplied in the options which were
* sent to the print function.
*
* @event beforeencodelegend
*/
/**
* Private constructor override.
*
* @private
*/
constructor: function(config) {
var me = this;
me.initialConfig = config;
Ext.apply(me, config);
if(!me.customParams) {
me.customParams = {};
}
me.callParent(arguments);
me.scales = Ext.create('Ext.data.JsonStore', {
proxy: me.getProxyConfiguration('scales'),
fields: [
"name",
{name: "value", type: "float"}
],
sortOnLoad: true,
sorters: { property: 'value', direction : 'DESC' }
});
me.dpis = Ext.create('Ext.data.JsonStore', {
proxy: me.getProxyConfiguration('dpis'),
fields: [
"name",
{name: "value", type: "float"}
]
});
me.layouts = Ext.create('Ext.data.JsonStore', {
proxy: me.getProxyConfiguration('layouts'),
fields: [
"name",
{name: "size", mapping: "map"},
{name: "rotation", type: "boolean"}
]
});
if(config.capabilities) {
me.loadStores();
} else {
if(me.url.split("/").pop()) {
me.url += "/";
}
if (me.initialConfig.autoLoad) {
me.loadCapabilities();
}
}
},
/**
* An internal method that creates a valid proxy configuration object for
* the passed rootPropertyname. This method is mostly existing because the
* name of the rootProperty key we need in the JSON reader is different
* between ExtJS 4 and 5 (`root` and `rootProperty` respectively).
*
* Will always return a memory proxy configuration with a JSON reader where
* the correct value for the root of the data is set to the value given.
*
* this.getProxyConfiguration('dpis');
* // results in ExtJS 4 in the following configuration...
* {
* type: "memory",
* reader: {
* type: "json",
* root: "dpis"
* }
* }
* // ...while the same call in ExtJS 5 evaluates to
* {
* type: "memory",
* reader: {
* type: "json",
* rootProperty: "dpis"
* }
* }
*
* This method is only used in the #constructor to set up the stores for
* the available scales, DPIs and layouts.
*
* @private
*/
getProxyConfiguration: function(rootPropertyName) {
var readerRootProperty = GeoExt.isExt4 ? 'root' : 'rootProperty',
readerCfg = {type: "json"},
proxyCfg;
readerCfg[readerRootProperty] = rootPropertyName;
proxyCfg = {
type: "memory",
reader: readerCfg
};
return proxyCfg;
},
/**
* Sets the layout for this printProvider.
*
* @param {Ext.data.Record} layout The record of the layout.
*/
setLayout: function(layout) {
this.layout = layout;
this.fireEvent("layoutchange", this, layout);
},
/**
* Sets the dpi for this printProvider.
*
* @param {Ext.data.Record} dpi The dpi record.
*
*/
setDpi: function(dpi) {
this.dpi = dpi;
this.fireEvent("dpichange", this, dpi);
},
/**
* Sends the print command to the print service and opens a new window
* with the resulting PDF.
*
* Valid properties for the `options` argument:
*
* * `legend` - {@link GeoExt.LegendPanel} If provided, the legend
* will be added to the print document. For the printed result to
* look like the LegendPanel, the following `!legends` block
* should be included in the `items` of your page layout in the
* print module's configuration file:
*
* - !legends
* maxIconWidth: 0
* maxIconHeight: 0
* classIndentation: 0
* layerSpace: 5
* layerFontSize: 10
*
* * `overview` - `OpenLayers.Control.OverviewMap` If provided,
* the layers for the overview map in the printout will be taken from
* the OverviewMap control. If not provided, the print service will
* use the main map's layers for the overview map. Applies only for
* layouts configured to print an overview map.
*
* @param {GeoExt.MapPanel/OpenLayers.Map} map The map to print.
* @param {GeoExt.data.PrintPage[]/GeoExt.data.PrintPage} pages Page or
* pages to print.
* @param {Object} options Object with additional options, see above.
*/
print: function(map, pages, options) {
if(map instanceof GeoExt.MapPanel) {
map = map.map;
}
pages = pages instanceof Array ? pages : [pages];
options = options || {};
if(this.fireEvent("beforeprint", this, map, pages, options) === false) {
return;
}
var jsonData = Ext.apply({
units: map.getUnits(),
srs: map.baseLayer.projection.getCode(),
layout: this.layout.get("name"),
dpi: this.dpi.get("value")
}, this.customParams);
var pagesLayer = pages[0].feature.layer;
var encodedLayers = [];
// ensure that the baseLayer is the first one in the encoded list
var layers = map.layers.concat();
Ext.Array.remove(layers, map.baseLayer);
Ext.Array.insert(layers, 0, [map.baseLayer]);
Ext.each(layers, function(layer){
if(layer !== pagesLayer && layer.getVisibility() === true) {
var enc = this.encodeLayer(layer);
enc && encodedLayers.push(enc);
}
}, this);
jsonData.layers = encodedLayers;
var encodedPages = [];
Ext.each(pages, function(page) {
encodedPages.push(Ext.apply({
center: [page.center.lon, page.center.lat],
scale: page.scale.get("value"),
rotation: page.rotation
}, page.customParams));
}, this);
jsonData.pages = encodedPages;
if (options.overview) {
var encodedOverviewLayers = [];
Ext.each(options.overview.layers, function(layer) {
var enc = this.encodeLayer(layer);
enc && encodedOverviewLayers.push(enc);
}, this);
jsonData.overviewLayers = encodedOverviewLayers;
}
if(options.legend && !(this.fireEvent("beforeencodelegend", this, jsonData, options.legend) === false)) {
var legend = options.legend;
var rendered = legend.rendered;
if (!rendered) {
legend = legend.cloneConfig({
renderTo: document.body,
hidden: true
});
}
var encodedLegends = [];
legend.items && legend.items.each(function(cmp) {
if(!cmp.hidden) {
var encFn = this.encoders.legends[cmp.getXType()];
// MapFish Print doesn't currently support per-page
// legends, so we use the scale of the first page.
encodedLegends = encodedLegends.concat(
encFn.call(this, cmp, jsonData.pages[0].scale));
}
}, this);
if (!rendered) {
legend.destroy();
}
jsonData.legends = encodedLegends;
}
if(this.method === "GET") {
var url = Ext.urlAppend(this.capabilities.printURL,
"spec=" + encodeURIComponent(Ext.encode(jsonData)));
this.download(url);
} else {
Ext.Ajax.request({
url: this.capabilities.createURL,
timeout: this.timeout,
jsonData: jsonData,
headers: {"Content-Type": "application/json; charset=" + this.encoding},
success: function(response) {
var url = Ext.decode(response.responseText).getURL;
this.download(url);
},
failure: function(response) {
this.fireEvent("printexception", this, response);
},
params: this.initialConfig.baseParams,
scope: this
});
}
},
/**
* Actually triggers a 'download' of the passed URL.
*
* @param {String} url
* @private
*/
download: function(url) {
if (this.fireEvent("beforedownload", this, url) !== false) {
if (Ext.isOpera) {
// Make sure that Opera don't replace the content tab with
// the pdf
window.open(url);
} else {
// This avoids popup blockers for all other browsers
window.location.href = url;
}
}
this.fireEvent("print", this, url);
},
/**
* Loads the capabilities from the print service. If this instance is
* configured with either `#capabilities` or a `#url` and `#autoLoad`
* set to true, then this method does not need to be called from the
* application.
*/
loadCapabilities: function() {
if (!this.url) {
return;
}
var url = this.url + "info.json";
Ext.Ajax.request({
url: url,
method: "GET",
disableCaching: false,
success: function(response) {
this.capabilities = Ext.decode(response.responseText);
this.loadStores();
},
params: this.initialConfig.baseParams,
scope: this
});
},
/**
* Loads the internal stores and fires the #loadcapabilities event when done.
*
* @private
*/
loadStores: function() {
this.scales.loadRawData(this.capabilities);
this.dpis.loadRawData(this.capabilities);
this.layouts.loadRawData(this.capabilities);
this.setLayout(this.layouts.getAt(0));
this.setDpi(this.dpis.getAt(0));
this.fireEvent("loadcapabilities", this, this.capabilities);
},
/**
* Encodes a given layer according to the definitions in #encoders.
*
* @param {OpenLayers.Layer} layer
* @return {Object}
* @private
*/
encodeLayer: function(layer) {
var encLayer;
for(var c in this.encoders.layers) {
if(OpenLayers.Layer[c] && layer instanceof OpenLayers.Layer[c]) {
if(this.fireEvent("beforeencodelayer", this, layer) === false) {
return;
}
encLayer = this.encoders.layers[c].call(this, layer);
this.fireEvent("encodelayer", this, layer, encLayer);
break;
}
}
// only return the encLayer object when we have a type. Prevents a
// fallback on base encoders like HTTPRequest.
return (encLayer && encLayer.type) ? encLayer : null;
},
/**
* Converts the provided url to an absolute url.
*
* @param {String} url
* @return {String}
* @private
*/
getAbsoluteUrl: function(url) {
var a;
if(Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
a = document.createElement("<a href='" + url + "'/>");
a.style.display = "none";
document.body.appendChild(a);
a.href = a.href;
document.body.removeChild(a);
} else {
a = document.createElement("a");
a.href = url;
}
return a.href;
},
/**
* Encoders for all print content.
*
* @property {Object} encoders
* @private
*/
encoders: {
"layers": {
"Layer": function(layer) {
var enc = {};
if (layer.options && layer.options.maxScale) {
enc.minScaleDenominator = layer.options.maxScale;
}
if (layer.options && layer.options.minScale) {
enc.maxScaleDenominator = layer.options.minScale;
}
return enc;
},
"WMS": function(layer) {
var enc = this.encoders.layers.HTTPRequest.call(this, layer);
Ext.apply(enc, {
type: 'WMS',
layers: [layer.params.LAYERS].join(",").split(","),
format: layer.params.FORMAT,
styles: [layer.params.STYLES].join(",").split(",")
});
var param;
for(var p in layer.params) {
param = p.toLowerCase();
if(!layer.DEFAULT_PARAMS[param] &&
"layers,styles,width,height,srs".indexOf(param) == -1) {
if(!enc.customParams) {
enc.customParams = {};
}
enc.customParams[p] = layer.params[p];
}
}
return enc;
},
"OSM": function(layer) {
var enc = this.encoders.layers.TileCache.call(this, layer);
return Ext.apply(enc, {
type: 'OSM',
baseURL: enc.baseURL.substr(0, enc.baseURL.indexOf("$")),
extension: "png"
});
},
"TMS": function(layer) {
var enc = this.encoders.layers.TileCache.call(this, layer);
return Ext.apply(enc, {
type: 'TMS',
format: layer.type
});
},
"TileCache": function(layer) {
var enc = this.encoders.layers.HTTPRequest.call(this, layer);
return Ext.apply(enc, {
type: 'TileCache',
layer: layer.layername,
maxExtent: layer.maxExtent.toArray(),
tileSize: [layer.tileSize.w, layer.tileSize.h],
extension: layer.extension,
resolutions: layer.serverResolutions || layer.resolutions
});
},
"WMTS": function(layer) {
var enc = this.encoders.layers.HTTPRequest.call(this, layer);
return Ext.apply(enc, {
type: 'WMTS',
layer: layer.layer,
version: layer.version,
requestEncoding: layer.requestEncoding,
tileOrigin: [layer.tileOrigin.lon, layer.tileOrigin.lat],
tileSize: [layer.tileSize.w, layer.tileSize.h],
style: layer.style,
formatSuffix: layer.formatSuffix,
dimensions: layer.dimensions,
params: layer.params,
maxExtent: (layer.tileFullExtent != null) ? layer.tileFullExtent.toArray() : layer.maxExtent.toArray(),
matrixSet: layer.matrixSet,
zoomOffset: layer.zoomOffset,
resolutions: layer.serverResolutions || layer.resolutions
});
},
"KaMapCache": function(layer) {
var enc = this.encoders.layers.KaMap.call(this, layer);
return Ext.apply(enc, {
type: 'KaMapCache',
// group param is mandatory when using KaMapCache
group: layer.params['g'],
metaTileWidth: layer.params['metaTileSize']['w'],
metaTileHeight: layer.params['metaTileSize']['h']
});
},
"KaMap": function(layer) {
var enc = this.encoders.layers.HTTPRequest.call(this, layer);
return Ext.apply(enc, {
type: 'KaMap',
map: layer.params['map'],
extension: layer.params['i'],
// group param is optional when using KaMap
group: layer.params['g'] || "",
maxExtent: layer.maxExtent.toArray(),
tileSize: [layer.tileSize.w, layer.tileSize.h],
resolutions: layer.serverResolutions || layer.resolutions
});
},
"HTTPRequest": function(layer) {
var enc = this.encoders.layers.Layer.call(this, layer);
return Ext.apply(enc, {
baseURL: this.getAbsoluteUrl(layer.url instanceof Array ?
layer.url[0] : layer.url),
opacity: (layer.opacity != null) ? layer.opacity : 1.0,
singleTile: layer.singleTile
});
},
"Image": function(layer) {
var enc = this.encoders.layers.Layer.call(this, layer);
return Ext.apply(enc, {
type: 'Image',
baseURL: this.getAbsoluteUrl(layer.getURL(layer.extent)),
opacity: (layer.opacity != null) ? layer.opacity : 1.0,
extent: layer.extent.toArray(),
pixelSize: [layer.size.w, layer.size.h],
name: layer.name
});
},
"Vector": function(layer) {
if(!layer.features.length) {
return;
}
var encFeatures = [];
var encStyles = {};
var features = layer.features;
var featureFormat = new OpenLayers.Format.GeoJSON();
var styleFormat = new OpenLayers.Format.JSON();
var nextId = 1;
var styleDict = {};
var feature, style, dictKey, dictItem, styleName;
for(var i=0, len=features.length; i<len; ++i) {
feature = features[i];
style = feature.style || layer.style ||
layer.styleMap.createSymbolizer(feature,
feature.renderIntent);
dictKey = styleFormat.write(style);
dictItem = styleDict[dictKey];
if(dictItem) {
//this style is already known
styleName = dictItem;
} else {
//new style
styleDict[dictKey] = styleName = nextId++;
if(style.externalGraphic) {
encStyles[styleName] = Ext.applyIf({
externalGraphic: this.getAbsoluteUrl(
style.externalGraphic)}, style);
} else {
encStyles[styleName] = style;
}
}
var featureGeoJson = featureFormat.extract.feature.call(
featureFormat, feature);
featureGeoJson.properties = OpenLayers.Util.extend({
_gx_style: styleName
}, featureGeoJson.properties);
encFeatures.push(featureGeoJson);
}
var enc = this.encoders.layers.Layer.call(this, layer);
return Ext.apply(enc, {
type: 'Vector',
styles: encStyles,
styleProperty: '_gx_style',
geoJson: {
type: "FeatureCollection",
features: encFeatures
},
name: layer.name,
opacity: (layer.opacity != null) ? layer.opacity : 1.0
});
},
"Markers": function(layer) {
var features = [];
for (var i=0, len=layer.markers.length; i<len; i++) {
var marker = layer.markers[i];
var geometry = new OpenLayers.Geometry.Point(marker.lonlat.lon, marker.lonlat.lat);
var style = {externalGraphic: marker.icon.url,
graphicWidth: marker.icon.size.w, graphicHeight: marker.icon.size.h,
graphicXOffset: marker.icon.offset.x, graphicYOffset: marker.icon.offset.y};
var feature = new OpenLayers.Feature.Vector(geometry, {}, style);
features.push(feature);
}
var vector = new OpenLayers.Layer.Vector(layer.name);
vector.addFeatures(features);
var output = this.encoders.layers.Vector.call(this, vector);
vector.destroy();
return output;
}
},
"legends": {
"gx_wmslegend": function(legend, scale) {
var enc = this.encoders.legends.base.call(this, legend);
var icons = [];
for(var i=1, len=legend.items.getCount(); i<len; ++i) {
var url = legend.items.get(i).url;
if(legend.useScaleParameter === true &&
url.toLowerCase().indexOf(
'request=getlegendgraphic') != -1) {
var split = url.split("?");
var params = Ext.urlDecode(split[1]);
params['SCALE'] = scale;
url = split[0] + "?" + Ext.urlEncode(params);
}
icons.push(this.getAbsoluteUrl(url));
}
enc[0].classes[0] = {
name: "",
icons: icons
};
return enc;
},
"gx_urllegend": function(legend) {
var enc = this.encoders.legends.base.call(this, legend);
enc[0].classes.push({
name: "",
icon: this.getAbsoluteUrl(legend.items.get(1).url)
});
return enc;
},
"base": function(legend){
return [{
name: legend.getLabel(),
classes: []
}];
}
}
}
});
|
exports = {};
|
/*global define*/
define([
'jquery',
'orotranslation/js/translator',
'underscore',
'oroui/js/mediator',
'routing',
'oroui/js/app/views/base/view',
'oroui/js/messenger'
], function($, __, _, mediator, routing, BaseView, messenger) {
'use strict';
var EmailNotificationView;
EmailNotificationView = BaseView.extend({
contextsView: null,
countNewEmail: null,
inputName: '',
events: {
'click button.mark-as-read': 'onClickMarkAsRead',
'click .info': 'onClickOpenEmail'
},
initialize: function(options) {
this.options = _.defaults(options || {}, this.options);
this.template = _.template($('#email-notification-item').html());
this.$containerEmails = $(options.el).find('.items');
this.countNewEmail = parseInt(options.count);
this.$el.show();
this.collection = options.collection;
this.initEvents();
this.render();
},
render: function() {
var $view;
var i;
this.$containerEmails.empty();
this.updateViewMode();
for (i in this.collection.models) {
if (this.collection.models.hasOwnProperty(i)) {
$view = this.getView(this.collection.models[i]);
this.$containerEmails.append($view);
}
}
this.initLayout();
},
getView: function(model) {
var view = this.template({
entity: model
});
var $view = $(view);
$view.find('.replay a').attr('data-url', model.get('route'));
if (model.get('seen')) {
$view.removeClass('new');
$view.find('.icon-envelope').removeClass('new');
}
return $view;
},
onClickMarkAsRead: function() {
var self = this;
$.ajax({
url: routing.generate('oro_email_mark_all_as_seen'),
success: function(response) {
self.collection.markAllAsRead();
self.render();
self.setCount(0);
if (response.successful) {
mediator.trigger('datagrid:doRefresh:user-email-grid');
}
self.initLayout();
},
error: function(model, response) {
messenger.showErrorMessage(__('oro.email.error.mark_as_read'), response.responseJSON || {});
}
});
},
updateViewMode: function() {
if (!this.isActiveTypeDropDown('notification')) {
if (this.collection.models.length === 0) {
this.setModeDropDownMenu('empty');
this.$el.find('.oro-dropdown-toggle .icon-envelope').removeClass('new');
} else {
this.setModeDropDownMenu('content');
if (this.countNewEmail > 0) {
this.$el.find('.oro-dropdown-toggle .icon-envelope').addClass('new');
} else {
this.$el.find('.oro-dropdown-toggle .icon-envelope').removeClass('new');
}
}
}
},
resetModeDropDownMenu: function() {
this.$el.find('.dropdown-menu').removeClass('content empty notification');
return this;
},
setModeDropDownMenu: function(type) {
this.resetModeDropDownMenu();
this.$el.find('.dropdown-menu').addClass(type);
},
isActiveTypeDropDown: function(type) {
return this.$el.find('.dropdown-menu').hasClass(type);
},
onClickOpenEmail: function(e) {
var id = $(e.currentTarget).data('id');
var url;
var model;
url = routing.generate('oro_email_thread_view', {id: id});
mediator.execute('redirectTo', {url: url});
model = this.collection.findWhere({id: id});
this.$el.find('#' + model.cid).removeClass('new');
this.$el.find('#' + model.cid).find('.icon-envelope').removeClass('new');
this.updateViewMode();
},
setCount: function(count) {
count = parseInt(count);
this.countNewEmail = count;
if (count > 10) {
count = '10+';
}
if (count === 0) {
count = '';
}
this.$el.find('.icon-envelope span').html(count);
this.updateViewMode();
},
initEvents: function() {
var self = this;
this.$el.click(function() {
if (self.isActiveTypeDropDown('notification')) {
self.open();
self.setModeDropDownMenu('content');
}
self.updateViewMode();
});
this.collection.on('reset', function() {
self.$containerEmails.empty();
self.setCount(0);
});
this.collection.on('add', function(model) {
var $view = self.getView(model);
self.$containerEmails.append($view);
self.initLayout();
});
},
showNotification: function() {
if (!this.isOpen()) {
this.open();
this.setModeDropDownMenu('notification');
}
},
isOpen: function() {
this.$el.hasClass('open');
},
close: function() {
this.$el.removeClass('open');
},
open: function() {
this.$el.addClass('open');
}
});
return EmailNotificationView;
});
|
describe('ionRefresher directive', function() {
beforeEach(module('ionic'));
function setup(attrs, scopeProps) {
var el;
inject(function($compile, $rootScope) {
var scope = $rootScope.$new();
var ionicScrollCtrl = {
_setRefresher: jasmine.createSpy('setRefresher'),
scrollView: {
finishPullToRefresh: jasmine.createSpy('finishPullToRefresh')
}
};
angular.extend(scope, scopeProps || {});
el = angular.element('<ion-refresher '+(attrs||'')+'></ion-refresher>');
el.data('$$ionicScrollController', ionicScrollCtrl);
$compile(el)(scope);
ionic.requestAnimationFrame = function() {};
$rootScope.$apply();
});
return el;
}
it('should error without ionicScroll', inject(function($compile, $rootScope) {
expect(function() {
$compile('<ion-refresher>')($rootScope);
}).toThrow();
}));
it('should bind $onRefresh', function() {
var refreshSpy = jasmine.createSpy('onRefresh');
var el = setup('on-refresh="refreshSpy()"', {
refreshSpy: refreshSpy
});
expect(refreshSpy).not.toHaveBeenCalled();
el.scope().$onRefresh();
expect(refreshSpy).toHaveBeenCalled();
});
it('should bind $onRefreshOpening', function() {
var spyMe = jasmine.createSpy('onRefreshOpening');
var el = setup('on-pulling="spyMe()"', {
spyMe: spyMe
});
expect(spyMe).not.toHaveBeenCalled();
el.scope().$onPulling();
expect(spyMe).toHaveBeenCalled();
});
it('should setRefresher on scrollCtrl', function() {
var el = setup();
expect(el.controller('$ionicScroll')._setRefresher.callCount).toBe(1);
expect(el.controller('$ionicScroll')._setRefresher).toHaveBeenCalledWith(
el.scope(), el[0]
);
});
it('should listen for scroll.refreshComplete', function() {
var el = setup();
el.addClass('active');
var ctrl = el.controller('$ionicScroll');
expect(ctrl.scrollView.finishPullToRefresh).not.toHaveBeenCalled();
el.scope().$broadcast('scroll.refreshComplete');
expect(el.hasClass('active')).toBe(true);
expect(ctrl.scrollView.finishPullToRefresh).not.toHaveBeenCalled();
el.scope().$apply();
expect(ctrl.scrollView.finishPullToRefresh).toHaveBeenCalled();
});
it('should not have default pullingIcon', function() {
var el = setup();
expect(el[0].querySelector('.icon-pulling .ion-ios-arrow-down')).toBeFalsy();
});
it('should allow custom pullingIcon', function() {
var el = setup('pulling-icon="super-icon"');
expect(el[0].querySelector('.icon-pulling .ion-arrow-down-c')).toBeFalsy();
expect(el[0].querySelector('.icon-pulling .super-icon')).toBeTruthy();
});
it('should have default spinner', function() {
var el = setup();
expect(el[0].querySelector('ion-spinner')).toBeTruthy();
});
it('should have spinner', function() {
var el = setup('spinner="android"');
expect(el[0].querySelector('.spinner-android')).toBeTruthy();
});
it('should allow custom refreshingIcon', function() {
var el = setup('refreshing-icon="monkey-icon"');
expect(el[0].querySelector('.icon.icon-refreshing.ion-arrow-down-c')).toBeFalsy();
expect(el[0].querySelector('.monkey-icon')).toBeTruthy();
});
it('should allow pullingText', function() {
var el = setup('pulling-text="{{2+2}} <b>some</b> text"');
expect(el[0].querySelector('.text-pulling').innerHTML).toBe('4 <b>some</b> text');
});
it('should allow refreshingText', function() {
var el = setup('refreshing-text="{{3+2}} <b>text</b>"');
expect(el[0].querySelector('.text-refreshing').innerHTML).toBe('5 <b>text</b>');
});
it('should allow pulling rotation animation to be disabled', function() {
var el = setup('disable-pulling-rotation="true"');
expect(el[0].querySelector('.pulling-rotation-disabled').innerHTML).toBeTruthy();
});
});
|
// Copyright 2015-2021 JC Fisher
import isfalsy from "./isfalsy";
// Returns true when the value is not falsey
// https://developer.mozilla.org/en-US/docs/Glossary/Truthy
export default function istruthy(value) {
return !isfalsy(value);
}
|
/** @babel */
import {Emitter, Disposable, CompositeDisposable} from 'event-kit'
import {Point, Range} from 'text-buffer'
import TextEditor from './text-editor'
import ScopeDescriptor from './scope-descriptor'
const EDITOR_PARAMS_BY_SETTING_KEY = [
['core.fileEncoding', 'encoding'],
['editor.atomicSoftTabs', 'atomicSoftTabs'],
['editor.showInvisibles', 'showInvisibles'],
['editor.tabLength', 'tabLength'],
['editor.invisibles', 'invisibles'],
['editor.showCursorOnSelection', 'showCursorOnSelection'],
['editor.showIndentGuide', 'showIndentGuide'],
['editor.showLineNumbers', 'showLineNumbers'],
['editor.softWrap', 'softWrapped'],
['editor.softWrapHangingIndent', 'softWrapHangingIndentLength'],
['editor.softWrapAtPreferredLineLength', 'softWrapAtPreferredLineLength'],
['editor.preferredLineLength', 'preferredLineLength'],
['editor.maxScreenLineLength', 'maxScreenLineLength'],
['editor.autoIndent', 'autoIndent'],
['editor.autoIndentOnPaste', 'autoIndentOnPaste'],
['editor.scrollPastEnd', 'scrollPastEnd'],
['editor.undoGroupingInterval', 'undoGroupingInterval'],
['editor.nonWordCharacters', 'nonWordCharacters'],
['editor.scrollSensitivity', 'scrollSensitivity']
]
const GRAMMAR_SELECTION_RANGE = Range(Point.ZERO, Point(10, 0)).freeze()
// Experimental: This global registry tracks registered `TextEditors`.
//
// If you want to add functionality to a wider set of text editors than just
// those appearing within workspace panes, use `atom.textEditors.observe` to
// invoke a callback for all current and future registered text editors.
//
// If you want packages to be able to add functionality to your non-pane text
// editors (such as a search field in a custom user interface element), register
// them for observation via `atom.textEditors.add`. **Important:** When you're
// done using your editor, be sure to call `dispose` on the returned disposable
// to avoid leaking editors.
export default class TextEditorRegistry {
constructor ({config, grammarRegistry, assert, packageManager}) {
this.assert = assert
this.config = config
this.grammarRegistry = grammarRegistry
this.scopedSettingsDelegate = new ScopedSettingsDelegate(config)
this.grammarAddedOrUpdated = this.grammarAddedOrUpdated.bind(this)
this.clear()
this.initialPackageActivationPromise = new Promise((resolve) => {
// TODO: Remove this usage of a private property of PackageManager.
// Should PackageManager just expose a promise-based API like this?
if (packageManager.deferredActivationHooks) {
packageManager.onDidActivateInitialPackages(resolve)
} else {
resolve()
}
})
}
deserialize (state) {
this.editorGrammarOverrides = state.editorGrammarOverrides
}
serialize () {
return {
editorGrammarOverrides: Object.assign({}, this.editorGrammarOverrides)
}
}
clear () {
if (this.subscriptions) {
this.subscriptions.dispose()
}
this.subscriptions = new CompositeDisposable()
this.editors = new Set()
this.emitter = new Emitter()
this.scopesWithConfigSubscriptions = new Set()
this.editorsWithMaintainedConfig = new Set()
this.editorsWithMaintainedGrammar = new Set()
this.editorGrammarOverrides = {}
this.editorGrammarScores = new WeakMap()
this.subscriptions.add(
this.grammarRegistry.onDidAddGrammar(this.grammarAddedOrUpdated),
this.grammarRegistry.onDidUpdateGrammar(this.grammarAddedOrUpdated)
)
}
destroy () {
this.subscriptions.dispose()
this.editorsWithMaintainedConfig = null
}
// Register a `TextEditor`.
//
// * `editor` The editor to register.
//
// Returns a {Disposable} on which `.dispose()` can be called to remove the
// added editor. To avoid any memory leaks this should be called when the
// editor is destroyed.
add (editor) {
this.editors.add(editor)
editor.registered = true
this.emitter.emit('did-add-editor', editor)
return new Disposable(() => this.remove(editor))
}
build (params) {
params = Object.assign({assert: this.assert}, params)
let scope = null
if (params.buffer) {
const filePath = params.buffer.getPath()
const headContent = params.buffer.getTextInRange(GRAMMAR_SELECTION_RANGE)
params.grammar = this.grammarRegistry.selectGrammar(filePath, headContent)
scope = new ScopeDescriptor({scopes: [params.grammar.scopeName]})
}
Object.assign(params, this.textEditorParamsForScope(scope))
return new TextEditor(params)
}
// Remove a `TextEditor`.
//
// * `editor` The editor to remove.
//
// Returns a {Boolean} indicating whether the editor was successfully removed.
remove (editor) {
var removed = this.editors.delete(editor)
editor.registered = false
return removed
}
// Invoke the given callback with all the current and future registered
// `TextEditors`.
//
// * `callback` {Function} to be called with current and future text editors.
//
// Returns a {Disposable} on which `.dispose()` can be called to unsubscribe.
observe (callback) {
this.editors.forEach(callback)
return this.emitter.on('did-add-editor', callback)
}
// Keep a {TextEditor}'s configuration in sync with Atom's settings.
//
// * `editor` The editor whose configuration will be maintained.
//
// Returns a {Disposable} that can be used to stop updating the editor's
// configuration.
maintainConfig (editor) {
if (this.editorsWithMaintainedConfig.has(editor)) {
return new Disposable(noop)
}
this.editorsWithMaintainedConfig.add(editor)
editor.setScopedSettingsDelegate(this.scopedSettingsDelegate)
this.subscribeToSettingsForEditorScope(editor)
const grammarChangeSubscription = editor.onDidChangeGrammar(() => {
this.subscribeToSettingsForEditorScope(editor)
})
this.subscriptions.add(grammarChangeSubscription)
const updateTabTypes = () => {
const configOptions = {scope: editor.getRootScopeDescriptor()}
editor.setSoftTabs(shouldEditorUseSoftTabs(
editor,
this.config.get('editor.tabType', configOptions),
this.config.get('editor.softTabs', configOptions)
))
}
updateTabTypes()
const tokenizeSubscription = editor.onDidTokenize(updateTabTypes)
this.subscriptions.add(tokenizeSubscription)
return new Disposable(() => {
this.editorsWithMaintainedConfig.delete(editor)
editor.setScopedSettingsDelegate(null)
tokenizeSubscription.dispose()
grammarChangeSubscription.dispose()
this.subscriptions.remove(grammarChangeSubscription)
this.subscriptions.remove(tokenizeSubscription)
})
}
// Set a {TextEditor}'s grammar based on its path and content, and continue
// to update its grammar as grammars are added or updated, or the editor's
// file path changes.
//
// * `editor` The editor whose grammar will be maintained.
//
// Returns a {Disposable} that can be used to stop updating the editor's
// grammar.
maintainGrammar (editor) {
if (this.editorsWithMaintainedGrammar.has(editor)) {
return new Disposable(noop)
}
this.editorsWithMaintainedGrammar.add(editor)
const buffer = editor.getBuffer()
for (let existingEditor of this.editorsWithMaintainedGrammar) {
if (existingEditor.getBuffer() === buffer) {
const existingOverride = this.editorGrammarOverrides[existingEditor.id]
if (existingOverride) {
this.editorGrammarOverrides[editor.id] = existingOverride
}
break
}
}
this.selectGrammarForEditor(editor)
const pathChangeSubscription = editor.onDidChangePath(() => {
this.editorGrammarScores.delete(editor)
this.selectGrammarForEditor(editor)
})
this.subscriptions.add(pathChangeSubscription)
return new Disposable(() => {
delete this.editorGrammarOverrides[editor.id]
this.editorsWithMaintainedGrammar.delete(editor)
this.subscriptions.remove(pathChangeSubscription)
pathChangeSubscription.dispose()
})
}
// Force a {TextEditor} to use a different grammar than the one that would
// otherwise be selected for it.
//
// * `editor` The editor whose gramamr will be set.
// * `scopeName` The {String} root scope name for the desired {Grammar}.
setGrammarOverride (editor, scopeName) {
this.editorGrammarOverrides[editor.id] = scopeName
this.editorGrammarScores.delete(editor)
editor.setGrammar(this.grammarRegistry.grammarForScopeName(scopeName))
}
// Retrieve the grammar scope name that has been set as a grammar override
// for the given {TextEditor}.
//
// * `editor` The editor.
//
// Returns a {String} scope name, or `null` if no override has been set
// for the given editor.
getGrammarOverride (editor) {
return this.editorGrammarOverrides[editor.id]
}
// Remove any grammar override that has been set for the given {TextEditor}.
//
// * `editor` The editor.
clearGrammarOverride (editor) {
delete this.editorGrammarOverrides[editor.id]
this.selectGrammarForEditor(editor)
}
// Private
grammarAddedOrUpdated (grammar) {
this.editorsWithMaintainedGrammar.forEach((editor) => {
if (grammar.injectionSelector) {
if (editor.tokenizedBuffer.hasTokenForSelector(grammar.injectionSelector)) {
editor.tokenizedBuffer.retokenizeLines()
}
return
}
const grammarOverride = this.editorGrammarOverrides[editor.id]
if (grammarOverride) {
if (grammar.scopeName === grammarOverride) {
editor.setGrammar(grammar)
}
} else {
const score = this.grammarRegistry.getGrammarScore(
grammar,
editor.getPath(),
editor.getTextInBufferRange(GRAMMAR_SELECTION_RANGE)
)
let currentScore = this.editorGrammarScores.get(editor)
if (currentScore == null || score > currentScore) {
editor.setGrammar(grammar)
this.editorGrammarScores.set(editor, score)
}
}
})
}
selectGrammarForEditor (editor) {
const grammarOverride = this.editorGrammarOverrides[editor.id]
if (grammarOverride) {
const grammar = this.grammarRegistry.grammarForScopeName(grammarOverride)
editor.setGrammar(grammar)
return
}
const {grammar, score} = this.grammarRegistry.selectGrammarWithScore(
editor.getPath(),
editor.getTextInBufferRange(GRAMMAR_SELECTION_RANGE)
)
if (!grammar) {
throw new Error(`No grammar found for path: ${editor.getPath()}`)
}
const currentScore = this.editorGrammarScores.get(editor)
if (currentScore == null || score > currentScore) {
editor.setGrammar(grammar)
this.editorGrammarScores.set(editor, score)
}
}
async subscribeToSettingsForEditorScope (editor) {
await this.initialPackageActivationPromise
const scopeDescriptor = editor.getRootScopeDescriptor()
const scopeChain = scopeDescriptor.getScopeChain()
editor.update(this.textEditorParamsForScope(scopeDescriptor))
if (!this.scopesWithConfigSubscriptions.has(scopeChain)) {
this.scopesWithConfigSubscriptions.add(scopeChain)
const configOptions = {scope: scopeDescriptor}
for (const [settingKey, paramName] of EDITOR_PARAMS_BY_SETTING_KEY) {
this.subscriptions.add(
this.config.onDidChange(settingKey, configOptions, ({newValue}) => {
this.editorsWithMaintainedConfig.forEach((editor) => {
if (editor.getRootScopeDescriptor().isEqual(scopeDescriptor)) {
editor.update({[paramName]: newValue})
}
})
})
)
}
const updateTabTypes = () => {
const tabType = this.config.get('editor.tabType', configOptions)
const softTabs = this.config.get('editor.softTabs', configOptions)
this.editorsWithMaintainedConfig.forEach((editor) => {
if (editor.getRootScopeDescriptor().isEqual(scopeDescriptor)) {
editor.setSoftTabs(shouldEditorUseSoftTabs(editor, tabType, softTabs))
}
})
}
this.subscriptions.add(
this.config.onDidChange('editor.tabType', configOptions, updateTabTypes),
this.config.onDidChange('editor.softTabs', configOptions, updateTabTypes)
)
}
}
textEditorParamsForScope (scopeDescriptor) {
const result = {}
const configOptions = {scope: scopeDescriptor}
for (const [settingKey, paramName] of EDITOR_PARAMS_BY_SETTING_KEY) {
result[paramName] = this.config.get(settingKey, configOptions)
}
return result
}
}
function shouldEditorUseSoftTabs (editor, tabType, softTabs) {
switch (tabType) {
case 'hard':
return false
case 'soft':
return true
case 'auto':
switch (editor.usesSoftTabs()) {
case true:
return true
case false:
return false
default:
return softTabs
}
}
}
function noop () {}
class ScopedSettingsDelegate {
constructor (config) {
this.config = config
}
getNonWordCharacters (scope) {
return this.config.get('editor.nonWordCharacters', {scope: scope})
}
getIncreaseIndentPattern (scope) {
return this.config.get('editor.increaseIndentPattern', {scope: scope})
}
getDecreaseIndentPattern (scope) {
return this.config.get('editor.decreaseIndentPattern', {scope: scope})
}
getDecreaseNextIndentPattern (scope) {
return this.config.get('editor.decreaseNextIndentPattern', {scope: scope})
}
getFoldEndPattern (scope) {
return this.config.get('editor.foldEndPattern', {scope: scope})
}
getCommentStrings (scope) {
const commentStartEntries = this.config.getAll('editor.commentStart', {scope})
const commentEndEntries = this.config.getAll('editor.commentEnd', {scope})
const commentStartEntry = commentStartEntries[0]
const commentEndEntry = commentEndEntries.find((entry) => {
return entry.scopeSelector === commentStartEntry.scopeSelector
})
return {
commentStartString: commentStartEntry && commentStartEntry.value,
commentEndString: commentEndEntry && commentEndEntry.value
}
}
}
TextEditorRegistry.ScopedSettingsDelegate = ScopedSettingsDelegate
|
'use strict';
module.exports = TinyQueue;
function TinyQueue(data, compare) {
this.data = data || [];
this.length = this.data.length;
this.compare = compare || defaultCompare;
if (data) for (var i = Math.floor(this.length / 2); i >= 0; i--) this._down(i);
}
function defaultCompare(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}
TinyQueue.prototype = {
push: function (item) {
this.data.push(item);
this.length++;
this._up(this.length - 1);
},
pop: function () {
var top = this.data[0];
this.data[0] = this.data[this.length - 1];
this.length--;
this.data.pop();
this._down(0);
return top;
},
peek: function () {
return this.data[0];
},
_up: function (pos) {
var data = this.data,
compare = this.compare;
while (pos > 0) {
var parent = Math.floor((pos - 1) / 2);
if (compare(data[pos], data[parent]) < 0) {
swap(data, parent, pos);
pos = parent;
} else break;
}
},
_down: function (pos) {
var data = this.data,
compare = this.compare,
len = this.length;
while (true) {
var left = 2 * pos + 1,
right = left + 1,
min = pos;
if (left < len && compare(data[left], data[min]) < 0) min = left;
if (right < len && compare(data[right], data[min]) < 0) min = right;
if (min === pos) return;
swap(data, min, pos);
pos = min;
}
}
};
function swap(data, i, j) {
var tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Notify = factory());
}(this, (function () { 'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
/*
* Author: Alex Gibson
* https://github.com/alexgibson/notify.js
* License: MIT license
*/
var N = window.Notification;
function isFunction(item) {
return typeof item === 'function';
}
function Notify(title) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (typeof title !== 'string') {
throw new Error('Notify(): first arg (title) must be a string.');
}
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) !== 'object') {
throw new Error('Notify(): second arg (options) must be an object.');
}
var _options$notifyShow = options.notifyShow,
notifyShow = _options$notifyShow === undefined ? null : _options$notifyShow,
_options$notifyClose = options.notifyClose,
notifyClose = _options$notifyClose === undefined ? null : _options$notifyClose,
_options$notifyClick = options.notifyClick,
notifyClick = _options$notifyClick === undefined ? null : _options$notifyClick,
_options$notifyError = options.notifyError,
notifyError = _options$notifyError === undefined ? null : _options$notifyError,
_options$closeOnClick = options.closeOnClick,
closeOnClick = _options$closeOnClick === undefined ? false : _options$closeOnClick,
_options$timeout = options.timeout,
timeout = _options$timeout === undefined ? null : _options$timeout,
rest = objectWithoutProperties(options, ['notifyShow', 'notifyClose', 'notifyClick', 'notifyError', 'closeOnClick', 'timeout']);
this.title = title;
this.options = rest;
this.permission = null;
this.closeOnClick = closeOnClick;
this.timeout = timeout;
//callback when notification is displayed
if (isFunction(notifyShow)) {
this.onShowCallback = notifyShow;
}
//callback when notification is closed
if (isFunction(notifyClose)) {
this.onCloseCallback = notifyClose;
}
//callback when notification is clicked
if (isFunction(notifyClick)) {
this.onClickCallback = notifyClick;
}
//callback when notification throws error
if (isFunction(notifyError)) {
this.onErrorCallback = notifyError;
}
}
// returns true if the browser supports Web Notifications
// https://developers.google.com/web/updates/2015/05/Notifying-you-of-notificiation-changes
// @param {perm} for test purposes only
Notify.isSupported = function (perm) {
if (!N || !N.requestPermission) {
return false;
}
if (perm === 'granted' || N.permission === 'granted') {
throw new Error('You must only call this before calling Notification.requestPermission(), otherwise this feature detect would trigger an actual notification!');
}
try {
new N('');
} catch (e) {
if (e.name === 'TypeError') {
return false;
}
}
return true;
};
// true if the permission is not granted
Notify.needsPermission = N && N.permission && N.permission === 'granted' ? false : true;
// asks the user for permission to display notifications. Then calls the callback functions is supplied.
Notify.requestPermission = function (onPermissionGrantedCallback, onPermissionDeniedCallback) {
N.requestPermission(function (perm) {
switch (perm) {
case 'granted':
Notify.needsPermission = false;
if (isFunction(onPermissionGrantedCallback)) {
onPermissionGrantedCallback();
}
break;
case 'denied':
Notify.needsPermission = true;
if (isFunction(onPermissionDeniedCallback)) {
onPermissionDeniedCallback();
}
break;
}
});
};
Notify.prototype.show = function () {
this.myNotify = new N(this.title, this.options);
if (!this.options.requireInteraction && this.timeout && !isNaN(this.timeout)) {
setTimeout(this.close.bind(this), this.timeout * 1000);
}
this.myNotify.addEventListener('show', this, false);
this.myNotify.addEventListener('error', this, false);
this.myNotify.addEventListener('close', this, false);
this.myNotify.addEventListener('click', this, false);
};
Notify.prototype.onShowNotification = function (e) {
if (this.onShowCallback) {
this.onShowCallback(e);
}
};
Notify.prototype.onCloseNotification = function (e) {
if (this.onCloseCallback) {
this.onCloseCallback(e);
}
this.destroy();
};
Notify.prototype.onClickNotification = function (e) {
if (this.onClickCallback) {
this.onClickCallback(e);
}
if (this.closeOnClick) {
this.close();
}
};
Notify.prototype.onErrorNotification = function (e) {
if (this.onErrorCallback) {
this.onErrorCallback(e);
}
this.destroy();
};
Notify.prototype.destroy = function () {
this.myNotify.removeEventListener('show', this, false);
this.myNotify.removeEventListener('error', this, false);
this.myNotify.removeEventListener('close', this, false);
this.myNotify.removeEventListener('click', this, false);
};
Notify.prototype.close = function () {
this.myNotify.close();
};
Notify.prototype.handleEvent = function (e) {
switch (e.type) {
case 'show':
this.onShowNotification(e);
break;
case 'close':
this.onCloseNotification(e);
break;
case 'click':
this.onClickNotification(e);
break;
case 'error':
this.onErrorNotification(e);
break;
}
};
return Notify;
})));
|
app.pages['gamble'] = function(params) {
if ($('.slideWrapper1 div').length == 0) {
sliderInit();
}
if (params.secretPhrase) {
app.gamble(params.secretPhrase);
}
$btn = $('.btn_roll');
$btn.off();
$btn.click(function() {
if (!app.vars.secretPhrase) {
app.showLoginModal({ nextPage: 'gamble' });
} else {
app.gamble(app.vars.secretPhrase);
}
});
};
/* Take bet size and odds, send API call, poll for result */
app.gamble = function(secretPhrase) {
var $rightPage = $('.page-details .content');
$rightPage.show();
$rightPage.find('.response').hide();
$rightPage.find('.slider-comments').show();
var amount = $('#betSize').val();
var odds = $('.oddSize').val();
var config = app.config;
var opts = {
requestType: 'transferAsset',
secretPhrase: secretPhrase,
recipient: config.banker,
quantityQNT: amount * config.chipNQT,
deadline: config.deadline,
feeNQT: config.NQT,
asset: config.chipsAssetId,
messageToEncrypt: odds,
messageToEncryptIsText: true
};
if (app.validateOptions() === false) {
console.error('Cannod send, one or several options are empty or of invalid format', opts);
}
app.callChain(opts, function(err, response) {
if (err) {
var error = response.errorDescription || 'Unknown error';
app.warningWindowShow({
text: error
});
return;
}
app.loadingWindowShow({ text: 'Rolling NeoDice<br/>It might take a minute...' });
app.pollForResult({
transaction: response,
success: function(response) {
app.loadingWindowHide();
app.showBetResults(response);
app.updateBalance();
},
error: function() {
app.loadingWindowHide();
console.error('Error while polling');
}/*,
test: function() {
return 'testHash_jadkflkadjfkladkjaldkjldkgjakdjg';
}*/
});
});
};
/* Display modal with bet result based on transaction's message */
app.showBetResults = function(response) {
var message = response.attachment.message;
var $popupContent = $('#betResultWindow .modal-body');
var luckyNumber = new RegExp(/Lucky Number: (\d+)?/gi).exec(message);
luckyNumber = luckyNumber[1] || 'n/a';
var result = response.attachment.quantityQNT > 0? 'Your bet has WON!': 'Your bet has lost';
var balance = new RegExp(/balance after transaction: ([\d.]+)?/gi).exec(message);
balance = balance[1] || 'n/a';
$popupContent.find('.luckyNumber').html(luckyNumber);
$popupContent.find('.result').html(result);
$popupContent.find('.balance').html(balance);
$('#betResultWindow').modal();
};
|
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import wait from 'ember-test-helpers/wait';
const { Object:EmberObject, RSVP } = Ember;
const { resolve } = RSVP;
moduleForComponent('session-objective-list-item', 'Integration | Component | session objective list item', {
integration: true
});
test('it renders', function(assert) {
let objective = EmberObject.create({
title: 'fake title'
});
this.set('objective', objective);
this.on('nothing', parseInt);
this.render(hbs`{{session-objective-list-item
objective=objective
remove=(action 'nothing')
manageParents=(action 'nothing')
manageDescriptors=(action 'nothing')
}}`);
assert.equal(this.$('td:eq(0)').text().trim(), 'fake title');
assert.equal(this.$('td:eq(1) button').text().trim(), 'Add New');
assert.equal(this.$('td:eq(2) button').text().trim(), 'Add New');
assert.equal(this.$('td:eq(3) i').length, 1);
});
test('renders removable', function(assert) {
let objective = EmberObject.create({
title: 'fake title'
});
this.set('objective', objective);
this.on('nothing', parseInt);
this.render(hbs`{{session-objective-list-item
objective=objective
showRemoveConfirmation=true
remove=(action 'nothing')
manageParents=(action 'nothing')
manageDescriptors=(action 'nothing')
}}`);
assert.ok(this.$('tr').hasClass('confirm-removal'));
});
test('can change title', async function(assert) {
let objective = EmberObject.create({
title: 'fake title',
save(){
assert.equal(this.get('title'), '<p>new title</p>');
return resolve();
}
});
this.set('objective', objective);
this.on('nothing', parseInt);
this.render(hbs`{{session-objective-list-item
objective=objective
remove=(action 'nothing')
manageParents=(action 'nothing')
manageDescriptors=(action 'nothing')
}}`);
this.$('td:eq(0) .editable').click();
this.$('td:eq(0) .fr-box').froalaEditor('html.set', 'new title');
this.$('td:eq(0) .fr-box').froalaEditor('events.trigger', 'contentChanged');
this.$('td:eq(0) .done').click();
await wait();
});
test('can manage parents', function(assert) {
let objective = EmberObject.create({
title: 'fake title'
});
this.set('objective', objective);
this.on('nothing', parseInt);
this.on('something', ()=>{
assert.ok(true);
});
this.render(hbs`{{session-objective-list-item
objective=objective
remove=(action 'nothing')
manageParents=(action 'something')
manageDescriptors=(action 'nothing')
}}`);
this.$('td:eq(1) button').click();
});
test('can manage descriptors', function(assert) {
let objective = EmberObject.create({
title: 'fake title'
});
this.set('objective', objective);
this.on('nothing', parseInt);
this.on('something', ()=>{
assert.ok(true);
});
this.render(hbs`{{session-objective-list-item
objective=objective
remove=(action 'nothing')
manageParents=(action 'nothing')
manageDescriptors=(action 'something')
}}`);
this.$('td:eq(2) button').click();
});
test('can trigger removal', function(assert) {
let objective = EmberObject.create({
title: 'fake title'
});
this.set('objective', objective);
this.on('nothing', parseInt);
this.on('something', ()=>{
assert.ok(true);
});
this.render(hbs`{{session-objective-list-item
objective=objective
remove=(action 'something')
manageParents=(action 'nothing')
manageDescriptors=(action 'nothing')
}}`);
this.$('td:eq(3) i').click();
});
|
'use strict';
module.exports = function (t, a) {
a(t('arar'), false, "String");
a(t(12), false, "Number");
a(t(true), false, "Boolean");
a(t(new Date()), false, "Date");
a(t(String('raz')), false, "String object");
a(t({}), false, "Plain object");
a(t(/a/), true, "Regular expression");
a(t(new RegExp('a')), true, "Regular expression via constructor");
};
|
/**
* gonebusy
*
* This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io )
*/
'use strict';
const stream = require('stream');
class APIHelper {
/**
* Replaces template parameters in the given url
* @param {String} queryBuilder The query string builder to replace the template parameters
* @param {Array} parameters The parameters to replace in the queryBuilder
* @returns {String} The query string with replaced template parameters
*/
static appendUrlWithTemplateParameters(queryBuilder, parameters) {
// perform parameter validation
if (queryBuilder === null) {
return null;
}
if (parameters === null) {
return queryBuilder;
}
let queryString = queryBuilder;
// iterate and replace parameters
const keys = Object.keys(parameters);
for (let iter = 0; iter < keys.length; iter += 1) {
let replaceValue = '';
// load parameter value
const element = parameters[keys[iter]];
if (element === null) {
replaceValue = '';
} else if (element instanceof Array) {
replaceValue = element.map(el => encodeURIComponent(el));
replaceValue = replaceValue.join('/');
} else {
replaceValue = encodeURIComponent(element.toString());
}
queryString = queryString.replace(`{${keys[iter]}}`, replaceValue);
}
return queryString;
}
/**
* Appends the given set of parameters to the given query string
* @param {String} queryBuilder The query url string to append the parameters
* @param {Array} parameters The parameters to append
* @returns {String} The query string appended with query parameters
*/
static appendUrlWithQueryParameters(queryBuilder, parameters) {
// perform parameter validation
if (queryBuilder === null) {
return null;
}
if (parameters === queryBuilder) {
return queryBuilder;
}
const hasParams = queryBuilder.indexOf('?') > -1;
// iterate and replace parameters
const encoded = this.urlEncodeObject(parameters);
const separator = (hasParams) ? '&' : '?';
const queryString = queryBuilder + separator + encoded;
return queryString;
}
/**
* Validates and processes the given Url
* @param {String} url The Url to process
* @return {String} Processed url
*/
static cleanUrl(url) {
// ensure that the urls are absolute
const re = /^https?:\/\/[^/]+/;
const match = url.match(re);
if (match === null) {
return null;
}
// remove redundant forward slashes
const protocol = match[0];
let queryUrl = url.substring(protocol.length);
queryUrl = queryUrl.replace(/\/\/+/, '/');
const result = protocol + queryUrl;
return result;
}
/**
* JSON Serialization of a given object.
* @param {Object} data The object to serialize into JSON
* @return {Object} The serialized Json string representation of the given object
*/
static jsonSerialize(data) {
return JSON.stringify(data);
}
/**
* Formats the template parameters in the string
* @param {string} str The string containing the template
* @return {string} The string with template parameters filled in.
*/
static formatString(str) {
let formattedStr = str;
if (!formattedStr || arguments.length <= 1) return formattedStr;
for (let iter = 1; iter < arguments.length; iter += 1) {
const reg = new RegExp(`\\{${(iter - 1)}\\}`, 'gm');
formattedStr = formattedStr.replace(reg, arguments[iter]);
}
return formattedStr;
}
/**
* Cleans the object by removing null properties.
* @param {object} input Object or dictionary.
* @return {object} Returns the cleaned version of the object.
*/
static cleanObject(input) {
if (!input) {
return input;
}
const cleanedObj = input;
if (cleanedObj instanceof stream.Stream) {
return cleanedObj;
}
const keys = Object.keys(cleanedObj);
for (let iter = 0; iter < keys.length; iter += 1) {
const value = cleanedObj[keys[iter]];
if (value === null || value === undefined) {
if (cleanedObj.constructor === Array) {
cleanedObj.splice(keys[iter], 1);
} else delete cleanedObj[keys[iter]];
} else if (Object.prototype.toString.call(value) === '[object Object]') {
this.cleanObject(value);
} else if (value.constructor === Array) {
this.cleanObject(value);
}
}
return cleanedObj;
}
/**
* Shallow merges the properties of two objects
* @param {object} first The object to merge in to
* @param {object} second The object to be added to first
*
* @return {object} The merged (modified) first object
*/
static merge(first, second) {
if (!first) {
return first;
}
const merged = first;
if (second !== undefined && second !== null) {
const attrNamesSecond = Object.keys(second);
for (let iter = 0; iter < attrNamesSecond.length; iter += 1) {
merged[attrNamesSecond[iter]] = second[attrNamesSecond[iter]];
}
}
return merged;
}
/**
* Checks if the elements of the given array are all primitives
* @param {array} value The array to be checked
*
* @return {bool} The result of primitive checking
*/
static isPrimitiveArray(value) {
if (value.constructor && value.constructor !== Array) {
return false;
}
if (value.length === 0) return true;
return value.every(obj =>
(obj === null
|| obj === undefined)
|| (obj.constructor
&& [String, Number, Boolean].indexOf(obj.constructor) >= 0));
}
/**
* Converts an object to formdata serialization.
* @param {Object} obj The object to serialize
* @param {array} keys The keys of the object
* @return {array<key,value>} Result of serialization
*/
static formDataEncodeObject(obj, keys) {
let value;
let fullSubName;
let subValue;
let innerObj;
let returnKeys = keys;
if (!keys) {
returnKeys = [];
}
if (!obj) {
return null;
}
const keysOfObj = Object.keys(obj);
for (let outerIter = 0; outerIter < keysOfObj.length; outerIter += 1) {
value = obj[keysOfObj[outerIter]];
if (value instanceof stream.Stream) {
returnKeys.push({
key: keysOfObj[outerIter],
value,
});
} else if (value instanceof Array) {
const arrayFormat = '{0}[{1}]';
for (let iter = 0; iter < value.length; iter += 1) {
subValue = value[iter];
fullSubName = this.formatString(arrayFormat, keysOfObj[outerIter], iter);
innerObj = {};
innerObj[fullSubName] = subValue;
this.formDataEncodeObject(innerObj, returnKeys);
}
} else if (value instanceof Object) {
const subNameKeys = Object.keys(value);
for (let iter = 0; iter < subNameKeys.length; iter += 1) {
subValue = value[subNameKeys[iter]];
fullSubName = `${keysOfObj[outerIter]}[${subNameKeys[iter]}]`;
innerObj = {};
innerObj[fullSubName] = subValue;
this.formDataEncodeObject(innerObj, returnKeys);
}
} else if (value !== undefined && value !== null) {
if (!(value instanceof Object)) {
returnKeys.push({
key: keysOfObj[outerIter],
value,
});
}
}
}
return returnKeys;
}
/**
* Converts an object to x-www-form-urlencoded serialization.
* @param {Object} obj The object to be serialized
* @return {String} The result of serialization
*/
static urlEncodeObject(obj) {
if (!obj) {
return null;
}
const params = this.formDataEncodeObject(obj);
let query = '';
const index = Object.keys(params);
for (let iter = 0; iter < index.length; iter += 1) {
const pair = params[index[iter]];
const key = pair.key;
const value = pair.value;
query += `${encodeURIComponent(key)}=${encodeURIComponent(value)}&`;
}
return query.length ? query.substr(0, query.length - 1) : query;
}
/**
* Returns Datetime string value for field
* @param value {object} Datetime object
* @param type {string} The Datetime format of the date object (value) passed in
* @returns {string} Stringified Datetime object
*/
static stringifyDateTime(value, type) {
if (value === null || value === undefined) {
return null;
}
switch (type) {
case 'unixtimestamp':
return value.getTime();
case 'rfc1123':
return value.toUTCString();
case 'rfc3339':
return value.format();
case 'date':
return value.format('YYYY-MM-DD');
default:
return value.format('YYYY-MM-DD');
}
}
}
module.exports = APIHelper;
|
import OSMFire_Core from 'MainCore'
//******************************************************
//Responsible for making AJAX calls to server API
//******************************************************
OSMFire_Core.jQueryAjaxEngine = (function () {
let self = {},
response, callbackFunc, page
self.makeAjaxCall = function (apiURL, QueryStr, callBackFunction, method) {
callbackFunc = callBackFunction
self.makeAjaxCallToServer(apiURL, QueryStr, (method || 'GET'), callbackFunc)
}
self.returnResults = function (handler) {
if (response) {
// return the result back to the caller
handler(response)
} else {
self.showErrorMessage('No response has been returned from the AJAX call')
}
}
self.loadPageByAjax = function (elemToAttachTo, pageSrc, sectionToExtractId, callbackFunc) {
// if an id was sent then we need to extract only that piece from the loaded page
if (sectionToExtractId) {
pageSrc = ' #' + sectionToExtractId
}
$(elemToAttachTo).load(pageSrc, function(responseText, textStatus, XMLHttpRequest) {
if (textStatus === 'success') {
if (typeof callbackFunc === 'function') {
callbackFunc()
}
return true
}
if (textStatus === 'error') {
self.showErrorMessage('Ajax load has failed from loadPage method.')
return false
}
})
}
self.getJSONObj = function (url, callbackFunc) {
$.getJSON(url, function(data) {
callbackFunc(data)
}).fail(function() {
self.showErrorMessage('Was not able to load page, from loadJSON method')
})
}
self.makeAjaxCallToServer = function (url, theQuery, method, handler) {
// need this for IE call
jQuery.support.cors = true
$.ajax({
url: url,
data: theQuery,
type: method,
processData: true,
crossDomain: true,
timeout: 10000,
// dataType: "json",
success: function(response) {
try {
// create a json object from the response. this is required for firefox.
response = JSON.parse(response)
} catch (e) {
// if it is not a json object then send as a string
response = response
}
},
error: function(request, type, errorThrown) {
let errorMsg
switch (type) {
case 'abort':
errorMsg = 'AJAX call has been aborted'
return
case 'timeout':
errorMsg = 'AJAX call has timedout'
break
case 'notmodified':
errorMsg = 'AJAX call has been notmodified'
break
case 'parseerror':
errorMsg = 'AJAX Engine parse error'
break
default:
errorMsg = 'A general error in AjaxEngine'
}
self.showErrorMessage(errorMsg + errorThrown)
},
fail: function(msg) {
self.showErrorMessage('Failure in AjaxEngine ' + msg)
}
}).done(function() {
// after the ajax call has returned values, call the function to return it to the caller
self.returnResults(handler)
}).always(function() {
self.showInfoMessage('Ajax call was initiated', 'orange')
})
}
self.showErrorMessage = function (message, color) {
let msgColor = color || 'red'
if (OSMFire_Core.log) {
OSMFire_Core.log(3, message, msgColor)
} else {
console.error(message)
}
}
self.showInfoMessage = function (message, color) {
const msgColor = color || 'blue'
if (OSMFire_Core.log) {
OSMFire_Core.log(1, message, msgColor)
} else {
console.error(message)
}
}
self.initialize = function () {
self.showInfoMessage('AjaxEngine Module has been initialized...')
}
// register with MainCore
self.register = (function () {
OSMFire_Core.registerModule(self)
})()
return {
makeAjaxCall: self.makeAjaxCall,
loadPageByAjax: self.loadPageByAjax,
getJSONObj: self.getJSONObj
}
})
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Fiber} from './ReactInternalTypes';
import type {ExpirationTime} from './ReactFiberExpirationTime.old';
import type {
ReactFundamentalComponentInstance,
ReactScopeInstance,
} from 'shared/ReactTypes';
import type {FiberRoot} from './ReactInternalTypes';
import type {
Instance,
Type,
Props,
Container,
ChildSet,
} from './ReactFiberHostConfig';
import type {
SuspenseState,
SuspenseListRenderState,
} from './ReactFiberSuspenseComponent.old';
import type {SuspenseContext} from './ReactFiberSuspenseContext.old';
import {resetWorkInProgressVersions as resetMutableSourceWorkInProgressVersions} from './ReactMutableSource.old';
import {now} from './SchedulerWithReactIntegration.old';
import {
IndeterminateComponent,
FunctionComponent,
ClassComponent,
HostRoot,
HostComponent,
HostText,
HostPortal,
ContextProvider,
ContextConsumer,
ForwardRef,
Fragment,
Mode,
Profiler,
SuspenseComponent,
SuspenseListComponent,
MemoComponent,
SimpleMemoComponent,
LazyComponent,
IncompleteClassComponent,
FundamentalComponent,
ScopeComponent,
Block,
} from './ReactWorkTags';
import {NoMode, BlockingMode, ProfileMode} from './ReactTypeOfMode';
import {
Ref,
Update,
NoEffect,
DidCapture,
Deletion,
Snapshot,
} from './ReactSideEffectTags';
import invariant from 'shared/invariant';
import {
createInstance,
createTextInstance,
appendInitialChild,
finalizeInitialChildren,
prepareUpdate,
supportsMutation,
supportsPersistence,
cloneInstance,
cloneHiddenInstance,
cloneHiddenTextInstance,
createContainerChildSet,
appendChildToContainerChildSet,
finalizeContainerChildren,
getFundamentalComponentInstance,
mountFundamentalComponent,
cloneFundamentalInstance,
shouldUpdateFundamentalComponent,
preparePortalMount,
prepareScopeUpdate,
} from './ReactFiberHostConfig';
import {
getRootHostContainer,
popHostContext,
getHostContext,
popHostContainer,
} from './ReactFiberHostContext.old';
import {
suspenseStackCursor,
InvisibleParentSuspenseContext,
hasSuspenseContext,
popSuspenseContext,
pushSuspenseContext,
setShallowSuspenseContext,
ForceSuspenseFallback,
setDefaultShallowSuspenseContext,
} from './ReactFiberSuspenseContext.old';
import {findFirstSuspended} from './ReactFiberSuspenseComponent.old';
import {
isContextProvider as isLegacyContextProvider,
popContext as popLegacyContext,
popTopLevelContextObject as popTopLevelLegacyContextObject,
} from './ReactFiberContext.old';
import {popProvider} from './ReactFiberNewContext.old';
import {
prepareToHydrateHostInstance,
prepareToHydrateHostTextInstance,
prepareToHydrateHostSuspenseInstance,
popHydrationState,
resetHydrationState,
getIsHydrating,
} from './ReactFiberHydrationContext.old';
import {
enableSchedulerTracing,
enableSuspenseCallback,
enableSuspenseServerRenderer,
enableDeprecatedFlareAPI,
enableFundamentalAPI,
enableScopeAPI,
enableBlocksAPI,
enableProfilerTimer,
} from 'shared/ReactFeatureFlags';
import {
markSpawnedWork,
renderDidSuspend,
renderDidSuspendDelayIfPossible,
renderHasNotSuspendedYet,
} from './ReactFiberWorkLoop.old';
import {createFundamentalStateInstance} from './ReactFiberFundamental.old';
import {Never} from './ReactFiberExpirationTime.old';
import {resetChildFibers} from './ReactChildFiber.old';
import {updateDeprecatedEventListeners} from './ReactFiberDeprecatedEvents.old';
import {createScopeInstance} from './ReactFiberScope.old';
import {transferActualDuration} from './ReactProfilerTimer.old';
function markUpdate(workInProgress: Fiber) {
// Tag the fiber with an update effect. This turns a Placement into
// a PlacementAndUpdate.
workInProgress.effectTag |= Update;
}
function markRef(workInProgress: Fiber) {
workInProgress.effectTag |= Ref;
}
let appendAllChildren;
let updateHostContainer;
let updateHostComponent;
let updateHostText;
if (supportsMutation) {
// Mutation mode
appendAllChildren = function(
parent: Instance,
workInProgress: Fiber,
needsVisibilityToggle: boolean,
isHidden: boolean,
) {
// We only have the top Fiber that was created but we need recurse down its
// children to find all the terminal nodes.
let node = workInProgress.child;
while (node !== null) {
if (node.tag === HostComponent || node.tag === HostText) {
appendInitialChild(parent, node.stateNode);
} else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
appendInitialChild(parent, node.stateNode.instance);
} else if (node.tag === HostPortal) {
// If we have a portal child, then we don't want to traverse
// down its children. Instead, we'll get insertions from each child in
// the portal directly.
} else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
if (node === workInProgress) {
return;
}
while (node.sibling === null) {
if (node.return === null || node.return === workInProgress) {
return;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
};
updateHostContainer = function(workInProgress: Fiber) {
// Noop
};
updateHostComponent = function(
current: Fiber,
workInProgress: Fiber,
type: Type,
newProps: Props,
rootContainerInstance: Container,
) {
// If we have an alternate, that means this is an update and we need to
// schedule a side-effect to do the updates.
const oldProps = current.memoizedProps;
if (oldProps === newProps) {
// In mutation mode, this is sufficient for a bailout because
// we won't touch this node even if children changed.
return;
}
// If we get updated because one of our children updated, we don't
// have newProps so we'll have to reuse them.
// TODO: Split the update API as separate for the props vs. children.
// Even better would be if children weren't special cased at all tho.
const instance: Instance = workInProgress.stateNode;
const currentHostContext = getHostContext();
// TODO: Experiencing an error where oldProps is null. Suggests a host
// component is hitting the resume path. Figure out why. Possibly
// related to `hidden`.
const updatePayload = prepareUpdate(
instance,
type,
oldProps,
newProps,
rootContainerInstance,
currentHostContext,
);
// TODO: Type this specific to this type of component.
workInProgress.updateQueue = (updatePayload: any);
// If the update payload indicates that there is a change or if there
// is a new ref we mark this as an update. All the work is done in commitWork.
if (updatePayload) {
markUpdate(workInProgress);
}
};
updateHostText = function(
current: Fiber,
workInProgress: Fiber,
oldText: string,
newText: string,
) {
// If the text differs, mark it as an update. All the work in done in commitWork.
if (oldText !== newText) {
markUpdate(workInProgress);
}
};
} else if (supportsPersistence) {
// Persistent host tree mode
appendAllChildren = function(
parent: Instance,
workInProgress: Fiber,
needsVisibilityToggle: boolean,
isHidden: boolean,
) {
// We only have the top Fiber that was created but we need recurse down its
// children to find all the terminal nodes.
let node = workInProgress.child;
while (node !== null) {
// eslint-disable-next-line no-labels
branches: if (node.tag === HostComponent) {
let instance = node.stateNode;
if (needsVisibilityToggle && isHidden) {
// This child is inside a timed out tree. Hide it.
const props = node.memoizedProps;
const type = node.type;
instance = cloneHiddenInstance(instance, type, props, node);
}
appendInitialChild(parent, instance);
} else if (node.tag === HostText) {
let instance = node.stateNode;
if (needsVisibilityToggle && isHidden) {
// This child is inside a timed out tree. Hide it.
const text = node.memoizedProps;
instance = cloneHiddenTextInstance(instance, text, node);
}
appendInitialChild(parent, instance);
} else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
let instance = node.stateNode.instance;
if (needsVisibilityToggle && isHidden) {
// This child is inside a timed out tree. Hide it.
const props = node.memoizedProps;
const type = node.type;
instance = cloneHiddenInstance(instance, type, props, node);
}
appendInitialChild(parent, instance);
} else if (node.tag === HostPortal) {
// If we have a portal child, then we don't want to traverse
// down its children. Instead, we'll get insertions from each child in
// the portal directly.
} else if (node.tag === SuspenseComponent) {
if ((node.effectTag & Update) !== NoEffect) {
// Need to toggle the visibility of the primary children.
const newIsHidden = node.memoizedState !== null;
if (newIsHidden) {
const primaryChildParent = node.child;
if (primaryChildParent !== null) {
if (primaryChildParent.child !== null) {
primaryChildParent.child.return = primaryChildParent;
appendAllChildren(
parent,
primaryChildParent,
true,
newIsHidden,
);
}
const fallbackChildParent = primaryChildParent.sibling;
if (fallbackChildParent !== null) {
fallbackChildParent.return = node;
node = fallbackChildParent;
continue;
}
}
}
}
if (node.child !== null) {
// Continue traversing like normal
node.child.return = node;
node = node.child;
continue;
}
} else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
// $FlowFixMe This is correct but Flow is confused by the labeled break.
node = (node: Fiber);
if (node === workInProgress) {
return;
}
while (node.sibling === null) {
if (node.return === null || node.return === workInProgress) {
return;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
};
// An unfortunate fork of appendAllChildren because we have two different parent types.
const appendAllChildrenToContainer = function(
containerChildSet: ChildSet,
workInProgress: Fiber,
needsVisibilityToggle: boolean,
isHidden: boolean,
) {
// We only have the top Fiber that was created but we need recurse down its
// children to find all the terminal nodes.
let node = workInProgress.child;
while (node !== null) {
// eslint-disable-next-line no-labels
branches: if (node.tag === HostComponent) {
let instance = node.stateNode;
if (needsVisibilityToggle && isHidden) {
// This child is inside a timed out tree. Hide it.
const props = node.memoizedProps;
const type = node.type;
instance = cloneHiddenInstance(instance, type, props, node);
}
appendChildToContainerChildSet(containerChildSet, instance);
} else if (node.tag === HostText) {
let instance = node.stateNode;
if (needsVisibilityToggle && isHidden) {
// This child is inside a timed out tree. Hide it.
const text = node.memoizedProps;
instance = cloneHiddenTextInstance(instance, text, node);
}
appendChildToContainerChildSet(containerChildSet, instance);
} else if (enableFundamentalAPI && node.tag === FundamentalComponent) {
let instance = node.stateNode.instance;
if (needsVisibilityToggle && isHidden) {
// This child is inside a timed out tree. Hide it.
const props = node.memoizedProps;
const type = node.type;
instance = cloneHiddenInstance(instance, type, props, node);
}
appendChildToContainerChildSet(containerChildSet, instance);
} else if (node.tag === HostPortal) {
// If we have a portal child, then we don't want to traverse
// down its children. Instead, we'll get insertions from each child in
// the portal directly.
} else if (node.tag === SuspenseComponent) {
if ((node.effectTag & Update) !== NoEffect) {
// Need to toggle the visibility of the primary children.
const newIsHidden = node.memoizedState !== null;
if (newIsHidden) {
const primaryChildParent = node.child;
if (primaryChildParent !== null) {
if (primaryChildParent.child !== null) {
primaryChildParent.child.return = primaryChildParent;
appendAllChildrenToContainer(
containerChildSet,
primaryChildParent,
true,
newIsHidden,
);
}
const fallbackChildParent = primaryChildParent.sibling;
if (fallbackChildParent !== null) {
fallbackChildParent.return = node;
node = fallbackChildParent;
continue;
}
}
}
}
if (node.child !== null) {
// Continue traversing like normal
node.child.return = node;
node = node.child;
continue;
}
} else if (node.child !== null) {
node.child.return = node;
node = node.child;
continue;
}
// $FlowFixMe This is correct but Flow is confused by the labeled break.
node = (node: Fiber);
if (node === workInProgress) {
return;
}
while (node.sibling === null) {
if (node.return === null || node.return === workInProgress) {
return;
}
node = node.return;
}
node.sibling.return = node.return;
node = node.sibling;
}
};
updateHostContainer = function(workInProgress: Fiber) {
const portalOrRoot: {
containerInfo: Container,
pendingChildren: ChildSet,
...
} = workInProgress.stateNode;
const childrenUnchanged = workInProgress.firstEffect === null;
if (childrenUnchanged) {
// No changes, just reuse the existing instance.
} else {
const container = portalOrRoot.containerInfo;
const newChildSet = createContainerChildSet(container);
// If children might have changed, we have to add them all to the set.
appendAllChildrenToContainer(newChildSet, workInProgress, false, false);
portalOrRoot.pendingChildren = newChildSet;
// Schedule an update on the container to swap out the container.
markUpdate(workInProgress);
finalizeContainerChildren(container, newChildSet);
}
};
updateHostComponent = function(
current: Fiber,
workInProgress: Fiber,
type: Type,
newProps: Props,
rootContainerInstance: Container,
) {
const currentInstance = current.stateNode;
const oldProps = current.memoizedProps;
// If there are no effects associated with this node, then none of our children had any updates.
// This guarantees that we can reuse all of them.
const childrenUnchanged = workInProgress.firstEffect === null;
if (childrenUnchanged && oldProps === newProps) {
// No changes, just reuse the existing instance.
// Note that this might release a previous clone.
workInProgress.stateNode = currentInstance;
return;
}
const recyclableInstance: Instance = workInProgress.stateNode;
const currentHostContext = getHostContext();
let updatePayload = null;
if (oldProps !== newProps) {
updatePayload = prepareUpdate(
recyclableInstance,
type,
oldProps,
newProps,
rootContainerInstance,
currentHostContext,
);
}
if (childrenUnchanged && updatePayload === null) {
// No changes, just reuse the existing instance.
// Note that this might release a previous clone.
workInProgress.stateNode = currentInstance;
return;
}
const newInstance = cloneInstance(
currentInstance,
updatePayload,
type,
oldProps,
newProps,
workInProgress,
childrenUnchanged,
recyclableInstance,
);
if (
finalizeInitialChildren(
newInstance,
type,
newProps,
rootContainerInstance,
currentHostContext,
)
) {
markUpdate(workInProgress);
}
workInProgress.stateNode = newInstance;
if (childrenUnchanged) {
// If there are no other effects in this tree, we need to flag this node as having one.
// Even though we're not going to use it for anything.
// Otherwise parents won't know that there are new children to propagate upwards.
markUpdate(workInProgress);
} else {
// If children might have changed, we have to add them all to the set.
appendAllChildren(newInstance, workInProgress, false, false);
}
};
updateHostText = function(
current: Fiber,
workInProgress: Fiber,
oldText: string,
newText: string,
) {
if (oldText !== newText) {
// If the text content differs, we'll create a new text instance for it.
const rootContainerInstance = getRootHostContainer();
const currentHostContext = getHostContext();
workInProgress.stateNode = createTextInstance(
newText,
rootContainerInstance,
currentHostContext,
workInProgress,
);
// We'll have to mark it as having an effect, even though we won't use the effect for anything.
// This lets the parents know that at least one of their children has changed.
markUpdate(workInProgress);
} else {
workInProgress.stateNode = current.stateNode;
}
};
} else {
// No host operations
updateHostContainer = function(workInProgress: Fiber) {
// Noop
};
updateHostComponent = function(
current: Fiber,
workInProgress: Fiber,
type: Type,
newProps: Props,
rootContainerInstance: Container,
) {
// Noop
};
updateHostText = function(
current: Fiber,
workInProgress: Fiber,
oldText: string,
newText: string,
) {
// Noop
};
}
function cutOffTailIfNeeded(
renderState: SuspenseListRenderState,
hasRenderedATailFallback: boolean,
) {
if (getIsHydrating()) {
// If we're hydrating, we should consume as many items as we can
// so we don't leave any behind.
return;
}
switch (renderState.tailMode) {
case 'hidden': {
// Any insertions at the end of the tail list after this point
// should be invisible. If there are already mounted boundaries
// anything before them are not considered for collapsing.
// Therefore we need to go through the whole tail to find if
// there are any.
let tailNode = renderState.tail;
let lastTailNode = null;
while (tailNode !== null) {
if (tailNode.alternate !== null) {
lastTailNode = tailNode;
}
tailNode = tailNode.sibling;
}
// Next we're simply going to delete all insertions after the
// last rendered item.
if (lastTailNode === null) {
// All remaining items in the tail are insertions.
renderState.tail = null;
} else {
// Detach the insertion after the last node that was already
// inserted.
lastTailNode.sibling = null;
}
break;
}
case 'collapsed': {
// Any insertions at the end of the tail list after this point
// should be invisible. If there are already mounted boundaries
// anything before them are not considered for collapsing.
// Therefore we need to go through the whole tail to find if
// there are any.
let tailNode = renderState.tail;
let lastTailNode = null;
while (tailNode !== null) {
if (tailNode.alternate !== null) {
lastTailNode = tailNode;
}
tailNode = tailNode.sibling;
}
// Next we're simply going to delete all insertions after the
// last rendered item.
if (lastTailNode === null) {
// All remaining items in the tail are insertions.
if (!hasRenderedATailFallback && renderState.tail !== null) {
// We suspended during the head. We want to show at least one
// row at the tail. So we'll keep on and cut off the rest.
renderState.tail.sibling = null;
} else {
renderState.tail = null;
}
} else {
// Detach the insertion after the last node that was already
// inserted.
lastTailNode.sibling = null;
}
break;
}
}
}
function completeWork(
current: Fiber | null,
workInProgress: Fiber,
renderExpirationTime: ExpirationTime,
): Fiber | null {
const newProps = workInProgress.pendingProps;
switch (workInProgress.tag) {
case IndeterminateComponent:
case LazyComponent:
case SimpleMemoComponent:
case FunctionComponent:
case ForwardRef:
case Fragment:
case Mode:
case Profiler:
case ContextConsumer:
case MemoComponent:
return null;
case ClassComponent: {
const Component = workInProgress.type;
if (isLegacyContextProvider(Component)) {
popLegacyContext(workInProgress);
}
return null;
}
case HostRoot: {
popHostContainer(workInProgress);
popTopLevelLegacyContextObject(workInProgress);
resetMutableSourceWorkInProgressVersions();
const fiberRoot = (workInProgress.stateNode: FiberRoot);
if (fiberRoot.pendingContext) {
fiberRoot.context = fiberRoot.pendingContext;
fiberRoot.pendingContext = null;
}
if (current === null || current.child === null) {
// If we hydrated, pop so that we can delete any remaining children
// that weren't hydrated.
const wasHydrated = popHydrationState(workInProgress);
if (wasHydrated) {
// If we hydrated, then we'll need to schedule an update for
// the commit side-effects on the root.
markUpdate(workInProgress);
} else if (!fiberRoot.hydrate) {
// Schedule an effect to clear this container at the start of the next commit.
// This handles the case of React rendering into a container with previous children.
// It's also safe to do for updates too, because current.child would only be null
// if the previous render was null (so the the container would already be empty).
workInProgress.effectTag |= Snapshot;
}
}
updateHostContainer(workInProgress);
return null;
}
case HostComponent: {
popHostContext(workInProgress);
const rootContainerInstance = getRootHostContainer();
const type = workInProgress.type;
if (current !== null && workInProgress.stateNode != null) {
updateHostComponent(
current,
workInProgress,
type,
newProps,
rootContainerInstance,
);
if (enableDeprecatedFlareAPI) {
const prevListeners = current.memoizedProps.DEPRECATED_flareListeners;
const nextListeners = newProps.DEPRECATED_flareListeners;
if (prevListeners !== nextListeners) {
markUpdate(workInProgress);
}
}
if (current.ref !== workInProgress.ref) {
markRef(workInProgress);
}
} else {
if (!newProps) {
invariant(
workInProgress.stateNode !== null,
'We must have new props for new mounts. This error is likely ' +
'caused by a bug in React. Please file an issue.',
);
// This can happen when we abort work.
return null;
}
const currentHostContext = getHostContext();
// TODO: Move createInstance to beginWork and keep it on a context
// "stack" as the parent. Then append children as we go in beginWork
// or completeWork depending on whether we want to add them top->down or
// bottom->up. Top->down is faster in IE11.
const wasHydrated = popHydrationState(workInProgress);
if (wasHydrated) {
// TODO: Move this and createInstance step into the beginPhase
// to consolidate.
if (
prepareToHydrateHostInstance(
workInProgress,
rootContainerInstance,
currentHostContext,
)
) {
// If changes to the hydrated node need to be applied at the
// commit-phase we mark this as such.
markUpdate(workInProgress);
}
if (enableDeprecatedFlareAPI) {
const listeners = newProps.DEPRECATED_flareListeners;
if (listeners != null) {
updateDeprecatedEventListeners(
listeners,
workInProgress,
rootContainerInstance,
);
}
}
} else {
const instance = createInstance(
type,
newProps,
rootContainerInstance,
currentHostContext,
workInProgress,
);
appendAllChildren(instance, workInProgress, false, false);
// This needs to be set before we mount Flare event listeners
workInProgress.stateNode = instance;
if (enableDeprecatedFlareAPI) {
const listeners = newProps.DEPRECATED_flareListeners;
if (listeners != null) {
updateDeprecatedEventListeners(
listeners,
workInProgress,
rootContainerInstance,
);
}
}
// Certain renderers require commit-time effects for initial mount.
// (eg DOM renderer supports auto-focus for certain elements).
// Make sure such renderers get scheduled for later work.
if (
finalizeInitialChildren(
instance,
type,
newProps,
rootContainerInstance,
currentHostContext,
)
) {
markUpdate(workInProgress);
}
}
if (workInProgress.ref !== null) {
// If there is a ref on a host node we need to schedule a callback
markRef(workInProgress);
}
}
return null;
}
case HostText: {
const newText = newProps;
if (current && workInProgress.stateNode != null) {
const oldText = current.memoizedProps;
// If we have an alternate, that means this is an update and we need
// to schedule a side-effect to do the updates.
updateHostText(current, workInProgress, oldText, newText);
} else {
if (typeof newText !== 'string') {
invariant(
workInProgress.stateNode !== null,
'We must have new props for new mounts. This error is likely ' +
'caused by a bug in React. Please file an issue.',
);
// This can happen when we abort work.
}
const rootContainerInstance = getRootHostContainer();
const currentHostContext = getHostContext();
const wasHydrated = popHydrationState(workInProgress);
if (wasHydrated) {
if (prepareToHydrateHostTextInstance(workInProgress)) {
markUpdate(workInProgress);
}
} else {
workInProgress.stateNode = createTextInstance(
newText,
rootContainerInstance,
currentHostContext,
workInProgress,
);
}
}
return null;
}
case SuspenseComponent: {
popSuspenseContext(workInProgress);
const nextState: null | SuspenseState = workInProgress.memoizedState;
if (enableSuspenseServerRenderer) {
if (nextState !== null && nextState.dehydrated !== null) {
if (current === null) {
const wasHydrated = popHydrationState(workInProgress);
invariant(
wasHydrated,
'A dehydrated suspense component was completed without a hydrated node. ' +
'This is probably a bug in React.',
);
prepareToHydrateHostSuspenseInstance(workInProgress);
if (enableSchedulerTracing) {
markSpawnedWork(Never);
}
return null;
} else {
// We should never have been in a hydration state if we didn't have a current.
// However, in some of those paths, we might have reentered a hydration state
// and then we might be inside a hydration state. In that case, we'll need to exit out of it.
resetHydrationState();
if ((workInProgress.effectTag & DidCapture) === NoEffect) {
// This boundary did not suspend so it's now hydrated and unsuspended.
workInProgress.memoizedState = null;
}
// If nothing suspended, we need to schedule an effect to mark this boundary
// as having hydrated so events know that they're free to be invoked.
// It's also a signal to replay events and the suspense callback.
// If something suspended, schedule an effect to attach retry listeners.
// So we might as well always mark this.
workInProgress.effectTag |= Update;
return null;
}
}
}
if ((workInProgress.effectTag & DidCapture) !== NoEffect) {
// Something suspended. Re-render with the fallback children.
workInProgress.expirationTime = renderExpirationTime;
if (
enableProfilerTimer &&
(workInProgress.mode & ProfileMode) !== NoMode
) {
transferActualDuration(workInProgress);
}
// Do not reset the effect list.
return workInProgress;
}
const nextDidTimeout = nextState !== null;
let prevDidTimeout = false;
if (current === null) {
if (workInProgress.memoizedProps.fallback !== undefined) {
popHydrationState(workInProgress);
}
} else {
const prevState: null | SuspenseState = current.memoizedState;
prevDidTimeout = prevState !== null;
if (!nextDidTimeout && prevState !== null) {
// We just switched from the fallback to the normal children.
// Delete the fallback.
// TODO: Would it be better to store the fallback fragment on
// the stateNode during the begin phase?
const currentFallbackChild: Fiber | null = (current.child: any)
.sibling;
if (currentFallbackChild !== null) {
// Deletions go at the beginning of the return fiber's effect list
const first = workInProgress.firstEffect;
if (first !== null) {
workInProgress.firstEffect = currentFallbackChild;
currentFallbackChild.nextEffect = first;
} else {
workInProgress.firstEffect = workInProgress.lastEffect = currentFallbackChild;
currentFallbackChild.nextEffect = null;
}
currentFallbackChild.effectTag = Deletion;
}
}
}
if (nextDidTimeout && !prevDidTimeout) {
// If this subtreee is running in blocking mode we can suspend,
// otherwise we won't suspend.
// TODO: This will still suspend a synchronous tree if anything
// in the concurrent tree already suspended during this render.
// This is a known bug.
if ((workInProgress.mode & BlockingMode) !== NoMode) {
// TODO: Move this back to throwException because this is too late
// if this is a large tree which is common for initial loads. We
// don't know if we should restart a render or not until we get
// this marker, and this is too late.
// If this render already had a ping or lower pri updates,
// and this is the first time we know we're going to suspend we
// should be able to immediately restart from within throwException.
const hasInvisibleChildContext =
current === null &&
workInProgress.memoizedProps.unstable_avoidThisFallback !== true;
if (
hasInvisibleChildContext ||
hasSuspenseContext(
suspenseStackCursor.current,
(InvisibleParentSuspenseContext: SuspenseContext),
)
) {
// If this was in an invisible tree or a new render, then showing
// this boundary is ok.
renderDidSuspend();
} else {
// Otherwise, we're going to have to hide content so we should
// suspend for longer if possible.
renderDidSuspendDelayIfPossible();
}
}
}
if (supportsPersistence) {
// TODO: Only schedule updates if not prevDidTimeout.
if (nextDidTimeout) {
// If this boundary just timed out, schedule an effect to attach a
// retry listener to the promise. This flag is also used to hide the
// primary children.
workInProgress.effectTag |= Update;
}
}
if (supportsMutation) {
// TODO: Only schedule updates if these values are non equal, i.e. it changed.
if (nextDidTimeout || prevDidTimeout) {
// If this boundary just timed out, schedule an effect to attach a
// retry listener to the promise. This flag is also used to hide the
// primary children. In mutation mode, we also need the flag to
// *unhide* children that were previously hidden, so check if this
// is currently timed out, too.
workInProgress.effectTag |= Update;
}
}
if (
enableSuspenseCallback &&
workInProgress.updateQueue !== null &&
workInProgress.memoizedProps.suspenseCallback != null
) {
// Always notify the callback
workInProgress.effectTag |= Update;
}
return null;
}
case HostPortal:
popHostContainer(workInProgress);
updateHostContainer(workInProgress);
if (current === null) {
preparePortalMount(workInProgress.stateNode.containerInfo);
}
return null;
case ContextProvider:
// Pop provider fiber
popProvider(workInProgress);
return null;
case IncompleteClassComponent: {
// Same as class component case. I put it down here so that the tags are
// sequential to ensure this switch is compiled to a jump table.
const Component = workInProgress.type;
if (isLegacyContextProvider(Component)) {
popLegacyContext(workInProgress);
}
return null;
}
case SuspenseListComponent: {
popSuspenseContext(workInProgress);
const renderState: null | SuspenseListRenderState =
workInProgress.memoizedState;
if (renderState === null) {
// We're running in the default, "independent" mode.
// We don't do anything in this mode.
return null;
}
let didSuspendAlready =
(workInProgress.effectTag & DidCapture) !== NoEffect;
const renderedTail = renderState.rendering;
if (renderedTail === null) {
// We just rendered the head.
if (!didSuspendAlready) {
// This is the first pass. We need to figure out if anything is still
// suspended in the rendered set.
// If new content unsuspended, but there's still some content that
// didn't. Then we need to do a second pass that forces everything
// to keep showing their fallbacks.
// We might be suspended if something in this render pass suspended, or
// something in the previous committed pass suspended. Otherwise,
// there's no chance so we can skip the expensive call to
// findFirstSuspended.
const cannotBeSuspended =
renderHasNotSuspendedYet() &&
(current === null || (current.effectTag & DidCapture) === NoEffect);
if (!cannotBeSuspended) {
let row = workInProgress.child;
while (row !== null) {
const suspended = findFirstSuspended(row);
if (suspended !== null) {
didSuspendAlready = true;
workInProgress.effectTag |= DidCapture;
cutOffTailIfNeeded(renderState, false);
// If this is a newly suspended tree, it might not get committed as
// part of the second pass. In that case nothing will subscribe to
// its thennables. Instead, we'll transfer its thennables to the
// SuspenseList so that it can retry if they resolve.
// There might be multiple of these in the list but since we're
// going to wait for all of them anyway, it doesn't really matter
// which ones gets to ping. In theory we could get clever and keep
// track of how many dependencies remain but it gets tricky because
// in the meantime, we can add/remove/change items and dependencies.
// We might bail out of the loop before finding any but that
// doesn't matter since that means that the other boundaries that
// we did find already has their listeners attached.
const newThennables = suspended.updateQueue;
if (newThennables !== null) {
workInProgress.updateQueue = newThennables;
workInProgress.effectTag |= Update;
}
// Rerender the whole list, but this time, we'll force fallbacks
// to stay in place.
// Reset the effect list before doing the second pass since that's now invalid.
if (renderState.lastEffect === null) {
workInProgress.firstEffect = null;
}
workInProgress.lastEffect = renderState.lastEffect;
// Reset the child fibers to their original state.
resetChildFibers(workInProgress, renderExpirationTime);
// Set up the Suspense Context to force suspense and immediately
// rerender the children.
pushSuspenseContext(
workInProgress,
setShallowSuspenseContext(
suspenseStackCursor.current,
ForceSuspenseFallback,
),
);
return workInProgress.child;
}
row = row.sibling;
}
}
} else {
cutOffTailIfNeeded(renderState, false);
}
// Next we're going to render the tail.
} else {
// Append the rendered row to the child list.
if (!didSuspendAlready) {
const suspended = findFirstSuspended(renderedTail);
if (suspended !== null) {
workInProgress.effectTag |= DidCapture;
didSuspendAlready = true;
// Ensure we transfer the update queue to the parent so that it doesn't
// get lost if this row ends up dropped during a second pass.
const newThennables = suspended.updateQueue;
if (newThennables !== null) {
workInProgress.updateQueue = newThennables;
workInProgress.effectTag |= Update;
}
cutOffTailIfNeeded(renderState, true);
// This might have been modified.
if (
renderState.tail === null &&
renderState.tailMode === 'hidden' &&
!renderedTail.alternate &&
!getIsHydrating() // We don't cut it if we're hydrating.
) {
// We need to delete the row we just rendered.
// Reset the effect list to what it was before we rendered this
// child. The nested children have already appended themselves.
const lastEffect = (workInProgress.lastEffect =
renderState.lastEffect);
// Remove any effects that were appended after this point.
if (lastEffect !== null) {
lastEffect.nextEffect = null;
}
// We're done.
return null;
}
} else if (
// The time it took to render last row is greater than time until
// the expiration.
now() * 2 - renderState.renderingStartTime >
renderState.tailExpiration &&
renderExpirationTime > Never
) {
// We have now passed our CPU deadline and we'll just give up further
// attempts to render the main content and only render fallbacks.
// The assumption is that this is usually faster.
workInProgress.effectTag |= DidCapture;
didSuspendAlready = true;
cutOffTailIfNeeded(renderState, false);
// Since nothing actually suspended, there will nothing to ping this
// to get it started back up to attempt the next item. If we can show
// them, then they really have the same priority as this render.
// So we'll pick it back up the very next render pass once we've had
// an opportunity to yield for paint.
const nextPriority = renderExpirationTime - 1;
workInProgress.expirationTime = workInProgress.childExpirationTime = nextPriority;
if (enableSchedulerTracing) {
markSpawnedWork(nextPriority);
}
}
}
if (renderState.isBackwards) {
// The effect list of the backwards tail will have been added
// to the end. This breaks the guarantee that life-cycles fire in
// sibling order but that isn't a strong guarantee promised by React.
// Especially since these might also just pop in during future commits.
// Append to the beginning of the list.
renderedTail.sibling = workInProgress.child;
workInProgress.child = renderedTail;
} else {
const previousSibling = renderState.last;
if (previousSibling !== null) {
previousSibling.sibling = renderedTail;
} else {
workInProgress.child = renderedTail;
}
renderState.last = renderedTail;
}
}
if (renderState.tail !== null) {
// We still have tail rows to render.
if (renderState.tailExpiration === 0) {
// Heuristic for how long we're willing to spend rendering rows
// until we just give up and show what we have so far.
const TAIL_EXPIRATION_TIMEOUT_MS = 500;
renderState.tailExpiration = now() + TAIL_EXPIRATION_TIMEOUT_MS;
// TODO: This is meant to mimic the train model or JND but this
// is a per component value. It should really be since the start
// of the total render or last commit. Consider using something like
// globalMostRecentFallbackTime. That doesn't account for being
// suspended for part of the time or when it's a new render.
// It should probably use a global start time value instead.
}
// Pop a row.
const next = renderState.tail;
renderState.rendering = next;
renderState.tail = next.sibling;
renderState.lastEffect = workInProgress.lastEffect;
renderState.renderingStartTime = now();
next.sibling = null;
// Restore the context.
// TODO: We can probably just avoid popping it instead and only
// setting it the first time we go from not suspended to suspended.
let suspenseContext = suspenseStackCursor.current;
if (didSuspendAlready) {
suspenseContext = setShallowSuspenseContext(
suspenseContext,
ForceSuspenseFallback,
);
} else {
suspenseContext = setDefaultShallowSuspenseContext(suspenseContext);
}
pushSuspenseContext(workInProgress, suspenseContext);
// Do a pass over the next row.
return next;
}
return null;
}
case FundamentalComponent: {
if (enableFundamentalAPI) {
const fundamentalImpl = workInProgress.type.impl;
let fundamentalInstance: ReactFundamentalComponentInstance<
any,
any,
> | null = workInProgress.stateNode;
if (fundamentalInstance === null) {
const getInitialState = fundamentalImpl.getInitialState;
let fundamentalState;
if (getInitialState !== undefined) {
fundamentalState = getInitialState(newProps);
}
fundamentalInstance = workInProgress.stateNode = createFundamentalStateInstance(
workInProgress,
newProps,
fundamentalImpl,
fundamentalState || {},
);
const instance = ((getFundamentalComponentInstance(
fundamentalInstance,
): any): Instance);
fundamentalInstance.instance = instance;
if (fundamentalImpl.reconcileChildren === false) {
return null;
}
appendAllChildren(instance, workInProgress, false, false);
mountFundamentalComponent(fundamentalInstance);
} else {
// We fire update in commit phase
const prevProps = fundamentalInstance.props;
fundamentalInstance.prevProps = prevProps;
fundamentalInstance.props = newProps;
fundamentalInstance.currentFiber = workInProgress;
if (supportsPersistence) {
const instance = cloneFundamentalInstance(fundamentalInstance);
fundamentalInstance.instance = instance;
appendAllChildren(instance, workInProgress, false, false);
}
const shouldUpdate = shouldUpdateFundamentalComponent(
fundamentalInstance,
);
if (shouldUpdate) {
markUpdate(workInProgress);
}
}
return null;
}
break;
}
case ScopeComponent: {
if (enableScopeAPI) {
if (current === null) {
const scopeInstance: ReactScopeInstance = createScopeInstance();
workInProgress.stateNode = scopeInstance;
if (enableDeprecatedFlareAPI) {
const listeners = newProps.DEPRECATED_flareListeners;
if (listeners != null) {
const rootContainerInstance = getRootHostContainer();
updateDeprecatedEventListeners(
listeners,
workInProgress,
rootContainerInstance,
);
}
}
prepareScopeUpdate(scopeInstance, workInProgress);
if (workInProgress.ref !== null) {
markRef(workInProgress);
markUpdate(workInProgress);
}
} else {
if (enableDeprecatedFlareAPI) {
const prevListeners =
current.memoizedProps.DEPRECATED_flareListeners;
const nextListeners = newProps.DEPRECATED_flareListeners;
if (
prevListeners !== nextListeners ||
workInProgress.ref !== null
) {
markUpdate(workInProgress);
}
} else {
if (workInProgress.ref !== null) {
markUpdate(workInProgress);
}
}
if (current.ref !== workInProgress.ref) {
markRef(workInProgress);
}
}
return null;
}
break;
}
case Block:
if (enableBlocksAPI) {
return null;
}
break;
}
invariant(
false,
'Unknown unit of work tag (%s). This error is likely caused by a bug in ' +
'React. Please file an issue.',
workInProgress.tag,
);
}
export {completeWork};
|
var assert = require('assert')
, es = require('event-stream')
, StreamQueue = require('../src')
, PlatformStream = require('stream')
, Stream = require('readable-stream')
;
// Test each type of stream
[PlatformStream, Stream].slice(PlatformStream.Readable ? 0 : 1)
.forEach(function(Stream) {
// Tests
describe('StreamQueue', function() {
describe('in binary mode', function() {
describe('and with async streams', function() {
it('should work with functionnal API', function(done) {
StreamQueue(
writeToStream(new Stream.PassThrough(), ['wa','dup']),
writeToStream(new Stream.PassThrough(), ['pl','op']),
writeToStream(new Stream.PassThrough(), ['ki','koo','lol'])
).pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
});
it('should work with functionnal API and options', function(done) {
StreamQueue({pause: true},
writeToStream(new Stream.PassThrough(), ['wa','dup']),
writeToStream(new Stream.PassThrough(), ['pl','op']),
writeToStream(new Stream.PassThrough(), ['ki','koo','lol'])
).pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
});
it('should work with POO API', function(done) {
var queue = new StreamQueue();
queue.queue(writeToStream(new Stream.PassThrough(), ['wa','dup']));
queue.queue(writeToStream(new Stream.PassThrough(), ['pl','op']));
queue.queue(writeToStream(new Stream.PassThrough(), ['ki','koo','lol']));
assert.equal(queue.length, 3);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.done();
});
it('should pause streams in flowing mode', function(done) {
var queue = new StreamQueue({
pauseFlowingStream: true,
resumeFlowingStream: true
});
queue.queue(readableStream(['wa','dup']));
queue.queue(writeToStream(new Stream.PassThrough(), ['pl','op']));
queue.queue(writeToStream(new Stream.PassThrough(), ['ki','koo','lol']));
assert.equal(queue.length, 3);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.done();
});
it('should work with POO API and options', function(done) {
var queue = new StreamQueue({
pauseFlowingStream: true,
resumeFlowingStream: true
});
queue.queue(writeToStream(new Stream.PassThrough(), ['wa','dup']));
queue.queue(writeToStream(new Stream.PassThrough(), ['pl','op']));
queue.queue(writeToStream(new Stream.PassThrough(), ['ki','koo','lol']));
assert.equal(queue.length, 3);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.done();
});
it('should work with POO API and a late done call', function(done) {
var queue = new StreamQueue();
queue.queue(writeToStream(new Stream.PassThrough(), ['wa','dup']));
queue.queue(writeToStream(new Stream.PassThrough(), ['pl','op']));
queue.queue(writeToStream(new Stream.PassThrough(), ['ki','koo','lol']));
assert.equal(queue.length, 3);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
setTimeout(function() {
queue.done();
}, 100);
});
it('should work with POO API and no stream plus sync done', function(done) {
var queue = new StreamQueue();
assert.equal(queue.length, 0);
queue.queue();
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, '');
done();
}));
queue.done();
});
it('should work with POO API and no stream plus async done', function(done) {
var queue = new StreamQueue();
assert.equal(queue.length, 0);
queue.queue();
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, '');
done();
}));
setTimeout(function() {
queue.done();
}, 100);
});
it('should work with POO API and a streamqueue stream plus async done', function(done) {
var queue = new StreamQueue();
var child = new StreamQueue();
queue.queue(child);
assert.equal(queue.length, 1);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, '');
done();
}));
child.done();
setTimeout(function() {
queue.done();
}, 100);
});
it('should work with POO API and a streamqueue stream plus async done', function(done) {
var queue = new StreamQueue();
var child = new StreamQueue();
queue.queue(child);
assert.equal(queue.length, 1);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, '');
done();
}));
child.done();
queue.done();
});
it('should work with POO API and a streamqueue ended stream plus async done', function(done) {
var queue = new StreamQueue();
var child = new StreamQueue();
queue.queue(child);
child.done();
assert.equal(queue.length, 1);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, '');
done();
}));
setTimeout(function() {
queue.done();
}, 100);
});
it('should fire end asynchronously with streams', function(done) {
var queue = new StreamQueue();
var ended = false;
queue.queue(writeToStream(new Stream.PassThrough(), ['wa','dup'])
.on('end', function() {
assert.equal(ended, false);
}));
queue.queue(writeToStream(new Stream.PassThrough(), ['pl','op'])
.on('end', function() {
assert.equal(ended, false);
}));
queue.queue(writeToStream(new Stream.PassThrough(), ['ki','koo','lol'])
.on('end', function() {
assert.equal(ended, false);
}));
assert.equal(queue.length, 3);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.on('end', function() {
ended = true;
});
queue.done();
assert.equal(ended, false);
});
it('should fire end asynchronously when empty', function(done) {
var queue = new StreamQueue();
var ended = false;
assert.equal(queue.length, 0);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, '');
done();
}));
queue.on('end', function() {
ended = true;
});
queue.done();
assert.equal(ended, false);
});
it('should work with POO API and a streamqueue ended stream plus sync done', function(done) {
var queue = new StreamQueue();
var child = new StreamQueue();
queue.queue(child);
child.done();
assert.equal(queue.length, 1);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, '');
done();
}));
queue.done();
});
it('should work with POO API and a streamqueue ended stream plus async done', function(done) {
var queue = new StreamQueue();
var child = new StreamQueue();
child.done();
queue.queue(child);
assert.equal(queue.length, 1);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, '');
done();
}));
setTimeout(function() {
queue.done();
}, 100);
});
it('should work with POO API and a streamqueue ended stream plus sync done', function(done) {
var queue = new StreamQueue();
var child = new StreamQueue();
child.done();
queue.queue(child);
assert.equal(queue.length, 1);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, '');
done();
}));
queue.done();
});
it('should reemit errors', function(done) {
var gotError = false;
var queue = new StreamQueue();
queue.queue(erroredStream('Aouch!'));
queue.queue(writeToStream(new Stream.PassThrough(), ['wa','dup']));
queue.queue(writeToStream(new Stream.PassThrough(), ['pl','op']));
queue.queue(writeToStream(new Stream.PassThrough(), ['ki','koo','lol']));
assert.equal(queue.length, 4);
queue.on('error', function(err) {
gotError = true;
});
queue.pipe(es.wait(function(err, data) {
assert(gotError);
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.done();
});
});
describe('and with sync streams', function() {
it('should work with functionnal API', function(done) {
StreamQueue(
writeToStreamSync(new Stream.PassThrough(), ['wa','dup']),
writeToStreamSync(new Stream.PassThrough(), ['pl','op']),
writeToStreamSync(new Stream.PassThrough(), ['ki','koo','lol'])
).pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
});
it('should work with POO API', function(done) {
var queue = new StreamQueue();
queue.queue(writeToStreamSync(new Stream.PassThrough(), ['wa','dup']));
queue.queue(writeToStreamSync(new Stream.PassThrough(), ['pl','op']));
queue.queue(writeToStreamSync(new Stream.PassThrough(), ['ki','koo','lol']));
assert.equal(queue.length, 3);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.done();
});
it('should emit an error when calling done twice', function(done) {
var queue = new StreamQueue();
queue.queue(writeToStreamSync(new Stream.PassThrough(), ['wa','dup']));
queue.queue(writeToStreamSync(new Stream.PassThrough(), ['pl','op']));
queue.queue(writeToStreamSync(new Stream.PassThrough(), ['ki','koo','lol']));
assert.equal(queue.length, 3);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.done();
assert.throws(function() {
queue.done();
});
});
it('should emit an error when queueing after done was called', function(done) {
var queue = new StreamQueue();
queue.queue(writeToStreamSync(new Stream.PassThrough(), ['wa','dup']));
queue.queue(writeToStreamSync(new Stream.PassThrough(), ['pl','op']));
queue.queue(writeToStreamSync(new Stream.PassThrough(), ['ki','koo','lol']));
assert.equal(queue.length, 3);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.done();
assert.throws(function() {
queue.queue(new Stream.PassThrough());
});
});
it('should reemit errors', function(done) {
var gotError = false;
var queue = new StreamQueue();
queue.queue(erroredStream('Aouch!'));
queue.queue(writeToStreamSync(new Stream.PassThrough(), ['wa','dup']));
queue.queue(writeToStreamSync(new Stream.PassThrough(), ['pl','op']));
queue.queue(writeToStreamSync(new Stream.PassThrough(), ['ki','koo','lol']));
assert.equal(queue.length, 4);
queue.on('error', function(err) {
gotError = true;
assert.equal(err.message, 'Aouch!');
});
queue.pipe(es.wait(function(err, data) {
assert(gotError);
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.done();
});
});
describe('and with functions returning streams', function() {
it('should work with functionnal API', function(done) {
StreamQueue(function() {
return writeToStream(new Stream.PassThrough(), ['wa','dup']);
}, function() {
return writeToStream(new Stream.PassThrough(), ['pl','op']);
}, function() {
return writeToStream(new Stream.PassThrough(), ['ki','koo','lol']);
}).pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
});
it('should work with functionnal API and options', function(done) {
var stream1 = new Stream.PassThrough()
, stream2 = new Stream.PassThrough()
, stream3 = new Stream.PassThrough()
;
StreamQueue({pause: true},
function() {
return writeToStream(new Stream.PassThrough(), ['wa','dup']);
}, function() {
return writeToStream(new Stream.PassThrough(), ['pl','op']);
}, function() {
return writeToStream(new Stream.PassThrough(), ['ki','koo','lol']);
})
.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
});
it('should work with POO API', function(done) {
var queue = new StreamQueue();
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['wa','dup']);
});
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['pl','op']);
});
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['ki','koo','lol']);
});
assert.equal(queue.length, 3);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.done();
});
it('should pause streams in flowing mode', function(done) {
var queue = new StreamQueue({
pauseFlowingStream: true,
resumeFlowingStream: true
});
queue.queue(function() {
return readableStream(['wa','dup']);
});
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['pl','op']);
});
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['ki','koo','lol']);
});
assert.equal(queue.length, 3);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.done();
});
it('should work with POO API and options', function(done) {
var queue = new StreamQueue({
pauseFlowingStream: true,
resumeFlowingStream: true
});
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['wa','dup']);
});
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['pl','op'])
});
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['ki','koo','lol'])
});
assert.equal(queue.length, 3);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.done();
});
it('should work with POO API and a late done call', function(done) {
var queue = new StreamQueue();
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['wa','dup']);
});
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['pl','op'])
});
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['ki','koo','lol'])
});
assert.equal(queue.length, 3);
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
setTimeout(function() {
queue.done();
}, 100);
});
it('should reemit errors', function(done) {
var gotError = false;
var queue = new StreamQueue();
queue.queue(erroredStream('Aouch!'));
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['wa','dup']);
});
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['pl','op'])
});
queue.queue(function() {
return writeToStream(new Stream.PassThrough(), ['ki','koo','lol'])
});
assert.equal(queue.length, 4);
queue.on('error', function(err) {
gotError = true;
});
queue.pipe(es.wait(function(err, data) {
assert(gotError);
assert.equal(err, null);
assert.equal(data, 'wadupplopkikoolol');
done();
}));
queue.done();
});
});
});
describe('in object mode', function() {
var objs = [];
it('should work', function(done) {
var queue = new StreamQueue({objectMode: true});
queue.queue(writeToStream(new Stream.PassThrough({objectMode: true}), [{s:'wa'},{s:'dup'}]));
queue.queue(writeToStream(new Stream.PassThrough({objectMode: true}), [{s:'pl'},{s:'op'}]));
queue.queue(writeToStream(new Stream.PassThrough({objectMode: true}), [{s:'ki'},{s:'koo'},{s:'lol'}]));
queue.on('data', objs.push.bind(objs));
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.deepEqual(objs, [{s:'wa'},{s:'dup'},{s:'pl'},{s:'op'},{s:'ki'},{s:'koo'},{s:'lol'}]);
done();
}));
queue.done();
});
});
});
});
describe('streamqueue with old 0.8 streams', function() {
it('should work', function(done) {
var queue = new StreamQueue();
queue.queue(writeToStreamOld(new PlatformStream(), ['wa','dup'], 50));
queue.queue(writeToStreamOld(new PlatformStream(), ['pl','op']));
queue.queue(writeToStreamOld(new PlatformStream(), ['ki','koo','lol']));
queue.pipe(es.wait(function(err, data) {
assert.equal(err, null);
assert.deepEqual(data, 'wadupplopkikoolol');
done();
}));
queue.done();
});
});
// Helpers
// Helpers
function writeToStreamSync(stream, chunks) {
if(!chunks.length) {
stream.end();
} else {
stream.write(chunks.shift());
writeToStreamSync(stream, chunks);
}
return stream;
}
function writeToStream(stream, chunks) {
if(!chunks.length) {
stream.end();
} else {
setTimeout(function() {
stream.write(chunks.shift());
writeToStream(stream, chunks);
});
}
return stream;
}
function writeToStreamOld(stream, chunks, timeout) {
stream.readable = true;
if(!chunks.length) {
stream.emit('end');
} else {
setTimeout(function() {
stream.emit('data', chunks.shift());
writeToStreamOld(stream, chunks, timeout);
}, timeout || 0);
}
return stream;
}
function readableStream(chunks) {
var stream = new Stream.Readable();
stream._read = function() {
if(chunks.length) {
setTimeout(function() {
stream.push(chunks.shift());
if(!chunks.length) {
stream.push(null);
}
});
}
}
stream.resume();
return stream;
}
function erroredStream(msg) {
var erroredStream = new Stream.PassThrough();
setTimeout(function() {
erroredStream.emit('error', new Error(msg));
erroredStream.end();
});
return erroredStream;
}
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M5.78 2.95C7.24 2.16 9.48 2 12 2c4.42 0 8 .5 8 4v10c0 .35-.08.67-.19.98L13.83 11H18V6H8.83L5.78 2.95zm14 19.66L18.17 21H16v-2H8v2H5v-2.78c-.61-.55-1-1.34-1-2.22V6.83L1.39 4.22 2.8 2.81l18.38 18.38-1.4 1.42zM9 15.5c0-.83-.67-1.5-1.5-1.5S6 14.67 6 15.5 6.67 17 7.5 17 9 16.33 9 15.5zM8.17 11 6 8.83V11h2.17z"
}), 'NoTransferSharp');
exports.default = _default;
|
version https://git-lfs.github.com/spec/v1
oid sha256:f3bd05882d550e93186316a597c70ee687ecd2af0b3a555e9630af0e580f63cd
size 15702
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014 Marco Grätsch
*
* 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.
*
*
* @param {jQuery} $
*/
(function($) {
'use strict';
var filterMode = 'unlink',
elementClass = 'lsr-link',
parentClass = 'lsr-link-parent',
warningClass = 'lsr-warning',
messageClass = 'lsr-message',
domainlist = (JSON.parse(localStorage.getItem('domainlist')) || []),
lang = {},
debug = false,
/**
* Predefined filters
*/
filters = {
unlink: function($el, $parent, url, domain) {
if ($parent && $parent.length && !$parent.hasClass(parentClass)) {
$parent.addClass(parentClass);
}
var $span = $('<span title="' + replaceVars(lang.link_removed, domain, url) + '"></span>').text($el.text());
$span.addClass(elementClass);
$el.replaceWith($span);
},
remove: function($el, $parent, url, domain) {
var $message = '';
if (lang.content_removed) {
$message = $('<div></div>');
$message.addClass(messageClass).text(replaceVars(lang.content_removed, domain, url));
}
if ($parent && $parent.length) {
$parent.replaceWith($message);
return;
}
$el.replaceWith($message);
},
marker: function($el, $parent, url, domain) {
if ($parent && $parent.length && !$parent.hasClass(parentClass)) {
$parent.addClass(parentClass);
}
if (!$el.hasClass(elementClass)) {
$el.addClass(elementClass);
}
},
confirm: function($el, $parent, url, domain) {
$el.off('click').on('click', function(ev) {
ev.preventDefault();
if (confirm(replaceVars(lang.confirm, domain, url))) {
window.location = url;
}
});
},
warning: function($el, $parent, url, domain) {
var $warning = $('<div></div>');
$parent = $parent || $el.closest('div');
$warning.addClass(warningClass).text(replaceVars(lang.warning, domain, url));
$parent.not('has-' + warningClass)
.addClass('has-' + warningClass)
.prepend($warning);
}
},
/**
* Update List Handler
*
* @param {String} url
* @param {Function} cb
*/
updateList = function(url, cb) {
$.get(url, {}, function(data, status, jqXHR) {
var ts = Math.round(Date.now()/1000);
localStorage.setItem('domainlist', JSON.stringify(data));
localStorage.setItem('last-update', ts);
domainlist = data;
cb(data, ts, url, status);
}, 'json');
},
/**
* Check if an update should be performed
*
* @param {String} interval
* @return {Boolean}
*/
checkUpdates = function(interval) {
var lastUpdate = localStorage.getItem('last-update') || null,
intervalTime = 0,
now = Math.round(Date.now()/1000);
if (interval === 'off') {
if (!localStorage.getItem('domainlist')) {
return true;
}
return false;
}
if (!localStorage.getItem('domainlist')) {
return true;
}
if (!lastUpdate) {
return true;
}
switch (interval) {
case 'hourly':
intervalTime = (60*60);
break;
case 'daily':
intervalTime = (60*60*24);
break;
case 'weekly':
intervalTime = (60*60*24*7);
break;
case 'monthly':
intervalTime = (60*60*24*30);
break;
}
if (now >= lastUpdate + intervalTime) {
return true;
}
return false;
},
/**
* Replace variables in strings
*
* @param {String} text
* @param {String} domain
* @param {String} url
* @return {String}
*/
replaceVars = function(text, domain, url) {
return text.replace('##domain##', domain).replace('##url##', url);
},
/**
* Check if the URL is a link to a specific domain
*
* @param {String} url
* @param {String} domain
* @return {Boolean}
*/
match = function(url, domain) {
if (url.indexOf('.' + domain) !== -1 || url.indexOf('//' + domain) !== -1) {
if (debug) {
console.log('Match found: Domain: ' + domain + ', URL: ' + url);
}
return true;
}
return false;
},
/**
* Filter an element
*
* @param {jQuery} $el
* @param {jQuery} $parent
* @param {String} domain
* @param {Function} cb
*/
filter = function($el, $parent, domain, cb) {
var url = $el.attr('href');
if (url) {
if (match(url, domain)) {
cb($el, $parent, url, domain);
}
return;
}
$el.find('a,link').each(function() {
filter($(this), $el, domain, cb);
});
},
/**
* Default onUpdateList-Handler
*
* @param {Array} data
* @param {Number} ts
* @param {String} url
* @param {String} status
*/
onUpdateList = function(data, ts, url, status) {
if (debug) {
console.log('Blacklist updated at ' + (new Date(ts*1000)).toLocaleString() + ' from ' + url);
console.log('List contains actually ' + data.length + ' domains');
}
},
/**
* Default onFilterMatch-Handler
*
* @param {jQuery} $el
* @param {jQuery} $parent
* @param {String} url
* @param {String} domain
*/
onFilterMatch = function($el, $parent, url, domain) {
if (!filters[filterMode]) {
if (debug) {
console.log('Invalid filter-mode: ' + filterMode + ', using default (unlink)');
}
filterMode = 'unlink';
}
filters[filterMode]($el, $parent, url, domain);
},
/**
* Default Options
*/
defaultOptions = {
domainlist: 'https://cdn.rawgit.com/magdev/leistungsschutzgelderpresser/master/domains.json',
updateInterval: 'weekly',
forceUpdate: false,
debug: false,
onFilterMatch: onFilterMatch,
onUpdateList: onUpdateList,
filterMode: 'unlink',
parentSelector: null,
elementClass: 'lsr-link',
parentClass: 'lsr-link-parent',
warningClass: 'lsr-warning',
messageClass: 'lsr-message',
lang: {
link_removed: 'Link removed',
content_removed: 'Content removed',
warning: 'WARNING! Contains LSR-related Links',
confirm: 'The link goes to ##domain##! Are you sure you want to follow this link?'
}
};
/**
* jQuery LSR-Filter
*
* @param {Object} options
* @return {jQuery}
*/
$.fn.lsr = function(options) {
var opts = $.extend(defaultOptions, options);
filterMode = opts.filterMode;
elementClass = opts.elementClass;
parentClass = opts.parentClass;
warningClass = opts.warningClass;
messageClass = opts.messageClass;
lang = opts.lang;
debug = opts.debug;
if (checkUpdates(opts.updateInterval) || opts.forceUpdate) {
updateList(opts.domainlist, opts.onUpdateList);
}
return this.each(function() {
var $this = $(this),
$parent = $(this).closest(opts.parentSelector);
domainlist.forEach(function(domain) {
filter($this, $parent, domain, opts.onFilterMatch);
});
});
};
// Apply filter to elements using data-attributes
$('[data-filter="lsr"]').each(function() {
$(this).lsr(this.dataset);
});
})(jQuery);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.