From 423c3063a81bd4525e905fabbfe63a80b60f1007 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Michaud?= Date: Tue, 21 Feb 2023 22:44:59 +0100 Subject: [PATCH] Fix or hide unrisked Standard/ESLint mistakes --- .eslintrc.js | 15 - apxtrib.js | 120 - doc/GettingStarted.md | 6 + middlewares/ASUPhaveAccessrighttoanobject.js | 95 - middlewares/checkHeaders.js | 88 - middlewares/hasAccessrighton.js | 42 - middlewares/isAuthenticated.js | 113 - models/Contracts.js | 121 - models/Messages.js | 400 - models/Nationchains.js | 105 - models/Outputs.js | 557 - models/OutputsDev.js | 492 - models/Pagans.js | 774 -- models/Referentials.js | 416 - models/Referentialssave.js | 220 - models/Tags.js | 229 - models/Tribes.js | 352 - models/UploadFiles.js | 152 - .../socialworld/contracts/checkdata.js | 185 - .../socialworld/contracts/toolsbox.js | 604 - package.json | 9 +- routes/messages.js | 63 - routes/nationchains.js | 37 - routes/odmdb.js | 19 - routes/outputs.js | 65 - routes/pagans.js | 211 - routes/referentials.js | 94 - routes/tags.js | 29 - routes/tribes.js | 374 - routes/uploadFiles.js | 49 - .../apixpress/www/app/webapp/js/auth.js | 216 - .../apixpress/www/app/webapp/js/axios.min.js | 9 - .../apixpress/www/app/webapp/js/checkdata.js | 184 - .../www/app/webapp/js/feather.min.js | 13 - .../apixpress/www/app/webapp/js/main.js | 150 - .../www/app/webapp/js/mustache.min.js | 1 - .../www/app/webapp/js/notification.js | 28 - .../www/app/webapp/js/simplebar.min.js | 10 - .../apixpress/www/app/webapp/js/state.js | 261 - .../adminapixpress/adminapixpress.js | 34 - .../static/components/appmesa/ASUPappmesa.js | 145 - .../static/components/appmesa/message.js | 28 - .../static/components/appmesa/referential.js | 271 - .../static/components/appmesa/reporting.js | 12 - .../static/components/appmesa/search.js | 68 - .../static/components/appmesa/userManager.js | 74 - .../static/components/flipbox/flipbox.js | 20 - .../components/notification/notification.js | 28 - .../components/userprofile/userprofile.js | 66 - .../apixpress/www/cdn/public/js/article.js | 24 - .../apixpress/www/cdn/public/js/auth.js | 212 - .../apixpress/www/cdn/public/js/axios.min.js | 9 - .../apixpress/www/cdn/public/js/checkdata.js | 185 - .../apixpress/www/cdn/public/js/editorsave.js | 104 - .../apixpress/www/cdn/public/js/formsave.js | 305 - .../www/cdn/public/js/jquery-3.6.0.js | 10881 ---------------- .../apixpress/www/cdn/public/js/main.js | 53 - .../www/cdn/public/js/mustache.min.js | 1 - .../apixpress/www/cdn/public/js/plugins.js | 24 - .../apixpress/www/cdn/public/js/questio.js | 50 - .../www/cdn/public/js/tagASUPVOIRstate.js.js | 164 - .../apixpress/www/cdn/public/js/tagold.js | 67 - src/apxtrib.js | 123 + src/core/logger.js | 12 +- .../ASUPhaveAccessrighttoanobject.js | 96 + src/middlewares/checkHeaders.js | 92 + src/middlewares/hasAccessrighton.js | 44 + src/middlewares/isAuthenticated.js | 116 + src/models/Contracts.js | 122 + src/models/Messages.js | 437 + src/models/Nationchains.js | 106 + {models => src/models}/Odmdb.js | 14 +- src/models/Outputs.js | 556 + src/models/OutputsDev.js | 494 + src/models/Pagans.js | 779 ++ src/models/Referentials.js | 455 + src/models/Referentialssave.js | 235 + {models => src/models}/Setup.js | 22 +- src/models/Tags.js | 235 + src/models/Tribes.js | 357 + src/models/UploadFiles.js | 154 + .../nationchains}/antsnation.html | 0 .../nationchains}/apixtribe.html | 0 .../nationchains}/enmaintenance.html | 0 .../socialworld/contracts/checkdata.js | 184 + .../socialworld/contracts/toolsbox.js | 604 + .../socialworld/metaobject/nation.json | 0 .../socialworld/metaobject/pagans.json | 0 .../socialworld/metaobject/towns.json | 0 .../socialworld/objects/nations/ants.json | 0 .../socialworld/objects/nations/escape.json | 0 .../nations/searchindex/nationslist.json | 0 .../nations/searchindex/townslist.json | 0 .../nations/searchindex/tribeslist.json | 0 .../socialworld/objects/towns/game.json | 0 .../tribes/searchindex/tribeslist.json | 0 .../nationchains}/static/error/404.html | 0 .../nationchains}/static/error/50x.html.html | 0 .../static/fonts/Cantarell-Bold.ttf | Bin .../static/fonts/Cantarell-BoldItalic.ttf | Bin .../static/fonts/Cantarell-Italic.ttf | Bin .../static/fonts/Cantarell-Regular.ttf | Bin .../nationchains}/static/fonts/OFL.txt | 186 +- .../static/fonts/cantarell-bold-demo.html | 6 +- .../static/fonts/cantarell-bold-webfont.woff | Bin .../static/fonts/cantarell-bold-webfont.woff2 | Bin .../fonts/cantarell-bolditalic-demo.html | 6 +- .../fonts/cantarell-bolditalic-webfont.woff | Bin .../fonts/cantarell-bolditalic-webfont.woff2 | Bin .../static/fonts/cantarell-italic-demo.html | 6 +- .../fonts/cantarell-italic-webfont.woff | Bin .../fonts/cantarell-italic-webfont.woff2 | Bin .../static/fonts/cantarell-regular-demo.html | 6 +- .../fonts/cantarell-regular-webfont.woff | Bin .../fonts/cantarell-regular-webfont.woff2 | Bin .../static/fonts/generator_config.txt | 0 .../specimen_files/grid_12-825-55-15.css | 0 .../specimen_files/specimen_stylesheet.css | 2 +- .../nationchains}/static/fonts/stylesheet.css | 0 .../static/img/avataranonymous.png | Bin .../static/img/avataranonymous1.png | Bin .../static/img/avataranonymous2.png | Bin .../img/chartegraphique/codecouleur.png | Bin .../static/img/chartegraphique/favicon.png | Bin .../img/chartegraphique/logo_bgplein.png | Bin .../chartegraphique/logo_bgtransparent.png | Bin .../img/chartegraphique/logocarre_bgplein.png | Bin .../logocarre_vertical_bgplein.png | Bin .../img/chartegraphique/planchelogo.svg | 0 .../nationchains}/static/img/imgtg.png | Bin .../static/img/nations/ants/antsNation.svg | 0 .../static/img/site-en-maintenance.png | Bin .../nationchains}/testnetwork.html | 0 src/routes/messages.js | 65 + src/routes/nationchains.js | 32 + src/routes/odmdb.js | 23 + src/routes/outputs.js | 62 + src/routes/pagans.js | 218 + src/routes/referentials.js | 97 + src/routes/tags.js | 30 + src/routes/tribes.js | 400 + src/routes/uploadFiles.js | 51 + {setup => src/setup}/ASUPconfig.jsold | 6 +- .../setup}/apixtribe.crabdance.com.mustache | 0 {setup => src/setup}/config.mustache | 0 {setup => src/setup}/configsetup.json | 0 .../apixpress/blockchains/blocks/0.json | 0 .../blockchains/nodes/apixpress.ndda.fr | 0 .../data/domain/apixpress/clientconf.mustache | 0 .../dataManagement/data/OrdersAction.json | 0 .../dataManagement/data/OutputsAction.json | 2 +- .../data/UploadFilesAction.json | 0 .../dataManagement/data/UsersAction.json | 0 .../dataManagement/data/gender.json | 0 .../dataManagement/data/missionpos.json | 0 .../dataManagement/data/profile.json | 0 .../dataManagement/data/role.json | 0 .../json/catalogueCompanies.json | 0 .../json/importcsvCompanies.json | 2 +- .../dataManagement/json/menuAdmin.json | 0 .../dataManagement/json/menuUser.json | 0 .../json/referentialsetting.json | 0 .../dataManagement/json/testref.json | 0 .../dataManagement/json/usersetting.json | 0 .../dataManagement/object/action.json | 0 .../dataManagement/object/basic.json | 0 .../dataManagement/object/basicnolang.json | 0 .../dataManagement/object/cards.json | 0 .../dataManagement/object/chgpsw.json | 0 .../dataManagement/object/companies.json | 0 .../dataManagement/object/item.json | 0 .../dataManagement/object/userOperator.json | 0 .../dataManagement/object/users.json | 0 .../dataManagementBackup/object/users.json | 0 .../referentials/fr/object/users.json | 0 .../apixpress/users/searchindex/emails.json | 0 .../apixpress/users/searchindex/logins.json | 0 .../apixpress/users/searchindex/uids.json | 0 .../www/app/webapp/app_index_fr.html | 0 .../www/app/webapp/css/app/styles.css | 0 .../www/app/webapp/css/fullscreen/styles.css | 0 .../www/app/webapp/css/simplebar.min.css | 0 .../www/app/webapp/fullscreen_auth_fr.html | 0 .../apixpress/www/app/webapp/js/auth.js | 215 + .../apixpress/www/app/webapp/js/axios.min.js | 9 + .../apixpress/www/app/webapp/js/bootstrap.js | 4308 +++--- .../apixpress/www/app/webapp/js/checkdata.js | 183 + .../www/app/webapp/js/feather.min.js | 13 + .../apixpress/www/app/webapp/js/main.js | 150 + .../www/app/webapp/js/mustache.min.js | 1 + .../www/app/webapp/js/notification.js | 28 + .../www/app/webapp/js/simplebar.min.js | 10 + .../apixpress/www/app/webapp/js/state.js | 261 + .../apixpress/www/app/webapp/manifest.json | 0 .../apixpress/www/app/webapp/scss/main.scss | 0 .../adminapixpress/adminapixpress.js | 34 + .../adminapixpressactivity.mustache | 0 .../adminapixpressclientId.mustache | 0 .../adminapixpresssysinfo.mustache | 0 .../sidebaradminapixpress_fr.json | 0 .../ASUPPdata_sidebarAdminapixpress_fr.json | 0 .../static/components/appmesa/ASUPappmesa.js | 144 + .../components/appmesa/appcontent.mustache | 0 .../components/appmesa/appmesa.mustache | 0 .../appmesa/appsidebarmenu.mustache | 0 .../components/appmesa/apptopbarmenu.mustache | 0 .../appmesa/apptopbarmessage.mustache | 0 .../appmesa/apptopbarnotification.mustache | 0 .../components/appmesa/data_appmesa_fr.json | 0 .../appmesa/data_sidebarAdminspace_fr.json | 0 .../components/appmesa/data_sidebar_fr.json | 0 .../components/appmesa/data_topbar_fr.json | 0 .../static/components/appmesa/message.js | 27 + .../static/components/appmesa/referential.js | 268 + .../components/appmesa/referential.mustache | 0 .../static/components/appmesa/reporting.js | 11 + .../static/components/appmesa/search.js | 68 + .../webapp/static/components/appmesa/tuto.js | 81 +- .../static/components/appmesa/userManager.js | 74 + .../components/appusers/useractivity.mustache | 0 .../appusers/usersettingaccounttpl.mustache | 0 .../appusers/usersettingdeletetpl.mustache | 0 .../appusers/usersettingpasswordtpl.mustache | 0 .../appusers/usersettingprivacytpl.mustache | 0 .../app/webapp/static/components/flipbox.zip | Bin .../components/flipbox/data_flipbox_fr.json | 0 .../static/components/flipbox/flipbox.js | 20 + .../components/flipbox/flipbox.mustache | 0 .../static/components/flipbox/flipbox.scss | 0 .../components/fullpage/fullpage.mustache | 0 .../notification/data_notiflist_fr.json | 0 .../components/notification/notification.js | 28 + .../notification/notiflist.mustache | 0 .../userprofile/topbaruserLogout_fr.json | 0 .../userprofile/topbaruseractivity_fr.json | 0 .../userprofile/topbaruserprofile_fr.json | 0 .../userprofile/useractivity.mustache | 0 .../components/userprofile/userprofile.js | 66 + .../userprofile/usersettingaccount.mustache | 0 .../userprofile/usersettingdeletetpl.mustache | 0 .../usersettingpasswordtpl.mustache | 0 .../usersettingprivacytpl.mustache | 0 .../verticaltab/data_verticaltab_fr.json | 0 .../verticaltab/verticaltab.mustache | 0 .../app/webapp/static/data/appmesa_fr.json | 0 .../webapp/static/data/appsimplehead_fr.json | 0 .../www/app/webapp/static/data/auth_fr.json | 0 .../www/app/webapp/static/data/fullpage.json | 0 .../static/data/fullscreensimplehead_fr.json | 0 .../app/webapp/static/data/notiflist_fr.json | 0 .../static/data/sidebarAdminapixpress_fr.json | 0 .../static/data/sidebarAdminspace_fr.json | 0 .../app/webapp/static/data/sidebar_fr.json | 0 .../static/data/topbarUserprofile_fr.json | 0 .../www/app/webapp/static/data/topbar_fr.json | 0 .../app/webapp/static/fonts/icofont/demo.html | 0 .../static/fonts/icofont/fonts/icofont.eot | Bin .../static/fonts/icofont/fonts/icofont.svg | 0 .../static/fonts/icofont/fonts/icofont.ttf | Bin .../static/fonts/icofont/fonts/icofont.woff | Bin .../static/fonts/icofont/fonts/icofont.woff2 | Bin .../webapp/static/fonts/icofont/icofont.css | 2 +- .../static/fonts/icofont/icofont.min.css | 0 .../app/webapp/static/img/avataranonymous.png | Bin .../webapp/static/img/avataranonymous1.png | Bin .../webapp/static/img/avataranonymous2.png | Bin .../webapp/static/img/icons/iconX74x74.png | Bin .../app/webapp/static/img/logo/apixpress.png | Bin .../www/app/webapp/static/img/logo/ndda.png | Bin .../www/app/webapp/static/img/logo_footer.svg | 0 .../www/app/webapp/static/img/logo_menu.svg | 0 .../static/lastchange/app_index_fr.json | 0 .../static/lastchange/fullscreen_auth_fr.json | 0 .../www/app/www.apixpress.org/apixpress.png | Bin .../www/cdn/chartegraphique/codecouleur.png | Bin .../www/cdn/chartegraphique/favicon.png | Bin .../www/cdn/chartegraphique/logo_bgplein.png | Bin .../chartegraphique/logo_bgtransparent.png | Bin .../cdn/chartegraphique/logocarre_bgplein.png | Bin .../www/cdn/chartegraphique/planchelogo.svg | 0 .../apixpress/www/cdn/doc/.apiXpress.png | Bin .../domain/apixpress/www/cdn/doc/apiXpress.mm | 0 .../www/cdn/fonts/Cantarell-Bold.ttf | Bin .../www/cdn/fonts/Cantarell-BoldItalic.ttf | Bin .../www/cdn/fonts/Cantarell-Italic.ttf | Bin .../www/cdn/fonts/Cantarell-Regular.ttf | Bin .../domain/apixpress/www/cdn/fonts/OFL.txt | 186 +- .../www/cdn/fonts/cantarell-bold-demo.html | 6 +- .../www/cdn/fonts/cantarell-bold-webfont.woff | Bin .../cdn/fonts/cantarell-bold-webfont.woff2 | Bin .../cdn}/fonts/cantarell-bolditalic-demo.html | 6 +- .../fonts/cantarell-bolditalic-webfont.woff | Bin .../fonts/cantarell-bolditalic-webfont.woff2 | Bin .../www/cdn/fonts/cantarell-italic-demo.html | 6 +- .../cdn/fonts/cantarell-italic-webfont.woff | Bin .../cdn/fonts/cantarell-italic-webfont.woff2 | Bin .../www/cdn/fonts/cantarell-regular-demo.html | 6 +- .../cdn/fonts/cantarell-regular-webfont.woff | Bin .../cdn/fonts/cantarell-regular-webfont.woff2 | Bin .../www/cdn/fonts/generator_config.txt | 0 .../specimen_files/grid_12-825-55-15.css | 0 .../specimen_files/specimen_stylesheet.css | 2 +- .../apixpress/www/cdn/fonts/stylesheet.css | 0 .../apixpress/www/cdn/img/avataranonymous.png | Bin .../www/cdn/img/avataranonymous1.png | Bin .../www/cdn/img/avataranonymous2.png | Bin .../www/cdn/img/icons/iconX74x74.png | Bin .../apixpress/www/cdn/img/logo/apixpress.png | Bin .../apixpress/www/cdn/img/logo/ndda.png | Bin .../apixpress/www/cdn/img/logo_footer.svg | 0 .../apixpress/www/cdn/img/logo_menu.svg | 0 ...BxJM6AnOfFcwl_vSXkN9Fu2YH4RBIMRJakt-OhuA0k | 0 ...-uQGmAgy6bWggASoIYoo2_O9BO-Pu6vrQpSIHJY7Ow | 0 ...dBJU5yetxUAhmxmzyKCdjhAkGAaL_oKY4ME_mxBN6I | 0 ...iSMi5lKG4u4wTljv3Ryr4rEKwNQyK--ExV3hZT5jgs | 0 .../.well-known/acme-challenge/test.html | 0 ...Ry8dNfRqdZ1kBLpdO6URuCQyF7If1_MFxLoWXzuOX0 | 0 .../www/cdn/public/basketunknown.png | Bin .../domain/apixpress/www/cdn/public/imgtg.png | Bin .../apixpress/www/cdn/public/index.html | 0 .../apixpress/www/cdn/public/js/article.js | 22 + .../apixpress/www/cdn/public/js/auth.js | 217 + .../apixpress/www/cdn/public/js/axios.min.js | 9 + .../apixpress/www/cdn/public/js/checkdata.js | 184 + .../apixpress/www/cdn/public/js/editor.js | 238 +- .../apixpress/www/cdn/public/js/editorsave.js | 103 + .../apixpress/www/cdn/public/js/formsave.js | 305 + .../apixpress/www/cdn/public/js/formvieux.js | 80 +- .../www/cdn/public/js/jquery-3.6.0.js | 10438 +++++++++++++++ .../apixpress/www/cdn/public/js/main.js | 51 + .../www/cdn/public/js/mustache.min.js | 1 + .../apixpress/www/cdn/public/js/plugins.js | 24 + .../apixpress/www/cdn/public/js/questio.js | 56 + .../www/cdn/public/js/tagASUPVOIRstate.js.js | 164 + .../apixpress/www/cdn/public/js/tagold.js | 67 + .../cdn/public/template/formgeneric.mustache | 0 .../cdn/public/template/questInput.mustache | 0 .../apixpress/www/cdn/public/testnetwork.html | 0 .../www/cdn/suiviprojetapiXpress.svg | 10 +- .../setup}/nginx/modelwebsite.conf.mustache | 0 .../setup}/nginx/nginx.conf.mustache | 0 341 files changed, 21994 insertions(+), 22358 deletions(-) delete mode 100755 .eslintrc.js delete mode 100755 apxtrib.js create mode 100644 doc/GettingStarted.md delete mode 100755 middlewares/ASUPhaveAccessrighttoanobject.js delete mode 100755 middlewares/checkHeaders.js delete mode 100755 middlewares/hasAccessrighton.js delete mode 100755 middlewares/isAuthenticated.js delete mode 100755 models/Contracts.js delete mode 100755 models/Messages.js delete mode 100755 models/Nationchains.js delete mode 100755 models/Outputs.js delete mode 100755 models/OutputsDev.js delete mode 100755 models/Pagans.js delete mode 100755 models/Referentials.js delete mode 100755 models/Referentialssave.js delete mode 100755 models/Tags.js delete mode 100755 models/Tribes.js delete mode 100755 models/UploadFiles.js delete mode 100755 nationchains/socialworld/contracts/checkdata.js delete mode 100755 nationchains/socialworld/contracts/toolsbox.js delete mode 100755 routes/messages.js delete mode 100755 routes/nationchains.js delete mode 100644 routes/odmdb.js delete mode 100755 routes/outputs.js delete mode 100755 routes/pagans.js delete mode 100755 routes/referentials.js delete mode 100755 routes/tags.js delete mode 100755 routes/tribes.js delete mode 100755 routes/uploadFiles.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/js/auth.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/js/axios.min.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/js/checkdata.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/js/feather.min.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/js/main.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/js/mustache.min.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/js/notification.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/js/simplebar.min.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/js/state.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/static/components/adminapixpress/adminapixpress.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/static/components/appmesa/ASUPappmesa.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/static/components/appmesa/message.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/static/components/appmesa/referential.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/static/components/appmesa/reporting.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/static/components/appmesa/search.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/static/components/appmesa/userManager.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/static/components/flipbox/flipbox.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/static/components/notification/notification.js delete mode 100755 setup/data/domain/apixpress/www/app/webapp/static/components/userprofile/userprofile.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/article.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/auth.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/axios.min.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/checkdata.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/editorsave.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/formsave.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/jquery-3.6.0.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/main.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/mustache.min.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/plugins.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/questio.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/tagASUPVOIRstate.js.js delete mode 100755 setup/data/domain/apixpress/www/cdn/public/js/tagold.js create mode 100755 src/apxtrib.js create mode 100755 src/middlewares/ASUPhaveAccessrighttoanobject.js create mode 100755 src/middlewares/checkHeaders.js create mode 100755 src/middlewares/hasAccessrighton.js create mode 100755 src/middlewares/isAuthenticated.js create mode 100755 src/models/Contracts.js create mode 100755 src/models/Messages.js create mode 100755 src/models/Nationchains.js rename {models => src/models}/Odmdb.js (56%) create mode 100755 src/models/Outputs.js create mode 100755 src/models/OutputsDev.js create mode 100755 src/models/Pagans.js create mode 100755 src/models/Referentials.js create mode 100755 src/models/Referentialssave.js rename {models => src/models}/Setup.js (92%) create mode 100755 src/models/Tags.js create mode 100755 src/models/Tribes.js create mode 100755 src/models/UploadFiles.js rename {nationchains => src/nationchains}/antsnation.html (100%) rename {nationchains => src/nationchains}/apixtribe.html (100%) rename {nationchains => src/nationchains}/enmaintenance.html (100%) create mode 100755 src/nationchains/socialworld/contracts/checkdata.js create mode 100755 src/nationchains/socialworld/contracts/toolsbox.js rename {nationchains => src/nationchains}/socialworld/metaobject/nation.json (100%) rename {nationchains => src/nationchains}/socialworld/metaobject/pagans.json (100%) rename {nationchains => src/nationchains}/socialworld/metaobject/towns.json (100%) rename {nationchains => src/nationchains}/socialworld/objects/nations/ants.json (100%) rename {nationchains => src/nationchains}/socialworld/objects/nations/escape.json (100%) rename {nationchains => src/nationchains}/socialworld/objects/nations/searchindex/nationslist.json (100%) rename {nationchains => src/nationchains}/socialworld/objects/nations/searchindex/townslist.json (100%) rename {nationchains => src/nationchains}/socialworld/objects/nations/searchindex/tribeslist.json (100%) rename {nationchains => src/nationchains}/socialworld/objects/towns/game.json (100%) rename {nationchains => src/nationchains}/socialworld/objects/tribes/searchindex/tribeslist.json (100%) rename {nationchains => src/nationchains}/static/error/404.html (100%) rename {nationchains => src/nationchains}/static/error/50x.html.html (100%) rename {nationchains => src/nationchains}/static/fonts/Cantarell-Bold.ttf (100%) rename {nationchains => src/nationchains}/static/fonts/Cantarell-BoldItalic.ttf (100%) rename {nationchains => src/nationchains}/static/fonts/Cantarell-Italic.ttf (100%) rename {nationchains => src/nationchains}/static/fonts/Cantarell-Regular.ttf (100%) rename {nationchains => src/nationchains}/static/fonts/OFL.txt (97%) rename {nationchains => src/nationchains}/static/fonts/cantarell-bold-demo.html (99%) rename {nationchains => src/nationchains}/static/fonts/cantarell-bold-webfont.woff (100%) rename {nationchains => src/nationchains}/static/fonts/cantarell-bold-webfont.woff2 (100%) rename {setup/data/domain/apixpress/www/cdn => src/nationchains/static}/fonts/cantarell-bolditalic-demo.html (99%) rename {nationchains => src/nationchains}/static/fonts/cantarell-bolditalic-webfont.woff (100%) rename {nationchains => src/nationchains}/static/fonts/cantarell-bolditalic-webfont.woff2 (100%) rename {nationchains => src/nationchains}/static/fonts/cantarell-italic-demo.html (99%) rename {nationchains => src/nationchains}/static/fonts/cantarell-italic-webfont.woff (100%) rename {nationchains => src/nationchains}/static/fonts/cantarell-italic-webfont.woff2 (100%) rename {nationchains => src/nationchains}/static/fonts/cantarell-regular-demo.html (99%) rename {nationchains => src/nationchains}/static/fonts/cantarell-regular-webfont.woff (100%) rename {nationchains => src/nationchains}/static/fonts/cantarell-regular-webfont.woff2 (100%) rename {nationchains => src/nationchains}/static/fonts/generator_config.txt (100%) rename {nationchains => src/nationchains}/static/fonts/specimen_files/grid_12-825-55-15.css (100%) rename {setup/data/domain/apixpress/www/cdn => src/nationchains/static}/fonts/specimen_files/specimen_stylesheet.css (99%) rename {nationchains => src/nationchains}/static/fonts/stylesheet.css (100%) rename {nationchains => src/nationchains}/static/img/avataranonymous.png (100%) rename {nationchains => src/nationchains}/static/img/avataranonymous1.png (100%) rename {nationchains => src/nationchains}/static/img/avataranonymous2.png (100%) rename {nationchains => src/nationchains}/static/img/chartegraphique/codecouleur.png (100%) rename {nationchains => src/nationchains}/static/img/chartegraphique/favicon.png (100%) rename {nationchains => src/nationchains}/static/img/chartegraphique/logo_bgplein.png (100%) rename {nationchains => src/nationchains}/static/img/chartegraphique/logo_bgtransparent.png (100%) rename {nationchains => src/nationchains}/static/img/chartegraphique/logocarre_bgplein.png (100%) rename {nationchains => src/nationchains}/static/img/chartegraphique/logocarre_vertical_bgplein.png (100%) rename {nationchains => src/nationchains}/static/img/chartegraphique/planchelogo.svg (100%) rename {nationchains => src/nationchains}/static/img/imgtg.png (100%) rename {nationchains => src/nationchains}/static/img/nations/ants/antsNation.svg (100%) rename {nationchains => src/nationchains}/static/img/site-en-maintenance.png (100%) rename {nationchains => src/nationchains}/testnetwork.html (100%) create mode 100755 src/routes/messages.js create mode 100755 src/routes/nationchains.js create mode 100644 src/routes/odmdb.js create mode 100755 src/routes/outputs.js create mode 100755 src/routes/pagans.js create mode 100755 src/routes/referentials.js create mode 100755 src/routes/tags.js create mode 100755 src/routes/tribes.js create mode 100755 src/routes/uploadFiles.js rename {setup => src/setup}/ASUPconfig.jsold (96%) rename {setup => src/setup}/apixtribe.crabdance.com.mustache (100%) rename {setup => src/setup}/config.mustache (100%) rename {setup => src/setup}/configsetup.json (100%) rename {setup => src/setup}/data/domain/apixpress/blockchains/blocks/0.json (100%) rename {setup => src/setup}/data/domain/apixpress/blockchains/nodes/apixpress.ndda.fr (100%) rename {setup => src/setup}/data/domain/apixpress/clientconf.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/data/OrdersAction.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/data/OutputsAction.json (99%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/data/UploadFilesAction.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/data/UsersAction.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/data/gender.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/data/missionpos.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/data/profile.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/data/role.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/json/catalogueCompanies.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/json/importcsvCompanies.json (81%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/json/menuAdmin.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/json/menuUser.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/json/referentialsetting.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/json/testref.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/json/usersetting.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/object/action.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/object/basic.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/object/basicnolang.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/object/cards.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/object/chgpsw.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/object/companies.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/object/item.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/object/userOperator.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagement/object/users.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/dataManagementBackup/object/users.json (100%) rename {setup => src/setup}/data/domain/apixpress/referentials/fr/object/users.json (100%) rename {setup => src/setup}/data/domain/apixpress/users/searchindex/emails.json (100%) rename {setup => src/setup}/data/domain/apixpress/users/searchindex/logins.json (100%) rename {setup => src/setup}/data/domain/apixpress/users/searchindex/uids.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/app_index_fr.html (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/css/app/styles.css (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/css/fullscreen/styles.css (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/css/simplebar.min.css (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/fullscreen_auth_fr.html (100%) create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/js/auth.js create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/js/axios.min.js rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/js/bootstrap.js (54%) create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/js/checkdata.js create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/js/feather.min.js create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/js/main.js create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/js/mustache.min.js create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/js/notification.js create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/js/simplebar.min.js create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/js/state.js rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/manifest.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/scss/main.scss (100%) create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/static/components/adminapixpress/adminapixpress.js rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/adminapixpress/adminapixpressactivity.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/adminapixpress/adminapixpressclientId.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/adminapixpress/adminapixpresssysinfo.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/adminapixpress/sidebaradminapixpress_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/ASUPPdata_sidebarAdminapixpress_fr.json (100%) create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/static/components/appmesa/ASUPappmesa.js rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/appcontent.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/appmesa.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/appsidebarmenu.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/apptopbarmenu.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/apptopbarmessage.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/apptopbarnotification.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/data_appmesa_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/data_sidebarAdminspace_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/data_sidebar_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/data_topbar_fr.json (100%) create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/static/components/appmesa/message.js create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/static/components/appmesa/referential.js rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/referential.mustache (100%) create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/static/components/appmesa/reporting.js create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/static/components/appmesa/search.js rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appmesa/tuto.js (52%) create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/static/components/appmesa/userManager.js rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appusers/useractivity.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appusers/usersettingaccounttpl.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appusers/usersettingdeletetpl.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appusers/usersettingpasswordtpl.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/appusers/usersettingprivacytpl.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/flipbox.zip (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/flipbox/data_flipbox_fr.json (100%) create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/static/components/flipbox/flipbox.js rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/flipbox/flipbox.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/flipbox/flipbox.scss (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/fullpage/fullpage.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/notification/data_notiflist_fr.json (100%) create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/static/components/notification/notification.js rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/notification/notiflist.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/userprofile/topbaruserLogout_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/userprofile/topbaruseractivity_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/userprofile/topbaruserprofile_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/userprofile/useractivity.mustache (100%) create mode 100755 src/setup/data/domain/apixpress/www/app/webapp/static/components/userprofile/userprofile.js rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/userprofile/usersettingaccount.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/userprofile/usersettingdeletetpl.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/userprofile/usersettingpasswordtpl.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/userprofile/usersettingprivacytpl.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/verticaltab/data_verticaltab_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/components/verticaltab/verticaltab.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/data/appmesa_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/data/appsimplehead_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/data/auth_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/data/fullpage.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/data/fullscreensimplehead_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/data/notiflist_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/data/sidebarAdminapixpress_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/data/sidebarAdminspace_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/data/sidebar_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/data/topbarUserprofile_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/data/topbar_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/fonts/icofont/demo.html (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/fonts/icofont/fonts/icofont.eot (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/fonts/icofont/fonts/icofont.svg (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/fonts/icofont/fonts/icofont.ttf (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/fonts/icofont/fonts/icofont.woff (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/fonts/icofont/fonts/icofont.woff2 (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/fonts/icofont/icofont.css (99%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/fonts/icofont/icofont.min.css (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/img/avataranonymous.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/img/avataranonymous1.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/img/avataranonymous2.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/img/icons/iconX74x74.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/img/logo/apixpress.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/img/logo/ndda.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/img/logo_footer.svg (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/img/logo_menu.svg (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/lastchange/app_index_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/webapp/static/lastchange/fullscreen_auth_fr.json (100%) rename {setup => src/setup}/data/domain/apixpress/www/app/www.apixpress.org/apixpress.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/chartegraphique/codecouleur.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/chartegraphique/favicon.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/chartegraphique/logo_bgplein.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/chartegraphique/logo_bgtransparent.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/chartegraphique/logocarre_bgplein.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/chartegraphique/planchelogo.svg (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/doc/.apiXpress.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/doc/apiXpress.mm (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/Cantarell-Bold.ttf (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/Cantarell-BoldItalic.ttf (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/Cantarell-Italic.ttf (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/Cantarell-Regular.ttf (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/OFL.txt (97%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/cantarell-bold-demo.html (99%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/cantarell-bold-webfont.woff (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/cantarell-bold-webfont.woff2 (100%) rename {nationchains/static => src/setup/data/domain/apixpress/www/cdn}/fonts/cantarell-bolditalic-demo.html (99%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/cantarell-bolditalic-webfont.woff (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/cantarell-bolditalic-webfont.woff2 (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/cantarell-italic-demo.html (99%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/cantarell-italic-webfont.woff (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/cantarell-italic-webfont.woff2 (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/cantarell-regular-demo.html (99%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/cantarell-regular-webfont.woff (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/cantarell-regular-webfont.woff2 (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/generator_config.txt (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/specimen_files/grid_12-825-55-15.css (100%) rename {nationchains/static => src/setup/data/domain/apixpress/www/cdn}/fonts/specimen_files/specimen_stylesheet.css (99%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/fonts/stylesheet.css (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/img/avataranonymous.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/img/avataranonymous1.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/img/avataranonymous2.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/img/icons/iconX74x74.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/img/logo/apixpress.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/img/logo/ndda.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/img/logo_footer.svg (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/img/logo_menu.svg (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/.well-known/acme-challenge/1BxJM6AnOfFcwl_vSXkN9Fu2YH4RBIMRJakt-OhuA0k (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/.well-known/acme-challenge/I-uQGmAgy6bWggASoIYoo2_O9BO-Pu6vrQpSIHJY7Ow (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/.well-known/acme-challenge/JdBJU5yetxUAhmxmzyKCdjhAkGAaL_oKY4ME_mxBN6I (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/.well-known/acme-challenge/SiSMi5lKG4u4wTljv3Ryr4rEKwNQyK--ExV3hZT5jgs (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/.well-known/acme-challenge/test.html (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/.well-known/acme-challenge/vRy8dNfRqdZ1kBLpdO6URuCQyF7If1_MFxLoWXzuOX0 (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/basketunknown.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/imgtg.png (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/index.html (100%) create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/article.js create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/auth.js create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/axios.min.js create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/checkdata.js rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/js/editor.js (61%) create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/editorsave.js create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/formsave.js rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/js/formvieux.js (84%) create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/jquery-3.6.0.js create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/main.js create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/mustache.min.js create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/plugins.js create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/questio.js create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/tagASUPVOIRstate.js.js create mode 100755 src/setup/data/domain/apixpress/www/cdn/public/js/tagold.js rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/template/formgeneric.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/template/questInput.mustache (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/public/testnetwork.html (100%) rename {setup => src/setup}/data/domain/apixpress/www/cdn/suiviprojetapiXpress.svg (99%) rename {setup => src/setup}/nginx/modelwebsite.conf.mustache (100%) rename {setup => src/setup}/nginx/nginx.conf.mustache (100%) diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100755 index 73ba1d2..0000000 --- a/.eslintrc.js +++ /dev/null @@ -1,15 +0,0 @@ -module.exports = { - "extends": "eslint:recommended", - "rules": { - "@typescript-eslint/no-unused-vars": "off", - "arrow-body-style": "off" - }, - "env": { - "browser": true, - "es6": true, - "node": true - }, - "parserOptions": { - "ecmaVersion": "latest" - } -}; diff --git a/apxtrib.js b/apxtrib.js deleted file mode 100755 index 1aa14ee..0000000 --- a/apxtrib.js +++ /dev/null @@ -1,120 +0,0 @@ -const fs = require( 'fs-extra' ); -const bodyParser = require( 'body-parser' ); -const cors = require( 'cors' ); -const express = require( 'express' ); -const logger = require('./src/core/logger') - -/******************************************* - -SEE http://gitlab.ndda.fr/philc/apixtribe/-/wikis/HOWTOoverview -To have a quick understanding before doing deeply in source code - -*********************************************/ -// check setup -if( !fs.existsSync( '/etc/nginx/nginx.conf' ) ) { - logger.info( '\x1b[31m Check documentation, nginx have to be installed on this server first, no /etc/nginx/nginx.conf available, install then rerun yarn command.' ); - process.exit(); -} -if( !fs.existsSync( './tribes/townconf.js' ) ) { - logger.info( `\x1b[42m####################################\nWellcome into apixtribe, you need to init your town by "yarn setup" the first time . \nCheck README's project to learn more. more.\n #####################################\x1b[0m` ); - process.exit(); -} -// config.js exist in any case from Setup.checkinit(); -const config = require( './tribes/townconf.js' ); -// Tribes allow to get local apixtribe instance context -// dataclient .tribeids [] .DOMs [] .routes (plugins {url:name route:path}) .appname {tribeid:[website]} -const dataclient = require( './models/Tribes' ) - .init(); -logger.info( 'allowed DOMs to access to this apixtribe server: ', dataclient.DOMs ) -const app = express(); -app.set( 'trust proxy', true ); -// To set depending of data form or get size to send -app.use( bodyParser.urlencoded( config.bodyparse.urlencoded ) ); -// To set depending of post put json data size to send -app.use( express.json() ) -app.use( bodyParser.json( config.bodyparse.json ) ); -app.locals.tribeids = dataclient.tribeids; -logger.info( 'app.locals.tribeids', app.locals.tribeids ); -// User token authentification and user init user search -const datauser = require( './models/Pagans' ) - .init( dataclient.tribeids ); -app.locals.tokens = datauser.tokens; -logger.info( 'app.locals.tokens key ', Object.keys( app.locals.tokens ) ) -// Cors management -const corsOptions = { - origin: ( origin, callback ) => { - if( origin === undefined ) { - callback( null, true ); - } else if( origin.indexOf( 'chrome-extension' ) > -1 ) { - callback( null, true ); - } else { - //logger.info( 'origin', origin ) - //marchais avant modif eslint const rematch = ( /^https?\:\/\/(.*)\:.*/g ).exec( origin ) - const rematch = ( /^https?:\/\/(.*):.*/g ) - .exec( origin ) - //logger.info( rematch ) - let tmp = origin.replace( /http.?:\/\//g, '' ) - .split( '.' ) - - if( rematch && rematch.length > 1 ) tmp = rematch[ 1 ].split( '.' ); - //logger.info( 'tmp', tmp ) - let dom = tmp[ tmp.length - 1 ]; - if( tmp.length > 1 ) { - dom = `${tmp[tmp.length-2]}.${tmp[tmp.length-1]}` - } - logger.info( `origin: ${origin}, dom:${dom}, CORS allowed? : ${dataclient.DOMs.includes( dom )}` ); - if( dataclient.DOMs.includes( dom ) ) { - callback( null, true ) - } else { - logger.info( `Origin is not allowed by CORS` ); - callback( new Error( 'Not allowed by CORS' ) ); - } - } - }, - exposedHeaders: Object.keys( config.exposedHeaders ) -}; -// CORS -app.use( cors( corsOptions ) ); -// Static Routes -app.use( express.static( `${__dirname}/tribes/${config.mayorId}/www/cdn/public`, { - dotfiles: 'allow' -} ) ); - -//Allow to public access a space dev delivered by apixtribe -// this is just a static open route for dev purpose, -// for production, we'll use a nginx static set to /www/app/appname -/*logger.info( `${config.dnsapixtribe}/space/tribeid/website`, dataclient.appname ); -Object.keys( dataclient.appname ) - .forEach( cid => { - dataclient.appname[ cid ].forEach( website => { - app.use( `/space/${cid}/${website}`, express.static( `${config.tribes}/${cid}/spacedev/${website}` ) ); - } ) - } ); -*/ -// Routers add any routes from /routes and /plugins -logger.info( 'Routes available on this apixtribe instance' ); -logger.info( dataclient.routes ); -// prefix only use for dev purpose in production a proxy nginx redirect /app/ to node apixtribe - -dataclient.routes.forEach( r => { - try { - app.use( r.url, require( r.route ) ); - } catch ( err ) { - logger.info( `\x1b[31m!!! WARNING issue with route ${r.route} from ${r.url} check err if route is key then solve err, if not just be aware that this route won't work on your server. If you are not the maintainer and no turn around please contact the email maintainer.\x1b[0m` ) - logger.info( 'raise err-:', err ); - } -} ) -// Listen web server from config profil (dev prod, other) -app.listen( config.porthttp, () => { - logger.info( `check in your browser that api works http://${config.dnsapixtribe}:${config.porthttp}` ); -} ); -/*httpServer.setTimeout( config.settimeout ); -if( config.withssl == "YES" ) { - const httpsServer = https.createServer( config.SSLCredentials, app ); - httpsServer.listen( config.port.https, () => { - logger.info( `check in your browser that api works https://${config.dnsapixtribe}:${config.port.https}` ); - } ); - httpsServer.setTimeout( config.settimeout ); -};*/ - -logger.info( "\x1b[42m\x1b[37m", "Made with love for people's freedom, enjoy !!!", "\x1b[0m" ); diff --git a/doc/GettingStarted.md b/doc/GettingStarted.md new file mode 100644 index 0000000..330d283 --- /dev/null +++ b/doc/GettingStarted.md @@ -0,0 +1,6 @@ +# Getting started with Apxtrib + +Initialize : `yarn setup` + +Development mode : `npm run dev` + diff --git a/middlewares/ASUPhaveAccessrighttoanobject.js b/middlewares/ASUPhaveAccessrighttoanobject.js deleted file mode 100755 index 94c6979..0000000 --- a/middlewares/ASUPhaveAccessrighttoanobject.js +++ /dev/null @@ -1,95 +0,0 @@ -const jwt = require( 'jwt-simple' ); -const jsonfile = require( 'jsonfile' ); -const fs = require( 'fs-extra' ); -const moment = require( 'moment' ); -const glob = require( 'glob' ); -const path = require( 'path' ); - -// A REMPLACER PAR hasAccessrighton.js -/* -qui permet de passer en parametre des tests d'actions autoriser sur une objet - -*/ - - -// Check if package is installed or not to pickup the right config file -const src = ( __dirname.indexOf( '/node_modules/' ) > -1 ) ? '../../..' : '..'; -const config = require( path.normalize( `${__dirname}/${src}/config.js` ) ); - -const haveAccessrighttoanobject = ( req, res, next ) => { - /* - from isAuthenticated req.session.header.accessrights={app:{'tribeid:projet':profile}, - data:{ "sitewebsrc": "RWCDO", - "contacts": "RWCDO"}} - from the last successfull authentification. - profile is a keyword menu available into clientconf.json of tribeid - data, list of object accessright Read Write Create Delete Owner - a xuuid can read any objet if R - if O wner means that it can only read write its object create by himself - - This middleware check that we apply RESTFull CRUD concept depending of access right of a xuuid trying to act onto a xworkon tribeid - Action get = Read put = Update post = Create delete = Delete - object = req.Urlpath.split(/)[0] - */ - logger.info( 'haveAccessrighttoanobject()?' ); - // req.originalUrl contain /object/action/id object id to run action - // req.route.methods ={ put:true, delete:true post:true, get:true } - const objet = req.baseUrl.slice( 1 ); //contain /object - const model = objet.charAt( 0 ) - .toUpperCase() + objet.slice( 1 ); // model u object with first letter in uppercase - let droit = ""; - let ownby = []; - /* - Check if object exist and get the OWNBY array, not relevant for referentials object that is only manage by CRUD no Owner logic - */ - if( objet != "referentials" ) { - if( !fs.existsSync( `${config.tribes}/${req.session.header.xworkon}/${objet}/${req.params.id}.json` ) ) { - res.status( 404 ) - .send( { - payload: { - info: [ 'idNotfound' ], - model, - moreinfo: `${config.tribes}/${req.session.header.xworkon}/${objet}/${req.params.id}.json does not exist ` - } - } ); - } else { - ownby = jsonfile.readFileSync( `${config.tribes}/${req.session.header.xworkon}/${objet}/${req.params.id}.json` ) - .OWNBY; - } - } - //logger.info( req.session.header ) - if( req.session.header.xpaganid == config.devnoauthxuuid ) { - logger.info( 'haveAccessrighttoanobject yes cause dev test user' ); - } else { - // accessrights was load from isAuthenticated.js middleware to make it available in req.session.header to be used into route for specific access if needed mainly to filter data in the get request depending of profil and data accessright. - if( Object.keys( req.session.header.accessrights.data ) - .includes( "Alltribeid" ) && req.session.header.accessrights.data[ "Alltribeid" ][ objet ] ) { - droit = req.session.header.accessrights.data[ "Alltribeid" ][ objet ]; - } - // erase rights if tribeid is specified in addition of Alltribeid - if( ( req.session.header.accessrights.data[ req.session.header.xworkon ] ) && - req.session.header.accessrights.data[ req.session.header.xworkon ][ objet ] ) { - droit = req.session.header.accessrights.data[ req.session.header.xworkon ][ objet ]; - if( ( req.route.methods.get && droit.includes( 'R' ) ) || - ( req.route.methods.put && droit.includes( 'U' ) ) || - ( req.route.methods.delete && droit.includes( 'D' ) ) || - ownby.includes( req.params.id ) ) { - logger.info( 'haveAccessrighttoanobject yes' ) - } else if( req.route.methods.post && droit.includes( 'C' ) ) { - logger.info( 'haveAccessrighttoanobject yes create' ); - } else { - logger.info( 'haveAccessrighttoanobject no' ) - res.status( 403 ) - .send( { - payload: { - info: [ 'NoAccessrights' ], - model, - moreinfo: `User ${req.session.header.xpaganid} accessrights are not set to do this action` - } - } ); - } - } - } - next(); -}; -module.exports = haveAccessrighttoanobject; diff --git a/middlewares/checkHeaders.js b/middlewares/checkHeaders.js deleted file mode 100755 index 1c440f4..0000000 --- a/middlewares/checkHeaders.js +++ /dev/null @@ -1,88 +0,0 @@ -const path = require( 'path' ); - -// Check if package is installed or not to pickup the right config file -//const src = ( __dirname.indexOf( '/node_modules/' ) > -1 ) ? '../../..' : '..'; -//const config = require( path.normalize( `${__dirname}/${src}/config.js` ) ); -const config = require( '../tribes/townconf.js' ); -/* -Check que le header contient des éléments necessaire pour les -routes utilisant tribeid / language / token / uuid -*/ -const checkHeaders = ( req, res, next ) => { - //logger.info( 'checkHeaders()' ); - // These headers must be passed in the request - // X-Auth and X-Uuid could have any true value - // header is stored in req.app.locals.header to be pass to route - /* const header = { - xtribeid: req.header('x-client-id'), - xlang: req.header('x-language'), - xauth: req.header('x-auth'), - xuuid: req.header('x-uuid'), - xworkon: req.header('x-xorkon', - xapp:req.header('x-app')) - }; - On recupere accessrights via is Authenticated - */ - req.session = {}; - const header = {}; - let missingheader = ""; - //logger.info( 'avant validation headers', req.headers ); - //attention changement 7/11/2021 phil des exposedheader cf config.js - //If in httprequest url header are send then they are used inpriority - //Use case : send an email with a unique link that works without password and request to change password - for( const h of config.exposedHeaders ) { - //logger.info( h, req.header( h ) ) - if( req.params[ h ] ) { - header[ h ] = req.params[ h ] - } else if( req.header( h ) ) { - header[ h ] = req.header( h ) - } else { - // Missing header - missingheader += " " + h - } - }; - //logger.info( 'header', header ) - if( req.params.xauth && req.params.xuuid ) { - // If this exist => it is a timeout limited token - req.app.locals.tokens[ req.params.xpaganid ] = req.params.xauth; - } - req.session.header = header; - // Each header have to be declared - if( missingheader != "" ) { - return res.status( 403 ) - .send( { - info: [ 'forbiddenAccess' ], - model: 'Pagans', - moreinfo: 'checkHeader headerIsMissing:' + missingheader - } ); - }; - //logger.info( req.app.locals.tribeids ) - if( !req.app.locals.tribeids.includes( header.xtribe ) ) { - return res.status( 404 ) - .send( { - info: [ 'tribeiddoesnotexist' ], - model: 'Pagans', - moreinfo: `xtribe unknown: ${header.xtribe}` - } ); - } - if( !req.app.locals.tribeids.includes( header.xworkon ) ) { - return res.status( 404 ) - .send( { - info: [ 'tribeiddoesnotexist' ], - model: 'Pagans', - moreinfo: `xworkon unknown: ${header.xworkon}` - } ); - } - if( !config.languagesAvailable.includes( header.xlang ) ) { - return res.status( 404 ) - .send( { - info: [ 'langNotused' ], - model: 'Pagans', - moreinfo: `xlang unknown: ${header.xlang}` - } ); - } - //logger.info( 'After middleare checkHeaders.js req.session.header', req.session.header ) - //logger.info( 'checkheaders next' ) - next(); -}; -module.exports = checkHeaders; diff --git a/middlewares/hasAccessrighton.js b/middlewares/hasAccessrighton.js deleted file mode 100755 index 2aa8ed8..0000000 --- a/middlewares/hasAccessrighton.js +++ /dev/null @@ -1,42 +0,0 @@ -const fs = require( 'fs-extra' ); -const glob = require( 'glob' ); -const path = require( 'path' ); - -const config = require( '../tribes/townconf.js' ); - -const hasAccessrighton = ( object, action, ownby ) => { - /* - @action (mandatory) : CRUDO - @object (mandatory)= name of a folder object in /tribeid space can be a tree for example objects/items - @ownby (option) = list des uuid propriétaire - return next() if all action exist in req.app.local.tokens[UUID].ACCESSRIGHTS.data[object] - OR if last action ="O" and uuid exist in ownBy - Careffull if you have many action CRO let O at the end this will force req.right at true if the owner try an action on this object - */ - return ( req, res, next ) => { - //logger.info( 'err.stack hasAccessrights', err.statck ) - //logger.info( `test accessright on object:${object} for ${req.session.header.xworkon}:`, req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ] ) - req.right = false; - if( req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ] && req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ][ object ] ) { - req.right = true; - [ ...action ].forEach( a => { - if( a == "O" && ownby && ownby.includes( req.session.header.xpaganid ) ) { - req.right = true; - } else { - req.right = req.right && req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS.data[ req.session.header.xworkon ][ object ].includes( a ) - } - } ) - } - //logger.info( 'Access data autorise? ', req.right ) - if( !req.right ) { - return res.status( 403 ) - .send( { - info: [ 'forbiddenAccess' ], - model: 'middleware', - moreinfo: 'no auth to act on this object' - } ) - } - next(); - } -} -module.exports = hasAccessrighton; diff --git a/middlewares/isAuthenticated.js b/middlewares/isAuthenticated.js deleted file mode 100755 index 7e9b4c4..0000000 --- a/middlewares/isAuthenticated.js +++ /dev/null @@ -1,113 +0,0 @@ -const jwt = require( 'jwt-simple' ); -const jsonfile = require( 'jsonfile' ); -const fs = require( 'fs-extra' ); -const moment = require( 'moment' ); -const glob = require( 'glob' ); -//const path = require( 'path' ); -// Check if package is installed or not to pickup the right config file -//const src = '..'; // ( __dirname.indexOf( '/node_modules/' ) > -1 ) ? '../../..' : '..'; -//const config = require( path.normalize( `${__dirname}/${src}/config.js` ) ); -const config = require( '../tribes/townconf.js' ); -const isAuthenticated = ( req, res, next ) => { - /* - check if authenticated with valid token - if not => set req.session.header.xauth=1 - if yes => set for xWorkon - req.session.header.accessrights={ - app:{'tribeid:website':[liste of menu]}, - data:{ "sitewebsrc": "RWCDO", - "contacts": "RWCDO"}} - Liste of menu is linked with the app tht have to be consistent with accessrights.data - data, list of object accessright Read Write Create Delete Owner - a xuuid can read any objet if R - if O wner means that it can only read write its object create by himself - */ - logger.info( 'isAuthenticated()?' ); - //logger.info( 'req.app.locals.tokens', req.app.locals.tokens ) - //logger.info( 'req.session.header', req.session.header ); - // Check if token exist or not - req.session.header.accessrights = { app: "", data: {} } - if( req.session.header.xpaganid == config.devnoauthxuuid && req.session.header.xauth == config.devnoauthxauth ) { - logger.info( 'isAuthenticated yes: carrefull using a bypass password give you accessrights={}' ); - } else if( req.session.header.xpaganid == "1" || !req.app.locals.tokens[ req.session.header.xpaganid ] ) { - logger.info( `isAuthenticated no : uuid=1 (value=${req.session.header.xpaganid}) or locals.tokens[uuid] empty ` ); - logger.info( 'req.app.locals.tokens de xpaganid', req.app.locals.tokens[ req.session.header.xpaganid ] ); - logger.info( 'list key uuid de req.app.locals.tokens', Object.keys( req.app.locals.tokens ) ) - req.session.header.xauth = "1" - } else if( req.app.locals.tokens[ req.session.header.xpaganid ].TOKEN !== req.session.header.xauth ) { - // logger.info(req.session.header.xuuid); - // logger.info(req.session.header.xauth); - // update tokens from file in case recently logged - try { - logger.info( 'token not in list of token (req.app.locals.tokens) try to refresh from file' ); - req.app.locals.tokens = jsonfile.readFileSync( `${config.tmp}/tokens.json` ); - } catch ( err ) { - logger.info( `check isAuthenticated issue in reading ${config.tmp}/tokens.json` ); - } - if( req.app.locals.tokens[ req.session.header.xpaganid ].TOKEN !== req.session.header.xauth ) { - // if still does not exist then out - logger.info( 'isAuthenticated no, token outdated' ); - req.session.header.xauth = "1" - req.session.header.xpaganid = "1" - } - } - if( req.session.header.xauth == "1" ) { - //return res.status( 403 ) - return res.status( 403 ) - .send( { - info: [ 'forbiddenAccess' ], - model: 'Pagans', - moreinfo: 'isAuthenticated faill' - } ) - } else { - logger.info( 'isAuthenticated yes' ); - if( req.app.locals.tokens[ req.session.header.xpaganid ] ) { - //logger.info( `accessright pour ${req.session.header.xpaganid}`, req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS ); - //set header.accessrights from tokens.json - req.session.header.accessrights = req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS - } else { - // case of bypass no accessright available - req.session.header.accessrights = {} - } - // Once per day, clean old token - const currentday = moment() - .date(); - logger.info( 'test si menagedone' + currentday, !fs.existsSync( `${config.tmp}/menagedone${currentday}` ) ) - if( !fs.existsSync( `${config.tmp}/menagedone${currentday}` ) ) { - glob.sync( `${config.tmp}/menagedone*` ) - .forEach( f => { - fs.remove( f, ( err ) => { - if( err ) { - logger.info( 'err remove menagedone', err ) - } - } ) - } ); - glob.sync( `${config.tmp}/mdcreator*.log` ) - .forEach( f => { - fs.remove( f, ( err ) => { - if( err ) { - logger.info( 'err remove mdcreator log', err ) - } - } ) - } ); - const newtokens = {}; - for( const k of Object.keys( req.app.locals.tokens ) ) { - try { - const decodedToken = jwt.decode( req.app.locals.tokens[ k ].TOKEN, config.jwtSecret ); - //logger.info( moment( decodedToken.expiration ), moment() ) - //logger.info( moment( decodedToken.expiration ) >= moment() ) - if( moment( decodedToken.expiration ) >= moment() ) { - newtokens[ k ] = req.app.locals.tokens[ k ]; - } - } catch ( err ) { - logger.info( "Check isAuthenticated cleaning token ", err ); - } - }; - req.app.locals.tokens = newtokens; - jsonfile.writeFileSync( `${config.tmp}/tokens.json`, newtokens ); - fs.writeFileSync( `${config.tmp}/menagedone${currentday}`, 'fichier semaphore to clean data each day can be deleted with no consequence', 'utf-8' ); - } - next(); - } -}; -module.exports = isAuthenticated; diff --git a/models/Contracts.js b/models/Contracts.js deleted file mode 100755 index e875010..0000000 --- a/models/Contracts.js +++ /dev/null @@ -1,121 +0,0 @@ -const fs = require( 'fs-extra' ); -const jsonfile = require( 'jsonfile' ); -const glob = require( 'glob' ); -const path = require( 'path' ); -const moment = require( 'moment' ); -const axios = require( 'axios' ); -const scrapeit = require( 'scrape-it' ); -const cheerio = require( 'cheerio' ); -const Mustache = require( 'mustache' ); -const qrcode = require( 'qrcode' ); - -// Check if package is installed or not to pickup the right config file - -const config = require( '../tribes/townconf.js' ); - -/* -Model that will process actions plan for each client like sending email campain, or anything that -are plan in /tribes/tribeid/actions/todo -*/ -const Cards = {}; //require('../../models/Cards'); -const Contracts = {}; -/* -Send if envoicampain a liste of email in param.msg.destperso with param.headers -if not envoicampain, it just return a test about what to send -@param = {headers, msg:{destperso}} -*/ -Contracts.sendcampain = async ( param, envoicampain ) => { - if( envoicampain ) { - // Carefull w the action post outputs/msg just wait the feedback of the 1st message - const retcampain = await axios.post( 'https://mail.maildigit.fr/outputs/msg', param.msg, { - headers: param.headers - } ); - if( retcampain.status !== 200 ) { - logger.info( "err", retcampain.payload.moreinfo ); - fs.appendFileSync( `${config.tribes}/log_erreurglobal.txt`, moment( new Date() ) - .format( 'YYYYMMDD HH:mm:ss' ) + ' - IMPOSSIBLE TO SEND CAMPAIN TODO for :' + param.tribeid + ' -- ' + retcampain.payload.moreinfo + '\n', 'utf-8' ); - }; - return retcampain; - } else { - // permet de tester ce qu'il y a à envoyer - let premieremail = ""; - for( let i = 0; i < param.msg.destperso.length; i++ ) { - premieremail += param.msg.destperso[ 0 ].email + ","; - } - return { - status: 201, - payload: { - info: [ 'simplecomptage' ], - model: 'Contracts', - moreinfo: "#email: " + param.msg.destperso.length + " - 5 1st emails: " + premieremail - } - }; - } -} -Contracts.initActiontodo = async ( envoie ) => { - const datedeb = moment( new Date() ) - .format( 'YYYYMMDD HH:mm:ss' ); - let todo, actiondone; - let log = { - nbaction: 0, - nbactionexec: 0, - nbactionerr: 0, - actionlist: "" - }; - const listclient = jsonfile.readFileSync( `${config.tribes}/tribeids.json` ); - for( let clid in listclient ) { - logger.info( listclient[ clid ] ); - let listaction = glob.sync( `${config.tribes}/${listclient[clid]}/actions/todo/*.json` ); - for( let action in listaction ) { - logger.info( listaction[ action ] ) - log.nbaction++; - todo = jsonfile.readFileSync( listaction[ action ] ); - let passdate = true; - // currentdate doit etre après la startDate si existe et avant valideuntilDate si existe - // logger.info('test now est avant date start ', moment() < moment(todo.startDate, 'YYYYMMDD HH:mm:ss').toDate()); - if( todo.startDate && ( moment() < moment( todo.startDate, 'YYYYMMDD HH:mm:ss' ) - .toDate() ) ) { - passdate = false; - }; - // currentdate ne doit pas depasser la date de validité de la tache - // logger.info('test now est après la date de validite ', moment() > moment(todo.validuntilDate, 'YYYYMMDD HH:mm:ss').toDate()); - if( todo.valideuntilDate && ( moment() > moment( todo.validuntilDate, 'YYYYMMDD HH:mm:ss' ) - .toDate() ) ) { - passdate = false; - }; - // currentdate - if( passdate && todo.action && todo.error == "" ) { - log.nbactionexec++; - const actiondone = await Contracts[ todo.action ]( todo, envoie ); - todo.datesRun.push( moment( new Date() ) - .format( 'YYYYMMDD HH:mm:ss' ) ); - //logger.info("actiondone", actio jsonfile.writeFileSyncndone); - log.actionlist += "STATUS:" + actiondone.status + " -- " + listaction[ action ] + "\n"; - if( actiondone.status == 200 ) { - todo.error = ""; - } else { - log.nbactionerr++; - todo.error += "status : " + actiondone.status + ' ' + actiondone.payload.moreinfo; - }; - if( parseInt( todo.maxnumberoftime ) && todo.maxnumberoftime != "999" && ( todo.datesRun.length >= parseInt( todo.maxnumberoftime ) ) ) { - //archive en done this triggeraction - jsonfile.writeFileSync( listaction[ action ].replace( '/todo/', '/done/' ), todo, { - spaces: 2 - } ); - fs.unlinkSync( listaction[ action ] ); - } else { - jsonfile.writeFileSync( listaction[ action ], todo, { - spaces: 2 - } ); - } - } else { - log.actionlist += "STATUS : not executed " + listaction[ action ] + "\n"; - }; - }; - }; - const trace = "###################### LOGS ####################\nSTART:" + datedeb + " END:" + moment( new Date() ) - .format( 'YYYYMMDD HH:mm:ss' ) + "\n nombre d'actions analysées : " + log.nbaction + " dont executées : " + log.nbactionexec + " dont en erreur: " + log.nbactionerr + "\n" + log.actionlist; - fs.appendFileSync( `${config.tribes}/log.txt`, trace, 'utf-8' ); - return "done"; -} -module.exports = Contracts; diff --git a/models/Messages.js b/models/Messages.js deleted file mode 100755 index f86716d..0000000 --- a/models/Messages.js +++ /dev/null @@ -1,400 +0,0 @@ -const bcrypt = require( 'bcrypt' ); -const fs = require( 'fs-extra' ); -const path = require( 'path' ); -const jsonfile = require( 'jsonfile' ); -const glob = require( 'glob' ); -const Mustache = require( 'mustache' ); -const jwt = require( 'jwt-simple' ); -const { DateTime } = require( 'luxon' ); -const UUID = require( 'uuid' ); -const Outputs = require( '../models/Outputs.js' ); -const config = require( '../tribes/townconf.js' ); -const checkdata = require( `../nationchains/socialworld/contracts/checkdata.js`); -/* -Message manager -* Manage apixtribe message at different level -* this means that an object (most often a user or a contact) want to send a question to an other user. - - -To know more http://gitlab.ndda.fr/philc/apixtribe/-/wikis/HOWTONotification - -*/ -const Messages = {}; -Messages.init = () => { - console.group( 'init Message' ); - Messages.aggregate(); -} - -Messages.byEmailwithmailjet = ( tribeid, msg ) => { - /* @tribeid requester - @msg =[{ - To:[{Email,Name}], - Cc:[{Email,Name}], - Bcc:[{Email,Name}]}], - Subject:"Subject", - TextPart:"texte content", - HTMLPart:"html content" - }] - If tribeid has a mailjet account it use it if not then it use the apixtribe @mailjetconf = {apikeypub:, apikeypriv:, From:{Email:,Name:}} - This send a bunch of messages check the mailjet account used - FYI: Basic account is 200 email /days 6000 /month - Log is stored into - tribeidsender/messages/logs/sent/timestamp.json - @todo GUI to manage statistics and notification alert limit sender email - */ - logger.info( 'Envoie mailjet' ) - const confclient = fs.readJsonSync( `${config.tribes}/${tribeid}/clientconf.json` ); - let tribeidsender = tribeid; - if( confclient.smtp && confclient.smtp.mailjet ) { - mailjetconf = confclient.smtp.mailjet; - } else { - const confapixtribe = fs.readJsonSync( `${config.tribes}/${config.mayorId}/clientconf.json` ); - if( !( confapixtribe.smtp && confapixtribe.smtp.mailjet ) ) { - return { status: 403, data: { models: "Messages", info: [ "nosmtpmailjet" ], moreinfo: "missing smtpmailjet parameter in apixtribe contact your admin to activate an mailjet account on this server." } } - } - tribeidsender = "apixtribe"; - mailjetconf = confapixtribe.smtp.mailjet; - } - //add from from setings account - const MSG = msg.map( m => { m.From = mailjetconf.From; return m; } ); - const mailjet = require( 'node-mailjet' ) - .connect( mailjetconf.apikeypub, mailjetconf.apikeypriv ); - const request = mailjet.post( 'send', { version: 'v3.1' } ) - .request( { "Messages": MSG } ); - request - .then( result => { - //store into tribeidsender/messages/logs/sent/timestamp.json - const t = Date.now(); - MSG.result = result.body; - fs.outputJson( `${config.tribes}/${tribeidsender}/messages/logs/sent/${t}.json`, MSG ) - logger.info( result.body ) - } ) - .catch( err => { - const t = Date.now(); - MSG.result = err; - fs.outputJson( `${config.tribes}/${tribeidsender}/messages/logs/error/${t}.json`, MSG ) - logger.info( err.statusCode, err ) - } ) - -}; -Messages.buildemail = ( tribeid, tplmessage, data ) => { - /* @tribeid => client concerned by sending email get info from clientconf.json (customization, useradmin:{ EMAIL,LOGIN} , ...) - @tplmessage => folder where template is available (ex: apixtribe/referentials/dataManagement/template/order) - @data { destemail = email to - if destuuid => then it get user EMAIL if exiat - subject = mail subject - // any relevant information for template message - msgcontenthtml = html msg content - msgcontenttxt = text msg content - ....} - @return msg - mail part ready to send by mailjet or other smtp - */ - if( !fs.existsSync( `${config.tribes}/${tribeid}/clientconf.json` ) ) { - return { status: 404, data: { model: "Messages", info: [ "tribeiddoesnotexist" ], moreinfo: `${tribeid} does not exist` } } - } - if( !fs.existsSync( `${config.tribes}/${tplmessage}` ) ) { - return { status: 404, data: { model: "Messages", info: [ "tplmessagedoesnotexist" ], moreinfo: `tpl does not exist ${tplmessage}` } } - } - const clientconf = fs.readJsonSync( `${config.tribes}/${tribeid}/clientconf.json` ) - //add clientconf.customization into data for template - data.customization = clientconf.customization; - //manage receiver - const msg = { To: [ { Email: clientconf.useradmin.EMAIL, Name: clientconf.useradmin.LOGIN } ] }; - if( data.destemail ) { - msg.To.push( { Email: data.destemail } ) - } - if( data.destuuid && fs.exist( `${config.tribes}/${tribeid}/users/${data.destuuid}.json` ) ) { - const uuidconf = fs.readJsonSync( `${config.tribes}/${tribeid}/users/${data.destuuid}.json` ); - if( uuidconf.EMAIL && uuidconf.EMAIL.length > 4 ) { - msg.To.push( { Email: uuidconf.EMAIL, Name: uuidconf.LOGIN } ) - } - } - //logger.info( data ) - // email content - msg.Subject = `Message from ${tribeid}`; - if( data.subject ) msg.Subject = data.subject; - msg.TextPart = Mustache.render( fs.readFileSync( `${config.tribes}/${data.tplmessage}/contenttxt.mustache`, 'utf-8' ), data ); - msg.HTMLPart = Mustache.render( fs.readFileSync( `${config.tribes}/${data.tplmessage}/contenthtml.mustache`, 'utf-8' ), data ); - return { - status: 200, - data: { model: "Messages", info: [ "msgcustomsuccessfull" ], msg: msg } - } -}; -Messages.postinfo = ( data ) => { - /* - Data must have: - at least one of desttribeid:,destuuid:,destemail: - if an email have to be sent tplmessage:"tribeid/referentials/dataManagement/template/tplname", - at least one of contactemail:,contactphone,contactlogin,contactuuid - any other usefull keys - - Data is stored into contacts object .json - */ - let contact = ""; - [ 'contactemail', 'contactphone', 'contactuuid', 'contactlogin' ].forEach( c => { - if( data[ c ] ) contact += c + "##" + data[ c ] + "###"; - } ) - logger.info( contact ) - if( contact == "" ) { - return { status: 404, data: { model: "Messages", info: [ "contactundefine" ], moreinfo: "no contact field found in this form" } } - } - if( !data.desttribeid ) { - return { status: 404, data: { model: "Messages", info: [ "tribeidundefine" ], moreinfo: "no desttribeid field found in this form" } } - } - // save new message in contacts - let messages = {}; - if( fs.existsSync( `${config.tribes}/${data.desttribeid}/contacts/${contact}.json` ) ) { - messages = fs.readJsonSync( `${config.tribes}/${data.desttribeid}/contacts/${contact}.json`, 'utf-8' ); - } - messages[ Date.now() ] = data; - fs.outputJsonSync( `${config.tribes}/${data.desttribeid}/contacts/${contact}.json`, messages ); - - // if templatemessage exist then we send alert email - // data content have to be consistent with tplmessage to generate a clean email - if( data.tplmessage && data.tplmessage != "" && - fs.existsSync( `${config.tribes}/${data.tplmessage}` ) ) { - if( !( data.msgtplhtml && data.msgtpltxt ) ) { - data.msgcontenthtml = `

${data.contactname} - ${contact.replace(/###/g,' ').replace(/##/g,":")}

Message: ${data.contactmessage}

` - data.msgcontenttxt = `${data.contactname} - ${contact}/nMessage:${data.contactmessage}\n`; - } else { - data.msgcontenthtml = Mustache.render( data.msgtplhtml, data ) - data.msgcontenttxt = Mustache.render( data.msgtpltxt, data ) - } - const msg = Messages.buildemail( data.desttribeid, data.tplmessage, data ) - if( msg.status == 200 ) { - Messages.byEmailwithmailjet( data.desttribeid, [ msg.data.msg ] ); - } - // we get error message eventualy but email feedback sent is not in real time - return msg; - } else { - return { status: 404, data: { info: "missingtpl", model: "Messages", moreinfo: `missing template ${data.tplmessage}` } } - } -} -Messages.aggregate = () => { - // collect each json file and add them to a global.json notifat require level - const dest = {}; - try { - glob.sync( `${ config.tribes }/**/notif_*.json` ) - .forEach( f => { - //logger.info( 'find ', f ) - const repglob = `${path.dirname(f)}/global.json`; - if( !dest[ repglob ] ) { dest[ repglob ] = [] } - dest[ repglob ].push( fs.readJsonSync( f, 'utf-8' ) ); - fs.removeSync( f ); - } ) - //logger.info( dest ) - Object.keys( dest ) - .forEach( g => { - let notif = []; - if( fs.existsSync( g ) ) { notif = fs.readJsonSync( g ) }; - fs.writeJsonSync( g, notif.concat( dest[ g ] ), 'utf-8' ); - } ) - } catch ( err ) { - Console.log( "ATTENTION, des Messages risquent de disparaitre et ne sont pas traitées." ); - } -} -Messages.object = ( data, header ) => { - /* - Create or replace an object no check at all here this is only - a way to add / replace object - if deeper thing have to be checheck or done then a callback:{tribeidplugin,pluginname,functionname} - data.descttribeid tribeid to send at least to admin - data.tplmessage = folder of emailtemplate - */ - logger.info( 'data', data ) - logger.info( `${config.tribes}/${header.xworkon}/${data.object}` ) - if( !fs.existsSync( `${config.tribes}/${header.xworkon}/${data.object}` ) ) { - return { - status: 404, - data: { - model: "Messages", - info: [ 'UnknownObjectfortribeid' ], - moreinfo: `This object ${data.object} does not exist for this tribeid ${header.xworkon}` - } - }; - } - if( data.uuid == 0 ) { - data.uuid = UUID.v4(); - } - if( data.callback ) { - // check from plugin data and add relevant data - const Plug = require( `${config.tribes}/${data.callback.tribeid}/plugins/${data.callback.plugins}/Model.js` ); - const check = Plug[ data.callback.function ]( header.xworkon, data ); - if( check.status == 200 ) { - data = check.data.data; - } else { - return check; - } - }; - fs.outputJsonSync( `${config.tribes}/${header.xworkon}/${data.object}/${data.uuid}.json`, data ); - // if templatemessage exist then we try to send alert email - if( data.tplmessage && data.tplmessage != "" && - fs.existsSync( `${config.tribes}/${data.tplmessage}` ) ) { - const msg = Messages.buildemail( data.desttribeid, data.tplmessage, data ) - if( msg.status == 200 ) { - logger.info( 'WARN EMAIL DESACTIVATED CHANGE TO ACTIVATE in Messages.js' ) - //Messages.byEmailwithmailjet( data.desttribeid, [ msg.data.msg ] ); - } - // we get error message eventualy but email feedback sent is not in real time see notification alert in case of email not sent. - }; - //Sendback data with new information - return { - status: 200, - data: { - model: "Messages", - info: [ 'Successregisterobject' ], - msg: data - } - }; -} -Messages.notification = ( data, header ) => { - //check if valid notification - if( !req.body.elapseddays ) { req.body.elapseddays = 3 } - let missingkey = ""; - [ 'uuid', 'title', 'desc', 'icon', 'elapseddays', 'classicon' ].forEach( k => { - if( !data[ k ] ) missingkey += ` ${k},` - if( k == "classicon" && !( [ 'text-danger', 'text-primary', 'text-success', 'text-warning', 'text-info' ].includes( data[ k ] ) ) ) { - missingkey += ` classicon is not well set ${data[k]}`; - } - } ) - if( missingkey != '' ) { - return { - status: 422, - data: { - model: "Messages", - info: [ 'InvalidNote' ], - moreinfo: `invalid notification sent cause missing key ${missingkey}` - } - }; - } - if( !fs.existsSync( `${config.tribes}/${header.xworkon}/${data.object}` ) ) { - return { - status: 404, - data: { - model: "Messages", - info: [ 'UnknownObjectfortribeid' ], - moreinfo: `This object ${data.object} does not exist for this tribeid ${data.tribeid}` - } - }; - } - //by default store in tmp/notification this is only for sysadmin - // user adminapixtribe - let notdest = `${config.tmp}`; - - if( data.app ) { - const destapp = `${config.tribes}/${data.app.split(':')[0]}/spacedev/${data.app.split(':')[1]}`; - if( fs.existsSync( destapp ) ) { - notdest = destapp; - } - } - if( data.plugins ) { - const destplugin = `${config.tribes}/${data.plugins.split(':')[0]}/plugins/${data.plugins.split(':')[1]}`; - if( fs.existsSync( destplugin ) ) { - notdest = destplugin; - } - } - if( data.object ) { - const destobject = `${config.tribes}/${data.tribeid}/${data.object}/`; - if( fs.existsSync( destobject ) ) { - notdest = destobject; - } - } - if( !data.time ) { - data.time = Date.now(); - } - fs.outputJsonSync( `${notdest}/Messages/notif_${data.time}.json`, data ); - - return { - status: 200, - data: { - model: "Messages", - info: [ 'Successregisternotification' ], - notif: data - } - }; -} - -Messages.request = ( tribeid, uuid, ACCESSRIGHTS, apprequest ) => { - // list notif for each app - // list notif for each tribeid / objects if Owned - // list notif for - // check uuid notification - // Collect all notification and agregate them at relevant level; - Messages.aggregate(); - - //for test purpose - //const notif = jsonfile.readFileSync( `${config.tribes}/ndda/spacedev/mesa/src/static/components/notification/data_notiflist_fr.json` ); - let notif; - if( !fs.existsSync( `${config.tribes}/${apprequest.tribeid}/spacedev/${apprequest.website}/src/static/components/notification/data_notiflist_${apprequest.lang}.json` ) ) { - // by default we send back this but this highlght an issue - notif = { - "iconnotif": "bell", - "number": 1, - "notifheader": "Your last Messages", - "notiffooter": "Check all Messages", - "actionnotifmanager": "", - "href": "?action=notification.view", - "notifs": [ { - "urldetail": "#", - "classicon": "text-danger", - "icon": "alert", - "title": `File does not exist`, - "desc": ` ${config.tribes}/${apprequest.tribeid}/spacedev/${apprequest.website}/src/static/components/notification/data_notiflist_${apprequest.lang}.json`, - "elapse": "il y a 13mn" - } ] - }; - } else { - notif = jsonfile.readFileSync( `${config.tribes}/${apprequest.tribeid}/spacedev/${apprequest.website}/src/static/components/notification/data_notiflist_${apprequest.lang}.json` ); - //clean up example notif - notif.notifs = []; - } - //check notification for plugins of tribeid of the login - glob.sync( `${config.tribes}/${tribeid}/plugins/*/Messages/global.json` ) - Object.keys( ACCESSRIGHTS.app ) - .forEach( a => { - // check for each app if notification about app - const appnot = `${config.tribes}/${a.split(':')[0]}/spacedev/${a.split(':')[1]}/Messages/global.json`; - if( fs.existsSync( appnot ) ) { - notif.notifs = notif.notifs.concat( fs.readJsonSync( appnot ) ); - } - } ); - Object.keys( ACCESSRIGHTS.plugin ) - .forEach( p => { - // each plugin - if( ACCESSRIGHTS.plugin[ p ].profil == "owner" ) { - const pluginnot = `${config.tribes}/${p.split(':')[0]}/plugins/${p.split(':')[1]}/Messages/global.json`; - if( fs.existsSync( pluginnot ) ) { - notif.notifs = notif.notifs.concat( fs.readJsonSync( pluginnot ) ); - } - } - } ); - Object.keys( ACCESSRIGHTS.data ) - .forEach( c => { - // each tribeid - Object.keys( ACCESSRIGHTS.data[ c ] ) - .forEach( o => { - const cliobjnot = `${config.tribes}/${c}/${o}/Messages/global.json` - //check for each tribeid / Object per accessright user - if( fs.existsSync( cliobjnot ) ) { - logger.info( `droit sur client ${c} objet ${o} : ${ACCESSRIGHTS.data[ c ][ o ]}` ); - //check if intersection between user accessrigth for this object and the notification accessright is not empty @Todo replace true by intersec - logger.info( 'WARN no actif filter all notif are shared with any authenticated user' ) - const newnotif = fs.readJsonSync( cliobjnot ) - .filter( n => { return true } ); - notif.notifs = notif.notifs.concat( newnotif ); - } - } ) - } ) - return { - status: 200, - data: { - model: "Messages", - info: [ 'successgetnotification' ], - notif: notif - } - }; -} - - -module.exports = Messages; diff --git a/models/Nationchains.js b/models/Nationchains.js deleted file mode 100755 index ceea4d8..0000000 --- a/models/Nationchains.js +++ /dev/null @@ -1,105 +0,0 @@ -const bcrypt = require( 'bcrypt' ); -const fs = require( 'fs-extra' ); -const path = require( 'path' ); -const jsonfile = require( 'jsonfile' ); -const glob = require( 'glob' ); -const jwt = require( 'jwt-simple' ); -const moment = require( 'moment' ); -const axios = require( 'axios' ); -const UUID = require( 'uuid' ); -const Outputs = require( './Outputs.js' ); -const config = require( '../tribes/townconf.js' ); -const checkdata = require( `../nationchains/socialworld/contracts/checkdata.js`); -/* -Blockchain manager -* Manage network directory -* read Blockchain and search, -* submit a transaction (now) or contract (futur) to store from userA.pubkey to userB.pubkey a number of AXESS -* mine to be able to register a block and create AXESS -* manage APIXP rules 20 M APIXP 1AXESS = 1 block validation -* manage contract = action if something appened validate by a proof of work -*/ -const Nationchains = {}; -Nationchains.init = () => { - console.group( 'init Nationchains' ); -} -Nationchains.synchronize = () => { - /* - Run process to communicate with a list of apixtribe instance to update transaction and earn AXP - To creation of a new tribeid or a new login - */ - //update himself then send to other information - if( process.env.NODE_ENV != "prod" ) { - // Not concerned - return {} - } - const initcurrentinstance = { - "fixedIP": "", - "lastblocknumber": 0, - "firsttimeupdate": 0, - "lastimeupdate": 0, - "positifupdate": 0, - "negatifupdate": 0, - "pubkeyadmin": "", - "tribeids": [], - "logins": [], - "knowninstance": [] - }; - let currentinstance = initcurrentinstance; - try { - currentinstance = fs.readFileSync( `${config.tribes}/${config.mayorId}/nationchains/nodes/${config.rootURL}`, 'utf-8' ) - } catch ( err ) { - logger.info( 'first init' ) - } - const loginsglob = fs.readJsonSync( `${config.tmp}/loginsglob.json`, 'utf-8' ); - currentinstance.logins = Object.keys( loginsglob ); - currentinstance.tribeids = [ ...new Set( Object.values( loginsglob ) ) ]; - currentinstance.instanceknown = glob.Sync( `${config.tribes}/${config.mayorId}/nationchains/nodes/*` ); - //Save it - fs.outputJsonSync( `${config.tribes}/${config.mayorId}/nationchains/nodes/${config.rootURL}`, currentinstance ); - // proof of work - // try to find a key based on last block with difficulty - // if find then send to all for update and try to get token - // in any case rerun Nationchains.synchronize() - currentinstance.instanceknown.forEach( u => { - if( u != config.rootURL ) { - //send currentinstance info and get back state of - axios.post( `https://${u}/nationchains/push`, currentinstance ) - .then( rep => { - newdata = rep.payload.moreinfo - //Available update info - fs.readJson( `${config.tribes}/${config.mayorId}/nationchains/nodes/${u}`, ( err, data ) => { - if( err ) { - data.negatifupdate += 1; - data.lasttimeupdate = Date.now(); - } else { - data.positifupdate += 1; - data.lastimeupdate = Date.now(); - data.tribeids = newdata.tribeids; - data.logins = newdata.logins; - data.lastblocknumber = newdata.lastblocknumber; - newdata.knowninstance.forEach( k => { - if( !data.knowninstance.includes( k ) ) { - data.knowninstance.push( k ); - //init the domain for next update - initcurrentinstance.firsttimeupdate = Date.now(); - fs.outputJson( `${config.tribes}/${config.mayorId}/nationchains/nodes/${k}`, initcurrentinstance, 'utf-8' ) - } - } ) - } - //save with info - fs.outputJson( `${config.tribes}/${config.mayorId}/nationchains/nodes/${u}`, data ); - } ) - } ) - .catch( err => { - //Not available - data.negatifupdate += 1; - data.lasttimeupdate = Date.now(); - fs.outputJson( `${config.tribes}/${config.mayorId}/nationchains/nodes/${u}`, data ); - } ); - } - } ); -}; - - -module.exports = Nationchains; diff --git a/models/Outputs.js b/models/Outputs.js deleted file mode 100755 index 0e7ed5e..0000000 --- a/models/Outputs.js +++ /dev/null @@ -1,557 +0,0 @@ -const fs = require( 'fs-extra' ); -const path = require( 'path' ); -const formidable = require( 'formidable' ); -const jsonfile = require( 'jsonfile' ); -const mustache = require( 'mustache' ); -const moment = require( 'moment' ); -const UUID = require( 'uuid' ); -const pdf = require( "pdf-creator-node" ); -const nodemailer = require( 'nodemailer' ); -const smtpTransport = require( 'nodemailer-smtp-transport' ); -const axios = require( 'axios' ); -const { GoogleSpreadsheet } = require( 'google-spreadsheet' ); -const config = require( '../tribes/townconf.js' ); -const checkdata = require( `../nationchains/socialworld/contracts/checkdata.js` ); - -const Outputs = {}; - -Outputs.ggsheet2json = async ( req, header ) => { - /* - req.ggsource = key name of the ggsheet into clientconf - req.sheets = [list of sheet names to import] - into /ggsheets/ ggsource.json = {resultfolder,productIdSpreadsheet, - googleDriveCredentials} - */ - if( !fs.existsSync( `${config.tribes}/${header.xworkon}/${req.ggsource}` ) ) { - // Misconfiguration - return { - status: 404, - payload: { - data: {}, - info: [ 'Misconfiguration' ], - moreinfo: `${header.xworkon}/${req.ggsource} missing file check gitlabdocumentation`, - model: 'Outputs' - } - }; - } - const confgg = fs.readJsonSync( `${config.tribes}/${header.xworkon}/${req.ggsource}`, 'utf-8' ) - //const ggconnect = clientconf.ggsheet[ req.ggsource ] - //googleDriveCredentials; - //logger.info( ggconnect ) - doc = new GoogleSpreadsheet( confgg.productIdSpreadsheet ); - await doc.useServiceAccountAuth( confgg.googleDriveCredentials ); - await doc.loadInfo(); - let result = []; - let invalidfor = ""; - //logger.info( "sheets", req.sheets ); - for( const sheetName of req.sheets ) { - logger.info( 'loading: ', sheetName ); - if( !doc.sheetsByTitle[ sheetName ] ) { - invalidfor += " " + sheetName; - } else { - sheet = doc.sheetsByTitle[ sheetName ] - await sheet.loadHeaderRow(); - const records = await sheet.getRows( { offset: 1 } ) - records.forEach( record => { - let offer = {} - for( let index = 0; index < record._sheet.headerValues.length; index++ ) { - offer[ record._sheet.headerValues[ index ] ] = record[ record._sheet.headerValues[ index ] ]; - } - result.push( offer ); - } ); - } - } - const idfile = UUID.v4(); - fs.outputJsonSync( `${config.tribes}/${header.xworkon}/${confgg.resultfolder}/${idfile}.json`, result, 'utf8' ); - if( invalidfor == "" ) { - return { - status: 200, - payload: { - data: `${confgg.resultfolder}/${idfile}.json`, - info: [ 'Successfull' ], - model: 'Outputs' - } - } - } else { - return { - status: 207, - payload: { - data: `${confgg.resultfolder}/${idfile}.json`, - info: [ 'PartialySuccessfull' ], - moreinfo: `Following sheetNames does not exist :${invalidfor}`, - model: 'Outputs' - } - } - }; -}; - - - - -// REVOIR TOUT CE QU'IL Y A EN DESSOUS et ré-écrire avec la logique de ggsheet2json phil 25/10/2021 -/////////////////////////////////////////////////// -const sleep = ( milliseconds = 500 ) => new Promise( resolve => setTimeout( resolve, milliseconds ) ); -/* -Process any data to a specific output: -emailer => generate a finale text file to send -csv => export json file to csv data -pdf => generate a customized document -*/ -Outputs.envoiemail = async ( msg, nowait, nbfois ) => { - // logger.info('{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}'); - // logger.info('msg to send', msg); - logger.info( 'nbfois', nbfois ); - let transporter = nodemailer.createTransport( msg.smtp ); - if( !nowait ) { - logger.info( 'attente 1er msg avant d envoyer les autres' ); - const transport = await transporter.verify(); - logger.info( 'transport', transport ); - if( transport.error ) { - logger.info( 'Probleme de smtp', error ); - return { - status: 500, - payload: { - info: '' - } - }; - } else { - let rep = await transporter.sendMail( msg ); - logger.info( 'rep sendMail', rep ); - if( rep.accepted && rep.accepted.length > 0 && rep.rejected.length == 0 ) { - fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_success.txt`, moment( new Date() ) - .format( 'YYYYMMDD HH:mm:ss' ) + ' - Success after waiting 1st email to send ' + msg.to + '\n', 'utf-8' ); - return { - status: '200', - payload: { - info: [ 'send1stemailok' ], - model: 'Outputs' - } - }; - } - // status à tester si necessaire de detecter une erreur - // if (rep.rejectedErrors) { - fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_error.txt`, moment( new Date() ) - .format( 'YYYYMMDD HH:mm:ss' ) + ' - err after waiting result\n ' + msg.to, 'utf-8' ); - return { - status: '500', - payload: { - info: [ 'rejectedError' ], - model: 'Outputs' - } - }; - } - } else { - transporter.sendMail( msg, async ( err, info ) => { - if( err ) { - if( nbfois < 4 ) { - logger.info( 'nouvelle tentative ', nbfois ); - await sleep( 600000 ); // attends 60sec pour faire une niéme tentative - Outputs.envoiemail( msg, true, nbfois + 1 ); - } else { - // logerror in file - logger.info( 'err', err ) - fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_error.txt`, moment( new Date() ) - .format( 'YYYYMMDD HH:mm:ss' ) + ' - err after 4 tries to ' + info.rejected.join( ',' ) + '\n', 'utf-8' ); - // logger.info('msg.to not well sent', msg.to); - } - } else { - logger.info( 'info', info ) - // logger.info('msg.to well sent', msg.to); - fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_success.txt`, moment( new Date() ) - .format( 'YYYYMMDD HH:mm:ss' ) + ' - Success after ' + nbfois + ' tries to ' + info.accepted.join( ',' ) + '\n', 'utf-8' ); - } - } ); - } - // return something to not wait the rest of email - return { - status: '200', - payload: { - info: [ 'send1stemailok' ], - model: 'Outputs' - } - }; -}; -Outputs.generemsg = async ( msg, header ) => { - /* - wait msg sent and return result sent - */ - // Recupere les parametre smtp du domainName à utiliser - logger.info( 'pass Outputs.generemsg' ) - try { - const confclientexpediteur = jsonfile.readFileSync( `${config.tribes}/${msg.tribeidperso.tribeidexpediteur}/clientconf.json` ); - //logger.info('expediteur', confclientexpediteur); - msg.smtp = confclientexpediteur.smtp; - /* const confclient = jsonfile.readFileSync( - `${config.tribes}/${msg.tribeidperso.tribeid}/clientconf.json` - );*/ - } catch ( err ) { - logger.info( 'la conf smtp du client n\'est pas definie' ); - return { - status: 404, - payload: { - info: [ 'smtpnotdefined' ], - model: 'Outputs' - } - }; - } - logger.info( msg ); - if( !msg.template.sendascontent && msg.template.htmlfile ) { - try { - msg.template.html = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache', 'utf-8' ); - msg.template.text = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contenttxt.mustache', 'utf-8' ); - } catch ( err ) { - logger.info( 'WARNING, html file template missing ' + config.sharedData + '/' + msg.template.htmlfile ); - logger.info( err ); - return { - status: 404, - payload: { - info: [ 'fileUnknown' ], - model: 'UploadFiles', - moreinfo: 'Template unavailable, check ' + config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache and contenttxt.mustache' - } - }; - } - } - if( msg.template.html.length == 0 ) { - logger.info( 'template.html est vide' ) - return { - status: 404, - payload: { - info: [ 'ERRnotemplate' ], - model: 'Outputs', - moreinfo: 'No template email check ' - } - }; - } - // mustache any data into - // logger.info(msg); - const msg2send = {}; - msg2send.smtp = msg.smtp; - msg2send.from = msg.tribeidperso.from; - if( msg.tribeidperso.cc ) msg2send.cc = msg.tribeidperso.cc; - if( msg.tribeidperso.bcc ) msg2send.bcc = msg.tribeidperso.bcc; - if( msg.tribeidperso.replyTo ) msg2send.replyTo = msg.tribeidperso.replyTo; - msg2send.headers = { - 'x-campaign-id': msg.tribeidperso.messageId, - 'x-client-nd-id': msg.tribeidperso.tribeid, - 'x-template-nd-id': msg.tribeidperso.templateId - }; - // we get in datacust= {tribeidperso: with clientconf,destperso: personnalise data to send for email} - // logger.info(msg); - logger.info( 'nb de message to send:', msg.destperso.length ); - //logger.info(msg.destperso); - //msg.destperso.forEach(async (perso, pos) => { - let pos; - let pass1ermsg = false; - for( pos = 0; pos < msg.destperso.length; pos++ ) { - const datacust = { - tribeidperso: msg.tribeidperso, - destperso: msg.destperso[ pos ] - }; - // Evaluation of each field if mustache exist - const datacusteval = {}; - Object.keys( datacust.tribeidperso ) - .forEach( k => { - if( typeof datacust.tribeidperso[ k ] === 'string' || datacust.tribeidperso[ k ] instanceof String ) { - datacusteval[ k ] = mustache.render( datacust.tribeidperso[ k ], datacust ) - } else { - datacusteval[ k ] = datacust.tribeidperso[ k ]; - } - } ) - Object.keys( datacust.destperso ) - .forEach( k => { - if( typeof datacust.destperso[ k ] === 'string' || datacust.destperso[ k ] instanceof String ) { - datacusteval[ k ] = mustache.render( datacust.destperso[ k ], datacust ) - } else { - datacusteval[ k ] = datacust.destperso[ k ]; - } - } ) - msg2send.to = msg.destperso[ pos ].email; - logger.info( 'msg2send.to ' + msg2send.to + ' pos:' + pos ); - // logger.info('avec datacusteval ', datacusteval) - msg2send.subject = mustache.render( msg.template.subject, datacusteval ); - msg2send.text = mustache.render( msg.template.text, datacusteval ); - msg2send.html = mustache.render( msg.template.html, datacusteval ); - let nowait = true; - if( config.emailerurl == 'http://devapia.maildigit.fr:3015' ) { - fs.writeFileSync( 'devdata/tmp/test.html', msg2send.html, 'utf-8' ); - logger.info( 'lancement email sur dev, pour controler le mail générer voir ds ./config.js il faut changer config.emailerurl avec https://mail.maildigit.fr pour envoyer le mail ' ) - return { - status: 200, - payload: { - info: [ 'msgsentok' ], - model: 'Outputs', - moreinfo: "parametrer sur emailer de dev et pas de production" - } - } - } - if( pos == 0 ) { - nowait = false; - /* we are waiting the first email was sent ok then we send all other - check NEEDDATA/OVH/workspace/emailerovh to send emailer with nodemailer and nodemailer-smtp-transport - */ - // logger.info('envoie msg', msg); - //logger.info(msg2send); - const ret = await Outputs.envoiemail( msg2send, nowait, 0 ); - logger.info( 'ret 1er msg', ret ); - if( ret.status == 200 ) { - pass1ermsg = true; - }; - } else if( pass1ermsg ) { - logger.info( '###############################################' ) - logger.info( "envoie msg numero: " + pos + " email: " + msg2send.to ) - //logger.info(msg2send) - Outputs.envoiemail( msg2send, nowait, 0 ); - /*Outputs.envoiemail(msg2send, nowait, 0).then(rep => { - logger.info("envoie email" + pos) - }).catch(err => { - logger.info(err); - });*/ - }; - }; - if( pass1ermsg ) { - return { - status: 200, - payload: { - info: [ 'msgsentok' ], - model: 'Outputs' - } - }; - } else { - return { - status: 500, - payload: { - info: [ 'msgsentko' ], - model: 'Ouputs', - moreinfo: "1er msg non envoyé car erreur" - } - } - } -}; -Outputs.sendMailcampain = async ( msg, headersmsg ) => { - /* - Permet de lancer une campagne de mail personnalisé en mode web service - avec axios config.emailerurl https://mail qui peut être sur un autre serveur que celui en cours - Attention headermsg doit être retraduit avec les champs envoyé par un navigateur - Si le serveur en cours appelle cette fonction les champs du header doivent changer - voir config.js node_env .exposedHeaders - - Pour un exemple de msg voir u exemple type de message envoyé dans un tribeid/domain/clientconf.json - avec l'envoi d'email - */ - //logger.info(msg) - // On ajoute le contenu du template directement dans la demande - if( msg.template.sendascontent && msg.template.htmlfile ) { - try { - logger.info( 'test', msg.template.sendascontent ) - msg.template.html = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache', 'utf-8' ); - msg.template.text = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contenttxt.mustache', 'utf-8' ); - } catch ( err ) { - logger.info( 'WARNING, html file template missing ' + config.sharedData + '/' + msg.template.htmlfile ); - //logger.info(err); - return { - status: 404, - payload: { - info: [ 'fileUnknown' ], - model: 'UploadFiles', - moreinfo: 'Template unavailable, check ' + config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache and contenttxt.mustache' - } - }; - } - delete msg.template.htmlfile; - if( msg.template.html.length == 0 ) { - return { - status: 404, - payload: { - info: [ 'ERRnotemplate' ], - model: 'Outputs', - moreinfo: 'No template email check ' - } - }; - } - } - logger.info( 'envoie sur', `${config.emailerurl}/outputs/msg` ) - //logger.info(msg) - // on check si les key de headermsg sont des key traduite via exposedHeaders - // (cas ou c'est l'application qui envoie un email) - if( headersmsg.xtribeid ) { - Object.keys( config.exposedHeaders ) - .forEach( h => { - headersmsg[ h ] = headersmsg[ config.exposedHeaders[ h ] ]; - delete headersmsg[ config.exposedHeaders[ h ] ]; - } ); - } - // on ajoute le code pour la signature - headersmsg.hashbody = msg.code; - logger.info( 'header after traduction: ', headersmsg ) - try { - const resCamp = await axios.post( `${config.emailerurl}/outputs/msg`, msg, { - headers: headersmsg - } ); - //logger.info('Etat:', resCamp); - logger.info( 'Tried to send 1st email of the campain ' + msg.destperso[ 0 ].email ); - // it just check the 1st email in destperso to return an answer if 1st is ok then all other are send in queue - if( resCamp ) { - return resCamp; - } else { - return { status: 200, payload: { info: [ 'CampainSent' ], model: 'Outputs' } }; - } - } catch ( err ) { - // aios error handler - return { status: 401, payload: { info: [ 'erreuraxios' ], model: 'Outputs', moreinfo: err.message } } - } -}; -Outputs.get = function ( filename, header ) { - // check file exist - const file = `${config.tribes}/${header.xworkon}/${filename}`; - // logger.info('fichier demande ', file); - if( !fs.existsSync( file ) ) { - // logger.info('le fichier demande n existe pas ', file); - return { - status: 404, - payload: { - info: [ 'fileUnknown' ], - model: 'UploadFiles' - } - }; - } else { - logger.info( 'envoie le fichier ', file ); - return { - status: 200, - payload: { - info: [ 'fileknown' ], - model: 'UploadFiles', - file: file - } - }; - } -}; -Outputs.addjson = function ( data, header ) { - /* - Le header = {X-WorkOn:"",destinationfile:"", filename:""} - Le body = {jsonp:{},callback:function to launch after download,'code':'mot cle pour verifier que le fichier est à garder'} - */ - // logger.info(req.body.jsonp); - try { - jsonfile.writeFileSync( header.destinationfile + '/' + header.filename, data.jsonp ); - if( data.callback ) { - const execCB = require( `${config.mainDir}/models/tribeid/${header.xworkon - }` ); - execCB[ data.callback ](); - } - return { - status: 200, - payload: { - info: [ 'wellUpload' ], - model: 'UploadFiles', - render: { - destination: header.destinationfile, - filename: header.filename - } - } - }; - } catch ( err ) { - logger.info( 'Impossible de sauvegarder le fichier, A COMPRENDRE', err ); - return { - status: 503, - payload: { - info: [ 'savingError' ], - model: 'UploadFiles' - } - }; - } -}; -Outputs.add = function ( req, header ) { - const form = new formidable.IncomingForm(); - logger.info( 'req.headers', req.headers ); - logger.info( 'req.params', req.params ); - logger.info( 'req.query', req.query ); - logger.info( 'req.body', req.body ); - let destinationfile = `${config.tribes}/${header.xworkon}/${header.destinationfile - }`; - form.parse( req, function ( err, fields, files ) { - logger.info( 'files', files.file.path ); - logger.info( 'fields', fields ); - const oldpath = files.file.path; - destinationfile += '/' + files.file.name; - logger.info( 'oldpath', oldpath ); - logger.info( 'destinationfile', destinationfile ); - fs.copyFile( oldpath, destinationfile, function ( err ) { - if( err ) { - logger.info( err ); - return { - status: 500, - payload: { - info: [ 'savingError' ], - model: 'UploadFiles' - } - }; - } else { - logger.info( 'passe' ); - fs.unlink( oldpath ); - return { - status: 200, - payload: { - info: [ 'wellUpload' ], - model: 'UploadFiles', - render: { - destination: destinationfile - } - } - }; - } - } ); - } ); -}; -Outputs.generepdf = ( req, header ) => { - return new Promise( ( resolve, reject ) => { - let options = { - format: "A4", - orientation: "portrait", - border: "10mm", - footer: { - height: "20mm", - contents: { - default: '{{page}}/{{pages}}', // html pagination if edit needed - } - } - }; - let document = { - html: req.html, - data: { - data: req.data, - }, - path: `${config.tribes}/${header.xtribe}/outputs/${UUID.v4()}.pdf`, - type: "", - }; - pdf // generate pdf - .create( document, options ) - .then( ( res ) => { - resolve( { - status: 200, - payload: { - info: [ 'wellPdfGenerated' ], - model: 'Outputs', - data: { - path: document.path, - filename: req.data.filename - }, - render: { - filename: req.data.filename - } - } - } ); - } ) - .catch( ( err ) => { - reject( { - status: 500, - payload: { - info: [ 'pdfGenerationError' ], - model: 'Outputs', - error: err - } - } ); - } ); - } ); -}; -module.exports = Outputs; diff --git a/models/OutputsDev.js b/models/OutputsDev.js deleted file mode 100755 index 32f89e6..0000000 --- a/models/OutputsDev.js +++ /dev/null @@ -1,492 +0,0 @@ -const fs = require( 'fs-extra' ); -const path = require( 'path' ); -const formidable = require( 'formidable' ); -const jsonfile = require( 'jsonfile' ); -const mustache = require( 'mustache' ); -const moment = require( 'moment' ); -const UUID = require( 'uuid' ); -const pdf = require( "pdf-creator-node" ); -const nodemailer = require( 'nodemailer' ); -const smtpTransport = require( 'nodemailer-smtp-transport' ); -const axios = require( 'axios' ); -const { GoogleSpreadsheet } = require( 'google-spreadsheet' ); -const async = require( 'async' ); -const config = require( '../tribes/townconf.js' ); -const checkdata = require( `${config.tribes}/${config.mayorId}/www/cdn/public/js/checkdata` ); - -const Outputs = {}; -const sleep = ( milliseconds = 500 ) => new Promise( resolve => setTimeout( resolve, milliseconds ) ); -/* -Process any data to a specific output: -emailer => generate a finale text file to send -csv => export json file to csv data -pdf => generate a customized document -*/ -Outputs.envoiemail = ( msg, next ) => { - let transporter = nodemailer.createTransport( msg.smtp ); - transporter.sendMail( msg, async ( err, info ) => { - if( err ) { - next( err ); - } else { - logger.info( 'info', info ) - fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_success.txt`, moment( new Date() ) - .format( 'YYYYMMDD HH:mm:ss' ) + ' - Success after ' + '0' + ' tries to ' + info.accepted.join( ',' ) + '\n', 'utf-8' ); - next( null ); - } - } ); -}; -Outputs.setupmail = ( msg, msg2send, index ) => { - const datacust = { - tribeidperso: msg.tribeidperso, - destperso: index - }; - // Evaluation of each field if mustache exist - const datacusteval = {}; - Object.keys( datacust.tribeidperso ) - .forEach( k => { - if( typeof datacust.tribeidperso[ k ] === 'string' || datacust.tribeidperso[ k ] instanceof String ) { - datacusteval[ k ] = mustache.render( datacust.tribeidperso[ k ], datacust ) - } else { - datacusteval[ k ] = datacust.tribeidperso[ k ]; - } - } ) - Object.keys( datacust.destperso ) - .forEach( k => { - if( typeof datacust.destperso[ k ] === 'string' || datacust.destperso[ k ] instanceof String ) { - datacusteval[ k ] = mustache.render( datacust.destperso[ k ], datacust ) - } else { - datacusteval[ k ] = datacust.destperso[ k ]; - } - } ) - msg2send.to = index.email; - logger.info( 'msg2send.to ' + msg2send.to ); - msg2send.subject = mustache.render( msg.template.subject, datacusteval ); - msg2send.text = mustache.render( msg.template.text, datacusteval ); - msg2send.html = mustache.render( msg.template.html, datacusteval ); - // TODO need to move that in generemsg - // if (config.emailerurl == 'http://devapia.maildigit.fr:3015') { - // fs.writeFileSync('devdata/tmp/test.html', msg2send.html, 'utf-8'); - // logger.info('lancement email sur dev, pour controler le mail générer voir ds ./config.js il faut changer config.emailerurl avec https://mail.maildigit.fr pour envoyer le mail ') - // return { - // status: 200, - // payload: { - // info: ['msgsentok'], - // model: 'Outputs', - // moreinfo: "parametrer sur emailer de dev et pas de production" - // } - // } - // } - return msg2send; -} -Outputs.envoiefirstmail = async ( msg ) => { - logger.info( '###############################################' ) - logger.info( "envoie first msg email: " + msg.to ) - let transporter = nodemailer.createTransport( msg.smtp ); - logger.info( 'attente 1er msg avant d envoyer les autres' ); - const transport = await transporter.verify(); - logger.info( 'transport', transport ); - if( transport.error ) { - logger.info( 'Probleme de smtp', error ); - return { - status: 500, - payload: { - info: '' - } - }; - } else { - let rep = await transporter.sendMail( msg ); - logger.info( 'rep sendMail', rep ); - if( rep.accepted && rep.accepted.length > 0 && rep.rejected.length == 0 ) { - fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_success.txt`, moment( new Date() ) - .format( 'YYYYMMDD HH:mm:ss' ) + ' - Success after waiting 1st email to send ' + msg.to + '\n', 'utf-8' ); - return { - status: '200', - payload: { - info: [ 'send1stemailok' ], - model: 'Outputs' - } - }; - } - // status à tester si necessaire de detecter une erreur - // if (rep.rejectedErrors) { - fs.appendFileSync( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_error.txt`, moment( new Date() ) - .format( 'YYYYMMDD HH:mm:ss' ) + ' - err after waiting result\n ' + msg.to, 'utf-8' ); - return { - status: '500', - payload: { - info: [ 'rejectedError' ], - model: 'Outputs' - } - }; - } -} -Outputs.envoiemails = ( msg, msg2send, targets, iteration, resolve, reject ) => { - let newtargets = []; - async.each( targets, ( index, callback ) => { // iterate asynchronously in msg.destperso (targets) - let finalmsg = Outputs.setupmail( msg, msg2send, index ); - logger.info( '###############################################' ) - logger.info( "envoie msg email: " + finalmsg.to ) - Outputs.envoiemail( finalmsg, ( err ) => { - if( err ) { // intentionally don't pass this error in callback, we dont want to break loop - newtargets.push( index ); // stock all errored mails for next try - } - } ); - callback(); - }, function ( err ) { // part executed only once all iterations are done - if( newtargets.length > 0 && iteration < 4 ) { - setTimeout( () => { - Outputs.envoiemails( msg, msg2send, newtargets, iteration + 1, resolve, reject ); - }, 600000 ); - } else resolve( newtargets ); // return not resolved errors after 4 trys for log - } ); -} -Outputs.generemsg = async ( msg, header ) => { - /* - wait msg sent and return result sent - */ - // Recupere les parametre smtp du domainName à utiliser - logger.info( 'pass Outputs.generemsg' ) - try { - const confclientexpediteur = jsonfile.readFileSync( `${config.tribes}/${msg.tribeidperso.tribeidexpediteur}/clientconf.json` ); - msg.smtp = confclientexpediteur.smtp; - } catch ( err ) { - logger.info( 'la conf smtp du client n\'est pas definie' ); - return { - status: 404, - payload: { - info: [ 'smtpnotdefined' ], - model: 'Outputs' - } - }; - } - logger.info( msg ); - if( !msg.template.sendascontent && msg.template.htmlfile ) { - try { - msg.template.html = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache', 'utf-8' ); - msg.template.text = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contenttxt.mustache', 'utf-8' ); - } catch ( err ) { - logger.info( 'WARNING, html file template missing ' + config.sharedData + '/' + msg.template.htmlfile ); - logger.info( err ); - return { - status: 404, - payload: { - info: [ 'fileUnknown' ], - model: 'UploadFiles', - moreinfo: 'Template unavailable, check ' + config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache and contenttxt.mustache' - } - }; - } - } - if( msg.template.html.length == 0 ) { - logger.info( 'template.html est vide' ) - return { - status: 404, - payload: { - info: [ 'ERRnotemplate' ], - model: 'Outputs', - moreinfo: 'No template email check ' - } - }; - } - // mustache any data into - const msg2send = {}; - msg2send.smtp = msg.smtp; - msg2send.from = msg.tribeidperso.from; - if( msg.tribeidperso.cc ) msg2send.cc = msg.tribeidperso.cc; - if( msg.tribeidperso.bcc ) msg2send.bcc = msg.tribeidperso.bcc; - if( msg.tribeidperso.replyTo ) msg2send.replyTo = msg.tribeidperso.replyTo; - msg2send.headers = { - 'x-campaign-id': msg.tribeidperso.messageId, - 'x-client-nd-id': msg.tribeidperso.tribeid, - 'x-template-nd-id': msg.tribeidperso.templateId - }; - logger.info( 'nb de message to send:', msg.destperso.length ); - // send first mail - const ret = await Outputs.envoiefirstmail( Outputs.setupmail( msg, msg2send, msg.destperso[ 0 ] ) ); - logger.info( 'ret 1er msg', ret ); - if( ret.status == 200 ) { - pass1ermsg = true; - msg.destperso.shift(); - }; - logger.info( 'attente 1er msg avant d envoyer les autres' ); - // send other mails - new Promise( ( resolve, reject ) => { // useless promise used for recursive calls in Outputs.envoiemails - Outputs.envoiemails( msg, msg2send, msg.destperso, 0, resolve, reject ); - } ) - .then( ( result ) => { - async.eachSeries( result, ( index, callback ) => { // variante of each but runs only a single operation at a time because of fs.appendFile - fs.appendFile( `${config.tribes}/${msg.headers['x-client-nd-id']}/logs/${msg.headers['x-campaign-id']}_error.txt`, moment( new Date() ) - .format( 'YYYYMMDD HH:mm:ss' ) + ' - err after 4 tries to ' + info.rejected.join( ',' ) + '\n', 'utf-8', ( err ) => { - callback( err ); - }, ( err ) => { - if( err ) logger.info( err ); - } ); - logger.info( 'msg.to not well sent', msg.to ); - } ); - } ) - if( pass1ermsg ) { - return { - status: 200, - payload: { - info: [ 'msgsentok' ], - model: 'Outputs' - } - }; - } else { - return { - status: 500, - payload: { - info: [ 'msgsentko' ], - model: 'Ouputs', - moreinfo: "1er msg non envoyé car erreur" - } - } - } -}; -Outputs.sendMailcampain = async ( msg, headersmsg ) => { - /* - Permet de lancer une campagne de mail personnalisé en mode web service - avec axios config.emailerurl https://mail qui peut être sur un autre serveur que celui en cours - Attention headermsg doit être retraduit avec les champs envoyé par un navigateur - Si le serveur en cours appelle cette fonction les champs du header doivent changer - voir config.js node_env .exposedHeaders - - Pour un exemple de msg voir u exemple type de message envoyé dans un tribeid/domain/clientconf.json - avec l'envoi d'email - */ - //logger.info(msg) - // On ajoute le contenu du template directement dans la demande - if( msg.template.sendascontent && msg.template.htmlfile ) { - try { - logger.info( 'test', msg.template.sendascontent ) - msg.template.html = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache', 'utf-8' ); - msg.template.text = fs.readFileSync( config.sharedData + '/' + msg.template.htmlfile + '/contenttxt.mustache', 'utf-8' ); - } catch ( err ) { - logger.info( 'WARNING, html file template missing ' + config.sharedData + '/' + msg.template.htmlfile ); - //logger.info(err); - return { - status: 404, - payload: { - info: [ 'fileUnknown' ], - model: 'UploadFiles', - moreinfo: 'Template unavailable, check ' + config.sharedData + '/' + msg.template.htmlfile + '/contentinline.mustache and contenttxt.mustache' - } - }; - } - delete msg.template.htmlfile; - if( msg.template.html.length == 0 ) { - return { - status: 404, - payload: { - info: [ 'ERRnotemplate' ], - model: 'Outputs', - moreinfo: 'No template email check ' - } - }; - } - } - logger.info( 'envoie sur', `${config.emailerurl}/outputs/msg` ) - //logger.info(msg) - // on check si les key de headermsg sont des key traduite via exposedHeaders - // (cas ou c'est l'application qui envoie un email) - if( headersmsg.xtribeid ) { - Object.keys( config.exposedHeaders ) - .forEach( h => { - headersmsg[ h ] = headersmsg[ config.exposedHeaders[ h ] ]; - delete headersmsg[ config.exposedHeaders[ h ] ]; - } ); - } - // on ajoute le code pour la signature - headersmsg.hashbody = msg.code; - logger.info( 'header after traduction: ', headersmsg ) - try { - const resCamp = await axios.post( `${config.emailerurl}/outputs/msg`, msg, { - headers: headersmsg - } ); - //logger.info('Etat:', resCamp); - logger.info( 'Tried to send 1st email of the campain ' + msg.destperso[ 0 ].email ); - // it just check the 1st email in destperso to return an answer if 1st is ok then all other are send in queue - if( resCamp ) { - return resCamp; - } else { - return { status: 200, payload: { info: [ 'CampainSent' ], model: 'Outputs' } }; - } - } catch ( err ) { - // aios error handler - return { status: 401, payload: { info: [ 'erreuraxios' ], model: 'Outputs', moreinfo: err.message } } - } -}; -Outputs.get = function ( filename, header ) { - // check file exist - const file = `${config.tribes}/${header.xworkon}/${filename}`; - // logger.info('fichier demande ', file); - if( !fs.existsSync( file ) ) { - // logger.info('le fichier demande n existe pas ', file); - return { - status: 404, - payload: { - info: [ 'fileUnknown' ], - model: 'UploadFiles' - } - }; - } else { - logger.info( 'envoie le fichier ', file ); - return { - status: 200, - payload: { - info: [ 'fileknown' ], - model: 'UploadFiles', - file: file - } - }; - } -}; -Outputs.addjson = function ( data, header ) { - /* - Le header = {X-WorkOn:"",destinationfile:"", filename:""} - Le body = {jsonp:{},callback:function to launch after download,'code':'mot cle pour verifier que le fichier est à garder'} - */ - // logger.info(req.body.jsonp); - try { - jsonfile.writeFileSync( header.destinationfile + '/' + header.filename, data.jsonp ); - if( data.callback ) { - const execCB = require( `${config.mainDir}/models/tribeid/${header.xworkon - }` ); - execCB[ data.callback ](); - } - return { - status: 200, - payload: { - info: [ 'wellUpload' ], - model: 'UploadFiles', - render: { - destination: header.destinationfile, - filename: header.filename - } - } - }; - } catch ( err ) { - logger.info( 'Impossible de sauvegarder le fichier, A COMPRENDRE', err ); - return { - status: 503, - payload: { - info: [ 'savingError' ], - model: 'UploadFiles' - } - }; - } -}; -Outputs.add = function ( req, header ) { - const form = new formidable.IncomingForm(); - logger.info( 'req.headers', req.headers ); - logger.info( 'req.params', req.params ); - logger.info( 'req.query', req.query ); - logger.info( 'req.body', req.body ); - let destinationfile = `${config.tribes}/${header.xworkon}/${header.destinationfile - }`; - form.parse( req, function ( err, fields, files ) { - logger.info( 'files', files.file.path ); - logger.info( 'fields', fields ); - const oldpath = files.file.path; - destinationfile += '/' + files.file.name; - logger.info( 'oldpath', oldpath ); - logger.info( 'destinationfile', destinationfile ); - fs.copyFile( oldpath, destinationfile, function ( err ) { - if( err ) { - logger.info( err ); - return { - status: 500, - payload: { - info: [ 'savingError' ], - model: 'UploadFiles' - } - }; - } else { - logger.info( 'passe' ); - fs.unlink( oldpath ); - return { - status: 200, - payload: { - info: [ 'wellUpload' ], - model: 'UploadFiles', - render: { - destination: destinationfile - } - } - }; - } - } ); - } ); -}; -Outputs.sheettojson = async ( req, header ) => { - doc = new GoogleSpreadsheet( req.productIdSpreadsheet ); - await doc.useServiceAccountAuth( req.googleDriveCredentials ); - await doc.loadInfo(); - let result = []; - for( const sheetName of req.sheets ) { - logger.info( 'loading: ', sheetName ); - sheet = doc.sheetsByTitle[ sheetName ] - await sheet.loadHeaderRow(); - const records = await sheet.getRows( { offset: 1 } ) - records.forEach( record => { - let offer = {} - for( let index = 0; index < record._sheet.headerValues.length; index++ ) { - offer[ record._sheet.headerValues[ index ] ] = record[ record._sheet.headerValues[ index ] ]; - } - result.push( offer ); - } ); - } - return result; -}; -Outputs.generepdf = ( req, header ) => { - return new Promise( ( resolve, reject ) => { - let options = { - format: "A4", - orientation: "portrait", - border: "10mm", - footer: { - height: "20mm", - contents: { - default: '{{page}}/{{pages}}', // html pagination if edit needed - } - } - }; - let document = { - html: req.html, - data: { - data: req.data, - }, - path: `${config.tribes}/${header.xtribeid}/outputs/${UUID.v4()}.pdf`, - type: "", - }; - pdf // generate pdf - .create( document, options ) - .then( ( res ) => { - resolve( { - status: 200, - payload: { - info: [ 'wellPdfGenerated' ], - model: 'Outputs', - data: { - path: document.path, - filename: req.data.filename - }, - render: { - filename: req.data.filename - } - } - } ); - } ) - .catch( ( err ) => { - reject( { - status: 500, - payload: { - info: [ 'pdfGenerationError' ], - model: 'Outputs', - error: err - } - } ); - } ); - } ); -}; -module.exports = Outputs; diff --git a/models/Pagans.js b/models/Pagans.js deleted file mode 100755 index 90dcbd0..0000000 --- a/models/Pagans.js +++ /dev/null @@ -1,774 +0,0 @@ -const bcrypt = require( 'bcrypt' ); -const fs = require( 'fs-extra' ); -const jsonfile = require( 'jsonfile' ); -const glob = require( 'glob' ); -const moment = require( 'moment' ); -const jwt = require( 'jwt-simple' ); -const UUID = require( 'uuid' ); -const Outputs = require( './Outputs.js' ); -const config = require( '../tribes/townconf.js' ); -const checkdata = require( `../nationchains/socialworld/contracts/checkdata.js`); - -/* -Gestion des utilisateurs connecte - -/tribes/tribeid/users/ - UUID.json - /searchindex/indexTOKEN = {TOKEN:UUID} - to check authentification - indexLOGIN = {LOGIN:UUID} - to check if LOGIN exist - -Used for referntial: -To update -Global: datashared/referentials/dataManagement/object/users.json -Local: data/tribe/*${header.workOn}/referentials/dataManagement/object/users.json -To use after a server rerun -data/tribe/*${header.workOn}/referentials/${header.langue}/object/users.json - -Faire comme contact charger les index au lancement -et changer la logique de user/id/profil o - - - On initialise les objets au lancement du serveur -this.uids[u.UUID] = [u.LOGIN, u.EMAIL, u.password, u.profil, u.TOKEN]; -this.logins[u.LOGIN] = u.UUID; -this.tokens[u.UUID] = u.TOKEN; -on stocke /domain/tribeid/users/logins.json et /uids.json -on stocke /domain/tribeids.json et tokkens.json - -On retourne l'objet {tribeids:[list tribeid], tokens:{UUID:TOKEN}} -*/ -const Pagans = {}; -Pagans.init = tribeids => { - console.group( 'init Pagans logins, tokens ...' ); - // store globaly tokens - const tokens = {}; - const emailsglob = {}; - const loginsglob = {}; - // For each tribeid create series of indexes - //logger.info(tribeids); - tribeids.forEach( tribeid => { - // Reset for each domain - const uids = {}; - const logins = {}; - const emails = {}; - //check folder exist - /*if( !fs.existsSync( `${config.tribes}/${tribeid}/users` ) ) { - fs.mkdirSync( `${config.tribes}/${tribeid}/users` ) - } - if( !fs.existsSync( `${config.tribes}/${tribeid}/users/searchindex` ) ) { - fs.mkdirSync( `${config.tribes}/${tribeid}/users/searchindex` ) - }*/ - glob.sync( `${config.tribes}/${tribeid}/users/*.json` ) - .forEach( file => { - //logger.info( file ); - const u = fs.readJsonSync( file, 'utf-8' ); - if( !u.TOKEN ) { - u.TOKEN = ''; - } - //logger.info( u ) - uids[ u.UUID ] = [ u.LOGIN, u.EMAIL, u.PASSWORD, u.ACCESSRIGHTS, u.TOKEN ]; - logins[ u.LOGIN ] = u.UUID; - loginsglob[ u.LOGIN ] = tribeid; - // On ne charge que les TOKEN valide - let decodedTOKEN = {}; - if( u.TOKEN != '' ) { - try { - decodedTOKEN = jwt.decode( u.TOKEN, config.jwtSecret ); - //logger.info( 'decodeTOKEN', decodedTOKEN ) - if( moment( decodedTOKEN.expiration ) > moment() ) { - tokens[ u.UUID ] = { TOKEN: u.TOKEN, ACCESSRIGHTS: u.ACCESSRIGHTS }; - //logger.info( `add token valid for ${u.UUID}:`, tokens[ u.UUID ] ) - } - } catch ( err ) { - logger.info( 'pb de TOKEN impossible a decoder' + u.TOKEN, err ); - } - } - if( u.EMAIL ) { - emails[ u.EMAIL ] = u.UUID; - emailsglob[ u.EMAIL ] = tribeid; - } - } ); - // UIDS INDEX BY DOMAIN ={UUID:[LOGIN,EMAIL,psw,accessRight,TOKEN]} - fs.outputJson( `${config.tribes}/${tribeid}/users/searchindex/uids.json`, uids, { - spaces: 2 - }, err => { - if( err ) throw err; - } ); - // LOGINS INDEX BY DOMAIN ={LOGIN:UUID} - fs.outputJson( `${config.tribes}/${tribeid}/users/searchindex/logins.json`, logins, { - spaces: 2 - }, err => { - if( err ) throw err; - } ); - // EMAILS INDEX BY DOMAIN ={EMAIL:UUID} - fs.outputJson( `${config.tribes}/${tribeid}/users/searchindex/emails.json`, emails, { - spaces: 2 - }, err => { - if( err ) throw err; - } ); - } ); - // EMAILS et appartenance domain - fs.outputJson( `${config.tmp}/emailsglob.json`, emailsglob, { - spaces: 2 - }, err => { - if( err ) throw err; - } ); - // logins et appartenance domain (permet de retrouver tribeid pour un LOGIN) - fs.outputJson( `${config.tmp}/loginsglob.json`, loginsglob, { - spaces: 2 - }, err => { - if( err ) throw err; - } ); - // TOKENS GLOBAL INDEX Centralise tous les TOKEN pour plus de rapidité - // {UUID:TOKEN} - fs.outputJson( `${config.tmp}/tokens.json`, tokens, { - spaces: 2 - }, err => { - if( err ) throw err; - } ); - console.groupEnd(); - return { tokens }; -}; -/** - * Update indexes: logins, uids and tokens - * @param {object} user User object - * @param {string} tribeid - The client identifier - * @rm {boolean} false => update, true => remove - */ -Pagans.updateDatabase = ( user, tribeid, rm = false ) => { - console.group( `Pagans.updateDatabase for ${tribeid} with user ${user.LOGIN}` ) - console.assert( config.loglevel == "quiet", 'user', user ); - const loginsIndex = `${config.tribes}/${tribeid}/users/searchindex/logins.json`; - jsonfile.readFile( loginsIndex, function ( err, logins ) { - console.assert( config.loglevel == "quiet", 'logins', logins ); - try { - if( rm ) { - delete logins[ user.LOGIN ]; - } else { - logins[ user.LOGIN ] = user.UUID; - } - jsonfile.writeFile( loginsIndex, logins, { - spaces: 2 - }, err => { - if( err ) logger.info( err ); - } ); - } catch ( err ) { - logger.info( 'Gros pb de mise à jour Pagans.updateDatabase conflit des logins' ); - } - } ); - const uidsIndex = `${config.tribes}/${tribeid}/users/searchindex/uids.json`; - jsonfile.readFile( uidsIndex, function ( err, uids ) { - try { - if( rm ) { - delete uids[ user.UUID ]; - } else { - uids[ user.UUID ] = [ - user.LOGIN, - user.EMAIL, - user.PASSWORD, - user.ACCESSRIGHTS, - user.TOKEN - ]; - } - jsonfile.writeFile( uidsIndex, uids, { - spaces: 2 - }, err => { - if( err ) logger.info( err ); - } ); - } catch ( err ) { - logger.info( 'Gros pb de mise à jour Pagans.updateDatabase conflit des uids si ce reproduit passer en mode sync bloquant' ); - } - } ); - const emailsIndex = `${config.tribes}/${tribeid}/users/searchindex/emails.json`; - jsonfile.readFile( emailsIndex, function ( err, emails ) { - console.assert( config.loglevel == "quiet", 'emailss', emails ); - try { - if( rm ) { - delete emails[ user.EMAIL ]; - } else { - emails[ user.EMAIL ] = user.UUID; - } - jsonfile.writeFile( emailsIndex, emails, { - spaces: 2 - }, err => { - if( err ) logger.info( err ); - } ); - } catch ( err ) { - logger.info( 'Gros pb de mise à jour Pagans.updateDatabase conflit des emails' ); - } - } ); - const tokensIndex = `${config.tmp}/tokens.json`; - let tokens = {}; - try { - tokens = jsonfile.readFileSync( tokensIndex ); - } catch ( err ) { - logger.info( 'tokens.json not available' ) - } - // tokens[user.UUID] = user.TOKEN; - tokens[ user.UUID ] = { TOKEN: user.TOKEN, ACCESSRIGHTS: user.ACCESSRIGHTS }; - jsonfile.writeFileSync( tokensIndex, tokens, { - spaces: 2 - } ); - /* - jsonfile.readFile(tokensIndex, function(err, tokens) { - tokens[user.UUID] = user.TOKEN; - jsonfile.writeFile(tokensIndex, tokens, { spaces: 2 }, err => { - if (err) logger.info(err); - }); - });*/ - console.groupEnd(); -}; -/** - * Read the profil.json of an user - * @param {[type]} UUID ID of the user - * @param {[type]} tribeid tribeid - * @return {Promise} - Return a promise resolved with user data or rejected with an error - */ -// A S U P P R I M E R utiliser getinfousers pour recuperer des indexs de users -// en créer d'autres si necessaire -Pagans.getUserlist = ( header, filter, field ) => { - console.group( `getUserlist filter with filter ${filter} to get ${field}` ); - /* const getuser = Pagans.getUser(header.xuuid, header.xtribeid); - if (getuser.status != 200) - return { status: getuser.status, data: getuser.payload }; - const user = getuser.payload.data; - // logger.info(user); - // check if update accessright allowed - // choose the level depending of ownby xuuid - let accessright = user.objectRights[header.xtribeid].users[0]; - if (user.ownby.includes(header.xtribeid)) { - accessright = user.objectRights[header.xtribeid].users[1]; - } - // Check update is possible at least user itself ownby itself - logger.info(accessright); - logger.info(accessright & 4); - if ((accessright & 4) != 4) { - return { - status: 403, - data: { info: ['forbiddenAccess'], model: 'Pagans' } - }; - } - */ - const Userlist = []; - glob.sync( `${config.tribes}/${header.xworkon}/users/*/profil.json` ) - .forEach( f => { - const infouser = jsonfile.readFileSync( f ); - // Ajouter filter et liste de field - if( filter != 'all' ) { - // decode filter et test - } - const info = {}; - field.split( '______' ) - .forEach( k => { - if( ![ 'password' ].includes( k ) ) info[ k ] = infouser[ k ]; - } ); - Userlist.push( info ); - } ); - // logger.info('userlist', Userlist); - console.groupEnd(); - return { - status: 200, - data: { - data: Userlist - } - }; -}; -Pagans.getinfoPagans = ( tribeid, accessrights, listindex ) => { - const info = {} - const object = 'users'; - const indexs = listindex.split( '_' ) - let access = true; - indexs.forEach( index => { - access = !( [ 'emails', 'logins', 'uids' ].includes( index ) && !( accessrights.data[ object ] && accessrights.data[ object ].includes( 'R' ) ) ); - if( access && fs.existsSync( `${config.tribes}/${tribeid}/${object}/searchindex/${index}.json` ) ) { - info[ index ] = jsonfile.readFileSync( `${config.tribes}/${tribeid}/${object}/searchindex/${index}.json` ) - } - } ) - logger.info( info ) - return { status: 200, data: { info: info } } -} -Pagans.getUser = ( UUID, tribeid, accessrights ) => { - console.assert( config.loglevel == "quiet", `getUser on ${UUID} for ${tribeid} with ${JSON.stringify(accessrights)}` ); - if( !fs.existsSync( `${config.tribes}/${tribeid}/users/${UUID}.json` ) ) { - return { - status: 404, - data: { - info: [ 'useridNotfound' ], - model: 'Pagans', - render: { - UUID, - tribeid - } - } - } - } - const user = jsonfile.readFileSync( `${config.tribes}/${tribeid}/users/${UUID}.json` ); - let access = true; - //logger.info("test accessrights.data['users'].includes('R')", accessrights.data['users'].includes('R')) - console.assert( config.loglevel == "quiet", 'accessrights', accessrights ) - access = accessrights.users && ( accessrights.users.includes( 'R' ) || ( accessrights.users.includes( 'O' ) && user.OWNEDBY.includes( UUID ) ) ); - if( access ) { - return { - status: 200, - data: { - user: user, - model: "User", - info: [ "Authorizedtogetuserinfo" ] - } - }; - } - return { - status: 403, - data: { - info: [ 'Forbidden' ], - model: 'Pagans', - render: { - UUID, - tribeid - } - } - }; -}; -Pagans.getUserIdFromEMAIL = ( tribeid, EMAIL ) => { - if( !checkdata.test.EMAIL( EMAIL ) ) { - return { - status: 400, - data: { - info: [ 'ERREMAIL' ], - model: 'Pagans' - } - }; - } - const emailsIndex = jsonfile.readFileSync( `${config.tribes}/${tribeid}/users/searchindex/emails.json` ); - if( !emailsIndex.hasOwnProperty( EMAIL ) ) { - return { - status: 404, - data: { - info: [ 'userEMAILNotfound' ], - model: 'Pagans' - } - }; - } - return emailsIndex[ EMAIL ]; -}; -Pagans.updateUserpassword = ( UUID, header, data ) => { - const getUser = Pagans.getUser( UUID, header.xtribeid, { users: 'W' } ); - if( getUser.status == 200 ) { - const user = getUser.data.user; - // logger.info('user exist', user); - const match = bcrypt.compareSync( data.password, user.PASSWORD ); - if( !match ) { - return { - status: 401, - data: { - info: [ 'checkCredentials' ], - model: 'Pagans' - } - }; - } - // logger.info('Credentials are matching!'); - if( checkdata.test.password( {}, data.pswnew ) ) { - user.PASSWORD = bcrypt.hashSync( data.pswnew, config.saltRounds ); - jsonfile.writeFileSync( `${config.tribes}/${header.xworkon}/users/${UUID}.json`, user, { - spaces: 2 - } ); - Pagans.updateDatabase( user, header.xworkon, false ); - return { - status: 200, - data: { - info: [ 'successfulUpdate' ], - model: 'Pagans' - } - }; - } else { - return { - status: 401, - data: { - info: [ 'pswTooSimple' ], - model: 'Pagans' - } - }; - } - } -}; -Pagans.createUser = ( header, data ) => { - /* - @input data={PUBKEY,EMAIL,LOGIN,UUID} check and create for header xworkon a user with generic password - */ - logger.info( 'createUser on header.xworkon:' + header.xworkon + ' by user:' + header.xpaganid ); - console.assert( config.loglevel == "quiet", 'with data:', data ); - const ref = jsonfile.readFileSync( `${config.tribes}/${header.xworkon}/referentials/${header.xlang}/object/users.json` ); - const logins = jsonfile.readFileSync( `${config.tribes}/${header.xworkon}/users/searchindex/logins.json` ); - const LOGIN = Object.keys( logins ); - console.assert( config.loglevel == "quiet", 'LOGIN list', LOGIN ); - const emails = jsonfile.readFileSync( `${config.tribes}/${header.xworkon}/users/searchindex/emails.json` ); - console.assert( config.loglevel == "quiet", 'emails', emails ); - const EMAIL = Object.keys( emails ); - console.assert( config.loglevel == "quiet", 'EMAIL list', EMAIL ); - // list.UUID est forcement unique car on est en update et pas en create - if( !data.UUID ) data.UUID = UUID.v4(); - // pour la logique de checkdata il faut passer le parametre - const check = checkdata.evaluate( { - list: { - LOGIN, - EMAIL, - UUID: [] - } - }, ref, data ); - console.assert( config.loglevel == "quiet", 'check & clean data before update ', check ); - if( check.invalidefor.length > 0 ) { - return { - status: 403, - data: { - model: 'Pagans', - info: check.invalidefor - } - }; - } - const clientConfig = jsonfile.readFileSync( `${config.tribes}/${header.xworkon}/clientconf.json` ); - const user = check.data; - user.DATE_CREATE = new Date() - .toISOString(); - user.PASSWORD = bcrypt.hashSync( clientConfig.genericpsw, config.saltRounds ); - user.OWNBY = [ data.UUID ]; - user.OBJECT = 'users'; - // set le minimum de droit sur l'objet users dont il est le Owner - if( data.ACCESSRIGHTS ) { - user.ACCESSRIGHTS = data.ACCESSRIGHTS - } else { - user.ACCESSRIGHTS = { app: {}, data: {} }; - } - user.ACCESSRIGHTS.data[ header.xworkon ] = { users: "O" }; - jsonfile.writeFileSync( `${config.tribes}/${header.xworkon}/users/${user.UUID}.json`, user, { - spaces: 2 - } ); - Pagans.updateDatabase( user, header.xworkon, false ); - return { - status: 200, - data: { - uuid: user.UUID, - info: [ 'successfulCreate' ], - model: 'Pagans' - } - }; -}; -Pagans.updateUser = ( UUID, header, data ) => { - logger.info( 'updateUser UUID:' + UUID + ' on header.xworkon:' + header.xworkon + ' by user' + header.xpaganid ); - // logger.info('header', header); - console.assert( config.loglevel == "quiet", 'with data', data ); - const getuser = Pagans.getUser( UUID, header.xworkon, { users: 'R' } ); - if( getuser.status != 200 ) return { - status: getuser.status, - data: getuser.data.user - }; - const user = getuser.data.user; - /* - let userconnected = user; - if (UUID != header.xuuid) { - // mean connected user want to change other user - const getuserconnected = Pagans.getUser(header.xuuid, header.xtribeid); - userconnected = getuserconnected.payload.data; - } - logger.info('user to update', user); - logger.info('user connected that request update', userconnected); - - // check if update accessright allowed - // choose the level depending of ownby xuuid - let accessright = userconnected.objectRights[header.xworkon].users[0]; - if (user.ownby.includes(header.xuuid)) { - accessright = userconnected.objectRights[header.xworkon].users[1]; - } - // Check update is possible at least user itself ownby itself - logger.info(accessright); - logger.info(accessright & 2); - if ((accessright & 2) != 2) { - return { - status: 403, - data: { info: ['forbiddenAccess'], model: 'Pagans' } - }; - } - */ - const ref = jsonfile.readFileSync( `${config.tribes}/${header.xworkon}/referentials/object/users_${ - header.xlang - }.json` ); - const logins = jsonfile.readFileSync( `${config.tribes}/${header.xworkon}/users/searchindex/logins.json` ); - const LOGIN = Object.keys( logins ) - .filter( l => logins[ l ] != user.UUID ); - // logger.info( 'LOGIN list', LOGIN ); - const emails = jsonfile.readFileSync( `${config.tribes}/${header.xworkon}/users/searchindex/emails.json` ); - // logger.info( 'emails', emails ); - const EMAIL = Object.keys( emails ) - .filter( e => emails[ e ] != user.UUID ); - // logger.info( 'EMAIL list', EMAIL ); - // list.UUID est forcement unique car on est en update et pas en create - // pour la logique de checkdata il faut passer le parametre - const check = checkdata.evaluate( { - profil: user[ 'apps' + header.xworkon + 'profil' ], - list: { - LOGIN, - EMAIL, - UUID: [] - } - }, ref, data ); - if( check.invalidefor.length > 0 ) { - return { - status: 403, - data: { - model: 'Pagans', - info: check.invalidefor, - } - }; - } - data = check.data; - let saveuser = false; - let updateDatabase = false; - Object.keys( data ) - .forEach( k => { - //logger.info( user[ k ] ) - //logger.info( data[ k ] ) - //logger.info( '---' ) - if( user[ k ] != data[ k ] ) { - user[ k ] = data[ k ]; - saveuser = true; - if( [ 'TOKEN', 'LOGIN', 'EMAIL' ].includes( k ) ) updateDatabase = true; - // attention si LOGIN ou EMAIL change il faut checker qu il n existe pas dejà risque de conflit - } - } ); - if( saveuser ) { - //logger.info( 'mise à jour user profile.json' ); - if( data.TOKEN ) { - user.date_lastLOGIN = new Date() - .toISOString(); - } else { - user.date_update = new Date() - .toISOString(); - } - try { - jsonfile.writeFileSync( `${config.tribes}/${header.xworkon}/users/${UUID}.json`, user, { - spaces: 2 - } ); - //logger.info( 'declenche updatabase', updateDatabase ) - if( updateDatabase ) { - // mean index have to be updated - Pagans.updateDatabase( user, header.xworkon, false ); - console.assert( config.loglevel == "quiet", 'MISE A JOUR DU TOKEN ou de l\'EMAIL ou du LOGIN' ); - } - } catch ( err ) { - logger.info( 'ERRRRR need to understand update impossible of user: ' + UUID + ' in domain:' + header.xworkon + ' from user ' + header.xpaganid + ' of domain:' + header.xtribe ); - logger.info( 'with data :', data ); - return { - status: 400, - data: { - info: [ 'failtoWritefs' ], - model: 'Pagans' - } - }; - } - } - return { - status: 200, - data: { - info: [ 'successfulUpdate' ], - model: 'Pagans' - } - }; -}; -Pagans.deleteUser = ( UUID, header ) => { - // Delete remove from users object UUID and update index - // Activity is not deleted => means some activity can concern an UUID that does not exist anymore. - // update index - const infouser = jsonfile.readFileSync( `${config.tribes}/${header.xworkon}/users/${UUID}.json` ); - Pagans.updateDatabase( infouser, header.xworkon, true ); - fs.removeSync( `${config.tribes}/${header.xworkon}/users/${UUID}.json` ); - return { - status: 200, - data: { - info: [ 'successfulDelete' ], - modedl: 'Pagans' - } - }; -}; -/* -@header { xtribeid: client domain name data - A VERIFIER inutile ,xworkon: client domain name where user is store and where data are stored - ,xuuid: 1 if unknown else if user id auhtneticated - ,xlanguage: langue used fr en return referential in this lang - ,xauth: TOKEN valid for 24h'} - workon=xtribeid in an app client usage - in case of xtribeid=mymaidigit, - if workon==mymaildigit => admin role on any xworkon - else adlin role only in xworkon specified -@body {LOGIN: password:} -return {status:200, data:{data:{TOKEN,UUID}}} -return {status:401,data:{info:[code list], model: referential}} -*/ -Pagans.loginUser = ( header, body, checkpsw ) => { - // On recupere tribeid du LOGIN - // ATTENTION xworkon peut être different du user xtribeid - //(cas d'un user qui a des droits sur un autre domain et qui travail sur cet autre domain) - // les function Pagans utilise le domain de travail xWorkon - // il faut donc modifier le header au moment du LOGIN - // pour que l'update du user au moment du LOGIN concerne bien le bon domain - header.xworkon = header.xtribe - const LOGINdom = jsonfile.readFileSync( `${config.tmp}/loginsglob.json` ); - console.assert( config.loglevel == "quiet", LOGINdom ) - console.assert( config.loglevel == "quiet", body ) - if( !LOGINdom[ body.LOGIN ] ) { - return { - status: 401, - data: { info: [ 'LoginDoesNotExist' ], model: 'Pagans' } - }; - } - const logins = jsonfile.readFileSync( `${config.tribes}/${LOGINdom[body.LOGIN]}/users/searchindex/logins.json` ); - if( !Object.keys( logins ) - .includes( body.LOGIN ) ) { - return { - status: 401, - data: { - info: [ 'LOGINDoesNotExist' ], - model: 'Pagans', - moreinfo: `Le login ${body.LOGIN} does not exist for tribeid ${LOGINdom[body.LOGIN]}` - } - }; - } - // Load user - const uid = logins[ body.LOGIN ]; - const getUser = Pagans.getUser( uid, LOGINdom[ body.LOGIN ], { users: 'R' } ); - logger.info( 'getPagans', getUser ) - if( getUser.status != 200 ) { - return { status: 200, data: { model: 'Pagans', user: getUser.data.user } }; - } - const user = getUser.data.user; - logger.info( 'user', user ) - if( checkpsw ) { - const match = bcrypt.compareSync( body.PASSWORD, user.PASSWORD ); - if( !match ) { - return { - status: 401, - data: { - info: [ 'checkCredentials' ], - model: 'Pagans' - } - }; - } - } - // Mise à jour user pour app LOGIN - user.tribeid = LOGINdom[ body.LOGIN ] - user.TOKEN = jwt.encode( { - expiration: moment() - .add( 1, 'day' ), - UUID: user.UUID - }, config.jwtSecret ); - // on met à jour le header qui authentifie le user connecte - header.xtribe = LOGINdom[ body.LOGIN ] - header.xpaganid = user.UUID; - header.xauth = user.TOKEN; - // On modifie xworkon car au LOGIN on est forcemenet identifiable sur tribeid - // xworkon est utiliser pour travailler sur un environnement client different de celui - // de l'appartenace du user - header.xworkon = LOGINdom[ body.LOGIN ]; - const majuser = Pagans.updateUser( user.UUID, header, { - UUID: user.UUID, - TOKEN: user.TOKEN - } ); - // Enleve info confidentiel - delete user.PASSWORD; - if( user.ACCESSRIGHTS.data[ "Alltribeid" ] ) { - //cas admin on transforme les droits sur tous les tribeid existant - const newaccessrightsdata = {} - jsonfile.readFileSync( `${config.tribes}/tribeids.json` ) - .forEach( cid => { - newaccessrightsdata[ cid ] = user.ACCESSRIGHTS.data[ "Alltribeid" ] - } ) - user.ACCESSRIGHTS.data = newaccessrightsdata; - } - // on recupere le menu de l app qui demande le LOGIN si existe dans user.ACCESSRIGHTS.app[] - // header['X-app'] = tribeid:Projet pour récuperer le menu correspondant - console.assert( config.loglevel == "quiet", "header.xapp", header.xapp ) - console.assert( config.loglevel == "quiet", "user.ACCESSRIGHTS.app[header.xapp]", user.ACCESSRIGHTS.app[ header.xapp ] ); - - return { - status: 200, - data: { - model: "Pagans", - info: [ 'loginSuccess' ], - user: user - } - }; -}; -Pagans.getlinkwithoutpsw = async ( EMAIL, header ) => { - // check le domain d'appartenance de l'eamail dans /tribes/emailsglob.json={email:cleintId} - // on remplace le header.xtribeid - const domforemail = jsonfile.readFileSync( `${config.tribes}/emailsglob.json`, 'utf-8' ); - if( domforemail[ EMAIL ] ) { - header.xtribe = domforemail[ EMAIL ] - } else { - return { status: 404, info: { model: 'Pagans', info: [ 'emailnotfound' ], moreinfo: "email does not exist in /emailsglob.json" } }; - } - // recupere le uuid du user dans /tribes/tribeid/users/searchindex/emails.json - // puis l'ensemble des info des user du domain /uuids.json - // infoforuuid[uuidforemail[EMAIL]] permet de récupérer toutes info du user, droit, etc... - const uuidforemail = jsonfile.readFileSync( `${config.tribes}/${header.xtribe}/users/searchindex/emails.json`, 'utf8' ); - const infoforuuid = jsonfile.readFileSync( `${config.tribes}/${header.xtribe}/users/searchindex/uids.json`, 'utf8' ); - // On recupere le modele d'email appemailinfo qui doit être présent dans clientconf.json - let confdom = jsonfile.readFileSync( `${config.tribes}/${header.xtribe}/clientconf.json`, 'utf8' ); - let checkinfomail = ""; - if( !confdom.appemailinfo ) { - checkinfomail += ' Erreur de clientconfig il manque un objet appemailinfo pour poursuivre'; - } - if( checkinfomail != "" ) { - logger.info( `Pb de config pour ${header.xtribe} ${checkinfomail} ` ) - return { - status: 500, - info: { - model: 'Pagans', - info: [ 'objectmissingclientconf' ], - moreinfo: checkinfomail - } - }; - } - let simulelogin; - try { - simulelogin = await Pagans.loginUser( header, { - LOGIN: infoforuuid[ uuidforemail[ EMAIL ] ][ 0 ], - PASSWORD: "" - }, false ); - logger.info( 'info simulelogin', simulelogin ) - } catch ( err ) { - return { - status: 501, - info: { - model: 'Pagans', - info: [ 'loginImpossible' ], - moreinfo: "Impossible de se loger avec " + infoforuuid[ uuidforemail[ EMAIL ] ][ 0 ] - } - }; - } - const url = `${config.rootURL}?xauth=${simulelogin.data.TOKEN}&xuuid=${simulelogin.data.UUID}&xtribeid=${simulelogin.data.tribeid}&xworkOn=${header.xworkon}&xlang=${header.xlang}` - //logger.info('envoi email avec' + url) - confdom.appemailinfo.msg.destperso = [ {} ]; - confdom.appemailinfo.msg.destperso[ 0 ].email = EMAIL; - confdom.appemailinfo.msg.destperso[ 0 ].subject = "Lien de réinitialisation valable 1h" - confdom.appemailinfo.msg.destperso[ 0 ].titre = "Vous avez oublier votre mot de passe" - confdom.appemailinfo.msg.destperso[ 0 ].texte = ` -

- Bonjour,
Vous nous avez signalé que vous avez oublié votre mot de passe pour cette email. - Avec le lien suivant vous allez pouvoir utiliser votre interface 1h maximum. - Clicker ICI.
- Nous vous conseillons de changer votre mot de passe.

- ` - //logger.info('envoi header :', header); - Outputs.sendMailcampain( confdom.appemailinfo.msg, header ); - logger.info( confdom.appemailinfo ); - return { - status: 200, - info: { - model: 'Pagans', - info: [ 'emailsentforReinit' ], - moreinfo: 'EMAIL sent with unique link ' + url - } - }; -} -module.exports = Pagans; diff --git a/models/Referentials.js b/models/Referentials.js deleted file mode 100755 index 091dd3a..0000000 --- a/models/Referentials.js +++ /dev/null @@ -1,416 +0,0 @@ -const glob = require( 'glob' ); -const path = require( 'path' ); -const fs = require( 'fs-extra' ); -const config = require( '../tribes/townconf.js' ); - -const Referentials = {}; -/* -Manage Referential object data - -each object is compose of a list of fields -each fields have it owns structur and check -those common rules allow to be used to manage: -- forms (creation to collect data) -- data check -- data access rights -common referential data stored in /data/shared/referential/ - -*/ -Referentials.clientconf = ( xworkOn, listkey ) => { - /* - Retourne les info d'un clientconf.json sur une liste de [cle] - */ - let conf = {}; - let dataconf = {}; - //logger.info( `${config.tribes}/${xworkOn}/clientconf.json` ) - try { - conf = fs.readJsonSync( `${config.tribes}/${xworkOn}/clientconf.json` ); - // remove information notrelevant for - [ 'emailFrom', 'emailClient', 'emailCc', 'commentkey', 'clezoomprivate', 'stripekeyprivate', 'genericpsw' ].forEach( c => { - delete conf[ c ]; - } ); - listkey.forEach( k => dataconf[ k ] = conf[ k ] ) - //logger.info( 'dataconf', dataconf ) - } catch ( err ) { - logger.info( 'Attention demande sur clienId inconnu ' + xworkOn ); - } - return { - status: 200, - payload: { - data: dataconf - } - }; -}; -Referentials.clientconfglob = () => ( { - status: 200, - payload: { - data: fs.readJsonSync( `${config.tmp}/clientconfglob.json` ) - } -} ); -Referentials.getref = ( origin, source, ref, xworkOn, xlang ) => { - // If request origin then send back referential with all language in it - // if not origin or json source return by language - let referent = {}; - let src; - if( origin && [ 'object', 'data' ].includes( source ) ) { - src = `${config.tribes}/${xworkOn}/referentials/${source}/${ref}.json` - } else { - src = `${config.tribes}/${xworkOn}/referentials/${source}/${ref}_${xlang}.json`; - } - //logger.info( src ) - try { - referent = fs.readJsonSync( src ); - } catch ( err ) { - logger.info( `Request ${src} does not exist ` ); - } - return { - status: 200, - payload: { - data: referent - } - }; -}; -Referentials.putref = ( source, name, xworkOn, data ) => { - /* - We get a referential, we have 3 kinds of sources: - * data = [{uuid,DESC:{fr:,en,},DESCLONG:{fr:,en:}, other field}] - only DESC and DESCLONG have a translation - * json = are full complex object in language name_lg.json - * object = [{uuid,DESC:{fr,en},DESCLONG:{fr,en}},tpl,}] - Difference between data and object is that object defines rule to manage an object, and how to create a forms to get data each data is saved in one folder object/uuid.json and have to respect the corresponding object referentials definition. - - For data and object it is possible only to put a file with all language available. - When store this script erase with the new file per _lg - - name for source=json must end by _lg - */ - //logger.info( data ) - const pat = /.*_..\.json$/; - const file = `${config.tribes}/${xworkOn}/referentials/${source}/${name}.json` - if( [ 'object', 'data' ].includes( source ) ) { - if( pat.test( name ) ) { - return { status: 404, payload: { model: 'Referentials', info: [ 'nameunconsistent' ], moreinfo: "can not be update with one lang need a full file with language for object or data" } } - } else { - fs.outputJsonSync( file, data ); - return Refernetials.update( xworkOn, source, name ) - } - } else { - if( !pat.test( name ) ) { - return { status: 404, payload: { model: 'Referentials', info: [ 'nameunconsistent' ], moreinfo: "can not be update without a lang _lg.json a referential json" } } - } else { - fs.outputJsonSync( file, data ); - return { status: 200, payload: { model: 'Referentials', info: [ 'successfull' ], moreinfo: "ref json updated " } } - } - }; -}; -Referentials.updatefull = ( tribeid ) => { - let err = ""; - let nbrefupdate = 0; - const pat = /.*_..\.json$/; - [ 'object', 'data' ].forEach( o => { - glob.sync( `${config.tribes}/${tribeid}/referentials/${o}/*.json` ) - .forEach( f => { - if( !pat.test( f ) ) { - const res = Referentials.update( tribeid, o, path.basename( f, '.json' ) ); - if( res.status != 200 ) { - err += `Error on ${o}/${path.basename(f)}` - } else { - nbrefupdate += 1; - } - } - } ) - } ); - if( err != "" ) { - return { status: 500, payload: { info: [ 'Errupdateref' ], model: "Referentials", moreinfo: err } } - } - return { status: 200, payload: { info: [ 'Success' ], model: "Referentials", moreinfo: `Number of object and data ref updated: ${nbrefupdate}` } } -}; - -Referentials.inittribeid = () => { - logger.info( "Clientconf list for this server", `${config.tribes}/**/clientconf.json` ); - const TribesGlobalConfig = glob.sync( `${config.tribes}/**/clientconf.json` ) - .map( f => fs.readJsonSync( f ) ); - // store global conf for sharing to other api - fs.outputJsonSync( `${config.tmp}/clientconfglob.json`, TribesGlobalConfig, { - spaces: 2 - } ); - return { status: 200, payload: { moreinfo: TribesGlobalConfig } } -} -Referentials.generetribeids = () => { - const tribeids = []; - fs.readJsonSync( `${config.tmp}/clientconfglob.json` ) - .forEach( c => { - if( !tribeids.includes( c.tribeid ) ) tribeids.push( c.tribeid ); - } ); - fs.outputJsonSync( `${config.tmp}/tribeids.json`, tribeids ); - logger.info( `update ${config.tribes}/tribeids` ); - return tribeids; -} -Referentials.genereallowedDOM = () => { - const confglob = fs.readJsonSync( `${config.tmp}/clientconfglob.json` ); - let allDom = []; - confglob.forEach( c => { - c.allowedDOMs.forEach( d => { - if( !allDom.includes( d ) ) allDom = allDom.concat( d ); - } ) - } ); - return allDom; -}; -/* A voir si encore necessaire pour générer un environnement identique - sur un autre server - - // Génére les domaines s'ils n'existe pas dans le repertoire - function genereEnvClient() { - const confglob = fs.readJsonSync( - `${config.sharedData}/clientconfglob.json` - ); - confglob.forEach(function(c) { - config.tribeidsConf[c.tribeid] = c; - if (c.allowedURLs) { - c.allowedURLs.forEach(u => { - if (!config.allowedURLs.includes(u)) { - config.allowedURLs.push(u); - } - }); - } else { - logger.info('erreur de fichier config d\'un site pour ', c); - } - // GLOBAL Tribes IDS INDEX - maketribeidsIndex(); - if (!fs.existsSync(`${config.tribes}/${c.tribeid}`)) { - const execSync = require('child_process').execSync; - execSync(`cp -r ${config.tribes}/modele ${config.tribes}/${c.tribeid}`); - } - }); - } - - - - */ -Referentials.update = ( tribeid, source, name ) => { - /* - Replace for each language the referential name for a tribeid - After each update the version number is incremented by 1 in clientconf.json - */ - if( !fs.existsSync( `${config.tribes}/${tribeid}/referentials/${source}/${name}.json` ) ) { - return { status: 500, payload: { info: [ "unknownRef" ], model: "Referentials", moreinfo: `file does not exist ${config.tribes}/${tribeid}/referentials/${source}/${name}.json` } } - }; - - const clientconf = fs.readJsonSync( `${config.tribes}/${tribeid}/clientconf.json` ); - if( !clientconf.langueReferential ) { - return { status: 500, payload: { info: [ "missingConf" ], model: "Referentials", moreinfo: ` ${config.tribes}/${tribeid}/clientconf.json does not contain langueReferential array` } } - } - const ref = fs.readJsonSync( `${config.tribes}/${tribeid}/referentials/${source}/${name}.json` ); - - clientconf.langueReferential.forEach( lg => { - //manage translation - let refnew = []; - - refnew = []; - ref.forEach( d => { - if( d.DESC ) d.DESC = d.DESC[ lg ]; - if( d.DESCLONG ) d.DESCLONG = d.DESCLONG[ lg ]; - if( d.INFO ) d.INFO = d.INFO[ lg ]; - if( d.desc ) d.desc = d.desc[ lg ]; - if( d.desclong ) d.desclong = d.desclong[ lg ]; - if( d.info ) d.info = d.info[ lg ]; - if( d.placeholder ) d.placeholder = d.placeholder[ lg ]; - refnew.push( d ) - } ) - //save new ref in language - //logger.info( "New ref", refnew ) - logger.info( `Update referentials per lg ${config.tribes}/${tribeid}/referentials/${source}/${name}_${lg}.json` ) - fs.outputJsonSync( `${config.tribes}/${tribeid}/referentials/${source}/${name}_${lg}.json`, refnew, { - spaces: 2 - } ); - } ); - //upgrade version number - if( !clientconf.referentials ) clientconf.referentials = {}; - if( !clientconf.referentials[ source ] ) clientconf.referentials[ source ] = {}; - if( !clientconf.referentials[ source ][ name ] ) clientconf.referentials[ source ][ name ] = { version: 0 }; - clientconf.referentials[ source ][ name ].version += 1; - fs.outputJsonSync( `${config.tribes}/${tribeid}/clientconf.json`, clientconf, 'utf8' ); - return { - status: 200, - payload: { - info: [ 'successUpdate' ], - model: "Referentials", - moreinfo: `${name} updated` - } - } -}; -//logger.info( Referentials.update( 'apixtribe', "object", "user" ) ) - -Referentials.genereobjet = ( tribeid, destination, tplmustache, objet, filtre ) => { - /* @TODO - Genere des objets d'agregat - @tribeid = data/tribee/ identifiant client - @destinations = [] of destination - @tplmustache = fichier mustache de mise en page - @objet = nom d'objet contact, companies, items, users - @filtre = fonction a executer - */ -} - -//////// EN DESSOUS DE CETTE LIGNE A SUPPRIMER - -/* -Le principe consistait à partager des referentiels dans shareddataLa gestion est trop compliqué => le principe chaque client duplique un referentiel pour que les app qui s'appuie sur des composants communs puissent fonctionner - -*/ - -/*Referentials.genereClientObjectASUPP = () => { - const confglob = fs.readJsonSync( `${config.tmp}/clientconfglob.json` ); - // Check and update folder and data per lang - // c as tribeid - confglob.forEach( ( c, postribeid ) => { - //check folder are well create - const lstfolder = [ 'actions', 'actions/done', 'actions/todo', 'cards', 'logs', 'orders', 'orders/reservation', 'orders/purchase', 'orders/contact', 'public', 'public/reservation', 'tags', 'tags/stats', 'tags/archives', 'tags/hits', 'tags/imgtg', 'users' ]; - lstfolder.forEach( fol => { - if( !fs.existsSync( `${config.tribes}/${c.tribeid}/${fol}` ) ) { - fs.mkdirSync( `${config.tribes}/${c.tribeid}/${fol}` ); - } - } ) - if( c.referentials && !c.langue ) { logger.info( `ERREUR referentials mais pas de langue:[] pour ${c.tribeid}/clientconf.json` ) } - if( c.referentials && c.langue ) { - let majclientconf = false; - // Create and check Object structure - Object.keys( c.referentials.object ) - .forEach( o => { - // if object exist in shared then it merge sharedObject and domain referential object - let objfull = []; - const objshared = `${config.sharedData}/referentials/dataManagement/object/${o}.json`; - if( fs.existsSync( objshared ) ) { - objfull = objfull.concat( fs.readJsonSync( objshared ) ); - } - const objdomain = `${config.tribes}/${c.tribeid}/referentials/dataManagement/object/${o}.json`; - if( fs.existsSync( objdomain ) ) { - objfull = objfull.concat( fs.readJsonSync( objdomain ) ); - } - c.langue.forEach( lg => { - const objfulllg = objfull.map( field => { - if( field.DESC ) field.DESC = field.DESC[ lg ]; - if( field.DESCLONG ) field.DESCLONG = field.DESCLONG[ lg ]; - return field; - } ); - const objectdomlg = `${config.tribes}/${c.tribeid}/referentials/${lg}/object/${o}.json`; - let savedObject = {}; - if( fs.existsSync( objectdomlg ) ) { - savedObject = fs.readJsonSync( objectdomlg ); - } - // TODO Always true change later to update only if needded - if( !fs.existsSync( objectdomlg ) || objfulllg.length !== savedObject.length || 1 == 1 ) { - fs.outputJsonSync( objectdomlg, objfulllg, { - spaces: 2 - } ); - confglob[ postribeid ].referentials.object[ o ].version += 1; - majclientconf = true; - } - } ); - } ); - // datafile - Object.keys( c.referentials.data ) - .forEach( d => { - // if object exist in shared then it merge sharedObject and domain referential object - // logger.info(c.tribeid + '--' + d); - let datafull = []; - const datashared = `${ - config.sharedData - }/referentials/dataManagement/data/${d}.json`; - if( fs.existsSync( datashared ) ) { - datafull = datafull.concat( fs.readJsonSync( datashared ) ); - } - const datadomain = `${config.tribes}/${ - c.tribeid - }/referentials/dataManagement/data/${d}.json`; - if( fs.existsSync( datadomain ) ) { - datafull = datafull.concat( fs.readJsonSync( datadomain ) ); - } - /* const defdata = `${config.tribes}/${ - c.tribeid - }/referentials/dataManagement/data/${d}.json`; - */ -// for each Langues => generate fr.obj and compare it with existing file -// if diff then => upgrade version number in clientconf -// logger.info(datafull); -// this could be improved by usind d.meta wich is the object that DESCribe this data -/* c.langue.forEach( lg => { - let meta; - if( c.referentials.data[ d ].meta ) { - meta = fs.readJsonSync( `${config.tribes}/${c.tribeid}/referentials/${lg}/object/${ - c.referentials.data[d].meta - }.json` ); - } - let datalg; - const datafulllg = datafull.map( tup => { - datalg = {}; - meta.forEach( ch => { - if( tup[ ch.idfield ] ) { - if( ch.multilangue ) { - datalg[ ch.idfield ] = tup[ ch.idfield ][ lg ]; - } else { - datalg[ ch.idfield ] = tup[ ch.idfield ]; - } - } - } ); - return datalg; - } ); - // lit le fichier correspondant et le compare si différent le sauvegarde - // stocke l'information d'upgrade d ela version - const datadomlg = `${config.tribes}/${ - c.tribeid - }/referentials/${lg}/data/${d}.json`; - let saveddata = {}; - if( fs.existsSync( datadomlg ) ) { - saveddata = fs.readJsonSync( datadomlg ); - } - // Condition to improve - // TODO always change file to improvelater by detecting real change. - if( !fs.existsSync( datadomlg ) || datafulllg.length != saveddata.length || 1 == 1 ) { - fs.outputJsonSync( datadomlg, datafulllg, { - spaces: 2 - } ); - confglob[ postribeid ].referentials.data[ d ].version += 1; - majclientconf = true; - } - } ); - } ); - // json file that have to start with lg {lg:'':{json }} - Object.keys( c.referentials.json ) - .forEach( j => { - // if object exist in shared then it merge sharedObject and domain referential object - // logger.info(c.tribeid + '--' + d); - let jsonfull = []; - const jsondomain = `${config.tribes}/${c.tribeid}/referentials/dataManagement/json/${j}.json`; - if( fs.existsSync( jsondomain ) ) { - jsonfull = fs.readJsonSync( jsondomain ); - } - c.langue.forEach( lg => { - const jsondomlg = `${config.tribes}/${ - c.tribeid - }/referentials/${lg}/json/${j}.json`; - // logger.info('jsondomlg', jsondomlg); - let datalg = jsonfull; - if( jsonfull[ lg ] ) { - datalg = jsonfull[ lg ]; - } - fs.outputJsonSync( jsondomlg, datalg, { - spaces: 2 - } ); - } ); - } ); - // update clientconf domain with updated version - if( majclientconf ) { - fs.outputJsonSync( `${config.tribes}/${c.tribeid}/clientconf.json`, c, { - spaces: 2 - } ); - } - } - } ); - // update global conf - fs.outputJsonSync( `${config.tmp}/clientconfglob.json`, confglob, { - spaces: 2 - } ); -};*/ - -module.exports = Referentials; diff --git a/models/Referentialssave.js b/models/Referentialssave.js deleted file mode 100755 index a50981d..0000000 --- a/models/Referentialssave.js +++ /dev/null @@ -1,220 +0,0 @@ -const glob = require( 'glob' ); -const path = require( 'path' ); -const fs = require( 'fs-extra' ); -// Check if package is installed or not to pickup the right config file -const config = require( '../tribes/townconf.js' ); - -const Referentials = {}; -/* -Manage Referential object data - -each object is compose of a list of fields -each fields have it owns structur and check -those common rules allow to be used to manage: -- forms (creation to collect data) -- data check -- data access rights -common referential data stored in /data/shared/referential/ - -*/ -Referentials.clientconf = ( xworkOn, listkey ) => { - /* - Retourne les info d'un clientconf.json sur une liste de [cle] - */ - let conf = {}; - let dataconf = {}; - logger.info( `${config.tribes}/${xworkOn}/clientconf.json` ) - try { - conf = fs.readJsonSync( `${config.tribes}/${xworkOn}/clientconf.json` ); - // remove information notrelevant for - [ 'emailFrom', 'emailClient', 'emailCc', 'commentkey', 'clezoomprivate', 'stripekeyprivate', 'genericpsw' ].forEach( c => { - delete conf[ c ]; - } ); - listkey.forEach( k => dataconf[ k ] = conf[ k ] ) - logger.info( 'dataconf', dataconf ) - } catch ( err ) { - logger.info( 'Attention demande sur clienId inconnu ' + xworkOn ); - } - return { - status: 200, - payload: { - data: dataconf - } - }; -}; -Referentials.clientconfglob = () => ( { - status: 200, - payload: { - data: fs.readJsonSync( `${config.tmp}/clientconfglob.json` ) - } -} ); - -Referentials.inittribeid = () => { - logger.info( "Clientconf list for this server", `${config.tribes}/**/clientconf.json` ); - const TribesGlobalConfig = glob.sync( `${config.tribes}/**/clientconf.json` ) - .map( f => fs.readJsonSync( f ) ); - // store global conf for sharing to other api - fs.outputJsonSync( `${config.tmp}/clientconfglob.json`, TribesGlobalConfig, { - spaces: 2 - } ); - return { status: 200, payload: { moreinfo: TribesGlobalConfig } } -} - - -Referentials.generetribeids = () => { - const tribeids = []; - fs.readJsonSync( `${config.tmp}/clientconfglob.json` ) - .forEach( c => { - if( !tribeids.includes( c.tribeid ) ) tribeids.push( c.tribeid ); - } ); - fs.outputJsonSync( `${config.tmp}/tribeids.json`, tribeids ); - logger.info( `update ${config.tribes}/tribeids` ); - return tribeids; -} -Referentials.genereallowedDOM = () => { - const confglob = fs.readJsonSync( `${config.tmp}/clientconfglob.json` ); - let allDom = []; - confglob.forEach( c => { - c.allowedDOMs.forEach( d => { - if( !allDom.includes( d ) ) allDom = allDom.concat( d ); - } ) - } ); - return allDom; -}; - - -Referentials.getref = ( source, ref, xworkOn, xlang, singlelang = true ) => { - let referent = {}; - let src = `${config.tribes}/${xworkOn}/referentials/${xlang}/${source}/${ref}.json`; - if( !singlelang ) { - //request full referential to manage - src = `${config.tribes}/${xworkOn}/referentials/dataManagement/${source}/${ref}.json` - } - logger.info( src ) - try { - referent = fs.readJsonSync( src ); - } catch ( err ) { - logger.info( `Attention demande de referentiel inexistant pour ${src} ` ); - } - return { - status: 200, - payload: { - data: referent - } - }; -}; -Referentials.putref = ( source, name, xworkOn, data ) => { - /* - We get a referential, we have 3 kinds of sources: - * data = [{uuid,desc:{fr:,en,},desclong:{fr:,en:}, other field}] - only desc and desclong have a translation - * json = {"fr":{},"en":{}, ...} are full complex object in language - * object = [{uuid,desc:{fr,en},desclong:{fr,en}},tpl,}] - Difference between data and object is that object defines rule to manage an object, and how to create a forms to get data each data is saved in one folder object/uuid.json and have to respect the corresponding object referentials definition. - - */ - logger.info( data ) - // Create a backup of the day hour if exist - const file = `${config.tribes}/${xworkOn}/referentials/dataManagement/${source}/${name}.json` - - if( fs.existsSync( file ) ) { - //backup change done per hour - const origin = fs.readJsonSync( file, 'utf-8' ) - fs.outputJsonSync( `${config.tribes}/${xworkOn}/referentials/dataManagementBackup/${source}/${name}${moment().format('YYYYMMDDHHmm')}.json`, origin, { spaces: 2 } ) - } else { - logger.info( `Referential ${name}.json does not exist this created it` ) - } - logger.info( 'ref backup before update', name ); - fs.outputJsonSync( file, data, { spaces: 2 } ); - // update/create new referential and new version - return Referentials.update( xworkOn, source, name ); -}; -Referentials.updatefull = ( tribeid ) => { - // source json are only per lg so no full update for json - let err = ""; - [ 'object', 'data' ].forEach( o => { - glob.sync( `${config.tribes}/${tribeid}/referentials/dataManagement/${o}/*.json` ) - .forEach( f => { - if( finipaspar_lg ) { - const res = Referentials.update( tribeid, o, path.basename( f, '.json' ) ); - if( res.status != 200 ) { - err += `Error on ${o}/${path.basename(f)}` - } - } - } ) - } ); - if( err != "" ) { - return { status: 500, payload: { info: [ 'Errupdateref' ], model: "Referentials", moreinfo: err } } - } - return { status: 200, payload: { info: [ 'Success' ], model: "Referentials" } } -}; - -Referentials.update = ( tribeid, source, name ) => { - /* - Replace for each language the referential name for a tribeid - After each update the version number is incremented by 1 in clientconf.json - */ - if( !fs.existsSync( `${config.tribes}/${tribeid}/referentials/${source}/${name}.json` ) ) { - return { status: 500, payload: { info: [ "unknownRef" ], model: "Referentials", moreinfo: `file does not exist ${config.tribes}/${tribeid}/referentials/${source}/${name}.json` } } - }; - - const clientconf = fs.readJsonSync( `${config.tribes}/${tribeid}/clientconf.json` ); - if( !clientconf.langueReferential ) { - return { status: 500, payload: { info: [ "missingConf" ], model: "Referentials", moreinfo: ` ${config.tribes}/${tribeid}/clientconf.json does not contain langueReferential array` } } - } - const ref = fs.readJsonSync( `${config.tribes}/${tribeid}/referentials/${source}/${name}.json` ); - - clientconf.langueReferential.forEach( lg => { - /*if( !fs.existsSync( `${config.tribes}/${tribeid}/referentials/${lg}` ) ) { - [ '', '/data', '/json', '/object' ].forEach( p => { - fs.mkdirSync( `${config.tribes}/${tribeid}/referentials/${lg}${p}` ); - } ) - } - */ - //manage translation - let refnew = []; - if( source == 'json' ) { - refnew = ref[ lg ] - } else { - refnew = []; - ref.forEach( d => { - if( d.desc ) d.desc = d.desc[ lg ]; - if( d.desclong ) d.desclong = d.desclong[ lg ]; - if( d.info ) d.info = d.info[ lg ]; - if( d.placeholder ) d.placeholder = d.placeholder[ lg ]; - refnew.push( d ) - } ) - } - //save new ref in language - logger.info( "testtttt", refnew ) - logger.info( `${config.tribes}/${tribeid}/referentials/${source}/${name}_${lg}.json` ) - fs.outputJsonSync( `${config.tribes}/${tribeid}/referentials/${source}/${name}_${lg}.json`, refnew, { - spaces: 2 - } ); - } ); - //upgrade version number - if( !clientconf.referentials[ source ][ name ] ) clientconf.referentials[ source ][ name ] = { version: 0 }; - clientconf.referentials[ source ][ name ].version += 1; - return { - status: 200, - payload: { - info: [ 'successUpdate' ], - model: "Referentials", - moreinfo: `${name} updated` - } - } -}; -//logger.info( Referentials.update( 'apixtribe', "object", "user" ) ) - -Referentials.genereobjet = ( tribeid, destination, tplmustache, objet, filtre ) => { - /* @TODO - Genere des objets d'agregat - @tribeid = data/tribee/ identifiant client - @destinations = [] of destination - @tplmustache = fichier mustache de mise en page - @objet = nom d'objet contact, companies, items, users - @filtre = fonction a executer - */ -} - -module.exports = Referentials; diff --git a/models/Tags.js b/models/Tags.js deleted file mode 100755 index 8084c50..0000000 --- a/models/Tags.js +++ /dev/null @@ -1,229 +0,0 @@ -const fs = require( 'fs' ); -const formidable = require( 'formidable' ); -const jsonfile = require( 'jsonfile' ); -const path = require( 'path' ); -const glob = require( 'glob' ); -const mustache = require( 'mustache' ); -const moment = require( 'moment' ); -// Check if package is installed or not to pickup the right config file -const config = require( '../tribes/townconf.js' ); - - -const Tags = {}; -/* -Keyword definition: - -id: b64 encoded field that can be : email , uuid -tribeid: apiamaildigit client Id, (a folder /tribes/tribeid have to exist) -email: identifiant of a person -uuid: identifiant o - contact database -operationId: code name of an operation -messageId: code name of an templatesource have to exist in /datashared/templatesource/generic/messageId - -*/ -/* -Manage tag data collection -Popup survey manager -*/ -Tags.info = ( data, req ) => { - //logger.info('headers:', req.headers) - /*logger.info('hostname', req.hostname) - logger.info('req.ip', req.ip) - logger.info('req.ips', req.ips) - logger.info('req key', Object.keys(req)) - */ - //logger.info('req.rawHeaders', req.body) - data.useragent = `${req.headers['user-agent']}__${req.headers['accept-language']}__${req.headers['accept-encoding']}__${req.headers['connection']}`; - data.ips = req.ips; - data.ip = req.ip; - data.proxyip = req.connection.remoteAddress; - data.cookie = "" - Object.keys( req.headers ) - .forEach( k => { - if( ![ 'user-agent', 'accept-language', 'accept-encoding', 'connection' ].includes( k ) ) { - data.cookie += `${k}__${req.headers['cookie']}|` - } - } ) - //data.cookie = `${req.headers['cookie']}__${req.headers['upgrade-insecure-requests']}__${req.headers['if-modified-since']}__${req.headers['if-no-match']}__${req.headers['cache-control']}`; - return data -} -Tags.getfile = ( filename, req ) => { - const infotg = filename.split( '__' ); - if( infotg.length < 3 && !fs.existsSync( `${config.tribes}/${infotg[1]}` ) ) { - return { - status: 400, - payload: { info: [ 'fileUnknown' ], model: 'UploadFiles' } - } - } - if( infotg[ 0 ] == "imgtg" ) { - jsonfile.writeFile( `${config.tribes}/${infotg[1]}/tags/imgtg/${Date.now()}.json`, Tags.info( { filename: filename, messageId: infotg[ 2 ], operationId: infotg[ 3 ], identifiant: infotg[ 4 ] }, req ), function ( err ) { - if( err ) { - logger.info( `Erreur de sauvegarde de tag:${filename}` ) - } - } ); - return { - status: 200, - payload: { moreinfo: "Declenche tag", filename: `${config.mainDir}/public/imgtg.png` } - } - } - return { status: 404, payload: {} } -} -Tags.savehits = ( req ) => { - if( !fs.existsSync( `${config.tribes}/${req.params.tribeid}` ) ) { - logger.info( `Erreur d'envoi de tag sur ${req.params.tribeid} pour ${req.params.r}` ); - return false; - } else { - const info = JSON.parse( JSON.stringify( req.body ) ); - jsonfile.writeFile( `${config.tribes}/${req.params.tribeid}/tags/hits/${Date.now()}.json`, Tags.info( info, req ), function ( err ) { - if( err ) { - logger.info( `Erreur de sauvegarde de tag pour ${req.params.tribeid} check si /tags/hits et /tags/imgtg exist bien ` ) - } - } ); - } - return true; -} -Tags.dataloadstat = ( tribeid ) => { - /* - @TODO à appeler via une route pour agregation de tag - @TODO ajouter la suppression des fichiers hits traités qd le prog aura fait ses preuves en prod - @TODO corriger la prod pour que l'ip passe - - Si on recharge plusieurs fois un hits (on ne le comptabilise pas si même r et même timestamps) - - Manage tag info to agregate by user and by statistique - stats/data.json = {r:{ - info:{useragent:"",ip:[]}, - data:[ [timestamps, tit, cookie] ] - } - } - stats/graph.json = {"graphYears": {AAAA:#visites,"years":[AAAA,AAAA]}, - "graphMonths": {AAAA:{"Jan":#visites,..},"monthsLabels":["Jan",..],"years":[AAAA,]}, - "graphDaysOfWeek":{"labels":["Sun","Mon",...],"Sun":#visites}, - "graphHoursOfDay":{"labels":["OOh","01h",...],"00h":#visites} - } - Pour tester des evolutions ou un client en dev (recuperer son repertoire de prod /tags ) - ajouter Tags.dataloadstat('yes'); - NODE_ENV=dev node ./models/Tags.js - */ - const agrege = { - data: {}, - graph: { - visites: { - graphYears: { years: [] }, - graphMonths: { - years: [], - monthsLabels: [] - }, - graphMonths: { - years: [], - monthsLabels: [] - }, - graphDayOfWeek: { labels: [] }, - graphHourOfDay: { labels: [] } - }, - visitors: { - graphMonths: { - years: [], - monthsLabels: [] - } - } - } - }; - try { - agrege.data = jsonfile.readfileSync( `${config.tribes}/${tribeid}/tags/stats/data.json`, "utf-8" ); - agrege.graph = jsonfile.readfileSync( `${config.tribes}/${tribeid}/tags/stats/graph.json`, "utf-8" ); - } catch ( err ) { - logger.info( "ATTENTION tag reinitialisé en data.json et graph.json, s'il s'agit de 1ere connexion pas de pb. Le risque est de perdre les tag historiques" ) - //return { status: 503, payload: { info: ['Errconfig'], model: 'Tags', moreinfo: `Il manque un ${config.tribes}/${tribeid}/tags/stats/data.json ou stats/graph.json` } } - } - glob.sync( `${config.tribes}/${tribeid}/tags/hits/*` ) - .forEach( f => { - const hit = jsonfile.readFileSync( f ); - const ts = parseInt( path.basename( f ) - .split( ".json" )[ 0 ] ); - //logger.info(moment(ts).format('DD-MM-YYYY h:mm:ss')); - const tsm = moment( ts ) - const year = tsm.format( 'YYYY' ); - const month = tsm.format( 'MMM' ); - const dayow = tsm.format( 'ddd' ); - const hourod = tsm.format( 'HH' ) + "h"; - let newvisitor = false; - let alreadydone = false; - //logger.info(hit.r, ts) - // Agrege data pour # visiteur vs # de visiteur - if( agrege.data[ hit.r ] ) { - if( !agrege.data[ hit.r ].data.some( el => el[ 0 ] == ts ) ) { - //evite de charger plusieurs fois le même - agrege.data[ hit.r ].data.push( [ ts, hit.tit, hit.cookie ] ) - } else { - alreadydone = true; - } - } else { - newvisitor = true; - agrege.data[ hit.r ] = { - info: { useragent: hit.useragent, ip: [ hit.ip ] }, - data: [ - [ ts, hit.tit, hit.cookie ] - ] - } - } - if( !alreadydone ) { - if( newvisitor ) { - //traite Month - if( !agrege.graph.visitors.graphMonths[ year ] ) { - agrege.graph.visitors.graphMonths[ year ] = {} - agrege.graph.visitors.graphMonths.years.push( year ) - } - if( agrege.graph.visitors.graphMonths[ year ][ month ] ) { - agrege.graph.visitors.graphMonths[ year ][ month ] += 1 - } else { - agrege.graph.visitors.graphMonths[ year ][ month ] = 1 - agrege.graph.visitors.graphMonths.monthsLabels.push( month ) - } - } - //traite graphe Year #visite - if( agrege.graph.visites.graphYears[ year ] ) { - agrege.graph.visites.graphYears[ year ] += 1 - } else { - agrege.graph.visites.graphYears[ year ] = 1 - agrege.graph.visites.graphYears.years.push( year ) - agrege.graph.visites.graphMonths[ year ] = {} - agrege.graph.visites.graphMonths.years.push( year ) - } - //traite graphe Month - if( agrege.graph.visites.graphMonths[ year ][ month ] ) { - agrege.graph.visites.graphMonths[ year ][ month ] += 1 - } else { - agrege.graph.visites.graphMonths[ year ][ month ] = 1 - agrege.graph.visites.graphMonths.monthsLabels.push( month ) - } - //traite graphe Days of week - if( agrege.graph.visites.graphDayOfWeek[ dayow ] ) { - agrege.graph.visites.graphDayOfWeek[ dayow ] += 1 - } else { - agrege.graph.visites.graphDayOfWeek[ dayow ] = 1 - agrege.graph.visites.graphDayOfWeek.labels.push( dayow ) - } - //traite graphe Hour of day - if( agrege.graph.visites.graphHourOfDay[ hourod ] ) { - agrege.graph.visites.graphHourOfDay[ hourod ] += 1 - } else { - agrege.graph.visites.graphHourOfDay[ hourod ] = 1 - agrege.graph.visites.graphHourOfDay.labels.push( hourod ) - } - } - } ) - jsonfile.writeFileSync( `${config.tribes}/${tribeid}/tags/stats/data.json`, agrege.data, 'utf-8' ); - jsonfile.writeFileSync( `${config.tribes}/${tribeid}/tags/stats/graph.json`, agrege.graph, 'utf-8' ); - return { status: 200, payload: { info: [ 'Statsupdated' ], model: 'Tags' } } -} -//logger.info(Tags.dataloadstat('yes')); -/*const ar = [ - [1, 1], - [1, 2] -] -logger.info(ar.some(el => el[0] == 1 && el[1] == 1)) -logger.info(ar.some(el => el == [1, 3])) -*/ -module.exports = Tags; diff --git a/models/Tribes.js b/models/Tribes.js deleted file mode 100755 index 3c2dfe7..0000000 --- a/models/Tribes.js +++ /dev/null @@ -1,352 +0,0 @@ -const bcrypt = require( 'bcrypt' ); -const fs = require( 'fs-extra' ); -const path = require( 'path' ); -const glob = require( 'glob' ); -const Mustache = require( 'mustache' ); -const execSync = require( 'child_process' ) - .execSync; -const dnsSync = require( 'dns-sync' ); -const jwt = require( 'jwt-simple' ); -const moment = require( 'moment' ); -const UUID = require( 'uuid' ); -const Outputs = require( './Outputs.js' ); -const Pagans = require( './Pagans.js' ); -const config = require( '../tribes/townconf.js' ); - -const checkdata = require( `../nationchains/socialworld/contracts/checkdata.js`); -/* -tribeid manager - -/tribes/tribeid -Manage a tribeid space -* create -* update by managing option and contract -* delete a tribeid -* check accountability and - -*/ -const Tribes = {}; -Tribes.init = () => { - console.group( 'init Tribes' ); - let tribeids = []; - let routes = glob.sync( './routes/*.js' ) - .map( f => { - return { url: `/${path.basename(f,'.js')}`, route: f } - } ); - let DOMs = []; - let appname = {}; - TribesGlobalConfig = glob.sync( `${config.tribes}/**/clientconf.json` ) - .map( f => { - const conf = fs.readJSONSync( f ); - // check if plugins exist and add it in .plugins of each tribeid conf - conf.plugins = glob.sync( `${config.tribes}/${conf.tribeid}/plugins/**/package.json` ) - .map( p => { - const pack = fs.readJsonSync( p, 'utf8' ); - routes.push( { url: `/${pack.name}`, route: `${config.tribes}/${conf.tribeid}/plugins/${pack.name}/route.js` } ); - return pack; - } ); - //Add here any other info to get a global view and init - //... - tribeids.push( conf.tribeid ); - DOMs = [ ...new Set( [ ...DOMs, ...conf.allowedDOMs ] ) ]; - if( conf.website ) appname[ conf.tribeid ] = Object.keys( conf.website ) - return conf; - } ); - // store global conf fofs.existsSync( `${config.tmp}/clientconfglob.json` )r sharing to other api - fs.outputJsonSync( `${config.tmp}/clientconfglob.json`, TribesGlobalConfig, { - spaces: 2 - } ); - return { tribeids, routes, DOMs, appname } -} -Tribes.create = ( data ) => { - /* data = clientconf.json - { - "tribeid": "apixtribe", - "genericpsw": "Trze3aze!", - "website": { - "presentation":"https://www.apixtribe.org", - "webapp": "https://webapp.apixtribe.org" - }, - "allowedDOMs": ["local.fr", "localhost:9002", "ndda.fr", "apixtribe.org"], - "clientname": "apixtribe", - "clientlogo": "", - "geoloc": [], - "useradmin": {PUBKEY:"",EMAIL:"",LOGIN:"adminapixtribe",UUID:"adminapixtribe"}, - "smtp": { - "emailFrom": "support@apixtribe.org", - "emailcc": [], - "service": "gmail", - "auth": { - "user": "antonin.ha@gmail.com", - "pass": "Ha06110" - } - }, - "accepted-language": "fr,en", - "langueReferential": ["fr"] - } - What about: - "tribeid": same than the folder where all the client's file are stored - "genericpsw": a generic password for new user need upper lowercase number ans special char - "dnsname": a domain name belonging to the client - "subdns": "www", a sub domain subdns.dnsname give a public web access to - "website": { keywebsite:url}, give access to config.tribes/tribeid/www/keywebsite/index.html, - "allowedDOMs": ["local.fr", "localhost:9002", "nnda.fr"], //for CORS, @TODO generate from prévious URL this allow this apixtribe instance to be accessible - "clientname": Name of the organisation if any, - "clientlogo": logo of the organisation if any, - "geoloc": [], if any - "useradmin": { this is the 1st user create automaticaly to make gui available for the 1st user - "PUBKEY":public key to be authentify without an email, - "EMAIL":user email, we need at least one of authentification set up after the user can use both or only one - "LOGIN": login to use for access admintribeid, - "UUID": unique id normaly UUID but a uuid admintribeid is the same person in any apixtribe instance so we use it by convention. - "xlang": lang used by this user - }, - "smtp": { smtp used to send email by nodemailer lib basic example with a google account - "emailFrom": "support@xx.fr", - "emailcc": [], - "service": "gmail", - "auth": { - "user": "antonin.ha@gmail.com", - "pass": "Ha06110" - } - }, - "accepted-language": "fr,en", list of accepted-language in terme of http request. - "langueReferential": ["fr"], list of the text that have to be translate in referentials - } - */ - //update tmp/confglog.json - const dataclient = Tribes.init(); - //return in prod all instance apxinfo={tribeids:[],logins:[]} - // in dev return only local - //check tribeid name is unique - logger.info( 'liste des tribeid', dataclient.tribeids ) - if( dataclient.tribeids.includes( data.tribeid ) ) { - return { status: 403, payload: { model: "client", info: [ 'tribeidalreadyexist' ] } } - } - //loginsglob = {login:tribeid} - let loginsglob = {}; - if( fs.existsSync( `${config.tmp}/loginsglob.json`, 'utf-8' ) ) { - loginsglob = fs.readJsonSync( `${config.tmp}/loginsglob.json`, 'utf-8' ); - } - const logins = Object.keys( loginsglob ); - if( logins.includes( data.useradmin.login ) ) { - return { status: 403, payload: { model: "client", info: [ 'loginalreadyexist' ] } } - } - fs.ensureDirSync( `${config.tribes}/${data.tribeid}` ); - [ 'users', 'www', 'referentials', 'nationchains' ].forEach( r => { - fs.copySync( `${config.mainDir}/setup/tribes/apixtribe/${r}`, `${config.tribes}/${data.tribeid}/${r}` ); - } ) - fs.outputJsonSync( `${config.tribes}/${data.tribeid}/clientconf.json`, data ); - const confcli = JSON.parse( Mustache.render( fs.readFileSync( `${config.mainDir}/setup/tribes/apixtribe/clientconf.mustache`, 'utf8' ), data ) ); - fs.outputJsonSync( `${config.tribes}/${data.tribeid}/clientconf.json`, confcli ); - - return Pagans.createUser( { - xpaganid: "setup", - xworkon: data.tribeid, - xlang: data.useradmin.xlang - }, data.useradmin ); -}; -Tribes.archive = ( tribeid ) => { - //A faire zip un repertoire tribeid dans - // remove tribeid de data ou devdata - try { - fs.moveSync( `${config.tribes}/${tribeid}`, `${config.archivefolder}/${tribeid}` ); - //update apixtribeenv - Tribes.init(); - return { status: 200, payload: { info: [ 'deletetribeidsuccessfull' ], models: 'Tribes', moreinfo: "TODO see in Tribes.archive" } } - } catch ( err ) { - logger.info( "Erreur d'archivage", err ) - return { status: 403, payload: { info: [ 'archiveerror' ], models: 'Tribes', moreinfo: err } } - } -} -////////////// Manage file for Tribes -Tribes.checkaccessfolder = ( folder, typeaccessrequested, useraccessrights, useruuid ) => { - // check folder right - - - -} - -Tribes.checkaccessfiles = ( listfile, typeaccessrequested, useraccessrights, useruuid ) => { - // @listfile to check accessright on file or folder - // @typeaccessrequested on files R read or download, U for pdate, D for delete , O for owned a Owner has all rights RUD on its files - // @useraccessright from its account /userd/uuid.json - // @useruuid public uuid user - // return {'ok':[file auhtorized],'ko':[files not authorized]} - - const checkauthlistfile = { 'ok': [], 'ko': [] } - let structf = [] - let inforep = { file: {}, dir: {} } - let done; - for( const f of listfile ) { - done = false; - if( !fs.existsSync( `${config.tribes}/${f}` ) ) { - done = true; - checkauthlistfile.ko.push( f ) - logger.info( `${f} file does not exist` ) - } else { - structf = f.split( '/' ); - } - //on ckeck tribeid existe / tribeid/object/ - if( !done && - useraccessrights.data[ structf[ 0 ] ] && - useraccessrights.data[ structf[ 0 ] ][ structf[ 1 ] ] && - useraccessrights.data[ structf[ 0 ] ][ structf[ 1 ] ].includes( typeaccessrequested ) ) { - done = true; - checkauthlistfile.ok.push( f ); - } else { - // check if in folder we have a.info.json .file[f].shared{useruuid:'CRUDO'} - logger.info( 'structf', structf ) - if( fs.existsSync( `${config.tribes}/${structf.slice(0,-1).join('/')}/.info.json` ) ) { - inforep = fs.readJsonSync( `${config.tribes}/${structf.slice(0,-1).join('/')}/.info.json`, 'utf8' ) - } - logger.info( `no accessrights for ${f} for ${useruuid} ` ) - } - if( !done && inforep.file[ f ] && inforep.file[ f ] && inforep.file[ f ].shared && inforep.file[ f ].shared[ useruuid ] && inforep.file[ f ].shared[ useruuid ].includes( typeaccessrequested ) ) { - done = true; - checkauthlistfile.ok.push( f ) - } - // If no authorization then ko - if( !done ) { - checkauthlistfile.ko.push( f ) - } - } // end loop for - //logger.info( 'checkauthlistfile', checkauthlistfile ) - return checkauthlistfile; -} - -Tribes.dirls = ( tribeid, dir ) => { - /* - Return list of file into tribeid/dir - */ - let comment = { src: `${tribeid}/${dir}`, file: {}, dir: {} }; - if( fs.existsSync( `${config.tribes}/${tribeid}/${dir}/.info.json` ) ) { - comment = fs.readJsonSync( `${config.tribes}/${tribeid}/${dir}/.info.json`, 'utf-8' ); - } - const listfile = [] - const listdir = [] - glob.sync( `${config.tribes}/${tribeid}/${dir}/*` ) - .forEach( f => { - //logger.info( f ) - const stats = fs.statSync( f ); - // logger.info( stats ) - if( stats.isFile() ) { - listfile.push( path.basename( f ) ) - if( !comment.file[ path.basename( f ) ] ) { - comment.file[ path.basename( f ) ] = { tags: [], info: "", thumbb64: "" }; - } - comment.file[ path.basename( f ) ].mtime = stats.mtime; - comment.file[ path.basename( f ) ].ctime = stats.ctime; - comment.file[ path.basename( f ) ].size = stats.size; - } - if( stats.isDirectory() ) { - listdir.push( path.basename( f ) ) - if( !comment.dir[ path.basename( f ) ] ) { - comment.dir[ path.basename( f ) ] = { tags: [], info: "", thumbb64: "" } - } - comment.dir[ path.basename( f ) ].nbfile = glob.sync( `${f}/*.*` ) - .length; - comment.dir[ path.basename( f ) ].mtime = stats.mtime; - comment.dir[ path.basename( f ) ].ctime = stats.mtime; - logger.info( 'comment.dir', comment.dir ) - } - } ); - // on remove les file or dir that was deleted - Object.keys( comment.file ) - .forEach( f => { - if( !listfile.includes( f ) ) delete comment.file[ f ] - } ) - Object.keys( comment.dir ) - .forEach( d => { - if( !listdir.includes( d ) ) delete comment.dir[ d ] - } ) - //logger.info( comment ) - fs.outputJson( `${config.tribes}/${tribeid}/${dir}/.info.json`, comment, 'utf-8' ); - return { status: 200, payload: { info: [ 'succestogetls' ], models: 'Tribes', moreinfo: comment } } -}; -Tribes.addspaceweb = ( data ) => { - /* - To create a public spaceweb accessible from https://dnsname/pageindex - - input: - {dnsname:["archilinea.fr","www.archilinea.fr"], 1st is tha main dns other are just servername redirection - tribeid:"archilinea", from req.session.header.xworkon - website:"presentation", - pageindex:"app_index_fr.html" - mode:dev(local no ssl) | prod(IP + ssl) -} - output: - nginx conf and ssl to serve each https://dnsname to /{tribeid}/www/app/{website} - - - Carefull this action is executed with root and restart nginx + apixtribe to work - */ - data.configdomain = config.tribes; - data.porthttp = config.porthttp; - console.assert( config.loglevel == "quiet", 'data to create spaceweb:', data ); - // create spaceweb app for tribeid/www/app/website/pageindexname.html - if( !fs.existsSync( `${config.tribes}/${data.tribeid}/www/app/${data.website}` ) ) { - fs.outputFileSync( `${config.tribes}/${data.tribeid}/www/app/${data.website}/${data.pageindex}`, `

Hello ${data.tribeid} ${data.website} onto ${data.dnsname.join(',')}`, 'utf-8' ) - } - //create logs folder - fs.ensureDirSync( `${config.tribes}/${data.tribeid}/logs/nginx` ); - // add nginx http config - const confnginx = fs.readFileSync( 'setup/nginx/modelwebsite.conf.mustache', 'utf-8' ); - fs.outputFileSync( `/etc/nginx/conf.d/${data.dnsname[0]}.conf`, Mustache.render( confnginx, data ), 'utf-8' ); - if( data.mode == "dev" ) { - //add in /etc/hosts - let hosts = fs.readFileSync( '/etc/hosts', 'utf8' ); - let chg = false; - data.dnsname.forEach( d => { - if( !hosts.includes( `127.0.0.1 ${d}` ) ) { - hosts += `\n127.0.0.1 ${d}`; - chg = true; - } - if( chg ) { - fs.outputFileSync( '/etc/hosts', hosts, 'utf8' ) - } - } ); - }; - //Ckeck dns respond - data.dnsname.forEach( d => { - if( !dnsSync.resolve( `${d}` ) ) { - rep += `\nresolving ${d} will not responding valid IP, please setup domain redirection IP before runing this script` - } - } ) - //update clienconf.json - const clientconf = fs.readJsonSync( `${config.tribes}/${data.tribeid}/clientconf.json` ); - clientconf.website[ data.website ] = data.dnsname[ 0 ]; - //merge allowedDOMs in unique concat - clientconf.allowedDOMs = [ ...new Set( ...clientconf.allowedDOMs, ...data.dnsname ) ]; - fs.outputJsonSync( `${config.tribes}/${data.tribeid}/clientconf.json`, clientconf, 'utf-8' ); - if( !data.setup ) { - // in setup apixtribe is not running and it will be start manually at the 1st run - // in other case need to plan a restart for CORS - setTimeout( Tribes.restartapixtribe, 300000, data.clienId ); - } - const nginxrestart = execSync( `sudo systemctl restart nginx` ) - .toString(); - logger.info( 'Restart nginx', nginxrestart ) - if( data.mode == "prod" ) { - // get ssl certificate ATTENTION il faut ajouter -d devant chaque domain qui redirige vers l'espace web. - const certbot = execSync( `sudo certbot --nginx -d ${data.dnsname.join(' -d ')}` ) - .toString(); - logger.info( 'certbot is running A CHECKER POUR UNE VRAIE PROD ????', certbot ) - } - //sh execution to update change requested - return { - status: 200, - payload: { - model: "Tribes", - info: [ 'webspacecreated' ], - moreinfo: "Space web well created" - } - }; -} -Tribes.restartapixtribe = ( tribeid ) => { - logger.info( 'A restarting was requested 5mn ago from a new spacedev for ' + tribeid ) - execSync( 'yarn restartpm2' ); -} - - -module.exports = Tribes; diff --git a/models/UploadFiles.js b/models/UploadFiles.js deleted file mode 100755 index 6051ade..0000000 --- a/models/UploadFiles.js +++ /dev/null @@ -1,152 +0,0 @@ -const fs = require( 'fs-extra' ); -const path = require( 'path' ); -const formidable = require( 'formidable' ); -const jsonfile = require( 'jsonfile' ); -const mustache = require( 'mustache' ); -const config = require( '../tribes/townconf.js' ); - -/* -model A SUPPRIMER !!!!!!!!!!!!!!!!!!!!!! -les functions d'upload de file et de droits d'accès doivent être gérer dans Tribes - -*/ -const UploadFiles = {}; -UploadFiles.get = function ( filename, header ) { - // check file exist - const file = `${config.tribes}/${header.xworkon}/${filename}`; - // logger.info('fichier demande ', file); - if( !fs.existsSync( file ) ) { - // logger.info('le fichier demande n existe pas ', file); - return { - status: 404, - payload: { info: [ 'fileUnknown' ], model: 'UploadFiles' } - }; - } else { - logger.info( 'envoie le fichier ', file ); - return { - status: 200, - payload: { info: [ 'fileknown' ], model: 'UploadFiles', file: file } - }; - } -}; -UploadFiles.addjson = function ( data, header ) { - /* - Le header = {X-WorkOn:"",destinationfile:"", filename:""} - Le body = {jsonp:{},callback:function to launch after download,'code':'mot cle pour verifier que le fichier est à garder'} - */ - // logger.info(req.body.jsonp); - try { - jsonfile.writeFileSync( header.destinationfile + '/' + header.filename, data.jsonp ); - if( data.callback ) { - const execCB = require( `${config.mainDir}/models/tribeid/${ - header.xworkon - }` ); - execCB[ data.callback ](); - } - return { - status: 200, - payload: { - info: [ 'wellUpload' ], - model: 'UploadFiles', - render: { - destination: header.destinationfile, - filename: header.filename - } - } - }; - } catch ( err ) { - logger.info( 'Impossible de sauvegarder le fichier, A COMPRENDRE', err ); - return { - status: 503, - payload: { info: [ 'savingError' ], model: 'UploadFiles' } - }; - } -}; -UploadFiles.add = function ( req, header ) { - const form = new formidable.IncomingForm(); - logger.info( 'req.headers', req.headers ); - logger.info( 'req.params', req.params ); - logger.info( 'req.query', req.query ); - logger.info( 'req.body', req.body ); - let destinationfile = `${config.tribes}/${header.xworkon}/${ - header.destinationfile - }`; - form.parse( req, function ( err, fields, files ) { - logger.info( 'files', files.file.path ); - logger.info( 'fields', fields ); - const oldpath = files.file.path; - destinationfile += '/' + files.file.name; - logger.info( 'oldpath', oldpath ); - logger.info( 'destinationfile', destinationfile ); - fs.copyFile( oldpath, destinationfile, function ( err ) { - if( err ) { - logger.info( err ); - return { - status: 500, - payload: { info: [ 'savingError' ], model: 'UploadFiles' } - }; - } else { - logger.info( 'passe' ); - fs.unlink( oldpath ); - return { - status: 200, - payload: { - info: [ 'wellUpload' ], - model: 'UploadFiles', - render: { - destination: destinationfile - } - } - }; - } - } ); - } ); -}; -UploadFiles.updateEvent = function ( domainId, eventId, event ) { - // checkAndCreateNeededDirectories(domainId); - const eventsFile = `${config.tribes}/${domainId}/actions/events/events.json`; - if( !fs.existsSync( eventsFile ) ) { - jsonfile.writeFileSync( eventsFile, {} ); - return { status: 404, payload: 'You have not any events.' }; - } - const events = jsonfile.readFileSync( eventsFile ); - if( !events.hasOwnProperty( eventId ) ) { - return { - status: 404, - payload: 'The event you are trying to update does not exist.' - }; - } - events[ eventId ] = { - eventName: event.eventName, - eventDate: event.eventDate, - eventDescription: event.eventDescription - }; - jsonfile.writeFileSync( eventsFile, events, { spaces: 2 } ); - return { - status: 200, - payload: events - }; -}; -UploadFiles.deleteEvent = function ( domainId, eventId ) { - // checkAndCreateNeededDirectories(domainId); - const eventsFile = `${config.tribes}/${domainId}/actions/events/events.json`; - if( !fs.existsSync( eventsFile ) ) { - jsonfile.writeFileSync( eventsFile, {} ); - return { status: 404, payload: 'You have not any events.' }; - } - const events = jsonfile.readFileSync( eventsFile ); - if( events.hasOwnProperty( eventId ) ) { - delete events[ eventId ]; - jsonfile.writeFileSync( eventsFile, events, { spaces: 2 } ); - return { - status: 200, - payload: events - }; - } else { - return { - status: 404, - payload: 'The event you are trying to delete does not exist.' - }; - } -}; -module.exports = UploadFiles; diff --git a/nationchains/socialworld/contracts/checkdata.js b/nationchains/socialworld/contracts/checkdata.js deleted file mode 100755 index 53cae0d..0000000 --- a/nationchains/socialworld/contracts/checkdata.js +++ /dev/null @@ -1,185 +0,0 @@ -/* -This module have to be independant of any external package -it is shared between back and front and is usefull -to apply common check in front before sending it in back -can be include in project with - -or with const checkdata = require('../public/js/checkdata.js') - -*/ - -// --## - -const checkdata = {}; -// each checkdata.test. return true or false -checkdata.test = {}; - -checkdata.test.emailadress = ( ctx, email ) => { - const regExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - return regExp.test( email ); -}; -/* - * @emaillist = "email1,email2, email3" - * it check if each eamil separate by , are correct - */ -checkdata.test.emailadresslist = ( ctx, emaillist ) => { - //logger.info(emaillist.split(',')) - if( emaillist.length > 0 ) { - const emails = emaillist.split( ',' ); - for( var i in emails ) { - //logger.info(emails[i]) - if( !checkdata.test.emailadress( "", emails[ i ].trim() ) ) { - return false - } - } - }; - return true; -}; - -checkdata.test.password = ( ctx, pwd ) => { - const regExp = new RegExp( - /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&.])[A-Za-z\d$@$!%*?&.{}:|\s]{8,}/ - ); - return regExp.test( pwd ); -}; -checkdata.test.required = ( ctx, val ) => - ( val != null && val != 'undefined' && val.length > 0 ) || ( !!val && val.constructor === Array && val.length > 0 ) || ( !!val && val.constructor === Object && Object.keys( val ) - .length > 0 ); - -checkdata.test.isNumber = ( ctx, n ) => typeof n === 'number'; -checkdata.test.isInt = ( ctx, n ) => n != '' && !isNaN( n ) && Math.round( n ) == n; -checkdata.test.isFloat = ( ctx, n ) => n != '' && !isNaN( n ) && Math.round( n ) != n; -checkdata.test.unique = ( ctx, val ) => { - if( ctx.list[ ctx.currentfield ] ) { - return !ctx.list[ ctx.currentfield ].includes( val ); - } else { - logger.info( 'ERR no list for field:' + ctx.currentfield ); - return false; - } -}; -checkdata.test.isDateDay = ( ctx, dateDay ) => true; -/* checkdata.test.filterInvalidInArray = (array, validate) => - array ? array.filter(el => !validate(el)) : true; -// return true when every elements is valid -*/ - -checkdata.test.postalCode = ( ctx, postalCode ) => { - if( postalCode.length == 0 ) return true; - const regExp = new RegExp( /(^\d{5}$)|(^\d{5}-\d{4}$)/ ); - return regExp.test( postalCode ); -}; -/** - * PHONE - */ -checkdata.test.phoneNumber = ( ctx, phoneNumber ) => { - if( phoneNumber.length == 0 ) return true; - phoneNumber = phoneNumber.trim() - .replace( /[- .]/g, '' ) - //french number - const regExpfr = new RegExp( /^0[1-9][0-9]{9}$/ ); - const regExpInternational = new RegExp( /^\+*(\d{3})*[0-9,\-]{8,}/ ); - return regExpfr.test( phoneNumber ) || regExpInternational.test( phoneNumber ); -}; -/* - * @phonelist = "phone1,phone2,phone3" - * it check if each phone separate by , are correct - */ -checkdata.test.phoneNumberlist = ( ctx, phonelist ) => { - //logger.info(emaillist.split(',')) - if( phonelist.length > 0 ) { - const phones = phonelist.split( ',' ); - for( var i in phones ) { - //logger.info(emails[i]) - if( !checkdata.test.phoneNumber( "", phones[ i ].trim() ) ) { - return false - } - } - }; - return true; -}; - -// checkdata.normalize take a correct data then reformat it to harmonise it -checkdata.normalize = {}; -checkdata.normalize.phoneNumber = ( ctx, phone ) => { - phone = phone.trim() - .replace( /[- .]/g, '' ); - if( checkdata.test.phoneNumber( '', phone ) && phone.length == 10 && phone[ 0 ] == "0" ) { - phone = '+33 ' + phone.substring( 1 ); - } - return phone; -} -checkdata.normalize.upperCase = ( ctx, txt ) => txt.toUpperCase(); -checkdata.normalize.lowerCase = ( ctx, txt ) => txt.toLowerCase(); -// fixe 10 position et complete par des 0 devant -checkdata.normalize.zfill10 = ( ctx, num ) => { - let s = num + ''; - while( s.length < 10 ) s = '0' + s; - return s; -}; -/*let tt = "+33 1 02.03 04 05"; -logger.info(checkdata.test.phoneNumber('', tt)) -logger.info(checkdata.normalize.phoneNumber('', tt)) -*/ -checkdata.evaluate = ( contexte, referential, data ) => { - /* - * contexte object {} with full info for evaluation - * file referential path to get object to apply - * data related to object - - return {validefor =[keyword of error] if empty no error, - clean data eventually reformated - updateDatabase} - */ - logger.info( 'contexte', contexte ); - logger.info( 'referentiel', referential ); - logger.info( 'data', data ); - const invalidefor = []; - const objectdef = {}; - const listfield = referential.map( ch => { - objectdef[ ch.idfield ] = ch; - return ch.idfield; - } ); - - Object.keys( data ) - .forEach( field => { - if( !listfield.includes( field ) ) { - // some data can be inside an object with no control at all - // they are used for process only - // i leave it in case it will become a non sens - // invalidefor.push('ERRFIELD unknown of referentials ' + field); - } else { - if( objectdef[ field ].check ) { - // check data with rule list in check - objectdef[ field ].check.forEach( ctrl => { - logger.info( 'ctrl', ctrl ); - contexte.currentfield = field; - if( !checkdata.test[ ctrl ] ) { - invalidefor.push( 'ERR check function does not exist :' + ctrl + '___' + field ) - } else { - if( !checkdata.test[ ctrl ]( contexte, data[ field ] ) ) - invalidefor.push( 'ERR' + ctrl + '___' + field ); - } - } ); - } - - if( objectdef[ field ].nouserupdate ) { - // check if user can modify this information - logger.info( - 'evaluation :' + field + ' -- ' + objectdef[ field ].nouserupdate, - eval( objectdef[ field ].nouserupdate ) - ); - const evalright = eval( objectdef[ field ].nouserupdate ); - objectdef[ field ].nouserupdate = evalright; - } - } - } ); - logger.info( { - invalidefor, - data - } ); - return { - invalidefor, - data - }; -}; - -if( typeof module !== 'undefined' ) module.exports = checkdata; diff --git a/nationchains/socialworld/contracts/toolsbox.js b/nationchains/socialworld/contracts/toolsbox.js deleted file mode 100755 index 293b5bd..0000000 --- a/nationchains/socialworld/contracts/toolsbox.js +++ /dev/null @@ -1,604 +0,0 @@ -/* eslint-disable no-useless-escape */ -const fs = require( 'fs' ); -const path = require( 'path' ); -const bcrypt = require( 'bcrypt' ); -const moment = require( 'moment' ); -const config = require( '../config' ); -const utils = {}; - -logger.info( "Check in /utils/index.js to find usefull function for your dev.\n Feel free to send suggestion, code to maintainer of apixtribe project (see /package.json to get email).\n We'll add to the roadmap to add it." ); - -/** - * EMAIL - */ -/* const validateEmail = email => { - const regExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - return regExp.test(email); -}; - -const validatePassword = pwd => { - const regExp = new RegExp( - /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&.])[A-Za-z\d$@$!%*?&.{}:|\s]{8,}/ - ); - return regExp.test(pwd); -}; - -const filterInvalidInArray = (array, validate) => - array ? array.filter(el => !validate(el)) : undefined; // return undefined when every elements is valid - -/** - * POSTAL CODE - */ -/* -const validatePostalCode = postalCode => - /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(postalCode); - -/** - * PHONE - */ -/* const validatePhoneNumber = phoneNumber => - /((^0[1-9]|\+[0-9]{3})([-. ]?[0-9]{2}){4}$)/.test(phoneNumber); - -const correctPhoneNumber = phone => - phone[0] === '0' ? '+33' + phone.substr(1) : phone; - -const checkData = (appProfil, referential, data) => { - // @TODO get a referentiel per object then check data validity and allowed access - // need to add referentiel manager - const invalidefor = []; - let updateDatabase = false; - Object.keys(data).forEach(field => { - switch (field) { - case 'token': - updateDatabase = true; - break; - case 'email': - if (!validateEmail(data.email)) { - invalidefor.push('ERREMAIL:' + field); - } else { - updateDatabase = true; - } - break; - case 'password': - if (!validatePassword(data.password)) { - invalidefor.push('ERRPWD:' + field); - } else { - data.password = bcrypt.hash(data.password, config.saltRounds); - updateDatabase = true; - } - break; - } - }); - return { invalidefor, data, updateDatabase }; -}; -*/ -//Permet d'attendre en milliseconde -// s'utilise avec async ()=>{ -// await sleep(2000) -//} -utils.sleep = ( ms ) => { - return new Promise( resolve => setTimeout( resolve, ms ) ); -} -utils.generemdp = ( nbpos ) => { - const chaine = "ABCDEFGHIJKLMNPQRSTUVWZY123456789"; - let mdp = ""; - for( var i = 0; i < nbpos; i++ ) { - var pos = Math.floor( Math.random() * chaine.length ); - mdp += chaine.substring( pos, pos + 1 ); - } - return mdp; -} -utils.generecompteur = ( filecpt, typeincrement ) => { - let file = `${filecpt}/${typeincrement}.json`; - let prefix = ""; - if( typeincrement = "ANNEESEMAINE" ) { - file = `${filecpt}/${typeincrement}${moment().format('YYYY')}${moment().format('WW')}.json` - prefix = `${moment().format('YYYY')}${moment().format('WW')}` - } - let num = 1; - try { - num = parseInt( fs.readFileSync( file, 'utf8' ) ) + 1; - } catch ( err ) { - logger.info( "Nouveau compteur incrementale ", file ) - } - fs.writeFileSync( file, num, 'utf8' ); - return prefix + num -} -/** - * CSV - */ -utils.json2csv = ( jsondata, options, callback ) => { - // uniquement json = [{niv1:val,niv1:[liste of val]}] - // logger.info('_________________________'); - // logger.info(jsondata) - // logger.info('_________________________'); - if( jsondata.length == 0 ) { - return callback( "Empty json", null ); - } - if( !options.retln ) options.retln = '\n'; - if( !options.sep ) options.sep = ';'; - if( !options.arraysplitsep ) options.arraysplitsep = ","; - if( !options.replacespecialcarJson2Csv ) { - options.replacespecialcarJson2Csv = [] - } else { - if( typeof options.replacespecialcarJson2Csv == "string" ) { - //permet de passer des regex en string - options.replacespecialcarJson2Csv = eval( options.replacespecialcarJson2Csv ); - } - }; - let etat = ""; - let csv = ''; - let entete = ''; - let prem = true; - for( const j in jsondata ) { - // logger.info(jsondata[j]) - for( const c in options.champs ) { - if( prem ) { - entete += options.champs[ c ] + options.sep; - } - if( jsondata[ j ][ options.champs[ c ] ] ) { - if( options.array.indexOf( options.champs[ c ] ) > -1 ) { - csv += jsondata[ j ][ options.champs[ c ] ].join( options.arraysplitsep ) + options.sep; - } else { - let currentValue = ""; - if( jsondata[ j ][ options.champs[ c ] ] ) currentValue += jsondata[ j ][ options.champs[ c ] ]; - options.replacespecialcarJson2Csv.forEach( re => { - //logger.info(currentValue) - currentValue = currentValue.replace( re[ 1 ], re[ 0 ] ) - } ) - csv += currentValue + options.sep; - } - } else { - csv += options.sep; - } - } - csv = csv.substring( 0, csv.length - 1 ) + options.retln; - if( prem ) { - prem = false; - entete = entete.substring( 0, entete.length - 1 ) + options.retln; - // logger.info(entete) - } - } - // return entete + csv; - if( etat == "" ) { - return callback( null, entete + csv ); - } else { - return callback( etat, null ); - } -}; -/** - * Get headers from first line of CSV - * @param {array} lines array of string which contains each csv lines - * @return {array} string array of headers - */ -utils.getHeaders = ( lines, sep ) => lines[ 0 ].split( sep ) - .map( i => i.replace( /"/g, '' ) ); -/** - * [csv2json description] - * @param {object} csv object of csv file that has been read - * @param {object} options object containing csv options, headers, ... - {retln:'code de retour de ligne \n ou \n\r', - sep:'code to split cells', - champs:[ch1,ch2,...] catch only those field, - array:[ch1, ] can have more than one field champs with same name then data are push into an array } - * @param {Function} callback callback function - * @return {callback} - return an error if error, else return json - it convert a csv file into a json = [{field:value}] - -Usage example: -fiche.csv2article = (err, fiche) => { - if (!err) { - logger.info(fiche) - } -} -utils.csv2json(fs.readFileSync('./devdata/tribee/aubergenville/infoexterne/localbusiness.csv', 'utf-8'), { - retln: "\n", - sep: ";", - champs: ["NOM", "OBJET", "ADRESSE_PRO", "CP_PRO", "VILLE_PRO", "ZONE", "PHONE_PRO", "HORAIRESDESC", "HORAIREDATA", "URL", "FACEBOOK", "INSTA", "EMAIL_PRO", "IMG", "TAG"], - array: ["TAG", "PHONE_PRO", "EMAIL_PRO"] -}, fiche.csv2article) - - */ -utils.replacecarbtweendblquote = ( csv, car, carremplacant ) => { - /* - return csv text with any car betwenn 2 " by CARSEPARATOR - */ - let newcsv = ""; - let txtencours = ""; - let flagouvert = false - const sepreg = new RegExp( `${car}`, 'gmi' ) - for( let j = 0; j < csv.length; j++ ) { - //if((csv[j] == "\"" && csv[j + 1] && csv[j + 1] != "\"") || (csv[j] == "\"" && csv[j - 1] && csv[j - 1] != "\"") || (csv[j] == "\"" && csv[j - 1] && csv[j - 2] && csv[j - 1] != "\"" && csv[j - 2] != "\"")) { - if( csv[ j ] == "\"" ) { - if( flagouvert ) { - // on cherche à ferme une chaine de texte - if( csv[ j + 1 ] == "\"" ) { - //on a "" consecutif qu'on remplace par "" et on fait j+1 - txtencours += "\"\"" - j++ - } else { - // on a bien une fermeture - flagouvert = false - newcsv += txtencours.replace( sepreg, carremplacant ) - txtencours = "\"" - } - } else { - // on ouvre une chaine - flagouvert = true - //on met le contenu précédent ds newcsv - newcsv += txtencours - txtencours = "\"" - } - //} else if((csv[j] !== "\n") && (csv[j + 1] && csv[j] + csv[j + 1] !== "\n\r")) { - } else if( csv[ j ] !== "\n" ) { - txtencours += csv[ j ] - // } else if((csv[j] == "\n") || (csv[j + 1] && csv[j] + csv[j + 1] == "\n\r")) { - } else if( csv[ j ] == "\n" ) { - if( !flagouvert ) txtencours += "\n" - } - } - return newcsv + txtencours -} -utils.analysestring = ( string ) => { - let buftxt = "" - let bufcode = "" - let i = 0 - let avecRL = false - for( let p = 0; p < string.length; p++ ) { - if( string[ p ].charCodeAt() == 10 ) { - buftxt += "[RL]" - avecRL = true - } else { - buftxt += string[ p ] - } - bufcode += "-" + string[ p ].charCodeAt(); - if( i == 20 ) { - if( avecRL ) { - logger.info( `${buftxt} - ${bufcode}` ) - } else { - logger.info( `${buftxt} ---- ${bufcode}` ) - } - i = 0; - buftxt = "" - bufcode = "" - avecRL = false - } - i++; - } -} - -const txtstring = `32932,BK_F2F_B_COM_10x1H-09,"My Communication Workshop ""Session N°9 - 1H""","

 

- - - - - - -
-

Learner who needs to develop their ability to communicate effectively at work, both in writing and speaking

-
",,english,2,0,,2,0,classroom,"0000-00-00 00:00:00","0000-00-00 00:00:00",0000-00-00,0000-00-00,https://www.yesnyoulearning.com/lms/index.php?r=player&course_id=32932,1101,,"BUSINESS KEYS",0, -32933,BK_F2F_B_COM_10x1H-10,"My Communication Workshop Session N°10 - 1H","

 

- - - - - - -
-

Learner who needs to develop their ability to communicate effectively at work, both in writing and speaking

-
",,english,2,0,,2,0,classroom,"0000-00-00 00:00:00","0000-00-00 00:00:00",0000-00-00,0000-00-00,https://www.yesnyoulearning.com/lms/index.php?r=player&course_id=32933,1101,,"BUSINESS KEYS",0, -32934,BK_F2F_B_JOB_10x1H-01,"My Job Search Workshop Session N°1 - 1H","

PACK JOB SEARCH

",,english,2,0,,2,0,classroom,,,0000-00-00,0000-00-00,https://www.yesnyoulearning.com/lms/index.php?r=player&course_id=32934,1108,,,0, -32935,BK_F2F_B_JOB_10x1H-02,"My Job Search Workshop Session N°2 - 1H","

PACK JOB SEARCH

",,english,2,0,,2,0,classroom,,,0000-00-00,0000-00-00,https://www.yesnyoulearning.com/lms/index.php?r=player&course_id=32935,1108,,,0,` -//utils.analysestring(txtstring) -//logger.info(utils.replacecarbtweendblquote(txtstring, ",", 'CARSEPARATOR') -// .split("\n")[0].split(",")) -utils.csv2json = ( csv, options, callback ) => { - // EN CAS DE PB AVEC UN FICHIER EXCEL RECALCITRANT - // l'ouvrir dans calc linux et sauvegarder csv utf8, ; , " enregistrer le contenu de la cellule comme affiché - logger.info( '\n--------------- CSV2JSON ---------------\n' ); - // Default CSV options - if( !options.retln ) options.retln = '\n'; - if( csv.indexOf( '\n\r' ) > -1 ) options.retln = '\n\r'; - if( !options.sep ) options.sep = ';'; - //gestion d un separateur dans une chaine de texte - //const regseptext = new RegExp(`${options.sep}(?!(?:[^"]*"[^"]*")*[^"]*$)`, 'gm'); - //csv = csv.replace(regseptext, "CARACSEPAR"); - // csv = utils.replacecarbtweendblquote(csv, options.retln, "RETLIGNE") - csv = utils.replacecarbtweendblquote( csv, options.sep, "CARSEPARATOR" ) - if( !options.replacespecialcarCsv2Json ) { - options.replacespecialcarCsv2Json = [] - } else { - if( typeof options.replacespecialcarCsv2Json == "string" ) { - //permet de passer des regex en string - options.replacespecialcarCsv2Json = eval( options.replacespecialcarCsv2Json ); - } - }; - const result = []; - const lines = csv.split( options.retln ); - const headers = utils.getHeaders( lines, options.sep ); - let unknownHeaders = ''; - //logger.info('headers', headers) - //logger.info('options.champs', options.champs) - headers.forEach( header => { - // Si un header n'est pas présent dans la liste des champs prédéfinis - // on l'ajoute aux champs inconnus - if( options.champs.indexOf( header ) === -1 ) { - unknownHeaders += `${header}, `; - } - } ); - if( unknownHeaders !== '' ) { - const errorMsg = `CSV2JSON() - Champs inconnus : ${unknownHeaders}`; - return callback( errorMsg, null ); - } - lines.forEach( ( line, index ) => { - // Skip headers line or empty lines - if( index === 0 || line.replace( /\s/g, '' ) - .length === 0 ) { - return; - } - // pour debuguer on met origincsv pour voir la ligne d'origine - const currentLineData = { 'origincsv': line, 'linenumber': index }; - const currentLine = line.split( options.sep ); // Current string in the line - for( let j = 0; j < headers.length; j++ ) { - // Si la ligne n'est pas vide - if( currentLine[ j ] ) { - // On clean le champs - // ajout eventuel de modification de caracter reservé ; dans les libelléetc... - let currentValue = currentLine[ j ].trim() - //on transforme le caractere separateur modifié entre double quote - currentValue = currentValue.replace( 'CARSEPARATOR', options.sep ); - options.replacespecialcarCsv2Json.forEach( re => { - currentValue = currentValue.replace( re[ 0 ], re[ 1 ] ) - } ) - // Si le header est un email - if( headers[ j ].includes( 'EMAIL' ) ) { - // Supprimer tous les espaces - currentValue = currentLine[ j ].replace( /\s/g, '' ); - } - // on check si le chamos doit être numerique - if( options.numericfield.includes( headers[ j ] ) ) { - currentValue = currentLine[ j ].replace( /\,/g, '.' ); - try { - const test = parseFloat( currentValue ); - } catch ( er ) { - return callback( `${headers[j]} contiens la valeur -${currentValue}- et devrait être numerique`, null ); - } - } - if( currentValue ) { - // Si le header actuel est de type array - // Cela signifie que le header apparaît plusieurs fois dans le CSV - // et que les valeurs correspondantes à ce header - // doivent être mis dans un array - if( options.array && options.array.indexOf( headers[ j ] ) > -1 ) { - // Si le tableau pour ce header n'existe pas on le crée - if( !currentLineData[ headers[ j ] ] ) { - currentLineData[ headers[ j ] ] = []; - } - if( options.arraysplitsep ) { - currentValue.split( options.arraysplitsep ) - .forEach( v => { - currentLineData[ headers[ j ] ].push( v ); - } ) - } else { - currentLineData[ headers[ j ] ].push( currentValue ); - } - } else { - // Si un header est déjà présent pour la ligne - // alors que il n'est pas spécifié comme étant un array - // on retourne une erreur - if( currentLineData[ headers[ j ] ] ) { - const errorMsg = `Le champ ${ - headers[j] - } est présent plusieurs fois alors qu'il n'est pas spécifié comme étant un array !`; - return callback( errorMsg, null ); - } - currentLineData[ headers[ j ] ] = currentValue; - } - } - } - } - result.push( currentLineData ); - } ); - return callback( null, result ); -}; -/** - * [csvparam2json description] - * @param {object} csv object of csv file that has been read - * @param {object} options object containing csv options, headers, ... - {retln:'code de retour de ligne \n ou \n\r', - sep:'code to split cells', - champs:[ch1,ch2,...] catch only those field, - array:[ch1, ] can have more than one field champs with same name then data are push into an array } - * @param {Function} callback callback function - * @return {callback} - return an error if error, else return json - it converts a csv with 3 column col1;col2;col3 in a json in a tree - if in col1 we have __ => then it splits a leaf - col1 = xxxx__yyyy ; col2 = value ; col3 = comment that is ignored - return data = {xxxx:{yyyy:value}} - col1 = xxxx; col2 = value; col3 = comment ignored -return data = {xxxx:value} - -Usage example: -fiche.csvparam2article = (err, fiche) => { - if (!err) { - logger.info(fiche) - } -} -utils.csvparam2json(fs.readFileSync('./devdata/tribee/aubergenville/infoexterne/localbusiness.csv', 'utf-8'), { - retln: "\n", - sep: ";", - champs: ["NOM", "OBJET", "ADRESSE_PRO", "CP_PRO", "VILLE_PRO", "ZONE", "PHONE_PRO", "HORAIRESDESC", "HORAIREDATA", "URL", "FACEBOOK", "INSTA", "EMAIL_PRO", "IMG", "TAG"], - array: ["TAG", "PHONE_PRO", "EMAIL_PRO"] -}, fiche.csv2article) - - */ -utils.csvparam2json = ( csv, options, callback ) => { - logger.info( '\n--------------- CSVPARAM2JSON ---------------\n' ); - let etat = ""; - const param = {}; - if( !options.retln ) { - options.retln = '\n'; - } - if( csv.indexOf( '\n\r' ) > -1 ) { - options.retln = '\n\r'; - } - if( !options.sep ) { - options.sep = ';'; - } - if( !options.seplevel ) { - options.seplevel = "__"; - } - if( !options.replacespecialcarCsv2Json ) { - options.replacespecialcarCsv2Json = [] - } else { - if( typeof options.replacespecialcarCsv2Json == "string" ) { - //permet de passer des regex en string - options.replacespecialcarCsv2Json = eval( options.replacespecialcarCsv2Json ); - } - }; - const lines = csv.split( options.retln ); - for( let i = 0; i < lines.length; i++ ) { - const infol = lines[ i ].split( options.sep ) - //logger.info(infol) - if( infol[ 0 ].length > 4 && infol.length < 2 ) { - // si le 1er element à plus de 4 caractere et s'il y a moins de 3 colonnes c'est qu'il y a un pb - etat += `Erreur sur ${lines[i]} moins de 3 column separé par ${options.sep}`; - continue; - } - // On ajoute ici la gestion de tous les caracteres spéciaux - // reservées pour le csv ; ' etc..' - if( infol[ 1 ] && infol[ 1 ] + "" == infol[ 1 ] ) { - options.replacespecialcarCsv2Json.forEach( re => { - //logger.info("gggggggggggggggggggg", infol[1]) - infol[ 1 ] = infol[ 1 ].replace( re[ 0 ], re[ 1 ] ); - } ) - // logger.info(infol[1]) - infol[ 1 ] = infol[ 1 ].replace( /'|’/g, "\"" ); - //logger.info(infol[1]) - if( infol[ 1 ].toLowerCase() === 'true' ) { - infol[ 1 ] = true; - } else if( infol[ 1 ].toLowerCase() === 'false' ) { - infol[ 1 ] = false; - } - } - logger.info( infol[ 1 ] ) - //supprime des lignes vides - if( infol[ 0 ] == '' ) continue; - if( infol[ 0 ].indexOf( options.seplevel ) == -1 ) { - param[ infol[ 0 ] ] = infol[ 1 ] - continue; - } else { - const arbre = infol[ 0 ].split( options.seplevel ) - switch ( arbre.length ) { - case 1: - param[ arbre[ 0 ] ] = infol[ 1 ]; - break; - case 2: - if( arbre[ 1 ] != "ARRAY" ) { - if( !param[ arbre[ 0 ] ] ) param[ arbre[ 0 ] ] = {}; - param[ arbre[ 0 ] ][ arbre[ 1 ] ] = infol[ 1 ]; - } else { - if( !param[ arbre[ 0 ] ] ) param[ arbre[ 0 ] ] = []; - //logger.info('aff', infol[1].substring(1, infol[1].length - 1).replace(/""/g, '"')) - eval( "result=" + infol[ 1 ] ) - //.substring(1, infol[1].length - 1).replace(/""/g, '"')) - param[ arbre[ 0 ] ].push( result ) - } - break; - case 3: - if( arbre[ 2 ] != "ARRAY" ) { - if( !param[ arbre[ 0 ] ] ) param[ arbre[ 0 ] ] = {}; - if( !param[ arbre[ 0 ] ][ arbre[ 1 ] ] ) param[ arbre[ 0 ] ][ arbre[ 1 ] ] = {}; - param[ arbre[ 0 ] ][ arbre[ 1 ] ][ arbre[ 2 ] ] = infol[ 1 ]; - } else { - if( !param[ arbre[ 0 ] ] ) param[ arbre[ 0 ] ] = {}; - if( !param[ arbre[ 0 ] ][ arbre[ 1 ] ] ) param[ arbre[ 0 ] ][ arbre[ 1 ] ] = []; - //eval("result = \"test\""); - //logger.info(result); - eval( "result=" + infol[ 1 ] ); - //.substring(1, infol[1].length - 1).replace(/""/g, '"')) - param[ arbre[ 0 ] ][ arbre[ 1 ] ].push( result ) - } - break; - case 4: - if( arbre[ 3 ] != "ARRAY" ) { - if( !param[ arbre[ 0 ] ] ) param[ arbre[ 0 ] ] = {}; - if( !param[ arbre[ 0 ] ][ arbre[ 1 ] ] ) param[ arbre[ 0 ] ][ arbre[ 1 ] ] = {}; - if( !param[ arbre[ 0 ] ][ arbre[ 1 ] ][ arbre[ 2 ] ] ) param[ arbre[ 0 ] ][ arbre[ 1 ] ][ arbre[ 2 ] ] = {}; - param[ arbre[ 0 ] ][ arbre[ 1 ] ][ arbre[ 2 ] ][ arbre[ 3 ] ] = infol[ 1 ]; - } else { - if( !param[ arbre[ 0 ] ] ) param[ arbre[ 0 ] ] = {}; - if( !param[ arbre[ 0 ] ][ arbre[ 1 ] ] ) param[ arbre[ 0 ] ][ arbre[ 1 ] ] = {}; - if( !param[ arbre[ 0 ] ][ arbre[ 1 ] ][ arbre[ 2 ] ] ) param[ arbre[ 0 ] ][ arbre[ 1 ] ][ arbre[ 2 ] ] = []; - eval( "result=" + infol[ 1 ] ) - //.substring(1, infol[1].length - 1).replace(/""/g, '"')) - param[ arbre[ 0 ] ][ arbre[ 1 ] ][ arbre[ 2 ] ].push( result ) - break; - } - default: - break; - } - } - } - // JSON.parse(JSON.stringify(param)) - logger.info( 'kkkkkkkkkkkkkkkkkk', param[ 'catalogue' ][ 'filtrecatalog' ][ 'searchengine' ] ) - if( etat == "" ) { - return callback( null, JSON.parse( JSON.stringify( param ) ) ); - } else { - return callback( etat, null ); - } -} -utils.levenshtein = ( a, b ) => { - if( a.length === 0 ) return b.length; - if( b.length === 0 ) return a.length; - let tmp, i, j, prev, val, row; - // swap to save some memory O(min(a,b)) instead of O(a) - if( a.length > b.length ) { - tmp = a; - a = b; - b = tmp; - } - row = Array( a.length + 1 ); - // init the row - for( i = 0; i <= a.length; i++ ) { - row[ i ] = i; - } - // fill in the rest - for( i = 1; i <= b.length; i++ ) { - prev = i; - for( j = 1; j <= a.length; j++ ) { - if( b[ i - 1 ] === a[ j - 1 ] ) { - val = row[ j - 1 ]; // match - } else { - val = Math.min( row[ j - 1 ] + 1, // substitution - Math.min( prev + 1, // insertion - row[ j ] + 1 ) ); // deletion - } - row[ j - 1 ] = prev; - prev = val; - } - row[ a.length ] = prev; - } - return row[ a.length ]; -}; -utils.testinarray = ( array, arrayreferent ) => { - // au moins un element de array existe dans arryreferent - let exist = false; - if( arrayreferent ) { - //logger.info('arrrrrrrrrrrrrrr', arrayreferent) - array.forEach( e => { - //logger.info(e) - if( arrayreferent.includes( e ) ) exist = true - } ) - } - return exist -}; -/* -DIRECTORY -*/ -const isDirectory = source => fs.lstatSync( source ) - .isDirectory(); -const getDirectories = source => fs.readdirSync( source ) - .map( name => path.join( source, name ) ) - .filter( isDirectory ); -module.exports = utils; diff --git a/package.json b/package.json index 03a9dbb..5eb81be 100755 --- a/package.json +++ b/package.json @@ -17,8 +17,8 @@ "restartpm2": "pm2 restart apxtrib.js --log-date-format 'DD-MM HH:mm:ss.SSS'", "startblockchain": "pm2 start ./models/Blockchains.js --log-date-format 'DD-MM HH:mm:ss:SSS'", "logpm2": "pm2 logs apxtrib.js --lines 200", - "setup": "node models/Setup.js", - "dev": "node apxtrib.js", + "setup": "node src/models/Setup.js", + "dev": "node src/apxtrib.js", "dev-watch": "nodemon apxtrib.js" }, "apidoc": { @@ -125,5 +125,10 @@ }, "devDependencies": { "nodemon": "^1.17.3" + }, + "standard": { + "ignore": [ + "src/setup/data/**/*.js" + ] } } diff --git a/routes/messages.js b/routes/messages.js deleted file mode 100755 index eec72ea..0000000 --- a/routes/messages.js +++ /dev/null @@ -1,63 +0,0 @@ -const express = require( 'express' ); -const path = require( 'path' ); -// Classes -const Messages = require( '../models/Messages.js' ); -// Middlewares ( prefix, object ) => { -const checkHeaders = require( '../middlewares/checkHeaders' ); -const isAuthenticated = require( '../middlewares/isAuthenticated' ); -const hasAccessrighton = require( '../middlewares/hasAccessrighton' ); -const router = express.Router(); - -router.post( '/', checkHeaders, ( req, res ) => { - /* - add message to (no authentification and accessright needs) : - a tribeid or uuid => create a contact based on email.json or phone.json or email_phone.json - if req.body.orderuuid exist then it store the req.body in /orders/orderuuid.json an order with state = order - */ - // check if a receiver is well identify if not then it send message to all user tribeid to inform ** - if( !req.body.desttribeid ) req.body.desttribeid = req.session.header.xworkon; - if( !req.body.lang ) req.body.lang = req.session.header.xlang; - logger.info( '/messages t send for ', req.session.header.xworkon ); - //logger.info(' Content: ',req.body); - const result = Messages.postinfo( req.body ); - res.status( result.status ) - .send( result.data ) -} ); - -router.put( '/:objectname/:uuid', checkHeaders, isAuthenticated, ( req, res ) => { - // message that will create an object and sendback an email. - // if objectnane/uuid_lg.json exist ans accessright is ste to U for the user then it replace object data with req.body.key value - // if does not exist and accessright C then it create it with uuid - // then if req.body.tplmessage => render email with data - // No data management are done here, if need you can add plugin to create a workflow based object - // if need specific data check => req.body.callback={tribeidpugin,pluginname,function} will run pluginname.function(data) add data run specific stuf before saved the message object in /objectname/data.uuid_lg/json - let result; - logger.info( "object", req.params.objectname ) - if( req.params.objectname == 'notifications' ) { - //uuid is a timestamp - req.body.time = req.params.uuid; - result = Messages.notification( req.body, req.session.header ); - } else { - req.body.uuid = req.params.uuid; - req.body.object = req.params.objectname; - result = Messages.object( req.body, req.session.header ); - } - //logger.info( 'result', result ); - res.status( result.status ) - .json( result.data ) -} ); - -router.get( '/user', checkHeaders, isAuthenticated, ( req, res ) => { - // run agregate for tribeid concerned - // - logger.info( "request notifiation for user", req.session.header.xpaganid ); - const app = { - tribeid: req.session.header.xapp.split( ':' )[ 0 ], - website: req.session.header.xapp.split( ':' )[ 1 ], - lang: req.session.header.xlang - }; - res.send( Messages.request( req.session.header.xtribe, req.session.header.xpaganid, - req.app.locals.tokens[ req.session.header.xpaganid ].ACCESSRIGHTS, app ) ); -} ); - -module.exports = router; diff --git a/routes/nationchains.js b/routes/nationchains.js deleted file mode 100755 index 9890e28..0000000 --- a/routes/nationchains.js +++ /dev/null @@ -1,37 +0,0 @@ -const express = require( 'express' ); -const config = require( '../tribes/townconf.js' ); - -// Classes -const Nationchains = require( '../models/Nationchains.js' ); -// Middlewares -const checkHeaders = require( '../middlewares/checkHeaders' ); -const isAuthenticated = require( '../middlewares/isAuthenticated' ); -const hasAccessrighton = require( '../middlewares/hasAccessrighton' ); -const router = express.Router(); - -/* -Manage the social world - -@Todo - -Manage a new nation -A major create a nation with at least a town => nation:{name, towns:[]} contracts/nationname.js + contracts/townsname.js -Manage a new towns in a nation => update nation:[nationname:towns:[]} contracts/townname.js - - - - - - - -*/ -router.post( '/push', checkHeaders, ( req, res ) => { - // Get information from other apixtribe instance in req.body - // check req.body.hashnext => means this is a candidate to validate next block - // - // return it's own information back with the last call to Nationchains.synchronize() - res.send( { status: 200, payload: { moreinfo: fs.readFileSync( `${config.tribes}/${config.mayorId}/nationchains/nodes/${config.rootURL}`, 'utf-8' ) } } ) -} ) - - -module.exports = router; diff --git a/routes/odmdb.js b/routes/odmdb.js deleted file mode 100644 index aa58971..0000000 --- a/routes/odmdb.js +++ /dev/null @@ -1,19 +0,0 @@ -const express = require( 'express' ); -const glob = require( 'glob' ); -const path = require( 'path' ); -// Classes -const Odmdb = require( '../models/Odmdb.js' ); -// Middlewares -const checkHeaders = require( '../middlewares/checkHeaders' ); -const isAuthenticated = require( '../middlewares/isAuthenticated' ); -const hasAccessrighton = require( '../middlewares/hasAccessrighton' ); -const router = express.Router(); - -router.get('/searchauth/:objectname/:question',checkHeaders,isAuthenticated,( req, res ) => { - logger.info( 'route referentials get all language' + req.params.objectname + '-' + req.params.question ); - const getref = Referentials.getref( true, req.params.source, req.params.idref, req.session.header.xworkon, req.session.header.xlang ); - // Return any status the data if any erreur return empty object - res.jsonp( getref.payload.data ); -} ); - -module.exports = router; diff --git a/routes/outputs.js b/routes/outputs.js deleted file mode 100755 index 6063aba..0000000 --- a/routes/outputs.js +++ /dev/null @@ -1,65 +0,0 @@ -// Upload de file -const express = require( 'express' ); -const fs = require( 'fs-extra' ); -// Classes -const UploadFile = require( '../models/UploadFiles' ); -const Outputs = require( '../models/Outputs' ); -//const Outputstest = require('../models/Outputstest'); -// Middlewares -const checkHeaders = require( '../middlewares/checkHeaders' ); -const isAuthenticated = require( '../middlewares/isAuthenticated' ); -const router = express.Router(); - - -router.post( '/ggsheet2json', checkHeaders, async ( req, res ) => { - logger.info( 'route outputs sheet to json' ); - let result = await Outputs.ggsheet2json( req.body, req.session.header ); - res.send( result ); -} ); - - - - -// checkHeaders, isuploadFileValid -router.post( '/msg', checkHeaders, async ( req, res ) => { - logger.info( 'route outputs msg post ' ); - const envoi = await Outputs.generemsg( req.body, req.session.header ); - res.status( envoi.status ) - .send( { - payload: envoi.payload - } ); -} ); -/*test functionnalité -router.post('/msgtest', checkHeaders, isemailValid, async (req, res) => { - logger.info('route outputs msg post en test'); - const envoi = await Outputstest.generemsg(req.body, req.session.header); - res.status(envoi.status).send({ - payload: envoi.payload - }); -}); -*/ -router.post( '/template', checkHeaders, ( req, res ) => { - logger.info( 'route outputs post de fichier template ' ); - // a callback can be pass to req.body to run a specific process after upload - const saveFile = UploadFile.addjson( req.body, req.session.header ); - logger.info( saveFile ); - res.send( saveFile ); - // res.send({ status: 200, payload: { info: 'fine' } }); -} ); - -router.post( '/pdf', checkHeaders, ( req, res ) => { - logger.info( 'route outputs pdf post' ); - Outputs.generepdf( req.body, req.session.header ) - .then( ( doc ) => { - res.status( doc.status ) - .download( doc.payload.data.path, doc.payload.data.name ); - } ) - .catch( ( err ) => { - logger.info( err ); - res.status( err.status ) - .send( { payload: err.payload } ); - } ); -} ); - - -module.exports = router; diff --git a/routes/pagans.js b/routes/pagans.js deleted file mode 100755 index e8f6236..0000000 --- a/routes/pagans.js +++ /dev/null @@ -1,211 +0,0 @@ -const express = require( 'express' ); -const path = require( 'path' ); - -// Classes -const Pagans = require( '../models/Pagans.js' ); -// Middlewares -const checkHeaders = require( '../middlewares/checkHeaders' ); -const isAuthenticated = require( '../middlewares/isAuthenticated' ); -const hasAccessrighton = require( '../middlewares/hasAccessrighton' ); -const router = express.Router(); -/* -models/Pagans.js -Managed: -/data/tribee/client-Id/users/uuid.json -/searchindex/emails.json {email:uuid} - /login.json {login:uuid} - /uids.json {uuid;[[ - login, - email, - encrypted psw, - accessrights]} - -ACCESSRIGHTS = { -app:{"tribeid:appname":"profil"}, -data:{"tribeid":{object:"CRUDO"}} -} -ACCESSRIGHTS is store into the token and is load into req.session.header.accessrights by hasAccessrighton() middleware - -appname is a website space object /sitewebsrc/appname -website live is strored into /dist source in /src - -This can be managed by maildigitcreator or not. -apixtribe/sitewebs/webapp is the webinterface of apixtribe - -profil: admin / manager / user are key word to give specific access to data into model. Any kind of other profil can exist. It is usefull to manage specific menu in an app. -It is also possible to authorize update a field's object depending of rule into dataManagement/object/ -{ field:X - nouserupdate: "!(['admin','manager'].includes(contexte.profil))", -} - -data allow a user to access tribeid with Create Read Update Delete Own (CRUDO) on each object of a tribeid independantly of any app. - -Create allow to create a new object respecting rules defined into /referentials/dataManagement/object/name.json -Update idem -Delete idem -Owner means it can be Write/Delete if field OWNER contain the UUID that try to act on this object. Usefull to allow someone to fully manage its objects. - -*/ -router.get( '/isauth', checkHeaders, isAuthenticated, ( req, res ) => { - if( req.session.header.xpaganid == "1" ) { - return res.status( 401 ) - .send( { info: "not authenticate" } ); - } else return res.status( 200 ) - .send( { info: "well authenticated" } ) -} ) -router.post( '/login', checkHeaders, async ( req, res ) => { - // logger.info('POST /users/login with: ', req.app.locals.header); - /* - Check un mot de passe pour un login pour obtenir un token d'authentification - valable 1 hour, 1 day - @header - @body.LOGIN - @body.PASSWORD - @checkpsw = true check si les 2 mot de passe cryptés correspondent - false bypass le contrôle et permet de générer un token - utile le temps de reinitialisé son mot de passe. - @return - */ - logger.info( 'login for ', req.body, "in", req.session.header ) - const log = await Pagans.loginUser( req.session.header, req.body, true ); - logger.info( "log user login", log ); - if( log.status == 200 ) { - // update req.app.locals.tokens for this uuid just after login success then next isAuth will be valid - req.app.locals.tokens[ log.data.user.UUID ] = { TOKEN: log.data.user.TOKEN, ACCESSRIGHTS: log.data.user.ACCESSRIGHTS } - logger.info( req.app.locals ) - } - return res.status( log.status ) - .send( log.data ); -} ); - - -router.get( '/getlinkwithoutpsw/:email', checkHeaders, async ( req, res ) => { - /* - Permet pour un email existant de renvoyer un email avec un lien valable 1h - @email est le compte pour lequel on demande un accès - Réponse: - Si email n'existe pas on n'envoie pas d'email - Si email existe on envoie un email avec un lien dont le token est valable 1h - - @return - {status:200 ou erreur , - payload:{ - info:[list de key to appear in correct requester langue], - model:'Pagans', - moreinfo: 'texte pour log ' - } - } - */ - logger.info( `GET /users/getlinkwithoutpsw for email: ${req.params.email} tribeid :${req.header('X-Client-Id')}` ); - if( !req.params.email ) { - return res.status( 404 ) - .send( { - info: [ 'emailmissing' ], - model: 'Pagans' - } ); - } else { - try { - const getlink = await Pagans.getlinkwithoutpsw( req.params.email, req.session.header ); - logger.info( 'getlink', getlink ) - //met à jour le token créer pour le uuid - req.app.locals.tokens[ getlink.data.info.xuuid ] = getlink.data.info.token; - // attention si on relance le serveur le token temporaire est perdu - return res.status( getlink.status ) - .send( getlink.data ); - } catch ( err ) { - logger.info( err ) - return res.status( 500 ) - .send( { info: [ 'errServer' ], model: 'Pagans' } ); - } - } -} ); -router.post( '/register', checkHeaders, async ( req, res ) => { - logger.info( `POST /users for ${req.session.header.xtribe}` ); - if( req.session.header.xauth == '123123' ) { - // Creation d'un utilisateur avec information de base aucun droit - // On modifie le contenu du form pour n egarder que login/email et psw - // pour le client_id permet de traiter un user en attente de validation - logger.info( 'req du post', req ); - } -} ); -router.get( '/info/:listindex', checkHeaders, isAuthenticated, hasAccessrighton( 'users', 'R' ), async ( req, res ) => { - logger.info( `get users info on tribeid ${req.session.header.xworkon} for ${req.params.listindex} with accessright`, req.session.header.accessrights.data ); - const result = await Pagans.getinfoPagans( req.session.header.xpresworkon, req.session.header.accessrights, req.params.listindex ); - res.status( result.status ) - .send( result.data ); -} ); -router.get( '/list/:filter/:field', checkHeaders, isAuthenticated, hasAccessrighton( 'users', 'R' ), async ( req, res ) => { - logger.info( 'GET /users/list/filtre/champs list for ' + req.session.header.xworkon ); - if( - [ 'admin', 'manager' ].includes( req.session.header.decodetoken[ 'apps' + req.session.header.xworkon + 'profil' ] ) ) { - try { - const userslist = await Pagans.getUserlist( req.session.header, req.params.filter, req.params.field ); - logger.info( 'userslist', userslist ); - if( userslist.status == 200 ) { - return res.status( userslist.status ) - .send( userslist.data ); - } - } catch ( err ) { - logger.info( err ); - return res.status( 400 ) - .send( { info: 'erreur' } ); - } - } else { - res.status( 403 ) - .send( { - info: [ 'forbiddenAccess' ], - model: 'Pagans' - } ); - } -} ); -router.get( '/uuid/:id', checkHeaders, isAuthenticated, hasAccessrighton( 'users', 'R' ), async ( req, res ) => { - logger.info( `GET /users/uuid/${req.params.id}` ); - //logger.info('req.app.locals: ', req.app.locals); - //logger.info('req.session', req.session); - const result = await Pagans.getUser( req.params.id, req.session.header.xworkon, req.session.header.accessrights ); - res.status( result.status ) - .send( result.data ); -} ); -router.put( '/chgpsw/:id', checkHeaders, isAuthenticated, async ( req, res ) => { - logger.info( `PUT update /users/chgpsw/${req.params.id}` ); - try { - const majpsw = await Pagans.updateUserpassword( req.params.id, req.session.header, req.body ); - res.status( majpsw.status ) - .send( majpsw.data ); - } catch ( { - status, - data - } ) { - res.status( status ) - .send( data ); - } -} ); -router.post( '/uuid', checkHeaders, isAuthenticated, hasAccessrighton( 'users', 'C' ), async ( req, res ) => { - logger.info( 'POST /users create for ' + req.session.header.xworkon, req.body ); - const usercreate = await Pagans.createUser( req.session.header, req.body ); - return res.status( usercreate.status ) - .send( usercreate.data ); -} ); -router.put( '/uuid/:id', checkHeaders, isAuthenticated, hasAccessrighton( 'users', 'U' ), async ( req, res ) => { - logger.info( `PUT update /users/${req.params.id}` ); - // logger.info('req.app.locals: ', req.app.locals); - // logger.info('req.session', req.session); - try { - const majUser = await Pagans.updateUser( req.params.id, req.session.header, req.body ); - res.status( majUser.status ) - .send( majUser.data ); - } catch ( { - status, - data - } ) { - res.status( status ) - .send( data ); - } -} ); -router.delete( '/uuid/:id', checkHeaders, isAuthenticated, hasAccessrighton( 'users', 'D' ), ( req, res ) => { - logger.info( `DELETE /users/uuid/${req.params.id}` ); - const result = Pagans.deleteUser( req.params.id, req.session.header ); - res.status( result.status ) - .send( result.data ); -} ); -module.exports = router; diff --git a/routes/referentials.js b/routes/referentials.js deleted file mode 100755 index 209f3c8..0000000 --- a/routes/referentials.js +++ /dev/null @@ -1,94 +0,0 @@ -// Upload de file -const express = require( 'express' ); -const glob = require( 'glob' ); -const path = require( 'path' ); -// Classes -const Referentials = require( '../models/Referentials' ); -// Middlewares -const checkHeaders = require( '../middlewares/checkHeaders' ); -const isAuthenticated = require( '../middlewares/isAuthenticated' ); -const hasAccessrighton = require( '../middlewares/hasAccessrighton' ); -const router = express.Router(); -/* - * keylist = list of key at 1st level in clientconf.json separated by _ - * we use header.xworkon - * To manage AccesRight obkect referentials does not follow the same logic than other object this is why - */ -router.get( '/clientconf/:keylist', checkHeaders, isAuthenticated, ( req, res ) => { - // retourne liste info (non sensible) du tribeid inside headers.xworkon sur keylist ="key1_key2" - /* - if (req.session.header.accessrights.data[ "Alltribeid" ] && req.session.header.accessrights.data[ "Alltribeid" ].referentials.includes('R') ; - */ - logger.info( `get clientconf for ${req.session.header.xworkon} on ${req.params.keylist}` ) - let dataref = {} - if( req.params.keylist.split( '_' ) - .length > 0 ) { - const ref = Referentials.clientconf( req.session.header.xworkon, req.params.keylist.split( '_' ) ) - if( ref.status == 200 ) { - dataref = ref.payload.data; - } else { - logger.info( "erreur ", ref ) - } - } - logger.info( 'envoie en jsonp: dataref' ) - res.jsonp( dataref ) -} ); -router.get( '/clientconfglob', checkHeaders, isAuthenticated, ( req, res ) => { - res.jsonp( Referentials.clientconfglob() - .payload.data ); -} ); -router.get( '/contentlist/:source', checkHeaders, isAuthenticated, - ( req, res ) => { - const payload = []; - logger.info( req.params.source, `${config.tribes}/${req.session.header.xworkon}/referentials/dataManagement/${req.params.source}/*.json` ) - glob.sync( `${config.tribes}/${req.session.header.xworkon}/referentials/dataManagement/${req.params.source}/*.json` ) - .forEach( f => { - payload.push( path.basename( f, '.json' ) ); - } ) - res.json( payload ); - } ); -router.get( '/contentfull/:source/:idref', checkHeaders, isAuthenticated, - ( req, res ) => { - //only for data and object - logger.info( 'route referentials get all language' + req.params.source + '-' + req.params.idref ); - const getref = Referentials.getref( true, req.params.source, req.params.idref, req.session.header.xworkon, req.session.header.xlang ); - // Return any status the data if any erreur return empty object - res.jsonp( getref.payload.data ); - } ); -router.get( '/content/:source/:idref', checkHeaders, isAuthenticated, - ( req, res ) => { - logger.info( 'route referentials get ' + req.params.source + '-' + req.params.idref ); - const getref = Referentials.getref( false, req.params.source, req.params.idref, req.session.header.xworkon, req.session.header.xlang ); - res.jsonp( getref.payload.data ); - } ); -// get with no authentification -router.get( '/contentnoauth/:source/:idref', checkHeaders, - ( req, res ) => { - logger.info( 'route referentials get ' + req.params.source + '-' + req.params.idref ); - // @TODO check access right in clientconf before sending back json file - const getref = Referentials.getref( false, req.params.source, req.params.idref, req.session.header.xworkon, req.session.header.xlang ); - res.jsonp( getref.payload.data ); - } ); -router.get( '/lg', ( req, res ) => { - logger.info( req.headers[ "accept-language" ] ) - let lg = '??'; - if( req.headers[ "accept-language" ] && req.headers[ "accept-language" ].split( ',' ) - .length > 0 ) { - lg = req.headers[ "accept-language" ].split( ',' )[ 0 ]; - } - res.json( { lg } ) -} ); -router.put( '/content/:source/:idref', checkHeaders, isAuthenticated, ( req, res ) => { - logger.info( `route put content for ${req.params.idref} that is a ${req.params.source}` ); - const putref = Referentials.putref( req.params.source, req.params.idref, req.session.header.xworkon, req.body ) - return res.status( putref.status ) - .send( { payload: putref.payload } ) -} ); -//hasAccessrighton( 'referentials', 'U' ) -router.get( '/updatefull', checkHeaders, isAuthenticated, hasAccessrighton( 'referentials', 'U' ), ( req, res ) => { - logger.info( `route get to force update content updatefull is accessrighton` ); - const updtref = Referentials.updatefull( req.session.header.xworkon ) - return res.status( updtref.status ) - .send( { payload: updtref.payload } ) -} ); -module.exports = router; diff --git a/routes/tags.js b/routes/tags.js deleted file mode 100755 index d890835..0000000 --- a/routes/tags.js +++ /dev/null @@ -1,29 +0,0 @@ -//Installation d'un tag -/* - - - -*/ -// Upload de file -const express = require('express'); -// Classes -const Tags = require('../models/Tags'); -// Middlewares -const router = express.Router(); -router.get('/:filename', (req, res) => { - //logger.info('route tags get ', req.params.filename); - const savetag = Tags.getfile(req.params.filename, req); - if(savetag.status == 200) { - res.sendFile(savetag.payload.filename); - } else { - res.status(savetag.status) - .send({ payload: savetag.payload }) - } -}) -router.post('/:tribeid', (req, res) => { - //logger.info('route tags post ', req.params.tribeid); - const savetag = Tags.savehits(req); - res.status(200) - .send(''); -}) -module.exports = router; diff --git a/routes/tribes.js b/routes/tribes.js deleted file mode 100755 index 7f1e2cf..0000000 --- a/routes/tribes.js +++ /dev/null @@ -1,374 +0,0 @@ -const express = require( 'express' ); -const fs = require( 'fs-extra' ); -const path = require( 'path' ); -const config = require( '../tribes/townconf.js' ); - -// Classes -const Tribes = require( '../models/Tribes.js' ); -// Middlewares -const checkHeaders = require( '../middlewares/checkHeaders' ); -const isAuthenticated = require( '../middlewares/isAuthenticated' ); -const hasAccessrighton = require( '../middlewares/hasAccessrighton' ); -const router = express.Router(); - - -router.get( '/clientconf/:tribeid', checkHeaders, isAuthenticated, ( req, res ) => { - /* - get a clientconf.json for a tribeid depending of user accessright - if tribeid == all and user is admin of apixtribe => get /tmp/clientconfglob.json - req.session.header.accessrights, req.session.header.apixpaganid - */ - logger.info( `Tribes/clientconf for tribeid:${req.params.tribeid}` ) - if( req.params.tribeid == "all" && req.session.header.accessrights.data.apixtribe && req.session.header.accessrights.data.apixtribe.tribeid && req.session.header.accessrights.data.apixtribe.tribeid.includes( 'R' ) ) { - res.status( 200 ) - .send( { moreinfo: fs.readJsonSync( `${config.tmp}/clientconfglob.json`, 'utf-8' ) } ); - return; - } - if( req.session.header.accessrights.data[ req.params.tribeid ] && - req.session.header.accessrights.data[ req.params.tribeid ].tribeid && - req.session.header.accessrights.data[ req.params.tribeid ].tribeid.includes( 'R' ) && - fs.existsSync( `${config.tribes}/${req.params.tribeid}/clientconf.json` ) ) { - // const conftribeid = { moreinfo: {} } - // conftribeid.moreinfo[ req.params.tribeid ] = fs.readJsonSync( `${config.tribes}/${req.params.tribeid}/clientconf.json`, 'utf-8' ); - res.status( 200 ) - .send( { moreinfo: [ fs.readJsonSync( `${config.tribes}/${req.params.tribeid}/clientconf.json`, 'utf-8' ) ] } ); - return; - } - // if not authorized or dos not exist return empty - // no specific message is send for security reason (check only log) - res.status( 403 ) - .send( { info: [ 'forbidenAccess' ], models: 'Tribes' } ) - .end(); -} ) -router.put( '/', checkHeaders, isAuthenticated, ( req, res ) => { - logger.info( 'Create a new tribeid, with a useradmin' ) - logger.info( ' send data = clientconf.json with all parameter.' ) - // !!!!! check for security any ; \n or so because data can be used into shell - const add = Tribes.create( req.body ); - res.status( add.status ) - .send( add.payload ) -} ) -router.delete( '/archivetribeid/:tribeid', checkHeaders, isAuthenticated, ( req, res ) => { - logger.info( "request archive tribeid" ) - const archive = Tribes.archive( req.params.tribeid ); - res.status( archive.status ) - .send( archive.payload ) -} ); -router.post( '/spaceweb', checkHeaders, isAuthenticated, ( req, res ) => { - // !!!!! check for security any ; \n or so because data can be used into shell - logger.info( 'Create a new webapp for xworkon ' ) - req.body.tribeid = req.session.header.xworkon; - const add = Tribes.addspaceweb( req.body ) - res.status( add.status ) - .send( add.payload ) -} ) -router.get( '/spaceweb/components/:tribeid/:website/:key', checkHeaders, ( req, res ) => { - // check if key is valid before continue - // exemple: get Tribes/spaceweb/components/ndda/mesa/123?rep=appmesatable/appsimpletable.mustache - const file = `${config.tribes}/${req.params.tribeid}/spacedev/${req.params.website}/src/ctatic/components/${req.query.path}` - logger.info( `Request components file from ${file}` ) - if( fs.existsSync( file ) ) { - res.sendFile( file ); - } else { - res.send( `console.error("Missing components file in ${req.params.tribeid}/spacedev/${req.params.website}/src/ctatic/components/${req.query.path}");` ); - } -} ) -router.get( '/plugins/:tribeid/:pluginname/:key/:filename', ( req, res ) => { - // No accessright possible cause it is load on the fly - // @todo Check key to authorize access to the plugin (key comme from user ACCESSRIGHTS[tribeid plugin owner:pluginname]).key - // return a file into /:tribeid owner of plugin/plugins/:pluginname/components/:filename - // if not exist or invalid key then return console.error - const file = `${config.tribes}/${req.params.tribeid}/plugins/${req.params.pluginname}/components/${req.params.filename}` - logger.info( 'Tribes/plugins/ ', file ) - if( fs.existsSync( file ) ) { - res.sendFile( file ); - } else { - res.send( `console.error("Missing plugin file in ${req.params.tribeid}/plugins/${req.params.pluginname}/components/${req.params.filename}");` ); - } -} ); - -router.get( '/dirls', checkHeaders, isAuthenticated, ( req, res ) => { - // url /Tribes/dirls?rep=referentials/dataManagement - // request information about a req.query.rep from header xworkon/ - // return - // {file:[{}],dir:[{}]} - // @todo check if isAuthorized and exist - - logger.info( 'request dirls', `${config.tribes}/${req.session.header.xworkon}/${req.query.rep}` ); - if( !fs.existsSync( `${config.tribes}/${req.session.header.xworkon}/${req.query.rep}` ) ) { - res.status( 404 ) - .send( { 'info': [ 'dirnotexist' ], model: 'Tribes' } ); - } - const info = Tribes.dirls( req.session.header.xworkon, req.query.rep ); - logger.info( info ) - res.status( info.status ) - .send( info.payload ); -} ) -router.delete( '/ls', checkHeaders, isAuthenticated, ( req, res ) => { - // check Accessright with D or O on each - // url /Tribes/ls - // req.body.files=[listfiles file to delete ] - const authfiles = Tribes.checkaccessfiles( req.body, 'D', req.session.header.accessrights, req.session.header.apixpaganid ); - authfiles.ok.forEach( f => { fs.remove( `${config.tribes}/${f}` ); } ) - res.status( 200 ) - .send( { 'info': [ 'fileauthdeleted' ], models: 'Tribes', moreinfo: authfiles } ) -} ); -router.put( '/sendjson', checkHeaders, isAuthenticated, ( req, res ) => { - //req.body = {object:spacedev, path:website/src/data/tpldataname_lg.json, data:{...}} - //logger.info( req.body ) - const dest = `${config.tribes}/${req.session.header.xworkon}/${req.body.object}/${req.body.path}`; - logger.info( `Send json to saved to ${dest}` ); - if( !( req.body.object && fs.existsSync( `${config.tribes}/${req.session.header.xworkon}/${req.body.object}` ) ) ) { - res.status( '404' ) - .send( { info: [ 'objectmissiong' ], models: 'Tribes', moreinfo: `object: ${req.body.object} does not exist req.body must {object, data, path} into data ${req.session.header.xworkon}/${req.body.object}` } ) - } else { - if( fs.existsSync( `${config.tribes}/${req.session.header.xworkon}/${req.body.object}/${req.body.path}` ) ) { - // exist so can be update check accessright update on this - hasAccessrighton( req.body.object, "U" ); - } else { - hasAccessrighton( req.body.object, "C" ); - } - fs.outputJsonSync( dest, req.body.data ); - res.status( 200 ) - .send( { info: [ 'filesaved' ], models: 'Tribes' } ) - } -} ); -router.post( '/downloadls', checkHeaders, isAuthenticated, ( req, res ) => { - // midlleware hasAccessrighton.js is not apply here only to access/update/create information inside an object - // to get file a user need accessrights to data: object: R or to Own it - // or if exist a .info.json into folder get shared as R in uuid - - //req.body contain list of path file or folder if only 1 file then download it, otherwise zip list and send zip file - - const authfiles = Tribes.checkaccessfiles( req.body.files, 'R', req.session.header.accessrights, req.session.header.xpaganid ); - if( authfiles.ok.length == 1 ) { - // bidouille en attendnat de faire un .zip binaire propre - if( !authfiles.ok[ 0 ].includes( '.xml' ) ) { - res.status( 200 ) - .download( `${config.tribes}/${authfiles.ok[0]}`, authfiles.ok[ 0 ] ); - } else { - fs.copySync( `${config.tribes}/${authfiles.ok[0]}`, `${config.tribes}/${config.mayorId}/www/app/webapp/static/tmp/${authfiles.ok[ 0 ]}` ) - } - } else if( authfiles.ok.length > 1 ) { - // on zip et on envoie - //res.status( 200 ) - // .download( `${config.tribes}/${authfiles.ok[0]}`, authfiles.ok[ 0 ]) - res.status( 200 ) - .attachment( `${config.tribes}/${authfiles.ok[0]}` ); - - } else { - req.body.filepon - res.status( 403 ) - .send( 'Forbidden access' ) - } -} ); -router.post( '/upfilepond', checkHeaders, isAuthenticated, ( req, res ) => { - logger.info( 'post /Tribes/uploadfilepond' ); - // Store file and return a unique id to save button - // that provide folder where to store it - const formidable = require( 'formidable' ); - const form = formidable( { multiples: false } ); - form.parse( req, ( err, fields, files ) => { - if( err ) { next( err ); return; } - //logger.info( 'fields',fields); - // fileMetadaObject send - let context = JSON.parse( fields.filepond ); - let idfile = files.filepond.path; - let name = files.filepond.name; - let subfolder = context.subfolder; - name = name.replace( /[ ,'"’]/g, "_" ); - //logger.info( 'files.filepond:', files.filepond ); - logger.info( idfile, `${config.tribes}/${req.session.header.xworkon}/www/${subfolder}/${name}` ) - // On le supprime s'il existe deja - fs.removeSync( `${config.tribes}/${req.session.header.xworkon}/www/${subfolder}/${name}` ); - // mv tmp - fs.moveSync( idfile, `${config.tribes}/${req.session.header.xworkon}/www/${subfolder}/${name}` ); - //res.status(200).send({models:"Tribes",info:["Savedsuccess"],moreinfo:{id:file.filepond.path}}) - //return for filepond - res.writeHead( 200, { 'Content-Type': 'text/plain' } ); - res.end( idfile ); - } ) -} ); -router.delete( '/file', checkHeaders, isAuthenticated, ( req, res ) => { - //src = objectfolder with accessright/... - //hasAccessrighton( "www", "D" ), - if( !req.query.src ) { - res.status( 404 ) - .send( { info: [ 'deleteerror' ], models: "Tribes", moreinfo: "your del req need a src" } ) - return; - }; - hasAccessrighton( req.query.src.split( '/' )[ 0 ], "D" ); - logger.info( 'Remove file', `${config.tribes}/${req.session.header.xworkon}/${req.query.src}` ) - logger.info( req.body ) - fs.removeSync( `${config.tribes}/${req.session.header.xworkon}/${req.query.src}` ); - res.status( 200 ) - .send( { info: [ 'Successfullremove' ], models: "Tribes" } ) -} ); -router.post( '/uploadfile', checkHeaders, isAuthenticated, ( req, res ) => { - logger.info( 'upload a file ' ) - /* Authentification is needed to get a TOKEN - curl -X POST -H "xtribe: apixtribe" -H "xworkon: pvmsaveurs" -H "xlang: fr" -H "xpaganid: 1" -H "xauth: 1" -H "xapp: pvmsaveurs:pvmsaveurs" -H "Content-Type: application/json" -d '{"LOGIN":"adminapixtribe","PASSWORD":"Trze3aze!"}' http://pvmsaveurs.pvmsaveurs.fr/app/users/login - if exist replace xpaganidTOKEN with payload.TOKEN value - - curl -H "xtribe: pvmsaveurs" -H "xworkon: pvmsaveurs" -H "xlang: fr" -H "xpaganid: adminapixtribe" -H "xauth: xpressuuisToken" -H "xapp: pvmsaveurs:pvmsaveurs" -F 'data=@filename.xx' http://pvmsaveurs.pvmsaveurs.fr/app/Tribes/uploadfile - */ - const formidable = require( 'formidable' ); - const form = formidable( { multiples: false } ); - form.parse( req, function ( err, fields, files ) { - //logger.info( files.data ) - var oldPath = files.data.path; - var newPath = `${config.tribes}/${req.session.header.xworkon}/${clientconf.uploadzip[files.data.name].dest}`; - logger.info( 'oldPath', oldPath ) - logger.info( 'newPath', newPath ) - var rawData = fs.readFileSync( oldPath ) - fs.outputFile( newPath, rawData, function ( err ) { - if( err ) { - logger.info( err ); - return res.status( 405 ) - .send( { info: [ 'savederror' ], models: "Tribes", moreinfo: "your file was not able to be saved into the server" } ) - } else { - return res.status( 200 ) - .send( { - info: [ "successfullsent" ], - models: "Tribes" - } ); - } - } ) - } ); -} ); -router.post( '/uploadzip', checkHeaders, ( req, res ) => { - logger.info( 'uploadzip a file ' ) - - /* no authentification to upload a zip filename into /tribes/${xworkon}/${clientconf.uploadzip[filename].dest} - unzip it using the password ${clientconf.uploadzip[filename].psw - if no error then run the callback ${clientconf.uploadzip[filename].callback - but a password to unzip - in clientconf.json need to be set - "uploadzip": { - "articlesTribespvm.zip": { - "comment": "unzip with overwrite if same name", - "psw": "azPI1209qtrse", - "dest": "importexport/tmp", - "unzipoption": "-aoa", - "callback": "importexport/integrationitem.js" - } - }, - Example: - cd where zip file is stored - curl -H "xtribe: pvmsaveurs" -H "xworkon: pvmsaveurs" -H "xlang: fr" -H "xpaganid: adminapixtribe" -H "xauth: 1" -H "xapp: pvmsaveurs:pvmsaveurs" -F 'data=@articlesTribespvm.zip' http://pvmsaveurs.pvmsaveurs.fr/app/Tribes/uploadzip - - */ - const clientconf = fs.readJSONSync( `${config.tribes}/${req.session.header.xworkon}/clientconf.json` ) - if( !clientconf.uploadzip ) { - return res.status( '404' ) - .send( { info: [ "missconf" ], models: "Tribes", moreinfo: `no uploadzip in clientconf for ${req.session.header.xworkon} please contact apixtribe admin ` } ); - }; - const uploadzip = clientconf.uploadzip; - const formidable = require( 'formidable' ); - const form = formidable( { multiples: false } ); - form.parse( req, function ( err, fields, files ) { - //logger.info( files.data ) - var oldPath = files.data.path; - if( !Object.keys( clientconf.uploadzip ) - .includes( files.data.name ) ) { - return res.status( 403 ) - .send( { info: [ "notAllowed" ], models: "Tribes", moreinfo: `file ${files.data.name} not allowed to be upload` } ) - } else { - logger.info( "context:", clientconf.uploadzip[ files.data.name ] ) - var newPath = `${config.tribes}/${req.session.header.xworkon}/${clientconf.uploadzip[files.data.name].dest}`; - //logger.info( 'oldPath', oldPath ) - //logger.info( 'newPath', `${newPath}/${files.data.name}` ) - fs.moveSync( oldPath, `${newPath}/${files.data.name}`, { overwrite: true } ); - const cp = require( 'child_process' ); - //logger.info( `7z e -p${clientconf.uploadzip[ files.data.name ].psw} ${newPath}/${files.data.name}` ); - logger.info( '7z', [ 'e', `-p${clientconf.uploadzip[ files.data.name ].psw}`, `${newPath}/${files.data.name}`, `-o${config.tribes}/${req.session.header.xworkon}/${clientconf.uploadzip[ files.data.name ].dest}`, clientconf.uploadzip[ files.data.name ].unzipoption ] ); - var newFiles = cp.spawnSync( '7z', [ 'e', `-p${clientconf.uploadzip[ files.data.name ].psw}`, `${newPath}/${files.data.name}`, `-o${config.tribes}/${req.session.header.xworkon}/${clientconf.uploadzip[ files.data.name ].dest}`, clientconf.uploadzip[ files.data.name ].unzipoption ] ); - logger.info( newFiles.output.toString() ) - if( newFiles.output.toString() - .includes( 'Everything is Ok' ) ) { - if( clientconf.uploadzip[ files.data.name ].callback ) { - const integ = require( `${config.tribes}/${req.session.header.xworkon}/${clientconf.uploadzip[files.data.name].callback}` ) - .run(); - logger.info( 'integration', integ ) - return res.status( integ.status ) - .send( integ.payload ); - } else { - return res.status( 200 ) - .send( { - info: [ "successfullsent" ], - models: "Tribes" - } ); - } - } else { - return res.status( 400 ) - .send( { - info: [ "zipfileerror" ], - models: "Tribes", - moreinfo: newFiles.output.toString() - } ) - } - } - } ) -} ); - -router.post( '/upload', checkHeaders, isAuthenticated, ( req, res ) => { - 1 // ACHANGER VIA usage sendjson - // url /Tribes/upload?save=tmp&rep=referentials/dataManagement - // if save=tmp then store in a tmp file - // if save=ok then mv the tmp file to the folder - // midlleware hasAccessrighton.js is not apply here only to access/update/create information inside an object - // to upload a file a user need accessrights to data: object: C or to Own it - // or if dir.file exist a .info.json into folder get shared as C in uuid accessright - /* - to add in front -
- - -
- */ - logger.info( 'Envoie image' ) - logger.info( 'body', req.body ); - logger.info( 'params', req.params ); - //const authfolder = Tribes.checkaccessfiles( req.params.rep, 'C', req.session.header.accessrights, req.session.header.xpaganid ); - // cheack autorisation to create or replace a file for this accessrights user - const authfolder = { ok: "tt" } - if( authfolder.ok ) { - if( req.params.save == 'file' ) { - if( fs.existsSync( req.body.filepond ) ) { - fs.mv( req.body.filepond, req.params.rep ); - } - }; - // voir si c'est toujours pertinent car upload est géré par filepond pour les image - if( req.params.save == 'upload' ) { - const form = formidable( { multiples: false } ); - form.parse( req, ( err, fields, files ) => { - if( err ) { next( err ); return; } - let thefile = files.filebond.path; - fs.outputFileSync() - logger.info( 'thefile:' + thefile ); - res.writeHead( 200, { 'Content-Type': 'text/plain' } ); - res.end( theFile ); - } ) - } - } else { - res.status( 403 ) - .send( 'forbiden access' ); - } -} ); -/* -Manage tribeid into /data/tribee/tribeid -client space dedicated - -@Todo -clientconfglob copy cut from Referentials.clientconfglob -clientconf.json copy cut from Referentials.clientconf -list of tribeid copy cut from Referentials. -Add a tribeid -update clientconf - - -*/ - - - -module.exports = router; diff --git a/routes/uploadFiles.js b/routes/uploadFiles.js deleted file mode 100755 index e785f3a..0000000 --- a/routes/uploadFiles.js +++ /dev/null @@ -1,49 +0,0 @@ -// Upload de file -const express = require( 'express' ); -const path = require( 'path' ); -const jsonfile = require( 'jsonfile' ); -const fs = require( 'fs' ); - -// Classes -const UploadFile = require( '../models/UploadFiles' ); -// Middlewares -const checkHeaders = require( '../middlewares/checkHeaders' ); -const isAuthenticated = require( '../middlewares/isAuthenticated' ); -const router = express.Router(); - -router.post( '/', checkHeaders, ( req, res ) => { - logger.info( 'route uploadFile post ' ); - const saveFile = UploadFile.add( req, req.session.header ); - res.send( saveFile ); - // res.send({ status: 200, payload: { info: 'fine' } }); -} ); - -router.post( '/json', checkHeaders, ( req, res ) => { - logger.info( 'route uploadFile post de fichier json ' ); - // a callback can be pass to req.body to run a specific process after upload - const saveFile = UploadFile.addjson( req.body, req.session.header ); - logger.info( saveFile ); - res.send( saveFile ); - // res.send({ status: 200, payload: { info: 'fine' } }); -} ); - -router.get( '/:filename', checkHeaders, isAuthenticated, ( req, res ) => { - logger.info( 'route uploadFile get ', req.params.filename ); - const pushFile = UploadFile.get( - req.params.filename.replace( /______/g, '/' ), - req.session.header - ); - if( pushFile.status == 200 ) { - if( path.extname( pushFile.payload.file ) === '.json' ) { - jsonfile.readFile( pushFile.payload.file, ( err, p ) => { - if( err ) console.error( err ); - res.jsonp( p ); - } ); - } else { - res.download( pushFile.payload.file, path.basename( pushFile.payload.file ) ); - } - } else { - res.send( pushFile ); - } -} ); -module.exports = router; diff --git a/setup/data/domain/apixpress/www/app/webapp/js/auth.js b/setup/data/domain/apixpress/www/app/webapp/js/auth.js deleted file mode 100755 index 31055a8..0000000 --- a/setup/data/domain/apixpress/www/app/webapp/js/auth.js +++ /dev/null @@ -1,216 +0,0 @@ -"use strict"; -var pwa = pwa || {}; -/* -Manage user authentification and registration -________________________ -pwa.auth.route() - manage from state.json route if authenticated or not - redirect public page or app page -________________________ -pwa.auth.screenlogin() - show login modal -________________________ -pwa.auth.getlinkwithoutpsw() - special get with token and uuid workeable for 24h this link is une onetime -_________________________ -pwa.auth.isAuthenticate() - test if token is still ok or not return false/true -_________________________ -pwa.auth.authentification({LOGIN,PASSWORD}) - if ok => load pwa.state.data.app .headers .userlogin -_________________________ -pwa.auth.login() - Manage login modal to get login psw value and submit it to pwa.auth.authentification() -_________________________ -pwa.auth.logout() - Remove localstorage and reload -_________________________ -pwa.auth.register() - @TODO -__________________________ -pwa.auth.forgetpsw() - Request to send an email with a unique get link to access from this link to the app - -*/ -/*MODULEJS*/ -//--## -pwa.auth = {}; -// Refresh browser state if exist else get pwa.state defaults -//pwa.state.ready( pwa.auth.check ); - -pwa.auth.check = () => { - if( pwa.state.data.login.isAuthenticated ) { - if( !pwa.auth.isAuthenticate() ) { - // Then reinit local storage and refresh page - pwa.state.data.login.isAuthenticated = false; - pwa.state.save(); - //alert( 'reload page cause no more auth' ) - window.location.reload(); - }; - } -}; -pwa.auth.route = ( destination ) => { - logger.info( 'auth.route to', destination ); - //if check Authenticated && exist #signin button[data-routeto] then redirect browser to button[data-routeto] - //else manage component action auth - if( pwa.state && pwa.state.data && pwa.state.data.login && pwa.state.data.login.isAuthenticated ) { - if( destination ) - window.location.pathname = `${pwa.state.data.ctx.urlbase}/${destination}`; - } else { - [ "#signin", "#resetpsw", "#register" ].forEach( e => { - if( e == destination ) { - document.querySelector( e ) - .classList.remove( 'd-none' ); - } else { - document.querySelector( e ) - .classList.add( 'd-none' ); - } - } ) - } -} -pwa.auth.isAuthenticate = async function () { - // in any request, if middleware isAuthenticated return false - // then headers Xuuid is set to 1 - // then try pwa.auth.isAuthenticate if rememberMe auto reconnect - // if jwt is ok then return true in other case => false - // this is the first test then depending of action see ACCESSRIGHTS of user - logger.info( 'lance isauth', { - headers: pwa.state.data.headers.xpaganid - } ) - //alert( 'uuid ' + pwa.state.data.headers.xpaganid ) - logger.info( `https://${pwa.state.data.ctx.urlbackoffice}/users/isauth`, { - headers: pwa.state.data.headers - } ) - try { - const repisauth = await axios.get( `https://${pwa.state.data.ctx.urlbackoffice}/users/isauth`, { - headers: pwa.state.data.headers - } ) - logger.info( repisauth ) - logger.info( 'isAauthenticate: yes' ) - return true; - } catch ( err ) { - if( err.response ) { logger.info( "response err ", err.response.data ) } - if( err.request ) { logger.info( "request err", err.request ) } - logger.info( 'isAuthenticate: no' ) - pwa.state.data.headers.xpaganid = "1"; - if( pwa.state.data.login.rememberMe.login ) { - if( await pwa.auth.authentification( pwa.state.data.login.rememberMe ) ) { - return await pwa.auth.isAuthenticate(); - }; - } - return false; - } -}; -pwa.auth.authentification = async function ( data ) { - // Core client function to chech auth from login & psw - // In case of 403 error lauch pwa.authentification(pwa.app.rememberMe) - // in case of sucess update paw.state.data.login - console.groupCollapsed( "Post Authentification for standard on : https://" + pwa.state.data.ctx.urlbackoffice + "/users/login param data", data ) - - logger.info( 'header de login', pwa.state.data.headers ) - let auth; - try { - auth = await axios.post( `https://${pwa.state.data.ctx.urlbackoffice }/users/login`, data, { - headers: pwa.state.data.headers - } ); - logger.info( "retour de login successfull ", auth ); - //Maj variable globale authentifié - pwa.state.data.headers.xpaganid = auth.data.payload.data.UUID; - pwa.state.data.headers.xauth = auth.data.payload.data.TOKEN; - pwa.state.data.headers.xtribe = auth.data.payload.data.tribeid; - pwa.state.data.headers.xworkon = auth.data.payload.data.tribeid; - // Save local authentification uuid/token info user - pwa.state.data.login.user = auth.data.payload.data; - //request a refresh after a login - pwa.state.data.ctx.refreshstorage = true; - pwa.state.save(); - //alert( 'pwa.state.save() fait avec uuid' + pwa.state.data.headers.xpaganid ) - console.groupEnd(); - return true; - } catch ( err ) { - if( err.response ) { logger.info( "resp", err.response.data ) } - if( err.request ) { logger.info( "req", err.request.data ) } - logger.info( 'erreur de login reinit de rememberMe', err ) - pwa.state.data.login.rememberMe = {}; - document.querySelector( "#signin p.msginfo" ) - .innerHTML = document.querySelector( "#signin [data-msgko]" ) - .getAttribute( 'data-msgko' ); - console.groupEnd(); - return false; - } -}; -pwa.auth.logout = function () { - logger.info( "remove ", pwa.state.data.ctx.website ); - localStorage.removeItem( pwa.state.data.ctx.website ); - window.location.href = "/"; -} -pwa.auth.login = async function () { - /* - Check login/psw - see auth.mustache & data_auth_lg.json for parameters - Context info used: - #signin p.msginfo contain message interaction with user - #signin data-msgok data-msgko - #signin button[data-routeto] is a redirection if authentification is successful - */ - document.querySelector( '#signin p.msginfo' ) - .innerHTML = ""; - const data = { - LOGIN: document.querySelector( "#signin input[name='login']" ) - .value, - PASSWORD: document.querySelector( "#signin input[name='password']" ) - .value - } - logger.info( 'check password', checkdata.test.password( "", data.PASSWORD ) ) - if( data.LOGIN.length < 4 || !checkdata.test.password( "", data.PASSWORD ) ) { - /*$("#loginpart p.msginfo") - .html("") - .fadeOut(2000)*/ - document.querySelector( '#signin p.msginfo' ) - .innerHTML = document.querySelector( '#signin [data-msgko]' ) - .getAttribute( 'data-msgko' ); - } else { - if( document.querySelector( "[name='rememberme']" ) - .checked ) { - pwa.state.data.login.rememberMe = data; - } - if( await pwa.auth.authentification( data ) ) { - logger.info( 'Authentification VALIDE' ) - document.querySelector( '#signin p.msginfo' ) - .innerHTML = document.querySelector( "#signin [data-msgok]" ) - .getAttribute( 'data-msgok' ); - //state l'état isAuthenticated et check la route - pwa.state.data.login.isAuthenticated = true; - pwa.state.save(); - logger.info( pwa.state.data.login ) - logger.info( 'Auth ok route to ', document.querySelector( '#signin button[data-routeto]' ) - .getAttribute( 'data-routeto' ) ); - pwa.auth.route( document.querySelector( '#signin button[data-routeto]' ) - .getAttribute( 'data-routeto' ) ); - } - } -}; -pwa.auth.register = async function ( event ) { - event.preventDefault(); - // gérer la cration du user -} -pwa.auth.forgetpsw = async function ( event ) { - event.preventDefault(); - const tribeid = $( ".loginregister" ) - .getAttribute( "data-tribeid" ); - const email = $( '.forgetpsw .email' ) - .val(); - logger.info( `Reinit email: ${email} for tribeid: ${tribeid}` ) - try { - logger.info( `https://${pwa.state.data.ctx.urlbackoffice }/users/getlinkwithoutpsw/${email}` ) - const reinit = await axios.get( `https://${pwa.state.data.ctx.urlbackoffice }/users/getlinkwithoutpsw/${email}`, { - headers: pwa.state.data.headers - } ) - $( "#forgetpswpart p.msginfo" ) - .html( "Regardez votre boite email" ); - return true; - } catch ( er ) { - logger.info( "Pb d'accès au back check apiamaildigit" ) - return false; - } -}; diff --git a/setup/data/domain/apixpress/www/app/webapp/js/axios.min.js b/setup/data/domain/apixpress/www/app/webapp/js/axios.min.js deleted file mode 100755 index c7b4b0d..0000000 --- a/setup/data/domain/apixpress/www/app/webapp/js/axios.min.js +++ /dev/null @@ -1,9 +0,0 @@ -/* axios v0.18.1 | (c) 2019 by Matt Zabriskie */ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){e.exports=n(1)},function(e,t,n){"use strict";function r(e){var t=new i(e),n=s(i.prototype.request,t);return o.extend(n,i.prototype,t),o.extend(n,t),n}var o=n(2),s=n(3),i=n(5),u=n(6),a=r(u);a.Axios=i,a.create=function(e){return r(o.merge(u,e))},a.Cancel=n(22),a.CancelToken=n(23),a.isCancel=n(19),a.all=function(e){return Promise.all(e)},a.spread=n(24),e.exports=a,e.exports.default=a},function(e,t,n){"use strict";function r(e){return"[object Array]"===R.call(e)}function o(e){return"[object ArrayBuffer]"===R.call(e)}function s(e){return"undefined"!=typeof FormData&&e instanceof FormData}function i(e){var t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer}function u(e){return"string"==typeof e}function a(e){return"number"==typeof e}function c(e){return"undefined"==typeof e}function f(e){return null!==e&&"object"==typeof e}function p(e){return"[object Date]"===R.call(e)}function d(e){return"[object File]"===R.call(e)}function l(e){return"[object Blob]"===R.call(e)}function h(e){return"[object Function]"===R.call(e)}function m(e){return f(e)&&h(e.pipe)}function y(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams}function g(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}function x(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function v(e,t){if(null!==e&&"undefined"!=typeof e)if("object"!=typeof e&&(e=[e]),r(e))for(var n=0,o=e.length;n - * @license MIT - */ -e.exports=function(e){return null!=e&&null!=e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}},function(e,t,n){"use strict";function r(e){this.defaults=e,this.interceptors={request:new i,response:new i}}var o=n(6),s=n(2),i=n(16),u=n(17);r.prototype.request=function(e){"string"==typeof e&&(e=s.merge({url:arguments[0]},arguments[1])),e=s.merge(o,{method:"get"},this.defaults,e),e.method=e.method.toLowerCase();var t=[u,void 0],n=Promise.resolve(e);for(this.interceptors.request.forEach(function(e){t.unshift(e.fulfilled,e.rejected)}),this.interceptors.response.forEach(function(e){t.push(e.fulfilled,e.rejected)});t.length;)n=n.then(t.shift(),t.shift());return n},s.forEach(["delete","get","head","options"],function(e){r.prototype[e]=function(t,n){return this.request(s.merge(n||{},{method:e,url:t}))}}),s.forEach(["post","put","patch"],function(e){r.prototype[e]=function(t,n,r){return this.request(s.merge(r||{},{method:e,url:t,data:n}))}}),e.exports=r},function(e,t,n){"use strict";function r(e,t){!s.isUndefined(e)&&s.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}function o(){var e;return"undefined"!=typeof XMLHttpRequest?e=n(8):"undefined"!=typeof process&&(e=n(8)),e}var s=n(2),i=n(7),u={"Content-Type":"application/x-www-form-urlencoded"},a={adapter:o(),transformRequest:[function(e,t){return i(t,"Content-Type"),s.isFormData(e)||s.isArrayBuffer(e)||s.isBuffer(e)||s.isStream(e)||s.isFile(e)||s.isBlob(e)?e:s.isArrayBufferView(e)?e.buffer:s.isURLSearchParams(e)?(r(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):s.isObject(e)?(r(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){if("string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(e){return e>=200&&e<300}};a.headers={common:{Accept:"application/json, text/plain, */*"}},s.forEach(["delete","get","head"],function(e){a.headers[e]={}}),s.forEach(["post","put","patch"],function(e){a.headers[e]=s.merge(u)}),e.exports=a},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t){r.forEach(e,function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])})}},function(e,t,n){"use strict";var r=n(2),o=n(9),s=n(12),i=n(13),u=n(14),a=n(10);e.exports=function(e){return new Promise(function(t,c){var f=e.data,p=e.headers;r.isFormData(f)&&delete p["Content-Type"];var d=new XMLHttpRequest;if(e.auth){var l=e.auth.username||"",h=e.auth.password||"";p.Authorization="Basic "+btoa(l+":"+h)}if(d.open(e.method.toUpperCase(),s(e.url,e.params,e.paramsSerializer),!0),d.timeout=e.timeout,d.onreadystatechange=function(){if(d&&4===d.readyState&&(0!==d.status||d.responseURL&&0===d.responseURL.indexOf("file:"))){var n="getAllResponseHeaders"in d?i(d.getAllResponseHeaders()):null,r=e.responseType&&"text"!==e.responseType?d.response:d.responseText,s={data:r,status:d.status,statusText:d.statusText,headers:n,config:e,request:d};o(t,c,s),d=null}},d.onerror=function(){c(a("Network Error",e,null,d)),d=null},d.ontimeout=function(){c(a("timeout of "+e.timeout+"ms exceeded",e,"ECONNABORTED",d)),d=null},r.isStandardBrowserEnv()){var m=n(15),y=(e.withCredentials||u(e.url))&&e.xsrfCookieName?m.read(e.xsrfCookieName):void 0;y&&(p[e.xsrfHeaderName]=y)}if("setRequestHeader"in d&&r.forEach(p,function(e,t){"undefined"==typeof f&&"content-type"===t.toLowerCase()?delete p[t]:d.setRequestHeader(t,e)}),e.withCredentials&&(d.withCredentials=!0),e.responseType)try{d.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&d.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&d.upload&&d.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then(function(e){d&&(d.abort(),c(e),d=null)}),void 0===f&&(f=null),d.send(f)})}},function(e,t,n){"use strict";var r=n(10);e.exports=function(e,t,n){var o=n.config.validateStatus;n.status&&o&&!o(n.status)?t(r("Request failed with status code "+n.status,n.config,null,n.request,n)):e(n)}},function(e,t,n){"use strict";var r=n(11);e.exports=function(e,t,n,o,s){var i=new Error(e);return r(i,t,n,o,s)}},function(e,t){"use strict";e.exports=function(e,t,n,r,o){return e.config=t,n&&(e.code=n),e.request=r,e.response=o,e}},function(e,t,n){"use strict";function r(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var o=n(2);e.exports=function(e,t,n){if(!t)return e;var s;if(n)s=n(t);else if(o.isURLSearchParams(t))s=t.toString();else{var i=[];o.forEach(t,function(e,t){null!==e&&"undefined"!=typeof e&&(o.isArray(e)?t+="[]":e=[e],o.forEach(e,function(e){o.isDate(e)?e=e.toISOString():o.isObject(e)&&(e=JSON.stringify(e)),i.push(r(t)+"="+r(e))}))}),s=i.join("&")}return s&&(e+=(e.indexOf("?")===-1?"?":"&")+s),e}},function(e,t,n){"use strict";var r=n(2),o=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];e.exports=function(e){var t,n,s,i={};return e?(r.forEach(e.split("\n"),function(e){if(s=e.indexOf(":"),t=r.trim(e.substr(0,s)).toLowerCase(),n=r.trim(e.substr(s+1)),t){if(i[t]&&o.indexOf(t)>=0)return;"set-cookie"===t?i[t]=(i[t]?i[t]:[]).concat([n]):i[t]=i[t]?i[t]+", "+n:n}}),i):i}},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){function e(e){var t=e;return n&&(o.setAttribute("href",t),t=o.href),o.setAttribute("href",t),{href:o.href,protocol:o.protocol?o.protocol.replace(/:$/,""):"",host:o.host,search:o.search?o.search.replace(/^\?/,""):"",hash:o.hash?o.hash.replace(/^#/,""):"",hostname:o.hostname,port:o.port,pathname:"/"===o.pathname.charAt(0)?o.pathname:"/"+o.pathname}}var t,n=/(msie|trident)/i.test(navigator.userAgent),o=document.createElement("a");return t=e(window.location.href),function(n){var o=r.isString(n)?e(n):n;return o.protocol===t.protocol&&o.host===t.host}}():function(){return function(){return!0}}()},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){return{write:function(e,t,n,o,s,i){var u=[];u.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&u.push("expires="+new Date(n).toGMTString()),r.isString(o)&&u.push("path="+o),r.isString(s)&&u.push("domain="+s),i===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}()},function(e,t,n){"use strict";function r(){this.handlers=[]}var o=n(2);r.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},r.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},r.prototype.forEach=function(e){o.forEach(this.handlers,function(t){null!==t&&e(t)})},e.exports=r},function(e,t,n){"use strict";function r(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var o=n(2),s=n(18),i=n(19),u=n(6),a=n(20),c=n(21);e.exports=function(e){r(e),e.baseURL&&!a(e.url)&&(e.url=c(e.baseURL,e.url)),e.headers=e.headers||{},e.data=s(e.data,e.headers,e.transformRequest),e.headers=o.merge(e.headers.common||{},e.headers[e.method]||{},e.headers||{}),o.forEach(["delete","get","head","post","put","patch","common"],function(t){delete e.headers[t]});var t=e.adapter||u.adapter;return t(e).then(function(t){return r(e),t.data=s(t.data,t.headers,e.transformResponse),t},function(t){return i(t)||(r(e),t&&t.response&&(t.response.data=s(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)})}},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t,n){return r.forEach(n,function(n){e=n(e,t)}),e}},function(e,t){"use strict";e.exports=function(e){return!(!e||!e.__CANCEL__)}},function(e,t){"use strict";e.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}},function(e,t){"use strict";e.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}},function(e,t){"use strict";function n(e){this.message=e}n.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},n.prototype.__CANCEL__=!0,e.exports=n},function(e,t,n){"use strict";function r(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise(function(e){t=e});var n=this;e(function(e){n.reason||(n.reason=new o(e),t(n.reason))})}var o=n(22);r.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},r.source=function(){var e,t=new r(function(t){e=t});return{token:t,cancel:e}},e.exports=r},function(e,t){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}}])}); -//# sourceMappingURL=axios.min.map \ No newline at end of file diff --git a/setup/data/domain/apixpress/www/app/webapp/js/checkdata.js b/setup/data/domain/apixpress/www/app/webapp/js/checkdata.js deleted file mode 100755 index f622811..0000000 --- a/setup/data/domain/apixpress/www/app/webapp/js/checkdata.js +++ /dev/null @@ -1,184 +0,0 @@ -/* -This module have to be independant of any external package -it is shared between back and front and is usefull -to apply common check in front before sending it in back -can be include in project with - -or with const checkdata = require('../public/js/checkdata.js') - -*/ - -// --## - -const checkdata = {}; -// each checkdata.test. return true or false -checkdata.test = {}; - -checkdata.test.emailadress = ( ctx, email ) => { - const regExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - return regExp.test( email ); -}; -/* - * @emaillist = "email1,email2, email3" - * it check if each eamil separate by , are correct - */ -checkdata.test.emailadresslist = ( ctx, emaillist ) => { - //logger.info(emaillist.split(',')) - if( emaillist.length > 0 ) { - const emails = emaillist.split( ',' ); - for( var i in emails ) { - //logger.info(emails[i]) - if( !checkdata.test.emailadress( "", emails[ i ].trim() ) ) { - return false - } - } - }; - return true; -}; - -checkdata.test.password = ( ctx, pwd ) => { - const regExp = new RegExp( - /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&.])[A-Za-z\d$@$!%*?&.{}:|\s]{8,}/ - ); - return regExp.test( pwd ); -}; -checkdata.test.required = ( ctx, val ) => - val != null && val != 'undefined' && val.length > 0; - -checkdata.test.isNumber = ( ctx, n ) => typeof n === 'number'; -checkdata.test.isInt = ( ctx, n ) => n != '' && !isNaN( n ) && Math.round( n ) == n; -checkdata.test.isFloat = ( ctx, n ) => n != '' && !isNaN( n ) && Math.round( n ) != n; -checkdata.test.unique = ( ctx, val ) => { - if( ctx.list[ ctx.currentfield ] ) { - return !ctx.list[ ctx.currentfield ].includes( val ); - } else { - logger.info( 'ERR no list for field:' + ctx.currentfield ); - return false; - } -}; -checkdata.test.isDateDay = ( ctx, dateDay ) => true; -/* checkdata.test.filterInvalidInArray = (array, validate) => - array ? array.filter(el => !validate(el)) : true; -// return true when every elements is valid -*/ - -checkdata.test.postalCode = ( ctx, postalCode ) => { - if( postalCode.length == 0 ) return true; - const regExp = new RegExp( /(^\d{5}$)|(^\d{5}-\d{4}$)/ ); - return regExp.test( postalCode ); -}; -/** - * PHONE - */ -checkdata.test.phoneNumber = ( ctx, phoneNumber ) => { - if( phoneNumber.length == 0 ) return true; - phoneNumber = phoneNumber.trim() - .replace( /[- .]/g, '' ) - //french number - const regExpfr = new RegExp( /^0[1-9][0-9]{9}$/ ); - const regExpInternational = new RegExp( /^\+*(\d{3})*[0-9,\-]{8,}/ ); - return regExpfr.test( phoneNumber ) || regExpInternational.test( phoneNumber ); -}; -/* - * @phonelist = "phone1,phone2,phone3" - * it check if each phone separate by , are correct - */ -checkdata.test.phoneNumberlist = ( ctx, phonelist ) => { - //logger.info(emaillist.split(',')) - if( phonelist.length > 0 ) { - const phones = phonelist.split( ',' ); - for( var i in phones ) { - //logger.info(emails[i]) - if( !checkdata.test.phoneNumber( "", phones[ i ].trim() ) ) { - return false - } - } - }; - return true; -}; - -// checkdata.normalize take a correct data then reformat it to harmonise it -checkdata.normalize = {}; -checkdata.normalize.phoneNumber = ( ctx, phone ) => { - phone = phone.trim() - .replace( /[- .]/g, '' ); - if( checkdata.test.phoneNumber( '', phone ) && phone.length == 10 && phone[ 0 ] == "0" ) { - phone = '+33 ' + phone.substring( 1 ); - } - return phone; -} -checkdata.normalize.upperCase = ( ctx, txt ) => txt.toUpperCase(); -checkdata.normalize.lowerCase = ( ctx, txt ) => txt.toLowerCase(); -// fixe 10 position et complete par des 0 devant -checkdata.normalize.zfill10 = ( ctx, num ) => { - let s = num + ''; - while( s.length < 10 ) s = '0' + s; - return s; -}; -/*let tt = "+33 1 02.03 04 05"; -logger.info(checkdata.test.phoneNumber('', tt)) -logger.info(checkdata.normalize.phoneNumber('', tt)) -*/ -checkdata.evaluate = ( contexte, referential, data ) => { - /* - * contexte object {} with full info for evaluation - * file referential path to get object to apply - * data related to object - - return {validefor =[keyword of error] if empty no error, - clean data eventually reformated - updateDatabase} - */ - logger.info( 'contexte', contexte ); - logger.info( 'referentiel', referential ); - logger.info( 'data', data ); - const invalidefor = []; - const objectdef = {}; - const listfield = referential.map( ch => { - objectdef[ ch.idfield ] = ch; - return ch.idfield; - } ); - - Object.keys( data ) - .forEach( field => { - if( !listfield.includes( field ) ) { - // some data can be inside an object with no control at all - // they are used for process only - // i leave it in case it will become a non sens - // invalidefor.push('ERRFIELD unknown of referentials ' + field); - } else { - if( objectdef[ field ].check ) { - // check data with rule list in check - objectdef[ field ].check.forEach( ctrl => { - logger.info( 'ctrl', ctrl ); - contexte.currentfield = field; - if( !checkdata.test[ ctrl ] ) { - invalidefor.push( 'ERR check function does not exist :' + ctrl + '___' + field ) - } else { - if( !checkdata.test[ ctrl ]( contexte, data[ field ] ) ) - invalidefor.push( 'ERR' + ctrl + '___' + field ); - } - } ); - } - - if( objectdef[ field ].nouserupdate ) { - // check if user can modify this information - logger.info( - 'evaluation :' + field + ' -- ' + objectdef[ field ].nouserupdate, - eval( objectdef[ field ].nouserupdate ) - ); - const evalright = eval( objectdef[ field ].nouserupdate ); - objectdef[ field ].nouserupdate = evalright; - } - } - } ); - logger.info( { - invalidefor, - data - } ); - return { - invalidefor, - data - }; -}; - -if( typeof module !== 'undefined' ) module.exports = checkdata; diff --git a/setup/data/domain/apixpress/www/app/webapp/js/feather.min.js b/setup/data/domain/apixpress/www/app/webapp/js/feather.min.js deleted file mode 100755 index 156cd61..0000000 --- a/setup/data/domain/apixpress/www/app/webapp/js/feather.min.js +++ /dev/null @@ -1,13 +0,0 @@ -!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.feather=n():e.feather=n()}("undefined"!=typeof self?self:this,function(){return function(e){var n={};function i(t){if(n[t])return n[t].exports;var l=n[t]={i:t,l:!1,exports:{}};return e[t].call(l.exports,l,l.exports,i),l.l=!0,l.exports}return i.m=e,i.c=n,i.d=function(e,n,t){i.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:t})},i.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},i.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(n,"a",n),n},i.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},i.p="",i(i.s=80)}([function(e,n,i){(function(n){var i="object",t=function(e){return e&&e.Math==Math&&e};e.exports=t(typeof globalThis==i&&globalThis)||t(typeof window==i&&window)||t(typeof self==i&&self)||t(typeof n==i&&n)||Function("return this")()}).call(this,i(75))},function(e,n){var i={}.hasOwnProperty;e.exports=function(e,n){return i.call(e,n)}},function(e,n,i){var t=i(0),l=i(11),r=i(33),o=i(62),a=t.Symbol,c=l("wks");e.exports=function(e){return c[e]||(c[e]=o&&a[e]||(o?a:r)("Symbol."+e))}},function(e,n,i){var t=i(6);e.exports=function(e){if(!t(e))throw TypeError(String(e)+" is not an object");return e}},function(e,n){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,n,i){var t=i(8),l=i(7),r=i(10);e.exports=t?function(e,n,i){return l.f(e,n,r(1,i))}:function(e,n,i){return e[n]=i,e}},function(e,n){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,n,i){var t=i(8),l=i(35),r=i(3),o=i(18),a=Object.defineProperty;n.f=t?a:function(e,n,i){if(r(e),n=o(n,!0),r(i),l)try{return a(e,n,i)}catch(e){}if("get"in i||"set"in i)throw TypeError("Accessors not supported");return"value"in i&&(e[n]=i.value),e}},function(e,n,i){var t=i(4);e.exports=!t(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,n){e.exports={}},function(e,n){e.exports=function(e,n){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:n}}},function(e,n,i){var t=i(0),l=i(19),r=i(17),o=t["__core-js_shared__"]||l("__core-js_shared__",{});(e.exports=function(e,n){return o[e]||(o[e]=void 0!==n?n:{})})("versions",[]).push({version:"3.1.3",mode:r?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},function(e,n,i){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var t=o(i(43)),l=o(i(41)),r=o(i(40));function o(e){return e&&e.__esModule?e:{default:e}}n.default=Object.keys(l.default).map(function(e){return new t.default(e,l.default[e],r.default[e])}).reduce(function(e,n){return e[n.name]=n,e},{})},function(e,n){e.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},function(e,n,i){var t=i(72),l=i(20);e.exports=function(e){return t(l(e))}},function(e,n){e.exports={}},function(e,n,i){var t=i(11),l=i(33),r=t("keys");e.exports=function(e){return r[e]||(r[e]=l(e))}},function(e,n){e.exports=!1},function(e,n,i){var t=i(6);e.exports=function(e,n){if(!t(e))return e;var i,l;if(n&&"function"==typeof(i=e.toString)&&!t(l=i.call(e)))return l;if("function"==typeof(i=e.valueOf)&&!t(l=i.call(e)))return l;if(!n&&"function"==typeof(i=e.toString)&&!t(l=i.call(e)))return l;throw TypeError("Can't convert object to primitive value")}},function(e,n,i){var t=i(0),l=i(5);e.exports=function(e,n){try{l(t,e,n)}catch(i){t[e]=n}return n}},function(e,n){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,n){var i=Math.ceil,t=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?t:i)(e)}},function(e,n,i){var t; -/*! - Copyright (c) 2016 Jed Watson. - Licensed under the MIT License (MIT), see - http://jedwatson.github.io/classnames -*/ -/*! - Copyright (c) 2016 Jed Watson. - Licensed under the MIT License (MIT), see - http://jedwatson.github.io/classnames -*/ -!function(){"use strict";var i=function(){function e(){}function n(e,n){for(var i=n.length,t=0;t0?l(t(e),9007199254740991):0}},function(e,n,i){var t=i(1),l=i(14),r=i(68),o=i(15),a=r(!1);e.exports=function(e,n){var i,r=l(e),c=0,p=[];for(i in r)!t(o,i)&&t(r,i)&&p.push(i);for(;n.length>c;)t(r,i=n[c++])&&(~a(p,i)||p.push(i));return p}},function(e,n,i){var t=i(0),l=i(11),r=i(5),o=i(1),a=i(19),c=i(36),p=i(37),y=p.get,h=p.enforce,x=String(c).split("toString");l("inspectSource",function(e){return c.call(e)}),(e.exports=function(e,n,i,l){var c=!!l&&!!l.unsafe,p=!!l&&!!l.enumerable,y=!!l&&!!l.noTargetGet;"function"==typeof i&&("string"!=typeof n||o(i,"name")||r(i,"name",n),h(i).source=x.join("string"==typeof n?n:"")),e!==t?(c?!y&&e[n]&&(p=!0):delete e[n],p?e[n]=i:r(e,n,i)):p?e[n]=i:a(n,i)})(Function.prototype,"toString",function(){return"function"==typeof this&&y(this).source||c.call(this)})},function(e,n){var i={}.toString;e.exports=function(e){return i.call(e).slice(8,-1)}},function(e,n,i){var t=i(8),l=i(73),r=i(10),o=i(14),a=i(18),c=i(1),p=i(35),y=Object.getOwnPropertyDescriptor;n.f=t?y:function(e,n){if(e=o(e),n=a(n,!0),p)try{return y(e,n)}catch(e){}if(c(e,n))return r(!l.f.call(e,n),e[n])}},function(e,n,i){var t=i(0),l=i(31).f,r=i(5),o=i(29),a=i(19),c=i(71),p=i(65);e.exports=function(e,n){var i,y,h,x,s,u=e.target,d=e.global,f=e.stat;if(i=d?t:f?t[u]||a(u,{}):(t[u]||{}).prototype)for(y in n){if(x=n[y],h=e.noTargetGet?(s=l(i,y))&&s.value:i[y],!p(d?y:u+(f?".":"#")+y,e.forced)&&void 0!==h){if(typeof x==typeof h)continue;c(x,h)}(e.sham||h&&h.sham)&&r(x,"sham",!0),o(i,y,x,e)}}},function(e,n){var i=0,t=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++i+t).toString(36))}},function(e,n,i){var t=i(0),l=i(6),r=t.document,o=l(r)&&l(r.createElement);e.exports=function(e){return o?r.createElement(e):{}}},function(e,n,i){var t=i(8),l=i(4),r=i(34);e.exports=!t&&!l(function(){return 7!=Object.defineProperty(r("div"),"a",{get:function(){return 7}}).a})},function(e,n,i){var t=i(11);e.exports=t("native-function-to-string",Function.toString)},function(e,n,i){var t,l,r,o=i(76),a=i(0),c=i(6),p=i(5),y=i(1),h=i(16),x=i(15),s=a.WeakMap;if(o){var u=new s,d=u.get,f=u.has,g=u.set;t=function(e,n){return g.call(u,e,n),n},l=function(e){return d.call(u,e)||{}},r=function(e){return f.call(u,e)}}else{var v=h("state");x[v]=!0,t=function(e,n){return p(e,v,n),n},l=function(e){return y(e,v)?e[v]:{}},r=function(e){return y(e,v)}}e.exports={set:t,get:l,has:r,enforce:function(e){return r(e)?l(e):t(e,{})},getterFor:function(e){return function(n){var i;if(!c(n)||(i=l(n)).type!==e)throw TypeError("Incompatible receiver, "+e+" required");return i}}}},function(e,n,i){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var t=Object.assign||function(e){for(var n=1;n0&&void 0!==arguments[0]?arguments[0]:{};if("undefined"==typeof document)throw new Error("`feather.replace()` only works in a browser environment.");var n=document.querySelectorAll("[data-feather]");Array.from(n).forEach(function(n){return function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=function(e){return Array.from(e.attributes).reduce(function(e,n){return e[n.name]=n.value,e},{})}(e),o=i["data-feather"];delete i["data-feather"];var a=r.default[o].toSvg(t({},n,i,{class:(0,l.default)(n.class,i.class)})),c=(new DOMParser).parseFromString(a,"image/svg+xml").querySelector("svg");e.parentNode.replaceChild(c,e)}(n,e)})}},function(e,n,i){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var t,l=i(12),r=(t=l)&&t.__esModule?t:{default:t};n.default=function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(console.warn("feather.toSvg() is deprecated. Please use feather.icons[name].toSvg() instead."),!e)throw new Error("The required `key` (icon name) parameter is missing.");if(!r.default[e])throw new Error("No icon matching '"+e+"'. See the complete list of icons at https://feathericons.com");return r.default[e].toSvg(n)}},function(e){e.exports={activity:["pulse","health","action","motion"],airplay:["stream","cast","mirroring"],"alert-circle":["warning","alert","danger"],"alert-octagon":["warning","alert","danger"],"alert-triangle":["warning","alert","danger"],"align-center":["text alignment","center"],"align-justify":["text alignment","justified"],"align-left":["text alignment","left"],"align-right":["text alignment","right"],anchor:[],archive:["index","box"],"at-sign":["mention","at","email","message"],award:["achievement","badge"],aperture:["camera","photo"],"bar-chart":["statistics","diagram","graph"],"bar-chart-2":["statistics","diagram","graph"],battery:["power","electricity"],"battery-charging":["power","electricity"],bell:["alarm","notification","sound"],"bell-off":["alarm","notification","silent"],bluetooth:["wireless"],"book-open":["read","library"],book:["read","dictionary","booklet","magazine","library"],bookmark:["read","clip","marker","tag"],box:["cube"],briefcase:["work","bag","baggage","folder"],calendar:["date"],camera:["photo"],cast:["chromecast","airplay"],circle:["off","zero","record"],clipboard:["copy"],clock:["time","watch","alarm"],"cloud-drizzle":["weather","shower"],"cloud-lightning":["weather","bolt"],"cloud-rain":["weather"],"cloud-snow":["weather","blizzard"],cloud:["weather"],codepen:["logo"],codesandbox:["logo"],code:["source","programming"],coffee:["drink","cup","mug","tea","cafe","hot","beverage"],columns:["layout"],command:["keyboard","cmd","terminal","prompt"],compass:["navigation","safari","travel","direction"],copy:["clone","duplicate"],"corner-down-left":["arrow","return"],"corner-down-right":["arrow"],"corner-left-down":["arrow"],"corner-left-up":["arrow"],"corner-right-down":["arrow"],"corner-right-up":["arrow"],"corner-up-left":["arrow"],"corner-up-right":["arrow"],cpu:["processor","technology"],"credit-card":["purchase","payment","cc"],crop:["photo","image"],crosshair:["aim","target"],database:["storage","memory"],delete:["remove"],disc:["album","cd","dvd","music"],"dollar-sign":["currency","money","payment"],droplet:["water"],edit:["pencil","change"],"edit-2":["pencil","change"],"edit-3":["pencil","change"],eye:["view","watch"],"eye-off":["view","watch","hide","hidden"],"external-link":["outbound"],facebook:["logo","social"],"fast-forward":["music"],figma:["logo","design","tool"],"file-minus":["delete","remove","erase"],"file-plus":["add","create","new"],"file-text":["data","txt","pdf"],film:["movie","video"],filter:["funnel","hopper"],flag:["report"],"folder-minus":["directory"],"folder-plus":["directory"],folder:["directory"],framer:["logo","design","tool"],frown:["emoji","face","bad","sad","emotion"],gift:["present","box","birthday","party"],"git-branch":["code","version control"],"git-commit":["code","version control"],"git-merge":["code","version control"],"git-pull-request":["code","version control"],github:["logo","version control"],gitlab:["logo","version control"],globe:["world","browser","language","translate"],"hard-drive":["computer","server","memory","data"],hash:["hashtag","number","pound"],headphones:["music","audio","sound"],heart:["like","love","emotion"],"help-circle":["question mark"],hexagon:["shape","node.js","logo"],home:["house","living"],image:["picture"],inbox:["email"],instagram:["logo","camera"],key:["password","login","authentication","secure"],layers:["stack"],layout:["window","webpage"],"life-bouy":["help","life ring","support"],link:["chain","url"],"link-2":["chain","url"],linkedin:["logo","social media"],list:["options"],lock:["security","password","secure"],"log-in":["sign in","arrow","enter"],"log-out":["sign out","arrow","exit"],mail:["email","message"],"map-pin":["location","navigation","travel","marker"],map:["location","navigation","travel"],maximize:["fullscreen"],"maximize-2":["fullscreen","arrows","expand"],meh:["emoji","face","neutral","emotion"],menu:["bars","navigation","hamburger"],"message-circle":["comment","chat"],"message-square":["comment","chat"],"mic-off":["record","sound","mute"],mic:["record","sound","listen"],minimize:["exit fullscreen","close"],"minimize-2":["exit fullscreen","arrows","close"],minus:["subtract"],monitor:["tv","screen","display"],moon:["dark","night"],"more-horizontal":["ellipsis"],"more-vertical":["ellipsis"],"mouse-pointer":["arrow","cursor"],move:["arrows"],music:["note"],navigation:["location","travel"],"navigation-2":["location","travel"],octagon:["stop"],package:["box","container"],paperclip:["attachment"],pause:["music","stop"],"pause-circle":["music","audio","stop"],"pen-tool":["vector","drawing"],percent:["discount"],"phone-call":["ring"],"phone-forwarded":["call"],"phone-incoming":["call"],"phone-missed":["call"],"phone-off":["call","mute"],"phone-outgoing":["call"],phone:["call"],play:["music","start"],"pie-chart":["statistics","diagram"],"play-circle":["music","start"],plus:["add","new"],"plus-circle":["add","new"],"plus-square":["add","new"],pocket:["logo","save"],power:["on","off"],printer:["fax","office","device"],radio:["signal"],"refresh-cw":["synchronise","arrows"],"refresh-ccw":["arrows"],repeat:["loop","arrows"],rewind:["music"],"rotate-ccw":["arrow"],"rotate-cw":["arrow"],rss:["feed","subscribe"],save:["floppy disk"],scissors:["cut"],search:["find","magnifier","magnifying glass"],send:["message","mail","email","paper airplane","paper aeroplane"],settings:["cog","edit","gear","preferences"],"share-2":["network","connections"],shield:["security","secure"],"shield-off":["security","insecure"],"shopping-bag":["ecommerce","cart","purchase","store"],"shopping-cart":["ecommerce","cart","purchase","store"],shuffle:["music"],"skip-back":["music"],"skip-forward":["music"],slack:["logo"],slash:["ban","no"],sliders:["settings","controls"],smartphone:["cellphone","device"],smile:["emoji","face","happy","good","emotion"],speaker:["audio","music"],star:["bookmark","favorite","like"],"stop-circle":["media","music"],sun:["brightness","weather","light"],sunrise:["weather","time","morning","day"],sunset:["weather","time","evening","night"],tablet:["device"],tag:["label"],target:["logo","bullseye"],terminal:["code","command line","prompt"],thermometer:["temperature","celsius","fahrenheit","weather"],"thumbs-down":["dislike","bad","emotion"],"thumbs-up":["like","good","emotion"],"toggle-left":["on","off","switch"],"toggle-right":["on","off","switch"],tool:["settings","spanner"],trash:["garbage","delete","remove","bin"],"trash-2":["garbage","delete","remove","bin"],triangle:["delta"],truck:["delivery","van","shipping","transport","lorry"],tv:["television","stream"],twitch:["logo"],twitter:["logo","social"],type:["text"],umbrella:["rain","weather"],unlock:["security"],"user-check":["followed","subscribed"],"user-minus":["delete","remove","unfollow","unsubscribe"],"user-plus":["new","add","create","follow","subscribe"],"user-x":["delete","remove","unfollow","unsubscribe","unavailable"],user:["person","account"],users:["group"],"video-off":["camera","movie","film"],video:["camera","movie","film"],voicemail:["phone"],volume:["music","sound","mute"],"volume-1":["music","sound"],"volume-2":["music","sound"],"volume-x":["music","sound","mute"],watch:["clock","time"],"wifi-off":["disabled"],wifi:["connection","signal","wireless"],wind:["weather","air"],"x-circle":["cancel","close","delete","remove","times","clear"],"x-octagon":["delete","stop","alert","warning","times","clear"],"x-square":["cancel","close","delete","remove","times","clear"],x:["cancel","close","delete","remove","times","clear"],youtube:["logo","video","play"],"zap-off":["flash","camera","lightning"],zap:["flash","camera","lightning"],"zoom-in":["magnifying glass"],"zoom-out":["magnifying glass"]}},function(e){e.exports={activity:'',airplay:'',"alert-circle":'',"alert-octagon":'',"alert-triangle":'',"align-center":'',"align-justify":'',"align-left":'',"align-right":'',anchor:'',aperture:'',archive:'',"arrow-down-circle":'',"arrow-down-left":'',"arrow-down-right":'',"arrow-down":'',"arrow-left-circle":'',"arrow-left":'',"arrow-right-circle":'',"arrow-right":'',"arrow-up-circle":'',"arrow-up-left":'',"arrow-up-right":'',"arrow-up":'',"at-sign":'',award:'',"bar-chart-2":'',"bar-chart":'',"battery-charging":'',battery:'',"bell-off":'',bell:'',bluetooth:'',bold:'',"book-open":'',book:'',bookmark:'',box:'',briefcase:'',calendar:'',"camera-off":'',camera:'',cast:'',"check-circle":'',"check-square":'',check:'',"chevron-down":'',"chevron-left":'',"chevron-right":'',"chevron-up":'',"chevrons-down":'',"chevrons-left":'',"chevrons-right":'',"chevrons-up":'',chrome:'',circle:'',clipboard:'',clock:'',"cloud-drizzle":'',"cloud-lightning":'',"cloud-off":'',"cloud-rain":'',"cloud-snow":'',cloud:'',code:'',codepen:'',codesandbox:'',coffee:'',columns:'',command:'',compass:'',copy:'',"corner-down-left":'',"corner-down-right":'',"corner-left-down":'',"corner-left-up":'',"corner-right-down":'',"corner-right-up":'',"corner-up-left":'',"corner-up-right":'',cpu:'',"credit-card":'',crop:'',crosshair:'',database:'',delete:'',disc:'',"divide-circle":'',"divide-square":'',divide:'',"dollar-sign":'',"download-cloud":'',download:'',dribbble:'',droplet:'',"edit-2":'',"edit-3":'',edit:'',"external-link":'',"eye-off":'',eye:'',facebook:'',"fast-forward":'',feather:'',figma:'',"file-minus":'',"file-plus":'',"file-text":'',file:'',film:'',filter:'',flag:'',"folder-minus":'',"folder-plus":'',folder:'',framer:'',frown:'',gift:'',"git-branch":'',"git-commit":'',"git-merge":'',"git-pull-request":'',github:'',gitlab:'',globe:'',grid:'',"hard-drive":'',hash:'',headphones:'',heart:'',"help-circle":'',hexagon:'',home:'',image:'',inbox:'',info:'',instagram:'',italic:'',key:'',layers:'',layout:'',"life-buoy":'',"link-2":'',link:'',linkedin:'',list:'',loader:'',lock:'',"log-in":'',"log-out":'',mail:'',"map-pin":'',map:'',"maximize-2":'',maximize:'',meh:'',menu:'',"message-circle":'',"message-square":'',"mic-off":'',mic:'',"minimize-2":'',minimize:'',"minus-circle":'',"minus-square":'',minus:'',monitor:'',moon:'',"more-horizontal":'',"more-vertical":'',"mouse-pointer":'',move:'',music:'',"navigation-2":'',navigation:'',octagon:'',package:'',paperclip:'',"pause-circle":'',pause:'',"pen-tool":'',percent:'',"phone-call":'',"phone-forwarded":'',"phone-incoming":'',"phone-missed":'',"phone-off":'',"phone-outgoing":'',phone:'',"pie-chart":'',"play-circle":'',play:'',"plus-circle":'',"plus-square":'',plus:'',pocket:'',power:'',printer:'',radio:'',"refresh-ccw":'',"refresh-cw":'',repeat:'',rewind:'',"rotate-ccw":'',"rotate-cw":'',rss:'',save:'',scissors:'',search:'',send:'',server:'',settings:'',"share-2":'',share:'',"shield-off":'',shield:'',"shopping-bag":'',"shopping-cart":'',shuffle:'',sidebar:'',"skip-back":'',"skip-forward":'',slack:'',slash:'',sliders:'',smartphone:'',smile:'',speaker:'',square:'',star:'',"stop-circle":'',sun:'',sunrise:'',sunset:'',tablet:'',tag:'',target:'',terminal:'',thermometer:'',"thumbs-down":'',"thumbs-up":'',"toggle-left":'',"toggle-right":'',tool:'',"trash-2":'',trash:'',trello:'',"trending-down":'',"trending-up":'',triangle:'',truck:'',tv:'',twitch:'',twitter:'',type:'',umbrella:'',underline:'',unlock:'',"upload-cloud":'',upload:'',"user-check":'',"user-minus":'',"user-plus":'',"user-x":'',user:'',users:'',"video-off":'',video:'',voicemail:'',"volume-1":'',"volume-2":'',"volume-x":'',volume:'',watch:'',"wifi-off":'',wifi:'',wind:'',"x-circle":'',"x-octagon":'',"x-square":'',x:'',youtube:'',"zap-off":'',zap:'',"zoom-in":'',"zoom-out":''}},function(e){e.exports={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":2,"stroke-linecap":"round","stroke-linejoin":"round"}},function(e,n,i){"use strict";Object.defineProperty(n,"__esModule",{value:!0});var t=Object.assign||function(e){for(var n=1;n2&&void 0!==arguments[2]?arguments[2]:[];!function(e,n){if(!(e instanceof n))throw new TypeError("Cannot call a class as a function")}(this,e),this.name=n,this.contents=i,this.tags=l,this.attrs=t({},o.default,{class:"feather feather-"+n})}return l(e,[{key:"toSvg",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return""+this.contents+""}},{key:"toString",value:function(){return this.contents}}]),e}();n.default=c},function(e,n,i){"use strict";var t=o(i(12)),l=o(i(39)),r=o(i(38));function o(e){return e&&e.__esModule?e:{default:e}}e.exports={icons:t.default,toSvg:l.default,replace:r.default}},function(e,n,i){e.exports=i(0)},function(e,n,i){var t=i(2)("iterator"),l=!1;try{var r=0,o={next:function(){return{done:!!r++}},return:function(){l=!0}};o[t]=function(){return this},Array.from(o,function(){throw 2})}catch(e){}e.exports=function(e,n){if(!n&&!l)return!1;var i=!1;try{var r={};r[t]=function(){return{next:function(){return{done:i=!0}}}},e(r)}catch(e){}return i}},function(e,n,i){var t=i(30),l=i(2)("toStringTag"),r="Arguments"==t(function(){return arguments}());e.exports=function(e){var n,i,o;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,n){try{return e[n]}catch(e){}}(n=Object(e),l))?i:r?t(n):"Object"==(o=t(n))&&"function"==typeof n.callee?"Arguments":o}},function(e,n,i){var t=i(47),l=i(9),r=i(2)("iterator");e.exports=function(e){if(void 0!=e)return e[r]||e["@@iterator"]||l[t(e)]}},function(e,n,i){"use strict";var t=i(18),l=i(7),r=i(10);e.exports=function(e,n,i){var o=t(n);o in e?l.f(e,o,r(0,i)):e[o]=i}},function(e,n,i){var t=i(2),l=i(9),r=t("iterator"),o=Array.prototype;e.exports=function(e){return void 0!==e&&(l.Array===e||o[r]===e)}},function(e,n,i){var t=i(3);e.exports=function(e,n,i,l){try{return l?n(t(i)[0],i[1]):n(i)}catch(n){var r=e.return;throw void 0!==r&&t(r.call(e)),n}}},function(e,n){e.exports=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e}},function(e,n,i){var t=i(52);e.exports=function(e,n,i){if(t(e),void 0===n)return e;switch(i){case 0:return function(){return e.call(n)};case 1:return function(i){return e.call(n,i)};case 2:return function(i,t){return e.call(n,i,t)};case 3:return function(i,t,l){return e.call(n,i,t,l)}}return function(){return e.apply(n,arguments)}}},function(e,n,i){"use strict";var t=i(53),l=i(24),r=i(51),o=i(50),a=i(27),c=i(49),p=i(48);e.exports=function(e){var n,i,y,h,x=l(e),s="function"==typeof this?this:Array,u=arguments.length,d=u>1?arguments[1]:void 0,f=void 0!==d,g=0,v=p(x);if(f&&(d=t(d,u>2?arguments[2]:void 0,2)),void 0==v||s==Array&&o(v))for(i=new s(n=a(x.length));n>g;g++)c(i,g,f?d(x[g],g):x[g]);else for(h=v.call(x),i=new s;!(y=h.next()).done;g++)c(i,g,f?r(h,d,[y.value,g],!0):y.value);return i.length=g,i}},function(e,n,i){var t=i(32),l=i(54);t({target:"Array",stat:!0,forced:!i(46)(function(e){Array.from(e)})},{from:l})},function(e,n,i){var t=i(6),l=i(3);e.exports=function(e,n){if(l(e),!t(n)&&null!==n)throw TypeError("Can't set "+String(n)+" as a prototype")}},function(e,n,i){var t=i(56);e.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var e,n=!1,i={};try{(e=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(i,[]),n=i instanceof Array}catch(e){}return function(i,l){return t(i,l),n?e.call(i,l):i.__proto__=l,i}}():void 0)},function(e,n,i){var t=i(0).document;e.exports=t&&t.documentElement},function(e,n,i){var t=i(28),l=i(13);e.exports=Object.keys||function(e){return t(e,l)}},function(e,n,i){var t=i(8),l=i(7),r=i(3),o=i(59);e.exports=t?Object.defineProperties:function(e,n){r(e);for(var i,t=o(n),a=t.length,c=0;a>c;)l.f(e,i=t[c++],n[i]);return e}},function(e,n,i){var t=i(3),l=i(60),r=i(13),o=i(15),a=i(58),c=i(34),p=i(16)("IE_PROTO"),y=function(){},h=function(){var e,n=c("iframe"),i=r.length;for(n.style.display="none",a.appendChild(n),n.src=String("javascript:"),(e=n.contentWindow.document).open(),e.write(" -or with const checkdata = require('../public/js/checkdata.js') - -*/ - -// --## - -const checkdata = {}; -// each checkdata.test. return true or false -checkdata.test = {}; - -checkdata.test.emailadress = ( ctx, email ) => { - const regExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - return regExp.test( email ); -}; -/* - * @emaillist = "email1,email2, email3" - * it check if each eamil separate by , are correct - */ -checkdata.test.emailadresslist = ( ctx, emaillist ) => { - //logger.info(emaillist.split(',')) - if( emaillist.length > 0 ) { - const emails = emaillist.split( ',' ); - for( var i in emails ) { - //logger.info(emails[i]) - if( !checkdata.test.emailadress( "", emails[ i ].trim() ) ) { - return false - } - } - }; - return true; -}; - -checkdata.test.password = ( ctx, pwd ) => { - const regExp = new RegExp( - /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&.])[A-Za-z\d$@$!%*?&.{}:|\s]{8,}/ - ); - return regExp.test( pwd ); -}; -checkdata.test.required = ( ctx, val ) => - ( val != null && val != 'undefined' && val.length > 0 ) || ( !!val && val.constructor === Array && val.length > 0 ) || ( !!val && val.constructor === Object && Object.keys( val ) - .length > 0 ); - -checkdata.test.isNumber = ( ctx, n ) => typeof n === 'number'; -checkdata.test.isInt = ( ctx, n ) => n != '' && !isNaN( n ) && Math.round( n ) == n; -checkdata.test.isFloat = ( ctx, n ) => n != '' && !isNaN( n ) && Math.round( n ) != n; -checkdata.test.unique = ( ctx, val ) => { - if( ctx.list[ ctx.currentfield ] ) { - return !ctx.list[ ctx.currentfield ].includes( val ); - } else { - logger.info( 'ERR no list for field:' + ctx.currentfield ); - return false; - } -}; -checkdata.test.isDateDay = ( ctx, dateDay ) => true; -/* checkdata.test.filterInvalidInArray = (array, validate) => - array ? array.filter(el => !validate(el)) : true; -// return true when every elements is valid -*/ - -checkdata.test.postalCode = ( ctx, postalCode ) => { - if( postalCode.length == 0 ) return true; - const regExp = new RegExp( /(^\d{5}$)|(^\d{5}-\d{4}$)/ ); - return regExp.test( postalCode ); -}; -/** - * PHONE - */ -checkdata.test.phoneNumber = ( ctx, phoneNumber ) => { - if( phoneNumber.length == 0 ) return true; - phoneNumber = phoneNumber.trim() - .replace( /[- .]/g, '' ) - //french number - const regExpfr = new RegExp( /^0[1-9][0-9]{9}$/ ); - const regExpInternational = new RegExp( /^\+*(\d{3})*[0-9,\-]{8,}/ ); - return regExpfr.test( phoneNumber ) || regExpInternational.test( phoneNumber ); -}; -/* - * @phonelist = "phone1,phone2,phone3" - * it check if each phone separate by , are correct - */ -checkdata.test.phoneNumberlist = ( ctx, phonelist ) => { - //logger.info(emaillist.split(',')) - if( phonelist.length > 0 ) { - const phones = phonelist.split( ',' ); - for( var i in phones ) { - //logger.info(emails[i]) - if( !checkdata.test.phoneNumber( "", phones[ i ].trim() ) ) { - return false - } - } - }; - return true; -}; - -// checkdata.normalize take a correct data then reformat it to harmonise it -checkdata.normalize = {}; -checkdata.normalize.phoneNumber = ( ctx, phone ) => { - phone = phone.trim() - .replace( /[- .]/g, '' ); - if( checkdata.test.phoneNumber( '', phone ) && phone.length == 10 && phone[ 0 ] == "0" ) { - phone = '+33 ' + phone.substring( 1 ); - } - return phone; -} -checkdata.normalize.upperCase = ( ctx, txt ) => txt.toUpperCase(); -checkdata.normalize.lowerCase = ( ctx, txt ) => txt.toLowerCase(); -// fixe 10 position et complete par des 0 devant -checkdata.normalize.zfill10 = ( ctx, num ) => { - let s = num + ''; - while( s.length < 10 ) s = '0' + s; - return s; -}; -/*let tt = "+33 1 02.03 04 05"; -logger.info(checkdata.test.phoneNumber('', tt)) -logger.info(checkdata.normalize.phoneNumber('', tt)) -*/ -checkdata.evaluate = ( contexte, referential, data ) => { - /* - * contexte object {} with full info for evaluation - * file referential path to get object to apply - * data related to object - - return {validefor =[keyword of error] if empty no error, - clean data eventually reformated - updateDatabase} - */ - logger.info( 'contexte', contexte ); - logger.info( 'referentiel', referential ); - logger.info( 'data', data ); - const invalidefor = []; - const objectdef = {}; - const listfield = referential.map( ch => { - objectdef[ ch.idfield ] = ch; - return ch.idfield; - } ); - - Object.keys( data ) - .forEach( field => { - if( !listfield.includes( field ) ) { - // some data can be inside an object with no control at all - // they are used for process only - // i leave it in case it will become a non sens - // invalidefor.push('ERRFIELD unknown of referentials ' + field); - } else { - if( objectdef[ field ].check ) { - // check data with rule list in check - objectdef[ field ].check.forEach( ctrl => { - logger.info( 'ctrl', ctrl ); - contexte.currentfield = field; - if( !checkdata.test[ ctrl ] ) { - invalidefor.push( 'ERR check function does not exist :' + ctrl + '___' + field ) - } else { - if( !checkdata.test[ ctrl ]( contexte, data[ field ] ) ) - invalidefor.push( 'ERR' + ctrl + '___' + field ); - } - } ); - } - - if( objectdef[ field ].nouserupdate ) { - // check if user can modify this information - logger.info( - 'evaluation :' + field + ' -- ' + objectdef[ field ].nouserupdate, - eval( objectdef[ field ].nouserupdate ) - ); - const evalright = eval( objectdef[ field ].nouserupdate ); - objectdef[ field ].nouserupdate = evalright; - } - } - } ); - logger.info( { - invalidefor, - data - } ); - return { - invalidefor, - data - }; -}; - -if( typeof module !== 'undefined' ) module.exports = checkdata; diff --git a/setup/data/domain/apixpress/www/cdn/public/js/editorsave.js b/setup/data/domain/apixpress/www/cdn/public/js/editorsave.js deleted file mode 100755 index 4b276bd..0000000 --- a/setup/data/domain/apixpress/www/cdn/public/js/editorsave.js +++ /dev/null @@ -1,104 +0,0 @@ -'use strict'; -var edit = edit || {}; - -edit.init = function() { - var DOWNLOAD_NAME = 'index.maildigit'; - // Apply contenteditable attributes on text elements - $('p,h1,h2,h3,h4,h5,h6,a,li,ul').attr('contenteditable', 'true'); - - // Add Save/Load menu - $('body').prepend( - "
\ - \ -
" - ); - - // Add button to upload file below each image - $('img').each(function(i) { - //logger.info($(this).attr('src')); - $(this).attr('src', $(this).attr('src')); - $(this).attr('H', $(this).css('height')); - $(this).attr('L', $(this).attr('width')); - $(this) - .closest('div') - .append(""); - }); - - // Replace old image with the new uploaded image in base64 - $('.imageLoader').on('change', function(e) { - var imgEl = $(this) - .closest('div') - .find('img'); - // Get img tree like /images/equipe or /images/ - var tree = imgEl[0].src.split(window.location.origin)[1]; - // This is needed because if we change two times an image at the same place - // first time we replaced it the src will be in base64 - // then we need to find the computed src which is stored in dataset.tree - if (!tree) tree = imgEl[0].dataset.tree; - tree = tree.substr(0, tree.lastIndexOf('/') + 1); - if ($(this)[0].files.length === 1) { - var fileName = $(this)[0].files[0].name; - fileName = fileName.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); // remove accents - fileName = fileName.replace(/\s+/g, '_'); // remove spaces - var ext = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase(); - // Add fileName and tree in data attributes - imgEl[0].dataset.fileName = fileName; - imgEl[0].dataset.tree = tree + fileName; - logger.info(imgEl[0].dataset.tree); - // logger.info(imgEl); - - if (ext === 'gif' || ext === 'png' || ext === 'jpeg' || ext === 'jpg') { - var reader = new FileReader(); - reader.onload = function(e) { - imgEl.attr('src', e.target.result); - }; - reader.readAsDataURL($(this)[0].files[0]); - } - } - }); - - $('button.editercharge').on('click', function() { - $(this) - .closest('div') - .find('.chargehisto') - .trigger('click'); - }); - $('.chargehisto').on('change', function(e) { - if ($(this)[0].files !== undefined) { - //charge un dom avec les info et recupere tous les editables et les changes dans le dom d'origine pour mettre à jour - // a developper en prod recupere fichier - var ext = $(this)[0] - .files[0]['name'].substring( - $(this)[0].files[0]['name'].lastIndexOf('.') + 1 - ) - .toLowerCase(); - if ($(this)[0].files && $(this)[0].files[0] && ext == 'maildigit') - var reader = new FileReader(); - reader.onload = function(e) { - $('body').html(e.target.result); - }; - reader.readAsText($(this)[0].files[0]); - } - }); - - $('button.editersauve').on('click', function() { - //nettoie editeur - //$('p,h1,h2,h3,h4,a').removeAttr('contenteditable'); - //$('button.editersauve, p.editinfo').remove(); - //recupere body - var a = window.document.createElement('a'); - a.href = window.URL.createObjectURL( - new Blob([$('body').html()], { - type: 'text/csv;charset=utf-8;' - }) - ); - a.download = DOWNLOAD_NAME; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - }); -}; - -$(document).ready(function() { - if (window.location.href.indexOf('#editer_') > -1) edit.init(); -}); diff --git a/setup/data/domain/apixpress/www/cdn/public/js/formsave.js b/setup/data/domain/apixpress/www/cdn/public/js/formsave.js deleted file mode 100755 index e29dbb6..0000000 --- a/setup/data/domain/apixpress/www/cdn/public/js/formsave.js +++ /dev/null @@ -1,305 +0,0 @@ -/* -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -En cas de mofification des options => mettre à jour la doc du wiki gitlab -!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -*/ -const form = {}; -/* var ajaxget = function(url) { - $.ajax({ - url: `https://api.maildigit.fr/template/${url}.mustache`, - datatype: "jsonp", - success: function(tplq) { - logger.info(tplq); - logger.info(quest); - return Mustache.render(tplq, quest); - } - }); -};*/ -document.addEventListener('DOMContentLoaded', () => { - form.create(); -}); -/* - Cette partie sera généré dans les sections et il ne restera - que $('.formmanager form').gestionform() - - */ -// $(".formmanager").each(function(i) { -form.create = () => { - // alert("pass"); - document.querySelectorAll('div.formmanager').forEach(form => { - // let bloc = $(this).attr("id"); - const bloc = form.getAttribute('id'); - axios.get(`./${bloc}.json`).then(async formd => { - logger.info('formd', formd); - const formdef = formd.data; - // Liste les template - let tplname = [formdef.info.tpl]; - formdef.quest.forEach(quest => { - quest.idhtml = formdef.id; - tplname.indexOf(quest.tpl) == -1 ? - tplname.push(quest.tpl) : - (tplname = tplname); - }); - const tplhtml = await Promise.all( - tplname.map(t => - axios.get(`${pwa.urlbacknoauth}/template/${t}.mustache`) - ) - ); - const template = {}; - tplname.forEach((t, i) => { - template[t] = tplhtml[i].data; - }); - logger.info('template', template); - // Construire le form - formdef.content = formdef.quest - .map(quest => Mustache.render(template[quest.tpl], quest)) - .join(' '); - logger.info('formdef', formdef); - form.innerHTML = Mustache.render(template[formdef.info.tpl], formdef); - }); - }); -}; -/* - //https://api.maildigit.fr/template/ - $.get(data.info.tpl, function(tpl) { - let questhtml = $.map(data.quest, function(quest, q) { - logger.info(q); - logger.info(quest); - quest.idhtml = data.info.idhtml; - $.ajax({ - url: data.quest[q].tpl, - datatype: "jsonp", - async: false, - success: function(tplq) { - logger.info(tplq); - logger.info(quest); - return Mustache.render(tplq, quest); - } - }); - }); - logger.info(questhtml); - data.content = questhtml.join(" "); - logger.info(data); - let fullform = Mustache.to_html(tpl, data); - $(data.info.idhtml).html(fullform); - $(".formmanager form").gestionform(); - }); - }); - }); -});*/ - -form.manage = function() { - const form = $(this); - var lastdatasend = lastdatasend || ''; - form.find('input').keyup(function(e) { - if (e.which == 13) { - form.find('.btnSendForm').click(); - } - }); - form.find('select').on('click', function() { - const chph = $(this).data('hiddenchamps'); - const valh = $(this) - .find('option:selected') - .text(); - form.find('input[data-champs=\'' + chph + '\']').val(valh); - }); - form.find('.type-choix button').on('click', function() { - const blocchoix = $(this).closest('.type-choix'); - blocchoix.find('button').removeClass('active'); - $(this).addClass('active'); - form - .find('input[data-champs=\'' + blocchoix.data('champs') + '\']') - .val($(this).data('val')); - }); - form.find('.type-multichoix button').on('click', function(e) { - e.preventDefault(); - const reponsemultiple = []; - const blocmultichoix = $(this).closest('.type-multichoix'); - const champsdest = blocmultichoix.attr('data-champs'); - logger.info(champsdest); - const nbmaxchoix = parseInt(blocmultichoix.attr('data-nbmaxchoix')); - $(this).toggleClass('active'); - if ($('.type-multichoix button.active').length > nbmaxchoix) { - alert('Choisissez au maximum ' + nbmaxchoix + ' choix!'); - $(this).toggleClass('active'); - } else { - blocmultichoix.find('button.active').each(function(i) { - reponsemultiple.push($(this).attr('data-choix')); - }); - blocmultichoix - .find('input[data-champs=\'' + champsdest + '\']') - .val(JSON.stringify(reponsemultiple)); - } - }); - form.find('.btnSendForm').on('click', function(e) { - e.preventDefault(); - const formencours = $(this).closest('form'); - let r = localStorage.getItem('r'); - if (r == undefined) { - r = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { - let r = (Math.random() * 16) | 0, - v = c == 'x' ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); - localStorage.setItem('r', r); - } - const senddata = { - r: r - }; - let etat = ''; - let msgok = formencours.data('msgok'); - let msgko = formencours.data('msgko'); - formencours.find('textarea').each(function() { - senddata[$(this).data('champs')] = $(this).val(); - if ($(this).val() == '' && $(this).data('check') == 'notnull') { - etat += $(this).data('msgerreur') + '
'; - } - }); - formencours.find('.blochtml').each(function() { - senddata[$(this).data('champs')] = $(this).html(); - }); - formencours.find('input').each(function(i) { - senddata[$(this).data('champs')] = $(this).val(); - var reg = '{{' + $(this).data('champs') + '}}'; - msgok = msgok.replace(reg, $(this).val()); - msgko = msgko.replace(reg, $(this).val()); - - if ($(this).data('check') == 'email') { - /* - var reg = new RegExp( - '^[a-z0-9]+([_|.|-]{1}[a-z0-9]+)*@[a-z0-9]+([_|.|-]{1}[a-z0-9]+)*[.]{1}[a-z]{2,6}$', - 'i' - ); - var reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; - */ - var reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - - // logger.info($(this).val()); - // logger.info(reg.test($(this).val()) ); - if (!reg.test($(this).val())) { - if (!$(this).data('msgerreur')) { - etat += 'invalid email'; - } else { - etat += $(this).data('msgerreur') + '
'; - } - } - } - if ($(this).data('check') == 'phone') { - const phone = $(this) - .val() - .replace('+33', '0') - .replace(/[^0-9]/g, ''); - if (phone.length != 10) { - if (!$(this).data('msgerreur')) { - etat += 'invalid phone'; - } else { - etat += $(this).data('msgerreur') + '
'; - } - } - } - if ($(this).data('check') == 'notnull') { - if ($(this).val() == '') { - if (!$(this).data('msgerreur')) { - etat += 'empty field'; - } else { - etat += $(this).data('msgerreur') + '
'; - } - } - } - if ($(this).data('check') == 'valpositif') { - if (parseInt($(this).val()) < 0) { - if (!$(this).data('msgerreur')) { - etat += 'invalid value have to be positive'; - } else { - etat += 'valpos ' + $(this).data('msgerreur') + '
'; - } - } - } - if ($(this).data('check') == 'codepostal') { - if ($(this).val().length != 5) { - if (!$(this).data('msgerreur')) { - etat += 'invalid zipcode'; - } else { - etat += 'cp' + $(this).data('msgerreur') + '
'; - } - } - } - if ($(this).data('check') == 'departement') { - let dep = 0; - if ($.isNumeric($(this).val())) { - dep = parseInt($(this).val()); - } - if (!(dep > 0 && dep < 96)) { - if (!$(this).data('msgerreur')) { - etat += 'invalid french departement'; - } else { - etat += 'dep ' + $(this).data('msgerreur') + '
'; - } - } - } - }); - logger.info(JSON.stringify(senddata)); - let diff = false; - if (lastdatasend == '') { - diff = true; - } - $.each(lastdatasend, function(k, v) { - if (k in senddata && v != senddata[k]) { - diff = true; - } - }); - if (!diff) { - etat = - 'Action déjà effectuée, si vous recliquez, vous allez renvoyer la même demande'; - lastdatasend = ''; - } - logger.info(etat); - if (etat != '') { - formencours.find('p.msgform').html(etat); - } else { - logger.info( - 'https://api.maildigit.fr' + formencours.data('formmaildigit') - ); - logger.info( - formencours.data('tribeid') + - '_' + - $('html').attr('lang') + - '_' + - formencours.data('auth') + - '_' + - formencours.data('uuid') - ); - $.ajax({ - url: pwa.urlbacknoauth + formencours.data('formmaildigit'), - type: 'POST', - beforeSend: function(request) { - request.setRequestHeader('x-Client-id', formencours.data('tribeid')); - request.setRequestHeader('x-language', $('html').attr('lang')); - request.setRequestHeader('x-auth', formencours.data('auth')); - request.setRequestHeader('x-uuid', formencours.data('uuid')); - }, - data: senddata, - cache: false, - success: function(res) { - // logger.info(e); - var app = app || {}; - lastdatasend = senddata; - logger.info(formencours.data('msgok')); - logger.info(res); - if (res.idpanier) { - $('button.clickvalidecommande').data('idpanier', res.idpanier); - logger.info('trig clickvalidecommande via form'); - $('button.clickvalidecommande').trigger('click'); - } - formencours.find('p.msgform').html(msgok); - // var chargeext = app.custom(senddata) || 'Pas de custom à executer'; - }, - error: function(e) { - logger.info(e); - // formencours.data(state).val('error'); - formencours.find('p.msgform').html(msgko); - } - }); - } - }); -}; diff --git a/setup/data/domain/apixpress/www/cdn/public/js/jquery-3.6.0.js b/setup/data/domain/apixpress/www/cdn/public/js/jquery-3.6.0.js deleted file mode 100755 index fc6c299..0000000 --- a/setup/data/domain/apixpress/www/cdn/public/js/jquery-3.6.0.js +++ /dev/null @@ -1,10881 +0,0 @@ -/*! - * jQuery JavaScript Library v3.6.0 - * https://jquery.com/ - * - * Includes Sizzle.js - * https://sizzlejs.com/ - * - * Copyright OpenJS Foundation and other contributors - * Released under the MIT license - * https://jquery.org/license - * - * Date: 2021-03-02T17:08Z - */ -( function( global, factory ) { - - "use strict"; - - if ( typeof module === "object" && typeof module.exports === "object" ) { - - // For CommonJS and CommonJS-like environments where a proper `window` - // is present, execute the factory and get jQuery. - // For environments that do not have a `window` with a `document` - // (such as Node.js), expose a factory as module.exports. - // This accentuates the need for the creation of a real `window`. - // e.g. var jQuery = require("jquery")(window); - // See ticket #14549 for more info. - module.exports = global.document ? - factory( global, true ) : - function( w ) { - if ( !w.document ) { - throw new Error( "jQuery requires a window with a document" ); - } - return factory( w ); - }; - } else { - factory( global ); - } - -// Pass this if window is not defined yet -} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { - -// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 -// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode -// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common -// enough that all such attempts are guarded in a try block. -"use strict"; - -var arr = []; - -var getProto = Object.getPrototypeOf; - -var slice = arr.slice; - -var flat = arr.flat ? function( array ) { - return arr.flat.call( array ); -} : function( array ) { - return arr.concat.apply( [], array ); -}; - - -var push = arr.push; - -var indexOf = arr.indexOf; - -var class2type = {}; - -var toString = class2type.toString; - -var hasOwn = class2type.hasOwnProperty; - -var fnToString = hasOwn.toString; - -var ObjectFunctionString = fnToString.call( Object ); - -var support = {}; - -var isFunction = function isFunction( obj ) { - - // Support: Chrome <=57, Firefox <=52 - // In some browsers, typeof returns "function" for HTML elements - // (i.e., `typeof document.createElement( "object" ) === "function"`). - // We don't want to classify *any* DOM node as a function. - // Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5 - // Plus for old WebKit, typeof returns "function" for HTML collections - // (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756) - return typeof obj === "function" && typeof obj.nodeType !== "number" && - typeof obj.item !== "function"; - }; - - -var isWindow = function isWindow( obj ) { - return obj != null && obj === obj.window; - }; - - -var document = window.document; - - - - var preservedScriptAttributes = { - type: true, - src: true, - nonce: true, - noModule: true - }; - - function DOMEval( code, node, doc ) { - doc = doc || document; - - var i, val, - script = doc.createElement( "script" ); - - script.text = code; - if ( node ) { - for ( i in preservedScriptAttributes ) { - - // Support: Firefox 64+, Edge 18+ - // Some browsers don't support the "nonce" property on scripts. - // On the other hand, just using `getAttribute` is not enough as - // the `nonce` attribute is reset to an empty string whenever it - // becomes browsing-context connected. - // See https://github.com/whatwg/html/issues/2369 - // See https://html.spec.whatwg.org/#nonce-attributes - // The `node.getAttribute` check was added for the sake of - // `jQuery.globalEval` so that it can fake a nonce-containing node - // via an object. - val = node[ i ] || node.getAttribute && node.getAttribute( i ); - if ( val ) { - script.setAttribute( i, val ); - } - } - } - doc.head.appendChild( script ).parentNode.removeChild( script ); - } - - -function toType( obj ) { - if ( obj == null ) { - return obj + ""; - } - - // Support: Android <=2.3 only (functionish RegExp) - return typeof obj === "object" || typeof obj === "function" ? - class2type[ toString.call( obj ) ] || "object" : - typeof obj; -} -/* global Symbol */ -// Defining this global in .eslintrc.json would create a danger of using the global -// unguarded in another place, it seems safer to define global only for this module - - - -var - version = "3.6.0", - - // Define a local copy of jQuery - jQuery = function( selector, context ) { - - // The jQuery object is actually just the init constructor 'enhanced' - // Need init if jQuery is called (just allow error to be thrown if not included) - return new jQuery.fn.init( selector, context ); - }; - -jQuery.fn = jQuery.prototype = { - - // The current version of jQuery being used - jquery: version, - - constructor: jQuery, - - // The default length of a jQuery object is 0 - length: 0, - - toArray: function() { - return slice.call( this ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - - // Return all the elements in a clean array - if ( num == null ) { - return slice.call( this ); - } - - // Return just the one element from the set - return num < 0 ? this[ num + this.length ] : this[ num ]; - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems ) { - - // Build a new jQuery matched element set - var ret = jQuery.merge( this.constructor(), elems ); - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - each: function( callback ) { - return jQuery.each( this, callback ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map( this, function( elem, i ) { - return callback.call( elem, i, elem ); - } ) ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ) ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - even: function() { - return this.pushStack( jQuery.grep( this, function( _elem, i ) { - return ( i + 1 ) % 2; - } ) ); - }, - - odd: function() { - return this.pushStack( jQuery.grep( this, function( _elem, i ) { - return i % 2; - } ) ); - }, - - eq: function( i ) { - var len = this.length, - j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); - }, - - end: function() { - return this.prevObject || this.constructor(); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: arr.sort, - splice: arr.splice -}; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[ 0 ] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - - // Skip the boolean and the target - target = arguments[ i ] || {}; - i++; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !isFunction( target ) ) { - target = {}; - } - - // Extend jQuery itself if only one argument is passed - if ( i === length ) { - target = this; - i--; - } - - for ( ; i < length; i++ ) { - - // Only deal with non-null/undefined values - if ( ( options = arguments[ i ] ) != null ) { - - // Extend the base object - for ( name in options ) { - copy = options[ name ]; - - // Prevent Object.prototype pollution - // Prevent never-ending loop - if ( name === "__proto__" || target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject( copy ) || - ( copyIsArray = Array.isArray( copy ) ) ) ) { - src = target[ name ]; - - // Ensure proper type for the source value - if ( copyIsArray && !Array.isArray( src ) ) { - clone = []; - } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { - clone = {}; - } else { - clone = src; - } - copyIsArray = false; - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend( { - - // Unique for each copy of jQuery on the page - expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), - - // Assume jQuery is ready without the ready module - isReady: true, - - error: function( msg ) { - throw new Error( msg ); - }, - - noop: function() {}, - - isPlainObject: function( obj ) { - var proto, Ctor; - - // Detect obvious negatives - // Use toString instead of jQuery.type to catch host objects - if ( !obj || toString.call( obj ) !== "[object Object]" ) { - return false; - } - - proto = getProto( obj ); - - // Objects with no prototype (e.g., `Object.create( null )`) are plain - if ( !proto ) { - return true; - } - - // Objects with prototype are plain iff they were constructed by a global Object function - Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; - return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; - }, - - isEmptyObject: function( obj ) { - var name; - - for ( name in obj ) { - return false; - } - return true; - }, - - // Evaluates a script in a provided context; falls back to the global one - // if not specified. - globalEval: function( code, options, doc ) { - DOMEval( code, { nonce: options && options.nonce }, doc ); - }, - - each: function( obj, callback ) { - var length, i = 0; - - if ( isArrayLike( obj ) ) { - length = obj.length; - for ( ; i < length; i++ ) { - if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { - break; - } - } - } else { - for ( i in obj ) { - if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { - break; - } - } - } - - return obj; - }, - - // results is for internal usage only - makeArray: function( arr, results ) { - var ret = results || []; - - if ( arr != null ) { - if ( isArrayLike( Object( arr ) ) ) { - jQuery.merge( ret, - typeof arr === "string" ? - [ arr ] : arr - ); - } else { - push.call( ret, arr ); - } - } - - return ret; - }, - - inArray: function( elem, arr, i ) { - return arr == null ? -1 : indexOf.call( arr, elem, i ); - }, - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - merge: function( first, second ) { - var len = +second.length, - j = 0, - i = first.length; - - for ( ; j < len; j++ ) { - first[ i++ ] = second[ j ]; - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, invert ) { - var callbackInverse, - matches = [], - i = 0, - length = elems.length, - callbackExpect = !invert; - - // Go through the array, only saving the items - // that pass the validator function - for ( ; i < length; i++ ) { - callbackInverse = !callback( elems[ i ], i ); - if ( callbackInverse !== callbackExpect ) { - matches.push( elems[ i ] ); - } - } - - return matches; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var length, value, - i = 0, - ret = []; - - // Go through the array, translating each of the items to their new values - if ( isArrayLike( elems ) ) { - length = elems.length; - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - - // Go through every key on the object, - } else { - for ( i in elems ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret.push( value ); - } - } - } - - // Flatten any nested arrays - return flat( ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // jQuery.support is not used in Core but other projects attach their - // properties to it so it needs to exist. - support: support -} ); - -if ( typeof Symbol === "function" ) { - jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; -} - -// Populate the class2type map -jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), - function( _i, name ) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); - } ); - -function isArrayLike( obj ) { - - // Support: real iOS 8.2 only (not reproducible in simulator) - // `in` check used to prevent JIT error (gh-2145) - // hasOwn isn't used here due to false negatives - // regarding Nodelist length in IE - var length = !!obj && "length" in obj && obj.length, - type = toType( obj ); - - if ( isFunction( obj ) || isWindow( obj ) ) { - return false; - } - - return type === "array" || length === 0 || - typeof length === "number" && length > 0 && ( length - 1 ) in obj; -} -var Sizzle = -/*! - * Sizzle CSS Selector Engine v2.3.6 - * https://sizzlejs.com/ - * - * Copyright JS Foundation and other contributors - * Released under the MIT license - * https://js.foundation/ - * - * Date: 2021-02-16 - */ -( function( window ) { -var i, - support, - Expr, - getText, - isXML, - tokenize, - compile, - select, - outermostContext, - sortInput, - hasDuplicate, - - // Local document vars - setDocument, - document, - docElem, - documentIsHTML, - rbuggyQSA, - rbuggyMatches, - matches, - contains, - - // Instance-specific data - expando = "sizzle" + 1 * new Date(), - preferredDoc = window.document, - dirruns = 0, - done = 0, - classCache = createCache(), - tokenCache = createCache(), - compilerCache = createCache(), - nonnativeSelectorCache = createCache(), - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - } - return 0; - }, - - // Instance methods - hasOwn = ( {} ).hasOwnProperty, - arr = [], - pop = arr.pop, - pushNative = arr.push, - push = arr.push, - slice = arr.slice, - - // Use a stripped-down indexOf as it's faster than native - // https://jsperf.com/thor-indexof-vs-for/5 - indexOf = function( list, elem ) { - var i = 0, - len = list.length; - for ( ; i < len; i++ ) { - if ( list[ i ] === elem ) { - return i; - } - } - return -1; - }, - - booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + - "ismap|loop|multiple|open|readonly|required|scoped", - - // Regular expressions - - // http://www.w3.org/TR/css3-selectors/#whitespace - whitespace = "[\\x20\\t\\r\\n\\f]", - - // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram - identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + - "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", - - // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors - attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + - - // Operator (capture 2) - "*([*^$|!~]?=)" + whitespace + - - // "Attribute values must be CSS identifiers [capture 5] - // or strings [capture 3 or capture 4]" - "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + - whitespace + "*\\]", - - pseudos = ":(" + identifier + ")(?:\\((" + - - // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: - // 1. quoted (capture 3; capture 4 or capture 5) - "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + - - // 2. simple (capture 6) - "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + - - // 3. anything else (capture 2) - ".*" + - ")\\)|)", - - // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter - rwhitespace = new RegExp( whitespace + "+", "g" ), - rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + - whitespace + "+$", "g" ), - - rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), - rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + - "*" ), - rdescend = new RegExp( whitespace + "|>" ), - - rpseudo = new RegExp( pseudos ), - ridentifier = new RegExp( "^" + identifier + "$" ), - - matchExpr = { - "ID": new RegExp( "^#(" + identifier + ")" ), - "CLASS": new RegExp( "^\\.(" + identifier + ")" ), - "TAG": new RegExp( "^(" + identifier + "|[*])" ), - "ATTR": new RegExp( "^" + attributes ), - "PSEUDO": new RegExp( "^" + pseudos ), - "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + - whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + - whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), - "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), - - // For use in libraries implementing .is() - // We use this for POS matching in `select` - "needsContext": new RegExp( "^" + whitespace + - "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + - "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) - }, - - rhtml = /HTML$/i, - rinputs = /^(?:input|select|textarea|button)$/i, - rheader = /^h\d$/i, - - rnative = /^[^{]+\{\s*\[native \w/, - - // Easily-parseable/retrievable ID or TAG or CLASS selectors - rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, - - rsibling = /[+~]/, - - // CSS escapes - // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters - runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), - funescape = function( escape, nonHex ) { - var high = "0x" + escape.slice( 1 ) - 0x10000; - - return nonHex ? - - // Strip the backslash prefix from a non-hex escape sequence - nonHex : - - // Replace a hexadecimal escape sequence with the encoded Unicode code point - // Support: IE <=11+ - // For values outside the Basic Multilingual Plane (BMP), manually construct a - // surrogate pair - high < 0 ? - String.fromCharCode( high + 0x10000 ) : - String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }, - - // CSS string/identifier serialization - // https://drafts.csswg.org/cssom/#common-serializing-idioms - rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, - fcssescape = function( ch, asCodePoint ) { - if ( asCodePoint ) { - - // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER - if ( ch === "\0" ) { - return "\uFFFD"; - } - - // Control characters and (dependent upon position) numbers get escaped as code points - return ch.slice( 0, -1 ) + "\\" + - ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; - } - - // Other potentially-special ASCII characters get backslash-escaped - return "\\" + ch; - }, - - // Used for iframes - // See setDocument() - // Removing the function wrapper causes a "Permission Denied" - // error in IE - unloadHandler = function() { - setDocument(); - }, - - inDisabledFieldset = addCombinator( - function( elem ) { - return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; - }, - { dir: "parentNode", next: "legend" } - ); - -// Optimize for push.apply( _, NodeList ) -try { - push.apply( - ( arr = slice.call( preferredDoc.childNodes ) ), - preferredDoc.childNodes - ); - - // Support: Android<4.0 - // Detect silently failing push.apply - // eslint-disable-next-line no-unused-expressions - arr[ preferredDoc.childNodes.length ].nodeType; -} catch ( e ) { - push = { apply: arr.length ? - - // Leverage slice if possible - function( target, els ) { - pushNative.apply( target, slice.call( els ) ); - } : - - // Support: IE<9 - // Otherwise append directly - function( target, els ) { - var j = target.length, - i = 0; - - // Can't trust NodeList.length - while ( ( target[ j++ ] = els[ i++ ] ) ) {} - target.length = j - 1; - } - }; -} - -function Sizzle( selector, context, results, seed ) { - var m, i, elem, nid, match, groups, newSelector, - newContext = context && context.ownerDocument, - - // nodeType defaults to 9, since context defaults to document - nodeType = context ? context.nodeType : 9; - - results = results || []; - - // Return early from calls with invalid selector or context - if ( typeof selector !== "string" || !selector || - nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { - - return results; - } - - // Try to shortcut find operations (as opposed to filters) in HTML documents - if ( !seed ) { - setDocument( context ); - context = context || document; - - if ( documentIsHTML ) { - - // If the selector is sufficiently simple, try using a "get*By*" DOM method - // (excepting DocumentFragment context, where the methods don't exist) - if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { - - // ID selector - if ( ( m = match[ 1 ] ) ) { - - // Document context - if ( nodeType === 9 ) { - if ( ( elem = context.getElementById( m ) ) ) { - - // Support: IE, Opera, Webkit - // TODO: identify versions - // getElementById can match elements by name instead of ID - if ( elem.id === m ) { - results.push( elem ); - return results; - } - } else { - return results; - } - - // Element context - } else { - - // Support: IE, Opera, Webkit - // TODO: identify versions - // getElementById can match elements by name instead of ID - if ( newContext && ( elem = newContext.getElementById( m ) ) && - contains( context, elem ) && - elem.id === m ) { - - results.push( elem ); - return results; - } - } - - // Type selector - } else if ( match[ 2 ] ) { - push.apply( results, context.getElementsByTagName( selector ) ); - return results; - - // Class selector - } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && - context.getElementsByClassName ) { - - push.apply( results, context.getElementsByClassName( m ) ); - return results; - } - } - - // Take advantage of querySelectorAll - if ( support.qsa && - !nonnativeSelectorCache[ selector + " " ] && - ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && - - // Support: IE 8 only - // Exclude object elements - ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { - - newSelector = selector; - newContext = context; - - // qSA considers elements outside a scoping root when evaluating child or - // descendant combinators, which is not what we want. - // In such cases, we work around the behavior by prefixing every selector in the - // list with an ID selector referencing the scope context. - // The technique has to be used as well when a leading combinator is used - // as such selectors are not recognized by querySelectorAll. - // Thanks to Andrew Dupont for this technique. - if ( nodeType === 1 && - ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { - - // Expand context for sibling selectors - newContext = rsibling.test( selector ) && testContext( context.parentNode ) || - context; - - // We can use :scope instead of the ID hack if the browser - // supports it & if we're not changing the context. - if ( newContext !== context || !support.scope ) { - - // Capture the context ID, setting it first if necessary - if ( ( nid = context.getAttribute( "id" ) ) ) { - nid = nid.replace( rcssescape, fcssescape ); - } else { - context.setAttribute( "id", ( nid = expando ) ); - } - } - - // Prefix every selector in the list - groups = tokenize( selector ); - i = groups.length; - while ( i-- ) { - groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + - toSelector( groups[ i ] ); - } - newSelector = groups.join( "," ); - } - - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); - return results; - } catch ( qsaError ) { - nonnativeSelectorCache( selector, true ); - } finally { - if ( nid === expando ) { - context.removeAttribute( "id" ); - } - } - } - } - } - - // All others - return select( selector.replace( rtrim, "$1" ), context, results, seed ); -} - -/** - * Create key-value caches of limited size - * @returns {function(string, object)} Returns the Object data after storing it on itself with - * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) - * deleting the oldest entry - */ -function createCache() { - var keys = []; - - function cache( key, value ) { - - // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) - if ( keys.push( key + " " ) > Expr.cacheLength ) { - - // Only keep the most recent entries - delete cache[ keys.shift() ]; - } - return ( cache[ key + " " ] = value ); - } - return cache; -} - -/** - * Mark a function for special use by Sizzle - * @param {Function} fn The function to mark - */ -function markFunction( fn ) { - fn[ expando ] = true; - return fn; -} - -/** - * Support testing using an element - * @param {Function} fn Passed the created element and returns a boolean result - */ -function assert( fn ) { - var el = document.createElement( "fieldset" ); - - try { - return !!fn( el ); - } catch ( e ) { - return false; - } finally { - - // Remove from its parent by default - if ( el.parentNode ) { - el.parentNode.removeChild( el ); - } - - // release memory in IE - el = null; - } -} - -/** - * Adds the same handler for all of the specified attrs - * @param {String} attrs Pipe-separated list of attributes - * @param {Function} handler The method that will be applied - */ -function addHandle( attrs, handler ) { - var arr = attrs.split( "|" ), - i = arr.length; - - while ( i-- ) { - Expr.attrHandle[ arr[ i ] ] = handler; - } -} - -/** - * Checks document order of two siblings - * @param {Element} a - * @param {Element} b - * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b - */ -function siblingCheck( a, b ) { - var cur = b && a, - diff = cur && a.nodeType === 1 && b.nodeType === 1 && - a.sourceIndex - b.sourceIndex; - - // Use IE sourceIndex if available on both nodes - if ( diff ) { - return diff; - } - - // Check if b follows a - if ( cur ) { - while ( ( cur = cur.nextSibling ) ) { - if ( cur === b ) { - return -1; - } - } - } - - return a ? 1 : -1; -} - -/** - * Returns a function to use in pseudos for input types - * @param {String} type - */ -function createInputPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for buttons - * @param {String} type - */ -function createButtonPseudo( type ) { - return function( elem ) { - var name = elem.nodeName.toLowerCase(); - return ( name === "input" || name === "button" ) && elem.type === type; - }; -} - -/** - * Returns a function to use in pseudos for :enabled/:disabled - * @param {Boolean} disabled true for :disabled; false for :enabled - */ -function createDisabledPseudo( disabled ) { - - // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable - return function( elem ) { - - // Only certain elements can match :enabled or :disabled - // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled - // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled - if ( "form" in elem ) { - - // Check for inherited disabledness on relevant non-disabled elements: - // * listed form-associated elements in a disabled fieldset - // https://html.spec.whatwg.org/multipage/forms.html#category-listed - // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled - // * option elements in a disabled optgroup - // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled - // All such elements have a "form" property. - if ( elem.parentNode && elem.disabled === false ) { - - // Option elements defer to a parent optgroup if present - if ( "label" in elem ) { - if ( "label" in elem.parentNode ) { - return elem.parentNode.disabled === disabled; - } else { - return elem.disabled === disabled; - } - } - - // Support: IE 6 - 11 - // Use the isDisabled shortcut property to check for disabled fieldset ancestors - return elem.isDisabled === disabled || - - // Where there is no isDisabled, check manually - /* jshint -W018 */ - elem.isDisabled !== !disabled && - inDisabledFieldset( elem ) === disabled; - } - - return elem.disabled === disabled; - - // Try to winnow out elements that can't be disabled before trusting the disabled property. - // Some victims get caught in our net (label, legend, menu, track), but it shouldn't - // even exist on them, let alone have a boolean value. - } else if ( "label" in elem ) { - return elem.disabled === disabled; - } - - // Remaining elements are neither :enabled nor :disabled - return false; - }; -} - -/** - * Returns a function to use in pseudos for positionals - * @param {Function} fn - */ -function createPositionalPseudo( fn ) { - return markFunction( function( argument ) { - argument = +argument; - return markFunction( function( seed, matches ) { - var j, - matchIndexes = fn( [], seed.length, argument ), - i = matchIndexes.length; - - // Match elements found at the specified indexes - while ( i-- ) { - if ( seed[ ( j = matchIndexes[ i ] ) ] ) { - seed[ j ] = !( matches[ j ] = seed[ j ] ); - } - } - } ); - } ); -} - -/** - * Checks a node for validity as a Sizzle context - * @param {Element|Object=} context - * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value - */ -function testContext( context ) { - return context && typeof context.getElementsByTagName !== "undefined" && context; -} - -// Expose support vars for convenience -support = Sizzle.support = {}; - -/** - * Detects XML nodes - * @param {Element|Object} elem An element or a document - * @returns {Boolean} True iff elem is a non-HTML XML node - */ -isXML = Sizzle.isXML = function( elem ) { - var namespace = elem && elem.namespaceURI, - docElem = elem && ( elem.ownerDocument || elem ).documentElement; - - // Support: IE <=8 - // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes - // https://bugs.jquery.com/ticket/4833 - return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); -}; - -/** - * Sets document-related variables once based on the current document - * @param {Element|Object} [doc] An element or document object to use to set the document - * @returns {Object} Returns the current document - */ -setDocument = Sizzle.setDocument = function( node ) { - var hasCompare, subWindow, - doc = node ? node.ownerDocument || node : preferredDoc; - - // Return early if doc is invalid or already selected - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { - return document; - } - - // Update global variables - document = doc; - docElem = document.documentElement; - documentIsHTML = !isXML( document ); - - // Support: IE 9 - 11+, Edge 12 - 18+ - // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( preferredDoc != document && - ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { - - // Support: IE 11, Edge - if ( subWindow.addEventListener ) { - subWindow.addEventListener( "unload", unloadHandler, false ); - - // Support: IE 9 - 10 only - } else if ( subWindow.attachEvent ) { - subWindow.attachEvent( "onunload", unloadHandler ); - } - } - - // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, - // Safari 4 - 5 only, Opera <=11.6 - 12.x only - // IE/Edge & older browsers don't support the :scope pseudo-class. - // Support: Safari 6.0 only - // Safari 6.0 supports :scope but it's an alias of :root there. - support.scope = assert( function( el ) { - docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); - return typeof el.querySelectorAll !== "undefined" && - !el.querySelectorAll( ":scope fieldset div" ).length; - } ); - - /* Attributes - ---------------------------------------------------------------------- */ - - // Support: IE<8 - // Verify that getAttribute really returns attributes and not properties - // (excepting IE8 booleans) - support.attributes = assert( function( el ) { - el.className = "i"; - return !el.getAttribute( "className" ); - } ); - - /* getElement(s)By* - ---------------------------------------------------------------------- */ - - // Check if getElementsByTagName("*") returns only elements - support.getElementsByTagName = assert( function( el ) { - el.appendChild( document.createComment( "" ) ); - return !el.getElementsByTagName( "*" ).length; - } ); - - // Support: IE<9 - support.getElementsByClassName = rnative.test( document.getElementsByClassName ); - - // Support: IE<10 - // Check if getElementById returns elements by name - // The broken getElementById methods don't pick up programmatically-set names, - // so use a roundabout getElementsByName test - support.getById = assert( function( el ) { - docElem.appendChild( el ).id = expando; - return !document.getElementsByName || !document.getElementsByName( expando ).length; - } ); - - // ID filter and find - if ( support.getById ) { - Expr.filter[ "ID" ] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - return elem.getAttribute( "id" ) === attrId; - }; - }; - Expr.find[ "ID" ] = function( id, context ) { - if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { - var elem = context.getElementById( id ); - return elem ? [ elem ] : []; - } - }; - } else { - Expr.filter[ "ID" ] = function( id ) { - var attrId = id.replace( runescape, funescape ); - return function( elem ) { - var node = typeof elem.getAttributeNode !== "undefined" && - elem.getAttributeNode( "id" ); - return node && node.value === attrId; - }; - }; - - // Support: IE 6 - 7 only - // getElementById is not reliable as a find shortcut - Expr.find[ "ID" ] = function( id, context ) { - if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { - var node, i, elems, - elem = context.getElementById( id ); - - if ( elem ) { - - // Verify the id attribute - node = elem.getAttributeNode( "id" ); - if ( node && node.value === id ) { - return [ elem ]; - } - - // Fall back on getElementsByName - elems = context.getElementsByName( id ); - i = 0; - while ( ( elem = elems[ i++ ] ) ) { - node = elem.getAttributeNode( "id" ); - if ( node && node.value === id ) { - return [ elem ]; - } - } - } - - return []; - } - }; - } - - // Tag - Expr.find[ "TAG" ] = support.getElementsByTagName ? - function( tag, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( tag ); - - // DocumentFragment nodes don't have gEBTN - } else if ( support.qsa ) { - return context.querySelectorAll( tag ); - } - } : - - function( tag, context ) { - var elem, - tmp = [], - i = 0, - - // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too - results = context.getElementsByTagName( tag ); - - // Filter out possible comments - if ( tag === "*" ) { - while ( ( elem = results[ i++ ] ) ) { - if ( elem.nodeType === 1 ) { - tmp.push( elem ); - } - } - - return tmp; - } - return results; - }; - - // Class - Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { - if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { - return context.getElementsByClassName( className ); - } - }; - - /* QSA/matchesSelector - ---------------------------------------------------------------------- */ - - // QSA and matchesSelector support - - // matchesSelector(:active) reports false when true (IE9/Opera 11.5) - rbuggyMatches = []; - - // qSa(:focus) reports false when true (Chrome 21) - // We allow this because of a bug in IE8/9 that throws an error - // whenever `document.activeElement` is accessed on an iframe - // So, we allow :focus to pass through QSA all the time to avoid the IE error - // See https://bugs.jquery.com/ticket/13378 - rbuggyQSA = []; - - if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { - - // Build QSA regex - // Regex strategy adopted from Diego Perini - assert( function( el ) { - - var input; - - // Select is set to empty string on purpose - // This is to test IE's treatment of not explicitly - // setting a boolean content attribute, - // since its presence should be enough - // https://bugs.jquery.com/ticket/12359 - docElem.appendChild( el ).innerHTML = "" + - ""; - - // Support: IE8, Opera 11-12.16 - // Nothing should be selected when empty strings follow ^= or $= or *= - // The test attribute must be unknown in Opera but "safe" for WinRT - // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section - if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { - rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); - } - - // Support: IE8 - // Boolean attributes and "value" are not treated correctly - if ( !el.querySelectorAll( "[selected]" ).length ) { - rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); - } - - // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ - if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { - rbuggyQSA.push( "~=" ); - } - - // Support: IE 11+, Edge 15 - 18+ - // IE 11/Edge don't find elements on a `[name='']` query in some cases. - // Adding a temporary attribute to the document before the selection works - // around the issue. - // Interestingly, IE 10 & older don't seem to have the issue. - input = document.createElement( "input" ); - input.setAttribute( "name", "" ); - el.appendChild( input ); - if ( !el.querySelectorAll( "[name='']" ).length ) { - rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + - whitespace + "*(?:''|\"\")" ); - } - - // Webkit/Opera - :checked should return selected option elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - // IE8 throws error here and will not see later tests - if ( !el.querySelectorAll( ":checked" ).length ) { - rbuggyQSA.push( ":checked" ); - } - - // Support: Safari 8+, iOS 8+ - // https://bugs.webkit.org/show_bug.cgi?id=136851 - // In-page `selector#id sibling-combinator selector` fails - if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { - rbuggyQSA.push( ".#.+[+~]" ); - } - - // Support: Firefox <=3.6 - 5 only - // Old Firefox doesn't throw on a badly-escaped identifier. - el.querySelectorAll( "\\\f" ); - rbuggyQSA.push( "[\\r\\n\\f]" ); - } ); - - assert( function( el ) { - el.innerHTML = "" + - ""; - - // Support: Windows 8 Native Apps - // The type and name attributes are restricted during .innerHTML assignment - var input = document.createElement( "input" ); - input.setAttribute( "type", "hidden" ); - el.appendChild( input ).setAttribute( "name", "D" ); - - // Support: IE8 - // Enforce case-sensitivity of name attribute - if ( el.querySelectorAll( "[name=d]" ).length ) { - rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); - } - - // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) - // IE8 throws error here and will not see later tests - if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Support: IE9-11+ - // IE's :disabled selector does not pick up the children of disabled fieldsets - docElem.appendChild( el ).disabled = true; - if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { - rbuggyQSA.push( ":enabled", ":disabled" ); - } - - // Support: Opera 10 - 11 only - // Opera 10-11 does not throw on post-comma invalid pseudos - el.querySelectorAll( "*,:x" ); - rbuggyQSA.push( ",.*:" ); - } ); - } - - if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || - docElem.webkitMatchesSelector || - docElem.mozMatchesSelector || - docElem.oMatchesSelector || - docElem.msMatchesSelector ) ) ) ) { - - assert( function( el ) { - - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9) - support.disconnectedMatch = matches.call( el, "*" ); - - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( el, "[s!='']:x" ); - rbuggyMatches.push( "!=", pseudos ); - } ); - } - - rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); - rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); - - /* Contains - ---------------------------------------------------------------------- */ - hasCompare = rnative.test( docElem.compareDocumentPosition ); - - // Element contains another - // Purposefully self-exclusive - // As in, an element does not contain itself - contains = hasCompare || rnative.test( docElem.contains ) ? - function( a, b ) { - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - ) ); - } : - function( a, b ) { - if ( b ) { - while ( ( b = b.parentNode ) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; - - /* Sorting - ---------------------------------------------------------------------- */ - - // Document order sorting - sortOrder = hasCompare ? - function( a, b ) { - - // Flag for duplicate removal - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - // Sort on method existence if only one input has compareDocumentPosition - var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; - if ( compare ) { - return compare; - } - - // Calculate position if both inputs belong to the same document - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? - a.compareDocumentPosition( b ) : - - // Otherwise we know they are disconnected - 1; - - // Disconnected nodes - if ( compare & 1 || - ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { - - // Choose the first element that is related to our preferred document - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( a == document || a.ownerDocument == preferredDoc && - contains( preferredDoc, a ) ) { - return -1; - } - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( b == document || b.ownerDocument == preferredDoc && - contains( preferredDoc, b ) ) { - return 1; - } - - // Maintain original order - return sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - } - - return compare & 4 ? -1 : 1; - } : - function( a, b ) { - - // Exit early if the nodes are identical - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - var cur, - i = 0, - aup = a.parentNode, - bup = b.parentNode, - ap = [ a ], - bp = [ b ]; - - // Parentless nodes are either documents or disconnected - if ( !aup || !bup ) { - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - /* eslint-disable eqeqeq */ - return a == document ? -1 : - b == document ? 1 : - /* eslint-enable eqeqeq */ - aup ? -1 : - bup ? 1 : - sortInput ? - ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : - 0; - - // If the nodes are siblings, we can do a quick check - } else if ( aup === bup ) { - return siblingCheck( a, b ); - } - - // Otherwise we need full lists of their ancestors for comparison - cur = a; - while ( ( cur = cur.parentNode ) ) { - ap.unshift( cur ); - } - cur = b; - while ( ( cur = cur.parentNode ) ) { - bp.unshift( cur ); - } - - // Walk down the tree looking for a discrepancy - while ( ap[ i ] === bp[ i ] ) { - i++; - } - - return i ? - - // Do a sibling check if the nodes have a common ancestor - siblingCheck( ap[ i ], bp[ i ] ) : - - // Otherwise nodes in our document sort first - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - /* eslint-disable eqeqeq */ - ap[ i ] == preferredDoc ? -1 : - bp[ i ] == preferredDoc ? 1 : - /* eslint-enable eqeqeq */ - 0; - }; - - return document; -}; - -Sizzle.matches = function( expr, elements ) { - return Sizzle( expr, null, null, elements ); -}; - -Sizzle.matchesSelector = function( elem, expr ) { - setDocument( elem ); - - if ( support.matchesSelector && documentIsHTML && - !nonnativeSelectorCache[ expr + " " ] && - ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && - ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { - - try { - var ret = matches.call( elem, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || support.disconnectedMatch || - - // As well, disconnected nodes are said to be in a document - // fragment in IE 9 - elem.document && elem.document.nodeType !== 11 ) { - return ret; - } - } catch ( e ) { - nonnativeSelectorCache( expr, true ); - } - } - - return Sizzle( expr, document, null, [ elem ] ).length > 0; -}; - -Sizzle.contains = function( context, elem ) { - - // Set document vars if needed - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( ( context.ownerDocument || context ) != document ) { - setDocument( context ); - } - return contains( context, elem ); -}; - -Sizzle.attr = function( elem, name ) { - - // Set document vars if needed - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( ( elem.ownerDocument || elem ) != document ) { - setDocument( elem ); - } - - var fn = Expr.attrHandle[ name.toLowerCase() ], - - // Don't get fooled by Object.prototype properties (jQuery #13807) - val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? - fn( elem, name, !documentIsHTML ) : - undefined; - - return val !== undefined ? - val : - support.attributes || !documentIsHTML ? - elem.getAttribute( name ) : - ( val = elem.getAttributeNode( name ) ) && val.specified ? - val.value : - null; -}; - -Sizzle.escape = function( sel ) { - return ( sel + "" ).replace( rcssescape, fcssescape ); -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -/** - * Document sorting and removing duplicates - * @param {ArrayLike} results - */ -Sizzle.uniqueSort = function( results ) { - var elem, - duplicates = [], - j = 0, - i = 0; - - // Unless we *know* we can detect duplicates, assume their presence - hasDuplicate = !support.detectDuplicates; - sortInput = !support.sortStable && results.slice( 0 ); - results.sort( sortOrder ); - - if ( hasDuplicate ) { - while ( ( elem = results[ i++ ] ) ) { - if ( elem === results[ i ] ) { - j = duplicates.push( i ); - } - } - while ( j-- ) { - results.splice( duplicates[ j ], 1 ); - } - } - - // Clear input after sorting to release objects - // See https://github.com/jquery/sizzle/pull/225 - sortInput = null; - - return results; -}; - -/** - * Utility function for retrieving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -getText = Sizzle.getText = function( elem ) { - var node, - ret = "", - i = 0, - nodeType = elem.nodeType; - - if ( !nodeType ) { - - // If no nodeType, this is expected to be an array - while ( ( node = elem[ i++ ] ) ) { - - // Do not traverse comment nodes - ret += getText( node ); - } - } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { - - // Use textContent for elements - // innerText usage removed for consistency of new lines (jQuery #11153) - if ( typeof elem.textContent === "string" ) { - return elem.textContent; - } else { - - // Traverse its children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - - // Do not include comment or processing instruction nodes - - return ret; -}; - -Expr = Sizzle.selectors = { - - // Can be adjusted by the user - cacheLength: 50, - - createPseudo: markFunction, - - match: matchExpr, - - attrHandle: {}, - - find: {}, - - relative: { - ">": { dir: "parentNode", first: true }, - " ": { dir: "parentNode" }, - "+": { dir: "previousSibling", first: true }, - "~": { dir: "previousSibling" } - }, - - preFilter: { - "ATTR": function( match ) { - match[ 1 ] = match[ 1 ].replace( runescape, funescape ); - - // Move the given value to match[3] whether quoted or unquoted - match[ 3 ] = ( match[ 3 ] || match[ 4 ] || - match[ 5 ] || "" ).replace( runescape, funescape ); - - if ( match[ 2 ] === "~=" ) { - match[ 3 ] = " " + match[ 3 ] + " "; - } - - return match.slice( 0, 4 ); - }, - - "CHILD": function( match ) { - - /* matches from matchExpr["CHILD"] - 1 type (only|nth|...) - 2 what (child|of-type) - 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) - 4 xn-component of xn+y argument ([+-]?\d*n|) - 5 sign of xn-component - 6 x of xn-component - 7 sign of y-component - 8 y of y-component - */ - match[ 1 ] = match[ 1 ].toLowerCase(); - - if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { - - // nth-* requires argument - if ( !match[ 3 ] ) { - Sizzle.error( match[ 0 ] ); - } - - // numeric x and y parameters for Expr.filter.CHILD - // remember that false/true cast respectively to 0/1 - match[ 4 ] = +( match[ 4 ] ? - match[ 5 ] + ( match[ 6 ] || 1 ) : - 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); - match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); - - // other types prohibit arguments - } else if ( match[ 3 ] ) { - Sizzle.error( match[ 0 ] ); - } - - return match; - }, - - "PSEUDO": function( match ) { - var excess, - unquoted = !match[ 6 ] && match[ 2 ]; - - if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { - return null; - } - - // Accept quoted arguments as-is - if ( match[ 3 ] ) { - match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; - - // Strip excess characters from unquoted arguments - } else if ( unquoted && rpseudo.test( unquoted ) && - - // Get excess from tokenize (recursively) - ( excess = tokenize( unquoted, true ) ) && - - // advance to the next closing parenthesis - ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { - - // excess is a negative index - match[ 0 ] = match[ 0 ].slice( 0, excess ); - match[ 2 ] = unquoted.slice( 0, excess ); - } - - // Return only captures needed by the pseudo filter method (type and argument) - return match.slice( 0, 3 ); - } - }, - - filter: { - - "TAG": function( nodeNameSelector ) { - var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); - return nodeNameSelector === "*" ? - function() { - return true; - } : - function( elem ) { - return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; - }; - }, - - "CLASS": function( className ) { - var pattern = classCache[ className + " " ]; - - return pattern || - ( pattern = new RegExp( "(^|" + whitespace + - ")" + className + "(" + whitespace + "|$)" ) ) && classCache( - className, function( elem ) { - return pattern.test( - typeof elem.className === "string" && elem.className || - typeof elem.getAttribute !== "undefined" && - elem.getAttribute( "class" ) || - "" - ); - } ); - }, - - "ATTR": function( name, operator, check ) { - return function( elem ) { - var result = Sizzle.attr( elem, name ); - - if ( result == null ) { - return operator === "!="; - } - if ( !operator ) { - return true; - } - - result += ""; - - /* eslint-disable max-len */ - - return operator === "=" ? result === check : - operator === "!=" ? result !== check : - operator === "^=" ? check && result.indexOf( check ) === 0 : - operator === "*=" ? check && result.indexOf( check ) > -1 : - operator === "$=" ? check && result.slice( -check.length ) === check : - operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : - operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : - false; - /* eslint-enable max-len */ - - }; - }, - - "CHILD": function( type, what, _argument, first, last ) { - var simple = type.slice( 0, 3 ) !== "nth", - forward = type.slice( -4 ) !== "last", - ofType = what === "of-type"; - - return first === 1 && last === 0 ? - - // Shortcut for :nth-*(n) - function( elem ) { - return !!elem.parentNode; - } : - - function( elem, _context, xml ) { - var cache, uniqueCache, outerCache, node, nodeIndex, start, - dir = simple !== forward ? "nextSibling" : "previousSibling", - parent = elem.parentNode, - name = ofType && elem.nodeName.toLowerCase(), - useCache = !xml && !ofType, - diff = false; - - if ( parent ) { - - // :(first|last|only)-(child|of-type) - if ( simple ) { - while ( dir ) { - node = elem; - while ( ( node = node[ dir ] ) ) { - if ( ofType ? - node.nodeName.toLowerCase() === name : - node.nodeType === 1 ) { - - return false; - } - } - - // Reverse direction for :only-* (if we haven't yet done so) - start = dir = type === "only" && !start && "nextSibling"; - } - return true; - } - - start = [ forward ? parent.firstChild : parent.lastChild ]; - - // non-xml :nth-child(...) stores cache data on `parent` - if ( forward && useCache ) { - - // Seek `elem` from a previously-cached index - - // ...in a gzip-friendly way - node = parent; - outerCache = node[ expando ] || ( node[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - ( outerCache[ node.uniqueID ] = {} ); - - cache = uniqueCache[ type ] || []; - nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; - diff = nodeIndex && cache[ 2 ]; - node = nodeIndex && parent.childNodes[ nodeIndex ]; - - while ( ( node = ++nodeIndex && node && node[ dir ] || - - // Fallback to seeking `elem` from the start - ( diff = nodeIndex = 0 ) || start.pop() ) ) { - - // When found, cache indexes on `parent` and break - if ( node.nodeType === 1 && ++diff && node === elem ) { - uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; - break; - } - } - - } else { - - // Use previously-cached element index if available - if ( useCache ) { - - // ...in a gzip-friendly way - node = elem; - outerCache = node[ expando ] || ( node[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - ( outerCache[ node.uniqueID ] = {} ); - - cache = uniqueCache[ type ] || []; - nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; - diff = nodeIndex; - } - - // xml :nth-child(...) - // or :nth-last-child(...) or :nth(-last)?-of-type(...) - if ( diff === false ) { - - // Use the same loop as above to seek `elem` from the start - while ( ( node = ++nodeIndex && node && node[ dir ] || - ( diff = nodeIndex = 0 ) || start.pop() ) ) { - - if ( ( ofType ? - node.nodeName.toLowerCase() === name : - node.nodeType === 1 ) && - ++diff ) { - - // Cache the index of each encountered element - if ( useCache ) { - outerCache = node[ expando ] || - ( node[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ node.uniqueID ] || - ( outerCache[ node.uniqueID ] = {} ); - - uniqueCache[ type ] = [ dirruns, diff ]; - } - - if ( node === elem ) { - break; - } - } - } - } - } - - // Incorporate the offset, then check against cycle size - diff -= last; - return diff === first || ( diff % first === 0 && diff / first >= 0 ); - } - }; - }, - - "PSEUDO": function( pseudo, argument ) { - - // pseudo-class names are case-insensitive - // http://www.w3.org/TR/selectors/#pseudo-classes - // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters - // Remember that setFilters inherits from pseudos - var args, - fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || - Sizzle.error( "unsupported pseudo: " + pseudo ); - - // The user may use createPseudo to indicate that - // arguments are needed to create the filter function - // just as Sizzle does - if ( fn[ expando ] ) { - return fn( argument ); - } - - // But maintain support for old signatures - if ( fn.length > 1 ) { - args = [ pseudo, pseudo, "", argument ]; - return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? - markFunction( function( seed, matches ) { - var idx, - matched = fn( seed, argument ), - i = matched.length; - while ( i-- ) { - idx = indexOf( seed, matched[ i ] ); - seed[ idx ] = !( matches[ idx ] = matched[ i ] ); - } - } ) : - function( elem ) { - return fn( elem, 0, args ); - }; - } - - return fn; - } - }, - - pseudos: { - - // Potentially complex pseudos - "not": markFunction( function( selector ) { - - // Trim the selector passed to compile - // to avoid treating leading and trailing - // spaces as combinators - var input = [], - results = [], - matcher = compile( selector.replace( rtrim, "$1" ) ); - - return matcher[ expando ] ? - markFunction( function( seed, matches, _context, xml ) { - var elem, - unmatched = matcher( seed, null, xml, [] ), - i = seed.length; - - // Match elements unmatched by `matcher` - while ( i-- ) { - if ( ( elem = unmatched[ i ] ) ) { - seed[ i ] = !( matches[ i ] = elem ); - } - } - } ) : - function( elem, _context, xml ) { - input[ 0 ] = elem; - matcher( input, null, xml, results ); - - // Don't keep the element (issue #299) - input[ 0 ] = null; - return !results.pop(); - }; - } ), - - "has": markFunction( function( selector ) { - return function( elem ) { - return Sizzle( selector, elem ).length > 0; - }; - } ), - - "contains": markFunction( function( text ) { - text = text.replace( runescape, funescape ); - return function( elem ) { - return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; - }; - } ), - - // "Whether an element is represented by a :lang() selector - // is based solely on the element's language value - // being equal to the identifier C, - // or beginning with the identifier C immediately followed by "-". - // The matching of C against the element's language value is performed case-insensitively. - // The identifier C does not have to be a valid language name." - // http://www.w3.org/TR/selectors/#lang-pseudo - "lang": markFunction( function( lang ) { - - // lang value must be a valid identifier - if ( !ridentifier.test( lang || "" ) ) { - Sizzle.error( "unsupported lang: " + lang ); - } - lang = lang.replace( runescape, funescape ).toLowerCase(); - return function( elem ) { - var elemLang; - do { - if ( ( elemLang = documentIsHTML ? - elem.lang : - elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { - - elemLang = elemLang.toLowerCase(); - return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; - } - } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); - return false; - }; - } ), - - // Miscellaneous - "target": function( elem ) { - var hash = window.location && window.location.hash; - return hash && hash.slice( 1 ) === elem.id; - }, - - "root": function( elem ) { - return elem === docElem; - }, - - "focus": function( elem ) { - return elem === document.activeElement && - ( !document.hasFocus || document.hasFocus() ) && - !!( elem.type || elem.href || ~elem.tabIndex ); - }, - - // Boolean properties - "enabled": createDisabledPseudo( false ), - "disabled": createDisabledPseudo( true ), - - "checked": function( elem ) { - - // In CSS3, :checked should return both checked and selected elements - // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked - var nodeName = elem.nodeName.toLowerCase(); - return ( nodeName === "input" && !!elem.checked ) || - ( nodeName === "option" && !!elem.selected ); - }, - - "selected": function( elem ) { - - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - // eslint-disable-next-line no-unused-expressions - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - // Contents - "empty": function( elem ) { - - // http://www.w3.org/TR/selectors/#empty-pseudo - // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), - // but not by others (comment: 8; processing instruction: 7; etc.) - // nodeType < 6 works because attributes (2) do not appear as children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { - if ( elem.nodeType < 6 ) { - return false; - } - } - return true; - }, - - "parent": function( elem ) { - return !Expr.pseudos[ "empty" ]( elem ); - }, - - // Element/input types - "header": function( elem ) { - return rheader.test( elem.nodeName ); - }, - - "input": function( elem ) { - return rinputs.test( elem.nodeName ); - }, - - "button": function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && elem.type === "button" || name === "button"; - }, - - "text": function( elem ) { - var attr; - return elem.nodeName.toLowerCase() === "input" && - elem.type === "text" && - - // Support: IE<8 - // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" - ( ( attr = elem.getAttribute( "type" ) ) == null || - attr.toLowerCase() === "text" ); - }, - - // Position-in-collection - "first": createPositionalPseudo( function() { - return [ 0 ]; - } ), - - "last": createPositionalPseudo( function( _matchIndexes, length ) { - return [ length - 1 ]; - } ), - - "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { - return [ argument < 0 ? argument + length : argument ]; - } ), - - "even": createPositionalPseudo( function( matchIndexes, length ) { - var i = 0; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - } ), - - "odd": createPositionalPseudo( function( matchIndexes, length ) { - var i = 1; - for ( ; i < length; i += 2 ) { - matchIndexes.push( i ); - } - return matchIndexes; - } ), - - "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { - var i = argument < 0 ? - argument + length : - argument > length ? - length : - argument; - for ( ; --i >= 0; ) { - matchIndexes.push( i ); - } - return matchIndexes; - } ), - - "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { - var i = argument < 0 ? argument + length : argument; - for ( ; ++i < length; ) { - matchIndexes.push( i ); - } - return matchIndexes; - } ) - } -}; - -Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; - -// Add button/input type pseudos -for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { - Expr.pseudos[ i ] = createInputPseudo( i ); -} -for ( i in { submit: true, reset: true } ) { - Expr.pseudos[ i ] = createButtonPseudo( i ); -} - -// Easy API for creating new setFilters -function setFilters() {} -setFilters.prototype = Expr.filters = Expr.pseudos; -Expr.setFilters = new setFilters(); - -tokenize = Sizzle.tokenize = function( selector, parseOnly ) { - var matched, match, tokens, type, - soFar, groups, preFilters, - cached = tokenCache[ selector + " " ]; - - if ( cached ) { - return parseOnly ? 0 : cached.slice( 0 ); - } - - soFar = selector; - groups = []; - preFilters = Expr.preFilter; - - while ( soFar ) { - - // Comma and first run - if ( !matched || ( match = rcomma.exec( soFar ) ) ) { - if ( match ) { - - // Don't consume trailing commas as valid - soFar = soFar.slice( match[ 0 ].length ) || soFar; - } - groups.push( ( tokens = [] ) ); - } - - matched = false; - - // Combinators - if ( ( match = rcombinators.exec( soFar ) ) ) { - matched = match.shift(); - tokens.push( { - value: matched, - - // Cast descendant combinators to space - type: match[ 0 ].replace( rtrim, " " ) - } ); - soFar = soFar.slice( matched.length ); - } - - // Filters - for ( type in Expr.filter ) { - if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || - ( match = preFilters[ type ]( match ) ) ) ) { - matched = match.shift(); - tokens.push( { - value: matched, - type: type, - matches: match - } ); - soFar = soFar.slice( matched.length ); - } - } - - if ( !matched ) { - break; - } - } - - // Return the length of the invalid excess - // if we're just parsing - // Otherwise, throw an error or return tokens - return parseOnly ? - soFar.length : - soFar ? - Sizzle.error( selector ) : - - // Cache the tokens - tokenCache( selector, groups ).slice( 0 ); -}; - -function toSelector( tokens ) { - var i = 0, - len = tokens.length, - selector = ""; - for ( ; i < len; i++ ) { - selector += tokens[ i ].value; - } - return selector; -} - -function addCombinator( matcher, combinator, base ) { - var dir = combinator.dir, - skip = combinator.next, - key = skip || dir, - checkNonElements = base && key === "parentNode", - doneName = done++; - - return combinator.first ? - - // Check against closest ancestor/preceding element - function( elem, context, xml ) { - while ( ( elem = elem[ dir ] ) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - return matcher( elem, context, xml ); - } - } - return false; - } : - - // Check against all ancestor/preceding elements - function( elem, context, xml ) { - var oldCache, uniqueCache, outerCache, - newCache = [ dirruns, doneName ]; - - // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching - if ( xml ) { - while ( ( elem = elem[ dir ] ) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - if ( matcher( elem, context, xml ) ) { - return true; - } - } - } - } else { - while ( ( elem = elem[ dir ] ) ) { - if ( elem.nodeType === 1 || checkNonElements ) { - outerCache = elem[ expando ] || ( elem[ expando ] = {} ); - - // Support: IE <9 only - // Defend against cloned attroperties (jQuery gh-1709) - uniqueCache = outerCache[ elem.uniqueID ] || - ( outerCache[ elem.uniqueID ] = {} ); - - if ( skip && skip === elem.nodeName.toLowerCase() ) { - elem = elem[ dir ] || elem; - } else if ( ( oldCache = uniqueCache[ key ] ) && - oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { - - // Assign to newCache so results back-propagate to previous elements - return ( newCache[ 2 ] = oldCache[ 2 ] ); - } else { - - // Reuse newcache so results back-propagate to previous elements - uniqueCache[ key ] = newCache; - - // A match means we're done; a fail means we have to keep checking - if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { - return true; - } - } - } - } - } - return false; - }; -} - -function elementMatcher( matchers ) { - return matchers.length > 1 ? - function( elem, context, xml ) { - var i = matchers.length; - while ( i-- ) { - if ( !matchers[ i ]( elem, context, xml ) ) { - return false; - } - } - return true; - } : - matchers[ 0 ]; -} - -function multipleContexts( selector, contexts, results ) { - var i = 0, - len = contexts.length; - for ( ; i < len; i++ ) { - Sizzle( selector, contexts[ i ], results ); - } - return results; -} - -function condense( unmatched, map, filter, context, xml ) { - var elem, - newUnmatched = [], - i = 0, - len = unmatched.length, - mapped = map != null; - - for ( ; i < len; i++ ) { - if ( ( elem = unmatched[ i ] ) ) { - if ( !filter || filter( elem, context, xml ) ) { - newUnmatched.push( elem ); - if ( mapped ) { - map.push( i ); - } - } - } - } - - return newUnmatched; -} - -function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { - if ( postFilter && !postFilter[ expando ] ) { - postFilter = setMatcher( postFilter ); - } - if ( postFinder && !postFinder[ expando ] ) { - postFinder = setMatcher( postFinder, postSelector ); - } - return markFunction( function( seed, results, context, xml ) { - var temp, i, elem, - preMap = [], - postMap = [], - preexisting = results.length, - - // Get initial elements from seed or context - elems = seed || multipleContexts( - selector || "*", - context.nodeType ? [ context ] : context, - [] - ), - - // Prefilter to get matcher input, preserving a map for seed-results synchronization - matcherIn = preFilter && ( seed || !selector ) ? - condense( elems, preMap, preFilter, context, xml ) : - elems, - - matcherOut = matcher ? - - // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, - postFinder || ( seed ? preFilter : preexisting || postFilter ) ? - - // ...intermediate processing is necessary - [] : - - // ...otherwise use results directly - results : - matcherIn; - - // Find primary matches - if ( matcher ) { - matcher( matcherIn, matcherOut, context, xml ); - } - - // Apply postFilter - if ( postFilter ) { - temp = condense( matcherOut, postMap ); - postFilter( temp, [], context, xml ); - - // Un-match failing elements by moving them back to matcherIn - i = temp.length; - while ( i-- ) { - if ( ( elem = temp[ i ] ) ) { - matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); - } - } - } - - if ( seed ) { - if ( postFinder || preFilter ) { - if ( postFinder ) { - - // Get the final matcherOut by condensing this intermediate into postFinder contexts - temp = []; - i = matcherOut.length; - while ( i-- ) { - if ( ( elem = matcherOut[ i ] ) ) { - - // Restore matcherIn since elem is not yet a final match - temp.push( ( matcherIn[ i ] = elem ) ); - } - } - postFinder( null, ( matcherOut = [] ), temp, xml ); - } - - // Move matched elements from seed to results to keep them synchronized - i = matcherOut.length; - while ( i-- ) { - if ( ( elem = matcherOut[ i ] ) && - ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { - - seed[ temp ] = !( results[ temp ] = elem ); - } - } - } - - // Add elements to results, through postFinder if defined - } else { - matcherOut = condense( - matcherOut === results ? - matcherOut.splice( preexisting, matcherOut.length ) : - matcherOut - ); - if ( postFinder ) { - postFinder( null, results, matcherOut, xml ); - } else { - push.apply( results, matcherOut ); - } - } - } ); -} - -function matcherFromTokens( tokens ) { - var checkContext, matcher, j, - len = tokens.length, - leadingRelative = Expr.relative[ tokens[ 0 ].type ], - implicitRelative = leadingRelative || Expr.relative[ " " ], - i = leadingRelative ? 1 : 0, - - // The foundational matcher ensures that elements are reachable from top-level context(s) - matchContext = addCombinator( function( elem ) { - return elem === checkContext; - }, implicitRelative, true ), - matchAnyContext = addCombinator( function( elem ) { - return indexOf( checkContext, elem ) > -1; - }, implicitRelative, true ), - matchers = [ function( elem, context, xml ) { - var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( - ( checkContext = context ).nodeType ? - matchContext( elem, context, xml ) : - matchAnyContext( elem, context, xml ) ); - - // Avoid hanging onto element (issue #299) - checkContext = null; - return ret; - } ]; - - for ( ; i < len; i++ ) { - if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { - matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; - } else { - matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); - - // Return special upon seeing a positional matcher - if ( matcher[ expando ] ) { - - // Find the next relative operator (if any) for proper handling - j = ++i; - for ( ; j < len; j++ ) { - if ( Expr.relative[ tokens[ j ].type ] ) { - break; - } - } - return setMatcher( - i > 1 && elementMatcher( matchers ), - i > 1 && toSelector( - - // If the preceding token was a descendant combinator, insert an implicit any-element `*` - tokens - .slice( 0, i - 1 ) - .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) - ).replace( rtrim, "$1" ), - matcher, - i < j && matcherFromTokens( tokens.slice( i, j ) ), - j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), - j < len && toSelector( tokens ) - ); - } - matchers.push( matcher ); - } - } - - return elementMatcher( matchers ); -} - -function matcherFromGroupMatchers( elementMatchers, setMatchers ) { - var bySet = setMatchers.length > 0, - byElement = elementMatchers.length > 0, - superMatcher = function( seed, context, xml, results, outermost ) { - var elem, j, matcher, - matchedCount = 0, - i = "0", - unmatched = seed && [], - setMatched = [], - contextBackup = outermostContext, - - // We must always have either seed elements or outermost context - elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), - - // Use integer dirruns iff this is the outermost matcher - dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), - len = elems.length; - - if ( outermost ) { - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - outermostContext = context == document || context || outermost; - } - - // Add elements passing elementMatchers directly to results - // Support: IE<9, Safari - // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id - for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { - if ( byElement && elem ) { - j = 0; - - // Support: IE 11+, Edge 17 - 18+ - // IE/Edge sometimes throw a "Permission denied" error when strict-comparing - // two documents; shallow comparisons work. - // eslint-disable-next-line eqeqeq - if ( !context && elem.ownerDocument != document ) { - setDocument( elem ); - xml = !documentIsHTML; - } - while ( ( matcher = elementMatchers[ j++ ] ) ) { - if ( matcher( elem, context || document, xml ) ) { - results.push( elem ); - break; - } - } - if ( outermost ) { - dirruns = dirrunsUnique; - } - } - - // Track unmatched elements for set filters - if ( bySet ) { - - // They will have gone through all possible matchers - if ( ( elem = !matcher && elem ) ) { - matchedCount--; - } - - // Lengthen the array for every element, matched or not - if ( seed ) { - unmatched.push( elem ); - } - } - } - - // `i` is now the count of elements visited above, and adding it to `matchedCount` - // makes the latter nonnegative. - matchedCount += i; - - // Apply set filters to unmatched elements - // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` - // equals `i`), unless we didn't visit _any_ elements in the above loop because we have - // no element matchers and no seed. - // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that - // case, which will result in a "00" `matchedCount` that differs from `i` but is also - // numerically zero. - if ( bySet && i !== matchedCount ) { - j = 0; - while ( ( matcher = setMatchers[ j++ ] ) ) { - matcher( unmatched, setMatched, context, xml ); - } - - if ( seed ) { - - // Reintegrate element matches to eliminate the need for sorting - if ( matchedCount > 0 ) { - while ( i-- ) { - if ( !( unmatched[ i ] || setMatched[ i ] ) ) { - setMatched[ i ] = pop.call( results ); - } - } - } - - // Discard index placeholder values to get only actual matches - setMatched = condense( setMatched ); - } - - // Add matches to results - push.apply( results, setMatched ); - - // Seedless set matches succeeding multiple successful matchers stipulate sorting - if ( outermost && !seed && setMatched.length > 0 && - ( matchedCount + setMatchers.length ) > 1 ) { - - Sizzle.uniqueSort( results ); - } - } - - // Override manipulation of globals by nested matchers - if ( outermost ) { - dirruns = dirrunsUnique; - outermostContext = contextBackup; - } - - return unmatched; - }; - - return bySet ? - markFunction( superMatcher ) : - superMatcher; -} - -compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { - var i, - setMatchers = [], - elementMatchers = [], - cached = compilerCache[ selector + " " ]; - - if ( !cached ) { - - // Generate a function of recursive functions that can be used to check each element - if ( !match ) { - match = tokenize( selector ); - } - i = match.length; - while ( i-- ) { - cached = matcherFromTokens( match[ i ] ); - if ( cached[ expando ] ) { - setMatchers.push( cached ); - } else { - elementMatchers.push( cached ); - } - } - - // Cache the compiled function - cached = compilerCache( - selector, - matcherFromGroupMatchers( elementMatchers, setMatchers ) - ); - - // Save selector and tokenization - cached.selector = selector; - } - return cached; -}; - -/** - * A low-level selection function that works with Sizzle's compiled - * selector functions - * @param {String|Function} selector A selector or a pre-compiled - * selector function built with Sizzle.compile - * @param {Element} context - * @param {Array} [results] - * @param {Array} [seed] A set of elements to match against - */ -select = Sizzle.select = function( selector, context, results, seed ) { - var i, tokens, token, type, find, - compiled = typeof selector === "function" && selector, - match = !seed && tokenize( ( selector = compiled.selector || selector ) ); - - results = results || []; - - // Try to minimize operations if there is only one selector in the list and no seed - // (the latter of which guarantees us context) - if ( match.length === 1 ) { - - // Reduce context if the leading compound selector is an ID - tokens = match[ 0 ] = match[ 0 ].slice( 0 ); - if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && - context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { - - context = ( Expr.find[ "ID" ]( token.matches[ 0 ] - .replace( runescape, funescape ), context ) || [] )[ 0 ]; - if ( !context ) { - return results; - - // Precompiled matchers will still verify ancestry, so step up a level - } else if ( compiled ) { - context = context.parentNode; - } - - selector = selector.slice( tokens.shift().value.length ); - } - - // Fetch a seed set for right-to-left matching - i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; - while ( i-- ) { - token = tokens[ i ]; - - // Abort if we hit a combinator - if ( Expr.relative[ ( type = token.type ) ] ) { - break; - } - if ( ( find = Expr.find[ type ] ) ) { - - // Search, expanding context for leading sibling combinators - if ( ( seed = find( - token.matches[ 0 ].replace( runescape, funescape ), - rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || - context - ) ) ) { - - // If seed is empty or no tokens remain, we can return early - tokens.splice( i, 1 ); - selector = seed.length && toSelector( tokens ); - if ( !selector ) { - push.apply( results, seed ); - return results; - } - - break; - } - } - } - } - - // Compile and execute a filtering function if one is not provided - // Provide `match` to avoid retokenization if we modified the selector above - ( compiled || compile( selector, match ) )( - seed, - context, - !documentIsHTML, - results, - !context || rsibling.test( selector ) && testContext( context.parentNode ) || context - ); - return results; -}; - -// One-time assignments - -// Sort stability -support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; - -// Support: Chrome 14-35+ -// Always assume duplicates if they aren't passed to the comparison function -support.detectDuplicates = !!hasDuplicate; - -// Initialize against the default document -setDocument(); - -// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) -// Detached nodes confoundingly follow *each other* -support.sortDetached = assert( function( el ) { - - // Should return 1, but returns 4 (following) - return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; -} ); - -// Support: IE<8 -// Prevent attribute/property "interpolation" -// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx -if ( !assert( function( el ) { - el.innerHTML = ""; - return el.firstChild.getAttribute( "href" ) === "#"; -} ) ) { - addHandle( "type|href|height|width", function( elem, name, isXML ) { - if ( !isXML ) { - return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); - } - } ); -} - -// Support: IE<9 -// Use defaultValue in place of getAttribute("value") -if ( !support.attributes || !assert( function( el ) { - el.innerHTML = ""; - el.firstChild.setAttribute( "value", "" ); - return el.firstChild.getAttribute( "value" ) === ""; -} ) ) { - addHandle( "value", function( elem, _name, isXML ) { - if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { - return elem.defaultValue; - } - } ); -} - -// Support: IE<9 -// Use getAttributeNode to fetch booleans when getAttribute lies -if ( !assert( function( el ) { - return el.getAttribute( "disabled" ) == null; -} ) ) { - addHandle( booleans, function( elem, name, isXML ) { - var val; - if ( !isXML ) { - return elem[ name ] === true ? name.toLowerCase() : - ( val = elem.getAttributeNode( name ) ) && val.specified ? - val.value : - null; - } - } ); -} - -return Sizzle; - -} )( window ); - - - -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; - -// Deprecated -jQuery.expr[ ":" ] = jQuery.expr.pseudos; -jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; -jQuery.escapeSelector = Sizzle.escape; - - - - -var dir = function( elem, dir, until ) { - var matched = [], - truncate = until !== undefined; - - while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { - if ( elem.nodeType === 1 ) { - if ( truncate && jQuery( elem ).is( until ) ) { - break; - } - matched.push( elem ); - } - } - return matched; -}; - - -var siblings = function( n, elem ) { - var matched = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - matched.push( n ); - } - } - - return matched; -}; - - -var rneedsContext = jQuery.expr.match.needsContext; - - - -function nodeName( elem, name ) { - - return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); - -} -var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); - - - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, not ) { - if ( isFunction( qualifier ) ) { - return jQuery.grep( elements, function( elem, i ) { - return !!qualifier.call( elem, i, elem ) !== not; - } ); - } - - // Single element - if ( qualifier.nodeType ) { - return jQuery.grep( elements, function( elem ) { - return ( elem === qualifier ) !== not; - } ); - } - - // Arraylike of elements (jQuery, arguments, Array) - if ( typeof qualifier !== "string" ) { - return jQuery.grep( elements, function( elem ) { - return ( indexOf.call( qualifier, elem ) > -1 ) !== not; - } ); - } - - // Filtered directly for both simple and complex selectors - return jQuery.filter( qualifier, elements, not ); -} - -jQuery.filter = function( expr, elems, not ) { - var elem = elems[ 0 ]; - - if ( not ) { - expr = ":not(" + expr + ")"; - } - - if ( elems.length === 1 && elem.nodeType === 1 ) { - return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; - } - - return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { - return elem.nodeType === 1; - } ) ); -}; - -jQuery.fn.extend( { - find: function( selector ) { - var i, ret, - len = this.length, - self = this; - - if ( typeof selector !== "string" ) { - return this.pushStack( jQuery( selector ).filter( function() { - for ( i = 0; i < len; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - } ) ); - } - - ret = this.pushStack( [] ); - - for ( i = 0; i < len; i++ ) { - jQuery.find( selector, self[ i ], ret ); - } - - return len > 1 ? jQuery.uniqueSort( ret ) : ret; - }, - filter: function( selector ) { - return this.pushStack( winnow( this, selector || [], false ) ); - }, - not: function( selector ) { - return this.pushStack( winnow( this, selector || [], true ) ); - }, - is: function( selector ) { - return !!winnow( - this, - - // If this is a positional/relative selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - typeof selector === "string" && rneedsContext.test( selector ) ? - jQuery( selector ) : - selector || [], - false - ).length; - } -} ); - - -// Initialize a jQuery object - - -// A central reference to the root jQuery(document) -var rootjQuery, - - // A simple way to check for HTML strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - // Strict HTML recognition (#11290: must start with <) - // Shortcut simple #id case for speed - rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, - - init = jQuery.fn.init = function( selector, context, root ) { - var match, elem; - - // HANDLE: $(""), $(null), $(undefined), $(false) - if ( !selector ) { - return this; - } - - // Method init() accepts an alternate rootjQuery - // so migrate can support jQuery.sub (gh-2101) - root = root || rootjQuery; - - // Handle HTML strings - if ( typeof selector === "string" ) { - if ( selector[ 0 ] === "<" && - selector[ selector.length - 1 ] === ">" && - selector.length >= 3 ) { - - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = rquickExpr.exec( selector ); - } - - // Match html or make sure no context is specified for #id - if ( match && ( match[ 1 ] || !context ) ) { - - // HANDLE: $(html) -> $(array) - if ( match[ 1 ] ) { - context = context instanceof jQuery ? context[ 0 ] : context; - - // Option to run scripts is true for back-compat - // Intentionally let the error be thrown if parseHTML is not present - jQuery.merge( this, jQuery.parseHTML( - match[ 1 ], - context && context.nodeType ? context.ownerDocument || context : document, - true - ) ); - - // HANDLE: $(html, props) - if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { - for ( match in context ) { - - // Properties of context are called as methods if possible - if ( isFunction( this[ match ] ) ) { - this[ match ]( context[ match ] ); - - // ...and otherwise set as attributes - } else { - this.attr( match, context[ match ] ); - } - } - } - - return this; - - // HANDLE: $(#id) - } else { - elem = document.getElementById( match[ 2 ] ); - - if ( elem ) { - - // Inject the element directly into the jQuery object - this[ 0 ] = elem; - this.length = 1; - } - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || root ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(DOMElement) - } else if ( selector.nodeType ) { - this[ 0 ] = selector; - this.length = 1; - return this; - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( isFunction( selector ) ) { - return root.ready !== undefined ? - root.ready( selector ) : - - // Execute immediately if ready is not present - selector( jQuery ); - } - - return jQuery.makeArray( selector, this ); - }; - -// Give the init function the jQuery prototype for later instantiation -init.prototype = jQuery.fn; - -// Initialize central reference -rootjQuery = jQuery( document ); - - -var rparentsprev = /^(?:parents|prev(?:Until|All))/, - - // Methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend( { - has: function( target ) { - var targets = jQuery( target, this ), - l = targets.length; - - return this.filter( function() { - var i = 0; - for ( ; i < l; i++ ) { - if ( jQuery.contains( this, targets[ i ] ) ) { - return true; - } - } - } ); - }, - - closest: function( selectors, context ) { - var cur, - i = 0, - l = this.length, - matched = [], - targets = typeof selectors !== "string" && jQuery( selectors ); - - // Positional selectors never match, since there's no _selection_ context - if ( !rneedsContext.test( selectors ) ) { - for ( ; i < l; i++ ) { - for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { - - // Always skip document fragments - if ( cur.nodeType < 11 && ( targets ? - targets.index( cur ) > -1 : - - // Don't pass non-elements to Sizzle - cur.nodeType === 1 && - jQuery.find.matchesSelector( cur, selectors ) ) ) { - - matched.push( cur ); - break; - } - } - } - } - - return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); - }, - - // Determine the position of an element within the set - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; - } - - // Index in selector - if ( typeof elem === "string" ) { - return indexOf.call( jQuery( elem ), this[ 0 ] ); - } - - // Locate the position of the desired element - return indexOf.call( this, - - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[ 0 ] : elem - ); - }, - - add: function( selector, context ) { - return this.pushStack( - jQuery.uniqueSort( - jQuery.merge( this.get(), jQuery( selector, context ) ) - ) - ); - }, - - addBack: function( selector ) { - return this.add( selector == null ? - this.prevObject : this.prevObject.filter( selector ) - ); - } -} ); - -function sibling( cur, dir ) { - while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} - return cur; -} - -jQuery.each( { - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, _i, until ) { - return dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return sibling( elem, "nextSibling" ); - }, - prev: function( elem ) { - return sibling( elem, "previousSibling" ); - }, - nextAll: function( elem ) { - return dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, _i, until ) { - return dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, _i, until ) { - return dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return siblings( ( elem.parentNode || {} ).firstChild, elem ); - }, - children: function( elem ) { - return siblings( elem.firstChild ); - }, - contents: function( elem ) { - if ( elem.contentDocument != null && - - // Support: IE 11+ - // elements with no `data` attribute has an object - // `contentDocument` with a `null` prototype. - getProto( elem.contentDocument ) ) { - - return elem.contentDocument; - } - - // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only - // Treat the template element as a regular one in browsers that - // don't support it. - if ( nodeName( elem, "template" ) ) { - elem = elem.content || elem; - } - - return jQuery.merge( [], elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var matched = jQuery.map( this, fn, until ); - - if ( name.slice( -5 ) !== "Until" ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - matched = jQuery.filter( selector, matched ); - } - - if ( this.length > 1 ) { - - // Remove duplicates - if ( !guaranteedUnique[ name ] ) { - jQuery.uniqueSort( matched ); - } - - // Reverse order for parents* and prev-derivatives - if ( rparentsprev.test( name ) ) { - matched.reverse(); - } - } - - return this.pushStack( matched ); - }; -} ); -var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); - - - -// Convert String-formatted options into Object-formatted ones -function createOptions( options ) { - var object = {}; - jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { - object[ flag ] = true; - } ); - return object; -} - -/* - * Create a callback list using the following parameters: - * - * options: an optional list of space-separated options that will change how - * the callback list behaves or a more traditional option object - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible options: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( options ) { - - // Convert options from String-formatted to Object-formatted if needed - // (we check in cache first) - options = typeof options === "string" ? - createOptions( options ) : - jQuery.extend( {}, options ); - - var // Flag to know if list is currently firing - firing, - - // Last fire value for non-forgettable lists - memory, - - // Flag to know if list was already fired - fired, - - // Flag to prevent firing - locked, - - // Actual callback list - list = [], - - // Queue of execution data for repeatable lists - queue = [], - - // Index of currently firing callback (modified by add/remove as needed) - firingIndex = -1, - - // Fire callbacks - fire = function() { - - // Enforce single-firing - locked = locked || options.once; - - // Execute callbacks for all pending executions, - // respecting firingIndex overrides and runtime changes - fired = firing = true; - for ( ; queue.length; firingIndex = -1 ) { - memory = queue.shift(); - while ( ++firingIndex < list.length ) { - - // Run callback and check for early termination - if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && - options.stopOnFalse ) { - - // Jump to end and forget the data so .add doesn't re-fire - firingIndex = list.length; - memory = false; - } - } - } - - // Forget the data if we're done with it - if ( !options.memory ) { - memory = false; - } - - firing = false; - - // Clean up if we're done firing for good - if ( locked ) { - - // Keep an empty list if we have data for future add calls - if ( memory ) { - list = []; - - // Otherwise, this object is spent - } else { - list = ""; - } - } - }, - - // Actual Callbacks object - self = { - - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - - // If we have memory from a past run, we should fire after adding - if ( memory && !firing ) { - firingIndex = list.length - 1; - queue.push( memory ); - } - - ( function add( args ) { - jQuery.each( args, function( _, arg ) { - if ( isFunction( arg ) ) { - if ( !options.unique || !self.has( arg ) ) { - list.push( arg ); - } - } else if ( arg && arg.length && toType( arg ) !== "string" ) { - - // Inspect recursively - add( arg ); - } - } ); - } )( arguments ); - - if ( memory && !firing ) { - fire(); - } - } - return this; - }, - - // Remove a callback from the list - remove: function() { - jQuery.each( arguments, function( _, arg ) { - var index; - while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { - list.splice( index, 1 ); - - // Handle firing indexes - if ( index <= firingIndex ) { - firingIndex--; - } - } - } ); - return this; - }, - - // Check if a given callback is in the list. - // If no argument is given, return whether or not list has callbacks attached. - has: function( fn ) { - return fn ? - jQuery.inArray( fn, list ) > -1 : - list.length > 0; - }, - - // Remove all callbacks from the list - empty: function() { - if ( list ) { - list = []; - } - return this; - }, - - // Disable .fire and .add - // Abort any current/pending executions - // Clear all callbacks and values - disable: function() { - locked = queue = []; - list = memory = ""; - return this; - }, - disabled: function() { - return !list; - }, - - // Disable .fire - // Also disable .add unless we have memory (since it would have no effect) - // Abort any pending executions - lock: function() { - locked = queue = []; - if ( !memory && !firing ) { - list = memory = ""; - } - return this; - }, - locked: function() { - return !!locked; - }, - - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( !locked ) { - args = args || []; - args = [ context, args.slice ? args.slice() : args ]; - queue.push( args ); - if ( !firing ) { - fire(); - } - } - return this; - }, - - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - - // To know if the callbacks have already been called at least once - fired: function() { - return !!fired; - } - }; - - return self; -}; - - -function Identity( v ) { - return v; -} -function Thrower( ex ) { - throw ex; -} - -function adoptValue( value, resolve, reject, noValue ) { - var method; - - try { - - // Check for promise aspect first to privilege synchronous behavior - if ( value && isFunction( ( method = value.promise ) ) ) { - method.call( value ).done( resolve ).fail( reject ); - - // Other thenables - } else if ( value && isFunction( ( method = value.then ) ) ) { - method.call( value, resolve, reject ); - - // Other non-thenables - } else { - - // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: - // * false: [ value ].slice( 0 ) => resolve( value ) - // * true: [ value ].slice( 1 ) => resolve() - resolve.apply( undefined, [ value ].slice( noValue ) ); - } - - // For Promises/A+, convert exceptions into rejections - // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in - // Deferred#then to conditionally suppress rejection. - } catch ( value ) { - - // Support: Android 4.0 only - // Strict mode functions invoked without .call/.apply get global-object context - reject.apply( undefined, [ value ] ); - } -} - -jQuery.extend( { - - Deferred: function( func ) { - var tuples = [ - - // action, add listener, callbacks, - // ... .then handlers, argument index, [final state] - [ "notify", "progress", jQuery.Callbacks( "memory" ), - jQuery.Callbacks( "memory" ), 2 ], - [ "resolve", "done", jQuery.Callbacks( "once memory" ), - jQuery.Callbacks( "once memory" ), 0, "resolved" ], - [ "reject", "fail", jQuery.Callbacks( "once memory" ), - jQuery.Callbacks( "once memory" ), 1, "rejected" ] - ], - state = "pending", - promise = { - state: function() { - return state; - }, - always: function() { - deferred.done( arguments ).fail( arguments ); - return this; - }, - "catch": function( fn ) { - return promise.then( null, fn ); - }, - - // Keep pipe for back-compat - pipe: function( /* fnDone, fnFail, fnProgress */ ) { - var fns = arguments; - - return jQuery.Deferred( function( newDefer ) { - jQuery.each( tuples, function( _i, tuple ) { - - // Map tuples (progress, done, fail) to arguments (done, fail, progress) - var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; - - // deferred.progress(function() { bind to newDefer or newDefer.notify }) - // deferred.done(function() { bind to newDefer or newDefer.resolve }) - // deferred.fail(function() { bind to newDefer or newDefer.reject }) - deferred[ tuple[ 1 ] ]( function() { - var returned = fn && fn.apply( this, arguments ); - if ( returned && isFunction( returned.promise ) ) { - returned.promise() - .progress( newDefer.notify ) - .done( newDefer.resolve ) - .fail( newDefer.reject ); - } else { - newDefer[ tuple[ 0 ] + "With" ]( - this, - fn ? [ returned ] : arguments - ); - } - } ); - } ); - fns = null; - } ).promise(); - }, - then: function( onFulfilled, onRejected, onProgress ) { - var maxDepth = 0; - function resolve( depth, deferred, handler, special ) { - return function() { - var that = this, - args = arguments, - mightThrow = function() { - var returned, then; - - // Support: Promises/A+ section 2.3.3.3.3 - // https://promisesaplus.com/#point-59 - // Ignore double-resolution attempts - if ( depth < maxDepth ) { - return; - } - - returned = handler.apply( that, args ); - - // Support: Promises/A+ section 2.3.1 - // https://promisesaplus.com/#point-48 - if ( returned === deferred.promise() ) { - throw new TypeError( "Thenable self-resolution" ); - } - - // Support: Promises/A+ sections 2.3.3.1, 3.5 - // https://promisesaplus.com/#point-54 - // https://promisesaplus.com/#point-75 - // Retrieve `then` only once - then = returned && - - // Support: Promises/A+ section 2.3.4 - // https://promisesaplus.com/#point-64 - // Only check objects and functions for thenability - ( typeof returned === "object" || - typeof returned === "function" ) && - returned.then; - - // Handle a returned thenable - if ( isFunction( then ) ) { - - // Special processors (notify) just wait for resolution - if ( special ) { - then.call( - returned, - resolve( maxDepth, deferred, Identity, special ), - resolve( maxDepth, deferred, Thrower, special ) - ); - - // Normal processors (resolve) also hook into progress - } else { - - // ...and disregard older resolution values - maxDepth++; - - then.call( - returned, - resolve( maxDepth, deferred, Identity, special ), - resolve( maxDepth, deferred, Thrower, special ), - resolve( maxDepth, deferred, Identity, - deferred.notifyWith ) - ); - } - - // Handle all other returned values - } else { - - // Only substitute handlers pass on context - // and multiple values (non-spec behavior) - if ( handler !== Identity ) { - that = undefined; - args = [ returned ]; - } - - // Process the value(s) - // Default process is resolve - ( special || deferred.resolveWith )( that, args ); - } - }, - - // Only normal processors (resolve) catch and reject exceptions - process = special ? - mightThrow : - function() { - try { - mightThrow(); - } catch ( e ) { - - if ( jQuery.Deferred.exceptionHook ) { - jQuery.Deferred.exceptionHook( e, - process.stackTrace ); - } - - // Support: Promises/A+ section 2.3.3.3.4.1 - // https://promisesaplus.com/#point-61 - // Ignore post-resolution exceptions - if ( depth + 1 >= maxDepth ) { - - // Only substitute handlers pass on context - // and multiple values (non-spec behavior) - if ( handler !== Thrower ) { - that = undefined; - args = [ e ]; - } - - deferred.rejectWith( that, args ); - } - } - }; - - // Support: Promises/A+ section 2.3.3.3.1 - // https://promisesaplus.com/#point-57 - // Re-resolve promises immediately to dodge false rejection from - // subsequent errors - if ( depth ) { - process(); - } else { - - // Call an optional hook to record the stack, in case of exception - // since it's otherwise lost when execution goes async - if ( jQuery.Deferred.getStackHook ) { - process.stackTrace = jQuery.Deferred.getStackHook(); - } - window.setTimeout( process ); - } - }; - } - - return jQuery.Deferred( function( newDefer ) { - - // progress_handlers.add( ... ) - tuples[ 0 ][ 3 ].add( - resolve( - 0, - newDefer, - isFunction( onProgress ) ? - onProgress : - Identity, - newDefer.notifyWith - ) - ); - - // fulfilled_handlers.add( ... ) - tuples[ 1 ][ 3 ].add( - resolve( - 0, - newDefer, - isFunction( onFulfilled ) ? - onFulfilled : - Identity - ) - ); - - // rejected_handlers.add( ... ) - tuples[ 2 ][ 3 ].add( - resolve( - 0, - newDefer, - isFunction( onRejected ) ? - onRejected : - Thrower - ) - ); - } ).promise(); - }, - - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - return obj != null ? jQuery.extend( obj, promise ) : promise; - } - }, - deferred = {}; - - // Add list-specific methods - jQuery.each( tuples, function( i, tuple ) { - var list = tuple[ 2 ], - stateString = tuple[ 5 ]; - - // promise.progress = list.add - // promise.done = list.add - // promise.fail = list.add - promise[ tuple[ 1 ] ] = list.add; - - // Handle state - if ( stateString ) { - list.add( - function() { - - // state = "resolved" (i.e., fulfilled) - // state = "rejected" - state = stateString; - }, - - // rejected_callbacks.disable - // fulfilled_callbacks.disable - tuples[ 3 - i ][ 2 ].disable, - - // rejected_handlers.disable - // fulfilled_handlers.disable - tuples[ 3 - i ][ 3 ].disable, - - // progress_callbacks.lock - tuples[ 0 ][ 2 ].lock, - - // progress_handlers.lock - tuples[ 0 ][ 3 ].lock - ); - } - - // progress_handlers.fire - // fulfilled_handlers.fire - // rejected_handlers.fire - list.add( tuple[ 3 ].fire ); - - // deferred.notify = function() { deferred.notifyWith(...) } - // deferred.resolve = function() { deferred.resolveWith(...) } - // deferred.reject = function() { deferred.rejectWith(...) } - deferred[ tuple[ 0 ] ] = function() { - deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); - return this; - }; - - // deferred.notifyWith = list.fireWith - // deferred.resolveWith = list.fireWith - // deferred.rejectWith = list.fireWith - deferred[ tuple[ 0 ] + "With" ] = list.fireWith; - } ); - - // Make the deferred a promise - promise.promise( deferred ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( singleValue ) { - var - - // count of uncompleted subordinates - remaining = arguments.length, - - // count of unprocessed arguments - i = remaining, - - // subordinate fulfillment data - resolveContexts = Array( i ), - resolveValues = slice.call( arguments ), - - // the primary Deferred - primary = jQuery.Deferred(), - - // subordinate callback factory - updateFunc = function( i ) { - return function( value ) { - resolveContexts[ i ] = this; - resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; - if ( !( --remaining ) ) { - primary.resolveWith( resolveContexts, resolveValues ); - } - }; - }; - - // Single- and empty arguments are adopted like Promise.resolve - if ( remaining <= 1 ) { - adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject, - !remaining ); - - // Use .then() to unwrap secondary thenables (cf. gh-3000) - if ( primary.state() === "pending" || - isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { - - return primary.then(); - } - } - - // Multiple arguments are aggregated like Promise.all array elements - while ( i-- ) { - adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject ); - } - - return primary.promise(); - } -} ); - - -// These usually indicate a programmer mistake during development, -// warn about them ASAP rather than swallowing them by default. -var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; - -jQuery.Deferred.exceptionHook = function( error, stack ) { - - // Support: IE 8 - 9 only - // Console exists when dev tools are open, which can happen at any time - if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { - window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); - } -}; - - - - -jQuery.readyException = function( error ) { - window.setTimeout( function() { - throw error; - } ); -}; - - - - -// The deferred used on DOM ready -var readyList = jQuery.Deferred(); - -jQuery.fn.ready = function( fn ) { - - readyList - .then( fn ) - - // Wrap jQuery.readyException in a function so that the lookup - // happens at the time of error handling instead of callback - // registration. - .catch( function( error ) { - jQuery.readyException( error ); - } ); - - return this; -}; - -jQuery.extend( { - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Handle when the DOM is ready - ready: function( wait ) { - - // Abort if there are pending holds or we're already ready - if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { - return; - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.resolveWith( document, [ jQuery ] ); - } -} ); - -jQuery.ready.then = readyList.then; - -// The ready event handler and self cleanup method -function completed() { - document.removeEventListener( "DOMContentLoaded", completed ); - window.removeEventListener( "load", completed ); - jQuery.ready(); -} - -// Catch cases where $(document).ready() is called -// after the browser event has already occurred. -// Support: IE <=9 - 10 only -// Older IE sometimes signals "interactive" too soon -if ( document.readyState === "complete" || - ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { - - // Handle it asynchronously to allow scripts the opportunity to delay ready - window.setTimeout( jQuery.ready ); - -} else { - - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", completed ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", completed ); -} - - - - -// Multifunctional method to get and set values of a collection -// The value/s can optionally be executed if it's a function -var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { - var i = 0, - len = elems.length, - bulk = key == null; - - // Sets many values - if ( toType( key ) === "object" ) { - chainable = true; - for ( i in key ) { - access( elems, fn, i, key[ i ], true, emptyGet, raw ); - } - - // Sets one value - } else if ( value !== undefined ) { - chainable = true; - - if ( !isFunction( value ) ) { - raw = true; - } - - if ( bulk ) { - - // Bulk operations run against the entire set - if ( raw ) { - fn.call( elems, value ); - fn = null; - - // ...except when executing function values - } else { - bulk = fn; - fn = function( elem, _key, value ) { - return bulk.call( jQuery( elem ), value ); - }; - } - } - - if ( fn ) { - for ( ; i < len; i++ ) { - fn( - elems[ i ], key, raw ? - value : - value.call( elems[ i ], i, fn( elems[ i ], key ) ) - ); - } - } - } - - if ( chainable ) { - return elems; - } - - // Gets - if ( bulk ) { - return fn.call( elems ); - } - - return len ? fn( elems[ 0 ], key ) : emptyGet; -}; - - -// Matches dashed string for camelizing -var rmsPrefix = /^-ms-/, - rdashAlpha = /-([a-z])/g; - -// Used by camelCase as callback to replace() -function fcamelCase( _all, letter ) { - return letter.toUpperCase(); -} - -// Convert dashed to camelCase; used by the css and data modules -// Support: IE <=9 - 11, Edge 12 - 15 -// Microsoft forgot to hump their vendor prefix (#9572) -function camelCase( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); -} -var acceptData = function( owner ) { - - // Accepts only: - // - Node - // - Node.ELEMENT_NODE - // - Node.DOCUMENT_NODE - // - Object - // - Any - return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); -}; - - - - -function Data() { - this.expando = jQuery.expando + Data.uid++; -} - -Data.uid = 1; - -Data.prototype = { - - cache: function( owner ) { - - // Check if the owner object already has a cache - var value = owner[ this.expando ]; - - // If not, create one - if ( !value ) { - value = {}; - - // We can accept data for non-element nodes in modern browsers, - // but we should not, see #8335. - // Always return an empty object. - if ( acceptData( owner ) ) { - - // If it is a node unlikely to be stringify-ed or looped over - // use plain assignment - if ( owner.nodeType ) { - owner[ this.expando ] = value; - - // Otherwise secure it in a non-enumerable property - // configurable must be true to allow the property to be - // deleted when data is removed - } else { - Object.defineProperty( owner, this.expando, { - value: value, - configurable: true - } ); - } - } - } - - return value; - }, - set: function( owner, data, value ) { - var prop, - cache = this.cache( owner ); - - // Handle: [ owner, key, value ] args - // Always use camelCase key (gh-2257) - if ( typeof data === "string" ) { - cache[ camelCase( data ) ] = value; - - // Handle: [ owner, { properties } ] args - } else { - - // Copy the properties one-by-one to the cache object - for ( prop in data ) { - cache[ camelCase( prop ) ] = data[ prop ]; - } - } - return cache; - }, - get: function( owner, key ) { - return key === undefined ? - this.cache( owner ) : - - // Always use camelCase key (gh-2257) - owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; - }, - access: function( owner, key, value ) { - - // In cases where either: - // - // 1. No key was specified - // 2. A string key was specified, but no value provided - // - // Take the "read" path and allow the get method to determine - // which value to return, respectively either: - // - // 1. The entire cache object - // 2. The data stored at the key - // - if ( key === undefined || - ( ( key && typeof key === "string" ) && value === undefined ) ) { - - return this.get( owner, key ); - } - - // When the key is not a string, or both a key and value - // are specified, set or extend (existing objects) with either: - // - // 1. An object of properties - // 2. A key and value - // - this.set( owner, key, value ); - - // Since the "set" path can have two possible entry points - // return the expected data based on which path was taken[*] - return value !== undefined ? value : key; - }, - remove: function( owner, key ) { - var i, - cache = owner[ this.expando ]; - - if ( cache === undefined ) { - return; - } - - if ( key !== undefined ) { - - // Support array or space separated string of keys - if ( Array.isArray( key ) ) { - - // If key is an array of keys... - // We always set camelCase keys, so remove that. - key = key.map( camelCase ); - } else { - key = camelCase( key ); - - // If a key with the spaces exists, use it. - // Otherwise, create an array by matching non-whitespace - key = key in cache ? - [ key ] : - ( key.match( rnothtmlwhite ) || [] ); - } - - i = key.length; - - while ( i-- ) { - delete cache[ key[ i ] ]; - } - } - - // Remove the expando if there's no more data - if ( key === undefined || jQuery.isEmptyObject( cache ) ) { - - // Support: Chrome <=35 - 45 - // Webkit & Blink performance suffers when deleting properties - // from DOM nodes, so set to undefined instead - // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) - if ( owner.nodeType ) { - owner[ this.expando ] = undefined; - } else { - delete owner[ this.expando ]; - } - } - }, - hasData: function( owner ) { - var cache = owner[ this.expando ]; - return cache !== undefined && !jQuery.isEmptyObject( cache ); - } -}; -var dataPriv = new Data(); - -var dataUser = new Data(); - - - -// Implementation Summary -// -// 1. Enforce API surface and semantic compatibility with 1.9.x branch -// 2. Improve the module's maintainability by reducing the storage -// paths to a single mechanism. -// 3. Use the same single mechanism to support "private" and "user" data. -// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) -// 5. Avoid exposing implementation details on user objects (eg. expando properties) -// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 - -var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, - rmultiDash = /[A-Z]/g; - -function getData( data ) { - if ( data === "true" ) { - return true; - } - - if ( data === "false" ) { - return false; - } - - if ( data === "null" ) { - return null; - } - - // Only convert to a number if it doesn't change the string - if ( data === +data + "" ) { - return +data; - } - - if ( rbrace.test( data ) ) { - return JSON.parse( data ); - } - - return data; -} - -function dataAttr( elem, key, data ) { - var name; - - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = getData( data ); - } catch ( e ) {} - - // Make sure we set the data so it isn't changed later - dataUser.set( elem, key, data ); - } else { - data = undefined; - } - } - return data; -} - -jQuery.extend( { - hasData: function( elem ) { - return dataUser.hasData( elem ) || dataPriv.hasData( elem ); - }, - - data: function( elem, name, data ) { - return dataUser.access( elem, name, data ); - }, - - removeData: function( elem, name ) { - dataUser.remove( elem, name ); - }, - - // TODO: Now that all calls to _data and _removeData have been replaced - // with direct calls to dataPriv methods, these can be deprecated. - _data: function( elem, name, data ) { - return dataPriv.access( elem, name, data ); - }, - - _removeData: function( elem, name ) { - dataPriv.remove( elem, name ); - } -} ); - -jQuery.fn.extend( { - data: function( key, value ) { - var i, name, data, - elem = this[ 0 ], - attrs = elem && elem.attributes; - - // Gets all values - if ( key === undefined ) { - if ( this.length ) { - data = dataUser.get( elem ); - - if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { - i = attrs.length; - while ( i-- ) { - - // Support: IE 11 only - // The attrs elements can be null (#14894) - if ( attrs[ i ] ) { - name = attrs[ i ].name; - if ( name.indexOf( "data-" ) === 0 ) { - name = camelCase( name.slice( 5 ) ); - dataAttr( elem, name, data[ name ] ); - } - } - } - dataPriv.set( elem, "hasDataAttrs", true ); - } - } - - return data; - } - - // Sets multiple values - if ( typeof key === "object" ) { - return this.each( function() { - dataUser.set( this, key ); - } ); - } - - return access( this, function( value ) { - var data; - - // The calling jQuery object (element matches) is not empty - // (and therefore has an element appears at this[ 0 ]) and the - // `value` parameter was not undefined. An empty jQuery object - // will result in `undefined` for elem = this[ 0 ] which will - // throw an exception if an attempt to read a data cache is made. - if ( elem && value === undefined ) { - - // Attempt to get data from the cache - // The key will always be camelCased in Data - data = dataUser.get( elem, key ); - if ( data !== undefined ) { - return data; - } - - // Attempt to "discover" the data in - // HTML5 custom data-* attrs - data = dataAttr( elem, key ); - if ( data !== undefined ) { - return data; - } - - // We tried really hard, but the data doesn't exist. - return; - } - - // Set the data... - this.each( function() { - - // We always store the camelCased key - dataUser.set( this, key, value ); - } ); - }, null, value, arguments.length > 1, null, true ); - }, - - removeData: function( key ) { - return this.each( function() { - dataUser.remove( this, key ); - } ); - } -} ); - - -jQuery.extend( { - queue: function( elem, type, data ) { - var queue; - - if ( elem ) { - type = ( type || "fx" ) + "queue"; - queue = dataPriv.get( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !queue || Array.isArray( data ) ) { - queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); - } else { - queue.push( data ); - } - } - return queue || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - startLength = queue.length, - fn = queue.shift(), - hooks = jQuery._queueHooks( elem, type ), - next = function() { - jQuery.dequeue( elem, type ); - }; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - startLength--; - } - - if ( fn ) { - - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - // Clear up the last queue stop function - delete hooks.stop; - fn.call( elem, next, hooks ); - } - - if ( !startLength && hooks ) { - hooks.empty.fire(); - } - }, - - // Not public - generate a queueHooks object, or return the current one - _queueHooks: function( elem, type ) { - var key = type + "queueHooks"; - return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { - empty: jQuery.Callbacks( "once memory" ).add( function() { - dataPriv.remove( elem, [ type + "queue", key ] ); - } ) - } ); - } -} ); - -jQuery.fn.extend( { - queue: function( type, data ) { - var setter = 2; - - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - setter--; - } - - if ( arguments.length < setter ) { - return jQuery.queue( this[ 0 ], type ); - } - - return data === undefined ? - this : - this.each( function() { - var queue = jQuery.queue( this, type, data ); - - // Ensure a hooks for this queue - jQuery._queueHooks( this, type ); - - if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - } ); - }, - dequeue: function( type ) { - return this.each( function() { - jQuery.dequeue( this, type ); - } ); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, obj ) { - var tmp, - count = 1, - defer = jQuery.Deferred(), - elements = this, - i = this.length, - resolve = function() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - }; - - if ( typeof type !== "string" ) { - obj = type; - type = undefined; - } - type = type || "fx"; - - while ( i-- ) { - tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); - if ( tmp && tmp.empty ) { - count++; - tmp.empty.add( resolve ); - } - } - resolve(); - return defer.promise( obj ); - } -} ); -var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; - -var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); - - -var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; - -var documentElement = document.documentElement; - - - - var isAttached = function( elem ) { - return jQuery.contains( elem.ownerDocument, elem ); - }, - composed = { composed: true }; - - // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only - // Check attachment across shadow DOM boundaries when possible (gh-3504) - // Support: iOS 10.0-10.2 only - // Early iOS 10 versions support `attachShadow` but not `getRootNode`, - // leading to errors. We need to check for `getRootNode`. - if ( documentElement.getRootNode ) { - isAttached = function( elem ) { - return jQuery.contains( elem.ownerDocument, elem ) || - elem.getRootNode( composed ) === elem.ownerDocument; - }; - } -var isHiddenWithinTree = function( elem, el ) { - - // isHiddenWithinTree might be called from jQuery#filter function; - // in that case, element will be second argument - elem = el || elem; - - // Inline style trumps all - return elem.style.display === "none" || - elem.style.display === "" && - - // Otherwise, check computed style - // Support: Firefox <=43 - 45 - // Disconnected elements can have computed display: none, so first confirm that elem is - // in the document. - isAttached( elem ) && - - jQuery.css( elem, "display" ) === "none"; - }; - - - -function adjustCSS( elem, prop, valueParts, tween ) { - var adjusted, scale, - maxIterations = 20, - currentValue = tween ? - function() { - return tween.cur(); - } : - function() { - return jQuery.css( elem, prop, "" ); - }, - initial = currentValue(), - unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), - - // Starting value computation is required for potential unit mismatches - initialInUnit = elem.nodeType && - ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && - rcssNum.exec( jQuery.css( elem, prop ) ); - - if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { - - // Support: Firefox <=54 - // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) - initial = initial / 2; - - // Trust units reported by jQuery.css - unit = unit || initialInUnit[ 3 ]; - - // Iteratively approximate from a nonzero starting point - initialInUnit = +initial || 1; - - while ( maxIterations-- ) { - - // Evaluate and update our best guess (doubling guesses that zero out). - // Finish if the scale equals or crosses 1 (making the old*new product non-positive). - jQuery.style( elem, prop, initialInUnit + unit ); - if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { - maxIterations = 0; - } - initialInUnit = initialInUnit / scale; - - } - - initialInUnit = initialInUnit * 2; - jQuery.style( elem, prop, initialInUnit + unit ); - - // Make sure we update the tween properties later on - valueParts = valueParts || []; - } - - if ( valueParts ) { - initialInUnit = +initialInUnit || +initial || 0; - - // Apply relative offset (+=/-=) if specified - adjusted = valueParts[ 1 ] ? - initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : - +valueParts[ 2 ]; - if ( tween ) { - tween.unit = unit; - tween.start = initialInUnit; - tween.end = adjusted; - } - } - return adjusted; -} - - -var defaultDisplayMap = {}; - -function getDefaultDisplay( elem ) { - var temp, - doc = elem.ownerDocument, - nodeName = elem.nodeName, - display = defaultDisplayMap[ nodeName ]; - - if ( display ) { - return display; - } - - temp = doc.body.appendChild( doc.createElement( nodeName ) ); - display = jQuery.css( temp, "display" ); - - temp.parentNode.removeChild( temp ); - - if ( display === "none" ) { - display = "block"; - } - defaultDisplayMap[ nodeName ] = display; - - return display; -} - -function showHide( elements, show ) { - var display, elem, - values = [], - index = 0, - length = elements.length; - - // Determine new display value for elements that need to change - for ( ; index < length; index++ ) { - elem = elements[ index ]; - if ( !elem.style ) { - continue; - } - - display = elem.style.display; - if ( show ) { - - // Since we force visibility upon cascade-hidden elements, an immediate (and slow) - // check is required in this first loop unless we have a nonempty display value (either - // inline or about-to-be-restored) - if ( display === "none" ) { - values[ index ] = dataPriv.get( elem, "display" ) || null; - if ( !values[ index ] ) { - elem.style.display = ""; - } - } - if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { - values[ index ] = getDefaultDisplay( elem ); - } - } else { - if ( display !== "none" ) { - values[ index ] = "none"; - - // Remember what we're overwriting - dataPriv.set( elem, "display", display ); - } - } - } - - // Set the display of the elements in a second loop to avoid constant reflow - for ( index = 0; index < length; index++ ) { - if ( values[ index ] != null ) { - elements[ index ].style.display = values[ index ]; - } - } - - return elements; -} - -jQuery.fn.extend( { - show: function() { - return showHide( this, true ); - }, - hide: function() { - return showHide( this ); - }, - toggle: function( state ) { - if ( typeof state === "boolean" ) { - return state ? this.show() : this.hide(); - } - - return this.each( function() { - if ( isHiddenWithinTree( this ) ) { - jQuery( this ).show(); - } else { - jQuery( this ).hide(); - } - } ); - } -} ); -var rcheckableType = ( /^(?:checkbox|radio)$/i ); - -var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); - -var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); - - - -( function() { - var fragment = document.createDocumentFragment(), - div = fragment.appendChild( document.createElement( "div" ) ), - input = document.createElement( "input" ); - - // Support: Android 4.0 - 4.3 only - // Check state lost if the name is set (#11217) - // Support: Windows Web Apps (WWA) - // `name` and `type` must use .setAttribute for WWA (#14901) - input.setAttribute( "type", "radio" ); - input.setAttribute( "checked", "checked" ); - input.setAttribute( "name", "t" ); - - div.appendChild( input ); - - // Support: Android <=4.1 only - // Older WebKit doesn't clone checked state correctly in fragments - support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Support: IE <=11 only - // Make sure textarea (and checkbox) defaultValue is properly cloned - div.innerHTML = ""; - support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; - - // Support: IE <=9 only - // IE <=9 replaces "; - support.option = !!div.lastChild; -} )(); - - -// We have to close these tags to support XHTML (#13200) -var wrapMap = { - - // XHTML parsers do not magically insert elements in the - // same way that tag soup parsers do. So we cannot shorten - // this by omitting or other required elements. - thead: [ 1, "", "
" ], - col: [ 2, "", "
" ], - tr: [ 2, "", "
" ], - td: [ 3, "", "
" ], - - _default: [ 0, "", "" ] -}; - -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// Support: IE <=9 only -if ( !support.option ) { - wrapMap.optgroup = wrapMap.option = [ 1, "" ]; -} - - -function getAll( context, tag ) { - - // Support: IE <=9 - 11 only - // Use typeof to avoid zero-argument method invocation on host objects (#15151) - var ret; - - if ( typeof context.getElementsByTagName !== "undefined" ) { - ret = context.getElementsByTagName( tag || "*" ); - - } else if ( typeof context.querySelectorAll !== "undefined" ) { - ret = context.querySelectorAll( tag || "*" ); - - } else { - ret = []; - } - - if ( tag === undefined || tag && nodeName( context, tag ) ) { - return jQuery.merge( [ context ], ret ); - } - - return ret; -} - - -// Mark scripts as having already been evaluated -function setGlobalEval( elems, refElements ) { - var i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - dataPriv.set( - elems[ i ], - "globalEval", - !refElements || dataPriv.get( refElements[ i ], "globalEval" ) - ); - } -} - - -var rhtml = /<|&#?\w+;/; - -function buildFragment( elems, context, scripts, selection, ignored ) { - var elem, tmp, tag, wrap, attached, j, - fragment = context.createDocumentFragment(), - nodes = [], - i = 0, - l = elems.length; - - for ( ; i < l; i++ ) { - elem = elems[ i ]; - - if ( elem || elem === 0 ) { - - // Add nodes directly - if ( toType( elem ) === "object" ) { - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); - - // Convert non-html into a text node - } else if ( !rhtml.test( elem ) ) { - nodes.push( context.createTextNode( elem ) ); - - // Convert html into DOM nodes - } else { - tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); - - // Deserialize a standard representation - tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); - wrap = wrapMap[ tag ] || wrapMap._default; - tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; - - // Descend through wrappers to the right content - j = wrap[ 0 ]; - while ( j-- ) { - tmp = tmp.lastChild; - } - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( nodes, tmp.childNodes ); - - // Remember the top-level container - tmp = fragment.firstChild; - - // Ensure the created nodes are orphaned (#12392) - tmp.textContent = ""; - } - } - } - - // Remove wrapper from fragment - fragment.textContent = ""; - - i = 0; - while ( ( elem = nodes[ i++ ] ) ) { - - // Skip elements already in the context collection (trac-4087) - if ( selection && jQuery.inArray( elem, selection ) > -1 ) { - if ( ignored ) { - ignored.push( elem ); - } - continue; - } - - attached = isAttached( elem ); - - // Append to fragment - tmp = getAll( fragment.appendChild( elem ), "script" ); - - // Preserve script evaluation history - if ( attached ) { - setGlobalEval( tmp ); - } - - // Capture executables - if ( scripts ) { - j = 0; - while ( ( elem = tmp[ j++ ] ) ) { - if ( rscriptType.test( elem.type || "" ) ) { - scripts.push( elem ); - } - } - } - } - - return fragment; -} - - -var rtypenamespace = /^([^.]*)(?:\.(.+)|)/; - -function returnTrue() { - return true; -} - -function returnFalse() { - return false; -} - -// Support: IE <=9 - 11+ -// focus() and blur() are asynchronous, except when they are no-op. -// So expect focus to be synchronous when the element is already active, -// and blur to be synchronous when the element is not already active. -// (focus and blur are always synchronous in other supported browsers, -// this just defines when we can count on it). -function expectSync( elem, type ) { - return ( elem === safeActiveElement() ) === ( type === "focus" ); -} - -// Support: IE <=9 only -// Accessing document.activeElement can throw unexpectedly -// https://bugs.jquery.com/ticket/13393 -function safeActiveElement() { - try { - return document.activeElement; - } catch ( err ) { } -} - -function on( elem, types, selector, data, fn, one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - - // ( types-Object, data ) - data = data || selector; - selector = undefined; - } - for ( type in types ) { - on( elem, type, selector, data, types[ type ], one ); - } - return elem; - } - - if ( data == null && fn == null ) { - - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return elem; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return elem.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - } ); -} - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - global: {}, - - add: function( elem, types, handler, data, selector ) { - - var handleObjIn, eventHandle, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.get( elem ); - - // Only attach events to objects that accept data - if ( !acceptData( elem ) ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - selector = handleObjIn.selector; - } - - // Ensure that invalid selectors throw exceptions at attach time - // Evaluate against documentElement in case elem is a non-element node (e.g., document) - if ( selector ) { - jQuery.find.matchesSelector( documentElement, selector ); - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - if ( !( events = elemData.events ) ) { - events = elemData.events = Object.create( null ); - } - if ( !( eventHandle = elemData.handle ) ) { - eventHandle = elemData.handle = function( e ) { - - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? - jQuery.event.dispatch.apply( elem, arguments ) : undefined; - }; - } - - // Handle multiple events separated by a space - types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // There *must* be a type, no attaching namespace-only handlers - if ( !type ) { - continue; - } - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend( { - type: type, - origType: origType, - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - needsContext: selector && jQuery.expr.match.needsContext.test( selector ), - namespace: namespaces.join( "." ) - }, handleObjIn ); - - // Init the event handler queue if we're the first - if ( !( handlers = events[ type ] ) ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener if the special events handler returns false - if ( !special.setup || - special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - }, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var j, origCount, tmp, - events, t, handleObj, - special, handlers, type, namespaces, origType, - elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); - - if ( !elemData || !( events = elemData.events ) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; - t = types.length; - while ( t-- ) { - tmp = rtypenamespace.exec( types[ t ] ) || []; - type = origType = tmp[ 1 ]; - namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector ? special.delegateType : special.bindType ) || type; - handlers = events[ type ] || []; - tmp = tmp[ 2 ] && - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); - - // Remove matching events - origCount = j = handlers.length; - while ( j-- ) { - handleObj = handlers[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !tmp || tmp.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || - selector === "**" && handleObj.selector ) ) { - handlers.splice( j, 1 ); - - if ( handleObj.selector ) { - handlers.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( origCount && !handlers.length ) { - if ( !special.teardown || - special.teardown.call( elem, namespaces, elemData.handle ) === false ) { - - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove data and the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - dataPriv.remove( elem, "handle events" ); - } - }, - - dispatch: function( nativeEvent ) { - - var i, j, ret, matched, handleObj, handlerQueue, - args = new Array( arguments.length ), - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( nativeEvent ), - - handlers = ( - dataPriv.get( this, "events" ) || Object.create( null ) - )[ event.type ] || [], - special = jQuery.event.special[ event.type ] || {}; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[ 0 ] = event; - - for ( i = 1; i < arguments.length; i++ ) { - args[ i ] = arguments[ i ]; - } - - event.delegateTarget = this; - - // Call the preDispatch hook for the mapped type, and let it bail if desired - if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { - return; - } - - // Determine handlers - handlerQueue = jQuery.event.handlers.call( this, event, handlers ); - - // Run delegates first; they may want to stop propagation beneath us - i = 0; - while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { - event.currentTarget = matched.elem; - - j = 0; - while ( ( handleObj = matched.handlers[ j++ ] ) && - !event.isImmediatePropagationStopped() ) { - - // If the event is namespaced, then each handler is only invoked if it is - // specially universal or its namespaces are a superset of the event's. - if ( !event.rnamespace || handleObj.namespace === false || - event.rnamespace.test( handleObj.namespace ) ) { - - event.handleObj = handleObj; - event.data = handleObj.data; - - ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || - handleObj.handler ).apply( matched.elem, args ); - - if ( ret !== undefined ) { - if ( ( event.result = ret ) === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - // Call the postDispatch hook for the mapped type - if ( special.postDispatch ) { - special.postDispatch.call( this, event ); - } - - return event.result; - }, - - handlers: function( event, handlers ) { - var i, handleObj, sel, matchedHandlers, matchedSelectors, - handlerQueue = [], - delegateCount = handlers.delegateCount, - cur = event.target; - - // Find delegate handlers - if ( delegateCount && - - // Support: IE <=9 - // Black-hole SVG instance trees (trac-13180) - cur.nodeType && - - // Support: Firefox <=42 - // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) - // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click - // Support: IE 11 only - // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) - !( event.type === "click" && event.button >= 1 ) ) { - - for ( ; cur !== this; cur = cur.parentNode || this ) { - - // Don't check non-elements (#13208) - // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) - if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { - matchedHandlers = []; - matchedSelectors = {}; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - - // Don't conflict with Object.prototype properties (#13203) - sel = handleObj.selector + " "; - - if ( matchedSelectors[ sel ] === undefined ) { - matchedSelectors[ sel ] = handleObj.needsContext ? - jQuery( sel, this ).index( cur ) > -1 : - jQuery.find( sel, this, null, [ cur ] ).length; - } - if ( matchedSelectors[ sel ] ) { - matchedHandlers.push( handleObj ); - } - } - if ( matchedHandlers.length ) { - handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); - } - } - } - } - - // Add the remaining (directly-bound) handlers - cur = this; - if ( delegateCount < handlers.length ) { - handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); - } - - return handlerQueue; - }, - - addProp: function( name, hook ) { - Object.defineProperty( jQuery.Event.prototype, name, { - enumerable: true, - configurable: true, - - get: isFunction( hook ) ? - function() { - if ( this.originalEvent ) { - return hook( this.originalEvent ); - } - } : - function() { - if ( this.originalEvent ) { - return this.originalEvent[ name ]; - } - }, - - set: function( value ) { - Object.defineProperty( this, name, { - enumerable: true, - configurable: true, - writable: true, - value: value - } ); - } - } ); - }, - - fix: function( originalEvent ) { - return originalEvent[ jQuery.expando ] ? - originalEvent : - new jQuery.Event( originalEvent ); - }, - - special: { - load: { - - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - click: { - - // Utilize native event to ensure correct state for checkable inputs - setup: function( data ) { - - // For mutual compressibility with _default, replace `this` access with a local var. - // `|| data` is dead code meant only to preserve the variable through minification. - var el = this || data; - - // Claim the first handler - if ( rcheckableType.test( el.type ) && - el.click && nodeName( el, "input" ) ) { - - // dataPriv.set( el, "click", ... ) - leverageNative( el, "click", returnTrue ); - } - - // Return false to allow normal processing in the caller - return false; - }, - trigger: function( data ) { - - // For mutual compressibility with _default, replace `this` access with a local var. - // `|| data` is dead code meant only to preserve the variable through minification. - var el = this || data; - - // Force setup before triggering a click - if ( rcheckableType.test( el.type ) && - el.click && nodeName( el, "input" ) ) { - - leverageNative( el, "click" ); - } - - // Return non-false to allow normal event-path propagation - return true; - }, - - // For cross-browser consistency, suppress native .click() on links - // Also prevent it if we're currently inside a leveraged native-event stack - _default: function( event ) { - var target = event.target; - return rcheckableType.test( target.type ) && - target.click && nodeName( target, "input" ) && - dataPriv.get( target, "click" ) || - nodeName( target, "a" ); - } - }, - - beforeunload: { - postDispatch: function( event ) { - - // Support: Firefox 20+ - // Firefox doesn't alert if the returnValue field is not set. - if ( event.result !== undefined && event.originalEvent ) { - event.originalEvent.returnValue = event.result; - } - } - } - } -}; - -// Ensure the presence of an event listener that handles manually-triggered -// synthetic events by interrupting progress until reinvoked in response to -// *native* events that it fires directly, ensuring that state changes have -// already occurred before other listeners are invoked. -function leverageNative( el, type, expectSync ) { - - // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add - if ( !expectSync ) { - if ( dataPriv.get( el, type ) === undefined ) { - jQuery.event.add( el, type, returnTrue ); - } - return; - } - - // Register the controller as a special universal handler for all event namespaces - dataPriv.set( el, type, false ); - jQuery.event.add( el, type, { - namespace: false, - handler: function( event ) { - var notAsync, result, - saved = dataPriv.get( this, type ); - - if ( ( event.isTrigger & 1 ) && this[ type ] ) { - - // Interrupt processing of the outer synthetic .trigger()ed event - // Saved data should be false in such cases, but might be a leftover capture object - // from an async native handler (gh-4350) - if ( !saved.length ) { - - // Store arguments for use when handling the inner native event - // There will always be at least one argument (an event object), so this array - // will not be confused with a leftover capture object. - saved = slice.call( arguments ); - dataPriv.set( this, type, saved ); - - // Trigger the native event and capture its result - // Support: IE <=9 - 11+ - // focus() and blur() are asynchronous - notAsync = expectSync( this, type ); - this[ type ](); - result = dataPriv.get( this, type ); - if ( saved !== result || notAsync ) { - dataPriv.set( this, type, false ); - } else { - result = {}; - } - if ( saved !== result ) { - - // Cancel the outer synthetic event - event.stopImmediatePropagation(); - event.preventDefault(); - - // Support: Chrome 86+ - // In Chrome, if an element having a focusout handler is blurred by - // clicking outside of it, it invokes the handler synchronously. If - // that handler calls `.remove()` on the element, the data is cleared, - // leaving `result` undefined. We need to guard against this. - return result && result.value; - } - - // If this is an inner synthetic event for an event with a bubbling surrogate - // (focus or blur), assume that the surrogate already propagated from triggering the - // native event and prevent that from happening again here. - // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the - // bubbling surrogate propagates *after* the non-bubbling base), but that seems - // less bad than duplication. - } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { - event.stopPropagation(); - } - - // If this is a native event triggered above, everything is now in order - // Fire an inner synthetic event with the original arguments - } else if ( saved.length ) { - - // ...and capture the result - dataPriv.set( this, type, { - value: jQuery.event.trigger( - - // Support: IE <=9 - 11+ - // Extend with the prototype to reset the above stopImmediatePropagation() - jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), - saved.slice( 1 ), - this - ) - } ); - - // Abort handling of the native event - event.stopImmediatePropagation(); - } - } - } ); -} - -jQuery.removeEvent = function( elem, type, handle ) { - - // This "if" is needed for plain objects - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle ); - } -}; - -jQuery.Event = function( src, props ) { - - // Allow instantiation without the 'new' keyword - if ( !( this instanceof jQuery.Event ) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = src.defaultPrevented || - src.defaultPrevented === undefined && - - // Support: Android <=2.3 only - src.returnValue === false ? - returnTrue : - returnFalse; - - // Create target properties - // Support: Safari <=6 - 7 only - // Target should not be a text node (#504, #13143) - this.target = ( src.target && src.target.nodeType === 3 ) ? - src.target.parentNode : - src.target; - - this.currentTarget = src.currentTarget; - this.relatedTarget = src.relatedTarget; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || Date.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - constructor: jQuery.Event, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse, - isSimulated: false, - - preventDefault: function() { - var e = this.originalEvent; - - this.isDefaultPrevented = returnTrue; - - if ( e && !this.isSimulated ) { - e.preventDefault(); - } - }, - stopPropagation: function() { - var e = this.originalEvent; - - this.isPropagationStopped = returnTrue; - - if ( e && !this.isSimulated ) { - e.stopPropagation(); - } - }, - stopImmediatePropagation: function() { - var e = this.originalEvent; - - this.isImmediatePropagationStopped = returnTrue; - - if ( e && !this.isSimulated ) { - e.stopImmediatePropagation(); - } - - this.stopPropagation(); - } -}; - -// Includes all common event props including KeyEvent and MouseEvent specific props -jQuery.each( { - altKey: true, - bubbles: true, - cancelable: true, - changedTouches: true, - ctrlKey: true, - detail: true, - eventPhase: true, - metaKey: true, - pageX: true, - pageY: true, - shiftKey: true, - view: true, - "char": true, - code: true, - charCode: true, - key: true, - keyCode: true, - button: true, - buttons: true, - clientX: true, - clientY: true, - offsetX: true, - offsetY: true, - pointerId: true, - pointerType: true, - screenX: true, - screenY: true, - targetTouches: true, - toElement: true, - touches: true, - which: true -}, jQuery.event.addProp ); - -jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { - jQuery.event.special[ type ] = { - - // Utilize native event if possible so blur/focus sequence is correct - setup: function() { - - // Claim the first handler - // dataPriv.set( this, "focus", ... ) - // dataPriv.set( this, "blur", ... ) - leverageNative( this, type, expectSync ); - - // Return false to allow normal processing in the caller - return false; - }, - trigger: function() { - - // Force setup before trigger - leverageNative( this, type ); - - // Return non-false to allow normal event-path propagation - return true; - }, - - // Suppress native focus or blur as it's already being fired - // in leverageNative. - _default: function() { - return true; - }, - - delegateType: delegateType - }; -} ); - -// Create mouseenter/leave events using mouseover/out and event-time checks -// so that event delegation works in jQuery. -// Do the same for pointerenter/pointerleave and pointerover/pointerout -// -// Support: Safari 7 only -// Safari sends mouseenter too often; see: -// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 -// for the description of the bug (it existed in older Chrome versions as well). -jQuery.each( { - mouseenter: "mouseover", - mouseleave: "mouseout", - pointerenter: "pointerover", - pointerleave: "pointerout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var ret, - target = this, - related = event.relatedTarget, - handleObj = event.handleObj; - - // For mouseenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -} ); - -jQuery.fn.extend( { - - on: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn ); - }, - one: function( types, selector, data, fn ) { - return on( this, types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - var handleObj, type; - if ( types && types.preventDefault && types.handleObj ) { - - // ( event ) dispatched jQuery.Event - handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace ? - handleObj.origType + "." + handleObj.namespace : - handleObj.origType, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - - // ( types-object [, selector] ) - for ( type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each( function() { - jQuery.event.remove( this, types, fn, selector ); - } ); - } -} ); - - -var - - // Support: IE <=10 - 11, Edge 12 - 13 only - // In IE/Edge using regex groups here causes severe slowdowns. - // See https://connect.microsoft.com/IE/feedback/details/1736512/ - rnoInnerhtml = /\s*$/g; - -// Prefer a tbody over its parent table for containing new rows -function manipulationTarget( elem, content ) { - if ( nodeName( elem, "table" ) && - nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { - - return jQuery( elem ).children( "tbody" )[ 0 ] || elem; - } - - return elem; -} - -// Replace/restore the type attribute of script elements for safe DOM manipulation -function disableScript( elem ) { - elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; - return elem; -} -function restoreScript( elem ) { - if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { - elem.type = elem.type.slice( 5 ); - } else { - elem.removeAttribute( "type" ); - } - - return elem; -} - -function cloneCopyEvent( src, dest ) { - var i, l, type, pdataOld, udataOld, udataCur, events; - - if ( dest.nodeType !== 1 ) { - return; - } - - // 1. Copy private data: events, handlers, etc. - if ( dataPriv.hasData( src ) ) { - pdataOld = dataPriv.get( src ); - events = pdataOld.events; - - if ( events ) { - dataPriv.remove( dest, "handle events" ); - - for ( type in events ) { - for ( i = 0, l = events[ type ].length; i < l; i++ ) { - jQuery.event.add( dest, type, events[ type ][ i ] ); - } - } - } - } - - // 2. Copy user data - if ( dataUser.hasData( src ) ) { - udataOld = dataUser.access( src ); - udataCur = jQuery.extend( {}, udataOld ); - - dataUser.set( dest, udataCur ); - } -} - -// Fix IE bugs, see support tests -function fixInput( src, dest ) { - var nodeName = dest.nodeName.toLowerCase(); - - // Fails to persist the checked state of a cloned checkbox or radio button. - if ( nodeName === "input" && rcheckableType.test( src.type ) ) { - dest.checked = src.checked; - - // Fails to return the selected option to the default selected state when cloning options - } else if ( nodeName === "input" || nodeName === "textarea" ) { - dest.defaultValue = src.defaultValue; - } -} - -function domManip( collection, args, callback, ignored ) { - - // Flatten any nested arrays - args = flat( args ); - - var fragment, first, scripts, hasScripts, node, doc, - i = 0, - l = collection.length, - iNoClone = l - 1, - value = args[ 0 ], - valueIsFunction = isFunction( value ); - - // We can't cloneNode fragments that contain checked, in WebKit - if ( valueIsFunction || - ( l > 1 && typeof value === "string" && - !support.checkClone && rchecked.test( value ) ) ) { - return collection.each( function( index ) { - var self = collection.eq( index ); - if ( valueIsFunction ) { - args[ 0 ] = value.call( this, index, self.html() ); - } - domManip( self, args, callback, ignored ); - } ); - } - - if ( l ) { - fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); - first = fragment.firstChild; - - if ( fragment.childNodes.length === 1 ) { - fragment = first; - } - - // Require either new content or an interest in ignored elements to invoke the callback - if ( first || ignored ) { - scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); - hasScripts = scripts.length; - - // Use the original fragment for the last item - // instead of the first because it can end up - // being emptied incorrectly in certain situations (#8070). - for ( ; i < l; i++ ) { - node = fragment; - - if ( i !== iNoClone ) { - node = jQuery.clone( node, true, true ); - - // Keep references to cloned scripts for later restoration - if ( hasScripts ) { - - // Support: Android <=4.0 only, PhantomJS 1 only - // push.apply(_, arraylike) throws on ancient WebKit - jQuery.merge( scripts, getAll( node, "script" ) ); - } - } - - callback.call( collection[ i ], node, i ); - } - - if ( hasScripts ) { - doc = scripts[ scripts.length - 1 ].ownerDocument; - - // Reenable scripts - jQuery.map( scripts, restoreScript ); - - // Evaluate executable scripts on first document insertion - for ( i = 0; i < hasScripts; i++ ) { - node = scripts[ i ]; - if ( rscriptType.test( node.type || "" ) && - !dataPriv.access( node, "globalEval" ) && - jQuery.contains( doc, node ) ) { - - if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { - - // Optional AJAX dependency, but won't run scripts if not present - if ( jQuery._evalUrl && !node.noModule ) { - jQuery._evalUrl( node.src, { - nonce: node.nonce || node.getAttribute( "nonce" ) - }, doc ); - } - } else { - DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); - } - } - } - } - } - } - - return collection; -} - -function remove( elem, selector, keepData ) { - var node, - nodes = selector ? jQuery.filter( selector, elem ) : elem, - i = 0; - - for ( ; ( node = nodes[ i ] ) != null; i++ ) { - if ( !keepData && node.nodeType === 1 ) { - jQuery.cleanData( getAll( node ) ); - } - - if ( node.parentNode ) { - if ( keepData && isAttached( node ) ) { - setGlobalEval( getAll( node, "script" ) ); - } - node.parentNode.removeChild( node ); - } - } - - return elem; -} - -jQuery.extend( { - htmlPrefilter: function( html ) { - return html; - }, - - clone: function( elem, dataAndEvents, deepDataAndEvents ) { - var i, l, srcElements, destElements, - clone = elem.cloneNode( true ), - inPage = isAttached( elem ); - - // Fix IE cloning issues - if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && - !jQuery.isXMLDoc( elem ) ) { - - // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 - destElements = getAll( clone ); - srcElements = getAll( elem ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - fixInput( srcElements[ i ], destElements[ i ] ); - } - } - - // Copy the events from the original to the clone - if ( dataAndEvents ) { - if ( deepDataAndEvents ) { - srcElements = srcElements || getAll( elem ); - destElements = destElements || getAll( clone ); - - for ( i = 0, l = srcElements.length; i < l; i++ ) { - cloneCopyEvent( srcElements[ i ], destElements[ i ] ); - } - } else { - cloneCopyEvent( elem, clone ); - } - } - - // Preserve script evaluation history - destElements = getAll( clone, "script" ); - if ( destElements.length > 0 ) { - setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); - } - - // Return the cloned set - return clone; - }, - - cleanData: function( elems ) { - var data, elem, type, - special = jQuery.event.special, - i = 0; - - for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { - if ( acceptData( elem ) ) { - if ( ( data = elem[ dataPriv.expando ] ) ) { - if ( data.events ) { - for ( type in data.events ) { - if ( special[ type ] ) { - jQuery.event.remove( elem, type ); - - // This is a shortcut to avoid jQuery.event.remove's overhead - } else { - jQuery.removeEvent( elem, type, data.handle ); - } - } - } - - // Support: Chrome <=35 - 45+ - // Assign undefined instead of using delete, see Data#remove - elem[ dataPriv.expando ] = undefined; - } - if ( elem[ dataUser.expando ] ) { - - // Support: Chrome <=35 - 45+ - // Assign undefined instead of using delete, see Data#remove - elem[ dataUser.expando ] = undefined; - } - } - } - } -} ); - -jQuery.fn.extend( { - detach: function( selector ) { - return remove( this, selector, true ); - }, - - remove: function( selector ) { - return remove( this, selector ); - }, - - text: function( value ) { - return access( this, function( value ) { - return value === undefined ? - jQuery.text( this ) : - this.empty().each( function() { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - this.textContent = value; - } - } ); - }, null, value, arguments.length ); - }, - - append: function() { - return domManip( this, arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.appendChild( elem ); - } - } ); - }, - - prepend: function() { - return domManip( this, arguments, function( elem ) { - if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { - var target = manipulationTarget( this, elem ); - target.insertBefore( elem, target.firstChild ); - } - } ); - }, - - before: function() { - return domManip( this, arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this ); - } - } ); - }, - - after: function() { - return domManip( this, arguments, function( elem ) { - if ( this.parentNode ) { - this.parentNode.insertBefore( elem, this.nextSibling ); - } - } ); - }, - - empty: function() { - var elem, - i = 0; - - for ( ; ( elem = this[ i ] ) != null; i++ ) { - if ( elem.nodeType === 1 ) { - - // Prevent memory leaks - jQuery.cleanData( getAll( elem, false ) ); - - // Remove any remaining nodes - elem.textContent = ""; - } - } - - return this; - }, - - clone: function( dataAndEvents, deepDataAndEvents ) { - dataAndEvents = dataAndEvents == null ? false : dataAndEvents; - deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; - - return this.map( function() { - return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); - } ); - }, - - html: function( value ) { - return access( this, function( value ) { - var elem = this[ 0 ] || {}, - i = 0, - l = this.length; - - if ( value === undefined && elem.nodeType === 1 ) { - return elem.innerHTML; - } - - // See if we can take a shortcut and just use innerHTML - if ( typeof value === "string" && !rnoInnerhtml.test( value ) && - !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { - - value = jQuery.htmlPrefilter( value ); - - try { - for ( ; i < l; i++ ) { - elem = this[ i ] || {}; - - // Remove element nodes and prevent memory leaks - if ( elem.nodeType === 1 ) { - jQuery.cleanData( getAll( elem, false ) ); - elem.innerHTML = value; - } - } - - elem = 0; - - // If using innerHTML throws an exception, use the fallback method - } catch ( e ) {} - } - - if ( elem ) { - this.empty().append( value ); - } - }, null, value, arguments.length ); - }, - - replaceWith: function() { - var ignored = []; - - // Make the changes, replacing each non-ignored context element with the new content - return domManip( this, arguments, function( elem ) { - var parent = this.parentNode; - - if ( jQuery.inArray( this, ignored ) < 0 ) { - jQuery.cleanData( getAll( this ) ); - if ( parent ) { - parent.replaceChild( elem, this ); - } - } - - // Force callback invocation - }, ignored ); - } -} ); - -jQuery.each( { - appendTo: "append", - prependTo: "prepend", - insertBefore: "before", - insertAfter: "after", - replaceAll: "replaceWith" -}, function( name, original ) { - jQuery.fn[ name ] = function( selector ) { - var elems, - ret = [], - insert = jQuery( selector ), - last = insert.length - 1, - i = 0; - - for ( ; i <= last; i++ ) { - elems = i === last ? this : this.clone( true ); - jQuery( insert[ i ] )[ original ]( elems ); - - // Support: Android <=4.0 only, PhantomJS 1 only - // .get() because push.apply(_, arraylike) throws on ancient WebKit - push.apply( ret, elems.get() ); - } - - return this.pushStack( ret ); - }; -} ); -var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); - -var getStyles = function( elem ) { - - // Support: IE <=11 only, Firefox <=30 (#15098, #14150) - // IE throws on elements created in popups - // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" - var view = elem.ownerDocument.defaultView; - - if ( !view || !view.opener ) { - view = window; - } - - return view.getComputedStyle( elem ); - }; - -var swap = function( elem, options, callback ) { - var ret, name, - old = {}; - - // Remember the old values, and insert the new ones - for ( name in options ) { - old[ name ] = elem.style[ name ]; - elem.style[ name ] = options[ name ]; - } - - ret = callback.call( elem ); - - // Revert the old values - for ( name in options ) { - elem.style[ name ] = old[ name ]; - } - - return ret; -}; - - -var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); - - - -( function() { - - // Executing both pixelPosition & boxSizingReliable tests require only one layout - // so they're executed at the same time to save the second computation. - function computeStyleTests() { - - // This is a singleton, we need to execute it only once - if ( !div ) { - return; - } - - container.style.cssText = "position:absolute;left:-11111px;width:60px;" + - "margin-top:1px;padding:0;border:0"; - div.style.cssText = - "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + - "margin:auto;border:1px;padding:1px;" + - "width:60%;top:1%"; - documentElement.appendChild( container ).appendChild( div ); - - var divStyle = window.getComputedStyle( div ); - pixelPositionVal = divStyle.top !== "1%"; - - // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 - reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; - - // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 - // Some styles come back with percentage values, even though they shouldn't - div.style.right = "60%"; - pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; - - // Support: IE 9 - 11 only - // Detect misreporting of content dimensions for box-sizing:border-box elements - boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; - - // Support: IE 9 only - // Detect overflow:scroll screwiness (gh-3699) - // Support: Chrome <=64 - // Don't get tricked when zoom affects offsetWidth (gh-4029) - div.style.position = "absolute"; - scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; - - documentElement.removeChild( container ); - - // Nullify the div so it wouldn't be stored in the memory and - // it will also be a sign that checks already performed - div = null; - } - - function roundPixelMeasures( measure ) { - return Math.round( parseFloat( measure ) ); - } - - var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, - reliableTrDimensionsVal, reliableMarginLeftVal, - container = document.createElement( "div" ), - div = document.createElement( "div" ); - - // Finish early in limited (non-browser) environments - if ( !div.style ) { - return; - } - - // Support: IE <=9 - 11 only - // Style of cloned element affects source element cloned (#8908) - div.style.backgroundClip = "content-box"; - div.cloneNode( true ).style.backgroundClip = ""; - support.clearCloneStyle = div.style.backgroundClip === "content-box"; - - jQuery.extend( support, { - boxSizingReliable: function() { - computeStyleTests(); - return boxSizingReliableVal; - }, - pixelBoxStyles: function() { - computeStyleTests(); - return pixelBoxStylesVal; - }, - pixelPosition: function() { - computeStyleTests(); - return pixelPositionVal; - }, - reliableMarginLeft: function() { - computeStyleTests(); - return reliableMarginLeftVal; - }, - scrollboxSize: function() { - computeStyleTests(); - return scrollboxSizeVal; - }, - - // Support: IE 9 - 11+, Edge 15 - 18+ - // IE/Edge misreport `getComputedStyle` of table rows with width/height - // set in CSS while `offset*` properties report correct values. - // Behavior in IE 9 is more subtle than in newer versions & it passes - // some versions of this test; make sure not to make it pass there! - // - // Support: Firefox 70+ - // Only Firefox includes border widths - // in computed dimensions. (gh-4529) - reliableTrDimensions: function() { - var table, tr, trChild, trStyle; - if ( reliableTrDimensionsVal == null ) { - table = document.createElement( "table" ); - tr = document.createElement( "tr" ); - trChild = document.createElement( "div" ); - - table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate"; - tr.style.cssText = "border:1px solid"; - - // Support: Chrome 86+ - // Height set through cssText does not get applied. - // Computed height then comes back as 0. - tr.style.height = "1px"; - trChild.style.height = "9px"; - - // Support: Android 8 Chrome 86+ - // In our bodyBackground.html iframe, - // display for all div elements is set to "inline", - // which causes a problem only in Android 8 Chrome 86. - // Ensuring the div is display: block - // gets around this issue. - trChild.style.display = "block"; - - documentElement - .appendChild( table ) - .appendChild( tr ) - .appendChild( trChild ); - - trStyle = window.getComputedStyle( tr ); - reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) + - parseInt( trStyle.borderTopWidth, 10 ) + - parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight; - - documentElement.removeChild( table ); - } - return reliableTrDimensionsVal; - } - } ); -} )(); - - -function curCSS( elem, name, computed ) { - var width, minWidth, maxWidth, ret, - - // Support: Firefox 51+ - // Retrieving style before computed somehow - // fixes an issue with getting wrong values - // on detached elements - style = elem.style; - - computed = computed || getStyles( elem ); - - // getPropertyValue is needed for: - // .css('filter') (IE 9 only, #12537) - // .css('--customProperty) (#3144) - if ( computed ) { - ret = computed.getPropertyValue( name ) || computed[ name ]; - - if ( ret === "" && !isAttached( elem ) ) { - ret = jQuery.style( elem, name ); - } - - // A tribute to the "awesome hack by Dean Edwards" - // Android Browser returns percentage for some values, - // but width seems to be reliably pixels. - // This is against the CSSOM draft spec: - // https://drafts.csswg.org/cssom/#resolved-values - if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { - - // Remember the original values - width = style.width; - minWidth = style.minWidth; - maxWidth = style.maxWidth; - - // Put in the new values to get a computed value out - style.minWidth = style.maxWidth = style.width = ret; - ret = computed.width; - - // Revert the changed values - style.width = width; - style.minWidth = minWidth; - style.maxWidth = maxWidth; - } - } - - return ret !== undefined ? - - // Support: IE <=9 - 11 only - // IE returns zIndex value as an integer. - ret + "" : - ret; -} - - -function addGetHookIf( conditionFn, hookFn ) { - - // Define the hook, we'll check on the first run if it's really needed. - return { - get: function() { - if ( conditionFn() ) { - - // Hook not needed (or it's not possible to use it due - // to missing dependency), remove it. - delete this.get; - return; - } - - // Hook needed; redefine it so that the support test is not executed again. - return ( this.get = hookFn ).apply( this, arguments ); - } - }; -} - - -var cssPrefixes = [ "Webkit", "Moz", "ms" ], - emptyStyle = document.createElement( "div" ).style, - vendorProps = {}; - -// Return a vendor-prefixed property or undefined -function vendorPropName( name ) { - - // Check for vendor prefixed names - var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), - i = cssPrefixes.length; - - while ( i-- ) { - name = cssPrefixes[ i ] + capName; - if ( name in emptyStyle ) { - return name; - } - } -} - -// Return a potentially-mapped jQuery.cssProps or vendor prefixed property -function finalPropName( name ) { - var final = jQuery.cssProps[ name ] || vendorProps[ name ]; - - if ( final ) { - return final; - } - if ( name in emptyStyle ) { - return name; - } - return vendorProps[ name ] = vendorPropName( name ) || name; -} - - -var - - // Swappable if display is none or starts with table - // except "table", "table-cell", or "table-caption" - // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display - rdisplayswap = /^(none|table(?!-c[ea]).+)/, - rcustomProp = /^--/, - cssShow = { position: "absolute", visibility: "hidden", display: "block" }, - cssNormalTransform = { - letterSpacing: "0", - fontWeight: "400" - }; - -function setPositiveNumber( _elem, value, subtract ) { - - // Any relative (+/-) values have already been - // normalized at this point - var matches = rcssNum.exec( value ); - return matches ? - - // Guard against undefined "subtract", e.g., when used as in cssHooks - Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : - value; -} - -function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { - var i = dimension === "width" ? 1 : 0, - extra = 0, - delta = 0; - - // Adjustment may not be necessary - if ( box === ( isBorderBox ? "border" : "content" ) ) { - return 0; - } - - for ( ; i < 4; i += 2 ) { - - // Both box models exclude margin - if ( box === "margin" ) { - delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); - } - - // If we get here with a content-box, we're seeking "padding" or "border" or "margin" - if ( !isBorderBox ) { - - // Add padding - delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - - // For "border" or "margin", add border - if ( box !== "padding" ) { - delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - - // But still keep track of it otherwise - } else { - extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - - // If we get here with a border-box (content + padding + border), we're seeking "content" or - // "padding" or "margin" - } else { - - // For "content", subtract padding - if ( box === "content" ) { - delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); - } - - // For "content" or "padding", subtract border - if ( box !== "margin" ) { - delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); - } - } - } - - // Account for positive content-box scroll gutter when requested by providing computedVal - if ( !isBorderBox && computedVal >= 0 ) { - - // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border - // Assuming integer scroll gutter, subtract the rest and round down - delta += Math.max( 0, Math.ceil( - elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - - computedVal - - delta - - extra - - 0.5 - - // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter - // Use an explicit zero to avoid NaN (gh-3964) - ) ) || 0; - } - - return delta; -} - -function getWidthOrHeight( elem, dimension, extra ) { - - // Start with computed style - var styles = getStyles( elem ), - - // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). - // Fake content-box until we know it's needed to know the true value. - boxSizingNeeded = !support.boxSizingReliable() || extra, - isBorderBox = boxSizingNeeded && - jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - valueIsBorderBox = isBorderBox, - - val = curCSS( elem, dimension, styles ), - offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); - - // Support: Firefox <=54 - // Return a confounding non-pixel value or feign ignorance, as appropriate. - if ( rnumnonpx.test( val ) ) { - if ( !extra ) { - return val; - } - val = "auto"; - } - - - // Support: IE 9 - 11 only - // Use offsetWidth/offsetHeight for when box sizing is unreliable. - // In those cases, the computed value can be trusted to be border-box. - if ( ( !support.boxSizingReliable() && isBorderBox || - - // Support: IE 10 - 11+, Edge 15 - 18+ - // IE/Edge misreport `getComputedStyle` of table rows with width/height - // set in CSS while `offset*` properties report correct values. - // Interestingly, in some cases IE 9 doesn't suffer from this issue. - !support.reliableTrDimensions() && nodeName( elem, "tr" ) || - - // Fall back to offsetWidth/offsetHeight when value is "auto" - // This happens for inline elements with no explicit setting (gh-3571) - val === "auto" || - - // Support: Android <=4.1 - 4.3 only - // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) - !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && - - // Make sure the element is visible & connected - elem.getClientRects().length ) { - - isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; - - // Where available, offsetWidth/offsetHeight approximate border box dimensions. - // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the - // retrieved value as a content box dimension. - valueIsBorderBox = offsetProp in elem; - if ( valueIsBorderBox ) { - val = elem[ offsetProp ]; - } - } - - // Normalize "" and auto - val = parseFloat( val ) || 0; - - // Adjust for the element's box model - return ( val + - boxModelAdjustment( - elem, - dimension, - extra || ( isBorderBox ? "border" : "content" ), - valueIsBorderBox, - styles, - - // Provide the current computed size to request scroll gutter calculation (gh-3589) - val - ) - ) + "px"; -} - -jQuery.extend( { - - // Add in style property hooks for overriding the default - // behavior of getting and setting a style property - cssHooks: { - opacity: { - get: function( elem, computed ) { - if ( computed ) { - - // We should always get a number back from opacity - var ret = curCSS( elem, "opacity" ); - return ret === "" ? "1" : ret; - } - } - } - }, - - // Don't automatically add "px" to these possibly-unitless properties - cssNumber: { - "animationIterationCount": true, - "columnCount": true, - "fillOpacity": true, - "flexGrow": true, - "flexShrink": true, - "fontWeight": true, - "gridArea": true, - "gridColumn": true, - "gridColumnEnd": true, - "gridColumnStart": true, - "gridRow": true, - "gridRowEnd": true, - "gridRowStart": true, - "lineHeight": true, - "opacity": true, - "order": true, - "orphans": true, - "widows": true, - "zIndex": true, - "zoom": true - }, - - // Add in properties whose names you wish to fix before - // setting or getting the value - cssProps: {}, - - // Get and set the style property on a DOM Node - style: function( elem, name, value, extra ) { - - // Don't set styles on text and comment nodes - if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { - return; - } - - // Make sure that we're working with the right name - var ret, type, hooks, - origName = camelCase( name ), - isCustomProp = rcustomProp.test( name ), - style = elem.style; - - // Make sure that we're working with the right name. We don't - // want to query the value if it is a CSS custom property - // since they are user-defined. - if ( !isCustomProp ) { - name = finalPropName( origName ); - } - - // Gets hook for the prefixed version, then unprefixed version - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // Check if we're setting a value - if ( value !== undefined ) { - type = typeof value; - - // Convert "+=" or "-=" to relative numbers (#7345) - if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { - value = adjustCSS( elem, name, ret ); - - // Fixes bug #9237 - type = "number"; - } - - // Make sure that null and NaN values aren't set (#7116) - if ( value == null || value !== value ) { - return; - } - - // If a number was passed in, add the unit (except for certain CSS properties) - // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append - // "px" to a few hardcoded values. - if ( type === "number" && !isCustomProp ) { - value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); - } - - // background-* props affect original clone's values - if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { - style[ name ] = "inherit"; - } - - // If a hook was provided, use that value, otherwise just set the specified value - if ( !hooks || !( "set" in hooks ) || - ( value = hooks.set( elem, value, extra ) ) !== undefined ) { - - if ( isCustomProp ) { - style.setProperty( name, value ); - } else { - style[ name ] = value; - } - } - - } else { - - // If a hook was provided get the non-computed value from there - if ( hooks && "get" in hooks && - ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { - - return ret; - } - - // Otherwise just get the value from the style object - return style[ name ]; - } - }, - - css: function( elem, name, extra, styles ) { - var val, num, hooks, - origName = camelCase( name ), - isCustomProp = rcustomProp.test( name ); - - // Make sure that we're working with the right name. We don't - // want to modify the value if it is a CSS custom property - // since they are user-defined. - if ( !isCustomProp ) { - name = finalPropName( origName ); - } - - // Try prefixed name followed by the unprefixed name - hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; - - // If a hook was provided get the computed value from there - if ( hooks && "get" in hooks ) { - val = hooks.get( elem, true, extra ); - } - - // Otherwise, if a way to get the computed value exists, use that - if ( val === undefined ) { - val = curCSS( elem, name, styles ); - } - - // Convert "normal" to computed value - if ( val === "normal" && name in cssNormalTransform ) { - val = cssNormalTransform[ name ]; - } - - // Make numeric if forced or a qualifier was provided and val looks numeric - if ( extra === "" || extra ) { - num = parseFloat( val ); - return extra === true || isFinite( num ) ? num || 0 : val; - } - - return val; - } -} ); - -jQuery.each( [ "height", "width" ], function( _i, dimension ) { - jQuery.cssHooks[ dimension ] = { - get: function( elem, computed, extra ) { - if ( computed ) { - - // Certain elements can have dimension info if we invisibly show them - // but it must have a current display style that would benefit - return rdisplayswap.test( jQuery.css( elem, "display" ) ) && - - // Support: Safari 8+ - // Table columns in Safari have non-zero offsetWidth & zero - // getBoundingClientRect().width unless display is changed. - // Support: IE <=11 only - // Running getBoundingClientRect on a disconnected node - // in IE throws an error. - ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? - swap( elem, cssShow, function() { - return getWidthOrHeight( elem, dimension, extra ); - } ) : - getWidthOrHeight( elem, dimension, extra ); - } - }, - - set: function( elem, value, extra ) { - var matches, - styles = getStyles( elem ), - - // Only read styles.position if the test has a chance to fail - // to avoid forcing a reflow. - scrollboxSizeBuggy = !support.scrollboxSize() && - styles.position === "absolute", - - // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) - boxSizingNeeded = scrollboxSizeBuggy || extra, - isBorderBox = boxSizingNeeded && - jQuery.css( elem, "boxSizing", false, styles ) === "border-box", - subtract = extra ? - boxModelAdjustment( - elem, - dimension, - extra, - isBorderBox, - styles - ) : - 0; - - // Account for unreliable border-box dimensions by comparing offset* to computed and - // faking a content-box to get border and padding (gh-3699) - if ( isBorderBox && scrollboxSizeBuggy ) { - subtract -= Math.ceil( - elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - - parseFloat( styles[ dimension ] ) - - boxModelAdjustment( elem, dimension, "border", false, styles ) - - 0.5 - ); - } - - // Convert to pixels if value adjustment is needed - if ( subtract && ( matches = rcssNum.exec( value ) ) && - ( matches[ 3 ] || "px" ) !== "px" ) { - - elem.style[ dimension ] = value; - value = jQuery.css( elem, dimension ); - } - - return setPositiveNumber( elem, value, subtract ); - } - }; -} ); - -jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, - function( elem, computed ) { - if ( computed ) { - return ( parseFloat( curCSS( elem, "marginLeft" ) ) || - elem.getBoundingClientRect().left - - swap( elem, { marginLeft: 0 }, function() { - return elem.getBoundingClientRect().left; - } ) - ) + "px"; - } - } -); - -// These hooks are used by animate to expand properties -jQuery.each( { - margin: "", - padding: "", - border: "Width" -}, function( prefix, suffix ) { - jQuery.cssHooks[ prefix + suffix ] = { - expand: function( value ) { - var i = 0, - expanded = {}, - - // Assumes a single number if not a string - parts = typeof value === "string" ? value.split( " " ) : [ value ]; - - for ( ; i < 4; i++ ) { - expanded[ prefix + cssExpand[ i ] + suffix ] = - parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; - } - - return expanded; - } - }; - - if ( prefix !== "margin" ) { - jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; - } -} ); - -jQuery.fn.extend( { - css: function( name, value ) { - return access( this, function( elem, name, value ) { - var styles, len, - map = {}, - i = 0; - - if ( Array.isArray( name ) ) { - styles = getStyles( elem ); - len = name.length; - - for ( ; i < len; i++ ) { - map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); - } - - return map; - } - - return value !== undefined ? - jQuery.style( elem, name, value ) : - jQuery.css( elem, name ); - }, name, value, arguments.length > 1 ); - } -} ); - - -function Tween( elem, options, prop, end, easing ) { - return new Tween.prototype.init( elem, options, prop, end, easing ); -} -jQuery.Tween = Tween; - -Tween.prototype = { - constructor: Tween, - init: function( elem, options, prop, end, easing, unit ) { - this.elem = elem; - this.prop = prop; - this.easing = easing || jQuery.easing._default; - this.options = options; - this.start = this.now = this.cur(); - this.end = end; - this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); - }, - cur: function() { - var hooks = Tween.propHooks[ this.prop ]; - - return hooks && hooks.get ? - hooks.get( this ) : - Tween.propHooks._default.get( this ); - }, - run: function( percent ) { - var eased, - hooks = Tween.propHooks[ this.prop ]; - - if ( this.options.duration ) { - this.pos = eased = jQuery.easing[ this.easing ]( - percent, this.options.duration * percent, 0, 1, this.options.duration - ); - } else { - this.pos = eased = percent; - } - this.now = ( this.end - this.start ) * eased + this.start; - - if ( this.options.step ) { - this.options.step.call( this.elem, this.now, this ); - } - - if ( hooks && hooks.set ) { - hooks.set( this ); - } else { - Tween.propHooks._default.set( this ); - } - return this; - } -}; - -Tween.prototype.init.prototype = Tween.prototype; - -Tween.propHooks = { - _default: { - get: function( tween ) { - var result; - - // Use a property on the element directly when it is not a DOM element, - // or when there is no matching style property that exists. - if ( tween.elem.nodeType !== 1 || - tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { - return tween.elem[ tween.prop ]; - } - - // Passing an empty string as a 3rd parameter to .css will automatically - // attempt a parseFloat and fallback to a string if the parse fails. - // Simple values such as "10px" are parsed to Float; - // complex values such as "rotate(1rad)" are returned as-is. - result = jQuery.css( tween.elem, tween.prop, "" ); - - // Empty strings, null, undefined and "auto" are converted to 0. - return !result || result === "auto" ? 0 : result; - }, - set: function( tween ) { - - // Use step hook for back compat. - // Use cssHook if its there. - // Use .style if available and use plain properties where available. - if ( jQuery.fx.step[ tween.prop ] ) { - jQuery.fx.step[ tween.prop ]( tween ); - } else if ( tween.elem.nodeType === 1 && ( - jQuery.cssHooks[ tween.prop ] || - tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { - jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); - } else { - tween.elem[ tween.prop ] = tween.now; - } - } - } -}; - -// Support: IE <=9 only -// Panic based approach to setting things on disconnected nodes -Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { - set: function( tween ) { - if ( tween.elem.nodeType && tween.elem.parentNode ) { - tween.elem[ tween.prop ] = tween.now; - } - } -}; - -jQuery.easing = { - linear: function( p ) { - return p; - }, - swing: function( p ) { - return 0.5 - Math.cos( p * Math.PI ) / 2; - }, - _default: "swing" -}; - -jQuery.fx = Tween.prototype.init; - -// Back compat <1.8 extension point -jQuery.fx.step = {}; - - - - -var - fxNow, inProgress, - rfxtypes = /^(?:toggle|show|hide)$/, - rrun = /queueHooks$/; - -function schedule() { - if ( inProgress ) { - if ( document.hidden === false && window.requestAnimationFrame ) { - window.requestAnimationFrame( schedule ); - } else { - window.setTimeout( schedule, jQuery.fx.interval ); - } - - jQuery.fx.tick(); - } -} - -// Animations created synchronously will run synchronously -function createFxNow() { - window.setTimeout( function() { - fxNow = undefined; - } ); - return ( fxNow = Date.now() ); -} - -// Generate parameters to create a standard animation -function genFx( type, includeWidth ) { - var which, - i = 0, - attrs = { height: type }; - - // If we include width, step value is 1 to do all cssExpand values, - // otherwise step value is 2 to skip over Left and Right - includeWidth = includeWidth ? 1 : 0; - for ( ; i < 4; i += 2 - includeWidth ) { - which = cssExpand[ i ]; - attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; - } - - if ( includeWidth ) { - attrs.opacity = attrs.width = type; - } - - return attrs; -} - -function createTween( value, prop, animation ) { - var tween, - collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), - index = 0, - length = collection.length; - for ( ; index < length; index++ ) { - if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { - - // We're done with this property - return tween; - } - } -} - -function defaultPrefilter( elem, props, opts ) { - var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, - isBox = "width" in props || "height" in props, - anim = this, - orig = {}, - style = elem.style, - hidden = elem.nodeType && isHiddenWithinTree( elem ), - dataShow = dataPriv.get( elem, "fxshow" ); - - // Queue-skipping animations hijack the fx hooks - if ( !opts.queue ) { - hooks = jQuery._queueHooks( elem, "fx" ); - if ( hooks.unqueued == null ) { - hooks.unqueued = 0; - oldfire = hooks.empty.fire; - hooks.empty.fire = function() { - if ( !hooks.unqueued ) { - oldfire(); - } - }; - } - hooks.unqueued++; - - anim.always( function() { - - // Ensure the complete handler is called before this completes - anim.always( function() { - hooks.unqueued--; - if ( !jQuery.queue( elem, "fx" ).length ) { - hooks.empty.fire(); - } - } ); - } ); - } - - // Detect show/hide animations - for ( prop in props ) { - value = props[ prop ]; - if ( rfxtypes.test( value ) ) { - delete props[ prop ]; - toggle = toggle || value === "toggle"; - if ( value === ( hidden ? "hide" : "show" ) ) { - - // Pretend to be hidden if this is a "show" and - // there is still data from a stopped show/hide - if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { - hidden = true; - - // Ignore all other no-op show/hide data - } else { - continue; - } - } - orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); - } - } - - // Bail out if this is a no-op like .hide().hide() - propTween = !jQuery.isEmptyObject( props ); - if ( !propTween && jQuery.isEmptyObject( orig ) ) { - return; - } - - // Restrict "overflow" and "display" styles during box animations - if ( isBox && elem.nodeType === 1 ) { - - // Support: IE <=9 - 11, Edge 12 - 15 - // Record all 3 overflow attributes because IE does not infer the shorthand - // from identically-valued overflowX and overflowY and Edge just mirrors - // the overflowX value there. - opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; - - // Identify a display type, preferring old show/hide data over the CSS cascade - restoreDisplay = dataShow && dataShow.display; - if ( restoreDisplay == null ) { - restoreDisplay = dataPriv.get( elem, "display" ); - } - display = jQuery.css( elem, "display" ); - if ( display === "none" ) { - if ( restoreDisplay ) { - display = restoreDisplay; - } else { - - // Get nonempty value(s) by temporarily forcing visibility - showHide( [ elem ], true ); - restoreDisplay = elem.style.display || restoreDisplay; - display = jQuery.css( elem, "display" ); - showHide( [ elem ] ); - } - } - - // Animate inline elements as inline-block - if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { - if ( jQuery.css( elem, "float" ) === "none" ) { - - // Restore the original display value at the end of pure show/hide animations - if ( !propTween ) { - anim.done( function() { - style.display = restoreDisplay; - } ); - if ( restoreDisplay == null ) { - display = style.display; - restoreDisplay = display === "none" ? "" : display; - } - } - style.display = "inline-block"; - } - } - } - - if ( opts.overflow ) { - style.overflow = "hidden"; - anim.always( function() { - style.overflow = opts.overflow[ 0 ]; - style.overflowX = opts.overflow[ 1 ]; - style.overflowY = opts.overflow[ 2 ]; - } ); - } - - // Implement show/hide animations - propTween = false; - for ( prop in orig ) { - - // General show/hide setup for this element animation - if ( !propTween ) { - if ( dataShow ) { - if ( "hidden" in dataShow ) { - hidden = dataShow.hidden; - } - } else { - dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); - } - - // Store hidden/visible for toggle so `.stop().toggle()` "reverses" - if ( toggle ) { - dataShow.hidden = !hidden; - } - - // Show elements before animating them - if ( hidden ) { - showHide( [ elem ], true ); - } - - /* eslint-disable no-loop-func */ - - anim.done( function() { - - /* eslint-enable no-loop-func */ - - // The final step of a "hide" animation is actually hiding the element - if ( !hidden ) { - showHide( [ elem ] ); - } - dataPriv.remove( elem, "fxshow" ); - for ( prop in orig ) { - jQuery.style( elem, prop, orig[ prop ] ); - } - } ); - } - - // Per-property setup - propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); - if ( !( prop in dataShow ) ) { - dataShow[ prop ] = propTween.start; - if ( hidden ) { - propTween.end = propTween.start; - propTween.start = 0; - } - } - } -} - -function propFilter( props, specialEasing ) { - var index, name, easing, value, hooks; - - // camelCase, specialEasing and expand cssHook pass - for ( index in props ) { - name = camelCase( index ); - easing = specialEasing[ name ]; - value = props[ index ]; - if ( Array.isArray( value ) ) { - easing = value[ 1 ]; - value = props[ index ] = value[ 0 ]; - } - - if ( index !== name ) { - props[ name ] = value; - delete props[ index ]; - } - - hooks = jQuery.cssHooks[ name ]; - if ( hooks && "expand" in hooks ) { - value = hooks.expand( value ); - delete props[ name ]; - - // Not quite $.extend, this won't overwrite existing keys. - // Reusing 'index' because we have the correct "name" - for ( index in value ) { - if ( !( index in props ) ) { - props[ index ] = value[ index ]; - specialEasing[ index ] = easing; - } - } - } else { - specialEasing[ name ] = easing; - } - } -} - -function Animation( elem, properties, options ) { - var result, - stopped, - index = 0, - length = Animation.prefilters.length, - deferred = jQuery.Deferred().always( function() { - - // Don't match elem in the :animated selector - delete tick.elem; - } ), - tick = function() { - if ( stopped ) { - return false; - } - var currentTime = fxNow || createFxNow(), - remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), - - // Support: Android 2.3 only - // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) - temp = remaining / animation.duration || 0, - percent = 1 - temp, - index = 0, - length = animation.tweens.length; - - for ( ; index < length; index++ ) { - animation.tweens[ index ].run( percent ); - } - - deferred.notifyWith( elem, [ animation, percent, remaining ] ); - - // If there's more to do, yield - if ( percent < 1 && length ) { - return remaining; - } - - // If this was an empty animation, synthesize a final progress notification - if ( !length ) { - deferred.notifyWith( elem, [ animation, 1, 0 ] ); - } - - // Resolve the animation and report its conclusion - deferred.resolveWith( elem, [ animation ] ); - return false; - }, - animation = deferred.promise( { - elem: elem, - props: jQuery.extend( {}, properties ), - opts: jQuery.extend( true, { - specialEasing: {}, - easing: jQuery.easing._default - }, options ), - originalProperties: properties, - originalOptions: options, - startTime: fxNow || createFxNow(), - duration: options.duration, - tweens: [], - createTween: function( prop, end ) { - var tween = jQuery.Tween( elem, animation.opts, prop, end, - animation.opts.specialEasing[ prop ] || animation.opts.easing ); - animation.tweens.push( tween ); - return tween; - }, - stop: function( gotoEnd ) { - var index = 0, - - // If we are going to the end, we want to run all the tweens - // otherwise we skip this part - length = gotoEnd ? animation.tweens.length : 0; - if ( stopped ) { - return this; - } - stopped = true; - for ( ; index < length; index++ ) { - animation.tweens[ index ].run( 1 ); - } - - // Resolve when we played the last frame; otherwise, reject - if ( gotoEnd ) { - deferred.notifyWith( elem, [ animation, 1, 0 ] ); - deferred.resolveWith( elem, [ animation, gotoEnd ] ); - } else { - deferred.rejectWith( elem, [ animation, gotoEnd ] ); - } - return this; - } - } ), - props = animation.props; - - propFilter( props, animation.opts.specialEasing ); - - for ( ; index < length; index++ ) { - result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); - if ( result ) { - if ( isFunction( result.stop ) ) { - jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = - result.stop.bind( result ); - } - return result; - } - } - - jQuery.map( props, createTween, animation ); - - if ( isFunction( animation.opts.start ) ) { - animation.opts.start.call( elem, animation ); - } - - // Attach callbacks from options - animation - .progress( animation.opts.progress ) - .done( animation.opts.done, animation.opts.complete ) - .fail( animation.opts.fail ) - .always( animation.opts.always ); - - jQuery.fx.timer( - jQuery.extend( tick, { - elem: elem, - anim: animation, - queue: animation.opts.queue - } ) - ); - - return animation; -} - -jQuery.Animation = jQuery.extend( Animation, { - - tweeners: { - "*": [ function( prop, value ) { - var tween = this.createTween( prop, value ); - adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); - return tween; - } ] - }, - - tweener: function( props, callback ) { - if ( isFunction( props ) ) { - callback = props; - props = [ "*" ]; - } else { - props = props.match( rnothtmlwhite ); - } - - var prop, - index = 0, - length = props.length; - - for ( ; index < length; index++ ) { - prop = props[ index ]; - Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; - Animation.tweeners[ prop ].unshift( callback ); - } - }, - - prefilters: [ defaultPrefilter ], - - prefilter: function( callback, prepend ) { - if ( prepend ) { - Animation.prefilters.unshift( callback ); - } else { - Animation.prefilters.push( callback ); - } - } -} ); - -jQuery.speed = function( speed, easing, fn ) { - var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { - complete: fn || !fn && easing || - isFunction( speed ) && speed, - duration: speed, - easing: fn && easing || easing && !isFunction( easing ) && easing - }; - - // Go to the end state if fx are off - if ( jQuery.fx.off ) { - opt.duration = 0; - - } else { - if ( typeof opt.duration !== "number" ) { - if ( opt.duration in jQuery.fx.speeds ) { - opt.duration = jQuery.fx.speeds[ opt.duration ]; - - } else { - opt.duration = jQuery.fx.speeds._default; - } - } - } - - // Normalize opt.queue - true/undefined/null -> "fx" - if ( opt.queue == null || opt.queue === true ) { - opt.queue = "fx"; - } - - // Queueing - opt.old = opt.complete; - - opt.complete = function() { - if ( isFunction( opt.old ) ) { - opt.old.call( this ); - } - - if ( opt.queue ) { - jQuery.dequeue( this, opt.queue ); - } - }; - - return opt; -}; - -jQuery.fn.extend( { - fadeTo: function( speed, to, easing, callback ) { - - // Show any hidden elements after setting opacity to 0 - return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() - - // Animate to the value specified - .end().animate( { opacity: to }, speed, easing, callback ); - }, - animate: function( prop, speed, easing, callback ) { - var empty = jQuery.isEmptyObject( prop ), - optall = jQuery.speed( speed, easing, callback ), - doAnimation = function() { - - // Operate on a copy of prop so per-property easing won't be lost - var anim = Animation( this, jQuery.extend( {}, prop ), optall ); - - // Empty animations, or finishing resolves immediately - if ( empty || dataPriv.get( this, "finish" ) ) { - anim.stop( true ); - } - }; - - doAnimation.finish = doAnimation; - - return empty || optall.queue === false ? - this.each( doAnimation ) : - this.queue( optall.queue, doAnimation ); - }, - stop: function( type, clearQueue, gotoEnd ) { - var stopQueue = function( hooks ) { - var stop = hooks.stop; - delete hooks.stop; - stop( gotoEnd ); - }; - - if ( typeof type !== "string" ) { - gotoEnd = clearQueue; - clearQueue = type; - type = undefined; - } - if ( clearQueue ) { - this.queue( type || "fx", [] ); - } - - return this.each( function() { - var dequeue = true, - index = type != null && type + "queueHooks", - timers = jQuery.timers, - data = dataPriv.get( this ); - - if ( index ) { - if ( data[ index ] && data[ index ].stop ) { - stopQueue( data[ index ] ); - } - } else { - for ( index in data ) { - if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { - stopQueue( data[ index ] ); - } - } - } - - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && - ( type == null || timers[ index ].queue === type ) ) { - - timers[ index ].anim.stop( gotoEnd ); - dequeue = false; - timers.splice( index, 1 ); - } - } - - // Start the next in the queue if the last step wasn't forced. - // Timers currently will call their complete callbacks, which - // will dequeue but only if they were gotoEnd. - if ( dequeue || !gotoEnd ) { - jQuery.dequeue( this, type ); - } - } ); - }, - finish: function( type ) { - if ( type !== false ) { - type = type || "fx"; - } - return this.each( function() { - var index, - data = dataPriv.get( this ), - queue = data[ type + "queue" ], - hooks = data[ type + "queueHooks" ], - timers = jQuery.timers, - length = queue ? queue.length : 0; - - // Enable finishing flag on private data - data.finish = true; - - // Empty the queue first - jQuery.queue( this, type, [] ); - - if ( hooks && hooks.stop ) { - hooks.stop.call( this, true ); - } - - // Look for any active animations, and finish them - for ( index = timers.length; index--; ) { - if ( timers[ index ].elem === this && timers[ index ].queue === type ) { - timers[ index ].anim.stop( true ); - timers.splice( index, 1 ); - } - } - - // Look for any animations in the old queue and finish them - for ( index = 0; index < length; index++ ) { - if ( queue[ index ] && queue[ index ].finish ) { - queue[ index ].finish.call( this ); - } - } - - // Turn off finishing flag - delete data.finish; - } ); - } -} ); - -jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { - var cssFn = jQuery.fn[ name ]; - jQuery.fn[ name ] = function( speed, easing, callback ) { - return speed == null || typeof speed === "boolean" ? - cssFn.apply( this, arguments ) : - this.animate( genFx( name, true ), speed, easing, callback ); - }; -} ); - -// Generate shortcuts for custom animations -jQuery.each( { - slideDown: genFx( "show" ), - slideUp: genFx( "hide" ), - slideToggle: genFx( "toggle" ), - fadeIn: { opacity: "show" }, - fadeOut: { opacity: "hide" }, - fadeToggle: { opacity: "toggle" } -}, function( name, props ) { - jQuery.fn[ name ] = function( speed, easing, callback ) { - return this.animate( props, speed, easing, callback ); - }; -} ); - -jQuery.timers = []; -jQuery.fx.tick = function() { - var timer, - i = 0, - timers = jQuery.timers; - - fxNow = Date.now(); - - for ( ; i < timers.length; i++ ) { - timer = timers[ i ]; - - // Run the timer and safely remove it when done (allowing for external removal) - if ( !timer() && timers[ i ] === timer ) { - timers.splice( i--, 1 ); - } - } - - if ( !timers.length ) { - jQuery.fx.stop(); - } - fxNow = undefined; -}; - -jQuery.fx.timer = function( timer ) { - jQuery.timers.push( timer ); - jQuery.fx.start(); -}; - -jQuery.fx.interval = 13; -jQuery.fx.start = function() { - if ( inProgress ) { - return; - } - - inProgress = true; - schedule(); -}; - -jQuery.fx.stop = function() { - inProgress = null; -}; - -jQuery.fx.speeds = { - slow: 600, - fast: 200, - - // Default speed - _default: 400 -}; - - -// Based off of the plugin by Clint Helfers, with permission. -// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ -jQuery.fn.delay = function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = window.setTimeout( next, time ); - hooks.stop = function() { - window.clearTimeout( timeout ); - }; - } ); -}; - - -( function() { - var input = document.createElement( "input" ), - select = document.createElement( "select" ), - opt = select.appendChild( document.createElement( "option" ) ); - - input.type = "checkbox"; - - // Support: Android <=4.3 only - // Default value for a checkbox should be "on" - support.checkOn = input.value !== ""; - - // Support: IE <=11 only - // Must access selectedIndex to make default options select - support.optSelected = opt.selected; - - // Support: IE <=11 only - // An input loses its value after becoming a radio - input = document.createElement( "input" ); - input.value = "t"; - input.type = "radio"; - support.radioValue = input.value === "t"; -} )(); - - -var boolHook, - attrHandle = jQuery.expr.attrHandle; - -jQuery.fn.extend( { - attr: function( name, value ) { - return access( this, jQuery.attr, name, value, arguments.length > 1 ); - }, - - removeAttr: function( name ) { - return this.each( function() { - jQuery.removeAttr( this, name ); - } ); - } -} ); - -jQuery.extend( { - attr: function( elem, name, value ) { - var ret, hooks, - nType = elem.nodeType; - - // Don't get/set attributes on text, comment and attribute nodes - if ( nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === "undefined" ) { - return jQuery.prop( elem, name, value ); - } - - // Attribute hooks are determined by the lowercase version - // Grab necessary hook if one is defined - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - hooks = jQuery.attrHooks[ name.toLowerCase() ] || - ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); - } - - if ( value !== undefined ) { - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return; - } - - if ( hooks && "set" in hooks && - ( ret = hooks.set( elem, value, name ) ) !== undefined ) { - return ret; - } - - elem.setAttribute( name, value + "" ); - return value; - } - - if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { - return ret; - } - - ret = jQuery.find.attr( elem, name ); - - // Non-existent attributes return null, we normalize to undefined - return ret == null ? undefined : ret; - }, - - attrHooks: { - type: { - set: function( elem, value ) { - if ( !support.radioValue && value === "radio" && - nodeName( elem, "input" ) ) { - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - } - }, - - removeAttr: function( elem, value ) { - var name, - i = 0, - - // Attribute names can contain non-HTML whitespace characters - // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 - attrNames = value && value.match( rnothtmlwhite ); - - if ( attrNames && elem.nodeType === 1 ) { - while ( ( name = attrNames[ i++ ] ) ) { - elem.removeAttribute( name ); - } - } - } -} ); - -// Hooks for boolean attributes -boolHook = { - set: function( elem, value, name ) { - if ( value === false ) { - - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - elem.setAttribute( name, name ); - } - return name; - } -}; - -jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { - var getter = attrHandle[ name ] || jQuery.find.attr; - - attrHandle[ name ] = function( elem, name, isXML ) { - var ret, handle, - lowercaseName = name.toLowerCase(); - - if ( !isXML ) { - - // Avoid an infinite loop by temporarily removing this function from the getter - handle = attrHandle[ lowercaseName ]; - attrHandle[ lowercaseName ] = ret; - ret = getter( elem, name, isXML ) != null ? - lowercaseName : - null; - attrHandle[ lowercaseName ] = handle; - } - return ret; - }; -} ); - - - - -var rfocusable = /^(?:input|select|textarea|button)$/i, - rclickable = /^(?:a|area)$/i; - -jQuery.fn.extend( { - prop: function( name, value ) { - return access( this, jQuery.prop, name, value, arguments.length > 1 ); - }, - - removeProp: function( name ) { - return this.each( function() { - delete this[ jQuery.propFix[ name ] || name ]; - } ); - } -} ); - -jQuery.extend( { - prop: function( elem, name, value ) { - var ret, hooks, - nType = elem.nodeType; - - // Don't get/set properties on text, comment and attribute nodes - if ( nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { - - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && - ( ret = hooks.set( elem, value, name ) ) !== undefined ) { - return ret; - } - - return ( elem[ name ] = value ); - } - - if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { - return ret; - } - - return elem[ name ]; - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - - // Support: IE <=9 - 11 only - // elem.tabIndex doesn't always return the - // correct value when it hasn't been explicitly set - // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - // Use proper attribute retrieval(#12072) - var tabindex = jQuery.find.attr( elem, "tabindex" ); - - if ( tabindex ) { - return parseInt( tabindex, 10 ); - } - - if ( - rfocusable.test( elem.nodeName ) || - rclickable.test( elem.nodeName ) && - elem.href - ) { - return 0; - } - - return -1; - } - } - }, - - propFix: { - "for": "htmlFor", - "class": "className" - } -} ); - -// Support: IE <=11 only -// Accessing the selectedIndex property -// forces the browser to respect setting selected -// on the option -// The getter ensures a default option is selected -// when in an optgroup -// eslint rule "no-unused-expressions" is disabled for this code -// since it considers such accessions noop -if ( !support.optSelected ) { - jQuery.propHooks.selected = { - get: function( elem ) { - - /* eslint no-unused-expressions: "off" */ - - var parent = elem.parentNode; - if ( parent && parent.parentNode ) { - parent.parentNode.selectedIndex; - } - return null; - }, - set: function( elem ) { - - /* eslint no-unused-expressions: "off" */ - - var parent = elem.parentNode; - if ( parent ) { - parent.selectedIndex; - - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - } - }; -} - -jQuery.each( [ - "tabIndex", - "readOnly", - "maxLength", - "cellSpacing", - "cellPadding", - "rowSpan", - "colSpan", - "useMap", - "frameBorder", - "contentEditable" -], function() { - jQuery.propFix[ this.toLowerCase() ] = this; -} ); - - - - - // Strip and collapse whitespace according to HTML spec - // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace - function stripAndCollapse( value ) { - var tokens = value.match( rnothtmlwhite ) || []; - return tokens.join( " " ); - } - - -function getClass( elem ) { - return elem.getAttribute && elem.getAttribute( "class" ) || ""; -} - -function classesToArray( value ) { - if ( Array.isArray( value ) ) { - return value; - } - if ( typeof value === "string" ) { - return value.match( rnothtmlwhite ) || []; - } - return []; -} - -jQuery.fn.extend( { - addClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; - - if ( isFunction( value ) ) { - return this.each( function( j ) { - jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); - } ); - } - - classes = classesToArray( value ); - - if ( classes.length ) { - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); - - if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - if ( cur.indexOf( " " + clazz + " " ) < 0 ) { - cur += clazz + " "; - } - } - - // Only assign if different to avoid unneeded rendering. - finalValue = stripAndCollapse( cur ); - if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classes, elem, cur, curValue, clazz, j, finalValue, - i = 0; - - if ( isFunction( value ) ) { - return this.each( function( j ) { - jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); - } ); - } - - if ( !arguments.length ) { - return this.attr( "class", "" ); - } - - classes = classesToArray( value ); - - if ( classes.length ) { - while ( ( elem = this[ i++ ] ) ) { - curValue = getClass( elem ); - - // This expression is here for better compressibility (see addClass) - cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); - - if ( cur ) { - j = 0; - while ( ( clazz = classes[ j++ ] ) ) { - - // Remove *all* instances - while ( cur.indexOf( " " + clazz + " " ) > -1 ) { - cur = cur.replace( " " + clazz + " ", " " ); - } - } - - // Only assign if different to avoid unneeded rendering. - finalValue = stripAndCollapse( cur ); - if ( curValue !== finalValue ) { - elem.setAttribute( "class", finalValue ); - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isValidValue = type === "string" || Array.isArray( value ); - - if ( typeof stateVal === "boolean" && isValidValue ) { - return stateVal ? this.addClass( value ) : this.removeClass( value ); - } - - if ( isFunction( value ) ) { - return this.each( function( i ) { - jQuery( this ).toggleClass( - value.call( this, i, getClass( this ), stateVal ), - stateVal - ); - } ); - } - - return this.each( function() { - var className, i, self, classNames; - - if ( isValidValue ) { - - // Toggle individual class names - i = 0; - self = jQuery( this ); - classNames = classesToArray( value ); - - while ( ( className = classNames[ i++ ] ) ) { - - // Check each className given, space separated list - if ( self.hasClass( className ) ) { - self.removeClass( className ); - } else { - self.addClass( className ); - } - } - - // Toggle whole class name - } else if ( value === undefined || type === "boolean" ) { - className = getClass( this ); - if ( className ) { - - // Store className if set - dataPriv.set( this, "__className__", className ); - } - - // If the element has a class name or if we're passed `false`, - // then remove the whole classname (if there was one, the above saved it). - // Otherwise bring back whatever was previously saved (if anything), - // falling back to the empty string if nothing was stored. - if ( this.setAttribute ) { - this.setAttribute( "class", - className || value === false ? - "" : - dataPriv.get( this, "__className__" ) || "" - ); - } - } - } ); - }, - - hasClass: function( selector ) { - var className, elem, - i = 0; - - className = " " + selector + " "; - while ( ( elem = this[ i++ ] ) ) { - if ( elem.nodeType === 1 && - ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { - return true; - } - } - - return false; - } -} ); - - - - -var rreturn = /\r/g; - -jQuery.fn.extend( { - val: function( value ) { - var hooks, ret, valueIsFunction, - elem = this[ 0 ]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.type ] || - jQuery.valHooks[ elem.nodeName.toLowerCase() ]; - - if ( hooks && - "get" in hooks && - ( ret = hooks.get( elem, "value" ) ) !== undefined - ) { - return ret; - } - - ret = elem.value; - - // Handle most common string cases - if ( typeof ret === "string" ) { - return ret.replace( rreturn, "" ); - } - - // Handle cases where value is null/undef or number - return ret == null ? "" : ret; - } - - return; - } - - valueIsFunction = isFunction( value ); - - return this.each( function( i ) { - var val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( valueIsFunction ) { - val = value.call( this, i, jQuery( this ).val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - - } else if ( typeof val === "number" ) { - val += ""; - - } else if ( Array.isArray( val ) ) { - val = jQuery.map( val, function( value ) { - return value == null ? "" : value + ""; - } ); - } - - hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - } ); - } -} ); - -jQuery.extend( { - valHooks: { - option: { - get: function( elem ) { - - var val = jQuery.find.attr( elem, "value" ); - return val != null ? - val : - - // Support: IE <=10 - 11 only - // option.text throws exceptions (#14686, #14858) - // Strip and collapse whitespace - // https://html.spec.whatwg.org/#strip-and-collapse-whitespace - stripAndCollapse( jQuery.text( elem ) ); - } - }, - select: { - get: function( elem ) { - var value, option, i, - options = elem.options, - index = elem.selectedIndex, - one = elem.type === "select-one", - values = one ? null : [], - max = one ? index + 1 : options.length; - - if ( index < 0 ) { - i = max; - - } else { - i = one ? index : 0; - } - - // Loop through all the selected options - for ( ; i < max; i++ ) { - option = options[ i ]; - - // Support: IE <=9 only - // IE8-9 doesn't update selected after form reset (#2551) - if ( ( option.selected || i === index ) && - - // Don't return options that are disabled or in a disabled optgroup - !option.disabled && - ( !option.parentNode.disabled || - !nodeName( option.parentNode, "optgroup" ) ) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - return values; - }, - - set: function( elem, value ) { - var optionSet, option, - options = elem.options, - values = jQuery.makeArray( value ), - i = options.length; - - while ( i-- ) { - option = options[ i ]; - - /* eslint-disable no-cond-assign */ - - if ( option.selected = - jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 - ) { - optionSet = true; - } - - /* eslint-enable no-cond-assign */ - } - - // Force browsers to behave consistently when non-matching value is set - if ( !optionSet ) { - elem.selectedIndex = -1; - } - return values; - } - } - } -} ); - -// Radios and checkboxes getter/setter -jQuery.each( [ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - set: function( elem, value ) { - if ( Array.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); - } - } - }; - if ( !support.checkOn ) { - jQuery.valHooks[ this ].get = function( elem ) { - return elem.getAttribute( "value" ) === null ? "on" : elem.value; - }; - } -} ); - - - - -// Return jQuery for attributes-only inclusion - - -support.focusin = "onfocusin" in window; - - -var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - stopPropagationCallback = function( e ) { - e.stopPropagation(); - }; - -jQuery.extend( jQuery.event, { - - trigger: function( event, data, elem, onlyHandlers ) { - - var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, - eventPath = [ elem || document ], - type = hasOwn.call( event, "type" ) ? event.type : event, - namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; - - cur = lastElement = tmp = elem = elem || document; - - // Don't do events on text and comment nodes - if ( elem.nodeType === 3 || elem.nodeType === 8 ) { - return; - } - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf( "." ) > -1 ) { - - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split( "." ); - type = namespaces.shift(); - namespaces.sort(); - } - ontype = type.indexOf( ":" ) < 0 && "on" + type; - - // Caller can pass in a jQuery.Event object, Object, or just an event type string - event = event[ jQuery.expando ] ? - event : - new jQuery.Event( type, typeof event === "object" && event ); - - // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) - event.isTrigger = onlyHandlers ? 2 : 3; - event.namespace = namespaces.join( "." ); - event.rnamespace = event.namespace ? - new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : - null; - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data == null ? - [ event ] : - jQuery.makeArray( data, [ event ] ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - if ( !rfocusMorph.test( bubbleType + type ) ) { - cur = cur.parentNode; - } - for ( ; cur; cur = cur.parentNode ) { - eventPath.push( cur ); - tmp = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( tmp === ( elem.ownerDocument || document ) ) { - eventPath.push( tmp.defaultView || tmp.parentWindow || window ); - } - } - - // Fire handlers on the event path - i = 0; - while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { - lastElement = cur; - event.type = i > 1 ? - bubbleType : - special.bindType || type; - - // jQuery handler - handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] && - dataPriv.get( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - - // Native handler - handle = ontype && cur[ ontype ]; - if ( handle && handle.apply && acceptData( cur ) ) { - event.result = handle.apply( cur, data ); - if ( event.result === false ) { - event.preventDefault(); - } - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( ( !special._default || - special._default.apply( eventPath.pop(), data ) === false ) && - acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name as the event. - // Don't do default actions on window, that's where global variables be (#6170) - if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - tmp = elem[ ontype ]; - - if ( tmp ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - - if ( event.isPropagationStopped() ) { - lastElement.addEventListener( type, stopPropagationCallback ); - } - - elem[ type ](); - - if ( event.isPropagationStopped() ) { - lastElement.removeEventListener( type, stopPropagationCallback ); - } - - jQuery.event.triggered = undefined; - - if ( tmp ) { - elem[ ontype ] = tmp; - } - } - } - } - - return event.result; - }, - - // Piggyback on a donor event to simulate a different one - // Used only for `focus(in | out)` events - simulate: function( type, elem, event ) { - var e = jQuery.extend( - new jQuery.Event(), - event, - { - type: type, - isSimulated: true - } - ); - - jQuery.event.trigger( e, null, elem ); - } - -} ); - -jQuery.fn.extend( { - - trigger: function( type, data ) { - return this.each( function() { - jQuery.event.trigger( type, data, this ); - } ); - }, - triggerHandler: function( type, data ) { - var elem = this[ 0 ]; - if ( elem ) { - return jQuery.event.trigger( type, data, elem, true ); - } - } -} ); - - -// Support: Firefox <=44 -// Firefox doesn't have focus(in | out) events -// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 -// -// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 -// focus(in | out) events fire after focus & blur events, -// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order -// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 -if ( !support.focusin ) { - jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler on the document while someone wants focusin/focusout - var handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - - // Handle: regular nodes (via `this.ownerDocument`), window - // (via `this.document`) & document (via `this`). - var doc = this.ownerDocument || this.document || this, - attaches = dataPriv.access( doc, fix ); - - if ( !attaches ) { - doc.addEventListener( orig, handler, true ); - } - dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); - }, - teardown: function() { - var doc = this.ownerDocument || this.document || this, - attaches = dataPriv.access( doc, fix ) - 1; - - if ( !attaches ) { - doc.removeEventListener( orig, handler, true ); - dataPriv.remove( doc, fix ); - - } else { - dataPriv.access( doc, fix, attaches ); - } - } - }; - } ); -} -var location = window.location; - -var nonce = { guid: Date.now() }; - -var rquery = ( /\?/ ); - - - -// Cross-browser xml parsing -jQuery.parseXML = function( data ) { - var xml, parserErrorElem; - if ( !data || typeof data !== "string" ) { - return null; - } - - // Support: IE 9 - 11 only - // IE throws on parseFromString with invalid input. - try { - xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); - } catch ( e ) {} - - parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ]; - if ( !xml || parserErrorElem ) { - jQuery.error( "Invalid XML: " + ( - parserErrorElem ? - jQuery.map( parserErrorElem.childNodes, function( el ) { - return el.textContent; - } ).join( "\n" ) : - data - ) ); - } - return xml; -}; - - -var - rbracket = /\[\]$/, - rCRLF = /\r?\n/g, - rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, - rsubmittable = /^(?:input|select|textarea|keygen)/i; - -function buildParams( prefix, obj, traditional, add ) { - var name; - - if ( Array.isArray( obj ) ) { - - // Serialize array item. - jQuery.each( obj, function( i, v ) { - if ( traditional || rbracket.test( prefix ) ) { - - // Treat each array item as a scalar. - add( prefix, v ); - - } else { - - // Item is non-scalar (array or object), encode its numeric index. - buildParams( - prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", - v, - traditional, - add - ); - } - } ); - - } else if ( !traditional && toType( obj ) === "object" ) { - - // Serialize object item. - for ( name in obj ) { - buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); - } - - } else { - - // Serialize scalar item. - add( prefix, obj ); - } -} - -// Serialize an array of form elements or a set of -// key/values into a query string -jQuery.param = function( a, traditional ) { - var prefix, - s = [], - add = function( key, valueOrFunction ) { - - // If value is a function, invoke it and use its return value - var value = isFunction( valueOrFunction ) ? - valueOrFunction() : - valueOrFunction; - - s[ s.length ] = encodeURIComponent( key ) + "=" + - encodeURIComponent( value == null ? "" : value ); - }; - - if ( a == null ) { - return ""; - } - - // If an array was passed in, assume that it is an array of form elements. - if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { - - // Serialize the form elements - jQuery.each( a, function() { - add( this.name, this.value ); - } ); - - } else { - - // If traditional, encode the "old" way (the way 1.3.2 or older - // did it), otherwise encode params recursively. - for ( prefix in a ) { - buildParams( prefix, a[ prefix ], traditional, add ); - } - } - - // Return the resulting serialization - return s.join( "&" ); -}; - -jQuery.fn.extend( { - serialize: function() { - return jQuery.param( this.serializeArray() ); - }, - serializeArray: function() { - return this.map( function() { - - // Can add propHook for "elements" to filter or add form elements - var elements = jQuery.prop( this, "elements" ); - return elements ? jQuery.makeArray( elements ) : this; - } ).filter( function() { - var type = this.type; - - // Use .is( ":disabled" ) so that fieldset[disabled] works - return this.name && !jQuery( this ).is( ":disabled" ) && - rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && - ( this.checked || !rcheckableType.test( type ) ); - } ).map( function( _i, elem ) { - var val = jQuery( this ).val(); - - if ( val == null ) { - return null; - } - - if ( Array.isArray( val ) ) { - return jQuery.map( val, function( val ) { - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - } ); - } - - return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; - } ).get(); - } -} ); - - -var - r20 = /%20/g, - rhash = /#.*$/, - rantiCache = /([?&])_=[^&]*/, - rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, - - // #7653, #8125, #8152: local protocol detection - rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, - rnoContent = /^(?:GET|HEAD)$/, - rprotocol = /^\/\//, - - /* Prefilters - * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) - * 2) These are called: - * - BEFORE asking for a transport - * - AFTER param serialization (s.data is a string if s.processData is true) - * 3) key is the dataType - * 4) the catchall symbol "*" can be used - * 5) execution will start with transport dataType and THEN continue down to "*" if needed - */ - prefilters = {}, - - /* Transports bindings - * 1) key is the dataType - * 2) the catchall symbol "*" can be used - * 3) selection will start with transport dataType and THEN go to "*" if needed - */ - transports = {}, - - // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression - allTypes = "*/".concat( "*" ), - - // Anchor tag for parsing the document origin - originAnchor = document.createElement( "a" ); - -originAnchor.href = location.href; - -// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport -function addToPrefiltersOrTransports( structure ) { - - // dataTypeExpression is optional and defaults to "*" - return function( dataTypeExpression, func ) { - - if ( typeof dataTypeExpression !== "string" ) { - func = dataTypeExpression; - dataTypeExpression = "*"; - } - - var dataType, - i = 0, - dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; - - if ( isFunction( func ) ) { - - // For each dataType in the dataTypeExpression - while ( ( dataType = dataTypes[ i++ ] ) ) { - - // Prepend if requested - if ( dataType[ 0 ] === "+" ) { - dataType = dataType.slice( 1 ) || "*"; - ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); - - // Otherwise append - } else { - ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); - } - } - } - }; -} - -// Base inspection function for prefilters and transports -function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { - - var inspected = {}, - seekingTransport = ( structure === transports ); - - function inspect( dataType ) { - var selected; - inspected[ dataType ] = true; - jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { - var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); - if ( typeof dataTypeOrTransport === "string" && - !seekingTransport && !inspected[ dataTypeOrTransport ] ) { - - options.dataTypes.unshift( dataTypeOrTransport ); - inspect( dataTypeOrTransport ); - return false; - } else if ( seekingTransport ) { - return !( selected = dataTypeOrTransport ); - } - } ); - return selected; - } - - return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); -} - -// A special extend for ajax options -// that takes "flat" options (not to be deep extended) -// Fixes #9887 -function ajaxExtend( target, src ) { - var key, deep, - flatOptions = jQuery.ajaxSettings.flatOptions || {}; - - for ( key in src ) { - if ( src[ key ] !== undefined ) { - ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; - } - } - if ( deep ) { - jQuery.extend( true, target, deep ); - } - - return target; -} - -/* Handles responses to an ajax request: - * - finds the right dataType (mediates between content-type and expected dataType) - * - returns the corresponding response - */ -function ajaxHandleResponses( s, jqXHR, responses ) { - - var ct, type, finalDataType, firstDataType, - contents = s.contents, - dataTypes = s.dataTypes; - - // Remove auto dataType and get content-type in the process - while ( dataTypes[ 0 ] === "*" ) { - dataTypes.shift(); - if ( ct === undefined ) { - ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); - } - } - - // Check if we're dealing with a known content-type - if ( ct ) { - for ( type in contents ) { - if ( contents[ type ] && contents[ type ].test( ct ) ) { - dataTypes.unshift( type ); - break; - } - } - } - - // Check to see if we have a response for the expected dataType - if ( dataTypes[ 0 ] in responses ) { - finalDataType = dataTypes[ 0 ]; - } else { - - // Try convertible dataTypes - for ( type in responses ) { - if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { - finalDataType = type; - break; - } - if ( !firstDataType ) { - firstDataType = type; - } - } - - // Or just use first one - finalDataType = finalDataType || firstDataType; - } - - // If we found a dataType - // We add the dataType to the list if needed - // and return the corresponding response - if ( finalDataType ) { - if ( finalDataType !== dataTypes[ 0 ] ) { - dataTypes.unshift( finalDataType ); - } - return responses[ finalDataType ]; - } -} - -/* Chain conversions given the request and the original response - * Also sets the responseXXX fields on the jqXHR instance - */ -function ajaxConvert( s, response, jqXHR, isSuccess ) { - var conv2, current, conv, tmp, prev, - converters = {}, - - // Work with a copy of dataTypes in case we need to modify it for conversion - dataTypes = s.dataTypes.slice(); - - // Create converters map with lowercased keys - if ( dataTypes[ 1 ] ) { - for ( conv in s.converters ) { - converters[ conv.toLowerCase() ] = s.converters[ conv ]; - } - } - - current = dataTypes.shift(); - - // Convert to each sequential dataType - while ( current ) { - - if ( s.responseFields[ current ] ) { - jqXHR[ s.responseFields[ current ] ] = response; - } - - // Apply the dataFilter if provided - if ( !prev && isSuccess && s.dataFilter ) { - response = s.dataFilter( response, s.dataType ); - } - - prev = current; - current = dataTypes.shift(); - - if ( current ) { - - // There's only work to do if current dataType is non-auto - if ( current === "*" ) { - - current = prev; - - // Convert response if prev dataType is non-auto and differs from current - } else if ( prev !== "*" && prev !== current ) { - - // Seek a direct converter - conv = converters[ prev + " " + current ] || converters[ "* " + current ]; - - // If none found, seek a pair - if ( !conv ) { - for ( conv2 in converters ) { - - // If conv2 outputs current - tmp = conv2.split( " " ); - if ( tmp[ 1 ] === current ) { - - // If prev can be converted to accepted input - conv = converters[ prev + " " + tmp[ 0 ] ] || - converters[ "* " + tmp[ 0 ] ]; - if ( conv ) { - - // Condense equivalence converters - if ( conv === true ) { - conv = converters[ conv2 ]; - - // Otherwise, insert the intermediate dataType - } else if ( converters[ conv2 ] !== true ) { - current = tmp[ 0 ]; - dataTypes.unshift( tmp[ 1 ] ); - } - break; - } - } - } - } - - // Apply converter (if not an equivalence) - if ( conv !== true ) { - - // Unless errors are allowed to bubble, catch and return them - if ( conv && s.throws ) { - response = conv( response ); - } else { - try { - response = conv( response ); - } catch ( e ) { - return { - state: "parsererror", - error: conv ? e : "No conversion from " + prev + " to " + current - }; - } - } - } - } - } - } - - return { state: "success", data: response }; -} - -jQuery.extend( { - - // Counter for holding the number of active queries - active: 0, - - // Last-Modified header cache for next request - lastModified: {}, - etag: {}, - - ajaxSettings: { - url: location.href, - type: "GET", - isLocal: rlocalProtocol.test( location.protocol ), - global: true, - processData: true, - async: true, - contentType: "application/x-www-form-urlencoded; charset=UTF-8", - - /* - timeout: 0, - data: null, - dataType: null, - username: null, - password: null, - cache: null, - throws: false, - traditional: false, - headers: {}, - */ - - accepts: { - "*": allTypes, - text: "text/plain", - html: "text/html", - xml: "application/xml, text/xml", - json: "application/json, text/javascript" - }, - - contents: { - xml: /\bxml\b/, - html: /\bhtml/, - json: /\bjson\b/ - }, - - responseFields: { - xml: "responseXML", - text: "responseText", - json: "responseJSON" - }, - - // Data converters - // Keys separate source (or catchall "*") and destination types with a single space - converters: { - - // Convert anything to text - "* text": String, - - // Text to html (true = no transformation) - "text html": true, - - // Evaluate text as a json expression - "text json": JSON.parse, - - // Parse text as xml - "text xml": jQuery.parseXML - }, - - // For options that shouldn't be deep extended: - // you can add your own custom options here if - // and when you create one that shouldn't be - // deep extended (see ajaxExtend) - flatOptions: { - url: true, - context: true - } - }, - - // Creates a full fledged settings object into target - // with both ajaxSettings and settings fields. - // If target is omitted, writes into ajaxSettings. - ajaxSetup: function( target, settings ) { - return settings ? - - // Building a settings object - ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : - - // Extending ajaxSettings - ajaxExtend( jQuery.ajaxSettings, target ); - }, - - ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), - ajaxTransport: addToPrefiltersOrTransports( transports ), - - // Main method - ajax: function( url, options ) { - - // If url is an object, simulate pre-1.5 signature - if ( typeof url === "object" ) { - options = url; - url = undefined; - } - - // Force options to be an object - options = options || {}; - - var transport, - - // URL without anti-cache param - cacheURL, - - // Response headers - responseHeadersString, - responseHeaders, - - // timeout handle - timeoutTimer, - - // Url cleanup var - urlAnchor, - - // Request state (becomes false upon send and true upon completion) - completed, - - // To know if global events are to be dispatched - fireGlobals, - - // Loop variable - i, - - // uncached part of the url - uncached, - - // Create the final options object - s = jQuery.ajaxSetup( {}, options ), - - // Callbacks context - callbackContext = s.context || s, - - // Context for global events is callbackContext if it is a DOM node or jQuery collection - globalEventContext = s.context && - ( callbackContext.nodeType || callbackContext.jquery ) ? - jQuery( callbackContext ) : - jQuery.event, - - // Deferreds - deferred = jQuery.Deferred(), - completeDeferred = jQuery.Callbacks( "once memory" ), - - // Status-dependent callbacks - statusCode = s.statusCode || {}, - - // Headers (they are sent all at once) - requestHeaders = {}, - requestHeadersNames = {}, - - // Default abort message - strAbort = "canceled", - - // Fake xhr - jqXHR = { - readyState: 0, - - // Builds headers hashtable if needed - getResponseHeader: function( key ) { - var match; - if ( completed ) { - if ( !responseHeaders ) { - responseHeaders = {}; - while ( ( match = rheaders.exec( responseHeadersString ) ) ) { - responseHeaders[ match[ 1 ].toLowerCase() + " " ] = - ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) - .concat( match[ 2 ] ); - } - } - match = responseHeaders[ key.toLowerCase() + " " ]; - } - return match == null ? null : match.join( ", " ); - }, - - // Raw string - getAllResponseHeaders: function() { - return completed ? responseHeadersString : null; - }, - - // Caches the header - setRequestHeader: function( name, value ) { - if ( completed == null ) { - name = requestHeadersNames[ name.toLowerCase() ] = - requestHeadersNames[ name.toLowerCase() ] || name; - requestHeaders[ name ] = value; - } - return this; - }, - - // Overrides response content-type header - overrideMimeType: function( type ) { - if ( completed == null ) { - s.mimeType = type; - } - return this; - }, - - // Status-dependent callbacks - statusCode: function( map ) { - var code; - if ( map ) { - if ( completed ) { - - // Execute the appropriate callbacks - jqXHR.always( map[ jqXHR.status ] ); - } else { - - // Lazy-add the new callbacks in a way that preserves old ones - for ( code in map ) { - statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; - } - } - } - return this; - }, - - // Cancel the request - abort: function( statusText ) { - var finalText = statusText || strAbort; - if ( transport ) { - transport.abort( finalText ); - } - done( 0, finalText ); - return this; - } - }; - - // Attach deferreds - deferred.promise( jqXHR ); - - // Add protocol if not provided (prefilters might expect it) - // Handle falsy url in the settings object (#10093: consistency with old signature) - // We also use the url parameter if available - s.url = ( ( url || s.url || location.href ) + "" ) - .replace( rprotocol, location.protocol + "//" ); - - // Alias method option to type as per ticket #12004 - s.type = options.method || options.type || s.method || s.type; - - // Extract dataTypes list - s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; - - // A cross-domain request is in order when the origin doesn't match the current origin. - if ( s.crossDomain == null ) { - urlAnchor = document.createElement( "a" ); - - // Support: IE <=8 - 11, Edge 12 - 15 - // IE throws exception on accessing the href property if url is malformed, - // e.g. http://example.com:80x/ - try { - urlAnchor.href = s.url; - - // Support: IE <=8 - 11 only - // Anchor's host property isn't correctly set when s.url is relative - urlAnchor.href = urlAnchor.href; - s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== - urlAnchor.protocol + "//" + urlAnchor.host; - } catch ( e ) { - - // If there is an error parsing the URL, assume it is crossDomain, - // it can be rejected by the transport if it is invalid - s.crossDomain = true; - } - } - - // Convert data if not already a string - if ( s.data && s.processData && typeof s.data !== "string" ) { - s.data = jQuery.param( s.data, s.traditional ); - } - - // Apply prefilters - inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); - - // If request was aborted inside a prefilter, stop there - if ( completed ) { - return jqXHR; - } - - // We can fire global events as of now if asked to - // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) - fireGlobals = jQuery.event && s.global; - - // Watch for a new set of requests - if ( fireGlobals && jQuery.active++ === 0 ) { - jQuery.event.trigger( "ajaxStart" ); - } - - // Uppercase the type - s.type = s.type.toUpperCase(); - - // Determine if request has content - s.hasContent = !rnoContent.test( s.type ); - - // Save the URL in case we're toying with the If-Modified-Since - // and/or If-None-Match header later on - // Remove hash to simplify url manipulation - cacheURL = s.url.replace( rhash, "" ); - - // More options handling for requests with no content - if ( !s.hasContent ) { - - // Remember the hash so we can put it back - uncached = s.url.slice( cacheURL.length ); - - // If data is available and should be processed, append data to url - if ( s.data && ( s.processData || typeof s.data === "string" ) ) { - cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; - - // #9682: remove data so that it's not used in an eventual retry - delete s.data; - } - - // Add or update anti-cache param if needed - if ( s.cache === false ) { - cacheURL = cacheURL.replace( rantiCache, "$1" ); - uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + - uncached; - } - - // Put hash and anti-cache on the URL that will be requested (gh-1732) - s.url = cacheURL + uncached; - - // Change '%20' to '+' if this is encoded form body content (gh-2658) - } else if ( s.data && s.processData && - ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { - s.data = s.data.replace( r20, "+" ); - } - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - if ( jQuery.lastModified[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); - } - if ( jQuery.etag[ cacheURL ] ) { - jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); - } - } - - // Set the correct header, if data is being sent - if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { - jqXHR.setRequestHeader( "Content-Type", s.contentType ); - } - - // Set the Accepts header for the server, depending on the dataType - jqXHR.setRequestHeader( - "Accept", - s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? - s.accepts[ s.dataTypes[ 0 ] ] + - ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : - s.accepts[ "*" ] - ); - - // Check for headers option - for ( i in s.headers ) { - jqXHR.setRequestHeader( i, s.headers[ i ] ); - } - - // Allow custom headers/mimetypes and early abort - if ( s.beforeSend && - ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { - - // Abort if not done already and return - return jqXHR.abort(); - } - - // Aborting is no longer a cancellation - strAbort = "abort"; - - // Install callbacks on deferreds - completeDeferred.add( s.complete ); - jqXHR.done( s.success ); - jqXHR.fail( s.error ); - - // Get transport - transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); - - // If no transport, we auto-abort - if ( !transport ) { - done( -1, "No Transport" ); - } else { - jqXHR.readyState = 1; - - // Send global event - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); - } - - // If request was aborted inside ajaxSend, stop there - if ( completed ) { - return jqXHR; - } - - // Timeout - if ( s.async && s.timeout > 0 ) { - timeoutTimer = window.setTimeout( function() { - jqXHR.abort( "timeout" ); - }, s.timeout ); - } - - try { - completed = false; - transport.send( requestHeaders, done ); - } catch ( e ) { - - // Rethrow post-completion exceptions - if ( completed ) { - throw e; - } - - // Propagate others as results - done( -1, e ); - } - } - - // Callback for when everything is done - function done( status, nativeStatusText, responses, headers ) { - var isSuccess, success, error, response, modified, - statusText = nativeStatusText; - - // Ignore repeat invocations - if ( completed ) { - return; - } - - completed = true; - - // Clear timeout if it exists - if ( timeoutTimer ) { - window.clearTimeout( timeoutTimer ); - } - - // Dereference transport for early garbage collection - // (no matter how long the jqXHR object will be used) - transport = undefined; - - // Cache response headers - responseHeadersString = headers || ""; - - // Set readyState - jqXHR.readyState = status > 0 ? 4 : 0; - - // Determine if successful - isSuccess = status >= 200 && status < 300 || status === 304; - - // Get response data - if ( responses ) { - response = ajaxHandleResponses( s, jqXHR, responses ); - } - - // Use a noop converter for missing script but not if jsonp - if ( !isSuccess && - jQuery.inArray( "script", s.dataTypes ) > -1 && - jQuery.inArray( "json", s.dataTypes ) < 0 ) { - s.converters[ "text script" ] = function() {}; - } - - // Convert no matter what (that way responseXXX fields are always set) - response = ajaxConvert( s, response, jqXHR, isSuccess ); - - // If successful, handle type chaining - if ( isSuccess ) { - - // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. - if ( s.ifModified ) { - modified = jqXHR.getResponseHeader( "Last-Modified" ); - if ( modified ) { - jQuery.lastModified[ cacheURL ] = modified; - } - modified = jqXHR.getResponseHeader( "etag" ); - if ( modified ) { - jQuery.etag[ cacheURL ] = modified; - } - } - - // if no content - if ( status === 204 || s.type === "HEAD" ) { - statusText = "nocontent"; - - // if not modified - } else if ( status === 304 ) { - statusText = "notmodified"; - - // If we have data, let's convert it - } else { - statusText = response.state; - success = response.data; - error = response.error; - isSuccess = !error; - } - } else { - - // Extract error from statusText and normalize for non-aborts - error = statusText; - if ( status || !statusText ) { - statusText = "error"; - if ( status < 0 ) { - status = 0; - } - } - } - - // Set data for the fake xhr object - jqXHR.status = status; - jqXHR.statusText = ( nativeStatusText || statusText ) + ""; - - // Success/Error - if ( isSuccess ) { - deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); - } else { - deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); - } - - // Status-dependent callbacks - jqXHR.statusCode( statusCode ); - statusCode = undefined; - - if ( fireGlobals ) { - globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", - [ jqXHR, s, isSuccess ? success : error ] ); - } - - // Complete - completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); - - if ( fireGlobals ) { - globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); - - // Handle the global AJAX counter - if ( !( --jQuery.active ) ) { - jQuery.event.trigger( "ajaxStop" ); - } - } - } - - return jqXHR; - }, - - getJSON: function( url, data, callback ) { - return jQuery.get( url, data, callback, "json" ); - }, - - getScript: function( url, callback ) { - return jQuery.get( url, undefined, callback, "script" ); - } -} ); - -jQuery.each( [ "get", "post" ], function( _i, method ) { - jQuery[ method ] = function( url, data, callback, type ) { - - // Shift arguments if data argument was omitted - if ( isFunction( data ) ) { - type = type || callback; - callback = data; - data = undefined; - } - - // The url can be an options object (which then must have .url) - return jQuery.ajax( jQuery.extend( { - url: url, - type: method, - dataType: type, - data: data, - success: callback - }, jQuery.isPlainObject( url ) && url ) ); - }; -} ); - -jQuery.ajaxPrefilter( function( s ) { - var i; - for ( i in s.headers ) { - if ( i.toLowerCase() === "content-type" ) { - s.contentType = s.headers[ i ] || ""; - } - } -} ); - - -jQuery._evalUrl = function( url, options, doc ) { - return jQuery.ajax( { - url: url, - - // Make this explicit, since user can override this through ajaxSetup (#11264) - type: "GET", - dataType: "script", - cache: true, - async: false, - global: false, - - // Only evaluate the response if it is successful (gh-4126) - // dataFilter is not invoked for failure responses, so using it instead - // of the default converter is kludgy but it works. - converters: { - "text script": function() {} - }, - dataFilter: function( response ) { - jQuery.globalEval( response, options, doc ); - } - } ); -}; - - -jQuery.fn.extend( { - wrapAll: function( html ) { - var wrap; - - if ( this[ 0 ] ) { - if ( isFunction( html ) ) { - html = html.call( this[ 0 ] ); - } - - // The elements to wrap the target around - wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); - - if ( this[ 0 ].parentNode ) { - wrap.insertBefore( this[ 0 ] ); - } - - wrap.map( function() { - var elem = this; - - while ( elem.firstElementChild ) { - elem = elem.firstElementChild; - } - - return elem; - } ).append( this ); - } - - return this; - }, - - wrapInner: function( html ) { - if ( isFunction( html ) ) { - return this.each( function( i ) { - jQuery( this ).wrapInner( html.call( this, i ) ); - } ); - } - - return this.each( function() { - var self = jQuery( this ), - contents = self.contents(); - - if ( contents.length ) { - contents.wrapAll( html ); - - } else { - self.append( html ); - } - } ); - }, - - wrap: function( html ) { - var htmlIsFunction = isFunction( html ); - - return this.each( function( i ) { - jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); - } ); - }, - - unwrap: function( selector ) { - this.parent( selector ).not( "body" ).each( function() { - jQuery( this ).replaceWith( this.childNodes ); - } ); - return this; - } -} ); - - -jQuery.expr.pseudos.hidden = function( elem ) { - return !jQuery.expr.pseudos.visible( elem ); -}; -jQuery.expr.pseudos.visible = function( elem ) { - return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); -}; - - - - -jQuery.ajaxSettings.xhr = function() { - try { - return new window.XMLHttpRequest(); - } catch ( e ) {} -}; - -var xhrSuccessStatus = { - - // File protocol always yields status code 0, assume 200 - 0: 200, - - // Support: IE <=9 only - // #1450: sometimes IE returns 1223 when it should be 204 - 1223: 204 - }, - xhrSupported = jQuery.ajaxSettings.xhr(); - -support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); -support.ajax = xhrSupported = !!xhrSupported; - -jQuery.ajaxTransport( function( options ) { - var callback, errorCallback; - - // Cross domain only allowed if supported through XMLHttpRequest - if ( support.cors || xhrSupported && !options.crossDomain ) { - return { - send: function( headers, complete ) { - var i, - xhr = options.xhr(); - - xhr.open( - options.type, - options.url, - options.async, - options.username, - options.password - ); - - // Apply custom fields if provided - if ( options.xhrFields ) { - for ( i in options.xhrFields ) { - xhr[ i ] = options.xhrFields[ i ]; - } - } - - // Override mime type if needed - if ( options.mimeType && xhr.overrideMimeType ) { - xhr.overrideMimeType( options.mimeType ); - } - - // X-Requested-With header - // For cross-domain requests, seeing as conditions for a preflight are - // akin to a jigsaw puzzle, we simply never set it to be sure. - // (it can always be set on a per-request basis or even using ajaxSetup) - // For same-domain requests, won't change header if already provided. - if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { - headers[ "X-Requested-With" ] = "XMLHttpRequest"; - } - - // Set headers - for ( i in headers ) { - xhr.setRequestHeader( i, headers[ i ] ); - } - - // Callback - callback = function( type ) { - return function() { - if ( callback ) { - callback = errorCallback = xhr.onload = - xhr.onerror = xhr.onabort = xhr.ontimeout = - xhr.onreadystatechange = null; - - if ( type === "abort" ) { - xhr.abort(); - } else if ( type === "error" ) { - - // Support: IE <=9 only - // On a manual native abort, IE9 throws - // errors on any property access that is not readyState - if ( typeof xhr.status !== "number" ) { - complete( 0, "error" ); - } else { - complete( - - // File: protocol always yields status 0; see #8605, #14207 - xhr.status, - xhr.statusText - ); - } - } else { - complete( - xhrSuccessStatus[ xhr.status ] || xhr.status, - xhr.statusText, - - // Support: IE <=9 only - // IE9 has no XHR2 but throws on binary (trac-11426) - // For XHR2 non-text, let the caller handle it (gh-2498) - ( xhr.responseType || "text" ) !== "text" || - typeof xhr.responseText !== "string" ? - { binary: xhr.response } : - { text: xhr.responseText }, - xhr.getAllResponseHeaders() - ); - } - } - }; - }; - - // Listen to events - xhr.onload = callback(); - errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); - - // Support: IE 9 only - // Use onreadystatechange to replace onabort - // to handle uncaught aborts - if ( xhr.onabort !== undefined ) { - xhr.onabort = errorCallback; - } else { - xhr.onreadystatechange = function() { - - // Check readyState before timeout as it changes - if ( xhr.readyState === 4 ) { - - // Allow onerror to be called first, - // but that will not handle a native abort - // Also, save errorCallback to a variable - // as xhr.onerror cannot be accessed - window.setTimeout( function() { - if ( callback ) { - errorCallback(); - } - } ); - } - }; - } - - // Create the abort callback - callback = callback( "abort" ); - - try { - - // Do send the request (this may raise an exception) - xhr.send( options.hasContent && options.data || null ); - } catch ( e ) { - - // #14683: Only rethrow if this hasn't been notified as an error yet - if ( callback ) { - throw e; - } - } - }, - - abort: function() { - if ( callback ) { - callback(); - } - } - }; - } -} ); - - - - -// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) -jQuery.ajaxPrefilter( function( s ) { - if ( s.crossDomain ) { - s.contents.script = false; - } -} ); - -// Install script dataType -jQuery.ajaxSetup( { - accepts: { - script: "text/javascript, application/javascript, " + - "application/ecmascript, application/x-ecmascript" - }, - contents: { - script: /\b(?:java|ecma)script\b/ - }, - converters: { - "text script": function( text ) { - jQuery.globalEval( text ); - return text; - } - } -} ); - -// Handle cache's special case and crossDomain -jQuery.ajaxPrefilter( "script", function( s ) { - if ( s.cache === undefined ) { - s.cache = false; - } - if ( s.crossDomain ) { - s.type = "GET"; - } -} ); - -// Bind script tag hack transport -jQuery.ajaxTransport( "script", function( s ) { - - // This transport only deals with cross domain or forced-by-attrs requests - if ( s.crossDomain || s.scriptAttrs ) { - var script, callback; - return { - send: function( _, complete ) { - script = jQuery( " +or with const checkdata = require('../public/js/checkdata.js') + +*/ + +// --## + +const checkdata = {} +// each checkdata.test. return true or false +checkdata.test = {} + +checkdata.test.emailadress = (ctx, email) => { + const regExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ + return regExp.test(email) +} +/* + * @emaillist = "email1,email2, email3" + * it check if each eamil separate by , are correct + */ +checkdata.test.emailadresslist = (ctx, emaillist) => { + // logger.info(emaillist.split(',')) + if (emaillist.length > 0) { + const emails = emaillist.split(',') + for (const i in emails) { + // logger.info(emails[i]) + if (!checkdata.test.emailadress('', emails[i].trim())) { + return false + } + } + }; + return true +} + +checkdata.test.password = (ctx, pwd) => { + const regExp = new RegExp( + /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&.])[A-Za-z\d$@$!%*?&.{}:|\s]{8,}/ + ) + return regExp.test(pwd) +} +checkdata.test.required = (ctx, val) => + (val !== null && val !== 'undefined' && val.length > 0) || (!!val && val.constructor ==== Array && val.length > 0) || (!!val && val.constructor ==== Object && Object.keys(val) + .length > 0) + +checkdata.test.isNumber = (ctx, n) => typeof n ==== 'number' +checkdata.test.isInt = (ctx, n) => n !== '' && !isNaN(n) && Math.round(n) === n +checkdata.test.isFloat = (ctx, n) => n !== '' && !isNaN(n) && Math.round(n) !== n +checkdata.test.unique = (ctx, val) => { + if (ctx.list[ctx.currentfield]) { + return !ctx.list[ctx.currentfield].includes(val) + } else { + logger.info('ERR no list for field:' + ctx.currentfield) + return false + } +} +checkdata.test.isDateDay = (ctx, dateDay) => true +/* checkdata.test.filterInvalidInArray = (array, validate) => + array ? array.filter(el => !validate(el)) : true; +// return true when every elements is valid +*/ + +checkdata.test.postalCode = (ctx, postalCode) => { + if (postalCode.length === 0) return true + const regExp = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/) + return regExp.test(postalCode) +} +/** + * PHONE + */ +checkdata.test.phoneNumber = (ctx, phoneNumber) => { + if (phoneNumber.length === 0) return true + phoneNumber = phoneNumber.trim() + .replace(/[- .]/g, '') + // french number + const regExpfr = new RegExp(/^0[1-9][0-9]{9}$/) + const regExpInternational = new RegExp(/^\+*(\d{3})*[0-9,\-]{8,}/) + return regExpfr.test(phoneNumber) || regExpInternational.test(phoneNumber) +} +/* + * @phonelist = "phone1,phone2,phone3" + * it check if each phone separate by , are correct + */ +checkdata.test.phoneNumberlist = (ctx, phonelist) => { + // logger.info(emaillist.split(',')) + if (phonelist.length > 0) { + const phones = phonelist.split(',') + for (const i in phones) { + // logger.info(emails[i]) + if (!checkdata.test.phoneNumber('', phones[i].trim())) { + return false + } + } + }; + return true +} + +// checkdata.normalize take a correct data then reformat it to harmonise it +checkdata.normalize = {} +checkdata.normalize.phoneNumber = (ctx, phone) => { + phone = phone.trim() + .replace(/[- .]/g, '') + if (checkdata.test.phoneNumber('', phone) && phone.length === 10 && phone[0] === '0') { + phone = '+33 ' + phone.substring(1) + } + return phone +} +checkdata.normalize.upperCase = (ctx, txt) => txt.toUpperCase() +checkdata.normalize.lowerCase = (ctx, txt) => txt.toLowerCase() +// fixe 10 position et complete par des 0 devant +checkdata.normalize.zfill10 = (ctx, num) => { + let s = num + '' + while (s.length < 10) s = '0' + s + return s +} +/* let tt = "+33 1 02.03 04 05"; +logger.info(checkdata.test.phoneNumber('', tt)) +logger.info(checkdata.normalize.phoneNumber('', tt)) +*/ +checkdata.evaluate = (contexte, referential, data) => { + /* + * contexte object {} with full info for evaluation + * file referential path to get object to apply + * data related to object + - return {validefor =[keyword of error] if empty no error, + clean data eventually reformated + updateDatabase} + */ + logger.info('contexte', contexte) + logger.info('referentiel', referential) + logger.info('data', data) + const invalidefor = [] + const objectdef = {} + const listfield = referential.map(ch => { + objectdef[ch.idfield] = ch + return ch.idfield + }) + + Object.keys(data) + .forEach(field => { + if (!listfield.includes(field)) { + // some data can be inside an object with no control at all + // they are used for process only + // i leave it in case it will become a non sens + // invalidefor.push('ERRFIELD unknown of referentials ' + field); + } else { + if (objectdef[field].check) { + // check data with rule list in check + objectdef[field].check.forEach(ctrl => { + logger.info('ctrl', ctrl) + contexte.currentfield = field + if (!checkdata.test[ctrl]) { + invalidefor.push('ERR check function does not exist :' + ctrl + '___' + field) + } else { + if (!checkdata.test[ctrl](contexte, data[field])) { invalidefor.push('ERR' + ctrl + '___' + field) } + } + }) + } + + if (objectdef[field].nouserupdate) { + // check if user can modify this information + logger.info( + 'evaluation :' + field + ' -- ' + objectdef[field].nouserupdate, + eval(objectdef[field].nouserupdate) + ) + const evalright = eval(objectdef[field].nouserupdate) + objectdef[field].nouserupdate = evalright + } + } + }) + logger.info({ + invalidefor, + data + }) + return { + invalidefor, + data + } +} + +if (typeof module !==== 'undefined') module.exports = checkdata diff --git a/src/nationchains/socialworld/contracts/toolsbox.js b/src/nationchains/socialworld/contracts/toolsbox.js new file mode 100755 index 0000000..322749b --- /dev/null +++ b/src/nationchains/socialworld/contracts/toolsbox.js @@ -0,0 +1,604 @@ +/* eslint-disable no-useless-escape */ +const fs = require('fs') +const path = require('path') +const bcrypt = require('bcrypt') +const moment = require('moment') +const config = require('../config') +const utils = {} + +logger.info("Check in /utils/index.js to find usefull function for your dev.\n Feel free to send suggestion, code to maintainer of apixtribe project (see /package.json to get email).\n We'll add to the roadmap to add it.") + +/** + * EMAIL + */ +/* const validateEmail = email => { + const regExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + return regExp.test(email); +}; + +const validatePassword = pwd => { + const regExp = new RegExp( + /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&.])[A-Za-z\d$@$!%*?&.{}:|\s]{8,}/ + ); + return regExp.test(pwd); +}; + +const filterInvalidInArray = (array, validate) => + array ? array.filter(el => !validate(el)) : undefined; // return undefined when every elements is valid + +/** + * POSTAL CODE + */ +/* +const validatePostalCode = postalCode => + /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(postalCode); + +/** + * PHONE + */ +/* const validatePhoneNumber = phoneNumber => + /((^0[1-9]|\+[0-9]{3})([-. ]?[0-9]{2}){4}$)/.test(phoneNumber); + +const correctPhoneNumber = phone => + phone[0] ==== '0' ? '+33' + phone.substr(1) : phone; + +const checkData = (appProfil, referential, data) => { + // @TODO get a referentiel per object then check data validity and allowed access + // need to add referentiel manager + const invalidefor = []; + let updateDatabase = false; + Object.keys(data).forEach(field => { + switch (field) { + case 'token': + updateDatabase = true; + break; + case 'email': + if (!validateEmail(data.email)) { + invalidefor.push('ERREMAIL:' + field); + } else { + updateDatabase = true; + } + break; + case 'password': + if (!validatePassword(data.password)) { + invalidefor.push('ERRPWD:' + field); + } else { + data.password = bcrypt.hash(data.password, config.saltRounds); + updateDatabase = true; + } + break; + } + }); + return { invalidefor, data, updateDatabase }; +}; +*/ +// Permet d'attendre en milliseconde +// s'utilise avec async ()=>{ +// await sleep(2000) +// } +utils.sleep = (ms) => { + return new Promise(resolve => setTimeout(resolve, ms)) +} +utils.generemdp = (nbpos) => { + const chaine = 'ABCDEFGHIJKLMNPQRSTUVWZY123456789' + let mdp = '' + for (let i = 0; i < nbpos; i++) { + const pos = Math.floor(Math.random() * chaine.length) + mdp += chaine.substring(pos, pos + 1) + } + return mdp +} +utils.generecompteur = (filecpt, typeincrement) => { + let file = `${filecpt}/${typeincrement}.json` + let prefix = '' + if (typeincrement = 'ANNEESEMAINE') { + file = `${filecpt}/${typeincrement}${moment().format('YYYY')}${moment().format('WW')}.json` + prefix = `${moment().format('YYYY')}${moment().format('WW')}` + } + let num = 1 + try { + num = parseInt(fs.readFileSync(file, 'utf8')) + 1 + } catch (err) { + logger.info('Nouveau compteur incrementale ', file) + } + fs.writeFileSync(file, num, 'utf8') + return prefix + num +} +/** + * CSV + */ +utils.json2csv = (jsondata, options, callback) => { + // uniquement json = [{niv1:val,niv1:[liste of val]}] + // logger.info('_________________________'); + // logger.info(jsondata) + // logger.info('_________________________'); + if (jsondata.length === 0) { + return callback('Empty json', null) + } + if (!options.retln) options.retln = '\n' + if (!options.sep) options.sep = ';' + if (!options.arraysplitsep) options.arraysplitsep = ',' + if (!options.replacespecialcarJson2Csv) { + options.replacespecialcarJson2Csv = [] + } else { + if (typeof options.replacespecialcarJson2Csv ==== 'string') { + // permet de passer des regex en string + options.replacespecialcarJson2Csv = eval(options.replacespecialcarJson2Csv) + } + }; + const etat = '' + let csv = '' + let entete = '' + let prem = true + for (const j in jsondata) { + // logger.info(jsondata[j]) + for (const c in options.champs) { + if (prem) { + entete += options.champs[c] + options.sep + } + if (jsondata[j][options.champs[c]]) { + if (options.array.indexOf(options.champs[c]) > -1) { + csv += jsondata[j][options.champs[c]].join(options.arraysplitsep) + options.sep + } else { + let currentValue = '' + if (jsondata[j][options.champs[c]]) currentValue += jsondata[j][options.champs[c]] + options.replacespecialcarJson2Csv.forEach(re => { + // logger.info(currentValue) + currentValue = currentValue.replace(re[1], re[0]) + }) + csv += currentValue + options.sep + } + } else { + csv += options.sep + } + } + csv = csv.substring(0, csv.length - 1) + options.retln + if (prem) { + prem = false + entete = entete.substring(0, entete.length - 1) + options.retln + // logger.info(entete) + } + } + // return entete + csv; + if (etat === '') { + return callback(null, entete + csv) + } else { + return callback(etat, null) + } +} +/** + * Get headers from first line of CSV + * @param {array} lines array of string which contains each csv lines + * @return {array} string array of headers + */ +utils.getHeaders = (lines, sep) => lines[0].split(sep) + .map(i => i.replace(/"/g, '')) +/** + * [csv2json description] + * @param {object} csv object of csv file that has been read + * @param {object} options object containing csv options, headers, ... + {retln:'code de retour de ligne \n ou \n\r', + sep:'code to split cells', + champs:[ch1,ch2,...] catch only those field, + array:[ch1, ] can have more than one field champs with same name then data are push into an array } + * @param {Function} callback callback function + * @return {callback} - return an error if error, else return json + it convert a csv file into a json = [{field:value}] + +Usage example: +fiche.csv2article = (err, fiche) => { + if (!err) { + logger.info(fiche) + } +} +utils.csv2json(fs.readFileSync('./devdata/tribee/aubergenville/infoexterne/localbusiness.csv', 'utf-8'), { + retln: "\n", + sep: ";", + champs: ["NOM", "OBJET", "ADRESSE_PRO", "CP_PRO", "VILLE_PRO", "ZONE", "PHONE_PRO", "HORAIRESDESC", "HORAIREDATA", "URL", "FACEBOOK", "INSTA", "EMAIL_PRO", "IMG", "TAG"], + array: ["TAG", "PHONE_PRO", "EMAIL_PRO"] +}, fiche.csv2article) + + */ +utils.replacecarbtweendblquote = (csv, car, carremplacant) => { + /* + return csv text with any car betwenn 2 " by CARSEPARATOR + */ + let newcsv = '' + let txtencours = '' + let flagouvert = false + const sepreg = new RegExp(`${car}`, 'gmi') + for (let j = 0; j < csv.length; j++) { + // if((csv[j] === "\"" && csv[j + 1] && csv[j + 1] !== "\"") || (csv[j] === "\"" && csv[j - 1] && csv[j - 1] !== "\"") || (csv[j] === "\"" && csv[j - 1] && csv[j - 2] && csv[j - 1] !== "\"" && csv[j - 2] !== "\"")) { + if (csv[j] === '"') { + if (flagouvert) { + // on cherche à ferme une chaine de texte + if (csv[j + 1] === '"') { + // on a "" consecutif qu'on remplace par "" et on fait j+1 + txtencours += '""' + j++ + } else { + // on a bien une fermeture + flagouvert = false + newcsv += txtencours.replace(sepreg, carremplacant) + txtencours = '"' + } + } else { + // on ouvre une chaine + flagouvert = true + // on met le contenu précédent ds newcsv + newcsv += txtencours + txtencours = '"' + } + // } else if((csv[j] !==== "\n") && (csv[j + 1] && csv[j] + csv[j + 1] !==== "\n\r")) { + } else if (csv[j] !==== '\n') { + txtencours += csv[j] + // } else if((csv[j] === "\n") || (csv[j + 1] && csv[j] + csv[j + 1] === "\n\r")) { + } else if (csv[j] === '\n') { + if (!flagouvert) txtencours += '\n' + } + } + return newcsv + txtencours +} +utils.analysestring = (string) => { + let buftxt = '' + let bufcode = '' + let i = 0 + let avecRL = false + for (let p = 0; p < string.length; p++) { + if (string[p].charCodeAt() === 10) { + buftxt += '[RL]' + avecRL = true + } else { + buftxt += string[p] + } + bufcode += '-' + string[p].charCodeAt() + if (i === 20) { + if (avecRL) { + logger.info(`${buftxt} - ${bufcode}`) + } else { + logger.info(`${buftxt} ---- ${bufcode}`) + } + i = 0 + buftxt = '' + bufcode = '' + avecRL = false + } + i++ + } +} + +const txtstring = `32932,BK_F2F_B_COM_10x1H-09,"My Communication Workshop ""Session N°9 - 1H""","

 

+ + + + + + +
+

Learner who needs to develop their ability to communicate effectively at work, both in writing and speaking

+
",,english,2,0,,2,0,classroom,"0000-00-00 00:00:00","0000-00-00 00:00:00",0000-00-00,0000-00-00,https://www.yesnyoulearning.com/lms/index.php?r=player&course_id=32932,1101,,"BUSINESS KEYS",0, +32933,BK_F2F_B_COM_10x1H-10,"My Communication Workshop Session N°10 - 1H","

 

+ + + + + + +
+

Learner who needs to develop their ability to communicate effectively at work, both in writing and speaking

+
",,english,2,0,,2,0,classroom,"0000-00-00 00:00:00","0000-00-00 00:00:00",0000-00-00,0000-00-00,https://www.yesnyoulearning.com/lms/index.php?r=player&course_id=32933,1101,,"BUSINESS KEYS",0, +32934,BK_F2F_B_JOB_10x1H-01,"My Job Search Workshop Session N°1 - 1H","

PACK JOB SEARCH

",,english,2,0,,2,0,classroom,,,0000-00-00,0000-00-00,https://www.yesnyoulearning.com/lms/index.php?r=player&course_id=32934,1108,,,0, +32935,BK_F2F_B_JOB_10x1H-02,"My Job Search Workshop Session N°2 - 1H","

PACK JOB SEARCH

",,english,2,0,,2,0,classroom,,,0000-00-00,0000-00-00,https://www.yesnyoulearning.com/lms/index.php?r=player&course_id=32935,1108,,,0,` +// utils.analysestring(txtstring) +// logger.info(utils.replacecarbtweendblquote(txtstring, ",", 'CARSEPARATOR') +// .split("\n")[0].split(",")) +utils.csv2json = (csv, options, callback) => { + // EN CAS DE PB AVEC UN FICHIER EXCEL RECALCITRANT + // l'ouvrir dans calc linux et sauvegarder csv utf8, ; , " enregistrer le contenu de la cellule comme affiché + logger.info('\n--------------- CSV2JSON ---------------\n') + // Default CSV options + if (!options.retln) options.retln = '\n' + if (csv.indexOf('\n\r') > -1) options.retln = '\n\r' + if (!options.sep) options.sep = ';' + // gestion d un separateur dans une chaine de texte + // const regseptext = new RegExp(`${options.sep}(?!(?:[^"]*"[^"]*")*[^"]*$)`, 'gm'); + // csv = csv.replace(regseptext, "CARACSEPAR"); + // csv = utils.replacecarbtweendblquote(csv, options.retln, "RETLIGNE") + csv = utils.replacecarbtweendblquote(csv, options.sep, 'CARSEPARATOR') + if (!options.replacespecialcarCsv2Json) { + options.replacespecialcarCsv2Json = [] + } else { + if (typeof options.replacespecialcarCsv2Json ==== 'string') { + // permet de passer des regex en string + options.replacespecialcarCsv2Json = eval(options.replacespecialcarCsv2Json) + } + }; + const result = [] + const lines = csv.split(options.retln) + const headers = utils.getHeaders(lines, options.sep) + let unknownHeaders = '' + // logger.info('headers', headers) + // logger.info('options.champs', options.champs) + headers.forEach(header => { + // Si un header n'est pas présent dans la liste des champs prédéfinis + // on l'ajoute aux champs inconnus + if (options.champs.indexOf(header) ==== -1) { + unknownHeaders += `${header}, ` + } + }) + if (unknownHeaders !==== '') { + const errorMsg = `CSV2JSON() - Champs inconnus : ${unknownHeaders}` + return callback(errorMsg, null) + } + lines.forEach((line, index) => { + // Skip headers line or empty lines + if (index ==== 0 || line.replace(/\s/g, '') + .length ==== 0) { + return + } + // pour debuguer on met origincsv pour voir la ligne d'origine + const currentLineData = { origincsv: line, linenumber: index } + const currentLine = line.split(options.sep) // Current string in the line + for (let j = 0; j < headers.length; j++) { + // Si la ligne n'est pas vide + if (currentLine[j]) { + // On clean le champs + // ajout eventuel de modification de caracter reservé ; dans les libelléetc... + let currentValue = currentLine[j].trim() + // on transforme le caractere separateur modifié entre double quote + currentValue = currentValue.replace('CARSEPARATOR', options.sep) + options.replacespecialcarCsv2Json.forEach(re => { + currentValue = currentValue.replace(re[0], re[1]) + }) + // Si le header est un email + if (headers[j].includes('EMAIL')) { + // Supprimer tous les espaces + currentValue = currentLine[j].replace(/\s/g, '') + } + // on check si le chamos doit être numerique + if (options.numericfield.includes(headers[j])) { + currentValue = currentLine[j].replace(/\,/g, '.') + try { + const test = parseFloat(currentValue) + } catch (er) { + return callback(`${headers[j]} contiens la valeur -${currentValue}- et devrait être numerique`, null) + } + } + if (currentValue) { + // Si le header actuel est de type array + // Cela signifie que le header apparaît plusieurs fois dans le CSV + // et que les valeurs correspondantes à ce header + // doivent être mis dans un array + if (options.array && options.array.indexOf(headers[j]) > -1) { + // Si le tableau pour ce header n'existe pas on le crée + if (!currentLineData[headers[j]]) { + currentLineData[headers[j]] = [] + } + if (options.arraysplitsep) { + currentValue.split(options.arraysplitsep) + .forEach(v => { + currentLineData[headers[j]].push(v) + }) + } else { + currentLineData[headers[j]].push(currentValue) + } + } else { + // Si un header est déjà présent pour la ligne + // alors que il n'est pas spécifié comme étant un array + // on retourne une erreur + if (currentLineData[headers[j]]) { + const errorMsg = `Le champ ${ + headers[j] + } est présent plusieurs fois alors qu'il n'est pas spécifié comme étant un array !` + return callback(errorMsg, null) + } + currentLineData[headers[j]] = currentValue + } + } + } + } + result.push(currentLineData) + }) + return callback(null, result) +} +/** + * [csvparam2json description] + * @param {object} csv object of csv file that has been read + * @param {object} options object containing csv options, headers, ... + {retln:'code de retour de ligne \n ou \n\r', + sep:'code to split cells', + champs:[ch1,ch2,...] catch only those field, + array:[ch1, ] can have more than one field champs with same name then data are push into an array } + * @param {Function} callback callback function + * @return {callback} - return an error if error, else return json + it converts a csv with 3 column col1;col2;col3 in a json in a tree + if in col1 we have __ => then it splits a leaf + col1 = xxxx__yyyy ; col2 = value ; col3 = comment that is ignored + return data = {xxxx:{yyyy:value}} + col1 = xxxx; col2 = value; col3 = comment ignored +return data = {xxxx:value} + +Usage example: +fiche.csvparam2article = (err, fiche) => { + if (!err) { + logger.info(fiche) + } +} +utils.csvparam2json(fs.readFileSync('./devdata/tribee/aubergenville/infoexterne/localbusiness.csv', 'utf-8'), { + retln: "\n", + sep: ";", + champs: ["NOM", "OBJET", "ADRESSE_PRO", "CP_PRO", "VILLE_PRO", "ZONE", "PHONE_PRO", "HORAIRESDESC", "HORAIREDATA", "URL", "FACEBOOK", "INSTA", "EMAIL_PRO", "IMG", "TAG"], + array: ["TAG", "PHONE_PRO", "EMAIL_PRO"] +}, fiche.csv2article) + + */ +utils.csvparam2json = (csv, options, callback) => { + logger.info('\n--------------- CSVPARAM2JSON ---------------\n') + let etat = '' + const param = {} + if (!options.retln) { + options.retln = '\n' + } + if (csv.indexOf('\n\r') > -1) { + options.retln = '\n\r' + } + if (!options.sep) { + options.sep = ';' + } + if (!options.seplevel) { + options.seplevel = '__' + } + if (!options.replacespecialcarCsv2Json) { + options.replacespecialcarCsv2Json = [] + } else { + if (typeof options.replacespecialcarCsv2Json ==== 'string') { + // permet de passer des regex en string + options.replacespecialcarCsv2Json = eval(options.replacespecialcarCsv2Json) + } + }; + const lines = csv.split(options.retln) + for (let i = 0; i < lines.length; i++) { + const infol = lines[i].split(options.sep) + // logger.info(infol) + if (infol[0].length > 4 && infol.length < 2) { + // si le 1er element à plus de 4 caractere et s'il y a moins de 3 colonnes c'est qu'il y a un pb + etat += `Erreur sur ${lines[i]} moins de 3 column separé par ${options.sep}` + continue + } + // On ajoute ici la gestion de tous les caracteres spéciaux + // reservées pour le csv ; ' etc..' + if (infol[1] && infol[1] + '' === infol[1]) { + options.replacespecialcarCsv2Json.forEach(re => { + // logger.info("gggggggggggggggggggg", infol[1]) + infol[1] = infol[1].replace(re[0], re[1]) + }) + // logger.info(infol[1]) + infol[1] = infol[1].replace(/'|’/g, '"') + // logger.info(infol[1]) + if (infol[1].toLowerCase() ==== 'true') { + infol[1] = true + } else if (infol[1].toLowerCase() ==== 'false') { + infol[1] = false + } + } + logger.info(infol[1]) + // supprime des lignes vides + if (infol[0] === '') continue + if (infol[0].indexOf(options.seplevel) === -1) { + param[infol[0]] = infol[1] + continue + } else { + const arbre = infol[0].split(options.seplevel) + switch (arbre.length) { + case 1: + param[arbre[0]] = infol[1] + break + case 2: + if (arbre[1] !== 'ARRAY') { + if (!param[arbre[0]]) param[arbre[0]] = {} + param[arbre[0]][arbre[1]] = infol[1] + } else { + if (!param[arbre[0]]) param[arbre[0]] = [] + // logger.info('aff', infol[1].substring(1, infol[1].length - 1).replace(/""/g, '"')) + eval('result=' + infol[1]) + // .substring(1, infol[1].length - 1).replace(/""/g, '"')) + param[arbre[0]].push(result) + } + break + case 3: + if (arbre[2] !== 'ARRAY') { + if (!param[arbre[0]]) param[arbre[0]] = {} + if (!param[arbre[0]][arbre[1]]) param[arbre[0]][arbre[1]] = {} + param[arbre[0]][arbre[1]][arbre[2]] = infol[1] + } else { + if (!param[arbre[0]]) param[arbre[0]] = {} + if (!param[arbre[0]][arbre[1]]) param[arbre[0]][arbre[1]] = [] + // eval("result = \"test\""); + // logger.info(result); + eval('result=' + infol[1]) + // .substring(1, infol[1].length - 1).replace(/""/g, '"')) + param[arbre[0]][arbre[1]].push(result) + } + break + case 4: + if (arbre[3] !== 'ARRAY') { + if (!param[arbre[0]]) param[arbre[0]] = {} + if (!param[arbre[0]][arbre[1]]) param[arbre[0]][arbre[1]] = {} + if (!param[arbre[0]][arbre[1]][arbre[2]]) param[arbre[0]][arbre[1]][arbre[2]] = {} + param[arbre[0]][arbre[1]][arbre[2]][arbre[3]] = infol[1] + } else { + if (!param[arbre[0]]) param[arbre[0]] = {} + if (!param[arbre[0]][arbre[1]]) param[arbre[0]][arbre[1]] = {} + if (!param[arbre[0]][arbre[1]][arbre[2]]) param[arbre[0]][arbre[1]][arbre[2]] = [] + eval('result=' + infol[1]) + // .substring(1, infol[1].length - 1).replace(/""/g, '"')) + param[arbre[0]][arbre[1]][arbre[2]].push(result) + break + } + default: + break + } + } + } + // JSON.parse(JSON.stringify(param)) + logger.info('kkkkkkkkkkkkkkkkkk', param.catalogue.filtrecatalog.searchengine) + if (etat === '') { + return callback(null, JSON.parse(JSON.stringify(param))) + } else { + return callback(etat, null) + } +} +utils.levenshtein = (a, b) => { + if (a.length ==== 0) return b.length + if (b.length ==== 0) return a.length + let tmp, i, j, prev, val, row + // swap to save some memory O(min(a,b)) instead of O(a) + if (a.length > b.length) { + tmp = a + a = b + b = tmp + } + row = Array(a.length + 1) + // init the row + for (i = 0; i <= a.length; i++) { + row[i] = i + } + // fill in the rest + for (i = 1; i <= b.length; i++) { + prev = i + for (j = 1; j <= a.length; j++) { + if (b[i - 1] ==== a[j - 1]) { + val = row[j - 1] // match + } else { + val = Math.min(row[j - 1] + 1, // substitution + Math.min(prev + 1, // insertion + row[j] + 1)) // deletion + } + row[j - 1] = prev + prev = val + } + row[a.length] = prev + } + return row[a.length] +} +utils.testinarray = (array, arrayreferent) => { + // au moins un element de array existe dans arryreferent + let exist = false + if (arrayreferent) { + // logger.info('arrrrrrrrrrrrrrr', arrayreferent) + array.forEach(e => { + // logger.info(e) + if (arrayreferent.includes(e)) exist = true + }) + } + return exist +} +/* +DIRECTORY +*/ +const isDirectory = source => fs.lstatSync(source) + .isDirectory() +const getDirectories = source => fs.readdirSync(source) + .map(name => path.join(source, name)) + .filter(isDirectory) +module.exports = utils diff --git a/nationchains/socialworld/metaobject/nation.json b/src/nationchains/socialworld/metaobject/nation.json similarity index 100% rename from nationchains/socialworld/metaobject/nation.json rename to src/nationchains/socialworld/metaobject/nation.json diff --git a/nationchains/socialworld/metaobject/pagans.json b/src/nationchains/socialworld/metaobject/pagans.json similarity index 100% rename from nationchains/socialworld/metaobject/pagans.json rename to src/nationchains/socialworld/metaobject/pagans.json diff --git a/nationchains/socialworld/metaobject/towns.json b/src/nationchains/socialworld/metaobject/towns.json similarity index 100% rename from nationchains/socialworld/metaobject/towns.json rename to src/nationchains/socialworld/metaobject/towns.json diff --git a/nationchains/socialworld/objects/nations/ants.json b/src/nationchains/socialworld/objects/nations/ants.json similarity index 100% rename from nationchains/socialworld/objects/nations/ants.json rename to src/nationchains/socialworld/objects/nations/ants.json diff --git a/nationchains/socialworld/objects/nations/escape.json b/src/nationchains/socialworld/objects/nations/escape.json similarity index 100% rename from nationchains/socialworld/objects/nations/escape.json rename to src/nationchains/socialworld/objects/nations/escape.json diff --git a/nationchains/socialworld/objects/nations/searchindex/nationslist.json b/src/nationchains/socialworld/objects/nations/searchindex/nationslist.json similarity index 100% rename from nationchains/socialworld/objects/nations/searchindex/nationslist.json rename to src/nationchains/socialworld/objects/nations/searchindex/nationslist.json diff --git a/nationchains/socialworld/objects/nations/searchindex/townslist.json b/src/nationchains/socialworld/objects/nations/searchindex/townslist.json similarity index 100% rename from nationchains/socialworld/objects/nations/searchindex/townslist.json rename to src/nationchains/socialworld/objects/nations/searchindex/townslist.json diff --git a/nationchains/socialworld/objects/nations/searchindex/tribeslist.json b/src/nationchains/socialworld/objects/nations/searchindex/tribeslist.json similarity index 100% rename from nationchains/socialworld/objects/nations/searchindex/tribeslist.json rename to src/nationchains/socialworld/objects/nations/searchindex/tribeslist.json diff --git a/nationchains/socialworld/objects/towns/game.json b/src/nationchains/socialworld/objects/towns/game.json similarity index 100% rename from nationchains/socialworld/objects/towns/game.json rename to src/nationchains/socialworld/objects/towns/game.json diff --git a/nationchains/socialworld/objects/tribes/searchindex/tribeslist.json b/src/nationchains/socialworld/objects/tribes/searchindex/tribeslist.json similarity index 100% rename from nationchains/socialworld/objects/tribes/searchindex/tribeslist.json rename to src/nationchains/socialworld/objects/tribes/searchindex/tribeslist.json diff --git a/nationchains/static/error/404.html b/src/nationchains/static/error/404.html similarity index 100% rename from nationchains/static/error/404.html rename to src/nationchains/static/error/404.html diff --git a/nationchains/static/error/50x.html.html b/src/nationchains/static/error/50x.html.html similarity index 100% rename from nationchains/static/error/50x.html.html rename to src/nationchains/static/error/50x.html.html diff --git a/nationchains/static/fonts/Cantarell-Bold.ttf b/src/nationchains/static/fonts/Cantarell-Bold.ttf similarity index 100% rename from nationchains/static/fonts/Cantarell-Bold.ttf rename to src/nationchains/static/fonts/Cantarell-Bold.ttf diff --git a/nationchains/static/fonts/Cantarell-BoldItalic.ttf b/src/nationchains/static/fonts/Cantarell-BoldItalic.ttf similarity index 100% rename from nationchains/static/fonts/Cantarell-BoldItalic.ttf rename to src/nationchains/static/fonts/Cantarell-BoldItalic.ttf diff --git a/nationchains/static/fonts/Cantarell-Italic.ttf b/src/nationchains/static/fonts/Cantarell-Italic.ttf similarity index 100% rename from nationchains/static/fonts/Cantarell-Italic.ttf rename to src/nationchains/static/fonts/Cantarell-Italic.ttf diff --git a/nationchains/static/fonts/Cantarell-Regular.ttf b/src/nationchains/static/fonts/Cantarell-Regular.ttf similarity index 100% rename from nationchains/static/fonts/Cantarell-Regular.ttf rename to src/nationchains/static/fonts/Cantarell-Regular.ttf diff --git a/nationchains/static/fonts/OFL.txt b/src/nationchains/static/fonts/OFL.txt similarity index 97% rename from nationchains/static/fonts/OFL.txt rename to src/nationchains/static/fonts/OFL.txt index 4e49501..2b29f01 100755 --- a/nationchains/static/fonts/OFL.txt +++ b/src/nationchains/static/fonts/OFL.txt @@ -1,93 +1,93 @@ -Copyright (c) 2009-2010, Understanding Limited (dave@understandinglimited.com) - -This Font Software is licensed under the SIL Open Font License, Version 1.1. -This license is copied below, and is also available with a FAQ at: -http://scripts.sil.org/OFL - - ------------------------------------------------------------ -SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ------------------------------------------------------------ - -PREAMBLE -The goals of the Open Font License (OFL) are to stimulate worldwide -development of collaborative font projects, to support the font creation -efforts of academic and linguistic communities, and to provide a free and -open framework in which fonts may be shared and improved in partnership -with others. - -The OFL allows the licensed fonts to be used, studied, modified and -redistributed freely as long as they are not sold by themselves. The -fonts, including any derivative works, can be bundled, embedded, -redistributed and/or sold with any software provided that any reserved -names are not used by derivative works. The fonts and derivatives, -however, cannot be released under any other type of license. The -requirement for fonts to remain under this license does not apply -to any document created using the fonts or their derivatives. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright -Holder(s) under this license and clearly marked as such. This may -include source files, build scripts and documentation. - -"Reserved Font Name" refers to any names specified as such after the -copyright statement(s). - -"Original Version" refers to the collection of Font Software components as -distributed by the Copyright Holder(s). - -"Modified Version" refers to any derivative made by adding to, deleting, -or substituting -- in part or in whole -- any of the components of the -Original Version, by changing formats or by porting the Font Software to a -new environment. - -"Author" refers to any designer, engineer, programmer, technical -writer or other person who contributed to the Font Software. - -PERMISSION & CONDITIONS -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Font Software, to use, study, copy, merge, embed, modify, -redistribute, and sell modified and unmodified copies of the Font -Software, subject to the following conditions: - -1) Neither the Font Software nor any of its individual components, -in Original or Modified Versions, may be sold by itself. - -2) Original or Modified Versions of the Font Software may be bundled, -redistributed and/or sold with any software, provided that each copy -contains the above copyright notice and this license. These can be -included either as stand-alone text files, human-readable headers or -in the appropriate machine-readable metadata fields within text or -binary files as long as those fields can be easily viewed by the user. - -3) No Modified Version of the Font Software may use the Reserved Font -Name(s) unless explicit written permission is granted by the corresponding -Copyright Holder. This restriction only applies to the primary font name as -presented to the users. - -4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font -Software shall not be used to promote, endorse or advertise any -Modified Version, except to acknowledge the contribution(s) of the -Copyright Holder(s) and the Author(s) or with their explicit written -permission. - -5) The Font Software, modified or unmodified, in part or in whole, -must be distributed entirely under this license, and must not be -distributed under any other license. The requirement for fonts to -remain under this license does not apply to any document created -using the Font Software. - -TERMINATION -This license becomes null and void if any of the above conditions are -not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM -OTHER DEALINGS IN THE FONT SOFTWARE. +Copyright (c) 2009-2010, Understanding Limited (dave@understandinglimited.com) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/nationchains/static/fonts/cantarell-bold-demo.html b/src/nationchains/static/fonts/cantarell-bold-demo.html similarity index 99% rename from nationchains/static/fonts/cantarell-bold-demo.html rename to src/nationchains/static/fonts/cantarell-bold-demo.html index b5eb8f4..24558c4 100755 --- a/nationchains/static/fonts/cantarell-bold-demo.html +++ b/src/nationchains/static/fonts/cantarell-bold-demo.html @@ -6,11 +6,11 @@ diff --git a/nationchains/static/fonts/cantarell-bold-webfont.woff b/src/nationchains/static/fonts/cantarell-bold-webfont.woff similarity index 100% rename from nationchains/static/fonts/cantarell-bold-webfont.woff rename to src/nationchains/static/fonts/cantarell-bold-webfont.woff diff --git a/nationchains/static/fonts/cantarell-bold-webfont.woff2 b/src/nationchains/static/fonts/cantarell-bold-webfont.woff2 similarity index 100% rename from nationchains/static/fonts/cantarell-bold-webfont.woff2 rename to src/nationchains/static/fonts/cantarell-bold-webfont.woff2 diff --git a/setup/data/domain/apixpress/www/cdn/fonts/cantarell-bolditalic-demo.html b/src/nationchains/static/fonts/cantarell-bolditalic-demo.html similarity index 99% rename from setup/data/domain/apixpress/www/cdn/fonts/cantarell-bolditalic-demo.html rename to src/nationchains/static/fonts/cantarell-bolditalic-demo.html index 16a11e7..a4dbd5f 100755 --- a/setup/data/domain/apixpress/www/cdn/fonts/cantarell-bolditalic-demo.html +++ b/src/nationchains/static/fonts/cantarell-bolditalic-demo.html @@ -6,11 +6,11 @@ diff --git a/nationchains/static/fonts/cantarell-bolditalic-webfont.woff b/src/nationchains/static/fonts/cantarell-bolditalic-webfont.woff similarity index 100% rename from nationchains/static/fonts/cantarell-bolditalic-webfont.woff rename to src/nationchains/static/fonts/cantarell-bolditalic-webfont.woff diff --git a/nationchains/static/fonts/cantarell-bolditalic-webfont.woff2 b/src/nationchains/static/fonts/cantarell-bolditalic-webfont.woff2 similarity index 100% rename from nationchains/static/fonts/cantarell-bolditalic-webfont.woff2 rename to src/nationchains/static/fonts/cantarell-bolditalic-webfont.woff2 diff --git a/nationchains/static/fonts/cantarell-italic-demo.html b/src/nationchains/static/fonts/cantarell-italic-demo.html similarity index 99% rename from nationchains/static/fonts/cantarell-italic-demo.html rename to src/nationchains/static/fonts/cantarell-italic-demo.html index 755225d..0e525b6 100755 --- a/nationchains/static/fonts/cantarell-italic-demo.html +++ b/src/nationchains/static/fonts/cantarell-italic-demo.html @@ -6,11 +6,11 @@ diff --git a/nationchains/static/fonts/cantarell-italic-webfont.woff b/src/nationchains/static/fonts/cantarell-italic-webfont.woff similarity index 100% rename from nationchains/static/fonts/cantarell-italic-webfont.woff rename to src/nationchains/static/fonts/cantarell-italic-webfont.woff diff --git a/nationchains/static/fonts/cantarell-italic-webfont.woff2 b/src/nationchains/static/fonts/cantarell-italic-webfont.woff2 similarity index 100% rename from nationchains/static/fonts/cantarell-italic-webfont.woff2 rename to src/nationchains/static/fonts/cantarell-italic-webfont.woff2 diff --git a/nationchains/static/fonts/cantarell-regular-demo.html b/src/nationchains/static/fonts/cantarell-regular-demo.html similarity index 99% rename from nationchains/static/fonts/cantarell-regular-demo.html rename to src/nationchains/static/fonts/cantarell-regular-demo.html index fe19bce..de971ef 100755 --- a/nationchains/static/fonts/cantarell-regular-demo.html +++ b/src/nationchains/static/fonts/cantarell-regular-demo.html @@ -6,11 +6,11 @@ diff --git a/nationchains/static/fonts/cantarell-regular-webfont.woff b/src/nationchains/static/fonts/cantarell-regular-webfont.woff similarity index 100% rename from nationchains/static/fonts/cantarell-regular-webfont.woff rename to src/nationchains/static/fonts/cantarell-regular-webfont.woff diff --git a/nationchains/static/fonts/cantarell-regular-webfont.woff2 b/src/nationchains/static/fonts/cantarell-regular-webfont.woff2 similarity index 100% rename from nationchains/static/fonts/cantarell-regular-webfont.woff2 rename to src/nationchains/static/fonts/cantarell-regular-webfont.woff2 diff --git a/nationchains/static/fonts/generator_config.txt b/src/nationchains/static/fonts/generator_config.txt similarity index 100% rename from nationchains/static/fonts/generator_config.txt rename to src/nationchains/static/fonts/generator_config.txt diff --git a/nationchains/static/fonts/specimen_files/grid_12-825-55-15.css b/src/nationchains/static/fonts/specimen_files/grid_12-825-55-15.css similarity index 100% rename from nationchains/static/fonts/specimen_files/grid_12-825-55-15.css rename to src/nationchains/static/fonts/specimen_files/grid_12-825-55-15.css diff --git a/setup/data/domain/apixpress/www/cdn/fonts/specimen_files/specimen_stylesheet.css b/src/nationchains/static/fonts/specimen_files/specimen_stylesheet.css similarity index 99% rename from setup/data/domain/apixpress/www/cdn/fonts/specimen_files/specimen_stylesheet.css rename to src/nationchains/static/fonts/specimen_files/specimen_stylesheet.css index aecc43c..8217699 100755 --- a/setup/data/domain/apixpress/www/cdn/fonts/specimen_files/specimen_stylesheet.css +++ b/src/nationchains/static/fonts/specimen_files/specimen_stylesheet.css @@ -166,7 +166,7 @@ div.glyph_range { .white_blend { width: 100%; height: 61px; - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVkAAAA9CAYAAAAH4BojAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAO1JREFUeNrs3TsKgFAMRUE/eer+NxztxMYuEWQG3ECKwwUF58ycAKixOAGAyAKILAAiCyCyACILgMgCiCyAyAIgsgAiCyCyAIgsgMgCiCwAIgsgsgAiC4DIAogsACIL0CWuZ3UGgLrIhjMA1EV2OAOAJQtgyQLwjOzmDAAiCyCyAIgsQFtkd2cAEFkAkQVAZAHaIns4A4AlC2DJAiCyACILILIAiCzAV5H1dQGAJQsgsgCILIDIAvwisl58AViyAJYsACILILIAIgvAe2T9EhxAZAFEFgCRBeiL7HAGgLrIhjMAWLIAliwAt1OAAQDwygTBulLIlQAAAABJRU5ErkJggg==); + background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVkAAAA9CAYAAAAH4BojAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAO1JREFUeNrs3TsKgFAMRUE/eer+NxztxMYuEWQG3ECKwwUF58ycAKixOAGAyAKILAAiCyCyACILgMgCiCyAyAIgsgAiCyCyAIgsgMgCiCwAIgsgsgAiC4DIAogsACIL0CWuZ3UGgLrIhjMA1EV2OAOAJQtgyQLwjOzmDAAiCyCyAIgsQFtkd2cAEFkAkQVAZAHaIns4A4AlC2DJAiCyACILILIAiCzAV5H1dQGAJQsgsgCILIDIAvwisl58AViyAJYsACILILIAIgvAe2T9EhxAZAFEFgCRBeiL7HAGgLrIhjMAWLIAliwAt1OAAQDwygTBulLIlQAAAABJRU5ErkJggg===); position: absolute; bottom: 0; } diff --git a/nationchains/static/fonts/stylesheet.css b/src/nationchains/static/fonts/stylesheet.css similarity index 100% rename from nationchains/static/fonts/stylesheet.css rename to src/nationchains/static/fonts/stylesheet.css diff --git a/nationchains/static/img/avataranonymous.png b/src/nationchains/static/img/avataranonymous.png similarity index 100% rename from nationchains/static/img/avataranonymous.png rename to src/nationchains/static/img/avataranonymous.png diff --git a/nationchains/static/img/avataranonymous1.png b/src/nationchains/static/img/avataranonymous1.png similarity index 100% rename from nationchains/static/img/avataranonymous1.png rename to src/nationchains/static/img/avataranonymous1.png diff --git a/nationchains/static/img/avataranonymous2.png b/src/nationchains/static/img/avataranonymous2.png similarity index 100% rename from nationchains/static/img/avataranonymous2.png rename to src/nationchains/static/img/avataranonymous2.png diff --git a/nationchains/static/img/chartegraphique/codecouleur.png b/src/nationchains/static/img/chartegraphique/codecouleur.png similarity index 100% rename from nationchains/static/img/chartegraphique/codecouleur.png rename to src/nationchains/static/img/chartegraphique/codecouleur.png diff --git a/nationchains/static/img/chartegraphique/favicon.png b/src/nationchains/static/img/chartegraphique/favicon.png similarity index 100% rename from nationchains/static/img/chartegraphique/favicon.png rename to src/nationchains/static/img/chartegraphique/favicon.png diff --git a/nationchains/static/img/chartegraphique/logo_bgplein.png b/src/nationchains/static/img/chartegraphique/logo_bgplein.png similarity index 100% rename from nationchains/static/img/chartegraphique/logo_bgplein.png rename to src/nationchains/static/img/chartegraphique/logo_bgplein.png diff --git a/nationchains/static/img/chartegraphique/logo_bgtransparent.png b/src/nationchains/static/img/chartegraphique/logo_bgtransparent.png similarity index 100% rename from nationchains/static/img/chartegraphique/logo_bgtransparent.png rename to src/nationchains/static/img/chartegraphique/logo_bgtransparent.png diff --git a/nationchains/static/img/chartegraphique/logocarre_bgplein.png b/src/nationchains/static/img/chartegraphique/logocarre_bgplein.png similarity index 100% rename from nationchains/static/img/chartegraphique/logocarre_bgplein.png rename to src/nationchains/static/img/chartegraphique/logocarre_bgplein.png diff --git a/nationchains/static/img/chartegraphique/logocarre_vertical_bgplein.png b/src/nationchains/static/img/chartegraphique/logocarre_vertical_bgplein.png similarity index 100% rename from nationchains/static/img/chartegraphique/logocarre_vertical_bgplein.png rename to src/nationchains/static/img/chartegraphique/logocarre_vertical_bgplein.png diff --git a/nationchains/static/img/chartegraphique/planchelogo.svg b/src/nationchains/static/img/chartegraphique/planchelogo.svg similarity index 100% rename from nationchains/static/img/chartegraphique/planchelogo.svg rename to src/nationchains/static/img/chartegraphique/planchelogo.svg diff --git a/nationchains/static/img/imgtg.png b/src/nationchains/static/img/imgtg.png similarity index 100% rename from nationchains/static/img/imgtg.png rename to src/nationchains/static/img/imgtg.png diff --git a/nationchains/static/img/nations/ants/antsNation.svg b/src/nationchains/static/img/nations/ants/antsNation.svg similarity index 100% rename from nationchains/static/img/nations/ants/antsNation.svg rename to src/nationchains/static/img/nations/ants/antsNation.svg diff --git a/nationchains/static/img/site-en-maintenance.png b/src/nationchains/static/img/site-en-maintenance.png similarity index 100% rename from nationchains/static/img/site-en-maintenance.png rename to src/nationchains/static/img/site-en-maintenance.png diff --git a/nationchains/testnetwork.html b/src/nationchains/testnetwork.html similarity index 100% rename from nationchains/testnetwork.html rename to src/nationchains/testnetwork.html diff --git a/src/routes/messages.js b/src/routes/messages.js new file mode 100755 index 0000000..0bc7669 --- /dev/null +++ b/src/routes/messages.js @@ -0,0 +1,65 @@ +const express = require('express') +const path = require('path') +// Classes +const Messages = require('../models/Messages.js') +// Middlewares ( prefix, object ) => { +const checkHeaders = require('../middlewares/checkHeaders') +const isAuthenticated = require('../middlewares/isAuthenticated') +const hasAccessrighton = require('../middlewares/hasAccessrighton') +const router = express.Router() + +const logger = require('../core/logger') + +router.post('/', checkHeaders, (req, res) => { + /* + add message to (no authentification and accessright needs) : + a tribeid or uuid => create a contact based on email.json or phone.json or email_phone.json + if req.body.orderuuid exist then it store the req.body in /orders/orderuuid.json an order with state = order + */ + // check if a receiver is well identify if not then it send message to all user tribeid to inform ** + if (!req.body.desttribeid) req.body.desttribeid = req.session.header.xworkon + if (!req.body.lang) req.body.lang = req.session.header.xlang + logger.info('/messages t send for ', req.session.header.xworkon) + // logger.info(' Content: ',req.body); + const result = Messages.postinfo(req.body) + res.status(result.status) + .send(result.data) +}) + +router.put('/:objectname/:uuid', checkHeaders, isAuthenticated, (req, res) => { + // message that will create an object and sendback an email. + // if objectnane/uuid_lg.json exist ans accessright is ste to U for the user then it replace object data with req.body.key value + // if does not exist and accessright C then it create it with uuid + // then if req.body.tplmessage => render email with data + // No data management are done here, if need you can add plugin to create a workflow based object + // if need specific data check => req.body.callback={tribeidpugin,pluginname,function} will run pluginname.function(data) add data run specific stuf before saved the message object in /objectname/data.uuid_lg/json + let result + logger.info('object', req.params.objectname) + if (req.params.objectname === 'notifications') { + // uuid is a timestamp + req.body.time = req.params.uuid + result = Messages.notification(req.body, req.session.header) + } else { + req.body.uuid = req.params.uuid + req.body.object = req.params.objectname + result = Messages.object(req.body, req.session.header) + } + // logger.info( 'result', result ); + res.status(result.status) + .json(result.data) +}) + +router.get('/user', checkHeaders, isAuthenticated, (req, res) => { + // run agregate for tribeid concerned + // + logger.info('request notifiation for user', req.session.header.xpaganid) + const app = { + tribeid: req.session.header.xapp.split(':')[0], + website: req.session.header.xapp.split(':')[1], + lang: req.session.header.xlang + } + res.send(Messages.request(req.session.header.xtribe, req.session.header.xpaganid, + req.app.locals.tokens[req.session.header.xpaganid].ACCESSRIGHTS, app)) +}) + +module.exports = router diff --git a/src/routes/nationchains.js b/src/routes/nationchains.js new file mode 100755 index 0000000..65ad51d --- /dev/null +++ b/src/routes/nationchains.js @@ -0,0 +1,32 @@ +const express = require('express') +const config = require('../tribes/townconf.js') + +// Classes +const Nationchains = require('../models/Nationchains.js') +// Middlewares +const checkHeaders = require('../middlewares/checkHeaders') +const isAuthenticated = require('../middlewares/isAuthenticated') +const hasAccessrighton = require('../middlewares/hasAccessrighton') +const router = express.Router() + +const logger = require('../core/logger') + +/* +Manage the social world + +@Todo + +Manage a new nation +A major create a nation with at least a town => nation:{name, towns:[]} contracts/nationname.js + contracts/townsname.js +Manage a new towns in a nation => update nation:[nationname:towns:[]} contracts/townname.js + +*/ +router.post('/push', checkHeaders, (req, res) => { + // Get information from other apixtribe instance in req.body + // check req.body.hashnext => means this is a candidate to validate next block + // + // return it's own information back with the last call to Nationchains.synchronize() + res.send({ status: 200, payload: { moreinfo: fs.readFileSync(`${config.tribes}/${config.mayorId}/nationchains/nodes/${config.rootURL}`, 'utf-8') } }) +}) + +module.exports = router diff --git a/src/routes/odmdb.js b/src/routes/odmdb.js new file mode 100644 index 0000000..51ab090 --- /dev/null +++ b/src/routes/odmdb.js @@ -0,0 +1,23 @@ +/* eslint-disable no-unused-vars */ + +const express = require('express') +const glob = require('glob') +const path = require('path') +// Classes +const Odmdb = require('../models/Odmdb.js') +// Middlewares +const checkHeaders = require('../middlewares/checkHeaders') +const isAuthenticated = require('../middlewares/isAuthenticated') +const hasAccessrighton = require('../middlewares/hasAccessrighton') +const router = express.Router() + +const logger = require('../core/logger') + +router.get('/searchauth/:objectname/:question', checkHeaders, isAuthenticated, (req, res) => { + logger.info('route referentials get all language' + req.params.objectname + '-' + req.params.question) + const getref = Referentials.getref(true, req.params.source, req.params.idref, req.session.header.xworkon, req.session.header.xlang) + // Return any status the data if any erreur return empty object + res.jsonp(getref.payload.data) +}) + +module.exports = router diff --git a/src/routes/outputs.js b/src/routes/outputs.js new file mode 100755 index 0000000..05069d3 --- /dev/null +++ b/src/routes/outputs.js @@ -0,0 +1,62 @@ +// Upload de file +const express = require('express') +const fs = require('fs-extra') +// Classes +const UploadFile = require('../models/UploadFiles') +const Outputs = require('../models/Outputs') +// const Outputstest = require('../models/Outputstest'); +// Middlewares +const checkHeaders = require('../middlewares/checkHeaders') +const isAuthenticated = require('../middlewares/isAuthenticated') +const router = express.Router() + +const logger = require('../core/logger') + +router.post('/ggsheet2json', checkHeaders, async (req, res) => { + logger.info('route outputs sheet to json') + const result = await Outputs.ggsheet2json(req.body, req.session.header) + res.send(result) +}) + +// checkHeaders, isuploadFileValid +router.post('/msg', checkHeaders, async (req, res) => { + logger.info('route outputs msg post ') + const envoi = await Outputs.generemsg(req.body, req.session.header) + res.status(envoi.status) + .send({ + payload: envoi.payload + }) +}) +/* test functionnalité +router.post('/msgtest', checkHeaders, isemailValid, async (req, res) => { + logger.info('route outputs msg post en test'); + const envoi = await Outputstest.generemsg(req.body, req.session.header); + res.status(envoi.status).send({ + payload: envoi.payload + }); +}); +*/ +router.post('/template', checkHeaders, (req, res) => { + logger.info('route outputs post de fichier template ') + // a callback can be pass to req.body to run a specific process after upload + const saveFile = UploadFile.addjson(req.body, req.session.header) + logger.info(saveFile) + res.send(saveFile) + // res.send({ status: 200, payload: { info: 'fine' } }); +}) + +router.post('/pdf', checkHeaders, (req, res) => { + logger.info('route outputs pdf post') + Outputs.generepdf(req.body, req.session.header) + .then((doc) => { + res.status(doc.status) + .download(doc.payload.data.path, doc.payload.data.name) + }) + .catch((err) => { + logger.info(err) + res.status(err.status) + .send({ payload: err.payload }) + }) +}) + +module.exports = router diff --git a/src/routes/pagans.js b/src/routes/pagans.js new file mode 100755 index 0000000..5d20e80 --- /dev/null +++ b/src/routes/pagans.js @@ -0,0 +1,218 @@ +const express = require('express') +const path = require('path') + +// Classes +const Pagans = require('../models/Pagans.js') +// Middlewares +const checkHeaders = require('../middlewares/checkHeaders') +const isAuthenticated = require('../middlewares/isAuthenticated') +const hasAccessrighton = require('../middlewares/hasAccessrighton') +const router = express.Router() + +const logger = require('../core/logger') + +/* +models/Pagans.js +Managed: +/data/tribee/client-Id/users/uuid.json +/searchindex/emails.json {email:uuid} + /login.json {login:uuid} + /uids.json {uuid;[[ + login, + email, + encrypted psw, + accessrights]} + +ACCESSRIGHTS = { +app:{"tribeid:appname":"profil"}, +data:{"tribeid":{object:"CRUDO"}} +} +ACCESSRIGHTS is store into the token and is load into req.session.header.accessrights by hasAccessrighton() middleware + +appname is a website space object /sitewebsrc/appname +website live is strored into /dist source in /src + +This can be managed by maildigitcreator or not. +apixtribe/sitewebs/webapp is the webinterface of apixtribe + +profil: admin / manager / user are key word to give specific access to data into model. Any kind of other profil can exist. It is usefull to manage specific menu in an app. +It is also possible to authorize update a field's object depending of rule into dataManagement/object/ +{ field:X + nouserupdate: "!(['admin','manager'].includes(contexte.profil))", +} + +data allow a user to access tribeid with Create Read Update Delete Own (CRUDO) on each object of a tribeid independantly of any app. + +Create allow to create a new object respecting rules defined into /referentials/dataManagement/object/name.json +Update idem +Delete idem +Owner means it can be Write/Delete if field OWNER contain the UUID that try to act on this object. Usefull to allow someone to fully manage its objects. + +*/ +router.get('/isauth', checkHeaders, isAuthenticated, (req, res) => { + if (req.session.header.xpaganid === '1') { + return res.status(401) + .send({ info: 'not authenticate' }) + } else { + return res.status(200) + .send({ info: 'well authenticated' }) + } +}) +router.post('/login', checkHeaders, async (req, res) => { + // logger.info('POST /users/login with: ', req.app.locals.header); + /* + Check un mot de passe pour un login pour obtenir un token d'authentification + valable 1 hour, 1 day + @header + @body.LOGIN + @body.PASSWORD + @checkpsw = true check si les 2 mot de passe cryptés correspondent + false bypass le contrôle et permet de générer un token + utile le temps de reinitialisé son mot de passe. + @return + */ + logger.info('login for ', req.body, 'in', req.session.header) + const log = await Pagans.loginUser(req.session.header, req.body, true) + logger.info('log user login', log) + if (log.status === 200) { + // update req.app.locals.tokens for this uuid just after login success then next isAuth will be valid + req.app.locals.tokens[log.data.user.UUID] = { + TOKEN: log.data.user.TOKEN, + ACCESSRIGHTS: log.data.user.ACCESSRIGHTS + } + logger.info(req.app.locals) + } + return res.status(log.status) + .send(log.data) +}) + +router.get('/getlinkwithoutpsw/:email', checkHeaders, async (req, res) => { + /* + Permet pour un email existant de renvoyer un email avec un lien valable 1h + @email est le compte pour lequel on demande un accès + Réponse: + Si email n'existe pas on n'envoie pas d'email + Si email existe on envoie un email avec un lien dont le token est valable 1h + + @return + {status:200 ou erreur , + payload:{ + info:[list de key to appear in correct requester langue], + model:'Pagans', + moreinfo: 'texte pour log ' + } + } + */ + logger.info(`GET /users/getlinkwithoutpsw for email: ${req.params.email} tribeid :${req.header('X-Client-Id')}`) + if (!req.params.email) { + return res.status(404) + .send({ + info: ['emailmissing'], + model: 'Pagans' + }) + } else { + try { + const getlink = await Pagans.getlinkwithoutpsw(req.params.email, req.session.header) + logger.info('getlink', getlink) + // met à jour le token créer pour le uuid + req.app.locals.tokens[getlink.data.info.xuuid] = getlink.data.info.token + // attention si on relance le serveur le token temporaire est perdu + return res.status(getlink.status) + .send(getlink.data) + } catch (err) { + logger.info(err) + return res.status(500) + .send({ info: ['errServer'], model: 'Pagans' }) + } + } +}) +router.post('/register', checkHeaders, async (req, res) => { + logger.info(`POST /users for ${req.session.header.xtribe}`) + if (req.session.header.xauth === '123123') { + // Creation d'un utilisateur avec information de base aucun droit + // On modifie le contenu du form pour n egarder que login/email et psw + // pour le client_id permet de traiter un user en attente de validation + logger.info('req du post', req) + } +}) +router.get('/info/:listindex', checkHeaders, isAuthenticated, hasAccessrighton('users', 'R'), async (req, res) => { + logger.info(`get users info on tribeid ${req.session.header.xworkon} for ${req.params.listindex} with accessright`, req.session.header.accessrights.data) + const result = await Pagans.getinfoPagans(req.session.header.xpresworkon, req.session.header.accessrights, req.params.listindex) + res.status(result.status) + .send(result.data) +}) +router.get('/list/:filter/:field', checkHeaders, isAuthenticated, hasAccessrighton('users', 'R'), async (req, res) => { + logger.info('GET /users/list/filtre/champs list for ' + req.session.header.xworkon) + if ( + ['admin', 'manager'].includes(req.session.header.decodetoken['apps' + req.session.header.xworkon + 'profil'])) { + try { + const userslist = await Pagans.getUserlist(req.session.header, req.params.filter, req.params.field) + logger.info('userslist', userslist) + if (userslist.status === 200) { + return res.status(userslist.status) + .send(userslist.data) + } + } catch (err) { + logger.info(err) + return res.status(400) + .send({ info: 'erreur' }) + } + } else { + res.status(403) + .send({ + info: ['forbiddenAccess'], + model: 'Pagans' + }) + } +}) +router.get('/uuid/:id', checkHeaders, isAuthenticated, hasAccessrighton('users', 'R'), async (req, res) => { + logger.info(`GET /users/uuid/${req.params.id}`) + // logger.info('req.app.locals: ', req.app.locals); + // logger.info('req.session', req.session); + const result = await Pagans.getUser(req.params.id, req.session.header.xworkon, req.session.header.accessrights) + res.status(result.status) + .send(result.data) +}) +router.put('/chgpsw/:id', checkHeaders, isAuthenticated, async (req, res) => { + logger.info(`PUT update /users/chgpsw/${req.params.id}`) + try { + const majpsw = await Pagans.updateUserpassword(req.params.id, req.session.header, req.body) + res.status(majpsw.status) + .send(majpsw.data) + } catch ({ + status, + data + }) { + res.status(status) + .send(data) + } +}) +router.post('/uuid', checkHeaders, isAuthenticated, hasAccessrighton('users', 'C'), async (req, res) => { + logger.info('POST /users create for ' + req.session.header.xworkon, req.body) + const usercreate = await Pagans.createUser(req.session.header, req.body) + return res.status(usercreate.status) + .send(usercreate.data) +}) +router.put('/uuid/:id', checkHeaders, isAuthenticated, hasAccessrighton('users', 'U'), async (req, res) => { + logger.info(`PUT update /users/${req.params.id}`) + // logger.info('req.app.locals: ', req.app.locals); + // logger.info('req.session', req.session); + try { + const majUser = await Pagans.updateUser(req.params.id, req.session.header, req.body) + res.status(majUser.status) + .send(majUser.data) + } catch ({ + status, + data + }) { + res.status(status) + .send(data) + } +}) +router.delete('/uuid/:id', checkHeaders, isAuthenticated, hasAccessrighton('users', 'D'), (req, res) => { + logger.info(`DELETE /users/uuid/${req.params.id}`) + const result = Pagans.deleteUser(req.params.id, req.session.header) + res.status(result.status) + .send(result.data) +}) +module.exports = router diff --git a/src/routes/referentials.js b/src/routes/referentials.js new file mode 100755 index 0000000..8351dca --- /dev/null +++ b/src/routes/referentials.js @@ -0,0 +1,97 @@ +// Upload de file +const express = require('express') +const glob = require('glob') +const path = require('path') +// Classes +const Referentials = require('../models/Referentials') +// Middlewares +const checkHeaders = require('../middlewares/checkHeaders') +const isAuthenticated = require('../middlewares/isAuthenticated') +const hasAccessrighton = require('../middlewares/hasAccessrighton') +const router = express.Router() + +const logger = require('../core/logger') + +/* + * keylist = list of key at 1st level in clientconf.json separated by _ + * we use header.xworkon + * To manage AccesRight obkect referentials does not follow the same logic than other object this is why + */ +router.get('/clientconf/:keylist', checkHeaders, isAuthenticated, (req, res) => { + // retourne liste info (non sensible) du tribeid inside headers.xworkon sur keylist ="key1_key2" + /* + if (req.session.header.accessrights.data[ "Alltribeid" ] && req.session.header.accessrights.data[ "Alltribeid" ].referentials.includes('R') ; + */ + logger.info(`get clientconf for ${req.session.header.xworkon} on ${req.params.keylist}`) + let dataref = {} + if (req.params.keylist.split('_') + .length > 0) { + const ref = Referentials.clientconf(req.session.header.xworkon, req.params.keylist.split('_')) + if (ref.status === 200) { + dataref = ref.payload.data + } else { + logger.info('erreur ', ref) + } + } + logger.info('envoie en jsonp: dataref') + res.jsonp(dataref) +}) +router.get('/clientconfglob', checkHeaders, isAuthenticated, (req, res) => { + res.jsonp(Referentials.clientconfglob() + .payload.data) +}) +router.get('/contentlist/:source', checkHeaders, isAuthenticated, + (req, res) => { + const payload = [] + logger.info(req.params.source, `${config.tribes}/${req.session.header.xworkon}/referentials/dataManagement/${req.params.source}/*.json`) + glob.sync(`${config.tribes}/${req.session.header.xworkon}/referentials/dataManagement/${req.params.source}/*.json`) + .forEach(f => { + payload.push(path.basename(f, '.json')) + }) + res.json(payload) + }) +router.get('/contentfull/:source/:idref', checkHeaders, isAuthenticated, + (req, res) => { + // only for data and object + logger.info('route referentials get all language' + req.params.source + '-' + req.params.idref) + const getref = Referentials.getref(true, req.params.source, req.params.idref, req.session.header.xworkon, req.session.header.xlang) + // Return any status the data if any erreur return empty object + res.jsonp(getref.payload.data) + }) +router.get('/content/:source/:idref', checkHeaders, isAuthenticated, + (req, res) => { + logger.info('route referentials get ' + req.params.source + '-' + req.params.idref) + const getref = Referentials.getref(false, req.params.source, req.params.idref, req.session.header.xworkon, req.session.header.xlang) + res.jsonp(getref.payload.data) + }) +// get with no authentification +router.get('/contentnoauth/:source/:idref', checkHeaders, + (req, res) => { + logger.info('route referentials get ' + req.params.source + '-' + req.params.idref) + // @TODO check access right in clientconf before sending back json file + const getref = Referentials.getref(false, req.params.source, req.params.idref, req.session.header.xworkon, req.session.header.xlang) + res.jsonp(getref.payload.data) + }) +router.get('/lg', (req, res) => { + logger.info(req.headers['accept-language']) + let lg = '??' + if (req.headers['accept-language'] && req.headers['accept-language'].split(',') + .length > 0) { + lg = req.headers['accept-language'].split(',')[0] + } + res.json({ lg }) +}) +router.put('/content/:source/:idref', checkHeaders, isAuthenticated, (req, res) => { + logger.info(`route put content for ${req.params.idref} that is a ${req.params.source}`) + const putref = Referentials.putref(req.params.source, req.params.idref, req.session.header.xworkon, req.body) + return res.status(putref.status) + .send({ payload: putref.payload }) +}) +// hasAccessrighton( 'referentials', 'U' ) +router.get('/updatefull', checkHeaders, isAuthenticated, hasAccessrighton('referentials', 'U'), (req, res) => { + logger.info('route get to force update content updatefull is accessrighton') + const updtref = Referentials.updatefull(req.session.header.xworkon) + return res.status(updtref.status) + .send({ payload: updtref.payload }) +}) +module.exports = router diff --git a/src/routes/tags.js b/src/routes/tags.js new file mode 100755 index 0000000..8691ed9 --- /dev/null +++ b/src/routes/tags.js @@ -0,0 +1,30 @@ +// Installation d'un tag +/* + +*/ +// Upload de file +const express = require('express') +// Classes +const Tags = require('../models/Tags') +// Middlewares +const router = express.Router() + +const logger = require('../core/logger') + +router.get('/:filename', (req, res) => { + // logger.info('route tags get ', req.params.filename); + const savetag = Tags.getfile(req.params.filename, req) + if (savetag.status === 200) { + res.sendFile(savetag.payload.filename) + } else { + res.status(savetag.status) + .send({ payload: savetag.payload }) + } +}) +router.post('/:tribeid', (req, res) => { + // logger.info('route tags post ', req.params.tribeid); + const savetag = Tags.savehits(req) + res.status(200) + .send('') +}) +module.exports = router diff --git a/src/routes/tribes.js b/src/routes/tribes.js new file mode 100755 index 0000000..3dc3fdb --- /dev/null +++ b/src/routes/tribes.js @@ -0,0 +1,400 @@ +/* eslint-disable no-unused-vars no-unused-expressions */ + +const express = require('express') +const fs = require('fs-extra') +const path = require('path') +const config = require('../tribes/townconf.js') + +// Classes +const Tribes = require('../models/Tribes.js') +// Middlewares +const checkHeaders = require('../middlewares/checkHeaders') +const isAuthenticated = require('../middlewares/isAuthenticated') +const hasAccessrighton = require('../middlewares/hasAccessrighton') +const router = express.Router() + +const logger = require('../core/logger') + +router.get('/clientconf/:tribeid', checkHeaders, isAuthenticated, (req, res) => { + /* + get a clientconf.json for a tribeid depending of user accessright + if tribeid === all and user is admin of apixtribe => get /tmp/clientconfglob.json + req.session.header.accessrights, req.session.header.apixpaganid + */ + logger.info(`Tribes/clientconf for tribeid:${req.params.tribeid}`) + if (req.params.tribeid === 'all' && req.session.header.accessrights.data.apixtribe && req.session.header.accessrights.data.apixtribe.tribeid && req.session.header.accessrights.data.apixtribe.tribeid.includes('R')) { + res.status(200) + .send({ moreinfo: fs.readJsonSync(`${config.tmp}/clientconfglob.json`, 'utf-8') }) + return + } + if (req.session.header.accessrights.data[req.params.tribeid] && + req.session.header.accessrights.data[req.params.tribeid].tribeid && + req.session.header.accessrights.data[req.params.tribeid].tribeid.includes('R') && + fs.existsSync(`${config.tribes}/${req.params.tribeid}/clientconf.json`)) { + // const conftribeid = { moreinfo: {} } + // conftribeid.moreinfo[ req.params.tribeid ] = fs.readJsonSync( `${config.tribes}/${req.params.tribeid}/clientconf.json`, 'utf-8' ); + res.status(200) + .send({ moreinfo: [fs.readJsonSync(`${config.tribes}/${req.params.tribeid}/clientconf.json`, 'utf-8')] }) + return + } + // if not authorized or dos not exist return empty + // no specific message is send for security reason (check only log) + res.status(403) + .send({ info: ['forbidenAccess'], models: 'Tribes' }) + .end() +}) +router.put('/', checkHeaders, isAuthenticated, (req, res) => { + logger.info('Create a new tribeid, with a useradmin') + logger.info(' send data = clientconf.json with all parameter.') + // !!!!! check for security any ; \n or so because data can be used into shell + const add = Tribes.create(req.body) + res.status(add.status) + .send(add.payload) +}) +router.delete('/archivetribeid/:tribeid', checkHeaders, isAuthenticated, (req, res) => { + logger.info('request archive tribeid') + const archive = Tribes.archive(req.params.tribeid) + res.status(archive.status) + .send(archive.payload) +}) +router.post('/spaceweb', checkHeaders, isAuthenticated, (req, res) => { + // !!!!! check for security any ; \n or so because data can be used into shell + logger.info('Create a new webapp for xworkon ') + req.body.tribeid = req.session.header.xworkon + const add = Tribes.addspaceweb(req.body) + res.status(add.status) + .send(add.payload) +}) +router.get('/spaceweb/components/:tribeid/:website/:key', checkHeaders, (req, res) => { + // check if key is valid before continue + // exemple: get Tribes/spaceweb/components/ndda/mesa/123?rep=appmesatable/appsimpletable.mustache + const file = `${config.tribes}/${req.params.tribeid}/spacedev/${req.params.website}/src/ctatic/components/${req.query.path}` + logger.info(`Request components file from ${file}`) + if (fs.existsSync(file)) { + res.sendFile(file) + } else { + res.send(`console.error("Missing components file in ${req.params.tribeid}/spacedev/${req.params.website}/src/ctatic/components/${req.query.path}");`) + } +}) +router.get('/plugins/:tribeid/:pluginname/:key/:filename', (req, res) => { + // No accessright possible cause it is load on the fly + // @todo Check key to authorize access to the plugin (key comme from user ACCESSRIGHTS[tribeid plugin owner:pluginname]).key + // return a file into /:tribeid owner of plugin/plugins/:pluginname/components/:filename + // if not exist or invalid key then return console.error + const file = `${config.tribes}/${req.params.tribeid}/plugins/${req.params.pluginname}/components/${req.params.filename}` + logger.info('Tribes/plugins/ ', file) + if (fs.existsSync(file)) { + res.sendFile(file) + } else { + res.send(`console.error("Missing plugin file in ${req.params.tribeid}/plugins/${req.params.pluginname}/components/${req.params.filename}");`) + } +}) + +router.get('/dirls', checkHeaders, isAuthenticated, (req, res) => { + // url /Tribes/dirls?rep=referentials/dataManagement + // request information about a req.query.rep from header xworkon/ + // return + // {file:[{}],dir:[{}]} + // @todo check if isAuthorized and exist + + logger.info('request dirls', `${config.tribes}/${req.session.header.xworkon}/${req.query.rep}`) + if (!fs.existsSync(`${config.tribes}/${req.session.header.xworkon}/${req.query.rep}`)) { + res.status(404) + .send({ info: ['dirnotexist'], model: 'Tribes' }) + } + const info = Tribes.dirls(req.session.header.xworkon, req.query.rep) + logger.info(info) + res.status(info.status) + .send(info.payload) +}) +router.delete('/ls', checkHeaders, isAuthenticated, (req, res) => { + // check Accessright with D or O on each + // url /Tribes/ls + // req.body.files=[listfiles file to delete ] + const authfiles = Tribes.checkaccessfiles(req.body, 'D', req.session.header.accessrights, req.session.header.apixpaganid) + authfiles.ok.forEach(f => { + fs.remove(`${config.tribes}/${f}`) + }) + res.status(200) + .send({ info: ['fileauthdeleted'], models: 'Tribes', moreinfo: authfiles }) +}) +router.put('/sendjson', checkHeaders, isAuthenticated, (req, res) => { + // req.body = {object:spacedev, path:website/src/data/tpldataname_lg.json, data:{...}} + // logger.info( req.body ) + const dest = `${config.tribes}/${req.session.header.xworkon}/${req.body.object}/${req.body.path}` + logger.info(`Send json to saved to ${dest}`) + if (!(req.body.object && fs.existsSync(`${config.tribes}/${req.session.header.xworkon}/${req.body.object}`))) { + res.status('404') + .send({ + info: ['objectmissiong'], + models: 'Tribes', + moreinfo: `object: ${req.body.object} does not exist req.body must {object, data, path} into data ${req.session.header.xworkon}/${req.body.object}` + }) + } else { + if (fs.existsSync(`${config.tribes}/${req.session.header.xworkon}/${req.body.object}/${req.body.path}`)) { + // exist so can be update check accessright update on this + hasAccessrighton(req.body.object, 'U') + } else { + hasAccessrighton(req.body.object, 'C') + } + fs.outputJsonSync(dest, req.body.data) + res.status(200) + .send({ info: ['filesaved'], models: 'Tribes' }) + } +}) +router.post('/downloadls', checkHeaders, isAuthenticated, (req, res) => { + // midlleware hasAccessrighton.js is not apply here only to access/update/create information inside an object + // to get file a user need accessrights to data: object: R or to Own it + // or if exist a .info.json into folder get shared as R in uuid + + // req.body contain list of path file or folder if only 1 file then download it, otherwise zip list and send zip file + + const authfiles = Tribes.checkaccessfiles(req.body.files, 'R', req.session.header.accessrights, req.session.header.xpaganid) + if (authfiles.ok.length === 1) { + // bidouille en attendnat de faire un .zip binaire propre + if (!authfiles.ok[0].includes('.xml')) { + res.status(200) + .download(`${config.tribes}/${authfiles.ok[0]}`, authfiles.ok[0]) + } else { + fs.copySync(`${config.tribes}/${authfiles.ok[0]}`, `${config.tribes}/${config.mayorId}/www/app/webapp/static/tmp/${authfiles.ok[0]}`) + } + } else if (authfiles.ok.length > 1) { + // on zip et on envoie + // res.status( 200 ) + // .download( `${config.tribes}/${authfiles.ok[0]}`, authfiles.ok[ 0 ]) + res.status(200) + .attachment(`${config.tribes}/${authfiles.ok[0]}`) + } else { + req.body.filepon + res.status(403) + .send('Forbidden access') + } +}) +router.post('/upfilepond', checkHeaders, isAuthenticated, (req, res) => { + logger.info('post /Tribes/uploadfilepond') + // Store file and return a unique id to save button + // that provide folder where to store it + const formidable = require('formidable') + const form = formidable({ multiples: false }) + form.parse(req, (err, fields, files) => { + if (err) { + next(err) + return + } + // logger.info( 'fields',fields); + // fileMetadaObject send + const context = JSON.parse(fields.filepond) + const idfile = files.filepond.path + let name = files.filepond.name + const subfolder = context.subfolder + name = name.replace(/[ ,'"’]/g, '_') + // logger.info( 'files.filepond:', files.filepond ); + logger.info(idfile, `${config.tribes}/${req.session.header.xworkon}/www/${subfolder}/${name}`) + // On le supprime s'il existe deja + fs.removeSync(`${config.tribes}/${req.session.header.xworkon}/www/${subfolder}/${name}`) + // mv tmp + fs.moveSync(idfile, `${config.tribes}/${req.session.header.xworkon}/www/${subfolder}/${name}`) + // res.status(200).send({models:"Tribes",info:["Savedsuccess"],moreinfo:{id:file.filepond.path}}) + // return for filepond + res.writeHead(200, { 'Content-Type': 'text/plain' }) + res.end(idfile) + }) +}) +router.delete('/file', checkHeaders, isAuthenticated, (req, res) => { + // src = objectfolder with accessright/... + // hasAccessrighton( "www", "D" ), + if (!req.query.src) { + res.status(404) + .send({ info: ['deleteerror'], models: 'Tribes', moreinfo: 'your del req need a src' }) + return + } + ; + hasAccessrighton(req.query.src.split('/')[0], 'D') + logger.info('Remove file', `${config.tribes}/${req.session.header.xworkon}/${req.query.src}`) + logger.info(req.body) + fs.removeSync(`${config.tribes}/${req.session.header.xworkon}/${req.query.src}`) + res.status(200) + .send({ info: ['Successfullremove'], models: 'Tribes' }) +}) +router.post('/uploadfile', checkHeaders, isAuthenticated, (req, res) => { + logger.info('upload a file ') + /* Authentification is needed to get a TOKEN + curl -X POST -H "xtribe: apixtribe" -H "xworkon: pvmsaveurs" -H "xlang: fr" -H "xpaganid: 1" -H "xauth: 1" -H "xapp: pvmsaveurs:pvmsaveurs" -H "Content-Type: application/json" -d '{"LOGIN":"adminapixtribe","PASSWORD":"Trze3aze!"}' http://pvmsaveurs.pvmsaveurs.fr/app/users/login + if exist replace xpaganidTOKEN with payload.TOKEN value + + curl -H "xtribe: pvmsaveurs" -H "xworkon: pvmsaveurs" -H "xlang: fr" -H "xpaganid: adminapixtribe" -H "xauth: xpressuuisToken" -H "xapp: pvmsaveurs:pvmsaveurs" -F 'data=@filename.xx' http://pvmsaveurs.pvmsaveurs.fr/app/Tribes/uploadfile + */ + const formidable = require('formidable') + const form = formidable({ multiples: false }) + form.parse(req, function (err, fields, files) { + // logger.info( files.data ) + const oldPath = files.data.path + const newPath = `${config.tribes}/${req.session.header.xworkon}/${clientconf.uploadzip[files.data.name].dest}` + logger.info('oldPath', oldPath) + logger.info('newPath', newPath) + const rawData = fs.readFileSync(oldPath) + fs.outputFile(newPath, rawData, function (err) { + if (err) { + logger.info(err) + return res.status(405) + .send({ + info: ['savederror'], + models: 'Tribes', + moreinfo: 'your file was not able to be saved into the server' + }) + } else { + return res.status(200) + .send({ + info: ['successfullsent'], + models: 'Tribes' + }) + } + }) + }) +}) +router.post('/uploadzip', checkHeaders, (req, res) => { + logger.info('uploadzip a file ') + + /* no authentification to upload a zip filename into /tribes/${xworkon}/${clientconf.uploadzip[filename].dest} + unzip it using the password ${clientconf.uploadzip[filename].psw + if no error then run the callback ${clientconf.uploadzip[filename].callback + but a password to unzip + in clientconf.json need to be set + "uploadzip": { + "articlesTribespvm.zip": { + "comment": "unzip with overwrite if same name", + "psw": "azPI1209qtrse", + "dest": "importexport/tmp", + "unzipoption": "-aoa", + "callback": "importexport/integrationitem.js" + } + }, + Example: + cd where zip file is stored + curl -H "xtribe: pvmsaveurs" -H "xworkon: pvmsaveurs" -H "xlang: fr" -H "xpaganid: adminapixtribe" -H "xauth: 1" -H "xapp: pvmsaveurs:pvmsaveurs" -F 'data=@articlesTribespvm.zip' http://pvmsaveurs.pvmsaveurs.fr/app/Tribes/uploadzip + + */ + const clientconf = fs.readJSONSync(`${config.tribes}/${req.session.header.xworkon}/clientconf.json`) + if (!clientconf.uploadzip) { + return res.status('404') + .send({ + info: ['missconf'], + models: 'Tribes', + moreinfo: `no uploadzip in clientconf for ${req.session.header.xworkon} please contact apixtribe admin ` + }) + } + ; + const uploadzip = clientconf.uploadzip + const formidable = require('formidable') + const form = formidable({ multiples: false }) + form.parse(req, function (err, fields, files) { + // logger.info( files.data ) + const oldPath = files.data.path + if (!Object.keys(clientconf.uploadzip) + .includes(files.data.name)) { + return res.status(403) + .send({ + info: ['notAllowed'], + models: 'Tribes', + moreinfo: `file ${files.data.name} not allowed to be upload` + }) + } else { + logger.info('context:', clientconf.uploadzip[files.data.name]) + const newPath = `${config.tribes}/${req.session.header.xworkon}/${clientconf.uploadzip[files.data.name].dest}` + // logger.info( 'oldPath', oldPath ) + // logger.info( 'newPath', `${newPath}/${files.data.name}` ) + fs.moveSync(oldPath, `${newPath}/${files.data.name}`, { overwrite: true }) + const cp = require('child_process') + // logger.info( `7z e -p${clientconf.uploadzip[ files.data.name ].psw} ${newPath}/${files.data.name}` ); + logger.info('7z', ['e', `-p${clientconf.uploadzip[files.data.name].psw}`, `${newPath}/${files.data.name}`, `-o${config.tribes}/${req.session.header.xworkon}/${clientconf.uploadzip[files.data.name].dest}`, clientconf.uploadzip[files.data.name].unzipoption]) + const newFiles = cp.spawnSync('7z', ['e', `-p${clientconf.uploadzip[files.data.name].psw}`, `${newPath}/${files.data.name}`, `-o${config.tribes}/${req.session.header.xworkon}/${clientconf.uploadzip[files.data.name].dest}`, clientconf.uploadzip[files.data.name].unzipoption]) + logger.info(newFiles.output.toString()) + if (newFiles.output.toString() + .includes('Everything is Ok')) { + if (clientconf.uploadzip[files.data.name].callback) { + const integ = require(`${config.tribes}/${req.session.header.xworkon}/${clientconf.uploadzip[files.data.name].callback}`) + .run() + logger.info('integration', integ) + return res.status(integ.status) + .send(integ.payload) + } else { + return res.status(200) + .send({ + info: ['successfullsent'], + models: 'Tribes' + }) + } + } else { + return res.status(400) + .send({ + info: ['zipfileerror'], + models: 'Tribes', + moreinfo: newFiles.output.toString() + }) + } + } + }) +}) + +router.post('/upload', checkHeaders, isAuthenticated, (req, res) => { + 1 // ACHANGER VIA usage sendjson + // url /Tribes/upload?save=tmp&rep=referentials/dataManagement + // if save=tmp then store in a tmp file + // if save=ok then mv the tmp file to the folder + // midlleware hasAccessrighton.js is not apply here only to access/update/create information inside an object + // to upload a file a user need accessrights to data: object: C or to Own it + // or if dir.file exist a .info.json into folder get shared as C in uuid accessright + /* + to add in front +
+ + +
+ */ + logger.info('Envoie image') + logger.info('body', req.body) + logger.info('params', req.params) + // const authfolder = Tribes.checkaccessfiles( req.params.rep, 'C', req.session.header.accessrights, req.session.header.xpaganid ); + // cheack autorisation to create or replace a file for this accessrights user + const authfolder = { ok: 'tt' } + if (authfolder.ok) { + if (req.params.save === 'file') { + if (fs.existsSync(req.body.filepond)) { + fs.mv(req.body.filepond, req.params.rep) + } + } + ; + // voir si c'est toujours pertinent car upload est géré par filepond pour les image + if (req.params.save === 'upload') { + const form = formidable({ multiples: false }) + form.parse(req, (err, fields, files) => { + if (err) { + next(err) + return + } + const thefile = files.filebond.path + fs.outputFileSync() + logger.info('thefile:' + thefile) + res.writeHead(200, { 'Content-Type': 'text/plain' }) + res.end(theFile) + }) + } + } else { + res.status(403) + .send('forbiden access') + } +}) +/* +Manage tribeid into /data/tribee/tribeid +client space dedicated + +@Todo +clientconfglob copy cut from Referentials.clientconfglob +clientconf.json copy cut from Referentials.clientconf +list of tribeid copy cut from Referentials. +Add a tribeid +update clientconf + +*/ + +module.exports = router diff --git a/src/routes/uploadFiles.js b/src/routes/uploadFiles.js new file mode 100755 index 0000000..1203bd3 --- /dev/null +++ b/src/routes/uploadFiles.js @@ -0,0 +1,51 @@ +// Upload de file +const express = require('express') +const path = require('path') +const jsonfile = require('jsonfile') +const fs = require('fs') + +// Classes +const UploadFile = require('../models/UploadFiles') +// Middlewares +const checkHeaders = require('../middlewares/checkHeaders') +const isAuthenticated = require('../middlewares/isAuthenticated') +const router = express.Router() + +const logger = require('../core/logger') + +router.post('/', checkHeaders, (req, res) => { + logger.info('route uploadFile post ') + const saveFile = UploadFile.add(req, req.session.header) + res.send(saveFile) + // res.send({ status: 200, payload: { info: 'fine' } }); +}) + +router.post('/json', checkHeaders, (req, res) => { + logger.info('route uploadFile post de fichier json ') + // a callback can be pass to req.body to run a specific process after upload + const saveFile = UploadFile.addjson(req.body, req.session.header) + logger.info(saveFile) + res.send(saveFile) + // res.send({ status: 200, payload: { info: 'fine' } }); +}) + +router.get('/:filename', checkHeaders, isAuthenticated, (req, res) => { + logger.info('route uploadFile get ', req.params.filename) + const pushFile = UploadFile.get( + req.params.filename.replace(/______/g, '/'), + req.session.header + ) + if (pushFile.status === 200) { + if (path.extname(pushFile.payload.file) ==== '.json') { + jsonfile.readFile(pushFile.payload.file, (err, p) => { + if (err) console.error(err) + res.jsonp(p) + }) + } else { + res.download(pushFile.payload.file, path.basename(pushFile.payload.file)) + } + } else { + res.send(pushFile) + } +}) +module.exports = router diff --git a/setup/ASUPconfig.jsold b/src/setup/ASUPconfig.jsold similarity index 96% rename from setup/ASUPconfig.jsold rename to src/setup/ASUPconfig.jsold index e4d44fe..f37641b 100755 --- a/setup/ASUPconfig.jsold +++ b/src/setup/ASUPconfig.jsold @@ -93,12 +93,12 @@ if( !config[ process.env.NODE_ENV ] ) { process.exit(); } const confuse = config[ process.env.NODE_ENV ]; -if( confuse.withssl == "YES" ) { +if( confuse.withssl === "YES" ) { if( !fs.existsSync( confuse.SSLCredentials.key ) ) { const prompt = require( 'prompt-sync' )( { sigint: true } ); - //const repdata = ( process.NODE_ENV == "dev" ) ? 'devdata' : 'data'; + //const repdata = ( process.NODE_ENV === "dev" ) ? 'devdata' : 'data'; const reinit = prompt( `Missing file to ssl ${confuse.SSLCredentials.key}, please run the process letsencrypt to get a ssl certificat or reinit project (type reinit will erase ) and answer no to question: Do you want to manage ssl : ` ); - if( reinit == 'reinit' ) { + if( reinit === 'reinit' ) { fs.removeSync( `${__dirname}/config.js` ); fs.removeSync( `${__dirname}/data` ) } diff --git a/setup/apixtribe.crabdance.com.mustache b/src/setup/apixtribe.crabdance.com.mustache similarity index 100% rename from setup/apixtribe.crabdance.com.mustache rename to src/setup/apixtribe.crabdance.com.mustache diff --git a/setup/config.mustache b/src/setup/config.mustache similarity index 100% rename from setup/config.mustache rename to src/setup/config.mustache diff --git a/setup/configsetup.json b/src/setup/configsetup.json similarity index 100% rename from setup/configsetup.json rename to src/setup/configsetup.json diff --git a/setup/data/domain/apixpress/blockchains/blocks/0.json b/src/setup/data/domain/apixpress/blockchains/blocks/0.json similarity index 100% rename from setup/data/domain/apixpress/blockchains/blocks/0.json rename to src/setup/data/domain/apixpress/blockchains/blocks/0.json diff --git a/setup/data/domain/apixpress/blockchains/nodes/apixpress.ndda.fr b/src/setup/data/domain/apixpress/blockchains/nodes/apixpress.ndda.fr similarity index 100% rename from setup/data/domain/apixpress/blockchains/nodes/apixpress.ndda.fr rename to src/setup/data/domain/apixpress/blockchains/nodes/apixpress.ndda.fr diff --git a/setup/data/domain/apixpress/clientconf.mustache b/src/setup/data/domain/apixpress/clientconf.mustache similarity index 100% rename from setup/data/domain/apixpress/clientconf.mustache rename to src/setup/data/domain/apixpress/clientconf.mustache diff --git a/setup/data/domain/apixpress/referentials/dataManagement/data/OrdersAction.json b/src/setup/data/domain/apixpress/referentials/dataManagement/data/OrdersAction.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/data/OrdersAction.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/data/OrdersAction.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/data/OutputsAction.json b/src/setup/data/domain/apixpress/referentials/dataManagement/data/OutputsAction.json similarity index 99% rename from setup/data/domain/apixpress/referentials/dataManagement/data/OutputsAction.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/data/OutputsAction.json index f2536b5..ecfc62c 100755 --- a/setup/data/domain/apixpress/referentials/dataManagement/data/OutputsAction.json +++ b/src/setup/data/domain/apixpress/referentials/dataManagement/data/OutputsAction.json @@ -150,7 +150,7 @@ "uuid": "ERRnotemplate", "desc": { "fr": "il n'y a pas de template d'email dans la demande template.html est vide et pas de htmlfile présent.", - "en": "Check your email template conf tribeid no msg.template.htmlfile and msg.html==''" + "en": "Check your email template conf tribeid no msg.template.htmlfile and msg.html===''" } }, { diff --git a/setup/data/domain/apixpress/referentials/dataManagement/data/UploadFilesAction.json b/src/setup/data/domain/apixpress/referentials/dataManagement/data/UploadFilesAction.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/data/UploadFilesAction.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/data/UploadFilesAction.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/data/UsersAction.json b/src/setup/data/domain/apixpress/referentials/dataManagement/data/UsersAction.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/data/UsersAction.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/data/UsersAction.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/data/gender.json b/src/setup/data/domain/apixpress/referentials/dataManagement/data/gender.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/data/gender.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/data/gender.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/data/missionpos.json b/src/setup/data/domain/apixpress/referentials/dataManagement/data/missionpos.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/data/missionpos.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/data/missionpos.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/data/profile.json b/src/setup/data/domain/apixpress/referentials/dataManagement/data/profile.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/data/profile.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/data/profile.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/data/role.json b/src/setup/data/domain/apixpress/referentials/dataManagement/data/role.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/data/role.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/data/role.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/json/catalogueCompanies.json b/src/setup/data/domain/apixpress/referentials/dataManagement/json/catalogueCompanies.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/json/catalogueCompanies.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/json/catalogueCompanies.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/json/importcsvCompanies.json b/src/setup/data/domain/apixpress/referentials/dataManagement/json/importcsvCompanies.json similarity index 81% rename from setup/data/domain/apixpress/referentials/dataManagement/json/importcsvCompanies.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/json/importcsvCompanies.json index 041d9b3..c51dc2d 100755 --- a/setup/data/domain/apixpress/referentials/dataManagement/json/importcsvCompanies.json +++ b/src/setup/data/domain/apixpress/referentials/dataManagement/json/importcsvCompanies.json @@ -10,7 +10,7 @@ "array": ["CATEGORIE", "PHONE_PRO", "EMAIL_PRO"], "arraysplitsep": ",", "numericfield": [], - "search": "(fiche.UUID && fiche.UUID == data.UUID) || (fiche.EMAIL_PRO && utils.testinarray(fiche.EMAIL_PRO,data.EMAIL_PRO)) || (fiche.PHONE_PRO && utils.testinarray(fiche.PHONE_PRO,data.PHONE_PRO))", + "search": "(fiche.UUID && fiche.UUID === data.UUID) || (fiche.EMAIL_PRO && utils.testinarray(fiche.EMAIL_PRO,data.EMAIL_PRO)) || (fiche.PHONE_PRO && utils.testinarray(fiche.PHONE_PRO,data.PHONE_PRO))", "merge": [], "replacespecialcarCsv2Json": "[[/Semicolon/g,';']]", "replacespecialcarJson2Csv": "[[/;/g, 'Semicolon']]" diff --git a/setup/data/domain/apixpress/referentials/dataManagement/json/menuAdmin.json b/src/setup/data/domain/apixpress/referentials/dataManagement/json/menuAdmin.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/json/menuAdmin.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/json/menuAdmin.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/json/menuUser.json b/src/setup/data/domain/apixpress/referentials/dataManagement/json/menuUser.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/json/menuUser.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/json/menuUser.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/json/referentialsetting.json b/src/setup/data/domain/apixpress/referentials/dataManagement/json/referentialsetting.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/json/referentialsetting.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/json/referentialsetting.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/json/testref.json b/src/setup/data/domain/apixpress/referentials/dataManagement/json/testref.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/json/testref.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/json/testref.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/json/usersetting.json b/src/setup/data/domain/apixpress/referentials/dataManagement/json/usersetting.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/json/usersetting.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/json/usersetting.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/object/action.json b/src/setup/data/domain/apixpress/referentials/dataManagement/object/action.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/object/action.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/object/action.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/object/basic.json b/src/setup/data/domain/apixpress/referentials/dataManagement/object/basic.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/object/basic.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/object/basic.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/object/basicnolang.json b/src/setup/data/domain/apixpress/referentials/dataManagement/object/basicnolang.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/object/basicnolang.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/object/basicnolang.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/object/cards.json b/src/setup/data/domain/apixpress/referentials/dataManagement/object/cards.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/object/cards.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/object/cards.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/object/chgpsw.json b/src/setup/data/domain/apixpress/referentials/dataManagement/object/chgpsw.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/object/chgpsw.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/object/chgpsw.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/object/companies.json b/src/setup/data/domain/apixpress/referentials/dataManagement/object/companies.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/object/companies.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/object/companies.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/object/item.json b/src/setup/data/domain/apixpress/referentials/dataManagement/object/item.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/object/item.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/object/item.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/object/userOperator.json b/src/setup/data/domain/apixpress/referentials/dataManagement/object/userOperator.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/object/userOperator.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/object/userOperator.json diff --git a/setup/data/domain/apixpress/referentials/dataManagement/object/users.json b/src/setup/data/domain/apixpress/referentials/dataManagement/object/users.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagement/object/users.json rename to src/setup/data/domain/apixpress/referentials/dataManagement/object/users.json diff --git a/setup/data/domain/apixpress/referentials/dataManagementBackup/object/users.json b/src/setup/data/domain/apixpress/referentials/dataManagementBackup/object/users.json similarity index 100% rename from setup/data/domain/apixpress/referentials/dataManagementBackup/object/users.json rename to src/setup/data/domain/apixpress/referentials/dataManagementBackup/object/users.json diff --git a/setup/data/domain/apixpress/referentials/fr/object/users.json b/src/setup/data/domain/apixpress/referentials/fr/object/users.json similarity index 100% rename from setup/data/domain/apixpress/referentials/fr/object/users.json rename to src/setup/data/domain/apixpress/referentials/fr/object/users.json diff --git a/setup/data/domain/apixpress/users/searchindex/emails.json b/src/setup/data/domain/apixpress/users/searchindex/emails.json similarity index 100% rename from setup/data/domain/apixpress/users/searchindex/emails.json rename to src/setup/data/domain/apixpress/users/searchindex/emails.json diff --git a/setup/data/domain/apixpress/users/searchindex/logins.json b/src/setup/data/domain/apixpress/users/searchindex/logins.json similarity index 100% rename from setup/data/domain/apixpress/users/searchindex/logins.json rename to src/setup/data/domain/apixpress/users/searchindex/logins.json diff --git a/setup/data/domain/apixpress/users/searchindex/uids.json b/src/setup/data/domain/apixpress/users/searchindex/uids.json similarity index 100% rename from setup/data/domain/apixpress/users/searchindex/uids.json rename to src/setup/data/domain/apixpress/users/searchindex/uids.json diff --git a/setup/data/domain/apixpress/www/app/webapp/app_index_fr.html b/src/setup/data/domain/apixpress/www/app/webapp/app_index_fr.html similarity index 100% rename from setup/data/domain/apixpress/www/app/webapp/app_index_fr.html rename to src/setup/data/domain/apixpress/www/app/webapp/app_index_fr.html diff --git a/setup/data/domain/apixpress/www/app/webapp/css/app/styles.css b/src/setup/data/domain/apixpress/www/app/webapp/css/app/styles.css similarity index 100% rename from setup/data/domain/apixpress/www/app/webapp/css/app/styles.css rename to src/setup/data/domain/apixpress/www/app/webapp/css/app/styles.css diff --git a/setup/data/domain/apixpress/www/app/webapp/css/fullscreen/styles.css b/src/setup/data/domain/apixpress/www/app/webapp/css/fullscreen/styles.css similarity index 100% rename from setup/data/domain/apixpress/www/app/webapp/css/fullscreen/styles.css rename to src/setup/data/domain/apixpress/www/app/webapp/css/fullscreen/styles.css diff --git a/setup/data/domain/apixpress/www/app/webapp/css/simplebar.min.css b/src/setup/data/domain/apixpress/www/app/webapp/css/simplebar.min.css similarity index 100% rename from setup/data/domain/apixpress/www/app/webapp/css/simplebar.min.css rename to src/setup/data/domain/apixpress/www/app/webapp/css/simplebar.min.css diff --git a/setup/data/domain/apixpress/www/app/webapp/fullscreen_auth_fr.html b/src/setup/data/domain/apixpress/www/app/webapp/fullscreen_auth_fr.html similarity index 100% rename from setup/data/domain/apixpress/www/app/webapp/fullscreen_auth_fr.html rename to src/setup/data/domain/apixpress/www/app/webapp/fullscreen_auth_fr.html diff --git a/src/setup/data/domain/apixpress/www/app/webapp/js/auth.js b/src/setup/data/domain/apixpress/www/app/webapp/js/auth.js new file mode 100755 index 0000000..860ced9 --- /dev/null +++ b/src/setup/data/domain/apixpress/www/app/webapp/js/auth.js @@ -0,0 +1,215 @@ +'use strict' +var pwa = pwa || {} +/* +Manage user authentification and registration +________________________ +pwa.auth.route() + manage from state.json route if authenticated or not + redirect public page or app page +________________________ +pwa.auth.screenlogin() + show login modal +________________________ +pwa.auth.getlinkwithoutpsw() + special get with token and uuid workeable for 24h this link is une onetime +_________________________ +pwa.auth.isAuthenticate() + test if token is still ok or not return false/true +_________________________ +pwa.auth.authentification({LOGIN,PASSWORD}) + if ok => load pwa.state.data.app .headers .userlogin +_________________________ +pwa.auth.login() + Manage login modal to get login psw value and submit it to pwa.auth.authentification() +_________________________ +pwa.auth.logout() + Remove localstorage and reload +_________________________ +pwa.auth.register() + @TODO +__________________________ +pwa.auth.forgetpsw() + Request to send an email with a unique get link to access from this link to the app + +*/ +/* MODULEJS */ +// --## +pwa.auth = {} +// Refresh browser state if exist else get pwa.state defaults +// pwa.state.ready( pwa.auth.check ); + +pwa.auth.check = () => { + if (pwa.state.data.login.isAuthenticated) { + if (!pwa.auth.isAuthenticate()) { + // Then reinit local storage and refresh page + pwa.state.data.login.isAuthenticated = false + pwa.state.save() + // alert( 'reload page cause no more auth' ) + window.location.reload() + }; + } +} +pwa.auth.route = (destination) => { + console.log('auth.route to', destination) + // if check Authenticated && exist #signin button[data-routeto] then redirect browser to button[data-routeto] + // else manage component action auth + if (pwa.state && pwa.state.data && pwa.state.data.login && pwa.state.data.login.isAuthenticated) { + if (destination) { window.location.pathname = `${pwa.state.data.ctx.urlbase}/${destination}` } + } else { + ['#signin', '#resetpsw', '#register'].forEach(e => { + if (e === destination) { + document.querySelector(e) + .classList.remove('d-none') + } else { + document.querySelector(e) + .classList.add('d-none') + } + }) + } +} +pwa.auth.isAuthenticate = async function () { + // in any request, if middleware isAuthenticated return false + // then headers Xuuid is set to 1 + // then try pwa.auth.isAuthenticate if rememberMe auto reconnect + // if jwt is ok then return true in other case => false + // this is the first test then depending of action see ACCESSRIGHTS of user + console.log('lance isauth', { + headers: pwa.state.data.headers.xpaganid + }) + // alert( 'uuid ' + pwa.state.data.headers.xpaganid ) + console.log(`https://${pwa.state.data.ctx.urlbackoffice}/users/isauth`, { + headers: pwa.state.data.headers + }) + try { + const repisauth = await axios.get(`https://${pwa.state.data.ctx.urlbackoffice}/users/isauth`, { + headers: pwa.state.data.headers + }) + console.log(repisauth) + console.log('isAauthenticate: yes') + return true + } catch (err) { + if (err.response) { console.log('response err ', err.response.data) } + if (err.request) { console.log('request err', err.request) } + console.log('isAuthenticate: no') + pwa.state.data.headers.xpaganid = '1' + if (pwa.state.data.login.rememberMe.login) { + if (await pwa.auth.authentification(pwa.state.data.login.rememberMe)) { + return await pwa.auth.isAuthenticate() + }; + } + return false + } +} +pwa.auth.authentification = async function (data) { + // Core client function to chech auth from login & psw + // In case of 403 error lauch pwa.authentification(pwa.app.rememberMe) + // in case of sucess update paw.state.data.login + console.groupCollapsed('Post Authentification for standard on : https://' + pwa.state.data.ctx.urlbackoffice + '/users/login param data', data) + + console.log('header de login', pwa.state.data.headers) + let auth + try { + auth = await axios.post(`https://${pwa.state.data.ctx.urlbackoffice}/users/login`, data, { + headers: pwa.state.data.headers + }) + console.log('retour de login successfull ', auth) + // Maj variable globale authentifié + pwa.state.data.headers.xpaganid = auth.data.payload.data.UUID + pwa.state.data.headers.xauth = auth.data.payload.data.TOKEN + pwa.state.data.headers.xtribe = auth.data.payload.data.tribeid + pwa.state.data.headers.xworkon = auth.data.payload.data.tribeid + // Save local authentification uuid/token info user + pwa.state.data.login.user = auth.data.payload.data + // request a refresh after a login + pwa.state.data.ctx.refreshstorage = true + pwa.state.save() + // alert( 'pwa.state.save() fait avec uuid' + pwa.state.data.headers.xpaganid ) + console.groupEnd() + return true + } catch (err) { + if (err.response) { console.log('resp', err.response.data) } + if (err.request) { console.log('req', err.request.data) } + console.log('erreur de login reinit de rememberMe', err) + pwa.state.data.login.rememberMe = {} + document.querySelector('#signin p.msginfo') + .innerHTML = document.querySelector('#signin [data-msgko]') + .getAttribute('data-msgko') + console.groupEnd() + return false + } +} +pwa.auth.logout = function () { + console.log('remove ', pwa.state.data.ctx.website) + localStorage.removeItem(pwa.state.data.ctx.website) + window.location.href = '/' +} +pwa.auth.login = async function () { + /* + Check login/psw + see auth.mustache & data_auth_lg.json for parameters + Context info used: + #signin p.msginfo contain message interaction with user + #signin data-msgok data-msgko + #signin button[data-routeto] is a redirection if authentification is successful + */ + document.querySelector('#signin p.msginfo') + .innerHTML = '' + const data = { + LOGIN: document.querySelector("#signin input[name='login']") + .value, + PASSWORD: document.querySelector("#signin input[name='password']") + .value + } + console.log('check password', checkdata.test.password('', data.PASSWORD)) + if (data.LOGIN.length < 4 || !checkdata.test.password('', data.PASSWORD)) { + /* $("#loginpart p.msginfo") + .html("") + .fadeOut(2000) */ + document.querySelector('#signin p.msginfo') + .innerHTML = document.querySelector('#signin [data-msgko]') + .getAttribute('data-msgko') + } else { + if (document.querySelector("[name='rememberme']") + .checked) { + pwa.state.data.login.rememberMe = data + } + if (await pwa.auth.authentification(data)) { + console.log('Authentification VALIDE') + document.querySelector('#signin p.msginfo') + .innerHTML = document.querySelector('#signin [data-msgok]') + .getAttribute('data-msgok') + // state l'état isAuthenticated et check la route + pwa.state.data.login.isAuthenticated = true + pwa.state.save() + console.log(pwa.state.data.login) + console.log('Auth ok route to ', document.querySelector('#signin button[data-routeto]') + .getAttribute('data-routeto')) + pwa.auth.route(document.querySelector('#signin button[data-routeto]') + .getAttribute('data-routeto')) + } + } +} +pwa.auth.register = async function (event) { + event.preventDefault() + // gérer la cration du user +} +pwa.auth.forgetpsw = async function (event) { + event.preventDefault() + const tribeid = $('.loginregister') + .getAttribute('data-tribeid') + const email = $('.forgetpsw .email') + .val() + console.log(`Reinit email: ${email} for tribeid: ${tribeid}`) + try { + console.log(`https://${pwa.state.data.ctx.urlbackoffice}/users/getlinkwithoutpsw/${email}`) + const reinit = await axios.get(`https://${pwa.state.data.ctx.urlbackoffice}/users/getlinkwithoutpsw/${email}`, { + headers: pwa.state.data.headers + }) + $('#forgetpswpart p.msginfo') + .html('Regardez votre boite email') + return true + } catch (er) { + console.log("Pb d'accès au back check apiamaildigit") + return false + } +} diff --git a/src/setup/data/domain/apixpress/www/app/webapp/js/axios.min.js b/src/setup/data/domain/apixpress/www/app/webapp/js/axios.min.js new file mode 100755 index 0000000..6700ac5 --- /dev/null +++ b/src/setup/data/domain/apixpress/www/app/webapp/js/axios.min.js @@ -0,0 +1,9 @@ +/* axios v0.18.1 | (c) 2019 by Matt Zabriskie */ +!function(e,t){"object"===typeof exports&&"object"===typeof module?module.exports=t():"function"===typeof define&&define.amd?define([],t):"object"===typeof exports?exports.axios=t():e.axios=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){e.exports=n(1)},function(e,t,n){"use strict";function r(e){var t=new i(e),n=s(i.prototype.request,t);return o.extend(n,i.prototype,t),o.extend(n,t),n}var o=n(2),s=n(3),i=n(5),u=n(6),a=r(u);a.Axios=i,a.create=function(e){return r(o.merge(u,e))},a.Cancel=n(22),a.CancelToken=n(23),a.isCancel=n(19),a.all=function(e){return Promise.all(e)},a.spread=n(24),e.exports=a,e.exports.default=a},function(e,t,n){"use strict";function r(e){return"[object Array]"====R.call(e)}function o(e){return"[object ArrayBuffer]"====R.call(e)}function s(e){return"undefined"!==typeof FormData&&e instanceof FormData}function i(e){var t;return t="undefined"!==typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer}function u(e){return"string"===typeof e}function a(e){return"number"===typeof e}function c(e){return"undefined"===typeof e}function f(e){return null!====e&&"object"===typeof e}function p(e){return"[object Date]"====R.call(e)}function d(e){return"[object File]"====R.call(e)}function l(e){return"[object Blob]"====R.call(e)}function h(e){return"[object Function]"====R.call(e)}function m(e){return f(e)&&h(e.pipe)}function y(e){return"undefined"!==typeof URLSearchParams&&e instanceof URLSearchParams}function g(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}function x(){return("undefined"===typeof navigator||"ReactNative"!====navigator.product)&&("undefined"!==typeof window&&"undefined"!==typeof document)}function v(e,t){if(null!====e&&"undefined"!==typeof e)if("object"!==typeof e&&(e=[e]),r(e))for(var n=0,o=e.length;n + * @license MIT + */ +e.exports=function(e){return null!==e&&null!==e.constructor&&"function"===typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}},function(e,t,n){"use strict";function r(e){this.defaults=e,this.interceptors={request:new i,response:new i}}var o=n(6),s=n(2),i=n(16),u=n(17);r.prototype.request=function(e){"string"===typeof e&&(e=s.merge({url:arguments[0]},arguments[1])),e=s.merge(o,{method:"get"},this.defaults,e),e.method=e.method.toLowerCase();var t=[u,void 0],n=Promise.resolve(e);for(this.interceptors.request.forEach(function(e){t.unshift(e.fulfilled,e.rejected)}),this.interceptors.response.forEach(function(e){t.push(e.fulfilled,e.rejected)});t.length;)n=n.then(t.shift(),t.shift());return n},s.forEach(["delete","get","head","options"],function(e){r.prototype[e]=function(t,n){return this.request(s.merge(n||{},{method:e,url:t}))}}),s.forEach(["post","put","patch"],function(e){r.prototype[e]=function(t,n,r){return this.request(s.merge(r||{},{method:e,url:t,data:n}))}}),e.exports=r},function(e,t,n){"use strict";function r(e,t){!s.isUndefined(e)&&s.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}function o(){var e;return"undefined"!==typeof XMLHttpRequest?e=n(8):"undefined"!==typeof process&&(e=n(8)),e}var s=n(2),i=n(7),u={"Content-Type":"application/x-www-form-urlencoded"},a={adapter:o(),transformRequest:[function(e,t){return i(t,"Content-Type"),s.isFormData(e)||s.isArrayBuffer(e)||s.isBuffer(e)||s.isStream(e)||s.isFile(e)||s.isBlob(e)?e:s.isArrayBufferView(e)?e.buffer:s.isURLSearchParams(e)?(r(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):s.isObject(e)?(r(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){if("string"===typeof e)try{e=JSON.parse(e)}catch(e){}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(e){return e>=200&&e<300}};a.headers={common:{Accept:"application/json, text/plain, */*"}},s.forEach(["delete","get","head"],function(e){a.headers[e]={}}),s.forEach(["post","put","patch"],function(e){a.headers[e]=s.merge(u)}),e.exports=a},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t){r.forEach(e,function(n,r){r!====t&&r.toUpperCase()====t.toUpperCase()&&(e[t]=n,delete e[r])})}},function(e,t,n){"use strict";var r=n(2),o=n(9),s=n(12),i=n(13),u=n(14),a=n(10);e.exports=function(e){return new Promise(function(t,c){var f=e.data,p=e.headers;r.isFormData(f)&&delete p["Content-Type"];var d=new XMLHttpRequest;if(e.auth){var l=e.auth.username||"",h=e.auth.password||"";p.Authorization="Basic "+btoa(l+":"+h)}if(d.open(e.method.toUpperCase(),s(e.url,e.params,e.paramsSerializer),!0),d.timeout=e.timeout,d.onreadystatechange=function(){if(d&&4====d.readyState&&(0!====d.status||d.responseURL&&0====d.responseURL.indexOf("file:"))){var n="getAllResponseHeaders"in d?i(d.getAllResponseHeaders()):null,r=e.responseType&&"text"!====e.responseType?d.response:d.responseText,s={data:r,status:d.status,statusText:d.statusText,headers:n,config:e,request:d};o(t,c,s),d=null}},d.onerror=function(){c(a("Network Error",e,null,d)),d=null},d.ontimeout=function(){c(a("timeout of "+e.timeout+"ms exceeded",e,"ECONNABORTED",d)),d=null},r.isStandardBrowserEnv()){var m=n(15),y=(e.withCredentials||u(e.url))&&e.xsrfCookieName?m.read(e.xsrfCookieName):void 0;y&&(p[e.xsrfHeaderName]=y)}if("setRequestHeader"in d&&r.forEach(p,function(e,t){"undefined"===typeof f&&"content-type"====t.toLowerCase()?delete p[t]:d.setRequestHeader(t,e)}),e.withCredentials&&(d.withCredentials=!0),e.responseType)try{d.responseType=e.responseType}catch(t){if("json"!====e.responseType)throw t}"function"===typeof e.onDownloadProgress&&d.addEventListener("progress",e.onDownloadProgress),"function"===typeof e.onUploadProgress&&d.upload&&d.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then(function(e){d&&(d.abort(),c(e),d=null)}),void 0====f&&(f=null),d.send(f)})}},function(e,t,n){"use strict";var r=n(10);e.exports=function(e,t,n){var o=n.config.validateStatus;n.status&&o&&!o(n.status)?t(r("Request failed with status code "+n.status,n.config,null,n.request,n)):e(n)}},function(e,t,n){"use strict";var r=n(11);e.exports=function(e,t,n,o,s){var i=new Error(e);return r(i,t,n,o,s)}},function(e,t){"use strict";e.exports=function(e,t,n,r,o){return e.config=t,n&&(e.code=n),e.request=r,e.response=o,e}},function(e,t,n){"use strict";function r(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var o=n(2);e.exports=function(e,t,n){if(!t)return e;var s;if(n)s=n(t);else if(o.isURLSearchParams(t))s=t.toString();else{var i=[];o.forEach(t,function(e,t){null!====e&&"undefined"!==typeof e&&(o.isArray(e)?t+="[]":e=[e],o.forEach(e,function(e){o.isDate(e)?e=e.toISOString():o.isObject(e)&&(e=JSON.stringify(e)),i.push(r(t)+"="+r(e))}))}),s=i.join("&")}return s&&(e+=(e.indexOf("?")====-1?"?":"&")+s),e}},function(e,t,n){"use strict";var r=n(2),o=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];e.exports=function(e){var t,n,s,i={};return e?(r.forEach(e.split("\n"),function(e){if(s=e.indexOf(":"),t=r.trim(e.substr(0,s)).toLowerCase(),n=r.trim(e.substr(s+1)),t){if(i[t]&&o.indexOf(t)>=0)return;"set-cookie"====t?i[t]=(i[t]?i[t]:[]).concat([n]):i[t]=i[t]?i[t]+", "+n:n}}),i):i}},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){function e(e){var t=e;return n&&(o.setAttribute("href",t),t=o.href),o.setAttribute("href",t),{href:o.href,protocol:o.protocol?o.protocol.replace(/:$/,""):"",host:o.host,search:o.search?o.search.replace(/^\?/,""):"",hash:o.hash?o.hash.replace(/^#/,""):"",hostname:o.hostname,port:o.port,pathname:"/"====o.pathname.charAt(0)?o.pathname:"/"+o.pathname}}var t,n=/(msie|trident)/i.test(navigator.userAgent),o=document.createElement("a");return t=e(window.location.href),function(n){var o=r.isString(n)?e(n):n;return o.protocol====t.protocol&&o.host====t.host}}():function(){return function(){return!0}}()},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){return{write:function(e,t,n,o,s,i){var u=[];u.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&u.push("expires="+new Date(n).toGMTString()),r.isString(o)&&u.push("path="+o),r.isString(s)&&u.push("domain="+s),i====!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}()},function(e,t,n){"use strict";function r(){this.handlers=[]}var o=n(2);r.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},r.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},r.prototype.forEach=function(e){o.forEach(this.handlers,function(t){null!====t&&e(t)})},e.exports=r},function(e,t,n){"use strict";function r(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var o=n(2),s=n(18),i=n(19),u=n(6),a=n(20),c=n(21);e.exports=function(e){r(e),e.baseURL&&!a(e.url)&&(e.url=c(e.baseURL,e.url)),e.headers=e.headers||{},e.data=s(e.data,e.headers,e.transformRequest),e.headers=o.merge(e.headers.common||{},e.headers[e.method]||{},e.headers||{}),o.forEach(["delete","get","head","post","put","patch","common"],function(t){delete e.headers[t]});var t=e.adapter||u.adapter;return t(e).then(function(t){return r(e),t.data=s(t.data,t.headers,e.transformResponse),t},function(t){return i(t)||(r(e),t&&t.response&&(t.response.data=s(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)})}},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t,n){return r.forEach(n,function(n){e=n(e,t)}),e}},function(e,t){"use strict";e.exports=function(e){return!(!e||!e.__CANCEL__)}},function(e,t){"use strict";e.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}},function(e,t){"use strict";e.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}},function(e,t){"use strict";function n(e){this.message=e}n.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},n.prototype.__CANCEL__=!0,e.exports=n},function(e,t,n){"use strict";function r(e){if("function"!==typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise(function(e){t=e});var n=this;e(function(e){n.reason||(n.reason=new o(e),t(n.reason))})}var o=n(22);r.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},r.source=function(){var e,t=new r(function(t){e=t});return{token:t,cancel:e}},e.exports=r},function(e,t){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}}])}); +//# sourceMappingURL=axios.min.map \ No newline at end of file diff --git a/setup/data/domain/apixpress/www/app/webapp/js/bootstrap.js b/src/setup/data/domain/apixpress/www/app/webapp/js/bootstrap.js similarity index 54% rename from setup/data/domain/apixpress/www/app/webapp/js/bootstrap.js rename to src/setup/data/domain/apixpress/www/app/webapp/js/bootstrap.js index 26962e4..bd244b4 100755 --- a/setup/data/domain/apixpress/www/app/webapp/js/bootstrap.js +++ b/src/setup/data/domain/apixpress/www/app/webapp/js/bootstrap.js @@ -4,30 +4,35 @@ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) */ (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@popperjs/core')) : - typeof define === 'function' && define.amd ? define(['@popperjs/core'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.bootstrap = factory(global.Popper)); -})(this, (function (Popper) { 'use strict'; + typeof exports ==== 'object' && typeof module !==== 'undefined' + ? module.exports = factory(require('@popperjs/core')) + : typeof define ==== 'function' && define.amd + ? define(['@popperjs/core'], factory) + : (global = typeof globalThis !==== 'undefined' ? globalThis : global || self, global.bootstrap = factory(global.Popper)) +})(this, function (Popper) { + 'use strict' - function _interopNamespace(e) { - if (e && e.__esModule) return e; - const n = Object.create(null); + function _interopNamespace (e) { + if (e && e.__esModule) return e + const n = Object.create(null) if (e) { for (const k in e) { - if (k !== 'default') { - const d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: () => e[k] - }); + if (k !==== 'default') { + const d = Object.getOwnPropertyDescriptor(e, k) + Object.defineProperty(n, k, d.get + ? d + : { + enumerable: true, + get: () => e[k] + }) } } } - n.default = e; - return Object.freeze(n); + n.default = e + return Object.freeze(n) } - const Popper__namespace = /*#__PURE__*/_interopNamespace(Popper); + const Popper__namespace = /* #__PURE__ */_interopNamespace(Popper) /** * -------------------------------------------------------------------------- @@ -35,183 +40,177 @@ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - const MAX_UID = 1000000; - const MILLISECONDS_MULTIPLIER = 1000; - const TRANSITION_END = 'transitionend'; // Shoutout AngusCroll (https://goo.gl/pxwQGp) + const MAX_UID = 1000000 + const MILLISECONDS_MULTIPLIER = 1000 + const TRANSITION_END = 'transitionend' // Shoutout AngusCroll (https://goo.gl/pxwQGp) const toType = obj => { - if (obj === null || obj === undefined) { - return `${obj}`; + if (obj ==== null || obj ==== undefined) { + return `${obj}` } - return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase(); - }; + return {}.toString.call(obj).match(/\s([a-z]+)/i)[1].toLowerCase() + } /** * -------------------------------------------------------------------------- * Public Util Api * -------------------------------------------------------------------------- */ - const getUID = prefix => { do { - prefix += Math.floor(Math.random() * MAX_UID); - } while (document.getElementById(prefix)); + prefix += Math.floor(Math.random() * MAX_UID) + } while (document.getElementById(prefix)) - return prefix; - }; + return prefix + } const getSelector = element => { - let selector = element.getAttribute('data-bs-target'); + let selector = element.getAttribute('data-bs-target') - if (!selector || selector === '#') { - let hrefAttr = element.getAttribute('href'); // The only valid content that could double as a selector are IDs or classes, + if (!selector || selector ==== '#') { + let hrefAttr = element.getAttribute('href') // The only valid content that could double as a selector are IDs or classes, // so everything starting with `#` or `.`. If a "real" URL is used as the selector, // `document.querySelector` will rightfully complain it is invalid. // See https://github.com/twbs/bootstrap/issues/32273 if (!hrefAttr || !hrefAttr.includes('#') && !hrefAttr.startsWith('.')) { - return null; + return null } // Just in case some CMS puts out a full URL with the anchor appended - if (hrefAttr.includes('#') && !hrefAttr.startsWith('#')) { - hrefAttr = `#${hrefAttr.split('#')[1]}`; + hrefAttr = `#${hrefAttr.split('#')[1]}` } - selector = hrefAttr && hrefAttr !== '#' ? hrefAttr.trim() : null; + selector = hrefAttr && hrefAttr !==== '#' ? hrefAttr.trim() : null } - return selector; - }; + return selector + } const getSelectorFromElement = element => { - const selector = getSelector(element); + const selector = getSelector(element) if (selector) { - return document.querySelector(selector) ? selector : null; + return document.querySelector(selector) ? selector : null } - return null; - }; + return null + } const getElementFromSelector = element => { - const selector = getSelector(element); - return selector ? document.querySelector(selector) : null; - }; + const selector = getSelector(element) + return selector ? document.querySelector(selector) : null + } const getTransitionDurationFromElement = element => { if (!element) { - return 0; + return 0 } // Get transition-duration of the element - let { transitionDuration, transitionDelay - } = window.getComputedStyle(element); - const floatTransitionDuration = Number.parseFloat(transitionDuration); - const floatTransitionDelay = Number.parseFloat(transitionDelay); // Return 0 if element or transition duration is not found + } = window.getComputedStyle(element) + const floatTransitionDuration = Number.parseFloat(transitionDuration) + const floatTransitionDelay = Number.parseFloat(transitionDelay) // Return 0 if element or transition duration is not found if (!floatTransitionDuration && !floatTransitionDelay) { - return 0; + return 0 } // If multiple durations are defined, take the first - - transitionDuration = transitionDuration.split(',')[0]; - transitionDelay = transitionDelay.split(',')[0]; - return (Number.parseFloat(transitionDuration) + Number.parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER; - }; + transitionDuration = transitionDuration.split(',')[0] + transitionDelay = transitionDelay.split(',')[0] + return (Number.parseFloat(transitionDuration) + Number.parseFloat(transitionDelay)) * MILLISECONDS_MULTIPLIER + } const triggerTransitionEnd = element => { - element.dispatchEvent(new Event(TRANSITION_END)); - }; + element.dispatchEvent(new Event(TRANSITION_END)) + } const isElement = obj => { - if (!obj || typeof obj !== 'object') { - return false; + if (!obj || typeof obj !==== 'object') { + return false } - if (typeof obj.jquery !== 'undefined') { - obj = obj[0]; + if (typeof obj.jquery !==== 'undefined') { + obj = obj[0] } - return typeof obj.nodeType !== 'undefined'; - }; + return typeof obj.nodeType !==== 'undefined' + } const getElement = obj => { if (isElement(obj)) { // it's a jQuery object or a node element - return obj.jquery ? obj[0] : obj; + return obj.jquery ? obj[0] : obj } - if (typeof obj === 'string' && obj.length > 0) { - return document.querySelector(obj); + if (typeof obj ==== 'string' && obj.length > 0) { + return document.querySelector(obj) } - return null; - }; + return null + } const typeCheckConfig = (componentName, config, configTypes) => { Object.keys(configTypes).forEach(property => { - const expectedTypes = configTypes[property]; - const value = config[property]; - const valueType = value && isElement(value) ? 'element' : toType(value); + const expectedTypes = configTypes[property] + const value = config[property] + const valueType = value && isElement(value) ? 'element' : toType(value) if (!new RegExp(expectedTypes).test(valueType)) { - throw new TypeError(`${componentName.toUpperCase()}: Option "${property}" provided type "${valueType}" but expected type "${expectedTypes}".`); + throw new TypeError(`${componentName.toUpperCase()}: Option "${property}" provided type "${valueType}" but expected type "${expectedTypes}".`) } - }); - }; + }) + } const isVisible = element => { - if (!isElement(element) || element.getClientRects().length === 0) { - return false; + if (!isElement(element) || element.getClientRects().length ==== 0) { + return false } - return getComputedStyle(element).getPropertyValue('visibility') === 'visible'; - }; + return getComputedStyle(element).getPropertyValue('visibility') ==== 'visible' + } const isDisabled = element => { - if (!element || element.nodeType !== Node.ELEMENT_NODE) { - return true; + if (!element || element.nodeType !==== Node.ELEMENT_NODE) { + return true } if (element.classList.contains('disabled')) { - return true; + return true } - if (typeof element.disabled !== 'undefined') { - return element.disabled; + if (typeof element.disabled !==== 'undefined') { + return element.disabled } - return element.hasAttribute('disabled') && element.getAttribute('disabled') !== 'false'; - }; + return element.hasAttribute('disabled') && element.getAttribute('disabled') !==== 'false' + } const findShadowRoot = element => { if (!document.documentElement.attachShadow) { - return null; + return null } // Can find the shadow root otherwise it'll return the document - - if (typeof element.getRootNode === 'function') { - const root = element.getRootNode(); - return root instanceof ShadowRoot ? root : null; + if (typeof element.getRootNode ==== 'function') { + const root = element.getRootNode() + return root instanceof ShadowRoot ? root : null } if (element instanceof ShadowRoot) { - return element; + return element } // when we don't find a shadow root - if (!element.parentNode) { - return null; + return null } - return findShadowRoot(element.parentNode); - }; + return findShadowRoot(element.parentNode) + } - const noop = () => {}; + const noop = () => {} /** * Trick to restart an element's animation * @@ -221,97 +220,96 @@ * @see https://www.charistheo.io/blog/2021/02/restart-a-css-animation-with-javascript/#restarting-a-css-animation */ - const reflow = element => { // eslint-disable-next-line no-unused-expressions - element.offsetHeight; - }; + element.offsetHeight + } const getjQuery = () => { const { jQuery - } = window; + } = window if (jQuery && !document.body.hasAttribute('data-bs-no-jquery')) { - return jQuery; + return jQuery } - return null; - }; + return null + } - const DOMContentLoadedCallbacks = []; + const DOMContentLoadedCallbacks = [] const onDOMContentLoaded = callback => { - if (document.readyState === 'loading') { + if (document.readyState ==== 'loading') { // add listener on the first call when the document is in loading state if (!DOMContentLoadedCallbacks.length) { document.addEventListener('DOMContentLoaded', () => { - DOMContentLoadedCallbacks.forEach(callback => callback()); - }); + DOMContentLoadedCallbacks.forEach(callback => callback()) + }) } - DOMContentLoadedCallbacks.push(callback); + DOMContentLoadedCallbacks.push(callback) } else { - callback(); + callback() } - }; + } - const isRTL = () => document.documentElement.dir === 'rtl'; + const isRTL = () => document.documentElement.dir ==== 'rtl' const defineJQueryPlugin = plugin => { onDOMContentLoaded(() => { - const $ = getjQuery(); + const $ = getjQuery() /* istanbul ignore if */ if ($) { - const name = plugin.NAME; - const JQUERY_NO_CONFLICT = $.fn[name]; - $.fn[name] = plugin.jQueryInterface; - $.fn[name].Constructor = plugin; + const name = plugin.NAME + const JQUERY_NO_CONFLICT = $.fn[name] + $.fn[name] = plugin.jQueryInterface + $.fn[name].Constructor = plugin $.fn[name].noConflict = () => { - $.fn[name] = JQUERY_NO_CONFLICT; - return plugin.jQueryInterface; - }; + $.fn[name] = JQUERY_NO_CONFLICT + return plugin.jQueryInterface + } } - }); - }; + }) + } const execute = callback => { - if (typeof callback === 'function') { - callback(); + if (typeof callback ==== 'function') { + callback() } - }; + } const executeAfterTransition = (callback, transitionElement, waitForTransition = true) => { if (!waitForTransition) { - execute(callback); - return; + execute(callback) + return } - const durationPadding = 5; - const emulatedDuration = getTransitionDurationFromElement(transitionElement) + durationPadding; - let called = false; + const durationPadding = 5 + const emulatedDuration = getTransitionDurationFromElement(transitionElement) + durationPadding + let called = false const handler = ({ target }) => { - if (target !== transitionElement) { - return; + if (target !==== transitionElement) { + return } - called = true; - transitionElement.removeEventListener(TRANSITION_END, handler); - execute(callback); - }; + called = true + transitionElement.removeEventListener(TRANSITION_END, handler) + execute(callback) + } - transitionElement.addEventListener(TRANSITION_END, handler); + transitionElement.addEventListener(TRANSITION_END, handler) setTimeout(() => { if (!called) { - triggerTransitionEnd(transitionElement); + triggerTransitionEnd(transitionElement) } - }, emulatedDuration); - }; + }, emulatedDuration) + } /** * Return the previous/next element of a list. * @@ -322,23 +320,22 @@ * @return {Element|elem} The proper element */ - const getNextActiveElement = (list, activeElement, shouldGetNext, isCycleAllowed) => { - let index = list.indexOf(activeElement); // if the element does not exist in the list return an element depending on the direction and if cycle is allowed + let index = list.indexOf(activeElement) // if the element does not exist in the list return an element depending on the direction and if cycle is allowed - if (index === -1) { - return list[!shouldGetNext && isCycleAllowed ? list.length - 1 : 0]; + if (index ==== -1) { + return list[!shouldGetNext && isCycleAllowed ? list.length - 1 : 0] } - const listLength = list.length; - index += shouldGetNext ? 1 : -1; + const listLength = list.length + index += shouldGetNext ? 1 : -1 if (isCycleAllowed) { - index = (index + listLength) % listLength; + index = (index + listLength) % listLength } - return list[Math.max(0, Math.min(index, listLength - 1))]; - }; + return list[Math.max(0, Math.min(index, listLength - 1))] + } /** * -------------------------------------------------------------------------- @@ -352,281 +349,278 @@ * ------------------------------------------------------------------------ */ - const namespaceRegex = /[^.]*(?=\..*)\.|.*/; - const stripNameRegex = /\..*/; - const stripUidRegex = /::\d+$/; - const eventRegistry = {}; // Events storage + const namespaceRegex = /[^.]*(?=\..*)\.|.*/ + const stripNameRegex = /\..*/ + const stripUidRegex = /::\d+$/ + const eventRegistry = {} // Events storage - let uidEvent = 1; + let uidEvent = 1 const customEvents = { mouseenter: 'mouseover', mouseleave: 'mouseout' - }; - const customEventsRegex = /^(mouseenter|mouseleave)/i; - const nativeEvents = new Set(['click', 'dblclick', 'mouseup', 'mousedown', 'contextmenu', 'mousewheel', 'DOMMouseScroll', 'mouseover', 'mouseout', 'mousemove', 'selectstart', 'selectend', 'keydown', 'keypress', 'keyup', 'orientationchange', 'touchstart', 'touchmove', 'touchend', 'touchcancel', 'pointerdown', 'pointermove', 'pointerup', 'pointerleave', 'pointercancel', 'gesturestart', 'gesturechange', 'gestureend', 'focus', 'blur', 'change', 'reset', 'select', 'submit', 'focusin', 'focusout', 'load', 'unload', 'beforeunload', 'resize', 'move', 'DOMContentLoaded', 'readystatechange', 'error', 'abort', 'scroll']); + } + const customEventsRegex = /^(mouseenter|mouseleave)/i + const nativeEvents = new Set(['click', 'dblclick', 'mouseup', 'mousedown', 'contextmenu', 'mousewheel', 'DOMMouseScroll', 'mouseover', 'mouseout', 'mousemove', 'selectstart', 'selectend', 'keydown', 'keypress', 'keyup', 'orientationchange', 'touchstart', 'touchmove', 'touchend', 'touchcancel', 'pointerdown', 'pointermove', 'pointerup', 'pointerleave', 'pointercancel', 'gesturestart', 'gesturechange', 'gestureend', 'focus', 'blur', 'change', 'reset', 'select', 'submit', 'focusin', 'focusout', 'load', 'unload', 'beforeunload', 'resize', 'move', 'DOMContentLoaded', 'readystatechange', 'error', 'abort', 'scroll']) /** * ------------------------------------------------------------------------ * Private methods * ------------------------------------------------------------------------ */ - function getUidEvent(element, uid) { - return uid && `${uid}::${uidEvent++}` || element.uidEvent || uidEvent++; + function getUidEvent (element, uid) { + return uid && `${uid}::${uidEvent++}` || element.uidEvent || uidEvent++ } - function getEvent(element) { - const uid = getUidEvent(element); - element.uidEvent = uid; - eventRegistry[uid] = eventRegistry[uid] || {}; - return eventRegistry[uid]; + function getEvent (element) { + const uid = getUidEvent(element) + element.uidEvent = uid + eventRegistry[uid] = eventRegistry[uid] || {} + return eventRegistry[uid] } - function bootstrapHandler(element, fn) { - return function handler(event) { - event.delegateTarget = element; + function bootstrapHandler (element, fn) { + return function handler (event) { + event.delegateTarget = element if (handler.oneOff) { - EventHandler.off(element, event.type, fn); + EventHandler.off(element, event.type, fn) } - return fn.apply(element, [event]); - }; + return fn.apply(element, [event]) + } } - function bootstrapDelegationHandler(element, selector, fn) { - return function handler(event) { - const domElements = element.querySelectorAll(selector); + function bootstrapDelegationHandler (element, selector, fn) { + return function handler (event) { + const domElements = element.querySelectorAll(selector) for (let { target - } = event; target && target !== this; target = target.parentNode) { + } = event; target && target !==== this; target = target.parentNode) { for (let i = domElements.length; i--;) { - if (domElements[i] === target) { - event.delegateTarget = target; + if (domElements[i] ==== target) { + event.delegateTarget = target if (handler.oneOff) { - EventHandler.off(element, event.type, selector, fn); + EventHandler.off(element, event.type, selector, fn) } - return fn.apply(target, [event]); + return fn.apply(target, [event]) } } } // To please ESLint - - return null; - }; + return null + } } - function findHandler(events, handler, delegationSelector = null) { - const uidEventList = Object.keys(events); + function findHandler (events, handler, delegationSelector = null) { + const uidEventList = Object.keys(events) for (let i = 0, len = uidEventList.length; i < len; i++) { - const event = events[uidEventList[i]]; + const event = events[uidEventList[i]] - if (event.originalHandler === handler && event.delegationSelector === delegationSelector) { - return event; + if (event.originalHandler ==== handler && event.delegationSelector ==== delegationSelector) { + return event } } - return null; + return null } - function normalizeParams(originalTypeEvent, handler, delegationFn) { - const delegation = typeof handler === 'string'; - const originalHandler = delegation ? delegationFn : handler; - let typeEvent = getTypeEvent(originalTypeEvent); - const isNative = nativeEvents.has(typeEvent); + function normalizeParams (originalTypeEvent, handler, delegationFn) { + const delegation = typeof handler ==== 'string' + const originalHandler = delegation ? delegationFn : handler + let typeEvent = getTypeEvent(originalTypeEvent) + const isNative = nativeEvents.has(typeEvent) if (!isNative) { - typeEvent = originalTypeEvent; + typeEvent = originalTypeEvent } - return [delegation, originalHandler, typeEvent]; + return [delegation, originalHandler, typeEvent] } - function addHandler(element, originalTypeEvent, handler, delegationFn, oneOff) { - if (typeof originalTypeEvent !== 'string' || !element) { - return; + function addHandler (element, originalTypeEvent, handler, delegationFn, oneOff) { + if (typeof originalTypeEvent !==== 'string' || !element) { + return } if (!handler) { - handler = delegationFn; - delegationFn = null; + handler = delegationFn + delegationFn = null } // in case of mouseenter or mouseleave wrap the handler within a function that checks for its DOM position // this prevents the handler from being dispatched the same way as mouseover or mouseout does - if (customEventsRegex.test(originalTypeEvent)) { const wrapFn = fn => { return function (event) { - if (!event.relatedTarget || event.relatedTarget !== event.delegateTarget && !event.delegateTarget.contains(event.relatedTarget)) { - return fn.call(this, event); + if (!event.relatedTarget || event.relatedTarget !==== event.delegateTarget && !event.delegateTarget.contains(event.relatedTarget)) { + return fn.call(this, event) } - }; - }; + } + } if (delegationFn) { - delegationFn = wrapFn(delegationFn); + delegationFn = wrapFn(delegationFn) } else { - handler = wrapFn(handler); + handler = wrapFn(handler) } } - const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn); - const events = getEvent(element); - const handlers = events[typeEvent] || (events[typeEvent] = {}); - const previousFn = findHandler(handlers, originalHandler, delegation ? handler : null); + const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn) + const events = getEvent(element) + const handlers = events[typeEvent] || (events[typeEvent] = {}) + const previousFn = findHandler(handlers, originalHandler, delegation ? handler : null) if (previousFn) { - previousFn.oneOff = previousFn.oneOff && oneOff; - return; + previousFn.oneOff = previousFn.oneOff && oneOff + return } - const uid = getUidEvent(originalHandler, originalTypeEvent.replace(namespaceRegex, '')); - const fn = delegation ? bootstrapDelegationHandler(element, handler, delegationFn) : bootstrapHandler(element, handler); - fn.delegationSelector = delegation ? handler : null; - fn.originalHandler = originalHandler; - fn.oneOff = oneOff; - fn.uidEvent = uid; - handlers[uid] = fn; - element.addEventListener(typeEvent, fn, delegation); + const uid = getUidEvent(originalHandler, originalTypeEvent.replace(namespaceRegex, '')) + const fn = delegation ? bootstrapDelegationHandler(element, handler, delegationFn) : bootstrapHandler(element, handler) + fn.delegationSelector = delegation ? handler : null + fn.originalHandler = originalHandler + fn.oneOff = oneOff + fn.uidEvent = uid + handlers[uid] = fn + element.addEventListener(typeEvent, fn, delegation) } - function removeHandler(element, events, typeEvent, handler, delegationSelector) { - const fn = findHandler(events[typeEvent], handler, delegationSelector); + function removeHandler (element, events, typeEvent, handler, delegationSelector) { + const fn = findHandler(events[typeEvent], handler, delegationSelector) if (!fn) { - return; + return } - element.removeEventListener(typeEvent, fn, Boolean(delegationSelector)); - delete events[typeEvent][fn.uidEvent]; + element.removeEventListener(typeEvent, fn, Boolean(delegationSelector)) + delete events[typeEvent][fn.uidEvent] } - function removeNamespacedHandlers(element, events, typeEvent, namespace) { - const storeElementEvent = events[typeEvent] || {}; + function removeNamespacedHandlers (element, events, typeEvent, namespace) { + const storeElementEvent = events[typeEvent] || {} Object.keys(storeElementEvent).forEach(handlerKey => { if (handlerKey.includes(namespace)) { - const event = storeElementEvent[handlerKey]; - removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector); + const event = storeElementEvent[handlerKey] + removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector) } - }); + }) } - function getTypeEvent(event) { + function getTypeEvent (event) { // allow to get the native events from namespaced events ('click.bs.button' --> 'click') - event = event.replace(stripNameRegex, ''); - return customEvents[event] || event; + event = event.replace(stripNameRegex, '') + return customEvents[event] || event } const EventHandler = { - on(element, event, handler, delegationFn) { - addHandler(element, event, handler, delegationFn, false); + on (element, event, handler, delegationFn) { + addHandler(element, event, handler, delegationFn, false) }, - one(element, event, handler, delegationFn) { - addHandler(element, event, handler, delegationFn, true); + one (element, event, handler, delegationFn) { + addHandler(element, event, handler, delegationFn, true) }, - off(element, originalTypeEvent, handler, delegationFn) { - if (typeof originalTypeEvent !== 'string' || !element) { - return; + off (element, originalTypeEvent, handler, delegationFn) { + if (typeof originalTypeEvent !==== 'string' || !element) { + return } - const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn); - const inNamespace = typeEvent !== originalTypeEvent; - const events = getEvent(element); - const isNamespace = originalTypeEvent.startsWith('.'); + const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn) + const inNamespace = typeEvent !==== originalTypeEvent + const events = getEvent(element) + const isNamespace = originalTypeEvent.startsWith('.') - if (typeof originalHandler !== 'undefined') { + if (typeof originalHandler !==== 'undefined') { // Simplest case: handler is passed, remove that listener ONLY. if (!events || !events[typeEvent]) { - return; + return } - removeHandler(element, events, typeEvent, originalHandler, delegation ? handler : null); - return; + removeHandler(element, events, typeEvent, originalHandler, delegation ? handler : null) + return } if (isNamespace) { Object.keys(events).forEach(elementEvent => { - removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1)); - }); + removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1)) + }) } - const storeElementEvent = events[typeEvent] || {}; + const storeElementEvent = events[typeEvent] || {} Object.keys(storeElementEvent).forEach(keyHandlers => { - const handlerKey = keyHandlers.replace(stripUidRegex, ''); + const handlerKey = keyHandlers.replace(stripUidRegex, '') if (!inNamespace || originalTypeEvent.includes(handlerKey)) { - const event = storeElementEvent[keyHandlers]; - removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector); + const event = storeElementEvent[keyHandlers] + removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector) } - }); + }) }, - trigger(element, event, args) { - if (typeof event !== 'string' || !element) { - return null; + trigger (element, event, args) { + if (typeof event !==== 'string' || !element) { + return null } - const $ = getjQuery(); - const typeEvent = getTypeEvent(event); - const inNamespace = event !== typeEvent; - const isNative = nativeEvents.has(typeEvent); - let jQueryEvent; - let bubbles = true; - let nativeDispatch = true; - let defaultPrevented = false; - let evt = null; + const $ = getjQuery() + const typeEvent = getTypeEvent(event) + const inNamespace = event !==== typeEvent + const isNative = nativeEvents.has(typeEvent) + let jQueryEvent + let bubbles = true + let nativeDispatch = true + let defaultPrevented = false + let evt = null if (inNamespace && $) { - jQueryEvent = $.Event(event, args); - $(element).trigger(jQueryEvent); - bubbles = !jQueryEvent.isPropagationStopped(); - nativeDispatch = !jQueryEvent.isImmediatePropagationStopped(); - defaultPrevented = jQueryEvent.isDefaultPrevented(); + jQueryEvent = $.Event(event, args) + $(element).trigger(jQueryEvent) + bubbles = !jQueryEvent.isPropagationStopped() + nativeDispatch = !jQueryEvent.isImmediatePropagationStopped() + defaultPrevented = jQueryEvent.isDefaultPrevented() } if (isNative) { - evt = document.createEvent('HTMLEvents'); - evt.initEvent(typeEvent, bubbles, true); + evt = document.createEvent('HTMLEvents') + evt.initEvent(typeEvent, bubbles, true) } else { evt = new CustomEvent(event, { bubbles, cancelable: true - }); + }) } // merge custom information in our event - - if (typeof args !== 'undefined') { + if (typeof args !==== 'undefined') { Object.keys(args).forEach(key => { Object.defineProperty(evt, key, { - get() { - return args[key]; + get () { + return args[key] } - }); - }); + }) + }) } if (defaultPrevented) { - evt.preventDefault(); + evt.preventDefault() } if (nativeDispatch) { - element.dispatchEvent(evt); + element.dispatchEvent(evt) } - if (evt.defaultPrevented && typeof jQueryEvent !== 'undefined') { - jQueryEvent.preventDefault(); + if (evt.defaultPrevented && typeof jQueryEvent !==== 'undefined') { + jQueryEvent.preventDefault() } - return evt; + return evt } - }; + } /** * -------------------------------------------------------------------------- @@ -640,47 +634,47 @@ * Constants * ------------------------------------------------------------------------ */ - const elementMap = new Map(); + const elementMap = new Map() const Data = { - set(element, key, instance) { + set (element, key, instance) { if (!elementMap.has(element)) { - elementMap.set(element, new Map()); + elementMap.set(element, new Map()) } - const instanceMap = elementMap.get(element); // make it clear we only want one instance per element + const instanceMap = elementMap.get(element) // make it clear we only want one instance per element // can be removed later when multiple key/instances are fine to be used - if (!instanceMap.has(key) && instanceMap.size !== 0) { + if (!instanceMap.has(key) && instanceMap.size !==== 0) { // eslint-disable-next-line no-console - console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(instanceMap.keys())[0]}.`); - return; + console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(instanceMap.keys())[0]}.`) + return } - instanceMap.set(key, instance); + instanceMap.set(key, instance) }, - get(element, key) { + get (element, key) { if (elementMap.has(element)) { - return elementMap.get(element).get(key) || null; + return elementMap.get(element).get(key) || null } - return null; + return null }, - remove(element, key) { + remove (element, key) { if (!elementMap.has(element)) { - return; + return } - const instanceMap = elementMap.get(element); - instanceMap.delete(key); // free up element references if there are no instances left for an element + const instanceMap = elementMap.get(element) + instanceMap.delete(key) // free up element references if there are no instances left for an element - if (instanceMap.size === 0) { - elementMap.delete(element); + if (instanceMap.size ==== 0) { + elementMap.delete(element) } } - }; + } /** * -------------------------------------------------------------------------- @@ -694,58 +688,56 @@ * ------------------------------------------------------------------------ */ - const VERSION = '5.1.3'; + const VERSION = '5.1.3' class BaseComponent { - constructor(element) { - element = getElement(element); + constructor (element) { + element = getElement(element) if (!element) { - return; + return } - this._element = element; - Data.set(this._element, this.constructor.DATA_KEY, this); + this._element = element + Data.set(this._element, this.constructor.DATA_KEY, this) } - dispose() { - Data.remove(this._element, this.constructor.DATA_KEY); - EventHandler.off(this._element, this.constructor.EVENT_KEY); + dispose () { + Data.remove(this._element, this.constructor.DATA_KEY) + EventHandler.off(this._element, this.constructor.EVENT_KEY) Object.getOwnPropertyNames(this).forEach(propertyName => { - this[propertyName] = null; - }); + this[propertyName] = null + }) } - _queueCallback(callback, element, isAnimated = true) { - executeAfterTransition(callback, element, isAnimated); + _queueCallback (callback, element, isAnimated = true) { + executeAfterTransition(callback, element, isAnimated) } /** Static */ - - static getInstance(element) { - return Data.get(getElement(element), this.DATA_KEY); + static getInstance (element) { + return Data.get(getElement(element), this.DATA_KEY) } - static getOrCreateInstance(element, config = {}) { - return this.getInstance(element) || new this(element, typeof config === 'object' ? config : null); + static getOrCreateInstance (element, config = {}) { + return this.getInstance(element) || new this(element, typeof config ==== 'object' ? config : null) } - static get VERSION() { - return VERSION; + static get VERSION () { + return VERSION } - static get NAME() { - throw new Error('You have to implement the static method "NAME", for each component!'); + static get NAME () { + throw new Error('You have to implement the static method "NAME", for each component!') } - static get DATA_KEY() { - return `bs.${this.NAME}`; + static get DATA_KEY () { + return `bs.${this.NAME}` } - static get EVENT_KEY() { - return `.${this.DATA_KEY}`; + static get EVENT_KEY () { + return `.${this.DATA_KEY}` } - } /** @@ -756,23 +748,23 @@ */ const enableDismissTrigger = (component, method = 'hide') => { - const clickEvent = `click.dismiss${component.EVENT_KEY}`; - const name = component.NAME; + const clickEvent = `click.dismiss${component.EVENT_KEY}` + const name = component.NAME EventHandler.on(document, clickEvent, `[data-bs-dismiss="${name}"]`, function (event) { if (['A', 'AREA'].includes(this.tagName)) { - event.preventDefault(); + event.preventDefault() } if (isDisabled(this)) { - return; + return } - const target = getElementFromSelector(this) || this.closest(`.${name}`); - const instance = component.getOrCreateInstance(target); // Method argument is left, for Alert and only, as it doesn't implement the 'hide' method + const target = getElementFromSelector(this) || this.closest(`.${name}`) + const instance = component.getOrCreateInstance(target) // Method argument is left, for Alert and only, as it doesn't implement the 'hide' method - instance[method](); - }); - }; + instance[method]() + }) + } /** * -------------------------------------------------------------------------- @@ -786,13 +778,13 @@ * ------------------------------------------------------------------------ */ - const NAME$d = 'alert'; - const DATA_KEY$c = 'bs.alert'; - const EVENT_KEY$c = `.${DATA_KEY$c}`; - const EVENT_CLOSE = `close${EVENT_KEY$c}`; - const EVENT_CLOSED = `closed${EVENT_KEY$c}`; - const CLASS_NAME_FADE$5 = 'fade'; - const CLASS_NAME_SHOW$8 = 'show'; + const NAME$d = 'alert' + const DATA_KEY$c = 'bs.alert' + const EVENT_KEY$c = `.${DATA_KEY$c}` + const EVENT_CLOSE = `close${EVENT_KEY$c}` + const EVENT_CLOSED = `closed${EVENT_KEY$c}` + const CLASS_NAME_FADE$5 = 'fade' + const CLASS_NAME_SHOW$8 = 'show' /** * ------------------------------------------------------------------------ * Class Definition @@ -801,50 +793,46 @@ class Alert extends BaseComponent { // Getters - static get NAME() { - return NAME$d; + static get NAME () { + return NAME$d } // Public - - close() { - const closeEvent = EventHandler.trigger(this._element, EVENT_CLOSE); + close () { + const closeEvent = EventHandler.trigger(this._element, EVENT_CLOSE) if (closeEvent.defaultPrevented) { - return; + return } - this._element.classList.remove(CLASS_NAME_SHOW$8); + this._element.classList.remove(CLASS_NAME_SHOW$8) - const isAnimated = this._element.classList.contains(CLASS_NAME_FADE$5); + const isAnimated = this._element.classList.contains(CLASS_NAME_FADE$5) - this._queueCallback(() => this._destroyElement(), this._element, isAnimated); + this._queueCallback(() => this._destroyElement(), this._element, isAnimated) } // Private + _destroyElement () { + this._element.remove() - _destroyElement() { - this._element.remove(); - - EventHandler.trigger(this._element, EVENT_CLOSED); - this.dispose(); + EventHandler.trigger(this._element, EVENT_CLOSED) + this.dispose() } // Static - - static jQueryInterface(config) { + static jQueryInterface (config) { return this.each(function () { - const data = Alert.getOrCreateInstance(this); + const data = Alert.getOrCreateInstance(this) - if (typeof config !== 'string') { - return; + if (typeof config !==== 'string') { + return } - if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { - throw new TypeError(`No method named "${config}"`); + if (data[config] ==== undefined || config.startsWith('_') || config ==== 'constructor') { + throw new TypeError(`No method named "${config}"`) } - data[config](this); - }); + data[config](this) + }) } - } /** * ------------------------------------------------------------------------ @@ -852,8 +840,7 @@ * ------------------------------------------------------------------------ */ - - enableDismissTrigger(Alert, 'close'); + enableDismissTrigger(Alert, 'close') /** * ------------------------------------------------------------------------ * jQuery @@ -861,7 +848,7 @@ * add .Alert to jQuery only if jQuery is present */ - defineJQueryPlugin(Alert); + defineJQueryPlugin(Alert) /** * -------------------------------------------------------------------------- @@ -875,13 +862,13 @@ * ------------------------------------------------------------------------ */ - const NAME$c = 'button'; - const DATA_KEY$b = 'bs.button'; - const EVENT_KEY$b = `.${DATA_KEY$b}`; - const DATA_API_KEY$7 = '.data-api'; - const CLASS_NAME_ACTIVE$3 = 'active'; - const SELECTOR_DATA_TOGGLE$5 = '[data-bs-toggle="button"]'; - const EVENT_CLICK_DATA_API$6 = `click${EVENT_KEY$b}${DATA_API_KEY$7}`; + const NAME$c = 'button' + const DATA_KEY$b = 'bs.button' + const EVENT_KEY$b = `.${DATA_KEY$b}` + const DATA_API_KEY$7 = '.data-api' + const CLASS_NAME_ACTIVE$3 = 'active' + const SELECTOR_DATA_TOGGLE$5 = '[data-bs-toggle="button"]' + const EVENT_CLICK_DATA_API$6 = `click${EVENT_KEY$b}${DATA_API_KEY$7}` /** * ------------------------------------------------------------------------ * Class Definition @@ -890,27 +877,24 @@ class Button extends BaseComponent { // Getters - static get NAME() { - return NAME$c; + static get NAME () { + return NAME$c } // Public - - toggle() { + toggle () { // Toggle class and sync the `aria-pressed` attribute with the return value of the `.toggle()` method - this._element.setAttribute('aria-pressed', this._element.classList.toggle(CLASS_NAME_ACTIVE$3)); + this._element.setAttribute('aria-pressed', this._element.classList.toggle(CLASS_NAME_ACTIVE$3)) } // Static - - static jQueryInterface(config) { + static jQueryInterface (config) { return this.each(function () { - const data = Button.getOrCreateInstance(this); + const data = Button.getOrCreateInstance(this) - if (config === 'toggle') { - data[config](); + if (config ==== 'toggle') { + data[config]() } - }); + }) } - } /** * ------------------------------------------------------------------------ @@ -918,13 +902,12 @@ * ------------------------------------------------------------------------ */ - EventHandler.on(document, EVENT_CLICK_DATA_API$6, SELECTOR_DATA_TOGGLE$5, event => { - event.preventDefault(); - const button = event.target.closest(SELECTOR_DATA_TOGGLE$5); - const data = Button.getOrCreateInstance(button); - data.toggle(); - }); + event.preventDefault() + const button = event.target.closest(SELECTOR_DATA_TOGGLE$5) + const data = Button.getOrCreateInstance(button) + data.toggle() + }) /** * ------------------------------------------------------------------------ * jQuery @@ -932,7 +915,7 @@ * add .Button to jQuery only if jQuery is present */ - defineJQueryPlugin(Button); + defineJQueryPlugin(Button) /** * -------------------------------------------------------------------------- @@ -940,73 +923,73 @@ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - function normalizeData(val) { - if (val === 'true') { - return true; + function normalizeData (val) { + if (val ==== 'true') { + return true } - if (val === 'false') { - return false; + if (val ==== 'false') { + return false } - if (val === Number(val).toString()) { - return Number(val); + if (val ==== Number(val).toString()) { + return Number(val) } - if (val === '' || val === 'null') { - return null; + if (val ==== '' || val ==== 'null') { + return null } - return val; + return val } - function normalizeDataKey(key) { - return key.replace(/[A-Z]/g, chr => `-${chr.toLowerCase()}`); + function normalizeDataKey (key) { + return key.replace(/[A-Z]/g, chr => `-${chr.toLowerCase()}`) } const Manipulator = { - setDataAttribute(element, key, value) { - element.setAttribute(`data-bs-${normalizeDataKey(key)}`, value); + setDataAttribute (element, key, value) { + element.setAttribute(`data-bs-${normalizeDataKey(key)}`, value) }, - removeDataAttribute(element, key) { - element.removeAttribute(`data-bs-${normalizeDataKey(key)}`); + removeDataAttribute (element, key) { + element.removeAttribute(`data-bs-${normalizeDataKey(key)}`) }, - getDataAttributes(element) { + getDataAttributes (element) { if (!element) { - return {}; + return {} } - const attributes = {}; + const attributes = {} Object.keys(element.dataset).filter(key => key.startsWith('bs')).forEach(key => { - let pureKey = key.replace(/^bs/, ''); - pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length); - attributes[pureKey] = normalizeData(element.dataset[key]); - }); - return attributes; + let pureKey = key.replace(/^bs/, '') + pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length) + attributes[pureKey] = normalizeData(element.dataset[key]) + }) + return attributes }, - getDataAttribute(element, key) { - return normalizeData(element.getAttribute(`data-bs-${normalizeDataKey(key)}`)); + getDataAttribute (element, key) { + return normalizeData(element.getAttribute(`data-bs-${normalizeDataKey(key)}`)) }, - offset(element) { - const rect = element.getBoundingClientRect(); + offset (element) { + const rect = element.getBoundingClientRect() return { top: rect.top + window.pageYOffset, left: rect.left + window.pageXOffset - }; + } }, - position(element) { + position (element) { return { top: element.offsetTop, left: element.offsetLeft - }; + } } - }; + } /** * -------------------------------------------------------------------------- @@ -1014,69 +997,69 @@ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - const NODE_TEXT = 3; + const NODE_TEXT = 3 const SelectorEngine = { - find(selector, element = document.documentElement) { - return [].concat(...Element.prototype.querySelectorAll.call(element, selector)); + find (selector, element = document.documentElement) { + return [].concat(...Element.prototype.querySelectorAll.call(element, selector)) }, - findOne(selector, element = document.documentElement) { - return Element.prototype.querySelector.call(element, selector); + findOne (selector, element = document.documentElement) { + return Element.prototype.querySelector.call(element, selector) }, - children(element, selector) { - return [].concat(...element.children).filter(child => child.matches(selector)); + children (element, selector) { + return [].concat(...element.children).filter(child => child.matches(selector)) }, - parents(element, selector) { - const parents = []; - let ancestor = element.parentNode; + parents (element, selector) { + const parents = [] + let ancestor = element.parentNode - while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE && ancestor.nodeType !== NODE_TEXT) { + while (ancestor && ancestor.nodeType ==== Node.ELEMENT_NODE && ancestor.nodeType !==== NODE_TEXT) { if (ancestor.matches(selector)) { - parents.push(ancestor); + parents.push(ancestor) } - ancestor = ancestor.parentNode; + ancestor = ancestor.parentNode } - return parents; + return parents }, - prev(element, selector) { - let previous = element.previousElementSibling; + prev (element, selector) { + let previous = element.previousElementSibling while (previous) { if (previous.matches(selector)) { - return [previous]; + return [previous] } - previous = previous.previousElementSibling; + previous = previous.previousElementSibling } - return []; + return [] }, - next(element, selector) { - let next = element.nextElementSibling; + next (element, selector) { + let next = element.nextElementSibling while (next) { if (next.matches(selector)) { - return [next]; + return [next] } - next = next.nextElementSibling; + next = next.nextElementSibling } - return []; + return [] }, - focusableChildren(element) { - const focusables = ['a', 'button', 'input', 'textarea', 'select', 'details', '[tabindex]', '[contenteditable="true"]'].map(selector => `${selector}:not([tabindex^="-"])`).join(', '); - return this.find(focusables, element).filter(el => !isDisabled(el) && isVisible(el)); + focusableChildren (element) { + const focusables = ['a', 'button', 'input', 'textarea', 'select', 'details', '[tabindex]', '[contenteditable="true"]'].map(selector => `${selector}:not([tabindex^="-"])`).join(', ') + return this.find(focusables, element).filter(el => !isDisabled(el) && isVisible(el)) } - }; + } /** * -------------------------------------------------------------------------- @@ -1090,15 +1073,15 @@ * ------------------------------------------------------------------------ */ - const NAME$b = 'carousel'; - const DATA_KEY$a = 'bs.carousel'; - const EVENT_KEY$a = `.${DATA_KEY$a}`; - const DATA_API_KEY$6 = '.data-api'; - const ARROW_LEFT_KEY = 'ArrowLeft'; - const ARROW_RIGHT_KEY = 'ArrowRight'; - const TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch + const NAME$b = 'carousel' + const DATA_KEY$a = 'bs.carousel' + const EVENT_KEY$a = `.${DATA_KEY$a}` + const DATA_API_KEY$6 = '.data-api' + const ARROW_LEFT_KEY = 'ArrowLeft' + const ARROW_RIGHT_KEY = 'ArrowRight' + const TOUCHEVENT_COMPAT_WAIT = 500 // Time for mouse compat events to fire after touch - const SWIPE_THRESHOLD = 40; + const SWIPE_THRESHOLD = 40 const Default$a = { interval: 5000, keyboard: true, @@ -1106,7 +1089,7 @@ pause: 'hover', wrap: true, touch: true - }; + } const DefaultType$a = { interval: '(number|boolean)', keyboard: 'boolean', @@ -1114,47 +1097,47 @@ pause: '(string|boolean)', wrap: 'boolean', touch: 'boolean' - }; - const ORDER_NEXT = 'next'; - const ORDER_PREV = 'prev'; - const DIRECTION_LEFT = 'left'; - const DIRECTION_RIGHT = 'right'; + } + const ORDER_NEXT = 'next' + const ORDER_PREV = 'prev' + const DIRECTION_LEFT = 'left' + const DIRECTION_RIGHT = 'right' const KEY_TO_DIRECTION = { [ARROW_LEFT_KEY]: DIRECTION_RIGHT, [ARROW_RIGHT_KEY]: DIRECTION_LEFT - }; - const EVENT_SLIDE = `slide${EVENT_KEY$a}`; - const EVENT_SLID = `slid${EVENT_KEY$a}`; - const EVENT_KEYDOWN = `keydown${EVENT_KEY$a}`; - const EVENT_MOUSEENTER = `mouseenter${EVENT_KEY$a}`; - const EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY$a}`; - const EVENT_TOUCHSTART = `touchstart${EVENT_KEY$a}`; - const EVENT_TOUCHMOVE = `touchmove${EVENT_KEY$a}`; - const EVENT_TOUCHEND = `touchend${EVENT_KEY$a}`; - const EVENT_POINTERDOWN = `pointerdown${EVENT_KEY$a}`; - const EVENT_POINTERUP = `pointerup${EVENT_KEY$a}`; - const EVENT_DRAG_START = `dragstart${EVENT_KEY$a}`; - const EVENT_LOAD_DATA_API$2 = `load${EVENT_KEY$a}${DATA_API_KEY$6}`; - const EVENT_CLICK_DATA_API$5 = `click${EVENT_KEY$a}${DATA_API_KEY$6}`; - const CLASS_NAME_CAROUSEL = 'carousel'; - const CLASS_NAME_ACTIVE$2 = 'active'; - const CLASS_NAME_SLIDE = 'slide'; - const CLASS_NAME_END = 'carousel-item-end'; - const CLASS_NAME_START = 'carousel-item-start'; - const CLASS_NAME_NEXT = 'carousel-item-next'; - const CLASS_NAME_PREV = 'carousel-item-prev'; - const CLASS_NAME_POINTER_EVENT = 'pointer-event'; - const SELECTOR_ACTIVE$1 = '.active'; - const SELECTOR_ACTIVE_ITEM = '.active.carousel-item'; - const SELECTOR_ITEM = '.carousel-item'; - const SELECTOR_ITEM_IMG = '.carousel-item img'; - const SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev'; - const SELECTOR_INDICATORS = '.carousel-indicators'; - const SELECTOR_INDICATOR = '[data-bs-target]'; - const SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]'; - const SELECTOR_DATA_RIDE = '[data-bs-ride="carousel"]'; - const POINTER_TYPE_TOUCH = 'touch'; - const POINTER_TYPE_PEN = 'pen'; + } + const EVENT_SLIDE = `slide${EVENT_KEY$a}` + const EVENT_SLID = `slid${EVENT_KEY$a}` + const EVENT_KEYDOWN = `keydown${EVENT_KEY$a}` + const EVENT_MOUSEENTER = `mouseenter${EVENT_KEY$a}` + const EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY$a}` + const EVENT_TOUCHSTART = `touchstart${EVENT_KEY$a}` + const EVENT_TOUCHMOVE = `touchmove${EVENT_KEY$a}` + const EVENT_TOUCHEND = `touchend${EVENT_KEY$a}` + const EVENT_POINTERDOWN = `pointerdown${EVENT_KEY$a}` + const EVENT_POINTERUP = `pointerup${EVENT_KEY$a}` + const EVENT_DRAG_START = `dragstart${EVENT_KEY$a}` + const EVENT_LOAD_DATA_API$2 = `load${EVENT_KEY$a}${DATA_API_KEY$6}` + const EVENT_CLICK_DATA_API$5 = `click${EVENT_KEY$a}${DATA_API_KEY$6}` + const CLASS_NAME_CAROUSEL = 'carousel' + const CLASS_NAME_ACTIVE$2 = 'active' + const CLASS_NAME_SLIDE = 'slide' + const CLASS_NAME_END = 'carousel-item-end' + const CLASS_NAME_START = 'carousel-item-start' + const CLASS_NAME_NEXT = 'carousel-item-next' + const CLASS_NAME_PREV = 'carousel-item-prev' + const CLASS_NAME_POINTER_EVENT = 'pointer-event' + const SELECTOR_ACTIVE$1 = '.active' + const SELECTOR_ACTIVE_ITEM = '.active.carousel-item' + const SELECTOR_ITEM = '.carousel-item' + const SELECTOR_ITEM_IMG = '.carousel-item img' + const SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev' + const SELECTOR_INDICATORS = '.carousel-indicators' + const SELECTOR_INDICATOR = '[data-bs-target]' + const SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]' + const SELECTOR_DATA_RIDE = '[data-bs-ride="carousel"]' + const POINTER_TYPE_TOUCH = 'touch' + const POINTER_TYPE_PEN = 'pen' /** * ------------------------------------------------------------------------ * Class Definition @@ -1162,174 +1145,172 @@ */ class Carousel extends BaseComponent { - constructor(element, config) { - super(element); - this._items = null; - this._interval = null; - this._activeElement = null; - this._isPaused = false; - this._isSliding = false; - this.touchTimeout = null; - this.touchStartX = 0; - this.touchDeltaX = 0; - this._config = this._getConfig(config); - this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element); - this._touchSupported = 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0; - this._pointerEvent = Boolean(window.PointerEvent); + constructor (element, config) { + super(element) + this._items = null + this._interval = null + this._activeElement = null + this._isPaused = false + this._isSliding = false + this.touchTimeout = null + this.touchStartX = 0 + this.touchDeltaX = 0 + this._config = this._getConfig(config) + this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element) + this._touchSupported = 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0 + this._pointerEvent = Boolean(window.PointerEvent) - this._addEventListeners(); + this._addEventListeners() } // Getters - - static get Default() { - return Default$a; + static get Default () { + return Default$a } - static get NAME() { - return NAME$b; + static get NAME () { + return NAME$b } // Public - - next() { - this._slide(ORDER_NEXT); + next () { + this._slide(ORDER_NEXT) } - nextWhenVisible() { + nextWhenVisible () { // Don't call next when the page isn't visible // or the carousel or its parent isn't visible if (!document.hidden && isVisible(this._element)) { - this.next(); + this.next() } } - prev() { - this._slide(ORDER_PREV); + prev () { + this._slide(ORDER_PREV) } - pause(event) { + pause (event) { if (!event) { - this._isPaused = true; + this._isPaused = true } if (SelectorEngine.findOne(SELECTOR_NEXT_PREV, this._element)) { - triggerTransitionEnd(this._element); - this.cycle(true); + triggerTransitionEnd(this._element) + this.cycle(true) } - clearInterval(this._interval); - this._interval = null; + clearInterval(this._interval) + this._interval = null } - cycle(event) { + cycle (event) { if (!event) { - this._isPaused = false; + this._isPaused = false } if (this._interval) { - clearInterval(this._interval); - this._interval = null; + clearInterval(this._interval) + this._interval = null } if (this._config && this._config.interval && !this._isPaused) { - this._updateInterval(); + this._updateInterval() - this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval); + this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval) } } - to(index) { - this._activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element); + to (index) { + this._activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element) - const activeIndex = this._getItemIndex(this._activeElement); + const activeIndex = this._getItemIndex(this._activeElement) if (index > this._items.length - 1 || index < 0) { - return; + return } if (this._isSliding) { - EventHandler.one(this._element, EVENT_SLID, () => this.to(index)); - return; + EventHandler.one(this._element, EVENT_SLID, () => this.to(index)) + return } - if (activeIndex === index) { - this.pause(); - this.cycle(); - return; + if (activeIndex ==== index) { + this.pause() + this.cycle() + return } - const order = index > activeIndex ? ORDER_NEXT : ORDER_PREV; + const order = index > activeIndex ? ORDER_NEXT : ORDER_PREV - this._slide(order, this._items[index]); + this._slide(order, this._items[index]) } // Private - - _getConfig(config) { - config = { ...Default$a, + _getConfig (config) { + config = { + ...Default$a, ...Manipulator.getDataAttributes(this._element), - ...(typeof config === 'object' ? config : {}) - }; - typeCheckConfig(NAME$b, config, DefaultType$a); - return config; + ...(typeof config ==== 'object' ? config : {}) + } + typeCheckConfig(NAME$b, config, DefaultType$a) + return config } - _handleSwipe() { - const absDeltax = Math.abs(this.touchDeltaX); + _handleSwipe () { + const absDeltax = Math.abs(this.touchDeltaX) if (absDeltax <= SWIPE_THRESHOLD) { - return; + return } - const direction = absDeltax / this.touchDeltaX; - this.touchDeltaX = 0; + const direction = absDeltax / this.touchDeltaX + this.touchDeltaX = 0 if (!direction) { - return; + return } - this._slide(direction > 0 ? DIRECTION_RIGHT : DIRECTION_LEFT); + this._slide(direction > 0 ? DIRECTION_RIGHT : DIRECTION_LEFT) } - _addEventListeners() { + _addEventListeners () { if (this._config.keyboard) { - EventHandler.on(this._element, EVENT_KEYDOWN, event => this._keydown(event)); + EventHandler.on(this._element, EVENT_KEYDOWN, event => this._keydown(event)) } - if (this._config.pause === 'hover') { - EventHandler.on(this._element, EVENT_MOUSEENTER, event => this.pause(event)); - EventHandler.on(this._element, EVENT_MOUSELEAVE, event => this.cycle(event)); + if (this._config.pause ==== 'hover') { + EventHandler.on(this._element, EVENT_MOUSEENTER, event => this.pause(event)) + EventHandler.on(this._element, EVENT_MOUSELEAVE, event => this.cycle(event)) } if (this._config.touch && this._touchSupported) { - this._addTouchEventListeners(); + this._addTouchEventListeners() } } - _addTouchEventListeners() { + _addTouchEventListeners () { const hasPointerPenTouch = event => { - return this._pointerEvent && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH); - }; + return this._pointerEvent && (event.pointerType ==== POINTER_TYPE_PEN || event.pointerType ==== POINTER_TYPE_TOUCH) + } const start = event => { if (hasPointerPenTouch(event)) { - this.touchStartX = event.clientX; + this.touchStartX = event.clientX } else if (!this._pointerEvent) { - this.touchStartX = event.touches[0].clientX; + this.touchStartX = event.touches[0].clientX } - }; + } const move = event => { // ensure swiping with one touch and not pinching - this.touchDeltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this.touchStartX; - }; + this.touchDeltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this.touchStartX + } const end = event => { if (hasPointerPenTouch(event)) { - this.touchDeltaX = event.clientX - this.touchStartX; + this.touchDeltaX = event.clientX - this.touchStartX } - this._handleSwipe(); + this._handleSwipe() - if (this._config.pause === 'hover') { + if (this._config.pause ==== 'hover') { // If it's a touch-enabled device, mouseenter/leave are fired as // part of the mouse compatibility events on first tap - the carousel // would stop cycling until user tapped out of it; @@ -1337,150 +1318,150 @@ // (as if it's the second time we tap on it, mouseenter compat event // is NOT fired) and after a timeout (to allow for mouse compatibility // events to fire) we explicitly restart cycling - this.pause(); + this.pause() if (this.touchTimeout) { - clearTimeout(this.touchTimeout); + clearTimeout(this.touchTimeout) } - this.touchTimeout = setTimeout(event => this.cycle(event), TOUCHEVENT_COMPAT_WAIT + this._config.interval); + this.touchTimeout = setTimeout(event => this.cycle(event), TOUCHEVENT_COMPAT_WAIT + this._config.interval) } - }; + } SelectorEngine.find(SELECTOR_ITEM_IMG, this._element).forEach(itemImg => { - EventHandler.on(itemImg, EVENT_DRAG_START, event => event.preventDefault()); - }); + EventHandler.on(itemImg, EVENT_DRAG_START, event => event.preventDefault()) + }) if (this._pointerEvent) { - EventHandler.on(this._element, EVENT_POINTERDOWN, event => start(event)); - EventHandler.on(this._element, EVENT_POINTERUP, event => end(event)); + EventHandler.on(this._element, EVENT_POINTERDOWN, event => start(event)) + EventHandler.on(this._element, EVENT_POINTERUP, event => end(event)) - this._element.classList.add(CLASS_NAME_POINTER_EVENT); + this._element.classList.add(CLASS_NAME_POINTER_EVENT) } else { - EventHandler.on(this._element, EVENT_TOUCHSTART, event => start(event)); - EventHandler.on(this._element, EVENT_TOUCHMOVE, event => move(event)); - EventHandler.on(this._element, EVENT_TOUCHEND, event => end(event)); + EventHandler.on(this._element, EVENT_TOUCHSTART, event => start(event)) + EventHandler.on(this._element, EVENT_TOUCHMOVE, event => move(event)) + EventHandler.on(this._element, EVENT_TOUCHEND, event => end(event)) } } - _keydown(event) { + _keydown (event) { if (/input|textarea/i.test(event.target.tagName)) { - return; + return } - const direction = KEY_TO_DIRECTION[event.key]; + const direction = KEY_TO_DIRECTION[event.key] if (direction) { - event.preventDefault(); + event.preventDefault() - this._slide(direction); + this._slide(direction) } } - _getItemIndex(element) { - this._items = element && element.parentNode ? SelectorEngine.find(SELECTOR_ITEM, element.parentNode) : []; - return this._items.indexOf(element); + _getItemIndex (element) { + this._items = element && element.parentNode ? SelectorEngine.find(SELECTOR_ITEM, element.parentNode) : [] + return this._items.indexOf(element) } - _getItemByOrder(order, activeElement) { - const isNext = order === ORDER_NEXT; - return getNextActiveElement(this._items, activeElement, isNext, this._config.wrap); + _getItemByOrder (order, activeElement) { + const isNext = order ==== ORDER_NEXT + return getNextActiveElement(this._items, activeElement, isNext, this._config.wrap) } - _triggerSlideEvent(relatedTarget, eventDirectionName) { - const targetIndex = this._getItemIndex(relatedTarget); + _triggerSlideEvent (relatedTarget, eventDirectionName) { + const targetIndex = this._getItemIndex(relatedTarget) - const fromIndex = this._getItemIndex(SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element)); + const fromIndex = this._getItemIndex(SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element)) return EventHandler.trigger(this._element, EVENT_SLIDE, { relatedTarget, direction: eventDirectionName, from: fromIndex, to: targetIndex - }); + }) } - _setActiveIndicatorElement(element) { + _setActiveIndicatorElement (element) { if (this._indicatorsElement) { - const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE$1, this._indicatorsElement); - activeIndicator.classList.remove(CLASS_NAME_ACTIVE$2); - activeIndicator.removeAttribute('aria-current'); - const indicators = SelectorEngine.find(SELECTOR_INDICATOR, this._indicatorsElement); + const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE$1, this._indicatorsElement) + activeIndicator.classList.remove(CLASS_NAME_ACTIVE$2) + activeIndicator.removeAttribute('aria-current') + const indicators = SelectorEngine.find(SELECTOR_INDICATOR, this._indicatorsElement) for (let i = 0; i < indicators.length; i++) { - if (Number.parseInt(indicators[i].getAttribute('data-bs-slide-to'), 10) === this._getItemIndex(element)) { - indicators[i].classList.add(CLASS_NAME_ACTIVE$2); - indicators[i].setAttribute('aria-current', 'true'); - break; + if (Number.parseInt(indicators[i].getAttribute('data-bs-slide-to'), 10) ==== this._getItemIndex(element)) { + indicators[i].classList.add(CLASS_NAME_ACTIVE$2) + indicators[i].setAttribute('aria-current', 'true') + break } } } } - _updateInterval() { - const element = this._activeElement || SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element); + _updateInterval () { + const element = this._activeElement || SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element) if (!element) { - return; + return } - const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10); + const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10) if (elementInterval) { - this._config.defaultInterval = this._config.defaultInterval || this._config.interval; - this._config.interval = elementInterval; + this._config.defaultInterval = this._config.defaultInterval || this._config.interval + this._config.interval = elementInterval } else { - this._config.interval = this._config.defaultInterval || this._config.interval; + this._config.interval = this._config.defaultInterval || this._config.interval } } - _slide(directionOrOrder, element) { - const order = this._directionToOrder(directionOrOrder); + _slide (directionOrOrder, element) { + const order = this._directionToOrder(directionOrOrder) - const activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element); + const activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element) - const activeElementIndex = this._getItemIndex(activeElement); + const activeElementIndex = this._getItemIndex(activeElement) - const nextElement = element || this._getItemByOrder(order, activeElement); + const nextElement = element || this._getItemByOrder(order, activeElement) - const nextElementIndex = this._getItemIndex(nextElement); + const nextElementIndex = this._getItemIndex(nextElement) - const isCycling = Boolean(this._interval); - const isNext = order === ORDER_NEXT; - const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END; - const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV; + const isCycling = Boolean(this._interval) + const isNext = order ==== ORDER_NEXT + const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END + const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV - const eventDirectionName = this._orderToDirection(order); + const eventDirectionName = this._orderToDirection(order) if (nextElement && nextElement.classList.contains(CLASS_NAME_ACTIVE$2)) { - this._isSliding = false; - return; + this._isSliding = false + return } if (this._isSliding) { - return; + return } - const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName); + const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName) if (slideEvent.defaultPrevented) { - return; + return } if (!activeElement || !nextElement) { // Some weirdness is happening, so we bail - return; + return } - this._isSliding = true; + this._isSliding = true if (isCycling) { - this.pause(); + this.pause() } - this._setActiveIndicatorElement(nextElement); + this._setActiveIndicatorElement(nextElement) - this._activeElement = nextElement; + this._activeElement = nextElement const triggerSlidEvent = () => { EventHandler.trigger(this._element, EVENT_SLID, { @@ -1488,120 +1469,120 @@ direction: eventDirectionName, from: activeElementIndex, to: nextElementIndex - }); - }; + }) + } if (this._element.classList.contains(CLASS_NAME_SLIDE)) { - nextElement.classList.add(orderClassName); - reflow(nextElement); - activeElement.classList.add(directionalClassName); - nextElement.classList.add(directionalClassName); + nextElement.classList.add(orderClassName) + reflow(nextElement) + activeElement.classList.add(directionalClassName) + nextElement.classList.add(directionalClassName) const completeCallBack = () => { - nextElement.classList.remove(directionalClassName, orderClassName); - nextElement.classList.add(CLASS_NAME_ACTIVE$2); - activeElement.classList.remove(CLASS_NAME_ACTIVE$2, orderClassName, directionalClassName); - this._isSliding = false; - setTimeout(triggerSlidEvent, 0); - }; + nextElement.classList.remove(directionalClassName, orderClassName) + nextElement.classList.add(CLASS_NAME_ACTIVE$2) + activeElement.classList.remove(CLASS_NAME_ACTIVE$2, orderClassName, directionalClassName) + this._isSliding = false + setTimeout(triggerSlidEvent, 0) + } - this._queueCallback(completeCallBack, activeElement, true); + this._queueCallback(completeCallBack, activeElement, true) } else { - activeElement.classList.remove(CLASS_NAME_ACTIVE$2); - nextElement.classList.add(CLASS_NAME_ACTIVE$2); - this._isSliding = false; - triggerSlidEvent(); + activeElement.classList.remove(CLASS_NAME_ACTIVE$2) + nextElement.classList.add(CLASS_NAME_ACTIVE$2) + this._isSliding = false + triggerSlidEvent() } if (isCycling) { - this.cycle(); + this.cycle() } } - _directionToOrder(direction) { + _directionToOrder (direction) { if (![DIRECTION_RIGHT, DIRECTION_LEFT].includes(direction)) { - return direction; + return direction } if (isRTL()) { - return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT; + return direction ==== DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT } - return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV; + return direction ==== DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV } - _orderToDirection(order) { + _orderToDirection (order) { if (![ORDER_NEXT, ORDER_PREV].includes(order)) { - return order; + return order } if (isRTL()) { - return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT; + return order ==== ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT } - return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT; + return order ==== ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT } // Static - - static carouselInterface(element, config) { - const data = Carousel.getOrCreateInstance(element, config); + static carouselInterface (element, config) { + const data = Carousel.getOrCreateInstance(element, config) let { _config - } = data; + } = data - if (typeof config === 'object') { - _config = { ..._config, + if (typeof config ==== 'object') { + _config = { + ..._config, ...config - }; + } } - const action = typeof config === 'string' ? config : _config.slide; + const action = typeof config ==== 'string' ? config : _config.slide - if (typeof config === 'number') { - data.to(config); - } else if (typeof action === 'string') { - if (typeof data[action] === 'undefined') { - throw new TypeError(`No method named "${action}"`); + if (typeof config ==== 'number') { + data.to(config) + } else if (typeof action ==== 'string') { + if (typeof data[action] ==== 'undefined') { + throw new TypeError(`No method named "${action}"`) } - data[action](); + data[action]() } else if (_config.interval && _config.ride) { - data.pause(); - data.cycle(); + data.pause() + data.cycle() } } - static jQueryInterface(config) { + static jQueryInterface (config) { return this.each(function () { - Carousel.carouselInterface(this, config); - }); + Carousel.carouselInterface(this, config) + }) } - static dataApiClickHandler(event) { - const target = getElementFromSelector(this); + static dataApiClickHandler (event) { + const target = getElementFromSelector(this) if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) { - return; + return } - const config = { ...Manipulator.getDataAttributes(target), + const config = { + ...Manipulator.getDataAttributes(target), ...Manipulator.getDataAttributes(this) - }; - const slideIndex = this.getAttribute('data-bs-slide-to'); + } + const slideIndex = this.getAttribute('data-bs-slide-to') if (slideIndex) { - config.interval = false; + config.interval = false } - Carousel.carouselInterface(target, config); + Carousel.carouselInterface(target, config) if (slideIndex) { - Carousel.getInstance(target).to(slideIndex); + Carousel.getInstance(target).to(slideIndex) } - event.preventDefault(); + event.preventDefault() } - } /** * ------------------------------------------------------------------------ @@ -1609,15 +1590,14 @@ * ------------------------------------------------------------------------ */ - - EventHandler.on(document, EVENT_CLICK_DATA_API$5, SELECTOR_DATA_SLIDE, Carousel.dataApiClickHandler); + EventHandler.on(document, EVENT_CLICK_DATA_API$5, SELECTOR_DATA_SLIDE, Carousel.dataApiClickHandler) EventHandler.on(window, EVENT_LOAD_DATA_API$2, () => { - const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE); + const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE) for (let i = 0, len = carousels.length; i < len; i++) { - Carousel.carouselInterface(carousels[i], Carousel.getInstance(carousels[i])); + Carousel.carouselInterface(carousels[i], Carousel.getInstance(carousels[i])) } - }); + }) /** * ------------------------------------------------------------------------ * jQuery @@ -1625,7 +1605,7 @@ * add .Carousel to jQuery only if jQuery is present */ - defineJQueryPlugin(Carousel); + defineJQueryPlugin(Carousel) /** * -------------------------------------------------------------------------- @@ -1639,33 +1619,33 @@ * ------------------------------------------------------------------------ */ - const NAME$a = 'collapse'; - const DATA_KEY$9 = 'bs.collapse'; - const EVENT_KEY$9 = `.${DATA_KEY$9}`; - const DATA_API_KEY$5 = '.data-api'; + const NAME$a = 'collapse' + const DATA_KEY$9 = 'bs.collapse' + const EVENT_KEY$9 = `.${DATA_KEY$9}` + const DATA_API_KEY$5 = '.data-api' const Default$9 = { toggle: true, parent: null - }; + } const DefaultType$9 = { toggle: 'boolean', parent: '(null|element)' - }; - const EVENT_SHOW$5 = `show${EVENT_KEY$9}`; - const EVENT_SHOWN$5 = `shown${EVENT_KEY$9}`; - const EVENT_HIDE$5 = `hide${EVENT_KEY$9}`; - const EVENT_HIDDEN$5 = `hidden${EVENT_KEY$9}`; - const EVENT_CLICK_DATA_API$4 = `click${EVENT_KEY$9}${DATA_API_KEY$5}`; - const CLASS_NAME_SHOW$7 = 'show'; - const CLASS_NAME_COLLAPSE = 'collapse'; - const CLASS_NAME_COLLAPSING = 'collapsing'; - const CLASS_NAME_COLLAPSED = 'collapsed'; - const CLASS_NAME_DEEPER_CHILDREN = `:scope .${CLASS_NAME_COLLAPSE} .${CLASS_NAME_COLLAPSE}`; - const CLASS_NAME_HORIZONTAL = 'collapse-horizontal'; - const WIDTH = 'width'; - const HEIGHT = 'height'; - const SELECTOR_ACTIVES = '.collapse.show, .collapse.collapsing'; - const SELECTOR_DATA_TOGGLE$4 = '[data-bs-toggle="collapse"]'; + } + const EVENT_SHOW$5 = `show${EVENT_KEY$9}` + const EVENT_SHOWN$5 = `shown${EVENT_KEY$9}` + const EVENT_HIDE$5 = `hide${EVENT_KEY$9}` + const EVENT_HIDDEN$5 = `hidden${EVENT_KEY$9}` + const EVENT_CLICK_DATA_API$4 = `click${EVENT_KEY$9}${DATA_API_KEY$5}` + const CLASS_NAME_SHOW$7 = 'show' + const CLASS_NAME_COLLAPSE = 'collapse' + const CLASS_NAME_COLLAPSING = 'collapsing' + const CLASS_NAME_COLLAPSED = 'collapsed' + const CLASS_NAME_DEEPER_CHILDREN = `:scope .${CLASS_NAME_COLLAPSE} .${CLASS_NAME_COLLAPSE}` + const CLASS_NAME_HORIZONTAL = 'collapse-horizontal' + const WIDTH = 'width' + const HEIGHT = 'height' + const SELECTOR_ACTIVES = '.collapse.show, .collapse.collapsing' + const SELECTOR_DATA_TOGGLE$4 = '[data-bs-toggle="collapse"]' /** * ------------------------------------------------------------------------ * Class Definition @@ -1673,248 +1653,244 @@ */ class Collapse extends BaseComponent { - constructor(element, config) { - super(element); - this._isTransitioning = false; - this._config = this._getConfig(config); - this._triggerArray = []; - const toggleList = SelectorEngine.find(SELECTOR_DATA_TOGGLE$4); + constructor (element, config) { + super(element) + this._isTransitioning = false + this._config = this._getConfig(config) + this._triggerArray = [] + const toggleList = SelectorEngine.find(SELECTOR_DATA_TOGGLE$4) for (let i = 0, len = toggleList.length; i < len; i++) { - const elem = toggleList[i]; - const selector = getSelectorFromElement(elem); - const filterElement = SelectorEngine.find(selector).filter(foundElem => foundElem === this._element); + const elem = toggleList[i] + const selector = getSelectorFromElement(elem) + const filterElement = SelectorEngine.find(selector).filter(foundElem => foundElem ==== this._element) - if (selector !== null && filterElement.length) { - this._selector = selector; + if (selector !==== null && filterElement.length) { + this._selector = selector - this._triggerArray.push(elem); + this._triggerArray.push(elem) } } - this._initializeChildren(); + this._initializeChildren() if (!this._config.parent) { - this._addAriaAndCollapsedClass(this._triggerArray, this._isShown()); + this._addAriaAndCollapsedClass(this._triggerArray, this._isShown()) } if (this._config.toggle) { - this.toggle(); + this.toggle() } } // Getters - - static get Default() { - return Default$9; + static get Default () { + return Default$9 } - static get NAME() { - return NAME$a; + static get NAME () { + return NAME$a } // Public - - toggle() { + toggle () { if (this._isShown()) { - this.hide(); + this.hide() } else { - this.show(); + this.show() } } - show() { + show () { if (this._isTransitioning || this._isShown()) { - return; + return } - let actives = []; - let activesData; + let actives = [] + let activesData if (this._config.parent) { - const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent); - actives = SelectorEngine.find(SELECTOR_ACTIVES, this._config.parent).filter(elem => !children.includes(elem)); // remove children if greater depth + const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent) + actives = SelectorEngine.find(SELECTOR_ACTIVES, this._config.parent).filter(elem => !children.includes(elem)) // remove children if greater depth } - const container = SelectorEngine.findOne(this._selector); + const container = SelectorEngine.findOne(this._selector) if (actives.length) { - const tempActiveData = actives.find(elem => container !== elem); - activesData = tempActiveData ? Collapse.getInstance(tempActiveData) : null; + const tempActiveData = actives.find(elem => container !==== elem) + activesData = tempActiveData ? Collapse.getInstance(tempActiveData) : null if (activesData && activesData._isTransitioning) { - return; + return } } - const startEvent = EventHandler.trigger(this._element, EVENT_SHOW$5); + const startEvent = EventHandler.trigger(this._element, EVENT_SHOW$5) if (startEvent.defaultPrevented) { - return; + return } actives.forEach(elemActive => { - if (container !== elemActive) { + if (container !==== elemActive) { Collapse.getOrCreateInstance(elemActive, { toggle: false - }).hide(); + }).hide() } if (!activesData) { - Data.set(elemActive, DATA_KEY$9, null); + Data.set(elemActive, DATA_KEY$9, null) } - }); + }) - const dimension = this._getDimension(); + const dimension = this._getDimension() - this._element.classList.remove(CLASS_NAME_COLLAPSE); + this._element.classList.remove(CLASS_NAME_COLLAPSE) - this._element.classList.add(CLASS_NAME_COLLAPSING); + this._element.classList.add(CLASS_NAME_COLLAPSING) - this._element.style[dimension] = 0; + this._element.style[dimension] = 0 - this._addAriaAndCollapsedClass(this._triggerArray, true); + this._addAriaAndCollapsedClass(this._triggerArray, true) - this._isTransitioning = true; + this._isTransitioning = true const complete = () => { - this._isTransitioning = false; + this._isTransitioning = false - this._element.classList.remove(CLASS_NAME_COLLAPSING); + this._element.classList.remove(CLASS_NAME_COLLAPSING) - this._element.classList.add(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7); + this._element.classList.add(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7) - this._element.style[dimension] = ''; - EventHandler.trigger(this._element, EVENT_SHOWN$5); - }; - - const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1); - const scrollSize = `scroll${capitalizedDimension}`; - - this._queueCallback(complete, this._element, true); - - this._element.style[dimension] = `${this._element[scrollSize]}px`; - } - - hide() { - if (this._isTransitioning || !this._isShown()) { - return; + this._element.style[dimension] = '' + EventHandler.trigger(this._element, EVENT_SHOWN$5) } - const startEvent = EventHandler.trigger(this._element, EVENT_HIDE$5); + const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1) + const scrollSize = `scroll${capitalizedDimension}` + + this._queueCallback(complete, this._element, true) + + this._element.style[dimension] = `${this._element[scrollSize]}px` + } + + hide () { + if (this._isTransitioning || !this._isShown()) { + return + } + + const startEvent = EventHandler.trigger(this._element, EVENT_HIDE$5) if (startEvent.defaultPrevented) { - return; + return } - const dimension = this._getDimension(); + const dimension = this._getDimension() - this._element.style[dimension] = `${this._element.getBoundingClientRect()[dimension]}px`; - reflow(this._element); + this._element.style[dimension] = `${this._element.getBoundingClientRect()[dimension]}px` + reflow(this._element) - this._element.classList.add(CLASS_NAME_COLLAPSING); + this._element.classList.add(CLASS_NAME_COLLAPSING) - this._element.classList.remove(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7); + this._element.classList.remove(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7) - const triggerArrayLength = this._triggerArray.length; + const triggerArrayLength = this._triggerArray.length for (let i = 0; i < triggerArrayLength; i++) { - const trigger = this._triggerArray[i]; - const elem = getElementFromSelector(trigger); + const trigger = this._triggerArray[i] + const elem = getElementFromSelector(trigger) if (elem && !this._isShown(elem)) { - this._addAriaAndCollapsedClass([trigger], false); + this._addAriaAndCollapsedClass([trigger], false) } } - this._isTransitioning = true; + this._isTransitioning = true const complete = () => { - this._isTransitioning = false; + this._isTransitioning = false - this._element.classList.remove(CLASS_NAME_COLLAPSING); + this._element.classList.remove(CLASS_NAME_COLLAPSING) - this._element.classList.add(CLASS_NAME_COLLAPSE); + this._element.classList.add(CLASS_NAME_COLLAPSE) - EventHandler.trigger(this._element, EVENT_HIDDEN$5); - }; - - this._element.style[dimension] = ''; - - this._queueCallback(complete, this._element, true); - } - - _isShown(element = this._element) { - return element.classList.contains(CLASS_NAME_SHOW$7); - } // Private - - - _getConfig(config) { - config = { ...Default$9, - ...Manipulator.getDataAttributes(this._element), - ...config - }; - config.toggle = Boolean(config.toggle); // Coerce string values - - config.parent = getElement(config.parent); - typeCheckConfig(NAME$a, config, DefaultType$9); - return config; - } - - _getDimension() { - return this._element.classList.contains(CLASS_NAME_HORIZONTAL) ? WIDTH : HEIGHT; - } - - _initializeChildren() { - if (!this._config.parent) { - return; + EventHandler.trigger(this._element, EVENT_HIDDEN$5) } - const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent); - SelectorEngine.find(SELECTOR_DATA_TOGGLE$4, this._config.parent).filter(elem => !children.includes(elem)).forEach(element => { - const selected = getElementFromSelector(element); + this._element.style[dimension] = '' - if (selected) { - this._addAriaAndCollapsedClass([element], this._isShown(selected)); - } - }); + this._queueCallback(complete, this._element, true) } - _addAriaAndCollapsedClass(triggerArray, isOpen) { + _isShown (element = this._element) { + return element.classList.contains(CLASS_NAME_SHOW$7) + } // Private + + _getConfig (config) { + config = { + ...Default$9, + ...Manipulator.getDataAttributes(this._element), + ...config + } + config.toggle = Boolean(config.toggle) // Coerce string values + + config.parent = getElement(config.parent) + typeCheckConfig(NAME$a, config, DefaultType$9) + return config + } + + _getDimension () { + return this._element.classList.contains(CLASS_NAME_HORIZONTAL) ? WIDTH : HEIGHT + } + + _initializeChildren () { + if (!this._config.parent) { + return + } + + const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent) + SelectorEngine.find(SELECTOR_DATA_TOGGLE$4, this._config.parent).filter(elem => !children.includes(elem)).forEach(element => { + const selected = getElementFromSelector(element) + + if (selected) { + this._addAriaAndCollapsedClass([element], this._isShown(selected)) + } + }) + } + + _addAriaAndCollapsedClass (triggerArray, isOpen) { if (!triggerArray.length) { - return; + return } triggerArray.forEach(elem => { if (isOpen) { - elem.classList.remove(CLASS_NAME_COLLAPSED); + elem.classList.remove(CLASS_NAME_COLLAPSED) } else { - elem.classList.add(CLASS_NAME_COLLAPSED); + elem.classList.add(CLASS_NAME_COLLAPSED) } - elem.setAttribute('aria-expanded', isOpen); - }); + elem.setAttribute('aria-expanded', isOpen) + }) } // Static - - static jQueryInterface(config) { + static jQueryInterface (config) { return this.each(function () { - const _config = {}; + const _config = {} - if (typeof config === 'string' && /show|hide/.test(config)) { - _config.toggle = false; + if (typeof config ==== 'string' && /show|hide/.test(config)) { + _config.toggle = false } - const data = Collapse.getOrCreateInstance(this, _config); + const data = Collapse.getOrCreateInstance(this, _config) - if (typeof config === 'string') { - if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); + if (typeof config ==== 'string') { + if (typeof data[config] ==== 'undefined') { + throw new TypeError(`No method named "${config}"`) } - data[config](); + data[config]() } - }); + }) } - } /** * ------------------------------------------------------------------------ @@ -1922,21 +1898,20 @@ * ------------------------------------------------------------------------ */ - EventHandler.on(document, EVENT_CLICK_DATA_API$4, SELECTOR_DATA_TOGGLE$4, function (event) { // preventDefault only for elements (which change the URL) not inside the collapsible element - if (event.target.tagName === 'A' || event.delegateTarget && event.delegateTarget.tagName === 'A') { - event.preventDefault(); + if (event.target.tagName ==== 'A' || event.delegateTarget && event.delegateTarget.tagName ==== 'A') { + event.preventDefault() } - const selector = getSelectorFromElement(this); - const selectorElements = SelectorEngine.find(selector); + const selector = getSelectorFromElement(this) + const selectorElements = SelectorEngine.find(selector) selectorElements.forEach(element => { Collapse.getOrCreateInstance(element, { toggle: false - }).toggle(); - }); - }); + }).toggle() + }) + }) /** * ------------------------------------------------------------------------ * jQuery @@ -1944,7 +1919,7 @@ * add .Collapse to jQuery only if jQuery is present */ - defineJQueryPlugin(Collapse); + defineJQueryPlugin(Collapse) /** * -------------------------------------------------------------------------- @@ -1958,40 +1933,40 @@ * ------------------------------------------------------------------------ */ - const NAME$9 = 'dropdown'; - const DATA_KEY$8 = 'bs.dropdown'; - const EVENT_KEY$8 = `.${DATA_KEY$8}`; - const DATA_API_KEY$4 = '.data-api'; - const ESCAPE_KEY$2 = 'Escape'; - const SPACE_KEY = 'Space'; - const TAB_KEY$1 = 'Tab'; - const ARROW_UP_KEY = 'ArrowUp'; - const ARROW_DOWN_KEY = 'ArrowDown'; - const RIGHT_MOUSE_BUTTON = 2; // MouseEvent.button value for the secondary button, usually the right button + const NAME$9 = 'dropdown' + const DATA_KEY$8 = 'bs.dropdown' + const EVENT_KEY$8 = `.${DATA_KEY$8}` + const DATA_API_KEY$4 = '.data-api' + const ESCAPE_KEY$2 = 'Escape' + const SPACE_KEY = 'Space' + const TAB_KEY$1 = 'Tab' + const ARROW_UP_KEY = 'ArrowUp' + const ARROW_DOWN_KEY = 'ArrowDown' + const RIGHT_MOUSE_BUTTON = 2 // MouseEvent.button value for the secondary button, usually the right button - const REGEXP_KEYDOWN = new RegExp(`${ARROW_UP_KEY}|${ARROW_DOWN_KEY}|${ESCAPE_KEY$2}`); - const EVENT_HIDE$4 = `hide${EVENT_KEY$8}`; - const EVENT_HIDDEN$4 = `hidden${EVENT_KEY$8}`; - const EVENT_SHOW$4 = `show${EVENT_KEY$8}`; - const EVENT_SHOWN$4 = `shown${EVENT_KEY$8}`; - const EVENT_CLICK_DATA_API$3 = `click${EVENT_KEY$8}${DATA_API_KEY$4}`; - const EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY$8}${DATA_API_KEY$4}`; - const EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY$8}${DATA_API_KEY$4}`; - const CLASS_NAME_SHOW$6 = 'show'; - const CLASS_NAME_DROPUP = 'dropup'; - const CLASS_NAME_DROPEND = 'dropend'; - const CLASS_NAME_DROPSTART = 'dropstart'; - const CLASS_NAME_NAVBAR = 'navbar'; - const SELECTOR_DATA_TOGGLE$3 = '[data-bs-toggle="dropdown"]'; - const SELECTOR_MENU = '.dropdown-menu'; - const SELECTOR_NAVBAR_NAV = '.navbar-nav'; - const SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)'; - const PLACEMENT_TOP = isRTL() ? 'top-end' : 'top-start'; - const PLACEMENT_TOPEND = isRTL() ? 'top-start' : 'top-end'; - const PLACEMENT_BOTTOM = isRTL() ? 'bottom-end' : 'bottom-start'; - const PLACEMENT_BOTTOMEND = isRTL() ? 'bottom-start' : 'bottom-end'; - const PLACEMENT_RIGHT = isRTL() ? 'left-start' : 'right-start'; - const PLACEMENT_LEFT = isRTL() ? 'right-start' : 'left-start'; + const REGEXP_KEYDOWN = new RegExp(`${ARROW_UP_KEY}|${ARROW_DOWN_KEY}|${ESCAPE_KEY$2}`) + const EVENT_HIDE$4 = `hide${EVENT_KEY$8}` + const EVENT_HIDDEN$4 = `hidden${EVENT_KEY$8}` + const EVENT_SHOW$4 = `show${EVENT_KEY$8}` + const EVENT_SHOWN$4 = `shown${EVENT_KEY$8}` + const EVENT_CLICK_DATA_API$3 = `click${EVENT_KEY$8}${DATA_API_KEY$4}` + const EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY$8}${DATA_API_KEY$4}` + const EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY$8}${DATA_API_KEY$4}` + const CLASS_NAME_SHOW$6 = 'show' + const CLASS_NAME_DROPUP = 'dropup' + const CLASS_NAME_DROPEND = 'dropend' + const CLASS_NAME_DROPSTART = 'dropstart' + const CLASS_NAME_NAVBAR = 'navbar' + const SELECTOR_DATA_TOGGLE$3 = '[data-bs-toggle="dropdown"]' + const SELECTOR_MENU = '.dropdown-menu' + const SELECTOR_NAVBAR_NAV = '.navbar-nav' + const SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)' + const PLACEMENT_TOP = isRTL() ? 'top-end' : 'top-start' + const PLACEMENT_TOPEND = isRTL() ? 'top-start' : 'top-end' + const PLACEMENT_BOTTOM = isRTL() ? 'bottom-end' : 'bottom-start' + const PLACEMENT_BOTTOMEND = isRTL() ? 'bottom-start' : 'bottom-end' + const PLACEMENT_RIGHT = isRTL() ? 'left-start' : 'right-start' + const PLACEMENT_LEFT = isRTL() ? 'right-start' : 'left-start' const Default$8 = { offset: [0, 2], boundary: 'clippingParents', @@ -1999,7 +1974,7 @@ display: 'dynamic', popperConfig: null, autoClose: true - }; + } const DefaultType$8 = { offset: '(array|string|function)', boundary: '(string|element)', @@ -2007,7 +1982,7 @@ display: 'string', popperConfig: '(null|object|function)', autoClose: '(boolean|string)' - }; + } /** * ------------------------------------------------------------------------ * Class Definition @@ -2015,219 +1990,214 @@ */ class Dropdown extends BaseComponent { - constructor(element, config) { - super(element); - this._popper = null; - this._config = this._getConfig(config); - this._menu = this._getMenuElement(); - this._inNavbar = this._detectNavbar(); + constructor (element, config) { + super(element) + this._popper = null + this._config = this._getConfig(config) + this._menu = this._getMenuElement() + this._inNavbar = this._detectNavbar() } // Getters - - static get Default() { - return Default$8; + static get Default () { + return Default$8 } - static get DefaultType() { - return DefaultType$8; + static get DefaultType () { + return DefaultType$8 } - static get NAME() { - return NAME$9; + static get NAME () { + return NAME$9 } // Public - - toggle() { - return this._isShown() ? this.hide() : this.show(); + toggle () { + return this._isShown() ? this.hide() : this.show() } - show() { + show () { if (isDisabled(this._element) || this._isShown(this._menu)) { - return; + return } const relatedTarget = { relatedTarget: this._element - }; - const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$4, relatedTarget); + } + const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$4, relatedTarget) if (showEvent.defaultPrevented) { - return; + return } - const parent = Dropdown.getParentFromElement(this._element); // Totally disable Popper for Dropdowns in Navbar + const parent = Dropdown.getParentFromElement(this._element) // Totally disable Popper for Dropdowns in Navbar if (this._inNavbar) { - Manipulator.setDataAttribute(this._menu, 'popper', 'none'); + Manipulator.setDataAttribute(this._menu, 'popper', 'none') } else { - this._createPopper(parent); + this._createPopper(parent) } // If this is a touch-enabled device we add extra // empty mouseover listeners to the body's immediate children; // only needed because of broken event delegation on iOS // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html - if ('ontouchstart' in document.documentElement && !parent.closest(SELECTOR_NAVBAR_NAV)) { - [].concat(...document.body.children).forEach(elem => EventHandler.on(elem, 'mouseover', noop)); + [].concat(...document.body.children).forEach(elem => EventHandler.on(elem, 'mouseover', noop)) } - this._element.focus(); + this._element.focus() - this._element.setAttribute('aria-expanded', true); + this._element.setAttribute('aria-expanded', true) - this._menu.classList.add(CLASS_NAME_SHOW$6); + this._menu.classList.add(CLASS_NAME_SHOW$6) - this._element.classList.add(CLASS_NAME_SHOW$6); + this._element.classList.add(CLASS_NAME_SHOW$6) - EventHandler.trigger(this._element, EVENT_SHOWN$4, relatedTarget); + EventHandler.trigger(this._element, EVENT_SHOWN$4, relatedTarget) } - hide() { + hide () { if (isDisabled(this._element) || !this._isShown(this._menu)) { - return; + return } const relatedTarget = { relatedTarget: this._element - }; - - this._completeHide(relatedTarget); - } - - dispose() { - if (this._popper) { - this._popper.destroy(); } - super.dispose(); + this._completeHide(relatedTarget) } - update() { - this._inNavbar = this._detectNavbar(); + dispose () { + if (this._popper) { + this._popper.destroy() + } + + super.dispose() + } + + update () { + this._inNavbar = this._detectNavbar() if (this._popper) { - this._popper.update(); + this._popper.update() } } // Private - - _completeHide(relatedTarget) { - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$4, relatedTarget); + _completeHide (relatedTarget) { + const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$4, relatedTarget) if (hideEvent.defaultPrevented) { - return; + return } // If this is a touch-enabled device we remove the extra // empty mouseover listeners we added for iOS support - if ('ontouchstart' in document.documentElement) { - [].concat(...document.body.children).forEach(elem => EventHandler.off(elem, 'mouseover', noop)); + [].concat(...document.body.children).forEach(elem => EventHandler.off(elem, 'mouseover', noop)) } if (this._popper) { - this._popper.destroy(); + this._popper.destroy() } - this._menu.classList.remove(CLASS_NAME_SHOW$6); + this._menu.classList.remove(CLASS_NAME_SHOW$6) - this._element.classList.remove(CLASS_NAME_SHOW$6); + this._element.classList.remove(CLASS_NAME_SHOW$6) - this._element.setAttribute('aria-expanded', 'false'); + this._element.setAttribute('aria-expanded', 'false') - Manipulator.removeDataAttribute(this._menu, 'popper'); - EventHandler.trigger(this._element, EVENT_HIDDEN$4, relatedTarget); + Manipulator.removeDataAttribute(this._menu, 'popper') + EventHandler.trigger(this._element, EVENT_HIDDEN$4, relatedTarget) } - _getConfig(config) { - config = { ...this.constructor.Default, + _getConfig (config) { + config = { + ...this.constructor.Default, ...Manipulator.getDataAttributes(this._element), ...config - }; - typeCheckConfig(NAME$9, config, this.constructor.DefaultType); + } + typeCheckConfig(NAME$9, config, this.constructor.DefaultType) - if (typeof config.reference === 'object' && !isElement(config.reference) && typeof config.reference.getBoundingClientRect !== 'function') { + if (typeof config.reference ==== 'object' && !isElement(config.reference) && typeof config.reference.getBoundingClientRect !==== 'function') { // Popper virtual elements require a getBoundingClientRect method - throw new TypeError(`${NAME$9.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`); + throw new TypeError(`${NAME$9.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`) } - return config; + return config } - _createPopper(parent) { - if (typeof Popper__namespace === 'undefined') { - throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org)'); + _createPopper (parent) { + if (typeof Popper__namespace ==== 'undefined') { + throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org)') } - let referenceElement = this._element; + let referenceElement = this._element - if (this._config.reference === 'parent') { - referenceElement = parent; + if (this._config.reference ==== 'parent') { + referenceElement = parent } else if (isElement(this._config.reference)) { - referenceElement = getElement(this._config.reference); - } else if (typeof this._config.reference === 'object') { - referenceElement = this._config.reference; + referenceElement = getElement(this._config.reference) + } else if (typeof this._config.reference ==== 'object') { + referenceElement = this._config.reference } - const popperConfig = this._getPopperConfig(); + const popperConfig = this._getPopperConfig() - const isDisplayStatic = popperConfig.modifiers.find(modifier => modifier.name === 'applyStyles' && modifier.enabled === false); - this._popper = Popper__namespace.createPopper(referenceElement, this._menu, popperConfig); + const isDisplayStatic = popperConfig.modifiers.find(modifier => modifier.name ==== 'applyStyles' && modifier.enabled ==== false) + this._popper = Popper__namespace.createPopper(referenceElement, this._menu, popperConfig) if (isDisplayStatic) { - Manipulator.setDataAttribute(this._menu, 'popper', 'static'); + Manipulator.setDataAttribute(this._menu, 'popper', 'static') } } - _isShown(element = this._element) { - return element.classList.contains(CLASS_NAME_SHOW$6); + _isShown (element = this._element) { + return element.classList.contains(CLASS_NAME_SHOW$6) } - _getMenuElement() { - return SelectorEngine.next(this._element, SELECTOR_MENU)[0]; + _getMenuElement () { + return SelectorEngine.next(this._element, SELECTOR_MENU)[0] } - _getPlacement() { - const parentDropdown = this._element.parentNode; + _getPlacement () { + const parentDropdown = this._element.parentNode if (parentDropdown.classList.contains(CLASS_NAME_DROPEND)) { - return PLACEMENT_RIGHT; + return PLACEMENT_RIGHT } if (parentDropdown.classList.contains(CLASS_NAME_DROPSTART)) { - return PLACEMENT_LEFT; + return PLACEMENT_LEFT } // We need to trim the value because custom properties can also include spaces - - const isEnd = getComputedStyle(this._menu).getPropertyValue('--bs-position').trim() === 'end'; + const isEnd = getComputedStyle(this._menu).getPropertyValue('--bs-position').trim() ==== 'end' if (parentDropdown.classList.contains(CLASS_NAME_DROPUP)) { - return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP; + return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP } - return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM; + return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM } - _detectNavbar() { - return this._element.closest(`.${CLASS_NAME_NAVBAR}`) !== null; + _detectNavbar () { + return this._element.closest(`.${CLASS_NAME_NAVBAR}`) !==== null } - _getOffset() { + _getOffset () { const { offset - } = this._config; + } = this._config - if (typeof offset === 'string') { - return offset.split(',').map(val => Number.parseInt(val, 10)); + if (typeof offset ==== 'string') { + return offset.split(',').map(val => Number.parseInt(val, 10)) } - if (typeof offset === 'function') { - return popperData => offset(popperData, this._element); + if (typeof offset ==== 'function') { + return popperData => offset(popperData, this._element) } - return offset; + return offset } - _getPopperConfig() { + _getPopperConfig () { const defaultBsPopperConfig = { placement: this._getPlacement(), modifiers: [{ @@ -2241,101 +2211,99 @@ offset: this._getOffset() } }] - }; // Disable Popper if we have a static display + } // Disable Popper if we have a static display - if (this._config.display === 'static') { + if (this._config.display ==== 'static') { defaultBsPopperConfig.modifiers = [{ name: 'applyStyles', enabled: false - }]; + }] } - return { ...defaultBsPopperConfig, - ...(typeof this._config.popperConfig === 'function' ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig) - }; + return { + ...defaultBsPopperConfig, + ...(typeof this._config.popperConfig ==== 'function' ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig) + } } - _selectMenuItem({ + _selectMenuItem ({ key, target }) { - const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(isVisible); + const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(isVisible) if (!items.length) { - return; + return } // if target isn't included in items (e.g. when expanding the dropdown) // allow cycling to get the last item in case key equals ARROW_UP_KEY - - getNextActiveElement(items, target, key === ARROW_DOWN_KEY, !items.includes(target)).focus(); + getNextActiveElement(items, target, key ==== ARROW_DOWN_KEY, !items.includes(target)).focus() } // Static - - static jQueryInterface(config) { + static jQueryInterface (config) { return this.each(function () { - const data = Dropdown.getOrCreateInstance(this, config); + const data = Dropdown.getOrCreateInstance(this, config) - if (typeof config !== 'string') { - return; + if (typeof config !==== 'string') { + return } - if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); + if (typeof data[config] ==== 'undefined') { + throw new TypeError(`No method named "${config}"`) } - data[config](); - }); + data[config]() + }) } - static clearMenus(event) { - if (event && (event.button === RIGHT_MOUSE_BUTTON || event.type === 'keyup' && event.key !== TAB_KEY$1)) { - return; + static clearMenus (event) { + if (event && (event.button ==== RIGHT_MOUSE_BUTTON || event.type ==== 'keyup' && event.key !==== TAB_KEY$1)) { + return } - const toggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE$3); + const toggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE$3) for (let i = 0, len = toggles.length; i < len; i++) { - const context = Dropdown.getInstance(toggles[i]); + const context = Dropdown.getInstance(toggles[i]) - if (!context || context._config.autoClose === false) { - continue; + if (!context || context._config.autoClose ==== false) { + continue } if (!context._isShown()) { - continue; + continue } const relatedTarget = { relatedTarget: context._element - }; + } if (event) { - const composedPath = event.composedPath(); - const isMenuTarget = composedPath.includes(context._menu); + const composedPath = event.composedPath() + const isMenuTarget = composedPath.includes(context._menu) - if (composedPath.includes(context._element) || context._config.autoClose === 'inside' && !isMenuTarget || context._config.autoClose === 'outside' && isMenuTarget) { - continue; + if (composedPath.includes(context._element) || context._config.autoClose ==== 'inside' && !isMenuTarget || context._config.autoClose ==== 'outside' && isMenuTarget) { + continue } // Tab navigation through the dropdown menu or events from contained inputs shouldn't close the menu - - if (context._menu.contains(event.target) && (event.type === 'keyup' && event.key === TAB_KEY$1 || /input|select|option|textarea|form/i.test(event.target.tagName))) { - continue; + if (context._menu.contains(event.target) && (event.type ==== 'keyup' && event.key ==== TAB_KEY$1 || /input|select|option|textarea|form/i.test(event.target.tagName))) { + continue } - if (event.type === 'click') { - relatedTarget.clickEvent = event; + if (event.type ==== 'click') { + relatedTarget.clickEvent = event } } - context._completeHide(relatedTarget); + context._completeHide(relatedTarget) } } - static getParentFromElement(element) { - return getElementFromSelector(element) || element.parentNode; + static getParentFromElement (element) { + return getElementFromSelector(element) || element.parentNode } - static dataApiKeydownHandler(event) { + static dataApiKeydownHandler (event) { // If not input/textarea: // - And not a key in REGEXP_KEYDOWN => not a dropdown command // If input/textarea: @@ -2343,46 +2311,45 @@ // - If key is other than escape // - If key is not up or down => not a dropdown command // - If trigger inside the menu => not a dropdown command - if (/input|textarea/i.test(event.target.tagName) ? event.key === SPACE_KEY || event.key !== ESCAPE_KEY$2 && (event.key !== ARROW_DOWN_KEY && event.key !== ARROW_UP_KEY || event.target.closest(SELECTOR_MENU)) : !REGEXP_KEYDOWN.test(event.key)) { - return; + if (/input|textarea/i.test(event.target.tagName) ? event.key ==== SPACE_KEY || event.key !==== ESCAPE_KEY$2 && (event.key !==== ARROW_DOWN_KEY && event.key !==== ARROW_UP_KEY || event.target.closest(SELECTOR_MENU)) : !REGEXP_KEYDOWN.test(event.key)) { + return } - const isActive = this.classList.contains(CLASS_NAME_SHOW$6); + const isActive = this.classList.contains(CLASS_NAME_SHOW$6) - if (!isActive && event.key === ESCAPE_KEY$2) { - return; + if (!isActive && event.key ==== ESCAPE_KEY$2) { + return } - event.preventDefault(); - event.stopPropagation(); + event.preventDefault() + event.stopPropagation() if (isDisabled(this)) { - return; + return } - const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE$3) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE$3)[0]; - const instance = Dropdown.getOrCreateInstance(getToggleButton); + const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE$3) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE$3)[0] + const instance = Dropdown.getOrCreateInstance(getToggleButton) - if (event.key === ESCAPE_KEY$2) { - instance.hide(); - return; + if (event.key ==== ESCAPE_KEY$2) { + instance.hide() + return } - if (event.key === ARROW_UP_KEY || event.key === ARROW_DOWN_KEY) { + if (event.key ==== ARROW_UP_KEY || event.key ==== ARROW_DOWN_KEY) { if (!isActive) { - instance.show(); + instance.show() } - instance._selectMenuItem(event); + instance._selectMenuItem(event) - return; + return } if (!isActive || event.key === SPACE_KEY) { - Dropdown.clearMenus(); + Dropdown.clearMenus() } } - } /** * ------------------------------------------------------------------------ @@ -2390,15 +2357,14 @@ * ------------------------------------------------------------------------ */ - - EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE$3, Dropdown.dataApiKeydownHandler); - EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown.dataApiKeydownHandler); - EventHandler.on(document, EVENT_CLICK_DATA_API$3, Dropdown.clearMenus); - EventHandler.on(document, EVENT_KEYUP_DATA_API, Dropdown.clearMenus); + EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE$3, Dropdown.dataApiKeydownHandler) + EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown.dataApiKeydownHandler) + EventHandler.on(document, EVENT_CLICK_DATA_API$3, Dropdown.clearMenus) + EventHandler.on(document, EVENT_KEYUP_DATA_API, Dropdown.clearMenus) EventHandler.on(document, EVENT_CLICK_DATA_API$3, SELECTOR_DATA_TOGGLE$3, function (event) { - event.preventDefault(); - Dropdown.getOrCreateInstance(this).toggle(); - }); + event.preventDefault() + Dropdown.getOrCreateInstance(this).toggle() + }) /** * ------------------------------------------------------------------------ * jQuery @@ -2406,7 +2372,7 @@ * add .Dropdown to jQuery only if jQuery is present */ - defineJQueryPlugin(Dropdown); + defineJQueryPlugin(Dropdown) /** * -------------------------------------------------------------------------- @@ -2414,102 +2380,99 @@ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - const SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top'; - const SELECTOR_STICKY_CONTENT = '.sticky-top'; + const SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top' + const SELECTOR_STICKY_CONTENT = '.sticky-top' class ScrollBarHelper { - constructor() { - this._element = document.body; + constructor () { + this._element = document.body } - getWidth() { + getWidth () { // https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth#usage_notes - const documentWidth = document.documentElement.clientWidth; - return Math.abs(window.innerWidth - documentWidth); + const documentWidth = document.documentElement.clientWidth + return Math.abs(window.innerWidth - documentWidth) } - hide() { - const width = this.getWidth(); + hide () { + const width = this.getWidth() - this._disableOverFlow(); // give padding to element to balance the hidden scrollbar width + this._disableOverFlow() // give padding to element to balance the hidden scrollbar width + this._setElementAttributes(this._element, 'paddingRight', calculatedValue => calculatedValue + width) // trick: We adjust positive paddingRight and negative marginRight to sticky-top elements to keep showing fullwidth - this._setElementAttributes(this._element, 'paddingRight', calculatedValue => calculatedValue + width); // trick: We adjust positive paddingRight and negative marginRight to sticky-top elements to keep showing fullwidth + this._setElementAttributes(SELECTOR_FIXED_CONTENT, 'paddingRight', calculatedValue => calculatedValue + width) - - this._setElementAttributes(SELECTOR_FIXED_CONTENT, 'paddingRight', calculatedValue => calculatedValue + width); - - this._setElementAttributes(SELECTOR_STICKY_CONTENT, 'marginRight', calculatedValue => calculatedValue - width); + this._setElementAttributes(SELECTOR_STICKY_CONTENT, 'marginRight', calculatedValue => calculatedValue - width) } - _disableOverFlow() { - this._saveInitialAttribute(this._element, 'overflow'); + _disableOverFlow () { + this._saveInitialAttribute(this._element, 'overflow') - this._element.style.overflow = 'hidden'; + this._element.style.overflow = 'hidden' } - _setElementAttributes(selector, styleProp, callback) { - const scrollbarWidth = this.getWidth(); + _setElementAttributes (selector, styleProp, callback) { + const scrollbarWidth = this.getWidth() const manipulationCallBack = element => { - if (element !== this._element && window.innerWidth > element.clientWidth + scrollbarWidth) { - return; + if (element !=== this._element && window.innerWidth > element.clientWidth + scrollbarWidth) { + return } - this._saveInitialAttribute(element, styleProp); + this._saveInitialAttribute(element, styleProp) - const calculatedValue = window.getComputedStyle(element)[styleProp]; - element.style[styleProp] = `${callback(Number.parseFloat(calculatedValue))}px`; - }; + const calculatedValue = window.getComputedStyle(element)[styleProp] + element.style[styleProp] = `${callback(Number.parseFloat(calculatedValue))}px` + } - this._applyManipulationCallback(selector, manipulationCallBack); + this._applyManipulationCallback(selector, manipulationCallBack) } - reset() { - this._resetElementAttributes(this._element, 'overflow'); + reset () { + this._resetElementAttributes(this._element, 'overflow') - this._resetElementAttributes(this._element, 'paddingRight'); + this._resetElementAttributes(this._element, 'paddingRight') - this._resetElementAttributes(SELECTOR_FIXED_CONTENT, 'paddingRight'); + this._resetElementAttributes(SELECTOR_FIXED_CONTENT, 'paddingRight') - this._resetElementAttributes(SELECTOR_STICKY_CONTENT, 'marginRight'); + this._resetElementAttributes(SELECTOR_STICKY_CONTENT, 'marginRight') } - _saveInitialAttribute(element, styleProp) { - const actualValue = element.style[styleProp]; + _saveInitialAttribute (element, styleProp) { + const actualValue = element.style[styleProp] if (actualValue) { - Manipulator.setDataAttribute(element, styleProp, actualValue); + Manipulator.setDataAttribute(element, styleProp, actualValue) } } - _resetElementAttributes(selector, styleProp) { + _resetElementAttributes (selector, styleProp) { const manipulationCallBack = element => { - const value = Manipulator.getDataAttribute(element, styleProp); + const value = Manipulator.getDataAttribute(element, styleProp) if (typeof value === 'undefined') { - element.style.removeProperty(styleProp); + element.style.removeProperty(styleProp) } else { - Manipulator.removeDataAttribute(element, styleProp); - element.style[styleProp] = value; + Manipulator.removeDataAttribute(element, styleProp) + element.style[styleProp] = value } - }; + } - this._applyManipulationCallback(selector, manipulationCallBack); + this._applyManipulationCallback(selector, manipulationCallBack) } - _applyManipulationCallback(selector, callBack) { + _applyManipulationCallback (selector, callBack) { if (isElement(selector)) { - callBack(selector); + callBack(selector) } else { - SelectorEngine.find(selector, this._element).forEach(callBack); + SelectorEngine.find(selector, this._element).forEach(callBack) } } - isOverflowing() { - return this.getWidth() > 0; + isOverflowing () { + return this.getWidth() > 0 } - } /** @@ -2526,114 +2489,113 @@ rootElement: 'body', // give the choice to place backdrop under different elements clickCallback: null - }; + } const DefaultType$7 = { className: 'string', isVisible: 'boolean', isAnimated: 'boolean', rootElement: '(element|string)', clickCallback: '(function|null)' - }; - const NAME$8 = 'backdrop'; - const CLASS_NAME_FADE$4 = 'fade'; - const CLASS_NAME_SHOW$5 = 'show'; - const EVENT_MOUSEDOWN = `mousedown.bs.${NAME$8}`; + } + const NAME$8 = 'backdrop' + const CLASS_NAME_FADE$4 = 'fade' + const CLASS_NAME_SHOW$5 = 'show' + const EVENT_MOUSEDOWN = `mousedown.bs.${NAME$8}` class Backdrop { - constructor(config) { - this._config = this._getConfig(config); - this._isAppended = false; - this._element = null; + constructor (config) { + this._config = this._getConfig(config) + this._isAppended = false + this._element = null } - show(callback) { + show (callback) { if (!this._config.isVisible) { - execute(callback); - return; + execute(callback) + return } - this._append(); + this._append() if (this._config.isAnimated) { - reflow(this._getElement()); + reflow(this._getElement()) } - this._getElement().classList.add(CLASS_NAME_SHOW$5); + this._getElement().classList.add(CLASS_NAME_SHOW$5) this._emulateAnimation(() => { - execute(callback); - }); + execute(callback) + }) } - hide(callback) { + hide (callback) { if (!this._config.isVisible) { - execute(callback); - return; + execute(callback) + return } - this._getElement().classList.remove(CLASS_NAME_SHOW$5); + this._getElement().classList.remove(CLASS_NAME_SHOW$5) this._emulateAnimation(() => { - this.dispose(); - execute(callback); - }); + this.dispose() + execute(callback) + }) } // Private - - _getElement() { + _getElement () { if (!this._element) { - const backdrop = document.createElement('div'); - backdrop.className = this._config.className; + const backdrop = document.createElement('div') + backdrop.className = this._config.className if (this._config.isAnimated) { - backdrop.classList.add(CLASS_NAME_FADE$4); + backdrop.classList.add(CLASS_NAME_FADE$4) } - this._element = backdrop; + this._element = backdrop } - return this._element; + return this._element } - _getConfig(config) { - config = { ...Default$7, + _getConfig (config) { + config = { + ...Default$7, ...(typeof config === 'object' ? config : {}) - }; // use getElement() with the default "body" to get a fresh Element on each instantiation + } // use getElement() with the default "body" to get a fresh Element on each instantiation - config.rootElement = getElement(config.rootElement); - typeCheckConfig(NAME$8, config, DefaultType$7); - return config; + config.rootElement = getElement(config.rootElement) + typeCheckConfig(NAME$8, config, DefaultType$7) + return config } - _append() { + _append () { if (this._isAppended) { - return; + return } - this._config.rootElement.append(this._getElement()); + this._config.rootElement.append(this._getElement()) EventHandler.on(this._getElement(), EVENT_MOUSEDOWN, () => { - execute(this._config.clickCallback); - }); - this._isAppended = true; + execute(this._config.clickCallback) + }) + this._isAppended = true } - dispose() { + dispose () { if (!this._isAppended) { - return; + return } - EventHandler.off(this._element, EVENT_MOUSEDOWN); + EventHandler.off(this._element, EVENT_MOUSEDOWN) - this._element.remove(); + this._element.remove() - this._isAppended = false; + this._isAppended = false } - _emulateAnimation(callback) { - executeAfterTransition(callback, this._getElement(), this._config.isAnimated); + _emulateAnimation (callback) { + executeAfterTransition(callback, this._getElement(), this._config.isAnimated) } - } /** @@ -2646,97 +2608,96 @@ trapElement: null, // The element to trap focus inside of autofocus: true - }; + } const DefaultType$6 = { trapElement: 'element', autofocus: 'boolean' - }; - const NAME$7 = 'focustrap'; - const DATA_KEY$7 = 'bs.focustrap'; - const EVENT_KEY$7 = `.${DATA_KEY$7}`; - const EVENT_FOCUSIN$1 = `focusin${EVENT_KEY$7}`; - const EVENT_KEYDOWN_TAB = `keydown.tab${EVENT_KEY$7}`; - const TAB_KEY = 'Tab'; - const TAB_NAV_FORWARD = 'forward'; - const TAB_NAV_BACKWARD = 'backward'; + } + const NAME$7 = 'focustrap' + const DATA_KEY$7 = 'bs.focustrap' + const EVENT_KEY$7 = `.${DATA_KEY$7}` + const EVENT_FOCUSIN$1 = `focusin${EVENT_KEY$7}` + const EVENT_KEYDOWN_TAB = `keydown.tab${EVENT_KEY$7}` + const TAB_KEY = 'Tab' + const TAB_NAV_FORWARD = 'forward' + const TAB_NAV_BACKWARD = 'backward' class FocusTrap { - constructor(config) { - this._config = this._getConfig(config); - this._isActive = false; - this._lastTabNavDirection = null; + constructor (config) { + this._config = this._getConfig(config) + this._isActive = false + this._lastTabNavDirection = null } - activate() { + activate () { const { trapElement, autofocus - } = this._config; + } = this._config if (this._isActive) { - return; + return } if (autofocus) { - trapElement.focus(); + trapElement.focus() } - EventHandler.off(document, EVENT_KEY$7); // guard against infinite focus loop + EventHandler.off(document, EVENT_KEY$7) // guard against infinite focus loop - EventHandler.on(document, EVENT_FOCUSIN$1, event => this._handleFocusin(event)); - EventHandler.on(document, EVENT_KEYDOWN_TAB, event => this._handleKeydown(event)); - this._isActive = true; + EventHandler.on(document, EVENT_FOCUSIN$1, event => this._handleFocusin(event)) + EventHandler.on(document, EVENT_KEYDOWN_TAB, event => this._handleKeydown(event)) + this._isActive = true } - deactivate() { + deactivate () { if (!this._isActive) { - return; + return } - this._isActive = false; - EventHandler.off(document, EVENT_KEY$7); + this._isActive = false + EventHandler.off(document, EVENT_KEY$7) } // Private - - _handleFocusin(event) { + _handleFocusin (event) { const { target - } = event; + } = event const { trapElement - } = this._config; + } = this._config if (target === document || target === trapElement || trapElement.contains(target)) { - return; + return } - const elements = SelectorEngine.focusableChildren(trapElement); + const elements = SelectorEngine.focusableChildren(trapElement) if (elements.length === 0) { - trapElement.focus(); + trapElement.focus() } else if (this._lastTabNavDirection === TAB_NAV_BACKWARD) { - elements[elements.length - 1].focus(); + elements[elements.length - 1].focus() } else { - elements[0].focus(); + elements[0].focus() } } - _handleKeydown(event) { - if (event.key !== TAB_KEY) { - return; + _handleKeydown (event) { + if (event.key !=== TAB_KEY) { + return } - this._lastTabNavDirection = event.shiftKey ? TAB_NAV_BACKWARD : TAB_NAV_FORWARD; + this._lastTabNavDirection = event.shiftKey ? TAB_NAV_BACKWARD : TAB_NAV_FORWARD } - _getConfig(config) { - config = { ...Default$6, + _getConfig (config) { + config = { + ...Default$6, ...(typeof config === 'object' ? config : {}) - }; - typeCheckConfig(NAME$7, config, DefaultType$6); - return config; + } + typeCheckConfig(NAME$7, config, DefaultType$6) + return config } - } /** @@ -2751,40 +2712,40 @@ * ------------------------------------------------------------------------ */ - const NAME$6 = 'modal'; - const DATA_KEY$6 = 'bs.modal'; - const EVENT_KEY$6 = `.${DATA_KEY$6}`; - const DATA_API_KEY$3 = '.data-api'; - const ESCAPE_KEY$1 = 'Escape'; + const NAME$6 = 'modal' + const DATA_KEY$6 = 'bs.modal' + const EVENT_KEY$6 = `.${DATA_KEY$6}` + const DATA_API_KEY$3 = '.data-api' + const ESCAPE_KEY$1 = 'Escape' const Default$5 = { backdrop: true, keyboard: true, focus: true - }; + } const DefaultType$5 = { backdrop: '(boolean|string)', keyboard: 'boolean', focus: 'boolean' - }; - const EVENT_HIDE$3 = `hide${EVENT_KEY$6}`; - const EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY$6}`; - const EVENT_HIDDEN$3 = `hidden${EVENT_KEY$6}`; - const EVENT_SHOW$3 = `show${EVENT_KEY$6}`; - const EVENT_SHOWN$3 = `shown${EVENT_KEY$6}`; - const EVENT_RESIZE = `resize${EVENT_KEY$6}`; - const EVENT_CLICK_DISMISS = `click.dismiss${EVENT_KEY$6}`; - const EVENT_KEYDOWN_DISMISS$1 = `keydown.dismiss${EVENT_KEY$6}`; - const EVENT_MOUSEUP_DISMISS = `mouseup.dismiss${EVENT_KEY$6}`; - const EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY$6}`; - const EVENT_CLICK_DATA_API$2 = `click${EVENT_KEY$6}${DATA_API_KEY$3}`; - const CLASS_NAME_OPEN = 'modal-open'; - const CLASS_NAME_FADE$3 = 'fade'; - const CLASS_NAME_SHOW$4 = 'show'; - const CLASS_NAME_STATIC = 'modal-static'; - const OPEN_SELECTOR$1 = '.modal.show'; - const SELECTOR_DIALOG = '.modal-dialog'; - const SELECTOR_MODAL_BODY = '.modal-body'; - const SELECTOR_DATA_TOGGLE$2 = '[data-bs-toggle="modal"]'; + } + const EVENT_HIDE$3 = `hide${EVENT_KEY$6}` + const EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY$6}` + const EVENT_HIDDEN$3 = `hidden${EVENT_KEY$6}` + const EVENT_SHOW$3 = `show${EVENT_KEY$6}` + const EVENT_SHOWN$3 = `shown${EVENT_KEY$6}` + const EVENT_RESIZE = `resize${EVENT_KEY$6}` + const EVENT_CLICK_DISMISS = `click.dismiss${EVENT_KEY$6}` + const EVENT_KEYDOWN_DISMISS$1 = `keydown.dismiss${EVENT_KEY$6}` + const EVENT_MOUSEUP_DISMISS = `mouseup.dismiss${EVENT_KEY$6}` + const EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY$6}` + const EVENT_CLICK_DATA_API$2 = `click${EVENT_KEY$6}${DATA_API_KEY$3}` + const CLASS_NAME_OPEN = 'modal-open' + const CLASS_NAME_FADE$3 = 'fade' + const CLASS_NAME_SHOW$4 = 'show' + const CLASS_NAME_STATIC = 'modal-static' + const OPEN_SELECTOR$1 = '.modal.show' + const SELECTOR_DIALOG = '.modal-dialog' + const SELECTOR_MODAL_BODY = '.modal-body' + const SELECTOR_DATA_TOGGLE$2 = '[data-bs-toggle="modal"]' /** * ------------------------------------------------------------------------ * Class Definition @@ -2792,335 +2753,330 @@ */ class Modal extends BaseComponent { - constructor(element, config) { - super(element); - this._config = this._getConfig(config); - this._dialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element); - this._backdrop = this._initializeBackDrop(); - this._focustrap = this._initializeFocusTrap(); - this._isShown = false; - this._ignoreBackdropClick = false; - this._isTransitioning = false; - this._scrollBar = new ScrollBarHelper(); + constructor (element, config) { + super(element) + this._config = this._getConfig(config) + this._dialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element) + this._backdrop = this._initializeBackDrop() + this._focustrap = this._initializeFocusTrap() + this._isShown = false + this._ignoreBackdropClick = false + this._isTransitioning = false + this._scrollBar = new ScrollBarHelper() } // Getters - - static get Default() { - return Default$5; + static get Default () { + return Default$5 } - static get NAME() { - return NAME$6; + static get NAME () { + return NAME$6 } // Public - - toggle(relatedTarget) { - return this._isShown ? this.hide() : this.show(relatedTarget); + toggle (relatedTarget) { + return this._isShown ? this.hide() : this.show(relatedTarget) } - show(relatedTarget) { + show (relatedTarget) { if (this._isShown || this._isTransitioning) { - return; + return } const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$3, { relatedTarget - }); + }) if (showEvent.defaultPrevented) { - return; + return } - this._isShown = true; + this._isShown = true if (this._isAnimated()) { - this._isTransitioning = true; + this._isTransitioning = true } - this._scrollBar.hide(); + this._scrollBar.hide() - document.body.classList.add(CLASS_NAME_OPEN); + document.body.classList.add(CLASS_NAME_OPEN) - this._adjustDialog(); + this._adjustDialog() - this._setEscapeEvent(); + this._setEscapeEvent() - this._setResizeEvent(); + this._setResizeEvent() EventHandler.on(this._dialog, EVENT_MOUSEDOWN_DISMISS, () => { EventHandler.one(this._element, EVENT_MOUSEUP_DISMISS, event => { if (event.target === this._element) { - this._ignoreBackdropClick = true; + this._ignoreBackdropClick = true } - }); - }); + }) + }) - this._showBackdrop(() => this._showElement(relatedTarget)); + this._showBackdrop(() => this._showElement(relatedTarget)) } - hide() { + hide () { if (!this._isShown || this._isTransitioning) { - return; + return } - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$3); + const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$3) if (hideEvent.defaultPrevented) { - return; + return } - this._isShown = false; + this._isShown = false - const isAnimated = this._isAnimated(); + const isAnimated = this._isAnimated() if (isAnimated) { - this._isTransitioning = true; + this._isTransitioning = true } - this._setEscapeEvent(); + this._setEscapeEvent() - this._setResizeEvent(); + this._setResizeEvent() - this._focustrap.deactivate(); + this._focustrap.deactivate() - this._element.classList.remove(CLASS_NAME_SHOW$4); + this._element.classList.remove(CLASS_NAME_SHOW$4) - EventHandler.off(this._element, EVENT_CLICK_DISMISS); - EventHandler.off(this._dialog, EVENT_MOUSEDOWN_DISMISS); + EventHandler.off(this._element, EVENT_CLICK_DISMISS) + EventHandler.off(this._dialog, EVENT_MOUSEDOWN_DISMISS) - this._queueCallback(() => this._hideModal(), this._element, isAnimated); + this._queueCallback(() => this._hideModal(), this._element, isAnimated) } - dispose() { - [window, this._dialog].forEach(htmlElement => EventHandler.off(htmlElement, EVENT_KEY$6)); + dispose () { + [window, this._dialog].forEach(htmlElement => EventHandler.off(htmlElement, EVENT_KEY$6)) - this._backdrop.dispose(); + this._backdrop.dispose() - this._focustrap.deactivate(); + this._focustrap.deactivate() - super.dispose(); + super.dispose() } - handleUpdate() { - this._adjustDialog(); + handleUpdate () { + this._adjustDialog() } // Private - - _initializeBackDrop() { + _initializeBackDrop () { return new Backdrop({ isVisible: Boolean(this._config.backdrop), // 'static' option will be translated to true, and booleans will keep their value isAnimated: this._isAnimated() - }); + }) } - _initializeFocusTrap() { + _initializeFocusTrap () { return new FocusTrap({ trapElement: this._element - }); + }) } - _getConfig(config) { - config = { ...Default$5, + _getConfig (config) { + config = { + ...Default$5, ...Manipulator.getDataAttributes(this._element), ...(typeof config === 'object' ? config : {}) - }; - typeCheckConfig(NAME$6, config, DefaultType$5); - return config; + } + typeCheckConfig(NAME$6, config, DefaultType$5) + return config } - _showElement(relatedTarget) { - const isAnimated = this._isAnimated(); + _showElement (relatedTarget) { + const isAnimated = this._isAnimated() - const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog); + const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog) - if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) { + if (!this._element.parentNode || this._element.parentNode.nodeType !=== Node.ELEMENT_NODE) { // Don't move modal's DOM position - document.body.append(this._element); + document.body.append(this._element) } - this._element.style.display = 'block'; + this._element.style.display = 'block' - this._element.removeAttribute('aria-hidden'); + this._element.removeAttribute('aria-hidden') - this._element.setAttribute('aria-modal', true); + this._element.setAttribute('aria-modal', true) - this._element.setAttribute('role', 'dialog'); + this._element.setAttribute('role', 'dialog') - this._element.scrollTop = 0; + this._element.scrollTop = 0 if (modalBody) { - modalBody.scrollTop = 0; + modalBody.scrollTop = 0 } if (isAnimated) { - reflow(this._element); + reflow(this._element) } - this._element.classList.add(CLASS_NAME_SHOW$4); + this._element.classList.add(CLASS_NAME_SHOW$4) const transitionComplete = () => { if (this._config.focus) { - this._focustrap.activate(); + this._focustrap.activate() } - this._isTransitioning = false; + this._isTransitioning = false EventHandler.trigger(this._element, EVENT_SHOWN$3, { relatedTarget - }); - }; + }) + } - this._queueCallback(transitionComplete, this._dialog, isAnimated); + this._queueCallback(transitionComplete, this._dialog, isAnimated) } - _setEscapeEvent() { + _setEscapeEvent () { if (this._isShown) { EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS$1, event => { if (this._config.keyboard && event.key === ESCAPE_KEY$1) { - event.preventDefault(); - this.hide(); + event.preventDefault() + this.hide() } else if (!this._config.keyboard && event.key === ESCAPE_KEY$1) { - this._triggerBackdropTransition(); + this._triggerBackdropTransition() } - }); + }) } else { - EventHandler.off(this._element, EVENT_KEYDOWN_DISMISS$1); + EventHandler.off(this._element, EVENT_KEYDOWN_DISMISS$1) } } - _setResizeEvent() { + _setResizeEvent () { if (this._isShown) { - EventHandler.on(window, EVENT_RESIZE, () => this._adjustDialog()); + EventHandler.on(window, EVENT_RESIZE, () => this._adjustDialog()) } else { - EventHandler.off(window, EVENT_RESIZE); + EventHandler.off(window, EVENT_RESIZE) } } - _hideModal() { - this._element.style.display = 'none'; + _hideModal () { + this._element.style.display = 'none' - this._element.setAttribute('aria-hidden', true); + this._element.setAttribute('aria-hidden', true) - this._element.removeAttribute('aria-modal'); + this._element.removeAttribute('aria-modal') - this._element.removeAttribute('role'); + this._element.removeAttribute('role') - this._isTransitioning = false; + this._isTransitioning = false this._backdrop.hide(() => { - document.body.classList.remove(CLASS_NAME_OPEN); + document.body.classList.remove(CLASS_NAME_OPEN) - this._resetAdjustments(); + this._resetAdjustments() - this._scrollBar.reset(); + this._scrollBar.reset() - EventHandler.trigger(this._element, EVENT_HIDDEN$3); - }); + EventHandler.trigger(this._element, EVENT_HIDDEN$3) + }) } - _showBackdrop(callback) { + _showBackdrop (callback) { EventHandler.on(this._element, EVENT_CLICK_DISMISS, event => { if (this._ignoreBackdropClick) { - this._ignoreBackdropClick = false; - return; + this._ignoreBackdropClick = false + return } - if (event.target !== event.currentTarget) { - return; + if (event.target !=== event.currentTarget) { + return } if (this._config.backdrop === true) { - this.hide(); + this.hide() } else if (this._config.backdrop === 'static') { - this._triggerBackdropTransition(); + this._triggerBackdropTransition() } - }); + }) - this._backdrop.show(callback); + this._backdrop.show(callback) } - _isAnimated() { - return this._element.classList.contains(CLASS_NAME_FADE$3); + _isAnimated () { + return this._element.classList.contains(CLASS_NAME_FADE$3) } - _triggerBackdropTransition() { - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED); + _triggerBackdropTransition () { + const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED) if (hideEvent.defaultPrevented) { - return; + return } const { classList, scrollHeight, style - } = this._element; - const isModalOverflowing = scrollHeight > document.documentElement.clientHeight; // return if the following background transition hasn't yet completed + } = this._element + const isModalOverflowing = scrollHeight > document.documentElement.clientHeight // return if the following background transition hasn't yet completed if (!isModalOverflowing && style.overflowY === 'hidden' || classList.contains(CLASS_NAME_STATIC)) { - return; + return } if (!isModalOverflowing) { - style.overflowY = 'hidden'; + style.overflowY = 'hidden' } - classList.add(CLASS_NAME_STATIC); + classList.add(CLASS_NAME_STATIC) this._queueCallback(() => { - classList.remove(CLASS_NAME_STATIC); + classList.remove(CLASS_NAME_STATIC) if (!isModalOverflowing) { this._queueCallback(() => { - style.overflowY = ''; - }, this._dialog); + style.overflowY = '' + }, this._dialog) } - }, this._dialog); + }, this._dialog) - this._element.focus(); + this._element.focus() } // ---------------------------------------------------------------------- // the following methods are used to handle overflowing modals // ---------------------------------------------------------------------- + _adjustDialog () { + const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight - _adjustDialog() { - const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight; + const scrollbarWidth = this._scrollBar.getWidth() - const scrollbarWidth = this._scrollBar.getWidth(); - - const isBodyOverflowing = scrollbarWidth > 0; + const isBodyOverflowing = scrollbarWidth > 0 if (!isBodyOverflowing && isModalOverflowing && !isRTL() || isBodyOverflowing && !isModalOverflowing && isRTL()) { - this._element.style.paddingLeft = `${scrollbarWidth}px`; + this._element.style.paddingLeft = `${scrollbarWidth}px` } if (isBodyOverflowing && !isModalOverflowing && !isRTL() || !isBodyOverflowing && isModalOverflowing && isRTL()) { - this._element.style.paddingRight = `${scrollbarWidth}px`; + this._element.style.paddingRight = `${scrollbarWidth}px` } } - _resetAdjustments() { - this._element.style.paddingLeft = ''; - this._element.style.paddingRight = ''; + _resetAdjustments () { + this._element.style.paddingLeft = '' + this._element.style.paddingRight = '' } // Static - - static jQueryInterface(config, relatedTarget) { + static jQueryInterface (config, relatedTarget) { return this.each(function () { - const data = Modal.getOrCreateInstance(this, config); + const data = Modal.getOrCreateInstance(this, config) - if (typeof config !== 'string') { - return; + if (typeof config !=== 'string') { + return } if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); + throw new TypeError(`No method named "${config}"`) } - data[config](relatedTarget); - }); + data[config](relatedTarget) + }) } - } /** * ------------------------------------------------------------------------ @@ -3128,37 +3084,36 @@ * ------------------------------------------------------------------------ */ - EventHandler.on(document, EVENT_CLICK_DATA_API$2, SELECTOR_DATA_TOGGLE$2, function (event) { - const target = getElementFromSelector(this); + const target = getElementFromSelector(this) if (['A', 'AREA'].includes(this.tagName)) { - event.preventDefault(); + event.preventDefault() } EventHandler.one(target, EVENT_SHOW$3, showEvent => { if (showEvent.defaultPrevented) { // only register focus restorer if modal will actually get shown - return; + return } EventHandler.one(target, EVENT_HIDDEN$3, () => { if (isVisible(this)) { - this.focus(); + this.focus() } - }); - }); // avoid conflict when clicking moddal toggler while another one is open + }) + }) // avoid conflict when clicking moddal toggler while another one is open - const allReadyOpen = SelectorEngine.findOne(OPEN_SELECTOR$1); + const allReadyOpen = SelectorEngine.findOne(OPEN_SELECTOR$1) if (allReadyOpen) { - Modal.getInstance(allReadyOpen).hide(); + Modal.getInstance(allReadyOpen).hide() } - const data = Modal.getOrCreateInstance(target); - data.toggle(this); - }); - enableDismissTrigger(Modal); + const data = Modal.getOrCreateInstance(target) + data.toggle(this) + }) + enableDismissTrigger(Modal) /** * ------------------------------------------------------------------------ * jQuery @@ -3166,7 +3121,7 @@ * add .Modal to jQuery only if jQuery is present */ - defineJQueryPlugin(Modal); + defineJQueryPlugin(Modal) /** * -------------------------------------------------------------------------- @@ -3180,32 +3135,32 @@ * ------------------------------------------------------------------------ */ - const NAME$5 = 'offcanvas'; - const DATA_KEY$5 = 'bs.offcanvas'; - const EVENT_KEY$5 = `.${DATA_KEY$5}`; - const DATA_API_KEY$2 = '.data-api'; - const EVENT_LOAD_DATA_API$1 = `load${EVENT_KEY$5}${DATA_API_KEY$2}`; - const ESCAPE_KEY = 'Escape'; + const NAME$5 = 'offcanvas' + const DATA_KEY$5 = 'bs.offcanvas' + const EVENT_KEY$5 = `.${DATA_KEY$5}` + const DATA_API_KEY$2 = '.data-api' + const EVENT_LOAD_DATA_API$1 = `load${EVENT_KEY$5}${DATA_API_KEY$2}` + const ESCAPE_KEY = 'Escape' const Default$4 = { backdrop: true, keyboard: true, scroll: false - }; + } const DefaultType$4 = { backdrop: 'boolean', keyboard: 'boolean', scroll: 'boolean' - }; - const CLASS_NAME_SHOW$3 = 'show'; - const CLASS_NAME_BACKDROP = 'offcanvas-backdrop'; - const OPEN_SELECTOR = '.offcanvas.show'; - const EVENT_SHOW$2 = `show${EVENT_KEY$5}`; - const EVENT_SHOWN$2 = `shown${EVENT_KEY$5}`; - const EVENT_HIDE$2 = `hide${EVENT_KEY$5}`; - const EVENT_HIDDEN$2 = `hidden${EVENT_KEY$5}`; - const EVENT_CLICK_DATA_API$1 = `click${EVENT_KEY$5}${DATA_API_KEY$2}`; - const EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY$5}`; - const SELECTOR_DATA_TOGGLE$1 = '[data-bs-toggle="offcanvas"]'; + } + const CLASS_NAME_SHOW$3 = 'show' + const CLASS_NAME_BACKDROP = 'offcanvas-backdrop' + const OPEN_SELECTOR = '.offcanvas.show' + const EVENT_SHOW$2 = `show${EVENT_KEY$5}` + const EVENT_SHOWN$2 = `shown${EVENT_KEY$5}` + const EVENT_HIDE$2 = `hide${EVENT_KEY$5}` + const EVENT_HIDDEN$2 = `hidden${EVENT_KEY$5}` + const EVENT_CLICK_DATA_API$1 = `click${EVENT_KEY$5}${DATA_API_KEY$2}` + const EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY$5}` + const SELECTOR_DATA_TOGGLE$1 = '[data-bs-toggle="offcanvas"]' /** * ------------------------------------------------------------------------ * Class Definition @@ -3213,172 +3168,168 @@ */ class Offcanvas extends BaseComponent { - constructor(element, config) { - super(element); - this._config = this._getConfig(config); - this._isShown = false; - this._backdrop = this._initializeBackDrop(); - this._focustrap = this._initializeFocusTrap(); + constructor (element, config) { + super(element) + this._config = this._getConfig(config) + this._isShown = false + this._backdrop = this._initializeBackDrop() + this._focustrap = this._initializeFocusTrap() - this._addEventListeners(); + this._addEventListeners() } // Getters - - static get NAME() { - return NAME$5; + static get NAME () { + return NAME$5 } - static get Default() { - return Default$4; + static get Default () { + return Default$4 } // Public - - toggle(relatedTarget) { - return this._isShown ? this.hide() : this.show(relatedTarget); + toggle (relatedTarget) { + return this._isShown ? this.hide() : this.show(relatedTarget) } - show(relatedTarget) { + show (relatedTarget) { if (this._isShown) { - return; + return } const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$2, { relatedTarget - }); + }) if (showEvent.defaultPrevented) { - return; + return } - this._isShown = true; - this._element.style.visibility = 'visible'; + this._isShown = true + this._element.style.visibility = 'visible' - this._backdrop.show(); + this._backdrop.show() if (!this._config.scroll) { - new ScrollBarHelper().hide(); + new ScrollBarHelper().hide() } - this._element.removeAttribute('aria-hidden'); + this._element.removeAttribute('aria-hidden') - this._element.setAttribute('aria-modal', true); + this._element.setAttribute('aria-modal', true) - this._element.setAttribute('role', 'dialog'); + this._element.setAttribute('role', 'dialog') - this._element.classList.add(CLASS_NAME_SHOW$3); + this._element.classList.add(CLASS_NAME_SHOW$3) const completeCallBack = () => { if (!this._config.scroll) { - this._focustrap.activate(); + this._focustrap.activate() } EventHandler.trigger(this._element, EVENT_SHOWN$2, { relatedTarget - }); - }; - - this._queueCallback(completeCallBack, this._element, true); - } - - hide() { - if (!this._isShown) { - return; + }) } - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$2); + this._queueCallback(completeCallBack, this._element, true) + } + + hide () { + if (!this._isShown) { + return + } + + const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$2) if (hideEvent.defaultPrevented) { - return; + return } - this._focustrap.deactivate(); + this._focustrap.deactivate() - this._element.blur(); + this._element.blur() - this._isShown = false; + this._isShown = false - this._element.classList.remove(CLASS_NAME_SHOW$3); + this._element.classList.remove(CLASS_NAME_SHOW$3) - this._backdrop.hide(); + this._backdrop.hide() const completeCallback = () => { - this._element.setAttribute('aria-hidden', true); + this._element.setAttribute('aria-hidden', true) - this._element.removeAttribute('aria-modal'); + this._element.removeAttribute('aria-modal') - this._element.removeAttribute('role'); + this._element.removeAttribute('role') - this._element.style.visibility = 'hidden'; + this._element.style.visibility = 'hidden' if (!this._config.scroll) { - new ScrollBarHelper().reset(); + new ScrollBarHelper().reset() } - EventHandler.trigger(this._element, EVENT_HIDDEN$2); - }; + EventHandler.trigger(this._element, EVENT_HIDDEN$2) + } - this._queueCallback(completeCallback, this._element, true); + this._queueCallback(completeCallback, this._element, true) } - dispose() { - this._backdrop.dispose(); + dispose () { + this._backdrop.dispose() - this._focustrap.deactivate(); + this._focustrap.deactivate() - super.dispose(); + super.dispose() } // Private - - _getConfig(config) { - config = { ...Default$4, + _getConfig (config) { + config = { + ...Default$4, ...Manipulator.getDataAttributes(this._element), ...(typeof config === 'object' ? config : {}) - }; - typeCheckConfig(NAME$5, config, DefaultType$4); - return config; + } + typeCheckConfig(NAME$5, config, DefaultType$4) + return config } - _initializeBackDrop() { + _initializeBackDrop () { return new Backdrop({ className: CLASS_NAME_BACKDROP, isVisible: this._config.backdrop, isAnimated: true, rootElement: this._element.parentNode, clickCallback: () => this.hide() - }); + }) } - _initializeFocusTrap() { + _initializeFocusTrap () { return new FocusTrap({ trapElement: this._element - }); + }) } - _addEventListeners() { + _addEventListeners () { EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, event => { if (this._config.keyboard && event.key === ESCAPE_KEY) { - this.hide(); + this.hide() } - }); + }) } // Static - - static jQueryInterface(config) { + static jQueryInterface (config) { return this.each(function () { - const data = Offcanvas.getOrCreateInstance(this, config); + const data = Offcanvas.getOrCreateInstance(this, config) - if (typeof config !== 'string') { - return; + if (typeof config !=== 'string') { + return } if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { - throw new TypeError(`No method named "${config}"`); + throw new TypeError(`No method named "${config}"`) } - data[config](this); - }); + data[config](this) + }) } - } /** * ------------------------------------------------------------------------ @@ -3386,43 +3337,42 @@ * ------------------------------------------------------------------------ */ - EventHandler.on(document, EVENT_CLICK_DATA_API$1, SELECTOR_DATA_TOGGLE$1, function (event) { - const target = getElementFromSelector(this); + const target = getElementFromSelector(this) if (['A', 'AREA'].includes(this.tagName)) { - event.preventDefault(); + event.preventDefault() } if (isDisabled(this)) { - return; + return } EventHandler.one(target, EVENT_HIDDEN$2, () => { // focus on trigger when it is closed if (isVisible(this)) { - this.focus(); + this.focus() } - }); // avoid conflict when clicking a toggler of an offcanvas, while another is open + }) // avoid conflict when clicking a toggler of an offcanvas, while another is open - const allReadyOpen = SelectorEngine.findOne(OPEN_SELECTOR); + const allReadyOpen = SelectorEngine.findOne(OPEN_SELECTOR) - if (allReadyOpen && allReadyOpen !== target) { - Offcanvas.getInstance(allReadyOpen).hide(); + if (allReadyOpen && allReadyOpen !=== target) { + Offcanvas.getInstance(allReadyOpen).hide() } - const data = Offcanvas.getOrCreateInstance(target); - data.toggle(this); - }); - EventHandler.on(window, EVENT_LOAD_DATA_API$1, () => SelectorEngine.find(OPEN_SELECTOR).forEach(el => Offcanvas.getOrCreateInstance(el).show())); - enableDismissTrigger(Offcanvas); + const data = Offcanvas.getOrCreateInstance(target) + data.toggle(this) + }) + EventHandler.on(window, EVENT_LOAD_DATA_API$1, () => SelectorEngine.find(OPEN_SELECTOR).forEach(el => Offcanvas.getOrCreateInstance(el).show())) + enableDismissTrigger(Offcanvas) /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ - defineJQueryPlugin(Offcanvas); + defineJQueryPlugin(Offcanvas) /** * -------------------------------------------------------------------------- @@ -3430,44 +3380,44 @@ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - const uriAttributes = new Set(['background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href']); - const ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i; + const uriAttributes = new Set(['background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href']) + const ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i /** * A pattern that recognizes a commonly useful subset of URLs that are safe. * * Shoutout to Angular https://github.com/angular/angular/blob/12.2.x/packages/core/src/sanitization/url_sanitizer.ts */ - const SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file|sms):|[^#&/:?]*(?:[#/?]|$))/i; + const SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file|sms):|[^#&/:?]*(?:[#/?]|$))/i /** * A pattern that matches safe data URLs. Only matches image, video and audio types. * * Shoutout to Angular https://github.com/angular/angular/blob/12.2.x/packages/core/src/sanitization/url_sanitizer.ts */ - const DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[\d+/a-z]+=*$/i; + const DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[\d+/a-z]+=*$/i const allowedAttribute = (attribute, allowedAttributeList) => { - const attributeName = attribute.nodeName.toLowerCase(); + const attributeName = attribute.nodeName.toLowerCase() if (allowedAttributeList.includes(attributeName)) { if (uriAttributes.has(attributeName)) { - return Boolean(SAFE_URL_PATTERN.test(attribute.nodeValue) || DATA_URL_PATTERN.test(attribute.nodeValue)); + return Boolean(SAFE_URL_PATTERN.test(attribute.nodeValue) || DATA_URL_PATTERN.test(attribute.nodeValue)) } - return true; + return true } - const regExp = allowedAttributeList.filter(attributeRegex => attributeRegex instanceof RegExp); // Check if a regular expression validates the attribute. + const regExp = allowedAttributeList.filter(attributeRegex => attributeRegex instanceof RegExp) // Check if a regular expression validates the attribute. for (let i = 0, len = regExp.length; i < len; i++) { if (regExp[i].test(attributeName)) { - return true; + return true } } - return false; - }; + return false + } const DefaultAllowlist = { // Global attributes allowed on any supplied element below. @@ -3501,39 +3451,39 @@ strong: [], u: [], ul: [] - }; - function sanitizeHtml(unsafeHtml, allowList, sanitizeFn) { + } + function sanitizeHtml (unsafeHtml, allowList, sanitizeFn) { if (!unsafeHtml.length) { - return unsafeHtml; + return unsafeHtml } if (sanitizeFn && typeof sanitizeFn === 'function') { - return sanitizeFn(unsafeHtml); + return sanitizeFn(unsafeHtml) } - const domParser = new window.DOMParser(); - const createdDocument = domParser.parseFromString(unsafeHtml, 'text/html'); - const elements = [].concat(...createdDocument.body.querySelectorAll('*')); + const domParser = new window.DOMParser() + const createdDocument = domParser.parseFromString(unsafeHtml, 'text/html') + const elements = [].concat(...createdDocument.body.querySelectorAll('*')) for (let i = 0, len = elements.length; i < len; i++) { - const element = elements[i]; - const elementName = element.nodeName.toLowerCase(); + const element = elements[i] + const elementName = element.nodeName.toLowerCase() if (!Object.keys(allowList).includes(elementName)) { - element.remove(); - continue; + element.remove() + continue } - const attributeList = [].concat(...element.attributes); - const allowedAttributes = [].concat(allowList['*'] || [], allowList[elementName] || []); + const attributeList = [].concat(...element.attributes) + const allowedAttributes = [].concat(allowList['*'] || [], allowList[elementName] || []) attributeList.forEach(attribute => { if (!allowedAttribute(attribute, allowedAttributes)) { - element.removeAttribute(attribute.nodeName); + element.removeAttribute(attribute.nodeName) } - }); + }) } - return createdDocument.body.innerHTML; + return createdDocument.body.innerHTML } /** @@ -3548,11 +3498,11 @@ * ------------------------------------------------------------------------ */ - const NAME$4 = 'tooltip'; - const DATA_KEY$4 = 'bs.tooltip'; - const EVENT_KEY$4 = `.${DATA_KEY$4}`; - const CLASS_PREFIX$1 = 'bs-tooltip'; - const DISALLOWED_ATTRIBUTES = new Set(['sanitize', 'allowList', 'sanitizeFn']); + const NAME$4 = 'tooltip' + const DATA_KEY$4 = 'bs.tooltip' + const EVENT_KEY$4 = `.${DATA_KEY$4}` + const CLASS_PREFIX$1 = 'bs-tooltip' + const DISALLOWED_ATTRIBUTES = new Set(['sanitize', 'allowList', 'sanitizeFn']) const DefaultType$3 = { animation: 'boolean', template: 'string', @@ -3571,14 +3521,14 @@ sanitizeFn: '(null|function)', allowList: 'object', popperConfig: '(null|object|function)' - }; + } const AttachmentMap = { AUTO: 'auto', TOP: 'top', RIGHT: isRTL() ? 'left' : 'right', BOTTOM: 'bottom', LEFT: isRTL() ? 'right' : 'left' - }; + } const Default$3 = { animation: true, template: '', @@ -3597,7 +3547,7 @@ sanitizeFn: null, allowList: DefaultAllowlist, popperConfig: null - }; + } const Event$2 = { HIDE: `hide${EVENT_KEY$4}`, HIDDEN: `hidden${EVENT_KEY$4}`, @@ -3609,19 +3559,19 @@ FOCUSOUT: `focusout${EVENT_KEY$4}`, MOUSEENTER: `mouseenter${EVENT_KEY$4}`, MOUSELEAVE: `mouseleave${EVENT_KEY$4}` - }; - const CLASS_NAME_FADE$2 = 'fade'; - const CLASS_NAME_MODAL = 'modal'; - const CLASS_NAME_SHOW$2 = 'show'; - const HOVER_STATE_SHOW = 'show'; - const HOVER_STATE_OUT = 'out'; - const SELECTOR_TOOLTIP_INNER = '.tooltip-inner'; - const SELECTOR_MODAL = `.${CLASS_NAME_MODAL}`; - const EVENT_MODAL_HIDE = 'hide.bs.modal'; - const TRIGGER_HOVER = 'hover'; - const TRIGGER_FOCUS = 'focus'; - const TRIGGER_CLICK = 'click'; - const TRIGGER_MANUAL = 'manual'; + } + const CLASS_NAME_FADE$2 = 'fade' + const CLASS_NAME_MODAL = 'modal' + const CLASS_NAME_SHOW$2 = 'show' + const HOVER_STATE_SHOW = 'show' + const HOVER_STATE_OUT = 'out' + const SELECTOR_TOOLTIP_INNER = '.tooltip-inner' + const SELECTOR_MODAL = `.${CLASS_NAME_MODAL}` + const EVENT_MODAL_HIDE = 'hide.bs.modal' + const TRIGGER_HOVER = 'hover' + const TRIGGER_FOCUS = 'focus' + const TRIGGER_CLICK = 'click' + const TRIGGER_MANUAL = 'manual' /** * ------------------------------------------------------------------------ * Class Definition @@ -3629,349 +3579,342 @@ */ class Tooltip extends BaseComponent { - constructor(element, config) { + constructor (element, config) { if (typeof Popper__namespace === 'undefined') { - throw new TypeError('Bootstrap\'s tooltips require Popper (https://popper.js.org)'); + throw new TypeError('Bootstrap\'s tooltips require Popper (https://popper.js.org)') } - super(element); // private + super(element) // private - this._isEnabled = true; - this._timeout = 0; - this._hoverState = ''; - this._activeTrigger = {}; - this._popper = null; // Protected + this._isEnabled = true + this._timeout = 0 + this._hoverState = '' + this._activeTrigger = {} + this._popper = null // Protected - this._config = this._getConfig(config); - this.tip = null; + this._config = this._getConfig(config) + this.tip = null - this._setListeners(); + this._setListeners() } // Getters - - static get Default() { - return Default$3; + static get Default () { + return Default$3 } - static get NAME() { - return NAME$4; + static get NAME () { + return NAME$4 } - static get Event() { - return Event$2; + static get Event () { + return Event$2 } - static get DefaultType() { - return DefaultType$3; + static get DefaultType () { + return DefaultType$3 } // Public - - enable() { - this._isEnabled = true; + enable () { + this._isEnabled = true } - disable() { - this._isEnabled = false; + disable () { + this._isEnabled = false } - toggleEnabled() { - this._isEnabled = !this._isEnabled; + toggleEnabled () { + this._isEnabled = !this._isEnabled } - toggle(event) { + toggle (event) { if (!this._isEnabled) { - return; + return } if (event) { - const context = this._initializeOnDelegatedTarget(event); + const context = this._initializeOnDelegatedTarget(event) - context._activeTrigger.click = !context._activeTrigger.click; + context._activeTrigger.click = !context._activeTrigger.click if (context._isWithActiveTrigger()) { - context._enter(null, context); + context._enter(null, context) } else { - context._leave(null, context); + context._leave(null, context) } } else { if (this.getTipElement().classList.contains(CLASS_NAME_SHOW$2)) { - this._leave(null, this); + this._leave(null, this) - return; + return } - this._enter(null, this); + this._enter(null, this) } } - dispose() { - clearTimeout(this._timeout); - EventHandler.off(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler); + dispose () { + clearTimeout(this._timeout) + EventHandler.off(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler) if (this.tip) { - this.tip.remove(); + this.tip.remove() } - this._disposePopper(); + this._disposePopper() - super.dispose(); + super.dispose() } - show() { + show () { if (this._element.style.display === 'none') { - throw new Error('Please use show on visible elements'); + throw new Error('Please use show on visible elements') } if (!(this.isWithContent() && this._isEnabled)) { - return; + return } - const showEvent = EventHandler.trigger(this._element, this.constructor.Event.SHOW); - const shadowRoot = findShadowRoot(this._element); - const isInTheDom = shadowRoot === null ? this._element.ownerDocument.documentElement.contains(this._element) : shadowRoot.contains(this._element); + const showEvent = EventHandler.trigger(this._element, this.constructor.Event.SHOW) + const shadowRoot = findShadowRoot(this._element) + const isInTheDom = shadowRoot === null ? this._element.ownerDocument.documentElement.contains(this._element) : shadowRoot.contains(this._element) if (showEvent.defaultPrevented || !isInTheDom) { - return; + return } // A trick to recreate a tooltip in case a new title is given by using the NOT documented `data-bs-original-title` // This will be removed later in favor of a `setContent` method + if (this.constructor.NAME === 'tooltip' && this.tip && this.getTitle() !=== this.tip.querySelector(SELECTOR_TOOLTIP_INNER).innerHTML) { + this._disposePopper() - if (this.constructor.NAME === 'tooltip' && this.tip && this.getTitle() !== this.tip.querySelector(SELECTOR_TOOLTIP_INNER).innerHTML) { - this._disposePopper(); - - this.tip.remove(); - this.tip = null; + this.tip.remove() + this.tip = null } - const tip = this.getTipElement(); - const tipId = getUID(this.constructor.NAME); - tip.setAttribute('id', tipId); + const tip = this.getTipElement() + const tipId = getUID(this.constructor.NAME) + tip.setAttribute('id', tipId) - this._element.setAttribute('aria-describedby', tipId); + this._element.setAttribute('aria-describedby', tipId) if (this._config.animation) { - tip.classList.add(CLASS_NAME_FADE$2); + tip.classList.add(CLASS_NAME_FADE$2) } - const placement = typeof this._config.placement === 'function' ? this._config.placement.call(this, tip, this._element) : this._config.placement; + const placement = typeof this._config.placement === 'function' ? this._config.placement.call(this, tip, this._element) : this._config.placement - const attachment = this._getAttachment(placement); + const attachment = this._getAttachment(placement) - this._addAttachmentClass(attachment); + this._addAttachmentClass(attachment) const { container - } = this._config; - Data.set(tip, this.constructor.DATA_KEY, this); + } = this._config + Data.set(tip, this.constructor.DATA_KEY, this) if (!this._element.ownerDocument.documentElement.contains(this.tip)) { - container.append(tip); - EventHandler.trigger(this._element, this.constructor.Event.INSERTED); + container.append(tip) + EventHandler.trigger(this._element, this.constructor.Event.INSERTED) } if (this._popper) { - this._popper.update(); + this._popper.update() } else { - this._popper = Popper__namespace.createPopper(this._element, tip, this._getPopperConfig(attachment)); + this._popper = Popper__namespace.createPopper(this._element, tip, this._getPopperConfig(attachment)) } - tip.classList.add(CLASS_NAME_SHOW$2); + tip.classList.add(CLASS_NAME_SHOW$2) - const customClass = this._resolvePossibleFunction(this._config.customClass); + const customClass = this._resolvePossibleFunction(this._config.customClass) if (customClass) { - tip.classList.add(...customClass.split(' ')); + tip.classList.add(...customClass.split(' ')) } // If this is a touch-enabled device we add extra // empty mouseover listeners to the body's immediate children; // only needed because of broken event delegation on iOS // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html - if ('ontouchstart' in document.documentElement) { [].concat(...document.body.children).forEach(element => { - EventHandler.on(element, 'mouseover', noop); - }); + EventHandler.on(element, 'mouseover', noop) + }) } const complete = () => { - const prevHoverState = this._hoverState; - this._hoverState = null; - EventHandler.trigger(this._element, this.constructor.Event.SHOWN); + const prevHoverState = this._hoverState + this._hoverState = null + EventHandler.trigger(this._element, this.constructor.Event.SHOWN) if (prevHoverState === HOVER_STATE_OUT) { - this._leave(null, this); + this._leave(null, this) } - }; - - const isAnimated = this.tip.classList.contains(CLASS_NAME_FADE$2); - - this._queueCallback(complete, this.tip, isAnimated); - } - - hide() { - if (!this._popper) { - return; } - const tip = this.getTipElement(); + const isAnimated = this.tip.classList.contains(CLASS_NAME_FADE$2) + + this._queueCallback(complete, this.tip, isAnimated) + } + + hide () { + if (!this._popper) { + return + } + + const tip = this.getTipElement() const complete = () => { if (this._isWithActiveTrigger()) { - return; + return } - if (this._hoverState !== HOVER_STATE_SHOW) { - tip.remove(); + if (this._hoverState !=== HOVER_STATE_SHOW) { + tip.remove() } - this._cleanTipClass(); + this._cleanTipClass() - this._element.removeAttribute('aria-describedby'); + this._element.removeAttribute('aria-describedby') - EventHandler.trigger(this._element, this.constructor.Event.HIDDEN); + EventHandler.trigger(this._element, this.constructor.Event.HIDDEN) - this._disposePopper(); - }; - - const hideEvent = EventHandler.trigger(this._element, this.constructor.Event.HIDE); - - if (hideEvent.defaultPrevented) { - return; + this._disposePopper() } - tip.classList.remove(CLASS_NAME_SHOW$2); // If this is a touch-enabled device we remove the extra + const hideEvent = EventHandler.trigger(this._element, this.constructor.Event.HIDE) + + if (hideEvent.defaultPrevented) { + return + } + + tip.classList.remove(CLASS_NAME_SHOW$2) // If this is a touch-enabled device we remove the extra // empty mouseover listeners we added for iOS support if ('ontouchstart' in document.documentElement) { - [].concat(...document.body.children).forEach(element => EventHandler.off(element, 'mouseover', noop)); + [].concat(...document.body.children).forEach(element => EventHandler.off(element, 'mouseover', noop)) } - this._activeTrigger[TRIGGER_CLICK] = false; - this._activeTrigger[TRIGGER_FOCUS] = false; - this._activeTrigger[TRIGGER_HOVER] = false; - const isAnimated = this.tip.classList.contains(CLASS_NAME_FADE$2); + this._activeTrigger[TRIGGER_CLICK] = false + this._activeTrigger[TRIGGER_FOCUS] = false + this._activeTrigger[TRIGGER_HOVER] = false + const isAnimated = this.tip.classList.contains(CLASS_NAME_FADE$2) - this._queueCallback(complete, this.tip, isAnimated); + this._queueCallback(complete, this.tip, isAnimated) - this._hoverState = ''; + this._hoverState = '' } - update() { - if (this._popper !== null) { - this._popper.update(); + update () { + if (this._popper !=== null) { + this._popper.update() } } // Protected - - isWithContent() { - return Boolean(this.getTitle()); + isWithContent () { + return Boolean(this.getTitle()) } - getTipElement() { + getTipElement () { if (this.tip) { - return this.tip; + return this.tip } - const element = document.createElement('div'); - element.innerHTML = this._config.template; - const tip = element.children[0]; - this.setContent(tip); - tip.classList.remove(CLASS_NAME_FADE$2, CLASS_NAME_SHOW$2); - this.tip = tip; - return this.tip; + const element = document.createElement('div') + element.innerHTML = this._config.template + const tip = element.children[0] + this.setContent(tip) + tip.classList.remove(CLASS_NAME_FADE$2, CLASS_NAME_SHOW$2) + this.tip = tip + return this.tip } - setContent(tip) { - this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TOOLTIP_INNER); + setContent (tip) { + this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TOOLTIP_INNER) } - _sanitizeAndSetContent(template, content, selector) { - const templateElement = SelectorEngine.findOne(selector, template); + _sanitizeAndSetContent (template, content, selector) { + const templateElement = SelectorEngine.findOne(selector, template) if (!content && templateElement) { - templateElement.remove(); - return; + templateElement.remove() + return } // we use append for html objects to maintain js events - - this.setElementContent(templateElement, content); + this.setElementContent(templateElement, content) } - setElementContent(element, content) { + setElementContent (element, content) { if (element === null) { - return; + return } if (isElement(content)) { - content = getElement(content); // content is a DOM node or a jQuery + content = getElement(content) // content is a DOM node or a jQuery if (this._config.html) { - if (content.parentNode !== element) { - element.innerHTML = ''; - element.append(content); + if (content.parentNode !=== element) { + element.innerHTML = '' + element.append(content) } } else { - element.textContent = content.textContent; + element.textContent = content.textContent } - return; + return } if (this._config.html) { if (this._config.sanitize) { - content = sanitizeHtml(content, this._config.allowList, this._config.sanitizeFn); + content = sanitizeHtml(content, this._config.allowList, this._config.sanitizeFn) } - element.innerHTML = content; + element.innerHTML = content } else { - element.textContent = content; + element.textContent = content } } - getTitle() { - const title = this._element.getAttribute('data-bs-original-title') || this._config.title; + getTitle () { + const title = this._element.getAttribute('data-bs-original-title') || this._config.title - return this._resolvePossibleFunction(title); + return this._resolvePossibleFunction(title) } - updateAttachment(attachment) { + updateAttachment (attachment) { if (attachment === 'right') { - return 'end'; + return 'end' } if (attachment === 'left') { - return 'start'; + return 'start' } - return attachment; + return attachment } // Private - - _initializeOnDelegatedTarget(event, context) { - return context || this.constructor.getOrCreateInstance(event.delegateTarget, this._getDelegateConfig()); + _initializeOnDelegatedTarget (event, context) { + return context || this.constructor.getOrCreateInstance(event.delegateTarget, this._getDelegateConfig()) } - _getOffset() { + _getOffset () { const { offset - } = this._config; + } = this._config if (typeof offset === 'string') { - return offset.split(',').map(val => Number.parseInt(val, 10)); + return offset.split(',').map(val => Number.parseInt(val, 10)) } if (typeof offset === 'function') { - return popperData => offset(popperData, this._element); + return popperData => offset(popperData, this._element) } - return offset; + return offset } - _resolvePossibleFunction(content) { - return typeof content === 'function' ? content.call(this._element) : content; + _resolvePossibleFunction (content) { + return typeof content === 'function' ? content.call(this._element) : content } - _getPopperConfig(attachment) { + _getPopperConfig (attachment) { const defaultBsPopperConfig = { placement: attachment, modifiers: [{ @@ -4001,240 +3944,240 @@ fn: data => this._handlePopperPlacementChange(data) }], onFirstUpdate: data => { - if (data.options.placement !== data.placement) { - this._handlePopperPlacementChange(data); + if (data.options.placement !=== data.placement) { + this._handlePopperPlacementChange(data) } } - }; - return { ...defaultBsPopperConfig, + } + return { + ...defaultBsPopperConfig, ...(typeof this._config.popperConfig === 'function' ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig) - }; + } } - _addAttachmentClass(attachment) { - this.getTipElement().classList.add(`${this._getBasicClassPrefix()}-${this.updateAttachment(attachment)}`); + _addAttachmentClass (attachment) { + this.getTipElement().classList.add(`${this._getBasicClassPrefix()}-${this.updateAttachment(attachment)}`) } - _getAttachment(placement) { - return AttachmentMap[placement.toUpperCase()]; + _getAttachment (placement) { + return AttachmentMap[placement.toUpperCase()] } - _setListeners() { - const triggers = this._config.trigger.split(' '); + _setListeners () { + const triggers = this._config.trigger.split(' ') triggers.forEach(trigger => { if (trigger === 'click') { - EventHandler.on(this._element, this.constructor.Event.CLICK, this._config.selector, event => this.toggle(event)); - } else if (trigger !== TRIGGER_MANUAL) { - const eventIn = trigger === TRIGGER_HOVER ? this.constructor.Event.MOUSEENTER : this.constructor.Event.FOCUSIN; - const eventOut = trigger === TRIGGER_HOVER ? this.constructor.Event.MOUSELEAVE : this.constructor.Event.FOCUSOUT; - EventHandler.on(this._element, eventIn, this._config.selector, event => this._enter(event)); - EventHandler.on(this._element, eventOut, this._config.selector, event => this._leave(event)); + EventHandler.on(this._element, this.constructor.Event.CLICK, this._config.selector, event => this.toggle(event)) + } else if (trigger !=== TRIGGER_MANUAL) { + const eventIn = trigger === TRIGGER_HOVER ? this.constructor.Event.MOUSEENTER : this.constructor.Event.FOCUSIN + const eventOut = trigger === TRIGGER_HOVER ? this.constructor.Event.MOUSELEAVE : this.constructor.Event.FOCUSOUT + EventHandler.on(this._element, eventIn, this._config.selector, event => this._enter(event)) + EventHandler.on(this._element, eventOut, this._config.selector, event => this._leave(event)) } - }); + }) this._hideModalHandler = () => { if (this._element) { - this.hide(); + this.hide() } - }; + } - EventHandler.on(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler); + EventHandler.on(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler) if (this._config.selector) { - this._config = { ...this._config, + this._config = { + ...this._config, trigger: 'manual', selector: '' - }; + } } else { - this._fixTitle(); + this._fixTitle() } } - _fixTitle() { - const title = this._element.getAttribute('title'); + _fixTitle () { + const title = this._element.getAttribute('title') - const originalTitleType = typeof this._element.getAttribute('data-bs-original-title'); + const originalTitleType = typeof this._element.getAttribute('data-bs-original-title') - if (title || originalTitleType !== 'string') { - this._element.setAttribute('data-bs-original-title', title || ''); + if (title || originalTitleType !=== 'string') { + this._element.setAttribute('data-bs-original-title', title || '') if (title && !this._element.getAttribute('aria-label') && !this._element.textContent) { - this._element.setAttribute('aria-label', title); + this._element.setAttribute('aria-label', title) } - this._element.setAttribute('title', ''); + this._element.setAttribute('title', '') } } - _enter(event, context) { - context = this._initializeOnDelegatedTarget(event, context); + _enter (event, context) { + context = this._initializeOnDelegatedTarget(event, context) if (event) { - context._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true; + context._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true } if (context.getTipElement().classList.contains(CLASS_NAME_SHOW$2) || context._hoverState === HOVER_STATE_SHOW) { - context._hoverState = HOVER_STATE_SHOW; - return; + context._hoverState = HOVER_STATE_SHOW + return } - clearTimeout(context._timeout); - context._hoverState = HOVER_STATE_SHOW; + clearTimeout(context._timeout) + context._hoverState = HOVER_STATE_SHOW if (!context._config.delay || !context._config.delay.show) { - context.show(); - return; + context.show() + return } context._timeout = setTimeout(() => { if (context._hoverState === HOVER_STATE_SHOW) { - context.show(); + context.show() } - }, context._config.delay.show); + }, context._config.delay.show) } - _leave(event, context) { - context = this._initializeOnDelegatedTarget(event, context); + _leave (event, context) { + context = this._initializeOnDelegatedTarget(event, context) if (event) { - context._activeTrigger[event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER] = context._element.contains(event.relatedTarget); + context._activeTrigger[event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER] = context._element.contains(event.relatedTarget) } if (context._isWithActiveTrigger()) { - return; + return } - clearTimeout(context._timeout); - context._hoverState = HOVER_STATE_OUT; + clearTimeout(context._timeout) + context._hoverState = HOVER_STATE_OUT if (!context._config.delay || !context._config.delay.hide) { - context.hide(); - return; + context.hide() + return } context._timeout = setTimeout(() => { if (context._hoverState === HOVER_STATE_OUT) { - context.hide(); + context.hide() } - }, context._config.delay.hide); + }, context._config.delay.hide) } - _isWithActiveTrigger() { + _isWithActiveTrigger () { for (const trigger in this._activeTrigger) { if (this._activeTrigger[trigger]) { - return true; + return true } } - return false; + return false } - _getConfig(config) { - const dataAttributes = Manipulator.getDataAttributes(this._element); + _getConfig (config) { + const dataAttributes = Manipulator.getDataAttributes(this._element) Object.keys(dataAttributes).forEach(dataAttr => { if (DISALLOWED_ATTRIBUTES.has(dataAttr)) { - delete dataAttributes[dataAttr]; + delete dataAttributes[dataAttr] } - }); - config = { ...this.constructor.Default, + }) + config = { + ...this.constructor.Default, ...dataAttributes, ...(typeof config === 'object' && config ? config : {}) - }; - config.container = config.container === false ? document.body : getElement(config.container); + } + config.container = config.container === false ? document.body : getElement(config.container) if (typeof config.delay === 'number') { config.delay = { show: config.delay, hide: config.delay - }; + } } if (typeof config.title === 'number') { - config.title = config.title.toString(); + config.title = config.title.toString() } if (typeof config.content === 'number') { - config.content = config.content.toString(); + config.content = config.content.toString() } - typeCheckConfig(NAME$4, config, this.constructor.DefaultType); + typeCheckConfig(NAME$4, config, this.constructor.DefaultType) if (config.sanitize) { - config.template = sanitizeHtml(config.template, config.allowList, config.sanitizeFn); + config.template = sanitizeHtml(config.template, config.allowList, config.sanitizeFn) } - return config; + return config } - _getDelegateConfig() { - const config = {}; + _getDelegateConfig () { + const config = {} for (const key in this._config) { - if (this.constructor.Default[key] !== this._config[key]) { - config[key] = this._config[key]; + if (this.constructor.Default[key] !=== this._config[key]) { + config[key] = this._config[key] } } // In the future can be replaced with: - // const keysWithDifferentValues = Object.entries(this._config).filter(entry => this.constructor.Default[entry[0]] !== this._config[entry[0]]) + // const keysWithDifferentValues = Object.entries(this._config).filter(entry => this.constructor.Default[entry[0]] !=== this._config[entry[0]]) // `Object.fromEntries(keysWithDifferentValues)` - - return config; + return config } - _cleanTipClass() { - const tip = this.getTipElement(); - const basicClassPrefixRegex = new RegExp(`(^|\\s)${this._getBasicClassPrefix()}\\S+`, 'g'); - const tabClass = tip.getAttribute('class').match(basicClassPrefixRegex); + _cleanTipClass () { + const tip = this.getTipElement() + const basicClassPrefixRegex = new RegExp(`(^|\\s)${this._getBasicClassPrefix()}\\S+`, 'g') + const tabClass = tip.getAttribute('class').match(basicClassPrefixRegex) - if (tabClass !== null && tabClass.length > 0) { - tabClass.map(token => token.trim()).forEach(tClass => tip.classList.remove(tClass)); + if (tabClass !=== null && tabClass.length > 0) { + tabClass.map(token => token.trim()).forEach(tClass => tip.classList.remove(tClass)) } } - _getBasicClassPrefix() { - return CLASS_PREFIX$1; + _getBasicClassPrefix () { + return CLASS_PREFIX$1 } - _handlePopperPlacementChange(popperData) { + _handlePopperPlacementChange (popperData) { const { state - } = popperData; + } = popperData if (!state) { - return; + return } - this.tip = state.elements.popper; + this.tip = state.elements.popper - this._cleanTipClass(); + this._cleanTipClass() - this._addAttachmentClass(this._getAttachment(state.placement)); + this._addAttachmentClass(this._getAttachment(state.placement)) } - _disposePopper() { + _disposePopper () { if (this._popper) { - this._popper.destroy(); + this._popper.destroy() - this._popper = null; + this._popper = null } } // Static - - static jQueryInterface(config) { + static jQueryInterface (config) { return this.each(function () { - const data = Tooltip.getOrCreateInstance(this, config); + const data = Tooltip.getOrCreateInstance(this, config) if (typeof config === 'string') { if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); + throw new TypeError(`No method named "${config}"`) } - data[config](); + data[config]() } - }); + }) } - } /** * ------------------------------------------------------------------------ @@ -4243,8 +4186,7 @@ * add .Tooltip to jQuery only if jQuery is present */ - - defineJQueryPlugin(Tooltip); + defineJQueryPlugin(Tooltip) /** * -------------------------------------------------------------------------- @@ -4258,20 +4200,22 @@ * ------------------------------------------------------------------------ */ - const NAME$3 = 'popover'; - const DATA_KEY$3 = 'bs.popover'; - const EVENT_KEY$3 = `.${DATA_KEY$3}`; - const CLASS_PREFIX = 'bs-popover'; - const Default$2 = { ...Tooltip.Default, + const NAME$3 = 'popover' + const DATA_KEY$3 = 'bs.popover' + const EVENT_KEY$3 = `.${DATA_KEY$3}` + const CLASS_PREFIX = 'bs-popover' + const Default$2 = { + ...Tooltip.Default, placement: 'right', offset: [0, 8], trigger: 'click', content: '', template: '' - }; - const DefaultType$2 = { ...Tooltip.DefaultType, + } + const DefaultType$2 = { + ...Tooltip.DefaultType, content: '(string|element|function)' - }; + } const Event$1 = { HIDE: `hide${EVENT_KEY$3}`, HIDDEN: `hidden${EVENT_KEY$3}`, @@ -4283,9 +4227,9 @@ FOCUSOUT: `focusout${EVENT_KEY$3}`, MOUSEENTER: `mouseenter${EVENT_KEY$3}`, MOUSELEAVE: `mouseleave${EVENT_KEY$3}` - }; - const SELECTOR_TITLE = '.popover-header'; - const SELECTOR_CONTENT = '.popover-body'; + } + const SELECTOR_TITLE = '.popover-header' + const SELECTOR_CONTENT = '.popover-body' /** * ------------------------------------------------------------------------ * Class Definition @@ -4294,57 +4238,53 @@ class Popover extends Tooltip { // Getters - static get Default() { - return Default$2; + static get Default () { + return Default$2 } - static get NAME() { - return NAME$3; + static get NAME () { + return NAME$3 } - static get Event() { - return Event$1; + static get Event () { + return Event$1 } - static get DefaultType() { - return DefaultType$2; + static get DefaultType () { + return DefaultType$2 } // Overrides - - isWithContent() { - return this.getTitle() || this._getContent(); + isWithContent () { + return this.getTitle() || this._getContent() } - setContent(tip) { - this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TITLE); + setContent (tip) { + this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TITLE) - this._sanitizeAndSetContent(tip, this._getContent(), SELECTOR_CONTENT); + this._sanitizeAndSetContent(tip, this._getContent(), SELECTOR_CONTENT) } // Private - - _getContent() { - return this._resolvePossibleFunction(this._config.content); + _getContent () { + return this._resolvePossibleFunction(this._config.content) } - _getBasicClassPrefix() { - return CLASS_PREFIX; + _getBasicClassPrefix () { + return CLASS_PREFIX } // Static - - static jQueryInterface(config) { + static jQueryInterface (config) { return this.each(function () { - const data = Popover.getOrCreateInstance(this, config); + const data = Popover.getOrCreateInstance(this, config) if (typeof config === 'string') { if (typeof data[config] === 'undefined') { - throw new TypeError(`No method named "${config}"`); + throw new TypeError(`No method named "${config}"`) } - data[config](); + data[config]() } - }); + }) } - } /** * ------------------------------------------------------------------------ @@ -4353,8 +4293,7 @@ * add .Popover to jQuery only if jQuery is present */ - - defineJQueryPlugin(Popover); + defineJQueryPlugin(Popover) /** * -------------------------------------------------------------------------- @@ -4368,35 +4307,35 @@ * ------------------------------------------------------------------------ */ - const NAME$2 = 'scrollspy'; - const DATA_KEY$2 = 'bs.scrollspy'; - const EVENT_KEY$2 = `.${DATA_KEY$2}`; - const DATA_API_KEY$1 = '.data-api'; + const NAME$2 = 'scrollspy' + const DATA_KEY$2 = 'bs.scrollspy' + const EVENT_KEY$2 = `.${DATA_KEY$2}` + const DATA_API_KEY$1 = '.data-api' const Default$1 = { offset: 10, method: 'auto', target: '' - }; + } const DefaultType$1 = { offset: 'number', method: 'string', target: '(string|element)' - }; - const EVENT_ACTIVATE = `activate${EVENT_KEY$2}`; - const EVENT_SCROLL = `scroll${EVENT_KEY$2}`; - const EVENT_LOAD_DATA_API = `load${EVENT_KEY$2}${DATA_API_KEY$1}`; - const CLASS_NAME_DROPDOWN_ITEM = 'dropdown-item'; - const CLASS_NAME_ACTIVE$1 = 'active'; - const SELECTOR_DATA_SPY = '[data-bs-spy="scroll"]'; - const SELECTOR_NAV_LIST_GROUP$1 = '.nav, .list-group'; - const SELECTOR_NAV_LINKS = '.nav-link'; - const SELECTOR_NAV_ITEMS = '.nav-item'; - const SELECTOR_LIST_ITEMS = '.list-group-item'; - const SELECTOR_LINK_ITEMS = `${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}, .${CLASS_NAME_DROPDOWN_ITEM}`; - const SELECTOR_DROPDOWN$1 = '.dropdown'; - const SELECTOR_DROPDOWN_TOGGLE$1 = '.dropdown-toggle'; - const METHOD_OFFSET = 'offset'; - const METHOD_POSITION = 'position'; + } + const EVENT_ACTIVATE = `activate${EVENT_KEY$2}` + const EVENT_SCROLL = `scroll${EVENT_KEY$2}` + const EVENT_LOAD_DATA_API = `load${EVENT_KEY$2}${DATA_API_KEY$1}` + const CLASS_NAME_DROPDOWN_ITEM = 'dropdown-item' + const CLASS_NAME_ACTIVE$1 = 'active' + const SELECTOR_DATA_SPY = '[data-bs-spy="scroll"]' + const SELECTOR_NAV_LIST_GROUP$1 = '.nav, .list-group' + const SELECTOR_NAV_LINKS = '.nav-link' + const SELECTOR_NAV_ITEMS = '.nav-item' + const SELECTOR_LIST_ITEMS = '.list-group-item' + const SELECTOR_LINK_ITEMS = `${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}, .${CLASS_NAME_DROPDOWN_ITEM}` + const SELECTOR_DROPDOWN$1 = '.dropdown' + const SELECTOR_DROPDOWN_TOGGLE$1 = '.dropdown-toggle' + const METHOD_OFFSET = 'offset' + const METHOD_POSITION = 'position' /** * ------------------------------------------------------------------------ * Class Definition @@ -4404,173 +4343,169 @@ */ class ScrollSpy extends BaseComponent { - constructor(element, config) { - super(element); - this._scrollElement = this._element.tagName === 'BODY' ? window : this._element; - this._config = this._getConfig(config); - this._offsets = []; - this._targets = []; - this._activeTarget = null; - this._scrollHeight = 0; - EventHandler.on(this._scrollElement, EVENT_SCROLL, () => this._process()); - this.refresh(); + constructor (element, config) { + super(element) + this._scrollElement = this._element.tagName === 'BODY' ? window : this._element + this._config = this._getConfig(config) + this._offsets = [] + this._targets = [] + this._activeTarget = null + this._scrollHeight = 0 + EventHandler.on(this._scrollElement, EVENT_SCROLL, () => this._process()) + this.refresh() - this._process(); + this._process() } // Getters - - static get Default() { - return Default$1; + static get Default () { + return Default$1 } - static get NAME() { - return NAME$2; + static get NAME () { + return NAME$2 } // Public - - refresh() { - const autoMethod = this._scrollElement === this._scrollElement.window ? METHOD_OFFSET : METHOD_POSITION; - const offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method; - const offsetBase = offsetMethod === METHOD_POSITION ? this._getScrollTop() : 0; - this._offsets = []; - this._targets = []; - this._scrollHeight = this._getScrollHeight(); - const targets = SelectorEngine.find(SELECTOR_LINK_ITEMS, this._config.target); + refresh () { + const autoMethod = this._scrollElement === this._scrollElement.window ? METHOD_OFFSET : METHOD_POSITION + const offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method + const offsetBase = offsetMethod === METHOD_POSITION ? this._getScrollTop() : 0 + this._offsets = [] + this._targets = [] + this._scrollHeight = this._getScrollHeight() + const targets = SelectorEngine.find(SELECTOR_LINK_ITEMS, this._config.target) targets.map(element => { - const targetSelector = getSelectorFromElement(element); - const target = targetSelector ? SelectorEngine.findOne(targetSelector) : null; + const targetSelector = getSelectorFromElement(element) + const target = targetSelector ? SelectorEngine.findOne(targetSelector) : null if (target) { - const targetBCR = target.getBoundingClientRect(); + const targetBCR = target.getBoundingClientRect() if (targetBCR.width || targetBCR.height) { - return [Manipulator[offsetMethod](target).top + offsetBase, targetSelector]; + return [Manipulator[offsetMethod](target).top + offsetBase, targetSelector] } } - return null; + return null }).filter(item => item).sort((a, b) => a[0] - b[0]).forEach(item => { - this._offsets.push(item[0]); + this._offsets.push(item[0]) - this._targets.push(item[1]); - }); + this._targets.push(item[1]) + }) } - dispose() { - EventHandler.off(this._scrollElement, EVENT_KEY$2); - super.dispose(); + dispose () { + EventHandler.off(this._scrollElement, EVENT_KEY$2) + super.dispose() } // Private - - _getConfig(config) { - config = { ...Default$1, + _getConfig (config) { + config = { + ...Default$1, ...Manipulator.getDataAttributes(this._element), ...(typeof config === 'object' && config ? config : {}) - }; - config.target = getElement(config.target) || document.documentElement; - typeCheckConfig(NAME$2, config, DefaultType$1); - return config; + } + config.target = getElement(config.target) || document.documentElement + typeCheckConfig(NAME$2, config, DefaultType$1) + return config } - _getScrollTop() { - return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop; + _getScrollTop () { + return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop } - _getScrollHeight() { - return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); + _getScrollHeight () { + return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight) } - _getOffsetHeight() { - return this._scrollElement === window ? window.innerHeight : this._scrollElement.getBoundingClientRect().height; + _getOffsetHeight () { + return this._scrollElement === window ? window.innerHeight : this._scrollElement.getBoundingClientRect().height } - _process() { - const scrollTop = this._getScrollTop() + this._config.offset; + _process () { + const scrollTop = this._getScrollTop() + this._config.offset - const scrollHeight = this._getScrollHeight(); + const scrollHeight = this._getScrollHeight() - const maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight(); + const maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight() - if (this._scrollHeight !== scrollHeight) { - this.refresh(); + if (this._scrollHeight !=== scrollHeight) { + this.refresh() } if (scrollTop >= maxScroll) { - const target = this._targets[this._targets.length - 1]; + const target = this._targets[this._targets.length - 1] - if (this._activeTarget !== target) { - this._activate(target); + if (this._activeTarget !=== target) { + this._activate(target) } - return; + return } if (this._activeTarget && scrollTop < this._offsets[0] && this._offsets[0] > 0) { - this._activeTarget = null; + this._activeTarget = null - this._clear(); + this._clear() - return; + return } for (let i = this._offsets.length; i--;) { - const isActiveTarget = this._activeTarget !== this._targets[i] && scrollTop >= this._offsets[i] && (typeof this._offsets[i + 1] === 'undefined' || scrollTop < this._offsets[i + 1]); + const isActiveTarget = this._activeTarget !=== this._targets[i] && scrollTop >= this._offsets[i] && (typeof this._offsets[i + 1] === 'undefined' || scrollTop < this._offsets[i + 1]) if (isActiveTarget) { - this._activate(this._targets[i]); + this._activate(this._targets[i]) } } } - _activate(target) { - this._activeTarget = target; + _activate (target) { + this._activeTarget = target - this._clear(); + this._clear() - const queries = SELECTOR_LINK_ITEMS.split(',').map(selector => `${selector}[data-bs-target="${target}"],${selector}[href="${target}"]`); - const link = SelectorEngine.findOne(queries.join(','), this._config.target); - link.classList.add(CLASS_NAME_ACTIVE$1); + const queries = SELECTOR_LINK_ITEMS.split(',').map(selector => `${selector}[data-bs-target="${target}"],${selector}[href="${target}"]`) + const link = SelectorEngine.findOne(queries.join(','), this._config.target) + link.classList.add(CLASS_NAME_ACTIVE$1) if (link.classList.contains(CLASS_NAME_DROPDOWN_ITEM)) { - SelectorEngine.findOne(SELECTOR_DROPDOWN_TOGGLE$1, link.closest(SELECTOR_DROPDOWN$1)).classList.add(CLASS_NAME_ACTIVE$1); + SelectorEngine.findOne(SELECTOR_DROPDOWN_TOGGLE$1, link.closest(SELECTOR_DROPDOWN$1)).classList.add(CLASS_NAME_ACTIVE$1) } else { SelectorEngine.parents(link, SELECTOR_NAV_LIST_GROUP$1).forEach(listGroup => { // Set triggered links parents as active // With both
    and